SQLite

Check-in [590d4ac1]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Fix documentation typos.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | shunning-error
Files: files | file ages | folders
SHA1: 590d4ac1ee0db824c00c1f6b0ec3cc9437cb1477
User & Date: drh 2009-11-04 18:51:17
Context
2009-11-04
21:49
Do not accept a codec no an in-memory database. (check-in: 6f3081a8 user: drh tags: shunning-error)
18:51
Fix documentation typos. (check-in: 590d4ac1 user: drh tags: shunning-error)
18:16 Edit [eb7a544fe49d1626|eb7a544f]: Change background color to "#ffc0d0". Edit check-in comment. Timestamp 2009-11-04 13:30:02. (artifact: f228c7ca user: drh)
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added Makefile.arm-wince-mingw32ce-gcc.





















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/make
#
# Makefile for SQLITE
#
# This is a template makefile for SQLite.  Most people prefer to
# use the autoconf generated "configure" script to generate the
# makefile automatically.  But that does not work for everybody
# and in every situation.  If you are having problems with the
# "configure" script, you might want to try this makefile as an
# alternative.  Create a copy of this file, edit the parameters
# below and type "make".
#

#### The directory where to find the mingw32ce tools
MINGW32CE = /opt/mingw32ce/bin

#### The target prefix of the mingw32ce tools
TARGET = arm-wince-mingw32ce

#### The toplevel directory of the source tree.  This is the directory
#    that contains this "Makefile.in" and the "configure.in" script.
#
TOP = ../sqlite

#### C Compiler and options for use in building executables that
#    will run on the platform that is doing the build.
#
BCC = gcc -g -O2
#BCC = /opt/ancic/bin/c89 -0

#### If the target operating system supports the "usleep()" system
#    call, then define the HAVE_USLEEP macro for all C modules.
#
USLEEP = 
#USLEEP = -DHAVE_USLEEP=1

#### If you want the SQLite library to be safe for use within a 
#    multi-threaded program, then define the following macro
#    appropriately:
#
THREADSAFE = -DTHREADSAFE=1
#THREADSAFE = -DTHREADSAFE=0

#### Specify any extra linker options needed to make the library
#    thread safe
#
#THREADLIB = -lpthread
THREADLIB = 

#### Specify any extra libraries needed to access required functions.
#
#TLIBS = -lrt    # fdatasync on Solaris 8
TLIBS = 

#### Leave SQLITE_DEBUG undefined for maximum speed.  Use SQLITE_DEBUG=1
#    to check for memory leaks.  Use SQLITE_DEBUG=2 to print a log of all
#    malloc()s and free()s in order to track down memory leaks.
#    
#    SQLite uses some expensive assert() statements in the inner loop.
#    You can make the library go almost twice as fast if you compile
#    with -DNDEBUG=1
#
#OPTS = -DSQLITE_DEBUG=2
#OPTS = -DSQLITE_DEBUG=1
#OPTS = 
OPTS = -DNDEBUG=1 -DSQLITE_OS_WIN=1 -D_WIN32_WCE=1
#OPTS += -DHAVE_FDATASYNC=1

#### The suffix to add to executable files.  ".exe" for windows.
#    Nothing for unix.
#
EXE = .exe
#EXE =

#### C Compile and options for use in building executables that 
#    will run on the target platform.  This is usually the same
#    as BCC, unless you are cross-compiling.
#
#TCC = gcc -O6
#TCC = gcc -g -O0 -Wall
#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage
#TCC = /opt/mingw/bin/i386-mingw32-gcc -O6
TCC = $(MINGW32CE)/$(TARGET)-gcc -O2
#TCC = /opt/ansic/bin/c89 -O +z -Wl,-a,archive

#### Tools used to build a static library.
#
#AR = ar cr
#AR = /opt/mingw/bin/i386-mingw32-ar cr
AR = $(MINGW32CE)/$(TARGET)-ar cr
#RANLIB = ranlib
#RANLIB = /opt/mingw/bin/i386-mingw32-ranlib
RANLIB = $(MINGW32CE)/$(TARGET)-ranlib

#MKSHLIB = gcc -shared
#SO = so
#SHPREFIX = lib
MKSHLIB = $(MINGW32CE)/$(TARGET)-gcc -shared
SO = dll
SHPREFIX =

#### Extra compiler options needed for programs that use the TCL library.
#
#TCL_FLAGS =
#TCL_FLAGS = -DSTATIC_BUILD=1
TCL_FLAGS = -I/home/drh/tcltk/8.4linux
#TCL_FLAGS = -I/home/drh/tcltk/8.4win -DSTATIC_BUILD=1
#TCL_FLAGS = -I/home/drh/tcltk/8.3hpux

#### Linker options needed to link against the TCL library.
#
#LIBTCL = -ltcl -lm -ldl
LIBTCL = /home/drh/tcltk/8.4linux/libtcl8.4g.a -lm -ldl
#LIBTCL = /home/drh/tcltk/8.4win/libtcl84s.a -lmsvcrt
#LIBTCL = /home/drh/tcltk/8.3hpux/libtcl8.3.a -ldld -lm -lc

#### Additional objects for SQLite library when TCL support is enabled.
TCLOBJ =
#TCLOBJ = tclsqlite.o

#### Compiler options needed for programs that use the readline() library.
#
READLINE_FLAGS =
#READLINE_FLAGS = -DHAVE_READLINE=1 -I/usr/include/readline

#### Linker options needed by programs using readline() must link against.
#
LIBREADLINE =
#LIBREADLINE = -static -lreadline -ltermcap

#### Which "awk" program provides nawk compatibilty
#
# NAWK = nawk
NAWK = awk

# You should not have to change anything below this line
###############################################################################
include $(TOP)/main.mk

Added Makefile.in.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
#!/usr/make
#
# Makefile for SQLITE
#
# This makefile is suppose to be configured automatically using the
# autoconf.  But if that does not work for you, you can configure
# the makefile manually.  Just set the parameters below to values that
# work well for your system.
#
# If the configure script does not work out-of-the-box, you might
# be able to get it to work by giving it some hints.  See the comment
# at the beginning of configure.in for additional information.
#

# The toplevel directory of the source tree.  This is the directory
# that contains this "Makefile.in" and the "configure.in" script.
#
TOP = @srcdir@

# C Compiler and options for use in building executables that
# will run on the platform that is doing the build.
#
BCC = @BUILD_CC@ @BUILD_CFLAGS@

# C Compile and options for use in building executables that 
# will run on the target platform.  (BCC and TCC are usually the
# same unless your are cross-compiling.)
#
TCC = @CC@ @CPPFLAGS@ @CFLAGS@ -I. -I${TOP}/src

# Define this for the autoconf-based build, so that the code knows it can
# include the generated config.h
# 
TCC += -D_HAVE_SQLITE_CONFIG_H

# Define -DNDEBUG to compile without debugging (i.e., for production usage)
# Omitting the define will cause extra debugging code to be inserted and
# includes extra comments when "EXPLAIN stmt" is used.
#
TCC += @TARGET_DEBUG@ @XTHREADCONNECT@

# Compiler options needed for programs that use the TCL library.
#
TCC += @TCL_INCLUDE_SPEC@

# The library that programs using TCL must link against.
#
LIBTCL = @TCL_LIB_SPEC@ @TCL_LIBS@

# Compiler options needed for programs that use the readline() library.
#
READLINE_FLAGS = -DHAVE_READLINE=@TARGET_HAVE_READLINE@ @TARGET_READLINE_INC@

# The library that programs using readline() must link against.
#
LIBREADLINE = @TARGET_READLINE_LIBS@

# Should the database engine be compiled threadsafe
#
TCC += -DSQLITE_THREADSAFE=@SQLITE_THREADSAFE@

# Do threads override each others locks by default (1), or do we test (-1)
#
TCC += -DSQLITE_THREAD_OVERRIDE_LOCK=@THREADSOVERRIDELOCKS@

# Any target libraries which libsqlite must be linked against
# 
TLIBS = @LIBS@

# Flags controlling use of the in memory btree implementation
#
# SQLITE_TEMP_STORE is 0 to force temporary tables to be in a file, 1 to
# default to file, 2 to default to memory, and 3 to force temporary
# tables to always be in memory.
#
TEMP_STORE = -DSQLITE_TEMP_STORE=@TEMP_STORE@

# Enable/disable loadable extensions, and other optional features
# based on configuration. (-DSQLITE_OMIT*, -DSQLITE_ENABLE*).  
# The same set of OMIT and ENABLE flags should be passed to the 
# LEMON parser generator and the mkkeywordhash tool as well.
OPT_FEATURE_FLAGS = @OPT_FEATURE_FLAGS@

TCC += $(OPT_FEATURE_FLAGS)

# Add in any optional parameters specified on the make commane line
# ie.  make "OPTS=-DSQLITE_ENABLE_FOO=1 -DSQLITE_OMIT_FOO=1".
TCC += $(OPTS)

# Version numbers and release number for the SQLite being compiled.
#
VERSION = @VERSION@
VERSION_NUMBER = @VERSION_NUMBER@
RELEASE = @RELEASE@

# Filename extensions
#
BEXE = @BUILD_EXEEXT@
TEXE = @TARGET_EXEEXT@

# The following variable is "1" if the configure script was able to locate
# the tclConfig.sh file.  It is an empty string otherwise.  When this
# variable is "1", the TCL extension library (libtclsqlite3.so) is built
# and installed.
#
HAVE_TCL = @HAVE_TCL@

# This is the command to use for tclsh - normally just "tclsh", but we may
# know the specific version we want to use
#
TCLSH_CMD = @TCLSH_CMD@

# Where do we want to install the tcl plugin
#
TCLLIBDIR = @TCLLIBDIR@

# The suffix used on shared libraries.  Ex:  ".dll", ".so", ".dylib"
#
SHLIB_SUFFIX = @TCL_SHLIB_SUFFIX@

# If gcov support was enabled by the configure script, add the appropriate
# flags here.  It's not always as easy as just having the user add the right
# CFLAGS / LDFLAGS, because libtool wants to use CFLAGS when linking, which
# causes build errors with -fprofile-arcs -ftest-coverage with some GCCs.  
# Supposedly GCC does the right thing if you use --coverage, but in 
# practice it still fails.  See:
#
# http://www.mail-archive.com/debian-gcc@lists.debian.org/msg26197.html
#
# for more info.
#
GCOV_CFLAGS1 = -DSQLITE_COVERAGE_TEST=1 -fprofile-arcs -ftest-coverage
GCOV_LDFLAGS1 = -lgcov
USE_GCOV = @USE_GCOV@
LTCOMPILE_EXTRAS += $(GCOV_CFLAGS$(USE_GCOV))
LTLINK_EXTRAS += $(GCOV_LDFLAGS$(USE_GCOV))


# The directory into which to store package information for

# Some standard variables and programs
#
prefix = @prefix@
exec_prefix = @exec_prefix@
libdir = @libdir@
pkgconfigdir = $(libdir)/pkgconfig
bindir = @bindir@
includedir = @includedir@
INSTALL = @INSTALL@
LIBTOOL = ./libtool
ALLOWRELEASE = @ALLOWRELEASE@

# libtool compile/link/install
LTCOMPILE = $(LIBTOOL) --mode=compile --tag=CC $(TCC) $(LTCOMPILE_EXTRAS)
LTLINK = $(LIBTOOL) --mode=link $(TCC) $(LTCOMPILE_EXTRAS) @LDFLAGS@ $(LTLINK_EXTRAS)
LTINSTALL = $(LIBTOOL) --mode=install $(INSTALL)

# nawk compatible awk.
NAWK = @AWK@

# You should not have to change anything below this line
###############################################################################

# Object files for the SQLite library (non-amalgamation).
#
OBJS0 = alter.lo analyze.lo attach.lo auth.lo backup.lo bitvec.lo btmutex.lo \
        btree.lo build.lo callback.lo complete.lo date.lo \
        delete.lo expr.lo fault.lo fkey.lo func.lo global.lo \
        hash.lo journal.lo insert.lo legacy.lo loadext.lo \
        main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \
        memjournal.lo \
        mutex.lo mutex_noop.lo mutex_os2.lo mutex_unix.lo mutex_w32.lo \
        notify.lo opcodes.lo os.lo os_unix.lo os_win.lo os_os2.lo \
        pager.lo parse.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \
        random.lo resolve.lo rowset.lo select.lo status.lo \
        table.lo tokenize.lo trigger.lo update.lo \
        util.lo vacuum.lo \
        vdbe.lo vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo \
        walker.lo where.lo utf.lo vtab.lo

# Object files for the amalgamation.
#
OBJS1 = sqlite3.lo

# Determine the real value of LIBOBJ based on the 'configure' script
#
USE_AMALGAMATION = @USE_AMALGAMATION@
LIBOBJ = $(OBJS$(USE_AMALGAMATION))


# All of the source code files.
#
SRC = \
  $(TOP)/src/alter.c \
  $(TOP)/src/analyze.c \
  $(TOP)/src/attach.c \
  $(TOP)/src/auth.c \
  $(TOP)/src/backup.c \
  $(TOP)/src/bitvec.c \
  $(TOP)/src/btmutex.c \
  $(TOP)/src/btree.c \
  $(TOP)/src/btree.h \
  $(TOP)/src/btreeInt.h \
  $(TOP)/src/build.c \
  $(TOP)/src/callback.c \
  $(TOP)/src/complete.c \
  $(TOP)/src/date.c \
  $(TOP)/src/delete.c \
  $(TOP)/src/expr.c \
  $(TOP)/src/fault.c \
  $(TOP)/src/fkey.c \
  $(TOP)/src/func.c \
  $(TOP)/src/global.c \
  $(TOP)/src/hash.c \
  $(TOP)/src/hash.h \
  $(TOP)/src/hwtime.h \
  $(TOP)/src/insert.c \
  $(TOP)/src/journal.c \
  $(TOP)/src/legacy.c \
  $(TOP)/src/loadext.c \
  $(TOP)/src/main.c \
  $(TOP)/src/malloc.c \
  $(TOP)/src/mem0.c \
  $(TOP)/src/mem1.c \
  $(TOP)/src/mem2.c \
  $(TOP)/src/mem3.c \
  $(TOP)/src/mem5.c \
  $(TOP)/src/memjournal.c \
  $(TOP)/src/mutex.c \
  $(TOP)/src/mutex.h \
  $(TOP)/src/mutex_noop.c \
  $(TOP)/src/mutex_os2.c \
  $(TOP)/src/mutex_unix.c \
  $(TOP)/src/mutex_w32.c \
  $(TOP)/src/notify.c \
  $(TOP)/src/os.c \
  $(TOP)/src/os.h \
  $(TOP)/src/os_common.h \
  $(TOP)/src/os_os2.c \
  $(TOP)/src/os_unix.c \
  $(TOP)/src/os_win.c \
  $(TOP)/src/pager.c \
  $(TOP)/src/pager.h \
  $(TOP)/src/parse.y \
  $(TOP)/src/pcache.c \
  $(TOP)/src/pcache.h \
  $(TOP)/src/pcache1.c \
  $(TOP)/src/pragma.c \
  $(TOP)/src/prepare.c \
  $(TOP)/src/printf.c \
  $(TOP)/src/random.c \
  $(TOP)/src/resolve.c \
  $(TOP)/src/rowset.c \
  $(TOP)/src/select.c \
  $(TOP)/src/status.c \
  $(TOP)/src/shell.c \
  $(TOP)/src/sqlite.h.in \
  $(TOP)/src/sqlite3ext.h \
  $(TOP)/src/sqliteInt.h \
  $(TOP)/src/sqliteLimit.h \
  $(TOP)/src/table.c \
  $(TOP)/src/tclsqlite.c \
  $(TOP)/src/tokenize.c \
  $(TOP)/src/trigger.c \
  $(TOP)/src/utf.c \
  $(TOP)/src/update.c \
  $(TOP)/src/util.c \
  $(TOP)/src/vacuum.c \
  $(TOP)/src/vdbe.c \
  $(TOP)/src/vdbe.h \
  $(TOP)/src/vdbeapi.c \
  $(TOP)/src/vdbeaux.c \
  $(TOP)/src/vdbeblob.c \
  $(TOP)/src/vdbemem.c \
  $(TOP)/src/vdbeInt.h \
  $(TOP)/src/vtab.c \
  $(TOP)/src/walker.c \
  $(TOP)/src/where.c

# Generated source code files
#
SRC += \
  keywordhash.h \
  opcodes.c \
  opcodes.h \
  parse.c \
  parse.h \
  config.h \
  sqlite3.h

# Source code for extensions
#
SRC += \
  $(TOP)/ext/fts1/fts1.c \
  $(TOP)/ext/fts1/fts1.h \
  $(TOP)/ext/fts1/fts1_hash.c \
  $(TOP)/ext/fts1/fts1_hash.h \
  $(TOP)/ext/fts1/fts1_porter.c \
  $(TOP)/ext/fts1/fts1_tokenizer.h \
  $(TOP)/ext/fts1/fts1_tokenizer1.c
SRC += \
  $(TOP)/ext/fts2/fts2.c \
  $(TOP)/ext/fts2/fts2.h \
  $(TOP)/ext/fts2/fts2_hash.c \
  $(TOP)/ext/fts2/fts2_hash.h \
  $(TOP)/ext/fts2/fts2_icu.c \
  $(TOP)/ext/fts2/fts2_porter.c \
  $(TOP)/ext/fts2/fts2_tokenizer.h \
  $(TOP)/ext/fts2/fts2_tokenizer.c \
  $(TOP)/ext/fts2/fts2_tokenizer1.c
SRC += \
  $(TOP)/ext/fts3/fts3.c \
  $(TOP)/ext/fts3/fts3.h \
  $(TOP)/ext/fts3/fts3_expr.c \
  $(TOP)/ext/fts3/fts3_expr.h \
  $(TOP)/ext/fts3/fts3_hash.c \
  $(TOP)/ext/fts3/fts3_hash.h \
  $(TOP)/ext/fts3/fts3_icu.c \
  $(TOP)/ext/fts3/fts3_porter.c \
  $(TOP)/ext/fts3/fts3_tokenizer.h \
  $(TOP)/ext/fts3/fts3_tokenizer.c \
  $(TOP)/ext/fts3/fts3_tokenizer1.c
SRC += \
  $(TOP)/ext/icu/sqliteicu.h \
  $(TOP)/ext/icu/icu.c
SRC += \
  $(TOP)/ext/rtree/rtree.h \
  $(TOP)/ext/rtree/rtree.c

# Source code to the library files needed by the test fixture
#
TESTSRC2 = \
  $(TOP)/src/attach.c \
  $(TOP)/src/backup.c \
  $(TOP)/src/bitvec.c \
  $(TOP)/src/btree.c \
  $(TOP)/src/build.c \
  $(TOP)/src/date.c \
  $(TOP)/src/expr.c \
  $(TOP)/src/func.c \
  $(TOP)/src/insert.c \
  $(TOP)/src/mem5.c \
  $(TOP)/src/os.c \
  $(TOP)/src/os_os2.c \
  $(TOP)/src/os_unix.c \
  $(TOP)/src/os_win.c \
  $(TOP)/src/pager.c \
  $(TOP)/src/pcache.c \
  $(TOP)/src/pcache1.c \
  $(TOP)/src/pragma.c \
  $(TOP)/src/prepare.c \
  $(TOP)/src/printf.c \
  $(TOP)/src/random.c \
  $(TOP)/src/select.c \
  $(TOP)/src/tokenize.c \
  $(TOP)/src/utf.c \
  $(TOP)/src/util.c \
  $(TOP)/src/vdbe.c \
  $(TOP)/src/vdbeapi.c \
  $(TOP)/src/vdbeaux.c \
  $(TOP)/src/vdbemem.c \
  $(TOP)/src/where.c \
  parse.c

# Source code to the actual test files.
#
TESTSRC = \
  $(TOP)/src/test1.c \
  $(TOP)/src/test2.c \
  $(TOP)/src/test3.c \
  $(TOP)/src/test4.c \
  $(TOP)/src/test5.c \
  $(TOP)/src/test6.c \
  $(TOP)/src/test7.c \
  $(TOP)/src/test8.c \
  $(TOP)/src/test9.c \
  $(TOP)/src/test_autoext.c \
  $(TOP)/src/test_async.c \
  $(TOP)/src/test_backup.c \
  $(TOP)/src/test_btree.c \
  $(TOP)/src/test_config.c \
  $(TOP)/src/test_devsym.c \
  $(TOP)/src/test_func.c \
  $(TOP)/src/test_hexio.c \
  $(TOP)/src/test_init.c \
  $(TOP)/src/test_journal.c \
  $(TOP)/src/test_malloc.c \
  $(TOP)/src/test_mutex.c \
  $(TOP)/src/test_onefile.c \
  $(TOP)/src/test_osinst.c \
  $(TOP)/src/test_pcache.c \
  $(TOP)/src/test_schema.c \
  $(TOP)/src/test_server.c \
  $(TOP)/src/test_tclvar.c \
  $(TOP)/src/test_thread.c \
  $(TOP)/src/test_wsd.c

# Header files used by all library source files.
#
HDR = \
   sqlite3.h  \
   $(TOP)/src/btree.h \
   $(TOP)/src/btreeInt.h \
   $(TOP)/src/hash.h \
   $(TOP)/src/hwtime.h \
   $(TOP)/src/sqliteLimit.h \
   $(TOP)/src/mutex.h \
   opcodes.h \
   $(TOP)/src/os.h \
   $(TOP)/src/os_common.h \
   $(TOP)/src/sqlite3ext.h \
   $(TOP)/src/sqliteInt.h  \
   $(TOP)/src/vdbe.h \
   $(TOP)/src/vdbeInt.h \
   parse.h \
   config.h

# Header files used by extensions
#
HDR += \
  $(TOP)/ext/fts1/fts1.h \
  $(TOP)/ext/fts1/fts1_hash.h \
  $(TOP)/ext/fts1/fts1_tokenizer.h
HDR += \
  $(TOP)/ext/fts2/fts2.h \
  $(TOP)/ext/fts2/fts2_hash.h \
  $(TOP)/ext/fts2/fts2_tokenizer.h
HDR += \
  $(TOP)/ext/fts3/fts3.h \
  $(TOP)/ext/fts3/fts3_expr.h \
  $(TOP)/ext/fts3/fts3_hash.h \
  $(TOP)/ext/fts3/fts3_tokenizer.h
HDR += \
  $(TOP)/ext/rtree/rtree.h
HDR += \
  $(TOP)/ext/icu/sqliteicu.h

# If using the amalgamation, use sqlite3.c directly to build the test
# fixture.  Otherwise link against libsqlite3.la.  (This distinction is
# necessary because the test fixture requires non-API symbols which are
# hidden when the library is built via the amalgamation).
#
TESTFIXTURE_SRC0 = $(TESTSRC2) libsqlite3.la
TESTFIXTURE_SRC1 = sqlite3.c
TESTFIXTURE_SRC = $(TESTSRC) $(TOP)/src/tclsqlite.c $(TESTFIXTURE_SRC$(USE_AMALGAMATION))


# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.la sqlite3$(TEXE) $(HAVE_TCL:1=libtclsqlite3.la)

Makefile: $(TOP)/Makefile.in
	./config.status

sqlite3.pc: $(TOP)/sqlite3.pc.in
	./config.status

# Generate the file "last_change" which contains the date of change
# of the most recently modified source code file
#
last_change:	$(SRC)
	cat $(SRC) | grep '$$Id: ' | sort -k 5 | tail -1 \
          | $(NAWK) '{print $$5,$$6}' >last_change

libsqlite3.la:	$(LIBOBJ)
	$(LTLINK) -o $@ $(LIBOBJ) $(TLIBS) \
		${ALLOWRELEASE} -rpath "$(libdir)" -version-info "8:6:8"

libtclsqlite3.la:	tclsqlite.lo libsqlite3.la
	$(LTLINK) -o $@ tclsqlite.lo \
		libsqlite3.la @TCL_STUB_LIB_SPEC@ $(TLIBS) \
		-rpath "$(TCLLIBDIR)" \
		-version-info "8:6:8" \
		-avoid-version

sqlite3$(TEXE):	$(TOP)/src/shell.c libsqlite3.la sqlite3.h
	$(LTLINK) $(READLINE_FLAGS) \
		-o $@ $(TOP)/src/shell.c libsqlite3.la \
		$(LIBREADLINE) $(TLIBS) -rpath "$(libdir)"

# This target creates a directory named "tsrc" and fills it with
# copies of all of the C source code and header files needed to
# build on the target system.  Some of the C source code and header
# files are automatically generated.  This target takes care of
# all that automatic generation.
#
.target_source:	$(SRC)
	rm -rf tsrc
	mkdir -p tsrc
	cp $(SRC) tsrc
	rm tsrc/sqlite.h.in tsrc/parse.y
	$(TCLSH_CMD) $(TOP)/tool/vdbe-compress.tcl <tsrc/vdbe.c >vdbe.new
	mv vdbe.new tsrc/vdbe.c
	touch .target_source

sqlite3.c:	.target_source $(TOP)/tool/mksqlite3c.tcl
	$(TCLSH_CMD) $(TOP)/tool/mksqlite3c.tcl

# Rules to build the LEMON compiler generator
#
lemon$(BEXE):	$(TOP)/tool/lemon.c $(TOP)/src/lempar.c
	$(BCC) -o $@ $(TOP)/tool/lemon.c
	cp $(TOP)/src/lempar.c .


# Rule to build the amalgamation
#
sqlite3.lo:	sqlite3.c
	$(LTCOMPILE) $(TEMP_STORE) -c sqlite3.c

# Rules to build individual files
#
alter.lo:	$(TOP)/src/alter.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/alter.c

analyze.lo:	$(TOP)/src/analyze.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/analyze.c

attach.lo:	$(TOP)/src/attach.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/attach.c

auth.lo:	$(TOP)/src/auth.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/auth.c

backup.lo:	$(TOP)/src/backup.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/backup.c

bitvec.lo:	$(TOP)/src/bitvec.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/bitvec.c

btmutex.lo:	$(TOP)/src/btmutex.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btmutex.c

btree.lo:	$(TOP)/src/btree.c $(HDR) $(TOP)/src/pager.h
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btree.c

build.lo:	$(TOP)/src/build.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/build.c

callback.lo:	$(TOP)/src/callback.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/callback.c

complete.lo:	$(TOP)/src/complete.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/complete.c

date.lo:	$(TOP)/src/date.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/date.c

delete.lo:	$(TOP)/src/delete.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/delete.c

expr.lo:	$(TOP)/src/expr.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/expr.c

fault.lo:	$(TOP)/src/fault.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fault.c

fkey.lo:	$(TOP)/src/fkey.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fkey.c

func.lo:	$(TOP)/src/func.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/func.c

global.lo:	$(TOP)/src/global.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/global.c

hash.lo:	$(TOP)/src/hash.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/hash.c

insert.lo:	$(TOP)/src/insert.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/insert.c

journal.lo:	$(TOP)/src/journal.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/journal.c

legacy.lo:	$(TOP)/src/legacy.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/legacy.c

loadext.lo:	$(TOP)/src/loadext.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/loadext.c

main.lo:	$(TOP)/src/main.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/main.c

malloc.lo:	$(TOP)/src/malloc.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/malloc.c

mem0.lo:	$(TOP)/src/mem0.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem0.c

mem1.lo:	$(TOP)/src/mem1.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem1.c

mem2.lo:	$(TOP)/src/mem2.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem2.c

mem3.lo:	$(TOP)/src/mem3.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem3.c

mem5.lo:	$(TOP)/src/mem5.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem5.c

memjournal.lo:	$(TOP)/src/memjournal.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/memjournal.c

mutex.lo:	$(TOP)/src/mutex.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex.c

mutex_noop.lo:	$(TOP)/src/mutex_noop.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_noop.c

mutex_os2.lo:	$(TOP)/src/mutex_os2.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_os2.c

mutex_unix.lo:	$(TOP)/src/mutex_unix.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_unix.c

mutex_w32.lo:	$(TOP)/src/mutex_w32.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_w32.c

notify.lo:	$(TOP)/src/notify.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/notify.c

pager.lo:	$(TOP)/src/pager.c $(HDR) $(TOP)/src/pager.h
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pager.c

pcache.lo:	$(TOP)/src/pcache.c $(HDR) $(TOP)/src/pcache.h
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache.c

pcache1.lo:	$(TOP)/src/pcache1.c $(HDR) $(TOP)/src/pcache.h
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache1.c

opcodes.lo:	opcodes.c
	$(LTCOMPILE) $(TEMP_STORE) -c opcodes.c

opcodes.c:	opcodes.h $(TOP)/mkopcodec.awk
	sort -n -b -k 3 opcodes.h | $(NAWK) -f $(TOP)/mkopcodec.awk >opcodes.c

opcodes.h:	parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk
	cat parse.h $(TOP)/src/vdbe.c | $(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h

os.lo:	$(TOP)/src/os.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os.c

os_unix.lo:	$(TOP)/src/os_unix.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_unix.c

os_win.lo:	$(TOP)/src/os_win.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_win.c

os_os2.lo:	$(TOP)/src/os_os2.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_os2.c

parse.lo:	parse.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c parse.c

parse.h:	parse.c

parse.c:	$(TOP)/src/parse.y lemon$(BEXE) $(TOP)/addopcodes.awk
	cp $(TOP)/src/parse.y .
	./lemon$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) parse.y
	mv parse.h parse.h.temp
	$(NAWK) -f $(TOP)/addopcodes.awk parse.h.temp >parse.h

pragma.lo:	$(TOP)/src/pragma.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pragma.c

prepare.lo:	$(TOP)/src/prepare.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/prepare.c

printf.lo:	$(TOP)/src/printf.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/printf.c

random.lo:	$(TOP)/src/random.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/random.c

resolve.lo:	$(TOP)/src/resolve.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/resolve.c

rowset.lo:	$(TOP)/src/rowset.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/rowset.c

select.lo:	$(TOP)/src/select.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/select.c

status.lo:	$(TOP)/src/status.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/status.c

sqlite3.h:	$(TOP)/src/sqlite.h.in $(TOP)/manifest.uuid $(TOP)/VERSION
	tclsh $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h

table.lo:	$(TOP)/src/table.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/table.c

tclsqlite.lo:	$(TOP)/src/tclsqlite.c $(HDR)
	$(LTCOMPILE) -DUSE_TCL_STUBS=1 -c $(TOP)/src/tclsqlite.c

tokenize.lo:	$(TOP)/src/tokenize.c keywordhash.h $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/tokenize.c

keywordhash.h:	$(TOP)/tool/mkkeywordhash.c
	$(BCC) -o mkkeywordhash$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)/tool/mkkeywordhash.c
	./mkkeywordhash$(BEXE) >keywordhash.h

trigger.lo:	$(TOP)/src/trigger.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/trigger.c

update.lo:	$(TOP)/src/update.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/update.c

utf.lo:	$(TOP)/src/utf.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/utf.c

util.lo:	$(TOP)/src/util.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/util.c

vacuum.lo:	$(TOP)/src/vacuum.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vacuum.c

vdbe.lo:	$(TOP)/src/vdbe.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbe.c

vdbeapi.lo:	$(TOP)/src/vdbeapi.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeapi.c

vdbeaux.lo:	$(TOP)/src/vdbeaux.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeaux.c

vdbeblob.lo:	$(TOP)/src/vdbeblob.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeblob.c

vdbemem.lo:	$(TOP)/src/vdbemem.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbemem.c

vtab.lo:	$(TOP)/src/vtab.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vtab.c

walker.lo:	$(TOP)/src/walker.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/walker.c

where.lo:	$(TOP)/src/where.c $(HDR)
	$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/where.c

tclsqlite-shell.lo:	$(TOP)/src/tclsqlite.c $(HDR)
	$(LTCOMPILE) -DTCLSH=1 -o $@ -c $(TOP)/src/tclsqlite.c

tclsqlite-stubs.lo:	$(TOP)/src/tclsqlite.c $(HDR)
	$(LTCOMPILE) -DTCL_USE_STUBS=1 -o $@ -c $(TOP)/src/tclsqlite.c

tclsqlite3$(TEXE):	tclsqlite-shell.lo libsqlite3.la
	$(LTLINK) -o $@ tclsqlite-shell.lo \
		 libsqlite3.la $(LIBTCL)

testfixture$(TEXE):	$(TESTFIXTURE_SRC)
	$(LTLINK) -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_NO_SYNC=1\
		-DSQLITE_CRASH_TEST=1 \
                -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE $(TEMP_STORE) \
		-o $@ $(TESTFIXTURE_SRC) $(LIBTCL) $(TLIBS)


fulltest:	testfixture$(TEXE) sqlite3$(TEXE)
	./testfixture$(TEXE) $(TOP)/test/all.test

test:	testfixture$(TEXE) sqlite3$(TEXE)
	./testfixture$(TEXE) $(TOP)/test/veryquick.test

sqlite3_analyzer$(TEXE):	$(TESTFIXTURE_SRC) $(TOP)/tool/spaceanal.tcl
	sed \
	  -e '/^#/d' \
	  -e 's,\\,\\\\,g' \
	  -e 's,",\\",g' \
	  -e 's,^,",' \
	  -e 's,$$,\\n",' \
	  $(TOP)/tool/spaceanal.tcl >spaceanal_tcl.h
	$(LTLINK) -DTCLSH=2 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 \
		-DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE \
		$(TEMP_STORE) -o $@ $(TESTFIXTURE_SRC) $(LIBTCL)


lib_install:	libsqlite3.la
	$(INSTALL) -d $(DESTDIR)$(libdir)
	$(LTINSTALL) libsqlite3.la $(DESTDIR)$(libdir)
	
install:	sqlite3$(BEXE) lib_install sqlite3.h sqlite3.pc ${HAVE_TCL:1=tcl_install}
	$(INSTALL) -d $(DESTDIR)$(bindir)
	$(LTINSTALL) sqlite3$(BEXE) $(DESTDIR)$(bindir)
	$(INSTALL) -d $(DESTDIR)$(includedir)
	$(INSTALL) -m 0644 sqlite3.h $(DESTDIR)$(includedir)
	$(INSTALL) -m 0644 $(TOP)/src/sqlite3ext.h $(DESTDIR)$(includedir)
	$(INSTALL) -d $(DESTDIR)$(pkgconfigdir)
	$(INSTALL) -m 0644 sqlite3.pc $(DESTDIR)$(pkgconfigdir)

pkgIndex.tcl:
	echo 'package ifneeded sqlite3 $(RELEASE) [list load $(TCLLIBDIR)/libtclsqlite3.so sqlite3]' > $@
tcl_install:	lib_install libtclsqlite3.la pkgIndex.tcl
	$(INSTALL) -d $(DESTDIR)$(TCLLIBDIR)
	$(LTINSTALL) libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR)
	rm -f $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.a
	$(INSTALL) -m 0644 pkgIndex.tcl $(DESTDIR)$(TCLLIBDIR)

clean:	
	rm -f *.lo *.la *.o sqlite3$(TEXE) libsqlite3.la
	rm -f sqlite3.h opcodes.*
	rm -rf .libs .deps tsrc
	rm -f lemon$(BEXE) lempar.c parse.* sqlite*.tar.gz
	rm -f mkkeywordhash$(BEXE) keywordhash.h
	rm -f $(PUBLISH)
	rm -f *.da *.bb *.bbg gmon.out
	rm -f testfixture$(TEXE) test.db
	rm -f common.tcl
	rm -f sqlite3.dll sqlite3.lib sqlite3.def
	rm -f sqlite3.c .target_source

distclean:	clean
	rm -f config.log config.status libtool Makefile sqlite3.pc

#
# Windows section
#
dll: sqlite3.dll

REAL_LIBOBJ = $(LIBOBJ:%.lo=.libs/%.o)

$(REAL_LIBOBJ): $(LIBOBJ)

sqlite3.def: $(REAL_LIBOBJ)
	echo 'EXPORTS' >sqlite3.def
	nm $(REAL_LIBOBJ) | grep ' T ' | grep ' _sqlite3_' \
		| sed 's/^.* _//' >>sqlite3.def

sqlite3.dll: $(REAL_LIBOBJ) sqlite3.def
	$(TCC) -shared -o $@ sqlite3.def \
		-Wl,"--strip-all" $(REAL_LIBOBJ)

Added Makefile.linux-gcc.

































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/make
#
# Makefile for SQLITE
#
# This is a template makefile for SQLite.  Most people prefer to
# use the autoconf generated "configure" script to generate the
# makefile automatically.  But that does not work for everybody
# and in every situation.  If you are having problems with the
# "configure" script, you might want to try this makefile as an
# alternative.  Create a copy of this file, edit the parameters
# below and type "make".
#

#### The toplevel directory of the source tree.  This is the directory
#    that contains this "Makefile.in" and the "configure.in" script.
#
TOP = ../sqlite

#### C Compiler and options for use in building executables that
#    will run on the platform that is doing the build.
#
BCC = gcc -g -O2
#BCC = /opt/ancic/bin/c89 -0

#### If the target operating system supports the "usleep()" system
#    call, then define the HAVE_USLEEP macro for all C modules.
#
#USLEEP = 
USLEEP = -DHAVE_USLEEP=1

#### If you want the SQLite library to be safe for use within a 
#    multi-threaded program, then define the following macro
#    appropriately:
#
#THREADSAFE = -DTHREADSAFE=1
THREADSAFE = -DTHREADSAFE=0

#### Specify any extra linker options needed to make the library
#    thread safe
#
#THREADLIB = -lpthread
THREADLIB = 

#### Specify any extra libraries needed to access required functions.
#
#TLIBS = -lrt    # fdatasync on Solaris 8
TLIBS = 

#### Leave SQLITE_DEBUG undefined for maximum speed.  Use SQLITE_DEBUG=1
#    to check for memory leaks.  Use SQLITE_DEBUG=2 to print a log of all
#    malloc()s and free()s in order to track down memory leaks.
#    
#    SQLite uses some expensive assert() statements in the inner loop.
#    You can make the library go almost twice as fast if you compile
#    with -DNDEBUG=1
#
#OPTS = -DSQLITE_DEBUG=2
#OPTS = -DSQLITE_DEBUG=1
#OPTS = 
OPTS = -DNDEBUG=1
OPTS += -DHAVE_FDATASYNC=1

#### The suffix to add to executable files.  ".exe" for windows.
#    Nothing for unix.
#
#EXE = .exe
EXE =

#### C Compile and options for use in building executables that 
#    will run on the target platform.  This is usually the same
#    as BCC, unless you are cross-compiling.
#
TCC = gcc -O6
#TCC = gcc -g -O0 -Wall
#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage
#TCC = /opt/mingw/bin/i386-mingw32-gcc -O6
#TCC = /opt/ansic/bin/c89 -O +z -Wl,-a,archive

#### Tools used to build a static library.
#
AR = ar cr
#AR = /opt/mingw/bin/i386-mingw32-ar cr
RANLIB = ranlib
#RANLIB = /opt/mingw/bin/i386-mingw32-ranlib

MKSHLIB = gcc -shared
SO = so
SHPREFIX = lib
# SO = dll
# SHPREFIX =

#### Extra compiler options needed for programs that use the TCL library.
#
#TCL_FLAGS =
#TCL_FLAGS = -DSTATIC_BUILD=1
TCL_FLAGS = -I/home/drh/tcltk/8.4linux
#TCL_FLAGS = -I/home/drh/tcltk/8.4win -DSTATIC_BUILD=1
#TCL_FLAGS = -I/home/drh/tcltk/8.3hpux

#### Linker options needed to link against the TCL library.
#
#LIBTCL = -ltcl -lm -ldl
LIBTCL = /home/drh/tcltk/8.4linux/libtcl8.4g.a -lm -ldl
#LIBTCL = /home/drh/tcltk/8.4win/libtcl84s.a -lmsvcrt
#LIBTCL = /home/drh/tcltk/8.3hpux/libtcl8.3.a -ldld -lm -lc

#### Additional objects for SQLite library when TCL support is enabled.
#TCLOBJ =
TCLOBJ = tclsqlite.o

#### Compiler options needed for programs that use the readline() library.
#
READLINE_FLAGS =
#READLINE_FLAGS = -DHAVE_READLINE=1 -I/usr/include/readline

#### Linker options needed by programs using readline() must link against.
#
LIBREADLINE =
#LIBREADLINE = -static -lreadline -ltermcap

#### Which "awk" program provides nawk compatibilty
#
# NAWK = nawk
NAWK = awk

# You should not have to change anything below this line
###############################################################################
include $(TOP)/main.mk

Added Makefile.vxworks.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
#!/usr/make
#
# Makefile for SQLITE on VxWorks

ifeq ($(FORCPU),)
  FORCPU = SH32gnule
endif

TOOL_FAMILY = gnu

include $(WIND_USR)/tool/gnu/make.$(FORCPU)

#### The toplevel directory of the source tree.  This is the directory
#    that contains this "Makefile.in" and the "configure.in" script.
#
TOP = .

#### C Compiler and options for use in building executables that
#    will run on the platform that is doing the build.
#
BCC = gcc -g -O2
#BCC = /opt/ancic/bin/c89 -0

#### If the target operating system supports the "usleep()" system
#    call, then define the HAVE_USLEEP macro for all C modules.
#
USLEEP = 
#USLEEP = -DHAVE_USLEEP=1

#### If you want the SQLite library to be safe for use within a 
#    multi-threaded program, then define the following macro
#    appropriately:
#
THREADSAFE = -DSQLITE_THREADSAFE=1
#THREADSAFE = -DSQLITE_THREADSAFE=0

#### Specify any extra linker options needed to make the library
#    thread safe
#
#THREADLIB = -lpthread
THREADLIB = 

#### Specify any extra libraries needed to access required functions.
#
ifeq ($(CPU),SH32) 
  # for SH4 shared library
  TLIBS_SHARED += -L$(WIND_USR)/lib/sh/SH32/commonle/PIC
else 
  # for all other CPUs shared library
  TLIBS_SHARED += $(LD_LINK_PATH_ATEND) $(LD_PARTIAL_LAST_FLAGS)
endif
# for static library
TLIBS += $(LD_LINK_PATH_ATEND) $(LD_PARTIAL_LAST_FLAGS)

#### Leave SQLITE_DEBUG undefined for maximum speed.  Use SQLITE_DEBUG=1
#    to check for memory leaks.  Use SQLITE_DEBUG=2 to print a log of all
#    malloc()s and free()s in order to track down memory leaks.
#    
#    SQLite uses some expensive assert() statements in the inner loop.
#    You can make the library go almost twice as fast if you compile
#    with -DNDEBUG=1
#
#OPTS = -DSQLITE_DEBUG=2
#OPTS = -DSQLITE_DEBUG=1
#OPTS = 
OPTS = -DNDEBUG=1 -DSQLITE_OS_UNIX=1 $(THREADSAFE)
OPTS += -DSQLITE_OMIT_LOAD_EXTENSION=1
OPTS += -DSQLITE_ENABLE_LOCKING_STYLE=1
OPTS += -DSQLITE_THREAD_OVERRIDE_LOCK=0
OPTS += -DSQLITE_ENABLE_COLUMN_METADATA=1
OPTS += -DHAVE_FDATASYNC=1

#### The suffix to add to executable files.  ".exe" for windows.
#    Nothing for unix.
#
EXE = .vxe
#EXE =

#### C Compile and options for use in building executables that 
#    will run on the target platform.  This is usually the same
#    as BCC, unless you are cross-compiling.
#
#TCC = gcc -O6
#TCC = gcc -g -O0 -Wall
#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage
#TCC = /opt/mingw/bin/i386-mingw32-gcc -O6
TCC = $(CC) $(DEFINE_CC) -O2 -g -mrtp $(CC_ARCH_SPEC) -D_REENTRANT=1 -D_VX_CPU=_VX_$(CPU) -D_VX_TOOL_FAMILY=$(TOOL_FAMILY) -D_VX_TOOL=$(TOOL)
TCC += -I$(WIND_USR)/h -I$(WIND_USR)/h/wrn/coreip
#TCC = /opt/ansic/bin/c89 -O +z -Wl,-a,archive

#TCC_SHARED = $(TCC) -fPIC
TCC_SHARED = $(TCC)

#### Tools used to build a static library.
#
#ARX = ar cr
#ARX = /opt/mingw/bin/i386-mingw32-ar cr
AR += cr
#RANLIB = ranlib
#RANLIB = /opt/mingw/bin/i386-mingw32-ranlib

#MKSHLIB = gcc -shared
#SO = so
#SHPREFIX = lib
MKSHLIB = $(CC) $(DEFINE_CC) -mrtp -shared $(CC_ARCH_SPEC) -D_VX_CPU=_VX_$(CPU) -D_VX_TOOL_FAMILY=$(TOOL_FAMILY) -D_VX_TOOL=$(TOOL)
SO = so
SHPREFIX = lib

#### Extra compiler options needed for programs that use the TCL library.
#
#TCL_FLAGS =
#TCL_FLAGS = -DSTATIC_BUILD=1
TCL_FLAGS = -I/home/drh/tcltk/8.4linux
#TCL_FLAGS = -I/home/drh/tcltk/8.4win -DSTATIC_BUILD=1
#TCL_FLAGS = -I/home/drh/tcltk/8.3hpux

#### Linker options needed to link against the TCL library.
#
#LIBTCL = -ltcl -lm -ldl
LIBTCL = /home/drh/tcltk/8.4linux/libtcl8.4g.a -lm -ldl
#LIBTCL = /home/drh/tcltk/8.4win/libtcl84s.a -lmsvcrt
#LIBTCL = /home/drh/tcltk/8.3hpux/libtcl8.3.a -ldld -lm -lc

#### Additional objects for SQLite library when TCL support is enabled.
TCLOBJ =
#TCLOBJ = tclsqlite.o

#### Compiler options needed for programs that use the readline() library.
#
READLINE_FLAGS =
#READLINE_FLAGS = -DHAVE_READLINE=1 -I/usr/include/readline

#### Linker options needed by programs using readline() must link against.
#
LIBREADLINE =
#LIBREADLINE = -static -lreadline -ltermcap

#### Which "awk" program provides nawk compatibilty
#
# NAWK = nawk
NAWK = awk


#### Pasted and adapted main.mk file
###############################################################################
# The following macros should be defined before this script is
# invoked:
#
# TOP              The toplevel directory of the source tree.  This is the
#                  directory that contains this "Makefile.in" and the
#                  "configure.in" script.
#
# BCC              C Compiler and options for use in building executables that
#                  will run on the platform that is doing the build.
#
# THREADLIB        Specify any extra linker options needed to make the library
#                  thread safe
#
# OPTS             Extra compiler command-line options.
#
# EXE              The suffix to add to executable files.  ".exe" for windows
#                  and "" for Unix.
#
# TCC              C Compiler and options for use in building executables that 
#                  will run on the target platform.  This is usually the same
#                  as BCC, unless you are cross-compiling.
#
# AR               Tools used to build a static library.
# RANLIB
#
# TCL_FLAGS        Extra compiler options needed for programs that use the
#                  TCL library.
#
# LIBTCL           Linker options needed to link against the TCL library.
#
# READLINE_FLAGS   Compiler options needed for programs that use the
#                  readline() library.
#
# LIBREADLINE      Linker options needed by programs using readline() must
#                  link against.
#
# NAWK             Nawk compatible awk program.  Older (obsolete?) solaris
#                  systems need this to avoid using the original AT&T AWK.
#
# Once the macros above are defined, the rest of this make script will
# build the SQLite library and testing tools.
################################################################################

# This is how we compile
#
TCCX = $(TCC) $(OPTS) -I. -I$(TOP)/src -I$(TOP)
TCCX_SHARED = $(TCC_SHARED) $(OPTS) -I. -I$(TOP)/src -I$(TOP) \
	-I$(TOP)/ext/rtree -I$(TOP)/ext/icu -I$(TOP)/ext/fts3 \
	-I$(TOP)/ext/async

# Object files for the SQLite library.
#
LIBOBJ+= alter.o analyze.o attach.o auth.o \
         backup.o bitvec.o btmutex.o btree.o build.o \
         callback.o complete.o date.o delete.o expr.o fault.o \
         fts3.o fts3_expr.o fts3_hash.o fts3_icu.o fts3_porter.o \
         fts3_tokenizer.o fts3_tokenizer1.o \
         func.o global.o hash.o \
         icu.o insert.o journal.o legacy.o loadext.o \
         main.o malloc.o mem0.o mem1.o mem2.o mem3.o mem5.o \
         memjournal.o \
         mutex.o mutex_noop.o mutex_os2.o mutex_unix.o mutex_w32.o \
         notify.o opcodes.o os.o os_os2.o os_unix.o os_win.o \
         pager.o parse.o pcache.o pcache1.o pragma.o prepare.o printf.o \
         random.o resolve.o rowset.o rtree.o select.o status.o \
         table.o tokenize.o trigger.o \
         update.o util.o vacuum.o \
         vdbe.o vdbeapi.o vdbeaux.o vdbeblob.o vdbemem.o \
         walker.o where.o utf.o vtab.o



# All of the source code files.
#
SRC = \
  $(TOP)/src/alter.c \
  $(TOP)/src/analyze.c \
  $(TOP)/src/attach.c \
  $(TOP)/src/auth.c \
  $(TOP)/src/backup.c \
  $(TOP)/src/bitvec.c \
  $(TOP)/src/btmutex.c \
  $(TOP)/src/btree.c \
  $(TOP)/src/btree.h \
  $(TOP)/src/btreeInt.h \
  $(TOP)/src/build.c \
  $(TOP)/src/callback.c \
  $(TOP)/src/complete.c \
  $(TOP)/src/date.c \
  $(TOP)/src/delete.c \
  $(TOP)/src/expr.c \
  $(TOP)/src/fault.c \
  $(TOP)/src/func.c \
  $(TOP)/src/global.c \
  $(TOP)/src/hash.c \
  $(TOP)/src/hash.h \
  $(TOP)/src/hwtime.h \
  $(TOP)/src/insert.c \
  $(TOP)/src/journal.c \
  $(TOP)/src/legacy.c \
  $(TOP)/src/loadext.c \
  $(TOP)/src/main.c \
  $(TOP)/src/malloc.c \
  $(TOP)/src/mem0.c \
  $(TOP)/src/mem1.c \
  $(TOP)/src/mem2.c \
  $(TOP)/src/mem3.c \
  $(TOP)/src/mem5.c \
  $(TOP)/src/memjournal.c \
  $(TOP)/src/mutex.c \
  $(TOP)/src/mutex.h \
  $(TOP)/src/mutex_noop.c \
  $(TOP)/src/mutex_os2.c \
  $(TOP)/src/mutex_unix.c \
  $(TOP)/src/mutex_w32.c \
  $(TOP)/src/notify.c \
  $(TOP)/src/os.c \
  $(TOP)/src/os.h \
  $(TOP)/src/os_common.h \
  $(TOP)/src/os_os2.c \
  $(TOP)/src/os_unix.c \
  $(TOP)/src/os_win.c \
  $(TOP)/src/pager.c \
  $(TOP)/src/pager.h \
  $(TOP)/src/parse.y \
  $(TOP)/src/pcache.c \
  $(TOP)/src/pcache.h \
  $(TOP)/src/pcache1.c \
  $(TOP)/src/pragma.c \
  $(TOP)/src/prepare.c \
  $(TOP)/src/printf.c \
  $(TOP)/src/random.c \
  $(TOP)/src/resolve.c \
  $(TOP)/src/rowset.c \
  $(TOP)/src/select.c \
  $(TOP)/src/status.c \
  $(TOP)/src/shell.c \
  $(TOP)/src/sqlite.h.in \
  $(TOP)/src/sqlite3ext.h \
  $(TOP)/src/sqliteInt.h \
  $(TOP)/src/sqliteLimit.h \
  $(TOP)/src/table.c \
  $(TOP)/src/tclsqlite.c \
  $(TOP)/src/tokenize.c \
  $(TOP)/src/trigger.c \
  $(TOP)/src/utf.c \
  $(TOP)/src/update.c \
  $(TOP)/src/util.c \
  $(TOP)/src/vacuum.c \
  $(TOP)/src/vdbe.c \
  $(TOP)/src/vdbe.h \
  $(TOP)/src/vdbeapi.c \
  $(TOP)/src/vdbeaux.c \
  $(TOP)/src/vdbeblob.c \
  $(TOP)/src/vdbemem.c \
  $(TOP)/src/vdbeInt.h \
  $(TOP)/src/vtab.c \
  $(TOP)/src/walker.c \
  $(TOP)/src/where.c

# Source code for extensions
#
SRC += \
  $(TOP)/ext/fts1/fts1.c \
  $(TOP)/ext/fts1/fts1.h \
  $(TOP)/ext/fts1/fts1_hash.c \
  $(TOP)/ext/fts1/fts1_hash.h \
  $(TOP)/ext/fts1/fts1_porter.c \
  $(TOP)/ext/fts1/fts1_tokenizer.h \
  $(TOP)/ext/fts1/fts1_tokenizer1.c
SRC += \
  $(TOP)/ext/fts2/fts2.c \
  $(TOP)/ext/fts2/fts2.h \
  $(TOP)/ext/fts2/fts2_hash.c \
  $(TOP)/ext/fts2/fts2_hash.h \
  $(TOP)/ext/fts2/fts2_icu.c \
  $(TOP)/ext/fts2/fts2_porter.c \
  $(TOP)/ext/fts2/fts2_tokenizer.h \
  $(TOP)/ext/fts2/fts2_tokenizer.c \
  $(TOP)/ext/fts2/fts2_tokenizer1.c
SRC += \
  $(TOP)/ext/fts3/fts3.c \
  $(TOP)/ext/fts3/fts3.h \
  $(TOP)/ext/fts3/fts3_expr.c \
  $(TOP)/ext/fts3/fts3_expr.h \
  $(TOP)/ext/fts3/fts3_hash.c \
  $(TOP)/ext/fts3/fts3_hash.h \
  $(TOP)/ext/fts3/fts3_icu.c \
  $(TOP)/ext/fts3/fts3_porter.c \
  $(TOP)/ext/fts3/fts3_tokenizer.h \
  $(TOP)/ext/fts3/fts3_tokenizer.c \
  $(TOP)/ext/fts3/fts3_tokenizer1.c
SRC += \
  $(TOP)/ext/icu/sqliteicu.h \
  $(TOP)/ext/icu/icu.c 
SRC += \
  $(TOP)/ext/rtree/rtree.h \
  $(TOP)/ext/rtree/rtree.c


# Generated source code files
#
SRC += \
  keywordhash.h \
  opcodes.c \
  opcodes.h \
  parse.c \
  parse.h \
  sqlite3.h


# Source code to the test files.
#
TESTSRC = \
  $(TOP)/src/test1.c \
  $(TOP)/src/test2.c \
  $(TOP)/src/test3.c \
  $(TOP)/src/test4.c \
  $(TOP)/src/test5.c \
  $(TOP)/src/test6.c \
  $(TOP)/src/test7.c \
  $(TOP)/src/test8.c \
  $(TOP)/src/test9.c \
  $(TOP)/src/test_autoext.c \
  $(TOP)/src/test_async.c \
  $(TOP)/src/test_backup.c \
  $(TOP)/src/test_btree.c \
  $(TOP)/src/test_config.c \
  $(TOP)/src/test_devsym.c \
  $(TOP)/src/test_func.c \
  $(TOP)/src/test_hexio.c \
  $(TOP)/src/test_journal.c \
  $(TOP)/src/test_malloc.c \
  $(TOP)/src/test_md5.c \
  $(TOP)/src/test_mutex.c \
  $(TOP)/src/test_onefile.c \
  $(TOP)/src/test_osinst.c \
  $(TOP)/src/test_pcache.c \
  $(TOP)/src/test_schema.c \
  $(TOP)/src/test_server.c \
  $(TOP)/src/test_tclvar.c \
  $(TOP)/src/test_thread.c \
  $(TOP)/src/test_wsd.c \

#TESTSRC += $(TOP)/ext/fts2/fts2_tokenizer.c
#TESTSRC += $(TOP)/ext/fts3/fts3_tokenizer.c

TESTSRC2 = \
  $(TOP)/src/attach.c $(TOP)/src/backup.c $(TOP)/src/btree.c                   \
  $(TOP)/src/build.c $(TOP)/src/date.c                                         \
  $(TOP)/src/expr.c $(TOP)/src/func.c $(TOP)/src/insert.c $(TOP)/src/os.c      \
  $(TOP)/src/os_os2.c $(TOP)/src/os_unix.c $(TOP)/src/os_win.c                 \
  $(TOP)/src/pager.c $(TOP)/src/pragma.c $(TOP)/src/prepare.c                  \
  $(TOP)/src/printf.c $(TOP)/src/random.c $(TOP)/src/pcache.c                  \
  $(TOP)/src/pcache1.c $(TOP)/src/select.c $(TOP)/src/tokenize.c               \
  $(TOP)/src/utf.c $(TOP)/src/util.c $(TOP)/src/vdbeapi.c $(TOP)/src/vdbeaux.c \
  $(TOP)/src/vdbe.c $(TOP)/src/vdbemem.c $(TOP)/src/where.c parse.c            \
  $(TOP)/ext/fts3/fts3.c $(TOP)/ext/fts3/fts3_expr.c                           \
  $(TOP)/ext/fts3/fts3_tokenizer.c                                             \
  $(TOP)/ext/async/sqlite3async.c

# Header files used by all library source files.
#
HDR = \
   $(TOP)/src/btree.h \
   $(TOP)/src/btreeInt.h \
   $(TOP)/src/hash.h \
   $(TOP)/src/hwtime.h \
   keywordhash.h \
   $(TOP)/src/mutex.h \
   opcodes.h \
   $(TOP)/src/os.h \
   $(TOP)/src/os_common.h \
   $(TOP)/src/pager.h \
   $(TOP)/src/pcache.h \
   parse.h  \
   sqlite3.h  \
   $(TOP)/src/sqlite3ext.h \
   $(TOP)/src/sqliteInt.h  \
   $(TOP)/src/sqliteLimit.h \
   $(TOP)/src/vdbe.h \
   $(TOP)/src/vdbeInt.h

# Header files used by extensions
#
EXTHDR += \
  $(TOP)/ext/fts1/fts1.h \
  $(TOP)/ext/fts1/fts1_hash.h \
  $(TOP)/ext/fts1/fts1_tokenizer.h
EXTHDR += \
  $(TOP)/ext/fts2/fts2.h \
  $(TOP)/ext/fts2/fts2_hash.h \
  $(TOP)/ext/fts2/fts2_tokenizer.h
EXTHDR += \
  $(TOP)/ext/fts3/fts3.h \
  $(TOP)/ext/fts3/fts3_expr.h \
  $(TOP)/ext/fts3/fts3_hash.h \
  $(TOP)/ext/fts3/fts3_tokenizer.h
EXTHDR += \
  $(TOP)/ext/rtree/rtree.h
EXTHDR += \
  $(TOP)/ext/icu/sqliteicu.h

# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.a sqlite3$(EXE)

libsqlite3.a:	$(LIBOBJ)
	$(AR) libsqlite3.a $(LIBOBJ)
	$(RANLIB) libsqlite3.a

$(SHPREFIX)sqlite3.$(SO):	$(LIBOBJ)
	$(MKSHLIB) -o $(SHPREFIX)sqlite3.$(SO) $(LIBOBJ) $(TLIBS_SHARED)

sqlite3$(EXE):	$(TOP)/src/shell.c libsqlite3.a sqlite3.h
	$(TCCX) $(READLINE_FLAGS) -o sqlite3$(EXE)      \
		$(TOP)/src/shell.c                      \
		$(LIBREADLINE) $(TLIBS) $(THREADLIB) -L. -lsqlite3

# This target creates a directory named "tsrc" and fills it with
# copies of all of the C source code and header files needed to
# build on the target system.  Some of the C source code and header
# files are automatically generated.  This target takes care of
# all that automatic generation.
#
target_source:	$(SRC)
	rm -rf tsrc
	mkdir tsrc
	cp -f $(SRC) tsrc
	rm tsrc/sqlite.h.in tsrc/parse.y
	touch target_source

sqlite3.c:	target_source $(TOP)/tool/mksqlite3c.tcl
	tclsh $(TOP)/tool/mksqlite3c.tcl
	cp sqlite3.c tclsqlite3.c
	cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c

fts2amal.c:	target_source $(TOP)/ext/fts2/mkfts2amal.tcl
	tclsh $(TOP)/ext/fts2/mkfts2amal.tcl

fts3amal.c:	target_source $(TOP)/ext/fts3/mkfts3amal.tcl
	tclsh $(TOP)/ext/fts3/mkfts3amal.tcl

# Rules to build the LEMON compiler generator
#
lemon:	$(TOP)/tool/lemon.c $(TOP)/src/lempar.c
	$(BCC) -o lemon $(TOP)/tool/lemon.c
	cp $(TOP)/src/lempar.c .

# Rules to build individual *.o files from generated *.c files. This
# applies to:
#
#     parse.o
#     opcodes.o
#
%.o: %.c $(HDR)
	$(TCCX_SHARED) -c $<

# Rules to build individual *.o files from files in the src directory.
#
%.o: $(TOP)/src/%.c $(HDR)
	$(TCCX_SHARED) -c $<

tclsqlite.o:	$(TOP)/src/tclsqlite.c $(HDR)
	$(TCCX_SHARED) $(TCL_FLAGS) -c $(TOP)/src/tclsqlite.c



# Rules to build opcodes.c and opcodes.h
#
opcodes.c:	opcodes.h $(TOP)/mkopcodec.awk
	sort -n -b -k 3 opcodes.h | $(NAWK) -f $(TOP)/mkopcodec.awk >opcodes.c

opcodes.h:	parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk
	cat parse.h $(TOP)/src/vdbe.c | \
		$(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h

# Rules to build parse.c and parse.h - the outputs of lemon.
#
parse.h:	parse.c

parse.c:	$(TOP)/src/parse.y lemon $(TOP)/addopcodes.awk
	cp $(TOP)/src/parse.y .
	rm -f parse.h
	./lemon $(OPTS) parse.y
	mv parse.h parse.h.temp
	awk -f $(TOP)/addopcodes.awk parse.h.temp >parse.h

sqlite3.h:	$(TOP)/src/sqlite.h.in 
	sed -e s/--VERS--/`cat ${TOP}/VERSION`/ \
	    -e s/--VERSION-NUMBER--/`cat ${TOP}/VERSION | sed 's/[^0-9]/ /g' | $(NAWK) '{printf "%d%03d%03d",$$1,$$2,$$3}'`/ \
                 $(TOP)/src/sqlite.h.in >sqlite3.h

keywordhash.h:	$(TOP)/tool/mkkeywordhash.c
	$(BCC) -o mkkeywordhash $(OPTS) $(TOP)/tool/mkkeywordhash.c
	./mkkeywordhash >keywordhash.h



# Rules to build the extension objects.
#
icu.o:	$(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c

fts2.o:	$(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c

fts2_hash.o:	$(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c

fts2_icu.o:	$(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c

fts2_porter.o:	$(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c

fts2_tokenizer.o:	$(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c

fts2_tokenizer1.o:	$(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c

fts3.o:	$(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c

fts3_expr.o:	$(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c

fts3_hash.o:	$(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c

fts3_icu.o:	$(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c

fts3_porter.o:	$(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c

fts3_tokenizer.o:	$(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c

fts3_tokenizer1.o:	$(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c

rtree.o:	$(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR)
	$(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c


# Rules for building test programs and for running tests
#
tclsqlite3:	$(TOP)/src/tclsqlite.c libsqlite3.a
	$(TCCX_SHARED) $(TCL_FLAGS) -DTCLSH=1 -o tclsqlite3 \
		$(TOP)/src/tclsqlite.c libsqlite3.a $(LIBTCL) $(THREADLIB)


# Rules to build the 'testfixture' application.
#
TESTFIXTURE_FLAGS  = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1
TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE 

testfixture$(EXE): $(TESTSRC2) libsqlite3.a $(TESTSRC) $(TOP)/src/tclsqlite.c
	$(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS)                            \
		$(TESTSRC) $(TESTSRC2) $(TOP)/src/tclsqlite.c                \
		-o testfixture$(EXE) $(LIBTCL) $(THREADLIB) libsqlite3.a

amalgamation-testfixture$(EXE): sqlite3.c $(TESTSRC) $(TOP)/src/tclsqlite.c
	$(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS)                            \
		$(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c                  \
		-o testfixture$(EXE) $(LIBTCL) $(THREADLIB)

fts3-testfixture$(EXE): sqlite3.c fts3amal.c $(TESTSRC) $(TOP)/src/tclsqlite.c
	$(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS)                            \
	-DSQLITE_ENABLE_FTS3=1                                               \
		$(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c fts3amal.c       \
		-o testfixture$(EXE) $(LIBTCL) $(THREADLIB)

fulltest:	testfixture$(EXE) sqlite3$(EXE)
	./testfixture$(EXE) $(TOP)/test/all.test

soaktest:	testfixture$(EXE) sqlite3$(EXE)
	./testfixture$(EXE) $(TOP)/test/all.test -soak 1

test:	testfixture$(EXE) sqlite3$(EXE)
	./testfixture$(EXE) $(TOP)/test/veryquick.test

sqlite3_analyzer$(EXE):	$(TOP)/src/tclsqlite.c sqlite3.c $(TESTSRC) \
			$(TOP)/tool/spaceanal.tcl
	sed \
	  -e '/^#/d' \
	  -e 's,\\,\\\\,g' \
	  -e 's,",\\",g' \
	  -e 's,^,",' \
	  -e 's,$$,\\n",' \
	  $(TOP)/tool/spaceanal.tcl >spaceanal_tcl.h
	$(TCCX) $(TCL_FLAGS)                  $(TESTFIXTURE_FLAGS)                                 \
		-DTCLSH=2 -DSQLITE_TEST=1 -DSQLITE_DEBUG=1 -DSQLITE_PRIVATE="" \
		$(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c                    \
		-o sqlite3_analyzer$(EXE)                                      \
		$(LIBTCL) $(THREADLIB)

TEST_EXTENSION = $(SHPREFIX)testloadext.$(SO)
$(TEST_EXTENSION): $(TOP)/src/test_loadext.c
	$(MKSHLIB) $(TOP)/src/test_loadext.c -o $(TEST_EXTENSION)

extensiontest: testfixture$(EXE) $(TEST_EXTENSION)
	./testfixture$(EXE) $(TOP)/test/loadext.test

clean:	
	rm -f *.o sqlite3$(EXE) libsqlite3.a sqlite3.h opcodes.*
	rm -f lemon lempar.c parse.* sqlite*.tar.gz mkkeywordhash keywordhash.h
	rm -f $(PUBLISH)
	rm -f *.da *.bb *.bbg gmon.out
	rm -rf tsrc target_source
	rm -f testloadext.dll libtestloadext.so
	rm -f sqlite3.c fts?amal.c tclsqlite3.c
	rm -f $(SHPREFIX)sqlite3.$(SO)

Added README.















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
This directory contains source code to 

    SQLite: An Embeddable SQL Database Engine

To compile the project, first create a directory in which to place
the build products.  It is recommended, but not required, that the
build directory be separate from the source directory.  Cd into the
build directory and then from the build directory run the configure
script found at the root of the source tree.  Then run "make".

For example:

    tar xzf sqlite.tar.gz    ;#  Unpack the source tree into "sqlite"
    mkdir bld                ;#  Build will occur in a sibling directory
    cd bld                   ;#  Change to the build directory
    ../sqlite/configure      ;#  Run the configure script
    make                     ;#  Run the makefile.
    make install             ;#  (Optional) Install the build products

The configure script uses autoconf 2.61 and libtool.  If the configure
script does not work out for you, there is a generic makefile named
"Makefile.linux-gcc" in the top directory of the source tree that you
can copy and edit to suit your needs.  Comments on the generic makefile
show what changes are needed.

The linux binaries on the website are created using the generic makefile,
not the configure script.  The windows binaries on the website are created
using MinGW32 configured as a cross-compiler running under Linux.  For 
details, see the ./publish.sh script at the top-level of the source tree.
The developers do not use teh configure script.

SQLite does not require TCL to run, but a TCL installation is required
by the makefiles.  SQLite contains a lot of generated code and TCL is
used to do much of that code generation.  The makefile also requires
AWK.

Contacts:

   http://www.sqlite.org/

Added VERSION.



>
1
3.6.20

Added aclocal.m4.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
# generated automatically by aclocal 1.10.2 -*- Autoconf -*-

# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
# 2005, 2006, 2007, 2008  Free Software Foundation, Inc.
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.

# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
#
#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
#                 2006, 2007, 2008 Free Software Foundation, Inc.
#   Written by Gordon Matzigkeit, 1996
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.

m4_define([_LT_COPYING], [dnl
#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
#                 2006, 2007, 2008 Free Software Foundation, Inc.
#   Written by Gordon Matzigkeit, 1996
#
#   This file is part of GNU Libtool.
#
# GNU Libtool is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# As a special exception to the GNU General Public License,
# if you distribute this file as part of a program or library that
# is built using GNU Libtool, you may include this file under the
# same distribution terms that you use for the rest of that program.
#
# GNU Libtool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Libtool; see the file COPYING.  If not, a copy
# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
# obtained by writing to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
])

# serial 56 LT_INIT


# LT_PREREQ(VERSION)
# ------------------
# Complain and exit if this libtool version is less that VERSION.
m4_defun([LT_PREREQ],
[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
       [m4_default([$3],
		   [m4_fatal([Libtool version $1 or higher is required],
		             63)])],
       [$2])])


# _LT_CHECK_BUILDDIR
# ------------------
# Complain if the absolute build directory name contains unusual characters
m4_defun([_LT_CHECK_BUILDDIR],
[case `pwd` in
  *\ * | *\	*)
    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
esac
])


# LT_INIT([OPTIONS])
# ------------------
AC_DEFUN([LT_INIT],
[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
AC_BEFORE([$0], [LT_LANG])dnl
AC_BEFORE([$0], [LT_OUTPUT])dnl
AC_BEFORE([$0], [LTDL_INIT])dnl
m4_require([_LT_CHECK_BUILDDIR])dnl

dnl Autoconf doesn't catch unexpanded LT_ macros by default:
m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
dnl unless we require an AC_DEFUNed macro:
AC_REQUIRE([LTOPTIONS_VERSION])dnl
AC_REQUIRE([LTSUGAR_VERSION])dnl
AC_REQUIRE([LTVERSION_VERSION])dnl
AC_REQUIRE([LTOBSOLETE_VERSION])dnl
m4_require([_LT_PROG_LTMAIN])dnl

dnl Parse OPTIONS
_LT_SET_OPTIONS([$0], [$1])

# This can be used to rebuild libtool when needed
LIBTOOL_DEPS="$ltmain"

# Always use our own libtool.
LIBTOOL='$(SHELL) $(top_builddir)/libtool'
AC_SUBST(LIBTOOL)dnl

_LT_SETUP

# Only expand once:
m4_define([LT_INIT])
])# LT_INIT

# Old names:
AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
dnl AC_DEFUN([AM_PROG_LIBTOOL], [])


# _LT_CC_BASENAME(CC)
# -------------------
# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
m4_defun([_LT_CC_BASENAME],
[for cc_temp in $1""; do
  case $cc_temp in
    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
    \-*) ;;
    *) break;;
  esac
done
cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
])


# _LT_FILEUTILS_DEFAULTS
# ----------------------
# It is okay to use these file commands and assume they have been set
# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
m4_defun([_LT_FILEUTILS_DEFAULTS],
[: ${CP="cp -f"}
: ${MV="mv -f"}
: ${RM="rm -f"}
])# _LT_FILEUTILS_DEFAULTS


# _LT_SETUP
# ---------
m4_defun([_LT_SETUP],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
AC_REQUIRE([AC_CANONICAL_BUILD])dnl
_LT_DECL([], [host_alias], [0], [The host system])dnl
_LT_DECL([], [host], [0])dnl
_LT_DECL([], [host_os], [0])dnl
dnl
_LT_DECL([], [build_alias], [0], [The build system])dnl
_LT_DECL([], [build], [0])dnl
_LT_DECL([], [build_os], [0])dnl
dnl
AC_REQUIRE([AC_PROG_CC])dnl
AC_REQUIRE([LT_PATH_LD])dnl
AC_REQUIRE([LT_PATH_NM])dnl
dnl
AC_REQUIRE([AC_PROG_LN_S])dnl
test -z "$LN_S" && LN_S="ln -s"
_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
dnl
AC_REQUIRE([LT_CMD_MAX_LEN])dnl
_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
dnl
m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_CHECK_SHELL_FEATURES])dnl
m4_require([_LT_CMD_RELOAD])dnl
m4_require([_LT_CHECK_MAGIC_METHOD])dnl
m4_require([_LT_CMD_OLD_ARCHIVE])dnl
m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl

_LT_CONFIG_LIBTOOL_INIT([
# See if we are running on zsh, and set the options which allow our
# commands through without removal of \ escapes INIT.
if test -n "\${ZSH_VERSION+set}" ; then
   setopt NO_GLOB_SUBST
fi
])
if test -n "${ZSH_VERSION+set}" ; then
   setopt NO_GLOB_SUBST
fi

_LT_CHECK_OBJDIR

m4_require([_LT_TAG_COMPILER])dnl
_LT_PROG_ECHO_BACKSLASH

case $host_os in
aix3*)
  # AIX sometimes has problems with the GCC collect2 program.  For some
  # reason, if we set the COLLECT_NAMES environment variable, the problems
  # vanish in a puff of smoke.
  if test "X${COLLECT_NAMES+set}" != Xset; then
    COLLECT_NAMES=
    export COLLECT_NAMES
  fi
  ;;
esac

# Sed substitution that helps us do robust quoting.  It backslashifies
# metacharacters that are still active within double-quoted strings.
sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'

# Same as above, but do not quote variable references.
double_quote_subst='s/\([["`\\]]\)/\\\1/g'

# Sed substitution to delay expansion of an escaped shell variable in a
# double_quote_subst'ed string.
delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'

# Sed substitution to delay expansion of an escaped single quote.
delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'

# Sed substitution to avoid accidental globbing in evaled expressions
no_glob_subst='s/\*/\\\*/g'

# Global variables:
ofile=libtool
can_build_shared=yes

# All known linkers require a `.a' archive for static linking (except MSVC,
# which needs '.lib').
libext=a

with_gnu_ld="$lt_cv_prog_gnu_ld"

old_CC="$CC"
old_CFLAGS="$CFLAGS"

# Set sane defaults for various variables
test -z "$CC" && CC=cc
test -z "$LTCC" && LTCC=$CC
test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
test -z "$LD" && LD=ld
test -z "$ac_objext" && ac_objext=o

_LT_CC_BASENAME([$compiler])

# Only perform the check for file, if the check method requires it
test -z "$MAGIC_CMD" && MAGIC_CMD=file
case $deplibs_check_method in
file_magic*)
  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
    _LT_PATH_MAGIC
  fi
  ;;
esac

# Use C for the default configuration in the libtool script
LT_SUPPORTED_TAG([CC])
_LT_LANG_C_CONFIG
_LT_LANG_DEFAULT_CONFIG
_LT_CONFIG_COMMANDS
])# _LT_SETUP


# _LT_PROG_LTMAIN
# ---------------
# Note that this code is called both from `configure', and `config.status'
# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
# `config.status' has no value for ac_aux_dir unless we are using Automake,
# so we pass a copy along to make sure it has a sensible value anyway.
m4_defun([_LT_PROG_LTMAIN],
[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
ltmain="$ac_aux_dir/ltmain.sh"
])# _LT_PROG_LTMAIN



# So that we can recreate a full libtool script including additional
# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
# in macros and then make a single call at the end using the `libtool'
# label.


# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
# ----------------------------------------
# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
m4_define([_LT_CONFIG_LIBTOOL_INIT],
[m4_ifval([$1],
          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
                     [$1
])])])

# Initialize.
m4_define([_LT_OUTPUT_LIBTOOL_INIT])


# _LT_CONFIG_LIBTOOL([COMMANDS])
# ------------------------------
# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
m4_define([_LT_CONFIG_LIBTOOL],
[m4_ifval([$1],
          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
                     [$1
])])])

# Initialize.
m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])


# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
# -----------------------------------------------------
m4_defun([_LT_CONFIG_SAVE_COMMANDS],
[_LT_CONFIG_LIBTOOL([$1])
_LT_CONFIG_LIBTOOL_INIT([$2])
])


# _LT_FORMAT_COMMENT([COMMENT])
# -----------------------------
# Add leading comment marks to the start of each line, and a trailing
# full-stop to the whole comment if one is not present already.
m4_define([_LT_FORMAT_COMMENT],
[m4_ifval([$1], [
m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
)])





# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
# -------------------------------------------------------------------
# CONFIGNAME is the name given to the value in the libtool script.
# VARNAME is the (base) name used in the configure script.
# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
# VARNAME.  Any other value will be used directly.
m4_define([_LT_DECL],
[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
	[m4_ifval([$1], [$1], [$2])])
    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
    m4_ifval([$4],
	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
    lt_dict_add_subkey([lt_decl_dict], [$2],
	[tagged?], [m4_ifval([$5], [yes], [no])])])
])


# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
# --------------------------------------------------------
m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])


# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
# ------------------------------------------------
m4_define([lt_decl_tag_varnames],
[_lt_decl_filter([tagged?], [yes], $@)])


# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
# ---------------------------------------------------------
m4_define([_lt_decl_filter],
[m4_case([$#],
  [0], [m4_fatal([$0: too few arguments: $#])],
  [1], [m4_fatal([$0: too few arguments: $#: $1])],
  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
])


# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
# --------------------------------------------------
m4_define([lt_decl_quote_varnames],
[_lt_decl_filter([value], [1], $@)])


# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
# ---------------------------------------------------
m4_define([lt_decl_dquote_varnames],
[_lt_decl_filter([value], [2], $@)])


# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
# ---------------------------------------------------
m4_define([lt_decl_varnames_tagged],
[m4_assert([$# <= 2])dnl
_$0(m4_quote(m4_default([$1], [[, ]])),
    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
m4_define([_lt_decl_varnames_tagged],
[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])


# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
# ------------------------------------------------
m4_define([lt_decl_all_varnames],
[_$0(m4_quote(m4_default([$1], [[, ]])),
     m4_if([$2], [],
	   m4_quote(lt_decl_varnames),
	m4_quote(m4_shift($@))))[]dnl
])
m4_define([_lt_decl_all_varnames],
[lt_join($@, lt_decl_varnames_tagged([$1],
			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
])


# _LT_CONFIG_STATUS_DECLARE([VARNAME])
# ------------------------------------
# Quote a variable value, and forward it to `config.status' so that its
# declaration there will have the same value as in `configure'.  VARNAME
# must have a single quote delimited value for this to work.
m4_define([_LT_CONFIG_STATUS_DECLARE],
[$1='`$ECHO "X$][$1" | $Xsed -e "$delay_single_quote_subst"`'])


# _LT_CONFIG_STATUS_DECLARATIONS
# ------------------------------
# We delimit libtool config variables with single quotes, so when
# we write them to config.status, we have to be sure to quote all
# embedded single quotes properly.  In configure, this macro expands
# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
#
#    <var>='`$ECHO "X$<var>" | $Xsed -e "$delay_single_quote_subst"`'
m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])


# _LT_LIBTOOL_TAGS
# ----------------
# Output comment and list of tags supported by the script
m4_defun([_LT_LIBTOOL_TAGS],
[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
available_tags="_LT_TAGS"dnl
])


# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
# -----------------------------------
# Extract the dictionary values for VARNAME (optionally with TAG) and
# expand to a commented shell variable setting:
#
#    # Some comment about what VAR is for.
#    visible_name=$lt_internal_name
m4_define([_LT_LIBTOOL_DECLARE],
[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
					   [description])))[]dnl
m4_pushdef([_libtool_name],
    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
    [0], [_libtool_name=[$]$1],
    [1], [_libtool_name=$lt_[]$1],
    [2], [_libtool_name=$lt_[]$1],
    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
])


# _LT_LIBTOOL_CONFIG_VARS
# -----------------------
# Produce commented declarations of non-tagged libtool config variables
# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
# section) are produced by _LT_LIBTOOL_TAG_VARS.
m4_defun([_LT_LIBTOOL_CONFIG_VARS],
[m4_foreach([_lt_var],
    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])


# _LT_LIBTOOL_TAG_VARS(TAG)
# -------------------------
m4_define([_LT_LIBTOOL_TAG_VARS],
[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])


# _LT_TAGVAR(VARNAME, [TAGNAME])
# ------------------------------
m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])


# _LT_CONFIG_COMMANDS
# -------------------
# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
# variables for single and double quote escaping we saved from calls
# to _LT_DECL, we can put quote escaped variables declarations
# into `config.status', and then the shell code to quote escape them in
# for loops in `config.status'.  Finally, any additional code accumulated
# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
m4_defun([_LT_CONFIG_COMMANDS],
[AC_PROVIDE_IFELSE([LT_OUTPUT],
	dnl If the libtool generation code has been placed in $CONFIG_LT,
	dnl instead of duplicating it all over again into config.status,
	dnl then we will have config.status run $CONFIG_LT later, so it
	dnl needs to know what name is stored there:
        [AC_CONFIG_COMMANDS([libtool],
            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
    dnl If the libtool generation code is destined for config.status,
    dnl expand the accumulated commands and init code now:
    [AC_CONFIG_COMMANDS([libtool],
        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
])#_LT_CONFIG_COMMANDS


# Initialize.
m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
[

# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH

sed_quote_subst='$sed_quote_subst'
double_quote_subst='$double_quote_subst'
delay_variable_subst='$delay_variable_subst'
_LT_CONFIG_STATUS_DECLARATIONS
LTCC='$LTCC'
LTCFLAGS='$LTCFLAGS'
compiler='$compiler_DEFAULT'

# Quote evaled strings.
for var in lt_decl_all_varnames([[ \
]], lt_decl_quote_varnames); do
    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
    *[[\\\\\\\`\\"\\\$]]*)
      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
      ;;
    *)
      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
      ;;
    esac
done

# Double-quote double-evaled strings.
for var in lt_decl_all_varnames([[ \
]], lt_decl_dquote_varnames); do
    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
    *[[\\\\\\\`\\"\\\$]]*)
      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
      ;;
    *)
      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
      ;;
    esac
done

# Fix-up fallback echo if it was mangled by the above quoting rules.
case \$lt_ECHO in
*'\\\[$]0 --fallback-echo"')dnl "
  lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\[$]0 --fallback-echo"\[$]/\[$]0 --fallback-echo"/'\`
  ;;
esac

_LT_OUTPUT_LIBTOOL_INIT
])


# LT_OUTPUT
# ---------
# This macro allows early generation of the libtool script (before
# AC_OUTPUT is called), incase it is used in configure for compilation
# tests.
AC_DEFUN([LT_OUTPUT],
[: ${CONFIG_LT=./config.lt}
AC_MSG_NOTICE([creating $CONFIG_LT])
cat >"$CONFIG_LT" <<_LTEOF
#! $SHELL
# Generated by $as_me.
# Run this file to recreate a libtool stub with the current configuration.

lt_cl_silent=false
SHELL=\${CONFIG_SHELL-$SHELL}
_LTEOF

cat >>"$CONFIG_LT" <<\_LTEOF
AS_SHELL_SANITIZE
_AS_PREPARE

exec AS_MESSAGE_FD>&1
exec AS_MESSAGE_LOG_FD>>config.log
{
  echo
  AS_BOX([Running $as_me.])
} >&AS_MESSAGE_LOG_FD

lt_cl_help="\
\`$as_me' creates a local libtool stub from the current configuration,
for use in further configure time tests before the real libtool is
generated.

Usage: $[0] [[OPTIONS]]

  -h, --help      print this help, then exit
  -V, --version   print version number, then exit
  -q, --quiet     do not print progress messages
  -d, --debug     don't remove temporary files

Report bugs to <bug-libtool@gnu.org>."

lt_cl_version="\
m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
configured by $[0], generated by m4_PACKAGE_STRING.

Copyright (C) 2008 Free Software Foundation, Inc.
This config.lt script is free software; the Free Software Foundation
gives unlimited permision to copy, distribute and modify it."

while test $[#] != 0
do
  case $[1] in
    --version | --v* | -V )
      echo "$lt_cl_version"; exit 0 ;;
    --help | --h* | -h )
      echo "$lt_cl_help"; exit 0 ;;
    --debug | --d* | -d )
      debug=: ;;
    --quiet | --q* | --silent | --s* | -q )
      lt_cl_silent=: ;;

    -*) AC_MSG_ERROR([unrecognized option: $[1]
Try \`$[0] --help' for more information.]) ;;

    *) AC_MSG_ERROR([unrecognized argument: $[1]
Try \`$[0] --help' for more information.]) ;;
  esac
  shift
done

if $lt_cl_silent; then
  exec AS_MESSAGE_FD>/dev/null
fi
_LTEOF

cat >>"$CONFIG_LT" <<_LTEOF
_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
_LTEOF

cat >>"$CONFIG_LT" <<\_LTEOF
AC_MSG_NOTICE([creating $ofile])
_LT_OUTPUT_LIBTOOL_COMMANDS
AS_EXIT(0)
_LTEOF
chmod +x "$CONFIG_LT"

# configure is writing to config.log, but config.lt does its own redirection,
# appending to config.log, which fails on DOS, as config.log is still kept
# open by configure.  Here we exec the FD to /dev/null, effectively closing
# config.log, so it can be properly (re)opened and appended to by config.lt.
if test "$no_create" != yes; then
  lt_cl_success=:
  test "$silent" = yes &&
    lt_config_lt_args="$lt_config_lt_args --quiet"
  exec AS_MESSAGE_LOG_FD>/dev/null
  $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
  exec AS_MESSAGE_LOG_FD>>config.log
  $lt_cl_success || AS_EXIT(1)
fi
])# LT_OUTPUT


# _LT_CONFIG(TAG)
# ---------------
# If TAG is the built-in tag, create an initial libtool script with a
# default configuration from the untagged config vars.  Otherwise add code
# to config.status for appending the configuration named by TAG from the
# matching tagged config vars.
m4_defun([_LT_CONFIG],
[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
_LT_CONFIG_SAVE_COMMANDS([
  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
  m4_if(_LT_TAG, [C], [
    # See if we are running on zsh, and set the options which allow our
    # commands through without removal of \ escapes.
    if test -n "${ZSH_VERSION+set}" ; then
      setopt NO_GLOB_SUBST
    fi

    cfgfile="${ofile}T"
    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
    $RM "$cfgfile"

    cat <<_LT_EOF >> "$cfgfile"
#! $SHELL

# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
# NOTE: Changes made to this file will be lost: look at ltmain.sh.
#
_LT_COPYING
_LT_LIBTOOL_TAGS

# ### BEGIN LIBTOOL CONFIG
_LT_LIBTOOL_CONFIG_VARS
_LT_LIBTOOL_TAG_VARS
# ### END LIBTOOL CONFIG

_LT_EOF

  case $host_os in
  aix3*)
    cat <<\_LT_EOF >> "$cfgfile"
# AIX sometimes has problems with the GCC collect2 program.  For some
# reason, if we set the COLLECT_NAMES environment variable, the problems
# vanish in a puff of smoke.
if test "X${COLLECT_NAMES+set}" != Xset; then
  COLLECT_NAMES=
  export COLLECT_NAMES
fi
_LT_EOF
    ;;
  esac

  _LT_PROG_LTMAIN

  # We use sed instead of cat because bash on DJGPP gets confused if
  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
  # text mode, it properly converts lines to CR/LF.  This bash problem
  # is reportedly fixed, but why not run on old versions too?
  sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \
    || (rm -f "$cfgfile"; exit 1)

  _LT_PROG_XSI_SHELLFNS

  sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \
    || (rm -f "$cfgfile"; exit 1)

  mv -f "$cfgfile" "$ofile" ||
    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
  chmod +x "$ofile"
],
[cat <<_LT_EOF >> "$ofile"

dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
dnl in a comment (ie after a #).
# ### BEGIN LIBTOOL TAG CONFIG: $1
_LT_LIBTOOL_TAG_VARS(_LT_TAG)
# ### END LIBTOOL TAG CONFIG: $1
_LT_EOF
])dnl /m4_if
],
[m4_if([$1], [], [
    PACKAGE='$PACKAGE'
    VERSION='$VERSION'
    TIMESTAMP='$TIMESTAMP'
    RM='$RM'
    ofile='$ofile'], [])
])dnl /_LT_CONFIG_SAVE_COMMANDS
])# _LT_CONFIG


# LT_SUPPORTED_TAG(TAG)
# ---------------------
# Trace this macro to discover what tags are supported by the libtool
# --tag option, using:
#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
AC_DEFUN([LT_SUPPORTED_TAG], [])


# C support is built-in for now
m4_define([_LT_LANG_C_enabled], [])
m4_define([_LT_TAGS], [])


# LT_LANG(LANG)
# -------------
# Enable libtool support for the given language if not already enabled.
AC_DEFUN([LT_LANG],
[AC_BEFORE([$0], [LT_OUTPUT])dnl
m4_case([$1],
  [C],			[_LT_LANG(C)],
  [C++],		[_LT_LANG(CXX)],
  [Java],		[_LT_LANG(GCJ)],
  [Fortran 77],		[_LT_LANG(F77)],
  [Fortran],		[_LT_LANG(FC)],
  [Windows Resource],	[_LT_LANG(RC)],
  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
    [_LT_LANG($1)],
    [m4_fatal([$0: unsupported language: "$1"])])])dnl
])# LT_LANG


# _LT_LANG(LANGNAME)
# ------------------
m4_defun([_LT_LANG],
[m4_ifdef([_LT_LANG_]$1[_enabled], [],
  [LT_SUPPORTED_TAG([$1])dnl
  m4_append([_LT_TAGS], [$1 ])dnl
  m4_define([_LT_LANG_]$1[_enabled], [])dnl
  _LT_LANG_$1_CONFIG($1)])dnl
])# _LT_LANG


# _LT_LANG_DEFAULT_CONFIG
# -----------------------
m4_defun([_LT_LANG_DEFAULT_CONFIG],
[AC_PROVIDE_IFELSE([AC_PROG_CXX],
  [LT_LANG(CXX)],
  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])

AC_PROVIDE_IFELSE([AC_PROG_F77],
  [LT_LANG(F77)],
  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])

AC_PROVIDE_IFELSE([AC_PROG_FC],
  [LT_LANG(FC)],
  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])

dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
dnl pulling things in needlessly.
AC_PROVIDE_IFELSE([AC_PROG_GCJ],
  [LT_LANG(GCJ)],
  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
    [LT_LANG(GCJ)],
    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
      [LT_LANG(GCJ)],
      [m4_ifdef([AC_PROG_GCJ],
	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
       m4_ifdef([A][M_PROG_GCJ],
	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
       m4_ifdef([LT_PROG_GCJ],
	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])

AC_PROVIDE_IFELSE([LT_PROG_RC],
  [LT_LANG(RC)],
  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
])# _LT_LANG_DEFAULT_CONFIG

# Obsolete macros:
AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
dnl AC_DEFUN([AC_LIBTOOL_F77], [])
dnl AC_DEFUN([AC_LIBTOOL_FC], [])
dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])


# _LT_TAG_COMPILER
# ----------------
m4_defun([_LT_TAG_COMPILER],
[AC_REQUIRE([AC_PROG_CC])dnl

_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl

# If no C compiler was specified, use CC.
LTCC=${LTCC-"$CC"}

# If no C compiler flags were specified, use CFLAGS.
LTCFLAGS=${LTCFLAGS-"$CFLAGS"}

# Allow CC to be a program name with arguments.
compiler=$CC
])# _LT_TAG_COMPILER


# _LT_COMPILER_BOILERPLATE
# ------------------------
# Check for compiler boilerplate output or warnings with
# the simple compiler test code.
m4_defun([_LT_COMPILER_BOILERPLATE],
[m4_require([_LT_DECL_SED])dnl
ac_outfile=conftest.$ac_objext
echo "$lt_simple_compile_test_code" >conftest.$ac_ext
eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
_lt_compiler_boilerplate=`cat conftest.err`
$RM conftest*
])# _LT_COMPILER_BOILERPLATE


# _LT_LINKER_BOILERPLATE
# ----------------------
# Check for linker boilerplate output or warnings with
# the simple link test code.
m4_defun([_LT_LINKER_BOILERPLATE],
[m4_require([_LT_DECL_SED])dnl
ac_outfile=conftest.$ac_objext
echo "$lt_simple_link_test_code" >conftest.$ac_ext
eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
_lt_linker_boilerplate=`cat conftest.err`
$RM -r conftest*
])# _LT_LINKER_BOILERPLATE

# _LT_REQUIRED_DARWIN_CHECKS
# -------------------------
m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
  case $host_os in
    rhapsody* | darwin*)
    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
    AC_CHECK_TOOL([LIPO], [lipo], [:])
    AC_CHECK_TOOL([OTOOL], [otool], [:])
    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
    _LT_DECL([], [DSYMUTIL], [1],
      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
    _LT_DECL([], [NMEDIT], [1],
      [Tool to change global to local symbols on Mac OS X])
    _LT_DECL([], [LIPO], [1],
      [Tool to manipulate fat objects and archives on Mac OS X])
    _LT_DECL([], [OTOOL], [1],
      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
    _LT_DECL([], [OTOOL64], [1],
      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])

    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
      [lt_cv_apple_cc_single_mod=no
      if test -z "${LT_MULTI_MODULE}"; then
	# By default we will add the -single_module flag. You can override
	# by either setting the environment variable LT_MULTI_MODULE
	# non-empty at configure time, or by adding -multi_module to the
	# link flags.
	rm -rf libconftest.dylib*
	echo "int foo(void){return 1;}" > conftest.c
	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
        _lt_result=$?
	if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then
	  lt_cv_apple_cc_single_mod=yes
	else
	  cat conftest.err >&AS_MESSAGE_LOG_FD
	fi
	rm -rf libconftest.dylib*
	rm -f conftest.*
      fi])
    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
      [lt_cv_ld_exported_symbols_list],
      [lt_cv_ld_exported_symbols_list=no
      save_LDFLAGS=$LDFLAGS
      echo "_main" > conftest.sym
      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
	[lt_cv_ld_exported_symbols_list=yes],
	[lt_cv_ld_exported_symbols_list=no])
	LDFLAGS="$save_LDFLAGS"
    ])
    case $host_os in
    rhapsody* | darwin1.[[012]])
      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
    darwin1.*)
      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
    darwin*) # darwin 5.x on
      # if running on 10.5 or later, the deployment target defaults
      # to the OS version, if on x86, and 10.4, the deployment
      # target defaults to 10.4. Don't you love it?
      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
	10.[[012]]*)
	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
	10.*)
	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
      esac
    ;;
  esac
    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
      _lt_dar_single_mod='$single_module'
    fi
    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
    else
      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
    fi
    if test "$DSYMUTIL" != ":"; then
      _lt_dsymutil='~$DSYMUTIL $lib || :'
    else
      _lt_dsymutil=
    fi
    ;;
  esac
])


# _LT_DARWIN_LINKER_FEATURES
# --------------------------
# Checks for linker and compiler features on darwin
m4_defun([_LT_DARWIN_LINKER_FEATURES],
[
  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
  _LT_TAGVAR(hardcode_direct, $1)=no
  _LT_TAGVAR(hardcode_automatic, $1)=yes
  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
  _LT_TAGVAR(whole_archive_flag_spec, $1)=''
  _LT_TAGVAR(link_all_deplibs, $1)=yes
  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
  case $cc_basename in
     ifort*) _lt_dar_can_shared=yes ;;
     *) _lt_dar_can_shared=$GCC ;;
  esac
  if test "$_lt_dar_can_shared" = "yes"; then
    output_verbose_link_cmd=echo
    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
    m4_if([$1], [CXX],
[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
    fi
],[])
  else
  _LT_TAGVAR(ld_shlibs, $1)=no
  fi
])

# _LT_SYS_MODULE_PATH_AIX
# -----------------------
# Links a minimal program and checks the executable
# for the system default hardcoded library path. In most cases,
# this is /usr/lib:/lib, but when the MPI compilers are used
# the location of the communication and MPI libs are included too.
# If we don't find anything, use the default library path according
# to the aix ld manual.
m4_defun([_LT_SYS_MODULE_PATH_AIX],
[m4_require([_LT_DECL_SED])dnl
AC_LINK_IFELSE(AC_LANG_PROGRAM,[
lt_aix_libpath_sed='
    /Import File Strings/,/^$/ {
	/^0/ {
	    s/^0  *\(.*\)$/\1/
	    p
	}
    }'
aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
# Check for a 64-bit object if we didn't find anything.
if test -z "$aix_libpath"; then
  aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
fi],[])
if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
])# _LT_SYS_MODULE_PATH_AIX


# _LT_SHELL_INIT(ARG)
# -------------------
m4_define([_LT_SHELL_INIT],
[ifdef([AC_DIVERSION_NOTICE],
	     [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
	 [AC_DIVERT_PUSH(NOTICE)])
$1
AC_DIVERT_POP
])# _LT_SHELL_INIT


# _LT_PROG_ECHO_BACKSLASH
# -----------------------
# Add some code to the start of the generated configure script which
# will find an echo command which doesn't interpret backslashes.
m4_defun([_LT_PROG_ECHO_BACKSLASH],
[_LT_SHELL_INIT([
# Check that we are running under the correct shell.
SHELL=${CONFIG_SHELL-/bin/sh}

case X$lt_ECHO in
X*--fallback-echo)
  # Remove one level of quotation (which was required for Make).
  ECHO=`echo "$lt_ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
  ;;
esac

ECHO=${lt_ECHO-echo}
if test "X[$]1" = X--no-reexec; then
  # Discard the --no-reexec flag, and continue.
  shift
elif test "X[$]1" = X--fallback-echo; then
  # Avoid inline document here, it may be left over
  :
elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then
  # Yippee, $ECHO works!
  :
else
  # Restart under the correct shell.
  exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
fi

if test "X[$]1" = X--fallback-echo; then
  # used as fallback echo
  shift
  cat <<_LT_EOF
[$]*
_LT_EOF
  exit 0
fi

# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH

if test -z "$lt_ECHO"; then
  if test "X${echo_test_string+set}" != Xset; then
    # find a string as large as possible, as long as the shell can cope with it
    for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
      # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
      if { echo_test_string=`eval $cmd`; } 2>/dev/null &&
	 { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null
      then
        break
      fi
    done
  fi

  if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
     echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
     test "X$echo_testing_string" = "X$echo_test_string"; then
    :
  else
    # The Solaris, AIX, and Digital Unix default echo programs unquote
    # backslashes.  This makes it impossible to quote backslashes using
    #   echo "$something" | sed 's/\\/\\\\/g'
    #
    # So, first we look for a working echo in the user's PATH.

    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
    for dir in $PATH /usr/ucb; do
      IFS="$lt_save_ifs"
      if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
         test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
         echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
         test "X$echo_testing_string" = "X$echo_test_string"; then
        ECHO="$dir/echo"
        break
      fi
    done
    IFS="$lt_save_ifs"

    if test "X$ECHO" = Xecho; then
      # We didn't find a better echo, so look for alternatives.
      if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' &&
         echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` &&
         test "X$echo_testing_string" = "X$echo_test_string"; then
        # This shell has a builtin print -r that does the trick.
        ECHO='print -r'
      elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } &&
	   test "X$CONFIG_SHELL" != X/bin/ksh; then
        # If we have ksh, try running configure again with it.
        ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
        export ORIGINAL_CONFIG_SHELL
        CONFIG_SHELL=/bin/ksh
        export CONFIG_SHELL
        exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
      else
        # Try using printf.
        ECHO='printf %s\n'
        if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
	   echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
	   test "X$echo_testing_string" = "X$echo_test_string"; then
	  # Cool, printf works
	  :
        elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
	     test "X$echo_testing_string" = 'X\t' &&
	     echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
	     test "X$echo_testing_string" = "X$echo_test_string"; then
	  CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
	  export CONFIG_SHELL
	  SHELL="$CONFIG_SHELL"
	  export SHELL
	  ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
        elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
	     test "X$echo_testing_string" = 'X\t' &&
	     echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
	     test "X$echo_testing_string" = "X$echo_test_string"; then
	  ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
        else
	  # maybe with a smaller string...
	  prev=:

	  for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do
	    if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null
	    then
	      break
	    fi
	    prev="$cmd"
	  done

	  if test "$prev" != 'sed 50q "[$]0"'; then
	    echo_test_string=`eval $prev`
	    export echo_test_string
	    exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
	  else
	    # Oops.  We lost completely, so just stick with echo.
	    ECHO=echo
	  fi
        fi
      fi
    fi
  fi
fi

# Copy echo and quote the copy suitably for passing to libtool from
# the Makefile, instead of quoting the original, which is used later.
lt_ECHO=$ECHO
if test "X$lt_ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then
   lt_ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
fi

AC_SUBST(lt_ECHO)
])
_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
_LT_DECL([], [ECHO], [1],
    [An echo program that does not interpret backslashes])
])# _LT_PROG_ECHO_BACKSLASH


# _LT_ENABLE_LOCK
# ---------------
m4_defun([_LT_ENABLE_LOCK],
[AC_ARG_ENABLE([libtool-lock],
  [AS_HELP_STRING([--disable-libtool-lock],
    [avoid locking (might break parallel builds)])])
test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes

# Some flags need to be propagated to the compiler or linker for good
# libtool support.
case $host in
ia64-*-hpux*)
  # Find out which ABI we are using.
  echo 'int i;' > conftest.$ac_ext
  if AC_TRY_EVAL(ac_compile); then
    case `/usr/bin/file conftest.$ac_objext` in
      *ELF-32*)
	HPUX_IA64_MODE="32"
	;;
      *ELF-64*)
	HPUX_IA64_MODE="64"
	;;
    esac
  fi
  rm -rf conftest*
  ;;
*-*-irix6*)
  # Find out which ABI we are using.
  echo '[#]line __oline__ "configure"' > conftest.$ac_ext
  if AC_TRY_EVAL(ac_compile); then
    if test "$lt_cv_prog_gnu_ld" = yes; then
      case `/usr/bin/file conftest.$ac_objext` in
	*32-bit*)
	  LD="${LD-ld} -melf32bsmip"
	  ;;
	*N32*)
	  LD="${LD-ld} -melf32bmipn32"
	  ;;
	*64-bit*)
	  LD="${LD-ld} -melf64bmip"
	;;
      esac
    else
      case `/usr/bin/file conftest.$ac_objext` in
	*32-bit*)
	  LD="${LD-ld} -32"
	  ;;
	*N32*)
	  LD="${LD-ld} -n32"
	  ;;
	*64-bit*)
	  LD="${LD-ld} -64"
	  ;;
      esac
    fi
  fi
  rm -rf conftest*
  ;;

x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
  # Find out which ABI we are using.
  echo 'int i;' > conftest.$ac_ext
  if AC_TRY_EVAL(ac_compile); then
    case `/usr/bin/file conftest.o` in
      *32-bit*)
	case $host in
	  x86_64-*kfreebsd*-gnu)
	    LD="${LD-ld} -m elf_i386_fbsd"
	    ;;
	  x86_64-*linux*)
	    LD="${LD-ld} -m elf_i386"
	    ;;
	  ppc64-*linux*|powerpc64-*linux*)
	    LD="${LD-ld} -m elf32ppclinux"
	    ;;
	  s390x-*linux*)
	    LD="${LD-ld} -m elf_s390"
	    ;;
	  sparc64-*linux*)
	    LD="${LD-ld} -m elf32_sparc"
	    ;;
	esac
	;;
      *64-bit*)
	case $host in
	  x86_64-*kfreebsd*-gnu)
	    LD="${LD-ld} -m elf_x86_64_fbsd"
	    ;;
	  x86_64-*linux*)
	    LD="${LD-ld} -m elf_x86_64"
	    ;;
	  ppc*-*linux*|powerpc*-*linux*)
	    LD="${LD-ld} -m elf64ppc"
	    ;;
	  s390*-*linux*|s390*-*tpf*)
	    LD="${LD-ld} -m elf64_s390"
	    ;;
	  sparc*-*linux*)
	    LD="${LD-ld} -m elf64_sparc"
	    ;;
	esac
	;;
    esac
  fi
  rm -rf conftest*
  ;;

*-*-sco3.2v5*)
  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
  SAVE_CFLAGS="$CFLAGS"
  CFLAGS="$CFLAGS -belf"
  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
    [AC_LANG_PUSH(C)
     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
     AC_LANG_POP])
  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
    CFLAGS="$SAVE_CFLAGS"
  fi
  ;;
sparc*-*solaris*)
  # Find out which ABI we are using.
  echo 'int i;' > conftest.$ac_ext
  if AC_TRY_EVAL(ac_compile); then
    case `/usr/bin/file conftest.o` in
    *64-bit*)
      case $lt_cv_prog_gnu_ld in
      yes*) LD="${LD-ld} -m elf64_sparc" ;;
      *)
	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
	  LD="${LD-ld} -64"
	fi
	;;
      esac
      ;;
    esac
  fi
  rm -rf conftest*
  ;;
esac

need_locks="$enable_libtool_lock"
])# _LT_ENABLE_LOCK


# _LT_CMD_OLD_ARCHIVE
# -------------------
m4_defun([_LT_CMD_OLD_ARCHIVE],
[AC_CHECK_TOOL(AR, ar, false)
test -z "$AR" && AR=ar
test -z "$AR_FLAGS" && AR_FLAGS=cru
_LT_DECL([], [AR], [1], [The archiver])
_LT_DECL([], [AR_FLAGS], [1])

AC_CHECK_TOOL(STRIP, strip, :)
test -z "$STRIP" && STRIP=:
_LT_DECL([], [STRIP], [1], [A symbol stripping program])

AC_CHECK_TOOL(RANLIB, ranlib, :)
test -z "$RANLIB" && RANLIB=:
_LT_DECL([], [RANLIB], [1],
    [Commands used to install an old-style archive])

# Determine commands to create old-style static archives.
old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
old_postinstall_cmds='chmod 644 $oldlib'
old_postuninstall_cmds=

if test -n "$RANLIB"; then
  case $host_os in
  openbsd*)
    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
    ;;
  *)
    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
    ;;
  esac
  old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
fi
_LT_DECL([], [old_postinstall_cmds], [2])
_LT_DECL([], [old_postuninstall_cmds], [2])
_LT_TAGDECL([], [old_archive_cmds], [2],
    [Commands used to build an old-style archive])
])# _LT_CMD_OLD_ARCHIVE


# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
# ----------------------------------------------------------------
# Check whether the given compiler option works
AC_DEFUN([_LT_COMPILER_OPTION],
[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_DECL_SED])dnl
AC_CACHE_CHECK([$1], [$2],
  [$2=no
   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
   lt_compiler_flag="$3"
   # Insert the option either (1) after the last *FLAGS variable, or
   # (2) before a word containing "conftest.", or (3) at the end.
   # Note that $ac_compile itself does not contain backslashes and begins
   # with a dollar sign (not a hyphen), so the echo should work correctly.
   # The option is referenced via a variable to avoid confusing sed.
   lt_compile=`echo "$ac_compile" | $SED \
   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
   -e 's:$: $lt_compiler_flag:'`
   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
   (eval "$lt_compile" 2>conftest.err)
   ac_status=$?
   cat conftest.err >&AS_MESSAGE_LOG_FD
   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
   if (exit $ac_status) && test -s "$ac_outfile"; then
     # The compiler can only warn and ignore the option if not recognized
     # So say no if there are warnings other than the usual output.
     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
       $2=yes
     fi
   fi
   $RM conftest*
])

if test x"[$]$2" = xyes; then
    m4_if([$5], , :, [$5])
else
    m4_if([$6], , :, [$6])
fi
])# _LT_COMPILER_OPTION

# Old name:
AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])


# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
#                  [ACTION-SUCCESS], [ACTION-FAILURE])
# ----------------------------------------------------
# Check whether the given linker option works
AC_DEFUN([_LT_LINKER_OPTION],
[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_DECL_SED])dnl
AC_CACHE_CHECK([$1], [$2],
  [$2=no
   save_LDFLAGS="$LDFLAGS"
   LDFLAGS="$LDFLAGS $3"
   echo "$lt_simple_link_test_code" > conftest.$ac_ext
   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
     # The linker can only warn and ignore the option if not recognized
     # So say no if there are warnings
     if test -s conftest.err; then
       # Append any errors to the config.log.
       cat conftest.err 1>&AS_MESSAGE_LOG_FD
       $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
       if diff conftest.exp conftest.er2 >/dev/null; then
         $2=yes
       fi
     else
       $2=yes
     fi
   fi
   $RM -r conftest*
   LDFLAGS="$save_LDFLAGS"
])

if test x"[$]$2" = xyes; then
    m4_if([$4], , :, [$4])
else
    m4_if([$5], , :, [$5])
fi
])# _LT_LINKER_OPTION

# Old name:
AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])


# LT_CMD_MAX_LEN
#---------------
AC_DEFUN([LT_CMD_MAX_LEN],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
# find the maximum length of command line arguments
AC_MSG_CHECKING([the maximum length of command line arguments])
AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
  i=0
  teststring="ABCD"

  case $build_os in
  msdosdjgpp*)
    # On DJGPP, this test can blow up pretty badly due to problems in libc
    # (any single argument exceeding 2000 bytes causes a buffer overrun
    # during glob expansion).  Even if it were fixed, the result of this
    # check would be larger than it should be.
    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
    ;;

  gnu*)
    # Under GNU Hurd, this test is not required because there is
    # no limit to the length of command line arguments.
    # Libtool will interpret -1 as no limit whatsoever
    lt_cv_sys_max_cmd_len=-1;
    ;;

  cygwin* | mingw* | cegcc*)
    # On Win9x/ME, this test blows up -- it succeeds, but takes
    # about 5 minutes as the teststring grows exponentially.
    # Worse, since 9x/ME are not pre-emptively multitasking,
    # you end up with a "frozen" computer, even though with patience
    # the test eventually succeeds (with a max line length of 256k).
    # Instead, let's just punt: use the minimum linelength reported by
    # all of the supported platforms: 8192 (on NT/2K/XP).
    lt_cv_sys_max_cmd_len=8192;
    ;;

  amigaos*)
    # On AmigaOS with pdksh, this test takes hours, literally.
    # So we just punt and use a minimum line length of 8192.
    lt_cv_sys_max_cmd_len=8192;
    ;;

  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
    # This has been around since 386BSD, at least.  Likely further.
    if test -x /sbin/sysctl; then
      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
    elif test -x /usr/sbin/sysctl; then
      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
    else
      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
    fi
    # And add a safety zone
    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
    ;;

  interix*)
    # We know the value 262144 and hardcode it with a safety zone (like BSD)
    lt_cv_sys_max_cmd_len=196608
    ;;

  osf*)
    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
    # nice to cause kernel panics so lets avoid the loop below.
    # First set a reasonable default.
    lt_cv_sys_max_cmd_len=16384
    #
    if test -x /sbin/sysconfig; then
      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
        *1*) lt_cv_sys_max_cmd_len=-1 ;;
      esac
    fi
    ;;
  sco3.2v5*)
    lt_cv_sys_max_cmd_len=102400
    ;;
  sysv5* | sco5v6* | sysv4.2uw2*)
    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
    if test -n "$kargmax"; then
      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
    else
      lt_cv_sys_max_cmd_len=32768
    fi
    ;;
  *)
    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
    if test -n "$lt_cv_sys_max_cmd_len"; then
      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
    else
      # Make teststring a little bigger before we do anything with it.
      # a 1K string should be a reasonable start.
      for i in 1 2 3 4 5 6 7 8 ; do
        teststring=$teststring$teststring
      done
      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
      # If test is not a shell built-in, we'll probably end up computing a
      # maximum length that is only half of the actual maximum length, but
      # we can't tell.
      while { test "X"`$SHELL [$]0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \
	         = "XX$teststring$teststring"; } >/dev/null 2>&1 &&
	      test $i != 17 # 1/2 MB should be enough
      do
        i=`expr $i + 1`
        teststring=$teststring$teststring
      done
      # Only check the string length outside the loop.
      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
      teststring=
      # Add a significant safety factor because C++ compilers can tack on
      # massive amounts of additional arguments before passing them to the
      # linker.  It appears as though 1/2 is a usable value.
      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
    fi
    ;;
  esac
])
if test -n $lt_cv_sys_max_cmd_len ; then
  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
else
  AC_MSG_RESULT(none)
fi
max_cmd_len=$lt_cv_sys_max_cmd_len
_LT_DECL([], [max_cmd_len], [0],
    [What is the maximum length of a command?])
])# LT_CMD_MAX_LEN

# Old name:
AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])


# _LT_HEADER_DLFCN
# ----------------
m4_defun([_LT_HEADER_DLFCN],
[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
])# _LT_HEADER_DLFCN


# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
# ----------------------------------------------------------------
m4_defun([_LT_TRY_DLOPEN_SELF],
[m4_require([_LT_HEADER_DLFCN])dnl
if test "$cross_compiling" = yes; then :
  [$4]
else
  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
  lt_status=$lt_dlunknown
  cat > conftest.$ac_ext <<_LT_EOF
[#line __oline__ "configure"
#include "confdefs.h"

#if HAVE_DLFCN_H
#include <dlfcn.h>
#endif

#include <stdio.h>

#ifdef RTLD_GLOBAL
#  define LT_DLGLOBAL		RTLD_GLOBAL
#else
#  ifdef DL_GLOBAL
#    define LT_DLGLOBAL		DL_GLOBAL
#  else
#    define LT_DLGLOBAL		0
#  endif
#endif

/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
   find out it does not work in some platform. */
#ifndef LT_DLLAZY_OR_NOW
#  ifdef RTLD_LAZY
#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
#  else
#    ifdef DL_LAZY
#      define LT_DLLAZY_OR_NOW		DL_LAZY
#    else
#      ifdef RTLD_NOW
#        define LT_DLLAZY_OR_NOW	RTLD_NOW
#      else
#        ifdef DL_NOW
#          define LT_DLLAZY_OR_NOW	DL_NOW
#        else
#          define LT_DLLAZY_OR_NOW	0
#        endif
#      endif
#    endif
#  endif
#endif

void fnord() { int i=42;}
int main ()
{
  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
  int status = $lt_dlunknown;

  if (self)
    {
      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
      /* dlclose (self); */
    }
  else
    puts (dlerror ());

  return status;
}]
_LT_EOF
  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
    lt_status=$?
    case x$lt_status in
      x$lt_dlno_uscore) $1 ;;
      x$lt_dlneed_uscore) $2 ;;
      x$lt_dlunknown|x*) $3 ;;
    esac
  else :
    # compilation failed
    $3
  fi
fi
rm -fr conftest*
])# _LT_TRY_DLOPEN_SELF


# LT_SYS_DLOPEN_SELF
# ------------------
AC_DEFUN([LT_SYS_DLOPEN_SELF],
[m4_require([_LT_HEADER_DLFCN])dnl
if test "x$enable_dlopen" != xyes; then
  enable_dlopen=unknown
  enable_dlopen_self=unknown
  enable_dlopen_self_static=unknown
else
  lt_cv_dlopen=no
  lt_cv_dlopen_libs=

  case $host_os in
  beos*)
    lt_cv_dlopen="load_add_on"
    lt_cv_dlopen_libs=
    lt_cv_dlopen_self=yes
    ;;

  mingw* | pw32* | cegcc*)
    lt_cv_dlopen="LoadLibrary"
    lt_cv_dlopen_libs=
    ;;

  cygwin*)
    lt_cv_dlopen="dlopen"
    lt_cv_dlopen_libs=
    ;;

  darwin*)
  # if libdl is installed we need to link against it
    AC_CHECK_LIB([dl], [dlopen],
		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
    lt_cv_dlopen="dyld"
    lt_cv_dlopen_libs=
    lt_cv_dlopen_self=yes
    ])
    ;;

  *)
    AC_CHECK_FUNC([shl_load],
	  [lt_cv_dlopen="shl_load"],
      [AC_CHECK_LIB([dld], [shl_load],
	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
	[AC_CHECK_FUNC([dlopen],
	      [lt_cv_dlopen="dlopen"],
	  [AC_CHECK_LIB([dl], [dlopen],
		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
	    [AC_CHECK_LIB([svld], [dlopen],
		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
	      [AC_CHECK_LIB([dld], [dld_link],
		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
	      ])
	    ])
	  ])
	])
      ])
    ;;
  esac

  if test "x$lt_cv_dlopen" != xno; then
    enable_dlopen=yes
  else
    enable_dlopen=no
  fi

  case $lt_cv_dlopen in
  dlopen)
    save_CPPFLAGS="$CPPFLAGS"
    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"

    save_LDFLAGS="$LDFLAGS"
    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"

    save_LIBS="$LIBS"
    LIBS="$lt_cv_dlopen_libs $LIBS"

    AC_CACHE_CHECK([whether a program can dlopen itself],
	  lt_cv_dlopen_self, [dnl
	  _LT_TRY_DLOPEN_SELF(
	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
    ])

    if test "x$lt_cv_dlopen_self" = xyes; then
      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
	  lt_cv_dlopen_self_static, [dnl
	  _LT_TRY_DLOPEN_SELF(
	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
      ])
    fi

    CPPFLAGS="$save_CPPFLAGS"
    LDFLAGS="$save_LDFLAGS"
    LIBS="$save_LIBS"
    ;;
  esac

  case $lt_cv_dlopen_self in
  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
  *) enable_dlopen_self=unknown ;;
  esac

  case $lt_cv_dlopen_self_static in
  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
  *) enable_dlopen_self_static=unknown ;;
  esac
fi
_LT_DECL([dlopen_support], [enable_dlopen], [0],
	 [Whether dlopen is supported])
_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
	 [Whether dlopen of programs is supported])
_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
	 [Whether dlopen of statically linked programs is supported])
])# LT_SYS_DLOPEN_SELF

# Old name:
AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])


# _LT_COMPILER_C_O([TAGNAME])
# ---------------------------
# Check to see if options -c and -o are simultaneously supported by compiler.
# This macro does not hard code the compiler like AC_PROG_CC_C_O.
m4_defun([_LT_COMPILER_C_O],
[m4_require([_LT_DECL_SED])dnl
m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_TAG_COMPILER])dnl
AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
   $RM -r conftest 2>/dev/null
   mkdir conftest
   cd conftest
   mkdir out
   echo "$lt_simple_compile_test_code" > conftest.$ac_ext

   lt_compiler_flag="-o out/conftest2.$ac_objext"
   # Insert the option either (1) after the last *FLAGS variable, or
   # (2) before a word containing "conftest.", or (3) at the end.
   # Note that $ac_compile itself does not contain backslashes and begins
   # with a dollar sign (not a hyphen), so the echo should work correctly.
   lt_compile=`echo "$ac_compile" | $SED \
   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
   -e 's:$: $lt_compiler_flag:'`
   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
   (eval "$lt_compile" 2>out/conftest.err)
   ac_status=$?
   cat out/conftest.err >&AS_MESSAGE_LOG_FD
   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
   if (exit $ac_status) && test -s out/conftest2.$ac_objext
   then
     # The compiler can only warn and ignore the option if not recognized
     # So say no if there are warnings
     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
     fi
   fi
   chmod u+w . 2>&AS_MESSAGE_LOG_FD
   $RM conftest*
   # SGI C++ compiler will create directory out/ii_files/ for
   # template instantiation
   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
   $RM out/* && rmdir out
   cd ..
   $RM -r conftest
   $RM conftest*
])
_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
	[Does compiler simultaneously support -c and -o options?])
])# _LT_COMPILER_C_O


# _LT_COMPILER_FILE_LOCKS([TAGNAME])
# ----------------------------------
# Check to see if we can do hard links to lock some files if needed
m4_defun([_LT_COMPILER_FILE_LOCKS],
[m4_require([_LT_ENABLE_LOCK])dnl
m4_require([_LT_FILEUTILS_DEFAULTS])dnl
_LT_COMPILER_C_O([$1])

hard_links="nottested"
if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
  # do not overwrite the value of need_locks provided by the user
  AC_MSG_CHECKING([if we can lock with hard links])
  hard_links=yes
  $RM conftest*
  ln conftest.a conftest.b 2>/dev/null && hard_links=no
  touch conftest.a
  ln conftest.a conftest.b 2>&5 || hard_links=no
  ln conftest.a conftest.b 2>/dev/null && hard_links=no
  AC_MSG_RESULT([$hard_links])
  if test "$hard_links" = no; then
    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
    need_locks=warn
  fi
else
  need_locks=no
fi
_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
])# _LT_COMPILER_FILE_LOCKS


# _LT_CHECK_OBJDIR
# ----------------
m4_defun([_LT_CHECK_OBJDIR],
[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
[rm -f .libs 2>/dev/null
mkdir .libs 2>/dev/null
if test -d .libs; then
  lt_cv_objdir=.libs
else
  # MS-DOS does not allow filenames that begin with a dot.
  lt_cv_objdir=_libs
fi
rmdir .libs 2>/dev/null])
objdir=$lt_cv_objdir
_LT_DECL([], [objdir], [0],
         [The name of the directory that contains temporary libtool files])dnl
m4_pattern_allow([LT_OBJDIR])dnl
AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
  [Define to the sub-directory in which libtool stores uninstalled libraries.])
])# _LT_CHECK_OBJDIR


# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
# --------------------------------------
# Check hardcoding attributes.
m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
[AC_MSG_CHECKING([how to hardcode library paths into programs])
_LT_TAGVAR(hardcode_action, $1)=
if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then

  # We can hardcode non-existent directories.
  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
     # If the only mechanism to avoid hardcoding is shlibpath_var, we
     # have to relink, otherwise we might link with an installed library
     # when we should be linking with a yet-to-be-installed one
     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
    # Linking always hardcodes the temporary library directory.
    _LT_TAGVAR(hardcode_action, $1)=relink
  else
    # We can link without hardcoding, and we can hardcode nonexisting dirs.
    _LT_TAGVAR(hardcode_action, $1)=immediate
  fi
else
  # We cannot hardcode anything, or else we can only hardcode existing
  # directories.
  _LT_TAGVAR(hardcode_action, $1)=unsupported
fi
AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])

if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
  # Fast installation is not supported
  enable_fast_install=no
elif test "$shlibpath_overrides_runpath" = yes ||
     test "$enable_shared" = no; then
  # Fast installation is not necessary
  enable_fast_install=needless
fi
_LT_TAGDECL([], [hardcode_action], [0],
    [How to hardcode a shared library path into an executable])
])# _LT_LINKER_HARDCODE_LIBPATH


# _LT_CMD_STRIPLIB
# ----------------
m4_defun([_LT_CMD_STRIPLIB],
[m4_require([_LT_DECL_EGREP])
striplib=
old_striplib=
AC_MSG_CHECKING([whether stripping libraries is possible])
if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
  AC_MSG_RESULT([yes])
else
# FIXME - insert some real tests, host_os isn't really good enough
  case $host_os in
  darwin*)
    if test -n "$STRIP" ; then
      striplib="$STRIP -x"
      old_striplib="$STRIP -S"
      AC_MSG_RESULT([yes])
    else
      AC_MSG_RESULT([no])
    fi
    ;;
  *)
    AC_MSG_RESULT([no])
    ;;
  esac
fi
_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
_LT_DECL([], [striplib], [1])
])# _LT_CMD_STRIPLIB


# _LT_SYS_DYNAMIC_LINKER([TAG])
# -----------------------------
# PORTME Fill in your ld.so characteristics
m4_defun([_LT_SYS_DYNAMIC_LINKER],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
m4_require([_LT_DECL_EGREP])dnl
m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_DECL_OBJDUMP])dnl
m4_require([_LT_DECL_SED])dnl
AC_MSG_CHECKING([dynamic linker characteristics])
m4_if([$1],
	[], [
if test "$GCC" = yes; then
  case $host_os in
    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
    *) lt_awk_arg="/^libraries:/" ;;
  esac
  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"`
  if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then
    # if the path contains ";" then we assume it to be the separator
    # otherwise default to the standard path separator (i.e. ":") - it is
    # assumed that no part of a normal pathname contains ";" but that should
    # okay in the real world where ";" in dirpaths is itself problematic.
    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'`
  else
    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
  fi
  # Ok, now we have the path, separated by spaces, we can step through it
  # and add multilib dir if necessary.
  lt_tmp_lt_search_path_spec=
  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
  for lt_sys_path in $lt_search_path_spec; do
    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
    else
      test -d "$lt_sys_path" && \
	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
    fi
  done
  lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk '
BEGIN {RS=" "; FS="/|\n";} {
  lt_foo="";
  lt_count=0;
  for (lt_i = NF; lt_i > 0; lt_i--) {
    if ($lt_i != "" && $lt_i != ".") {
      if ($lt_i == "..") {
        lt_count++;
      } else {
        if (lt_count == 0) {
          lt_foo="/" $lt_i lt_foo;
        } else {
          lt_count--;
        }
      }
    }
  }
  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
}'`
  sys_lib_search_path_spec=`$ECHO $lt_search_path_spec`
else
  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
fi])
library_names_spec=
libname_spec='lib$name'
soname_spec=
shrext_cmds=".so"
postinstall_cmds=
postuninstall_cmds=
finish_cmds=
finish_eval=
shlibpath_var=
shlibpath_overrides_runpath=unknown
version_type=none
dynamic_linker="$host_os ld.so"
sys_lib_dlsearch_path_spec="/lib /usr/lib"
need_lib_prefix=unknown
hardcode_into_libs=no

# when you set need_version to no, make sure it does not cause -set_version
# flags to be left without arguments
need_version=unknown

case $host_os in
aix3*)
  version_type=linux
  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
  shlibpath_var=LIBPATH

  # AIX 3 has no versioning support, so we append a major version to the name.
  soname_spec='${libname}${release}${shared_ext}$major'
  ;;

aix[[4-9]]*)
  version_type=linux
  need_lib_prefix=no
  need_version=no
  hardcode_into_libs=yes
  if test "$host_cpu" = ia64; then
    # AIX 5 supports IA64
    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
    shlibpath_var=LD_LIBRARY_PATH
  else
    # With GCC up to 2.95.x, collect2 would create an import file
    # for dependence libraries.  The import file would start with
    # the line `#! .'.  This would cause the generated library to
    # depend on `.', always an invalid library.  This was fixed in
    # development snapshots of GCC prior to 3.0.
    case $host_os in
      aix4 | aix4.[[01]] | aix4.[[01]].*)
      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
	   echo ' yes '
	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
	:
      else
	can_build_shared=no
      fi
      ;;
    esac
    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
    # soname into executable. Probably we can add versioning support to
    # collect2, so additional links can be useful in future.
    if test "$aix_use_runtimelinking" = yes; then
      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
      # instead of lib<name>.a to let people know that these are not
      # typical AIX shared libraries.
      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
    else
      # We preserve .a as extension for shared libraries through AIX4.2
      # and later when we are not doing run time linking.
      library_names_spec='${libname}${release}.a $libname.a'
      soname_spec='${libname}${release}${shared_ext}$major'
    fi
    shlibpath_var=LIBPATH
  fi
  ;;

amigaos*)
  case $host_cpu in
  powerpc)
    # Since July 2007 AmigaOS4 officially supports .so libraries.
    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
    ;;
  m68k)
    library_names_spec='$libname.ixlibrary $libname.a'
    # Create ${libname}_ixlibrary.a entries in /sys/libs.
    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
    ;;
  esac
  ;;

beos*)
  library_names_spec='${libname}${shared_ext}'
  dynamic_linker="$host_os ld.so"
  shlibpath_var=LIBRARY_PATH
  ;;

bsdi[[45]]*)
  version_type=linux
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
  shlibpath_var=LD_LIBRARY_PATH
  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
  # the default ld.so.conf also contains /usr/contrib/lib and
  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
  # libtool to hard-code these into programs
  ;;

cygwin* | mingw* | pw32* | cegcc*)
  version_type=windows
  shrext_cmds=".dll"
  need_version=no
  need_lib_prefix=no

  case $GCC,$host_os in
  yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*)
    library_names_spec='$libname.dll.a'
    # DLL is installed to $(libdir)/../bin by postinstall_cmds
    postinstall_cmds='base_file=`basename \${file}`~
      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
      dldir=$destdir/`dirname \$dlpath`~
      test -d \$dldir || mkdir -p \$dldir~
      $install_prog $dir/$dlname \$dldir/$dlname~
      chmod a+x \$dldir/$dlname~
      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
      fi'
    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
      dlpath=$dir/\$dldll~
       $RM \$dlpath'
    shlibpath_overrides_runpath=yes

    case $host_os in
    cygwin*)
      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
      sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
      ;;
    mingw* | cegcc*)
      # MinGW DLLs use traditional 'lib' prefix
      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
      sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
        # It is most probably a Windows format PATH printed by
        # mingw gcc, but we are running on Cygwin. Gcc prints its search
        # path with ; separators, and with drive letters. We can handle the
        # drive letters (cygwin fileutils understands them), so leave them,
        # especially as we might pass files found there to a mingw objdump,
        # which wouldn't understand a cygwinified path. Ahh.
        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
      else
        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
      fi
      ;;
    pw32*)
      # pw32 DLLs use 'pw' prefix rather than 'lib'
      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
      ;;
    esac
    ;;

  *)
    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
    ;;
  esac
  dynamic_linker='Win32 ld.exe'
  # FIXME: first we should search . and the directory the executable is in
  shlibpath_var=PATH
  ;;

darwin* | rhapsody*)
  dynamic_linker="$host_os dyld"
  version_type=darwin
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
  soname_spec='${libname}${release}${major}$shared_ext'
  shlibpath_overrides_runpath=yes
  shlibpath_var=DYLD_LIBRARY_PATH
  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
m4_if([$1], [],[
  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
  ;;

dgux*)
  version_type=linux
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  ;;

freebsd1*)
  dynamic_linker=no
  ;;

freebsd* | dragonfly*)
  # DragonFly does not have aout.  When/if they implement a new
  # versioning mechanism, adjust this.
  if test -x /usr/bin/objformat; then
    objformat=`/usr/bin/objformat`
  else
    case $host_os in
    freebsd[[123]]*) objformat=aout ;;
    *) objformat=elf ;;
    esac
  fi
  # Handle Gentoo/FreeBSD as it was Linux
  case $host_vendor in
    gentoo)
      version_type=linux ;;
    *)
      version_type=freebsd-$objformat ;;
  esac

  case $version_type in
    freebsd-elf*)
      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
      need_version=no
      need_lib_prefix=no
      ;;
    freebsd-*)
      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
      need_version=yes
      ;;
    linux)
      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
      soname_spec='${libname}${release}${shared_ext}$major'
      need_lib_prefix=no
      need_version=no
      ;;
  esac
  shlibpath_var=LD_LIBRARY_PATH
  case $host_os in
  freebsd2*)
    shlibpath_overrides_runpath=yes
    ;;
  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
    shlibpath_overrides_runpath=yes
    hardcode_into_libs=yes
    ;;
  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
    shlibpath_overrides_runpath=no
    hardcode_into_libs=yes
    ;;
  *) # from 4.6 on, and DragonFly
    shlibpath_overrides_runpath=yes
    hardcode_into_libs=yes
    ;;
  esac
  ;;

gnu*)
  version_type=linux
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  hardcode_into_libs=yes
  ;;

hpux9* | hpux10* | hpux11*)
  # Give a soname corresponding to the major version so that dld.sl refuses to
  # link against other versions.
  version_type=sunos
  need_lib_prefix=no
  need_version=no
  case $host_cpu in
  ia64*)
    shrext_cmds='.so'
    hardcode_into_libs=yes
    dynamic_linker="$host_os dld.so"
    shlibpath_var=LD_LIBRARY_PATH
    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
    soname_spec='${libname}${release}${shared_ext}$major'
    if test "X$HPUX_IA64_MODE" = X32; then
      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
    else
      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
    fi
    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
    ;;
  hppa*64*)
    shrext_cmds='.sl'
    hardcode_into_libs=yes
    dynamic_linker="$host_os dld.sl"
    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
    soname_spec='${libname}${release}${shared_ext}$major'
    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
    ;;
  *)
    shrext_cmds='.sl'
    dynamic_linker="$host_os dld.sl"
    shlibpath_var=SHLIB_PATH
    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
    soname_spec='${libname}${release}${shared_ext}$major'
    ;;
  esac
  # HP-UX runs *really* slowly unless shared libraries are mode 555.
  postinstall_cmds='chmod 555 $lib'
  ;;

interix[[3-9]]*)
  version_type=linux
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=no
  hardcode_into_libs=yes
  ;;

irix5* | irix6* | nonstopux*)
  case $host_os in
    nonstopux*) version_type=nonstopux ;;
    *)
	if test "$lt_cv_prog_gnu_ld" = yes; then
		version_type=linux
	else
		version_type=irix
	fi ;;
  esac
  need_lib_prefix=no
  need_version=no
  soname_spec='${libname}${release}${shared_ext}$major'
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
  case $host_os in
  irix5* | nonstopux*)
    libsuff= shlibsuff=
    ;;
  *)
    case $LD in # libtool.m4 will add one of these switches to LD
    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
      libsuff= shlibsuff= libmagic=32-bit;;
    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
      libsuff=32 shlibsuff=N32 libmagic=N32;;
    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
      libsuff=64 shlibsuff=64 libmagic=64-bit;;
    *) libsuff= shlibsuff= libmagic=never-match;;
    esac
    ;;
  esac
  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
  shlibpath_overrides_runpath=no
  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
  hardcode_into_libs=yes
  ;;

# No shared lib support for Linux oldld, aout, or coff.
linux*oldld* | linux*aout* | linux*coff*)
  dynamic_linker=no
  ;;

# This must be Linux ELF.
linux* | k*bsd*-gnu)
  version_type=linux
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=no
  # Some binutils ld are patched to set DT_RUNPATH
  save_LDFLAGS=$LDFLAGS
  save_libdir=$libdir
  eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
       LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
  AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
    [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
       [shlibpath_overrides_runpath=yes])])
  LDFLAGS=$save_LDFLAGS
  libdir=$save_libdir

  # This implies no fast_install, which is unacceptable.
  # Some rework will be needed to allow for fast_install
  # before this can be enabled.
  hardcode_into_libs=yes

  # Append ld.so.conf contents to the search path
  if test -f /etc/ld.so.conf; then
    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
  fi

  # We used to test for /lib/ld.so.1 and disable shared libraries on
  # powerpc, because MkLinux only supported shared libraries with the
  # GNU dynamic linker.  Since this was broken with cross compilers,
  # most powerpc-linux boxes support dynamic linking these days and
  # people can always --disable-shared, the test was removed, and we
  # assume the GNU/Linux dynamic linker is in use.
  dynamic_linker='GNU/Linux ld.so'
  ;;

netbsd*)
  version_type=sunos
  need_lib_prefix=no
  need_version=no
  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
    dynamic_linker='NetBSD (a.out) ld.so'
  else
    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
    soname_spec='${libname}${release}${shared_ext}$major'
    dynamic_linker='NetBSD ld.elf_so'
  fi
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=yes
  hardcode_into_libs=yes
  ;;

newsos6)
  version_type=linux
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=yes
  ;;

*nto* | *qnx*)
  version_type=qnx
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=no
  hardcode_into_libs=yes
  dynamic_linker='ldqnx.so'
  ;;

openbsd*)
  version_type=sunos
  sys_lib_dlsearch_path_spec="/usr/lib"
  need_lib_prefix=no
  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
  case $host_os in
    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
    *)				need_version=no  ;;
  esac
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
  shlibpath_var=LD_LIBRARY_PATH
  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
    case $host_os in
      openbsd2.[[89]] | openbsd2.[[89]].*)
	shlibpath_overrides_runpath=no
	;;
      *)
	shlibpath_overrides_runpath=yes
	;;
      esac
  else
    shlibpath_overrides_runpath=yes
  fi
  ;;

os2*)
  libname_spec='$name'
  shrext_cmds=".dll"
  need_lib_prefix=no
  library_names_spec='$libname${shared_ext} $libname.a'
  dynamic_linker='OS/2 ld.exe'
  shlibpath_var=LIBPATH
  ;;

osf3* | osf4* | osf5*)
  version_type=osf
  need_lib_prefix=no
  need_version=no
  soname_spec='${libname}${release}${shared_ext}$major'
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  shlibpath_var=LD_LIBRARY_PATH
  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
  ;;

rdos*)
  dynamic_linker=no
  ;;

solaris*)
  version_type=linux
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=yes
  hardcode_into_libs=yes
  # ldd complains unless libraries are executable
  postinstall_cmds='chmod +x $lib'
  ;;

sunos4*)
  version_type=sunos
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=yes
  if test "$with_gnu_ld" = yes; then
    need_lib_prefix=no
  fi
  need_version=yes
  ;;

sysv4 | sysv4.3*)
  version_type=linux
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  case $host_vendor in
    sni)
      shlibpath_overrides_runpath=no
      need_lib_prefix=no
      runpath_var=LD_RUN_PATH
      ;;
    siemens)
      need_lib_prefix=no
      ;;
    motorola)
      need_lib_prefix=no
      need_version=no
      shlibpath_overrides_runpath=no
      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
      ;;
  esac
  ;;

sysv4*MP*)
  if test -d /usr/nec ;then
    version_type=linux
    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
    soname_spec='$libname${shared_ext}.$major'
    shlibpath_var=LD_LIBRARY_PATH
  fi
  ;;

sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
  version_type=freebsd-elf
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=yes
  hardcode_into_libs=yes
  if test "$with_gnu_ld" = yes; then
    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
  else
    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
    case $host_os in
      sco3.2v5*)
        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
	;;
    esac
  fi
  sys_lib_dlsearch_path_spec='/usr/lib'
  ;;

tpf*)
  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
  version_type=linux
  need_lib_prefix=no
  need_version=no
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  shlibpath_var=LD_LIBRARY_PATH
  shlibpath_overrides_runpath=no
  hardcode_into_libs=yes
  ;;

uts4*)
  version_type=linux
  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
  soname_spec='${libname}${release}${shared_ext}$major'
  shlibpath_var=LD_LIBRARY_PATH
  ;;

*)
  dynamic_linker=no
  ;;
esac
AC_MSG_RESULT([$dynamic_linker])
test "$dynamic_linker" = no && can_build_shared=no

variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
if test "$GCC" = yes; then
  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
fi

if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
fi
if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
fi

_LT_DECL([], [variables_saved_for_relink], [1],
    [Variables whose values should be saved in libtool wrapper scripts and
    restored at link time])
_LT_DECL([], [need_lib_prefix], [0],
    [Do we need the "lib" prefix for modules?])
_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
_LT_DECL([], [version_type], [0], [Library versioning type])
_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
_LT_DECL([], [shlibpath_overrides_runpath], [0],
    [Is shlibpath searched before the hard-coded library search path?])
_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
_LT_DECL([], [library_names_spec], [1],
    [[List of archive names.  First name is the real one, the rest are links.
    The last name is the one that the linker finds with -lNAME]])
_LT_DECL([], [soname_spec], [1],
    [[The coded name of the library, if different from the real name]])
_LT_DECL([], [postinstall_cmds], [2],
    [Command to use after installation of a shared archive])
_LT_DECL([], [postuninstall_cmds], [2],
    [Command to use after uninstallation of a shared archive])
_LT_DECL([], [finish_cmds], [2],
    [Commands used to finish a libtool library installation in a directory])
_LT_DECL([], [finish_eval], [1],
    [[As "finish_cmds", except a single script fragment to be evaled but
    not shown]])
_LT_DECL([], [hardcode_into_libs], [0],
    [Whether we should hardcode library paths into libraries])
_LT_DECL([], [sys_lib_search_path_spec], [2],
    [Compile-time system search path for libraries])
_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
    [Run-time system search path for libraries])
])# _LT_SYS_DYNAMIC_LINKER


# _LT_PATH_TOOL_PREFIX(TOOL)
# --------------------------
# find a file program which can recognize shared library
AC_DEFUN([_LT_PATH_TOOL_PREFIX],
[m4_require([_LT_DECL_EGREP])dnl
AC_MSG_CHECKING([for $1])
AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
[case $MAGIC_CMD in
[[\\/*] |  ?:[\\/]*])
  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
  ;;
*)
  lt_save_MAGIC_CMD="$MAGIC_CMD"
  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
dnl $ac_dummy forces splitting on constant user-supplied paths.
dnl POSIX.2 word splitting is done only on the output of word expansions,
dnl not every word.  This closes a longstanding sh security hole.
  ac_dummy="m4_if([$2], , $PATH, [$2])"
  for ac_dir in $ac_dummy; do
    IFS="$lt_save_ifs"
    test -z "$ac_dir" && ac_dir=.
    if test -f $ac_dir/$1; then
      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
      if test -n "$file_magic_test_file"; then
	case $deplibs_check_method in
	"file_magic "*)
	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
	    $EGREP "$file_magic_regex" > /dev/null; then
	    :
	  else
	    cat <<_LT_EOF 1>&2

*** Warning: the command libtool uses to detect shared libraries,
*** $file_magic_cmd, produces output that libtool cannot recognize.
*** The result is that libtool may fail to recognize shared libraries
*** as such.  This will affect the creation of libtool libraries that
*** depend on shared libraries, but programs linked with such libtool
*** libraries will work regardless of this problem.  Nevertheless, you
*** may want to report the problem to your system manager and/or to
*** bug-libtool@gnu.org

_LT_EOF
	  fi ;;
	esac
      fi
      break
    fi
  done
  IFS="$lt_save_ifs"
  MAGIC_CMD="$lt_save_MAGIC_CMD"
  ;;
esac])
MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
if test -n "$MAGIC_CMD"; then
  AC_MSG_RESULT($MAGIC_CMD)
else
  AC_MSG_RESULT(no)
fi
_LT_DECL([], [MAGIC_CMD], [0],
	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
])# _LT_PATH_TOOL_PREFIX

# Old name:
AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])


# _LT_PATH_MAGIC
# --------------
# find a file program which can recognize a shared library
m4_defun([_LT_PATH_MAGIC],
[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
if test -z "$lt_cv_path_MAGIC_CMD"; then
  if test -n "$ac_tool_prefix"; then
    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
  else
    MAGIC_CMD=:
  fi
fi
])# _LT_PATH_MAGIC


# LT_PATH_LD
# ----------
# find the pathname to the GNU or non-GNU linker
AC_DEFUN([LT_PATH_LD],
[AC_REQUIRE([AC_PROG_CC])dnl
AC_REQUIRE([AC_CANONICAL_HOST])dnl
AC_REQUIRE([AC_CANONICAL_BUILD])dnl
m4_require([_LT_DECL_SED])dnl
m4_require([_LT_DECL_EGREP])dnl

AC_ARG_WITH([gnu-ld],
    [AS_HELP_STRING([--with-gnu-ld],
	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
    [test "$withval" = no || with_gnu_ld=yes],
    [with_gnu_ld=no])dnl

ac_prog=ld
if test "$GCC" = yes; then
  # Check if gcc -print-prog-name=ld gives a path.
  AC_MSG_CHECKING([for ld used by $CC])
  case $host in
  *-*-mingw*)
    # gcc leaves a trailing carriage return which upsets mingw
    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
  *)
    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
  esac
  case $ac_prog in
    # Accept absolute paths.
    [[\\/]]* | ?:[[\\/]]*)
      re_direlt='/[[^/]][[^/]]*/\.\./'
      # Canonicalize the pathname of ld
      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
      done
      test -z "$LD" && LD="$ac_prog"
      ;;
  "")
    # If it fails, then pretend we aren't using GCC.
    ac_prog=ld
    ;;
  *)
    # If it is relative, then search for the first ld in PATH.
    with_gnu_ld=unknown
    ;;
  esac
elif test "$with_gnu_ld" = yes; then
  AC_MSG_CHECKING([for GNU ld])
else
  AC_MSG_CHECKING([for non-GNU ld])
fi
AC_CACHE_VAL(lt_cv_path_LD,
[if test -z "$LD"; then
  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
  for ac_dir in $PATH; do
    IFS="$lt_save_ifs"
    test -z "$ac_dir" && ac_dir=.
    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
      lt_cv_path_LD="$ac_dir/$ac_prog"
      # Check to see if the program is GNU ld.  I'd rather use --version,
      # but apparently some variants of GNU ld only accept -v.
      # Break only if it was the GNU/non-GNU ld that we prefer.
      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
      *GNU* | *'with BFD'*)
	test "$with_gnu_ld" != no && break
	;;
      *)
	test "$with_gnu_ld" != yes && break
	;;
      esac
    fi
  done
  IFS="$lt_save_ifs"
else
  lt_cv_path_LD="$LD" # Let the user override the test with a path.
fi])
LD="$lt_cv_path_LD"
if test -n "$LD"; then
  AC_MSG_RESULT($LD)
else
  AC_MSG_RESULT(no)
fi
test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
_LT_PATH_LD_GNU
AC_SUBST([LD])

_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
])# LT_PATH_LD

# Old names:
AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_PROG_LD], [])
dnl AC_DEFUN([AC_PROG_LD], [])


# _LT_PATH_LD_GNU
#- --------------
m4_defun([_LT_PATH_LD_GNU],
[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
[# I'd rather use --version here, but apparently some GNU lds only accept -v.
case `$LD -v 2>&1 </dev/null` in
*GNU* | *'with BFD'*)
  lt_cv_prog_gnu_ld=yes
  ;;
*)
  lt_cv_prog_gnu_ld=no
  ;;
esac])
with_gnu_ld=$lt_cv_prog_gnu_ld
])# _LT_PATH_LD_GNU


# _LT_CMD_RELOAD
# --------------
# find reload flag for linker
#   -- PORTME Some linkers may need a different reload flag.
m4_defun([_LT_CMD_RELOAD],
[AC_CACHE_CHECK([for $LD option to reload object files],
  lt_cv_ld_reload_flag,
  [lt_cv_ld_reload_flag='-r'])
reload_flag=$lt_cv_ld_reload_flag
case $reload_flag in
"" | " "*) ;;
*) reload_flag=" $reload_flag" ;;
esac
reload_cmds='$LD$reload_flag -o $output$reload_objs'
case $host_os in
  darwin*)
    if test "$GCC" = yes; then
      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
    else
      reload_cmds='$LD$reload_flag -o $output$reload_objs'
    fi
    ;;
esac
_LT_DECL([], [reload_flag], [1], [How to create reloadable object files])dnl
_LT_DECL([], [reload_cmds], [2])dnl
])# _LT_CMD_RELOAD


# _LT_CHECK_MAGIC_METHOD
# ----------------------
# how to check for library dependencies
#  -- PORTME fill in with the dynamic library characteristics
m4_defun([_LT_CHECK_MAGIC_METHOD],
[m4_require([_LT_DECL_EGREP])
m4_require([_LT_DECL_OBJDUMP])
AC_CACHE_CHECK([how to recognize dependent libraries],
lt_cv_deplibs_check_method,
[lt_cv_file_magic_cmd='$MAGIC_CMD'
lt_cv_file_magic_test_file=
lt_cv_deplibs_check_method='unknown'
# Need to set the preceding variable on all platforms that support
# interlibrary dependencies.
# 'none' -- dependencies not supported.
# `unknown' -- same as none, but documents that we really don't know.
# 'pass_all' -- all dependencies passed with no checks.
# 'test_compile' -- check by making test program.
# 'file_magic [[regex]]' -- check by looking for files in library path
# which responds to the $file_magic_cmd with a given extended regex.
# If you have `file' or equivalent on your system and you're not sure
# whether `pass_all' will *always* work, you probably want this one.

case $host_os in
aix[[4-9]]*)
  lt_cv_deplibs_check_method=pass_all
  ;;

beos*)
  lt_cv_deplibs_check_method=pass_all
  ;;

bsdi[[45]]*)
  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
  lt_cv_file_magic_cmd='/usr/bin/file -L'
  lt_cv_file_magic_test_file=/shlib/libc.so
  ;;

cygwin*)
  # func_win32_libid is a shell function defined in ltmain.sh
  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
  lt_cv_file_magic_cmd='func_win32_libid'
  ;;

mingw* | pw32*)
  # Base MSYS/MinGW do not provide the 'file' command needed by
  # func_win32_libid shell function, so use a weaker test based on 'objdump',
  # unless we find 'file', for example because we are cross-compiling.
  if ( file / ) >/dev/null 2>&1; then
    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
    lt_cv_file_magic_cmd='func_win32_libid'
  else
    lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
    lt_cv_file_magic_cmd='$OBJDUMP -f'
  fi
  ;;

cegcc)
  # use the weaker test based on 'objdump'. See mingw*.
  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
  lt_cv_file_magic_cmd='$OBJDUMP -f'
  ;;

darwin* | rhapsody*)
  lt_cv_deplibs_check_method=pass_all
  ;;

freebsd* | dragonfly*)
  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
    case $host_cpu in
    i*86 )
      # Not sure whether the presence of OpenBSD here was a mistake.
      # Let's accept both of them until this is cleared up.
      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
      lt_cv_file_magic_cmd=/usr/bin/file
      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
      ;;
    esac
  else
    lt_cv_deplibs_check_method=pass_all
  fi
  ;;

gnu*)
  lt_cv_deplibs_check_method=pass_all
  ;;

hpux10.20* | hpux11*)
  lt_cv_file_magic_cmd=/usr/bin/file
  case $host_cpu in
  ia64*)
    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
    ;;
  hppa*64*)
    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]']
    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
    ;;
  *)
    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library'
    lt_cv_file_magic_test_file=/usr/lib/libc.sl
    ;;
  esac
  ;;

interix[[3-9]]*)
  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
  ;;

irix5* | irix6* | nonstopux*)
  case $LD in
  *-32|*"-32 ") libmagic=32-bit;;
  *-n32|*"-n32 ") libmagic=N32;;
  *-64|*"-64 ") libmagic=64-bit;;
  *) libmagic=never-match;;
  esac
  lt_cv_deplibs_check_method=pass_all
  ;;

# This must be Linux ELF.
linux* | k*bsd*-gnu)
  lt_cv_deplibs_check_method=pass_all
  ;;

netbsd*)
  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
  else
    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
  fi
  ;;

newos6*)
  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
  lt_cv_file_magic_cmd=/usr/bin/file
  lt_cv_file_magic_test_file=/usr/lib/libnls.so
  ;;

*nto* | *qnx*)
  lt_cv_deplibs_check_method=pass_all
  ;;

openbsd*)
  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
  else
    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
  fi
  ;;

osf3* | osf4* | osf5*)
  lt_cv_deplibs_check_method=pass_all
  ;;

rdos*)
  lt_cv_deplibs_check_method=pass_all
  ;;

solaris*)
  lt_cv_deplibs_check_method=pass_all
  ;;

sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
  lt_cv_deplibs_check_method=pass_all
  ;;

sysv4 | sysv4.3*)
  case $host_vendor in
  motorola)
    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
    ;;
  ncr)
    lt_cv_deplibs_check_method=pass_all
    ;;
  sequent)
    lt_cv_file_magic_cmd='/bin/file'
    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
    ;;
  sni)
    lt_cv_file_magic_cmd='/bin/file'
    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
    lt_cv_file_magic_test_file=/lib/libc.so
    ;;
  siemens)
    lt_cv_deplibs_check_method=pass_all
    ;;
  pc)
    lt_cv_deplibs_check_method=pass_all
    ;;
  esac
  ;;

tpf*)
  lt_cv_deplibs_check_method=pass_all
  ;;
esac
])
file_magic_cmd=$lt_cv_file_magic_cmd
deplibs_check_method=$lt_cv_deplibs_check_method
test -z "$deplibs_check_method" && deplibs_check_method=unknown

_LT_DECL([], [deplibs_check_method], [1],
    [Method to check whether dependent libraries are shared objects])
_LT_DECL([], [file_magic_cmd], [1],
    [Command to use when deplibs_check_method == "file_magic"])
])# _LT_CHECK_MAGIC_METHOD


# LT_PATH_NM
# ----------
# find the pathname to a BSD- or MS-compatible name lister
AC_DEFUN([LT_PATH_NM],
[AC_REQUIRE([AC_PROG_CC])dnl
AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
[if test -n "$NM"; then
  # Let the user override the test.
  lt_cv_path_NM="$NM"
else
  lt_nm_to_check="${ac_tool_prefix}nm"
  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
    lt_nm_to_check="$lt_nm_to_check nm"
  fi
  for lt_tmp_nm in $lt_nm_to_check; do
    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
      IFS="$lt_save_ifs"
      test -z "$ac_dir" && ac_dir=.
      tmp_nm="$ac_dir/$lt_tmp_nm"
      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
	# Check to see if the nm accepts a BSD-compat flag.
	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
	#   nm: unknown option "B" ignored
	# Tru64's nm complains that /dev/null is an invalid object file
	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
	*/dev/null* | *'Invalid file or object type'*)
	  lt_cv_path_NM="$tmp_nm -B"
	  break
	  ;;
	*)
	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
	  */dev/null*)
	    lt_cv_path_NM="$tmp_nm -p"
	    break
	    ;;
	  *)
	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
	    continue # so that we can try to find one that supports BSD flags
	    ;;
	  esac
	  ;;
	esac
      fi
    done
    IFS="$lt_save_ifs"
  done
  : ${lt_cv_path_NM=no}
fi])
if test "$lt_cv_path_NM" != "no"; then
  NM="$lt_cv_path_NM"
else
  # Didn't find any BSD compatible name lister, look for dumpbin.
  AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :)
  AC_SUBST([DUMPBIN])
  if test "$DUMPBIN" != ":"; then
    NM="$DUMPBIN"
  fi
fi
test -z "$NM" && NM=nm
AC_SUBST([NM])
_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl

AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
  [lt_cv_nm_interface="BSD nm"
  echo "int some_variable = 0;" > conftest.$ac_ext
  (eval echo "\"\$as_me:__oline__: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
  (eval "$ac_compile" 2>conftest.err)
  cat conftest.err >&AS_MESSAGE_LOG_FD
  (eval echo "\"\$as_me:__oline__: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
  cat conftest.err >&AS_MESSAGE_LOG_FD
  (eval echo "\"\$as_me:__oline__: output\"" >&AS_MESSAGE_LOG_FD)
  cat conftest.out >&AS_MESSAGE_LOG_FD
  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
    lt_cv_nm_interface="MS dumpbin"
  fi
  rm -f conftest*])
])# LT_PATH_NM

# Old names:
AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_PROG_NM], [])
dnl AC_DEFUN([AC_PROG_NM], [])


# LT_LIB_M
# --------
# check for math library
AC_DEFUN([LT_LIB_M],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
LIBM=
case $host in
*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
  # These system don't have libm, or don't need it
  ;;
*-ncr-sysv4.3*)
  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
  ;;
*)
  AC_CHECK_LIB(m, cos, LIBM="-lm")
  ;;
esac
AC_SUBST([LIBM])
])# LT_LIB_M

# Old name:
AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_CHECK_LIBM], [])


# _LT_COMPILER_NO_RTTI([TAGNAME])
# -------------------------------
m4_defun([_LT_COMPILER_NO_RTTI],
[m4_require([_LT_TAG_COMPILER])dnl

_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=

if test "$GCC" = yes; then
  _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'

  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
    lt_cv_prog_compiler_rtti_exceptions,
    [-fno-rtti -fno-exceptions], [],
    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
fi
_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
	[Compiler flag to turn off builtin functions])
])# _LT_COMPILER_NO_RTTI


# _LT_CMD_GLOBAL_SYMBOLS
# ----------------------
m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
AC_REQUIRE([AC_PROG_CC])dnl
AC_REQUIRE([LT_PATH_NM])dnl
AC_REQUIRE([LT_PATH_LD])dnl
m4_require([_LT_DECL_SED])dnl
m4_require([_LT_DECL_EGREP])dnl
m4_require([_LT_TAG_COMPILER])dnl

# Check for command to grab the raw symbol name followed by C symbol from nm.
AC_MSG_CHECKING([command to parse $NM output from $compiler object])
AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
[
# These are sane defaults that work on at least a few old systems.
# [They come from Ultrix.  What could be older than Ultrix?!! ;)]

# Character class describing NM global symbol codes.
symcode='[[BCDEGRST]]'

# Regexp to match symbols that can be accessed directly from C.
sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'

# Define system-specific variables.
case $host_os in
aix*)
  symcode='[[BCDT]]'
  ;;
cygwin* | mingw* | pw32* | cegcc*)
  symcode='[[ABCDGISTW]]'
  ;;
hpux*)
  if test "$host_cpu" = ia64; then
    symcode='[[ABCDEGRST]]'
  fi
  ;;
irix* | nonstopux*)
  symcode='[[BCDEGRST]]'
  ;;
osf*)
  symcode='[[BCDEGQRST]]'
  ;;
solaris*)
  symcode='[[BDRT]]'
  ;;
sco3.2v5*)
  symcode='[[DT]]'
  ;;
sysv4.2uw2*)
  symcode='[[DT]]'
  ;;
sysv5* | sco5v6* | unixware* | OpenUNIX*)
  symcode='[[ABDT]]'
  ;;
sysv4)
  symcode='[[DFNSTU]]'
  ;;
esac

# If we're using GNU nm, then use its standard symbol codes.
case `$NM -V 2>&1` in
*GNU* | *'with BFD'*)
  symcode='[[ABCDGIRSTW]]' ;;
esac

# Transform an extracted symbol line into a proper C declaration.
# Some systems (esp. on ia64) link data and code symbols differently,
# so use this general approach.
lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"

# Transform an extracted symbol line into symbol name and symbol address
lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"

# Handle CRLF in mingw tool chain
opt_cr=
case $build_os in
mingw*)
  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
  ;;
esac

# Try without a prefix underscore, then with it.
for ac_symprfx in "" "_"; do

  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
  symxfrm="\\1 $ac_symprfx\\2 \\2"

  # Write the raw and C identifiers.
  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
    # Fake it for dumpbin and say T for any non-static function
    # and D for any global variable.
    # Also find C++ and __fastcall symbols from MSVC++,
    # which start with @ or ?.
    lt_cv_sys_global_symbol_pipe="$AWK ['"\
"     {last_section=section; section=\$ 3};"\
"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
"     \$ 0!~/External *\|/{next};"\
"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
"     {if(hide[section]) next};"\
"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
"     ' prfx=^$ac_symprfx]"
  else
    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
  fi

  # Check to see that the pipe works correctly.
  pipe_works=no

  rm -f conftest*
  cat > conftest.$ac_ext <<_LT_EOF
#ifdef __cplusplus
extern "C" {
#endif
char nm_test_var;
void nm_test_func(void);
void nm_test_func(void){}
#ifdef __cplusplus
}
#endif
int main(){nm_test_var='a';nm_test_func();return(0);}
_LT_EOF

  if AC_TRY_EVAL(ac_compile); then
    # Now try to grab the symbols.
    nlist=conftest.nm
    if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then
      # Try sorting and uniquifying the output.
      if sort "$nlist" | uniq > "$nlist"T; then
	mv -f "$nlist"T "$nlist"
      else
	rm -f "$nlist"T
      fi

      # Make sure that we snagged all the symbols we need.
      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
	  cat <<_LT_EOF > conftest.$ac_ext
#ifdef __cplusplus
extern "C" {
#endif

_LT_EOF
	  # Now generate the symbol file.
	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'

	  cat <<_LT_EOF >> conftest.$ac_ext

/* The mapping between symbol names and symbols.  */
const struct {
  const char *name;
  void       *address;
}
lt__PROGRAM__LTX_preloaded_symbols[[]] =
{
  { "@PROGRAM@", (void *) 0 },
_LT_EOF
	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
	  cat <<\_LT_EOF >> conftest.$ac_ext
  {0, (void *) 0}
};

/* This works around a problem in FreeBSD linker */
#ifdef FREEBSD_WORKAROUND
static const void *lt_preloaded_setup() {
  return lt__PROGRAM__LTX_preloaded_symbols;
}
#endif

#ifdef __cplusplus
}
#endif
_LT_EOF
	  # Now try linking the two files.
	  mv conftest.$ac_objext conftstm.$ac_objext
	  lt_save_LIBS="$LIBS"
	  lt_save_CFLAGS="$CFLAGS"
	  LIBS="conftstm.$ac_objext"
	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
	    pipe_works=yes
	  fi
	  LIBS="$lt_save_LIBS"
	  CFLAGS="$lt_save_CFLAGS"
	else
	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
	fi
      else
	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
      fi
    else
      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
    fi
  else
    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
    cat conftest.$ac_ext >&5
  fi
  rm -rf conftest* conftst*

  # Do not use the global_symbol_pipe unless it works.
  if test "$pipe_works" = yes; then
    break
  else
    lt_cv_sys_global_symbol_pipe=
  fi
done
])
if test -z "$lt_cv_sys_global_symbol_pipe"; then
  lt_cv_sys_global_symbol_to_cdecl=
fi
if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
  AC_MSG_RESULT(failed)
else
  AC_MSG_RESULT(ok)
fi

_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
    [Take the output of nm and produce a listing of raw symbols and C names])
_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
    [Transform the output of nm in a proper C declaration])
_LT_DECL([global_symbol_to_c_name_address],
    [lt_cv_sys_global_symbol_to_c_name_address], [1],
    [Transform the output of nm in a C name address pair])
_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
    [Transform the output of nm in a C name address pair when lib prefix is needed])
]) # _LT_CMD_GLOBAL_SYMBOLS


# _LT_COMPILER_PIC([TAGNAME])
# ---------------------------
m4_defun([_LT_COMPILER_PIC],
[m4_require([_LT_TAG_COMPILER])dnl
_LT_TAGVAR(lt_prog_compiler_wl, $1)=
_LT_TAGVAR(lt_prog_compiler_pic, $1)=
_LT_TAGVAR(lt_prog_compiler_static, $1)=

AC_MSG_CHECKING([for $compiler option to produce PIC])
m4_if([$1], [CXX], [
  # C++ specific cases for pic, static, wl, etc.
  if test "$GXX" = yes; then
    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'

    case $host_os in
    aix*)
      # All AIX code is PIC.
      if test "$host_cpu" = ia64; then
	# AIX 5 now supports IA64 processor
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      fi
      ;;

    amigaos*)
      case $host_cpu in
      powerpc)
            # see comment about AmigaOS4 .so support
            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
        ;;
      m68k)
            # FIXME: we need at least 68020 code to build shared libraries, but
            # adding the `-m68020' flag to GCC prevents building anything better,
            # like `-m68040'.
            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
        ;;
      esac
      ;;

    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
      # PIC is the default for these OSes.
      ;;
    mingw* | cygwin* | os2* | pw32* | cegcc*)
      # This hack is so that the source file can tell whether it is being
      # built for inclusion in a dll (and should export symbols for example).
      # Although the cygwin gcc ignores -fPIC, still need this for old-style
      # (--disable-auto-import) libraries
      m4_if([$1], [GCJ], [],
	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
      ;;
    darwin* | rhapsody*)
      # PIC is the default on this platform
      # Common symbols not allowed in MH_DYLIB files
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
      ;;
    *djgpp*)
      # DJGPP does not support shared libraries at all
      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
      ;;
    interix[[3-9]]*)
      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
      # Instead, we relocate shared libraries at runtime.
      ;;
    sysv4*MP*)
      if test -d /usr/nec; then
	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
      fi
      ;;
    hpux*)
      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
      # sets the default TLS model and affects inlining.
      case $host_cpu in
      hppa*64*)
	;;
      *)
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
	;;
      esac
      ;;
    *qnx* | *nto*)
      # QNX uses GNU C++, but need to define -shared option too, otherwise
      # it will coredump.
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
      ;;
    *)
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
      ;;
    esac
  else
    case $host_os in
      aix[[4-9]]*)
	# All AIX code is PIC.
	if test "$host_cpu" = ia64; then
	  # AIX 5 now supports IA64 processor
	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	else
	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
	fi
	;;
      chorus*)
	case $cc_basename in
	cxch68*)
	  # Green Hills C++ Compiler
	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
	  ;;
	esac
	;;
      dgux*)
	case $cc_basename in
	  ec++*)
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	    ;;
	  ghcx*)
	    # Green Hills C++ Compiler
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
	    ;;
	  *)
	    ;;
	esac
	;;
      freebsd* | dragonfly*)
	# FreeBSD uses GNU C++
	;;
      hpux9* | hpux10* | hpux11*)
	case $cc_basename in
	  CC*)
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
	    if test "$host_cpu" != ia64; then
	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
	    fi
	    ;;
	  aCC*)
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
	    case $host_cpu in
	    hppa*64*|ia64*)
	      # +Z the default
	      ;;
	    *)
	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
	      ;;
	    esac
	    ;;
	  *)
	    ;;
	esac
	;;
      interix*)
	# This is c89, which is MS Visual C++ (no shared libs)
	# Anyone wants to do a port?
	;;
      irix5* | irix6* | nonstopux*)
	case $cc_basename in
	  CC*)
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
	    # CC pic flag -KPIC is the default.
	    ;;
	  *)
	    ;;
	esac
	;;
      linux* | k*bsd*-gnu)
	case $cc_basename in
	  KCC*)
	    # KAI C++ Compiler
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
	    ;;
	  ecpc* )
	    # old Intel C++ for x86_64 which still supported -KPIC.
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
	    ;;
	  icpc* )
	    # Intel C++, used to be incompatible with GCC.
	    # ICC 10 doesn't accept -KPIC any more.
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
	    ;;
	  pgCC* | pgcpp*)
	    # Portland Group C++ compiler
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	    ;;
	  cxx*)
	    # Compaq C++
	    # Make sure the PIC flag is empty.  It appears that all Alpha
	    # Linux and Compaq Tru64 Unix objects are PIC.
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
	    ;;
	  xlc* | xlC*)
	    # IBM XL 8.0 on PPC
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
	    ;;
	  *)
	    case `$CC -V 2>&1 | sed 5q` in
	    *Sun\ C*)
	      # Sun C++ 5.9
	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
	      ;;
	    esac
	    ;;
	esac
	;;
      lynxos*)
	;;
      m88k*)
	;;
      mvs*)
	case $cc_basename in
	  cxx*)
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
	    ;;
	  *)
	    ;;
	esac
	;;
      netbsd*)
	;;
      *qnx* | *nto*)
        # QNX uses GNU C++, but need to define -shared option too, otherwise
        # it will coredump.
        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
        ;;
      osf3* | osf4* | osf5*)
	case $cc_basename in
	  KCC*)
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
	    ;;
	  RCC*)
	    # Rational C++ 2.4.1
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
	    ;;
	  cxx*)
	    # Digital/Compaq C++
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    # Make sure the PIC flag is empty.  It appears that all Alpha
	    # Linux and Compaq Tru64 Unix objects are PIC.
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
	    ;;
	  *)
	    ;;
	esac
	;;
      psos*)
	;;
      solaris*)
	case $cc_basename in
	  CC*)
	    # Sun C++ 4.2, 5.x and Centerline C++
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
	    ;;
	  gcx*)
	    # Green Hills C++ Compiler
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
	    ;;
	  *)
	    ;;
	esac
	;;
      sunos4*)
	case $cc_basename in
	  CC*)
	    # Sun C++ 4.x
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	    ;;
	  lcc*)
	    # Lucid
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
	    ;;
	  *)
	    ;;
	esac
	;;
      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
	case $cc_basename in
	  CC*)
	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	    ;;
	esac
	;;
      tandem*)
	case $cc_basename in
	  NCC*)
	    # NonStop-UX NCC 3.20
	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	    ;;
	  *)
	    ;;
	esac
	;;
      vxworks*)
	;;
      *)
	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
	;;
    esac
  fi
],
[
  if test "$GCC" = yes; then
    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'

    case $host_os in
      aix*)
      # All AIX code is PIC.
      if test "$host_cpu" = ia64; then
	# AIX 5 now supports IA64 processor
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      fi
      ;;

    amigaos*)
      case $host_cpu in
      powerpc)
            # see comment about AmigaOS4 .so support
            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
        ;;
      m68k)
            # FIXME: we need at least 68020 code to build shared libraries, but
            # adding the `-m68020' flag to GCC prevents building anything better,
            # like `-m68040'.
            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
        ;;
      esac
      ;;

    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
      # PIC is the default for these OSes.
      ;;

    mingw* | cygwin* | pw32* | os2* | cegcc*)
      # This hack is so that the source file can tell whether it is being
      # built for inclusion in a dll (and should export symbols for example).
      # Although the cygwin gcc ignores -fPIC, still need this for old-style
      # (--disable-auto-import) libraries
      m4_if([$1], [GCJ], [],
	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
      ;;

    darwin* | rhapsody*)
      # PIC is the default on this platform
      # Common symbols not allowed in MH_DYLIB files
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
      ;;

    hpux*)
      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
      # sets the default TLS model and affects inlining.
      case $host_cpu in
      hppa*64*)
	# +Z the default
	;;
      *)
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
	;;
      esac
      ;;

    interix[[3-9]]*)
      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
      # Instead, we relocate shared libraries at runtime.
      ;;

    msdosdjgpp*)
      # Just because we use GCC doesn't mean we suddenly get shared libraries
      # on systems that don't support them.
      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
      enable_shared=no
      ;;

    *nto* | *qnx*)
      # QNX uses GNU C++, but need to define -shared option too, otherwise
      # it will coredump.
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
      ;;

    sysv4*MP*)
      if test -d /usr/nec; then
	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
      fi
      ;;

    *)
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
      ;;
    esac
  else
    # PORTME Check for flag to pass linker flags through the system compiler.
    case $host_os in
    aix*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      if test "$host_cpu" = ia64; then
	# AIX 5 now supports IA64 processor
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      else
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
      fi
      ;;

    mingw* | cygwin* | pw32* | os2* | cegcc*)
      # This hack is so that the source file can tell whether it is being
      # built for inclusion in a dll (and should export symbols for example).
      m4_if([$1], [GCJ], [],
	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
      ;;

    hpux9* | hpux10* | hpux11*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
      # not for PA HP-UX.
      case $host_cpu in
      hppa*64*|ia64*)
	# +Z the default
	;;
      *)
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
	;;
      esac
      # Is there a better lt_prog_compiler_static that works with the bundled CC?
      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
      ;;

    irix5* | irix6* | nonstopux*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      # PIC (with -KPIC) is the default.
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
      ;;

    linux* | k*bsd*-gnu)
      case $cc_basename in
      # old Intel for x86_64 which still supported -KPIC.
      ecc*)
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
        ;;
      # icc used to be incompatible with GCC.
      # ICC 10 doesn't accept -KPIC any more.
      icc* | ifort*)
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
        ;;
      # Lahey Fortran 8.1.
      lf95*)
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
	;;
      pgcc* | pgf77* | pgf90* | pgf95*)
        # Portland Group compilers (*not* the Pentium gcc compiler,
	# which looks to be a dead project)
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
        ;;
      ccc*)
        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
        # All Alpha code is PIC.
        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
        ;;
      xl*)
	# IBM XL C 8.0/Fortran 10.1 on PPC
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
	;;
      *)
	case `$CC -V 2>&1 | sed 5q` in
	*Sun\ C*)
	  # Sun C 5.9
	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
	  ;;
	*Sun\ F*)
	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
	  ;;
	esac
	;;
      esac
      ;;

    newsos6)
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      ;;

    *nto* | *qnx*)
      # QNX uses GNU C++, but need to define -shared option too, otherwise
      # it will coredump.
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
      ;;

    osf3* | osf4* | osf5*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      # All OSF/1 code is PIC.
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
      ;;

    rdos*)
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
      ;;

    solaris*)
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      case $cc_basename in
      f77* | f90* | f95*)
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
      *)
	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
      esac
      ;;

    sunos4*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      ;;

    sysv4 | sysv4.2uw2* | sysv4.3*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      ;;

    sysv4*MP*)
      if test -d /usr/nec ;then
	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      fi
      ;;

    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      ;;

    unicos*)
      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
      ;;

    uts4*)
      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
      ;;

    *)
      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
      ;;
    esac
  fi
])
case $host_os in
  # For platforms which do not support PIC, -DPIC is meaningless:
  *djgpp*)
    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
    ;;
  *)
    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
    ;;
esac
AC_MSG_RESULT([$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
	[How to pass a linker flag through the compiler])

#
# Check to make sure the PIC flag actually works.
#
if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
     "" | " "*) ;;
     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
     esac],
    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
fi
_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
	[Additional compiler flags for building library objects])

#
# Check to make sure the static flag actually works.
#
wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
  $lt_tmp_static_flag,
  [],
  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
	[Compiler flag to prevent dynamic linking])
])# _LT_COMPILER_PIC


# _LT_LINKER_SHLIBS([TAGNAME])
# ----------------------------
# See if the linker supports building shared libraries.
m4_defun([_LT_LINKER_SHLIBS],
[AC_REQUIRE([LT_PATH_LD])dnl
AC_REQUIRE([LT_PATH_NM])dnl
m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_DECL_EGREP])dnl
m4_require([_LT_DECL_SED])dnl
m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
m4_require([_LT_TAG_COMPILER])dnl
AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
m4_if([$1], [CXX], [
  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
  case $host_os in
  aix[[4-9]]*)
    # If we're using GNU nm, then we don't want the "-C" option.
    # -C means demangle to AIX nm, but means don't demangle with GNU nm
    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
    else
      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
    fi
    ;;
  pw32*)
    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
  ;;
  cygwin* | mingw* | cegcc*)
    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
  ;;
  *)
    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
  ;;
  esac
  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
], [
  runpath_var=
  _LT_TAGVAR(allow_undefined_flag, $1)=
  _LT_TAGVAR(always_export_symbols, $1)=no
  _LT_TAGVAR(archive_cmds, $1)=
  _LT_TAGVAR(archive_expsym_cmds, $1)=
  _LT_TAGVAR(compiler_needs_object, $1)=no
  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
  _LT_TAGVAR(hardcode_automatic, $1)=no
  _LT_TAGVAR(hardcode_direct, $1)=no
  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
  _LT_TAGVAR(hardcode_libdir_separator, $1)=
  _LT_TAGVAR(hardcode_minus_L, $1)=no
  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
  _LT_TAGVAR(inherit_rpath, $1)=no
  _LT_TAGVAR(link_all_deplibs, $1)=unknown
  _LT_TAGVAR(module_cmds, $1)=
  _LT_TAGVAR(module_expsym_cmds, $1)=
  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
  _LT_TAGVAR(thread_safe_flag_spec, $1)=
  _LT_TAGVAR(whole_archive_flag_spec, $1)=
  # include_expsyms should be a list of space-separated symbols to be *always*
  # included in the symbol list
  _LT_TAGVAR(include_expsyms, $1)=
  # exclude_expsyms can be an extended regexp of symbols to exclude
  # it will be wrapped by ` (' and `)$', so one must not match beginning or
  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
  # as well as any symbol that contains `d'.
  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
  # platforms (ab)use it in PIC code, but their linkers get confused if
  # the symbol is explicitly referenced.  Since portable code cannot
  # rely on this symbol name, it's probably fine to never include it in
  # preloaded symbol tables.
  # Exclude shared library initialization/finalization symbols.
dnl Note also adjust exclude_expsyms for C++ above.
  extract_expsyms_cmds=

  case $host_os in
  cygwin* | mingw* | pw32* | cegcc*)
    # FIXME: the MSVC++ port hasn't been tested in a loooong time
    # When not using gcc, we currently assume that we are using
    # Microsoft Visual C++.
    if test "$GCC" != yes; then
      with_gnu_ld=no
    fi
    ;;
  interix*)
    # we just hope/assume this is gcc and not c89 (= MSVC++)
    with_gnu_ld=yes
    ;;
  openbsd*)
    with_gnu_ld=no
    ;;
  esac

  _LT_TAGVAR(ld_shlibs, $1)=yes
  if test "$with_gnu_ld" = yes; then
    # If archive_cmds runs LD, not CC, wlarc should be empty
    wlarc='${wl}'

    # Set some defaults for GNU ld with shared library support. These
    # are reset later if shared libraries are not supported. Putting them
    # here allows them to be overridden if necessary.
    runpath_var=LD_RUN_PATH
    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
    # ancient GNU ld didn't support --whole-archive et. al.
    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
    else
      _LT_TAGVAR(whole_archive_flag_spec, $1)=
    fi
    supports_anon_versioning=no
    case `$LD -v 2>&1` in
      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
      *\ 2.11.*) ;; # other 2.11 versions
      *) supports_anon_versioning=yes ;;
    esac

    # See if GNU ld supports shared libraries.
    case $host_os in
    aix[[3-9]]*)
      # On AIX/PPC, the GNU linker is very broken
      if test "$host_cpu" != ia64; then
	_LT_TAGVAR(ld_shlibs, $1)=no
	cat <<_LT_EOF 1>&2

*** Warning: the GNU linker, at least up to release 2.9.1, is reported
*** to be unable to reliably create shared libraries on AIX.
*** Therefore, libtool is disabling shared libraries support.  If you
*** really care for shared libraries, you may want to modify your PATH
*** so that a non-GNU linker is found, and then restart.

_LT_EOF
      fi
      ;;

    amigaos*)
      case $host_cpu in
      powerpc)
            # see comment about AmigaOS4 .so support
            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
            _LT_TAGVAR(archive_expsym_cmds, $1)=''
        ;;
      m68k)
            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
            _LT_TAGVAR(hardcode_minus_L, $1)=yes
        ;;
      esac
      ;;

    beos*)
      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
	# Joseph Beckenbach <jrb3@best.com> says some releases of gcc
	# support --undefined.  This deserves some investigation.  FIXME
	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
      else
	_LT_TAGVAR(ld_shlibs, $1)=no
      fi
      ;;

    cygwin* | mingw* | pw32* | cegcc*)
      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
      # as there is no search path for DLLs.
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
      _LT_TAGVAR(always_export_symbols, $1)=no
      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'

      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
	# If the export-symbols file already is a .def file (1st line
	# is EXPORTS), use it as is; otherwise, prepend...
	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
	  cp $export_symbols $output_objdir/$soname.def;
	else
	  echo EXPORTS > $output_objdir/$soname.def;
	  cat $export_symbols >> $output_objdir/$soname.def;
	fi~
	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
      else
	_LT_TAGVAR(ld_shlibs, $1)=no
      fi
      ;;

    interix[[3-9]]*)
      _LT_TAGVAR(hardcode_direct, $1)=no
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
      # Instead, shared libraries are loaded at an image base (0x10000000 by
      # default) and relocated if they conflict, which is a slow very memory
      # consuming and fragmenting process.  To avoid this, we pick a random,
      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
      ;;

    gnu* | linux* | tpf* | k*bsd*-gnu)
      tmp_diet=no
      if test "$host_os" = linux-dietlibc; then
	case $cc_basename in
	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
	esac
      fi
      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
	 && test "$tmp_diet" = no
      then
	tmp_addflag=
	tmp_sharedflag='-shared'
	case $cc_basename,$host_cpu in
        pgcc*)				# Portland Group C compiler
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
	  tmp_addflag=' $pic_flag'
	  ;;
	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
	  tmp_addflag=' $pic_flag -Mnomain' ;;
	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
	  tmp_addflag=' -i_dynamic' ;;
	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
	  tmp_addflag=' -i_dynamic -nofor_main' ;;
	ifc* | ifort*)			# Intel Fortran compiler
	  tmp_addflag=' -nofor_main' ;;
	lf95*)				# Lahey Fortran 8.1
	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
	  tmp_sharedflag='--shared' ;;
	xl[[cC]]*)			# IBM XL C 8.0 on PPC (deal with xlf below)
	  tmp_sharedflag='-qmkshrobj'
	  tmp_addflag= ;;
	esac
	case `$CC -V 2>&1 | sed 5q` in
	*Sun\ C*)			# Sun C 5.9
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
	  _LT_TAGVAR(compiler_needs_object, $1)=yes
	  tmp_sharedflag='-G' ;;
	*Sun\ F*)			# Sun Fortran 8.3
	  tmp_sharedflag='-G' ;;
	esac
	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'

        if test "x$supports_anon_versioning" = xyes; then
          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
	    echo "local: *; };" >> $output_objdir/$libname.ver~
	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
        fi

	case $cc_basename in
	xlf*)
	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
	  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir'
	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib'
	  if test "x$supports_anon_versioning" = xyes; then
	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
	      echo "local: *; };" >> $output_objdir/$libname.ver~
	      $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
	  fi
	  ;;
	esac
      else
        _LT_TAGVAR(ld_shlibs, $1)=no
      fi
      ;;

    netbsd*)
      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
	wlarc=
      else
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
      fi
      ;;

    solaris*)
      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
	_LT_TAGVAR(ld_shlibs, $1)=no
	cat <<_LT_EOF 1>&2

*** Warning: The releases 2.8.* of the GNU linker cannot reliably
*** create shared libraries on Solaris systems.  Therefore, libtool
*** is disabling shared libraries support.  We urge you to upgrade GNU
*** binutils to release 2.9.1 or newer.  Another option is to modify
*** your PATH or compiler configuration so that the native linker is
*** used, and then restart.

_LT_EOF
      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
      else
	_LT_TAGVAR(ld_shlibs, $1)=no
      fi
      ;;

    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
      case `$LD -v 2>&1` in
        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
	_LT_TAGVAR(ld_shlibs, $1)=no
	cat <<_LT_EOF 1>&2

*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
*** reliably create shared libraries on SCO systems.  Therefore, libtool
*** is disabling shared libraries support.  We urge you to upgrade GNU
*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
*** your PATH or compiler configuration so that the native linker is
*** used, and then restart.

_LT_EOF
	;;
	*)
	  # For security reasons, it is highly recommended that you always
	  # use absolute paths for naming shared libraries, and exclude the
	  # DT_RUNPATH tag from executables and libraries.  But doing so
	  # requires that you compile everything twice, which is a pain.
	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
	  else
	    _LT_TAGVAR(ld_shlibs, $1)=no
	  fi
	;;
      esac
      ;;

    sunos4*)
      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
      wlarc=
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    *)
      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
      else
	_LT_TAGVAR(ld_shlibs, $1)=no
      fi
      ;;
    esac

    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
      runpath_var=
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
      _LT_TAGVAR(whole_archive_flag_spec, $1)=
    fi
  else
    # PORTME fill in a description of your system's linker (not GNU ld)
    case $host_os in
    aix3*)
      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
      _LT_TAGVAR(always_export_symbols, $1)=yes
      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
      # Note: this linker hardcodes the directories in LIBPATH if there
      # are no directories specified by -L.
      _LT_TAGVAR(hardcode_minus_L, $1)=yes
      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
	# Neither direct hardcoding nor static linking is supported with a
	# broken collect2.
	_LT_TAGVAR(hardcode_direct, $1)=unsupported
      fi
      ;;

    aix[[4-9]]*)
      if test "$host_cpu" = ia64; then
	# On IA64, the linker does run time linking by default, so we don't
	# have to do anything special.
	aix_use_runtimelinking=no
	exp_sym_flag='-Bexport'
	no_entry_flag=""
      else
	# If we're using GNU nm, then we don't want the "-C" option.
	# -C means demangle to AIX nm, but means don't demangle with GNU nm
	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
	else
	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
	fi
	aix_use_runtimelinking=no

	# Test if we are trying to use run time linking or normal
	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
	# need to do runtime linking.
	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
	  for ld_flag in $LDFLAGS; do
	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
	    aix_use_runtimelinking=yes
	    break
	  fi
	  done
	  ;;
	esac

	exp_sym_flag='-bexport'
	no_entry_flag='-bnoentry'
      fi

      # When large executables or shared objects are built, AIX ld can
      # have problems creating the table of contents.  If linking a library
      # or program results in "error TOC overflow" add -mminimal-toc to
      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.

      _LT_TAGVAR(archive_cmds, $1)=''
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
      _LT_TAGVAR(link_all_deplibs, $1)=yes
      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'

      if test "$GCC" = yes; then
	case $host_os in aix4.[[012]]|aix4.[[012]].*)
	# We only want to do this on AIX 4.2 and lower, the check
	# below for broken collect2 doesn't work under 4.3+
	  collect2name=`${CC} -print-prog-name=collect2`
	  if test -f "$collect2name" &&
	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
	  then
	  # We have reworked collect2
	  :
	  else
	  # We have old collect2
	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
	  # It fails to find uninstalled libraries when the uninstalled
	  # path is not listed in the libpath.  Setting hardcode_minus_L
	  # to unsupported forces relinking
	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
	  fi
	  ;;
	esac
	shared_flag='-shared'
	if test "$aix_use_runtimelinking" = yes; then
	  shared_flag="$shared_flag "'${wl}-G'
	fi
      else
	# not using gcc
	if test "$host_cpu" = ia64; then
	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
	# chokes on -Wl,-G. The following line is correct:
	  shared_flag='-G'
	else
	  if test "$aix_use_runtimelinking" = yes; then
	    shared_flag='${wl}-G'
	  else
	    shared_flag='${wl}-bM:SRE'
	  fi
	fi
      fi

      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
      # It seems that -bexpall does not export symbols beginning with
      # underscore (_), so it is better to generate a list of symbols to export.
      _LT_TAGVAR(always_export_symbols, $1)=yes
      if test "$aix_use_runtimelinking" = yes; then
	# Warning - without using the other runtime loading flags (-brtl),
	# -berok will link without error, but may produce a broken library.
	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
        # Determine the default libpath from the value encoded in an
        # empty executable.
        _LT_SYS_MODULE_PATH_AIX
        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
      else
	if test "$host_cpu" = ia64; then
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
	else
	 # Determine the default libpath from the value encoded in an
	 # empty executable.
	 _LT_SYS_MODULE_PATH_AIX
	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
	  # Warning - without using the other run time loading flags,
	  # -berok will link without error, but may produce a broken library.
	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
	  # Exported symbols can be pulled into shared objects from archives
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
	  # This is similar to how AIX traditionally builds its shared libraries.
	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
	fi
      fi
      ;;

    amigaos*)
      case $host_cpu in
      powerpc)
            # see comment about AmigaOS4 .so support
            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
            _LT_TAGVAR(archive_expsym_cmds, $1)=''
        ;;
      m68k)
            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
            _LT_TAGVAR(hardcode_minus_L, $1)=yes
        ;;
      esac
      ;;

    bsdi[[45]]*)
      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
      ;;

    cygwin* | mingw* | pw32* | cegcc*)
      # When not using gcc, we currently assume that we are using
      # Microsoft Visual C++.
      # hardcode_libdir_flag_spec is actually meaningless, as there is
      # no search path for DLLs.
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
      # Tell ltmain to make .lib files, not .a files.
      libext=lib
      # Tell ltmain to make .dll files, not .so files.
      shrext_cmds=".dll"
      # FIXME: Setting linknames here is a bad hack.
      _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames='
      # The linker will automatically build a .lib file if we build a DLL.
      _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
      # FIXME: Should let the user specify the lib program.
      _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
      _LT_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`'
      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
      ;;

    darwin* | rhapsody*)
      _LT_DARWIN_LINKER_FEATURES($1)
      ;;

    dgux*)
      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    freebsd1*)
      _LT_TAGVAR(ld_shlibs, $1)=no
      ;;

    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
    # support.  Future versions do this automatically, but an explicit c++rt0.o
    # does not break anything, and helps significantly (at the cost of a little
    # extra space).
    freebsd2.2*)
      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
    freebsd2*)
      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_minus_L, $1)=yes
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
    freebsd* | dragonfly*)
      _LT_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    hpux9*)
      if test "$GCC" = yes; then
	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
      else
	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
      fi
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
      _LT_TAGVAR(hardcode_direct, $1)=yes

      # hardcode_minus_L: Not really in the search PATH,
      # but as the default location of the library.
      _LT_TAGVAR(hardcode_minus_L, $1)=yes
      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
      ;;

    hpux10*)
      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
      else
	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
      fi
      if test "$with_gnu_ld" = no; then
	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
	_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
	_LT_TAGVAR(hardcode_direct, $1)=yes
	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
	# hardcode_minus_L: Not really in the search PATH,
	# but as the default location of the library.
	_LT_TAGVAR(hardcode_minus_L, $1)=yes
      fi
      ;;

    hpux11*)
      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
	case $host_cpu in
	hppa*64*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	ia64*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	esac
      else
	case $host_cpu in
	hppa*64*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	ia64*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	esac
      fi
      if test "$with_gnu_ld" = no; then
	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
	_LT_TAGVAR(hardcode_libdir_separator, $1)=:

	case $host_cpu in
	hppa*64*|ia64*)
	  _LT_TAGVAR(hardcode_direct, $1)=no
	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	  ;;
	*)
	  _LT_TAGVAR(hardcode_direct, $1)=yes
	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'

	  # hardcode_minus_L: Not really in the search PATH,
	  # but as the default location of the library.
	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
	  ;;
	esac
      fi
      ;;

    irix5* | irix6* | nonstopux*)
      if test "$GCC" = yes; then
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
	# Try to use the -exported_symbol ld option, if it does not
	# work, assume that -exports_file does not work either and
	# implicitly export all symbols.
        save_LDFLAGS="$LDFLAGS"
        LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
        AC_LINK_IFELSE(int foo(void) {},
          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
        )
        LDFLAGS="$save_LDFLAGS"
      else
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
      fi
      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
      _LT_TAGVAR(inherit_rpath, $1)=yes
      _LT_TAGVAR(link_all_deplibs, $1)=yes
      ;;

    netbsd*)
      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
      else
	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
      fi
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    newsos6)
      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    *nto* | *qnx*)
      ;;

    openbsd*)
      if test -f /usr/libexec/ld.so; then
	_LT_TAGVAR(hardcode_direct, $1)=yes
	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
	else
	  case $host_os in
	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
	     ;;
	   *)
	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	     ;;
	  esac
	fi
      else
	_LT_TAGVAR(ld_shlibs, $1)=no
      fi
      ;;

    os2*)
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
      _LT_TAGVAR(hardcode_minus_L, $1)=yes
      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
      ;;

    osf3*)
      if test "$GCC" = yes; then
	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
      else
	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
      fi
      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
      ;;

    osf4* | osf5*)	# as osf3* with the addition of -msym flag
      if test "$GCC" = yes; then
	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
      else
	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'

	# Both c and cxx compiler support -rpath directly
	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
      fi
      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
      ;;

    solaris*)
      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
      if test "$GCC" = yes; then
	wlarc='${wl}'
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
	  $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
      else
	case `$CC -V 2>&1` in
	*"Compilers 5.0"*)
	  wlarc=''
	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
	  ;;
	*)
	  wlarc='${wl}'
	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
	  ;;
	esac
      fi
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      case $host_os in
      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
      *)
	# The compiler driver will combine and reorder linker options,
	# but understands `-z linker_flag'.  GCC discards it without `$wl',
	# but is careful enough not to reorder.
	# Supported since Solaris 2.6 (maybe 2.5.1?)
	if test "$GCC" = yes; then
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
	else
	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
	fi
	;;
      esac
      _LT_TAGVAR(link_all_deplibs, $1)=yes
      ;;

    sunos4*)
      if test "x$host_vendor" = xsequent; then
	# Use $CC to link under sequent, because it throws in some extra .o
	# files that make .init and .fini sections work.
	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
      else
	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
      fi
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
      _LT_TAGVAR(hardcode_direct, $1)=yes
      _LT_TAGVAR(hardcode_minus_L, $1)=yes
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    sysv4)
      case $host_vendor in
	sni)
	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
	;;
	siemens)
	  ## LD is ld it makes a PLAMLIB
	  ## CC just makes a GrossModule.
	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
	  _LT_TAGVAR(hardcode_direct, $1)=no
        ;;
	motorola)
	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
	;;
      esac
      runpath_var='LD_RUN_PATH'
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    sysv4.3*)
      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
      ;;

    sysv4*MP*)
      if test -d /usr/nec; then
	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	runpath_var=LD_RUN_PATH
	hardcode_runpath_var=yes
	_LT_TAGVAR(ld_shlibs, $1)=yes
      fi
      ;;

    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      runpath_var='LD_RUN_PATH'

      if test "$GCC" = yes; then
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
      else
	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
      fi
      ;;

    sysv5* | sco3.2v5* | sco5v6*)
      # Note: We can NOT use -z defs as we might desire, because we do not
      # link with -lc, and that would cause any symbols used from libc to
      # always be unresolved, which means just about no library would
      # ever link correctly.  If we're not using GNU ld we use -z text
      # though, which does catch some bad symbols but isn't as heavy-handed
      # as -z defs.
      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
      _LT_TAGVAR(link_all_deplibs, $1)=yes
      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
      runpath_var='LD_RUN_PATH'

      if test "$GCC" = yes; then
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
      else
	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
      fi
      ;;

    uts4*)
      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      ;;

    *)
      _LT_TAGVAR(ld_shlibs, $1)=no
      ;;
    esac

    if test x$host_vendor = xsni; then
      case $host in
      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
	;;
      esac
    fi
  fi
])
AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no

_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld

_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
_LT_DECL([], [extract_expsyms_cmds], [2],
    [The commands to extract the exported symbol list from a shared archive])

#
# Do we need to explicitly link libc?
#
case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
x|xyes)
  # Assume -lc should be added
  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes

  if test "$enable_shared" = yes && test "$GCC" = yes; then
    case $_LT_TAGVAR(archive_cmds, $1) in
    *'~'*)
      # FIXME: we may have to deal with multi-command sequences.
      ;;
    '$CC '*)
      # Test whether the compiler implicitly links with -lc since on some
      # systems, -lgcc has to come before -lc. If gcc already passes -lc
      # to ld, don't add -lc before -lgcc.
      AC_MSG_CHECKING([whether -lc should be explicitly linked in])
      $RM conftest*
      echo "$lt_simple_compile_test_code" > conftest.$ac_ext

      if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
        soname=conftest
        lib=conftest
        libobjs=conftest.$ac_objext
        deplibs=
        wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
	pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
        compiler_flags=-v
        linker_flags=-v
        verstring=
        output_objdir=.
        libname=conftest
        lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
        _LT_TAGVAR(allow_undefined_flag, $1)=
        if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
        then
	  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
        else
	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
        fi
        _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
      else
        cat conftest.err 1>&5
      fi
      $RM conftest*
      AC_MSG_RESULT([$_LT_TAGVAR(archive_cmds_need_lc, $1)])
      ;;
    esac
  fi
  ;;
esac

_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
    [Whether or not to add -lc for building shared libraries])
_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
    [enable_shared_with_static_runtimes], [0],
    [Whether or not to disallow shared libs when runtime libs are static])
_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
    [Compiler flag to allow reflexive dlopens])
_LT_TAGDECL([], [whole_archive_flag_spec], [1],
    [Compiler flag to generate shared objects directly from archives])
_LT_TAGDECL([], [compiler_needs_object], [1],
    [Whether the compiler copes with passing no objects directly])
_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
    [Create an old-style archive from a shared archive])
_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
    [Create a temporary old-style archive to link instead of a shared archive])
_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
_LT_TAGDECL([], [archive_expsym_cmds], [2])
_LT_TAGDECL([], [module_cmds], [2],
    [Commands used to build a loadable module if different from building
    a shared archive.])
_LT_TAGDECL([], [module_expsym_cmds], [2])
_LT_TAGDECL([], [with_gnu_ld], [1],
    [Whether we are building with GNU ld or not])
_LT_TAGDECL([], [allow_undefined_flag], [1],
    [Flag that allows shared libraries with undefined symbols to be built])
_LT_TAGDECL([], [no_undefined_flag], [1],
    [Flag that enforces no undefined symbols])
_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
    [Flag to hardcode $libdir into a binary during linking.
    This must work even if $libdir does not exist])
_LT_TAGDECL([], [hardcode_libdir_flag_spec_ld], [1],
    [[If ld is used when linking, flag to hardcode $libdir into a binary
    during linking.  This must work even if $libdir does not exist]])
_LT_TAGDECL([], [hardcode_libdir_separator], [1],
    [Whether we need a single "-rpath" flag with a separated argument])
_LT_TAGDECL([], [hardcode_direct], [0],
    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
    DIR into the resulting binary])
_LT_TAGDECL([], [hardcode_direct_absolute], [0],
    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
    DIR into the resulting binary and the resulting library dependency is
    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
    library is relocated])
_LT_TAGDECL([], [hardcode_minus_L], [0],
    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
    into the resulting binary])
_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
    into the resulting binary])
_LT_TAGDECL([], [hardcode_automatic], [0],
    [Set to "yes" if building a shared library automatically hardcodes DIR
    into the library and all subsequent libraries and executables linked
    against it])
_LT_TAGDECL([], [inherit_rpath], [0],
    [Set to yes if linker adds runtime paths of dependent libraries
    to runtime path list])
_LT_TAGDECL([], [link_all_deplibs], [0],
    [Whether libtool must link a program against all its dependency libraries])
_LT_TAGDECL([], [fix_srcfile_path], [1],
    [Fix the shell variable $srcfile for the compiler])
_LT_TAGDECL([], [always_export_symbols], [0],
    [Set to "yes" if exported symbols are required])
_LT_TAGDECL([], [export_symbols_cmds], [2],
    [The commands to list exported symbols])
_LT_TAGDECL([], [exclude_expsyms], [1],
    [Symbols that should not be listed in the preloaded symbols])
_LT_TAGDECL([], [include_expsyms], [1],
    [Symbols that must always be exported])
_LT_TAGDECL([], [prelink_cmds], [2],
    [Commands necessary for linking programs (against libraries) with templates])
_LT_TAGDECL([], [file_list_spec], [1],
    [Specify filename containing input files])
dnl FIXME: Not yet implemented
dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
dnl    [Compiler flag to generate thread safe objects])
])# _LT_LINKER_SHLIBS


# _LT_LANG_C_CONFIG([TAG])
# ------------------------
# Ensure that the configuration variables for a C compiler are suitably
# defined.  These variables are subsequently used by _LT_CONFIG to write
# the compiler configuration to `libtool'.
m4_defun([_LT_LANG_C_CONFIG],
[m4_require([_LT_DECL_EGREP])dnl
lt_save_CC="$CC"
AC_LANG_PUSH(C)

# Source file extension for C test sources.
ac_ext=c

# Object file extension for compiled C test sources.
objext=o
_LT_TAGVAR(objext, $1)=$objext

# Code to be used in simple compile tests
lt_simple_compile_test_code="int some_variable = 0;"

# Code to be used in simple link tests
lt_simple_link_test_code='int main(){return(0);}'

_LT_TAG_COMPILER
# Save the default compiler, since it gets overwritten when the other
# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
compiler_DEFAULT=$CC

# save warnings/boilerplate of simple test code
_LT_COMPILER_BOILERPLATE
_LT_LINKER_BOILERPLATE

if test -n "$compiler"; then
  _LT_COMPILER_NO_RTTI($1)
  _LT_COMPILER_PIC($1)
  _LT_COMPILER_C_O($1)
  _LT_COMPILER_FILE_LOCKS($1)
  _LT_LINKER_SHLIBS($1)
  _LT_SYS_DYNAMIC_LINKER($1)
  _LT_LINKER_HARDCODE_LIBPATH($1)
  LT_SYS_DLOPEN_SELF
  _LT_CMD_STRIPLIB

  # Report which library types will actually be built
  AC_MSG_CHECKING([if libtool supports shared libraries])
  AC_MSG_RESULT([$can_build_shared])

  AC_MSG_CHECKING([whether to build shared libraries])
  test "$can_build_shared" = "no" && enable_shared=no

  # On AIX, shared libraries and static libraries use the same namespace, and
  # are all built from PIC.
  case $host_os in
  aix3*)
    test "$enable_shared" = yes && enable_static=no
    if test -n "$RANLIB"; then
      archive_cmds="$archive_cmds~\$RANLIB \$lib"
      postinstall_cmds='$RANLIB $lib'
    fi
    ;;

  aix[[4-9]]*)
    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
      test "$enable_shared" = yes && enable_static=no
    fi
    ;;
  esac
  AC_MSG_RESULT([$enable_shared])

  AC_MSG_CHECKING([whether to build static libraries])
  # Make sure either enable_shared or enable_static is yes.
  test "$enable_shared" = yes || enable_static=yes
  AC_MSG_RESULT([$enable_static])

  _LT_CONFIG($1)
fi
AC_LANG_POP
CC="$lt_save_CC"
])# _LT_LANG_C_CONFIG


# _LT_PROG_CXX
# ------------
# Since AC_PROG_CXX is broken, in that it returns g++ if there is no c++
# compiler, we have our own version here.
m4_defun([_LT_PROG_CXX],
[
pushdef([AC_MSG_ERROR], [_lt_caught_CXX_error=yes])
AC_PROG_CXX
if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
    (test "X$CXX" != "Xg++"))) ; then
  AC_PROG_CXXCPP
else
  _lt_caught_CXX_error=yes
fi
popdef([AC_MSG_ERROR])
])# _LT_PROG_CXX

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([_LT_PROG_CXX], [])


# _LT_LANG_CXX_CONFIG([TAG])
# --------------------------
# Ensure that the configuration variables for a C++ compiler are suitably
# defined.  These variables are subsequently used by _LT_CONFIG to write
# the compiler configuration to `libtool'.
m4_defun([_LT_LANG_CXX_CONFIG],
[AC_REQUIRE([_LT_PROG_CXX])dnl
m4_require([_LT_FILEUTILS_DEFAULTS])dnl
m4_require([_LT_DECL_EGREP])dnl

AC_LANG_PUSH(C++)
_LT_TAGVAR(archive_cmds_need_lc, $1)=no
_LT_TAGVAR(allow_undefined_flag, $1)=
_LT_TAGVAR(always_export_symbols, $1)=no
_LT_TAGVAR(archive_expsym_cmds, $1)=
_LT_TAGVAR(compiler_needs_object, $1)=no
_LT_TAGVAR(export_dynamic_flag_spec, $1)=
_LT_TAGVAR(hardcode_direct, $1)=no
_LT_TAGVAR(hardcode_direct_absolute, $1)=no
_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
_LT_TAGVAR(hardcode_libdir_separator, $1)=
_LT_TAGVAR(hardcode_minus_L, $1)=no
_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
_LT_TAGVAR(hardcode_automatic, $1)=no
_LT_TAGVAR(inherit_rpath, $1)=no
_LT_TAGVAR(module_cmds, $1)=
_LT_TAGVAR(module_expsym_cmds, $1)=
_LT_TAGVAR(link_all_deplibs, $1)=unknown
_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
_LT_TAGVAR(no_undefined_flag, $1)=
_LT_TAGVAR(whole_archive_flag_spec, $1)=
_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no

# Source file extension for C++ test sources.
ac_ext=cpp

# Object file extension for compiled C++ test sources.
objext=o
_LT_TAGVAR(objext, $1)=$objext

# No sense in running all these tests if we already determined that
# the CXX compiler isn't working.  Some variables (like enable_shared)
# are currently assumed to apply to all compilers on this platform,
# and will be corrupted by setting them based on a non-working compiler.
if test "$_lt_caught_CXX_error" != yes; then
  # Code to be used in simple compile tests
  lt_simple_compile_test_code="int some_variable = 0;"

  # Code to be used in simple link tests
  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'

  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
  _LT_TAG_COMPILER

  # save warnings/boilerplate of simple test code
  _LT_COMPILER_BOILERPLATE
  _LT_LINKER_BOILERPLATE

  # Allow CC to be a program name with arguments.
  lt_save_CC=$CC
  lt_save_LD=$LD
  lt_save_GCC=$GCC
  GCC=$GXX
  lt_save_with_gnu_ld=$with_gnu_ld
  lt_save_path_LD=$lt_cv_path_LD
  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
  else
    $as_unset lt_cv_prog_gnu_ld
  fi
  if test -n "${lt_cv_path_LDCXX+set}"; then
    lt_cv_path_LD=$lt_cv_path_LDCXX
  else
    $as_unset lt_cv_path_LD
  fi
  test -z "${LDCXX+set}" || LD=$LDCXX
  CC=${CXX-"c++"}
  compiler=$CC
  _LT_TAGVAR(compiler, $1)=$CC
  _LT_CC_BASENAME([$compiler])

  if test -n "$compiler"; then
    # We don't want -fno-exception when compiling C++ code, so set the
    # no_builtin_flag separately
    if test "$GXX" = yes; then
      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
    else
      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
    fi

    if test "$GXX" = yes; then
      # Set up default GNU C++ configuration

      LT_PATH_LD

      # Check if GNU C++ uses GNU ld as the underlying linker, since the
      # archiving commands below assume that GNU ld is being used.
      if test "$with_gnu_ld" = yes; then
        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'

        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'

        # If archive_cmds runs LD, not CC, wlarc should be empty
        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
        #     investigate it a little bit more. (MM)
        wlarc='${wl}'

        # ancient GNU ld didn't support --whole-archive et. al.
        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
	  $GREP 'no-whole-archive' > /dev/null; then
          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
        else
          _LT_TAGVAR(whole_archive_flag_spec, $1)=
        fi
      else
        with_gnu_ld=no
        wlarc=

        # A generic and very simple default shared library creation
        # command for GNU C++ for the case where it uses the native
        # linker, instead of GNU ld.  If possible, this setting should
        # overridden to take advantage of the native linker features on
        # the platform it is being used on.
        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
      fi

      # Commands to make compiler produce verbose output that lists
      # what "hidden" libraries, object files and flags are used when
      # linking a shared library.
      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'

    else
      GXX=no
      with_gnu_ld=no
      wlarc=
    fi

    # PORTME: fill in a description of your system's C++ link characteristics
    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
    _LT_TAGVAR(ld_shlibs, $1)=yes
    case $host_os in
      aix3*)
        # FIXME: insert proper C++ library support
        _LT_TAGVAR(ld_shlibs, $1)=no
        ;;
      aix[[4-9]]*)
        if test "$host_cpu" = ia64; then
          # On IA64, the linker does run time linking by default, so we don't
          # have to do anything special.
          aix_use_runtimelinking=no
          exp_sym_flag='-Bexport'
          no_entry_flag=""
        else
          aix_use_runtimelinking=no

          # Test if we are trying to use run time linking or normal
          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
          # need to do runtime linking.
          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
	    for ld_flag in $LDFLAGS; do
	      case $ld_flag in
	      *-brtl*)
	        aix_use_runtimelinking=yes
	        break
	        ;;
	      esac
	    done
	    ;;
          esac

          exp_sym_flag='-bexport'
          no_entry_flag='-bnoentry'
        fi

        # When large executables or shared objects are built, AIX ld can
        # have problems creating the table of contents.  If linking a library
        # or program results in "error TOC overflow" add -mminimal-toc to
        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.

        _LT_TAGVAR(archive_cmds, $1)=''
        _LT_TAGVAR(hardcode_direct, $1)=yes
        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
        _LT_TAGVAR(link_all_deplibs, $1)=yes
        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'

        if test "$GXX" = yes; then
          case $host_os in aix4.[[012]]|aix4.[[012]].*)
          # We only want to do this on AIX 4.2 and lower, the check
          # below for broken collect2 doesn't work under 4.3+
	  collect2name=`${CC} -print-prog-name=collect2`
	  if test -f "$collect2name" &&
	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
	  then
	    # We have reworked collect2
	    :
	  else
	    # We have old collect2
	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
	    # It fails to find uninstalled libraries when the uninstalled
	    # path is not listed in the libpath.  Setting hardcode_minus_L
	    # to unsupported forces relinking
	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
	  fi
          esac
          shared_flag='-shared'
	  if test "$aix_use_runtimelinking" = yes; then
	    shared_flag="$shared_flag "'${wl}-G'
	  fi
        else
          # not using gcc
          if test "$host_cpu" = ia64; then
	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
	  # chokes on -Wl,-G. The following line is correct:
	  shared_flag='-G'
          else
	    if test "$aix_use_runtimelinking" = yes; then
	      shared_flag='${wl}-G'
	    else
	      shared_flag='${wl}-bM:SRE'
	    fi
          fi
        fi

        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
        # It seems that -bexpall does not export symbols beginning with
        # underscore (_), so it is better to generate a list of symbols to
	# export.
        _LT_TAGVAR(always_export_symbols, $1)=yes
        if test "$aix_use_runtimelinking" = yes; then
          # Warning - without using the other runtime loading flags (-brtl),
          # -berok will link without error, but may produce a broken library.
          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
          # Determine the default libpath from the value encoded in an empty
          # executable.
          _LT_SYS_MODULE_PATH_AIX
          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"

          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
        else
          if test "$host_cpu" = ia64; then
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
          else
	    # Determine the default libpath from the value encoded in an
	    # empty executable.
	    _LT_SYS_MODULE_PATH_AIX
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
	    # Warning - without using the other run time loading flags,
	    # -berok will link without error, but may produce a broken library.
	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
	    # Exported symbols can be pulled into shared objects from archives
	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
	    # This is similar to how AIX traditionally builds its shared
	    # libraries.
	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
          fi
        fi
        ;;

      beos*)
	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
	  # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
	  # support --undefined.  This deserves some investigation.  FIXME
	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
	else
	  _LT_TAGVAR(ld_shlibs, $1)=no
	fi
	;;

      chorus*)
        case $cc_basename in
          *)
	  # FIXME: insert proper C++ library support
	  _LT_TAGVAR(ld_shlibs, $1)=no
	  ;;
        esac
        ;;

      cygwin* | mingw* | pw32* | cegcc*)
        # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
        # as there is no search path for DLLs.
        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
        _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
        _LT_TAGVAR(always_export_symbols, $1)=no
        _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes

        if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
          # If the export-symbols file already is a .def file (1st line
          # is EXPORTS), use it as is; otherwise, prepend...
          _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
	    cp $export_symbols $output_objdir/$soname.def;
          else
	    echo EXPORTS > $output_objdir/$soname.def;
	    cat $export_symbols >> $output_objdir/$soname.def;
          fi~
          $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
        else
          _LT_TAGVAR(ld_shlibs, $1)=no
        fi
        ;;
      darwin* | rhapsody*)
        _LT_DARWIN_LINKER_FEATURES($1)
	;;

      dgux*)
        case $cc_basename in
          ec++*)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          ghcx*)
	    # Green Hills C++ Compiler
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          *)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
        esac
        ;;

      freebsd[[12]]*)
        # C++ shared libraries reported to be fairly broken before
	# switch to ELF
        _LT_TAGVAR(ld_shlibs, $1)=no
        ;;

      freebsd-elf*)
        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
        ;;

      freebsd* | dragonfly*)
        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
        # conventions
        _LT_TAGVAR(ld_shlibs, $1)=yes
        ;;

      gnu*)
        ;;

      hpux9*)
        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
        _LT_TAGVAR(hardcode_direct, $1)=yes
        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
				             # but as the default
				             # location of the library.

        case $cc_basename in
          CC*)
            # FIXME: insert proper C++ library support
            _LT_TAGVAR(ld_shlibs, $1)=no
            ;;
          aCC*)
            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
            # Commands to make compiler produce verbose output that lists
            # what "hidden" libraries, object files and flags are used when
            # linking a shared library.
            #
            # There doesn't appear to be a way to prevent this compiler from
            # explicitly linking system object files so we need to strip them
            # from the output so that they don't get included in the library
            # dependencies.
            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
            ;;
          *)
            if test "$GXX" = yes; then
              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
            else
              # FIXME: insert proper C++ library support
              _LT_TAGVAR(ld_shlibs, $1)=no
            fi
            ;;
        esac
        ;;

      hpux10*|hpux11*)
        if test $with_gnu_ld = no; then
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:

          case $host_cpu in
            hppa*64*|ia64*)
              ;;
            *)
	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
              ;;
          esac
        fi
        case $host_cpu in
          hppa*64*|ia64*)
            _LT_TAGVAR(hardcode_direct, $1)=no
            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
            ;;
          *)
            _LT_TAGVAR(hardcode_direct, $1)=yes
            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
					         # but as the default
					         # location of the library.
            ;;
        esac

        case $cc_basename in
          CC*)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          aCC*)
	    case $host_cpu in
	      hppa*64*)
	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	        ;;
	      ia64*)
	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	        ;;
	      *)
	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	        ;;
	    esac
	    # Commands to make compiler produce verbose output that lists
	    # what "hidden" libraries, object files and flags are used when
	    # linking a shared library.
	    #
	    # There doesn't appear to be a way to prevent this compiler from
	    # explicitly linking system object files so we need to strip them
	    # from the output so that they don't get included in the library
	    # dependencies.
	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
	    ;;
          *)
	    if test "$GXX" = yes; then
	      if test $with_gnu_ld = no; then
	        case $host_cpu in
	          hppa*64*)
	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	            ;;
	          ia64*)
	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	            ;;
	          *)
	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	            ;;
	        esac
	      fi
	    else
	      # FIXME: insert proper C++ library support
	      _LT_TAGVAR(ld_shlibs, $1)=no
	    fi
	    ;;
        esac
        ;;

      interix[[3-9]]*)
	_LT_TAGVAR(hardcode_direct, $1)=no
	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
	# Instead, shared libraries are loaded at an image base (0x10000000 by
	# default) and relocated if they conflict, which is a slow very memory
	# consuming and fragmenting process.  To avoid this, we pick a random,
	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
	;;
      irix5* | irix6*)
        case $cc_basename in
          CC*)
	    # SGI C++
	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'

	    # Archives containing C++ object files must be created using
	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
	    # necessary to make sure instantiated templates are included
	    # in the archive.
	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
	    ;;
          *)
	    if test "$GXX" = yes; then
	      if test "$with_gnu_ld" = no; then
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
	      else
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` -o $lib'
	      fi
	    fi
	    _LT_TAGVAR(link_all_deplibs, $1)=yes
	    ;;
        esac
        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
        _LT_TAGVAR(inherit_rpath, $1)=yes
        ;;

      linux* | k*bsd*-gnu)
        case $cc_basename in
          KCC*)
	    # Kuck and Associates, Inc. (KAI) C++ Compiler

	    # KCC will only create a shared library if the output file
	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
	    # to its proper name (with version) after linking.
	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
	    # Commands to make compiler produce verbose output that lists
	    # what "hidden" libraries, object files and flags are used when
	    # linking a shared library.
	    #
	    # There doesn't appear to be a way to prevent this compiler from
	    # explicitly linking system object files so we need to strip them
	    # from the output so that they don't get included in the library
	    # dependencies.
	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'

	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'

	    # Archives containing C++ object files must be created using
	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
	    ;;
	  icpc* | ecpc* )
	    # Intel C++
	    with_gnu_ld=yes
	    # version 8.0 and above of icpc choke on multiply defined symbols
	    # if we add $predep_objects and $postdep_objects, however 7.1 and
	    # earlier do not add the objects themselves.
	    case `$CC -V 2>&1` in
	      *"Version 7."*)
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
		;;
	      *)  # Version 8.0 or newer
	        tmp_idyn=
	        case $host_cpu in
		  ia64*) tmp_idyn=' -i_dynamic';;
		esac
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
		;;
	    esac
	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
	    ;;
          pgCC* | pgcpp*)
            # Portland Group C++ compiler
	    case `$CC -V` in
	    *pgCC\ [[1-5]]* | *pgcpp\ [[1-5]]*)
	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
		rm -rf $tpldir~
		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
		compile_command="$compile_command `find $tpldir -name \*.o | $NL2SP`"'
	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
		rm -rf $tpldir~
		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | $NL2SP`~
		$RANLIB $oldlib'
	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
		rm -rf $tpldir~
		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
		rm -rf $tpldir~
		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
	      ;;
	    *) # Version 6 will use weak symbols
	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
	      ;;
	    esac

	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
            ;;
	  cxx*)
	    # Compaq C++
	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'

	    runpath_var=LD_RUN_PATH
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:

	    # Commands to make compiler produce verbose output that lists
	    # what "hidden" libraries, object files and flags are used when
	    # linking a shared library.
	    #
	    # There doesn't appear to be a way to prevent this compiler from
	    # explicitly linking system object files so we need to strip them
	    # from the output so that they don't get included in the library
	    # dependencies.
	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
	    ;;
	  xl*)
	    # IBM XL 8.0 on PPC, with GNU ld
	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
	    if test "x$supports_anon_versioning" = xyes; then
	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
		echo "local: *; };" >> $output_objdir/$libname.ver~
		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
	    fi
	    ;;
	  *)
	    case `$CC -V 2>&1 | sed 5q` in
	    *Sun\ C*)
	      # Sun C++ 5.9
	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
	      _LT_TAGVAR(compiler_needs_object, $1)=yes

	      # Not sure whether something based on
	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
	      # would be better.
	      output_verbose_link_cmd='echo'

	      # Archives containing C++ object files must be created using
	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
	      # necessary to make sure instantiated templates are included
	      # in the archive.
	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
	      ;;
	    esac
	    ;;
	esac
	;;

      lynxos*)
        # FIXME: insert proper C++ library support
	_LT_TAGVAR(ld_shlibs, $1)=no
	;;

      m88k*)
        # FIXME: insert proper C++ library support
        _LT_TAGVAR(ld_shlibs, $1)=no
	;;

      mvs*)
        case $cc_basename in
          cxx*)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
	  *)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
	esac
	;;

      netbsd*)
        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
	  wlarc=
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
	  _LT_TAGVAR(hardcode_direct, $1)=yes
	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	fi
	# Workaround some broken pre-1.5 toolchains
	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
	;;

      *nto* | *qnx*)
        _LT_TAGVAR(ld_shlibs, $1)=yes
	;;

      openbsd2*)
        # C++ shared libraries are fairly broken
	_LT_TAGVAR(ld_shlibs, $1)=no
	;;

      openbsd*)
	if test -f /usr/libexec/ld.so; then
	  _LT_TAGVAR(hardcode_direct, $1)=yes
	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
	  fi
	  output_verbose_link_cmd=echo
	else
	  _LT_TAGVAR(ld_shlibs, $1)=no
	fi
	;;

      osf3* | osf4* | osf5*)
        case $cc_basename in
          KCC*)
	    # Kuck and Associates, Inc. (KAI) C++ Compiler

	    # KCC will only create a shared library if the output file
	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
	    # to its proper name (with version) after linking.
	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'

	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:

	    # Archives containing C++ object files must be created using
	    # the KAI C++ compiler.
	    case $host in
	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
	    esac
	    ;;
          RCC*)
	    # Rational C++ 2.4.1
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          cxx*)
	    case $host in
	      osf3*)
	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && $ECHO "X${wl}-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
		;;
	      *)
	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
	          echo "-hidden">> $lib.exp~
	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~
	          $RM $lib.exp'
	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
		;;
	    esac

	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:

	    # Commands to make compiler produce verbose output that lists
	    # what "hidden" libraries, object files and flags are used when
	    # linking a shared library.
	    #
	    # There doesn't appear to be a way to prevent this compiler from
	    # explicitly linking system object files so we need to strip them
	    # from the output so that they don't get included in the library
	    # dependencies.
	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
	    ;;
	  *)
	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
	      case $host in
	        osf3*)
	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
		  ;;
	        *)
	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
		  ;;
	      esac

	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:

	      # Commands to make compiler produce verbose output that lists
	      # what "hidden" libraries, object files and flags are used when
	      # linking a shared library.
	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'

	    else
	      # FIXME: insert proper C++ library support
	      _LT_TAGVAR(ld_shlibs, $1)=no
	    fi
	    ;;
        esac
        ;;

      psos*)
        # FIXME: insert proper C++ library support
        _LT_TAGVAR(ld_shlibs, $1)=no
        ;;

      sunos4*)
        case $cc_basename in
          CC*)
	    # Sun C++ 4.x
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          lcc*)
	    # Lucid
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          *)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
        esac
        ;;

      solaris*)
        case $cc_basename in
          CC*)
	    # Sun C++ 4.2, 5.x and Centerline C++
            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'

	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	    case $host_os in
	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
	      *)
		# The compiler driver will combine and reorder linker options,
		# but understands `-z linker_flag'.
	        # Supported since Solaris 2.6 (maybe 2.5.1?)
		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
	        ;;
	    esac
	    _LT_TAGVAR(link_all_deplibs, $1)=yes

	    output_verbose_link_cmd='echo'

	    # Archives containing C++ object files must be created using
	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
	    # necessary to make sure instantiated templates are included
	    # in the archive.
	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
	    ;;
          gcx*)
	    # Green Hills C++ Compiler
	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'

	    # The C++ compiler must be used to create the archive.
	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
	    ;;
          *)
	    # GNU C++ compiler with Solaris linker
	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
		  $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'

	        # Commands to make compiler produce verbose output that lists
	        # what "hidden" libraries, object files and flags are used when
	        # linking a shared library.
	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
	      else
	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
	        # platform.
	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'

	        # Commands to make compiler produce verbose output that lists
	        # what "hidden" libraries, object files and flags are used when
	        # linking a shared library.
	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
	      fi

	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
	      case $host_os in
		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
		*)
		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
		  ;;
	      esac
	    fi
	    ;;
        esac
        ;;

    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
      runpath_var='LD_RUN_PATH'

      case $cc_basename in
        CC*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
	*)
	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	  ;;
      esac
      ;;

      sysv5* | sco3.2v5* | sco5v6*)
	# Note: We can NOT use -z defs as we might desire, because we do not
	# link with -lc, and that would cause any symbols used from libc to
	# always be unresolved, which means just about no library would
	# ever link correctly.  If we're not using GNU ld we use -z text
	# though, which does catch some bad symbols but isn't as heavy-handed
	# as -z defs.
	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
	_LT_TAGVAR(link_all_deplibs, $1)=yes
	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
	runpath_var='LD_RUN_PATH'

	case $cc_basename in
          CC*)
	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	    ;;
	  *)
	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
	    ;;
	esac
      ;;

      tandem*)
        case $cc_basename in
          NCC*)
	    # NonStop-UX NCC 3.20
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
          *)
	    # FIXME: insert proper C++ library support
	    _LT_TAGVAR(ld_shlibs, $1)=no
	    ;;
        esac
        ;;

      vxworks*)
        # FIXME: insert proper C++ library support
        _LT_TAGVAR(ld_shlibs, $1)=no
        ;;

      *)
        # FIXME: insert proper C++ library support
        _LT_TAGVAR(ld_shlibs, $1)=no
        ;;
    esac

    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no

    _LT_TAGVAR(GCC, $1)="$GXX"
    _LT_TAGVAR(LD, $1)="$LD"

    ## CAVEAT EMPTOR:
    ## There is no encapsulation within the following macros, do not change
    ## the running order or otherwise move them around unless you know exactly
    ## what you are doing...
    _LT_SYS_HIDDEN_LIBDEPS($1)
    _LT_COMPILER_PIC($1)
    _LT_COMPILER_C_O($1)
    _LT_COMPILER_FILE_LOCKS($1)
    _LT_LINKER_SHLIBS($1)
    _LT_SYS_DYNAMIC_LINKER($1)
    _LT_LINKER_HARDCODE_LIBPATH($1)

    _LT_CONFIG($1)
  fi # test -n "$compiler"

  CC=$lt_save_CC
  LDCXX=$LD
  LD=$lt_save_LD
  GCC=$lt_save_GCC
  with_gnu_ld=$lt_save_with_gnu_ld
  lt_cv_path_LDCXX=$lt_cv_path_LD
  lt_cv_path_LD=$lt_save_path_LD
  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
fi # test "$_lt_caught_CXX_error" != yes

AC_LANG_POP
])# _LT_LANG_CXX_CONFIG


# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
# ---------------------------------
# Figure out "hidden" library dependencies from verbose
# compiler output when linking a shared library.
# Parse the compiler output and extract the necessary
# objects, libraries and library flags.
m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
# Dependencies to place before and after the object being linked:
_LT_TAGVAR(predep_objects, $1)=
_LT_TAGVAR(postdep_objects, $1)=
_LT_TAGVAR(predeps, $1)=
_LT_TAGVAR(postdeps, $1)=
_LT_TAGVAR(compiler_lib_search_path, $1)=

dnl we can't use the lt_simple_compile_test_code here,
dnl because it contains code intended for an executable,
dnl not a library.  It's possible we should let each
dnl tag define a new lt_????_link_test_code variable,
dnl but it's only used here...
m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
int a;
void foo (void) { a = 0; }
_LT_EOF
], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
class Foo
{
public:
  Foo (void) { a = 0; }
private:
  int a;
};
_LT_EOF
], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
      subroutine foo
      implicit none
      integer*4 a
      a=0
      return
      end
_LT_EOF
], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
      subroutine foo
      implicit none
      integer a
      a=0
      return
      end
_LT_EOF
], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
public class foo {
  private int a;
  public void bar (void) {
    a = 0;
  }
};
_LT_EOF
])
dnl Parse the compiler output and extract the necessary
dnl objects, libraries and library flags.
if AC_TRY_EVAL(ac_compile); then
  # Parse the compiler output and extract the necessary
  # objects, libraries and library flags.

  # Sentinel used to keep track of whether or not we are before
  # the conftest object file.
  pre_test_object_deps_done=no

  for p in `eval "$output_verbose_link_cmd"`; do
    case $p in

    -L* | -R* | -l*)
       # Some compilers place space between "-{L,R}" and the path.
       # Remove the space.
       if test $p = "-L" ||
          test $p = "-R"; then
	 prev=$p
	 continue
       else
	 prev=
       fi

       if test "$pre_test_object_deps_done" = no; then
	 case $p in
	 -L* | -R*)
	   # Internal compiler library paths should come after those
	   # provided the user.  The postdeps already come after the
	   # user supplied libs so there is no need to process them.
	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
	   else
	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
	   fi
	   ;;
	 # The "-l" case would never come before the object being
	 # linked, so don't bother handling this case.
	 esac
       else
	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
	 else
	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
	 fi
       fi
       ;;

    *.$objext)
       # This assumes that the test object file only shows up
       # once in the compiler output.
       if test "$p" = "conftest.$objext"; then
	 pre_test_object_deps_done=yes
	 continue
       fi

       if test "$pre_test_object_deps_done" = no; then
	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
	   _LT_TAGVAR(predep_objects, $1)="$p"
	 else
	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
	 fi
       else
	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
	   _LT_TAGVAR(postdep_objects, $1)="$p"
	 else
	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
	 fi
       fi
       ;;

    *) ;; # Ignore the rest.

    esac
  done

  # Clean up.
  rm -f a.out a.exe
else
  echo "libtool.m4: error: problem compiling $1 test program"
fi

$RM -f confest.$objext

# PORTME: override above test on systems where it is broken
m4_if([$1], [CXX],
[case $host_os in
interix[[3-9]]*)
  # Interix 3.5 installs completely hosed .la files for C++, so rather than
  # hack all around it, let's just trust "g++" to DTRT.
  _LT_TAGVAR(predep_objects,$1)=
  _LT_TAGVAR(postdep_objects,$1)=
  _LT_TAGVAR(postdeps,$1)=
  ;;

linux*)
  case `$CC -V 2>&1 | sed 5q` in
  *Sun\ C*)
    # Sun C++ 5.9

    # The more standards-conforming stlport4 library is
    # incompatible with the Cstd library. Avoid specifying
    # it if it's in CXXFLAGS. Ignore libCrun as
    # -library=stlport4 depends on it.
    case " $CXX $CXXFLAGS " in
    *" -library=stlport4 "*)
      solaris_use_stlport4=yes
      ;;
    esac

    if test "$solaris_use_stlport4" != yes; then
      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
    fi
    ;;
  esac
  ;;

solaris*)
  case $cc_basename in
  CC*)
    # The more standards-conforming stlport4 library is
    # incompatible with the Cstd library. Avoid specifying
    # it if it's in CXXFLAGS. Ignore libCrun as
    # -library=stlport4 depends on it.
    case " $CXX $CXXFLAGS " in
    *" -library=stlport4 "*)
      solaris_use_stlport4=yes
      ;;
    esac

    # Adding this requires a known-good setup of shared libraries for
    # Sun compiler versions before 5.6, else PIC objects from an old
    # archive will be linked into the output, leading to subtle bugs.
    if test "$solaris_use_stlport4" != yes; then
      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
    fi
    ;;
  esac
  ;;
esac
])

case " $_LT_TAGVAR(postdeps, $1) " in
*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
esac
 _LT_TAGVAR(compiler_lib_search_dirs, $1)=
if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
 _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
fi
_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
    [The directories searched by this compiler when creating a shared library])
_LT_TAGDECL([], [predep_objects], [1],
    [Dependencies to place before and after the objects being linked to
    create a shared library])
_LT_TAGDECL([], [postdep_objects], [1])
_LT_TAGDECL([], [predeps], [1])
_LT_TAGDECL([], [postdeps], [1])
_LT_TAGDECL([], [compiler_lib_search_path], [1],
    [The library search path used internally by the compiler when linking
    a shared library])
])# _LT_SYS_HIDDEN_LIBDEPS


# _LT_PROG_F77
# ------------
# Since AC_PROG_F77 is broken, in that it returns the empty string
# if there is no fortran compiler, we have our own version here.
m4_defun([_LT_PROG_F77],
[
pushdef([AC_MSG_ERROR], [_lt_disable_F77=yes])
AC_PROG_F77
if test -z "$F77" || test "X$F77" = "Xno"; then
  _lt_disable_F77=yes
fi
popdef([AC_MSG_ERROR])
])# _LT_PROG_F77

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([_LT_PROG_F77], [])


# _LT_LANG_F77_CONFIG([TAG])
# --------------------------
# Ensure that the configuration variables for a Fortran 77 compiler are
# suitably defined.  These variables are subsequently used by _LT_CONFIG
# to write the compiler configuration to `libtool'.
m4_defun([_LT_LANG_F77_CONFIG],
[AC_REQUIRE([_LT_PROG_F77])dnl
AC_LANG_PUSH(Fortran 77)

_LT_TAGVAR(archive_cmds_need_lc, $1)=no
_LT_TAGVAR(allow_undefined_flag, $1)=
_LT_TAGVAR(always_export_symbols, $1)=no
_LT_TAGVAR(archive_expsym_cmds, $1)=
_LT_TAGVAR(export_dynamic_flag_spec, $1)=
_LT_TAGVAR(hardcode_direct, $1)=no
_LT_TAGVAR(hardcode_direct_absolute, $1)=no
_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
_LT_TAGVAR(hardcode_libdir_separator, $1)=
_LT_TAGVAR(hardcode_minus_L, $1)=no
_LT_TAGVAR(hardcode_automatic, $1)=no
_LT_TAGVAR(inherit_rpath, $1)=no
_LT_TAGVAR(module_cmds, $1)=
_LT_TAGVAR(module_expsym_cmds, $1)=
_LT_TAGVAR(link_all_deplibs, $1)=unknown
_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
_LT_TAGVAR(no_undefined_flag, $1)=
_LT_TAGVAR(whole_archive_flag_spec, $1)=
_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no

# Source file extension for f77 test sources.
ac_ext=f

# Object file extension for compiled f77 test sources.
objext=o
_LT_TAGVAR(objext, $1)=$objext

# No sense in running all these tests if we already determined that
# the F77 compiler isn't working.  Some variables (like enable_shared)
# are currently assumed to apply to all compilers on this platform,
# and will be corrupted by setting them based on a non-working compiler.
if test "$_lt_disable_F77" != yes; then
  # Code to be used in simple compile tests
  lt_simple_compile_test_code="\
      subroutine t
      return
      end
"

  # Code to be used in simple link tests
  lt_simple_link_test_code="\
      program t
      end
"

  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
  _LT_TAG_COMPILER

  # save warnings/boilerplate of simple test code
  _LT_COMPILER_BOILERPLATE
  _LT_LINKER_BOILERPLATE

  # Allow CC to be a program name with arguments.
  lt_save_CC="$CC"
  lt_save_GCC=$GCC
  CC=${F77-"f77"}
  compiler=$CC
  _LT_TAGVAR(compiler, $1)=$CC
  _LT_CC_BASENAME([$compiler])
  GCC=$G77
  if test -n "$compiler"; then
    AC_MSG_CHECKING([if libtool supports shared libraries])
    AC_MSG_RESULT([$can_build_shared])

    AC_MSG_CHECKING([whether to build shared libraries])
    test "$can_build_shared" = "no" && enable_shared=no

    # On AIX, shared libraries and static libraries use the same namespace, and
    # are all built from PIC.
    case $host_os in
      aix3*)
        test "$enable_shared" = yes && enable_static=no
        if test -n "$RANLIB"; then
          archive_cmds="$archive_cmds~\$RANLIB \$lib"
          postinstall_cmds='$RANLIB $lib'
        fi
        ;;
      aix[[4-9]]*)
	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
	  test "$enable_shared" = yes && enable_static=no
	fi
        ;;
    esac
    AC_MSG_RESULT([$enable_shared])

    AC_MSG_CHECKING([whether to build static libraries])
    # Make sure either enable_shared or enable_static is yes.
    test "$enable_shared" = yes || enable_static=yes
    AC_MSG_RESULT([$enable_static])

    _LT_TAGVAR(GCC, $1)="$G77"
    _LT_TAGVAR(LD, $1)="$LD"

    ## CAVEAT EMPTOR:
    ## There is no encapsulation within the following macros, do not change
    ## the running order or otherwise move them around unless you know exactly
    ## what you are doing...
    _LT_COMPILER_PIC($1)
    _LT_COMPILER_C_O($1)
    _LT_COMPILER_FILE_LOCKS($1)
    _LT_LINKER_SHLIBS($1)
    _LT_SYS_DYNAMIC_LINKER($1)
    _LT_LINKER_HARDCODE_LIBPATH($1)

    _LT_CONFIG($1)
  fi # test -n "$compiler"

  GCC=$lt_save_GCC
  CC="$lt_save_CC"
fi # test "$_lt_disable_F77" != yes

AC_LANG_POP
])# _LT_LANG_F77_CONFIG


# _LT_PROG_FC
# -----------
# Since AC_PROG_FC is broken, in that it returns the empty string
# if there is no fortran compiler, we have our own version here.
m4_defun([_LT_PROG_FC],
[
pushdef([AC_MSG_ERROR], [_lt_disable_FC=yes])
AC_PROG_FC
if test -z "$FC" || test "X$FC" = "Xno"; then
  _lt_disable_FC=yes
fi
popdef([AC_MSG_ERROR])
])# _LT_PROG_FC

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([_LT_PROG_FC], [])


# _LT_LANG_FC_CONFIG([TAG])
# -------------------------
# Ensure that the configuration variables for a Fortran compiler are
# suitably defined.  These variables are subsequently used by _LT_CONFIG
# to write the compiler configuration to `libtool'.
m4_defun([_LT_LANG_FC_CONFIG],
[AC_REQUIRE([_LT_PROG_FC])dnl
AC_LANG_PUSH(Fortran)

_LT_TAGVAR(archive_cmds_need_lc, $1)=no
_LT_TAGVAR(allow_undefined_flag, $1)=
_LT_TAGVAR(always_export_symbols, $1)=no
_LT_TAGVAR(archive_expsym_cmds, $1)=
_LT_TAGVAR(export_dynamic_flag_spec, $1)=
_LT_TAGVAR(hardcode_direct, $1)=no
_LT_TAGVAR(hardcode_direct_absolute, $1)=no
_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
_LT_TAGVAR(hardcode_libdir_separator, $1)=
_LT_TAGVAR(hardcode_minus_L, $1)=no
_LT_TAGVAR(hardcode_automatic, $1)=no
_LT_TAGVAR(inherit_rpath, $1)=no
_LT_TAGVAR(module_cmds, $1)=
_LT_TAGVAR(module_expsym_cmds, $1)=
_LT_TAGVAR(link_all_deplibs, $1)=unknown
_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
_LT_TAGVAR(no_undefined_flag, $1)=
_LT_TAGVAR(whole_archive_flag_spec, $1)=
_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no

# Source file extension for fc test sources.
ac_ext=${ac_fc_srcext-f}

# Object file extension for compiled fc test sources.
objext=o
_LT_TAGVAR(objext, $1)=$objext

# No sense in running all these tests if we already determined that
# the FC compiler isn't working.  Some variables (like enable_shared)
# are currently assumed to apply to all compilers on this platform,
# and will be corrupted by setting them based on a non-working compiler.
if test "$_lt_disable_FC" != yes; then
  # Code to be used in simple compile tests
  lt_simple_compile_test_code="\
      subroutine t
      return
      end
"

  # Code to be used in simple link tests
  lt_simple_link_test_code="\
      program t
      end
"

  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
  _LT_TAG_COMPILER

  # save warnings/boilerplate of simple test code
  _LT_COMPILER_BOILERPLATE
  _LT_LINKER_BOILERPLATE

  # Allow CC to be a program name with arguments.
  lt_save_CC="$CC"
  lt_save_GCC=$GCC
  CC=${FC-"f95"}
  compiler=$CC
  GCC=$ac_cv_fc_compiler_gnu

  _LT_TAGVAR(compiler, $1)=$CC
  _LT_CC_BASENAME([$compiler])

  if test -n "$compiler"; then
    AC_MSG_CHECKING([if libtool supports shared libraries])
    AC_MSG_RESULT([$can_build_shared])

    AC_MSG_CHECKING([whether to build shared libraries])
    test "$can_build_shared" = "no" && enable_shared=no

    # On AIX, shared libraries and static libraries use the same namespace, and
    # are all built from PIC.
    case $host_os in
      aix3*)
        test "$enable_shared" = yes && enable_static=no
        if test -n "$RANLIB"; then
          archive_cmds="$archive_cmds~\$RANLIB \$lib"
          postinstall_cmds='$RANLIB $lib'
        fi
        ;;
      aix[[4-9]]*)
	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
	  test "$enable_shared" = yes && enable_static=no
	fi
        ;;
    esac
    AC_MSG_RESULT([$enable_shared])

    AC_MSG_CHECKING([whether to build static libraries])
    # Make sure either enable_shared or enable_static is yes.
    test "$enable_shared" = yes || enable_static=yes
    AC_MSG_RESULT([$enable_static])

    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
    _LT_TAGVAR(LD, $1)="$LD"

    ## CAVEAT EMPTOR:
    ## There is no encapsulation within the following macros, do not change
    ## the running order or otherwise move them around unless you know exactly
    ## what you are doing...
    _LT_SYS_HIDDEN_LIBDEPS($1)
    _LT_COMPILER_PIC($1)
    _LT_COMPILER_C_O($1)
    _LT_COMPILER_FILE_LOCKS($1)
    _LT_LINKER_SHLIBS($1)
    _LT_SYS_DYNAMIC_LINKER($1)
    _LT_LINKER_HARDCODE_LIBPATH($1)

    _LT_CONFIG($1)
  fi # test -n "$compiler"

  GCC=$lt_save_GCC
  CC="$lt_save_CC"
fi # test "$_lt_disable_FC" != yes

AC_LANG_POP
])# _LT_LANG_FC_CONFIG


# _LT_LANG_GCJ_CONFIG([TAG])
# --------------------------
# Ensure that the configuration variables for the GNU Java Compiler compiler
# are suitably defined.  These variables are subsequently used by _LT_CONFIG
# to write the compiler configuration to `libtool'.
m4_defun([_LT_LANG_GCJ_CONFIG],
[AC_REQUIRE([LT_PROG_GCJ])dnl
AC_LANG_SAVE

# Source file extension for Java test sources.
ac_ext=java

# Object file extension for compiled Java test sources.
objext=o
_LT_TAGVAR(objext, $1)=$objext

# Code to be used in simple compile tests
lt_simple_compile_test_code="class foo {}"

# Code to be used in simple link tests
lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'

# ltmain only uses $CC for tagged configurations so make sure $CC is set.
_LT_TAG_COMPILER

# save warnings/boilerplate of simple test code
_LT_COMPILER_BOILERPLATE
_LT_LINKER_BOILERPLATE

# Allow CC to be a program name with arguments.
lt_save_CC="$CC"
lt_save_GCC=$GCC
GCC=yes
CC=${GCJ-"gcj"}
compiler=$CC
_LT_TAGVAR(compiler, $1)=$CC
_LT_TAGVAR(LD, $1)="$LD"
_LT_CC_BASENAME([$compiler])

# GCJ did not exist at the time GCC didn't implicitly link libc in.
_LT_TAGVAR(archive_cmds_need_lc, $1)=no

_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds

if test -n "$compiler"; then
  _LT_COMPILER_NO_RTTI($1)
  _LT_COMPILER_PIC($1)
  _LT_COMPILER_C_O($1)
  _LT_COMPILER_FILE_LOCKS($1)
  _LT_LINKER_SHLIBS($1)
  _LT_LINKER_HARDCODE_LIBPATH($1)

  _LT_CONFIG($1)
fi

AC_LANG_RESTORE

GCC=$lt_save_GCC
CC="$lt_save_CC"
])# _LT_LANG_GCJ_CONFIG


# _LT_LANG_RC_CONFIG([TAG])
# -------------------------
# Ensure that the configuration variables for the Windows resource compiler
# are suitably defined.  These variables are subsequently used by _LT_CONFIG
# to write the compiler configuration to `libtool'.
m4_defun([_LT_LANG_RC_CONFIG],
[AC_REQUIRE([LT_PROG_RC])dnl
AC_LANG_SAVE

# Source file extension for RC test sources.
ac_ext=rc

# Object file extension for compiled RC test sources.
objext=o
_LT_TAGVAR(objext, $1)=$objext

# Code to be used in simple compile tests
lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'

# Code to be used in simple link tests
lt_simple_link_test_code="$lt_simple_compile_test_code"

# ltmain only uses $CC for tagged configurations so make sure $CC is set.
_LT_TAG_COMPILER

# save warnings/boilerplate of simple test code
_LT_COMPILER_BOILERPLATE
_LT_LINKER_BOILERPLATE

# Allow CC to be a program name with arguments.
lt_save_CC="$CC"
lt_save_GCC=$GCC
GCC=
CC=${RC-"windres"}
compiler=$CC
_LT_TAGVAR(compiler, $1)=$CC
_LT_CC_BASENAME([$compiler])
_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes

if test -n "$compiler"; then
  :
  _LT_CONFIG($1)
fi

GCC=$lt_save_GCC
AC_LANG_RESTORE
CC="$lt_save_CC"
])# _LT_LANG_RC_CONFIG


# LT_PROG_GCJ
# -----------
AC_DEFUN([LT_PROG_GCJ],
[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
    [AC_CHECK_TOOL(GCJ, gcj,)
      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
      AC_SUBST(GCJFLAGS)])])[]dnl
])

# Old name:
AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([LT_AC_PROG_GCJ], [])


# LT_PROG_RC
# ----------
AC_DEFUN([LT_PROG_RC],
[AC_CHECK_TOOL(RC, windres,)
])

# Old name:
AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([LT_AC_PROG_RC], [])


# _LT_DECL_EGREP
# --------------
# If we don't have a new enough Autoconf to choose the best grep
# available, choose the one first in the user's PATH.
m4_defun([_LT_DECL_EGREP],
[AC_REQUIRE([AC_PROG_EGREP])dnl
AC_REQUIRE([AC_PROG_FGREP])dnl
test -z "$GREP" && GREP=grep
_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
_LT_DECL([], [EGREP], [1], [An ERE matcher])
_LT_DECL([], [FGREP], [1], [A literal string matcher])
dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
AC_SUBST([GREP])
])


# _LT_DECL_OBJDUMP
# --------------
# If we don't have a new enough Autoconf to choose the best objdump
# available, choose the one first in the user's PATH.
m4_defun([_LT_DECL_OBJDUMP],
[AC_CHECK_TOOL(OBJDUMP, objdump, false)
test -z "$OBJDUMP" && OBJDUMP=objdump
_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
AC_SUBST([OBJDUMP])
])


# _LT_DECL_SED
# ------------
# Check for a fully-functional sed program, that truncates
# as few characters as possible.  Prefer GNU sed if found.
m4_defun([_LT_DECL_SED],
[AC_PROG_SED
test -z "$SED" && SED=sed
Xsed="$SED -e 1s/^X//"
_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
])# _LT_DECL_SED

m4_ifndef([AC_PROG_SED], [
# NOTE: This macro has been submitted for inclusion into   #
#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
#  a released version of Autoconf we should remove this    #
#  macro and use it instead.                               #

m4_defun([AC_PROG_SED],
[AC_MSG_CHECKING([for a sed that does not truncate output])
AC_CACHE_VAL(lt_cv_path_SED,
[# Loop through the user's path and test for sed and gsed.
# Then use that list of sed's as ones to test for truncation.
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
  IFS=$as_save_IFS
  test -z "$as_dir" && as_dir=.
  for lt_ac_prog in sed gsed; do
    for ac_exec_ext in '' $ac_executable_extensions; do
      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
      fi
    done
  done
done
IFS=$as_save_IFS
lt_ac_max=0
lt_ac_count=0
# Add /usr/xpg4/bin/sed as it is typically found on Solaris
# along with /bin/sed that truncates output.
for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
  test ! -f $lt_ac_sed && continue
  cat /dev/null > conftest.in
  lt_ac_count=0
  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
  # Check for GNU sed and select it if it is found.
  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
    lt_cv_path_SED=$lt_ac_sed
    break
  fi
  while true; do
    cat conftest.in conftest.in >conftest.tmp
    mv conftest.tmp conftest.in
    cp conftest.in conftest.nl
    echo >>conftest.nl
    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
    cmp -s conftest.out conftest.nl || break
    # 10000 chars as input seems more than enough
    test $lt_ac_count -gt 10 && break
    lt_ac_count=`expr $lt_ac_count + 1`
    if test $lt_ac_count -gt $lt_ac_max; then
      lt_ac_max=$lt_ac_count
      lt_cv_path_SED=$lt_ac_sed
    fi
  done
done
])
SED=$lt_cv_path_SED
AC_SUBST([SED])
AC_MSG_RESULT([$SED])
])#AC_PROG_SED
])#m4_ifndef

# Old name:
AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([LT_AC_PROG_SED], [])


# _LT_CHECK_SHELL_FEATURES
# ------------------------
# Find out whether the shell is Bourne or XSI compatible,
# or has some other useful features.
m4_defun([_LT_CHECK_SHELL_FEATURES],
[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
# Try some XSI features
xsi_shell=no
( _lt_dummy="a/b/c"
  test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \
      = c,a/b,, \
    && eval 'test $(( 1 + 1 )) -eq 2 \
    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
  && xsi_shell=yes
AC_MSG_RESULT([$xsi_shell])
_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])

AC_MSG_CHECKING([whether the shell understands "+="])
lt_shell_append=no
( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
    >/dev/null 2>&1 \
  && lt_shell_append=yes
AC_MSG_RESULT([$lt_shell_append])
_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])

if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
  lt_unset=unset
else
  lt_unset=false
fi
_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl

# test EBCDIC or ASCII
case `echo X|tr X '\101'` in
 A) # ASCII based system
    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
  lt_SP2NL='tr \040 \012'
  lt_NL2SP='tr \015\012 \040\040'
  ;;
 *) # EBCDIC based system
  lt_SP2NL='tr \100 \n'
  lt_NL2SP='tr \r\n \100\100'
  ;;
esac
_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
])# _LT_CHECK_SHELL_FEATURES


# _LT_PROG_XSI_SHELLFNS
# ---------------------
# Bourne and XSI compatible variants of some useful shell functions.
m4_defun([_LT_PROG_XSI_SHELLFNS],
[case $xsi_shell in
  yes)
    cat << \_LT_EOF >> "$cfgfile"

# func_dirname file append nondir_replacement
# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
# otherwise set result to NONDIR_REPLACEMENT.
func_dirname ()
{
  case ${1} in
    */*) func_dirname_result="${1%/*}${2}" ;;
    *  ) func_dirname_result="${3}" ;;
  esac
}

# func_basename file
func_basename ()
{
  func_basename_result="${1##*/}"
}

# func_dirname_and_basename file append nondir_replacement
# perform func_basename and func_dirname in a single function
# call:
#   dirname:  Compute the dirname of FILE.  If nonempty,
#             add APPEND to the result, otherwise set result
#             to NONDIR_REPLACEMENT.
#             value returned in "$func_dirname_result"
#   basename: Compute filename of FILE.
#             value retuned in "$func_basename_result"
# Implementation must be kept synchronized with func_dirname
# and func_basename. For efficiency, we do not delegate to
# those functions but instead duplicate the functionality here.
func_dirname_and_basename ()
{
  case ${1} in
    */*) func_dirname_result="${1%/*}${2}" ;;
    *  ) func_dirname_result="${3}" ;;
  esac
  func_basename_result="${1##*/}"
}

# func_stripname prefix suffix name
# strip PREFIX and SUFFIX off of NAME.
# PREFIX and SUFFIX must not contain globbing or regex special
# characters, hashes, percent signs, but SUFFIX may contain a leading
# dot (in which case that matches only a dot).
func_stripname ()
{
  # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
  # positional parameters, so assign one to ordinary parameter first.
  func_stripname_result=${3}
  func_stripname_result=${func_stripname_result#"${1}"}
  func_stripname_result=${func_stripname_result%"${2}"}
}

# func_opt_split
func_opt_split ()
{
  func_opt_split_opt=${1%%=*}
  func_opt_split_arg=${1#*=}
}

# func_lo2o object
func_lo2o ()
{
  case ${1} in
    *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
    *)    func_lo2o_result=${1} ;;
  esac
}

# func_xform libobj-or-source
func_xform ()
{
  func_xform_result=${1%.*}.lo
}

# func_arith arithmetic-term...
func_arith ()
{
  func_arith_result=$(( $[*] ))
}

# func_len string
# STRING may not start with a hyphen.
func_len ()
{
  func_len_result=${#1}
}

_LT_EOF
    ;;
  *) # Bourne compatible functions.
    cat << \_LT_EOF >> "$cfgfile"

# func_dirname file append nondir_replacement
# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
# otherwise set result to NONDIR_REPLACEMENT.
func_dirname ()
{
  # Extract subdirectory from the argument.
  func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"`
  if test "X$func_dirname_result" = "X${1}"; then
    func_dirname_result="${3}"
  else
    func_dirname_result="$func_dirname_result${2}"
  fi
}

# func_basename file
func_basename ()
{
  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
}

dnl func_dirname_and_basename
dnl A portable version of this function is already defined in general.m4sh
dnl so there is no need for it here.

# func_stripname prefix suffix name
# strip PREFIX and SUFFIX off of NAME.
# PREFIX and SUFFIX must not contain globbing or regex special
# characters, hashes, percent signs, but SUFFIX may contain a leading
# dot (in which case that matches only a dot).
# func_strip_suffix prefix name
func_stripname ()
{
  case ${2} in
    .*) func_stripname_result=`$ECHO "X${3}" \
           | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;;
    *)  func_stripname_result=`$ECHO "X${3}" \
           | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;;
  esac
}

# sed scripts:
my_sed_long_opt='1s/^\(-[[^=]]*\)=.*/\1/;q'
my_sed_long_arg='1s/^-[[^=]]*=//'

# func_opt_split
func_opt_split ()
{
  func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"`
  func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"`
}

# func_lo2o object
func_lo2o ()
{
  func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"`
}

# func_xform libobj-or-source
func_xform ()
{
  func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[[^.]]*$/.lo/'`
}

# func_arith arithmetic-term...
func_arith ()
{
  func_arith_result=`expr "$[@]"`
}

# func_len string
# STRING may not start with a hyphen.
func_len ()
{
  func_len_result=`expr "$[1]" : ".*" 2>/dev/null || echo $max_cmd_len`
}

_LT_EOF
esac

case $lt_shell_append in
  yes)
    cat << \_LT_EOF >> "$cfgfile"

# func_append var value
# Append VALUE to the end of shell variable VAR.
func_append ()
{
  eval "$[1]+=\$[2]"
}
_LT_EOF
    ;;
  *)
    cat << \_LT_EOF >> "$cfgfile"

# func_append var value
# Append VALUE to the end of shell variable VAR.
func_append ()
{
  eval "$[1]=\$$[1]\$[2]"
}

_LT_EOF
    ;;
  esac
])

# Helper functions for option handling.                    -*- Autoconf -*-
#
#   Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
#   Written by Gary V. Vaughan, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.

# serial 6 ltoptions.m4

# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])


# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
# ------------------------------------------
m4_define([_LT_MANGLE_OPTION],
[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])


# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
# ---------------------------------------
# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
# saved as a flag.
m4_define([_LT_SET_OPTION],
[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
        _LT_MANGLE_DEFUN([$1], [$2]),
    [m4_warning([Unknown $1 option `$2'])])[]dnl
])


# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
# ------------------------------------------------------------
# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
m4_define([_LT_IF_OPTION],
[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])


# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
# -------------------------------------------------------
# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
# are set.
m4_define([_LT_UNLESS_OPTIONS],
[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
		      [m4_define([$0_found])])])[]dnl
m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
])[]dnl
])


# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
# ----------------------------------------
# OPTION-LIST is a space-separated list of Libtool options associated
# with MACRO-NAME.  If any OPTION has a matching handler declared with
# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
# the unknown option and exit.
m4_defun([_LT_SET_OPTIONS],
[# Set options
m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
    [_LT_SET_OPTION([$1], _LT_Option)])

m4_if([$1],[LT_INIT],[
  dnl
  dnl Simply set some default values (i.e off) if boolean options were not
  dnl specified:
  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
  ])
  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
  ])
  dnl
  dnl If no reference was made to various pairs of opposing options, then
  dnl we run the default mode handler for the pair.  For example, if neither
  dnl `shared' nor `disable-shared' was passed, we enable building of shared
  dnl archives by default:
  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
  		   [_LT_ENABLE_FAST_INSTALL])
  ])
])# _LT_SET_OPTIONS



# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
# -----------------------------------------
m4_define([_LT_MANGLE_DEFUN],
[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])


# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
# -----------------------------------------------
m4_define([LT_OPTION_DEFINE],
[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
])# LT_OPTION_DEFINE


# dlopen
# ------
LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
])

AU_DEFUN([AC_LIBTOOL_DLOPEN],
[_LT_SET_OPTION([LT_INIT], [dlopen])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the `dlopen' option into LT_INIT's first parameter.])
])

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])


# win32-dll
# ---------
# Declare package support for building win32 dll's.
LT_OPTION_DEFINE([LT_INIT], [win32-dll],
[enable_win32_dll=yes

case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-cegcc*)
  AC_CHECK_TOOL(AS, as, false)
  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
  AC_CHECK_TOOL(OBJDUMP, objdump, false)
  ;;
esac

test -z "$AS" && AS=as
_LT_DECL([], [AS],      [0], [Assembler program])dnl

test -z "$DLLTOOL" && DLLTOOL=dlltool
_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl

test -z "$OBJDUMP" && OBJDUMP=objdump
_LT_DECL([], [OBJDUMP], [0], [Object dumper program])dnl
])# win32-dll

AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
_LT_SET_OPTION([LT_INIT], [win32-dll])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the `win32-dll' option into LT_INIT's first parameter.])
])

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])


# _LT_ENABLE_SHARED([DEFAULT])
# ----------------------------
# implement the --enable-shared flag, and supports the `shared' and
# `disable-shared' LT_INIT options.
# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
m4_define([_LT_ENABLE_SHARED],
[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([shared],
    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
    [p=${PACKAGE-default}
    case $enableval in
    yes) enable_shared=yes ;;
    no) enable_shared=no ;;
    *)
      enable_shared=no
      # Look at the argument we got.  We use all the common list separators.
      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
      for pkg in $enableval; do
	IFS="$lt_save_ifs"
	if test "X$pkg" = "X$p"; then
	  enable_shared=yes
	fi
      done
      IFS="$lt_save_ifs"
      ;;
    esac],
    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)

    _LT_DECL([build_libtool_libs], [enable_shared], [0],
	[Whether or not to build shared libraries])
])# _LT_ENABLE_SHARED

LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])

# Old names:
AC_DEFUN([AC_ENABLE_SHARED],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
])

AC_DEFUN([AC_DISABLE_SHARED],
[_LT_SET_OPTION([LT_INIT], [disable-shared])
])

AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_ENABLE_SHARED], [])
dnl AC_DEFUN([AM_DISABLE_SHARED], [])



# _LT_ENABLE_STATIC([DEFAULT])
# ----------------------------
# implement the --enable-static flag, and support the `static' and
# `disable-static' LT_INIT options.
# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
m4_define([_LT_ENABLE_STATIC],
[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([static],
    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
    [p=${PACKAGE-default}
    case $enableval in
    yes) enable_static=yes ;;
    no) enable_static=no ;;
    *)
     enable_static=no
      # Look at the argument we got.  We use all the common list separators.
      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
      for pkg in $enableval; do
	IFS="$lt_save_ifs"
	if test "X$pkg" = "X$p"; then
	  enable_static=yes
	fi
      done
      IFS="$lt_save_ifs"
      ;;
    esac],
    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)

    _LT_DECL([build_old_libs], [enable_static], [0],
	[Whether or not to build static libraries])
])# _LT_ENABLE_STATIC

LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])

# Old names:
AC_DEFUN([AC_ENABLE_STATIC],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
])

AC_DEFUN([AC_DISABLE_STATIC],
[_LT_SET_OPTION([LT_INIT], [disable-static])
])

AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_ENABLE_STATIC], [])
dnl AC_DEFUN([AM_DISABLE_STATIC], [])



# _LT_ENABLE_FAST_INSTALL([DEFAULT])
# ----------------------------------
# implement the --enable-fast-install flag, and support the `fast-install'
# and `disable-fast-install' LT_INIT options.
# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
m4_define([_LT_ENABLE_FAST_INSTALL],
[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([fast-install],
    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
    [p=${PACKAGE-default}
    case $enableval in
    yes) enable_fast_install=yes ;;
    no) enable_fast_install=no ;;
    *)
      enable_fast_install=no
      # Look at the argument we got.  We use all the common list separators.
      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
      for pkg in $enableval; do
	IFS="$lt_save_ifs"
	if test "X$pkg" = "X$p"; then
	  enable_fast_install=yes
	fi
      done
      IFS="$lt_save_ifs"
      ;;
    esac],
    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)

_LT_DECL([fast_install], [enable_fast_install], [0],
	 [Whether or not to optimize for fast installation])dnl
])# _LT_ENABLE_FAST_INSTALL

LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])

# Old names:
AU_DEFUN([AC_ENABLE_FAST_INSTALL],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you put
the `fast-install' option into LT_INIT's first parameter.])
])

AU_DEFUN([AC_DISABLE_FAST_INSTALL],
[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you put
the `disable-fast-install' option into LT_INIT's first parameter.])
])

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])


# _LT_WITH_PIC([MODE])
# --------------------
# implement the --with-pic flag, and support the `pic-only' and `no-pic'
# LT_INIT options.
# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
m4_define([_LT_WITH_PIC],
[AC_ARG_WITH([pic],
    [AS_HELP_STRING([--with-pic],
	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
    [pic_mode="$withval"],
    [pic_mode=default])

test -z "$pic_mode" && pic_mode=m4_default([$1], [default])

_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
])# _LT_WITH_PIC

LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])

# Old name:
AU_DEFUN([AC_LIBTOOL_PICMODE],
[_LT_SET_OPTION([LT_INIT], [pic-only])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the `pic-only' option into LT_INIT's first parameter.])
])

dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])


m4_define([_LTDL_MODE], [])
LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
		 [m4_define([_LTDL_MODE], [nonrecursive])])
LT_OPTION_DEFINE([LTDL_INIT], [recursive],
		 [m4_define([_LTDL_MODE], [recursive])])
LT_OPTION_DEFINE([LTDL_INIT], [subproject],
		 [m4_define([_LTDL_MODE], [subproject])])

m4_define([_LTDL_TYPE], [])
LT_OPTION_DEFINE([LTDL_INIT], [installable],
		 [m4_define([_LTDL_TYPE], [installable])])
LT_OPTION_DEFINE([LTDL_INIT], [convenience],
		 [m4_define([_LTDL_TYPE], [convenience])])

# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
#
# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
# Written by Gary V. Vaughan, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.

# serial 6 ltsugar.m4

# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])


# lt_join(SEP, ARG1, [ARG2...])
# -----------------------------
# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
# associated separator.
# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
# versions in m4sugar had bugs.
m4_define([lt_join],
[m4_if([$#], [1], [],
       [$#], [2], [[$2]],
       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
m4_define([_lt_join],
[m4_if([$#$2], [2], [],
       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])


# lt_car(LIST)
# lt_cdr(LIST)
# ------------
# Manipulate m4 lists.
# These macros are necessary as long as will still need to support
# Autoconf-2.59 which quotes differently.
m4_define([lt_car], [[$1]])
m4_define([lt_cdr],
[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
       [$#], 1, [],
       [m4_dquote(m4_shift($@))])])
m4_define([lt_unquote], $1)


# lt_append(MACRO-NAME, STRING, [SEPARATOR])
# ------------------------------------------
# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
# Note that neither SEPARATOR nor STRING are expanded; they are appended
# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
# No SEPARATOR is output if MACRO-NAME was previously undefined (different
# than defined and empty).
#
# This macro is needed until we can rely on Autoconf 2.62, since earlier
# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
m4_define([lt_append],
[m4_define([$1],
	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])



# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
# ----------------------------------------------------------
# Produce a SEP delimited list of all paired combinations of elements of
# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
# has the form PREFIXmINFIXSUFFIXn.
# Needed until we can rely on m4_combine added in Autoconf 2.62.
m4_define([lt_combine],
[m4_if(m4_eval([$# > 3]), [1],
       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
[[m4_foreach([_Lt_prefix], [$2],
	     [m4_foreach([_Lt_suffix],
		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])


# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
# -----------------------------------------------------------------------
# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
m4_define([lt_if_append_uniq],
[m4_ifdef([$1],
	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
		 [lt_append([$1], [$2], [$3])$4],
		 [$5])],
	  [lt_append([$1], [$2], [$3])$4])])


# lt_dict_add(DICT, KEY, VALUE)
# -----------------------------
m4_define([lt_dict_add],
[m4_define([$1($2)], [$3])])


# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
# --------------------------------------------
m4_define([lt_dict_add_subkey],
[m4_define([$1($2:$3)], [$4])])


# lt_dict_fetch(DICT, KEY, [SUBKEY])
# ----------------------------------
m4_define([lt_dict_fetch],
[m4_ifval([$3],
	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])


# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
# -----------------------------------------------------------------
m4_define([lt_if_dict_fetch],
[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
	[$5],
    [$6])])


# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
# --------------------------------------------------------------
m4_define([lt_dict_filter],
[m4_if([$5], [], [],
  [lt_join(m4_quote(m4_default([$4], [[, ]])),
           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
])

# ltversion.m4 -- version numbers			-*- Autoconf -*-
#
#   Copyright (C) 2004 Free Software Foundation, Inc.
#   Written by Scott James Remnant, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.

# Generated from ltversion.in.

# serial 3012 ltversion.m4
# This file is part of GNU Libtool

m4_define([LT_PACKAGE_VERSION], [2.2.6])
m4_define([LT_PACKAGE_REVISION], [1.3012])

AC_DEFUN([LTVERSION_VERSION],
[macro_version='2.2.6'
macro_revision='1.3012'
_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
_LT_DECL(, macro_revision, 0)
])

# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
#
#   Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc.
#   Written by Scott James Remnant, 2004.
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.

# serial 4 lt~obsolete.m4

# These exist entirely to fool aclocal when bootstrapping libtool.
#
# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
# which have later been changed to m4_define as they aren't part of the
# exported API, or moved to Autoconf or Automake where they belong.
#
# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
# using a macro with the same name in our local m4/libtool.m4 it'll
# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
# and doesn't know about Autoconf macros at all.)
#
# So we provide this file, which has a silly filename so it's always
# included after everything else.  This provides aclocal with the
# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
# because those macros already exist, or will be overwritten later.
# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
#
# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
# Yes, that means every name once taken will need to remain here until
# we give up compatibility with versions before 1.7, at which point
# we need to keep only those names which we still refer to.

# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])

m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
m4_ifndef([AC_LIBTOOL_RC],		[AC_DEFUN([AC_LIBTOOL_RC])])
m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])

Added addopcodes.awk.





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/awk
#
# This script appends additional token codes to the end of the
# parse.h file that lemon generates.  These extra token codes are
# not used by the parser.  But they are used by the tokenizer and/or
# the code generator.
#
#
BEGIN {
  max = 0
}
/^#define TK_/ {
  print $0
  if( max<$3 ) max = $3
}
END {
  printf "#define TK_%-29s %4d\n", "TO_TEXT",         ++max
  printf "#define TK_%-29s %4d\n", "TO_BLOB",         ++max
  printf "#define TK_%-29s %4d\n", "TO_NUMERIC",      ++max
  printf "#define TK_%-29s %4d\n", "TO_INT",          ++max
  printf "#define TK_%-29s %4d\n", "TO_REAL",         ++max
  printf "#define TK_%-29s %4d\n", "ISNOT",           ++max
  printf "#define TK_%-29s %4d\n", "END_OF_FILE",     ++max
  printf "#define TK_%-29s %4d\n", "ILLEGAL",         ++max
  printf "#define TK_%-29s %4d\n", "SPACE",           ++max
  printf "#define TK_%-29s %4d\n", "UNCLOSED_STRING", ++max
  printf "#define TK_%-29s %4d\n", "FUNCTION",        ++max
  printf "#define TK_%-29s %4d\n", "COLUMN",          ++max
  printf "#define TK_%-29s %4d\n", "AGG_FUNCTION",    ++max
  printf "#define TK_%-29s %4d\n", "AGG_COLUMN",      ++max
  printf "#define TK_%-29s %4d\n", "CONST_FUNC",      ++max
  printf "#define TK_%-29s %4d\n", "UMINUS",          ++max
  printf "#define TK_%-29s %4d\n", "UPLUS",           ++max
}

Added art/2005osaward.gif.

cannot compute difference between binary files

Added art/SQLite.eps.

cannot compute difference between binary files

Added art/SQLite.gif.

cannot compute difference between binary files

Added art/SQLiteLogo3.tiff.

cannot compute difference between binary files

Added art/SQLite_big.gif.

cannot compute difference between binary files

Added art/nocopy.gif.

cannot compute difference between binary files

Added art/powered_by_sqlite.gif.

cannot compute difference between binary files

Added art/src_logo.gif.

cannot compute difference between binary files

Added config.guess.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
#! /bin/sh
# Attempt to guess a canonical system name.
#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
#   Inc.

timestamp='2007-07-22'

# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.


# Originally written by Per Bothner <per@bothner.com>.
# Please send patches to <config-patches@gnu.org>.  Submit a context
# diff and a properly formatted ChangeLog entry.
#
# This script attempts to guess a canonical system name similar to
# config.sub.  If it succeeds, it prints the system name on stdout, and
# exits with 0.  Otherwise, it exits with 1.
#
# The plan is that this can be called by configure scripts if you
# don't specify an explicit build system type.

me=`echo "$0" | sed -e 's,.*/,,'`

usage="\
Usage: $0 [OPTION]

Output the configuration name of the system \`$me' is run on.

Operation modes:
  -h, --help         print this help, then exit
  -t, --time-stamp   print date of last modification, then exit
  -v, --version      print version number, then exit

Report bugs and patches to <config-patches@gnu.org>."

version="\
GNU config.guess ($timestamp)

Originally written by Per Bothner.
Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."

help="
Try \`$me --help' for more information."

# Parse command line
while test $# -gt 0 ; do
  case $1 in
    --time-stamp | --time* | -t )
       echo "$timestamp" ; exit ;;
    --version | -v )
       echo "$version" ; exit ;;
    --help | --h* | -h )
       echo "$usage"; exit ;;
    -- )     # Stop option processing
       shift; break ;;
    - )	# Use stdin as input.
       break ;;
    -* )
       echo "$me: invalid option $1$help" >&2
       exit 1 ;;
    * )
       break ;;
  esac
done

if test $# != 0; then
  echo "$me: too many arguments$help" >&2
  exit 1
fi

trap 'exit 1' 1 2 15

# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
# compiler to aid in system detection is discouraged as it requires
# temporary files to be created and, as you can see below, it is a
# headache to deal with in a portable fashion.

# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
# use `HOST_CC' if defined, but it is deprecated.

# Portable tmp directory creation inspired by the Autoconf team.

set_cc_for_build='
trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
: ${TMPDIR=/tmp} ;
 { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
 { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
 { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
 { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
dummy=$tmp/dummy ;
tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
case $CC_FOR_BUILD,$HOST_CC,$CC in
 ,,)    echo "int x;" > $dummy.c ;
	for c in cc gcc c89 c99 ; do
	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
	     CC_FOR_BUILD="$c"; break ;
	  fi ;
	done ;
	if test x"$CC_FOR_BUILD" = x ; then
	  CC_FOR_BUILD=no_compiler_found ;
	fi
	;;
 ,,*)   CC_FOR_BUILD=$CC ;;
 ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
esac ; set_cc_for_build= ;'

# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
# (ghazi@noc.rutgers.edu 1994-08-24)
if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
	PATH=$PATH:/.attbin ; export PATH
fi

UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown

if [ "${UNAME_SYSTEM}" = "Linux" ] ; then
	eval $set_cc_for_build
	cat << EOF > $dummy.c
	#include <features.h>
	#ifdef __UCLIBC__
	# ifdef __UCLIBC_CONFIG_VERSION__
	LIBC=uclibc __UCLIBC_CONFIG_VERSION__
	# else
	LIBC=uclibc
	# endif
	#else
	LIBC=gnu
	#endif
EOF
	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep LIBC= | sed -e 's: ::g'`
fi

# Note: order is significant - the case branches are not exclusive.

case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
    *:NetBSD:*:*)
	# NetBSD (nbsd) targets should (where applicable) match one or
	# more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
	# switched to ELF, *-*-netbsd* would select the old
	# object file format.  This provides both forward
	# compatibility and a consistent mechanism for selecting the
	# object file format.
	#
	# Note: NetBSD doesn't particularly care about the vendor
	# portion of the name.  We always set it to "unknown".
	sysctl="sysctl -n hw.machine_arch"
	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
	case "${UNAME_MACHINE_ARCH}" in
	    armeb) machine=armeb-unknown ;;
	    arm*) machine=arm-unknown ;;
	    sh3el) machine=shl-unknown ;;
	    sh3eb) machine=sh-unknown ;;
	    sh5el) machine=sh5le-unknown ;;
	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
	esac
	# The Operating System including object format, if it has switched
	# to ELF recently, or will in the future.
	case "${UNAME_MACHINE_ARCH}" in
	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
		eval $set_cc_for_build
		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
			| grep __ELF__ >/dev/null
		then
		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
		    # Return netbsd for either.  FIX?
		    os=netbsd
		else
		    os=netbsdelf
		fi
		;;
	    *)
	        os=netbsd
		;;
	esac
	# The OS release
	# Debian GNU/NetBSD machines have a different userland, and
	# thus, need a distinct triplet. However, they do not need
	# kernel version information, so it can be replaced with a
	# suitable tag, in the style of linux-gnu.
	case "${UNAME_VERSION}" in
	    Debian*)
		release='-gnu'
		;;
	    *)
		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
		;;
	esac
	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
	# contains redundant information, the shorter form:
	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
	echo "${machine}-${os}${release}"
	exit ;;
    *:OpenBSD:*:*)
	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
	exit ;;
    *:ekkoBSD:*:*)
	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
	exit ;;
    *:SolidBSD:*:*)
	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
	exit ;;
    macppc:MirBSD:*:*)
	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
	exit ;;
    *:MirBSD:*:*)
	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
	exit ;;
    alpha:OSF1:*:*)
	case $UNAME_RELEASE in
	*4.0)
		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
		;;
	*5.*)
	        UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
		;;
	esac
	# According to Compaq, /usr/sbin/psrinfo has been available on
	# OSF/1 and Tru64 systems produced since 1995.  I hope that
	# covers most systems running today.  This code pipes the CPU
	# types through head -n 1, so we only detect the type of CPU 0.
	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
	case "$ALPHA_CPU_TYPE" in
	    "EV4 (21064)")
		UNAME_MACHINE="alpha" ;;
	    "EV4.5 (21064)")
		UNAME_MACHINE="alpha" ;;
	    "LCA4 (21066/21068)")
		UNAME_MACHINE="alpha" ;;
	    "EV5 (21164)")
		UNAME_MACHINE="alphaev5" ;;
	    "EV5.6 (21164A)")
		UNAME_MACHINE="alphaev56" ;;
	    "EV5.6 (21164PC)")
		UNAME_MACHINE="alphapca56" ;;
	    "EV5.7 (21164PC)")
		UNAME_MACHINE="alphapca57" ;;
	    "EV6 (21264)")
		UNAME_MACHINE="alphaev6" ;;
	    "EV6.7 (21264A)")
		UNAME_MACHINE="alphaev67" ;;
	    "EV6.8CB (21264C)")
		UNAME_MACHINE="alphaev68" ;;
	    "EV6.8AL (21264B)")
		UNAME_MACHINE="alphaev68" ;;
	    "EV6.8CX (21264D)")
		UNAME_MACHINE="alphaev68" ;;
	    "EV6.9A (21264/EV69A)")
		UNAME_MACHINE="alphaev69" ;;
	    "EV7 (21364)")
		UNAME_MACHINE="alphaev7" ;;
	    "EV7.9 (21364A)")
		UNAME_MACHINE="alphaev79" ;;
	esac
	# A Pn.n version is a patched version.
	# A Vn.n version is a released version.
	# A Tn.n version is a released field test version.
	# A Xn.n version is an unreleased experimental baselevel.
	# 1.2 uses "1.2" for uname -r.
	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
	exit ;;
    Alpha\ *:Windows_NT*:*)
	# How do we know it's Interix rather than the generic POSIX subsystem?
	# Should we change UNAME_MACHINE based on the output of uname instead
	# of the specific Alpha model?
	echo alpha-pc-interix
	exit ;;
    21064:Windows_NT:50:3)
	echo alpha-dec-winnt3.5
	exit ;;
    Amiga*:UNIX_System_V:4.0:*)
	echo m68k-unknown-sysv4
	exit ;;
    *:[Aa]miga[Oo][Ss]:*:*)
	echo ${UNAME_MACHINE}-unknown-amigaos
	exit ;;
    *:[Mm]orph[Oo][Ss]:*:*)
	echo ${UNAME_MACHINE}-unknown-morphos
	exit ;;
    *:OS/390:*:*)
	echo i370-ibm-openedition
	exit ;;
    *:z/VM:*:*)
	echo s390-ibm-zvmoe
	exit ;;
    *:OS400:*:*)
        echo powerpc-ibm-os400
	exit ;;
    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
	echo arm-acorn-riscix${UNAME_RELEASE}
	exit ;;
    arm:riscos:*:*|arm:RISCOS:*:*)
	echo arm-unknown-riscos
	exit ;;
    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
	echo hppa1.1-hitachi-hiuxmpp
	exit ;;
    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
	if test "`(/bin/universe) 2>/dev/null`" = att ; then
		echo pyramid-pyramid-sysv3
	else
		echo pyramid-pyramid-bsd
	fi
	exit ;;
    NILE*:*:*:dcosx)
	echo pyramid-pyramid-svr4
	exit ;;
    DRS?6000:unix:4.0:6*)
	echo sparc-icl-nx6
	exit ;;
    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
	case `/usr/bin/uname -p` in
	    sparc) echo sparc-icl-nx7; exit ;;
	esac ;;
    sun4H:SunOS:5.*:*)
	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
	exit ;;
    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
	exit ;;
    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
	exit ;;
    sun4*:SunOS:6*:*)
	# According to config.sub, this is the proper way to canonicalize
	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
	# it's likely to be more like Solaris than SunOS4.
	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
	exit ;;
    sun4*:SunOS:*:*)
	case "`/usr/bin/arch -k`" in
	    Series*|S4*)
		UNAME_RELEASE=`uname -v`
		;;
	esac
	# Japanese Language versions have a version number like `4.1.3-JL'.
	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
	exit ;;
    sun3*:SunOS:*:*)
	echo m68k-sun-sunos${UNAME_RELEASE}
	exit ;;
    sun*:*:4.2BSD:*)
	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
	case "`/bin/arch`" in
	    sun3)
		echo m68k-sun-sunos${UNAME_RELEASE}
		;;
	    sun4)
		echo sparc-sun-sunos${UNAME_RELEASE}
		;;
	esac
	exit ;;
    aushp:SunOS:*:*)
	echo sparc-auspex-sunos${UNAME_RELEASE}
	exit ;;
    # The situation for MiNT is a little confusing.  The machine name
    # can be virtually everything (everything which is not
    # "atarist" or "atariste" at least should have a processor
    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
    # to the lowercase version "mint" (or "freemint").  Finally
    # the system name "TOS" denotes a system which is actually not
    # MiNT.  But MiNT is downward compatible to TOS, so this should
    # be no problem.
    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
        echo m68k-atari-mint${UNAME_RELEASE}
	exit ;;
    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
	echo m68k-atari-mint${UNAME_RELEASE}
        exit ;;
    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
        echo m68k-atari-mint${UNAME_RELEASE}
	exit ;;
    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
        echo m68k-milan-mint${UNAME_RELEASE}
        exit ;;
    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
        echo m68k-hades-mint${UNAME_RELEASE}
        exit ;;
    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
        echo m68k-unknown-mint${UNAME_RELEASE}
        exit ;;
    m68k:machten:*:*)
	echo m68k-apple-machten${UNAME_RELEASE}
	exit ;;
    powerpc:machten:*:*)
	echo powerpc-apple-machten${UNAME_RELEASE}
	exit ;;
    RISC*:Mach:*:*)
	echo mips-dec-mach_bsd4.3
	exit ;;
    RISC*:ULTRIX:*:*)
	echo mips-dec-ultrix${UNAME_RELEASE}
	exit ;;
    VAX*:ULTRIX*:*:*)
	echo vax-dec-ultrix${UNAME_RELEASE}
	exit ;;
    2020:CLIX:*:* | 2430:CLIX:*:*)
	echo clipper-intergraph-clix${UNAME_RELEASE}
	exit ;;
    mips:*:*:UMIPS | mips:*:*:RISCos)
	eval $set_cc_for_build
	sed 's/^	//' << EOF >$dummy.c
#ifdef __cplusplus
#include <stdio.h>  /* for printf() prototype */
	int main (int argc, char *argv[]) {
#else
	int main (argc, argv) int argc; char *argv[]; {
#endif
	#if defined (host_mips) && defined (MIPSEB)
	#if defined (SYSTYPE_SYSV)
	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
	#endif
	#if defined (SYSTYPE_SVR4)
	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
	#endif
	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
	#endif
	#endif
	  exit (-1);
	}
EOF
	$CC_FOR_BUILD -o $dummy $dummy.c &&
	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
	  SYSTEM_NAME=`$dummy $dummyarg` &&
	    { echo "$SYSTEM_NAME"; exit; }
	echo mips-mips-riscos${UNAME_RELEASE}
	exit ;;
    Motorola:PowerMAX_OS:*:*)
	echo powerpc-motorola-powermax
	exit ;;
    Motorola:*:4.3:PL8-*)
	echo powerpc-harris-powermax
	exit ;;
    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
	echo powerpc-harris-powermax
	exit ;;
    Night_Hawk:Power_UNIX:*:*)
	echo powerpc-harris-powerunix
	exit ;;
    m88k:CX/UX:7*:*)
	echo m88k-harris-cxux7
	exit ;;
    m88k:*:4*:R4*)
	echo m88k-motorola-sysv4
	exit ;;
    m88k:*:3*:R3*)
	echo m88k-motorola-sysv3
	exit ;;
    AViiON:dgux:*:*)
        # DG/UX returns AViiON for all architectures
        UNAME_PROCESSOR=`/usr/bin/uname -p`
	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
	then
	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
	       [ ${TARGET_BINARY_INTERFACE}x = x ]
	    then
		echo m88k-dg-dgux${UNAME_RELEASE}
	    else
		echo m88k-dg-dguxbcs${UNAME_RELEASE}
	    fi
	else
	    echo i586-dg-dgux${UNAME_RELEASE}
	fi
 	exit ;;
    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
	echo m88k-dolphin-sysv3
	exit ;;
    M88*:*:R3*:*)
	# Delta 88k system running SVR3
	echo m88k-motorola-sysv3
	exit ;;
    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
	echo m88k-tektronix-sysv3
	exit ;;
    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
	echo m68k-tektronix-bsd
	exit ;;
    *:IRIX*:*:*)
	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
	exit ;;
    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
    i*86:AIX:*:*)
	echo i386-ibm-aix
	exit ;;
    ia64:AIX:*:*)
	if [ -x /usr/bin/oslevel ] ; then
		IBM_REV=`/usr/bin/oslevel`
	else
		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
	fi
	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
	exit ;;
    *:AIX:2:3)
	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
		eval $set_cc_for_build
		sed 's/^		//' << EOF >$dummy.c
		#include <sys/systemcfg.h>

		main()
			{
			if (!__power_pc())
				exit(1);
			puts("powerpc-ibm-aix3.2.5");
			exit(0);
			}
EOF
		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
		then
			echo "$SYSTEM_NAME"
		else
			echo rs6000-ibm-aix3.2.5
		fi
	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
		echo rs6000-ibm-aix3.2.4
	else
		echo rs6000-ibm-aix3.2
	fi
	exit ;;
    *:AIX:*:[45])
	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
		IBM_ARCH=rs6000
	else
		IBM_ARCH=powerpc
	fi
	if [ -x /usr/bin/oslevel ] ; then
		IBM_REV=`/usr/bin/oslevel`
	else
		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
	fi
	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
	exit ;;
    *:AIX:*:*)
	echo rs6000-ibm-aix
	exit ;;
    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
	echo romp-ibm-bsd4.4
	exit ;;
    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
	exit ;;                             # report: romp-ibm BSD 4.3
    *:BOSX:*:*)
	echo rs6000-bull-bosx
	exit ;;
    DPX/2?00:B.O.S.:*:*)
	echo m68k-bull-sysv3
	exit ;;
    9000/[34]??:4.3bsd:1.*:*)
	echo m68k-hp-bsd
	exit ;;
    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
	echo m68k-hp-bsd4.4
	exit ;;
    9000/[34678]??:HP-UX:*:*)
	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
	case "${UNAME_MACHINE}" in
	    9000/31? )            HP_ARCH=m68000 ;;
	    9000/[34]?? )         HP_ARCH=m68k ;;
	    9000/[678][0-9][0-9])
		if [ -x /usr/bin/getconf ]; then
		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
                    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
                    case "${sc_cpu_version}" in
                      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
                      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
                      532)                      # CPU_PA_RISC2_0
                        case "${sc_kernel_bits}" in
                          32) HP_ARCH="hppa2.0n" ;;
                          64) HP_ARCH="hppa2.0w" ;;
			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
                        esac ;;
                    esac
		fi
		if [ "${HP_ARCH}" = "" ]; then
		    eval $set_cc_for_build
		    sed 's/^              //' << EOF >$dummy.c

              #define _HPUX_SOURCE
              #include <stdlib.h>
              #include <unistd.h>

              int main ()
              {
              #if defined(_SC_KERNEL_BITS)
                  long bits = sysconf(_SC_KERNEL_BITS);
              #endif
                  long cpu  = sysconf (_SC_CPU_VERSION);

                  switch (cpu)
              	{
              	case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
              	case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
              	case CPU_PA_RISC2_0:
              #if defined(_SC_KERNEL_BITS)
              	    switch (bits)
              		{
              		case 64: puts ("hppa2.0w"); break;
              		case 32: puts ("hppa2.0n"); break;
              		default: puts ("hppa2.0"); break;
              		} break;
              #else  /* !defined(_SC_KERNEL_BITS) */
              	    puts ("hppa2.0"); break;
              #endif
              	default: puts ("hppa1.0"); break;
              	}
                  exit (0);
              }
EOF
		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
		    test -z "$HP_ARCH" && HP_ARCH=hppa
		fi ;;
	esac
	if [ ${HP_ARCH} = "hppa2.0w" ]
	then
	    eval $set_cc_for_build

	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
	    # generating 64-bit code.  GNU and HP use different nomenclature:
	    #
	    # $ CC_FOR_BUILD=cc ./config.guess
	    # => hppa2.0w-hp-hpux11.23
	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
	    # => hppa64-hp-hpux11.23

	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
		grep __LP64__ >/dev/null
	    then
		HP_ARCH="hppa2.0w"
	    else
		HP_ARCH="hppa64"
	    fi
	fi
	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
	exit ;;
    ia64:HP-UX:*:*)
	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
	echo ia64-hp-hpux${HPUX_REV}
	exit ;;
    3050*:HI-UX:*:*)
	eval $set_cc_for_build
	sed 's/^	//' << EOF >$dummy.c
	#include <unistd.h>
	int
	main ()
	{
	  long cpu = sysconf (_SC_CPU_VERSION);
	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
	     results, however.  */
	  if (CPU_IS_PA_RISC (cpu))
	    {
	      switch (cpu)
		{
		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
		  default: puts ("hppa-hitachi-hiuxwe2"); break;
		}
	    }
	  else if (CPU_IS_HP_MC68K (cpu))
	    puts ("m68k-hitachi-hiuxwe2");
	  else puts ("unknown-hitachi-hiuxwe2");
	  exit (0);
	}
EOF
	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
		{ echo "$SYSTEM_NAME"; exit; }
	echo unknown-hitachi-hiuxwe2
	exit ;;
    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
	echo hppa1.1-hp-bsd
	exit ;;
    9000/8??:4.3bsd:*:*)
	echo hppa1.0-hp-bsd
	exit ;;
    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
	echo hppa1.0-hp-mpeix
	exit ;;
    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
	echo hppa1.1-hp-osf
	exit ;;
    hp8??:OSF1:*:*)
	echo hppa1.0-hp-osf
	exit ;;
    i*86:OSF1:*:*)
	if [ -x /usr/sbin/sysversion ] ; then
	    echo ${UNAME_MACHINE}-unknown-osf1mk
	else
	    echo ${UNAME_MACHINE}-unknown-osf1
	fi
	exit ;;
    parisc*:Lites*:*:*)
	echo hppa1.1-hp-lites
	exit ;;
    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
	echo c1-convex-bsd
        exit ;;
    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
	if getsysinfo -f scalar_acc
	then echo c32-convex-bsd
	else echo c2-convex-bsd
	fi
        exit ;;
    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
	echo c34-convex-bsd
        exit ;;
    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
	echo c38-convex-bsd
        exit ;;
    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
	echo c4-convex-bsd
        exit ;;
    CRAY*Y-MP:*:*:*)
	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
	exit ;;
    CRAY*[A-Z]90:*:*:*)
	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
	      -e 's/\.[^.]*$/.X/'
	exit ;;
    CRAY*TS:*:*:*)
	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
	exit ;;
    CRAY*T3E:*:*:*)
	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
	exit ;;
    CRAY*SV1:*:*:*)
	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
	exit ;;
    *:UNICOS/mp:*:*)
	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
	exit ;;
    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
        FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
        echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
        exit ;;
    5000:UNIX_System_V:4.*:*)
        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
        FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
	exit ;;
    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
	exit ;;
    sparc*:BSD/OS:*:*)
	echo sparc-unknown-bsdi${UNAME_RELEASE}
	exit ;;
    *:BSD/OS:*:*)
	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
	exit ;;
    *:FreeBSD:*:*)
	case ${UNAME_MACHINE} in
	    pc98)
		echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
	    amd64)
		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
	    *)
		echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
	esac
	exit ;;
    i*:CYGWIN*:*)
	echo ${UNAME_MACHINE}-pc-cygwin
	exit ;;
    *:MINGW*:*)
	echo ${UNAME_MACHINE}-pc-mingw32
	exit ;;
    i*:windows32*:*)
    	# uname -m includes "-pc" on this system.
    	echo ${UNAME_MACHINE}-mingw32
	exit ;;
    i*:PW*:*)
	echo ${UNAME_MACHINE}-pc-pw32
	exit ;;
    *:Interix*:[3456]*)
    	case ${UNAME_MACHINE} in
	    x86)
		echo i586-pc-interix${UNAME_RELEASE}
		exit ;;
	    EM64T | authenticamd)
		echo x86_64-unknown-interix${UNAME_RELEASE}
		exit ;;
	esac ;;
    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
	echo i${UNAME_MACHINE}-pc-mks
	exit ;;
    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
	# How do we know it's Interix rather than the generic POSIX subsystem?
	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
	# UNAME_MACHINE based on the output of uname instead of i386?
	echo i586-pc-interix
	exit ;;
    i*:UWIN*:*)
	echo ${UNAME_MACHINE}-pc-uwin
	exit ;;
    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
	echo x86_64-unknown-cygwin
	exit ;;
    p*:CYGWIN*:*)
	echo powerpcle-unknown-cygwin
	exit ;;
    prep*:SunOS:5.*:*)
	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
	exit ;;
    *:GNU:*:*)
	# the GNU system
	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
	exit ;;
    *:GNU/*:*:*)
	# other systems with GNU libc and userland
	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
	exit ;;
    i*86:Minix:*:*)
	echo ${UNAME_MACHINE}-pc-minix
	exit ;;
    arm*:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    avr32*:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    cris:Linux:*:*)
	echo cris-axis-linux-${LIBC}
	exit ;;
    crisv32:Linux:*:*)
	echo crisv32-axis-linux-${LIBC}
	exit ;;
    frv:Linux:*:*)
    	echo frv-unknown-linux-${LIBC}
	exit ;;
    ia64:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    m32r*:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    m68*:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    mips:Linux:*:*)
	eval $set_cc_for_build
	sed 's/^	//' << EOF >$dummy.c
	#undef CPU
	#undef mips
	#undef mipsel
	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
	CPU=mipsel
	#else
	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
	CPU=mips
	#else
	CPU=
	#endif
	#endif
EOF
	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
	    /^CPU/{
		s: ::g
		p
	    }'`"
	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
	;;
    mips64:Linux:*:*)
	eval $set_cc_for_build
	sed 's/^	//' << EOF >$dummy.c
	#undef CPU
	#undef mips64
	#undef mips64el
	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
	CPU=mips64el
	#else
	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
	CPU=mips64
	#else
	CPU=
	#endif
	#endif
EOF
	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
	    /^CPU/{
		s: ::g
		p
	    }'`"
	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
	;;
    or32:Linux:*:*)
	echo or32-unknown-linux-${LIBC}
	exit ;;
    ppc:Linux:*:*)
	echo powerpc-unknown-linux-${LIBC}
	exit ;;
    ppc64:Linux:*:*)
	echo powerpc64-unknown-linux-${LIBC}
	exit ;;
    alpha:Linux:*:*)
	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
	  EV5)   UNAME_MACHINE=alphaev5 ;;
	  EV56)  UNAME_MACHINE=alphaev56 ;;
	  PCA56) UNAME_MACHINE=alphapca56 ;;
	  PCA57) UNAME_MACHINE=alphapca56 ;;
	  EV6)   UNAME_MACHINE=alphaev6 ;;
	  EV67)  UNAME_MACHINE=alphaev67 ;;
	  EV68*) UNAME_MACHINE=alphaev68 ;;
        esac
	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    parisc:Linux:*:* | hppa:Linux:*:*)
	# Look for CPU level
	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
	  *)    echo hppa-unknown-linux-${LIBC} ;;
	esac
	exit ;;
    parisc64:Linux:*:* | hppa64:Linux:*:*)
	echo hppa64-unknown-linux-${LIBC}
	exit ;;
    s390:Linux:*:* | s390x:Linux:*:*)
	echo ${UNAME_MACHINE}-ibm-linux
	exit ;;
    sh64*:Linux:*:*)
    	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    sh*:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    sparc:Linux:*:* | sparc64:Linux:*:*)
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
	exit ;;
    vax:Linux:*:*)
	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
	exit ;;
    x86_64:Linux:*:*)
	echo x86_64-unknown-linux-${LIBC}
	exit ;;
    xtensa:Linux:*:*)
    	echo xtensa-unknown-linux-${LIBC}
	exit ;;
    i*86:Linux:*:*)
	# The BFD linker knows what the default object file format is, so
	# first see if it will tell us. cd to the root directory to prevent
	# problems with other programs or directories called `ld' in the path.
	# Set LC_ALL=C to ensure ld outputs messages in English.
	ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
			 | sed -ne '/supported targets:/!d
				    s/[ 	][ 	]*/ /g
				    s/.*supported targets: *//
				    s/ .*//
				    p'`
        case "$ld_supported_targets" in
	  elf32-i386)
		TENTATIVE="${UNAME_MACHINE}-pc-linux-${LIBC}"
		;;
	  a.out-i386-linux)
		echo "${UNAME_MACHINE}-pc-linux-${LIBC}aout"
		exit ;;
	  coff-i386)
		echo "${UNAME_MACHINE}-pc-linux-${LIBC}coff"
		exit ;;
	  "")
		# Either a pre-BFD a.out linker (linux-gnuoldld) or
		# one that does not give us useful --help.
		echo "${UNAME_MACHINE}-pc-linux-${LIBC}oldld"
		exit ;;
	esac
	# This should get integrated into the C code below, but now we hack
	if [ "$LIBC" != "gnu" ] ; then echo "$TENTATIVE" && exit 0 ; fi
	# Determine whether the default compiler is a.out or elf
	eval $set_cc_for_build
	sed 's/^	//' << EOF >$dummy.c
	#include <features.h>
	#ifdef __ELF__
	# ifdef __GLIBC__
	#  if __GLIBC__ >= 2
	LIBC=gnu
	#  else
	LIBC=gnulibc1
	#  endif
	# else
	LIBC=gnulibc1
	# endif
	#else
	#if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC)
	LIBC=gnu
	#else
	LIBC=gnuaout
	#endif
	#endif
	#ifdef __dietlibc__
	LIBC=dietlibc
	#endif
EOF
	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
	    /^LIBC/{
		s: ::g
		p
	    }'`"
	test x"${LIBC}" != x && {
		echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
		exit
	}
	test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; }
	;;
    i*86:DYNIX/ptx:4*:*)
	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
	# earlier versions are messed up and put the nodename in both
	# sysname and nodename.
	echo i386-sequent-sysv4
	exit ;;
    i*86:UNIX_SV:4.2MP:2.*)
        # Unixware is an offshoot of SVR4, but it has its own version
        # number series starting with 2...
        # I am not positive that other SVR4 systems won't match this,
	# I just have to hope.  -- rms.
        # Use sysv4.2uw... so that sysv4* matches it.
	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
	exit ;;
    i*86:OS/2:*:*)
	# If we were able to find `uname', then EMX Unix compatibility
	# is probably installed.
	echo ${UNAME_MACHINE}-pc-os2-emx
	exit ;;
    i*86:XTS-300:*:STOP)
	echo ${UNAME_MACHINE}-unknown-stop
	exit ;;
    i*86:atheos:*:*)
	echo ${UNAME_MACHINE}-unknown-atheos
	exit ;;
    i*86:syllable:*:*)
	echo ${UNAME_MACHINE}-pc-syllable
	exit ;;
    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
	echo i386-unknown-lynxos${UNAME_RELEASE}
	exit ;;
    i*86:*DOS:*:*)
	echo ${UNAME_MACHINE}-pc-msdosdjgpp
	exit ;;
    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
	else
		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
	fi
	exit ;;
    i*86:*:5:[678]*)
    	# UnixWare 7.x, OpenUNIX and OpenServer 6.
	case `/bin/uname -X | grep "^Machine"` in
	    *486*)	     UNAME_MACHINE=i486 ;;
	    *Pentium)	     UNAME_MACHINE=i586 ;;
	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
	esac
	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
	exit ;;
    i*86:*:3.2:*)
	if test -f /usr/options/cb.name; then
		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
	elif /bin/uname -X 2>/dev/null >/dev/null ; then
		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
			&& UNAME_MACHINE=i586
		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
			&& UNAME_MACHINE=i686
		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
			&& UNAME_MACHINE=i686
		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
	else
		echo ${UNAME_MACHINE}-pc-sysv32
	fi
	exit ;;
    pc:*:*:*)
	# Left here for compatibility:
        # uname -m prints for DJGPP always 'pc', but it prints nothing about
        # the processor, so we play safe by assuming i386.
	echo i386-pc-msdosdjgpp
        exit ;;
    Intel:Mach:3*:*)
	echo i386-pc-mach3
	exit ;;
    paragon:*:*:*)
	echo i860-intel-osf1
	exit ;;
    i860:*:4.*:*) # i860-SVR4
	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
	else # Add other i860-SVR4 vendors below as they are discovered.
	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
	fi
	exit ;;
    mini*:CTIX:SYS*5:*)
	# "miniframe"
	echo m68010-convergent-sysv
	exit ;;
    mc68k:UNIX:SYSTEM5:3.51m)
	echo m68k-convergent-sysv
	exit ;;
    M680?0:D-NIX:5.3:*)
	echo m68k-diab-dnix
	exit ;;
    M68*:*:R3V[5678]*:*)
	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
	OS_REL=''
	test -r /etc/.relid \
	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
        /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
          && { echo i486-ncr-sysv4; exit; } ;;
    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
	echo m68k-unknown-lynxos${UNAME_RELEASE}
	exit ;;
    mc68030:UNIX_System_V:4.*:*)
	echo m68k-atari-sysv4
	exit ;;
    TSUNAMI:LynxOS:2.*:*)
	echo sparc-unknown-lynxos${UNAME_RELEASE}
	exit ;;
    rs6000:LynxOS:2.*:*)
	echo rs6000-unknown-lynxos${UNAME_RELEASE}
	exit ;;
    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
	echo powerpc-unknown-lynxos${UNAME_RELEASE}
	exit ;;
    SM[BE]S:UNIX_SV:*:*)
	echo mips-dde-sysv${UNAME_RELEASE}
	exit ;;
    RM*:ReliantUNIX-*:*:*)
	echo mips-sni-sysv4
	exit ;;
    RM*:SINIX-*:*:*)
	echo mips-sni-sysv4
	exit ;;
    *:SINIX-*:*:*)
	if uname -p 2>/dev/null >/dev/null ; then
		UNAME_MACHINE=`(uname -p) 2>/dev/null`
		echo ${UNAME_MACHINE}-sni-sysv4
	else
		echo ns32k-sni-sysv
	fi
	exit ;;
    PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
                      # says <Richard.M.Bartel@ccMail.Census.GOV>
        echo i586-unisys-sysv4
        exit ;;
    *:UNIX_System_V:4*:FTX*)
	# From Gerald Hewes <hewes@openmarket.com>.
	# How about differentiating between stratus architectures? -djm
	echo hppa1.1-stratus-sysv4
	exit ;;
    *:*:*:FTX*)
	# From seanf@swdc.stratus.com.
	echo i860-stratus-sysv4
	exit ;;
    i*86:VOS:*:*)
	# From Paul.Green@stratus.com.
	echo ${UNAME_MACHINE}-stratus-vos
	exit ;;
    *:VOS:*:*)
	# From Paul.Green@stratus.com.
	echo hppa1.1-stratus-vos
	exit ;;
    mc68*:A/UX:*:*)
	echo m68k-apple-aux${UNAME_RELEASE}
	exit ;;
    news*:NEWS-OS:6*:*)
	echo mips-sony-newsos6
	exit ;;
    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
	if [ -d /usr/nec ]; then
	        echo mips-nec-sysv${UNAME_RELEASE}
	else
	        echo mips-unknown-sysv${UNAME_RELEASE}
	fi
        exit ;;
    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
	echo powerpc-be-beos
	exit ;;
    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
	echo powerpc-apple-beos
	exit ;;
    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
	echo i586-pc-beos
	exit ;;
    SX-4:SUPER-UX:*:*)
	echo sx4-nec-superux${UNAME_RELEASE}
	exit ;;
    SX-5:SUPER-UX:*:*)
	echo sx5-nec-superux${UNAME_RELEASE}
	exit ;;
    SX-6:SUPER-UX:*:*)
	echo sx6-nec-superux${UNAME_RELEASE}
	exit ;;
    SX-7:SUPER-UX:*:*)
	echo sx7-nec-superux${UNAME_RELEASE}
	exit ;;
    SX-8:SUPER-UX:*:*)
	echo sx8-nec-superux${UNAME_RELEASE}
	exit ;;
    SX-8R:SUPER-UX:*:*)
	echo sx8r-nec-superux${UNAME_RELEASE}
	exit ;;
    Power*:Rhapsody:*:*)
	echo powerpc-apple-rhapsody${UNAME_RELEASE}
	exit ;;
    *:Rhapsody:*:*)
	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
	exit ;;
    *:Darwin:*:*)
	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
	case $UNAME_PROCESSOR in
	    unknown) UNAME_PROCESSOR=powerpc ;;
	esac
	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
	exit ;;
    *:procnto*:*:* | *:QNX:[0123456789]*:*)
	UNAME_PROCESSOR=`uname -p`
	if test "$UNAME_PROCESSOR" = "x86"; then
		UNAME_PROCESSOR=i386
		UNAME_MACHINE=pc
	fi
	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
	exit ;;
    *:QNX:*:4*)
	echo i386-pc-qnx
	exit ;;
    NSE-?:NONSTOP_KERNEL:*:*)
	echo nse-tandem-nsk${UNAME_RELEASE}
	exit ;;
    NSR-?:NONSTOP_KERNEL:*:*)
	echo nsr-tandem-nsk${UNAME_RELEASE}
	exit ;;
    *:NonStop-UX:*:*)
	echo mips-compaq-nonstopux
	exit ;;
    BS2000:POSIX*:*:*)
	echo bs2000-siemens-sysv
	exit ;;
    DS/*:UNIX_System_V:*:*)
	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
	exit ;;
    *:Plan9:*:*)
	# "uname -m" is not consistent, so use $cputype instead. 386
	# is converted to i386 for consistency with other x86
	# operating systems.
	if test "$cputype" = "386"; then
	    UNAME_MACHINE=i386
	else
	    UNAME_MACHINE="$cputype"
	fi
	echo ${UNAME_MACHINE}-unknown-plan9
	exit ;;
    *:TOPS-10:*:*)
	echo pdp10-unknown-tops10
	exit ;;
    *:TENEX:*:*)
	echo pdp10-unknown-tenex
	exit ;;
    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
	echo pdp10-dec-tops20
	exit ;;
    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
	echo pdp10-xkl-tops20
	exit ;;
    *:TOPS-20:*:*)
	echo pdp10-unknown-tops20
	exit ;;
    *:ITS:*:*)
	echo pdp10-unknown-its
	exit ;;
    SEI:*:*:SEIUX)
        echo mips-sei-seiux${UNAME_RELEASE}
	exit ;;
    *:DragonFly:*:*)
	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
	exit ;;
    *:*VMS:*:*)
    	UNAME_MACHINE=`(uname -p) 2>/dev/null`
	case "${UNAME_MACHINE}" in
	    A*) echo alpha-dec-vms ; exit ;;
	    I*) echo ia64-dec-vms ; exit ;;
	    V*) echo vax-dec-vms ; exit ;;
	esac ;;
    *:XENIX:*:SysV)
	echo i386-pc-xenix
	exit ;;
    i*86:skyos:*:*)
	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
	exit ;;
    i*86:rdos:*:*)
	echo ${UNAME_MACHINE}-pc-rdos
	exit ;;
esac

#echo '(No uname command or uname output not recognized.)' 1>&2
#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2

eval $set_cc_for_build
cat >$dummy.c <<EOF
#ifdef _SEQUENT_
# include <sys/types.h>
# include <sys/utsname.h>
#endif
main ()
{
#if defined (sony)
#if defined (MIPSEB)
  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
     I don't know....  */
  printf ("mips-sony-bsd\n"); exit (0);
#else
#include <sys/param.h>
  printf ("m68k-sony-newsos%s\n",
#ifdef NEWSOS4
          "4"
#else
	  ""
#endif
         ); exit (0);
#endif
#endif

#if defined (__arm) && defined (__acorn) && defined (__unix)
  printf ("arm-acorn-riscix\n"); exit (0);
#endif

#if defined (hp300) && !defined (hpux)
  printf ("m68k-hp-bsd\n"); exit (0);
#endif

#if defined (NeXT)
#if !defined (__ARCHITECTURE__)
#define __ARCHITECTURE__ "m68k"
#endif
  int version;
  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
  if (version < 4)
    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
  else
    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
  exit (0);
#endif

#if defined (MULTIMAX) || defined (n16)
#if defined (UMAXV)
  printf ("ns32k-encore-sysv\n"); exit (0);
#else
#if defined (CMU)
  printf ("ns32k-encore-mach\n"); exit (0);
#else
  printf ("ns32k-encore-bsd\n"); exit (0);
#endif
#endif
#endif

#if defined (__386BSD__)
  printf ("i386-pc-bsd\n"); exit (0);
#endif

#if defined (sequent)
#if defined (i386)
  printf ("i386-sequent-dynix\n"); exit (0);
#endif
#if defined (ns32000)
  printf ("ns32k-sequent-dynix\n"); exit (0);
#endif
#endif

#if defined (_SEQUENT_)
    struct utsname un;

    uname(&un);

    if (strncmp(un.version, "V2", 2) == 0) {
	printf ("i386-sequent-ptx2\n"); exit (0);
    }
    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
	printf ("i386-sequent-ptx1\n"); exit (0);
    }
    printf ("i386-sequent-ptx\n"); exit (0);

#endif

#if defined (vax)
# if !defined (ultrix)
#  include <sys/param.h>
#  if defined (BSD)
#   if BSD == 43
      printf ("vax-dec-bsd4.3\n"); exit (0);
#   else
#    if BSD == 199006
      printf ("vax-dec-bsd4.3reno\n"); exit (0);
#    else
      printf ("vax-dec-bsd\n"); exit (0);
#    endif
#   endif
#  else
    printf ("vax-dec-bsd\n"); exit (0);
#  endif
# else
    printf ("vax-dec-ultrix\n"); exit (0);
# endif
#endif

#if defined (alliant) && defined (i860)
  printf ("i860-alliant-bsd\n"); exit (0);
#endif

  exit (1);
}
EOF

$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
	{ echo "$SYSTEM_NAME"; exit; }

# Apollos put the system type in the environment.

test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }

# Convex versions that predate uname can use getsysinfo(1)

if [ -x /usr/convex/getsysinfo ]
then
    case `getsysinfo -f cpu_type` in
    c1*)
	echo c1-convex-bsd
	exit ;;
    c2*)
	if getsysinfo -f scalar_acc
	then echo c32-convex-bsd
	else echo c2-convex-bsd
	fi
	exit ;;
    c34*)
	echo c34-convex-bsd
	exit ;;
    c38*)
	echo c38-convex-bsd
	exit ;;
    c4*)
	echo c4-convex-bsd
	exit ;;
    esac
fi

cat >&2 <<EOF
$0: unable to guess system type

This script, last modified $timestamp, has failed to recognize
the operating system you are using. It is advised that you
download the most up to date version of the config scripts from

  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess
and
  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub

If the version you run ($0) is already up to date, please
send the following data and any information you think might be
pertinent to <config-patches@gnu.org> in order to provide the needed
information to handle your system.

config.guess timestamp = $timestamp

uname -m = `(uname -m) 2>/dev/null || echo unknown`
uname -r = `(uname -r) 2>/dev/null || echo unknown`
uname -s = `(uname -s) 2>/dev/null || echo unknown`
uname -v = `(uname -v) 2>/dev/null || echo unknown`

/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`

hostinfo               = `(hostinfo) 2>/dev/null`
/bin/universe          = `(/bin/universe) 2>/dev/null`
/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
/bin/arch              = `(/bin/arch) 2>/dev/null`
/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`

UNAME_MACHINE = ${UNAME_MACHINE}
UNAME_RELEASE = ${UNAME_RELEASE}
UNAME_SYSTEM  = ${UNAME_SYSTEM}
UNAME_VERSION = ${UNAME_VERSION}
EOF

exit 1

# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:

Added config.h.in.

















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* config.h.in.  Generated from configure.ac by autoheader.  */

/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H

/* Define to 1 if you have the `fdatasync' function. */
#undef HAVE_FDATASYNC

/* Define to 1 if you have the `gmtime_r' function. */
#undef HAVE_GMTIME_R

/* Define to 1 if the system has the type `int16_t'. */
#undef HAVE_INT16_T

/* Define to 1 if the system has the type `int32_t'. */
#undef HAVE_INT32_T

/* Define to 1 if the system has the type `int64_t'. */
#undef HAVE_INT64_T

/* Define to 1 if the system has the type `int8_t'. */
#undef HAVE_INT8_T

/* Define to 1 if the system has the type `intptr_t'. */
#undef HAVE_INTPTR_T

/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H

/* Define to 1 if you have the `localtime_r' function. */
#undef HAVE_LOCALTIME_R

/* Define to 1 if you have the `localtime_s' function. */
#undef HAVE_LOCALTIME_S

/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H

/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H

/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H

/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H

/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H

/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H

/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H

/* Define to 1 if the system has the type `uint16_t'. */
#undef HAVE_UINT16_T

/* Define to 1 if the system has the type `uint32_t'. */
#undef HAVE_UINT32_T

/* Define to 1 if the system has the type `uint64_t'. */
#undef HAVE_UINT64_T

/* Define to 1 if the system has the type `uint8_t'. */
#undef HAVE_UINT8_T

/* Define to 1 if the system has the type `uintptr_t'. */
#undef HAVE_UINTPTR_T

/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H

/* Define to 1 if you have the `usleep' function. */
#undef HAVE_USLEEP

/* Define to the sub-directory in which libtool stores uninstalled libraries.
   */
#undef LT_OBJDIR

/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT

/* Define to the full name of this package. */
#undef PACKAGE_NAME

/* Define to the full name and version of this package. */
#undef PACKAGE_STRING

/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME

/* Define to the version of this package. */
#undef PACKAGE_VERSION

/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS

/* Number of bits in a file offset, on hosts where this is settable. */
#undef _FILE_OFFSET_BITS

/* Define for large files, on AIX-style hosts. */
#undef _LARGE_FILES

Added config.sub.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
#! /bin/sh
# Configuration validation subroutine script.
#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
#   Inc.

timestamp='2007-06-28'

# This file is (in principle) common to ALL GNU software.
# The presence of a machine in this file suggests that SOME GNU software
# can handle that machine.  It does not imply ALL GNU software can.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.


# Please send patches to <config-patches@gnu.org>.  Submit a context
# diff and a properly formatted ChangeLog entry.
#
# Configuration subroutine to validate and canonicalize a configuration type.
# Supply the specified configuration type as an argument.
# If it is invalid, we print an error message on stderr and exit with code 1.
# Otherwise, we print the canonical config type on stdout and succeed.

# This file is supposed to be the same for all GNU packages
# and recognize all the CPU types, system types and aliases
# that are meaningful with *any* GNU software.
# Each package is responsible for reporting which valid configurations
# it does not support.  The user should be able to distinguish
# a failure to support a valid configuration from a meaningless
# configuration.

# The goal of this file is to map all the various variations of a given
# machine specification into a single specification in the form:
#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
# or in some cases, the newer four-part form:
#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
# It is wrong to echo any other type of specification.

me=`echo "$0" | sed -e 's,.*/,,'`

usage="\
Usage: $0 [OPTION] CPU-MFR-OPSYS
       $0 [OPTION] ALIAS

Canonicalize a configuration name.

Operation modes:
  -h, --help         print this help, then exit
  -t, --time-stamp   print date of last modification, then exit
  -v, --version      print version number, then exit

Report bugs and patches to <config-patches@gnu.org>."

version="\
GNU config.sub ($timestamp)

Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."

help="
Try \`$me --help' for more information."

# Parse command line
while test $# -gt 0 ; do
  case $1 in
    --time-stamp | --time* | -t )
       echo "$timestamp" ; exit ;;
    --version | -v )
       echo "$version" ; exit ;;
    --help | --h* | -h )
       echo "$usage"; exit ;;
    -- )     # Stop option processing
       shift; break ;;
    - )	# Use stdin as input.
       break ;;
    -* )
       echo "$me: invalid option $1$help"
       exit 1 ;;

    *local*)
       # First pass through any local machine types.
       echo $1
       exit ;;

    * )
       break ;;
  esac
done

case $# in
 0) echo "$me: missing argument$help" >&2
    exit 1;;
 1) ;;
 *) echo "$me: too many arguments$help" >&2
    exit 1;;
esac

# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
# Here we must recognize all the valid KERNEL-OS combinations.
maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
case $maybe_os in
  nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
  uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
  storm-chaos* | os2-emx* | rtmk-nova*)
    os=-$maybe_os
    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
    ;;
  *)
    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
    if [ $basic_machine != $1 ]
    then os=`echo $1 | sed 's/.*-/-/'`
    else os=; fi
    ;;
esac

### Let's recognize common machines as not being operating systems so
### that things like config.sub decstation-3100 work.  We also
### recognize some manufacturers as not being operating systems, so we
### can provide default operating systems below.
case $os in
	-sun*os*)
		# Prevent following clause from handling this invalid input.
		;;
	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
	-apple | -axis | -knuth | -cray)
		os=
		basic_machine=$1
		;;
	-sim | -cisco | -oki | -wec | -winbond)
		os=
		basic_machine=$1
		;;
	-scout)
		;;
	-wrs)
		os=-vxworks
		basic_machine=$1
		;;
	-chorusos*)
		os=-chorusos
		basic_machine=$1
		;;
 	-chorusrdb)
 		os=-chorusrdb
		basic_machine=$1
 		;;
	-hiux*)
		os=-hiuxwe2
		;;
	-sco6)
		os=-sco5v6
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-sco5)
		os=-sco3.2v5
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-sco4)
		os=-sco3.2v4
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-sco3.2.[4-9]*)
		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-sco3.2v[4-9]*)
		# Don't forget version if it is 3.2v4 or newer.
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-sco5v6*)
		# Don't forget version if it is 3.2v4 or newer.
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-sco*)
		os=-sco3.2v2
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-udk*)
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-isc)
		os=-isc2.2
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-clix*)
		basic_machine=clipper-intergraph
		;;
	-isc*)
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
		;;
	-lynx*)
		os=-lynxos
		;;
	-ptx*)
		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
		;;
	-windowsnt*)
		os=`echo $os | sed -e 's/windowsnt/winnt/'`
		;;
	-psos*)
		os=-psos
		;;
	-mint | -mint[0-9]*)
		basic_machine=m68k-atari
		os=-mint
		;;
esac

# Decode aliases for certain CPU-COMPANY combinations.
case $basic_machine in
	# Recognize the basic CPU types without company name.
	# Some are omitted here because they have special meanings below.
	1750a | 580 \
	| a29k \
	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
	| am33_2.0 \
	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
	| bfin \
	| c4x | clipper \
	| d10v | d30v | dlx | dsp16xx | dvp \
	| fido | fr30 | frv \
	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
	| i370 | i860 | i960 | ia64 \
	| ip2k | iq2000 \
	| m32c | m32r | m32rle | m68000 | m68k | m88k \
	| maxq | mb | microblaze | mcore | mep \
	| mips | mipsbe | mipseb | mipsel | mipsle \
	| mips16 \
	| mips64 | mips64el \
	| mips64vr | mips64vrel \
	| mips64orion | mips64orionel \
	| mips64vr4100 | mips64vr4100el \
	| mips64vr4300 | mips64vr4300el \
	| mips64vr5000 | mips64vr5000el \
	| mips64vr5900 | mips64vr5900el \
	| mipsisa32 | mipsisa32el \
	| mipsisa32r2 | mipsisa32r2el \
	| mipsisa64 | mipsisa64el \
	| mipsisa64r2 | mipsisa64r2el \
	| mipsisa64sb1 | mipsisa64sb1el \
	| mipsisa64sr71k | mipsisa64sr71kel \
	| mipstx39 | mipstx39el \
	| mn10200 | mn10300 \
	| mt \
	| msp430 \
	| nios | nios2 \
	| ns16k | ns32k \
	| or32 \
	| pdp10 | pdp11 | pj | pjl \
	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
	| pyramid \
	| score \
	| sh | sh[1234] | sh[24]a | sh[24]a*eb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
	| sh64 | sh64le \
	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
	| spu | strongarm \
	| tahoe | thumb | tic4x | tic80 | tron \
	| v850 | v850e \
	| we32k \
	| x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \
	| z8k)
		basic_machine=$basic_machine-unknown
		;;
	m6811 | m68hc11 | m6812 | m68hc12)
		# Motorola 68HC11/12.
		basic_machine=$basic_machine-unknown
		os=-none
		;;
	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
		;;
	ms1)
		basic_machine=mt-unknown
		;;

	# We use `pc' rather than `unknown'
	# because (1) that's what they normally are, and
	# (2) the word "unknown" tends to confuse beginning users.
	i*86 | x86_64)
	  basic_machine=$basic_machine-pc
	  ;;
	# Object if more than one company name word.
	*-*-*)
		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
		exit 1
		;;
	# Recognize the basic CPU types with company name.
	580-* \
	| a29k-* \
	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
	| avr-* | avr32-* \
	| bfin-* | bs2000-* \
	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
	| clipper-* | craynv-* | cydra-* \
	| d10v-* | d30v-* | dlx-* \
	| elxsi-* \
	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
	| h8300-* | h8500-* \
	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
	| i*86-* | i860-* | i960-* | ia64-* \
	| ip2k-* | iq2000-* \
	| m32c-* | m32r-* | m32rle-* \
	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
	| m88110-* | m88k-* | maxq-* | mcore-* \
	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
	| mips16-* \
	| mips64-* | mips64el-* \
	| mips64vr-* | mips64vrel-* \
	| mips64orion-* | mips64orionel-* \
	| mips64vr4100-* | mips64vr4100el-* \
	| mips64vr4300-* | mips64vr4300el-* \
	| mips64vr5000-* | mips64vr5000el-* \
	| mips64vr5900-* | mips64vr5900el-* \
	| mipsisa32-* | mipsisa32el-* \
	| mipsisa32r2-* | mipsisa32r2el-* \
	| mipsisa64-* | mipsisa64el-* \
	| mipsisa64r2-* | mipsisa64r2el-* \
	| mipsisa64sb1-* | mipsisa64sb1el-* \
	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
	| mipstx39-* | mipstx39el-* \
	| mmix-* \
	| mt-* \
	| msp430-* \
	| nios-* | nios2-* \
	| none-* | np1-* | ns16k-* | ns32k-* \
	| orion-* \
	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
	| pyramid-* \
	| romp-* | rs6000-* \
	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]a*eb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
	| sparclite-* \
	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \
	| tahoe-* | thumb-* \
	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
	| tron-* \
	| v850-* | v850e-* | vax-* \
	| we32k-* \
	| x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \
	| xstormy16-* | xtensa-* \
	| ymp-* \
	| z8k-*)
		;;
	# Recognize the various machine names and aliases which stand
	# for a CPU type and a company and sometimes even an OS.
	386bsd)
		basic_machine=i386-unknown
		os=-bsd
		;;
	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
		basic_machine=m68000-att
		;;
	3b*)
		basic_machine=we32k-att
		;;
	a29khif)
		basic_machine=a29k-amd
		os=-udi
		;;
    	abacus)
		basic_machine=abacus-unknown
		;;
	adobe68k)
		basic_machine=m68010-adobe
		os=-scout
		;;
	alliant | fx80)
		basic_machine=fx80-alliant
		;;
	altos | altos3068)
		basic_machine=m68k-altos
		;;
	am29k)
		basic_machine=a29k-none
		os=-bsd
		;;
	amd64)
		basic_machine=x86_64-pc
		;;
	amd64-*)
		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	amdahl)
		basic_machine=580-amdahl
		os=-sysv
		;;
	amiga | amiga-*)
		basic_machine=m68k-unknown
		;;
	amigaos | amigados)
		basic_machine=m68k-unknown
		os=-amigaos
		;;
	amigaunix | amix)
		basic_machine=m68k-unknown
		os=-sysv4
		;;
	apollo68)
		basic_machine=m68k-apollo
		os=-sysv
		;;
	apollo68bsd)
		basic_machine=m68k-apollo
		os=-bsd
		;;
	aux)
		basic_machine=m68k-apple
		os=-aux
		;;
	balance)
		basic_machine=ns32k-sequent
		os=-dynix
		;;
	c90)
		basic_machine=c90-cray
		os=-unicos
		;;
	convex-c1)
		basic_machine=c1-convex
		os=-bsd
		;;
	convex-c2)
		basic_machine=c2-convex
		os=-bsd
		;;
	convex-c32)
		basic_machine=c32-convex
		os=-bsd
		;;
	convex-c34)
		basic_machine=c34-convex
		os=-bsd
		;;
	convex-c38)
		basic_machine=c38-convex
		os=-bsd
		;;
	cray | j90)
		basic_machine=j90-cray
		os=-unicos
		;;
	craynv)
		basic_machine=craynv-cray
		os=-unicosmp
		;;
	cr16)
		basic_machine=cr16-unknown
		os=-elf
		;;
	crds | unos)
		basic_machine=m68k-crds
		;;
	crisv32 | crisv32-* | etraxfs*)
		basic_machine=crisv32-axis
		;;
	cris | cris-* | etrax*)
		basic_machine=cris-axis
		;;
	crx)
		basic_machine=crx-unknown
		os=-elf
		;;
	da30 | da30-*)
		basic_machine=m68k-da30
		;;
	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
		basic_machine=mips-dec
		;;
	decsystem10* | dec10*)
		basic_machine=pdp10-dec
		os=-tops10
		;;
	decsystem20* | dec20*)
		basic_machine=pdp10-dec
		os=-tops20
		;;
	delta | 3300 | motorola-3300 | motorola-delta \
	      | 3300-motorola | delta-motorola)
		basic_machine=m68k-motorola
		;;
	delta88)
		basic_machine=m88k-motorola
		os=-sysv3
		;;
	djgpp)
		basic_machine=i586-pc
		os=-msdosdjgpp
		;;
	dpx20 | dpx20-*)
		basic_machine=rs6000-bull
		os=-bosx
		;;
	dpx2* | dpx2*-bull)
		basic_machine=m68k-bull
		os=-sysv3
		;;
	ebmon29k)
		basic_machine=a29k-amd
		os=-ebmon
		;;
	elxsi)
		basic_machine=elxsi-elxsi
		os=-bsd
		;;
	encore | umax | mmax)
		basic_machine=ns32k-encore
		;;
	es1800 | OSE68k | ose68k | ose | OSE)
		basic_machine=m68k-ericsson
		os=-ose
		;;
	fx2800)
		basic_machine=i860-alliant
		;;
	genix)
		basic_machine=ns32k-ns
		;;
	gmicro)
		basic_machine=tron-gmicro
		os=-sysv
		;;
	go32)
		basic_machine=i386-pc
		os=-go32
		;;
	h3050r* | hiux*)
		basic_machine=hppa1.1-hitachi
		os=-hiuxwe2
		;;
	h8300hms)
		basic_machine=h8300-hitachi
		os=-hms
		;;
	h8300xray)
		basic_machine=h8300-hitachi
		os=-xray
		;;
	h8500hms)
		basic_machine=h8500-hitachi
		os=-hms
		;;
	harris)
		basic_machine=m88k-harris
		os=-sysv3
		;;
	hp300-*)
		basic_machine=m68k-hp
		;;
	hp300bsd)
		basic_machine=m68k-hp
		os=-bsd
		;;
	hp300hpux)
		basic_machine=m68k-hp
		os=-hpux
		;;
	hp3k9[0-9][0-9] | hp9[0-9][0-9])
		basic_machine=hppa1.0-hp
		;;
	hp9k2[0-9][0-9] | hp9k31[0-9])
		basic_machine=m68000-hp
		;;
	hp9k3[2-9][0-9])
		basic_machine=m68k-hp
		;;
	hp9k6[0-9][0-9] | hp6[0-9][0-9])
		basic_machine=hppa1.0-hp
		;;
	hp9k7[0-79][0-9] | hp7[0-79][0-9])
		basic_machine=hppa1.1-hp
		;;
	hp9k78[0-9] | hp78[0-9])
		# FIXME: really hppa2.0-hp
		basic_machine=hppa1.1-hp
		;;
	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
		# FIXME: really hppa2.0-hp
		basic_machine=hppa1.1-hp
		;;
	hp9k8[0-9][13679] | hp8[0-9][13679])
		basic_machine=hppa1.1-hp
		;;
	hp9k8[0-9][0-9] | hp8[0-9][0-9])
		basic_machine=hppa1.0-hp
		;;
	hppa-next)
		os=-nextstep3
		;;
	hppaosf)
		basic_machine=hppa1.1-hp
		os=-osf
		;;
	hppro)
		basic_machine=hppa1.1-hp
		os=-proelf
		;;
	i370-ibm* | ibm*)
		basic_machine=i370-ibm
		;;
# I'm not sure what "Sysv32" means.  Should this be sysv3.2?
	i*86v32)
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
		os=-sysv32
		;;
	i*86v4*)
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
		os=-sysv4
		;;
	i*86v)
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
		os=-sysv
		;;
	i*86sol2)
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
		os=-solaris2
		;;
	i386mach)
		basic_machine=i386-mach
		os=-mach
		;;
	i386-vsta | vsta)
		basic_machine=i386-unknown
		os=-vsta
		;;
	iris | iris4d)
		basic_machine=mips-sgi
		case $os in
		    -irix*)
			;;
		    *)
			os=-irix4
			;;
		esac
		;;
	isi68 | isi)
		basic_machine=m68k-isi
		os=-sysv
		;;
	m88k-omron*)
		basic_machine=m88k-omron
		;;
	magnum | m3230)
		basic_machine=mips-mips
		os=-sysv
		;;
	merlin)
		basic_machine=ns32k-utek
		os=-sysv
		;;
	mingw32)
		basic_machine=i386-pc
		os=-mingw32
		;;
	mingw32ce)
		basic_machine=arm-unknown
		os=-mingw32ce
		;;
	miniframe)
		basic_machine=m68000-convergent
		;;
	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
		basic_machine=m68k-atari
		os=-mint
		;;
	mipsEE* | ee | ps2)
		basic_machine=mips64r5900el-scei
		case $os in
		    -linux*)
			;;
		    *)
			os=-elf
			;;
		esac
		;;
	iop)
		basic_machine=mipsel-scei
		os=-irx
		;;
	dvp)
		basic_machine=dvp-scei
		os=-elf
		;;
	mips3*-*)
		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
		;;
	mips3*)
		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
		;;
	monitor)
		basic_machine=m68k-rom68k
		os=-coff
		;;
	morphos)
		basic_machine=powerpc-unknown
		os=-morphos
		;;
	msdos)
		basic_machine=i386-pc
		os=-msdos
		;;
	ms1-*)
		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
		;;
	mvs)
		basic_machine=i370-ibm
		os=-mvs
		;;
	ncr3000)
		basic_machine=i486-ncr
		os=-sysv4
		;;
	netbsd386)
		basic_machine=i386-unknown
		os=-netbsd
		;;
	netwinder)
		basic_machine=armv4l-rebel
		os=-linux
		;;
	news | news700 | news800 | news900)
		basic_machine=m68k-sony
		os=-newsos
		;;
	news1000)
		basic_machine=m68030-sony
		os=-newsos
		;;
	news-3600 | risc-news)
		basic_machine=mips-sony
		os=-newsos
		;;
	necv70)
		basic_machine=v70-nec
		os=-sysv
		;;
	next | m*-next )
		basic_machine=m68k-next
		case $os in
		    -nextstep* )
			;;
		    -ns2*)
		      os=-nextstep2
			;;
		    *)
		      os=-nextstep3
			;;
		esac
		;;
	nh3000)
		basic_machine=m68k-harris
		os=-cxux
		;;
	nh[45]000)
		basic_machine=m88k-harris
		os=-cxux
		;;
	nindy960)
		basic_machine=i960-intel
		os=-nindy
		;;
	mon960)
		basic_machine=i960-intel
		os=-mon960
		;;
	nonstopux)
		basic_machine=mips-compaq
		os=-nonstopux
		;;
	np1)
		basic_machine=np1-gould
		;;
	nsr-tandem)
		basic_machine=nsr-tandem
		;;
	op50n-* | op60c-*)
		basic_machine=hppa1.1-oki
		os=-proelf
		;;
	openrisc | openrisc-*)
		basic_machine=or32-unknown
		;;
	os400)
		basic_machine=powerpc-ibm
		os=-os400
		;;
	OSE68000 | ose68000)
		basic_machine=m68000-ericsson
		os=-ose
		;;
	os68k)
		basic_machine=m68k-none
		os=-os68k
		;;
	pa-hitachi)
		basic_machine=hppa1.1-hitachi
		os=-hiuxwe2
		;;
	paragon)
		basic_machine=i860-intel
		os=-osf
		;;
	pbd)
		basic_machine=sparc-tti
		;;
	pbb)
		basic_machine=m68k-tti
		;;
	pc532 | pc532-*)
		basic_machine=ns32k-pc532
		;;
	pc98)
		basic_machine=i386-pc
		;;
	pc98-*)
		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	pentium | p5 | k5 | k6 | nexgen | viac3)
		basic_machine=i586-pc
		;;
	pentiumpro | p6 | 6x86 | athlon | athlon_*)
		basic_machine=i686-pc
		;;
	pentiumii | pentium2 | pentiumiii | pentium3)
		basic_machine=i686-pc
		;;
	pentium4)
		basic_machine=i786-pc
		;;
	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	pentiumpro-* | p6-* | 6x86-* | athlon-*)
		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	pentium4-*)
		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	pn)
		basic_machine=pn-gould
		;;
	power)	basic_machine=power-ibm
		;;
	ppc)	basic_machine=powerpc-unknown
		;;
	ppc-*)	basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	ppcle | powerpclittle | ppc-le | powerpc-little)
		basic_machine=powerpcle-unknown
		;;
	ppcle-* | powerpclittle-*)
		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	ppc64)	basic_machine=powerpc64-unknown
		;;
	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
		basic_machine=powerpc64le-unknown
		;;
	ppc64le-* | powerpc64little-*)
		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
		;;
	ps2)
		basic_machine=i386-ibm
		;;
	pw32)
		basic_machine=i586-unknown
		os=-pw32
		;;
	rdos)
		basic_machine=i386-pc
		os=-rdos
		;;
	rom68k)
		basic_machine=m68k-rom68k
		os=-coff
		;;
	rm[46]00)
		basic_machine=mips-siemens
		;;
	rtpc | rtpc-*)
		basic_machine=romp-ibm
		;;
	s390 | s390-*)
		basic_machine=s390-ibm
		;;
	s390x | s390x-*)
		basic_machine=s390x-ibm
		;;
	sa29200)
		basic_machine=a29k-amd
		os=-udi
		;;
	sb1)
		basic_machine=mipsisa64sb1-unknown
		;;
	sb1el)
		basic_machine=mipsisa64sb1el-unknown
		;;
	sde)
		basic_machine=mipsisa32-sde
		os=-elf
		;;
	sei)
		basic_machine=mips-sei
		os=-seiux
		;;
	sequent)
		basic_machine=i386-sequent
		;;
	sh)
		basic_machine=sh-hitachi
		os=-hms
		;;
	sh5el)
		basic_machine=sh5le-unknown
		;;
	sh64)
		basic_machine=sh64-unknown
		;;
	sparclite-wrs | simso-wrs)
		basic_machine=sparclite-wrs
		os=-vxworks
		;;
	sps7)
		basic_machine=m68k-bull
		os=-sysv2
		;;
	spur)
		basic_machine=spur-unknown
		;;
	st2000)
		basic_machine=m68k-tandem
		;;
	stratus)
		basic_machine=i860-stratus
		os=-sysv4
		;;
	sun2)
		basic_machine=m68000-sun
		;;
	sun2os3)
		basic_machine=m68000-sun
		os=-sunos3
		;;
	sun2os4)
		basic_machine=m68000-sun
		os=-sunos4
		;;
	sun3os3)
		basic_machine=m68k-sun
		os=-sunos3
		;;
	sun3os4)
		basic_machine=m68k-sun
		os=-sunos4
		;;
	sun4os3)
		basic_machine=sparc-sun
		os=-sunos3
		;;
	sun4os4)
		basic_machine=sparc-sun
		os=-sunos4
		;;
	sun4sol2)
		basic_machine=sparc-sun
		os=-solaris2
		;;
	sun3 | sun3-*)
		basic_machine=m68k-sun
		;;
	sun4)
		basic_machine=sparc-sun
		;;
	sun386 | sun386i | roadrunner)
		basic_machine=i386-sun
		;;
	sv1)
		basic_machine=sv1-cray
		os=-unicos
		;;
	symmetry)
		basic_machine=i386-sequent
		os=-dynix
		;;
	t3e)
		basic_machine=alphaev5-cray
		os=-unicos
		;;
	t90)
		basic_machine=t90-cray
		os=-unicos
		;;
	tic54x | c54x*)
		basic_machine=tic54x-unknown
		os=-coff
		;;
	tic55x | c55x*)
		basic_machine=tic55x-unknown
		os=-coff
		;;
	tic6x | c6x*)
		basic_machine=tic6x-unknown
		os=-coff
		;;
	tx39)
		basic_machine=mipstx39-unknown
		;;
	tx39el)
		basic_machine=mipstx39el-unknown
		;;
	toad1)
		basic_machine=pdp10-xkl
		os=-tops20
		;;
	tower | tower-32)
		basic_machine=m68k-ncr
		;;
	tpf)
		basic_machine=s390x-ibm
		os=-tpf
		;;
	udi29k)
		basic_machine=a29k-amd
		os=-udi
		;;
	ultra3)
		basic_machine=a29k-nyu
		os=-sym1
		;;
	v810 | necv810)
		basic_machine=v810-nec
		os=-none
		;;
	vaxv)
		basic_machine=vax-dec
		os=-sysv
		;;
	vms)
		basic_machine=vax-dec
		os=-vms
		;;
	vpp*|vx|vx-*)
		basic_machine=f301-fujitsu
		;;
	vxworks960)
		basic_machine=i960-wrs
		os=-vxworks
		;;
	vxworks68)
		basic_machine=m68k-wrs
		os=-vxworks
		;;
	vxworks29k)
		basic_machine=a29k-wrs
		os=-vxworks
		;;
	w65*)
		basic_machine=w65-wdc
		os=-none
		;;
	w89k-*)
		basic_machine=hppa1.1-winbond
		os=-proelf
		;;
	xbox)
		basic_machine=i686-pc
		os=-mingw32
		;;
	xps | xps100)
		basic_machine=xps100-honeywell
		;;
	ymp)
		basic_machine=ymp-cray
		os=-unicos
		;;
	z8k-*-coff)
		basic_machine=z8k-unknown
		os=-sim
		;;
	none)
		basic_machine=none-none
		os=-none
		;;

# Here we handle the default manufacturer of certain CPU types.  It is in
# some cases the only manufacturer, in others, it is the most popular.
	w89k)
		basic_machine=hppa1.1-winbond
		;;
	op50n)
		basic_machine=hppa1.1-oki
		;;
	op60c)
		basic_machine=hppa1.1-oki
		;;
	romp)
		basic_machine=romp-ibm
		;;
	mmix)
		basic_machine=mmix-knuth
		;;
	rs6000)
		basic_machine=rs6000-ibm
		;;
	vax)
		basic_machine=vax-dec
		;;
	pdp10)
		# there are many clones, so DEC is not a safe bet
		basic_machine=pdp10-unknown
		;;
	pdp11)
		basic_machine=pdp11-dec
		;;
	we32k)
		basic_machine=we32k-att
		;;
	sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
		basic_machine=sh-unknown
		;;
	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
		basic_machine=sparc-sun
		;;
	cydra)
		basic_machine=cydra-cydrome
		;;
	orion)
		basic_machine=orion-highlevel
		;;
	orion105)
		basic_machine=clipper-highlevel
		;;
	mac | mpw | mac-mpw)
		basic_machine=m68k-apple
		;;
	pmac | pmac-mpw)
		basic_machine=powerpc-apple
		;;
	*-unknown)
		# Make sure to match an already-canonicalized machine name.
		;;
	*)
		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
		exit 1
		;;
esac

# Here we canonicalize certain aliases for manufacturers.
case $basic_machine in
	*-digital*)
		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
		;;
	*-commodore*)
		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
		;;
	*)
		;;
esac

# Decode manufacturer-specific aliases for certain operating systems.

if [ x"$os" != x"" ]
then
case $os in
        # First match some system type aliases
        # that might get confused with valid system types.
	# -solaris* is a basic system type, with this one exception.
	-solaris1 | -solaris1.*)
		os=`echo $os | sed -e 's|solaris1|sunos4|'`
		;;
	-solaris)
		os=-solaris2
		;;
	-svr4*)
		os=-sysv4
		;;
	-unixware*)
		os=-sysv4.2uw
		;;
	-gnu/linux*)
		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
		;;
	# First accept the basic system types.
	# The portable systems comes first.
	# Each alternative MUST END IN A *, to match a version number.
	# -sysv* is not here because it comes later, after sysvr4.
	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
	      | -aos* \
	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
	      | -openbsd* | -solidbsd* \
	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
	      | -chorusos* | -chorusrdb* \
	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
	      | -uxpv* | -beos* | -mpeix* | -udk* \
	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -irx*)
	# Remember, each alternative MUST END IN *, to match a version number.
		;;
	-qnx*)
		case $basic_machine in
		    x86-* | i*86-*)
			;;
		    *)
			os=-nto$os
			;;
		esac
		;;
	-nto-qnx*)
		;;
	-nto*)
		os=`echo $os | sed -e 's|nto|nto-qnx|'`
		;;
	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
		;;
	-mac*)
		os=`echo $os | sed -e 's|mac|macos|'`
		;;
	-linux-dietlibc)
		os=-linux-dietlibc
		;;
	-linux*)
		os=`echo $os | sed -e 's|linux|linux-gnu|'`
		;;
	-sunos5*)
		os=`echo $os | sed -e 's|sunos5|solaris2|'`
		;;
	-sunos6*)
		os=`echo $os | sed -e 's|sunos6|solaris3|'`
		;;
	-opened*)
		os=-openedition
		;;
        -os400*)
		os=-os400
		;;
	-wince*)
		os=-wince
		;;
	-osfrose*)
		os=-osfrose
		;;
	-osf*)
		os=-osf
		;;
	-utek*)
		os=-bsd
		;;
	-dynix*)
		os=-bsd
		;;
	-acis*)
		os=-aos
		;;
	-atheos*)
		os=-atheos
		;;
	-syllable*)
		os=-syllable
		;;
	-386bsd)
		os=-bsd
		;;
	-ctix* | -uts*)
		os=-sysv
		;;
	-nova*)
		os=-rtmk-nova
		;;
	-ns2 )
		os=-nextstep2
		;;
	-nsk*)
		os=-nsk
		;;
	# Preserve the version number of sinix5.
	-sinix5.*)
		os=`echo $os | sed -e 's|sinix|sysv|'`
		;;
	-sinix*)
		os=-sysv4
		;;
        -tpf*)
		os=-tpf
		;;
	-triton*)
		os=-sysv3
		;;
	-oss*)
		os=-sysv3
		;;
	-svr4)
		os=-sysv4
		;;
	-svr3)
		os=-sysv3
		;;
	-sysvr4)
		os=-sysv4
		;;
	# This must come after -sysvr4.
	-sysv*)
		;;
	-ose*)
		os=-ose
		;;
	-es1800*)
		os=-ose
		;;
	-xenix)
		os=-xenix
		;;
	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
		os=-mint
		;;
	-aros*)
		os=-aros
		;;
	-kaos*)
		os=-kaos
		;;
	-zvmoe)
		os=-zvmoe
		;;
	-none)
		;;
	*)
		# Get rid of the `-' at the beginning of $os.
		os=`echo $os | sed 's/[^-]*-//'`
		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
		exit 1
		;;
esac
else

# Here we handle the default operating systems that come with various machines.
# The value should be what the vendor currently ships out the door with their
# machine or put another way, the most popular os provided with the machine.

# Note that if you're going to try to match "-MANUFACTURER" here (say,
# "-sun"), then you have to tell the case statement up towards the top
# that MANUFACTURER isn't an operating system.  Otherwise, code above
# will signal an error saying that MANUFACTURER isn't an operating
# system, and we'll never get to this point.

case $basic_machine in
        score-*)
		os=-elf
		;;
        spu-*)
		os=-elf
		;;
	*-acorn)
		os=-riscix1.2
		;;
	arm*-rebel)
		os=-linux
		;;
	arm*-semi)
		os=-aout
		;;
        c4x-* | tic4x-*)
        	os=-coff
		;;
	# This must come before the *-dec entry.
	pdp10-*)
		os=-tops20
		;;
	pdp11-*)
		os=-none
		;;
	*-dec | vax-*)
		os=-ultrix4.2
		;;
	m68*-apollo)
		os=-domain
		;;
	i386-sun)
		os=-sunos4.0.2
		;;
	m68000-sun)
		os=-sunos3
		# This also exists in the configure program, but was not the
		# default.
		# os=-sunos4
		;;
	m68*-cisco)
		os=-aout
		;;
        mep-*)
		os=-elf
		;;
	mips*-cisco)
		os=-elf
		;;
	mips*-*)
		os=-elf
		;;
	or32-*)
		os=-coff
		;;
	*-tti)	# must be before sparc entry or we get the wrong os.
		os=-sysv3
		;;
	sparc-* | *-sun)
		os=-sunos4.1.1
		;;
	*-be)
		os=-beos
		;;
	*-haiku)
		os=-haiku
		;;
	*-ibm)
		os=-aix
		;;
    	*-knuth)
		os=-mmixware
		;;
	*-wec)
		os=-proelf
		;;
	*-winbond)
		os=-proelf
		;;
	*-oki)
		os=-proelf
		;;
	*-hp)
		os=-hpux
		;;
	*-hitachi)
		os=-hiux
		;;
	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
		os=-sysv
		;;
	*-cbm)
		os=-amigaos
		;;
	*-dg)
		os=-dgux
		;;
	*-dolphin)
		os=-sysv3
		;;
	m68k-ccur)
		os=-rtu
		;;
	m88k-omron*)
		os=-luna
		;;
	*-next )
		os=-nextstep
		;;
	*-sequent)
		os=-ptx
		;;
	*-crds)
		os=-unos
		;;
	*-ns)
		os=-genix
		;;
	i370-*)
		os=-mvs
		;;
	*-next)
		os=-nextstep3
		;;
	*-gould)
		os=-sysv
		;;
	*-highlevel)
		os=-bsd
		;;
	*-encore)
		os=-bsd
		;;
	*-sgi)
		os=-irix
		;;
	*-siemens)
		os=-sysv4
		;;
	*-masscomp)
		os=-rtu
		;;
	f30[01]-fujitsu | f700-fujitsu)
		os=-uxpv
		;;
	*-rom68k)
		os=-coff
		;;
	*-*bug)
		os=-coff
		;;
	*-apple)
		os=-macos
		;;
	*-atari*)
		os=-mint
		;;
	*)
		os=-none
		;;
esac
fi

# Here we handle the case where we know the os, and the CPU type, but not the
# manufacturer.  We pick the logical manufacturer.
vendor=unknown
case $basic_machine in
	*-unknown)
		case $os in
			-riscix*)
				vendor=acorn
				;;
			-sunos*)
				vendor=sun
				;;
			-aix*)
				vendor=ibm
				;;
			-beos*)
				vendor=be
				;;
			-hpux*)
				vendor=hp
				;;
			-mpeix*)
				vendor=hp
				;;
			-hiux*)
				vendor=hitachi
				;;
			-unos*)
				vendor=crds
				;;
			-dgux*)
				vendor=dg
				;;
			-luna*)
				vendor=omron
				;;
			-genix*)
				vendor=ns
				;;
			-mvs* | -opened*)
				vendor=ibm
				;;
			-os400*)
				vendor=ibm
				;;
			-ptx*)
				vendor=sequent
				;;
			-tpf*)
				vendor=ibm
				;;
			-vxsim* | -vxworks* | -windiss*)
				vendor=wrs
				;;
			-aux*)
				vendor=apple
				;;
			-hms*)
				vendor=hitachi
				;;
			-mpw* | -macos*)
				vendor=apple
				;;
			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
				vendor=atari
				;;
			-vos*)
				vendor=stratus
				;;
		esac
		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
		;;
esac

echo $basic_machine$os
exit

# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:

Added configure.

more than 10,000 changes

Added configure.ac.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#
# The build process allows for using a cross-compiler.  But the default
# action is to target the same platform that we are running on.  The
# configure script needs to discover the following properties of the 
# build and target systems:
#
#    srcdir
#
#        The is the name of the directory that contains the
#        "configure" shell script.  All source files are
#        located relative to this directory.
#
#    bindir
#
#        The name of the directory where executables should be
#        written by the "install" target of the makefile.
#
#    program_prefix
#
#        Add this prefix to the names of all executables that run
#        on the target machine.  Default: ""
#
#    ENABLE_SHARED
#
#        True if shared libraries should be generated.
#
#    BUILD_CC
#
#        The name of a command that is used to convert C
#        source files into executables that run on the build
#        platform.
#
#    BUILD_CFLAGS
#
#        Switches that the build compiler needs in order to construct
#        command-line programs.
#
#    BUILD_LIBS
#
#        Libraries that the build compiler needs in order to construct
#        command-line programs.
#
#    BUILD_EXEEXT
#
#        The filename extension for executables on the build
#        platform.  "" for Unix and ".exe" for Windows.
#
#    TCL_*
#
#        Lots of values are read in from the tclConfig.sh script,
#        if that script is available.  This values are used for
#        constructing and installing the TCL extension.
#
#    TARGET_READLINE_LIBS
#
#        This is the library directives passed to the target linker
#        that cause the executable to link against the readline library.
#        This might be a switch like "-lreadline" or pathnames of library
#        file like "../../src/libreadline.a".
#
#    TARGET_READLINE_INC
#
#        This variables define the directory that contain header
#        files for the readline library.  If the compiler is able 
#        to find <readline.h> on its own, then this can be blank.
#
#    TARGET_EXEEXT
#
#        The filename extension for executables on the
#        target platform.  "" for Unix and ".exe" for windows.
#
# The generated configure script will make an attempt to guess
# at all of the above parameters.  You can override any of
# the guesses by setting the environment variable named
# "config_AAAA" where "AAAA" is the name of the parameter
# described above.  (Exception: srcdir cannot be set this way.)
# If you have a file that sets one or more of these environment
# variables, you can invoke configure as follows:
#
#           configure --with-hints=FILE
#
# where FILE is the name of the file that sets the environment
# variables.  FILE should be an absolute pathname.
#
# This configure.in file is easy to reuse on other projects.  Just
# change the argument to AC_INIT().  And disable any features that
# you don't need (for example BLT) by erasing or commenting out
# the corresponding code.
#
AC_INIT(sqlite, m4_esyscmd([cat VERSION | tr -d '\n']))

dnl Make sure the local VERSION file matches this configure script
sqlite_version_sanity_check=`cat $srcdir/VERSION | tr -d '\n'`
if test "$PACKAGE_VERSION" != "$sqlite_version_sanity_check" ; then
AC_MSG_ERROR([configure script is out of date:
 configure \$PACKAGE_VERSION = $PACKAGE_VERSION
 top level VERSION file     = $sqlite_version_sanity_check
please regen with autoconf])
fi

dnl Put the RCS revision string after AC_INIT so that it will also
dnl show in in configure.
# The following RCS revision string applies to configure.in
# $Revision: 1.56 $

#########
# Programs needed
#
AC_PROG_LIBTOOL
AC_PROG_INSTALL
AC_PROG_AWK

#########
# Enable large file support (if special flags are necessary)
#
AC_SYS_LARGEFILE

#########
# Check for needed/wanted data types
AC_CHECK_TYPES([int8_t, int16_t, int32_t, int64_t, intptr_t, uint8_t,
                uint16_t, uint32_t, uint64_t, uintptr_t])

#########
# Check for needed/wanted headers
AC_CHECK_HEADERS([sys/types.h stdlib.h stdint.h inttypes.h])

#########
# Figure out whether or not we have these functions
#
AC_CHECK_FUNCS([usleep fdatasync localtime_r gmtime_r localtime_s])

#########
# By default, we use the amalgamation (this may be changed below...)
#
USE_AMALGAMATION=1

#########
# See whether we can run specific tclsh versions known to work well;
# if not, then we fall back to plain tclsh.
# TODO: try other versions before falling back?
# 
AC_CHECK_PROGS(TCLSH_CMD, [tclsh8.4 tclsh], none)
if test "$TCLSH_CMD" = "none"; then
  # If we can't find a local tclsh, then building the amalgamation will fail.
  # We act as though --disable-amalgamation has been used.
  echo "Warning: can't find tclsh - defaulting to non-amalgamation build."
  USE_AMALGAMATION=0
  TCLSH_CMD="tclsh"
fi
AC_SUBST(TCLSH_CMD)

AC_ARG_VAR([TCLLIBDIR], [Where to install tcl plugin])
if test "x${TCLLIBDIR+set}" != "xset" ; then
  TCLLIBDIR='$(libdir)'
  for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}` ; do
    TCLLIBDIR=$i
    break
  done
  TCLLIBDIR="${TCLLIBDIR}/sqlite3"
fi


#########
# Set up an appropriate program prefix
#
if test "$program_prefix" = "NONE"; then
  program_prefix=""
fi
AC_SUBST(program_prefix)

VERSION=[`cat $srcdir/VERSION | sed 's/^\([0-9]*\.*[0-9]*\).*/\1/'`]
AC_MSG_NOTICE(Version set to $VERSION)
AC_SUBST(VERSION)
RELEASE=`cat $srcdir/VERSION`
AC_MSG_NOTICE(Release set to $RELEASE)
AC_SUBST(RELEASE)
VERSION_NUMBER=[`cat $srcdir/VERSION \
                           | sed 's/[^0-9]/ /g' \
                | awk '{printf "%d%03d%03d",$1,$2,$3}'`]
AC_MSG_NOTICE(Version number set to $VERSION_NUMBER)
AC_SUBST(VERSION_NUMBER)

#########
# Check to see if the --with-hints=FILE option is used.  If there is none,
# then check for a files named "$host.hints" and ../$hosts.hints where
# $host is the hostname of the build system.  If still no hints are
# found, try looking in $system.hints and ../$system.hints where
# $system is the result of uname -s.
#
AC_ARG_WITH(hints,
  AC_HELP_STRING([--with-hints=FILE],[Read configuration options from FILE]),
  hints=$withval)
if test "$hints" = ""; then
  host=`hostname | sed 's/\..*//'`
  if test -r $host.hints; then
    hints=$host.hints
  else
     if test -r ../$host.hints; then
       hints=../$host.hints
     fi
  fi
fi
if test "$hints" = ""; then
  sys=`uname -s`
  if test -r $sys.hints; then
    hints=$sys.hints
  else
     if test -r ../$sys.hints; then
       hints=../$sys.hints
     fi
  fi
fi
if test "$hints" != ""; then
  AC_MSG_RESULT(reading hints from $hints)
  . $hints
fi

#########
# Locate a compiler for the build machine.  This compiler should
# generate command-line programs that run on the build machine.
#
if test x"$cross_compiling" = xno; then
	BUILD_CC=$CC
	BUILD_CFLAGS=$CFLAGS
else
	if test "${BUILD_CC+set}" != set; then
		AC_CHECK_PROGS(BUILD_CC, gcc cc cl)
	fi
	if test "${BUILD_CFLAGS+set}" != set; then
		BUILD_CFLAGS="-g"
	fi
fi
AC_SUBST(BUILD_CC)

##########
# Do we want to support multithreaded use of sqlite
#
AC_ARG_ENABLE(threadsafe, 
AC_HELP_STRING([--enable-threadsafe],[Support threadsafe operation]),,enable_threadsafe=yes)
AC_MSG_CHECKING([whether to support threadsafe operation])
if test "$enable_threadsafe" = "no"; then
  SQLITE_THREADSAFE=0
  AC_MSG_RESULT([no])
else
  SQLITE_THREADSAFE=1
  AC_MSG_RESULT([yes])
fi
AC_SUBST(SQLITE_THREADSAFE)

if test "$SQLITE_THREADSAFE" = "1"; then
  AC_SEARCH_LIBS(pthread_create, pthread)
fi

##########
# Do we want to allow a connection created in one thread to be used
# in another thread.  This does not work on many Linux systems (ex: RedHat 9)
# due to bugs in the threading implementations.  This is thus off by default.
#
AC_ARG_ENABLE(cross-thread-connections, 
AC_HELP_STRING([--enable-cross-thread-connections],[Allow connection sharing across threads]),,enable_xthreadconnect=no)
AC_MSG_CHECKING([whether to allow connections to be shared across threads])
if test "$enable_xthreadconnect" = "no"; then
  XTHREADCONNECT=''
  AC_MSG_RESULT([no])
else
  XTHREADCONNECT='-DSQLITE_ALLOW_XTHREAD_CONNECT=1'
  AC_MSG_RESULT([yes])
fi
AC_SUBST(XTHREADCONNECT)

##########
# Do we want to set threadsOverrideEachOthersLocks variable to be 1 (true) by
# default. Normally, a test at runtime is performed to determine the
# appropriate value of this variable. Use this option only if you're sure that
# threads can safely override each others locks in all runtime situations.
#
AC_ARG_ENABLE(threads-override-locks, 
AC_HELP_STRING([--enable-threads-override-locks],[Threads can override each others locks]),,enable_threads_override_locks=no)
AC_MSG_CHECKING([whether threads can override each others locks])
if test "$enable_threads_override_locks" = "no"; then
  THREADSOVERRIDELOCKS='-1'
  AC_MSG_RESULT([no])
else
  THREADSOVERRIDELOCKS='1'
  AC_MSG_RESULT([yes])
fi
AC_SUBST(THREADSOVERRIDELOCKS)

##########
# Do we want to support release
#
AC_ARG_ENABLE(releasemode, 
AC_HELP_STRING([--enable-releasemode],[Support libtool link to release mode]),,enable_releasemode=no)
AC_MSG_CHECKING([whether to support shared library linked as release mode or not])
if test "$enable_releasemode" = "no"; then
  ALLOWRELEASE=""
  AC_MSG_RESULT([no])
else
  ALLOWRELEASE="-release `cat $srcdir/VERSION`"
  AC_MSG_RESULT([yes])
fi
AC_SUBST(ALLOWRELEASE)

##########
# Do we want temporary databases in memory
#
AC_ARG_ENABLE(tempstore, 
AC_HELP_STRING([--enable-tempstore],[Use an in-ram database for temporary tables (never,no,yes,always)]),,enable_tempstore=no)
AC_MSG_CHECKING([whether to use an in-ram database for temporary tables])
case "$enable_tempstore" in
  never ) 
    TEMP_STORE=0
    AC_MSG_RESULT([never])
  ;;
  no ) 
    TEMP_STORE=1
    AC_MSG_RESULT([no])
  ;;
  yes ) 
     TEMP_STORE=2
    AC_MSG_RESULT([yes])
  ;;
  always ) 
     TEMP_STORE=3
    AC_MSG_RESULT([always])
  ;;
  * ) 
    TEMP_STORE=1
    AC_MSG_RESULT([no])
  ;;
esac

AC_SUBST(TEMP_STORE)

###########
# Lots of things are different if we are compiling for Windows using
# the CYGWIN environment.  So check for that special case and handle
# things accordingly.
#
AC_MSG_CHECKING([if executables have the .exe suffix])
if test "$config_BUILD_EXEEXT" = ".exe"; then
  CYGWIN=yes
  AC_MSG_RESULT(yes)
else
  AC_MSG_RESULT(unknown)
fi
if test "$CYGWIN" != "yes"; then
  AC_CYGWIN
fi
if test "$CYGWIN" = "yes"; then
  BUILD_EXEEXT=.exe
else
  BUILD_EXEEXT=$EXEEXT
fi
if test x"$cross_compiling" = xno; then
  TARGET_EXEEXT=$BUILD_EXEEXT
else
  TARGET_EXEEXT=$config_TARGET_EXEEXT
fi
if test "$TARGET_EXEEXT" = ".exe"; then
  if test $OS2_SHELL ; then
    SQLITE_OS_UNIX=0
    SQLITE_OS_WIN=0
    SQLITE_OS_OS2=1
    CFLAGS="$CFLAGS -DSQLITE_OS_OS2=1"
  else
    SQLITE_OS_UNIX=0
    SQLITE_OS_WIN=1
    SQLITE_OS_OS2=0
    CFLAGS="$CFLAGS -DSQLITE_OS_WIN=1"
  fi
else
  SQLITE_OS_UNIX=1
  SQLITE_OS_WIN=0
  SQLITE_OS_OS2=0
  CFLAGS="$CFLAGS -DSQLITE_OS_UNIX=1"
fi

AC_SUBST(BUILD_EXEEXT)
AC_SUBST(SQLITE_OS_UNIX)
AC_SUBST(SQLITE_OS_WIN)
AC_SUBST(SQLITE_OS_OS2)
AC_SUBST(TARGET_EXEEXT)

##########
# Figure out all the parameters needed to compile against Tcl.
#
# This code is derived from the SC_PATH_TCLCONFIG and SC_LOAD_TCLCONFIG
# macros in the in the tcl.m4 file of the standard TCL distribution.
# Those macros could not be used directly since we have to make some
# minor changes to accomodate systems that do not have TCL installed.
#
AC_ARG_ENABLE(tcl, AC_HELP_STRING([--disable-tcl],[do not build TCL extension]),
      [use_tcl=$enableval],[use_tcl=yes])
if test "${use_tcl}" = "yes" ; then
  AC_ARG_WITH(tcl, AC_HELP_STRING([--with-tcl=DIR],[directory containing tcl configuration (tclConfig.sh)]), with_tclconfig=${withval})
  AC_MSG_CHECKING([for Tcl configuration])
  AC_CACHE_VAL(ac_cv_c_tclconfig,[
    # First check to see if --with-tcl was specified.
    if test x"${with_tclconfig}" != x ; then
      if test -f "${with_tclconfig}/tclConfig.sh" ; then
        ac_cv_c_tclconfig=`(cd ${with_tclconfig}; pwd)`
      else
        AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
      fi
    fi

    # Start autosearch by asking tclsh
    if test x"$cross_compiling" = xno; then
      for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}`
      do
        if test -f "$i/tclConfig.sh" ; then
          ac_cv_c_tclconfig="$i"
          break
        fi
      done
    fi

    # then check for a private Tcl installation
    if test x"${ac_cv_c_tclconfig}" = x ; then
      for i in \
            ../tcl \
            `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
            `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
            `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
            ../../tcl \
            `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
            `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
            `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
            ../../../tcl \
            `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
            `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
            `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null`
      do
        if test -f "$i/unix/tclConfig.sh" ; then
          ac_cv_c_tclconfig=`(cd $i/unix; pwd)`
          break
        fi
      done
    fi

    # check in a few common install locations
    if test x"${ac_cv_c_tclconfig}" = x ; then
      for i in \
            `ls -d ${libdir} 2>/dev/null` \
            `ls -d /usr/local/lib 2>/dev/null` \
            `ls -d /usr/contrib/lib 2>/dev/null` \
            `ls -d /usr/lib 2>/dev/null`
      do
        if test -f "$i/tclConfig.sh" ; then
           ac_cv_c_tclconfig=`(cd $i; pwd)`
           break
        fi
      done
    fi

    # check in a few other private locations
    if test x"${ac_cv_c_tclconfig}" = x ; then
      for i in \
         ${srcdir}/../tcl \
         `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
         `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
         `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null`
      do
        if test -f "$i/unix/tclConfig.sh" ; then
          ac_cv_c_tclconfig=`(cd $i/unix; pwd)`
          break
        fi
      done
    fi
  ])

  if test x"${ac_cv_c_tclconfig}" = x ; then
    use_tcl=no
    AC_MSG_WARN(Can't find Tcl configuration definitions)
    AC_MSG_WARN(*** Without Tcl the regression tests cannot be executed ***)
    AC_MSG_WARN(*** Consider using --with-tcl=... to define location of Tcl ***)
  else
    TCL_BIN_DIR=${ac_cv_c_tclconfig}
    AC_MSG_RESULT(found $TCL_BIN_DIR/tclConfig.sh)

    AC_MSG_CHECKING([for existence of $TCL_BIN_DIR/tclConfig.sh])
    if test -f "$TCL_BIN_DIR/tclConfig.sh" ; then
      AC_MSG_RESULT([loading])
      . $TCL_BIN_DIR/tclConfig.sh
    else
      AC_MSG_RESULT([file not found])
    fi
    
    #
    # If the TCL_BIN_DIR is the build directory (not the install directory),
    # then set the common variable name to the value of the build variables.
    # For example, the variable TCL_LIB_SPEC will be set to the value
    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
    # installed and uninstalled version of Tcl.
    #
    
    if test -f $TCL_BIN_DIR/Makefile ; then
      TCL_LIB_SPEC=${TCL_BUILD_LIB_SPEC}
      TCL_STUB_LIB_SPEC=${TCL_BUILD_STUB_LIB_SPEC}
      TCL_STUB_LIB_PATH=${TCL_BUILD_STUB_LIB_PATH}
    fi
    
    #
    # eval is required to do the TCL_DBGX substitution
    #
    
    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
    
    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
    
    AC_SUBST(TCL_VERSION)
    AC_SUBST(TCL_BIN_DIR)
    AC_SUBST(TCL_SRC_DIR)
    AC_SUBST(TCL_LIBS)
    AC_SUBST(TCL_INCLUDE_SPEC)
    
    AC_SUBST(TCL_LIB_FILE)
    AC_SUBST(TCL_LIB_FLAG)
    AC_SUBST(TCL_LIB_SPEC)
    
    AC_SUBST(TCL_STUB_LIB_FILE)
    AC_SUBST(TCL_STUB_LIB_FLAG)
    AC_SUBST(TCL_STUB_LIB_SPEC)
  fi
fi
if test "${use_tcl}" = "no" ; then
  HAVE_TCL=""
else
  HAVE_TCL=1
fi
AC_SUBST(HAVE_TCL)

##########
# Figure out what C libraries are required to compile programs
# that use "readline()" library.
#
TARGET_READLINE_LIBS=""
TARGET_READLINE_INC=""
TARGET_HAVE_READLINE=0
AC_ARG_ENABLE([readline],
	[AC_HELP_STRING([--disable-readline],[disable readline support [default=detect]])],
	[with_readline=$enableval],
	[with_readline=auto])

if test x"$with_readline" != xno; then
	found="yes"

	AC_ARG_WITH([readline-lib],
		[AC_HELP_STRING([--with-readline-lib],[specify readline library])],
		[with_readline_lib=$withval],
		[with_readline_lib="auto"])
	if test "x$with_readline_lib" = xauto; then
		save_LIBS="$LIBS"
		LIBS=""
		AC_SEARCH_LIBS(tgetent, [readline ncurses curses termcap], [term_LIBS="$LIBS"], [term_LIBS=""])
		AC_CHECK_LIB([readline], [readline], [TARGET_READLINE_LIBS="-lreadline"], [found="no"])
		TARGET_READLINE_LIBS="$TARGET_READLINE_LIBS $term_LIBS"
		LIBS="$save_LIBS"
	else
		TARGET_READLINE_LIBS="$with_readline_lib"
	fi

	AC_ARG_WITH([readline-inc],
		[AC_HELP_STRING([--with-readline-inc],[specify readline include paths])],
		[with_readline_inc=$withval],
		[with_readline_inc="auto"])
	if test "x$with_readline_inc" = xauto; then
		AC_CHECK_HEADER(readline.h, [found="yes"], [
			found="no"
			if test "$cross_compiling" != yes; then
				for dir in /usr /usr/local /usr/local/readline /usr/contrib /mingw; do
					for subdir in include include/readline; do
						AC_CHECK_FILE($dir/$subdir/readline.h, found=yes)
						if test "$found" = "yes"; then
							TARGET_READLINE_INC="-I$dir/$subdir"
							break
						fi
					done
					test "$found" = "yes" && break
				done
			fi
		])
	else
		TARGET_READLINE_INC="$with_readline_inc"
	fi

	if test x"$found" = xno; then
		TARGET_READLINE_LIBS=""
		TARGET_READLINE_INC=""
		TARGET_HAVE_READLINE=0
	else
		TARGET_HAVE_READLINE=1
	fi
fi

AC_SUBST(TARGET_READLINE_LIBS)
AC_SUBST(TARGET_READLINE_INC)
AC_SUBST(TARGET_HAVE_READLINE)

##########
# Figure out what C libraries are required to compile programs
# that use "fdatasync()" function.
#
AC_SEARCH_LIBS(fdatasync, [rt])

#########
# check for debug enabled
AC_ARG_ENABLE(debug, AC_HELP_STRING([--enable-debug],[enable debugging & verbose explain]),
      [use_debug=$enableval],[use_debug=no])
if test "${use_debug}" = "yes" ; then
  TARGET_DEBUG="-DSQLITE_DEBUG=1"
else
  TARGET_DEBUG="-DNDEBUG"
fi
AC_SUBST(TARGET_DEBUG)

#########
# See whether we should use the amalgamation to build
AC_ARG_ENABLE(amalgamation, AC_HELP_STRING([--disable-amalgamation],
      [Disable the amalgamation and instead build all files separately]),
      [use_amalgamation=$enableval],[use_amalgamation=yes])
if test "${use_amalgamation}" != "yes" ; then
  USE_AMALGAMATION=0
fi
AC_SUBST(USE_AMALGAMATION)

#########
# See whether we should allow loadable extensions
AC_ARG_ENABLE(load-extension, AC_HELP_STRING([--enable-load-extension],
      [Enable loading of external extensions]),
      [use_loadextension=$enableval],[use_loadextension=no])
if test "${use_loadextension}" = "yes" ; then
  OPT_FEATURE_FLAGS=""
else
  OPT_FEATURE_FLAGS="-DSQLITE_OMIT_LOAD_EXTENSION=1"
fi

#########
# attempt to duplicate any OMITS and ENABLES into the $(OPT_FEATURE_FLAGS) parameter
for option in $CFLAGS $CPPFLAGS
do
  case $option in
    -DSQLITE_OMIT*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";;
    -DSQLITE_ENABLE*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";;
  esac
done
AC_SUBST(OPT_FEATURE_FLAGS)


# attempt to remove any OMITS and ENABLES from the $(CFLAGS) parameter
ac_temp_CFLAGS=""
for option in $CFLAGS
do
  case $option in
    -DSQLITE_OMIT*) ;;
    -DSQLITE_ENABLE*) ;;
    *) ac_temp_CFLAGS="$ac_temp_CFLAGS $option";;
  esac
done
CFLAGS=$ac_temp_CFLAGS


# attempt to remove any OMITS and ENABLES from the $(CPPFLAGS) parameter
ac_temp_CPPFLAGS=""
for option in $CPPFLAGS
do
  case $option in
    -DSQLITE_OMIT*) ;;
    -DSQLITE_ENABLE*) ;;
    *) ac_temp_CPPFLAGS="$ac_temp_CPPFLAGS $option";;
  esac
done
CPPFLAGS=$ac_temp_CPPFLAGS


# attempt to remove any OMITS and ENABLES from the $(BUILD_CFLAGS) parameter
ac_temp_BUILD_CFLAGS=""
for option in $BUILD_CFLAGS
do
  case $option in
    -DSQLITE_OMIT*) ;;
    -DSQLITE_ENABLE*) ;;
    *) ac_temp_BUILD_CFLAGS="$ac_temp_BUILD_CFLAGS $option";;
  esac
done
BUILD_CFLAGS=$ac_temp_BUILD_CFLAGS


#########
# See whether we should use GCOV
AC_ARG_ENABLE(gcov, AC_HELP_STRING([--enable-gcov],
      [Enable coverage testing using gcov]),
      [use_gcov=$enableval],[use_gcov=no])
if test "${use_gcov}" = "yes" ; then
  USE_GCOV=1
else
  USE_GCOV=0
fi
AC_SUBST(USE_GCOV)


#########
# Output the config header
AC_CONFIG_HEADERS(config.h)

#########
# Generate the output files.
#
AC_SUBST(BUILD_CFLAGS)
AC_OUTPUT([
Makefile
sqlite3.pc
])

Added contrib/sqlitecon.tcl.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# A Tk console widget for SQLite.  Invoke sqlitecon::create with a window name,
# a prompt string, a title to set a new top-level window, and the SQLite
# database handle.  For example:
#
#     sqlitecon::create .sqlcon {sql:- } {SQL Console} db
#
# A toplevel window is created that allows you to type in SQL commands to
# be processed on the spot.
#
# A limited set of dot-commands are supported:
#
#     .table
#     .schema ?TABLE?
#     .mode list|column|multicolumn|line
#     .exit
#
# In addition, a new SQL function named "edit()" is created.  This function
# takes a single text argument and returns a text result.  Whenever the
# the function is called, it pops up a new toplevel window containing a
# text editor screen initialized to the argument.  When the "OK" button
# is pressed, whatever revised text is in the text editor is returned as
# the result of the edit() function.  This allows text fields of SQL tables
# to be edited quickly and easily as follows:
#
#    UPDATE table1 SET dscr = edit(dscr) WHERE rowid=15;
#


# Create a namespace to work in
#
namespace eval ::sqlitecon {
  # do nothing
}

# Create a console widget named $w.  The prompt string is $prompt.
# The title at the top of the window is $title.  The database connection
# object is $db
#
proc sqlitecon::create {w prompt title db} {
  upvar #0 $w.t v
  if {[winfo exists $w]} {destroy $w}
  if {[info exists v]} {unset v}
  toplevel $w
  wm title $w $title
  wm iconname $w $title
  frame $w.mb -bd 2 -relief raised
  pack $w.mb -side top -fill x
  menubutton $w.mb.file -text File -menu $w.mb.file.m
  menubutton $w.mb.edit -text Edit -menu $w.mb.edit.m
  pack $w.mb.file $w.mb.edit -side left -padx 8 -pady 1
  set m [menu $w.mb.file.m -tearoff 0]
  $m add command -label {Close} -command "destroy $w"
  sqlitecon::create_child $w $prompt $w.mb.edit.m
  set v(db) $db
  $db function edit ::sqlitecon::_edit
}

# This routine creates a console as a child window within a larger
# window.  It also creates an edit menu named "$editmenu" if $editmenu!="".
# The calling function is responsible for posting the edit menu.
#
proc sqlitecon::create_child {w prompt editmenu} {
  upvar #0 $w.t v
  if {$editmenu!=""} {
    set m [menu $editmenu -tearoff 0]
    $m add command -label Cut -command "sqlitecon::Cut $w.t"
    $m add command -label Copy -command "sqlitecon::Copy $w.t"
    $m add command -label Paste -command "sqlitecon::Paste $w.t"
    $m add command -label {Clear Screen} -command "sqlitecon::Clear $w.t"
    $m add separator
    $m add command -label {Save As...} -command "sqlitecon::SaveFile $w.t"
    catch {$editmenu config -postcommand "sqlitecon::EnableEditMenu $w"}
  }
  scrollbar $w.sb -orient vertical -command "$w.t yview"
  pack $w.sb -side right -fill y
  text $w.t -font fixed -yscrollcommand "$w.sb set"
  pack $w.t -side right -fill both -expand 1
  bindtags $w.t Sqlitecon
  set v(editmenu) $editmenu
  set v(history) 0
  set v(historycnt) 0
  set v(current) -1
  set v(prompt) $prompt
  set v(prior) {}
  set v(plength) [string length $v(prompt)]
  set v(x) 0
  set v(y) 0
  set v(mode) column
  set v(header) on
  $w.t mark set insert end
  $w.t tag config ok -foreground blue
  $w.t tag config err -foreground red
  $w.t insert end $v(prompt)
  $w.t mark set out 1.0
  after idle "focus $w.t"
}

bind Sqlitecon <1> {sqlitecon::Button1 %W %x %y}
bind Sqlitecon <B1-Motion> {sqlitecon::B1Motion %W %x %y}
bind Sqlitecon <B1-Leave> {sqlitecon::B1Leave %W %x %y}
bind Sqlitecon <B1-Enter> {sqlitecon::cancelMotor %W}
bind Sqlitecon <ButtonRelease-1> {sqlitecon::cancelMotor %W}
bind Sqlitecon <KeyPress> {sqlitecon::Insert %W %A}
bind Sqlitecon <Left> {sqlitecon::Left %W}
bind Sqlitecon <Control-b> {sqlitecon::Left %W}
bind Sqlitecon <Right> {sqlitecon::Right %W}
bind Sqlitecon <Control-f> {sqlitecon::Right %W}
bind Sqlitecon <BackSpace> {sqlitecon::Backspace %W}
bind Sqlitecon <Control-h> {sqlitecon::Backspace %W}
bind Sqlitecon <Delete> {sqlitecon::Delete %W}
bind Sqlitecon <Control-d> {sqlitecon::Delete %W}
bind Sqlitecon <Home> {sqlitecon::Home %W}
bind Sqlitecon <Control-a> {sqlitecon::Home %W}
bind Sqlitecon <End> {sqlitecon::End %W}
bind Sqlitecon <Control-e> {sqlitecon::End %W}
bind Sqlitecon <Return> {sqlitecon::Enter %W}
bind Sqlitecon <KP_Enter> {sqlitecon::Enter %W}
bind Sqlitecon <Up> {sqlitecon::Prior %W}
bind Sqlitecon <Control-p> {sqlitecon::Prior %W}
bind Sqlitecon <Down> {sqlitecon::Next %W}
bind Sqlitecon <Control-n> {sqlitecon::Next %W}
bind Sqlitecon <Control-k> {sqlitecon::EraseEOL %W}
bind Sqlitecon <<Cut>> {sqlitecon::Cut %W}
bind Sqlitecon <<Copy>> {sqlitecon::Copy %W}
bind Sqlitecon <<Paste>> {sqlitecon::Paste %W}
bind Sqlitecon <<Clear>> {sqlitecon::Clear %W}

# Insert a single character at the insertion cursor
#
proc sqlitecon::Insert {w a} {
  $w insert insert $a
  $w yview insert
}

# Move the cursor one character to the left
#
proc sqlitecon::Left {w} {
  upvar #0 $w v
  scan [$w index insert] %d.%d row col
  if {$col>$v(plength)} {
    $w mark set insert "insert -1c"
  }
}

# Erase the character to the left of the cursor
#
proc sqlitecon::Backspace {w} {
  upvar #0 $w v
  scan [$w index insert] %d.%d row col
  if {$col>$v(plength)} {
    $w delete {insert -1c}
  }
}

# Erase to the end of the line
#
proc sqlitecon::EraseEOL {w} {
  upvar #0 $w v
  scan [$w index insert] %d.%d row col
  if {$col>=$v(plength)} {
    $w delete insert {insert lineend}
  }
}

# Move the cursor one character to the right
#
proc sqlitecon::Right {w} {
  $w mark set insert "insert +1c"
}

# Erase the character to the right of the cursor
#
proc sqlitecon::Delete w {
  $w delete insert
}

# Move the cursor to the beginning of the current line
#
proc sqlitecon::Home w {
  upvar #0 $w v
  scan [$w index insert] %d.%d row col
  $w mark set insert $row.$v(plength)
}

# Move the cursor to the end of the current line
#
proc sqlitecon::End w {
  $w mark set insert {insert lineend}
}

# Add a line to the history
#
proc sqlitecon::addHistory {w line} {
  upvar #0 $w v
  if {$v(historycnt)>0} {
    set last [lindex $v(history) [expr $v(historycnt)-1]]
    if {[string compare $last $line]} {
      lappend v(history) $line
      incr v(historycnt)
    }
  } else {
    set v(history) [list $line]
    set v(historycnt) 1
  }
  set v(current) $v(historycnt)
}

# Called when "Enter" is pressed.  Do something with the line
# of text that was entered.
#
proc sqlitecon::Enter w {
  upvar #0 $w v
  scan [$w index insert] %d.%d row col
  set start $row.$v(plength)
  set line [$w get $start "$start lineend"]
  $w insert end \n
  $w mark set out end
  if {$v(prior)==""} {
    set cmd $line
  } else {
    set cmd $v(prior)\n$line
  }
  if {[string index $cmd 0]=="." || [$v(db) complete $cmd]} {
    regsub -all {\n} [string trim $cmd] { } cmd2
    addHistory $w $cmd2
    set rc [catch {DoCommand $w $cmd} res]
    if {![winfo exists $w]} return
    if {$rc} {
      $w insert end $res\n err
    } elseif {[string length $res]>0} {
      $w insert end $res\n ok
    }
    set v(prior) {}
    $w insert end $v(prompt)
  } else {
    set v(prior) $cmd
    regsub -all {[^ ]} $v(prompt) . x
    $w insert end $x
  }
  $w mark set insert end
  $w mark set out {insert linestart}
  $w yview insert
}

# Execute a single SQL command.  Pay special attention to control
# directives that begin with "."
#
# The return value is the text output from the command, properly
# formatted.
#
proc sqlitecon::DoCommand {w cmd} {
  upvar #0 $w v
  set mode $v(mode)
  set header $v(header)
  if {[regexp {^(\.[a-z]+)} $cmd all word]} {
    if {$word==".mode"} {
      regexp {^.[a-z]+ +([a-z]+)} $cmd all v(mode)
      return {}
    } elseif {$word==".exit"} {
      destroy [winfo toplevel $w]
      return {}
    } elseif {$word==".header"} {
      regexp {^.[a-z]+ +([a-z]+)} $cmd all v(header)
      return {}
    } elseif {$word==".tables"} {
      set mode multicolumn
      set cmd {SELECT name FROM sqlite_master WHERE type='table'
               UNION ALL
               SELECT name FROM sqlite_temp_master WHERE type='table'}
      $v(db) eval {PRAGMA database_list} {
         if {$name!="temp" && $name!="main"} {
            append cmd "UNION ALL SELECT name FROM $name.sqlite_master\
                        WHERE type='table'"
         }
      }
      append cmd  { ORDER BY 1}
    } elseif {$word==".fullschema"} {
      set pattern %
      regexp {^.[a-z]+ +([^ ]+)} $cmd all pattern
      set mode list
      set header 0
      set cmd "SELECT sql FROM sqlite_master WHERE tbl_name LIKE '$pattern'
               AND sql NOT NULL UNION ALL SELECT sql FROM sqlite_temp_master
               WHERE tbl_name LIKE '$pattern' AND sql NOT NULL"
      $v(db) eval {PRAGMA database_list} {
         if {$name!="temp" && $name!="main"} {
            append cmd " UNION ALL SELECT sql FROM $name.sqlite_master\
                        WHERE tbl_name LIKE '$pattern' AND sql NOT NULL"
         }
      }
    } elseif {$word==".schema"} {
      set pattern %
      regexp {^.[a-z]+ +([^ ]+)} $cmd all pattern
      set mode list
      set header 0
      set cmd "SELECT sql FROM sqlite_master WHERE name LIKE '$pattern'
               AND sql NOT NULL UNION ALL SELECT sql FROM sqlite_temp_master
               WHERE name LIKE '$pattern' AND sql NOT NULL"
      $v(db) eval {PRAGMA database_list} {
         if {$name!="temp" && $name!="main"} {
            append cmd " UNION ALL SELECT sql FROM $name.sqlite_master\
                        WHERE name LIKE '$pattern' AND sql NOT NULL"
         }
      }
    } else {
      return \
        ".exit\n.mode line|list|column\n.schema ?TABLENAME?\n.tables"
    }
  }
  set res {}
  if {$mode=="list"} {
    $v(db) eval $cmd x {
      set sep {}
      foreach col $x(*) {
        append res $sep$x($col)
        set sep |
      }
      append res \n
    }
    if {[info exists x(*)] && $header} {
      set sep {}
      set hdr {}
      foreach col $x(*) {
        append hdr $sep$col
        set sep |
      }
      set res $hdr\n$res
    }
  } elseif {[string range $mode 0 2]=="col"} {
    set y {}
    $v(db) eval $cmd x {
      foreach col $x(*) {
        if {![info exists cw($col)] || $cw($col)<[string length $x($col)]} {
           set cw($col) [string length $x($col)]
        }
        lappend y $x($col)
      }
    }
    if {[info exists x(*)] && $header} {
      set hdr {}
      set ln {}
      set dash ---------------------------------------------------------------
      append dash ------------------------------------------------------------
      foreach col $x(*) {
        if {![info exists cw($col)] || $cw($col)<[string length $col]} {
           set cw($col) [string length $col]
        }
        lappend hdr $col
        lappend ln [string range $dash 1 $cw($col)]
      }
      set y [concat $hdr $ln $y]
    }
    if {[info exists x(*)]} {
      set format {}
      set arglist {}
      set arglist2 {}
      set i 0
      foreach col $x(*) {
        lappend arglist x$i
        append arglist2 " \$x$i"
        incr i
        append format "  %-$cw($col)s"
      }
      set format [string trimleft $format]\n
      if {[llength $arglist]>0} {
        foreach $arglist $y "append res \[format [list $format] $arglist2\]"
      }
    }
  } elseif {$mode=="multicolumn"} {
    set y [$v(db) eval $cmd]
    set max 0
    foreach e $y {
      if {$max<[string length $e]} {set max [string length $e]}
    }
    set ncol [expr {int(80/($max+2))}]
    if {$ncol<1} {set ncol 1}
    set nelem [llength $y]
    set nrow [expr {($nelem+$ncol-1)/$ncol}]
    set format "%-${max}s"
    for {set i 0} {$i<$nrow} {incr i} {
      set j $i
      while 1 {
        append res [format $format [lindex $y $j]]
        incr j $nrow
        if {$j>=$nelem} break
        append res {  }
      }
      append res \n
    }
  } else {
    $v(db) eval $cmd x {
      foreach col $x(*) {append res "$col = $x($col)\n"}
      append res \n
    }
  }
  return [string trimright $res]
}

# Change the line to the previous line
#
proc sqlitecon::Prior w {
  upvar #0 $w v
  if {$v(current)<=0} return
  incr v(current) -1
  set line [lindex $v(history) $v(current)]
  sqlitecon::SetLine $w $line
}

# Change the line to the next line
#
proc sqlitecon::Next w {
  upvar #0 $w v
  if {$v(current)>=$v(historycnt)} return
  incr v(current) 1
  set line [lindex $v(history) $v(current)]
  sqlitecon::SetLine $w $line
}

# Change the contents of the entry line
#
proc sqlitecon::SetLine {w line} {
  upvar #0 $w v
  scan [$w index insert] %d.%d row col
  set start $row.$v(plength)
  $w delete $start end
  $w insert end $line
  $w mark set insert end
  $w yview insert
}

# Called when the mouse button is pressed at position $x,$y on
# the console widget.
#
proc sqlitecon::Button1 {w x y} {
  global tkPriv
  upvar #0 $w v
  set v(mouseMoved) 0
  set v(pressX) $x
  set p [sqlitecon::nearestBoundry $w $x $y]
  scan [$w index insert] %d.%d ix iy
  scan $p %d.%d px py
  if {$px==$ix} {
    $w mark set insert $p
  }
  $w mark set anchor $p
  focus $w
}

# Find the boundry between characters that is nearest
# to $x,$y
#
proc sqlitecon::nearestBoundry {w x y} {
  set p [$w index @$x,$y]
  set bb [$w bbox $p]
  if {![string compare $bb ""]} {return $p}
  if {($x-[lindex $bb 0])<([lindex $bb 2]/2)} {return $p}
  $w index "$p + 1 char"
}

# This routine extends the selection to the point specified by $x,$y
#
proc sqlitecon::SelectTo {w x y} {
  upvar #0 $w v
  set cur [sqlitecon::nearestBoundry $w $x $y]
  if {[catch {$w index anchor}]} {
    $w mark set anchor $cur
  }
  set anchor [$w index anchor]
  if {[$w compare $cur != $anchor] || (abs($v(pressX) - $x) >= 3)} {
    if {$v(mouseMoved)==0} {
      $w tag remove sel 0.0 end
    }
    set v(mouseMoved) 1
  }
  if {[$w compare $cur < anchor]} {
    set first $cur
    set last anchor
  } else {
    set first anchor
    set last $cur
  }
  if {$v(mouseMoved)} {
    $w tag remove sel 0.0 $first
    $w tag add sel $first $last
    $w tag remove sel $last end
    update idletasks
  }
}

# Called whenever the mouse moves while button-1 is held down.
#
proc sqlitecon::B1Motion {w x y} {
  upvar #0 $w v
  set v(y) $y
  set v(x) $x
  sqlitecon::SelectTo $w $x $y
}

# Called whenever the mouse leaves the boundries of the widget
# while button 1 is held down.
#
proc sqlitecon::B1Leave {w x y} {
  upvar #0 $w v
  set v(y) $y
  set v(x) $x
  sqlitecon::motor $w
}

# This routine is called to automatically scroll the window when
# the mouse drags offscreen.
#
proc sqlitecon::motor w {
  upvar #0 $w v
  if {![winfo exists $w]} return
  if {$v(y)>=[winfo height $w]} {
    $w yview scroll 1 units
  } elseif {$v(y)<0} {
    $w yview scroll -1 units
  } else {
    return
  }
  sqlitecon::SelectTo $w $v(x) $v(y)
  set v(timer) [after 50 sqlitecon::motor $w]
}

# This routine cancels the scrolling motor if it is active
#
proc sqlitecon::cancelMotor w {
  upvar #0 $w v
  catch {after cancel $v(timer)}
  catch {unset v(timer)}
}

# Do a Copy operation on the stuff currently selected.
#
proc sqlitecon::Copy w {
  if {![catch {set text [$w get sel.first sel.last]}]} {
     clipboard clear -displayof $w
     clipboard append -displayof $w $text
  }
}

# Return 1 if the selection exists and is contained
# entirely on the input line.  Return 2 if the selection
# exists but is not entirely on the input line.  Return 0
# if the selection does not exist.
#
proc sqlitecon::canCut w {
  set r [catch {
    scan [$w index sel.first] %d.%d s1x s1y
    scan [$w index sel.last] %d.%d s2x s2y
    scan [$w index insert] %d.%d ix iy
  }]
  if {$r==1} {return 0}
  if {$s1x==$ix && $s2x==$ix} {return 1}
  return 2
}

# Do a Cut operation if possible.  Cuts are only allowed
# if the current selection is entirely contained on the
# current input line.
#
proc sqlitecon::Cut w {
  if {[sqlitecon::canCut $w]==1} {
    sqlitecon::Copy $w
    $w delete sel.first sel.last
  }
}

# Do a paste opeation.
#
proc sqlitecon::Paste w {
  if {[sqlitecon::canCut $w]==1} {
    $w delete sel.first sel.last
  }
  if {[catch {selection get -displayof $w -selection CLIPBOARD} topaste]
    && [catch {selection get -displayof $w -selection PRIMARY} topaste]} {
    return
  }
  if {[info exists ::$w]} {
    set prior 0
    foreach line [split $topaste \n] {
      if {$prior} {
        sqlitecon::Enter $w
        update
      }
      set prior 1
      $w insert insert $line
    }
  } else {
    $w insert insert $topaste
  }
}

# Enable or disable entries in the Edit menu
#
proc sqlitecon::EnableEditMenu w {
  upvar #0 $w.t v
  set m $v(editmenu)
  if {$m=="" || ![winfo exists $m]} return
  switch [sqlitecon::canCut $w.t] {
    0 {
      $m entryconf Copy -state disabled
      $m entryconf Cut -state disabled
    }
    1 {
      $m entryconf Copy -state normal
      $m entryconf Cut -state normal
    }
    2 {
      $m entryconf Copy -state normal
      $m entryconf Cut -state disabled
    }
  }
}

# Prompt the user for the name of a writable file.  Then write the
# entire contents of the console screen to that file.
#
proc sqlitecon::SaveFile w {
  set types {
    {{Text Files}  {.txt}}
    {{All Files}    *}
  }
  set f [tk_getSaveFile -filetypes $types -title "Write Screen To..."]
  if {$f!=""} {
    if {[catch {open $f w} fd]} {
      tk_messageBox -type ok -icon error -message $fd
    } else {
      puts $fd [string trimright [$w get 1.0 end] \n]
      close $fd
    }
  }
}

# Erase everything from the console above the insertion line.
#
proc sqlitecon::Clear w {
  $w delete 1.0 {insert linestart}
}

# An in-line editor for SQL
#
proc sqlitecon::_edit {origtxt {title {}}} {
  for {set i 0} {[winfo exists .ed$i]} {incr i} continue
  set w .ed$i
  toplevel $w
  wm protocol $w WM_DELETE_WINDOW "$w.b.can invoke"
  wm title $w {Inline SQL Editor}
  frame $w.b
  pack $w.b -side bottom -fill x
  button $w.b.can -text Cancel -width 6 -command [list set ::$w 0]
  button $w.b.ok -text OK -width 6 -command [list set ::$w 1]
  button $w.b.cut -text Cut -width 6 -command [list ::sqlitecon::Cut $w.t]
  button $w.b.copy -text Copy -width 6 -command [list ::sqlitecon::Copy $w.t]
  button $w.b.paste -text Paste -width 6 -command [list ::sqlitecon::Paste $w.t]
  set ::$w {}
  pack $w.b.cut $w.b.copy $w.b.paste $w.b.can $w.b.ok\
     -side left -padx 5 -pady 5 -expand 1
  if {$title!=""} {
    label $w.title -text $title
    pack $w.title -side top -padx 5 -pady 5
  }
  text $w.t -bg white -fg black -yscrollcommand [list $w.sb set]
  pack $w.t -side left -fill both -expand 1
  scrollbar $w.sb -orient vertical -command [list $w.t yview]
  pack $w.sb -side left -fill y
  $w.t insert end $origtxt

  vwait ::$w

  if {[set ::$w]} {
    set txt [string trimright [$w.t get 1.0 end]]
  } else {
    set txt $origtxt
  }
  destroy $w
  return $txt
}

Added doc/lemon.html.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
<html>
<head>
<title>The Lemon Parser Generator</title>
</head>
<body bgcolor=white>
<h1 align=center>The Lemon Parser Generator</h1>

<p>Lemon is an LALR(1) parser generator for C or C++.  
It does the same job as ``bison'' and ``yacc''.
But lemon is not another bison or yacc clone.  It
uses a different grammar syntax which is designed to
reduce the number of coding errors.  Lemon also uses a more
sophisticated parsing engine that is faster than yacc and
bison and which is both reentrant and thread-safe.
Furthermore, Lemon implements features that can be used
to eliminate resource leaks, making is suitable for use
in long-running programs such as graphical user interfaces
or embedded controllers.</p>

<p>This document is an introduction to the Lemon
parser generator.</p>

<h2>Theory of Operation</h2>

<p>The main goal of Lemon is to translate a context free grammar (CFG)
for a particular language into C code that implements a parser for
that language.
The program has two inputs:
<ul>
<li>The grammar specification.
<li>A parser template file.
</ul>
Typically, only the grammar specification is supplied by the programmer.
Lemon comes with a default parser template which works fine for most
applications.  But the user is free to substitute a different parser
template if desired.</p>

<p>Depending on command-line options, Lemon will generate between
one and three files of outputs.
<ul>
<li>C code to implement the parser.
<li>A header file defining an integer ID for each terminal symbol.
<li>An information file that describes the states of the generated parser
    automaton.
</ul>
By default, all three of these output files are generated.
The header file is suppressed if the ``-m'' command-line option is
used and the report file is omitted when ``-q'' is selected.</p>

<p>The grammar specification file uses a ``.y'' suffix, by convention.
In the examples used in this document, we'll assume the name of the
grammar file is ``gram.y''.  A typical use of Lemon would be the
following command:
<pre>
   lemon gram.y
</pre>
This command will generate three output files named ``gram.c'',
``gram.h'' and ``gram.out''.
The first is C code to implement the parser.  The second
is the header file that defines numerical values for all
terminal symbols, and the last is the report that explains
the states used by the parser automaton.</p>

<h3>Command Line Options</h3>

<p>The behavior of Lemon can be modified using command-line options.
You can obtain a list of the available command-line options together
with a brief explanation of what each does by typing
<pre>
   lemon -?
</pre>
As of this writing, the following command-line options are supported:
<ul>
<li><tt>-b</tt>
<li><tt>-c</tt>
<li><tt>-g</tt>
<li><tt>-m</tt>
<li><tt>-q</tt>
<li><tt>-s</tt>
<li><tt>-x</tt>
</ul>
The ``-b'' option reduces the amount of text in the report file by
printing only the basis of each parser state, rather than the full
configuration.
The ``-c'' option suppresses action table compression.  Using -c
will make the parser a little larger and slower but it will detect
syntax errors sooner.
The ``-g'' option causes no output files to be generated at all.
Instead, the input grammar file is printed on standard output but
with all comments, actions and other extraneous text deleted.  This
is a useful way to get a quick summary of a grammar.
The ``-m'' option causes the output C source file to be compatible
with the ``makeheaders'' program.
Makeheaders is a program that automatically generates header files
from C source code.  When the ``-m'' option is used, the header
file is not output since the makeheaders program will take care
of generated all header files automatically.
The ``-q'' option suppresses the report file.
Using ``-s'' causes a brief summary of parser statistics to be
printed.  Like this:
<pre>
   Parser statistics: 74 terminals, 70 nonterminals, 179 rules
                      340 states, 2026 parser table entries, 0 conflicts
</pre>
Finally, the ``-x'' option causes Lemon to print its version number
and then stops without attempting to read the grammar or generate a parser.</p>

<h3>The Parser Interface</h3>

<p>Lemon doesn't generate a complete, working program.  It only generates
a few subroutines that implement a parser.  This section describes
the interface to those subroutines.  It is up to the programmer to
call these subroutines in an appropriate way in order to produce a
complete system.</p>

<p>Before a program begins using a Lemon-generated parser, the program
must first create the parser.
A new parser is created as follows:
<pre>
   void *pParser = ParseAlloc( malloc );
</pre>
The ParseAlloc() routine allocates and initializes a new parser and
returns a pointer to it.
The actual data structure used to represent a parser is opaque --
its internal structure is not visible or usable by the calling routine.
For this reason, the ParseAlloc() routine returns a pointer to void
rather than a pointer to some particular structure.
The sole argument to the ParseAlloc() routine is a pointer to the
subroutine used to allocate memory.  Typically this means ``malloc()''.</p>

<p>After a program is finished using a parser, it can reclaim all
memory allocated by that parser by calling
<pre>
   ParseFree(pParser, free);
</pre>
The first argument is the same pointer returned by ParseAlloc().  The
second argument is a pointer to the function used to release bulk
memory back to the system.</p>

<p>After a parser has been allocated using ParseAlloc(), the programmer
must supply the parser with a sequence of tokens (terminal symbols) to
be parsed.  This is accomplished by calling the following function
once for each token:
<pre>
   Parse(pParser, hTokenID, sTokenData, pArg);
</pre>
The first argument to the Parse() routine is the pointer returned by
ParseAlloc().
The second argument is a small positive integer that tells the parse the
type of the next token in the data stream.
There is one token type for each terminal symbol in the grammar.
The gram.h file generated by Lemon contains #define statements that
map symbolic terminal symbol names into appropriate integer values.
(A value of 0 for the second argument is a special flag to the
parser to indicate that the end of input has been reached.)
The third argument is the value of the given token.  By default,
the type of the third argument is integer, but the grammar will
usually redefine this type to be some kind of structure.
Typically the second argument will be a broad category of tokens
such as ``identifier'' or ``number'' and the third argument will
be the name of the identifier or the value of the number.</p>

<p>The Parse() function may have either three or four arguments,
depending on the grammar.  If the grammar specification file request
it, the Parse() function will have a fourth parameter that can be
of any type chosen by the programmer.  The parser doesn't do anything
with this argument except to pass it through to action routines.
This is a convenient mechanism for passing state information down
to the action routines without having to use global variables.</p>

<p>A typical use of a Lemon parser might look something like the
following:
<pre>
   01 ParseTree *ParseFile(const char *zFilename){
   02    Tokenizer *pTokenizer;
   03    void *pParser;
   04    Token sToken;
   05    int hTokenId;
   06    ParserState sState;
   07
   08    pTokenizer = TokenizerCreate(zFilename);
   09    pParser = ParseAlloc( malloc );
   10    InitParserState(&sState);
   11    while( GetNextToken(pTokenizer, &hTokenId, &sToken) ){
   12       Parse(pParser, hTokenId, sToken, &sState);
   13    }
   14    Parse(pParser, 0, sToken, &sState);
   15    ParseFree(pParser, free );
   16    TokenizerFree(pTokenizer);
   17    return sState.treeRoot;
   18 }
</pre>
This example shows a user-written routine that parses a file of
text and returns a pointer to the parse tree.
(We've omitted all error-handling from this example to keep it
simple.)
We assume the existence of some kind of tokenizer which is created
using TokenizerCreate() on line 8 and deleted by TokenizerFree()
on line 16.  The GetNextToken() function on line 11 retrieves the
next token from the input file and puts its type in the 
integer variable hTokenId.  The sToken variable is assumed to be
some kind of structure that contains details about each token,
such as its complete text, what line it occurs on, etc. </p>

<p>This example also assumes the existence of structure of type
ParserState that holds state information about a particular parse.
An instance of such a structure is created on line 6 and initialized
on line 10.  A pointer to this structure is passed into the Parse()
routine as the optional 4th argument.
The action routine specified by the grammar for the parser can use
the ParserState structure to hold whatever information is useful and
appropriate.  In the example, we note that the treeRoot field of
the ParserState structure is left pointing to the root of the parse
tree.</p>

<p>The core of this example as it relates to Lemon is as follows:
<pre>
   ParseFile(){
      pParser = ParseAlloc( malloc );
      while( GetNextToken(pTokenizer,&hTokenId, &sToken) ){
         Parse(pParser, hTokenId, sToken);
      }
      Parse(pParser, 0, sToken);
      ParseFree(pParser, free );
   }
</pre>
Basically, what a program has to do to use a Lemon-generated parser
is first create the parser, then send it lots of tokens obtained by
tokenizing an input source.  When the end of input is reached, the
Parse() routine should be called one last time with a token type
of 0.  This step is necessary to inform the parser that the end of
input has been reached.  Finally, we reclaim memory used by the
parser by calling ParseFree().</p>

<p>There is one other interface routine that should be mentioned
before we move on.
The ParseTrace() function can be used to generate debugging output
from the parser.  A prototype for this routine is as follows:
<pre>
   ParseTrace(FILE *stream, char *zPrefix);
</pre>
After this routine is called, a short (one-line) message is written
to the designated output stream every time the parser changes states
or calls an action routine.  Each such message is prefaced using
the text given by zPrefix.  This debugging output can be turned off
by calling ParseTrace() again with a first argument of NULL (0).</p>

<h3>Differences With YACC and BISON</h3>

<p>Programmers who have previously used the yacc or bison parser
generator will notice several important differences between yacc and/or
bison and Lemon.
<ul>
<li>In yacc and bison, the parser calls the tokenizer.  In Lemon,
    the tokenizer calls the parser.
<li>Lemon uses no global variables.  Yacc and bison use global variables
    to pass information between the tokenizer and parser.
<li>Lemon allows multiple parsers to be running simultaneously.  Yacc
    and bison do not.
</ul>
These differences may cause some initial confusion for programmers
with prior yacc and bison experience.
But after years of experience using Lemon, I firmly
believe that the Lemon way of doing things is better.</p>

<h2>Input File Syntax</h2>

<p>The main purpose of the grammar specification file for Lemon is
to define the grammar for the parser.  But the input file also
specifies additional information Lemon requires to do its job.
Most of the work in using Lemon is in writing an appropriate
grammar file.</p>

<p>The grammar file for lemon is, for the most part, free format.
It does not have sections or divisions like yacc or bison.  Any
declaration can occur at any point in the file.
Lemon ignores whitespace (except where it is needed to separate
tokens) and it honors the same commenting conventions as C and C++.</p>

<h3>Terminals and Nonterminals</h3>

<p>A terminal symbol (token) is any string of alphanumeric
and underscore characters
that begins with an upper case letter.
A terminal can contain lower class letters after the first character,
but the usual convention is to make terminals all upper case.
A nonterminal, on the other hand, is any string of alphanumeric
and underscore characters than begins with a lower case letter.
Again, the usual convention is to make nonterminals use all lower
case letters.</p>

<p>In Lemon, terminal and nonterminal symbols do not need to 
be declared or identified in a separate section of the grammar file.
Lemon is able to generate a list of all terminals and nonterminals
by examining the grammar rules, and it can always distinguish a
terminal from a nonterminal by checking the case of the first
character of the name.</p>

<p>Yacc and bison allow terminal symbols to have either alphanumeric
names or to be individual characters included in single quotes, like
this: ')' or '$'.  Lemon does not allow this alternative form for
terminal symbols.  With Lemon, all symbols, terminals and nonterminals,
must have alphanumeric names.</p>

<h3>Grammar Rules</h3>

<p>The main component of a Lemon grammar file is a sequence of grammar
rules.
Each grammar rule consists of a nonterminal symbol followed by
the special symbol ``::='' and then a list of terminals and/or nonterminals.
The rule is terminated by a period.
The list of terminals and nonterminals on the right-hand side of the
rule can be empty.
Rules can occur in any order, except that the left-hand side of the
first rule is assumed to be the start symbol for the grammar (unless
specified otherwise using the <tt>%start</tt> directive described below.)
A typical sequence of grammar rules might look something like this:
<pre>
  expr ::= expr PLUS expr.
  expr ::= expr TIMES expr.
  expr ::= LPAREN expr RPAREN.
  expr ::= VALUE.
</pre>
</p>

<p>There is one non-terminal in this example, ``expr'', and five
terminal symbols or tokens: ``PLUS'', ``TIMES'', ``LPAREN'',
``RPAREN'' and ``VALUE''.</p>

<p>Like yacc and bison, Lemon allows the grammar to specify a block
of C code that will be executed whenever a grammar rule is reduced
by the parser.
In Lemon, this action is specified by putting the C code (contained
within curly braces <tt>{...}</tt>) immediately after the
period that closes the rule.
For example:
<pre>
  expr ::= expr PLUS expr.   { printf("Doing an addition...\n"); }
</pre>
</p>

<p>In order to be useful, grammar actions must normally be linked to
their associated grammar rules.
In yacc and bison, this is accomplished by embedding a ``$$'' in the
action to stand for the value of the left-hand side of the rule and
symbols ``$1'', ``$2'', and so forth to stand for the value of
the terminal or nonterminal at position 1, 2 and so forth on the
right-hand side of the rule.
This idea is very powerful, but it is also very error-prone.  The
single most common source of errors in a yacc or bison grammar is
to miscount the number of symbols on the right-hand side of a grammar
rule and say ``$7'' when you really mean ``$8''.</p>

<p>Lemon avoids the need to count grammar symbols by assigning symbolic
names to each symbol in a grammar rule and then using those symbolic
names in the action.
In yacc or bison, one would write this:
<pre>
  expr -> expr PLUS expr  { $$ = $1 + $3; };
</pre>
But in Lemon, the same rule becomes the following:
<pre>
  expr(A) ::= expr(B) PLUS expr(C).  { A = B+C; }
</pre>
In the Lemon rule, any symbol in parentheses after a grammar rule
symbol becomes a place holder for that symbol in the grammar rule.
This place holder can then be used in the associated C action to
stand for the value of that symbol.<p>

<p>The Lemon notation for linking a grammar rule with its reduce
action is superior to yacc/bison on several counts.
First, as mentioned above, the Lemon method avoids the need to
count grammar symbols.
Secondly, if a terminal or nonterminal in a Lemon grammar rule
includes a linking symbol in parentheses but that linking symbol
is not actually used in the reduce action, then an error message
is generated.
For example, the rule
<pre>
  expr(A) ::= expr(B) PLUS expr(C).  { A = B; }
</pre>
will generate an error because the linking symbol ``C'' is used
in the grammar rule but not in the reduce action.</p>

<p>The Lemon notation for linking grammar rules to reduce actions
also facilitates the use of destructors for reclaiming memory
allocated by the values of terminals and nonterminals on the
right-hand side of a rule.</p>

<h3>Precedence Rules</h3>

<p>Lemon resolves parsing ambiguities in exactly the same way as
yacc and bison.  A shift-reduce conflict is resolved in favor
of the shift, and a reduce-reduce conflict is resolved by reducing
whichever rule comes first in the grammar file.</p>

<p>Just like in
yacc and bison, Lemon allows a measure of control 
over the resolution of paring conflicts using precedence rules.
A precedence value can be assigned to any terminal symbol
using the %left, %right or %nonassoc directives.  Terminal symbols
mentioned in earlier directives have a lower precedence that
terminal symbols mentioned in later directives.  For example:</p>

<p><pre>
   %left AND.
   %left OR.
   %nonassoc EQ NE GT GE LT LE.
   %left PLUS MINUS.
   %left TIMES DIVIDE MOD.
   %right EXP NOT.
</pre></p>

<p>In the preceding sequence of directives, the AND operator is
defined to have the lowest precedence.  The OR operator is one
precedence level higher.  And so forth.  Hence, the grammar would
attempt to group the ambiguous expression
<pre>
     a AND b OR c
</pre>
like this
<pre>
     a AND (b OR c).
</pre>
The associativity (left, right or nonassoc) is used to determine
the grouping when the precedence is the same.  AND is left-associative
in our example, so
<pre>
     a AND b AND c
</pre>
is parsed like this
<pre>
     (a AND b) AND c.
</pre>
The EXP operator is right-associative, though, so
<pre>
     a EXP b EXP c
</pre>
is parsed like this
<pre>
     a EXP (b EXP c).
</pre>
The nonassoc precedence is used for non-associative operators.
So
<pre>
     a EQ b EQ c
</pre>
is an error.</p>

<p>The precedence of non-terminals is transferred to rules as follows:
The precedence of a grammar rule is equal to the precedence of the
left-most terminal symbol in the rule for which a precedence is
defined.  This is normally what you want, but in those cases where
you want to precedence of a grammar rule to be something different,
you can specify an alternative precedence symbol by putting the
symbol in square braces after the period at the end of the rule and
before any C-code.  For example:</p>

<p><pre>
   expr = MINUS expr.  [NOT]
</pre></p>

<p>This rule has a precedence equal to that of the NOT symbol, not the
MINUS symbol as would have been the case by default.</p>

<p>With the knowledge of how precedence is assigned to terminal
symbols and individual
grammar rules, we can now explain precisely how parsing conflicts
are resolved in Lemon.  Shift-reduce conflicts are resolved
as follows:
<ul>
<li> If either the token to be shifted or the rule to be reduced
     lacks precedence information, then resolve in favor of the
     shift, but report a parsing conflict.
<li> If the precedence of the token to be shifted is greater than
     the precedence of the rule to reduce, then resolve in favor
     of the shift.  No parsing conflict is reported.
<li> If the precedence of the token it be shifted is less than the
     precedence of the rule to reduce, then resolve in favor of the
     reduce action.  No parsing conflict is reported.
<li> If the precedences are the same and the shift token is
     right-associative, then resolve in favor of the shift.
     No parsing conflict is reported.
<li> If the precedences are the same the the shift token is
     left-associative, then resolve in favor of the reduce.
     No parsing conflict is reported.
<li> Otherwise, resolve the conflict by doing the shift and
     report the parsing conflict.
</ul>
Reduce-reduce conflicts are resolved this way:
<ul>
<li> If either reduce rule 
     lacks precedence information, then resolve in favor of the
     rule that appears first in the grammar and report a parsing
     conflict.
<li> If both rules have precedence and the precedence is different
     then resolve the dispute in favor of the rule with the highest
     precedence and do not report a conflict.
<li> Otherwise, resolve the conflict by reducing by the rule that
     appears first in the grammar and report a parsing conflict.
</ul>

<h3>Special Directives</h3>

<p>The input grammar to Lemon consists of grammar rules and special
directives.  We've described all the grammar rules, so now we'll
talk about the special directives.</p>

<p>Directives in lemon can occur in any order.  You can put them before
the grammar rules, or after the grammar rules, or in the mist of the
grammar rules.  It doesn't matter.  The relative order of
directives used to assign precedence to terminals is important, but
other than that, the order of directives in Lemon is arbitrary.</p>

<p>Lemon supports the following special directives:
<ul>
<li><tt>%code</tt>
<li><tt>%default_destructor</tt>
<li><tt>%default_type</tt>
<li><tt>%destructor</tt>
<li><tt>%extra_argument</tt>
<li><tt>%include</tt>
<li><tt>%left</tt>
<li><tt>%name</tt>
<li><tt>%nonassoc</tt>
<li><tt>%parse_accept</tt>
<li><tt>%parse_failure </tt>
<li><tt>%right</tt>
<li><tt>%stack_overflow</tt>
<li><tt>%stack_size</tt>
<li><tt>%start_symbol</tt>
<li><tt>%syntax_error</tt>
<li><tt>%token_destructor</tt>
<li><tt>%token_prefix</tt>
<li><tt>%token_type</tt>
<li><tt>%type</tt>
</ul>
Each of these directives will be described separately in the
following sections:</p>

<h4>The <tt>%code</tt> directive</h4>

<p>The %code directive is used to specify addition C/C++ code that
is added to the end of the main output file.  This is similar to
the %include directive except that %include is inserted at the
beginning of the main output file.</p>

<p>%code is typically used to include some action routines or perhaps
a tokenizer as part of the output file.</p>

<h4>The <tt>%default_destructor</tt> directive</h4>

<p>The %default_destructor directive specifies a destructor to 
use for non-terminals that do not have their own destructor
specified by a separate %destructor directive.  See the documentation
on the %destructor directive below for additional information.</p>

<p>In some grammers, many different non-terminal symbols have the
same datatype and hence the same destructor.  This directive is
a convenience way to specify the same destructor for all those
non-terminals using a single statement.</p>

<h4>The <tt>%default_type</tt> directive</h4>

<p>The %default_type directive specifies the datatype of non-terminal
symbols that do no have their own datatype defined using a separate
%type directive.  See the documentation on %type below for addition
information.</p>

<h4>The <tt>%destructor</tt> directive</h4>

<p>The %destructor directive is used to specify a destructor for
a non-terminal symbol.
(See also the %token_destructor directive which is used to
specify a destructor for terminal symbols.)</p>

<p>A non-terminal's destructor is called to dispose of the
non-terminal's value whenever the non-terminal is popped from
the stack.  This includes all of the following circumstances:
<ul>
<li> When a rule reduces and the value of a non-terminal on
     the right-hand side is not linked to C code.
<li> When the stack is popped during error processing.
<li> When the ParseFree() function runs.
</ul>
The destructor can do whatever it wants with the value of
the non-terminal, but its design is to deallocate memory
or other resources held by that non-terminal.</p>

<p>Consider an example:
<pre>
   %type nt {void*}
   %destructor nt { free($$); }
   nt(A) ::= ID NUM.   { A = malloc( 100 ); }
</pre>
This example is a bit contrived but it serves to illustrate how
destructors work.  The example shows a non-terminal named
``nt'' that holds values of type ``void*''.  When the rule for
an ``nt'' reduces, it sets the value of the non-terminal to
space obtained from malloc().  Later, when the nt non-terminal
is popped from the stack, the destructor will fire and call
free() on this malloced space, thus avoiding a memory leak.
(Note that the symbol ``$$'' in the destructor code is replaced
by the value of the non-terminal.)</p>

<p>It is important to note that the value of a non-terminal is passed
to the destructor whenever the non-terminal is removed from the
stack, unless the non-terminal is used in a C-code action.  If
the non-terminal is used by C-code, then it is assumed that the
C-code will take care of destroying it if it should really
be destroyed.  More commonly, the value is used to build some
larger structure and we don't want to destroy it, which is why
the destructor is not called in this circumstance.</p>

<p>By appropriate use of destructors, it is possible to
build a parser using Lemon that can be used within a long-running
program, such as a GUI, that will not leak memory or other resources.
To do the same using yacc or bison is much more difficult.</p>

<h4>The <tt>%extra_argument</tt> directive</h4>

The %extra_argument directive instructs Lemon to add a 4th parameter
to the parameter list of the Parse() function it generates.  Lemon
doesn't do anything itself with this extra argument, but it does
make the argument available to C-code action routines, destructors,
and so forth.  For example, if the grammar file contains:</p>

<p><pre>
    %extra_argument { MyStruct *pAbc }
</pre></p>

<p>Then the Parse() function generated will have an 4th parameter
of type ``MyStruct*'' and all action routines will have access to
a variable named ``pAbc'' that is the value of the 4th parameter
in the most recent call to Parse().</p>

<h4>The <tt>%include</tt> directive</h4>

<p>The %include directive specifies C code that is included at the
top of the generated parser.  You can include any text you want --
the Lemon parser generator copies it blindly.  If you have multiple
%include directives in your grammar file the value of the last
%include directive overwrites all the others.</p.

<p>The %include directive is very handy for getting some extra #include
preprocessor statements at the beginning of the generated parser.
For example:</p>

<p><pre>
   %include {#include &lt;unistd.h&gt;}
</pre></p>

<p>This might be needed, for example, if some of the C actions in the
grammar call functions that are prototyed in unistd.h.</p>

<h4>The <tt>%left</tt> directive</h4>

The %left directive is used (along with the %right and
%nonassoc directives) to declare precedences of terminal
symbols.  Every terminal symbol whose name appears after
a %left directive but before the next period (``.'') is
given the same left-associative precedence value.  Subsequent
%left directives have higher precedence.  For example:</p>

<p><pre>
   %left AND.
   %left OR.
   %nonassoc EQ NE GT GE LT LE.
   %left PLUS MINUS.
   %left TIMES DIVIDE MOD.
   %right EXP NOT.
</pre></p>

<p>Note the period that terminates each %left, %right or %nonassoc
directive.</p>

<p>LALR(1) grammars can get into a situation where they require
a large amount of stack space if you make heavy use or right-associative
operators.  For this reason, it is recommended that you use %left
rather than %right whenever possible.</p>

<h4>The <tt>%name</tt> directive</h4>

<p>By default, the functions generated by Lemon all begin with the
five-character string ``Parse''.  You can change this string to something
different using the %name directive.  For instance:</p>

<p><pre>
   %name Abcde
</pre></p>

<p>Putting this directive in the grammar file will cause Lemon to generate
functions named
<ul>
<li> AbcdeAlloc(),
<li> AbcdeFree(),
<li> AbcdeTrace(), and
<li> Abcde().
</ul>
The %name directive allows you to generator two or more different
parsers and link them all into the same executable.
</p>

<h4>The <tt>%nonassoc</tt> directive</h4>

<p>This directive is used to assign non-associative precedence to
one or more terminal symbols.  See the section on precedence rules
or on the %left directive for additional information.</p>

<h4>The <tt>%parse_accept</tt> directive</h4>

<p>The %parse_accept directive specifies a block of C code that is
executed whenever the parser accepts its input string.  To ``accept''
an input string means that the parser was able to process all tokens
without error.</p>

<p>For example:</p>

<p><pre>
   %parse_accept {
      printf("parsing complete!\n");
   }
</pre></p>


<h4>The <tt>%parse_failure</tt> directive</h4>

<p>The %parse_failure directive specifies a block of C code that
is executed whenever the parser fails complete.  This code is not
executed until the parser has tried and failed to resolve an input
error using is usual error recovery strategy.  The routine is
only invoked when parsing is unable to continue.</p>

<p><pre>
   %parse_failure {
     fprintf(stderr,"Giving up.  Parser is hopelessly lost...\n");
   }
</pre></p>

<h4>The <tt>%right</tt> directive</h4>

<p>This directive is used to assign right-associative precedence to
one or more terminal symbols.  See the section on precedence rules
or on the %left directive for additional information.</p>

<h4>The <tt>%stack_overflow</tt> directive</h4>

<p>The %stack_overflow directive specifies a block of C code that
is executed if the parser's internal stack ever overflows.  Typically
this just prints an error message.  After a stack overflow, the parser
will be unable to continue and must be reset.</p>

<p><pre>
   %stack_overflow {
     fprintf(stderr,"Giving up.  Parser stack overflow\n");
   }
</pre></p>

<p>You can help prevent parser stack overflows by avoiding the use
of right recursion and right-precedence operators in your grammar.
Use left recursion and and left-precedence operators instead, to
encourage rules to reduce sooner and keep the stack size down.
For example, do rules like this:
<pre>
   list ::= list element.      // left-recursion.  Good!
   list ::= .
</pre>
Not like this:
<pre>
   list ::= element list.      // right-recursion.  Bad!
   list ::= .
</pre>

<h4>The <tt>%stack_size</tt> directive</h4>

<p>If stack overflow is a problem and you can't resolve the trouble
by using left-recursion, then you might want to increase the size
of the parser's stack using this directive.  Put an positive integer
after the %stack_size directive and Lemon will generate a parse
with a stack of the requested size.  The default value is 100.</p>

<p><pre>
   %stack_size 2000
</pre></p>

<h4>The <tt>%start_symbol</tt> directive</h4>

<p>By default, the start-symbol for the grammar that Lemon generates
is the first non-terminal that appears in the grammar file.  But you
can choose a different start-symbol using the %start_symbol directive.</p>

<p><pre>
   %start_symbol  prog
</pre></p>

<h4>The <tt>%token_destructor</tt> directive</h4>

<p>The %destructor directive assigns a destructor to a non-terminal
symbol.  (See the description of the %destructor directive above.)
This directive does the same thing for all terminal symbols.</p>

<p>Unlike non-terminal symbols which may each have a different data type
for their values, terminals all use the same data type (defined by
the %token_type directive) and so they use a common destructor.  Other
than that, the token destructor works just like the non-terminal
destructors.</p>

<h4>The <tt>%token_prefix</tt> directive</h4>

<p>Lemon generates #defines that assign small integer constants
to each terminal symbol in the grammar.  If desired, Lemon will
add a prefix specified by this directive
to each of the #defines it generates.
So if the default output of Lemon looked like this:
<pre>
    #define AND              1
    #define MINUS            2
    #define OR               3
    #define PLUS             4
</pre>
You can insert a statement into the grammar like this:
<pre>
    %token_prefix    TOKEN_
</pre>
to cause Lemon to produce these symbols instead:
<pre>
    #define TOKEN_AND        1
    #define TOKEN_MINUS      2
    #define TOKEN_OR         3
    #define TOKEN_PLUS       4
</pre>

<h4>The <tt>%token_type</tt> and <tt>%type</tt> directives</h4>

<p>These directives are used to specify the data types for values
on the parser's stack associated with terminal and non-terminal
symbols.  The values of all terminal symbols must be of the same
type.  This turns out to be the same data type as the 3rd parameter
to the Parse() function generated by Lemon.  Typically, you will
make the value of a terminal symbol by a pointer to some kind of
token structure.  Like this:</p>

<p><pre>
   %token_type    {Token*}
</pre></p>

<p>If the data type of terminals is not specified, the default value
is ``int''.</p>

<p>Non-terminal symbols can each have their own data types.  Typically
the data type  of a non-terminal is a pointer to the root of a parse-tree
structure that contains all information about that non-terminal.
For example:</p>

<p><pre>
   %type   expr  {Expr*}
</pre></p>

<p>Each entry on the parser's stack is actually a union containing
instances of all data types for every non-terminal and terminal symbol.
Lemon will automatically use the correct element of this union depending
on what the corresponding non-terminal or terminal symbol is.  But
the grammar designer should keep in mind that the size of the union
will be the size of its largest element.  So if you have a single
non-terminal whose data type requires 1K of storage, then your 100
entry parser stack will require 100K of heap space.  If you are willing
and able to pay that price, fine.  You just need to know.</p>

<h3>Error Processing</h3>

<p>After extensive experimentation over several years, it has been
discovered that the error recovery strategy used by yacc is about
as good as it gets.  And so that is what Lemon uses.</p>

<p>When a Lemon-generated parser encounters a syntax error, it
first invokes the code specified by the %syntax_error directive, if
any.  It then enters its error recovery strategy.  The error recovery
strategy is to begin popping the parsers stack until it enters a
state where it is permitted to shift a special non-terminal symbol
named ``error''.  It then shifts this non-terminal and continues
parsing.  But the %syntax_error routine will not be called again
until at least three new tokens have been successfully shifted.</p>

<p>If the parser pops its stack until the stack is empty, and it still
is unable to shift the error symbol, then the %parse_failed routine
is invoked and the parser resets itself to its start state, ready
to begin parsing a new file.  This is what will happen at the very
first syntax error, of course, if there are no instances of the 
``error'' non-terminal in your grammar.</p>

</body>
</html>

Added ext/README.txt.





>
>
1
2
Version loadable extensions to SQLite are found in subfolders
of this folder.

Added ext/async/README.txt.









































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

Normally, when SQLite writes to a database file, it waits until the write
operation is finished before returning control to the calling application.
Since writing to the file-system is usually very slow compared with CPU
bound operations, this can be a performance bottleneck. This directory
contains an extension that causes SQLite to perform all write requests
using a separate thread running in the background. Although this does not
reduce the overall system resources (CPU, disk bandwidth etc.) at all, it
allows SQLite to return control to the caller quickly even when writing to
the database, eliminating the bottleneck.

  1. Functionality

    1.1 How it Works
    1.2 Limitations
    1.3 Locking and Concurrency

  2. Compilation and Usage

  3. Porting



1. FUNCTIONALITY

  With asynchronous I/O, write requests are handled by a separate thread
  running in the background.  This means that the thread that initiates
  a database write does not have to wait for (sometimes slow) disk I/O
  to occur.  The write seems to happen very quickly, though in reality
  it is happening at its usual slow pace in the background.

  Asynchronous I/O appears to give better responsiveness, but at a price.
  You lose the Durable property.  With the default I/O backend of SQLite,
  once a write completes, you know that the information you wrote is
  safely on disk.  With the asynchronous I/O, this is not the case.  If
  your program crashes or if a power loss occurs after the database
  write but before the asynchronous write thread has completed, then the
  database change might never make it to disk and the next user of the
  database might not see your change.

  You lose Durability with asynchronous I/O, but you still retain the
  other parts of ACID:  Atomic,  Consistent, and Isolated.  Many
  appliations get along fine without the Durablity.

  1.1 How it Works

    Asynchronous I/O works by creating a special SQLite "vfs" structure
    and registering it with sqlite3_vfs_register(). When files opened via 
    this vfs are written to (using the vfs xWrite() method), the data is not 
    written directly to disk, but is placed in the "write-queue" to be
    handled by the background thread.

    When files opened with the asynchronous vfs are read from 
    (using the vfs xRead() method), the data is read from the file on 
    disk and the write-queue, so that from the point of view of
    the vfs reader the xWrite() appears to have already completed.

    The special vfs is registered (and unregistered) by calls to the 
    API functions sqlite3async_initialize() and sqlite3async_shutdown().
    See section "Compilation and Usage" below for details.

  1.2 Limitations

    In order to gain experience with the main ideas surrounding asynchronous 
    IO, this implementation is deliberately kept simple. Additional 
    capabilities may be added in the future.

    For example, as currently implemented, if writes are happening at a 
    steady stream that exceeds the I/O capability of the background writer
    thread, the queue of pending write operations will grow without bound.
    If this goes on for long enough, the host system could run out of memory. 
    A more sophisticated module could to keep track of the quantity of 
    pending writes and stop accepting new write requests when the queue of 
    pending writes grows too large.

  1.3 Locking and Concurrency

    Multiple connections from within a single process that use this
    implementation of asynchronous IO may access a single database
    file concurrently. From the point of view of the user, if all
    connections are from within a single process, there is no difference
    between the concurrency offered by "normal" SQLite and SQLite
    using the asynchronous backend.

    If file-locking is enabled (it is enabled by default), then connections
    from multiple processes may also read and write the database file.
    However concurrency is reduced as follows:

      * When a connection using asynchronous IO begins a database
        transaction, the database is locked immediately. However the
        lock is not released until after all relevant operations
        in the write-queue have been flushed to disk. This means
        (for example) that the database may remain locked for some 
        time after a "COMMIT" or "ROLLBACK" is issued.

      * If an application using asynchronous IO executes transactions
        in quick succession, other database users may be effectively
        locked out of the database. This is because when a BEGIN
        is executed, a database lock is established immediately. But
        when the corresponding COMMIT or ROLLBACK occurs, the lock
        is not released until the relevant part of the write-queue 
        has been flushed through. As a result, if a COMMIT is followed
        by a BEGIN before the write-queue is flushed through, the database 
        is never unlocked,preventing other processes from accessing 
        the database.

    File-locking may be disabled at runtime using the sqlite3async_control()
    API (see below). This may improve performance when an NFS or other 
    network file-system, as the synchronous round-trips to the server be 
    required to establish file locks are avoided. However, if multiple 
    connections attempt to access the same database file when file-locking
    is disabled, application crashes and database corruption is a likely
    outcome.


2. COMPILATION AND USAGE

  The asynchronous IO extension consists of a single file of C code
  (sqlite3async.c), and a header file (sqlite3async.h) that defines the 
  C API used by applications to activate and control the modules 
  functionality.

  To use the asynchronous IO extension, compile sqlite3async.c as
  part of the application that uses SQLite. Then use the API defined
  in sqlite3async.h to initialize and configure the module.

  The asynchronous IO VFS API is described in detail in comments in 
  sqlite3async.h. Using the API usually consists of the following steps:

    1. Register the asynchronous IO VFS with SQLite by calling the
       sqlite3async_initialize() function.

    2. Create a background thread to perform write operations and call
       sqlite3async_run().

    3. Use the normal SQLite API to read and write to databases via 
       the asynchronous IO VFS.

  Refer to sqlite3async.h for details.


3. PORTING

  Currently the asynchronous IO extension is compatible with win32 systems
  and systems that support the pthreads interface, including Mac OSX, Linux, 
  and other varieties of Unix. 

  To port the asynchronous IO extension to another platform, the user must
  implement mutex and condition variable primitives for the new platform.
  Currently there is no externally available interface to allow this, but
  modifying the code within sqlite3async.c to include the new platforms
  concurrency primitives is relatively easy. Search within sqlite3async.c
  for the comment string "PORTING FUNCTIONS" for details. Then implement
  new versions of each of the following:

    static void async_mutex_enter(int eMutex);
    static void async_mutex_leave(int eMutex);
    static void async_cond_wait(int eCond, int eMutex);
    static void async_cond_signal(int eCond);
    static void async_sched_yield(void);

  The functionality required of each of the above functions is described
  in comments in sqlite3async.c.

Added ext/async/sqlite3async.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
/*
** 2005 December 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** $Id: sqlite3async.c,v 1.7 2009/07/18 11:52:04 danielk1977 Exp $
**
** This file contains the implementation of an asynchronous IO backend 
** for SQLite.
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO)

#include "sqlite3async.h"
#include "sqlite3.h"
#include <stdarg.h>
#include <string.h>
#include <assert.h>

/* Useful macros used in several places */
#define MIN(x,y) ((x)<(y)?(x):(y))
#define MAX(x,y) ((x)>(y)?(x):(y))

#ifndef SQLITE_AMALGAMATION
/* Macro to mark parameters as unused and silence compiler warnings. */
#define UNUSED_PARAMETER(x) (void)(x)
#endif

/* Forward references */
typedef struct AsyncWrite AsyncWrite;
typedef struct AsyncFile AsyncFile;
typedef struct AsyncFileData AsyncFileData;
typedef struct AsyncFileLock AsyncFileLock;
typedef struct AsyncLock AsyncLock;

/* Enable for debugging */
#ifndef NDEBUG
#include <stdio.h>
static int sqlite3async_trace = 0;
# define ASYNC_TRACE(X) if( sqlite3async_trace ) asyncTrace X
static void asyncTrace(const char *zFormat, ...){
  char *z;
  va_list ap;
  va_start(ap, zFormat);
  z = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  fprintf(stderr, "[%d] %s", 0 /* (int)pthread_self() */, z);
  sqlite3_free(z);
}
#else
# define ASYNC_TRACE(X)
#endif

/*
** THREAD SAFETY NOTES
**
** Basic rules:
**
**     * Both read and write access to the global write-op queue must be 
**       protected by the async.queueMutex. As are the async.ioError and
**       async.nFile variables.
**
**     * The async.pLock list and all AsyncLock and AsyncFileLock
**       structures must be protected by the async.lockMutex mutex.
**
**     * The file handles from the underlying system are not assumed to 
**       be thread safe.
**
**     * See the last two paragraphs under "The Writer Thread" for
**       an assumption to do with file-handle synchronization by the Os.
**
** Deadlock prevention:
**
**     There are three mutex used by the system: the "writer" mutex, 
**     the "queue" mutex and the "lock" mutex. Rules are:
**
**     * It is illegal to block on the writer mutex when any other mutex
**       are held, and 
**
**     * It is illegal to block on the queue mutex when the lock mutex
**       is held.
**
**     i.e. mutex's must be grabbed in the order "writer", "queue", "lock".
**
** File system operations (invoked by SQLite thread):
**
**     xOpen
**     xDelete
**     xFileExists
**
** File handle operations (invoked by SQLite thread):
**
**         asyncWrite, asyncClose, asyncTruncate, asyncSync 
**    
**     The operations above add an entry to the global write-op list. They
**     prepare the entry, acquire the async.queueMutex momentarily while
**     list pointers are  manipulated to insert the new entry, then release
**     the mutex and signal the writer thread to wake up in case it happens
**     to be asleep.
**
**    
**         asyncRead, asyncFileSize.
**
**     Read operations. Both of these read from both the underlying file
**     first then adjust their result based on pending writes in the 
**     write-op queue.   So async.queueMutex is held for the duration
**     of these operations to prevent other threads from changing the
**     queue in mid operation.
**    
**
**         asyncLock, asyncUnlock, asyncCheckReservedLock
**    
**     These primitives implement in-process locking using a hash table
**     on the file name.  Files are locked correctly for connections coming
**     from the same process.  But other processes cannot see these locks
**     and will therefore not honor them.
**
**
** The writer thread:
**
**     The async.writerMutex is used to make sure only there is only
**     a single writer thread running at a time.
**
**     Inside the writer thread is a loop that works like this:
**
**         WHILE (write-op list is not empty)
**             Do IO operation at head of write-op list
**             Remove entry from head of write-op list
**         END WHILE
**
**     The async.queueMutex is always held during the <write-op list is 
**     not empty> test, and when the entry is removed from the head
**     of the write-op list. Sometimes it is held for the interim
**     period (while the IO is performed), and sometimes it is
**     relinquished. It is relinquished if (a) the IO op is an
**     ASYNC_CLOSE or (b) when the file handle was opened, two of
**     the underlying systems handles were opened on the same
**     file-system entry.
**
**     If condition (b) above is true, then one file-handle 
**     (AsyncFile.pBaseRead) is used exclusively by sqlite threads to read the
**     file, the other (AsyncFile.pBaseWrite) by sqlite3_async_flush() 
**     threads to perform write() operations. This means that read 
**     operations are not blocked by asynchronous writes (although 
**     asynchronous writes may still be blocked by reads).
**
**     This assumes that the OS keeps two handles open on the same file
**     properly in sync. That is, any read operation that starts after a
**     write operation on the same file system entry has completed returns
**     data consistent with the write. We also assume that if one thread 
**     reads a file while another is writing it all bytes other than the
**     ones actually being written contain valid data.
**
**     If the above assumptions are not true, set the preprocessor symbol
**     SQLITE_ASYNC_TWO_FILEHANDLES to 0.
*/


#ifndef NDEBUG
# define TESTONLY( X ) X
#else
# define TESTONLY( X )
#endif

/*
** PORTING FUNCTIONS
**
** There are two definitions of the following functions. One for pthreads
** compatible systems and one for Win32. These functions isolate the OS
** specific code required by each platform.
**
** The system uses three mutexes and a single condition variable. To
** block on a mutex, async_mutex_enter() is called. The parameter passed
** to async_mutex_enter(), which must be one of ASYNC_MUTEX_LOCK,
** ASYNC_MUTEX_QUEUE or ASYNC_MUTEX_WRITER, identifies which of the three
** mutexes to lock. Similarly, to unlock a mutex, async_mutex_leave() is
** called with a parameter identifying the mutex being unlocked. Mutexes
** are not recursive - it is an error to call async_mutex_enter() to
** lock a mutex that is already locked, or to call async_mutex_leave()
** to unlock a mutex that is not currently locked.
**
** The async_cond_wait() and async_cond_signal() functions are modelled
** on the pthreads functions with similar names. The first parameter to
** both functions is always ASYNC_COND_QUEUE. When async_cond_wait()
** is called the mutex identified by the second parameter must be held.
** The mutex is unlocked, and the calling thread simultaneously begins 
** waiting for the condition variable to be signalled by another thread.
** After another thread signals the condition variable, the calling
** thread stops waiting, locks mutex eMutex and returns. The 
** async_cond_signal() function is used to signal the condition variable. 
** It is assumed that the mutex used by the thread calling async_cond_wait() 
** is held by the caller of async_cond_signal() (otherwise there would be 
** a race condition).
**
** It is guaranteed that no other thread will call async_cond_wait() when
** there is already a thread waiting on the condition variable.
**
** The async_sched_yield() function is called to suggest to the operating
** system that it would be a good time to shift the current thread off the
** CPU. The system will still work if this function is not implemented
** (it is not currently implemented for win32), but it might be marginally
** more efficient if it is.
*/
static void async_mutex_enter(int eMutex);
static void async_mutex_leave(int eMutex);
static void async_cond_wait(int eCond, int eMutex);
static void async_cond_signal(int eCond);
static void async_sched_yield(void);

/*
** There are also two definitions of the following. async_os_initialize()
** is called when the asynchronous VFS is first installed, and os_shutdown()
** is called when it is uninstalled (from within sqlite3async_shutdown()).
**
** For pthreads builds, both of these functions are no-ops. For win32,
** they provide an opportunity to initialize and finalize the required
** mutex and condition variables.
**
** If async_os_initialize() returns other than zero, then the initialization
** fails and SQLITE_ERROR is returned to the user.
*/
static int async_os_initialize(void);
static void async_os_shutdown(void);

/* Values for use as the 'eMutex' argument of the above functions. The
** integer values assigned to these constants are important for assert()
** statements that verify that mutexes are locked in the correct order.
** Specifically, it is unsafe to try to lock mutex N while holding a lock 
** on mutex M if (M<=N).
*/
#define ASYNC_MUTEX_LOCK    0
#define ASYNC_MUTEX_QUEUE   1
#define ASYNC_MUTEX_WRITER  2

/* Values for use as the 'eCond' argument of the above functions. */
#define ASYNC_COND_QUEUE    0

/*************************************************************************
** Start of OS specific code.
*/
#if SQLITE_OS_WIN || defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)

#include <windows.h>

/* The following block contains the win32 specific code. */

#define mutex_held(X) (GetCurrentThreadId()==primitives.aHolder[X])

static struct AsyncPrimitives {
  int isInit;
  DWORD aHolder[3];
  CRITICAL_SECTION aMutex[3];
  HANDLE aCond[1];
} primitives = { 0 };

static int async_os_initialize(void){
  if( !primitives.isInit ){
    primitives.aCond[0] = CreateEvent(NULL, TRUE, FALSE, 0);
    if( primitives.aCond[0]==NULL ){
      return 1;
    }
    InitializeCriticalSection(&primitives.aMutex[0]);
    InitializeCriticalSection(&primitives.aMutex[1]);
    InitializeCriticalSection(&primitives.aMutex[2]);
    primitives.isInit = 1;
  }
  return 0;
}
static void async_os_shutdown(void){
  if( primitives.isInit ){
    DeleteCriticalSection(&primitives.aMutex[0]);
    DeleteCriticalSection(&primitives.aMutex[1]);
    DeleteCriticalSection(&primitives.aMutex[2]);
    CloseHandle(primitives.aCond[0]);
    primitives.isInit = 0;
  }
}

/* The following block contains the Win32 specific code. */
static void async_mutex_enter(int eMutex){
  assert( eMutex==0 || eMutex==1 || eMutex==2 );
  assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) );
  assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) );
  assert( eMutex!=0 || (!mutex_held(0)) );
  EnterCriticalSection(&primitives.aMutex[eMutex]);
  TESTONLY( primitives.aHolder[eMutex] = GetCurrentThreadId(); )
}
static void async_mutex_leave(int eMutex){
  assert( eMutex==0 || eMutex==1 || eMutex==2 );
  assert( mutex_held(eMutex) );
  TESTONLY( primitives.aHolder[eMutex] = 0; )
  LeaveCriticalSection(&primitives.aMutex[eMutex]);
}
static void async_cond_wait(int eCond, int eMutex){
  ResetEvent(primitives.aCond[eCond]);
  async_mutex_leave(eMutex);
  WaitForSingleObject(primitives.aCond[eCond], INFINITE);
  async_mutex_enter(eMutex);
}
static void async_cond_signal(int eCond){
  assert( mutex_held(ASYNC_MUTEX_QUEUE) );
  SetEvent(primitives.aCond[eCond]);
}
static void async_sched_yield(void){
  Sleep(0);
}
#else

/* The following block contains the pthreads specific code. */
#include <pthread.h>
#include <sched.h>

#define mutex_held(X) pthread_equal(primitives.aHolder[X], pthread_self())

static int  async_os_initialize(void) {return 0;}
static void async_os_shutdown(void) {}

static struct AsyncPrimitives {
  pthread_mutex_t aMutex[3];
  pthread_cond_t aCond[1];
  pthread_t aHolder[3];
} primitives = {
  { PTHREAD_MUTEX_INITIALIZER, 
    PTHREAD_MUTEX_INITIALIZER, 
    PTHREAD_MUTEX_INITIALIZER
  } , {
    PTHREAD_COND_INITIALIZER
  } , { 0, 0, 0 }
};

static void async_mutex_enter(int eMutex){
  assert( eMutex==0 || eMutex==1 || eMutex==2 );
  assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) );
  assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) );
  assert( eMutex!=0 || (!mutex_held(0)) );
  pthread_mutex_lock(&primitives.aMutex[eMutex]);
  TESTONLY( primitives.aHolder[eMutex] = pthread_self(); )
}
static void async_mutex_leave(int eMutex){
  assert( eMutex==0 || eMutex==1 || eMutex==2 );
  assert( mutex_held(eMutex) );
  TESTONLY( primitives.aHolder[eMutex] = 0; )
  pthread_mutex_unlock(&primitives.aMutex[eMutex]);
}
static void async_cond_wait(int eCond, int eMutex){
  assert( eMutex==0 || eMutex==1 || eMutex==2 );
  assert( mutex_held(eMutex) );
  TESTONLY( primitives.aHolder[eMutex] = 0; )
  pthread_cond_wait(&primitives.aCond[eCond], &primitives.aMutex[eMutex]);
  TESTONLY( primitives.aHolder[eMutex] = pthread_self(); )
}
static void async_cond_signal(int eCond){
  assert( mutex_held(ASYNC_MUTEX_QUEUE) );
  pthread_cond_signal(&primitives.aCond[eCond]);
}
static void async_sched_yield(void){
  sched_yield();
}
#endif
/*
** End of OS specific code.
*************************************************************************/

#define assert_mutex_is_held(X) assert( mutex_held(X) )


#ifndef SQLITE_ASYNC_TWO_FILEHANDLES
/* #define SQLITE_ASYNC_TWO_FILEHANDLES 0 */
#define SQLITE_ASYNC_TWO_FILEHANDLES 1
#endif

/*
** State information is held in the static variable "async" defined
** as the following structure.
**
** Both async.ioError and async.nFile are protected by async.queueMutex.
*/
static struct TestAsyncStaticData {
  AsyncWrite *pQueueFirst;     /* Next write operation to be processed */
  AsyncWrite *pQueueLast;      /* Last write operation on the list */
  AsyncLock *pLock;            /* Linked list of all AsyncLock structures */
  volatile int ioDelay;        /* Extra delay between write operations */
  volatile int eHalt;          /* One of the SQLITEASYNC_HALT_XXX values */
  volatile int bLockFiles;     /* Current value of "lockfiles" parameter */
  int ioError;                 /* True if an IO error has occurred */
  int nFile;                   /* Number of open files (from sqlite pov) */
} async = { 0,0,0,0,0,1,0,0 };

/* Possible values of AsyncWrite.op */
#define ASYNC_NOOP          0
#define ASYNC_WRITE         1
#define ASYNC_SYNC          2
#define ASYNC_TRUNCATE      3
#define ASYNC_CLOSE         4
#define ASYNC_DELETE        5
#define ASYNC_OPENEXCLUSIVE 6
#define ASYNC_UNLOCK        7

/* Names of opcodes.  Used for debugging only.
** Make sure these stay in sync with the macros above!
*/
static const char *azOpcodeName[] = {
  "NOOP", "WRITE", "SYNC", "TRUNCATE", "CLOSE", "DELETE", "OPENEX", "UNLOCK"
};

/*
** Entries on the write-op queue are instances of the AsyncWrite
** structure, defined here.
**
** The interpretation of the iOffset and nByte variables varies depending 
** on the value of AsyncWrite.op:
**
** ASYNC_NOOP:
**     No values used.
**
** ASYNC_WRITE:
**     iOffset -> Offset in file to write to.
**     nByte   -> Number of bytes of data to write (pointed to by zBuf).
**
** ASYNC_SYNC:
**     nByte   -> flags to pass to sqlite3OsSync().
**
** ASYNC_TRUNCATE:
**     iOffset -> Size to truncate file to.
**     nByte   -> Unused.
**
** ASYNC_CLOSE:
**     iOffset -> Unused.
**     nByte   -> Unused.
**
** ASYNC_DELETE:
**     iOffset -> Contains the "syncDir" flag.
**     nByte   -> Number of bytes of zBuf points to (file name).
**
** ASYNC_OPENEXCLUSIVE:
**     iOffset -> Value of "delflag".
**     nByte   -> Number of bytes of zBuf points to (file name).
**
** ASYNC_UNLOCK:
**     nByte   -> Argument to sqlite3OsUnlock().
**
**
** For an ASYNC_WRITE operation, zBuf points to the data to write to the file. 
** This space is sqlite3_malloc()d along with the AsyncWrite structure in a
** single blob, so is deleted when sqlite3_free() is called on the parent 
** structure.
*/
struct AsyncWrite {
  AsyncFileData *pFileData;    /* File to write data to or sync */
  int op;                      /* One of ASYNC_xxx etc. */
  sqlite_int64 iOffset;        /* See above */
  int nByte;          /* See above */
  char *zBuf;         /* Data to write to file (or NULL if op!=ASYNC_WRITE) */
  AsyncWrite *pNext;  /* Next write operation (to any file) */
};

/*
** An instance of this structure is created for each distinct open file 
** (i.e. if two handles are opened on the one file, only one of these
** structures is allocated) and stored in the async.aLock hash table. The
** keys for async.aLock are the full pathnames of the opened files.
**
** AsyncLock.pList points to the head of a linked list of AsyncFileLock
** structures, one for each handle currently open on the file.
**
** If the opened file is not a main-database (the SQLITE_OPEN_MAIN_DB is
** not passed to the sqlite3OsOpen() call), or if async.bLockFiles is 
** false, variables AsyncLock.pFile and AsyncLock.eLock are never used. 
** Otherwise, pFile is a file handle opened on the file in question and 
** used to obtain the file-system locks required by database connections 
** within this process.
**
** See comments above the asyncLock() function for more details on 
** the implementation of database locking used by this backend.
*/
struct AsyncLock {
  char *zFile;
  int nFile;
  sqlite3_file *pFile;
  int eLock;
  AsyncFileLock *pList;
  AsyncLock *pNext;           /* Next in linked list headed by async.pLock */
};

/*
** An instance of the following structure is allocated along with each
** AsyncFileData structure (see AsyncFileData.lock), but is only used if the
** file was opened with the SQLITE_OPEN_MAIN_DB.
*/
struct AsyncFileLock {
  int eLock;                /* Internally visible lock state (sqlite pov) */
  int eAsyncLock;           /* Lock-state with write-queue unlock */
  AsyncFileLock *pNext;
};

/* 
** The AsyncFile structure is a subclass of sqlite3_file used for 
** asynchronous IO. 
**
** All of the actual data for the structure is stored in the structure
** pointed to by AsyncFile.pData, which is allocated as part of the
** sqlite3OsOpen() using sqlite3_malloc(). The reason for this is that the
** lifetime of the AsyncFile structure is ended by the caller after OsClose()
** is called, but the data in AsyncFileData may be required by the
** writer thread after that point.
*/
struct AsyncFile {
  sqlite3_io_methods *pMethod;
  AsyncFileData *pData;
};
struct AsyncFileData {
  char *zName;               /* Underlying OS filename - used for debugging */
  int nName;                 /* Number of characters in zName */
  sqlite3_file *pBaseRead;   /* Read handle to the underlying Os file */
  sqlite3_file *pBaseWrite;  /* Write handle to the underlying Os file */
  AsyncFileLock lock;        /* Lock state for this handle */
  AsyncLock *pLock;          /* AsyncLock object for this file system entry */
  AsyncWrite closeOp;        /* Preallocated close operation */
};

/*
** Add an entry to the end of the global write-op list. pWrite should point 
** to an AsyncWrite structure allocated using sqlite3_malloc().  The writer
** thread will call sqlite3_free() to free the structure after the specified
** operation has been completed.
**
** Once an AsyncWrite structure has been added to the list, it becomes the
** property of the writer thread and must not be read or modified by the
** caller.  
*/
static void addAsyncWrite(AsyncWrite *pWrite){
  /* We must hold the queue mutex in order to modify the queue pointers */
  if( pWrite->op!=ASYNC_UNLOCK ){
    async_mutex_enter(ASYNC_MUTEX_QUEUE);
  }

  /* Add the record to the end of the write-op queue */
  assert( !pWrite->pNext );
  if( async.pQueueLast ){
    assert( async.pQueueFirst );
    async.pQueueLast->pNext = pWrite;
  }else{
    async.pQueueFirst = pWrite;
  }
  async.pQueueLast = pWrite;
  ASYNC_TRACE(("PUSH %p (%s %s %d)\n", pWrite, azOpcodeName[pWrite->op],
         pWrite->pFileData ? pWrite->pFileData->zName : "-", pWrite->iOffset));

  if( pWrite->op==ASYNC_CLOSE ){
    async.nFile--;
  }

  /* The writer thread might have been idle because there was nothing
  ** on the write-op queue for it to do.  So wake it up. */
  async_cond_signal(ASYNC_COND_QUEUE);

  /* Drop the queue mutex */
  if( pWrite->op!=ASYNC_UNLOCK ){
    async_mutex_leave(ASYNC_MUTEX_QUEUE);
  }
}

/*
** Increment async.nFile in a thread-safe manner.
*/
static void incrOpenFileCount(void){
  /* We must hold the queue mutex in order to modify async.nFile */
  async_mutex_enter(ASYNC_MUTEX_QUEUE);
  if( async.nFile==0 ){
    async.ioError = SQLITE_OK;
  }
  async.nFile++;
  async_mutex_leave(ASYNC_MUTEX_QUEUE);
}

/*
** This is a utility function to allocate and populate a new AsyncWrite
** structure and insert it (via addAsyncWrite() ) into the global list.
*/
static int addNewAsyncWrite(
  AsyncFileData *pFileData, 
  int op, 
  sqlite3_int64 iOffset, 
  int nByte,
  const char *zByte
){
  AsyncWrite *p;
  if( op!=ASYNC_CLOSE && async.ioError ){
    return async.ioError;
  }
  p = sqlite3_malloc(sizeof(AsyncWrite) + (zByte?nByte:0));
  if( !p ){
    /* The upper layer does not expect operations like OsWrite() to
    ** return SQLITE_NOMEM. This is partly because under normal conditions
    ** SQLite is required to do rollback without calling malloc(). So
    ** if malloc() fails here, treat it as an I/O error. The above
    ** layer knows how to handle that.
    */
    return SQLITE_IOERR;
  }
  p->op = op;
  p->iOffset = iOffset;
  p->nByte = nByte;
  p->pFileData = pFileData;
  p->pNext = 0;
  if( zByte ){
    p->zBuf = (char *)&p[1];
    memcpy(p->zBuf, zByte, nByte);
  }else{
    p->zBuf = 0;
  }
  addAsyncWrite(p);
  return SQLITE_OK;
}

/*
** Close the file. This just adds an entry to the write-op list, the file is
** not actually closed.
*/
static int asyncClose(sqlite3_file *pFile){
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;

  /* Unlock the file, if it is locked */
  async_mutex_enter(ASYNC_MUTEX_LOCK);
  p->lock.eLock = 0;
  async_mutex_leave(ASYNC_MUTEX_LOCK);

  addAsyncWrite(&p->closeOp);
  return SQLITE_OK;
}

/*
** Implementation of sqlite3OsWrite() for asynchronous files. Instead of 
** writing to the underlying file, this function adds an entry to the end of
** the global AsyncWrite list. Either SQLITE_OK or SQLITE_NOMEM may be
** returned.
*/
static int asyncWrite(
  sqlite3_file *pFile, 
  const void *pBuf, 
  int amt, 
  sqlite3_int64 iOff
){
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  return addNewAsyncWrite(p, ASYNC_WRITE, iOff, amt, pBuf);
}

/*
** Read data from the file. First we read from the filesystem, then adjust 
** the contents of the buffer based on ASYNC_WRITE operations in the 
** write-op queue.
**
** This method holds the mutex from start to finish.
*/
static int asyncRead(
  sqlite3_file *pFile, 
  void *zOut, 
  int iAmt, 
  sqlite3_int64 iOffset
){
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  int rc = SQLITE_OK;
  sqlite3_int64 filesize;
  sqlite3_file *pBase = p->pBaseRead;
  sqlite3_int64 iAmt64 = (sqlite3_int64)iAmt;

  /* Grab the write queue mutex for the duration of the call */
  async_mutex_enter(ASYNC_MUTEX_QUEUE);

  /* If an I/O error has previously occurred in this virtual file 
  ** system, then all subsequent operations fail.
  */
  if( async.ioError!=SQLITE_OK ){
    rc = async.ioError;
    goto asyncread_out;
  }

  if( pBase->pMethods ){
    sqlite3_int64 nRead;
    rc = pBase->pMethods->xFileSize(pBase, &filesize);
    if( rc!=SQLITE_OK ){
      goto asyncread_out;
    }
    nRead = MIN(filesize - iOffset, iAmt64);
    if( nRead>0 ){
      rc = pBase->pMethods->xRead(pBase, zOut, nRead, iOffset);
      ASYNC_TRACE(("READ %s %d bytes at %d\n", p->zName, nRead, iOffset));
    }
  }

  if( rc==SQLITE_OK ){
    AsyncWrite *pWrite;
    char *zName = p->zName;

    for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){
      if( pWrite->op==ASYNC_WRITE && (
        (pWrite->pFileData==p) ||
        (zName && pWrite->pFileData->zName==zName)
      )){
        sqlite3_int64 nCopy;
        sqlite3_int64 nByte64 = (sqlite3_int64)pWrite->nByte;

        /* Set variable iBeginIn to the offset in buffer pWrite->zBuf[] from
        ** which data should be copied. Set iBeginOut to the offset within
        ** the output buffer to which data should be copied. If either of
        ** these offsets is a negative number, set them to 0.
        */
        sqlite3_int64 iBeginOut = (pWrite->iOffset-iOffset);
        sqlite3_int64 iBeginIn = -iBeginOut;
        if( iBeginIn<0 ) iBeginIn = 0;
        if( iBeginOut<0 ) iBeginOut = 0;

        nCopy = MIN(nByte64-iBeginIn, iAmt64-iBeginOut);
        if( nCopy>0 ){
          memcpy(&((char *)zOut)[iBeginOut], &pWrite->zBuf[iBeginIn], nCopy);
          ASYNC_TRACE(("OVERREAD %d bytes at %d\n", nCopy, iBeginOut+iOffset));
        }
      }
    }
  }

asyncread_out:
  async_mutex_leave(ASYNC_MUTEX_QUEUE);
  return rc;
}

/*
** Truncate the file to nByte bytes in length. This just adds an entry to 
** the write-op list, no IO actually takes place.
*/
static int asyncTruncate(sqlite3_file *pFile, sqlite3_int64 nByte){
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  return addNewAsyncWrite(p, ASYNC_TRUNCATE, nByte, 0, 0);
}

/*
** Sync the file. This just adds an entry to the write-op list, the 
** sync() is done later by sqlite3_async_flush().
*/
static int asyncSync(sqlite3_file *pFile, int flags){
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  return addNewAsyncWrite(p, ASYNC_SYNC, 0, flags, 0);
}

/*
** Read the size of the file. First we read the size of the file system 
** entry, then adjust for any ASYNC_WRITE or ASYNC_TRUNCATE operations 
** currently in the write-op list. 
**
** This method holds the mutex from start to finish.
*/
int asyncFileSize(sqlite3_file *pFile, sqlite3_int64 *piSize){
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  int rc = SQLITE_OK;
  sqlite3_int64 s = 0;
  sqlite3_file *pBase;

  async_mutex_enter(ASYNC_MUTEX_QUEUE);

  /* Read the filesystem size from the base file. If pMethods is NULL, this
  ** means the file hasn't been opened yet. In this case all relevant data 
  ** must be in the write-op queue anyway, so we can omit reading from the
  ** file-system.
  */
  pBase = p->pBaseRead;
  if( pBase->pMethods ){
    rc = pBase->pMethods->xFileSize(pBase, &s);
  }

  if( rc==SQLITE_OK ){
    AsyncWrite *pWrite;
    for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){
      if( pWrite->op==ASYNC_DELETE 
       && p->zName 
       && strcmp(p->zName, pWrite->zBuf)==0 
      ){
        s = 0;
      }else if( pWrite->pFileData && (
          (pWrite->pFileData==p) 
       || (p->zName && pWrite->pFileData->zName==p->zName) 
      )){
        switch( pWrite->op ){
          case ASYNC_WRITE:
            s = MAX(pWrite->iOffset + (sqlite3_int64)(pWrite->nByte), s);
            break;
          case ASYNC_TRUNCATE:
            s = MIN(s, pWrite->iOffset);
            break;
        }
      }
    }
    *piSize = s;
  }
  async_mutex_leave(ASYNC_MUTEX_QUEUE);
  return rc;
}

/*
** Lock or unlock the actual file-system entry.
*/
static int getFileLock(AsyncLock *pLock){
  int rc = SQLITE_OK;
  AsyncFileLock *pIter;
  int eRequired = 0;

  if( pLock->pFile ){
    for(pIter=pLock->pList; pIter; pIter=pIter->pNext){
      assert(pIter->eAsyncLock>=pIter->eLock);
      if( pIter->eAsyncLock>eRequired ){
        eRequired = pIter->eAsyncLock;
        assert(eRequired>=0 && eRequired<=SQLITE_LOCK_EXCLUSIVE);
      }
    }

    if( eRequired>pLock->eLock ){
      rc = pLock->pFile->pMethods->xLock(pLock->pFile, eRequired);
      if( rc==SQLITE_OK ){
        pLock->eLock = eRequired;
      }
    }
    else if( eRequired<pLock->eLock && eRequired<=SQLITE_LOCK_SHARED ){
      rc = pLock->pFile->pMethods->xUnlock(pLock->pFile, eRequired);
      if( rc==SQLITE_OK ){
        pLock->eLock = eRequired;
      }
    }
  }

  return rc;
}

/*
** Return the AsyncLock structure from the global async.pLock list 
** associated with the file-system entry identified by path zName 
** (a string of nName bytes). If no such structure exists, return 0.
*/
static AsyncLock *findLock(const char *zName, int nName){
  AsyncLock *p = async.pLock;
  while( p && (p->nFile!=nName || memcmp(p->zFile, zName, nName)) ){
    p = p->pNext;
  }
  return p;
}

/*
** The following two methods - asyncLock() and asyncUnlock() - are used
** to obtain and release locks on database files opened with the
** asynchronous backend.
*/
static int asyncLock(sqlite3_file *pFile, int eLock){
  int rc = SQLITE_OK;
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;

  if( p->zName ){
    async_mutex_enter(ASYNC_MUTEX_LOCK);
    if( p->lock.eLock<eLock ){
      AsyncLock *pLock = p->pLock;
      AsyncFileLock *pIter;
      assert(pLock && pLock->pList);
      for(pIter=pLock->pList; pIter; pIter=pIter->pNext){
        if( pIter!=&p->lock && (
          (eLock==SQLITE_LOCK_EXCLUSIVE && pIter->eLock>=SQLITE_LOCK_SHARED) ||
          (eLock==SQLITE_LOCK_PENDING && pIter->eLock>=SQLITE_LOCK_RESERVED) ||
          (eLock==SQLITE_LOCK_RESERVED && pIter->eLock>=SQLITE_LOCK_RESERVED) ||
          (eLock==SQLITE_LOCK_SHARED && pIter->eLock>=SQLITE_LOCK_PENDING)
        )){
          rc = SQLITE_BUSY;
        }
      }
      if( rc==SQLITE_OK ){
        p->lock.eLock = eLock;
        p->lock.eAsyncLock = MAX(p->lock.eAsyncLock, eLock);
      }
      assert(p->lock.eAsyncLock>=p->lock.eLock);
      if( rc==SQLITE_OK ){
        rc = getFileLock(pLock);
      }
    }
    async_mutex_leave(ASYNC_MUTEX_LOCK);
  }

  ASYNC_TRACE(("LOCK %d (%s) rc=%d\n", eLock, p->zName, rc));
  return rc;
}
static int asyncUnlock(sqlite3_file *pFile, int eLock){
  int rc = SQLITE_OK;
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  if( p->zName ){
    AsyncFileLock *pLock = &p->lock;
    async_mutex_enter(ASYNC_MUTEX_QUEUE);
    async_mutex_enter(ASYNC_MUTEX_LOCK);
    pLock->eLock = MIN(pLock->eLock, eLock);
    rc = addNewAsyncWrite(p, ASYNC_UNLOCK, 0, eLock, 0);
    async_mutex_leave(ASYNC_MUTEX_LOCK);
    async_mutex_leave(ASYNC_MUTEX_QUEUE);
  }
  return rc;
}

/*
** This function is called when the pager layer first opens a database file
** and is checking for a hot-journal.
*/
static int asyncCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  int ret = 0;
  AsyncFileLock *pIter;
  AsyncFileData *p = ((AsyncFile *)pFile)->pData;

  async_mutex_enter(ASYNC_MUTEX_LOCK);
  for(pIter=p->pLock->pList; pIter; pIter=pIter->pNext){
    if( pIter->eLock>=SQLITE_LOCK_RESERVED ){
      ret = 1;
      break;
    }
  }
  async_mutex_leave(ASYNC_MUTEX_LOCK);

  ASYNC_TRACE(("CHECK-LOCK %d (%s)\n", ret, p->zName));
  *pResOut = ret;
  return SQLITE_OK;
}

/* 
** sqlite3_file_control() implementation.
*/
static int asyncFileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_FCNTL_LOCKSTATE: {
      async_mutex_enter(ASYNC_MUTEX_LOCK);
      *(int*)pArg = ((AsyncFile*)id)->pData->lock.eLock;
      async_mutex_leave(ASYNC_MUTEX_LOCK);
      return SQLITE_OK;
    }
  }
  return SQLITE_ERROR;
}

/* 
** Return the device characteristics and sector-size of the device. It
** is tricky to implement these correctly, as this backend might 
** not have an open file handle at this point.
*/
static int asyncSectorSize(sqlite3_file *pFile){
  UNUSED_PARAMETER(pFile);
  return 512;
}
static int asyncDeviceCharacteristics(sqlite3_file *pFile){
  UNUSED_PARAMETER(pFile);
  return 0;
}

static int unlinkAsyncFile(AsyncFileData *pData){
  AsyncFileLock **ppIter;
  int rc = SQLITE_OK;

  if( pData->zName ){
    AsyncLock *pLock = pData->pLock;
    for(ppIter=&pLock->pList; *ppIter; ppIter=&((*ppIter)->pNext)){
      if( (*ppIter)==&pData->lock ){
        *ppIter = pData->lock.pNext;
        break;
      }
    }
    if( !pLock->pList ){
      AsyncLock **pp;
      if( pLock->pFile ){
        pLock->pFile->pMethods->xClose(pLock->pFile);
      }
      for(pp=&async.pLock; *pp!=pLock; pp=&((*pp)->pNext));
      *pp = pLock->pNext;
      sqlite3_free(pLock);
    }else{
      rc = getFileLock(pLock);
    }
  }

  return rc;
}

/*
** The parameter passed to this function is a copy of a 'flags' parameter
** passed to this modules xOpen() method. This function returns true
** if the file should be opened asynchronously, or false if it should
** be opened immediately.
**
** If the file is to be opened asynchronously, then asyncOpen() will add
** an entry to the event queue and the file will not actually be opened
** until the event is processed. Otherwise, the file is opened directly
** by the caller.
*/
static int doAsynchronousOpen(int flags){
  return (flags&SQLITE_OPEN_CREATE) && (
      (flags&SQLITE_OPEN_MAIN_JOURNAL) ||
      (flags&SQLITE_OPEN_TEMP_JOURNAL) ||
      (flags&SQLITE_OPEN_DELETEONCLOSE)
  );
}

/*
** Open a file.
*/
static int asyncOpen(
  sqlite3_vfs *pAsyncVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  static sqlite3_io_methods async_methods = {
    1,                               /* iVersion */
    asyncClose,                      /* xClose */
    asyncRead,                       /* xRead */
    asyncWrite,                      /* xWrite */
    asyncTruncate,                   /* xTruncate */
    asyncSync,                       /* xSync */
    asyncFileSize,                   /* xFileSize */
    asyncLock,                       /* xLock */
    asyncUnlock,                     /* xUnlock */
    asyncCheckReservedLock,          /* xCheckReservedLock */
    asyncFileControl,                /* xFileControl */
    asyncSectorSize,                 /* xSectorSize */
    asyncDeviceCharacteristics       /* xDeviceCharacteristics */
  };

  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  AsyncFile *p = (AsyncFile *)pFile;
  int nName = 0;
  int rc = SQLITE_OK;
  int nByte;
  AsyncFileData *pData;
  AsyncLock *pLock = 0;
  char *z;
  int isAsyncOpen = doAsynchronousOpen(flags);

  /* If zName is NULL, then the upper layer is requesting an anonymous file */
  if( zName ){
    nName = (int)strlen(zName)+1;
  }

  nByte = (
    sizeof(AsyncFileData) +        /* AsyncFileData structure */
    2 * pVfs->szOsFile +           /* AsyncFileData.pBaseRead and pBaseWrite */
    nName                          /* AsyncFileData.zName */
  ); 
  z = sqlite3_malloc(nByte);
  if( !z ){
    return SQLITE_NOMEM;
  }
  memset(z, 0, nByte);
  pData = (AsyncFileData*)z;
  z += sizeof(pData[0]);
  pData->pBaseRead = (sqlite3_file*)z;
  z += pVfs->szOsFile;
  pData->pBaseWrite = (sqlite3_file*)z;
  pData->closeOp.pFileData = pData;
  pData->closeOp.op = ASYNC_CLOSE;

  if( zName ){
    z += pVfs->szOsFile;
    pData->zName = z;
    pData->nName = nName;
    memcpy(pData->zName, zName, nName);
  }

  if( !isAsyncOpen ){
    int flagsout;
    rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, &flagsout);
    if( rc==SQLITE_OK 
     && (flagsout&SQLITE_OPEN_READWRITE) 
     && (flags&SQLITE_OPEN_EXCLUSIVE)==0
    ){
      rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseWrite, flags, 0);
    }
    if( pOutFlags ){
      *pOutFlags = flagsout;
    }
  }

  async_mutex_enter(ASYNC_MUTEX_LOCK);

  if( zName && rc==SQLITE_OK ){
    pLock = findLock(pData->zName, pData->nName);
    if( !pLock ){
      int nByte = pVfs->szOsFile + sizeof(AsyncLock) + pData->nName + 1; 
      pLock = (AsyncLock *)sqlite3_malloc(nByte);
      if( pLock ){
        memset(pLock, 0, nByte);
        if( async.bLockFiles && (flags&SQLITE_OPEN_MAIN_DB) ){
          pLock->pFile = (sqlite3_file *)&pLock[1];
          rc = pVfs->xOpen(pVfs, pData->zName, pLock->pFile, flags, 0);
          if( rc!=SQLITE_OK ){
            sqlite3_free(pLock);
            pLock = 0;
          }
        }
        if( pLock ){
          pLock->nFile = pData->nName;
          pLock->zFile = &((char *)(&pLock[1]))[pVfs->szOsFile];
          memcpy(pLock->zFile, pData->zName, pLock->nFile);
          pLock->pNext = async.pLock;
          async.pLock = pLock;
        }
      }else{
        rc = SQLITE_NOMEM;
      }
    }
  }

  if( rc==SQLITE_OK ){
    p->pMethod = &async_methods;
    p->pData = pData;

    /* Link AsyncFileData.lock into the linked list of 
    ** AsyncFileLock structures for this file.
    */
    if( zName ){
      pData->lock.pNext = pLock->pList;
      pLock->pList = &pData->lock;
      pData->zName = pLock->zFile;
    }
  }else{
    if( pData->pBaseRead->pMethods ){
      pData->pBaseRead->pMethods->xClose(pData->pBaseRead);
    }
    if( pData->pBaseWrite->pMethods ){
      pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite);
    }
    sqlite3_free(pData);
  }

  async_mutex_leave(ASYNC_MUTEX_LOCK);

  if( rc==SQLITE_OK ){
    incrOpenFileCount();
    pData->pLock = pLock;
  }

  if( rc==SQLITE_OK && isAsyncOpen ){
    rc = addNewAsyncWrite(pData, ASYNC_OPENEXCLUSIVE, (sqlite3_int64)flags,0,0);
    if( rc==SQLITE_OK ){
      if( pOutFlags ) *pOutFlags = flags;
    }else{
      async_mutex_enter(ASYNC_MUTEX_LOCK);
      unlinkAsyncFile(pData);
      async_mutex_leave(ASYNC_MUTEX_LOCK);
      sqlite3_free(pData);
    }
  }
  if( rc!=SQLITE_OK ){
    p->pMethod = 0;
  }
  return rc;
}

/*
** Implementation of sqlite3OsDelete. Add an entry to the end of the 
** write-op queue to perform the delete.
*/
static int asyncDelete(sqlite3_vfs *pAsyncVfs, const char *z, int syncDir){
  UNUSED_PARAMETER(pAsyncVfs);
  return addNewAsyncWrite(0, ASYNC_DELETE, syncDir, (int)strlen(z)+1, z);
}

/*
** Implementation of sqlite3OsAccess. This method holds the mutex from
** start to finish.
*/
static int asyncAccess(
  sqlite3_vfs *pAsyncVfs, 
  const char *zName, 
  int flags,
  int *pResOut
){
  int rc;
  int ret;
  AsyncWrite *p;
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;

  assert(flags==SQLITE_ACCESS_READWRITE 
      || flags==SQLITE_ACCESS_READ 
      || flags==SQLITE_ACCESS_EXISTS 
  );

  async_mutex_enter(ASYNC_MUTEX_QUEUE);
  rc = pVfs->xAccess(pVfs, zName, flags, &ret);
  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
    for(p=async.pQueueFirst; p; p = p->pNext){
      if( p->op==ASYNC_DELETE && 0==strcmp(p->zBuf, zName) ){
        ret = 0;
      }else if( p->op==ASYNC_OPENEXCLUSIVE 
             && p->pFileData->zName
             && 0==strcmp(p->pFileData->zName, zName) 
      ){
        ret = 1;
      }
    }
  }
  ASYNC_TRACE(("ACCESS(%s): %s = %d\n", 
    flags==SQLITE_ACCESS_READWRITE?"read-write":
    flags==SQLITE_ACCESS_READ?"read":"exists"
    , zName, ret)
  );
  async_mutex_leave(ASYNC_MUTEX_QUEUE);
  *pResOut = ret;
  return rc;
}

/*
** Fill in zPathOut with the full path to the file identified by zPath.
*/
static int asyncFullPathname(
  sqlite3_vfs *pAsyncVfs, 
  const char *zPath, 
  int nPathOut,
  char *zPathOut
){
  int rc;
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  rc = pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);

  /* Because of the way intra-process file locking works, this backend
  ** needs to return a canonical path. The following block assumes the
  ** file-system uses unix style paths. 
  */
  if( rc==SQLITE_OK ){
    int i, j;
    int n = nPathOut;
    char *z = zPathOut;
    while( n>1 && z[n-1]=='/' ){ n--; }
    for(i=j=0; i<n; i++){
      if( z[i]=='/' ){
        if( z[i+1]=='/' ) continue;
        if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
          i += 1;
          continue;
        }
        if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
          while( j>0 && z[j-1]!='/' ){ j--; }
          if( j>0 ){ j--; }
          i += 2;
          continue;
        }
      }
      z[j++] = z[i];
    }
    z[j] = 0;
  }

  return rc;
}
static void *asyncDlOpen(sqlite3_vfs *pAsyncVfs, const char *zPath){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  return pVfs->xDlOpen(pVfs, zPath);
}
static void asyncDlError(sqlite3_vfs *pAsyncVfs, int nByte, char *zErrMsg){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  pVfs->xDlError(pVfs, nByte, zErrMsg);
}
static void (*asyncDlSym(
  sqlite3_vfs *pAsyncVfs, 
  void *pHandle, 
  const char *zSymbol
))(void){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  return pVfs->xDlSym(pVfs, pHandle, zSymbol);
}
static void asyncDlClose(sqlite3_vfs *pAsyncVfs, void *pHandle){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  pVfs->xDlClose(pVfs, pHandle);
}
static int asyncRandomness(sqlite3_vfs *pAsyncVfs, int nByte, char *zBufOut){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  return pVfs->xRandomness(pVfs, nByte, zBufOut);
}
static int asyncSleep(sqlite3_vfs *pAsyncVfs, int nMicro){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  return pVfs->xSleep(pVfs, nMicro);
}
static int asyncCurrentTime(sqlite3_vfs *pAsyncVfs, double *pTimeOut){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  return pVfs->xCurrentTime(pVfs, pTimeOut);
}

static sqlite3_vfs async_vfs = {
  1,                    /* iVersion */
  sizeof(AsyncFile),    /* szOsFile */
  0,                    /* mxPathname */
  0,                    /* pNext */
  SQLITEASYNC_VFSNAME,  /* zName */
  0,                    /* pAppData */
  asyncOpen,            /* xOpen */
  asyncDelete,          /* xDelete */
  asyncAccess,          /* xAccess */
  asyncFullPathname,    /* xFullPathname */
  asyncDlOpen,          /* xDlOpen */
  asyncDlError,         /* xDlError */
  asyncDlSym,           /* xDlSym */
  asyncDlClose,         /* xDlClose */
  asyncRandomness,      /* xDlError */
  asyncSleep,           /* xDlSym */
  asyncCurrentTime      /* xDlClose */
};

/* 
** This procedure runs in a separate thread, reading messages off of the
** write queue and processing them one by one.  
**
** If async.writerHaltNow is true, then this procedure exits
** after processing a single message.
**
** If async.writerHaltWhenIdle is true, then this procedure exits when
** the write queue is empty.
**
** If both of the above variables are false, this procedure runs
** indefinately, waiting for operations to be added to the write queue
** and processing them in the order in which they arrive.
**
** An artifical delay of async.ioDelay milliseconds is inserted before
** each write operation in order to simulate the effect of a slow disk.
**
** Only one instance of this procedure may be running at a time.
*/
static void asyncWriterThread(void){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)(async_vfs.pAppData);
  AsyncWrite *p = 0;
  int rc = SQLITE_OK;
  int holdingMutex = 0;

  async_mutex_enter(ASYNC_MUTEX_WRITER);

  while( async.eHalt!=SQLITEASYNC_HALT_NOW ){
    int doNotFree = 0;
    sqlite3_file *pBase = 0;

    if( !holdingMutex ){
      async_mutex_enter(ASYNC_MUTEX_QUEUE);
    }
    while( (p = async.pQueueFirst)==0 ){
      if( async.eHalt!=SQLITEASYNC_HALT_NEVER ){
        async_mutex_leave(ASYNC_MUTEX_QUEUE);
        break;
      }else{
        ASYNC_TRACE(("IDLE\n"));
        async_cond_wait(ASYNC_COND_QUEUE, ASYNC_MUTEX_QUEUE);
        ASYNC_TRACE(("WAKEUP\n"));
      }
    }
    if( p==0 ) break;
    holdingMutex = 1;

    /* Right now this thread is holding the mutex on the write-op queue.
    ** Variable 'p' points to the first entry in the write-op queue. In
    ** the general case, we hold on to the mutex for the entire body of
    ** the loop. 
    **
    ** However in the cases enumerated below, we relinquish the mutex,
    ** perform the IO, and then re-request the mutex before removing 'p' from
    ** the head of the write-op queue. The idea is to increase concurrency with
    ** sqlite threads.
    **
    **     * An ASYNC_CLOSE operation.
    **     * An ASYNC_OPENEXCLUSIVE operation. For this one, we relinquish 
    **       the mutex, call the underlying xOpenExclusive() function, then
    **       re-aquire the mutex before seting the AsyncFile.pBaseRead 
    **       variable.
    **     * ASYNC_SYNC and ASYNC_WRITE operations, if 
    **       SQLITE_ASYNC_TWO_FILEHANDLES was set at compile time and two
    **       file-handles are open for the particular file being "synced".
    */
    if( async.ioError!=SQLITE_OK && p->op!=ASYNC_CLOSE ){
      p->op = ASYNC_NOOP;
    }
    if( p->pFileData ){
      pBase = p->pFileData->pBaseWrite;
      if( 
        p->op==ASYNC_CLOSE || 
        p->op==ASYNC_OPENEXCLUSIVE ||
        (pBase->pMethods && (p->op==ASYNC_SYNC || p->op==ASYNC_WRITE) ) 
      ){
        async_mutex_leave(ASYNC_MUTEX_QUEUE);
        holdingMutex = 0;
      }
      if( !pBase->pMethods ){
        pBase = p->pFileData->pBaseRead;
      }
    }

    switch( p->op ){
      case ASYNC_NOOP:
        break;

      case ASYNC_WRITE:
        assert( pBase );
        ASYNC_TRACE(("WRITE %s %d bytes at %d\n",
                p->pFileData->zName, p->nByte, p->iOffset));
        rc = pBase->pMethods->xWrite(pBase, (void *)(p->zBuf), p->nByte, p->iOffset);
        break;

      case ASYNC_SYNC:
        assert( pBase );
        ASYNC_TRACE(("SYNC %s\n", p->pFileData->zName));
        rc = pBase->pMethods->xSync(pBase, p->nByte);
        break;

      case ASYNC_TRUNCATE:
        assert( pBase );
        ASYNC_TRACE(("TRUNCATE %s to %d bytes\n", 
                p->pFileData->zName, p->iOffset));
        rc = pBase->pMethods->xTruncate(pBase, p->iOffset);
        break;

      case ASYNC_CLOSE: {
        AsyncFileData *pData = p->pFileData;
        ASYNC_TRACE(("CLOSE %s\n", p->pFileData->zName));
        if( pData->pBaseWrite->pMethods ){
          pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite);
        }
        if( pData->pBaseRead->pMethods ){
          pData->pBaseRead->pMethods->xClose(pData->pBaseRead);
        }

        /* Unlink AsyncFileData.lock from the linked list of AsyncFileLock 
        ** structures for this file. Obtain the async.lockMutex mutex 
        ** before doing so.
        */
        async_mutex_enter(ASYNC_MUTEX_LOCK);
        rc = unlinkAsyncFile(pData);
        async_mutex_leave(ASYNC_MUTEX_LOCK);

        if( !holdingMutex ){
          async_mutex_enter(ASYNC_MUTEX_QUEUE);
          holdingMutex = 1;
        }
        assert_mutex_is_held(ASYNC_MUTEX_QUEUE);
        async.pQueueFirst = p->pNext;
        sqlite3_free(pData);
        doNotFree = 1;
        break;
      }

      case ASYNC_UNLOCK: {
        AsyncWrite *pIter;
        AsyncFileData *pData = p->pFileData;
        int eLock = p->nByte;

        /* When a file is locked by SQLite using the async backend, it is 
        ** locked within the 'real' file-system synchronously. When it is
        ** unlocked, an ASYNC_UNLOCK event is added to the write-queue to
        ** unlock the file asynchronously. The design of the async backend
        ** requires that the 'real' file-system file be locked from the
        ** time that SQLite first locks it (and probably reads from it)
        ** until all asynchronous write events that were scheduled before
        ** SQLite unlocked the file have been processed.
        **
        ** This is more complex if SQLite locks and unlocks the file multiple
        ** times in quick succession. For example, if SQLite does: 
        ** 
        **   lock, write, unlock, lock, write, unlock
        **
        ** Each "lock" operation locks the file immediately. Each "write" 
        ** and "unlock" operation adds an event to the event queue. If the
        ** second "lock" operation is performed before the first "unlock"
        ** operation has been processed asynchronously, then the first
        ** "unlock" cannot be safely processed as is, since this would mean
        ** the file was unlocked when the second "write" operation is
        ** processed. To work around this, when processing an ASYNC_UNLOCK
        ** operation, SQLite:
        **
        **   1) Unlocks the file to the minimum of the argument passed to
        **      the xUnlock() call and the current lock from SQLite's point
        **      of view, and
        **
        **   2) Only unlocks the file at all if this event is the last
        **      ASYNC_UNLOCK event on this file in the write-queue.
        */ 
        assert( holdingMutex==1 );
        assert( async.pQueueFirst==p );
        for(pIter=async.pQueueFirst->pNext; pIter; pIter=pIter->pNext){
          if( pIter->pFileData==pData && pIter->op==ASYNC_UNLOCK ) break;
        }
        if( !pIter ){
          async_mutex_enter(ASYNC_MUTEX_LOCK);
          pData->lock.eAsyncLock = MIN(
              pData->lock.eAsyncLock, MAX(pData->lock.eLock, eLock)
          );
          assert(pData->lock.eAsyncLock>=pData->lock.eLock);
          rc = getFileLock(pData->pLock);
          async_mutex_leave(ASYNC_MUTEX_LOCK);
        }
        break;
      }

      case ASYNC_DELETE:
        ASYNC_TRACE(("DELETE %s\n", p->zBuf));
        rc = pVfs->xDelete(pVfs, p->zBuf, (int)p->iOffset);
        break;

      case ASYNC_OPENEXCLUSIVE: {
        int flags = (int)p->iOffset;
        AsyncFileData *pData = p->pFileData;
        ASYNC_TRACE(("OPEN %s flags=%d\n", p->zBuf, (int)p->iOffset));
        assert(pData->pBaseRead->pMethods==0 && pData->pBaseWrite->pMethods==0);
        rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, 0);
        assert( holdingMutex==0 );
        async_mutex_enter(ASYNC_MUTEX_QUEUE);
        holdingMutex = 1;
        break;
      }

      default: assert(!"Illegal value for AsyncWrite.op");
    }

    /* If we didn't hang on to the mutex during the IO op, obtain it now
    ** so that the AsyncWrite structure can be safely removed from the 
    ** global write-op queue.
    */
    if( !holdingMutex ){
      async_mutex_enter(ASYNC_MUTEX_QUEUE);
      holdingMutex = 1;
    }
    /* ASYNC_TRACE(("UNLINK %p\n", p)); */
    if( p==async.pQueueLast ){
      async.pQueueLast = 0;
    }
    if( !doNotFree ){
      assert_mutex_is_held(ASYNC_MUTEX_QUEUE);
      async.pQueueFirst = p->pNext;
      sqlite3_free(p);
    }
    assert( holdingMutex );

    /* An IO error has occurred. We cannot report the error back to the
    ** connection that requested the I/O since the error happened 
    ** asynchronously.  The connection has already moved on.  There 
    ** really is nobody to report the error to.
    **
    ** The file for which the error occurred may have been a database or
    ** journal file. Regardless, none of the currently queued operations
    ** associated with the same database should now be performed. Nor should
    ** any subsequently requested IO on either a database or journal file 
    ** handle for the same database be accepted until the main database
    ** file handle has been closed and reopened.
    **
    ** Furthermore, no further IO should be queued or performed on any file
    ** handle associated with a database that may have been part of a 
    ** multi-file transaction that included the database associated with 
    ** the IO error (i.e. a database ATTACHed to the same handle at some 
    ** point in time).
    */
    if( rc!=SQLITE_OK ){
      async.ioError = rc;
    }

    if( async.ioError && !async.pQueueFirst ){
      async_mutex_enter(ASYNC_MUTEX_LOCK);
      if( 0==async.pLock ){
        async.ioError = SQLITE_OK;
      }
      async_mutex_leave(ASYNC_MUTEX_LOCK);
    }

    /* Drop the queue mutex before continuing to the next write operation
    ** in order to give other threads a chance to work with the write queue.
    */
    if( !async.pQueueFirst || !async.ioError ){
      async_mutex_leave(ASYNC_MUTEX_QUEUE);
      holdingMutex = 0;
      if( async.ioDelay>0 ){
        pVfs->xSleep(pVfs, async.ioDelay*1000);
      }else{
        async_sched_yield();
      }
    }
  }
  
  async_mutex_leave(ASYNC_MUTEX_WRITER);
  return;
}

/*
** Install the asynchronous VFS.
*/ 
int sqlite3async_initialize(const char *zParent, int isDefault){
  int rc = SQLITE_OK;
  if( async_vfs.pAppData==0 ){
    sqlite3_vfs *pParent = sqlite3_vfs_find(zParent);
    if( !pParent || async_os_initialize() ){
      rc = SQLITE_ERROR;
    }else if( SQLITE_OK!=(rc = sqlite3_vfs_register(&async_vfs, isDefault)) ){
      async_os_shutdown();
    }else{
      async_vfs.pAppData = (void *)pParent;
      async_vfs.mxPathname = ((sqlite3_vfs *)async_vfs.pAppData)->mxPathname;
    }
  }
  return rc;
}

/*
** Uninstall the asynchronous VFS.
*/
void sqlite3async_shutdown(void){
  if( async_vfs.pAppData ){
    async_os_shutdown();
    sqlite3_vfs_unregister((sqlite3_vfs *)&async_vfs);
    async_vfs.pAppData = 0;
  }
}

/*
** Process events on the write-queue.
*/
void sqlite3async_run(void){
  asyncWriterThread();
}

/*
** Control/configure the asynchronous IO system.
*/
int sqlite3async_control(int op, ...){
  va_list ap;
  va_start(ap, op);
  switch( op ){
    case SQLITEASYNC_HALT: {
      int eWhen = va_arg(ap, int);
      if( eWhen!=SQLITEASYNC_HALT_NEVER
       && eWhen!=SQLITEASYNC_HALT_NOW
       && eWhen!=SQLITEASYNC_HALT_IDLE
      ){
        return SQLITE_MISUSE;
      }
      async.eHalt = eWhen;
      async_mutex_enter(ASYNC_MUTEX_QUEUE);
      async_cond_signal(ASYNC_COND_QUEUE);
      async_mutex_leave(ASYNC_MUTEX_QUEUE);
      break;
    }

    case SQLITEASYNC_DELAY: {
      int iDelay = va_arg(ap, int);
      if( iDelay<0 ){
        return SQLITE_MISUSE;
      }
      async.ioDelay = iDelay;
      break;
    }

    case SQLITEASYNC_LOCKFILES: {
      int bLock = va_arg(ap, int);
      async_mutex_enter(ASYNC_MUTEX_QUEUE);
      if( async.nFile || async.pQueueFirst ){
        async_mutex_leave(ASYNC_MUTEX_QUEUE);
        return SQLITE_MISUSE;
      }
      async.bLockFiles = bLock;
      async_mutex_leave(ASYNC_MUTEX_QUEUE);
      break;
    }
      
    case SQLITEASYNC_GET_HALT: {
      int *peWhen = va_arg(ap, int *);
      *peWhen = async.eHalt;
      break;
    }
    case SQLITEASYNC_GET_DELAY: {
      int *piDelay = va_arg(ap, int *);
      *piDelay = async.ioDelay;
      break;
    }
    case SQLITEASYNC_GET_LOCKFILES: {
      int *piDelay = va_arg(ap, int *);
      *piDelay = async.bLockFiles;
      break;
    }

    default:
      return SQLITE_ERROR;
  }
  return SQLITE_OK;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO) */

Added ext/async/sqlite3async.h.































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

#ifndef __SQLITEASYNC_H_
#define __SQLITEASYNC_H_ 1

/*
** Make sure we can call this stuff from C++.
*/
#ifdef __cplusplus
extern "C" {
#endif

#define SQLITEASYNC_VFSNAME "sqlite3async"

/*
** THREAD SAFETY NOTES:
**
** Of the four API functions in this file, the following are not threadsafe:
**
**   sqlite3async_initialize()
**   sqlite3async_shutdown()
**
** Care must be taken that neither of these functions is called while 
** another thread may be calling either any sqlite3async_XXX() function
** or an sqlite3_XXX() API function related to a database handle that
** is using the asynchronous IO VFS.
**
** These functions:
**
**   sqlite3async_run()
**   sqlite3async_control()
**
** are threadsafe. It is quite safe to call either of these functions even
** if another thread may also be calling one of them or an sqlite3_XXX()
** function related to a database handle that uses the asynchronous IO VFS.
*/

/*
** Initialize the asynchronous IO VFS and register it with SQLite using
** sqlite3_vfs_register(). If the asynchronous VFS is already initialized
** and registered, this function is a no-op. The asynchronous IO VFS
** is registered as "sqlite3async".
**
** The asynchronous IO VFS does not make operating system IO requests 
** directly. Instead, it uses an existing VFS implementation for all
** required file-system operations. If the first parameter to this function
** is NULL, then the current default VFS is used for IO. If it is not
** NULL, then it must be the name of an existing VFS. In other words, the
** first argument to this function is passed to sqlite3_vfs_find() to
** locate the VFS to use for all real IO operations. This VFS is known
** as the "parent VFS".
**
** If the second parameter to this function is non-zero, then the 
** asynchronous IO VFS is registered as the default VFS for all SQLite 
** database connections within the process. Otherwise, the asynchronous IO
** VFS is only used by connections opened using sqlite3_open_v2() that
** specifically request VFS "sqlite3async".
**
** If a parent VFS cannot be located, then SQLITE_ERROR is returned.
** In the unlikely event that operating system specific initialization
** fails (win32 systems create the required critical section and event 
** objects within this function), then SQLITE_ERROR is also returned.
** Finally, if the call to sqlite3_vfs_register() returns an error, then 
** the error code is returned to the user by this function. In all three
** of these cases, intialization has failed and the asynchronous IO VFS
** is not registered with SQLite.
**
** Otherwise, if no error occurs, SQLITE_OK is returned.
*/ 
int sqlite3async_initialize(const char *zParent, int isDefault);

/*
** This function unregisters the asynchronous IO VFS using 
** sqlite3_vfs_unregister().
**
** On win32 platforms, this function also releases the small number of 
** critical section and event objects created by sqlite3async_initialize().
*/ 
void sqlite3async_shutdown();

/*
** This function may only be called when the asynchronous IO VFS is 
** installed (after a call to sqlite3async_initialize()). It processes
** zero or more queued write operations before returning. It is expected
** (but not required) that this function will be called by a different 
** thread than those threads that use SQLite. The "background thread"
** that performs IO.
**
** How many queued write operations are performed before returning 
** depends on the global setting configured by passing the SQLITEASYNC_HALT
** verb to sqlite3async_control() (see below for details). By default
** this function never returns - it processes all pending operations and 
** then blocks waiting for new ones.
**
** If multiple simultaneous calls are made to sqlite3async_run() from two
** or more threads, then the calls are serialized internally.
*/
void sqlite3async_run();

/*
** This function may only be called when the asynchronous IO VFS is 
** installed (after a call to sqlite3async_initialize()). It is used 
** to query or configure various parameters that affect the operation 
** of the asynchronous IO VFS. At present there are three parameters 
** supported:
**
**   * The "halt" parameter, which configures the circumstances under
**     which the sqlite3async_run() parameter is configured.
**
**   * The "delay" parameter. Setting the delay parameter to a non-zero
**     value causes the sqlite3async_run() function to sleep for the
**     configured number of milliseconds between each queued write 
**     operation.
**
**   * The "lockfiles" parameter. This parameter determines whether or 
**     not the asynchronous IO VFS locks the database files it operates
**     on. Disabling file locking can improve throughput.
**
** This function is always passed two arguments. When setting the value
** of a parameter, the first argument must be one of SQLITEASYNC_HALT,
** SQLITEASYNC_DELAY or SQLITEASYNC_LOCKFILES. The second argument must
** be passed the new value for the parameter as type "int".
**
** When querying the current value of a paramter, the first argument must
** be one of SQLITEASYNC_GET_HALT, GET_DELAY or GET_LOCKFILES. The second 
** argument to this function must be of type (int *). The current value
** of the queried parameter is copied to the memory pointed to by the
** second argument. For example:
**
**   int eCurrentHalt;
**   int eNewHalt = SQLITEASYNC_HALT_IDLE;
**
**   sqlite3async_control(SQLITEASYNC_HALT, eNewHalt);
**   sqlite3async_control(SQLITEASYNC_GET_HALT, &eCurrentHalt);
**   assert( eNewHalt==eCurrentHalt );
**
** See below for more detail on each configuration parameter.
**
** SQLITEASYNC_HALT:
**
**   This is used to set the value of the "halt" parameter. The second
**   argument must be one of the SQLITEASYNC_HALT_XXX symbols defined
**   below (either NEVER, IDLE and NOW).
**
**   If the parameter is set to NEVER, then calls to sqlite3async_run()
**   never return. This is the default setting. If the parameter is set
**   to IDLE, then calls to sqlite3async_run() return as soon as the
**   queue of pending write operations is empty. If the parameter is set
**   to NOW, then calls to sqlite3async_run() return as quickly as 
**   possible, without processing any pending write requests.
**
**   If an attempt is made to set this parameter to an integer value other
**   than SQLITEASYNC_HALT_NEVER, IDLE or NOW, then sqlite3async_control() 
**   returns SQLITE_MISUSE and the current value of the parameter is not 
**   modified.
**
**   Modifying the "halt" parameter affects calls to sqlite3async_run() 
**   made by other threads that are currently in progress.
**
** SQLITEASYNC_DELAY:
**
**   This is used to set the value of the "delay" parameter. If set to
**   a non-zero value, then after completing a pending write request, the
**   sqlite3async_run() function sleeps for the configured number of 
**   milliseconds.
**
**   If an attempt is made to set this parameter to a negative value,
**   sqlite3async_control() returns SQLITE_MISUSE and the current value
**   of the parameter is not modified.
**
**   Modifying the "delay" parameter affects calls to sqlite3async_run() 
**   made by other threads that are currently in progress.
**
** SQLITEASYNC_LOCKFILES:
**
**   This is used to set the value of the "lockfiles" parameter. This
**   parameter must be set to either 0 or 1. If set to 1, then the
**   asynchronous IO VFS uses the xLock() and xUnlock() methods of the
**   parent VFS to lock database files being read and/or written. If
**   the parameter is set to 0, then these locks are omitted.
**
**   This parameter may only be set when there are no open database
**   connections using the VFS and the queue of pending write requests
**   is empty. Attempting to set it when this is not true, or to set it 
**   to a value other than 0 or 1 causes sqlite3async_control() to return
**   SQLITE_MISUSE and the value of the parameter to remain unchanged.
**
**   If this parameter is set to zero, then it is only safe to access the
**   database via the asynchronous IO VFS from within a single process. If
**   while writing to the database via the asynchronous IO VFS the database
**   is also read or written from within another process, or via another
**   connection that does not use the asynchronous IO VFS within the same
**   process, the results are undefined (and may include crashes or database
**   corruption).
**
**   Alternatively, if this parameter is set to 1, then it is safe to access
**   the database from multiple connections within multiple processes using
**   either the asynchronous IO VFS or the parent VFS directly.
*/
int sqlite3async_control(int op, ...);

/*
** Values that can be used as the first argument to sqlite3async_control().
*/
#define SQLITEASYNC_HALT          1
#define SQLITEASYNC_GET_HALT      2
#define SQLITEASYNC_DELAY         3
#define SQLITEASYNC_GET_DELAY     4
#define SQLITEASYNC_LOCKFILES     5
#define SQLITEASYNC_GET_LOCKFILES 6

/*
** If the first argument to sqlite3async_control() is SQLITEASYNC_HALT,
** the second argument should be one of the following.
*/
#define SQLITEASYNC_HALT_NEVER 0       /* Never halt (default value) */
#define SQLITEASYNC_HALT_NOW   1       /* Halt as soon as possible */
#define SQLITEASYNC_HALT_IDLE  2       /* Halt when write-queue is empty */

#ifdef __cplusplus
}  /* End of the 'extern "C"' block */
#endif
#endif        /* ifndef __SQLITEASYNC_H_ */

Added ext/fts1/README.txt.





>
>
1
2
This folder contains source code to the first full-text search
extension for SQLite.

Added ext/fts1/ft_hash.c.









































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables used in SQLite.
** We've modified it slightly to serve as a standalone hash table
** implementation for the full-text indexing module.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "ft_hash.h"

void *malloc_and_zero(int n){
  void *p = malloc(n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
** keyClass is one of the constants HASH_INT, HASH_POINTER,
** HASH_BINARY, or HASH_STRING.  The value of keyClass 
** determines what kind of key the hash table will use.  "copyKey" is
** true if the hash table should make its own private copy of keys and
** false if it should just use the supplied pointer.  CopyKey only makes
** sense for HASH_STRING and HASH_BINARY and is ignored
** for other key classes.
*/
void HashInit(Hash *pNew, int keyClass, int copyKey){
  assert( pNew!=0 );
  assert( keyClass>=HASH_STRING && keyClass<=HASH_BINARY );
  pNew->keyClass = keyClass;
#if 0
  if( keyClass==HASH_POINTER || keyClass==HASH_INT ) copyKey = 0;
#endif
  pNew->copyKey = copyKey;
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->xMalloc = malloc_and_zero;
  pNew->xFree = free;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void HashClear(Hash *pH){
  HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    HashElem *next_elem = elem->next;
    if( pH->copyKey && elem->pKey ){
      pH->xFree(elem->pKey);
    }
    pH->xFree(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

#if 0 /* NOT USED */
/*
** Hash and comparison functions when the mode is HASH_INT
*/
static int intHash(const void *pKey, int nKey){
  return nKey ^ (nKey<<8) ^ (nKey>>8);
}
static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  return n2 - n1;
}
#endif

#if 0 /* NOT USED */
/*
** Hash and comparison functions when the mode is HASH_POINTER
*/
static int ptrHash(const void *pKey, int nKey){
  uptr x = Addr(pKey);
  return x ^ (x<<8) ^ (x>>8);
}
static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( pKey1==pKey2 ) return 0;
  if( pKey1<pKey2 ) return -1;
  return 1;
}
#endif

/*
** Hash and comparison functions when the mode is HASH_STRING
*/
static int strHash(const void *pKey, int nKey){
  const char *z = (const char *)pKey;
  int h = 0;
  if( nKey<=0 ) nKey = (int) strlen(z);
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ *z++;
    nKey--;
  }
  return h & 0x7fffffff;
}
static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
}

/*
** Hash and comparison functions when the mode is HASH_BINARY
*/
static int binHash(const void *pKey, int nKey){
  int h = 0;
  const char *z = (const char *)pKey;
  while( nKey-- > 0 ){
    h = (h<<3) ^ h ^ *(z++);
  }
  return h & 0x7fffffff;
}
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return memcmp(pKey1,pKey2,n1);
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** The C syntax in this function definition may be unfamilar to some 
** programmers, so we provide the following additional explanation:
**
** The name of the function is "hashFunction".  The function takes a
** single parameter "keyClass".  The return value of hashFunction()
** is a pointer to another function.  Specifically, the return value
** of hashFunction() is a pointer to a function that takes two parameters
** with types "const void*" and "int" and returns an "int".
*/
static int (*hashFunction(int keyClass))(const void*,int){
#if 0  /* HASH_INT and HASH_POINTER are never used */
  switch( keyClass ){
    case HASH_INT:     return &intHash;
    case HASH_POINTER: return &ptrHash;
    case HASH_STRING:  return &strHash;
    case HASH_BINARY:  return &binHash;;
    default: break;
  }
  return 0;
#else
  if( keyClass==HASH_STRING ){
    return &strHash;
  }else{
    assert( keyClass==HASH_BINARY );
    return &binHash;
  }
#endif
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** For help in interpreted the obscure C code in the function definition,
** see the header comment on the previous function.
*/
static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
#if 0 /* HASH_INT and HASH_POINTER are never used */
  switch( keyClass ){
    case HASH_INT:     return &intCompare;
    case HASH_POINTER: return &ptrCompare;
    case HASH_STRING:  return &strCompare;
    case HASH_BINARY:  return &binCompare;
    default: break;
  }
  return 0;
#else
  if( keyClass==HASH_STRING ){
    return &strCompare;
  }else{
    assert( keyClass==HASH_BINARY );
    return &binCompare;
  }
#endif
}

/* Link an element into the hash table
*/
static void insertElement(
  Hash *pH,              /* The complete hash table */
  struct _ht *pEntry,    /* The entry into which pNew is inserted */
  HashElem *pNew         /* The element to be inserted */
){
  HashElem *pHead;       /* First element already in pEntry */
  pHead = pEntry->chain;
  if( pHead ){
    pNew->next = pHead;
    pNew->prev = pHead->prev;
    if( pHead->prev ){ pHead->prev->next = pNew; }
    else             { pH->first = pNew; }
    pHead->prev = pNew;
  }else{
    pNew->next = pH->first;
    if( pH->first ){ pH->first->prev = pNew; }
    pNew->prev = 0;
    pH->first = pNew;
  }
  pEntry->count++;
  pEntry->chain = pNew;
}


/* Resize the hash table so that it cantains "new_size" buckets.
** "new_size" must be a power of 2.  The hash table might fail 
** to resize if sqliteMalloc() fails.
*/
static void rehash(Hash *pH, int new_size){
  struct _ht *new_ht;            /* The new hash table */
  HashElem *elem, *next_elem;    /* For looping over existing elements */
  int (*xHash)(const void*,int); /* The hash function */

  assert( (new_size & (new_size-1))==0 );
  new_ht = (struct _ht *)pH->xMalloc( new_size*sizeof(struct _ht) );
  if( new_ht==0 ) return;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size;
  xHash = hashFunction(pH->keyClass);
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
}

/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static HashElem *findElementGivenHash(
  const Hash *pH,     /* The pH to be searched */
  const void *pKey,   /* The key we are searching for */
  int nKey,
  int h               /* The hash for this key. */
){
  HashElem *elem;                /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */
  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */

  if( pH->ht ){
    struct _ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
    xCompare = compareFunction(pH->keyClass);
    while( count-- && elem ){
      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
        return elem;
      }
      elem = elem->next;
    }
  }
  return 0;
}

/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
  Hash *pH,         /* The pH containing "elem" */
  HashElem* elem,   /* The element to be removed from the pH */
  int h             /* Hash value for the element */
){
  struct _ht *pEntry;
  if( elem->prev ){
    elem->prev->next = elem->next; 
  }else{
    pH->first = elem->next;
  }
  if( elem->next ){
    elem->next->prev = elem->prev;
  }
  pEntry = &pH->ht[h];
  if( pEntry->chain==elem ){
    pEntry->chain = elem->next;
  }
  pEntry->count--;
  if( pEntry->count<=0 ){
    pEntry->chain = 0;
  }
  if( pH->copyKey && elem->pKey ){
    pH->xFree(elem->pKey);
  }
  pH->xFree( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    HashClear(pH);
  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
void *HashFind(const Hash *pH, const void *pKey, int nKey){
  int h;             /* A hash on key */
  HashElem *elem;    /* The element that matches key */
  int (*xHash)(const void*,int);  /* The hash function */

  if( pH==0 || pH->ht==0 ) return 0;
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  h = (*xHash)(pKey,nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
  return elem ? elem->data : 0;
}

/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  int hraw;             /* Raw hash value of the key */
  int h;                /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */
  int (*xHash)(const void*,int);  /* The hash function */

  assert( pH!=0 );
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  hraw = (*xHash)(pKey, nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)pH->xMalloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = pH->xMalloc( nKey );
    if( new_elem->pKey==0 ){
      pH->xFree(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->htsize==0 ){
    rehash(pH,8);
    if( pH->htsize==0 ){
      pH->count = 0;
      pH->xFree(new_elem);
      return data;
    }
  }
  if( pH->count > pH->htsize ){
    rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  insertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}

Added ext/fts1/ft_hash.h.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in SQLite.  We've modified it slightly to serve as a standalone
** hash table implementation for the full-text indexing module.
**
*/
#ifndef _HASH_H_
#define _HASH_H_

/* Forward declarations of structures. */
typedef struct Hash Hash;
typedef struct HashElem HashElem;

/* A complete hash table is an instance of the following structure.
** The internals of this structure are intended to be opaque -- client
** code should not attempt to access or modify the fields of this structure
** directly.  Change this structure only by using the routines below.
** However, many of the "procedures" and "functions" for modifying and
** accessing this structure are really macros, so we can't really make
** this structure opaque.
*/
struct Hash {
  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
  char copyKey;           /* True if copy of key made on insert */
  int count;              /* Number of entries in this table */
  HashElem *first;        /* The first element of the array */
  void *(*xMalloc)(int);  /* malloc() function to use */
  void (*xFree)(void *);  /* free() function to use */
  int htsize;             /* Number of buckets in the hash table */
  struct _ht {            /* the hash table */
    int count;               /* Number of entries with this hash */
    HashElem *chain;         /* Pointer to first entry with this hash */
  } *ht;
};

/* Each element in the hash table is an instance of the following 
** structure.  All elements are stored on a single doubly-linked list.
**
** Again, this structure is intended to be opaque, but it can't really
** be opaque because it is used by macros.
*/
struct HashElem {
  HashElem *next, *prev;   /* Next and previous elements in the table */
  void *data;              /* Data associated with this element */
  void *pKey; int nKey;    /* Key associated with this element */
};

/*
** There are 4 different modes of operation for a hash table:
**
**   HASH_INT         nKey is used as the key and pKey is ignored.
**
**   HASH_POINTER     pKey is used as the key and nKey is ignored.
**
**   HASH_STRING      pKey points to a string that is nKey bytes long
**                           (including the null-terminator, if any).  Case
**                           is respected in comparisons.
**
**   HASH_BINARY      pKey points to binary data nKey bytes long. 
**                           memcmp() is used to compare keys.
**
** A copy of the key is made for HASH_STRING and HASH_BINARY
** if the copyKey parameter to HashInit is 1.  
*/
/* #define HASH_INT       1 // NOT USED */
/* #define HASH_POINTER   2 // NOT USED */
#define HASH_STRING    3
#define HASH_BINARY    4

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void HashInit(Hash*, int keytype, int copyKey);
void *HashInsert(Hash*, const void *pKey, int nKey, void *pData);
void *HashFind(const Hash*, const void *pKey, int nKey);
void HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   Hash h;
**   HashElem *p;
**   ...
**   for(p=HashFirst(&h); p; p=HashNext(p)){
**     SomeStructure *pData = HashData(p);
**     // do something with pData
**   }
*/
#define HashFirst(H)  ((H)->first)
#define HashNext(E)   ((E)->next)
#define HashData(E)   ((E)->data)
#define HashKey(E)    ((E)->pKey)
#define HashKeysize(E) ((E)->nKey)

/*
** Number of entries in a hash table
*/
#define HashCount(H)  ((H)->count)

#endif /* _HASH_H_ */

Added ext/fts1/fts1.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
/* fts1 has a design flaw which can lead to database corruption (see
** below).  It is recommended not to use it any longer, instead use
** fts3 (or higher).  If you believe that your use of fts1 is safe,
** add -DSQLITE_ENABLE_BROKEN_FTS1=1 to your CFLAGS.
*/
#if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)) \
        && !defined(SQLITE_ENABLE_BROKEN_FTS1)
#error fts1 has a design flaw and has been deprecated.
#endif
/* The flaw is that fts1 uses the content table's unaliased rowid as
** the unique docid.  fts1 embeds the rowid in the index it builds,
** and expects the rowid to not change.  The SQLite VACUUM operation
** will renumber such rowids, thereby breaking fts1.  If you are using
** fts1 in a system which has disabled VACUUM, then you can continue
** to use it safely.  Note that PRAGMA auto_vacuum does NOT disable
** VACUUM, though systems using auto_vacuum are unlikely to invoke
** VACUUM.
**
** fts1 should be safe even across VACUUM if you only insert documents
** and never delete.
*/

/* The author disclaims copyright to this source code.
 *
 * This is an SQLite module implementing full-text search.
 */

/*
** The code in this file is only compiled if:
**
**     * The FTS1 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS1 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS1 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)

#if defined(SQLITE_ENABLE_FTS1) && !defined(SQLITE_CORE)
# define SQLITE_CORE 1
#endif

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts1.h"
#include "fts1_hash.h"
#include "fts1_tokenizer.h"
#include "sqlite3.h"
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1


#if 0
# define TRACE(A)  printf A; fflush(stdout)
#else
# define TRACE(A)
#endif

/* utility functions */

typedef struct StringBuffer {
  int len;      /* length, not including null terminator */
  int alloced;  /* Space allocated for s[] */ 
  char *s;      /* Content of the string */
} StringBuffer;

static void initStringBuffer(StringBuffer *sb){
  sb->len = 0;
  sb->alloced = 100;
  sb->s = malloc(100);
  sb->s[0] = '\0';
}

static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
  if( sb->len + nFrom >= sb->alloced ){
    sb->alloced = sb->len + nFrom + 100;
    sb->s = realloc(sb->s, sb->alloced+1);
    if( sb->s==0 ){
      initStringBuffer(sb);
      return;
    }
  }
  memcpy(sb->s + sb->len, zFrom, nFrom);
  sb->len += nFrom;
  sb->s[sb->len] = 0;
}
static void append(StringBuffer *sb, const char *zFrom){
  nappend(sb, zFrom, strlen(zFrom));
}

/* We encode variable-length integers in little-endian order using seven bits
 * per byte as follows:
**
** KEY:
**         A = 0xxxxxxx    7 bits of data and one flag bit
**         B = 1xxxxxxx    7 bits of data and one flag bit
**
**  7 bits - A
** 14 bits - BA
** 21 bits - BBA
** and so on.
*/

/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
#define VARINT_MAX 10

/* Write a 64-bit variable-length integer to memory starting at p[0].
 * The length of data written will be between 1 and VARINT_MAX bytes.
 * The number of bytes written is returned. */
static int putVarint(char *p, sqlite_int64 v){
  unsigned char *q = (unsigned char *) p;
  sqlite_uint64 vu = v;
  do{
    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
    vu >>= 7;
  }while( vu!=0 );
  q[-1] &= 0x7f;  /* turn off high bit in final byte */
  assert( q - (unsigned char *)p <= VARINT_MAX );
  return (int) (q - (unsigned char *)p);
}

/* Read a 64-bit variable-length integer from memory starting at p[0].
 * Return the number of bytes read, or 0 on error.
 * The value is stored in *v. */
static int getVarint(const char *p, sqlite_int64 *v){
  const unsigned char *q = (const unsigned char *) p;
  sqlite_uint64 x = 0, y = 1;
  while( (*q & 0x80) == 0x80 ){
    x += y * (*q++ & 0x7f);
    y <<= 7;
    if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
      assert( 0 );
      return 0;
    }
  }
  x += y * (*q++);
  *v = (sqlite_int64) x;
  return (int) (q - (unsigned char *)p);
}

static int getVarint32(const char *p, int *pi){
 sqlite_int64 i;
 int ret = getVarint(p, &i);
 *pi = (int) i;
 assert( *pi==i );
 return ret;
}

/*** Document lists ***
 *
 * A document list holds a sorted list of varint-encoded document IDs.
 *
 * A doclist with type DL_POSITIONS_OFFSETS is stored like this:
 *
 * array {
 *   varint docid;
 *   array {
 *     varint position;     (delta from previous position plus POS_BASE)
 *     varint startOffset;  (delta from previous startOffset)
 *     varint endOffset;    (delta from startOffset)
 *   }
 * }
 *
 * Here, array { X } means zero or more occurrences of X, adjacent in memory.
 *
 * A position list may hold positions for text in multiple columns.  A position
 * POS_COLUMN is followed by a varint containing the index of the column for
 * following positions in the list.  Any positions appearing before any
 * occurrences of POS_COLUMN are for column 0.
 *
 * A doclist with type DL_POSITIONS is like the above, but holds only docids
 * and positions without offset information.
 *
 * A doclist with type DL_DOCIDS is like the above, but holds only docids
 * without positions or offset information.
 *
 * On disk, every document list has positions and offsets, so we don't bother
 * to serialize a doclist's type.
 * 
 * We don't yet delta-encode document IDs; doing so will probably be a
 * modest win.
 *
 * NOTE(shess) I've thought of a slightly (1%) better offset encoding.
 * After the first offset, estimate the next offset by using the
 * current token position and the previous token position and offset,
 * offset to handle some variance.  So the estimate would be
 * (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded
 * as normal.  Offsets more than 64 chars from the estimate are
 * encoded as the delta to the previous start offset + 128.  An
 * additional tiny increment can be gained by using the end offset of
 * the previous token to make the estimate a tiny bit more precise.
*/

/* It is not safe to call isspace(), tolower(), or isalnum() on
** hi-bit-set characters.  This is the same solution used in the
** tokenizer.
*/
/* TODO(shess) The snippet-generation code should be using the
** tokenizer-generated tokens rather than doing its own local
** tokenization.
*/
/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
static int safe_isspace(char c){
  return (c&0x80)==0 ? isspace(c) : 0;
}
static int safe_tolower(char c){
  return (c&0x80)==0 ? tolower(c) : c;
}
static int safe_isalnum(char c){
  return (c&0x80)==0 ? isalnum(c) : 0;
}

typedef enum DocListType {
  DL_DOCIDS,              /* docids only */
  DL_POSITIONS,           /* docids + positions */
  DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
} DocListType;

/*
** By default, only positions and not offsets are stored in the doclists.
** To change this so that offsets are stored too, compile with
**
**          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
**
*/
#ifndef DL_DEFAULT
# define DL_DEFAULT DL_POSITIONS
#endif

typedef struct DocList {
  char *pData;
  int nData;
  DocListType iType;
  int iLastColumn;    /* the last column written */
  int iLastPos;       /* the last position written */
  int iLastOffset;    /* the last start offset written */
} DocList;

enum {
  POS_END = 0,        /* end of this position list */
  POS_COLUMN,         /* followed by new column number */
  POS_BASE
};

/* Initialize a new DocList to hold the given data. */
static void docListInit(DocList *d, DocListType iType,
                        const char *pData, int nData){
  d->nData = nData;
  if( nData>0 ){
    d->pData = malloc(nData);
    memcpy(d->pData, pData, nData);
  } else {
    d->pData = NULL;
  }
  d->iType = iType;
  d->iLastColumn = 0;
  d->iLastPos = d->iLastOffset = 0;
}

/* Create a new dynamically-allocated DocList. */
static DocList *docListNew(DocListType iType){
  DocList *d = (DocList *) malloc(sizeof(DocList));
  docListInit(d, iType, 0, 0);
  return d;
}

static void docListDestroy(DocList *d){
  free(d->pData);
#ifndef NDEBUG
  memset(d, 0x55, sizeof(*d));
#endif
}

static void docListDelete(DocList *d){
  docListDestroy(d);
  free(d);
}

static char *docListEnd(DocList *d){
  return d->pData + d->nData;
}

/* Append a varint to a DocList's data. */
static void appendVarint(DocList *d, sqlite_int64 i){
  char c[VARINT_MAX];
  int n = putVarint(c, i);
  d->pData = realloc(d->pData, d->nData + n);
  memcpy(d->pData + d->nData, c, n);
  d->nData += n;
}

static void docListAddDocid(DocList *d, sqlite_int64 iDocid){
  appendVarint(d, iDocid);
  if( d->iType>=DL_POSITIONS ){
    appendVarint(d, POS_END);  /* initially empty position list */
    d->iLastColumn = 0;
    d->iLastPos = d->iLastOffset = 0;
  }
}

/* helper function for docListAddPos and docListAddPosOffset */
static void addPos(DocList *d, int iColumn, int iPos){
  assert( d->nData>0 );
  --d->nData;  /* remove previous terminator */
  if( iColumn!=d->iLastColumn ){
    assert( iColumn>d->iLastColumn );
    appendVarint(d, POS_COLUMN);
    appendVarint(d, iColumn);
    d->iLastColumn = iColumn;
    d->iLastPos = d->iLastOffset = 0;
  }
  assert( iPos>=d->iLastPos );
  appendVarint(d, iPos-d->iLastPos+POS_BASE);
  d->iLastPos = iPos;
}

/* Add a position to the last position list in a doclist. */
static void docListAddPos(DocList *d, int iColumn, int iPos){
  assert( d->iType==DL_POSITIONS );
  addPos(d, iColumn, iPos);
  appendVarint(d, POS_END);  /* add new terminator */
}

/*
** Add a position and starting and ending offsets to a doclist.
**
** If the doclist is setup to handle only positions, then insert
** the position only and ignore the offsets.
*/
static void docListAddPosOffset(
  DocList *d,             /* Doclist under construction */
  int iColumn,            /* Column the inserted term is part of */
  int iPos,               /* Position of the inserted term */
  int iStartOffset,       /* Starting offset of inserted term */
  int iEndOffset          /* Ending offset of inserted term */
){
  assert( d->iType>=DL_POSITIONS );
  addPos(d, iColumn, iPos);
  if( d->iType==DL_POSITIONS_OFFSETS ){
    assert( iStartOffset>=d->iLastOffset );
    appendVarint(d, iStartOffset-d->iLastOffset);
    d->iLastOffset = iStartOffset;
    assert( iEndOffset>=iStartOffset );
    appendVarint(d, iEndOffset-iStartOffset);
  }
  appendVarint(d, POS_END);  /* add new terminator */
}

/*
** A DocListReader object is a cursor into a doclist.  Initialize
** the cursor to the beginning of the doclist by calling readerInit().
** Then use routines
**
**      peekDocid()
**      readDocid()
**      readPosition()
**      skipPositionList()
**      and so forth...
**
** to read information out of the doclist.  When we reach the end
** of the doclist, atEnd() returns TRUE.
*/
typedef struct DocListReader {
  DocList *pDoclist;  /* The document list we are stepping through */
  char *p;            /* Pointer to next unread byte in the doclist */
  int iLastColumn;
  int iLastPos;  /* the last position read, or -1 when not in a position list */
} DocListReader;

/*
** Initialize the DocListReader r to point to the beginning of pDoclist.
*/
static void readerInit(DocListReader *r, DocList *pDoclist){
  r->pDoclist = pDoclist;
  if( pDoclist!=NULL ){
    r->p = pDoclist->pData;
  }
  r->iLastColumn = -1;
  r->iLastPos = -1;
}

/*
** Return TRUE if we have reached then end of pReader and there is
** nothing else left to read.
*/
static int atEnd(DocListReader *pReader){
  return pReader->pDoclist==0 || (pReader->p >= docListEnd(pReader->pDoclist));
}

/* Peek at the next docid without advancing the read pointer. 
*/
static sqlite_int64 peekDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos==-1 );
  getVarint(pReader->p, &ret);
  return ret;
}

/* Read the next docid.   See also nextDocid().
*/
static sqlite_int64 readDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos==-1 );
  pReader->p += getVarint(pReader->p, &ret);
  if( pReader->pDoclist->iType>=DL_POSITIONS ){
    pReader->iLastColumn = 0;
    pReader->iLastPos = 0;
  }
  return ret;
}

/* Read the next position and column index from a position list.
 * Returns the position, or -1 at the end of the list. */
static int readPosition(DocListReader *pReader, int *iColumn){
  int i;
  int iType = pReader->pDoclist->iType;

  if( pReader->iLastPos==-1 ){
    return -1;
  }
  assert( !atEnd(pReader) );

  if( iType<DL_POSITIONS ){
    return -1;
  }
  pReader->p += getVarint32(pReader->p, &i);
  if( i==POS_END ){
    pReader->iLastColumn = pReader->iLastPos = -1;
    *iColumn = -1;
    return -1;
  }
  if( i==POS_COLUMN ){
    pReader->p += getVarint32(pReader->p, &pReader->iLastColumn);
    pReader->iLastPos = 0;
    pReader->p += getVarint32(pReader->p, &i);
    assert( i>=POS_BASE );
  }
  pReader->iLastPos += ((int) i)-POS_BASE;
  if( iType>=DL_POSITIONS_OFFSETS ){
    /* Skip over offsets, ignoring them for now. */
    int iStart, iEnd;
    pReader->p += getVarint32(pReader->p, &iStart);
    pReader->p += getVarint32(pReader->p, &iEnd);
  }
  *iColumn = pReader->iLastColumn;
  return pReader->iLastPos;
}

/* Skip past the end of a position list. */
static void skipPositionList(DocListReader *pReader){
  DocList *p = pReader->pDoclist;
  if( p && p->iType>=DL_POSITIONS ){
    int iColumn;
    while( readPosition(pReader, &iColumn)!=-1 ){}
  }
}

/* Skip over a docid, including its position list if the doclist has
 * positions. */
static void skipDocument(DocListReader *pReader){
  readDocid(pReader);
  skipPositionList(pReader);
}

/* Skip past all docids which are less than [iDocid].  Returns 1 if a docid
 * matching [iDocid] was found.  */
static int skipToDocid(DocListReader *pReader, sqlite_int64 iDocid){
  sqlite_int64 d = 0;
  while( !atEnd(pReader) && (d=peekDocid(pReader))<iDocid ){
    skipDocument(pReader);
  }
  return !atEnd(pReader) && d==iDocid;
}

/* Return the first document in a document list.
*/
static sqlite_int64 firstDocid(DocList *d){
  DocListReader r;
  readerInit(&r, d);
  return readDocid(&r);
}

#ifdef SQLITE_DEBUG
/*
** This routine is used for debugging purpose only.
**
** Write the content of a doclist to standard output.
*/
static void printDoclist(DocList *p){
  DocListReader r;
  const char *zSep = "";

  readerInit(&r, p);
  while( !atEnd(&r) ){
    sqlite_int64 docid = readDocid(&r);
    if( docid==0 ){
      skipPositionList(&r);
      continue;
    }
    printf("%s%lld", zSep, docid);
    zSep =  ",";
    if( p->iType>=DL_POSITIONS ){
      int iPos, iCol;
      const char *zDiv = "";
      printf("(");
      while( (iPos = readPosition(&r, &iCol))>=0 ){
        printf("%s%d:%d", zDiv, iCol, iPos);
        zDiv = ":";
      }
      printf(")");
    }
  }
  printf("\n");
  fflush(stdout);
}
#endif /* SQLITE_DEBUG */

/* Trim the given doclist to contain only positions in column
 * [iRestrictColumn]. */
static void docListRestrictColumn(DocList *in, int iRestrictColumn){
  DocListReader r;
  DocList out;

  assert( in->iType>=DL_POSITIONS );
  readerInit(&r, in);
  docListInit(&out, DL_POSITIONS, NULL, 0);

  while( !atEnd(&r) ){
    sqlite_int64 iDocid = readDocid(&r);
    int iPos, iColumn;

    docListAddDocid(&out, iDocid);
    while( (iPos = readPosition(&r, &iColumn)) != -1 ){
      if( iColumn==iRestrictColumn ){
        docListAddPos(&out, iColumn, iPos);
      }
    }
  }

  docListDestroy(in);
  *in = out;
}

/* Trim the given doclist by discarding any docids without any remaining
 * positions. */
static void docListDiscardEmpty(DocList *in) {
  DocListReader r;
  DocList out;

  /* TODO: It would be nice to implement this operation in place; that
   * could save a significant amount of memory in queries with long doclists. */
  assert( in->iType>=DL_POSITIONS );
  readerInit(&r, in);
  docListInit(&out, DL_POSITIONS, NULL, 0);

  while( !atEnd(&r) ){
    sqlite_int64 iDocid = readDocid(&r);
    int match = 0;
    int iPos, iColumn;
    while( (iPos = readPosition(&r, &iColumn)) != -1 ){
      if( !match ){
        docListAddDocid(&out, iDocid);
        match = 1;
      }
      docListAddPos(&out, iColumn, iPos);
    }
  }

  docListDestroy(in);
  *in = out;
}

/* Helper function for docListUpdate() and docListAccumulate().
** Splices a doclist element into the doclist represented by r,
** leaving r pointing after the newly spliced element.
*/
static void docListSpliceElement(DocListReader *r, sqlite_int64 iDocid,
                                 const char *pSource, int nSource){
  DocList *d = r->pDoclist;
  char *pTarget;
  int nTarget, found;

  found = skipToDocid(r, iDocid);

  /* Describe slice in d to place pSource/nSource. */
  pTarget = r->p;
  if( found ){
    skipDocument(r);
    nTarget = r->p-pTarget;
  }else{
    nTarget = 0;
  }

  /* The sense of the following is that there are three possibilities.
  ** If nTarget==nSource, we should not move any memory nor realloc.
  ** If nTarget>nSource, trim target and realloc.
  ** If nTarget<nSource, realloc then expand target.
  */
  if( nTarget>nSource ){
    memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget));
  }
  if( nTarget!=nSource ){
    int iDoclist = pTarget-d->pData;
    d->pData = realloc(d->pData, d->nData+nSource-nTarget);
    pTarget = d->pData+iDoclist;
  }
  if( nTarget<nSource ){
    memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget));
  }

  memcpy(pTarget, pSource, nSource);
  d->nData += nSource-nTarget;
  r->p = pTarget+nSource;
}

/* Insert/update pUpdate into the doclist. */
static void docListUpdate(DocList *d, DocList *pUpdate){
  DocListReader reader;

  assert( d!=NULL && pUpdate!=NULL );
  assert( d->iType==pUpdate->iType);

  readerInit(&reader, d);
  docListSpliceElement(&reader, firstDocid(pUpdate),
                       pUpdate->pData, pUpdate->nData);
}

/* Propagate elements from pUpdate to pAcc, overwriting elements with
** matching docids.
*/
static void docListAccumulate(DocList *pAcc, DocList *pUpdate){
  DocListReader accReader, updateReader;

  /* Handle edge cases where one doclist is empty. */
  assert( pAcc!=NULL );
  if( pUpdate==NULL || pUpdate->nData==0 ) return;
  if( pAcc->nData==0 ){
    pAcc->pData = malloc(pUpdate->nData);
    memcpy(pAcc->pData, pUpdate->pData, pUpdate->nData);
    pAcc->nData = pUpdate->nData;
    return;
  }

  readerInit(&accReader, pAcc);
  readerInit(&updateReader, pUpdate);

  while( !atEnd(&updateReader) ){
    char *pSource = updateReader.p;
    sqlite_int64 iDocid = readDocid(&updateReader);
    skipPositionList(&updateReader);
    docListSpliceElement(&accReader, iDocid, pSource, updateReader.p-pSource);
  }
}

/*
** Read the next docid off of pIn.  Return 0 if we reach the end.
*
* TODO: This assumes that docids are never 0, but they may actually be 0 since
* users can choose docids when inserting into a full-text table.  Fix this.
*/
static sqlite_int64 nextDocid(DocListReader *pIn){
  skipPositionList(pIn);
  return atEnd(pIn) ? 0 : readDocid(pIn);
}

/*
** pLeft and pRight are two DocListReaders that are pointing to
** positions lists of the same document: iDocid. 
**
** If there are no instances in pLeft or pRight where the position
** of pLeft is one less than the position of pRight, then this
** routine adds nothing to pOut.
**
** If there are one or more instances where positions from pLeft
** are exactly one less than positions from pRight, then add a new
** document record to pOut.  If pOut wants to hold positions, then
** include the positions from pRight that are one more than a
** position in pLeft.  In other words:  pRight.iPos==pLeft.iPos+1.
**
** pLeft and pRight are left pointing at the next document record.
*/
static void mergePosList(
  DocListReader *pLeft,    /* Left position list */
  DocListReader *pRight,   /* Right position list */
  sqlite_int64 iDocid,     /* The docid from pLeft and pRight */
  DocList *pOut            /* Write the merged document record here */
){
  int iLeftCol, iLeftPos = readPosition(pLeft, &iLeftCol);
  int iRightCol, iRightPos = readPosition(pRight, &iRightCol);
  int match = 0;

  /* Loop until we've reached the end of both position lists. */
  while( iLeftPos!=-1 && iRightPos!=-1 ){
    if( iLeftCol==iRightCol && iLeftPos+1==iRightPos ){
      if( !match ){
        docListAddDocid(pOut, iDocid);
        match = 1;
      }
      if( pOut->iType>=DL_POSITIONS ){
        docListAddPos(pOut, iRightCol, iRightPos);
      }
      iLeftPos = readPosition(pLeft, &iLeftCol);
      iRightPos = readPosition(pRight, &iRightCol);
    }else if( iRightCol<iLeftCol ||
              (iRightCol==iLeftCol && iRightPos<iLeftPos+1) ){
      iRightPos = readPosition(pRight, &iRightCol);
    }else{
      iLeftPos = readPosition(pLeft, &iLeftCol);
    }
  }
  if( iLeftPos>=0 ) skipPositionList(pLeft);
  if( iRightPos>=0 ) skipPositionList(pRight);
}

/* We have two doclists:  pLeft and pRight.
** Write the phrase intersection of these two doclists into pOut.
**
** A phrase intersection means that two documents only match
** if pLeft.iPos+1==pRight.iPos.
**
** The output pOut may or may not contain positions.  If pOut
** does contain positions, they are the positions of pRight.
*/
static void docListPhraseMerge(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight;

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextDocid(&left);
  docidRight = nextDocid(&right);

  while( docidLeft>0 && docidRight>0 ){
    if( docidLeft<docidRight ){
      docidLeft = nextDocid(&left);
    }else if( docidRight<docidLeft ){
      docidRight = nextDocid(&right);
    }else{
      mergePosList(&left, &right, docidLeft, pOut);
      docidLeft = nextDocid(&left);
      docidRight = nextDocid(&right);
    }
  }
}

/* We have two doclists:  pLeft and pRight.
** Write the intersection of these two doclists into pOut.
** Only docids are matched.  Position information is ignored.
**
** The output pOut never holds positions.
*/
static void docListAndMerge(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight;

  assert( pOut->iType<DL_POSITIONS );

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextDocid(&left);
  docidRight = nextDocid(&right);

  while( docidLeft>0 && docidRight>0 ){
    if( docidLeft<docidRight ){
      docidLeft = nextDocid(&left);
    }else if( docidRight<docidLeft ){
      docidRight = nextDocid(&right);
    }else{
      docListAddDocid(pOut, docidLeft);
      docidLeft = nextDocid(&left);
      docidRight = nextDocid(&right);
    }
  }
}

/* We have two doclists:  pLeft and pRight.
** Write the union of these two doclists into pOut.
** Only docids are matched.  Position information is ignored.
**
** The output pOut never holds positions.
*/
static void docListOrMerge(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight, priorLeft;

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextDocid(&left);
  docidRight = nextDocid(&right);

  while( docidLeft>0 && docidRight>0 ){
    if( docidLeft<=docidRight ){
      docListAddDocid(pOut, docidLeft);
    }else{
      docListAddDocid(pOut, docidRight);
    }
    priorLeft = docidLeft;
    if( docidLeft<=docidRight ){
      docidLeft = nextDocid(&left);
    }
    if( docidRight>0 && docidRight<=priorLeft ){
      docidRight = nextDocid(&right);
    }
  }
  while( docidLeft>0 ){
    docListAddDocid(pOut, docidLeft);
    docidLeft = nextDocid(&left);
  }
  while( docidRight>0 ){
    docListAddDocid(pOut, docidRight);
    docidRight = nextDocid(&right);
  }
}

/* We have two doclists:  pLeft and pRight.
** Write into pOut all documents that occur in pLeft but not
** in pRight.
**
** Only docids are matched.  Position information is ignored.
**
** The output pOut never holds positions.
*/
static void docListExceptMerge(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight, priorLeft;

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextDocid(&left);
  docidRight = nextDocid(&right);

  while( docidLeft>0 && docidRight>0 ){
    priorLeft = docidLeft;
    if( docidLeft<docidRight ){
      docListAddDocid(pOut, docidLeft);
    }
    if( docidLeft<=docidRight ){
      docidLeft = nextDocid(&left);
    }
    if( docidRight>0 && docidRight<=priorLeft ){
      docidRight = nextDocid(&right);
    }
  }
  while( docidLeft>0 ){
    docListAddDocid(pOut, docidLeft);
    docidLeft = nextDocid(&left);
  }
}

static char *string_dup_n(const char *s, int n){
  char *str = malloc(n + 1);
  memcpy(str, s, n);
  str[n] = '\0';
  return str;
}

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it is not part of the standard C library and
 * may not be available everywhere.) */
static char *string_dup(const char *s){
  return string_dup_n(s, strlen(s));
}

/* Format a string, replacing each occurrence of the % character with
 * zDb.zName.  This may be more convenient than sqlite_mprintf()
 * when one string is used repeatedly in a format string.
 * The caller must free() the returned string. */
static char *string_format(const char *zFormat,
                           const char *zDb, const char *zName){
  const char *p;
  size_t len = 0;
  size_t nDb = strlen(zDb);
  size_t nName = strlen(zName);
  size_t nFullTableName = nDb+1+nName;
  char *result;
  char *r;

  /* first compute length needed */
  for(p = zFormat ; *p ; ++p){
    len += (*p=='%' ? nFullTableName : 1);
  }
  len += 1;  /* for null terminator */

  r = result = malloc(len);
  for(p = zFormat; *p; ++p){
    if( *p=='%' ){
      memcpy(r, zDb, nDb);
      r += nDb;
      *r++ = '.';
      memcpy(r, zName, nName);
      r += nName;
    } else {
      *r++ = *p;
    }
  }
  *r++ = '\0';
  assert( r == result + len );
  return result;
}

static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
                    const char *zFormat){
  char *zCommand = string_format(zFormat, zDb, zName);
  int rc;
  TRACE(("FTS1 sql: %s\n", zCommand));
  rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  free(zCommand);
  return rc;
}

static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
                       sqlite3_stmt **ppStmt, const char *zFormat){
  char *zCommand = string_format(zFormat, zDb, zName);
  int rc;
  TRACE(("FTS1 prepare: %s\n", zCommand));
  rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL);
  free(zCommand);
  return rc;
}

/* end utility functions */

/* Forward reference */
typedef struct fulltext_vtab fulltext_vtab;

/* A single term in a query is represented by an instances of
** the following structure.
*/
typedef struct QueryTerm {
  short int nPhrase; /* How many following terms are part of the same phrase */
  short int iPhrase; /* This is the i-th term of a phrase. */
  short int iColumn; /* Column of the index that must match this term */
  signed char isOr;  /* this term is preceded by "OR" */
  signed char isNot; /* this term is preceded by "-" */
  char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
  int nTerm;         /* Number of bytes in pTerm[] */
} QueryTerm;


/* A query string is parsed into a Query structure.
 *
 * We could, in theory, allow query strings to be complicated
 * nested expressions with precedence determined by parentheses.
 * But none of the major search engines do this.  (Perhaps the
 * feeling is that an parenthesized expression is two complex of
 * an idea for the average user to grasp.)  Taking our lead from
 * the major search engines, we will allow queries to be a list
 * of terms (with an implied AND operator) or phrases in double-quotes,
 * with a single optional "-" before each non-phrase term to designate
 * negation and an optional OR connector.
 *
 * OR binds more tightly than the implied AND, which is what the
 * major search engines seem to do.  So, for example:
 * 
 *    [one two OR three]     ==>    one AND (two OR three)
 *    [one OR two three]     ==>    (one OR two) AND three
 *
 * A "-" before a term matches all entries that lack that term.
 * The "-" must occur immediately before the term with in intervening
 * space.  This is how the search engines do it.
 *
 * A NOT term cannot be the right-hand operand of an OR.  If this
 * occurs in the query string, the NOT is ignored:
 *
 *    [one OR -two]          ==>    one OR two
 *
 */
typedef struct Query {
  fulltext_vtab *pFts;  /* The full text index */
  int nTerms;           /* Number of terms in the query */
  QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
  int nextIsOr;         /* Set the isOr flag on the next inserted term */
  int nextColumn;       /* Next word parsed must be in this column */
  int dfltColumn;       /* The default column */
} Query;


/*
** An instance of the following structure keeps track of generated
** matching-word offset information and snippets.
*/
typedef struct Snippet {
  int nMatch;     /* Total number of matches */
  int nAlloc;     /* Space allocated for aMatch[] */
  struct snippetMatch { /* One entry for each matching term */
    char snStatus;       /* Status flag for use while constructing snippets */
    short int iCol;      /* The column that contains the match */
    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
    short int nByte;     /* Number of bytes in the term */
    int iStart;          /* The offset to the first character of the term */
  } *aMatch;      /* Points to space obtained from malloc */
  char *zOffset;  /* Text rendering of aMatch[] */
  int nOffset;    /* strlen(zOffset) */
  char *zSnippet; /* Snippet text */
  int nSnippet;   /* strlen(zSnippet) */
} Snippet;


typedef enum QueryType {
  QUERY_GENERIC,   /* table scan */
  QUERY_ROWID,     /* lookup by rowid */
  QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
} QueryType;

/* TODO(shess) CHUNK_MAX controls how much data we allow in segment 0
** before we start aggregating into larger segments.  Lower CHUNK_MAX
** means that for a given input we have more individual segments per
** term, which means more rows in the table and a bigger index (due to
** both more rows and bigger rowids).  But it also reduces the average
** cost of adding new elements to the segment 0 doclist, and it seems
** to reduce the number of pages read and written during inserts.  256
** was chosen by measuring insertion times for a certain input (first
** 10k documents of Enron corpus), though including query performance
** in the decision may argue for a larger value.
*/
#define CHUNK_MAX 256

typedef enum fulltext_statement {
  CONTENT_INSERT_STMT,
  CONTENT_SELECT_STMT,
  CONTENT_UPDATE_STMT,
  CONTENT_DELETE_STMT,

  TERM_SELECT_STMT,
  TERM_SELECT_ALL_STMT,
  TERM_INSERT_STMT,
  TERM_UPDATE_STMT,
  TERM_DELETE_STMT,

  MAX_STMT                     /* Always at end! */
} fulltext_statement;

/* These must exactly match the enum above. */
/* TODO(adam): Is there some risk that a statement (in particular,
** pTermSelectStmt) will be used in two cursors at once, e.g.  if a
** query joins a virtual table to itself?  If so perhaps we should
** move some of these to the cursor object.
*/
static const char *const fulltext_zStatement[MAX_STMT] = {
  /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
  /* CONTENT_SELECT */ "select * from %_content where rowid = ?",
  /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
  /* CONTENT_DELETE */ "delete from %_content where rowid = ?",

  /* TERM_SELECT */
  "select rowid, doclist from %_term where term = ? and segment = ?",
  /* TERM_SELECT_ALL */
  "select doclist from %_term where term = ? order by segment",
  /* TERM_INSERT */
  "insert into %_term (rowid, term, segment, doclist) values (?, ?, ?, ?)",
  /* TERM_UPDATE */ "update %_term set doclist = ? where rowid = ?",
  /* TERM_DELETE */ "delete from %_term where rowid = ?",
};

/*
** A connection to a fulltext index is an instance of the following
** structure.  The xCreate and xConnect methods create an instance
** of this structure and xDestroy and xDisconnect free that instance.
** All other methods receive a pointer to the structure as one of their
** arguments.
*/
struct fulltext_vtab {
  sqlite3_vtab base;               /* Base class used by SQLite core */
  sqlite3 *db;                     /* The database connection */
  const char *zDb;                 /* logical database name */
  const char *zName;               /* virtual table name */
  int nColumn;                     /* number of columns in virtual table */
  char **azColumn;                 /* column names.  malloced */
  char **azContentColumn;          /* column names in content table; malloced */
  sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */

  /* Precompiled statements which we keep as long as the table is
  ** open.
  */
  sqlite3_stmt *pFulltextStatements[MAX_STMT];
};

/*
** When the core wants to do a query, it create a cursor using a
** call to xOpen.  This structure is an instance of a cursor.  It
** is destroyed by xClose.
*/
typedef struct fulltext_cursor {
  sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
  QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
  sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
  int eof;                         /* True if at End Of Results */
  Query q;                         /* Parsed query string */
  Snippet snippet;                 /* Cached snippet for the current row */
  int iColumn;                     /* Column being searched */
  DocListReader result;  /* used when iCursorType == QUERY_FULLTEXT */ 
} fulltext_cursor;

static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  return (fulltext_vtab *) c->base.pVtab;
}

static const sqlite3_module fulltextModule;   /* forward declaration */

/* Append a list of strings separated by commas to a StringBuffer. */
static void appendList(StringBuffer *sb, int nString, char **azString){
  int i;
  for(i=0; i<nString; ++i){
    if( i>0 ) append(sb, ", ");
    append(sb, azString[i]);
  }
}

/* Return a dynamically generated statement of the form
 *   insert into %_content (rowid, ...) values (?, ...)
 */
static const char *contentInsertStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;

  initStringBuffer(&sb);
  append(&sb, "insert into %_content (rowid, ");
  appendList(&sb, v->nColumn, v->azContentColumn);
  append(&sb, ") values (?");
  for(i=0; i<v->nColumn; ++i)
    append(&sb, ", ?");
  append(&sb, ")");
  return sb.s;
}

/* Return a dynamically generated statement of the form
 *   update %_content set [col_0] = ?, [col_1] = ?, ...
 *                    where rowid = ?
 */
static const char *contentUpdateStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;

  initStringBuffer(&sb);
  append(&sb, "update %_content set ");
  for(i=0; i<v->nColumn; ++i) {
    if( i>0 ){
      append(&sb, ", ");
    }
    append(&sb, v->azContentColumn[i]);
    append(&sb, " = ?");
  }
  append(&sb, " where rowid = ?");
  return sb.s;
}

/* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
** If the indicated statement has never been prepared, it is prepared
** and cached, otherwise the cached version is reset.
*/
static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
                             sqlite3_stmt **ppStmt){
  assert( iStmt<MAX_STMT );
  if( v->pFulltextStatements[iStmt]==NULL ){
    const char *zStmt;
    int rc;
    switch( iStmt ){
      case CONTENT_INSERT_STMT:
        zStmt = contentInsertStatement(v); break;
      case CONTENT_UPDATE_STMT:
        zStmt = contentUpdateStatement(v); break;
      default:
        zStmt = fulltext_zStatement[iStmt];
    }
    rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
                         zStmt);
    if( zStmt != fulltext_zStatement[iStmt]) free((void *) zStmt);
    if( rc!=SQLITE_OK ) return rc;
  } else {
    int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
    if( rc!=SQLITE_OK ) return rc;
  }

  *ppStmt = v->pFulltextStatements[iStmt];
  return SQLITE_OK;
}

/* Step the indicated statement, handling errors SQLITE_BUSY (by
** retrying) and SQLITE_SCHEMA (by re-preparing and transferring
** bindings to the new statement).
** TODO(adam): We should extend this function so that it can work with
** statements declared locally, not only globally cached statements.
*/
static int sql_step_statement(fulltext_vtab *v, fulltext_statement iStmt,
                              sqlite3_stmt **ppStmt){
  int rc;
  sqlite3_stmt *s = *ppStmt;
  assert( iStmt<MAX_STMT );
  assert( s==v->pFulltextStatements[iStmt] );

  while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){
    if( rc==SQLITE_BUSY ) continue;
    if( rc!=SQLITE_ERROR ) return rc;

    /* If an SQLITE_SCHEMA error has occurred, then finalizing this
     * statement is going to delete the fulltext_vtab structure. If
     * the statement just executed is in the pFulltextStatements[]
     * array, it will be finalized twice. So remove it before
     * calling sqlite3_finalize().
     */
    v->pFulltextStatements[iStmt] = NULL;
    rc = sqlite3_finalize(s);
    break;
  }
  return rc;

 err:
  sqlite3_finalize(s);
  return rc;
}

/* Like sql_step_statement(), but convert SQLITE_DONE to SQLITE_OK.
** Useful for statements like UPDATE, where we expect no results.
*/
static int sql_single_step_statement(fulltext_vtab *v,
                                     fulltext_statement iStmt,
                                     sqlite3_stmt **ppStmt){
  int rc = sql_step_statement(v, iStmt, ppStmt);
  return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
}

/* insert into %_content (rowid, ...) values ([rowid], [pValues]) */
static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
                          sqlite3_value **pValues){
  sqlite3_stmt *s;
  int i;
  int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_value(s, 1, rowid);
  if( rc!=SQLITE_OK ) return rc;

  for(i=0; i<v->nColumn; ++i){
    rc = sqlite3_bind_value(s, 2+i, pValues[i]);
    if( rc!=SQLITE_OK ) return rc;
  }

  return sql_single_step_statement(v, CONTENT_INSERT_STMT, &s);
}

/* update %_content set col0 = pValues[0], col1 = pValues[1], ...
 *                  where rowid = [iRowid] */
static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
                          sqlite_int64 iRowid){
  sqlite3_stmt *s;
  int i;
  int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  for(i=0; i<v->nColumn; ++i){
    rc = sqlite3_bind_value(s, 1+i, pValues[i]);
    if( rc!=SQLITE_OK ) return rc;
  }

  rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, CONTENT_UPDATE_STMT, &s);
}

static void freeStringArray(int nString, const char **pString){
  int i;

  for (i=0 ; i < nString ; ++i) {
    if( pString[i]!=NULL ) free((void *) pString[i]);
  }
  free((void *) pString);
}

/* select * from %_content where rowid = [iRow]
 * The caller must delete the returned array and all strings in it.
 * null fields will be NULL in the returned array.
 *
 * TODO: Perhaps we should return pointer/length strings here for consistency
 * with other code which uses pointer/length. */
static int content_select(fulltext_vtab *v, sqlite_int64 iRow,
                          const char ***pValues){
  sqlite3_stmt *s;
  const char **values;
  int i;
  int rc;

  *pValues = NULL;

  rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_step_statement(v, CONTENT_SELECT_STMT, &s);
  if( rc!=SQLITE_ROW ) return rc;

  values = (const char **) malloc(v->nColumn * sizeof(const char *));
  for(i=0; i<v->nColumn; ++i){
    if( sqlite3_column_type(s, i)==SQLITE_NULL ){
      values[i] = NULL;
    }else{
      values[i] = string_dup((char*)sqlite3_column_text(s, i));
    }
  }

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ){
    *pValues = values;
    return SQLITE_OK;
  }

  freeStringArray(v->nColumn, values);
  return rc;
}

/* delete from %_content where rowid = [iRow ] */
static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iRow);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, CONTENT_DELETE_STMT, &s);
}

/* select rowid, doclist from %_term
 *  where term = [pTerm] and segment = [iSegment]
 * If found, returns SQLITE_ROW; the caller must free the
 * returned doclist.  If no rows found, returns SQLITE_DONE. */
static int term_select(fulltext_vtab *v, const char *pTerm, int nTerm,
                       int iSegment,
                       sqlite_int64 *rowid, DocList *out){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 1, pTerm, nTerm, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 2, iSegment);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_step_statement(v, TERM_SELECT_STMT, &s);
  if( rc!=SQLITE_ROW ) return rc;

  *rowid = sqlite3_column_int64(s, 0);
  docListInit(out, DL_DEFAULT,
              sqlite3_column_blob(s, 1), sqlite3_column_bytes(s, 1));

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  return rc==SQLITE_DONE ? SQLITE_ROW : rc;
}

/* Load the segment doclists for term pTerm and merge them in
** appropriate order into out.  Returns SQLITE_OK if successful.  If
** there are no segments for pTerm, successfully returns an empty
** doclist in out.
**
** Each document consists of 1 or more "columns".  The number of
** columns is v->nColumn.  If iColumn==v->nColumn, then return
** position information about all columns.  If iColumn<v->nColumn,
** then only return position information about the iColumn-th column
** (where the first column is 0).
*/
static int term_select_all(
  fulltext_vtab *v,     /* The fulltext index we are querying against */
  int iColumn,          /* If <nColumn, only look at the iColumn-th column */
  const char *pTerm,    /* The term whose posting lists we want */
  int nTerm,            /* Number of bytes in pTerm */
  DocList *out          /* Write the resulting doclist here */
){
  DocList doclist;
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_SELECT_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 1, pTerm, nTerm, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  docListInit(&doclist, DL_DEFAULT, 0, 0);

  /* TODO(shess) Handle schema and busy errors. */
  while( (rc=sql_step_statement(v, TERM_SELECT_ALL_STMT, &s))==SQLITE_ROW ){
    DocList old;

    /* TODO(shess) If we processed doclists from oldest to newest, we
    ** could skip the malloc() involved with the following call.  For
    ** now, I'd rather keep this logic similar to index_insert_term().
    ** We could additionally drop elements when we see deletes, but
    ** that would require a distinct version of docListAccumulate().
    */
    docListInit(&old, DL_DEFAULT,
                sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0));

    if( iColumn<v->nColumn ){   /* querying a single column */
      docListRestrictColumn(&old, iColumn);
    }

    /* doclist contains the newer data, so write it over old.  Then
    ** steal accumulated result for doclist.
    */
    docListAccumulate(&old, &doclist);
    docListDestroy(&doclist);
    doclist = old;
  }
  if( rc!=SQLITE_DONE ){
    docListDestroy(&doclist);
    return rc;
  }

  docListDiscardEmpty(&doclist);
  *out = doclist;
  return SQLITE_OK;
}

/* insert into %_term (rowid, term, segment, doclist)
               values ([piRowid], [pTerm], [iSegment], [doclist])
** Lets sqlite select rowid if piRowid is NULL, else uses *piRowid.
**
** NOTE(shess) piRowid is IN, with values of "space of int64" plus
** null, it is not used to pass data back to the caller.
*/
static int term_insert(fulltext_vtab *v, sqlite_int64 *piRowid,
                       const char *pTerm, int nTerm,
                       int iSegment, DocList *doclist){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  if( piRowid==NULL ){
    rc = sqlite3_bind_null(s, 1);
  }else{
    rc = sqlite3_bind_int64(s, 1, *piRowid);
  }
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 2, pTerm, nTerm, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 3, iSegment);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 4, doclist->pData, doclist->nData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, TERM_INSERT_STMT, &s);
}

/* update %_term set doclist = [doclist] where rowid = [rowid] */
static int term_update(fulltext_vtab *v, sqlite_int64 rowid,
                       DocList *doclist){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_UPDATE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 1, doclist->pData, doclist->nData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, rowid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, TERM_UPDATE_STMT, &s);
}

static int term_delete(fulltext_vtab *v, sqlite_int64 rowid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, rowid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, TERM_DELETE_STMT, &s);
}

/*
** Free the memory used to contain a fulltext_vtab structure.
*/
static void fulltext_vtab_destroy(fulltext_vtab *v){
  int iStmt, i;

  TRACE(("FTS1 Destroy %p\n", v));
  for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
    if( v->pFulltextStatements[iStmt]!=NULL ){
      sqlite3_finalize(v->pFulltextStatements[iStmt]);
      v->pFulltextStatements[iStmt] = NULL;
    }
  }

  if( v->pTokenizer!=NULL ){
    v->pTokenizer->pModule->xDestroy(v->pTokenizer);
    v->pTokenizer = NULL;
  }
  
  free(v->azColumn);
  for(i = 0; i < v->nColumn; ++i) {
    sqlite3_free(v->azContentColumn[i]);
  }
  free(v->azContentColumn);
  free(v);
}

/*
** Token types for parsing the arguments to xConnect or xCreate.
*/
#define TOKEN_EOF         0    /* End of file */
#define TOKEN_SPACE       1    /* Any kind of whitespace */
#define TOKEN_ID          2    /* An identifier */
#define TOKEN_STRING      3    /* A string literal */
#define TOKEN_PUNCT       4    /* A single punctuation character */

/*
** If X is a character that can be used in an identifier then
** IdChar(X) will be true.  Otherwise it is false.
**
** For ASCII, any character with the high-order bit set is
** allowed in an identifier.  For 7-bit characters, 
** sqlite3IsIdChar[X] must be 1.
**
** Ticket #1066.  the SQL standard does not allow '$' in the
** middle of identfiers.  But many SQL implementations do. 
** SQLite will allow '$' in identifiers for compatibility.
** But the feature is undocumented.
*/
static const char isIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20]))


/*
** Return the length of the token that begins at z[0]. 
** Store the token type in *tokenType before returning.
*/
static int getToken(const char *z, int *tokenType){
  int i, c;
  switch( *z ){
    case 0: {
      *tokenType = TOKEN_EOF;
      return 0;
    }
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; safe_isspace(z[i]); i++){}
      *tokenType = TOKEN_SPACE;
      return i;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      for(i=1; (c=z[i])!=0; i++){
        if( c==delim ){
          if( z[i+1]==delim ){
            i++;
          }else{
            break;
          }
        }
      }
      *tokenType = TOKEN_STRING;
      return i + (c!=0);
    }
    case '[': {
      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
      *tokenType = TOKEN_ID;
      return i;
    }
    default: {
      if( !IdChar(*z) ){
        break;
      }
      for(i=1; IdChar(z[i]); i++){}
      *tokenType = TOKEN_ID;
      return i;
    }
  }
  *tokenType = TOKEN_PUNCT;
  return 1;
}

/*
** A token extracted from a string is an instance of the following
** structure.
*/
typedef struct Token {
  const char *z;       /* Pointer to token text.  Not '\000' terminated */
  short int n;         /* Length of the token text in bytes. */
} Token;

/*
** Given a input string (which is really one of the argv[] parameters
** passed into xConnect or xCreate) split the string up into tokens.
** Return an array of pointers to '\000' terminated strings, one string
** for each non-whitespace token.
**
** The returned array is terminated by a single NULL pointer.
**
** Space to hold the returned array is obtained from a single
** malloc and should be freed by passing the return value to free().
** The individual strings within the token list are all a part of
** the single memory allocation and will all be freed at once.
*/
static char **tokenizeString(const char *z, int *pnToken){
  int nToken = 0;
  Token *aToken = malloc( strlen(z) * sizeof(aToken[0]) );
  int n = 1;
  int e, i;
  int totalSize = 0;
  char **azToken;
  char *zCopy;
  while( n>0 ){
    n = getToken(z, &e);
    if( e!=TOKEN_SPACE ){
      aToken[nToken].z = z;
      aToken[nToken].n = n;
      nToken++;
      totalSize += n+1;
    }
    z += n;
  }
  azToken = (char**)malloc( nToken*sizeof(char*) + totalSize );
  zCopy = (char*)&azToken[nToken];
  nToken--;
  for(i=0; i<nToken; i++){
    azToken[i] = zCopy;
    n = aToken[i].n;
    memcpy(zCopy, aToken[i].z, n);
    zCopy[n] = 0;
    zCopy += n+1;
  }
  azToken[nToken] = 0;
  free(aToken);
  *pnToken = nToken;
  return azToken;
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** Examples:
**
**     "abc"   becomes   abc
**     'xyz'   becomes   xyz
**     [pqr]   becomes   pqr
**     `mno`   becomes   mno
*/
static void dequoteString(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return;
  }
  for(i=1, j=0; z[i]; i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = quote;
        i++;
      }else{
        z[j++] = 0;
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
}

/*
** The input azIn is a NULL-terminated list of tokens.  Remove the first
** token and all punctuation tokens.  Remove the quotes from
** around string literal tokens.
**
** Example:
**
**     input:      tokenize chinese ( 'simplifed' , 'mixed' )
**     output:     chinese simplifed mixed
**
** Another example:
**
**     input:      delimiters ( '[' , ']' , '...' )
**     output:     [ ] ...
*/
static void tokenListToIdList(char **azIn){
  int i, j;
  if( azIn ){
    for(i=0, j=-1; azIn[i]; i++){
      if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
        dequoteString(azIn[i]);
        if( j>=0 ){
          azIn[j] = azIn[i];
        }
        j++;
      }
    }
    azIn[j] = 0;
  }
}


/*
** Find the first alphanumeric token in the string zIn.  Null-terminate
** this token.  Remove any quotation marks.  And return a pointer to
** the result.
*/
static char *firstToken(char *zIn, char **pzTail){
  int n, ttype;
  while(1){
    n = getToken(zIn, &ttype);
    if( ttype==TOKEN_SPACE ){
      zIn += n;
    }else if( ttype==TOKEN_EOF ){
      *pzTail = zIn;
      return 0;
    }else{
      zIn[n] = 0;
      *pzTail = &zIn[1];
      dequoteString(zIn);
      return zIn;
    }
  }
  /*NOTREACHED*/
}

/* Return true if...
**
**   *  s begins with the string t, ignoring case
**   *  s is longer than t
**   *  The first character of s beyond t is not a alphanumeric
** 
** Ignore leading space in *s.
**
** To put it another way, return true if the first token of
** s[] is t[].
*/
static int startsWith(const char *s, const char *t){
  while( safe_isspace(*s) ){ s++; }
  while( *t ){
    if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
  }
  return *s!='_' && !safe_isalnum(*s);
}

/*
** An instance of this structure defines the "spec" of a
** full text index.  This structure is populated by parseSpec
** and use by fulltextConnect and fulltextCreate.
*/
typedef struct TableSpec {
  const char *zDb;         /* Logical database name */
  const char *zName;       /* Name of the full-text index */
  int nColumn;             /* Number of columns to be indexed */
  char **azColumn;         /* Original names of columns to be indexed */
  char **azContentColumn;  /* Column names for %_content */
  char **azTokenizer;      /* Name of tokenizer and its arguments */
} TableSpec;

/*
** Reclaim all of the memory used by a TableSpec
*/
static void clearTableSpec(TableSpec *p) {
  free(p->azColumn);
  free(p->azContentColumn);
  free(p->azTokenizer);
}

/* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
 *
 * CREATE VIRTUAL TABLE email
 *        USING fts1(subject, body, tokenize mytokenizer(myarg))
 *
 * We return parsed information in a TableSpec structure.
 * 
 */
static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
                     char**pzErr){
  int i, n;
  char *z, *zDummy;
  char **azArg;
  const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */

  assert( argc>=3 );
  /* Current interface:
  ** argv[0] - module name
  ** argv[1] - database name
  ** argv[2] - table name
  ** argv[3..] - columns, optionally followed by tokenizer specification
  **             and snippet delimiters specification.
  */

  /* Make a copy of the complete argv[][] array in a single allocation.
  ** The argv[][] array is read-only and transient.  We can write to the
  ** copy in order to modify things and the copy is persistent.
  */
  memset(pSpec, 0, sizeof(*pSpec));
  for(i=n=0; i<argc; i++){
    n += strlen(argv[i]) + 1;
  }
  azArg = malloc( sizeof(char*)*argc + n );
  if( azArg==0 ){
    return SQLITE_NOMEM;
  }
  z = (char*)&azArg[argc];
  for(i=0; i<argc; i++){
    azArg[i] = z;
    strcpy(z, argv[i]);
    z += strlen(z)+1;
  }

  /* Identify the column names and the tokenizer and delimiter arguments
  ** in the argv[][] array.
  */
  pSpec->zDb = azArg[1];
  pSpec->zName = azArg[2];
  pSpec->nColumn = 0;
  pSpec->azColumn = azArg;
  zTokenizer = "tokenize simple";
  for(i=3; i<argc; ++i){
    if( startsWith(azArg[i],"tokenize") ){
      zTokenizer = azArg[i];
    }else{
      z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
      pSpec->nColumn++;
    }
  }
  if( pSpec->nColumn==0 ){
    azArg[0] = "content";
    pSpec->nColumn = 1;
  }

  /*
  ** Construct the list of content column names.
  **
  ** Each content column name will be of the form cNNAAAA
  ** where NN is the column number and AAAA is the sanitized
  ** column name.  "sanitized" means that special characters are
  ** converted to "_".  The cNN prefix guarantees that all column
  ** names are unique.
  **
  ** The AAAA suffix is not strictly necessary.  It is included
  ** for the convenience of people who might examine the generated
  ** %_content table and wonder what the columns are used for.
  */
  pSpec->azContentColumn = malloc( pSpec->nColumn * sizeof(char *) );
  if( pSpec->azContentColumn==0 ){
    clearTableSpec(pSpec);
    return SQLITE_NOMEM;
  }
  for(i=0; i<pSpec->nColumn; i++){
    char *p;
    pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
    for (p = pSpec->azContentColumn[i]; *p ; ++p) {
      if( !safe_isalnum(*p) ) *p = '_';
    }
  }

  /*
  ** Parse the tokenizer specification string.
  */
  pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
  tokenListToIdList(pSpec->azTokenizer);

  return SQLITE_OK;
}

/*
** Generate a CREATE TABLE statement that describes the schema of
** the virtual table.  Return a pointer to this schema string.
**
** Space is obtained from sqlite3_mprintf() and should be freed
** using sqlite3_free().
*/
static char *fulltextSchema(
  int nColumn,                  /* Number of columns */
  const char *const* azColumn,  /* List of columns */
  const char *zTableName        /* Name of the table */
){
  int i;
  char *zSchema, *zNext;
  const char *zSep = "(";
  zSchema = sqlite3_mprintf("CREATE TABLE x");
  for(i=0; i<nColumn; i++){
    zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
    sqlite3_free(zSchema);
    zSchema = zNext;
    zSep = ",";
  }
  zNext = sqlite3_mprintf("%s,%Q)", zSchema, zTableName);
  sqlite3_free(zSchema);
  return zNext;
}

/*
** Build a new sqlite3_vtab structure that will describe the
** fulltext index defined by spec.
*/
static int constructVtab(
  sqlite3 *db,              /* The SQLite database connection */
  TableSpec *spec,          /* Parsed spec information from parseSpec() */
  sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
  char **pzErr              /* Write any error message here */
){
  int rc;
  int n;
  fulltext_vtab *v = 0;
  const sqlite3_tokenizer_module *m = NULL;
  char *schema;

  v = (fulltext_vtab *) malloc(sizeof(fulltext_vtab));
  if( v==0 ) return SQLITE_NOMEM;
  memset(v, 0, sizeof(*v));
  /* sqlite will initialize v->base */
  v->db = db;
  v->zDb = spec->zDb;       /* Freed when azColumn is freed */
  v->zName = spec->zName;   /* Freed when azColumn is freed */
  v->nColumn = spec->nColumn;
  v->azContentColumn = spec->azContentColumn;
  spec->azContentColumn = 0;
  v->azColumn = spec->azColumn;
  spec->azColumn = 0;

  if( spec->azTokenizer==0 ){
    return SQLITE_NOMEM;
  }
  /* TODO(shess) For now, add new tokenizers as else if clauses. */
  if( spec->azTokenizer[0]==0 || startsWith(spec->azTokenizer[0], "simple") ){
    sqlite3Fts1SimpleTokenizerModule(&m);
  }else if( startsWith(spec->azTokenizer[0], "porter") ){
    sqlite3Fts1PorterTokenizerModule(&m);
  }else{
    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
    rc = SQLITE_ERROR;
    goto err;
  }
  for(n=0; spec->azTokenizer[n]; n++){}
  if( n ){
    rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
                    &v->pTokenizer);
  }else{
    rc = m->xCreate(0, 0, &v->pTokenizer);
  }
  if( rc!=SQLITE_OK ) goto err;
  v->pTokenizer->pModule = m;

  /* TODO: verify the existence of backing tables foo_content, foo_term */

  schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
                          spec->zName);
  rc = sqlite3_declare_vtab(db, schema);
  sqlite3_free(schema);
  if( rc!=SQLITE_OK ) goto err;

  memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));

  *ppVTab = &v->base;
  TRACE(("FTS1 Connect %p\n", v));

  return rc;

err:
  fulltext_vtab_destroy(v);
  return rc;
}

static int fulltextConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVTab,
  char **pzErr
){
  TableSpec spec;
  int rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  rc = constructVtab(db, &spec, ppVTab, pzErr);
  clearTableSpec(&spec);
  return rc;
}

  /* The %_content table holds the text of each document, with
  ** the rowid used as the docid.
  **
  ** The %_term table maps each term to a document list blob
  ** containing elements sorted by ascending docid, each element
  ** encoded as:
  **
  **   docid varint-encoded
  **   token elements:
  **     position+1 varint-encoded as delta from previous position
  **     start offset varint-encoded as delta from previous start offset
  **     end offset varint-encoded as delta from start offset
  **
  ** The sentinel position of 0 indicates the end of the token list.
  **
  ** Additionally, doclist blobs are chunked into multiple segments,
  ** using segment to order the segments.  New elements are added to
  ** the segment at segment 0, until it exceeds CHUNK_MAX.  Then
  ** segment 0 is deleted, and the doclist is inserted at segment 1.
  ** If there is already a doclist at segment 1, the segment 0 doclist
  ** is merged with it, the segment 1 doclist is deleted, and the
  ** merged doclist is inserted at segment 2, repeating those
  ** operations until an insert succeeds.
  **
  ** Since this structure doesn't allow us to update elements in place
  ** in case of deletion or update, these are simply written to
  ** segment 0 (with an empty token list in case of deletion), with
  ** docListAccumulate() taking care to retain lower-segment
  ** information in preference to higher-segment information.
  */
  /* TODO(shess) Provide a VACUUM type operation which both removes
  ** deleted elements which are no longer necessary, and duplicated
  ** elements.  I suspect this will probably not be necessary in
  ** practice, though.
  */
static int fulltextCreate(sqlite3 *db, void *pAux,
                          int argc, const char * const *argv,
                          sqlite3_vtab **ppVTab, char **pzErr){
  int rc;
  TableSpec spec;
  StringBuffer schema;
  TRACE(("FTS1 Create\n"));

  rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  initStringBuffer(&schema);
  append(&schema, "CREATE TABLE %_content(");
  appendList(&schema, spec.nColumn, spec.azContentColumn);
  append(&schema, ")");
  rc = sql_exec(db, spec.zDb, spec.zName, schema.s);
  free(schema.s);
  if( rc!=SQLITE_OK ) goto out;

  rc = sql_exec(db, spec.zDb, spec.zName,
    "create table %_term(term text, segment integer, doclist blob, "
                        "primary key(term, segment));");
  if( rc!=SQLITE_OK ) goto out;

  rc = constructVtab(db, &spec, ppVTab, pzErr);

out:
  clearTableSpec(&spec);
  return rc;
}

/* Decide how to handle an SQL query. */
static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  int i;
  TRACE(("FTS1 BestIndex\n"));

  for(i=0; i<pInfo->nConstraint; ++i){
    const struct sqlite3_index_constraint *pConstraint;
    pConstraint = &pInfo->aConstraint[i];
    if( pConstraint->usable ) {
      if( pConstraint->iColumn==-1 &&
          pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
        pInfo->idxNum = QUERY_ROWID;      /* lookup by rowid */
        TRACE(("FTS1 QUERY_ROWID\n"));
      } else if( pConstraint->iColumn>=0 &&
                 pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
        /* full-text search */
        pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
        TRACE(("FTS1 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
      } else continue;

      pInfo->aConstraintUsage[i].argvIndex = 1;
      pInfo->aConstraintUsage[i].omit = 1;

      /* An arbitrary value for now.
       * TODO: Perhaps rowid matches should be considered cheaper than
       * full-text searches. */
      pInfo->estimatedCost = 1.0;   

      return SQLITE_OK;
    }
  }
  pInfo->idxNum = QUERY_GENERIC;
  return SQLITE_OK;
}

static int fulltextDisconnect(sqlite3_vtab *pVTab){
  TRACE(("FTS1 Disconnect %p\n", pVTab));
  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextDestroy(sqlite3_vtab *pVTab){
  fulltext_vtab *v = (fulltext_vtab *)pVTab;
  int rc;

  TRACE(("FTS1 Destroy %p\n", pVTab));
  rc = sql_exec(v->db, v->zDb, v->zName,
                "drop table if exists %_content;"
                "drop table if exists %_term;"
                );
  if( rc!=SQLITE_OK ) return rc;

  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  fulltext_cursor *c;

  c = (fulltext_cursor *) calloc(sizeof(fulltext_cursor), 1);
  /* sqlite will initialize c->base */
  *ppCursor = &c->base;
  TRACE(("FTS1 Open %p: %p\n", pVTab, c));

  return SQLITE_OK;
}


/* Free all of the dynamically allocated memory held by *q
*/
static void queryClear(Query *q){
  int i;
  for(i = 0; i < q->nTerms; ++i){
    free(q->pTerms[i].pTerm);
  }
  free(q->pTerms);
  memset(q, 0, sizeof(*q));
}

/* Free all of the dynamically allocated memory held by the
** Snippet
*/
static void snippetClear(Snippet *p){
  free(p->aMatch);
  free(p->zOffset);
  free(p->zSnippet);
  memset(p, 0, sizeof(*p));
}
/*
** Append a single entry to the p->aMatch[] log.
*/
static void snippetAppendMatch(
  Snippet *p,               /* Append the entry to this snippet */
  int iCol, int iTerm,      /* The column and query term */
  int iStart, int nByte     /* Offset and size of the match */
){
  int i;
  struct snippetMatch *pMatch;
  if( p->nMatch+1>=p->nAlloc ){
    p->nAlloc = p->nAlloc*2 + 10;
    p->aMatch = realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
    if( p->aMatch==0 ){
      p->nMatch = 0;
      p->nAlloc = 0;
      return;
    }
  }
  i = p->nMatch++;
  pMatch = &p->aMatch[i];
  pMatch->iCol = iCol;
  pMatch->iTerm = iTerm;
  pMatch->iStart = iStart;
  pMatch->nByte = nByte;
}

/*
** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
*/
#define FTS1_ROTOR_SZ   (32)
#define FTS1_ROTOR_MASK (FTS1_ROTOR_SZ-1)

/*
** Add entries to pSnippet->aMatch[] for every match that occurs against
** document zDoc[0..nDoc-1] which is stored in column iColumn.
*/
static void snippetOffsetsOfColumn(
  Query *pQuery,
  Snippet *pSnippet,
  int iColumn,
  const char *zDoc,
  int nDoc
){
  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
  fulltext_vtab *pVtab;                /* The full text index */
  int nColumn;                         /* Number of columns in the index */
  const QueryTerm *aTerm;              /* Query string terms */
  int nTerm;                           /* Number of query string terms */  
  int i, j;                            /* Loop counters */
  int rc;                              /* Return code */
  unsigned int match, prevMatch;       /* Phrase search bitmasks */
  const char *zToken;                  /* Next token from the tokenizer */
  int nToken;                          /* Size of zToken */
  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */

  /* The following variables keep a circular buffer of the last
  ** few tokens */
  unsigned int iRotor = 0;             /* Index of current token */
  int iRotorBegin[FTS1_ROTOR_SZ];      /* Beginning offset of token */
  int iRotorLen[FTS1_ROTOR_SZ];        /* Length of token */

  pVtab = pQuery->pFts;
  nColumn = pVtab->nColumn;
  pTokenizer = pVtab->pTokenizer;
  pTModule = pTokenizer->pModule;
  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
  if( rc ) return;
  pTCursor->pTokenizer = pTokenizer;
  aTerm = pQuery->pTerms;
  nTerm = pQuery->nTerms;
  if( nTerm>=FTS1_ROTOR_SZ ){
    nTerm = FTS1_ROTOR_SZ - 1;
  }
  prevMatch = 0;
  while(1){
    rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
    if( rc ) break;
    iRotorBegin[iRotor&FTS1_ROTOR_MASK] = iBegin;
    iRotorLen[iRotor&FTS1_ROTOR_MASK] = iEnd-iBegin;
    match = 0;
    for(i=0; i<nTerm; i++){
      int iCol;
      iCol = aTerm[i].iColumn;
      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
      if( aTerm[i].nTerm!=nToken ) continue;
      if( memcmp(aTerm[i].pTerm, zToken, nToken) ) continue;
      if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
      match |= 1<<i;
      if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
        for(j=aTerm[i].iPhrase-1; j>=0; j--){
          int k = (iRotor-j) & FTS1_ROTOR_MASK;
          snippetAppendMatch(pSnippet, iColumn, i-j,
                iRotorBegin[k], iRotorLen[k]);
        }
      }
    }
    prevMatch = match<<1;
    iRotor++;
  }
  pTModule->xClose(pTCursor);  
}


/*
** Compute all offsets for the current row of the query.  
** If the offsets have already been computed, this routine is a no-op.
*/
static void snippetAllOffsets(fulltext_cursor *p){
  int nColumn;
  int iColumn, i;
  int iFirst, iLast;
  fulltext_vtab *pFts;

  if( p->snippet.nMatch ) return;
  if( p->q.nTerms==0 ) return;
  pFts = p->q.pFts;
  nColumn = pFts->nColumn;
  iColumn = p->iCursorType - QUERY_FULLTEXT;
  if( iColumn<0 || iColumn>=nColumn ){
    iFirst = 0;
    iLast = nColumn-1;
  }else{
    iFirst = iColumn;
    iLast = iColumn;
  }
  for(i=iFirst; i<=iLast; i++){
    const char *zDoc;
    int nDoc;
    zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
    nDoc = sqlite3_column_bytes(p->pStmt, i+1);
    snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
  }
}

/*
** Convert the information in the aMatch[] array of the snippet
** into the string zOffset[0..nOffset-1].
*/
static void snippetOffsetText(Snippet *p){
  int i;
  int cnt = 0;
  StringBuffer sb;
  char zBuf[200];
  if( p->zOffset ) return;
  initStringBuffer(&sb);
  for(i=0; i<p->nMatch; i++){
    struct snippetMatch *pMatch = &p->aMatch[i];
    zBuf[0] = ' ';
    sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
        pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
    append(&sb, zBuf);
    cnt++;
  }
  p->zOffset = sb.s;
  p->nOffset = sb.len;
}

/*
** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
** of matching words some of which might be in zDoc.  zDoc is column
** number iCol.
**
** iBreak is suggested spot in zDoc where we could begin or end an
** excerpt.  Return a value similar to iBreak but possibly adjusted
** to be a little left or right so that the break point is better.
*/
static int wordBoundary(
  int iBreak,                   /* The suggested break point */
  const char *zDoc,             /* Document text */
  int nDoc,                     /* Number of bytes in zDoc[] */
  struct snippetMatch *aMatch,  /* Matching words */
  int nMatch,                   /* Number of entries in aMatch[] */
  int iCol                      /* The column number for zDoc[] */
){
  int i;
  if( iBreak<=10 ){
    return 0;
  }
  if( iBreak>=nDoc-10 ){
    return nDoc;
  }
  for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
  if( i<nMatch ){
    if( aMatch[i].iStart<iBreak+10 ){
      return aMatch[i].iStart;
    }
    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
      return aMatch[i-1].iStart;
    }
  }
  for(i=1; i<=10; i++){
    if( safe_isspace(zDoc[iBreak-i]) ){
      return iBreak - i + 1;
    }
    if( safe_isspace(zDoc[iBreak+i]) ){
      return iBreak + i + 1;
    }
  }
  return iBreak;
}

/*
** If the StringBuffer does not end in white space, add a single
** space character to the end.
*/
static void appendWhiteSpace(StringBuffer *p){
  if( p->len==0 ) return;
  if( safe_isspace(p->s[p->len-1]) ) return;
  append(p, " ");
}

/*
** Remove white space from teh end of the StringBuffer
*/
static void trimWhiteSpace(StringBuffer *p){
  while( p->len>0 && safe_isspace(p->s[p->len-1]) ){
    p->len--;
  }
}



/*
** Allowed values for Snippet.aMatch[].snStatus
*/
#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */

/*
** Generate the text of a snippet.
*/
static void snippetText(
  fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
  const char *zStartMark,     /* Markup to appear before each match */
  const char *zEndMark,       /* Markup to appear after each match */
  const char *zEllipsis       /* Ellipsis mark */
){
  int i, j;
  struct snippetMatch *aMatch;
  int nMatch;
  int nDesired;
  StringBuffer sb;
  int tailCol;
  int tailOffset;
  int iCol;
  int nDoc;
  const char *zDoc;
  int iStart, iEnd;
  int tailEllipsis = 0;
  int iMatch;
  

  free(pCursor->snippet.zSnippet);
  pCursor->snippet.zSnippet = 0;
  aMatch = pCursor->snippet.aMatch;
  nMatch = pCursor->snippet.nMatch;
  initStringBuffer(&sb);

  for(i=0; i<nMatch; i++){
    aMatch[i].snStatus = SNIPPET_IGNORE;
  }
  nDesired = 0;
  for(i=0; i<pCursor->q.nTerms; i++){
    for(j=0; j<nMatch; j++){
      if( aMatch[j].iTerm==i ){
        aMatch[j].snStatus = SNIPPET_DESIRED;
        nDesired++;
        break;
      }
    }
  }

  iMatch = 0;
  tailCol = -1;
  tailOffset = 0;
  for(i=0; i<nMatch && nDesired>0; i++){
    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
    nDesired--;
    iCol = aMatch[i].iCol;
    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
    iStart = aMatch[i].iStart - 40;
    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
    if( iStart<=10 ){
      iStart = 0;
    }
    if( iCol==tailCol && iStart<=tailOffset+20 ){
      iStart = tailOffset;
    }
    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
      trimWhiteSpace(&sb);
      appendWhiteSpace(&sb);
      append(&sb, zEllipsis);
      appendWhiteSpace(&sb);
    }
    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
    if( iEnd>=nDoc-10 ){
      iEnd = nDoc;
      tailEllipsis = 0;
    }else{
      tailEllipsis = 1;
    }
    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
    while( iStart<iEnd ){
      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
             && aMatch[iMatch].iCol<=iCol ){
        iMatch++;
      }
      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
             && aMatch[iMatch].iCol==iCol ){
        nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
        iStart = aMatch[iMatch].iStart;
        append(&sb, zStartMark);
        nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
        append(&sb, zEndMark);
        iStart += aMatch[iMatch].nByte;
        for(j=iMatch+1; j<nMatch; j++){
          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
              && aMatch[j].snStatus==SNIPPET_DESIRED ){
            nDesired--;
            aMatch[j].snStatus = SNIPPET_IGNORE;
          }
        }
      }else{
        nappend(&sb, &zDoc[iStart], iEnd - iStart);
        iStart = iEnd;
      }
    }
    tailCol = iCol;
    tailOffset = iEnd;
  }
  trimWhiteSpace(&sb);
  if( tailEllipsis ){
    appendWhiteSpace(&sb);
    append(&sb, zEllipsis);
  }
  pCursor->snippet.zSnippet = sb.s;
  pCursor->snippet.nSnippet = sb.len;  
}


/*
** Close the cursor.  For additional information see the documentation
** on the xClose method of the virtual table interface.
*/
static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  TRACE(("FTS1 Close %p\n", c));
  sqlite3_finalize(c->pStmt);
  queryClear(&c->q);
  snippetClear(&c->snippet);
  if( c->result.pDoclist!=NULL ){
    docListDelete(c->result.pDoclist);
  }
  free(c);
  return SQLITE_OK;
}

static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  sqlite_int64 iDocid;
  int rc;

  TRACE(("FTS1 Next %p\n", pCursor));
  snippetClear(&c->snippet);
  if( c->iCursorType < QUERY_FULLTEXT ){
    /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
    rc = sqlite3_step(c->pStmt);
    switch( rc ){
      case SQLITE_ROW:
        c->eof = 0;
        return SQLITE_OK;
      case SQLITE_DONE:
        c->eof = 1;
        return SQLITE_OK;
      default:
        c->eof = 1;
        return rc;
    }
  } else {  /* full-text query */
    rc = sqlite3_reset(c->pStmt);
    if( rc!=SQLITE_OK ) return rc;

    iDocid = nextDocid(&c->result);
    if( iDocid==0 ){
      c->eof = 1;
      return SQLITE_OK;
    }
    rc = sqlite3_bind_int64(c->pStmt, 1, iDocid);
    if( rc!=SQLITE_OK ) return rc;
    /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
    rc = sqlite3_step(c->pStmt);
    if( rc==SQLITE_ROW ){   /* the case we expect */
      c->eof = 0;
      return SQLITE_OK;
    }
    /* an error occurred; abort */
    return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  }
}


/* Return a DocList corresponding to the query term *pTerm.  If *pTerm
** is the first term of a phrase query, go ahead and evaluate the phrase
** query and return the doclist for the entire phrase query.
**
** The result is stored in pTerm->doclist.
*/
static int docListOfTerm(
  fulltext_vtab *v,     /* The full text index */
  int iColumn,          /* column to restrict to.  No restrition if >=nColumn */
  QueryTerm *pQTerm,    /* Term we are looking for, or 1st term of a phrase */
  DocList **ppResult    /* Write the result here */
){
  DocList *pLeft, *pRight, *pNew;
  int i, rc;

  pLeft = docListNew(DL_POSITIONS);
  rc = term_select_all(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pLeft);
  if( rc ){
    docListDelete(pLeft);
    return rc;
  }
  for(i=1; i<=pQTerm->nPhrase; i++){
    pRight = docListNew(DL_POSITIONS);
    rc = term_select_all(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm, pRight);
    if( rc ){
      docListDelete(pLeft);
      return rc;
    }
    pNew = docListNew(i<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS);
    docListPhraseMerge(pLeft, pRight, pNew);
    docListDelete(pLeft);
    docListDelete(pRight);
    pLeft = pNew;
  }
  *ppResult = pLeft;
  return SQLITE_OK;
}

/* Add a new term pTerm[0..nTerm-1] to the query *q.
*/
static void queryAdd(Query *q, const char *pTerm, int nTerm){
  QueryTerm *t;
  ++q->nTerms;
  q->pTerms = realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
  if( q->pTerms==0 ){
    q->nTerms = 0;
    return;
  }
  t = &q->pTerms[q->nTerms - 1];
  memset(t, 0, sizeof(*t));
  t->pTerm = malloc(nTerm+1);
  memcpy(t->pTerm, pTerm, nTerm);
  t->pTerm[nTerm] = 0;
  t->nTerm = nTerm;
  t->isOr = q->nextIsOr;
  q->nextIsOr = 0;
  t->iColumn = q->nextColumn;
  q->nextColumn = q->dfltColumn;
}

/*
** Check to see if the string zToken[0...nToken-1] matches any
** column name in the virtual table.   If it does,
** return the zero-indexed column number.  If not, return -1.
*/
static int checkColumnSpecifier(
  fulltext_vtab *pVtab,    /* The virtual table */
  const char *zToken,      /* Text of the token */
  int nToken               /* Number of characters in the token */
){
  int i;
  for(i=0; i<pVtab->nColumn; i++){
    if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
        && pVtab->azColumn[i][nToken]==0 ){
      return i;
    }
  }
  return -1;
}

/*
** Parse the text at pSegment[0..nSegment-1].  Add additional terms
** to the query being assemblied in pQuery.
**
** inPhrase is true if pSegment[0..nSegement-1] is contained within
** double-quotes.  If inPhrase is true, then the first term
** is marked with the number of terms in the phrase less one and
** OR and "-" syntax is ignored.  If inPhrase is false, then every
** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
*/
static int tokenizeSegment(
  sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
  const char *pSegment, int nSegment,     /* Query expression being parsed */
  int inPhrase,                           /* True if within "..." */
  Query *pQuery                           /* Append results here */
){
  const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  sqlite3_tokenizer_cursor *pCursor;
  int firstIndex = pQuery->nTerms;
  int iCol;
  int nTerm = 1;
  
  int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
  if( rc!=SQLITE_OK ) return rc;
  pCursor->pTokenizer = pTokenizer;

  while( 1 ){
    const char *pToken;
    int nToken, iBegin, iEnd, iPos;

    rc = pModule->xNext(pCursor,
                        &pToken, &nToken,
                        &iBegin, &iEnd, &iPos);
    if( rc!=SQLITE_OK ) break;
    if( !inPhrase &&
        pSegment[iEnd]==':' &&
         (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
      pQuery->nextColumn = iCol;
      continue;
    }
    if( !inPhrase && pQuery->nTerms>0 && nToken==2
         && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){
      pQuery->nextIsOr = 1;
      continue;
    }
    queryAdd(pQuery, pToken, nToken);
    if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
      pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
    }
    pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
    if( inPhrase ){
      nTerm++;
    }
  }

  if( inPhrase && pQuery->nTerms>firstIndex ){
    pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
  }

  return pModule->xClose(pCursor);
}

/* Parse a query string, yielding a Query object pQuery.
**
** The calling function will need to queryClear() to clean up
** the dynamically allocated memory held by pQuery.
*/
static int parseQuery(
  fulltext_vtab *v,        /* The fulltext index */
  const char *zInput,      /* Input text of the query string */
  int nInput,              /* Size of the input text */
  int dfltColumn,          /* Default column of the index to match against */
  Query *pQuery            /* Write the parse results here. */
){
  int iInput, inPhrase = 0;

  if( zInput==0 ) nInput = 0;
  if( nInput<0 ) nInput = strlen(zInput);
  pQuery->nTerms = 0;
  pQuery->pTerms = NULL;
  pQuery->nextIsOr = 0;
  pQuery->nextColumn = dfltColumn;
  pQuery->dfltColumn = dfltColumn;
  pQuery->pFts = v;

  for(iInput=0; iInput<nInput; ++iInput){
    int i;
    for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
    if( i>iInput ){
      tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
                       pQuery);
    }
    iInput = i;
    if( i<nInput ){
      assert( zInput[i]=='"' );
      inPhrase = !inPhrase;
    }
  }

  if( inPhrase ){
    /* unmatched quote */
    queryClear(pQuery);
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}

/* Perform a full-text query using the search expression in
** zInput[0..nInput-1].  Return a list of matching documents
** in pResult.
**
** Queries must match column iColumn.  Or if iColumn>=nColumn
** they are allowed to match against any column.
*/
static int fulltextQuery(
  fulltext_vtab *v,      /* The full text index */
  int iColumn,           /* Match against this column by default */
  const char *zInput,    /* The query string */
  int nInput,            /* Number of bytes in zInput[] */
  DocList **pResult,     /* Write the result doclist here */
  Query *pQuery          /* Put parsed query string here */
){
  int i, iNext, rc;
  DocList *pLeft = NULL;
  DocList *pRight, *pNew, *pOr;
  int nNot = 0;
  QueryTerm *aTerm;

  rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
  if( rc!=SQLITE_OK ) return rc;

  /* Merge AND terms. */
  aTerm = pQuery->pTerms;
  for(i = 0; i<pQuery->nTerms; i=iNext){
    if( aTerm[i].isNot ){
      /* Handle all NOT terms in a separate pass */
      nNot++;
      iNext = i + aTerm[i].nPhrase+1;
      continue;
    }
    iNext = i + aTerm[i].nPhrase + 1;
    rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &pRight);
    if( rc ){
      queryClear(pQuery);
      return rc;
    }
    while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
      rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &pOr);
      iNext += aTerm[iNext].nPhrase + 1;
      if( rc ){
        queryClear(pQuery);
        return rc;
      }
      pNew = docListNew(DL_DOCIDS);
      docListOrMerge(pRight, pOr, pNew);
      docListDelete(pRight);
      docListDelete(pOr);
      pRight = pNew;
    }
    if( pLeft==0 ){
      pLeft = pRight;
    }else{
      pNew = docListNew(DL_DOCIDS);
      docListAndMerge(pLeft, pRight, pNew);
      docListDelete(pRight);
      docListDelete(pLeft);
      pLeft = pNew;
    }
  }

  if( nNot && pLeft==0 ){
    /* We do not yet know how to handle a query of only NOT terms */
    return SQLITE_ERROR;
  }

  /* Do the EXCEPT terms */
  for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
    if( !aTerm[i].isNot ) continue;
    rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &pRight);
    if( rc ){
      queryClear(pQuery);
      docListDelete(pLeft);
      return rc;
    }
    pNew = docListNew(DL_DOCIDS);
    docListExceptMerge(pLeft, pRight, pNew);
    docListDelete(pRight);
    docListDelete(pLeft);
    pLeft = pNew;
  }

  *pResult = pLeft;
  return rc;
}

/*
** This is the xFilter interface for the virtual table.  See
** the virtual table xFilter method documentation for additional
** information.
**
** If idxNum==QUERY_GENERIC then do a full table scan against
** the %_content table.
**
** If idxNum==QUERY_ROWID then do a rowid lookup for a single entry
** in the %_content table.
**
** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
** column on the left-hand side of the MATCH operator is column
** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
** side of the MATCH operator.
*/
/* TODO(shess) Upgrade the cursor initialization and destruction to
** account for fulltextFilter() being called multiple times on the
** same cursor.  The current solution is very fragile.  Apply fix to
** fts2 as appropriate.
*/
static int fulltextFilter(
  sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
  int idxNum, const char *idxStr,   /* Which indexing scheme to use */
  int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);
  int rc;
  char *zSql;

  TRACE(("FTS1 Filter %p\n",pCursor));

  zSql = sqlite3_mprintf("select rowid, * from %%_content %s",
                          idxNum==QUERY_GENERIC ? "" : "where rowid=?");
  sqlite3_finalize(c->pStmt);
  rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql);
  sqlite3_free(zSql);
  if( rc!=SQLITE_OK ) return rc;

  c->iCursorType = idxNum;
  switch( idxNum ){
    case QUERY_GENERIC:
      break;

    case QUERY_ROWID:
      rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
      if( rc!=SQLITE_OK ) return rc;
      break;

    default:   /* full-text search */
    {
      const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
      DocList *pResult;
      assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
      assert( argc==1 );
      queryClear(&c->q);
      rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &pResult, &c->q);
      if( rc!=SQLITE_OK ) return rc;
      if( c->result.pDoclist!=NULL ) docListDelete(c->result.pDoclist);
      readerInit(&c->result, pResult);
      break;
    }
  }

  return fulltextNext(pCursor);
}

/* This is the xEof method of the virtual table.  The SQLite core
** calls this routine to find out if it has reached the end of
** a query's results set.
*/
static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  return c->eof;
}

/* This is the xColumn method of the virtual table.  The SQLite
** core calls this method during a query when it needs the value
** of a column from the virtual table.  This method needs to use
** one of the sqlite3_result_*() routines to store the requested
** value back in the pContext.
*/
static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
                          sqlite3_context *pContext, int idxCol){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);

  if( idxCol<v->nColumn ){
    sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
    sqlite3_result_value(pContext, pVal);
  }else if( idxCol==v->nColumn ){
    /* The extra column whose name is the same as the table.
    ** Return a blob which is a pointer to the cursor
    */
    sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
  }
  return SQLITE_OK;
}

/* This is the xRowid method.  The SQLite core calls this routine to
** retrive the rowid for the current row of the result set.  The
** rowid should be written to *pRowid.
*/
static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;

  *pRowid = sqlite3_column_int64(c->pStmt, 0);
  return SQLITE_OK;
}

/* Add all terms in [zText] to the given hash table.  If [iColumn] > 0,
 * we also store positions and offsets in the hash table using the given
 * column number. */
static int buildTerms(fulltext_vtab *v, fts1Hash *terms, sqlite_int64 iDocid,
                      const char *zText, int iColumn){
  sqlite3_tokenizer *pTokenizer = v->pTokenizer;
  sqlite3_tokenizer_cursor *pCursor;
  const char *pToken;
  int nTokenBytes;
  int iStartOffset, iEndOffset, iPosition;
  int rc;

  rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  if( rc!=SQLITE_OK ) return rc;

  pCursor->pTokenizer = pTokenizer;
  while( SQLITE_OK==pTokenizer->pModule->xNext(pCursor,
                                               &pToken, &nTokenBytes,
                                               &iStartOffset, &iEndOffset,
                                               &iPosition) ){
    DocList *p;

    /* Positions can't be negative; we use -1 as a terminator internally. */
    if( iPosition<0 ){
      pTokenizer->pModule->xClose(pCursor);
      return SQLITE_ERROR;
    }

    p = fts1HashFind(terms, pToken, nTokenBytes);
    if( p==NULL ){
      p = docListNew(DL_DEFAULT);
      docListAddDocid(p, iDocid);
      fts1HashInsert(terms, pToken, nTokenBytes, p);
    }
    if( iColumn>=0 ){
      docListAddPosOffset(p, iColumn, iPosition, iStartOffset, iEndOffset);
    }
  }

  /* TODO(shess) Check return?  Should this be able to cause errors at
  ** this point?  Actually, same question about sqlite3_finalize(),
  ** though one could argue that failure there means that the data is
  ** not durable.  *ponder*
  */
  pTokenizer->pModule->xClose(pCursor);
  return rc;
}

/* Update the %_terms table to map the term [pTerm] to the given rowid. */
static int index_insert_term(fulltext_vtab *v, const char *pTerm, int nTerm,
                             DocList *d){
  sqlite_int64 iIndexRow;
  DocList doclist;
  int iSegment = 0, rc;

  rc = term_select(v, pTerm, nTerm, iSegment, &iIndexRow, &doclist);
  if( rc==SQLITE_DONE ){
    docListInit(&doclist, DL_DEFAULT, 0, 0);
    docListUpdate(&doclist, d);
    /* TODO(shess) Consider length(doclist)>CHUNK_MAX? */
    rc = term_insert(v, NULL, pTerm, nTerm, iSegment, &doclist);
    goto err;
  }
  if( rc!=SQLITE_ROW ) return SQLITE_ERROR;

  docListUpdate(&doclist, d);
  if( doclist.nData<=CHUNK_MAX ){
    rc = term_update(v, iIndexRow, &doclist);
    goto err;
  }

  /* Doclist doesn't fit, delete what's there, and accumulate
  ** forward.
  */
  rc = term_delete(v, iIndexRow);
  if( rc!=SQLITE_OK ) goto err;

  /* Try to insert the doclist into a higher segment bucket.  On
  ** failure, accumulate existing doclist with the doclist from that
  ** bucket, and put results in the next bucket.
  */
  iSegment++;
  while( (rc=term_insert(v, &iIndexRow, pTerm, nTerm, iSegment,
                         &doclist))!=SQLITE_OK ){
    sqlite_int64 iSegmentRow;
    DocList old;
    int rc2;

    /* Retain old error in case the term_insert() error was really an
    ** error rather than a bounced insert.
    */
    rc2 = term_select(v, pTerm, nTerm, iSegment, &iSegmentRow, &old);
    if( rc2!=SQLITE_ROW ) goto err;

    rc = term_delete(v, iSegmentRow);
    if( rc!=SQLITE_OK ) goto err;

    /* Reusing lowest-number deleted row keeps the index smaller. */
    if( iSegmentRow<iIndexRow ) iIndexRow = iSegmentRow;

    /* doclist contains the newer data, so accumulate it over old.
    ** Then steal accumulated data for doclist.
    */
    docListAccumulate(&old, &doclist);
    docListDestroy(&doclist);
    doclist = old;

    iSegment++;
  }

 err:
  docListDestroy(&doclist);
  return rc;
}

/* Add doclists for all terms in [pValues] to the hash table [terms]. */
static int insertTerms(fulltext_vtab *v, fts1Hash *terms, sqlite_int64 iRowid,
                sqlite3_value **pValues){
  int i;
  for(i = 0; i < v->nColumn ; ++i){
    char *zText = (char*)sqlite3_value_text(pValues[i]);
    int rc = buildTerms(v, terms, iRowid, zText, i);
    if( rc!=SQLITE_OK ) return rc;
  }
  return SQLITE_OK;
}

/* Add empty doclists for all terms in the given row's content to the hash
 * table [pTerms]. */
static int deleteTerms(fulltext_vtab *v, fts1Hash *pTerms, sqlite_int64 iRowid){
  const char **pValues;
  int i;

  int rc = content_select(v, iRowid, &pValues);
  if( rc!=SQLITE_OK ) return rc;

  for(i = 0 ; i < v->nColumn; ++i) {
    rc = buildTerms(v, pTerms, iRowid, pValues[i], -1);
    if( rc!=SQLITE_OK ) break;
  }

  freeStringArray(v->nColumn, pValues);
  return SQLITE_OK;
}

/* Insert a row into the %_content table; set *piRowid to be the ID of the
 * new row.  Fill [pTerms] with new doclists for the %_term table. */
static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid,
                        sqlite3_value **pValues,
                        sqlite_int64 *piRowid, fts1Hash *pTerms){
  int rc;

  rc = content_insert(v, pRequestRowid, pValues);  /* execute an SQL INSERT */
  if( rc!=SQLITE_OK ) return rc;
  *piRowid = sqlite3_last_insert_rowid(v->db);
  return insertTerms(v, pTerms, *piRowid, pValues);
}

/* Delete a row from the %_content table; fill [pTerms] with empty doclists
 * to be written to the %_term table. */
static int index_delete(fulltext_vtab *v, sqlite_int64 iRow, fts1Hash *pTerms){
  int rc = deleteTerms(v, pTerms, iRow);
  if( rc!=SQLITE_OK ) return rc;
  return content_delete(v, iRow);  /* execute an SQL DELETE */
}

/* Update a row in the %_content table; fill [pTerms] with new doclists for the
 * %_term table. */
static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
                        sqlite3_value **pValues, fts1Hash *pTerms){
  /* Generate an empty doclist for each term that previously appeared in this
   * row. */
  int rc = deleteTerms(v, pTerms, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
  if( rc!=SQLITE_OK ) return rc;

  /* Now add positions for terms which appear in the updated row. */
  return insertTerms(v, pTerms, iRow, pValues);
}

/* This function implements the xUpdate callback; it is the top-level entry
 * point for inserting, deleting or updating a row in a full-text table. */
static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
                   sqlite_int64 *pRowid){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  fts1Hash terms;   /* maps term string -> PosList */
  int rc;
  fts1HashElem *e;

  TRACE(("FTS1 Update %p\n", pVtab));
  
  fts1HashInit(&terms, FTS1_HASH_STRING, 1);

  if( nArg<2 ){
    rc = index_delete(v, sqlite3_value_int64(ppArg[0]), &terms);
  } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
    /* An update:
     * ppArg[0] = old rowid
     * ppArg[1] = new rowid
     * ppArg[2..2+v->nColumn-1] = values
     * ppArg[2+v->nColumn] = value for magic column (we ignore this)
     */
    sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
    if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
      sqlite3_value_int64(ppArg[1]) != rowid ){
      rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
    } else {
      assert( nArg==2+v->nColumn+1);
      rc = index_update(v, rowid, &ppArg[2], &terms);
    }
  } else {
    /* An insert:
     * ppArg[1] = requested rowid
     * ppArg[2..2+v->nColumn-1] = values
     * ppArg[2+v->nColumn] = value for magic column (we ignore this)
     */
    assert( nArg==2+v->nColumn+1);
    rc = index_insert(v, ppArg[1], &ppArg[2], pRowid, &terms);
  }

  if( rc==SQLITE_OK ){
    /* Write updated doclists to disk. */
    for(e=fts1HashFirst(&terms); e; e=fts1HashNext(e)){
      DocList *p = fts1HashData(e);
      rc = index_insert_term(v, fts1HashKey(e), fts1HashKeysize(e), p);
      if( rc!=SQLITE_OK ) break;
    }
  }

  /* clean up */
  for(e=fts1HashFirst(&terms); e; e=fts1HashNext(e)){
    DocList *p = fts1HashData(e);
    docListDelete(p);
  }
  fts1HashClear(&terms);

  return rc;
}

/*
** Implementation of the snippet() function for FTS1
*/
static void snippetFunc(
  sqlite3_context *pContext,
  int argc,
  sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc<1 ) return;
  if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
      sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
  }else{
    const char *zStart = "<b>";
    const char *zEnd = "</b>";
    const char *zEllipsis = "<b>...</b>";
    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    if( argc>=2 ){
      zStart = (const char*)sqlite3_value_text(argv[1]);
      if( argc>=3 ){
        zEnd = (const char*)sqlite3_value_text(argv[2]);
        if( argc>=4 ){
          zEllipsis = (const char*)sqlite3_value_text(argv[3]);
        }
      }
    }
    snippetAllOffsets(pCursor);
    snippetText(pCursor, zStart, zEnd, zEllipsis);
    sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
                        pCursor->snippet.nSnippet, SQLITE_STATIC);
  }
}

/*
** Implementation of the offsets() function for FTS1
*/
static void snippetOffsetsFunc(
  sqlite3_context *pContext,
  int argc,
  sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc<1 ) return;
  if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
      sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
  }else{
    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    snippetAllOffsets(pCursor);
    snippetOffsetText(&pCursor->snippet);
    sqlite3_result_text(pContext,
                        pCursor->snippet.zOffset, pCursor->snippet.nOffset,
                        SQLITE_STATIC);
  }
}

/*
** This routine implements the xFindFunction method for the FTS1
** virtual table.
*/
static int fulltextFindFunction(
  sqlite3_vtab *pVtab,
  int nArg,
  const char *zName,
  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  void **ppArg
){
  if( strcmp(zName,"snippet")==0 ){
    *pxFunc = snippetFunc;
    return 1;
  }else if( strcmp(zName,"offsets")==0 ){
    *pxFunc = snippetOffsetsFunc;
    return 1;
  }
  return 0;
}

/*
** Rename an fts1 table.
*/
static int fulltextRename(
  sqlite3_vtab *pVtab,
  const char *zName
){
  fulltext_vtab *p = (fulltext_vtab *)pVtab;
  int rc = SQLITE_NOMEM;
  char *zSql = sqlite3_mprintf(
    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
    "ALTER TABLE %Q.'%q_term' RENAME TO '%q_term';"
    , p->zDb, p->zName, zName
    , p->zDb, p->zName, zName
  );
  if( zSql ){
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  return rc;
}

static const sqlite3_module fulltextModule = {
  /* iVersion      */ 0,
  /* xCreate       */ fulltextCreate,
  /* xConnect      */ fulltextConnect,
  /* xBestIndex    */ fulltextBestIndex,
  /* xDisconnect   */ fulltextDisconnect,
  /* xDestroy      */ fulltextDestroy,
  /* xOpen         */ fulltextOpen,
  /* xClose        */ fulltextClose,
  /* xFilter       */ fulltextFilter,
  /* xNext         */ fulltextNext,
  /* xEof          */ fulltextEof,
  /* xColumn       */ fulltextColumn,
  /* xRowid        */ fulltextRowid,
  /* xUpdate       */ fulltextUpdate,
  /* xBegin        */ 0, 
  /* xSync         */ 0,
  /* xCommit       */ 0,
  /* xRollback     */ 0,
  /* xFindFunction */ fulltextFindFunction,
  /* xRename       */ fulltextRename,
};

int sqlite3Fts1Init(sqlite3 *db){
  sqlite3_overload_function(db, "snippet", -1);
  sqlite3_overload_function(db, "offsets", -1);
  return sqlite3_create_module(db, "fts1", &fulltextModule, 0);
}

#if !SQLITE_CORE
int sqlite3_extension_init(sqlite3 *db, char **pzErrMsg,
                           const sqlite3_api_routines *pApi){
  SQLITE_EXTENSION_INIT2(pApi)
  return sqlite3Fts1Init(db);
}
#endif

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */

Added ext/fts1/fts1.h.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

int sqlite3Fts1Init(sqlite3 *db);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */

Added ext/fts1/fts1_hash.c.



































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables used in SQLite.
** We've modified it slightly to serve as a standalone hash table
** implementation for the full-text indexing module.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>

/*
** The code in this file is only compiled if:
**
**     * The FTS1 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS1 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS1 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)


#include "fts1_hash.h"

static void *malloc_and_zero(int n){
  void *p = malloc(n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
** keyClass is one of the constants 
** FTS1_HASH_BINARY or FTS1_HASH_STRING.  The value of keyClass 
** determines what kind of key the hash table will use.  "copyKey" is
** true if the hash table should make its own private copy of keys and
** false if it should just use the supplied pointer.
*/
void sqlite3Fts1HashInit(fts1Hash *pNew, int keyClass, int copyKey){
  assert( pNew!=0 );
  assert( keyClass>=FTS1_HASH_STRING && keyClass<=FTS1_HASH_BINARY );
  pNew->keyClass = keyClass;
  pNew->copyKey = copyKey;
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->xMalloc = malloc_and_zero;
  pNew->xFree = free;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite3Fts1HashClear(fts1Hash *pH){
  fts1HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    fts1HashElem *next_elem = elem->next;
    if( pH->copyKey && elem->pKey ){
      pH->xFree(elem->pKey);
    }
    pH->xFree(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** Hash and comparison functions when the mode is FTS1_HASH_STRING
*/
static int strHash(const void *pKey, int nKey){
  const char *z = (const char *)pKey;
  int h = 0;
  if( nKey<=0 ) nKey = (int) strlen(z);
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ *z++;
    nKey--;
  }
  return h & 0x7fffffff;
}
static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
}

/*
** Hash and comparison functions when the mode is FTS1_HASH_BINARY
*/
static int binHash(const void *pKey, int nKey){
  int h = 0;
  const char *z = (const char *)pKey;
  while( nKey-- > 0 ){
    h = (h<<3) ^ h ^ *(z++);
  }
  return h & 0x7fffffff;
}
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return memcmp(pKey1,pKey2,n1);
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** The C syntax in this function definition may be unfamilar to some 
** programmers, so we provide the following additional explanation:
**
** The name of the function is "hashFunction".  The function takes a
** single parameter "keyClass".  The return value of hashFunction()
** is a pointer to another function.  Specifically, the return value
** of hashFunction() is a pointer to a function that takes two parameters
** with types "const void*" and "int" and returns an "int".
*/
static int (*hashFunction(int keyClass))(const void*,int){
  if( keyClass==FTS1_HASH_STRING ){
    return &strHash;
  }else{
    assert( keyClass==FTS1_HASH_BINARY );
    return &binHash;
  }
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** For help in interpreted the obscure C code in the function definition,
** see the header comment on the previous function.
*/
static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
  if( keyClass==FTS1_HASH_STRING ){
    return &strCompare;
  }else{
    assert( keyClass==FTS1_HASH_BINARY );
    return &binCompare;
  }
}

/* Link an element into the hash table
*/
static void insertElement(
  fts1Hash *pH,            /* The complete hash table */
  struct _fts1ht *pEntry,  /* The entry into which pNew is inserted */
  fts1HashElem *pNew       /* The element to be inserted */
){
  fts1HashElem *pHead;     /* First element already in pEntry */
  pHead = pEntry->chain;
  if( pHead ){
    pNew->next = pHead;
    pNew->prev = pHead->prev;
    if( pHead->prev ){ pHead->prev->next = pNew; }
    else             { pH->first = pNew; }
    pHead->prev = pNew;
  }else{
    pNew->next = pH->first;
    if( pH->first ){ pH->first->prev = pNew; }
    pNew->prev = 0;
    pH->first = pNew;
  }
  pEntry->count++;
  pEntry->chain = pNew;
}


/* Resize the hash table so that it cantains "new_size" buckets.
** "new_size" must be a power of 2.  The hash table might fail 
** to resize if sqliteMalloc() fails.
*/
static void rehash(fts1Hash *pH, int new_size){
  struct _fts1ht *new_ht;          /* The new hash table */
  fts1HashElem *elem, *next_elem;  /* For looping over existing elements */
  int (*xHash)(const void*,int);   /* The hash function */

  assert( (new_size & (new_size-1))==0 );
  new_ht = (struct _fts1ht *)pH->xMalloc( new_size*sizeof(struct _fts1ht) );
  if( new_ht==0 ) return;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size;
  xHash = hashFunction(pH->keyClass);
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
}

/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static fts1HashElem *findElementGivenHash(
  const fts1Hash *pH, /* The pH to be searched */
  const void *pKey,   /* The key we are searching for */
  int nKey,
  int h               /* The hash for this key. */
){
  fts1HashElem *elem;            /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */
  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */

  if( pH->ht ){
    struct _fts1ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
    xCompare = compareFunction(pH->keyClass);
    while( count-- && elem ){
      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
        return elem;
      }
      elem = elem->next;
    }
  }
  return 0;
}

/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
  fts1Hash *pH,         /* The pH containing "elem" */
  fts1HashElem* elem,   /* The element to be removed from the pH */
  int h                 /* Hash value for the element */
){
  struct _fts1ht *pEntry;
  if( elem->prev ){
    elem->prev->next = elem->next; 
  }else{
    pH->first = elem->next;
  }
  if( elem->next ){
    elem->next->prev = elem->prev;
  }
  pEntry = &pH->ht[h];
  if( pEntry->chain==elem ){
    pEntry->chain = elem->next;
  }
  pEntry->count--;
  if( pEntry->count<=0 ){
    pEntry->chain = 0;
  }
  if( pH->copyKey && elem->pKey ){
    pH->xFree(elem->pKey);
  }
  pH->xFree( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    fts1HashClear(pH);
  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
void *sqlite3Fts1HashFind(const fts1Hash *pH, const void *pKey, int nKey){
  int h;                 /* A hash on key */
  fts1HashElem *elem;    /* The element that matches key */
  int (*xHash)(const void*,int);  /* The hash function */

  if( pH==0 || pH->ht==0 ) return 0;
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  h = (*xHash)(pKey,nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
  return elem ? elem->data : 0;
}

/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *sqlite3Fts1HashInsert(
  fts1Hash *pH,        /* The hash table to insert into */
  const void *pKey,    /* The key */
  int nKey,            /* Number of bytes in the key */
  void *data           /* The data */
){
  int hraw;                 /* Raw hash value of the key */
  int h;                    /* the hash of the key modulo hash table size */
  fts1HashElem *elem;       /* Used to loop thru the element list */
  fts1HashElem *new_elem;   /* New element added to the pH */
  int (*xHash)(const void*,int);  /* The hash function */

  assert( pH!=0 );
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  hraw = (*xHash)(pKey, nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (fts1HashElem*)pH->xMalloc( sizeof(fts1HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = pH->xMalloc( nKey );
    if( new_elem->pKey==0 ){
      pH->xFree(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->htsize==0 ){
    rehash(pH,8);
    if( pH->htsize==0 ){
      pH->count = 0;
      pH->xFree(new_elem);
      return data;
    }
  }
  if( pH->count > pH->htsize ){
    rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  insertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */

Added ext/fts1/fts1_hash.h.

































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in SQLite.  We've modified it slightly to serve as a standalone
** hash table implementation for the full-text indexing module.
**
*/
#ifndef _FTS1_HASH_H_
#define _FTS1_HASH_H_

/* Forward declarations of structures. */
typedef struct fts1Hash fts1Hash;
typedef struct fts1HashElem fts1HashElem;

/* A complete hash table is an instance of the following structure.
** The internals of this structure are intended to be opaque -- client
** code should not attempt to access or modify the fields of this structure
** directly.  Change this structure only by using the routines below.
** However, many of the "procedures" and "functions" for modifying and
** accessing this structure are really macros, so we can't really make
** this structure opaque.
*/
struct fts1Hash {
  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
  char copyKey;           /* True if copy of key made on insert */
  int count;              /* Number of entries in this table */
  fts1HashElem *first;    /* The first element of the array */
  void *(*xMalloc)(int);  /* malloc() function to use */
  void (*xFree)(void *);  /* free() function to use */
  int htsize;             /* Number of buckets in the hash table */
  struct _fts1ht {        /* the hash table */
    int count;               /* Number of entries with this hash */
    fts1HashElem *chain;     /* Pointer to first entry with this hash */
  } *ht;
};

/* Each element in the hash table is an instance of the following 
** structure.  All elements are stored on a single doubly-linked list.
**
** Again, this structure is intended to be opaque, but it can't really
** be opaque because it is used by macros.
*/
struct fts1HashElem {
  fts1HashElem *next, *prev; /* Next and previous elements in the table */
  void *data;                /* Data associated with this element */
  void *pKey; int nKey;      /* Key associated with this element */
};

/*
** There are 2 different modes of operation for a hash table:
**
**   FTS1_HASH_STRING        pKey points to a string that is nKey bytes long
**                           (including the null-terminator, if any).  Case
**                           is respected in comparisons.
**
**   FTS1_HASH_BINARY        pKey points to binary data nKey bytes long. 
**                           memcmp() is used to compare keys.
**
** A copy of the key is made if the copyKey parameter to fts1HashInit is 1.  
*/
#define FTS1_HASH_STRING    1
#define FTS1_HASH_BINARY    2

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite3Fts1HashInit(fts1Hash*, int keytype, int copyKey);
void *sqlite3Fts1HashInsert(fts1Hash*, const void *pKey, int nKey, void *pData);
void *sqlite3Fts1HashFind(const fts1Hash*, const void *pKey, int nKey);
void sqlite3Fts1HashClear(fts1Hash*);

/*
** Shorthand for the functions above
*/
#define fts1HashInit   sqlite3Fts1HashInit
#define fts1HashInsert sqlite3Fts1HashInsert
#define fts1HashFind   sqlite3Fts1HashFind
#define fts1HashClear  sqlite3Fts1HashClear

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   fts1Hash h;
**   fts1HashElem *p;
**   ...
**   for(p=fts1HashFirst(&h); p; p=fts1HashNext(p)){
**     SomeStructure *pData = fts1HashData(p);
**     // do something with pData
**   }
*/
#define fts1HashFirst(H)  ((H)->first)
#define fts1HashNext(E)   ((E)->next)
#define fts1HashData(E)   ((E)->data)
#define fts1HashKey(E)    ((E)->pKey)
#define fts1HashKeysize(E) ((E)->nKey)

/*
** Number of entries in a hash table
*/
#define fts1HashCount(H)  ((H)->count)

#endif /* _FTS1_HASH_H_ */

Added ext/fts1/fts1_porter.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/*
** 2006 September 30
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Implementation of the full-text-search tokenizer that implements
** a Porter stemmer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS1 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS1 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS1 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)


#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts1_tokenizer.h"

/*
** Class derived from sqlite3_tokenizer
*/
typedef struct porter_tokenizer {
  sqlite3_tokenizer base;      /* Base class */
} porter_tokenizer;

/*
** Class derived from sqlit3_tokenizer_cursor
*/
typedef struct porter_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *zInput;          /* input we are tokenizing */
  int nInput;                  /* size of the input */
  int iOffset;                 /* current position in zInput */
  int iToken;                  /* index of next token to be returned */
  char *zToken;                /* storage for current token */
  int nAllocated;              /* space allocated to zToken buffer */
} porter_tokenizer_cursor;


/* Forward declaration */
static const sqlite3_tokenizer_module porterTokenizerModule;


/*
** Create a new tokenizer instance.
*/
static int porterCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  porter_tokenizer *t;
  t = (porter_tokenizer *) calloc(sizeof(*t), 1);
  if( t==NULL ) return SQLITE_NOMEM;

  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  free(pTokenizer);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is zInput[0..nInput-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int porterOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *zInput, int nInput,        /* String to be tokenized */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  porter_tokenizer_cursor *c;

  c = (porter_tokenizer_cursor *) malloc(sizeof(*c));
  if( c==NULL ) return SQLITE_NOMEM;

  c->zInput = zInput;
  if( zInput==0 ){
    c->nInput = 0;
  }else if( nInput<0 ){
    c->nInput = (int)strlen(zInput);
  }else{
    c->nInput = nInput;
  }
  c->iOffset = 0;                 /* start tokenizing at the beginning */
  c->iToken = 0;
  c->zToken = NULL;               /* no space allocated, yet. */
  c->nAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to
** porterOpen() above.
*/
static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  free(c->zToken);
  free(c);
  return SQLITE_OK;
}
/*
** Vowel or consonant
*/
static const char cType[] = {
   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   1, 1, 1, 2, 1
};

/*
** isConsonant() and isVowel() determine if their first character in
** the string they point to is a consonant or a vowel, according
** to Porter ruls.  
**
** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
** 'Y' is a consonant unless it follows another consonant,
** in which case it is a vowel.
**
** In these routine, the letters are in reverse order.  So the 'y' rule
** is that 'y' is a consonant unless it is followed by another
** consonent.
*/
static int isVowel(const char*);
static int isConsonant(const char *z){
  int j;
  char x = *z;
  if( x==0 ) return 0;
  assert( x>='a' && x<='z' );
  j = cType[x-'a'];
  if( j<2 ) return j;
  return z[1]==0 || isVowel(z + 1);
}
static int isVowel(const char *z){
  int j;
  char x = *z;
  if( x==0 ) return 0;
  assert( x>='a' && x<='z' );
  j = cType[x-'a'];
  if( j<2 ) return 1-j;
  return isConsonant(z + 1);
}

/*
** Let any sequence of one or more vowels be represented by V and let
** C be sequence of one or more consonants.  Then every word can be
** represented as:
**
**           [C] (VC){m} [V]
**
** In prose:  A word is an optional consonant followed by zero or
** vowel-consonant pairs followed by an optional vowel.  "m" is the
** number of vowel consonant pairs.  This routine computes the value
** of m for the first i bytes of a word.
**
** Return true if the m-value for z is 1 or more.  In other words,
** return true if z contains at least one vowel that is followed
** by a consonant.
**
** In this routine z[] is in reverse order.  So we are really looking
** for an instance of of a consonant followed by a vowel.
*/
static int m_gt_0(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/* Like mgt0 above except we are looking for a value of m which is
** exactly 1
*/
static int m_eq_1(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 1;
  while( isConsonant(z) ){ z++; }
  return *z==0;
}

/* Like mgt0 above except we are looking for a value of m>1 instead
** or m>0
*/
static int m_gt_1(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/*
** Return TRUE if there is a vowel anywhere within z[0..n-1]
*/
static int hasVowel(const char *z){
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/*
** Return TRUE if the word ends in a double consonant.
**
** The text is reversed here. So we are really looking at
** the first two characters of z[].
*/
static int doubleConsonant(const char *z){
  return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
}

/*
** Return TRUE if the word ends with three letters which
** are consonant-vowel-consonent and where the final consonant
** is not 'w', 'x', or 'y'.
**
** The word is reversed here.  So we are really checking the
** first three letters and the first one cannot be in [wxy].
*/
static int star_oh(const char *z){
  return
    z[0]!=0 && isConsonant(z) &&
    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
    z[1]!=0 && isVowel(z+1) &&
    z[2]!=0 && isConsonant(z+2);
}

/*
** If the word ends with zFrom and xCond() is true for the stem
** of the word that preceeds the zFrom ending, then change the 
** ending to zTo.
**
** The input word *pz and zFrom are both in reverse order.  zTo
** is in normal order. 
**
** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
** match.  Not that TRUE is returned even if xCond() fails and
** no substitution occurs.
*/
static int stem(
  char **pz,             /* The word being stemmed (Reversed) */
  const char *zFrom,     /* If the ending matches this... (Reversed) */
  const char *zTo,       /* ... change the ending to this (not reversed) */
  int (*xCond)(const char*)   /* Condition that must be true */
){
  char *z = *pz;
  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  if( *zFrom!=0 ) return 0;
  if( xCond && !xCond(z) ) return 1;
  while( *zTo ){
    *(--z) = *(zTo++);
  }
  *pz = z;
  return 1;
}

/*
** This is the fallback stemmer used when the porter stemmer is
** inappropriate.  The input word is copied into the output with
** US-ASCII case folding.  If the input word is too long (more
** than 20 bytes if it contains no digits or more than 6 bytes if
** it contains digits) then word is truncated to 20 or 6 bytes
** by taking 10 or 3 bytes from the beginning and end.
*/
static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  int i, mx, j;
  int hasDigit = 0;
  for(i=0; i<nIn; i++){
    int c = zIn[i];
    if( c>='A' && c<='Z' ){
      zOut[i] = c - 'A' + 'a';
    }else{
      if( c>='0' && c<='9' ) hasDigit = 1;
      zOut[i] = c;
    }
  }
  mx = hasDigit ? 3 : 10;
  if( nIn>mx*2 ){
    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
      zOut[j] = zOut[i];
    }
    i = j;
  }
  zOut[i] = 0;
  *pnOut = i;
}


/*
** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
** zOut is at least big enough to hold nIn bytes.  Write the actual
** size of the output word (exclusive of the '\0' terminator) into *pnOut.
**
** Any upper-case characters in the US-ASCII character set ([A-Z])
** are converted to lower case.  Upper-case UTF characters are
** unchanged.
**
** Words that are longer than about 20 bytes are stemmed by retaining
** a few bytes from the beginning and the end of the word.  If the
** word contains digits, 3 bytes are taken from the beginning and
** 3 bytes from the end.  For long words without digits, 10 bytes
** are taken from each end.  US-ASCII case folding still applies.
** 
** If the input word contains not digits but does characters not 
** in [a-zA-Z] then no stemming is attempted and this routine just 
** copies the input into the input into the output with US-ASCII
** case folding.
**
** Stemming never increases the length of the word.  So there is
** no chance of overflowing the zOut buffer.
*/
static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  int i, j, c;
  char zReverse[28];
  char *z, *z2;
  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
    /* The word is too big or too small for the porter stemmer.
    ** Fallback to the copy stemmer */
    copy_stemmer(zIn, nIn, zOut, pnOut);
    return;
  }
  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
    c = zIn[i];
    if( c>='A' && c<='Z' ){
      zReverse[j] = c + 'a' - 'A';
    }else if( c>='a' && c<='z' ){
      zReverse[j] = c;
    }else{
      /* The use of a character not in [a-zA-Z] means that we fallback
      ** to the copy stemmer */
      copy_stemmer(zIn, nIn, zOut, pnOut);
      return;
    }
  }
  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  z = &zReverse[j+1];


  /* Step 1a */
  if( z[0]=='s' ){
    if(
     !stem(&z, "sess", "ss", 0) &&
     !stem(&z, "sei", "i", 0)  &&
     !stem(&z, "ss", "ss", 0)
    ){
      z++;
    }
  }

  /* Step 1b */  
  z2 = z;
  if( stem(&z, "dee", "ee", m_gt_0) ){
    /* Do nothing.  The work was all in the test */
  }else if( 
     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
      && z!=z2
  ){
     if( stem(&z, "ta", "ate", 0) ||
         stem(&z, "lb", "ble", 0) ||
         stem(&z, "zi", "ize", 0) ){
       /* Do nothing.  The work was all in the test */
     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
       z++;
     }else if( m_eq_1(z) && star_oh(z) ){
       *(--z) = 'e';
     }
  }

  /* Step 1c */
  if( z[0]=='y' && hasVowel(z+1) ){
    z[0] = 'i';
  }

  /* Step 2 */
  switch( z[1] ){
   case 'a':
     stem(&z, "lanoita", "ate", m_gt_0) ||
     stem(&z, "lanoit", "tion", m_gt_0);
     break;
   case 'c':
     stem(&z, "icne", "ence", m_gt_0) ||
     stem(&z, "icna", "ance", m_gt_0);
     break;
   case 'e':
     stem(&z, "rezi", "ize", m_gt_0);
     break;
   case 'g':
     stem(&z, "igol", "log", m_gt_0);
     break;
   case 'l':
     stem(&z, "ilb", "ble", m_gt_0) ||
     stem(&z, "illa", "al", m_gt_0) ||
     stem(&z, "iltne", "ent", m_gt_0) ||
     stem(&z, "ile", "e", m_gt_0) ||
     stem(&z, "ilsuo", "ous", m_gt_0);
     break;
   case 'o':
     stem(&z, "noitazi", "ize", m_gt_0) ||
     stem(&z, "noita", "ate", m_gt_0) ||
     stem(&z, "rota", "ate", m_gt_0);
     break;
   case 's':
     stem(&z, "msila", "al", m_gt_0) ||
     stem(&z, "ssenevi", "ive", m_gt_0) ||
     stem(&z, "ssenluf", "ful", m_gt_0) ||
     stem(&z, "ssensuo", "ous", m_gt_0);
     break;
   case 't':
     stem(&z, "itila", "al", m_gt_0) ||
     stem(&z, "itivi", "ive", m_gt_0) ||
     stem(&z, "itilib", "ble", m_gt_0);
     break;
  }

  /* Step 3 */
  switch( z[0] ){
   case 'e':
     stem(&z, "etaci", "ic", m_gt_0) ||
     stem(&z, "evita", "", m_gt_0)   ||
     stem(&z, "ezila", "al", m_gt_0);
     break;
   case 'i':
     stem(&z, "itici", "ic", m_gt_0);
     break;
   case 'l':
     stem(&z, "laci", "ic", m_gt_0) ||
     stem(&z, "luf", "", m_gt_0);
     break;
   case 's':
     stem(&z, "ssen", "", m_gt_0);
     break;
  }

  /* Step 4 */
  switch( z[1] ){
   case 'a':
     if( z[0]=='l' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'c':
     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
       z += 4;
     }
     break;
   case 'e':
     if( z[0]=='r' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'i':
     if( z[0]=='c' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'l':
     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
       z += 4;
     }
     break;
   case 'n':
     if( z[0]=='t' ){
       if( z[2]=='a' ){
         if( m_gt_1(z+3) ){
           z += 3;
         }
       }else if( z[2]=='e' ){
         stem(&z, "tneme", "", m_gt_1) ||
         stem(&z, "tnem", "", m_gt_1) ||
         stem(&z, "tne", "", m_gt_1);
       }
     }
     break;
   case 'o':
     if( z[0]=='u' ){
       if( m_gt_1(z+2) ){
         z += 2;
       }
     }else if( z[3]=='s' || z[3]=='t' ){
       stem(&z, "noi", "", m_gt_1);
     }
     break;
   case 's':
     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
   case 't':
     stem(&z, "eta", "", m_gt_1) ||
     stem(&z, "iti", "", m_gt_1);
     break;
   case 'u':
     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
   case 'v':
   case 'z':
     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
  }

  /* Step 5a */
  if( z[0]=='e' ){
    if( m_gt_1(z+1) ){
      z++;
    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
      z++;
    }
  }

  /* Step 5b */
  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
    z++;
  }

  /* z[] is now the stemmed word in reverse order.  Flip it back
  ** around into forward order and return.
  */
  *pnOut = i = strlen(z);
  zOut[i] = 0;
  while( *z ){
    zOut[--i] = *(z++);
  }
}

/*
** Characters that can be part of a token.  We assume any character
** whose value is greater than 0x80 (any UTF character) can be
** part of a token.  In other words, delimiters all must have
** values of 0x7f or lower.
*/
static const char isIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define idChar(C)  (((ch=C)&0x80)!=0 || (ch>0x2f && isIdChar[ch-0x30]))
#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !isIdChar[ch-0x30]))

/*
** Extract the next token from a tokenization cursor.  The cursor must
** have been opened by a prior call to porterOpen().
*/
static int porterNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
  const char **pzToken,               /* OUT: *pzToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  const char *z = c->zInput;

  while( c->iOffset<c->nInput ){
    int iStartOffset, ch;

    /* Scan past delimiter characters */
    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
      c->iOffset++;
    }

    /* Count non-delimiter characters. */
    iStartOffset = c->iOffset;
    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
      c->iOffset++;
    }

    if( c->iOffset>iStartOffset ){
      int n = c->iOffset-iStartOffset;
      if( n>c->nAllocated ){
        c->nAllocated = n+20;
        c->zToken = realloc(c->zToken, c->nAllocated);
        if( c->zToken==NULL ) return SQLITE_NOMEM;
      }
      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
      *pzToken = c->zToken;
      *piStartOffset = iStartOffset;
      *piEndOffset = c->iOffset;
      *piPosition = c->iToken++;
      return SQLITE_OK;
    }
  }
  return SQLITE_DONE;
}

/*
** The set of routines that implement the porter-stemmer tokenizer
*/
static const sqlite3_tokenizer_module porterTokenizerModule = {
  0,
  porterCreate,
  porterDestroy,
  porterOpen,
  porterClose,
  porterNext,
};

/*
** Allocate a new porter tokenizer.  Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts1PorterTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &porterTokenizerModule;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */

Added ext/fts1/fts1_tokenizer.h.





















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
** 2006 July 10
**
** The author disclaims copyright to this source code.
**
*************************************************************************
** Defines the interface to tokenizers used by fulltext-search.  There
** are three basic components:
**
** sqlite3_tokenizer_module is a singleton defining the tokenizer
** interface functions.  This is essentially the class structure for
** tokenizers.
**
** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
** including customization information defined at creation time.
**
** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
** tokens from a particular input.
*/
#ifndef _FTS1_TOKENIZER_H_
#define _FTS1_TOKENIZER_H_

/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
** If tokenizers are to be allowed to call sqlite3_*() functions, then
** we will need a way to register the API consistently.
*/
#include "sqlite3.h"

/*
** Structures used by the tokenizer interface.
*/
typedef struct sqlite3_tokenizer sqlite3_tokenizer;
typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;

struct sqlite3_tokenizer_module {
  int iVersion;                  /* currently 0 */

  /*
  ** Create and destroy a tokenizer.  argc/argv are passed down from
  ** the fulltext virtual table creation to allow customization.
  */
  int (*xCreate)(int argc, const char *const*argv,
                 sqlite3_tokenizer **ppTokenizer);
  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);

  /*
  ** Tokenize a particular input.  Call xOpen() to prepare to
  ** tokenize, xNext() repeatedly until it returns SQLITE_DONE, then
  ** xClose() to free any internal state.  The pInput passed to
  ** xOpen() must exist until the cursor is closed.  The ppToken
  ** result from xNext() is only valid until the next call to xNext()
  ** or until xClose() is called.
  */
  /* TODO(shess) current implementation requires pInput to be
  ** nul-terminated.  This should either be fixed, or pInput/nBytes
  ** should be converted to zInput.
  */
  int (*xOpen)(sqlite3_tokenizer *pTokenizer,
               const char *pInput, int nBytes,
               sqlite3_tokenizer_cursor **ppCursor);
  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
               const char **ppToken, int *pnBytes,
               int *piStartOffset, int *piEndOffset, int *piPosition);
};

struct sqlite3_tokenizer {
  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
  /* Tokenizer implementations will typically add additional fields */
};

struct sqlite3_tokenizer_cursor {
  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
  /* Tokenizer implementations will typically add additional fields */
};

/*
** Get the module for a tokenizer which generates tokens based on a
** set of non-token characters.  The default is to break tokens at any
** non-alnum character, though the set of delimiters can also be
** specified by the first argv argument to xCreate().
*/
/* TODO(shess) This doesn't belong here.  Need some sort of
** registration process.
*/
void sqlite3Fts1SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts1PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);

#endif /* _FTS1_TOKENIZER_H_ */

Added ext/fts1/fts1_tokenizer1.c.



























































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
** The author disclaims copyright to this source code.
**
*************************************************************************
** Implementation of the "simple" full-text-search tokenizer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS1 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS1 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS1 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)


#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts1_tokenizer.h"

typedef struct simple_tokenizer {
  sqlite3_tokenizer base;
  char delim[128];             /* flag ASCII delimiters */
} simple_tokenizer;

typedef struct simple_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *pInput;          /* input we are tokenizing */
  int nBytes;                  /* size of the input */
  int iOffset;                 /* current position in pInput */
  int iToken;                  /* index of next token to be returned */
  char *pToken;                /* storage for current token */
  int nTokenAllocated;         /* space allocated to zToken buffer */
} simple_tokenizer_cursor;


/* Forward declaration */
static const sqlite3_tokenizer_module simpleTokenizerModule;

static int isDelim(simple_tokenizer *t, unsigned char c){
  return c<0x80 && t->delim[c];
}

/*
** Create a new tokenizer instance.
*/
static int simpleCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  simple_tokenizer *t;

  t = (simple_tokenizer *) calloc(sizeof(*t), 1);
  if( t==NULL ) return SQLITE_NOMEM;

  /* TODO(shess) Delimiters need to remain the same from run to run,
  ** else we need to reindex.  One solution would be a meta-table to
  ** track such information in the database, then we'd only want this
  ** information on the initial create.
  */
  if( argc>1 ){
    int i, n = strlen(argv[1]);
    for(i=0; i<n; i++){
      unsigned char ch = argv[1][i];
      /* We explicitly don't support UTF-8 delimiters for now. */
      if( ch>=0x80 ){
        free(t);
        return SQLITE_ERROR;
      }
      t->delim[ch] = 1;
    }
  } else {
    /* Mark non-alphanumeric ASCII characters as delimiters */
    int i;
    for(i=1; i<0x80; i++){
      t->delim[i] = !isalnum(i);
    }
  }

  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  free(pTokenizer);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is pInput[0..nBytes-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int simpleOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *pInput, int nBytes,        /* String to be tokenized */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  simple_tokenizer_cursor *c;

  c = (simple_tokenizer_cursor *) malloc(sizeof(*c));
  if( c==NULL ) return SQLITE_NOMEM;

  c->pInput = pInput;
  if( pInput==0 ){
    c->nBytes = 0;
  }else if( nBytes<0 ){
    c->nBytes = (int)strlen(pInput);
  }else{
    c->nBytes = nBytes;
  }
  c->iOffset = 0;                 /* start tokenizing at the beginning */
  c->iToken = 0;
  c->pToken = NULL;               /* no space allocated, yet. */
  c->nTokenAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to
** simpleOpen() above.
*/
static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  free(c->pToken);
  free(c);
  return SQLITE_OK;
}

/*
** Extract the next token from a tokenization cursor.  The cursor must
** have been opened by a prior call to simpleOpen().
*/
static int simpleNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
  const char **ppToken,               /* OUT: *ppToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  unsigned char *p = (unsigned char *)c->pInput;

  while( c->iOffset<c->nBytes ){
    int iStartOffset;

    /* Scan past delimiter characters */
    while( c->iOffset<c->nBytes && isDelim(t, p[c->iOffset]) ){
      c->iOffset++;
    }

    /* Count non-delimiter characters. */
    iStartOffset = c->iOffset;
    while( c->iOffset<c->nBytes && !isDelim(t, p[c->iOffset]) ){
      c->iOffset++;
    }

    if( c->iOffset>iStartOffset ){
      int i, n = c->iOffset-iStartOffset;
      if( n>c->nTokenAllocated ){
        c->nTokenAllocated = n+20;
        c->pToken = realloc(c->pToken, c->nTokenAllocated);
        if( c->pToken==NULL ) return SQLITE_NOMEM;
      }
      for(i=0; i<n; i++){
        /* TODO(shess) This needs expansion to handle UTF-8
        ** case-insensitivity.
        */
        unsigned char ch = p[iStartOffset+i];
        c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
      }
      *ppToken = c->pToken;
      *pnBytes = n;
      *piStartOffset = iStartOffset;
      *piEndOffset = c->iOffset;
      *piPosition = c->iToken++;

      return SQLITE_OK;
    }
  }
  return SQLITE_DONE;
}

/*
** The set of routines that implement the simple tokenizer
*/
static const sqlite3_tokenizer_module simpleTokenizerModule = {
  0,
  simpleCreate,
  simpleDestroy,
  simpleOpen,
  simpleClose,
  simpleNext,
};

/*
** Allocate a new simple tokenizer.  Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts1SimpleTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &simpleTokenizerModule;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */

Added ext/fts1/fulltext.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
/* The author disclaims copyright to this source code.
 *
 * This is an SQLite module implementing full-text search.
 */

#include <assert.h>
#if !defined(__APPLE__)
#include <malloc.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fulltext.h"
#include "ft_hash.h"
#include "tokenizer.h"
#include "sqlite3.h"
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1

/* utility functions */

/* We encode variable-length integers in little-endian order using seven bits
 * per byte as follows:
**
** KEY:
**         A = 0xxxxxxx    7 bits of data and one flag bit
**         B = 1xxxxxxx    7 bits of data and one flag bit
**
**  7 bits - A
** 14 bits - BA
** 21 bits - BBA
** and so on.
*/

/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
#define VARINT_MAX 10

/* Write a 64-bit variable-length integer to memory starting at p[0].
 * The length of data written will be between 1 and VARINT_MAX bytes.
 * The number of bytes written is returned. */
static int putVarint(char *p, sqlite_int64 v){
  unsigned char *q = (unsigned char *) p;
  sqlite_uint64 vu = v;
  do{
    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
    vu >>= 7;
  }while( vu!=0 );
  q[-1] &= 0x7f;  /* turn off high bit in final byte */
  assert( q - (unsigned char *)p <= VARINT_MAX );
  return (int) (q - (unsigned char *)p);
}

/* Read a 64-bit variable-length integer from memory starting at p[0].
 * Return the number of bytes read, or 0 on error.
 * The value is stored in *v. */
static int getVarint(const char *p, sqlite_int64 *v){
  const unsigned char *q = (const unsigned char *) p;
  sqlite_uint64 x = 0, y = 1;
  while( (*q & 0x80) == 0x80 ){
    x += y * (*q++ & 0x7f);
    y <<= 7;
    if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
      assert( 0 );
      return 0;
    }
  }
  x += y * (*q++);
  *v = (sqlite_int64) x;
  return (int) (q - (unsigned char *)p);
}

static int getVarint32(const char *p, int *pi){
 sqlite_int64 i;
 int ret = getVarint(p, &i);
 *pi = (int) i;
 assert( *pi==i );
 return ret;
}

/*** Document lists ***
 *
 * A document list holds a sorted list of varint-encoded document IDs.
 *
 * A doclist with type DL_POSITIONS_OFFSETS is stored like this:
 *
 * array {
 *   varint docid;
 *   array {
 *     varint position;     (delta from previous position plus 1, or 0 for end)
 *     varint startOffset;  (delta from previous startOffset)
 *     varint endOffset;    (delta from startOffset)
 *   }
 * }
 *
 * Here, array { X } means zero or more occurrences of X, adjacent in memory.
 *
 * A doclist with type DL_POSITIONS is like the above, but holds only docids
 * and positions without offset information.
 *
 * A doclist with type DL_DOCIDS is like the above, but holds only docids
 * without positions or offset information.
 *
 * On disk, every document list has positions and offsets, so we don't bother
 * to serialize a doclist's type.
 * 
 * We don't yet delta-encode document IDs; doing so will probably be a
 * modest win.
 *
 * NOTE(shess) I've thought of a slightly (1%) better offset encoding.
 * After the first offset, estimate the next offset by using the
 * current token position and the previous token position and offset,
 * offset to handle some variance.  So the estimate would be
 * (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded
 * as normal.  Offsets more than 64 chars from the estimate are
 * encoded as the delta to the previous start offset + 128.  An
 * additional tiny increment can be gained by using the end offset of
 * the previous token to make the estimate a tiny bit more precise.
*/

typedef enum DocListType {
  DL_DOCIDS,              /* docids only */
  DL_POSITIONS,           /* docids + positions */
  DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
} DocListType;

typedef struct DocList {
  char *pData;
  int nData;
  DocListType iType;
  int iLastPos;       /* the last position written */
  int iLastOffset;    /* the last start offset written */
} DocList;

/* Initialize a new DocList to hold the given data. */
static void docListInit(DocList *d, DocListType iType,
                        const char *pData, int nData){
  d->nData = nData;
  if( nData>0 ){
    d->pData = malloc(nData);
    memcpy(d->pData, pData, nData);
  } else {
    d->pData = NULL;
  }
  d->iType = iType;
  d->iLastPos = 0;
  d->iLastOffset = 0;
}

/* Create a new dynamically-allocated DocList. */
static DocList *docListNew(DocListType iType){
  DocList *d = (DocList *) malloc(sizeof(DocList));
  docListInit(d, iType, 0, 0);
  return d;
}

static void docListDestroy(DocList *d){
  free(d->pData);
#ifndef NDEBUG
  memset(d, 0x55, sizeof(*d));
#endif
}

static void docListDelete(DocList *d){
  docListDestroy(d);
  free(d);
}

static char *docListEnd(DocList *d){
  return d->pData + d->nData;
}

/* Append a varint to a DocList's data. */
static void appendVarint(DocList *d, sqlite_int64 i){
  char c[VARINT_MAX];
  int n = putVarint(c, i);
  d->pData = realloc(d->pData, d->nData + n);
  memcpy(d->pData + d->nData, c, n);
  d->nData += n;
}

static void docListAddDocid(DocList *d, sqlite_int64 iDocid){
  appendVarint(d, iDocid);
  d->iLastPos = 0;
}

/* Add a position to the last position list in a doclist. */
static void docListAddPos(DocList *d, int iPos){
  assert( d->iType>=DL_POSITIONS );
  appendVarint(d, iPos-d->iLastPos+1);
  d->iLastPos = iPos;
}

static void docListAddPosOffset(DocList *d, int iPos,
                                int iStartOffset, int iEndOffset){
  assert( d->iType==DL_POSITIONS_OFFSETS );
  docListAddPos(d, iPos);
  appendVarint(d, iStartOffset-d->iLastOffset);
  d->iLastOffset = iStartOffset;
  appendVarint(d, iEndOffset-iStartOffset);
}

/* Terminate the last position list in the given doclist. */
static void docListAddEndPos(DocList *d){
  appendVarint(d, 0);
}

typedef struct DocListReader {
  DocList *pDoclist;
  char *p;
  int iLastPos;    /* the last position read */
} DocListReader;

static void readerInit(DocListReader *r, DocList *pDoclist){
  r->pDoclist = pDoclist;
  if( pDoclist!=NULL ){
    r->p = pDoclist->pData;
  }
  r->iLastPos = 0;
}

static int readerAtEnd(DocListReader *pReader){
  return pReader->p >= docListEnd(pReader->pDoclist);
}

/* Peek at the next docid without advancing the read pointer. */
static sqlite_int64 peekDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !readerAtEnd(pReader) );
  getVarint(pReader->p, &ret);
  return ret;
}

/* Read the next docid. */
static sqlite_int64 readDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !readerAtEnd(pReader) );
  pReader->p += getVarint(pReader->p, &ret);
  pReader->iLastPos = 0;
  return ret;
}

/* Read the next position from a position list.
 * Returns the position, or -1 at the end of the list. */
static int readPosition(DocListReader *pReader){
  int i;
  int iType = pReader->pDoclist->iType;
  assert( iType>=DL_POSITIONS );
  assert( !readerAtEnd(pReader) );

  pReader->p += getVarint32(pReader->p, &i);
  if( i==0 ){
    pReader->iLastPos = -1;
    return -1;
  }
  pReader->iLastPos += ((int) i)-1;
  if( iType>=DL_POSITIONS_OFFSETS ){
    /* Skip over offsets, ignoring them for now. */
    int iStart, iEnd;
    pReader->p += getVarint32(pReader->p, &iStart);
    pReader->p += getVarint32(pReader->p, &iEnd);
  }
  return pReader->iLastPos;
}

/* Skip past the end of a position list. */
static void skipPositionList(DocListReader *pReader){
  while( readPosition(pReader)!=-1 )
    ;
}

/* Skip over a docid, including its position list if the doclist has
 * positions. */
static void skipDocument(DocListReader *pReader){
  readDocid(pReader);
  if( pReader->pDoclist->iType >= DL_POSITIONS ){
    skipPositionList(pReader);
  }
}

static sqlite_int64 firstDocid(DocList *d){
  DocListReader r;
  readerInit(&r, d);
  return readDocid(&r);
}

/* Doclist multi-tool.  Pass pUpdate==NULL to delete the indicated docid;
 * otherwise pUpdate, which must contain only the single docid [iDocid], is
 * inserted (if not present) or updated (if already present). */
static int docListUpdate(DocList *d, sqlite_int64 iDocid, DocList *pUpdate){
  int modified = 0;
  DocListReader reader;
  char *p;

  if( pUpdate!=NULL ){
    assert( d->iType==pUpdate->iType);
    assert( iDocid==firstDocid(pUpdate) );
  }

  readerInit(&reader, d);
  while( !readerAtEnd(&reader) && peekDocid(&reader)<iDocid ){
    skipDocument(&reader);
  }

  p = reader.p;
  /* Delete if there is a matching element. */
  if( !readerAtEnd(&reader) && iDocid==peekDocid(&reader) ){
    skipDocument(&reader);
    memmove(p, reader.p, docListEnd(d) - reader.p);
    d->nData -= (reader.p - p);
    modified = 1;
  }

  /* Insert if indicated. */
  if( pUpdate!=NULL ){
    int iDoclist = p-d->pData;
    docListAddEndPos(pUpdate);

    d->pData = realloc(d->pData, d->nData+pUpdate->nData);
    p = d->pData + iDoclist;

    memmove(p+pUpdate->nData, p, docListEnd(d) - p);
    memcpy(p, pUpdate->pData, pUpdate->nData);
    d->nData += pUpdate->nData;
    modified = 1;
  }

  return modified;
}

/* Split the second half of doclist d into a separate doclist d2.  Returns 1
 * if successful, or 0 if d contains a single document and hence can't be
 * split. */
static int docListSplit(DocList *d, DocList *d2){
  const char *pSplitPoint = d->pData + d->nData / 2;
  DocListReader reader;

  readerInit(&reader, d);
  while( reader.p<pSplitPoint ){
    skipDocument(&reader);
  }
  if( readerAtEnd(&reader) ) return 0;
  docListInit(d2, d->iType, reader.p, docListEnd(d) - reader.p);
  d->nData = reader.p - d->pData;
  d->pData = realloc(d->pData, d->nData);
  return 1;
}

/* A DocListMerge computes the AND of an in-memory DocList [in] and a chunked
 * on-disk doclist, resulting in another in-memory DocList [out].  [in]
 * and [out] may or may not store position information according to the
 * caller's wishes.  The on-disk doclist always comes with positions.
 *
 * The caller must read each chunk of the on-disk doclist in succession and
 * pass it to mergeBlock().
 *
 * If [in] has positions, then the merge output contains only documents with
 * matching positions in the two input doclists.  If [in] does not have
 * positions, then the merge output contains all documents common to the two
 * input doclists.
 *
 * If [in] is NULL, then the on-disk doclist is copied to [out] directly.
 *
 * A merge is performed using an integer [iOffset] provided by the caller.
 * [iOffset] is subtracted from each position in the on-disk doclist for the
 * purpose of position comparison; this is helpful in implementing phrase
 * searches.
 *
 * A DocListMerge is not yet able to propagate offsets through query
 * processing; we should add that capability soon.
*/
typedef struct DocListMerge {
  DocListReader in;
  DocList *pOut;
  int iOffset;
} DocListMerge;

static void mergeInit(DocListMerge *m,
                      DocList *pIn, int iOffset, DocList *pOut){
  readerInit(&m->in, pIn);
  m->pOut = pOut;
  m->iOffset = iOffset;

  /* can't handle offsets yet */
  assert( pIn==NULL || pIn->iType <= DL_POSITIONS );
  assert( pOut->iType <= DL_POSITIONS );
}

/* A helper function for mergeBlock(), below.  Merge the position lists
 * pointed to by m->in and pBlockReader.
 * If the merge matches, write [iDocid] to m->pOut; if m->pOut
 * has positions then write all matching positions as well. */
static void mergePosList(DocListMerge *m, sqlite_int64 iDocid,
                  DocListReader *pBlockReader){
  int block_pos = readPosition(pBlockReader);
  int in_pos = readPosition(&m->in);
  int match = 0;
  while( block_pos!=-1 || in_pos!=-1 ){
    if( block_pos-m->iOffset==in_pos ){
      if( !match ){
        docListAddDocid(m->pOut, iDocid);
        match = 1;
      }
      if( m->pOut->iType >= DL_POSITIONS ){
        docListAddPos(m->pOut, in_pos);
      }
      block_pos = readPosition(pBlockReader);
      in_pos = readPosition(&m->in);
    } else if( in_pos==-1 || (block_pos!=-1 && block_pos-m->iOffset<in_pos) ){
      block_pos = readPosition(pBlockReader);
    } else {
      in_pos = readPosition(&m->in);
    }
  }
  if( m->pOut->iType >= DL_POSITIONS && match ){
    docListAddEndPos(m->pOut);
  }
}

/* Merge one block of an on-disk doclist into a DocListMerge. */
static void mergeBlock(DocListMerge *m, DocList *pBlock){
  DocListReader blockReader;
  assert( pBlock->iType >= DL_POSITIONS );
  readerInit(&blockReader, pBlock);
  while( !readerAtEnd(&blockReader) ){
    sqlite_int64 iDocid = readDocid(&blockReader);
    if( m->in.pDoclist!=NULL ){
      while( 1 ){
        if( readerAtEnd(&m->in) ) return;  /* nothing more to merge */
        if( peekDocid(&m->in)>=iDocid ) break;
        skipDocument(&m->in);
      }
      if( peekDocid(&m->in)>iDocid ){  /* [pIn] has no match with iDocid */
        skipPositionList(&blockReader);  /* skip this docid in the block */
        continue;
      }
      readDocid(&m->in);
    }
    /* We have a document match. */
    if( m->in.pDoclist==NULL || m->in.pDoclist->iType < DL_POSITIONS ){
      /* We don't need to do a poslist merge. */
      docListAddDocid(m->pOut, iDocid);
      if( m->pOut->iType >= DL_POSITIONS ){
        /* Copy all positions to the output doclist. */
        while( 1 ){
          int pos = readPosition(&blockReader);
          if( pos==-1 ) break;
          docListAddPos(m->pOut, pos);
        }
        docListAddEndPos(m->pOut);
      } else skipPositionList(&blockReader);
      continue;
    }
    mergePosList(m, iDocid, &blockReader);
  }
}

static char *string_dup_n(const char *s, int n){
  char *str = malloc(n + 1);
  memcpy(str, s, n);
  str[n] = '\0';
  return str;
}

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it's not part of the standard C library and
 * may not be available everywhere.) */
static char *string_dup(const char *s){
  return string_dup_n(s, strlen(s));
}

/* Format a string, replacing each occurrence of the % character with
 * zName.  This may be more convenient than sqlite_mprintf()
 * when one string is used repeatedly in a format string.
 * The caller must free() the returned string. */
static char *string_format(const char *zFormat, const char *zName){
  const char *p;
  size_t len = 0;
  size_t nName = strlen(zName);
  char *result;
  char *r;

  /* first compute length needed */
  for(p = zFormat ; *p ; ++p){
    len += (*p=='%' ? nName : 1);
  }
  len += 1;  /* for null terminator */

  r = result = malloc(len);
  for(p = zFormat; *p; ++p){
    if( *p=='%' ){
      memcpy(r, zName, nName);
      r += nName;
    } else {
      *r++ = *p;
    }
  }
  *r++ = '\0';
  assert( r == result + len );
  return result;
}

static int sql_exec(sqlite3 *db, const char *zName, const char *zFormat){
  char *zCommand = string_format(zFormat, zName);
  int rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  free(zCommand);
  return rc;
}

static int sql_prepare(sqlite3 *db, const char *zName, sqlite3_stmt **ppStmt,
                const char *zFormat){
  char *zCommand = string_format(zFormat, zName);
  int rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL);
  free(zCommand);
  return rc;
}

/* end utility functions */

#define QUERY_GENERIC 0
#define QUERY_FULLTEXT 1

#define CHUNK_MAX 1024

typedef enum fulltext_statement {
  CONTENT_INSERT_STMT,
  CONTENT_SELECT_STMT,
  CONTENT_DELETE_STMT,

  TERM_SELECT_STMT,
  TERM_CHUNK_SELECT_STMT,
  TERM_INSERT_STMT,
  TERM_UPDATE_STMT,
  TERM_DELETE_STMT,

  MAX_STMT                     /* Always at end! */
} fulltext_statement;

/* These must exactly match the enum above. */
/* TODO(adam): Is there some risk that a statement (in particular,
** pTermSelectStmt) will be used in two cursors at once, e.g.  if a
** query joins a virtual table to itself?  If so perhaps we should
** move some of these to the cursor object.
*/
static const char *fulltext_zStatement[MAX_STMT] = {
  /* CONTENT_INSERT */ "insert into %_content (rowid, content) values (?, ?)",
  /* CONTENT_SELECT */ "select content from %_content where rowid = ?",
  /* CONTENT_DELETE */ "delete from %_content where rowid = ?",

  /* TERM_SELECT */
  "select rowid, doclist from %_term where term = ? and first = ?",
  /* TERM_CHUNK_SELECT */
  "select max(first) from %_term where term = ? and first <= ?",
  /* TERM_INSERT */
  "insert into %_term (term, first, doclist) values (?, ?, ?)",
  /* TERM_UPDATE */ "update %_term set doclist = ? where rowid = ?",
  /* TERM_DELETE */ "delete from %_term where rowid = ?",
};

typedef struct fulltext_vtab {
  sqlite3_vtab base;
  sqlite3 *db;
  const char *zName;               /* virtual table name */
  sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */

  /* Precompiled statements which we keep as long as the table is
  ** open.
  */
  sqlite3_stmt *pFulltextStatements[MAX_STMT];
} fulltext_vtab;

typedef struct fulltext_cursor {
  sqlite3_vtab_cursor base;
  int iCursorType;  /* QUERY_GENERIC or QUERY_FULLTEXT */

  sqlite3_stmt *pStmt;

  int eof;

  /* The following is used only when iCursorType == QUERY_FULLTEXT. */
  DocListReader result;
} fulltext_cursor;

static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  return (fulltext_vtab *) c->base.pVtab;
}

static sqlite3_module fulltextModule;   /* forward declaration */

/* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
** If the indicated statement has never been prepared, it is prepared
** and cached, otherwise the cached version is reset.
*/
static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
                             sqlite3_stmt **ppStmt){
  assert( iStmt<MAX_STMT );
  if( v->pFulltextStatements[iStmt]==NULL ){
    int rc = sql_prepare(v->db, v->zName, &v->pFulltextStatements[iStmt],
                         fulltext_zStatement[iStmt]);
    if( rc!=SQLITE_OK ) return rc;
  } else {
    int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
    if( rc!=SQLITE_OK ) return rc;
  }

  *ppStmt = v->pFulltextStatements[iStmt];
  return SQLITE_OK;
}

/* Step the indicated statement, handling errors SQLITE_BUSY (by
** retrying) and SQLITE_SCHEMA (by re-preparing and transferring
** bindings to the new statement).
** TODO(adam): We should extend this function so that it can work with
** statements declared locally, not only globally cached statements.
*/
static int sql_step_statement(fulltext_vtab *v, fulltext_statement iStmt,
                              sqlite3_stmt **ppStmt){
  int rc;
  sqlite3_stmt *s = *ppStmt;
  assert( iStmt<MAX_STMT );
  assert( s==v->pFulltextStatements[iStmt] );

  while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){
    sqlite3_stmt *pNewStmt;

    if( rc==SQLITE_BUSY ) continue;
    if( rc!=SQLITE_ERROR ) return rc;

    rc = sqlite3_reset(s);
    if( rc!=SQLITE_SCHEMA ) return SQLITE_ERROR;

    v->pFulltextStatements[iStmt] = NULL;   /* Still in s */
    rc = sql_get_statement(v, iStmt, &pNewStmt);
    if( rc!=SQLITE_OK ) goto err;
    *ppStmt = pNewStmt;

    rc = sqlite3_transfer_bindings(s, pNewStmt);
    if( rc!=SQLITE_OK ) goto err;

    rc = sqlite3_finalize(s);
    if( rc!=SQLITE_OK ) return rc;
    s = pNewStmt;
  }
  return rc;

 err:
  sqlite3_finalize(s);
  return rc;
}

/* Like sql_step_statement(), but convert SQLITE_DONE to SQLITE_OK.
** Useful for statements like UPDATE, where we expect no results.
*/
static int sql_single_step_statement(fulltext_vtab *v,
                                     fulltext_statement iStmt,
                                     sqlite3_stmt **ppStmt){
  int rc = sql_step_statement(v, iStmt, ppStmt);
  return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
}

/* insert into %_content (rowid, content) values ([rowid], [zContent]) */
static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
                          const char *zContent, int nContent){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_value(s, 1, rowid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 2, zContent, nContent, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, CONTENT_INSERT_STMT, &s);
}

/* select content from %_content where rowid = [iRow]
 * The caller must delete the returned string. */
static int content_select(fulltext_vtab *v, sqlite_int64 iRow,
                          char **pzContent){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_step_statement(v, CONTENT_SELECT_STMT, &s);
  if( rc!=SQLITE_ROW ) return rc;

  *pzContent = string_dup((const char *)sqlite3_column_text(s, 0));

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_OK;

  free(*pzContent);
  return rc;
}

/* delete from %_content where rowid = [iRow ] */
static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iRow);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, CONTENT_DELETE_STMT, &s);
}

/* select rowid, doclist from %_term where term = [zTerm] and first = [iFirst]
 * If found, returns SQLITE_OK; the caller must free the returned doclist.
 * If no rows found, returns SQLITE_ERROR. */
static int term_select(fulltext_vtab *v, const char *zTerm, int nTerm,
                       sqlite_int64 iFirst,
                       sqlite_int64 *rowid,
                       DocList *out){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_TRANSIENT);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, iFirst);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_step_statement(v, TERM_SELECT_STMT, &s);
  if( rc!=SQLITE_ROW ) return rc==SQLITE_DONE ? SQLITE_ERROR : rc;

  *rowid = sqlite3_column_int64(s, 0);
  docListInit(out, DL_POSITIONS_OFFSETS,
              sqlite3_column_blob(s, 1), sqlite3_column_bytes(s, 1));

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  return rc==SQLITE_DONE ? SQLITE_OK : rc;
}

/* select max(first) from %_term where term = [zTerm] and first <= [iFirst]
 * If found, returns SQLITE_ROW and result in *piResult; if the query returns
 * NULL (meaning no row found) returns SQLITE_DONE.
 */
static int term_chunk_select(fulltext_vtab *v, const char *zTerm, int nTerm,
                           sqlite_int64 iFirst, sqlite_int64 *piResult){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_CHUNK_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, iFirst);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_step_statement(v, TERM_CHUNK_SELECT_STMT, &s);
  if( rc!=SQLITE_ROW ) return rc==SQLITE_DONE ? SQLITE_ERROR : rc;

  switch( sqlite3_column_type(s, 0) ){
    case SQLITE_NULL:
      rc = SQLITE_DONE;
      break;
    case SQLITE_INTEGER:
     *piResult = sqlite3_column_int64(s, 0);
     break;
    default:
      return SQLITE_ERROR;
  }
  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  if( sqlite3_step(s) != SQLITE_DONE ) return SQLITE_ERROR;
  return rc;
}

/* insert into %_term (term, first, doclist)
               values ([zTerm], [iFirst], [doclist]) */
static int term_insert(fulltext_vtab *v, const char *zTerm, int nTerm,
                       sqlite_int64 iFirst, DocList *doclist){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, iFirst);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 3, doclist->pData, doclist->nData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, TERM_INSERT_STMT, &s);
}

/* update %_term set doclist = [doclist] where rowid = [rowid] */
static int term_update(fulltext_vtab *v, sqlite_int64 rowid,
                       DocList *doclist){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_UPDATE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 1, doclist->pData, doclist->nData,
                         SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, rowid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, TERM_UPDATE_STMT, &s);
}

static int term_delete(fulltext_vtab *v, sqlite_int64 rowid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, TERM_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, rowid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step_statement(v, TERM_DELETE_STMT, &s);
}

static void fulltext_vtab_destroy(fulltext_vtab *v){
  int iStmt;

  for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
    if( v->pFulltextStatements[iStmt]!=NULL ){
      sqlite3_finalize(v->pFulltextStatements[iStmt]);
      v->pFulltextStatements[iStmt] = NULL;
    }
  }

  if( v->pTokenizer!=NULL ){
    v->pTokenizer->pModule->xDestroy(v->pTokenizer);
    v->pTokenizer = NULL;
  }

  free((void *) v->zName);
  free(v);
}

/* Current interface:
** argv[0] - module name
** argv[1] - database name
** argv[2] - table name
** argv[3] - tokenizer name (optional, a sensible default is provided)
** argv[4..] - passed to tokenizer (optional based on tokenizer)
**/
static int fulltextConnect(sqlite3 *db, void *pAux, int argc, char **argv,
                           sqlite3_vtab **ppVTab){
  int rc;
  fulltext_vtab *v;
  sqlite3_tokenizer_module *m = NULL;

  assert( argc>=3 );
  v = (fulltext_vtab *) malloc(sizeof(fulltext_vtab));
  /* sqlite will initialize v->base */
  v->db = db;
  v->zName = string_dup(argv[2]);
  v->pTokenizer = NULL;

  if( argc==3 ){
    get_simple_tokenizer_module(&m);
  } else {
    /* TODO(shess) For now, add new tokenizers as else if clauses. */
    if( !strcmp(argv[3], "simple") ){
      get_simple_tokenizer_module(&m);
    } else {
      assert( "unrecognized tokenizer"==NULL );
    }
  }

  /* TODO(shess) Since tokenization impacts the index, the parameters
  ** to the tokenizer need to be identical when a persistent virtual
  ** table is re-created.  One solution would be a meta-table to track
  ** such information in the database.  Then we could verify that the
  ** information is identical on subsequent creates.
  */
  /* TODO(shess) Why isn't argv already (const char **)? */
  rc = m->xCreate(argc-3, (const char **) (argv+3), &v->pTokenizer);
  if( rc!=SQLITE_OK ) return rc;
  v->pTokenizer->pModule = m;

  /* TODO: verify the existence of backing tables foo_content, foo_term */

  rc = sqlite3_declare_vtab(db, "create table x(content text)");
  if( rc!=SQLITE_OK ) return rc;

  memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));

  *ppVTab = &v->base;
  return SQLITE_OK;
}

static int fulltextCreate(sqlite3 *db, void *pAux, int argc, char **argv,
                          sqlite3_vtab **ppVTab){
  int rc;
  assert( argc>=3 );

  /* The %_content table holds the text of each full-text item, with
  ** the rowid used as the docid.
  **
  ** The %_term table maps each term to a document list blob
  ** containing elements sorted by ascending docid, each element
  ** encoded as:
  **
  **   docid varint-encoded
  **   token count varint-encoded
  **   "count" token elements (poslist):
  **     position varint-encoded as delta from previous position
  **     start offset varint-encoded as delta from previous start offset
  **     end offset varint-encoded as delta from start offset
  **
  ** Additionally, doclist blobs can be chunked into multiple rows,
  ** using "first" to order the blobs.  "first" is simply the first
  ** docid in the blob.
  */
  /*
  ** NOTE(shess) That last sentence is incorrect in the face of
  ** deletion, which can leave a doclist that doesn't contain the
  ** first from that row.  I _believe_ this does not matter to the
  ** operation of the system, but it might be reasonable to update
  ** appropriately in case this assumption becomes more important.
  */
  rc = sql_exec(db, argv[2],
    "create table %_content(content text);"
    "create table %_term(term text, first integer, doclist blob);"
    "create index %_index on %_term(term, first)");
  if( rc!=SQLITE_OK ) return rc;

  return fulltextConnect(db, pAux, argc, argv, ppVTab);
}

/* Decide how to handle an SQL query.
 * At the moment, MATCH queries can include implicit boolean ANDs; we
 * haven't implemented phrase searches or OR yet. */
static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  int i;

  for(i=0; i<pInfo->nConstraint; ++i){
    const struct sqlite3_index_constraint *pConstraint;
    pConstraint = &pInfo->aConstraint[i];
    if( pConstraint->iColumn==0 &&
        pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH &&
        pConstraint->usable ){   /* a full-text search */
      pInfo->aConstraintUsage[i].argvIndex = 1;
      pInfo->aConstraintUsage[i].omit = 1;
      pInfo->idxNum = QUERY_FULLTEXT;
      pInfo->estimatedCost = 1.0;   /* an arbitrary value for now */
      return SQLITE_OK;
    }
  }
  pInfo->idxNum = QUERY_GENERIC;
  return SQLITE_OK;
}

static int fulltextDisconnect(sqlite3_vtab *pVTab){
  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextDestroy(sqlite3_vtab *pVTab){
  fulltext_vtab *v = (fulltext_vtab *)pVTab;

  int rc = sql_exec(v->db, v->zName,
                    "drop table %_content; drop table %_term");
  if( rc!=SQLITE_OK ) return rc;

  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  fulltext_cursor *c;

  c = (fulltext_cursor *) calloc(sizeof(fulltext_cursor), 1);
  /* sqlite will initialize c->base */
  *ppCursor = &c->base;

  return SQLITE_OK;
}

static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  sqlite3_finalize(c->pStmt);
  if( c->result.pDoclist!=NULL ){
    docListDelete(c->result.pDoclist);
  }
  free(c);
  return SQLITE_OK;
}

static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  sqlite_int64 iDocid;
  int rc;

  switch( c->iCursorType ){
    case QUERY_GENERIC:
      /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
      rc = sqlite3_step(c->pStmt);
      switch( rc ){
        case SQLITE_ROW:
          c->eof = 0;
          return SQLITE_OK;
        case SQLITE_DONE:
          c->eof = 1;
          return SQLITE_OK;
        default:
          c->eof = 1;
          return rc;
      }
    case QUERY_FULLTEXT:
      rc = sqlite3_reset(c->pStmt);
      if( rc!=SQLITE_OK ) return rc;

      if( readerAtEnd(&c->result)){
        c->eof = 1;
        return SQLITE_OK;
      }
      iDocid = readDocid(&c->result);
      rc = sqlite3_bind_int64(c->pStmt, 1, iDocid);
      if( rc!=SQLITE_OK ) return rc;
      /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
      rc = sqlite3_step(c->pStmt);
      if( rc==SQLITE_ROW ){   /* the case we expect */
        c->eof = 0;
        return SQLITE_OK;
      }
      /* an error occurred; abort */
      return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
    default:
      assert( 0 );
      return SQLITE_ERROR;  /* not reached */
  }
}

static int term_select_doclist(fulltext_vtab *v, const char *pTerm, int nTerm,
                               sqlite3_stmt **ppStmt){
  int rc;
  if( *ppStmt ){
    rc = sqlite3_reset(*ppStmt);
  } else {
    rc = sql_prepare(v->db, v->zName, ppStmt,
      "select doclist from %_term where term = ? order by first");
  }
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_text(*ppStmt, 1, pTerm, nTerm, SQLITE_TRANSIENT);
  if( rc!=SQLITE_OK ) return rc;

  return sqlite3_step(*ppStmt);   /* TODO(adamd): handle schema error */
}

/* Read the posting list for [zTerm]; AND it with the doclist [in] to
 * produce the doclist [out], using the given offset [iOffset] for phrase
 * matching.
 * (*pSelect) is used to hold an SQLite statement used inside this function;
 * the caller should initialize *pSelect to NULL before the first call.
 */
static int query_merge(fulltext_vtab *v, sqlite3_stmt **pSelect,
                       const char *zTerm,
                       DocList *pIn, int iOffset, DocList *out){
  int rc;
  DocListMerge merge;

  if( pIn!=NULL && !pIn->nData ){
    /* If [pIn] is already empty, there's no point in reading the
     * posting list to AND it in; return immediately. */
      return SQLITE_OK;
  }

  rc = term_select_doclist(v, zTerm, -1, pSelect);
  if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;

  mergeInit(&merge, pIn, iOffset, out);
  while( rc==SQLITE_ROW ){
    DocList block;
    docListInit(&block, DL_POSITIONS_OFFSETS,
                sqlite3_column_blob(*pSelect, 0),
                sqlite3_column_bytes(*pSelect, 0));
    mergeBlock(&merge, &block);
    docListDestroy(&block);

    rc = sqlite3_step(*pSelect);
    if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
      return rc;
    }
  }
  
  return SQLITE_OK;
}

typedef struct QueryTerm {
  int is_phrase;    /* true if this term begins a new phrase */
  const char *zTerm;
} QueryTerm;

/* A parsed query.
 *
 * As an example, parsing the query ["four score" years "new nation"] will
 * yield a Query with 5 terms:
 *   "four",   is_phrase = 1
 *   "score",  is_phrase = 0
 *   "years",  is_phrase = 1
 *   "new",    is_phrase = 1
 *   "nation", is_phrase = 0
 */
typedef struct Query {
  int nTerms;
  QueryTerm *pTerm;
} Query;

static void query_add(Query *q, int is_phrase, const char *zTerm){
  QueryTerm *t;
  ++q->nTerms;
  q->pTerm = realloc(q->pTerm, q->nTerms * sizeof(q->pTerm[0]));
  t = &q->pTerm[q->nTerms - 1];
  t->is_phrase = is_phrase;
  t->zTerm = zTerm;
}
    
static void query_free(Query *q){
  int i;
  for(i = 0; i < q->nTerms; ++i){
    free((void *) q->pTerm[i].zTerm);
  }
  free(q->pTerm);
}

static int tokenize_segment(sqlite3_tokenizer *pTokenizer,
                            const char *zQuery, int in_phrase,
                            Query *pQuery){
  sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  sqlite3_tokenizer_cursor *pCursor;
  int is_first = 1;
  
  int rc = pModule->xOpen(pTokenizer, zQuery, -1, &pCursor);
  if( rc!=SQLITE_OK ) return rc;
  pCursor->pTokenizer = pTokenizer;

  while( 1 ){
    const char *zToken;
    int nToken, iStartOffset, iEndOffset, dummy_pos;

    rc = pModule->xNext(pCursor,
                        &zToken, &nToken,
                        &iStartOffset, &iEndOffset,
                        &dummy_pos);
    if( rc!=SQLITE_OK ) break;
    query_add(pQuery, !in_phrase || is_first, string_dup_n(zToken, nToken));
    is_first = 0;
  }

  return pModule->xClose(pCursor);
}

/* Parse a query string, yielding a Query object. */
static int parse_query(fulltext_vtab *v, const char *zQuery, Query *pQuery){
  char *zQuery1 = string_dup(zQuery);
  int in_phrase = 0;
  char *s = zQuery1;
  pQuery->nTerms = 0;
  pQuery->pTerm = NULL;

  while( *s ){
    char *t = s;
    while( *t ){
      if( *t=='"' ){
        *t++ = '\0';
        break;
      }
      ++t;
    }
    if( *s ){
      tokenize_segment(v->pTokenizer, s, in_phrase, pQuery);
    }
    s = t;
    in_phrase = !in_phrase;
  }
  
  free(zQuery1);
  return SQLITE_OK;
}

/* Perform a full-text query; return a list of documents in [pResult]. */
static int fulltext_query(fulltext_vtab *v, const char *zQuery,
                          DocList **pResult){
  Query q;
  int phrase_start = -1;
  int i;
  sqlite3_stmt *pSelect = NULL;
  DocList *d = NULL;

  int rc = parse_query(v, zQuery, &q);
  if( rc!=SQLITE_OK ) return rc;

  /* Merge terms. */
  for(i = 0 ; i < q.nTerms ; ++i){
    /* In each merge step, we need to generate positions whenever we're
     * processing a phrase which hasn't ended yet. */
    int need_positions = i<q.nTerms-1 && !q.pTerm[i+1].is_phrase;
    DocList *next = docListNew(need_positions ? DL_POSITIONS : DL_DOCIDS);
    if( q.pTerm[i].is_phrase ){
      phrase_start = i;
    }
    rc = query_merge(v, &pSelect, q.pTerm[i].zTerm, d, i - phrase_start, next);
    if( rc!=SQLITE_OK ) break;
    if( d!=NULL ){
      docListDelete(d);
    }
    d = next;
  }

  sqlite3_finalize(pSelect);
  query_free(&q);
  *pResult = d;
  return rc;
}

static int fulltextFilter(sqlite3_vtab_cursor *pCursor,
                          int idxNum, const char *idxStr,
                          int argc, sqlite3_value **argv){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);
  int rc;
  const char *zStatement;

  c->iCursorType = idxNum;
  switch( idxNum ){
    case QUERY_GENERIC:
      zStatement = "select rowid, content from %_content";
      break;

    case QUERY_FULLTEXT:   /* full-text search */
    {
      const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
      DocList *pResult;
      assert( argc==1 );
      rc = fulltext_query(v, zQuery, &pResult);
      if( rc!=SQLITE_OK ) return rc;
      readerInit(&c->result, pResult);
      zStatement = "select rowid, content from %_content where rowid = ?";
      break;
    }

    default:
      assert( 0 );
  }

  rc = sql_prepare(v->db, v->zName, &c->pStmt, zStatement);
  if( rc!=SQLITE_OK ) return rc;

  return fulltextNext(pCursor);
}

static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  return c->eof;
}

static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
                          sqlite3_context *pContext, int idxCol){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  const char *s;

  assert( idxCol==0 );
  s = (const char *) sqlite3_column_text(c->pStmt, 1);
  sqlite3_result_text(pContext, s, -1, SQLITE_TRANSIENT);

  return SQLITE_OK;
}

static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;

  *pRowid = sqlite3_column_int64(c->pStmt, 0);
  return SQLITE_OK;
}

/* Build a hash table containing all terms in zText. */
static int build_terms(Hash *terms, sqlite3_tokenizer *pTokenizer,
                       const char *zText, sqlite_int64 iDocid){
  sqlite3_tokenizer_cursor *pCursor;
  const char *pToken;
  int nTokenBytes;
  int iStartOffset, iEndOffset, iPosition;

  int rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  if( rc!=SQLITE_OK ) return rc;

  pCursor->pTokenizer = pTokenizer;
  HashInit(terms, HASH_STRING, 1);
  while( SQLITE_OK==pTokenizer->pModule->xNext(pCursor,
                                               &pToken, &nTokenBytes,
                                               &iStartOffset, &iEndOffset,
                                               &iPosition) ){
    DocList *p;

    /* Positions can't be negative; we use -1 as a terminator internally. */
    if( iPosition<0 ) {
      rc = SQLITE_ERROR;  
      goto err;
    }

    p = HashFind(terms, pToken, nTokenBytes);
    if( p==NULL ){
      p = docListNew(DL_POSITIONS_OFFSETS);
      docListAddDocid(p, iDocid);
      HashInsert(terms, pToken, nTokenBytes, p);
    }
    docListAddPosOffset(p, iPosition, iStartOffset, iEndOffset);
  }

err:
  /* TODO(shess) Check return?  Should this be able to cause errors at
  ** this point?  Actually, same question about sqlite3_finalize(),
  ** though one could argue that failure there means that the data is
  ** not durable.  *ponder*
  */
  pTokenizer->pModule->xClose(pCursor);
  return rc;
}
/* Update the %_terms table to map the term [zTerm] to the given rowid. */
static int index_insert_term(fulltext_vtab *v, const char *zTerm, int nTerm,
                             sqlite_int64 iDocid, DocList *p){
  sqlite_int64 iFirst;
  sqlite_int64 iIndexRow;
  DocList doclist;

  int rc = term_chunk_select(v, zTerm, nTerm, iDocid, &iFirst);
  if( rc==SQLITE_DONE ){
    docListInit(&doclist, DL_POSITIONS_OFFSETS, 0, 0);
    if( docListUpdate(&doclist, iDocid, p) ){
      rc = term_insert(v, zTerm, nTerm, iDocid, &doclist);
      docListDestroy(&doclist);
      return rc;
    }
    return SQLITE_OK;
  }
  if( rc!=SQLITE_ROW ) return SQLITE_ERROR;

  /* This word is in the index; add this document ID to its blob. */

  rc = term_select(v, zTerm, nTerm, iFirst, &iIndexRow, &doclist);
  if( rc!=SQLITE_OK ) return rc;

  if( docListUpdate(&doclist, iDocid, p) ){
    /* If the blob is too big, split it in half. */
    if( doclist.nData>CHUNK_MAX ){
      DocList half;
      if( docListSplit(&doclist, &half) ){
        rc = term_insert(v, zTerm, nTerm, firstDocid(&half), &half);
        docListDestroy(&half);
        if( rc!=SQLITE_OK ) goto err;
      }
    }
    rc = term_update(v, iIndexRow, &doclist);
  }

err:
  docListDestroy(&doclist);
  return rc;
}

/* Insert a row into the full-text index; set *piRowid to be the ID of the
 * new row. */
static int index_insert(fulltext_vtab *v,
                        sqlite3_value *pRequestRowid, const char *zText,
                        sqlite_int64 *piRowid){
  Hash terms;  /* maps term string -> PosList */
  HashElem *e;

  int rc = content_insert(v, pRequestRowid, zText, -1);
  if( rc!=SQLITE_OK ) return rc;
  *piRowid = sqlite3_last_insert_rowid(v->db);

  if( !zText ) return SQLITE_OK;   /* nothing to index */

  rc = build_terms(&terms, v->pTokenizer, zText, *piRowid);
  if( rc!=SQLITE_OK ) return rc;

  for(e=HashFirst(&terms); e; e=HashNext(e)){
    DocList *p = HashData(e);
    rc = index_insert_term(v, HashKey(e), HashKeysize(e), *piRowid, p);
    if( rc!=SQLITE_OK ) break;
  }

  for(e=HashFirst(&terms); e; e=HashNext(e)){
    DocList *p = HashData(e);
    docListDelete(p);
  }
  HashClear(&terms);
  return rc;
}

static int index_delete_term(fulltext_vtab *v, const char *zTerm, int nTerm,
                             sqlite_int64 iDocid){
  sqlite_int64 iFirst;
  sqlite_int64 iIndexRow;
  DocList doclist;

  int rc = term_chunk_select(v, zTerm, nTerm, iDocid, &iFirst);
  if( rc!=SQLITE_ROW ) return SQLITE_ERROR;

  rc = term_select(v, zTerm, nTerm, iFirst, &iIndexRow, &doclist);
  if( rc!=SQLITE_OK ) return rc;

  if( docListUpdate(&doclist, iDocid, NULL) ){
    if( doclist.nData>0 ){
      rc = term_update(v, iIndexRow, &doclist);
    } else {  /* empty posting list */
      rc = term_delete(v, iIndexRow);
    }
  }
  docListDestroy(&doclist);
  return rc;
}

/* Delete a row from the full-text index. */
static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  char *zText;
  Hash terms;
  HashElem *e;

  int rc = content_select(v, iRow, &zText);
  if( rc!=SQLITE_OK ) return rc;

  rc = build_terms(&terms, v->pTokenizer, zText, iRow);
  free(zText);
  if( rc!=SQLITE_OK ) return rc;

  for(e=HashFirst(&terms); e; e=HashNext(e)){
    rc = index_delete_term(v, HashKey(e), HashKeysize(e), iRow);
    if( rc!=SQLITE_OK ) break;
  }
  for(e=HashFirst(&terms); e; e=HashNext(e)){
    DocList *p = HashData(e);
    docListDelete(p);
  }
  HashClear(&terms);

  return content_delete(v, iRow);
}

static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
                   sqlite_int64 *pRowid){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;

  if( nArg<2 ){
    return index_delete(v, sqlite3_value_int64(ppArg[0]));
  }

  if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
    return SQLITE_ERROR;   /* an update; not yet supported */
  }

  assert( nArg==3 );    /* ppArg[1] = rowid, ppArg[2] = content */
  return index_insert(v, ppArg[1],
                      (const char *)sqlite3_value_text(ppArg[2]), pRowid);
}

static sqlite3_module fulltextModule = {
  0,
  fulltextCreate,
  fulltextConnect,
  fulltextBestIndex,
  fulltextDisconnect,
  fulltextDestroy,
  fulltextOpen,
  fulltextClose,
  fulltextFilter,
  fulltextNext,
  fulltextEof,
  fulltextColumn,
  fulltextRowid,
  fulltextUpdate
};

int fulltext_init(sqlite3 *db){
 return sqlite3_create_module(db, "fulltext", &fulltextModule, 0);
}

#if !SQLITE_CORE
int sqlite3_extension_init(sqlite3 *db, char **pzErrMsg,
                           const sqlite3_api_routines *pApi){
 SQLITE_EXTENSION_INIT2(pApi)
 return fulltext_init(db);
}
#endif

Added ext/fts1/fulltext.h.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

int fulltext_init(sqlite3 *db);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */

Added ext/fts1/simple_tokenizer.c.





























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*
** The author disclaims copyright to this source code.
**
*************************************************************************
** Implementation of the "simple" full-text-search tokenizer.
*/

#include <assert.h>
#if !defined(__APPLE__)
#include <malloc.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "tokenizer.h"

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it's not part of the standard C library and
 * may not be available everywhere.) */
/* TODO(shess) Copied from fulltext.c, consider util.c for such
** things. */
static char *string_dup(const char *s){
  char *str = malloc(strlen(s) + 1);
  strcpy(str, s);
  return str;
}

typedef struct simple_tokenizer {
  sqlite3_tokenizer base;
  const char *zDelim;          /* token delimiters */
} simple_tokenizer;

typedef struct simple_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *pInput;          /* input we are tokenizing */
  int nBytes;                  /* size of the input */
  const char *pCurrent;        /* current position in pInput */
  int iToken;                  /* index of next token to be returned */
  char *zToken;                /* storage for current token */
  int nTokenBytes;             /* actual size of current token */
  int nTokenAllocated;         /* space allocated to zToken buffer */
} simple_tokenizer_cursor;

static sqlite3_tokenizer_module simpleTokenizerModule;/* forward declaration */

static int simpleCreate(
  int argc, const char **argv,
  sqlite3_tokenizer **ppTokenizer
){
  simple_tokenizer *t;

  t = (simple_tokenizer *) malloc(sizeof(simple_tokenizer));
  /* TODO(shess) Delimiters need to remain the same from run to run,
  ** else we need to reindex.  One solution would be a meta-table to
  ** track such information in the database, then we'd only want this
  ** information on the initial create.
  */
  if( argc>1 ){
    t->zDelim = string_dup(argv[1]);
  } else {
    /* Build a string excluding alphanumeric ASCII characters */
    char zDelim[0x80];               /* nul-terminated, so nul not a member */
    int i, j;
    for(i=1, j=0; i<0x80; i++){
      if( !isalnum(i) ){
        zDelim[j++] = i;
      }
    }
    zDelim[j++] = '\0';
    assert( j<=sizeof(zDelim) );
    t->zDelim = string_dup(zDelim);
  }

  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  simple_tokenizer *t = (simple_tokenizer *) pTokenizer;

  free((void *) t->zDelim);
  free(t);

  return SQLITE_OK;
}

static int simpleOpen(
  sqlite3_tokenizer *pTokenizer,
  const char *pInput, int nBytes,
  sqlite3_tokenizer_cursor **ppCursor
){
  simple_tokenizer_cursor *c;

  c = (simple_tokenizer_cursor *) malloc(sizeof(simple_tokenizer_cursor));
  c->pInput = pInput;
  c->nBytes = nBytes<0 ? (int) strlen(pInput) : nBytes;
  c->pCurrent = c->pInput;        /* start tokenizing at the beginning */
  c->iToken = 0;
  c->zToken = NULL;               /* no space allocated, yet. */
  c->nTokenBytes = 0;
  c->nTokenAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;

  if( NULL!=c->zToken ){
    free(c->zToken);
  }
  free(c);

  return SQLITE_OK;
}

static int simpleNext(
  sqlite3_tokenizer_cursor *pCursor,
  const char **ppToken, int *pnBytes,
  int *piStartOffset, int *piEndOffset, int *piPosition
){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  int ii;

  while( c->pCurrent-c->pInput<c->nBytes ){
    int n = (int) strcspn(c->pCurrent, t->zDelim);
    if( n>0 ){
      if( n+1>c->nTokenAllocated ){
        c->zToken = realloc(c->zToken, n+1);
      }
      for(ii=0; ii<n; ii++){
        /* TODO(shess) This needs expansion to handle UTF-8
        ** case-insensitivity.
        */
        char ch = c->pCurrent[ii];
        c->zToken[ii] = (unsigned char)ch<0x80 ? tolower(ch) : ch;
      }
      c->zToken[n] = '\0';
      *ppToken = c->zToken;
      *pnBytes = n;
      *piStartOffset = (int) (c->pCurrent-c->pInput);
      *piEndOffset = *piStartOffset+n;
      *piPosition = c->iToken++;
      c->pCurrent += n + 1;

      return SQLITE_OK;
    }
    c->pCurrent += n + 1;
    /* TODO(shess) could strspn() to skip delimiters en masse.  Needs
    ** to happen in two places, though, which is annoying.
    */
  }
  return SQLITE_DONE;
}

static sqlite3_tokenizer_module simpleTokenizerModule = {
  0,
  simpleCreate,
  simpleDestroy,
  simpleOpen,
  simpleClose,
  simpleNext,
};

void get_simple_tokenizer_module(
  sqlite3_tokenizer_module **ppModule
){
  *ppModule = &simpleTokenizerModule;
}

Added ext/fts1/tokenizer.h.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
** 2006 July 10
**
** The author disclaims copyright to this source code.
**
*************************************************************************
** Defines the interface to tokenizers used by fulltext-search.  There
** are three basic components:
**
** sqlite3_tokenizer_module is a singleton defining the tokenizer
** interface functions.  This is essentially the class structure for
** tokenizers.
**
** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
** including customization information defined at creation time.
**
** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
** tokens from a particular input.
*/
#ifndef _TOKENIZER_H_
#define _TOKENIZER_H_

/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
** If tokenizers are to be allowed to call sqlite3_*() functions, then
** we will need a way to register the API consistently.
*/
#include "sqlite3.h"

/*
** Structures used by the tokenizer interface.
*/
typedef struct sqlite3_tokenizer sqlite3_tokenizer;
typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;

struct sqlite3_tokenizer_module {
  int iVersion;                  /* currently 0 */

  /*
  ** Create and destroy a tokenizer.  argc/argv are passed down from
  ** the fulltext virtual table creation to allow customization.
  */
  int (*xCreate)(int argc, const char **argv,
                 sqlite3_tokenizer **ppTokenizer);
  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);

  /*
  ** Tokenize a particular input.  Call xOpen() to prepare to
  ** tokenize, xNext() repeatedly until it returns SQLITE_DONE, then
  ** xClose() to free any internal state.  The pInput passed to
  ** xOpen() must exist until the cursor is closed.  The ppToken
  ** result from xNext() is only valid until the next call to xNext()
  ** or until xClose() is called.
  */
  /* TODO(shess) current implementation requires pInput to be
  ** nul-terminated.  This should either be fixed, or pInput/nBytes
  ** should be converted to zInput.
  */
  int (*xOpen)(sqlite3_tokenizer *pTokenizer,
               const char *pInput, int nBytes,
               sqlite3_tokenizer_cursor **ppCursor);
  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
               const char **ppToken, int *pnBytes,
               int *piStartOffset, int *piEndOffset, int *piPosition);
};

struct sqlite3_tokenizer {
  sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
  /* Tokenizer implementations will typically add additional fields */
};

struct sqlite3_tokenizer_cursor {
  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
  /* Tokenizer implementations will typically add additional fields */
};

/*
** Get the module for a tokenizer which generates tokens based on a
** set of non-token characters.  The default is to break tokens at any
** non-alnum character, though the set of delimiters can also be
** specified by the first argv argument to xCreate().
*/
/* TODO(shess) This doesn't belong here.  Need some sort of
** registration process.
*/
void get_simple_tokenizer_module(sqlite3_tokenizer_module **ppModule);

#endif /* _TOKENIZER_H_ */

Added ext/fts2/README.tokenizers.











































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

1. FTS2 Tokenizers

  When creating a new full-text table, FTS2 allows the user to select
  the text tokenizer implementation to be used when indexing text
  by specifying a "tokenizer" clause as part of the CREATE VIRTUAL TABLE
  statement:

    CREATE VIRTUAL TABLE <table-name> USING fts2(
      <columns ...> [, tokenizer <tokenizer-name> [<tokenizer-args>]]
    );

  The built-in tokenizers (valid values to pass as <tokenizer name>) are
  "simple" and "porter".

  <tokenizer-args> should consist of zero or more white-space separated
  arguments to pass to the selected tokenizer implementation. The 
  interpretation of the arguments, if any, depends on the individual 
  tokenizer.

2. Custom Tokenizers

  FTS2 allows users to provide custom tokenizer implementations. The 
  interface used to create a new tokenizer is defined and described in 
  the fts2_tokenizer.h source file.

  Registering a new FTS2 tokenizer is similar to registering a new 
  virtual table module with SQLite. The user passes a pointer to a
  structure containing pointers to various callback functions that
  make up the implementation of the new tokenizer type. For tokenizers,
  the structure (defined in fts2_tokenizer.h) is called
  "sqlite3_tokenizer_module".

  FTS2 does not expose a C-function that users call to register new
  tokenizer types with a database handle. Instead, the pointer must
  be encoded as an SQL blob value and passed to FTS2 through the SQL
  engine by evaluating a special scalar function, "fts2_tokenizer()".
  The fts2_tokenizer() function may be called with one or two arguments,
  as follows:

    SELECT fts2_tokenizer(<tokenizer-name>);
    SELECT fts2_tokenizer(<tokenizer-name>, <sqlite3_tokenizer_module ptr>);
  
  Where <tokenizer-name> is a string identifying the tokenizer and
  <sqlite3_tokenizer_module ptr> is a pointer to an sqlite3_tokenizer_module
  structure encoded as an SQL blob. If the second argument is present,
  it is registered as tokenizer <tokenizer-name> and a copy of it
  returned. If only one argument is passed, a pointer to the tokenizer
  implementation currently registered as <tokenizer-name> is returned,
  encoded as a blob. Or, if no such tokenizer exists, an SQL exception
  (error) is raised.

  SECURITY: If the fts2 extension is used in an environment where potentially
    malicious users may execute arbitrary SQL (i.e. gears), they should be
    prevented from invoking the fts2_tokenizer() function, possibly using the
    authorisation callback.

  See "Sample code" below for an example of calling the fts2_tokenizer()
  function from C code.

3. ICU Library Tokenizers

  If this extension is compiled with the SQLITE_ENABLE_ICU pre-processor 
  symbol defined, then there exists a built-in tokenizer named "icu" 
  implemented using the ICU library. The first argument passed to the
  xCreate() method (see fts2_tokenizer.h) of this tokenizer may be
  an ICU locale identifier. For example "tr_TR" for Turkish as used
  in Turkey, or "en_AU" for English as used in Australia. For example:

    "CREATE VIRTUAL TABLE thai_text USING fts2(text, tokenizer icu th_TH)"

  The ICU tokenizer implementation is very simple. It splits the input
  text according to the ICU rules for finding word boundaries and discards
  any tokens that consist entirely of white-space. This may be suitable
  for some applications in some locales, but not all. If more complex
  processing is required, for example to implement stemming or 
  discard punctuation, this can be done by creating a tokenizer 
  implementation that uses the ICU tokenizer as part of its implementation.

  When using the ICU tokenizer this way, it is safe to overwrite the
  contents of the strings returned by the xNext() method (see
  fts2_tokenizer.h).

4. Sample code.

  The following two code samples illustrate the way C code should invoke
  the fts2_tokenizer() scalar function:

      int registerTokenizer(
        sqlite3 *db, 
        char *zName, 
        const sqlite3_tokenizer_module *p
      ){
        int rc;
        sqlite3_stmt *pStmt;
        const char zSql[] = "SELECT fts2_tokenizer(?, ?)";
      
        rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
        if( rc!=SQLITE_OK ){
          return rc;
        }
      
        sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
        sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
        sqlite3_step(pStmt);
      
        return sqlite3_finalize(pStmt);
      }
      
      int queryTokenizer(
        sqlite3 *db, 
        char *zName,  
        const sqlite3_tokenizer_module **pp
      ){
        int rc;
        sqlite3_stmt *pStmt;
        const char zSql[] = "SELECT fts2_tokenizer(?)";
      
        *pp = 0;
        rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
        if( rc!=SQLITE_OK ){
          return rc;
        }
      
        sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
        if( SQLITE_ROW==sqlite3_step(pStmt) ){
          if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
            memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
          }
        }
      
        return sqlite3_finalize(pStmt);
      }

Added ext/fts2/README.txt.









>
>
>
>
1
2
3
4
This folder contains source code to the second full-text search
extension for SQLite.  While the API is the same, this version uses a
substantially different storage schema from fts1, so tables will need
to be rebuilt.

Added ext/fts2/fts2.c.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
/* fts2 has a design flaw which can lead to database corruption (see
** below).  It is recommended not to use it any longer, instead use
** fts3 (or higher).  If you believe that your use of fts2 is safe,
** add -DSQLITE_ENABLE_BROKEN_FTS2=1 to your CFLAGS.
*/
#if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)) \
        && !defined(SQLITE_ENABLE_BROKEN_FTS2)
#error fts2 has a design flaw and has been deprecated.
#endif
/* The flaw is that fts2 uses the content table's unaliased rowid as
** the unique docid.  fts2 embeds the rowid in the index it builds,
** and expects the rowid to not change.  The SQLite VACUUM operation
** will renumber such rowids, thereby breaking fts2.  If you are using
** fts2 in a system which has disabled VACUUM, then you can continue
** to use it safely.  Note that PRAGMA auto_vacuum does NOT disable
** VACUUM, though systems using auto_vacuum are unlikely to invoke
** VACUUM.
**
** Unlike fts1, which is safe across VACUUM if you never delete
** documents, fts2 has a second exposure to this flaw, in the segments
** table.  So fts2 should be considered unsafe across VACUUM in all
** cases.
*/

/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is an SQLite module implementing full-text search.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/

/* TODO(shess) Consider exporting this comment to an HTML file or the
** wiki.
*/
/* The full-text index is stored in a series of b+tree (-like)
** structures called segments which map terms to doclists.  The
** structures are like b+trees in layout, but are constructed from the
** bottom up in optimal fashion and are not updatable.  Since trees
** are built from the bottom up, things will be described from the
** bottom up.
**
**
**** Varints ****
** The basic unit of encoding is a variable-length integer called a
** varint.  We encode variable-length integers in little-endian order
** using seven bits * per byte as follows:
**
** KEY:
**         A = 0xxxxxxx    7 bits of data and one flag bit
**         B = 1xxxxxxx    7 bits of data and one flag bit
**
**  7 bits - A
** 14 bits - BA
** 21 bits - BBA
** and so on.
**
** This is identical to how sqlite encodes varints (see util.c).
**
**
**** Document lists ****
** A doclist (document list) holds a docid-sorted list of hits for a
** given term.  Doclists hold docids, and can optionally associate
** token positions and offsets with docids.
**
** A DL_POSITIONS_OFFSETS doclist is stored like this:
**
** array {
**   varint docid;
**   array {                (position list for column 0)
**     varint position;     (delta from previous position plus POS_BASE)
**     varint startOffset;  (delta from previous startOffset)
**     varint endOffset;    (delta from startOffset)
**   }
**   array {
**     varint POS_COLUMN;   (marks start of position list for new column)
**     varint column;       (index of new column)
**     array {
**       varint position;   (delta from previous position plus POS_BASE)
**       varint startOffset;(delta from previous startOffset)
**       varint endOffset;  (delta from startOffset)
**     }
**   }
**   varint POS_END;        (marks end of positions for this document.
** }
**
** Here, array { X } means zero or more occurrences of X, adjacent in
** memory.  A "position" is an index of a token in the token stream
** generated by the tokenizer, while an "offset" is a byte offset,
** both based at 0.  Note that POS_END and POS_COLUMN occur in the
** same logical place as the position element, and act as sentinals
** ending a position list array.
**
** A DL_POSITIONS doclist omits the startOffset and endOffset
** information.  A DL_DOCIDS doclist omits both the position and
** offset information, becoming an array of varint-encoded docids.
**
** On-disk data is stored as type DL_DEFAULT, so we don't serialize
** the type.  Due to how deletion is implemented in the segmentation
** system, on-disk doclists MUST store at least positions.
**
**
**** Segment leaf nodes ****
** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
** nodes are written using LeafWriter, and read using LeafReader (to
** iterate through a single leaf node's data) and LeavesReader (to
** iterate through a segment's entire leaf layer).  Leaf nodes have
** the format:
**
** varint iHeight;             (height from leaf level, always 0)
** varint nTerm;               (length of first term)
** char pTerm[nTerm];          (content of first term)
** varint nDoclist;            (length of term's associated doclist)
** char pDoclist[nDoclist];    (content of doclist)
** array {
**                             (further terms are delta-encoded)
**   varint nPrefix;           (length of prefix shared with previous term)
**   varint nSuffix;           (length of unshared suffix)
**   char pTermSuffix[nSuffix];(unshared suffix of next term)
**   varint nDoclist;          (length of term's associated doclist)
**   char pDoclist[nDoclist];  (content of doclist)
** }
**
** Here, array { X } means zero or more occurrences of X, adjacent in
** memory.
**
** Leaf nodes are broken into blocks which are stored contiguously in
** the %_segments table in sorted order.  This means that when the end
** of a node is reached, the next term is in the node with the next
** greater node id.
**
** New data is spilled to a new leaf node when the current node
** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
** larger than STANDALONE_MIN (default 1024) is placed in a standalone
** node (a leaf node with a single term and doclist).  The goal of
** these settings is to pack together groups of small doclists while
** making it efficient to directly access large doclists.  The
** assumption is that large doclists represent terms which are more
** likely to be query targets.
**
** TODO(shess) It may be useful for blocking decisions to be more
** dynamic.  For instance, it may make more sense to have a 2.5k leaf
** node rather than splitting into 2k and .5k nodes.  My intuition is
** that this might extend through 2x or 4x the pagesize.
**
**
**** Segment interior nodes ****
** Segment interior nodes store blockids for subtree nodes and terms
** to describe what data is stored by the each subtree.  Interior
** nodes are written using InteriorWriter, and read using
** InteriorReader.  InteriorWriters are created as needed when
** SegmentWriter creates new leaf nodes, or when an interior node
** itself grows too big and must be split.  The format of interior
** nodes:
**
** varint iHeight;           (height from leaf level, always >0)
** varint iBlockid;          (block id of node's leftmost subtree)
** optional {
**   varint nTerm;           (length of first term)
**   char pTerm[nTerm];      (content of first term)
**   array {
**                                (further terms are delta-encoded)
**     varint nPrefix;            (length of shared prefix with previous term)
**     varint nSuffix;            (length of unshared suffix)
**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
**   }
** }
**
** Here, optional { X } means an optional element, while array { X }
** means zero or more occurrences of X, adjacent in memory.
**
** An interior node encodes n terms separating n+1 subtrees.  The
** subtree blocks are contiguous, so only the first subtree's blockid
** is encoded.  The subtree at iBlockid will contain all terms less
** than the first term encoded (or all terms if no term is encoded).
** Otherwise, for terms greater than or equal to pTerm[i] but less
** than pTerm[i+1], the subtree for that term will be rooted at
** iBlockid+i.  Interior nodes only store enough term data to
** distinguish adjacent children (if the rightmost term of the left
** child is "something", and the leftmost term of the right child is
** "wicked", only "w" is stored).
**
** New data is spilled to a new interior node at the same height when
** the current node exceeds INTERIOR_MAX bytes (default 2048).
** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
** interior nodes and making the tree too skinny.  The interior nodes
** at a given height are naturally tracked by interior nodes at
** height+1, and so on.
**
**
**** Segment directory ****
** The segment directory in table %_segdir stores meta-information for
** merging and deleting segments, and also the root node of the
** segment's tree.
**
** The root node is the top node of the segment's tree after encoding
** the entire segment, restricted to ROOT_MAX bytes (default 1024).
** This could be either a leaf node or an interior node.  If the top
** node requires more than ROOT_MAX bytes, it is flushed to %_segments
** and a new root interior node is generated (which should always fit
** within ROOT_MAX because it only needs space for 2 varints, the
** height and the blockid of the previous root).
**
** The meta-information in the segment directory is:
**   level               - segment level (see below)
**   idx                 - index within level
**                       - (level,idx uniquely identify a segment)
**   start_block         - first leaf node
**   leaves_end_block    - last leaf node
**   end_block           - last block (including interior nodes)
**   root                - contents of root node
**
** If the root node is a leaf node, then start_block,
** leaves_end_block, and end_block are all 0.
**
**
**** Segment merging ****
** To amortize update costs, segments are groups into levels and
** merged in matches.  Each increase in level represents exponentially
** more documents.
**
** New documents (actually, document updates) are tokenized and
** written individually (using LeafWriter) to a level 0 segment, with
** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
** level 0 segments are merged into a single level 1 segment.  Level 1
** is populated like level 0, and eventually MERGE_COUNT level 1
** segments are merged to a single level 2 segment (representing
** MERGE_COUNT^2 updates), and so on.
**
** A segment merge traverses all segments at a given level in
** parallel, performing a straightforward sorted merge.  Since segment
** leaf nodes are written in to the %_segments table in order, this
** merge traverses the underlying sqlite disk structures efficiently.
** After the merge, all segment blocks from the merged level are
** deleted.
**
** MERGE_COUNT controls how often we merge segments.  16 seems to be
** somewhat of a sweet spot for insertion performance.  32 and 64 show
** very similar performance numbers to 16 on insertion, though they're
** a tiny bit slower (perhaps due to more overhead in merge-time
** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
** 16, 2 about 66% slower than 16.
**
** At query time, high MERGE_COUNT increases the number of segments
** which need to be scanned and merged.  For instance, with 100k docs
** inserted:
**
**    MERGE_COUNT   segments
**       16           25
**        8           12
**        4           10
**        2            6
**
** This appears to have only a moderate impact on queries for very
** frequent terms (which are somewhat dominated by segment merge
** costs), and infrequent and non-existent terms still seem to be fast
** even with many segments.
**
** TODO(shess) That said, it would be nice to have a better query-side
** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
** optimizations to things like doclist merging will swing the sweet
** spot around.
**
**
**
**** Handling of deletions and updates ****
** Since we're using a segmented structure, with no docid-oriented
** index into the term index, we clearly cannot simply update the term
** index when a document is deleted or updated.  For deletions, we
** write an empty doclist (varint(docid) varint(POS_END)), for updates
** we simply write the new doclist.  Segment merges overwrite older
** data for a particular docid with newer data, so deletes or updates
** will eventually overtake the earlier data and knock it out.  The
** query logic likewise merges doclists so that newer data knocks out
** older data.
**
** TODO(shess) Provide a VACUUM type operation to clear out all
** deletions and duplications.  This would basically be a forced merge
** into a single segment.
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)

#if defined(SQLITE_ENABLE_FTS2) && !defined(SQLITE_CORE)
# define SQLITE_CORE 1
#endif

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts2.h"
#include "fts2_hash.h"
#include "fts2_tokenizer.h"
#include "sqlite3.h"
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1


/* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
** would be nice to order the file better, perhaps something along the
** lines of:
**
**  - utility functions
**  - table setup functions
**  - table update functions
**  - table query functions
**
** Put the query functions last because they're likely to reference
** typedefs or functions from the table update section.
*/

#if 0
# define TRACE(A)  printf A; fflush(stdout)
#else
# define TRACE(A)
#endif

/* It is not safe to call isspace(), tolower(), or isalnum() on
** hi-bit-set characters.  This is the same solution used in the
** tokenizer.
*/
/* TODO(shess) The snippet-generation code should be using the
** tokenizer-generated tokens rather than doing its own local
** tokenization.
*/
/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
static int safe_isspace(char c){
  return (c&0x80)==0 ? isspace(c) : 0;
}
static int safe_tolower(char c){
  return (c&0x80)==0 ? tolower(c) : c;
}
static int safe_isalnum(char c){
  return (c&0x80)==0 ? isalnum(c) : 0;
}

typedef enum DocListType {
  DL_DOCIDS,              /* docids only */
  DL_POSITIONS,           /* docids + positions */
  DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
} DocListType;

/*
** By default, only positions and not offsets are stored in the doclists.
** To change this so that offsets are stored too, compile with
**
**          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
**
** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
** into (no deletes or updates).
*/
#ifndef DL_DEFAULT
# define DL_DEFAULT DL_POSITIONS
#endif

enum {
  POS_END = 0,        /* end of this position list */
  POS_COLUMN,         /* followed by new column number */
  POS_BASE
};

/* MERGE_COUNT controls how often we merge segments (see comment at
** top of file).
*/
#define MERGE_COUNT 16

/* utility functions */

/* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
** record to prevent errors of the form:
**
** my_function(SomeType *b){
**   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
** }
*/
/* TODO(shess) Obvious candidates for a header file. */
#define CLEAR(b) memset(b, '\0', sizeof(*(b)))

#ifndef NDEBUG
#  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
#else
#  define SCRAMBLE(b)
#endif

/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
#define VARINT_MAX 10

/* Write a 64-bit variable-length integer to memory starting at p[0].
 * The length of data written will be between 1 and VARINT_MAX bytes.
 * The number of bytes written is returned. */
static int putVarint(char *p, sqlite_int64 v){
  unsigned char *q = (unsigned char *) p;
  sqlite_uint64 vu = v;
  do{
    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
    vu >>= 7;
  }while( vu!=0 );
  q[-1] &= 0x7f;  /* turn off high bit in final byte */
  assert( q - (unsigned char *)p <= VARINT_MAX );
  return (int) (q - (unsigned char *)p);
}

/* Read a 64-bit variable-length integer from memory starting at p[0].
 * Return the number of bytes read, or 0 on error.
 * The value is stored in *v. */
static int getVarint(const char *p, sqlite_int64 *v){
  const unsigned char *q = (const unsigned char *) p;
  sqlite_uint64 x = 0, y = 1;
  while( (*q & 0x80) == 0x80 ){
    x += y * (*q++ & 0x7f);
    y <<= 7;
    if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
      assert( 0 );
      return 0;
    }
  }
  x += y * (*q++);
  *v = (sqlite_int64) x;
  return (int) (q - (unsigned char *)p);
}

static int getVarint32(const char *p, int *pi){
 sqlite_int64 i;
 int ret = getVarint(p, &i);
 *pi = (int) i;
 assert( *pi==i );
 return ret;
}

/*******************************************************************/
/* DataBuffer is used to collect data into a buffer in piecemeal
** fashion.  It implements the usual distinction between amount of
** data currently stored (nData) and buffer capacity (nCapacity).
**
** dataBufferInit - create a buffer with given initial capacity.
** dataBufferReset - forget buffer's data, retaining capacity.
** dataBufferDestroy - free buffer's data.
** dataBufferSwap - swap contents of two buffers.
** dataBufferExpand - expand capacity without adding data.
** dataBufferAppend - append data.
** dataBufferAppend2 - append two pieces of data at once.
** dataBufferReplace - replace buffer's data.
*/
typedef struct DataBuffer {
  char *pData;          /* Pointer to malloc'ed buffer. */
  int nCapacity;        /* Size of pData buffer. */
  int nData;            /* End of data loaded into pData. */
} DataBuffer;

static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
  assert( nCapacity>=0 );
  pBuffer->nData = 0;
  pBuffer->nCapacity = nCapacity;
  pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
}
static void dataBufferReset(DataBuffer *pBuffer){
  pBuffer->nData = 0;
}
static void dataBufferDestroy(DataBuffer *pBuffer){
  if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
  SCRAMBLE(pBuffer);
}
static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
  DataBuffer tmp = *pBuffer1;
  *pBuffer1 = *pBuffer2;
  *pBuffer2 = tmp;
}
static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
  assert( nAddCapacity>0 );
  /* TODO(shess) Consider expanding more aggressively.  Note that the
  ** underlying malloc implementation may take care of such things for
  ** us already.
  */
  if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
    pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
    pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
  }
}
static void dataBufferAppend(DataBuffer *pBuffer,
                             const char *pSource, int nSource){
  assert( nSource>0 && pSource!=NULL );
  dataBufferExpand(pBuffer, nSource);
  memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
  pBuffer->nData += nSource;
}
static void dataBufferAppend2(DataBuffer *pBuffer,
                              const char *pSource1, int nSource1,
                              const char *pSource2, int nSource2){
  assert( nSource1>0 && pSource1!=NULL );
  assert( nSource2>0 && pSource2!=NULL );
  dataBufferExpand(pBuffer, nSource1+nSource2);
  memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
  memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
  pBuffer->nData += nSource1+nSource2;
}
static void dataBufferReplace(DataBuffer *pBuffer,
                              const char *pSource, int nSource){
  dataBufferReset(pBuffer);
  dataBufferAppend(pBuffer, pSource, nSource);
}

/* StringBuffer is a null-terminated version of DataBuffer. */
typedef struct StringBuffer {
  DataBuffer b;            /* Includes null terminator. */
} StringBuffer;

static void initStringBuffer(StringBuffer *sb){
  dataBufferInit(&sb->b, 100);
  dataBufferReplace(&sb->b, "", 1);
}
static int stringBufferLength(StringBuffer *sb){
  return sb->b.nData-1;
}
static char *stringBufferData(StringBuffer *sb){
  return sb->b.pData;
}
static void stringBufferDestroy(StringBuffer *sb){
  dataBufferDestroy(&sb->b);
}

static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
  assert( sb->b.nData>0 );
  if( nFrom>0 ){
    sb->b.nData--;
    dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
  }
}
static void append(StringBuffer *sb, const char *zFrom){
  nappend(sb, zFrom, strlen(zFrom));
}

/* Append a list of strings separated by commas. */
static void appendList(StringBuffer *sb, int nString, char **azString){
  int i;
  for(i=0; i<nString; ++i){
    if( i>0 ) append(sb, ", ");
    append(sb, azString[i]);
  }
}

static int endsInWhiteSpace(StringBuffer *p){
  return stringBufferLength(p)>0 &&
    safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
}

/* If the StringBuffer ends in something other than white space, add a
** single space character to the end.
*/
static void appendWhiteSpace(StringBuffer *p){
  if( stringBufferLength(p)==0 ) return;
  if( !endsInWhiteSpace(p) ) append(p, " ");
}

/* Remove white space from the end of the StringBuffer */
static void trimWhiteSpace(StringBuffer *p){
  while( endsInWhiteSpace(p) ){
    p->b.pData[--p->b.nData-1] = '\0';
  }
}

/*******************************************************************/
/* DLReader is used to read document elements from a doclist.  The
** current docid is cached, so dlrDocid() is fast.  DLReader does not
** own the doclist buffer.
**
** dlrAtEnd - true if there's no more data to read.
** dlrDocid - docid of current document.
** dlrDocData - doclist data for current document (including docid).
** dlrDocDataBytes - length of same.
** dlrAllDataBytes - length of all remaining data.
** dlrPosData - position data for current document.
** dlrPosDataLen - length of pos data for current document (incl POS_END).
** dlrStep - step to current document.
** dlrInit - initial for doclist of given type against given data.
** dlrDestroy - clean up.
**
** Expected usage is something like:
**
**   DLReader reader;
**   dlrInit(&reader, pData, nData);
**   while( !dlrAtEnd(&reader) ){
**     // calls to dlrDocid() and kin.
**     dlrStep(&reader);
**   }
**   dlrDestroy(&reader);
*/
typedef struct DLReader {
  DocListType iType;
  const char *pData;
  int nData;

  sqlite_int64 iDocid;
  int nElement;
} DLReader;

static int dlrAtEnd(DLReader *pReader){
  assert( pReader->nData>=0 );
  return pReader->nData==0;
}
static sqlite_int64 dlrDocid(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->iDocid;
}
static const char *dlrDocData(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->pData;
}
static int dlrDocDataBytes(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->nElement;
}
static int dlrAllDataBytes(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->nData;
}
/* TODO(shess) Consider adding a field to track iDocid varint length
** to make these two functions faster.  This might matter (a tiny bit)
** for queries.
*/
static const char *dlrPosData(DLReader *pReader){
  sqlite_int64 iDummy;
  int n = getVarint(pReader->pData, &iDummy);
  assert( !dlrAtEnd(pReader) );
  return pReader->pData+n;
}
static int dlrPosDataLen(DLReader *pReader){
  sqlite_int64 iDummy;
  int n = getVarint(pReader->pData, &iDummy);
  assert( !dlrAtEnd(pReader) );
  return pReader->nElement-n;
}
static void dlrStep(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );

  /* Skip past current doclist element. */
  assert( pReader->nElement<=pReader->nData );
  pReader->pData += pReader->nElement;
  pReader->nData -= pReader->nElement;

  /* If there is more data, read the next doclist element. */
  if( pReader->nData!=0 ){
    sqlite_int64 iDocidDelta;
    int iDummy, n = getVarint(pReader->pData, &iDocidDelta);
    pReader->iDocid += iDocidDelta;
    if( pReader->iType>=DL_POSITIONS ){
      assert( n<pReader->nData );
      while( 1 ){
        n += getVarint32(pReader->pData+n, &iDummy);
        assert( n<=pReader->nData );
        if( iDummy==POS_END ) break;
        if( iDummy==POS_COLUMN ){
          n += getVarint32(pReader->pData+n, &iDummy);
          assert( n<pReader->nData );
        }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
          n += getVarint32(pReader->pData+n, &iDummy);
          n += getVarint32(pReader->pData+n, &iDummy);
          assert( n<pReader->nData );
        }
      }
    }
    pReader->nElement = n;
    assert( pReader->nElement<=pReader->nData );
  }
}
static void dlrInit(DLReader *pReader, DocListType iType,
                    const char *pData, int nData){
  assert( pData!=NULL && nData!=0 );
  pReader->iType = iType;
  pReader->pData = pData;
  pReader->nData = nData;
  pReader->nElement = 0;
  pReader->iDocid = 0;

  /* Load the first element's data.  There must be a first element. */
  dlrStep(pReader);
}
static void dlrDestroy(DLReader *pReader){
  SCRAMBLE(pReader);
}

#ifndef NDEBUG
/* Verify that the doclist can be validly decoded.  Also returns the
** last docid found because it is convenient in other assertions for
** DLWriter.
*/
static void docListValidate(DocListType iType, const char *pData, int nData,
                            sqlite_int64 *pLastDocid){
  sqlite_int64 iPrevDocid = 0;
  assert( nData>0 );
  assert( pData!=0 );
  assert( pData+nData>pData );
  while( nData!=0 ){
    sqlite_int64 iDocidDelta;
    int n = getVarint(pData, &iDocidDelta);
    iPrevDocid += iDocidDelta;
    if( iType>DL_DOCIDS ){
      int iDummy;
      while( 1 ){
        n += getVarint32(pData+n, &iDummy);
        if( iDummy==POS_END ) break;
        if( iDummy==POS_COLUMN ){
          n += getVarint32(pData+n, &iDummy);
        }else if( iType>DL_POSITIONS ){
          n += getVarint32(pData+n, &iDummy);
          n += getVarint32(pData+n, &iDummy);
        }
        assert( n<=nData );
      }
    }
    assert( n<=nData );
    pData += n;
    nData -= n;
  }
  if( pLastDocid ) *pLastDocid = iPrevDocid;
}
#define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
#else
#define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
#endif

/*******************************************************************/
/* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
** always appends to the buffer and does not own it.
**
** dlwInit - initialize to write a given type doclistto a buffer.
** dlwDestroy - clear the writer's memory.  Does not free buffer.
** dlwAppend - append raw doclist data to buffer.
** dlwCopy - copy next doclist from reader to writer.
** dlwAdd - construct doclist element and append to buffer.
**    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
*/
typedef struct DLWriter {
  DocListType iType;
  DataBuffer *b;
  sqlite_int64 iPrevDocid;
#ifndef NDEBUG
  int has_iPrevDocid;
#endif
} DLWriter;

static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
  pWriter->b = b;
  pWriter->iType = iType;
  pWriter->iPrevDocid = 0;
#ifndef NDEBUG
  pWriter->has_iPrevDocid = 0;
#endif
}
static void dlwDestroy(DLWriter *pWriter){
  SCRAMBLE(pWriter);
}
/* iFirstDocid is the first docid in the doclist in pData.  It is
** needed because pData may point within a larger doclist, in which
** case the first item would be delta-encoded.
**
** iLastDocid is the final docid in the doclist in pData.  It is
** needed to create the new iPrevDocid for future delta-encoding.  The
** code could decode the passed doclist to recreate iLastDocid, but
** the only current user (docListMerge) already has decoded this
** information.
*/
/* TODO(shess) This has become just a helper for docListMerge.
** Consider a refactor to make this cleaner.
*/
static void dlwAppend(DLWriter *pWriter,
                      const char *pData, int nData,
                      sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
  sqlite_int64 iDocid = 0;
  char c[VARINT_MAX];
  int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
#ifndef NDEBUG
  sqlite_int64 iLastDocidDelta;
#endif

  /* Recode the initial docid as delta from iPrevDocid. */
  nFirstOld = getVarint(pData, &iDocid);
  assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
  nFirstNew = putVarint(c, iFirstDocid-pWriter->iPrevDocid);

  /* Verify that the incoming doclist is valid AND that it ends with
  ** the expected docid.  This is essential because we'll trust this
  ** docid in future delta-encoding.
  */
  ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
  assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );

  /* Append recoded initial docid and everything else.  Rest of docids
  ** should have been delta-encoded from previous initial docid.
  */
  if( nFirstOld<nData ){
    dataBufferAppend2(pWriter->b, c, nFirstNew,
                      pData+nFirstOld, nData-nFirstOld);
  }else{
    dataBufferAppend(pWriter->b, c, nFirstNew);
  }
  pWriter->iPrevDocid = iLastDocid;
}
static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
  dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
            dlrDocid(pReader), dlrDocid(pReader));
}
static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
  char c[VARINT_MAX];
  int n = putVarint(c, iDocid-pWriter->iPrevDocid);

  /* Docids must ascend. */
  assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
  assert( pWriter->iType==DL_DOCIDS );

  dataBufferAppend(pWriter->b, c, n);
  pWriter->iPrevDocid = iDocid;
#ifndef NDEBUG
  pWriter->has_iPrevDocid = 1;
#endif
}

/*******************************************************************/
/* PLReader is used to read data from a document's position list.  As
** the caller steps through the list, data is cached so that varints
** only need to be decoded once.
**
** plrInit, plrDestroy - create/destroy a reader.
** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
** plrAtEnd - at end of stream, only call plrDestroy once true.
** plrStep - step to the next element.
*/
typedef struct PLReader {
  /* These refer to the next position's data.  nData will reach 0 when
  ** reading the last position, so plrStep() signals EOF by setting
  ** pData to NULL.
  */
  const char *pData;
  int nData;

  DocListType iType;
  int iColumn;         /* the last column read */
  int iPosition;       /* the last position read */
  int iStartOffset;    /* the last start offset read */
  int iEndOffset;      /* the last end offset read */
} PLReader;

static int plrAtEnd(PLReader *pReader){
  return pReader->pData==NULL;
}
static int plrColumn(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iColumn;
}
static int plrPosition(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iPosition;
}
static int plrStartOffset(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iStartOffset;
}
static int plrEndOffset(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iEndOffset;
}
static void plrStep(PLReader *pReader){
  int i, n;

  assert( !plrAtEnd(pReader) );

  if( pReader->nData==0 ){
    pReader->pData = NULL;
    return;
  }

  n = getVarint32(pReader->pData, &i);
  if( i==POS_COLUMN ){
    n += getVarint32(pReader->pData+n, &pReader->iColumn);
    pReader->iPosition = 0;
    pReader->iStartOffset = 0;
    n += getVarint32(pReader->pData+n, &i);
  }
  /* Should never see adjacent column changes. */
  assert( i!=POS_COLUMN );

  if( i==POS_END ){
    pReader->nData = 0;
    pReader->pData = NULL;
    return;
  }

  pReader->iPosition += i-POS_BASE;
  if( pReader->iType==DL_POSITIONS_OFFSETS ){
    n += getVarint32(pReader->pData+n, &i);
    pReader->iStartOffset += i;
    n += getVarint32(pReader->pData+n, &i);
    pReader->iEndOffset = pReader->iStartOffset+i;
  }
  assert( n<=pReader->nData );
  pReader->pData += n;
  pReader->nData -= n;
}

static void plrInit(PLReader *pReader, DLReader *pDLReader){
  pReader->pData = dlrPosData(pDLReader);
  pReader->nData = dlrPosDataLen(pDLReader);
  pReader->iType = pDLReader->iType;
  pReader->iColumn = 0;
  pReader->iPosition = 0;
  pReader->iStartOffset = 0;
  pReader->iEndOffset = 0;
  plrStep(pReader);
}
static void plrDestroy(PLReader *pReader){
  SCRAMBLE(pReader);
}

/*******************************************************************/
/* PLWriter is used in constructing a document's position list.  As a
** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
** PLWriter writes to the associated DLWriter's buffer.
**
** plwInit - init for writing a document's poslist.
** plwDestroy - clear a writer.
** plwAdd - append position and offset information.
** plwCopy - copy next position's data from reader to writer.
** plwTerminate - add any necessary doclist terminator.
**
** Calling plwAdd() after plwTerminate() may result in a corrupt
** doclist.
*/
/* TODO(shess) Until we've written the second item, we can cache the
** first item's information.  Then we'd have three states:
**
** - initialized with docid, no positions.
** - docid and one position.
** - docid and multiple positions.
**
** Only the last state needs to actually write to dlw->b, which would
** be an improvement in the DLCollector case.
*/
typedef struct PLWriter {
  DLWriter *dlw;

  int iColumn;    /* the last column written */
  int iPos;       /* the last position written */
  int iOffset;    /* the last start offset written */
} PLWriter;

/* TODO(shess) In the case where the parent is reading these values
** from a PLReader, we could optimize to a copy if that PLReader has
** the same type as pWriter.
*/
static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
                   int iStartOffset, int iEndOffset){
  /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
  ** iStartOffsetDelta, and iEndOffsetDelta.
  */
  char c[5*VARINT_MAX];
  int n = 0;

  /* Ban plwAdd() after plwTerminate(). */
  assert( pWriter->iPos!=-1 );

  if( pWriter->dlw->iType==DL_DOCIDS ) return;

  if( iColumn!=pWriter->iColumn ){
    n += putVarint(c+n, POS_COLUMN);
    n += putVarint(c+n, iColumn);
    pWriter->iColumn = iColumn;
    pWriter->iPos = 0;
    pWriter->iOffset = 0;
  }
  assert( iPos>=pWriter->iPos );
  n += putVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
  pWriter->iPos = iPos;
  if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
    assert( iStartOffset>=pWriter->iOffset );
    n += putVarint(c+n, iStartOffset-pWriter->iOffset);
    pWriter->iOffset = iStartOffset;
    assert( iEndOffset>=iStartOffset );
    n += putVarint(c+n, iEndOffset-iStartOffset);
  }
  dataBufferAppend(pWriter->dlw->b, c, n);
}
static void plwCopy(PLWriter *pWriter, PLReader *pReader){
  plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
         plrStartOffset(pReader), plrEndOffset(pReader));
}
static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
  char c[VARINT_MAX];
  int n;

  pWriter->dlw = dlw;

  /* Docids must ascend. */
  assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
  n = putVarint(c, iDocid-pWriter->dlw->iPrevDocid);
  dataBufferAppend(pWriter->dlw->b, c, n);
  pWriter->dlw->iPrevDocid = iDocid;
#ifndef NDEBUG
  pWriter->dlw->has_iPrevDocid = 1;
#endif

  pWriter->iColumn = 0;
  pWriter->iPos = 0;
  pWriter->iOffset = 0;
}
/* TODO(shess) Should plwDestroy() also terminate the doclist?  But
** then plwDestroy() would no longer be just a destructor, it would
** also be doing work, which isn't consistent with the overall idiom.
** Another option would be for plwAdd() to always append any necessary
** terminator, so that the output is always correct.  But that would
** add incremental work to the common case with the only benefit being
** API elegance.  Punt for now.
*/
static void plwTerminate(PLWriter *pWriter){
  if( pWriter->dlw->iType>DL_DOCIDS ){
    char c[VARINT_MAX];
    int n = putVarint(c, POS_END);
    dataBufferAppend(pWriter->dlw->b, c, n);
  }
#ifndef NDEBUG
  /* Mark as terminated for assert in plwAdd(). */
  pWriter->iPos = -1;
#endif
}
static void plwDestroy(PLWriter *pWriter){
  SCRAMBLE(pWriter);
}

/*******************************************************************/
/* DLCollector wraps PLWriter and DLWriter to provide a
** dynamically-allocated doclist area to use during tokenization.
**
** dlcNew - malloc up and initialize a collector.
** dlcDelete - destroy a collector and all contained items.
** dlcAddPos - append position and offset information.
** dlcAddDoclist - add the collected doclist to the given buffer.
** dlcNext - terminate the current document and open another.
*/
typedef struct DLCollector {
  DataBuffer b;
  DLWriter dlw;
  PLWriter plw;
} DLCollector;

/* TODO(shess) This could also be done by calling plwTerminate() and
** dataBufferAppend().  I tried that, expecting nominal performance
** differences, but it seemed to pretty reliably be worth 1% to code
** it this way.  I suspect it is the incremental malloc overhead (some
** percentage of the plwTerminate() calls will cause a realloc), so
** this might be worth revisiting if the DataBuffer implementation
** changes.
*/
static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
  if( pCollector->dlw.iType>DL_DOCIDS ){
    char c[VARINT_MAX];
    int n = putVarint(c, POS_END);
    dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
  }else{
    dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
  }
}
static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
  plwTerminate(&pCollector->plw);
  plwDestroy(&pCollector->plw);
  plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
}
static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
                      int iStartOffset, int iEndOffset){
  plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
}

static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
  DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
  dataBufferInit(&pCollector->b, 0);
  dlwInit(&pCollector->dlw, iType, &pCollector->b);
  plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  return pCollector;
}
static void dlcDelete(DLCollector *pCollector){
  plwDestroy(&pCollector->plw);
  dlwDestroy(&pCollector->dlw);
  dataBufferDestroy(&pCollector->b);
  SCRAMBLE(pCollector);
  sqlite3_free(pCollector);
}


/* Copy the doclist data of iType in pData/nData into *out, trimming
** unnecessary data as we go.  Only columns matching iColumn are
** copied, all columns copied if iColumn is -1.  Elements with no
** matching columns are dropped.  The output is an iOutType doclist.
*/
/* NOTE(shess) This code is only valid after all doclists are merged.
** If this is run before merges, then doclist items which represent
** deletion will be trimmed, and will thus not effect a deletion
** during the merge.
*/
static void docListTrim(DocListType iType, const char *pData, int nData,
                        int iColumn, DocListType iOutType, DataBuffer *out){
  DLReader dlReader;
  DLWriter dlWriter;

  assert( iOutType<=iType );

  dlrInit(&dlReader, iType, pData, nData);
  dlwInit(&dlWriter, iOutType, out);

  while( !dlrAtEnd(&dlReader) ){
    PLReader plReader;
    PLWriter plWriter;
    int match = 0;

    plrInit(&plReader, &dlReader);

    while( !plrAtEnd(&plReader) ){
      if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
        if( !match ){
          plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
          match = 1;
        }
        plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
               plrStartOffset(&plReader), plrEndOffset(&plReader));
      }
      plrStep(&plReader);
    }
    if( match ){
      plwTerminate(&plWriter);
      plwDestroy(&plWriter);
    }

    plrDestroy(&plReader);
    dlrStep(&dlReader);
  }
  dlwDestroy(&dlWriter);
  dlrDestroy(&dlReader);
}

/* Used by docListMerge() to keep doclists in the ascending order by
** docid, then ascending order by age (so the newest comes first).
*/
typedef struct OrderedDLReader {
  DLReader *pReader;

  /* TODO(shess) If we assume that docListMerge pReaders is ordered by
  ** age (which we do), then we could use pReader comparisons to break
  ** ties.
  */
  int idx;
} OrderedDLReader;

/* Order eof to end, then by docid asc, idx desc. */
static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
  if( dlrAtEnd(r1->pReader) ){
    if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
    return 1;                              /* Only r1 atEnd(). */
  }
  if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */

  if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
  if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;

  /* Descending on idx. */
  return r2->idx-r1->idx;
}

/* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
** p[1..n-1] is already sorted.
*/
/* TODO(shess) Is this frequent enough to warrant a binary search?
** Before implementing that, instrument the code to check.  In most
** current usage, I expect that p[0] will be less than p[1] a very
** high proportion of the time.
*/
static void orderedDLReaderReorder(OrderedDLReader *p, int n){
  while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
    OrderedDLReader tmp = p[0];
    p[0] = p[1];
    p[1] = tmp;
    n--;
    p++;
  }
}

/* Given an array of doclist readers, merge their doclist elements
** into out in sorted order (by docid), dropping elements from older
** readers when there is a duplicate docid.  pReaders is assumed to be
** ordered by age, oldest first.
*/
/* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
** be fixed.
*/
static void docListMerge(DataBuffer *out,
                         DLReader *pReaders, int nReaders){
  OrderedDLReader readers[MERGE_COUNT];
  DLWriter writer;
  int i, n;
  const char *pStart = 0;
  int nStart = 0;
  sqlite_int64 iFirstDocid = 0, iLastDocid = 0;

  assert( nReaders>0 );
  if( nReaders==1 ){
    dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
    return;
  }

  assert( nReaders<=MERGE_COUNT );
  n = 0;
  for(i=0; i<nReaders; i++){
    assert( pReaders[i].iType==pReaders[0].iType );
    readers[i].pReader = pReaders+i;
    readers[i].idx = i;
    n += dlrAllDataBytes(&pReaders[i]);
  }
  /* Conservatively size output to sum of inputs.  Output should end
  ** up strictly smaller than input.
  */
  dataBufferExpand(out, n);

  /* Get the readers into sorted order. */
  while( i-->0 ){
    orderedDLReaderReorder(readers+i, nReaders-i);
  }

  dlwInit(&writer, pReaders[0].iType, out);
  while( !dlrAtEnd(readers[0].pReader) ){
    sqlite_int64 iDocid = dlrDocid(readers[0].pReader);

    /* If this is a continuation of the current buffer to copy, extend
    ** that buffer.  memcpy() seems to be more efficient if it has a
    ** lots of data to copy.
    */
    if( dlrDocData(readers[0].pReader)==pStart+nStart ){
      nStart += dlrDocDataBytes(readers[0].pReader);
    }else{
      if( pStart!=0 ){
        dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
      }
      pStart = dlrDocData(readers[0].pReader);
      nStart = dlrDocDataBytes(readers[0].pReader);
      iFirstDocid = iDocid;
    }
    iLastDocid = iDocid;
    dlrStep(readers[0].pReader);

    /* Drop all of the older elements with the same docid. */
    for(i=1; i<nReaders &&
             !dlrAtEnd(readers[i].pReader) &&
             dlrDocid(readers[i].pReader)==iDocid; i++){
      dlrStep(readers[i].pReader);
    }

    /* Get the readers back into order. */
    while( i-->0 ){
      orderedDLReaderReorder(readers+i, nReaders-i);
    }
  }

  /* Copy over any remaining elements. */
  if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  dlwDestroy(&writer);
}

/* Helper function for posListUnion().  Compares the current position
** between left and right, returning as standard C idiom of <0 if
** left<right, >0 if left>right, and 0 if left==right.  "End" always
** compares greater.
*/
static int posListCmp(PLReader *pLeft, PLReader *pRight){
  assert( pLeft->iType==pRight->iType );
  if( pLeft->iType==DL_DOCIDS ) return 0;

  if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
  if( plrAtEnd(pRight) ) return -1;

  if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
  if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;

  if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
  if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
  if( pLeft->iType==DL_POSITIONS ) return 0;

  if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
  if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;

  if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
  if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;

  return 0;
}

/* Write the union of position lists in pLeft and pRight to pOut.
** "Union" in this case meaning "All unique position tuples".  Should
** work with any doclist type, though both inputs and the output
** should be the same type.
*/
static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
  PLReader left, right;
  PLWriter writer;

  assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  assert( pLeft->iType==pRight->iType );
  assert( pLeft->iType==pOut->iType );

  plrInit(&left, pLeft);
  plrInit(&right, pRight);
  plwInit(&writer, pOut, dlrDocid(pLeft));

  while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
    int c = posListCmp(&left, &right);
    if( c<0 ){
      plwCopy(&writer, &left);
      plrStep(&left);
    }else if( c>0 ){
      plwCopy(&writer, &right);
      plrStep(&right);
    }else{
      plwCopy(&writer, &left);
      plrStep(&left);
      plrStep(&right);
    }
  }

  plwTerminate(&writer);
  plwDestroy(&writer);
  plrDestroy(&left);
  plrDestroy(&right);
}

/* Write the union of doclists in pLeft and pRight to pOut.  For
** docids in common between the inputs, the union of the position
** lists is written.  Inputs and outputs are always type DL_DEFAULT.
*/
static void docListUnion(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 ){
    if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
    return;
  }
  if( nRight==0 ){
    dataBufferAppend(pOut, pLeft, nLeft);
    return;
  }

  dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
  dlrInit(&right, DL_DEFAULT, pRight, nRight);
  dlwInit(&writer, DL_DEFAULT, pOut);

  while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
    if( dlrAtEnd(&right) ){
      dlwCopy(&writer, &left);
      dlrStep(&left);
    }else if( dlrAtEnd(&left) ){
      dlwCopy(&writer, &right);
      dlrStep(&right);
    }else if( dlrDocid(&left)<dlrDocid(&right) ){
      dlwCopy(&writer, &left);
      dlrStep(&left);
    }else if( dlrDocid(&left)>dlrDocid(&right) ){
      dlwCopy(&writer, &right);
      dlrStep(&right);
    }else{
      posListUnion(&left, &right, &writer);
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* pLeft and pRight are DLReaders positioned to the same docid.
**
** If there are no instances in pLeft or pRight where the position
** of pLeft is one less than the position of pRight, then this
** routine adds nothing to pOut.
**
** If there are one or more instances where positions from pLeft
** are exactly one less than positions from pRight, then add a new
** document record to pOut.  If pOut wants to hold positions, then
** include the positions from pRight that are one more than a
** position in pLeft.  In other words:  pRight.iPos==pLeft.iPos+1.
*/
static void posListPhraseMerge(DLReader *pLeft, DLReader *pRight,
                               DLWriter *pOut){
  PLReader left, right;
  PLWriter writer;
  int match = 0;

  assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  assert( pOut->iType!=DL_POSITIONS_OFFSETS );

  plrInit(&left, pLeft);
  plrInit(&right, pRight);

  while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
    if( plrColumn(&left)<plrColumn(&right) ){
      plrStep(&left);
    }else if( plrColumn(&left)>plrColumn(&right) ){
      plrStep(&right);
    }else if( plrPosition(&left)+1<plrPosition(&right) ){
      plrStep(&left);
    }else if( plrPosition(&left)+1>plrPosition(&right) ){
      plrStep(&right);
    }else{
      if( !match ){
        plwInit(&writer, pOut, dlrDocid(pLeft));
        match = 1;
      }
      plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
      plrStep(&left);
      plrStep(&right);
    }
  }

  if( match ){
    plwTerminate(&writer);
    plwDestroy(&writer);
  }

  plrDestroy(&left);
  plrDestroy(&right);
}

/* We have two doclists with positions:  pLeft and pRight.
** Write the phrase intersection of these two doclists into pOut.
**
** A phrase intersection means that two documents only match
** if pLeft.iPos+1==pRight.iPos.
**
** iType controls the type of data written to pOut.  If iType is
** DL_POSITIONS, the positions are those from pRight.
*/
static void docListPhraseMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DocListType iType,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 || nRight==0 ) return;

  assert( iType!=DL_POSITIONS_OFFSETS );

  dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
  dlrInit(&right, DL_POSITIONS, pRight, nRight);
  dlwInit(&writer, iType, pOut);

  while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
    if( dlrDocid(&left)<dlrDocid(&right) ){
      dlrStep(&left);
    }else if( dlrDocid(&right)<dlrDocid(&left) ){
      dlrStep(&right);
    }else{
      posListPhraseMerge(&left, &right, &writer);
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* We have two DL_DOCIDS doclists:  pLeft and pRight.
** Write the intersection of these two doclists into pOut as a
** DL_DOCIDS doclist.
*/
static void docListAndMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 || nRight==0 ) return;

  dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  dlrInit(&right, DL_DOCIDS, pRight, nRight);
  dlwInit(&writer, DL_DOCIDS, pOut);

  while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
    if( dlrDocid(&left)<dlrDocid(&right) ){
      dlrStep(&left);
    }else if( dlrDocid(&right)<dlrDocid(&left) ){
      dlrStep(&right);
    }else{
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* We have two DL_DOCIDS doclists:  pLeft and pRight.
** Write the union of these two doclists into pOut as a
** DL_DOCIDS doclist.
*/
static void docListOrMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 ){
    if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
    return;
  }
  if( nRight==0 ){
    dataBufferAppend(pOut, pLeft, nLeft);
    return;
  }

  dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  dlrInit(&right, DL_DOCIDS, pRight, nRight);
  dlwInit(&writer, DL_DOCIDS, pOut);

  while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
    if( dlrAtEnd(&right) ){
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
    }else if( dlrAtEnd(&left) ){
      dlwAdd(&writer, dlrDocid(&right));
      dlrStep(&right);
    }else if( dlrDocid(&left)<dlrDocid(&right) ){
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
    }else if( dlrDocid(&right)<dlrDocid(&left) ){
      dlwAdd(&writer, dlrDocid(&right));
      dlrStep(&right);
    }else{
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* We have two DL_DOCIDS doclists:  pLeft and pRight.
** Write into pOut as DL_DOCIDS doclist containing all documents that
** occur in pLeft but not in pRight.
*/
static void docListExceptMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 ) return;
  if( nRight==0 ){
    dataBufferAppend(pOut, pLeft, nLeft);
    return;
  }

  dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  dlrInit(&right, DL_DOCIDS, pRight, nRight);
  dlwInit(&writer, DL_DOCIDS, pOut);

  while( !dlrAtEnd(&left) ){
    while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
      dlrStep(&right);
    }
    if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
      dlwAdd(&writer, dlrDocid(&left));
    }
    dlrStep(&left);
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

static char *string_dup_n(const char *s, int n){
  char *str = sqlite3_malloc(n + 1);
  memcpy(str, s, n);
  str[n] = '\0';
  return str;
}

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it is not part of the standard C library and
 * may not be available everywhere.) */
static char *string_dup(const char *s){
  return string_dup_n(s, strlen(s));
}

/* Format a string, replacing each occurrence of the % character with
 * zDb.zName.  This may be more convenient than sqlite_mprintf()
 * when one string is used repeatedly in a format string.
 * The caller must free() the returned string. */
static char *string_format(const char *zFormat,
                           const char *zDb, const char *zName){
  const char *p;
  size_t len = 0;
  size_t nDb = strlen(zDb);
  size_t nName = strlen(zName);
  size_t nFullTableName = nDb+1+nName;
  char *result;
  char *r;

  /* first compute length needed */
  for(p = zFormat ; *p ; ++p){
    len += (*p=='%' ? nFullTableName : 1);
  }
  len += 1;  /* for null terminator */

  r = result = sqlite3_malloc(len);
  for(p = zFormat; *p; ++p){
    if( *p=='%' ){
      memcpy(r, zDb, nDb);
      r += nDb;
      *r++ = '.';
      memcpy(r, zName, nName);
      r += nName;
    } else {
      *r++ = *p;
    }
  }
  *r++ = '\0';
  assert( r == result + len );
  return result;
}

static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
                    const char *zFormat){
  char *zCommand = string_format(zFormat, zDb, zName);
  int rc;
  TRACE(("FTS2 sql: %s\n", zCommand));
  rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  sqlite3_free(zCommand);
  return rc;
}

static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
                       sqlite3_stmt **ppStmt, const char *zFormat){
  char *zCommand = string_format(zFormat, zDb, zName);
  int rc;
  TRACE(("FTS2 prepare: %s\n", zCommand));
  rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
  sqlite3_free(zCommand);
  return rc;
}

/* end utility functions */

/* Forward reference */
typedef struct fulltext_vtab fulltext_vtab;

/* A single term in a query is represented by an instances of
** the following structure.
*/
typedef struct QueryTerm {
  short int nPhrase; /* How many following terms are part of the same phrase */
  short int iPhrase; /* This is the i-th term of a phrase. */
  short int iColumn; /* Column of the index that must match this term */
  signed char isOr;  /* this term is preceded by "OR" */
  signed char isNot; /* this term is preceded by "-" */
  signed char isPrefix; /* this term is followed by "*" */
  char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
  int nTerm;         /* Number of bytes in pTerm[] */
} QueryTerm;


/* A query string is parsed into a Query structure.
 *
 * We could, in theory, allow query strings to be complicated
 * nested expressions with precedence determined by parentheses.
 * But none of the major search engines do this.  (Perhaps the
 * feeling is that an parenthesized expression is two complex of
 * an idea for the average user to grasp.)  Taking our lead from
 * the major search engines, we will allow queries to be a list
 * of terms (with an implied AND operator) or phrases in double-quotes,
 * with a single optional "-" before each non-phrase term to designate
 * negation and an optional OR connector.
 *
 * OR binds more tightly than the implied AND, which is what the
 * major search engines seem to do.  So, for example:
 * 
 *    [one two OR three]     ==>    one AND (two OR three)
 *    [one OR two three]     ==>    (one OR two) AND three
 *
 * A "-" before a term matches all entries that lack that term.
 * The "-" must occur immediately before the term with in intervening
 * space.  This is how the search engines do it.
 *
 * A NOT term cannot be the right-hand operand of an OR.  If this
 * occurs in the query string, the NOT is ignored:
 *
 *    [one OR -two]          ==>    one OR two
 *
 */
typedef struct Query {
  fulltext_vtab *pFts;  /* The full text index */
  int nTerms;           /* Number of terms in the query */
  QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
  int nextIsOr;         /* Set the isOr flag on the next inserted term */
  int nextColumn;       /* Next word parsed must be in this column */
  int dfltColumn;       /* The default column */
} Query;


/*
** An instance of the following structure keeps track of generated
** matching-word offset information and snippets.
*/
typedef struct Snippet {
  int nMatch;     /* Total number of matches */
  int nAlloc;     /* Space allocated for aMatch[] */
  struct snippetMatch { /* One entry for each matching term */
    char snStatus;       /* Status flag for use while constructing snippets */
    short int iCol;      /* The column that contains the match */
    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
    short int nByte;     /* Number of bytes in the term */
    int iStart;          /* The offset to the first character of the term */
  } *aMatch;      /* Points to space obtained from malloc */
  char *zOffset;  /* Text rendering of aMatch[] */
  int nOffset;    /* strlen(zOffset) */
  char *zSnippet; /* Snippet text */
  int nSnippet;   /* strlen(zSnippet) */
} Snippet;


typedef enum QueryType {
  QUERY_GENERIC,   /* table scan */
  QUERY_ROWID,     /* lookup by rowid */
  QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
} QueryType;

typedef enum fulltext_statement {
  CONTENT_INSERT_STMT,
  CONTENT_SELECT_STMT,
  CONTENT_UPDATE_STMT,
  CONTENT_DELETE_STMT,
  CONTENT_EXISTS_STMT,

  BLOCK_INSERT_STMT,
  BLOCK_SELECT_STMT,
  BLOCK_DELETE_STMT,
  BLOCK_DELETE_ALL_STMT,

  SEGDIR_MAX_INDEX_STMT,
  SEGDIR_SET_STMT,
  SEGDIR_SELECT_LEVEL_STMT,
  SEGDIR_SPAN_STMT,
  SEGDIR_DELETE_STMT,
  SEGDIR_SELECT_SEGMENT_STMT,
  SEGDIR_SELECT_ALL_STMT,
  SEGDIR_DELETE_ALL_STMT,
  SEGDIR_COUNT_STMT,

  MAX_STMT                     /* Always at end! */
} fulltext_statement;

/* These must exactly match the enum above. */
/* TODO(shess): Is there some risk that a statement will be used in two
** cursors at once, e.g.  if a query joins a virtual table to itself?
** If so perhaps we should move some of these to the cursor object.
*/
static const char *const fulltext_zStatement[MAX_STMT] = {
  /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
  /* CONTENT_SELECT */ "select * from %_content where rowid = ?",
  /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
  /* CONTENT_DELETE */ "delete from %_content where rowid = ?",
  /* CONTENT_EXISTS */ "select rowid from %_content limit 1",

  /* BLOCK_INSERT */ "insert into %_segments values (?)",
  /* BLOCK_SELECT */ "select block from %_segments where rowid = ?",
  /* BLOCK_DELETE */ "delete from %_segments where rowid between ? and ?",
  /* BLOCK_DELETE_ALL */ "delete from %_segments",

  /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
  /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
  /* SEGDIR_SELECT_LEVEL */
  "select start_block, leaves_end_block, root from %_segdir "
  " where level = ? order by idx",
  /* SEGDIR_SPAN */
  "select min(start_block), max(end_block) from %_segdir "
  " where level = ? and start_block <> 0",
  /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",

  /* NOTE(shess): The first three results of the following two
  ** statements must match.
  */
  /* SEGDIR_SELECT_SEGMENT */
  "select start_block, leaves_end_block, root from %_segdir "
  " where level = ? and idx = ?",
  /* SEGDIR_SELECT_ALL */
  "select start_block, leaves_end_block, root from %_segdir "
  " order by level desc, idx asc",
  /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
  /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
};

/*
** A connection to a fulltext index is an instance of the following
** structure.  The xCreate and xConnect methods create an instance
** of this structure and xDestroy and xDisconnect free that instance.
** All other methods receive a pointer to the structure as one of their
** arguments.
*/
struct fulltext_vtab {
  sqlite3_vtab base;               /* Base class used by SQLite core */
  sqlite3 *db;                     /* The database connection */
  const char *zDb;                 /* logical database name */
  const char *zName;               /* virtual table name */
  int nColumn;                     /* number of columns in virtual table */
  char **azColumn;                 /* column names.  malloced */
  char **azContentColumn;          /* column names in content table; malloced */
  sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */

  /* Precompiled statements which we keep as long as the table is
  ** open.
  */
  sqlite3_stmt *pFulltextStatements[MAX_STMT];

  /* Precompiled statements used for segment merges.  We run a
  ** separate select across the leaf level of each tree being merged.
  */
  sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
  /* The statement used to prepare pLeafSelectStmts. */
#define LEAF_SELECT \
  "select block from %_segments where rowid between ? and ? order by rowid"

  /* These buffer pending index updates during transactions.
  ** nPendingData estimates the memory size of the pending data.  It
  ** doesn't include the hash-bucket overhead, nor any malloc
  ** overhead.  When nPendingData exceeds kPendingThreshold, the
  ** buffer is flushed even before the transaction closes.
  ** pendingTerms stores the data, and is only valid when nPendingData
  ** is >=0 (nPendingData<0 means pendingTerms has not been
  ** initialized).  iPrevDocid is the last docid written, used to make
  ** certain we're inserting in sorted order.
  */
  int nPendingData;
#define kPendingThreshold (1*1024*1024)
  sqlite_int64 iPrevDocid;
  fts2Hash pendingTerms;
};

/*
** When the core wants to do a query, it create a cursor using a
** call to xOpen.  This structure is an instance of a cursor.  It
** is destroyed by xClose.
*/
typedef struct fulltext_cursor {
  sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
  QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
  sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
  int eof;                         /* True if at End Of Results */
  Query q;                         /* Parsed query string */
  Snippet snippet;                 /* Cached snippet for the current row */
  int iColumn;                     /* Column being searched */
  DataBuffer result;               /* Doclist results from fulltextQuery */
  DLReader reader;                 /* Result reader if result not empty */
} fulltext_cursor;

static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  return (fulltext_vtab *) c->base.pVtab;
}

static const sqlite3_module fts2Module;   /* forward declaration */

/* Return a dynamically generated statement of the form
 *   insert into %_content (rowid, ...) values (?, ...)
 */
static const char *contentInsertStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;

  initStringBuffer(&sb);
  append(&sb, "insert into %_content (rowid, ");
  appendList(&sb, v->nColumn, v->azContentColumn);
  append(&sb, ") values (?");
  for(i=0; i<v->nColumn; ++i)
    append(&sb, ", ?");
  append(&sb, ")");
  return stringBufferData(&sb);
}

/* Return a dynamically generated statement of the form
 *   update %_content set [col_0] = ?, [col_1] = ?, ...
 *                    where rowid = ?
 */
static const char *contentUpdateStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;

  initStringBuffer(&sb);
  append(&sb, "update %_content set ");
  for(i=0; i<v->nColumn; ++i) {
    if( i>0 ){
      append(&sb, ", ");
    }
    append(&sb, v->azContentColumn[i]);
    append(&sb, " = ?");
  }
  append(&sb, " where rowid = ?");
  return stringBufferData(&sb);
}

/* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
** If the indicated statement has never been prepared, it is prepared
** and cached, otherwise the cached version is reset.
*/
static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
                             sqlite3_stmt **ppStmt){
  assert( iStmt<MAX_STMT );
  if( v->pFulltextStatements[iStmt]==NULL ){
    const char *zStmt;
    int rc;
    switch( iStmt ){
      case CONTENT_INSERT_STMT:
        zStmt = contentInsertStatement(v); break;
      case CONTENT_UPDATE_STMT:
        zStmt = contentUpdateStatement(v); break;
      default:
        zStmt = fulltext_zStatement[iStmt];
    }
    rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
                         zStmt);
    if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
    if( rc!=SQLITE_OK ) return rc;
  } else {
    int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
    if( rc!=SQLITE_OK ) return rc;
  }

  *ppStmt = v->pFulltextStatements[iStmt];
  return SQLITE_OK;
}

/* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
** where we expect no results.
*/
static int sql_single_step(sqlite3_stmt *s){
  int rc = sqlite3_step(s);
  return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
}

/* Like sql_get_statement(), but for special replicated LEAF_SELECT
** statements.  idx -1 is a special case for an uncached version of
** the statement (used in the optimize implementation).
*/
/* TODO(shess) Write version for generic statements and then share
** that between the cached-statement functions.
*/
static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
                                  sqlite3_stmt **ppStmt){
  assert( idx>=-1 && idx<MERGE_COUNT );
  if( idx==-1 ){
    return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
  }else if( v->pLeafSelectStmts[idx]==NULL ){
    int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
                         LEAF_SELECT);
    if( rc!=SQLITE_OK ) return rc;
  }else{
    int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
    if( rc!=SQLITE_OK ) return rc;
  }

  *ppStmt = v->pLeafSelectStmts[idx];
  return SQLITE_OK;
}

/* insert into %_content (rowid, ...) values ([rowid], [pValues]) */
static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
                          sqlite3_value **pValues){
  sqlite3_stmt *s;
  int i;
  int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_value(s, 1, rowid);
  if( rc!=SQLITE_OK ) return rc;

  for(i=0; i<v->nColumn; ++i){
    rc = sqlite3_bind_value(s, 2+i, pValues[i]);
    if( rc!=SQLITE_OK ) return rc;
  }

  return sql_single_step(s);
}

/* update %_content set col0 = pValues[0], col1 = pValues[1], ...
 *                  where rowid = [iRowid] */
static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
                          sqlite_int64 iRowid){
  sqlite3_stmt *s;
  int i;
  int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  for(i=0; i<v->nColumn; ++i){
    rc = sqlite3_bind_value(s, 1+i, pValues[i]);
    if( rc!=SQLITE_OK ) return rc;
  }

  rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

static void freeStringArray(int nString, const char **pString){
  int i;

  for (i=0 ; i < nString ; ++i) {
    if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
  }
  sqlite3_free((void *) pString);
}

/* select * from %_content where rowid = [iRow]
 * The caller must delete the returned array and all strings in it.
 * null fields will be NULL in the returned array.
 *
 * TODO: Perhaps we should return pointer/length strings here for consistency
 * with other code which uses pointer/length. */
static int content_select(fulltext_vtab *v, sqlite_int64 iRow,
                          const char ***pValues){
  sqlite3_stmt *s;
  const char **values;
  int i;
  int rc;

  *pValues = NULL;

  rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc!=SQLITE_ROW ) return rc;

  values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
  for(i=0; i<v->nColumn; ++i){
    if( sqlite3_column_type(s, i)==SQLITE_NULL ){
      values[i] = NULL;
    }else{
      values[i] = string_dup((char*)sqlite3_column_text(s, i));
    }
  }

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ){
    *pValues = values;
    return SQLITE_OK;
  }

  freeStringArray(v->nColumn, values);
  return rc;
}

/* delete from %_content where rowid = [iRow ] */
static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iRow);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
** no rows exist, and any error in case of failure.
*/
static int content_exists(fulltext_vtab *v){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc!=SQLITE_ROW ) return rc;

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_ROW;
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  return rc;
}

/* insert into %_segments values ([pData])
**   returns assigned rowid in *piBlockid
*/
static int block_insert(fulltext_vtab *v, const char *pData, int nData,
                        sqlite_int64 *piBlockid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;

  *piBlockid = sqlite3_last_insert_rowid(v->db);
  return SQLITE_OK;
}

/* delete from %_segments
**   where rowid between [iStartBlockid] and [iEndBlockid]
**
** Deletes the range of blocks, inclusive, used to delete the blocks
** which form a segment.
*/
static int block_delete(fulltext_vtab *v,
                        sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
** at iLevel.  Returns SQLITE_DONE if there are no segments at
** iLevel.  Otherwise returns an error.
*/
static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  /* Should always get at least one row due to how max() works. */
  if( rc==SQLITE_DONE ) return SQLITE_DONE;
  if( rc!=SQLITE_ROW ) return rc;

  /* NULL means that there were no inputs to max(). */
  if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
    rc = sqlite3_step(s);
    if( rc==SQLITE_ROW ) return SQLITE_ERROR;
    return rc;
  }

  *pidx = sqlite3_column_int(s, 0);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;
  return SQLITE_ROW;
}

/* insert into %_segdir values (
**   [iLevel], [idx],
**   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
**   [pRootData]
** )
*/
static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
                      sqlite_int64 iStartBlockid,
                      sqlite_int64 iLeavesEndBlockid,
                      sqlite_int64 iEndBlockid,
                      const char *pRootData, int nRootData){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 2, idx);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 3, iStartBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 5, iEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Queries %_segdir for the block span of the segments in level
** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
** SQLITE_ROW if there are blocks, else an error.
*/
static int segdir_span(fulltext_vtab *v, int iLevel,
                       sqlite_int64 *piStartBlockid,
                       sqlite_int64 *piEndBlockid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
  if( rc!=SQLITE_ROW ) return rc;

  /* This happens if all segments at this level are entirely inline. */
  if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
    /* We expect only one row.  We must execute another sqlite3_step()
     * to complete the iteration; otherwise the table will remain locked. */
    int rc2 = sqlite3_step(s);
    if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
    return rc2;
  }

  *piStartBlockid = sqlite3_column_int64(s, 0);
  *piEndBlockid = sqlite3_column_int64(s, 1);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;
  return SQLITE_ROW;
}

/* Delete the segment blocks and segment directory records for all
** segments at iLevel.
*/
static int segdir_delete(fulltext_vtab *v, int iLevel){
  sqlite3_stmt *s;
  sqlite_int64 iStartBlockid, iEndBlockid;
  int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
  if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;

  if( rc==SQLITE_ROW ){
    rc = block_delete(v, iStartBlockid, iEndBlockid);
    if( rc!=SQLITE_OK ) return rc;
  }

  /* Delete the segment directory itself. */
  rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Delete entire fts index, SQLITE_OK on success, relevant error on
** failure.
*/
static int segdir_delete_all(fulltext_vtab *v){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_single_step(s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Returns SQLITE_OK with *pnSegments set to the number of entries in
** %_segdir and *piMaxLevel set to the highest level which has a
** segment.  Otherwise returns the SQLite error which caused failure.
*/
static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  /* TODO(shess): This case should not be possible?  Should stronger
  ** measures be taken if it happens?
  */
  if( rc==SQLITE_DONE ){
    *pnSegments = 0;
    *piMaxLevel = 0;
    return SQLITE_OK;
  }
  if( rc!=SQLITE_ROW ) return rc;

  *pnSegments = sqlite3_column_int(s, 0);
  *piMaxLevel = sqlite3_column_int(s, 1);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_OK;
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  return rc;
}

/* TODO(shess) clearPendingTerms() is far down the file because
** writeZeroSegment() is far down the file because LeafWriter is far
** down the file.  Consider refactoring the code to move the non-vtab
** code above the vtab code so that we don't need this forward
** reference.
*/
static int clearPendingTerms(fulltext_vtab *v);

/*
** Free the memory used to contain a fulltext_vtab structure.
*/
static void fulltext_vtab_destroy(fulltext_vtab *v){
  int iStmt, i;

  TRACE(("FTS2 Destroy %p\n", v));
  for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
    if( v->pFulltextStatements[iStmt]!=NULL ){
      sqlite3_finalize(v->pFulltextStatements[iStmt]);
      v->pFulltextStatements[iStmt] = NULL;
    }
  }

  for( i=0; i<MERGE_COUNT; i++ ){
    if( v->pLeafSelectStmts[i]!=NULL ){
      sqlite3_finalize(v->pLeafSelectStmts[i]);
      v->pLeafSelectStmts[i] = NULL;
    }
  }

  if( v->pTokenizer!=NULL ){
    v->pTokenizer->pModule->xDestroy(v->pTokenizer);
    v->pTokenizer = NULL;
  }

  clearPendingTerms(v);

  sqlite3_free(v->azColumn);
  for(i = 0; i < v->nColumn; ++i) {
    sqlite3_free(v->azContentColumn[i]);
  }
  sqlite3_free(v->azContentColumn);
  sqlite3_free(v);
}

/*
** Token types for parsing the arguments to xConnect or xCreate.
*/
#define TOKEN_EOF         0    /* End of file */
#define TOKEN_SPACE       1    /* Any kind of whitespace */
#define TOKEN_ID          2    /* An identifier */
#define TOKEN_STRING      3    /* A string literal */
#define TOKEN_PUNCT       4    /* A single punctuation character */

/*
** If X is a character that can be used in an identifier then
** IdChar(X) will be true.  Otherwise it is false.
**
** For ASCII, any character with the high-order bit set is
** allowed in an identifier.  For 7-bit characters, 
** sqlite3IsIdChar[X] must be 1.
**
** Ticket #1066.  the SQL standard does not allow '$' in the
** middle of identfiers.  But many SQL implementations do. 
** SQLite will allow '$' in identifiers for compatibility.
** But the feature is undocumented.
*/
static const char isIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20]))


/*
** Return the length of the token that begins at z[0]. 
** Store the token type in *tokenType before returning.
*/
static int getToken(const char *z, int *tokenType){
  int i, c;
  switch( *z ){
    case 0: {
      *tokenType = TOKEN_EOF;
      return 0;
    }
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; safe_isspace(z[i]); i++){}
      *tokenType = TOKEN_SPACE;
      return i;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      for(i=1; (c=z[i])!=0; i++){
        if( c==delim ){
          if( z[i+1]==delim ){
            i++;
          }else{
            break;
          }
        }
      }
      *tokenType = TOKEN_STRING;
      return i + (c!=0);
    }
    case '[': {
      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
      *tokenType = TOKEN_ID;
      return i;
    }
    default: {
      if( !IdChar(*z) ){
        break;
      }
      for(i=1; IdChar(z[i]); i++){}
      *tokenType = TOKEN_ID;
      return i;
    }
  }
  *tokenType = TOKEN_PUNCT;
  return 1;
}

/*
** A token extracted from a string is an instance of the following
** structure.
*/
typedef struct Token {
  const char *z;       /* Pointer to token text.  Not '\000' terminated */
  short int n;         /* Length of the token text in bytes. */
} Token;

/*
** Given a input string (which is really one of the argv[] parameters
** passed into xConnect or xCreate) split the string up into tokens.
** Return an array of pointers to '\000' terminated strings, one string
** for each non-whitespace token.
**
** The returned array is terminated by a single NULL pointer.
**
** Space to hold the returned array is obtained from a single
** malloc and should be freed by passing the return value to free().
** The individual strings within the token list are all a part of
** the single memory allocation and will all be freed at once.
*/
static char **tokenizeString(const char *z, int *pnToken){
  int nToken = 0;
  Token *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
  int n = 1;
  int e, i;
  int totalSize = 0;
  char **azToken;
  char *zCopy;
  while( n>0 ){
    n = getToken(z, &e);
    if( e!=TOKEN_SPACE ){
      aToken[nToken].z = z;
      aToken[nToken].n = n;
      nToken++;
      totalSize += n+1;
    }
    z += n;
  }
  azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
  zCopy = (char*)&azToken[nToken];
  nToken--;
  for(i=0; i<nToken; i++){
    azToken[i] = zCopy;
    n = aToken[i].n;
    memcpy(zCopy, aToken[i].z, n);
    zCopy[n] = 0;
    zCopy += n+1;
  }
  azToken[nToken] = 0;
  sqlite3_free(aToken);
  *pnToken = nToken;
  return azToken;
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** Examples:
**
**     "abc"   becomes   abc
**     'xyz'   becomes   xyz
**     [pqr]   becomes   pqr
**     `mno`   becomes   mno
*/
static void dequoteString(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return;
  }
  for(i=1, j=0; z[i]; i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = quote;
        i++;
      }else{
        z[j++] = 0;
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
}

/*
** The input azIn is a NULL-terminated list of tokens.  Remove the first
** token and all punctuation tokens.  Remove the quotes from
** around string literal tokens.
**
** Example:
**
**     input:      tokenize chinese ( 'simplifed' , 'mixed' )
**     output:     chinese simplifed mixed
**
** Another example:
**
**     input:      delimiters ( '[' , ']' , '...' )
**     output:     [ ] ...
*/
static void tokenListToIdList(char **azIn){
  int i, j;
  if( azIn ){
    for(i=0, j=-1; azIn[i]; i++){
      if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
        dequoteString(azIn[i]);
        if( j>=0 ){
          azIn[j] = azIn[i];
        }
        j++;
      }
    }
    azIn[j] = 0;
  }
}


/*
** Find the first alphanumeric token in the string zIn.  Null-terminate
** this token.  Remove any quotation marks.  And return a pointer to
** the result.
*/
static char *firstToken(char *zIn, char **pzTail){
  int n, ttype;
  while(1){
    n = getToken(zIn, &ttype);
    if( ttype==TOKEN_SPACE ){
      zIn += n;
    }else if( ttype==TOKEN_EOF ){
      *pzTail = zIn;
      return 0;
    }else{
      zIn[n] = 0;
      *pzTail = &zIn[1];
      dequoteString(zIn);
      return zIn;
    }
  }
  /*NOTREACHED*/
}

/* Return true if...
**
**   *  s begins with the string t, ignoring case
**   *  s is longer than t
**   *  The first character of s beyond t is not a alphanumeric
** 
** Ignore leading space in *s.
**
** To put it another way, return true if the first token of
** s[] is t[].
*/
static int startsWith(const char *s, const char *t){
  while( safe_isspace(*s) ){ s++; }
  while( *t ){
    if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
  }
  return *s!='_' && !safe_isalnum(*s);
}

/*
** An instance of this structure defines the "spec" of a
** full text index.  This structure is populated by parseSpec
** and use by fulltextConnect and fulltextCreate.
*/
typedef struct TableSpec {
  const char *zDb;         /* Logical database name */
  const char *zName;       /* Name of the full-text index */
  int nColumn;             /* Number of columns to be indexed */
  char **azColumn;         /* Original names of columns to be indexed */
  char **azContentColumn;  /* Column names for %_content */
  char **azTokenizer;      /* Name of tokenizer and its arguments */
} TableSpec;

/*
** Reclaim all of the memory used by a TableSpec
*/
static void clearTableSpec(TableSpec *p) {
  sqlite3_free(p->azColumn);
  sqlite3_free(p->azContentColumn);
  sqlite3_free(p->azTokenizer);
}

/* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
 *
 * CREATE VIRTUAL TABLE email
 *        USING fts2(subject, body, tokenize mytokenizer(myarg))
 *
 * We return parsed information in a TableSpec structure.
 * 
 */
static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
                     char**pzErr){
  int i, n;
  char *z, *zDummy;
  char **azArg;
  const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */

  assert( argc>=3 );
  /* Current interface:
  ** argv[0] - module name
  ** argv[1] - database name
  ** argv[2] - table name
  ** argv[3..] - columns, optionally followed by tokenizer specification
  **             and snippet delimiters specification.
  */

  /* Make a copy of the complete argv[][] array in a single allocation.
  ** The argv[][] array is read-only and transient.  We can write to the
  ** copy in order to modify things and the copy is persistent.
  */
  CLEAR(pSpec);
  for(i=n=0; i<argc; i++){
    n += strlen(argv[i]) + 1;
  }
  azArg = sqlite3_malloc( sizeof(char*)*argc + n );
  if( azArg==0 ){
    return SQLITE_NOMEM;
  }
  z = (char*)&azArg[argc];
  for(i=0; i<argc; i++){
    azArg[i] = z;
    strcpy(z, argv[i]);
    z += strlen(z)+1;
  }

  /* Identify the column names and the tokenizer and delimiter arguments
  ** in the argv[][] array.
  */
  pSpec->zDb = azArg[1];
  pSpec->zName = azArg[2];
  pSpec->nColumn = 0;
  pSpec->azColumn = azArg;
  zTokenizer = "tokenize simple";
  for(i=3; i<argc; ++i){
    if( startsWith(azArg[i],"tokenize") ){
      zTokenizer = azArg[i];
    }else{
      z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
      pSpec->nColumn++;
    }
  }
  if( pSpec->nColumn==0 ){
    azArg[0] = "content";
    pSpec->nColumn = 1;
  }

  /*
  ** Construct the list of content column names.
  **
  ** Each content column name will be of the form cNNAAAA
  ** where NN is the column number and AAAA is the sanitized
  ** column name.  "sanitized" means that special characters are
  ** converted to "_".  The cNN prefix guarantees that all column
  ** names are unique.
  **
  ** The AAAA suffix is not strictly necessary.  It is included
  ** for the convenience of people who might examine the generated
  ** %_content table and wonder what the columns are used for.
  */
  pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
  if( pSpec->azContentColumn==0 ){
    clearTableSpec(pSpec);
    return SQLITE_NOMEM;
  }
  for(i=0; i<pSpec->nColumn; i++){
    char *p;
    pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
    for (p = pSpec->azContentColumn[i]; *p ; ++p) {
      if( !safe_isalnum(*p) ) *p = '_';
    }
  }

  /*
  ** Parse the tokenizer specification string.
  */
  pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
  tokenListToIdList(pSpec->azTokenizer);

  return SQLITE_OK;
}

/*
** Generate a CREATE TABLE statement that describes the schema of
** the virtual table.  Return a pointer to this schema string.
**
** Space is obtained from sqlite3_mprintf() and should be freed
** using sqlite3_free().
*/
static char *fulltextSchema(
  int nColumn,                  /* Number of columns */
  const char *const* azColumn,  /* List of columns */
  const char *zTableName        /* Name of the table */
){
  int i;
  char *zSchema, *zNext;
  const char *zSep = "(";
  zSchema = sqlite3_mprintf("CREATE TABLE x");
  for(i=0; i<nColumn; i++){
    zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
    sqlite3_free(zSchema);
    zSchema = zNext;
    zSep = ",";
  }
  zNext = sqlite3_mprintf("%s,%Q)", zSchema, zTableName);
  sqlite3_free(zSchema);
  return zNext;
}

/*
** Build a new sqlite3_vtab structure that will describe the
** fulltext index defined by spec.
*/
static int constructVtab(
  sqlite3 *db,              /* The SQLite database connection */
  fts2Hash *pHash,          /* Hash table containing tokenizers */
  TableSpec *spec,          /* Parsed spec information from parseSpec() */
  sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
  char **pzErr              /* Write any error message here */
){
  int rc;
  int n;
  fulltext_vtab *v = 0;
  const sqlite3_tokenizer_module *m = NULL;
  char *schema;

  char const *zTok;         /* Name of tokenizer to use for this fts table */
  int nTok;                 /* Length of zTok, including nul terminator */

  v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
  if( v==0 ) return SQLITE_NOMEM;
  CLEAR(v);
  /* sqlite will initialize v->base */
  v->db = db;
  v->zDb = spec->zDb;       /* Freed when azColumn is freed */
  v->zName = spec->zName;   /* Freed when azColumn is freed */
  v->nColumn = spec->nColumn;
  v->azContentColumn = spec->azContentColumn;
  spec->azContentColumn = 0;
  v->azColumn = spec->azColumn;
  spec->azColumn = 0;

  if( spec->azTokenizer==0 ){
    return SQLITE_NOMEM;
  }

  zTok = spec->azTokenizer[0]; 
  if( !zTok ){
    zTok = "simple";
  }
  nTok = strlen(zTok)+1;

  m = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zTok, nTok);
  if( !m ){
    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
    rc = SQLITE_ERROR;
    goto err;
  }

  for(n=0; spec->azTokenizer[n]; n++){}
  if( n ){
    rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
                    &v->pTokenizer);
  }else{
    rc = m->xCreate(0, 0, &v->pTokenizer);
  }
  if( rc!=SQLITE_OK ) goto err;
  v->pTokenizer->pModule = m;

  /* TODO: verify the existence of backing tables foo_content, foo_term */

  schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
                          spec->zName);
  rc = sqlite3_declare_vtab(db, schema);
  sqlite3_free(schema);
  if( rc!=SQLITE_OK ) goto err;

  memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));

  /* Indicate that the buffer is not live. */
  v->nPendingData = -1;

  *ppVTab = &v->base;
  TRACE(("FTS2 Connect %p\n", v));

  return rc;

err:
  fulltext_vtab_destroy(v);
  return rc;
}

static int fulltextConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVTab,
  char **pzErr
){
  TableSpec spec;
  int rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);
  clearTableSpec(&spec);
  return rc;
}

/* The %_content table holds the text of each document, with
** the rowid used as the docid.
*/
/* TODO(shess) This comment needs elaboration to match the updated
** code.  Work it into the top-of-file comment at that time.
*/
static int fulltextCreate(sqlite3 *db, void *pAux,
                          int argc, const char * const *argv,
                          sqlite3_vtab **ppVTab, char **pzErr){
  int rc;
  TableSpec spec;
  StringBuffer schema;
  TRACE(("FTS2 Create\n"));

  rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  initStringBuffer(&schema);
  append(&schema, "CREATE TABLE %_content(");
  appendList(&schema, spec.nColumn, spec.azContentColumn);
  append(&schema, ")");
  rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
  stringBufferDestroy(&schema);
  if( rc!=SQLITE_OK ) goto out;

  rc = sql_exec(db, spec.zDb, spec.zName,
                "create table %_segments(block blob);");
  if( rc!=SQLITE_OK ) goto out;

  rc = sql_exec(db, spec.zDb, spec.zName,
                "create table %_segdir("
                "  level integer,"
                "  idx integer,"
                "  start_block integer,"
                "  leaves_end_block integer,"
                "  end_block integer,"
                "  root blob,"
                "  primary key(level, idx)"
                ");");
  if( rc!=SQLITE_OK ) goto out;

  rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);

out:
  clearTableSpec(&spec);
  return rc;
}

/* Decide how to handle an SQL query. */
static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  int i;
  TRACE(("FTS2 BestIndex\n"));

  for(i=0; i<pInfo->nConstraint; ++i){
    const struct sqlite3_index_constraint *pConstraint;
    pConstraint = &pInfo->aConstraint[i];
    if( pConstraint->usable ) {
      if( pConstraint->iColumn==-1 &&
          pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
        pInfo->idxNum = QUERY_ROWID;      /* lookup by rowid */
        TRACE(("FTS2 QUERY_ROWID\n"));
      } else if( pConstraint->iColumn>=0 &&
                 pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
        /* full-text search */
        pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
        TRACE(("FTS2 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
      } else continue;

      pInfo->aConstraintUsage[i].argvIndex = 1;
      pInfo->aConstraintUsage[i].omit = 1;

      /* An arbitrary value for now.
       * TODO: Perhaps rowid matches should be considered cheaper than
       * full-text searches. */
      pInfo->estimatedCost = 1.0;   

      return SQLITE_OK;
    }
  }
  pInfo->idxNum = QUERY_GENERIC;
  return SQLITE_OK;
}

static int fulltextDisconnect(sqlite3_vtab *pVTab){
  TRACE(("FTS2 Disconnect %p\n", pVTab));
  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextDestroy(sqlite3_vtab *pVTab){
  fulltext_vtab *v = (fulltext_vtab *)pVTab;
  int rc;

  TRACE(("FTS2 Destroy %p\n", pVTab));
  rc = sql_exec(v->db, v->zDb, v->zName,
                "drop table if exists %_content;"
                "drop table if exists %_segments;"
                "drop table if exists %_segdir;"
                );
  if( rc!=SQLITE_OK ) return rc;

  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  fulltext_cursor *c;

  c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
  if( c ){
    memset(c, 0, sizeof(fulltext_cursor));
    /* sqlite will initialize c->base */
    *ppCursor = &c->base;
    TRACE(("FTS2 Open %p: %p\n", pVTab, c));
    return SQLITE_OK;
  }else{
    return SQLITE_NOMEM;
  }
}


/* Free all of the dynamically allocated memory held by *q
*/
static void queryClear(Query *q){
  int i;
  for(i = 0; i < q->nTerms; ++i){
    sqlite3_free(q->pTerms[i].pTerm);
  }
  sqlite3_free(q->pTerms);
  CLEAR(q);
}

/* Free all of the dynamically allocated memory held by the
** Snippet
*/
static void snippetClear(Snippet *p){
  sqlite3_free(p->aMatch);
  sqlite3_free(p->zOffset);
  sqlite3_free(p->zSnippet);
  CLEAR(p);
}
/*
** Append a single entry to the p->aMatch[] log.
*/
static void snippetAppendMatch(
  Snippet *p,               /* Append the entry to this snippet */
  int iCol, int iTerm,      /* The column and query term */
  int iStart, int nByte     /* Offset and size of the match */
){
  int i;
  struct snippetMatch *pMatch;
  if( p->nMatch+1>=p->nAlloc ){
    p->nAlloc = p->nAlloc*2 + 10;
    p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
    if( p->aMatch==0 ){
      p->nMatch = 0;
      p->nAlloc = 0;
      return;
    }
  }
  i = p->nMatch++;
  pMatch = &p->aMatch[i];
  pMatch->iCol = iCol;
  pMatch->iTerm = iTerm;
  pMatch->iStart = iStart;
  pMatch->nByte = nByte;
}

/*
** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
*/
#define FTS2_ROTOR_SZ   (32)
#define FTS2_ROTOR_MASK (FTS2_ROTOR_SZ-1)

/*
** Add entries to pSnippet->aMatch[] for every match that occurs against
** document zDoc[0..nDoc-1] which is stored in column iColumn.
*/
static void snippetOffsetsOfColumn(
  Query *pQuery,
  Snippet *pSnippet,
  int iColumn,
  const char *zDoc,
  int nDoc
){
  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
  fulltext_vtab *pVtab;                /* The full text index */
  int nColumn;                         /* Number of columns in the index */
  const QueryTerm *aTerm;              /* Query string terms */
  int nTerm;                           /* Number of query string terms */  
  int i, j;                            /* Loop counters */
  int rc;                              /* Return code */
  unsigned int match, prevMatch;       /* Phrase search bitmasks */
  const char *zToken;                  /* Next token from the tokenizer */
  int nToken;                          /* Size of zToken */
  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */

  /* The following variables keep a circular buffer of the last
  ** few tokens */
  unsigned int iRotor = 0;             /* Index of current token */
  int iRotorBegin[FTS2_ROTOR_SZ];      /* Beginning offset of token */
  int iRotorLen[FTS2_ROTOR_SZ];        /* Length of token */

  pVtab = pQuery->pFts;
  nColumn = pVtab->nColumn;
  pTokenizer = pVtab->pTokenizer;
  pTModule = pTokenizer->pModule;
  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
  if( rc ) return;
  pTCursor->pTokenizer = pTokenizer;
  aTerm = pQuery->pTerms;
  nTerm = pQuery->nTerms;
  if( nTerm>=FTS2_ROTOR_SZ ){
    nTerm = FTS2_ROTOR_SZ - 1;
  }
  prevMatch = 0;
  while(1){
    rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
    if( rc ) break;
    iRotorBegin[iRotor&FTS2_ROTOR_MASK] = iBegin;
    iRotorLen[iRotor&FTS2_ROTOR_MASK] = iEnd-iBegin;
    match = 0;
    for(i=0; i<nTerm; i++){
      int iCol;
      iCol = aTerm[i].iColumn;
      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
      if( aTerm[i].nTerm>nToken ) continue;
      if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
      assert( aTerm[i].nTerm<=nToken );
      if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
      if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
      match |= 1<<i;
      if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
        for(j=aTerm[i].iPhrase-1; j>=0; j--){
          int k = (iRotor-j) & FTS2_ROTOR_MASK;
          snippetAppendMatch(pSnippet, iColumn, i-j,
                iRotorBegin[k], iRotorLen[k]);
        }
      }
    }
    prevMatch = match<<1;
    iRotor++;
  }
  pTModule->xClose(pTCursor);  
}


/*
** Compute all offsets for the current row of the query.  
** If the offsets have already been computed, this routine is a no-op.
*/
static void snippetAllOffsets(fulltext_cursor *p){
  int nColumn;
  int iColumn, i;
  int iFirst, iLast;
  fulltext_vtab *pFts;

  if( p->snippet.nMatch ) return;
  if( p->q.nTerms==0 ) return;
  pFts = p->q.pFts;
  nColumn = pFts->nColumn;
  iColumn = (p->iCursorType - QUERY_FULLTEXT);
  if( iColumn<0 || iColumn>=nColumn ){
    iFirst = 0;
    iLast = nColumn-1;
  }else{
    iFirst = iColumn;
    iLast = iColumn;
  }
  for(i=iFirst; i<=iLast; i++){
    const char *zDoc;
    int nDoc;
    zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
    nDoc = sqlite3_column_bytes(p->pStmt, i+1);
    snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
  }
}

/*
** Convert the information in the aMatch[] array of the snippet
** into the string zOffset[0..nOffset-1].
*/
static void snippetOffsetText(Snippet *p){
  int i;
  int cnt = 0;
  StringBuffer sb;
  char zBuf[200];
  if( p->zOffset ) return;
  initStringBuffer(&sb);
  for(i=0; i<p->nMatch; i++){
    struct snippetMatch *pMatch = &p->aMatch[i];
    zBuf[0] = ' ';
    sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
        pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
    append(&sb, zBuf);
    cnt++;
  }
  p->zOffset = stringBufferData(&sb);
  p->nOffset = stringBufferLength(&sb);
}

/*
** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
** of matching words some of which might be in zDoc.  zDoc is column
** number iCol.
**
** iBreak is suggested spot in zDoc where we could begin or end an
** excerpt.  Return a value similar to iBreak but possibly adjusted
** to be a little left or right so that the break point is better.
*/
static int wordBoundary(
  int iBreak,                   /* The suggested break point */
  const char *zDoc,             /* Document text */
  int nDoc,                     /* Number of bytes in zDoc[] */
  struct snippetMatch *aMatch,  /* Matching words */
  int nMatch,                   /* Number of entries in aMatch[] */
  int iCol                      /* The column number for zDoc[] */
){
  int i;
  if( iBreak<=10 ){
    return 0;
  }
  if( iBreak>=nDoc-10 ){
    return nDoc;
  }
  for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
  if( i<nMatch ){
    if( aMatch[i].iStart<iBreak+10 ){
      return aMatch[i].iStart;
    }
    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
      return aMatch[i-1].iStart;
    }
  }
  for(i=1; i<=10; i++){
    if( safe_isspace(zDoc[iBreak-i]) ){
      return iBreak - i + 1;
    }
    if( safe_isspace(zDoc[iBreak+i]) ){
      return iBreak + i + 1;
    }
  }
  return iBreak;
}



/*
** Allowed values for Snippet.aMatch[].snStatus
*/
#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */

/*
** Generate the text of a snippet.
*/
static void snippetText(
  fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
  const char *zStartMark,     /* Markup to appear before each match */
  const char *zEndMark,       /* Markup to appear after each match */
  const char *zEllipsis       /* Ellipsis mark */
){
  int i, j;
  struct snippetMatch *aMatch;
  int nMatch;
  int nDesired;
  StringBuffer sb;
  int tailCol;
  int tailOffset;
  int iCol;
  int nDoc;
  const char *zDoc;
  int iStart, iEnd;
  int tailEllipsis = 0;
  int iMatch;
  

  sqlite3_free(pCursor->snippet.zSnippet);
  pCursor->snippet.zSnippet = 0;
  aMatch = pCursor->snippet.aMatch;
  nMatch = pCursor->snippet.nMatch;
  initStringBuffer(&sb);

  for(i=0; i<nMatch; i++){
    aMatch[i].snStatus = SNIPPET_IGNORE;
  }
  nDesired = 0;
  for(i=0; i<pCursor->q.nTerms; i++){
    for(j=0; j<nMatch; j++){
      if( aMatch[j].iTerm==i ){
        aMatch[j].snStatus = SNIPPET_DESIRED;
        nDesired++;
        break;
      }
    }
  }

  iMatch = 0;
  tailCol = -1;
  tailOffset = 0;
  for(i=0; i<nMatch && nDesired>0; i++){
    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
    nDesired--;
    iCol = aMatch[i].iCol;
    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
    iStart = aMatch[i].iStart - 40;
    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
    if( iStart<=10 ){
      iStart = 0;
    }
    if( iCol==tailCol && iStart<=tailOffset+20 ){
      iStart = tailOffset;
    }
    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
      trimWhiteSpace(&sb);
      appendWhiteSpace(&sb);
      append(&sb, zEllipsis);
      appendWhiteSpace(&sb);
    }
    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
    if( iEnd>=nDoc-10 ){
      iEnd = nDoc;
      tailEllipsis = 0;
    }else{
      tailEllipsis = 1;
    }
    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
    while( iStart<iEnd ){
      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
             && aMatch[iMatch].iCol<=iCol ){
        iMatch++;
      }
      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
             && aMatch[iMatch].iCol==iCol ){
        nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
        iStart = aMatch[iMatch].iStart;
        append(&sb, zStartMark);
        nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
        append(&sb, zEndMark);
        iStart += aMatch[iMatch].nByte;
        for(j=iMatch+1; j<nMatch; j++){
          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
              && aMatch[j].snStatus==SNIPPET_DESIRED ){
            nDesired--;
            aMatch[j].snStatus = SNIPPET_IGNORE;
          }
        }
      }else{
        nappend(&sb, &zDoc[iStart], iEnd - iStart);
        iStart = iEnd;
      }
    }
    tailCol = iCol;
    tailOffset = iEnd;
  }
  trimWhiteSpace(&sb);
  if( tailEllipsis ){
    appendWhiteSpace(&sb);
    append(&sb, zEllipsis);
  }
  pCursor->snippet.zSnippet = stringBufferData(&sb);
  pCursor->snippet.nSnippet = stringBufferLength(&sb);
}


/*
** Close the cursor.  For additional information see the documentation
** on the xClose method of the virtual table interface.
*/
static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  TRACE(("FTS2 Close %p\n", c));
  sqlite3_finalize(c->pStmt);
  queryClear(&c->q);
  snippetClear(&c->snippet);
  if( c->result.nData!=0 ) dlrDestroy(&c->reader);
  dataBufferDestroy(&c->result);
  sqlite3_free(c);
  return SQLITE_OK;
}

static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  int rc;

  TRACE(("FTS2 Next %p\n", pCursor));
  snippetClear(&c->snippet);
  if( c->iCursorType < QUERY_FULLTEXT ){
    /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
    rc = sqlite3_step(c->pStmt);
    switch( rc ){
      case SQLITE_ROW:
        c->eof = 0;
        return SQLITE_OK;
      case SQLITE_DONE:
        c->eof = 1;
        return SQLITE_OK;
      default:
        c->eof = 1;
        return rc;
    }
  } else {  /* full-text query */
    rc = sqlite3_reset(c->pStmt);
    if( rc!=SQLITE_OK ) return rc;

    if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
      c->eof = 1;
      return SQLITE_OK;
    }
    rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
    dlrStep(&c->reader);
    if( rc!=SQLITE_OK ) return rc;
    /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
    rc = sqlite3_step(c->pStmt);
    if( rc==SQLITE_ROW ){   /* the case we expect */
      c->eof = 0;
      return SQLITE_OK;
    }
    /* an error occurred; abort */
    return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  }
}


/* TODO(shess) If we pushed LeafReader to the top of the file, or to
** another file, term_select() could be pushed above
** docListOfTerm().
*/
static int termSelect(fulltext_vtab *v, int iColumn,
                      const char *pTerm, int nTerm, int isPrefix,
                      DocListType iType, DataBuffer *out);

/* Return a DocList corresponding to the query term *pTerm.  If *pTerm
** is the first term of a phrase query, go ahead and evaluate the phrase
** query and return the doclist for the entire phrase query.
**
** The resulting DL_DOCIDS doclist is stored in pResult, which is
** overwritten.
*/
static int docListOfTerm(
  fulltext_vtab *v,   /* The full text index */
  int iColumn,        /* column to restrict to.  No restriction if >=nColumn */
  QueryTerm *pQTerm,  /* Term we are looking for, or 1st term of a phrase */
  DataBuffer *pResult /* Write the result here */
){
  DataBuffer left, right, new;
  int i, rc;

  /* No phrase search if no position info. */
  assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );

  /* This code should never be called with buffered updates. */
  assert( v->nPendingData<0 );

  dataBufferInit(&left, 0);
  rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
                  0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS, &left);
  if( rc ) return rc;
  for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
    dataBufferInit(&right, 0);
    rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
                    pQTerm[i].isPrefix, DL_POSITIONS, &right);
    if( rc ){
      dataBufferDestroy(&left);
      return rc;
    }
    dataBufferInit(&new, 0);
    docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
                       i<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS, &new);
    dataBufferDestroy(&left);
    dataBufferDestroy(&right);
    left = new;
  }
  *pResult = left;
  return SQLITE_OK;
}

/* Add a new term pTerm[0..nTerm-1] to the query *q.
*/
static void queryAdd(Query *q, const char *pTerm, int nTerm){
  QueryTerm *t;
  ++q->nTerms;
  q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
  if( q->pTerms==0 ){
    q->nTerms = 0;
    return;
  }
  t = &q->pTerms[q->nTerms - 1];
  CLEAR(t);
  t->pTerm = sqlite3_malloc(nTerm+1);
  memcpy(t->pTerm, pTerm, nTerm);
  t->pTerm[nTerm] = 0;
  t->nTerm = nTerm;
  t->isOr = q->nextIsOr;
  t->isPrefix = 0;
  q->nextIsOr = 0;
  t->iColumn = q->nextColumn;
  q->nextColumn = q->dfltColumn;
}

/*
** Check to see if the string zToken[0...nToken-1] matches any
** column name in the virtual table.   If it does,
** return the zero-indexed column number.  If not, return -1.
*/
static int checkColumnSpecifier(
  fulltext_vtab *pVtab,    /* The virtual table */
  const char *zToken,      /* Text of the token */
  int nToken               /* Number of characters in the token */
){
  int i;
  for(i=0; i<pVtab->nColumn; i++){
    if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
        && pVtab->azColumn[i][nToken]==0 ){
      return i;
    }
  }
  return -1;
}

/*
** Parse the text at pSegment[0..nSegment-1].  Add additional terms
** to the query being assemblied in pQuery.
**
** inPhrase is true if pSegment[0..nSegement-1] is contained within
** double-quotes.  If inPhrase is true, then the first term
** is marked with the number of terms in the phrase less one and
** OR and "-" syntax is ignored.  If inPhrase is false, then every
** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
*/
static int tokenizeSegment(
  sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
  const char *pSegment, int nSegment,     /* Query expression being parsed */
  int inPhrase,                           /* True if within "..." */
  Query *pQuery                           /* Append results here */
){
  const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  sqlite3_tokenizer_cursor *pCursor;
  int firstIndex = pQuery->nTerms;
  int iCol;
  int nTerm = 1;
  
  int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
  if( rc!=SQLITE_OK ) return rc;
  pCursor->pTokenizer = pTokenizer;

  while( 1 ){
    const char *pToken;
    int nToken, iBegin, iEnd, iPos;

    rc = pModule->xNext(pCursor,
                        &pToken, &nToken,
                        &iBegin, &iEnd, &iPos);
    if( rc!=SQLITE_OK ) break;
    if( !inPhrase &&
        pSegment[iEnd]==':' &&
         (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
      pQuery->nextColumn = iCol;
      continue;
    }
    if( !inPhrase && pQuery->nTerms>0 && nToken==2
         && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){
      pQuery->nextIsOr = 1;
      continue;
    }
    queryAdd(pQuery, pToken, nToken);
    if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
      pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
    }
    if( iEnd<nSegment && pSegment[iEnd]=='*' ){
      pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
    }
    pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
    if( inPhrase ){
      nTerm++;
    }
  }

  if( inPhrase && pQuery->nTerms>firstIndex ){
    pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
  }

  return pModule->xClose(pCursor);
}

/* Parse a query string, yielding a Query object pQuery.
**
** The calling function will need to queryClear() to clean up
** the dynamically allocated memory held by pQuery.
*/
static int parseQuery(
  fulltext_vtab *v,        /* The fulltext index */
  const char *zInput,      /* Input text of the query string */
  int nInput,              /* Size of the input text */
  int dfltColumn,          /* Default column of the index to match against */
  Query *pQuery            /* Write the parse results here. */
){
  int iInput, inPhrase = 0;

  if( zInput==0 ) nInput = 0;
  if( nInput<0 ) nInput = strlen(zInput);
  pQuery->nTerms = 0;
  pQuery->pTerms = NULL;
  pQuery->nextIsOr = 0;
  pQuery->nextColumn = dfltColumn;
  pQuery->dfltColumn = dfltColumn;
  pQuery->pFts = v;

  for(iInput=0; iInput<nInput; ++iInput){
    int i;
    for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
    if( i>iInput ){
      tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
                       pQuery);
    }
    iInput = i;
    if( i<nInput ){
      assert( zInput[i]=='"' );
      inPhrase = !inPhrase;
    }
  }

  if( inPhrase ){
    /* unmatched quote */
    queryClear(pQuery);
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}

/* TODO(shess) Refactor the code to remove this forward decl. */
static int flushPendingTerms(fulltext_vtab *v);

/* Perform a full-text query using the search expression in
** zInput[0..nInput-1].  Return a list of matching documents
** in pResult.
**
** Queries must match column iColumn.  Or if iColumn>=nColumn
** they are allowed to match against any column.
*/
static int fulltextQuery(
  fulltext_vtab *v,      /* The full text index */
  int iColumn,           /* Match against this column by default */
  const char *zInput,    /* The query string */
  int nInput,            /* Number of bytes in zInput[] */
  DataBuffer *pResult,   /* Write the result doclist here */
  Query *pQuery          /* Put parsed query string here */
){
  int i, iNext, rc;
  DataBuffer left, right, or, new;
  int nNot = 0;
  QueryTerm *aTerm;

  /* TODO(shess) Instead of flushing pendingTerms, we could query for
  ** the relevant term and merge the doclist into what we receive from
  ** the database.  Wait and see if this is a common issue, first.
  **
  ** A good reason not to flush is to not generate update-related
  ** error codes from here.
  */

  /* Flush any buffered updates before executing the query. */
  rc = flushPendingTerms(v);
  if( rc!=SQLITE_OK ) return rc;

  /* TODO(shess) I think that the queryClear() calls below are not
  ** necessary, because fulltextClose() already clears the query.
  */
  rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
  if( rc!=SQLITE_OK ) return rc;

  /* Empty or NULL queries return no results. */
  if( pQuery->nTerms==0 ){
    dataBufferInit(pResult, 0);
    return SQLITE_OK;
  }

  /* Merge AND terms. */
  /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
  aTerm = pQuery->pTerms;
  for(i = 0; i<pQuery->nTerms; i=iNext){
    if( aTerm[i].isNot ){
      /* Handle all NOT terms in a separate pass */
      nNot++;
      iNext = i + aTerm[i].nPhrase+1;
      continue;
    }
    iNext = i + aTerm[i].nPhrase + 1;
    rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
    if( rc ){
      if( i!=nNot ) dataBufferDestroy(&left);
      queryClear(pQuery);
      return rc;
    }
    while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
      rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
      iNext += aTerm[iNext].nPhrase + 1;
      if( rc ){
        if( i!=nNot ) dataBufferDestroy(&left);
        dataBufferDestroy(&right);
        queryClear(pQuery);
        return rc;
      }
      dataBufferInit(&new, 0);
      docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
      dataBufferDestroy(&right);
      dataBufferDestroy(&or);
      right = new;
    }
    if( i==nNot ){           /* first term processed. */
      left = right;
    }else{
      dataBufferInit(&new, 0);
      docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
      dataBufferDestroy(&right);
      dataBufferDestroy(&left);
      left = new;
    }
  }

  if( nNot==pQuery->nTerms ){
    /* We do not yet know how to handle a query of only NOT terms */
    return SQLITE_ERROR;
  }

  /* Do the EXCEPT terms */
  for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
    if( !aTerm[i].isNot ) continue;
    rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
    if( rc ){
      queryClear(pQuery);
      dataBufferDestroy(&left);
      return rc;
    }
    dataBufferInit(&new, 0);
    docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
    dataBufferDestroy(&right);
    dataBufferDestroy(&left);
    left = new;
  }

  *pResult = left;
  return rc;
}

/*
** This is the xFilter interface for the virtual table.  See
** the virtual table xFilter method documentation for additional
** information.
**
** If idxNum==QUERY_GENERIC then do a full table scan against
** the %_content table.
**
** If idxNum==QUERY_ROWID then do a rowid lookup for a single entry
** in the %_content table.
**
** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
** column on the left-hand side of the MATCH operator is column
** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
** side of the MATCH operator.
*/
/* TODO(shess) Upgrade the cursor initialization and destruction to
** account for fulltextFilter() being called multiple times on the
** same cursor.  The current solution is very fragile.  Apply fix to
** fts2 as appropriate.
*/
static int fulltextFilter(
  sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
  int idxNum, const char *idxStr,   /* Which indexing scheme to use */
  int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);
  int rc;

  TRACE(("FTS2 Filter %p\n",pCursor));

  /* If the cursor has a statement that was not prepared according to
  ** idxNum, clear it.  I believe all calls to fulltextFilter with a
  ** given cursor will have the same idxNum , but in this case it's
  ** easy to be safe.
  */
  if( c->pStmt && c->iCursorType!=idxNum ){
    sqlite3_finalize(c->pStmt);
    c->pStmt = NULL;
  }

  /* Get a fresh statement appropriate to idxNum. */
  /* TODO(shess): Add a prepared-statement cache in the vt structure.
  ** The cache must handle multiple open cursors.  Easier to cache the
  ** statement variants at the vt to reduce malloc/realloc/free here.
  ** Or we could have a StringBuffer variant which allowed stack
  ** construction for small values.
  */
  if( !c->pStmt ){
    char *zSql = sqlite3_mprintf("select rowid, * from %%_content %s",
                                 idxNum==QUERY_GENERIC ? "" : "where rowid=?");
    rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql);
    sqlite3_free(zSql);
    if( rc!=SQLITE_OK ) return rc;
    c->iCursorType = idxNum;
  }else{
    sqlite3_reset(c->pStmt);
    assert( c->iCursorType==idxNum );
  }

  switch( idxNum ){
    case QUERY_GENERIC:
      break;

    case QUERY_ROWID:
      rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
      if( rc!=SQLITE_OK ) return rc;
      break;

    default:   /* full-text search */
    {
      const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
      assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
      assert( argc==1 );
      queryClear(&c->q);
      if( c->result.nData!=0 ){
        /* This case happens if the same cursor is used repeatedly. */
        dlrDestroy(&c->reader);
        dataBufferReset(&c->result);
      }else{
        dataBufferInit(&c->result, 0);
      }
      rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
      if( rc!=SQLITE_OK ) return rc;
      if( c->result.nData!=0 ){
        dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
      }
      break;
    }
  }

  return fulltextNext(pCursor);
}

/* This is the xEof method of the virtual table.  The SQLite core
** calls this routine to find out if it has reached the end of
** a query's results set.
*/
static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  return c->eof;
}

/* This is the xColumn method of the virtual table.  The SQLite
** core calls this method during a query when it needs the value
** of a column from the virtual table.  This method needs to use
** one of the sqlite3_result_*() routines to store the requested
** value back in the pContext.
*/
static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
                          sqlite3_context *pContext, int idxCol){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);

  if( idxCol<v->nColumn ){
    sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
    sqlite3_result_value(pContext, pVal);
  }else if( idxCol==v->nColumn ){
    /* The extra column whose name is the same as the table.
    ** Return a blob which is a pointer to the cursor
    */
    sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
  }
  return SQLITE_OK;
}

/* This is the xRowid method.  The SQLite core calls this routine to
** retrive the rowid for the current row of the result set.  The
** rowid should be written to *pRowid.
*/
static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;

  *pRowid = sqlite3_column_int64(c->pStmt, 0);
  return SQLITE_OK;
}

/* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
** we also store positions and offsets in the hash table using that
** column number.
*/
static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
                      const char *zText, int iColumn){
  sqlite3_tokenizer *pTokenizer = v->pTokenizer;
  sqlite3_tokenizer_cursor *pCursor;
  const char *pToken;
  int nTokenBytes;
  int iStartOffset, iEndOffset, iPosition;
  int rc;

  rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  if( rc!=SQLITE_OK ) return rc;

  pCursor->pTokenizer = pTokenizer;
  while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
                                                   &pToken, &nTokenBytes,
                                                   &iStartOffset, &iEndOffset,
                                                   &iPosition)) ){
    DLCollector *p;
    int nData;                   /* Size of doclist before our update. */

    /* Positions can't be negative; we use -1 as a terminator
     * internally.  Token can't be NULL or empty. */
    if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
      rc = SQLITE_ERROR;
      break;
    }

    p = fts2HashFind(&v->pendingTerms, pToken, nTokenBytes);
    if( p==NULL ){
      nData = 0;
      p = dlcNew(iDocid, DL_DEFAULT);
      fts2HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);

      /* Overhead for our hash table entry, the key, and the value. */
      v->nPendingData += sizeof(struct fts2HashElem)+sizeof(*p)+nTokenBytes;
    }else{
      nData = p->b.nData;
      if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
    }
    if( iColumn>=0 ){
      dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
    }

    /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
    v->nPendingData += p->b.nData-nData;
  }

  /* TODO(shess) Check return?  Should this be able to cause errors at
  ** this point?  Actually, same question about sqlite3_finalize(),
  ** though one could argue that failure there means that the data is
  ** not durable.  *ponder*
  */
  pTokenizer->pModule->xClose(pCursor);
  if( SQLITE_DONE == rc ) return SQLITE_OK;
  return rc;
}

/* Add doclists for all terms in [pValues] to pendingTerms table. */
static int insertTerms(fulltext_vtab *v, sqlite_int64 iRowid,
                       sqlite3_value **pValues){
  int i;
  for(i = 0; i < v->nColumn ; ++i){
    char *zText = (char*)sqlite3_value_text(pValues[i]);
    int rc = buildTerms(v, iRowid, zText, i);
    if( rc!=SQLITE_OK ) return rc;
  }
  return SQLITE_OK;
}

/* Add empty doclists for all terms in the given row's content to
** pendingTerms.
*/
static int deleteTerms(fulltext_vtab *v, sqlite_int64 iRowid){
  const char **pValues;
  int i, rc;

  /* TODO(shess) Should we allow such tables at all? */
  if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;

  rc = content_select(v, iRowid, &pValues);
  if( rc!=SQLITE_OK ) return rc;

  for(i = 0 ; i < v->nColumn; ++i) {
    rc = buildTerms(v, iRowid, pValues[i], -1);
    if( rc!=SQLITE_OK ) break;
  }

  freeStringArray(v->nColumn, pValues);
  return SQLITE_OK;
}

/* TODO(shess) Refactor the code to remove this forward decl. */
static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);

/* Insert a row into the %_content table; set *piRowid to be the ID of the
** new row.  Add doclists for terms to pendingTerms.
*/
static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid,
                        sqlite3_value **pValues, sqlite_int64 *piRowid){
  int rc;

  rc = content_insert(v, pRequestRowid, pValues);  /* execute an SQL INSERT */
  if( rc!=SQLITE_OK ) return rc;

  *piRowid = sqlite3_last_insert_rowid(v->db);
  rc = initPendingTerms(v, *piRowid);
  if( rc!=SQLITE_OK ) return rc;

  return insertTerms(v, *piRowid, pValues);
}

/* Delete a row from the %_content table; add empty doclists for terms
** to pendingTerms.
*/
static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  int rc = initPendingTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = deleteTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  return content_delete(v, iRow);  /* execute an SQL DELETE */
}

/* Update a row in the %_content table; add delete doclists to
** pendingTerms for old terms not in the new data, add insert doclists
** to pendingTerms for terms in the new data.
*/
static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
                        sqlite3_value **pValues){
  int rc = initPendingTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  /* Generate an empty doclist for each term that previously appeared in this
   * row. */
  rc = deleteTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
  if( rc!=SQLITE_OK ) return rc;

  /* Now add positions for terms which appear in the updated row. */
  return insertTerms(v, iRow, pValues);
}

/*******************************************************************/
/* InteriorWriter is used to collect terms and block references into
** interior nodes in %_segments.  See commentary at top of file for
** format.
*/

/* How large interior nodes can grow. */
#define INTERIOR_MAX 2048

/* Minimum number of terms per interior node (except the root). This
** prevents large terms from making the tree too skinny - must be >0
** so that the tree always makes progress.  Note that the min tree
** fanout will be INTERIOR_MIN_TERMS+1.
*/
#define INTERIOR_MIN_TERMS 7
#if INTERIOR_MIN_TERMS<1
# error INTERIOR_MIN_TERMS must be greater than 0.
#endif

/* ROOT_MAX controls how much data is stored inline in the segment
** directory.
*/
/* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
** can both see it, but if the caller passed it in, we wouldn't even
** need a define.
*/
#define ROOT_MAX 1024
#if ROOT_MAX<VARINT_MAX*2
# error ROOT_MAX must have enough space for a header.
#endif

/* InteriorBlock stores a linked-list of interior blocks while a lower
** layer is being constructed.
*/
typedef struct InteriorBlock {
  DataBuffer term;           /* Leftmost term in block's subtree. */
  DataBuffer data;           /* Accumulated data for the block. */
  struct InteriorBlock *next;
} InteriorBlock;

static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
                                       const char *pTerm, int nTerm){
  InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
  char c[VARINT_MAX+VARINT_MAX];
  int n;

  if( block ){
    memset(block, 0, sizeof(*block));
    dataBufferInit(&block->term, 0);
    dataBufferReplace(&block->term, pTerm, nTerm);

    n = putVarint(c, iHeight);
    n += putVarint(c+n, iChildBlock);
    dataBufferInit(&block->data, INTERIOR_MAX);
    dataBufferReplace(&block->data, c, n);
  }
  return block;
}

#ifndef NDEBUG
/* Verify that the data is readable as an interior node. */
static void interiorBlockValidate(InteriorBlock *pBlock){
  const char *pData = pBlock->data.pData;
  int nData = pBlock->data.nData;
  int n, iDummy;
  sqlite_int64 iBlockid;

  assert( nData>0 );
  assert( pData!=0 );
  assert( pData+nData>pData );

  /* Must lead with height of node as a varint(n), n>0 */
  n = getVarint32(pData, &iDummy);
  assert( n>0 );
  assert( iDummy>0 );
  assert( n<nData );
  pData += n;
  nData -= n;

  /* Must contain iBlockid. */
  n = getVarint(pData, &iBlockid);
  assert( n>0 );
  assert( n<=nData );
  pData += n;
  nData -= n;

  /* Zero or more terms of positive length */
  if( nData!=0 ){
    /* First term is not delta-encoded. */
    n = getVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>0 );
    assert( n+iDummy>0);
    assert( n+iDummy<=nData );
    pData += n+iDummy;
    nData -= n+iDummy;

    /* Following terms delta-encoded. */
    while( nData!=0 ){
      /* Length of shared prefix. */
      n = getVarint32(pData, &iDummy);
      assert( n>0 );
      assert( iDummy>=0 );
      assert( n<nData );
      pData += n;
      nData -= n;

      /* Length and data of distinct suffix. */
      n = getVarint32(pData, &iDummy);
      assert( n>0 );
      assert( iDummy>0 );
      assert( n+iDummy>0);
      assert( n+iDummy<=nData );
      pData += n+iDummy;
      nData -= n+iDummy;
    }
  }
}
#define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
#else
#define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
#endif

typedef struct InteriorWriter {
  int iHeight;                   /* from 0 at leaves. */
  InteriorBlock *first, *last;
  struct InteriorWriter *parentWriter;

  DataBuffer term;               /* Last term written to block "last". */
  sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
#ifndef NDEBUG
  sqlite_int64 iLastChildBlock;  /* for consistency checks. */
#endif
} InteriorWriter;

/* Initialize an interior node where pTerm[nTerm] marks the leftmost
** term in the tree.  iChildBlock is the leftmost child block at the
** next level down the tree.
*/
static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
                               sqlite_int64 iChildBlock,
                               InteriorWriter *pWriter){
  InteriorBlock *block;
  assert( iHeight>0 );
  CLEAR(pWriter);

  pWriter->iHeight = iHeight;
  pWriter->iOpeningChildBlock = iChildBlock;
#ifndef NDEBUG
  pWriter->iLastChildBlock = iChildBlock;
#endif
  block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
  pWriter->last = pWriter->first = block;
  ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  dataBufferInit(&pWriter->term, 0);
}

/* Append the child node rooted at iChildBlock to the interior node,
** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
*/
static void interiorWriterAppend(InteriorWriter *pWriter,
                                 const char *pTerm, int nTerm,
                                 sqlite_int64 iChildBlock){
  char c[VARINT_MAX+VARINT_MAX];
  int n, nPrefix = 0;

  ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);

  /* The first term written into an interior node is actually
  ** associated with the second child added (the first child was added
  ** in interiorWriterInit, or in the if clause at the bottom of this
  ** function).  That term gets encoded straight up, with nPrefix left
  ** at 0.
  */
  if( pWriter->term.nData==0 ){
    n = putVarint(c, nTerm);
  }else{
    while( nPrefix<pWriter->term.nData &&
           pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
      nPrefix++;
    }

    n = putVarint(c, nPrefix);
    n += putVarint(c+n, nTerm-nPrefix);
  }

#ifndef NDEBUG
  pWriter->iLastChildBlock++;
#endif
  assert( pWriter->iLastChildBlock==iChildBlock );

  /* Overflow to a new block if the new term makes the current block
  ** too big, and the current block already has enough terms.
  */
  if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
      iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
    pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
                                           pTerm, nTerm);
    pWriter->last = pWriter->last->next;
    pWriter->iOpeningChildBlock = iChildBlock;
    dataBufferReset(&pWriter->term);
  }else{
    dataBufferAppend2(&pWriter->last->data, c, n,
                      pTerm+nPrefix, nTerm-nPrefix);
    dataBufferReplace(&pWriter->term, pTerm, nTerm);
  }
  ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
}

/* Free the space used by pWriter, including the linked-list of
** InteriorBlocks, and parentWriter, if present.
*/
static int interiorWriterDestroy(InteriorWriter *pWriter){
  InteriorBlock *block = pWriter->first;

  while( block!=NULL ){
    InteriorBlock *b = block;
    block = block->next;
    dataBufferDestroy(&b->term);
    dataBufferDestroy(&b->data);
    sqlite3_free(b);
  }
  if( pWriter->parentWriter!=NULL ){
    interiorWriterDestroy(pWriter->parentWriter);
    sqlite3_free(pWriter->parentWriter);
  }
  dataBufferDestroy(&pWriter->term);
  SCRAMBLE(pWriter);
  return SQLITE_OK;
}

/* If pWriter can fit entirely in ROOT_MAX, return it as the root info
** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
** pWriter to %_segments, building a new layer of interior nodes, and
** recursively ask for their root into.
*/
static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
                                  char **ppRootInfo, int *pnRootInfo,
                                  sqlite_int64 *piEndBlockid){
  InteriorBlock *block = pWriter->first;
  sqlite_int64 iBlockid = 0;
  int rc;

  /* If we can fit the segment inline */
  if( block==pWriter->last && block->data.nData<ROOT_MAX ){
    *ppRootInfo = block->data.pData;
    *pnRootInfo = block->data.nData;
    return SQLITE_OK;
  }

  /* Flush the first block to %_segments, and create a new level of
  ** interior node.
  */
  ASSERT_VALID_INTERIOR_BLOCK(block);
  rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  if( rc!=SQLITE_OK ) return rc;
  *piEndBlockid = iBlockid;

  pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
  interiorWriterInit(pWriter->iHeight+1,
                     block->term.pData, block->term.nData,
                     iBlockid, pWriter->parentWriter);

  /* Flush additional blocks and append to the higher interior
  ** node.
  */
  for(block=block->next; block!=NULL; block=block->next){
    ASSERT_VALID_INTERIOR_BLOCK(block);
    rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
    if( rc!=SQLITE_OK ) return rc;
    *piEndBlockid = iBlockid;

    interiorWriterAppend(pWriter->parentWriter,
                         block->term.pData, block->term.nData, iBlockid);
  }

  /* Parent node gets the chance to be the root. */
  return interiorWriterRootInfo(v, pWriter->parentWriter,
                                ppRootInfo, pnRootInfo, piEndBlockid);
}

/****************************************************************/
/* InteriorReader is used to read off the data from an interior node
** (see comment at top of file for the format).
*/
typedef struct InteriorReader {
  const char *pData;
  int nData;

  DataBuffer term;          /* previous term, for decoding term delta. */

  sqlite_int64 iBlockid;
} InteriorReader;

static void interiorReaderDestroy(InteriorReader *pReader){
  dataBufferDestroy(&pReader->term);
  SCRAMBLE(pReader);
}

/* TODO(shess) The assertions are great, but what if we're in NDEBUG
** and the blob is empty or otherwise contains suspect data?
*/
static void interiorReaderInit(const char *pData, int nData,
                               InteriorReader *pReader){
  int n, nTerm;

  /* Require at least the leading flag byte */
  assert( nData>0 );
  assert( pData[0]!='\0' );

  CLEAR(pReader);

  /* Decode the base blockid, and set the cursor to the first term. */
  n = getVarint(pData+1, &pReader->iBlockid);
  assert( 1+n<=nData );
  pReader->pData = pData+1+n;
  pReader->nData = nData-(1+n);

  /* A single-child interior node (such as when a leaf node was too
  ** large for the segment directory) won't have any terms.
  ** Otherwise, decode the first term.
  */
  if( pReader->nData==0 ){
    dataBufferInit(&pReader->term, 0);
  }else{
    n = getVarint32(pReader->pData, &nTerm);
    dataBufferInit(&pReader->term, nTerm);
    dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
    assert( n+nTerm<=pReader->nData );
    pReader->pData += n+nTerm;
    pReader->nData -= n+nTerm;
  }
}

static int interiorReaderAtEnd(InteriorReader *pReader){
  return pReader->term.nData==0;
}

static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
  return pReader->iBlockid;
}

static int interiorReaderTermBytes(InteriorReader *pReader){
  assert( !interiorReaderAtEnd(pReader) );
  return pReader->term.nData;
}
static const char *interiorReaderTerm(InteriorReader *pReader){
  assert( !interiorReaderAtEnd(pReader) );
  return pReader->term.pData;
}

/* Step forward to the next term in the node. */
static void interiorReaderStep(InteriorReader *pReader){
  assert( !interiorReaderAtEnd(pReader) );

  /* If the last term has been read, signal eof, else construct the
  ** next term.
  */
  if( pReader->nData==0 ){
    dataBufferReset(&pReader->term);
  }else{
    int n, nPrefix, nSuffix;

    n = getVarint32(pReader->pData, &nPrefix);
    n += getVarint32(pReader->pData+n, &nSuffix);

    /* Truncate the current term and append suffix data. */
    pReader->term.nData = nPrefix;
    dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);

    assert( n+nSuffix<=pReader->nData );
    pReader->pData += n+nSuffix;
    pReader->nData -= n+nSuffix;
  }
  pReader->iBlockid++;
}

/* Compare the current term to pTerm[nTerm], returning strcmp-style
** results.  If isPrefix, equality means equal through nTerm bytes.
*/
static int interiorReaderTermCmp(InteriorReader *pReader,
                                 const char *pTerm, int nTerm, int isPrefix){
  const char *pReaderTerm = interiorReaderTerm(pReader);
  int nReaderTerm = interiorReaderTermBytes(pReader);
  int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;

  if( n==0 ){
    if( nReaderTerm>0 ) return -1;
    if( nTerm>0 ) return 1;
    return 0;
  }

  c = memcmp(pReaderTerm, pTerm, n);
  if( c!=0 ) return c;
  if( isPrefix && n==nTerm ) return 0;
  return nReaderTerm - nTerm;
}

/****************************************************************/
/* LeafWriter is used to collect terms and associated doclist data
** into leaf blocks in %_segments (see top of file for format info).
** Expected usage is:
**
** LeafWriter writer;
** leafWriterInit(0, 0, &writer);
** while( sorted_terms_left_to_process ){
**   // data is doclist data for that term.
**   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
**   if( rc!=SQLITE_OK ) goto err;
** }
** rc = leafWriterFinalize(v, &writer);
**err:
** leafWriterDestroy(&writer);
** return rc;
**
** leafWriterStep() may write a collected leaf out to %_segments.
** leafWriterFinalize() finishes writing any buffered data and stores
** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
** InteriorWriters allocated as part of writing this segment.
**
** TODO(shess) Document leafWriterStepMerge().
*/

/* Put terms with data this big in their own block. */
#define STANDALONE_MIN 1024

/* Keep leaf blocks below this size. */
#define LEAF_MAX 2048

typedef struct LeafWriter {
  int iLevel;
  int idx;
  sqlite_int64 iStartBlockid;     /* needed to create the root info */
  sqlite_int64 iEndBlockid;       /* when we're done writing. */

  DataBuffer term;                /* previous encoded term */
  DataBuffer data;                /* encoding buffer */

  /* bytes of first term in the current node which distinguishes that
  ** term from the last term of the previous node.
  */
  int nTermDistinct;

  InteriorWriter parentWriter;    /* if we overflow */
  int has_parent;
} LeafWriter;

static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
  CLEAR(pWriter);
  pWriter->iLevel = iLevel;
  pWriter->idx = idx;

  dataBufferInit(&pWriter->term, 32);

  /* Start out with a reasonably sized block, though it can grow. */
  dataBufferInit(&pWriter->data, LEAF_MAX);
}

#ifndef NDEBUG
/* Verify that the data is readable as a leaf node. */
static void leafNodeValidate(const char *pData, int nData){
  int n, iDummy;

  if( nData==0 ) return;
  assert( nData>0 );
  assert( pData!=0 );
  assert( pData+nData>pData );

  /* Must lead with a varint(0) */
  n = getVarint32(pData, &iDummy);
  assert( iDummy==0 );
  assert( n>0 );
  assert( n<nData );
  pData += n;
  nData -= n;

  /* Leading term length and data must fit in buffer. */
  n = getVarint32(pData, &iDummy);
  assert( n>0 );
  assert( iDummy>0 );
  assert( n+iDummy>0 );
  assert( n+iDummy<nData );
  pData += n+iDummy;
  nData -= n+iDummy;

  /* Leading term's doclist length and data must fit. */
  n = getVarint32(pData, &iDummy);
  assert( n>0 );
  assert( iDummy>0 );
  assert( n+iDummy>0 );
  assert( n+iDummy<=nData );
  ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  pData += n+iDummy;
  nData -= n+iDummy;

  /* Verify that trailing terms and doclists also are readable. */
  while( nData!=0 ){
    n = getVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>=0 );
    assert( n<nData );
    pData += n;
    nData -= n;
    n = getVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>0 );
    assert( n+iDummy>0 );
    assert( n+iDummy<nData );
    pData += n+iDummy;
    nData -= n+iDummy;

    n = getVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>0 );
    assert( n+iDummy>0 );
    assert( n+iDummy<=nData );
    ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
    pData += n+iDummy;
    nData -= n+iDummy;
  }
}
#define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
#else
#define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
#endif

/* Flush the current leaf node to %_segments, and adding the resulting
** blockid and the starting term to the interior node which will
** contain it.
*/
static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
                                   int iData, int nData){
  sqlite_int64 iBlockid = 0;
  const char *pStartingTerm;
  int nStartingTerm, rc, n;

  /* Must have the leading varint(0) flag, plus at least some
  ** valid-looking data.
  */
  assert( nData>2 );
  assert( iData>=0 );
  assert( iData+nData<=pWriter->data.nData );
  ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);

  rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
  if( rc!=SQLITE_OK ) return rc;
  assert( iBlockid!=0 );

  /* Reconstruct the first term in the leaf for purposes of building
  ** the interior node.
  */
  n = getVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
  pStartingTerm = pWriter->data.pData+iData+1+n;
  assert( pWriter->data.nData>iData+1+n+nStartingTerm );
  assert( pWriter->nTermDistinct>0 );
  assert( pWriter->nTermDistinct<=nStartingTerm );
  nStartingTerm = pWriter->nTermDistinct;

  if( pWriter->has_parent ){
    interiorWriterAppend(&pWriter->parentWriter,
                         pStartingTerm, nStartingTerm, iBlockid);
  }else{
    interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
                       &pWriter->parentWriter);
    pWriter->has_parent = 1;
  }

  /* Track the span of this segment's leaf nodes. */
  if( pWriter->iEndBlockid==0 ){
    pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
  }else{
    pWriter->iEndBlockid++;
    assert( iBlockid==pWriter->iEndBlockid );
  }

  return SQLITE_OK;
}
static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
  int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
  if( rc!=SQLITE_OK ) return rc;

  /* Re-initialize the output buffer. */
  dataBufferReset(&pWriter->data);

  return SQLITE_OK;
}

/* Fetch the root info for the segment.  If the entire leaf fits
** within ROOT_MAX, then it will be returned directly, otherwise it
** will be flushed and the root info will be returned from the
** interior node.  *piEndBlockid is set to the blockid of the last
** interior or leaf node written to disk (0 if none are written at
** all).
*/
static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
                              char **ppRootInfo, int *pnRootInfo,
                              sqlite_int64 *piEndBlockid){
  /* we can fit the segment entirely inline */
  if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
    *ppRootInfo = pWriter->data.pData;
    *pnRootInfo = pWriter->data.nData;
    *piEndBlockid = 0;
    return SQLITE_OK;
  }

  /* Flush remaining leaf data. */
  if( pWriter->data.nData>0 ){
    int rc = leafWriterFlush(v, pWriter);
    if( rc!=SQLITE_OK ) return rc;
  }

  /* We must have flushed a leaf at some point. */
  assert( pWriter->has_parent );

  /* Tenatively set the end leaf blockid as the end blockid.  If the
  ** interior node can be returned inline, this will be the final
  ** blockid, otherwise it will be overwritten by
  ** interiorWriterRootInfo().
  */
  *piEndBlockid = pWriter->iEndBlockid;

  return interiorWriterRootInfo(v, &pWriter->parentWriter,
                                ppRootInfo, pnRootInfo, piEndBlockid);
}

/* Collect the rootInfo data and store it into the segment directory.
** This has the effect of flushing the segment's leaf data to
** %_segments, and also flushing any interior nodes to %_segments.
*/
static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
  sqlite_int64 iEndBlockid;
  char *pRootInfo;
  int rc, nRootInfo;

  rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  /* Don't bother storing an entirely empty segment. */
  if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;

  return segdir_set(v, pWriter->iLevel, pWriter->idx,
                    pWriter->iStartBlockid, pWriter->iEndBlockid,
                    iEndBlockid, pRootInfo, nRootInfo);
}

static void leafWriterDestroy(LeafWriter *pWriter){
  if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
  dataBufferDestroy(&pWriter->term);
  dataBufferDestroy(&pWriter->data);
}

/* Encode a term into the leafWriter, delta-encoding as appropriate.
** Returns the length of the new term which distinguishes it from the
** previous term, which can be used to set nTermDistinct when a node
** boundary is crossed.
*/
static int leafWriterEncodeTerm(LeafWriter *pWriter,
                                const char *pTerm, int nTerm){
  char c[VARINT_MAX+VARINT_MAX];
  int n, nPrefix = 0;

  assert( nTerm>0 );
  while( nPrefix<pWriter->term.nData &&
         pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
    nPrefix++;
    /* Failing this implies that the terms weren't in order. */
    assert( nPrefix<nTerm );
  }

  if( pWriter->data.nData==0 ){
    /* Encode the node header and leading term as:
    **  varint(0)
    **  varint(nTerm)
    **  char pTerm[nTerm]
    */
    n = putVarint(c, '\0');
    n += putVarint(c+n, nTerm);
    dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
  }else{
    /* Delta-encode the term as:
    **  varint(nPrefix)
    **  varint(nSuffix)
    **  char pTermSuffix[nSuffix]
    */
    n = putVarint(c, nPrefix);
    n += putVarint(c+n, nTerm-nPrefix);
    dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
  }
  dataBufferReplace(&pWriter->term, pTerm, nTerm);

  return nPrefix+1;
}

/* Used to avoid a memmove when a large amount of doclist data is in
** the buffer.  This constructs a node and term header before
** iDoclistData and flushes the resulting complete node using
** leafWriterInternalFlush().
*/
static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
                                 const char *pTerm, int nTerm,
                                 int iDoclistData){
  char c[VARINT_MAX+VARINT_MAX];
  int iData, n = putVarint(c, 0);
  n += putVarint(c+n, nTerm);

  /* There should always be room for the header.  Even if pTerm shared
  ** a substantial prefix with the previous term, the entire prefix
  ** could be constructed from earlier data in the doclist, so there
  ** should be room.
  */
  assert( iDoclistData>=n+nTerm );

  iData = iDoclistData-(n+nTerm);
  memcpy(pWriter->data.pData+iData, c, n);
  memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);

  return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
}

/* Push pTerm[nTerm] along with the doclist data to the leaf layer of
** %_segments.
*/
static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
                               const char *pTerm, int nTerm,
                               DLReader *pReaders, int nReaders){
  char c[VARINT_MAX+VARINT_MAX];
  int iTermData = pWriter->data.nData, iDoclistData;
  int i, nData, n, nActualData, nActual, rc, nTermDistinct;

  ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);

  /* Remember nTermDistinct if opening a new node. */
  if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;

  iDoclistData = pWriter->data.nData;

  /* Estimate the length of the merged doclist so we can leave space
  ** to encode it.
  */
  for(i=0, nData=0; i<nReaders; i++){
    nData += dlrAllDataBytes(&pReaders[i]);
  }
  n = putVarint(c, nData);
  dataBufferAppend(&pWriter->data, c, n);

  docListMerge(&pWriter->data, pReaders, nReaders);
  ASSERT_VALID_DOCLIST(DL_DEFAULT,
                       pWriter->data.pData+iDoclistData+n,
                       pWriter->data.nData-iDoclistData-n, NULL);

  /* The actual amount of doclist data at this point could be smaller
  ** than the length we encoded.  Additionally, the space required to
  ** encode this length could be smaller.  For small doclists, this is
  ** not a big deal, we can just use memmove() to adjust things.
  */
  nActualData = pWriter->data.nData-(iDoclistData+n);
  nActual = putVarint(c, nActualData);
  assert( nActualData<=nData );
  assert( nActual<=n );

  /* If the new doclist is big enough for force a standalone leaf
  ** node, we can immediately flush it inline without doing the
  ** memmove().
  */
  /* TODO(shess) This test matches leafWriterStep(), which does this
  ** test before it knows the cost to varint-encode the term and
  ** doclist lengths.  At some point, change to
  ** pWriter->data.nData-iTermData>STANDALONE_MIN.
  */
  if( nTerm+nActualData>STANDALONE_MIN ){
    /* Push leaf node from before this term. */
    if( iTermData>0 ){
      rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
      if( rc!=SQLITE_OK ) return rc;

      pWriter->nTermDistinct = nTermDistinct;
    }

    /* Fix the encoded doclist length. */
    iDoclistData += n - nActual;
    memcpy(pWriter->data.pData+iDoclistData, c, nActual);

    /* Push the standalone leaf node. */
    rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
    if( rc!=SQLITE_OK ) return rc;

    /* Leave the node empty. */
    dataBufferReset(&pWriter->data);

    return rc;
  }

  /* At this point, we know that the doclist was small, so do the
  ** memmove if indicated.
  */
  if( nActual<n ){
    memmove(pWriter->data.pData+iDoclistData+nActual,
            pWriter->data.pData+iDoclistData+n,
            pWriter->data.nData-(iDoclistData+n));
    pWriter->data.nData -= n-nActual;
  }

  /* Replace written length with actual length. */
  memcpy(pWriter->data.pData+iDoclistData, c, nActual);

  /* If the node is too large, break things up. */
  /* TODO(shess) This test matches leafWriterStep(), which does this
  ** test before it knows the cost to varint-encode the term and
  ** doclist lengths.  At some point, change to
  ** pWriter->data.nData>LEAF_MAX.
  */
  if( iTermData+nTerm+nActualData>LEAF_MAX ){
    /* Flush out the leading data as a node */
    rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
    if( rc!=SQLITE_OK ) return rc;

    pWriter->nTermDistinct = nTermDistinct;

    /* Rebuild header using the current term */
    n = putVarint(pWriter->data.pData, 0);
    n += putVarint(pWriter->data.pData+n, nTerm);
    memcpy(pWriter->data.pData+n, pTerm, nTerm);
    n += nTerm;

    /* There should always be room, because the previous encoding
    ** included all data necessary to construct the term.
    */
    assert( n<iDoclistData );
    /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
    ** following memcpy() is safe (as opposed to needing a memmove).
    */
    assert( 2*STANDALONE_MIN<=LEAF_MAX );
    assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
    memcpy(pWriter->data.pData+n,
           pWriter->data.pData+iDoclistData,
           pWriter->data.nData-iDoclistData);
    pWriter->data.nData -= iDoclistData-n;
  }
  ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);

  return SQLITE_OK;
}

/* Push pTerm[nTerm] along with the doclist data to the leaf layer of
** %_segments.
*/
/* TODO(shess) Revise writeZeroSegment() so that doclists are
** constructed directly in pWriter->data.
*/
static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
                          const char *pTerm, int nTerm,
                          const char *pData, int nData){
  int rc;
  DLReader reader;

  dlrInit(&reader, DL_DEFAULT, pData, nData);
  rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
  dlrDestroy(&reader);

  return rc;
}


/****************************************************************/
/* LeafReader is used to iterate over an individual leaf node. */
typedef struct LeafReader {
  DataBuffer term;          /* copy of current term. */

  const char *pData;        /* data for current term. */
  int nData;
} LeafReader;

static void leafReaderDestroy(LeafReader *pReader){
  dataBufferDestroy(&pReader->term);
  SCRAMBLE(pReader);
}

static int leafReaderAtEnd(LeafReader *pReader){
  return pReader->nData<=0;
}

/* Access the current term. */
static int leafReaderTermBytes(LeafReader *pReader){
  return pReader->term.nData;
}
static const char *leafReaderTerm(LeafReader *pReader){
  assert( pReader->term.nData>0 );
  return pReader->term.pData;
}

/* Access the doclist data for the current term. */
static int leafReaderDataBytes(LeafReader *pReader){
  int nData;
  assert( pReader->term.nData>0 );
  getVarint32(pReader->pData, &nData);
  return nData;
}
static const char *leafReaderData(LeafReader *pReader){
  int n, nData;
  assert( pReader->term.nData>0 );
  n = getVarint32(pReader->pData, &nData);
  return pReader->pData+n;
}

static void leafReaderInit(const char *pData, int nData,
                           LeafReader *pReader){
  int nTerm, n;

  assert( nData>0 );
  assert( pData[0]=='\0' );

  CLEAR(pReader);

  /* Read the first term, skipping the header byte. */
  n = getVarint32(pData+1, &nTerm);
  dataBufferInit(&pReader->term, nTerm);
  dataBufferReplace(&pReader->term, pData+1+n, nTerm);

  /* Position after the first term. */
  assert( 1+n+nTerm<nData );
  pReader->pData = pData+1+n+nTerm;
  pReader->nData = nData-1-n-nTerm;
}

/* Step the reader forward to the next term. */
static void leafReaderStep(LeafReader *pReader){
  int n, nData, nPrefix, nSuffix;
  assert( !leafReaderAtEnd(pReader) );

  /* Skip previous entry's data block. */
  n = getVarint32(pReader->pData, &nData);
  assert( n+nData<=pReader->nData );
  pReader->pData += n+nData;
  pReader->nData -= n+nData;

  if( !leafReaderAtEnd(pReader) ){
    /* Construct the new term using a prefix from the old term plus a
    ** suffix from the leaf data.
    */
    n = getVarint32(pReader->pData, &nPrefix);
    n += getVarint32(pReader->pData+n, &nSuffix);
    assert( n+nSuffix<pReader->nData );
    pReader->term.nData = nPrefix;
    dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);

    pReader->pData += n+nSuffix;
    pReader->nData -= n+nSuffix;
  }
}

/* strcmp-style comparison of pReader's current term against pTerm.
** If isPrefix, equality means equal through nTerm bytes.
*/
static int leafReaderTermCmp(LeafReader *pReader,
                             const char *pTerm, int nTerm, int isPrefix){
  int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
  if( n==0 ){
    if( pReader->term.nData>0 ) return -1;
    if(nTerm>0 ) return 1;
    return 0;
  }

  c = memcmp(pReader->term.pData, pTerm, n);
  if( c!=0 ) return c;
  if( isPrefix && n==nTerm ) return 0;
  return pReader->term.nData - nTerm;
}


/****************************************************************/
/* LeavesReader wraps LeafReader to allow iterating over the entire
** leaf layer of the tree.
*/
typedef struct LeavesReader {
  int idx;                  /* Index within the segment. */

  sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
  int eof;                  /* we've seen SQLITE_DONE from pStmt. */

  LeafReader leafReader;    /* reader for the current leaf. */
  DataBuffer rootData;      /* root data for inline. */
} LeavesReader;

/* Access the current term. */
static int leavesReaderTermBytes(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderTermBytes(&pReader->leafReader);
}
static const char *leavesReaderTerm(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderTerm(&pReader->leafReader);
}

/* Access the doclist data for the current term. */
static int leavesReaderDataBytes(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderDataBytes(&pReader->leafReader);
}
static const char *leavesReaderData(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderData(&pReader->leafReader);
}

static int leavesReaderAtEnd(LeavesReader *pReader){
  return pReader->eof;
}

/* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
** leaving the statement handle open, which locks the table.
*/
/* TODO(shess) This "solution" is not satisfactory.  Really, there
** should be check-in function for all statement handles which
** arranges to call sqlite3_reset().  This most likely will require
** modification to control flow all over the place, though, so for now
** just punt.
**
** Note the the current system assumes that segment merges will run to
** completion, which is why this particular probably hasn't arisen in
** this case.  Probably a brittle assumption.
*/
static int leavesReaderReset(LeavesReader *pReader){
  return sqlite3_reset(pReader->pStmt);
}

static void leavesReaderDestroy(LeavesReader *pReader){
  /* If idx is -1, that means we're using a non-cached statement
  ** handle in the optimize() case, so we need to release it.
  */
  if( pReader->pStmt!=NULL && pReader->idx==-1 ){
    sqlite3_finalize(pReader->pStmt);
  }
  leafReaderDestroy(&pReader->leafReader);
  dataBufferDestroy(&pReader->rootData);
  SCRAMBLE(pReader);
}

/* Initialize pReader with the given root data (if iStartBlockid==0
** the leaf data was entirely contained in the root), or from the
** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
*/
static int leavesReaderInit(fulltext_vtab *v,
                            int idx,
                            sqlite_int64 iStartBlockid,
                            sqlite_int64 iEndBlockid,
                            const char *pRootData, int nRootData,
                            LeavesReader *pReader){
  CLEAR(pReader);
  pReader->idx = idx;

  dataBufferInit(&pReader->rootData, 0);
  if( iStartBlockid==0 ){
    /* Entire leaf level fit in root data. */
    dataBufferReplace(&pReader->rootData, pRootData, nRootData);
    leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
                   &pReader->leafReader);
  }else{
    sqlite3_stmt *s;
    int rc = sql_get_leaf_statement(v, idx, &s);
    if( rc!=SQLITE_OK ) return rc;

    rc = sqlite3_bind_int64(s, 1, iStartBlockid);
    if( rc!=SQLITE_OK ) return rc;

    rc = sqlite3_bind_int64(s, 2, iEndBlockid);
    if( rc!=SQLITE_OK ) return rc;

    rc = sqlite3_step(s);
    if( rc==SQLITE_DONE ){
      pReader->eof = 1;
      return SQLITE_OK;
    }
    if( rc!=SQLITE_ROW ) return rc;

    pReader->pStmt = s;
    leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
                   sqlite3_column_bytes(pReader->pStmt, 0),
                   &pReader->leafReader);
  }
  return SQLITE_OK;
}

/* Step the current leaf forward to the next term.  If we reach the
** end of the current leaf, step forward to the next leaf block.
*/
static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
  assert( !leavesReaderAtEnd(pReader) );
  leafReaderStep(&pReader->leafReader);

  if( leafReaderAtEnd(&pReader->leafReader) ){
    int rc;
    if( pReader->rootData.pData ){
      pReader->eof = 1;
      return SQLITE_OK;
    }
    rc = sqlite3_step(pReader->pStmt);
    if( rc!=SQLITE_ROW ){
      pReader->eof = 1;
      return rc==SQLITE_DONE ? SQLITE_OK : rc;
    }
    leafReaderDestroy(&pReader->leafReader);
    leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
                   sqlite3_column_bytes(pReader->pStmt, 0),
                   &pReader->leafReader);
  }
  return SQLITE_OK;
}

/* Order LeavesReaders by their term, ignoring idx.  Readers at eof
** always sort to the end.
*/
static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
  if( leavesReaderAtEnd(lr1) ){
    if( leavesReaderAtEnd(lr2) ) return 0;
    return 1;
  }
  if( leavesReaderAtEnd(lr2) ) return -1;

  return leafReaderTermCmp(&lr1->leafReader,
                           leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
                           0);
}

/* Similar to leavesReaderTermCmp(), with additional ordering by idx
** so that older segments sort before newer segments.
*/
static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
  int c = leavesReaderTermCmp(lr1, lr2);
  if( c!=0 ) return c;
  return lr1->idx-lr2->idx;
}

/* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
** sorted position.
*/
static void leavesReaderReorder(LeavesReader *pLr, int nLr){
  while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
    LeavesReader tmp = pLr[0];
    pLr[0] = pLr[1];
    pLr[1] = tmp;
    nLr--;
    pLr++;
  }
}

/* Initializes pReaders with the segments from level iLevel, returning
** the number of segments in *piReaders.  Leaves pReaders in sorted
** order.
*/
static int leavesReadersInit(fulltext_vtab *v, int iLevel,
                             LeavesReader *pReaders, int *piReaders){
  sqlite3_stmt *s;
  int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  i = 0;
  while( (rc = sqlite3_step(s))==SQLITE_ROW ){
    sqlite_int64 iStart = sqlite3_column_int64(s, 0);
    sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
    const char *pRootData = sqlite3_column_blob(s, 2);
    int nRootData = sqlite3_column_bytes(s, 2);

    assert( i<MERGE_COUNT );
    rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
                          &pReaders[i]);
    if( rc!=SQLITE_OK ) break;

    i++;
  }
  if( rc!=SQLITE_DONE ){
    while( i-->0 ){
      leavesReaderDestroy(&pReaders[i]);
    }
    return rc;
  }

  *piReaders = i;

  /* Leave our results sorted by term, then age. */
  while( i-- ){
    leavesReaderReorder(pReaders+i, *piReaders-i);
  }
  return SQLITE_OK;
}

/* Merge doclists from pReaders[nReaders] into a single doclist, which
** is written to pWriter.  Assumes pReaders is ordered oldest to
** newest.
*/
/* TODO(shess) Consider putting this inline in segmentMerge(). */
static int leavesReadersMerge(fulltext_vtab *v,
                              LeavesReader *pReaders, int nReaders,
                              LeafWriter *pWriter){
  DLReader dlReaders[MERGE_COUNT];
  const char *pTerm = leavesReaderTerm(pReaders);
  int i, nTerm = leavesReaderTermBytes(pReaders);

  assert( nReaders<=MERGE_COUNT );

  for(i=0; i<nReaders; i++){
    dlrInit(&dlReaders[i], DL_DEFAULT,
            leavesReaderData(pReaders+i),
            leavesReaderDataBytes(pReaders+i));
  }

  return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
}

/* Forward ref due to mutual recursion with segdirNextIndex(). */
static int segmentMerge(fulltext_vtab *v, int iLevel);

/* Put the next available index at iLevel into *pidx.  If iLevel
** already has MERGE_COUNT segments, they are merged to a higher
** level to make room.
*/
static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
  int rc = segdir_max_index(v, iLevel, pidx);
  if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
    *pidx = 0;
  }else if( rc==SQLITE_ROW ){
    if( *pidx==(MERGE_COUNT-1) ){
      rc = segmentMerge(v, iLevel);
      if( rc!=SQLITE_OK ) return rc;
      *pidx = 0;
    }else{
      (*pidx)++;
    }
  }else{
    return rc;
  }
  return SQLITE_OK;
}

/* Merge MERGE_COUNT segments at iLevel into a new segment at
** iLevel+1.  If iLevel+1 is already full of segments, those will be
** merged to make room.
*/
static int segmentMerge(fulltext_vtab *v, int iLevel){
  LeafWriter writer;
  LeavesReader lrs[MERGE_COUNT];
  int i, rc, idx = 0;

  /* Determine the next available segment index at the next level,
  ** merging as necessary.
  */
  rc = segdirNextIndex(v, iLevel+1, &idx);
  if( rc!=SQLITE_OK ) return rc;

  /* TODO(shess) This assumes that we'll always see exactly
  ** MERGE_COUNT segments to merge at a given level.  That will be
  ** broken if we allow the developer to request preemptive or
  ** deferred merging.
  */
  memset(&lrs, '\0', sizeof(lrs));
  rc = leavesReadersInit(v, iLevel, lrs, &i);
  if( rc!=SQLITE_OK ) return rc;
  assert( i==MERGE_COUNT );

  leafWriterInit(iLevel+1, idx, &writer);

  /* Since leavesReaderReorder() pushes readers at eof to the end,
  ** when the first reader is empty, all will be empty.
  */
  while( !leavesReaderAtEnd(lrs) ){
    /* Figure out how many readers share their next term. */
    for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
      if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
    }

    rc = leavesReadersMerge(v, lrs, i, &writer);
    if( rc!=SQLITE_OK ) goto err;

    /* Step forward those that were merged. */
    while( i-->0 ){
      rc = leavesReaderStep(v, lrs+i);
      if( rc!=SQLITE_OK ) goto err;

      /* Reorder by term, then by age. */
      leavesReaderReorder(lrs+i, MERGE_COUNT-i);
    }
  }

  for(i=0; i<MERGE_COUNT; i++){
    leavesReaderDestroy(&lrs[i]);
  }

  rc = leafWriterFinalize(v, &writer);
  leafWriterDestroy(&writer);
  if( rc!=SQLITE_OK ) return rc;

  /* Delete the merged segment data. */
  return segdir_delete(v, iLevel);

 err:
  for(i=0; i<MERGE_COUNT; i++){
    leavesReaderDestroy(&lrs[i]);
  }
  leafWriterDestroy(&writer);
  return rc;
}

/* Accumulate the union of *acc and *pData into *acc. */
static void docListAccumulateUnion(DataBuffer *acc,
                                   const char *pData, int nData) {
  DataBuffer tmp = *acc;
  dataBufferInit(acc, tmp.nData+nData);
  docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
  dataBufferDestroy(&tmp);
}

/* TODO(shess) It might be interesting to explore different merge
** strategies, here.  For instance, since this is a sorted merge, we
** could easily merge many doclists in parallel.  With some
** comprehension of the storage format, we could merge all of the
** doclists within a leaf node directly from the leaf node's storage.
** It may be worthwhile to merge smaller doclists before larger
** doclists, since they can be traversed more quickly - but the
** results may have less overlap, making them more expensive in a
** different way.
*/

/* Scan pReader for pTerm/nTerm, and merge the term's doclist over
** *out (any doclists with duplicate docids overwrite those in *out).
** Internal function for loadSegmentLeaf().
*/
static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
                                const char *pTerm, int nTerm, int isPrefix,
                                DataBuffer *out){
  /* doclist data is accumulated into pBuffers similar to how one does
  ** increment in binary arithmetic.  If index 0 is empty, the data is
  ** stored there.  If there is data there, it is merged and the
  ** results carried into position 1, with further merge-and-carry
  ** until an empty position is found.
  */
  DataBuffer *pBuffers = NULL;
  int nBuffers = 0, nMaxBuffers = 0, rc;

  assert( nTerm>0 );

  for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
      rc=leavesReaderStep(v, pReader)){
    /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
    ** already taken to compare the terms of two LeavesReaders.  Think
    ** on a better name.  [Meanwhile, break encapsulation rather than
    ** use a confusing name.]
    */
    int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
    if( c>0 ) break;      /* Past any possible matches. */
    if( c==0 ){
      const char *pData = leavesReaderData(pReader);
      int iBuffer, nData = leavesReaderDataBytes(pReader);

      /* Find the first empty buffer. */
      for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
        if( 0==pBuffers[iBuffer].nData ) break;
      }

      /* Out of buffers, add an empty one. */
      if( iBuffer==nBuffers ){
        if( nBuffers==nMaxBuffers ){
          DataBuffer *p;
          nMaxBuffers += 20;

          /* Manual realloc so we can handle NULL appropriately. */
          p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
          if( p==NULL ){
            rc = SQLITE_NOMEM;
            break;
          }

          if( nBuffers>0 ){
            assert(pBuffers!=NULL);
            memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
            sqlite3_free(pBuffers);
          }
          pBuffers = p;
        }
        dataBufferInit(&(pBuffers[nBuffers]), 0);
        nBuffers++;
      }

      /* At this point, must have an empty at iBuffer. */
      assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);

      /* If empty was first buffer, no need for merge logic. */
      if( iBuffer==0 ){
        dataBufferReplace(&(pBuffers[0]), pData, nData);
      }else{
        /* pAcc is the empty buffer the merged data will end up in. */
        DataBuffer *pAcc = &(pBuffers[iBuffer]);
        DataBuffer *p = &(pBuffers[0]);

        /* Handle position 0 specially to avoid need to prime pAcc
        ** with pData/nData.
        */
        dataBufferSwap(p, pAcc);
        docListAccumulateUnion(pAcc, pData, nData);

        /* Accumulate remaining doclists into pAcc. */
        for(++p; p<pAcc; ++p){
          docListAccumulateUnion(pAcc, p->pData, p->nData);

          /* dataBufferReset() could allow a large doclist to blow up
          ** our memory requirements.
          */
          if( p->nCapacity<1024 ){
            dataBufferReset(p);
          }else{
            dataBufferDestroy(p);
            dataBufferInit(p, 0);
          }
        }
      }
    }
  }

  /* Union all the doclists together into *out. */
  /* TODO(shess) What if *out is big?  Sigh. */
  if( rc==SQLITE_OK && nBuffers>0 ){
    int iBuffer;
    for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
      if( pBuffers[iBuffer].nData>0 ){
        if( out->nData==0 ){
          dataBufferSwap(out, &(pBuffers[iBuffer]));
        }else{
          docListAccumulateUnion(out, pBuffers[iBuffer].pData,
                                 pBuffers[iBuffer].nData);
        }
      }
    }
  }

  while( nBuffers-- ){
    dataBufferDestroy(&(pBuffers[nBuffers]));
  }
  if( pBuffers!=NULL ) sqlite3_free(pBuffers);

  return rc;
}

/* Call loadSegmentLeavesInt() with pData/nData as input. */
static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
                           const char *pTerm, int nTerm, int isPrefix,
                           DataBuffer *out){
  LeavesReader reader;
  int rc;

  assert( nData>1 );
  assert( *pData=='\0' );
  rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
  if( rc!=SQLITE_OK ) return rc;

  rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  leavesReaderReset(&reader);
  leavesReaderDestroy(&reader);
  return rc;
}

/* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
** iEndLeaf (inclusive) as input, and merge the resulting doclist into
** out.
*/
static int loadSegmentLeaves(fulltext_vtab *v,
                             sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
                             const char *pTerm, int nTerm, int isPrefix,
                             DataBuffer *out){
  int rc;
  LeavesReader reader;

  assert( iStartLeaf<=iEndLeaf );
  rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
  if( rc!=SQLITE_OK ) return rc;

  rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  leavesReaderReset(&reader);
  leavesReaderDestroy(&reader);
  return rc;
}

/* Taking pData/nData as an interior node, find the sequence of child
** nodes which could include pTerm/nTerm/isPrefix.  Note that the
** interior node terms logically come between the blocks, so there is
** one more blockid than there are terms (that block contains terms >=
** the last interior-node term).
*/
/* TODO(shess) The calling code may already know that the end child is
** not worth calculating, because the end may be in a later sibling
** node.  Consider whether breaking symmetry is worthwhile.  I suspect
** it is not worthwhile.
*/
static void getChildrenContaining(const char *pData, int nData,
                                  const char *pTerm, int nTerm, int isPrefix,
                                  sqlite_int64 *piStartChild,
                                  sqlite_int64 *piEndChild){
  InteriorReader reader;

  assert( nData>1 );
  assert( *pData!='\0' );
  interiorReaderInit(pData, nData, &reader);

  /* Scan for the first child which could contain pTerm/nTerm. */
  while( !interiorReaderAtEnd(&reader) ){
    if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
    interiorReaderStep(&reader);
  }
  *piStartChild = interiorReaderCurrentBlockid(&reader);

  /* Keep scanning to find a term greater than our term, using prefix
  ** comparison if indicated.  If isPrefix is false, this will be the
  ** same blockid as the starting block.
  */
  while( !interiorReaderAtEnd(&reader) ){
    if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
    interiorReaderStep(&reader);
  }
  *piEndChild = interiorReaderCurrentBlockid(&reader);

  interiorReaderDestroy(&reader);

  /* Children must ascend, and if !prefix, both must be the same. */
  assert( *piEndChild>=*piStartChild );
  assert( isPrefix || *piStartChild==*piEndChild );
}

/* Read block at iBlockid and pass it with other params to
** getChildrenContaining().
*/
static int loadAndGetChildrenContaining(
  fulltext_vtab *v,
  sqlite_int64 iBlockid,
  const char *pTerm, int nTerm, int isPrefix,
  sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
){
  sqlite3_stmt *s = NULL;
  int rc;

  assert( iBlockid!=0 );
  assert( pTerm!=NULL );
  assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
  assert( piStartChild!=NULL );
  assert( piEndChild!=NULL );

  rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_ERROR;
  if( rc!=SQLITE_ROW ) return rc;

  getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
                        pTerm, nTerm, isPrefix, piStartChild, piEndChild);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain
   * locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;

  return SQLITE_OK;
}

/* Traverse the tree represented by pData[nData] looking for
** pTerm[nTerm], placing its doclist into *out.  This is internal to
** loadSegment() to make error-handling cleaner.
*/
static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
                          sqlite_int64 iLeavesEnd,
                          const char *pTerm, int nTerm, int isPrefix,
                          DataBuffer *out){
  /* Special case where root is a leaf. */
  if( *pData=='\0' ){
    return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
  }else{
    int rc;
    sqlite_int64 iStartChild, iEndChild;

    /* Process pData as an interior node, then loop down the tree
    ** until we find the set of leaf nodes to scan for the term.
    */
    getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
                          &iStartChild, &iEndChild);
    while( iStartChild>iLeavesEnd ){
      sqlite_int64 iNextStart, iNextEnd;
      rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
                                        &iNextStart, &iNextEnd);
      if( rc!=SQLITE_OK ) return rc;

      /* If we've branched, follow the end branch, too. */
      if( iStartChild!=iEndChild ){
        sqlite_int64 iDummy;
        rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
                                          &iDummy, &iNextEnd);
        if( rc!=SQLITE_OK ) return rc;
      }

      assert( iNextStart<=iNextEnd );
      iStartChild = iNextStart;
      iEndChild = iNextEnd;
    }
    assert( iStartChild<=iLeavesEnd );
    assert( iEndChild<=iLeavesEnd );

    /* Scan through the leaf segments for doclists. */
    return loadSegmentLeaves(v, iStartChild, iEndChild,
                             pTerm, nTerm, isPrefix, out);
  }
}

/* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
** merge its doclist over *out (any duplicate doclists read from the
** segment rooted at pData will overwrite those in *out).
*/
/* TODO(shess) Consider changing this to determine the depth of the
** leaves using either the first characters of interior nodes (when
** ==1, we're one level above the leaves), or the first character of
** the root (which will describe the height of the tree directly).
** Either feels somewhat tricky to me.
*/
/* TODO(shess) The current merge is likely to be slow for large
** doclists (though it should process from newest/smallest to
** oldest/largest, so it may not be that bad).  It might be useful to
** modify things to allow for N-way merging.  This could either be
** within a segment, with pairwise merges across segments, or across
** all segments at once.
*/
static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
                       sqlite_int64 iLeavesEnd,
                       const char *pTerm, int nTerm, int isPrefix,
                       DataBuffer *out){
  DataBuffer result;
  int rc;

  assert( nData>1 );

  /* This code should never be called with buffered updates. */
  assert( v->nPendingData<0 );

  dataBufferInit(&result, 0);
  rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
                      pTerm, nTerm, isPrefix, &result);
  if( rc==SQLITE_OK && result.nData>0 ){
    if( out->nData==0 ){
      DataBuffer tmp = *out;
      *out = result;
      result = tmp;
    }else{
      DataBuffer merged;
      DLReader readers[2];

      dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
      dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
      dataBufferInit(&merged, out->nData+result.nData);
      docListMerge(&merged, readers, 2);
      dataBufferDestroy(out);
      *out = merged;
      dlrDestroy(&readers[0]);
      dlrDestroy(&readers[1]);
    }
  }
  dataBufferDestroy(&result);
  return rc;
}

/* Scan the database and merge together the posting lists for the term
** into *out.
*/
static int termSelect(fulltext_vtab *v, int iColumn,
                      const char *pTerm, int nTerm, int isPrefix,
                      DocListType iType, DataBuffer *out){
  DataBuffer doclist;
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  /* This code should never be called with buffered updates. */
  assert( v->nPendingData<0 );

  dataBufferInit(&doclist, 0);

  /* Traverse the segments from oldest to newest so that newer doclist
  ** elements for given docids overwrite older elements.
  */
  while( (rc = sqlite3_step(s))==SQLITE_ROW ){
    const char *pData = sqlite3_column_blob(s, 2);
    const int nData = sqlite3_column_bytes(s, 2);
    const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
    rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
                     &doclist);
    if( rc!=SQLITE_OK ) goto err;
  }
  if( rc==SQLITE_DONE ){
    if( doclist.nData!=0 ){
      /* TODO(shess) The old term_select_all() code applied the column
      ** restrict as we merged segments, leading to smaller buffers.
      ** This is probably worthwhile to bring back, once the new storage
      ** system is checked in.
      */
      if( iColumn==v->nColumn) iColumn = -1;
      docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
                  iColumn, iType, out);
    }
    rc = SQLITE_OK;
  }

 err:
  dataBufferDestroy(&doclist);
  return rc;
}

/****************************************************************/
/* Used to hold hashtable data for sorting. */
typedef struct TermData {
  const char *pTerm;
  int nTerm;
  DLCollector *pCollector;
} TermData;

/* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
** for equal, >0 for greater-than).
*/
static int termDataCmp(const void *av, const void *bv){
  const TermData *a = (const TermData *)av;
  const TermData *b = (const TermData *)bv;
  int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
  int c = memcmp(a->pTerm, b->pTerm, n);
  if( c!=0 ) return c;
  return a->nTerm-b->nTerm;
}

/* Order pTerms data by term, then write a new level 0 segment using
** LeafWriter.
*/
static int writeZeroSegment(fulltext_vtab *v, fts2Hash *pTerms){
  fts2HashElem *e;
  int idx, rc, i, n;
  TermData *pData;
  LeafWriter writer;
  DataBuffer dl;

  /* Determine the next index at level 0, merging as necessary. */
  rc = segdirNextIndex(v, 0, &idx);
  if( rc!=SQLITE_OK ) return rc;

  n = fts2HashCount(pTerms);
  pData = sqlite3_malloc(n*sizeof(TermData));

  for(i = 0, e = fts2HashFirst(pTerms); e; i++, e = fts2HashNext(e)){
    assert( i<n );
    pData[i].pTerm = fts2HashKey(e);
    pData[i].nTerm = fts2HashKeysize(e);
    pData[i].pCollector = fts2HashData(e);
  }
  assert( i==n );

  /* TODO(shess) Should we allow user-defined collation sequences,
  ** here?  I think we only need that once we support prefix searches.
  */
  if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);

  /* TODO(shess) Refactor so that we can write directly to the segment
  ** DataBuffer, as happens for segment merges.
  */
  leafWriterInit(0, idx, &writer);
  dataBufferInit(&dl, 0);
  for(i=0; i<n; i++){
    dataBufferReset(&dl);
    dlcAddDoclist(pData[i].pCollector, &dl);
    rc = leafWriterStep(v, &writer,
                        pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
    if( rc!=SQLITE_OK ) goto err;
  }
  rc = leafWriterFinalize(v, &writer);

 err:
  dataBufferDestroy(&dl);
  sqlite3_free(pData);
  leafWriterDestroy(&writer);
  return rc;
}

/* If pendingTerms has data, free it. */
static int clearPendingTerms(fulltext_vtab *v){
  if( v->nPendingData>=0 ){
    fts2HashElem *e;
    for(e=fts2HashFirst(&v->pendingTerms); e; e=fts2HashNext(e)){
      dlcDelete(fts2HashData(e));
    }
    fts2HashClear(&v->pendingTerms);
    v->nPendingData = -1;
  }
  return SQLITE_OK;
}

/* If pendingTerms has data, flush it to a level-zero segment, and
** free it.
*/
static int flushPendingTerms(fulltext_vtab *v){
  if( v->nPendingData>=0 ){
    int rc = writeZeroSegment(v, &v->pendingTerms);
    if( rc==SQLITE_OK ) clearPendingTerms(v);
    return rc;
  }
  return SQLITE_OK;
}

/* If pendingTerms is "too big", or docid is out of order, flush it.
** Regardless, be certain that pendingTerms is initialized for use.
*/
static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  /* TODO(shess) Explore whether partially flushing the buffer on
  ** forced-flush would provide better performance.  I suspect that if
  ** we ordered the doclists by size and flushed the largest until the
  ** buffer was half empty, that would let the less frequent terms
  ** generate longer doclists.
  */
  if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
    int rc = flushPendingTerms(v);
    if( rc!=SQLITE_OK ) return rc;
  }
  if( v->nPendingData<0 ){
    fts2HashInit(&v->pendingTerms, FTS2_HASH_STRING, 1);
    v->nPendingData = 0;
  }
  v->iPrevDocid = iDocid;
  return SQLITE_OK;
}

/* This function implements the xUpdate callback; it is the top-level entry
 * point for inserting, deleting or updating a row in a full-text table. */
static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
                   sqlite_int64 *pRowid){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  int rc;

  TRACE(("FTS2 Update %p\n", pVtab));

  if( nArg<2 ){
    rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
    if( rc==SQLITE_OK ){
      /* If we just deleted the last row in the table, clear out the
      ** index data.
      */
      rc = content_exists(v);
      if( rc==SQLITE_ROW ){
        rc = SQLITE_OK;
      }else if( rc==SQLITE_DONE ){
        /* Clear the pending terms so we don't flush a useless level-0
        ** segment when the transaction closes.
        */
        rc = clearPendingTerms(v);
        if( rc==SQLITE_OK ){
          rc = segdir_delete_all(v);
        }
      }
    }
  } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
    /* An update:
     * ppArg[0] = old rowid
     * ppArg[1] = new rowid
     * ppArg[2..2+v->nColumn-1] = values
     * ppArg[2+v->nColumn] = value for magic column (we ignore this)
     */
    sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
    if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
      sqlite3_value_int64(ppArg[1]) != rowid ){
      rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
    } else {
      assert( nArg==2+v->nColumn+1);
      rc = index_update(v, rowid, &ppArg[2]);
    }
  } else {
    /* An insert:
     * ppArg[1] = requested rowid
     * ppArg[2..2+v->nColumn-1] = values
     * ppArg[2+v->nColumn] = value for magic column (we ignore this)
     */
    assert( nArg==2+v->nColumn+1);
    rc = index_insert(v, ppArg[1], &ppArg[2], pRowid);
  }

  return rc;
}

static int fulltextSync(sqlite3_vtab *pVtab){
  TRACE(("FTS2 xSync()\n"));
  return flushPendingTerms((fulltext_vtab *)pVtab);
}

static int fulltextBegin(sqlite3_vtab *pVtab){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  TRACE(("FTS2 xBegin()\n"));

  /* Any buffered updates should have been cleared by the previous
  ** transaction.
  */
  assert( v->nPendingData<0 );
  return clearPendingTerms(v);
}

static int fulltextCommit(sqlite3_vtab *pVtab){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  TRACE(("FTS2 xCommit()\n"));

  /* Buffered updates should have been cleared by fulltextSync(). */
  assert( v->nPendingData<0 );
  return clearPendingTerms(v);
}

static int fulltextRollback(sqlite3_vtab *pVtab){
  TRACE(("FTS2 xRollback()\n"));
  return clearPendingTerms((fulltext_vtab *)pVtab);
}

/*
** Implementation of the snippet() function for FTS2
*/
static void snippetFunc(
  sqlite3_context *pContext,
  int argc,
  sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc<1 ) return;
  if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
      sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
  }else{
    const char *zStart = "<b>";
    const char *zEnd = "</b>";
    const char *zEllipsis = "<b>...</b>";
    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    if( argc>=2 ){
      zStart = (const char*)sqlite3_value_text(argv[1]);
      if( argc>=3 ){
        zEnd = (const char*)sqlite3_value_text(argv[2]);
        if( argc>=4 ){
          zEllipsis = (const char*)sqlite3_value_text(argv[3]);
        }
      }
    }
    snippetAllOffsets(pCursor);
    snippetText(pCursor, zStart, zEnd, zEllipsis);
    sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
                        pCursor->snippet.nSnippet, SQLITE_STATIC);
  }
}

/*
** Implementation of the offsets() function for FTS2
*/
static void snippetOffsetsFunc(
  sqlite3_context *pContext,
  int argc,
  sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc<1 ) return;
  if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
      sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
  }else{
    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    snippetAllOffsets(pCursor);
    snippetOffsetText(&pCursor->snippet);
    sqlite3_result_text(pContext,
                        pCursor->snippet.zOffset, pCursor->snippet.nOffset,
                        SQLITE_STATIC);
  }
}

/* OptLeavesReader is nearly identical to LeavesReader, except that
** where LeavesReader is geared towards the merging of complete
** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
** is geared towards implementation of the optimize() function, and
** can merge all segments simultaneously.  This version may be
** somewhat less efficient than LeavesReader because it merges into an
** accumulator rather than doing an N-way merge, but since segment
** size grows exponentially (so segment count logrithmically) this is
** probably not an immediate problem.
*/
/* TODO(shess): Prove that assertion, or extend the merge code to
** merge tree fashion (like the prefix-searching code does).
*/
/* TODO(shess): OptLeavesReader and LeavesReader could probably be
** merged with little or no loss of performance for LeavesReader.  The
** merged code would need to handle >MERGE_COUNT segments, and would
** also need to be able to optionally optimize away deletes.
*/
typedef struct OptLeavesReader {
  /* Segment number, to order readers by age. */
  int segment;
  LeavesReader reader;
} OptLeavesReader;

static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
  return leavesReaderAtEnd(&pReader->reader);
}
static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
  return leavesReaderTermBytes(&pReader->reader);
}
static const char *optLeavesReaderData(OptLeavesReader *pReader){
  return leavesReaderData(&pReader->reader);
}
static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
  return leavesReaderDataBytes(&pReader->reader);
}
static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
  return leavesReaderTerm(&pReader->reader);
}
static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
  return leavesReaderStep(v, &pReader->reader);
}
static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
}
/* Order by term ascending, segment ascending (oldest to newest), with
** exhausted readers to the end.
*/
static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  int c = optLeavesReaderTermCmp(lr1, lr2);
  if( c!=0 ) return c;
  return lr1->segment-lr2->segment;
}
/* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
** pLr[1..nLr-1] is already sorted.
*/
static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
  while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
    OptLeavesReader tmp = pLr[0];
    pLr[0] = pLr[1];
    pLr[1] = tmp;
    nLr--;
    pLr++;
  }
}

/* optimize() helper function.  Put the readers in order and iterate
** through them, merging doclists for matching terms into pWriter.
** Returns SQLITE_OK on success, or the SQLite error code which
** prevented success.
*/
static int optimizeInternal(fulltext_vtab *v,
                            OptLeavesReader *readers, int nReaders,
                            LeafWriter *pWriter){
  int i, rc = SQLITE_OK;
  DataBuffer doclist, merged, tmp;

  /* Order the readers. */
  i = nReaders;
  while( i-- > 0 ){
    optLeavesReaderReorder(&readers[i], nReaders-i);
  }

  dataBufferInit(&doclist, LEAF_MAX);
  dataBufferInit(&merged, LEAF_MAX);

  /* Exhausted readers bubble to the end, so when the first reader is
  ** at eof, all are at eof.
  */
  while( !optLeavesReaderAtEnd(&readers[0]) ){

    /* Figure out how many readers share the next term. */
    for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
      if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
    }

    /* Special-case for no merge. */
    if( i==1 ){
      /* Trim deletions from the doclist. */
      dataBufferReset(&merged);
      docListTrim(DL_DEFAULT,
                  optLeavesReaderData(&readers[0]),
                  optLeavesReaderDataBytes(&readers[0]),
                  -1, DL_DEFAULT, &merged);
    }else{
      DLReader dlReaders[MERGE_COUNT];
      int iReader, nReaders;

      /* Prime the pipeline with the first reader's doclist.  After
      ** one pass index 0 will reference the accumulated doclist.
      */
      dlrInit(&dlReaders[0], DL_DEFAULT,
              optLeavesReaderData(&readers[0]),
              optLeavesReaderDataBytes(&readers[0]));
      iReader = 1;

      assert( iReader<i );  /* Must execute the loop at least once. */
      while( iReader<i ){
        /* Merge 16 inputs per pass. */
        for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
             iReader++, nReaders++ ){
          dlrInit(&dlReaders[nReaders], DL_DEFAULT,
                  optLeavesReaderData(&readers[iReader]),
                  optLeavesReaderDataBytes(&readers[iReader]));
        }

        /* Merge doclists and swap result into accumulator. */
        dataBufferReset(&merged);
        docListMerge(&merged, dlReaders, nReaders);
        tmp = merged;
        merged = doclist;
        doclist = tmp;

        while( nReaders-- > 0 ){
          dlrDestroy(&dlReaders[nReaders]);
        }

        /* Accumulated doclist to reader 0 for next pass. */
        dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
      }

      /* Destroy reader that was left in the pipeline. */
      dlrDestroy(&dlReaders[0]);

      /* Trim deletions from the doclist. */
      dataBufferReset(&merged);
      docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
                  -1, DL_DEFAULT, &merged);
    }

    /* Only pass doclists with hits (skip if all hits deleted). */
    if( merged.nData>0 ){
      rc = leafWriterStep(v, pWriter,
                          optLeavesReaderTerm(&readers[0]),
                          optLeavesReaderTermBytes(&readers[0]),
                          merged.pData, merged.nData);
      if( rc!=SQLITE_OK ) goto err;
    }

    /* Step merged readers to next term and reorder. */
    while( i-- > 0 ){
      rc = optLeavesReaderStep(v, &readers[i]);
      if( rc!=SQLITE_OK ) goto err;

      optLeavesReaderReorder(&readers[i], nReaders-i);
    }
  }

 err:
  dataBufferDestroy(&doclist);
  dataBufferDestroy(&merged);
  return rc;
}

/* Implement optimize() function for FTS3.  optimize(t) merges all
** segments in the fts index into a single segment.  't' is the magic
** table-named column.
*/
static void optimizeFunc(sqlite3_context *pContext,
                         int argc, sqlite3_value **argv){
  fulltext_cursor *pCursor;
  if( argc>1 ){
    sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
  }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
            sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
  }else{
    fulltext_vtab *v;
    int i, rc, iMaxLevel;
    OptLeavesReader *readers;
    int nReaders;
    LeafWriter writer;
    sqlite3_stmt *s;

    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    v = cursor_vtab(pCursor);

    /* Flush any buffered updates before optimizing. */
    rc = flushPendingTerms(v);
    if( rc!=SQLITE_OK ) goto err;

    rc = segdir_count(v, &nReaders, &iMaxLevel);
    if( rc!=SQLITE_OK ) goto err;
    if( nReaders==0 || nReaders==1 ){
      sqlite3_result_text(pContext, "Index already optimal", -1,
                          SQLITE_STATIC);
      return;
    }

    rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
    if( rc!=SQLITE_OK ) goto err;

    readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
    if( readers==NULL ) goto err;

    /* Note that there will already be a segment at this position
    ** until we call segdir_delete() on iMaxLevel.
    */
    leafWriterInit(iMaxLevel, 0, &writer);

    i = 0;
    while( (rc = sqlite3_step(s))==SQLITE_ROW ){
      sqlite_int64 iStart = sqlite3_column_int64(s, 0);
      sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
      const char *pRootData = sqlite3_column_blob(s, 2);
      int nRootData = sqlite3_column_bytes(s, 2);

      assert( i<nReaders );
      rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
                            &readers[i].reader);
      if( rc!=SQLITE_OK ) break;

      readers[i].segment = i;
      i++;
    }

    /* If we managed to successfully read them all, optimize them. */
    if( rc==SQLITE_DONE ){
      assert( i==nReaders );
      rc = optimizeInternal(v, readers, nReaders, &writer);
    }

    while( i-- > 0 ){
      leavesReaderDestroy(&readers[i].reader);
    }
    sqlite3_free(readers);

    /* If we've successfully gotten to here, delete the old segments
    ** and flush the interior structure of the new segment.
    */
    if( rc==SQLITE_OK ){
      for( i=0; i<=iMaxLevel; i++ ){
        rc = segdir_delete(v, i);
        if( rc!=SQLITE_OK ) break;
      }

      if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
    }

    leafWriterDestroy(&writer);

    if( rc!=SQLITE_OK ) goto err;

    sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
    return;

    /* TODO(shess): Error-handling needs to be improved along the
    ** lines of the dump_ functions.
    */
 err:
    {
      char buf[512];
      sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
                       sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
      sqlite3_result_error(pContext, buf, -1);
    }
  }
}

#ifdef SQLITE_TEST
/* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
** pull the error from the context's db handle.
*/
static void generateError(sqlite3_context *pContext,
                          const char *prefix, const char *msg){
  char buf[512];
  if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
  sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
  sqlite3_result_error(pContext, buf, -1);
}

/* Helper function to collect the set of terms in the segment into
** pTerms.  The segment is defined by the leaf nodes between
** iStartBlockid and iEndBlockid, inclusive, or by the contents of
** pRootData if iStartBlockid is 0 (in which case the entire segment
** fit in a leaf).
*/
static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
                               fts2Hash *pTerms){
  const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
  const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
  const char *pRootData = sqlite3_column_blob(s, 2);
  const int nRootData = sqlite3_column_bytes(s, 2);
  LeavesReader reader;
  int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
                            pRootData, nRootData, &reader);
  if( rc!=SQLITE_OK ) return rc;

  while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
    const char *pTerm = leavesReaderTerm(&reader);
    const int nTerm = leavesReaderTermBytes(&reader);
    void *oldValue = sqlite3Fts2HashFind(pTerms, pTerm, nTerm);
    void *newValue = (void *)((char *)oldValue+1);

    /* From the comment before sqlite3Fts2HashInsert in fts2_hash.c,
    ** the data value passed is returned in case of malloc failure.
    */
    if( newValue==sqlite3Fts2HashInsert(pTerms, pTerm, nTerm, newValue) ){
      rc = SQLITE_NOMEM;
    }else{
      rc = leavesReaderStep(v, &reader);
    }
  }

  leavesReaderDestroy(&reader);
  return rc;
}

/* Helper function to build the result string for dump_terms(). */
static int generateTermsResult(sqlite3_context *pContext, fts2Hash *pTerms){
  int iTerm, nTerms, nResultBytes, iByte;
  char *result;
  TermData *pData;
  fts2HashElem *e;

  /* Iterate pTerms to generate an array of terms in pData for
  ** sorting.
  */
  nTerms = fts2HashCount(pTerms);
  assert( nTerms>0 );
  pData = sqlite3_malloc(nTerms*sizeof(TermData));
  if( pData==NULL ) return SQLITE_NOMEM;

  nResultBytes = 0;
  for(iTerm = 0, e = fts2HashFirst(pTerms); e; iTerm++, e = fts2HashNext(e)){
    nResultBytes += fts2HashKeysize(e)+1;   /* Term plus trailing space */
    assert( iTerm<nTerms );
    pData[iTerm].pTerm = fts2HashKey(e);
    pData[iTerm].nTerm = fts2HashKeysize(e);
    pData[iTerm].pCollector = fts2HashData(e);  /* unused */
  }
  assert( iTerm==nTerms );

  assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
  result = sqlite3_malloc(nResultBytes);
  if( result==NULL ){
    sqlite3_free(pData);
    return SQLITE_NOMEM;
  }

  if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);

  /* Read the terms in order to build the result. */
  iByte = 0;
  for(iTerm=0; iTerm<nTerms; ++iTerm){
    memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
    iByte += pData[iTerm].nTerm;
    result[iByte++] = ' ';
  }
  assert( iByte==nResultBytes );
  assert( result[nResultBytes-1]==' ' );
  result[nResultBytes-1] = '\0';

  /* Passes away ownership of result. */
  sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
  sqlite3_free(pData);
  return SQLITE_OK;
}

/* Implements dump_terms() for use in inspecting the fts2 index from
** tests.  TEXT result containing the ordered list of terms joined by
** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
** specified by level, idx (in %_segdir), while dump_terms(t) dumps
** all terms in the index.  In both cases t is the fts table's magic
** table-named column.
*/
static void dumpTermsFunc(
  sqlite3_context *pContext,
  int argc, sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc!=3 && argc!=1 ){
    generateError(pContext, "dump_terms", "incorrect arguments");
  }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
            sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    generateError(pContext, "dump_terms", "illegal first argument");
  }else{
    fulltext_vtab *v;
    fts2Hash terms;
    sqlite3_stmt *s = NULL;
    int rc;

    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    v = cursor_vtab(pCursor);

    /* If passed only the cursor column, get all segments.  Otherwise
    ** get the segment described by the following two arguments.
    */
    if( argc==1 ){
      rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
    }else{
      rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
      if( rc==SQLITE_OK ){
        rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
        if( rc==SQLITE_OK ){
          rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
        }
      }
    }

    if( rc!=SQLITE_OK ){
      generateError(pContext, "dump_terms", NULL);
      return;
    }

    /* Collect the terms for each segment. */
    sqlite3Fts2HashInit(&terms, FTS2_HASH_STRING, 1);
    while( (rc = sqlite3_step(s))==SQLITE_ROW ){
      rc = collectSegmentTerms(v, s, &terms);
      if( rc!=SQLITE_OK ) break;
    }

    if( rc!=SQLITE_DONE ){
      sqlite3_reset(s);
      generateError(pContext, "dump_terms", NULL);
    }else{
      const int nTerms = fts2HashCount(&terms);
      if( nTerms>0 ){
        rc = generateTermsResult(pContext, &terms);
        if( rc==SQLITE_NOMEM ){
          generateError(pContext, "dump_terms", "out of memory");
        }else{
          assert( rc==SQLITE_OK );
        }
      }else if( argc==3 ){
        /* The specific segment asked for could not be found. */
        generateError(pContext, "dump_terms", "segment not found");
      }else{
        /* No segments found. */
        /* TODO(shess): It should be impossible to reach this.  This
        ** case can only happen for an empty table, in which case
        ** SQLite has no rows to call this function on.
        */
        sqlite3_result_null(pContext);
      }
    }
    sqlite3Fts2HashClear(&terms);
  }
}

/* Expand the DL_DEFAULT doclist in pData into a text result in
** pContext.
*/
static void createDoclistResult(sqlite3_context *pContext,
                                const char *pData, int nData){
  DataBuffer dump;
  DLReader dlReader;

  assert( pData!=NULL && nData>0 );

  dataBufferInit(&dump, 0);
  dlrInit(&dlReader, DL_DEFAULT, pData, nData);
  for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
    char buf[256];
    PLReader plReader;

    plrInit(&plReader, &dlReader);
    if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
      sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
      dataBufferAppend(&dump, buf, strlen(buf));
    }else{
      int iColumn = plrColumn(&plReader);

      sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
                       dlrDocid(&dlReader), iColumn);
      dataBufferAppend(&dump, buf, strlen(buf));

      for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
        if( plrColumn(&plReader)!=iColumn ){
          iColumn = plrColumn(&plReader);
          sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
          assert( dump.nData>0 );
          dump.nData--;                     /* Overwrite trailing space. */
          assert( dump.pData[dump.nData]==' ');
          dataBufferAppend(&dump, buf, strlen(buf));
        }
        if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
          sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
                           plrPosition(&plReader),
                           plrStartOffset(&plReader), plrEndOffset(&plReader));
        }else if( DL_DEFAULT==DL_POSITIONS ){
          sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
        }else{
          assert( NULL=="Unhandled DL_DEFAULT value");
        }
        dataBufferAppend(&dump, buf, strlen(buf));
      }
      plrDestroy(&plReader);

      assert( dump.nData>0 );
      dump.nData--;                     /* Overwrite trailing space. */
      assert( dump.pData[dump.nData]==' ');
      dataBufferAppend(&dump, "]] ", 3);
    }
  }
  dlrDestroy(&dlReader);

  assert( dump.nData>0 );
  dump.nData--;                     /* Overwrite trailing space. */
  assert( dump.pData[dump.nData]==' ');
  dump.pData[dump.nData] = '\0';
  assert( dump.nData>0 );

  /* Passes ownership of dump's buffer to pContext. */
  sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
  dump.pData = NULL;
  dump.nData = dump.nCapacity = 0;
}

/* Implements dump_doclist() for use in inspecting the fts2 index from
** tests.  TEXT result containing a string representation of the
** doclist for the indicated term.  dump_doclist(t, term, level, idx)
** dumps the doclist for term from the segment specified by level, idx
** (in %_segdir), while dump_doclist(t, term) dumps the logical
** doclist for the term across all segments.  The per-segment doclist
** can contain deletions, while the full-index doclist will not
** (deletions are omitted).
**
** Result formats differ with the setting of DL_DEFAULTS.  Examples:
**
** DL_DOCIDS: [1] [3] [7]
** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
**
** In each case the number after the outer '[' is the docid.  In the
** latter two cases, the number before the inner '[' is the column
** associated with the values within.  For DL_POSITIONS the numbers
** within are the positions, for DL_POSITIONS_OFFSETS they are the
** position, the start offset, and the end offset.
*/
static void dumpDoclistFunc(
  sqlite3_context *pContext,
  int argc, sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc!=2 && argc!=4 ){
    generateError(pContext, "dump_doclist", "incorrect arguments");
  }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
            sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    generateError(pContext, "dump_doclist", "illegal first argument");
  }else if( sqlite3_value_text(argv[1])==NULL ||
            sqlite3_value_text(argv[1])[0]=='\0' ){
    generateError(pContext, "dump_doclist", "empty second argument");
  }else{
    const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
    const int nTerm = strlen(pTerm);
    fulltext_vtab *v;
    int rc;
    DataBuffer doclist;

    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    v = cursor_vtab(pCursor);

    dataBufferInit(&doclist, 0);

    /* termSelect() yields the same logical doclist that queries are
    ** run against.
    */
    if( argc==2 ){
      rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
    }else{
      sqlite3_stmt *s = NULL;

      /* Get our specific segment's information. */
      rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
      if( rc==SQLITE_OK ){
        rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
        if( rc==SQLITE_OK ){
          rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
        }
      }

      if( rc==SQLITE_OK ){
        rc = sqlite3_step(s);

        if( rc==SQLITE_DONE ){
          dataBufferDestroy(&doclist);
          generateError(pContext, "dump_doclist", "segment not found");
          return;
        }

        /* Found a segment, load it into doclist. */
        if( rc==SQLITE_ROW ){
          const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
          const char *pData = sqlite3_column_blob(s, 2);
          const int nData = sqlite3_column_bytes(s, 2);

          /* loadSegment() is used by termSelect() to load each
          ** segment's data.
          */
          rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
                           &doclist);
          if( rc==SQLITE_OK ){
            rc = sqlite3_step(s);

            /* Should not have more than one matching segment. */
            if( rc!=SQLITE_DONE ){
              sqlite3_reset(s);
              dataBufferDestroy(&doclist);
              generateError(pContext, "dump_doclist", "invalid segdir");
              return;
            }
            rc = SQLITE_OK;
          }
        }
      }

      sqlite3_reset(s);
    }

    if( rc==SQLITE_OK ){
      if( doclist.nData>0 ){
        createDoclistResult(pContext, doclist.pData, doclist.nData);
      }else{
        /* TODO(shess): This can happen if the term is not present, or
        ** if all instances of the term have been deleted and this is
        ** an all-index dump.  It may be interesting to distinguish
        ** these cases.
        */
        sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
      }
    }else if( rc==SQLITE_NOMEM ){
      /* Handle out-of-memory cases specially because if they are
      ** generated in fts2 code they may not be reflected in the db
      ** handle.
      */
      /* TODO(shess): Handle this more comprehensively.
      ** sqlite3ErrStr() has what I need, but is internal.
      */
      generateError(pContext, "dump_doclist", "out of memory");
    }else{
      generateError(pContext, "dump_doclist", NULL);
    }

    dataBufferDestroy(&doclist);
  }
}
#endif

/*
** This routine implements the xFindFunction method for the FTS2
** virtual table.
*/
static int fulltextFindFunction(
  sqlite3_vtab *pVtab,
  int nArg,
  const char *zName,
  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  void **ppArg
){
  if( strcmp(zName,"snippet")==0 ){
    *pxFunc = snippetFunc;
    return 1;
  }else if( strcmp(zName,"offsets")==0 ){
    *pxFunc = snippetOffsetsFunc;
    return 1;
  }else if( strcmp(zName,"optimize")==0 ){
    *pxFunc = optimizeFunc;
    return 1;
#ifdef SQLITE_TEST
    /* NOTE(shess): These functions are present only for testing
    ** purposes.  No particular effort is made to optimize their
    ** execution or how they build their results.
    */
  }else if( strcmp(zName,"dump_terms")==0 ){
    /* fprintf(stderr, "Found dump_terms\n"); */
    *pxFunc = dumpTermsFunc;
    return 1;
  }else if( strcmp(zName,"dump_doclist")==0 ){
    /* fprintf(stderr, "Found dump_doclist\n"); */
    *pxFunc = dumpDoclistFunc;
    return 1;
#endif
  }
  return 0;
}

/*
** Rename an fts2 table.
*/
static int fulltextRename(
  sqlite3_vtab *pVtab,
  const char *zName
){
  fulltext_vtab *p = (fulltext_vtab *)pVtab;
  int rc = SQLITE_NOMEM;
  char *zSql = sqlite3_mprintf(
    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
    , p->zDb, p->zName, zName 
    , p->zDb, p->zName, zName 
    , p->zDb, p->zName, zName
  );
  if( zSql ){
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  return rc;
}

static const sqlite3_module fts2Module = {
  /* iVersion      */ 0,
  /* xCreate       */ fulltextCreate,
  /* xConnect      */ fulltextConnect,
  /* xBestIndex    */ fulltextBestIndex,
  /* xDisconnect   */ fulltextDisconnect,
  /* xDestroy      */ fulltextDestroy,
  /* xOpen         */ fulltextOpen,
  /* xClose        */ fulltextClose,
  /* xFilter       */ fulltextFilter,
  /* xNext         */ fulltextNext,
  /* xEof          */ fulltextEof,
  /* xColumn       */ fulltextColumn,
  /* xRowid        */ fulltextRowid,
  /* xUpdate       */ fulltextUpdate,
  /* xBegin        */ fulltextBegin,
  /* xSync         */ fulltextSync,
  /* xCommit       */ fulltextCommit,
  /* xRollback     */ fulltextRollback,
  /* xFindFunction */ fulltextFindFunction,
  /* xRename */       fulltextRename,
};

static void hashDestroy(void *p){
  fts2Hash *pHash = (fts2Hash *)p;
  sqlite3Fts2HashClear(pHash);
  sqlite3_free(pHash);
}

/*
** The fts2 built-in tokenizers - "simple" and "porter" - are implemented
** in files fts2_tokenizer1.c and fts2_porter.c respectively. The following
** two forward declarations are for functions declared in these files
** used to retrieve the respective implementations.
**
** Calling sqlite3Fts2SimpleTokenizerModule() sets the value pointed
** to by the argument to point a the "simple" tokenizer implementation.
** Function ...PorterTokenizerModule() sets *pModule to point to the
** porter tokenizer/stemmer implementation.
*/
void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);

int sqlite3Fts2InitHashTable(sqlite3 *, fts2Hash *, const char *);

/*
** Initialise the fts2 extension. If this extension is built as part
** of the sqlite library, then this function is called directly by
** SQLite. If fts2 is built as a dynamically loadable extension, this
** function is called by the sqlite3_extension_init() entry point.
*/
int sqlite3Fts2Init(sqlite3 *db){
  int rc = SQLITE_OK;
  fts2Hash *pHash = 0;
  const sqlite3_tokenizer_module *pSimple = 0;
  const sqlite3_tokenizer_module *pPorter = 0;
  const sqlite3_tokenizer_module *pIcu = 0;

  sqlite3Fts2SimpleTokenizerModule(&pSimple);
  sqlite3Fts2PorterTokenizerModule(&pPorter);
#ifdef SQLITE_ENABLE_ICU
  sqlite3Fts2IcuTokenizerModule(&pIcu);
#endif

  /* Allocate and initialise the hash-table used to store tokenizers. */
  pHash = sqlite3_malloc(sizeof(fts2Hash));
  if( !pHash ){
    rc = SQLITE_NOMEM;
  }else{
    sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1);
  }

  /* Load the built-in tokenizers into the hash table */
  if( rc==SQLITE_OK ){
    if( sqlite3Fts2HashInsert(pHash, "simple", 7, (void *)pSimple)
     || sqlite3Fts2HashInsert(pHash, "porter", 7, (void *)pPorter) 
     || (pIcu && sqlite3Fts2HashInsert(pHash, "icu", 4, (void *)pIcu))
    ){
      rc = SQLITE_NOMEM;
    }
  }

  /* Create the virtual table wrapper around the hash-table and overload 
  ** the two scalar functions. If this is successful, register the
  ** module with sqlite.
  */
  if( SQLITE_OK==rc 
   && SQLITE_OK==(rc = sqlite3Fts2InitHashTable(db, pHash, "fts2_tokenizer"))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
#ifdef SQLITE_TEST
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
#endif
  ){
    return sqlite3_create_module_v2(
        db, "fts2", &fts2Module, (void *)pHash, hashDestroy
    );
  }

  /* An error has occurred. Delete the hash table and return the error code. */
  assert( rc!=SQLITE_OK );
  if( pHash ){
    sqlite3Fts2HashClear(pHash);
    sqlite3_free(pHash);
  }
  return rc;
}

#if !SQLITE_CORE
int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi)
  return sqlite3Fts2Init(db);
}
#endif

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */

Added ext/fts2/fts2.h.





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file is used by programs that want to link against the
** FTS2 library.  All it does is declare the sqlite3Fts2Init() interface.
*/
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

int sqlite3Fts2Init(sqlite3 *db);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */

Added ext/fts2/fts2_hash.c.













































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables used in SQLite.
** We've modified it slightly to serve as a standalone hash table
** implementation for the full-text indexing module.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "sqlite3.h"
#include "fts2_hash.h"

/*
** Malloc and Free functions
*/
static void *fts2HashMalloc(int n){
  void *p = sqlite3_malloc(n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}
static void fts2HashFree(void *p){
  sqlite3_free(p);
}

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
** keyClass is one of the constants 
** FTS2_HASH_BINARY or FTS2_HASH_STRING.  The value of keyClass 
** determines what kind of key the hash table will use.  "copyKey" is
** true if the hash table should make its own private copy of keys and
** false if it should just use the supplied pointer.
*/
void sqlite3Fts2HashInit(fts2Hash *pNew, int keyClass, int copyKey){
  assert( pNew!=0 );
  assert( keyClass>=FTS2_HASH_STRING && keyClass<=FTS2_HASH_BINARY );
  pNew->keyClass = keyClass;
  pNew->copyKey = copyKey;
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite3Fts2HashClear(fts2Hash *pH){
  fts2HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  fts2HashFree(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    fts2HashElem *next_elem = elem->next;
    if( pH->copyKey && elem->pKey ){
      fts2HashFree(elem->pKey);
    }
    fts2HashFree(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** Hash and comparison functions when the mode is FTS2_HASH_STRING
*/
static int strHash(const void *pKey, int nKey){
  const char *z = (const char *)pKey;
  int h = 0;
  if( nKey<=0 ) nKey = (int) strlen(z);
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ *z++;
    nKey--;
  }
  return h & 0x7fffffff;
}
static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
}

/*
** Hash and comparison functions when the mode is FTS2_HASH_BINARY
*/
static int binHash(const void *pKey, int nKey){
  int h = 0;
  const char *z = (const char *)pKey;
  while( nKey-- > 0 ){
    h = (h<<3) ^ h ^ *(z++);
  }
  return h & 0x7fffffff;
}
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return memcmp(pKey1,pKey2,n1);
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** The C syntax in this function definition may be unfamilar to some 
** programmers, so we provide the following additional explanation:
**
** The name of the function is "hashFunction".  The function takes a
** single parameter "keyClass".  The return value of hashFunction()
** is a pointer to another function.  Specifically, the return value
** of hashFunction() is a pointer to a function that takes two parameters
** with types "const void*" and "int" and returns an "int".
*/
static int (*hashFunction(int keyClass))(const void*,int){
  if( keyClass==FTS2_HASH_STRING ){
    return &strHash;
  }else{
    assert( keyClass==FTS2_HASH_BINARY );
    return &binHash;
  }
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** For help in interpreted the obscure C code in the function definition,
** see the header comment on the previous function.
*/
static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
  if( keyClass==FTS2_HASH_STRING ){
    return &strCompare;
  }else{
    assert( keyClass==FTS2_HASH_BINARY );
    return &binCompare;
  }
}

/* Link an element into the hash table
*/
static void insertElement(
  fts2Hash *pH,            /* The complete hash table */
  struct _fts2ht *pEntry,  /* The entry into which pNew is inserted */
  fts2HashElem *pNew       /* The element to be inserted */
){
  fts2HashElem *pHead;     /* First element already in pEntry */
  pHead = pEntry->chain;
  if( pHead ){
    pNew->next = pHead;
    pNew->prev = pHead->prev;
    if( pHead->prev ){ pHead->prev->next = pNew; }
    else             { pH->first = pNew; }
    pHead->prev = pNew;
  }else{
    pNew->next = pH->first;
    if( pH->first ){ pH->first->prev = pNew; }
    pNew->prev = 0;
    pH->first = pNew;
  }
  pEntry->count++;
  pEntry->chain = pNew;
}


/* Resize the hash table so that it cantains "new_size" buckets.
** "new_size" must be a power of 2.  The hash table might fail 
** to resize if sqliteMalloc() fails.
*/
static void rehash(fts2Hash *pH, int new_size){
  struct _fts2ht *new_ht;          /* The new hash table */
  fts2HashElem *elem, *next_elem;  /* For looping over existing elements */
  int (*xHash)(const void*,int);   /* The hash function */

  assert( (new_size & (new_size-1))==0 );
  new_ht = (struct _fts2ht *)fts2HashMalloc( new_size*sizeof(struct _fts2ht) );
  if( new_ht==0 ) return;
  fts2HashFree(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size;
  xHash = hashFunction(pH->keyClass);
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
}

/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static fts2HashElem *findElementGivenHash(
  const fts2Hash *pH, /* The pH to be searched */
  const void *pKey,   /* The key we are searching for */
  int nKey,
  int h               /* The hash for this key. */
){
  fts2HashElem *elem;            /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */
  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */

  if( pH->ht ){
    struct _fts2ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
    xCompare = compareFunction(pH->keyClass);
    while( count-- && elem ){
      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
        return elem;
      }
      elem = elem->next;
    }
  }
  return 0;
}

/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
  fts2Hash *pH,         /* The pH containing "elem" */
  fts2HashElem* elem,   /* The element to be removed from the pH */
  int h                 /* Hash value for the element */
){
  struct _fts2ht *pEntry;
  if( elem->prev ){
    elem->prev->next = elem->next; 
  }else{
    pH->first = elem->next;
  }
  if( elem->next ){
    elem->next->prev = elem->prev;
  }
  pEntry = &pH->ht[h];
  if( pEntry->chain==elem ){
    pEntry->chain = elem->next;
  }
  pEntry->count--;
  if( pEntry->count<=0 ){
    pEntry->chain = 0;
  }
  if( pH->copyKey && elem->pKey ){
    fts2HashFree(elem->pKey);
  }
  fts2HashFree( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    fts2HashClear(pH);
  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
void *sqlite3Fts2HashFind(const fts2Hash *pH, const void *pKey, int nKey){
  int h;                 /* A hash on key */
  fts2HashElem *elem;    /* The element that matches key */
  int (*xHash)(const void*,int);  /* The hash function */

  if( pH==0 || pH->ht==0 ) return 0;
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  h = (*xHash)(pKey,nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
  return elem ? elem->data : 0;
}

/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *sqlite3Fts2HashInsert(
  fts2Hash *pH,        /* The hash table to insert into */
  const void *pKey,    /* The key */
  int nKey,            /* Number of bytes in the key */
  void *data           /* The data */
){
  int hraw;                 /* Raw hash value of the key */
  int h;                    /* the hash of the key modulo hash table size */
  fts2HashElem *elem;       /* Used to loop thru the element list */
  fts2HashElem *new_elem;   /* New element added to the pH */
  int (*xHash)(const void*,int);  /* The hash function */

  assert( pH!=0 );
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  hraw = (*xHash)(pKey, nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (fts2HashElem*)fts2HashMalloc( sizeof(fts2HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = fts2HashMalloc( nKey );
    if( new_elem->pKey==0 ){
      fts2HashFree(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->htsize==0 ){
    rehash(pH,8);
    if( pH->htsize==0 ){
      pH->count = 0;
      fts2HashFree(new_elem);
      return data;
    }
  }
  if( pH->count > pH->htsize ){
    rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  insertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */

Added ext/fts2/fts2_hash.h.





























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in SQLite.  We've modified it slightly to serve as a standalone
** hash table implementation for the full-text indexing module.
**
*/
#ifndef _FTS2_HASH_H_
#define _FTS2_HASH_H_

/* Forward declarations of structures. */
typedef struct fts2Hash fts2Hash;
typedef struct fts2HashElem fts2HashElem;

/* A complete hash table is an instance of the following structure.
** The internals of this structure are intended to be opaque -- client
** code should not attempt to access or modify the fields of this structure
** directly.  Change this structure only by using the routines below.
** However, many of the "procedures" and "functions" for modifying and
** accessing this structure are really macros, so we can't really make
** this structure opaque.
*/
struct fts2Hash {
  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
  char copyKey;           /* True if copy of key made on insert */
  int count;              /* Number of entries in this table */
  fts2HashElem *first;    /* The first element of the array */
  int htsize;             /* Number of buckets in the hash table */
  struct _fts2ht {        /* the hash table */
    int count;               /* Number of entries with this hash */
    fts2HashElem *chain;     /* Pointer to first entry with this hash */
  } *ht;
};

/* Each element in the hash table is an instance of the following 
** structure.  All elements are stored on a single doubly-linked list.
**
** Again, this structure is intended to be opaque, but it can't really
** be opaque because it is used by macros.
*/
struct fts2HashElem {
  fts2HashElem *next, *prev; /* Next and previous elements in the table */
  void *data;                /* Data associated with this element */
  void *pKey; int nKey;      /* Key associated with this element */
};

/*
** There are 2 different modes of operation for a hash table:
**
**   FTS2_HASH_STRING        pKey points to a string that is nKey bytes long
**                           (including the null-terminator, if any).  Case
**                           is respected in comparisons.
**
**   FTS2_HASH_BINARY        pKey points to binary data nKey bytes long. 
**                           memcmp() is used to compare keys.
**
** A copy of the key is made if the copyKey parameter to fts2HashInit is 1.  
*/
#define FTS2_HASH_STRING    1
#define FTS2_HASH_BINARY    2

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite3Fts2HashInit(fts2Hash*, int keytype, int copyKey);
void *sqlite3Fts2HashInsert(fts2Hash*, const void *pKey, int nKey, void *pData);
void *sqlite3Fts2HashFind(const fts2Hash*, const void *pKey, int nKey);
void sqlite3Fts2HashClear(fts2Hash*);

/*
** Shorthand for the functions above
*/
#define fts2HashInit   sqlite3Fts2HashInit
#define fts2HashInsert sqlite3Fts2HashInsert
#define fts2HashFind   sqlite3Fts2HashFind
#define fts2HashClear  sqlite3Fts2HashClear

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   fts2Hash h;
**   fts2HashElem *p;
**   ...
**   for(p=fts2HashFirst(&h); p; p=fts2HashNext(p)){
**     SomeStructure *pData = fts2HashData(p);
**     // do something with pData
**   }
*/
#define fts2HashFirst(H)  ((H)->first)
#define fts2HashNext(E)   ((E)->next)
#define fts2HashData(E)   ((E)->data)
#define fts2HashKey(E)    ((E)->pKey)
#define fts2HashKeysize(E) ((E)->nKey)

/*
** Number of entries in a hash table
*/
#define fts2HashCount(H)  ((H)->count)

#endif /* _FTS2_HASH_H_ */

Added ext/fts2/fts2_icu.c.









































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
** 2007 June 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements a tokenizer for fts2 based on the ICU library.
** 
** $Id: fts2_icu.c,v 1.3 2008/12/18 05:30:26 danielk1977 Exp $
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)
#ifdef SQLITE_ENABLE_ICU

#include <assert.h>
#include <string.h>
#include "fts2_tokenizer.h"

#include <unicode/ubrk.h>
#include <unicode/ucol.h>
#include <unicode/ustring.h>
#include <unicode/utf16.h>

typedef struct IcuTokenizer IcuTokenizer;
typedef struct IcuCursor IcuCursor;

struct IcuTokenizer {
  sqlite3_tokenizer base;
  char *zLocale;
};

struct IcuCursor {
  sqlite3_tokenizer_cursor base;

  UBreakIterator *pIter;      /* ICU break-iterator object */
  int nChar;                  /* Number of UChar elements in pInput */
  UChar *aChar;               /* Copy of input using utf-16 encoding */
  int *aOffset;               /* Offsets of each character in utf-8 input */

  int nBuffer;
  char *zBuffer;

  int iToken;
};

/*
** Create a new tokenizer instance.
*/
static int icuCreate(
  int argc,                            /* Number of entries in argv[] */
  const char * const *argv,            /* Tokenizer creation arguments */
  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
){
  IcuTokenizer *p;
  int n = 0;

  if( argc>0 ){
    n = strlen(argv[0])+1;
  }
  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  if( !p ){
    return SQLITE_NOMEM;
  }
  memset(p, 0, sizeof(IcuTokenizer));

  if( n ){
    p->zLocale = (char *)&p[1];
    memcpy(p->zLocale, argv[0], n);
  }

  *ppTokenizer = (sqlite3_tokenizer *)p;

  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  sqlite3_free(p);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is pInput[0..nBytes-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int icuOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *zInput,                    /* Input string */
  int nInput,                            /* Length of zInput in bytes */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  IcuCursor *pCsr;

  const int32_t opt = U_FOLD_CASE_DEFAULT;
  UErrorCode status = U_ZERO_ERROR;
  int nChar;

  UChar32 c;
  int iInput = 0;
  int iOut = 0;

  *ppCursor = 0;

  if( nInput<0 ){
    nInput = strlen(zInput);
  }
  nChar = nInput+1;
  pCsr = (IcuCursor *)sqlite3_malloc(
      sizeof(IcuCursor) +                /* IcuCursor */
      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
  );
  if( !pCsr ){
    return SQLITE_NOMEM;
  }
  memset(pCsr, 0, sizeof(IcuCursor));
  pCsr->aChar = (UChar *)&pCsr[1];
  pCsr->aOffset = (int *)&pCsr->aChar[nChar];

  pCsr->aOffset[iOut] = iInput;
  U8_NEXT(zInput, iInput, nInput, c); 
  while( c>0 ){
    int isError = 0;
    c = u_foldCase(c, opt);
    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
    if( isError ){
      sqlite3_free(pCsr);
      return SQLITE_ERROR;
    }
    pCsr->aOffset[iOut] = iInput;

    if( iInput<nInput ){
      U8_NEXT(zInput, iInput, nInput, c);
    }else{
      c = 0;
    }
  }

  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  if( !U_SUCCESS(status) ){
    sqlite3_free(pCsr);
    return SQLITE_ERROR;
  }
  pCsr->nChar = iOut;

  ubrk_first(pCsr->pIter);
  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to icuOpen().
*/
static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  IcuCursor *pCsr = (IcuCursor *)pCursor;
  ubrk_close(pCsr->pIter);
  sqlite3_free(pCsr->zBuffer);
  sqlite3_free(pCsr);
  return SQLITE_OK;
}

/*
** Extract the next token from a tokenization cursor.
*/
static int icuNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
  const char **ppToken,               /* OUT: *ppToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  IcuCursor *pCsr = (IcuCursor *)pCursor;

  int iStart = 0;
  int iEnd = 0;
  int nByte = 0;

  while( iStart==iEnd ){
    UChar32 c;

    iStart = ubrk_current(pCsr->pIter);
    iEnd = ubrk_next(pCsr->pIter);
    if( iEnd==UBRK_DONE ){
      return SQLITE_DONE;
    }

    while( iStart<iEnd ){
      int iWhite = iStart;
      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
      if( u_isspace(c) ){
        iStart = iWhite;
      }else{
        break;
      }
    }
    assert(iStart<=iEnd);
  }

  do {
    UErrorCode status = U_ZERO_ERROR;
    if( nByte ){
      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
      if( !zNew ){
        return SQLITE_NOMEM;
      }
      pCsr->zBuffer = zNew;
      pCsr->nBuffer = nByte;
    }

    u_strToUTF8(
        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
        &status                                  /* Output success/failure */
    );
  } while( nByte>pCsr->nBuffer );

  *ppToken = pCsr->zBuffer;
  *pnBytes = nByte;
  *piStartOffset = pCsr->aOffset[iStart];
  *piEndOffset = pCsr->aOffset[iEnd];
  *piPosition = pCsr->iToken++;

  return SQLITE_OK;
}

/*
** The set of routines that implement the simple tokenizer
*/
static const sqlite3_tokenizer_module icuTokenizerModule = {
  0,                           /* iVersion */
  icuCreate,                   /* xCreate  */
  icuDestroy,                  /* xCreate  */
  icuOpen,                     /* xOpen    */
  icuClose,                    /* xClose   */
  icuNext,                     /* xNext    */
};

/*
** Set *ppModule to point at the implementation of the ICU tokenizer.
*/
void sqlite3Fts2IcuTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &icuTokenizerModule;
}

#endif /* defined(SQLITE_ENABLE_ICU) */
#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */

Added ext/fts2/fts2_porter.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*
** 2006 September 30
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Implementation of the full-text-search tokenizer that implements
** a Porter stemmer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)


#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts2_tokenizer.h"

/*
** Class derived from sqlite3_tokenizer
*/
typedef struct porter_tokenizer {
  sqlite3_tokenizer base;      /* Base class */
} porter_tokenizer;

/*
** Class derived from sqlit3_tokenizer_cursor
*/
typedef struct porter_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *zInput;          /* input we are tokenizing */
  int nInput;                  /* size of the input */
  int iOffset;                 /* current position in zInput */
  int iToken;                  /* index of next token to be returned */
  char *zToken;                /* storage for current token */
  int nAllocated;              /* space allocated to zToken buffer */
} porter_tokenizer_cursor;


/* Forward declaration */
static const sqlite3_tokenizer_module porterTokenizerModule;


/*
** Create a new tokenizer instance.
*/
static int porterCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  porter_tokenizer *t;
  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  if( t==NULL ) return SQLITE_NOMEM;
  memset(t, 0, sizeof(*t));
  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  sqlite3_free(pTokenizer);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is zInput[0..nInput-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int porterOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *zInput, int nInput,        /* String to be tokenized */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  porter_tokenizer_cursor *c;

  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  if( c==NULL ) return SQLITE_NOMEM;

  c->zInput = zInput;
  if( zInput==0 ){
    c->nInput = 0;
  }else if( nInput<0 ){
    c->nInput = (int)strlen(zInput);
  }else{
    c->nInput = nInput;
  }
  c->iOffset = 0;                 /* start tokenizing at the beginning */
  c->iToken = 0;
  c->zToken = NULL;               /* no space allocated, yet. */
  c->nAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to
** porterOpen() above.
*/
static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  sqlite3_free(c->zToken);
  sqlite3_free(c);
  return SQLITE_OK;
}
/*
** Vowel or consonant
*/
static const char cType[] = {
   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   1, 1, 1, 2, 1
};

/*
** isConsonant() and isVowel() determine if their first character in
** the string they point to is a consonant or a vowel, according
** to Porter ruls.  
**
** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
** 'Y' is a consonant unless it follows another consonant,
** in which case it is a vowel.
**
** In these routine, the letters are in reverse order.  So the 'y' rule
** is that 'y' is a consonant unless it is followed by another
** consonent.
*/
static int isVowel(const char*);
static int isConsonant(const char *z){
  int j;
  char x = *z;
  if( x==0 ) return 0;
  assert( x>='a' && x<='z' );
  j = cType[x-'a'];
  if( j<2 ) return j;
  return z[1]==0 || isVowel(z + 1);
}
static int isVowel(const char *z){
  int j;
  char x = *z;
  if( x==0 ) return 0;
  assert( x>='a' && x<='z' );
  j = cType[x-'a'];
  if( j<2 ) return 1-j;
  return isConsonant(z + 1);
}

/*
** Let any sequence of one or more vowels be represented by V and let
** C be sequence of one or more consonants.  Then every word can be
** represented as:
**
**           [C] (VC){m} [V]
**
** In prose:  A word is an optional consonant followed by zero or
** vowel-consonant pairs followed by an optional vowel.  "m" is the
** number of vowel consonant pairs.  This routine computes the value
** of m for the first i bytes of a word.
**
** Return true if the m-value for z is 1 or more.  In other words,
** return true if z contains at least one vowel that is followed
** by a consonant.
**
** In this routine z[] is in reverse order.  So we are really looking
** for an instance of of a consonant followed by a vowel.
*/
static int m_gt_0(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/* Like mgt0 above except we are looking for a value of m which is
** exactly 1
*/
static int m_eq_1(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 1;
  while( isConsonant(z) ){ z++; }
  return *z==0;
}

/* Like mgt0 above except we are looking for a value of m>1 instead
** or m>0
*/
static int m_gt_1(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/*
** Return TRUE if there is a vowel anywhere within z[0..n-1]
*/
static int hasVowel(const char *z){
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/*
** Return TRUE if the word ends in a double consonant.
**
** The text is reversed here. So we are really looking at
** the first two characters of z[].
*/
static int doubleConsonant(const char *z){
  return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
}

/*
** Return TRUE if the word ends with three letters which
** are consonant-vowel-consonent and where the final consonant
** is not 'w', 'x', or 'y'.
**
** The word is reversed here.  So we are really checking the
** first three letters and the first one cannot be in [wxy].
*/
static int star_oh(const char *z){
  return
    z[0]!=0 && isConsonant(z) &&
    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
    z[1]!=0 && isVowel(z+1) &&
    z[2]!=0 && isConsonant(z+2);
}

/*
** If the word ends with zFrom and xCond() is true for the stem
** of the word that preceeds the zFrom ending, then change the 
** ending to zTo.
**
** The input word *pz and zFrom are both in reverse order.  zTo
** is in normal order. 
**
** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
** match.  Not that TRUE is returned even if xCond() fails and
** no substitution occurs.
*/
static int stem(
  char **pz,             /* The word being stemmed (Reversed) */
  const char *zFrom,     /* If the ending matches this... (Reversed) */
  const char *zTo,       /* ... change the ending to this (not reversed) */
  int (*xCond)(const char*)   /* Condition that must be true */
){
  char *z = *pz;
  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  if( *zFrom!=0 ) return 0;
  if( xCond && !xCond(z) ) return 1;
  while( *zTo ){
    *(--z) = *(zTo++);
  }
  *pz = z;
  return 1;
}

/*
** This is the fallback stemmer used when the porter stemmer is
** inappropriate.  The input word is copied into the output with
** US-ASCII case folding.  If the input word is too long (more
** than 20 bytes if it contains no digits or more than 6 bytes if
** it contains digits) then word is truncated to 20 or 6 bytes
** by taking 10 or 3 bytes from the beginning and end.
*/
static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  int i, mx, j;
  int hasDigit = 0;
  for(i=0; i<nIn; i++){
    int c = zIn[i];
    if( c>='A' && c<='Z' ){
      zOut[i] = c - 'A' + 'a';
    }else{
      if( c>='0' && c<='9' ) hasDigit = 1;
      zOut[i] = c;
    }
  }
  mx = hasDigit ? 3 : 10;
  if( nIn>mx*2 ){
    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
      zOut[j] = zOut[i];
    }
    i = j;
  }
  zOut[i] = 0;
  *pnOut = i;
}


/*
** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
** zOut is at least big enough to hold nIn bytes.  Write the actual
** size of the output word (exclusive of the '\0' terminator) into *pnOut.
**
** Any upper-case characters in the US-ASCII character set ([A-Z])
** are converted to lower case.  Upper-case UTF characters are
** unchanged.
**
** Words that are longer than about 20 bytes are stemmed by retaining
** a few bytes from the beginning and the end of the word.  If the
** word contains digits, 3 bytes are taken from the beginning and
** 3 bytes from the end.  For long words without digits, 10 bytes
** are taken from each end.  US-ASCII case folding still applies.
** 
** If the input word contains not digits but does characters not 
** in [a-zA-Z] then no stemming is attempted and this routine just 
** copies the input into the input into the output with US-ASCII
** case folding.
**
** Stemming never increases the length of the word.  So there is
** no chance of overflowing the zOut buffer.
*/
static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  int i, j, c;
  char zReverse[28];
  char *z, *z2;
  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
    /* The word is too big or too small for the porter stemmer.
    ** Fallback to the copy stemmer */
    copy_stemmer(zIn, nIn, zOut, pnOut);
    return;
  }
  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
    c = zIn[i];
    if( c>='A' && c<='Z' ){
      zReverse[j] = c + 'a' - 'A';
    }else if( c>='a' && c<='z' ){
      zReverse[j] = c;
    }else{
      /* The use of a character not in [a-zA-Z] means that we fallback
      ** to the copy stemmer */
      copy_stemmer(zIn, nIn, zOut, pnOut);
      return;
    }
  }
  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  z = &zReverse[j+1];


  /* Step 1a */
  if( z[0]=='s' ){
    if(
     !stem(&z, "sess", "ss", 0) &&
     !stem(&z, "sei", "i", 0)  &&
     !stem(&z, "ss", "ss", 0)
    ){
      z++;
    }
  }

  /* Step 1b */  
  z2 = z;
  if( stem(&z, "dee", "ee", m_gt_0) ){
    /* Do nothing.  The work was all in the test */
  }else if( 
     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
      && z!=z2
  ){
     if( stem(&z, "ta", "ate", 0) ||
         stem(&z, "lb", "ble", 0) ||
         stem(&z, "zi", "ize", 0) ){
       /* Do nothing.  The work was all in the test */
     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
       z++;
     }else if( m_eq_1(z) && star_oh(z) ){
       *(--z) = 'e';
     }
  }

  /* Step 1c */
  if( z[0]=='y' && hasVowel(z+1) ){
    z[0] = 'i';
  }

  /* Step 2 */
  switch( z[1] ){
   case 'a':
     stem(&z, "lanoita", "ate", m_gt_0) ||
     stem(&z, "lanoit", "tion", m_gt_0);
     break;
   case 'c':
     stem(&z, "icne", "ence", m_gt_0) ||
     stem(&z, "icna", "ance", m_gt_0);
     break;
   case 'e':
     stem(&z, "rezi", "ize", m_gt_0);
     break;
   case 'g':
     stem(&z, "igol", "log", m_gt_0);
     break;
   case 'l':
     stem(&z, "ilb", "ble", m_gt_0) ||
     stem(&z, "illa", "al", m_gt_0) ||
     stem(&z, "iltne", "ent", m_gt_0) ||
     stem(&z, "ile", "e", m_gt_0) ||
     stem(&z, "ilsuo", "ous", m_gt_0);
     break;
   case 'o':
     stem(&z, "noitazi", "ize", m_gt_0) ||
     stem(&z, "noita", "ate", m_gt_0) ||
     stem(&z, "rota", "ate", m_gt_0);
     break;
   case 's':
     stem(&z, "msila", "al", m_gt_0) ||
     stem(&z, "ssenevi", "ive", m_gt_0) ||
     stem(&z, "ssenluf", "ful", m_gt_0) ||
     stem(&z, "ssensuo", "ous", m_gt_0);
     break;
   case 't':
     stem(&z, "itila", "al", m_gt_0) ||
     stem(&z, "itivi", "ive", m_gt_0) ||
     stem(&z, "itilib", "ble", m_gt_0);
     break;
  }

  /* Step 3 */
  switch( z[0] ){
   case 'e':
     stem(&z, "etaci", "ic", m_gt_0) ||
     stem(&z, "evita", "", m_gt_0)   ||
     stem(&z, "ezila", "al", m_gt_0);
     break;
   case 'i':
     stem(&z, "itici", "ic", m_gt_0);
     break;
   case 'l':
     stem(&z, "laci", "ic", m_gt_0) ||
     stem(&z, "luf", "", m_gt_0);
     break;
   case 's':
     stem(&z, "ssen", "", m_gt_0);
     break;
  }

  /* Step 4 */
  switch( z[1] ){
   case 'a':
     if( z[0]=='l' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'c':
     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
       z += 4;
     }
     break;
   case 'e':
     if( z[0]=='r' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'i':
     if( z[0]=='c' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'l':
     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
       z += 4;
     }
     break;
   case 'n':
     if( z[0]=='t' ){
       if( z[2]=='a' ){
         if( m_gt_1(z+3) ){
           z += 3;
         }
       }else if( z[2]=='e' ){
         stem(&z, "tneme", "", m_gt_1) ||
         stem(&z, "tnem", "", m_gt_1) ||
         stem(&z, "tne", "", m_gt_1);
       }
     }
     break;
   case 'o':
     if( z[0]=='u' ){
       if( m_gt_1(z+2) ){
         z += 2;
       }
     }else if( z[3]=='s' || z[3]=='t' ){
       stem(&z, "noi", "", m_gt_1);
     }
     break;
   case 's':
     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
   case 't':
     stem(&z, "eta", "", m_gt_1) ||
     stem(&z, "iti", "", m_gt_1);
     break;
   case 'u':
     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
   case 'v':
   case 'z':
     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
  }

  /* Step 5a */
  if( z[0]=='e' ){
    if( m_gt_1(z+1) ){
      z++;
    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
      z++;
    }
  }

  /* Step 5b */
  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
    z++;
  }

  /* z[] is now the stemmed word in reverse order.  Flip it back
  ** around into forward order and return.
  */
  *pnOut = i = strlen(z);
  zOut[i] = 0;
  while( *z ){
    zOut[--i] = *(z++);
  }
}

/*
** Characters that can be part of a token.  We assume any character
** whose value is greater than 0x80 (any UTF character) can be
** part of a token.  In other words, delimiters all must have
** values of 0x7f or lower.
*/
static const char porterIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))

/*
** Extract the next token from a tokenization cursor.  The cursor must
** have been opened by a prior call to porterOpen().
*/
static int porterNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
  const char **pzToken,               /* OUT: *pzToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  const char *z = c->zInput;

  while( c->iOffset<c->nInput ){
    int iStartOffset, ch;

    /* Scan past delimiter characters */
    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
      c->iOffset++;
    }

    /* Count non-delimiter characters. */
    iStartOffset = c->iOffset;
    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
      c->iOffset++;
    }

    if( c->iOffset>iStartOffset ){
      int n = c->iOffset-iStartOffset;
      if( n>c->nAllocated ){
        c->nAllocated = n+20;
        c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
        if( c->zToken==NULL ) return SQLITE_NOMEM;
      }
      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
      *pzToken = c->zToken;
      *piStartOffset = iStartOffset;
      *piEndOffset = c->iOffset;
      *piPosition = c->iToken++;
      return SQLITE_OK;
    }
  }
  return SQLITE_DONE;
}

/*
** The set of routines that implement the porter-stemmer tokenizer
*/
static const sqlite3_tokenizer_module porterTokenizerModule = {
  0,
  porterCreate,
  porterDestroy,
  porterOpen,
  porterClose,
  porterNext,
};

/*
** Allocate a new porter tokenizer.  Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts2PorterTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &porterTokenizerModule;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */

Added ext/fts2/fts2_tokenizer.c.







































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
** 2007 June 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is part of an SQLite module implementing full-text search.
** This particular file implements the generic tokenizer interface.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)


#include "sqlite3.h"
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1

#include "fts2_hash.h"
#include "fts2_tokenizer.h"
#include <assert.h>

/*
** Implementation of the SQL scalar function for accessing the underlying 
** hash table. This function may be called as follows:
**
**   SELECT <function-name>(<key-name>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts2InitHashTable() function (e.g. 'fts2_tokenizer').
**
** If the <pointer> argument is specified, it must be a blob value
** containing a pointer to be stored as the hash data corresponding
** to the string <key-name>. If <pointer> is not specified, then
** the string <key-name> must already exist in the has table. Otherwise,
** an error is returned.
**
** Whether or not the <pointer> argument is specified, the value returned
** is a blob containing the pointer stored as the hash data corresponding
** to string <key-name> (after the hash-table is updated, if applicable).
*/
static void scalarFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fts2Hash *pHash;
  void *pPtr = 0;
  const unsigned char *zName;
  int nName;

  assert( argc==1 || argc==2 );

  pHash = (fts2Hash *)sqlite3_user_data(context);

  zName = sqlite3_value_text(argv[0]);
  nName = sqlite3_value_bytes(argv[0])+1;

  if( argc==2 ){
    void *pOld;
    int n = sqlite3_value_bytes(argv[1]);
    if( n!=sizeof(pPtr) ){
      sqlite3_result_error(context, "argument type mismatch", -1);
      return;
    }
    pPtr = *(void **)sqlite3_value_blob(argv[1]);
    pOld = sqlite3Fts2HashInsert(pHash, (void *)zName, nName, pPtr);
    if( pOld==pPtr ){
      sqlite3_result_error(context, "out of memory", -1);
      return;
    }
  }else{
    pPtr = sqlite3Fts2HashFind(pHash, zName, nName);
    if( !pPtr ){
      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
      sqlite3_result_error(context, zErr, -1);
      sqlite3_free(zErr);
      return;
    }
  }

  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
}

#ifdef SQLITE_TEST

#include <tcl.h>
#include <string.h>

/*
** Implementation of a special SQL scalar function for testing tokenizers 
** designed to be used in concert with the Tcl testing framework. This
** function must be called with two arguments:
**
**   SELECT <function-name>(<key-name>, <input-string>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts2InitHashTable() function (e.g. 'fts2_tokenizer')
** concatenated with the string '_test' (e.g. 'fts2_tokenizer_test').
**
** The return value is a string that may be interpreted as a Tcl
** list. For each token in the <input-string>, three elements are
** added to the returned list. The first is the token position, the 
** second is the token text (folded, stemmed, etc.) and the third is the
** substring of <input-string> associated with the token. For example, 
** using the built-in "simple" tokenizer:
**
**   SELECT fts_tokenizer_test('simple', 'I don't see how');
**
** will return the string:
**
**   "{0 i I 1 dont don't 2 see see 3 how how}"
**   
*/
static void testFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fts2Hash *pHash;
  sqlite3_tokenizer_module *p;
  sqlite3_tokenizer *pTokenizer = 0;
  sqlite3_tokenizer_cursor *pCsr = 0;

  const char *zErr = 0;

  const char *zName;
  int nName;
  const char *zInput;
  int nInput;

  const char *zArg = 0;

  const char *zToken;
  int nToken;
  int iStart;
  int iEnd;
  int iPos;

  Tcl_Obj *pRet;

  assert( argc==2 || argc==3 );

  nName = sqlite3_value_bytes(argv[0]);
  zName = (const char *)sqlite3_value_text(argv[0]);
  nInput = sqlite3_value_bytes(argv[argc-1]);
  zInput = (const char *)sqlite3_value_text(argv[argc-1]);

  if( argc==3 ){
    zArg = (const char *)sqlite3_value_text(argv[1]);
  }

  pHash = (fts2Hash *)sqlite3_user_data(context);
  p = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zName, nName+1);

  if( !p ){
    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
    sqlite3_result_error(context, zErr, -1);
    sqlite3_free(zErr);
    return;
  }

  pRet = Tcl_NewObj();
  Tcl_IncrRefCount(pRet);

  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
    zErr = "error in xCreate()";
    goto finish;
  }
  pTokenizer->pModule = p;
  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
    zErr = "error in xOpen()";
    goto finish;
  }
  pCsr->pTokenizer = pTokenizer;

  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
    zToken = &zInput[iStart];
    nToken = iEnd-iStart;
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  }

  if( SQLITE_OK!=p->xClose(pCsr) ){
    zErr = "error in xClose()";
    goto finish;
  }
  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
    zErr = "error in xDestroy()";
    goto finish;
  }

finish:
  if( zErr ){
    sqlite3_result_error(context, zErr, -1);
  }else{
    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  }
  Tcl_DecrRefCount(pRet);
}

static
int registerTokenizer(
  sqlite3 *db, 
  char *zName, 
  const sqlite3_tokenizer_module *p
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts2_tokenizer(?, ?)";

  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  sqlite3_step(pStmt);

  return sqlite3_finalize(pStmt);
}

static
int queryFts2Tokenizer(
  sqlite3 *db, 
  char *zName,  
  const sqlite3_tokenizer_module **pp
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts2_tokenizer(?)";

  *pp = 0;
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  if( SQLITE_ROW==sqlite3_step(pStmt) ){
    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
      memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
    }
  }

  return sqlite3_finalize(pStmt);
}

void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);

/*
** Implementation of the scalar function fts2_tokenizer_internal_test().
** This function is used for testing only, it is not included in the
** build unless SQLITE_TEST is defined.
**
** The purpose of this is to test that the fts2_tokenizer() function
** can be used as designed by the C-code in the queryFts2Tokenizer and
** registerTokenizer() functions above. These two functions are repeated
** in the README.tokenizer file as an example, so it is important to
** test them.
**
** To run the tests, evaluate the fts2_tokenizer_internal_test() scalar
** function with no arguments. An assert() will fail if a problem is
** detected. i.e.:
**
**     SELECT fts2_tokenizer_internal_test();
**
*/
static void intTestFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int rc;
  const sqlite3_tokenizer_module *p1;
  const sqlite3_tokenizer_module *p2;
  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);

  /* Test the query function */
  sqlite3Fts2SimpleTokenizerModule(&p1);
  rc = queryFts2Tokenizer(db, "simple", &p2);
  assert( rc==SQLITE_OK );
  assert( p1==p2 );
  rc = queryFts2Tokenizer(db, "nosuchtokenizer", &p2);
  assert( rc==SQLITE_ERROR );
  assert( p2==0 );
  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );

  /* Test the storage function */
  rc = registerTokenizer(db, "nosuchtokenizer", p1);
  assert( rc==SQLITE_OK );
  rc = queryFts2Tokenizer(db, "nosuchtokenizer", &p2);
  assert( rc==SQLITE_OK );
  assert( p2==p1 );

  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
}

#endif

/*
** Set up SQL objects in database db used to access the contents of
** the hash table pointed to by argument pHash. The hash table must
** been initialised to use string keys, and to take a private copy 
** of the key when a value is inserted. i.e. by a call similar to:
**
**    sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1);
**
** This function adds a scalar function (see header comment above
** scalarFunc() in this file for details) and, if ENABLE_TABLE is
** defined at compilation time, a temporary virtual table (see header 
** comment above struct HashTableVtab) to the database schema. Both 
** provide read/write access to the contents of *pHash.
**
** The third argument to this function, zName, is used as the name
** of both the scalar and, if created, the virtual table.
*/
int sqlite3Fts2InitHashTable(
  sqlite3 *db, 
  fts2Hash *pHash, 
  const char *zName
){
  int rc = SQLITE_OK;
  void *p = (void *)pHash;
  const int any = SQLITE_ANY;
  char *zTest = 0;
  char *zTest2 = 0;

#ifdef SQLITE_TEST
  void *pdb = (void *)db;
  zTest = sqlite3_mprintf("%s_test", zName);
  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  if( !zTest || !zTest2 ){
    rc = SQLITE_NOMEM;
  }
#endif

  if( rc!=SQLITE_OK
   || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
#ifdef SQLITE_TEST
   || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
#endif
  );

  sqlite3_free(zTest);
  sqlite3_free(zTest2);
  return rc;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */

Added ext/fts2/fts2_tokenizer.h.



































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
** 2006 July 10
**
** The author disclaims copyright to this source code.
**
*************************************************************************
** Defines the interface to tokenizers used by fulltext-search.  There
** are three basic components:
**
** sqlite3_tokenizer_module is a singleton defining the tokenizer
** interface functions.  This is essentially the class structure for
** tokenizers.
**
** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
** including customization information defined at creation time.
**
** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
** tokens from a particular input.
*/
#ifndef _FTS2_TOKENIZER_H_
#define _FTS2_TOKENIZER_H_

/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
** If tokenizers are to be allowed to call sqlite3_*() functions, then
** we will need a way to register the API consistently.
*/
#include "sqlite3.h"

/*
** Structures used by the tokenizer interface. When a new tokenizer
** implementation is registered, the caller provides a pointer to
** an sqlite3_tokenizer_module containing pointers to the callback
** functions that make up an implementation.
**
** When an fts2 table is created, it passes any arguments passed to
** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
** implementation. The xCreate() function in turn returns an 
** sqlite3_tokenizer structure representing the specific tokenizer to
** be used for the fts2 table (customized by the tokenizer clause arguments).
**
** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
** method is called. It returns an sqlite3_tokenizer_cursor object
** that may be used to tokenize a specific input buffer based on
** the tokenization rules supplied by a specific sqlite3_tokenizer
** object.
*/
typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
typedef struct sqlite3_tokenizer sqlite3_tokenizer;
typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;

struct sqlite3_tokenizer_module {

  /*
  ** Structure version. Should always be set to 0.
  */
  int iVersion;

  /*
  ** Create a new tokenizer. The values in the argv[] array are the
  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  ** TABLE statement that created the fts2 table. For example, if
  ** the following SQL is executed:
  **
  **   CREATE .. USING fts2( ... , tokenizer <tokenizer-name> arg1 arg2)
  **
  ** then argc is set to 2, and the argv[] array contains pointers
  ** to the strings "arg1" and "arg2".
  **
  ** This method should return either SQLITE_OK (0), or an SQLite error 
  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  ** to point at the newly created tokenizer structure. The generic
  ** sqlite3_tokenizer.pModule variable should not be initialised by
  ** this callback. The caller will do so.
  */
  int (*xCreate)(
    int argc,                           /* Size of argv array */
    const char *const*argv,             /* Tokenizer argument strings */
    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
  );

  /*
  ** Destroy an existing tokenizer. The fts2 module calls this method
  ** exactly once for each successful call to xCreate().
  */
  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);

  /*
  ** Create a tokenizer cursor to tokenize an input buffer. The caller
  ** is responsible for ensuring that the input buffer remains valid
  ** until the cursor is closed (using the xClose() method). 
  */
  int (*xOpen)(
    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
    const char *pInput, int nBytes,      /* Input buffer */
    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
  );

  /*
  ** Destroy an existing tokenizer cursor. The fts2 module calls this 
  ** method exactly once for each successful call to xOpen().
  */
  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);

  /*
  ** Retrieve the next token from the tokenizer cursor pCursor. This
  ** method should either return SQLITE_OK and set the values of the
  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  ** the end of the buffer has been reached, or an SQLite error code.
  **
  ** *ppToken should be set to point at a buffer containing the 
  ** normalized version of the token (i.e. after any case-folding and/or
  ** stemming has been performed). *pnBytes should be set to the length
  ** of this buffer in bytes. The input text that generated the token is
  ** identified by the byte offsets returned in *piStartOffset and
  ** *piEndOffset.
  **
  ** The buffer *ppToken is set to point at is managed by the tokenizer
  ** implementation. It is only required to be valid until the next call
  ** to xNext() or xClose(). 
  */
  /* TODO(shess) current implementation requires pInput to be
  ** nul-terminated.  This should either be fixed, or pInput/nBytes
  ** should be converted to zInput.
  */
  int (*xNext)(
    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
    int *piPosition      /* OUT: Number of tokens returned before this one */
  );
};

struct sqlite3_tokenizer {
  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
  /* Tokenizer implementations will typically add additional fields */
};

struct sqlite3_tokenizer_cursor {
  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
  /* Tokenizer implementations will typically add additional fields */
};

#endif /* _FTS2_TOKENIZER_H_ */

Added ext/fts2/fts2_tokenizer1.c.













































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** Implementation of the "simple" full-text-search tokenizer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)


#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts2_tokenizer.h"

typedef struct simple_tokenizer {
  sqlite3_tokenizer base;
  char delim[128];             /* flag ASCII delimiters */
} simple_tokenizer;

typedef struct simple_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *pInput;          /* input we are tokenizing */
  int nBytes;                  /* size of the input */
  int iOffset;                 /* current position in pInput */
  int iToken;                  /* index of next token to be returned */
  char *pToken;                /* storage for current token */
  int nTokenAllocated;         /* space allocated to zToken buffer */
} simple_tokenizer_cursor;


/* Forward declaration */
static const sqlite3_tokenizer_module simpleTokenizerModule;

static int simpleDelim(simple_tokenizer *t, unsigned char c){
  return c<0x80 && t->delim[c];
}

/*
** Create a new tokenizer instance.
*/
static int simpleCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  simple_tokenizer *t;

  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  if( t==NULL ) return SQLITE_NOMEM;
  memset(t, 0, sizeof(*t));

  /* TODO(shess) Delimiters need to remain the same from run to run,
  ** else we need to reindex.  One solution would be a meta-table to
  ** track such information in the database, then we'd only want this
  ** information on the initial create.
  */
  if( argc>1 ){
    int i, n = strlen(argv[1]);
    for(i=0; i<n; i++){
      unsigned char ch = argv[1][i];
      /* We explicitly don't support UTF-8 delimiters for now. */
      if( ch>=0x80 ){
        sqlite3_free(t);
        return SQLITE_ERROR;
      }
      t->delim[ch] = 1;
    }
  } else {
    /* Mark non-alphanumeric ASCII characters as delimiters */
    int i;
    for(i=1; i<0x80; i++){
      t->delim[i] = !isalnum(i);
    }
  }

  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  sqlite3_free(pTokenizer);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is pInput[0..nBytes-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int simpleOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *pInput, int nBytes,        /* String to be tokenized */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  simple_tokenizer_cursor *c;

  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  if( c==NULL ) return SQLITE_NOMEM;

  c->pInput = pInput;
  if( pInput==0 ){
    c->nBytes = 0;
  }else if( nBytes<0 ){
    c->nBytes = (int)strlen(pInput);
  }else{
    c->nBytes = nBytes;
  }
  c->iOffset = 0;                 /* start tokenizing at the beginning */
  c->iToken = 0;
  c->pToken = NULL;               /* no space allocated, yet. */
  c->nTokenAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to
** simpleOpen() above.
*/
static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  sqlite3_free(c->pToken);
  sqlite3_free(c);
  return SQLITE_OK;
}

/*
** Extract the next token from a tokenization cursor.  The cursor must
** have been opened by a prior call to simpleOpen().
*/
static int simpleNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
  const char **ppToken,               /* OUT: *ppToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  unsigned char *p = (unsigned char *)c->pInput;

  while( c->iOffset<c->nBytes ){
    int iStartOffset;

    /* Scan past delimiter characters */
    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
      c->iOffset++;
    }

    /* Count non-delimiter characters. */
    iStartOffset = c->iOffset;
    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
      c->iOffset++;
    }

    if( c->iOffset>iStartOffset ){
      int i, n = c->iOffset-iStartOffset;
      if( n>c->nTokenAllocated ){
        c->nTokenAllocated = n+20;
        c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
        if( c->pToken==NULL ) return SQLITE_NOMEM;
      }
      for(i=0; i<n; i++){
        /* TODO(shess) This needs expansion to handle UTF-8
        ** case-insensitivity.
        */
        unsigned char ch = p[iStartOffset+i];
        c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
      }
      *ppToken = c->pToken;
      *pnBytes = n;
      *piStartOffset = iStartOffset;
      *piEndOffset = c->iOffset;
      *piPosition = c->iToken++;

      return SQLITE_OK;
    }
  }
  return SQLITE_DONE;
}

/*
** The set of routines that implement the simple tokenizer
*/
static const sqlite3_tokenizer_module simpleTokenizerModule = {
  0,
  simpleCreate,
  simpleDestroy,
  simpleOpen,
  simpleClose,
  simpleNext,
};

/*
** Allocate a new simple tokenizer.  Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts2SimpleTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &simpleTokenizerModule;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */

Added ext/fts2/mkfts2amal.tcl.









































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/tclsh
#
# This script builds a single C code file holding all of FTS2 code.
# The name of the output file is fts2amal.c.  To build this file,
# first do:
#
#      make target_source
#
# The make target above moves all of the source code files into
# a subdirectory named "tsrc".  (This script expects to find the files
# there and will not work if they are not found.)
#
# After the "tsrc" directory has been created and populated, run
# this script:
#
#      tclsh mkfts2amal.tcl
#
# The amalgamated FTS2 code will be written into fts2amal.c
#

# Open the output file and write a header comment at the beginning
# of the file.
#
set out [open fts2amal.c w]
set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1]
puts $out [subst \
{/******************************************************************************
** This file is an amalgamation of separate C source files from the SQLite
** Full Text Search extension 2 (fts2).  By combining all the individual C 
** code  files into this single large file, the entire code can be compiled 
** as a one translation unit.  This allows many compilers to do optimizations
** that would not be possible if the files were compiled separately.  It also
** makes the code easier to import into other projects.
**
** This amalgamation was generated on $today.
*/}]

# These are the header files used by FTS2.  The first time any of these 
# files are seen in a #include statement in the C code, include the complete
# text of the file in-line.  The file only needs to be included once.
#
foreach hdr {
   fts2.h
   fts2_hash.h
   fts2_tokenizer.h
   sqlite3.h
   sqlite3ext.h
} {
  set available_hdr($hdr) 1
}

# 78 stars used for comment formatting.
set s78 \
{*****************************************************************************}

# Insert a comment into the code
#
proc section_comment {text} {
  global out s78
  set n [string length $text]
  set nstar [expr {60 - $n}]
  set stars [string range $s78 0 $nstar]
  puts $out "/************** $text $stars/"
}

# Read the source file named $filename and write it into the
# sqlite3.c output file.  If any #include statements are seen,
# process them approprately.
#
proc copy_file {filename} {
  global seen_hdr available_hdr out
  set tail [file tail $filename]
  section_comment "Begin file $tail"
  set in [open $filename r]
  while {![eof $in]} {
    set line [gets $in]
    if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} {
      if {[info exists available_hdr($hdr)]} {
        if {$available_hdr($hdr)} {
          section_comment "Include $hdr in the middle of $tail"
          copy_file tsrc/$hdr
          section_comment "Continuing where we left off in $tail"
        }
      } elseif {![info exists seen_hdr($hdr)]} {
        set seen_hdr($hdr) 1
        puts $out $line
      }
    } elseif {[regexp {^#ifdef __cplusplus} $line]} {
      puts $out "#if 0"
    } elseif {[regexp {^#line} $line]} {
      # Skip #line directives.
    } else {
      puts $out $line
    }
  }
  close $in
  section_comment "End of $tail"
}


# Process the source files.  Process files containing commonly
# used subroutines first in order to help the compiler find
# inlining opportunities.
#
foreach file {
   fts2.c
   fts2_hash.c
   fts2_porter.c
   fts2_tokenizer.c
   fts2_tokenizer1.c
   fts2_icu.c
} {
  copy_file tsrc/$file
}

close $out

Added ext/fts3/README.syntax.



































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209

1. OVERVIEW

  This README file describes the syntax of the arguments that may be passed to
  the FTS3 MATCH operator used for full-text queries. For example, if table 
  "t1" is an Fts3 virtual table, the following SQL query:

    SELECT * FROM t1 WHERE <col> MATCH <full-text query>

  may be used to retrieve all rows that match a specified for full-text query. 
  The text "<col>" should be replaced by either the name of the fts3 table 
  (in this case "t1"), or by the name of one of the columns of the fts3 
  table. <full-text-query> should be replaced by an SQL expression that 
  computes to a string containing an Fts3 query.

  If the left-hand-side of the MATCH operator is set to the name of the
  fts3 table, then by default the query may be matched against any column
  of the table. If it is set to a column name, then by default the query
  may only match the specified column. In both cases this may be overriden
  as part of the query text (see sections 2 and 3 below).

  As of SQLite version 3.6.8, Fts3 supports two slightly different query 
  formats; the standard syntax, which is used by default, and the enhanced
  query syntax which can be selected by compiling with the pre-processor
  symbol SQLITE_ENABLE_FTS3_PARENTHESIS defined.

    -DSQLITE_ENABLE_FTS3_PARENTHESIS

2. STANDARD QUERY SYNTAX

  When using the standard Fts3 query syntax, a query usually consists of a 
  list of terms (words) separated by white-space characters. To match a
  query, a row (or column) of an Fts3 table must contain each of the specified
  terms. For example, the following query:

    <col> MATCH 'hello world'

  matches rows (or columns, if <col> is the name of a column name) that 
  contain at least one instance of the token "hello", and at least one 
  instance of the token "world". Tokens may be grouped into phrases using
  quotation marks. In this case, a matching row or column must contain each
  of the tokens in the phrase in the order specified, with no intervening
  tokens. For example, the query:

    <col> MATCH '"hello world" joe"

  matches the first of the following two documents, but not the second or
  third:

    "'Hello world', said Joe."
    "One should always greet the world with a cheery hello, thought Joe."
    "How many hello world programs could their be?"

  As well as grouping tokens together by phrase, the binary NEAR operator 
  may be used to search for rows that contain two or more specified tokens 
  or phrases within a specified proximity of each other. The NEAR operator
  must always be specified in upper case. The word "near" in lower or mixed
  case is treated as an ordinary token. For example, the following query:

    <col> MATCH 'engineering NEAR consultancy'

  matches rows that contain both the "engineering" and "consultancy" tokens
  in the same column with not more than 10 other words between them. It does
  not matter which of the two terms occurs first in the document, only that
  they be seperated by only 10 tokens or less. The user may also specify
  a different required proximity by adding "/N" immediately after the NEAR
  operator, where N is an integer. For example:

    <col> MATCH 'engineering NEAR/5 consultancy'

  searches for a row containing an instance of each specified token seperated
  by not more than 5 other tokens. More than one NEAR operator can be used
  in as sequence. For example this query:

    <col> MATCH 'reliable NEAR/2 engineering NEAR/5 consultancy'

  searches for a row that contains an instance of the token "reliable" 
  seperated by not more than two tokens from an instance of "engineering",
  which is in turn separated by not more than 5 other tokens from an
  instance of the term "consultancy". Phrases enclosed in quotes may
  also be used as arguments to the NEAR operator.

  Similar to the NEAR operator, one or more tokens or phrases may be 
  separated by OR operators. In this case, only one of the specified tokens
  or phrases must appear in the document. For example, the query:

    <col> MATCH 'hello OR world'

  matches rows that contain either the term "hello", or the term "world",
  or both. Note that unlike in many programming languages, the OR operator
  has a higher precedence than the AND operators implied between white-space
  separated tokens. The following query matches documents that contain the
  term 'sqlite' and at least one of the terms 'fantastic' or 'impressive',
  not those that contain both 'sqlite' and 'fantastic' or 'impressive':

    <col> MATCH 'sqlite fantastic OR impressive'

  Any token that is part of an Fts3 query expression, whether or not it is
  part of a phrase enclosed in quotes, may have a '*' character appended to
  it. In this case, the token matches all terms that begin with the characters
  of the token, not just those that exactly match it. For example, the 
  following query:

    <col> MATCH 'sql*'

  matches all rows that contain the term "SQLite", as well as those that
  contain "SQL".

  A token that is not part of a quoted phrase may be preceded by a '-'
  character, which indicates that matching rows must not contain the 
  specified term. For example, the following:

    <col> MATCH '"database engine" -sqlite'

  matches rows that contain the phrase "database engine" but do not contain
  the term "sqlite". If the '-' character occurs inside a quoted phrase,
  it is ignored. It is possible to use both the '-' prefix and the '*' postfix
  on a single term. At this time, all Fts3 queries must contain at least
  one term or phrase that is not preceded by the '-' prefix.

  Regardless of whether or not a table name or column name is used on the 
  left hand side of the MATCH operator, a specific column of the fts3 table
  may be associated with each token in a query by preceding a token with
  a column name followed by a ':' character. For example, regardless of what
  is specified for <col>, the following query requires that column "col1"
  of the table contains the term "hello", and that column "col2" of the
  table contains the term "world". If the table does not contain columns
  named "col1" and "col2", then an error is returned and the query is
  not run.

    <col> MATCH 'col1:hello col2:world'

  It is not possible to associate a specific table column with a quoted 
  phrase or a term preceded by a '-' operator. A '*' character may be
  appended to a term associated with a specific column for prefix matching.

3. ENHANCED QUERY SYNTAX

  The enhanced query syntax is quite similar to the standard query syntax,
  with the following four differences:

  1) Parenthesis are supported. When using the enhanced query syntax,
     parenthesis may be used to overcome the built-in precedence of the
     supplied binary operators. For example, the following query:

       <col> MATCH '(hello world) OR (simple example)'

     matches documents that contain both "hello" and "world", and documents
     that contain both "simple" and "example". It is not possible to forumlate
     such a query using the standard syntax.

  2) Instead of separating tokens and phrases by whitespace, an AND operator
     may be explicitly specified. This does not change query processing at
     all, but may be used to improve readability. For example, the following
     query is handled identically to the one above:

       <col> MATCH '(hello AND world) OR (simple AND example)'

     As with the OR and NEAR operators, the AND operator must be specified
     in upper case. The word "and" specified in lower or mixed case is 
     handled as a regular token.

  3) The '-' token prefix is not supported. Instead, a new binary operator,
     NOT, is included. The NOT operator requires that the query specified
     as its left-hand operator matches, but that the query specified as the
     right-hand operator does not. For example, to query for all rows that
     contain the term "example" but not the term "simple", the following
     query could be used:

       <col> MATCH 'example NOT simple'

     As for all other operators, the NOT operator must be specified in
     upper case. Otherwise it will be treated as a regular token.

  4) Unlike in the standard syntax, where the OR operator has a higher
     precedence than the implicit AND operator, when using the enhanced
     syntax implicit and explict AND operators have a higher precedence
     than OR operators. Using the enhanced syntax, the following two
     queries are equivalent:

       <col> MATCH 'sqlite fantastic OR impressive'
       <col> MATCH '(sqlite AND fantastic) OR impressive'

     however, when using the standard syntax, the query:

       <col> MATCH 'sqlite fantastic OR impressive'

     is equivalent to the enhanced syntax query:

       <col> MATCH 'sqlite AND (fantastic OR impressive)'

     The precedence of all enhanced syntax operators, in order from highest
     to lowest, is:

       NEAR       (highest precedence, tightest grouping)
       NOT
       AND
       OR         (lowest precedence, loosest grouping)

  Using the advanced syntax, it is possible to specify expressions enclosed
  in parenthesis as operands to the NOT, AND and OR operators. However both
  the left and right hand side operands of NEAR operators must be either
  tokens or phrases. Attempting the following query will return an error:

    <col> MATCH 'sqlite NEAR (fantastic OR impressive)'

  Queries of this form must be re-written as:

    <col> MATCH 'sqlite NEAR fantastic OR sqlite NEAR impressive'

Added ext/fts3/README.tokenizers.











































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

1. FTS3 Tokenizers

  When creating a new full-text table, FTS3 allows the user to select
  the text tokenizer implementation to be used when indexing text
  by specifying a "tokenize" clause as part of the CREATE VIRTUAL TABLE
  statement:

    CREATE VIRTUAL TABLE <table-name> USING fts3(
      <columns ...> [, tokenize <tokenizer-name> [<tokenizer-args>]]
    );

  The built-in tokenizers (valid values to pass as <tokenizer name>) are
  "simple" and "porter".

  <tokenizer-args> should consist of zero or more white-space separated
  arguments to pass to the selected tokenizer implementation. The 
  interpretation of the arguments, if any, depends on the individual 
  tokenizer.

2. Custom Tokenizers

  FTS3 allows users to provide custom tokenizer implementations. The 
  interface used to create a new tokenizer is defined and described in 
  the fts3_tokenizer.h source file.

  Registering a new FTS3 tokenizer is similar to registering a new 
  virtual table module with SQLite. The user passes a pointer to a
  structure containing pointers to various callback functions that
  make up the implementation of the new tokenizer type. For tokenizers,
  the structure (defined in fts3_tokenizer.h) is called
  "sqlite3_tokenizer_module".

  FTS3 does not expose a C-function that users call to register new
  tokenizer types with a database handle. Instead, the pointer must
  be encoded as an SQL blob value and passed to FTS3 through the SQL
  engine by evaluating a special scalar function, "fts3_tokenizer()".
  The fts3_tokenizer() function may be called with one or two arguments,
  as follows:

    SELECT fts3_tokenizer(<tokenizer-name>);
    SELECT fts3_tokenizer(<tokenizer-name>, <sqlite3_tokenizer_module ptr>);
  
  Where <tokenizer-name> is a string identifying the tokenizer and
  <sqlite3_tokenizer_module ptr> is a pointer to an sqlite3_tokenizer_module
  structure encoded as an SQL blob. If the second argument is present,
  it is registered as tokenizer <tokenizer-name> and a copy of it
  returned. If only one argument is passed, a pointer to the tokenizer
  implementation currently registered as <tokenizer-name> is returned,
  encoded as a blob. Or, if no such tokenizer exists, an SQL exception
  (error) is raised.

  SECURITY: If the fts3 extension is used in an environment where potentially
    malicious users may execute arbitrary SQL (i.e. gears), they should be
    prevented from invoking the fts3_tokenizer() function, possibly using the
    authorisation callback.

  See "Sample code" below for an example of calling the fts3_tokenizer()
  function from C code.

3. ICU Library Tokenizers

  If this extension is compiled with the SQLITE_ENABLE_ICU pre-processor 
  symbol defined, then there exists a built-in tokenizer named "icu" 
  implemented using the ICU library. The first argument passed to the
  xCreate() method (see fts3_tokenizer.h) of this tokenizer may be
  an ICU locale identifier. For example "tr_TR" for Turkish as used
  in Turkey, or "en_AU" for English as used in Australia. For example:

    "CREATE VIRTUAL TABLE thai_text USING fts3(text, tokenizer icu th_TH)"

  The ICU tokenizer implementation is very simple. It splits the input
  text according to the ICU rules for finding word boundaries and discards
  any tokens that consist entirely of white-space. This may be suitable
  for some applications in some locales, but not all. If more complex
  processing is required, for example to implement stemming or 
  discard punctuation, this can be done by creating a tokenizer 
  implementation that uses the ICU tokenizer as part of its implementation.

  When using the ICU tokenizer this way, it is safe to overwrite the
  contents of the strings returned by the xNext() method (see
  fts3_tokenizer.h).

4. Sample code.

  The following two code samples illustrate the way C code should invoke
  the fts3_tokenizer() scalar function:

      int registerTokenizer(
        sqlite3 *db, 
        char *zName, 
        const sqlite3_tokenizer_module *p
      ){
        int rc;
        sqlite3_stmt *pStmt;
        const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
      
        rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
        if( rc!=SQLITE_OK ){
          return rc;
        }
      
        sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
        sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
        sqlite3_step(pStmt);
      
        return sqlite3_finalize(pStmt);
      }
      
      int queryTokenizer(
        sqlite3 *db, 
        char *zName,  
        const sqlite3_tokenizer_module **pp
      ){
        int rc;
        sqlite3_stmt *pStmt;
        const char zSql[] = "SELECT fts3_tokenizer(?)";
      
        *pp = 0;
        rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
        if( rc!=SQLITE_OK ){
          return rc;
        }
      
        sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
        if( SQLITE_ROW==sqlite3_step(pStmt) ){
          if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
            memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
          }
        }
      
        return sqlite3_finalize(pStmt);
      }

Added ext/fts3/README.txt.









>
>
>
>
1
2
3
4
This folder contains source code to the second full-text search
extension for SQLite.  While the API is the same, this version uses a
substantially different storage schema from fts1, so tables will need
to be rebuilt.

Added ext/fts3/fts3.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is an SQLite module implementing full-text search.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS3 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS3 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
*/

/* TODO(shess) Consider exporting this comment to an HTML file or the
** wiki.
*/
/* The full-text index is stored in a series of b+tree (-like)
** structures called segments which map terms to doclists.  The
** structures are like b+trees in layout, but are constructed from the
** bottom up in optimal fashion and are not updatable.  Since trees
** are built from the bottom up, things will be described from the
** bottom up.
**
**
**** Varints ****
** The basic unit of encoding is a variable-length integer called a
** varint.  We encode variable-length integers in little-endian order
** using seven bits * per byte as follows:
**
** KEY:
**         A = 0xxxxxxx    7 bits of data and one flag bit
**         B = 1xxxxxxx    7 bits of data and one flag bit
**
**  7 bits - A
** 14 bits - BA
** 21 bits - BBA
** and so on.
**
** This is identical to how sqlite encodes varints (see util.c).
**
**
**** Document lists ****
** A doclist (document list) holds a docid-sorted list of hits for a
** given term.  Doclists hold docids, and can optionally associate
** token positions and offsets with docids.
**
** A DL_POSITIONS_OFFSETS doclist is stored like this:
**
** array {
**   varint docid;
**   array {                (position list for column 0)
**     varint position;     (delta from previous position plus POS_BASE)
**     varint startOffset;  (delta from previous startOffset)
**     varint endOffset;    (delta from startOffset)
**   }
**   array {
**     varint POS_COLUMN;   (marks start of position list for new column)
**     varint column;       (index of new column)
**     array {
**       varint position;   (delta from previous position plus POS_BASE)
**       varint startOffset;(delta from previous startOffset)
**       varint endOffset;  (delta from startOffset)
**     }
**   }
**   varint POS_END;        (marks end of positions for this document.
** }
**
** Here, array { X } means zero or more occurrences of X, adjacent in
** memory.  A "position" is an index of a token in the token stream
** generated by the tokenizer, while an "offset" is a byte offset,
** both based at 0.  Note that POS_END and POS_COLUMN occur in the
** same logical place as the position element, and act as sentinals
** ending a position list array.
**
** A DL_POSITIONS doclist omits the startOffset and endOffset
** information.  A DL_DOCIDS doclist omits both the position and
** offset information, becoming an array of varint-encoded docids.
**
** On-disk data is stored as type DL_DEFAULT, so we don't serialize
** the type.  Due to how deletion is implemented in the segmentation
** system, on-disk doclists MUST store at least positions.
**
**
**** Segment leaf nodes ****
** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
** nodes are written using LeafWriter, and read using LeafReader (to
** iterate through a single leaf node's data) and LeavesReader (to
** iterate through a segment's entire leaf layer).  Leaf nodes have
** the format:
**
** varint iHeight;             (height from leaf level, always 0)
** varint nTerm;               (length of first term)
** char pTerm[nTerm];          (content of first term)
** varint nDoclist;            (length of term's associated doclist)
** char pDoclist[nDoclist];    (content of doclist)
** array {
**                             (further terms are delta-encoded)
**   varint nPrefix;           (length of prefix shared with previous term)
**   varint nSuffix;           (length of unshared suffix)
**   char pTermSuffix[nSuffix];(unshared suffix of next term)
**   varint nDoclist;          (length of term's associated doclist)
**   char pDoclist[nDoclist];  (content of doclist)
** }
**
** Here, array { X } means zero or more occurrences of X, adjacent in
** memory.
**
** Leaf nodes are broken into blocks which are stored contiguously in
** the %_segments table in sorted order.  This means that when the end
** of a node is reached, the next term is in the node with the next
** greater node id.
**
** New data is spilled to a new leaf node when the current node
** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
** larger than STANDALONE_MIN (default 1024) is placed in a standalone
** node (a leaf node with a single term and doclist).  The goal of
** these settings is to pack together groups of small doclists while
** making it efficient to directly access large doclists.  The
** assumption is that large doclists represent terms which are more
** likely to be query targets.
**
** TODO(shess) It may be useful for blocking decisions to be more
** dynamic.  For instance, it may make more sense to have a 2.5k leaf
** node rather than splitting into 2k and .5k nodes.  My intuition is
** that this might extend through 2x or 4x the pagesize.
**
**
**** Segment interior nodes ****
** Segment interior nodes store blockids for subtree nodes and terms
** to describe what data is stored by the each subtree.  Interior
** nodes are written using InteriorWriter, and read using
** InteriorReader.  InteriorWriters are created as needed when
** SegmentWriter creates new leaf nodes, or when an interior node
** itself grows too big and must be split.  The format of interior
** nodes:
**
** varint iHeight;           (height from leaf level, always >0)
** varint iBlockid;          (block id of node's leftmost subtree)
** optional {
**   varint nTerm;           (length of first term)
**   char pTerm[nTerm];      (content of first term)
**   array {
**                                (further terms are delta-encoded)
**     varint nPrefix;            (length of shared prefix with previous term)
**     varint nSuffix;            (length of unshared suffix)
**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
**   }
** }
**
** Here, optional { X } means an optional element, while array { X }
** means zero or more occurrences of X, adjacent in memory.
**
** An interior node encodes n terms separating n+1 subtrees.  The
** subtree blocks are contiguous, so only the first subtree's blockid
** is encoded.  The subtree at iBlockid will contain all terms less
** than the first term encoded (or all terms if no term is encoded).
** Otherwise, for terms greater than or equal to pTerm[i] but less
** than pTerm[i+1], the subtree for that term will be rooted at
** iBlockid+i.  Interior nodes only store enough term data to
** distinguish adjacent children (if the rightmost term of the left
** child is "something", and the leftmost term of the right child is
** "wicked", only "w" is stored).
**
** New data is spilled to a new interior node at the same height when
** the current node exceeds INTERIOR_MAX bytes (default 2048).
** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
** interior nodes and making the tree too skinny.  The interior nodes
** at a given height are naturally tracked by interior nodes at
** height+1, and so on.
**
**
**** Segment directory ****
** The segment directory in table %_segdir stores meta-information for
** merging and deleting segments, and also the root node of the
** segment's tree.
**
** The root node is the top node of the segment's tree after encoding
** the entire segment, restricted to ROOT_MAX bytes (default 1024).
** This could be either a leaf node or an interior node.  If the top
** node requires more than ROOT_MAX bytes, it is flushed to %_segments
** and a new root interior node is generated (which should always fit
** within ROOT_MAX because it only needs space for 2 varints, the
** height and the blockid of the previous root).
**
** The meta-information in the segment directory is:
**   level               - segment level (see below)
**   idx                 - index within level
**                       - (level,idx uniquely identify a segment)
**   start_block         - first leaf node
**   leaves_end_block    - last leaf node
**   end_block           - last block (including interior nodes)
**   root                - contents of root node
**
** If the root node is a leaf node, then start_block,
** leaves_end_block, and end_block are all 0.
**
**
**** Segment merging ****
** To amortize update costs, segments are grouped into levels and
** merged in batches.  Each increase in level represents exponentially
** more documents.
**
** New documents (actually, document updates) are tokenized and
** written individually (using LeafWriter) to a level 0 segment, with
** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
** level 0 segments are merged into a single level 1 segment.  Level 1
** is populated like level 0, and eventually MERGE_COUNT level 1
** segments are merged to a single level 2 segment (representing
** MERGE_COUNT^2 updates), and so on.
**
** A segment merge traverses all segments at a given level in
** parallel, performing a straightforward sorted merge.  Since segment
** leaf nodes are written in to the %_segments table in order, this
** merge traverses the underlying sqlite disk structures efficiently.
** After the merge, all segment blocks from the merged level are
** deleted.
**
** MERGE_COUNT controls how often we merge segments.  16 seems to be
** somewhat of a sweet spot for insertion performance.  32 and 64 show
** very similar performance numbers to 16 on insertion, though they're
** a tiny bit slower (perhaps due to more overhead in merge-time
** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
** 16, 2 about 66% slower than 16.
**
** At query time, high MERGE_COUNT increases the number of segments
** which need to be scanned and merged.  For instance, with 100k docs
** inserted:
**
**    MERGE_COUNT   segments
**       16           25
**        8           12
**        4           10
**        2            6
**
** This appears to have only a moderate impact on queries for very
** frequent terms (which are somewhat dominated by segment merge
** costs), and infrequent and non-existent terms still seem to be fast
** even with many segments.
**
** TODO(shess) That said, it would be nice to have a better query-side
** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
** optimizations to things like doclist merging will swing the sweet
** spot around.
**
**
**
**** Handling of deletions and updates ****
** Since we're using a segmented structure, with no docid-oriented
** index into the term index, we clearly cannot simply update the term
** index when a document is deleted or updated.  For deletions, we
** write an empty doclist (varint(docid) varint(POS_END)), for updates
** we simply write the new doclist.  Segment merges overwrite older
** data for a particular docid with newer data, so deletes or updates
** will eventually overtake the earlier data and knock it out.  The
** query logic likewise merges doclists so that newer data knocks out
** older data.
**
** TODO(shess) Provide a VACUUM type operation to clear out all
** deletions and duplications.  This would basically be a forced merge
** into a single segment.
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)

#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
# define SQLITE_CORE 1
#endif

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts3.h"
#include "fts3_expr.h"
#include "fts3_hash.h"
#include "fts3_tokenizer.h"
#ifndef SQLITE_CORE 
# include "sqlite3ext.h"
  SQLITE_EXTENSION_INIT1
#endif


/* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
** would be nice to order the file better, perhaps something along the
** lines of:
**
**  - utility functions
**  - table setup functions
**  - table update functions
**  - table query functions
**
** Put the query functions last because they're likely to reference
** typedefs or functions from the table update section.
*/

#if 0
# define FTSTRACE(A)  printf A; fflush(stdout)
#else
# define FTSTRACE(A)
#endif

/* It is not safe to call isspace(), tolower(), or isalnum() on
** hi-bit-set characters.  This is the same solution used in the
** tokenizer.
*/
/* TODO(shess) The snippet-generation code should be using the
** tokenizer-generated tokens rather than doing its own local
** tokenization.
*/
/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
static int safe_isspace(char c){
  return (c&0x80)==0 ? isspace(c) : 0;
}
static int safe_tolower(char c){
  return (c&0x80)==0 ? tolower(c) : c;
}
static int safe_isalnum(char c){
  return (c&0x80)==0 ? isalnum(c) : 0;
}

typedef enum DocListType {
  DL_DOCIDS,              /* docids only */
  DL_POSITIONS,           /* docids + positions */
  DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
} DocListType;

/*
** By default, only positions and not offsets are stored in the doclists.
** To change this so that offsets are stored too, compile with
**
**          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
**
** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
** into (no deletes or updates).
*/
#ifndef DL_DEFAULT
# define DL_DEFAULT DL_POSITIONS
#endif

enum {
  POS_END = 0,        /* end of this position list */
  POS_COLUMN,         /* followed by new column number */
  POS_BASE
};

/* MERGE_COUNT controls how often we merge segments (see comment at
** top of file).
*/
#define MERGE_COUNT 16

/* utility functions */

/* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
** record to prevent errors of the form:
**
** my_function(SomeType *b){
**   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
** }
*/
/* TODO(shess) Obvious candidates for a header file. */
#define CLEAR(b) memset(b, '\0', sizeof(*(b)))

#ifndef NDEBUG
#  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
#else
#  define SCRAMBLE(b)
#endif

/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
#define VARINT_MAX 10

/* Write a 64-bit variable-length integer to memory starting at p[0].
 * The length of data written will be between 1 and VARINT_MAX bytes.
 * The number of bytes written is returned. */
static int fts3PutVarint(char *p, sqlite_int64 v){
  unsigned char *q = (unsigned char *) p;
  sqlite_uint64 vu = v;
  do{
    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
    vu >>= 7;
  }while( vu!=0 );
  q[-1] &= 0x7f;  /* turn off high bit in final byte */
  assert( q - (unsigned char *)p <= VARINT_MAX );
  return (int) (q - (unsigned char *)p);
}

/* Read a 64-bit variable-length integer from memory starting at p[0].
 * Return the number of bytes read, or 0 on error.
 * The value is stored in *v. */
static int fts3GetVarint(const char *p, sqlite_int64 *v){
  const unsigned char *q = (const unsigned char *) p;
  sqlite_uint64 x = 0, y = 1;
  while( (*q & 0x80) == 0x80 ){
    x += y * (*q++ & 0x7f);
    y <<= 7;
    if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
      assert( 0 );
      return 0;
    }
  }
  x += y * (*q++);
  *v = (sqlite_int64) x;
  return (int) (q - (unsigned char *)p);
}

static int fts3GetVarint32(const char *p, int *pi){
 sqlite_int64 i;
 int ret = fts3GetVarint(p, &i);
 *pi = (int) i;
 assert( *pi==i );
 return ret;
}

/*******************************************************************/
/* DataBuffer is used to collect data into a buffer in piecemeal
** fashion.  It implements the usual distinction between amount of
** data currently stored (nData) and buffer capacity (nCapacity).
**
** dataBufferInit - create a buffer with given initial capacity.
** dataBufferReset - forget buffer's data, retaining capacity.
** dataBufferDestroy - free buffer's data.
** dataBufferSwap - swap contents of two buffers.
** dataBufferExpand - expand capacity without adding data.
** dataBufferAppend - append data.
** dataBufferAppend2 - append two pieces of data at once.
** dataBufferReplace - replace buffer's data.
*/
typedef struct DataBuffer {
  char *pData;          /* Pointer to malloc'ed buffer. */
  int nCapacity;        /* Size of pData buffer. */
  int nData;            /* End of data loaded into pData. */
} DataBuffer;

static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
  assert( nCapacity>=0 );
  pBuffer->nData = 0;
  pBuffer->nCapacity = nCapacity;
  pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
}
static void dataBufferReset(DataBuffer *pBuffer){
  pBuffer->nData = 0;
}
static void dataBufferDestroy(DataBuffer *pBuffer){
  if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
  SCRAMBLE(pBuffer);
}
static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
  DataBuffer tmp = *pBuffer1;
  *pBuffer1 = *pBuffer2;
  *pBuffer2 = tmp;
}
static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
  assert( nAddCapacity>0 );
  /* TODO(shess) Consider expanding more aggressively.  Note that the
  ** underlying malloc implementation may take care of such things for
  ** us already.
  */
  if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
    pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
    pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
  }
}
static void dataBufferAppend(DataBuffer *pBuffer,
                             const char *pSource, int nSource){
  assert( nSource>0 && pSource!=NULL );
  dataBufferExpand(pBuffer, nSource);
  memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
  pBuffer->nData += nSource;
}
static void dataBufferAppend2(DataBuffer *pBuffer,
                              const char *pSource1, int nSource1,
                              const char *pSource2, int nSource2){
  assert( nSource1>0 && pSource1!=NULL );
  assert( nSource2>0 && pSource2!=NULL );
  dataBufferExpand(pBuffer, nSource1+nSource2);
  memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
  memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
  pBuffer->nData += nSource1+nSource2;
}
static void dataBufferReplace(DataBuffer *pBuffer,
                              const char *pSource, int nSource){
  dataBufferReset(pBuffer);
  dataBufferAppend(pBuffer, pSource, nSource);
}

/* StringBuffer is a null-terminated version of DataBuffer. */
typedef struct StringBuffer {
  DataBuffer b;            /* Includes null terminator. */
} StringBuffer;

static void initStringBuffer(StringBuffer *sb){
  dataBufferInit(&sb->b, 100);
  dataBufferReplace(&sb->b, "", 1);
}
static int stringBufferLength(StringBuffer *sb){
  return sb->b.nData-1;
}
static char *stringBufferData(StringBuffer *sb){
  return sb->b.pData;
}
static void stringBufferDestroy(StringBuffer *sb){
  dataBufferDestroy(&sb->b);
}

static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
  assert( sb->b.nData>0 );
  if( nFrom>0 ){
    sb->b.nData--;
    dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
  }
}
static void append(StringBuffer *sb, const char *zFrom){
  nappend(sb, zFrom, strlen(zFrom));
}

/* Append a list of strings separated by commas. */
static void appendList(StringBuffer *sb, int nString, char **azString){
  int i;
  for(i=0; i<nString; ++i){
    if( i>0 ) append(sb, ", ");
    append(sb, azString[i]);
  }
}

static int endsInWhiteSpace(StringBuffer *p){
  return stringBufferLength(p)>0 &&
    safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
}

/* If the StringBuffer ends in something other than white space, add a
** single space character to the end.
*/
static void appendWhiteSpace(StringBuffer *p){
  if( stringBufferLength(p)==0 ) return;
  if( !endsInWhiteSpace(p) ) append(p, " ");
}

/* Remove white space from the end of the StringBuffer */
static void trimWhiteSpace(StringBuffer *p){
  while( endsInWhiteSpace(p) ){
    p->b.pData[--p->b.nData-1] = '\0';
  }
}

/*******************************************************************/
/* DLReader is used to read document elements from a doclist.  The
** current docid is cached, so dlrDocid() is fast.  DLReader does not
** own the doclist buffer.
**
** dlrAtEnd - true if there's no more data to read.
** dlrDocid - docid of current document.
** dlrDocData - doclist data for current document (including docid).
** dlrDocDataBytes - length of same.
** dlrAllDataBytes - length of all remaining data.
** dlrPosData - position data for current document.
** dlrPosDataLen - length of pos data for current document (incl POS_END).
** dlrStep - step to current document.
** dlrInit - initial for doclist of given type against given data.
** dlrDestroy - clean up.
**
** Expected usage is something like:
**
**   DLReader reader;
**   dlrInit(&reader, pData, nData);
**   while( !dlrAtEnd(&reader) ){
**     // calls to dlrDocid() and kin.
**     dlrStep(&reader);
**   }
**   dlrDestroy(&reader);
*/
typedef struct DLReader {
  DocListType iType;
  const char *pData;
  int nData;

  sqlite_int64 iDocid;
  int nElement;
} DLReader;

static int dlrAtEnd(DLReader *pReader){
  assert( pReader->nData>=0 );
  return pReader->nData==0;
}
static sqlite_int64 dlrDocid(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->iDocid;
}
static const char *dlrDocData(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->pData;
}
static int dlrDocDataBytes(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->nElement;
}
static int dlrAllDataBytes(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );
  return pReader->nData;
}
/* TODO(shess) Consider adding a field to track iDocid varint length
** to make these two functions faster.  This might matter (a tiny bit)
** for queries.
*/
static const char *dlrPosData(DLReader *pReader){
  sqlite_int64 iDummy;
  int n = fts3GetVarint(pReader->pData, &iDummy);
  assert( !dlrAtEnd(pReader) );
  return pReader->pData+n;
}
static int dlrPosDataLen(DLReader *pReader){
  sqlite_int64 iDummy;
  int n = fts3GetVarint(pReader->pData, &iDummy);
  assert( !dlrAtEnd(pReader) );
  return pReader->nElement-n;
}
static void dlrStep(DLReader *pReader){
  assert( !dlrAtEnd(pReader) );

  /* Skip past current doclist element. */
  assert( pReader->nElement<=pReader->nData );
  pReader->pData += pReader->nElement;
  pReader->nData -= pReader->nElement;

  /* If there is more data, read the next doclist element. */
  if( pReader->nData!=0 ){
    sqlite_int64 iDocidDelta;
    int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
    pReader->iDocid += iDocidDelta;
    if( pReader->iType>=DL_POSITIONS ){
      assert( n<pReader->nData );
      while( 1 ){
        n += fts3GetVarint32(pReader->pData+n, &iDummy);
        assert( n<=pReader->nData );
        if( iDummy==POS_END ) break;
        if( iDummy==POS_COLUMN ){
          n += fts3GetVarint32(pReader->pData+n, &iDummy);
          assert( n<pReader->nData );
        }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
          n += fts3GetVarint32(pReader->pData+n, &iDummy);
          n += fts3GetVarint32(pReader->pData+n, &iDummy);
          assert( n<pReader->nData );
        }
      }
    }
    pReader->nElement = n;
    assert( pReader->nElement<=pReader->nData );
  }
}
static void dlrInit(DLReader *pReader, DocListType iType,
                    const char *pData, int nData){
  assert( pData!=NULL && nData!=0 );
  pReader->iType = iType;
  pReader->pData = pData;
  pReader->nData = nData;
  pReader->nElement = 0;
  pReader->iDocid = 0;

  /* Load the first element's data.  There must be a first element. */
  dlrStep(pReader);
}
static void dlrDestroy(DLReader *pReader){
  SCRAMBLE(pReader);
}

#ifndef NDEBUG
/* Verify that the doclist can be validly decoded.  Also returns the
** last docid found because it is convenient in other assertions for
** DLWriter.
*/
static void docListValidate(DocListType iType, const char *pData, int nData,
                            sqlite_int64 *pLastDocid){
  sqlite_int64 iPrevDocid = 0;
  assert( nData>0 );
  assert( pData!=0 );
  assert( pData+nData>pData );
  while( nData!=0 ){
    sqlite_int64 iDocidDelta;
    int n = fts3GetVarint(pData, &iDocidDelta);
    iPrevDocid += iDocidDelta;
    if( iType>DL_DOCIDS ){
      int iDummy;
      while( 1 ){
        n += fts3GetVarint32(pData+n, &iDummy);
        if( iDummy==POS_END ) break;
        if( iDummy==POS_COLUMN ){
          n += fts3GetVarint32(pData+n, &iDummy);
        }else if( iType>DL_POSITIONS ){
          n += fts3GetVarint32(pData+n, &iDummy);
          n += fts3GetVarint32(pData+n, &iDummy);
        }
        assert( n<=nData );
      }
    }
    assert( n<=nData );
    pData += n;
    nData -= n;
  }
  if( pLastDocid ) *pLastDocid = iPrevDocid;
}
#define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
#else
#define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
#endif

/*******************************************************************/
/* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
** always appends to the buffer and does not own it.
**
** dlwInit - initialize to write a given type doclistto a buffer.
** dlwDestroy - clear the writer's memory.  Does not free buffer.
** dlwAppend - append raw doclist data to buffer.
** dlwCopy - copy next doclist from reader to writer.
** dlwAdd - construct doclist element and append to buffer.
**    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
*/
typedef struct DLWriter {
  DocListType iType;
  DataBuffer *b;
  sqlite_int64 iPrevDocid;
#ifndef NDEBUG
  int has_iPrevDocid;
#endif
} DLWriter;

static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
  pWriter->b = b;
  pWriter->iType = iType;
  pWriter->iPrevDocid = 0;
#ifndef NDEBUG
  pWriter->has_iPrevDocid = 0;
#endif
}
static void dlwDestroy(DLWriter *pWriter){
  SCRAMBLE(pWriter);
}
/* iFirstDocid is the first docid in the doclist in pData.  It is
** needed because pData may point within a larger doclist, in which
** case the first item would be delta-encoded.
**
** iLastDocid is the final docid in the doclist in pData.  It is
** needed to create the new iPrevDocid for future delta-encoding.  The
** code could decode the passed doclist to recreate iLastDocid, but
** the only current user (docListMerge) already has decoded this
** information.
*/
/* TODO(shess) This has become just a helper for docListMerge.
** Consider a refactor to make this cleaner.
*/
static void dlwAppend(DLWriter *pWriter,
                      const char *pData, int nData,
                      sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
  sqlite_int64 iDocid = 0;
  char c[VARINT_MAX];
  int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
#ifndef NDEBUG
  sqlite_int64 iLastDocidDelta;
#endif

  /* Recode the initial docid as delta from iPrevDocid. */
  nFirstOld = fts3GetVarint(pData, &iDocid);
  assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
  nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);

  /* Verify that the incoming doclist is valid AND that it ends with
  ** the expected docid.  This is essential because we'll trust this
  ** docid in future delta-encoding.
  */
  ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
  assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );

  /* Append recoded initial docid and everything else.  Rest of docids
  ** should have been delta-encoded from previous initial docid.
  */
  if( nFirstOld<nData ){
    dataBufferAppend2(pWriter->b, c, nFirstNew,
                      pData+nFirstOld, nData-nFirstOld);
  }else{
    dataBufferAppend(pWriter->b, c, nFirstNew);
  }
  pWriter->iPrevDocid = iLastDocid;
}
static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
  dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
            dlrDocid(pReader), dlrDocid(pReader));
}
static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
  char c[VARINT_MAX];
  int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);

  /* Docids must ascend. */
  assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
  assert( pWriter->iType==DL_DOCIDS );

  dataBufferAppend(pWriter->b, c, n);
  pWriter->iPrevDocid = iDocid;
#ifndef NDEBUG
  pWriter->has_iPrevDocid = 1;
#endif
}

/*******************************************************************/
/* PLReader is used to read data from a document's position list.  As
** the caller steps through the list, data is cached so that varints
** only need to be decoded once.
**
** plrInit, plrDestroy - create/destroy a reader.
** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
** plrAtEnd - at end of stream, only call plrDestroy once true.
** plrStep - step to the next element.
*/
typedef struct PLReader {
  /* These refer to the next position's data.  nData will reach 0 when
  ** reading the last position, so plrStep() signals EOF by setting
  ** pData to NULL.
  */
  const char *pData;
  int nData;

  DocListType iType;
  int iColumn;         /* the last column read */
  int iPosition;       /* the last position read */
  int iStartOffset;    /* the last start offset read */
  int iEndOffset;      /* the last end offset read */
} PLReader;

static int plrAtEnd(PLReader *pReader){
  return pReader->pData==NULL;
}
static int plrColumn(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iColumn;
}
static int plrPosition(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iPosition;
}
static int plrStartOffset(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iStartOffset;
}
static int plrEndOffset(PLReader *pReader){
  assert( !plrAtEnd(pReader) );
  return pReader->iEndOffset;
}
static void plrStep(PLReader *pReader){
  int i, n;

  assert( !plrAtEnd(pReader) );

  if( pReader->nData==0 ){
    pReader->pData = NULL;
    return;
  }

  n = fts3GetVarint32(pReader->pData, &i);
  if( i==POS_COLUMN ){
    n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
    pReader->iPosition = 0;
    pReader->iStartOffset = 0;
    n += fts3GetVarint32(pReader->pData+n, &i);
  }
  /* Should never see adjacent column changes. */
  assert( i!=POS_COLUMN );

  if( i==POS_END ){
    pReader->nData = 0;
    pReader->pData = NULL;
    return;
  }

  pReader->iPosition += i-POS_BASE;
  if( pReader->iType==DL_POSITIONS_OFFSETS ){
    n += fts3GetVarint32(pReader->pData+n, &i);
    pReader->iStartOffset += i;
    n += fts3GetVarint32(pReader->pData+n, &i);
    pReader->iEndOffset = pReader->iStartOffset+i;
  }
  assert( n<=pReader->nData );
  pReader->pData += n;
  pReader->nData -= n;
}

static void plrInit(PLReader *pReader, DLReader *pDLReader){
  pReader->pData = dlrPosData(pDLReader);
  pReader->nData = dlrPosDataLen(pDLReader);
  pReader->iType = pDLReader->iType;
  pReader->iColumn = 0;
  pReader->iPosition = 0;
  pReader->iStartOffset = 0;
  pReader->iEndOffset = 0;
  plrStep(pReader);
}
static void plrDestroy(PLReader *pReader){
  SCRAMBLE(pReader);
}

/*******************************************************************/
/* PLWriter is used in constructing a document's position list.  As a
** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
** PLWriter writes to the associated DLWriter's buffer.
**
** plwInit - init for writing a document's poslist.
** plwDestroy - clear a writer.
** plwAdd - append position and offset information.
** plwCopy - copy next position's data from reader to writer.
** plwTerminate - add any necessary doclist terminator.
**
** Calling plwAdd() after plwTerminate() may result in a corrupt
** doclist.
*/
/* TODO(shess) Until we've written the second item, we can cache the
** first item's information.  Then we'd have three states:
**
** - initialized with docid, no positions.
** - docid and one position.
** - docid and multiple positions.
**
** Only the last state needs to actually write to dlw->b, which would
** be an improvement in the DLCollector case.
*/
typedef struct PLWriter {
  DLWriter *dlw;

  int iColumn;    /* the last column written */
  int iPos;       /* the last position written */
  int iOffset;    /* the last start offset written */
} PLWriter;

/* TODO(shess) In the case where the parent is reading these values
** from a PLReader, we could optimize to a copy if that PLReader has
** the same type as pWriter.
*/
static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
                   int iStartOffset, int iEndOffset){
  /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
  ** iStartOffsetDelta, and iEndOffsetDelta.
  */
  char c[5*VARINT_MAX];
  int n = 0;

  /* Ban plwAdd() after plwTerminate(). */
  assert( pWriter->iPos!=-1 );

  if( pWriter->dlw->iType==DL_DOCIDS ) return;

  if( iColumn!=pWriter->iColumn ){
    n += fts3PutVarint(c+n, POS_COLUMN);
    n += fts3PutVarint(c+n, iColumn);
    pWriter->iColumn = iColumn;
    pWriter->iPos = 0;
    pWriter->iOffset = 0;
  }
  assert( iPos>=pWriter->iPos );
  n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
  pWriter->iPos = iPos;
  if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
    assert( iStartOffset>=pWriter->iOffset );
    n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
    pWriter->iOffset = iStartOffset;
    assert( iEndOffset>=iStartOffset );
    n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
  }
  dataBufferAppend(pWriter->dlw->b, c, n);
}
static void plwCopy(PLWriter *pWriter, PLReader *pReader){
  plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
         plrStartOffset(pReader), plrEndOffset(pReader));
}
static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
  char c[VARINT_MAX];
  int n;

  pWriter->dlw = dlw;

  /* Docids must ascend. */
  assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
  n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
  dataBufferAppend(pWriter->dlw->b, c, n);
  pWriter->dlw->iPrevDocid = iDocid;
#ifndef NDEBUG
  pWriter->dlw->has_iPrevDocid = 1;
#endif

  pWriter->iColumn = 0;
  pWriter->iPos = 0;
  pWriter->iOffset = 0;
}
/* TODO(shess) Should plwDestroy() also terminate the doclist?  But
** then plwDestroy() would no longer be just a destructor, it would
** also be doing work, which isn't consistent with the overall idiom.
** Another option would be for plwAdd() to always append any necessary
** terminator, so that the output is always correct.  But that would
** add incremental work to the common case with the only benefit being
** API elegance.  Punt for now.
*/
static void plwTerminate(PLWriter *pWriter){
  if( pWriter->dlw->iType>DL_DOCIDS ){
    char c[VARINT_MAX];
    int n = fts3PutVarint(c, POS_END);
    dataBufferAppend(pWriter->dlw->b, c, n);
  }
#ifndef NDEBUG
  /* Mark as terminated for assert in plwAdd(). */
  pWriter->iPos = -1;
#endif
}
static void plwDestroy(PLWriter *pWriter){
  SCRAMBLE(pWriter);
}

/*******************************************************************/
/* DLCollector wraps PLWriter and DLWriter to provide a
** dynamically-allocated doclist area to use during tokenization.
**
** dlcNew - malloc up and initialize a collector.
** dlcDelete - destroy a collector and all contained items.
** dlcAddPos - append position and offset information.
** dlcAddDoclist - add the collected doclist to the given buffer.
** dlcNext - terminate the current document and open another.
*/
typedef struct DLCollector {
  DataBuffer b;
  DLWriter dlw;
  PLWriter plw;
} DLCollector;

/* TODO(shess) This could also be done by calling plwTerminate() and
** dataBufferAppend().  I tried that, expecting nominal performance
** differences, but it seemed to pretty reliably be worth 1% to code
** it this way.  I suspect it is the incremental malloc overhead (some
** percentage of the plwTerminate() calls will cause a realloc), so
** this might be worth revisiting if the DataBuffer implementation
** changes.
*/
static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
  if( pCollector->dlw.iType>DL_DOCIDS ){
    char c[VARINT_MAX];
    int n = fts3PutVarint(c, POS_END);
    dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
  }else{
    dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
  }
}
static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
  plwTerminate(&pCollector->plw);
  plwDestroy(&pCollector->plw);
  plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
}
static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
                      int iStartOffset, int iEndOffset){
  plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
}

static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
  DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
  dataBufferInit(&pCollector->b, 0);
  dlwInit(&pCollector->dlw, iType, &pCollector->b);
  plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  return pCollector;
}
static void dlcDelete(DLCollector *pCollector){
  plwDestroy(&pCollector->plw);
  dlwDestroy(&pCollector->dlw);
  dataBufferDestroy(&pCollector->b);
  SCRAMBLE(pCollector);
  sqlite3_free(pCollector);
}


/* Copy the doclist data of iType in pData/nData into *out, trimming
** unnecessary data as we go.  Only columns matching iColumn are
** copied, all columns copied if iColumn is -1.  Elements with no
** matching columns are dropped.  The output is an iOutType doclist.
*/
/* NOTE(shess) This code is only valid after all doclists are merged.
** If this is run before merges, then doclist items which represent
** deletion will be trimmed, and will thus not effect a deletion
** during the merge.
*/
static void docListTrim(DocListType iType, const char *pData, int nData,
                        int iColumn, DocListType iOutType, DataBuffer *out){
  DLReader dlReader;
  DLWriter dlWriter;

  assert( iOutType<=iType );

  dlrInit(&dlReader, iType, pData, nData);
  dlwInit(&dlWriter, iOutType, out);

  while( !dlrAtEnd(&dlReader) ){
    PLReader plReader;
    PLWriter plWriter;
    int match = 0;

    plrInit(&plReader, &dlReader);

    while( !plrAtEnd(&plReader) ){
      if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
        if( !match ){
          plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
          match = 1;
        }
        plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
               plrStartOffset(&plReader), plrEndOffset(&plReader));
      }
      plrStep(&plReader);
    }
    if( match ){
      plwTerminate(&plWriter);
      plwDestroy(&plWriter);
    }

    plrDestroy(&plReader);
    dlrStep(&dlReader);
  }
  dlwDestroy(&dlWriter);
  dlrDestroy(&dlReader);
}

/* Used by docListMerge() to keep doclists in the ascending order by
** docid, then ascending order by age (so the newest comes first).
*/
typedef struct OrderedDLReader {
  DLReader *pReader;

  /* TODO(shess) If we assume that docListMerge pReaders is ordered by
  ** age (which we do), then we could use pReader comparisons to break
  ** ties.
  */
  int idx;
} OrderedDLReader;

/* Order eof to end, then by docid asc, idx desc. */
static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
  if( dlrAtEnd(r1->pReader) ){
    if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
    return 1;                              /* Only r1 atEnd(). */
  }
  if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */

  if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
  if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;

  /* Descending on idx. */
  return r2->idx-r1->idx;
}

/* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
** p[1..n-1] is already sorted.
*/
/* TODO(shess) Is this frequent enough to warrant a binary search?
** Before implementing that, instrument the code to check.  In most
** current usage, I expect that p[0] will be less than p[1] a very
** high proportion of the time.
*/
static void orderedDLReaderReorder(OrderedDLReader *p, int n){
  while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
    OrderedDLReader tmp = p[0];
    p[0] = p[1];
    p[1] = tmp;
    n--;
    p++;
  }
}

/* Given an array of doclist readers, merge their doclist elements
** into out in sorted order (by docid), dropping elements from older
** readers when there is a duplicate docid.  pReaders is assumed to be
** ordered by age, oldest first.
*/
/* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
** be fixed.
*/
static void docListMerge(DataBuffer *out,
                         DLReader *pReaders, int nReaders){
  OrderedDLReader readers[MERGE_COUNT];
  DLWriter writer;
  int i, n;
  const char *pStart = 0;
  int nStart = 0;
  sqlite_int64 iFirstDocid = 0, iLastDocid = 0;

  assert( nReaders>0 );
  if( nReaders==1 ){
    dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
    return;
  }

  assert( nReaders<=MERGE_COUNT );
  n = 0;
  for(i=0; i<nReaders; i++){
    assert( pReaders[i].iType==pReaders[0].iType );
    readers[i].pReader = pReaders+i;
    readers[i].idx = i;
    n += dlrAllDataBytes(&pReaders[i]);
  }
  /* Conservatively size output to sum of inputs.  Output should end
  ** up strictly smaller than input.
  */
  dataBufferExpand(out, n);

  /* Get the readers into sorted order. */
  while( i-->0 ){
    orderedDLReaderReorder(readers+i, nReaders-i);
  }

  dlwInit(&writer, pReaders[0].iType, out);
  while( !dlrAtEnd(readers[0].pReader) ){
    sqlite_int64 iDocid = dlrDocid(readers[0].pReader);

    /* If this is a continuation of the current buffer to copy, extend
    ** that buffer.  memcpy() seems to be more efficient if it has a
    ** lots of data to copy.
    */
    if( dlrDocData(readers[0].pReader)==pStart+nStart ){
      nStart += dlrDocDataBytes(readers[0].pReader);
    }else{
      if( pStart!=0 ){
        dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
      }
      pStart = dlrDocData(readers[0].pReader);
      nStart = dlrDocDataBytes(readers[0].pReader);
      iFirstDocid = iDocid;
    }
    iLastDocid = iDocid;
    dlrStep(readers[0].pReader);

    /* Drop all of the older elements with the same docid. */
    for(i=1; i<nReaders &&
             !dlrAtEnd(readers[i].pReader) &&
             dlrDocid(readers[i].pReader)==iDocid; i++){
      dlrStep(readers[i].pReader);
    }

    /* Get the readers back into order. */
    while( i-->0 ){
      orderedDLReaderReorder(readers+i, nReaders-i);
    }
  }

  /* Copy over any remaining elements. */
  if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  dlwDestroy(&writer);
}

/* Helper function for posListUnion().  Compares the current position
** between left and right, returning as standard C idiom of <0 if
** left<right, >0 if left>right, and 0 if left==right.  "End" always
** compares greater.
*/
static int posListCmp(PLReader *pLeft, PLReader *pRight){
  assert( pLeft->iType==pRight->iType );
  if( pLeft->iType==DL_DOCIDS ) return 0;

  if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
  if( plrAtEnd(pRight) ) return -1;

  if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
  if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;

  if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
  if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
  if( pLeft->iType==DL_POSITIONS ) return 0;

  if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
  if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;

  if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
  if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;

  return 0;
}

/* Write the union of position lists in pLeft and pRight to pOut.
** "Union" in this case meaning "All unique position tuples".  Should
** work with any doclist type, though both inputs and the output
** should be the same type.
*/
static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
  PLReader left, right;
  PLWriter writer;

  assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  assert( pLeft->iType==pRight->iType );
  assert( pLeft->iType==pOut->iType );

  plrInit(&left, pLeft);
  plrInit(&right, pRight);
  plwInit(&writer, pOut, dlrDocid(pLeft));

  while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
    int c = posListCmp(&left, &right);
    if( c<0 ){
      plwCopy(&writer, &left);
      plrStep(&left);
    }else if( c>0 ){
      plwCopy(&writer, &right);
      plrStep(&right);
    }else{
      plwCopy(&writer, &left);
      plrStep(&left);
      plrStep(&right);
    }
  }

  plwTerminate(&writer);
  plwDestroy(&writer);
  plrDestroy(&left);
  plrDestroy(&right);
}

/* Write the union of doclists in pLeft and pRight to pOut.  For
** docids in common between the inputs, the union of the position
** lists is written.  Inputs and outputs are always type DL_DEFAULT.
*/
static void docListUnion(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 ){
    if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
    return;
  }
  if( nRight==0 ){
    dataBufferAppend(pOut, pLeft, nLeft);
    return;
  }

  dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
  dlrInit(&right, DL_DEFAULT, pRight, nRight);
  dlwInit(&writer, DL_DEFAULT, pOut);

  while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
    if( dlrAtEnd(&right) ){
      dlwCopy(&writer, &left);
      dlrStep(&left);
    }else if( dlrAtEnd(&left) ){
      dlwCopy(&writer, &right);
      dlrStep(&right);
    }else if( dlrDocid(&left)<dlrDocid(&right) ){
      dlwCopy(&writer, &left);
      dlrStep(&left);
    }else if( dlrDocid(&left)>dlrDocid(&right) ){
      dlwCopy(&writer, &right);
      dlrStep(&right);
    }else{
      posListUnion(&left, &right, &writer);
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* 
** This function is used as part of the implementation of phrase and
** NEAR matching.
**
** pLeft and pRight are DLReaders positioned to the same docid in
** lists of type DL_POSITION. This function writes an entry to the
** DLWriter pOut for each position in pRight that is less than
** (nNear+1) greater (but not equal to or smaller) than a position 
** in pLeft. For example, if nNear is 0, and the positions contained
** by pLeft and pRight are:
**
**    pLeft:  5 10 15 20
**    pRight: 6  9 17 21
**
** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
** then a positionids "6" and "21" are also added to pOut.
**
** If boolean argument isSaveLeft is true, then positionids are copied
** from pLeft instead of pRight. In the example above, the positions "5"
** and "20" would be added instead of "6" and "21".
*/
static void posListPhraseMerge(
  DLReader *pLeft, 
  DLReader *pRight,
  int nNear,
  int isSaveLeft,
  DLWriter *pOut
){
  PLReader left, right;
  PLWriter writer;
  int match = 0;

  assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  assert( pOut->iType!=DL_POSITIONS_OFFSETS );

  plrInit(&left, pLeft);
  plrInit(&right, pRight);

  while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
    if( plrColumn(&left)<plrColumn(&right) ){
      plrStep(&left);
    }else if( plrColumn(&left)>plrColumn(&right) ){
      plrStep(&right);
    }else if( plrPosition(&left)>=plrPosition(&right) ){
      plrStep(&right);
    }else{
      if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
        if( !match ){
          plwInit(&writer, pOut, dlrDocid(pLeft));
          match = 1;
        }
        if( !isSaveLeft ){
          plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
        }else{
          plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
        }
        plrStep(&right);
      }else{
        plrStep(&left);
      }
    }
  }

  if( match ){
    plwTerminate(&writer);
    plwDestroy(&writer);
  }

  plrDestroy(&left);
  plrDestroy(&right);
}

/*
** Compare the values pointed to by the PLReaders passed as arguments. 
** Return -1 if the value pointed to by pLeft is considered less than
** the value pointed to by pRight, +1 if it is considered greater
** than it, or 0 if it is equal. i.e.
**
**     (*pLeft - *pRight)
**
** A PLReader that is in the EOF condition is considered greater than
** any other. If neither argument is in EOF state, the return value of
** plrColumn() is used. If the plrColumn() values are equal, the
** comparison is on the basis of plrPosition().
*/
static int plrCompare(PLReader *pLeft, PLReader *pRight){
  assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));

  if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
    return (plrAtEnd(pRight) ? -1 : 1);
  }
  if( plrColumn(pLeft)!=plrColumn(pRight) ){
    return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
  }
  if( plrPosition(pLeft)!=plrPosition(pRight) ){
    return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
  }
  return 0;
}

/* We have two doclists with positions:  pLeft and pRight. Depending
** on the value of the nNear parameter, perform either a phrase
** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
** and write the results into pOut.
**
** A phrase intersection means that two documents only match
** if pLeft.iPos+1==pRight.iPos.
**
** A NEAR intersection means that two documents only match if 
** (abs(pLeft.iPos-pRight.iPos)<nNear).
**
** If a NEAR intersection is requested, then the nPhrase argument should
** be passed the number of tokens in the two operands to the NEAR operator
** combined. For example:
**
**       Query syntax               nPhrase
**      ------------------------------------
**       "A B C" NEAR "D E"         5
**       A NEAR B                   2
**
** iType controls the type of data written to pOut.  If iType is
** DL_POSITIONS, the positions are those from pRight.
*/
static void docListPhraseMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
  int nPhrase,          /* Number of tokens in left+right operands to NEAR */
  DocListType iType,    /* Type of doclist to write to pOut */
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 || nRight==0 ) return;

  assert( iType!=DL_POSITIONS_OFFSETS );

  dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
  dlrInit(&right, DL_POSITIONS, pRight, nRight);
  dlwInit(&writer, iType, pOut);

  while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
    if( dlrDocid(&left)<dlrDocid(&right) ){
      dlrStep(&left);
    }else if( dlrDocid(&right)<dlrDocid(&left) ){
      dlrStep(&right);
    }else{
      if( nNear==0 ){
        posListPhraseMerge(&left, &right, 0, 0, &writer);
      }else{
        /* This case occurs when two terms (simple terms or phrases) are
         * connected by a NEAR operator, span (nNear+1). i.e.
         *
         *     '"terrible company" NEAR widget'
         */
        DataBuffer one = {0, 0, 0};
        DataBuffer two = {0, 0, 0};

        DLWriter dlwriter2;
        DLReader dr1 = {0, 0, 0, 0, 0}; 
        DLReader dr2 = {0, 0, 0, 0, 0};

        dlwInit(&dlwriter2, iType, &one);
        posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
        dlwInit(&dlwriter2, iType, &two);
        posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);

        if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
        if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);

        if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
          PLReader pr1 = {0};
          PLReader pr2 = {0};

          PLWriter plwriter;
          plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));

          if( one.nData ) plrInit(&pr1, &dr1);
          if( two.nData ) plrInit(&pr2, &dr2);
          while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
            int iCompare = plrCompare(&pr1, &pr2);
            switch( iCompare ){
              case -1:
                plwCopy(&plwriter, &pr1);
                plrStep(&pr1);
                break;
              case 1:
                plwCopy(&plwriter, &pr2);
                plrStep(&pr2);
                break;
              case 0:
                plwCopy(&plwriter, &pr1);
                plrStep(&pr1);
                plrStep(&pr2);
                break;
            }
          }
          plwTerminate(&plwriter);
        }
        dataBufferDestroy(&one);
        dataBufferDestroy(&two);
      }
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* We have two DL_DOCIDS doclists:  pLeft and pRight.
** Write the intersection of these two doclists into pOut as a
** DL_DOCIDS doclist.
*/
static void docListAndMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 || nRight==0 ) return;

  dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  dlrInit(&right, DL_DOCIDS, pRight, nRight);
  dlwInit(&writer, DL_DOCIDS, pOut);

  while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
    if( dlrDocid(&left)<dlrDocid(&right) ){
      dlrStep(&left);
    }else if( dlrDocid(&right)<dlrDocid(&left) ){
      dlrStep(&right);
    }else{
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* We have two DL_DOCIDS doclists:  pLeft and pRight.
** Write the union of these two doclists into pOut as a
** DL_DOCIDS doclist.
*/
static void docListOrMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 ){
    if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
    return;
  }
  if( nRight==0 ){
    dataBufferAppend(pOut, pLeft, nLeft);
    return;
  }

  dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  dlrInit(&right, DL_DOCIDS, pRight, nRight);
  dlwInit(&writer, DL_DOCIDS, pOut);

  while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
    if( dlrAtEnd(&right) ){
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
    }else if( dlrAtEnd(&left) ){
      dlwAdd(&writer, dlrDocid(&right));
      dlrStep(&right);
    }else if( dlrDocid(&left)<dlrDocid(&right) ){
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
    }else if( dlrDocid(&right)<dlrDocid(&left) ){
      dlwAdd(&writer, dlrDocid(&right));
      dlrStep(&right);
    }else{
      dlwAdd(&writer, dlrDocid(&left));
      dlrStep(&left);
      dlrStep(&right);
    }
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

/* We have two DL_DOCIDS doclists:  pLeft and pRight.
** Write into pOut as DL_DOCIDS doclist containing all documents that
** occur in pLeft but not in pRight.
*/
static void docListExceptMerge(
  const char *pLeft, int nLeft,
  const char *pRight, int nRight,
  DataBuffer *pOut      /* Write the combined doclist here */
){
  DLReader left, right;
  DLWriter writer;

  if( nLeft==0 ) return;
  if( nRight==0 ){
    dataBufferAppend(pOut, pLeft, nLeft);
    return;
  }

  dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  dlrInit(&right, DL_DOCIDS, pRight, nRight);
  dlwInit(&writer, DL_DOCIDS, pOut);

  while( !dlrAtEnd(&left) ){
    while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
      dlrStep(&right);
    }
    if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
      dlwAdd(&writer, dlrDocid(&left));
    }
    dlrStep(&left);
  }

  dlrDestroy(&left);
  dlrDestroy(&right);
  dlwDestroy(&writer);
}

static char *string_dup_n(const char *s, int n){
  char *str = sqlite3_malloc(n + 1);
  memcpy(str, s, n);
  str[n] = '\0';
  return str;
}

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it is not part of the standard C library and
 * may not be available everywhere.) */
static char *string_dup(const char *s){
  return string_dup_n(s, strlen(s));
}

/* Format a string, replacing each occurrence of the % character with
 * zDb.zName.  This may be more convenient than sqlite_mprintf()
 * when one string is used repeatedly in a format string.
 * The caller must free() the returned string. */
static char *string_format(const char *zFormat,
                           const char *zDb, const char *zName){
  const char *p;
  size_t len = 0;
  size_t nDb = strlen(zDb);
  size_t nName = strlen(zName);
  size_t nFullTableName = nDb+1+nName;
  char *result;
  char *r;

  /* first compute length needed */
  for(p = zFormat ; *p ; ++p){
    len += (*p=='%' ? nFullTableName : 1);
  }
  len += 1;  /* for null terminator */

  r = result = sqlite3_malloc(len);
  for(p = zFormat; *p; ++p){
    if( *p=='%' ){
      memcpy(r, zDb, nDb);
      r += nDb;
      *r++ = '.';
      memcpy(r, zName, nName);
      r += nName;
    } else {
      *r++ = *p;
    }
  }
  *r++ = '\0';
  assert( r == result + len );
  return result;
}

static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
                    const char *zFormat){
  char *zCommand = string_format(zFormat, zDb, zName);
  int rc;
  FTSTRACE(("FTS3 sql: %s\n", zCommand));
  rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  sqlite3_free(zCommand);
  return rc;
}

static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
                       sqlite3_stmt **ppStmt, const char *zFormat){
  char *zCommand = string_format(zFormat, zDb, zName);
  int rc;
  FTSTRACE(("FTS3 prepare: %s\n", zCommand));
  rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
  sqlite3_free(zCommand);
  return rc;
}

/* end utility functions */

/* Forward reference */
typedef struct fulltext_vtab fulltext_vtab;

/*
** An instance of the following structure keeps track of generated
** matching-word offset information and snippets.
*/
typedef struct Snippet {
  int nMatch;     /* Total number of matches */
  int nAlloc;     /* Space allocated for aMatch[] */
  struct snippetMatch { /* One entry for each matching term */
    char snStatus;       /* Status flag for use while constructing snippets */
    short int iCol;      /* The column that contains the match */
    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
    int iToken;          /* The index of the matching document token */
    short int nByte;     /* Number of bytes in the term */
    int iStart;          /* The offset to the first character of the term */
  } *aMatch;      /* Points to space obtained from malloc */
  char *zOffset;  /* Text rendering of aMatch[] */
  int nOffset;    /* strlen(zOffset) */
  char *zSnippet; /* Snippet text */
  int nSnippet;   /* strlen(zSnippet) */
} Snippet;


typedef enum QueryType {
  QUERY_GENERIC,   /* table scan */
  QUERY_DOCID,     /* lookup by docid */
  QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
} QueryType;

typedef enum fulltext_statement {
  CONTENT_INSERT_STMT,
  CONTENT_SELECT_STMT,
  CONTENT_UPDATE_STMT,
  CONTENT_DELETE_STMT,
  CONTENT_EXISTS_STMT,

  BLOCK_INSERT_STMT,
  BLOCK_SELECT_STMT,
  BLOCK_DELETE_STMT,
  BLOCK_DELETE_ALL_STMT,

  SEGDIR_MAX_INDEX_STMT,
  SEGDIR_SET_STMT,
  SEGDIR_SELECT_LEVEL_STMT,
  SEGDIR_SPAN_STMT,
  SEGDIR_DELETE_STMT,
  SEGDIR_SELECT_SEGMENT_STMT,
  SEGDIR_SELECT_ALL_STMT,
  SEGDIR_DELETE_ALL_STMT,
  SEGDIR_COUNT_STMT,

  MAX_STMT                     /* Always at end! */
} fulltext_statement;

/* These must exactly match the enum above. */
/* TODO(shess): Is there some risk that a statement will be used in two
** cursors at once, e.g.  if a query joins a virtual table to itself?
** If so perhaps we should move some of these to the cursor object.
*/
static const char *const fulltext_zStatement[MAX_STMT] = {
  /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
  /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
  /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
  /* CONTENT_DELETE */ "delete from %_content where docid = ?",
  /* CONTENT_EXISTS */ "select docid from %_content limit 1",

  /* BLOCK_INSERT */
  "insert into %_segments (blockid, block) values (null, ?)",
  /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
  /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
  /* BLOCK_DELETE_ALL */ "delete from %_segments",

  /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
  /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
  /* SEGDIR_SELECT_LEVEL */
  "select start_block, leaves_end_block, root from %_segdir "
  " where level = ? order by idx",
  /* SEGDIR_SPAN */
  "select min(start_block), max(end_block) from %_segdir "
  " where level = ? and start_block <> 0",
  /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",

  /* NOTE(shess): The first three results of the following two
  ** statements must match.
  */
  /* SEGDIR_SELECT_SEGMENT */
  "select start_block, leaves_end_block, root from %_segdir "
  " where level = ? and idx = ?",
  /* SEGDIR_SELECT_ALL */
  "select start_block, leaves_end_block, root from %_segdir "
  " order by level desc, idx asc",
  /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
  /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
};

/*
** A connection to a fulltext index is an instance of the following
** structure.  The xCreate and xConnect methods create an instance
** of this structure and xDestroy and xDisconnect free that instance.
** All other methods receive a pointer to the structure as one of their
** arguments.
*/
struct fulltext_vtab {
  sqlite3_vtab base;               /* Base class used by SQLite core */
  sqlite3 *db;                     /* The database connection */
  const char *zDb;                 /* logical database name */
  const char *zName;               /* virtual table name */
  int nColumn;                     /* number of columns in virtual table */
  char **azColumn;                 /* column names.  malloced */
  char **azContentColumn;          /* column names in content table; malloced */
  sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */

  /* Precompiled statements which we keep as long as the table is
  ** open.
  */
  sqlite3_stmt *pFulltextStatements[MAX_STMT];

  /* Precompiled statements used for segment merges.  We run a
  ** separate select across the leaf level of each tree being merged.
  */
  sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
  /* The statement used to prepare pLeafSelectStmts. */
#define LEAF_SELECT \
  "select block from %_segments where blockid between ? and ? order by blockid"

  /* These buffer pending index updates during transactions.
  ** nPendingData estimates the memory size of the pending data.  It
  ** doesn't include the hash-bucket overhead, nor any malloc
  ** overhead.  When nPendingData exceeds kPendingThreshold, the
  ** buffer is flushed even before the transaction closes.
  ** pendingTerms stores the data, and is only valid when nPendingData
  ** is >=0 (nPendingData<0 means pendingTerms has not been
  ** initialized).  iPrevDocid is the last docid written, used to make
  ** certain we're inserting in sorted order.
  */
  int nPendingData;
#define kPendingThreshold (1*1024*1024)
  sqlite_int64 iPrevDocid;
  fts3Hash pendingTerms;
};

/*
** When the core wants to do a query, it create a cursor using a
** call to xOpen.  This structure is an instance of a cursor.  It
** is destroyed by xClose.
*/
typedef struct fulltext_cursor {
  sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
  QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
  sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
  int eof;                         /* True if at End Of Results */
  Fts3Expr *pExpr;                 /* Parsed MATCH query string */
  Snippet snippet;                 /* Cached snippet for the current row */
  int iColumn;                     /* Column being searched */
  DataBuffer result;               /* Doclist results from fulltextQuery */
  DLReader reader;                 /* Result reader if result not empty */
} fulltext_cursor;

static fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  return (fulltext_vtab *) c->base.pVtab;
}

static const sqlite3_module fts3Module;   /* forward declaration */

/* Return a dynamically generated statement of the form
 *   insert into %_content (docid, ...) values (?, ...)
 */
static const char *contentInsertStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;

  initStringBuffer(&sb);
  append(&sb, "insert into %_content (docid, ");
  appendList(&sb, v->nColumn, v->azContentColumn);
  append(&sb, ") values (?");
  for(i=0; i<v->nColumn; ++i)
    append(&sb, ", ?");
  append(&sb, ")");
  return stringBufferData(&sb);
}

/* Return a dynamically generated statement of the form
 *   select <content columns> from %_content where docid = ?
 */
static const char *contentSelectStatement(fulltext_vtab *v){
  StringBuffer sb;
  initStringBuffer(&sb);
  append(&sb, "SELECT ");
  appendList(&sb, v->nColumn, v->azContentColumn);
  append(&sb, " FROM %_content WHERE docid = ?");
  return stringBufferData(&sb);
}

/* Return a dynamically generated statement of the form
 *   update %_content set [col_0] = ?, [col_1] = ?, ...
 *                    where docid = ?
 */
static const char *contentUpdateStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;

  initStringBuffer(&sb);
  append(&sb, "update %_content set ");
  for(i=0; i<v->nColumn; ++i) {
    if( i>0 ){
      append(&sb, ", ");
    }
    append(&sb, v->azContentColumn[i]);
    append(&sb, " = ?");
  }
  append(&sb, " where docid = ?");
  return stringBufferData(&sb);
}

/* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
** If the indicated statement has never been prepared, it is prepared
** and cached, otherwise the cached version is reset.
*/
static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
                             sqlite3_stmt **ppStmt){
  assert( iStmt<MAX_STMT );
  if( v->pFulltextStatements[iStmt]==NULL ){
    const char *zStmt;
    int rc;
    switch( iStmt ){
      case CONTENT_INSERT_STMT:
        zStmt = contentInsertStatement(v); break;
      case CONTENT_SELECT_STMT:
        zStmt = contentSelectStatement(v); break;
      case CONTENT_UPDATE_STMT:
        zStmt = contentUpdateStatement(v); break;
      default:
        zStmt = fulltext_zStatement[iStmt];
    }
    rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
                         zStmt);
    if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
    if( rc!=SQLITE_OK ) return rc;
  } else {
    int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
    if( rc!=SQLITE_OK ) return rc;
  }

  *ppStmt = v->pFulltextStatements[iStmt];
  return SQLITE_OK;
}

/* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
** where we expect no results.
*/
static int sql_single_step(sqlite3_stmt *s){
  int rc = sqlite3_step(s);
  return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
}

/* Like sql_get_statement(), but for special replicated LEAF_SELECT
** statements.  idx -1 is a special case for an uncached version of
** the statement (used in the optimize implementation).
*/
/* TODO(shess) Write version for generic statements and then share
** that between the cached-statement functions.
*/
static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
                                  sqlite3_stmt **ppStmt){
  assert( idx>=-1 && idx<MERGE_COUNT );
  if( idx==-1 ){
    return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
  }else if( v->pLeafSelectStmts[idx]==NULL ){
    int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
                         LEAF_SELECT);
    if( rc!=SQLITE_OK ) return rc;
  }else{
    int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
    if( rc!=SQLITE_OK ) return rc;
  }

  *ppStmt = v->pLeafSelectStmts[idx];
  return SQLITE_OK;
}

/* insert into %_content (docid, ...) values ([docid], [pValues])
** If the docid contains SQL NULL, then a unique docid will be
** generated.
*/
static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
                          sqlite3_value **pValues){
  sqlite3_stmt *s;
  int i;
  int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_value(s, 1, docid);
  if( rc!=SQLITE_OK ) return rc;

  for(i=0; i<v->nColumn; ++i){
    rc = sqlite3_bind_value(s, 2+i, pValues[i]);
    if( rc!=SQLITE_OK ) return rc;
  }

  return sql_single_step(s);
}

/* update %_content set col0 = pValues[0], col1 = pValues[1], ...
 *                  where docid = [iDocid] */
static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
                          sqlite_int64 iDocid){
  sqlite3_stmt *s;
  int i;
  int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  for(i=0; i<v->nColumn; ++i){
    rc = sqlite3_bind_value(s, 1+i, pValues[i]);
    if( rc!=SQLITE_OK ) return rc;
  }

  rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

static void freeStringArray(int nString, const char **pString){
  int i;

  for (i=0 ; i < nString ; ++i) {
    if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
  }
  sqlite3_free((void *) pString);
}

/* select * from %_content where docid = [iDocid]
 * The caller must delete the returned array and all strings in it.
 * null fields will be NULL in the returned array.
 *
 * TODO: Perhaps we should return pointer/length strings here for consistency
 * with other code which uses pointer/length. */
static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
                          const char ***pValues){
  sqlite3_stmt *s;
  const char **values;
  int i;
  int rc;

  *pValues = NULL;

  rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iDocid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc!=SQLITE_ROW ) return rc;

  values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
  for(i=0; i<v->nColumn; ++i){
    if( sqlite3_column_type(s, i)==SQLITE_NULL ){
      values[i] = NULL;
    }else{
      values[i] = string_dup((char*)sqlite3_column_text(s, i));
    }
  }

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ){
    *pValues = values;
    return SQLITE_OK;
  }

  freeStringArray(v->nColumn, values);
  return rc;
}

/* delete from %_content where docid = [iDocid ] */
static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iDocid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
** no rows exist, and any error in case of failure.
*/
static int content_exists(fulltext_vtab *v){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc!=SQLITE_ROW ) return rc;

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_ROW;
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  return rc;
}

/* insert into %_segments values ([pData])
**   returns assigned blockid in *piBlockid
*/
static int block_insert(fulltext_vtab *v, const char *pData, int nData,
                        sqlite_int64 *piBlockid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;

  /* blockid column is an alias for rowid. */
  *piBlockid = sqlite3_last_insert_rowid(v->db);
  return SQLITE_OK;
}

/* delete from %_segments
**   where blockid between [iStartBlockid] and [iEndBlockid]
**
** Deletes the range of blocks, inclusive, used to delete the blocks
** which form a segment.
*/
static int block_delete(fulltext_vtab *v,
                        sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
** at iLevel.  Returns SQLITE_DONE if there are no segments at
** iLevel.  Otherwise returns an error.
*/
static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  /* Should always get at least one row due to how max() works. */
  if( rc==SQLITE_DONE ) return SQLITE_DONE;
  if( rc!=SQLITE_ROW ) return rc;

  /* NULL means that there were no inputs to max(). */
  if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
    rc = sqlite3_step(s);
    if( rc==SQLITE_ROW ) return SQLITE_ERROR;
    return rc;
  }

  *pidx = sqlite3_column_int(s, 0);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;
  return SQLITE_ROW;
}

/* insert into %_segdir values (
**   [iLevel], [idx],
**   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
**   [pRootData]
** )
*/
static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
                      sqlite_int64 iStartBlockid,
                      sqlite_int64 iLeavesEndBlockid,
                      sqlite_int64 iEndBlockid,
                      const char *pRootData, int nRootData){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 2, idx);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 3, iStartBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 5, iEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Queries %_segdir for the block span of the segments in level
** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
** SQLITE_ROW if there are blocks, else an error.
*/
static int segdir_span(fulltext_vtab *v, int iLevel,
                       sqlite_int64 *piStartBlockid,
                       sqlite_int64 *piEndBlockid){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
  if( rc!=SQLITE_ROW ) return rc;

  /* This happens if all segments at this level are entirely inline. */
  if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
    /* We expect only one row.  We must execute another sqlite3_step()
     * to complete the iteration; otherwise the table will remain locked. */
    int rc2 = sqlite3_step(s);
    if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
    return rc2;
  }

  *piStartBlockid = sqlite3_column_int64(s, 0);
  *piEndBlockid = sqlite3_column_int64(s, 1);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;
  return SQLITE_ROW;
}

/* Delete the segment blocks and segment directory records for all
** segments at iLevel.
*/
static int segdir_delete(fulltext_vtab *v, int iLevel){
  sqlite3_stmt *s;
  sqlite_int64 iStartBlockid, iEndBlockid;
  int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
  if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;

  if( rc==SQLITE_ROW ){
    rc = block_delete(v, iStartBlockid, iEndBlockid);
    if( rc!=SQLITE_OK ) return rc;
  }

  /* Delete the segment directory itself. */
  rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Delete entire fts index, SQLITE_OK on success, relevant error on
** failure.
*/
static int segdir_delete_all(fulltext_vtab *v){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_single_step(s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  return sql_single_step(s);
}

/* Returns SQLITE_OK with *pnSegments set to the number of entries in
** %_segdir and *piMaxLevel set to the highest level which has a
** segment.  Otherwise returns the SQLite error which caused failure.
*/
static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  /* TODO(shess): This case should not be possible?  Should stronger
  ** measures be taken if it happens?
  */
  if( rc==SQLITE_DONE ){
    *pnSegments = 0;
    *piMaxLevel = 0;
    return SQLITE_OK;
  }
  if( rc!=SQLITE_ROW ) return rc;

  *pnSegments = sqlite3_column_int(s, 0);
  *piMaxLevel = sqlite3_column_int(s, 1);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_OK;
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  return rc;
}

/* TODO(shess) clearPendingTerms() is far down the file because
** writeZeroSegment() is far down the file because LeafWriter is far
** down the file.  Consider refactoring the code to move the non-vtab
** code above the vtab code so that we don't need this forward
** reference.
*/
static int clearPendingTerms(fulltext_vtab *v);

/*
** Free the memory used to contain a fulltext_vtab structure.
*/
static void fulltext_vtab_destroy(fulltext_vtab *v){
  int iStmt, i;

  FTSTRACE(("FTS3 Destroy %p\n", v));
  for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
    if( v->pFulltextStatements[iStmt]!=NULL ){
      sqlite3_finalize(v->pFulltextStatements[iStmt]);
      v->pFulltextStatements[iStmt] = NULL;
    }
  }

  for( i=0; i<MERGE_COUNT; i++ ){
    if( v->pLeafSelectStmts[i]!=NULL ){
      sqlite3_finalize(v->pLeafSelectStmts[i]);
      v->pLeafSelectStmts[i] = NULL;
    }
  }

  if( v->pTokenizer!=NULL ){
    v->pTokenizer->pModule->xDestroy(v->pTokenizer);
    v->pTokenizer = NULL;
  }

  clearPendingTerms(v);

  sqlite3_free(v->azColumn);
  for(i = 0; i < v->nColumn; ++i) {
    sqlite3_free(v->azContentColumn[i]);
  }
  sqlite3_free(v->azContentColumn);
  sqlite3_free(v);
}

/*
** Token types for parsing the arguments to xConnect or xCreate.
*/
#define TOKEN_EOF         0    /* End of file */
#define TOKEN_SPACE       1    /* Any kind of whitespace */
#define TOKEN_ID          2    /* An identifier */
#define TOKEN_STRING      3    /* A string literal */
#define TOKEN_PUNCT       4    /* A single punctuation character */

/*
** If X is a character that can be used in an identifier then
** ftsIdChar(X) will be true.  Otherwise it is false.
**
** For ASCII, any character with the high-order bit set is
** allowed in an identifier.  For 7-bit characters, 
** isFtsIdChar[X] must be 1.
**
** Ticket #1066.  the SQL standard does not allow '$' in the
** middle of identfiers.  But many SQL implementations do. 
** SQLite will allow '$' in identifiers for compatibility.
** But the feature is undocumented.
*/
static const char isFtsIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))


/*
** Return the length of the token that begins at z[0]. 
** Store the token type in *tokenType before returning.
*/
static int ftsGetToken(const char *z, int *tokenType){
  int i, c;
  switch( *z ){
    case 0: {
      *tokenType = TOKEN_EOF;
      return 0;
    }
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; safe_isspace(z[i]); i++){}
      *tokenType = TOKEN_SPACE;
      return i;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      for(i=1; (c=z[i])!=0; i++){
        if( c==delim ){
          if( z[i+1]==delim ){
            i++;
          }else{
            break;
          }
        }
      }
      *tokenType = TOKEN_STRING;
      return i + (c!=0);
    }
    case '[': {
      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
      *tokenType = TOKEN_ID;
      return i;
    }
    default: {
      if( !ftsIdChar(*z) ){
        break;
      }
      for(i=1; ftsIdChar(z[i]); i++){}
      *tokenType = TOKEN_ID;
      return i;
    }
  }
  *tokenType = TOKEN_PUNCT;
  return 1;
}

/*
** A token extracted from a string is an instance of the following
** structure.
*/
typedef struct FtsToken {
  const char *z;       /* Pointer to token text.  Not '\000' terminated */
  short int n;         /* Length of the token text in bytes. */
} FtsToken;

/*
** Given a input string (which is really one of the argv[] parameters
** passed into xConnect or xCreate) split the string up into tokens.
** Return an array of pointers to '\000' terminated strings, one string
** for each non-whitespace token.
**
** The returned array is terminated by a single NULL pointer.
**
** Space to hold the returned array is obtained from a single
** malloc and should be freed by passing the return value to free().
** The individual strings within the token list are all a part of
** the single memory allocation and will all be freed at once.
*/
static char **tokenizeString(const char *z, int *pnToken){
  int nToken = 0;
  FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
  int n = 1;
  int e, i;
  int totalSize = 0;
  char **azToken;
  char *zCopy;
  while( n>0 ){
    n = ftsGetToken(z, &e);
    if( e!=TOKEN_SPACE ){
      aToken[nToken].z = z;
      aToken[nToken].n = n;
      nToken++;
      totalSize += n+1;
    }
    z += n;
  }
  azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
  zCopy = (char*)&azToken[nToken];
  nToken--;
  for(i=0; i<nToken; i++){
    azToken[i] = zCopy;
    n = aToken[i].n;
    memcpy(zCopy, aToken[i].z, n);
    zCopy[n] = 0;
    zCopy += n+1;
  }
  azToken[nToken] = 0;
  sqlite3_free(aToken);
  *pnToken = nToken;
  return azToken;
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** Examples:
**
**     "abc"   becomes   abc
**     'xyz'   becomes   xyz
**     [pqr]   becomes   pqr
**     `mno`   becomes   mno
*/
static void dequoteString(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return;
  }
  for(i=1, j=0; z[i]; i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = quote;
        i++;
      }else{
        z[j++] = 0;
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
}

/*
** The input azIn is a NULL-terminated list of tokens.  Remove the first
** token and all punctuation tokens.  Remove the quotes from
** around string literal tokens.
**
** Example:
**
**     input:      tokenize chinese ( 'simplifed' , 'mixed' )
**     output:     chinese simplifed mixed
**
** Another example:
**
**     input:      delimiters ( '[' , ']' , '...' )
**     output:     [ ] ...
*/
static void tokenListToIdList(char **azIn){
  int i, j;
  if( azIn ){
    for(i=0, j=-1; azIn[i]; i++){
      if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
        dequoteString(azIn[i]);
        if( j>=0 ){
          azIn[j] = azIn[i];
        }
        j++;
      }
    }
    azIn[j] = 0;
  }
}


/*
** Find the first alphanumeric token in the string zIn.  Null-terminate
** this token.  Remove any quotation marks.  And return a pointer to
** the result.
*/
static char *firstToken(char *zIn, char **pzTail){
  int n, ttype;
  while(1){
    n = ftsGetToken(zIn, &ttype);
    if( ttype==TOKEN_SPACE ){
      zIn += n;
    }else if( ttype==TOKEN_EOF ){
      *pzTail = zIn;
      return 0;
    }else{
      zIn[n] = 0;
      *pzTail = &zIn[1];
      dequoteString(zIn);
      return zIn;
    }
  }
  /*NOTREACHED*/
}

/* Return true if...
**
**   *  s begins with the string t, ignoring case
**   *  s is longer than t
**   *  The first character of s beyond t is not a alphanumeric
** 
** Ignore leading space in *s.
**
** To put it another way, return true if the first token of
** s[] is t[].
*/
static int startsWith(const char *s, const char *t){
  while( safe_isspace(*s) ){ s++; }
  while( *t ){
    if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
  }
  return *s!='_' && !safe_isalnum(*s);
}

/*
** An instance of this structure defines the "spec" of a
** full text index.  This structure is populated by parseSpec
** and use by fulltextConnect and fulltextCreate.
*/
typedef struct TableSpec {
  const char *zDb;         /* Logical database name */
  const char *zName;       /* Name of the full-text index */
  int nColumn;             /* Number of columns to be indexed */
  char **azColumn;         /* Original names of columns to be indexed */
  char **azContentColumn;  /* Column names for %_content */
  char **azTokenizer;      /* Name of tokenizer and its arguments */
} TableSpec;

/*
** Reclaim all of the memory used by a TableSpec
*/
static void clearTableSpec(TableSpec *p) {
  sqlite3_free(p->azColumn);
  sqlite3_free(p->azContentColumn);
  sqlite3_free(p->azTokenizer);
}

/* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
 *
 * CREATE VIRTUAL TABLE email
 *        USING fts3(subject, body, tokenize mytokenizer(myarg))
 *
 * We return parsed information in a TableSpec structure.
 * 
 */
static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
                     char**pzErr){
  int i, n;
  char *z, *zDummy;
  char **azArg;
  const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */

  assert( argc>=3 );
  /* Current interface:
  ** argv[0] - module name
  ** argv[1] - database name
  ** argv[2] - table name
  ** argv[3..] - columns, optionally followed by tokenizer specification
  **             and snippet delimiters specification.
  */

  /* Make a copy of the complete argv[][] array in a single allocation.
  ** The argv[][] array is read-only and transient.  We can write to the
  ** copy in order to modify things and the copy is persistent.
  */
  CLEAR(pSpec);
  for(i=n=0; i<argc; i++){
    n += strlen(argv[i]) + 1;
  }
  azArg = sqlite3_malloc( sizeof(char*)*argc + n );
  if( azArg==0 ){
    return SQLITE_NOMEM;
  }
  z = (char*)&azArg[argc];
  for(i=0; i<argc; i++){
    azArg[i] = z;
    strcpy(z, argv[i]);
    z += strlen(z)+1;
  }

  /* Identify the column names and the tokenizer and delimiter arguments
  ** in the argv[][] array.
  */
  pSpec->zDb = azArg[1];
  pSpec->zName = azArg[2];
  pSpec->nColumn = 0;
  pSpec->azColumn = azArg;
  zTokenizer = "tokenize simple";
  for(i=3; i<argc; ++i){
    if( startsWith(azArg[i],"tokenize") ){
      zTokenizer = azArg[i];
    }else{
      z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
      pSpec->nColumn++;
    }
  }
  if( pSpec->nColumn==0 ){
    azArg[0] = "content";
    pSpec->nColumn = 1;
  }

  /*
  ** Construct the list of content column names.
  **
  ** Each content column name will be of the form cNNAAAA
  ** where NN is the column number and AAAA is the sanitized
  ** column name.  "sanitized" means that special characters are
  ** converted to "_".  The cNN prefix guarantees that all column
  ** names are unique.
  **
  ** The AAAA suffix is not strictly necessary.  It is included
  ** for the convenience of people who might examine the generated
  ** %_content table and wonder what the columns are used for.
  */
  pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
  if( pSpec->azContentColumn==0 ){
    clearTableSpec(pSpec);
    return SQLITE_NOMEM;
  }
  for(i=0; i<pSpec->nColumn; i++){
    char *p;
    pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
    for (p = pSpec->azContentColumn[i]; *p ; ++p) {
      if( !safe_isalnum(*p) ) *p = '_';
    }
  }

  /*
  ** Parse the tokenizer specification string.
  */
  pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
  tokenListToIdList(pSpec->azTokenizer);

  return SQLITE_OK;
}

/*
** Generate a CREATE TABLE statement that describes the schema of
** the virtual table.  Return a pointer to this schema string.
**
** Space is obtained from sqlite3_mprintf() and should be freed
** using sqlite3_free().
*/
static char *fulltextSchema(
  int nColumn,                  /* Number of columns */
  const char *const* azColumn,  /* List of columns */
  const char *zTableName        /* Name of the table */
){
  int i;
  char *zSchema, *zNext;
  const char *zSep = "(";
  zSchema = sqlite3_mprintf("CREATE TABLE x");
  for(i=0; i<nColumn; i++){
    zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
    sqlite3_free(zSchema);
    zSchema = zNext;
    zSep = ",";
  }
  zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
  sqlite3_free(zSchema);
  zSchema = zNext;
  zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
  sqlite3_free(zSchema);
  return zNext;
}

/*
** Build a new sqlite3_vtab structure that will describe the
** fulltext index defined by spec.
*/
static int constructVtab(
  sqlite3 *db,              /* The SQLite database connection */
  fts3Hash *pHash,          /* Hash table containing tokenizers */
  TableSpec *spec,          /* Parsed spec information from parseSpec() */
  sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
  char **pzErr              /* Write any error message here */
){
  int rc;
  int n;
  fulltext_vtab *v = 0;
  const sqlite3_tokenizer_module *m = NULL;
  char *schema;

  char const *zTok;         /* Name of tokenizer to use for this fts table */
  int nTok;                 /* Length of zTok, including nul terminator */

  v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
  if( v==0 ) return SQLITE_NOMEM;
  CLEAR(v);
  /* sqlite will initialize v->base */
  v->db = db;
  v->zDb = spec->zDb;       /* Freed when azColumn is freed */
  v->zName = spec->zName;   /* Freed when azColumn is freed */
  v->nColumn = spec->nColumn;
  v->azContentColumn = spec->azContentColumn;
  spec->azContentColumn = 0;
  v->azColumn = spec->azColumn;
  spec->azColumn = 0;

  if( spec->azTokenizer==0 ){
    return SQLITE_NOMEM;
  }

  zTok = spec->azTokenizer[0]; 
  if( !zTok ){
    zTok = "simple";
  }
  nTok = strlen(zTok)+1;

  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
  if( !m ){
    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
    rc = SQLITE_ERROR;
    goto err;
  }

  for(n=0; spec->azTokenizer[n]; n++){}
  if( n ){
    rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
                    &v->pTokenizer);
  }else{
    rc = m->xCreate(0, 0, &v->pTokenizer);
  }
  if( rc!=SQLITE_OK ) goto err;
  v->pTokenizer->pModule = m;

  /* TODO: verify the existence of backing tables foo_content, foo_term */

  schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
                          spec->zName);
  rc = sqlite3_declare_vtab(db, schema);
  sqlite3_free(schema);
  if( rc!=SQLITE_OK ) goto err;

  memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));

  /* Indicate that the buffer is not live. */
  v->nPendingData = -1;

  *ppVTab = &v->base;
  FTSTRACE(("FTS3 Connect %p\n", v));

  return rc;

err:
  fulltext_vtab_destroy(v);
  return rc;
}

static int fulltextConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVTab,
  char **pzErr
){
  TableSpec spec;
  int rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
  clearTableSpec(&spec);
  return rc;
}

/* The %_content table holds the text of each document, with
** the docid column exposed as the SQLite rowid for the table.
*/
/* TODO(shess) This comment needs elaboration to match the updated
** code.  Work it into the top-of-file comment at that time.
*/
static int fulltextCreate(sqlite3 *db, void *pAux,
                          int argc, const char * const *argv,
                          sqlite3_vtab **ppVTab, char **pzErr){
  int rc;
  TableSpec spec;
  StringBuffer schema;
  FTSTRACE(("FTS3 Create\n"));

  rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  initStringBuffer(&schema);
  append(&schema, "CREATE TABLE %_content(");
  append(&schema, "  docid INTEGER PRIMARY KEY,");
  appendList(&schema, spec.nColumn, spec.azContentColumn);
  append(&schema, ")");
  rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
  stringBufferDestroy(&schema);
  if( rc!=SQLITE_OK ) goto out;

  rc = sql_exec(db, spec.zDb, spec.zName,
                "create table %_segments("
                "  blockid INTEGER PRIMARY KEY,"
                "  block blob"
                ");"
                );
  if( rc!=SQLITE_OK ) goto out;

  rc = sql_exec(db, spec.zDb, spec.zName,
                "create table %_segdir("
                "  level integer,"
                "  idx integer,"
                "  start_block integer,"
                "  leaves_end_block integer,"
                "  end_block integer,"
                "  root blob,"
                "  primary key(level, idx)"
                ");");
  if( rc!=SQLITE_OK ) goto out;

  rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);

out:
  clearTableSpec(&spec);
  return rc;
}

/* Decide how to handle an SQL query. */
static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  fulltext_vtab *v = (fulltext_vtab *)pVTab;
  int i;
  FTSTRACE(("FTS3 BestIndex\n"));

  for(i=0; i<pInfo->nConstraint; ++i){
    const struct sqlite3_index_constraint *pConstraint;
    pConstraint = &pInfo->aConstraint[i];
    if( pConstraint->usable ) {
      if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
          pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
        pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
        FTSTRACE(("FTS3 QUERY_DOCID\n"));
      } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
                 pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
        /* full-text search */
        pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
        FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
      } else continue;

      pInfo->aConstraintUsage[i].argvIndex = 1;
      pInfo->aConstraintUsage[i].omit = 1;

      /* An arbitrary value for now.
       * TODO: Perhaps docid matches should be considered cheaper than
       * full-text searches. */
      pInfo->estimatedCost = 1.0;   

      return SQLITE_OK;
    }
  }
  pInfo->idxNum = QUERY_GENERIC;
  return SQLITE_OK;
}

static int fulltextDisconnect(sqlite3_vtab *pVTab){
  FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextDestroy(sqlite3_vtab *pVTab){
  fulltext_vtab *v = (fulltext_vtab *)pVTab;
  int rc;

  FTSTRACE(("FTS3 Destroy %p\n", pVTab));
  rc = sql_exec(v->db, v->zDb, v->zName,
                "drop table if exists %_content;"
                "drop table if exists %_segments;"
                "drop table if exists %_segdir;"
                );
  if( rc!=SQLITE_OK ) return rc;

  fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  return SQLITE_OK;
}

static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  fulltext_cursor *c;

  c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
  if( c ){
    memset(c, 0, sizeof(fulltext_cursor));
    /* sqlite will initialize c->base */
    *ppCursor = &c->base;
    FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
    return SQLITE_OK;
  }else{
    return SQLITE_NOMEM;
  }
}

/* Free all of the dynamically allocated memory held by the
** Snippet
*/
static void snippetClear(Snippet *p){
  sqlite3_free(p->aMatch);
  sqlite3_free(p->zOffset);
  sqlite3_free(p->zSnippet);
  CLEAR(p);
}

/*
** Append a single entry to the p->aMatch[] log.
*/
static void snippetAppendMatch(
  Snippet *p,               /* Append the entry to this snippet */
  int iCol, int iTerm,      /* The column and query term */
  int iToken,               /* Matching token in document */
  int iStart, int nByte     /* Offset and size of the match */
){
  int i;
  struct snippetMatch *pMatch;
  if( p->nMatch+1>=p->nAlloc ){
    p->nAlloc = p->nAlloc*2 + 10;
    p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
    if( p->aMatch==0 ){
      p->nMatch = 0;
      p->nAlloc = 0;
      return;
    }
  }
  i = p->nMatch++;
  pMatch = &p->aMatch[i];
  pMatch->iCol = iCol;
  pMatch->iTerm = iTerm;
  pMatch->iToken = iToken;
  pMatch->iStart = iStart;
  pMatch->nByte = nByte;
}

/*
** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
*/
#define FTS3_ROTOR_SZ   (32)
#define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)

/*
** Function to iterate through the tokens of a compiled expression.
**
** Except, skip all tokens on the right-hand side of a NOT operator.
** This function is used to find tokens as part of snippet and offset
** generation and we do nt want snippets and offsets to report matches
** for tokens on the RHS of a NOT.
*/
static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
  Fts3Expr *p = *ppExpr;
  int iToken = *piToken;
  if( iToken<0 ){
    /* In this case the expression p is the root of an expression tree.
    ** Move to the first token in the expression tree.
    */
    while( p->pLeft ){
      p = p->pLeft;
    }
    iToken = 0;
  }else{
    assert(p && p->eType==FTSQUERY_PHRASE );
    if( iToken<(p->pPhrase->nToken-1) ){
      iToken++;
    }else{
      iToken = 0;
      while( p->pParent && p->pParent->pLeft!=p ){
        assert( p->pParent->pRight==p );
        p = p->pParent;
      }
      p = p->pParent;
      if( p ){
        assert( p->pRight!=0 );
        p = p->pRight;
        while( p->pLeft ){
          p = p->pLeft;
        }
      }
    }
  }

  *ppExpr = p;
  *piToken = iToken;
  return p?1:0;
}

/*
** Return TRUE if the expression node pExpr is located beneath the
** RHS of a NOT operator.
*/
static int fts3ExprBeneathNot(Fts3Expr *p){
  Fts3Expr *pParent;
  while( p ){
    pParent = p->pParent;
    if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
      return 1;
    }
    p = pParent;
  }
  return 0;
}

/*
** Add entries to pSnippet->aMatch[] for every match that occurs against
** document zDoc[0..nDoc-1] which is stored in column iColumn.
*/
static void snippetOffsetsOfColumn(
  fulltext_cursor *pCur,         /* The fulltest search cursor */
  Snippet *pSnippet,             /* The Snippet object to be filled in */
  int iColumn,                   /* Index of fulltext table column */
  const char *zDoc,              /* Text of the fulltext table column */
  int nDoc                       /* Length of zDoc in bytes */
){
  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
  fulltext_vtab *pVtab;                /* The full text index */
  int nColumn;                         /* Number of columns in the index */
  int i, j;                            /* Loop counters */
  int rc;                              /* Return code */
  unsigned int match, prevMatch;       /* Phrase search bitmasks */
  const char *zToken;                  /* Next token from the tokenizer */
  int nToken;                          /* Size of zToken */
  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */

  /* The following variables keep a circular buffer of the last
  ** few tokens */
  unsigned int iRotor = 0;             /* Index of current token */
  int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
  int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */

  pVtab = cursor_vtab(pCur);
  nColumn = pVtab->nColumn;
  pTokenizer = pVtab->pTokenizer;
  pTModule = pTokenizer->pModule;
  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
  if( rc ) return;
  pTCursor->pTokenizer = pTokenizer;

  prevMatch = 0;
  while( !pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos) ){
    Fts3Expr *pIter = pCur->pExpr;
    int iIter = -1;
    iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
    iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
    match = 0;
    for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
      int nPhrase;                    /* Number of tokens in current phrase */
      struct PhraseToken *pToken;     /* Current token */
      int iCol;                       /* Column index */

      if( fts3ExprBeneathNot(pIter) ) continue;
      nPhrase = pIter->pPhrase->nToken;
      pToken = &pIter->pPhrase->aToken[iIter];
      iCol = pIter->pPhrase->iColumn;
      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
      if( pToken->n>nToken ) continue;
      if( !pToken->isPrefix && pToken->n<nToken ) continue;
      assert( pToken->n<=nToken );
      if( memcmp(pToken->z, zToken, pToken->n) ) continue;
      if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
      match |= 1<<i;
      if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
        for(j=nPhrase-1; j>=0; j--){
          int k = (iRotor-j) & FTS3_ROTOR_MASK;
          snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
                iRotorBegin[k], iRotorLen[k]);
        }
      }
    }
    prevMatch = match<<1;
    iRotor++;
  }
  pTModule->xClose(pTCursor);  
}

/*
** Remove entries from the pSnippet structure to account for the NEAR
** operator. When this is called, pSnippet contains the list of token 
** offsets produced by treating all NEAR operators as AND operators.
** This function removes any entries that should not be present after
** accounting for the NEAR restriction. For example, if the queried
** document is:
**
**     "A B C D E A"
**
** and the query is:
** 
**     A NEAR/0 E
**
** then when this function is called the Snippet contains token offsets
** 0, 4 and 5. This function removes the "0" entry (because the first A
** is not near enough to an E).
**
** When this function is called, the value pointed to by parameter piLeft is
** the integer id of the left-most token in the expression tree headed by
** pExpr. This function increments *piLeft by the total number of tokens
** in the expression tree headed by pExpr.
**
** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
*/
static int trimSnippetOffsets(
  Fts3Expr *pExpr,      /* The search expression */
  Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
  int *piLeft           /* Index of left-most token in pExpr */
){
  if( pExpr ){
    if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
      return 1;
    }

    switch( pExpr->eType ){
      case FTSQUERY_PHRASE:
        *piLeft += pExpr->pPhrase->nToken;
        break;
      case FTSQUERY_NEAR: {
        /* The right-hand-side of a NEAR operator is always a phrase. The
        ** left-hand-side is either a phrase or an expression tree that is 
        ** itself headed by a NEAR operator. The following initializations
        ** set local variable iLeft to the token number of the left-most
        ** token in the right-hand phrase, and iRight to the right most
        ** token in the same phrase. For example, if we had:
        **
        **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
        **
        ** then iLeft will be set to 2 (token number of ghi) and nToken will
        ** be set to 4.
        */
        Fts3Expr *pLeft = pExpr->pLeft;
        Fts3Expr *pRight = pExpr->pRight;
        int iLeft = *piLeft;
        int nNear = pExpr->nNear;
        int nToken = pRight->pPhrase->nToken;
        int jj, ii;
        if( pLeft->eType==FTSQUERY_NEAR ){
          pLeft = pLeft->pRight;
        }
        assert( pRight->eType==FTSQUERY_PHRASE );
        assert( pLeft->eType==FTSQUERY_PHRASE );
        nToken += pLeft->pPhrase->nToken;

        for(ii=0; ii<pSnippet->nMatch; ii++){
          struct snippetMatch *p = &pSnippet->aMatch[ii];
          if( p->iTerm==iLeft ){
            int isOk = 0;
            /* Snippet ii is an occurence of query term iLeft in the document.
            ** It occurs at position (p->iToken) of the document. We now
            ** search for an instance of token (iLeft-1) somewhere in the 
            ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within 
            ** the set of snippetMatch structures. If one is found, proceed. 
            ** If one cannot be found, then remove snippets ii..(ii+N-1) 
            ** from the matching snippets, where N is the number of tokens 
            ** in phrase pRight->pPhrase.
            */
            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
              if( p2->iTerm==(iLeft-1) ){
                if( p2->iToken>=(p->iToken-nNear-1) 
                 && p2->iToken<(p->iToken+nNear+nToken) 
                ){
                  isOk = 1;
                }
              }
            }
            if( !isOk ){
              int kk;
              for(kk=0; kk<pRight->pPhrase->nToken; kk++){
                pSnippet->aMatch[kk+ii].iTerm = -2;
              }
              return 1;
            }
          }
          if( p->iTerm==(iLeft-1) ){
            int isOk = 0;
            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
              if( p2->iTerm==iLeft ){
                if( p2->iToken<=(p->iToken+nNear+1) 
                 && p2->iToken>(p->iToken-nNear-nToken) 
                ){
                  isOk = 1;
                }
              }
            }
            if( !isOk ){
              int kk;
              for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
                pSnippet->aMatch[ii-kk].iTerm = -2;
              }
              return 1;
            }
          }
        }
        break;
      }
    }

    if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
      return 1;
    }
  }
  return 0;
}

/*
** Compute all offsets for the current row of the query.  
** If the offsets have already been computed, this routine is a no-op.
*/
static void snippetAllOffsets(fulltext_cursor *p){
  int nColumn;
  int iColumn, i;
  int iFirst, iLast;
  int iTerm = 0;
  fulltext_vtab *pFts = cursor_vtab(p);

  if( p->snippet.nMatch || p->pExpr==0 ){
    return;
  }
  nColumn = pFts->nColumn;
  iColumn = (p->iCursorType - QUERY_FULLTEXT);
  if( iColumn<0 || iColumn>=nColumn ){
    /* Look for matches over all columns of the full-text index */
    iFirst = 0;
    iLast = nColumn-1;
  }else{
    /* Look for matches in the iColumn-th column of the index only */
    iFirst = iColumn;
    iLast = iColumn;
  }
  for(i=iFirst; i<=iLast; i++){
    const char *zDoc;
    int nDoc;
    zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
    nDoc = sqlite3_column_bytes(p->pStmt, i+1);
    snippetOffsetsOfColumn(p, &p->snippet, i, zDoc, nDoc);
  }

  while( trimSnippetOffsets(p->pExpr, &p->snippet, &iTerm) ){
    iTerm = 0;
  }
}

/*
** Convert the information in the aMatch[] array of the snippet
** into the string zOffset[0..nOffset-1]. This string is used as
** the return of the SQL offsets() function.
*/
static void snippetOffsetText(Snippet *p){
  int i;
  int cnt = 0;
  StringBuffer sb;
  char zBuf[200];
  if( p->zOffset ) return;
  initStringBuffer(&sb);
  for(i=0; i<p->nMatch; i++){
    struct snippetMatch *pMatch = &p->aMatch[i];
    if( pMatch->iTerm>=0 ){
      /* If snippetMatch.iTerm is less than 0, then the match was 
      ** discarded as part of processing the NEAR operator (see the 
      ** trimSnippetOffsetsForNear() function for details). Ignore 
      ** it in this case
      */
      zBuf[0] = ' ';
      sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
          pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
      append(&sb, zBuf);
      cnt++;
    }
  }
  p->zOffset = stringBufferData(&sb);
  p->nOffset = stringBufferLength(&sb);
}

/*
** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
** of matching words some of which might be in zDoc.  zDoc is column
** number iCol.
**
** iBreak is suggested spot in zDoc where we could begin or end an
** excerpt.  Return a value similar to iBreak but possibly adjusted
** to be a little left or right so that the break point is better.
*/
static int wordBoundary(
  int iBreak,                   /* The suggested break point */
  const char *zDoc,             /* Document text */
  int nDoc,                     /* Number of bytes in zDoc[] */
  struct snippetMatch *aMatch,  /* Matching words */
  int nMatch,                   /* Number of entries in aMatch[] */
  int iCol                      /* The column number for zDoc[] */
){
  int i;
  if( iBreak<=10 ){
    return 0;
  }
  if( iBreak>=nDoc-10 ){
    return nDoc;
  }
  for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
  if( i<nMatch ){
    if( aMatch[i].iStart<iBreak+10 ){
      return aMatch[i].iStart;
    }
    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
      return aMatch[i-1].iStart;
    }
  }
  for(i=1; i<=10; i++){
    if( safe_isspace(zDoc[iBreak-i]) ){
      return iBreak - i + 1;
    }
    if( safe_isspace(zDoc[iBreak+i]) ){
      return iBreak + i + 1;
    }
  }
  return iBreak;
}



/*
** Allowed values for Snippet.aMatch[].snStatus
*/
#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */

/*
** Generate the text of a snippet.
*/
static void snippetText(
  fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
  const char *zStartMark,     /* Markup to appear before each match */
  const char *zEndMark,       /* Markup to appear after each match */
  const char *zEllipsis       /* Ellipsis mark */
){
  int i, j;
  struct snippetMatch *aMatch;
  int nMatch;
  int nDesired;
  StringBuffer sb;
  int tailCol;
  int tailOffset;
  int iCol;
  int nDoc;
  const char *zDoc;
  int iStart, iEnd;
  int tailEllipsis = 0;
  int iMatch;
  

  sqlite3_free(pCursor->snippet.zSnippet);
  pCursor->snippet.zSnippet = 0;
  aMatch = pCursor->snippet.aMatch;
  nMatch = pCursor->snippet.nMatch;
  initStringBuffer(&sb);

  for(i=0; i<nMatch; i++){
    aMatch[i].snStatus = SNIPPET_IGNORE;
  }
  nDesired = 0;
  for(i=0; i<FTS3_ROTOR_SZ; i++){
    for(j=0; j<nMatch; j++){
      if( aMatch[j].iTerm==i ){
        aMatch[j].snStatus = SNIPPET_DESIRED;
        nDesired++;
        break;
      }
    }
  }

  iMatch = 0;
  tailCol = -1;
  tailOffset = 0;
  for(i=0; i<nMatch && nDesired>0; i++){
    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
    nDesired--;
    iCol = aMatch[i].iCol;
    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
    iStart = aMatch[i].iStart - 40;
    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
    if( iStart<=10 ){
      iStart = 0;
    }
    if( iCol==tailCol && iStart<=tailOffset+20 ){
      iStart = tailOffset;
    }
    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
      trimWhiteSpace(&sb);
      appendWhiteSpace(&sb);
      append(&sb, zEllipsis);
      appendWhiteSpace(&sb);
    }
    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
    if( iEnd>=nDoc-10 ){
      iEnd = nDoc;
      tailEllipsis = 0;
    }else{
      tailEllipsis = 1;
    }
    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
    while( iStart<iEnd ){
      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
             && aMatch[iMatch].iCol<=iCol ){
        iMatch++;
      }
      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
             && aMatch[iMatch].iCol==iCol ){
        nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
        iStart = aMatch[iMatch].iStart;
        append(&sb, zStartMark);
        nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
        append(&sb, zEndMark);
        iStart += aMatch[iMatch].nByte;
        for(j=iMatch+1; j<nMatch; j++){
          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
              && aMatch[j].snStatus==SNIPPET_DESIRED ){
            nDesired--;
            aMatch[j].snStatus = SNIPPET_IGNORE;
          }
        }
      }else{
        nappend(&sb, &zDoc[iStart], iEnd - iStart);
        iStart = iEnd;
      }
    }
    tailCol = iCol;
    tailOffset = iEnd;
  }
  trimWhiteSpace(&sb);
  if( tailEllipsis ){
    appendWhiteSpace(&sb);
    append(&sb, zEllipsis);
  }
  pCursor->snippet.zSnippet = stringBufferData(&sb);
  pCursor->snippet.nSnippet = stringBufferLength(&sb);
}


/*
** Close the cursor.  For additional information see the documentation
** on the xClose method of the virtual table interface.
*/
static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  FTSTRACE(("FTS3 Close %p\n", c));
  sqlite3_finalize(c->pStmt);
  sqlite3Fts3ExprFree(c->pExpr);
  snippetClear(&c->snippet);
  if( c->result.nData!=0 ){
    dlrDestroy(&c->reader);
  }
  dataBufferDestroy(&c->result);
  sqlite3_free(c);
  return SQLITE_OK;
}

static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  int rc;

  FTSTRACE(("FTS3 Next %p\n", pCursor));
  snippetClear(&c->snippet);
  if( c->iCursorType < QUERY_FULLTEXT ){
    /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
    rc = sqlite3_step(c->pStmt);
    switch( rc ){
      case SQLITE_ROW:
        c->eof = 0;
        return SQLITE_OK;
      case SQLITE_DONE:
        c->eof = 1;
        return SQLITE_OK;
      default:
        c->eof = 1;
        return rc;
    }
  } else {  /* full-text query */
    rc = sqlite3_reset(c->pStmt);
    if( rc!=SQLITE_OK ) return rc;

    if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
      c->eof = 1;
      return SQLITE_OK;
    }
    rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
    dlrStep(&c->reader);
    if( rc!=SQLITE_OK ) return rc;
    /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
    rc = sqlite3_step(c->pStmt);
    if( rc==SQLITE_ROW ){   /* the case we expect */
      c->eof = 0;
      return SQLITE_OK;
    }
    /* an error occurred; abort */
    return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  }
}


/* TODO(shess) If we pushed LeafReader to the top of the file, or to
** another file, term_select() could be pushed above
** docListOfTerm().
*/
static int termSelect(fulltext_vtab *v, int iColumn,
                      const char *pTerm, int nTerm, int isPrefix,
                      DocListType iType, DataBuffer *out);

/* 
** Return a DocList corresponding to the phrase *pPhrase.
**
** The resulting DL_DOCIDS doclist is stored in pResult, which is
** overwritten.
*/
static int docListOfPhrase(
  fulltext_vtab *pTab,   /* The full text index */
  Fts3Phrase *pPhrase,   /* Phrase to return a doclist corresponding to */
  DocListType eListType, /* Either DL_DOCIDS or DL_POSITIONS */
  DataBuffer *pResult    /* Write the result here */
){
  int ii;
  int rc = SQLITE_OK;
  int iCol = pPhrase->iColumn;
  DocListType eType = eListType;
  assert( eType==DL_POSITIONS || eType==DL_DOCIDS );
  if( pPhrase->nToken>1 ){
    eType = DL_POSITIONS;
  }

  /* This code should never be called with buffered updates. */
  assert( pTab->nPendingData<0 );

  for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
    DataBuffer tmp;
    struct PhraseToken *p = &pPhrase->aToken[ii];
    rc = termSelect(pTab, iCol, p->z, p->n, p->isPrefix, eType, &tmp);
    if( rc==SQLITE_OK ){
      if( ii==0 ){
        *pResult = tmp;
      }else{
        DataBuffer res = *pResult;
        dataBufferInit(pResult, 0);
        if( ii==(pPhrase->nToken-1) ){
          eType = eListType;
        }
        docListPhraseMerge(
          res.pData, res.nData, tmp.pData, tmp.nData, 0, 0, eType, pResult
        );
        dataBufferDestroy(&res);
        dataBufferDestroy(&tmp);
      }
    }
  }

  return rc;
}

/*
** Evaluate the full-text expression pExpr against fts3 table pTab. Write
** the results into pRes.
*/
static int evalFts3Expr(
  fulltext_vtab *pTab,           /* Fts3 Virtual table object */
  Fts3Expr *pExpr,               /* Parsed fts3 expression */
  DataBuffer *pRes               /* OUT: Write results of the expression here */
){
  int rc = SQLITE_OK;

  /* Initialize the output buffer. If this is an empty query (pExpr==0), 
  ** this is all that needs to be done. Empty queries produce empty 
  ** result sets.
  */
  dataBufferInit(pRes, 0);

  if( pExpr ){
    if( pExpr->eType==FTSQUERY_PHRASE ){
      DocListType eType = DL_DOCIDS;
      if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
        eType = DL_POSITIONS;
      }
      rc = docListOfPhrase(pTab, pExpr->pPhrase, eType, pRes);
    }else{
      DataBuffer lhs;
      DataBuffer rhs;

      dataBufferInit(&rhs, 0);
      if( SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pLeft, &lhs)) 
       && SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pRight, &rhs)) 
      ){
        switch( pExpr->eType ){
          case FTSQUERY_NEAR: {
            int nToken;
            Fts3Expr *pLeft;
            DocListType eType = DL_DOCIDS;
            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
              eType = DL_POSITIONS;
            }
            pLeft = pExpr->pLeft;
            while( pLeft->eType==FTSQUERY_NEAR ){ 
              pLeft=pLeft->pRight;
            }
            assert( pExpr->pRight->eType==FTSQUERY_PHRASE );
            assert( pLeft->eType==FTSQUERY_PHRASE );
            nToken = pLeft->pPhrase->nToken + pExpr->pRight->pPhrase->nToken;
            docListPhraseMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, 
                pExpr->nNear+1, nToken, eType, pRes
            );
            break;
          }
          case FTSQUERY_NOT: {
            docListExceptMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData,pRes);
            break;
          }
          case FTSQUERY_AND: {
            docListAndMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
            break;
          }
          case FTSQUERY_OR: {
            docListOrMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
            break;
          }
        }
      }
      dataBufferDestroy(&lhs);
      dataBufferDestroy(&rhs);
    }
  }

  return rc;
}

/* TODO(shess) Refactor the code to remove this forward decl. */
static int flushPendingTerms(fulltext_vtab *v);

/* Perform a full-text query using the search expression in
** zInput[0..nInput-1].  Return a list of matching documents
** in pResult.
**
** Queries must match column iColumn.  Or if iColumn>=nColumn
** they are allowed to match against any column.
*/
static int fulltextQuery(
  fulltext_vtab *v,      /* The full text index */
  int iColumn,           /* Match against this column by default */
  const char *zInput,    /* The query string */
  int nInput,            /* Number of bytes in zInput[] */
  DataBuffer *pResult,   /* Write the result doclist here */
  Fts3Expr **ppExpr        /* Put parsed query string here */
){
  int rc;

  /* TODO(shess) Instead of flushing pendingTerms, we could query for
  ** the relevant term and merge the doclist into what we receive from
  ** the database.  Wait and see if this is a common issue, first.
  **
  ** A good reason not to flush is to not generate update-related
  ** error codes from here.
  */

  /* Flush any buffered updates before executing the query. */
  rc = flushPendingTerms(v);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  /* Parse the query passed to the MATCH operator. */
  rc = sqlite3Fts3ExprParse(v->pTokenizer, 
      v->azColumn, v->nColumn, iColumn, zInput, nInput, ppExpr
  );
  if( rc!=SQLITE_OK ){
    assert( 0==(*ppExpr) );
    return rc;
  }

  return evalFts3Expr(v, *ppExpr, pResult);
}

/*
** This is the xFilter interface for the virtual table.  See
** the virtual table xFilter method documentation for additional
** information.
**
** If idxNum==QUERY_GENERIC then do a full table scan against
** the %_content table.
**
** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
** in the %_content table.
**
** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
** column on the left-hand side of the MATCH operator is column
** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
** side of the MATCH operator.
*/
/* TODO(shess) Upgrade the cursor initialization and destruction to
** account for fulltextFilter() being called multiple times on the
** same cursor.  The current solution is very fragile.  Apply fix to
** fts3 as appropriate.
*/
static int fulltextFilter(
  sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
  int idxNum, const char *idxStr,   /* Which indexing scheme to use */
  int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);
  int rc;

  FTSTRACE(("FTS3 Filter %p\n",pCursor));

  /* If the cursor has a statement that was not prepared according to
  ** idxNum, clear it.  I believe all calls to fulltextFilter with a
  ** given cursor will have the same idxNum , but in this case it's
  ** easy to be safe.
  */
  if( c->pStmt && c->iCursorType!=idxNum ){
    sqlite3_finalize(c->pStmt);
    c->pStmt = NULL;
  }

  /* Get a fresh statement appropriate to idxNum. */
  /* TODO(shess): Add a prepared-statement cache in the vt structure.
  ** The cache must handle multiple open cursors.  Easier to cache the
  ** statement variants at the vt to reduce malloc/realloc/free here.
  ** Or we could have a StringBuffer variant which allowed stack
  ** construction for small values.
  */
  if( !c->pStmt ){
    StringBuffer sb;
    initStringBuffer(&sb);
    append(&sb, "SELECT docid, ");
    appendList(&sb, v->nColumn, v->azContentColumn);
    append(&sb, " FROM %_content");
    if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
    rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
                     stringBufferData(&sb));
    stringBufferDestroy(&sb);
    if( rc!=SQLITE_OK ) return rc;
    c->iCursorType = idxNum;
  }else{
    sqlite3_reset(c->pStmt);
    assert( c->iCursorType==idxNum );
  }

  switch( idxNum ){
    case QUERY_GENERIC:
      break;

    case QUERY_DOCID:
      rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
      if( rc!=SQLITE_OK ) return rc;
      break;

    default:   /* full-text search */
    {
      int iCol = idxNum-QUERY_FULLTEXT;
      const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
      assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
      assert( argc==1 );
      if( c->result.nData!=0 ){
        /* This case happens if the same cursor is used repeatedly. */
        dlrDestroy(&c->reader);
        dataBufferReset(&c->result);
      }else{
        dataBufferInit(&c->result, 0);
      }
      rc = fulltextQuery(v, iCol, zQuery, -1, &c->result, &c->pExpr);
      if( rc!=SQLITE_OK ) return rc;
      if( c->result.nData!=0 ){
        dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
      }
      break;
    }
  }

  return fulltextNext(pCursor);
}

/* This is the xEof method of the virtual table.  The SQLite core
** calls this routine to find out if it has reached the end of
** a query's results set.
*/
static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  return c->eof;
}

/* This is the xColumn method of the virtual table.  The SQLite
** core calls this method during a query when it needs the value
** of a column from the virtual table.  This method needs to use
** one of the sqlite3_result_*() routines to store the requested
** value back in the pContext.
*/
static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
                          sqlite3_context *pContext, int idxCol){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;
  fulltext_vtab *v = cursor_vtab(c);

  if( idxCol<v->nColumn ){
    sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
    sqlite3_result_value(pContext, pVal);
  }else if( idxCol==v->nColumn ){
    /* The extra column whose name is the same as the table.
    ** Return a blob which is a pointer to the cursor
    */
    sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
  }else if( idxCol==v->nColumn+1 ){
    /* The docid column, which is an alias for rowid. */
    sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
    sqlite3_result_value(pContext, pVal);
  }
  return SQLITE_OK;
}

/* This is the xRowid method.  The SQLite core calls this routine to
** retrieve the rowid for the current row of the result set.  fts3
** exposes %_content.docid as the rowid for the virtual table.  The
** rowid should be written to *pRowid.
*/
static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  fulltext_cursor *c = (fulltext_cursor *) pCursor;

  *pRowid = sqlite3_column_int64(c->pStmt, 0);
  return SQLITE_OK;
}

/* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
** we also store positions and offsets in the hash table using that
** column number.
*/
static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
                      const char *zText, int iColumn){
  sqlite3_tokenizer *pTokenizer = v->pTokenizer;
  sqlite3_tokenizer_cursor *pCursor;
  const char *pToken;
  int nTokenBytes;
  int iStartOffset, iEndOffset, iPosition;
  int rc;

  rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  if( rc!=SQLITE_OK ) return rc;

  pCursor->pTokenizer = pTokenizer;
  while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
                                                   &pToken, &nTokenBytes,
                                                   &iStartOffset, &iEndOffset,
                                                   &iPosition)) ){
    DLCollector *p;
    int nData;                   /* Size of doclist before our update. */

    /* Positions can't be negative; we use -1 as a terminator
     * internally.  Token can't be NULL or empty. */
    if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
      rc = SQLITE_ERROR;
      break;
    }

    p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
    if( p==NULL ){
      nData = 0;
      p = dlcNew(iDocid, DL_DEFAULT);
      fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);

      /* Overhead for our hash table entry, the key, and the value. */
      v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
    }else{
      nData = p->b.nData;
      if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
    }
    if( iColumn>=0 ){
      dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
    }

    /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
    v->nPendingData += p->b.nData-nData;
  }

  /* TODO(shess) Check return?  Should this be able to cause errors at
  ** this point?  Actually, same question about sqlite3_finalize(),
  ** though one could argue that failure there means that the data is
  ** not durable.  *ponder*
  */
  pTokenizer->pModule->xClose(pCursor);
  if( SQLITE_DONE == rc ) return SQLITE_OK;
  return rc;
}

/* Add doclists for all terms in [pValues] to pendingTerms table. */
static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
                       sqlite3_value **pValues){
  int i;
  for(i = 0; i < v->nColumn ; ++i){
    char *zText = (char*)sqlite3_value_text(pValues[i]);
    int rc = buildTerms(v, iDocid, zText, i);
    if( rc!=SQLITE_OK ) return rc;
  }
  return SQLITE_OK;
}

/* Add empty doclists for all terms in the given row's content to
** pendingTerms.
*/
static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  const char **pValues;
  int i, rc;

  /* TODO(shess) Should we allow such tables at all? */
  if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;

  rc = content_select(v, iDocid, &pValues);
  if( rc!=SQLITE_OK ) return rc;

  for(i = 0 ; i < v->nColumn; ++i) {
    rc = buildTerms(v, iDocid, pValues[i], -1);
    if( rc!=SQLITE_OK ) break;
  }

  freeStringArray(v->nColumn, pValues);
  return SQLITE_OK;
}

/* TODO(shess) Refactor the code to remove this forward decl. */
static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);

/* Insert a row into the %_content table; set *piDocid to be the ID of the
** new row.  Add doclists for terms to pendingTerms.
*/
static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
                        sqlite3_value **pValues, sqlite_int64 *piDocid){
  int rc;

  rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
  if( rc!=SQLITE_OK ) return rc;

  /* docid column is an alias for rowid. */
  *piDocid = sqlite3_last_insert_rowid(v->db);
  rc = initPendingTerms(v, *piDocid);
  if( rc!=SQLITE_OK ) return rc;

  return insertTerms(v, *piDocid, pValues);
}

/* Delete a row from the %_content table; add empty doclists for terms
** to pendingTerms.
*/
static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  int rc = initPendingTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = deleteTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  return content_delete(v, iRow);  /* execute an SQL DELETE */
}

/* Update a row in the %_content table; add delete doclists to
** pendingTerms for old terms not in the new data, add insert doclists
** to pendingTerms for terms in the new data.
*/
static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
                        sqlite3_value **pValues){
  int rc = initPendingTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  /* Generate an empty doclist for each term that previously appeared in this
   * row. */
  rc = deleteTerms(v, iRow);
  if( rc!=SQLITE_OK ) return rc;

  rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
  if( rc!=SQLITE_OK ) return rc;

  /* Now add positions for terms which appear in the updated row. */
  return insertTerms(v, iRow, pValues);
}

/*******************************************************************/
/* InteriorWriter is used to collect terms and block references into
** interior nodes in %_segments.  See commentary at top of file for
** format.
*/

/* How large interior nodes can grow. */
#define INTERIOR_MAX 2048

/* Minimum number of terms per interior node (except the root). This
** prevents large terms from making the tree too skinny - must be >0
** so that the tree always makes progress.  Note that the min tree
** fanout will be INTERIOR_MIN_TERMS+1.
*/
#define INTERIOR_MIN_TERMS 7
#if INTERIOR_MIN_TERMS<1
# error INTERIOR_MIN_TERMS must be greater than 0.
#endif

/* ROOT_MAX controls how much data is stored inline in the segment
** directory.
*/
/* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
** can both see it, but if the caller passed it in, we wouldn't even
** need a define.
*/
#define ROOT_MAX 1024
#if ROOT_MAX<VARINT_MAX*2
# error ROOT_MAX must have enough space for a header.
#endif

/* InteriorBlock stores a linked-list of interior blocks while a lower
** layer is being constructed.
*/
typedef struct InteriorBlock {
  DataBuffer term;           /* Leftmost term in block's subtree. */
  DataBuffer data;           /* Accumulated data for the block. */
  struct InteriorBlock *next;
} InteriorBlock;

static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
                                       const char *pTerm, int nTerm){
  InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
  char c[VARINT_MAX+VARINT_MAX];
  int n;

  if( block ){
    memset(block, 0, sizeof(*block));
    dataBufferInit(&block->term, 0);
    dataBufferReplace(&block->term, pTerm, nTerm);

    n = fts3PutVarint(c, iHeight);
    n += fts3PutVarint(c+n, iChildBlock);
    dataBufferInit(&block->data, INTERIOR_MAX);
    dataBufferReplace(&block->data, c, n);
  }
  return block;
}

#ifndef NDEBUG
/* Verify that the data is readable as an interior node. */
static void interiorBlockValidate(InteriorBlock *pBlock){
  const char *pData = pBlock->data.pData;
  int nData = pBlock->data.nData;
  int n, iDummy;
  sqlite_int64 iBlockid;

  assert( nData>0 );
  assert( pData!=0 );
  assert( pData+nData>pData );

  /* Must lead with height of node as a varint(n), n>0 */
  n = fts3GetVarint32(pData, &iDummy);
  assert( n>0 );
  assert( iDummy>0 );
  assert( n<nData );
  pData += n;
  nData -= n;

  /* Must contain iBlockid. */
  n = fts3GetVarint(pData, &iBlockid);
  assert( n>0 );
  assert( n<=nData );
  pData += n;
  nData -= n;

  /* Zero or more terms of positive length */
  if( nData!=0 ){
    /* First term is not delta-encoded. */
    n = fts3GetVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>0 );
    assert( n+iDummy>0);
    assert( n+iDummy<=nData );
    pData += n+iDummy;
    nData -= n+iDummy;

    /* Following terms delta-encoded. */
    while( nData!=0 ){
      /* Length of shared prefix. */
      n = fts3GetVarint32(pData, &iDummy);
      assert( n>0 );
      assert( iDummy>=0 );
      assert( n<nData );
      pData += n;
      nData -= n;

      /* Length and data of distinct suffix. */
      n = fts3GetVarint32(pData, &iDummy);
      assert( n>0 );
      assert( iDummy>0 );
      assert( n+iDummy>0);
      assert( n+iDummy<=nData );
      pData += n+iDummy;
      nData -= n+iDummy;
    }
  }
}
#define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
#else
#define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
#endif

typedef struct InteriorWriter {
  int iHeight;                   /* from 0 at leaves. */
  InteriorBlock *first, *last;
  struct InteriorWriter *parentWriter;

  DataBuffer term;               /* Last term written to block "last". */
  sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
#ifndef NDEBUG
  sqlite_int64 iLastChildBlock;  /* for consistency checks. */
#endif
} InteriorWriter;

/* Initialize an interior node where pTerm[nTerm] marks the leftmost
** term in the tree.  iChildBlock is the leftmost child block at the
** next level down the tree.
*/
static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
                               sqlite_int64 iChildBlock,
                               InteriorWriter *pWriter){
  InteriorBlock *block;
  assert( iHeight>0 );
  CLEAR(pWriter);

  pWriter->iHeight = iHeight;
  pWriter->iOpeningChildBlock = iChildBlock;
#ifndef NDEBUG
  pWriter->iLastChildBlock = iChildBlock;
#endif
  block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
  pWriter->last = pWriter->first = block;
  ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  dataBufferInit(&pWriter->term, 0);
}

/* Append the child node rooted at iChildBlock to the interior node,
** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
*/
static void interiorWriterAppend(InteriorWriter *pWriter,
                                 const char *pTerm, int nTerm,
                                 sqlite_int64 iChildBlock){
  char c[VARINT_MAX+VARINT_MAX];
  int n, nPrefix = 0;

  ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);

  /* The first term written into an interior node is actually
  ** associated with the second child added (the first child was added
  ** in interiorWriterInit, or in the if clause at the bottom of this
  ** function).  That term gets encoded straight up, with nPrefix left
  ** at 0.
  */
  if( pWriter->term.nData==0 ){
    n = fts3PutVarint(c, nTerm);
  }else{
    while( nPrefix<pWriter->term.nData &&
           pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
      nPrefix++;
    }

    n = fts3PutVarint(c, nPrefix);
    n += fts3PutVarint(c+n, nTerm-nPrefix);
  }

#ifndef NDEBUG
  pWriter->iLastChildBlock++;
#endif
  assert( pWriter->iLastChildBlock==iChildBlock );

  /* Overflow to a new block if the new term makes the current block
  ** too big, and the current block already has enough terms.
  */
  if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
      iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
    pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
                                           pTerm, nTerm);
    pWriter->last = pWriter->last->next;
    pWriter->iOpeningChildBlock = iChildBlock;
    dataBufferReset(&pWriter->term);
  }else{
    dataBufferAppend2(&pWriter->last->data, c, n,
                      pTerm+nPrefix, nTerm-nPrefix);
    dataBufferReplace(&pWriter->term, pTerm, nTerm);
  }
  ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
}

/* Free the space used by pWriter, including the linked-list of
** InteriorBlocks, and parentWriter, if present.
*/
static int interiorWriterDestroy(InteriorWriter *pWriter){
  InteriorBlock *block = pWriter->first;

  while( block!=NULL ){
    InteriorBlock *b = block;
    block = block->next;
    dataBufferDestroy(&b->term);
    dataBufferDestroy(&b->data);
    sqlite3_free(b);
  }
  if( pWriter->parentWriter!=NULL ){
    interiorWriterDestroy(pWriter->parentWriter);
    sqlite3_free(pWriter->parentWriter);
  }
  dataBufferDestroy(&pWriter->term);
  SCRAMBLE(pWriter);
  return SQLITE_OK;
}

/* If pWriter can fit entirely in ROOT_MAX, return it as the root info
** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
** pWriter to %_segments, building a new layer of interior nodes, and
** recursively ask for their root into.
*/
static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
                                  char **ppRootInfo, int *pnRootInfo,
                                  sqlite_int64 *piEndBlockid){
  InteriorBlock *block = pWriter->first;
  sqlite_int64 iBlockid = 0;
  int rc;

  /* If we can fit the segment inline */
  if( block==pWriter->last && block->data.nData<ROOT_MAX ){
    *ppRootInfo = block->data.pData;
    *pnRootInfo = block->data.nData;
    return SQLITE_OK;
  }

  /* Flush the first block to %_segments, and create a new level of
  ** interior node.
  */
  ASSERT_VALID_INTERIOR_BLOCK(block);
  rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  if( rc!=SQLITE_OK ) return rc;
  *piEndBlockid = iBlockid;

  pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
  interiorWriterInit(pWriter->iHeight+1,
                     block->term.pData, block->term.nData,
                     iBlockid, pWriter->parentWriter);

  /* Flush additional blocks and append to the higher interior
  ** node.
  */
  for(block=block->next; block!=NULL; block=block->next){
    ASSERT_VALID_INTERIOR_BLOCK(block);
    rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
    if( rc!=SQLITE_OK ) return rc;
    *piEndBlockid = iBlockid;

    interiorWriterAppend(pWriter->parentWriter,
                         block->term.pData, block->term.nData, iBlockid);
  }

  /* Parent node gets the chance to be the root. */
  return interiorWriterRootInfo(v, pWriter->parentWriter,
                                ppRootInfo, pnRootInfo, piEndBlockid);
}

/****************************************************************/
/* InteriorReader is used to read off the data from an interior node
** (see comment at top of file for the format).
*/
typedef struct InteriorReader {
  const char *pData;
  int nData;

  DataBuffer term;          /* previous term, for decoding term delta. */

  sqlite_int64 iBlockid;
} InteriorReader;

static void interiorReaderDestroy(InteriorReader *pReader){
  dataBufferDestroy(&pReader->term);
  SCRAMBLE(pReader);
}

/* TODO(shess) The assertions are great, but what if we're in NDEBUG
** and the blob is empty or otherwise contains suspect data?
*/
static void interiorReaderInit(const char *pData, int nData,
                               InteriorReader *pReader){
  int n, nTerm;

  /* Require at least the leading flag byte */
  assert( nData>0 );
  assert( pData[0]!='\0' );

  CLEAR(pReader);

  /* Decode the base blockid, and set the cursor to the first term. */
  n = fts3GetVarint(pData+1, &pReader->iBlockid);
  assert( 1+n<=nData );
  pReader->pData = pData+1+n;
  pReader->nData = nData-(1+n);

  /* A single-child interior node (such as when a leaf node was too
  ** large for the segment directory) won't have any terms.
  ** Otherwise, decode the first term.
  */
  if( pReader->nData==0 ){
    dataBufferInit(&pReader->term, 0);
  }else{
    n = fts3GetVarint32(pReader->pData, &nTerm);
    dataBufferInit(&pReader->term, nTerm);
    dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
    assert( n+nTerm<=pReader->nData );
    pReader->pData += n+nTerm;
    pReader->nData -= n+nTerm;
  }
}

static int interiorReaderAtEnd(InteriorReader *pReader){
  return pReader->term.nData==0;
}

static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
  return pReader->iBlockid;
}

static int interiorReaderTermBytes(InteriorReader *pReader){
  assert( !interiorReaderAtEnd(pReader) );
  return pReader->term.nData;
}
static const char *interiorReaderTerm(InteriorReader *pReader){
  assert( !interiorReaderAtEnd(pReader) );
  return pReader->term.pData;
}

/* Step forward to the next term in the node. */
static void interiorReaderStep(InteriorReader *pReader){
  assert( !interiorReaderAtEnd(pReader) );

  /* If the last term has been read, signal eof, else construct the
  ** next term.
  */
  if( pReader->nData==0 ){
    dataBufferReset(&pReader->term);
  }else{
    int n, nPrefix, nSuffix;

    n = fts3GetVarint32(pReader->pData, &nPrefix);
    n += fts3GetVarint32(pReader->pData+n, &nSuffix);

    /* Truncate the current term and append suffix data. */
    pReader->term.nData = nPrefix;
    dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);

    assert( n+nSuffix<=pReader->nData );
    pReader->pData += n+nSuffix;
    pReader->nData -= n+nSuffix;
  }
  pReader->iBlockid++;
}

/* Compare the current term to pTerm[nTerm], returning strcmp-style
** results.  If isPrefix, equality means equal through nTerm bytes.
*/
static int interiorReaderTermCmp(InteriorReader *pReader,
                                 const char *pTerm, int nTerm, int isPrefix){
  const char *pReaderTerm = interiorReaderTerm(pReader);
  int nReaderTerm = interiorReaderTermBytes(pReader);
  int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;

  if( n==0 ){
    if( nReaderTerm>0 ) return -1;
    if( nTerm>0 ) return 1;
    return 0;
  }

  c = memcmp(pReaderTerm, pTerm, n);
  if( c!=0 ) return c;
  if( isPrefix && n==nTerm ) return 0;
  return nReaderTerm - nTerm;
}

/****************************************************************/
/* LeafWriter is used to collect terms and associated doclist data
** into leaf blocks in %_segments (see top of file for format info).
** Expected usage is:
**
** LeafWriter writer;
** leafWriterInit(0, 0, &writer);
** while( sorted_terms_left_to_process ){
**   // data is doclist data for that term.
**   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
**   if( rc!=SQLITE_OK ) goto err;
** }
** rc = leafWriterFinalize(v, &writer);
**err:
** leafWriterDestroy(&writer);
** return rc;
**
** leafWriterStep() may write a collected leaf out to %_segments.
** leafWriterFinalize() finishes writing any buffered data and stores
** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
** InteriorWriters allocated as part of writing this segment.
**
** TODO(shess) Document leafWriterStepMerge().
*/

/* Put terms with data this big in their own block. */
#define STANDALONE_MIN 1024

/* Keep leaf blocks below this size. */
#define LEAF_MAX 2048

typedef struct LeafWriter {
  int iLevel;
  int idx;
  sqlite_int64 iStartBlockid;     /* needed to create the root info */
  sqlite_int64 iEndBlockid;       /* when we're done writing. */

  DataBuffer term;                /* previous encoded term */
  DataBuffer data;                /* encoding buffer */

  /* bytes of first term in the current node which distinguishes that
  ** term from the last term of the previous node.
  */
  int nTermDistinct;

  InteriorWriter parentWriter;    /* if we overflow */
  int has_parent;
} LeafWriter;

static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
  CLEAR(pWriter);
  pWriter->iLevel = iLevel;
  pWriter->idx = idx;

  dataBufferInit(&pWriter->term, 32);

  /* Start out with a reasonably sized block, though it can grow. */
  dataBufferInit(&pWriter->data, LEAF_MAX);
}

#ifndef NDEBUG
/* Verify that the data is readable as a leaf node. */
static void leafNodeValidate(const char *pData, int nData){
  int n, iDummy;

  if( nData==0 ) return;
  assert( nData>0 );
  assert( pData!=0 );
  assert( pData+nData>pData );

  /* Must lead with a varint(0) */
  n = fts3GetVarint32(pData, &iDummy);
  assert( iDummy==0 );
  assert( n>0 );
  assert( n<nData );
  pData += n;
  nData -= n;

  /* Leading term length and data must fit in buffer. */
  n = fts3GetVarint32(pData, &iDummy);
  assert( n>0 );
  assert( iDummy>0 );
  assert( n+iDummy>0 );
  assert( n+iDummy<nData );
  pData += n+iDummy;
  nData -= n+iDummy;

  /* Leading term's doclist length and data must fit. */
  n = fts3GetVarint32(pData, &iDummy);
  assert( n>0 );
  assert( iDummy>0 );
  assert( n+iDummy>0 );
  assert( n+iDummy<=nData );
  ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  pData += n+iDummy;
  nData -= n+iDummy;

  /* Verify that trailing terms and doclists also are readable. */
  while( nData!=0 ){
    n = fts3GetVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>=0 );
    assert( n<nData );
    pData += n;
    nData -= n;
    n = fts3GetVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>0 );
    assert( n+iDummy>0 );
    assert( n+iDummy<nData );
    pData += n+iDummy;
    nData -= n+iDummy;

    n = fts3GetVarint32(pData, &iDummy);
    assert( n>0 );
    assert( iDummy>0 );
    assert( n+iDummy>0 );
    assert( n+iDummy<=nData );
    ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
    pData += n+iDummy;
    nData -= n+iDummy;
  }
}
#define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
#else
#define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
#endif

/* Flush the current leaf node to %_segments, and adding the resulting
** blockid and the starting term to the interior node which will
** contain it.
*/
static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
                                   int iData, int nData){
  sqlite_int64 iBlockid = 0;
  const char *pStartingTerm;
  int nStartingTerm, rc, n;

  /* Must have the leading varint(0) flag, plus at least some
  ** valid-looking data.
  */
  assert( nData>2 );
  assert( iData>=0 );
  assert( iData+nData<=pWriter->data.nData );
  ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);

  rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
  if( rc!=SQLITE_OK ) return rc;
  assert( iBlockid!=0 );

  /* Reconstruct the first term in the leaf for purposes of building
  ** the interior node.
  */
  n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
  pStartingTerm = pWriter->data.pData+iData+1+n;
  assert( pWriter->data.nData>iData+1+n+nStartingTerm );
  assert( pWriter->nTermDistinct>0 );
  assert( pWriter->nTermDistinct<=nStartingTerm );
  nStartingTerm = pWriter->nTermDistinct;

  if( pWriter->has_parent ){
    interiorWriterAppend(&pWriter->parentWriter,
                         pStartingTerm, nStartingTerm, iBlockid);
  }else{
    interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
                       &pWriter->parentWriter);
    pWriter->has_parent = 1;
  }

  /* Track the span of this segment's leaf nodes. */
  if( pWriter->iEndBlockid==0 ){
    pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
  }else{
    pWriter->iEndBlockid++;
    assert( iBlockid==pWriter->iEndBlockid );
  }

  return SQLITE_OK;
}
static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
  int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
  if( rc!=SQLITE_OK ) return rc;

  /* Re-initialize the output buffer. */
  dataBufferReset(&pWriter->data);

  return SQLITE_OK;
}

/* Fetch the root info for the segment.  If the entire leaf fits
** within ROOT_MAX, then it will be returned directly, otherwise it
** will be flushed and the root info will be returned from the
** interior node.  *piEndBlockid is set to the blockid of the last
** interior or leaf node written to disk (0 if none are written at
** all).
*/
static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
                              char **ppRootInfo, int *pnRootInfo,
                              sqlite_int64 *piEndBlockid){
  /* we can fit the segment entirely inline */
  if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
    *ppRootInfo = pWriter->data.pData;
    *pnRootInfo = pWriter->data.nData;
    *piEndBlockid = 0;
    return SQLITE_OK;
  }

  /* Flush remaining leaf data. */
  if( pWriter->data.nData>0 ){
    int rc = leafWriterFlush(v, pWriter);
    if( rc!=SQLITE_OK ) return rc;
  }

  /* We must have flushed a leaf at some point. */
  assert( pWriter->has_parent );

  /* Tenatively set the end leaf blockid as the end blockid.  If the
  ** interior node can be returned inline, this will be the final
  ** blockid, otherwise it will be overwritten by
  ** interiorWriterRootInfo().
  */
  *piEndBlockid = pWriter->iEndBlockid;

  return interiorWriterRootInfo(v, &pWriter->parentWriter,
                                ppRootInfo, pnRootInfo, piEndBlockid);
}

/* Collect the rootInfo data and store it into the segment directory.
** This has the effect of flushing the segment's leaf data to
** %_segments, and also flushing any interior nodes to %_segments.
*/
static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
  sqlite_int64 iEndBlockid;
  char *pRootInfo;
  int rc, nRootInfo;

  rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
  if( rc!=SQLITE_OK ) return rc;

  /* Don't bother storing an entirely empty segment. */
  if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;

  return segdir_set(v, pWriter->iLevel, pWriter->idx,
                    pWriter->iStartBlockid, pWriter->iEndBlockid,
                    iEndBlockid, pRootInfo, nRootInfo);
}

static void leafWriterDestroy(LeafWriter *pWriter){
  if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
  dataBufferDestroy(&pWriter->term);
  dataBufferDestroy(&pWriter->data);
}

/* Encode a term into the leafWriter, delta-encoding as appropriate.
** Returns the length of the new term which distinguishes it from the
** previous term, which can be used to set nTermDistinct when a node
** boundary is crossed.
*/
static int leafWriterEncodeTerm(LeafWriter *pWriter,
                                const char *pTerm, int nTerm){
  char c[VARINT_MAX+VARINT_MAX];
  int n, nPrefix = 0;

  assert( nTerm>0 );
  while( nPrefix<pWriter->term.nData &&
         pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
    nPrefix++;
    /* Failing this implies that the terms weren't in order. */
    assert( nPrefix<nTerm );
  }

  if( pWriter->data.nData==0 ){
    /* Encode the node header and leading term as:
    **  varint(0)
    **  varint(nTerm)
    **  char pTerm[nTerm]
    */
    n = fts3PutVarint(c, '\0');
    n += fts3PutVarint(c+n, nTerm);
    dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
  }else{
    /* Delta-encode the term as:
    **  varint(nPrefix)
    **  varint(nSuffix)
    **  char pTermSuffix[nSuffix]
    */
    n = fts3PutVarint(c, nPrefix);
    n += fts3PutVarint(c+n, nTerm-nPrefix);
    dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
  }
  dataBufferReplace(&pWriter->term, pTerm, nTerm);

  return nPrefix+1;
}

/* Used to avoid a memmove when a large amount of doclist data is in
** the buffer.  This constructs a node and term header before
** iDoclistData and flushes the resulting complete node using
** leafWriterInternalFlush().
*/
static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
                                 const char *pTerm, int nTerm,
                                 int iDoclistData){
  char c[VARINT_MAX+VARINT_MAX];
  int iData, n = fts3PutVarint(c, 0);
  n += fts3PutVarint(c+n, nTerm);

  /* There should always be room for the header.  Even if pTerm shared
  ** a substantial prefix with the previous term, the entire prefix
  ** could be constructed from earlier data in the doclist, so there
  ** should be room.
  */
  assert( iDoclistData>=n+nTerm );

  iData = iDoclistData-(n+nTerm);
  memcpy(pWriter->data.pData+iData, c, n);
  memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);

  return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
}

/* Push pTerm[nTerm] along with the doclist data to the leaf layer of
** %_segments.
*/
static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
                               const char *pTerm, int nTerm,
                               DLReader *pReaders, int nReaders){
  char c[VARINT_MAX+VARINT_MAX];
  int iTermData = pWriter->data.nData, iDoclistData;
  int i, nData, n, nActualData, nActual, rc, nTermDistinct;

  ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);

  /* Remember nTermDistinct if opening a new node. */
  if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;

  iDoclistData = pWriter->data.nData;

  /* Estimate the length of the merged doclist so we can leave space
  ** to encode it.
  */
  for(i=0, nData=0; i<nReaders; i++){
    nData += dlrAllDataBytes(&pReaders[i]);
  }
  n = fts3PutVarint(c, nData);
  dataBufferAppend(&pWriter->data, c, n);

  docListMerge(&pWriter->data, pReaders, nReaders);
  ASSERT_VALID_DOCLIST(DL_DEFAULT,
                       pWriter->data.pData+iDoclistData+n,
                       pWriter->data.nData-iDoclistData-n, NULL);

  /* The actual amount of doclist data at this point could be smaller
  ** than the length we encoded.  Additionally, the space required to
  ** encode this length could be smaller.  For small doclists, this is
  ** not a big deal, we can just use memmove() to adjust things.
  */
  nActualData = pWriter->data.nData-(iDoclistData+n);
  nActual = fts3PutVarint(c, nActualData);
  assert( nActualData<=nData );
  assert( nActual<=n );

  /* If the new doclist is big enough for force a standalone leaf
  ** node, we can immediately flush it inline without doing the
  ** memmove().
  */
  /* TODO(shess) This test matches leafWriterStep(), which does this
  ** test before it knows the cost to varint-encode the term and
  ** doclist lengths.  At some point, change to
  ** pWriter->data.nData-iTermData>STANDALONE_MIN.
  */
  if( nTerm+nActualData>STANDALONE_MIN ){
    /* Push leaf node from before this term. */
    if( iTermData>0 ){
      rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
      if( rc!=SQLITE_OK ) return rc;

      pWriter->nTermDistinct = nTermDistinct;
    }

    /* Fix the encoded doclist length. */
    iDoclistData += n - nActual;
    memcpy(pWriter->data.pData+iDoclistData, c, nActual);

    /* Push the standalone leaf node. */
    rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
    if( rc!=SQLITE_OK ) return rc;

    /* Leave the node empty. */
    dataBufferReset(&pWriter->data);

    return rc;
  }

  /* At this point, we know that the doclist was small, so do the
  ** memmove if indicated.
  */
  if( nActual<n ){
    memmove(pWriter->data.pData+iDoclistData+nActual,
            pWriter->data.pData+iDoclistData+n,
            pWriter->data.nData-(iDoclistData+n));
    pWriter->data.nData -= n-nActual;
  }

  /* Replace written length with actual length. */
  memcpy(pWriter->data.pData+iDoclistData, c, nActual);

  /* If the node is too large, break things up. */
  /* TODO(shess) This test matches leafWriterStep(), which does this
  ** test before it knows the cost to varint-encode the term and
  ** doclist lengths.  At some point, change to
  ** pWriter->data.nData>LEAF_MAX.
  */
  if( iTermData+nTerm+nActualData>LEAF_MAX ){
    /* Flush out the leading data as a node */
    rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
    if( rc!=SQLITE_OK ) return rc;

    pWriter->nTermDistinct = nTermDistinct;

    /* Rebuild header using the current term */
    n = fts3PutVarint(pWriter->data.pData, 0);
    n += fts3PutVarint(pWriter->data.pData+n, nTerm);
    memcpy(pWriter->data.pData+n, pTerm, nTerm);
    n += nTerm;

    /* There should always be room, because the previous encoding
    ** included all data necessary to construct the term.
    */
    assert( n<iDoclistData );
    /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
    ** following memcpy() is safe (as opposed to needing a memmove).
    */
    assert( 2*STANDALONE_MIN<=LEAF_MAX );
    assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
    memcpy(pWriter->data.pData+n,
           pWriter->data.pData+iDoclistData,
           pWriter->data.nData-iDoclistData);
    pWriter->data.nData -= iDoclistData-n;
  }
  ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);

  return SQLITE_OK;
}

/* Push pTerm[nTerm] along with the doclist data to the leaf layer of
** %_segments.
*/
/* TODO(shess) Revise writeZeroSegment() so that doclists are
** constructed directly in pWriter->data.
*/
static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
                          const char *pTerm, int nTerm,
                          const char *pData, int nData){
  int rc;
  DLReader reader;

  dlrInit(&reader, DL_DEFAULT, pData, nData);
  rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
  dlrDestroy(&reader);

  return rc;
}


/****************************************************************/
/* LeafReader is used to iterate over an individual leaf node. */
typedef struct LeafReader {
  DataBuffer term;          /* copy of current term. */

  const char *pData;        /* data for current term. */
  int nData;
} LeafReader;

static void leafReaderDestroy(LeafReader *pReader){
  dataBufferDestroy(&pReader->term);
  SCRAMBLE(pReader);
}

static int leafReaderAtEnd(LeafReader *pReader){
  return pReader->nData<=0;
}

/* Access the current term. */
static int leafReaderTermBytes(LeafReader *pReader){
  return pReader->term.nData;
}
static const char *leafReaderTerm(LeafReader *pReader){
  assert( pReader->term.nData>0 );
  return pReader->term.pData;
}

/* Access the doclist data for the current term. */
static int leafReaderDataBytes(LeafReader *pReader){
  int nData;
  assert( pReader->term.nData>0 );
  fts3GetVarint32(pReader->pData, &nData);
  return nData;
}
static const char *leafReaderData(LeafReader *pReader){
  int n, nData;
  assert( pReader->term.nData>0 );
  n = fts3GetVarint32(pReader->pData, &nData);
  return pReader->pData+n;
}

static void leafReaderInit(const char *pData, int nData,
                           LeafReader *pReader){
  int nTerm, n;

  assert( nData>0 );
  assert( pData[0]=='\0' );

  CLEAR(pReader);

  /* Read the first term, skipping the header byte. */
  n = fts3GetVarint32(pData+1, &nTerm);
  dataBufferInit(&pReader->term, nTerm);
  dataBufferReplace(&pReader->term, pData+1+n, nTerm);

  /* Position after the first term. */
  assert( 1+n+nTerm<nData );
  pReader->pData = pData+1+n+nTerm;
  pReader->nData = nData-1-n-nTerm;
}

/* Step the reader forward to the next term. */
static void leafReaderStep(LeafReader *pReader){
  int n, nData, nPrefix, nSuffix;
  assert( !leafReaderAtEnd(pReader) );

  /* Skip previous entry's data block. */
  n = fts3GetVarint32(pReader->pData, &nData);
  assert( n+nData<=pReader->nData );
  pReader->pData += n+nData;
  pReader->nData -= n+nData;

  if( !leafReaderAtEnd(pReader) ){
    /* Construct the new term using a prefix from the old term plus a
    ** suffix from the leaf data.
    */
    n = fts3GetVarint32(pReader->pData, &nPrefix);
    n += fts3GetVarint32(pReader->pData+n, &nSuffix);
    assert( n+nSuffix<pReader->nData );
    pReader->term.nData = nPrefix;
    dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);

    pReader->pData += n+nSuffix;
    pReader->nData -= n+nSuffix;
  }
}

/* strcmp-style comparison of pReader's current term against pTerm.
** If isPrefix, equality means equal through nTerm bytes.
*/
static int leafReaderTermCmp(LeafReader *pReader,
                             const char *pTerm, int nTerm, int isPrefix){
  int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
  if( n==0 ){
    if( pReader->term.nData>0 ) return -1;
    if(nTerm>0 ) return 1;
    return 0;
  }

  c = memcmp(pReader->term.pData, pTerm, n);
  if( c!=0 ) return c;
  if( isPrefix && n==nTerm ) return 0;
  return pReader->term.nData - nTerm;
}


/****************************************************************/
/* LeavesReader wraps LeafReader to allow iterating over the entire
** leaf layer of the tree.
*/
typedef struct LeavesReader {
  int idx;                  /* Index within the segment. */

  sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
  int eof;                  /* we've seen SQLITE_DONE from pStmt. */

  LeafReader leafReader;    /* reader for the current leaf. */
  DataBuffer rootData;      /* root data for inline. */
} LeavesReader;

/* Access the current term. */
static int leavesReaderTermBytes(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderTermBytes(&pReader->leafReader);
}
static const char *leavesReaderTerm(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderTerm(&pReader->leafReader);
}

/* Access the doclist data for the current term. */
static int leavesReaderDataBytes(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderDataBytes(&pReader->leafReader);
}
static const char *leavesReaderData(LeavesReader *pReader){
  assert( !pReader->eof );
  return leafReaderData(&pReader->leafReader);
}

static int leavesReaderAtEnd(LeavesReader *pReader){
  return pReader->eof;
}

/* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
** leaving the statement handle open, which locks the table.
*/
/* TODO(shess) This "solution" is not satisfactory.  Really, there
** should be check-in function for all statement handles which
** arranges to call sqlite3_reset().  This most likely will require
** modification to control flow all over the place, though, so for now
** just punt.
**
** Note the the current system assumes that segment merges will run to
** completion, which is why this particular probably hasn't arisen in
** this case.  Probably a brittle assumption.
*/
static int leavesReaderReset(LeavesReader *pReader){
  return sqlite3_reset(pReader->pStmt);
}

static void leavesReaderDestroy(LeavesReader *pReader){
  /* If idx is -1, that means we're using a non-cached statement
  ** handle in the optimize() case, so we need to release it.
  */
  if( pReader->pStmt!=NULL && pReader->idx==-1 ){
    sqlite3_finalize(pReader->pStmt);
  }
  leafReaderDestroy(&pReader->leafReader);
  dataBufferDestroy(&pReader->rootData);
  SCRAMBLE(pReader);
}

/* Initialize pReader with the given root data (if iStartBlockid==0
** the leaf data was entirely contained in the root), or from the
** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
*/
static int leavesReaderInit(fulltext_vtab *v,
                            int idx,
                            sqlite_int64 iStartBlockid,
                            sqlite_int64 iEndBlockid,
                            const char *pRootData, int nRootData,
                            LeavesReader *pReader){
  CLEAR(pReader);
  pReader->idx = idx;

  dataBufferInit(&pReader->rootData, 0);
  if( iStartBlockid==0 ){
    /* Entire leaf level fit in root data. */
    dataBufferReplace(&pReader->rootData, pRootData, nRootData);
    leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
                   &pReader->leafReader);
  }else{
    sqlite3_stmt *s;
    int rc = sql_get_leaf_statement(v, idx, &s);
    if( rc!=SQLITE_OK ) return rc;

    rc = sqlite3_bind_int64(s, 1, iStartBlockid);
    if( rc!=SQLITE_OK ) return rc;

    rc = sqlite3_bind_int64(s, 2, iEndBlockid);
    if( rc!=SQLITE_OK ) return rc;

    rc = sqlite3_step(s);
    if( rc==SQLITE_DONE ){
      pReader->eof = 1;
      return SQLITE_OK;
    }
    if( rc!=SQLITE_ROW ) return rc;

    pReader->pStmt = s;
    leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
                   sqlite3_column_bytes(pReader->pStmt, 0),
                   &pReader->leafReader);
  }
  return SQLITE_OK;
}

/* Step the current leaf forward to the next term.  If we reach the
** end of the current leaf, step forward to the next leaf block.
*/
static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
  assert( !leavesReaderAtEnd(pReader) );
  leafReaderStep(&pReader->leafReader);

  if( leafReaderAtEnd(&pReader->leafReader) ){
    int rc;
    if( pReader->rootData.pData ){
      pReader->eof = 1;
      return SQLITE_OK;
    }
    rc = sqlite3_step(pReader->pStmt);
    if( rc!=SQLITE_ROW ){
      pReader->eof = 1;
      return rc==SQLITE_DONE ? SQLITE_OK : rc;
    }
    leafReaderDestroy(&pReader->leafReader);
    leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
                   sqlite3_column_bytes(pReader->pStmt, 0),
                   &pReader->leafReader);
  }
  return SQLITE_OK;
}

/* Order LeavesReaders by their term, ignoring idx.  Readers at eof
** always sort to the end.
*/
static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
  if( leavesReaderAtEnd(lr1) ){
    if( leavesReaderAtEnd(lr2) ) return 0;
    return 1;
  }
  if( leavesReaderAtEnd(lr2) ) return -1;

  return leafReaderTermCmp(&lr1->leafReader,
                           leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
                           0);
}

/* Similar to leavesReaderTermCmp(), with additional ordering by idx
** so that older segments sort before newer segments.
*/
static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
  int c = leavesReaderTermCmp(lr1, lr2);
  if( c!=0 ) return c;
  return lr1->idx-lr2->idx;
}

/* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
** sorted position.
*/
static void leavesReaderReorder(LeavesReader *pLr, int nLr){
  while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
    LeavesReader tmp = pLr[0];
    pLr[0] = pLr[1];
    pLr[1] = tmp;
    nLr--;
    pLr++;
  }
}

/* Initializes pReaders with the segments from level iLevel, returning
** the number of segments in *piReaders.  Leaves pReaders in sorted
** order.
*/
static int leavesReadersInit(fulltext_vtab *v, int iLevel,
                             LeavesReader *pReaders, int *piReaders){
  sqlite3_stmt *s;
  int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int(s, 1, iLevel);
  if( rc!=SQLITE_OK ) return rc;

  i = 0;
  while( (rc = sqlite3_step(s))==SQLITE_ROW ){
    sqlite_int64 iStart = sqlite3_column_int64(s, 0);
    sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
    const char *pRootData = sqlite3_column_blob(s, 2);
    int nRootData = sqlite3_column_bytes(s, 2);

    assert( i<MERGE_COUNT );
    rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
                          &pReaders[i]);
    if( rc!=SQLITE_OK ) break;

    i++;
  }
  if( rc!=SQLITE_DONE ){
    while( i-->0 ){
      leavesReaderDestroy(&pReaders[i]);
    }
    return rc;
  }

  *piReaders = i;

  /* Leave our results sorted by term, then age. */
  while( i-- ){
    leavesReaderReorder(pReaders+i, *piReaders-i);
  }
  return SQLITE_OK;
}

/* Merge doclists from pReaders[nReaders] into a single doclist, which
** is written to pWriter.  Assumes pReaders is ordered oldest to
** newest.
*/
/* TODO(shess) Consider putting this inline in segmentMerge(). */
static int leavesReadersMerge(fulltext_vtab *v,
                              LeavesReader *pReaders, int nReaders,
                              LeafWriter *pWriter){
  DLReader dlReaders[MERGE_COUNT];
  const char *pTerm = leavesReaderTerm(pReaders);
  int i, nTerm = leavesReaderTermBytes(pReaders);

  assert( nReaders<=MERGE_COUNT );

  for(i=0; i<nReaders; i++){
    dlrInit(&dlReaders[i], DL_DEFAULT,
            leavesReaderData(pReaders+i),
            leavesReaderDataBytes(pReaders+i));
  }

  return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
}

/* Forward ref due to mutual recursion with segdirNextIndex(). */
static int segmentMerge(fulltext_vtab *v, int iLevel);

/* Put the next available index at iLevel into *pidx.  If iLevel
** already has MERGE_COUNT segments, they are merged to a higher
** level to make room.
*/
static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
  int rc = segdir_max_index(v, iLevel, pidx);
  if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
    *pidx = 0;
  }else if( rc==SQLITE_ROW ){
    if( *pidx==(MERGE_COUNT-1) ){
      rc = segmentMerge(v, iLevel);
      if( rc!=SQLITE_OK ) return rc;
      *pidx = 0;
    }else{
      (*pidx)++;
    }
  }else{
    return rc;
  }
  return SQLITE_OK;
}

/* Merge MERGE_COUNT segments at iLevel into a new segment at
** iLevel+1.  If iLevel+1 is already full of segments, those will be
** merged to make room.
*/
static int segmentMerge(fulltext_vtab *v, int iLevel){
  LeafWriter writer;
  LeavesReader lrs[MERGE_COUNT];
  int i, rc, idx = 0;

  /* Determine the next available segment index at the next level,
  ** merging as necessary.
  */
  rc = segdirNextIndex(v, iLevel+1, &idx);
  if( rc!=SQLITE_OK ) return rc;

  /* TODO(shess) This assumes that we'll always see exactly
  ** MERGE_COUNT segments to merge at a given level.  That will be
  ** broken if we allow the developer to request preemptive or
  ** deferred merging.
  */
  memset(&lrs, '\0', sizeof(lrs));
  rc = leavesReadersInit(v, iLevel, lrs, &i);
  if( rc!=SQLITE_OK ) return rc;
  assert( i==MERGE_COUNT );

  leafWriterInit(iLevel+1, idx, &writer);

  /* Since leavesReaderReorder() pushes readers at eof to the end,
  ** when the first reader is empty, all will be empty.
  */
  while( !leavesReaderAtEnd(lrs) ){
    /* Figure out how many readers share their next term. */
    for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
      if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
    }

    rc = leavesReadersMerge(v, lrs, i, &writer);
    if( rc!=SQLITE_OK ) goto err;

    /* Step forward those that were merged. */
    while( i-->0 ){
      rc = leavesReaderStep(v, lrs+i);
      if( rc!=SQLITE_OK ) goto err;

      /* Reorder by term, then by age. */
      leavesReaderReorder(lrs+i, MERGE_COUNT-i);
    }
  }

  for(i=0; i<MERGE_COUNT; i++){
    leavesReaderDestroy(&lrs[i]);
  }

  rc = leafWriterFinalize(v, &writer);
  leafWriterDestroy(&writer);
  if( rc!=SQLITE_OK ) return rc;

  /* Delete the merged segment data. */
  return segdir_delete(v, iLevel);

 err:
  for(i=0; i<MERGE_COUNT; i++){
    leavesReaderDestroy(&lrs[i]);
  }
  leafWriterDestroy(&writer);
  return rc;
}

/* Accumulate the union of *acc and *pData into *acc. */
static void docListAccumulateUnion(DataBuffer *acc,
                                   const char *pData, int nData) {
  DataBuffer tmp = *acc;
  dataBufferInit(acc, tmp.nData+nData);
  docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
  dataBufferDestroy(&tmp);
}

/* TODO(shess) It might be interesting to explore different merge
** strategies, here.  For instance, since this is a sorted merge, we
** could easily merge many doclists in parallel.  With some
** comprehension of the storage format, we could merge all of the
** doclists within a leaf node directly from the leaf node's storage.
** It may be worthwhile to merge smaller doclists before larger
** doclists, since they can be traversed more quickly - but the
** results may have less overlap, making them more expensive in a
** different way.
*/

/* Scan pReader for pTerm/nTerm, and merge the term's doclist over
** *out (any doclists with duplicate docids overwrite those in *out).
** Internal function for loadSegmentLeaf().
*/
static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
                                const char *pTerm, int nTerm, int isPrefix,
                                DataBuffer *out){
  /* doclist data is accumulated into pBuffers similar to how one does
  ** increment in binary arithmetic.  If index 0 is empty, the data is
  ** stored there.  If there is data there, it is merged and the
  ** results carried into position 1, with further merge-and-carry
  ** until an empty position is found.
  */
  DataBuffer *pBuffers = NULL;
  int nBuffers = 0, nMaxBuffers = 0, rc;

  assert( nTerm>0 );

  for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
      rc=leavesReaderStep(v, pReader)){
    /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
    ** already taken to compare the terms of two LeavesReaders.  Think
    ** on a better name.  [Meanwhile, break encapsulation rather than
    ** use a confusing name.]
    */
    int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
    if( c>0 ) break;      /* Past any possible matches. */
    if( c==0 ){
      const char *pData = leavesReaderData(pReader);
      int iBuffer, nData = leavesReaderDataBytes(pReader);

      /* Find the first empty buffer. */
      for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
        if( 0==pBuffers[iBuffer].nData ) break;
      }

      /* Out of buffers, add an empty one. */
      if( iBuffer==nBuffers ){
        if( nBuffers==nMaxBuffers ){
          DataBuffer *p;
          nMaxBuffers += 20;

          /* Manual realloc so we can handle NULL appropriately. */
          p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
          if( p==NULL ){
            rc = SQLITE_NOMEM;
            break;
          }

          if( nBuffers>0 ){
            assert(pBuffers!=NULL);
            memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
            sqlite3_free(pBuffers);
          }
          pBuffers = p;
        }
        dataBufferInit(&(pBuffers[nBuffers]), 0);
        nBuffers++;
      }

      /* At this point, must have an empty at iBuffer. */
      assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);

      /* If empty was first buffer, no need for merge logic. */
      if( iBuffer==0 ){
        dataBufferReplace(&(pBuffers[0]), pData, nData);
      }else{
        /* pAcc is the empty buffer the merged data will end up in. */
        DataBuffer *pAcc = &(pBuffers[iBuffer]);
        DataBuffer *p = &(pBuffers[0]);

        /* Handle position 0 specially to avoid need to prime pAcc
        ** with pData/nData.
        */
        dataBufferSwap(p, pAcc);
        docListAccumulateUnion(pAcc, pData, nData);

        /* Accumulate remaining doclists into pAcc. */
        for(++p; p<pAcc; ++p){
          docListAccumulateUnion(pAcc, p->pData, p->nData);

          /* dataBufferReset() could allow a large doclist to blow up
          ** our memory requirements.
          */
          if( p->nCapacity<1024 ){
            dataBufferReset(p);
          }else{
            dataBufferDestroy(p);
            dataBufferInit(p, 0);
          }
        }
      }
    }
  }

  /* Union all the doclists together into *out. */
  /* TODO(shess) What if *out is big?  Sigh. */
  if( rc==SQLITE_OK && nBuffers>0 ){
    int iBuffer;
    for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
      if( pBuffers[iBuffer].nData>0 ){
        if( out->nData==0 ){
          dataBufferSwap(out, &(pBuffers[iBuffer]));
        }else{
          docListAccumulateUnion(out, pBuffers[iBuffer].pData,
                                 pBuffers[iBuffer].nData);
        }
      }
    }
  }

  while( nBuffers-- ){
    dataBufferDestroy(&(pBuffers[nBuffers]));
  }
  if( pBuffers!=NULL ) sqlite3_free(pBuffers);

  return rc;
}

/* Call loadSegmentLeavesInt() with pData/nData as input. */
static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
                           const char *pTerm, int nTerm, int isPrefix,
                           DataBuffer *out){
  LeavesReader reader;
  int rc;

  assert( nData>1 );
  assert( *pData=='\0' );
  rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
  if( rc!=SQLITE_OK ) return rc;

  rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  leavesReaderReset(&reader);
  leavesReaderDestroy(&reader);
  return rc;
}

/* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
** iEndLeaf (inclusive) as input, and merge the resulting doclist into
** out.
*/
static int loadSegmentLeaves(fulltext_vtab *v,
                             sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
                             const char *pTerm, int nTerm, int isPrefix,
                             DataBuffer *out){
  int rc;
  LeavesReader reader;

  assert( iStartLeaf<=iEndLeaf );
  rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
  if( rc!=SQLITE_OK ) return rc;

  rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  leavesReaderReset(&reader);
  leavesReaderDestroy(&reader);
  return rc;
}

/* Taking pData/nData as an interior node, find the sequence of child
** nodes which could include pTerm/nTerm/isPrefix.  Note that the
** interior node terms logically come between the blocks, so there is
** one more blockid than there are terms (that block contains terms >=
** the last interior-node term).
*/
/* TODO(shess) The calling code may already know that the end child is
** not worth calculating, because the end may be in a later sibling
** node.  Consider whether breaking symmetry is worthwhile.  I suspect
** it is not worthwhile.
*/
static void getChildrenContaining(const char *pData, int nData,
                                  const char *pTerm, int nTerm, int isPrefix,
                                  sqlite_int64 *piStartChild,
                                  sqlite_int64 *piEndChild){
  InteriorReader reader;

  assert( nData>1 );
  assert( *pData!='\0' );
  interiorReaderInit(pData, nData, &reader);

  /* Scan for the first child which could contain pTerm/nTerm. */
  while( !interiorReaderAtEnd(&reader) ){
    if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
    interiorReaderStep(&reader);
  }
  *piStartChild = interiorReaderCurrentBlockid(&reader);

  /* Keep scanning to find a term greater than our term, using prefix
  ** comparison if indicated.  If isPrefix is false, this will be the
  ** same blockid as the starting block.
  */
  while( !interiorReaderAtEnd(&reader) ){
    if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
    interiorReaderStep(&reader);
  }
  *piEndChild = interiorReaderCurrentBlockid(&reader);

  interiorReaderDestroy(&reader);

  /* Children must ascend, and if !prefix, both must be the same. */
  assert( *piEndChild>=*piStartChild );
  assert( isPrefix || *piStartChild==*piEndChild );
}

/* Read block at iBlockid and pass it with other params to
** getChildrenContaining().
*/
static int loadAndGetChildrenContaining(
  fulltext_vtab *v,
  sqlite_int64 iBlockid,
  const char *pTerm, int nTerm, int isPrefix,
  sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
){
  sqlite3_stmt *s = NULL;
  int rc;

  assert( iBlockid!=0 );
  assert( pTerm!=NULL );
  assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
  assert( piStartChild!=NULL );
  assert( piEndChild!=NULL );

  rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_bind_int64(s, 1, iBlockid);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3_step(s);
  if( rc==SQLITE_DONE ) return SQLITE_ERROR;
  if( rc!=SQLITE_ROW ) return rc;

  getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
                        pTerm, nTerm, isPrefix, piStartChild, piEndChild);

  /* We expect only one row.  We must execute another sqlite3_step()
   * to complete the iteration; otherwise the table will remain
   * locked. */
  rc = sqlite3_step(s);
  if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  if( rc!=SQLITE_DONE ) return rc;

  return SQLITE_OK;
}

/* Traverse the tree represented by pData[nData] looking for
** pTerm[nTerm], placing its doclist into *out.  This is internal to
** loadSegment() to make error-handling cleaner.
*/
static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
                          sqlite_int64 iLeavesEnd,
                          const char *pTerm, int nTerm, int isPrefix,
                          DataBuffer *out){
  /* Special case where root is a leaf. */
  if( *pData=='\0' ){
    return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
  }else{
    int rc;
    sqlite_int64 iStartChild, iEndChild;

    /* Process pData as an interior node, then loop down the tree
    ** until we find the set of leaf nodes to scan for the term.
    */
    getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
                          &iStartChild, &iEndChild);
    while( iStartChild>iLeavesEnd ){
      sqlite_int64 iNextStart, iNextEnd;
      rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
                                        &iNextStart, &iNextEnd);
      if( rc!=SQLITE_OK ) return rc;

      /* If we've branched, follow the end branch, too. */
      if( iStartChild!=iEndChild ){
        sqlite_int64 iDummy;
        rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
                                          &iDummy, &iNextEnd);
        if( rc!=SQLITE_OK ) return rc;
      }

      assert( iNextStart<=iNextEnd );
      iStartChild = iNextStart;
      iEndChild = iNextEnd;
    }
    assert( iStartChild<=iLeavesEnd );
    assert( iEndChild<=iLeavesEnd );

    /* Scan through the leaf segments for doclists. */
    return loadSegmentLeaves(v, iStartChild, iEndChild,
                             pTerm, nTerm, isPrefix, out);
  }
}

/* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
** merge its doclist over *out (any duplicate doclists read from the
** segment rooted at pData will overwrite those in *out).
*/
/* TODO(shess) Consider changing this to determine the depth of the
** leaves using either the first characters of interior nodes (when
** ==1, we're one level above the leaves), or the first character of
** the root (which will describe the height of the tree directly).
** Either feels somewhat tricky to me.
*/
/* TODO(shess) The current merge is likely to be slow for large
** doclists (though it should process from newest/smallest to
** oldest/largest, so it may not be that bad).  It might be useful to
** modify things to allow for N-way merging.  This could either be
** within a segment, with pairwise merges across segments, or across
** all segments at once.
*/
static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
                       sqlite_int64 iLeavesEnd,
                       const char *pTerm, int nTerm, int isPrefix,
                       DataBuffer *out){
  DataBuffer result;
  int rc;

  assert( nData>1 );

  /* This code should never be called with buffered updates. */
  assert( v->nPendingData<0 );

  dataBufferInit(&result, 0);
  rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
                      pTerm, nTerm, isPrefix, &result);
  if( rc==SQLITE_OK && result.nData>0 ){
    if( out->nData==0 ){
      DataBuffer tmp = *out;
      *out = result;
      result = tmp;
    }else{
      DataBuffer merged;
      DLReader readers[2];

      dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
      dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
      dataBufferInit(&merged, out->nData+result.nData);
      docListMerge(&merged, readers, 2);
      dataBufferDestroy(out);
      *out = merged;
      dlrDestroy(&readers[0]);
      dlrDestroy(&readers[1]);
    }
  }
  dataBufferDestroy(&result);
  return rc;
}

/* Scan the database and merge together the posting lists for the term
** into *out.
*/
static int termSelect(
  fulltext_vtab *v, 
  int iColumn,
  const char *pTerm, int nTerm,             /* Term to query for */
  int isPrefix,                             /* True for a prefix search */
  DocListType iType, 
  DataBuffer *out                           /* Write results here */
){
  DataBuffer doclist;
  sqlite3_stmt *s;
  int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  if( rc!=SQLITE_OK ) return rc;

  /* This code should never be called with buffered updates. */
  assert( v->nPendingData<0 );

  dataBufferInit(&doclist, 0);
  dataBufferInit(out, 0);

  /* Traverse the segments from oldest to newest so that newer doclist
  ** elements for given docids overwrite older elements.
  */
  while( (rc = sqlite3_step(s))==SQLITE_ROW ){
    const char *pData = sqlite3_column_blob(s, 2);
    const int nData = sqlite3_column_bytes(s, 2);
    const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
    rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
                     &doclist);
    if( rc!=SQLITE_OK ) goto err;
  }
  if( rc==SQLITE_DONE ){
    if( doclist.nData!=0 ){
      /* TODO(shess) The old term_select_all() code applied the column
      ** restrict as we merged segments, leading to smaller buffers.
      ** This is probably worthwhile to bring back, once the new storage
      ** system is checked in.
      */
      if( iColumn==v->nColumn) iColumn = -1;
      docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
                  iColumn, iType, out);
    }
    rc = SQLITE_OK;
  }

 err:
  dataBufferDestroy(&doclist);
  return rc;
}

/****************************************************************/
/* Used to hold hashtable data for sorting. */
typedef struct TermData {
  const char *pTerm;
  int nTerm;
  DLCollector *pCollector;
} TermData;

/* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
** for equal, >0 for greater-than).
*/
static int termDataCmp(const void *av, const void *bv){
  const TermData *a = (const TermData *)av;
  const TermData *b = (const TermData *)bv;
  int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
  int c = memcmp(a->pTerm, b->pTerm, n);
  if( c!=0 ) return c;
  return a->nTerm-b->nTerm;
}

/* Order pTerms data by term, then write a new level 0 segment using
** LeafWriter.
*/
static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
  fts3HashElem *e;
  int idx, rc, i, n;
  TermData *pData;
  LeafWriter writer;
  DataBuffer dl;

  /* Determine the next index at level 0, merging as necessary. */
  rc = segdirNextIndex(v, 0, &idx);
  if( rc!=SQLITE_OK ) return rc;

  n = fts3HashCount(pTerms);
  pData = sqlite3_malloc(n*sizeof(TermData));

  for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
    assert( i<n );
    pData[i].pTerm = fts3HashKey(e);
    pData[i].nTerm = fts3HashKeysize(e);
    pData[i].pCollector = fts3HashData(e);
  }
  assert( i==n );

  /* TODO(shess) Should we allow user-defined collation sequences,
  ** here?  I think we only need that once we support prefix searches.
  */
  if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);

  /* TODO(shess) Refactor so that we can write directly to the segment
  ** DataBuffer, as happens for segment merges.
  */
  leafWriterInit(0, idx, &writer);
  dataBufferInit(&dl, 0);
  for(i=0; i<n; i++){
    dataBufferReset(&dl);
    dlcAddDoclist(pData[i].pCollector, &dl);
    rc = leafWriterStep(v, &writer,
                        pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
    if( rc!=SQLITE_OK ) goto err;
  }
  rc = leafWriterFinalize(v, &writer);

 err:
  dataBufferDestroy(&dl);
  sqlite3_free(pData);
  leafWriterDestroy(&writer);
  return rc;
}

/* If pendingTerms has data, free it. */
static int clearPendingTerms(fulltext_vtab *v){
  if( v->nPendingData>=0 ){
    fts3HashElem *e;
    for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
      dlcDelete(fts3HashData(e));
    }
    fts3HashClear(&v->pendingTerms);
    v->nPendingData = -1;
  }
  return SQLITE_OK;
}

/* If pendingTerms has data, flush it to a level-zero segment, and
** free it.
*/
static int flushPendingTerms(fulltext_vtab *v){
  if( v->nPendingData>=0 ){
    int rc = writeZeroSegment(v, &v->pendingTerms);
    if( rc==SQLITE_OK ) clearPendingTerms(v);
    return rc;
  }
  return SQLITE_OK;
}

/* If pendingTerms is "too big", or docid is out of order, flush it.
** Regardless, be certain that pendingTerms is initialized for use.
*/
static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  /* TODO(shess) Explore whether partially flushing the buffer on
  ** forced-flush would provide better performance.  I suspect that if
  ** we ordered the doclists by size and flushed the largest until the
  ** buffer was half empty, that would let the less frequent terms
  ** generate longer doclists.
  */
  if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
    int rc = flushPendingTerms(v);
    if( rc!=SQLITE_OK ) return rc;
  }
  if( v->nPendingData<0 ){
    fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
    v->nPendingData = 0;
  }
  v->iPrevDocid = iDocid;
  return SQLITE_OK;
}

/* This function implements the xUpdate callback; it is the top-level entry
 * point for inserting, deleting or updating a row in a full-text table. */
static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
                          sqlite_int64 *pRowid){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  int rc;

  FTSTRACE(("FTS3 Update %p\n", pVtab));

  if( nArg<2 ){
    rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
    if( rc==SQLITE_OK ){
      /* If we just deleted the last row in the table, clear out the
      ** index data.
      */
      rc = content_exists(v);
      if( rc==SQLITE_ROW ){
        rc = SQLITE_OK;
      }else if( rc==SQLITE_DONE ){
        /* Clear the pending terms so we don't flush a useless level-0
        ** segment when the transaction closes.
        */
        rc = clearPendingTerms(v);
        if( rc==SQLITE_OK ){
          rc = segdir_delete_all(v);
        }
      }
    }
  } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
    /* An update:
     * ppArg[0] = old rowid
     * ppArg[1] = new rowid
     * ppArg[2..2+v->nColumn-1] = values
     * ppArg[2+v->nColumn] = value for magic column (we ignore this)
     * ppArg[2+v->nColumn+1] = value for docid
     */
    sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
    if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
        sqlite3_value_int64(ppArg[1]) != rowid ){
      rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
    }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
              sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
      rc = SQLITE_ERROR;  /* we don't allow changing the docid */
    }else{
      assert( nArg==2+v->nColumn+2);
      rc = index_update(v, rowid, &ppArg[2]);
    }
  } else {
    /* An insert:
     * ppArg[1] = requested rowid
     * ppArg[2..2+v->nColumn-1] = values
     * ppArg[2+v->nColumn] = value for magic column (we ignore this)
     * ppArg[2+v->nColumn+1] = value for docid
     */
    sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
    assert( nArg==2+v->nColumn+2);
    if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
        SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
      /* TODO(shess) Consider allowing this to work if the values are
      ** identical.  I'm inclined to discourage that usage, though,
      ** given that both rowid and docid are special columns.  Better
      ** would be to define one or the other as the default winner,
      ** but should it be fts3-centric (docid) or SQLite-centric
      ** (rowid)?
      */
      rc = SQLITE_ERROR;
    }else{
      if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
        pRequestDocid = ppArg[1];
      }
      rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
    }
  }

  return rc;
}

static int fulltextSync(sqlite3_vtab *pVtab){
  FTSTRACE(("FTS3 xSync()\n"));
  return flushPendingTerms((fulltext_vtab *)pVtab);
}

static int fulltextBegin(sqlite3_vtab *pVtab){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  FTSTRACE(("FTS3 xBegin()\n"));

  /* Any buffered updates should have been cleared by the previous
  ** transaction.
  */
  assert( v->nPendingData<0 );
  return clearPendingTerms(v);
}

static int fulltextCommit(sqlite3_vtab *pVtab){
  fulltext_vtab *v = (fulltext_vtab *) pVtab;
  FTSTRACE(("FTS3 xCommit()\n"));

  /* Buffered updates should have been cleared by fulltextSync(). */
  assert( v->nPendingData<0 );
  return clearPendingTerms(v);
}

static int fulltextRollback(sqlite3_vtab *pVtab){
  FTSTRACE(("FTS3 xRollback()\n"));
  return clearPendingTerms((fulltext_vtab *)pVtab);
}

/*
** Implementation of the snippet() function for FTS3
*/
static void snippetFunc(
  sqlite3_context *pContext,
  int argc,
  sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc<1 ) return;
  if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
      sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
  }else{
    const char *zStart = "<b>";
    const char *zEnd = "</b>";
    const char *zEllipsis = "<b>...</b>";
    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    if( argc>=2 ){
      zStart = (const char*)sqlite3_value_text(argv[1]);
      if( argc>=3 ){
        zEnd = (const char*)sqlite3_value_text(argv[2]);
        if( argc>=4 ){
          zEllipsis = (const char*)sqlite3_value_text(argv[3]);
        }
      }
    }
    snippetAllOffsets(pCursor);
    snippetText(pCursor, zStart, zEnd, zEllipsis);
    sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
                        pCursor->snippet.nSnippet, SQLITE_STATIC);
  }
}

/*
** Implementation of the offsets() function for FTS3
*/
static void snippetOffsetsFunc(
  sqlite3_context *pContext,
  int argc,
  sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc<1 ) return;
  if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
      sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
  }else{
    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    snippetAllOffsets(pCursor);
    snippetOffsetText(&pCursor->snippet);
    sqlite3_result_text(pContext,
                        pCursor->snippet.zOffset, pCursor->snippet.nOffset,
                        SQLITE_STATIC);
  }
}

/* OptLeavesReader is nearly identical to LeavesReader, except that
** where LeavesReader is geared towards the merging of complete
** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
** is geared towards implementation of the optimize() function, and
** can merge all segments simultaneously.  This version may be
** somewhat less efficient than LeavesReader because it merges into an
** accumulator rather than doing an N-way merge, but since segment
** size grows exponentially (so segment count logrithmically) this is
** probably not an immediate problem.
*/
/* TODO(shess): Prove that assertion, or extend the merge code to
** merge tree fashion (like the prefix-searching code does).
*/
/* TODO(shess): OptLeavesReader and LeavesReader could probably be
** merged with little or no loss of performance for LeavesReader.  The
** merged code would need to handle >MERGE_COUNT segments, and would
** also need to be able to optionally optimize away deletes.
*/
typedef struct OptLeavesReader {
  /* Segment number, to order readers by age. */
  int segment;
  LeavesReader reader;
} OptLeavesReader;

static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
  return leavesReaderAtEnd(&pReader->reader);
}
static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
  return leavesReaderTermBytes(&pReader->reader);
}
static const char *optLeavesReaderData(OptLeavesReader *pReader){
  return leavesReaderData(&pReader->reader);
}
static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
  return leavesReaderDataBytes(&pReader->reader);
}
static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
  return leavesReaderTerm(&pReader->reader);
}
static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
  return leavesReaderStep(v, &pReader->reader);
}
static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
}
/* Order by term ascending, segment ascending (oldest to newest), with
** exhausted readers to the end.
*/
static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  int c = optLeavesReaderTermCmp(lr1, lr2);
  if( c!=0 ) return c;
  return lr1->segment-lr2->segment;
}
/* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
** pLr[1..nLr-1] is already sorted.
*/
static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
  while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
    OptLeavesReader tmp = pLr[0];
    pLr[0] = pLr[1];
    pLr[1] = tmp;
    nLr--;
    pLr++;
  }
}

/* optimize() helper function.  Put the readers in order and iterate
** through them, merging doclists for matching terms into pWriter.
** Returns SQLITE_OK on success, or the SQLite error code which
** prevented success.
*/
static int optimizeInternal(fulltext_vtab *v,
                            OptLeavesReader *readers, int nReaders,
                            LeafWriter *pWriter){
  int i, rc = SQLITE_OK;
  DataBuffer doclist, merged, tmp;

  /* Order the readers. */
  i = nReaders;
  while( i-- > 0 ){
    optLeavesReaderReorder(&readers[i], nReaders-i);
  }

  dataBufferInit(&doclist, LEAF_MAX);
  dataBufferInit(&merged, LEAF_MAX);

  /* Exhausted readers bubble to the end, so when the first reader is
  ** at eof, all are at eof.
  */
  while( !optLeavesReaderAtEnd(&readers[0]) ){

    /* Figure out how many readers share the next term. */
    for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
      if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
    }

    /* Special-case for no merge. */
    if( i==1 ){
      /* Trim deletions from the doclist. */
      dataBufferReset(&merged);
      docListTrim(DL_DEFAULT,
                  optLeavesReaderData(&readers[0]),
                  optLeavesReaderDataBytes(&readers[0]),
                  -1, DL_DEFAULT, &merged);
    }else{
      DLReader dlReaders[MERGE_COUNT];
      int iReader, nReaders;

      /* Prime the pipeline with the first reader's doclist.  After
      ** one pass index 0 will reference the accumulated doclist.
      */
      dlrInit(&dlReaders[0], DL_DEFAULT,
              optLeavesReaderData(&readers[0]),
              optLeavesReaderDataBytes(&readers[0]));
      iReader = 1;

      assert( iReader<i );  /* Must execute the loop at least once. */
      while( iReader<i ){
        /* Merge 16 inputs per pass. */
        for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
             iReader++, nReaders++ ){
          dlrInit(&dlReaders[nReaders], DL_DEFAULT,
                  optLeavesReaderData(&readers[iReader]),
                  optLeavesReaderDataBytes(&readers[iReader]));
        }

        /* Merge doclists and swap result into accumulator. */
        dataBufferReset(&merged);
        docListMerge(&merged, dlReaders, nReaders);
        tmp = merged;
        merged = doclist;
        doclist = tmp;

        while( nReaders-- > 0 ){
          dlrDestroy(&dlReaders[nReaders]);
        }

        /* Accumulated doclist to reader 0 for next pass. */
        dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
      }

      /* Destroy reader that was left in the pipeline. */
      dlrDestroy(&dlReaders[0]);

      /* Trim deletions from the doclist. */
      dataBufferReset(&merged);
      docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
                  -1, DL_DEFAULT, &merged);
    }

    /* Only pass doclists with hits (skip if all hits deleted). */
    if( merged.nData>0 ){
      rc = leafWriterStep(v, pWriter,
                          optLeavesReaderTerm(&readers[0]),
                          optLeavesReaderTermBytes(&readers[0]),
                          merged.pData, merged.nData);
      if( rc!=SQLITE_OK ) goto err;
    }

    /* Step merged readers to next term and reorder. */
    while( i-- > 0 ){
      rc = optLeavesReaderStep(v, &readers[i]);
      if( rc!=SQLITE_OK ) goto err;

      optLeavesReaderReorder(&readers[i], nReaders-i);
    }
  }

 err:
  dataBufferDestroy(&doclist);
  dataBufferDestroy(&merged);
  return rc;
}

/* Implement optimize() function for FTS3.  optimize(t) merges all
** segments in the fts index into a single segment.  't' is the magic
** table-named column.
*/
static void optimizeFunc(sqlite3_context *pContext,
                         int argc, sqlite3_value **argv){
  fulltext_cursor *pCursor;
  if( argc>1 ){
    sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
  }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
            sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
  }else{
    fulltext_vtab *v;
    int i, rc, iMaxLevel;
    OptLeavesReader *readers;
    int nReaders;
    LeafWriter writer;
    sqlite3_stmt *s;

    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    v = cursor_vtab(pCursor);

    /* Flush any buffered updates before optimizing. */
    rc = flushPendingTerms(v);
    if( rc!=SQLITE_OK ) goto err;

    rc = segdir_count(v, &nReaders, &iMaxLevel);
    if( rc!=SQLITE_OK ) goto err;
    if( nReaders==0 || nReaders==1 ){
      sqlite3_result_text(pContext, "Index already optimal", -1,
                          SQLITE_STATIC);
      return;
    }

    rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
    if( rc!=SQLITE_OK ) goto err;

    readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
    if( readers==NULL ) goto err;

    /* Note that there will already be a segment at this position
    ** until we call segdir_delete() on iMaxLevel.
    */
    leafWriterInit(iMaxLevel, 0, &writer);

    i = 0;
    while( (rc = sqlite3_step(s))==SQLITE_ROW ){
      sqlite_int64 iStart = sqlite3_column_int64(s, 0);
      sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
      const char *pRootData = sqlite3_column_blob(s, 2);
      int nRootData = sqlite3_column_bytes(s, 2);

      assert( i<nReaders );
      rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
                            &readers[i].reader);
      if( rc!=SQLITE_OK ) break;

      readers[i].segment = i;
      i++;
    }

    /* If we managed to successfully read them all, optimize them. */
    if( rc==SQLITE_DONE ){
      assert( i==nReaders );
      rc = optimizeInternal(v, readers, nReaders, &writer);
    }

    while( i-- > 0 ){
      leavesReaderDestroy(&readers[i].reader);
    }
    sqlite3_free(readers);

    /* If we've successfully gotten to here, delete the old segments
    ** and flush the interior structure of the new segment.
    */
    if( rc==SQLITE_OK ){
      for( i=0; i<=iMaxLevel; i++ ){
        rc = segdir_delete(v, i);
        if( rc!=SQLITE_OK ) break;
      }

      if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
    }

    leafWriterDestroy(&writer);

    if( rc!=SQLITE_OK ) goto err;

    sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
    return;

    /* TODO(shess): Error-handling needs to be improved along the
    ** lines of the dump_ functions.
    */
 err:
    {
      char buf[512];
      sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
                       sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
      sqlite3_result_error(pContext, buf, -1);
    }
  }
}

#ifdef SQLITE_TEST
/* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
** pull the error from the context's db handle.
*/
static void generateError(sqlite3_context *pContext,
                          const char *prefix, const char *msg){
  char buf[512];
  if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
  sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
  sqlite3_result_error(pContext, buf, -1);
}

/* Helper function to collect the set of terms in the segment into
** pTerms.  The segment is defined by the leaf nodes between
** iStartBlockid and iEndBlockid, inclusive, or by the contents of
** pRootData if iStartBlockid is 0 (in which case the entire segment
** fit in a leaf).
*/
static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
                               fts3Hash *pTerms){
  const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
  const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
  const char *pRootData = sqlite3_column_blob(s, 2);
  const int nRootData = sqlite3_column_bytes(s, 2);
  LeavesReader reader;
  int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
                            pRootData, nRootData, &reader);
  if( rc!=SQLITE_OK ) return rc;

  while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
    const char *pTerm = leavesReaderTerm(&reader);
    const int nTerm = leavesReaderTermBytes(&reader);
    void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
    void *newValue = (void *)((char *)oldValue+1);

    /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
    ** the data value passed is returned in case of malloc failure.
    */
    if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
      rc = SQLITE_NOMEM;
    }else{
      rc = leavesReaderStep(v, &reader);
    }
  }

  leavesReaderDestroy(&reader);
  return rc;
}

/* Helper function to build the result string for dump_terms(). */
static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
  int iTerm, nTerms, nResultBytes, iByte;
  char *result;
  TermData *pData;
  fts3HashElem *e;

  /* Iterate pTerms to generate an array of terms in pData for
  ** sorting.
  */
  nTerms = fts3HashCount(pTerms);
  assert( nTerms>0 );
  pData = sqlite3_malloc(nTerms*sizeof(TermData));
  if( pData==NULL ) return SQLITE_NOMEM;

  nResultBytes = 0;
  for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
    nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
    assert( iTerm<nTerms );
    pData[iTerm].pTerm = fts3HashKey(e);
    pData[iTerm].nTerm = fts3HashKeysize(e);
    pData[iTerm].pCollector = fts3HashData(e);  /* unused */
  }
  assert( iTerm==nTerms );

  assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
  result = sqlite3_malloc(nResultBytes);
  if( result==NULL ){
    sqlite3_free(pData);
    return SQLITE_NOMEM;
  }

  if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);

  /* Read the terms in order to build the result. */
  iByte = 0;
  for(iTerm=0; iTerm<nTerms; ++iTerm){
    memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
    iByte += pData[iTerm].nTerm;
    result[iByte++] = ' ';
  }
  assert( iByte==nResultBytes );
  assert( result[nResultBytes-1]==' ' );
  result[nResultBytes-1] = '\0';

  /* Passes away ownership of result. */
  sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
  sqlite3_free(pData);
  return SQLITE_OK;
}

/* Implements dump_terms() for use in inspecting the fts3 index from
** tests.  TEXT result containing the ordered list of terms joined by
** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
** specified by level, idx (in %_segdir), while dump_terms(t) dumps
** all terms in the index.  In both cases t is the fts table's magic
** table-named column.
*/
static void dumpTermsFunc(
  sqlite3_context *pContext,
  int argc, sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc!=3 && argc!=1 ){
    generateError(pContext, "dump_terms", "incorrect arguments");
  }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
            sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    generateError(pContext, "dump_terms", "illegal first argument");
  }else{
    fulltext_vtab *v;
    fts3Hash terms;
    sqlite3_stmt *s = NULL;
    int rc;

    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    v = cursor_vtab(pCursor);

    /* If passed only the cursor column, get all segments.  Otherwise
    ** get the segment described by the following two arguments.
    */
    if( argc==1 ){
      rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
    }else{
      rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
      if( rc==SQLITE_OK ){
        rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
        if( rc==SQLITE_OK ){
          rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
        }
      }
    }

    if( rc!=SQLITE_OK ){
      generateError(pContext, "dump_terms", NULL);
      return;
    }

    /* Collect the terms for each segment. */
    sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
    while( (rc = sqlite3_step(s))==SQLITE_ROW ){
      rc = collectSegmentTerms(v, s, &terms);
      if( rc!=SQLITE_OK ) break;
    }

    if( rc!=SQLITE_DONE ){
      sqlite3_reset(s);
      generateError(pContext, "dump_terms", NULL);
    }else{
      const int nTerms = fts3HashCount(&terms);
      if( nTerms>0 ){
        rc = generateTermsResult(pContext, &terms);
        if( rc==SQLITE_NOMEM ){
          generateError(pContext, "dump_terms", "out of memory");
        }else{
          assert( rc==SQLITE_OK );
        }
      }else if( argc==3 ){
        /* The specific segment asked for could not be found. */
        generateError(pContext, "dump_terms", "segment not found");
      }else{
        /* No segments found. */
        /* TODO(shess): It should be impossible to reach this.  This
        ** case can only happen for an empty table, in which case
        ** SQLite has no rows to call this function on.
        */
        sqlite3_result_null(pContext);
      }
    }
    sqlite3Fts3HashClear(&terms);
  }
}

/* Expand the DL_DEFAULT doclist in pData into a text result in
** pContext.
*/
static void createDoclistResult(sqlite3_context *pContext,
                                const char *pData, int nData){
  DataBuffer dump;
  DLReader dlReader;

  assert( pData!=NULL && nData>0 );

  dataBufferInit(&dump, 0);
  dlrInit(&dlReader, DL_DEFAULT, pData, nData);
  for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
    char buf[256];
    PLReader plReader;

    plrInit(&plReader, &dlReader);
    if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
      sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
      dataBufferAppend(&dump, buf, strlen(buf));
    }else{
      int iColumn = plrColumn(&plReader);

      sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
                       dlrDocid(&dlReader), iColumn);
      dataBufferAppend(&dump, buf, strlen(buf));

      for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
        if( plrColumn(&plReader)!=iColumn ){
          iColumn = plrColumn(&plReader);
          sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
          assert( dump.nData>0 );
          dump.nData--;                     /* Overwrite trailing space. */
          assert( dump.pData[dump.nData]==' ');
          dataBufferAppend(&dump, buf, strlen(buf));
        }
        if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
          sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
                           plrPosition(&plReader),
                           plrStartOffset(&plReader), plrEndOffset(&plReader));
        }else if( DL_DEFAULT==DL_POSITIONS ){
          sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
        }else{
          assert( NULL=="Unhandled DL_DEFAULT value");
        }
        dataBufferAppend(&dump, buf, strlen(buf));
      }
      plrDestroy(&plReader);

      assert( dump.nData>0 );
      dump.nData--;                     /* Overwrite trailing space. */
      assert( dump.pData[dump.nData]==' ');
      dataBufferAppend(&dump, "]] ", 3);
    }
  }
  dlrDestroy(&dlReader);

  assert( dump.nData>0 );
  dump.nData--;                     /* Overwrite trailing space. */
  assert( dump.pData[dump.nData]==' ');
  dump.pData[dump.nData] = '\0';
  assert( dump.nData>0 );

  /* Passes ownership of dump's buffer to pContext. */
  sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
  dump.pData = NULL;
  dump.nData = dump.nCapacity = 0;
}

/* Implements dump_doclist() for use in inspecting the fts3 index from
** tests.  TEXT result containing a string representation of the
** doclist for the indicated term.  dump_doclist(t, term, level, idx)
** dumps the doclist for term from the segment specified by level, idx
** (in %_segdir), while dump_doclist(t, term) dumps the logical
** doclist for the term across all segments.  The per-segment doclist
** can contain deletions, while the full-index doclist will not
** (deletions are omitted).
**
** Result formats differ with the setting of DL_DEFAULTS.  Examples:
**
** DL_DOCIDS: [1] [3] [7]
** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
**
** In each case the number after the outer '[' is the docid.  In the
** latter two cases, the number before the inner '[' is the column
** associated with the values within.  For DL_POSITIONS the numbers
** within are the positions, for DL_POSITIONS_OFFSETS they are the
** position, the start offset, and the end offset.
*/
static void dumpDoclistFunc(
  sqlite3_context *pContext,
  int argc, sqlite3_value **argv
){
  fulltext_cursor *pCursor;
  if( argc!=2 && argc!=4 ){
    generateError(pContext, "dump_doclist", "incorrect arguments");
  }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
            sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
    generateError(pContext, "dump_doclist", "illegal first argument");
  }else if( sqlite3_value_text(argv[1])==NULL ||
            sqlite3_value_text(argv[1])[0]=='\0' ){
    generateError(pContext, "dump_doclist", "empty second argument");
  }else{
    const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
    const int nTerm = strlen(pTerm);
    fulltext_vtab *v;
    int rc;
    DataBuffer doclist;

    memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
    v = cursor_vtab(pCursor);

    dataBufferInit(&doclist, 0);

    /* termSelect() yields the same logical doclist that queries are
    ** run against.
    */
    if( argc==2 ){
      rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
    }else{
      sqlite3_stmt *s = NULL;

      /* Get our specific segment's information. */
      rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
      if( rc==SQLITE_OK ){
        rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
        if( rc==SQLITE_OK ){
          rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
        }
      }

      if( rc==SQLITE_OK ){
        rc = sqlite3_step(s);

        if( rc==SQLITE_DONE ){
          dataBufferDestroy(&doclist);
          generateError(pContext, "dump_doclist", "segment not found");
          return;
        }

        /* Found a segment, load it into doclist. */
        if( rc==SQLITE_ROW ){
          const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
          const char *pData = sqlite3_column_blob(s, 2);
          const int nData = sqlite3_column_bytes(s, 2);

          /* loadSegment() is used by termSelect() to load each
          ** segment's data.
          */
          rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
                           &doclist);
          if( rc==SQLITE_OK ){
            rc = sqlite3_step(s);

            /* Should not have more than one matching segment. */
            if( rc!=SQLITE_DONE ){
              sqlite3_reset(s);
              dataBufferDestroy(&doclist);
              generateError(pContext, "dump_doclist", "invalid segdir");
              return;
            }
            rc = SQLITE_OK;
          }
        }
      }

      sqlite3_reset(s);
    }

    if( rc==SQLITE_OK ){
      if( doclist.nData>0 ){
        createDoclistResult(pContext, doclist.pData, doclist.nData);
      }else{
        /* TODO(shess): This can happen if the term is not present, or
        ** if all instances of the term have been deleted and this is
        ** an all-index dump.  It may be interesting to distinguish
        ** these cases.
        */
        sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
      }
    }else if( rc==SQLITE_NOMEM ){
      /* Handle out-of-memory cases specially because if they are
      ** generated in fts3 code they may not be reflected in the db
      ** handle.
      */
      /* TODO(shess): Handle this more comprehensively.
      ** sqlite3ErrStr() has what I need, but is internal.
      */
      generateError(pContext, "dump_doclist", "out of memory");
    }else{
      generateError(pContext, "dump_doclist", NULL);
    }

    dataBufferDestroy(&doclist);
  }
}
#endif

/*
** This routine implements the xFindFunction method for the FTS3
** virtual table.
*/
static int fulltextFindFunction(
  sqlite3_vtab *pVtab,
  int nArg,
  const char *zName,
  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  void **ppArg
){
  if( strcmp(zName,"snippet")==0 ){
    *pxFunc = snippetFunc;
    return 1;
  }else if( strcmp(zName,"offsets")==0 ){
    *pxFunc = snippetOffsetsFunc;
    return 1;
  }else if( strcmp(zName,"optimize")==0 ){
    *pxFunc = optimizeFunc;
    return 1;
#ifdef SQLITE_TEST
    /* NOTE(shess): These functions are present only for testing
    ** purposes.  No particular effort is made to optimize their
    ** execution or how they build their results.
    */
  }else if( strcmp(zName,"dump_terms")==0 ){
    /* fprintf(stderr, "Found dump_terms\n"); */
    *pxFunc = dumpTermsFunc;
    return 1;
  }else if( strcmp(zName,"dump_doclist")==0 ){
    /* fprintf(stderr, "Found dump_doclist\n"); */
    *pxFunc = dumpDoclistFunc;
    return 1;
#endif
  }
  return 0;
}

/*
** Rename an fts3 table.
*/
static int fulltextRename(
  sqlite3_vtab *pVtab,
  const char *zName
){
  fulltext_vtab *p = (fulltext_vtab *)pVtab;
  int rc = SQLITE_NOMEM;
  char *zSql = sqlite3_mprintf(
    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
    , p->zDb, p->zName, zName 
    , p->zDb, p->zName, zName 
    , p->zDb, p->zName, zName
  );
  if( zSql ){
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  return rc;
}

static const sqlite3_module fts3Module = {
  /* iVersion      */ 0,
  /* xCreate       */ fulltextCreate,
  /* xConnect      */ fulltextConnect,
  /* xBestIndex    */ fulltextBestIndex,
  /* xDisconnect   */ fulltextDisconnect,
  /* xDestroy      */ fulltextDestroy,
  /* xOpen         */ fulltextOpen,
  /* xClose        */ fulltextClose,
  /* xFilter       */ fulltextFilter,
  /* xNext         */ fulltextNext,
  /* xEof          */ fulltextEof,
  /* xColumn       */ fulltextColumn,
  /* xRowid        */ fulltextRowid,
  /* xUpdate       */ fulltextUpdate,
  /* xBegin        */ fulltextBegin,
  /* xSync         */ fulltextSync,
  /* xCommit       */ fulltextCommit,
  /* xRollback     */ fulltextRollback,
  /* xFindFunction */ fulltextFindFunction,
  /* xRename */       fulltextRename,
};

static void hashDestroy(void *p){
  fts3Hash *pHash = (fts3Hash *)p;
  sqlite3Fts3HashClear(pHash);
  sqlite3_free(pHash);
}

/*
** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
** two forward declarations are for functions declared in these files
** used to retrieve the respective implementations.
**
** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
** to by the argument to point a the "simple" tokenizer implementation.
** Function ...PorterTokenizerModule() sets *pModule to point to the
** porter tokenizer/stemmer implementation.
*/
void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);

int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);

/*
** Initialise the fts3 extension. If this extension is built as part
** of the sqlite library, then this function is called directly by
** SQLite. If fts3 is built as a dynamically loadable extension, this
** function is called by the sqlite3_extension_init() entry point.
*/
int sqlite3Fts3Init(sqlite3 *db){
  int rc = SQLITE_OK;
  fts3Hash *pHash = 0;
  const sqlite3_tokenizer_module *pSimple = 0;
  const sqlite3_tokenizer_module *pPorter = 0;
  const sqlite3_tokenizer_module *pIcu = 0;

  sqlite3Fts3SimpleTokenizerModule(&pSimple);
  sqlite3Fts3PorterTokenizerModule(&pPorter);
#ifdef SQLITE_ENABLE_ICU
  sqlite3Fts3IcuTokenizerModule(&pIcu);
#endif

  /* Allocate and initialise the hash-table used to store tokenizers. */
  pHash = sqlite3_malloc(sizeof(fts3Hash));
  if( !pHash ){
    rc = SQLITE_NOMEM;
  }else{
    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  }

  /* Load the built-in tokenizers into the hash table */
  if( rc==SQLITE_OK ){
    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
    ){
      rc = SQLITE_NOMEM;
    }
  }

#ifdef SQLITE_TEST
  sqlite3Fts3ExprInitTestInterface(db);
#endif

  /* Create the virtual table wrapper around the hash-table and overload 
  ** the two scalar functions. If this is successful, register the
  ** module with sqlite.
  */
  if( SQLITE_OK==rc 
   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
#ifdef SQLITE_TEST
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
#endif
  ){
    return sqlite3_create_module_v2(
        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
    );
  }

  /* An error has occurred. Delete the hash table and return the error code. */
  assert( rc!=SQLITE_OK );
  if( pHash ){
    sqlite3Fts3HashClear(pHash);
    sqlite3_free(pHash);
  }
  return rc;
}

#if !SQLITE_CORE
int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi)
  return sqlite3Fts3Init(db);
}
#endif

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/fts3.h.





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file is used by programs that want to link against the
** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
*/
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

int sqlite3Fts3Init(sqlite3 *db);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */

Added ext/fts3/fts3_expr.c.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
/*
** 2008 Nov 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This module contains code that implements a parser for fts3 query strings
** (the right-hand argument to the MATCH operator). Because the supported 
** syntax is relatively simple, the whole tokenizer/parser system is
** hand-coded. The public interface to this module is declared in source
** code file "fts3_expr.h".
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)

/*
** By default, this module parses the legacy syntax that has been 
** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
** is defined, then it uses the new syntax. The differences between
** the new and the old syntaxes are:
**
**  a) The new syntax supports parenthesis. The old does not.
**
**  b) The new syntax supports the AND and NOT operators. The old does not.
**
**  c) The old syntax supports the "-" token qualifier. This is not 
**     supported by the new syntax (it is replaced by the NOT operator).
**
**  d) When using the old syntax, the OR operator has a greater precedence
**     than an implicit AND. When using the new, both implicity and explicit
**     AND operators have a higher precedence than OR.
**
** If compiled with SQLITE_TEST defined, then this module exports the
** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
** to zero causes the module to use the old syntax. If it is set to 
** non-zero the new syntax is activated. This is so both syntaxes can
** be tested using a single build of testfixture.
*/
#ifdef SQLITE_TEST
int sqlite3_fts3_enable_parentheses = 0;
#else
# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
#  define sqlite3_fts3_enable_parentheses 1
# else
#  define sqlite3_fts3_enable_parentheses 0
# endif
#endif

/*
** Default span for NEAR operators.
*/
#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10

#include "fts3_expr.h"
#include "sqlite3.h"
#include <ctype.h>
#include <string.h>
#include <assert.h>

typedef struct ParseContext ParseContext;
struct ParseContext {
  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
  const char **azCol;                 /* Array of column names for fts3 table */
  int nCol;                           /* Number of entries in azCol[] */
  int iDefaultCol;                    /* Default column to query */
  sqlite3_context *pCtx;              /* Write error message here */
  int nNest;                          /* Number of nested brackets */
};

/*
** This function is equivalent to the standard isspace() function. 
**
** The standard isspace() can be awkward to use safely, because although it
** is defined to accept an argument of type int, its behaviour when passed
** an integer that falls outside of the range of the unsigned char type
** is undefined (and sometimes, "undefined" means segfault). This wrapper
** is defined to accept an argument of type char, and always returns 0 for
** any values that fall outside of the range of the unsigned char type (i.e.
** negative values).
*/
static int fts3isspace(char c){
  return (c&0x80)==0 ? isspace(c) : 0;
}

/*
** Extract the next token from buffer z (length n) using the tokenizer
** and other information (column names etc.) in pParse. Create an Fts3Expr
** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
** single token and set *ppExpr to point to it. If the end of the buffer is
** reached before a token is found, set *ppExpr to zero. It is the
** responsibility of the caller to eventually deallocate the allocated 
** Fts3Expr structure (if any) by passing it to sqlite3_free().
**
** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
** fails.
*/
static int getNextToken(
  ParseContext *pParse,                   /* fts3 query parse context */
  int iCol,                               /* Value for Fts3Phrase.iColumn */
  const char *z, int n,                   /* Input string */
  Fts3Expr **ppExpr,                      /* OUT: expression */
  int *pnConsumed                         /* OUT: Number of bytes consumed */
){
  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  int rc;
  sqlite3_tokenizer_cursor *pCursor;
  Fts3Expr *pRet = 0;
  int nConsumed = 0;

  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
  if( rc==SQLITE_OK ){
    const char *zToken;
    int nToken, iStart, iEnd, iPosition;
    int nByte;                               /* total space to allocate */

    pCursor->pTokenizer = pTokenizer;
    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);

    if( rc==SQLITE_OK ){
      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
      if( !pRet ){
        rc = SQLITE_NOMEM;
      }else{
        memset(pRet, 0, nByte);
        pRet->eType = FTSQUERY_PHRASE;
        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
        pRet->pPhrase->nToken = 1;
        pRet->pPhrase->iColumn = iCol;
        pRet->pPhrase->aToken[0].n = nToken;
        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);

        if( iEnd<n && z[iEnd]=='*' ){
          pRet->pPhrase->aToken[0].isPrefix = 1;
          iEnd++;
        }
        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
          pRet->pPhrase->isNot = 1;
        }
      }
      nConsumed = iEnd;
    }

    pModule->xClose(pCursor);
  }
  
  *pnConsumed = nConsumed;
  *ppExpr = pRet;
  return rc;
}


/*
** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
** then free the old allocation.
*/
void *fts3ReallocOrFree(void *pOrig, int nNew){
  void *pRet = sqlite3_realloc(pOrig, nNew);
  if( !pRet ){
    sqlite3_free(pOrig);
  }
  return pRet;
}

/*
** Buffer zInput, length nInput, contains the contents of a quoted string
** that appeared as part of an fts3 query expression. Neither quote character
** is included in the buffer. This function attempts to tokenize the entire
** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
** containing the results.
**
** If successful, SQLITE_OK is returned and *ppExpr set to point at the
** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
** to 0.
*/
static int getNextString(
  ParseContext *pParse,                   /* fts3 query parse context */
  const char *zInput, int nInput,         /* Input string */
  Fts3Expr **ppExpr                       /* OUT: expression */
){
  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  int rc;
  Fts3Expr *p = 0;
  sqlite3_tokenizer_cursor *pCursor = 0;
  char *zTemp = 0;
  int nTemp = 0;

  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
  if( rc==SQLITE_OK ){
    int ii;
    pCursor->pTokenizer = pTokenizer;
    for(ii=0; rc==SQLITE_OK; ii++){
      const char *zToken;
      int nToken, iBegin, iEnd, iPos;
      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
      if( rc==SQLITE_OK ){
        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
        if( !p || !zTemp ){
          goto no_mem;
        }
        if( ii==0 ){
          memset(p, 0, nByte);
          p->pPhrase = (Fts3Phrase *)&p[1];
        }
        p->pPhrase = (Fts3Phrase *)&p[1];
        p->pPhrase->nToken = ii+1;
        p->pPhrase->aToken[ii].n = nToken;
        memcpy(&zTemp[nTemp], zToken, nToken);
        nTemp += nToken;
        if( iEnd<nInput && zInput[iEnd]=='*' ){
          p->pPhrase->aToken[ii].isPrefix = 1;
        }else{
          p->pPhrase->aToken[ii].isPrefix = 0;
        }
      }
    }

    pModule->xClose(pCursor);
    pCursor = 0;
  }

  if( rc==SQLITE_DONE ){
    int jj;
    char *zNew;
    int nNew = 0;
    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
    p = fts3ReallocOrFree(p, nByte + nTemp);
    if( !p ){
      goto no_mem;
    }
    if( zTemp ){
      zNew = &(((char *)p)[nByte]);
      memcpy(zNew, zTemp, nTemp);
    }else{
      memset(p, 0, nByte+nTemp);
    }
    p->pPhrase = (Fts3Phrase *)&p[1];
    for(jj=0; jj<p->pPhrase->nToken; jj++){
      p->pPhrase->aToken[jj].z = &zNew[nNew];
      nNew += p->pPhrase->aToken[jj].n;
    }
    sqlite3_free(zTemp);
    p->eType = FTSQUERY_PHRASE;
    p->pPhrase->iColumn = pParse->iDefaultCol;
    rc = SQLITE_OK;
  }

  *ppExpr = p;
  return rc;
no_mem:

  if( pCursor ){
    pModule->xClose(pCursor);
  }
  sqlite3_free(zTemp);
  sqlite3_free(p);
  *ppExpr = 0;
  return SQLITE_NOMEM;
}

/*
** Function getNextNode(), which is called by fts3ExprParse(), may itself
** call fts3ExprParse(). So this forward declaration is required.
*/
static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);

/*
** The output variable *ppExpr is populated with an allocated Fts3Expr 
** structure, or set to 0 if the end of the input buffer is reached.
**
** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
** If SQLITE_ERROR is returned, pContext is populated with an error message.
*/
static int getNextNode(
  ParseContext *pParse,                   /* fts3 query parse context */
  const char *z, int n,                   /* Input string */
  Fts3Expr **ppExpr,                      /* OUT: expression */
  int *pnConsumed                         /* OUT: Number of bytes consumed */
){
  static const struct Fts3Keyword {
    char z[4];                            /* Keyword text */
    unsigned char n;                      /* Length of the keyword */
    unsigned char parenOnly;              /* Only valid in paren mode */
    unsigned char eType;                  /* Keyword code */
  } aKeyword[] = {
    { "OR" ,  2, 0, FTSQUERY_OR   },
    { "AND",  3, 1, FTSQUERY_AND  },
    { "NOT",  3, 1, FTSQUERY_NOT  },
    { "NEAR", 4, 0, FTSQUERY_NEAR }
  };
  int ii;
  int iCol;
  int iColLen;
  int rc;
  Fts3Expr *pRet = 0;

  const char *zInput = z;
  int nInput = n;

  /* Skip over any whitespace before checking for a keyword, an open or
  ** close bracket, or a quoted string. 
  */
  while( nInput>0 && fts3isspace(*zInput) ){
    nInput--;
    zInput++;
  }
  if( nInput==0 ){
    return SQLITE_DONE;
  }

  /* See if we are dealing with a keyword. */
  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
    const struct Fts3Keyword *pKey = &aKeyword[ii];

    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
      continue;
    }

    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
      int nKey = pKey->n;
      char cNext;

      /* If this is a "NEAR" keyword, check for an explicit nearness. */
      if( pKey->eType==FTSQUERY_NEAR ){
        assert( nKey==4 );
        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
          nNear = 0;
          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
            nNear = nNear * 10 + (zInput[nKey] - '0');
          }
        }
      }

      /* At this point this is probably a keyword. But for that to be true,
      ** the next byte must contain either whitespace, an open or close
      ** parenthesis, a quote character, or EOF. 
      */
      cNext = zInput[nKey];
      if( fts3isspace(cNext) 
       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
      ){
        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
        memset(pRet, 0, sizeof(Fts3Expr));
        pRet->eType = pKey->eType;
        pRet->nNear = nNear;
        *ppExpr = pRet;
        *pnConsumed = (zInput - z) + nKey;
        return SQLITE_OK;
      }

      /* Turns out that wasn't a keyword after all. This happens if the
      ** user has supplied a token such as "ORacle". Continue.
      */
    }
  }

  /* Check for an open bracket. */
  if( sqlite3_fts3_enable_parentheses ){
    if( *zInput=='(' ){
      int nConsumed;
      int rc;
      pParse->nNest++;
      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
      if( rc==SQLITE_OK && !*ppExpr ){
        rc = SQLITE_DONE;
      }
      *pnConsumed = (zInput - z) + 1 + nConsumed;
      return rc;
    }
  
    /* Check for a close bracket. */
    if( *zInput==')' ){
      pParse->nNest--;
      *pnConsumed = (zInput - z) + 1;
      return SQLITE_DONE;
    }
  }

  /* See if we are dealing with a quoted phrase. If this is the case, then
  ** search for the closing quote and pass the whole string to getNextString()
  ** for processing. This is easy to do, as fts3 has no syntax for escaping
  ** a quote character embedded in a string.
  */
  if( *zInput=='"' ){
    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
    *pnConsumed = (zInput - z) + ii + 1;
    if( ii==nInput ){
      return SQLITE_ERROR;
    }
    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  }


  /* If control flows to this point, this must be a regular token, or 
  ** the end of the input. Read a regular token using the sqlite3_tokenizer
  ** interface. Before doing so, figure out if there is an explicit
  ** column specifier for the token. 
  **
  ** TODO: Strangely, it is not possible to associate a column specifier
  ** with a quoted phrase, only with a single token. Not sure if this was
  ** an implementation artifact or an intentional decision when fts3 was
  ** first implemented. Whichever it was, this module duplicates the 
  ** limitation.
  */
  iCol = pParse->iDefaultCol;
  iColLen = 0;
  for(ii=0; ii<pParse->nCol; ii++){
    const char *zStr = pParse->azCol[ii];
    int nStr = strlen(zStr);
    if( nInput>nStr && zInput[nStr]==':' 
     && sqlite3_strnicmp(zStr, zInput, nStr)==0 
    ){
      iCol = ii;
      iColLen = ((zInput - z) + nStr + 1);
      break;
    }
  }
  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  *pnConsumed += iColLen;
  return rc;
}

/*
** The argument is an Fts3Expr structure for a binary operator (any type
** except an FTSQUERY_PHRASE). Return an integer value representing the
** precedence of the operator. Lower values have a higher precedence (i.e.
** group more tightly). For example, in the C language, the == operator
** groups more tightly than ||, and would therefore have a higher precedence.
**
** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
** is defined), the order of the operators in precedence from highest to
** lowest is:
**
**   NEAR
**   NOT
**   AND (including implicit ANDs)
**   OR
**
** Note that when using the old query syntax, the OR operator has a higher
** precedence than the AND operator.
*/
static int opPrecedence(Fts3Expr *p){
  assert( p->eType!=FTSQUERY_PHRASE );
  if( sqlite3_fts3_enable_parentheses ){
    return p->eType;
  }else if( p->eType==FTSQUERY_NEAR ){
    return 1;
  }else if( p->eType==FTSQUERY_OR ){
    return 2;
  }
  assert( p->eType==FTSQUERY_AND );
  return 3;
}

/*
** Argument ppHead contains a pointer to the current head of a query 
** expression tree being parsed. pPrev is the expression node most recently
** inserted into the tree. This function adds pNew, which is always a binary
** operator node, into the expression tree based on the relative precedence
** of pNew and the existing nodes of the tree. This may result in the head
** of the tree changing, in which case *ppHead is set to the new root node.
*/
static void insertBinaryOperator(
  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
  Fts3Expr *pNew           /* New binary node to insert into expression tree */
){
  Fts3Expr *pSplit = pPrev;
  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
    pSplit = pSplit->pParent;
  }

  if( pSplit->pParent ){
    assert( pSplit->pParent->pRight==pSplit );
    pSplit->pParent->pRight = pNew;
    pNew->pParent = pSplit->pParent;
  }else{
    *ppHead = pNew;
  }
  pNew->pLeft = pSplit;
  pSplit->pParent = pNew;
}

/*
** Parse the fts3 query expression found in buffer z, length n. This function
** returns either when the end of the buffer is reached or an unmatched 
** closing bracket - ')' - is encountered.
**
** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
** parsed form of the expression and *pnConsumed is set to the number of
** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
** (out of memory error) or SQLITE_ERROR (parse error) is returned.
*/
static int fts3ExprParse(
  ParseContext *pParse,                   /* fts3 query parse context */
  const char *z, int n,                   /* Text of MATCH query */
  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
  int *pnConsumed                         /* OUT: Number of bytes consumed */
){
  Fts3Expr *pRet = 0;
  Fts3Expr *pPrev = 0;
  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
  int nIn = n;
  const char *zIn = z;
  int rc = SQLITE_OK;
  int isRequirePhrase = 1;

  while( rc==SQLITE_OK ){
    Fts3Expr *p = 0;
    int nByte = 0;
    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
    if( rc==SQLITE_OK ){
      int isPhrase;

      if( !sqlite3_fts3_enable_parentheses 
       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
      ){
        /* Create an implicit NOT operator. */
        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
        if( !pNot ){
          sqlite3Fts3ExprFree(p);
          rc = SQLITE_NOMEM;
          goto exprparse_out;
        }
        memset(pNot, 0, sizeof(Fts3Expr));
        pNot->eType = FTSQUERY_NOT;
        pNot->pRight = p;
        if( pNotBranch ){
          pNot->pLeft = pNotBranch;
        }
        pNotBranch = pNot;
        p = pPrev;
      }else{
        int eType = p->eType;
        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);

        /* The isRequirePhrase variable is set to true if a phrase or
        ** an expression contained in parenthesis is required. If a
        ** binary operator (AND, OR, NOT or NEAR) is encounted when
        ** isRequirePhrase is set, this is a syntax error.
        */
        if( !isPhrase && isRequirePhrase ){
          sqlite3Fts3ExprFree(p);
          rc = SQLITE_ERROR;
          goto exprparse_out;
        }
  
        if( isPhrase && !isRequirePhrase ){
          /* Insert an implicit AND operator. */
          Fts3Expr *pAnd;
          assert( pRet && pPrev );
          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
          if( !pAnd ){
            sqlite3Fts3ExprFree(p);
            rc = SQLITE_NOMEM;
            goto exprparse_out;
          }
          memset(pAnd, 0, sizeof(Fts3Expr));
          pAnd->eType = FTSQUERY_AND;
          insertBinaryOperator(&pRet, pPrev, pAnd);
          pPrev = pAnd;
        }

        /* This test catches attempts to make either operand of a NEAR
        ** operator something other than a phrase. For example, either of
        ** the following:
        **
        **    (bracketed expression) NEAR phrase
        **    phrase NEAR (bracketed expression)
        **
        ** Return an error in either case.
        */
        if( pPrev && (
            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
        )){
          sqlite3Fts3ExprFree(p);
          rc = SQLITE_ERROR;
          goto exprparse_out;
        }
  
        if( isPhrase ){
          if( pRet ){
            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
            pPrev->pRight = p;
            p->pParent = pPrev;
          }else{
            pRet = p;
          }
        }else{
          insertBinaryOperator(&pRet, pPrev, p);
        }
        isRequirePhrase = !isPhrase;
      }
      assert( nByte>0 );
    }
    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
    nIn -= nByte;
    zIn += nByte;
    pPrev = p;
  }

  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
    rc = SQLITE_ERROR;
  }

  if( rc==SQLITE_DONE ){
    rc = SQLITE_OK;
    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
      if( !pRet ){
        rc = SQLITE_ERROR;
      }else{
        Fts3Expr *pIter = pNotBranch;
        while( pIter->pLeft ){
          pIter = pIter->pLeft;
        }
        pIter->pLeft = pRet;
        pRet = pNotBranch;
      }
    }
  }
  *pnConsumed = n - nIn;

exprparse_out:
  if( rc!=SQLITE_OK ){
    sqlite3Fts3ExprFree(pRet);
    sqlite3Fts3ExprFree(pNotBranch);
    pRet = 0;
  }
  *ppExpr = pRet;
  return rc;
}

/*
** Parameters z and n contain a pointer to and length of a buffer containing
** an fts3 query expression, respectively. This function attempts to parse the
** query expression and create a tree of Fts3Expr structures representing the
** parsed expression. If successful, *ppExpr is set to point to the head
** of the parsed expression tree and SQLITE_OK is returned. If an error
** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
** error) is returned and *ppExpr is set to 0.
**
** If parameter n is a negative number, then z is assumed to point to a
** nul-terminated string and the length is determined using strlen().
**
** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
** use to normalize query tokens while parsing the expression. The azCol[]
** array, which is assumed to contain nCol entries, should contain the names
** of each column in the target fts3 table, in order from left to right. 
** Column names must be nul-terminated strings.
**
** The iDefaultCol parameter should be passed the index of the table column
** that appears on the left-hand-side of the MATCH operator (the default
** column to match against for tokens for which a column name is not explicitly
** specified as part of the query string), or -1 if tokens may by default
** match any table column.
*/
int sqlite3Fts3ExprParse(
  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
  char **azCol,                       /* Array of column names for fts3 table */
  int nCol,                           /* Number of entries in azCol[] */
  int iDefaultCol,                    /* Default column to query */
  const char *z, int n,               /* Text of MATCH query */
  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
){
  int nParsed;
  int rc;
  ParseContext sParse;
  sParse.pTokenizer = pTokenizer;
  sParse.azCol = (const char **)azCol;
  sParse.nCol = nCol;
  sParse.iDefaultCol = iDefaultCol;
  sParse.nNest = 0;
  if( z==0 ){
    *ppExpr = 0;
    return SQLITE_OK;
  }
  if( n<0 ){
    n = strlen(z);
  }
  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);

  /* Check for mismatched parenthesis */
  if( rc==SQLITE_OK && sParse.nNest ){
    rc = SQLITE_ERROR;
    sqlite3Fts3ExprFree(*ppExpr);
    *ppExpr = 0;
  }

  return rc;
}

/*
** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
*/
void sqlite3Fts3ExprFree(Fts3Expr *p){
  if( p ){
    sqlite3Fts3ExprFree(p->pLeft);
    sqlite3Fts3ExprFree(p->pRight);
    sqlite3_free(p);
  }
}

/****************************************************************************
*****************************************************************************
** Everything after this point is just test code.
*/

#ifdef SQLITE_TEST

#include <stdio.h>

/*
** Function to query the hash-table of tokenizers (see README.tokenizers).
*/
static int queryTestTokenizer(
  sqlite3 *db, 
  const char *zName,  
  const sqlite3_tokenizer_module **pp
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts3_tokenizer(?)";

  *pp = 0;
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  if( SQLITE_ROW==sqlite3_step(pStmt) ){
    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
      memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
    }
  }

  return sqlite3_finalize(pStmt);
}

/*
** This function is part of the test interface for the query parser. It
** writes a text representation of the query expression pExpr into the
** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
** enough to store the required text representation.
*/
static void exprToString(Fts3Expr *pExpr, char *zBuf){
  switch( pExpr->eType ){
    case FTSQUERY_PHRASE: {
      Fts3Phrase *pPhrase = pExpr->pPhrase;
      int i;
      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
      for(i=0; i<pPhrase->nToken; i++){
        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
      }
      return;
    }

    case FTSQUERY_NEAR:
      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
      break;
    case FTSQUERY_NOT:
      zBuf += sprintf(zBuf, "NOT ");
      break;
    case FTSQUERY_AND:
      zBuf += sprintf(zBuf, "AND ");
      break;
    case FTSQUERY_OR:
      zBuf += sprintf(zBuf, "OR ");
      break;
  }

  zBuf += sprintf(zBuf, "{");
  exprToString(pExpr->pLeft, zBuf);
  zBuf += strlen(zBuf);
  zBuf += sprintf(zBuf, "} ");

  zBuf += sprintf(zBuf, "{");
  exprToString(pExpr->pRight, zBuf);
  zBuf += strlen(zBuf);
  zBuf += sprintf(zBuf, "}");
}

/*
** This is the implementation of a scalar SQL function used to test the 
** expression parser. It should be called as follows:
**
**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
**
** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
** to parse the query expression (see README.tokenizers). The second argument
** is the query expression to parse. Each subsequent argument is the name
** of a column of the fts3 table that the query expression may refer to.
** For example:
**
**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
*/
static void fts3ExprTest(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  sqlite3_tokenizer_module const *pModule = 0;
  sqlite3_tokenizer *pTokenizer = 0;
  int rc;
  char **azCol = 0;
  const char *zExpr;
  int nExpr;
  int nCol;
  int ii;
  Fts3Expr *pExpr;
  sqlite3 *db = sqlite3_context_db_handle(context);

  if( argc<3 ){
    sqlite3_result_error(context, 
        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
    );
    return;
  }

  rc = queryTestTokenizer(db,
                          (const char *)sqlite3_value_text(argv[0]), &pModule);
  if( rc==SQLITE_NOMEM ){
    sqlite3_result_error_nomem(context);
    goto exprtest_out;
  }else if( !pModule ){
    sqlite3_result_error(context, "No such tokenizer module", -1);
    goto exprtest_out;
  }

  rc = pModule->xCreate(0, 0, &pTokenizer);
  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  if( rc==SQLITE_NOMEM ){
    sqlite3_result_error_nomem(context);
    goto exprtest_out;
  }
  pTokenizer->pModule = pModule;

  zExpr = (const char *)sqlite3_value_text(argv[1]);
  nExpr = sqlite3_value_bytes(argv[1]);
  nCol = argc-2;
  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  if( !azCol ){
    sqlite3_result_error_nomem(context);
    goto exprtest_out;
  }
  for(ii=0; ii<nCol; ii++){
    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  }

  rc = sqlite3Fts3ExprParse(
      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
  );
  if( rc==SQLITE_NOMEM ){
    sqlite3_result_error_nomem(context);
    goto exprtest_out;
  }else if( rc==SQLITE_OK ){
    char zBuf[4096];
    exprToString(pExpr, zBuf);
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
    sqlite3Fts3ExprFree(pExpr);
  }else{
    sqlite3_result_error(context, "Error parsing expression", -1);
  }

exprtest_out:
  if( pModule && pTokenizer ){
    rc = pModule->xDestroy(pTokenizer);
  }
  sqlite3_free(azCol);
}

/*
** Register the query expression parser test function fts3_exprtest() 
** with database connection db. 
*/
void sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  sqlite3_create_function(
      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  );
}

#endif
#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/fts3_expr.h.

































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
** 2008 Nov 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
*/

#include "fts3_tokenizer.h"
#include "sqlite3.h"

/*
** The following describes the syntax supported by the fts3 MATCH
** operator in a similar format to that used by the lemon parser
** generator. This module does not use actually lemon, it uses a
** custom parser.
**
**   query ::= andexpr (OR andexpr)*.
**
**   andexpr ::= notexpr (AND? notexpr)*.
**
**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
**   notexpr ::= LP query RP.
**
**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
**
**   distance_opt ::= .
**   distance_opt ::= / INTEGER.
**
**   phrase ::= TOKEN.
**   phrase ::= COLUMN:TOKEN.
**   phrase ::= "TOKEN TOKEN TOKEN...".
*/

typedef struct Fts3Expr Fts3Expr;
typedef struct Fts3Phrase Fts3Phrase;

/*
** A "phrase" is a sequence of one or more tokens that must match in
** sequence.  A single token is the base case and the most common case.
** For a sequence of tokens contained in "...", nToken will be the number
** of tokens in the string.
*/
struct Fts3Phrase {
  int nToken;          /* Number of tokens in the phrase */
  int iColumn;         /* Index of column this phrase must match */
  int isNot;           /* Phrase prefixed by unary not (-) operator */
  struct PhraseToken {
    char *z;              /* Text of the token */
    int n;                /* Number of bytes in buffer pointed to by z */
    int isPrefix;         /* True if token ends in with a "*" character */
  } aToken[1];         /* One entry for each token in the phrase */
};

/*
** A tree of these objects forms the RHS of a MATCH operator.
*/
struct Fts3Expr {
  int eType;                 /* One of the FTSQUERY_XXX values defined below */
  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
  Fts3Expr *pLeft;           /* Left operand */
  Fts3Expr *pRight;          /* Right operand */
  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
};

int sqlite3Fts3ExprParse(sqlite3_tokenizer *, char **, int, int, 
                         const char *, int, Fts3Expr **);
void sqlite3Fts3ExprFree(Fts3Expr *);

/*
** Candidate values for Fts3Query.eType. Note that the order of the first
** four values is in order of precedence when parsing expressions. For 
** example, the following:
**
**   "a OR b AND c NOT d NEAR e"
**
** is equivalent to:
**
**   "a OR (b AND (c NOT (d NEAR e)))"
*/
#define FTSQUERY_NEAR   1
#define FTSQUERY_NOT    2
#define FTSQUERY_AND    3
#define FTSQUERY_OR     4
#define FTSQUERY_PHRASE 5

#ifdef SQLITE_TEST
void sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
#endif

Added ext/fts3/fts3_hash.c.











































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables used in SQLite.
** We've modified it slightly to serve as a standalone hash table
** implementation for the full-text indexing module.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS3 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS3 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "sqlite3.h"
#include "fts3_hash.h"

/*
** Malloc and Free functions
*/
static void *fts3HashMalloc(int n){
  void *p = sqlite3_malloc(n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}
static void fts3HashFree(void *p){
  sqlite3_free(p);
}

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
** keyClass is one of the constants 
** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
** determines what kind of key the hash table will use.  "copyKey" is
** true if the hash table should make its own private copy of keys and
** false if it should just use the supplied pointer.
*/
void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
  assert( pNew!=0 );
  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  pNew->keyClass = keyClass;
  pNew->copyKey = copyKey;
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite3Fts3HashClear(fts3Hash *pH){
  fts3HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  fts3HashFree(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    fts3HashElem *next_elem = elem->next;
    if( pH->copyKey && elem->pKey ){
      fts3HashFree(elem->pKey);
    }
    fts3HashFree(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** Hash and comparison functions when the mode is FTS3_HASH_STRING
*/
static int fts3StrHash(const void *pKey, int nKey){
  const char *z = (const char *)pKey;
  int h = 0;
  if( nKey<=0 ) nKey = (int) strlen(z);
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ *z++;
    nKey--;
  }
  return h & 0x7fffffff;
}
static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
}

/*
** Hash and comparison functions when the mode is FTS3_HASH_BINARY
*/
static int fts3BinHash(const void *pKey, int nKey){
  int h = 0;
  const char *z = (const char *)pKey;
  while( nKey-- > 0 ){
    h = (h<<3) ^ h ^ *(z++);
  }
  return h & 0x7fffffff;
}
static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return memcmp(pKey1,pKey2,n1);
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** The C syntax in this function definition may be unfamilar to some 
** programmers, so we provide the following additional explanation:
**
** The name of the function is "ftsHashFunction".  The function takes a
** single parameter "keyClass".  The return value of ftsHashFunction()
** is a pointer to another function.  Specifically, the return value
** of ftsHashFunction() is a pointer to a function that takes two parameters
** with types "const void*" and "int" and returns an "int".
*/
static int (*ftsHashFunction(int keyClass))(const void*,int){
  if( keyClass==FTS3_HASH_STRING ){
    return &fts3StrHash;
  }else{
    assert( keyClass==FTS3_HASH_BINARY );
    return &fts3BinHash;
  }
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** For help in interpreted the obscure C code in the function definition,
** see the header comment on the previous function.
*/
static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  if( keyClass==FTS3_HASH_STRING ){
    return &fts3StrCompare;
  }else{
    assert( keyClass==FTS3_HASH_BINARY );
    return &fts3BinCompare;
  }
}

/* Link an element into the hash table
*/
static void fts3HashInsertElement(
  fts3Hash *pH,            /* The complete hash table */
  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
  fts3HashElem *pNew       /* The element to be inserted */
){
  fts3HashElem *pHead;     /* First element already in pEntry */
  pHead = pEntry->chain;
  if( pHead ){
    pNew->next = pHead;
    pNew->prev = pHead->prev;
    if( pHead->prev ){ pHead->prev->next = pNew; }
    else             { pH->first = pNew; }
    pHead->prev = pNew;
  }else{
    pNew->next = pH->first;
    if( pH->first ){ pH->first->prev = pNew; }
    pNew->prev = 0;
    pH->first = pNew;
  }
  pEntry->count++;
  pEntry->chain = pNew;
}


/* Resize the hash table so that it cantains "new_size" buckets.
** "new_size" must be a power of 2.  The hash table might fail 
** to resize if sqliteMalloc() fails.
*/
static void fts3Rehash(fts3Hash *pH, int new_size){
  struct _fts3ht *new_ht;          /* The new hash table */
  fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
  int (*xHash)(const void*,int);   /* The hash function */

  assert( (new_size & (new_size-1))==0 );
  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  if( new_ht==0 ) return;
  fts3HashFree(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size;
  xHash = ftsHashFunction(pH->keyClass);
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
    next_elem = elem->next;
    fts3HashInsertElement(pH, &new_ht[h], elem);
  }
}

/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static fts3HashElem *fts3FindElementByHash(
  const fts3Hash *pH, /* The pH to be searched */
  const void *pKey,   /* The key we are searching for */
  int nKey,
  int h               /* The hash for this key. */
){
  fts3HashElem *elem;            /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */
  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */

  if( pH->ht ){
    struct _fts3ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
    xCompare = ftsCompareFunction(pH->keyClass);
    while( count-- && elem ){
      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
        return elem;
      }
      elem = elem->next;
    }
  }
  return 0;
}

/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void fts3RemoveElementByHash(
  fts3Hash *pH,         /* The pH containing "elem" */
  fts3HashElem* elem,   /* The element to be removed from the pH */
  int h                 /* Hash value for the element */
){
  struct _fts3ht *pEntry;
  if( elem->prev ){
    elem->prev->next = elem->next; 
  }else{
    pH->first = elem->next;
  }
  if( elem->next ){
    elem->next->prev = elem->prev;
  }
  pEntry = &pH->ht[h];
  if( pEntry->chain==elem ){
    pEntry->chain = elem->next;
  }
  pEntry->count--;
  if( pEntry->count<=0 ){
    pEntry->chain = 0;
  }
  if( pH->copyKey && elem->pKey ){
    fts3HashFree(elem->pKey);
  }
  fts3HashFree( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    fts3HashClear(pH);
  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
  int h;                 /* A hash on key */
  fts3HashElem *elem;    /* The element that matches key */
  int (*xHash)(const void*,int);  /* The hash function */

  if( pH==0 || pH->ht==0 ) return 0;
  xHash = ftsHashFunction(pH->keyClass);
  assert( xHash!=0 );
  h = (*xHash)(pKey,nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  return elem ? elem->data : 0;
}

/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *sqlite3Fts3HashInsert(
  fts3Hash *pH,        /* The hash table to insert into */
  const void *pKey,    /* The key */
  int nKey,            /* Number of bytes in the key */
  void *data           /* The data */
){
  int hraw;                 /* Raw hash value of the key */
  int h;                    /* the hash of the key modulo hash table size */
  fts3HashElem *elem;       /* Used to loop thru the element list */
  fts3HashElem *new_elem;   /* New element added to the pH */
  int (*xHash)(const void*,int);  /* The hash function */

  assert( pH!=0 );
  xHash = ftsHashFunction(pH->keyClass);
  assert( xHash!=0 );
  hraw = (*xHash)(pKey, nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  elem = fts3FindElementByHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      fts3RemoveElementByHash(pH,elem,h);
    }else{
      elem->data = data;
    }
    return old_data;
  }
  if( data==0 ) return 0;
  if( pH->htsize==0 ){
    fts3Rehash(pH,8);
    if( pH->htsize==0 ){
      pH->count = 0;
      return data;
    }
  }
  new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = fts3HashMalloc( nKey );
    if( new_elem->pKey==0 ){
      fts3HashFree(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->count > pH->htsize ){
    fts3Rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/fts3_hash.h.





























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in SQLite.  We've modified it slightly to serve as a standalone
** hash table implementation for the full-text indexing module.
**
*/
#ifndef _FTS3_HASH_H_
#define _FTS3_HASH_H_

/* Forward declarations of structures. */
typedef struct fts3Hash fts3Hash;
typedef struct fts3HashElem fts3HashElem;

/* A complete hash table is an instance of the following structure.
** The internals of this structure are intended to be opaque -- client
** code should not attempt to access or modify the fields of this structure
** directly.  Change this structure only by using the routines below.
** However, many of the "procedures" and "functions" for modifying and
** accessing this structure are really macros, so we can't really make
** this structure opaque.
*/
struct fts3Hash {
  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
  char copyKey;           /* True if copy of key made on insert */
  int count;              /* Number of entries in this table */
  fts3HashElem *first;    /* The first element of the array */
  int htsize;             /* Number of buckets in the hash table */
  struct _fts3ht {        /* the hash table */
    int count;               /* Number of entries with this hash */
    fts3HashElem *chain;     /* Pointer to first entry with this hash */
  } *ht;
};

/* Each element in the hash table is an instance of the following 
** structure.  All elements are stored on a single doubly-linked list.
**
** Again, this structure is intended to be opaque, but it can't really
** be opaque because it is used by macros.
*/
struct fts3HashElem {
  fts3HashElem *next, *prev; /* Next and previous elements in the table */
  void *data;                /* Data associated with this element */
  void *pKey; int nKey;      /* Key associated with this element */
};

/*
** There are 2 different modes of operation for a hash table:
**
**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
**                           (including the null-terminator, if any).  Case
**                           is respected in comparisons.
**
**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
**                           memcmp() is used to compare keys.
**
** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
*/
#define FTS3_HASH_STRING    1
#define FTS3_HASH_BINARY    2

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
void sqlite3Fts3HashClear(fts3Hash*);

/*
** Shorthand for the functions above
*/
#define fts3HashInit   sqlite3Fts3HashInit
#define fts3HashInsert sqlite3Fts3HashInsert
#define fts3HashFind   sqlite3Fts3HashFind
#define fts3HashClear  sqlite3Fts3HashClear

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   fts3Hash h;
**   fts3HashElem *p;
**   ...
**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
**     SomeStructure *pData = fts3HashData(p);
**     // do something with pData
**   }
*/
#define fts3HashFirst(H)  ((H)->first)
#define fts3HashNext(E)   ((E)->next)
#define fts3HashData(E)   ((E)->data)
#define fts3HashKey(E)    ((E)->pKey)
#define fts3HashKeysize(E) ((E)->nKey)

/*
** Number of entries in a hash table
*/
#define fts3HashCount(H)  ((H)->count)

#endif /* _FTS3_HASH_H_ */

Added ext/fts3/fts3_icu.c.









































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
** 2007 June 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements a tokenizer for fts3 based on the ICU library.
** 
** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
#ifdef SQLITE_ENABLE_ICU

#include <assert.h>
#include <string.h>
#include "fts3_tokenizer.h"

#include <unicode/ubrk.h>
#include <unicode/ucol.h>
#include <unicode/ustring.h>
#include <unicode/utf16.h>

typedef struct IcuTokenizer IcuTokenizer;
typedef struct IcuCursor IcuCursor;

struct IcuTokenizer {
  sqlite3_tokenizer base;
  char *zLocale;
};

struct IcuCursor {
  sqlite3_tokenizer_cursor base;

  UBreakIterator *pIter;      /* ICU break-iterator object */
  int nChar;                  /* Number of UChar elements in pInput */
  UChar *aChar;               /* Copy of input using utf-16 encoding */
  int *aOffset;               /* Offsets of each character in utf-8 input */

  int nBuffer;
  char *zBuffer;

  int iToken;
};

/*
** Create a new tokenizer instance.
*/
static int icuCreate(
  int argc,                            /* Number of entries in argv[] */
  const char * const *argv,            /* Tokenizer creation arguments */
  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
){
  IcuTokenizer *p;
  int n = 0;

  if( argc>0 ){
    n = strlen(argv[0])+1;
  }
  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  if( !p ){
    return SQLITE_NOMEM;
  }
  memset(p, 0, sizeof(IcuTokenizer));

  if( n ){
    p->zLocale = (char *)&p[1];
    memcpy(p->zLocale, argv[0], n);
  }

  *ppTokenizer = (sqlite3_tokenizer *)p;

  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  sqlite3_free(p);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is pInput[0..nBytes-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int icuOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *zInput,                    /* Input string */
  int nInput,                            /* Length of zInput in bytes */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  IcuCursor *pCsr;

  const int32_t opt = U_FOLD_CASE_DEFAULT;
  UErrorCode status = U_ZERO_ERROR;
  int nChar;

  UChar32 c;
  int iInput = 0;
  int iOut = 0;

  *ppCursor = 0;

  if( nInput<0 ){
    nInput = strlen(zInput);
  }
  nChar = nInput+1;
  pCsr = (IcuCursor *)sqlite3_malloc(
      sizeof(IcuCursor) +                /* IcuCursor */
      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
  );
  if( !pCsr ){
    return SQLITE_NOMEM;
  }
  memset(pCsr, 0, sizeof(IcuCursor));
  pCsr->aChar = (UChar *)&pCsr[1];
  pCsr->aOffset = (int *)&pCsr->aChar[nChar];

  pCsr->aOffset[iOut] = iInput;
  U8_NEXT(zInput, iInput, nInput, c); 
  while( c>0 ){
    int isError = 0;
    c = u_foldCase(c, opt);
    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
    if( isError ){
      sqlite3_free(pCsr);
      return SQLITE_ERROR;
    }
    pCsr->aOffset[iOut] = iInput;

    if( iInput<nInput ){
      U8_NEXT(zInput, iInput, nInput, c);
    }else{
      c = 0;
    }
  }

  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  if( !U_SUCCESS(status) ){
    sqlite3_free(pCsr);
    return SQLITE_ERROR;
  }
  pCsr->nChar = iOut;

  ubrk_first(pCsr->pIter);
  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to icuOpen().
*/
static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  IcuCursor *pCsr = (IcuCursor *)pCursor;
  ubrk_close(pCsr->pIter);
  sqlite3_free(pCsr->zBuffer);
  sqlite3_free(pCsr);
  return SQLITE_OK;
}

/*
** Extract the next token from a tokenization cursor.
*/
static int icuNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
  const char **ppToken,               /* OUT: *ppToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  IcuCursor *pCsr = (IcuCursor *)pCursor;

  int iStart = 0;
  int iEnd = 0;
  int nByte = 0;

  while( iStart==iEnd ){
    UChar32 c;

    iStart = ubrk_current(pCsr->pIter);
    iEnd = ubrk_next(pCsr->pIter);
    if( iEnd==UBRK_DONE ){
      return SQLITE_DONE;
    }

    while( iStart<iEnd ){
      int iWhite = iStart;
      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
      if( u_isspace(c) ){
        iStart = iWhite;
      }else{
        break;
      }
    }
    assert(iStart<=iEnd);
  }

  do {
    UErrorCode status = U_ZERO_ERROR;
    if( nByte ){
      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
      if( !zNew ){
        return SQLITE_NOMEM;
      }
      pCsr->zBuffer = zNew;
      pCsr->nBuffer = nByte;
    }

    u_strToUTF8(
        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
        &status                                  /* Output success/failure */
    );
  } while( nByte>pCsr->nBuffer );

  *ppToken = pCsr->zBuffer;
  *pnBytes = nByte;
  *piStartOffset = pCsr->aOffset[iStart];
  *piEndOffset = pCsr->aOffset[iEnd];
  *piPosition = pCsr->iToken++;

  return SQLITE_OK;
}

/*
** The set of routines that implement the simple tokenizer
*/
static const sqlite3_tokenizer_module icuTokenizerModule = {
  0,                           /* iVersion */
  icuCreate,                   /* xCreate  */
  icuDestroy,                  /* xCreate  */
  icuOpen,                     /* xOpen    */
  icuClose,                    /* xClose   */
  icuNext,                     /* xNext    */
};

/*
** Set *ppModule to point at the implementation of the ICU tokenizer.
*/
void sqlite3Fts3IcuTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &icuTokenizerModule;
}

#endif /* defined(SQLITE_ENABLE_ICU) */
#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/fts3_porter.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*
** 2006 September 30
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Implementation of the full-text-search tokenizer that implements
** a Porter stemmer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS3 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS3 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)


#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts3_tokenizer.h"

/*
** Class derived from sqlite3_tokenizer
*/
typedef struct porter_tokenizer {
  sqlite3_tokenizer base;      /* Base class */
} porter_tokenizer;

/*
** Class derived from sqlit3_tokenizer_cursor
*/
typedef struct porter_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *zInput;          /* input we are tokenizing */
  int nInput;                  /* size of the input */
  int iOffset;                 /* current position in zInput */
  int iToken;                  /* index of next token to be returned */
  char *zToken;                /* storage for current token */
  int nAllocated;              /* space allocated to zToken buffer */
} porter_tokenizer_cursor;


/* Forward declaration */
static const sqlite3_tokenizer_module porterTokenizerModule;


/*
** Create a new tokenizer instance.
*/
static int porterCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  porter_tokenizer *t;
  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  if( t==NULL ) return SQLITE_NOMEM;
  memset(t, 0, sizeof(*t));
  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  sqlite3_free(pTokenizer);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is zInput[0..nInput-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int porterOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *zInput, int nInput,        /* String to be tokenized */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  porter_tokenizer_cursor *c;

  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  if( c==NULL ) return SQLITE_NOMEM;

  c->zInput = zInput;
  if( zInput==0 ){
    c->nInput = 0;
  }else if( nInput<0 ){
    c->nInput = (int)strlen(zInput);
  }else{
    c->nInput = nInput;
  }
  c->iOffset = 0;                 /* start tokenizing at the beginning */
  c->iToken = 0;
  c->zToken = NULL;               /* no space allocated, yet. */
  c->nAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to
** porterOpen() above.
*/
static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  sqlite3_free(c->zToken);
  sqlite3_free(c);
  return SQLITE_OK;
}
/*
** Vowel or consonant
*/
static const char cType[] = {
   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   1, 1, 1, 2, 1
};

/*
** isConsonant() and isVowel() determine if their first character in
** the string they point to is a consonant or a vowel, according
** to Porter ruls.  
**
** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
** 'Y' is a consonant unless it follows another consonant,
** in which case it is a vowel.
**
** In these routine, the letters are in reverse order.  So the 'y' rule
** is that 'y' is a consonant unless it is followed by another
** consonent.
*/
static int isVowel(const char*);
static int isConsonant(const char *z){
  int j;
  char x = *z;
  if( x==0 ) return 0;
  assert( x>='a' && x<='z' );
  j = cType[x-'a'];
  if( j<2 ) return j;
  return z[1]==0 || isVowel(z + 1);
}
static int isVowel(const char *z){
  int j;
  char x = *z;
  if( x==0 ) return 0;
  assert( x>='a' && x<='z' );
  j = cType[x-'a'];
  if( j<2 ) return 1-j;
  return isConsonant(z + 1);
}

/*
** Let any sequence of one or more vowels be represented by V and let
** C be sequence of one or more consonants.  Then every word can be
** represented as:
**
**           [C] (VC){m} [V]
**
** In prose:  A word is an optional consonant followed by zero or
** vowel-consonant pairs followed by an optional vowel.  "m" is the
** number of vowel consonant pairs.  This routine computes the value
** of m for the first i bytes of a word.
**
** Return true if the m-value for z is 1 or more.  In other words,
** return true if z contains at least one vowel that is followed
** by a consonant.
**
** In this routine z[] is in reverse order.  So we are really looking
** for an instance of of a consonant followed by a vowel.
*/
static int m_gt_0(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/* Like mgt0 above except we are looking for a value of m which is
** exactly 1
*/
static int m_eq_1(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 1;
  while( isConsonant(z) ){ z++; }
  return *z==0;
}

/* Like mgt0 above except we are looking for a value of m>1 instead
** or m>0
*/
static int m_gt_1(const char *z){
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isVowel(z) ){ z++; }
  if( *z==0 ) return 0;
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/*
** Return TRUE if there is a vowel anywhere within z[0..n-1]
*/
static int hasVowel(const char *z){
  while( isConsonant(z) ){ z++; }
  return *z!=0;
}

/*
** Return TRUE if the word ends in a double consonant.
**
** The text is reversed here. So we are really looking at
** the first two characters of z[].
*/
static int doubleConsonant(const char *z){
  return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
}

/*
** Return TRUE if the word ends with three letters which
** are consonant-vowel-consonent and where the final consonant
** is not 'w', 'x', or 'y'.
**
** The word is reversed here.  So we are really checking the
** first three letters and the first one cannot be in [wxy].
*/
static int star_oh(const char *z){
  return
    z[0]!=0 && isConsonant(z) &&
    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
    z[1]!=0 && isVowel(z+1) &&
    z[2]!=0 && isConsonant(z+2);
}

/*
** If the word ends with zFrom and xCond() is true for the stem
** of the word that preceeds the zFrom ending, then change the 
** ending to zTo.
**
** The input word *pz and zFrom are both in reverse order.  zTo
** is in normal order. 
**
** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
** match.  Not that TRUE is returned even if xCond() fails and
** no substitution occurs.
*/
static int stem(
  char **pz,             /* The word being stemmed (Reversed) */
  const char *zFrom,     /* If the ending matches this... (Reversed) */
  const char *zTo,       /* ... change the ending to this (not reversed) */
  int (*xCond)(const char*)   /* Condition that must be true */
){
  char *z = *pz;
  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  if( *zFrom!=0 ) return 0;
  if( xCond && !xCond(z) ) return 1;
  while( *zTo ){
    *(--z) = *(zTo++);
  }
  *pz = z;
  return 1;
}

/*
** This is the fallback stemmer used when the porter stemmer is
** inappropriate.  The input word is copied into the output with
** US-ASCII case folding.  If the input word is too long (more
** than 20 bytes if it contains no digits or more than 6 bytes if
** it contains digits) then word is truncated to 20 or 6 bytes
** by taking 10 or 3 bytes from the beginning and end.
*/
static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  int i, mx, j;
  int hasDigit = 0;
  for(i=0; i<nIn; i++){
    int c = zIn[i];
    if( c>='A' && c<='Z' ){
      zOut[i] = c - 'A' + 'a';
    }else{
      if( c>='0' && c<='9' ) hasDigit = 1;
      zOut[i] = c;
    }
  }
  mx = hasDigit ? 3 : 10;
  if( nIn>mx*2 ){
    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
      zOut[j] = zOut[i];
    }
    i = j;
  }
  zOut[i] = 0;
  *pnOut = i;
}


/*
** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
** zOut is at least big enough to hold nIn bytes.  Write the actual
** size of the output word (exclusive of the '\0' terminator) into *pnOut.
**
** Any upper-case characters in the US-ASCII character set ([A-Z])
** are converted to lower case.  Upper-case UTF characters are
** unchanged.
**
** Words that are longer than about 20 bytes are stemmed by retaining
** a few bytes from the beginning and the end of the word.  If the
** word contains digits, 3 bytes are taken from the beginning and
** 3 bytes from the end.  For long words without digits, 10 bytes
** are taken from each end.  US-ASCII case folding still applies.
** 
** If the input word contains not digits but does characters not 
** in [a-zA-Z] then no stemming is attempted and this routine just 
** copies the input into the input into the output with US-ASCII
** case folding.
**
** Stemming never increases the length of the word.  So there is
** no chance of overflowing the zOut buffer.
*/
static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  int i, j, c;
  char zReverse[28];
  char *z, *z2;
  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
    /* The word is too big or too small for the porter stemmer.
    ** Fallback to the copy stemmer */
    copy_stemmer(zIn, nIn, zOut, pnOut);
    return;
  }
  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
    c = zIn[i];
    if( c>='A' && c<='Z' ){
      zReverse[j] = c + 'a' - 'A';
    }else if( c>='a' && c<='z' ){
      zReverse[j] = c;
    }else{
      /* The use of a character not in [a-zA-Z] means that we fallback
      ** to the copy stemmer */
      copy_stemmer(zIn, nIn, zOut, pnOut);
      return;
    }
  }
  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  z = &zReverse[j+1];


  /* Step 1a */
  if( z[0]=='s' ){
    if(
     !stem(&z, "sess", "ss", 0) &&
     !stem(&z, "sei", "i", 0)  &&
     !stem(&z, "ss", "ss", 0)
    ){
      z++;
    }
  }

  /* Step 1b */  
  z2 = z;
  if( stem(&z, "dee", "ee", m_gt_0) ){
    /* Do nothing.  The work was all in the test */
  }else if( 
     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
      && z!=z2
  ){
     if( stem(&z, "ta", "ate", 0) ||
         stem(&z, "lb", "ble", 0) ||
         stem(&z, "zi", "ize", 0) ){
       /* Do nothing.  The work was all in the test */
     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
       z++;
     }else if( m_eq_1(z) && star_oh(z) ){
       *(--z) = 'e';
     }
  }

  /* Step 1c */
  if( z[0]=='y' && hasVowel(z+1) ){
    z[0] = 'i';
  }

  /* Step 2 */
  switch( z[1] ){
   case 'a':
     stem(&z, "lanoita", "ate", m_gt_0) ||
     stem(&z, "lanoit", "tion", m_gt_0);
     break;
   case 'c':
     stem(&z, "icne", "ence", m_gt_0) ||
     stem(&z, "icna", "ance", m_gt_0);
     break;
   case 'e':
     stem(&z, "rezi", "ize", m_gt_0);
     break;
   case 'g':
     stem(&z, "igol", "log", m_gt_0);
     break;
   case 'l':
     stem(&z, "ilb", "ble", m_gt_0) ||
     stem(&z, "illa", "al", m_gt_0) ||
     stem(&z, "iltne", "ent", m_gt_0) ||
     stem(&z, "ile", "e", m_gt_0) ||
     stem(&z, "ilsuo", "ous", m_gt_0);
     break;
   case 'o':
     stem(&z, "noitazi", "ize", m_gt_0) ||
     stem(&z, "noita", "ate", m_gt_0) ||
     stem(&z, "rota", "ate", m_gt_0);
     break;
   case 's':
     stem(&z, "msila", "al", m_gt_0) ||
     stem(&z, "ssenevi", "ive", m_gt_0) ||
     stem(&z, "ssenluf", "ful", m_gt_0) ||
     stem(&z, "ssensuo", "ous", m_gt_0);
     break;
   case 't':
     stem(&z, "itila", "al", m_gt_0) ||
     stem(&z, "itivi", "ive", m_gt_0) ||
     stem(&z, "itilib", "ble", m_gt_0);
     break;
  }

  /* Step 3 */
  switch( z[0] ){
   case 'e':
     stem(&z, "etaci", "ic", m_gt_0) ||
     stem(&z, "evita", "", m_gt_0)   ||
     stem(&z, "ezila", "al", m_gt_0);
     break;
   case 'i':
     stem(&z, "itici", "ic", m_gt_0);
     break;
   case 'l':
     stem(&z, "laci", "ic", m_gt_0) ||
     stem(&z, "luf", "", m_gt_0);
     break;
   case 's':
     stem(&z, "ssen", "", m_gt_0);
     break;
  }

  /* Step 4 */
  switch( z[1] ){
   case 'a':
     if( z[0]=='l' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'c':
     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
       z += 4;
     }
     break;
   case 'e':
     if( z[0]=='r' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'i':
     if( z[0]=='c' && m_gt_1(z+2) ){
       z += 2;
     }
     break;
   case 'l':
     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
       z += 4;
     }
     break;
   case 'n':
     if( z[0]=='t' ){
       if( z[2]=='a' ){
         if( m_gt_1(z+3) ){
           z += 3;
         }
       }else if( z[2]=='e' ){
         stem(&z, "tneme", "", m_gt_1) ||
         stem(&z, "tnem", "", m_gt_1) ||
         stem(&z, "tne", "", m_gt_1);
       }
     }
     break;
   case 'o':
     if( z[0]=='u' ){
       if( m_gt_1(z+2) ){
         z += 2;
       }
     }else if( z[3]=='s' || z[3]=='t' ){
       stem(&z, "noi", "", m_gt_1);
     }
     break;
   case 's':
     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
   case 't':
     stem(&z, "eta", "", m_gt_1) ||
     stem(&z, "iti", "", m_gt_1);
     break;
   case 'u':
     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
   case 'v':
   case 'z':
     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
       z += 3;
     }
     break;
  }

  /* Step 5a */
  if( z[0]=='e' ){
    if( m_gt_1(z+1) ){
      z++;
    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
      z++;
    }
  }

  /* Step 5b */
  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
    z++;
  }

  /* z[] is now the stemmed word in reverse order.  Flip it back
  ** around into forward order and return.
  */
  *pnOut = i = strlen(z);
  zOut[i] = 0;
  while( *z ){
    zOut[--i] = *(z++);
  }
}

/*
** Characters that can be part of a token.  We assume any character
** whose value is greater than 0x80 (any UTF character) can be
** part of a token.  In other words, delimiters all must have
** values of 0x7f or lower.
*/
static const char porterIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))

/*
** Extract the next token from a tokenization cursor.  The cursor must
** have been opened by a prior call to porterOpen().
*/
static int porterNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
  const char **pzToken,               /* OUT: *pzToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  const char *z = c->zInput;

  while( c->iOffset<c->nInput ){
    int iStartOffset, ch;

    /* Scan past delimiter characters */
    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
      c->iOffset++;
    }

    /* Count non-delimiter characters. */
    iStartOffset = c->iOffset;
    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
      c->iOffset++;
    }

    if( c->iOffset>iStartOffset ){
      int n = c->iOffset-iStartOffset;
      if( n>c->nAllocated ){
        c->nAllocated = n+20;
        c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
        if( c->zToken==NULL ) return SQLITE_NOMEM;
      }
      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
      *pzToken = c->zToken;
      *piStartOffset = iStartOffset;
      *piEndOffset = c->iOffset;
      *piPosition = c->iToken++;
      return SQLITE_OK;
    }
  }
  return SQLITE_DONE;
}

/*
** The set of routines that implement the porter-stemmer tokenizer
*/
static const sqlite3_tokenizer_module porterTokenizerModule = {
  0,
  porterCreate,
  porterDestroy,
  porterOpen,
  porterClose,
  porterNext,
};

/*
** Allocate a new porter tokenizer.  Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts3PorterTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &porterTokenizerModule;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/fts3_tokenizer.c.







































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
** 2007 June 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is part of an SQLite module implementing full-text search.
** This particular file implements the generic tokenizer interface.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS3 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS3 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)

#include "sqlite3ext.h"
#ifndef SQLITE_CORE
  SQLITE_EXTENSION_INIT1
#endif

#include "fts3_hash.h"
#include "fts3_tokenizer.h"
#include <assert.h>

/*
** Implementation of the SQL scalar function for accessing the underlying 
** hash table. This function may be called as follows:
**
**   SELECT <function-name>(<key-name>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
**
** If the <pointer> argument is specified, it must be a blob value
** containing a pointer to be stored as the hash data corresponding
** to the string <key-name>. If <pointer> is not specified, then
** the string <key-name> must already exist in the has table. Otherwise,
** an error is returned.
**
** Whether or not the <pointer> argument is specified, the value returned
** is a blob containing the pointer stored as the hash data corresponding
** to string <key-name> (after the hash-table is updated, if applicable).
*/
static void scalarFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fts3Hash *pHash;
  void *pPtr = 0;
  const unsigned char *zName;
  int nName;

  assert( argc==1 || argc==2 );

  pHash = (fts3Hash *)sqlite3_user_data(context);

  zName = sqlite3_value_text(argv[0]);
  nName = sqlite3_value_bytes(argv[0])+1;

  if( argc==2 ){
    void *pOld;
    int n = sqlite3_value_bytes(argv[1]);
    if( n!=sizeof(pPtr) ){
      sqlite3_result_error(context, "argument type mismatch", -1);
      return;
    }
    pPtr = *(void **)sqlite3_value_blob(argv[1]);
    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
    if( pOld==pPtr ){
      sqlite3_result_error(context, "out of memory", -1);
      return;
    }
  }else{
    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
    if( !pPtr ){
      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
      sqlite3_result_error(context, zErr, -1);
      sqlite3_free(zErr);
      return;
    }
  }

  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
}

#ifdef SQLITE_TEST

#include <tcl.h>
#include <string.h>

/*
** Implementation of a special SQL scalar function for testing tokenizers 
** designed to be used in concert with the Tcl testing framework. This
** function must be called with two arguments:
**
**   SELECT <function-name>(<key-name>, <input-string>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
**
** The return value is a string that may be interpreted as a Tcl
** list. For each token in the <input-string>, three elements are
** added to the returned list. The first is the token position, the 
** second is the token text (folded, stemmed, etc.) and the third is the
** substring of <input-string> associated with the token. For example, 
** using the built-in "simple" tokenizer:
**
**   SELECT fts_tokenizer_test('simple', 'I don't see how');
**
** will return the string:
**
**   "{0 i I 1 dont don't 2 see see 3 how how}"
**   
*/
static void testFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fts3Hash *pHash;
  sqlite3_tokenizer_module *p;
  sqlite3_tokenizer *pTokenizer = 0;
  sqlite3_tokenizer_cursor *pCsr = 0;

  const char *zErr = 0;

  const char *zName;
  int nName;
  const char *zInput;
  int nInput;

  const char *zArg = 0;

  const char *zToken;
  int nToken;
  int iStart;
  int iEnd;
  int iPos;

  Tcl_Obj *pRet;

  assert( argc==2 || argc==3 );

  nName = sqlite3_value_bytes(argv[0]);
  zName = (const char *)sqlite3_value_text(argv[0]);
  nInput = sqlite3_value_bytes(argv[argc-1]);
  zInput = (const char *)sqlite3_value_text(argv[argc-1]);

  if( argc==3 ){
    zArg = (const char *)sqlite3_value_text(argv[1]);
  }

  pHash = (fts3Hash *)sqlite3_user_data(context);
  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);

  if( !p ){
    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
    sqlite3_result_error(context, zErr, -1);
    sqlite3_free(zErr);
    return;
  }

  pRet = Tcl_NewObj();
  Tcl_IncrRefCount(pRet);

  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
    zErr = "error in xCreate()";
    goto finish;
  }
  pTokenizer->pModule = p;
  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
    zErr = "error in xOpen()";
    goto finish;
  }
  pCsr->pTokenizer = pTokenizer;

  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
    zToken = &zInput[iStart];
    nToken = iEnd-iStart;
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  }

  if( SQLITE_OK!=p->xClose(pCsr) ){
    zErr = "error in xClose()";
    goto finish;
  }
  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
    zErr = "error in xDestroy()";
    goto finish;
  }

finish:
  if( zErr ){
    sqlite3_result_error(context, zErr, -1);
  }else{
    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  }
  Tcl_DecrRefCount(pRet);
}

static
int registerTokenizer(
  sqlite3 *db, 
  char *zName, 
  const sqlite3_tokenizer_module *p
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";

  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  sqlite3_step(pStmt);

  return sqlite3_finalize(pStmt);
}

static
int queryTokenizer(
  sqlite3 *db, 
  char *zName,  
  const sqlite3_tokenizer_module **pp
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts3_tokenizer(?)";

  *pp = 0;
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  if( SQLITE_ROW==sqlite3_step(pStmt) ){
    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
      memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
    }
  }

  return sqlite3_finalize(pStmt);
}

void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);

/*
** Implementation of the scalar function fts3_tokenizer_internal_test().
** This function is used for testing only, it is not included in the
** build unless SQLITE_TEST is defined.
**
** The purpose of this is to test that the fts3_tokenizer() function
** can be used as designed by the C-code in the queryTokenizer and
** registerTokenizer() functions above. These two functions are repeated
** in the README.tokenizer file as an example, so it is important to
** test them.
**
** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
** function with no arguments. An assert() will fail if a problem is
** detected. i.e.:
**
**     SELECT fts3_tokenizer_internal_test();
**
*/
static void intTestFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int rc;
  const sqlite3_tokenizer_module *p1;
  const sqlite3_tokenizer_module *p2;
  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);

  /* Test the query function */
  sqlite3Fts3SimpleTokenizerModule(&p1);
  rc = queryTokenizer(db, "simple", &p2);
  assert( rc==SQLITE_OK );
  assert( p1==p2 );
  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  assert( rc==SQLITE_ERROR );
  assert( p2==0 );
  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );

  /* Test the storage function */
  rc = registerTokenizer(db, "nosuchtokenizer", p1);
  assert( rc==SQLITE_OK );
  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  assert( rc==SQLITE_OK );
  assert( p2==p1 );

  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
}

#endif

/*
** Set up SQL objects in database db used to access the contents of
** the hash table pointed to by argument pHash. The hash table must
** been initialised to use string keys, and to take a private copy 
** of the key when a value is inserted. i.e. by a call similar to:
**
**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
**
** This function adds a scalar function (see header comment above
** scalarFunc() in this file for details) and, if ENABLE_TABLE is
** defined at compilation time, a temporary virtual table (see header 
** comment above struct HashTableVtab) to the database schema. Both 
** provide read/write access to the contents of *pHash.
**
** The third argument to this function, zName, is used as the name
** of both the scalar and, if created, the virtual table.
*/
int sqlite3Fts3InitHashTable(
  sqlite3 *db, 
  fts3Hash *pHash, 
  const char *zName
){
  int rc = SQLITE_OK;
  void *p = (void *)pHash;
  const int any = SQLITE_ANY;
  char *zTest = 0;
  char *zTest2 = 0;

#ifdef SQLITE_TEST
  void *pdb = (void *)db;
  zTest = sqlite3_mprintf("%s_test", zName);
  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  if( !zTest || !zTest2 ){
    rc = SQLITE_NOMEM;
  }
#endif

  if( rc!=SQLITE_OK
   || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
#ifdef SQLITE_TEST
   || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
#endif
  );

  sqlite3_free(zTest);
  sqlite3_free(zTest2);
  return rc;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/fts3_tokenizer.h.









































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
** 2006 July 10
**
** The author disclaims copyright to this source code.
**
*************************************************************************
** Defines the interface to tokenizers used by fulltext-search.  There
** are three basic components:
**
** sqlite3_tokenizer_module is a singleton defining the tokenizer
** interface functions.  This is essentially the class structure for
** tokenizers.
**
** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
** including customization information defined at creation time.
**
** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
** tokens from a particular input.
*/
#ifndef _FTS3_TOKENIZER_H_
#define _FTS3_TOKENIZER_H_

/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
** If tokenizers are to be allowed to call sqlite3_*() functions, then
** we will need a way to register the API consistently.
*/
#include "sqlite3.h"

/*
** Structures used by the tokenizer interface. When a new tokenizer
** implementation is registered, the caller provides a pointer to
** an sqlite3_tokenizer_module containing pointers to the callback
** functions that make up an implementation.
**
** When an fts3 table is created, it passes any arguments passed to
** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
** implementation. The xCreate() function in turn returns an 
** sqlite3_tokenizer structure representing the specific tokenizer to
** be used for the fts3 table (customized by the tokenizer clause arguments).
**
** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
** method is called. It returns an sqlite3_tokenizer_cursor object
** that may be used to tokenize a specific input buffer based on
** the tokenization rules supplied by a specific sqlite3_tokenizer
** object.
*/
typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
typedef struct sqlite3_tokenizer sqlite3_tokenizer;
typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;

struct sqlite3_tokenizer_module {

  /*
  ** Structure version. Should always be set to 0.
  */
  int iVersion;

  /*
  ** Create a new tokenizer. The values in the argv[] array are the
  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  ** TABLE statement that created the fts3 table. For example, if
  ** the following SQL is executed:
  **
  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  **
  ** then argc is set to 2, and the argv[] array contains pointers
  ** to the strings "arg1" and "arg2".
  **
  ** This method should return either SQLITE_OK (0), or an SQLite error 
  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  ** to point at the newly created tokenizer structure. The generic
  ** sqlite3_tokenizer.pModule variable should not be initialised by
  ** this callback. The caller will do so.
  */
  int (*xCreate)(
    int argc,                           /* Size of argv array */
    const char *const*argv,             /* Tokenizer argument strings */
    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
  );

  /*
  ** Destroy an existing tokenizer. The fts3 module calls this method
  ** exactly once for each successful call to xCreate().
  */
  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);

  /*
  ** Create a tokenizer cursor to tokenize an input buffer. The caller
  ** is responsible for ensuring that the input buffer remains valid
  ** until the cursor is closed (using the xClose() method). 
  */
  int (*xOpen)(
    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
    const char *pInput, int nBytes,      /* Input buffer */
    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
  );

  /*
  ** Destroy an existing tokenizer cursor. The fts3 module calls this 
  ** method exactly once for each successful call to xOpen().
  */
  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);

  /*
  ** Retrieve the next token from the tokenizer cursor pCursor. This
  ** method should either return SQLITE_OK and set the values of the
  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  ** the end of the buffer has been reached, or an SQLite error code.
  **
  ** *ppToken should be set to point at a buffer containing the 
  ** normalized version of the token (i.e. after any case-folding and/or
  ** stemming has been performed). *pnBytes should be set to the length
  ** of this buffer in bytes. The input text that generated the token is
  ** identified by the byte offsets returned in *piStartOffset and
  ** *piEndOffset. *piStartOffset should be set to the index of the first
  ** byte of the token in the input buffer. *piEndOffset should be set
  ** to the index of the first byte just past the end of the token in
  ** the input buffer.
  **
  ** The buffer *ppToken is set to point at is managed by the tokenizer
  ** implementation. It is only required to be valid until the next call
  ** to xNext() or xClose(). 
  */
  /* TODO(shess) current implementation requires pInput to be
  ** nul-terminated.  This should either be fixed, or pInput/nBytes
  ** should be converted to zInput.
  */
  int (*xNext)(
    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
    int *piPosition      /* OUT: Number of tokens returned before this one */
  );
};

struct sqlite3_tokenizer {
  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
  /* Tokenizer implementations will typically add additional fields */
};

struct sqlite3_tokenizer_cursor {
  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
  /* Tokenizer implementations will typically add additional fields */
};

#endif /* _FTS3_TOKENIZER_H_ */

Added ext/fts3/fts3_tokenizer1.c.













































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** Implementation of the "simple" full-text-search tokenizer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS3 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS3 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)


#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "fts3_tokenizer.h"

typedef struct simple_tokenizer {
  sqlite3_tokenizer base;
  char delim[128];             /* flag ASCII delimiters */
} simple_tokenizer;

typedef struct simple_tokenizer_cursor {
  sqlite3_tokenizer_cursor base;
  const char *pInput;          /* input we are tokenizing */
  int nBytes;                  /* size of the input */
  int iOffset;                 /* current position in pInput */
  int iToken;                  /* index of next token to be returned */
  char *pToken;                /* storage for current token */
  int nTokenAllocated;         /* space allocated to zToken buffer */
} simple_tokenizer_cursor;


/* Forward declaration */
static const sqlite3_tokenizer_module simpleTokenizerModule;

static int simpleDelim(simple_tokenizer *t, unsigned char c){
  return c<0x80 && t->delim[c];
}

/*
** Create a new tokenizer instance.
*/
static int simpleCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  simple_tokenizer *t;

  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  if( t==NULL ) return SQLITE_NOMEM;
  memset(t, 0, sizeof(*t));

  /* TODO(shess) Delimiters need to remain the same from run to run,
  ** else we need to reindex.  One solution would be a meta-table to
  ** track such information in the database, then we'd only want this
  ** information on the initial create.
  */
  if( argc>1 ){
    int i, n = strlen(argv[1]);
    for(i=0; i<n; i++){
      unsigned char ch = argv[1][i];
      /* We explicitly don't support UTF-8 delimiters for now. */
      if( ch>=0x80 ){
        sqlite3_free(t);
        return SQLITE_ERROR;
      }
      t->delim[ch] = 1;
    }
  } else {
    /* Mark non-alphanumeric ASCII characters as delimiters */
    int i;
    for(i=1; i<0x80; i++){
      t->delim[i] = !isalnum(i);
    }
  }

  *ppTokenizer = &t->base;
  return SQLITE_OK;
}

/*
** Destroy a tokenizer
*/
static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  sqlite3_free(pTokenizer);
  return SQLITE_OK;
}

/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is pInput[0..nBytes-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int simpleOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *pInput, int nBytes,        /* String to be tokenized */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  simple_tokenizer_cursor *c;

  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  if( c==NULL ) return SQLITE_NOMEM;

  c->pInput = pInput;
  if( pInput==0 ){
    c->nBytes = 0;
  }else if( nBytes<0 ){
    c->nBytes = (int)strlen(pInput);
  }else{
    c->nBytes = nBytes;
  }
  c->iOffset = 0;                 /* start tokenizing at the beginning */
  c->iToken = 0;
  c->pToken = NULL;               /* no space allocated, yet. */
  c->nTokenAllocated = 0;

  *ppCursor = &c->base;
  return SQLITE_OK;
}

/*
** Close a tokenization cursor previously opened by a call to
** simpleOpen() above.
*/
static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  sqlite3_free(c->pToken);
  sqlite3_free(c);
  return SQLITE_OK;
}

/*
** Extract the next token from a tokenization cursor.  The cursor must
** have been opened by a prior call to simpleOpen().
*/
static int simpleNext(
  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
  const char **ppToken,               /* OUT: *ppToken is the token text */
  int *pnBytes,                       /* OUT: Number of bytes in token */
  int *piStartOffset,                 /* OUT: Starting offset of token */
  int *piEndOffset,                   /* OUT: Ending offset of token */
  int *piPosition                     /* OUT: Position integer of token */
){
  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  unsigned char *p = (unsigned char *)c->pInput;

  while( c->iOffset<c->nBytes ){
    int iStartOffset;

    /* Scan past delimiter characters */
    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
      c->iOffset++;
    }

    /* Count non-delimiter characters. */
    iStartOffset = c->iOffset;
    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
      c->iOffset++;
    }

    if( c->iOffset>iStartOffset ){
      int i, n = c->iOffset-iStartOffset;
      if( n>c->nTokenAllocated ){
        c->nTokenAllocated = n+20;
        c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
        if( c->pToken==NULL ) return SQLITE_NOMEM;
      }
      for(i=0; i<n; i++){
        /* TODO(shess) This needs expansion to handle UTF-8
        ** case-insensitivity.
        */
        unsigned char ch = p[iStartOffset+i];
        c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
      }
      *ppToken = c->pToken;
      *pnBytes = n;
      *piStartOffset = iStartOffset;
      *piEndOffset = c->iOffset;
      *piPosition = c->iToken++;

      return SQLITE_OK;
    }
  }
  return SQLITE_DONE;
}

/*
** The set of routines that implement the simple tokenizer
*/
static const sqlite3_tokenizer_module simpleTokenizerModule = {
  0,
  simpleCreate,
  simpleDestroy,
  simpleOpen,
  simpleClose,
  simpleNext,
};

/*
** Allocate a new simple tokenizer.  Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts3SimpleTokenizerModule(
  sqlite3_tokenizer_module const**ppModule
){
  *ppModule = &simpleTokenizerModule;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

Added ext/fts3/mkfts3amal.tcl.







































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/tclsh
#
# This script builds a single C code file holding all of FTS3 code.
# The name of the output file is fts3amal.c.  To build this file,
# first do:
#
#      make target_source
#
# The make target above moves all of the source code files into
# a subdirectory named "tsrc".  (This script expects to find the files
# there and will not work if they are not found.)
#
# After the "tsrc" directory has been created and populated, run
# this script:
#
#      tclsh mkfts3amal.tcl
#
# The amalgamated FTS3 code will be written into fts3amal.c
#

# Open the output file and write a header comment at the beginning
# of the file.
#
set out [open fts3amal.c w]
set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1]
puts $out [subst \
{/******************************************************************************
** This file is an amalgamation of separate C source files from the SQLite
** Full Text Search extension 2 (fts3).  By combining all the individual C 
** code  files into this single large file, the entire code can be compiled 
** as a one translation unit.  This allows many compilers to do optimizations
** that would not be possible if the files were compiled separately.  It also
** makes the code easier to import into other projects.
**
** This amalgamation was generated on $today.
*/}]

# These are the header files used by FTS3.  The first time any of these 
# files are seen in a #include statement in the C code, include the complete
# text of the file in-line.  The file only needs to be included once.
#
foreach hdr {
   fts3.h
   fts3_hash.h
   fts3_tokenizer.h
   sqlite3.h
   sqlite3ext.h
} {
  set available_hdr($hdr) 1
}

# 78 stars used for comment formatting.
set s78 \
{*****************************************************************************}

# Insert a comment into the code
#
proc section_comment {text} {
  global out s78
  set n [string length $text]
  set nstar [expr {60 - $n}]
  set stars [string range $s78 0 $nstar]
  puts $out "/************** $text $stars/"
}

# Read the source file named $filename and write it into the
# sqlite3.c output file.  If any #include statements are seen,
# process them approprately.
#
proc copy_file {filename} {
  global seen_hdr available_hdr out
  set tail [file tail $filename]
  section_comment "Begin file $tail"
  set in [open $filename r]
  while {![eof $in]} {
    set line [gets $in]
    if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} {
      if {[info exists available_hdr($hdr)]} {
        if {$available_hdr($hdr)} {
          section_comment "Include $hdr in the middle of $tail"
          copy_file tsrc/$hdr
          section_comment "Continuing where we left off in $tail"
        }
      } elseif {![info exists seen_hdr($hdr)]} {
        set seen_hdr($hdr) 1
        puts $out $line
      }
    } elseif {[regexp {^#ifdef __cplusplus} $line]} {
      puts $out "#if 0"
    } elseif {[regexp {^#line} $line]} {
      # Skip #line directives.
    } else {
      puts $out $line
    }
  }
  close $in
  section_comment "End of $tail"
}


# Process the source files.  Process files containing commonly
# used subroutines first in order to help the compiler find
# inlining opportunities.
#
foreach file {
   fts3.c
   fts3_hash.c
   fts3_porter.c
   fts3_tokenizer.c
   fts3_tokenizer1.c
} {
  copy_file tsrc/$file
}

close $out

Added ext/icu/README.txt.





















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

This directory contains source code for the SQLite "ICU" extension, an
integration of the "International Components for Unicode" library with
SQLite. Documentation follows.

    1. Features
    
        1.1  SQL Scalars upper() and lower()
        1.2  Unicode Aware LIKE Operator
        1.3  ICU Collation Sequences
        1.4  SQL REGEXP Operator
    
    2. Compilation and Usage
    
    3. Bugs, Problems and Security Issues
    
        3.1  The "case_sensitive_like" Pragma
        3.2  The SQLITE_MAX_LIKE_PATTERN_LENGTH Macro
        3.3  Collation Sequence Security Issue


1. FEATURES

  1.1  SQL Scalars upper() and lower()

    SQLite's built-in implementations of these two functions only 
    provide case mapping for the 26 letters used in the English
    language. The ICU based functions provided by this extension
    provide case mapping, where defined, for the full range of 
    unicode characters.

    ICU provides two types of case mapping, "general" case mapping and
    "language specific". Refer to ICU documentation for the differences
    between the two. Specifically:

       http://www.icu-project.org/userguide/caseMappings.html
       http://www.icu-project.org/userguide/posix.html#case_mappings

    To utilise "general" case mapping, the upper() or lower() scalar 
    functions are invoked with one argument:

        upper('ABC') -> 'abc'
        lower('abc') -> 'ABC'

    To access ICU "language specific" case mapping, upper() or lower()
    should be invoked with two arguments. The second argument is the name
    of the locale to use. Passing an empty string ("") or SQL NULL value
    as the second argument is the same as invoking the 1 argument version
    of upper() or lower():

        lower('I', 'en_us') -> 'i'
        lower('I', 'tr_tr') -> 'ı' (small dotless i)

  1.2  Unicode Aware LIKE Operator

    Similarly to the upper() and lower() functions, the built-in SQLite LIKE
    operator understands case equivalence for the 26 letters of the English
    language alphabet. The implementation of LIKE included in this
    extension uses the ICU function u_foldCase() to provide case
    independent comparisons for the full range of unicode characters.  

    The U_FOLD_CASE_DEFAULT flag is passed to u_foldCase(), meaning the
    dotless 'I' character used in the Turkish language is considered
    to be in the same equivalence class as the dotted 'I' character
    used by many languages (including English).

  1.3  ICU Collation Sequences

    A special SQL scalar function, icu_load_collation() is provided that 
    may be used to register ICU collation sequences with SQLite. It
    is always called with exactly two arguments, the ICU locale 
    identifying the collation sequence to ICU, and the name of the
    SQLite collation sequence to create. For example, to create an
    SQLite collation sequence named "turkish" using Turkish language
    sorting rules, the SQL statement:

        SELECT icu_load_collation('tr_TR', 'turkish');

    Or, for Australian English:

        SELECT icu_load_collation('en_AU', 'australian');

    The identifiers "turkish" and "australian" may then be used
    as collation sequence identifiers in SQL statements:

        CREATE TABLE aust_turkish_penpals(
          australian_penpal_name TEXT COLLATE australian,
          turkish_penpal_name    TEXT COLLATE turkish
        );
  
  1.4 SQL REGEXP Operator

    This extension provides an implementation of the SQL binary
    comparision operator "REGEXP", based on the regular expression functions
    provided by the ICU library. The syntax of the operator is as described
    in SQLite documentation:

        <string> REGEXP <re-pattern>

    This extension uses the ICU defaults for regular expression matching
    behaviour. Specifically, this means that:

        * Matching is case-sensitive,
        * Regular expression comments are not allowed within patterns, and
        * The '^' and '$' characters match the beginning and end of the
          <string> argument, not the beginning and end of lines within
          the <string> argument.

    Even more specifically, the value passed to the "flags" parameter
    of ICU C function uregex_open() is 0.


2  COMPILATION AND USAGE

  The easiest way to compile and use the ICU extension is to build
  and use it as a dynamically loadable SQLite extension. To do this
  using gcc on *nix:

    gcc -shared icu.c `icu-config --ldflags` -o libSqliteIcu.so

  You may need to add "-I" flags so that gcc can find sqlite3ext.h
  and sqlite3.h. The resulting shared lib, libSqliteIcu.so, may be
  loaded into sqlite in the same way as any other dynamically loadable
  extension.


3 BUGS, PROBLEMS AND SECURITY ISSUES

  3.1 The "case_sensitive_like" Pragma

    This extension does not work well with the "case_sensitive_like"
    pragma. If this pragma is used before the ICU extension is loaded,
    then the pragma has no effect. If the pragma is used after the ICU
    extension is loaded, then SQLite ignores the ICU implementation and
    always uses the built-in LIKE operator.

    The ICU extension LIKE operator is always case insensitive.

  3.2 The SQLITE_MAX_LIKE_PATTERN_LENGTH Macro

    Passing very long patterns to the built-in SQLite LIKE operator can
    cause a stack overflow. To curb this problem, SQLite defines the
    SQLITE_MAX_LIKE_PATTERN_LENGTH macro as the maximum length of a
    pattern in bytes (irrespective of encoding). The default value is
    defined in internal header file "limits.h".
    
    The ICU extension LIKE implementation suffers from the same 
    problem and uses the same solution. However, since the ICU extension
    code does not include the SQLite file "limits.h", modifying
    the default value therein does not affect the ICU extension.
    The default value of SQLITE_MAX_LIKE_PATTERN_LENGTH used by
    the ICU extension LIKE operator is 50000, defined in source 
    file "icu.c".

  3.3 Collation Sequence Security Issue

    Internally, SQLite assumes that indices stored in database files
    are sorted according to the collation sequence indicated by the
    SQL schema. Changing the definition of a collation sequence after
    an index has been built is therefore equivalent to database
    corruption. The SQLite library is not very well tested under
    these conditions, and may contain potential buffer overruns
    or other programming errors that could be exploited by a malicious
    programmer.

    If the ICU extension is used in an environment where potentially
    malicious users may execute arbitrary SQL (i.e. gears), they
    should be prevented from invoking the icu_load_collation() function,
    possibly using the authorisation callback.

Added ext/icu/icu.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/*
** 2007 May 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
**
** This file implements an integration between the ICU library 
** ("International Components for Unicode", an open-source library 
** for handling unicode data) and SQLite. The integration uses 
** ICU to provide the following to SQLite:
**
**   * An implementation of the SQL regexp() function (and hence REGEXP
**     operator) using the ICU uregex_XX() APIs.
**
**   * Implementations of the SQL scalar upper() and lower() functions
**     for case mapping.
**
**   * Integration of ICU and SQLite collation seqences.
**
**   * An implementation of the LIKE operator that uses ICU to 
**     provide case-independent matching.
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)

/* Include ICU headers */
#include <unicode/utypes.h>
#include <unicode/uregex.h>
#include <unicode/ustring.h>
#include <unicode/ucol.h>

#include <assert.h>

#ifndef SQLITE_CORE
  #include "sqlite3ext.h"
  SQLITE_EXTENSION_INIT1
#else
  #include "sqlite3.h"
#endif

/*
** Maximum length (in bytes) of the pattern in a LIKE or GLOB
** operator.
*/
#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
#endif

/*
** Version of sqlite3_free() that is always a function, never a macro.
*/
static void xFree(void *p){
  sqlite3_free(p);
}

/*
** Compare two UTF-8 strings for equality where the first string is
** a "LIKE" expression. Return true (1) if they are the same and 
** false (0) if they are different.
*/
static int icuLikeCompare(
  const uint8_t *zPattern,   /* LIKE pattern */
  const uint8_t *zString,    /* The UTF-8 string to compare against */
  const UChar32 uEsc         /* The escape character */
){
  static const int MATCH_ONE = (UChar32)'_';
  static const int MATCH_ALL = (UChar32)'%';

  int iPattern = 0;       /* Current byte index in zPattern */
  int iString = 0;        /* Current byte index in zString */

  int prevEscape = 0;     /* True if the previous character was uEsc */

  while( zPattern[iPattern]!=0 ){

    /* Read (and consume) the next character from the input pattern. */
    UChar32 uPattern;
    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
    assert(uPattern!=0);

    /* There are now 4 possibilities:
    **
    **     1. uPattern is an unescaped match-all character "%",
    **     2. uPattern is an unescaped match-one character "_",
    **     3. uPattern is an unescaped escape character, or
    **     4. uPattern is to be handled as an ordinary character
    */
    if( !prevEscape && uPattern==MATCH_ALL ){
      /* Case 1. */
      uint8_t c;

      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
      ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
      ** test string.
      */
      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
        if( c==MATCH_ONE ){
          if( zString[iString]==0 ) return 0;
          U8_FWD_1_UNSAFE(zString, iString);
        }
        iPattern++;
      }

      if( zPattern[iPattern]==0 ) return 1;

      while( zString[iString] ){
        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
          return 1;
        }
        U8_FWD_1_UNSAFE(zString, iString);
      }
      return 0;

    }else if( !prevEscape && uPattern==MATCH_ONE ){
      /* Case 2. */
      if( zString[iString]==0 ) return 0;
      U8_FWD_1_UNSAFE(zString, iString);

    }else if( !prevEscape && uPattern==uEsc){
      /* Case 3. */
      prevEscape = 1;

    }else{
      /* Case 4. */
      UChar32 uString;
      U8_NEXT_UNSAFE(zString, iString, uString);
      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
      if( uString!=uPattern ){
        return 0;
      }
      prevEscape = 0;
    }
  }

  return zString[iString]==0;
}

/*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A LIKE B
**
** is implemented as like(B, A). If there is an escape character E, 
**
**       A LIKE B ESCAPE E
**
** is mapped to like(B, A, E).
*/
static void icuLikeFunc(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  const unsigned char *zA = sqlite3_value_text(argv[0]);
  const unsigned char *zB = sqlite3_value_text(argv[1]);
  UChar32 uEsc = 0;

  /* Limit the length of the LIKE or GLOB pattern to avoid problems
  ** of deep recursion and N*N behavior in patternCompare().
  */
  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
    return;
  }


  if( argc==3 ){
    /* The escape character string must consist of a single UTF-8 character.
    ** Otherwise, return an error.
    */
    int nE= sqlite3_value_bytes(argv[2]);
    const unsigned char *zE = sqlite3_value_text(argv[2]);
    int i = 0;
    if( zE==0 ) return;
    U8_NEXT(zE, i, nE, uEsc);
    if( i!=nE){
      sqlite3_result_error(context, 
          "ESCAPE expression must be a single character", -1);
      return;
    }
  }

  if( zA && zB ){
    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  }
}

/*
** This function is called when an ICU function called from within
** the implementation of an SQL scalar function returns an error.
**
** The scalar function context passed as the first argument is 
** loaded with an error message based on the following two args.
*/
static void icuFunctionError(
  sqlite3_context *pCtx,       /* SQLite scalar function context */
  const char *zName,           /* Name of ICU function that failed */
  UErrorCode e                 /* Error code returned by ICU function */
){
  char zBuf[128];
  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  zBuf[127] = '\0';
  sqlite3_result_error(pCtx, zBuf, -1);
}

/*
** Function to delete compiled regexp objects. Registered as
** a destructor function with sqlite3_set_auxdata().
*/
static void icuRegexpDelete(void *p){
  URegularExpression *pExpr = (URegularExpression *)p;
  uregex_close(pExpr);
}

/*
** Implementation of SQLite REGEXP operator. This scalar function takes
** two arguments. The first is a regular expression pattern to compile
** the second is a string to match against that pattern. If either 
** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
** is 1 if the string matches the pattern, or 0 otherwise.
**
** SQLite maps the regexp() function to the regexp() operator such
** that the following two are equivalent:
**
**     zString REGEXP zPattern
**     regexp(zPattern, zString)
**
** Uses the following ICU regexp APIs:
**
**     uregex_open()
**     uregex_matches()
**     uregex_close()
*/
static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  UErrorCode status = U_ZERO_ERROR;
  URegularExpression *pExpr;
  UBool res;
  const UChar *zString = sqlite3_value_text16(apArg[1]);

  /* If the left hand side of the regexp operator is NULL, 
  ** then the result is also NULL. 
  */
  if( !zString ){
    return;
  }

  pExpr = sqlite3_get_auxdata(p, 0);
  if( !pExpr ){
    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
    if( !zPattern ){
      return;
    }
    pExpr = uregex_open(zPattern, -1, 0, 0, &status);

    if( U_SUCCESS(status) ){
      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
    }else{
      assert(!pExpr);
      icuFunctionError(p, "uregex_open", status);
      return;
    }
  }

  /* Configure the text that the regular expression operates on. */
  uregex_setText(pExpr, zString, -1, &status);
  if( !U_SUCCESS(status) ){
    icuFunctionError(p, "uregex_setText", status);
    return;
  }

  /* Attempt the match */
  res = uregex_matches(pExpr, 0, &status);
  if( !U_SUCCESS(status) ){
    icuFunctionError(p, "uregex_matches", status);
    return;
  }

  /* Set the text that the regular expression operates on to a NULL
  ** pointer. This is not really necessary, but it is tidier than 
  ** leaving the regular expression object configured with an invalid
  ** pointer after this function returns.
  */
  uregex_setText(pExpr, 0, 0, &status);

  /* Return 1 or 0. */
  sqlite3_result_int(p, res ? 1 : 0);
}

/*
** Implementations of scalar functions for case mapping - upper() and 
** lower(). Function upper() converts its input to upper-case (ABC).
** Function lower() converts to lower-case (abc).
**
** ICU provides two types of case mapping, "general" case mapping and
** "language specific". Refer to ICU documentation for the differences
** between the two.
**
** To utilise "general" case mapping, the upper() or lower() scalar 
** functions are invoked with one argument:
**
**     upper('ABC') -> 'abc'
**     lower('abc') -> 'ABC'
**
** To access ICU "language specific" case mapping, upper() or lower()
** should be invoked with two arguments. The second argument is the name
** of the locale to use. Passing an empty string ("") or SQL NULL value
** as the second argument is the same as invoking the 1 argument version
** of upper() or lower().
**
**     lower('I', 'en_us') -> 'i'
**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
**
** http://www.icu-project.org/userguide/posix.html#case_mappings
*/
static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  const UChar *zInput;
  UChar *zOutput;
  int nInput;
  int nOutput;

  UErrorCode status = U_ZERO_ERROR;
  const char *zLocale = 0;

  assert(nArg==1 || nArg==2);
  if( nArg==2 ){
    zLocale = (const char *)sqlite3_value_text(apArg[1]);
  }

  zInput = sqlite3_value_text16(apArg[0]);
  if( !zInput ){
    return;
  }
  nInput = sqlite3_value_bytes16(apArg[0]);

  nOutput = nInput * 2 + 2;
  zOutput = sqlite3_malloc(nOutput);
  if( !zOutput ){
    return;
  }

  if( sqlite3_user_data(p) ){
    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  }else{
    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  }

  if( !U_SUCCESS(status) ){
    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
    return;
  }

  sqlite3_result_text16(p, zOutput, -1, xFree);
}

/*
** Collation sequence destructor function. The pCtx argument points to
** a UCollator structure previously allocated using ucol_open().
*/
static void icuCollationDel(void *pCtx){
  UCollator *p = (UCollator *)pCtx;
  ucol_close(p);
}

/*
** Collation sequence comparison function. The pCtx argument points to
** a UCollator structure previously allocated using ucol_open().
*/
static int icuCollationColl(
  void *pCtx,
  int nLeft,
  const void *zLeft,
  int nRight,
  const void *zRight
){
  UCollationResult res;
  UCollator *p = (UCollator *)pCtx;
  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  switch( res ){
    case UCOL_LESS:    return -1;
    case UCOL_GREATER: return +1;
    case UCOL_EQUAL:   return 0;
  }
  assert(!"Unexpected return value from ucol_strcoll()");
  return 0;
}

/*
** Implementation of the scalar function icu_load_collation().
**
** This scalar function is used to add ICU collation based collation 
** types to an SQLite database connection. It is intended to be called
** as follows:
**
**     SELECT icu_load_collation(<locale>, <collation-name>);
**
** Where <locale> is a string containing an ICU locale identifier (i.e.
** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
** collation sequence to create.
*/
static void icuLoadCollation(
  sqlite3_context *p, 
  int nArg, 
  sqlite3_value **apArg
){
  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  UErrorCode status = U_ZERO_ERROR;
  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
  UCollator *pUCollator;    /* ICU library collation object */
  int rc;                   /* Return code from sqlite3_create_collation_x() */

  assert(nArg==2);
  zLocale = (const char *)sqlite3_value_text(apArg[0]);
  zName = (const char *)sqlite3_value_text(apArg[1]);

  if( !zLocale || !zName ){
    return;
  }

  pUCollator = ucol_open(zLocale, &status);
  if( !U_SUCCESS(status) ){
    icuFunctionError(p, "ucol_open", status);
    return;
  }
  assert(p);

  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
      icuCollationColl, icuCollationDel
  );
  if( rc!=SQLITE_OK ){
    ucol_close(pUCollator);
    sqlite3_result_error(p, "Error registering collation function", -1);
  }
}

/*
** Register the ICU extension functions with database db.
*/
int sqlite3IcuInit(sqlite3 *db){
  struct IcuScalar {
    const char *zName;                        /* Function name */
    int nArg;                                 /* Number of arguments */
    int enc;                                  /* Optimal text encoding */
    void *pContext;                           /* sqlite3_user_data() context */
    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  } scalars[] = {
    {"regexp",-1, SQLITE_ANY,          0, icuRegexpFunc},

    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},

    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},

    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},

    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  };

  int rc = SQLITE_OK;
  int i;

  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
    struct IcuScalar *p = &scalars[i];
    rc = sqlite3_create_function(
        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
    );
  }

  return rc;
}

#if !SQLITE_CORE
int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi)
  return sqlite3IcuInit(db);
}
#endif

#endif

Added ext/icu/sqliteicu.h.























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
** 2008 May 26
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file is used by programs that want to link against the
** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
*/
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

int sqlite3IcuInit(sqlite3 *db);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */

Added ext/rtree/README.

















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

This directory contains an SQLite extension that implements a virtual 
table type that allows users to create, query and manipulate r-tree[1] 
data structures inside of SQLite databases. Users create, populate 
and query r-tree structures using ordinary SQL statements.

    1.  SQL Interface

        1.1  Table Creation
        1.2  Data Manipulation
        1.3  Data Querying
        1.4  Introspection and Analysis

    2.  Compilation and Deployment

    3.  References


1. SQL INTERFACE

  1.1 Table Creation.

    All r-tree virtual tables have an odd number of columns between
    3 and 11. Unlike regular SQLite tables, r-tree tables are strongly 
    typed. 

    The leftmost column is always the pimary key and contains 64-bit 
    integer values. Each subsequent column contains a 32-bit real
    value. For each pair of real values, the first (leftmost) must be 
    less than or equal to the second. R-tree tables may be 
    constructed using the following syntax:

      CREATE VIRTUAL TABLE <name> USING rtree(<column-names>)

    For example:

      CREATE VIRTUAL TABLE boxes USING rtree(boxno, xmin, xmax, ymin, ymax);
      INSERT INTO boxes VALUES(1, 1.0, 3.0, 2.0, 4.0);

    Constructing a virtual r-tree table <name> creates the following three
    real tables in the database to store the data structure:

      <name>_node
      <name>_rowid
      <name>_parent

    Dropping or modifying the contents of these tables directly will
    corrupt the r-tree structure. To delete an r-tree from a database,
    use a regular DROP TABLE statement:

      DROP TABLE <name>;

    Dropping the main r-tree table automatically drops the automatically
    created tables. 

  1.2 Data Manipulation (INSERT, UPDATE, DELETE).

    The usual INSERT, UPDATE or DELETE syntax is used to manipulate data
    stored in an r-tree table. Please note the following:

      * Inserting a NULL value into the primary key column has the
        same effect as inserting a NULL into an INTEGER PRIMARY KEY
        column of a regular table. The system automatically assigns
        an unused integer key value to the new record. Usually, this
        is one greater than the largest primary key value currently
        present in the table.

      * Attempting to insert a duplicate primary key value fails with
        an SQLITE_CONSTRAINT error.

      * Attempting to insert or modify a record such that the value
        stored in the (N*2)th column is greater than that stored in
        the (N*2+1)th column fails with an SQLITE_CONSTRAINT error.

      * When a record is inserted, values are always converted to 
        the required type (64-bit integer or 32-bit real) as if they
        were part of an SQL CAST expression. Non-numeric strings are
        converted to zero.

  1.3 Queries.

    R-tree tables may be queried using all of the same SQL syntax supported
    by regular tables. However, some query patterns are more efficient
    than others.

    R-trees support fast lookup by primary key value (O(logN), like 
    regular tables).

    Any combination of equality and range (<, <=, >, >=) constraints
    on spatial data columns may be used to optimize other queries. This
    is the key advantage to using r-tree tables instead of creating 
    indices on regular tables.

  1.4 Introspection and Analysis.

    TODO: Describe rtreenode() and rtreedepth() functions.


2. COMPILATION AND USAGE

  The easiest way to compile and use the RTREE extension is to build
  and use it as a dynamically loadable SQLite extension. To do this
  using gcc on *nix:

    gcc -shared rtree.c -o libSqliteRtree.so

  You may need to add "-I" flags so that gcc can find sqlite3ext.h
  and sqlite3.h. The resulting shared lib, libSqliteRtree.so, may be
  loaded into sqlite in the same way as any other dynamicly loadable
  extension.


3. REFERENCES

  [1]  Atonin Guttman, "R-trees - A Dynamic Index Structure For Spatial 
       Searching", University of California Berkeley, 1984.

  [2]  Norbert Beckmann, Hans-Peter Kriegel, Ralf Schneider, Bernhard Seeger,
       "The R*-tree: An Efficient and Robust Access Method for Points and
       Rectangles", Universitaet Bremen, 1990.

Added ext/rtree/rtree.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code for implementations of the r-tree and r*-tree
** algorithms packaged as an SQLite virtual table module.
**
** $Id: rtree.c,v 1.14 2009/08/06 18:36:47 danielk1977 Exp $
*/

#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)

/*
** This file contains an implementation of a couple of different variants
** of the r-tree algorithm. See the README file for further details. The 
** same data-structure is used for all, but the algorithms for insert and
** delete operations vary. The variants used are selected at compile time 
** by defining the following symbols:
*/

/* Either, both or none of the following may be set to activate 
** r*tree variant algorithms.
*/
#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
#define VARIANT_RSTARTREE_REINSERT      1

/* 
** Exactly one of the following must be set to 1.
*/
#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
#define VARIANT_RSTARTREE_SPLIT         1

#define VARIANT_GUTTMAN_SPLIT \
        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)

#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  #define PickNext QuadraticPickNext
  #define PickSeeds QuadraticPickSeeds
  #define AssignCells splitNodeGuttman
#endif
#if VARIANT_GUTTMAN_LINEAR_SPLIT
  #define PickNext LinearPickNext
  #define PickSeeds LinearPickSeeds
  #define AssignCells splitNodeGuttman
#endif
#if VARIANT_RSTARTREE_SPLIT
  #define AssignCells splitNodeStartree
#endif


#ifndef SQLITE_CORE
  #include "sqlite3ext.h"
  SQLITE_EXTENSION_INIT1
#else
  #include "sqlite3.h"
#endif

#include <string.h>
#include <assert.h>

#ifndef SQLITE_AMALGAMATION
typedef sqlite3_int64 i64;
typedef unsigned char u8;
typedef unsigned int u32;
#endif

typedef struct Rtree Rtree;
typedef struct RtreeCursor RtreeCursor;
typedef struct RtreeNode RtreeNode;
typedef struct RtreeCell RtreeCell;
typedef struct RtreeConstraint RtreeConstraint;
typedef union RtreeCoord RtreeCoord;

/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
#define RTREE_MAX_DIMENSIONS 5

/* Size of hash table Rtree.aHash. This hash table is not expected to
** ever contain very many entries, so a fixed number of buckets is 
** used.
*/
#define HASHSIZE 128

/* 
** An rtree virtual-table object.
*/
struct Rtree {
  sqlite3_vtab base;
  sqlite3 *db;                /* Host database connection */
  int iNodeSize;              /* Size in bytes of each node in the node table */
  int nDim;                   /* Number of dimensions */
  int nBytesPerCell;          /* Bytes consumed per cell */
  int iDepth;                 /* Current depth of the r-tree structure */
  char *zDb;                  /* Name of database containing r-tree table */
  char *zName;                /* Name of r-tree table */ 
  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
  int nBusy;                  /* Current number of users of this structure */

  /* List of nodes removed during a CondenseTree operation. List is
  ** linked together via the pointer normally used for hash chains -
  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  */
  RtreeNode *pDeleted;
  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */

  /* Statements to read/write/delete a record from xxx_node */
  sqlite3_stmt *pReadNode;
  sqlite3_stmt *pWriteNode;
  sqlite3_stmt *pDeleteNode;

  /* Statements to read/write/delete a record from xxx_rowid */
  sqlite3_stmt *pReadRowid;
  sqlite3_stmt *pWriteRowid;
  sqlite3_stmt *pDeleteRowid;

  /* Statements to read/write/delete a record from xxx_parent */
  sqlite3_stmt *pReadParent;
  sqlite3_stmt *pWriteParent;
  sqlite3_stmt *pDeleteParent;

  int eCoordType;
};

/* Possible values for eCoordType: */
#define RTREE_COORD_REAL32 0
#define RTREE_COORD_INT32  1

/*
** The minimum number of cells allowed for a node is a third of the 
** maximum. In Gutman's notation:
**
**     m = M/3
**
** If an R*-tree "Reinsert" operation is required, the same number of
** cells are removed from the overfull node and reinserted into the tree.
*/
#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
#define RTREE_MAXCELLS 51

/* 
** An rtree cursor object.
*/
struct RtreeCursor {
  sqlite3_vtab_cursor base;
  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
  int iCell;                        /* Index of current cell in pNode */
  int iStrategy;                    /* Copy of idxNum search parameter */
  int nConstraint;                  /* Number of entries in aConstraint */
  RtreeConstraint *aConstraint;     /* Search constraints. */
};

union RtreeCoord {
  float f;
  int i;
};

/*
** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
** formatted as a double. This macro assumes that local variable pRtree points
** to the Rtree structure associated with the RtreeCoord.
*/
#define DCOORD(coord) (                           \
  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
    ((double)coord.f) :                           \
    ((double)coord.i)                             \
)

/*
** A search constraint.
*/
struct RtreeConstraint {
  int iCoord;                       /* Index of constrained coordinate */
  int op;                           /* Constraining operation */
  double rValue;                    /* Constraint value. */
};

/* Possible values for RtreeConstraint.op */
#define RTREE_EQ 0x41
#define RTREE_LE 0x42
#define RTREE_LT 0x43
#define RTREE_GE 0x44
#define RTREE_GT 0x45

/* 
** An rtree structure node.
**
** Data format (RtreeNode.zData):
**
**   1. If the node is the root node (node 1), then the first 2 bytes
**      of the node contain the tree depth as a big-endian integer.
**      For non-root nodes, the first 2 bytes are left unused.
**
**   2. The next 2 bytes contain the number of entries currently 
**      stored in the node.
**
**   3. The remainder of the node contains the node entries. Each entry
**      consists of a single 8-byte integer followed by an even number
**      of 4-byte coordinates. For leaf nodes the integer is the rowid
**      of a record. For internal nodes it is the node number of a
**      child page.
*/
struct RtreeNode {
  RtreeNode *pParent;               /* Parent node */
  i64 iNode;
  int nRef;
  int isDirty;
  u8 *zData;
  RtreeNode *pNext;                 /* Next node in this hash chain */
};
#define NCELL(pNode) readInt16(&(pNode)->zData[2])

/* 
** Structure to store a deserialized rtree record.
*/
struct RtreeCell {
  i64 iRowid;
  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
};

#ifndef MAX
# define MAX(x,y) ((x) < (y) ? (y) : (x))
#endif
#ifndef MIN
# define MIN(x,y) ((x) > (y) ? (y) : (x))
#endif

/*
** Functions to deserialize a 16 bit integer, 32 bit real number and
** 64 bit integer. The deserialized value is returned.
*/
static int readInt16(u8 *p){
  return (p[0]<<8) + p[1];
}
static void readCoord(u8 *p, RtreeCoord *pCoord){
  u32 i = (
    (((u32)p[0]) << 24) + 
    (((u32)p[1]) << 16) + 
    (((u32)p[2]) <<  8) + 
    (((u32)p[3]) <<  0)
  );
  *(u32 *)pCoord = i;
}
static i64 readInt64(u8 *p){
  return (
    (((i64)p[0]) << 56) + 
    (((i64)p[1]) << 48) + 
    (((i64)p[2]) << 40) + 
    (((i64)p[3]) << 32) + 
    (((i64)p[4]) << 24) + 
    (((i64)p[5]) << 16) + 
    (((i64)p[6]) <<  8) + 
    (((i64)p[7]) <<  0)
  );
}

/*
** Functions to serialize a 16 bit integer, 32 bit real number and
** 64 bit integer. The value returned is the number of bytes written
** to the argument buffer (always 2, 4 and 8 respectively).
*/
static int writeInt16(u8 *p, int i){
  p[0] = (i>> 8)&0xFF;
  p[1] = (i>> 0)&0xFF;
  return 2;
}
static int writeCoord(u8 *p, RtreeCoord *pCoord){
  u32 i;
  assert( sizeof(RtreeCoord)==4 );
  assert( sizeof(u32)==4 );
  i = *(u32 *)pCoord;
  p[0] = (i>>24)&0xFF;
  p[1] = (i>>16)&0xFF;
  p[2] = (i>> 8)&0xFF;
  p[3] = (i>> 0)&0xFF;
  return 4;
}
static int writeInt64(u8 *p, i64 i){
  p[0] = (i>>56)&0xFF;
  p[1] = (i>>48)&0xFF;
  p[2] = (i>>40)&0xFF;
  p[3] = (i>>32)&0xFF;
  p[4] = (i>>24)&0xFF;
  p[5] = (i>>16)&0xFF;
  p[6] = (i>> 8)&0xFF;
  p[7] = (i>> 0)&0xFF;
  return 8;
}

/*
** Increment the reference count of node p.
*/
static void nodeReference(RtreeNode *p){
  if( p ){
    p->nRef++;
  }
}

/*
** Clear the content of node p (set all bytes to 0x00).
*/
static void nodeZero(Rtree *pRtree, RtreeNode *p){
  if( p ){
    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
    p->isDirty = 1;
  }
}

/*
** Given a node number iNode, return the corresponding key to use
** in the Rtree.aHash table.
*/
static int nodeHash(i64 iNode){
  return (
    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  ) % HASHSIZE;
}

/*
** Search the node hash table for node iNode. If found, return a pointer
** to it. Otherwise, return 0.
*/
static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  RtreeNode *p;
  assert( iNode!=0 );
  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  return p;
}

/*
** Add node pNode to the node hash table.
*/
static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  if( pNode ){
    int iHash;
    assert( pNode->pNext==0 );
    iHash = nodeHash(pNode->iNode);
    pNode->pNext = pRtree->aHash[iHash];
    pRtree->aHash[iHash] = pNode;
  }
}

/*
** Remove node pNode from the node hash table.
*/
static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  RtreeNode **pp;
  if( pNode->iNode!=0 ){
    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
    *pp = pNode->pNext;
    pNode->pNext = 0;
  }
}

/*
** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
** indicating that node has not yet been assigned a node number. It is
** assigned a node number when nodeWrite() is called to write the
** node contents out to the database.
*/
static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
  RtreeNode *pNode;
  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  if( pNode ){
    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
    pNode->zData = (u8 *)&pNode[1];
    pNode->nRef = 1;
    pNode->pParent = pParent;
    pNode->isDirty = 1;
    nodeReference(pParent);
  }
  return pNode;
}

/*
** Obtain a reference to an r-tree node.
*/
static int
nodeAcquire(
  Rtree *pRtree,             /* R-tree structure */
  i64 iNode,                 /* Node number to load */
  RtreeNode *pParent,        /* Either the parent node or NULL */
  RtreeNode **ppNode         /* OUT: Acquired node */
){
  int rc;
  RtreeNode *pNode;

  /* Check if the requested node is already in the hash table. If so,
  ** increase its reference count and return it.
  */
  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
    if( pParent && !pNode->pParent ){
      nodeReference(pParent);
      pNode->pParent = pParent;
    }
    pNode->nRef++;
    *ppNode = pNode;
    return SQLITE_OK;
  }

  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  if( !pNode ){
    *ppNode = 0;
    return SQLITE_NOMEM;
  }
  pNode->pParent = pParent;
  pNode->zData = (u8 *)&pNode[1];
  pNode->nRef = 1;
  pNode->iNode = iNode;
  pNode->isDirty = 0;
  pNode->pNext = 0;

  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  rc = sqlite3_step(pRtree->pReadNode);
  if( rc==SQLITE_ROW ){
    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
    nodeReference(pParent);
  }else{
    sqlite3_free(pNode);
    pNode = 0;
  }

  *ppNode = pNode;
  rc = sqlite3_reset(pRtree->pReadNode);

  if( rc==SQLITE_OK && iNode==1 ){
    pRtree->iDepth = readInt16(pNode->zData);
  }

  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
  nodeHashInsert(pRtree, pNode);

  return rc;
}

/*
** Overwrite cell iCell of node pNode with the contents of pCell.
*/
static void nodeOverwriteCell(
  Rtree *pRtree, 
  RtreeNode *pNode,  
  RtreeCell *pCell, 
  int iCell
){
  int ii;
  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  p += writeInt64(p, pCell->iRowid);
  for(ii=0; ii<(pRtree->nDim*2); ii++){
    p += writeCoord(p, &pCell->aCoord[ii]);
  }
  pNode->isDirty = 1;
}

/*
** Remove cell the cell with index iCell from node pNode.
*/
static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  memmove(pDst, pSrc, nByte);
  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  pNode->isDirty = 1;
}

/*
** Insert the contents of cell pCell into node pNode. If the insert
** is successful, return SQLITE_OK.
**
** If there is not enough free space in pNode, return SQLITE_FULL.
*/
static int
nodeInsertCell(
  Rtree *pRtree, 
  RtreeNode *pNode, 
  RtreeCell *pCell 
){
  int nCell;                    /* Current number of cells in pNode */
  int nMaxCell;                 /* Maximum number of cells for pNode */

  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  nCell = NCELL(pNode);

  assert(nCell<=nMaxCell);

  if( nCell<nMaxCell ){
    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
    writeInt16(&pNode->zData[2], nCell+1);
    pNode->isDirty = 1;
  }

  return (nCell==nMaxCell);
}

/*
** If the node is dirty, write it out to the database.
*/
static int
nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  int rc = SQLITE_OK;
  if( pNode->isDirty ){
    sqlite3_stmt *p = pRtree->pWriteNode;
    if( pNode->iNode ){
      sqlite3_bind_int64(p, 1, pNode->iNode);
    }else{
      sqlite3_bind_null(p, 1);
    }
    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
    sqlite3_step(p);
    pNode->isDirty = 0;
    rc = sqlite3_reset(p);
    if( pNode->iNode==0 && rc==SQLITE_OK ){
      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
      nodeHashInsert(pRtree, pNode);
    }
  }
  return rc;
}

/*
** Release a reference to a node. If the node is dirty and the reference
** count drops to zero, the node data is written to the database.
*/
static int
nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  int rc = SQLITE_OK;
  if( pNode ){
    assert( pNode->nRef>0 );
    pNode->nRef--;
    if( pNode->nRef==0 ){
      if( pNode->iNode==1 ){
        pRtree->iDepth = -1;
      }
      if( pNode->pParent ){
        rc = nodeRelease(pRtree, pNode->pParent);
      }
      if( rc==SQLITE_OK ){
        rc = nodeWrite(pRtree, pNode);
      }
      nodeHashDelete(pRtree, pNode);
      sqlite3_free(pNode);
    }
  }
  return rc;
}

/*
** Return the 64-bit integer value associated with cell iCell of
** node pNode. If pNode is a leaf node, this is a rowid. If it is
** an internal node, then the 64-bit integer is a child page number.
*/
static i64 nodeGetRowid(
  Rtree *pRtree, 
  RtreeNode *pNode, 
  int iCell
){
  assert( iCell<NCELL(pNode) );
  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
}

/*
** Return coordinate iCoord from cell iCell in node pNode.
*/
static void nodeGetCoord(
  Rtree *pRtree, 
  RtreeNode *pNode, 
  int iCell,
  int iCoord,
  RtreeCoord *pCoord           /* Space to write result to */
){
  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
}

/*
** Deserialize cell iCell of node pNode. Populate the structure pointed
** to by pCell with the results.
*/
static void nodeGetCell(
  Rtree *pRtree, 
  RtreeNode *pNode, 
  int iCell,
  RtreeCell *pCell
){
  int ii;
  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  for(ii=0; ii<pRtree->nDim*2; ii++){
    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  }
}


/* Forward declaration for the function that does the work of
** the virtual table module xCreate() and xConnect() methods.
*/
static int rtreeInit(
  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
);

/* 
** Rtree virtual table module xCreate method.
*/
static int rtreeCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
}

/* 
** Rtree virtual table module xConnect method.
*/
static int rtreeConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
}

/*
** Increment the r-tree reference count.
*/
static void rtreeReference(Rtree *pRtree){
  pRtree->nBusy++;
}

/*
** Decrement the r-tree reference count. When the reference count reaches
** zero the structure is deleted.
*/
static void rtreeRelease(Rtree *pRtree){
  pRtree->nBusy--;
  if( pRtree->nBusy==0 ){
    sqlite3_finalize(pRtree->pReadNode);
    sqlite3_finalize(pRtree->pWriteNode);
    sqlite3_finalize(pRtree->pDeleteNode);
    sqlite3_finalize(pRtree->pReadRowid);
    sqlite3_finalize(pRtree->pWriteRowid);
    sqlite3_finalize(pRtree->pDeleteRowid);
    sqlite3_finalize(pRtree->pReadParent);
    sqlite3_finalize(pRtree->pWriteParent);
    sqlite3_finalize(pRtree->pDeleteParent);
    sqlite3_free(pRtree);
  }
}

/* 
** Rtree virtual table module xDisconnect method.
*/
static int rtreeDisconnect(sqlite3_vtab *pVtab){
  rtreeRelease((Rtree *)pVtab);
  return SQLITE_OK;
}

/* 
** Rtree virtual table module xDestroy method.
*/
static int rtreeDestroy(sqlite3_vtab *pVtab){
  Rtree *pRtree = (Rtree *)pVtab;
  int rc;
  char *zCreate = sqlite3_mprintf(
    "DROP TABLE '%q'.'%q_node';"
    "DROP TABLE '%q'.'%q_rowid';"
    "DROP TABLE '%q'.'%q_parent';",
    pRtree->zDb, pRtree->zName, 
    pRtree->zDb, pRtree->zName,
    pRtree->zDb, pRtree->zName
  );
  if( !zCreate ){
    rc = SQLITE_NOMEM;
  }else{
    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
    sqlite3_free(zCreate);
  }
  if( rc==SQLITE_OK ){
    rtreeRelease(pRtree);
  }

  return rc;
}

/* 
** Rtree virtual table module xOpen method.
*/
static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  int rc = SQLITE_NOMEM;
  RtreeCursor *pCsr;

  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  if( pCsr ){
    memset(pCsr, 0, sizeof(RtreeCursor));
    pCsr->base.pVtab = pVTab;
    rc = SQLITE_OK;
  }
  *ppCursor = (sqlite3_vtab_cursor *)pCsr;

  return rc;
}

/* 
** Rtree virtual table module xClose method.
*/
static int rtreeClose(sqlite3_vtab_cursor *cur){
  Rtree *pRtree = (Rtree *)(cur->pVtab);
  int rc;
  RtreeCursor *pCsr = (RtreeCursor *)cur;
  sqlite3_free(pCsr->aConstraint);
  rc = nodeRelease(pRtree, pCsr->pNode);
  sqlite3_free(pCsr);
  return rc;
}

/*
** Rtree virtual table module xEof method.
**
** Return non-zero if the cursor does not currently point to a valid 
** record (i.e if the scan has finished), or zero otherwise.
*/
static int rtreeEof(sqlite3_vtab_cursor *cur){
  RtreeCursor *pCsr = (RtreeCursor *)cur;
  return (pCsr->pNode==0);
}

/* 
** Cursor pCursor currently points to a cell in a non-leaf page.
** Return true if the sub-tree headed by the cell is filtered
** (excluded) by the constraints in the pCursor->aConstraint[] 
** array, or false otherwise.
*/
static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
  RtreeCell cell;
  int ii;
  int bRes = 0;

  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
    RtreeConstraint *p = &pCursor->aConstraint[ii];
    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);

    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
        || p->op==RTREE_GT || p->op==RTREE_EQ
    );

    switch( p->op ){
      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
      case RTREE_EQ: 
        bRes = (p->rValue>cell_max || p->rValue<cell_min);
        break;
    }
  }

  return bRes;
}

/* 
** Return true if the cell that cursor pCursor currently points to
** would be filtered (excluded) by the constraints in the 
** pCursor->aConstraint[] array, or false otherwise.
**
** This function assumes that the cell is part of a leaf node.
*/
static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
  RtreeCell cell;
  int ii;

  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  for(ii=0; ii<pCursor->nConstraint; ii++){
    RtreeConstraint *p = &pCursor->aConstraint[ii];
    double coord = DCOORD(cell.aCoord[p->iCoord]);
    int res;
    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
        || p->op==RTREE_GT || p->op==RTREE_EQ
    );
    switch( p->op ){
      case RTREE_LE: res = (coord<=p->rValue); break;
      case RTREE_LT: res = (coord<p->rValue);  break;
      case RTREE_GE: res = (coord>=p->rValue); break;
      case RTREE_GT: res = (coord>p->rValue);  break;
      case RTREE_EQ: res = (coord==p->rValue); break;
    }

    if( !res ) return 1;
  }

  return 0;
}

/*
** Cursor pCursor currently points at a node that heads a sub-tree of
** height iHeight (if iHeight==0, then the node is a leaf). Descend
** to point to the left-most cell of the sub-tree that matches the 
** configured constraints.
*/
static int descendToCell(
  Rtree *pRtree, 
  RtreeCursor *pCursor, 
  int iHeight,
  int *pEof                 /* OUT: Set to true if cannot descend */
){
  int isEof;
  int rc;
  int ii;
  RtreeNode *pChild;
  sqlite3_int64 iRowid;

  RtreeNode *pSavedNode = pCursor->pNode;
  int iSavedCell = pCursor->iCell;

  assert( iHeight>=0 );

  if( iHeight==0 ){
    isEof = testRtreeEntry(pRtree, pCursor);
  }else{
    isEof = testRtreeCell(pRtree, pCursor);
  }
  if( isEof || iHeight==0 ){
    *pEof = isEof;
    return SQLITE_OK;
  }

  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  nodeRelease(pRtree, pCursor->pNode);
  pCursor->pNode = pChild;
  isEof = 1;
  for(ii=0; isEof && ii<NCELL(pChild); ii++){
    pCursor->iCell = ii;
    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
    if( rc!=SQLITE_OK ){
      return rc;
    }
  }

  if( isEof ){
    assert( pCursor->pNode==pChild );
    nodeReference(pSavedNode);
    nodeRelease(pRtree, pChild);
    pCursor->pNode = pSavedNode;
    pCursor->iCell = iSavedCell;
  }

  *pEof = isEof;
  return SQLITE_OK;
}

/*
** One of the cells in node pNode is guaranteed to have a 64-bit 
** integer value equal to iRowid. Return the index of this cell.
*/
static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
  int ii;
  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
    assert( ii<(NCELL(pNode)-1) );
  }
  return ii;
}

/*
** Return the index of the cell containing a pointer to node pNode
** in its parent. If pNode is the root node, return -1.
*/
static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
  RtreeNode *pParent = pNode->pParent;
  if( pParent ){
    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
  }
  return -1;
}

/* 
** Rtree virtual table module xNext method.
*/
static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  int rc = SQLITE_OK;

  if( pCsr->iStrategy==1 ){
    /* This "scan" is a direct lookup by rowid. There is no next entry. */
    nodeRelease(pRtree, pCsr->pNode);
    pCsr->pNode = 0;
  }

  else if( pCsr->pNode ){
    /* Move to the next entry that matches the configured constraints. */
    int iHeight = 0;
    while( pCsr->pNode ){
      RtreeNode *pNode = pCsr->pNode;
      int nCell = NCELL(pNode);
      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
        int isEof;
        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
        if( rc!=SQLITE_OK || !isEof ){
          return rc;
        }
      }
      pCsr->pNode = pNode->pParent;
      pCsr->iCell = nodeParentIndex(pRtree, pNode);
      nodeReference(pCsr->pNode);
      nodeRelease(pRtree, pNode);
      iHeight++;
    }
  }

  return rc;
}

/* 
** Rtree virtual table module xRowid method.
*/
static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;

  assert(pCsr->pNode);
  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);

  return SQLITE_OK;
}

/* 
** Rtree virtual table module xColumn method.
*/
static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  Rtree *pRtree = (Rtree *)cur->pVtab;
  RtreeCursor *pCsr = (RtreeCursor *)cur;

  if( i==0 ){
    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
    sqlite3_result_int64(ctx, iRowid);
  }else{
    RtreeCoord c;
    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
      sqlite3_result_double(ctx, c.f);
    }else{
      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
      sqlite3_result_int(ctx, c.i);
    }
  }

  return SQLITE_OK;
}

/* 
** Use nodeAcquire() to obtain the leaf node containing the record with 
** rowid iRowid. If successful, set *ppLeaf to point to the node and
** return SQLITE_OK. If there is no such record in the table, set
** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
** to zero and return an SQLite error code.
*/
static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  int rc;
  *ppLeaf = 0;
  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
    sqlite3_reset(pRtree->pReadRowid);
  }else{
    rc = sqlite3_reset(pRtree->pReadRowid);
  }
  return rc;
}


/* 
** Rtree virtual table module xFilter method.
*/
static int rtreeFilter(
  sqlite3_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite3_value **argv
){
  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;

  RtreeNode *pRoot = 0;
  int ii;
  int rc = SQLITE_OK;

  rtreeReference(pRtree);

  sqlite3_free(pCsr->aConstraint);
  pCsr->aConstraint = 0;
  pCsr->iStrategy = idxNum;

  if( idxNum==1 ){
    /* Special case - lookup by rowid. */
    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
    i64 iRowid = sqlite3_value_int64(argv[0]);
    rc = findLeafNode(pRtree, iRowid, &pLeaf);
    pCsr->pNode = pLeaf; 
    if( pLeaf && rc==SQLITE_OK ){
      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
    }
  }else{
    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
    ** with the configured constraints. 
    */
    if( argc>0 ){
      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
      pCsr->nConstraint = argc;
      if( !pCsr->aConstraint ){
        rc = SQLITE_NOMEM;
      }else{
        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
        for(ii=0; ii<argc; ii++){
          RtreeConstraint *p = &pCsr->aConstraint[ii];
          p->op = idxStr[ii*2];
          p->iCoord = idxStr[ii*2+1]-'a';
          p->rValue = sqlite3_value_double(argv[ii]);
        }
      }
    }
  
    if( rc==SQLITE_OK ){
      pCsr->pNode = 0;
      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
    }
    if( rc==SQLITE_OK ){
      int isEof = 1;
      int nCell = NCELL(pRoot);
      pCsr->pNode = pRoot;
      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
        assert( pCsr->pNode==pRoot );
        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
        if( !isEof ){
          break;
        }
      }
      if( rc==SQLITE_OK && isEof ){
        assert( pCsr->pNode==pRoot );
        nodeRelease(pRtree, pRoot);
        pCsr->pNode = 0;
      }
      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
    }
  }

  rtreeRelease(pRtree);
  return rc;
}

/*
** Rtree virtual table module xBestIndex method. There are three
** table scan strategies to choose from (in order from most to 
** least desirable):
**
**   idxNum     idxStr        Strategy
**   ------------------------------------------------
**     1        Unused        Direct lookup by rowid.
**     2        See below     R-tree query.
**     3        Unused        Full table scan.
**   ------------------------------------------------
**
** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
** 2 is used, idxStr is formatted to contain 2 bytes for each 
** constraint used. The first two bytes of idxStr correspond to 
** the constraint in sqlite3_index_info.aConstraintUsage[] with
** (argvIndex==1) etc.
**
** The first of each pair of bytes in idxStr identifies the constraint
** operator as follows:
**
**   Operator    Byte Value
**   ----------------------
**      =        0x41 ('A')
**     <=        0x42 ('B')
**      <        0x43 ('C')
**     >=        0x44 ('D')
**      >        0x45 ('E')
**   ----------------------
**
** The second of each pair of bytes identifies the coordinate column
** to which the constraint applies. The leftmost coordinate column
** is 'a', the second from the left 'b' etc.
*/
static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  int rc = SQLITE_OK;
  int ii, cCol;

  int iIdx = 0;
  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  memset(zIdxStr, 0, sizeof(zIdxStr));

  assert( pIdxInfo->idxStr==0 );
  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];

    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
      /* We have an equality constraint on the rowid. Use strategy 1. */
      int jj;
      for(jj=0; jj<ii; jj++){
        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
        pIdxInfo->aConstraintUsage[jj].omit = 0;
      }
      pIdxInfo->idxNum = 1;
      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
      pIdxInfo->aConstraintUsage[jj].omit = 1;

      /* This strategy involves a two rowid lookups on an B-Tree structures
      ** and then a linear search of an R-Tree node. This should be 
      ** considered almost as quick as a direct rowid lookup (for which 
      ** sqlite uses an internal cost of 0.0).
      */ 
      pIdxInfo->estimatedCost = 10.0;
      return SQLITE_OK;
    }

    if( p->usable && p->iColumn>0 ){
      u8 op = 0;
      switch( p->op ){
        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
      }
      if( op ){
        /* Make sure this particular constraint has not been used before.
        ** If it has been used before, ignore it.
        **
        ** A <= or < can be used if there is a prior >= or >.
        ** A >= or > can be used if there is a prior < or <=.
        ** A <= or < is disqualified if there is a prior <=, <, or ==.
        ** A >= or > is disqualified if there is a prior >=, >, or ==.
        ** A == is disqualifed if there is any prior constraint.
        */
        int j, opmsk;
        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
        assert( compatible[RTREE_EQ & 7]==0 );
        assert( compatible[RTREE_LT & 7]==1 );
        assert( compatible[RTREE_LE & 7]==1 );
        assert( compatible[RTREE_GT & 7]==2 );
        assert( compatible[RTREE_GE & 7]==2 );
        cCol = p->iColumn - 1 + 'a';
        opmsk = compatible[op & 7];
        for(j=0; j<iIdx; j+=2){
          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
            op = 0;
            break;
          }
        }
      }
      if( op ){
        assert( iIdx<sizeof(zIdxStr)-1 );
        zIdxStr[iIdx++] = op;
        zIdxStr[iIdx++] = cCol;
        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
        pIdxInfo->aConstraintUsage[ii].omit = 1;
      }
    }
  }

  pIdxInfo->idxNum = 2;
  pIdxInfo->needToFreeIdxStr = 1;
  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
    return SQLITE_NOMEM;
  }
  assert( iIdx>=0 );
  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  return rc;
}

/*
** Return the N-dimensional volumn of the cell stored in *p.
*/
static float cellArea(Rtree *pRtree, RtreeCell *p){
  float area = 1.0;
  int ii;
  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  }
  return area;
}

/*
** Return the margin length of cell p. The margin length is the sum
** of the objects size in each dimension.
*/
static float cellMargin(Rtree *pRtree, RtreeCell *p){
  float margin = 0.0;
  int ii;
  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  }
  return margin;
}

/*
** Store the union of cells p1 and p2 in p1.
*/
static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  int ii;
  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
    }
  }else{
    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
    }
  }
}

/*
** Return true if the area covered by p2 is a subset of the area covered
** by p1. False otherwise.
*/
static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  int ii;
  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
    RtreeCoord *a1 = &p1->aCoord[ii];
    RtreeCoord *a2 = &p2->aCoord[ii];
    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
    ){
      return 0;
    }
  }
  return 1;
}

/*
** Return the amount cell p would grow by if it were unioned with pCell.
*/
static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  float area;
  RtreeCell cell;
  memcpy(&cell, p, sizeof(RtreeCell));
  area = cellArea(pRtree, &cell);
  cellUnion(pRtree, &cell, pCell);
  return (cellArea(pRtree, &cell)-area);
}

#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
static float cellOverlap(
  Rtree *pRtree, 
  RtreeCell *p, 
  RtreeCell *aCell, 
  int nCell, 
  int iExclude
){
  int ii;
  float overlap = 0.0;
  for(ii=0; ii<nCell; ii++){
    if( ii!=iExclude ){
      int jj;
      float o = 1.0;
      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
        double x1;
        double x2;

        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));

        if( x2<x1 ){
          o = 0.0;
          break;
        }else{
          o = o * (x2-x1);
        }
      }
      overlap += o;
    }
  }
  return overlap;
}
#endif

#if VARIANT_RSTARTREE_CHOOSESUBTREE
static float cellOverlapEnlargement(
  Rtree *pRtree, 
  RtreeCell *p, 
  RtreeCell *pInsert, 
  RtreeCell *aCell, 
  int nCell, 
  int iExclude
){
  float before;
  float after;
  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  cellUnion(pRtree, p, pInsert);
  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  return after-before;
}
#endif


/*
** This function implements the ChooseLeaf algorithm from Gutman[84].
** ChooseSubTree in r*tree terminology.
*/
static int ChooseLeaf(
  Rtree *pRtree,               /* Rtree table */
  RtreeCell *pCell,            /* Cell to insert into rtree */
  int iHeight,                 /* Height of sub-tree rooted at pCell */
  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
){
  int rc;
  int ii;
  RtreeNode *pNode;
  rc = nodeAcquire(pRtree, 1, 0, &pNode);

  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
    int iCell;
    sqlite3_int64 iBest;

    float fMinGrowth;
    float fMinArea;
    float fMinOverlap;

    int nCell = NCELL(pNode);
    RtreeCell cell;
    RtreeNode *pChild;

    RtreeCell *aCell = 0;

#if VARIANT_RSTARTREE_CHOOSESUBTREE
    if( ii==(pRtree->iDepth-1) ){
      int jj;
      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
      if( !aCell ){
        rc = SQLITE_NOMEM;
        nodeRelease(pRtree, pNode);
        pNode = 0;
        continue;
      }
      for(jj=0; jj<nCell; jj++){
        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
      }
    }
#endif

    /* Select the child node which will be enlarged the least if pCell
    ** is inserted into it. Resolve ties by choosing the entry with
    ** the smallest area.
    */
    for(iCell=0; iCell<nCell; iCell++){
      float growth;
      float area;
      float overlap = 0.0;
      nodeGetCell(pRtree, pNode, iCell, &cell);
      growth = cellGrowth(pRtree, &cell, pCell);
      area = cellArea(pRtree, &cell);
#if VARIANT_RSTARTREE_CHOOSESUBTREE
      if( ii==(pRtree->iDepth-1) ){
        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
      }
#endif
      if( (iCell==0) 
       || (overlap<fMinOverlap) 
       || (overlap==fMinOverlap && growth<fMinGrowth)
       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
      ){
        fMinOverlap = overlap;
        fMinGrowth = growth;
        fMinArea = area;
        iBest = cell.iRowid;
      }
    }

    sqlite3_free(aCell);
    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
    nodeRelease(pRtree, pNode);
    pNode = pChild;
  }

  *ppLeaf = pNode;
  return rc;
}

/*
** A cell with the same content as pCell has just been inserted into
** the node pNode. This function updates the bounding box cells in
** all ancestor elements.
*/
static void AdjustTree(
  Rtree *pRtree,                    /* Rtree table */
  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
  RtreeCell *pCell                  /* This cell was just inserted */
){
  RtreeNode *p = pNode;
  while( p->pParent ){
    RtreeCell cell;
    RtreeNode *pParent = p->pParent;
    int iCell = nodeParentIndex(pRtree, p);

    nodeGetCell(pRtree, pParent, iCell, &cell);
    if( !cellContains(pRtree, &cell, pCell) ){
      cellUnion(pRtree, &cell, pCell);
      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
    }
 
    p = pParent;
  }
}

/*
** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
*/
static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  sqlite3_step(pRtree->pWriteRowid);
  return sqlite3_reset(pRtree->pWriteRowid);
}

/*
** Write mapping (iNode->iPar) to the <rtree>_parent table.
*/
static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  sqlite3_step(pRtree->pWriteParent);
  return sqlite3_reset(pRtree->pWriteParent);
}

static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);

#if VARIANT_GUTTMAN_LINEAR_SPLIT
/*
** Implementation of the linear variant of the PickNext() function from
** Guttman[84].
*/
static RtreeCell *LinearPickNext(
  Rtree *pRtree,
  RtreeCell *aCell, 
  int nCell, 
  RtreeCell *pLeftBox, 
  RtreeCell *pRightBox,
  int *aiUsed
){
  int ii;
  for(ii=0; aiUsed[ii]; ii++);
  aiUsed[ii] = 1;
  return &aCell[ii];
}

/*
** Implementation of the linear variant of the PickSeeds() function from
** Guttman[84].
*/
static void LinearPickSeeds(
  Rtree *pRtree,
  RtreeCell *aCell, 
  int nCell, 
  int *piLeftSeed, 
  int *piRightSeed
){
  int i;
  int iLeftSeed = 0;
  int iRightSeed = 1;
  float maxNormalInnerWidth = 0.0;

  /* Pick two "seed" cells from the array of cells. The algorithm used
  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
  ** indices of the two seed cells in the array are stored in local
  ** variables iLeftSeek and iRightSeed.
  */
  for(i=0; i<pRtree->nDim; i++){
    float x1 = DCOORD(aCell[0].aCoord[i*2]);
    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
    float x3 = x1;
    float x4 = x2;
    int jj;

    int iCellLeft = 0;
    int iCellRight = 0;

    for(jj=1; jj<nCell; jj++){
      float left = DCOORD(aCell[jj].aCoord[i*2]);
      float right = DCOORD(aCell[jj].aCoord[i*2+1]);

      if( left<x1 ) x1 = left;
      if( right>x4 ) x4 = right;
      if( left>x3 ){
        x3 = left;
        iCellRight = jj;
      }
      if( right<x2 ){
        x2 = right;
        iCellLeft = jj;
      }
    }

    if( x4!=x1 ){
      float normalwidth = (x3 - x2) / (x4 - x1);
      if( normalwidth>maxNormalInnerWidth ){
        iLeftSeed = iCellLeft;
        iRightSeed = iCellRight;
      }
    }
  }

  *piLeftSeed = iLeftSeed;
  *piRightSeed = iRightSeed;
}
#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */

#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
/*
** Implementation of the quadratic variant of the PickNext() function from
** Guttman[84].
*/
static RtreeCell *QuadraticPickNext(
  Rtree *pRtree,
  RtreeCell *aCell, 
  int nCell, 
  RtreeCell *pLeftBox, 
  RtreeCell *pRightBox,
  int *aiUsed
){
  #define FABS(a) ((a)<0.0?-1.0*(a):(a))

  int iSelect = -1;
  float fDiff;
  int ii;
  for(ii=0; ii<nCell; ii++){
    if( aiUsed[ii]==0 ){
      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
      float diff = FABS(right-left);
      if( iSelect<0 || diff>fDiff ){
        fDiff = diff;
        iSelect = ii;
      }
    }
  }
  aiUsed[iSelect] = 1;
  return &aCell[iSelect];
}

/*
** Implementation of the quadratic variant of the PickSeeds() function from
** Guttman[84].
*/
static void QuadraticPickSeeds(
  Rtree *pRtree,
  RtreeCell *aCell, 
  int nCell, 
  int *piLeftSeed, 
  int *piRightSeed
){
  int ii;
  int jj;

  int iLeftSeed = 0;
  int iRightSeed = 1;
  float fWaste = 0.0;

  for(ii=0; ii<nCell; ii++){
    for(jj=ii+1; jj<nCell; jj++){
      float right = cellArea(pRtree, &aCell[jj]);
      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
      float waste = growth - right;

      if( waste>fWaste ){
        iLeftSeed = ii;
        iRightSeed = jj;
        fWaste = waste;
      }
    }
  }

  *piLeftSeed = iLeftSeed;
  *piRightSeed = iRightSeed;
}
#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */

/*
** Arguments aIdx, aDistance and aSpare all point to arrays of size
** nIdx. The aIdx array contains the set of integers from 0 to 
** (nIdx-1) in no particular order. This function sorts the values
** in aIdx according to the indexed values in aDistance. For
** example, assuming the inputs:
**
**   aIdx      = { 0,   1,   2,   3 }
**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
**
** this function sets the aIdx array to contain:
**
**   aIdx      = { 0,   1,   2,   3 }
**
** The aSpare array is used as temporary working space by the
** sorting algorithm.
*/
static void SortByDistance(
  int *aIdx, 
  int nIdx, 
  float *aDistance, 
  int *aSpare
){
  if( nIdx>1 ){
    int iLeft = 0;
    int iRight = 0;

    int nLeft = nIdx/2;
    int nRight = nIdx-nLeft;
    int *aLeft = aIdx;
    int *aRight = &aIdx[nLeft];

    SortByDistance(aLeft, nLeft, aDistance, aSpare);
    SortByDistance(aRight, nRight, aDistance, aSpare);

    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
    aLeft = aSpare;

    while( iLeft<nLeft || iRight<nRight ){
      if( iLeft==nLeft ){
        aIdx[iLeft+iRight] = aRight[iRight];
        iRight++;
      }else if( iRight==nRight ){
        aIdx[iLeft+iRight] = aLeft[iLeft];
        iLeft++;
      }else{
        float fLeft = aDistance[aLeft[iLeft]];
        float fRight = aDistance[aRight[iRight]];
        if( fLeft<fRight ){
          aIdx[iLeft+iRight] = aLeft[iLeft];
          iLeft++;
        }else{
          aIdx[iLeft+iRight] = aRight[iRight];
          iRight++;
        }
      }
    }

#if 0
    /* Check that the sort worked */
    {
      int jj;
      for(jj=1; jj<nIdx; jj++){
        float left = aDistance[aIdx[jj-1]];
        float right = aDistance[aIdx[jj]];
        assert( left<=right );
      }
    }
#endif
  }
}

/*
** Arguments aIdx, aCell and aSpare all point to arrays of size
** nIdx. The aIdx array contains the set of integers from 0 to 
** (nIdx-1) in no particular order. This function sorts the values
** in aIdx according to dimension iDim of the cells in aCell. The
** minimum value of dimension iDim is considered first, the
** maximum used to break ties.
**
** The aSpare array is used as temporary working space by the
** sorting algorithm.
*/
static void SortByDimension(
  Rtree *pRtree,
  int *aIdx, 
  int nIdx, 
  int iDim, 
  RtreeCell *aCell, 
  int *aSpare
){
  if( nIdx>1 ){

    int iLeft = 0;
    int iRight = 0;

    int nLeft = nIdx/2;
    int nRight = nIdx-nLeft;
    int *aLeft = aIdx;
    int *aRight = &aIdx[nLeft];

    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);

    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
    aLeft = aSpare;
    while( iLeft<nLeft || iRight<nRight ){
      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
      if( (iLeft!=nLeft) && ((iRight==nRight)
       || (xleft1<xright1)
       || (xleft1==xright1 && xleft2<xright2)
      )){
        aIdx[iLeft+iRight] = aLeft[iLeft];
        iLeft++;
      }else{
        aIdx[iLeft+iRight] = aRight[iRight];
        iRight++;
      }
    }

#if 0
    /* Check that the sort worked */
    {
      int jj;
      for(jj=1; jj<nIdx; jj++){
        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
      }
    }
#endif
  }
}

#if VARIANT_RSTARTREE_SPLIT
/*
** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
*/
static int splitNodeStartree(
  Rtree *pRtree,
  RtreeCell *aCell,
  int nCell,
  RtreeNode *pLeft,
  RtreeNode *pRight,
  RtreeCell *pBboxLeft,
  RtreeCell *pBboxRight
){
  int **aaSorted;
  int *aSpare;
  int ii;

  int iBestDim;
  int iBestSplit;
  float fBestMargin;

  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));

  aaSorted = (int **)sqlite3_malloc(nByte);
  if( !aaSorted ){
    return SQLITE_NOMEM;
  }

  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  memset(aaSorted, 0, nByte);
  for(ii=0; ii<pRtree->nDim; ii++){
    int jj;
    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
    for(jj=0; jj<nCell; jj++){
      aaSorted[ii][jj] = jj;
    }
    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  }

  for(ii=0; ii<pRtree->nDim; ii++){
    float margin = 0.0;
    float fBestOverlap;
    float fBestArea;
    int iBestLeft;
    int nLeft;

    for(
      nLeft=RTREE_MINCELLS(pRtree); 
      nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
      nLeft++
    ){
      RtreeCell left;
      RtreeCell right;
      int kk;
      float overlap;
      float area;

      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
      for(kk=1; kk<(nCell-1); kk++){
        if( kk<nLeft ){
          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
        }else{
          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
        }
      }
      margin += cellMargin(pRtree, &left);
      margin += cellMargin(pRtree, &right);
      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
      if( (nLeft==RTREE_MINCELLS(pRtree))
       || (overlap<fBestOverlap)
       || (overlap==fBestOverlap && area<fBestArea)
      ){
        iBestLeft = nLeft;
        fBestOverlap = overlap;
        fBestArea = area;
      }
    }

    if( ii==0 || margin<fBestMargin ){
      iBestDim = ii;
      fBestMargin = margin;
      iBestSplit = iBestLeft;
    }
  }

  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  for(ii=0; ii<nCell; ii++){
    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
    nodeInsertCell(pRtree, pTarget, pCell);
    cellUnion(pRtree, pBbox, pCell);
  }

  sqlite3_free(aaSorted);
  return SQLITE_OK;
}
#endif

#if VARIANT_GUTTMAN_SPLIT
/*
** Implementation of the regular R-tree SplitNode from Guttman[1984].
*/
static int splitNodeGuttman(
  Rtree *pRtree,
  RtreeCell *aCell,
  int nCell,
  RtreeNode *pLeft,
  RtreeNode *pRight,
  RtreeCell *pBboxLeft,
  RtreeCell *pBboxRight
){
  int iLeftSeed = 0;
  int iRightSeed = 1;
  int *aiUsed;
  int i;

  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  if( !aiUsed ){
    return SQLITE_NOMEM;
  }
  memset(aiUsed, 0, sizeof(int)*nCell);

  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);

  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  aiUsed[iLeftSeed] = 1;
  aiUsed[iRightSeed] = 1;

  for(i=nCell-2; i>0; i--){
    RtreeCell *pNext;
    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
    float diff =  
      cellGrowth(pRtree, pBboxLeft, pNext) - 
      cellGrowth(pRtree, pBboxRight, pNext)
    ;
    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
    ){
      nodeInsertCell(pRtree, pRight, pNext);
      cellUnion(pRtree, pBboxRight, pNext);
    }else{
      nodeInsertCell(pRtree, pLeft, pNext);
      cellUnion(pRtree, pBboxLeft, pNext);
    }
  }

  sqlite3_free(aiUsed);
  return SQLITE_OK;
}
#endif

static int updateMapping(
  Rtree *pRtree, 
  i64 iRowid, 
  RtreeNode *pNode, 
  int iHeight
){
  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  if( iHeight>0 ){
    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
    if( pChild ){
      nodeRelease(pRtree, pChild->pParent);
      nodeReference(pNode);
      pChild->pParent = pNode;
    }
  }
  return xSetMapping(pRtree, iRowid, pNode->iNode);
}

static int SplitNode(
  Rtree *pRtree,
  RtreeNode *pNode,
  RtreeCell *pCell,
  int iHeight
){
  int i;
  int newCellIsRight = 0;

  int rc = SQLITE_OK;
  int nCell = NCELL(pNode);
  RtreeCell *aCell;
  int *aiUsed;

  RtreeNode *pLeft = 0;
  RtreeNode *pRight = 0;

  RtreeCell leftbbox;
  RtreeCell rightbbox;

  /* Allocate an array and populate it with a copy of pCell and 
  ** all cells from node pLeft. Then zero the original node.
  */
  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  if( !aCell ){
    rc = SQLITE_NOMEM;
    goto splitnode_out;
  }
  aiUsed = (int *)&aCell[nCell+1];
  memset(aiUsed, 0, sizeof(int)*(nCell+1));
  for(i=0; i<nCell; i++){
    nodeGetCell(pRtree, pNode, i, &aCell[i]);
  }
  nodeZero(pRtree, pNode);
  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  nCell++;

  if( pNode->iNode==1 ){
    pRight = nodeNew(pRtree, pNode, 1);
    pLeft = nodeNew(pRtree, pNode, 1);
    pRtree->iDepth++;
    pNode->isDirty = 1;
    writeInt16(pNode->zData, pRtree->iDepth);
  }else{
    pLeft = pNode;
    pRight = nodeNew(pRtree, pLeft->pParent, 1);
    nodeReference(pLeft);
  }

  if( !pLeft || !pRight ){
    rc = SQLITE_NOMEM;
    goto splitnode_out;
  }

  memset(pLeft->zData, 0, pRtree->iNodeSize);
  memset(pRight->zData, 0, pRtree->iNodeSize);

  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  if( rc!=SQLITE_OK ){
    goto splitnode_out;
  }

  /* Ensure both child nodes have node numbers assigned to them. */
  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  ){
    goto splitnode_out;
  }

  rightbbox.iRowid = pRight->iNode;
  leftbbox.iRowid = pLeft->iNode;

  if( pNode->iNode==1 ){
    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
    if( rc!=SQLITE_OK ){
      goto splitnode_out;
    }
  }else{
    RtreeNode *pParent = pLeft->pParent;
    int iCell = nodeParentIndex(pRtree, pLeft);
    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
    AdjustTree(pRtree, pParent, &leftbbox);
  }
  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
    goto splitnode_out;
  }

  for(i=0; i<NCELL(pRight); i++){
    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
    if( iRowid==pCell->iRowid ){
      newCellIsRight = 1;
    }
    if( rc!=SQLITE_OK ){
      goto splitnode_out;
    }
  }
  if( pNode->iNode==1 ){
    for(i=0; i<NCELL(pLeft); i++){
      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
      if( rc!=SQLITE_OK ){
        goto splitnode_out;
      }
    }
  }else if( newCellIsRight==0 ){
    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  }

  if( rc==SQLITE_OK ){
    rc = nodeRelease(pRtree, pRight);
    pRight = 0;
  }
  if( rc==SQLITE_OK ){
    rc = nodeRelease(pRtree, pLeft);
    pLeft = 0;
  }

splitnode_out:
  nodeRelease(pRtree, pRight);
  nodeRelease(pRtree, pLeft);
  sqlite3_free(aCell);
  return rc;
}

static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  int rc = SQLITE_OK;
  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
    }else{
      rc = SQLITE_ERROR;
    }
    sqlite3_reset(pRtree->pReadParent);
    if( rc==SQLITE_OK ){
      rc = fixLeafParent(pRtree, pLeaf->pParent);
    }
  }
  return rc;
}

static int deleteCell(Rtree *, RtreeNode *, int, int);

static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  int rc;
  RtreeNode *pParent;
  int iCell;

  assert( pNode->nRef==1 );

  /* Remove the entry in the parent cell. */
  iCell = nodeParentIndex(pRtree, pNode);
  pParent = pNode->pParent;
  pNode->pParent = 0;
  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
  ){
    return rc;
  }

  /* Remove the xxx_node entry. */
  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  sqlite3_step(pRtree->pDeleteNode);
  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
    return rc;
  }

  /* Remove the xxx_parent entry. */
  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  sqlite3_step(pRtree->pDeleteParent);
  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
    return rc;
  }
  
  /* Remove the node from the in-memory hash table and link it into
  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  */
  nodeHashDelete(pRtree, pNode);
  pNode->iNode = iHeight;
  pNode->pNext = pRtree->pDeleted;
  pNode->nRef++;
  pRtree->pDeleted = pNode;

  return SQLITE_OK;
}

static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  RtreeNode *pParent = pNode->pParent;
  if( pParent ){
    int ii; 
    int nCell = NCELL(pNode);
    RtreeCell box;                            /* Bounding box for pNode */
    nodeGetCell(pRtree, pNode, 0, &box);
    for(ii=1; ii<nCell; ii++){
      RtreeCell cell;
      nodeGetCell(pRtree, pNode, ii, &cell);
      cellUnion(pRtree, &box, &cell);
    }
    box.iRowid = pNode->iNode;
    ii = nodeParentIndex(pRtree, pNode);
    nodeOverwriteCell(pRtree, pParent, &box, ii);
    fixBoundingBox(pRtree, pParent);
  }
}

/*
** Delete the cell at index iCell of node pNode. After removing the
** cell, adjust the r-tree data structure if required.
*/
static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  int rc;

  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
    return rc;
  }

  /* Remove the cell from the node. This call just moves bytes around
  ** the in-memory node image, so it cannot fail.
  */
  nodeDeleteCell(pRtree, pNode, iCell);

  /* If the node is not the tree root and now has less than the minimum
  ** number of cells, remove it from the tree. Otherwise, update the
  ** cell in the parent node so that it tightly contains the updated
  ** node.
  */
  if( pNode->iNode!=1 ){
    RtreeNode *pParent = pNode->pParent;
    if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
    ){
      rc = removeNode(pRtree, pNode, iHeight);
    }else{
      fixBoundingBox(pRtree, pNode);
    }
  }

  return rc;
}

static int Reinsert(
  Rtree *pRtree, 
  RtreeNode *pNode, 
  RtreeCell *pCell, 
  int iHeight
){
  int *aOrder;
  int *aSpare;
  RtreeCell *aCell;
  float *aDistance;
  int nCell;
  float aCenterCoord[RTREE_MAX_DIMENSIONS];
  int iDim;
  int ii;
  int rc = SQLITE_OK;

  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);

  nCell = NCELL(pNode)+1;

  /* Allocate the buffers used by this operation. The allocation is
  ** relinquished before this function returns.
  */
  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
    sizeof(RtreeCell) +         /* aCell array */
    sizeof(int)       +         /* aOrder array */
    sizeof(int)       +         /* aSpare array */
    sizeof(float)               /* aDistance array */
  ));
  if( !aCell ){
    return SQLITE_NOMEM;
  }
  aOrder    = (int *)&aCell[nCell];
  aSpare    = (int *)&aOrder[nCell];
  aDistance = (float *)&aSpare[nCell];

  for(ii=0; ii<nCell; ii++){
    if( ii==(nCell-1) ){
      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
    }else{
      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
    }
    aOrder[ii] = ii;
    for(iDim=0; iDim<pRtree->nDim; iDim++){
      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
    }
  }
  for(iDim=0; iDim<pRtree->nDim; iDim++){
    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
  }

  for(ii=0; ii<nCell; ii++){
    aDistance[ii] = 0.0;
    for(iDim=0; iDim<pRtree->nDim; iDim++){
      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
          DCOORD(aCell[ii].aCoord[iDim*2]);
      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
    }
  }

  SortByDistance(aOrder, nCell, aDistance, aSpare);
  nodeZero(pRtree, pNode);

  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
    RtreeCell *p = &aCell[aOrder[ii]];
    nodeInsertCell(pRtree, pNode, p);
    if( p->iRowid==pCell->iRowid ){
      if( iHeight==0 ){
        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
      }else{
        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
      }
    }
  }
  if( rc==SQLITE_OK ){
    fixBoundingBox(pRtree, pNode);
  }
  for(; rc==SQLITE_OK && ii<nCell; ii++){
    /* Find a node to store this cell in. pNode->iNode currently contains
    ** the height of the sub-tree headed by the cell.
    */
    RtreeNode *pInsert;
    RtreeCell *p = &aCell[aOrder[ii]];
    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
    if( rc==SQLITE_OK ){
      int rc2;
      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
      rc2 = nodeRelease(pRtree, pInsert);
      if( rc==SQLITE_OK ){
        rc = rc2;
      }
    }
  }

  sqlite3_free(aCell);
  return rc;
}

/*
** Insert cell pCell into node pNode. Node pNode is the head of a 
** subtree iHeight high (leaf nodes have iHeight==0).
*/
static int rtreeInsertCell(
  Rtree *pRtree,
  RtreeNode *pNode,
  RtreeCell *pCell,
  int iHeight
){
  int rc = SQLITE_OK;
  if( iHeight>0 ){
    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
    if( pChild ){
      nodeRelease(pRtree, pChild->pParent);
      nodeReference(pNode);
      pChild->pParent = pNode;
    }
  }
  if( nodeInsertCell(pRtree, pNode, pCell) ){
#if VARIANT_RSTARTREE_REINSERT
    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
      rc = SplitNode(pRtree, pNode, pCell, iHeight);
    }else{
      pRtree->iReinsertHeight = iHeight;
      rc = Reinsert(pRtree, pNode, pCell, iHeight);
    }
#else
    rc = SplitNode(pRtree, pNode, pCell, iHeight);
#endif
  }else{
    AdjustTree(pRtree, pNode, pCell);
    if( iHeight==0 ){
      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
    }else{
      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
    }
  }
  return rc;
}

static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  int ii;
  int rc = SQLITE_OK;
  int nCell = NCELL(pNode);

  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
    RtreeNode *pInsert;
    RtreeCell cell;
    nodeGetCell(pRtree, pNode, ii, &cell);

    /* Find a node to store this cell in. pNode->iNode currently contains
    ** the height of the sub-tree headed by the cell.
    */
    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
    if( rc==SQLITE_OK ){
      int rc2;
      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
      rc2 = nodeRelease(pRtree, pInsert);
      if( rc==SQLITE_OK ){
        rc = rc2;
      }
    }
  }
  return rc;
}

/*
** Select a currently unused rowid for a new r-tree record.
*/
static int newRowid(Rtree *pRtree, i64 *piRowid){
  int rc;
  sqlite3_bind_null(pRtree->pWriteRowid, 1);
  sqlite3_bind_null(pRtree->pWriteRowid, 2);
  sqlite3_step(pRtree->pWriteRowid);
  rc = sqlite3_reset(pRtree->pWriteRowid);
  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  return rc;
}

#ifndef NDEBUG
static int hashIsEmpty(Rtree *pRtree){
  int ii;
  for(ii=0; ii<HASHSIZE; ii++){
    assert( !pRtree->aHash[ii] );
  }
  return 1;
}
#endif

/*
** The xUpdate method for rtree module virtual tables.
*/
static int rtreeUpdate(
  sqlite3_vtab *pVtab, 
  int nData, 
  sqlite3_value **azData, 
  sqlite_int64 *pRowid
){
  Rtree *pRtree = (Rtree *)pVtab;
  int rc = SQLITE_OK;

  rtreeReference(pRtree);

  assert(nData>=1);
  assert(hashIsEmpty(pRtree));

  /* If azData[0] is not an SQL NULL value, it is the rowid of a
  ** record to delete from the r-tree table. The following block does
  ** just that.
  */
  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
    i64 iDelete;                /* The rowid to delete */
    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
    int iCell;                  /* Index of iDelete cell in pLeaf */
    RtreeNode *pRoot;

    /* Obtain a reference to the root node to initialise Rtree.iDepth */
    rc = nodeAcquire(pRtree, 1, 0, &pRoot);

    /* Obtain a reference to the leaf node that contains the entry 
    ** about to be deleted. 
    */
    if( rc==SQLITE_OK ){
      iDelete = sqlite3_value_int64(azData[0]);
      rc = findLeafNode(pRtree, iDelete, &pLeaf);
    }

    /* Delete the cell in question from the leaf node. */
    if( rc==SQLITE_OK ){
      int rc2;
      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
      rc = deleteCell(pRtree, pLeaf, iCell, 0);
      rc2 = nodeRelease(pRtree, pLeaf);
      if( rc==SQLITE_OK ){
        rc = rc2;
      }
    }

    /* Delete the corresponding entry in the <rtree>_rowid table. */
    if( rc==SQLITE_OK ){
      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
      sqlite3_step(pRtree->pDeleteRowid);
      rc = sqlite3_reset(pRtree->pDeleteRowid);
    }

    /* Check if the root node now has exactly one child. If so, remove
    ** it, schedule the contents of the child for reinsertion and 
    ** reduce the tree height by one.
    **
    ** This is equivalent to copying the contents of the child into
    ** the root node (the operation that Gutman's paper says to perform 
    ** in this scenario).
    */
    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
        RtreeNode *pChild;
        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
        if( rc==SQLITE_OK ){
          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
        }
        if( rc==SQLITE_OK ){
          pRtree->iDepth--;
          writeInt16(pRoot->zData, pRtree->iDepth);
          pRoot->isDirty = 1;
        }
      }
    }

    /* Re-insert the contents of any underfull nodes removed from the tree. */
    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
      if( rc==SQLITE_OK ){
        rc = reinsertNodeContent(pRtree, pLeaf);
      }
      pRtree->pDeleted = pLeaf->pNext;
      sqlite3_free(pLeaf);
    }

    /* Release the reference to the root node. */
    if( rc==SQLITE_OK ){
      rc = nodeRelease(pRtree, pRoot);
    }else{
      nodeRelease(pRtree, pRoot);
    }
  }

  /* If the azData[] array contains more than one element, elements
  ** (azData[2]..azData[argc-1]) contain a new record to insert into
  ** the r-tree structure.
  */
  if( rc==SQLITE_OK && nData>1 ){
    /* Insert a new record into the r-tree */
    RtreeCell cell;
    int ii;
    RtreeNode *pLeaf;

    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
    assert( nData==(pRtree->nDim*2 + 3) );
    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
          rc = SQLITE_CONSTRAINT;
          goto constraint;
        }
      }
    }else{
      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
          rc = SQLITE_CONSTRAINT;
          goto constraint;
        }
      }
    }

    /* Figure out the rowid of the new row. */
    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
      rc = newRowid(pRtree, &cell.iRowid);
    }else{
      cell.iRowid = sqlite3_value_int64(azData[2]);
      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
        sqlite3_reset(pRtree->pReadRowid);
        rc = SQLITE_CONSTRAINT;
        goto constraint;
      }
      rc = sqlite3_reset(pRtree->pReadRowid);
    }

    if( rc==SQLITE_OK ){
      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
    }
    if( rc==SQLITE_OK ){
      int rc2;
      pRtree->iReinsertHeight = -1;
      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
      rc2 = nodeRelease(pRtree, pLeaf);
      if( rc==SQLITE_OK ){
        rc = rc2;
      }
    }
  }

constraint:
  rtreeRelease(pRtree);
  return rc;
}

/*
** The xRename method for rtree module virtual tables.
*/
static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  Rtree *pRtree = (Rtree *)pVtab;
  int rc = SQLITE_NOMEM;
  char *zSql = sqlite3_mprintf(
    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
    , pRtree->zDb, pRtree->zName, zNewName 
    , pRtree->zDb, pRtree->zName, zNewName 
    , pRtree->zDb, pRtree->zName, zNewName
  );
  if( zSql ){
    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  return rc;
}

static sqlite3_module rtreeModule = {
  0,                         /* iVersion */
  rtreeCreate,                /* xCreate - create a table */
  rtreeConnect,               /* xConnect - connect to an existing table */
  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
  rtreeDestroy,               /* xDestroy - Drop a table */
  rtreeOpen,                  /* xOpen - open a cursor */
  rtreeClose,                 /* xClose - close a cursor */
  rtreeFilter,                /* xFilter - configure scan constraints */
  rtreeNext,                  /* xNext - advance a cursor */
  rtreeEof,                   /* xEof */
  rtreeColumn,                /* xColumn - read data */
  rtreeRowid,                 /* xRowid - read data */
  rtreeUpdate,                /* xUpdate - write data */
  0,                          /* xBegin - begin transaction */
  0,                          /* xSync - sync transaction */
  0,                          /* xCommit - commit transaction */
  0,                          /* xRollback - rollback transaction */
  0,                          /* xFindFunction - function overloading */
  rtreeRename                 /* xRename - rename the table */
};

static int rtreeSqlInit(
  Rtree *pRtree, 
  sqlite3 *db, 
  const char *zDb, 
  const char *zPrefix, 
  int isCreate
){
  int rc = SQLITE_OK;

  #define N_STATEMENT 9
  static const char *azSql[N_STATEMENT] = {
    /* Read and write the xxx_node table */
    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",

    /* Read and write the xxx_rowid table */
    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",

    /* Read and write the xxx_parent table */
    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  };
  sqlite3_stmt **appStmt[N_STATEMENT];
  int i;

  pRtree->db = db;

  if( isCreate ){
    char *zCreate = sqlite3_mprintf(
"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
    );
    if( !zCreate ){
      return SQLITE_NOMEM;
    }
    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
    sqlite3_free(zCreate);
    if( rc!=SQLITE_OK ){
      return rc;
    }
  }

  appStmt[0] = &pRtree->pReadNode;
  appStmt[1] = &pRtree->pWriteNode;
  appStmt[2] = &pRtree->pDeleteNode;
  appStmt[3] = &pRtree->pReadRowid;
  appStmt[4] = &pRtree->pWriteRowid;
  appStmt[5] = &pRtree->pDeleteRowid;
  appStmt[6] = &pRtree->pReadParent;
  appStmt[7] = &pRtree->pWriteParent;
  appStmt[8] = &pRtree->pDeleteParent;

  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
    if( zSql ){
      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
    }else{
      rc = SQLITE_NOMEM;
    }
    sqlite3_free(zSql);
  }

  return rc;
}

/*
** This routine queries database handle db for the page-size used by
** database zDb. If successful, the page-size in bytes is written to
** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
** code is returned.
*/
static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
  int rc = SQLITE_NOMEM;
  char *zSql;
  sqlite3_stmt *pStmt = 0;

  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
  if( !zSql ){
    return SQLITE_NOMEM;
  }

  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  sqlite3_free(zSql);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  if( SQLITE_ROW==sqlite3_step(pStmt) ){
    *piPageSize = sqlite3_column_int(pStmt, 0);
  }
  return sqlite3_finalize(pStmt);
}

/* 
** This function is the implementation of both the xConnect and xCreate
** methods of the r-tree virtual table.
**
**   argv[0]   -> module name
**   argv[1]   -> database name
**   argv[2]   -> table name
**   argv[...] -> column names...
*/
static int rtreeInit(
  sqlite3 *db,                        /* Database connection */
  void *pAux,                         /* One of the RTREE_COORD_* constants */
  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
  char **pzErr,                       /* OUT: Error message, if any */
  int isCreate                        /* True for xCreate, false for xConnect */
){
  int rc = SQLITE_OK;
  int iPageSize = 0;
  Rtree *pRtree;
  int nDb;              /* Length of string argv[1] */
  int nName;            /* Length of string argv[2] */
  int eCoordType = (int)pAux;

  const char *aErrMsg[] = {
    0,                                                    /* 0 */
    "Wrong number of columns for an rtree table",         /* 1 */
    "Too few columns for an rtree table",                 /* 2 */
    "Too many columns for an rtree table"                 /* 3 */
  };

  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  if( aErrMsg[iErr] ){
    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
    return SQLITE_ERROR;
  }

  rc = getPageSize(db, argv[1], &iPageSize);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  /* Allocate the sqlite3_vtab structure */
  nDb = strlen(argv[1]);
  nName = strlen(argv[2]);
  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  if( !pRtree ){
    return SQLITE_NOMEM;
  }
  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  pRtree->nBusy = 1;
  pRtree->base.pModule = &rtreeModule;
  pRtree->zDb = (char *)&pRtree[1];
  pRtree->zName = &pRtree->zDb[nDb+1];
  pRtree->nDim = (argc-4)/2;
  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  pRtree->eCoordType = eCoordType;
  memcpy(pRtree->zDb, argv[1], nDb);
  memcpy(pRtree->zName, argv[2], nName);

  /* Figure out the node size to use. By default, use 64 bytes less than
  ** the database page-size. This ensures that each node is stored on
  ** a single database page.
  **
  ** If the databasd page-size is so large that more than RTREE_MAXCELLS
  ** entries would fit in a single node, use a smaller node-size.
  */
  pRtree->iNodeSize = iPageSize-64;
  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
    pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  }

  /* Create/Connect to the underlying relational database schema. If
  ** that is successful, call sqlite3_declare_vtab() to configure
  ** the r-tree table schema.
  */
  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  }else{
    char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
    char *zTmp;
    int ii;
    for(ii=4; zSql && ii<argc; ii++){
      zTmp = zSql;
      zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
      sqlite3_free(zTmp);
    }
    if( zSql ){
      zTmp = zSql;
      zSql = sqlite3_mprintf("%s);", zTmp);
      sqlite3_free(zTmp);
    }
    if( !zSql ){
      rc = SQLITE_NOMEM;
    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
    }
    sqlite3_free(zSql);
  }

  if( rc==SQLITE_OK ){
    *ppVtab = (sqlite3_vtab *)pRtree;
  }else{
    rtreeRelease(pRtree);
  }
  return rc;
}


/*
** Implementation of a scalar function that decodes r-tree nodes to
** human readable strings. This can be used for debugging and analysis.
**
** The scalar function takes two arguments, a blob of data containing
** an r-tree node, and the number of dimensions the r-tree indexes.
** For a two-dimensional r-tree structure called "rt", to deserialize
** all nodes, a statement like:
**
**   SELECT rtreenode(2, data) FROM rt_node;
**
** The human readable string takes the form of a Tcl list with one
** entry for each cell in the r-tree node. Each entry is itself a
** list, containing the 8-byte rowid/pageno followed by the 
** <num-dimension>*2 coordinates.
*/
static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  char *zText = 0;
  RtreeNode node;
  Rtree tree;
  int ii;

  memset(&node, 0, sizeof(RtreeNode));
  memset(&tree, 0, sizeof(Rtree));
  tree.nDim = sqlite3_value_int(apArg[0]);
  tree.nBytesPerCell = 8 + 8 * tree.nDim;
  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);

  for(ii=0; ii<NCELL(&node); ii++){
    char zCell[512];
    int nCell = 0;
    RtreeCell cell;
    int jj;

    nodeGetCell(&tree, &node, ii, &cell);
    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
    nCell = strlen(zCell);
    for(jj=0; jj<tree.nDim*2; jj++){
      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
      nCell = strlen(zCell);
    }

    if( zText ){
      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
      sqlite3_free(zText);
      zText = zTextNew;
    }else{
      zText = sqlite3_mprintf("{%s}", zCell);
    }
  }
  
  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
}

static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
   || sqlite3_value_bytes(apArg[0])<2
  ){
    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
  }else{
    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
    sqlite3_result_int(ctx, readInt16(zBlob));
  }
}

/*
** Register the r-tree module with database handle db. This creates the
** virtual table module "rtree" and the debugging/analysis scalar 
** function "rtreenode".
*/
int sqlite3RtreeInit(sqlite3 *db){
  int rc = SQLITE_OK;

  if( rc==SQLITE_OK ){
    int utf8 = SQLITE_UTF8;
    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  }
  if( rc==SQLITE_OK ){
    int utf8 = SQLITE_UTF8;
    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  }
  if( rc==SQLITE_OK ){
    void *c = (void *)RTREE_COORD_REAL32;
    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  }
  if( rc==SQLITE_OK ){
    void *c = (void *)RTREE_COORD_INT32;
    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  }

  return rc;
}

#if !SQLITE_CORE
int sqlite3_extension_init(
  sqlite3 *db,
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi)
  return sqlite3RtreeInit(db);
}
#endif

#endif

Added ext/rtree/rtree.h.





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
** 2008 May 26
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file is used by programs that want to link against the
** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
*/
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

int sqlite3RtreeInit(sqlite3 *db);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */

Added ext/rtree/rtree1.test.









































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# 2008 Feb 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing the r-tree extension.
#
# $Id: rtree1.test,v 1.7 2009/07/17 16:54:48 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
}
source [file join [file dirname [info script]] rtree_util.tcl]
source $testdir/tester.tcl

# Test plan:
#
#   rtree-1.*: Creating/destroying r-tree tables.
#   rtree-2.*: Test the implicit constraints - unique rowid and
#              (coord[N]<=coord[N+1]) for even values of N. Also
#              automatic assigning of rowid values.
#   rtree-3.*: Linear scans of r-tree data.
#   rtree-4.*: Test INSERT
#   rtree-5.*: Test DELETE
#   rtree-6.*: Test UPDATE
#   rtree-7.*: Test renaming an r-tree table.
#   rtree-8.*: Test constrained scans of r-tree data.
#

ifcapable !rtree {
  finish_test
  return
}

#----------------------------------------------------------------------------
# Test cases rtree-1.* test CREATE and DROP table statements.
#

# Test creating and dropping an rtree table.
#
do_test rtree-1.1.1 {
  execsql { CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2) }
} {}
do_test rtree-1.1.2 {
  execsql { SELECT name FROM sqlite_master ORDER BY name }
} {t1 t1_node t1_parent t1_rowid}
do_test rtree-1.1.3 {
  execsql { 
    DROP TABLE t1; 
    SELECT name FROM sqlite_master ORDER BY name;
  }
} {}

# Test creating and dropping an rtree table with an odd name in
# an attached database.
#
do_test rtree-1.2.1 {
  file delete -force test2.db
  execsql {
    ATTACH 'test2.db' AS aux;
    CREATE VIRTUAL TABLE aux.'a" "b' USING rtree(ii, x1, x2, y1, y2);
  }
} {}
do_test rtree-1.2.2 {
  execsql { SELECT name FROM sqlite_master ORDER BY name }
} {}
do_test rtree-1.2.3 {
  execsql { SELECT name FROM aux.sqlite_master ORDER BY name }
} {{a" "b} {a" "b_node} {a" "b_parent} {a" "b_rowid}}
do_test rtree-1.2.4 {
  execsql { 
    DROP TABLE aux.'a" "b'; 
    SELECT name FROM aux.sqlite_master ORDER BY name;
  }
} {}

# Test that the logic for checking the number of columns specified
# for an rtree table. Acceptable values are odd numbers between 3 and
# 11, inclusive.
#
set cols [list i1 i2 i3 i4 i5 i6 i7 i8 i9 iA iB iC iD iE iF iG iH iI iJ iK]
for {set nCol 1} {$nCol<[llength $cols]} {incr nCol} {

  set columns [join [lrange $cols 0 [expr {$nCol-1}]] ,]

  set X {0 {}}
  if {$nCol%2 == 0}  { set X {1 {Wrong number of columns for an rtree table}} }
  if {$nCol < 3}     { set X {1 {Too few columns for an rtree table}} }
  if {$nCol > 11}    { set X {1 {Too many columns for an rtree table}} }

  do_test rtree-1.3.$nCol {
    catchsql " 
      CREATE VIRTUAL TABLE t1 USING rtree($columns);
    "
  } $X

  catchsql { DROP TABLE t1 }
}

# Test that it is possible to open an existing database that contains
# r-tree tables.
#
do_test rtree-1.4.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2);
    INSERT INTO t1 VALUES(1, 5.0, 10.0);
    INSERT INTO t1 VALUES(2, 15.0, 20.0);
  }
} {}
do_test rtree-1.4.2 {
  db close
  sqlite3 db test.db
  execsql { SELECT * FROM t1 ORDER BY ii }
} {1 5.0 10.0 2 15.0 20.0}
do_test rtree-1.4.3 {
  execsql { DROP TABLE t1 }
} {}

# Test that it is possible to create an r-tree table with ridiculous
# column names.
#
do_test rtree-1.5.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING rtree("the key", "x dim.", "x2'dim");
    INSERT INTO t1 VALUES(1, 2, 3);
    SELECT "the key", "x dim.", "x2'dim" FROM t1;
  }
} {1 2.0 3.0}
do_test rtree-1.5.1 {
  execsql { DROP TABLE t1 }
} {}

# Force the r-tree constructor to fail.
#
do_test rtree-1.6.1 {
  execsql { CREATE TABLE t1_rowid(a); }
  catchsql {
    CREATE VIRTUAL TABLE t1 USING rtree("the key", "x dim.", "x2'dim");
  }
} {1 {table "t1_rowid" already exists}}
do_test rtree-1.6.1 {
  execsql { DROP TABLE t1_rowid }
} {}

#----------------------------------------------------------------------------
# Test cases rtree-2.* 
#
do_test rtree-2.1.1 {
  execsql { 
    CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2);
    SELECT * FROM t1;
  }
} {}

do_test rtree-2.1.2 {
  execsql { INSERT INTO t1 VALUES(NULL, 1, 3, 2, 4) }
  execsql { SELECT * FROM t1 }
} {1 1.0 3.0 2.0 4.0}
do_test rtree-2.1.3 {
  execsql { INSERT INTO t1 VALUES(NULL, 1, 3, 2, 4) }
  execsql { SELECT rowid FROM t1 ORDER BY rowid }
} {1 2}
do_test rtree-2.1.3 {
  execsql { INSERT INTO t1 VALUES(NULL, 1, 3, 2, 4) }
  execsql { SELECT ii FROM t1 ORDER BY ii }
} {1 2 3}

do_test rtree-2.2.1 {
  catchsql { INSERT INTO t1 VALUES(2, 1, 3, 2, 4) }
} {1 {constraint failed}}
do_test rtree-2.2.2 {
  catchsql { INSERT INTO t1 VALUES(4, 1, 3, 4, 2) }
} {1 {constraint failed}}
do_test rtree-2.2.3 {
  catchsql { INSERT INTO t1 VALUES(4, 3, 1, 2, 4) }
} {1 {constraint failed}}
do_test rtree-2.2.4 {
  execsql { SELECT ii FROM t1 ORDER BY ii }
} {1 2 3}

do_test rtree-2.X {
  execsql { DROP TABLE t1 }
} {}

#----------------------------------------------------------------------------
# Test cases rtree-3.* test linear scans of r-tree table data. To test
# this we have to insert some data into an r-tree, but that is not the
# focus of these tests.
#
do_test rtree-3.1.1 {
  execsql { 
    CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2);
    SELECT * FROM t1;
  }
} {}
do_test rtree-3.1.2 {
  execsql { 
    INSERT INTO t1 VALUES(5, 1, 3, 2, 4);
    SELECT * FROM t1;
  }
} {5 1.0 3.0 2.0 4.0}
do_test rtree-3.1.3 {
  execsql {
    INSERT INTO t1 VALUES(6, 2, 6, 4, 8);
    SELECT * FROM t1;
  }
} {5 1.0 3.0 2.0 4.0 6 2.0 6.0 4.0 8.0}

# Test the constraint on the coordinates (c[i]<=c[i+1] where (i%2==0)):
do_test rtree-3.2.1 {
  catchsql { INSERT INTO t1 VALUES(7, 2, 6, 4, 3) }
} {1 {constraint failed}}
do_test rtree-3.2.2 {
  catchsql { INSERT INTO t1 VALUES(8, 2, 6, 3, 3) }
} {0 {}}

#----------------------------------------------------------------------------
# Test cases rtree-5.* test DELETE operations.
#
do_test rtree-5.1.1 {
  execsql { CREATE VIRTUAL TABLE t2 USING rtree(ii, x1, x2) }
} {}
do_test rtree-5.1.2 {
  execsql { 
    INSERT INTO t2 VALUES(1, 10, 20);
    INSERT INTO t2 VALUES(2, 30, 40);
    INSERT INTO t2 VALUES(3, 50, 60);
    SELECT * FROM t2 ORDER BY ii;
  }
} {1 10.0 20.0 2 30.0 40.0 3 50.0 60.0}
do_test rtree-5.1.3 {
  execsql { 
    DELETE FROM t2 WHERE ii=2;
    SELECT * FROM t2 ORDER BY ii;
  }
} {1 10.0 20.0 3 50.0 60.0}
do_test rtree-5.1.4 {
  execsql { 
    DELETE FROM t2 WHERE ii=1;
    SELECT * FROM t2 ORDER BY ii;
  }
} {3 50.0 60.0}
do_test rtree-5.1.5 {
  execsql { 
    DELETE FROM t2 WHERE ii=3;
    SELECT * FROM t2 ORDER BY ii;
  }
} {}
do_test rtree-5.1.6 {
  execsql { SELECT * FROM t2_rowid }
} {}

#----------------------------------------------------------------------------
# Test cases rtree-5.* test UPDATE operations.
#
do_test rtree-6.1.1 {
  execsql { CREATE VIRTUAL TABLE t3 USING rtree(ii, x1, x2, y1, y2) }
} {}
do_test rtree-6.1.2 {
  execsql {
    INSERT INTO t3 VALUES(1, 2, 3, 4, 5);
    UPDATE t3 SET x2=5;
    SELECT * FROM t3;
  }
} {1 2.0 5.0 4.0 5.0}
do_test rtree-6.1.3 {
  execsql { UPDATE t3 SET ii = 2 }
  execsql { SELECT * FROM t3 }
} {2 2.0 5.0 4.0 5.0}

#----------------------------------------------------------------------------
# Test cases rtree-7.* test rename operations.
#
do_test rtree-7.1.1 {
  execsql {
    CREATE VIRTUAL TABLE t4 USING rtree(ii, x1, x2, y1, y2, z1, z2);
    INSERT INTO t4 VALUES(1, 2, 3, 4, 5, 6, 7);
  }
} {}
do_test rtree-7.1.2 {
  execsql { ALTER TABLE t4 RENAME TO t5 }
  execsql { SELECT * FROM t5 }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.1.3 {
  db close
  sqlite3 db test.db
  execsql { SELECT * FROM t5 }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.1.4 {
  execsql { ALTER TABLE t5 RENAME TO 'raisara "one"'''}
  execsql { SELECT * FROM "raisara ""one""'" }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.1.5 {
  execsql { SELECT * FROM 'raisara "one"''' }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.1.6 {
  execsql { ALTER TABLE "raisara ""one""'" RENAME TO "abc 123" }
  execsql { SELECT * FROM "abc 123" }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.1.7 {
  db close
  sqlite3 db test.db
  execsql { SELECT * FROM "abc 123" }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}

# An error midway through a rename operation.
do_test rtree-7.2.1 {
  execsql { 
    CREATE TABLE t4_node(a);
  }
  catchsql { ALTER TABLE "abc 123" RENAME TO t4 }
} {1 {SQL logic error or missing database}}
do_test rtree-7.2.2 {
  execsql { SELECT * FROM "abc 123" }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.2.3 {
  execsql { 
    DROP TABLE t4_node;
    CREATE TABLE t4_rowid(a);
  }
  catchsql { ALTER TABLE "abc 123" RENAME TO t4 }
} {1 {SQL logic error or missing database}}
do_test rtree-7.2.4 {
  db close
  sqlite3 db test.db
  execsql { SELECT * FROM "abc 123" }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}
do_test rtree-7.2.5 {
  execsql { DROP TABLE t4_rowid }
  execsql { ALTER TABLE "abc 123" RENAME TO t4 }
  execsql { SELECT * FROM t4 }
} {1 2.0 3.0 4.0 5.0 6.0 7.0}


#----------------------------------------------------------------------------
# Test cases rtree-8.*
#

# Test that the function to determine if a leaf cell is part of the
# result set works.
do_test rtree-8.1.1 {
  execsql {
    CREATE VIRTUAL TABLE t6 USING rtree(ii, x1, x2);
    INSERT INTO t6 VALUES(1, 3, 7);
    INSERT INTO t6 VALUES(2, 4, 6);
  }
} {}
do_test rtree-8.1.2 { execsql { SELECT ii FROM t6 WHERE x1>2 } } {1 2}
do_test rtree-8.1.3 { execsql { SELECT ii FROM t6 WHERE x1>3 } } {2}
do_test rtree-8.1.4 { execsql { SELECT ii FROM t6 WHERE x1>4 } } {}
do_test rtree-8.1.5 { execsql { SELECT ii FROM t6 WHERE x1>5 } } {}
do_test rtree-8.1.6 { execsql { SELECT ii FROM t6 WHERE x1<3 } } {}
do_test rtree-8.1.7 { execsql { SELECT ii FROM t6 WHERE x1<4 } } {1}
do_test rtree-8.1.8 { execsql { SELECT ii FROM t6 WHERE x1<5 } } {1 2}

#----------------------------------------------------------------------------
# Test cases rtree-9.*
#
# Test that ticket #3549 is fixed.
do_test rtree-9.1 {
  execsql {
    CREATE TABLE foo (id INTEGER PRIMARY KEY);
    CREATE VIRTUAL TABLE bar USING rtree (id, minX, maxX, minY, maxY);
    INSERT INTO foo VALUES (null);
    INSERT INTO foo SELECT null FROM foo;
    INSERT INTO foo SELECT null FROM foo;
    INSERT INTO foo SELECT null FROM foo;
    INSERT INTO foo SELECT null FROM foo;
    INSERT INTO foo SELECT null FROM foo;
    INSERT INTO foo SELECT null FROM foo;
    DELETE FROM foo WHERE id > 40;
    INSERT INTO bar SELECT NULL, 0, 0, 0, 0 FROM foo;
  }
} {}

# This used to crash.
do_test rtree-9.2 {
  execsql {
    SELECT count(*) FROM bar b1, bar b2, foo s1 WHERE s1.id = b1.id;
  }
} {1600}
do_test rtree-9.3 {
  execsql {
    SELECT count(*) FROM bar b1, bar b2, foo s1 
    WHERE b1.minX <= b2.maxX AND s1.id = b1.id;
  }
} {1600}

#-------------------------------------------------------------------------
# Ticket #3970: Check that the error message is meaningful when a 
# keyword is used as a column name.
#
do_test rtree-10.1 {
  catchsql { CREATE VIRTUAL TABLE t7 USING rtree(index, x1, y1, x2, y2) }
} {1 {near "index": syntax error}}

finish_test

Added ext/rtree/rtree2.test.

















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# 2008 Feb 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing the r-tree extension.
#
# $Id: rtree2.test,v 1.4 2008/07/14 15:37:01 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
} 
source [file join [file dirname [info script]] rtree_util.tcl]
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

set ::NROW   1000
set ::NDEL     10
set ::NSELECT 100

if {[info exists ISQUICK] && $ISQUICK} {
  set ::NROW 100
  set ::NSELECT 10
}

foreach module {rtree_i32 rtree} {
  for {set nDim 1} {$nDim <= 5} {incr nDim} {
  
    do_test rtree2-$module.$nDim.1 {
      set cols [list]
      foreach c [list c0 c1 c2 c3 c4 c5 c6 c7 c8 c9] {
        lappend cols "$c REAL"
      }
      set cols [join [lrange $cols 0 [expr {$nDim*2-1}]] ", "]
      execsql " 
        CREATE VIRTUAL TABLE t1 USING ${module}(ii, $cols);
        CREATE TABLE t2 (ii, $cols);
      "
    } {}
  
    do_test rtree2-$module.$nDim.2 {
      db transaction {
        for {set ii 0} {$ii < $::NROW} {incr ii} {
          #puts "Row $ii"
          set values [list]
          for {set jj 0} {$jj<$nDim*2} {incr jj} {
            lappend values [expr int(rand()*1000)]
          }
          set values [join $values ,]
          #puts [rtree_treedump db t1]
          #puts "INSERT INTO t2 VALUES($ii, $values)"
          set rc [catch {db eval "INSERT INTO t1 VALUES($ii, $values)"}]
          if {$rc} {
            incr ii -1
          } else {
            db eval "INSERT INTO t2 VALUES($ii, $values)"
          }
          #if {[rtree_check db t1]} {
            #puts [rtree_treedump db t1]
            #exit
          #}
        }
      }
  
      set t1 [execsql {SELECT * FROM t1 ORDER BY ii}]
      set t2 [execsql {SELECT * FROM t2 ORDER BY ii}]
      set rc [expr {$t1 eq $t2}]
      if {$rc != 1} {
        puts $t1
        puts $t2
      }
      set rc
    } {1}
  
    do_test rtree2-$module.$nDim.3 {
      rtree_check db t1
    } 0
  
    set OPS [list < > <= >= =]
    for {set ii 0} {$ii < $::NSELECT} {incr ii} {
      do_test rtree2-$module.$nDim.4.$ii.1 {
        set where [list]
        foreach look_three_dots! {. . .} {
          set colidx [expr int(rand()*($nDim*2+1))-1]
          if {$colidx<0} {
            set col ii
          } else {
            set col "c$colidx"
          }
          set op  [lindex $OPS [expr int(rand()*[llength $OPS])]]
          set val [expr int(rand()*1000)]
          lappend where "$col $op $val"
        }
        set where [join $where " AND "]
  
        set t1 [execsql "SELECT * FROM t1 WHERE $where ORDER BY ii"]
        set t2 [execsql "SELECT * FROM t2 WHERE $where ORDER BY ii"]
        set rc [expr {$t1 eq $t2}]
        if {$rc != 1} {
          #puts $where
          puts $t1
          puts $t2
          #puts [rtree_treedump db t1]
          #breakpoint
          #set t1 [execsql "SELECT * FROM t1 WHERE $where ORDER BY ii"]
          #exit
        }
        set rc
      } {1}
    }
  
    for {set ii 0} {$ii < $::NROW} {incr ii $::NDEL} {
      #puts [rtree_treedump db t1]
      do_test rtree2-$module.$nDim.5.$ii.1 {
        execsql "DELETE FROM t2 WHERE ii <= $::ii"
        execsql "DELETE FROM t1 WHERE ii <= $::ii"
  
        set t1 [execsql {SELECT * FROM t1 ORDER BY ii}]
        set t2 [execsql {SELECT * FROM t2 ORDER BY ii}]
        set rc [expr {$t1 eq $t2}]
        if {$rc != 1} {
          puts $t1
          puts $t2
        }
        set rc
      } {1}
      do_test rtree2-$module.$nDim.5.$ii.2 {
        rtree_check db t1
      } {0}
    }
  
    do_test rtree2-$module.$nDim.6 {
      execsql {
        DROP TABLE t1;
        DROP TABLE t2;
      }
    } {}
  }
}

finish_test

Added ext/rtree/rtree3.test.





















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 2008 Feb 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing that the r-tree correctly handles
# out-of-memory conditions.
#
# $Id: rtree3.test,v 1.2 2008/06/23 15:55:52 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
} 
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

# Only run these tests if memory debugging is turned on.
#
source $testdir/malloc_common.tcl
if {!$MEMDEBUG} {
   puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

do_malloc_test rtree3-1 -sqlbody {
  BEGIN TRANSACTION;
  CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2);
  INSERT INTO rt VALUES(NULL, 3, 5, 7, 9);
  INSERT INTO rt VALUES(NULL, 13, 15, 17, 19);
  DELETE FROM rt WHERE ii = 1;
  SELECT * FROM rt;
  SELECT ii FROM rt WHERE ii = 2;
  COMMIT;
} 
do_malloc_test rtree3-2 -sqlprep {
  CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2);
  INSERT INTO rt VALUES(NULL, 3, 5, 7, 9);
} -sqlbody {
  DROP TABLE rt;
} 


do_malloc_test rtree3-3 -sqlprep {
  CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2);
  INSERT INTO rt VALUES(NULL, 3, 5, 7, 9);
} -tclbody {
  db eval BEGIN
  for {set ii 0} {$ii < 100} {incr ii} {
    set f [expr rand()]
    db eval {INSERT INTO rt VALUES(NULL, $f*10.0, $f*10.0, $f*15.0, $f*15.0)}
  }
  db eval COMMIT
  db eval BEGIN
  for {set ii 0} {$ii < 100} {incr ii} {
    set f [expr rand()]
    db eval { DELETE FROM rt WHERE x1<($f*10.0) AND x1>($f*10.5) }
  }
  db eval COMMIT
} 

finish_test

Added ext/rtree/rtree4.test.

























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# 2008 May 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Randomized test cases for the rtree extension.
#
# $Id: rtree4.test,v 1.3 2008/06/23 15:55:52 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
} 
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

set ::NROW 2500
if {[info exists ISQUICK] && $ISQUICK} {
  set ::NROW 250
}

# Return a floating point number between -X and X.
# 
proc rand {X} {
  return [expr {int((rand()-0.5)*1024.0*$X)/512.0}]
}

# Return a positive floating point number less than or equal to X
#
proc randincr {X} {
  while 1 {
    set r [expr {int(rand()*$X*32.0)/32.0}]
    if {$r>0.0} {return $r}
  }
}

# Scramble the $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# Always use the same random seed so that the sequence of tests
# is repeatable.
#
expr {srand(1234)}

# Run these tests for all number of dimensions between 1 and 5.
#
for {set nDim 1} {$nDim<=5} {incr nDim} {

  # Construct an rtree virtual table and an ordinary btree table
  # to mirror it.  The ordinary table should be much slower (since
  # it has to do a full table scan) but should give the exact same
  # answers.
  #
  do_test rtree4-$nDim.1 {
    set clist {}
    set cklist {}
    for {set i 0} {$i<$nDim} {incr i} {
      lappend clist mn$i mx$i
      lappend cklist "mn$i<mx$i"
    }
    db eval "DROP TABLE IF EXISTS rx"
    db eval "DROP TABLE IF EXISTS bx"
    db eval "CREATE VIRTUAL TABLE rx USING rtree(id, [join $clist ,])"
    db eval "CREATE TABLE bx(id INTEGER PRIMARY KEY,\
                [join $clist ,], CHECK( [join $cklist { AND }] ))"
  } {}

  # Do many insertions of small objects.  Do both overlapping and
  # contained-within queries after each insert to verify that all
  # is well.
  #
  unset -nocomplain where
  for {set i 1} {$i<$::NROW} {incr i} {
    # Do a random insert
    #
    do_test rtree-$nDim.2.$i.1 {
      set vlist {}
      for {set j 0} {$j<$nDim} {incr j} {
        set mn [rand 10000]
        set mx [expr {$mn+[randincr 50]}]
        lappend vlist $mn $mx
      }
      db eval "INSERT INTO rx VALUES(NULL, [join $vlist ,])"
      db eval "INSERT INTO bx VALUES(NULL, [join $vlist ,])"
    } {}

    # Do a contained-in query on all dimensions
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      set mn [rand 10000]
      set mx [expr {$mn+[randincr 500]}]
      lappend where mn$j>=$mn mx$j<=$mx
    }
    set where "WHERE [join $where { AND }]"
    do_test rtree-$nDim.2.$i.2 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do an overlaps query on all dimensions
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      set mn [rand 10000]
      set mx [expr {$mn+[randincr 500]}]
      lappend where mx$j>=$mn mn$j<=$mx
    }
    set where "WHERE [join $where { AND }]"
    do_test rtree-$nDim.2.$i.3 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do a contained-in query with surplus contraints at the beginning.
    # This should force a full-table scan on the rtree.
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      lappend where mn$j>-10000 mx$j<10000
    }
    for {set j 0} {$j<$nDim} {incr j} {
      set mn [rand 10000]
      set mx [expr {$mn+[randincr 500]}]
      lappend where mn$j>=$mn mx$j<=$mx
    }
    set where "WHERE [join $where { AND }]"
    do_test rtree-$nDim.2.$i.3 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do an overlaps query with surplus contraints at the beginning.
    # This should force a full-table scan on the rtree.
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      lappend where mn$j>=-10000 mx$j<=10000
    }
    for {set j 0} {$j<$nDim} {incr j} {
      set mn [rand 10000]
      set mx [expr {$mn+[randincr 500]}]
      lappend where mx$j>$mn mn$j<$mx
    }
    set where "WHERE [join $where { AND }]"
    do_test rtree-$nDim.2.$i.4 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do a contained-in query with surplus contraints at the end
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      set mn [rand 10000]
      set mx [expr {$mn+[randincr 500]}]
      lappend where mn$j>=$mn mx$j<$mx
    }
    for {set j [expr {$nDim-1}]} {$j>=0} {incr j -1} {
      lappend where mn$j>=-10000 mx$j<10000
    }
    set where "WHERE [join $where { AND }]"
    do_test rtree-$nDim.2.$i.5 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do an overlaps query with surplus contraints at the end
    #
    set where {}
    for {set j [expr {$nDim-1}]} {$j>=0} {incr j -1} {
      set mn [rand 10000]
      set mx [expr {$mn+[randincr 500]}]
      lappend where mx$j>$mn mn$j<=$mx
    }
    for {set j 0} {$j<$nDim} {incr j} {
      lappend where mx$j>-10000 mn$j<=10000
    }
    set where "WHERE [join $where { AND }]"
    do_test rtree-$nDim.2.$i.6 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do a contained-in query with surplus contraints where the 
    # constraints appear in a random order.
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      set mn1 [rand 10000]
      set mn2 [expr {$mn1+[randincr 100]}]
      set mx1 [expr {$mn2+[randincr 400]}]
      set mx2 [expr {$mx1+[randincr 100]}]
      lappend where mn$j>=$mn1 mn$j>$mn2 mx$j<$mx1 mx$j<=$mx2
    }
    set where "WHERE [join [scramble $where] { AND }]"
    do_test rtree-$nDim.2.$i.7 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]

    # Do an overlaps query with surplus contraints where the
    # constraints appear in a random order.
    #
    set where {}
    for {set j 0} {$j<$nDim} {incr j} {
      set mn1 [rand 10000]
      set mn2 [expr {$mn1+[randincr 100]}]
      set mx1 [expr {$mn2+[randincr 400]}]
      set mx2 [expr {$mx1+[randincr 100]}]
      lappend where mx$j>=$mn1 mx$j>$mn2 mn$j<$mx1 mn$j<=$mx2
    }
    set where "WHERE [join [scramble $where] { AND }]"
    do_test rtree-$nDim.2.$i.8 {
      list $where [db eval "SELECT id FROM rx $where ORDER BY id"]
    } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]]
  }

}

finish_test

Added ext/rtree/rtree5.test.

































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 2008 Jul 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing the r-tree extension when it is
# configured to store values as 32 bit integers.
#
# $Id: rtree5.test,v 1.1 2008/07/14 15:37:01 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
} 
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

do_test rtree5-1.0 {
  execsql { CREATE VIRTUAL TABLE t1 USING rtree_i32(id, x1, x2, y1, y2) }
} {}
do_test rtree5-1.1 {
  execsql { INSERT INTO t1 VALUES(1, 5, 10, 4, 11.2) }
} {}
do_test rtree5-1.2 { 
  execsql { SELECT * FROM t1 }
} {1 5 10 4 11}
do_test rtree5-1.3 { 
  execsql { SELECT typeof(x1) FROM t1 }
} {integer}

do_test rtree5-1.4 { 
  execsql { SELECT x1==5 FROM t1 }
} {1}
do_test rtree5-1.5 { 
  execsql { SELECT x1==5.2 FROM t1 }
} {0}
do_test rtree5-1.6 { 
  execsql { SELECT x1==5.0 FROM t1 }
} {1}

do_test rtree5-1.7 { 
  execsql { SELECT count(*) FROM t1 WHERE x1==5 }
} {1}
do_test rtree5-1.8 { 
  execsql { SELECT count(*) FROM t1 WHERE x1==5.2 }
} {0}
do_test rtree5-1.9 { 
  execsql { SELECT count(*) FROM t1 WHERE x1==5.0 }
} {1}

do_test rtree5-1.10 { 
  execsql { SELECT (1<<31)-5, (1<<31)-1, -1*(1<<31), -1*(1<<31)+5 }
} {2147483643 2147483647 -2147483648 -2147483643}
do_test rtree5-1.10 { 
  execsql { 
    INSERT INTO t1 VALUES(2, (1<<31)-5, (1<<31)-1, -1*(1<<31), -1*(1<<31)+5) 
  }
} {}
do_test rtree5-1.12 { 
  execsql { SELECT * FROM t1 WHERE id=2 }
} {2 2147483643 2147483647 -2147483648 -2147483643}
do_test rtree5-1.13 { 
  execsql { 
    SELECT * FROM t1 WHERE 
        x1=2147483643 AND x2=2147483647 AND 
        y1=-2147483648 AND y2=-2147483643
  }
} {2 2147483643 2147483647 -2147483648 -2147483643}

finish_test

Added ext/rtree/rtree6.test.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# 2008 Sep 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: rtree6.test,v 1.1 2008/09/01 12:47:00 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
} 
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

#   Operator    Byte Value
#   ----------------------
#      =        0x41 ('A')
#     <=        0x42 ('B')
#      <        0x43 ('C')
#     >=        0x44 ('D')
#      >        0x45 ('E')
#   ----------------------

proc rtree_strategy {sql} {
  set ret [list]
  db eval "explain $sql" a {
    if {$a(opcode) eq "VFilter"} {
      lappend ret $a(p4)
    }
  }
  set ret
}

proc query_plan {sql} {
  set ret [list]
  db eval "explain query plan $sql" a {
    lappend ret $a(detail)
  }
  set ret
}

do_test rtree6-1.1 {
  execsql {
    CREATE TABLE t2(k INTEGER PRIMARY KEY, v);
    CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2);
  }
} {}

do_test rtree6-1.2 {
  rtree_strategy {SELECT * FROM t1 WHERE x1>10}
} {Ea}

do_test rtree6-1.3 {
  rtree_strategy {SELECT * FROM t1 WHERE x1<10}
} {Ca}

do_test rtree6-1.4 {
  rtree_strategy {SELECT * FROM t1,t2 WHERE k=ii AND x1<10}
} {Ca}

do_test rtree6-1.5 {
  rtree_strategy {SELECT * FROM t1,t2 WHERE k=+ii AND x1<10}
} {Ca}

do_test rtree6.2.1 {
  query_plan {SELECT * FROM t1,t2 WHERE k=+ii AND x1<10}
} [list \
  {TABLE t1 VIRTUAL TABLE INDEX 2:Ca} \
  {TABLE t2 USING PRIMARY KEY}        \
]

do_test rtree6.2.2 {
  query_plan {SELECT * FROM t1,t2 WHERE k=ii AND x1<10}
} [list \
  {TABLE t1 VIRTUAL TABLE INDEX 2:Ca} \
  {TABLE t2 USING PRIMARY KEY}        \
]

do_test rtree6.2.3 {
  query_plan {SELECT * FROM t1,t2 WHERE k=ii}
} [list \
  {TABLE t2}                          \
  {TABLE t1 VIRTUAL TABLE INDEX 1:}   \
]

do_test rtree6.2.4 {
  query_plan {SELECT * FROM t1,t2 WHERE v=10 and x1<10 and x2>10}
} [list \
  {TABLE t1 VIRTUAL TABLE INDEX 2:CaEb}   \
  {TABLE t2}                              \
]

do_test rtree6.2.5 {
  query_plan {SELECT * FROM t1,t2 WHERE k=ii AND x1<v}
} [list \
  {TABLE t2}                              \
  {TABLE t1 VIRTUAL TABLE INDEX 1:}   \
]

finish_test

Added ext/rtree/rtree_perf.tcl.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

set testdir [file join [file dirname $argv0] .. .. test]
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

set NROW   10000
set NQUERY   500

puts "Generating $NROW rows of data..."
set data [list]
for {set ii 0} {$ii < $NROW} {incr ii} {
  set x1 [expr {rand()*1000}]
  set x2 [expr {$x1+rand()*50}]
  set y1 [expr {rand()*1000}]
  set y2 [expr {$y1+rand()*50}]
  lappend data $x1 $x2 $y1 $y2
}
puts "Finished generating data"


set sql1 {CREATE TABLE btree(ii INTEGER PRIMARY KEY, x1, x2, y1, y2)}
set sql2 {CREATE VIRTUAL TABLE rtree USING rtree(ii, x1, x2, y1, y2)}
puts "Creating tables:"
puts "  $sql1"
puts "  $sql2"
db eval $sql1
db eval $sql2

db eval "pragma cache_size=100"

puts -nonewline "Inserting into btree... "
flush stdout
set btree_time [time {db transaction {
  set ii 1
  foreach {x1 x2 y1 y2} $data {
    db eval {INSERT INTO btree VALUES($ii, $x1, $x2, $y1, $y2)}
    incr ii
  }
}}]
puts "$btree_time"

puts -nonewline "Inserting into rtree... "
flush stdout
set rtree_time [time {db transaction {
  set ii 1
  foreach {x1 x2 y1 y2} $data {
    incr ii
    db eval {INSERT INTO rtree VALUES($ii, $x1, $x2, $y1, $y2)}
  }
}}]
puts "$rtree_time"


puts -nonewline "Selecting from btree... "
flush stdout
set btree_select_time [time {
  foreach {x1 x2 y1 y2} [lrange $data 0 [expr $NQUERY*4-1]] {
    db eval {SELECT * FROM btree WHERE x1<$x1 AND x2>$x2 AND y1<$y1 AND y2>$y2}
 }
}]
puts "$btree_select_time"

puts -nonewline "Selecting from rtree... "
flush stdout
set rtree_select_time [time {
  foreach {x1 x2 y1 y2} [lrange $data 0 [expr $NQUERY*4-1]] {
    db eval {SELECT * FROM rtree WHERE x1<$x1 AND x2>$x2 AND y1<$y1 AND y2>$y2}
  }
}]
puts "$rtree_select_time"


Added ext/rtree/rtree_util.tcl.







































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# 2008 Feb 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains Tcl code that may be useful for testing or
# analyzing r-tree structures created with this module. It is
# used by both test procedures and the r-tree viewer application.
#
# $Id: rtree_util.tcl,v 1.1 2008/05/26 18:41:54 danielk1977 Exp $
#


#--------------------------------------------------------------------------
# PUBLIC API:
#
#   rtree_depth
#   rtree_ndim
#   rtree_node
#   rtree_mincells
#   rtree_check
#   rtree_dump
#   rtree_treedump
#

proc rtree_depth {db zTab} {
  $db one "SELECT rtreedepth(data) FROM ${zTab}_node WHERE nodeno=1"
}

proc rtree_nodedepth {db zTab iNode} {
  set iDepth [rtree_depth $db $zTab]
  
  set ii $iNode
  while {$ii != 1} {
    set sql "SELECT parentnode FROM ${zTab}_parent WHERE nodeno = $ii"
    set ii [db one $sql]
    incr iDepth -1
  }
  
  return $iDepth
}

# Return the number of dimensions of the rtree.
#
proc rtree_ndim {db zTab} {
  set nDim [expr {(([llength [$db eval "pragma table_info($zTab)"]]/6)-1)/2}]
}

# Return the contents of rtree node $iNode.
#
proc rtree_node {db zTab iNode {iPrec 6}} {
  set nDim [rtree_ndim $db $zTab]
  set sql "
    SELECT rtreenode($nDim, data) FROM ${zTab}_node WHERE nodeno = $iNode
  "
  set node [db one $sql]

  set nCell [llength $node]
  set nCoord [expr $nDim*2]
  for {set ii 0} {$ii < $nCell} {incr ii} {
    for {set jj 1} {$jj <= $nCoord} {incr jj} {
      set newval [format "%.${iPrec}f" [lindex $node $ii $jj]]
      lset node $ii $jj $newval
    }
  }
  set node
}

proc rtree_mincells {db zTab} {
  set n [$db one "select length(data) FROM ${zTab}_node LIMIT 1"]
  set nMax [expr {int(($n-4)/(8+[rtree_ndim $db $zTab]*2*4))}]
  return [expr {int($nMax/3)}]
}

# An integrity check for the rtree $zTab accessible via database 
# connection $db.
#
proc rtree_check {db zTab} {
  array unset ::checked
 
  # Check each r-tree node.
  set rc [catch {
    rtree_node_check $db $zTab 1 [rtree_depth $db $zTab]
  } msg]
  if {$rc && $msg ne ""} { error $msg }

  # Check that the _rowid and _parent tables have the right 
  # number of entries.
  set nNode   [$db one "SELECT count(*) FROM ${zTab}_node"]
  set nRow    [$db one "SELECT count(*) FROM ${zTab}"]
  set nRowid  [$db one "SELECT count(*) FROM ${zTab}_rowid"]
  set nParent [$db one "SELECT count(*) FROM ${zTab}_parent"]

  if {$nNode != ($nParent+1)} { 
    error "Wrong number of entries in ${zTab}_parent"
  }
  if {$nRow != $nRowid} { 
    error "Wrong number of entries in ${zTab}_rowid"
  }
  
  return $rc
}

proc rtree_node_check {db zTab iNode iDepth} {
  if {[info exists ::checked($iNode)]} { error "Second ref to $iNode" }
  set ::checked($iNode) 1

  set node [rtree_node $db $zTab $iNode]
  if {$iNode!=1 && [llength $node]==0} { error "No such node: $iNode" }

  if {$iNode != 1 && [llength $node]<[rtree_mincells $db $zTab]} {
    puts "Node $iNode: Has only [llength $node] cells"
    error ""
  }
  if {$iNode == 1 && [llength $node]==1 && [rtree_depth $db $zTab]>0} {
    set depth [rtree_depth $db $zTab]
    puts "Node $iNode: Has only 1 child (tree depth is $depth)"
    error ""
  }

  set nDim [expr {([llength [lindex $node 0]]-1)/2}]

  if {$iDepth > 0} {
    set d [expr $iDepth-1]
    foreach cell $node {
      set shouldbe [rtree_node_check $db $zTab [lindex $cell 0] $d]
      if {$cell ne $shouldbe} {
        puts "Node $iNode: Cell is: {$cell}, should be {$shouldbe}"
        error ""
      }
    }
  }

  set mapping_table "${zTab}_parent" 
  set mapping_sql "SELECT parentnode FROM $mapping_table WHERE rowid = \$rowid"
  if {$iDepth==0} { 
    set mapping_table "${zTab}_rowid"
    set mapping_sql "SELECT nodeno FROM $mapping_table WHERE rowid = \$rowid"
  }
  foreach cell $node {
    set rowid [lindex $cell 0]
    set mapping [db one $mapping_sql]
    if {$mapping != $iNode} {
      puts "Node $iNode: $mapping_table entry for cell $rowid is $mapping"
      error ""
    }
  }

  set ret [list $iNode]
  for {set ii 1} {$ii <= $nDim*2} {incr ii} {
    set f [lindex $node 0 $ii]
    foreach cell $node {
      set f2 [lindex $cell $ii]
      if {($ii%2)==1 && $f2<$f} {set f $f2}
      if {($ii%2)==0 && $f2>$f} {set f $f2}
    }
    lappend ret $f
  }
  return $ret
}

proc rtree_dump {db zTab} {
  set zRet ""
  set nDim [expr {(([llength [$db eval "pragma table_info($zTab)"]]/6)-1)/2}]
  set sql "SELECT nodeno, rtreenode($nDim, data) AS node FROM ${zTab}_node"
  $db eval $sql {
    append zRet [format "% -10s %s\n" $nodeno $node]
  }
  set zRet
}

proc rtree_nodetreedump {db zTab zIndent iDepth iNode} {
  set ret ""
  set node [rtree_node $db $zTab $iNode 1]
  append ret [format "%-3d %s%s\n" $iNode $zIndent $node]
  if {$iDepth>0} {
    foreach cell $node {
      set i [lindex $cell 0]
      append ret [rtree_nodetreedump $db $zTab "$zIndent  " [expr $iDepth-1] $i]
    }
  }
  set ret
}

proc rtree_treedump {db zTab} {
  set d [rtree_depth $db $zTab]
  rtree_nodetreedump $db $zTab "" $d 1
}

Added ext/rtree/tkt3363.test.













































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 2008 Sep 08
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing that ticket #3363 is fixed.
#
# $Id: tkt3363.test,v 1.1 2008/09/08 11:07:03 danielk1977 Exp $
#

if {![info exists testdir]} {
  set testdir [file join [file dirname $argv0] .. .. test]
}
source [file join [file dirname [info script]] rtree_util.tcl]
source $testdir/tester.tcl

ifcapable !rtree {
  finish_test
  return
}

do_test tkt3363.1.1 {
  execsql { CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2) }
} {}

do_test tkt3363.1.2 {
  for {set ii 1} {$ii < 50} {incr ii} {
    set x 1000000
    set y [expr 4000000 + $ii*10]
    execsql { INSERT INTO t1 VALUES($ii, $x, $x, $y, $y) }
  }
} {}

do_test tkt3363.1.3 {
  execsql { 
    SELECT count(*) FROM t1 WHERE +y2>4000425.0;
  }
} {7}

do_test tkt3363.1.4 {
  execsql { 
    SELECT count(*) FROM t1 WHERE y2>4000425.0;
  }
} {7}

finish_test


Added ext/rtree/viewrtree.tcl.



























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189

load ./libsqlite3.dylib
#package require sqlite3
source [file join [file dirname $argv0] rtree_util.tcl]

wm title . "SQLite r-tree viewer"

if {[llength $argv]!=1} {
  puts stderr "Usage: $argv0 <database-file>"
  puts stderr ""
  exit
}
sqlite3 db [lindex $argv 0]

canvas .c -background white -width 400 -height 300 -highlightthickness 0

button .b -text "Parent Node" -command {
  set sql "SELECT parentnode FROM $::O(zTab)_parent WHERE nodeno = $::O(iNode)"
  set ::O(iNode) [db one $sql]
  if {$::O(iNode) eq ""} {set ::O(iNode) 1}
  view_node
}

set O(iNode) 1
set O(zTab) ""
set O(listbox_captions)  [list]
set O(listbox_itemmap)   [list]
set O(listbox_highlight) -1

listbox   .l -listvariable ::O(listbox_captions) -yscrollcommand {.ls set}
scrollbar .ls -command {.l yview}
label     .status -font courier -anchor w
label     .title -anchor w -text "Node 1:" -background white -borderwidth 0


set rtree_tables [list]
db eval {
  SELECT name 
  FROM sqlite_master 
  WHERE type='table' AND sql LIKE '%virtual%table%using%rtree%'
} {
  set nCol [expr [llength [db eval "pragma table_info($name)"]]/6]
  if {$nCol != 5} {
    puts stderr "Not viewing $name - is not 2-dimensional"
  } else {
    lappend rtree_tables [list Table $name]
  }
}
if {$rtree_tables eq ""} {
  puts stderr "Cannot find an r-tree table in database [lindex $argv 0]"
  puts stderr ""
  exit
}
eval tk_optionMenu .select option_var $rtree_tables
trace add variable option_var write set_option_var
proc set_option_var {args} {
  set ::O(zTab) [lindex $::option_var 1]
  set ::O(iNode) 1
  view_node
}
set ::O(zTab) [lindex $::rtree_tables 0 1]

bind .l <1> {listbox_click [.l nearest %y]}
bind .l <Motion> {listbox_mouseover [.l nearest %y]}
bind .l <Leave>  {listbox_mouseover -1}

proc listbox_click {sel} {
  if {$sel ne ""} {
    set ::O(iNode) [lindex $::O(listbox_captions) $sel 1]
    view_node
  }
}
proc listbox_mouseover {i} {
  set oldid [lindex $::O(listbox_itemmap) $::O(listbox_highlight)]
  .c itemconfigure $oldid -fill ""

  .l selection clear 0 end
  .status configure -text ""
  if {$i>=0} {
    set id [lindex $::O(listbox_itemmap) $i]
    .c itemconfigure $id -fill grey
    .c lower $id
    set ::O(listbox_highlight) $i
    .l selection set $i
    .status configure -text [cell_report db $::O(zTab) $::O(iNode) $i]
  }
}

grid configure .select  -row 0 -column 0 -columnspan 2 -sticky nsew
grid configure .b       -row 1 -column 0 -columnspan 2 -sticky nsew
grid configure .l       -row 2 -column 0               -sticky nsew
grid configure .status  -row 3 -column 0 -columnspan 3 -sticky nsew

grid configure .title   -row 0 -column 2               -sticky nsew
grid configure .c       -row 1 -column 2 -rowspan 2    -sticky nsew
grid configure .ls      -row 2 -column 1               -sticky nsew

grid columnconfigure . 2 -weight 1
grid rowconfigure    . 2 -weight 1

proc node_bbox {data} {
  set xmin 0
  set xmax 0
  set ymin 0
  set ymax 0
  foreach {rowid xmin xmax ymin ymax} [lindex $data 0] break
  foreach cell [lrange $data 1 end] {
    foreach {rowid x1 x2 y1 y2} $cell break
    if {$x1 < $xmin} {set xmin $x1}
    if {$x2 > $xmax} {set xmax $x2}
    if {$y1 < $ymin} {set ymin $y1}
    if {$y2 > $ymax} {set ymax $y2}
  }
  list $xmin $xmax $ymin $ymax
}

proc view_node {} {
  set iNode $::O(iNode)
  set zTab $::O(zTab)

  set data [rtree_node db $zTab $iNode 12]
  set depth [rtree_nodedepth db $zTab $iNode]

  .c delete all
  set ::O(listbox_captions) [list]
  set ::O(listbox_itemmap) [list]
  set $::O(listbox_highlight) -1

  .b configure -state normal
  if {$iNode == 1} {.b configure -state disabled}
  .title configure -text "Node $iNode: [cell_report db $zTab $iNode -1]"

  foreach {xmin xmax ymin ymax} [node_bbox $data] break
  set total_area 0.0

  set xscale [expr {double([winfo width .c]-20)/($xmax-$xmin)}]
  set yscale [expr {double([winfo height .c]-20)/($ymax-$ymin)}]

  set xoff [expr {10.0 - $xmin*$xscale}]
  set yoff [expr {10.0 - $ymin*$yscale}]

  foreach cell $data {
    foreach {rowid x1 x2 y1 y2} $cell break
    set total_area [expr {$total_area + ($x2-$x1)*($y2-$y1)}]
    set x1 [expr {$x1*$xscale + $xoff}]
    set x2 [expr {$x2*$xscale + $xoff}]
    set y1 [expr {$y1*$yscale + $yoff}]
    set y2 [expr {$y2*$yscale + $yoff}]

    set id [.c create rectangle $x1 $y1 $x2 $y2]
    if {$depth>0} {
      lappend ::O(listbox_captions) "Node $rowid"
      lappend ::O(listbox_itemmap) $id
    }
  }
}

proc cell_report {db zTab iParent iCell} {
  set data [rtree_node db $zTab $iParent 12]
  set cell [lindex $data $iCell]

  foreach {xmin xmax ymin ymax} [node_bbox $data] break
  set total_area [expr ($xmax-$xmin)*($ymax-$ymin)]

  if {$cell eq ""} {
    set cell_area 0.0
    foreach cell $data {
      foreach {rowid x1 x2 y1 y2} $cell break
      set cell_area [expr $cell_area+($x2-$x1)*($y2-$y1)]
    }
    set cell_area [expr $cell_area/[llength $data]]
    set zReport [format "Size = %.1f x %.1f    Average child area = %.1f%%" \
      [expr $xmax-$xmin] [expr $ymax-$ymin] [expr 100.0*$cell_area/$total_area]\
    ]
    append zReport "   Sub-tree height: [rtree_nodedepth db $zTab $iParent]"
  } else {
    foreach {rowid x1 x2 y1 y2} $cell break
    set cell_area  [expr ($x2-$x1)*($y2-$y1)]
    set zReport [format "Size = %.1f x %.1f    Area = %.1f%%" \
      [expr $x2-$x1] [expr $y2-$y1] [expr 100.0*$cell_area/$total_area]
    ]
  }

  return $zReport
}

view_node
bind .c <Configure> view_node

Added install-sh.























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/bin/sh
#
# install - install a program, script, or datafile
# This comes from X11R5 (mit/util/scripts/install.sh).
#
# Copyright 1991 by the Massachusetts Institute of Technology
#
# Permission to use, copy, modify, distribute, and sell this software and its
# documentation for any purpose is hereby granted without fee, provided that
# the above copyright notice appear in all copies and that both that
# copyright notice and this permission notice appear in supporting
# documentation, and that the name of M.I.T. not be used in advertising or
# publicity pertaining to distribution of the software without specific,
# written prior permission.  M.I.T. makes no representations about the
# suitability of this software for any purpose.  It is provided "as is"
# without express or implied warranty.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.  It can only install one file at a time, a restriction
# shared with many OS's install programs.


# set DOITPROG to echo to test this script

# Don't use :- since 4.3BSD and earlier shells don't like it.
doit="${DOITPROG-}"


# put in absolute paths if you don't have them in your path; or use env. vars.

mvprog="${MVPROG-mv}"
cpprog="${CPPROG-cp}"
chmodprog="${CHMODPROG-chmod}"
chownprog="${CHOWNPROG-chown}"
chgrpprog="${CHGRPPROG-chgrp}"
stripprog="${STRIPPROG-strip}"
rmprog="${RMPROG-rm}"
mkdirprog="${MKDIRPROG-mkdir}"

transformbasename=""
transform_arg=""
instcmd="$mvprog"
chmodcmd="$chmodprog 0755"
chowncmd=""
chgrpcmd=""
stripcmd=""
rmcmd="$rmprog -f"
mvcmd="$mvprog"
src=""
dst=""
dir_arg=""

while [ x"$1" != x ]; do
    case $1 in
	-c) instcmd="$cpprog"
	    shift
	    continue;;

	-d) dir_arg=true
	    shift
	    continue;;

	-m) chmodcmd="$chmodprog $2"
	    shift
	    shift
	    continue;;

	-o) chowncmd="$chownprog $2"
	    shift
	    shift
	    continue;;

	-g) chgrpcmd="$chgrpprog $2"
	    shift
	    shift
	    continue;;

	-s) stripcmd="$stripprog"
	    shift
	    continue;;

	-t=*) transformarg=`echo $1 | sed 's/-t=//'`
	    shift
	    continue;;

	-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
	    shift
	    continue;;

	*)  if [ x"$src" = x ]
	    then
		src=$1
	    else
		# this colon is to work around a 386BSD /bin/sh bug
		:
		dst=$1
	    fi
	    shift
	    continue;;
    esac
done

if [ x"$src" = x ]
then
	echo "install:	no input file specified"
	exit 1
else
	true
fi

if [ x"$dir_arg" != x ]; then
	dst=$src
	src=""
	
	if [ -d $dst ]; then
		instcmd=:
		chmodcmd=""
	else
		instcmd=mkdir
	fi
else

# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
# might cause directories to be created, which would be especially bad 
# if $src (and thus $dsttmp) contains '*'.

	if [ -f $src -o -d $src ]
	then
		true
	else
		echo "install:  $src does not exist"
		exit 1
	fi
	
	if [ x"$dst" = x ]
	then
		echo "install:	no destination specified"
		exit 1
	else
		true
	fi

# If destination is a directory, append the input filename; if your system
# does not like double slashes in filenames, you may need to add some logic

	if [ -d $dst ]
	then
		dst="$dst"/`basename $src`
	else
		true
	fi
fi

## this sed command emulates the dirname command
dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`

# Make sure that the destination directory exists.
#  this part is taken from Noah Friedman's mkinstalldirs script

# Skip lots of stat calls in the usual case.
if [ ! -d "$dstdir" ]; then
defaultIFS='	
'
IFS="${IFS-${defaultIFS}}"

oIFS="${IFS}"
# Some sh's can't handle IFS=/ for some reason.
IFS='%'
set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
IFS="${oIFS}"

pathcomp=''

while [ $# -ne 0 ] ; do
	pathcomp="${pathcomp}${1}"
	shift

	if [ ! -d "${pathcomp}" ] ;
        then
		$mkdirprog "${pathcomp}"
	else
		true
	fi

	pathcomp="${pathcomp}/"
done
fi

if [ x"$dir_arg" != x ]
then
	$doit $instcmd $dst &&

	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
else

# If we're going to rename the final executable, determine the name now.

	if [ x"$transformarg" = x ] 
	then
		dstfile=`basename $dst`
	else
		dstfile=`basename $dst $transformbasename | 
			sed $transformarg`$transformbasename
	fi

# don't allow the sed command to completely eliminate the filename

	if [ x"$dstfile" = x ] 
	then
		dstfile=`basename $dst`
	else
		true
	fi

# Make a temp file name in the proper directory.

	dsttmp=$dstdir/#inst.$$#

# Move or copy the file name to the temp name

	$doit $instcmd $src $dsttmp &&

	trap "rm -f ${dsttmp}" 0 &&

# and set any options; do chmod last to preserve setuid bits

# If any of these fail, we abort the whole thing.  If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $instcmd $src $dsttmp" command.

	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&

# Now rename the file to the real destination.

	$doit $rmcmd -f $dstdir/$dstfile &&
	$doit $mvcmd $dsttmp $dstdir/$dstfile 

fi &&


exit 0

Added ltmain.sh.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
# Generated from ltmain.m4sh.

# ltmain.sh (GNU libtool) 2.2.6
# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996

# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.  There is NO
# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# GNU Libtool is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# As a special exception to the GNU General Public License,
# if you distribute this file as part of a program or library that
# is built using GNU Libtool, you may include this file under the
# same distribution terms that you use for the rest of that program.
#
# GNU Libtool is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Libtool; see the file COPYING.  If not, a copy
# can be downloaded from http://www.gnu.org/licenses/gpl.html,
# or obtained by writing to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

# Usage: $progname [OPTION]... [MODE-ARG]...
#
# Provide generalized library-building support services.
#
#     --config             show all configuration variables
#     --debug              enable verbose shell tracing
# -n, --dry-run            display commands without modifying any files
#     --features           display basic configuration information and exit
#     --mode=MODE          use operation mode MODE
#     --preserve-dup-deps  don't remove duplicate dependency libraries
#     --quiet, --silent    don't print informational messages
#     --tag=TAG            use configuration variables from tag TAG
# -v, --verbose            print informational messages (default)
#     --version            print version information
# -h, --help               print short or long help message
#
# MODE must be one of the following:
#
#       clean              remove files from the build directory
#       compile            compile a source file into a libtool object
#       execute            automatically set library path, then run a program
#       finish             complete the installation of libtool libraries
#       install            install libraries or executables
#       link               create a library or an executable
#       uninstall          remove libraries from an installed directory
#
# MODE-ARGS vary depending on the MODE.
# Try `$progname --help --mode=MODE' for a more detailed description of MODE.
#
# When reporting a bug, please describe a test case to reproduce it and
# include the following information:
#
#       host-triplet:	$host
#       shell:		$SHELL
#       compiler:		$LTCC
#       compiler flags:		$LTCFLAGS
#       linker:		$LD (gnu? $with_gnu_ld)
#       $progname:		(GNU libtool) 2.2.6
#       automake:		$automake_version
#       autoconf:		$autoconf_version
#
# Report bugs to <bug-libtool@gnu.org>.

PROGRAM=ltmain.sh
PACKAGE=libtool
VERSION=2.2.6
TIMESTAMP=""
package_revision=1.3012

# Be Bourne compatible
if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
  emulate sh
  NULLCMD=:
  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
  # is contrary to our usage.  Disable this feature.
  alias -g '${1+"$@"}'='"$@"'
  setopt NO_GLOB_SUBST
else
  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
fi
BIN_SH=xpg4; export BIN_SH # for Tru64
DUALCASE=1; export DUALCASE # for MKS sh

# NLS nuisances: We save the old values to restore during execute mode.
# Only set LANG and LC_ALL to C if already set.
# These must not be set unconditionally because not all systems understand
# e.g. LANG=C (notably SCO).
lt_user_locale=
lt_safe_locale=
for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
do
  eval "if test \"\${$lt_var+set}\" = set; then
          save_$lt_var=\$$lt_var
          $lt_var=C
	  export $lt_var
	  lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\"
	  lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\"
	fi"
done

$lt_unset CDPATH





: ${CP="cp -f"}
: ${ECHO="echo"}
: ${EGREP="/usr/bin/grep -E"}
: ${FGREP="/usr/bin/grep -F"}
: ${GREP="/usr/bin/grep"}
: ${LN_S="ln -s"}
: ${MAKE="make"}
: ${MKDIR="mkdir"}
: ${MV="mv -f"}
: ${RM="rm -f"}
: ${SED="/opt/local/bin/gsed"}
: ${SHELL="${CONFIG_SHELL-/bin/sh}"}
: ${Xsed="$SED -e 1s/^X//"}

# Global variables:
EXIT_SUCCESS=0
EXIT_FAILURE=1
EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.

exit_status=$EXIT_SUCCESS

# Make sure IFS has a sensible default
lt_nl='
'
IFS=" 	$lt_nl"

dirname="s,/[^/]*$,,"
basename="s,^.*/,,"

# func_dirname_and_basename file append nondir_replacement
# perform func_basename and func_dirname in a single function
# call:
#   dirname:  Compute the dirname of FILE.  If nonempty,
#             add APPEND to the result, otherwise set result
#             to NONDIR_REPLACEMENT.
#             value returned in "$func_dirname_result"
#   basename: Compute filename of FILE.
#             value retuned in "$func_basename_result"
# Implementation must be kept synchronized with func_dirname
# and func_basename. For efficiency, we do not delegate to
# those functions but instead duplicate the functionality here.
func_dirname_and_basename ()
{
  # Extract subdirectory from the argument.
  func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"`
  if test "X$func_dirname_result" = "X${1}"; then
    func_dirname_result="${3}"
  else
    func_dirname_result="$func_dirname_result${2}"
  fi
  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
}

# Generated shell functions inserted here.

# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
# is ksh but when the shell is invoked as "sh" and the current value of
# the _XPG environment variable is not equal to 1 (one), the special
# positional parameter $0, within a function call, is the name of the
# function.
progpath="$0"

# The name of this program:
# In the unlikely event $progname began with a '-', it would play havoc with
# func_echo (imagine progname=-n), so we prepend ./ in that case:
func_dirname_and_basename "$progpath"
progname=$func_basename_result
case $progname in
  -*) progname=./$progname ;;
esac

# Make sure we have an absolute path for reexecution:
case $progpath in
  [\\/]*|[A-Za-z]:\\*) ;;
  *[\\/]*)
     progdir=$func_dirname_result
     progdir=`cd "$progdir" && pwd`
     progpath="$progdir/$progname"
     ;;
  *)
     save_IFS="$IFS"
     IFS=:
     for progdir in $PATH; do
       IFS="$save_IFS"
       test -x "$progdir/$progname" && break
     done
     IFS="$save_IFS"
     test -n "$progdir" || progdir=`pwd`
     progpath="$progdir/$progname"
     ;;
esac

# Sed substitution that helps us do robust quoting.  It backslashifies
# metacharacters that are still active within double-quoted strings.
Xsed="${SED}"' -e 1s/^X//'
sed_quote_subst='s/\([`"$\\]\)/\\\1/g'

# Same as above, but do not quote variable references.
double_quote_subst='s/\(["`\\]\)/\\\1/g'

# Re-`\' parameter expansions in output of double_quote_subst that were
# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
# in input to double_quote_subst, that '$' was protected from expansion.
# Since each input `\' is now two `\'s, look for any number of runs of
# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
bs='\\'
bs2='\\\\'
bs4='\\\\\\\\'
dollar='\$'
sed_double_backslash="\
  s/$bs4/&\\
/g
  s/^$bs2$dollar/$bs&/
  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
  s/\n//g"

# Standard options:
opt_dry_run=false
opt_help=false
opt_quiet=false
opt_verbose=false
opt_warning=:

# func_echo arg...
# Echo program name prefixed message, along with the current mode
# name if it has been set yet.
func_echo ()
{
    $ECHO "$progname${mode+: }$mode: $*"
}

# func_verbose arg...
# Echo program name prefixed message in verbose mode only.
func_verbose ()
{
    $opt_verbose && func_echo ${1+"$@"}

    # A bug in bash halts the script if the last line of a function
    # fails when set -e is in force, so we need another command to
    # work around that:
    :
}

# func_error arg...
# Echo program name prefixed message to standard error.
func_error ()
{
    $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2
}

# func_warning arg...
# Echo program name prefixed warning message to standard error.
func_warning ()
{
    $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2

    # bash bug again:
    :
}

# func_fatal_error arg...
# Echo program name prefixed message to standard error, and exit.
func_fatal_error ()
{
    func_error ${1+"$@"}
    exit $EXIT_FAILURE
}

# func_fatal_help arg...
# Echo program name prefixed message to standard error, followed by
# a help hint, and exit.
func_fatal_help ()
{
    func_error ${1+"$@"}
    func_fatal_error "$help"
}
help="Try \`$progname --help' for more information."  ## default


# func_grep expression filename
# Check whether EXPRESSION matches any line of FILENAME, without output.
func_grep ()
{
    $GREP "$1" "$2" >/dev/null 2>&1
}


# func_mkdir_p directory-path
# Make sure the entire path to DIRECTORY-PATH is available.
func_mkdir_p ()
{
    my_directory_path="$1"
    my_dir_list=

    if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then

      # Protect directory names starting with `-'
      case $my_directory_path in
        -*) my_directory_path="./$my_directory_path" ;;
      esac

      # While some portion of DIR does not yet exist...
      while test ! -d "$my_directory_path"; do
        # ...make a list in topmost first order.  Use a colon delimited
	# list incase some portion of path contains whitespace.
        my_dir_list="$my_directory_path:$my_dir_list"

        # If the last portion added has no slash in it, the list is done
        case $my_directory_path in */*) ;; *) break ;; esac

        # ...otherwise throw away the child directory and loop
        my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"`
      done
      my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'`

      save_mkdir_p_IFS="$IFS"; IFS=':'
      for my_dir in $my_dir_list; do
	IFS="$save_mkdir_p_IFS"
        # mkdir can fail with a `File exist' error if two processes
        # try to create one of the directories concurrently.  Don't
        # stop in that case!
        $MKDIR "$my_dir" 2>/dev/null || :
      done
      IFS="$save_mkdir_p_IFS"

      # Bail out if we (or some other process) failed to create a directory.
      test -d "$my_directory_path" || \
        func_fatal_error "Failed to create \`$1'"
    fi
}


# func_mktempdir [string]
# Make a temporary directory that won't clash with other running
# libtool processes, and avoids race conditions if possible.  If
# given, STRING is the basename for that directory.
func_mktempdir ()
{
    my_template="${TMPDIR-/tmp}/${1-$progname}"

    if test "$opt_dry_run" = ":"; then
      # Return a directory name, but don't create it in dry-run mode
      my_tmpdir="${my_template}-$$"
    else

      # If mktemp works, use that first and foremost
      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`

      if test ! -d "$my_tmpdir"; then
        # Failing that, at least try and use $RANDOM to avoid a race
        my_tmpdir="${my_template}-${RANDOM-0}$$"

        save_mktempdir_umask=`umask`
        umask 0077
        $MKDIR "$my_tmpdir"
        umask $save_mktempdir_umask
      fi

      # If we're not in dry-run mode, bomb out on failure
      test -d "$my_tmpdir" || \
        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
    fi

    $ECHO "X$my_tmpdir" | $Xsed
}


# func_quote_for_eval arg
# Aesthetically quote ARG to be evaled later.
# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
# is double-quoted, suitable for a subsequent eval, whereas
# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
# which are still active within double quotes backslashified.
func_quote_for_eval ()
{
    case $1 in
      *[\\\`\"\$]*)
	func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;;
      *)
        func_quote_for_eval_unquoted_result="$1" ;;
    esac

    case $func_quote_for_eval_unquoted_result in
      # Double-quote args containing shell metacharacters to delay
      # word splitting, command substitution and and variable
      # expansion for a subsequent eval.
      # Many Bourne shells cannot handle close brackets correctly
      # in scan sets, so we specify it separately.
      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
        func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\""
        ;;
      *)
        func_quote_for_eval_result="$func_quote_for_eval_unquoted_result"
    esac
}


# func_quote_for_expand arg
# Aesthetically quote ARG to be evaled later; same as above,
# but do not quote variable references.
func_quote_for_expand ()
{
    case $1 in
      *[\\\`\"]*)
	my_arg=`$ECHO "X$1" | $Xsed \
	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
      *)
        my_arg="$1" ;;
    esac

    case $my_arg in
      # Double-quote args containing shell metacharacters to delay
      # word splitting and command substitution for a subsequent eval.
      # Many Bourne shells cannot handle close brackets correctly
      # in scan sets, so we specify it separately.
      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
        my_arg="\"$my_arg\""
        ;;
    esac

    func_quote_for_expand_result="$my_arg"
}


# func_show_eval cmd [fail_exp]
# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
# is given, then evaluate it.
func_show_eval ()
{
    my_cmd="$1"
    my_fail_exp="${2-:}"

    ${opt_silent-false} || {
      func_quote_for_expand "$my_cmd"
      eval "func_echo $func_quote_for_expand_result"
    }

    if ${opt_dry_run-false}; then :; else
      eval "$my_cmd"
      my_status=$?
      if test "$my_status" -eq 0; then :; else
	eval "(exit $my_status); $my_fail_exp"
      fi
    fi
}


# func_show_eval_locale cmd [fail_exp]
# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
# is given, then evaluate it.  Use the saved locale for evaluation.
func_show_eval_locale ()
{
    my_cmd="$1"
    my_fail_exp="${2-:}"

    ${opt_silent-false} || {
      func_quote_for_expand "$my_cmd"
      eval "func_echo $func_quote_for_expand_result"
    }

    if ${opt_dry_run-false}; then :; else
      eval "$lt_user_locale
	    $my_cmd"
      my_status=$?
      eval "$lt_safe_locale"
      if test "$my_status" -eq 0; then :; else
	eval "(exit $my_status); $my_fail_exp"
      fi
    fi
}





# func_version
# Echo version message to standard output and exit.
func_version ()
{
    $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / {
        s/^# //
	s/^# *$//
        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
        p
     }' < "$progpath"
     exit $?
}

# func_usage
# Echo short help message to standard output and exit.
func_usage ()
{
    $SED -n '/^# Usage:/,/# -h/ {
        s/^# //
	s/^# *$//
	s/\$progname/'$progname'/
	p
    }' < "$progpath"
    $ECHO
    $ECHO "run \`$progname --help | more' for full usage"
    exit $?
}

# func_help
# Echo long help message to standard output and exit.
func_help ()
{
    $SED -n '/^# Usage:/,/# Report bugs to/ {
        s/^# //
	s/^# *$//
	s*\$progname*'$progname'*
	s*\$host*'"$host"'*
	s*\$SHELL*'"$SHELL"'*
	s*\$LTCC*'"$LTCC"'*
	s*\$LTCFLAGS*'"$LTCFLAGS"'*
	s*\$LD*'"$LD"'*
	s/\$with_gnu_ld/'"$with_gnu_ld"'/
	s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/
	s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/
	p
     }' < "$progpath"
    exit $?
}

# func_missing_arg argname
# Echo program name prefixed message to standard error and set global
# exit_cmd.
func_missing_arg ()
{
    func_error "missing argument for $1"
    exit_cmd=exit
}

exit_cmd=:





# Check that we have a working $ECHO.
if test "X$1" = X--no-reexec; then
  # Discard the --no-reexec flag, and continue.
  shift
elif test "X$1" = X--fallback-echo; then
  # Avoid inline document here, it may be left over
  :
elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then
  # Yippee, $ECHO works!
  :
else
  # Restart under the correct shell, and then maybe $ECHO will work.
  exec $SHELL "$progpath" --no-reexec ${1+"$@"}
fi
# Same for EGREP, and just to be sure, do LTCC as well
if test "x$EGREP" = x ; then
    EGREP=egrep
fi
if test "x$LTCC" = x ; then
    LTCC=${CC-gcc}
fi

if test "X$1" = X--fallback-echo; then
  # used as fallback echo
  shift
  cat <<EOF
$*
EOF
  exit $EXIT_SUCCESS
fi

magic="%%%MAGIC variable%%%"
magic_exe="%%%MAGIC EXE variable%%%"

# Global variables.
# $mode is unset
nonopt=
execute_dlfiles=
preserve_args=
lo2o="s/\\.lo\$/.${objext}/"
o2lo="s/\\.${objext}\$/.lo/"
extracted_archives=
extracted_serial=0

opt_dry_run=false
opt_duplicate_deps=false
opt_silent=false
opt_debug=:

# If this variable is set in any of the actions, the command in it
# will be execed at the end.  This prevents here-documents from being
# left over by shells.
exec_cmd=

# func_fatal_configuration arg...
# Echo program name prefixed message to standard error, followed by
# a configuration failure hint, and exit.
func_fatal_configuration ()
{
    func_error ${1+"$@"}
    func_error "See the $PACKAGE documentation for more information."
    func_fatal_error "Fatal configuration error."
}


# func_config
# Display the configuration for all the tags in this script.
func_config ()
{
    re_begincf='^# ### BEGIN LIBTOOL'
    re_endcf='^# ### END LIBTOOL'

    # Default configuration.
    $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath"

    # Now print the configurations for the tags.
    for tagname in $taglist; do
      $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath"
    done

    exit $?
}

# func_features
# Display the features supported by this script.
func_features ()
{
    $ECHO "host: $host"
    if test "$build_libtool_libs" = yes; then
      $ECHO "enable shared libraries"
    else
      $ECHO "disable shared libraries"
    fi
    if test "$build_old_libs" = yes; then
      $ECHO "enable static libraries"
    else
      $ECHO "disable static libraries"
    fi

    exit $?
}

# func_enable_tag tagname
# Verify that TAGNAME is valid, and either flag an error and exit, or
# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
# variable here.
func_enable_tag ()
{
  # Global variable:
  tagname="$1"

  re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
  re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
  sed_extractcf="/$re_begincf/,/$re_endcf/p"

  # Validate tagname.
  case $tagname in
    *[!-_A-Za-z0-9,/]*)
      func_fatal_error "invalid tag name: $tagname"
      ;;
  esac

  # Don't test for the "default" C tag, as we know it's
  # there but not specially marked.
  case $tagname in
    CC) ;;
    *)
      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
	taglist="$taglist $tagname"

	# Evaluate the configuration.  Be careful to quote the path
	# and the sed script, to avoid splitting on whitespace, but
	# also don't use non-portable quotes within backquotes within
	# quotes we have to do it in 2 steps:
	extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
	eval "$extractedcf"
      else
	func_error "ignoring unknown tag $tagname"
      fi
      ;;
  esac
}

# Parse options once, thoroughly.  This comes as soon as possible in
# the script to make things like `libtool --version' happen quickly.
{

  # Shorthand for --mode=foo, only valid as the first argument
  case $1 in
  clean|clea|cle|cl)
    shift; set dummy --mode clean ${1+"$@"}; shift
    ;;
  compile|compil|compi|comp|com|co|c)
    shift; set dummy --mode compile ${1+"$@"}; shift
    ;;
  execute|execut|execu|exec|exe|ex|e)
    shift; set dummy --mode execute ${1+"$@"}; shift
    ;;
  finish|finis|fini|fin|fi|f)
    shift; set dummy --mode finish ${1+"$@"}; shift
    ;;
  install|instal|insta|inst|ins|in|i)
    shift; set dummy --mode install ${1+"$@"}; shift
    ;;
  link|lin|li|l)
    shift; set dummy --mode link ${1+"$@"}; shift
    ;;
  uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
    shift; set dummy --mode uninstall ${1+"$@"}; shift
    ;;
  esac

  # Parse non-mode specific arguments:
  while test "$#" -gt 0; do
    opt="$1"
    shift

    case $opt in
      --config)		func_config					;;

      --debug)		preserve_args="$preserve_args $opt"
			func_echo "enabling shell trace mode"
			opt_debug='set -x'
			$opt_debug
			;;

      -dlopen)		test "$#" -eq 0 && func_missing_arg "$opt" && break
			execute_dlfiles="$execute_dlfiles $1"
			shift
			;;

      --dry-run | -n)	opt_dry_run=:					;;
      --features)       func_features					;;
      --finish)		mode="finish"					;;

      --mode)		test "$#" -eq 0 && func_missing_arg "$opt" && break
			case $1 in
			  # Valid mode arguments:
			  clean)	;;
			  compile)	;;
			  execute)	;;
			  finish)	;;
			  install)	;;
			  link)		;;
			  relink)	;;
			  uninstall)	;;

			  # Catch anything else as an error
			  *) func_error "invalid argument for $opt"
			     exit_cmd=exit
			     break
			     ;;
		        esac

			mode="$1"
			shift
			;;

      --preserve-dup-deps)
			opt_duplicate_deps=:				;;

      --quiet|--silent)	preserve_args="$preserve_args $opt"
			opt_silent=:
			;;

      --verbose| -v)	preserve_args="$preserve_args $opt"
			opt_silent=false
			;;

      --tag)		test "$#" -eq 0 && func_missing_arg "$opt" && break
			preserve_args="$preserve_args $opt $1"
			func_enable_tag "$1"	# tagname is set here
			shift
			;;

      # Separate optargs to long options:
      -dlopen=*|--mode=*|--tag=*)
			func_opt_split "$opt"
			set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"}
			shift
			;;

      -\?|-h)		func_usage					;;
      --help)		opt_help=:					;;
      --version)	func_version					;;

      -*)		func_fatal_help "unrecognized option \`$opt'"	;;

      *)		nonopt="$opt"
			break
			;;
    esac
  done


  case $host in
    *cygwin* | *mingw* | *pw32* | *cegcc*)
      # don't eliminate duplications in $postdeps and $predeps
      opt_duplicate_compiler_generated_deps=:
      ;;
    *)
      opt_duplicate_compiler_generated_deps=$opt_duplicate_deps
      ;;
  esac

  # Having warned about all mis-specified options, bail out if
  # anything was wrong.
  $exit_cmd $EXIT_FAILURE
}

# func_check_version_match
# Ensure that we are using m4 macros, and libtool script from the same
# release of libtool.
func_check_version_match ()
{
  if test "$package_revision" != "$macro_revision"; then
    if test "$VERSION" != "$macro_version"; then
      if test -z "$macro_version"; then
        cat >&2 <<_LT_EOF
$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
$progname: definition of this LT_INIT comes from an older release.
$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
$progname: and run autoconf again.
_LT_EOF
      else
        cat >&2 <<_LT_EOF
$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
$progname: and run autoconf again.
_LT_EOF
      fi
    else
      cat >&2 <<_LT_EOF
$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,
$progname: but the definition of this LT_INIT comes from revision $macro_revision.
$progname: You should recreate aclocal.m4 with macros from revision $package_revision
$progname: of $PACKAGE $VERSION and run autoconf again.
_LT_EOF
    fi

    exit $EXIT_MISMATCH
  fi
}


## ----------- ##
##    Main.    ##
## ----------- ##

$opt_help || {
  # Sanity checks first:
  func_check_version_match

  if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
    func_fatal_configuration "not configured to build any kind of library"
  fi

  test -z "$mode" && func_fatal_error "error: you must specify a MODE."


  # Darwin sucks
  eval std_shrext=\"$shrext_cmds\"


  # Only execute mode is allowed to have -dlopen flags.
  if test -n "$execute_dlfiles" && test "$mode" != execute; then
    func_error "unrecognized option \`-dlopen'"
    $ECHO "$help" 1>&2
    exit $EXIT_FAILURE
  fi

  # Change the help message to a mode-specific one.
  generic_help="$help"
  help="Try \`$progname --help --mode=$mode' for more information."
}


# func_lalib_p file
# True iff FILE is a libtool `.la' library or `.lo' object file.
# This function is only a basic sanity check; it will hardly flush out
# determined imposters.
func_lalib_p ()
{
    test -f "$1" &&
      $SED -e 4q "$1" 2>/dev/null \
        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
}

# func_lalib_unsafe_p file
# True iff FILE is a libtool `.la' library or `.lo' object file.
# This function implements the same check as func_lalib_p without
# resorting to external programs.  To this end, it redirects stdin and
# closes it afterwards, without saving the original file descriptor.
# As a safety measure, use it only where a negative result would be
# fatal anyway.  Works if `file' does not exist.
func_lalib_unsafe_p ()
{
    lalib_p=no
    if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then
	for lalib_p_l in 1 2 3 4
	do
	    read lalib_p_line
	    case "$lalib_p_line" in
		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;;
	    esac
	done
	exec 0<&5 5<&-
    fi
    test "$lalib_p" = yes
}

# func_ltwrapper_script_p file
# True iff FILE is a libtool wrapper script
# This function is only a basic sanity check; it will hardly flush out
# determined imposters.
func_ltwrapper_script_p ()
{
    func_lalib_p "$1"
}

# func_ltwrapper_executable_p file
# True iff FILE is a libtool wrapper executable
# This function is only a basic sanity check; it will hardly flush out
# determined imposters.
func_ltwrapper_executable_p ()
{
    func_ltwrapper_exec_suffix=
    case $1 in
    *.exe) ;;
    *) func_ltwrapper_exec_suffix=.exe ;;
    esac
    $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1
}

# func_ltwrapper_scriptname file
# Assumes file is an ltwrapper_executable
# uses $file to determine the appropriate filename for a
# temporary ltwrapper_script.
func_ltwrapper_scriptname ()
{
    func_ltwrapper_scriptname_result=""
    if func_ltwrapper_executable_p "$1"; then
	func_dirname_and_basename "$1" "" "."
	func_stripname '' '.exe' "$func_basename_result"
	func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
    fi
}

# func_ltwrapper_p file
# True iff FILE is a libtool wrapper script or wrapper executable
# This function is only a basic sanity check; it will hardly flush out
# determined imposters.
func_ltwrapper_p ()
{
    func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1"
}


# func_execute_cmds commands fail_cmd
# Execute tilde-delimited COMMANDS.
# If FAIL_CMD is given, eval that upon failure.
# FAIL_CMD may read-access the current command in variable CMD!
func_execute_cmds ()
{
    $opt_debug
    save_ifs=$IFS; IFS='~'
    for cmd in $1; do
      IFS=$save_ifs
      eval cmd=\"$cmd\"
      func_show_eval "$cmd" "${2-:}"
    done
    IFS=$save_ifs
}


# func_source file
# Source FILE, adding directory component if necessary.
# Note that it is not necessary on cygwin/mingw to append a dot to
# FILE even if both FILE and FILE.exe exist: automatic-append-.exe
# behavior happens only for exec(3), not for open(2)!  Also, sourcing
# `FILE.' does not work on cygwin managed mounts.
func_source ()
{
    $opt_debug
    case $1 in
    */* | *\\*)	. "$1" ;;
    *)		. "./$1" ;;
    esac
}


# func_infer_tag arg
# Infer tagged configuration to use if any are available and
# if one wasn't chosen via the "--tag" command line option.
# Only attempt this if the compiler in the base compile
# command doesn't match the default compiler.
# arg is usually of the form 'gcc ...'
func_infer_tag ()
{
    $opt_debug
    if test -n "$available_tags" && test -z "$tagname"; then
      CC_quoted=
      for arg in $CC; do
        func_quote_for_eval "$arg"
	CC_quoted="$CC_quoted $func_quote_for_eval_result"
      done
      case $@ in
      # Blanks in the command may have been stripped by the calling shell,
      # but not from the CC environment variable when configure was run.
      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;;
      # Blanks at the start of $base_compile will cause this to fail
      # if we don't check for them as well.
      *)
	for z in $available_tags; do
	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
	    # Evaluate the configuration.
	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
	    CC_quoted=
	    for arg in $CC; do
	      # Double-quote args containing other shell metacharacters.
	      func_quote_for_eval "$arg"
	      CC_quoted="$CC_quoted $func_quote_for_eval_result"
	    done
	    case "$@ " in
	      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*)
	      # The compiler in the base compile command matches
	      # the one in the tagged configuration.
	      # Assume this is the tagged configuration we want.
	      tagname=$z
	      break
	      ;;
	    esac
	  fi
	done
	# If $tagname still isn't set, then no tagged configuration
	# was found and let the user know that the "--tag" command
	# line option must be used.
	if test -z "$tagname"; then
	  func_echo "unable to infer tagged configuration"
	  func_fatal_error "specify a tag with \`--tag'"
#	else
#	  func_verbose "using $tagname tagged configuration"
	fi
	;;
      esac
    fi
}



# func_write_libtool_object output_name pic_name nonpic_name
# Create a libtool object file (analogous to a ".la" file),
# but don't create it if we're doing a dry run.
func_write_libtool_object ()
{
    write_libobj=${1}
    if test "$build_libtool_libs" = yes; then
      write_lobj=\'${2}\'
    else
      write_lobj=none
    fi

    if test "$build_old_libs" = yes; then
      write_oldobj=\'${3}\'
    else
      write_oldobj=none
    fi

    $opt_dry_run || {
      cat >${write_libobj}T <<EOF
# $write_libobj - a libtool object file
# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
#
# Please DO NOT delete this file!
# It is necessary for linking the library.

# Name of the PIC object.
pic_object=$write_lobj

# Name of the non-PIC object
non_pic_object=$write_oldobj

EOF
      $MV "${write_libobj}T" "${write_libobj}"
    }
}

# func_mode_compile arg...
func_mode_compile ()
{
    $opt_debug
    # Get the compilation command and the source file.
    base_compile=
    srcfile="$nonopt"  #  always keep a non-empty value in "srcfile"
    suppress_opt=yes
    suppress_output=
    arg_mode=normal
    libobj=
    later=
    pie_flag=

    for arg
    do
      case $arg_mode in
      arg  )
	# do not "continue".  Instead, add this to base_compile
	lastarg="$arg"
	arg_mode=normal
	;;

      target )
	libobj="$arg"
	arg_mode=normal
	continue
	;;

      normal )
	# Accept any command-line options.
	case $arg in
	-o)
	  test -n "$libobj" && \
	    func_fatal_error "you cannot specify \`-o' more than once"
	  arg_mode=target
	  continue
	  ;;

	-pie | -fpie | -fPIE)
          pie_flag="$pie_flag $arg"
	  continue
	  ;;

	-shared | -static | -prefer-pic | -prefer-non-pic)
	  later="$later $arg"
	  continue
	  ;;

	-no-suppress)
	  suppress_opt=no
	  continue
	  ;;

	-Xcompiler)
	  arg_mode=arg  #  the next one goes into the "base_compile" arg list
	  continue      #  The current "srcfile" will either be retained or
	  ;;            #  replaced later.  I would guess that would be a bug.

	-Wc,*)
	  func_stripname '-Wc,' '' "$arg"
	  args=$func_stripname_result
	  lastarg=
	  save_ifs="$IFS"; IFS=','
	  for arg in $args; do
	    IFS="$save_ifs"
	    func_quote_for_eval "$arg"
	    lastarg="$lastarg $func_quote_for_eval_result"
	  done
	  IFS="$save_ifs"
	  func_stripname ' ' '' "$lastarg"
	  lastarg=$func_stripname_result

	  # Add the arguments to base_compile.
	  base_compile="$base_compile $lastarg"
	  continue
	  ;;

	*)
	  # Accept the current argument as the source file.
	  # The previous "srcfile" becomes the current argument.
	  #
	  lastarg="$srcfile"
	  srcfile="$arg"
	  ;;
	esac  #  case $arg
	;;
      esac    #  case $arg_mode

      # Aesthetically quote the previous argument.
      func_quote_for_eval "$lastarg"
      base_compile="$base_compile $func_quote_for_eval_result"
    done # for arg

    case $arg_mode in
    arg)
      func_fatal_error "you must specify an argument for -Xcompile"
      ;;
    target)
      func_fatal_error "you must specify a target with \`-o'"
      ;;
    *)
      # Get the name of the library object.
      test -z "$libobj" && {
	func_basename "$srcfile"
	libobj="$func_basename_result"
      }
      ;;
    esac

    # Recognize several different file suffixes.
    # If the user specifies -o file.o, it is replaced with file.lo
    case $libobj in
    *.[cCFSifmso] | \
    *.ada | *.adb | *.ads | *.asm | \
    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
    *.[fF][09]? | *.for | *.java | *.obj | *.sx)
      func_xform "$libobj"
      libobj=$func_xform_result
      ;;
    esac

    case $libobj in
    *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;;
    *)
      func_fatal_error "cannot determine name of library object from \`$libobj'"
      ;;
    esac

    func_infer_tag $base_compile

    for arg in $later; do
      case $arg in
      -shared)
	test "$build_libtool_libs" != yes && \
	  func_fatal_configuration "can not build a shared library"
	build_old_libs=no
	continue
	;;

      -static)
	build_libtool_libs=no
	build_old_libs=yes
	continue
	;;

      -prefer-pic)
	pic_mode=yes
	continue
	;;

      -prefer-non-pic)
	pic_mode=no
	continue
	;;
      esac
    done

    func_quote_for_eval "$libobj"
    test "X$libobj" != "X$func_quote_for_eval_result" \
      && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
      && func_warning "libobj name \`$libobj' may not contain shell special characters."
    func_dirname_and_basename "$obj" "/" ""
    objname="$func_basename_result"
    xdir="$func_dirname_result"
    lobj=${xdir}$objdir/$objname

    test -z "$base_compile" && \
      func_fatal_help "you must specify a compilation command"

    # Delete any leftover library objects.
    if test "$build_old_libs" = yes; then
      removelist="$obj $lobj $libobj ${libobj}T"
    else
      removelist="$lobj $libobj ${libobj}T"
    fi

    # On Cygwin there's no "real" PIC flag so we must build both object types
    case $host_os in
    cygwin* | mingw* | pw32* | os2* | cegcc*)
      pic_mode=default
      ;;
    esac
    if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
      # non-PIC code in shared libraries is not supported
      pic_mode=default
    fi

    # Calculate the filename of the output object if compiler does
    # not support -o with -c
    if test "$compiler_c_o" = no; then
      output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
      lockfile="$output_obj.lock"
    else
      output_obj=
      need_locks=no
      lockfile=
    fi

    # Lock this critical section if it is needed
    # We use this script file to make the link, it avoids creating a new file
    if test "$need_locks" = yes; then
      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
	func_echo "Waiting for $lockfile to be removed"
	sleep 2
      done
    elif test "$need_locks" = warn; then
      if test -f "$lockfile"; then
	$ECHO "\
*** ERROR, $lockfile exists and contains:
`cat $lockfile 2>/dev/null`

This indicates that another process is trying to use the same
temporary object file, and libtool could not work around it because
your compiler does not support \`-c' and \`-o' together.  If you
repeat this compilation, it may succeed, by chance, but you had better
avoid parallel builds (make -j) in this platform, or get a better
compiler."

	$opt_dry_run || $RM $removelist
	exit $EXIT_FAILURE
      fi
      removelist="$removelist $output_obj"
      $ECHO "$srcfile" > "$lockfile"
    fi

    $opt_dry_run || $RM $removelist
    removelist="$removelist $lockfile"
    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15

    if test -n "$fix_srcfile_path"; then
      eval srcfile=\"$fix_srcfile_path\"
    fi
    func_quote_for_eval "$srcfile"
    qsrcfile=$func_quote_for_eval_result

    # Only build a PIC object if we are building libtool libraries.
    if test "$build_libtool_libs" = yes; then
      # Without this assignment, base_compile gets emptied.
      fbsd_hideous_sh_bug=$base_compile

      if test "$pic_mode" != no; then
	command="$base_compile $qsrcfile $pic_flag"
      else
	# Don't build PIC code
	command="$base_compile $qsrcfile"
      fi

      func_mkdir_p "$xdir$objdir"

      if test -z "$output_obj"; then
	# Place PIC objects in $objdir
	command="$command -o $lobj"
      fi

      func_show_eval_locale "$command"	\
          'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'

      if test "$need_locks" = warn &&
	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
	$ECHO "\
*** ERROR, $lockfile contains:
`cat $lockfile 2>/dev/null`

but it should contain:
$srcfile

This indicates that another process is trying to use the same
temporary object file, and libtool could not work around it because
your compiler does not support \`-c' and \`-o' together.  If you
repeat this compilation, it may succeed, by chance, but you had better
avoid parallel builds (make -j) in this platform, or get a better
compiler."

	$opt_dry_run || $RM $removelist
	exit $EXIT_FAILURE
      fi

      # Just move the object if needed, then go on to compile the next one
      if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
	func_show_eval '$MV "$output_obj" "$lobj"' \
	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
      fi

      # Allow error messages only from the first compilation.
      if test "$suppress_opt" = yes; then
	suppress_output=' >/dev/null 2>&1'
      fi
    fi

    # Only build a position-dependent object if we build old libraries.
    if test "$build_old_libs" = yes; then
      if test "$pic_mode" != yes; then
	# Don't build PIC code
	command="$base_compile $qsrcfile$pie_flag"
      else
	command="$base_compile $qsrcfile $pic_flag"
      fi
      if test "$compiler_c_o" = yes; then
	command="$command -o $obj"
      fi

      # Suppress compiler output if we already did a PIC compilation.
      command="$command$suppress_output"
      func_show_eval_locale "$command" \
        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'

      if test "$need_locks" = warn &&
	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
	$ECHO "\
*** ERROR, $lockfile contains:
`cat $lockfile 2>/dev/null`

but it should contain:
$srcfile

This indicates that another process is trying to use the same
temporary object file, and libtool could not work around it because
your compiler does not support \`-c' and \`-o' together.  If you
repeat this compilation, it may succeed, by chance, but you had better
avoid parallel builds (make -j) in this platform, or get a better
compiler."

	$opt_dry_run || $RM $removelist
	exit $EXIT_FAILURE
      fi

      # Just move the object if needed
      if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
	func_show_eval '$MV "$output_obj" "$obj"' \
	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
      fi
    fi

    $opt_dry_run || {
      func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"

      # Unlock the critical section if it was locked
      if test "$need_locks" != no; then
	removelist=$lockfile
        $RM "$lockfile"
      fi
    }

    exit $EXIT_SUCCESS
}

$opt_help || {
test "$mode" = compile && func_mode_compile ${1+"$@"}
}

func_mode_help ()
{
    # We need to display help for each of the modes.
    case $mode in
      "")
        # Generic help is extracted from the usage comments
        # at the start of this file.
        func_help
        ;;

      clean)
        $ECHO \
"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...

Remove files from the build directory.

RM is the name of the program to use to delete files associated with each FILE
(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
to RM.

If FILE is a libtool library, object or program, all the files associated
with it are deleted. Otherwise, only FILE itself is deleted using RM."
        ;;

      compile)
      $ECHO \
"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE

Compile a source file into a libtool library object.

This mode accepts the following additional options:

  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
  -no-suppress      do not suppress compiler output for multiple passes
  -prefer-pic       try to building PIC objects only
  -prefer-non-pic   try to building non-PIC objects only
  -shared           do not build a \`.o' file suitable for static linking
  -static           only build a \`.o' file suitable for static linking

COMPILE-COMMAND is a command to be used in creating a \`standard' object file
from the given SOURCEFILE.

The output file name is determined by removing the directory component from
SOURCEFILE, then substituting the C source code suffix \`.c' with the
library object suffix, \`.lo'."
        ;;

      execute)
        $ECHO \
"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...

Automatically set library path, then run a program.

This mode accepts the following additional options:

  -dlopen FILE      add the directory containing FILE to the library path

This mode sets the library path environment variable according to \`-dlopen'
flags.

If any of the ARGS are libtool executable wrappers, then they are translated
into their corresponding uninstalled binary, and any of their required library
directories are added to the library path.

Then, COMMAND is executed, with ARGS as arguments."
        ;;

      finish)
        $ECHO \
"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...

Complete the installation of libtool libraries.

Each LIBDIR is a directory that contains libtool libraries.

The commands that this mode executes may require superuser privileges.  Use
the \`--dry-run' option if you just want to see what would be executed."
        ;;

      install)
        $ECHO \
"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...

Install executables or libraries.

INSTALL-COMMAND is the installation command.  The first component should be
either the \`install' or \`cp' program.

The following components of INSTALL-COMMAND are treated specially:

  -inst-prefix PREFIX-DIR  Use PREFIX-DIR as a staging area for installation

The rest of the components are interpreted as arguments to that command (only
BSD-compatible install options are recognized)."
        ;;

      link)
        $ECHO \
"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...

Link object files or libraries together to form another library, or to
create an executable program.

LINK-COMMAND is a command using the C compiler that you would use to create
a program from several object files.

The following components of LINK-COMMAND are treated specially:

  -all-static       do not do any dynamic linking at all
  -avoid-version    do not add a version suffix if possible
  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
  -export-symbols SYMFILE
                    try to export only the symbols listed in SYMFILE
  -export-symbols-regex REGEX
                    try to export only the symbols matching REGEX
  -LLIBDIR          search LIBDIR for required installed libraries
  -lNAME            OUTPUT-FILE requires the installed library libNAME
  -module           build a library that can dlopened
  -no-fast-install  disable the fast-install mode
  -no-install       link a not-installable executable
  -no-undefined     declare that a library does not refer to external symbols
  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
  -objectlist FILE  Use a list of object files found in FILE to specify objects
  -precious-files-regex REGEX
                    don't remove output files matching REGEX
  -release RELEASE  specify package release information
  -rpath LIBDIR     the created library will eventually be installed in LIBDIR
  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries
  -shared           only do dynamic linking of libtool libraries
  -shrext SUFFIX    override the standard shared library file extension
  -static           do not do any dynamic linking of uninstalled libtool libraries
  -static-libtool-libs
                    do not do any dynamic linking of libtool libraries
  -version-info CURRENT[:REVISION[:AGE]]
                    specify library version info [each variable defaults to 0]
  -weak LIBNAME     declare that the target provides the LIBNAME interface

All other options (arguments beginning with \`-') are ignored.

Every other argument is treated as a filename.  Files ending in \`.la' are
treated as uninstalled libtool libraries, other files are standard or library
object files.

If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
only library objects (\`.lo' files) may be specified, and \`-rpath' is
required, except when creating a convenience library.

If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
using \`ar' and \`ranlib', or on Windows using \`lib'.

If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
is created, otherwise an executable program is created."
        ;;

      uninstall)
        $ECHO \
"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...

Remove libraries from an installation directory.

RM is the name of the program to use to delete files associated with each FILE
(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
to RM.

If FILE is a libtool library, all the files associated with it are deleted.
Otherwise, only FILE itself is deleted using RM."
        ;;

      *)
        func_fatal_help "invalid operation mode \`$mode'"
        ;;
    esac

    $ECHO
    $ECHO "Try \`$progname --help' for more information about other modes."

    exit $?
}

  # Now that we've collected a possible --mode arg, show help if necessary
  $opt_help && func_mode_help


# func_mode_execute arg...
func_mode_execute ()
{
    $opt_debug
    # The first argument is the command name.
    cmd="$nonopt"
    test -z "$cmd" && \
      func_fatal_help "you must specify a COMMAND"

    # Handle -dlopen flags immediately.
    for file in $execute_dlfiles; do
      test -f "$file" \
	|| func_fatal_help "\`$file' is not a file"

      dir=
      case $file in
      *.la)
	# Check to see that this really is a libtool archive.
	func_lalib_unsafe_p "$file" \
	  || func_fatal_help "\`$lib' is not a valid libtool archive"

	# Read the libtool library.
	dlname=
	library_names=
	func_source "$file"

	# Skip this library if it cannot be dlopened.
	if test -z "$dlname"; then
	  # Warn if it was a shared library.
	  test -n "$library_names" && \
	    func_warning "\`$file' was not linked with \`-export-dynamic'"
	  continue
	fi

	func_dirname "$file" "" "."
	dir="$func_dirname_result"

	if test -f "$dir/$objdir/$dlname"; then
	  dir="$dir/$objdir"
	else
	  if test ! -f "$dir/$dlname"; then
	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"
	  fi
	fi
	;;

      *.lo)
	# Just add the directory containing the .lo file.
	func_dirname "$file" "" "."
	dir="$func_dirname_result"
	;;

      *)
	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
	continue
	;;
      esac

      # Get the absolute pathname.
      absdir=`cd "$dir" && pwd`
      test -n "$absdir" && dir="$absdir"

      # Now add the directory to shlibpath_var.
      if eval "test -z \"\$$shlibpath_var\""; then
	eval "$shlibpath_var=\"\$dir\""
      else
	eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
      fi
    done

    # This variable tells wrapper scripts just to set shlibpath_var
    # rather than running their programs.
    libtool_execute_magic="$magic"

    # Check if any of the arguments is a wrapper script.
    args=
    for file
    do
      case $file in
      -*) ;;
      *)
	# Do a test to see if this is really a libtool program.
	if func_ltwrapper_script_p "$file"; then
	  func_source "$file"
	  # Transform arg to wrapped name.
	  file="$progdir/$program"
	elif func_ltwrapper_executable_p "$file"; then
	  func_ltwrapper_scriptname "$file"
	  func_source "$func_ltwrapper_scriptname_result"
	  # Transform arg to wrapped name.
	  file="$progdir/$program"
	fi
	;;
      esac
      # Quote arguments (to preserve shell metacharacters).
      func_quote_for_eval "$file"
      args="$args $func_quote_for_eval_result"
    done

    if test "X$opt_dry_run" = Xfalse; then
      if test -n "$shlibpath_var"; then
	# Export the shlibpath_var.
	eval "export $shlibpath_var"
      fi

      # Restore saved environment variables
      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
      do
	eval "if test \"\${save_$lt_var+set}\" = set; then
                $lt_var=\$save_$lt_var; export $lt_var
	      else
		$lt_unset $lt_var
	      fi"
      done

      # Now prepare to actually exec the command.
      exec_cmd="\$cmd$args"
    else
      # Display what would be done.
      if test -n "$shlibpath_var"; then
	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
	$ECHO "export $shlibpath_var"
      fi
      $ECHO "$cmd$args"
      exit $EXIT_SUCCESS
    fi
}

test "$mode" = execute && func_mode_execute ${1+"$@"}


# func_mode_finish arg...
func_mode_finish ()
{
    $opt_debug
    libdirs="$nonopt"
    admincmds=

    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
      for dir
      do
	libdirs="$libdirs $dir"
      done

      for libdir in $libdirs; do
	if test -n "$finish_cmds"; then
	  # Do each command in the finish commands.
	  func_execute_cmds "$finish_cmds" 'admincmds="$admincmds
'"$cmd"'"'
	fi
	if test -n "$finish_eval"; then
	  # Do the single finish_eval.
	  eval cmds=\"$finish_eval\"
	  $opt_dry_run || eval "$cmds" || admincmds="$admincmds
       $cmds"
	fi
      done
    fi

    # Exit here if they wanted silent mode.
    $opt_silent && exit $EXIT_SUCCESS

    $ECHO "X----------------------------------------------------------------------" | $Xsed
    $ECHO "Libraries have been installed in:"
    for libdir in $libdirs; do
      $ECHO "   $libdir"
    done
    $ECHO
    $ECHO "If you ever happen to want to link against installed libraries"
    $ECHO "in a given directory, LIBDIR, you must either use libtool, and"
    $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'"
    $ECHO "flag during linking and do at least one of the following:"
    if test -n "$shlibpath_var"; then
      $ECHO "   - add LIBDIR to the \`$shlibpath_var' environment variable"
      $ECHO "     during execution"
    fi
    if test -n "$runpath_var"; then
      $ECHO "   - add LIBDIR to the \`$runpath_var' environment variable"
      $ECHO "     during linking"
    fi
    if test -n "$hardcode_libdir_flag_spec"; then
      libdir=LIBDIR
      eval flag=\"$hardcode_libdir_flag_spec\"

      $ECHO "   - use the \`$flag' linker flag"
    fi
    if test -n "$admincmds"; then
      $ECHO "   - have your system administrator run these commands:$admincmds"
    fi
    if test -f /etc/ld.so.conf; then
      $ECHO "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
    fi
    $ECHO

    $ECHO "See any operating system documentation about shared libraries for"
    case $host in
      solaris2.[6789]|solaris2.1[0-9])
        $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual"
	$ECHO "pages."
	;;
      *)
        $ECHO "more information, such as the ld(1) and ld.so(8) manual pages."
        ;;
    esac
    $ECHO "X----------------------------------------------------------------------" | $Xsed
    exit $EXIT_SUCCESS
}

test "$mode" = finish && func_mode_finish ${1+"$@"}


# func_mode_install arg...
func_mode_install ()
{
    $opt_debug
    # There may be an optional sh(1) argument at the beginning of
    # install_prog (especially on Windows NT).
    if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
       # Allow the use of GNU shtool's install command.
       $ECHO "X$nonopt" | $GREP shtool >/dev/null; then
      # Aesthetically quote it.
      func_quote_for_eval "$nonopt"
      install_prog="$func_quote_for_eval_result "
      arg=$1
      shift
    else
      install_prog=
      arg=$nonopt
    fi

    # The real first argument should be the name of the installation program.
    # Aesthetically quote it.
    func_quote_for_eval "$arg"
    install_prog="$install_prog$func_quote_for_eval_result"

    # We need to accept at least all the BSD install flags.
    dest=
    files=
    opts=
    prev=
    install_type=
    isdir=no
    stripme=
    for arg
    do
      if test -n "$dest"; then
	files="$files $dest"
	dest=$arg
	continue
      fi

      case $arg in
      -d) isdir=yes ;;
      -f)
	case " $install_prog " in
	*[\\\ /]cp\ *) ;;
	*) prev=$arg ;;
	esac
	;;
      -g | -m | -o)
	prev=$arg
	;;
      -s)
	stripme=" -s"
	continue
	;;
      -*)
	;;
      *)
	# If the previous option needed an argument, then skip it.
	if test -n "$prev"; then
	  prev=
	else
	  dest=$arg
	  continue
	fi
	;;
      esac

      # Aesthetically quote the argument.
      func_quote_for_eval "$arg"
      install_prog="$install_prog $func_quote_for_eval_result"
    done

    test -z "$install_prog" && \
      func_fatal_help "you must specify an install program"

    test -n "$prev" && \
      func_fatal_help "the \`$prev' option requires an argument"

    if test -z "$files"; then
      if test -z "$dest"; then
	func_fatal_help "no file or destination specified"
      else
	func_fatal_help "you must specify a destination"
      fi
    fi

    # Strip any trailing slash from the destination.
    func_stripname '' '/' "$dest"
    dest=$func_stripname_result

    # Check to see that the destination is a directory.
    test -d "$dest" && isdir=yes
    if test "$isdir" = yes; then
      destdir="$dest"
      destname=
    else
      func_dirname_and_basename "$dest" "" "."
      destdir="$func_dirname_result"
      destname="$func_basename_result"

      # Not a directory, so check to see that there is only one file specified.
      set dummy $files; shift
      test "$#" -gt 1 && \
	func_fatal_help "\`$dest' is not a directory"
    fi
    case $destdir in
    [\\/]* | [A-Za-z]:[\\/]*) ;;
    *)
      for file in $files; do
	case $file in
	*.lo) ;;
	*)
	  func_fatal_help "\`$destdir' must be an absolute directory name"
	  ;;
	esac
      done
      ;;
    esac

    # This variable tells wrapper scripts just to set variables rather
    # than running their programs.
    libtool_install_magic="$magic"

    staticlibs=
    future_libdirs=
    current_libdirs=
    for file in $files; do

      # Do each installation.
      case $file in
      *.$libext)
	# Do the static libraries later.
	staticlibs="$staticlibs $file"
	;;

      *.la)
	# Check to see that this really is a libtool archive.
	func_lalib_unsafe_p "$file" \
	  || func_fatal_help "\`$file' is not a valid libtool archive"

	library_names=
	old_library=
	relink_command=
	func_source "$file"

	# Add the libdir to current_libdirs if it is the destination.
	if test "X$destdir" = "X$libdir"; then
	  case "$current_libdirs " in
	  *" $libdir "*) ;;
	  *) current_libdirs="$current_libdirs $libdir" ;;
	  esac
	else
	  # Note the libdir as a future libdir.
	  case "$future_libdirs " in
	  *" $libdir "*) ;;
	  *) future_libdirs="$future_libdirs $libdir" ;;
	  esac
	fi

	func_dirname "$file" "/" ""
	dir="$func_dirname_result"
	dir="$dir$objdir"

	if test -n "$relink_command"; then
	  # Determine the prefix the user has applied to our future dir.
	  inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"`

	  # Don't allow the user to place us outside of our expected
	  # location b/c this prevents finding dependent libraries that
	  # are installed to the same prefix.
	  # At present, this check doesn't affect windows .dll's that
	  # are installed into $libdir/../bin (currently, that works fine)
	  # but it's something to keep an eye on.
	  test "$inst_prefix_dir" = "$destdir" && \
	    func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"

	  if test -n "$inst_prefix_dir"; then
	    # Stick the inst_prefix_dir data into the link command.
	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
	  else
	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"`
	  fi

	  func_warning "relinking \`$file'"
	  func_show_eval "$relink_command" \
	    'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
	fi

	# See the names of the shared library.
	set dummy $library_names; shift
	if test -n "$1"; then
	  realname="$1"
	  shift

	  srcname="$realname"
	  test -n "$relink_command" && srcname="$realname"T

	  # Install the shared library and build the symlinks.
	  func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \
	      'exit $?'
	  tstripme="$stripme"
	  case $host_os in
	  cygwin* | mingw* | pw32* | cegcc*)
	    case $realname in
	    *.dll.a)
	      tstripme=""
	      ;;
	    esac
	    ;;
	  esac
	  if test -n "$tstripme" && test -n "$striplib"; then
	    func_show_eval "$striplib $destdir/$realname" 'exit $?'
	  fi

	  if test "$#" -gt 0; then
	    # Delete the old symlinks, and create new ones.
	    # Try `ln -sf' first, because the `ln' binary might depend on
	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
	    # so we also need to try rm && ln -s.
	    for linkname
	    do
	      test "$linkname" != "$realname" \
		&& func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })"
	    done
	  fi

	  # Do each command in the postinstall commands.
	  lib="$destdir/$realname"
	  func_execute_cmds "$postinstall_cmds" 'exit $?'
	fi

	# Install the pseudo-library for information purposes.
	func_basename "$file"
	name="$func_basename_result"
	instname="$dir/$name"i
	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'

	# Maybe install the static library, too.
	test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
	;;

      *.lo)
	# Install (i.e. copy) a libtool object.

	# Figure out destination file name, if it wasn't already specified.
	if test -n "$destname"; then
	  destfile="$destdir/$destname"
	else
	  func_basename "$file"
	  destfile="$func_basename_result"
	  destfile="$destdir/$destfile"
	fi

	# Deduce the name of the destination old-style object file.
	case $destfile in
	*.lo)
	  func_lo2o "$destfile"
	  staticdest=$func_lo2o_result
	  ;;
	*.$objext)
	  staticdest="$destfile"
	  destfile=
	  ;;
	*)
	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
	  ;;
	esac

	# Install the libtool object if requested.
	test -n "$destfile" && \
	  func_show_eval "$install_prog $file $destfile" 'exit $?'

	# Install the old object if enabled.
	if test "$build_old_libs" = yes; then
	  # Deduce the name of the old-style object file.
	  func_lo2o "$file"
	  staticobj=$func_lo2o_result
	  func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?'
	fi
	exit $EXIT_SUCCESS
	;;

      *)
	# Figure out destination file name, if it wasn't already specified.
	if test -n "$destname"; then
	  destfile="$destdir/$destname"
	else
	  func_basename "$file"
	  destfile="$func_basename_result"
	  destfile="$destdir/$destfile"
	fi

	# If the file is missing, and there is a .exe on the end, strip it
	# because it is most likely a libtool script we actually want to
	# install
	stripped_ext=""
	case $file in
	  *.exe)
	    if test ! -f "$file"; then
	      func_stripname '' '.exe' "$file"
	      file=$func_stripname_result
	      stripped_ext=".exe"
	    fi
	    ;;
	esac

	# Do a test to see if this is really a libtool program.
	case $host in
	*cygwin* | *mingw*)
	    if func_ltwrapper_executable_p "$file"; then
	      func_ltwrapper_scriptname "$file"
	      wrapper=$func_ltwrapper_scriptname_result
	    else
	      func_stripname '' '.exe' "$file"
	      wrapper=$func_stripname_result
	    fi
	    ;;
	*)
	    wrapper=$file
	    ;;
	esac
	if func_ltwrapper_script_p "$wrapper"; then
	  notinst_deplibs=
	  relink_command=

	  func_source "$wrapper"

	  # Check the variables that should have been set.
	  test -z "$generated_by_libtool_version" && \
	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"

	  finalize=yes
	  for lib in $notinst_deplibs; do
	    # Check to see that each library is installed.
	    libdir=
	    if test -f "$lib"; then
	      func_source "$lib"
	    fi
	    libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
	    if test -n "$libdir" && test ! -f "$libfile"; then
	      func_warning "\`$lib' has not been installed in \`$libdir'"
	      finalize=no
	    fi
	  done

	  relink_command=
	  func_source "$wrapper"

	  outputname=
	  if test "$fast_install" = no && test -n "$relink_command"; then
	    $opt_dry_run || {
	      if test "$finalize" = yes; then
	        tmpdir=`func_mktempdir`
		func_basename "$file$stripped_ext"
		file="$func_basename_result"
	        outputname="$tmpdir/$file"
	        # Replace the output file specification.
	        relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'`

	        $opt_silent || {
	          func_quote_for_expand "$relink_command"
		  eval "func_echo $func_quote_for_expand_result"
	        }
	        if eval "$relink_command"; then :
	          else
		  func_error "error: relink \`$file' with the above command before installing it"
		  $opt_dry_run || ${RM}r "$tmpdir"
		  continue
	        fi
	        file="$outputname"
	      else
	        func_warning "cannot relink \`$file'"
	      fi
	    }
	  else
	    # Install the binary that we compiled earlier.
	    file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
	  fi
	fi

	# remove .exe since cygwin /usr/bin/install will append another
	# one anyway
	case $install_prog,$host in
	*/usr/bin/install*,*cygwin*)
	  case $file:$destfile in
	  *.exe:*.exe)
	    # this is ok
	    ;;
	  *.exe:*)
	    destfile=$destfile.exe
	    ;;
	  *:*.exe)
	    func_stripname '' '.exe' "$destfile"
	    destfile=$func_stripname_result
	    ;;
	  esac
	  ;;
	esac
	func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?'
	$opt_dry_run || if test -n "$outputname"; then
	  ${RM}r "$tmpdir"
	fi
	;;
      esac
    done

    for file in $staticlibs; do
      func_basename "$file"
      name="$func_basename_result"

      # Set up the ranlib parameters.
      oldlib="$destdir/$name"

      func_show_eval "$install_prog \$file \$oldlib" 'exit $?'

      if test -n "$stripme" && test -n "$old_striplib"; then
	func_show_eval "$old_striplib $oldlib" 'exit $?'
      fi

      # Do each command in the postinstall commands.
      func_execute_cmds "$old_postinstall_cmds" 'exit $?'
    done

    test -n "$future_libdirs" && \
      func_warning "remember to run \`$progname --finish$future_libdirs'"

    if test -n "$current_libdirs"; then
      # Maybe just do a dry run.
      $opt_dry_run && current_libdirs=" -n$current_libdirs"
      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
    else
      exit $EXIT_SUCCESS
    fi
}

test "$mode" = install && func_mode_install ${1+"$@"}


# func_generate_dlsyms outputname originator pic_p
# Extract symbols from dlprefiles and create ${outputname}S.o with
# a dlpreopen symbol table.
func_generate_dlsyms ()
{
    $opt_debug
    my_outputname="$1"
    my_originator="$2"
    my_pic_p="${3-no}"
    my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
    my_dlsyms=

    if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
      if test -n "$NM" && test -n "$global_symbol_pipe"; then
	my_dlsyms="${my_outputname}S.c"
      else
	func_error "not configured to extract global symbols from dlpreopened files"
      fi
    fi

    if test -n "$my_dlsyms"; then
      case $my_dlsyms in
      "") ;;
      *.c)
	# Discover the nlist of each of the dlfiles.
	nlist="$output_objdir/${my_outputname}.nm"

	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"

	# Parse the name list into a source file.
	func_verbose "creating $output_objdir/$my_dlsyms"

	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */
/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */

#ifdef __cplusplus
extern \"C\" {
#endif

/* External symbol declarations for the compiler. */\
"

	if test "$dlself" = yes; then
	  func_verbose "generating symbol list for \`$output'"

	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"

	  # Add our own program objects to the symbol list.
	  progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
	  for progfile in $progfiles; do
	    func_verbose "extracting global C symbols from \`$progfile'"
	    $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'"
	  done

	  if test -n "$exclude_expsyms"; then
	    $opt_dry_run || {
	      eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
	      eval '$MV "$nlist"T "$nlist"'
	    }
	  fi

	  if test -n "$export_symbols_regex"; then
	    $opt_dry_run || {
	      eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
	      eval '$MV "$nlist"T "$nlist"'
	    }
	  fi

	  # Prepare the list of exported symbols
	  if test -z "$export_symbols"; then
	    export_symbols="$output_objdir/$outputname.exp"
	    $opt_dry_run || {
	      $RM $export_symbols
	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
	      case $host in
	      *cygwin* | *mingw* | *cegcc* )
                eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
                eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
	        ;;
	      esac
	    }
	  else
	    $opt_dry_run || {
	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
	      eval '$MV "$nlist"T "$nlist"'
	      case $host in
	        *cygwin | *mingw* | *cegcc* )
	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
	          ;;
	      esac
	    }
	  fi
	fi

	for dlprefile in $dlprefiles; do
	  func_verbose "extracting global C symbols from \`$dlprefile'"
	  func_basename "$dlprefile"
	  name="$func_basename_result"
	  $opt_dry_run || {
	    eval '$ECHO ": $name " >> "$nlist"'
	    eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'"
	  }
	done

	$opt_dry_run || {
	  # Make sure we have at least an empty file.
	  test -f "$nlist" || : > "$nlist"

	  if test -n "$exclude_expsyms"; then
	    $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
	    $MV "$nlist"T "$nlist"
	  fi

	  # Try sorting and uniquifying the output.
	  if $GREP -v "^: " < "$nlist" |
	      if sort -k 3 </dev/null >/dev/null 2>&1; then
		sort -k 3
	      else
		sort +2
	      fi |
	      uniq > "$nlist"S; then
	    :
	  else
	    $GREP -v "^: " < "$nlist" > "$nlist"S
	  fi

	  if test -f "$nlist"S; then
	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
	  else
	    $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms"
	  fi

	  $ECHO >> "$output_objdir/$my_dlsyms" "\

/* The mapping between symbol names and symbols.  */
typedef struct {
  const char *name;
  void *address;
} lt_dlsymlist;
"
	  case $host in
	  *cygwin* | *mingw* | *cegcc* )
	    $ECHO >> "$output_objdir/$my_dlsyms" "\
/* DATA imports from DLLs on WIN32 con't be const, because
   runtime relocations are performed -- see ld's documentation
   on pseudo-relocs.  */"
	    lt_dlsym_const= ;;
	  *osf5*)
	    echo >> "$output_objdir/$my_dlsyms" "\
/* This system does not cope well with relocations in const data */"
	    lt_dlsym_const= ;;
	  *)
	    lt_dlsym_const=const ;;
	  esac

	  $ECHO >> "$output_objdir/$my_dlsyms" "\
extern $lt_dlsym_const lt_dlsymlist
lt_${my_prefix}_LTX_preloaded_symbols[];
$lt_dlsym_const lt_dlsymlist
lt_${my_prefix}_LTX_preloaded_symbols[] =
{\
  { \"$my_originator\", (void *) 0 },"

	  case $need_lib_prefix in
	  no)
	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms"
	    ;;
	  *)
	    eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms"
	    ;;
	  esac
	  $ECHO >> "$output_objdir/$my_dlsyms" "\
  {0, (void *) 0}
};

/* This works around a problem in FreeBSD linker */
#ifdef FREEBSD_WORKAROUND
static const void *lt_preloaded_setup() {
  return lt_${my_prefix}_LTX_preloaded_symbols;
}
#endif

#ifdef __cplusplus
}
#endif\
"
	} # !$opt_dry_run

	pic_flag_for_symtable=
	case "$compile_command " in
	*" -static "*) ;;
	*)
	  case $host in
	  # compiling the symbol table file with pic_flag works around
	  # a FreeBSD bug that causes programs to crash when -lm is
	  # linked before any other PIC object.  But we must not use
	  # pic_flag when linking with -static.  The problem exists in
	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
	  *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
	  *-*-hpux*)
	    pic_flag_for_symtable=" $pic_flag"  ;;
	  *)
	    if test "X$my_pic_p" != Xno; then
	      pic_flag_for_symtable=" $pic_flag"
	    fi
	    ;;
	  esac
	  ;;
	esac
	symtab_cflags=
	for arg in $LTCFLAGS; do
	  case $arg in
	  -pie | -fpie | -fPIE) ;;
	  *) symtab_cflags="$symtab_cflags $arg" ;;
	  esac
	done

	# Now compile the dynamic symbol file.
	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'

	# Clean up the generated files.
	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"'

	# Transform the symbol file into the correct name.
	symfileobj="$output_objdir/${my_outputname}S.$objext"
	case $host in
	*cygwin* | *mingw* | *cegcc* )
	  if test -f "$output_objdir/$my_outputname.def"; then
	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
	  else
	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
	  fi
	  ;;
	*)
	  compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
	  finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
	  ;;
	esac
	;;
      *)
	func_fatal_error "unknown suffix for \`$my_dlsyms'"
	;;
      esac
    else
      # We keep going just in case the user didn't refer to
      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
      # really was required.

      # Nullify the symbol file.
      compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
      finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
    fi
}

# func_win32_libid arg
# return the library type of file 'arg'
#
# Need a lot of goo to handle *both* DLLs and import libs
# Has to be a shell function in order to 'eat' the argument
# that is supplied when $file_magic_command is called.
func_win32_libid ()
{
  $opt_debug
  win32_libid_type="unknown"
  win32_fileres=`file -L $1 2>/dev/null`
  case $win32_fileres in
  *ar\ archive\ import\ library*) # definitely import
    win32_libid_type="x86 archive import"
    ;;
  *ar\ archive*) # could be an import, or static
    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
       $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
      win32_nmres=`eval $NM -f posix -A $1 |
	$SED -n -e '
	    1,100{
		/ I /{
		    s,.*,import,
		    p
		    q
		}
	    }'`
      case $win32_nmres in
      import*)  win32_libid_type="x86 archive import";;
      *)        win32_libid_type="x86 archive static";;
      esac
    fi
    ;;
  *DLL*)
    win32_libid_type="x86 DLL"
    ;;
  *executable*) # but shell scripts are "executable" too...
    case $win32_fileres in
    *MS\ Windows\ PE\ Intel*)
      win32_libid_type="x86 DLL"
      ;;
    esac
    ;;
  esac
  $ECHO "$win32_libid_type"
}



# func_extract_an_archive dir oldlib
func_extract_an_archive ()
{
    $opt_debug
    f_ex_an_ar_dir="$1"; shift
    f_ex_an_ar_oldlib="$1"
    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?'
    if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
     :
    else
      func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib"
    fi
}


# func_extract_archives gentop oldlib ...
func_extract_archives ()
{
    $opt_debug
    my_gentop="$1"; shift
    my_oldlibs=${1+"$@"}
    my_oldobjs=""
    my_xlib=""
    my_xabs=""
    my_xdir=""

    for my_xlib in $my_oldlibs; do
      # Extract the objects.
      case $my_xlib in
	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
	*) my_xabs=`pwd`"/$my_xlib" ;;
      esac
      func_basename "$my_xlib"
      my_xlib="$func_basename_result"
      my_xlib_u=$my_xlib
      while :; do
        case " $extracted_archives " in
	*" $my_xlib_u "*)
	  func_arith $extracted_serial + 1
	  extracted_serial=$func_arith_result
	  my_xlib_u=lt$extracted_serial-$my_xlib ;;
	*) break ;;
	esac
      done
      extracted_archives="$extracted_archives $my_xlib_u"
      my_xdir="$my_gentop/$my_xlib_u"

      func_mkdir_p "$my_xdir"

      case $host in
      *-darwin*)
	func_verbose "Extracting $my_xabs"
	# Do not bother doing anything if just a dry run
	$opt_dry_run || {
	  darwin_orig_dir=`pwd`
	  cd $my_xdir || exit $?
	  darwin_archive=$my_xabs
	  darwin_curdir=`pwd`
	  darwin_base_archive=`basename "$darwin_archive"`
	  darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true`
	  if test -n "$darwin_arches"; then
	    darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
	    darwin_arch=
	    func_verbose "$darwin_base_archive has multiple architectures $darwin_arches"
	    for darwin_arch in  $darwin_arches ; do
	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
	      cd "$darwin_curdir"
	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
	    done # $darwin_arches
            ## Okay now we've a bunch of thin objects, gotta fatten them up :)
	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u`
	    darwin_file=
	    darwin_files=
	    for darwin_file in $darwin_filelist; do
	      darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
	      $LIPO -create -output "$darwin_file" $darwin_files
	    done # $darwin_filelist
	    $RM -rf unfat-$$
	    cd "$darwin_orig_dir"
	  else
	    cd $darwin_orig_dir
	    func_extract_an_archive "$my_xdir" "$my_xabs"
	  fi # $darwin_arches
	} # !$opt_dry_run
	;;
      *)
        func_extract_an_archive "$my_xdir" "$my_xabs"
	;;
      esac
      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
    done

    func_extract_archives_result="$my_oldobjs"
}



# func_emit_wrapper_part1 [arg=no]
#
# Emit the first part of a libtool wrapper script on stdout.
# For more information, see the description associated with
# func_emit_wrapper(), below.
func_emit_wrapper_part1 ()
{
	func_emit_wrapper_part1_arg1=no
	if test -n "$1" ; then
	  func_emit_wrapper_part1_arg1=$1
	fi

	$ECHO "\
#! $SHELL

# $output - temporary wrapper script for $objdir/$outputname
# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
#
# The $output program cannot be directly executed until all the libtool
# libraries that it depends on are installed.
#
# This wrapper script should never be moved out of the build directory.
# If it is, it will not operate correctly.

# Sed substitution that helps us do robust quoting.  It backslashifies
# metacharacters that are still active within double-quoted strings.
Xsed='${SED} -e 1s/^X//'
sed_quote_subst='$sed_quote_subst'

# Be Bourne compatible
if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
  emulate sh
  NULLCMD=:
  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
  # is contrary to our usage.  Disable this feature.
  alias -g '\${1+\"\$@\"}'='\"\$@\"'
  setopt NO_GLOB_SUBST
else
  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
fi
BIN_SH=xpg4; export BIN_SH # for Tru64
DUALCASE=1; export DUALCASE # for MKS sh

# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH

relink_command=\"$relink_command\"

# This environment variable determines our operation mode.
if test \"\$libtool_install_magic\" = \"$magic\"; then
  # install mode needs the following variables:
  generated_by_libtool_version='$macro_version'
  notinst_deplibs='$notinst_deplibs'
else
  # When we are sourced in execute mode, \$file and \$ECHO are already set.
  if test \"\$libtool_execute_magic\" != \"$magic\"; then
    ECHO=\"$qecho\"
    file=\"\$0\"
    # Make sure echo works.
    if test \"X\$1\" = X--no-reexec; then
      # Discard the --no-reexec flag, and continue.
      shift
    elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then
      # Yippee, \$ECHO works!
      :
    else
      # Restart under the correct shell, and then maybe \$ECHO will work.
      exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
    fi
  fi\
"
	$ECHO "\

  # Find the directory that this script lives in.
  thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
  test \"x\$thisdir\" = \"x\$file\" && thisdir=.

  # Follow symbolic links until we get to the real thisdir.
  file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
  while test -n \"\$file\"; do
    destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`

    # If there was a directory component, then change thisdir.
    if test \"x\$destdir\" != \"x\$file\"; then
      case \"\$destdir\" in
      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
      *) thisdir=\"\$thisdir/\$destdir\" ;;
      esac
    fi

    file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
    file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
  done
"
}
# end: func_emit_wrapper_part1

# func_emit_wrapper_part2 [arg=no]
#
# Emit the second part of a libtool wrapper script on stdout.
# For more information, see the description associated with
# func_emit_wrapper(), below.
func_emit_wrapper_part2 ()
{
	func_emit_wrapper_part2_arg1=no
	if test -n "$1" ; then
	  func_emit_wrapper_part2_arg1=$1
	fi

	$ECHO "\

  # Usually 'no', except on cygwin/mingw when embedded into
  # the cwrapper.
  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1
  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
    # special case for '.'
    if test \"\$thisdir\" = \".\"; then
      thisdir=\`pwd\`
    fi
    # remove .libs from thisdir
    case \"\$thisdir\" in
    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;;
    $objdir )   thisdir=. ;;
    esac
  fi

  # Try to get the absolute directory name.
  absdir=\`cd \"\$thisdir\" && pwd\`
  test -n \"\$absdir\" && thisdir=\"\$absdir\"
"

	if test "$fast_install" = yes; then
	  $ECHO "\
  program=lt-'$outputname'$exeext
  progdir=\"\$thisdir/$objdir\"

  if test ! -f \"\$progdir/\$program\" ||
     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
       test \"X\$file\" != \"X\$progdir/\$program\"; }; then

    file=\"\$\$-\$program\"

    if test ! -d \"\$progdir\"; then
      $MKDIR \"\$progdir\"
    else
      $RM \"\$progdir/\$file\"
    fi"

	  $ECHO "\

    # relink executable if necessary
    if test -n \"\$relink_command\"; then
      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
      else
	$ECHO \"\$relink_command_output\" >&2
	$RM \"\$progdir/\$file\"
	exit 1
      fi
    fi

    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
    { $RM \"\$progdir/\$program\";
      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
    $RM \"\$progdir/\$file\"
  fi"
	else
	  $ECHO "\
  program='$outputname'
  progdir=\"\$thisdir/$objdir\"
"
	fi

	$ECHO "\

  if test -f \"\$progdir/\$program\"; then"

	# Export our shlibpath_var if we have one.
	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
	  $ECHO "\
    # Add our own library path to $shlibpath_var
    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"

    # Some systems cannot cope with colon-terminated $shlibpath_var
    # The second colon is a workaround for a bug in BeOS R4 sed
    $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`

    export $shlibpath_var
"
	fi

	# fixup the dll searchpath if we need to.
	if test -n "$dllsearchpath"; then
	  $ECHO "\
    # Add the dll search path components to the executable PATH
    PATH=$dllsearchpath:\$PATH
"
	fi

	$ECHO "\
    if test \"\$libtool_execute_magic\" != \"$magic\"; then
      # Run the actual program with our arguments.
"
	case $host in
	# Backslashes separate directories on plain windows
	*-*-mingw | *-*-os2* | *-cegcc*)
	  $ECHO "\
      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
"
	  ;;

	*)
	  $ECHO "\
      exec \"\$progdir/\$program\" \${1+\"\$@\"}
"
	  ;;
	esac
	$ECHO "\
      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
      exit 1
    fi
  else
    # The program doesn't exist.
    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
    $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
    exit 1
  fi
fi\
"
}
# end: func_emit_wrapper_part2


# func_emit_wrapper [arg=no]
#
# Emit a libtool wrapper script on stdout.
# Don't directly open a file because we may want to
# incorporate the script contents within a cygwin/mingw
# wrapper executable.  Must ONLY be called from within
# func_mode_link because it depends on a number of variables
# set therein.
#
# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
# variable will take.  If 'yes', then the emitted script
# will assume that the directory in which it is stored is
# the $objdir directory.  This is a cygwin/mingw-specific
# behavior.
func_emit_wrapper ()
{
	func_emit_wrapper_arg1=no
	if test -n "$1" ; then
	  func_emit_wrapper_arg1=$1
	fi

	# split this up so that func_emit_cwrapperexe_src
	# can call each part independently.
	func_emit_wrapper_part1 "${func_emit_wrapper_arg1}"
	func_emit_wrapper_part2 "${func_emit_wrapper_arg1}"
}


# func_to_host_path arg
#
# Convert paths to host format when used with build tools.
# Intended for use with "native" mingw (where libtool itself
# is running under the msys shell), or in the following cross-
# build environments:
#    $build          $host
#    mingw (msys)    mingw  [e.g. native]
#    cygwin          mingw
#    *nix + wine     mingw
# where wine is equipped with the `winepath' executable.
# In the native mingw case, the (msys) shell automatically
# converts paths for any non-msys applications it launches,
# but that facility isn't available from inside the cwrapper.
# Similar accommodations are necessary for $host mingw and
# $build cygwin.  Calling this function does no harm for other
# $host/$build combinations not listed above.
#
# ARG is the path (on $build) that should be converted to
# the proper representation for $host. The result is stored
# in $func_to_host_path_result.
func_to_host_path ()
{
  func_to_host_path_result="$1"
  if test -n "$1" ; then
    case $host in
      *mingw* )
        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
        case $build in
          *mingw* ) # actually, msys
            # awkward: cmd appends spaces to result
            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
            func_to_host_path_tmp1=`( cmd //c echo "$1" |\
              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
              $SED -e "$lt_sed_naive_backslashify"`
            ;;
          *cygwin* )
            func_to_host_path_tmp1=`cygpath -w "$1"`
            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
              $SED -e "$lt_sed_naive_backslashify"`
            ;;
          * )
            # Unfortunately, winepath does not exit with a non-zero
            # error code, so we are forced to check the contents of
            # stdout. On the other hand, if the command is not
            # found, the shell will set an exit code of 127 and print
            # *an error message* to stdout. So we must check for both
            # error code of zero AND non-empty stdout, which explains
            # the odd construction:
            func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null`
            if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then
              func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
                $SED -e "$lt_sed_naive_backslashify"`
            else
              # Allow warning below.
              func_to_host_path_result=""
            fi
            ;;
        esac
        if test -z "$func_to_host_path_result" ; then
          func_error "Could not determine host path corresponding to"
          func_error "  '$1'"
          func_error "Continuing, but uninstalled executables may not work."
          # Fallback:
          func_to_host_path_result="$1"
        fi
        ;;
    esac
  fi
}
# end: func_to_host_path

# func_to_host_pathlist arg
#
# Convert pathlists to host format when used with build tools.
# See func_to_host_path(), above. This function supports the
# following $build/$host combinations (but does no harm for
# combinations not listed here):
#    $build          $host
#    mingw (msys)    mingw  [e.g. native]
#    cygwin          mingw
#    *nix + wine     mingw
#
# Path separators are also converted from $build format to
# $host format. If ARG begins or ends with a path separator
# character, it is preserved (but converted to $host format)
# on output.
#
# ARG is a pathlist (on $build) that should be converted to
# the proper representation on $host. The result is stored
# in $func_to_host_pathlist_result.
func_to_host_pathlist ()
{
  func_to_host_pathlist_result="$1"
  if test -n "$1" ; then
    case $host in
      *mingw* )
        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
        # Remove leading and trailing path separator characters from
        # ARG. msys behavior is inconsistent here, cygpath turns them
        # into '.;' and ';.', and winepath ignores them completely.
        func_to_host_pathlist_tmp2="$1"
        # Once set for this call, this variable should not be
        # reassigned. It is used in tha fallback case.
        func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\
          $SED -e 's|^:*||' -e 's|:*$||'`
        case $build in
          *mingw* ) # Actually, msys.
            # Awkward: cmd appends spaces to result.
            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
            func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\
              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
              $SED -e "$lt_sed_naive_backslashify"`
            ;;
          *cygwin* )
            func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"`
            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
              $SED -e "$lt_sed_naive_backslashify"`
            ;;
          * )
            # unfortunately, winepath doesn't convert pathlists
            func_to_host_pathlist_result=""
            func_to_host_pathlist_oldIFS=$IFS
            IFS=:
            for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do
              IFS=$func_to_host_pathlist_oldIFS
              if test -n "$func_to_host_pathlist_f" ; then
                func_to_host_path "$func_to_host_pathlist_f"
                if test -n "$func_to_host_path_result" ; then
                  if test -z "$func_to_host_pathlist_result" ; then
                    func_to_host_pathlist_result="$func_to_host_path_result"
                  else
                    func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result"
                  fi
                fi
              fi
              IFS=:
            done
            IFS=$func_to_host_pathlist_oldIFS
            ;;
        esac
        if test -z "$func_to_host_pathlist_result" ; then
          func_error "Could not determine the host path(s) corresponding to"
          func_error "  '$1'"
          func_error "Continuing, but uninstalled executables may not work."
          # Fallback. This may break if $1 contains DOS-style drive
          # specifications. The fix is not to complicate the expression
          # below, but for the user to provide a working wine installation
          # with winepath so that path translation in the cross-to-mingw
          # case works properly.
          lt_replace_pathsep_nix_to_dos="s|:|;|g"
          func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\
            $SED -e "$lt_replace_pathsep_nix_to_dos"`
        fi
        # Now, add the leading and trailing path separators back
        case "$1" in
          :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result"
            ;;
        esac
        case "$1" in
          *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;"
            ;;
        esac
        ;;
    esac
  fi
}
# end: func_to_host_pathlist

# func_emit_cwrapperexe_src
# emit the source code for a wrapper executable on stdout
# Must ONLY be called from within func_mode_link because
# it depends on a number of variable set therein.
func_emit_cwrapperexe_src ()
{
	cat <<EOF

/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION

   The $output program cannot be directly executed until all the libtool
   libraries that it depends on are installed.

   This wrapper executable should never be moved out of the build directory.
   If it is, it will not operate correctly.

   Currently, it simply execs the wrapper *script* "$SHELL $output",
   but could eventually absorb all of the scripts functionality and
   exec $objdir/$outputname directly.
*/
EOF
	    cat <<"EOF"
#include <stdio.h>
#include <stdlib.h>
#ifdef _MSC_VER
# include <direct.h>
# include <process.h>
# include <io.h>
# define setmode _setmode
#else
# include <unistd.h>
# include <stdint.h>
# ifdef __CYGWIN__
#  include <io.h>
#  define HAVE_SETENV
#  ifdef __STRICT_ANSI__
char *realpath (const char *, char *);
int putenv (char *);
int setenv (const char *, const char *, int);
#  endif
# endif
#endif
#include <malloc.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>

#if defined(PATH_MAX)
# define LT_PATHMAX PATH_MAX
#elif defined(MAXPATHLEN)
# define LT_PATHMAX MAXPATHLEN
#else
# define LT_PATHMAX 1024
#endif

#ifndef S_IXOTH
# define S_IXOTH 0
#endif
#ifndef S_IXGRP
# define S_IXGRP 0
#endif

#ifdef _MSC_VER
# define S_IXUSR _S_IEXEC
# define stat _stat
# ifndef _INTPTR_T_DEFINED
#  define intptr_t int
# endif
#endif

#ifndef DIR_SEPARATOR
# define DIR_SEPARATOR '/'
# define PATH_SEPARATOR ':'
#endif

#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
  defined (__OS2__)
# define HAVE_DOS_BASED_FILE_SYSTEM
# define FOPEN_WB "wb"
# ifndef DIR_SEPARATOR_2
#  define DIR_SEPARATOR_2 '\\'
# endif
# ifndef PATH_SEPARATOR_2
#  define PATH_SEPARATOR_2 ';'
# endif
#endif

#ifndef DIR_SEPARATOR_2
# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
#else /* DIR_SEPARATOR_2 */
# define IS_DIR_SEPARATOR(ch) \
	(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
#endif /* DIR_SEPARATOR_2 */

#ifndef PATH_SEPARATOR_2
# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
#else /* PATH_SEPARATOR_2 */
# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
#endif /* PATH_SEPARATOR_2 */

#ifdef __CYGWIN__
# define FOPEN_WB "wb"
#endif

#ifndef FOPEN_WB
# define FOPEN_WB "w"
#endif
#ifndef _O_BINARY
# define _O_BINARY 0
#endif

#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
#define XFREE(stale) do { \
  if (stale) { free ((void *) stale); stale = 0; } \
} while (0)

#undef LTWRAPPER_DEBUGPRINTF
#if defined DEBUGWRAPPER
# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args
static void
ltwrapper_debugprintf (const char *fmt, ...)
{
    va_list args;
    va_start (args, fmt);
    (void) vfprintf (stderr, fmt, args);
    va_end (args);
}
#else
# define LTWRAPPER_DEBUGPRINTF(args)
#endif

const char *program_name = NULL;

void *xmalloc (size_t num);
char *xstrdup (const char *string);
const char *base_name (const char *name);
char *find_executable (const char *wrapper);
char *chase_symlinks (const char *pathspec);
int make_executable (const char *path);
int check_executable (const char *path);
char *strendzap (char *str, const char *pat);
void lt_fatal (const char *message, ...);
void lt_setenv (const char *name, const char *value);
char *lt_extend_str (const char *orig_value, const char *add, int to_end);
void lt_opt_process_env_set (const char *arg);
void lt_opt_process_env_prepend (const char *arg);
void lt_opt_process_env_append (const char *arg);
int lt_split_name_value (const char *arg, char** name, char** value);
void lt_update_exe_path (const char *name, const char *value);
void lt_update_lib_path (const char *name, const char *value);

static const char *script_text_part1 =
EOF

	    func_emit_wrapper_part1 yes |
	        $SED -e 's/\([\\"]\)/\\\1/g' \
	             -e 's/^/  "/' -e 's/$/\\n"/'
	    echo ";"
	    cat <<EOF

static const char *script_text_part2 =
EOF
	    func_emit_wrapper_part2 yes |
	        $SED -e 's/\([\\"]\)/\\\1/g' \
	             -e 's/^/  "/' -e 's/$/\\n"/'
	    echo ";"

	    cat <<EOF
const char * MAGIC_EXE = "$magic_exe";
const char * LIB_PATH_VARNAME = "$shlibpath_var";
EOF

	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
              func_to_host_pathlist "$temp_rpath"
	      cat <<EOF
const char * LIB_PATH_VALUE   = "$func_to_host_pathlist_result";
EOF
	    else
	      cat <<"EOF"
const char * LIB_PATH_VALUE   = "";
EOF
	    fi

	    if test -n "$dllsearchpath"; then
              func_to_host_pathlist "$dllsearchpath:"
	      cat <<EOF
const char * EXE_PATH_VARNAME = "PATH";
const char * EXE_PATH_VALUE   = "$func_to_host_pathlist_result";
EOF
	    else
	      cat <<"EOF"
const char * EXE_PATH_VARNAME = "";
const char * EXE_PATH_VALUE   = "";
EOF
	    fi

	    if test "$fast_install" = yes; then
	      cat <<EOF
const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */
EOF
	    else
	      cat <<EOF
const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */
EOF
	    fi


	    cat <<"EOF"

#define LTWRAPPER_OPTION_PREFIX         "--lt-"
#define LTWRAPPER_OPTION_PREFIX_LENGTH  5

static const size_t opt_prefix_len         = LTWRAPPER_OPTION_PREFIX_LENGTH;
static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;

static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";

static const size_t env_set_opt_len     = LTWRAPPER_OPTION_PREFIX_LENGTH + 7;
static const char *env_set_opt          = LTWRAPPER_OPTION_PREFIX "env-set";
  /* argument is putenv-style "foo=bar", value of foo is set to bar */

static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11;
static const char *env_prepend_opt      = LTWRAPPER_OPTION_PREFIX "env-prepend";
  /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */

static const size_t env_append_opt_len  = LTWRAPPER_OPTION_PREFIX_LENGTH + 10;
static const char *env_append_opt       = LTWRAPPER_OPTION_PREFIX "env-append";
  /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */

int
main (int argc, char *argv[])
{
  char **newargz;
  int  newargc;
  char *tmp_pathspec;
  char *actual_cwrapper_path;
  char *actual_cwrapper_name;
  char *target_name;
  char *lt_argv_zero;
  intptr_t rval = 127;

  int i;

  program_name = (char *) xstrdup (base_name (argv[0]));
  LTWRAPPER_DEBUGPRINTF (("(main) argv[0]      : %s\n", argv[0]));
  LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name));

  /* very simple arg parsing; don't want to rely on getopt */
  for (i = 1; i < argc; i++)
    {
      if (strcmp (argv[i], dumpscript_opt) == 0)
	{
EOF
	    case "$host" in
	      *mingw* | *cygwin* )
		# make stdout use "unix" line endings
		echo "          setmode(1,_O_BINARY);"
		;;
	      esac

	    cat <<"EOF"
	  printf ("%s", script_text_part1);
	  printf ("%s", script_text_part2);
	  return 0;
	}
    }

  newargz = XMALLOC (char *, argc + 1);
  tmp_pathspec = find_executable (argv[0]);
  if (tmp_pathspec == NULL)
    lt_fatal ("Couldn't find %s", argv[0]);
  LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n",
			  tmp_pathspec));

  actual_cwrapper_path = chase_symlinks (tmp_pathspec);
  LTWRAPPER_DEBUGPRINTF (("(main) found exe (after symlink chase) at : %s\n",
			  actual_cwrapper_path));
  XFREE (tmp_pathspec);

  actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path));
  strendzap (actual_cwrapper_path, actual_cwrapper_name);

  /* wrapper name transforms */
  strendzap (actual_cwrapper_name, ".exe");
  tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1);
  XFREE (actual_cwrapper_name);
  actual_cwrapper_name = tmp_pathspec;
  tmp_pathspec = 0;

  /* target_name transforms -- use actual target program name; might have lt- prefix */
  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));
  strendzap (target_name, ".exe");
  tmp_pathspec = lt_extend_str (target_name, ".exe", 1);
  XFREE (target_name);
  target_name = tmp_pathspec;
  tmp_pathspec = 0;

  LTWRAPPER_DEBUGPRINTF (("(main) libtool target name: %s\n",
			  target_name));
EOF

	    cat <<EOF
  newargz[0] =
    XMALLOC (char, (strlen (actual_cwrapper_path) +
		    strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1));
  strcpy (newargz[0], actual_cwrapper_path);
  strcat (newargz[0], "$objdir");
  strcat (newargz[0], "/");
EOF

	    cat <<"EOF"
  /* stop here, and copy so we don't have to do this twice */
  tmp_pathspec = xstrdup (newargz[0]);

  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */
  strcat (newargz[0], actual_cwrapper_name);

  /* DO want the lt- prefix here if it exists, so use target_name */
  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);
  XFREE (tmp_pathspec);
  tmp_pathspec = NULL;
EOF

	    case $host_os in
	      mingw*)
	    cat <<"EOF"
  {
    char* p;
    while ((p = strchr (newargz[0], '\\')) != NULL)
      {
	*p = '/';
      }
    while ((p = strchr (lt_argv_zero, '\\')) != NULL)
      {
	*p = '/';
      }
  }
EOF
	    ;;
	    esac

	    cat <<"EOF"
  XFREE (target_name);
  XFREE (actual_cwrapper_path);
  XFREE (actual_cwrapper_name);

  lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
  lt_setenv ("DUALCASE", "1");  /* for MSK sh */
  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);

  newargc=0;
  for (i = 1; i < argc; i++)
    {
      if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0)
        {
          if (argv[i][env_set_opt_len] == '=')
            {
              const char *p = argv[i] + env_set_opt_len + 1;
              lt_opt_process_env_set (p);
            }
          else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc)
            {
              lt_opt_process_env_set (argv[++i]); /* don't copy */
            }
          else
            lt_fatal ("%s missing required argument", env_set_opt);
          continue;
        }
      if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0)
        {
          if (argv[i][env_prepend_opt_len] == '=')
            {
              const char *p = argv[i] + env_prepend_opt_len + 1;
              lt_opt_process_env_prepend (p);
            }
          else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc)
            {
              lt_opt_process_env_prepend (argv[++i]); /* don't copy */
            }
          else
            lt_fatal ("%s missing required argument", env_prepend_opt);
          continue;
        }
      if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0)
        {
          if (argv[i][env_append_opt_len] == '=')
            {
              const char *p = argv[i] + env_append_opt_len + 1;
              lt_opt_process_env_append (p);
            }
          else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc)
            {
              lt_opt_process_env_append (argv[++i]); /* don't copy */
            }
          else
            lt_fatal ("%s missing required argument", env_append_opt);
          continue;
        }
      if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0)
        {
          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
             namespace, but it is not one of the ones we know about and
             have already dealt with, above (inluding dump-script), then
             report an error. Otherwise, targets might begin to believe
             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
             namespace. The first time any user complains about this, we'll
             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
             or a configure.ac-settable value.
           */
          lt_fatal ("Unrecognized option in %s namespace: '%s'",
                    ltwrapper_option_prefix, argv[i]);
        }
      /* otherwise ... */
      newargz[++newargc] = xstrdup (argv[i]);
    }
  newargz[++newargc] = NULL;

  LTWRAPPER_DEBUGPRINTF     (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>")));
  for (i = 0; i < newargc; i++)
    {
      LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d]   : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>")));
    }

EOF

	    case $host_os in
	      mingw*)
		cat <<"EOF"
  /* execv doesn't actually work on mingw as expected on unix */
  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
  if (rval == -1)
    {
      /* failed to start process */
      LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno));
      return 127;
    }
  return rval;
EOF
		;;
	      *)
		cat <<"EOF"
  execv (lt_argv_zero, newargz);
  return rval; /* =127, but avoids unused variable warning */
EOF
		;;
	    esac

	    cat <<"EOF"
}

void *
xmalloc (size_t num)
{
  void *p = (void *) malloc (num);
  if (!p)
    lt_fatal ("Memory exhausted");

  return p;
}

char *
xstrdup (const char *string)
{
  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),
			  string) : NULL;
}

const char *
base_name (const char *name)
{
  const char *base;

#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
  /* Skip over the disk name in MSDOS pathnames. */
  if (isalpha ((unsigned char) name[0]) && name[1] == ':')
    name += 2;
#endif

  for (base = name; *name; name++)
    if (IS_DIR_SEPARATOR (*name))
      base = name + 1;
  return base;
}

int
check_executable (const char *path)
{
  struct stat st;

  LTWRAPPER_DEBUGPRINTF (("(check_executable)  : %s\n",
			  path ? (*path ? path : "EMPTY!") : "NULL!"));
  if ((!path) || (!*path))
    return 0;

  if ((stat (path, &st) >= 0)
      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
    return 1;
  else
    return 0;
}

int
make_executable (const char *path)
{
  int rval = 0;
  struct stat st;

  LTWRAPPER_DEBUGPRINTF (("(make_executable)   : %s\n",
			  path ? (*path ? path : "EMPTY!") : "NULL!"));
  if ((!path) || (!*path))
    return 0;

  if (stat (path, &st) >= 0)
    {
      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);
    }
  return rval;
}

/* Searches for the full path of the wrapper.  Returns
   newly allocated full path name if found, NULL otherwise
   Does not chase symlinks, even on platforms that support them.
*/
char *
find_executable (const char *wrapper)
{
  int has_slash = 0;
  const char *p;
  const char *p_next;
  /* static buffer for getcwd */
  char tmp[LT_PATHMAX + 1];
  int tmp_len;
  char *concat_name;

  LTWRAPPER_DEBUGPRINTF (("(find_executable)   : %s\n",
			  wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!"));

  if ((wrapper == NULL) || (*wrapper == '\0'))
    return NULL;

  /* Absolute path? */
#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')
    {
      concat_name = xstrdup (wrapper);
      if (check_executable (concat_name))
	return concat_name;
      XFREE (concat_name);
    }
  else
    {
#endif
      if (IS_DIR_SEPARATOR (wrapper[0]))
	{
	  concat_name = xstrdup (wrapper);
	  if (check_executable (concat_name))
	    return concat_name;
	  XFREE (concat_name);
	}
#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
    }
#endif

  for (p = wrapper; *p; p++)
    if (*p == '/')
      {
	has_slash = 1;
	break;
      }
  if (!has_slash)
    {
      /* no slashes; search PATH */
      const char *path = getenv ("PATH");
      if (path != NULL)
	{
	  for (p = path; *p; p = p_next)
	    {
	      const char *q;
	      size_t p_len;
	      for (q = p; *q; q++)
		if (IS_PATH_SEPARATOR (*q))
		  break;
	      p_len = q - p;
	      p_next = (*q == '\0' ? q : q + 1);
	      if (p_len == 0)
		{
		  /* empty path: current directory */
		  if (getcwd (tmp, LT_PATHMAX) == NULL)
		    lt_fatal ("getcwd failed");
		  tmp_len = strlen (tmp);
		  concat_name =
		    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
		  memcpy (concat_name, tmp, tmp_len);
		  concat_name[tmp_len] = '/';
		  strcpy (concat_name + tmp_len + 1, wrapper);
		}
	      else
		{
		  concat_name =
		    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);
		  memcpy (concat_name, p, p_len);
		  concat_name[p_len] = '/';
		  strcpy (concat_name + p_len + 1, wrapper);
		}
	      if (check_executable (concat_name))
		return concat_name;
	      XFREE (concat_name);
	    }
	}
      /* not found in PATH; assume curdir */
    }
  /* Relative path | not found in path: prepend cwd */
  if (getcwd (tmp, LT_PATHMAX) == NULL)
    lt_fatal ("getcwd failed");
  tmp_len = strlen (tmp);
  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
  memcpy (concat_name, tmp, tmp_len);
  concat_name[tmp_len] = '/';
  strcpy (concat_name + tmp_len + 1, wrapper);

  if (check_executable (concat_name))
    return concat_name;
  XFREE (concat_name);
  return NULL;
}

char *
chase_symlinks (const char *pathspec)
{
#ifndef S_ISLNK
  return xstrdup (pathspec);
#else
  char buf[LT_PATHMAX];
  struct stat s;
  char *tmp_pathspec = xstrdup (pathspec);
  char *p;
  int has_symlinks = 0;
  while (strlen (tmp_pathspec) && !has_symlinks)
    {
      LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n",
			      tmp_pathspec));
      if (lstat (tmp_pathspec, &s) == 0)
	{
	  if (S_ISLNK (s.st_mode) != 0)
	    {
	      has_symlinks = 1;
	      break;
	    }

	  /* search backwards for last DIR_SEPARATOR */
	  p = tmp_pathspec + strlen (tmp_pathspec) - 1;
	  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
	    p--;
	  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
	    {
	      /* no more DIR_SEPARATORS left */
	      break;
	    }
	  *p = '\0';
	}
      else
	{
	  char *errstr = strerror (errno);
	  lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr);
	}
    }
  XFREE (tmp_pathspec);

  if (!has_symlinks)
    {
      return xstrdup (pathspec);
    }

  tmp_pathspec = realpath (pathspec, buf);
  if (tmp_pathspec == 0)
    {
      lt_fatal ("Could not follow symlinks for %s", pathspec);
    }
  return xstrdup (tmp_pathspec);
#endif
}

char *
strendzap (char *str, const char *pat)
{
  size_t len, patlen;

  assert (str != NULL);
  assert (pat != NULL);

  len = strlen (str);
  patlen = strlen (pat);

  if (patlen <= len)
    {
      str += len - patlen;
      if (strcmp (str, pat) == 0)
	*str = '\0';
    }
  return str;
}

static void
lt_error_core (int exit_status, const char *mode,
	       const char *message, va_list ap)
{
  fprintf (stderr, "%s: %s: ", program_name, mode);
  vfprintf (stderr, message, ap);
  fprintf (stderr, ".\n");

  if (exit_status >= 0)
    exit (exit_status);
}

void
lt_fatal (const char *message, ...)
{
  va_list ap;
  va_start (ap, message);
  lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
  va_end (ap);
}

void
lt_setenv (const char *name, const char *value)
{
  LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n",
                          (name ? name : "<NULL>"),
                          (value ? value : "<NULL>")));
  {
#ifdef HAVE_SETENV
    /* always make a copy, for consistency with !HAVE_SETENV */
    char *str = xstrdup (value);
    setenv (name, str, 1);
#else
    int len = strlen (name) + 1 + strlen (value) + 1;
    char *str = XMALLOC (char, len);
    sprintf (str, "%s=%s", name, value);
    if (putenv (str) != EXIT_SUCCESS)
      {
        XFREE (str);
      }
#endif
  }
}

char *
lt_extend_str (const char *orig_value, const char *add, int to_end)
{
  char *new_value;
  if (orig_value && *orig_value)
    {
      int orig_value_len = strlen (orig_value);
      int add_len = strlen (add);
      new_value = XMALLOC (char, add_len + orig_value_len + 1);
      if (to_end)
        {
          strcpy (new_value, orig_value);
          strcpy (new_value + orig_value_len, add);
        }
      else
        {
          strcpy (new_value, add);
          strcpy (new_value + add_len, orig_value);
        }
    }
  else
    {
      new_value = xstrdup (add);
    }
  return new_value;
}

int
lt_split_name_value (const char *arg, char** name, char** value)
{
  const char *p;
  int len;
  if (!arg || !*arg)
    return 1;

  p = strchr (arg, (int)'=');

  if (!p)
    return 1;

  *value = xstrdup (++p);

  len = strlen (arg) - strlen (*value);
  *name = XMALLOC (char, len);
  strncpy (*name, arg, len-1);
  (*name)[len - 1] = '\0';

  return 0;
}

void
lt_opt_process_env_set (const char *arg)
{
  char *name = NULL;
  char *value = NULL;

  if (lt_split_name_value (arg, &name, &value) != 0)
    {
      XFREE (name);
      XFREE (value);
      lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg);
    }

  lt_setenv (name, value);
  XFREE (name);
  XFREE (value);
}

void
lt_opt_process_env_prepend (const char *arg)
{
  char *name = NULL;
  char *value = NULL;
  char *new_value = NULL;

  if (lt_split_name_value (arg, &name, &value) != 0)
    {
      XFREE (name);
      XFREE (value);
      lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg);
    }

  new_value = lt_extend_str (getenv (name), value, 0);
  lt_setenv (name, new_value);
  XFREE (new_value);
  XFREE (name);
  XFREE (value);
}

void
lt_opt_process_env_append (const char *arg)
{
  char *name = NULL;
  char *value = NULL;
  char *new_value = NULL;

  if (lt_split_name_value (arg, &name, &value) != 0)
    {
      XFREE (name);
      XFREE (value);
      lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg);
    }

  new_value = lt_extend_str (getenv (name), value, 1);
  lt_setenv (name, new_value);
  XFREE (new_value);
  XFREE (name);
  XFREE (value);
}

void
lt_update_exe_path (const char *name, const char *value)
{
  LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
                          (name ? name : "<NULL>"),
                          (value ? value : "<NULL>")));

  if (name && *name && value && *value)
    {
      char *new_value = lt_extend_str (getenv (name), value, 0);
      /* some systems can't cope with a ':'-terminated path #' */
      int len = strlen (new_value);
      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
        {
          new_value[len-1] = '\0';
        }
      lt_setenv (name, new_value);
      XFREE (new_value);
    }
}

void
lt_update_lib_path (const char *name, const char *value)
{
  LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
                          (name ? name : "<NULL>"),
                          (value ? value : "<NULL>")));

  if (name && *name && value && *value)
    {
      char *new_value = lt_extend_str (getenv (name), value, 0);
      lt_setenv (name, new_value);
      XFREE (new_value);
    }
}


EOF
}
# end: func_emit_cwrapperexe_src

# func_mode_link arg...
func_mode_link ()
{
    $opt_debug
    case $host in
    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
      # It is impossible to link a dll without this setting, and
      # we shouldn't force the makefile maintainer to figure out
      # which system we are compiling for in order to pass an extra
      # flag for every libtool invocation.
      # allow_undefined=no

      # FIXME: Unfortunately, there are problems with the above when trying
      # to make a dll which has undefined symbols, in which case not
      # even a static library is built.  For now, we need to specify
      # -no-undefined on the libtool link line when we can be certain
      # that all symbols are satisfied, otherwise we get a static library.
      allow_undefined=yes
      ;;
    *)
      allow_undefined=yes
      ;;
    esac
    libtool_args=$nonopt
    base_compile="$nonopt $@"
    compile_command=$nonopt
    finalize_command=$nonopt

    compile_rpath=
    finalize_rpath=
    compile_shlibpath=
    finalize_shlibpath=
    convenience=
    old_convenience=
    deplibs=
    old_deplibs=
    compiler_flags=
    linker_flags=
    dllsearchpath=
    lib_search_path=`pwd`
    inst_prefix_dir=
    new_inherited_linker_flags=

    avoid_version=no
    dlfiles=
    dlprefiles=
    dlself=no
    export_dynamic=no
    export_symbols=
    export_symbols_regex=
    generated=
    libobjs=
    ltlibs=
    module=no
    no_install=no
    objs=
    non_pic_objects=
    precious_files_regex=
    prefer_static_libs=no
    preload=no
    prev=
    prevarg=
    release=
    rpath=
    xrpath=
    perm_rpath=
    temp_rpath=
    thread_safe=no
    vinfo=
    vinfo_number=no
    weak_libs=
    single_module="${wl}-single_module"
    func_infer_tag $base_compile

    # We need to know -static, to get the right output filenames.
    for arg
    do
      case $arg in
      -shared)
	test "$build_libtool_libs" != yes && \
	  func_fatal_configuration "can not build a shared library"
	build_old_libs=no
	break
	;;
      -all-static | -static | -static-libtool-libs)
	case $arg in
	-all-static)
	  if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
	    func_warning "complete static linking is impossible in this configuration"
	  fi
	  if test -n "$link_static_flag"; then
	    dlopen_self=$dlopen_self_static
	  fi
	  prefer_static_libs=yes
	  ;;
	-static)
	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
	    dlopen_self=$dlopen_self_static
	  fi
	  prefer_static_libs=built
	  ;;
	-static-libtool-libs)
	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
	    dlopen_self=$dlopen_self_static
	  fi
	  prefer_static_libs=yes
	  ;;
	esac
	build_libtool_libs=no
	build_old_libs=yes
	break
	;;
      esac
    done

    # See if our shared archives depend on static archives.
    test -n "$old_archive_from_new_cmds" && build_old_libs=yes

    # Go through the arguments, transforming them on the way.
    while test "$#" -gt 0; do
      arg="$1"
      shift
      func_quote_for_eval "$arg"
      qarg=$func_quote_for_eval_unquoted_result
      func_append libtool_args " $func_quote_for_eval_result"

      # If the previous option needs an argument, assign it.
      if test -n "$prev"; then
	case $prev in
	output)
	  func_append compile_command " @OUTPUT@"
	  func_append finalize_command " @OUTPUT@"
	  ;;
	esac

	case $prev in
	dlfiles|dlprefiles)
	  if test "$preload" = no; then
	    # Add the symbol object into the linking commands.
	    func_append compile_command " @SYMFILE@"
	    func_append finalize_command " @SYMFILE@"
	    preload=yes
	  fi
	  case $arg in
	  *.la | *.lo) ;;  # We handle these cases below.
	  force)
	    if test "$dlself" = no; then
	      dlself=needless
	      export_dynamic=yes
	    fi
	    prev=
	    continue
	    ;;
	  self)
	    if test "$prev" = dlprefiles; then
	      dlself=yes
	    elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
	      dlself=yes
	    else
	      dlself=needless
	      export_dynamic=yes
	    fi
	    prev=
	    continue
	    ;;
	  *)
	    if test "$prev" = dlfiles; then
	      dlfiles="$dlfiles $arg"
	    else
	      dlprefiles="$dlprefiles $arg"
	    fi
	    prev=
	    continue
	    ;;
	  esac
	  ;;
	expsyms)
	  export_symbols="$arg"
	  test -f "$arg" \
	    || func_fatal_error "symbol file \`$arg' does not exist"
	  prev=
	  continue
	  ;;
	expsyms_regex)
	  export_symbols_regex="$arg"
	  prev=
	  continue
	  ;;
	framework)
	  case $host in
	    *-*-darwin*)
	      case "$deplibs " in
		*" $qarg.ltframework "*) ;;
		*) deplibs="$deplibs $qarg.ltframework" # this is fixed later
		   ;;
	      esac
	      ;;
	  esac
	  prev=
	  continue
	  ;;
	inst_prefix)
	  inst_prefix_dir="$arg"
	  prev=
	  continue
	  ;;
	objectlist)
	  if test -f "$arg"; then
	    save_arg=$arg
	    moreargs=
	    for fil in `cat "$save_arg"`
	    do
#	      moreargs="$moreargs $fil"
	      arg=$fil
	      # A libtool-controlled object.

	      # Check to see that this really is a libtool object.
	      if func_lalib_unsafe_p "$arg"; then
		pic_object=
		non_pic_object=

		# Read the .lo file
		func_source "$arg"

		if test -z "$pic_object" ||
		   test -z "$non_pic_object" ||
		   test "$pic_object" = none &&
		   test "$non_pic_object" = none; then
		  func_fatal_error "cannot find name of object for \`$arg'"
		fi

		# Extract subdirectory from the argument.
		func_dirname "$arg" "/" ""
		xdir="$func_dirname_result"

		if test "$pic_object" != none; then
		  # Prepend the subdirectory the object is found in.
		  pic_object="$xdir$pic_object"

		  if test "$prev" = dlfiles; then
		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
		      dlfiles="$dlfiles $pic_object"
		      prev=
		      continue
		    else
		      # If libtool objects are unsupported, then we need to preload.
		      prev=dlprefiles
		    fi
		  fi

		  # CHECK ME:  I think I busted this.  -Ossama
		  if test "$prev" = dlprefiles; then
		    # Preload the old-style object.
		    dlprefiles="$dlprefiles $pic_object"
		    prev=
		  fi

		  # A PIC object.
		  func_append libobjs " $pic_object"
		  arg="$pic_object"
		fi

		# Non-PIC object.
		if test "$non_pic_object" != none; then
		  # Prepend the subdirectory the object is found in.
		  non_pic_object="$xdir$non_pic_object"

		  # A standard non-PIC object
		  func_append non_pic_objects " $non_pic_object"
		  if test -z "$pic_object" || test "$pic_object" = none ; then
		    arg="$non_pic_object"
		  fi
		else
		  # If the PIC object exists, use it instead.
		  # $xdir was prepended to $pic_object above.
		  non_pic_object="$pic_object"
		  func_append non_pic_objects " $non_pic_object"
		fi
	      else
		# Only an error if not doing a dry-run.
		if $opt_dry_run; then
		  # Extract subdirectory from the argument.
		  func_dirname "$arg" "/" ""
		  xdir="$func_dirname_result"

		  func_lo2o "$arg"
		  pic_object=$xdir$objdir/$func_lo2o_result
		  non_pic_object=$xdir$func_lo2o_result
		  func_append libobjs " $pic_object"
		  func_append non_pic_objects " $non_pic_object"
	        else
		  func_fatal_error "\`$arg' is not a valid libtool object"
		fi
	      fi
	    done
	  else
	    func_fatal_error "link input file \`$arg' does not exist"
	  fi
	  arg=$save_arg
	  prev=
	  continue
	  ;;
	precious_regex)
	  precious_files_regex="$arg"
	  prev=
	  continue
	  ;;
	release)
	  release="-$arg"
	  prev=
	  continue
	  ;;
	rpath | xrpath)
	  # We need an absolute path.
	  case $arg in
	  [\\/]* | [A-Za-z]:[\\/]*) ;;
	  *)
	    func_fatal_error "only absolute run-paths are allowed"
	    ;;
	  esac
	  if test "$prev" = rpath; then
	    case "$rpath " in
	    *" $arg "*) ;;
	    *) rpath="$rpath $arg" ;;
	    esac
	  else
	    case "$xrpath " in
	    *" $arg "*) ;;
	    *) xrpath="$xrpath $arg" ;;
	    esac
	  fi
	  prev=
	  continue
	  ;;
	shrext)
	  shrext_cmds="$arg"
	  prev=
	  continue
	  ;;
	weak)
	  weak_libs="$weak_libs $arg"
	  prev=
	  continue
	  ;;
	xcclinker)
	  linker_flags="$linker_flags $qarg"
	  compiler_flags="$compiler_flags $qarg"
	  prev=
	  func_append compile_command " $qarg"
	  func_append finalize_command " $qarg"
	  continue
	  ;;
	xcompiler)
	  compiler_flags="$compiler_flags $qarg"
	  prev=
	  func_append compile_command " $qarg"
	  func_append finalize_command " $qarg"
	  continue
	  ;;
	xlinker)
	  linker_flags="$linker_flags $qarg"
	  compiler_flags="$compiler_flags $wl$qarg"
	  prev=
	  func_append compile_command " $wl$qarg"
	  func_append finalize_command " $wl$qarg"
	  continue
	  ;;
	*)
	  eval "$prev=\"\$arg\""
	  prev=
	  continue
	  ;;
	esac
      fi # test -n "$prev"

      prevarg="$arg"

      case $arg in
      -all-static)
	if test -n "$link_static_flag"; then
	  # See comment for -static flag below, for more details.
	  func_append compile_command " $link_static_flag"
	  func_append finalize_command " $link_static_flag"
	fi
	continue
	;;

      -allow-undefined)
	# FIXME: remove this flag sometime in the future.
	func_fatal_error "\`-allow-undefined' must not be used because it is the default"
	;;

      -avoid-version)
	avoid_version=yes
	continue
	;;

      -dlopen)
	prev=dlfiles
	continue
	;;

      -dlpreopen)
	prev=dlprefiles
	continue
	;;

      -export-dynamic)
	export_dynamic=yes
	continue
	;;

      -export-symbols | -export-symbols-regex)
	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
	  func_fatal_error "more than one -exported-symbols argument is not allowed"
	fi
	if test "X$arg" = "X-export-symbols"; then
	  prev=expsyms
	else
	  prev=expsyms_regex
	fi
	continue
	;;

      -framework)
	prev=framework
	continue
	;;

      -inst-prefix-dir)
	prev=inst_prefix
	continue
	;;

      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
      # so, if we see these flags be careful not to treat them like -L
      -L[A-Z][A-Z]*:*)
	case $with_gcc/$host in
	no/*-*-irix* | /*-*-irix*)
	  func_append compile_command " $arg"
	  func_append finalize_command " $arg"
	  ;;
	esac
	continue
	;;

      -L*)
	func_stripname '-L' '' "$arg"
	dir=$func_stripname_result
	if test -z "$dir"; then
	  if test "$#" -gt 0; then
	    func_fatal_error "require no space between \`-L' and \`$1'"
	  else
	    func_fatal_error "need path for \`-L' option"
	  fi
	fi
	# We need an absolute path.
	case $dir in
	[\\/]* | [A-Za-z]:[\\/]*) ;;
	*)
	  absdir=`cd "$dir" && pwd`
	  test -z "$absdir" && \
	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
	  dir="$absdir"
	  ;;
	esac
	case "$deplibs " in
	*" -L$dir "*) ;;
	*)
	  deplibs="$deplibs -L$dir"
	  lib_search_path="$lib_search_path $dir"
	  ;;
	esac
	case $host in
	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
	  testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'`
	  case :$dllsearchpath: in
	  *":$dir:"*) ;;
	  ::) dllsearchpath=$dir;;
	  *) dllsearchpath="$dllsearchpath:$dir";;
	  esac
	  case :$dllsearchpath: in
	  *":$testbindir:"*) ;;
	  ::) dllsearchpath=$testbindir;;
	  *) dllsearchpath="$dllsearchpath:$testbindir";;
	  esac
	  ;;
	esac
	continue
	;;

      -l*)
	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
	  case $host in
	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*)
	    # These systems don't actually have a C or math library (as such)
	    continue
	    ;;
	  *-*-os2*)
	    # These systems don't actually have a C library (as such)
	    test "X$arg" = "X-lc" && continue
	    ;;
	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
	    # Do not include libc due to us having libc/libc_r.
	    test "X$arg" = "X-lc" && continue
	    ;;
	  *-*-rhapsody* | *-*-darwin1.[012])
	    # Rhapsody C and math libraries are in the System framework
	    deplibs="$deplibs System.ltframework"
	    continue
	    ;;
	  *-*-sco3.2v5* | *-*-sco5v6*)
	    # Causes problems with __ctype
	    test "X$arg" = "X-lc" && continue
	    ;;
	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
	    # Compiler inserts libc in the correct place for threads to work
	    test "X$arg" = "X-lc" && continue
	    ;;
	  esac
	elif test "X$arg" = "X-lc_r"; then
	 case $host in
	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
	   # Do not include libc_r directly, use -pthread flag.
	   continue
	   ;;
	 esac
	fi
	deplibs="$deplibs $arg"
	continue
	;;

      -module)
	module=yes
	continue
	;;

      # Tru64 UNIX uses -model [arg] to determine the layout of C++
      # classes, name mangling, and exception handling.
      # Darwin uses the -arch flag to determine output architecture.
      -model|-arch|-isysroot)
	compiler_flags="$compiler_flags $arg"
	func_append compile_command " $arg"
	func_append finalize_command " $arg"
	prev=xcompiler
	continue
	;;

      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
	compiler_flags="$compiler_flags $arg"
	func_append compile_command " $arg"
	func_append finalize_command " $arg"
	case "$new_inherited_linker_flags " in
	    *" $arg "*) ;;
	    * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;;
	esac
	continue
	;;

      -multi_module)
	single_module="${wl}-multi_module"
	continue
	;;

      -no-fast-install)
	fast_install=no
	continue
	;;

      -no-install)
	case $host in
	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
	  # The PATH hackery in wrapper scripts is required on Windows
	  # and Darwin in order for the loader to find any dlls it needs.
	  func_warning "\`-no-install' is ignored for $host"
	  func_warning "assuming \`-no-fast-install' instead"
	  fast_install=no
	  ;;
	*) no_install=yes ;;
	esac
	continue
	;;

      -no-undefined)
	allow_undefined=no
	continue
	;;

      -objectlist)
	prev=objectlist
	continue
	;;

      -o) prev=output ;;

      -precious-files-regex)
	prev=precious_regex
	continue
	;;

      -release)
	prev=release
	continue
	;;

      -rpath)
	prev=rpath
	continue
	;;

      -R)
	prev=xrpath
	continue
	;;

      -R*)
	func_stripname '-R' '' "$arg"
	dir=$func_stripname_result
	# We need an absolute path.
	case $dir in
	[\\/]* | [A-Za-z]:[\\/]*) ;;
	*)
	  func_fatal_error "only absolute run-paths are allowed"
	  ;;
	esac
	case "$xrpath " in
	*" $dir "*) ;;
	*) xrpath="$xrpath $dir" ;;
	esac
	continue
	;;

      -shared)
	# The effects of -shared are defined in a previous loop.
	continue
	;;

      -shrext)
	prev=shrext
	continue
	;;

      -static | -static-libtool-libs)
	# The effects of -static are defined in a previous loop.
	# We used to do the same as -all-static on platforms that
	# didn't have a PIC flag, but the assumption that the effects
	# would be equivalent was wrong.  It would break on at least
	# Digital Unix and AIX.
	continue
	;;

      -thread-safe)
	thread_safe=yes
	continue
	;;

      -version-info)
	prev=vinfo
	continue
	;;

      -version-number)
	prev=vinfo
	vinfo_number=yes
	continue
	;;

      -weak)
        prev=weak
	continue
	;;

      -Wc,*)
	func_stripname '-Wc,' '' "$arg"
	args=$func_stripname_result
	arg=
	save_ifs="$IFS"; IFS=','
	for flag in $args; do
	  IFS="$save_ifs"
          func_quote_for_eval "$flag"
	  arg="$arg $wl$func_quote_for_eval_result"
	  compiler_flags="$compiler_flags $func_quote_for_eval_result"
	done
	IFS="$save_ifs"
	func_stripname ' ' '' "$arg"
	arg=$func_stripname_result
	;;

      -Wl,*)
	func_stripname '-Wl,' '' "$arg"
	args=$func_stripname_result
	arg=
	save_ifs="$IFS"; IFS=','
	for flag in $args; do
	  IFS="$save_ifs"
          func_quote_for_eval "$flag"
	  arg="$arg $wl$func_quote_for_eval_result"
	  compiler_flags="$compiler_flags $wl$func_quote_for_eval_result"
	  linker_flags="$linker_flags $func_quote_for_eval_result"
	done
	IFS="$save_ifs"
	func_stripname ' ' '' "$arg"
	arg=$func_stripname_result
	;;

      -Xcompiler)
	prev=xcompiler
	continue
	;;

      -Xlinker)
	prev=xlinker
	continue
	;;

      -XCClinker)
	prev=xcclinker
	continue
	;;

      # -msg_* for osf cc
      -msg_*)
	func_quote_for_eval "$arg"
	arg="$func_quote_for_eval_result"
	;;

      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
      # -r[0-9][0-9]* specifies the processor on the SGI compiler
      # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
      # +DA*, +DD* enable 64-bit mode on the HP compiler
      # -q* pass through compiler args for the IBM compiler
      # -m*, -t[45]*, -txscale* pass through architecture-specific
      # compiler args for GCC
      # -F/path gives path to uninstalled frameworks, gcc on darwin
      # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC
      # @file GCC response files
      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*)
        func_quote_for_eval "$arg"
	arg="$func_quote_for_eval_result"
        func_append compile_command " $arg"
        func_append finalize_command " $arg"
        compiler_flags="$compiler_flags $arg"
        continue
        ;;

      # Some other compiler flag.
      -* | +*)
        func_quote_for_eval "$arg"
	arg="$func_quote_for_eval_result"
	;;

      *.$objext)
	# A standard object.
	objs="$objs $arg"
	;;

      *.lo)
	# A libtool-controlled object.

	# Check to see that this really is a libtool object.
	if func_lalib_unsafe_p "$arg"; then
	  pic_object=
	  non_pic_object=

	  # Read the .lo file
	  func_source "$arg"

	  if test -z "$pic_object" ||
	     test -z "$non_pic_object" ||
	     test "$pic_object" = none &&
	     test "$non_pic_object" = none; then
	    func_fatal_error "cannot find name of object for \`$arg'"
	  fi

	  # Extract subdirectory from the argument.
	  func_dirname "$arg" "/" ""
	  xdir="$func_dirname_result"

	  if test "$pic_object" != none; then
	    # Prepend the subdirectory the object is found in.
	    pic_object="$xdir$pic_object"

	    if test "$prev" = dlfiles; then
	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
		dlfiles="$dlfiles $pic_object"
		prev=
		continue
	      else
		# If libtool objects are unsupported, then we need to preload.
		prev=dlprefiles
	      fi
	    fi

	    # CHECK ME:  I think I busted this.  -Ossama
	    if test "$prev" = dlprefiles; then
	      # Preload the old-style object.
	      dlprefiles="$dlprefiles $pic_object"
	      prev=
	    fi

	    # A PIC object.
	    func_append libobjs " $pic_object"
	    arg="$pic_object"
	  fi

	  # Non-PIC object.
	  if test "$non_pic_object" != none; then
	    # Prepend the subdirectory the object is found in.
	    non_pic_object="$xdir$non_pic_object"

	    # A standard non-PIC object
	    func_append non_pic_objects " $non_pic_object"
	    if test -z "$pic_object" || test "$pic_object" = none ; then
	      arg="$non_pic_object"
	    fi
	  else
	    # If the PIC object exists, use it instead.
	    # $xdir was prepended to $pic_object above.
	    non_pic_object="$pic_object"
	    func_append non_pic_objects " $non_pic_object"
	  fi
	else
	  # Only an error if not doing a dry-run.
	  if $opt_dry_run; then
	    # Extract subdirectory from the argument.
	    func_dirname "$arg" "/" ""
	    xdir="$func_dirname_result"

	    func_lo2o "$arg"
	    pic_object=$xdir$objdir/$func_lo2o_result
	    non_pic_object=$xdir$func_lo2o_result
	    func_append libobjs " $pic_object"
	    func_append non_pic_objects " $non_pic_object"
	  else
	    func_fatal_error "\`$arg' is not a valid libtool object"
	  fi
	fi
	;;

      *.$libext)
	# An archive.
	deplibs="$deplibs $arg"
	old_deplibs="$old_deplibs $arg"
	continue
	;;

      *.la)
	# A libtool-controlled library.

	if test "$prev" = dlfiles; then
	  # This library was specified with -dlopen.
	  dlfiles="$dlfiles $arg"
	  prev=
	elif test "$prev" = dlprefiles; then
	  # The library was specified with -dlpreopen.
	  dlprefiles="$dlprefiles $arg"
	  prev=
	else
	  deplibs="$deplibs $arg"
	fi
	continue
	;;

      # Some other compiler argument.
      *)
	# Unknown arguments in both finalize_command and compile_command need
	# to be aesthetically quoted because they are evaled later.
	func_quote_for_eval "$arg"
	arg="$func_quote_for_eval_result"
	;;
      esac # arg

      # Now actually substitute the argument into the commands.
      if test -n "$arg"; then
	func_append compile_command " $arg"
	func_append finalize_command " $arg"
      fi
    done # argument parsing loop

    test -n "$prev" && \
      func_fatal_help "the \`$prevarg' option requires an argument"

    if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
      eval arg=\"$export_dynamic_flag_spec\"
      func_append compile_command " $arg"
      func_append finalize_command " $arg"
    fi

    oldlibs=
    # calculate the name of the file, without its directory
    func_basename "$output"
    outputname="$func_basename_result"
    libobjs_save="$libobjs"

    if test -n "$shlibpath_var"; then
      # get the directories listed in $shlibpath_var
      eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
    else
      shlib_search_path=
    fi
    eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
    eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"

    func_dirname "$output" "/" ""
    output_objdir="$func_dirname_result$objdir"
    # Create the object directory.
    func_mkdir_p "$output_objdir"

    # Determine the type of output
    case $output in
    "")
      func_fatal_help "you must specify an output file"
      ;;
    *.$libext) linkmode=oldlib ;;
    *.lo | *.$objext) linkmode=obj ;;
    *.la) linkmode=lib ;;
    *) linkmode=prog ;; # Anything else should be a program.
    esac

    specialdeplibs=

    libs=
    # Find all interdependent deplibs by searching for libraries
    # that are linked more than once (e.g. -la -lb -la)
    for deplib in $deplibs; do
      if $opt_duplicate_deps ; then
	case "$libs " in
	*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
	esac
      fi
      libs="$libs $deplib"
    done

    if test "$linkmode" = lib; then
      libs="$predeps $libs $compiler_lib_search_path $postdeps"

      # Compute libraries that are listed more than once in $predeps
      # $postdeps and mark them as special (i.e., whose duplicates are
      # not to be eliminated).
      pre_post_deps=
      if $opt_duplicate_compiler_generated_deps; then
	for pre_post_dep in $predeps $postdeps; do
	  case "$pre_post_deps " in
	  *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
	  esac
	  pre_post_deps="$pre_post_deps $pre_post_dep"
	done
      fi
      pre_post_deps=
    fi

    deplibs=
    newdependency_libs=
    newlib_search_path=
    need_relink=no # whether we're linking any uninstalled libtool libraries
    notinst_deplibs= # not-installed libtool libraries
    notinst_path= # paths that contain not-installed libtool libraries

    case $linkmode in
    lib)
	passes="conv dlpreopen link"
	for file in $dlfiles $dlprefiles; do
	  case $file in
	  *.la) ;;
	  *)
	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file"
	    ;;
	  esac
	done
	;;
    prog)
	compile_deplibs=
	finalize_deplibs=
	alldeplibs=no
	newdlfiles=
	newdlprefiles=
	passes="conv scan dlopen dlpreopen link"
	;;
    *)  passes="conv"
	;;
    esac

    for pass in $passes; do
      # The preopen pass in lib mode reverses $deplibs; put it back here
      # so that -L comes before libs that need it for instance...
      if test "$linkmode,$pass" = "lib,link"; then
	## FIXME: Find the place where the list is rebuilt in the wrong
	##        order, and fix it there properly
        tmp_deplibs=
	for deplib in $deplibs; do
	  tmp_deplibs="$deplib $tmp_deplibs"
	done
	deplibs="$tmp_deplibs"
      fi

      if test "$linkmode,$pass" = "lib,link" ||
	 test "$linkmode,$pass" = "prog,scan"; then
	libs="$deplibs"
	deplibs=
      fi
      if test "$linkmode" = prog; then
	case $pass in
	dlopen) libs="$dlfiles" ;;
	dlpreopen) libs="$dlprefiles" ;;
	link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
	esac
      fi
      if test "$linkmode,$pass" = "lib,dlpreopen"; then
	# Collect and forward deplibs of preopened libtool libs
	for lib in $dlprefiles; do
	  # Ignore non-libtool-libs
	  dependency_libs=
	  case $lib in
	  *.la)	func_source "$lib" ;;
	  esac

	  # Collect preopened libtool deplibs, except any this library
	  # has declared as weak libs
	  for deplib in $dependency_libs; do
            deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"`
	    case " $weak_libs " in
	    *" $deplib_base "*) ;;
	    *) deplibs="$deplibs $deplib" ;;
	    esac
	  done
	done
	libs="$dlprefiles"
      fi
      if test "$pass" = dlopen; then
	# Collect dlpreopened libraries
	save_deplibs="$deplibs"
	deplibs=
      fi

      for deplib in $libs; do
	lib=
	found=no
	case $deplib in
	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
	  if test "$linkmode,$pass" = "prog,link"; then
	    compile_deplibs="$deplib $compile_deplibs"
	    finalize_deplibs="$deplib $finalize_deplibs"
	  else
	    compiler_flags="$compiler_flags $deplib"
	    if test "$linkmode" = lib ; then
		case "$new_inherited_linker_flags " in
		    *" $deplib "*) ;;
		    * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;;
		esac
	    fi
	  fi
	  continue
	  ;;
	-l*)
	  if test "$linkmode" != lib && test "$linkmode" != prog; then
	    func_warning "\`-l' is ignored for archives/objects"
	    continue
	  fi
	  func_stripname '-l' '' "$deplib"
	  name=$func_stripname_result
	  if test "$linkmode" = lib; then
	    searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path"
	  else
	    searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path"
	  fi
	  for searchdir in $searchdirs; do
	    for search_ext in .la $std_shrext .so .a; do
	      # Search the libtool library
	      lib="$searchdir/lib${name}${search_ext}"
	      if test -f "$lib"; then
		if test "$search_ext" = ".la"; then
		  found=yes
		else
		  found=no
		fi
		break 2
	      fi
	    done
	  done
	  if test "$found" != yes; then
	    # deplib doesn't seem to be a libtool library
	    if test "$linkmode,$pass" = "prog,link"; then
	      compile_deplibs="$deplib $compile_deplibs"
	      finalize_deplibs="$deplib $finalize_deplibs"
	    else
	      deplibs="$deplib $deplibs"
	      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
	    fi
	    continue
	  else # deplib is a libtool library
	    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
	    # We need to do some special things here, and not later.
	    if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
	      case " $predeps $postdeps " in
	      *" $deplib "*)
		if func_lalib_p "$lib"; then
		  library_names=
		  old_library=
		  func_source "$lib"
		  for l in $old_library $library_names; do
		    ll="$l"
		  done
		  if test "X$ll" = "X$old_library" ; then # only static version available
		    found=no
		    func_dirname "$lib" "" "."
		    ladir="$func_dirname_result"
		    lib=$ladir/$old_library
		    if test "$linkmode,$pass" = "prog,link"; then
		      compile_deplibs="$deplib $compile_deplibs"
		      finalize_deplibs="$deplib $finalize_deplibs"
		    else
		      deplibs="$deplib $deplibs"
		      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
		    fi
		    continue
		  fi
		fi
		;;
	      *) ;;
	      esac
	    fi
	  fi
	  ;; # -l
	*.ltframework)
	  if test "$linkmode,$pass" = "prog,link"; then
	    compile_deplibs="$deplib $compile_deplibs"
	    finalize_deplibs="$deplib $finalize_deplibs"
	  else
	    deplibs="$deplib $deplibs"
	    if test "$linkmode" = lib ; then
		case "$new_inherited_linker_flags " in
		    *" $deplib "*) ;;
		    * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;;
		esac
	    fi
	  fi
	  continue
	  ;;
	-L*)
	  case $linkmode in
	  lib)
	    deplibs="$deplib $deplibs"
	    test "$pass" = conv && continue
	    newdependency_libs="$deplib $newdependency_libs"
	    func_stripname '-L' '' "$deplib"
	    newlib_search_path="$newlib_search_path $func_stripname_result"
	    ;;
	  prog)
	    if test "$pass" = conv; then
	      deplibs="$deplib $deplibs"
	      continue
	    fi
	    if test "$pass" = scan; then
	      deplibs="$deplib $deplibs"
	    else
	      compile_deplibs="$deplib $compile_deplibs"
	      finalize_deplibs="$deplib $finalize_deplibs"
	    fi
	    func_stripname '-L' '' "$deplib"
	    newlib_search_path="$newlib_search_path $func_stripname_result"
	    ;;
	  *)
	    func_warning "\`-L' is ignored for archives/objects"
	    ;;
	  esac # linkmode
	  continue
	  ;; # -L
	-R*)
	  if test "$pass" = link; then
	    func_stripname '-R' '' "$deplib"
	    dir=$func_stripname_result
	    # Make sure the xrpath contains only unique directories.
	    case "$xrpath " in
	    *" $dir "*) ;;
	    *) xrpath="$xrpath $dir" ;;
	    esac
	  fi
	  deplibs="$deplib $deplibs"
	  continue
	  ;;
	*.la) lib="$deplib" ;;
	*.$libext)
	  if test "$pass" = conv; then
	    deplibs="$deplib $deplibs"
	    continue
	  fi
	  case $linkmode in
	  lib)
	    # Linking convenience modules into shared libraries is allowed,
	    # but linking other static libraries is non-portable.
	    case " $dlpreconveniencelibs " in
	    *" $deplib "*) ;;
	    *)
	      valid_a_lib=no
	      case $deplibs_check_method in
		match_pattern*)
		  set dummy $deplibs_check_method; shift
		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
		  if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \
		    | $EGREP "$match_pattern_regex" > /dev/null; then
		    valid_a_lib=yes
		  fi
		;;
		pass_all)
		  valid_a_lib=yes
		;;
	      esac
	      if test "$valid_a_lib" != yes; then
		$ECHO
		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
		$ECHO "*** I have the capability to make that library automatically link in when"
		$ECHO "*** you link to this library.  But I can only do this if you have a"
		$ECHO "*** shared version of the library, which you do not appear to have"
		$ECHO "*** because the file extensions .$libext of this argument makes me believe"
		$ECHO "*** that it is just a static archive that I should not use here."
	      else
		$ECHO
		$ECHO "*** Warning: Linking the shared library $output against the"
		$ECHO "*** static library $deplib is not portable!"
		deplibs="$deplib $deplibs"
	      fi
	      ;;
	    esac
	    continue
	    ;;
	  prog)
	    if test "$pass" != link; then
	      deplibs="$deplib $deplibs"
	    else
	      compile_deplibs="$deplib $compile_deplibs"
	      finalize_deplibs="$deplib $finalize_deplibs"
	    fi
	    continue
	    ;;
	  esac # linkmode
	  ;; # *.$libext
	*.lo | *.$objext)
	  if test "$pass" = conv; then
	    deplibs="$deplib $deplibs"
	  elif test "$linkmode" = prog; then
	    if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
	      # If there is no dlopen support or we're linking statically,
	      # we need to preload.
	      newdlprefiles="$newdlprefiles $deplib"
	      compile_deplibs="$deplib $compile_deplibs"
	      finalize_deplibs="$deplib $finalize_deplibs"
	    else
	      newdlfiles="$newdlfiles $deplib"
	    fi
	  fi
	  continue
	  ;;
	%DEPLIBS%)
	  alldeplibs=yes
	  continue
	  ;;
	esac # case $deplib

	if test "$found" = yes || test -f "$lib"; then :
	else
	  func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'"
	fi

	# Check to see that this really is a libtool archive.
	func_lalib_unsafe_p "$lib" \
	  || func_fatal_error "\`$lib' is not a valid libtool archive"

	func_dirname "$lib" "" "."
	ladir="$func_dirname_result"

	dlname=
	dlopen=
	dlpreopen=
	libdir=
	library_names=
	old_library=
	inherited_linker_flags=
	# If the library was installed with an old release of libtool,
	# it will not redefine variables installed, or shouldnotlink
	installed=yes
	shouldnotlink=no
	avoidtemprpath=


	# Read the .la file
	func_source "$lib"

	# Convert "-framework foo" to "foo.ltframework"
	if test -n "$inherited_linker_flags"; then
	  tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'`
	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
	    case " $new_inherited_linker_flags " in
	      *" $tmp_inherited_linker_flag "*) ;;
	      *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";;
	    esac
	  done
	fi
	dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	if test "$linkmode,$pass" = "lib,link" ||
	   test "$linkmode,$pass" = "prog,scan" ||
	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
	  test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
	  test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
	fi

	if test "$pass" = conv; then
	  # Only check for convenience libraries
	  deplibs="$lib $deplibs"
	  if test -z "$libdir"; then
	    if test -z "$old_library"; then
	      func_fatal_error "cannot find name of link library for \`$lib'"
	    fi
	    # It is a libtool convenience library, so add in its objects.
	    convenience="$convenience $ladir/$objdir/$old_library"
	    old_convenience="$old_convenience $ladir/$objdir/$old_library"
	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
	    func_fatal_error "\`$lib' is not a convenience library"
	  fi
	  tmp_libs=
	  for deplib in $dependency_libs; do
	    deplibs="$deplib $deplibs"
	    if $opt_duplicate_deps ; then
	      case "$tmp_libs " in
	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
	      esac
	    fi
	    tmp_libs="$tmp_libs $deplib"
	  done
	  continue
	fi # $pass = conv


	# Get the name of the library we link against.
	linklib=
	for l in $old_library $library_names; do
	  linklib="$l"
	done
	if test -z "$linklib"; then
	  func_fatal_error "cannot find name of link library for \`$lib'"
	fi

	# This library was specified with -dlopen.
	if test "$pass" = dlopen; then
	  if test -z "$libdir"; then
	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
	  fi
	  if test -z "$dlname" ||
	     test "$dlopen_support" != yes ||
	     test "$build_libtool_libs" = no; then
	    # If there is no dlname, no dlopen support or we're linking
	    # statically, we need to preload.  We also need to preload any
	    # dependent libraries so libltdl's deplib preloader doesn't
	    # bomb out in the load deplibs phase.
	    dlprefiles="$dlprefiles $lib $dependency_libs"
	  else
	    newdlfiles="$newdlfiles $lib"
	  fi
	  continue
	fi # $pass = dlopen

	# We need an absolute path.
	case $ladir in
	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
	*)
	  abs_ladir=`cd "$ladir" && pwd`
	  if test -z "$abs_ladir"; then
	    func_warning "cannot determine absolute directory name of \`$ladir'"
	    func_warning "passing it literally to the linker, although it might fail"
	    abs_ladir="$ladir"
	  fi
	  ;;
	esac
	func_basename "$lib"
	laname="$func_basename_result"

	# Find the relevant object directory and library name.
	if test "X$installed" = Xyes; then
	  if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
	    func_warning "library \`$lib' was moved."
	    dir="$ladir"
	    absdir="$abs_ladir"
	    libdir="$abs_ladir"
	  else
	    dir="$libdir"
	    absdir="$libdir"
	  fi
	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
	else
	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
	    dir="$ladir"
	    absdir="$abs_ladir"
	    # Remove this search path later
	    notinst_path="$notinst_path $abs_ladir"
	  else
	    dir="$ladir/$objdir"
	    absdir="$abs_ladir/$objdir"
	    # Remove this search path later
	    notinst_path="$notinst_path $abs_ladir"
	  fi
	fi # $installed = yes
	func_stripname 'lib' '.la' "$laname"
	name=$func_stripname_result

	# This library was specified with -dlpreopen.
	if test "$pass" = dlpreopen; then
	  if test -z "$libdir" && test "$linkmode" = prog; then
	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
	  fi
	  # Prefer using a static library (so that no silly _DYNAMIC symbols
	  # are required to link).
	  if test -n "$old_library"; then
	    newdlprefiles="$newdlprefiles $dir/$old_library"
	    # Keep a list of preopened convenience libraries to check
	    # that they are being used correctly in the link pass.
	    test -z "$libdir" && \
		dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library"
	  # Otherwise, use the dlname, so that lt_dlopen finds it.
	  elif test -n "$dlname"; then
	    newdlprefiles="$newdlprefiles $dir/$dlname"
	  else
	    newdlprefiles="$newdlprefiles $dir/$linklib"
	  fi
	fi # $pass = dlpreopen

	if test -z "$libdir"; then
	  # Link the convenience library
	  if test "$linkmode" = lib; then
	    deplibs="$dir/$old_library $deplibs"
	  elif test "$linkmode,$pass" = "prog,link"; then
	    compile_deplibs="$dir/$old_library $compile_deplibs"
	    finalize_deplibs="$dir/$old_library $finalize_deplibs"
	  else
	    deplibs="$lib $deplibs" # used for prog,scan pass
	  fi
	  continue
	fi


	if test "$linkmode" = prog && test "$pass" != link; then
	  newlib_search_path="$newlib_search_path $ladir"
	  deplibs="$lib $deplibs"

	  linkalldeplibs=no
	  if test "$link_all_deplibs" != no || test -z "$library_names" ||
	     test "$build_libtool_libs" = no; then
	    linkalldeplibs=yes
	  fi

	  tmp_libs=
	  for deplib in $dependency_libs; do
	    case $deplib in
	    -L*) func_stripname '-L' '' "$deplib"
	         newlib_search_path="$newlib_search_path $func_stripname_result"
		 ;;
	    esac
	    # Need to link against all dependency_libs?
	    if test "$linkalldeplibs" = yes; then
	      deplibs="$deplib $deplibs"
	    else
	      # Need to hardcode shared library paths
	      # or/and link against static libraries
	      newdependency_libs="$deplib $newdependency_libs"
	    fi
	    if $opt_duplicate_deps ; then
	      case "$tmp_libs " in
	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
	      esac
	    fi
	    tmp_libs="$tmp_libs $deplib"
	  done # for deplib
	  continue
	fi # $linkmode = prog...

	if test "$linkmode,$pass" = "prog,link"; then
	  if test -n "$library_names" &&
	     { { test "$prefer_static_libs" = no ||
	         test "$prefer_static_libs,$installed" = "built,yes"; } ||
	       test -z "$old_library"; }; then
	    # We need to hardcode the library path
	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
	      # Make sure the rpath contains only unique directories.
	      case "$temp_rpath:" in
	      *"$absdir:"*) ;;
	      *) temp_rpath="$temp_rpath$absdir:" ;;
	      esac
	    fi

	    # Hardcode the library path.
	    # Skip directories that are in the system default run-time
	    # search path.
	    case " $sys_lib_dlsearch_path " in
	    *" $absdir "*) ;;
	    *)
	      case "$compile_rpath " in
	      *" $absdir "*) ;;
	      *) compile_rpath="$compile_rpath $absdir"
	      esac
	      ;;
	    esac
	    case " $sys_lib_dlsearch_path " in
	    *" $libdir "*) ;;
	    *)
	      case "$finalize_rpath " in
	      *" $libdir "*) ;;
	      *) finalize_rpath="$finalize_rpath $libdir"
	      esac
	      ;;
	    esac
	  fi # $linkmode,$pass = prog,link...

	  if test "$alldeplibs" = yes &&
	     { test "$deplibs_check_method" = pass_all ||
	       { test "$build_libtool_libs" = yes &&
		 test -n "$library_names"; }; }; then
	    # We only need to search for static libraries
	    continue
	  fi
	fi

	link_static=no # Whether the deplib will be linked statically
	use_static_libs=$prefer_static_libs
	if test "$use_static_libs" = built && test "$installed" = yes; then
	  use_static_libs=no
	fi
	if test -n "$library_names" &&
	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
	  case $host in
	  *cygwin* | *mingw* | *cegcc*)
	      # No point in relinking DLLs because paths are not encoded
	      notinst_deplibs="$notinst_deplibs $lib"
	      need_relink=no
	    ;;
	  *)
	    if test "$installed" = no; then
	      notinst_deplibs="$notinst_deplibs $lib"
	      need_relink=yes
	    fi
	    ;;
	  esac
	  # This is a shared library

	  # Warn about portability, can't link against -module's on some
	  # systems (darwin).  Don't bleat about dlopened modules though!
	  dlopenmodule=""
	  for dlpremoduletest in $dlprefiles; do
	    if test "X$dlpremoduletest" = "X$lib"; then
	      dlopenmodule="$dlpremoduletest"
	      break
	    fi
	  done
	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
	    $ECHO
	    if test "$linkmode" = prog; then
	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
	    else
	      $ECHO "*** Warning: Linking the shared library $output against the loadable module"
	    fi
	    $ECHO "*** $linklib is not portable!"
	  fi
	  if test "$linkmode" = lib &&
	     test "$hardcode_into_libs" = yes; then
	    # Hardcode the library path.
	    # Skip directories that are in the system default run-time
	    # search path.
	    case " $sys_lib_dlsearch_path " in
	    *" $absdir "*) ;;
	    *)
	      case "$compile_rpath " in
	      *" $absdir "*) ;;
	      *) compile_rpath="$compile_rpath $absdir"
	      esac
	      ;;
	    esac
	    case " $sys_lib_dlsearch_path " in
	    *" $libdir "*) ;;
	    *)
	      case "$finalize_rpath " in
	      *" $libdir "*) ;;
	      *) finalize_rpath="$finalize_rpath $libdir"
	      esac
	      ;;
	    esac
	  fi

	  if test -n "$old_archive_from_expsyms_cmds"; then
	    # figure out the soname
	    set dummy $library_names
	    shift
	    realname="$1"
	    shift
	    libname=`eval "\\$ECHO \"$libname_spec\""`
	    # use dlname if we got it. it's perfectly good, no?
	    if test -n "$dlname"; then
	      soname="$dlname"
	    elif test -n "$soname_spec"; then
	      # bleh windows
	      case $host in
	      *cygwin* | mingw* | *cegcc*)
	        func_arith $current - $age
		major=$func_arith_result
		versuffix="-$major"
		;;
	      esac
	      eval soname=\"$soname_spec\"
	    else
	      soname="$realname"
	    fi

	    # Make a new name for the extract_expsyms_cmds to use
	    soroot="$soname"
	    func_basename "$soroot"
	    soname="$func_basename_result"
	    func_stripname 'lib' '.dll' "$soname"
	    newlib=libimp-$func_stripname_result.a

	    # If the library has no export list, then create one now
	    if test -f "$output_objdir/$soname-def"; then :
	    else
	      func_verbose "extracting exported symbol list from \`$soname'"
	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
	    fi

	    # Create $newlib
	    if test -f "$output_objdir/$newlib"; then :; else
	      func_verbose "generating import library for \`$soname'"
	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
	    fi
	    # make sure the library variables are pointing to the new library
	    dir=$output_objdir
	    linklib=$newlib
	  fi # test -n "$old_archive_from_expsyms_cmds"

	  if test "$linkmode" = prog || test "$mode" != relink; then
	    add_shlibpath=
	    add_dir=
	    add=
	    lib_linked=yes
	    case $hardcode_action in
	    immediate | unsupported)
	      if test "$hardcode_direct" = no; then
		add="$dir/$linklib"
		case $host in
		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
		    *-*-unixware7*) add_dir="-L$dir" ;;
		  *-*-darwin* )
		    # if the lib is a (non-dlopened) module then we can not
		    # link against it, someone is ignoring the earlier warnings
		    if /usr/bin/file -L $add 2> /dev/null |
			 $GREP ": [^:]* bundle" >/dev/null ; then
		      if test "X$dlopenmodule" != "X$lib"; then
			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
			if test -z "$old_library" ; then
			  $ECHO
			  $ECHO "*** And there doesn't seem to be a static archive available"
			  $ECHO "*** The link will probably fail, sorry"
			else
			  add="$dir/$old_library"
			fi
		      elif test -n "$old_library"; then
			add="$dir/$old_library"
		      fi
		    fi
		esac
	      elif test "$hardcode_minus_L" = no; then
		case $host in
		*-*-sunos*) add_shlibpath="$dir" ;;
		esac
		add_dir="-L$dir"
		add="-l$name"
	      elif test "$hardcode_shlibpath_var" = no; then
		add_shlibpath="$dir"
		add="-l$name"
	      else
		lib_linked=no
	      fi
	      ;;
	    relink)
	      if test "$hardcode_direct" = yes &&
	         test "$hardcode_direct_absolute" = no; then
		add="$dir/$linklib"
	      elif test "$hardcode_minus_L" = yes; then
		add_dir="-L$dir"
		# Try looking first in the location we're being installed to.
		if test -n "$inst_prefix_dir"; then
		  case $libdir in
		    [\\/]*)
		      add_dir="$add_dir -L$inst_prefix_dir$libdir"
		      ;;
		  esac
		fi
		add="-l$name"
	      elif test "$hardcode_shlibpath_var" = yes; then
		add_shlibpath="$dir"
		add="-l$name"
	      else
		lib_linked=no
	      fi
	      ;;
	    *) lib_linked=no ;;
	    esac

	    if test "$lib_linked" != yes; then
	      func_fatal_configuration "unsupported hardcode properties"
	    fi

	    if test -n "$add_shlibpath"; then
	      case :$compile_shlibpath: in
	      *":$add_shlibpath:"*) ;;
	      *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
	      esac
	    fi
	    if test "$linkmode" = prog; then
	      test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
	      test -n "$add" && compile_deplibs="$add $compile_deplibs"
	    else
	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
	      test -n "$add" && deplibs="$add $deplibs"
	      if test "$hardcode_direct" != yes &&
		 test "$hardcode_minus_L" != yes &&
		 test "$hardcode_shlibpath_var" = yes; then
		case :$finalize_shlibpath: in
		*":$libdir:"*) ;;
		*) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
		esac
	      fi
	    fi
	  fi

	  if test "$linkmode" = prog || test "$mode" = relink; then
	    add_shlibpath=
	    add_dir=
	    add=
	    # Finalize command for both is simple: just hardcode it.
	    if test "$hardcode_direct" = yes &&
	       test "$hardcode_direct_absolute" = no; then
	      add="$libdir/$linklib"
	    elif test "$hardcode_minus_L" = yes; then
	      add_dir="-L$libdir"
	      add="-l$name"
	    elif test "$hardcode_shlibpath_var" = yes; then
	      case :$finalize_shlibpath: in
	      *":$libdir:"*) ;;
	      *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
	      esac
	      add="-l$name"
	    elif test "$hardcode_automatic" = yes; then
	      if test -n "$inst_prefix_dir" &&
		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
		add="$inst_prefix_dir$libdir/$linklib"
	      else
		add="$libdir/$linklib"
	      fi
	    else
	      # We cannot seem to hardcode it, guess we'll fake it.
	      add_dir="-L$libdir"
	      # Try looking first in the location we're being installed to.
	      if test -n "$inst_prefix_dir"; then
		case $libdir in
		  [\\/]*)
		    add_dir="$add_dir -L$inst_prefix_dir$libdir"
		    ;;
		esac
	      fi
	      add="-l$name"
	    fi

	    if test "$linkmode" = prog; then
	      test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
	      test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
	    else
	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
	      test -n "$add" && deplibs="$add $deplibs"
	    fi
	  fi
	elif test "$linkmode" = prog; then
	  # Here we assume that one of hardcode_direct or hardcode_minus_L
	  # is not unsupported.  This is valid on all known static and
	  # shared platforms.
	  if test "$hardcode_direct" != unsupported; then
	    test -n "$old_library" && linklib="$old_library"
	    compile_deplibs="$dir/$linklib $compile_deplibs"
	    finalize_deplibs="$dir/$linklib $finalize_deplibs"
	  else
	    compile_deplibs="-l$name -L$dir $compile_deplibs"
	    finalize_deplibs="-l$name -L$dir $finalize_deplibs"
	  fi
	elif test "$build_libtool_libs" = yes; then
	  # Not a shared library
	  if test "$deplibs_check_method" != pass_all; then
	    # We're trying link a shared library against a static one
	    # but the system doesn't support it.

	    # Just print a warning and add the library to dependency_libs so
	    # that the program can be linked against the static library.
	    $ECHO
	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
	    $ECHO "*** I have the capability to make that library automatically link in when"
	    $ECHO "*** you link to this library.  But I can only do this if you have a"
	    $ECHO "*** shared version of the library, which you do not appear to have."
	    if test "$module" = yes; then
	      $ECHO "*** But as you try to build a module library, libtool will still create "
	      $ECHO "*** a static module, that should work as long as the dlopening application"
	      $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime."
	      if test -z "$global_symbol_pipe"; then
		$ECHO
		$ECHO "*** However, this would only work if libtool was able to extract symbol"
		$ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could"
		$ECHO "*** not find such a program.  So, this module is probably useless."
		$ECHO "*** \`nm' from GNU binutils and a full rebuild may help."
	      fi
	      if test "$build_old_libs" = no; then
		build_libtool_libs=module
		build_old_libs=yes
	      else
		build_libtool_libs=no
	      fi
	    fi
	  else
	    deplibs="$dir/$old_library $deplibs"
	    link_static=yes
	  fi
	fi # link shared/static library?

	if test "$linkmode" = lib; then
	  if test -n "$dependency_libs" &&
	     { test "$hardcode_into_libs" != yes ||
	       test "$build_old_libs" = yes ||
	       test "$link_static" = yes; }; then
	    # Extract -R from dependency_libs
	    temp_deplibs=
	    for libdir in $dependency_libs; do
	      case $libdir in
	      -R*) func_stripname '-R' '' "$libdir"
	           temp_xrpath=$func_stripname_result
		   case " $xrpath " in
		   *" $temp_xrpath "*) ;;
		   *) xrpath="$xrpath $temp_xrpath";;
		   esac;;
	      *) temp_deplibs="$temp_deplibs $libdir";;
	      esac
	    done
	    dependency_libs="$temp_deplibs"
	  fi

	  newlib_search_path="$newlib_search_path $absdir"
	  # Link against this library
	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
	  # ... and its dependency_libs
	  tmp_libs=
	  for deplib in $dependency_libs; do
	    newdependency_libs="$deplib $newdependency_libs"
	    if $opt_duplicate_deps ; then
	      case "$tmp_libs " in
	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
	      esac
	    fi
	    tmp_libs="$tmp_libs $deplib"
	  done

	  if test "$link_all_deplibs" != no; then
	    # Add the search paths of all dependency libraries
	    for deplib in $dependency_libs; do
	      case $deplib in
	      -L*) path="$deplib" ;;
	      *.la)
	        func_dirname "$deplib" "" "."
		dir="$func_dirname_result"
		# We need an absolute path.
		case $dir in
		[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
		*)
		  absdir=`cd "$dir" && pwd`
		  if test -z "$absdir"; then
		    func_warning "cannot determine absolute directory name of \`$dir'"
		    absdir="$dir"
		  fi
		  ;;
		esac
		if $GREP "^installed=no" $deplib > /dev/null; then
		case $host in
		*-*-darwin*)
		  depdepl=
		  eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
		  if test -n "$deplibrary_names" ; then
		    for tmp in $deplibrary_names ; do
		      depdepl=$tmp
		    done
		    if test -f "$absdir/$objdir/$depdepl" ; then
		      depdepl="$absdir/$objdir/$depdepl"
		      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
                      if test -z "$darwin_install_name"; then
                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
                      fi
		      compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
		      linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}"
		      path=
		    fi
		  fi
		  ;;
		*)
		  path="-L$absdir/$objdir"
		  ;;
		esac
		else
		  eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
		  test -z "$libdir" && \
		    func_fatal_error "\`$deplib' is not a valid libtool archive"
		  test "$absdir" != "$libdir" && \
		    func_warning "\`$deplib' seems to be moved"

		  path="-L$absdir"
		fi
		;;
	      esac
	      case " $deplibs " in
	      *" $path "*) ;;
	      *) deplibs="$path $deplibs" ;;
	      esac
	    done
	  fi # link_all_deplibs != no
	fi # linkmode = lib
      done # for deplib in $libs
      if test "$pass" = link; then
	if test "$linkmode" = "prog"; then
	  compile_deplibs="$new_inherited_linker_flags $compile_deplibs"
	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
	else
	  compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	fi
      fi
      dependency_libs="$newdependency_libs"
      if test "$pass" = dlpreopen; then
	# Link the dlpreopened libraries before other libraries
	for deplib in $save_deplibs; do
	  deplibs="$deplib $deplibs"
	done
      fi
      if test "$pass" != dlopen; then
	if test "$pass" != conv; then
	  # Make sure lib_search_path contains only unique directories.
	  lib_search_path=
	  for dir in $newlib_search_path; do
	    case "$lib_search_path " in
	    *" $dir "*) ;;
	    *) lib_search_path="$lib_search_path $dir" ;;
	    esac
	  done
	  newlib_search_path=
	fi

	if test "$linkmode,$pass" != "prog,link"; then
	  vars="deplibs"
	else
	  vars="compile_deplibs finalize_deplibs"
	fi
	for var in $vars dependency_libs; do
	  # Add libraries to $var in reverse order
	  eval tmp_libs=\"\$$var\"
	  new_libs=
	  for deplib in $tmp_libs; do
	    # FIXME: Pedantically, this is the right thing to do, so
	    #        that some nasty dependency loop isn't accidentally
	    #        broken:
	    #new_libs="$deplib $new_libs"
	    # Pragmatically, this seems to cause very few problems in
	    # practice:
	    case $deplib in
	    -L*) new_libs="$deplib $new_libs" ;;
	    -R*) ;;
	    *)
	      # And here is the reason: when a library appears more
	      # than once as an explicit dependence of a library, or
	      # is implicitly linked in more than once by the
	      # compiler, it is considered special, and multiple
	      # occurrences thereof are not removed.  Compare this
	      # with having the same library being listed as a
	      # dependency of multiple other libraries: in this case,
	      # we know (pedantically, we assume) the library does not
	      # need to be listed more than once, so we keep only the
	      # last copy.  This is not always right, but it is rare
	      # enough that we require users that really mean to play
	      # such unportable linking tricks to link the library
	      # using -Wl,-lname, so that libtool does not consider it
	      # for duplicate removal.
	      case " $specialdeplibs " in
	      *" $deplib "*) new_libs="$deplib $new_libs" ;;
	      *)
		case " $new_libs " in
		*" $deplib "*) ;;
		*) new_libs="$deplib $new_libs" ;;
		esac
		;;
	      esac
	      ;;
	    esac
	  done
	  tmp_libs=
	  for deplib in $new_libs; do
	    case $deplib in
	    -L*)
	      case " $tmp_libs " in
	      *" $deplib "*) ;;
	      *) tmp_libs="$tmp_libs $deplib" ;;
	      esac
	      ;;
	    *) tmp_libs="$tmp_libs $deplib" ;;
	    esac
	  done
	  eval $var=\"$tmp_libs\"
	done # for var
      fi
      # Last step: remove runtime libs from dependency_libs
      # (they stay in deplibs)
      tmp_libs=
      for i in $dependency_libs ; do
	case " $predeps $postdeps $compiler_lib_search_path " in
	*" $i "*)
	  i=""
	  ;;
	esac
	if test -n "$i" ; then
	  tmp_libs="$tmp_libs $i"
	fi
      done
      dependency_libs=$tmp_libs
    done # for pass
    if test "$linkmode" = prog; then
      dlfiles="$newdlfiles"
    fi
    if test "$linkmode" = prog || test "$linkmode" = lib; then
      dlprefiles="$newdlprefiles"
    fi

    case $linkmode in
    oldlib)
      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
	func_warning "\`-dlopen' is ignored for archives"
      fi

      case " $deplibs" in
      *\ -l* | *\ -L*)
	func_warning "\`-l' and \`-L' are ignored for archives" ;;
      esac

      test -n "$rpath" && \
	func_warning "\`-rpath' is ignored for archives"

      test -n "$xrpath" && \
	func_warning "\`-R' is ignored for archives"

      test -n "$vinfo" && \
	func_warning "\`-version-info/-version-number' is ignored for archives"

      test -n "$release" && \
	func_warning "\`-release' is ignored for archives"

      test -n "$export_symbols$export_symbols_regex" && \
	func_warning "\`-export-symbols' is ignored for archives"

      # Now set the variables for building old libraries.
      build_libtool_libs=no
      oldlibs="$output"
      objs="$objs$old_deplibs"
      ;;

    lib)
      # Make sure we only generate libraries of the form `libNAME.la'.
      case $outputname in
      lib*)
	func_stripname 'lib' '.la' "$outputname"
	name=$func_stripname_result
	eval shared_ext=\"$shrext_cmds\"
	eval libname=\"$libname_spec\"
	;;
      *)
	test "$module" = no && \
	  func_fatal_help "libtool library \`$output' must begin with \`lib'"

	if test "$need_lib_prefix" != no; then
	  # Add the "lib" prefix for modules if required
	  func_stripname '' '.la' "$outputname"
	  name=$func_stripname_result
	  eval shared_ext=\"$shrext_cmds\"
	  eval libname=\"$libname_spec\"
	else
	  func_stripname '' '.la' "$outputname"
	  libname=$func_stripname_result
	fi
	;;
      esac

      if test -n "$objs"; then
	if test "$deplibs_check_method" != pass_all; then
	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
	else
	  $ECHO
	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
	  $ECHO "*** objects $objs is not portable!"
	  libobjs="$libobjs $objs"
	fi
      fi

      test "$dlself" != no && \
	func_warning "\`-dlopen self' is ignored for libtool libraries"

      set dummy $rpath
      shift
      test "$#" -gt 1 && \
	func_warning "ignoring multiple \`-rpath's for a libtool library"

      install_libdir="$1"

      oldlibs=
      if test -z "$rpath"; then
	if test "$build_libtool_libs" = yes; then
	  # Building a libtool convenience library.
	  # Some compilers have problems with a `.al' extension so
	  # convenience libraries should have the same extension an
	  # archive normally would.
	  oldlibs="$output_objdir/$libname.$libext $oldlibs"
	  build_libtool_libs=convenience
	  build_old_libs=yes
	fi

	test -n "$vinfo" && \
	  func_warning "\`-version-info/-version-number' is ignored for convenience libraries"

	test -n "$release" && \
	  func_warning "\`-release' is ignored for convenience libraries"
      else

	# Parse the version information argument.
	save_ifs="$IFS"; IFS=':'
	set dummy $vinfo 0 0 0
	shift
	IFS="$save_ifs"

	test -n "$7" && \
	  func_fatal_help "too many parameters to \`-version-info'"

	# convert absolute version numbers to libtool ages
	# this retains compatibility with .la files and attempts
	# to make the code below a bit more comprehensible

	case $vinfo_number in
	yes)
	  number_major="$1"
	  number_minor="$2"
	  number_revision="$3"
	  #
	  # There are really only two kinds -- those that
	  # use the current revision as the major version
	  # and those that subtract age and use age as
	  # a minor version.  But, then there is irix
	  # which has an extra 1 added just for fun
	  #
	  case $version_type in
	  darwin|linux|osf|windows|none)
	    func_arith $number_major + $number_minor
	    current=$func_arith_result
	    age="$number_minor"
	    revision="$number_revision"
	    ;;
	  freebsd-aout|freebsd-elf|sunos)
	    current="$number_major"
	    revision="$number_minor"
	    age="0"
	    ;;
	  irix|nonstopux)
	    func_arith $number_major + $number_minor
	    current=$func_arith_result
	    age="$number_minor"
	    revision="$number_minor"
	    lt_irix_increment=no
	    ;;
	  esac
	  ;;
	no)
	  current="$1"
	  revision="$2"
	  age="$3"
	  ;;
	esac

	# Check that each of the things are valid numbers.
	case $current in
	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
	*)
	  func_error "CURRENT \`$current' must be a nonnegative integer"
	  func_fatal_error "\`$vinfo' is not valid version information"
	  ;;
	esac

	case $revision in
	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
	*)
	  func_error "REVISION \`$revision' must be a nonnegative integer"
	  func_fatal_error "\`$vinfo' is not valid version information"
	  ;;
	esac

	case $age in
	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
	*)
	  func_error "AGE \`$age' must be a nonnegative integer"
	  func_fatal_error "\`$vinfo' is not valid version information"
	  ;;
	esac

	if test "$age" -gt "$current"; then
	  func_error "AGE \`$age' is greater than the current interface number \`$current'"
	  func_fatal_error "\`$vinfo' is not valid version information"
	fi

	# Calculate the version variables.
	major=
	versuffix=
	verstring=
	case $version_type in
	none) ;;

	darwin)
	  # Like Linux, but with the current version available in
	  # verstring for coding it into the library header
	  func_arith $current - $age
	  major=.$func_arith_result
	  versuffix="$major.$age.$revision"
	  # Darwin ld doesn't like 0 for these options...
	  func_arith $current + 1
	  minor_current=$func_arith_result
	  xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
	  ;;

	freebsd-aout)
	  major=".$current"
	  versuffix=".$current.$revision";
	  ;;

	freebsd-elf)
	  major=".$current"
	  versuffix=".$current"
	  ;;

	irix | nonstopux)
	  if test "X$lt_irix_increment" = "Xno"; then
	    func_arith $current - $age
	  else
	    func_arith $current - $age + 1
	  fi
	  major=$func_arith_result

	  case $version_type in
	    nonstopux) verstring_prefix=nonstopux ;;
	    *)         verstring_prefix=sgi ;;
	  esac
	  verstring="$verstring_prefix$major.$revision"

	  # Add in all the interfaces that we are compatible with.
	  loop=$revision
	  while test "$loop" -ne 0; do
	    func_arith $revision - $loop
	    iface=$func_arith_result
	    func_arith $loop - 1
	    loop=$func_arith_result
	    verstring="$verstring_prefix$major.$iface:$verstring"
	  done

	  # Before this point, $major must not contain `.'.
	  major=.$major
	  versuffix="$major.$revision"
	  ;;

	linux)
	  func_arith $current - $age
	  major=.$func_arith_result
	  versuffix="$major.$age.$revision"
	  ;;

	osf)
	  func_arith $current - $age
	  major=.$func_arith_result
	  versuffix=".$current.$age.$revision"
	  verstring="$current.$age.$revision"

	  # Add in all the interfaces that we are compatible with.
	  loop=$age
	  while test "$loop" -ne 0; do
	    func_arith $current - $loop
	    iface=$func_arith_result
	    func_arith $loop - 1
	    loop=$func_arith_result
	    verstring="$verstring:${iface}.0"
	  done

	  # Make executables depend on our current version.
	  verstring="$verstring:${current}.0"
	  ;;

	qnx)
	  major=".$current"
	  versuffix=".$current"
	  ;;

	sunos)
	  major=".$current"
	  versuffix=".$current.$revision"
	  ;;

	windows)
	  # Use '-' rather than '.', since we only want one
	  # extension on DOS 8.3 filesystems.
	  func_arith $current - $age
	  major=$func_arith_result
	  versuffix="-$major"
	  ;;

	*)
	  func_fatal_configuration "unknown library version type \`$version_type'"
	  ;;
	esac

	# Clear the version info if we defaulted, and they specified a release.
	if test -z "$vinfo" && test -n "$release"; then
	  major=
	  case $version_type in
	  darwin)
	    # we can't check for "0.0" in archive_cmds due to quoting
	    # problems, so we reset it completely
	    verstring=
	    ;;
	  *)
	    verstring="0.0"
	    ;;
	  esac
	  if test "$need_version" = no; then
	    versuffix=
	  else
	    versuffix=".0.0"
	  fi
	fi

	# Remove version info from name if versioning should be avoided
	if test "$avoid_version" = yes && test "$need_version" = no; then
	  major=
	  versuffix=
	  verstring=""
	fi

	# Check to see if the archive will have undefined symbols.
	if test "$allow_undefined" = yes; then
	  if test "$allow_undefined_flag" = unsupported; then
	    func_warning "undefined symbols not allowed in $host shared libraries"
	    build_libtool_libs=no
	    build_old_libs=yes
	  fi
	else
	  # Don't allow undefined symbols.
	  allow_undefined_flag="$no_undefined_flag"
	fi

      fi

      func_generate_dlsyms "$libname" "$libname" "yes"
      libobjs="$libobjs $symfileobj"
      test "X$libobjs" = "X " && libobjs=

      if test "$mode" != relink; then
	# Remove our outputs, but don't remove object files since they
	# may have been created when compiling PIC objects.
	removelist=
	tempremovelist=`$ECHO "$output_objdir/*"`
	for p in $tempremovelist; do
	  case $p in
	    *.$objext | *.gcno)
	       ;;
	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
	       if test "X$precious_files_regex" != "X"; then
		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
		 then
		   continue
		 fi
	       fi
	       removelist="$removelist $p"
	       ;;
	    *) ;;
	  esac
	done
	test -n "$removelist" && \
	  func_show_eval "${RM}r \$removelist"
      fi

      # Now set the variables for building old libraries.
      if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
	oldlibs="$oldlibs $output_objdir/$libname.$libext"

	# Transform .lo files to .o files.
	oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
      fi

      # Eliminate all temporary directories.
      #for path in $notinst_path; do
      #	lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"`
      #	deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"`
      #	dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"`
      #done

      if test -n "$xrpath"; then
	# If the user specified any rpath flags, then add them.
	temp_xrpath=
	for libdir in $xrpath; do
	  temp_xrpath="$temp_xrpath -R$libdir"
	  case "$finalize_rpath " in
	  *" $libdir "*) ;;
	  *) finalize_rpath="$finalize_rpath $libdir" ;;
	  esac
	done
	if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
	  dependency_libs="$temp_xrpath $dependency_libs"
	fi
      fi

      # Make sure dlfiles contains only unique files that won't be dlpreopened
      old_dlfiles="$dlfiles"
      dlfiles=
      for lib in $old_dlfiles; do
	case " $dlprefiles $dlfiles " in
	*" $lib "*) ;;
	*) dlfiles="$dlfiles $lib" ;;
	esac
      done

      # Make sure dlprefiles contains only unique files
      old_dlprefiles="$dlprefiles"
      dlprefiles=
      for lib in $old_dlprefiles; do
	case "$dlprefiles " in
	*" $lib "*) ;;
	*) dlprefiles="$dlprefiles $lib" ;;
	esac
      done

      if test "$build_libtool_libs" = yes; then
	if test -n "$rpath"; then
	  case $host in
	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*)
	    # these systems don't actually have a c library (as such)!
	    ;;
	  *-*-rhapsody* | *-*-darwin1.[012])
	    # Rhapsody C library is in the System framework
	    deplibs="$deplibs System.ltframework"
	    ;;
	  *-*-netbsd*)
	    # Don't link with libc until the a.out ld.so is fixed.
	    ;;
	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
	    # Do not include libc due to us having libc/libc_r.
	    ;;
	  *-*-sco3.2v5* | *-*-sco5v6*)
	    # Causes problems with __ctype
	    ;;
	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
	    # Compiler inserts libc in the correct place for threads to work
	    ;;
	  *)
	    # Add libc to deplibs on all other systems if necessary.
	    if test "$build_libtool_need_lc" = "yes"; then
	      deplibs="$deplibs -lc"
	    fi
	    ;;
	  esac
	fi

	# Transform deplibs into only deplibs that can be linked in shared.
	name_save=$name
	libname_save=$libname
	release_save=$release
	versuffix_save=$versuffix
	major_save=$major
	# I'm not sure if I'm treating the release correctly.  I think
	# release should show up in the -l (ie -lgmp5) so we don't want to
	# add it in twice.  Is that correct?
	release=""
	versuffix=""
	major=""
	newdeplibs=
	droppeddeps=no
	case $deplibs_check_method in
	pass_all)
	  # Don't check for shared/static.  Everything works.
	  # This might be a little naive.  We might want to check
	  # whether the library exists or not.  But this is on
	  # osf3 & osf4 and I'm not really sure... Just
	  # implementing what was already the behavior.
	  newdeplibs=$deplibs
	  ;;
	test_compile)
	  # This code stresses the "libraries are programs" paradigm to its
	  # limits. Maybe even breaks it.  We compile a program, linking it
	  # against the deplibs as a proxy for the library.  Then we can check
	  # whether they linked in statically or dynamically with ldd.
	  $opt_dry_run || $RM conftest.c
	  cat > conftest.c <<EOF
	  int main() { return 0; }
EOF
	  $opt_dry_run || $RM conftest
	  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
	    ldd_output=`ldd conftest`
	    for i in $deplibs; do
	      case $i in
	      -l*)
		func_stripname -l '' "$i"
		name=$func_stripname_result
		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
		  case " $predeps $postdeps " in
		  *" $i "*)
		    newdeplibs="$newdeplibs $i"
		    i=""
		    ;;
		  esac
		fi
		if test -n "$i" ; then
		  libname=`eval "\\$ECHO \"$libname_spec\""`
		  deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
		  set dummy $deplib_matches; shift
		  deplib_match=$1
		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
		    newdeplibs="$newdeplibs $i"
		  else
		    droppeddeps=yes
		    $ECHO
		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
		    $ECHO "*** I have the capability to make that library automatically link in when"
		    $ECHO "*** you link to this library.  But I can only do this if you have a"
		    $ECHO "*** shared version of the library, which I believe you do not have"
		    $ECHO "*** because a test_compile did reveal that the linker did not use it for"
		    $ECHO "*** its dynamic dependency list that programs get resolved with at runtime."
		  fi
		fi
		;;
	      *)
		newdeplibs="$newdeplibs $i"
		;;
	      esac
	    done
	  else
	    # Error occurred in the first compile.  Let's try to salvage
	    # the situation: Compile a separate program for each library.
	    for i in $deplibs; do
	      case $i in
	      -l*)
		func_stripname -l '' "$i"
		name=$func_stripname_result
		$opt_dry_run || $RM conftest
		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
		  ldd_output=`ldd conftest`
		  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
		    case " $predeps $postdeps " in
		    *" $i "*)
		      newdeplibs="$newdeplibs $i"
		      i=""
		      ;;
		    esac
		  fi
		  if test -n "$i" ; then
		    libname=`eval "\\$ECHO \"$libname_spec\""`
		    deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
		    set dummy $deplib_matches; shift
		    deplib_match=$1
		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
		      newdeplibs="$newdeplibs $i"
		    else
		      droppeddeps=yes
		      $ECHO
		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
		      $ECHO "*** I have the capability to make that library automatically link in when"
		      $ECHO "*** you link to this library.  But I can only do this if you have a"
		      $ECHO "*** shared version of the library, which you do not appear to have"
		      $ECHO "*** because a test_compile did reveal that the linker did not use this one"
		      $ECHO "*** as a dynamic dependency that programs can get resolved with at runtime."
		    fi
		  fi
		else
		  droppeddeps=yes
		  $ECHO
		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
		  $ECHO "*** make it link in!  You will probably need to install it or some"
		  $ECHO "*** library that it depends on before this library will be fully"
		  $ECHO "*** functional.  Installing it before continuing would be even better."
		fi
		;;
	      *)
		newdeplibs="$newdeplibs $i"
		;;
	      esac
	    done
	  fi
	  ;;
	file_magic*)
	  set dummy $deplibs_check_method; shift
	  file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
	  for a_deplib in $deplibs; do
	    case $a_deplib in
	    -l*)
	      func_stripname -l '' "$a_deplib"
	      name=$func_stripname_result
	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
		case " $predeps $postdeps " in
		*" $a_deplib "*)
		  newdeplibs="$newdeplibs $a_deplib"
		  a_deplib=""
		  ;;
		esac
	      fi
	      if test -n "$a_deplib" ; then
		libname=`eval "\\$ECHO \"$libname_spec\""`
		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
		  for potent_lib in $potential_libs; do
		      # Follow soft links.
		      if ls -lLd "$potent_lib" 2>/dev/null |
			 $GREP " -> " >/dev/null; then
			continue
		      fi
		      # The statement above tries to avoid entering an
		      # endless loop below, in case of cyclic links.
		      # We might still enter an endless loop, since a link
		      # loop can be closed while we follow links,
		      # but so what?
		      potlib="$potent_lib"
		      while test -h "$potlib" 2>/dev/null; do
			potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
			case $potliblink in
			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
			*) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
			esac
		      done
		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
			 $SED -e 10q |
			 $EGREP "$file_magic_regex" > /dev/null; then
			newdeplibs="$newdeplibs $a_deplib"
			a_deplib=""
			break 2
		      fi
		  done
		done
	      fi
	      if test -n "$a_deplib" ; then
		droppeddeps=yes
		$ECHO
		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
		$ECHO "*** I have the capability to make that library automatically link in when"
		$ECHO "*** you link to this library.  But I can only do this if you have a"
		$ECHO "*** shared version of the library, which you do not appear to have"
		$ECHO "*** because I did check the linker path looking for a file starting"
		if test -z "$potlib" ; then
		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
		else
		  $ECHO "*** with $libname and none of the candidates passed a file format test"
		  $ECHO "*** using a file magic. Last file checked: $potlib"
		fi
	      fi
	      ;;
	    *)
	      # Add a -L argument.
	      newdeplibs="$newdeplibs $a_deplib"
	      ;;
	    esac
	  done # Gone through all deplibs.
	  ;;
	match_pattern*)
	  set dummy $deplibs_check_method; shift
	  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
	  for a_deplib in $deplibs; do
	    case $a_deplib in
	    -l*)
	      func_stripname -l '' "$a_deplib"
	      name=$func_stripname_result
	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
		case " $predeps $postdeps " in
		*" $a_deplib "*)
		  newdeplibs="$newdeplibs $a_deplib"
		  a_deplib=""
		  ;;
		esac
	      fi
	      if test -n "$a_deplib" ; then
		libname=`eval "\\$ECHO \"$libname_spec\""`
		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
		  for potent_lib in $potential_libs; do
		    potlib="$potent_lib" # see symlink-check above in file_magic test
		    if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \
		       $EGREP "$match_pattern_regex" > /dev/null; then
		      newdeplibs="$newdeplibs $a_deplib"
		      a_deplib=""
		      break 2
		    fi
		  done
		done
	      fi
	      if test -n "$a_deplib" ; then
		droppeddeps=yes
		$ECHO
		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
		$ECHO "*** I have the capability to make that library automatically link in when"
		$ECHO "*** you link to this library.  But I can only do this if you have a"
		$ECHO "*** shared version of the library, which you do not appear to have"
		$ECHO "*** because I did check the linker path looking for a file starting"
		if test -z "$potlib" ; then
		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
		else
		  $ECHO "*** with $libname and none of the candidates passed a file format test"
		  $ECHO "*** using a regex pattern. Last file checked: $potlib"
		fi
	      fi
	      ;;
	    *)
	      # Add a -L argument.
	      newdeplibs="$newdeplibs $a_deplib"
	      ;;
	    esac
	  done # Gone through all deplibs.
	  ;;
	none | unknown | *)
	  newdeplibs=""
	  tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \
	      -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'`
	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
	    for i in $predeps $postdeps ; do
	      # can't use Xsed below, because $i might contain '/'
	      tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"`
	    done
	  fi
	  if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[	 ]//g' |
	     $GREP . >/dev/null; then
	    $ECHO
	    if test "X$deplibs_check_method" = "Xnone"; then
	      $ECHO "*** Warning: inter-library dependencies are not supported in this platform."
	    else
	      $ECHO "*** Warning: inter-library dependencies are not known to be supported."
	    fi
	    $ECHO "*** All declared inter-library dependencies are being dropped."
	    droppeddeps=yes
	  fi
	  ;;
	esac
	versuffix=$versuffix_save
	major=$major_save
	release=$release_save
	libname=$libname_save
	name=$name_save

	case $host in
	*-*-rhapsody* | *-*-darwin1.[012])
	  # On Rhapsody replace the C library with the System framework
	  newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
	  ;;
	esac

	if test "$droppeddeps" = yes; then
	  if test "$module" = yes; then
	    $ECHO
	    $ECHO "*** Warning: libtool could not satisfy all declared inter-library"
	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
	    $ECHO "*** a static module, that should work as long as the dlopening"
	    $ECHO "*** application is linked with the -dlopen flag."
	    if test -z "$global_symbol_pipe"; then
	      $ECHO
	      $ECHO "*** However, this would only work if libtool was able to extract symbol"
	      $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could"
	      $ECHO "*** not find such a program.  So, this module is probably useless."
	      $ECHO "*** \`nm' from GNU binutils and a full rebuild may help."
	    fi
	    if test "$build_old_libs" = no; then
	      oldlibs="$output_objdir/$libname.$libext"
	      build_libtool_libs=module
	      build_old_libs=yes
	    else
	      build_libtool_libs=no
	    fi
	  else
	    $ECHO "*** The inter-library dependencies that have been dropped here will be"
	    $ECHO "*** automatically added whenever a program is linked with this library"
	    $ECHO "*** or is declared to -dlopen it."

	    if test "$allow_undefined" = no; then
	      $ECHO
	      $ECHO "*** Since this library must not contain undefined symbols,"
	      $ECHO "*** because either the platform does not support them or"
	      $ECHO "*** it was explicitly requested with -no-undefined,"
	      $ECHO "*** libtool will only create a static version of it."
	      if test "$build_old_libs" = no; then
		oldlibs="$output_objdir/$libname.$libext"
		build_libtool_libs=module
		build_old_libs=yes
	      else
		build_libtool_libs=no
	      fi
	    fi
	  fi
	fi
	# Done checking deplibs!
	deplibs=$newdeplibs
      fi
      # Time to change all our "foo.ltframework" stuff back to "-framework foo"
      case $host in
	*-*-darwin*)
	  newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	  new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	  deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	  ;;
      esac

      # move library search paths that coincide with paths to not yet
      # installed libraries to the beginning of the library search list
      new_libs=
      for path in $notinst_path; do
	case " $new_libs " in
	*" -L$path/$objdir "*) ;;
	*)
	  case " $deplibs " in
	  *" -L$path/$objdir "*)
	    new_libs="$new_libs -L$path/$objdir" ;;
	  esac
	  ;;
	esac
      done
      for deplib in $deplibs; do
	case $deplib in
	-L*)
	  case " $new_libs " in
	  *" $deplib "*) ;;
	  *) new_libs="$new_libs $deplib" ;;
	  esac
	  ;;
	*) new_libs="$new_libs $deplib" ;;
	esac
      done
      deplibs="$new_libs"

      # All the library-specific variables (install_libdir is set above).
      library_names=
      old_library=
      dlname=

      # Test again, we may have decided not to build it any more
      if test "$build_libtool_libs" = yes; then
	if test "$hardcode_into_libs" = yes; then
	  # Hardcode the library paths
	  hardcode_libdirs=
	  dep_rpath=
	  rpath="$finalize_rpath"
	  test "$mode" != relink && rpath="$compile_rpath$rpath"
	  for libdir in $rpath; do
	    if test -n "$hardcode_libdir_flag_spec"; then
	      if test -n "$hardcode_libdir_separator"; then
		if test -z "$hardcode_libdirs"; then
		  hardcode_libdirs="$libdir"
		else
		  # Just accumulate the unique libdirs.
		  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
		  *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
		    ;;
		  *)
		    hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
		    ;;
		  esac
		fi
	      else
		eval flag=\"$hardcode_libdir_flag_spec\"
		dep_rpath="$dep_rpath $flag"
	      fi
	    elif test -n "$runpath_var"; then
	      case "$perm_rpath " in
	      *" $libdir "*) ;;
	      *) perm_rpath="$perm_rpath $libdir" ;;
	      esac
	    fi
	  done
	  # Substitute the hardcoded libdirs into the rpath.
	  if test -n "$hardcode_libdir_separator" &&
	     test -n "$hardcode_libdirs"; then
	    libdir="$hardcode_libdirs"
	    if test -n "$hardcode_libdir_flag_spec_ld"; then
	      eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
	    else
	      eval dep_rpath=\"$hardcode_libdir_flag_spec\"
	    fi
	  fi
	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
	    # We should set the runpath_var.
	    rpath=
	    for dir in $perm_rpath; do
	      rpath="$rpath$dir:"
	    done
	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
	  fi
	  test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
	fi

	shlibpath="$finalize_shlibpath"
	test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
	if test -n "$shlibpath"; then
	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
	fi

	# Get the real and link names of the library.
	eval shared_ext=\"$shrext_cmds\"
	eval library_names=\"$library_names_spec\"
	set dummy $library_names
	shift
	realname="$1"
	shift

	if test -n "$soname_spec"; then
	  eval soname=\"$soname_spec\"
	else
	  soname="$realname"
	fi
	if test -z "$dlname"; then
	  dlname=$soname
	fi

	lib="$output_objdir/$realname"
	linknames=
	for link
	do
	  linknames="$linknames $link"
	done

	# Use standard objects if they are pic
	test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
	test "X$libobjs" = "X " && libobjs=

	delfiles=
	if test -n "$export_symbols" && test -n "$include_expsyms"; then
	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
	  export_symbols="$output_objdir/$libname.uexp"
	  delfiles="$delfiles $export_symbols"
	fi

	orig_export_symbols=
	case $host_os in
	cygwin* | mingw* | cegcc*)
	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
	    # exporting using user supplied symfile
	    if test "x`$SED 1q $export_symbols`" != xEXPORTS; then
	      # and it's NOT already a .def file. Must figure out
	      # which of the given symbols are data symbols and tag
	      # them as such. So, trigger use of export_symbols_cmds.
	      # export_symbols gets reassigned inside the "prepare
	      # the list of exported symbols" if statement, so the
	      # include_expsyms logic still works.
	      orig_export_symbols="$export_symbols"
	      export_symbols=
	      always_export_symbols=yes
	    fi
	  fi
	  ;;
	esac

	# Prepare the list of exported symbols
	if test -z "$export_symbols"; then
	  if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
	    func_verbose "generating symbol list for \`$libname.la'"
	    export_symbols="$output_objdir/$libname.exp"
	    $opt_dry_run || $RM $export_symbols
	    cmds=$export_symbols_cmds
	    save_ifs="$IFS"; IFS='~'
	    for cmd in $cmds; do
	      IFS="$save_ifs"
	      eval cmd=\"$cmd\"
	      func_len " $cmd"
	      len=$func_len_result
	      if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
		func_show_eval "$cmd" 'exit $?'
		skipped_export=false
	      else
		# The command line is too long to execute in one step.
		func_verbose "using reloadable object file for export list..."
		skipped_export=:
		# Break out early, otherwise skipped_export may be
		# set to false by a later but shorter cmd.
		break
	      fi
	    done
	    IFS="$save_ifs"
	    if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then
	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
	    fi
	  fi
	fi

	if test -n "$export_symbols" && test -n "$include_expsyms"; then
	  tmp_export_symbols="$export_symbols"
	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
	  $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"'
	fi

	if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then
	  # The given exports_symbols file has to be filtered, so filter it.
	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
	  # 's' commands which not all seds can handle. GNU sed should be fine
	  # though. Also, the filter scales superlinearly with the number of
	  # global variables. join(1) would be nice here, but unfortunately
	  # isn't a blessed tool.
	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
	  delfiles="$delfiles $export_symbols $output_objdir/$libname.filter"
	  export_symbols=$output_objdir/$libname.def
	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
	fi

	tmp_deplibs=
	for test_deplib in $deplibs; do
	  case " $convenience " in
	  *" $test_deplib "*) ;;
	  *)
	    tmp_deplibs="$tmp_deplibs $test_deplib"
	    ;;
	  esac
	done
	deplibs="$tmp_deplibs"

	if test -n "$convenience"; then
	  if test -n "$whole_archive_flag_spec" &&
	    test "$compiler_needs_object" = yes &&
	    test -z "$libobjs"; then
	    # extract the archives, so we have objects to list.
	    # TODO: could optimize this to just extract one archive.
	    whole_archive_flag_spec=
	  fi
	  if test -n "$whole_archive_flag_spec"; then
	    save_libobjs=$libobjs
	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
	    test "X$libobjs" = "X " && libobjs=
	  else
	    gentop="$output_objdir/${outputname}x"
	    generated="$generated $gentop"

	    func_extract_archives $gentop $convenience
	    libobjs="$libobjs $func_extract_archives_result"
	    test "X$libobjs" = "X " && libobjs=
	  fi
	fi

	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
	  eval flag=\"$thread_safe_flag_spec\"
	  linker_flags="$linker_flags $flag"
	fi

	# Make a backup of the uninstalled library when relinking
	if test "$mode" = relink; then
	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
	fi

	# Do each of the archive commands.
	if test "$module" = yes && test -n "$module_cmds" ; then
	  if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
	    eval test_cmds=\"$module_expsym_cmds\"
	    cmds=$module_expsym_cmds
	  else
	    eval test_cmds=\"$module_cmds\"
	    cmds=$module_cmds
	  fi
	else
	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
	    eval test_cmds=\"$archive_expsym_cmds\"
	    cmds=$archive_expsym_cmds
	  else
	    eval test_cmds=\"$archive_cmds\"
	    cmds=$archive_cmds
	  fi
	fi

	if test "X$skipped_export" != "X:" &&
	   func_len " $test_cmds" &&
	   len=$func_len_result &&
	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
	  :
	else
	  # The command line is too long to link in one step, link piecewise
	  # or, if using GNU ld and skipped_export is not :, use a linker
	  # script.

	  # Save the value of $output and $libobjs because we want to
	  # use them later.  If we have whole_archive_flag_spec, we
	  # want to use save_libobjs as it was before
	  # whole_archive_flag_spec was expanded, because we can't
	  # assume the linker understands whole_archive_flag_spec.
	  # This may have to be revisited, in case too many
	  # convenience libraries get linked in and end up exceeding
	  # the spec.
	  if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
	    save_libobjs=$libobjs
	  fi
	  save_output=$output
	  output_la=`$ECHO "X$output" | $Xsed -e "$basename"`

	  # Clear the reloadable object creation command queue and
	  # initialize k to one.
	  test_cmds=
	  concat_cmds=
	  objlist=
	  last_robj=
	  k=1

	  if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then
	    output=${output_objdir}/${output_la}.lnkscript
	    func_verbose "creating GNU ld script: $output"
	    $ECHO 'INPUT (' > $output
	    for obj in $save_libobjs
	    do
	      $ECHO "$obj" >> $output
	    done
	    $ECHO ')' >> $output
	    delfiles="$delfiles $output"
	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
	    output=${output_objdir}/${output_la}.lnk
	    func_verbose "creating linker input file list: $output"
	    : > $output
	    set x $save_libobjs
	    shift
	    firstobj=
	    if test "$compiler_needs_object" = yes; then
	      firstobj="$1 "
	      shift
	    fi
	    for obj
	    do
	      $ECHO "$obj" >> $output
	    done
	    delfiles="$delfiles $output"
	    output=$firstobj\"$file_list_spec$output\"
	  else
	    if test -n "$save_libobjs"; then
	      func_verbose "creating reloadable object files..."
	      output=$output_objdir/$output_la-${k}.$objext
	      eval test_cmds=\"$reload_cmds\"
	      func_len " $test_cmds"
	      len0=$func_len_result
	      len=$len0

	      # Loop over the list of objects to be linked.
	      for obj in $save_libobjs
	      do
		func_len " $obj"
		func_arith $len + $func_len_result
		len=$func_arith_result
		if test "X$objlist" = X ||
		   test "$len" -lt "$max_cmd_len"; then
		  func_append objlist " $obj"
		else
		  # The command $test_cmds is almost too long, add a
		  # command to the queue.
		  if test "$k" -eq 1 ; then
		    # The first file doesn't have a previous command to add.
		    eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
		  else
		    # All subsequent reloadable object files will link in
		    # the last one created.
		    eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\"
		  fi
		  last_robj=$output_objdir/$output_la-${k}.$objext
		  func_arith $k + 1
		  k=$func_arith_result
		  output=$output_objdir/$output_la-${k}.$objext
		  objlist=$obj
		  func_len " $last_robj"
		  func_arith $len0 + $func_len_result
		  len=$func_arith_result
		fi
	      done
	      # Handle the remaining objects by creating one last
	      # reloadable object file.  All subsequent reloadable object
	      # files will link in the last one created.
	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
	      eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
	      if test -n "$last_robj"; then
	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
	      fi
	      delfiles="$delfiles $output"

	    else
	      output=
	    fi

	    if ${skipped_export-false}; then
	      func_verbose "generating symbol list for \`$libname.la'"
	      export_symbols="$output_objdir/$libname.exp"
	      $opt_dry_run || $RM $export_symbols
	      libobjs=$output
	      # Append the command to create the export file.
	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
	      eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\"
	      if test -n "$last_robj"; then
		eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
	      fi
	    fi

	    test -n "$save_libobjs" &&
	      func_verbose "creating a temporary reloadable object file: $output"

	    # Loop through the commands generated above and execute them.
	    save_ifs="$IFS"; IFS='~'
	    for cmd in $concat_cmds; do
	      IFS="$save_ifs"
	      $opt_silent || {
		  func_quote_for_expand "$cmd"
		  eval "func_echo $func_quote_for_expand_result"
	      }
	      $opt_dry_run || eval "$cmd" || {
		lt_exit=$?

		# Restore the uninstalled library and exit
		if test "$mode" = relink; then
		  ( cd "$output_objdir" && \
		    $RM "${realname}T" && \
		    $MV "${realname}U" "$realname" )
		fi

		exit $lt_exit
	      }
	    done
	    IFS="$save_ifs"

	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
	    fi
	  fi

          if ${skipped_export-false}; then
	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
	      tmp_export_symbols="$export_symbols"
	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
	      $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"'
	    fi

	    if test -n "$orig_export_symbols"; then
	      # The given exports_symbols file has to be filtered, so filter it.
	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
	      # 's' commands which not all seds can handle. GNU sed should be fine
	      # though. Also, the filter scales superlinearly with the number of
	      # global variables. join(1) would be nice here, but unfortunately
	      # isn't a blessed tool.
	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
	      delfiles="$delfiles $export_symbols $output_objdir/$libname.filter"
	      export_symbols=$output_objdir/$libname.def
	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
	    fi
	  fi

	  libobjs=$output
	  # Restore the value of output.
	  output=$save_output

	  if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
	    test "X$libobjs" = "X " && libobjs=
	  fi
	  # Expand the library linking commands again to reset the
	  # value of $libobjs for piecewise linking.

	  # Do each of the archive commands.
	  if test "$module" = yes && test -n "$module_cmds" ; then
	    if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
	      cmds=$module_expsym_cmds
	    else
	      cmds=$module_cmds
	    fi
	  else
	    if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
	      cmds=$archive_expsym_cmds
	    else
	      cmds=$archive_cmds
	    fi
	  fi
	fi

	if test -n "$delfiles"; then
	  # Append the command to remove temporary files to $cmds.
	  eval cmds=\"\$cmds~\$RM $delfiles\"
	fi

	# Add any objects from preloaded convenience libraries
	if test -n "$dlprefiles"; then
	  gentop="$output_objdir/${outputname}x"
	  generated="$generated $gentop"

	  func_extract_archives $gentop $dlprefiles
	  libobjs="$libobjs $func_extract_archives_result"
	  test "X$libobjs" = "X " && libobjs=
	fi

	save_ifs="$IFS"; IFS='~'
	for cmd in $cmds; do
	  IFS="$save_ifs"
	  eval cmd=\"$cmd\"
	  $opt_silent || {
	    func_quote_for_expand "$cmd"
	    eval "func_echo $func_quote_for_expand_result"
	  }
	  $opt_dry_run || eval "$cmd" || {
	    lt_exit=$?

	    # Restore the uninstalled library and exit
	    if test "$mode" = relink; then
	      ( cd "$output_objdir" && \
	        $RM "${realname}T" && \
		$MV "${realname}U" "$realname" )
	    fi

	    exit $lt_exit
	  }
	done
	IFS="$save_ifs"

	# Restore the uninstalled library and exit
	if test "$mode" = relink; then
	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?

	  if test -n "$convenience"; then
	    if test -z "$whole_archive_flag_spec"; then
	      func_show_eval '${RM}r "$gentop"'
	    fi
	  fi

	  exit $EXIT_SUCCESS
	fi

	# Create links to the real library.
	for linkname in $linknames; do
	  if test "$realname" != "$linkname"; then
	    func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?'
	  fi
	done

	# If -module or -export-dynamic was specified, set the dlname.
	if test "$module" = yes || test "$export_dynamic" = yes; then
	  # On all known operating systems, these are identical.
	  dlname="$soname"
	fi
      fi
      ;;

    obj)
      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
	func_warning "\`-dlopen' is ignored for objects"
      fi

      case " $deplibs" in
      *\ -l* | *\ -L*)
	func_warning "\`-l' and \`-L' are ignored for objects" ;;
      esac

      test -n "$rpath" && \
	func_warning "\`-rpath' is ignored for objects"

      test -n "$xrpath" && \
	func_warning "\`-R' is ignored for objects"

      test -n "$vinfo" && \
	func_warning "\`-version-info' is ignored for objects"

      test -n "$release" && \
	func_warning "\`-release' is ignored for objects"

      case $output in
      *.lo)
	test -n "$objs$old_deplibs" && \
	  func_fatal_error "cannot build library object \`$output' from non-libtool objects"

	libobj=$output
	func_lo2o "$libobj"
	obj=$func_lo2o_result
	;;
      *)
	libobj=
	obj="$output"
	;;
      esac

      # Delete the old objects.
      $opt_dry_run || $RM $obj $libobj

      # Objects from convenience libraries.  This assumes
      # single-version convenience libraries.  Whenever we create
      # different ones for PIC/non-PIC, this we'll have to duplicate
      # the extraction.
      reload_conv_objs=
      gentop=
      # reload_cmds runs $LD directly, so let us get rid of
      # -Wl from whole_archive_flag_spec and hope we can get by with
      # turning comma into space..
      wl=

      if test -n "$convenience"; then
	if test -n "$whole_archive_flag_spec"; then
	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
	  reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
	else
	  gentop="$output_objdir/${obj}x"
	  generated="$generated $gentop"

	  func_extract_archives $gentop $convenience
	  reload_conv_objs="$reload_objs $func_extract_archives_result"
	fi
      fi

      # Create the old-style object.
      reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test

      output="$obj"
      func_execute_cmds "$reload_cmds" 'exit $?'

      # Exit if we aren't doing a library object file.
      if test -z "$libobj"; then
	if test -n "$gentop"; then
	  func_show_eval '${RM}r "$gentop"'
	fi

	exit $EXIT_SUCCESS
      fi

      if test "$build_libtool_libs" != yes; then
	if test -n "$gentop"; then
	  func_show_eval '${RM}r "$gentop"'
	fi

	# Create an invalid libtool object if no PIC, so that we don't
	# accidentally link it into a program.
	# $show "echo timestamp > $libobj"
	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
	exit $EXIT_SUCCESS
      fi

      if test -n "$pic_flag" || test "$pic_mode" != default; then
	# Only do commands if we really have different PIC objects.
	reload_objs="$libobjs $reload_conv_objs"
	output="$libobj"
	func_execute_cmds "$reload_cmds" 'exit $?'
      fi

      if test -n "$gentop"; then
	func_show_eval '${RM}r "$gentop"'
      fi

      exit $EXIT_SUCCESS
      ;;

    prog)
      case $host in
	*cygwin*) func_stripname '' '.exe' "$output"
	          output=$func_stripname_result.exe;;
      esac
      test -n "$vinfo" && \
	func_warning "\`-version-info' is ignored for programs"

      test -n "$release" && \
	func_warning "\`-release' is ignored for programs"

      test "$preload" = yes \
        && test "$dlopen_support" = unknown \
	&& test "$dlopen_self" = unknown \
	&& test "$dlopen_self_static" = unknown && \
	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support."

      case $host in
      *-*-rhapsody* | *-*-darwin1.[012])
	# On Rhapsody replace the C library is the System framework
	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
	;;
      esac

      case $host in
      *-*-darwin*)
	# Don't allow lazy linking, it breaks C++ global constructors
	# But is supposedly fixed on 10.4 or later (yay!).
	if test "$tagname" = CXX ; then
	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
	    10.[0123])
	      compile_command="$compile_command ${wl}-bind_at_load"
	      finalize_command="$finalize_command ${wl}-bind_at_load"
	    ;;
	  esac
	fi
	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
	;;
      esac


      # move library search paths that coincide with paths to not yet
      # installed libraries to the beginning of the library search list
      new_libs=
      for path in $notinst_path; do
	case " $new_libs " in
	*" -L$path/$objdir "*) ;;
	*)
	  case " $compile_deplibs " in
	  *" -L$path/$objdir "*)
	    new_libs="$new_libs -L$path/$objdir" ;;
	  esac
	  ;;
	esac
      done
      for deplib in $compile_deplibs; do
	case $deplib in
	-L*)
	  case " $new_libs " in
	  *" $deplib "*) ;;
	  *) new_libs="$new_libs $deplib" ;;
	  esac
	  ;;
	*) new_libs="$new_libs $deplib" ;;
	esac
      done
      compile_deplibs="$new_libs"


      compile_command="$compile_command $compile_deplibs"
      finalize_command="$finalize_command $finalize_deplibs"

      if test -n "$rpath$xrpath"; then
	# If the user specified any rpath flags, then add them.
	for libdir in $rpath $xrpath; do
	  # This is the magic to use -rpath.
	  case "$finalize_rpath " in
	  *" $libdir "*) ;;
	  *) finalize_rpath="$finalize_rpath $libdir" ;;
	  esac
	done
      fi

      # Now hardcode the library paths
      rpath=
      hardcode_libdirs=
      for libdir in $compile_rpath $finalize_rpath; do
	if test -n "$hardcode_libdir_flag_spec"; then
	  if test -n "$hardcode_libdir_separator"; then
	    if test -z "$hardcode_libdirs"; then
	      hardcode_libdirs="$libdir"
	    else
	      # Just accumulate the unique libdirs.
	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
		;;
	      *)
		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
		;;
	      esac
	    fi
	  else
	    eval flag=\"$hardcode_libdir_flag_spec\"
	    rpath="$rpath $flag"
	  fi
	elif test -n "$runpath_var"; then
	  case "$perm_rpath " in
	  *" $libdir "*) ;;
	  *) perm_rpath="$perm_rpath $libdir" ;;
	  esac
	fi
	case $host in
	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
	  testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
	  case :$dllsearchpath: in
	  *":$libdir:"*) ;;
	  ::) dllsearchpath=$libdir;;
	  *) dllsearchpath="$dllsearchpath:$libdir";;
	  esac
	  case :$dllsearchpath: in
	  *":$testbindir:"*) ;;
	  ::) dllsearchpath=$testbindir;;
	  *) dllsearchpath="$dllsearchpath:$testbindir";;
	  esac
	  ;;
	esac
      done
      # Substitute the hardcoded libdirs into the rpath.
      if test -n "$hardcode_libdir_separator" &&
	 test -n "$hardcode_libdirs"; then
	libdir="$hardcode_libdirs"
	eval rpath=\" $hardcode_libdir_flag_spec\"
      fi
      compile_rpath="$rpath"

      rpath=
      hardcode_libdirs=
      for libdir in $finalize_rpath; do
	if test -n "$hardcode_libdir_flag_spec"; then
	  if test -n "$hardcode_libdir_separator"; then
	    if test -z "$hardcode_libdirs"; then
	      hardcode_libdirs="$libdir"
	    else
	      # Just accumulate the unique libdirs.
	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
		;;
	      *)
		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
		;;
	      esac
	    fi
	  else
	    eval flag=\"$hardcode_libdir_flag_spec\"
	    rpath="$rpath $flag"
	  fi
	elif test -n "$runpath_var"; then
	  case "$finalize_perm_rpath " in
	  *" $libdir "*) ;;
	  *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
	  esac
	fi
      done
      # Substitute the hardcoded libdirs into the rpath.
      if test -n "$hardcode_libdir_separator" &&
	 test -n "$hardcode_libdirs"; then
	libdir="$hardcode_libdirs"
	eval rpath=\" $hardcode_libdir_flag_spec\"
      fi
      finalize_rpath="$rpath"

      if test -n "$libobjs" && test "$build_old_libs" = yes; then
	# Transform all the library objects into standard objects.
	compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
	finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
      fi

      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"

      # template prelinking step
      if test -n "$prelink_cmds"; then
	func_execute_cmds "$prelink_cmds" 'exit $?'
      fi

      wrappers_required=yes
      case $host in
      *cygwin* | *mingw* )
        if test "$build_libtool_libs" != yes; then
          wrappers_required=no
        fi
        ;;
      *cegcc)
        # Disable wrappers for cegcc, we are cross compiling anyway.
        wrappers_required=no
        ;;
      *)
        if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
          wrappers_required=no
        fi
        ;;
      esac
      if test "$wrappers_required" = no; then
	# Replace the output file specification.
	compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
	link_command="$compile_command$compile_rpath"

	# We have no uninstalled library dependencies, so finalize right now.
	exit_status=0
	func_show_eval "$link_command" 'exit_status=$?'

	# Delete the generated files.
	if test -f "$output_objdir/${outputname}S.${objext}"; then
	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
	fi

	exit $exit_status
      fi

      if test -n "$compile_shlibpath$finalize_shlibpath"; then
	compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
      fi
      if test -n "$finalize_shlibpath"; then
	finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
      fi

      compile_var=
      finalize_var=
      if test -n "$runpath_var"; then
	if test -n "$perm_rpath"; then
	  # We should set the runpath_var.
	  rpath=
	  for dir in $perm_rpath; do
	    rpath="$rpath$dir:"
	  done
	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
	fi
	if test -n "$finalize_perm_rpath"; then
	  # We should set the runpath_var.
	  rpath=
	  for dir in $finalize_perm_rpath; do
	    rpath="$rpath$dir:"
	  done
	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
	fi
      fi

      if test "$no_install" = yes; then
	# We don't need to create a wrapper script.
	link_command="$compile_var$compile_command$compile_rpath"
	# Replace the output file specification.
	link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
	# Delete the old output file.
	$opt_dry_run || $RM $output
	# Link the executable and exit
	func_show_eval "$link_command" 'exit $?'
	exit $EXIT_SUCCESS
      fi

      if test "$hardcode_action" = relink; then
	# Fast installation is not supported
	link_command="$compile_var$compile_command$compile_rpath"
	relink_command="$finalize_var$finalize_command$finalize_rpath"

	func_warning "this platform does not like uninstalled shared libraries"
	func_warning "\`$output' will be relinked during installation"
      else
	if test "$fast_install" != no; then
	  link_command="$finalize_var$compile_command$finalize_rpath"
	  if test "$fast_install" = yes; then
	    relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'`
	  else
	    # fast_install is set to needless
	    relink_command=
	  fi
	else
	  link_command="$compile_var$compile_command$compile_rpath"
	  relink_command="$finalize_var$finalize_command$finalize_rpath"
	fi
      fi

      # Replace the output file specification.
      link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`

      # Delete the old output files.
      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname

      func_show_eval "$link_command" 'exit $?'

      # Now create the wrapper script.
      func_verbose "creating $output"

      # Quote the relink command for shipping.
      if test -n "$relink_command"; then
	# Preserve any variables that may affect compiler behavior
	for var in $variables_saved_for_relink; do
	  if eval test -z \"\${$var+set}\"; then
	    relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
	  elif eval var_value=\$$var; test -z "$var_value"; then
	    relink_command="$var=; export $var; $relink_command"
	  else
	    func_quote_for_eval "$var_value"
	    relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
	  fi
	done
	relink_command="(cd `pwd`; $relink_command)"
	relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"`
      fi

      # Quote $ECHO for shipping.
      if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then
	case $progpath in
	[\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
	*) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
	esac
	qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"`
      else
	qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"`
      fi

      # Only actually do things if not in dry run mode.
      $opt_dry_run || {
	# win32 will think the script is a binary if it has
	# a .exe suffix, so we strip it off here.
	case $output in
	  *.exe) func_stripname '' '.exe' "$output"
	         output=$func_stripname_result ;;
	esac
	# test for cygwin because mv fails w/o .exe extensions
	case $host in
	  *cygwin*)
	    exeext=.exe
	    func_stripname '' '.exe' "$outputname"
	    outputname=$func_stripname_result ;;
	  *) exeext= ;;
	esac
	case $host in
	  *cygwin* | *mingw* )
	    func_dirname_and_basename "$output" "" "."
	    output_name=$func_basename_result
	    output_path=$func_dirname_result
	    cwrappersource="$output_path/$objdir/lt-$output_name.c"
	    cwrapper="$output_path/$output_name.exe"
	    $RM $cwrappersource $cwrapper
	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15

	    func_emit_cwrapperexe_src > $cwrappersource

	    # The wrapper executable is built using the $host compiler,
	    # because it contains $host paths and files. If cross-
	    # compiling, it, like the target executable, must be
	    # executed on the $host or under an emulation environment.
	    $opt_dry_run || {
	      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource
	      $STRIP $cwrapper
	    }

	    # Now, create the wrapper script for func_source use:
	    func_ltwrapper_scriptname $cwrapper
	    $RM $func_ltwrapper_scriptname_result
	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15
	    $opt_dry_run || {
	      # note: this script will not be executed, so do not chmod.
	      if test "x$build" = "x$host" ; then
		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
	      else
		func_emit_wrapper no > $func_ltwrapper_scriptname_result
	      fi
	    }
	  ;;
	  * )
	    $RM $output
	    trap "$RM $output; exit $EXIT_FAILURE" 1 2 15

	    func_emit_wrapper no > $output
	    chmod +x $output
	  ;;
	esac
      }
      exit $EXIT_SUCCESS
      ;;
    esac

    # See if we need to build an old-fashioned archive.
    for oldlib in $oldlibs; do

      if test "$build_libtool_libs" = convenience; then
	oldobjs="$libobjs_save $symfileobj"
	addlibs="$convenience"
	build_libtool_libs=no
      else
	if test "$build_libtool_libs" = module; then
	  oldobjs="$libobjs_save"
	  build_libtool_libs=no
	else
	  oldobjs="$old_deplibs $non_pic_objects"
	  if test "$preload" = yes && test -f "$symfileobj"; then
	    oldobjs="$oldobjs $symfileobj"
	  fi
	fi
	addlibs="$old_convenience"
      fi

      if test -n "$addlibs"; then
	gentop="$output_objdir/${outputname}x"
	generated="$generated $gentop"

	func_extract_archives $gentop $addlibs
	oldobjs="$oldobjs $func_extract_archives_result"
      fi

      # Do each command in the archive commands.
      if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
	cmds=$old_archive_from_new_cmds
      else

	# Add any objects from preloaded convenience libraries
	if test -n "$dlprefiles"; then
	  gentop="$output_objdir/${outputname}x"
	  generated="$generated $gentop"

	  func_extract_archives $gentop $dlprefiles
	  oldobjs="$oldobjs $func_extract_archives_result"
	fi

	# POSIX demands no paths to be encoded in archives.  We have
	# to avoid creating archives with duplicate basenames if we
	# might have to extract them afterwards, e.g., when creating a
	# static archive out of a convenience library, or when linking
	# the entirety of a libtool archive into another (currently
	# not supported by libtool).
	if (for obj in $oldobjs
	    do
	      func_basename "$obj"
	      $ECHO "$func_basename_result"
	    done | sort | sort -uc >/dev/null 2>&1); then
	  :
	else
	  $ECHO "copying selected object files to avoid basename conflicts..."
	  gentop="$output_objdir/${outputname}x"
	  generated="$generated $gentop"
	  func_mkdir_p "$gentop"
	  save_oldobjs=$oldobjs
	  oldobjs=
	  counter=1
	  for obj in $save_oldobjs
	  do
	    func_basename "$obj"
	    objbase="$func_basename_result"
	    case " $oldobjs " in
	    " ") oldobjs=$obj ;;
	    *[\ /]"$objbase "*)
	      while :; do
		# Make sure we don't pick an alternate name that also
		# overlaps.
		newobj=lt$counter-$objbase
		func_arith $counter + 1
		counter=$func_arith_result
		case " $oldobjs " in
		*[\ /]"$newobj "*) ;;
		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
		esac
	      done
	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
	      oldobjs="$oldobjs $gentop/$newobj"
	      ;;
	    *) oldobjs="$oldobjs $obj" ;;
	    esac
	  done
	fi
	eval cmds=\"$old_archive_cmds\"

	func_len " $cmds"
	len=$func_len_result
	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
	  cmds=$old_archive_cmds
	else
	  # the command line is too long to link in one step, link in parts
	  func_verbose "using piecewise archive linking..."
	  save_RANLIB=$RANLIB
	  RANLIB=:
	  objlist=
	  concat_cmds=
	  save_oldobjs=$oldobjs
	  oldobjs=
	  # Is there a better way of finding the last object in the list?
	  for obj in $save_oldobjs
	  do
	    last_oldobj=$obj
	  done
	  eval test_cmds=\"$old_archive_cmds\"
	  func_len " $test_cmds"
	  len0=$func_len_result
	  len=$len0
	  for obj in $save_oldobjs
	  do
	    func_len " $obj"
	    func_arith $len + $func_len_result
	    len=$func_arith_result
	    func_append objlist " $obj"
	    if test "$len" -lt "$max_cmd_len"; then
	      :
	    else
	      # the above command should be used before it gets too long
	      oldobjs=$objlist
	      if test "$obj" = "$last_oldobj" ; then
		RANLIB=$save_RANLIB
	      fi
	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
	      eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
	      objlist=
	      len=$len0
	    fi
	  done
	  RANLIB=$save_RANLIB
	  oldobjs=$objlist
	  if test "X$oldobjs" = "X" ; then
	    eval cmds=\"\$concat_cmds\"
	  else
	    eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
	  fi
	fi
      fi
      func_execute_cmds "$cmds" 'exit $?'
    done

    test -n "$generated" && \
      func_show_eval "${RM}r$generated"

    # Now create the libtool archive.
    case $output in
    *.la)
      old_library=
      test "$build_old_libs" = yes && old_library="$libname.$libext"
      func_verbose "creating $output"

      # Preserve any variables that may affect compiler behavior
      for var in $variables_saved_for_relink; do
	if eval test -z \"\${$var+set}\"; then
	  relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
	elif eval var_value=\$$var; test -z "$var_value"; then
	  relink_command="$var=; export $var; $relink_command"
	else
	  func_quote_for_eval "$var_value"
	  relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
	fi
      done
      # Quote the link command for shipping.
      relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
      relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"`
      if test "$hardcode_automatic" = yes ; then
	relink_command=
      fi

      # Only create the output if not a dry run.
      $opt_dry_run || {
	for installed in no yes; do
	  if test "$installed" = yes; then
	    if test -z "$install_libdir"; then
	      break
	    fi
	    output="$output_objdir/$outputname"i
	    # Replace all uninstalled libtool libraries with the installed ones
	    newdependency_libs=
	    for deplib in $dependency_libs; do
	      case $deplib in
	      *.la)
		func_basename "$deplib"
		name="$func_basename_result"
		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
		test -z "$libdir" && \
		  func_fatal_error "\`$deplib' is not a valid libtool archive"
		if test "x$EGREP" = x ; then
			EGREP=egrep
		fi
		# We do not want portage's install root ($D) present.  Check only for
		# this if the .la is being installed.
		if test "$installed" = yes && test "$D"; then
		  eval mynewdependency_lib=`echo "$libdir/$name" |sed -e "s:$D:/:g" -e 's:/\+:/:g'`
		else
		  mynewdependency_lib="$libdir/$name"
		fi
		# Do not add duplicates
		if test "$mynewdependency_lib"; then
		  my_little_ninja_foo_1=`echo $newdependency_libs |$EGREP -e "$mynewdependency_lib"`
		  if test -z "$my_little_ninja_foo_1"; then
		    newdependency_libs="$newdependency_libs $mynewdependency_lib"
		  fi
		fi
		;;
		  *)
		if test "$installed" = yes; then
		  # Rather use S=WORKDIR if our version of portage supports it.
		  # This is because some ebuild (gcc) do not use $S as buildroot.
		  if test "$PWORKDIR"; then
		    S="$PWORKDIR"
		  fi
		  # We do not want portage's build root ($S) present.
		  my_little_ninja_foo_2=`echo $deplib |$EGREP -e "$S"`
		  # We do not want portage's install root ($D) present.
		  my_little_ninja_foo_3=`echo $deplib |$EGREP -e "$D"`
		  if test -n "$my_little_ninja_foo_2" && test "$S"; then
		    mynewdependency_lib=""
		  elif test -n "$my_little_ninja_foo_3" && test "$D"; then
		    eval mynewdependency_lib=`echo "$deplib" |sed -e "s:$D:/:g" -e 's:/\+:/:g'`
		  else
		    mynewdependency_lib="$deplib"
		  fi
		else
		  mynewdependency_lib="$deplib"
		fi
		# Do not add duplicates
		if test "$mynewdependency_lib"; then
		  my_little_ninja_foo_4=`echo $newdependency_libs |$EGREP -e "$mynewdependency_lib"`
		  if test -z "$my_little_ninja_foo_4"; then
			newdependency_libs="$newdependency_libs $mynewdependency_lib"
		  fi
		fi
		;;
	      esac
	    done
	    dependency_libs="$newdependency_libs"
	    newdlfiles=

	    for lib in $dlfiles; do
	      case $lib in
	      *.la)
	        func_basename "$lib"
		name="$func_basename_result"
		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
		test -z "$libdir" && \
		  func_fatal_error "\`$lib' is not a valid libtool archive"
		newdlfiles="$newdlfiles $libdir/$name"
		;;
	      *) newdlfiles="$newdlfiles $lib" ;;
	      esac
	    done
	    dlfiles="$newdlfiles"
	    newdlprefiles=
	    for lib in $dlprefiles; do
	      case $lib in
	      *.la)
		# Only pass preopened files to the pseudo-archive (for
		# eventual linking with the app. that links it) if we
		# didn't already link the preopened objects directly into
		# the library:
		func_basename "$lib"
		name="$func_basename_result"
		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
		test -z "$libdir" && \
		  func_fatal_error "\`$lib' is not a valid libtool archive"
		newdlprefiles="$newdlprefiles $libdir/$name"
		;;
	      esac
	    done
	    dlprefiles="$newdlprefiles"
	  else
	    newdlfiles=
	    for lib in $dlfiles; do
	      case $lib in
		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
		*) abs=`pwd`"/$lib" ;;
	      esac
	      newdlfiles="$newdlfiles $abs"
	    done
	    dlfiles="$newdlfiles"
	    newdlprefiles=
	    for lib in $dlprefiles; do
	      case $lib in
		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
		*) abs=`pwd`"/$lib" ;;
	      esac
	      newdlprefiles="$newdlprefiles $abs"
	    done
	    dlprefiles="$newdlprefiles"
	  fi
	  $RM $output
	  # place dlname in correct position for cygwin
	  tdlname=$dlname
	  case $host,$output,$installed,$module,$dlname in
	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
	  esac
	  # Do not add duplicates
	  if test "$installed" = yes && test "$D"; then
	    install_libdir=`echo "$install_libdir" |sed -e "s:$D:/:g" -e 's:/\+:/:g'`
	  fi
	  $ECHO > $output "\
# $outputname - a libtool library file
# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
#
# Please DO NOT delete this file!
# It is necessary for linking the library.

# The name that we can dlopen(3).
dlname='$tdlname'

# Names of this library.
library_names='$library_names'

# The name of the static archive.
old_library='$old_library'

# Linker flags that can not go in dependency_libs.
inherited_linker_flags='$new_inherited_linker_flags'

# Libraries that this one depends upon.
dependency_libs='$dependency_libs'

# Names of additional weak libraries provided by this library
weak_library_names='$weak_libs'

# Version information for $libname.
current=$current
age=$age
revision=$revision

# Is this an already installed library?
installed=$installed

# Should we warn about portability when linking against -modules?
shouldnotlink=$module

# Files to dlopen/dlpreopen
dlopen='$dlfiles'
dlpreopen='$dlprefiles'

# Directory that this library needs to be installed in:
libdir='$install_libdir'"
	  if test "$installed" = no && test "$need_relink" = yes; then
	    $ECHO >> $output "\
relink_command=\"$relink_command\""
	  fi
	done
      }

      # Do a symbolic link so that the libtool archive can be found in
      # LD_LIBRARY_PATH before the program is installed.
      func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?'
      ;;
    esac
    exit $EXIT_SUCCESS
}

{ test "$mode" = link || test "$mode" = relink; } &&
    func_mode_link ${1+"$@"}


# func_mode_uninstall arg...
func_mode_uninstall ()
{
    $opt_debug
    RM="$nonopt"
    files=
    rmforce=
    exit_status=0

    # This variable tells wrapper scripts just to set variables rather
    # than running their programs.
    libtool_install_magic="$magic"

    for arg
    do
      case $arg in
      -f) RM="$RM $arg"; rmforce=yes ;;
      -*) RM="$RM $arg" ;;
      *) files="$files $arg" ;;
      esac
    done

    test -z "$RM" && \
      func_fatal_help "you must specify an RM program"

    rmdirs=

    origobjdir="$objdir"
    for file in $files; do
      func_dirname "$file" "" "."
      dir="$func_dirname_result"
      if test "X$dir" = X.; then
	objdir="$origobjdir"
      else
	objdir="$dir/$origobjdir"
      fi
      func_basename "$file"
      name="$func_basename_result"
      test "$mode" = uninstall && objdir="$dir"

      # Remember objdir for removal later, being careful to avoid duplicates
      if test "$mode" = clean; then
	case " $rmdirs " in
	  *" $objdir "*) ;;
	  *) rmdirs="$rmdirs $objdir" ;;
	esac
      fi

      # Don't error if the file doesn't exist and rm -f was used.
      if { test -L "$file"; } >/dev/null 2>&1 ||
	 { test -h "$file"; } >/dev/null 2>&1 ||
	 test -f "$file"; then
	:
      elif test -d "$file"; then
	exit_status=1
	continue
      elif test "$rmforce" = yes; then
	continue
      fi

      rmfiles="$file"

      case $name in
      *.la)
	# Possibly a libtool archive, so verify it.
	if func_lalib_p "$file"; then
	  func_source $dir/$name

	  # Delete the libtool libraries and symlinks.
	  for n in $library_names; do
	    rmfiles="$rmfiles $objdir/$n"
	  done
	  test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"

	  case "$mode" in
	  clean)
	    case "  $library_names " in
	    # "  " in the beginning catches empty $dlname
	    *" $dlname "*) ;;
	    *) rmfiles="$rmfiles $objdir/$dlname" ;;
	    esac
	    test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
	    ;;
	  uninstall)
	    if test -n "$library_names"; then
	      # Do each command in the postuninstall commands.
	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
	    fi

	    if test -n "$old_library"; then
	      # Do each command in the old_postuninstall commands.
	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
	    fi
	    # FIXME: should reinstall the best remaining shared library.
	    ;;
	  esac
	fi
	;;

      *.lo)
	# Possibly a libtool object, so verify it.
	if func_lalib_p "$file"; then

	  # Read the .lo file
	  func_source $dir/$name

	  # Add PIC object to the list of files to remove.
	  if test -n "$pic_object" &&
	     test "$pic_object" != none; then
	    rmfiles="$rmfiles $dir/$pic_object"
	  fi

	  # Add non-PIC object to the list of files to remove.
	  if test -n "$non_pic_object" &&
	     test "$non_pic_object" != none; then
	    rmfiles="$rmfiles $dir/$non_pic_object"
	  fi
	fi
	;;

      *)
	if test "$mode" = clean ; then
	  noexename=$name
	  case $file in
	  *.exe)
	    func_stripname '' '.exe' "$file"
	    file=$func_stripname_result
	    func_stripname '' '.exe' "$name"
	    noexename=$func_stripname_result
	    # $file with .exe has already been added to rmfiles,
	    # add $file without .exe
	    rmfiles="$rmfiles $file"
	    ;;
	  esac
	  # Do a test to see if this is a libtool program.
	  if func_ltwrapper_p "$file"; then
	    if func_ltwrapper_executable_p "$file"; then
	      func_ltwrapper_scriptname "$file"
	      relink_command=
	      func_source $func_ltwrapper_scriptname_result
	      rmfiles="$rmfiles $func_ltwrapper_scriptname_result"
	    else
	      relink_command=
	      func_source $dir/$noexename
	    fi

	    # note $name still contains .exe if it was in $file originally
	    # as does the version of $file that was added into $rmfiles
	    rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
	    if test "$fast_install" = yes && test -n "$relink_command"; then
	      rmfiles="$rmfiles $objdir/lt-$name"
	    fi
	    if test "X$noexename" != "X$name" ; then
	      rmfiles="$rmfiles $objdir/lt-${noexename}.c"
	    fi
	  fi
	fi
	;;
      esac
      func_show_eval "$RM $rmfiles" 'exit_status=1'
    done
    objdir="$origobjdir"

    # Try to remove the ${objdir}s in the directories where we deleted files
    for dir in $rmdirs; do
      if test -d "$dir"; then
	func_show_eval "rmdir $dir >/dev/null 2>&1"
      fi
    done

    exit $exit_status
}

{ test "$mode" = uninstall || test "$mode" = clean; } &&
    func_mode_uninstall ${1+"$@"}

test -z "$mode" && {
  help="$generic_help"
  func_fatal_help "you must specify a MODE"
}

test -z "$exec_cmd" && \
  func_fatal_help "invalid operation mode \`$mode'"

if test -n "$exec_cmd"; then
  eval exec "$exec_cmd"
  exit $EXIT_FAILURE
fi

exit $exit_status


# The TAGs below are defined such that we never get into a situation
# in which we disable both kinds of libraries.  Given conflicting
# choices, we go for a static library, that is the most portable,
# since we can't tell whether shared libraries were disabled because
# the user asked for that or because the platform doesn't support
# them.  This is particularly important on AIX, because we don't
# support having both static and shared libraries enabled at the same
# time on that platform, so we default to a shared-only configuration.
# If a disable-shared tag is given, we'll fallback to a static-only
# configuration.  But we'll never go from static-only to shared-only.

# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
build_libtool_libs=no
build_old_libs=yes
# ### END LIBTOOL TAG CONFIG: disable-shared

# ### BEGIN LIBTOOL TAG CONFIG: disable-static
build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
# ### END LIBTOOL TAG CONFIG: disable-static

# Local Variables:
# mode:shell-script
# sh-indentation:2
# End:
# vi:sw=2

Added main.mk.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
###############################################################################
# The following macros should be defined before this script is
# invoked:
#
# TOP              The toplevel directory of the source tree.  This is the
#                  directory that contains this "Makefile.in" and the
#                  "configure.in" script.
#
# BCC              C Compiler and options for use in building executables that
#                  will run on the platform that is doing the build.
#
# THREADLIB        Specify any extra linker options needed to make the library
#                  thread safe
#
# OPTS             Extra compiler command-line options.
#
# EXE              The suffix to add to executable files.  ".exe" for windows
#                  and "" for Unix.
#
# TCC              C Compiler and options for use in building executables that 
#                  will run on the target platform.  This is usually the same
#                  as BCC, unless you are cross-compiling.
#
# AR               Tools used to build a static library.
# RANLIB
#
# TCL_FLAGS        Extra compiler options needed for programs that use the
#                  TCL library.
#
# LIBTCL           Linker options needed to link against the TCL library.
#
# READLINE_FLAGS   Compiler options needed for programs that use the
#                  readline() library.
#
# LIBREADLINE      Linker options needed by programs using readline() must
#                  link against.
#
# NAWK             Nawk compatible awk program.  Older (obsolete?) solaris
#                  systems need this to avoid using the original AT&T AWK.
#
# Once the macros above are defined, the rest of this make script will
# build the SQLite library and testing tools.
################################################################################

# This is how we compile
#
TCCX =  $(TCC) $(OPTS) -I. -I$(TOP)/src -I$(TOP) 
TCCX += -I$(TOP)/ext/rtree -I$(TOP)/ext/icu -I$(TOP)/ext/fts3
TCCX += -I$(TOP)/ext/async

# Object files for the SQLite library.
#
LIBOBJ+= alter.o analyze.o attach.o auth.o \
         backup.o bitvec.o btmutex.o btree.o build.o \
         callback.o complete.o date.o delete.o expr.o fault.o fkey.o \
         fts3.o fts3_expr.o fts3_hash.o fts3_icu.o fts3_porter.o \
         fts3_tokenizer.o fts3_tokenizer1.o \
         func.o global.o hash.o \
         icu.o insert.o journal.o legacy.o loadext.o \
         main.o malloc.o mem0.o mem1.o mem2.o mem3.o mem5.o \
         memjournal.o \
         mutex.o mutex_noop.o mutex_os2.o mutex_unix.o mutex_w32.o \
         notify.o opcodes.o os.o os_os2.o os_unix.o os_win.o \
         pager.o parse.o pcache.o pcache1.o pragma.o prepare.o printf.o \
         random.o resolve.o rowset.o rtree.o select.o status.o \
         table.o tokenize.o trigger.o \
         update.o util.o vacuum.o \
         vdbe.o vdbeapi.o vdbeaux.o vdbeblob.o vdbemem.o \
         walker.o where.o utf.o vtab.o



# All of the source code files.
#
SRC = \
  $(TOP)/src/alter.c \
  $(TOP)/src/analyze.c \
  $(TOP)/src/attach.c \
  $(TOP)/src/auth.c \
  $(TOP)/src/backup.c \
  $(TOP)/src/bitvec.c \
  $(TOP)/src/btmutex.c \
  $(TOP)/src/btree.c \
  $(TOP)/src/btree.h \
  $(TOP)/src/btreeInt.h \
  $(TOP)/src/build.c \
  $(TOP)/src/callback.c \
  $(TOP)/src/complete.c \
  $(TOP)/src/date.c \
  $(TOP)/src/delete.c \
  $(TOP)/src/expr.c \
  $(TOP)/src/fault.c \
  $(TOP)/src/fkey.c \
  $(TOP)/src/func.c \
  $(TOP)/src/global.c \
  $(TOP)/src/hash.c \
  $(TOP)/src/hash.h \
  $(TOP)/src/hwtime.h \
  $(TOP)/src/insert.c \
  $(TOP)/src/journal.c \
  $(TOP)/src/legacy.c \
  $(TOP)/src/loadext.c \
  $(TOP)/src/main.c \
  $(TOP)/src/malloc.c \
  $(TOP)/src/mem0.c \
  $(TOP)/src/mem1.c \
  $(TOP)/src/mem2.c \
  $(TOP)/src/mem3.c \
  $(TOP)/src/mem5.c \
  $(TOP)/src/memjournal.c \
  $(TOP)/src/mutex.c \
  $(TOP)/src/mutex.h \
  $(TOP)/src/mutex_noop.c \
  $(TOP)/src/mutex_os2.c \
  $(TOP)/src/mutex_unix.c \
  $(TOP)/src/mutex_w32.c \
  $(TOP)/src/notify.c \
  $(TOP)/src/os.c \
  $(TOP)/src/os.h \
  $(TOP)/src/os_common.h \
  $(TOP)/src/os_os2.c \
  $(TOP)/src/os_unix.c \
  $(TOP)/src/os_win.c \
  $(TOP)/src/pager.c \
  $(TOP)/src/pager.h \
  $(TOP)/src/parse.y \
  $(TOP)/src/pcache.c \
  $(TOP)/src/pcache.h \
  $(TOP)/src/pcache1.c \
  $(TOP)/src/pragma.c \
  $(TOP)/src/prepare.c \
  $(TOP)/src/printf.c \
  $(TOP)/src/random.c \
  $(TOP)/src/resolve.c \
  $(TOP)/src/rowset.c \
  $(TOP)/src/select.c \
  $(TOP)/src/status.c \
  $(TOP)/src/shell.c \
  $(TOP)/src/sqlite.h.in \
  $(TOP)/src/sqlite3ext.h \
  $(TOP)/src/sqliteInt.h \
  $(TOP)/src/sqliteLimit.h \
  $(TOP)/src/table.c \
  $(TOP)/src/tclsqlite.c \
  $(TOP)/src/tokenize.c \
  $(TOP)/src/trigger.c \
  $(TOP)/src/utf.c \
  $(TOP)/src/update.c \
  $(TOP)/src/util.c \
  $(TOP)/src/vacuum.c \
  $(TOP)/src/vdbe.c \
  $(TOP)/src/vdbe.h \
  $(TOP)/src/vdbeapi.c \
  $(TOP)/src/vdbeaux.c \
  $(TOP)/src/vdbeblob.c \
  $(TOP)/src/vdbemem.c \
  $(TOP)/src/vdbeInt.h \
  $(TOP)/src/vtab.c \
  $(TOP)/src/walker.c \
  $(TOP)/src/where.c

# Source code for extensions
#
SRC += \
  $(TOP)/ext/fts1/fts1.c \
  $(TOP)/ext/fts1/fts1.h \
  $(TOP)/ext/fts1/fts1_hash.c \
  $(TOP)/ext/fts1/fts1_hash.h \
  $(TOP)/ext/fts1/fts1_porter.c \
  $(TOP)/ext/fts1/fts1_tokenizer.h \
  $(TOP)/ext/fts1/fts1_tokenizer1.c
SRC += \
  $(TOP)/ext/fts2/fts2.c \
  $(TOP)/ext/fts2/fts2.h \
  $(TOP)/ext/fts2/fts2_hash.c \
  $(TOP)/ext/fts2/fts2_hash.h \
  $(TOP)/ext/fts2/fts2_icu.c \
  $(TOP)/ext/fts2/fts2_porter.c \
  $(TOP)/ext/fts2/fts2_tokenizer.h \
  $(TOP)/ext/fts2/fts2_tokenizer.c \
  $(TOP)/ext/fts2/fts2_tokenizer1.c
SRC += \
  $(TOP)/ext/fts3/fts3.c \
  $(TOP)/ext/fts3/fts3.h \
  $(TOP)/ext/fts3/fts3_expr.c \
  $(TOP)/ext/fts3/fts3_expr.h \
  $(TOP)/ext/fts3/fts3_hash.c \
  $(TOP)/ext/fts3/fts3_hash.h \
  $(TOP)/ext/fts3/fts3_icu.c \
  $(TOP)/ext/fts3/fts3_porter.c \
  $(TOP)/ext/fts3/fts3_tokenizer.h \
  $(TOP)/ext/fts3/fts3_tokenizer.c \
  $(TOP)/ext/fts3/fts3_tokenizer1.c
SRC += \
  $(TOP)/ext/icu/sqliteicu.h \
  $(TOP)/ext/icu/icu.c
SRC += \
  $(TOP)/ext/rtree/rtree.h \
  $(TOP)/ext/rtree/rtree.c


# Generated source code files
#
SRC += \
  keywordhash.h \
  opcodes.c \
  opcodes.h \
  parse.c \
  parse.h \
  sqlite3.h


# Source code to the test files.
#
TESTSRC = \
  $(TOP)/src/test1.c \
  $(TOP)/src/test2.c \
  $(TOP)/src/test3.c \
  $(TOP)/src/test4.c \
  $(TOP)/src/test5.c \
  $(TOP)/src/test6.c \
  $(TOP)/src/test7.c \
  $(TOP)/src/test8.c \
  $(TOP)/src/test9.c \
  $(TOP)/src/test_autoext.c \
  $(TOP)/src/test_async.c \
  $(TOP)/src/test_backup.c \
  $(TOP)/src/test_btree.c \
  $(TOP)/src/test_config.c \
  $(TOP)/src/test_devsym.c \
  $(TOP)/src/test_func.c \
  $(TOP)/src/test_hexio.c \
  $(TOP)/src/test_init.c \
  $(TOP)/src/test_journal.c \
  $(TOP)/src/test_malloc.c \
  $(TOP)/src/test_mutex.c \
  $(TOP)/src/test_onefile.c \
  $(TOP)/src/test_osinst.c \
  $(TOP)/src/test_pcache.c \
  $(TOP)/src/test_schema.c \
  $(TOP)/src/test_server.c \
  $(TOP)/src/test_tclvar.c \
  $(TOP)/src/test_thread.c \
  $(TOP)/src/test_wsd.c

#TESTSRC += $(TOP)/ext/fts2/fts2_tokenizer.c
#TESTSRC += $(TOP)/ext/fts3/fts3_tokenizer.c

TESTSRC2 = \
  $(TOP)/src/attach.c $(TOP)/src/backup.c $(TOP)/src/btree.c                   \
  $(TOP)/src/build.c $(TOP)/src/date.c                                         \
  $(TOP)/src/expr.c $(TOP)/src/func.c $(TOP)/src/insert.c $(TOP)/src/mem5.c    \
  $(TOP)/src/os.c                                                              \
  $(TOP)/src/os_os2.c $(TOP)/src/os_unix.c $(TOP)/src/os_win.c                 \
  $(TOP)/src/pager.c $(TOP)/src/pragma.c $(TOP)/src/prepare.c                  \
  $(TOP)/src/printf.c $(TOP)/src/random.c $(TOP)/src/pcache.c                  \
  $(TOP)/src/pcache1.c $(TOP)/src/select.c $(TOP)/src/tokenize.c               \
  $(TOP)/src/utf.c $(TOP)/src/util.c $(TOP)/src/vdbeapi.c $(TOP)/src/vdbeaux.c \
  $(TOP)/src/vdbe.c $(TOP)/src/vdbemem.c $(TOP)/src/where.c parse.c            \
  $(TOP)/ext/fts3/fts3.c $(TOP)/ext/fts3/fts3_expr.c                           \
  $(TOP)/ext/fts3/fts3_tokenizer.c                                             \
  $(TOP)/ext/async/sqlite3async.c

# Header files used by all library source files.
#
HDR = \
   $(TOP)/src/btree.h \
   $(TOP)/src/btreeInt.h \
   $(TOP)/src/hash.h \
   $(TOP)/src/hwtime.h \
   keywordhash.h \
   $(TOP)/src/mutex.h \
   opcodes.h \
   $(TOP)/src/os.h \
   $(TOP)/src/os_common.h \
   $(TOP)/src/pager.h \
   $(TOP)/src/pcache.h \
   parse.h  \
   sqlite3.h  \
   $(TOP)/src/sqlite3ext.h \
   $(TOP)/src/sqliteInt.h  \
   $(TOP)/src/sqliteLimit.h \
   $(TOP)/src/vdbe.h \
   $(TOP)/src/vdbeInt.h

# Header files used by extensions
#
EXTHDR += \
  $(TOP)/ext/fts1/fts1.h \
  $(TOP)/ext/fts1/fts1_hash.h \
  $(TOP)/ext/fts1/fts1_tokenizer.h
EXTHDR += \
  $(TOP)/ext/fts2/fts2.h \
  $(TOP)/ext/fts2/fts2_hash.h \
  $(TOP)/ext/fts2/fts2_tokenizer.h
EXTHDR += \
  $(TOP)/ext/fts3/fts3.h \
  $(TOP)/ext/fts3/fts3_expr.h \
  $(TOP)/ext/fts3/fts3_hash.h \
  $(TOP)/ext/fts3/fts3_tokenizer.h
EXTHDR += \
  $(TOP)/ext/rtree/rtree.h
EXTHDR += \
  $(TOP)/ext/icu/sqliteicu.h

# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.a sqlite3$(EXE)

libsqlite3.a:	$(LIBOBJ)
	$(AR) libsqlite3.a $(LIBOBJ)
	$(RANLIB) libsqlite3.a

sqlite3$(EXE):	$(TOP)/src/shell.c libsqlite3.a sqlite3.h
	$(TCCX) $(READLINE_FLAGS) -o sqlite3$(EXE)                  \
		$(TOP)/src/shell.c                                  \
		libsqlite3.a $(LIBREADLINE) $(TLIBS) $(THREADLIB)

objects: $(LIBOBJ_ORIG)

# This target creates a directory named "tsrc" and fills it with
# copies of all of the C source code and header files needed to
# build on the target system.  Some of the C source code and header
# files are automatically generated.  This target takes care of
# all that automatic generation.
#
target_source:	$(SRC) $(TOP)/tool/vdbe-compress.tcl
	rm -rf tsrc
	mkdir tsrc
	cp -f $(SRC) tsrc
	rm tsrc/sqlite.h.in tsrc/parse.y
	tclsh $(TOP)/tool/vdbe-compress.tcl <tsrc/vdbe.c >vdbe.new
	mv vdbe.new tsrc/vdbe.c
	touch target_source

sqlite3.c:	target_source $(TOP)/tool/mksqlite3c.tcl
	tclsh $(TOP)/tool/mksqlite3c.tcl
	cp sqlite3.c tclsqlite3.c
	cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c

fts2amal.c:	target_source $(TOP)/ext/fts2/mkfts2amal.tcl
	tclsh $(TOP)/ext/fts2/mkfts2amal.tcl

fts3amal.c:	target_source $(TOP)/ext/fts3/mkfts3amal.tcl
	tclsh $(TOP)/ext/fts3/mkfts3amal.tcl

# Rules to build the LEMON compiler generator
#
lemon:	$(TOP)/tool/lemon.c $(TOP)/src/lempar.c
	$(BCC) -o lemon $(TOP)/tool/lemon.c
	cp $(TOP)/src/lempar.c .

# Rules to build individual *.o files from generated *.c files. This
# applies to:
#
#     parse.o
#     opcodes.o
#
%.o: %.c $(HDR)
	$(TCCX) -c $<

# Rules to build individual *.o files from files in the src directory.
#
%.o: $(TOP)/src/%.c $(HDR)
	$(TCCX) -c $<

tclsqlite.o:	$(TOP)/src/tclsqlite.c $(HDR)
	$(TCCX) $(TCL_FLAGS) -c $(TOP)/src/tclsqlite.c



# Rules to build opcodes.c and opcodes.h
#
opcodes.c:	opcodes.h $(TOP)/mkopcodec.awk
	sort -n -b -k 3 opcodes.h | $(NAWK) -f $(TOP)/mkopcodec.awk >opcodes.c

opcodes.h:	parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk
	cat parse.h $(TOP)/src/vdbe.c | \
		$(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h

# Rules to build parse.c and parse.h - the outputs of lemon.
#
parse.h:	parse.c

parse.c:	$(TOP)/src/parse.y lemon $(TOP)/addopcodes.awk
	cp $(TOP)/src/parse.y .
	rm -f parse.h
	./lemon $(OPTS) parse.y
	mv parse.h parse.h.temp
	awk -f $(TOP)/addopcodes.awk parse.h.temp >parse.h

sqlite3.h:	$(TOP)/src/sqlite.h.in $(TOP)/manifest.uuid $(TOP)/VERSION
	tclsh $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h

keywordhash.h:	$(TOP)/tool/mkkeywordhash.c
	$(BCC) -o mkkeywordhash $(OPTS) $(TOP)/tool/mkkeywordhash.c
	./mkkeywordhash >keywordhash.h



# Rules to build the extension objects.
#
icu.o:	$(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c

fts2.o:	$(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c

fts2_hash.o:	$(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c

fts2_icu.o:	$(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c

fts2_porter.o:	$(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c

fts2_tokenizer.o:	$(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c

fts2_tokenizer1.o:	$(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c

fts3.o:	$(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c

fts3_expr.o:	$(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c

fts3_hash.o:	$(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c

fts3_icu.o:	$(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c

fts3_porter.o:	$(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c

fts3_tokenizer.o:	$(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c

fts3_tokenizer1.o:	$(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c

rtree.o:	$(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR)
	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c


# Rules for building test programs and for running tests
#
tclsqlite3:	$(TOP)/src/tclsqlite.c libsqlite3.a
	$(TCCX) $(TCL_FLAGS) -DTCLSH=1 -o tclsqlite3 \
		$(TOP)/src/tclsqlite.c libsqlite3.a $(LIBTCL) $(THREADLIB)


# Rules to build the 'testfixture' application.
#
TESTFIXTURE_FLAGS  = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1
TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE 

testfixture$(EXE): $(TESTSRC2) libsqlite3.a $(TESTSRC) $(TOP)/src/tclsqlite.c
	$(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS)                            \
		$(TESTSRC) $(TESTSRC2) $(TOP)/src/tclsqlite.c                \
		-o testfixture$(EXE) $(LIBTCL) $(THREADLIB) libsqlite3.a

amalgamation-testfixture$(EXE): sqlite3.c $(TESTSRC) $(TOP)/src/tclsqlite.c
	$(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS)                            \
		$(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c                  \
		-o testfixture$(EXE) $(LIBTCL) $(THREADLIB)

fts3-testfixture$(EXE): sqlite3.c fts3amal.c $(TESTSRC) $(TOP)/src/tclsqlite.c
	$(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS)                            \
	-DSQLITE_ENABLE_FTS3=1                                               \
		$(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c fts3amal.c       \
		-o testfixture$(EXE) $(LIBTCL) $(THREADLIB)

fulltest:	testfixture$(EXE) sqlite3$(EXE)
	./testfixture$(EXE) $(TOP)/test/all.test

soaktest:	testfixture$(EXE) sqlite3$(EXE)
	./testfixture$(EXE) $(TOP)/test/all.test -soak 1

test:	testfixture$(EXE) sqlite3$(EXE)
	./testfixture$(EXE) $(TOP)/test/veryquick.test

sqlite3_analyzer$(EXE):	$(TOP)/src/tclsqlite.c sqlite3.c $(TESTSRC) \
			$(TOP)/tool/spaceanal.tcl
	sed \
	  -e '/^#/d' \
	  -e 's,\\,\\\\,g' \
	  -e 's,",\\",g' \
	  -e 's,^,",' \
	  -e 's,$$,\\n",' \
	  $(TOP)/tool/spaceanal.tcl >spaceanal_tcl.h
	$(TCCX) $(TCL_FLAGS)                  $(TESTFIXTURE_FLAGS)                                 \
		-DTCLSH=2 -DSQLITE_TEST=1 -DSQLITE_DEBUG=1 -DSQLITE_PRIVATE="" \
		$(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c                    \
		-o sqlite3_analyzer$(EXE)                                      \
		$(LIBTCL) $(THREADLIB)

TEST_EXTENSION = $(SHPREFIX)testloadext.$(SO)
$(TEST_EXTENSION): $(TOP)/src/test_loadext.c
	$(MKSHLIB) $(TOP)/src/test_loadext.c -o $(TEST_EXTENSION)

extensiontest: testfixture$(EXE) $(TEST_EXTENSION)
	./testfixture$(EXE) $(TOP)/test/loadext.test


# Standard install and cleanup targets
#
install:	sqlite3 libsqlite3.a sqlite3.h
	mv sqlite3 /usr/bin
	mv libsqlite3.a /usr/lib
	mv sqlite3.h /usr/include

clean:	
	rm -f *.o sqlite3 libsqlite3.a sqlite3.h opcodes.*
	rm -f lemon lempar.c parse.* sqlite*.tar.gz mkkeywordhash keywordhash.h
	rm -f $(PUBLISH)
	rm -f *.da *.bb *.bbg gmon.out
	rm -rf tsrc target_source
	rm -f testloadext.dll libtestloadext.so
	rm -f sqlite3.c fts?amal.c tclsqlite3.c

Added mkdll.sh.



































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/sh
#
# This script is used to compile SQLite into a DLL.
#
# Two separate DLLs are generated.  "sqlite3.dll" is the core
# library.  "tclsqlite3.dll" contains the TCL bindings and is the
# library that is loaded into TCL in order to run SQLite.
#
make sqlite3.c
PATH=$PATH:/opt/mingw/bin
TCLDIR=/home/drh/tcltk/846/win/846win
TCLSTUBLIB=$TCLDIR/libtcl84stub.a
OPTS='-DUSE_TCL_STUBS=1 -DBUILD_sqlite=1 -DSQLITE_OS_WIN=1'
OPTS="$OPTS -DSQLITE_THREADSAFE=1"
OPTS="$OPTS -DSQLITE_ENABLE_FTS3=1"
OPTS="$OPTS -DSQLITE_ENABLE_RTREE=1"
OPTS="$OPTS -DSQLITE_ENABLE_COLUMN_METADATA=1"
CC="i386-mingw32msvc-gcc -Os $OPTS -Itsrc -I$TCLDIR"
NM="i386-mingw32msvc-nm"
CMD="$CC -c sqlite3.c"
echo $CMD
$CMD
CMD="$CC -c tclsqlite3.c"
echo $CMD
$CMD
echo 'EXPORTS' >tclsqlite3.def
$NM tclsqlite3.o | grep ' T ' >temp1
grep '_Init$' temp1 >temp2
grep '_SafeInit$' temp1 >>temp2
grep ' T _sqlite3_' temp1 >>temp2
echo 'EXPORTS' >tclsqlite3.def
sed 's/^.* T _//' temp2 | sort | uniq >>tclsqlite3.def
i386-mingw32msvc-dllwrap \
     --def tclsqlite3.def -v --export-all \
     --driver-name i386-mingw32msvc-gcc \
     --dlltool-name i386-mingw32msvc-dlltool \
     --as i386-mingw32msvc-as \
     --target i386-mingw32 \
     -dllname tclsqlite3.dll -lmsvcrt tclsqlite3.o $TCLSTUBLIB
$NM sqlite3.o | grep ' T ' >temp1
echo 'EXPORTS' >sqlite3.def
grep ' _sqlite3_' temp1 | sed 's/^.* _//' >>sqlite3.def
i386-mingw32msvc-dllwrap \
     --def sqlite3.def -v --export-all \
     --driver-name i386-mingw32msvc-gcc \
     --dlltool-name i386-mingw32msvc-dlltool \
     --as i386-mingw32msvc-as \
     --target i386-mingw32 \
     -dllname sqlite3.dll -lmsvcrt sqlite3.o

Added mkextu.sh.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/sh
#
# This script is used to compile SQLite into a shared library on Linux.
#
# Two separate shared libraries are generated.  "sqlite3.so" is the core
# library.  "tclsqlite3.so" contains the TCL bindings and is the
# library that is loaded into TCL in order to run SQLite.
#
CFLAGS=-O2 -Wall
make fts2amal.c
echo gcc $CFLAGS -shared fts2amal.c -o fts2.so
gcc $CFLAGS -shared fts2amal.c -o fts2.so
strip fts2.so

Added mkextw.sh.













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/sh
#
# This script is used to compile SQLite extensions into DLLs.
#
make fts2amal.c
PATH=$PATH:/opt/mingw/bin
OPTS='-DTHREADSAFE=1 -DBUILD_sqlite=1 -DSQLITE_OS_WIN=1'
CC="i386-mingw32msvc-gcc -O2 $OPTS -Itsrc"
NM="i386-mingw32msvc-nm"
CMD="$CC -c fts2amal.c"
echo $CMD
$CMD
echo 'EXPORTS' >fts2.def
echo 'sqlite3_extension_init' >>fts2.def
i386-mingw32msvc-dllwrap \
     --def fts2.def -v --export-all \
     --driver-name i386-mingw32msvc-gcc \
     --dlltool-name i386-mingw32msvc-dlltool \
     --as i386-mingw32msvc-as \
     --target i386-mingw32 \
     -dllname fts2.dll -lmsvcrt fts2amal.o
zip fts2dll.zip fts2.dll fts2.def

Added mkopcodec.awk.































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/awk -f
#
# This AWK script scans the opcodes.h file (which is itself generated by
# another awk script) and uses the information gleaned to create the
# opcodes.c source file.
#
# Opcodes.c contains strings which are the symbolic names for the various
# opcodes used by the VDBE.  These strings are used when disassembling a
# VDBE program during tracing or as a result of the EXPLAIN keyword.
#
BEGIN {
  print "/* Automatically generated.  Do not edit */"
  print "/* See the mkopcodec.awk script for details. */"
  printf "#if !defined(SQLITE_OMIT_EXPLAIN)"
  printf    " || !defined(NDEBUG)"
  printf    " || defined(VDBE_PROFILE)"
  print     " || defined(SQLITE_DEBUG)"
  print "const char *sqlite3OpcodeName(int i){"
  print " static const char *const azName[] = { \"?\","
}
/define OP_/ {
  sub("OP_","",$2)
  i++
  printf "     /* %3d */ \"%s\",\n", $3, $2
}
END {
  print "  };"
  print "  return azName[i];"
  print "}"
  print "#endif"
}

Added mkopcodeh.awk.

























































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/usr/bin/awk -f
#
# Generate the file opcodes.h.
#
# This AWK script scans a concatenation of the parse.h output file from the
# parser and the vdbe.c source file in order to generate the opcodes numbers
# for all opcodes.  
#
# The lines of the vdbe.c that we are interested in are of the form:
#
#       case OP_aaaa:      /* same as TK_bbbbb */
#
# The TK_ comment is optional.  If it is present, then the value assigned to
# the OP_ is the same as the TK_ value.  If missing, the OP_ value is assigned
# a small integer that is different from every other OP_ value.
#
# We go to the trouble of making some OP_ values the same as TK_ values
# as an optimization.  During parsing, things like expression operators
# are coded with TK_ values such as TK_ADD, TK_DIVIDE, and so forth.  Later
# during code generation, we need to generate corresponding opcodes like
# OP_Add and OP_Divide.  By making TK_ADD==OP_Add and TK_DIVIDE==OP_Divide,
# code to translate from one to the other is avoided.  This makes the
# code generator run (infinitesimally) faster and more importantly it makes
# the library footprint smaller.
#
# This script also scans for lines of the form:
#
#       case OP_aaaa:       /* jump, in1, in2, in3, out2-prerelease, out3 */
#
# When such comments are found on an opcode, it means that certain
# properties apply to that opcode.  Set corresponding flags using the
# OPFLG_INITIALIZER macro.
#


# Remember the TK_ values from the parse.h file
/^#define TK_/ {
  tk[$2] = 0+$3
}

# Scan for "case OP_aaaa:" lines in the vdbe.c file
/^case OP_/ {
  name = $2
  sub(/:/,"",name)
  sub("\r","",name)
  op[name] = -1
  jump[name] = 0
  out2_prerelease[name] = 0
  in1[name] = 0
  in2[name] = 0
  in3[name] = 0
  out3[name] = 0
  for(i=3; i<NF; i++){
    if($i=="same" && $(i+1)=="as"){
      sym = $(i+2)
      sub(/,/,"",sym)
      op[name] = tk[sym]
      used[op[name]] = 1
      sameas[op[name]] = sym
    }
    x = $i
    sub(",","",x)
    if(x=="jump"){
      jump[name] = 1
    }else if(x=="out2-prerelease"){
      out2_prerelease[name] = 1
    }else if(x=="in1"){
      in1[name] = 1
    }else if(x=="in2"){
      in2[name] = 1
    }else if(x=="in3"){
      in3[name] = 1
    }else if(x=="out3"){
      out3[name] = 1
    }
  }
  order[n_op++] = name;
}

# Assign numbers to all opcodes and output the result.
END {
  cnt = 0
  max = 0
  print "/* Automatically generated.  Do not edit */"
  print "/* See the mkopcodeh.awk script for details */"
  op["OP_Noop"] = -1;
  order[n_op++] = "OP_Noop";
  op["OP_Explain"] = -1;
  order[n_op++] = "OP_Explain";
  for(i=0; i<n_op; i++){
    name = order[i];
    if( op[name]<0 ){
      cnt++
      while( used[cnt] ) cnt++
      op[name] = cnt
    }
    used[op[name]] = 1;
    if( op[name]>max ) max = op[name]
    printf "#define %-25s %15d", name, op[name]
    if( sameas[op[name]] ) {
      printf "   /* same as %-12s*/", sameas[op[name]]
    } 
    printf "\n"

  }
  seenUnused = 0;
  for(i=1; i<max; i++){
    if( !used[i] ){
      if( !seenUnused ){
        printf "\n/* The following opcode values are never used */\n"
        seenUnused = 1
      }
      printf "#define %-25s %15d\n", sprintf( "OP_NotUsed_%-3d", i ), i
    }
  }

  # Generate the bitvectors:
  #
  #  bit 0:     jump
  #  bit 1:     pushes a result onto stack
  #  bit 2:     output to p1.  release p1 before opcode runs
  #
  for(i=0; i<=max; i++) bv[i] = 0;
  for(i=0; i<n_op; i++){
    name = order[i];
    x = op[name]
    a0 = a1 = a2 = a3 = a4 = a5 = a6 = a7 = 0
    # a8 = a9 = a10 = a11 = a12 = a13 = a14 = a15 = 0
    if( jump[name] ) a0 = 1;
    if( out2_prerelease[name] ) a1 = 2;
    if( in1[name] ) a2 = 4;
    if( in2[name] ) a3 = 8;
    if( in3[name] ) a4 = 16;
    if( out3[name] ) a5 = 32;
    # bv[x] = a0+a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12+a13+a14+a15;
    bv[x] = a0+a1+a2+a3+a4+a5+a6+a7;
  }
  print "\n"
  print "/* Properties such as \"out2\" or \"jump\" that are specified in"
  print "** comments following the \"case\" for each opcode in the vdbe.c"
  print "** are encoded into bitvectors as follows:"
  print "*/"
  print "#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */"
  print "#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */"
  print "#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */"
  print "#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */"
  print "#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */"
  print "#define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */"
  print "#define OPFLG_INITIALIZER {\\"
  for(i=0; i<=max; i++){
    if( i%8==0 ) printf("/* %3d */",i)
    printf " 0x%02x,", bv[i]
    if( i%8==7 ) printf("\\\n");
  }
  print "}"
}

Added mkso.sh.

































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/sh
#
# This script is used to compile SQLite into a shared library on Linux.
#
# Two separate shared libraries are generated.  "sqlite3.so" is the core
# library.  "tclsqlite3.so" contains the TCL bindings and is the
# library that is loaded into TCL in order to run SQLite.
#
make target_source
cd tsrc
rm shell.c
TCLDIR=/home/drh/tcltk/846/linux/846linux
TCLSTUBLIB=$TCLDIR/libtclstub8.4g.a
OPTS='-DUSE_TCL_STUBS=1 -DNDEBUG=1 -DHAVE_DLOPEN=1'
OPTS="$OPTS -DSQLITE_THREADSAFE=1"
OPTS="$OPTS -DSQLITE_ENABLE_FTS3=1"
OPTS="$OPTS -DSQLITE_ENABLE_COLUMN_METADATA=1"
for i in *.c; do
  if test $i != 'keywordhash.c'; then
    CMD="cc -fPIC $OPTS -O2 -I. -I$TCLDIR -c $i"
    echo $CMD
    $CMD
  fi
done
echo gcc -shared *.o $TCLSTUBLIB -o tclsqlite3.so
gcc -shared *.o $TCLSTUBLIB -o tclsqlite3.so
strip tclsqlite3.so
rm tclsqlite.c tclsqlite.o
echo gcc -shared *.o -o sqlite3.so
gcc -shared *.o -o sqlite3.so
strip sqlite3.so
cd ..

Added publish.sh.



















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/bin/sh
#
# This script is used to compile SQLite and package everything up
# so that it is ready to move to the SQLite website.
#

# Set srcdir to the name of the directory that contains the publish.sh
# script.
#
srcdir=`echo "$0" | sed 's%\(^.*\)/[^/][^/]*$%\1%'`

# Get the makefile.
#
cp $srcdir/Makefile.linux-gcc ./Makefile
chmod +x $srcdir/install-sh

# Get the current version number - needed to help build filenames
#
VERS=`cat $srcdir/VERSION`
VERSW=`sed 's/\./_/g' $srcdir/VERSION`
echo "VERSIONS: $VERS $VERSW"

# Start by building an sqlite shell for linux.
#
make clean
make sqlite3.c
CFLAGS="-Os -DSQLITE_ENABLE_FTS3=0 -DSQLITE_ENABLE_RTREE=0"
CFLAGS="$CFLAGS -DSQLITE_THREADSAFE=0"
echo '***** '"COMPILING sqlite3-$VERS.bin..."
gcc $CFLAGS -Itsrc sqlite3.c tsrc/shell.c -o sqlite3 -ldl
strip sqlite3
mv sqlite3 sqlite3-$VERS.bin
gzip sqlite3-$VERS.bin
chmod 644 sqlite3-$VERS.bin.gz
mv sqlite3-$VERS.bin.gz doc

# Build a source archive useful for windows.
#
make target_source
cd tsrc
echo '***** BUILDING preprocessed source archives'
rm fts[12]* icu*
rm -f ../doc/sqlite-source-$VERSW.zip
zip ../doc/sqlite-source-$VERSW.zip *
cd ..
cp tsrc/sqlite3.h tsrc/sqlite3ext.h .
pwd
zip doc/sqlite-amalgamation-$VERSW.zip sqlite3.c sqlite3.h sqlite3ext.h

# Build the sqlite.so and tclsqlite.so shared libraries
# under Linux
#
TCLDIR=/home/drh/tcltk/846/linux/846linux
TCLSTUBLIB=$TCLDIR/libtclstub8.4g.a
CFLAGS="-Os -DSQLITE_ENABLE_FTS3=3 -DSQLITE_ENABLE_RTREE=1"
CFLAGS="$CFLAGS -DHAVE_LOCALTIME_R=1 -DHAVE_GMTIME_R=1"
CFLAGS="$CFLAGS -DSQLITE_ENABLE_COLUMN_METADATA=1"
echo '***** BUILDING shared libraries for linux'
gcc $CFLAGS -shared tclsqlite3.c $TCLSTUBLIB -o tclsqlite3.so -lpthread
strip tclsqlite3.so
chmod 644 tclsqlite3.so
mv tclsqlite3.so tclsqlite-$VERS.so
gzip tclsqlite-$VERS.so
mv tclsqlite-$VERS.so.gz doc
gcc $CFLAGS -shared sqlite3.c -o sqlite3.so -lpthread
strip sqlite3.so
chmod 644 sqlite3.so
mv sqlite3.so sqlite-$VERS.so
gzip sqlite-$VERS.so
mv sqlite-$VERS.so.gz doc


# Build the tclsqlite3.dll and sqlite3.dll shared libraries.
#
. $srcdir/mkdll.sh
echo '***** PACKAGING shared libraries for windows'
echo zip doc/tclsqlite-$VERSW.zip tclsqlite3.dll
zip doc/tclsqlite-$VERSW.zip tclsqlite3.dll
echo zip doc/sqlitedll-$VERSW.zip sqlite3.dll sqlite3.def
zip doc/sqlitedll-$VERSW.zip sqlite3.dll sqlite3.def

# Build the sqlite.exe executable for windows.
#
OPTS='-DSTATIC_BUILD=1 -DNDEBUG=1 -DSQLITE_THREADSAFE=0'
OPTS="$OPTS -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_RTREE=1"
i386-mingw32msvc-gcc -Os $OPTS -Itsrc -I$TCLDIR sqlite3.c tsrc/shell.c \
      -o sqlite3.exe
zip doc/sqlite-$VERSW.zip sqlite3.exe

# Construct a tarball of the source tree
#
echo '***** BUILDING source archive'
ORIGIN=`pwd`
cd $srcdir
chmod +x configure
cd ..
mv sqlite sqlite-$VERS
EXCLUDE=`find sqlite-$VERS -print | egrep '(www/|art/|doc/|contrib/|_FOSSIL_)' | sed 's,^, --exclude ,'`
echo "tar czf $ORIGIN/doc/sqlite-$VERS.tar.gz $EXCLUDE sqlite-$VERS"
tar czf $ORIGIN/doc/sqlite-$VERS.tar.gz $EXCLUDE sqlite-$VERS
mv sqlite-$VERS sqlite
cd $ORIGIN

#
# Build RPMS (binary) and Source RPM
#

# Make sure we are properly setup to build RPMs
#
echo "%HOME %{expand:%%(cd; pwd)}" > $HOME/.rpmmacros
echo "%_topdir %{HOME}/rpm" >> $HOME/.rpmmacros
mkdir $HOME/rpm
mkdir $HOME/rpm/BUILD
mkdir $HOME/rpm/SOURCES
mkdir $HOME/rpm/RPMS
mkdir $HOME/rpm/SRPMS
mkdir $HOME/rpm/SPECS

# create the spec file from the template
sed s/SQLITE_VERSION/$VERS/g $srcdir/spec.template > $HOME/rpm/SPECS/sqlite.spec

# copy the source tarball to the rpm directory
cp doc/sqlite-$VERS.tar.gz $HOME/rpm/SOURCES/.

# build all the rpms
rpm -ba $HOME/rpm/SPECS/sqlite.spec >& rpm-$vers.log

# copy the RPMs into the build directory.
mv $HOME/rpm/RPMS/i386/sqlite*-$vers*.rpm doc
mv $HOME/rpm/SRPMS/sqlite-$vers*.rpm doc

# Build the website
#
#cp $srcdir/../historical/* doc
#make doc
#cd doc
#chmod 644 *.gz

Added publish_osx.sh.







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/bin/sh
#
# This script is used to compile SQLite and package everything up
# so that it is ready to move to the SQLite website.
#

# Set srcdir to the name of the directory that contains the publish.sh
# script.
#
srcdir=`echo "$0" | sed 's%\(^.*\)/[^/][^/]*$%\1%'`

# Get the makefile.
#
cp $srcdir/Makefile.linux-gcc ./Makefile
chmod +x $srcdir/install-sh

# Get the current version number - needed to help build filenames
#
VERS=`cat $srcdir/VERSION`
VERSW=`sed 's/\./_/g' $srcdir/VERSION`
echo "VERSIONS: $VERS $VERSW"

# Start by building an sqlite shell for linux.
#
make clean
make sqlite3.c
CFLAGS="-Os -DSQLITE_ENABLE_FTS3=1 -DSQLITE_THREADSAFE=0"
NAME=sqlite3-$VERS-osx-x86.bin
echo '***** '"COMPILING $NAME..."
gcc $CFLAGS -Itsrc sqlite3.c tsrc/shell.c -o $NAME -ldl
strip $NAME
chmod 644 $NAME
gzip $NAME
mkdir -p doc
mv $NAME.gz doc

Added spec.template.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
%define name sqlite
%define version SQLITE_VERSION
%define release 1

Name: %{name}
Summary: SQLite is a C library that implements an embeddable SQL database engine
Version: %{version}
Release: %{release}
Source: %{name}-%{version}.tar.gz
Group: System/Libraries
URL: http://www.sqlite.org/
License: Public Domain
BuildRoot: %{_tmppath}/%{name}-%{version}-root

%description
SQLite is a software library that implements a self-contained, serverless,
zero-configuration, transactional SQL database engine.
Programs that link with the SQLite library can have SQL database access
without running a separate RDBMS process. The distribution comes with a
standalone command-line access program (sqlite) that can be used to
administer an SQLite database and which serves as an example of how to
use the SQLite library.

%package -n %{name}-devel
Summary: Header files and libraries for developing apps which will use sqlite
Group: Development/C
Requires: %{name} = %{version}-%{release}

%description -n %{name}-devel
The sqlite-devel package contains the header files and libraries needed
to develop programs that use the SQLite database library.

%prep
%setup -q -n %{name}

%build
CFLAGS="%optflags -DNDEBUG=1" CXXFLAGS="%optflags -DNDEBUG=1" ./configure --prefix=%{_prefix}

make
make doc

%install
install -d $RPM_BUILD_ROOT/%{_prefix}
install -d $RPM_BUILD_ROOT/%{_prefix}/bin
install -d $RPM_BUILD_ROOT/%{_prefix}/include
install -d $RPM_BUILD_ROOT/%{_prefix}/lib
make install prefix=$RPM_BUILD_ROOT/%{_prefix}

%post -p /sbin/ldconfig

%postun -p /sbin/ldconfig

%clean
rm -fr $RPM_BUILD_ROOT

%files
%defattr(-, root, root)
%{_libdir}/*.so*
%{_bindir}/*

%files -n %{name}-devel
%defattr(-, root, root)
%{_libdir}/pkgconfig/sqlite3.pc
%{_libdir}/*.a
%{_libdir}/*.la
%{_includedir}/*
%doc doc/*

Added sqlite.pc.in.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
# Package Information for pkg-config

prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@

Name: SQLite
Description: SQL database engine
Version: @RELEASE@
Libs: -L${libdir} -lsqlite
Libs.private: @LIBS@
Cflags: -I${includedir}

Added sqlite3.1.











































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
.\"                                      Hey, EMACS: -*- nroff -*-
.\" First parameter, NAME, should be all caps
.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
.\" other parameters are allowed: see man(7), man(1)
.TH SQLITE3 1 "Mon Apr 15 23:49:17 2002"
.\" Please adjust this date whenever revising the manpage.
.\"
.\" Some roff macros, for reference:
.\" .nh        disable hyphenation
.\" .hy        enable hyphenation
.\" .ad l      left justify
.\" .ad b      justify to both left and right margins
.\" .nf        disable filling
.\" .fi        enable filling
.\" .br        insert line break
.\" .sp <n>    insert n+1 empty lines
.\" for manpage-specific macros, see man(7)
.SH NAME
.B sqlite3 
\- A command line interface for SQLite version 3

.SH SYNOPSIS
.B sqlite3
.RI [ options ]
.RI [ databasefile ]
.RI [ SQL ]

.SH SUMMARY
.PP
.B sqlite3
is a terminal-based front-end to the SQLite library that can evaluate
queries interactively and display the results in multiple formats.
.B sqlite3
can also be used within shell scripts and other applications to provide
batch processing features.

.SH DESCRIPTION
To start a
.B sqlite3
interactive session, invoke the
.B sqlite3
command and optionally provide the name of a database file.  If the
database file does not exist, it will be created.  If the database file
does exist, it will be opened.

For example, to create a new database file named "mydata.db", create
a table named "memos" and insert a couple of records into that table:
.sp
$ 
.B sqlite3 mydata.db
.br
SQLite version 3.1.3
.br
Enter ".help" for instructions
.br
sqlite>
.B create table memos(text, priority INTEGER);
.br
sqlite>
.B insert into memos values('deliver project description', 10);
.br
sqlite>
.B insert into memos values('lunch with Christine', 100);
.br
sqlite>
.B select * from memos;
.br
deliver project description|10
.br
lunch with Christine|100
.br
sqlite>
.sp

If no database name is supplied, the ATTACH sql command can be used
to attach to existing or create new database files.  ATTACH can also
be used to attach to multiple databases within the same interactive
session.  This is useful for migrating data between databases,
possibly changing the schema along the way.

Optionally, a SQL statement or set of SQL statements can be supplied as
a single argument.  Multiple statements should be separated by
semi-colons.

For example:
.sp
$ 
.B sqlite3 -line mydata.db 'select * from memos where priority > 20;'
.br
    text = lunch with Christine
.br
priority = 100
.br
.sp

.SS SQLITE META-COMMANDS
.PP
The interactive interpreter offers a set of meta-commands that can be
used to control the output format, examine the currently attached
database files, or perform administrative operations upon the
attached databases (such as rebuilding indices).   Meta-commands are
always prefixed with a dot (.).

A list of available meta-commands can be viewed at any time by issuing
the '.help' command.  For example:
.sp
sqlite>
.B .help
.nf
.cc |
.databases             List names and files of attached databases
.dump ?TABLE? ...      Dump the database in an SQL text format
.echo ON|OFF           Turn command echo on or off
.exit                  Exit this program
.explain ON|OFF        Turn output mode suitable for EXPLAIN on or off.
.header(s) ON|OFF      Turn display of headers on or off
.help                  Show this message
.import FILE TABLE     Import data from FILE into TABLE
.indices TABLE         Show names of all indices on TABLE
.mode MODE ?TABLE?     Set output mode where MODE is one of:
                         csv      Comma-separated values
                         column   Left-aligned columns.  (See .width)
                         html     HTML <table> code
                         insert   SQL insert statements for TABLE
                         line     One value per line
                         list     Values delimited by .separator string
                         tabs     Tab-separated values
                         tcl      TCL list elements
.nullvalue STRING      Print STRING in place of NULL values
.output FILENAME       Send output to FILENAME
.output stdout         Send output to the screen
.prompt MAIN CONTINUE  Replace the standard prompts
.quit                  Exit this program
.read FILENAME         Execute SQL in FILENAME
.schema ?TABLE?        Show the CREATE statements
.separator STRING      Change separator used by output mode and .import
.show                  Show the current values for various settings
.tables ?PATTERN?      List names of tables matching a LIKE pattern
.timeout MS            Try opening locked tables for MS milliseconds
.width NUM NUM ...     Set column widths for "column" mode
sqlite>
|cc .
.sp
.fi

.SH OPTIONS
.B sqlite3
has the following options:
.TP
.BI \-init\ file
Read and execute commands from
.I file
, which can contain a mix of SQL statements and meta-commands.
.TP
.B \-echo
Print commands before execution.
.TP
.B \-[no]header
Turn headers on or off.
.TP
.B \-column
Query results will be displayed in a table like form, using
whitespace characters to separate the columns and align the
output.
.TP
.B \-html
Query results will be output as simple HTML tables.
.TP
.B \-line
Query results will be displayed with one value per line, rows
separated by a blank line.  Designed to be easily parsed by
scripts or other programs
.TP
.B \-list
Query results will be displayed with the separator (|, by default)
character between each field value.  The default.
.TP
.BI \-separator\  separator
Set output field separator.  Default is '|'.
.TP
.BI \-nullvalue\  string
Set string used to represent NULL values.  Default is ''
(empty string).
.TP
.B \-version
Show SQLite version.
.TP
.B \-help
Show help on options and exit.


.SH INIT FILE
.B sqlite3
reads an initialization file to set the configuration of the
interactive environment.  Throughout initialization, any previously
specified setting can be overridden.  The sequence of initialization is
as follows:

o The default configuration is established as follows:

.sp
.nf
.cc |
mode            = LIST
separator       = "|"
main prompt     = "sqlite> "
continue prompt = "   ...> "
|cc .
.sp
.fi

o If the file 
.B ~/.sqliterc
exists, it is processed first.
can be found in the user's home directory, it is
read and processed.  It should generally only contain meta-commands.

o If the -init option is present, the specified file is processed.

o All other command line options are processed.

.SH SEE ALSO
http://www.sqlite.org/
.br
The sqlite-doc package
.SH AUTHOR
This manual page was originally written by Andreas Rottmann
<rotty@debian.org>, for the Debian GNU/Linux system (but may be used
by others).   It was subsequently revised by Bill Bumgarner <bbum@mac.com>.

Added sqlite3.pc.in.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
# Package Information for pkg-config

prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@

Name: SQLite
Description: SQL database engine
Version: @RELEASE@
Libs: -L${libdir} -lsqlite3
Libs.private: @LIBS@
Cflags: -I${includedir}

Added src/alter.c.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
/*
** 2005 February 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
**
** $Id: alter.c,v 1.62 2009/07/24 17:58:53 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#ifndef SQLITE_OMIT_ALTERTABLE


/*
** This function is used by SQL generated to implement the 
** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
** CREATE INDEX command. The second is a table name. The table name in 
** the CREATE TABLE or CREATE INDEX statement is replaced with the third
** argument and the result returned. Examples:
**
** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
**     -> 'CREATE TABLE def(a, b, c)'
**
** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
**     -> 'CREATE INDEX i ON def(a, b, c)'
*/
static void renameTableFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  unsigned char const *zSql = sqlite3_value_text(argv[0]);
  unsigned char const *zTableName = sqlite3_value_text(argv[1]);

  int token;
  Token tname;
  unsigned char const *zCsr = zSql;
  int len = 0;
  char *zRet;

  sqlite3 *db = sqlite3_context_db_handle(context);

  UNUSED_PARAMETER(NotUsed);

  /* The principle used to locate the table name in the CREATE TABLE 
  ** statement is that the table name is the first non-space token that
  ** is immediately followed by a TK_LP or TK_USING token.
  */
  if( zSql ){
    do {
      if( !*zCsr ){
        /* Ran out of input before finding an opening bracket. Return NULL. */
        return;
      }

      /* Store the token that zCsr points to in tname. */
      tname.z = (char*)zCsr;
      tname.n = len;

      /* Advance zCsr to the next token. Store that token type in 'token',
      ** and its length in 'len' (to be used next iteration of this loop).
      */
      do {
        zCsr += len;
        len = sqlite3GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP && token!=TK_USING );

    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  }
}

/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
** of any foreign key constraints that use the table being renamed as the 
** parent table. It is passed three arguments:
**
**   1) The complete text of the CREATE TABLE statement being modified,
**   2) The old name of the table being renamed, and
**   3) The new name of the table being renamed.
**
** It returns the new CREATE TABLE statement. For example:
**
**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
**       -> 'CREATE TABLE t1(a REFERENCES t3)'
*/
#ifndef SQLITE_OMIT_FOREIGN_KEY
static void renameParentFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  char *zOutput = 0;
  char *zResult;
  unsigned char const *zInput = sqlite3_value_text(argv[0]);
  unsigned char const *zOld = sqlite3_value_text(argv[1]);
  unsigned char const *zNew = sqlite3_value_text(argv[2]);

  unsigned const char *z;         /* Pointer to token */
  int n;                          /* Length of token z */
  int token;                      /* Type of token */

  UNUSED_PARAMETER(NotUsed);
  for(z=zInput; *z; z=z+n){
    n = sqlite3GetToken(z, &token);
    if( token==TK_REFERENCES ){
      char *zParent;
      do {
        z += n;
        n = sqlite3GetToken(z, &token);
      }while( token==TK_SPACE );

      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
      if( zParent==0 ) break;
      sqlite3Dequote(zParent);
      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
        );
        sqlite3DbFree(db, zOutput);
        zOutput = zOut;
        zInput = &z[n];
      }
      sqlite3DbFree(db, zParent);
    }
  }

  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  sqlite3DbFree(db, zOutput);
}
#endif

#ifndef SQLITE_OMIT_TRIGGER
/* This function is used by SQL generated to implement the
** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
** statement. The second is a table name. The table name in the CREATE 
** TRIGGER statement is replaced with the third argument and the result 
** returned. This is analagous to renameTableFunc() above, except for CREATE
** TRIGGER, not CREATE INDEX and CREATE TABLE.
*/
static void renameTriggerFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  unsigned char const *zSql = sqlite3_value_text(argv[0]);
  unsigned char const *zTableName = sqlite3_value_text(argv[1]);

  int token;
  Token tname;
  int dist = 3;
  unsigned char const *zCsr = zSql;
  int len = 0;
  char *zRet;
  sqlite3 *db = sqlite3_context_db_handle(context);

  UNUSED_PARAMETER(NotUsed);

  /* The principle used to locate the table name in the CREATE TRIGGER 
  ** statement is that the table name is the first token that is immediatedly
  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  ** of TK_WHEN, TK_BEGIN or TK_FOR.
  */
  if( zSql ){
    do {

      if( !*zCsr ){
        /* Ran out of input before finding the table name. Return NULL. */
        return;
      }

      /* Store the token that zCsr points to in tname. */
      tname.z = (char*)zCsr;
      tname.n = len;

      /* Advance zCsr to the next token. Store that token type in 'token',
      ** and its length in 'len' (to be used next iteration of this loop).
      */
      do {
        zCsr += len;
        len = sqlite3GetToken(zCsr, &token);
      }while( token==TK_SPACE );
      assert( len>0 );

      /* Variable 'dist' stores the number of tokens read since the most
      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
      ** token is read and 'dist' equals 2, the condition stated above
      ** to be met.
      **
      ** Note that ON cannot be a database, table or column name, so
      ** there is no need to worry about syntax like 
      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
      */
      dist++;
      if( token==TK_DOT || token==TK_ON ){
        dist = 0;
      }
    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );

    /* Variable tname now contains the token that is the old table-name
    ** in the CREATE TRIGGER statement.
    */
    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  }
}
#endif   /* !SQLITE_OMIT_TRIGGER */

/*
** Register built-in functions used to help implement ALTER TABLE
*/
void sqlite3AlterFunctions(sqlite3 *db){
  sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
                         renameTableFunc, 0, 0);
#ifndef SQLITE_OMIT_TRIGGER
  sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
                         renameTriggerFunc, 0, 0);
#endif
#ifndef SQLITE_OMIT_FOREIGN_KEY
  sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
                         renameParentFunc, 0, 0);
#endif
}

/*
** This function is used to create the text of expressions of the form:
**
**   name=<constant1> OR name=<constant2> OR ...
**
** If argument zWhere is NULL, then a pointer string containing the text 
** "name=<constant>" is returned, where <constant> is the quoted version
** of the string passed as argument zConstant. The returned buffer is
** allocated using sqlite3DbMalloc(). It is the responsibility of the
** caller to ensure that it is eventually freed.
**
** If argument zWhere is not NULL, then the string returned is 
** "<where> OR name=<constant>", where <where> is the contents of zWhere.
** In this case zWhere is passed to sqlite3DbFree() before returning.
** 
*/
static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  char *zNew;
  if( !zWhere ){
    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  }else{
    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
    sqlite3DbFree(db, zWhere);
  }
  return zNew;
}

#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
/*
** Generate the text of a WHERE expression which can be used to select all
** tables that have foreign key constraints that refer to table pTab (i.e.
** constraints for which pTab is the parent table) from the sqlite_master
** table.
*/
static char *whereForeignKeys(Parse *pParse, Table *pTab){
  FKey *p;
  char *zWhere = 0;
  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  }
  return zWhere;
}
#endif

/*
** Generate the text of a WHERE expression which can be used to select all
** temporary triggers on table pTab from the sqlite_temp_master table. If
** table pTab has no temporary triggers, or is itself stored in the 
** temporary database, NULL is returned.
*/
static char *whereTempTriggers(Parse *pParse, Table *pTab){
  Trigger *pTrig;
  char *zWhere = 0;
  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */

  /* If the table is not located in the temp-db (in which case NULL is 
  ** returned, loop through the tables list of triggers. For each trigger
  ** that is not part of the temp-db schema, add a clause to the WHERE 
  ** expression being built up in zWhere.
  */
  if( pTab->pSchema!=pTempSchema ){
    sqlite3 *db = pParse->db;
    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
      if( pTrig->pSchema==pTempSchema ){
        zWhere = whereOrName(db, zWhere, pTrig->zName);
      }
    }
  }
  return zWhere;
}

/*
** Generate code to drop and reload the internal representation of table
** pTab from the database, including triggers and temporary triggers.
** Argument zName is the name of the table in the database schema at
** the time the generated code is executed. This can be different from
** pTab->zName if this function is being called to code part of an 
** "ALTER TABLE RENAME TO" statement.
*/
static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  Vdbe *v;
  char *zWhere;
  int iDb;                   /* Index of database containing pTab */
#ifndef SQLITE_OMIT_TRIGGER
  Trigger *pTrig;
#endif

  v = sqlite3GetVdbe(pParse);
  if( NEVER(v==0) ) return;
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  assert( iDb>=0 );

#ifndef SQLITE_OMIT_TRIGGER
  /* Drop any table triggers from the internal schema. */
  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
    assert( iTrigDb==iDb || iTrigDb==1 );
    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  }
#endif

  /* Drop the table and index from the internal schema.  */
  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);

  /* Reload the table, index and permanent trigger schemas. */
  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  if( !zWhere ) return;
  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);

#ifndef SQLITE_OMIT_TRIGGER
  /* Now, if the table is not stored in the temp database, reload any temp 
  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
  */
  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
  }
#endif
}

/*
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
** command. 
*/
void sqlite3AlterRenameTable(
  Parse *pParse,            /* Parser context. */
  SrcList *pSrc,            /* The table to rename. */
  Token *pName              /* The new table name. */
){
  int iDb;                  /* Database that contains the table */
  char *zDb;                /* Name of database iDb */
  Table *pTab;              /* Table being renamed */
  char *zName = 0;          /* NULL-terminated version of pName */ 
  sqlite3 *db = pParse->db; /* Database connection */
  int nTabName;             /* Number of UTF-8 characters in zTabName */
  const char *zTabName;     /* Original name of the table */
  Vdbe *v;
#ifndef SQLITE_OMIT_TRIGGER
  char *zWhere = 0;         /* Where clause to locate temp triggers */
#endif
  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
  
  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  assert( pSrc->nSrc==1 );
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );

  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  if( !pTab ) goto exit_rename_table;
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  zDb = db->aDb[iDb].zName;

  /* Get a NULL terminated version of the new table name. */
  zName = sqlite3NameFromToken(db, pName);
  if( !zName ) goto exit_rename_table;

  /* Check that a table or index named 'zName' does not already exist
  ** in database iDb. If so, this is an error.
  */
  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
    sqlite3ErrorMsg(pParse, 
        "there is already another table or index with this name: %s", zName);
    goto exit_rename_table;
  }

  /* Make sure it is not a system table being altered, or a reserved name
  ** that the table is being renamed to.
  */
  if( sqlite3Strlen30(pTab->zName)>6 
   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
  ){
    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
    goto exit_rename_table;
  }
  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
    goto exit_rename_table;
  }

#ifndef SQLITE_OMIT_VIEW
  if( pTab->pSelect ){
    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
    goto exit_rename_table;
  }
#endif

#ifndef SQLITE_OMIT_AUTHORIZATION
  /* Invoke the authorization callback. */
  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
    goto exit_rename_table;
  }
#endif

#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto exit_rename_table;
  }
  if( IsVirtual(pTab) ){
    pVTab = sqlite3GetVTable(db, pTab);
    if( pVTab->pVtab->pModule->xRename==0 ){
      pVTab = 0;
    }
  }
#endif

  /* Begin a transaction and code the VerifyCookie for database iDb. 
  ** Then modify the schema cookie (since the ALTER TABLE modifies the
  ** schema). Open a statement transaction if the table is a virtual
  ** table.
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ){
    goto exit_rename_table;
  }
  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  sqlite3ChangeCookie(pParse, iDb);

  /* If this is a virtual table, invoke the xRename() function if
  ** one is defined. The xRename() callback will modify the names
  ** of any resources used by the v-table implementation (including other
  ** SQLite tables) that are identified by the name of the virtual table.
  */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( pVTab ){
    int i = ++pParse->nMem;
    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
    sqlite3MayAbort(pParse);
  }
#endif

  /* figure out how many UTF-8 characters are in zName */
  zTabName = pTab->zName;
  nTabName = sqlite3Utf8CharLen(zTabName, -1);

#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  if( db->flags&SQLITE_ForeignKeys ){
    /* If foreign-key support is enabled, rewrite the CREATE TABLE 
    ** statements corresponding to all child tables of foreign key constraints
    ** for which the renamed table is the parent table.  */
    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
      sqlite3NestedParse(pParse, 
          "UPDATE sqlite_master SET "
              "sql = sqlite_rename_parent(sql, %Q, %Q) "
              "WHERE %s;", zTabName, zName, zWhere);
      sqlite3DbFree(db, zWhere);
    }
  }
#endif

  /* Modify the sqlite_master table to use the new table name. */
  sqlite3NestedParse(pParse,
      "UPDATE %Q.%s SET "
#ifdef SQLITE_OMIT_TRIGGER
          "sql = sqlite_rename_table(sql, %Q), "
#else
          "sql = CASE "
            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
            "ELSE sqlite_rename_table(sql, %Q) END, "
#endif
          "tbl_name = %Q, "
          "name = CASE "
            "WHEN type='table' THEN %Q "
            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
            "ELSE name END "
      "WHERE tbl_name=%Q AND "
          "(type='table' OR type='index' OR type='trigger');", 
      zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
#ifndef SQLITE_OMIT_TRIGGER
      zName,
#endif
      zName, nTabName, zTabName
  );

#ifndef SQLITE_OMIT_AUTOINCREMENT
  /* If the sqlite_sequence table exists in this database, then update 
  ** it with the new table name.
  */
  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
    sqlite3NestedParse(pParse,
        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
        zDb, zName, pTab->zName);
  }
#endif

#ifndef SQLITE_OMIT_TRIGGER
  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  ** table. Don't do this if the table being ALTERed is itself located in
  ** the temp database.
  */
  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
    sqlite3NestedParse(pParse, 
        "UPDATE sqlite_temp_master SET "
            "sql = sqlite_rename_trigger(sql, %Q), "
            "tbl_name = %Q "
            "WHERE %s;", zName, zName, zWhere);
    sqlite3DbFree(db, zWhere);
  }
#endif

#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  if( db->flags&SQLITE_ForeignKeys ){
    FKey *p;
    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
      Table *pFrom = p->pFrom;
      if( pFrom!=pTab ){
        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
      }
    }
  }
#endif

  /* Drop and reload the internal table schema. */
  reloadTableSchema(pParse, pTab, zName);

exit_rename_table:
  sqlite3SrcListDelete(db, pSrc);
  sqlite3DbFree(db, zName);
}


/*
** Generate code to make sure the file format number is at least minFormat.
** The generated code will increase the file format number if necessary.
*/
void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  Vdbe *v;
  v = sqlite3GetVdbe(pParse);
  /* The VDBE should have been allocated before this routine is called.
  ** If that allocation failed, we would have quit before reaching this
  ** point */
  if( ALWAYS(v) ){
    int r1 = sqlite3GetTempReg(pParse);
    int r2 = sqlite3GetTempReg(pParse);
    int j1;
    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
    sqlite3VdbeUsesBtree(v, iDb);
    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
    sqlite3VdbeJumpHere(v, j1);
    sqlite3ReleaseTempReg(pParse, r1);
    sqlite3ReleaseTempReg(pParse, r2);
  }
}

/*
** This function is called after an "ALTER TABLE ... ADD" statement
** has been parsed. Argument pColDef contains the text of the new
** column definition.
**
** The Table structure pParse->pNewTable was extended to include
** the new column during parsing.
*/
void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  Table *pNew;              /* Copy of pParse->pNewTable */
  Table *pTab;              /* Table being altered */
  int iDb;                  /* Database number */
  const char *zDb;          /* Database name */
  const char *zTab;         /* Table name */
  char *zCol;               /* Null-terminated column definition */
  Column *pCol;             /* The new column */
  Expr *pDflt;              /* Default value for the new column */
  sqlite3 *db;              /* The database connection; */

  db = pParse->db;
  if( pParse->nErr || db->mallocFailed ) return;
  pNew = pParse->pNewTable;
  assert( pNew );

  assert( sqlite3BtreeHoldsAllMutexes(db) );
  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  zDb = db->aDb[iDb].zName;
  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
  pCol = &pNew->aCol[pNew->nCol-1];
  pDflt = pCol->pDflt;
  pTab = sqlite3FindTable(db, zTab, zDb);
  assert( pTab );

#ifndef SQLITE_OMIT_AUTHORIZATION
  /* Invoke the authorization callback. */
  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
    return;
  }
#endif

  /* If the default value for the new column was specified with a 
  ** literal NULL, then set pDflt to 0. This simplifies checking
  ** for an SQL NULL default below.
  */
  if( pDflt && pDflt->op==TK_NULL ){
    pDflt = 0;
  }

  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  ** If there is a NOT NULL constraint, then the default value for the
  ** column must not be NULL.
  */
  if( pCol->isPrimKey ){
    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
    return;
  }
  if( pNew->pIndex ){
    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
    return;
  }
  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
    sqlite3ErrorMsg(pParse, 
        "Cannot add a REFERENCES column with non-NULL default value");
    return;
  }
  if( pCol->notNull && !pDflt ){
    sqlite3ErrorMsg(pParse, 
        "Cannot add a NOT NULL column with default value NULL");
    return;
  }

  /* Ensure the default expression is something that sqlite3ValueFromExpr()
  ** can handle (i.e. not CURRENT_TIME etc.)
  */
  if( pDflt ){
    sqlite3_value *pVal;
    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
      db->mallocFailed = 1;
      return;
    }
    if( !pVal ){
      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
      return;
    }
    sqlite3ValueFree(pVal);
  }

  /* Modify the CREATE TABLE statement. */
  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  if( zCol ){
    char *zEnd = &zCol[pColDef->n-1];
    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
      *zEnd-- = '\0';
    }
    sqlite3NestedParse(pParse, 
        "UPDATE \"%w\".%s SET "
          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
        "WHERE type = 'table' AND name = %Q", 
      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
      zTab
    );
    sqlite3DbFree(db, zCol);
  }

  /* If the default value of the new column is NULL, then set the file
  ** format to 2. If the default value of the new column is not NULL,
  ** the file format becomes 3.
  */
  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);

  /* Reload the schema of the modified table. */
  reloadTableSchema(pParse, pTab, pTab->zName);
}

/*
** This function is called by the parser after the table-name in
** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
** pSrc is the full-name of the table being altered.
**
** This routine makes a (partial) copy of the Table structure
** for the table being altered and sets Parse.pNewTable to point
** to it. Routines called by the parser as the column definition
** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
** the copy. The copy of the Table structure is deleted by tokenize.c 
** after parsing is finished.
**
** Routine sqlite3AlterFinishAddColumn() will be called to complete
** coding the "ALTER TABLE ... ADD" statement.
*/
void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  Table *pNew;
  Table *pTab;
  Vdbe *v;
  int iDb;
  int i;
  int nAlloc;
  sqlite3 *db = pParse->db;

  /* Look up the table being altered. */
  assert( pParse->pNewTable==0 );
  assert( sqlite3BtreeHoldsAllMutexes(db) );
  if( db->mallocFailed ) goto exit_begin_add_column;
  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  if( !pTab ) goto exit_begin_add_column;

#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( IsVirtual(pTab) ){
    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
    goto exit_begin_add_column;
  }
#endif

  /* Make sure this is not an attempt to ALTER a view. */
  if( pTab->pSelect ){
    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
    goto exit_begin_add_column;
  }

  assert( pTab->addColOffset>0 );
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);

  /* Put a copy of the Table struct in Parse.pNewTable for the
  ** sqlite3AddColumn() function and friends to modify.  But modify
  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
  ** prefix, we insure that the name will not collide with an existing
  ** table because user table are not allowed to have the "sqlite_"
  ** prefix on their name.
  */
  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  if( !pNew ) goto exit_begin_add_column;
  pParse->pNewTable = pNew;
  pNew->nRef = 1;
  pNew->dbMem = pTab->dbMem;
  pNew->nCol = pTab->nCol;
  assert( pNew->nCol>0 );
  nAlloc = (((pNew->nCol-1)/8)*8)+8;
  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  if( !pNew->aCol || !pNew->zName ){
    db->mallocFailed = 1;
    goto exit_begin_add_column;
  }
  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  for(i=0; i<pNew->nCol; i++){
    Column *pCol = &pNew->aCol[i];
    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
    pCol->zColl = 0;
    pCol->zType = 0;
    pCol->pDflt = 0;
    pCol->zDflt = 0;
  }
  pNew->pSchema = db->aDb[iDb].pSchema;
  pNew->addColOffset = pTab->addColOffset;
  pNew->nRef = 1;

  /* Begin a transaction and increment the schema cookie.  */
  sqlite3BeginWriteOperation(pParse, 0, iDb);
  v = sqlite3GetVdbe(pParse);
  if( !v ) goto exit_begin_add_column;
  sqlite3ChangeCookie(pParse, iDb);

exit_begin_add_column:
  sqlite3SrcListDelete(db, pSrc);
  return;
}
#endif  /* SQLITE_ALTER_TABLE */

Added src/analyze.c.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
/*
** 2005 July 8
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code associated with the ANALYZE command.
**
** @(#) $Id: analyze.c,v 1.52 2009/04/16 17:45:48 drh Exp $
*/
#ifndef SQLITE_OMIT_ANALYZE
#include "sqliteInt.h"

/*
** This routine generates code that opens the sqlite_stat1 table for
** writing with cursor iStatCur. If the library was built with the
** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
** opened for writing using cursor (iStatCur+1)
**
** If the sqlite_stat1 tables does not previously exist, it is created.
** Similarly, if the sqlite_stat2 table does not exist and the library
** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
**
** Argument zWhere may be a pointer to a buffer containing a table name,
** or it may be a NULL pointer. If it is not NULL, then all entries in
** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
** with the named table are deleted. If zWhere==0, then code is generated
** to delete all stat table entries.
*/
static void openStatTable(
  Parse *pParse,          /* Parsing context */
  int iDb,                /* The database we are looking in */
  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
  const char *zWhere      /* Delete entries associated with this table */
){
  static struct {
    const char *zName;
    const char *zCols;
  } aTable[] = {
    { "sqlite_stat1", "tbl,idx,stat" },
#ifdef SQLITE_ENABLE_STAT2
    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
#endif
  };

  int aRoot[] = {0, 0};
  u8 aCreateTbl[] = {0, 0};

  int i;
  sqlite3 *db = pParse->db;
  Db *pDb;
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( v==0 ) return;
  assert( sqlite3BtreeHoldsAllMutexes(db) );
  assert( sqlite3VdbeDb(v)==db );
  pDb = &db->aDb[iDb];

  for(i=0; i<ArraySize(aTable); i++){
    const char *zTab = aTable[i].zName;
    Table *pStat;
    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
      /* The sqlite_stat[12] table does not exist. Create it. Note that a 
      ** side-effect of the CREATE TABLE statement is to leave the rootpage 
      ** of the new table in register pParse->regRoot. This is important 
      ** because the OpenWrite opcode below will be needing it. */
      sqlite3NestedParse(pParse,
          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
      );
      aRoot[i] = pParse->regRoot;
      aCreateTbl[i] = 1;
    }else{
      /* The table already exists. If zWhere is not NULL, delete all entries 
      ** associated with the table zWhere. If zWhere is NULL, delete the
      ** entire contents of the table. */
      aRoot[i] = pStat->tnum;
      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
      if( zWhere ){
        sqlite3NestedParse(pParse,
           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
        );
      }else{
        /* The sqlite_stat[12] table already exists.  Delete all rows. */
        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
      }
    }
  }

  /* Open the sqlite_stat[12] tables for writing. */
  for(i=0; i<ArraySize(aTable); i++){
    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  }
}

/*
** Generate code to do an analysis of all indices associated with
** a single table.
*/
static void analyzeOneTable(
  Parse *pParse,   /* Parser context */
  Table *pTab,     /* Table whose indices are to be analyzed */
  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
  int iMem         /* Available memory locations begin here */
){
  sqlite3 *db = pParse->db;    /* Database handle */
  Index *pIdx;                 /* An index to being analyzed */
  int iIdxCur;                 /* Cursor open on index being analyzed */
  Vdbe *v;                     /* The virtual machine being built up */
  int i;                       /* Loop counter */
  int topOfLoop;               /* The top of the loop */
  int endOfLoop;               /* The end of the loop */
  int addr;                    /* The address of an instruction */
  int iDb;                     /* Index of database containing pTab */
  int regTabname = iMem++;     /* Register containing table name */
  int regIdxname = iMem++;     /* Register containing index name */
  int regSampleno = iMem++;    /* Register containing next sample number */
  int regCol = iMem++;         /* Content of a column analyzed table */
  int regRec = iMem++;         /* Register holding completed record */
  int regTemp = iMem++;        /* Temporary use register */
  int regRowid = iMem++;       /* Rowid for the inserted record */

#ifdef SQLITE_ENABLE_STAT2
  int regTemp2 = iMem++;       /* Temporary use register */
  int regSamplerecno = iMem++; /* Index of next sample to record */
  int regRecno = iMem++;       /* Current sample index */
  int regLast = iMem++;        /* Index of last sample to record */
  int regFirst = iMem++;       /* Index of first sample to record */
#endif

  v = sqlite3GetVdbe(pParse);
  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
    /* Do no analysis for tables that have no indices */
    return;
  }
  assert( sqlite3BtreeHoldsAllMutexes(db) );
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  assert( iDb>=0 );
#ifndef SQLITE_OMIT_AUTHORIZATION
  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
      db->aDb[iDb].zName ) ){
    return;
  }
#endif

  /* Establish a read-lock on the table at the shared-cache level. */
  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);

  iIdxCur = pParse->nTab++;
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
    int nCol = pIdx->nColumn;
    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);

    if( iMem+1+(nCol*2)>pParse->nMem ){
      pParse->nMem = iMem+1+(nCol*2);
    }

    /* Open a cursor to the index to be analyzed. */
    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
        (char *)pKey, P4_KEYINFO_HANDOFF);
    VdbeComment((v, "%s", pIdx->zName));

    /* Populate the registers containing the table and index names. */
    if( pTab->pIndex==pIdx ){
      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
    }
    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);

#ifdef SQLITE_ENABLE_STAT2

    /* If this iteration of the loop is generating code to analyze the
    ** first index in the pTab->pIndex list, then register regLast has
    ** not been populated. In this case populate it now.  */
    if( pTab->pIndex==pIdx ){
      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);

      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
      sqlite3VdbeJumpHere(v, addr);
    }

    /* Zero the regSampleno and regRecno registers. */
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
#endif

    /* The block of memory cells initialized here is used as follows.
    **
    **    iMem:                
    **        The total number of rows in the table.
    **
    **    iMem+1 .. iMem+nCol: 
    **        Number of distinct entries in index considering the 
    **        left-most N columns only, where N is between 1 and nCol, 
    **        inclusive.
    **
    **    iMem+nCol+1 .. Mem+2*nCol:  
    **        Previous value of indexed columns, from left to right.
    **
    ** Cells iMem through iMem+nCol are initialized to 0. The others are 
    ** initialized to contain an SQL NULL.
    */
    for(i=0; i<=nCol; i++){
      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
    }
    for(i=0; i<nCol; i++){
      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
    }

    /* Start the analysis loop. This loop runs through all the entries in
    ** the index b-tree.  */
    endOfLoop = sqlite3VdbeMakeLabel(v);
    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
    topOfLoop = sqlite3VdbeCurrentAddr(v);
    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);

    for(i=0; i<nCol; i++){
      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
#ifdef SQLITE_ENABLE_STAT2
      if( i==0 ){
        /* Check if the record that cursor iIdxCur points to contains a
        ** value that should be stored in the sqlite_stat2 table. If so,
        ** store it.  */
        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
        assert( regTabname+1==regIdxname 
             && regTabname+2==regSampleno
             && regTabname+3==regCol
        );
        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);

        /* Calculate new values for regSamplerecno and regSampleno.
        **
        **   sampleno = sampleno + 1
        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
        */
        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);

        sqlite3VdbeJumpHere(v, ne);
        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
      }
#endif

      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
      /**** TODO:  add collating sequence *****/
      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
    }
    if( db->mallocFailed ){
      /* If a malloc failure has occurred, then the result of the expression 
      ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
      ** below may be negative. Which causes an assert() to fail (or an
      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
      return;
    }
    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
    for(i=0; i<nCol; i++){
      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
    }

    /* End of the analysis loop. */
    sqlite3VdbeResolveLabel(v, endOfLoop);
    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);

    /* Store the results in sqlite_stat1.
    **
    ** The result is a single row of the sqlite_stat1 table.  The first
    ** two columns are the names of the table and index.  The third column
    ** is a string composed of a list of integer statistics about the
    ** index.  The first integer in the list is the total number of entries
    ** in the index.  There is one additional integer in the list for each
    ** column of the table.  This additional integer is a guess of how many
    ** rows of the table the index will select.  If D is the count of distinct
    ** values and K is the total number of rows, then the integer is computed
    ** as:
    **
    **        I = (K+D-1)/D
    **
    ** If K==0 then no entry is made into the sqlite_stat1 table.  
    ** If K>0 then it is always the case the D>0 so division by zero
    ** is never possible.
    */
    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
    for(i=0; i<nCol; i++){
      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
    }
    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
    sqlite3VdbeJumpHere(v, addr);
  }
}

/*
** Generate code that will cause the most recent index analysis to
** be laoded into internal hash tables where is can be used.
*/
static void loadAnalysis(Parse *pParse, int iDb){
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  }
}

/*
** Generate code that will do an analysis of an entire database
*/
static void analyzeDatabase(Parse *pParse, int iDb){
  sqlite3 *db = pParse->db;
  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
  HashElem *k;
  int iStatCur;
  int iMem;

  sqlite3BeginWriteOperation(pParse, 0, iDb);
  iStatCur = pParse->nTab;
  pParse->nTab += 2;
  openStatTable(pParse, iDb, iStatCur, 0);
  iMem = pParse->nMem+1;
  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
    Table *pTab = (Table*)sqliteHashData(k);
    analyzeOneTable(pParse, pTab, iStatCur, iMem);
  }
  loadAnalysis(pParse, iDb);
}

/*
** Generate code that will do an analysis of a single table in
** a database.
*/
static void analyzeTable(Parse *pParse, Table *pTab){
  int iDb;
  int iStatCur;

  assert( pTab!=0 );
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  sqlite3BeginWriteOperation(pParse, 0, iDb);
  iStatCur = pParse->nTab;
  pParse->nTab += 2;
  openStatTable(pParse, iDb, iStatCur, pTab->zName);
  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
  loadAnalysis(pParse, iDb);
}

/*
** Generate code for the ANALYZE command.  The parser calls this routine
** when it recognizes an ANALYZE command.
**
**        ANALYZE                            -- 1
**        ANALYZE  <database>                -- 2
**        ANALYZE  ?<database>.?<tablename>  -- 3
**
** Form 1 causes all indices in all attached databases to be analyzed.
** Form 2 analyzes all indices the single database named.
** Form 3 analyzes all indices associated with the named table.
*/
void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  sqlite3 *db = pParse->db;
  int iDb;
  int i;
  char *z, *zDb;
  Table *pTab;
  Token *pTableName;

  /* Read the database schema. If an error occurs, leave an error message
  ** and code in pParse and return NULL. */
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    return;
  }

  assert( pName2!=0 || pName1==0 );
  if( pName1==0 ){
    /* Form 1:  Analyze everything */
    for(i=0; i<db->nDb; i++){
      if( i==1 ) continue;  /* Do not analyze the TEMP database */
      analyzeDatabase(pParse, i);
    }
  }else if( pName2->n==0 ){
    /* Form 2:  Analyze the database or table named */
    iDb = sqlite3FindDb(db, pName1);
    if( iDb>=0 ){
      analyzeDatabase(pParse, iDb);
    }else{
      z = sqlite3NameFromToken(db, pName1);
      if( z ){
        pTab = sqlite3LocateTable(pParse, 0, z, 0);
        sqlite3DbFree(db, z);
        if( pTab ){
          analyzeTable(pParse, pTab);
        }
      }
    }
  }else{
    /* Form 3: Analyze the fully qualified table name */
    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
    if( iDb>=0 ){
      zDb = db->aDb[iDb].zName;
      z = sqlite3NameFromToken(db, pTableName);
      if( z ){
        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
        sqlite3DbFree(db, z);
        if( pTab ){
          analyzeTable(pParse, pTab);
        }
      }
    }   
  }
}

/*
** Used to pass information from the analyzer reader through to the
** callback routine.
*/
typedef struct analysisInfo analysisInfo;
struct analysisInfo {
  sqlite3 *db;
  const char *zDatabase;
};

/*
** This callback is invoked once for each index when reading the
** sqlite_stat1 table.  
**
**     argv[0] = name of the index
**     argv[1] = results of analysis - on integer for each column
*/
static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  analysisInfo *pInfo = (analysisInfo*)pData;
  Index *pIndex;
  int i, c;
  unsigned int v;
  const char *z;

  assert( argc==2 );
  UNUSED_PARAMETER2(NotUsed, argc);

  if( argv==0 || argv[0]==0 || argv[1]==0 ){
    return 0;
  }
  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
  if( pIndex==0 ){
    return 0;
  }
  z = argv[1];
  for(i=0; *z && i<=pIndex->nColumn; i++){
    v = 0;
    while( (c=z[0])>='0' && c<='9' ){
      v = v*10 + c - '0';
      z++;
    }
    pIndex->aiRowEst[i] = v;
    if( *z==' ' ) z++;
  }
  return 0;
}

/*
** If the Index.aSample variable is not NULL, delete the aSample[] array
** and its contents.
*/
void sqlite3DeleteIndexSamples(Index *pIdx){
#ifdef SQLITE_ENABLE_STAT2
  if( pIdx->aSample ){
    int j;
    sqlite3 *dbMem = pIdx->pTable->dbMem;
    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
      IndexSample *p = &pIdx->aSample[j];
      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
      }
    }
    sqlite3DbFree(dbMem, pIdx->aSample);
    pIdx->aSample = 0;
  }
#else
  UNUSED_PARAMETER(pIdx);
#endif
}

/*
** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
** arrays. The contents of sqlite_stat2 are used to populate the
** Index.aSample[] arrays.
**
** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
** during compilation and the sqlite_stat2 table is present, no data is 
** read from it.
**
** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
** returned. However, in this case, data is read from the sqlite_stat1
** table (if it is present) before returning.
**
** If an OOM error occurs, this function always sets db->mallocFailed.
** This means if the caller does not care about other errors, the return
** code may be ignored.
*/
int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  analysisInfo sInfo;
  HashElem *i;
  char *zSql;
  int rc;

  assert( iDb>=0 && iDb<db->nDb );
  assert( db->aDb[iDb].pBt!=0 );
  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );

  /* Clear any prior statistics */
  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
    Index *pIdx = sqliteHashData(i);
    sqlite3DefaultRowEst(pIdx);
    sqlite3DeleteIndexSamples(pIdx);
  }

  /* Check to make sure the sqlite_stat1 table exists */
  sInfo.db = db;
  sInfo.zDatabase = db->aDb[iDb].zName;
  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
    return SQLITE_ERROR;
  }

  /* Load new statistics out of the sqlite_stat1 table */
  zSql = sqlite3MPrintf(db, 
      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  if( zSql==0 ){
    rc = SQLITE_NOMEM;
  }else{
    (void)sqlite3SafetyOff(db);
    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
    (void)sqlite3SafetyOn(db);
    sqlite3DbFree(db, zSql);
  }


  /* Load the statistics from the sqlite_stat2 table. */
#ifdef SQLITE_ENABLE_STAT2
  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
    rc = SQLITE_ERROR;
  }
  if( rc==SQLITE_OK ){
    sqlite3_stmt *pStmt = 0;

    zSql = sqlite3MPrintf(db, 
        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
    if( !zSql ){
      rc = SQLITE_NOMEM;
    }else{
      (void)sqlite3SafetyOff(db);
      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
      (void)sqlite3SafetyOn(db);
      sqlite3DbFree(db, zSql);
    }

    if( rc==SQLITE_OK ){
      (void)sqlite3SafetyOff(db);
      while( sqlite3_step(pStmt)==SQLITE_ROW ){
        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
        if( pIdx ){
          int iSample = sqlite3_column_int(pStmt, 1);
          sqlite3 *dbMem = pIdx->pTable->dbMem;
          assert( dbMem==db || dbMem==0 );
          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
            int eType = sqlite3_column_type(pStmt, 2);

            if( pIdx->aSample==0 ){
              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
              if( pIdx->aSample==0 ){
                db->mallocFailed = 1;
                break;
              }
            }

            assert( pIdx->aSample );
            {
              IndexSample *pSample = &pIdx->aSample[iSample];
              pSample->eType = (u8)eType;
              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
                pSample->u.r = sqlite3_column_double(pStmt, 2);
              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
                const char *z = (const char *)(
                    (eType==SQLITE_BLOB) ?
                    sqlite3_column_blob(pStmt, 2):
                    sqlite3_column_text(pStmt, 2)
                );
                int n = sqlite3_column_bytes(pStmt, 2);
                if( n>24 ){
                  n = 24;
                }
                pSample->nByte = (u8)n;
                pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
                if( pSample->u.z ){
                  memcpy(pSample->u.z, z, n);
                }else{
                  db->mallocFailed = 1;
                  break;
                }
              }
            }
          }
        }
      }
      rc = sqlite3_finalize(pStmt);
      (void)sqlite3SafetyOn(db);
    }
  }
#endif

  if( rc==SQLITE_NOMEM ){
    db->mallocFailed = 1;
  }
  return rc;
}


#endif /* SQLITE_OMIT_ANALYZE */

Added src/attach.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/*
** 2003 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
**
** $Id: attach.c,v 1.93 2009/05/31 21:21:41 drh Exp $
*/
#include "sqliteInt.h"

#ifndef SQLITE_OMIT_ATTACH
/*
** Resolve an expression that was part of an ATTACH or DETACH statement. This
** is slightly different from resolving a normal SQL expression, because simple
** identifiers are treated as strings, not possible column names or aliases.
**
** i.e. if the parser sees:
**
**     ATTACH DATABASE abc AS def
**
** it treats the two expressions as literal strings 'abc' and 'def' instead of
** looking for columns of the same name.
**
** This only applies to the root node of pExpr, so the statement:
**
**     ATTACH DATABASE abc||def AS 'db2'
**
** will fail because neither abc or def can be resolved.
*/
static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
{
  int rc = SQLITE_OK;
  if( pExpr ){
    if( pExpr->op!=TK_ID ){
      rc = sqlite3ResolveExprNames(pName, pExpr);
      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
        return SQLITE_ERROR;
      }
    }else{
      pExpr->op = TK_STRING;
    }
  }
  return rc;
}

/*
** An SQL user-function registered to do the work of an ATTACH statement. The
** three arguments to the function come directly from an attach statement:
**
**     ATTACH DATABASE x AS y KEY z
**
**     SELECT sqlite_attach(x, y, z)
**
** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
** third argument.
*/
static void attachFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  int i;
  int rc = 0;
  sqlite3 *db = sqlite3_context_db_handle(context);
  const char *zName;
  const char *zFile;
  Db *aNew;
  char *zErrDyn = 0;

  UNUSED_PARAMETER(NotUsed);

  zFile = (const char *)sqlite3_value_text(argv[0]);
  zName = (const char *)sqlite3_value_text(argv[1]);
  if( zFile==0 ) zFile = "";
  if( zName==0 ) zName = "";

  /* Check for the following errors:
  **
  **     * Too many attached databases,
  **     * Transaction currently open
  **     * Specified database name already being used.
  */
  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
      db->aLimit[SQLITE_LIMIT_ATTACHED]
    );
    goto attach_error;
  }
  if( !db->autoCommit ){
    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
    goto attach_error;
  }
  for(i=0; i<db->nDb; i++){
    char *z = db->aDb[i].zName;
    assert( z && zName );
    if( sqlite3StrICmp(z, zName)==0 ){
      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
      goto attach_error;
    }
  }

  /* Allocate the new entry in the db->aDb[] array and initialise the schema
  ** hash tables.
  */
  if( db->aDb==db->aDbStatic ){
    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
    if( aNew==0 ) return;
    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  }else{
    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
    if( aNew==0 ) return;
  }
  db->aDb = aNew;
  aNew = &db->aDb[db->nDb];
  memset(aNew, 0, sizeof(*aNew));

  /* Open the database file. If the btree is successfully opened, use
  ** it to obtain the database schema. At this point the schema may
  ** or may not be initialised.
  */
  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
                           db->openFlags | SQLITE_OPEN_MAIN_DB,
                           &aNew->pBt);
  db->nDb++;
  if( rc==SQLITE_CONSTRAINT ){
    rc = SQLITE_ERROR;
    zErrDyn = sqlite3MPrintf(db, "database is already attached");
  }else if( rc==SQLITE_OK ){
    Pager *pPager;
    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
    if( !aNew->pSchema ){
      rc = SQLITE_NOMEM;
    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
      zErrDyn = sqlite3MPrintf(db, 
        "attached databases must use the same text encoding as main database");
      rc = SQLITE_ERROR;
    }
    pPager = sqlite3BtreePager(aNew->pBt);
    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
    sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
  }
  aNew->zName = sqlite3DbStrDup(db, zName);
  aNew->safety_level = 3;

#if SQLITE_HAS_CODEC
  if( rc==SQLITE_OK ){
    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
    int nKey;
    char *zKey;
    int t = sqlite3_value_type(argv[2]);
    switch( t ){
      case SQLITE_INTEGER:
      case SQLITE_FLOAT:
        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
        rc = SQLITE_ERROR;
        break;
        
      case SQLITE_TEXT:
      case SQLITE_BLOB:
        nKey = sqlite3_value_bytes(argv[2]);
        zKey = (char *)sqlite3_value_blob(argv[2]);
        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
        break;

      case SQLITE_NULL:
        /* No key specified.  Use the key from the main database */
        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
        break;
    }
  }
#endif

  /* If the file was opened successfully, read the schema for the new database.
  ** If this fails, or if opening the file failed, then close the file and 
  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  ** we found it.
  */
  if( rc==SQLITE_OK ){
    (void)sqlite3SafetyOn(db);
    sqlite3BtreeEnterAll(db);
    rc = sqlite3Init(db, &zErrDyn);
    sqlite3BtreeLeaveAll(db);
    (void)sqlite3SafetyOff(db);
  }
  if( rc ){
    int iDb = db->nDb - 1;
    assert( iDb>=2 );
    if( db->aDb[iDb].pBt ){
      sqlite3BtreeClose(db->aDb[iDb].pBt);
      db->aDb[iDb].pBt = 0;
      db->aDb[iDb].pSchema = 0;
    }
    sqlite3ResetInternalSchema(db, 0);
    db->nDb = iDb;
    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
      db->mallocFailed = 1;
      sqlite3DbFree(db, zErrDyn);
      zErrDyn = sqlite3MPrintf(db, "out of memory");
    }else if( zErrDyn==0 ){
      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
    }
    goto attach_error;
  }
  
  return;

attach_error:
  /* Return an error if we get here */
  if( zErrDyn ){
    sqlite3_result_error(context, zErrDyn, -1);
    sqlite3DbFree(db, zErrDyn);
  }
  if( rc ) sqlite3_result_error_code(context, rc);
}

/*
** An SQL user-function registered to do the work of an DETACH statement. The
** three arguments to the function come directly from a detach statement:
**
**     DETACH DATABASE x
**
**     SELECT sqlite_detach(x)
*/
static void detachFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  const char *zName = (const char *)sqlite3_value_text(argv[0]);
  sqlite3 *db = sqlite3_context_db_handle(context);
  int i;
  Db *pDb = 0;
  char zErr[128];

  UNUSED_PARAMETER(NotUsed);

  if( zName==0 ) zName = "";
  for(i=0; i<db->nDb; i++){
    pDb = &db->aDb[i];
    if( pDb->pBt==0 ) continue;
    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  }

  if( i>=db->nDb ){
    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
    goto detach_error;
  }
  if( i<2 ){
    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
    goto detach_error;
  }
  if( !db->autoCommit ){
    sqlite3_snprintf(sizeof(zErr), zErr,
                     "cannot DETACH database within transaction");
    goto detach_error;
  }
  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
    goto detach_error;
  }

  sqlite3BtreeClose(pDb->pBt);
  pDb->pBt = 0;
  pDb->pSchema = 0;
  sqlite3ResetInternalSchema(db, 0);
  return;

detach_error:
  sqlite3_result_error(context, zErr, -1);
}

/*
** This procedure generates VDBE code for a single invocation of either the
** sqlite_detach() or sqlite_attach() SQL user functions.
*/
static void codeAttach(
  Parse *pParse,       /* The parser context */
  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
  FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
  Expr *pAuthArg,      /* Expression to pass to authorization callback */
  Expr *pFilename,     /* Name of database file */
  Expr *pDbname,       /* Name of the database to use internally */
  Expr *pKey           /* Database key for encryption extension */
){
  int rc;
  NameContext sName;
  Vdbe *v;
  sqlite3* db = pParse->db;
  int regArgs;

  memset(&sName, 0, sizeof(NameContext));
  sName.pParse = pParse;

  if( 
      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  ){
    pParse->nErr++;
    goto attach_end;
  }

#ifndef SQLITE_OMIT_AUTHORIZATION
  if( pAuthArg ){
    char *zAuthArg = pAuthArg->u.zToken;
    if( NEVER(zAuthArg==0) ){
      goto attach_end;
    }
    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
    if(rc!=SQLITE_OK ){
      goto attach_end;
    }
  }
#endif /* SQLITE_OMIT_AUTHORIZATION */


  v = sqlite3GetVdbe(pParse);
  regArgs = sqlite3GetTempRange(pParse, 4);
  sqlite3ExprCode(pParse, pFilename, regArgs);
  sqlite3ExprCode(pParse, pDbname, regArgs+1);
  sqlite3ExprCode(pParse, pKey, regArgs+2);

  assert( v || db->mallocFailed );
  if( v ){
    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);

    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
    ** statement only). For DETACH, set it to false (expire all existing
    ** statements).
    */
    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  }
  
attach_end:
  sqlite3ExprDelete(db, pFilename);
  sqlite3ExprDelete(db, pDbname);
  sqlite3ExprDelete(db, pKey);
}

/*
** Called by the parser to compile a DETACH statement.
**
**     DETACH pDbname
*/
void sqlite3Detach(Parse *pParse, Expr *pDbname){
  static FuncDef detach_func = {
    1,                /* nArg */
    SQLITE_UTF8,      /* iPrefEnc */
    0,                /* flags */
    0,                /* pUserData */
    0,                /* pNext */
    detachFunc,       /* xFunc */
    0,                /* xStep */
    0,                /* xFinalize */
    "sqlite_detach",  /* zName */
    0                 /* pHash */
  };
  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
}

/*
** Called by the parser to compile an ATTACH statement.
**
**     ATTACH p AS pDbname KEY pKey
*/
void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  static FuncDef attach_func = {
    3,                /* nArg */
    SQLITE_UTF8,      /* iPrefEnc */
    0,                /* flags */
    0,                /* pUserData */
    0,                /* pNext */
    attachFunc,       /* xFunc */
    0,                /* xStep */
    0,                /* xFinalize */
    "sqlite_attach",  /* zName */
    0                 /* pHash */
  };
  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
}
#endif /* SQLITE_OMIT_ATTACH */

/*
** Initialize a DbFixer structure.  This routine must be called prior
** to passing the structure to one of the sqliteFixAAAA() routines below.
**
** The return value indicates whether or not fixation is required.  TRUE
** means we do need to fix the database references, FALSE means we do not.
*/
int sqlite3FixInit(
  DbFixer *pFix,      /* The fixer to be initialized */
  Parse *pParse,      /* Error messages will be written here */
  int iDb,            /* This is the database that must be used */
  const char *zType,  /* "view", "trigger", or "index" */
  const Token *pName  /* Name of the view, trigger, or index */
){
  sqlite3 *db;

  if( NEVER(iDb<0) || iDb==1 ) return 0;
  db = pParse->db;
  assert( db->nDb>iDb );
  pFix->pParse = pParse;
  pFix->zDb = db->aDb[iDb].zName;
  pFix->zType = zType;
  pFix->pName = pName;
  return 1;
}

/*
** The following set of routines walk through the parse tree and assign
** a specific database to all table references where the database name
** was left unspecified in the original SQL statement.  The pFix structure
** must have been initialized by a prior call to sqlite3FixInit().
**
** These routines are used to make sure that an index, trigger, or
** view in one database does not refer to objects in a different database.
** (Exception: indices, triggers, and views in the TEMP database are
** allowed to refer to anything.)  If a reference is explicitly made
** to an object in a different database, an error message is added to
** pParse->zErrMsg and these routines return non-zero.  If everything
** checks out, these routines return 0.
*/
int sqlite3FixSrcList(
  DbFixer *pFix,       /* Context of the fixation */
  SrcList *pList       /* The Source list to check and modify */
){
  int i;
  const char *zDb;
  struct SrcList_item *pItem;

  if( NEVER(pList==0) ) return 0;
  zDb = pFix->zDb;
  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
    if( pItem->zDatabase==0 ){
      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
      sqlite3ErrorMsg(pFix->pParse,
         "%s %T cannot reference objects in database %s",
         pFix->zType, pFix->pName, pItem->zDatabase);
      return 1;
    }
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
#endif
  }
  return 0;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
int sqlite3FixSelect(
  DbFixer *pFix,       /* Context of the fixation */
  Select *pSelect      /* The SELECT statement to be fixed to one database */
){
  while( pSelect ){
    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
      return 1;
    }
    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
      return 1;
    }
    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
      return 1;
    }
    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
      return 1;
    }
    pSelect = pSelect->pPrior;
  }
  return 0;
}
int sqlite3FixExpr(
  DbFixer *pFix,     /* Context of the fixation */
  Expr *pExpr        /* The expression to be fixed to one database */
){
  while( pExpr ){
    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
    }else{
      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
    }
    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
      return 1;
    }
    pExpr = pExpr->pLeft;
  }
  return 0;
}
int sqlite3FixExprList(
  DbFixer *pFix,     /* Context of the fixation */
  ExprList *pList    /* The expression to be fixed to one database */
){
  int i;
  struct ExprList_item *pItem;
  if( pList==0 ) return 0;
  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
      return 1;
    }
  }
  return 0;
}
#endif

#ifndef SQLITE_OMIT_TRIGGER
int sqlite3FixTriggerStep(
  DbFixer *pFix,     /* Context of the fixation */
  TriggerStep *pStep /* The trigger step be fixed to one database */
){
  while( pStep ){
    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
      return 1;
    }
    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
      return 1;
    }
    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
      return 1;
    }
    pStep = pStep->pNext;
  }
  return 0;
}
#endif

Added src/auth.c.























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
** 2003 January 11
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the sqlite3_set_authorizer()
** API.  This facility is an optional feature of the library.  Embedded
** systems that do not need this facility may omit it by recompiling
** the library with -DSQLITE_OMIT_AUTHORIZATION=1
**
** $Id: auth.c,v 1.32 2009/07/02 18:40:35 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** All of the code in this file may be omitted by defining a single
** macro.
*/
#ifndef SQLITE_OMIT_AUTHORIZATION

/*
** Set or clear the access authorization function.
**
** The access authorization function is be called during the compilation
** phase to verify that the user has read and/or write access permission on
** various fields of the database.  The first argument to the auth function
** is a copy of the 3rd argument to this routine.  The second argument
** to the auth function is one of these constants:
**
**       SQLITE_CREATE_INDEX
**       SQLITE_CREATE_TABLE
**       SQLITE_CREATE_TEMP_INDEX
**       SQLITE_CREATE_TEMP_TABLE
**       SQLITE_CREATE_TEMP_TRIGGER
**       SQLITE_CREATE_TEMP_VIEW
**       SQLITE_CREATE_TRIGGER
**       SQLITE_CREATE_VIEW
**       SQLITE_DELETE
**       SQLITE_DROP_INDEX
**       SQLITE_DROP_TABLE
**       SQLITE_DROP_TEMP_INDEX
**       SQLITE_DROP_TEMP_TABLE
**       SQLITE_DROP_TEMP_TRIGGER
**       SQLITE_DROP_TEMP_VIEW
**       SQLITE_DROP_TRIGGER
**       SQLITE_DROP_VIEW
**       SQLITE_INSERT
**       SQLITE_PRAGMA
**       SQLITE_READ
**       SQLITE_SELECT
**       SQLITE_TRANSACTION
**       SQLITE_UPDATE
**
** The third and fourth arguments to the auth function are the name of
** the table and the column that are being accessed.  The auth function
** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
** means that the SQL statement will never-run - the sqlite3_exec() call
** will return with an error.  SQLITE_IGNORE means that the SQL statement
** should run but attempts to read the specified column will return NULL
** and attempts to write the column will be ignored.
**
** Setting the auth function to NULL disables this hook.  The default
** setting of the auth function is NULL.
*/
int sqlite3_set_authorizer(
  sqlite3 *db,
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  void *pArg
){
  sqlite3_mutex_enter(db->mutex);
  db->xAuth = xAuth;
  db->pAuthArg = pArg;
  sqlite3ExpirePreparedStatements(db);
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}

/*
** Write an error message into pParse->zErrMsg that explains that the
** user-supplied authorization function returned an illegal value.
*/
static void sqliteAuthBadReturnCode(Parse *pParse){
  sqlite3ErrorMsg(pParse, "authorizer malfunction");
  pParse->rc = SQLITE_ERROR;
}

/*
** Invoke the authorization callback for permission to read column zCol from
** table zTab in database zDb. This function assumes that an authorization
** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
**
** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
** is treated as SQLITE_DENY. In this case an error is left in pParse.
*/
int sqlite3AuthReadCol(
  Parse *pParse,                  /* The parser context */
  const char *zTab,               /* Table name */
  const char *zCol,               /* Column name */
  int iDb                         /* Index of containing database. */
){
  sqlite3 *db = pParse->db;       /* Database handle */
  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  int rc;                         /* Auth callback return code */

  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  if( rc==SQLITE_DENY ){
    if( db->nDb>2 || iDb!=0 ){
      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
    }else{
      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
    }
    pParse->rc = SQLITE_AUTH;
  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
    sqliteAuthBadReturnCode(pParse);
  }
  return rc;
}

/*
** The pExpr should be a TK_COLUMN expression.  The table referred to
** is in pTabList or else it is the NEW or OLD table of a trigger.  
** Check to see if it is OK to read this particular column.
**
** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
** then generate an error.
*/
void sqlite3AuthRead(
  Parse *pParse,        /* The parser context */
  Expr *pExpr,          /* The expression to check authorization on */
  Schema *pSchema,      /* The schema of the expression */
  SrcList *pTabList     /* All table that pExpr might refer to */
){
  sqlite3 *db = pParse->db;
  Table *pTab = 0;      /* The table being read */
  const char *zCol;     /* Name of the column of the table */
  int iSrc;             /* Index in pTabList->a[] of table being read */
  int iDb;              /* The index of the database the expression refers to */
  int iCol;             /* Index of column in table */

  if( db->xAuth==0 ) return;
  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  if( iDb<0 ){
    /* An attempt to read a column out of a subquery or other
    ** temporary table. */
    return;
  }

  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  if( pExpr->op==TK_TRIGGER ){
    pTab = pParse->pTriggerTab;
  }else{
    assert( pTabList );
    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
        pTab = pTabList->a[iSrc].pTab;
        break;
      }
    }
  }
  iCol = pExpr->iColumn;
  if( NEVER(pTab==0) ) return;

  if( iCol>=0 ){
    assert( iCol<pTab->nCol );
    zCol = pTab->aCol[iCol].zName;
  }else if( pTab->iPKey>=0 ){
    assert( pTab->iPKey<pTab->nCol );
    zCol = pTab->aCol[pTab->iPKey].zName;
  }else{
    zCol = "ROWID";
  }
  assert( iDb>=0 && iDb<db->nDb );
  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
    pExpr->op = TK_NULL;
  }
}

/*
** Do an authorization check using the code and arguments given.  Return
** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
** is returned, then the error count and error message in pParse are
** modified appropriately.
*/
int sqlite3AuthCheck(
  Parse *pParse,
  int code,
  const char *zArg1,
  const char *zArg2,
  const char *zArg3
){
  sqlite3 *db = pParse->db;
  int rc;

  /* Don't do any authorization checks if the database is initialising
  ** or if the parser is being invoked from within sqlite3_declare_vtab.
  */
  if( db->init.busy || IN_DECLARE_VTAB ){
    return SQLITE_OK;
  }

  if( db->xAuth==0 ){
    return SQLITE_OK;
  }
  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  if( rc==SQLITE_DENY ){
    sqlite3ErrorMsg(pParse, "not authorized");
    pParse->rc = SQLITE_AUTH;
  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
    rc = SQLITE_DENY;
    sqliteAuthBadReturnCode(pParse);
  }
  return rc;
}

/*
** Push an authorization context.  After this routine is called, the
** zArg3 argument to authorization callbacks will be zContext until
** popped.  Or if pParse==0, this routine is a no-op.
*/
void sqlite3AuthContextPush(
  Parse *pParse,
  AuthContext *pContext, 
  const char *zContext
){
  assert( pParse );
  pContext->pParse = pParse;
  pContext->zAuthContext = pParse->zAuthContext;
  pParse->zAuthContext = zContext;
}

/*
** Pop an authorization context that was previously pushed
** by sqlite3AuthContextPush
*/
void sqlite3AuthContextPop(AuthContext *pContext){
  if( pContext->pParse ){
    pContext->pParse->zAuthContext = pContext->zAuthContext;
    pContext->pParse = 0;
  }
}

#endif /* SQLITE_OMIT_AUTHORIZATION */

Added src/backup.c.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
** 2009 January 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_backup_XXX() 
** API functions and the related features.
**
** $Id: backup.c,v 1.19 2009/07/06 19:03:13 drh Exp $
*/
#include "sqliteInt.h"
#include "btreeInt.h"

/* Macro to find the minimum of two numeric values.
*/
#ifndef MIN
# define MIN(x,y) ((x)<(y)?(x):(y))
#endif

/*
** Structure allocated for each backup operation.
*/
struct sqlite3_backup {
  sqlite3* pDestDb;        /* Destination database handle */
  Btree *pDest;            /* Destination b-tree file */
  u32 iDestSchema;         /* Original schema cookie in destination */
  int bDestLocked;         /* True once a write-transaction is open on pDest */

  Pgno iNext;              /* Page number of the next source page to copy */
  sqlite3* pSrcDb;         /* Source database handle */
  Btree *pSrc;             /* Source b-tree file */

  int rc;                  /* Backup process error code */

  /* These two variables are set by every call to backup_step(). They are
  ** read by calls to backup_remaining() and backup_pagecount().
  */
  Pgno nRemaining;         /* Number of pages left to copy */
  Pgno nPagecount;         /* Total number of pages to copy */

  int isAttached;          /* True once backup has been registered with pager */
  sqlite3_backup *pNext;   /* Next backup associated with source pager */
};

/*
** THREAD SAFETY NOTES:
**
**   Once it has been created using backup_init(), a single sqlite3_backup
**   structure may be accessed via two groups of thread-safe entry points:
**
**     * Via the sqlite3_backup_XXX() API function backup_step() and 
**       backup_finish(). Both these functions obtain the source database
**       handle mutex and the mutex associated with the source BtShared 
**       structure, in that order.
**
**     * Via the BackupUpdate() and BackupRestart() functions, which are
**       invoked by the pager layer to report various state changes in
**       the page cache associated with the source database. The mutex
**       associated with the source database BtShared structure will always 
**       be held when either of these functions are invoked.
**
**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
**   backup_pagecount() are not thread-safe functions. If they are called
**   while some other thread is calling backup_step() or backup_finish(),
**   the values returned may be invalid. There is no way for a call to
**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
**   or backup_pagecount().
**
**   Depending on the SQLite configuration, the database handles and/or
**   the Btree objects may have their own mutexes that require locking.
**   Non-sharable Btrees (in-memory databases for example), do not have
**   associated mutexes.
*/

/*
** Return a pointer corresponding to database zDb (i.e. "main", "temp")
** in connection handle pDb. If such a database cannot be found, return
** a NULL pointer and write an error message to pErrorDb.
**
** If the "temp" database is requested, it may need to be opened by this 
** function. If an error occurs while doing so, return 0 and write an 
** error message to pErrorDb.
*/
static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  int i = sqlite3FindDbName(pDb, zDb);

  if( i==1 ){
    Parse *pParse;
    int rc = 0;
    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
    if( pParse==0 ){
      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
      rc = SQLITE_NOMEM;
    }else{
      pParse->db = pDb;
      if( sqlite3OpenTempDatabase(pParse) ){
        sqlite3ErrorClear(pParse);
        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
        rc = SQLITE_ERROR;
      }
      sqlite3StackFree(pErrorDb, pParse);
    }
    if( rc ){
      return 0;
    }
  }

  if( i<0 ){
    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
    return 0;
  }

  return pDb->aDb[i].pBt;
}

/*
** Create an sqlite3_backup process to copy the contents of zSrcDb from
** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
** a pointer to the new sqlite3_backup object.
**
** If an error occurs, NULL is returned and an error code and error message
** stored in database handle pDestDb.
*/
sqlite3_backup *sqlite3_backup_init(
  sqlite3* pDestDb,                     /* Database to write to */
  const char *zDestDb,                  /* Name of database within pDestDb */
  sqlite3* pSrcDb,                      /* Database connection to read from */
  const char *zSrcDb                    /* Name of database within pSrcDb */
){
  sqlite3_backup *p;                    /* Value to return */

  /* Lock the source database handle. The destination database
  ** handle is not locked in this routine, but it is locked in
  ** sqlite3_backup_step(). The user is required to ensure that no
  ** other thread accesses the destination handle for the duration
  ** of the backup operation.  Any attempt to use the destination
  ** database connection while a backup is in progress may cause
  ** a malfunction or a deadlock.
  */
  sqlite3_mutex_enter(pSrcDb->mutex);
  sqlite3_mutex_enter(pDestDb->mutex);

  if( pSrcDb==pDestDb ){
    sqlite3Error(
        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
    );
    p = 0;
  }else {
    /* Allocate space for a new sqlite3_backup object */
    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
    if( !p ){
      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
    }
  }

  /* If the allocation succeeded, populate the new object. */
  if( p ){
    memset(p, 0, sizeof(sqlite3_backup));
    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
    p->pDestDb = pDestDb;
    p->pSrcDb = pSrcDb;
    p->iNext = 1;
    p->isAttached = 0;

    if( 0==p->pSrc || 0==p->pDest ){
      /* One (or both) of the named databases did not exist. An error has
      ** already been written into the pDestDb handle. All that is left
      ** to do here is free the sqlite3_backup structure.
      */
      sqlite3_free(p);
      p = 0;
    }
  }
  if( p ){
    p->pSrc->nBackup++;
  }

  sqlite3_mutex_leave(pDestDb->mutex);
  sqlite3_mutex_leave(pSrcDb->mutex);
  return p;
}

/*
** Argument rc is an SQLite error code. Return true if this error is 
** considered fatal if encountered during a backup operation. All errors
** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
*/
static int isFatalError(int rc){
  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
}

/*
** Parameter zSrcData points to a buffer containing the data for 
** page iSrcPg from the source database. Copy this data into the 
** destination database.
*/
static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;

  int rc = SQLITE_OK;
  i64 iOff;

  assert( p->bDestLocked );
  assert( !isFatalError(p->rc) );
  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  assert( zSrcData );

  /* Catch the case where the destination is an in-memory database and the
  ** page sizes of the source and destination differ. 
  */
  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
    rc = SQLITE_READONLY;
  }

  /* This loop runs once for each destination page spanned by the source 
  ** page. For each iteration, variable iOff is set to the byte offset
  ** of the destination page.
  */
  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
    DbPage *pDestPg = 0;
    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
    ){
      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
      u8 *zDestData = sqlite3PagerGetData(pDestPg);
      u8 *zOut = &zDestData[iOff%nDestPgsz];

      /* Copy the data from the source page into the destination page.
      ** Then clear the Btree layer MemPage.isInit flag. Both this module
      ** and the pager code use this trick (clearing the first byte
      ** of the page 'extra' space to invalidate the Btree layers
      ** cached parse of the page). MemPage.isInit is marked 
      ** "MUST BE FIRST" for this purpose.
      */
      memcpy(zOut, zIn, nCopy);
      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
    }
    sqlite3PagerUnref(pDestPg);
  }

  return rc;
}

/*
** If pFile is currently larger than iSize bytes, then truncate it to
** exactly iSize bytes. If pFile is not larger than iSize bytes, then
** this function is a no-op.
**
** Return SQLITE_OK if everything is successful, or an SQLite error 
** code if an error occurs.
*/
static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  i64 iCurrent;
  int rc = sqlite3OsFileSize(pFile, &iCurrent);
  if( rc==SQLITE_OK && iCurrent>iSize ){
    rc = sqlite3OsTruncate(pFile, iSize);
  }
  return rc;
}

/*
** Register this backup object with the associated source pager for
** callbacks when pages are changed or the cache invalidated.
*/
static void attachBackupObject(sqlite3_backup *p){
  sqlite3_backup **pp;
  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  p->pNext = *pp;
  *pp = p;
  p->isAttached = 1;
}

/*
** Copy nPage pages from the source b-tree to the destination.
*/
int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  int rc;

  sqlite3_mutex_enter(p->pSrcDb->mutex);
  sqlite3BtreeEnter(p->pSrc);
  if( p->pDestDb ){
    sqlite3_mutex_enter(p->pDestDb->mutex);
  }

  rc = p->rc;
  if( !isFatalError(rc) ){
    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
    int ii;                            /* Iterator variable */
    int nSrcPage = -1;                 /* Size of source db in pages */
    int bCloseTrans = 0;               /* True if src db requires unlocking */

    /* If the source pager is currently in a write-transaction, return
    ** SQLITE_BUSY immediately.
    */
    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
      rc = SQLITE_BUSY;
    }else{
      rc = SQLITE_OK;
    }

    /* Lock the destination database, if it is not locked already. */
    if( SQLITE_OK==rc && p->bDestLocked==0
     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
    ){
      p->bDestLocked = 1;
      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
    }

    /* If there is no open read-transaction on the source database, open
    ** one now. If a transaction is opened here, then it will be closed
    ** before this function exits.
    */
    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
      bCloseTrans = 1;
    }
  
    /* Now that there is a read-lock on the source database, query the
    ** source pager for the number of pages in the database.
    */
    if( rc==SQLITE_OK ){
      rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
    }
    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
      const Pgno iSrcPg = p->iNext;                 /* Source page number */
      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
        DbPage *pSrcPg;                             /* Source page object */
        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
        if( rc==SQLITE_OK ){
          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
          sqlite3PagerUnref(pSrcPg);
        }
      }
      p->iNext++;
    }
    if( rc==SQLITE_OK ){
      p->nPagecount = nSrcPage;
      p->nRemaining = nSrcPage+1-p->iNext;
      if( p->iNext>(Pgno)nSrcPage ){
        rc = SQLITE_DONE;
      }else if( !p->isAttached ){
        attachBackupObject(p);
      }
    }
  
    /* Update the schema version field in the destination database. This
    ** is to make sure that the schema-version really does change in
    ** the case where the source and destination databases have the
    ** same schema version.
    */
    if( rc==SQLITE_DONE 
     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
    ){
      const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
      const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
      int nDestTruncate;
  
      if( p->pDestDb ){
        sqlite3ResetInternalSchema(p->pDestDb, 0);
      }

      /* Set nDestTruncate to the final number of pages in the destination
      ** database. The complication here is that the destination page
      ** size may be different to the source page size. 
      **
      ** If the source page size is smaller than the destination page size, 
      ** round up. In this case the call to sqlite3OsTruncate() below will
      ** fix the size of the file. However it is important to call
      ** sqlite3PagerTruncateImage() here so that any pages in the 
      ** destination file that lie beyond the nDestTruncate page mark are
      ** journalled by PagerCommitPhaseOne() before they are destroyed
      ** by the file truncation.
      */
      if( nSrcPagesize<nDestPagesize ){
        int ratio = nDestPagesize/nSrcPagesize;
        nDestTruncate = (nSrcPage+ratio-1)/ratio;
        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
          nDestTruncate--;
        }
      }else{
        nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
      }
      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);

      if( nSrcPagesize<nDestPagesize ){
        /* If the source page-size is smaller than the destination page-size,
        ** two extra things may need to happen:
        **
        **   * The destination may need to be truncated, and
        **
        **   * Data stored on the pages immediately following the 
        **     pending-byte page in the source database may need to be
        **     copied into the destination database.
        */
        const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);

        assert( pFile );
        assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
        ));
        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
        ){
          i64 iOff;
          i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
          for(
            iOff=PENDING_BYTE+nSrcPagesize; 
            rc==SQLITE_OK && iOff<iEnd; 
            iOff+=nSrcPagesize
          ){
            PgHdr *pSrcPg = 0;
            const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
            if( rc==SQLITE_OK ){
              u8 *zData = sqlite3PagerGetData(pSrcPg);
              rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
            }
            sqlite3PagerUnref(pSrcPg);
          }
        }
      }else{
        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
      }
  
      /* Finish committing the transaction to the destination database. */
      if( SQLITE_OK==rc
       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
      ){
        rc = SQLITE_DONE;
      }
    }
  
    /* If bCloseTrans is true, then this function opened a read transaction
    ** on the source database. Close the read transaction here. There is
    ** no need to check the return values of the btree methods here, as
    ** "committing" a read-only transaction cannot fail.
    */
    if( bCloseTrans ){
      TESTONLY( int rc2 );
      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
      assert( rc2==SQLITE_OK );
    }
  
    p->rc = rc;
  }
  if( p->pDestDb ){
    sqlite3_mutex_leave(p->pDestDb->mutex);
  }
  sqlite3BtreeLeave(p->pSrc);
  sqlite3_mutex_leave(p->pSrcDb->mutex);
  return rc;
}

/*
** Release all resources associated with an sqlite3_backup* handle.
*/
int sqlite3_backup_finish(sqlite3_backup *p){
  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
  sqlite3_mutex *mutex;                /* Mutex to protect source database */
  int rc;                              /* Value to return */

  /* Enter the mutexes */
  if( p==0 ) return SQLITE_OK;
  sqlite3_mutex_enter(p->pSrcDb->mutex);
  sqlite3BtreeEnter(p->pSrc);
  mutex = p->pSrcDb->mutex;
  if( p->pDestDb ){
    sqlite3_mutex_enter(p->pDestDb->mutex);
  }

  /* Detach this backup from the source pager. */
  if( p->pDestDb ){
    p->pSrc->nBackup--;
  }
  if( p->isAttached ){
    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
    while( *pp!=p ){
      pp = &(*pp)->pNext;
    }
    *pp = p->pNext;
  }

  /* If a transaction is still open on the Btree, roll it back. */
  sqlite3BtreeRollback(p->pDest);

  /* Set the error code of the destination database handle. */
  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  sqlite3Error(p->pDestDb, rc, 0);

  /* Exit the mutexes and free the backup context structure. */
  if( p->pDestDb ){
    sqlite3_mutex_leave(p->pDestDb->mutex);
  }
  sqlite3BtreeLeave(p->pSrc);
  if( p->pDestDb ){
    sqlite3_free(p);
  }
  sqlite3_mutex_leave(mutex);
  return rc;
}

/*
** Return the number of pages still to be backed up as of the most recent
** call to sqlite3_backup_step().
*/
int sqlite3_backup_remaining(sqlite3_backup *p){
  return p->nRemaining;
}

/*
** Return the total number of pages in the source database as of the most 
** recent call to sqlite3_backup_step().
*/
int sqlite3_backup_pagecount(sqlite3_backup *p){
  return p->nPagecount;
}

/*
** This function is called after the contents of page iPage of the
** source database have been modified. If page iPage has already been 
** copied into the destination database, then the data written to the
** destination is now invalidated. The destination copy of iPage needs
** to be updated with the new data before the backup operation is
** complete.
**
** It is assumed that the mutex associated with the BtShared object
** corresponding to the source database is held when this function is
** called.
*/
void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  sqlite3_backup *p;                   /* Iterator variable */
  for(p=pBackup; p; p=p->pNext){
    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
    if( !isFatalError(p->rc) && iPage<p->iNext ){
      /* The backup process p has already copied page iPage. But now it
      ** has been modified by a transaction on the source pager. Copy
      ** the new data into the backup.
      */
      int rc = backupOnePage(p, iPage, aData);
      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
      if( rc!=SQLITE_OK ){
        p->rc = rc;
      }
    }
  }
}

/*
** Restart the backup process. This is called when the pager layer
** detects that the database has been modified by an external database
** connection. In this case there is no way of knowing which of the
** pages that have been copied into the destination database are still 
** valid and which are not, so the entire process needs to be restarted.
**
** It is assumed that the mutex associated with the BtShared object
** corresponding to the source database is held when this function is
** called.
*/
void sqlite3BackupRestart(sqlite3_backup *pBackup){
  sqlite3_backup *p;                   /* Iterator variable */
  for(p=pBackup; p; p=p->pNext){
    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
    p->iNext = 1;
  }
}

#ifndef SQLITE_OMIT_VACUUM
/*
** Copy the complete content of pBtFrom into pBtTo.  A transaction
** must be active for both files.
**
** The size of file pTo may be reduced by this operation. If anything 
** goes wrong, the transaction on pTo is rolled back. If successful, the 
** transaction is committed before returning.
*/
int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  int rc;
  sqlite3_backup b;
  sqlite3BtreeEnter(pTo);
  sqlite3BtreeEnter(pFrom);

  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  ** to 0. This is used by the implementations of sqlite3_backup_step()
  ** and sqlite3_backup_finish() to detect that they are being called
  ** from this function, not directly by the user.
  */
  memset(&b, 0, sizeof(b));
  b.pSrcDb = pFrom->db;
  b.pSrc = pFrom;
  b.pDest = pTo;
  b.iNext = 1;

  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  ** file. By passing this as the number of pages to copy to
  ** sqlite3_backup_step(), we can guarantee that the copy finishes 
  ** within a single call (unless an error occurs). The assert() statement
  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
  ** or an error code.
  */
  sqlite3_backup_step(&b, 0x7FFFFFFF);
  assert( b.rc!=SQLITE_OK );
  rc = sqlite3_backup_finish(&b);
  if( rc==SQLITE_OK ){
    pTo->pBt->pageSizeFixed = 0;
  }

  sqlite3BtreeLeave(pFrom);
  sqlite3BtreeLeave(pTo);
  return rc;
}
#endif /* SQLITE_OMIT_VACUUM */

Added src/bitvec.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
** 2008 February 16
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements an object that represents a fixed-length
** bitmap.  Bits are numbered starting with 1.
**
** A bitmap is used to record which pages of a database file have been
** journalled during a transaction, or which pages have the "dont-write"
** property.  Usually only a few pages are meet either condition.
** So the bitmap is usually sparse and has low cardinality.
** But sometimes (for example when during a DROP of a large table) most
** or all of the pages in a database can get journalled.  In those cases, 
** the bitmap becomes dense with high cardinality.  The algorithm needs 
** to handle both cases well.
**
** The size of the bitmap is fixed when the object is created.
**
** All bits are clear when the bitmap is created.  Individual bits
** may be set or cleared one at a time.
**
** Test operations are about 100 times more common that set operations.
** Clear operations are exceedingly rare.  There are usually between
** 5 and 500 set operations per Bitvec object, though the number of sets can
** sometimes grow into tens of thousands or larger.  The size of the
** Bitvec object is the number of pages in the database file at the
** start of a transaction, and is thus usually less than a few thousand,
** but can be as large as 2 billion for a really big database.
**
** @(#) $Id: bitvec.c,v 1.17 2009/07/25 17:33:26 drh Exp $
*/
#include "sqliteInt.h"

/* Size of the Bitvec structure in bytes. */
#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */

/* Round the union size down to the nearest pointer boundary, since that's how 
** it will be aligned within the Bitvec struct. */
#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))

/* Type of the array "element" for the bitmap representation. 
** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
** Setting this to the "natural word" size of your CPU may improve
** performance. */
#define BITVEC_TELEM     u8
/* Size, in bits, of the bitmap element. */
#define BITVEC_SZELEM    8
/* Number of elements in a bitmap array. */
#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
/* Number of bits in the bitmap array. */
#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)

/* Number of u32 values in hash table. */
#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
/* Maximum number of entries in hash table before 
** sub-dividing and re-hashing. */
#define BITVEC_MXHASH    (BITVEC_NINT/2)
/* Hashing function for the aHash representation.
** Empirical testing showed that the *37 multiplier 
** (an arbitrary prime)in the hash function provided 
** no fewer collisions than the no-op *1. */
#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)

#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))


/*
** A bitmap is an instance of the following structure.
**
** This bitmap records the existance of zero or more bits
** with values between 1 and iSize, inclusive.
**
** There are three possible representations of the bitmap.
** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
** bitmap.  The least significant bit is bit 1.
**
** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
** a hash table that will hold up to BITVEC_MXHASH distinct values.
**
** Otherwise, the value i is redirected into one of BITVEC_NPTR
** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
** handles up to iDivisor separate values of i.  apSub[0] holds
** values between 1 and iDivisor.  apSub[1] holds values between
** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
** to hold deal with values between 1 and iDivisor.
*/
struct Bitvec {
  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
  u32 nSet;       /* Number of bits that are set - only valid for aHash
                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
                  ** this would be 125. */
  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
                  /* Should >=0 for apSub element. */
                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  union {
    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
    u32 aHash[BITVEC_NINT];      /* Hash table representation */
    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
  } u;
};

/*
** Create a new bitmap object able to handle bits between 0 and iSize,
** inclusive.  Return a pointer to the new object.  Return NULL if 
** malloc fails.
*/
Bitvec *sqlite3BitvecCreate(u32 iSize){
  Bitvec *p;
  assert( sizeof(*p)==BITVEC_SZ );
  p = sqlite3MallocZero( sizeof(*p) );
  if( p ){
    p->iSize = iSize;
  }
  return p;
}

/*
** Check to see if the i-th bit is set.  Return true or false.
** If p is NULL (if the bitmap has not been created) or if
** i is out of range, then return false.
*/
int sqlite3BitvecTest(Bitvec *p, u32 i){
  if( p==0 ) return 0;
  if( i>p->iSize || i==0 ) return 0;
  i--;
  while( p->iDivisor ){
    u32 bin = i/p->iDivisor;
    i = i%p->iDivisor;
    p = p->u.apSub[bin];
    if (!p) {
      return 0;
    }
  }
  if( p->iSize<=BITVEC_NBIT ){
    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  } else{
    u32 h = BITVEC_HASH(i++);
    while( p->u.aHash[h] ){
      if( p->u.aHash[h]==i ) return 1;
      h = (h+1) % BITVEC_NINT;
    }
    return 0;
  }
}

/*
** Set the i-th bit.  Return 0 on success and an error code if
** anything goes wrong.
**
** This routine might cause sub-bitmaps to be allocated.  Failing
** to get the memory needed to hold the sub-bitmap is the only
** that can go wrong with an insert, assuming p and i are valid.
**
** The calling function must ensure that p is a valid Bitvec object
** and that the value for "i" is within range of the Bitvec object.
** Otherwise the behavior is undefined.
*/
int sqlite3BitvecSet(Bitvec *p, u32 i){
  u32 h;
  if( p==0 ) return SQLITE_OK;
  assert( i>0 );
  assert( i<=p->iSize );
  i--;
  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
    u32 bin = i/p->iDivisor;
    i = i%p->iDivisor;
    if( p->u.apSub[bin]==0 ){
      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
    }
    p = p->u.apSub[bin];
  }
  if( p->iSize<=BITVEC_NBIT ){
    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
    return SQLITE_OK;
  }
  h = BITVEC_HASH(i++);
  /* if there wasn't a hash collision, and this doesn't */
  /* completely fill the hash, then just add it without */
  /* worring about sub-dividing and re-hashing. */
  if( !p->u.aHash[h] ){
    if (p->nSet<(BITVEC_NINT-1)) {
      goto bitvec_set_end;
    } else {
      goto bitvec_set_rehash;
    }
  }
  /* there was a collision, check to see if it's already */
  /* in hash, if not, try to find a spot for it */
  do {
    if( p->u.aHash[h]==i ) return SQLITE_OK;
    h++;
    if( h>=BITVEC_NINT ) h = 0;
  } while( p->u.aHash[h] );
  /* we didn't find it in the hash.  h points to the first */
  /* available free spot. check to see if this is going to */
  /* make our hash too "full".  */
bitvec_set_rehash:
  if( p->nSet>=BITVEC_MXHASH ){
    unsigned int j;
    int rc;
    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
    if( aiValues==0 ){
      return SQLITE_NOMEM;
    }else{
      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
      memset(p->u.apSub, 0, sizeof(p->u.apSub));
      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
      rc = sqlite3BitvecSet(p, i);
      for(j=0; j<BITVEC_NINT; j++){
        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
      }
      sqlite3StackFree(0, aiValues);
      return rc;
    }
  }
bitvec_set_end:
  p->nSet++;
  p->u.aHash[h] = i;
  return SQLITE_OK;
}

/*
** Clear the i-th bit.
**
** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
** that BitvecClear can use to rebuilt its hash table.
*/
void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  if( p==0 ) return;
  assert( i>0 );
  i--;
  while( p->iDivisor ){
    u32 bin = i/p->iDivisor;
    i = i%p->iDivisor;
    p = p->u.apSub[bin];
    if (!p) {
      return;
    }
  }
  if( p->iSize<=BITVEC_NBIT ){
    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  }else{
    unsigned int j;
    u32 *aiValues = pBuf;
    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
    memset(p->u.aHash, 0, sizeof(p->u.aHash));
    p->nSet = 0;
    for(j=0; j<BITVEC_NINT; j++){
      if( aiValues[j] && aiValues[j]!=(i+1) ){
        u32 h = BITVEC_HASH(aiValues[j]-1);
        p->nSet++;
        while( p->u.aHash[h] ){
          h++;
          if( h>=BITVEC_NINT ) h = 0;
        }
        p->u.aHash[h] = aiValues[j];
      }
    }
  }
}

/*
** Destroy a bitmap object.  Reclaim all memory used.
*/
void sqlite3BitvecDestroy(Bitvec *p){
  if( p==0 ) return;
  if( p->iDivisor ){
    unsigned int i;
    for(i=0; i<BITVEC_NPTR; i++){
      sqlite3BitvecDestroy(p->u.apSub[i]);
    }
  }
  sqlite3_free(p);
}

/*
** Return the value of the iSize parameter specified when Bitvec *p
** was created.
*/
u32 sqlite3BitvecSize(Bitvec *p){
  return p->iSize;
}

#ifndef SQLITE_OMIT_BUILTIN_TEST
/*
** Let V[] be an array of unsigned characters sufficient to hold
** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
** Then the following macros can be used to set, clear, or test
** individual bits within V.
*/
#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0

/*
** This routine runs an extensive test of the Bitvec code.
**
** The input is an array of integers that acts as a program
** to test the Bitvec.  The integers are opcodes followed
** by 0, 1, or 3 operands, depending on the opcode.  Another
** opcode follows immediately after the last operand.
**
** There are 6 opcodes numbered from 0 through 5.  0 is the
** "halt" opcode and causes the test to end.
**
**    0          Halt and return the number of errors
**    1 N S X    Set N bits beginning with S and incrementing by X
**    2 N S X    Clear N bits beginning with S and incrementing by X
**    3 N        Set N randomly chosen bits
**    4 N        Clear N randomly chosen bits
**    5 N S X    Set N bits from S increment X in array only, not in bitvec
**
** The opcodes 1 through 4 perform set and clear operations are performed
** on both a Bitvec object and on a linear array of bits obtained from malloc.
** Opcode 5 works on the linear array only, not on the Bitvec.
** Opcode 5 is used to deliberately induce a fault in order to
** confirm that error detection works.
**
** At the conclusion of the test the linear array is compared
** against the Bitvec object.  If there are any differences,
** an error is returned.  If they are the same, zero is returned.
**
** If a memory allocation error occurs, return -1.
*/
int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  Bitvec *pBitvec = 0;
  unsigned char *pV = 0;
  int rc = -1;
  int i, nx, pc, op;
  void *pTmpSpace;

  /* Allocate the Bitvec to be tested and a linear array of
  ** bits to act as the reference */
  pBitvec = sqlite3BitvecCreate( sz );
  pV = sqlite3_malloc( (sz+7)/8 + 1 );
  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
  memset(pV, 0, (sz+7)/8 + 1);

  /* NULL pBitvec tests */
  sqlite3BitvecSet(0, 1);
  sqlite3BitvecClear(0, 1, pTmpSpace);

  /* Run the program */
  pc = 0;
  while( (op = aOp[pc])!=0 ){
    switch( op ){
      case 1:
      case 2:
      case 5: {
        nx = 4;
        i = aOp[pc+2] - 1;
        aOp[pc+2] += aOp[pc+3];
        break;
      }
      case 3:
      case 4: 
      default: {
        nx = 2;
        sqlite3_randomness(sizeof(i), &i);
        break;
      }
    }
    if( (--aOp[pc+1]) > 0 ) nx = 0;
    pc += nx;
    i = (i & 0x7fffffff)%sz;
    if( (op & 1)!=0 ){
      SETBIT(pV, (i+1));
      if( op!=5 ){
        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
      }
    }else{
      CLEARBIT(pV, (i+1));
      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
    }
  }

  /* Test to make sure the linear array exactly matches the
  ** Bitvec object.  Start with the assumption that they do
  ** match (rc==0).  Change rc to non-zero if a discrepancy
  ** is found.
  */
  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
          + sqlite3BitvecTest(pBitvec, 0)
          + (sqlite3BitvecSize(pBitvec) - sz);
  for(i=1; i<=sz; i++){
    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
      rc = i;
      break;
    }
  }

  /* Free allocated structure */
bitvec_end:
  sqlite3_free(pTmpSpace);
  sqlite3_free(pV);
  sqlite3BitvecDestroy(pBitvec);
  return rc;
}
#endif /* SQLITE_OMIT_BUILTIN_TEST */

Added src/btmutex.c.

















































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
** 2007 August 27
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** $Id: btmutex.c,v 1.17 2009/07/20 12:33:33 drh Exp $
**
** This file contains code used to implement mutexes on Btree objects.
** This code really belongs in btree.c.  But btree.c is getting too
** big and we want to break it down some.  This packaged seemed like
** a good breakout.
*/
#include "btreeInt.h"
#ifndef SQLITE_OMIT_SHARED_CACHE
#if SQLITE_THREADSAFE

/*
** Obtain the BtShared mutex associated with B-Tree handle p. Also,
** set BtShared.db to the database handle associated with p and the
** p->locked boolean to true.
*/
static void lockBtreeMutex(Btree *p){
  assert( p->locked==0 );
  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  assert( sqlite3_mutex_held(p->db->mutex) );

  sqlite3_mutex_enter(p->pBt->mutex);
  p->pBt->db = p->db;
  p->locked = 1;
}

/*
** Release the BtShared mutex associated with B-Tree handle p and
** clear the p->locked boolean.
*/
static void unlockBtreeMutex(Btree *p){
  assert( p->locked==1 );
  assert( sqlite3_mutex_held(p->pBt->mutex) );
  assert( sqlite3_mutex_held(p->db->mutex) );
  assert( p->db==p->pBt->db );

  sqlite3_mutex_leave(p->pBt->mutex);
  p->locked = 0;
}

/*
** Enter a mutex on the given BTree object.
**
** If the object is not sharable, then no mutex is ever required
** and this routine is a no-op.  The underlying mutex is non-recursive.
** But we keep a reference count in Btree.wantToLock so the behavior
** of this interface is recursive.
**
** To avoid deadlocks, multiple Btrees are locked in the same order
** by all database connections.  The p->pNext is a list of other
** Btrees belonging to the same database connection as the p Btree
** which need to be locked after p.  If we cannot get a lock on
** p, then first unlock all of the others on p->pNext, then wait
** for the lock to become available on p, then relock all of the
** subsequent Btrees that desire a lock.
*/
void sqlite3BtreeEnter(Btree *p){
  Btree *pLater;

  /* Some basic sanity checking on the Btree.  The list of Btrees
  ** connected by pNext and pPrev should be in sorted order by
  ** Btree.pBt value. All elements of the list should belong to
  ** the same connection. Only shared Btrees are on the list. */
  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  assert( p->pNext==0 || p->pNext->db==p->db );
  assert( p->pPrev==0 || p->pPrev->db==p->db );
  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );

  /* Check for locking consistency */
  assert( !p->locked || p->wantToLock>0 );
  assert( p->sharable || p->wantToLock==0 );

  /* We should already hold a lock on the database connection */
  assert( sqlite3_mutex_held(p->db->mutex) );

  /* Unless the database is sharable and unlocked, then BtShared.db
  ** should already be set correctly. */
  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );

  if( !p->sharable ) return;
  p->wantToLock++;
  if( p->locked ) return;

  /* In most cases, we should be able to acquire the lock we
  ** want without having to go throught the ascending lock
  ** procedure that follows.  Just be sure not to block.
  */
  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
    p->pBt->db = p->db;
    p->locked = 1;
    return;
  }

  /* To avoid deadlock, first release all locks with a larger
  ** BtShared address.  Then acquire our lock.  Then reacquire
  ** the other BtShared locks that we used to hold in ascending
  ** order.
  */
  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
    assert( pLater->sharable );
    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
    assert( !pLater->locked || pLater->wantToLock>0 );
    if( pLater->locked ){
      unlockBtreeMutex(pLater);
    }
  }
  lockBtreeMutex(p);
  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
    if( pLater->wantToLock ){
      lockBtreeMutex(pLater);
    }
  }
}

/*
** Exit the recursive mutex on a Btree.
*/
void sqlite3BtreeLeave(Btree *p){
  if( p->sharable ){
    assert( p->wantToLock>0 );
    p->wantToLock--;
    if( p->wantToLock==0 ){
      unlockBtreeMutex(p);
    }
  }
}

#ifndef NDEBUG
/*
** Return true if the BtShared mutex is held on the btree, or if the
** B-Tree is not marked as sharable.
**
** This routine is used only from within assert() statements.
*/
int sqlite3BtreeHoldsMutex(Btree *p){
  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );

  return (p->sharable==0 || p->locked);
}
#endif


#ifndef SQLITE_OMIT_INCRBLOB
/*
** Enter and leave a mutex on a Btree given a cursor owned by that
** Btree.  These entry points are used by incremental I/O and can be
** omitted if that module is not used.
*/
void sqlite3BtreeEnterCursor(BtCursor *pCur){
  sqlite3BtreeEnter(pCur->pBtree);
}
void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  sqlite3BtreeLeave(pCur->pBtree);
}
#endif /* SQLITE_OMIT_INCRBLOB */


/*
** Enter the mutex on every Btree associated with a database
** connection.  This is needed (for example) prior to parsing
** a statement since we will be comparing table and column names
** against all schemas and we do not want those schemas being
** reset out from under us.
**
** There is a corresponding leave-all procedures.
**
** Enter the mutexes in accending order by BtShared pointer address
** to avoid the possibility of deadlock when two threads with
** two or more btrees in common both try to lock all their btrees
** at the same instant.
*/
void sqlite3BtreeEnterAll(sqlite3 *db){
  int i;
  Btree *p, *pLater;
  assert( sqlite3_mutex_held(db->mutex) );
  for(i=0; i<db->nDb; i++){
    p = db->aDb[i].pBt;
    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
    if( p && p->sharable ){
      p->wantToLock++;
      if( !p->locked ){
        assert( p->wantToLock==1 );
        while( p->pPrev ) p = p->pPrev;
        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
        ** the chain.  Otherwise the !p->locked test above would have failed */
        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
          if( pLater->locked ){
            unlockBtreeMutex(pLater);
          }
        }
        while( p ){
          lockBtreeMutex(p);
          p = p->pNext;
        }
      }
    }
  }
}
void sqlite3BtreeLeaveAll(sqlite3 *db){
  int i;
  Btree *p;
  assert( sqlite3_mutex_held(db->mutex) );
  for(i=0; i<db->nDb; i++){
    p = db->aDb[i].pBt;
    if( p && p->sharable ){
      assert( p->wantToLock>0 );
      p->wantToLock--;
      if( p->wantToLock==0 ){
        unlockBtreeMutex(p);
      }
    }
  }
}

#ifndef NDEBUG
/*
** Return true if the current thread holds the database connection
** mutex and all required BtShared mutexes.
**
** This routine is used inside assert() statements only.
*/
int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  int i;
  if( !sqlite3_mutex_held(db->mutex) ){
    return 0;
  }
  for(i=0; i<db->nDb; i++){
    Btree *p;
    p = db->aDb[i].pBt;
    if( p && p->sharable &&
         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
      return 0;
    }
  }
  return 1;
}
#endif /* NDEBUG */

/*
** Add a new Btree pointer to a BtreeMutexArray. 
** if the pointer can possibly be shared with
** another database connection.
**
** The pointers are kept in sorted order by pBtree->pBt.  That
** way when we go to enter all the mutexes, we can enter them
** in order without every having to backup and retry and without
** worrying about deadlock.
**
** The number of shared btrees will always be small (usually 0 or 1)
** so an insertion sort is an adequate algorithm here.
*/
void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
  int i, j;
  BtShared *pBt;
  if( pBtree==0 || pBtree->sharable==0 ) return;
#ifndef NDEBUG
  {
    for(i=0; i<pArray->nMutex; i++){
      assert( pArray->aBtree[i]!=pBtree );
    }
  }
#endif
  assert( pArray->nMutex>=0 );
  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
  pBt = pBtree->pBt;
  for(i=0; i<pArray->nMutex; i++){
    assert( pArray->aBtree[i]!=pBtree );
    if( pArray->aBtree[i]->pBt>pBt ){
      for(j=pArray->nMutex; j>i; j--){
        pArray->aBtree[j] = pArray->aBtree[j-1];
      }
      pArray->aBtree[i] = pBtree;
      pArray->nMutex++;
      return;
    }
  }
  pArray->aBtree[pArray->nMutex++] = pBtree;
}

/*
** Enter the mutex of every btree in the array.  This routine is
** called at the beginning of sqlite3VdbeExec().  The mutexes are
** exited at the end of the same function.
*/
void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
  int i;
  for(i=0; i<pArray->nMutex; i++){
    Btree *p = pArray->aBtree[i];
    /* Some basic sanity checking */
    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
    assert( !p->locked || p->wantToLock>0 );

    /* We should already hold a lock on the database connection */
    assert( sqlite3_mutex_held(p->db->mutex) );

    /* The Btree is sharable because only sharable Btrees are entered
    ** into the array in the first place. */
    assert( p->sharable );

    p->wantToLock++;
    if( !p->locked ){
      lockBtreeMutex(p);
    }
  }
}

/*
** Leave the mutex of every btree in the group.
*/
void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
  int i;
  for(i=0; i<pArray->nMutex; i++){
    Btree *p = pArray->aBtree[i];
    /* Some basic sanity checking */
    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
    assert( p->locked );
    assert( p->wantToLock>0 );

    /* We should already hold a lock on the database connection */
    assert( sqlite3_mutex_held(p->db->mutex) );

    p->wantToLock--;
    if( p->wantToLock==0 ){
      unlockBtreeMutex(p);
    }
  }
}

#else
void sqlite3BtreeEnter(Btree *p){
  p->pBt->db = p->db;
}
void sqlite3BtreeEnterAll(sqlite3 *db){
  int i;
  for(i=0; i<db->nDb; i++){
    Btree *p = db->aDb[i].pBt;
    if( p ){
      p->pBt->db = p->db;
    }
  }
}
#endif /* if SQLITE_THREADSAFE */
#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */

Added src/btree.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
/*
** 2004 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btree.c,v 1.705 2009/08/10 03:57:58 shane Exp $
**
** This file implements a external (disk-based) database using BTrees.
** See the header comment on "btreeInt.h" for additional information.
** Including a description of file format and an overview of operation.
*/
#include "btreeInt.h"

/*
** The header string that appears at the beginning of every
** SQLite database.
*/
static const char zMagicHeader[] = SQLITE_FILE_HEADER;

/*
** Set this global variable to 1 to enable tracing using the TRACE
** macro.
*/
#if 0
int sqlite3BtreeTrace=1;  /* True to enable tracing */
# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
#else
# define TRACE(X)
#endif



#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** A list of BtShared objects that are eligible for participation
** in shared cache.  This variable has file scope during normal builds,
** but the test harness needs to access it so we make it global for 
** test builds.
**
** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
*/
#ifdef SQLITE_TEST
BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
#else
static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
#endif
#endif /* SQLITE_OMIT_SHARED_CACHE */

#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** Enable or disable the shared pager and schema features.
**
** This routine has no effect on existing database connections.
** The shared cache setting effects only future calls to
** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
*/
int sqlite3_enable_shared_cache(int enable){
  sqlite3GlobalConfig.sharedCacheEnabled = enable;
  return SQLITE_OK;
}
#endif



#ifdef SQLITE_OMIT_SHARED_CACHE
  /*
  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  ** and clearAllSharedCacheTableLocks()
  ** manipulate entries in the BtShared.pLock linked list used to store
  ** shared-cache table level locks. If the library is compiled with the
  ** shared-cache feature disabled, then there is only ever one user
  ** of each BtShared structure and so this locking is not necessary. 
  ** So define the lock related functions as no-ops.
  */
  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  #define clearAllSharedCacheTableLocks(a)
  #define downgradeAllSharedCacheTableLocks(a)
  #define hasSharedCacheTableLock(a,b,c,d) 1
  #define hasReadConflicts(a, b) 0
#endif

#ifndef SQLITE_OMIT_SHARED_CACHE

#ifdef SQLITE_DEBUG
/*
**** This function is only used as part of an assert() statement. ***
**
** Check to see if pBtree holds the required locks to read or write to the 
** table with root page iRoot.   Return 1 if it does and 0 if not.
**
** For example, when writing to a table with root-page iRoot via 
** Btree connection pBtree:
**
**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
**
** When writing to an index that resides in a sharable database, the 
** caller should have first obtained a lock specifying the root page of
** the corresponding table. This makes things a bit more complicated,
** as this module treats each table as a separate structure. To determine
** the table corresponding to the index being written, this
** function has to search through the database schema.
**
** Instead of a lock on the table/index rooted at page iRoot, the caller may
** hold a write-lock on the schema table (root page 1). This is also
** acceptable.
*/
static int hasSharedCacheTableLock(
  Btree *pBtree,         /* Handle that must hold lock */
  Pgno iRoot,            /* Root page of b-tree */
  int isIndex,           /* True if iRoot is the root of an index b-tree */
  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
){
  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  Pgno iTab = 0;
  BtLock *pLock;

  /* If this database is not shareable, or if the client is reading
  ** and has the read-uncommitted flag set, then no lock is required. 
  ** Return true immediately.
  */
  if( (pBtree->sharable==0)
   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  ){
    return 1;
  }

  /* If the client is reading  or writing an index and the schema is
  ** not loaded, then it is too difficult to actually check to see if
  ** the correct locks are held.  So do not bother - just return true.
  ** This case does not come up very often anyhow.
  */
  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
    return 1;
  }

  /* Figure out the root-page that the lock should be held on. For table
  ** b-trees, this is just the root page of the b-tree being read or
  ** written. For index b-trees, it is the root page of the associated
  ** table.  */
  if( isIndex ){
    HashElem *p;
    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
      Index *pIdx = (Index *)sqliteHashData(p);
      if( pIdx->tnum==(int)iRoot ){
        iTab = pIdx->pTable->tnum;
      }
    }
  }else{
    iTab = iRoot;
  }

  /* Search for the required lock. Either a write-lock on root-page iTab, a 
  ** write-lock on the schema table, or (if the client is reading) a
  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
    if( pLock->pBtree==pBtree 
     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
     && pLock->eLock>=eLockType 
    ){
      return 1;
    }
  }

  /* Failed to find the required lock. */
  return 0;
}
#endif /* SQLITE_DEBUG */

#ifdef SQLITE_DEBUG
/*
**** This function may be used as part of assert() statements only. ****
**
** Return true if it would be illegal for pBtree to write into the
** table or index rooted at iRoot because other shared connections are
** simultaneously reading that same table or index.
**
** It is illegal for pBtree to write if some other Btree object that
** shares the same BtShared object is currently reading or writing
** the iRoot table.  Except, if the other Btree object has the
** read-uncommitted flag set, then it is OK for the other object to
** have a read cursor.
**
** For example, before writing to any part of the table or index
** rooted at page iRoot, one should call:
**
**    assert( !hasReadConflicts(pBtree, iRoot) );
*/
static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  BtCursor *p;
  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
    if( p->pgnoRoot==iRoot 
     && p->pBtree!=pBtree
     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
    ){
      return 1;
    }
  }
  return 0;
}
#endif    /* #ifdef SQLITE_DEBUG */

/*
** Query to see if Btree handle p may obtain a lock of type eLock 
** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
** SQLITE_OK if the lock may be obtained (by calling
** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
*/
static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  BtShared *pBt = p->pBt;
  BtLock *pIter;

  assert( sqlite3BtreeHoldsMutex(p) );
  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  assert( p->db!=0 );
  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  
  /* If requesting a write-lock, then the Btree must have an open write
  ** transaction on this file. And, obviously, for this to be so there 
  ** must be an open write transaction on the file itself.
  */
  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  
  /* This routine is a no-op if the shared-cache is not enabled */
  if( !p->sharable ){
    return SQLITE_OK;
  }

  /* If some other connection is holding an exclusive lock, the
  ** requested lock may not be obtained.
  */
  if( pBt->pWriter!=p && pBt->isExclusive ){
    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
    return SQLITE_LOCKED_SHAREDCACHE;
  }

  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
    /* The condition (pIter->eLock!=eLock) in the following if(...) 
    ** statement is a simplification of:
    **
    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
    **
    ** since we know that if eLock==WRITE_LOCK, then no other connection
    ** may hold a WRITE_LOCK on any table in this file (since there can
    ** only be a single writer).
    */
    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
      if( eLock==WRITE_LOCK ){
        assert( p==pBt->pWriter );
        pBt->isPending = 1;
      }
      return SQLITE_LOCKED_SHAREDCACHE;
    }
  }
  return SQLITE_OK;
}
#endif /* !SQLITE_OMIT_SHARED_CACHE */

#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** Add a lock on the table with root-page iTable to the shared-btree used
** by Btree handle p. Parameter eLock must be either READ_LOCK or 
** WRITE_LOCK.
**
** This function assumes the following:
**
**   (a) The specified Btree object p is connected to a sharable
**       database (one with the BtShared.sharable flag set), and
**
**   (b) No other Btree objects hold a lock that conflicts
**       with the requested lock (i.e. querySharedCacheTableLock() has
**       already been called and returned SQLITE_OK).
**
** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
** is returned if a malloc attempt fails.
*/
static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  BtShared *pBt = p->pBt;
  BtLock *pLock = 0;
  BtLock *pIter;

  assert( sqlite3BtreeHoldsMutex(p) );
  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  assert( p->db!=0 );

  /* A connection with the read-uncommitted flag set will never try to
  ** obtain a read-lock using this function. The only read-lock obtained
  ** by a connection in read-uncommitted mode is on the sqlite_master 
  ** table, and that lock is obtained in BtreeBeginTrans().  */
  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );

  /* This function should only be called on a sharable b-tree after it 
  ** has been determined that no other b-tree holds a conflicting lock.  */
  assert( p->sharable );
  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );

  /* First search the list for an existing lock on this table. */
  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
    if( pIter->iTable==iTable && pIter->pBtree==p ){
      pLock = pIter;
      break;
    }
  }

  /* If the above search did not find a BtLock struct associating Btree p
  ** with table iTable, allocate one and link it into the list.
  */
  if( !pLock ){
    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
    if( !pLock ){
      return SQLITE_NOMEM;
    }
    pLock->iTable = iTable;
    pLock->pBtree = p;
    pLock->pNext = pBt->pLock;
    pBt->pLock = pLock;
  }

  /* Set the BtLock.eLock variable to the maximum of the current lock
  ** and the requested lock. This means if a write-lock was already held
  ** and a read-lock requested, we don't incorrectly downgrade the lock.
  */
  assert( WRITE_LOCK>READ_LOCK );
  if( eLock>pLock->eLock ){
    pLock->eLock = eLock;
  }

  return SQLITE_OK;
}
#endif /* !SQLITE_OMIT_SHARED_CACHE */

#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** Release all the table locks (locks obtained via calls to
** the setSharedCacheTableLock() procedure) held by Btree object p.
**
** This function assumes that Btree p has an open read or write 
** transaction. If it does not, then the BtShared.isPending variable
** may be incorrectly cleared.
*/
static void clearAllSharedCacheTableLocks(Btree *p){
  BtShared *pBt = p->pBt;
  BtLock **ppIter = &pBt->pLock;

  assert( sqlite3BtreeHoldsMutex(p) );
  assert( p->sharable || 0==*ppIter );
  assert( p->inTrans>0 );

  while( *ppIter ){
    BtLock *pLock = *ppIter;
    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
    assert( pLock->pBtree->inTrans>=pLock->eLock );
    if( pLock->pBtree==p ){
      *ppIter = pLock->pNext;
      assert( pLock->iTable!=1 || pLock==&p->lock );
      if( pLock->iTable!=1 ){
        sqlite3_free(pLock);
      }
    }else{
      ppIter = &pLock->pNext;
    }
  }

  assert( pBt->isPending==0 || pBt->pWriter );
  if( pBt->pWriter==p ){
    pBt->pWriter = 0;
    pBt->isExclusive = 0;
    pBt->isPending = 0;
  }else if( pBt->nTransaction==2 ){
    /* This function is called when Btree p is concluding its 
    ** transaction. If there currently exists a writer, and p is not
    ** that writer, then the number of locks held by connections other
    ** than the writer must be about to drop to zero. In this case
    ** set the isPending flag to 0.
    **
    ** If there is not currently a writer, then BtShared.isPending must
    ** be zero already. So this next line is harmless in that case.
    */
    pBt->isPending = 0;
  }
}

/*
** This function changes all write-locks held by Btree p into read-locks.
*/
static void downgradeAllSharedCacheTableLocks(Btree *p){
  BtShared *pBt = p->pBt;
  if( pBt->pWriter==p ){
    BtLock *pLock;
    pBt->pWriter = 0;
    pBt->isExclusive = 0;
    pBt->isPending = 0;
    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
      pLock->eLock = READ_LOCK;
    }
  }
}

#endif /* SQLITE_OMIT_SHARED_CACHE */

static void releasePage(MemPage *pPage);  /* Forward reference */

/*
***** This routine is used inside of assert() only ****
**
** Verify that the cursor holds the mutex on its BtShared
*/
#ifdef SQLITE_DEBUG
static int cursorHoldsMutex(BtCursor *p){
  return sqlite3_mutex_held(p->pBt->mutex);
}
#endif


#ifndef SQLITE_OMIT_INCRBLOB
/*
** Invalidate the overflow page-list cache for cursor pCur, if any.
*/
static void invalidateOverflowCache(BtCursor *pCur){
  assert( cursorHoldsMutex(pCur) );
  sqlite3_free(pCur->aOverflow);
  pCur->aOverflow = 0;
}

/*
** Invalidate the overflow page-list cache for all cursors opened
** on the shared btree structure pBt.
*/
static void invalidateAllOverflowCache(BtShared *pBt){
  BtCursor *p;
  assert( sqlite3_mutex_held(pBt->mutex) );
  for(p=pBt->pCursor; p; p=p->pNext){
    invalidateOverflowCache(p);
  }
}

/*
** This function is called before modifying the contents of a table
** to invalidate any incrblob cursors that are open on the
** row or one of the rows being modified.
**
** If argument isClearTable is true, then the entire contents of the
** table is about to be deleted. In this case invalidate all incrblob
** cursors open on any row within the table with root-page pgnoRoot.
**
** Otherwise, if argument isClearTable is false, then the row with
** rowid iRow is being replaced or deleted. In this case invalidate
** only those incrblob cursors open on that specific row.
*/
static void invalidateIncrblobCursors(
  Btree *pBtree,          /* The database file to check */
  i64 iRow,               /* The rowid that might be changing */
  int isClearTable        /* True if all rows are being deleted */
){
  BtCursor *p;
  BtShared *pBt = pBtree->pBt;
  assert( sqlite3BtreeHoldsMutex(pBtree) );
  for(p=pBt->pCursor; p; p=p->pNext){
    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
      p->eState = CURSOR_INVALID;
    }
  }
}

#else
  /* Stub functions when INCRBLOB is omitted */
  #define invalidateOverflowCache(x)
  #define invalidateAllOverflowCache(x)
  #define invalidateIncrblobCursors(x,y,z)
#endif /* SQLITE_OMIT_INCRBLOB */

/*
** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
** when a page that previously contained data becomes a free-list leaf 
** page.
**
** The BtShared.pHasContent bitvec exists to work around an obscure
** bug caused by the interaction of two useful IO optimizations surrounding
** free-list leaf pages:
**
**   1) When all data is deleted from a page and the page becomes
**      a free-list leaf page, the page is not written to the database
**      (as free-list leaf pages contain no meaningful data). Sometimes
**      such a page is not even journalled (as it will not be modified,
**      why bother journalling it?).
**
**   2) When a free-list leaf page is reused, its content is not read
**      from the database or written to the journal file (why should it
**      be, if it is not at all meaningful?).
**
** By themselves, these optimizations work fine and provide a handy
** performance boost to bulk delete or insert operations. However, if
** a page is moved to the free-list and then reused within the same
** transaction, a problem comes up. If the page is not journalled when
** it is moved to the free-list and it is also not journalled when it
** is extracted from the free-list and reused, then the original data
** may be lost. In the event of a rollback, it may not be possible
** to restore the database to its original configuration.
**
** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
** moved to become a free-list leaf page, the corresponding bit is
** set in the bitvec. Whenever a leaf page is extracted from the free-list,
** optimization 2 above is omitted if the corresponding bit is already
** set in BtShared.pHasContent. The contents of the bitvec are cleared
** at the end of every transaction.
*/
static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  int rc = SQLITE_OK;
  if( !pBt->pHasContent ){
    int nPage = 100;
    sqlite3PagerPagecount(pBt->pPager, &nPage);
    /* If sqlite3PagerPagecount() fails there is no harm because the
    ** nPage variable is unchanged from its default value of 100 */
    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
    if( !pBt->pHasContent ){
      rc = SQLITE_NOMEM;
    }
  }
  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  }
  return rc;
}

/*
** Query the BtShared.pHasContent vector.
**
** This function is called when a free-list leaf page is removed from the
** free-list for reuse. It returns false if it is safe to retrieve the
** page from the pager layer with the 'no-content' flag set. True otherwise.
*/
static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  Bitvec *p = pBt->pHasContent;
  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
}

/*
** Clear (destroy) the BtShared.pHasContent bitvec. This should be
** invoked at the conclusion of each write-transaction.
*/
static void btreeClearHasContent(BtShared *pBt){
  sqlite3BitvecDestroy(pBt->pHasContent);
  pBt->pHasContent = 0;
}

/*
** Save the current cursor position in the variables BtCursor.nKey 
** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
**
** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
** prior to calling this routine.  
*/
static int saveCursorPosition(BtCursor *pCur){
  int rc;

  assert( CURSOR_VALID==pCur->eState );
  assert( 0==pCur->pKey );
  assert( cursorHoldsMutex(pCur) );

  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */

  /* If this is an intKey table, then the above call to BtreeKeySize()
  ** stores the integer key in pCur->nKey. In this case this value is
  ** all that is required. Otherwise, if pCur is not open on an intKey
  ** table, then malloc space for and store the pCur->nKey bytes of key 
  ** data.
  */
  if( 0==pCur->apPage[0]->intKey ){
    void *pKey = sqlite3Malloc( (int)pCur->nKey );
    if( pKey ){
      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
      if( rc==SQLITE_OK ){
        pCur->pKey = pKey;
      }else{
        sqlite3_free(pKey);
      }
    }else{
      rc = SQLITE_NOMEM;
    }
  }
  assert( !pCur->apPage[0]->intKey || !pCur->pKey );

  if( rc==SQLITE_OK ){
    int i;
    for(i=0; i<=pCur->iPage; i++){
      releasePage(pCur->apPage[i]);
      pCur->apPage[i] = 0;
    }
    pCur->iPage = -1;
    pCur->eState = CURSOR_REQUIRESEEK;
  }

  invalidateOverflowCache(pCur);
  return rc;
}

/*
** Save the positions of all cursors (except pExcept) that are open on
** the table  with root-page iRoot. Usually, this is called just before cursor
** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
*/
static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  BtCursor *p;
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( pExcept==0 || pExcept->pBt==pBt );
  for(p=pBt->pCursor; p; p=p->pNext){
    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
        p->eState==CURSOR_VALID ){
      int rc = saveCursorPosition(p);
      if( SQLITE_OK!=rc ){
        return rc;
      }
    }
  }
  return SQLITE_OK;
}

/*
** Clear the current cursor position.
*/
void sqlite3BtreeClearCursor(BtCursor *pCur){
  assert( cursorHoldsMutex(pCur) );
  sqlite3_free(pCur->pKey);
  pCur->pKey = 0;
  pCur->eState = CURSOR_INVALID;
}

/*
** In this version of BtreeMoveto, pKey is a packed index record
** such as is generated by the OP_MakeRecord opcode.  Unpack the
** record and then call BtreeMovetoUnpacked() to do the work.
*/
static int btreeMoveto(
  BtCursor *pCur,     /* Cursor open on the btree to be searched */
  const void *pKey,   /* Packed key if the btree is an index */
  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
  int bias,           /* Bias search to the high end */
  int *pRes           /* Write search results here */
){
  int rc;                    /* Status code */
  UnpackedRecord *pIdxKey;   /* Unpacked index key */
  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */

  if( pKey ){
    assert( nKey==(i64)(int)nKey );
    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
                                      aSpace, sizeof(aSpace));
    if( pIdxKey==0 ) return SQLITE_NOMEM;
  }else{
    pIdxKey = 0;
  }
  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  if( pKey ){
    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  }
  return rc;
}

/*
** Restore the cursor to the position it was in (or as close to as possible)
** when saveCursorPosition() was called. Note that this call deletes the 
** saved position info stored by saveCursorPosition(), so there can be
** at most one effective restoreCursorPosition() call after each 
** saveCursorPosition().
*/
static int btreeRestoreCursorPosition(BtCursor *pCur){
  int rc;
  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState>=CURSOR_REQUIRESEEK );
  if( pCur->eState==CURSOR_FAULT ){
    return pCur->skipNext;
  }
  pCur->eState = CURSOR_INVALID;
  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  if( rc==SQLITE_OK ){
    sqlite3_free(pCur->pKey);
    pCur->pKey = 0;
    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  }
  return rc;
}

#define restoreCursorPosition(p) \
  (p->eState>=CURSOR_REQUIRESEEK ? \
         btreeRestoreCursorPosition(p) : \
         SQLITE_OK)

/*
** Determine whether or not a cursor has moved from the position it
** was last placed at.  Cursors can move when the row they are pointing
** at is deleted out from under them.
**
** This routine returns an error code if something goes wrong.  The
** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
*/
int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  int rc;

  rc = restoreCursorPosition(pCur);
  if( rc ){
    *pHasMoved = 1;
    return rc;
  }
  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
    *pHasMoved = 1;
  }else{
    *pHasMoved = 0;
  }
  return SQLITE_OK;
}

#ifndef SQLITE_OMIT_AUTOVACUUM
/*
** Given a page number of a regular database page, return the page
** number for the pointer-map page that contains the entry for the
** input page number.
*/
static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  int nPagesPerMapPage;
  Pgno iPtrMap, ret;
  assert( sqlite3_mutex_held(pBt->mutex) );
  nPagesPerMapPage = (pBt->usableSize/5)+1;
  iPtrMap = (pgno-2)/nPagesPerMapPage;
  ret = (iPtrMap*nPagesPerMapPage) + 2; 
  if( ret==PENDING_BYTE_PAGE(pBt) ){
    ret++;
  }
  return ret;
}

/*
** Write an entry into the pointer map.
**
** This routine updates the pointer map entry for page number 'key'
** so that it maps to type 'eType' and parent page number 'pgno'.
**
** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
** a no-op.  If an error occurs, the appropriate error code is written
** into *pRC.
*/
static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  DbPage *pDbPage;  /* The pointer map page */
  u8 *pPtrmap;      /* The pointer map data */
  Pgno iPtrmap;     /* The pointer map page number */
  int offset;       /* Offset in pointer map page */
  int rc;           /* Return code from subfunctions */

  if( *pRC ) return;

  assert( sqlite3_mutex_held(pBt->mutex) );
  /* The master-journal page number must never be used as a pointer map page */
  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );

  assert( pBt->autoVacuum );
  if( key==0 ){
    *pRC = SQLITE_CORRUPT_BKPT;
    return;
  }
  iPtrmap = PTRMAP_PAGENO(pBt, key);
  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  if( rc!=SQLITE_OK ){
    *pRC = rc;
    return;
  }
  offset = PTRMAP_PTROFFSET(iPtrmap, key);
  if( offset<0 ){
    *pRC = SQLITE_CORRUPT_BKPT;
    goto ptrmap_exit;
  }
  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);

  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
    *pRC= rc = sqlite3PagerWrite(pDbPage);
    if( rc==SQLITE_OK ){
      pPtrmap[offset] = eType;
      put4byte(&pPtrmap[offset+1], parent);
    }
  }

ptrmap_exit:
  sqlite3PagerUnref(pDbPage);
}

/*
** Read an entry from the pointer map.
**
** This routine retrieves the pointer map entry for page 'key', writing
** the type and parent page number to *pEType and *pPgno respectively.
** An error code is returned if something goes wrong, otherwise SQLITE_OK.
*/
static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  DbPage *pDbPage;   /* The pointer map page */
  int iPtrmap;       /* Pointer map page index */
  u8 *pPtrmap;       /* Pointer map page data */
  int offset;        /* Offset of entry in pointer map */
  int rc;

  assert( sqlite3_mutex_held(pBt->mutex) );

  iPtrmap = PTRMAP_PAGENO(pBt, key);
  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  if( rc!=0 ){
    return rc;
  }
  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);

  offset = PTRMAP_PTROFFSET(iPtrmap, key);
  assert( pEType!=0 );
  *pEType = pPtrmap[offset];
  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);

  sqlite3PagerUnref(pDbPage);
  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  return SQLITE_OK;
}

#else /* if defined SQLITE_OMIT_AUTOVACUUM */
  #define ptrmapPut(w,x,y,z,rc)
  #define ptrmapGet(w,x,y,z) SQLITE_OK
  #define ptrmapPutOvflPtr(x, y, rc)
#endif

/*
** Given a btree page and a cell index (0 means the first cell on
** the page, 1 means the second cell, and so forth) return a pointer
** to the cell content.
**
** This routine works only for pages that do not contain overflow cells.
*/
#define findCell(P,I) \
  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))

/*
** This a more complex version of findCell() that works for
** pages that do contain overflow cells.
*/
static u8 *findOverflowCell(MemPage *pPage, int iCell){
  int i;
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  for(i=pPage->nOverflow-1; i>=0; i--){
    int k;
    struct _OvflCell *pOvfl;
    pOvfl = &pPage->aOvfl[i];
    k = pOvfl->idx;
    if( k<=iCell ){
      if( k==iCell ){
        return pOvfl->pCell;
      }
      iCell--;
    }
  }
  return findCell(pPage, iCell);
}

/*
** Parse a cell content block and fill in the CellInfo structure.  There
** are two versions of this function.  btreeParseCell() takes a 
** cell index as the second argument and btreeParseCellPtr() 
** takes a pointer to the body of the cell as its second argument.
**
** Within this file, the parseCell() macro can be called instead of
** btreeParseCellPtr(). Using some compilers, this will be faster.
*/
static void btreeParseCellPtr(
  MemPage *pPage,         /* Page containing the cell */
  u8 *pCell,              /* Pointer to the cell text. */
  CellInfo *pInfo         /* Fill in this structure */
){
  u16 n;                  /* Number bytes in cell content header */
  u32 nPayload;           /* Number of bytes of cell payload */

  assert( sqlite3_mutex_held(pPage->pBt->mutex) );

  pInfo->pCell = pCell;
  assert( pPage->leaf==0 || pPage->leaf==1 );
  n = pPage->childPtrSize;
  assert( n==4-4*pPage->leaf );
  if( pPage->intKey ){
    if( pPage->hasData ){
      n += getVarint32(&pCell[n], nPayload);
    }else{
      nPayload = 0;
    }
    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
    pInfo->nData = nPayload;
  }else{
    pInfo->nData = 0;
    n += getVarint32(&pCell[n], nPayload);
    pInfo->nKey = nPayload;
  }
  pInfo->nPayload = nPayload;
  pInfo->nHeader = n;
  testcase( nPayload==pPage->maxLocal );
  testcase( nPayload==pPage->maxLocal+1 );
  if( likely(nPayload<=pPage->maxLocal) ){
    /* This is the (easy) common case where the entire payload fits
    ** on the local page.  No overflow is required.
    */
    int nSize;          /* Total size of cell content in bytes */
    nSize = nPayload + n;
    pInfo->nLocal = (u16)nPayload;
    pInfo->iOverflow = 0;
    if( (nSize & ~3)==0 ){
      nSize = 4;        /* Minimum cell size is 4 */
    }
    pInfo->nSize = (u16)nSize;
  }else{
    /* If the payload will not fit completely on the local page, we have
    ** to decide how much to store locally and how much to spill onto
    ** overflow pages.  The strategy is to minimize the amount of unused
    ** space on overflow pages while keeping the amount of local storage
    ** in between minLocal and maxLocal.
    **
    ** Warning:  changing the way overflow payload is distributed in any
    ** way will result in an incompatible file format.
    */
    int minLocal;  /* Minimum amount of payload held locally */
    int maxLocal;  /* Maximum amount of payload held locally */
    int surplus;   /* Overflow payload available for local storage */

    minLocal = pPage->minLocal;
    maxLocal = pPage->maxLocal;
    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
    testcase( surplus==maxLocal );
    testcase( surplus==maxLocal+1 );
    if( surplus <= maxLocal ){
      pInfo->nLocal = (u16)surplus;
    }else{
      pInfo->nLocal = (u16)minLocal;
    }
    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
    pInfo->nSize = pInfo->iOverflow + 4;
  }
}
#define parseCell(pPage, iCell, pInfo) \
  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
static void btreeParseCell(
  MemPage *pPage,         /* Page containing the cell */
  int iCell,              /* The cell index.  First cell is 0 */
  CellInfo *pInfo         /* Fill in this structure */
){
  parseCell(pPage, iCell, pInfo);
}

/*
** Compute the total number of bytes that a Cell needs in the cell
** data area of the btree-page.  The return number includes the cell
** data header and the local payload, but not any overflow page or
** the space used by the cell pointer.
*/
static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  u8 *pIter = &pCell[pPage->childPtrSize];
  u32 nSize;

#ifdef SQLITE_DEBUG
  /* The value returned by this function should always be the same as
  ** the (CellInfo.nSize) value found by doing a full parse of the
  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  ** this function verifies that this invariant is not violated. */
  CellInfo debuginfo;
  btreeParseCellPtr(pPage, pCell, &debuginfo);
#endif

  if( pPage->intKey ){
    u8 *pEnd;
    if( pPage->hasData ){
      pIter += getVarint32(pIter, nSize);
    }else{
      nSize = 0;
    }

    /* pIter now points at the 64-bit integer key value, a variable length 
    ** integer. The following block moves pIter to point at the first byte
    ** past the end of the key value. */
    pEnd = &pIter[9];
    while( (*pIter++)&0x80 && pIter<pEnd );
  }else{
    pIter += getVarint32(pIter, nSize);
  }

  testcase( nSize==pPage->maxLocal );
  testcase( nSize==pPage->maxLocal+1 );
  if( nSize>pPage->maxLocal ){
    int minLocal = pPage->minLocal;
    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
    testcase( nSize==pPage->maxLocal );
    testcase( nSize==pPage->maxLocal+1 );
    if( nSize>pPage->maxLocal ){
      nSize = minLocal;
    }
    nSize += 4;
  }
  nSize += (u32)(pIter - pCell);

  /* The minimum size of any cell is 4 bytes. */
  if( nSize<4 ){
    nSize = 4;
  }

  assert( nSize==debuginfo.nSize );
  return (u16)nSize;
}

#ifdef SQLITE_DEBUG
/* This variation on cellSizePtr() is used inside of assert() statements
** only. */
static u16 cellSize(MemPage *pPage, int iCell){
  return cellSizePtr(pPage, findCell(pPage, iCell));
}
#endif

#ifndef SQLITE_OMIT_AUTOVACUUM
/*
** If the cell pCell, part of page pPage contains a pointer
** to an overflow page, insert an entry into the pointer-map
** for the overflow page.
*/
static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  CellInfo info;
  if( *pRC ) return;
  assert( pCell!=0 );
  btreeParseCellPtr(pPage, pCell, &info);
  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  if( info.iOverflow ){
    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  }
}
#endif


/*
** Defragment the page given.  All Cells are moved to the
** end of the page and all free space is collected into one
** big FreeBlk that occurs in between the header and cell
** pointer array and the cell content area.
*/
static int defragmentPage(MemPage *pPage){
  int i;                     /* Loop counter */
  int pc;                    /* Address of a i-th cell */
  int hdr;                   /* Offset to the page header */
  int size;                  /* Size of a cell */
  int usableSize;            /* Number of usable bytes on a page */
  int cellOffset;            /* Offset to the cell pointer array */
  int cbrk;                  /* Offset to the cell content area */
  int nCell;                 /* Number of cells on the page */
  unsigned char *data;       /* The page data */
  unsigned char *temp;       /* Temp area for cell content */
  int iCellFirst;            /* First allowable cell index */
  int iCellLast;             /* Last possible cell index */


  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( pPage->pBt!=0 );
  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  assert( pPage->nOverflow==0 );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  data = pPage->aData;
  hdr = pPage->hdrOffset;
  cellOffset = pPage->cellOffset;
  nCell = pPage->nCell;
  assert( nCell==get2byte(&data[hdr+3]) );
  usableSize = pPage->pBt->usableSize;
  cbrk = get2byte(&data[hdr+5]);
  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  cbrk = usableSize;
  iCellFirst = cellOffset + 2*nCell;
  iCellLast = usableSize - 4;
  for(i=0; i<nCell; i++){
    u8 *pAddr;     /* The i-th cell pointer */
    pAddr = &data[cellOffset + i*2];
    pc = get2byte(pAddr);
    testcase( pc==iCellFirst );
    testcase( pc==iCellLast );
#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
    /* These conditions have already been verified in btreeInitPage()
    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
    */
    if( pc<iCellFirst || pc>iCellLast ){
      return SQLITE_CORRUPT_BKPT;
    }
#endif
    assert( pc>=iCellFirst && pc<=iCellLast );
    size = cellSizePtr(pPage, &temp[pc]);
    cbrk -= size;
#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
    if( cbrk<iCellFirst ){
      return SQLITE_CORRUPT_BKPT;
    }
#else
    if( cbrk<iCellFirst || pc+size>usableSize ){
      return SQLITE_CORRUPT_BKPT;
    }
#endif
    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
    testcase( cbrk+size==usableSize );
    testcase( pc+size==usableSize );
    memcpy(&data[cbrk], &temp[pc], size);
    put2byte(pAddr, cbrk);
  }
  assert( cbrk>=iCellFirst );
  put2byte(&data[hdr+5], cbrk);
  data[hdr+1] = 0;
  data[hdr+2] = 0;
  data[hdr+7] = 0;
  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  if( cbrk-iCellFirst!=pPage->nFree ){
    return SQLITE_CORRUPT_BKPT;
  }
  return SQLITE_OK;
}

/*
** Allocate nByte bytes of space from within the B-Tree page passed
** as the first argument. Write into *pIdx the index into pPage->aData[]
** of the first byte of allocated space. Return either SQLITE_OK or
** an error code (usually SQLITE_CORRUPT).
**
** The caller guarantees that there is sufficient space to make the
** allocation.  This routine might need to defragment in order to bring
** all the space together, however.  This routine will avoid using
** the first two bytes past the cell pointer area since presumably this
** allocation is being made in order to insert a new cell, so we will
** also end up needing a new cell pointer.
*/
static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
  int nFrag;                           /* Number of fragmented bytes on pPage */
  int top;                             /* First byte of cell content area */
  int gap;        /* First byte of gap between cell pointers and cell content */
  int rc;         /* Integer return code */
  
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( pPage->pBt );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( nByte>=0 );  /* Minimum cell size is 4 */
  assert( pPage->nFree>=nByte );
  assert( pPage->nOverflow==0 );
  assert( nByte<pPage->pBt->usableSize-8 );

  nFrag = data[hdr+7];
  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  gap = pPage->cellOffset + 2*pPage->nCell;
  top = get2byte(&data[hdr+5]);
  if( gap>top ) return SQLITE_CORRUPT_BKPT;
  testcase( gap+2==top );
  testcase( gap+1==top );
  testcase( gap==top );

  if( nFrag>=60 ){
    /* Always defragment highly fragmented pages */
    rc = defragmentPage(pPage);
    if( rc ) return rc;
    top = get2byte(&data[hdr+5]);
  }else if( gap+2<=top ){
    /* Search the freelist looking for a free slot big enough to satisfy 
    ** the request. The allocation is made from the first free slot in 
    ** the list that is large enough to accomadate it.
    */
    int pc, addr;
    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
      int size = get2byte(&data[pc+2]);     /* Size of free slot */
      if( size>=nByte ){
        int x = size - nByte;
        testcase( x==4 );
        testcase( x==3 );
        if( x<4 ){
          /* Remove the slot from the free-list. Update the number of
          ** fragmented bytes within the page. */
          memcpy(&data[addr], &data[pc], 2);
          data[hdr+7] = (u8)(nFrag + x);
        }else{
          /* The slot remains on the free-list. Reduce its size to account
          ** for the portion used by the new allocation. */
          put2byte(&data[pc+2], x);
        }
        *pIdx = pc + x;
        return SQLITE_OK;
      }
    }
  }

  /* Check to make sure there is enough space in the gap to satisfy
  ** the allocation.  If not, defragment.
  */
  testcase( gap+2+nByte==top );
  if( gap+2+nByte>top ){
    rc = defragmentPage(pPage);
    if( rc ) return rc;
    top = get2byte(&data[hdr+5]);
    assert( gap+nByte<=top );
  }


  /* Allocate memory from the gap in between the cell pointer array
  ** and the cell content area.  The btreeInitPage() call has already
  ** validated the freelist.  Given that the freelist is valid, there
  ** is no way that the allocation can extend off the end of the page.
  ** The assert() below verifies the previous sentence.
  */
  top -= nByte;
  put2byte(&data[hdr+5], top);
  assert( top+nByte <= pPage->pBt->usableSize );
  *pIdx = top;
  return SQLITE_OK;
}

/*
** Return a section of the pPage->aData to the freelist.
** The first byte of the new free block is pPage->aDisk[start]
** and the size of the block is "size" bytes.
**
** Most of the effort here is involved in coalesing adjacent
** free blocks into a single big free block.
*/
static int freeSpace(MemPage *pPage, int start, int size){
  int addr, pbegin, hdr;
  int iLast;                        /* Largest possible freeblock offset */
  unsigned char *data = pPage->aData;

  assert( pPage->pBt!=0 );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  assert( (start + size)<=pPage->pBt->usableSize );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( size>=0 );   /* Minimum cell size is 4 */

#ifdef SQLITE_SECURE_DELETE
  /* Overwrite deleted information with zeros when the SECURE_DELETE 
  ** option is enabled at compile-time */
  memset(&data[start], 0, size);
#endif

  /* Add the space back into the linked list of freeblocks.  Note that
  ** even though the freeblock list was checked by btreeInitPage(),
  ** btreeInitPage() did not detect overlapping cells or
  ** freeblocks that overlapped cells.   Nor does it detect when the
  ** cell content area exceeds the value in the page header.  If these
  ** situations arise, then subsequent insert operations might corrupt
  ** the freelist.  So we do need to check for corruption while scanning
  ** the freelist.
  */
  hdr = pPage->hdrOffset;
  addr = hdr + 1;
  iLast = pPage->pBt->usableSize - 4;
  assert( start<=iLast );
  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
    if( pbegin<addr+4 ){
      return SQLITE_CORRUPT_BKPT;
    }
    addr = pbegin;
  }
  if( pbegin>iLast ){
    return SQLITE_CORRUPT_BKPT;
  }
  assert( pbegin>addr || pbegin==0 );
  put2byte(&data[addr], start);
  put2byte(&data[start], pbegin);
  put2byte(&data[start+2], size);
  pPage->nFree = pPage->nFree + (u16)size;

  /* Coalesce adjacent free blocks */
  addr = hdr + 1;
  while( (pbegin = get2byte(&data[addr]))>0 ){
    int pnext, psize, x;
    assert( pbegin>addr );
    assert( pbegin<=pPage->pBt->usableSize-4 );
    pnext = get2byte(&data[pbegin]);
    psize = get2byte(&data[pbegin+2]);
    if( pbegin + psize + 3 >= pnext && pnext>0 ){
      int frag = pnext - (pbegin+psize);
      if( (frag<0) || (frag>(int)data[hdr+7]) ){
        return SQLITE_CORRUPT_BKPT;
      }
      data[hdr+7] -= (u8)frag;
      x = get2byte(&data[pnext]);
      put2byte(&data[pbegin], x);
      x = pnext + get2byte(&data[pnext+2]) - pbegin;
      put2byte(&data[pbegin+2], x);
    }else{
      addr = pbegin;
    }
  }

  /* If the cell content area begins with a freeblock, remove it. */
  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
    int top;
    pbegin = get2byte(&data[hdr+1]);
    memcpy(&data[hdr+1], &data[pbegin], 2);
    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
    put2byte(&data[hdr+5], top);
  }
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  return SQLITE_OK;
}

/*
** Decode the flags byte (the first byte of the header) for a page
** and initialize fields of the MemPage structure accordingly.
**
** Only the following combinations are supported.  Anything different
** indicates a corrupt database files:
**
**         PTF_ZERODATA
**         PTF_ZERODATA | PTF_LEAF
**         PTF_LEAFDATA | PTF_INTKEY
**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
*/
static int decodeFlags(MemPage *pPage, int flagByte){
  BtShared *pBt;     /* A copy of pPage->pBt */

  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
  flagByte &= ~PTF_LEAF;
  pPage->childPtrSize = 4-4*pPage->leaf;
  pBt = pPage->pBt;
  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
    pPage->intKey = 1;
    pPage->hasData = pPage->leaf;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  }else if( flagByte==PTF_ZERODATA ){
    pPage->intKey = 0;
    pPage->hasData = 0;
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }else{
    return SQLITE_CORRUPT_BKPT;
  }
  return SQLITE_OK;
}

/*
** Initialize the auxiliary information for a disk block.
**
** Return SQLITE_OK on success.  If we see that the page does
** not contain a well-formed database page, then return 
** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
** guarantee that the page is well-formed.  It only shows that
** we failed to detect any corruption.
*/
static int btreeInitPage(MemPage *pPage){

  assert( pPage->pBt!=0 );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );

  if( !pPage->isInit ){
    u16 pc;            /* Address of a freeblock within pPage->aData[] */
    u8 hdr;            /* Offset to beginning of page header */
    u8 *data;          /* Equal to pPage->aData */
    BtShared *pBt;        /* The main btree structure */
    u16 usableSize;    /* Amount of usable space on each page */
    u16 cellOffset;    /* Offset from start of page to first cell pointer */
    u16 nFree;         /* Number of unused bytes on the page */
    u16 top;           /* First byte of the cell content area */
    int iCellFirst;    /* First allowable cell or freeblock offset */
    int iCellLast;     /* Last possible cell or freeblock offset */

    pBt = pPage->pBt;

    hdr = pPage->hdrOffset;
    data = pPage->aData;
    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
    pPage->maskPage = pBt->pageSize - 1;
    pPage->nOverflow = 0;
    usableSize = pBt->usableSize;
    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
    top = get2byte(&data[hdr+5]);
    pPage->nCell = get2byte(&data[hdr+3]);
    if( pPage->nCell>MX_CELL(pBt) ){
      /* To many cells for a single page.  The page must be corrupt */
      return SQLITE_CORRUPT_BKPT;
    }
    testcase( pPage->nCell==MX_CELL(pBt) );

    /* A malformed database page might cause us to read past the end
    ** of page when parsing a cell.  
    **
    ** The following block of code checks early to see if a cell extends
    ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
    ** returned if it does.
    */
    iCellFirst = cellOffset + 2*pPage->nCell;
    iCellLast = usableSize - 4;
#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
    {
      int i;            /* Index into the cell pointer array */
      int sz;           /* Size of a cell */

      if( !pPage->leaf ) iCellLast--;
      for(i=0; i<pPage->nCell; i++){
        pc = get2byte(&data[cellOffset+i*2]);
        testcase( pc==iCellFirst );
        testcase( pc==iCellLast );
        if( pc<iCellFirst || pc>iCellLast ){
          return SQLITE_CORRUPT_BKPT;
        }
        sz = cellSizePtr(pPage, &data[pc]);
        testcase( pc+sz==usableSize );
        if( pc+sz>usableSize ){
          return SQLITE_CORRUPT_BKPT;
        }
      }
      if( !pPage->leaf ) iCellLast++;
    }  
#endif

    /* Compute the total free space on the page */
    pc = get2byte(&data[hdr+1]);
    nFree = data[hdr+7] + top;
    while( pc>0 ){
      u16 next, size;
      if( pc<iCellFirst || pc>iCellLast ){
        /* Start of free block is off the page */
        return SQLITE_CORRUPT_BKPT; 
      }
      next = get2byte(&data[pc]);
      size = get2byte(&data[pc+2]);
      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
        /* Free blocks must be in ascending order. And the last byte of
	** the free-block must lie on the database page.  */
        return SQLITE_CORRUPT_BKPT; 
      }
      nFree = nFree + size;
      pc = next;
    }

    /* At this point, nFree contains the sum of the offset to the start
    ** of the cell-content area plus the number of free bytes within
    ** the cell-content area. If this is greater than the usable-size
    ** of the page, then the page must be corrupted. This check also
    ** serves to verify that the offset to the start of the cell-content
    ** area, according to the page header, lies within the page.
    */
    if( nFree>usableSize ){
      return SQLITE_CORRUPT_BKPT; 
    }
    pPage->nFree = (u16)(nFree - iCellFirst);
    pPage->isInit = 1;
  }
  return SQLITE_OK;
}

/*
** Set up a raw page so that it looks like a database page holding
** no entries.
*/
static void zeroPage(MemPage *pPage, int flags){
  unsigned char *data = pPage->aData;
  BtShared *pBt = pPage->pBt;
  u8 hdr = pPage->hdrOffset;
  u16 first;

  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( sqlite3_mutex_held(pBt->mutex) );
  /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
  data[hdr] = (char)flags;
  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  memset(&data[hdr+1], 0, 4);
  data[hdr+7] = 0;
  put2byte(&data[hdr+5], pBt->usableSize);
  pPage->nFree = pBt->usableSize - first;
  decodeFlags(pPage, flags);
  pPage->hdrOffset = hdr;
  pPage->cellOffset = first;
  pPage->nOverflow = 0;
  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
  pPage->maskPage = pBt->pageSize - 1;
  pPage->nCell = 0;
  pPage->isInit = 1;
}


/*
** Convert a DbPage obtained from the pager into a MemPage used by
** the btree layer.
*/
static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  pPage->aData = sqlite3PagerGetData(pDbPage);
  pPage->pDbPage = pDbPage;
  pPage->pBt = pBt;
  pPage->pgno = pgno;
  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  return pPage; 
}

/*
** Get a page from the pager.  Initialize the MemPage.pBt and
** MemPage.aData elements if needed.
**
** If the noContent flag is set, it means that we do not care about
** the content of the page at this time.  So do not go to the disk
** to fetch the content.  Just fill in the content with zeros for now.
** If in the future we call sqlite3PagerWrite() on this page, that
** means we have started to be concerned about content and the disk
** read should occur at that point.
*/
static int btreeGetPage(
  BtShared *pBt,       /* The btree */
  Pgno pgno,           /* Number of the page to fetch */
  MemPage **ppPage,    /* Return the page in this parameter */
  int noContent        /* Do not load page content if true */
){
  int rc;
  DbPage *pDbPage;

  assert( sqlite3_mutex_held(pBt->mutex) );
  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  if( rc ) return rc;
  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  return SQLITE_OK;
}

/*
** Retrieve a page from the pager cache. If the requested page is not
** already in the pager cache return NULL. Initialize the MemPage.pBt and
** MemPage.aData elements if needed.
*/
static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  DbPage *pDbPage;
  assert( sqlite3_mutex_held(pBt->mutex) );
  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  if( pDbPage ){
    return btreePageFromDbPage(pDbPage, pgno, pBt);
  }
  return 0;
}

/*
** Return the size of the database file in pages. If there is any kind of
** error, return ((unsigned int)-1).
*/
static Pgno pagerPagecount(BtShared *pBt){
  int nPage = -1;
  int rc;
  assert( pBt->pPage1 );
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  assert( rc==SQLITE_OK || nPage==-1 );
  return (Pgno)nPage;
}

/*
** Get a page from the pager and initialize it.  This routine is just a
** convenience wrapper around separate calls to btreeGetPage() and 
** btreeInitPage().
**
** If an error occurs, then the value *ppPage is set to is undefined. It
** may remain unchanged, or it may be set to an invalid value.
*/
static int getAndInitPage(
  BtShared *pBt,          /* The database file */
  Pgno pgno,           /* Number of the page to get */
  MemPage **ppPage     /* Write the page pointer here */
){
  int rc;
  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
  assert( sqlite3_mutex_held(pBt->mutex) );

  rc = btreeGetPage(pBt, pgno, ppPage, 0);
  if( rc==SQLITE_OK ){
    rc = btreeInitPage(*ppPage);
    if( rc!=SQLITE_OK ){
      releasePage(*ppPage);
    }
  }

  /* If the requested page number was either 0 or greater than the page
  ** number of the last page in the database, this function should return
  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
  ** is the case.  */
  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
  testcase( pgno==0 );
  testcase( pgno==iLastPg );

  return rc;
}

/*
** Release a MemPage.  This should be called once for each prior
** call to btreeGetPage.
*/
static void releasePage(MemPage *pPage){
  if( pPage ){
    assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
    assert( pPage->aData );
    assert( pPage->pBt );
    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
    sqlite3PagerUnref(pPage->pDbPage);
  }
}

/*
** During a rollback, when the pager reloads information into the cache
** so that the cache is restored to its original state at the start of
** the transaction, for each page restored this routine is called.
**
** This routine needs to reset the extra data section at the end of the
** page to agree with the restored data.
*/
static void pageReinit(DbPage *pData){
  MemPage *pPage;
  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  assert( sqlite3PagerPageRefcount(pData)>0 );
  if( pPage->isInit ){
    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
    pPage->isInit = 0;
    if( sqlite3PagerPageRefcount(pData)>1 ){
      /* pPage might not be a btree page;  it might be an overflow page
      ** or ptrmap page or a free page.  In those cases, the following
      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
      ** But no harm is done by this.  And it is very important that
      ** btreeInitPage() be called on every btree page so we make
      ** the call for every page that comes in for re-initing. */
      btreeInitPage(pPage);
    }
  }
}

/*
** Invoke the busy handler for a btree.
*/
static int btreeInvokeBusyHandler(void *pArg){
  BtShared *pBt = (BtShared*)pArg;
  assert( pBt->db );
  assert( sqlite3_mutex_held(pBt->db->mutex) );
  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
}

/*
** Open a database file.
** 
** zFilename is the name of the database file.  If zFilename is NULL
** a new database with a random name is created.  This randomly named
** database file will be deleted when sqlite3BtreeClose() is called.
** If zFilename is ":memory:" then an in-memory database is created
** that is automatically destroyed when it is closed.
**
** If the database is already opened in the same database connection
** and we are in shared cache mode, then the open will fail with an
** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
** objects in the same database connection since doing so will lead
** to problems with locking.
*/
int sqlite3BtreeOpen(
  const char *zFilename,  /* Name of the file containing the BTree database */
  sqlite3 *db,            /* Associated database handle */
  Btree **ppBtree,        /* Pointer to new Btree object written here */
  int flags,              /* Options */
  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
){
  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
  BtShared *pBt = 0;             /* Shared part of btree structure */
  Btree *p;                      /* Handle to return */
  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
  int rc = SQLITE_OK;            /* Result code from this function */
  u8 nReserve;                   /* Byte of unused space on each page */
  unsigned char zDbHeader[100];  /* Database header content */

  /* Set the variable isMemdb to true for an in-memory database, or 
  ** false for a file-based database. This symbol is only required if
  ** either of the shared-data or autovacuum features are compiled 
  ** into the library.
  */
#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
  #ifdef SQLITE_OMIT_MEMORYDB
    const int isMemdb = 0;
  #else
    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
  #endif
#endif

  assert( db!=0 );
  assert( sqlite3_mutex_held(db->mutex) );

  pVfs = db->pVfs;
  p = sqlite3MallocZero(sizeof(Btree));
  if( !p ){
    return SQLITE_NOMEM;
  }
  p->inTrans = TRANS_NONE;
  p->db = db;
#ifndef SQLITE_OMIT_SHARED_CACHE
  p->lock.pBtree = p;
  p->lock.iTable = 1;
#endif

#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  /*
  ** If this Btree is a candidate for shared cache, try to find an
  ** existing BtShared object that we can share with
  */
  if( isMemdb==0 && zFilename && zFilename[0] ){
    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
      int nFullPathname = pVfs->mxPathname+1;
      char *zFullPathname = sqlite3Malloc(nFullPathname);
      sqlite3_mutex *mutexShared;
      p->sharable = 1;
      if( !zFullPathname ){
        sqlite3_free(p);
        return SQLITE_NOMEM;
      }
      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
      sqlite3_mutex_enter(mutexOpen);
      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
      sqlite3_mutex_enter(mutexShared);
      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
        assert( pBt->nRef>0 );
        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
          int iDb;
          for(iDb=db->nDb-1; iDb>=0; iDb--){
            Btree *pExisting = db->aDb[iDb].pBt;
            if( pExisting && pExisting->pBt==pBt ){
              sqlite3_mutex_leave(mutexShared);
              sqlite3_mutex_leave(mutexOpen);
              sqlite3_free(zFullPathname);
              sqlite3_free(p);
              return SQLITE_CONSTRAINT;
            }
          }
          p->pBt = pBt;
          pBt->nRef++;
          break;
        }
      }
      sqlite3_mutex_leave(mutexShared);
      sqlite3_free(zFullPathname);
    }
#ifdef SQLITE_DEBUG
    else{
      /* In debug mode, we mark all persistent databases as sharable
      ** even when they are not.  This exercises the locking code and
      ** gives more opportunity for asserts(sqlite3_mutex_held())
      ** statements to find locking problems.
      */
      p->sharable = 1;
    }
#endif
  }
#endif
  if( pBt==0 ){
    /*
    ** The following asserts make sure that structures used by the btree are
    ** the right size.  This is to guard against size changes that result
    ** when compiling on a different architecture.
    */
    assert( sizeof(i64)==8 || sizeof(i64)==4 );
    assert( sizeof(u64)==8 || sizeof(u64)==4 );
    assert( sizeof(u32)==4 );
    assert( sizeof(u16)==2 );
    assert( sizeof(Pgno)==4 );
  
    pBt = sqlite3MallocZero( sizeof(*pBt) );
    if( pBt==0 ){
      rc = SQLITE_NOMEM;
      goto btree_open_out;
    }
    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
    if( rc==SQLITE_OK ){
      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
    }
    if( rc!=SQLITE_OK ){
      goto btree_open_out;
    }
    pBt->db = db;
    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
    p->pBt = pBt;
  
    pBt->pCursor = 0;
    pBt->pPage1 = 0;
    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
    pBt->pageSize = get2byte(&zDbHeader[16]);
    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
      pBt->pageSize = 0;
#ifndef SQLITE_OMIT_AUTOVACUUM
      /* If the magic name ":memory:" will create an in-memory database, then
      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
      ** regular file-name. In this case the auto-vacuum applies as per normal.
      */
      if( zFilename && !isMemdb ){
        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
      }
#endif
      nReserve = 0;
    }else{
      nReserve = zDbHeader[20];
      pBt->pageSizeFixed = 1;
#ifndef SQLITE_OMIT_AUTOVACUUM
      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
#endif
    }
    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
    if( rc ) goto btree_open_out;
    pBt->usableSize = pBt->pageSize - nReserve;
    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   
#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
    /* Add the new BtShared object to the linked list sharable BtShareds.
    */
    if( p->sharable ){
      sqlite3_mutex *mutexShared;
      pBt->nRef = 1;
      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
        if( pBt->mutex==0 ){
          rc = SQLITE_NOMEM;
          db->mallocFailed = 0;
          goto btree_open_out;
        }
      }
      sqlite3_mutex_enter(mutexShared);
      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
      sqlite3_mutex_leave(mutexShared);
    }
#endif
  }

#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  /* If the new Btree uses a sharable pBtShared, then link the new
  ** Btree into the list of all sharable Btrees for the same connection.
  ** The list is kept in ascending order by pBt address.
  */
  if( p->sharable ){
    int i;
    Btree *pSib;
    for(i=0; i<db->nDb; i++){
      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
        while( pSib->pPrev ){ pSib = pSib->pPrev; }
        if( p->pBt<pSib->pBt ){
          p->pNext = pSib;
          p->pPrev = 0;
          pSib->pPrev = p;
        }else{
          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
            pSib = pSib->pNext;
          }
          p->pNext = pSib->pNext;
          p->pPrev = pSib;
          if( p->pNext ){
            p->pNext->pPrev = p;
          }
          pSib->pNext = p;
        }
        break;
      }
    }
  }
#endif
  *ppBtree = p;

btree_open_out:
  if( rc!=SQLITE_OK ){
    if( pBt && pBt->pPager ){
      sqlite3PagerClose(pBt->pPager);
    }
    sqlite3_free(pBt);
    sqlite3_free(p);
    *ppBtree = 0;
  }
  if( mutexOpen ){
    assert( sqlite3_mutex_held(mutexOpen) );
    sqlite3_mutex_leave(mutexOpen);
  }
  return rc;
}

/*
** Decrement the BtShared.nRef counter.  When it reaches zero,
** remove the BtShared structure from the sharing list.  Return
** true if the BtShared.nRef counter reaches zero and return
** false if it is still positive.
*/
static int removeFromSharingList(BtShared *pBt){
#ifndef SQLITE_OMIT_SHARED_CACHE
  sqlite3_mutex *pMaster;
  BtShared *pList;
  int removed = 0;

  assert( sqlite3_mutex_notheld(pBt->mutex) );
  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  sqlite3_mutex_enter(pMaster);
  pBt->nRef--;
  if( pBt->nRef<=0 ){
    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
    }else{
      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
      while( ALWAYS(pList) && pList->pNext!=pBt ){
        pList=pList->pNext;
      }
      if( ALWAYS(pList) ){
        pList->pNext = pBt->pNext;
      }
    }
    if( SQLITE_THREADSAFE ){
      sqlite3_mutex_free(pBt->mutex);
    }
    removed = 1;
  }
  sqlite3_mutex_leave(pMaster);
  return removed;
#else
  return 1;
#endif
}

/*
** Make sure pBt->pTmpSpace points to an allocation of 
** MX_CELL_SIZE(pBt) bytes.
*/
static void allocateTempSpace(BtShared *pBt){
  if( !pBt->pTmpSpace ){
    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  }
}

/*
** Free the pBt->pTmpSpace allocation
*/
static void freeTempSpace(BtShared *pBt){
  sqlite3PageFree( pBt->pTmpSpace);
  pBt->pTmpSpace = 0;
}

/*
** Close an open database and invalidate all cursors.
*/
int sqlite3BtreeClose(Btree *p){
  BtShared *pBt = p->pBt;
  BtCursor *pCur;

  /* Close all cursors opened via this handle.  */
  assert( sqlite3_mutex_held(p->db->mutex) );
  sqlite3BtreeEnter(p);
  pCur = pBt->pCursor;
  while( pCur ){
    BtCursor *pTmp = pCur;
    pCur = pCur->pNext;
    if( pTmp->pBtree==p ){
      sqlite3BtreeCloseCursor(pTmp);
    }
  }

  /* Rollback any active transaction and free the handle structure.
  ** The call to sqlite3BtreeRollback() drops any table-locks held by
  ** this handle.
  */
  sqlite3BtreeRollback(p);
  sqlite3BtreeLeave(p);

  /* If there are still other outstanding references to the shared-btree
  ** structure, return now. The remainder of this procedure cleans 
  ** up the shared-btree.
  */
  assert( p->wantToLock==0 && p->locked==0 );
  if( !p->sharable || removeFromSharingList(pBt) ){
    /* The pBt is no longer on the sharing list, so we can access
    ** it without having to hold the mutex.
    **
    ** Clean out and delete the BtShared object.
    */
    assert( !pBt->pCursor );
    sqlite3PagerClose(pBt->pPager);
    if( pBt->xFreeSchema && pBt->pSchema ){
      pBt->xFreeSchema(pBt->pSchema);
    }
    sqlite3_free(pBt->pSchema);
    freeTempSpace(pBt);
    sqlite3_free(pBt);
  }

#ifndef SQLITE_OMIT_SHARED_CACHE
  assert( p->wantToLock==0 );
  assert( p->locked==0 );
  if( p->pPrev ) p->pPrev->pNext = p->pNext;
  if( p->pNext ) p->pNext->pPrev = p->pPrev;
#endif

  sqlite3_free(p);
  return SQLITE_OK;
}

/*
** Change the limit on the number of pages allowed in the cache.
**
** The maximum number of cache pages is set to the absolute
** value of mxPage.  If mxPage is negative, the pager will
** operate asynchronously - it will not stop to do fsync()s
** to insure data is written to the disk surface before
** continuing.  Transactions still work if synchronous is off,
** and the database cannot be corrupted if this program
** crashes.  But if the operating system crashes or there is
** an abrupt power failure when synchronous is off, the database
** could be left in an inconsistent and unrecoverable state.
** Synchronous is on by default so database corruption is not
** normally a worry.
*/
int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  BtShared *pBt = p->pBt;
  assert( sqlite3_mutex_held(p->db->mutex) );
  sqlite3BtreeEnter(p);
  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  sqlite3BtreeLeave(p);
  return SQLITE_OK;
}

/*
** Change the way data is synced to disk in order to increase or decrease
** how well the database resists damage due to OS crashes and power
** failures.  Level 1 is the same as asynchronous (no syncs() occur and
** there is a high probability of damage)  Level 2 is the default.  There
** is a very low but non-zero probability of damage.  Level 3 reduces the
** probability of damage to near zero but with a write performance reduction.
*/
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
  BtShared *pBt = p->pBt;
  assert( sqlite3_mutex_held(p->db->mutex) );
  sqlite3BtreeEnter(p);
  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
  sqlite3BtreeLeave(p);
  return SQLITE_OK;
}
#endif

/*
** Return TRUE if the given btree is set to safety level 1.  In other
** words, return TRUE if no sync() occurs on the disk files.
*/
int sqlite3BtreeSyncDisabled(Btree *p){
  BtShared *pBt = p->pBt;
  int rc;
  assert( sqlite3_mutex_held(p->db->mutex) );  
  sqlite3BtreeEnter(p);
  assert( pBt && pBt->pPager );
  rc = sqlite3PagerNosync(pBt->pPager);
  sqlite3BtreeLeave(p);
  return rc;
}

#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
/*
** Change the default pages size and the number of reserved bytes per page.
** Or, if the page size has already been fixed, return SQLITE_READONLY 
** without changing anything.
**
** The page size must be a power of 2 between 512 and 65536.  If the page
** size supplied does not meet this constraint then the page size is not
** changed.
**
** Page sizes are constrained to be a power of two so that the region
** of the database file used for locking (beginning at PENDING_BYTE,
** the first byte past the 1GB boundary, 0x40000000) needs to occur
** at the beginning of a page.
**
** If parameter nReserve is less than zero, then the number of reserved
** bytes per page is left unchanged.
**
** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
** and autovacuum mode can no longer be changed.
*/
int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  int rc = SQLITE_OK;
  BtShared *pBt = p->pBt;
  assert( nReserve>=-1 && nReserve<=255 );
  sqlite3BtreeEnter(p);
  if( pBt->pageSizeFixed ){
    sqlite3BtreeLeave(p);
    return SQLITE_READONLY;
  }
  if( nReserve<0 ){
    nReserve = pBt->pageSize - pBt->usableSize;
  }
  assert( nReserve>=0 && nReserve<=255 );
  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
        ((pageSize-1)&pageSize)==0 ){
    assert( (pageSize & 7)==0 );
    assert( !pBt->pPage1 && !pBt->pCursor );
    pBt->pageSize = (u16)pageSize;
    freeTempSpace(pBt);
  }
  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  pBt->usableSize = pBt->pageSize - (u16)nReserve;
  if( iFix ) pBt->pageSizeFixed = 1;
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** Return the currently defined page size
*/
int sqlite3BtreeGetPageSize(Btree *p){
  return p->pBt->pageSize;
}

/*
** Return the number of bytes of space at the end of every page that
** are intentually left unused.  This is the "reserved" space that is
** sometimes used by extensions.
*/
int sqlite3BtreeGetReserve(Btree *p){
  int n;
  sqlite3BtreeEnter(p);
  n = p->pBt->pageSize - p->pBt->usableSize;
  sqlite3BtreeLeave(p);
  return n;
}

/*
** Set the maximum page count for a database if mxPage is positive.
** No changes are made if mxPage is 0 or negative.
** Regardless of the value of mxPage, return the maximum page count.
*/
int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  int n;
  sqlite3BtreeEnter(p);
  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  sqlite3BtreeLeave(p);
  return n;
}
#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */

/*
** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
** is disabled. The default value for the auto-vacuum property is 
** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
*/
int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
#ifdef SQLITE_OMIT_AUTOVACUUM
  return SQLITE_READONLY;
#else
  BtShared *pBt = p->pBt;
  int rc = SQLITE_OK;
  u8 av = (u8)autoVacuum;

  sqlite3BtreeEnter(p);
  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
    rc = SQLITE_READONLY;
  }else{
    pBt->autoVacuum = av ?1:0;
    pBt->incrVacuum = av==2 ?1:0;
  }
  sqlite3BtreeLeave(p);
  return rc;
#endif
}

/*
** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
** enabled 1 is returned. Otherwise 0.
*/
int sqlite3BtreeGetAutoVacuum(Btree *p){
#ifdef SQLITE_OMIT_AUTOVACUUM
  return BTREE_AUTOVACUUM_NONE;
#else
  int rc;
  sqlite3BtreeEnter(p);
  rc = (
    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
    BTREE_AUTOVACUUM_INCR
  );
  sqlite3BtreeLeave(p);
  return rc;
#endif
}


/*
** Get a reference to pPage1 of the database file.  This will
** also acquire a readlock on that file.
**
** SQLITE_OK is returned on success.  If the file is not a
** well-formed database file, then SQLITE_CORRUPT is returned.
** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
** is returned if we run out of memory. 
*/
static int lockBtree(BtShared *pBt){
  int rc;
  MemPage *pPage1;
  int nPage;

  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( pBt->pPage1==0 );
  rc = sqlite3PagerSharedLock(pBt->pPager);
  if( rc!=SQLITE_OK ) return rc;
  rc = btreeGetPage(pBt, 1, &pPage1, 0);
  if( rc!=SQLITE_OK ) return rc;

  /* Do some checking to help insure the file we opened really is
  ** a valid database file. 
  */
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  if( rc!=SQLITE_OK ){
    goto page1_init_failed;
  }else if( nPage>0 ){
    int pageSize;
    int usableSize;
    u8 *page1 = pPage1->aData;
    rc = SQLITE_NOTADB;
    if( memcmp(page1, zMagicHeader, 16)!=0 ){
      goto page1_init_failed;
    }
    if( page1[18]>1 ){
      pBt->readOnly = 1;
    }
    if( page1[19]>1 ){
      goto page1_init_failed;
    }

    /* The maximum embedded fraction must be exactly 25%.  And the minimum
    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
    ** The original design allowed these amounts to vary, but as of
    ** version 3.6.0, we require them to be fixed.
    */
    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
      goto page1_init_failed;
    }
    pageSize = get2byte(&page1[16]);
    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
    ){
      goto page1_init_failed;
    }
    assert( (pageSize & 7)==0 );
    usableSize = pageSize - page1[20];
    if( pageSize!=pBt->pageSize ){
      /* After reading the first page of the database assuming a page size
      ** of BtShared.pageSize, we have discovered that the page-size is
      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
      ** zero and return SQLITE_OK. The caller will call this function
      ** again with the correct page-size.
      */
      releasePage(pPage1);
      pBt->usableSize = (u16)usableSize;
      pBt->pageSize = (u16)pageSize;
      freeTempSpace(pBt);
      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
                                   pageSize-usableSize);
      return rc;
    }
    if( usableSize<480 ){
      goto page1_init_failed;
    }
    pBt->pageSize = (u16)pageSize;
    pBt->usableSize = (u16)usableSize;
#ifndef SQLITE_OMIT_AUTOVACUUM
    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
#endif
  }

  /* maxLocal is the maximum amount of payload to store locally for
  ** a cell.  Make sure it is small enough so that at least minFanout
  ** cells can will fit on one page.  We assume a 10-byte page header.
  ** Besides the payload, the cell must store:
  **     2-byte pointer to the cell
  **     4-byte child pointer
  **     9-byte nKey value
  **     4-byte nData value
  **     4-byte overflow page pointer
  ** So a cell consists of a 2-byte poiner, a header which is as much as
  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  ** page pointer.
  */
  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
  pBt->maxLeaf = pBt->usableSize - 35;
  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  pBt->pPage1 = pPage1;
  return SQLITE_OK;

page1_init_failed:
  releasePage(pPage1);
  pBt->pPage1 = 0;
  return rc;
}

/*
** If there are no outstanding cursors and we are not in the middle
** of a transaction but there is a read lock on the database, then
** this routine unrefs the first page of the database file which 
** has the effect of releasing the read lock.
**
** If there is a transaction in progress, this routine is a no-op.
*/
static void unlockBtreeIfUnused(BtShared *pBt){
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
    assert( pBt->pPage1->aData );
    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
    assert( pBt->pPage1->aData );
    releasePage(pBt->pPage1);
    pBt->pPage1 = 0;
  }
}

/*
** If pBt points to an empty file then convert that empty file
** into a new empty database by initializing the first page of
** the database.
*/
static int newDatabase(BtShared *pBt){
  MemPage *pP1;
  unsigned char *data;
  int rc;
  int nPage;

  assert( sqlite3_mutex_held(pBt->mutex) );
  /* The database size has already been measured and cached, so failure
  ** is impossible here.  If the original size measurement failed, then
  ** processing aborts before entering this routine. */
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  if( NEVER(rc!=SQLITE_OK) || nPage>0 ){
    return rc;
  }
  pP1 = pBt->pPage1;
  assert( pP1!=0 );
  data = pP1->aData;
  rc = sqlite3PagerWrite(pP1->pDbPage);
  if( rc ) return rc;
  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  assert( sizeof(zMagicHeader)==16 );
  put2byte(&data[16], pBt->pageSize);
  data[18] = 1;
  data[19] = 1;
  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  data[21] = 64;
  data[22] = 32;
  data[23] = 32;
  memset(&data[24], 0, 100-24);
  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  pBt->pageSizeFixed = 1;
#ifndef SQLITE_OMIT_AUTOVACUUM
  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  put4byte(&data[36 + 4*4], pBt->autoVacuum);
  put4byte(&data[36 + 7*4], pBt->incrVacuum);
#endif
  return SQLITE_OK;
}

/*
** Attempt to start a new transaction. A write-transaction
** is started if the second argument is nonzero, otherwise a read-
** transaction.  If the second argument is 2 or more and exclusive
** transaction is started, meaning that no other process is allowed
** to access the database.  A preexisting transaction may not be
** upgraded to exclusive by calling this routine a second time - the
** exclusivity flag only works for a new transaction.
**
** A write-transaction must be started before attempting any 
** changes to the database.  None of the following routines 
** will work unless a transaction is started first:
**
**      sqlite3BtreeCreateTable()
**      sqlite3BtreeCreateIndex()
**      sqlite3BtreeClearTable()
**      sqlite3BtreeDropTable()
**      sqlite3BtreeInsert()
**      sqlite3BtreeDelete()
**      sqlite3BtreeUpdateMeta()
**
** If an initial attempt to acquire the lock fails because of lock contention
** and the database was previously unlocked, then invoke the busy handler
** if there is one.  But if there was previously a read-lock, do not
** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
** returned when there is already a read-lock in order to avoid a deadlock.
**
** Suppose there are two processes A and B.  A has a read lock and B has
** a reserved lock.  B tries to promote to exclusive but is blocked because
** of A's read lock.  A tries to promote to reserved but is blocked by B.
** One or the other of the two processes must give way or there can be
** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
** when A already has a read lock, we encourage A to give up and let B
** proceed.
*/
int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  sqlite3 *pBlock = 0;
  BtShared *pBt = p->pBt;
  int rc = SQLITE_OK;

  sqlite3BtreeEnter(p);
  btreeIntegrity(p);

  /* If the btree is already in a write-transaction, or it
  ** is already in a read-transaction and a read-transaction
  ** is requested, this is a no-op.
  */
  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
    goto trans_begun;
  }

  /* Write transactions are not possible on a read-only database */
  if( pBt->readOnly && wrflag ){
    rc = SQLITE_READONLY;
    goto trans_begun;
  }

#ifndef SQLITE_OMIT_SHARED_CACHE
  /* If another database handle has already opened a write transaction 
  ** on this shared-btree structure and a second write transaction is
  ** requested, return SQLITE_LOCKED.
  */
  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
    pBlock = pBt->pWriter->db;
  }else if( wrflag>1 ){
    BtLock *pIter;
    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
      if( pIter->pBtree!=p ){
        pBlock = pIter->pBtree->db;
        break;
      }
    }
  }
  if( pBlock ){
    sqlite3ConnectionBlocked(p->db, pBlock);
    rc = SQLITE_LOCKED_SHAREDCACHE;
    goto trans_begun;
  }
#endif

  /* Any read-only or read-write transaction implies a read-lock on 
  ** page 1. So if some other shared-cache client already has a write-lock 
  ** on page 1, the transaction cannot be opened. */
  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  if( SQLITE_OK!=rc ) goto trans_begun;

  do {
    /* Call lockBtree() until either pBt->pPage1 is populated or
    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
    ** reading page 1 it discovers that the page-size of the database 
    ** file is not pBt->pageSize. In this case lockBtree() will update
    ** pBt->pageSize to the page-size of the file on disk.
    */
    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );

    if( rc==SQLITE_OK && wrflag ){
      if( pBt->readOnly ){
        rc = SQLITE_READONLY;
      }else{
        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
        if( rc==SQLITE_OK ){
          rc = newDatabase(pBt);
        }
      }
    }
  
    if( rc!=SQLITE_OK ){
      unlockBtreeIfUnused(pBt);
    }
  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
          btreeInvokeBusyHandler(pBt) );

  if( rc==SQLITE_OK ){
    if( p->inTrans==TRANS_NONE ){
      pBt->nTransaction++;
#ifndef SQLITE_OMIT_SHARED_CACHE
      if( p->sharable ){
	assert( p->lock.pBtree==p && p->lock.iTable==1 );
        p->lock.eLock = READ_LOCK;
        p->lock.pNext = pBt->pLock;
        pBt->pLock = &p->lock;
      }
#endif
    }
    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
    if( p->inTrans>pBt->inTransaction ){
      pBt->inTransaction = p->inTrans;
    }
#ifndef SQLITE_OMIT_SHARED_CACHE
    if( wrflag ){
      assert( !pBt->pWriter );
      pBt->pWriter = p;
      pBt->isExclusive = (u8)(wrflag>1);
    }
#endif
  }


trans_begun:
  if( rc==SQLITE_OK && wrflag ){
    /* This call makes sure that the pager has the correct number of
    ** open savepoints. If the second parameter is greater than 0 and
    ** the sub-journal is not already open, then it will be opened here.
    */
    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  }

  btreeIntegrity(p);
  sqlite3BtreeLeave(p);
  return rc;
}

#ifndef SQLITE_OMIT_AUTOVACUUM

/*
** Set the pointer-map entries for all children of page pPage. Also, if
** pPage contains cells that point to overflow pages, set the pointer
** map entries for the overflow pages as well.
*/
static int setChildPtrmaps(MemPage *pPage){
  int i;                             /* Counter variable */
  int nCell;                         /* Number of cells in page pPage */
  int rc;                            /* Return code */
  BtShared *pBt = pPage->pBt;
  u8 isInitOrig = pPage->isInit;
  Pgno pgno = pPage->pgno;

  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  rc = btreeInitPage(pPage);
  if( rc!=SQLITE_OK ){
    goto set_child_ptrmaps_out;
  }
  nCell = pPage->nCell;

  for(i=0; i<nCell; i++){
    u8 *pCell = findCell(pPage, i);

    ptrmapPutOvflPtr(pPage, pCell, &rc);

    if( !pPage->leaf ){
      Pgno childPgno = get4byte(pCell);
      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
    }
  }

  if( !pPage->leaf ){
    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  }

set_child_ptrmaps_out:
  pPage->isInit = isInitOrig;
  return rc;
}

/*
** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
** that it points to iTo. Parameter eType describes the type of pointer to
** be modified, as  follows:
**
** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
**                   page of pPage.
**
** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
**                   page pointed to by one of the cells on pPage.
**
** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
**                   overflow page in the list.
*/
static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  if( eType==PTRMAP_OVERFLOW2 ){
    /* The pointer is always the first 4 bytes of the page in this case.  */
    if( get4byte(pPage->aData)!=iFrom ){
      return SQLITE_CORRUPT_BKPT;
    }
    put4byte(pPage->aData, iTo);
  }else{
    u8 isInitOrig = pPage->isInit;
    int i;
    int nCell;

    btreeInitPage(pPage);
    nCell = pPage->nCell;

    for(i=0; i<nCell; i++){
      u8 *pCell = findCell(pPage, i);
      if( eType==PTRMAP_OVERFLOW1 ){
        CellInfo info;
        btreeParseCellPtr(pPage, pCell, &info);
        if( info.iOverflow ){
          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
            put4byte(&pCell[info.iOverflow], iTo);
            break;
          }
        }
      }else{
        if( get4byte(pCell)==iFrom ){
          put4byte(pCell, iTo);
          break;
        }
      }
    }
  
    if( i==nCell ){
      if( eType!=PTRMAP_BTREE || 
          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
        return SQLITE_CORRUPT_BKPT;
      }
      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
    }

    pPage->isInit = isInitOrig;
  }
  return SQLITE_OK;
}


/*
** Move the open database page pDbPage to location iFreePage in the 
** database. The pDbPage reference remains valid.
**
** The isCommit flag indicates that there is no need to remember that
** the journal needs to be sync()ed before database page pDbPage->pgno 
** can be written to. The caller has already promised not to write to that
** page.
*/
static int relocatePage(
  BtShared *pBt,           /* Btree */
  MemPage *pDbPage,        /* Open page to move */
  u8 eType,                /* Pointer map 'type' entry for pDbPage */
  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
  Pgno iFreePage,          /* The location to move pDbPage to */
  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
){
  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
  Pgno iDbPage = pDbPage->pgno;
  Pager *pPager = pBt->pPager;
  int rc;

  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( pDbPage->pBt==pBt );

  /* Move page iDbPage from its current location to page number iFreePage */
  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
      iDbPage, iFreePage, iPtrPage, eType));
  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pDbPage->pgno = iFreePage;

  /* If pDbPage was a btree-page, then it may have child pages and/or cells
  ** that point to overflow pages. The pointer map entries for all these
  ** pages need to be changed.
  **
  ** If pDbPage is an overflow page, then the first 4 bytes may store a
  ** pointer to a subsequent overflow page. If this is the case, then
  ** the pointer map needs to be updated for the subsequent overflow page.
  */
  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
    rc = setChildPtrmaps(pDbPage);
    if( rc!=SQLITE_OK ){
      return rc;
    }
  }else{
    Pgno nextOvfl = get4byte(pDbPage->aData);
    if( nextOvfl!=0 ){
      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
      if( rc!=SQLITE_OK ){
        return rc;
      }
    }
  }

  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  ** that it points at iFreePage. Also fix the pointer map entry for
  ** iPtrPage.
  */
  if( eType!=PTRMAP_ROOTPAGE ){
    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
    if( rc!=SQLITE_OK ){
      releasePage(pPtrPage);
      return rc;
    }
    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
    releasePage(pPtrPage);
    if( rc==SQLITE_OK ){
      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
    }
  }
  return rc;
}

/* Forward declaration required by incrVacuumStep(). */
static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);

/*
** Perform a single step of an incremental-vacuum. If successful,
** return SQLITE_OK. If there is no work to do (and therefore no
** point in calling this function again), return SQLITE_DONE.
**
** More specificly, this function attempts to re-organize the 
** database so that the last page of the file currently in use
** is no longer in use.
**
** If the nFin parameter is non-zero, this function assumes
** that the caller will keep calling incrVacuumStep() until
** it returns SQLITE_DONE or an error, and that nFin is the
** number of pages the database file will contain after this 
** process is complete.  If nFin is zero, it is assumed that
** incrVacuumStep() will be called a finite amount of times
** which may or may not empty the freelist.  A full autovacuum
** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
*/
static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
  Pgno nFreeList;           /* Number of pages still on the free-list */

  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( iLastPg>nFin );

  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
    int rc;
    u8 eType;
    Pgno iPtrPage;

    nFreeList = get4byte(&pBt->pPage1->aData[36]);
    if( nFreeList==0 ){
      return SQLITE_DONE;
    }

    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    if( eType==PTRMAP_ROOTPAGE ){
      return SQLITE_CORRUPT_BKPT;
    }

    if( eType==PTRMAP_FREEPAGE ){
      if( nFin==0 ){
        /* Remove the page from the files free-list. This is not required
        ** if nFin is non-zero. In that case, the free-list will be
        ** truncated to zero after this function returns, so it doesn't 
        ** matter if it still contains some garbage entries.
        */
        Pgno iFreePg;
        MemPage *pFreePg;
        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
        if( rc!=SQLITE_OK ){
          return rc;
        }
        assert( iFreePg==iLastPg );
        releasePage(pFreePg);
      }
    } else {
      Pgno iFreePg;             /* Index of free page to move pLastPg to */
      MemPage *pLastPg;

      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
      if( rc!=SQLITE_OK ){
        return rc;
      }

      /* If nFin is zero, this loop runs exactly once and page pLastPg
      ** is swapped with the first free page pulled off the free list.
      **
      ** On the other hand, if nFin is greater than zero, then keep
      ** looping until a free-page located within the first nFin pages
      ** of the file is found.
      */
      do {
        MemPage *pFreePg;
        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
        if( rc!=SQLITE_OK ){
          releasePage(pLastPg);
          return rc;
        }
        releasePage(pFreePg);
      }while( nFin!=0 && iFreePg>nFin );
      assert( iFreePg<iLastPg );
      
      rc = sqlite3PagerWrite(pLastPg->pDbPage);
      if( rc==SQLITE_OK ){
        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
      }
      releasePage(pLastPg);
      if( rc!=SQLITE_OK ){
        return rc;
      }
    }
  }

  if( nFin==0 ){
    iLastPg--;
    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
        MemPage *pPg;
        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
        if( rc!=SQLITE_OK ){
          return rc;
        }
        rc = sqlite3PagerWrite(pPg->pDbPage);
        releasePage(pPg);
        if( rc!=SQLITE_OK ){
          return rc;
        }
      }
      iLastPg--;
    }
    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
  }
  return SQLITE_OK;
}

/*
** A write-transaction must be opened before calling this function.
** It performs a single unit of work towards an incremental vacuum.
**
** If the incremental vacuum is finished after this function has run,
** SQLITE_DONE is returned. If it is not finished, but no error occurred,
** SQLITE_OK is returned. Otherwise an SQLite error code. 
*/
int sqlite3BtreeIncrVacuum(Btree *p){
  int rc;
  BtShared *pBt = p->pBt;

  sqlite3BtreeEnter(p);
  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  if( !pBt->autoVacuum ){
    rc = SQLITE_DONE;
  }else{
    invalidateAllOverflowCache(pBt);
    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
  }
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** This routine is called prior to sqlite3PagerCommit when a transaction
** is commited for an auto-vacuum database.
**
** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
** the database file should be truncated to during the commit process. 
** i.e. the database has been reorganized so that only the first *pnTrunc
** pages are in use.
*/
static int autoVacuumCommit(BtShared *pBt){
  int rc = SQLITE_OK;
  Pager *pPager = pBt->pPager;
  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );

  assert( sqlite3_mutex_held(pBt->mutex) );
  invalidateAllOverflowCache(pBt);
  assert(pBt->autoVacuum);
  if( !pBt->incrVacuum ){
    Pgno nFin;         /* Number of pages in database after autovacuuming */
    Pgno nFree;        /* Number of pages on the freelist initially */
    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
    Pgno iFree;        /* The next page to be freed */
    int nEntry;        /* Number of entries on one ptrmap page */
    Pgno nOrig;        /* Database size before freeing */

    nOrig = pagerPagecount(pBt);
    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
      /* It is not possible to create a database for which the final page
      ** is either a pointer-map page or the pending-byte page. If one
      ** is encountered, this indicates corruption.
      */
      return SQLITE_CORRUPT_BKPT;
    }

    nFree = get4byte(&pBt->pPage1->aData[36]);
    nEntry = pBt->usableSize/5;
    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
    nFin = nOrig - nFree - nPtrmap;
    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
      nFin--;
    }
    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
      nFin--;
    }
    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;

    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
      rc = incrVacuumStep(pBt, nFin, iFree);
    }
    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
      rc = SQLITE_OK;
      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
      put4byte(&pBt->pPage1->aData[32], 0);
      put4byte(&pBt->pPage1->aData[36], 0);
      sqlite3PagerTruncateImage(pBt->pPager, nFin);
    }
    if( rc!=SQLITE_OK ){
      sqlite3PagerRollback(pPager);
    }
  }

  assert( nRef==sqlite3PagerRefcount(pPager) );
  return rc;
}

#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
# define setChildPtrmaps(x) SQLITE_OK
#endif

/*
** This routine does the first phase of a two-phase commit.  This routine
** causes a rollback journal to be created (if it does not already exist)
** and populated with enough information so that if a power loss occurs
** the database can be restored to its original state by playing back
** the journal.  Then the contents of the journal are flushed out to
** the disk.  After the journal is safely on oxide, the changes to the
** database are written into the database file and flushed to oxide.
** At the end of this call, the rollback journal still exists on the
** disk and we are still holding all locks, so the transaction has not
** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
** commit process.
**
** This call is a no-op if no write-transaction is currently active on pBt.
**
** Otherwise, sync the database file for the btree pBt. zMaster points to
** the name of a master journal file that should be written into the
** individual journal file, or is NULL, indicating no master journal file 
** (single database transaction).
**
** When this is called, the master journal should already have been
** created, populated with this journal pointer and synced to disk.
**
** Once this is routine has returned, the only thing required to commit
** the write-transaction for this database file is to delete the journal.
*/
int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  int rc = SQLITE_OK;
  if( p->inTrans==TRANS_WRITE ){
    BtShared *pBt = p->pBt;
    sqlite3BtreeEnter(p);
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum ){
      rc = autoVacuumCommit(pBt);
      if( rc!=SQLITE_OK ){
        sqlite3BtreeLeave(p);
        return rc;
      }
    }
#endif
    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
    sqlite3BtreeLeave(p);
  }
  return rc;
}

/*
** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
** at the conclusion of a transaction.
*/
static void btreeEndTransaction(Btree *p){
  BtShared *pBt = p->pBt;
  assert( sqlite3BtreeHoldsMutex(p) );

  btreeClearHasContent(pBt);
  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
    /* If there are other active statements that belong to this database
    ** handle, downgrade to a read-only transaction. The other statements
    ** may still be reading from the database.  */
    downgradeAllSharedCacheTableLocks(p);
    p->inTrans = TRANS_READ;
  }else{
    /* If the handle had any kind of transaction open, decrement the 
    ** transaction count of the shared btree. If the transaction count 
    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
    ** call below will unlock the pager.  */
    if( p->inTrans!=TRANS_NONE ){
      clearAllSharedCacheTableLocks(p);
      pBt->nTransaction--;
      if( 0==pBt->nTransaction ){
        pBt->inTransaction = TRANS_NONE;
      }
    }

    /* Set the current transaction state to TRANS_NONE and unlock the 
    ** pager if this call closed the only read or write transaction.  */
    p->inTrans = TRANS_NONE;
    unlockBtreeIfUnused(pBt);
  }

  btreeIntegrity(p);
}

/*
** Commit the transaction currently in progress.
**
** This routine implements the second phase of a 2-phase commit.  The
** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
** routine did all the work of writing information out to disk and flushing the
** contents so that they are written onto the disk platter.  All this
** routine has to do is delete or truncate or zero the header in the
** the rollback journal (which causes the transaction to commit) and
** drop locks.
**
** This will release the write lock on the database file.  If there
** are no active cursors, it also releases the read lock.
*/
int sqlite3BtreeCommitPhaseTwo(Btree *p){
  BtShared *pBt = p->pBt;

  sqlite3BtreeEnter(p);
  btreeIntegrity(p);

  /* If the handle has a write-transaction open, commit the shared-btrees 
  ** transaction and set the shared state to TRANS_READ.
  */
  if( p->inTrans==TRANS_WRITE ){
    int rc;
    assert( pBt->inTransaction==TRANS_WRITE );
    assert( pBt->nTransaction>0 );
    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
    if( rc!=SQLITE_OK ){
      sqlite3BtreeLeave(p);
      return rc;
    }
    pBt->inTransaction = TRANS_READ;
  }

  btreeEndTransaction(p);
  sqlite3BtreeLeave(p);
  return SQLITE_OK;
}

/*
** Do both phases of a commit.
*/
int sqlite3BtreeCommit(Btree *p){
  int rc;
  sqlite3BtreeEnter(p);
  rc = sqlite3BtreeCommitPhaseOne(p, 0);
  if( rc==SQLITE_OK ){
    rc = sqlite3BtreeCommitPhaseTwo(p);
  }
  sqlite3BtreeLeave(p);
  return rc;
}

#ifndef NDEBUG
/*
** Return the number of write-cursors open on this handle. This is for use
** in assert() expressions, so it is only compiled if NDEBUG is not
** defined.
**
** For the purposes of this routine, a write-cursor is any cursor that
** is capable of writing to the databse.  That means the cursor was
** originally opened for writing and the cursor has not be disabled
** by having its state changed to CURSOR_FAULT.
*/
static int countWriteCursors(BtShared *pBt){
  BtCursor *pCur;
  int r = 0;
  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
  }
  return r;
}
#endif

/*
** This routine sets the state to CURSOR_FAULT and the error
** code to errCode for every cursor on BtShared that pBtree
** references.
**
** Every cursor is tripped, including cursors that belong
** to other database connections that happen to be sharing
** the cache with pBtree.
**
** This routine gets called when a rollback occurs.
** All cursors using the same cache must be tripped
** to prevent them from trying to use the btree after
** the rollback.  The rollback may have deleted tables
** or moved root pages, so it is not sufficient to
** save the state of the cursor.  The cursor must be
** invalidated.
*/
void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  BtCursor *p;
  sqlite3BtreeEnter(pBtree);
  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
    int i;
    sqlite3BtreeClearCursor(p);
    p->eState = CURSOR_FAULT;
    p->skipNext = errCode;
    for(i=0; i<=p->iPage; i++){
      releasePage(p->apPage[i]);
      p->apPage[i] = 0;
    }
  }
  sqlite3BtreeLeave(pBtree);
}

/*
** Rollback the transaction in progress.  All cursors will be
** invalided by this operation.  Any attempt to use a cursor
** that was open at the beginning of this operation will result
** in an error.
**
** This will release the write lock on the database file.  If there
** are no active cursors, it also releases the read lock.
*/
int sqlite3BtreeRollback(Btree *p){
  int rc;
  BtShared *pBt = p->pBt;
  MemPage *pPage1;

  sqlite3BtreeEnter(p);
  rc = saveAllCursors(pBt, 0, 0);
#ifndef SQLITE_OMIT_SHARED_CACHE
  if( rc!=SQLITE_OK ){
    /* This is a horrible situation. An IO or malloc() error occurred whilst
    ** trying to save cursor positions. If this is an automatic rollback (as
    ** the result of a constraint, malloc() failure or IO error) then 
    ** the cache may be internally inconsistent (not contain valid trees) so
    ** we cannot simply return the error to the caller. Instead, abort 
    ** all queries that may be using any of the cursors that failed to save.
    */
    sqlite3BtreeTripAllCursors(p, rc);
  }
#endif
  btreeIntegrity(p);

  if( p->inTrans==TRANS_WRITE ){
    int rc2;

    assert( TRANS_WRITE==pBt->inTransaction );
    rc2 = sqlite3PagerRollback(pBt->pPager);
    if( rc2!=SQLITE_OK ){
      rc = rc2;
    }

    /* The rollback may have destroyed the pPage1->aData value.  So
    ** call btreeGetPage() on page 1 again to make
    ** sure pPage1->aData is set correctly. */
    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
      releasePage(pPage1);
    }
    assert( countWriteCursors(pBt)==0 );
    pBt->inTransaction = TRANS_READ;
  }

  btreeEndTransaction(p);
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** Start a statement subtransaction. The subtransaction can can be rolled
** back independently of the main transaction. You must start a transaction 
** before starting a subtransaction. The subtransaction is ended automatically 
** if the main transaction commits or rolls back.
**
** Statement subtransactions are used around individual SQL statements
** that are contained within a BEGIN...COMMIT block.  If a constraint
** error occurs within the statement, the effect of that one statement
** can be rolled back without having to rollback the entire transaction.
**
** A statement sub-transaction is implemented as an anonymous savepoint. The
** value passed as the second parameter is the total number of savepoints,
** including the new anonymous savepoint, open on the B-Tree. i.e. if there
** are no active savepoints and no other statement-transactions open,
** iStatement is 1. This anonymous savepoint can be released or rolled back
** using the sqlite3BtreeSavepoint() function.
*/
int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  int rc;
  BtShared *pBt = p->pBt;
  sqlite3BtreeEnter(p);
  assert( p->inTrans==TRANS_WRITE );
  assert( pBt->readOnly==0 );
  assert( iStatement>0 );
  assert( iStatement>p->db->nSavepoint );
  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
    rc = SQLITE_INTERNAL;
  }else{
    assert( pBt->inTransaction==TRANS_WRITE );
    /* At the pager level, a statement transaction is a savepoint with
    ** an index greater than all savepoints created explicitly using
    ** SQL statements. It is illegal to open, release or rollback any
    ** such savepoints while the statement transaction savepoint is active.
    */
    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  }
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
** or SAVEPOINT_RELEASE. This function either releases or rolls back the
** savepoint identified by parameter iSavepoint, depending on the value 
** of op.
**
** Normally, iSavepoint is greater than or equal to zero. However, if op is
** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
** contents of the entire transaction are rolled back. This is different
** from a normal transaction rollback, as no locks are released and the
** transaction remains open.
*/
int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  int rc = SQLITE_OK;
  if( p && p->inTrans==TRANS_WRITE ){
    BtShared *pBt = p->pBt;
    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
    sqlite3BtreeEnter(p);
    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
    if( rc==SQLITE_OK ){
      rc = newDatabase(pBt);
    }
    sqlite3BtreeLeave(p);
  }
  return rc;
}

/*
** Create a new cursor for the BTree whose root is on the page
** iTable. If a read-only cursor is requested, it is assumed that
** the caller already has at least a read-only transaction open
** on the database already. If a write-cursor is requested, then
** the caller is assumed to have an open write transaction.
**
** If wrFlag==0, then the cursor can only be used for reading.
** If wrFlag==1, then the cursor can be used for reading or for
** writing if other conditions for writing are also met.  These
** are the conditions that must be met in order for writing to
** be allowed:
**
** 1:  The cursor must have been opened with wrFlag==1
**
** 2:  Other database connections that share the same pager cache
**     but which are not in the READ_UNCOMMITTED state may not have
**     cursors open with wrFlag==0 on the same table.  Otherwise
**     the changes made by this write cursor would be visible to
**     the read cursors in the other database connection.
**
** 3:  The database must be writable (not on read-only media)
**
** 4:  There must be an active transaction.
**
** No checking is done to make sure that page iTable really is the
** root page of a b-tree.  If it is not, then the cursor acquired
** will not work correctly.
**
** It is assumed that the sqlite3BtreeCursorSize() bytes of memory 
** pointed to by pCur have been zeroed by the caller.
*/
static int btreeCursor(
  Btree *p,                              /* The btree */
  int iTable,                            /* Root page of table to open */
  int wrFlag,                            /* 1 to write. 0 read-only */
  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
  BtCursor *pCur                         /* Space for new cursor */
){
  BtShared *pBt = p->pBt;                /* Shared b-tree handle */

  assert( sqlite3BtreeHoldsMutex(p) );
  assert( wrFlag==0 || wrFlag==1 );

  /* The following assert statements verify that if this is a sharable 
  ** b-tree database, the connection is holding the required table locks, 
  ** and that no other connection has any open cursor that conflicts with 
  ** this lock.  */
  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );

  /* Assert that the caller has opened the required transaction. */
  assert( p->inTrans>TRANS_NONE );
  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  assert( pBt->pPage1 && pBt->pPage1->aData );

  if( NEVER(wrFlag && pBt->readOnly) ){
    return SQLITE_READONLY;
  }
  if( iTable==1 && pagerPagecount(pBt)==0 ){
    return SQLITE_EMPTY;
  }

  /* Now that no other errors can occur, finish filling in the BtCursor
  ** variables and link the cursor into the BtShared list.  */
  pCur->pgnoRoot = (Pgno)iTable;
  pCur->iPage = -1;
  pCur->pKeyInfo = pKeyInfo;
  pCur->pBtree = p;
  pCur->pBt = pBt;
  pCur->wrFlag = (u8)wrFlag;
  pCur->pNext = pBt->pCursor;
  if( pCur->pNext ){
    pCur->pNext->pPrev = pCur;
  }
  pBt->pCursor = pCur;
  pCur->eState = CURSOR_INVALID;
  pCur->cachedRowid = 0;
  return SQLITE_OK;
}
int sqlite3BtreeCursor(
  Btree *p,                                   /* The btree */
  int iTable,                                 /* Root page of table to open */
  int wrFlag,                                 /* 1 to write. 0 read-only */
  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
  BtCursor *pCur                              /* Write new cursor here */
){
  int rc;
  sqlite3BtreeEnter(p);
  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** Return the size of a BtCursor object in bytes.
**
** This interfaces is needed so that users of cursors can preallocate
** sufficient storage to hold a cursor.  The BtCursor object is opaque
** to users so they cannot do the sizeof() themselves - they must call
** this routine.
*/
int sqlite3BtreeCursorSize(void){
  return sizeof(BtCursor);
}

/*
** Set the cached rowid value of every cursor in the same database file
** as pCur and having the same root page number as pCur.  The value is
** set to iRowid.
**
** Only positive rowid values are considered valid for this cache.
** The cache is initialized to zero, indicating an invalid cache.
** A btree will work fine with zero or negative rowids.  We just cannot
** cache zero or negative rowids, which means tables that use zero or
** negative rowids might run a little slower.  But in practice, zero
** or negative rowids are very uncommon so this should not be a problem.
*/
void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  BtCursor *p;
  for(p=pCur->pBt->pCursor; p; p=p->pNext){
    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  }
  assert( pCur->cachedRowid==iRowid );
}

/*
** Return the cached rowid for the given cursor.  A negative or zero
** return value indicates that the rowid cache is invalid and should be
** ignored.  If the rowid cache has never before been set, then a
** zero is returned.
*/
sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  return pCur->cachedRowid;
}

/*
** Close a cursor.  The read lock on the database file is released
** when the last cursor is closed.
*/
int sqlite3BtreeCloseCursor(BtCursor *pCur){
  Btree *pBtree = pCur->pBtree;
  if( pBtree ){
    int i;
    BtShared *pBt = pCur->pBt;
    sqlite3BtreeEnter(pBtree);
    sqlite3BtreeClearCursor(pCur);
    if( pCur->pPrev ){
      pCur->pPrev->pNext = pCur->pNext;
    }else{
      pBt->pCursor = pCur->pNext;
    }
    if( pCur->pNext ){
      pCur->pNext->pPrev = pCur->pPrev;
    }
    for(i=0; i<=pCur->iPage; i++){
      releasePage(pCur->apPage[i]);
    }
    unlockBtreeIfUnused(pBt);
    invalidateOverflowCache(pCur);
    /* sqlite3_free(pCur); */
    sqlite3BtreeLeave(pBtree);
  }
  return SQLITE_OK;
}

/*
** Make sure the BtCursor* given in the argument has a valid
** BtCursor.info structure.  If it is not already valid, call
** btreeParseCell() to fill it in.
**
** BtCursor.info is a cache of the information in the current cell.
** Using this cache reduces the number of calls to btreeParseCell().
**
** 2007-06-25:  There is a bug in some versions of MSVC that cause the
** compiler to crash when getCellInfo() is implemented as a macro.
** But there is a measureable speed advantage to using the macro on gcc
** (when less compiler optimizations like -Os or -O0 are used and the
** compiler is not doing agressive inlining.)  So we use a real function
** for MSVC and a macro for everything else.  Ticket #2457.
*/
#ifndef NDEBUG
  static void assertCellInfo(BtCursor *pCur){
    CellInfo info;
    int iPage = pCur->iPage;
    memset(&info, 0, sizeof(info));
    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  }
#else
  #define assertCellInfo(x)
#endif
#ifdef _MSC_VER
  /* Use a real function in MSVC to work around bugs in that compiler. */
  static void getCellInfo(BtCursor *pCur){
    if( pCur->info.nSize==0 ){
      int iPage = pCur->iPage;
      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
      pCur->validNKey = 1;
    }else{
      assertCellInfo(pCur);
    }
  }
#else /* if not _MSC_VER */
  /* Use a macro in all other compilers so that the function is inlined */
#define getCellInfo(pCur)                                                      \
  if( pCur->info.nSize==0 ){                                                   \
    int iPage = pCur->iPage;                                                   \
    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
    pCur->validNKey = 1;                                                       \
  }else{                                                                       \
    assertCellInfo(pCur);                                                      \
  }
#endif /* _MSC_VER */

#ifndef NDEBUG  /* The next routine used only within assert() statements */
/*
** Return true if the given BtCursor is valid.  A valid cursor is one
** that is currently pointing to a row in a (non-empty) table.
** This is a verification routine is used only within assert() statements.
*/
int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  return pCur && pCur->eState==CURSOR_VALID;
}
#endif /* NDEBUG */

/*
** Set *pSize to the size of the buffer needed to hold the value of
** the key for the current entry.  If the cursor is not pointing
** to a valid entry, *pSize is set to 0. 
**
** For a table with the INTKEY flag set, this routine returns the key
** itself, not the number of bytes in the key.
**
** The caller must position the cursor prior to invoking this routine.
** 
** This routine cannot fail.  It always returns SQLITE_OK.  
*/
int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  if( pCur->eState!=CURSOR_VALID ){
    *pSize = 0;
  }else{
    getCellInfo(pCur);
    *pSize = pCur->info.nKey;
  }
  return SQLITE_OK;
}

/*
** Set *pSize to the number of bytes of data in the entry the
** cursor currently points to.
**
** The caller must guarantee that the cursor is pointing to a non-NULL
** valid entry.  In other words, the calling procedure must guarantee
** that the cursor has Cursor.eState==CURSOR_VALID.
**
** Failure is not possible.  This function always returns SQLITE_OK.
** It might just as well be a procedure (returning void) but we continue
** to return an integer result code for historical reasons.
*/
int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_VALID );
  getCellInfo(pCur);
  *pSize = pCur->info.nData;
  return SQLITE_OK;
}

/*
** Given the page number of an overflow page in the database (parameter
** ovfl), this function finds the page number of the next page in the 
** linked list of overflow pages. If possible, it uses the auto-vacuum
** pointer-map data instead of reading the content of page ovfl to do so. 
**
** If an error occurs an SQLite error code is returned. Otherwise:
**
** The page number of the next overflow page in the linked list is 
** written to *pPgnoNext. If page ovfl is the last page in its linked 
** list, *pPgnoNext is set to zero. 
**
** If ppPage is not NULL, and a reference to the MemPage object corresponding
** to page number pOvfl was obtained, then *ppPage is set to point to that
** reference. It is the responsibility of the caller to call releasePage()
** on *ppPage to free the reference. In no reference was obtained (because
** the pointer-map was used to obtain the value for *pPgnoNext), then
** *ppPage is set to zero.
*/
static int getOverflowPage(
  BtShared *pBt,               /* The database file */
  Pgno ovfl,                   /* Current overflow page number */
  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
  Pgno *pPgnoNext              /* OUT: Next overflow page number */
){
  Pgno next = 0;
  MemPage *pPage = 0;
  int rc = SQLITE_OK;

  assert( sqlite3_mutex_held(pBt->mutex) );
  assert(pPgnoNext);

#ifndef SQLITE_OMIT_AUTOVACUUM
  /* Try to find the next page in the overflow list using the
  ** autovacuum pointer-map pages. Guess that the next page in 
  ** the overflow list is page number (ovfl+1). If that guess turns 
  ** out to be wrong, fall back to loading the data of page 
  ** number ovfl to determine the next page number.
  */
  if( pBt->autoVacuum ){
    Pgno pgno;
    Pgno iGuess = ovfl+1;
    u8 eType;

    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
      iGuess++;
    }

    if( iGuess<=pagerPagecount(pBt) ){
      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
        next = iGuess;
        rc = SQLITE_DONE;
      }
    }
  }
#endif

  assert( next==0 || rc==SQLITE_DONE );
  if( rc==SQLITE_OK ){
    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
    assert( rc==SQLITE_OK || pPage==0 );
    if( rc==SQLITE_OK ){
      next = get4byte(pPage->aData);
    }
  }

  *pPgnoNext = next;
  if( ppPage ){
    *ppPage = pPage;
  }else{
    releasePage(pPage);
  }
  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
}

/*
** Copy data from a buffer to a page, or from a page to a buffer.
**
** pPayload is a pointer to data stored on database page pDbPage.
** If argument eOp is false, then nByte bytes of data are copied
** from pPayload to the buffer pointed at by pBuf. If eOp is true,
** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
** of data are copied from the buffer pBuf to pPayload.
**
** SQLITE_OK is returned on success, otherwise an error code.
*/
static int copyPayload(
  void *pPayload,           /* Pointer to page data */
  void *pBuf,               /* Pointer to buffer */
  int nByte,                /* Number of bytes to copy */
  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
  DbPage *pDbPage           /* Page containing pPayload */
){
  if( eOp ){
    /* Copy data from buffer to page (a write operation) */
    int rc = sqlite3PagerWrite(pDbPage);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    memcpy(pPayload, pBuf, nByte);
  }else{
    /* Copy data from page to buffer (a read operation) */
    memcpy(pBuf, pPayload, nByte);
  }
  return SQLITE_OK;
}

/*
** This function is used to read or overwrite payload information
** for the entry that the pCur cursor is pointing to. If the eOp
** parameter is 0, this is a read operation (data copied into
** buffer pBuf). If it is non-zero, a write (data copied from
** buffer pBuf).
**
** A total of "amt" bytes are read or written beginning at "offset".
** Data is read to or from the buffer pBuf.
**
** The content being read or written might appear on the main page
** or be scattered out on multiple overflow pages.
**
** If the BtCursor.isIncrblobHandle flag is set, and the current
** cursor entry uses one or more overflow pages, this function
** allocates space for and lazily popluates the overflow page-list 
** cache array (BtCursor.aOverflow). Subsequent calls use this
** cache to make seeking to the supplied offset more efficient.
**
** Once an overflow page-list cache has been allocated, it may be
** invalidated if some other cursor writes to the same table, or if
** the cursor is moved to a different row. Additionally, in auto-vacuum
** mode, the following events may invalidate an overflow page-list cache.
**
**   * An incremental vacuum,
**   * A commit in auto_vacuum="full" mode,
**   * Creating a table (may require moving an overflow page).
*/
static int accessPayload(
  BtCursor *pCur,      /* Cursor pointing to entry to read from */
  u32 offset,          /* Begin reading this far into payload */
  u32 amt,             /* Read this many bytes */
  unsigned char *pBuf, /* Write the bytes into this buffer */ 
  int eOp              /* zero to read. non-zero to write. */
){
  unsigned char *aPayload;
  int rc = SQLITE_OK;
  u32 nKey;
  int iIdx = 0;
  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */

  assert( pPage );
  assert( pCur->eState==CURSOR_VALID );
  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  assert( cursorHoldsMutex(pCur) );

  getCellInfo(pCur);
  aPayload = pCur->info.pCell + pCur->info.nHeader;
  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);

  if( NEVER(offset+amt > nKey+pCur->info.nData) 
   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  ){
    /* Trying to read or write past the end of the data is an error */
    return SQLITE_CORRUPT_BKPT;
  }

  /* Check if data must be read/written to/from the btree page itself. */
  if( offset<pCur->info.nLocal ){
    int a = amt;
    if( a+offset>pCur->info.nLocal ){
      a = pCur->info.nLocal - offset;
    }
    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
    offset = 0;
    pBuf += a;
    amt -= a;
  }else{
    offset -= pCur->info.nLocal;
  }

  if( rc==SQLITE_OK && amt>0 ){
    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
    Pgno nextPage;

    nextPage = get4byte(&aPayload[pCur->info.nLocal]);

#ifndef SQLITE_OMIT_INCRBLOB
    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
    ** has not been allocated, allocate it now. The array is sized at
    ** one entry for each overflow page in the overflow chain. The
    ** page number of the first overflow page is stored in aOverflow[0],
    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
    ** (the cache is lazily populated).
    */
    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
      /* nOvfl is always positive.  If it were zero, fetchPayload would have
      ** been used instead of this routine. */
      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
        rc = SQLITE_NOMEM;
      }
    }

    /* If the overflow page-list cache has been allocated and the
    ** entry for the first required overflow page is valid, skip
    ** directly to it.
    */
    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
      iIdx = (offset/ovflSize);
      nextPage = pCur->aOverflow[iIdx];
      offset = (offset%ovflSize);
    }
#endif

    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){

#ifndef SQLITE_OMIT_INCRBLOB
      /* If required, populate the overflow page-list cache. */
      if( pCur->aOverflow ){
        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
        pCur->aOverflow[iIdx] = nextPage;
      }
#endif

      if( offset>=ovflSize ){
        /* The only reason to read this page is to obtain the page
        ** number for the next page in the overflow chain. The page
        ** data is not required. So first try to lookup the overflow
        ** page-list cache, if any, then fall back to the getOverflowPage()
        ** function.
        */
#ifndef SQLITE_OMIT_INCRBLOB
        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
          nextPage = pCur->aOverflow[iIdx+1];
        } else 
#endif
          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
        offset -= ovflSize;
      }else{
        /* Need to read this page properly. It contains some of the
        ** range of data that is being read (eOp==0) or written (eOp!=0).
        */
        DbPage *pDbPage;
        int a = amt;
        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
        if( rc==SQLITE_OK ){
          aPayload = sqlite3PagerGetData(pDbPage);
          nextPage = get4byte(aPayload);
          if( a + offset > ovflSize ){
            a = ovflSize - offset;
          }
          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
          sqlite3PagerUnref(pDbPage);
          offset = 0;
          amt -= a;
          pBuf += a;
        }
      }
    }
  }

  if( rc==SQLITE_OK && amt>0 ){
    return SQLITE_CORRUPT_BKPT;
  }
  return rc;
}

/*
** Read part of the key associated with cursor pCur.  Exactly
** "amt" bytes will be transfered into pBuf[].  The transfer
** begins at "offset".
**
** The caller must ensure that pCur is pointing to a valid row
** in the table.
**
** Return SQLITE_OK on success or an error code if anything goes
** wrong.  An error is returned if "offset+amt" is larger than
** the available payload.
*/
int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_VALID );
  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
}

/*
** Read part of the data associated with cursor pCur.  Exactly
** "amt" bytes will be transfered into pBuf[].  The transfer
** begins at "offset".
**
** Return SQLITE_OK on success or an error code if anything goes
** wrong.  An error is returned if "offset+amt" is larger than
** the available payload.
*/
int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  int rc;

#ifndef SQLITE_OMIT_INCRBLOB
  if ( pCur->eState==CURSOR_INVALID ){
    return SQLITE_ABORT;
  }
#endif

  assert( cursorHoldsMutex(pCur) );
  rc = restoreCursorPosition(pCur);
  if( rc==SQLITE_OK ){
    assert( pCur->eState==CURSOR_VALID );
    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
    rc = accessPayload(pCur, offset, amt, pBuf, 0);
  }
  return rc;
}

/*
** Return a pointer to payload information from the entry that the 
** pCur cursor is pointing to.  The pointer is to the beginning of
** the key if skipKey==0 and it points to the beginning of data if
** skipKey==1.  The number of bytes of available key/data is written
** into *pAmt.  If *pAmt==0, then the value returned will not be
** a valid pointer.
**
** This routine is an optimization.  It is common for the entire key
** and data to fit on the local page and for there to be no overflow
** pages.  When that is so, this routine can be used to access the
** key and data without making a copy.  If the key and/or data spills
** onto overflow pages, then accessPayload() must be used to reassemble
** the key/data and copy it into a preallocated buffer.
**
** The pointer returned by this routine looks directly into the cached
** page of the database.  The data might change or move the next time
** any btree routine is called.
*/
static const unsigned char *fetchPayload(
  BtCursor *pCur,      /* Cursor pointing to entry to read from */
  int *pAmt,           /* Write the number of available bytes here */
  int skipKey          /* read beginning at data if this is true */
){
  unsigned char *aPayload;
  MemPage *pPage;
  u32 nKey;
  u32 nLocal;

  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  assert( pCur->eState==CURSOR_VALID );
  assert( cursorHoldsMutex(pCur) );
  pPage = pCur->apPage[pCur->iPage];
  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  if( NEVER(pCur->info.nSize==0) ){
    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
                   &pCur->info);
  }
  aPayload = pCur->info.pCell;
  aPayload += pCur->info.nHeader;
  if( pPage->intKey ){
    nKey = 0;
  }else{
    nKey = (int)pCur->info.nKey;
  }
  if( skipKey ){
    aPayload += nKey;
    nLocal = pCur->info.nLocal - nKey;
  }else{
    nLocal = pCur->info.nLocal;
    assert( nLocal<=nKey );
  }
  *pAmt = nLocal;
  return aPayload;
}


/*
** For the entry that cursor pCur is point to, return as
** many bytes of the key or data as are available on the local
** b-tree page.  Write the number of available bytes into *pAmt.
**
** The pointer returned is ephemeral.  The key/data may move
** or be destroyed on the next call to any Btree routine,
** including calls from other threads against the same cache.
** Hence, a mutex on the BtShared should be held prior to calling
** this routine.
**
** These routines is used to get quick access to key and data
** in the common case where no overflow pages are used.
*/
const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  const void *p = 0;
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  assert( cursorHoldsMutex(pCur) );
  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
    p = (const void*)fetchPayload(pCur, pAmt, 0);
  }
  return p;
}
const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  const void *p = 0;
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  assert( cursorHoldsMutex(pCur) );
  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
    p = (const void*)fetchPayload(pCur, pAmt, 1);
  }
  return p;
}


/*
** Move the cursor down to a new child page.  The newPgno argument is the
** page number of the child page to move to.
**
** This function returns SQLITE_CORRUPT if the page-header flags field of
** the new child page does not match the flags field of the parent (i.e.
** if an intkey page appears to be the parent of a non-intkey page, or
** vice-versa).
*/
static int moveToChild(BtCursor *pCur, u32 newPgno){
  int rc;
  int i = pCur->iPage;
  MemPage *pNewPage;
  BtShared *pBt = pCur->pBt;

  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_VALID );
  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
    return SQLITE_CORRUPT_BKPT;
  }
  rc = getAndInitPage(pBt, newPgno, &pNewPage);
  if( rc ) return rc;
  pCur->apPage[i+1] = pNewPage;
  pCur->aiIdx[i+1] = 0;
  pCur->iPage++;

  pCur->info.nSize = 0;
  pCur->validNKey = 0;
  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
    return SQLITE_CORRUPT_BKPT;
  }
  return SQLITE_OK;
}

#ifndef NDEBUG
/*
** Page pParent is an internal (non-leaf) tree page. This function 
** asserts that page number iChild is the left-child if the iIdx'th
** cell in page pParent. Or, if iIdx is equal to the total number of
** cells in pParent, that page number iChild is the right-child of
** the page.
*/
static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  assert( iIdx<=pParent->nCell );
  if( iIdx==pParent->nCell ){
    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  }else{
    assert( get4byte(findCell(pParent, iIdx))==iChild );
  }
}
#else
#  define assertParentIndex(x,y,z) 
#endif

/*
** Move the cursor up to the parent page.
**
** pCur->idx is set to the cell index that contains the pointer
** to the page we are coming from.  If we are coming from the
** right-most child page then pCur->idx is set to one more than
** the largest cell index.
*/
static void moveToParent(BtCursor *pCur){
  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_VALID );
  assert( pCur->iPage>0 );
  assert( pCur->apPage[pCur->iPage] );
  assertParentIndex(
    pCur->apPage[pCur->iPage-1], 
    pCur->aiIdx[pCur->iPage-1], 
    pCur->apPage[pCur->iPage]->pgno
  );
  releasePage(pCur->apPage[pCur->iPage]);
  pCur->iPage--;
  pCur->info.nSize = 0;
  pCur->validNKey = 0;
}

/*
** Move the cursor to point to the root page of its b-tree structure.
**
** If the table has a virtual root page, then the cursor is moved to point
** to the virtual root page instead of the actual root page. A table has a
** virtual root page when the actual root page contains no cells and a 
** single child page. This can only happen with the table rooted at page 1.
**
** If the b-tree structure is empty, the cursor state is set to 
** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
** cell located on the root (or virtual root) page and the cursor state
** is set to CURSOR_VALID.
**
** If this function returns successfully, it may be assumed that the
** page-header flags indicate that the [virtual] root-page is the expected 
** kind of b-tree page (i.e. if when opening the cursor the caller did not
** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
** indicating a table b-tree, or if the caller did specify a KeyInfo 
** structure the flags byte is set to 0x02 or 0x0A, indicating an index
** b-tree).
*/
static int moveToRoot(BtCursor *pCur){
  MemPage *pRoot;
  int rc = SQLITE_OK;
  Btree *p = pCur->pBtree;
  BtShared *pBt = p->pBt;

  assert( cursorHoldsMutex(pCur) );
  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
  if( pCur->eState>=CURSOR_REQUIRESEEK ){
    if( pCur->eState==CURSOR_FAULT ){
      assert( pCur->skipNext!=SQLITE_OK );
      return pCur->skipNext;
    }
    sqlite3BtreeClearCursor(pCur);
  }

  if( pCur->iPage>=0 ){
    int i;
    for(i=1; i<=pCur->iPage; i++){
      releasePage(pCur->apPage[i]);
    }
    pCur->iPage = 0;
  }else{
    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
    if( rc!=SQLITE_OK ){
      pCur->eState = CURSOR_INVALID;
      return rc;
    }
    pCur->iPage = 0;

    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
    ** NULL, the caller expects a table b-tree. If this is not the case,
    ** return an SQLITE_CORRUPT error.  */
    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
      return SQLITE_CORRUPT_BKPT;
    }
  }

  /* Assert that the root page is of the correct type. This must be the
  ** case as the call to this function that loaded the root-page (either
  ** this call or a previous invocation) would have detected corruption 
  ** if the assumption were not true, and it is not possible for the flags 
  ** byte to have been modified while this cursor is holding a reference
  ** to the page.  */
  pRoot = pCur->apPage[0];
  assert( pRoot->pgno==pCur->pgnoRoot );
  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );

  pCur->aiIdx[0] = 0;
  pCur->info.nSize = 0;
  pCur->atLast = 0;
  pCur->validNKey = 0;

  if( pRoot->nCell==0 && !pRoot->leaf ){
    Pgno subpage;
    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
    pCur->eState = CURSOR_VALID;
    rc = moveToChild(pCur, subpage);
  }else{
    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  }
  return rc;
}

/*
** Move the cursor down to the left-most leaf entry beneath the
** entry to which it is currently pointing.
**
** The left-most leaf is the one with the smallest key - the first
** in ascending order.
*/
static int moveToLeftmost(BtCursor *pCur){
  Pgno pgno;
  int rc = SQLITE_OK;
  MemPage *pPage;

  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_VALID );
  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
    rc = moveToChild(pCur, pgno);
  }
  return rc;
}

/*
** Move the cursor down to the right-most leaf entry beneath the
** page to which it is currently pointing.  Notice the difference
** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
** finds the left-most entry beneath the *entry* whereas moveToRightmost()
** finds the right-most entry beneath the *page*.
**
** The right-most entry is the one with the largest key - the last
** key in ascending order.
*/
static int moveToRightmost(BtCursor *pCur){
  Pgno pgno;
  int rc = SQLITE_OK;
  MemPage *pPage = 0;

  assert( cursorHoldsMutex(pCur) );
  assert( pCur->eState==CURSOR_VALID );
  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
    pCur->aiIdx[pCur->iPage] = pPage->nCell;
    rc = moveToChild(pCur, pgno);
  }
  if( rc==SQLITE_OK ){
    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
    pCur->info.nSize = 0;
    pCur->validNKey = 0;
  }
  return rc;
}

/* Move the cursor to the first entry in the table.  Return SQLITE_OK
** on success.  Set *pRes to 0 if the cursor actually points to something
** or set *pRes to 1 if the table is empty.
*/
int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  int rc;

  assert( cursorHoldsMutex(pCur) );
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  rc = moveToRoot(pCur);
  if( rc==SQLITE_OK ){
    if( pCur->eState==CURSOR_INVALID ){
      assert( pCur->apPage[pCur->iPage]->nCell==0 );
      *pRes = 1;
      rc = SQLITE_OK;
    }else{
      assert( pCur->apPage[pCur->iPage]->nCell>0 );
      *pRes = 0;
      rc = moveToLeftmost(pCur);
    }
  }
  return rc;
}

/* Move the cursor to the last entry in the table.  Return SQLITE_OK
** on success.  Set *pRes to 0 if the cursor actually points to something
** or set *pRes to 1 if the table is empty.
*/
int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  int rc;
 
  assert( cursorHoldsMutex(pCur) );
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );

  /* If the cursor already points to the last entry, this is a no-op. */
  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
#ifdef SQLITE_DEBUG
    /* This block serves to assert() that the cursor really does point 
    ** to the last entry in the b-tree. */
    int ii;
    for(ii=0; ii<pCur->iPage; ii++){
      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
    }
    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
    assert( pCur->apPage[pCur->iPage]->leaf );
#endif
    return SQLITE_OK;
  }

  rc = moveToRoot(pCur);
  if( rc==SQLITE_OK ){
    if( CURSOR_INVALID==pCur->eState ){
      assert( pCur->apPage[pCur->iPage]->nCell==0 );
      *pRes = 1;
    }else{
      assert( pCur->eState==CURSOR_VALID );
      *pRes = 0;
      rc = moveToRightmost(pCur);
      pCur->atLast = rc==SQLITE_OK ?1:0;
    }
  }
  return rc;
}

/* Move the cursor so that it points to an entry near the key 
** specified by pIdxKey or intKey.   Return a success code.
**
** For INTKEY tables, the intKey parameter is used.  pIdxKey 
** must be NULL.  For index tables, pIdxKey is used and intKey
** is ignored.
**
** If an exact match is not found, then the cursor is always
** left pointing at a leaf page which would hold the entry if it
** were present.  The cursor might point to an entry that comes
** before or after the key.
**
** An integer is written into *pRes which is the result of
** comparing the key with the entry to which the cursor is 
** pointing.  The meaning of the integer written into
** *pRes is as follows:
**
**     *pRes<0      The cursor is left pointing at an entry that
**                  is smaller than intKey/pIdxKey or if the table is empty
**                  and the cursor is therefore left point to nothing.
**
**     *pRes==0     The cursor is left pointing at an entry that
**                  exactly matches intKey/pIdxKey.
**
**     *pRes>0      The cursor is left pointing at an entry that
**                  is larger than intKey/pIdxKey.
**
*/
int sqlite3BtreeMovetoUnpacked(
  BtCursor *pCur,          /* The cursor to be moved */
  UnpackedRecord *pIdxKey, /* Unpacked index key */
  i64 intKey,              /* The table key */
  int biasRight,           /* If true, bias the search to the high end */
  int *pRes                /* Write search results here */
){
  int rc;

  assert( cursorHoldsMutex(pCur) );
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  assert( pRes );
  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );

  /* If the cursor is already positioned at the point we are trying
  ** to move to, then just return without doing any work */
  if( pCur->eState==CURSOR_VALID && pCur->validNKey 
   && pCur->apPage[0]->intKey 
  ){
    if( pCur->info.nKey==intKey ){
      *pRes = 0;
      return SQLITE_OK;
    }
    if( pCur->atLast && pCur->info.nKey<intKey ){
      *pRes = -1;
      return SQLITE_OK;
    }
  }

  rc = moveToRoot(pCur);
  if( rc ){
    return rc;
  }
  assert( pCur->apPage[pCur->iPage] );
  assert( pCur->apPage[pCur->iPage]->isInit );
  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
  if( pCur->eState==CURSOR_INVALID ){
    *pRes = -1;
    assert( pCur->apPage[pCur->iPage]->nCell==0 );
    return SQLITE_OK;
  }
  assert( pCur->apPage[0]->intKey || pIdxKey );
  for(;;){
    int lwr, upr;
    Pgno chldPg;
    MemPage *pPage = pCur->apPage[pCur->iPage];
    int c;

    /* pPage->nCell must be greater than zero. If this is the root-page
    ** the cursor would have been INVALID above and this for(;;) loop
    ** not run. If this is not the root-page, then the moveToChild() routine
    ** would have already detected db corruption. Similarly, pPage must
    ** be the right kind (index or table) of b-tree page. Otherwise
    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
    assert( pPage->nCell>0 );
    assert( pPage->intKey==(pIdxKey==0) );
    lwr = 0;
    upr = pPage->nCell-1;
    if( biasRight ){
      pCur->aiIdx[pCur->iPage] = (u16)upr;
    }else{
      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
    }
    for(;;){
      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
      u8 *pCell;                          /* Pointer to current cell in pPage */

      pCur->info.nSize = 0;
      pCell = findCell(pPage, idx) + pPage->childPtrSize;
      if( pPage->intKey ){
        i64 nCellKey;
        if( pPage->hasData ){
          u32 dummy;
          pCell += getVarint32(pCell, dummy);
        }
        getVarint(pCell, (u64*)&nCellKey);
        if( nCellKey==intKey ){
          c = 0;
        }else if( nCellKey<intKey ){
          c = -1;
        }else{
          assert( nCellKey>intKey );
          c = +1;
        }
        pCur->validNKey = 1;
        pCur->info.nKey = nCellKey;
      }else{
        /* The maximum supported page-size is 32768 bytes. This means that
        ** the maximum number of record bytes stored on an index B-Tree
        ** page is at most 8198 bytes, which may be stored as a 2-byte
        ** varint. This information is used to attempt to avoid parsing 
        ** the entire cell by checking for the cases where the record is 
        ** stored entirely within the b-tree page by inspecting the first 
        ** 2 bytes of the cell.
        */
        int nCell = pCell[0];
        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
          /* This branch runs if the record-size field of the cell is a
          ** single byte varint and the record fits entirely on the main
          ** b-tree page.  */
          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
        }else if( !(pCell[1] & 0x80) 
          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
        ){
          /* The record-size field is a 2 byte varint and the record 
          ** fits entirely on the main b-tree page.  */
          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
        }else{
          /* The record flows over onto one or more overflow pages. In
          ** this case the whole cell needs to be parsed, a buffer allocated
          ** and accessPayload() used to retrieve the record into the
          ** buffer before VdbeRecordCompare() can be called. */
          void *pCellKey;
          u8 * const pCellBody = pCell - pPage->childPtrSize;
          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
          nCell = (int)pCur->info.nKey;
          pCellKey = sqlite3Malloc( nCell );
          if( pCellKey==0 ){
            rc = SQLITE_NOMEM;
            goto moveto_finish;
          }
          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
          if( rc ){
            sqlite3_free(pCellKey);
            goto moveto_finish;
          }
          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
          sqlite3_free(pCellKey);
        }
      }
      if( c==0 ){
        if( pPage->intKey && !pPage->leaf ){
          lwr = idx;
          upr = lwr - 1;
          break;
        }else{
          *pRes = 0;
          rc = SQLITE_OK;
          goto moveto_finish;
        }
      }
      if( c<0 ){
        lwr = idx+1;
      }else{
        upr = idx-1;
      }
      if( lwr>upr ){
        break;
      }
      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
    }
    assert( lwr==upr+1 );
    assert( pPage->isInit );
    if( pPage->leaf ){
      chldPg = 0;
    }else if( lwr>=pPage->nCell ){
      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
    }else{
      chldPg = get4byte(findCell(pPage, lwr));
    }
    if( chldPg==0 ){
      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
      *pRes = c;
      rc = SQLITE_OK;
      goto moveto_finish;
    }
    pCur->aiIdx[pCur->iPage] = (u16)lwr;
    pCur->info.nSize = 0;
    pCur->validNKey = 0;
    rc = moveToChild(pCur, chldPg);
    if( rc ) goto moveto_finish;
  }
moveto_finish:
  return rc;
}


/*
** Return TRUE if the cursor is not pointing at an entry of the table.
**
** TRUE will be returned after a call to sqlite3BtreeNext() moves
** past the last entry in the table or sqlite3BtreePrev() moves past
** the first entry.  TRUE is also returned if the table is empty.
*/
int sqlite3BtreeEof(BtCursor *pCur){
  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  ** have been deleted? This API will need to change to return an error code
  ** as well as the boolean result value.
  */
  return (CURSOR_VALID!=pCur->eState);
}

/*
** Advance the cursor to the next entry in the database.  If
** successful then set *pRes=0.  If the cursor
** was already pointing to the last entry in the database before
** this routine was called, then set *pRes=1.
*/
int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  int rc;
  int idx;
  MemPage *pPage;

  assert( cursorHoldsMutex(pCur) );
  rc = restoreCursorPosition(pCur);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  assert( pRes!=0 );
  if( CURSOR_INVALID==pCur->eState ){
    *pRes = 1;
    return SQLITE_OK;
  }
  if( pCur->skipNext>0 ){
    pCur->skipNext = 0;
    *pRes = 0;
    return SQLITE_OK;
  }
  pCur->skipNext = 0;

  pPage = pCur->apPage[pCur->iPage];
  idx = ++pCur->aiIdx[pCur->iPage];
  assert( pPage->isInit );
  assert( idx<=pPage->nCell );

  pCur->info.nSize = 0;
  pCur->validNKey = 0;
  if( idx>=pPage->nCell ){
    if( !pPage->leaf ){
      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
      if( rc ) return rc;
      rc = moveToLeftmost(pCur);
      *pRes = 0;
      return rc;
    }
    do{
      if( pCur->iPage==0 ){
        *pRes = 1;
        pCur->eState = CURSOR_INVALID;
        return SQLITE_OK;
      }
      moveToParent(pCur);
      pPage = pCur->apPage[pCur->iPage];
    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
    *pRes = 0;
    if( pPage->intKey ){
      rc = sqlite3BtreeNext(pCur, pRes);
    }else{
      rc = SQLITE_OK;
    }
    return rc;
  }
  *pRes = 0;
  if( pPage->leaf ){
    return SQLITE_OK;
  }
  rc = moveToLeftmost(pCur);
  return rc;
}


/*
** Step the cursor to the back to the previous entry in the database.  If
** successful then set *pRes=0.  If the cursor
** was already pointing to the first entry in the database before
** this routine was called, then set *pRes=1.
*/
int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  int rc;
  MemPage *pPage;

  assert( cursorHoldsMutex(pCur) );
  rc = restoreCursorPosition(pCur);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pCur->atLast = 0;
  if( CURSOR_INVALID==pCur->eState ){
    *pRes = 1;
    return SQLITE_OK;
  }
  if( pCur->skipNext<0 ){
    pCur->skipNext = 0;
    *pRes = 0;
    return SQLITE_OK;
  }
  pCur->skipNext = 0;

  pPage = pCur->apPage[pCur->iPage];
  assert( pPage->isInit );
  if( !pPage->leaf ){
    int idx = pCur->aiIdx[pCur->iPage];
    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
    if( rc ){
      return rc;
    }
    rc = moveToRightmost(pCur);
  }else{
    while( pCur->aiIdx[pCur->iPage]==0 ){
      if( pCur->iPage==0 ){
        pCur->eState = CURSOR_INVALID;
        *pRes = 1;
        return SQLITE_OK;
      }
      moveToParent(pCur);
    }
    pCur->info.nSize = 0;
    pCur->validNKey = 0;

    pCur->aiIdx[pCur->iPage]--;
    pPage = pCur->apPage[pCur->iPage];
    if( pPage->intKey && !pPage->leaf ){
      rc = sqlite3BtreePrevious(pCur, pRes);
    }else{
      rc = SQLITE_OK;
    }
  }
  *pRes = 0;
  return rc;
}

/*
** Allocate a new page from the database file.
**
** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
** has already been called on the new page.)  The new page has also
** been referenced and the calling routine is responsible for calling
** sqlite3PagerUnref() on the new page when it is done.
**
** SQLITE_OK is returned on success.  Any other return value indicates
** an error.  *ppPage and *pPgno are undefined in the event of an error.
** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
**
** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
** locate a page close to the page number "nearby".  This can be used in an
** attempt to keep related pages close to each other in the database file,
** which in turn can make database access faster.
**
** If the "exact" parameter is not 0, and the page-number nearby exists 
** anywhere on the free-list, then it is guarenteed to be returned. This
** is only used by auto-vacuum databases when allocating a new table.
*/
static int allocateBtreePage(
  BtShared *pBt, 
  MemPage **ppPage, 
  Pgno *pPgno, 
  Pgno nearby,
  u8 exact
){
  MemPage *pPage1;
  int rc;
  u32 n;     /* Number of pages on the freelist */
  u32 k;     /* Number of leaves on the trunk of the freelist */
  MemPage *pTrunk = 0;
  MemPage *pPrevTrunk = 0;
  Pgno mxPage;     /* Total size of the database file */

  assert( sqlite3_mutex_held(pBt->mutex) );
  pPage1 = pBt->pPage1;
  mxPage = pagerPagecount(pBt);
  n = get4byte(&pPage1->aData[36]);
  testcase( n==mxPage-1 );
  if( n>=mxPage ){
    return SQLITE_CORRUPT_BKPT;
  }
  if( n>0 ){
    /* There are pages on the freelist.  Reuse one of those pages. */
    Pgno iTrunk;
    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
    
    /* If the 'exact' parameter was true and a query of the pointer-map
    ** shows that the page 'nearby' is somewhere on the free-list, then
    ** the entire-list will be searched for that page.
    */
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( exact && nearby<=mxPage ){
      u8 eType;
      assert( nearby>0 );
      assert( pBt->autoVacuum );
      rc = ptrmapGet(pBt, nearby, &eType, 0);
      if( rc ) return rc;
      if( eType==PTRMAP_FREEPAGE ){
        searchList = 1;
      }
      *pPgno = nearby;
    }
#endif

    /* Decrement the free-list count by 1. Set iTrunk to the index of the
    ** first free-list trunk page. iPrevTrunk is initially 1.
    */
    rc = sqlite3PagerWrite(pPage1->pDbPage);
    if( rc ) return rc;
    put4byte(&pPage1->aData[36], n-1);

    /* The code within this loop is run only once if the 'searchList' variable
    ** is not true. Otherwise, it runs once for each trunk-page on the
    ** free-list until the page 'nearby' is located.
    */
    do {
      pPrevTrunk = pTrunk;
      if( pPrevTrunk ){
        iTrunk = get4byte(&pPrevTrunk->aData[0]);
      }else{
        iTrunk = get4byte(&pPage1->aData[32]);
      }
      testcase( iTrunk==mxPage );
      if( iTrunk>mxPage ){
        rc = SQLITE_CORRUPT_BKPT;
      }else{
        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
      }
      if( rc ){
        pTrunk = 0;
        goto end_allocate_page;
      }

      k = get4byte(&pTrunk->aData[4]);
      if( k==0 && !searchList ){
        /* The trunk has no leaves and the list is not being searched. 
        ** So extract the trunk page itself and use it as the newly 
        ** allocated page */
        assert( pPrevTrunk==0 );
        rc = sqlite3PagerWrite(pTrunk->pDbPage);
        if( rc ){
          goto end_allocate_page;
        }
        *pPgno = iTrunk;
        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
        *ppPage = pTrunk;
        pTrunk = 0;
        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
        /* Value of k is out of range.  Database corruption */
        rc = SQLITE_CORRUPT_BKPT;
        goto end_allocate_page;
#ifndef SQLITE_OMIT_AUTOVACUUM
      }else if( searchList && nearby==iTrunk ){
        /* The list is being searched and this trunk page is the page
        ** to allocate, regardless of whether it has leaves.
        */
        assert( *pPgno==iTrunk );
        *ppPage = pTrunk;
        searchList = 0;
        rc = sqlite3PagerWrite(pTrunk->pDbPage);
        if( rc ){
          goto end_allocate_page;
        }
        if( k==0 ){
          if( !pPrevTrunk ){
            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
          }else{
            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
          }
        }else{
          /* The trunk page is required by the caller but it contains 
          ** pointers to free-list leaves. The first leaf becomes a trunk
          ** page in this case.
          */
          MemPage *pNewTrunk;
          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
          if( iNewTrunk>mxPage ){ 
            rc = SQLITE_CORRUPT_BKPT;
            goto end_allocate_page;
          }
          testcase( iNewTrunk==mxPage );
          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
          if( rc!=SQLITE_OK ){
            goto end_allocate_page;
          }
          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
          if( rc!=SQLITE_OK ){
            releasePage(pNewTrunk);
            goto end_allocate_page;
          }
          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
          put4byte(&pNewTrunk->aData[4], k-1);
          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
          releasePage(pNewTrunk);
          if( !pPrevTrunk ){
            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
            put4byte(&pPage1->aData[32], iNewTrunk);
          }else{
            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
            if( rc ){
              goto end_allocate_page;
            }
            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
          }
        }
        pTrunk = 0;
        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
#endif
      }else if( k>0 ){
        /* Extract a leaf from the trunk */
        u32 closest;
        Pgno iPage;
        unsigned char *aData = pTrunk->aData;
        rc = sqlite3PagerWrite(pTrunk->pDbPage);
        if( rc ){
          goto end_allocate_page;
        }
        if( nearby>0 ){
          u32 i;
          int dist;
          closest = 0;
          dist = get4byte(&aData[8]) - nearby;
          if( dist<0 ) dist = -dist;
          for(i=1; i<k; i++){
            int d2 = get4byte(&aData[8+i*4]) - nearby;
            if( d2<0 ) d2 = -d2;
            if( d2<dist ){
              closest = i;
              dist = d2;
            }
          }
        }else{
          closest = 0;
        }

        iPage = get4byte(&aData[8+closest*4]);
        testcase( iPage==mxPage );
        if( iPage>mxPage ){
          rc = SQLITE_CORRUPT_BKPT;
          goto end_allocate_page;
        }
        testcase( iPage==mxPage );
        if( !searchList || iPage==nearby ){
          int noContent;
          *pPgno = iPage;
          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
                 ": %d more free pages\n",
                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
          if( closest<k-1 ){
            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
          }
          put4byte(&aData[4], k-1);
          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
          noContent = !btreeGetHasContent(pBt, *pPgno);
          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
          if( rc==SQLITE_OK ){
            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
            if( rc!=SQLITE_OK ){
              releasePage(*ppPage);
            }
          }
          searchList = 0;
        }
      }
      releasePage(pPrevTrunk);
      pPrevTrunk = 0;
    }while( searchList );
  }else{
    /* There are no pages on the freelist, so create a new page at the
    ** end of the file */
    int nPage = pagerPagecount(pBt);
    *pPgno = nPage + 1;

    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
      (*pPgno)++;
    }

#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
      /* If *pPgno refers to a pointer-map page, allocate two new pages
      ** at the end of the file instead of one. The first allocated page
      ** becomes a new pointer-map page, the second is used by the caller.
      */
      MemPage *pPg = 0;
      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
      if( rc==SQLITE_OK ){
        rc = sqlite3PagerWrite(pPg->pDbPage);
        releasePage(pPg);
      }
      if( rc ) return rc;
      (*pPgno)++;
      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
    }
#endif

    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
    if( rc ) return rc;
    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
    if( rc!=SQLITE_OK ){
      releasePage(*ppPage);
    }
    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  }

  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );

end_allocate_page:
  releasePage(pTrunk);
  releasePage(pPrevTrunk);
  if( rc==SQLITE_OK ){
    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
      releasePage(*ppPage);
      return SQLITE_CORRUPT_BKPT;
    }
    (*ppPage)->isInit = 0;
  }else{
    *ppPage = 0;
  }
  return rc;
}

/*
** This function is used to add page iPage to the database file free-list. 
** It is assumed that the page is not already a part of the free-list.
**
** The value passed as the second argument to this function is optional.
** If the caller happens to have a pointer to the MemPage object 
** corresponding to page iPage handy, it may pass it as the second value. 
** Otherwise, it may pass NULL.
**
** If a pointer to a MemPage object is passed as the second argument,
** its reference count is not altered by this function.
*/
static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  MemPage *pTrunk = 0;                /* Free-list trunk page */
  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
  MemPage *pPage;                     /* Page being freed. May be NULL. */
  int rc;                             /* Return Code */
  int nFree;                          /* Initial number of pages on free-list */

  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( iPage>1 );
  assert( !pMemPage || pMemPage->pgno==iPage );

  if( pMemPage ){
    pPage = pMemPage;
    sqlite3PagerRef(pPage->pDbPage);
  }else{
    pPage = btreePageLookup(pBt, iPage);
  }

  /* Increment the free page count on pPage1 */
  rc = sqlite3PagerWrite(pPage1->pDbPage);
  if( rc ) goto freepage_out;
  nFree = get4byte(&pPage1->aData[36]);
  put4byte(&pPage1->aData[36], nFree+1);

#ifdef SQLITE_SECURE_DELETE
  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
  ** always fully overwrite deleted information with zeros.
  */
  if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
  ){
    goto freepage_out;
  }
  memset(pPage->aData, 0, pPage->pBt->pageSize);
#endif

  /* If the database supports auto-vacuum, write an entry in the pointer-map
  ** to indicate that the page is free.
  */
  if( ISAUTOVACUUM ){
    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
    if( rc ) goto freepage_out;
  }

  /* Now manipulate the actual database free-list structure. There are two
  ** possibilities. If the free-list is currently empty, or if the first
  ** trunk page in the free-list is full, then this page will become a
  ** new free-list trunk page. Otherwise, it will become a leaf of the
  ** first trunk page in the current free-list. This block tests if it
  ** is possible to add the page as a new free-list leaf.
  */
  if( nFree!=0 ){
    u32 nLeaf;                /* Initial number of leaf cells on trunk page */

    iTrunk = get4byte(&pPage1->aData[32]);
    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
    if( rc!=SQLITE_OK ){
      goto freepage_out;
    }

    nLeaf = get4byte(&pTrunk->aData[4]);
    assert( pBt->usableSize>32 );
    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
      rc = SQLITE_CORRUPT_BKPT;
      goto freepage_out;
    }
    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
      /* In this case there is room on the trunk page to insert the page
      ** being freed as a new leaf.
      **
      ** Note that the trunk page is not really full until it contains
      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
      ** coded.  But due to a coding error in versions of SQLite prior to
      ** 3.6.0, databases with freelist trunk pages holding more than
      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
      ** to maintain backwards compatibility with older versions of SQLite,
      ** we will continue to restrict the number of entries to usableSize/4 - 8
      ** for now.  At some point in the future (once everyone has upgraded
      ** to 3.6.0 or later) we should consider fixing the conditional above
      ** to read "usableSize/4-2" instead of "usableSize/4-8".
      */
      rc = sqlite3PagerWrite(pTrunk->pDbPage);
      if( rc==SQLITE_OK ){
        put4byte(&pTrunk->aData[4], nLeaf+1);
        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
#ifndef SQLITE_SECURE_DELETE
        if( pPage ){
          sqlite3PagerDontWrite(pPage->pDbPage);
        }
#endif
        rc = btreeSetHasContent(pBt, iPage);
      }
      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
      goto freepage_out;
    }
  }

  /* If control flows to this point, then it was not possible to add the
  ** the page being freed as a leaf page of the first trunk in the free-list.
  ** Possibly because the free-list is empty, or possibly because the 
  ** first trunk in the free-list is full. Either way, the page being freed
  ** will become the new first trunk page in the free-list.
  */
  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
    goto freepage_out;
  }
  rc = sqlite3PagerWrite(pPage->pDbPage);
  if( rc!=SQLITE_OK ){
    goto freepage_out;
  }
  put4byte(pPage->aData, iTrunk);
  put4byte(&pPage->aData[4], 0);
  put4byte(&pPage1->aData[32], iPage);
  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));

freepage_out:
  if( pPage ){
    pPage->isInit = 0;
  }
  releasePage(pPage);
  releasePage(pTrunk);
  return rc;
}
static void freePage(MemPage *pPage, int *pRC){
  if( (*pRC)==SQLITE_OK ){
    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  }
}

/*
** Free any overflow pages associated with the given Cell.
*/
static int clearCell(MemPage *pPage, unsigned char *pCell){
  BtShared *pBt = pPage->pBt;
  CellInfo info;
  Pgno ovflPgno;
  int rc;
  int nOvfl;
  u16 ovflPageSize;

  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  btreeParseCellPtr(pPage, pCell, &info);
  if( info.iOverflow==0 ){
    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
  }
  ovflPgno = get4byte(&pCell[info.iOverflow]);
  assert( pBt->usableSize > 4 );
  ovflPageSize = pBt->usableSize - 4;
  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  assert( ovflPgno==0 || nOvfl>0 );
  while( nOvfl-- ){
    Pgno iNext = 0;
    MemPage *pOvfl = 0;
    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
      /* 0 is not a legal page number and page 1 cannot be an 
      ** overflow page. Therefore if ovflPgno<2 or past the end of the 
      ** file the database must be corrupt. */
      return SQLITE_CORRUPT_BKPT;
    }
    if( nOvfl ){
      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
      if( rc ) return rc;
    }
    rc = freePage2(pBt, pOvfl, ovflPgno);
    if( pOvfl ){
      sqlite3PagerUnref(pOvfl->pDbPage);
    }
    if( rc ) return rc;
    ovflPgno = iNext;
  }
  return SQLITE_OK;
}

/*
** Create the byte sequence used to represent a cell on page pPage
** and write that byte sequence into pCell[].  Overflow pages are
** allocated and filled in as necessary.  The calling procedure
** is responsible for making sure sufficient space has been allocated
** for pCell[].
**
** Note that pCell does not necessary need to point to the pPage->aData
** area.  pCell might point to some temporary storage.  The cell will
** be constructed in this temporary area then copied into pPage->aData
** later.
*/
static int fillInCell(
  MemPage *pPage,                /* The page that contains the cell */
  unsigned char *pCell,          /* Complete text of the cell */
  const void *pKey, i64 nKey,    /* The key */
  const void *pData,int nData,   /* The data */
  int nZero,                     /* Extra zero bytes to append to pData */
  int *pnSize                    /* Write cell size here */
){
  int nPayload;
  const u8 *pSrc;
  int nSrc, n, rc;
  int spaceLeft;
  MemPage *pOvfl = 0;
  MemPage *pToRelease = 0;
  unsigned char *pPrior;
  unsigned char *pPayload;
  BtShared *pBt = pPage->pBt;
  Pgno pgnoOvfl = 0;
  int nHeader;
  CellInfo info;

  assert( sqlite3_mutex_held(pPage->pBt->mutex) );

  /* pPage is not necessarily writeable since pCell might be auxiliary
  ** buffer space that is separate from the pPage buffer area */
  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
            || sqlite3PagerIswriteable(pPage->pDbPage) );

  /* Fill in the header. */
  nHeader = 0;
  if( !pPage->leaf ){
    nHeader += 4;
  }
  if( pPage->hasData ){
    nHeader += putVarint(&pCell[nHeader], nData+nZero);
  }else{
    nData = nZero = 0;
  }
  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  btreeParseCellPtr(pPage, pCell, &info);
  assert( info.nHeader==nHeader );
  assert( info.nKey==nKey );
  assert( info.nData==(u32)(nData+nZero) );
  
  /* Fill in the payload */
  nPayload = nData + nZero;
  if( pPage->intKey ){
    pSrc = pData;
    nSrc = nData;
    nData = 0;
  }else{ 
    if( NEVER(nKey>0x7fffffff || pKey==0) ){
      return SQLITE_CORRUPT_BKPT;
    }
    nPayload += (int)nKey;
    pSrc = pKey;
    nSrc = (int)nKey;
  }
  *pnSize = info.nSize;
  spaceLeft = info.nLocal;
  pPayload = &pCell[nHeader];
  pPrior = &pCell[info.iOverflow];

  while( nPayload>0 ){
    if( spaceLeft==0 ){
#ifndef SQLITE_OMIT_AUTOVACUUM
      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
      if( pBt->autoVacuum ){
        do{
          pgnoOvfl++;
        } while( 
          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
        );
      }
#endif
      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
#ifndef SQLITE_OMIT_AUTOVACUUM
      /* If the database supports auto-vacuum, and the second or subsequent
      ** overflow page is being allocated, add an entry to the pointer-map
      ** for that page now. 
      **
      ** If this is the first overflow page, then write a partial entry 
      ** to the pointer-map. If we write nothing to this pointer-map slot,
      ** then the optimistic overflow chain processing in clearCell()
      ** may misinterpret the uninitialised values and delete the
      ** wrong pages from the database.
      */
      if( pBt->autoVacuum && rc==SQLITE_OK ){
        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
        if( rc ){
          releasePage(pOvfl);
        }
      }
#endif
      if( rc ){
        releasePage(pToRelease);
        return rc;
      }

      /* If pToRelease is not zero than pPrior points into the data area
      ** of pToRelease.  Make sure pToRelease is still writeable. */
      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );

      /* If pPrior is part of the data area of pPage, then make sure pPage
      ** is still writeable */
      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
            || sqlite3PagerIswriteable(pPage->pDbPage) );

      put4byte(pPrior, pgnoOvfl);
      releasePage(pToRelease);
      pToRelease = pOvfl;
      pPrior = pOvfl->aData;
      put4byte(pPrior, 0);
      pPayload = &pOvfl->aData[4];
      spaceLeft = pBt->usableSize - 4;
    }
    n = nPayload;
    if( n>spaceLeft ) n = spaceLeft;

    /* If pToRelease is not zero than pPayload points into the data area
    ** of pToRelease.  Make sure pToRelease is still writeable. */
    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );

    /* If pPayload is part of the data area of pPage, then make sure pPage
    ** is still writeable */
    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
            || sqlite3PagerIswriteable(pPage->pDbPage) );

    if( nSrc>0 ){
      if( n>nSrc ) n = nSrc;
      assert( pSrc );
      memcpy(pPayload, pSrc, n);
    }else{
      memset(pPayload, 0, n);
    }
    nPayload -= n;
    pPayload += n;
    pSrc += n;
    nSrc -= n;
    spaceLeft -= n;
    if( nSrc==0 ){
      nSrc = nData;
      pSrc = pData;
    }
  }
  releasePage(pToRelease);
  return SQLITE_OK;
}

/*
** Remove the i-th cell from pPage.  This routine effects pPage only.
** The cell content is not freed or deallocated.  It is assumed that
** the cell content has been copied someplace else.  This routine just
** removes the reference to the cell from pPage.
**
** "sz" must be the number of bytes in the cell.
*/
static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  int i;          /* Loop counter */
  int pc;         /* Offset to cell content of cell being deleted */
  u8 *data;       /* pPage->aData */
  u8 *ptr;        /* Used to move bytes around within data[] */
  int rc;         /* The return code */
  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */

  if( *pRC ) return;

  assert( idx>=0 && idx<pPage->nCell );
  assert( sz==cellSize(pPage, idx) );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  data = pPage->aData;
  ptr = &data[pPage->cellOffset + 2*idx];
  pc = get2byte(ptr);
  hdr = pPage->hdrOffset;
  testcase( pc==get2byte(&data[hdr+5]) );
  testcase( pc+sz==pPage->pBt->usableSize );
  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
    *pRC = SQLITE_CORRUPT_BKPT;
    return;
  }
  rc = freeSpace(pPage, pc, sz);
  if( rc ){
    *pRC = rc;
    return;
  }
  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
    ptr[0] = ptr[2];
    ptr[1] = ptr[3];
  }
  pPage->nCell--;
  put2byte(&data[hdr+3], pPage->nCell);
  pPage->nFree += 2;
}

/*
** Insert a new cell on pPage at cell index "i".  pCell points to the
** content of the cell.
**
** If the cell content will fit on the page, then put it there.  If it
** will not fit, then make a copy of the cell content into pTemp if
** pTemp is not null.  Regardless of pTemp, allocate a new entry
** in pPage->aOvfl[] and make it point to the cell content (either
** in pTemp or the original pCell) and also record its index. 
** Allocating a new entry in pPage->aCell[] implies that 
** pPage->nOverflow is incremented.
**
** If nSkip is non-zero, then do not copy the first nSkip bytes of the
** cell. The caller will overwrite them after this function returns. If
** nSkip is non-zero, then pCell may not point to an invalid memory location 
** (but pCell+nSkip is always valid).
*/
static void insertCell(
  MemPage *pPage,   /* Page into which we are copying */
  int i,            /* New cell becomes the i-th cell of the page */
  u8 *pCell,        /* Content of the new cell */
  int sz,           /* Bytes of content in pCell */
  u8 *pTemp,        /* Temp storage space for pCell, if needed */
  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
  int *pRC          /* Read and write return code from here */
){
  int idx;          /* Where to write new cell content in data[] */
  int j;            /* Loop counter */
  int end;          /* First byte past the last cell pointer in data[] */
  int ins;          /* Index in data[] where new cell pointer is inserted */
  int cellOffset;   /* Address of first cell pointer in data[] */
  u8 *data;         /* The content of the whole page */
  u8 *ptr;          /* Used for moving information around in data[] */

  int nSkip = (iChild ? 4 : 0);

  if( *pRC ) return;

  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
  assert( sz==cellSizePtr(pPage, pCell) );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  if( pPage->nOverflow || sz+2>pPage->nFree ){
    if( pTemp ){
      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
      pCell = pTemp;
    }
    if( iChild ){
      put4byte(pCell, iChild);
    }
    j = pPage->nOverflow++;
    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
    pPage->aOvfl[j].pCell = pCell;
    pPage->aOvfl[j].idx = (u16)i;
  }else{
    int rc = sqlite3PagerWrite(pPage->pDbPage);
    if( rc!=SQLITE_OK ){
      *pRC = rc;
      return;
    }
    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
    data = pPage->aData;
    cellOffset = pPage->cellOffset;
    end = cellOffset + 2*pPage->nCell;
    ins = cellOffset + 2*i;
    rc = allocateSpace(pPage, sz, &idx);
    if( rc ){ *pRC = rc; return; }
    /* The allocateSpace() routine guarantees the following two properties
    ** if it returns success */
    assert( idx >= end+2 );
    assert( idx+sz <= pPage->pBt->usableSize );
    pPage->nCell++;
    pPage->nFree -= (u16)(2 + sz);
    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
    if( iChild ){
      put4byte(&data[idx], iChild);
    }
    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
      ptr[0] = ptr[-2];
      ptr[1] = ptr[-1];
    }
    put2byte(&data[ins], idx);
    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pPage->pBt->autoVacuum ){
      /* The cell may contain a pointer to an overflow page. If so, write
      ** the entry for the overflow page into the pointer map.
      */
      ptrmapPutOvflPtr(pPage, pCell, pRC);
    }
#endif
  }
}

/*
** Add a list of cells to a page.  The page should be initially empty.
** The cells are guaranteed to fit on the page.
*/
static void assemblePage(
  MemPage *pPage,   /* The page to be assemblied */
  int nCell,        /* The number of cells to add to this page */
  u8 **apCell,      /* Pointers to cell bodies */
  u16 *aSize        /* Sizes of the cells */
){
  int i;            /* Loop counter */
  u8 *pCellptr;     /* Address of next cell pointer */
  int cellbody;     /* Address of next cell body */
  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */

  assert( pPage->nOverflow==0 );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );

  /* Check that the page has just been zeroed by zeroPage() */
  assert( pPage->nCell==0 );
  assert( get2byte(&data[hdr+5])==nUsable );

  pCellptr = &data[pPage->cellOffset + nCell*2];
  cellbody = nUsable;
  for(i=nCell-1; i>=0; i--){
    pCellptr -= 2;
    cellbody -= aSize[i];
    put2byte(pCellptr, cellbody);
    memcpy(&data[cellbody], apCell[i], aSize[i]);
  }
  put2byte(&data[hdr+3], nCell);
  put2byte(&data[hdr+5], cellbody);
  pPage->nFree -= (nCell*2 + nUsable - cellbody);
  pPage->nCell = (u16)nCell;
}

/*
** The following parameters determine how many adjacent pages get involved
** in a balancing operation.  NN is the number of neighbors on either side
** of the page that participate in the balancing operation.  NB is the
** total number of pages that participate, including the target page and
** NN neighbors on either side.
**
** The minimum value of NN is 1 (of course).  Increasing NN above 1
** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
** in exchange for a larger degradation in INSERT and UPDATE performance.
** The value of NN appears to give the best results overall.
*/
#define NN 1             /* Number of neighbors on either side of pPage */
#define NB (NN*2+1)      /* Total pages involved in the balance */


#ifndef SQLITE_OMIT_QUICKBALANCE
/*
** This version of balance() handles the common special case where
** a new entry is being inserted on the extreme right-end of the
** tree, in other words, when the new entry will become the largest
** entry in the tree.
**
** Instead of trying to balance the 3 right-most leaf pages, just add
** a new page to the right-hand side and put the one new entry in
** that page.  This leaves the right side of the tree somewhat
** unbalanced.  But odds are that we will be inserting new entries
** at the end soon afterwards so the nearly empty page will quickly
** fill up.  On average.
**
** pPage is the leaf page which is the right-most page in the tree.
** pParent is its parent.  pPage must have a single overflow entry
** which is also the right-most entry on the page.
**
** The pSpace buffer is used to store a temporary copy of the divider
** cell that will be inserted into pParent. Such a cell consists of a 4
** byte page number followed by a variable length integer. In other
** words, at most 13 bytes. Hence the pSpace buffer must be at
** least 13 bytes in size.
*/
static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
  MemPage *pNew;                       /* Newly allocated page */
  int rc;                              /* Return Code */
  Pgno pgnoNew;                        /* Page number of pNew */

  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  assert( pPage->nOverflow==1 );

  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;

  /* Allocate a new page. This page will become the right-sibling of 
  ** pPage. Make the parent page writable, so that the new divider cell
  ** may be inserted. If both these operations are successful, proceed.
  */
  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);

  if( rc==SQLITE_OK ){

    u8 *pOut = &pSpace[4];
    u8 *pCell = pPage->aOvfl[0].pCell;
    u16 szCell = cellSizePtr(pPage, pCell);
    u8 *pStop;

    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
    assemblePage(pNew, 1, &pCell, &szCell);

    /* If this is an auto-vacuum database, update the pointer map
    ** with entries for the new page, and any pointer from the 
    ** cell on the page to an overflow page. If either of these
    ** operations fails, the return code is set, but the contents
    ** of the parent page are still manipulated by thh code below.
    ** That is Ok, at this point the parent page is guaranteed to
    ** be marked as dirty. Returning an error code will cause a
    ** rollback, undoing any changes made to the parent page.
    */
    if( ISAUTOVACUUM ){
      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
      if( szCell>pNew->minLocal ){
        ptrmapPutOvflPtr(pNew, pCell, &rc);
      }
    }
  
    /* Create a divider cell to insert into pParent. The divider cell
    ** consists of a 4-byte page number (the page number of pPage) and
    ** a variable length key value (which must be the same value as the
    ** largest key on pPage).
    **
    ** To find the largest key value on pPage, first find the right-most 
    ** cell on pPage. The first two fields of this cell are the 
    ** record-length (a variable length integer at most 32-bits in size)
    ** and the key value (a variable length integer, may have any value).
    ** The first of the while(...) loops below skips over the record-length
    ** field. The second while(...) loop copies the key value from the
    ** cell on pPage into the pSpace buffer.
    */
    pCell = findCell(pPage, pPage->nCell-1);
    pStop = &pCell[9];
    while( (*(pCell++)&0x80) && pCell<pStop );
    pStop = &pCell[9];
    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );

    /* Insert the new divider cell into pParent. */
    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
               0, pPage->pgno, &rc);

    /* Set the right-child pointer of pParent to point to the new page. */
    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  
    /* Release the reference to the new page. */
    releasePage(pNew);
  }

  return rc;
}
#endif /* SQLITE_OMIT_QUICKBALANCE */

#if 0
/*
** This function does not contribute anything to the operation of SQLite.
** it is sometimes activated temporarily while debugging code responsible 
** for setting pointer-map entries.
*/
static int ptrmapCheckPages(MemPage **apPage, int nPage){
  int i, j;
  for(i=0; i<nPage; i++){
    Pgno n;
    u8 e;
    MemPage *pPage = apPage[i];
    BtShared *pBt = pPage->pBt;
    assert( pPage->isInit );

    for(j=0; j<pPage->nCell; j++){
      CellInfo info;
      u8 *z;
     
      z = findCell(pPage, j);
      btreeParseCellPtr(pPage, z, &info);
      if( info.iOverflow ){
        Pgno ovfl = get4byte(&z[info.iOverflow]);
        ptrmapGet(pBt, ovfl, &e, &n);
        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
      }
      if( !pPage->leaf ){
        Pgno child = get4byte(z);
        ptrmapGet(pBt, child, &e, &n);
        assert( n==pPage->pgno && e==PTRMAP_BTREE );
      }
    }
    if( !pPage->leaf ){
      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
      ptrmapGet(pBt, child, &e, &n);
      assert( n==pPage->pgno && e==PTRMAP_BTREE );
    }
  }
  return 1;
}
#endif

/*
** This function is used to copy the contents of the b-tree node stored 
** on page pFrom to page pTo. If page pFrom was not a leaf page, then
** the pointer-map entries for each child page are updated so that the
** parent page stored in the pointer map is page pTo. If pFrom contained
** any cells with overflow page pointers, then the corresponding pointer
** map entries are also updated so that the parent page is page pTo.
**
** If pFrom is currently carrying any overflow cells (entries in the
** MemPage.aOvfl[] array), they are not copied to pTo. 
**
** Before returning, page pTo is reinitialized using btreeInitPage().
**
** The performance of this function is not critical. It is only used by 
** the balance_shallower() and balance_deeper() procedures, neither of
** which are called often under normal circumstances.
*/
static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  if( (*pRC)==SQLITE_OK ){
    BtShared * const pBt = pFrom->pBt;
    u8 * const aFrom = pFrom->aData;
    u8 * const aTo = pTo->aData;
    int const iFromHdr = pFrom->hdrOffset;
    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
    TESTONLY(int rc;)
    int iData;
  
  
    assert( pFrom->isInit );
    assert( pFrom->nFree>=iToHdr );
    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
  
    /* Copy the b-tree node content from page pFrom to page pTo. */
    iData = get2byte(&aFrom[iFromHdr+5]);
    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  
    /* Reinitialize page pTo so that the contents of the MemPage structure
    ** match the new data. The initialization of pTo "cannot" fail, as the
    ** data copied from pFrom is known to be valid.  */
    pTo->isInit = 0;
    TESTONLY(rc = ) btreeInitPage(pTo);
    assert( rc==SQLITE_OK );
  
    /* If this is an auto-vacuum database, update the pointer-map entries
    ** for any b-tree or overflow pages that pTo now contains the pointers to.
    */
    if( ISAUTOVACUUM ){
      *pRC = setChildPtrmaps(pTo);
    }
  }
}

/*
** This routine redistributes cells on the iParentIdx'th child of pParent
** (hereafter "the page") and up to 2 siblings so that all pages have about the
** same amount of free space. Usually a single sibling on either side of the
** page are used in the balancing, though both siblings might come from one
** side if the page is the first or last child of its parent. If the page 
** has fewer than 2 siblings (something which can only happen if the page
** is a root page or a child of a root page) then all available siblings
** participate in the balancing.
**
** The number of siblings of the page might be increased or decreased by 
** one or two in an effort to keep pages nearly full but not over full. 
**
** Note that when this routine is called, some of the cells on the page
** might not actually be stored in MemPage.aData[]. This can happen
** if the page is overfull. This routine ensures that all cells allocated
** to the page and its siblings fit into MemPage.aData[] before returning.
**
** In the course of balancing the page and its siblings, cells may be
** inserted into or removed from the parent page (pParent). Doing so
** may cause the parent page to become overfull or underfull. If this
** happens, it is the responsibility of the caller to invoke the correct
** balancing routine to fix this problem (see the balance() routine). 
**
** If this routine fails for any reason, it might leave the database
** in a corrupted state. So if this routine fails, the database should
** be rolled back.
**
** The third argument to this function, aOvflSpace, is a pointer to a
** buffer big enough to hold one page. If while inserting cells into the parent
** page (pParent) the parent page becomes overfull, this buffer is
** used to store the parent's overflow cells. Because this function inserts
** a maximum of four divider cells into the parent page, and the maximum
** size of a cell stored within an internal node is always less than 1/4
** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
** enough for all overflow cells.
**
** If aOvflSpace is set to a null pointer, this function returns 
** SQLITE_NOMEM.
*/
static int balance_nonroot(
  MemPage *pParent,               /* Parent page of siblings being balanced */
  int iParentIdx,                 /* Index of "the page" in pParent */
  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
  int isRoot                      /* True if pParent is a root-page */
){
  BtShared *pBt;               /* The whole database */
  int nCell = 0;               /* Number of cells in apCell[] */
  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
  int nNew = 0;                /* Number of pages in apNew[] */
  int nOld;                    /* Number of pages in apOld[] */
  int i, j, k;                 /* Loop counters */
  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
  int rc = SQLITE_OK;          /* The return code */
  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
  int usableSpace;             /* Bytes in pPage beyond the header */
  int pageFlags;               /* Value of pPage->aData[0] */
  int subtotal;                /* Subtotal of bytes in cells on one page */
  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
  int szScratch;               /* Size of scratch memory requested */
  MemPage *apOld[NB];          /* pPage and up to two siblings */
  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
  u8 *pRight;                  /* Location in parent of right-sibling pointer */
  u8 *apDiv[NB-1];             /* Divider cells in pParent */
  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
  int szNew[NB+2];             /* Combined size of cells place on i-th page */
  u8 **apCell = 0;             /* All cells begin balanced */
  u16 *szCell;                 /* Local size of all cells in apCell[] */
  u8 *aSpace1;                 /* Space for copies of dividers cells */
  Pgno pgno;                   /* Temp var to store a page number in */

  pBt = pParent->pBt;
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );

#if 0
  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
#endif

  /* At this point pParent may have at most one overflow cell. And if
  ** this overflow cell is present, it must be the cell with 
  ** index iParentIdx. This scenario comes about when this function
  ** is called (indirectly) from sqlite3BtreeDelete().
  */
  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );

  if( !aOvflSpace ){
    return SQLITE_NOMEM;
  }

  /* Find the sibling pages to balance. Also locate the cells in pParent 
  ** that divide the siblings. An attempt is made to find NN siblings on 
  ** either side of pPage. More siblings are taken from one side, however, 
  ** if there are fewer than NN siblings on the other side. If pParent
  ** has NB or fewer children then all children of pParent are taken.  
  **
  ** This loop also drops the divider cells from the parent page. This
  ** way, the remainder of the function does not have to deal with any
  ** overflow cells in the parent page, since if any existed they will
  ** have already been removed.
  */
  i = pParent->nOverflow + pParent->nCell;
  if( i<2 ){
    nxDiv = 0;
    nOld = i+1;
  }else{
    nOld = 3;
    if( iParentIdx==0 ){                 
      nxDiv = 0;
    }else if( iParentIdx==i ){
      nxDiv = i-2;
    }else{
      nxDiv = iParentIdx-1;
    }
    i = 2;
  }
  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
    pRight = &pParent->aData[pParent->hdrOffset+8];
  }else{
    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  }
  pgno = get4byte(pRight);
  while( 1 ){
    rc = getAndInitPage(pBt, pgno, &apOld[i]);
    if( rc ){
      memset(apOld, 0, (i+1)*sizeof(MemPage*));
      goto balance_cleanup;
    }
    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
    if( (i--)==0 ) break;

    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
      apDiv[i] = pParent->aOvfl[0].pCell;
      pgno = get4byte(apDiv[i]);
      szNew[i] = cellSizePtr(pParent, apDiv[i]);
      pParent->nOverflow = 0;
    }else{
      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
      pgno = get4byte(apDiv[i]);
      szNew[i] = cellSizePtr(pParent, apDiv[i]);

      /* Drop the cell from the parent page. apDiv[i] still points to
      ** the cell within the parent, even though it has been dropped.
      ** This is safe because dropping a cell only overwrites the first
      ** four bytes of it, and this function does not need the first
      ** four bytes of the divider cell. So the pointer is safe to use
      ** later on.  
      **
      ** Unless SQLite is compiled in secure-delete mode. In this case,
      ** the dropCell() routine will overwrite the entire cell with zeroes.
      ** In this case, temporarily copy the cell into the aOvflSpace[]
      ** buffer. It will be copied out again as soon as the aSpace[] buffer
      ** is allocated.  */
#ifdef SQLITE_SECURE_DELETE
      memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
      apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
#endif
      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
    }
  }

  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  ** alignment */
  nMaxCells = (nMaxCells + 3)&~3;

  /*
  ** Allocate space for memory structures
  */
  k = pBt->pageSize + ROUND8(sizeof(MemPage));
  szScratch =
       nMaxCells*sizeof(u8*)                       /* apCell */
     + nMaxCells*sizeof(u16)                       /* szCell */
     + pBt->pageSize                               /* aSpace1 */
     + k*nOld;                                     /* Page copies (apCopy) */
  apCell = sqlite3ScratchMalloc( szScratch ); 
  if( apCell==0 ){
    rc = SQLITE_NOMEM;
    goto balance_cleanup;
  }
  szCell = (u16*)&apCell[nMaxCells];
  aSpace1 = (u8*)&szCell[nMaxCells];
  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );

  /*
  ** Load pointers to all cells on sibling pages and the divider cells
  ** into the local apCell[] array.  Make copies of the divider cells
  ** into space obtained from aSpace1[] and remove the the divider Cells
  ** from pParent.
  **
  ** If the siblings are on leaf pages, then the child pointers of the
  ** divider cells are stripped from the cells before they are copied
  ** into aSpace1[].  In this way, all cells in apCell[] are without
  ** child pointers.  If siblings are not leaves, then all cell in
  ** apCell[] include child pointers.  Either way, all cells in apCell[]
  ** are alike.
  **
  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
  */
  leafCorrection = apOld[0]->leaf*4;
  leafData = apOld[0]->hasData;
  for(i=0; i<nOld; i++){
    int limit;
    
    /* Before doing anything else, take a copy of the i'th original sibling
    ** The rest of this function will use data from the copies rather
    ** that the original pages since the original pages will be in the
    ** process of being overwritten.  */
    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
    memcpy(pOld, apOld[i], sizeof(MemPage));
    pOld->aData = (void*)&pOld[1];
    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);

    limit = pOld->nCell+pOld->nOverflow;
    for(j=0; j<limit; j++){
      assert( nCell<nMaxCells );
      apCell[nCell] = findOverflowCell(pOld, j);
      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
      nCell++;
    }
    if( i<nOld-1 && !leafData){
      u16 sz = (u16)szNew[i];
      u8 *pTemp;
      assert( nCell<nMaxCells );
      szCell[nCell] = sz;
      pTemp = &aSpace1[iSpace1];
      iSpace1 += sz;
      assert( sz<=pBt->pageSize/4 );
      assert( iSpace1<=pBt->pageSize );
      memcpy(pTemp, apDiv[i], sz);
      apCell[nCell] = pTemp+leafCorrection;
      assert( leafCorrection==0 || leafCorrection==4 );
      szCell[nCell] = szCell[nCell] - leafCorrection;
      if( !pOld->leaf ){
        assert( leafCorrection==0 );
        assert( pOld->hdrOffset==0 );
        /* The right pointer of the child page pOld becomes the left
        ** pointer of the divider cell */
        memcpy(apCell[nCell], &pOld->aData[8], 4);
      }else{
        assert( leafCorrection==4 );
        if( szCell[nCell]<4 ){
          /* Do not allow any cells smaller than 4 bytes. */
          szCell[nCell] = 4;
        }
      }
      nCell++;
    }
  }

  /*
  ** Figure out the number of pages needed to hold all nCell cells.
  ** Store this number in "k".  Also compute szNew[] which is the total
  ** size of all cells on the i-th page and cntNew[] which is the index
  ** in apCell[] of the cell that divides page i from page i+1.  
  ** cntNew[k] should equal nCell.
  **
  ** Values computed by this block:
  **
  **           k: The total number of sibling pages
  **    szNew[i]: Spaced used on the i-th sibling page.
  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  **              the right of the i-th sibling page.
  ** usableSpace: Number of bytes of space available on each sibling.
  ** 
  */
  usableSpace = pBt->usableSize - 12 + leafCorrection;
  for(subtotal=k=i=0; i<nCell; i++){
    assert( i<nMaxCells );
    subtotal += szCell[i] + 2;
    if( subtotal > usableSpace ){
      szNew[k] = subtotal - szCell[i];
      cntNew[k] = i;
      if( leafData ){ i--; }
      subtotal = 0;
      k++;
      if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
    }
  }
  szNew[k] = subtotal;
  cntNew[k] = nCell;
  k++;

  /*
  ** The packing computed by the previous block is biased toward the siblings
  ** on the left side.  The left siblings are always nearly full, while the
  ** right-most sibling might be nearly empty.  This block of code attempts
  ** to adjust the packing of siblings to get a better balance.
  **
  ** This adjustment is more than an optimization.  The packing above might
  ** be so out of balance as to be illegal.  For example, the right-most
  ** sibling might be completely empty.  This adjustment is not optional.
  */
  for(i=k-1; i>0; i--){
    int szRight = szNew[i];  /* Size of sibling on the right */
    int szLeft = szNew[i-1]; /* Size of sibling on the left */
    int r;              /* Index of right-most cell in left sibling */
    int d;              /* Index of first cell to the left of right sibling */

    r = cntNew[i-1] - 1;
    d = r + 1 - leafData;
    assert( d<nMaxCells );
    assert( r<nMaxCells );
    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
      szRight += szCell[d] + 2;
      szLeft -= szCell[r] + 2;
      cntNew[i-1]--;
      r = cntNew[i-1] - 1;
      d = r + 1 - leafData;
    }
    szNew[i] = szRight;
    szNew[i-1] = szLeft;
  }

  /* Either we found one or more cells (cntnew[0])>0) or pPage is
  ** a virtual root page.  A virtual root page is when the real root
  ** page is page 1 and we are the only child of that page.
  */
  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );

  TRACE(("BALANCE: old: %d %d %d  ",
    apOld[0]->pgno, 
    nOld>=2 ? apOld[1]->pgno : 0,
    nOld>=3 ? apOld[2]->pgno : 0
  ));

  /*
  ** Allocate k new pages.  Reuse old pages where possible.
  */
  if( apOld[0]->pgno<=1 ){
    rc = SQLITE_CORRUPT;
    goto balance_cleanup;
  }
  pageFlags = apOld[0]->aData[0];
  for(i=0; i<k; i++){
    MemPage *pNew;
    if( i<nOld ){
      pNew = apNew[i] = apOld[i];
      apOld[i] = 0;
      rc = sqlite3PagerWrite(pNew->pDbPage);
      nNew++;
      if( rc ) goto balance_cleanup;
    }else{
      assert( i>0 );
      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
      if( rc ) goto balance_cleanup;
      apNew[i] = pNew;
      nNew++;

      /* Set the pointer-map entry for the new sibling page. */
      if( ISAUTOVACUUM ){
        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
        if( rc!=SQLITE_OK ){
          goto balance_cleanup;
        }
      }
    }
  }

  /* Free any old pages that were not reused as new pages.
  */
  while( i<nOld ){
    freePage(apOld[i], &rc);
    if( rc ) goto balance_cleanup;
    releasePage(apOld[i]);
    apOld[i] = 0;
    i++;
  }

  /*
  ** Put the new pages in accending order.  This helps to
  ** keep entries in the disk file in order so that a scan
  ** of the table is a linear scan through the file.  That
  ** in turn helps the operating system to deliver pages
  ** from the disk more rapidly.
  **
  ** An O(n^2) insertion sort algorithm is used, but since
  ** n is never more than NB (a small constant), that should
  ** not be a problem.
  **
  ** When NB==3, this one optimization makes the database
  ** about 25% faster for large insertions and deletions.
  */
  for(i=0; i<k-1; i++){
    int minV = apNew[i]->pgno;
    int minI = i;
    for(j=i+1; j<k; j++){
      if( apNew[j]->pgno<(unsigned)minV ){
        minI = j;
        minV = apNew[j]->pgno;
      }
    }
    if( minI>i ){
      int t;
      MemPage *pT;
      t = apNew[i]->pgno;
      pT = apNew[i];
      apNew[i] = apNew[minI];
      apNew[minI] = pT;
    }
  }
  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
    apNew[0]->pgno, szNew[0],
    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));

  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  put4byte(pRight, apNew[nNew-1]->pgno);

  /*
  ** Evenly distribute the data in apCell[] across the new pages.
  ** Insert divider cells into pParent as necessary.
  */
  j = 0;
  for(i=0; i<nNew; i++){
    /* Assemble the new sibling page. */
    MemPage *pNew = apNew[i];
    assert( j<nMaxCells );
    zeroPage(pNew, pageFlags);
    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
    assert( pNew->nOverflow==0 );

    j = cntNew[i];

    /* If the sibling page assembled above was not the right-most sibling,
    ** insert a divider cell into the parent page.
    */
    assert( i<nNew-1 || j==nCell );
    if( j<nCell ){
      u8 *pCell;
      u8 *pTemp;
      int sz;

      assert( j<nMaxCells );
      pCell = apCell[j];
      sz = szCell[j] + leafCorrection;
      pTemp = &aOvflSpace[iOvflSpace];
      if( !pNew->leaf ){
        memcpy(&pNew->aData[8], pCell, 4);
      }else if( leafData ){
        /* If the tree is a leaf-data tree, and the siblings are leaves, 
        ** then there is no divider cell in apCell[]. Instead, the divider 
        ** cell consists of the integer key for the right-most cell of 
        ** the sibling-page assembled above only.
        */
        CellInfo info;
        j--;
        btreeParseCellPtr(pNew, apCell[j], &info);
        pCell = pTemp;
        sz = 4 + putVarint(&pCell[4], info.nKey);
        pTemp = 0;
      }else{
        pCell -= 4;
        /* Obscure case for non-leaf-data trees: If the cell at pCell was
        ** previously stored on a leaf node, and its reported size was 4
        ** bytes, then it may actually be smaller than this 
        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
        ** any cell). But it is important to pass the correct size to 
        ** insertCell(), so reparse the cell now.
        **
        ** Note that this can never happen in an SQLite data file, as all
        ** cells are at least 4 bytes. It only happens in b-trees used
        ** to evaluate "IN (SELECT ...)" and similar clauses.
        */
        if( szCell[j]==4 ){
          assert(leafCorrection==4);
          sz = cellSizePtr(pParent, pCell);
        }
      }
      iOvflSpace += sz;
      assert( sz<=pBt->pageSize/4 );
      assert( iOvflSpace<=pBt->pageSize );
      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
      if( rc!=SQLITE_OK ) goto balance_cleanup;
      assert( sqlite3PagerIswriteable(pParent->pDbPage) );

      j++;
      nxDiv++;
    }
  }
  assert( j==nCell );
  assert( nOld>0 );
  assert( nNew>0 );
  if( (pageFlags & PTF_LEAF)==0 ){
    u8 *zChild = &apCopy[nOld-1]->aData[8];
    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  }

  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
    /* The root page of the b-tree now contains no cells. The only sibling
    ** page is the right-child of the parent. Copy the contents of the
    ** child page into the parent, decreasing the overall height of the
    ** b-tree structure by one. This is described as the "balance-shallower"
    ** sub-algorithm in some documentation.
    **
    ** If this is an auto-vacuum database, the call to copyNodeContent() 
    ** sets all pointer-map entries corresponding to database image pages 
    ** for which the pointer is stored within the content being copied.
    **
    ** The second assert below verifies that the child page is defragmented
    ** (it must be, as it was just reconstructed using assemblePage()). This
    ** is important if the parent page happens to be page 1 of the database
    ** image.  */
    assert( nNew==1 );
    assert( apNew[0]->nFree == 
        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
    );
    copyNodeContent(apNew[0], pParent, &rc);
    freePage(apNew[0], &rc);
  }else if( ISAUTOVACUUM ){
    /* Fix the pointer-map entries for all the cells that were shifted around. 
    ** There are several different types of pointer-map entries that need to
    ** be dealt with by this routine. Some of these have been set already, but
    ** many have not. The following is a summary:
    **
    **   1) The entries associated with new sibling pages that were not
    **      siblings when this function was called. These have already
    **      been set. We don't need to worry about old siblings that were
    **      moved to the free-list - the freePage() code has taken care
    **      of those.
    **
    **   2) The pointer-map entries associated with the first overflow
    **      page in any overflow chains used by new divider cells. These 
    **      have also already been taken care of by the insertCell() code.
    **
    **   3) If the sibling pages are not leaves, then the child pages of
    **      cells stored on the sibling pages may need to be updated.
    **
    **   4) If the sibling pages are not internal intkey nodes, then any
    **      overflow pages used by these cells may need to be updated
    **      (internal intkey nodes never contain pointers to overflow pages).
    **
    **   5) If the sibling pages are not leaves, then the pointer-map
    **      entries for the right-child pages of each sibling may need
    **      to be updated.
    **
    ** Cases 1 and 2 are dealt with above by other code. The next
    ** block deals with cases 3 and 4 and the one after that, case 5. Since
    ** setting a pointer map entry is a relatively expensive operation, this
    ** code only sets pointer map entries for child or overflow pages that have
    ** actually moved between pages.  */
    MemPage *pNew = apNew[0];
    MemPage *pOld = apCopy[0];
    int nOverflow = pOld->nOverflow;
    int iNextOld = pOld->nCell + nOverflow;
    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
    j = 0;                             /* Current 'old' sibling page */
    k = 0;                             /* Current 'new' sibling page */
    for(i=0; i<nCell; i++){
      int isDivider = 0;
      while( i==iNextOld ){
        /* Cell i is the cell immediately following the last cell on old
        ** sibling page j. If the siblings are not leaf pages of an
        ** intkey b-tree, then cell i was a divider cell. */
        pOld = apCopy[++j];
        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
        if( pOld->nOverflow ){
          nOverflow = pOld->nOverflow;
          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
        }
        isDivider = !leafData;  
      }

      assert(nOverflow>0 || iOverflow<i );
      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
      if( i==iOverflow ){
        isDivider = 1;
        if( (--nOverflow)>0 ){
          iOverflow++;
        }
      }

      if( i==cntNew[k] ){
        /* Cell i is the cell immediately following the last cell on new
        ** sibling page k. If the siblings are not leaf pages of an
        ** intkey b-tree, then cell i is a divider cell.  */
        pNew = apNew[++k];
        if( !leafData ) continue;
      }
      assert( j<nOld );
      assert( k<nNew );

      /* If the cell was originally divider cell (and is not now) or
      ** an overflow cell, or if the cell was located on a different sibling
      ** page before the balancing, then the pointer map entries associated
      ** with any child or overflow pages need to be updated.  */
      if( isDivider || pOld->pgno!=pNew->pgno ){
        if( !leafCorrection ){
          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
        }
        if( szCell[i]>pNew->minLocal ){
          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
        }
      }
    }

    if( !leafCorrection ){
      for(i=0; i<nNew; i++){
        u32 key = get4byte(&apNew[i]->aData[8]);
        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
      }
    }

#if 0
    /* The ptrmapCheckPages() contains assert() statements that verify that
    ** all pointer map pages are set correctly. This is helpful while 
    ** debugging. This is usually disabled because a corrupt database may
    ** cause an assert() statement to fail.  */
    ptrmapCheckPages(apNew, nNew);
    ptrmapCheckPages(&pParent, 1);
#endif
  }

  assert( pParent->isInit );
  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
          nOld, nNew, nCell));

  /*
  ** Cleanup before returning.
  */
balance_cleanup:
  sqlite3ScratchFree(apCell);
  for(i=0; i<nOld; i++){
    releasePage(apOld[i]);
  }
  for(i=0; i<nNew; i++){
    releasePage(apNew[i]);
  }

  return rc;
}


/*
** This function is called when the root page of a b-tree structure is
** overfull (has one or more overflow pages).
**
** A new child page is allocated and the contents of the current root
** page, including overflow cells, are copied into the child. The root
** page is then overwritten to make it an empty page with the right-child 
** pointer pointing to the new page.
**
** Before returning, all pointer-map entries corresponding to pages 
** that the new child-page now contains pointers to are updated. The
** entry corresponding to the new right-child pointer of the root
** page is also updated.
**
** If successful, *ppChild is set to contain a reference to the child 
** page and SQLITE_OK is returned. In this case the caller is required
** to call releasePage() on *ppChild exactly once. If an error occurs,
** an error code is returned and *ppChild is set to 0.
*/
static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  int rc;                        /* Return value from subprocedures */
  MemPage *pChild = 0;           /* Pointer to a new child page */
  Pgno pgnoChild = 0;            /* Page number of the new child page */
  BtShared *pBt = pRoot->pBt;    /* The BTree */

  assert( pRoot->nOverflow>0 );
  assert( sqlite3_mutex_held(pBt->mutex) );

  /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
  ** page that will become the new right-child of pPage. Copy the contents
  ** of the node stored on pRoot into the new child page.
  */
  rc = sqlite3PagerWrite(pRoot->pDbPage);
  if( rc==SQLITE_OK ){
    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
    copyNodeContent(pRoot, pChild, &rc);
    if( ISAUTOVACUUM ){
      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
    }
  }
  if( rc ){
    *ppChild = 0;
    releasePage(pChild);
    return rc;
  }
  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  assert( pChild->nCell==pRoot->nCell );

  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));

  /* Copy the overflow cells from pRoot to pChild */
  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
  pChild->nOverflow = pRoot->nOverflow;

  /* Zero the contents of pRoot. Then install pChild as the right-child. */
  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);

  *ppChild = pChild;
  return SQLITE_OK;
}

/*
** The page that pCur currently points to has just been modified in
** some way. This function figures out if this modification means the
** tree needs to be balanced, and if so calls the appropriate balancing 
** routine. Balancing routines are:
**
**   balance_quick()
**   balance_deeper()
**   balance_nonroot()
*/
static int balance(BtCursor *pCur){
  int rc = SQLITE_OK;
  const int nMin = pCur->pBt->usableSize * 2 / 3;
  u8 aBalanceQuickSpace[13];
  u8 *pFree = 0;

  TESTONLY( int balance_quick_called = 0 );
  TESTONLY( int balance_deeper_called = 0 );

  do {
    int iPage = pCur->iPage;
    MemPage *pPage = pCur->apPage[iPage];

    if( iPage==0 ){
      if( pPage->nOverflow ){
        /* The root page of the b-tree is overfull. In this case call the
        ** balance_deeper() function to create a new child for the root-page
        ** and copy the current contents of the root-page to it. The
        ** next iteration of the do-loop will balance the child page.
        */ 
        assert( (balance_deeper_called++)==0 );
        rc = balance_deeper(pPage, &pCur->apPage[1]);
        if( rc==SQLITE_OK ){
          pCur->iPage = 1;
          pCur->aiIdx[0] = 0;
          pCur->aiIdx[1] = 0;
          assert( pCur->apPage[1]->nOverflow );
        }
      }else{
        break;
      }
    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
      break;
    }else{
      MemPage * const pParent = pCur->apPage[iPage-1];
      int const iIdx = pCur->aiIdx[iPage-1];

      rc = sqlite3PagerWrite(pParent->pDbPage);
      if( rc==SQLITE_OK ){
#ifndef SQLITE_OMIT_QUICKBALANCE
        if( pPage->hasData
         && pPage->nOverflow==1
         && pPage->aOvfl[0].idx==pPage->nCell
         && pParent->pgno!=1
         && pParent->nCell==iIdx
        ){
          /* Call balance_quick() to create a new sibling of pPage on which
          ** to store the overflow cell. balance_quick() inserts a new cell
          ** into pParent, which may cause pParent overflow. If this
          ** happens, the next interation of the do-loop will balance pParent 
          ** use either balance_nonroot() or balance_deeper(). Until this
          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
          ** buffer. 
          **
          ** The purpose of the following assert() is to check that only a
          ** single call to balance_quick() is made for each call to this
          ** function. If this were not verified, a subtle bug involving reuse
          ** of the aBalanceQuickSpace[] might sneak in.
          */
          assert( (balance_quick_called++)==0 );
          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
        }else
#endif
        {
          /* In this case, call balance_nonroot() to redistribute cells
          ** between pPage and up to 2 of its sibling pages. This involves
          ** modifying the contents of pParent, which may cause pParent to
          ** become overfull or underfull. The next iteration of the do-loop
          ** will balance the parent page to correct this.
          ** 
          ** If the parent page becomes overfull, the overflow cell or cells
          ** are stored in the pSpace buffer allocated immediately below. 
          ** A subsequent iteration of the do-loop will deal with this by
          ** calling balance_nonroot() (balance_deeper() may be called first,
          ** but it doesn't deal with overflow cells - just moves them to a
          ** different page). Once this subsequent call to balance_nonroot() 
          ** has completed, it is safe to release the pSpace buffer used by
          ** the previous call, as the overflow cell data will have been 
          ** copied either into the body of a database page or into the new
          ** pSpace buffer passed to the latter call to balance_nonroot().
          */
          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
          if( pFree ){
            /* If pFree is not NULL, it points to the pSpace buffer used 
            ** by a previous call to balance_nonroot(). Its contents are
            ** now stored either on real database pages or within the 
            ** new pSpace buffer, so it may be safely freed here. */
            sqlite3PageFree(pFree);
          }

          /* The pSpace buffer will be freed after the next call to
          ** balance_nonroot(), or just before this function returns, whichever
          ** comes first. */
          pFree = pSpace;
        }
      }

      pPage->nOverflow = 0;

      /* The next iteration of the do-loop balances the parent page. */
      releasePage(pPage);
      pCur->iPage--;
    }
  }while( rc==SQLITE_OK );

  if( pFree ){
    sqlite3PageFree(pFree);
  }
  return rc;
}


/*
** Insert a new record into the BTree.  The key is given by (pKey,nKey)
** and the data is given by (pData,nData).  The cursor is used only to
** define what table the record should be inserted into.  The cursor
** is left pointing at a random location.
**
** For an INTKEY table, only the nKey value of the key is used.  pKey is
** ignored.  For a ZERODATA table, the pData and nData are both ignored.
**
** If the seekResult parameter is non-zero, then a successful call to
** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
** been performed. seekResult is the search result returned (a negative
** number if pCur points at an entry that is smaller than (pKey, nKey), or
** a positive value if pCur points at an etry that is larger than 
** (pKey, nKey)). 
**
** If the seekResult parameter is non-zero, then the caller guarantees that
** cursor pCur is pointing at the existing copy of a row that is to be
** overwritten.  If the seekResult parameter is 0, then cursor pCur may
** point to any entry or to no entry at all and so this function has to seek
** the cursor before the new key can be inserted.
*/
int sqlite3BtreeInsert(
  BtCursor *pCur,                /* Insert data into the table of this cursor */
  const void *pKey, i64 nKey,    /* The key of the new record */
  const void *pData, int nData,  /* The data of the new record */
  int nZero,                     /* Number of extra 0 bytes to append to data */
  int appendBias,                /* True if this is likely an append */
  int seekResult                 /* Result of prior MovetoUnpacked() call */
){
  int rc;
  int loc = seekResult;          /* -1: before desired location  +1: after */
  int szNew = 0;
  int idx;
  MemPage *pPage;
  Btree *p = pCur->pBtree;
  BtShared *pBt = p->pBt;
  unsigned char *oldCell;
  unsigned char *newCell = 0;

  if( pCur->eState==CURSOR_FAULT ){
    assert( pCur->skipNext!=SQLITE_OK );
    return pCur->skipNext;
  }

  assert( cursorHoldsMutex(pCur) );
  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );

  /* Assert that the caller has been consistent. If this cursor was opened
  ** expecting an index b-tree, then the caller should be inserting blob
  ** keys with no associated data. If the cursor was opened expecting an
  ** intkey table, the caller should be inserting integer keys with a
  ** blob of associated data.  */
  assert( (pKey==0)==(pCur->pKeyInfo==0) );

  /* If this is an insert into a table b-tree, invalidate any incrblob 
  ** cursors open on the row being replaced (assuming this is a replace
  ** operation - if it is not, the following is a no-op).  */
  if( pCur->pKeyInfo==0 ){
    invalidateIncrblobCursors(p, nKey, 0);
  }

  /* Save the positions of any other cursors open on this table.
  **
  ** In some cases, the call to btreeMoveto() below is a no-op. For
  ** example, when inserting data into a table with auto-generated integer
  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
  ** integer key to use. It then calls this function to actually insert the 
  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  ** that the cursor is already where it needs to be and returns without
  ** doing any work. To avoid thwarting these optimizations, it is important
  ** not to clear the cursor here.
  */
  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  if( rc ) return rc;
  if( !loc ){
    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
    if( rc ) return rc;
  }
  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );

  pPage = pCur->apPage[pCur->iPage];
  assert( pPage->intKey || nKey>=0 );
  assert( pPage->leaf || !pPage->intKey );

  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
          pCur->pgnoRoot, nKey, nData, pPage->pgno,
          loc==0 ? "overwrite" : "new entry"));
  assert( pPage->isInit );
  allocateTempSpace(pBt);
  newCell = pBt->pTmpSpace;
  if( newCell==0 ) return SQLITE_NOMEM;
  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  if( rc ) goto end_insert;
  assert( szNew==cellSizePtr(pPage, newCell) );
  assert( szNew<=MX_CELL_SIZE(pBt) );
  idx = pCur->aiIdx[pCur->iPage];
  if( loc==0 ){
    u16 szOld;
    assert( idx<pPage->nCell );
    rc = sqlite3PagerWrite(pPage->pDbPage);
    if( rc ){
      goto end_insert;
    }
    oldCell = findCell(pPage, idx);
    if( !pPage->leaf ){
      memcpy(newCell, oldCell, 4);
    }
    szOld = cellSizePtr(pPage, oldCell);
    rc = clearCell(pPage, oldCell);
    dropCell(pPage, idx, szOld, &rc);
    if( rc ) goto end_insert;
  }else if( loc<0 && pPage->nCell>0 ){
    assert( pPage->leaf );
    idx = ++pCur->aiIdx[pCur->iPage];
  }else{
    assert( pPage->leaf );
  }
  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );

  /* If no error has occured and pPage has an overflow cell, call balance() 
  ** to redistribute the cells within the tree. Since balance() may move
  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  ** variables.
  **
  ** Previous versions of SQLite called moveToRoot() to move the cursor
  ** back to the root page as balance() used to invalidate the contents
  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  ** set the cursor state to "invalid". This makes common insert operations
  ** slightly faster.
  **
  ** There is a subtle but important optimization here too. When inserting
  ** multiple records into an intkey b-tree using a single cursor (as can
  ** happen while processing an "INSERT INTO ... SELECT" statement), it
  ** is advantageous to leave the cursor pointing to the last entry in
  ** the b-tree if possible. If the cursor is left pointing to the last
  ** entry in the table, and the next row inserted has an integer key
  ** larger than the largest existing key, it is possible to insert the
  ** row without seeking the cursor. This can be a big performance boost.
  */
  pCur->info.nSize = 0;
  pCur->validNKey = 0;
  if( rc==SQLITE_OK && pPage->nOverflow ){
    rc = balance(pCur);

    /* Must make sure nOverflow is reset to zero even if the balance()
    ** fails. Internal data structure corruption will result otherwise. 
    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
    ** from trying to save the current position of the cursor.  */
    pCur->apPage[pCur->iPage]->nOverflow = 0;
    pCur->eState = CURSOR_INVALID;
  }
  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );

end_insert:
  return rc;
}

/*
** Delete the entry that the cursor is pointing to.  The cursor
** is left pointing at a arbitrary location.
*/
int sqlite3BtreeDelete(BtCursor *pCur){
  Btree *p = pCur->pBtree;
  BtShared *pBt = p->pBt;              
  int rc;                              /* Return code */
  MemPage *pPage;                      /* Page to delete cell from */
  unsigned char *pCell;                /* Pointer to cell to delete */
  int iCellIdx;                        /* Index of cell to delete */
  int iCellDepth;                      /* Depth of node containing pCell */ 

  assert( cursorHoldsMutex(pCur) );
  assert( pBt->inTransaction==TRANS_WRITE );
  assert( !pBt->readOnly );
  assert( pCur->wrFlag );
  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  assert( !hasReadConflicts(p, pCur->pgnoRoot) );

  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
   || NEVER(pCur->eState!=CURSOR_VALID)
  ){
    return SQLITE_ERROR;  /* Something has gone awry. */
  }

  /* If this is a delete operation to remove a row from a table b-tree,
  ** invalidate any incrblob cursors open on the row being deleted.  */
  if( pCur->pKeyInfo==0 ){
    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  }

  iCellDepth = pCur->iPage;
  iCellIdx = pCur->aiIdx[iCellDepth];
  pPage = pCur->apPage[iCellDepth];
  pCell = findCell(pPage, iCellIdx);

  /* If the page containing the entry to delete is not a leaf page, move
  ** the cursor to the largest entry in the tree that is smaller than
  ** the entry being deleted. This cell will replace the cell being deleted
  ** from the internal node. The 'previous' entry is used for this instead
  ** of the 'next' entry, as the previous entry is always a part of the
  ** sub-tree headed by the child page of the cell being deleted. This makes
  ** balancing the tree following the delete operation easier.  */
  if( !pPage->leaf ){
    int notUsed;
    rc = sqlite3BtreePrevious(pCur, &notUsed);
    if( rc ) return rc;
  }

  /* Save the positions of any other cursors open on this table before
  ** making any modifications. Make the page containing the entry to be 
  ** deleted writable. Then free any overflow pages associated with the 
  ** entry and finally remove the cell itself from within the page.  
  */
  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  if( rc ) return rc;
  rc = sqlite3PagerWrite(pPage->pDbPage);
  if( rc ) return rc;
  rc = clearCell(pPage, pCell);
  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  if( rc ) return rc;

  /* If the cell deleted was not located on a leaf page, then the cursor
  ** is currently pointing to the largest entry in the sub-tree headed
  ** by the child-page of the cell that was just deleted from an internal
  ** node. The cell from the leaf node needs to be moved to the internal
  ** node to replace the deleted cell.  */
  if( !pPage->leaf ){
    MemPage *pLeaf = pCur->apPage[pCur->iPage];
    int nCell;
    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
    unsigned char *pTmp;

    pCell = findCell(pLeaf, pLeaf->nCell-1);
    nCell = cellSizePtr(pLeaf, pCell);
    assert( MX_CELL_SIZE(pBt)>=nCell );

    allocateTempSpace(pBt);
    pTmp = pBt->pTmpSpace;

    rc = sqlite3PagerWrite(pLeaf->pDbPage);
    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
    if( rc ) return rc;
  }

  /* Balance the tree. If the entry deleted was located on a leaf page,
  ** then the cursor still points to that page. In this case the first
  ** call to balance() repairs the tree, and the if(...) condition is
  ** never true.
  **
  ** Otherwise, if the entry deleted was on an internal node page, then
  ** pCur is pointing to the leaf page from which a cell was removed to
  ** replace the cell deleted from the internal node. This is slightly
  ** tricky as the leaf node may be underfull, and the internal node may
  ** be either under or overfull. In this case run the balancing algorithm
  ** on the leaf node first. If the balance proceeds far enough up the
  ** tree that we can be sure that any problem in the internal node has
  ** been corrected, so be it. Otherwise, after balancing the leaf node,
  ** walk the cursor up the tree to the internal node and balance it as 
  ** well.  */
  rc = balance(pCur);
  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
    while( pCur->iPage>iCellDepth ){
      releasePage(pCur->apPage[pCur->iPage--]);
    }
    rc = balance(pCur);
  }

  if( rc==SQLITE_OK ){
    moveToRoot(pCur);
  }
  return rc;
}

/*
** Create a new BTree table.  Write into *piTable the page
** number for the root page of the new table.
**
** The type of type is determined by the flags parameter.  Only the
** following values of flags are currently in use.  Other values for
** flags might not work:
**
**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
**     BTREE_ZERODATA                  Used for SQL indices
*/
static int btreeCreateTable(Btree *p, int *piTable, int flags){
  BtShared *pBt = p->pBt;
  MemPage *pRoot;
  Pgno pgnoRoot;
  int rc;

  assert( sqlite3BtreeHoldsMutex(p) );
  assert( pBt->inTransaction==TRANS_WRITE );
  assert( !pBt->readOnly );

#ifdef SQLITE_OMIT_AUTOVACUUM
  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  if( rc ){
    return rc;
  }
#else
  if( pBt->autoVacuum ){
    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
    MemPage *pPageMove; /* The page to move to. */

    /* Creating a new table may probably require moving an existing database
    ** to make room for the new tables root page. In case this page turns
    ** out to be an overflow page, delete all overflow page-map caches
    ** held by open cursors.
    */
    invalidateAllOverflowCache(pBt);

    /* Read the value of meta[3] from the database to determine where the
    ** root page of the new table should go. meta[3] is the largest root-page
    ** created so far, so the new root-page is (meta[3]+1).
    */
    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
    pgnoRoot++;

    /* The new root-page may not be allocated on a pointer-map page, or the
    ** PENDING_BYTE page.
    */
    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
      pgnoRoot++;
    }
    assert( pgnoRoot>=3 );

    /* Allocate a page. The page that currently resides at pgnoRoot will
    ** be moved to the allocated page (unless the allocated page happens
    ** to reside at pgnoRoot).
    */
    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
    if( rc!=SQLITE_OK ){
      return rc;
    }

    if( pgnoMove!=pgnoRoot ){
      /* pgnoRoot is the page that will be used for the root-page of
      ** the new table (assuming an error did not occur). But we were
      ** allocated pgnoMove. If required (i.e. if it was not allocated
      ** by extending the file), the current page at position pgnoMove
      ** is already journaled.
      */
      u8 eType = 0;
      Pgno iPtrPage = 0;

      releasePage(pPageMove);

      /* Move the page currently at pgnoRoot to pgnoMove. */
      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
      if( rc!=SQLITE_OK ){
        return rc;
      }
      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
        rc = SQLITE_CORRUPT_BKPT;
      }
      if( rc!=SQLITE_OK ){
        releasePage(pRoot);
        return rc;
      }
      assert( eType!=PTRMAP_ROOTPAGE );
      assert( eType!=PTRMAP_FREEPAGE );
      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
      releasePage(pRoot);

      /* Obtain the page at pgnoRoot */
      if( rc!=SQLITE_OK ){
        return rc;
      }
      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
      if( rc!=SQLITE_OK ){
        return rc;
      }
      rc = sqlite3PagerWrite(pRoot->pDbPage);
      if( rc!=SQLITE_OK ){
        releasePage(pRoot);
        return rc;
      }
    }else{
      pRoot = pPageMove;
    } 

    /* Update the pointer-map and meta-data with the new root-page number. */
    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
    if( rc ){
      releasePage(pRoot);
      return rc;
    }
    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
    if( rc ){
      releasePage(pRoot);
      return rc;
    }

  }else{
    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
    if( rc ) return rc;
  }
#endif
  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  zeroPage(pRoot, flags | PTF_LEAF);
  sqlite3PagerUnref(pRoot->pDbPage);
  *piTable = (int)pgnoRoot;
  return SQLITE_OK;
}
int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  int rc;
  sqlite3BtreeEnter(p);
  rc = btreeCreateTable(p, piTable, flags);
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** Erase the given database page and all its children.  Return
** the page to the freelist.
*/
static int clearDatabasePage(
  BtShared *pBt,           /* The BTree that contains the table */
  Pgno pgno,            /* Page number to clear */
  int freePageFlag,     /* Deallocate page if true */
  int *pnChange
){
  MemPage *pPage;
  int rc;
  unsigned char *pCell;
  int i;

  assert( sqlite3_mutex_held(pBt->mutex) );
  if( pgno>pagerPagecount(pBt) ){
    return SQLITE_CORRUPT_BKPT;
  }

  rc = getAndInitPage(pBt, pgno, &pPage);
  if( rc ) return rc;
  for(i=0; i<pPage->nCell; i++){
    pCell = findCell(pPage, i);
    if( !pPage->leaf ){
      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
      if( rc ) goto cleardatabasepage_out;
    }
    rc = clearCell(pPage, pCell);
    if( rc ) goto cleardatabasepage_out;
  }
  if( !pPage->leaf ){
    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
    if( rc ) goto cleardatabasepage_out;
  }else if( pnChange ){
    assert( pPage->intKey );
    *pnChange += pPage->nCell;
  }
  if( freePageFlag ){
    freePage(pPage, &rc);
  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  }

cleardatabasepage_out:
  releasePage(pPage);
  return rc;
}

/*
** Delete all information from a single table in the database.  iTable is
** the page number of the root of the table.  After this routine returns,
** the root page is empty, but still exists.
**
** This routine will fail with SQLITE_LOCKED if there are any open
** read cursors on the table.  Open write cursors are moved to the
** root of the table.
**
** If pnChange is not NULL, then table iTable must be an intkey table. The
** integer value pointed to by pnChange is incremented by the number of
** entries in the table.
*/
int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  int rc;
  BtShared *pBt = p->pBt;
  sqlite3BtreeEnter(p);
  assert( p->inTrans==TRANS_WRITE );

  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  ** is the root of a table b-tree - if it is not, the following call is
  ** a no-op).  */
  invalidateIncrblobCursors(p, 0, 1);

  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  if( SQLITE_OK==rc ){
    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  }
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** Erase all information in a table and add the root of the table to
** the freelist.  Except, the root of the principle table (the one on
** page 1) is never added to the freelist.
**
** This routine will fail with SQLITE_LOCKED if there are any open
** cursors on the table.
**
** If AUTOVACUUM is enabled and the page at iTable is not the last
** root page in the database file, then the last root page 
** in the database file is moved into the slot formerly occupied by
** iTable and that last slot formerly occupied by the last root page
** is added to the freelist instead of iTable.  In this say, all
** root pages are kept at the beginning of the database file, which
** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
** page number that used to be the last root page in the file before
** the move.  If no page gets moved, *piMoved is set to 0.
** The last root page is recorded in meta[3] and the value of
** meta[3] is updated by this procedure.
*/
static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  int rc;
  MemPage *pPage = 0;
  BtShared *pBt = p->pBt;

  assert( sqlite3BtreeHoldsMutex(p) );
  assert( p->inTrans==TRANS_WRITE );

  /* It is illegal to drop a table if any cursors are open on the
  ** database. This is because in auto-vacuum mode the backend may
  ** need to move another root-page to fill a gap left by the deleted
  ** root page. If an open cursor was using this page a problem would 
  ** occur.
  **
  ** This error is caught long before control reaches this point.
  */
  if( NEVER(pBt->pCursor) ){
    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
    return SQLITE_LOCKED_SHAREDCACHE;
  }

  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  if( rc ) return rc;
  rc = sqlite3BtreeClearTable(p, iTable, 0);
  if( rc ){
    releasePage(pPage);
    return rc;
  }

  *piMoved = 0;

  if( iTable>1 ){
#ifdef SQLITE_OMIT_AUTOVACUUM
    freePage(pPage, &rc);
    releasePage(pPage);
#else
    if( pBt->autoVacuum ){
      Pgno maxRootPgno;
      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);

      if( iTable==maxRootPgno ){
        /* If the table being dropped is the table with the largest root-page
        ** number in the database, put the root page on the free list. 
        */
        freePage(pPage, &rc);
        releasePage(pPage);
        if( rc!=SQLITE_OK ){
          return rc;
        }
      }else{
        /* The table being dropped does not have the largest root-page
        ** number in the database. So move the page that does into the 
        ** gap left by the deleted root-page.
        */
        MemPage *pMove;
        releasePage(pPage);
        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
        if( rc!=SQLITE_OK ){
          return rc;
        }
        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
        releasePage(pMove);
        if( rc!=SQLITE_OK ){
          return rc;
        }
        pMove = 0;
        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
        freePage(pMove, &rc);
        releasePage(pMove);
        if( rc!=SQLITE_OK ){
          return rc;
        }
        *piMoved = maxRootPgno;
      }

      /* Set the new 'max-root-page' value in the database header. This
      ** is the old value less one, less one more if that happens to
      ** be a root-page number, less one again if that is the
      ** PENDING_BYTE_PAGE.
      */
      maxRootPgno--;
      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
        maxRootPgno--;
      }
      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );

      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
    }else{
      freePage(pPage, &rc);
      releasePage(pPage);
    }
#endif
  }else{
    /* If sqlite3BtreeDropTable was called on page 1.
    ** This really never should happen except in a corrupt
    ** database. 
    */
    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
    releasePage(pPage);
  }
  return rc;  
}
int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  int rc;
  sqlite3BtreeEnter(p);
  rc = btreeDropTable(p, iTable, piMoved);
  sqlite3BtreeLeave(p);
  return rc;
}


/*
** This function may only be called if the b-tree connection already
** has a read or write transaction open on the database.
**
** Read the meta-information out of a database file.  Meta[0]
** is the number of free pages currently in the database.  Meta[1]
** through meta[15] are available for use by higher layers.  Meta[0]
** is read-only, the others are read/write.
** 
** The schema layer numbers meta values differently.  At the schema
** layer (and the SetCookie and ReadCookie opcodes) the number of
** free pages is not visible.  So Cookie[0] is the same as Meta[1].
*/
void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  BtShared *pBt = p->pBt;

  sqlite3BtreeEnter(p);
  assert( p->inTrans>TRANS_NONE );
  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  assert( pBt->pPage1 );
  assert( idx>=0 && idx<=15 );

  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);

  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  ** database, mark the database as read-only.  */
#ifdef SQLITE_OMIT_AUTOVACUUM
  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
#endif

  sqlite3BtreeLeave(p);
}

/*
** Write meta-information back into the database.  Meta[0] is
** read-only and may not be written.
*/
int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  BtShared *pBt = p->pBt;
  unsigned char *pP1;
  int rc;
  assert( idx>=1 && idx<=15 );
  sqlite3BtreeEnter(p);
  assert( p->inTrans==TRANS_WRITE );
  assert( pBt->pPage1!=0 );
  pP1 = pBt->pPage1->aData;
  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  if( rc==SQLITE_OK ){
    put4byte(&pP1[36 + idx*4], iMeta);
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( idx==BTREE_INCR_VACUUM ){
      assert( pBt->autoVacuum || iMeta==0 );
      assert( iMeta==0 || iMeta==1 );
      pBt->incrVacuum = (u8)iMeta;
    }
#endif
  }
  sqlite3BtreeLeave(p);
  return rc;
}

#ifndef SQLITE_OMIT_BTREECOUNT
/*
** The first argument, pCur, is a cursor opened on some b-tree. Count the
** number of entries in the b-tree and write the result to *pnEntry.
**
** SQLITE_OK is returned if the operation is successfully executed. 
** Otherwise, if an error is encountered (i.e. an IO error or database
** corruption) an SQLite error code is returned.
*/
int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  i64 nEntry = 0;                      /* Value to return in *pnEntry */
  int rc;                              /* Return code */
  rc = moveToRoot(pCur);

  /* Unless an error occurs, the following loop runs one iteration for each
  ** page in the B-Tree structure (not including overflow pages). 
  */
  while( rc==SQLITE_OK ){
    int iIdx;                          /* Index of child node in parent */
    MemPage *pPage;                    /* Current page of the b-tree */

    /* If this is a leaf page or the tree is not an int-key tree, then 
    ** this page contains countable entries. Increment the entry counter
    ** accordingly.
    */
    pPage = pCur->apPage[pCur->iPage];
    if( pPage->leaf || !pPage->intKey ){
      nEntry += pPage->nCell;
    }

    /* pPage is a leaf node. This loop navigates the cursor so that it 
    ** points to the first interior cell that it points to the parent of
    ** the next page in the tree that has not yet been visited. The
    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
    ** of the page, or to the number of cells in the page if the next page
    ** to visit is the right-child of its parent.
    **
    ** If all pages in the tree have been visited, return SQLITE_OK to the
    ** caller.
    */
    if( pPage->leaf ){
      do {
        if( pCur->iPage==0 ){
          /* All pages of the b-tree have been visited. Return successfully. */
          *pnEntry = nEntry;
          return SQLITE_OK;
        }
        moveToParent(pCur);
      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );

      pCur->aiIdx[pCur->iPage]++;
      pPage = pCur->apPage[pCur->iPage];
    }

    /* Descend to the child node of the cell that the cursor currently 
    ** points at. This is the right-child if (iIdx==pPage->nCell).
    */
    iIdx = pCur->aiIdx[pCur->iPage];
    if( iIdx==pPage->nCell ){
      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
    }else{
      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
    }
  }

  /* An error has occurred. Return an error code. */
  return rc;
}
#endif

/*
** Return the pager associated with a BTree.  This routine is used for
** testing and debugging only.
*/
Pager *sqlite3BtreePager(Btree *p){
  return p->pBt->pPager;
}

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/*
** Append a message to the error message string.
*/
static void checkAppendMsg(
  IntegrityCk *pCheck,
  char *zMsg1,
  const char *zFormat,
  ...
){
  va_list ap;
  if( !pCheck->mxErr ) return;
  pCheck->mxErr--;
  pCheck->nErr++;
  va_start(ap, zFormat);
  if( pCheck->errMsg.nChar ){
    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  }
  if( zMsg1 ){
    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  }
  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  va_end(ap);
  if( pCheck->errMsg.mallocFailed ){
    pCheck->mallocFailed = 1;
  }
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/*
** Add 1 to the reference count for page iPage.  If this is the second
** reference to the page, add an error message to pCheck->zErrMsg.
** Return 1 if there are 2 ore more references to the page and 0 if
** if this is the first reference to the page.
**
** Also check that the page number is in bounds.
*/
static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  if( iPage==0 ) return 1;
  if( iPage>pCheck->nPage ){
    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
    return 1;
  }
  if( pCheck->anRef[iPage]==1 ){
    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
    return 1;
  }
  return  (pCheck->anRef[iPage]++)>1;
}

#ifndef SQLITE_OMIT_AUTOVACUUM
/*
** Check that the entry in the pointer-map for page iChild maps to 
** page iParent, pointer type ptrType. If not, append an error message
** to pCheck.
*/
static void checkPtrmap(
  IntegrityCk *pCheck,   /* Integrity check context */
  Pgno iChild,           /* Child page number */
  u8 eType,              /* Expected pointer map type */
  Pgno iParent,          /* Expected pointer map parent page number */
  char *zContext         /* Context description (used for error msg) */
){
  int rc;
  u8 ePtrmapType;
  Pgno iPtrmapParent;

  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
    return;
  }

  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
    checkAppendMsg(pCheck, zContext, 
      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  }
}
#endif

/*
** Check the integrity of the freelist or of an overflow page list.
** Verify that the number of pages on the list is N.
*/
static void checkList(
  IntegrityCk *pCheck,  /* Integrity checking context */
  int isFreeList,       /* True for a freelist.  False for overflow page list */
  int iPage,            /* Page number for first page in the list */
  int N,                /* Expected number of pages in the list */
  char *zContext        /* Context for error messages */
){
  int i;
  int expected = N;
  int iFirst = iPage;
  while( N-- > 0 && pCheck->mxErr ){
    DbPage *pOvflPage;
    unsigned char *pOvflData;
    if( iPage<1 ){
      checkAppendMsg(pCheck, zContext,
         "%d of %d pages missing from overflow list starting at %d",
          N+1, expected, iFirst);
      break;
    }
    if( checkRef(pCheck, iPage, zContext) ) break;
    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
      break;
    }
    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
    if( isFreeList ){
      int n = get4byte(&pOvflData[4]);
#ifndef SQLITE_OMIT_AUTOVACUUM
      if( pCheck->pBt->autoVacuum ){
        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
      }
#endif
      if( n>pCheck->pBt->usableSize/4-2 ){
        checkAppendMsg(pCheck, zContext,
           "freelist leaf count too big on page %d", iPage);
        N--;
      }else{
        for(i=0; i<n; i++){
          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
#ifndef SQLITE_OMIT_AUTOVACUUM
          if( pCheck->pBt->autoVacuum ){
            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
          }
#endif
          checkRef(pCheck, iFreePage, zContext);
        }
        N -= n;
      }
    }
#ifndef SQLITE_OMIT_AUTOVACUUM
    else{
      /* If this database supports auto-vacuum and iPage is not the last
      ** page in this overflow list, check that the pointer-map entry for
      ** the following page matches iPage.
      */
      if( pCheck->pBt->autoVacuum && N>0 ){
        i = get4byte(pOvflData);
        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
      }
    }
#endif
    iPage = get4byte(pOvflData);
    sqlite3PagerUnref(pOvflPage);
  }
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/*
** Do various sanity checks on a single page of a tree.  Return
** the tree depth.  Root pages return 0.  Parents of root pages
** return 1, and so forth.
** 
** These checks are done:
**
**      1.  Make sure that cells and freeblocks do not overlap
**          but combine to completely cover the page.
**  NO  2.  Make sure cell keys are in order.
**  NO  3.  Make sure no key is less than or equal to zLowerBound.
**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
**      5.  Check the integrity of overflow pages.
**      6.  Recursively call checkTreePage on all children.
**      7.  Verify that the depth of all children is the same.
**      8.  Make sure this page is at least 33% full or else it is
**          the root of the tree.
*/
static int checkTreePage(
  IntegrityCk *pCheck,  /* Context for the sanity check */
  int iPage,            /* Page number of the page to check */
  char *zParentContext  /* Parent context */
){
  MemPage *pPage;
  int i, rc, depth, d2, pgno, cnt;
  int hdr, cellStart;
  int nCell;
  u8 *data;
  BtShared *pBt;
  int usableSize;
  char zContext[100];
  char *hit = 0;

  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);

  /* Check that the page exists
  */
  pBt = pCheck->pBt;
  usableSize = pBt->usableSize;
  if( iPage==0 ) return 0;
  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
    checkAppendMsg(pCheck, zContext,
       "unable to get the page. error code=%d", rc);
    return 0;
  }

  /* Clear MemPage.isInit to make sure the corruption detection code in
  ** btreeInitPage() is executed.  */
  pPage->isInit = 0;
  if( (rc = btreeInitPage(pPage))!=0 ){
    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
    checkAppendMsg(pCheck, zContext, 
                   "btreeInitPage() returns error code %d", rc);
    releasePage(pPage);
    return 0;
  }

  /* Check out all the cells.
  */
  depth = 0;
  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
    u8 *pCell;
    u32 sz;
    CellInfo info;

    /* Check payload overflow pages
    */
    sqlite3_snprintf(sizeof(zContext), zContext,
             "On tree page %d cell %d: ", iPage, i);
    pCell = findCell(pPage,i);
    btreeParseCellPtr(pPage, pCell, &info);
    sz = info.nData;
    if( !pPage->intKey ) sz += (int)info.nKey;
    assert( sz==info.nPayload );
    if( (sz>info.nLocal) 
     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
    ){
      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
#ifndef SQLITE_OMIT_AUTOVACUUM
      if( pBt->autoVacuum ){
        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
      }
#endif
      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
    }

    /* Check sanity of left child page.
    */
    if( !pPage->leaf ){
      pgno = get4byte(pCell);
#ifndef SQLITE_OMIT_AUTOVACUUM
      if( pBt->autoVacuum ){
        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
      }
#endif
      d2 = checkTreePage(pCheck, pgno, zContext);
      if( i>0 && d2!=depth ){
        checkAppendMsg(pCheck, zContext, "Child page depth differs");
      }
      depth = d2;
    }
  }
  if( !pPage->leaf ){
    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
    sqlite3_snprintf(sizeof(zContext), zContext, 
                     "On page %d at right child: ", iPage);
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum ){
      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
    }
#endif
    checkTreePage(pCheck, pgno, zContext);
  }
 
  /* Check for complete coverage of the page
  */
  data = pPage->aData;
  hdr = pPage->hdrOffset;
  hit = sqlite3PageMalloc( pBt->pageSize );
  if( hit==0 ){
    pCheck->mallocFailed = 1;
  }else{
    u16 contentOffset = get2byte(&data[hdr+5]);
    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
    memset(hit+contentOffset, 0, usableSize-contentOffset);
    memset(hit, 1, contentOffset);
    nCell = get2byte(&data[hdr+3]);
    cellStart = hdr + 12 - 4*pPage->leaf;
    for(i=0; i<nCell; i++){
      int pc = get2byte(&data[cellStart+i*2]);
      u16 size = 1024;
      int j;
      if( pc<=usableSize-4 ){
        size = cellSizePtr(pPage, &data[pc]);
      }
      if( (pc+size-1)>=usableSize ){
        checkAppendMsg(pCheck, 0, 
            "Corruption detected in cell %d on page %d",i,iPage,0);
      }else{
        for(j=pc+size-1; j>=pc; j--) hit[j]++;
      }
    }
    i = get2byte(&data[hdr+1]);
    while( i>0 ){
      int size, j;
      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
      size = get2byte(&data[i+2]);
      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
      for(j=i+size-1; j>=i; j--) hit[j]++;
      j = get2byte(&data[i]);
      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
      i = j;
    }
    for(i=cnt=0; i<usableSize; i++){
      if( hit[i]==0 ){
        cnt++;
      }else if( hit[i]>1 ){
        checkAppendMsg(pCheck, 0,
          "Multiple uses for byte %d of page %d", i, iPage);
        break;
      }
    }
    if( cnt!=data[hdr+7] ){
      checkAppendMsg(pCheck, 0, 
          "Fragmentation of %d bytes reported as %d on page %d",
          cnt, data[hdr+7], iPage);
    }
  }
  sqlite3PageFree(hit);
  releasePage(pPage);
  return depth+1;
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/*
** This routine does a complete check of the given BTree file.  aRoot[] is
** an array of pages numbers were each page number is the root page of
** a table.  nRoot is the number of entries in aRoot.
**
** A read-only or read-write transaction must be opened before calling
** this function.
**
** Write the number of error seen in *pnErr.  Except for some memory
** allocation errors,  an error message held in memory obtained from
** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
** returned.  If a memory allocation error occurs, NULL is returned.
*/
char *sqlite3BtreeIntegrityCheck(
  Btree *p,     /* The btree to be checked */
  int *aRoot,   /* An array of root pages numbers for individual trees */
  int nRoot,    /* Number of entries in aRoot[] */
  int mxErr,    /* Stop reporting errors after this many */
  int *pnErr    /* Write number of errors seen to this variable */
){
  Pgno i;
  int nRef;
  IntegrityCk sCheck;
  BtShared *pBt = p->pBt;
  char zErr[100];

  sqlite3BtreeEnter(p);
  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  nRef = sqlite3PagerRefcount(pBt->pPager);
  sCheck.pBt = pBt;
  sCheck.pPager = pBt->pPager;
  sCheck.nPage = pagerPagecount(sCheck.pBt);
  sCheck.mxErr = mxErr;
  sCheck.nErr = 0;
  sCheck.mallocFailed = 0;
  *pnErr = 0;
  if( sCheck.nPage==0 ){
    sqlite3BtreeLeave(p);
    return 0;
  }
  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
  if( !sCheck.anRef ){
    *pnErr = 1;
    sqlite3BtreeLeave(p);
    return 0;
  }
  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
  i = PENDING_BYTE_PAGE(pBt);
  if( i<=sCheck.nPage ){
    sCheck.anRef[i] = 1;
  }
  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);

  /* Check the integrity of the freelist
  */
  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");

  /* Check all the tables.
  */
  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
    if( aRoot[i]==0 ) continue;
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum && aRoot[i]>1 ){
      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
    }
#endif
    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
  }

  /* Make sure every page in the file is referenced
  */
  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
#ifdef SQLITE_OMIT_AUTOVACUUM
    if( sCheck.anRef[i]==0 ){
      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
    }
#else
    /* If the database supports auto-vacuum, make sure no tables contain
    ** references to pointer-map pages.
    */
    if( sCheck.anRef[i]==0 && 
       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
    }
    if( sCheck.anRef[i]!=0 && 
       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
    }
#endif
  }

  /* Make sure this analysis did not leave any unref() pages.
  ** This is an internal consistency check; an integrity check
  ** of the integrity check.
  */
  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
    checkAppendMsg(&sCheck, 0, 
      "Outstanding page count goes from %d to %d during this analysis",
      nRef, sqlite3PagerRefcount(pBt->pPager)
    );
  }

  /* Clean  up and report errors.
  */
  sqlite3BtreeLeave(p);
  sqlite3_free(sCheck.anRef);
  if( sCheck.mallocFailed ){
    sqlite3StrAccumReset(&sCheck.errMsg);
    *pnErr = sCheck.nErr+1;
    return 0;
  }
  *pnErr = sCheck.nErr;
  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  return sqlite3StrAccumFinish(&sCheck.errMsg);
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

/*
** Return the full pathname of the underlying database file.
**
** The pager filename is invariant as long as the pager is
** open so it is safe to access without the BtShared mutex.
*/
const char *sqlite3BtreeGetFilename(Btree *p){
  assert( p->pBt->pPager!=0 );
  return sqlite3PagerFilename(p->pBt->pPager);
}

/*
** Return the pathname of the journal file for this database. The return
** value of this routine is the same regardless of whether the journal file
** has been created or not.
**
** The pager journal filename is invariant as long as the pager is
** open so it is safe to access without the BtShared mutex.
*/
const char *sqlite3BtreeGetJournalname(Btree *p){
  assert( p->pBt->pPager!=0 );
  return sqlite3PagerJournalname(p->pBt->pPager);
}

/*
** Return non-zero if a transaction is active.
*/
int sqlite3BtreeIsInTrans(Btree *p){
  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  return (p && (p->inTrans==TRANS_WRITE));
}

/*
** Return non-zero if a read (or write) transaction is active.
*/
int sqlite3BtreeIsInReadTrans(Btree *p){
  assert( p );
  assert( sqlite3_mutex_held(p->db->mutex) );
  return p->inTrans!=TRANS_NONE;
}

int sqlite3BtreeIsInBackup(Btree *p){
  assert( p );
  assert( sqlite3_mutex_held(p->db->mutex) );
  return p->nBackup!=0;
}

/*
** This function returns a pointer to a blob of memory associated with
** a single shared-btree. The memory is used by client code for its own
** purposes (for example, to store a high-level schema associated with 
** the shared-btree). The btree layer manages reference counting issues.
**
** The first time this is called on a shared-btree, nBytes bytes of memory
** are allocated, zeroed, and returned to the caller. For each subsequent 
** call the nBytes parameter is ignored and a pointer to the same blob
** of memory returned. 
**
** If the nBytes parameter is 0 and the blob of memory has not yet been
** allocated, a null pointer is returned. If the blob has already been
** allocated, it is returned as normal.
**
** Just before the shared-btree is closed, the function passed as the 
** xFree argument when the memory allocation was made is invoked on the 
** blob of allocated memory. This function should not call sqlite3_free()
** on the memory, the btree layer does that.
*/
void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  BtShared *pBt = p->pBt;
  sqlite3BtreeEnter(p);
  if( !pBt->pSchema && nBytes ){
    pBt->pSchema = sqlite3MallocZero(nBytes);
    pBt->xFreeSchema = xFree;
  }
  sqlite3BtreeLeave(p);
  return pBt->pSchema;
}

/*
** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
** btree as the argument handle holds an exclusive lock on the 
** sqlite_master table. Otherwise SQLITE_OK.
*/
int sqlite3BtreeSchemaLocked(Btree *p){
  int rc;
  assert( sqlite3_mutex_held(p->db->mutex) );
  sqlite3BtreeEnter(p);
  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  sqlite3BtreeLeave(p);
  return rc;
}


#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** Obtain a lock on the table whose root page is iTab.  The
** lock is a write lock if isWritelock is true or a read lock
** if it is false.
*/
int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  int rc = SQLITE_OK;
  assert( p->inTrans!=TRANS_NONE );
  if( p->sharable ){
    u8 lockType = READ_LOCK + isWriteLock;
    assert( READ_LOCK+1==WRITE_LOCK );
    assert( isWriteLock==0 || isWriteLock==1 );

    sqlite3BtreeEnter(p);
    rc = querySharedCacheTableLock(p, iTab, lockType);
    if( rc==SQLITE_OK ){
      rc = setSharedCacheTableLock(p, iTab, lockType);
    }
    sqlite3BtreeLeave(p);
  }
  return rc;
}
#endif

#ifndef SQLITE_OMIT_INCRBLOB
/*
** Argument pCsr must be a cursor opened for writing on an 
** INTKEY table currently pointing at a valid table entry. 
** This function modifies the data stored as part of that entry.
**
** Only the data content may only be modified, it is not possible to 
** change the length of the data stored. If this function is called with
** parameters that attempt to write past the end of the existing data,
** no modifications are made and SQLITE_CORRUPT is returned.
*/
int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  int rc;
  assert( cursorHoldsMutex(pCsr) );
  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  assert( pCsr->isIncrblobHandle );

  rc = restoreCursorPosition(pCsr);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  if( pCsr->eState!=CURSOR_VALID ){
    return SQLITE_ABORT;
  }

  /* Check some assumptions: 
  **   (a) the cursor is open for writing,
  **   (b) there is a read/write transaction open,
  **   (c) the connection holds a write-lock on the table (if required),
  **   (d) there are no conflicting read-locks, and
  **   (e) the cursor points at a valid row of an intKey table.
  */
  if( !pCsr->wrFlag ){
    return SQLITE_READONLY;
  }
  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  assert( pCsr->apPage[pCsr->iPage]->intKey );

  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
}

/* 
** Set a flag on this cursor to cache the locations of pages from the 
** overflow list for the current row. This is used by cursors opened
** for incremental blob IO only.
**
** This function sets a flag only. The actual page location cache
** (stored in BtCursor.aOverflow[]) is allocated and used by function
** accessPayload() (the worker function for sqlite3BtreeData() and
** sqlite3BtreePutData()).
*/
void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  assert( cursorHoldsMutex(pCur) );
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  assert(!pCur->isIncrblobHandle);
  assert(!pCur->aOverflow);
  pCur->isIncrblobHandle = 1;
}
#endif

Added src/btree.h.





































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite B-Tree file
** subsystem.  See comments in the source code for a detailed description
** of what each interface routine does.
**
** @(#) $Id: btree.h,v 1.120 2009/07/22 00:35:24 drh Exp $
*/
#ifndef _BTREE_H_
#define _BTREE_H_

/* TODO: This definition is just included so other modules compile. It
** needs to be revisited.
*/
#define SQLITE_N_BTREE_META 10

/*
** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
*/
#ifndef SQLITE_DEFAULT_AUTOVACUUM
  #define SQLITE_DEFAULT_AUTOVACUUM 0
#endif

#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */

/*
** Forward declarations of structure
*/
typedef struct Btree Btree;
typedef struct BtCursor BtCursor;
typedef struct BtShared BtShared;
typedef struct BtreeMutexArray BtreeMutexArray;

/*
** This structure records all of the Btrees that need to hold
** a mutex before we enter sqlite3VdbeExec().  The Btrees are
** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
** we can always lock and unlock them all quickly.
*/
struct BtreeMutexArray {
  int nMutex;
  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
};


int sqlite3BtreeOpen(
  const char *zFilename,   /* Name of database file to open */
  sqlite3 *db,             /* Associated database connection */
  Btree **ppBtree,         /* Return open Btree* here */
  int flags,               /* Flags */
  int vfsFlags             /* Flags passed through to VFS open */
);

/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
** following values.
**
** NOTE:  These values must match the corresponding PAGER_ values in
** pager.h.
*/
#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
#define BTREE_READONLY      8  /* Open the database in read-only mode */
#define BTREE_READWRITE    16  /* Open for both reading and writing */
#define BTREE_CREATE       32  /* Create the database if it does not exist */

int sqlite3BtreeClose(Btree*);
int sqlite3BtreeSetCacheSize(Btree*,int);
int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
int sqlite3BtreeSyncDisabled(Btree*);
int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
int sqlite3BtreeGetPageSize(Btree*);
int sqlite3BtreeMaxPageCount(Btree*,int);
int sqlite3BtreeGetReserve(Btree*);
int sqlite3BtreeSetAutoVacuum(Btree *, int);
int sqlite3BtreeGetAutoVacuum(Btree *);
int sqlite3BtreeBeginTrans(Btree*,int);
int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
int sqlite3BtreeCommitPhaseTwo(Btree*);
int sqlite3BtreeCommit(Btree*);
int sqlite3BtreeRollback(Btree*);
int sqlite3BtreeBeginStmt(Btree*,int);
int sqlite3BtreeCreateTable(Btree*, int*, int flags);
int sqlite3BtreeIsInTrans(Btree*);
int sqlite3BtreeIsInReadTrans(Btree*);
int sqlite3BtreeIsInBackup(Btree*);
void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
int sqlite3BtreeSchemaLocked(Btree *pBtree);
int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
int sqlite3BtreeSavepoint(Btree *, int, int);

const char *sqlite3BtreeGetFilename(Btree *);
const char *sqlite3BtreeGetJournalname(Btree *);
int sqlite3BtreeCopyFile(Btree *, Btree *);

int sqlite3BtreeIncrVacuum(Btree *);

/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
** of the following flags:
*/
#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
#define BTREE_ZERODATA   2    /* Table has keys only - no data */
#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */

int sqlite3BtreeDropTable(Btree*, int, int*);
int sqlite3BtreeClearTable(Btree*, int, int*);
void sqlite3BtreeTripAllCursors(Btree*, int);

void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);

/*
** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
** should be one of the following values. The integer values are assigned 
** to constants so that the offset of the corresponding field in an
** SQLite database header may be found using the following formula:
**
**   offset = 36 + (idx * 4)
**
** For example, the free-page-count field is located at byte offset 36 of
** the database file header. The incr-vacuum-flag field is located at
** byte offset 64 (== 36+4*7).
*/
#define BTREE_FREE_PAGE_COUNT     0
#define BTREE_SCHEMA_VERSION      1
#define BTREE_FILE_FORMAT         2
#define BTREE_DEFAULT_CACHE_SIZE  3
#define BTREE_LARGEST_ROOT_PAGE   4
#define BTREE_TEXT_ENCODING       5
#define BTREE_USER_VERSION        6
#define BTREE_INCR_VACUUM         7

int sqlite3BtreeCursor(
  Btree*,                              /* BTree containing table to open */
  int iTable,                          /* Index of root page */
  int wrFlag,                          /* 1 for writing.  0 for read-only */
  struct KeyInfo*,                     /* First argument to compare function */
  BtCursor *pCursor                    /* Space to write cursor structure */
);
int sqlite3BtreeCursorSize(void);

int sqlite3BtreeCloseCursor(BtCursor*);
int sqlite3BtreeMovetoUnpacked(
  BtCursor*,
  UnpackedRecord *pUnKey,
  i64 intKey,
  int bias,
  int *pRes
);
int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
int sqlite3BtreeDelete(BtCursor*);
int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
                                  const void *pData, int nData,
                                  int nZero, int bias, int seekResult);
int sqlite3BtreeFirst(BtCursor*, int *pRes);
int sqlite3BtreeLast(BtCursor*, int *pRes);
int sqlite3BtreeNext(BtCursor*, int *pRes);
int sqlite3BtreeEof(BtCursor*);
int sqlite3BtreePrevious(BtCursor*, int *pRes);
int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);

char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
struct Pager *sqlite3BtreePager(Btree*);

int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
void sqlite3BtreeCacheOverflow(BtCursor *);
void sqlite3BtreeClearCursor(BtCursor *);

#ifndef NDEBUG
int sqlite3BtreeCursorIsValid(BtCursor*);
#endif

#ifndef SQLITE_OMIT_BTREECOUNT
int sqlite3BtreeCount(BtCursor *, i64 *);
#endif

#ifdef SQLITE_TEST
int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
void sqlite3BtreeCursorList(Btree*);
#endif

/*
** If we are not using shared cache, then there is no need to
** use mutexes to access the BtShared structures.  So make the
** Enter and Leave procedures no-ops.
*/
#ifndef SQLITE_OMIT_SHARED_CACHE
  void sqlite3BtreeEnter(Btree*);
  void sqlite3BtreeEnterAll(sqlite3*);
#else
# define sqlite3BtreeEnter(X) 
# define sqlite3BtreeEnterAll(X)
#endif

#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  void sqlite3BtreeLeave(Btree*);
  void sqlite3BtreeEnterCursor(BtCursor*);
  void sqlite3BtreeLeaveCursor(BtCursor*);
  void sqlite3BtreeLeaveAll(sqlite3*);
  void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
  void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
  void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
#ifndef NDEBUG
  /* These routines are used inside assert() statements only. */
  int sqlite3BtreeHoldsMutex(Btree*);
  int sqlite3BtreeHoldsAllMutexes(sqlite3*);
#endif
#else

# define sqlite3BtreeLeave(X)
# define sqlite3BtreeEnterCursor(X)
# define sqlite3BtreeLeaveCursor(X)
# define sqlite3BtreeLeaveAll(X)
# define sqlite3BtreeMutexArrayEnter(X)
# define sqlite3BtreeMutexArrayLeave(X)
# define sqlite3BtreeMutexArrayInsert(X,Y)

# define sqlite3BtreeHoldsMutex(X) 1
# define sqlite3BtreeHoldsAllMutexes(X) 1
#endif


#endif /* _BTREE_H_ */

Added src/btreeInt.h.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/*
** 2004 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btreeInt.h,v 1.52 2009/07/15 17:25:46 drh Exp $
**
** This file implements a external (disk-based) database using BTrees.
** For a detailed discussion of BTrees, refer to
**
**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
**     "Sorting And Searching", pages 473-480. Addison-Wesley
**     Publishing Company, Reading, Massachusetts.
**
** The basic idea is that each page of the file contains N database
** entries and N+1 pointers to subpages.
**
**   ----------------------------------------------------------------
**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
**   ----------------------------------------------------------------
**
** All of the keys on the page that Ptr(0) points to have values less
** than Key(0).  All of the keys on page Ptr(1) and its subpages have
** values greater than Key(0) and less than Key(1).  All of the keys
** on Ptr(N) and its subpages have values greater than Key(N-1).  And
** so forth.
**
** Finding a particular key requires reading O(log(M)) pages from the 
** disk where M is the number of entries in the tree.
**
** In this implementation, a single file can hold one or more separate 
** BTrees.  Each BTree is identified by the index of its root page.  The
** key and data for any entry are combined to form the "payload".  A
** fixed amount of payload can be carried directly on the database
** page.  If the payload is larger than the preset amount then surplus
** bytes are stored on overflow pages.  The payload for an entry
** and the preceding pointer are combined to form a "Cell".  Each 
** page has a small header which contains the Ptr(N) pointer and other
** information such as the size of key and data.
**
** FORMAT DETAILS
**
** The file is divided into pages.  The first page is called page 1,
** the second is page 2, and so forth.  A page number of zero indicates
** "no such page".  The page size can be any power of 2 between 512 and 32768.
** Each page can be either a btree page, a freelist page, an overflow
** page, or a pointer-map page.
**
** The first page is always a btree page.  The first 100 bytes of the first
** page contain a special header (the "file header") that describes the file.
** The format of the file header is as follows:
**
**   OFFSET   SIZE    DESCRIPTION
**      0      16     Header string: "SQLite format 3\000"
**     16       2     Page size in bytes.  
**     18       1     File format write version
**     19       1     File format read version
**     20       1     Bytes of unused space at the end of each page
**     21       1     Max embedded payload fraction
**     22       1     Min embedded payload fraction
**     23       1     Min leaf payload fraction
**     24       4     File change counter
**     28       4     Reserved for future use
**     32       4     First freelist page
**     36       4     Number of freelist pages in the file
**     40      60     15 4-byte meta values passed to higher layers
**
**     40       4     Schema cookie
**     44       4     File format of schema layer
**     48       4     Size of page cache
**     52       4     Largest root-page (auto/incr_vacuum)
**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
**     60       4     User version
**     64       4     Incremental vacuum mode
**     68       4     unused
**     72       4     unused
**     76       4     unused
**
** All of the integer values are big-endian (most significant byte first).
**
** The file change counter is incremented when the database is changed
** This counter allows other processes to know when the file has changed
** and thus when they need to flush their cache.
**
** The max embedded payload fraction is the amount of the total usable
** space in a page that can be consumed by a single cell for standard
** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
** is to limit the maximum cell size so that at least 4 cells will fit
** on one page.  Thus the default max embedded payload fraction is 64.
**
** If the payload for a cell is larger than the max payload, then extra
** payload is spilled to overflow pages.  Once an overflow page is allocated,
** as many bytes as possible are moved into the overflow pages without letting
** the cell size drop below the min embedded payload fraction.
**
** The min leaf payload fraction is like the min embedded payload fraction
** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
** not specified in the header.
**
** Each btree pages is divided into three sections:  The header, the
** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
** file header that occurs before the page header.
**
**      |----------------|
**      | file header    |   100 bytes.  Page 1 only.
**      |----------------|
**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
**      |----------------|
**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
**      | array          |   |  Grows downward
**      |                |   v
**      |----------------|
**      | unallocated    |
**      | space          |
**      |----------------|   ^  Grows upwards
**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
**      | area           |   |  and free space fragments.
**      |----------------|
**
** The page headers looks like this:
**
**   OFFSET   SIZE     DESCRIPTION
**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
**      1       2      byte offset to the first freeblock
**      3       2      number of cells on this page
**      5       2      first byte of the cell content area
**      7       1      number of fragmented free bytes
**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
**
** The flags define the format of this btree page.  The leaf flag means that
** this page has no children.  The zerodata flag means that this page carries
** only keys and no data.  The intkey flag means that the key is a integer
** which is stored in the key size entry of the cell header rather than in
** the payload area.
**
** The cell pointer array begins on the first byte after the page header.
** The cell pointer array contains zero or more 2-byte numbers which are
** offsets from the beginning of the page to the cell content in the cell
** content area.  The cell pointers occur in sorted order.  The system strives
** to keep free space after the last cell pointer so that new cells can
** be easily added without having to defragment the page.
**
** Cell content is stored at the very end of the page and grows toward the
** beginning of the page.
**
** Unused space within the cell content area is collected into a linked list of
** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
** to the first freeblock is given in the header.  Freeblocks occur in
** increasing order.  Because a freeblock must be at least 4 bytes in size,
** any group of 3 or fewer unused bytes in the cell content area cannot
** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
** a fragment.  The total number of bytes in all fragments is recorded.
** in the page header at offset 7.
**
**    SIZE    DESCRIPTION
**      2     Byte offset of the next freeblock
**      2     Bytes in this freeblock
**
** Cells are of variable length.  Cells are stored in the cell content area at
** the end of the page.  Pointers to the cells are in the cell pointer array
** that immediately follows the page header.  Cells is not necessarily
** contiguous or in order, but cell pointers are contiguous and in order.
**
** Cell content makes use of variable length integers.  A variable
** length integer is 1 to 9 bytes where the lower 7 bits of each 
** byte are used.  The integer consists of all bytes that have bit 8 set and
** the first byte with bit 8 clear.  The most significant byte of the integer
** appears first.  A variable-length integer may not be more than 9 bytes long.
** As a special case, all 8 bytes of the 9th byte are used as data.  This
** allows a 64-bit integer to be encoded in 9 bytes.
**
**    0x00                      becomes  0x00000000
**    0x7f                      becomes  0x0000007f
**    0x81 0x00                 becomes  0x00000080
**    0x82 0x00                 becomes  0x00000100
**    0x80 0x7f                 becomes  0x0000007f
**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
**
** Variable length integers are used for rowids and to hold the number of
** bytes of key and data in a btree cell.
**
** The content of a cell looks like this:
**
**    SIZE    DESCRIPTION
**      4     Page number of the left child. Omitted if leaf flag is set.
**     var    Number of bytes of data. Omitted if the zerodata flag is set.
**     var    Number of bytes of key. Or the key itself if intkey flag is set.
**      *     Payload
**      4     First page of the overflow chain.  Omitted if no overflow
**
** Overflow pages form a linked list.  Each page except the last is completely
** filled with data (pagesize - 4 bytes).  The last page can have as little
** as 1 byte of data.
**
**    SIZE    DESCRIPTION
**      4     Page number of next overflow page
**      *     Data
**
** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
** file header points to the first in a linked list of trunk page.  Each trunk
** page points to multiple leaf pages.  The content of a leaf page is
** unspecified.  A trunk page looks like this:
**
**    SIZE    DESCRIPTION
**      4     Page number of next trunk page
**      4     Number of leaf pointers on this page
**      *     zero or more pages numbers of leaves
*/
#include "sqliteInt.h"


/* The following value is the maximum cell size assuming a maximum page
** size give above.
*/
#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)

/* The maximum number of cells on a single page of the database.  This
** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
** plus 2 bytes for the index to the cell in the page header).  Such
** small cells will be rare, but they are possible.
*/
#define MX_CELL(pBt) ((pBt->pageSize-8)/6)

/* Forward declarations */
typedef struct MemPage MemPage;
typedef struct BtLock BtLock;

/*
** This is a magic string that appears at the beginning of every
** SQLite database in order to identify the file as a real database.
**
** You can change this value at compile-time by specifying a
** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
** header must be exactly 16 bytes including the zero-terminator so
** the string itself should be 15 characters long.  If you change
** the header, then your custom library will not be able to read 
** databases generated by the standard tools and the standard tools
** will not be able to read databases created by your custom library.
*/
#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
#  define SQLITE_FILE_HEADER "SQLite format 3"
#endif

/*
** Page type flags.  An ORed combination of these flags appear as the
** first byte of on-disk image of every BTree page.
*/
#define PTF_INTKEY    0x01
#define PTF_ZERODATA  0x02
#define PTF_LEAFDATA  0x04
#define PTF_LEAF      0x08

/*
** As each page of the file is loaded into memory, an instance of the following
** structure is appended and initialized to zero.  This structure stores
** information about the page that is decoded from the raw file page.
**
** The pParent field points back to the parent page.  This allows us to
** walk up the BTree from any leaf to the root.  Care must be taken to
** unref() the parent page pointer when this page is no longer referenced.
** The pageDestructor() routine handles that chore.
**
** Access to all fields of this structure is controlled by the mutex
** stored in MemPage.pBt->mutex.
*/
struct MemPage {
  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
  u8 intKey;           /* True if intkey flag is set */
  u8 leaf;             /* True if leaf flag is set */
  u8 hasData;          /* True if this page stores data */
  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
  u16 cellOffset;      /* Index in aData of first cell pointer */
  u16 nFree;           /* Number of free bytes on the page */
  u16 nCell;           /* Number of cells on this page, local and ovfl */
  u16 maskPage;        /* Mask for page offset */
  struct _OvflCell {   /* Cells that will not fit on aData[] */
    u8 *pCell;          /* Pointers to the body of the overflow cell */
    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
  } aOvfl[5];
  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
  u8 *aData;           /* Pointer to disk image of the page data */
  DbPage *pDbPage;     /* Pager page handle */
  Pgno pgno;           /* Page number for this page */
};

/*
** The in-memory image of a disk page has the auxiliary information appended
** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
** that extra information.
*/
#define EXTRA_SIZE sizeof(MemPage)

/*
** A linked list of the following structures is stored at BtShared.pLock.
** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
** is opened on the table with root page BtShared.iTable. Locks are removed
** from this list when a transaction is committed or rolled back, or when
** a btree handle is closed.
*/
struct BtLock {
  Btree *pBtree;        /* Btree handle holding this lock */
  Pgno iTable;          /* Root page of table */
  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
  BtLock *pNext;        /* Next in BtShared.pLock list */
};

/* Candidate values for BtLock.eLock */
#define READ_LOCK     1
#define WRITE_LOCK    2

/* A Btree handle
**
** A database connection contains a pointer to an instance of
** this object for every database file that it has open.  This structure
** is opaque to the database connection.  The database connection cannot
** see the internals of this structure and only deals with pointers to
** this structure.
**
** For some database files, the same underlying database cache might be 
** shared between multiple connections.  In that case, each connection
** has it own instance of this object.  But each instance of this object
** points to the same BtShared object.  The database cache and the
** schema associated with the database file are all contained within
** the BtShared object.
**
** All fields in this structure are accessed under sqlite3.mutex.
** The pBt pointer itself may not be changed while there exists cursors 
** in the referenced BtShared that point back to this Btree since those
** cursors have to do go through this Btree to find their BtShared and
** they often do so without holding sqlite3.mutex.
*/
struct Btree {
  sqlite3 *db;       /* The database connection holding this btree */
  BtShared *pBt;     /* Sharable content of this btree */
  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  u8 sharable;       /* True if we can share pBt with another db */
  u8 locked;         /* True if db currently has pBt locked */
  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
  int nBackup;       /* Number of backup operations reading this btree */
  Btree *pNext;      /* List of other sharable Btrees from the same db */
  Btree *pPrev;      /* Back pointer of the same list */
#ifndef SQLITE_OMIT_SHARED_CACHE
  BtLock lock;       /* Object used to lock page 1 */
#endif
};

/*
** Btree.inTrans may take one of the following values.
**
** If the shared-data extension is enabled, there may be multiple users
** of the Btree structure. At most one of these may open a write transaction,
** but any number may have active read transactions.
*/
#define TRANS_NONE  0
#define TRANS_READ  1
#define TRANS_WRITE 2

/*
** An instance of this object represents a single database file.
** 
** A single database file can be in use as the same time by two
** or more database connections.  When two or more connections are
** sharing the same database file, each connection has it own
** private Btree object for the file and each of those Btrees points
** to this one BtShared object.  BtShared.nRef is the number of
** connections currently sharing this database file.
**
** Fields in this structure are accessed under the BtShared.mutex
** mutex, except for nRef and pNext which are accessed under the
** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
** may not be modified once it is initially set as long as nRef>0.
** The pSchema field may be set once under BtShared.mutex and
** thereafter is unchanged as long as nRef>0.
**
** isPending:
**
**   If a BtShared client fails to obtain a write-lock on a database
**   table (because there exists one or more read-locks on the table),
**   the shared-cache enters 'pending-lock' state and isPending is
**   set to true.
**
**   The shared-cache leaves the 'pending lock' state when either of
**   the following occur:
**
**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
**     2) The number of locks held by other connections drops to zero.
**
**   while in the 'pending-lock' state, no connection may start a new
**   transaction.
**
**   This feature is included to help prevent writer-starvation.
*/
struct BtShared {
  Pager *pPager;        /* The page cache */
  sqlite3 *db;          /* Database connection currently using this Btree */
  BtCursor *pCursor;    /* A list of all open cursors */
  MemPage *pPage1;      /* First page of the database */
  u8 readOnly;          /* True if the underlying file is readonly */
  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
#ifndef SQLITE_OMIT_AUTOVACUUM
  u8 autoVacuum;        /* True if auto-vacuum is enabled */
  u8 incrVacuum;        /* True if incr-vacuum is enabled */
#endif
  u16 pageSize;         /* Total number of bytes on a page */
  u16 usableSize;       /* Number of usable bytes on each page */
  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
  u8 inTransaction;     /* Transaction state */
  int nTransaction;     /* Number of open transactions (read + write) */
  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
#ifndef SQLITE_OMIT_SHARED_CACHE
  int nRef;             /* Number of references to this structure */
  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
  BtLock *pLock;        /* List of locks held on this shared-btree struct */
  Btree *pWriter;       /* Btree with currently open write transaction */
  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
  u8 isPending;         /* If waiting for read-locks to clear */
#endif
  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
};

/*
** An instance of the following structure is used to hold information
** about a cell.  The parseCellPtr() function fills in this structure
** based on information extract from the raw disk page.
*/
typedef struct CellInfo CellInfo;
struct CellInfo {
  u8 *pCell;     /* Pointer to the start of cell content */
  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
  u32 nData;     /* Number of bytes of data */
  u32 nPayload;  /* Total amount of payload */
  u16 nHeader;   /* Size of the cell content header in bytes */
  u16 nLocal;    /* Amount of payload held locally */
  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
  u16 nSize;     /* Size of the cell content on the main b-tree page */
};

/*
** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
** this will be declared corrupt. This value is calculated based on a
** maximum database size of 2^31 pages a minimum fanout of 2 for a
** root-node and 3 for all other internal nodes.
**
** If a tree that appears to be taller than this is encountered, it is
** assumed that the database is corrupt.
*/
#define BTCURSOR_MAX_DEPTH 20

/*
** A cursor is a pointer to a particular entry within a particular
** b-tree within a database file.
**
** The entry is identified by its MemPage and the index in
** MemPage.aCell[] of the entry.
**
** A single database file can shared by two more database connections,
** but cursors cannot be shared.  Each cursor is associated with a
** particular database connection identified BtCursor.pBtree.db.
**
** Fields in this structure are accessed under the BtShared.mutex
** found at self->pBt->mutex. 
*/
struct BtCursor {
  Btree *pBtree;            /* The Btree to which this cursor belongs */
  BtShared *pBt;            /* The BtShared this cursor points to */
  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  Pgno pgnoRoot;            /* The root page of this tree */
  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
  CellInfo info;            /* A parse of the cell we are pointing at */
  u8 wrFlag;                /* True if writable */
  u8 atLast;                /* Cursor pointing to the last entry */
  u8 validNKey;             /* True if info.nKey is valid */
  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
  void *pKey;      /* Saved key that was cursor's last known position */
  i64 nKey;        /* Size of pKey, or last integer key */
  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
#ifndef SQLITE_OMIT_INCRBLOB
  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
  Pgno *aOverflow;          /* Cache of overflow page locations */
#endif
  i16 iPage;                            /* Index of current page in apPage */
  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
};

/*
** Potential values for BtCursor.eState.
**
** CURSOR_VALID:
**   Cursor points to a valid entry. getPayload() etc. may be called.
**
** CURSOR_INVALID:
**   Cursor does not point to a valid entry. This can happen (for example) 
**   because the table is empty or because BtreeCursorFirst() has not been
**   called.
**
** CURSOR_REQUIRESEEK:
**   The table that this cursor was opened on still exists, but has been 
**   modified since the cursor was last used. The cursor position is saved
**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
**   this state, restoreCursorPosition() can be called to attempt to
**   seek the cursor to the saved position.
**
** CURSOR_FAULT:
**   A unrecoverable error (an I/O error or a malloc failure) has occurred
**   on a different connection that shares the BtShared cache with this
**   cursor.  The error has left the cache in an inconsistent state.
**   Do nothing else with this cursor.  Any attempt to use the cursor
**   should return the error code stored in BtCursor.skip
*/
#define CURSOR_INVALID           0
#define CURSOR_VALID             1
#define CURSOR_REQUIRESEEK       2
#define CURSOR_FAULT             3

/* 
** The database page the PENDING_BYTE occupies. This page is never used.
*/
# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)

/*
** These macros define the location of the pointer-map entry for a 
** database page. The first argument to each is the number of usable
** bytes on each page of the database (often 1024). The second is the
** page number to look up in the pointer map.
**
** PTRMAP_PAGENO returns the database page number of the pointer-map
** page that stores the required pointer. PTRMAP_PTROFFSET returns
** the offset of the requested map entry.
**
** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
** this test.
*/
#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))

/*
** The pointer map is a lookup table that identifies the parent page for
** each child page in the database file.  The parent page is the page that
** contains a pointer to the child.  Every page in the database contains
** 0 or 1 parent pages.  (In this context 'database page' refers
** to any page that is not part of the pointer map itself.)  Each pointer map
** entry consists of a single byte 'type' and a 4 byte parent page number.
** The PTRMAP_XXX identifiers below are the valid types.
**
** The purpose of the pointer map is to facility moving pages from one
** position in the file to another as part of autovacuum.  When a page
** is moved, the pointer in its parent must be updated to point to the
** new location.  The pointer map is used to locate the parent page quickly.
**
** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
**                  used in this case.
**
** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
**                  is not used in this case.
**
** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
**                   overflow pages. The page number identifies the page that
**                   contains the cell with a pointer to this overflow page.
**
** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
**                   overflow pages. The page-number identifies the previous
**                   page in the overflow page list.
**
** PTRMAP_BTREE: The database page is a non-root btree page. The page number
**               identifies the parent page in the btree.
*/
#define PTRMAP_ROOTPAGE 1
#define PTRMAP_FREEPAGE 2
#define PTRMAP_OVERFLOW1 3
#define PTRMAP_OVERFLOW2 4
#define PTRMAP_BTREE 5

/* A bunch of assert() statements to check the transaction state variables
** of handle p (type Btree*) are internally consistent.
*/
#define btreeIntegrity(p) \
  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  assert( p->pBt->inTransaction>=p->inTrans ); 


/*
** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
** if the database supports auto-vacuum or not. Because it is used
** within an expression that is an argument to another macro 
** (sqliteMallocRaw), it is not possible to use conditional compilation.
** So, this macro is defined instead.
*/
#ifndef SQLITE_OMIT_AUTOVACUUM
#define ISAUTOVACUUM (pBt->autoVacuum)
#else
#define ISAUTOVACUUM 0
#endif


/*
** This structure is passed around through all the sanity checking routines
** in order to keep track of some global state information.
*/
typedef struct IntegrityCk IntegrityCk;
struct IntegrityCk {
  BtShared *pBt;    /* The tree being checked out */
  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
  Pgno nPage;       /* Number of pages in the database */
  int *anRef;       /* Number of times each page is referenced */
  int mxErr;        /* Stop accumulating errors when this reaches zero */
  int nErr;         /* Number of messages written to zErrMsg so far */
  int mallocFailed; /* A memory allocation error has occurred */
  StrAccum errMsg;  /* Accumulate the error message text here */
};

/*
** Read or write a two- and four-byte big-endian integer values.
*/
#define get2byte(x)   ((x)[0]<<8 | (x)[1])
#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
#define get4byte sqlite3Get4byte
#define put4byte sqlite3Put4byte

Added src/build.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the SQLite parser
** when syntax rules are reduced.  The routines in this file handle the
** following kinds of SQL syntax:
**
**     CREATE TABLE
**     DROP TABLE
**     CREATE INDEX
**     DROP INDEX
**     creating ID lists
**     BEGIN TRANSACTION
**     COMMIT
**     ROLLBACK
**
** $Id: build.c,v 1.557 2009/07/24 17:58:53 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** This routine is called when a new SQL statement is beginning to
** be parsed.  Initialize the pParse structure as needed.
*/
void sqlite3BeginParse(Parse *pParse, int explainFlag){
  pParse->explain = (u8)explainFlag;
  pParse->nVar = 0;
}

#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** The TableLock structure is only used by the sqlite3TableLock() and
** codeTableLocks() functions.
*/
struct TableLock {
  int iDb;             /* The database containing the table to be locked */
  int iTab;            /* The root page of the table to be locked */
  u8 isWriteLock;      /* True for write lock.  False for a read lock */
  const char *zName;   /* Name of the table */
};

/*
** Record the fact that we want to lock a table at run-time.  
**
** The table to be locked has root page iTab and is found in database iDb.
** A read or a write lock can be taken depending on isWritelock.
**
** This routine just records the fact that the lock is desired.  The
** code to make the lock occur is generated by a later call to
** codeTableLocks() which occurs during sqlite3FinishCoding().
*/
void sqlite3TableLock(
  Parse *pParse,     /* Parsing context */
  int iDb,           /* Index of the database containing the table to lock */
  int iTab,          /* Root page number of the table to be locked */
  u8 isWriteLock,    /* True for a write lock */
  const char *zName  /* Name of the table to be locked */
){
  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  int i;
  int nBytes;
  TableLock *p;
  assert( iDb>=0 );

  for(i=0; i<pToplevel->nTableLock; i++){
    p = &pToplevel->aTableLock[i];
    if( p->iDb==iDb && p->iTab==iTab ){
      p->isWriteLock = (p->isWriteLock || isWriteLock);
      return;
    }
  }

  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  pToplevel->aTableLock =
      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  if( pToplevel->aTableLock ){
    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
    p->iDb = iDb;
    p->iTab = iTab;
    p->isWriteLock = isWriteLock;
    p->zName = zName;
  }else{
    pToplevel->nTableLock = 0;
    pToplevel->db->mallocFailed = 1;
  }
}

/*
** Code an OP_TableLock instruction for each table locked by the
** statement (configured by calls to sqlite3TableLock()).
*/
static void codeTableLocks(Parse *pParse){
  int i;
  Vdbe *pVdbe; 

  pVdbe = sqlite3GetVdbe(pParse);
  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */

  for(i=0; i<pParse->nTableLock; i++){
    TableLock *p = &pParse->aTableLock[i];
    int p1 = p->iDb;
    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
                      p->zName, P4_STATIC);
  }
}
#else
  #define codeTableLocks(x)
#endif

/*
** This routine is called after a single SQL statement has been
** parsed and a VDBE program to execute that statement has been
** prepared.  This routine puts the finishing touches on the
** VDBE program and resets the pParse structure for the next
** parse.
**
** Note that if an error occurred, it might be the case that
** no VDBE code was generated.
*/
void sqlite3FinishCoding(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  db = pParse->db;
  if( db->mallocFailed ) return;
  if( pParse->nested ) return;
  if( pParse->nErr ) return;

  /* Begin by generating some termination code at the end of the
  ** vdbe program
  */
  v = sqlite3GetVdbe(pParse);
  assert( !pParse->isMultiWrite 
       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  if( v ){
    sqlite3VdbeAddOp0(v, OP_Halt);

    /* The cookie mask contains one bit for each database file open.
    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
    ** set for each database that is used.  Generate code to start a
    ** transaction on each used database and to verify the schema cookie
    ** on each used database.
    */
    if( pParse->cookieGoto>0 ){
      u32 mask;
      int iDb;
      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
        if( (mask & pParse->cookieMask)==0 ) continue;
        sqlite3VdbeUsesBtree(v, iDb);
        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
        if( db->init.busy==0 ){
          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
        }
      }
#ifndef SQLITE_OMIT_VIRTUALTABLE
      {
        int i;
        for(i=0; i<pParse->nVtabLock; i++){
          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
        }
        pParse->nVtabLock = 0;
      }
#endif

      /* Once all the cookies have been verified and transactions opened, 
      ** obtain the required table-locks. This is a no-op unless the 
      ** shared-cache feature is enabled.
      */
      codeTableLocks(pParse);

      /* Initialize any AUTOINCREMENT data structures required.
      */
      sqlite3AutoincrementBegin(pParse);

      /* Finally, jump back to the beginning of the executable code. */
      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
    }
  }


  /* Get the VDBE program ready for execution
  */
  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
#ifdef SQLITE_DEBUG
    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
    sqlite3VdbeTrace(v, trace);
#endif
    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
    /* A minimum of one cursor is required if autoincrement is used
    *  See ticket [a696379c1f08866] */
    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
                         pParse->nTab, pParse->nMaxArg, pParse->explain,
                         pParse->isMultiWrite && pParse->mayAbort);
    pParse->rc = SQLITE_DONE;
    pParse->colNamesSet = 0;
  }else if( pParse->rc==SQLITE_OK ){
    pParse->rc = SQLITE_ERROR;
  }
  pParse->nTab = 0;
  pParse->nMem = 0;
  pParse->nSet = 0;
  pParse->nVar = 0;
  pParse->cookieMask = 0;
  pParse->cookieGoto = 0;
}

/*
** Run the parser and code generator recursively in order to generate
** code for the SQL statement given onto the end of the pParse context
** currently under construction.  When the parser is run recursively
** this way, the final OP_Halt is not appended and other initialization
** and finalization steps are omitted because those are handling by the
** outermost parser.
**
** Not everything is nestable.  This facility is designed to permit
** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
** care if you decide to try to use this routine for some other purposes.
*/
void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  va_list ap;
  char *zSql;
  char *zErrMsg = 0;
  sqlite3 *db = pParse->db;
# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
  char saveBuf[SAVE_SZ];

  if( pParse->nErr ) return;
  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
  va_start(ap, zFormat);
  zSql = sqlite3VMPrintf(db, zFormat, ap);
  va_end(ap);
  if( zSql==0 ){
    return;   /* A malloc must have failed */
  }
  pParse->nested++;
  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  memset(&pParse->nVar, 0, SAVE_SZ);
  sqlite3RunParser(pParse, zSql, &zErrMsg);
  sqlite3DbFree(db, zErrMsg);
  sqlite3DbFree(db, zSql);
  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  pParse->nested--;
}

/*
** Locate the in-memory structure that describes a particular database
** table given the name of that table and (optionally) the name of the
** database containing the table.  Return NULL if not found.
**
** If zDatabase is 0, all databases are searched for the table and the
** first matching table is returned.  (No checking for duplicate table
** names is done.)  The search order is TEMP first, then MAIN, then any
** auxiliary databases added using the ATTACH command.
**
** See also sqlite3LocateTable().
*/
Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  Table *p = 0;
  int i;
  int nName;
  assert( zName!=0 );
  nName = sqlite3Strlen30(zName);
  for(i=OMIT_TEMPDB; i<db->nDb; i++){
    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
    if( p ) break;
  }
  return p;
}

/*
** Locate the in-memory structure that describes a particular database
** table given the name of that table and (optionally) the name of the
** database containing the table.  Return NULL if not found.  Also leave an
** error message in pParse->zErrMsg.
**
** The difference between this routine and sqlite3FindTable() is that this
** routine leaves an error message in pParse->zErrMsg where
** sqlite3FindTable() does not.
*/
Table *sqlite3LocateTable(
  Parse *pParse,         /* context in which to report errors */
  int isView,            /* True if looking for a VIEW rather than a TABLE */
  const char *zName,     /* Name of the table we are looking for */
  const char *zDbase     /* Name of the database.  Might be NULL */
){
  Table *p;

  /* Read the database schema. If an error occurs, leave an error message
  ** and code in pParse and return NULL. */
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    return 0;
  }

  p = sqlite3FindTable(pParse->db, zName, zDbase);
  if( p==0 ){
    const char *zMsg = isView ? "no such view" : "no such table";
    if( zDbase ){
      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
    }else{
      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
    }
    pParse->checkSchema = 1;
  }
  return p;
}

/*
** Locate the in-memory structure that describes 
** a particular index given the name of that index
** and the name of the database that contains the index.
** Return NULL if not found.
**
** If zDatabase is 0, all databases are searched for the
** table and the first matching index is returned.  (No checking
** for duplicate index names is done.)  The search order is
** TEMP first, then MAIN, then any auxiliary databases added
** using the ATTACH command.
*/
Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  Index *p = 0;
  int i;
  int nName = sqlite3Strlen30(zName);
  for(i=OMIT_TEMPDB; i<db->nDb; i++){
    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
    Schema *pSchema = db->aDb[j].pSchema;
    assert( pSchema );
    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
    if( p ) break;
  }
  return p;
}

/*
** Reclaim the memory used by an index
*/
static void freeIndex(Index *p){
  sqlite3 *db = p->pTable->dbMem;
#ifndef SQLITE_OMIT_ANALYZE
  sqlite3DeleteIndexSamples(p);
#endif
  sqlite3DbFree(db, p->zColAff);
  sqlite3DbFree(db, p);
}

/*
** Remove the given index from the index hash table, and free
** its memory structures.
**
** The index is removed from the database hash tables but
** it is not unlinked from the Table that it indexes.
** Unlinking from the Table must be done by the calling function.
*/
static void sqlite3DeleteIndex(Index *p){
  Index *pOld;
  const char *zName = p->zName;

  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
                           sqlite3Strlen30(zName), 0);
  assert( pOld==0 || pOld==p );
  freeIndex(p);
}

/*
** For the index called zIdxName which is found in the database iDb,
** unlike that index from its Table then remove the index from
** the index hash table and free all memory structures associated
** with the index.
*/
void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  Index *pIndex;
  int len;
  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;

  len = sqlite3Strlen30(zIdxName);
  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  if( pIndex ){
    if( pIndex->pTable->pIndex==pIndex ){
      pIndex->pTable->pIndex = pIndex->pNext;
    }else{
      Index *p;
      /* Justification of ALWAYS();  The index must be on the list of
      ** indices. */
      p = pIndex->pTable->pIndex;
      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
      if( ALWAYS(p && p->pNext==pIndex) ){
        p->pNext = pIndex->pNext;
      }
    }
    freeIndex(pIndex);
  }
  db->flags |= SQLITE_InternChanges;
}

/*
** Erase all schema information from the in-memory hash tables of
** a single database.  This routine is called to reclaim memory
** before the database closes.  It is also called during a rollback
** if there were schema changes during the transaction or if a
** schema-cookie mismatch occurs.
**
** If iDb==0 then reset the internal schema tables for all database
** files.  If iDb>=1 then reset the internal schema for only the
** single file indicated.
*/
void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
  int i, j;
  assert( iDb>=0 && iDb<db->nDb );

  if( iDb==0 ){
    sqlite3BtreeEnterAll(db);
  }
  for(i=iDb; i<db->nDb; i++){
    Db *pDb = &db->aDb[i];
    if( pDb->pSchema ){
      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
      sqlite3SchemaFree(pDb->pSchema);
    }
    if( iDb>0 ) return;
  }
  assert( iDb==0 );
  db->flags &= ~SQLITE_InternChanges;
  sqlite3VtabUnlockList(db);
  sqlite3BtreeLeaveAll(db);

  /* If one or more of the auxiliary database files has been closed,
  ** then remove them from the auxiliary database list.  We take the
  ** opportunity to do this here since we have just deleted all of the
  ** schema hash tables and therefore do not have to make any changes
  ** to any of those tables.
  */
  for(i=j=2; i<db->nDb; i++){
    struct Db *pDb = &db->aDb[i];
    if( pDb->pBt==0 ){
      sqlite3DbFree(db, pDb->zName);
      pDb->zName = 0;
      continue;
    }
    if( j<i ){
      db->aDb[j] = db->aDb[i];
    }
    j++;
  }
  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  db->nDb = j;
  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
    sqlite3DbFree(db, db->aDb);
    db->aDb = db->aDbStatic;
  }
}

/*
** This routine is called when a commit occurs.
*/
void sqlite3CommitInternalChanges(sqlite3 *db){
  db->flags &= ~SQLITE_InternChanges;
}

/*
** Clear the column names from a table or view.
*/
static void sqliteResetColumnNames(Table *pTable){
  int i;
  Column *pCol;
  sqlite3 *db = pTable->dbMem;
  testcase( db==0 );
  assert( pTable!=0 );
  if( (pCol = pTable->aCol)!=0 ){
    for(i=0; i<pTable->nCol; i++, pCol++){
      sqlite3DbFree(db, pCol->zName);
      sqlite3ExprDelete(db, pCol->pDflt);
      sqlite3DbFree(db, pCol->zDflt);
      sqlite3DbFree(db, pCol->zType);
      sqlite3DbFree(db, pCol->zColl);
    }
    sqlite3DbFree(db, pTable->aCol);
  }
  pTable->aCol = 0;
  pTable->nCol = 0;
}

/*
** Remove the memory data structures associated with the given
** Table.  No changes are made to disk by this routine.
**
** This routine just deletes the data structure.  It does not unlink
** the table data structure from the hash table.  But it does destroy
** memory structures of the indices and foreign keys associated with 
** the table.
*/
void sqlite3DeleteTable(Table *pTable){
  Index *pIndex, *pNext;
  sqlite3 *db;

  if( pTable==0 ) return;
  db = pTable->dbMem;
  testcase( db==0 );

  /* Do not delete the table until the reference count reaches zero. */
  pTable->nRef--;
  if( pTable->nRef>0 ){
    return;
  }
  assert( pTable->nRef==0 );

  /* Delete all indices associated with this table
  */
  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
    pNext = pIndex->pNext;
    assert( pIndex->pSchema==pTable->pSchema );
    sqlite3DeleteIndex(pIndex);
  }

  /* Delete any foreign keys attached to this table. */
  sqlite3FkDelete(pTable);

  /* Delete the Table structure itself.
  */
  sqliteResetColumnNames(pTable);
  sqlite3DbFree(db, pTable->zName);
  sqlite3DbFree(db, pTable->zColAff);
  sqlite3SelectDelete(db, pTable->pSelect);
#ifndef SQLITE_OMIT_CHECK
  sqlite3ExprDelete(db, pTable->pCheck);
#endif
  sqlite3VtabClear(pTable);
  sqlite3DbFree(db, pTable);
}

/*
** Unlink the given table from the hash tables and the delete the
** table structure with all its indices and foreign keys.
*/
void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  Table *p;
  Db *pDb;

  assert( db!=0 );
  assert( iDb>=0 && iDb<db->nDb );
  assert( zTabName && zTabName[0] );
  pDb = &db->aDb[iDb];
  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
                        sqlite3Strlen30(zTabName),0);
  sqlite3DeleteTable(p);
  db->flags |= SQLITE_InternChanges;
}

/*
** Given a token, return a string that consists of the text of that
** token.  Space to hold the returned string
** is obtained from sqliteMalloc() and must be freed by the calling
** function.
**
** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
** surround the body of the token are removed.
**
** Tokens are often just pointers into the original SQL text and so
** are not \000 terminated and are not persistent.  The returned string
** is \000 terminated and is persistent.
*/
char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  char *zName;
  if( pName ){
    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
    sqlite3Dequote(zName);
  }else{
    zName = 0;
  }
  return zName;
}

/*
** Open the sqlite_master table stored in database number iDb for
** writing. The table is opened using cursor 0.
*/
void sqlite3OpenMasterTable(Parse *p, int iDb){
  Vdbe *v = sqlite3GetVdbe(p);
  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
  if( p->nTab==0 ){
    p->nTab = 1;
  }
}

/*
** Parameter zName points to a nul-terminated buffer containing the name
** of a database ("main", "temp" or the name of an attached db). This
** function returns the index of the named database in db->aDb[], or
** -1 if the named db cannot be found.
*/
int sqlite3FindDbName(sqlite3 *db, const char *zName){
  int i = -1;         /* Database number */
  if( zName ){
    Db *pDb;
    int n = sqlite3Strlen30(zName);
    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
          0==sqlite3StrICmp(pDb->zName, zName) ){
        break;
      }
    }
  }
  return i;
}

/*
** The token *pName contains the name of a database (either "main" or
** "temp" or the name of an attached db). This routine returns the
** index of the named database in db->aDb[], or -1 if the named db 
** does not exist.
*/
int sqlite3FindDb(sqlite3 *db, Token *pName){
  int i;                               /* Database number */
  char *zName;                         /* Name we are searching for */
  zName = sqlite3NameFromToken(db, pName);
  i = sqlite3FindDbName(db, zName);
  sqlite3DbFree(db, zName);
  return i;
}

/* The table or view or trigger name is passed to this routine via tokens
** pName1 and pName2. If the table name was fully qualified, for example:
**
** CREATE TABLE xxx.yyy (...);
** 
** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
** the table name is not fully qualified, i.e.:
**
** CREATE TABLE yyy(...);
**
** Then pName1 is set to "yyy" and pName2 is "".
**
** This routine sets the *ppUnqual pointer to point at the token (pName1 or
** pName2) that stores the unqualified table name.  The index of the
** database "xxx" is returned.
*/
int sqlite3TwoPartName(
  Parse *pParse,      /* Parsing and code generating context */
  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
  Token **pUnqual     /* Write the unqualified object name here */
){
  int iDb;                    /* Database holding the object */
  sqlite3 *db = pParse->db;

  if( ALWAYS(pName2!=0) && pName2->n>0 ){
    if( db->init.busy ) {
      sqlite3ErrorMsg(pParse, "corrupt database");
      pParse->nErr++;
      return -1;
    }
    *pUnqual = pName2;
    iDb = sqlite3FindDb(db, pName1);
    if( iDb<0 ){
      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
      pParse->nErr++;
      return -1;
    }
  }else{
    assert( db->init.iDb==0 || db->init.busy );
    iDb = db->init.iDb;
    *pUnqual = pName1;
  }
  return iDb;
}

/*
** This routine is used to check if the UTF-8 string zName is a legal
** unqualified name for a new schema object (table, index, view or
** trigger). All names are legal except those that begin with the string
** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
** is reserved for internal use.
*/
int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  if( !pParse->db->init.busy && pParse->nested==0 
          && (pParse->db->flags & SQLITE_WriteSchema)==0
          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}

/*
** Begin constructing a new table representation in memory.  This is
** the first of several action routines that get called in response
** to a CREATE TABLE statement.  In particular, this routine is called
** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
** flag is true if the table should be stored in the auxiliary database
** file instead of in the main database file.  This is normally the case
** when the "TEMP" or "TEMPORARY" keyword occurs in between
** CREATE and TABLE.
**
** The new table record is initialized and put in pParse->pNewTable.
** As more of the CREATE TABLE statement is parsed, additional action
** routines will be called to add more information to this record.
** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
** is called to complete the construction of the new table record.
*/
void sqlite3StartTable(
  Parse *pParse,   /* Parser context */
  Token *pName1,   /* First part of the name of the table or view */
  Token *pName2,   /* Second part of the name of the table or view */
  int isTemp,      /* True if this is a TEMP table */
  int isView,      /* True if this is a VIEW */
  int isVirtual,   /* True if this is a VIRTUAL table */
  int noErr        /* Do nothing if table already exists */
){
  Table *pTable;
  char *zName = 0; /* The name of the new table */
  sqlite3 *db = pParse->db;
  Vdbe *v;
  int iDb;         /* Database number to create the table in */
  Token *pName;    /* Unqualified name of the table to create */

  /* The table or view name to create is passed to this routine via tokens
  ** pName1 and pName2. If the table name was fully qualified, for example:
  **
  ** CREATE TABLE xxx.yyy (...);
  ** 
  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  ** the table name is not fully qualified, i.e.:
  **
  ** CREATE TABLE yyy(...);
  **
  ** Then pName1 is set to "yyy" and pName2 is "".
  **
  ** The call below sets the pName pointer to point at the token (pName1 or
  ** pName2) that stores the unqualified table name. The variable iDb is
  ** set to the index of the database that the table or view is to be
  ** created in.
  */
  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  if( iDb<0 ) return;
  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
    /* If creating a temp table, the name may not be qualified */
    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
    return;
  }
  if( !OMIT_TEMPDB && isTemp ) iDb = 1;

  pParse->sNameToken = *pName;
  zName = sqlite3NameFromToken(db, pName);
  if( zName==0 ) return;
  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
    goto begin_table_error;
  }
  if( db->init.iDb==1 ) isTemp = 1;
#ifndef SQLITE_OMIT_AUTHORIZATION
  assert( (isTemp & 1)==isTemp );
  {
    int code;
    char *zDb = db->aDb[iDb].zName;
    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
      goto begin_table_error;
    }
    if( isView ){
      if( !OMIT_TEMPDB && isTemp ){
        code = SQLITE_CREATE_TEMP_VIEW;
      }else{
        code = SQLITE_CREATE_VIEW;
      }
    }else{
      if( !OMIT_TEMPDB && isTemp ){
        code = SQLITE_CREATE_TEMP_TABLE;
      }else{
        code = SQLITE_CREATE_TABLE;
      }
    }
    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
      goto begin_table_error;
    }
  }
#endif

  /* Make sure the new table name does not collide with an existing
  ** index or table name in the same database.  Issue an error message if
  ** it does. The exception is if the statement being parsed was passed
  ** to an sqlite3_declare_vtab() call. In that case only the column names
  ** and types will be used, so there is no need to test for namespace
  ** collisions.
  */
  if( !IN_DECLARE_VTAB ){
    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
      goto begin_table_error;
    }
    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
    if( pTable ){
      if( !noErr ){
        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
      }
      goto begin_table_error;
    }
    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
      goto begin_table_error;
    }
  }

  pTable = sqlite3DbMallocZero(db, sizeof(Table));
  if( pTable==0 ){
    db->mallocFailed = 1;
    pParse->rc = SQLITE_NOMEM;
    pParse->nErr++;
    goto begin_table_error;
  }
  pTable->zName = zName;
  pTable->iPKey = -1;
  pTable->pSchema = db->aDb[iDb].pSchema;
  pTable->nRef = 1;
  pTable->dbMem = 0;
  assert( pParse->pNewTable==0 );
  pParse->pNewTable = pTable;

  /* If this is the magic sqlite_sequence table used by autoincrement,
  ** then record a pointer to this table in the main database structure
  ** so that INSERT can find the table easily.
  */
#ifndef SQLITE_OMIT_AUTOINCREMENT
  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
    pTable->pSchema->pSeqTab = pTable;
  }
#endif

  /* Begin generating the code that will insert the table record into
  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
  ** and allocate the record number for the table entry now.  Before any
  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
  ** indices to be created and the table record must come before the 
  ** indices.  Hence, the record number for the table must be allocated
  ** now.
  */
  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
    int j1;
    int fileFormat;
    int reg1, reg2, reg3;
    sqlite3BeginWriteOperation(pParse, 0, iDb);

#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( isVirtual ){
      sqlite3VdbeAddOp0(v, OP_VBegin);
    }
#endif

    /* If the file format and encoding in the database have not been set, 
    ** set them now.
    */
    reg1 = pParse->regRowid = ++pParse->nMem;
    reg2 = pParse->regRoot = ++pParse->nMem;
    reg3 = ++pParse->nMem;
    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
    sqlite3VdbeUsesBtree(v, iDb);
    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
                  1 : SQLITE_MAX_FILE_FORMAT;
    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
    sqlite3VdbeJumpHere(v, j1);

    /* This just creates a place-holder record in the sqlite_master table.
    ** The record created does not contain anything yet.  It will be replaced
    ** by the real entry in code generated at sqlite3EndTable().
    **
    ** The rowid for the new entry is left in register pParse->regRowid.
    ** The root page number of the new table is left in reg pParse->regRoot.
    ** The rowid and root page number values are needed by the code that
    ** sqlite3EndTable will generate.
    */
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
    if( isView || isVirtual ){
      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
    }else
#endif
    {
      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
    }
    sqlite3OpenMasterTable(pParse, iDb);
    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
    sqlite3VdbeAddOp0(v, OP_Close);
  }

  /* Normal (non-error) return. */
  return;

  /* If an error occurs, we jump here */
begin_table_error:
  sqlite3DbFree(db, zName);
  return;
}

/*
** This macro is used to compare two strings in a case-insensitive manner.
** It is slightly faster than calling sqlite3StrICmp() directly, but
** produces larger code.
**
** WARNING: This macro is not compatible with the strcmp() family. It
** returns true if the two strings are equal, otherwise false.
*/
#define STRICMP(x, y) (\
sqlite3UpperToLower[*(unsigned char *)(x)]==   \
sqlite3UpperToLower[*(unsigned char *)(y)]     \
&& sqlite3StrICmp((x)+1,(y)+1)==0 )

/*
** Add a new column to the table currently being constructed.
**
** The parser calls this routine once for each column declaration
** in a CREATE TABLE statement.  sqlite3StartTable() gets called
** first to get things going.  Then this routine is called for each
** column.
*/
void sqlite3AddColumn(Parse *pParse, Token *pName){
  Table *p;
  int i;
  char *z;
  Column *pCol;
  sqlite3 *db = pParse->db;
  if( (p = pParse->pNewTable)==0 ) return;
#if SQLITE_MAX_COLUMN
  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
    return;
  }
#endif
  z = sqlite3NameFromToken(db, pName);
  if( z==0 ) return;
  for(i=0; i<p->nCol; i++){
    if( STRICMP(z, p->aCol[i].zName) ){
      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
      sqlite3DbFree(db, z);
      return;
    }
  }
  if( (p->nCol & 0x7)==0 ){
    Column *aNew;
    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
    if( aNew==0 ){
      sqlite3DbFree(db, z);
      return;
    }
    p->aCol = aNew;
  }
  pCol = &p->aCol[p->nCol];
  memset(pCol, 0, sizeof(p->aCol[0]));
  pCol->zName = z;
 
  /* If there is no type specified, columns have the default affinity
  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  ** be called next to set pCol->affinity correctly.
  */
  pCol->affinity = SQLITE_AFF_NONE;
  p->nCol++;
}

/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
** been seen on a column.  This routine sets the notNull flag on
** the column currently under construction.
*/
void sqlite3AddNotNull(Parse *pParse, int onError){
  Table *p;
  p = pParse->pNewTable;
  if( p==0 || NEVER(p->nCol<1) ) return;
  p->aCol[p->nCol-1].notNull = (u8)onError;
}

/*
** Scan the column type name zType (length nType) and return the
** associated affinity type.
**
** This routine does a case-independent search of zType for the 
** substrings in the following table. If one of the substrings is
** found, the corresponding affinity is returned. If zType contains
** more than one of the substrings, entries toward the top of 
** the table take priority. For example, if zType is 'BLOBINT', 
** SQLITE_AFF_INTEGER is returned.
**
** Substring     | Affinity
** --------------------------------
** 'INT'         | SQLITE_AFF_INTEGER
** 'CHAR'        | SQLITE_AFF_TEXT
** 'CLOB'        | SQLITE_AFF_TEXT
** 'TEXT'        | SQLITE_AFF_TEXT
** 'BLOB'        | SQLITE_AFF_NONE
** 'REAL'        | SQLITE_AFF_REAL
** 'FLOA'        | SQLITE_AFF_REAL
** 'DOUB'        | SQLITE_AFF_REAL
**
** If none of the substrings in the above table are found,
** SQLITE_AFF_NUMERIC is returned.
*/
char sqlite3AffinityType(const char *zIn){
  u32 h = 0;
  char aff = SQLITE_AFF_NUMERIC;

  if( zIn ) while( zIn[0] ){
    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
    zIn++;
    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
      aff = SQLITE_AFF_TEXT; 
    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
      aff = SQLITE_AFF_TEXT;
    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
      aff = SQLITE_AFF_TEXT;
    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
      aff = SQLITE_AFF_NONE;
#ifndef SQLITE_OMIT_FLOATING_POINT
    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
        && aff==SQLITE_AFF_NUMERIC ){
      aff = SQLITE_AFF_REAL;
    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
        && aff==SQLITE_AFF_NUMERIC ){
      aff = SQLITE_AFF_REAL;
    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
        && aff==SQLITE_AFF_NUMERIC ){
      aff = SQLITE_AFF_REAL;
#endif
    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
      aff = SQLITE_AFF_INTEGER;
      break;
    }
  }

  return aff;
}

/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.  The pFirst token is the first
** token in the sequence of tokens that describe the type of the
** column currently under construction.   pLast is the last token
** in the sequence.  Use this information to construct a string
** that contains the typename of the column and store that string
** in zType.
*/ 
void sqlite3AddColumnType(Parse *pParse, Token *pType){
  Table *p;
  Column *pCol;

  p = pParse->pNewTable;
  if( p==0 || NEVER(p->nCol<1) ) return;
  pCol = &p->aCol[p->nCol-1];
  assert( pCol->zType==0 );
  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  pCol->affinity = sqlite3AffinityType(pCol->zType);
}

/*
** The expression is the default value for the most recently added column
** of the table currently under construction.
**
** Default value expressions must be constant.  Raise an exception if this
** is not the case.
**
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.
*/
void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  Table *p;
  Column *pCol;
  sqlite3 *db = pParse->db;
  p = pParse->pNewTable;
  if( p!=0 ){
    pCol = &(p->aCol[p->nCol-1]);
    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
          pCol->zName);
    }else{
      /* A copy of pExpr is used instead of the original, as pExpr contains
      ** tokens that point to volatile memory. The 'span' of the expression
      ** is required by pragma table_info.
      */
      sqlite3ExprDelete(db, pCol->pDflt);
      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
      sqlite3DbFree(db, pCol->zDflt);
      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
                                     (int)(pSpan->zEnd - pSpan->zStart));
    }
  }
  sqlite3ExprDelete(db, pSpan->pExpr);
}

/*
** Designate the PRIMARY KEY for the table.  pList is a list of names 
** of columns that form the primary key.  If pList is NULL, then the
** most recently added column of the table is the primary key.
**
** A table can have at most one primary key.  If the table already has
** a primary key (and this is the second primary key) then create an
** error.
**
** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
** then we will try to use that column as the rowid.  Set the Table.iPKey
** field of the table under construction to be the index of the
** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
** no INTEGER PRIMARY KEY.
**
** If the key is not an INTEGER PRIMARY KEY, then create a unique
** index for the key.  No index is created for INTEGER PRIMARY KEYs.
*/
void sqlite3AddPrimaryKey(
  Parse *pParse,    /* Parsing context */
  ExprList *pList,  /* List of field names to be indexed */
  int onError,      /* What to do with a uniqueness conflict */
  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
){
  Table *pTab = pParse->pNewTable;
  char *zType = 0;
  int iCol = -1, i;
  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  if( pTab->tabFlags & TF_HasPrimaryKey ){
    sqlite3ErrorMsg(pParse, 
      "table \"%s\" has more than one primary key", pTab->zName);
    goto primary_key_exit;
  }
  pTab->tabFlags |= TF_HasPrimaryKey;
  if( pList==0 ){
    iCol = pTab->nCol - 1;
    pTab->aCol[iCol].isPrimKey = 1;
  }else{
    for(i=0; i<pList->nExpr; i++){
      for(iCol=0; iCol<pTab->nCol; iCol++){
        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
          break;
        }
      }
      if( iCol<pTab->nCol ){
        pTab->aCol[iCol].isPrimKey = 1;
      }
    }
    if( pList->nExpr>1 ) iCol = -1;
  }
  if( iCol>=0 && iCol<pTab->nCol ){
    zType = pTab->aCol[iCol].zType;
  }
  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
        && sortOrder==SQLITE_SO_ASC ){
    pTab->iPKey = iCol;
    pTab->keyConf = (u8)onError;
    assert( autoInc==0 || autoInc==1 );
    pTab->tabFlags |= autoInc*TF_Autoincrement;
  }else if( autoInc ){
#ifndef SQLITE_OMIT_AUTOINCREMENT
    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
       "INTEGER PRIMARY KEY");
#endif
  }else{
    Index *p;
    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
    if( p ){
      p->autoIndex = 2;
    }
    pList = 0;
  }

primary_key_exit:
  sqlite3ExprListDelete(pParse->db, pList);
  return;
}

/*
** Add a new CHECK constraint to the table currently under construction.
*/
void sqlite3AddCheckConstraint(
  Parse *pParse,    /* Parsing context */
  Expr *pCheckExpr  /* The check expression */
){
  sqlite3 *db = pParse->db;
#ifndef SQLITE_OMIT_CHECK
  Table *pTab = pParse->pNewTable;
  if( pTab && !IN_DECLARE_VTAB ){
    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
  }else
#endif
  {
    sqlite3ExprDelete(db, pCheckExpr);
  }
}

/*
** Set the collation function of the most recently parsed table column
** to the CollSeq given.
*/
void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  Table *p;
  int i;
  char *zColl;              /* Dequoted name of collation sequence */
  sqlite3 *db;

  if( (p = pParse->pNewTable)==0 ) return;
  i = p->nCol-1;
  db = pParse->db;
  zColl = sqlite3NameFromToken(db, pToken);
  if( !zColl ) return;

  if( sqlite3LocateCollSeq(pParse, zColl) ){
    Index *pIdx;
    p->aCol[i].zColl = zColl;
  
    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
    ** then an index may have been created on this column before the
    ** collation type was added. Correct this if it is the case.
    */
    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
      assert( pIdx->nColumn==1 );
      if( pIdx->aiColumn[0]==i ){
        pIdx->azColl[0] = p->aCol[i].zColl;
      }
    }
  }else{
    sqlite3DbFree(db, zColl);
  }
}

/*
** This function returns the collation sequence for database native text
** encoding identified by the string zName, length nName.
**
** If the requested collation sequence is not available, or not available
** in the database native encoding, the collation factory is invoked to
** request it. If the collation factory does not supply such a sequence,
** and the sequence is available in another text encoding, then that is
** returned instead.
**
** If no versions of the requested collations sequence are available, or
** another error occurs, NULL is returned and an error message written into
** pParse.
**
** This routine is a wrapper around sqlite3FindCollSeq().  This routine
** invokes the collation factory if the named collation cannot be found
** and generates an error message.
**
** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
*/
CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  sqlite3 *db = pParse->db;
  u8 enc = ENC(db);
  u8 initbusy = db->init.busy;
  CollSeq *pColl;

  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  if( !initbusy && (!pColl || !pColl->xCmp) ){
    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
    if( !pColl ){
      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
    }
  }

  return pColl;
}


/*
** Generate code that will increment the schema cookie.
**
** The schema cookie is used to determine when the schema for the
** database changes.  After each schema change, the cookie value
** changes.  When a process first reads the schema it records the
** cookie.  Thereafter, whenever it goes to access the database,
** it checks the cookie to make sure the schema has not changed
** since it was last read.
**
** This plan is not completely bullet-proof.  It is possible for
** the schema to change multiple times and for the cookie to be
** set back to prior value.  But schema changes are infrequent
** and the probability of hitting the same cookie value is only
** 1 chance in 2^32.  So we're safe enough.
*/
void sqlite3ChangeCookie(Parse *pParse, int iDb){
  int r1 = sqlite3GetTempReg(pParse);
  sqlite3 *db = pParse->db;
  Vdbe *v = pParse->pVdbe;
  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  sqlite3ReleaseTempReg(pParse, r1);
}

/*
** Measure the number of characters needed to output the given
** identifier.  The number returned includes any quotes used
** but does not include the null terminator.
**
** The estimate is conservative.  It might be larger that what is
** really needed.
*/
static int identLength(const char *z){
  int n;
  for(n=0; *z; n++, z++){
    if( *z=='"' ){ n++; }
  }
  return n + 2;
}

/*
** The first parameter is a pointer to an output buffer. The second 
** parameter is a pointer to an integer that contains the offset at
** which to write into the output buffer. This function copies the
** nul-terminated string pointed to by the third parameter, zSignedIdent,
** to the specified offset in the buffer and updates *pIdx to refer
** to the first byte after the last byte written before returning.
** 
** If the string zSignedIdent consists entirely of alpha-numeric
** characters, does not begin with a digit and is not an SQL keyword,
** then it is copied to the output buffer exactly as it is. Otherwise,
** it is quoted using double-quotes.
*/
static void identPut(char *z, int *pIdx, char *zSignedIdent){
  unsigned char *zIdent = (unsigned char*)zSignedIdent;
  int i, j, needQuote;
  i = *pIdx;

  for(j=0; zIdent[j]; j++){
    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  }
  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  if( !needQuote ){
    needQuote = zIdent[j];
  }

  if( needQuote ) z[i++] = '"';
  for(j=0; zIdent[j]; j++){
    z[i++] = zIdent[j];
    if( zIdent[j]=='"' ) z[i++] = '"';
  }
  if( needQuote ) z[i++] = '"';
  z[i] = 0;
  *pIdx = i;
}

/*
** Generate a CREATE TABLE statement appropriate for the given
** table.  Memory to hold the text of the statement is obtained
** from sqliteMalloc() and must be freed by the calling function.
*/
static char *createTableStmt(sqlite3 *db, Table *p){
  int i, k, n;
  char *zStmt;
  char *zSep, *zSep2, *zEnd;
  Column *pCol;
  n = 0;
  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
    n += identLength(pCol->zName) + 5;
  }
  n += identLength(p->zName);
  if( n<50 ){ 
    zSep = "";
    zSep2 = ",";
    zEnd = ")";
  }else{
    zSep = "\n  ";
    zSep2 = ",\n  ";
    zEnd = "\n)";
  }
  n += 35 + 6*p->nCol;
  zStmt = sqlite3Malloc( n );
  if( zStmt==0 ){
    db->mallocFailed = 1;
    return 0;
  }
  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  k = sqlite3Strlen30(zStmt);
  identPut(zStmt, &k, p->zName);
  zStmt[k++] = '(';
  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
    static const char * const azType[] = {
        /* SQLITE_AFF_TEXT    */ " TEXT",
        /* SQLITE_AFF_NONE    */ "",
        /* SQLITE_AFF_NUMERIC */ " NUM",
        /* SQLITE_AFF_INTEGER */ " INT",
        /* SQLITE_AFF_REAL    */ " REAL"
    };
    int len;
    const char *zType;

    sqlite3_snprintf(n-k, &zStmt[k], zSep);
    k += sqlite3Strlen30(&zStmt[k]);
    zSep = zSep2;
    identPut(zStmt, &k, pCol->zName);
    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
    testcase( pCol->affinity==SQLITE_AFF_TEXT );
    testcase( pCol->affinity==SQLITE_AFF_NONE );
    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
    testcase( pCol->affinity==SQLITE_AFF_REAL );
    
    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
    len = sqlite3Strlen30(zType);
    assert( pCol->affinity==SQLITE_AFF_NONE 
            || pCol->affinity==sqlite3AffinityType(zType) );
    memcpy(&zStmt[k], zType, len);
    k += len;
    assert( k<=n );
  }
  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  return zStmt;
}

/*
** This routine is called to report the final ")" that terminates
** a CREATE TABLE statement.
**
** The table structure that other action routines have been building
** is added to the internal hash tables, assuming no errors have
** occurred.
**
** An entry for the table is made in the master table on disk, unless
** this is a temporary table or db->init.busy==1.  When db->init.busy==1
** it means we are reading the sqlite_master table because we just
** connected to the database or because the sqlite_master table has
** recently changed, so the entry for this table already exists in
** the sqlite_master table.  We do not want to create it again.
**
** If the pSelect argument is not NULL, it means that this routine
** was called to create a table generated from a 
** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
** the new table will match the result set of the SELECT.
*/
void sqlite3EndTable(
  Parse *pParse,          /* Parse context */
  Token *pCons,           /* The ',' token after the last column defn. */
  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
){
  Table *p;
  sqlite3 *db = pParse->db;
  int iDb;

  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
    return;
  }
  p = pParse->pNewTable;
  if( p==0 ) return;

  assert( !db->init.busy || !pSelect );

  iDb = sqlite3SchemaToIndex(db, p->pSchema);

#ifndef SQLITE_OMIT_CHECK
  /* Resolve names in all CHECK constraint expressions.
  */
  if( p->pCheck ){
    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
    NameContext sNC;                /* Name context for pParse->pNewTable */

    memset(&sNC, 0, sizeof(sNC));
    memset(&sSrc, 0, sizeof(sSrc));
    sSrc.nSrc = 1;
    sSrc.a[0].zName = p->zName;
    sSrc.a[0].pTab = p;
    sSrc.a[0].iCursor = -1;
    sNC.pParse = pParse;
    sNC.pSrcList = &sSrc;
    sNC.isCheck = 1;
    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
      return;
    }
  }
#endif /* !defined(SQLITE_OMIT_CHECK) */

  /* If the db->init.busy is 1 it means we are reading the SQL off the
  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  ** So do not write to the disk again.  Extract the root page number
  ** for the table from the db->init.newTnum field.  (The page number
  ** should have been put there by the sqliteOpenCb routine.)
  */
  if( db->init.busy ){
    p->tnum = db->init.newTnum;
  }

  /* If not initializing, then create a record for the new table
  ** in the SQLITE_MASTER table of the database.
  **
  ** If this is a TEMPORARY table, write the entry into the auxiliary
  ** file instead of into the main database file.
  */
  if( !db->init.busy ){
    int n;
    Vdbe *v;
    char *zType;    /* "view" or "table" */
    char *zType2;   /* "VIEW" or "TABLE" */
    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */

    v = sqlite3GetVdbe(pParse);
    if( NEVER(v==0) ) return;

    sqlite3VdbeAddOp1(v, OP_Close, 0);

    /* 
    ** Initialize zType for the new view or table.
    */
    if( p->pSelect==0 ){
      /* A regular table */
      zType = "table";
      zType2 = "TABLE";
#ifndef SQLITE_OMIT_VIEW
    }else{
      /* A view */
      zType = "view";
      zType2 = "VIEW";
#endif
    }

    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
    ** statement to populate the new table. The root-page number for the
    ** new table is in register pParse->regRoot.
    **
    ** Once the SELECT has been coded by sqlite3Select(), it is in a
    ** suitable state to query for the column names and types to be used
    ** by the new table.
    **
    ** A shared-cache write-lock is not required to write to the new table,
    ** as a schema-lock must have already been obtained to create it. Since
    ** a schema-lock excludes all other database users, the write-lock would
    ** be redundant.
    */
    if( pSelect ){
      SelectDest dest;
      Table *pSelTab;

      assert(pParse->nTab==1);
      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
      sqlite3VdbeChangeP5(v, 1);
      pParse->nTab = 2;
      sqlite3SelectDestInit(&dest, SRT_Table, 1);
      sqlite3Select(pParse, pSelect, &dest);
      sqlite3VdbeAddOp1(v, OP_Close, 1);
      if( pParse->nErr==0 ){
        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
        if( pSelTab==0 ) return;
        assert( p->aCol==0 );
        p->nCol = pSelTab->nCol;
        p->aCol = pSelTab->aCol;
        pSelTab->nCol = 0;
        pSelTab->aCol = 0;
        sqlite3DeleteTable(pSelTab);
      }
    }

    /* Compute the complete text of the CREATE statement */
    if( pSelect ){
      zStmt = createTableStmt(db, p);
    }else{
      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
      zStmt = sqlite3MPrintf(db, 
          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
      );
    }

    /* A slot for the record has already been allocated in the 
    ** SQLITE_MASTER table.  We just need to update that slot with all
    ** the information we've collected.
    */
    sqlite3NestedParse(pParse,
      "UPDATE %Q.%s "
         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
       "WHERE rowid=#%d",
      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
      zType,
      p->zName,
      p->zName,
      pParse->regRoot,
      zStmt,
      pParse->regRowid
    );
    sqlite3DbFree(db, zStmt);
    sqlite3ChangeCookie(pParse, iDb);

#ifndef SQLITE_OMIT_AUTOINCREMENT
    /* Check to see if we need to create an sqlite_sequence table for
    ** keeping track of autoincrement keys.
    */
    if( p->tabFlags & TF_Autoincrement ){
      Db *pDb = &db->aDb[iDb];
      if( pDb->pSchema->pSeqTab==0 ){
        sqlite3NestedParse(pParse,
          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
          pDb->zName
        );
      }
    }
#endif

    /* Reparse everything to update our internal data structures */
    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
  }


  /* Add the table to the in-memory representation of the database.
  */
  if( db->init.busy ){
    Table *pOld;
    Schema *pSchema = p->pSchema;
    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
                             sqlite3Strlen30(p->zName),p);
    if( pOld ){
      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
      db->mallocFailed = 1;
      return;
    }
    pParse->pNewTable = 0;
    db->nTable++;
    db->flags |= SQLITE_InternChanges;

#ifndef SQLITE_OMIT_ALTERTABLE
    if( !p->pSelect ){
      const char *zName = (const char *)pParse->sNameToken.z;
      int nName;
      assert( !pSelect && pCons && pEnd );
      if( pCons->z==0 ){
        pCons = pEnd;
      }
      nName = (int)((const char *)pCons->z - zName);
      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
    }
#endif
  }
}

#ifndef SQLITE_OMIT_VIEW
/*
** The parser calls this routine in order to create a new VIEW
*/
void sqlite3CreateView(
  Parse *pParse,     /* The parsing context */
  Token *pBegin,     /* The CREATE token that begins the statement */
  Token *pName1,     /* The token that holds the name of the view */
  Token *pName2,     /* The token that holds the name of the view */
  Select *pSelect,   /* A SELECT statement that will become the new view */
  int isTemp,        /* TRUE for a TEMPORARY view */
  int noErr          /* Suppress error messages if VIEW already exists */
){
  Table *p;
  int n;
  const char *z;
  Token sEnd;
  DbFixer sFix;
  Token *pName;
  int iDb;
  sqlite3 *db = pParse->db;

  if( pParse->nVar>0 ){
    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
    sqlite3SelectDelete(db, pSelect);
    return;
  }
  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  p = pParse->pNewTable;
  if( p==0 ){
    sqlite3SelectDelete(db, pSelect);
    return;
  }
  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
                             ** there could not have been an error */
  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  iDb = sqlite3SchemaToIndex(db, p->pSchema);
  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
    && sqlite3FixSelect(&sFix, pSelect)
  ){
    sqlite3SelectDelete(db, pSelect);
    return;
  }

  /* Make a copy of the entire SELECT statement that defines the view.
  ** This will force all the Expr.token.z values to be dynamically
  ** allocated rather than point to the input string - which means that
  ** they will persist after the current sqlite3_exec() call returns.
  */
  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  sqlite3SelectDelete(db, pSelect);
  if( db->mallocFailed ){
    return;
  }
  if( !db->init.busy ){
    sqlite3ViewGetColumnNames(pParse, p);
  }

  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
  ** the end.
  */
  sEnd = pParse->sLastToken;
  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
    sEnd.z += sEnd.n;
  }
  sEnd.n = 0;
  n = (int)(sEnd.z - pBegin->z);
  z = pBegin->z;
  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  sEnd.z = &z[n-1];
  sEnd.n = 1;

  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  sqlite3EndTable(pParse, 0, &sEnd, 0);
  return;
}
#endif /* SQLITE_OMIT_VIEW */

#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** The Table structure pTable is really a VIEW.  Fill in the names of
** the columns of the view in the pTable structure.  Return the number
** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
*/
int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  Table *pSelTab;   /* A fake table from which we get the result set */
  Select *pSel;     /* Copy of the SELECT that implements the view */
  int nErr = 0;     /* Number of errors encountered */
  int n;            /* Temporarily holds the number of cursors assigned */
  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);

  assert( pTable );

#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( sqlite3VtabCallConnect(pParse, pTable) ){
    return SQLITE_ERROR;
  }
  if( IsVirtual(pTable) ) return 0;
#endif

#ifndef SQLITE_OMIT_VIEW
  /* A positive nCol means the columns names for this view are
  ** already known.
  */
  if( pTable->nCol>0 ) return 0;

  /* A negative nCol is a special marker meaning that we are currently
  ** trying to compute the column names.  If we enter this routine with
  ** a negative nCol, it means two or more views form a loop, like this:
  **
  **     CREATE VIEW one AS SELECT * FROM two;
  **     CREATE VIEW two AS SELECT * FROM one;
  **
  ** Actually, the error above is now caught prior to reaching this point.
  ** But the following test is still important as it does come up
  ** in the following:
  ** 
  **     CREATE TABLE main.ex1(a);
  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  **     SELECT * FROM temp.ex1;
  */
  if( pTable->nCol<0 ){
    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
    return 1;
  }
  assert( pTable->nCol>=0 );

  /* If we get this far, it means we need to compute the table names.
  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  ** "*" elements in the results set of the view and will assign cursors
  ** to the elements of the FROM clause.  But we do not want these changes
  ** to be permanent.  So the computation is done on a copy of the SELECT
  ** statement that defines the view.
  */
  assert( pTable->pSelect );
  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  if( pSel ){
    u8 enableLookaside = db->lookaside.bEnabled;
    n = pParse->nTab;
    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
    pTable->nCol = -1;
    db->lookaside.bEnabled = 0;
#ifndef SQLITE_OMIT_AUTHORIZATION
    xAuth = db->xAuth;
    db->xAuth = 0;
    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
    db->xAuth = xAuth;
#else
    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
#endif
    db->lookaside.bEnabled = enableLookaside;
    pParse->nTab = n;
    if( pSelTab ){
      assert( pTable->aCol==0 );
      pTable->nCol = pSelTab->nCol;
      pTable->aCol = pSelTab->aCol;
      pSelTab->nCol = 0;
      pSelTab->aCol = 0;
      sqlite3DeleteTable(pSelTab);
      pTable->pSchema->flags |= DB_UnresetViews;
    }else{
      pTable->nCol = 0;
      nErr++;
    }
    sqlite3SelectDelete(db, pSel);
  } else {
    nErr++;
  }
#endif /* SQLITE_OMIT_VIEW */
  return nErr;  
}
#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */

#ifndef SQLITE_OMIT_VIEW
/*
** Clear the column names from every VIEW in database idx.
*/
static void sqliteViewResetAll(sqlite3 *db, int idx){
  HashElem *i;
  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
    Table *pTab = sqliteHashData(i);
    if( pTab->pSelect ){
      sqliteResetColumnNames(pTab);
    }
  }
  DbClearProperty(db, idx, DB_UnresetViews);
}
#else
# define sqliteViewResetAll(A,B)
#endif /* SQLITE_OMIT_VIEW */

/*
** This function is called by the VDBE to adjust the internal schema
** used by SQLite when the btree layer moves a table root page. The
** root-page of a table or index in database iDb has changed from iFrom
** to iTo.
**
** Ticket #1728:  The symbol table might still contain information
** on tables and/or indices that are the process of being deleted.
** If you are unlucky, one of those deleted indices or tables might
** have the same rootpage number as the real table or index that is
** being moved.  So we cannot stop searching after the first match 
** because the first match might be for one of the deleted indices
** or tables and not the table/index that is actually being moved.
** We must continue looping until all tables and indices with
** rootpage==iFrom have been converted to have a rootpage of iTo
** in order to be certain that we got the right one.
*/
#ifndef SQLITE_OMIT_AUTOVACUUM
void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
  HashElem *pElem;
  Hash *pHash;

  pHash = &pDb->pSchema->tblHash;
  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    if( pTab->tnum==iFrom ){
      pTab->tnum = iTo;
    }
  }
  pHash = &pDb->pSchema->idxHash;
  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
    Index *pIdx = sqliteHashData(pElem);
    if( pIdx->tnum==iFrom ){
      pIdx->tnum = iTo;
    }
  }
}
#endif

/*
** Write code to erase the table with root-page iTable from database iDb.
** Also write code to modify the sqlite_master table and internal schema
** if a root-page of another table is moved by the btree-layer whilst
** erasing iTable (this can happen with an auto-vacuum database).
*/ 
static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  Vdbe *v = sqlite3GetVdbe(pParse);
  int r1 = sqlite3GetTempReg(pParse);
  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  sqlite3MayAbort(pParse);
#ifndef SQLITE_OMIT_AUTOVACUUM
  /* OP_Destroy stores an in integer r1. If this integer
  ** is non-zero, then it is the root page number of a table moved to
  ** location iTable. The following code modifies the sqlite_master table to
  ** reflect this.
  **
  ** The "#NNN" in the SQL is a special constant that means whatever value
  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
  ** token for additional information.
  */
  sqlite3NestedParse(pParse, 
     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
#endif
  sqlite3ReleaseTempReg(pParse, r1);
}

/*
** Write VDBE code to erase table pTab and all associated indices on disk.
** Code to update the sqlite_master tables and internal schema definitions
** in case a root-page belonging to another table is moved by the btree layer
** is also added (this can happen with an auto-vacuum database).
*/
static void destroyTable(Parse *pParse, Table *pTab){
#ifdef SQLITE_OMIT_AUTOVACUUM
  Index *pIdx;
  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  destroyRootPage(pParse, pTab->tnum, iDb);
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
    destroyRootPage(pParse, pIdx->tnum, iDb);
  }
#else
  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  ** is not defined), then it is important to call OP_Destroy on the
  ** table and index root-pages in order, starting with the numerically 
  ** largest root-page number. This guarantees that none of the root-pages
  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  ** following were coded:
  **
  ** OP_Destroy 4 0
  ** ...
  ** OP_Destroy 5 0
  **
  ** and root page 5 happened to be the largest root-page number in the
  ** database, then root page 5 would be moved to page 4 by the 
  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  ** a free-list page.
  */
  int iTab = pTab->tnum;
  int iDestroyed = 0;

  while( 1 ){
    Index *pIdx;
    int iLargest = 0;

    if( iDestroyed==0 || iTab<iDestroyed ){
      iLargest = iTab;
    }
    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
      int iIdx = pIdx->tnum;
      assert( pIdx->pSchema==pTab->pSchema );
      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
        iLargest = iIdx;
      }
    }
    if( iLargest==0 ){
      return;
    }else{
      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
      destroyRootPage(pParse, iLargest, iDb);
      iDestroyed = iLargest;
    }
  }
#endif
}

/*
** This routine is called to do the work of a DROP TABLE statement.
** pName is the name of the table to be dropped.
*/
void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  Table *pTab;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  if( db->mallocFailed ){
    goto exit_drop_table;
  }
  assert( pParse->nErr==0 );
  assert( pName->nSrc==1 );
  pTab = sqlite3LocateTable(pParse, isView, 
                            pName->a[0].zName, pName->a[0].zDatabase);

  if( pTab==0 ){
    if( noErr ){
      sqlite3ErrorClear(pParse);
    }
    goto exit_drop_table;
  }
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  assert( iDb>=0 && iDb<db->nDb );

  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  ** it is initialized.
  */
  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto exit_drop_table;
  }
#ifndef SQLITE_OMIT_AUTHORIZATION
  {
    int code;
    const char *zTab = SCHEMA_TABLE(iDb);
    const char *zDb = db->aDb[iDb].zName;
    const char *zArg2 = 0;
    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
      goto exit_drop_table;
    }
    if( isView ){
      if( !OMIT_TEMPDB && iDb==1 ){
        code = SQLITE_DROP_TEMP_VIEW;
      }else{
        code = SQLITE_DROP_VIEW;
      }
#ifndef SQLITE_OMIT_VIRTUALTABLE
    }else if( IsVirtual(pTab) ){
      code = SQLITE_DROP_VTABLE;
      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
#endif
    }else{
      if( !OMIT_TEMPDB && iDb==1 ){
        code = SQLITE_DROP_TEMP_TABLE;
      }else{
        code = SQLITE_DROP_TABLE;
      }
    }
    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
      goto exit_drop_table;
    }
    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
      goto exit_drop_table;
    }
  }
#endif
  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
    goto exit_drop_table;
  }

#ifndef SQLITE_OMIT_VIEW
  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  ** on a table.
  */
  if( isView && pTab->pSelect==0 ){
    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
    goto exit_drop_table;
  }
  if( !isView && pTab->pSelect ){
    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
    goto exit_drop_table;
  }
#endif

  /* Generate code to remove the table from the master table
  ** on disk.
  */
  v = sqlite3GetVdbe(pParse);
  if( v ){
    Trigger *pTrigger;
    Db *pDb = &db->aDb[iDb];
    sqlite3BeginWriteOperation(pParse, 1, iDb);

#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( IsVirtual(pTab) ){
      sqlite3VdbeAddOp0(v, OP_VBegin);
    }
#endif
    sqlite3FkDropTable(pParse, pName, pTab);

    /* Drop all triggers associated with the table being dropped. Code
    ** is generated to remove entries from sqlite_master and/or
    ** sqlite_temp_master if required.
    */
    pTrigger = sqlite3TriggerList(pParse, pTab);
    while( pTrigger ){
      assert( pTrigger->pSchema==pTab->pSchema || 
          pTrigger->pSchema==db->aDb[1].pSchema );
      sqlite3DropTriggerPtr(pParse, pTrigger);
      pTrigger = pTrigger->pNext;
    }

#ifndef SQLITE_OMIT_AUTOINCREMENT
    /* Remove any entries of the sqlite_sequence table associated with
    ** the table being dropped. This is done before the table is dropped
    ** at the btree level, in case the sqlite_sequence table needs to
    ** move as a result of the drop (can happen in auto-vacuum mode).
    */
    if( pTab->tabFlags & TF_Autoincrement ){
      sqlite3NestedParse(pParse,
        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
        pDb->zName, pTab->zName
      );
    }
#endif

    /* Drop all SQLITE_MASTER table and index entries that refer to the
    ** table. The program name loops through the master table and deletes
    ** every row that refers to a table of the same name as the one being
    ** dropped. Triggers are handled seperately because a trigger can be
    ** created in the temp database that refers to a table in another
    ** database.
    */
    sqlite3NestedParse(pParse, 
        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);

    /* Drop any statistics from the sqlite_stat1 table, if it exists */
    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
      sqlite3NestedParse(pParse,
        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
      );
    }

    if( !isView && !IsVirtual(pTab) ){
      destroyTable(pParse, pTab);
    }

    /* Remove the table entry from SQLite's internal schema and modify
    ** the schema cookie.
    */
    if( IsVirtual(pTab) ){
      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
    }
    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
    sqlite3ChangeCookie(pParse, iDb);
  }
  sqliteViewResetAll(db, iDb);

exit_drop_table:
  sqlite3SrcListDelete(db, pName);
}

/*
** This routine is called to create a new foreign key on the table
** currently under construction.  pFromCol determines which columns
** in the current table point to the foreign key.  If pFromCol==0 then
** connect the key to the last column inserted.  pTo is the name of
** the table referred to.  pToCol is a list of tables in the other
** pTo table that the foreign key points to.  flags contains all
** information about the conflict resolution algorithms specified
** in the ON DELETE, ON UPDATE and ON INSERT clauses.
**
** An FKey structure is created and added to the table currently
** under construction in the pParse->pNewTable field.
**
** The foreign key is set for IMMEDIATE processing.  A subsequent call
** to sqlite3DeferForeignKey() might change this to DEFERRED.
*/
void sqlite3CreateForeignKey(
  Parse *pParse,       /* Parsing context */
  ExprList *pFromCol,  /* Columns in this table that point to other table */
  Token *pTo,          /* Name of the other table */
  ExprList *pToCol,    /* Columns in the other table */
  int flags            /* Conflict resolution algorithms. */
){
  sqlite3 *db = pParse->db;
#ifndef SQLITE_OMIT_FOREIGN_KEY
  FKey *pFKey = 0;
  FKey *pNextTo;
  Table *p = pParse->pNewTable;
  int nByte;
  int i;
  int nCol;
  char *z;

  assert( pTo!=0 );
  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  if( pFromCol==0 ){
    int iCol = p->nCol-1;
    if( NEVER(iCol<0) ) goto fk_end;
    if( pToCol && pToCol->nExpr!=1 ){
      sqlite3ErrorMsg(pParse, "foreign key on %s"
         " should reference only one column of table %T",
         p->aCol[iCol].zName, pTo);
      goto fk_end;
    }
    nCol = 1;
  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
    sqlite3ErrorMsg(pParse,
        "number of columns in foreign key does not match the number of "
        "columns in the referenced table");
    goto fk_end;
  }else{
    nCol = pFromCol->nExpr;
  }
  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  if( pToCol ){
    for(i=0; i<pToCol->nExpr; i++){
      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
    }
  }
  pFKey = sqlite3DbMallocZero(db, nByte );
  if( pFKey==0 ){
    goto fk_end;
  }
  pFKey->pFrom = p;
  pFKey->pNextFrom = p->pFKey;
  z = (char*)&pFKey->aCol[nCol];
  pFKey->zTo = z;
  memcpy(z, pTo->z, pTo->n);
  z[pTo->n] = 0;
  sqlite3Dequote(z);
  z += pTo->n+1;
  pFKey->nCol = nCol;
  if( pFromCol==0 ){
    pFKey->aCol[0].iFrom = p->nCol-1;
  }else{
    for(i=0; i<nCol; i++){
      int j;
      for(j=0; j<p->nCol; j++){
        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
          pFKey->aCol[i].iFrom = j;
          break;
        }
      }
      if( j>=p->nCol ){
        sqlite3ErrorMsg(pParse, 
          "unknown column \"%s\" in foreign key definition", 
          pFromCol->a[i].zName);
        goto fk_end;
      }
    }
  }
  if( pToCol ){
    for(i=0; i<nCol; i++){
      int n = sqlite3Strlen30(pToCol->a[i].zName);
      pFKey->aCol[i].zCol = z;
      memcpy(z, pToCol->a[i].zName, n);
      z[n] = 0;
      z += n+1;
    }
  }
  pFKey->isDeferred = 0;
  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */

  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  );
  if( pNextTo==pFKey ){
    db->mallocFailed = 1;
    goto fk_end;
  }
  if( pNextTo ){
    assert( pNextTo->pPrevTo==0 );
    pFKey->pNextTo = pNextTo;
    pNextTo->pPrevTo = pFKey;
  }

  /* Link the foreign key to the table as the last step.
  */
  p->pFKey = pFKey;
  pFKey = 0;

fk_end:
  sqlite3DbFree(db, pFKey);
#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  sqlite3ExprListDelete(db, pFromCol);
  sqlite3ExprListDelete(db, pToCol);
}

/*
** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
** clause is seen as part of a foreign key definition.  The isDeferred
** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
** The behavior of the most recently created foreign key is adjusted
** accordingly.
*/
void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
#ifndef SQLITE_OMIT_FOREIGN_KEY
  Table *pTab;
  FKey *pFKey;
  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  pFKey->isDeferred = (u8)isDeferred;
#endif
}

/*
** Generate code that will erase and refill index *pIdx.  This is
** used to initialize a newly created index or to recompute the
** content of an index in response to a REINDEX command.
**
** if memRootPage is not negative, it means that the index is newly
** created.  The register specified by memRootPage contains the
** root page number of the index.  If memRootPage is negative, then
** the index already exists and must be cleared before being refilled and
** the root page number of the index is taken from pIndex->tnum.
*/
static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  Table *pTab = pIndex->pTable;  /* The table that is indexed */
  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
  int addr1;                     /* Address of top of loop */
  int tnum;                      /* Root page of index */
  Vdbe *v;                       /* Generate code into this virtual machine */
  KeyInfo *pKey;                 /* KeyInfo for index */
  int regIdxKey;                 /* Registers containing the index key */
  int regRecord;                 /* Register holding assemblied index record */
  sqlite3 *db = pParse->db;      /* The database connection */
  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);

#ifndef SQLITE_OMIT_AUTHORIZATION
  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
      db->aDb[iDb].zName ) ){
    return;
  }
#endif

  /* Require a write-lock on the table to perform this operation */
  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);

  v = sqlite3GetVdbe(pParse);
  if( v==0 ) return;
  if( memRootPage>=0 ){
    tnum = memRootPage;
  }else{
    tnum = pIndex->tnum;
    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  }
  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
                    (char *)pKey, P4_KEYINFO_HANDOFF);
  if( memRootPage>=0 ){
    sqlite3VdbeChangeP5(v, 1);
  }
  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  regRecord = sqlite3GetTempReg(pParse);
  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  if( pIndex->onError!=OE_None ){
    const int regRowid = regIdxKey + pIndex->nColumn;
    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);

    /* The registers accessed by the OP_IsUnique opcode were allocated
    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
    ** call above. Just before that function was freed they were released
    ** (made available to the compiler for reuse) using 
    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
    ** opcode use the values stored within seems dangerous. However, since
    ** we can be sure that no other temp registers have been allocated
    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
    */
    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
    sqlite3HaltConstraint(
        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
  }
  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  sqlite3ReleaseTempReg(pParse, regRecord);
  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  sqlite3VdbeJumpHere(v, addr1);
  sqlite3VdbeAddOp1(v, OP_Close, iTab);
  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
}

/*
** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
** and pTblList is the name of the table that is to be indexed.  Both will 
** be NULL for a primary key or an index that is created to satisfy a
** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
** as the table to be indexed.  pParse->pNewTable is a table that is
** currently being constructed by a CREATE TABLE statement.
**
** pList is a list of columns to be indexed.  pList will be NULL if this
** is a primary key or unique-constraint on the most recent column added
** to the table currently under construction.  
**
** If the index is created successfully, return a pointer to the new Index
** structure. This is used by sqlite3AddPrimaryKey() to mark the index
** as the tables primary key (Index.autoIndex==2).
*/
Index *sqlite3CreateIndex(
  Parse *pParse,     /* All information about this parse */
  Token *pName1,     /* First part of index name. May be NULL */
  Token *pName2,     /* Second part of index name. May be NULL */
  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  ExprList *pList,   /* A list of columns to be indexed */
  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  Token *pStart,     /* The CREATE token that begins this statement */
  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
  int sortOrder,     /* Sort order of primary key when pList==NULL */
  int ifNotExist     /* Omit error if index already exists */
){
  Index *pRet = 0;     /* Pointer to return */
  Table *pTab = 0;     /* Table to be indexed */
  Index *pIndex = 0;   /* The index to be created */
  char *zName = 0;     /* Name of the index */
  int nName;           /* Number of characters in zName */
  int i, j;
  Token nullId;        /* Fake token for an empty ID list */
  DbFixer sFix;        /* For assigning database names to pTable */
  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
  sqlite3 *db = pParse->db;
  Db *pDb;             /* The specific table containing the indexed database */
  int iDb;             /* Index of the database that is being written */
  Token *pName = 0;    /* Unqualified name of the index to create */
  struct ExprList_item *pListItem; /* For looping over pList */
  int nCol;
  int nExtra = 0;
  char *zExtra;

  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
  assert( pParse->nErr==0 );      /* Never called with prior errors */
  if( db->mallocFailed || IN_DECLARE_VTAB ){
    goto exit_create_index;
  }
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    goto exit_create_index;
  }

  /*
  ** Find the table that is to be indexed.  Return early if not found.
  */
  if( pTblName!=0 ){

    /* Use the two-part index name to determine the database 
    ** to search for the table. 'Fix' the table name to this db
    ** before looking up the table.
    */
    assert( pName1 && pName2 );
    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
    if( iDb<0 ) goto exit_create_index;

#ifndef SQLITE_OMIT_TEMPDB
    /* If the index name was unqualified, check if the the table
    ** is a temp table. If so, set the database to 1. Do not do this
    ** if initialising a database schema.
    */
    if( !db->init.busy ){
      pTab = sqlite3SrcListLookup(pParse, pTblName);
      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
        iDb = 1;
      }
    }
#endif

    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
        sqlite3FixSrcList(&sFix, pTblName)
    ){
      /* Because the parser constructs pTblName from a single identifier,
      ** sqlite3FixSrcList can never fail. */
      assert(0);
    }
    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
        pTblName->a[0].zDatabase);
    if( !pTab || db->mallocFailed ) goto exit_create_index;
    assert( db->aDb[iDb].pSchema==pTab->pSchema );
  }else{
    assert( pName==0 );
    pTab = pParse->pNewTable;
    if( !pTab ) goto exit_create_index;
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  }
  pDb = &db->aDb[iDb];

  assert( pTab!=0 );
  assert( pParse->nErr==0 );
  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
    goto exit_create_index;
  }
#ifndef SQLITE_OMIT_VIEW
  if( pTab->pSelect ){
    sqlite3ErrorMsg(pParse, "views may not be indexed");
    goto exit_create_index;
  }
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( IsVirtual(pTab) ){
    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
    goto exit_create_index;
  }
#endif

  /*
  ** Find the name of the index.  Make sure there is not already another
  ** index or table with the same name.  
  **
  ** Exception:  If we are reading the names of permanent indices from the
  ** sqlite_master table (because some other process changed the schema) and
  ** one of the index names collides with the name of a temporary table or
  ** index, then we will continue to process this index.
  **
  ** If pName==0 it means that we are
  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
  ** own name.
  */
  if( pName ){
    zName = sqlite3NameFromToken(db, pName);
    if( zName==0 ) goto exit_create_index;
    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
      goto exit_create_index;
    }
    if( !db->init.busy ){
      if( sqlite3FindTable(db, zName, 0)!=0 ){
        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
        goto exit_create_index;
      }
    }
    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
      if( !ifNotExist ){
        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
      }
      goto exit_create_index;
    }
  }else{
    int n;
    Index *pLoop;
    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
    if( zName==0 ){
      goto exit_create_index;
    }
  }

  /* Check for authorization to create an index.
  */
#ifndef SQLITE_OMIT_AUTHORIZATION
  {
    const char *zDb = pDb->zName;
    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
      goto exit_create_index;
    }
    i = SQLITE_CREATE_INDEX;
    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
      goto exit_create_index;
    }
  }
#endif

  /* If pList==0, it means this routine was called to make a primary
  ** key out of the last column added to the table under construction.
  ** So create a fake list to simulate this.
  */
  if( pList==0 ){
    nullId.z = pTab->aCol[pTab->nCol-1].zName;
    nullId.n = sqlite3Strlen30((char*)nullId.z);
    pList = sqlite3ExprListAppend(pParse, 0, 0);
    if( pList==0 ) goto exit_create_index;
    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
    pList->a[0].sortOrder = (u8)sortOrder;
  }

  /* Figure out how many bytes of space are required to store explicitly
  ** specified collation sequence names.
  */
  for(i=0; i<pList->nExpr; i++){
    Expr *pExpr = pList->a[i].pExpr;
    if( pExpr ){
      CollSeq *pColl = pExpr->pColl;
      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
      ** failure we have quit before reaching this point. */
      if( ALWAYS(pColl) ){
        nExtra += (1 + sqlite3Strlen30(pColl->zName));
      }
    }
  }

  /* 
  ** Allocate the index structure. 
  */
  nName = sqlite3Strlen30(zName);
  nCol = pList->nExpr;
  pIndex = sqlite3DbMallocZero(db, 
      sizeof(Index) +              /* Index structure  */
      sizeof(int)*nCol +           /* Index.aiColumn   */
      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
      sizeof(char *)*nCol +        /* Index.azColl     */
      sizeof(u8)*nCol +            /* Index.aSortOrder */
      nName + 1 +                  /* Index.zName      */
      nExtra                       /* Collation sequence names */
  );
  if( db->mallocFailed ){
    goto exit_create_index;
  }
  pIndex->azColl = (char**)(&pIndex[1]);
  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  zExtra = (char *)(&pIndex->zName[nName+1]);
  memcpy(pIndex->zName, zName, nName+1);
  pIndex->pTable = pTab;
  pIndex->nColumn = pList->nExpr;
  pIndex->onError = (u8)onError;
  pIndex->autoIndex = (u8)(pName==0);
  pIndex->pSchema = db->aDb[iDb].pSchema;

  /* Check to see if we should honor DESC requests on index columns
  */
  if( pDb->pSchema->file_format>=4 ){
    sortOrderMask = -1;   /* Honor DESC */
  }else{
    sortOrderMask = 0;    /* Ignore DESC */
  }

  /* Scan the names of the columns of the table to be indexed and
  ** load the column indices into the Index structure.  Report an error
  ** if any column is not found.
  **
  ** TODO:  Add a test to make sure that the same column is not named
  ** more than once within the same index.  Only the first instance of
  ** the column will ever be used by the optimizer.  Note that using the
  ** same column more than once cannot be an error because that would 
  ** break backwards compatibility - it needs to be a warning.
  */
  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
    const char *zColName = pListItem->zName;
    Column *pTabCol;
    int requestedSortOrder;
    char *zColl;                   /* Collation sequence name */

    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
    }
    if( j>=pTab->nCol ){
      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
        pTab->zName, zColName);
      goto exit_create_index;
    }
    pIndex->aiColumn[i] = j;
    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
    ** the way the "idxlist" non-terminal is constructed by the parser,
    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
    ** must exist or else there must have been an OOM error.  But if there
    ** was an OOM error, we would never reach this point. */
    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
      int nColl;
      zColl = pListItem->pExpr->pColl->zName;
      nColl = sqlite3Strlen30(zColl) + 1;
      assert( nExtra>=nColl );
      memcpy(zExtra, zColl, nColl);
      zColl = zExtra;
      zExtra += nColl;
      nExtra -= nColl;
    }else{
      zColl = pTab->aCol[j].zColl;
      if( !zColl ){
        zColl = db->pDfltColl->zName;
      }
    }
    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
      goto exit_create_index;
    }
    pIndex->azColl[i] = zColl;
    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  }
  sqlite3DefaultRowEst(pIndex);

  if( pTab==pParse->pNewTable ){
    /* This routine has been called to create an automatic index as a
    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
    ** i.e. one of:
    **
    ** CREATE TABLE t(x PRIMARY KEY, y);
    ** CREATE TABLE t(x, y, UNIQUE(x, y));
    **
    ** Either way, check to see if the table already has such an index. If
    ** so, don't bother creating this one. This only applies to
    ** automatically created indices. Users can do as they wish with
    ** explicit indices.
    **
    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
    ** (and thus suppressing the second one) even if they have different
    ** sort orders.
    **
    ** If there are different collating sequences or if the columns of
    ** the constraint occur in different orders, then the constraints are
    ** considered distinct and both result in separate indices.
    */
    Index *pIdx;
    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
      int k;
      assert( pIdx->onError!=OE_None );
      assert( pIdx->autoIndex );
      assert( pIndex->onError!=OE_None );

      if( pIdx->nColumn!=pIndex->nColumn ) continue;
      for(k=0; k<pIdx->nColumn; k++){
        const char *z1;
        const char *z2;
        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
        z1 = pIdx->azColl[k];
        z2 = pIndex->azColl[k];
        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
      }
      if( k==pIdx->nColumn ){
        if( pIdx->onError!=pIndex->onError ){
          /* This constraint creates the same index as a previous
          ** constraint specified somewhere in the CREATE TABLE statement.
          ** However the ON CONFLICT clauses are different. If both this 
          ** constraint and the previous equivalent constraint have explicit
          ** ON CONFLICT clauses this is an error. Otherwise, use the
          ** explicitly specified behaviour for the index.
          */
          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
            sqlite3ErrorMsg(pParse, 
                "conflicting ON CONFLICT clauses specified", 0);
          }
          if( pIdx->onError==OE_Default ){
            pIdx->onError = pIndex->onError;
          }
        }
        goto exit_create_index;
      }
    }
  }

  /* Link the new Index structure to its table and to the other
  ** in-memory database structures. 
  */
  if( db->init.busy ){
    Index *p;
    p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
                          pIndex);
    if( p ){
      assert( p==pIndex );  /* Malloc must have failed */
      db->mallocFailed = 1;
      goto exit_create_index;
    }
    db->flags |= SQLITE_InternChanges;
    if( pTblName!=0 ){
      pIndex->tnum = db->init.newTnum;
    }
  }

  /* If the db->init.busy is 0 then create the index on disk.  This
  ** involves writing the index into the master table and filling in the
  ** index with the current table contents.
  **
  ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
  ** command.  db->init.busy is 1 when a database is opened and 
  ** CREATE INDEX statements are read out of the master table.  In
  ** the latter case the index already exists on disk, which is why
  ** we don't want to recreate it.
  **
  ** If pTblName==0 it means this index is generated as a primary key
  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
  ** has just been created, it contains no data and the index initialization
  ** step can be skipped.
  */
  else{ /* if( db->init.busy==0 ) */
    Vdbe *v;
    char *zStmt;
    int iMem = ++pParse->nMem;

    v = sqlite3GetVdbe(pParse);
    if( v==0 ) goto exit_create_index;


    /* Create the rootpage for the index
    */
    sqlite3BeginWriteOperation(pParse, 1, iDb);
    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);

    /* Gather the complete text of the CREATE INDEX statement into
    ** the zStmt variable
    */
    if( pStart ){
      assert( pEnd!=0 );
      /* A named index with an explicit CREATE INDEX statement */
      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
        onError==OE_None ? "" : " UNIQUE",
        pEnd->z - pName->z + 1,
        pName->z);
    }else{
      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
      /* zStmt = sqlite3MPrintf(""); */
      zStmt = 0;
    }

    /* Add an entry in sqlite_master for this index
    */
    sqlite3NestedParse(pParse, 
        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
        pIndex->zName,
        pTab->zName,
        iMem,
        zStmt
    );
    sqlite3DbFree(db, zStmt);

    /* Fill the index with data and reparse the schema. Code an OP_Expire
    ** to invalidate all pre-compiled statements.
    */
    if( pTblName ){
      sqlite3RefillIndex(pParse, pIndex, iMem);
      sqlite3ChangeCookie(pParse, iDb);
      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
      sqlite3VdbeAddOp1(v, OP_Expire, 0);
    }
  }

  /* When adding an index to the list of indices for a table, make
  ** sure all indices labeled OE_Replace come after all those labeled
  ** OE_Ignore.  This is necessary for the correct constraint check
  ** processing (in sqlite3GenerateConstraintChecks()) as part of
  ** UPDATE and INSERT statements.  
  */
  if( db->init.busy || pTblName==0 ){
    if( onError!=OE_Replace || pTab->pIndex==0
         || pTab->pIndex->onError==OE_Replace){
      pIndex->pNext = pTab->pIndex;
      pTab->pIndex = pIndex;
    }else{
      Index *pOther = pTab->pIndex;
      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
        pOther = pOther->pNext;
      }
      pIndex->pNext = pOther->pNext;
      pOther->pNext = pIndex;
    }
    pRet = pIndex;
    pIndex = 0;
  }

  /* Clean up before exiting */
exit_create_index:
  if( pIndex ){
    sqlite3_free(pIndex->zColAff);
    sqlite3DbFree(db, pIndex);
  }
  sqlite3ExprListDelete(db, pList);
  sqlite3SrcListDelete(db, pTblName);
  sqlite3DbFree(db, zName);
  return pRet;
}

/*
** Fill the Index.aiRowEst[] array with default information - information
** to be used when we have not run the ANALYZE command.
**
** aiRowEst[0] is suppose to contain the number of elements in the index.
** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
** number of rows in the table that match any particular value of the
** first column of the index.  aiRowEst[2] is an estimate of the number
** of rows that match any particular combiniation of the first 2 columns
** of the index.  And so forth.  It must always be the case that
*
**           aiRowEst[N]<=aiRowEst[N-1]
**           aiRowEst[N]>=1
**
** Apart from that, we have little to go on besides intuition as to
** how aiRowEst[] should be initialized.  The numbers generated here
** are based on typical values found in actual indices.
*/
void sqlite3DefaultRowEst(Index *pIdx){
  unsigned *a = pIdx->aiRowEst;
  int i;
  assert( a!=0 );
  a[0] = 1000000;
  for(i=pIdx->nColumn; i>=5; i--){
    a[i] = 5;
  }
  while( i>=1 ){
    a[i] = 11 - i;
    i--;
  }
  if( pIdx->onError!=OE_None ){
    a[pIdx->nColumn] = 1;
  }
}

/*
** This routine will drop an existing named index.  This routine
** implements the DROP INDEX statement.
*/
void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  Index *pIndex;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  assert( pParse->nErr==0 );   /* Never called with prior errors */
  if( db->mallocFailed ){
    goto exit_drop_index;
  }
  assert( pName->nSrc==1 );
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    goto exit_drop_index;
  }
  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  if( pIndex==0 ){
    if( !ifExists ){
      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
    }
    pParse->checkSchema = 1;
    goto exit_drop_index;
  }
  if( pIndex->autoIndex ){
    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
      "or PRIMARY KEY constraint cannot be dropped", 0);
    goto exit_drop_index;
  }
  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
#ifndef SQLITE_OMIT_AUTHORIZATION
  {
    int code = SQLITE_DROP_INDEX;
    Table *pTab = pIndex->pTable;
    const char *zDb = db->aDb[iDb].zName;
    const char *zTab = SCHEMA_TABLE(iDb);
    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
      goto exit_drop_index;
    }
    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
      goto exit_drop_index;
    }
  }
#endif

  /* Generate code to remove the index and from the master table */
  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3BeginWriteOperation(pParse, 1, iDb);
    sqlite3NestedParse(pParse,
       "DELETE FROM %Q.%s WHERE name=%Q",
       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
       pIndex->zName
    );
    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
      sqlite3NestedParse(pParse,
        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
        db->aDb[iDb].zName, pIndex->zName
      );
    }
    sqlite3ChangeCookie(pParse, iDb);
    destroyRootPage(pParse, pIndex->tnum, iDb);
    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  }

exit_drop_index:
  sqlite3SrcListDelete(db, pName);
}

/*
** pArray is a pointer to an array of objects.  Each object in the
** array is szEntry bytes in size.  This routine allocates a new
** object on the end of the array.
**
** *pnEntry is the number of entries already in use.  *pnAlloc is
** the previously allocated size of the array.  initSize is the
** suggested initial array size allocation.
**
** The index of the new entry is returned in *pIdx.
**
** This routine returns a pointer to the array of objects.  This
** might be the same as the pArray parameter or it might be a different
** pointer if the array was resized.
*/
void *sqlite3ArrayAllocate(
  sqlite3 *db,      /* Connection to notify of malloc failures */
  void *pArray,     /* Array of objects.  Might be reallocated */
  int szEntry,      /* Size of each object in the array */
  int initSize,     /* Suggested initial allocation, in elements */
  int *pnEntry,     /* Number of objects currently in use */
  int *pnAlloc,     /* Current size of the allocation, in elements */
  int *pIdx         /* Write the index of a new slot here */
){
  char *z;
  if( *pnEntry >= *pnAlloc ){
    void *pNew;
    int newSize;
    newSize = (*pnAlloc)*2 + initSize;
    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
    if( pNew==0 ){
      *pIdx = -1;
      return pArray;
    }
    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
    pArray = pNew;
  }
  z = (char*)pArray;
  memset(&z[*pnEntry * szEntry], 0, szEntry);
  *pIdx = *pnEntry;
  ++*pnEntry;
  return pArray;
}

/*
** Append a new element to the given IdList.  Create a new IdList if
** need be.
**
** A new IdList is returned, or NULL if malloc() fails.
*/
IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  int i;
  if( pList==0 ){
    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
    if( pList==0 ) return 0;
    pList->nAlloc = 0;
  }
  pList->a = sqlite3ArrayAllocate(
      db,
      pList->a,
      sizeof(pList->a[0]),
      5,
      &pList->nId,
      &pList->nAlloc,
      &i
  );
  if( i<0 ){
    sqlite3IdListDelete(db, pList);
    return 0;
  }
  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  return pList;
}

/*
** Delete an IdList.
*/
void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  int i;
  if( pList==0 ) return;
  for(i=0; i<pList->nId; i++){
    sqlite3DbFree(db, pList->a[i].zName);
  }
  sqlite3DbFree(db, pList->a);
  sqlite3DbFree(db, pList);
}

/*
** Return the index in pList of the identifier named zId.  Return -1
** if not found.
*/
int sqlite3IdListIndex(IdList *pList, const char *zName){
  int i;
  if( pList==0 ) return -1;
  for(i=0; i<pList->nId; i++){
    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  }
  return -1;
}

/*
** Expand the space allocated for the given SrcList object by
** creating nExtra new slots beginning at iStart.  iStart is zero based.
** New slots are zeroed.
**
** For example, suppose a SrcList initially contains two entries: A,B.
** To append 3 new entries onto the end, do this:
**
**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
**
** After the call above it would contain:  A, B, nil, nil, nil.
** If the iStart argument had been 1 instead of 2, then the result
** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
** the iStart value would be 0.  The result then would
** be: nil, nil, nil, A, B.
**
** If a memory allocation fails the SrcList is unchanged.  The
** db->mallocFailed flag will be set to true.
*/
SrcList *sqlite3SrcListEnlarge(
  sqlite3 *db,       /* Database connection to notify of OOM errors */
  SrcList *pSrc,     /* The SrcList to be enlarged */
  int nExtra,        /* Number of new slots to add to pSrc->a[] */
  int iStart         /* Index in pSrc->a[] of first new slot */
){
  int i;

  /* Sanity checking on calling parameters */
  assert( iStart>=0 );
  assert( nExtra>=1 );
  assert( pSrc!=0 );
  assert( iStart<=pSrc->nSrc );

  /* Allocate additional space if needed */
  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
    SrcList *pNew;
    int nAlloc = pSrc->nSrc+nExtra;
    int nGot;
    pNew = sqlite3DbRealloc(db, pSrc,
               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
    if( pNew==0 ){
      assert( db->mallocFailed );
      return pSrc;
    }
    pSrc = pNew;
    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
    pSrc->nAlloc = (u16)nGot;
  }

  /* Move existing slots that come after the newly inserted slots
  ** out of the way */
  for(i=pSrc->nSrc-1; i>=iStart; i--){
    pSrc->a[i+nExtra] = pSrc->a[i];
  }
  pSrc->nSrc += (i16)nExtra;

  /* Zero the newly allocated slots */
  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  for(i=iStart; i<iStart+nExtra; i++){
    pSrc->a[i].iCursor = -1;
  }

  /* Return a pointer to the enlarged SrcList */
  return pSrc;
}


/*
** Append a new table name to the given SrcList.  Create a new SrcList if
** need be.  A new entry is created in the SrcList even if pTable is NULL.
**
** A SrcList is returned, or NULL if there is an OOM error.  The returned
** SrcList might be the same as the SrcList that was input or it might be
** a new one.  If an OOM error does occurs, then the prior value of pList
** that is input to this routine is automatically freed.
**
** If pDatabase is not null, it means that the table has an optional
** database name prefix.  Like this:  "database.table".  The pDatabase
** points to the table name and the pTable points to the database name.
** The SrcList.a[].zName field is filled with the table name which might
** come from pTable (if pDatabase is NULL) or from pDatabase.  
** SrcList.a[].zDatabase is filled with the database name from pTable,
** or with NULL if no database is specified.
**
** In other words, if call like this:
**
**         sqlite3SrcListAppend(D,A,B,0);
**
** Then B is a table name and the database name is unspecified.  If called
** like this:
**
**         sqlite3SrcListAppend(D,A,B,C);
**
** Then C is the table name and B is the database name.  If C is defined
** then so is B.  In other words, we never have a case where:
**
**         sqlite3SrcListAppend(D,A,0,C);
**
** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
** before being added to the SrcList.
*/
SrcList *sqlite3SrcListAppend(
  sqlite3 *db,        /* Connection to notify of malloc failures */
  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
  Token *pTable,      /* Table to append */
  Token *pDatabase    /* Database of the table */
){
  struct SrcList_item *pItem;
  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
  if( pList==0 ){
    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
    if( pList==0 ) return 0;
    pList->nAlloc = 1;
  }
  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  if( db->mallocFailed ){
    sqlite3SrcListDelete(db, pList);
    return 0;
  }
  pItem = &pList->a[pList->nSrc-1];
  if( pDatabase && pDatabase->z==0 ){
    pDatabase = 0;
  }
  if( pDatabase ){
    Token *pTemp = pDatabase;
    pDatabase = pTable;
    pTable = pTemp;
  }
  pItem->zName = sqlite3NameFromToken(db, pTable);
  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  return pList;
}

/*
** Assign VdbeCursor index numbers to all tables in a SrcList
*/
void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  int i;
  struct SrcList_item *pItem;
  assert(pList || pParse->db->mallocFailed );
  if( pList ){
    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
      if( pItem->iCursor>=0 ) break;
      pItem->iCursor = pParse->nTab++;
      if( pItem->pSelect ){
        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
      }
    }
  }
}

/*
** Delete an entire SrcList including all its substructure.
*/
void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  int i;
  struct SrcList_item *pItem;
  if( pList==0 ) return;
  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
    sqlite3DbFree(db, pItem->zDatabase);
    sqlite3DbFree(db, pItem->zName);
    sqlite3DbFree(db, pItem->zAlias);
    sqlite3DbFree(db, pItem->zIndex);
    sqlite3DeleteTable(pItem->pTab);
    sqlite3SelectDelete(db, pItem->pSelect);
    sqlite3ExprDelete(db, pItem->pOn);
    sqlite3IdListDelete(db, pItem->pUsing);
  }
  sqlite3DbFree(db, pList);
}

/*
** This routine is called by the parser to add a new term to the
** end of a growing FROM clause.  The "p" parameter is the part of
** the FROM clause that has already been constructed.  "p" is NULL
** if this is the first term of the FROM clause.  pTable and pDatabase
** are the name of the table and database named in the FROM clause term.
** pDatabase is NULL if the database name qualifier is missing - the
** usual case.  If the term has a alias, then pAlias points to the
** alias token.  If the term is a subquery, then pSubquery is the
** SELECT statement that the subquery encodes.  The pTable and
** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
** parameters are the content of the ON and USING clauses.
**
** Return a new SrcList which encodes is the FROM with the new
** term added.
*/
SrcList *sqlite3SrcListAppendFromTerm(
  Parse *pParse,          /* Parsing context */
  SrcList *p,             /* The left part of the FROM clause already seen */
  Token *pTable,          /* Name of the table to add to the FROM clause */
  Token *pDatabase,       /* Name of the database containing pTable */
  Token *pAlias,          /* The right-hand side of the AS subexpression */
  Select *pSubquery,      /* A subquery used in place of a table name */
  Expr *pOn,              /* The ON clause of a join */
  IdList *pUsing          /* The USING clause of a join */
){
  struct SrcList_item *pItem;
  sqlite3 *db = pParse->db;
  if( !p && (pOn || pUsing) ){
    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
      (pOn ? "ON" : "USING")
    );
    goto append_from_error;
  }
  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  if( p==0 || NEVER(p->nSrc==0) ){
    goto append_from_error;
  }
  pItem = &p->a[p->nSrc-1];
  assert( pAlias!=0 );
  if( pAlias->n ){
    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  }
  pItem->pSelect = pSubquery;
  pItem->pOn = pOn;
  pItem->pUsing = pUsing;
  return p;

 append_from_error:
  assert( p==0 );
  sqlite3ExprDelete(db, pOn);
  sqlite3IdListDelete(db, pUsing);
  sqlite3SelectDelete(db, pSubquery);
  return 0;
}

/*
** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
** element of the source-list passed as the second argument.
*/
void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  assert( pIndexedBy!=0 );
  if( p && ALWAYS(p->nSrc>0) ){
    struct SrcList_item *pItem = &p->a[p->nSrc-1];
    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
    if( pIndexedBy->n==1 && !pIndexedBy->z ){
      /* A "NOT INDEXED" clause was supplied. See parse.y 
      ** construct "indexed_opt" for details. */
      pItem->notIndexed = 1;
    }else{
      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
    }
  }
}

/*
** When building up a FROM clause in the parser, the join operator
** is initially attached to the left operand.  But the code generator
** expects the join operator to be on the right operand.  This routine
** Shifts all join operators from left to right for an entire FROM
** clause.
**
** Example: Suppose the join is like this:
**
**           A natural cross join B
**
** The operator is "natural cross join".  The A and B operands are stored
** in p->a[0] and p->a[1], respectively.  The parser initially stores the
** operator with A.  This routine shifts that operator over to B.
*/
void sqlite3SrcListShiftJoinType(SrcList *p){
  if( p && p->a ){
    int i;
    for(i=p->nSrc-1; i>0; i--){
      p->a[i].jointype = p->a[i-1].jointype;
    }
    p->a[0].jointype = 0;
  }
}

/*
** Begin a transaction
*/
void sqlite3BeginTransaction(Parse *pParse, int type){
  sqlite3 *db;
  Vdbe *v;
  int i;

  assert( pParse!=0 );
  db = pParse->db;
  assert( db!=0 );
/*  if( db->aDb[0].pBt==0 ) return; */
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
    return;
  }
  v = sqlite3GetVdbe(pParse);
  if( !v ) return;
  if( type!=TK_DEFERRED ){
    for(i=0; i<db->nDb; i++){
      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
      sqlite3VdbeUsesBtree(v, i);
    }
  }
  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
}

/*
** Commit a transaction
*/
void sqlite3CommitTransaction(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  assert( pParse!=0 );
  db = pParse->db;
  assert( db!=0 );
/*  if( db->aDb[0].pBt==0 ) return; */
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
    return;
  }
  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  }
}

/*
** Rollback a transaction
*/
void sqlite3RollbackTransaction(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  assert( pParse!=0 );
  db = pParse->db;
  assert( db!=0 );
/*  if( db->aDb[0].pBt==0 ) return; */
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
    return;
  }
  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  }
}

/*
** This function is called by the parser when it parses a command to create,
** release or rollback an SQL savepoint. 
*/
void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  char *zName = sqlite3NameFromToken(pParse->db, pName);
  if( zName ){
    Vdbe *v = sqlite3GetVdbe(pParse);
#ifndef SQLITE_OMIT_AUTHORIZATION
    static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
#endif
    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
      sqlite3DbFree(pParse->db, zName);
      return;
    }
    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  }
}

/*
** Make sure the TEMP database is open and available for use.  Return
** the number of errors.  Leave any error messages in the pParse structure.
*/
int sqlite3OpenTempDatabase(Parse *pParse){
  sqlite3 *db = pParse->db;
  if( db->aDb[1].pBt==0 && !pParse->explain ){
    int rc;
    static const int flags = 
          SQLITE_OPEN_READWRITE |
          SQLITE_OPEN_CREATE |
          SQLITE_OPEN_EXCLUSIVE |
          SQLITE_OPEN_DELETEONCLOSE |
          SQLITE_OPEN_TEMP_DB;

    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
                                 &db->aDb[1].pBt);
    if( rc!=SQLITE_OK ){
      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
        "file for storing temporary tables");
      pParse->rc = rc;
      return 1;
    }
    assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
    assert( db->aDb[1].pSchema );
    sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
                            db->dfltJournalMode);
  }
  return 0;
}

/*
** Generate VDBE code that will verify the schema cookie and start
** a read-transaction for all named database files.
**
** It is important that all schema cookies be verified and all
** read transactions be started before anything else happens in
** the VDBE program.  But this routine can be called after much other
** code has been generated.  So here is what we do:
**
** The first time this routine is called, we code an OP_Goto that
** will jump to a subroutine at the end of the program.  Then we
** record every database that needs its schema verified in the
** pParse->cookieMask field.  Later, after all other code has been
** generated, the subroutine that does the cookie verifications and
** starts the transactions will be coded and the OP_Goto P2 value
** will be made to point to that subroutine.  The generation of the
** cookie verification subroutine code happens in sqlite3FinishCoding().
**
** If iDb<0 then code the OP_Goto only - don't set flag to verify the
** schema on any databases.  This can be used to position the OP_Goto
** early in the code, before we know if any database tables will be used.
*/
void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  Parse *pToplevel = sqlite3ParseToplevel(pParse);

  if( pToplevel->cookieGoto==0 ){
    Vdbe *v = sqlite3GetVdbe(pToplevel);
    if( v==0 ) return;  /* This only happens if there was a prior error */
    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  }
  if( iDb>=0 ){
    sqlite3 *db = pToplevel->db;
    int mask;

    assert( iDb<db->nDb );
    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
    assert( iDb<SQLITE_MAX_ATTACHED+2 );
    mask = 1<<iDb;
    if( (pToplevel->cookieMask & mask)==0 ){
      pToplevel->cookieMask |= mask;
      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
      if( !OMIT_TEMPDB && iDb==1 ){
        sqlite3OpenTempDatabase(pToplevel);
      }
    }
  }
}

/*
** Generate VDBE code that prepares for doing an operation that
** might change the database.
**
** This routine starts a new transaction if we are not already within
** a transaction.  If we are already within a transaction, then a checkpoint
** is set if the setStatement parameter is true.  A checkpoint should
** be set for operations that might fail (due to a constraint) part of
** the way through and which will need to undo some writes without having to
** rollback the whole transaction.  For operations where all constraints
** can be checked before any changes are made to the database, it is never
** necessary to undo a write and the checkpoint should not be set.
*/
void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  sqlite3CodeVerifySchema(pParse, iDb);
  pToplevel->writeMask |= 1<<iDb;
  pToplevel->isMultiWrite |= setStatement;
}

/*
** Indicate that the statement currently under construction might write
** more than one entry (example: deleting one row then inserting another,
** inserting multiple rows in a table, or inserting a row and index entries.)
** If an abort occurs after some of these writes have completed, then it will
** be necessary to undo the completed writes.
*/
void sqlite3MultiWrite(Parse *pParse){
  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  pToplevel->isMultiWrite = 1;
}

/* 
** The code generator calls this routine if is discovers that it is
** possible to abort a statement prior to completion.  In order to 
** perform this abort without corrupting the database, we need to make
** sure that the statement is protected by a statement transaction.
**
** Technically, we only need to set the mayAbort flag if the
** isMultiWrite flag was previously set.  There is a time dependency
** such that the abort must occur after the multiwrite.  This makes
** some statements involving the REPLACE conflict resolution algorithm
** go a little faster.  But taking advantage of this time dependency
** makes it more difficult to prove that the code is correct (in 
** particular, it prevents us from writing an effective
** implementation of sqlite3AssertMayAbort()) and so we have chosen
** to take the safe route and skip the optimization.
*/
void sqlite3MayAbort(Parse *pParse){
  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  pToplevel->mayAbort = 1;
}

/*
** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
** error. The onError parameter determines which (if any) of the statement
** and/or current transaction is rolled back.
*/
void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( onError==OE_Abort ){
    sqlite3MayAbort(pParse);
  }
  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
}

/*
** Check to see if pIndex uses the collating sequence pColl.  Return
** true if it does and false if it does not.
*/
#ifndef SQLITE_OMIT_REINDEX
static int collationMatch(const char *zColl, Index *pIndex){
  int i;
  assert( zColl!=0 );
  for(i=0; i<pIndex->nColumn; i++){
    const char *z = pIndex->azColl[i];
    assert( z!=0 );
    if( 0==sqlite3StrICmp(z, zColl) ){
      return 1;
    }
  }
  return 0;
}
#endif

/*
** Recompute all indices of pTab that use the collating sequence pColl.
** If pColl==0 then recompute all indices of pTab.
*/
#ifndef SQLITE_OMIT_REINDEX
static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  Index *pIndex;              /* An index associated with pTab */

  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
    if( zColl==0 || collationMatch(zColl, pIndex) ){
      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
      sqlite3BeginWriteOperation(pParse, 0, iDb);
      sqlite3RefillIndex(pParse, pIndex, -1);
    }
  }
}
#endif

/*
** Recompute all indices of all tables in all databases where the
** indices use the collating sequence pColl.  If pColl==0 then recompute
** all indices everywhere.
*/
#ifndef SQLITE_OMIT_REINDEX
static void reindexDatabases(Parse *pParse, char const *zColl){
  Db *pDb;                    /* A single database */
  int iDb;                    /* The database index number */
  sqlite3 *db = pParse->db;   /* The database connection */
  HashElem *k;                /* For looping over tables in pDb */
  Table *pTab;                /* A table in the database */

  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
    assert( pDb!=0 );
    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
      pTab = (Table*)sqliteHashData(k);
      reindexTable(pParse, pTab, zColl);
    }
  }
}
#endif

/*
** Generate code for the REINDEX command.
**
**        REINDEX                            -- 1
**        REINDEX  <collation>               -- 2
**        REINDEX  ?<database>.?<tablename>  -- 3
**        REINDEX  ?<database>.?<indexname>  -- 4
**
** Form 1 causes all indices in all attached databases to be rebuilt.
** Form 2 rebuilds all indices in all databases that use the named
** collating function.  Forms 3 and 4 rebuild the named index or all
** indices associated with the named table.
*/
#ifndef SQLITE_OMIT_REINDEX
void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
  char *z;                    /* Name of a table or index */
  const char *zDb;            /* Name of the database */
  Table *pTab;                /* A table in the database */
  Index *pIndex;              /* An index associated with pTab */
  int iDb;                    /* The database index number */
  sqlite3 *db = pParse->db;   /* The database connection */
  Token *pObjName;            /* Name of the table or index to be reindexed */

  /* Read the database schema. If an error occurs, leave an error message
  ** and code in pParse and return NULL. */
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    return;
  }

  if( pName1==0 ){
    reindexDatabases(pParse, 0);
    return;
  }else if( NEVER(pName2==0) || pName2->z==0 ){
    char *zColl;
    assert( pName1->z );
    zColl = sqlite3NameFromToken(pParse->db, pName1);
    if( !zColl ) return;
    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
    if( pColl ){
      reindexDatabases(pParse, zColl);
      sqlite3DbFree(db, zColl);
      return;
    }
    sqlite3DbFree(db, zColl);
  }
  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  if( iDb<0 ) return;
  z = sqlite3NameFromToken(db, pObjName);
  if( z==0 ) return;
  zDb = db->aDb[iDb].zName;
  pTab = sqlite3FindTable(db, z, zDb);
  if( pTab ){
    reindexTable(pParse, pTab, 0);
    sqlite3DbFree(db, z);
    return;
  }
  pIndex = sqlite3FindIndex(db, z, zDb);
  sqlite3DbFree(db, z);
  if( pIndex ){
    sqlite3BeginWriteOperation(pParse, 0, iDb);
    sqlite3RefillIndex(pParse, pIndex, -1);
    return;
  }
  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
}
#endif

/*
** Return a dynamicly allocated KeyInfo structure that can be used
** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
**
** If successful, a pointer to the new structure is returned. In this case
** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
** pointer. If an error occurs (out of memory or missing collation 
** sequence), NULL is returned and the state of pParse updated to reflect
** the error.
*/
KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  int i;
  int nCol = pIdx->nColumn;
  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  sqlite3 *db = pParse->db;
  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);

  if( pKey ){
    pKey->db = pParse->db;
    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
    for(i=0; i<nCol; i++){
      char *zColl = pIdx->azColl[i];
      assert( zColl );
      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
    }
    pKey->nField = (u16)nCol;
  }

  if( pParse->nErr ){
    sqlite3DbFree(db, pKey);
    pKey = 0;
  }
  return pKey;
}

Added src/callback.c.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
** 2005 May 23 
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
**
** $Id: callback.c,v 1.42 2009/06/17 00:35:31 drh Exp $
*/

#include "sqliteInt.h"

/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the encoding enc of name zName, length nName.
*/
static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  assert( !db->xCollNeeded || !db->xCollNeeded16 );
  if( db->xCollNeeded ){
    char *zExternal = sqlite3DbStrDup(db, zName);
    if( !zExternal ) return;
    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
    sqlite3DbFree(db, zExternal);
  }
#ifndef SQLITE_OMIT_UTF16
  if( db->xCollNeeded16 ){
    char const *zExternal;
    sqlite3_value *pTmp = sqlite3ValueNew(db);
    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
    if( zExternal ){
      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
    }
    sqlite3ValueFree(pTmp);
  }
#endif
}

/*
** This routine is called if the collation factory fails to deliver a
** collation function in the best encoding but there may be other versions
** of this collation function (for other text encodings) available. Use one
** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
** possible.
*/
static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  CollSeq *pColl2;
  char *z = pColl->zName;
  int i;
  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  for(i=0; i<3; i++){
    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
    if( pColl2->xCmp!=0 ){
      memcpy(pColl, pColl2, sizeof(CollSeq));
      pColl->xDel = 0;         /* Do not copy the destructor */
      return SQLITE_OK;
    }
  }
  return SQLITE_ERROR;
}

/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
** 
** If it is not NULL, then pColl must point to the database native encoding 
** collation sequence with name zName, length nName.
**
** The return value is either the collation sequence to be used in database
** db for collation type name zName, length nName, or NULL, if no collation
** sequence can be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
*/
CollSeq *sqlite3GetCollSeq(
  sqlite3* db,          /* The database connection */
  u8 enc,               /* The desired encoding for the collating sequence */
  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
  const char *zName     /* Collating sequence name */
){
  CollSeq *p;

  p = pColl;
  if( !p ){
    p = sqlite3FindCollSeq(db, enc, zName, 0);
  }
  if( !p || !p->xCmp ){
    /* No collation sequence of this type for this encoding is registered.
    ** Call the collation factory to see if it can supply us with one.
    */
    callCollNeeded(db, enc, zName);
    p = sqlite3FindCollSeq(db, enc, zName, 0);
  }
  if( p && !p->xCmp && synthCollSeq(db, p) ){
    p = 0;
  }
  assert( !p || p->xCmp );
  return p;
}

/*
** This routine is called on a collation sequence before it is used to
** check that it is defined. An undefined collation sequence exists when
** a database is loaded that contains references to collation sequences
** that have not been defined by sqlite3_create_collation() etc.
**
** If required, this routine calls the 'collation needed' callback to
** request a definition of the collating sequence. If this doesn't work, 
** an equivalent collating sequence that uses a text encoding different
** from the main database is substituted, if one is available.
*/
int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  if( pColl ){
    const char *zName = pColl->zName;
    sqlite3 *db = pParse->db;
    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
    if( !p ){
      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
      pParse->nErr++;
      return SQLITE_ERROR;
    }
    assert( p==pColl );
  }
  return SQLITE_OK;
}



/*
** Locate and return an entry from the db.aCollSeq hash table. If the entry
** specified by zName and nName is not found and parameter 'create' is
** true, then create a new entry. Otherwise return NULL.
**
** Each pointer stored in the sqlite3.aCollSeq hash table contains an
** array of three CollSeq structures. The first is the collation sequence
** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
**
** Stored immediately after the three collation sequences is a copy of
** the collation sequence name. A pointer to this string is stored in
** each collation sequence structure.
*/
static CollSeq *findCollSeqEntry(
  sqlite3 *db,          /* Database connection */
  const char *zName,    /* Name of the collating sequence */
  int create            /* Create a new entry if true */
){
  CollSeq *pColl;
  int nName = sqlite3Strlen30(zName);
  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);

  if( 0==pColl && create ){
    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
    if( pColl ){
      CollSeq *pDel = 0;
      pColl[0].zName = (char*)&pColl[3];
      pColl[0].enc = SQLITE_UTF8;
      pColl[1].zName = (char*)&pColl[3];
      pColl[1].enc = SQLITE_UTF16LE;
      pColl[2].zName = (char*)&pColl[3];
      pColl[2].enc = SQLITE_UTF16BE;
      memcpy(pColl[0].zName, zName, nName);
      pColl[0].zName[nName] = 0;
      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);

      /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
      ** return the pColl pointer to be deleted (because it wasn't added
      ** to the hash table).
      */
      assert( pDel==0 || pDel==pColl );
      if( pDel!=0 ){
        db->mallocFailed = 1;
        sqlite3DbFree(db, pDel);
        pColl = 0;
      }
    }
  }
  return pColl;
}

/*
** Parameter zName points to a UTF-8 encoded string nName bytes long.
** Return the CollSeq* pointer for the collation sequence named zName
** for the encoding 'enc' from the database 'db'.
**
** If the entry specified is not found and 'create' is true, then create a
** new entry.  Otherwise return NULL.
**
** A separate function sqlite3LocateCollSeq() is a wrapper around
** this routine.  sqlite3LocateCollSeq() invokes the collation factory
** if necessary and generates an error message if the collating sequence
** cannot be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
*/
CollSeq *sqlite3FindCollSeq(
  sqlite3 *db,
  u8 enc,
  const char *zName,
  int create
){
  CollSeq *pColl;
  if( zName ){
    pColl = findCollSeqEntry(db, zName, create);
  }else{
    pColl = db->pDfltColl;
  }
  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  if( pColl ) pColl += enc-1;
  return pColl;
}

/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 0 and 6, as follows:
**
** 0: Not a match, or if nArg<0 and the function is has no implementation.
** 1: A variable arguments function that prefers UTF-8 when a UTF-16
**    encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
**    requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality(FuncDef *p, int nArg, u8 enc){
  int match = 0;
  if( p->nArg==-1 || p->nArg==nArg 
   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
  ){
    match = 1;
    if( p->nArg==nArg || nArg==-1 ){
      match = 4;
    }
    if( enc==p->iPrefEnc ){
      match += 2;
    }
    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
      match += 1;
    }
  }
  return match;
}

/*
** Search a FuncDefHash for a function with the given name.  Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef *functionSearch(
  FuncDefHash *pHash,  /* Hash table to search */
  int h,               /* Hash of the name */
  const char *zFunc,   /* Name of function */
  int nFunc            /* Number of bytes in zFunc */
){
  FuncDef *p;
  for(p=pHash->a[h]; p; p=p->pHash){
    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
      return p;
    }
  }
  return 0;
}

/*
** Insert a new FuncDef into a FuncDefHash hash table.
*/
void sqlite3FuncDefInsert(
  FuncDefHash *pHash,  /* The hash table into which to insert */
  FuncDef *pDef        /* The function definition to insert */
){
  FuncDef *pOther;
  int nName = sqlite3Strlen30(pDef->zName);
  u8 c1 = (u8)pDef->zName[0];
  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  pOther = functionSearch(pHash, h, pDef->zName, nName);
  if( pOther ){
    assert( pOther!=pDef && pOther->pNext!=pDef );
    pDef->pNext = pOther->pNext;
    pOther->pNext = pDef;
  }else{
    pDef->pNext = 0;
    pDef->pHash = pHash->a[h];
    pHash->a[h] = pDef;
  }
}
  
  

/*
** Locate a user function given a name, a number of arguments and a flag
** indicating whether the function prefers UTF-16 over UTF-8.  Return a
** pointer to the FuncDef structure that defines that function, or return
** NULL if the function does not exist.
**
** If the createFlag argument is true, then a new (blank) FuncDef
** structure is created and liked into the "db" structure if a
** no matching function previously existed.  When createFlag is true
** and the nArg parameter is -1, then only a function that accepts
** any number of arguments will be returned.
**
** If createFlag is false and nArg is -1, then the first valid
** function found is returned.  A function is valid if either xFunc
** or xStep is non-zero.
**
** If createFlag is false, then a function with the required name and
** number of arguments may be returned even if the eTextRep flag does not
** match that requested.
*/
FuncDef *sqlite3FindFunction(
  sqlite3 *db,       /* An open database */
  const char *zName, /* Name of the function.  Not null-terminated */
  int nName,         /* Number of characters in the name */
  int nArg,          /* Number of arguments.  -1 means any number */
  u8 enc,            /* Preferred text encoding */
  int createFlag     /* Create new entry if true and does not otherwise exist */
){
  FuncDef *p;         /* Iterator variable */
  FuncDef *pBest = 0; /* Best match found so far */
  int bestScore = 0;  /* Score of best match */
  int h;              /* Hash value */


  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);

  /* First search for a match amongst the application-defined functions.
  */
  p = functionSearch(&db->aFunc, h, zName, nName);
  while( p ){
    int score = matchQuality(p, nArg, enc);
    if( score>bestScore ){
      pBest = p;
      bestScore = score;
    }
    p = p->pNext;
  }

  /* If no match is found, search the built-in functions.
  **
  ** Except, if createFlag is true, that means that we are trying to
  ** install a new function.  Whatever FuncDef structure is returned will
  ** have fields overwritten with new information appropriate for the
  ** new function.  But the FuncDefs for built-in functions are read-only.
  ** So we must not search for built-ins when creating a new function.
  */ 
  if( !createFlag && !pBest ){
    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
    p = functionSearch(pHash, h, zName, nName);
    while( p ){
      int score = matchQuality(p, nArg, enc);
      if( score>bestScore ){
        pBest = p;
        bestScore = score;
      }
      p = p->pNext;
    }
  }

  /* If the createFlag parameter is true and the search did not reveal an
  ** exact match for the name, number of arguments and encoding, then add a
  ** new entry to the hash table and return it.
  */
  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
    pBest->zName = (char *)&pBest[1];
    pBest->nArg = (u16)nArg;
    pBest->iPrefEnc = enc;
    memcpy(pBest->zName, zName, nName);
    pBest->zName[nName] = 0;
    sqlite3FuncDefInsert(&db->aFunc, pBest);
  }

  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
    return pBest;
  }
  return 0;
}

/*
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
** pointer itself, it just cleans up subsiduary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
void sqlite3SchemaFree(void *p){
  Hash temp1;
  Hash temp2;
  HashElem *pElem;
  Schema *pSchema = (Schema *)p;

  temp1 = pSchema->tblHash;
  temp2 = pSchema->trigHash;
  sqlite3HashInit(&pSchema->trigHash);
  sqlite3HashClear(&pSchema->idxHash);
  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  }
  sqlite3HashClear(&temp2);
  sqlite3HashInit(&pSchema->tblHash);
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    assert( pTab->dbMem==0 );
    sqlite3DeleteTable(pTab);
  }
  sqlite3HashClear(&temp1);
  sqlite3HashClear(&pSchema->fkeyHash);
  pSchema->pSeqTab = 0;
  pSchema->flags &= ~DB_SchemaLoaded;
}

/*
** Find and return the schema associated with a BTree.  Create
** a new one if necessary.
*/
Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  Schema * p;
  if( pBt ){
    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
  }else{
    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
  }
  if( !p ){
    db->mallocFailed = 1;
  }else if ( 0==p->file_format ){
    sqlite3HashInit(&p->tblHash);
    sqlite3HashInit(&p->idxHash);
    sqlite3HashInit(&p->trigHash);
    sqlite3HashInit(&p->fkeyHash);
    p->enc = SQLITE_UTF8;
  }
  return p;
}

Added src/complete.c.











































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that implements the sqlite3_complete() API.
** This code used to be part of the tokenizer.c source file.  But by
** separating it out, the code will be automatically omitted from
** static links that do not use it.
**
** $Id: complete.c,v 1.8 2009/04/28 04:46:42 drh Exp $
*/
#include "sqliteInt.h"
#ifndef SQLITE_OMIT_COMPLETE

/*
** This is defined in tokenize.c.  We just have to import the definition.
*/
#ifndef SQLITE_AMALGAMATION
#ifdef SQLITE_ASCII
extern const char sqlite3IsAsciiIdChar[];
#define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
#endif
#ifdef SQLITE_EBCDIC
extern const char sqlite3IsEbcdicIdChar[];
#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
#endif
#endif /* SQLITE_AMALGAMATION */


/*
** Token types used by the sqlite3_complete() routine.  See the header
** comments on that procedure for additional information.
*/
#define tkSEMI    0
#define tkWS      1
#define tkOTHER   2
#define tkEXPLAIN 3
#define tkCREATE  4
#define tkTEMP    5
#define tkTRIGGER 6
#define tkEND     7

/*
** Return TRUE if the given SQL string ends in a semicolon.
**
** Special handling is require for CREATE TRIGGER statements.
** Whenever the CREATE TRIGGER keywords are seen, the statement
** must end with ";END;".
**
** This implementation uses a state machine with 7 states:
**
**   (0) START     At the beginning or end of an SQL statement.  This routine
**                 returns 1 if it ends in the START state and 0 if it ends
**                 in any other state.
**
**   (1) NORMAL    We are in the middle of statement which ends with a single
**                 semicolon.
**
**   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
**                 a statement.
**
**   (3) CREATE    The keyword CREATE has been seen at the beginning of a
**                 statement, possibly preceeded by EXPLAIN and/or followed by
**                 TEMP or TEMPORARY
**
**   (4) TRIGGER   We are in the middle of a trigger definition that must be
**                 ended by a semicolon, the keyword END, and another semicolon.
**
**   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
**                 the end of a trigger definition.
**
**   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
**                 of a trigger difinition.
**
** Transitions between states above are determined by tokens extracted
** from the input.  The following tokens are significant:
**
**   (0) tkSEMI      A semicolon.
**   (1) tkWS        Whitespace
**   (2) tkOTHER     Any other SQL token.
**   (3) tkEXPLAIN   The "explain" keyword.
**   (4) tkCREATE    The "create" keyword.
**   (5) tkTEMP      The "temp" or "temporary" keyword.
**   (6) tkTRIGGER   The "trigger" keyword.
**   (7) tkEND       The "end" keyword.
**
** Whitespace never causes a state transition and is always ignored.
**
** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
** to recognize the end of a trigger can be omitted.  All we have to do
** is look for a semicolon that is not part of an string or comment.
*/
int sqlite3_complete(const char *zSql){
  u8 state = 0;   /* Current state, using numbers defined in header comment */
  u8 token;       /* Value of the next token */

#ifndef SQLITE_OMIT_TRIGGER
  /* A complex statement machine used to detect the end of a CREATE TRIGGER
  ** statement.  This is the normal case.
  */
  static const u8 trans[7][8] = {
                     /* Token:                                                */
     /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
     /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
     /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
     /* 2 EXPLAIN: */ {    0,  2,     2,      1,      3,    1,       1,   1,  },
     /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
     /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
     /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
     /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
  };
#else
  /* If triggers are not suppored by this compile then the statement machine
  ** used to detect the end of a statement is much simplier
  */
  static const u8 trans[2][3] = {
                     /* Token:           */
     /* State:       **  SEMI  WS  OTHER */
     /* 0   START: */ {    0,  0,     1, },
     /* 1  NORMAL: */ {    0,  1,     1, },
  };
#endif /* SQLITE_OMIT_TRIGGER */

  while( *zSql ){
    switch( *zSql ){
      case ';': {  /* A semicolon */
        token = tkSEMI;
        break;
      }
      case ' ':
      case '\r':
      case '\t':
      case '\n':
      case '\f': {  /* White space is ignored */
        token = tkWS;
        break;
      }
      case '/': {   /* C-style comments */
        if( zSql[1]!='*' ){
          token = tkOTHER;
          break;
        }
        zSql += 2;
        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
        if( zSql[0]==0 ) return 0;
        zSql++;
        token = tkWS;
        break;
      }
      case '-': {   /* SQL-style comments from "--" to end of line */
        if( zSql[1]!='-' ){
          token = tkOTHER;
          break;
        }
        while( *zSql && *zSql!='\n' ){ zSql++; }
        if( *zSql==0 ) return state==0;
        token = tkWS;
        break;
      }
      case '[': {   /* Microsoft-style identifiers in [...] */
        zSql++;
        while( *zSql && *zSql!=']' ){ zSql++; }
        if( *zSql==0 ) return 0;
        token = tkOTHER;
        break;
      }
      case '`':     /* Grave-accent quoted symbols used by MySQL */
      case '"':     /* single- and double-quoted strings */
      case '\'': {
        int c = *zSql;
        zSql++;
        while( *zSql && *zSql!=c ){ zSql++; }
        if( *zSql==0 ) return 0;
        token = tkOTHER;
        break;
      }
      default: {
        int c;
        if( IdChar((u8)*zSql) ){
          /* Keywords and unquoted identifiers */
          int nId;
          for(nId=1; IdChar(zSql[nId]); nId++){}
#ifdef SQLITE_OMIT_TRIGGER
          token = tkOTHER;
#else
          switch( *zSql ){
            case 'c': case 'C': {
              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
                token = tkCREATE;
              }else{
                token = tkOTHER;
              }
              break;
            }
            case 't': case 'T': {
              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
                token = tkTRIGGER;
              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
                token = tkTEMP;
              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
                token = tkTEMP;
              }else{
                token = tkOTHER;
              }
              break;
            }
            case 'e':  case 'E': {
              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
                token = tkEND;
              }else
#ifndef SQLITE_OMIT_EXPLAIN
              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
                token = tkEXPLAIN;
              }else
#endif
              {
                token = tkOTHER;
              }
              break;
            }
            default: {
              token = tkOTHER;
              break;
            }
          }
#endif /* SQLITE_OMIT_TRIGGER */
          zSql += nId-1;
        }else{
          /* Operators and special symbols */
          token = tkOTHER;
        }
        break;
      }
    }
    state = trans[state][token];
    zSql++;
  }
  return state==0;
}

#ifndef SQLITE_OMIT_UTF16
/*
** This routine is the same as the sqlite3_complete() routine described
** above, except that the parameter is required to be UTF-16 encoded, not
** UTF-8.
*/
int sqlite3_complete16(const void *zSql){
  sqlite3_value *pVal;
  char const *zSql8;
  int rc = SQLITE_NOMEM;

#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite3_initialize();
  if( rc ) return rc;
#endif
  pVal = sqlite3ValueNew(0);
  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  if( zSql8 ){
    rc = sqlite3_complete(zSql8);
  }else{
    rc = SQLITE_NOMEM;
  }
  sqlite3ValueFree(pVal);
  return sqlite3ApiExit(0, rc);
}
#endif /* SQLITE_OMIT_UTF16 */
#endif /* SQLITE_OMIT_COMPLETE */

Added src/date.c.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
/*
** 2003 October 31
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement date and time
** functions for SQLite.  
**
** There is only one exported symbol in this file - the function
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: date.c,v 1.107 2009/05/03 20:23:53 drh Exp $
**
** SQLite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system. 
**
** 1970-01-01 00:00:00 is JD 2440587.5
** 2000-01-01 00:00:00 is JD 2451544.5
**
** This implemention requires years to be expressed as a 4-digit number
** which means that only dates between 0000-01-01 and 9999-12-31 can
** be represented, even though julian day numbers allow a much wider
** range of dates.
**
** The Gregorian calendar system is used for all dates and times,
** even those that predate the Gregorian calendar.  Historians usually
** use the Julian calendar for dates prior to 1582-10-15 and for some
** dates afterwards, depending on locale.  Beware of this difference.
**
** The conversion algorithms are implemented based on descriptions
** in the following text:
**
**      Jean Meeus
**      Astronomical Algorithms, 2nd Edition, 1998
**      ISBM 0-943396-61-1
**      Willmann-Bell, Inc
**      Richmond, Virginia (USA)
*/
#include "sqliteInt.h"
#include <stdlib.h>
#include <assert.h>
#include <time.h>

#ifndef SQLITE_OMIT_DATETIME_FUNCS

/*
** On recent Windows platforms, the localtime_s() function is available
** as part of the "Secure CRT". It is essentially equivalent to 
** localtime_r() available under most POSIX platforms, except that the 
** order of the parameters is reversed.
**
** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
**
** If the user has not indicated to use localtime_r() or localtime_s()
** already, check for an MSVC build environment that provides 
** localtime_s().
*/
#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
#define HAVE_LOCALTIME_S 1
#endif

/*
** A structure for holding a single date and time.
*/
typedef struct DateTime DateTime;
struct DateTime {
  sqlite3_int64 iJD; /* The julian day number times 86400000 */
  int Y, M, D;       /* Year, month, and day */
  int h, m;          /* Hour and minutes */
  int tz;            /* Timezone offset in minutes */
  double s;          /* Seconds */
  char validYMD;     /* True (1) if Y,M,D are valid */
  char validHMS;     /* True (1) if h,m,s are valid */
  char validJD;      /* True (1) if iJD is valid */
  char validTZ;      /* True (1) if tz is valid */
};


/*
** Convert zDate into one or more integers.  Additional arguments
** come in groups of 5 as follows:
**
**       N       number of digits in the integer
**       min     minimum allowed value of the integer
**       max     maximum allowed value of the integer
**       nextC   first character after the integer
**       pVal    where to write the integers value.
**
** Conversions continue until one with nextC==0 is encountered.
** The function returns the number of successful conversions.
*/
static int getDigits(const char *zDate, ...){
  va_list ap;
  int val;
  int N;
  int min;
  int max;
  int nextC;
  int *pVal;
  int cnt = 0;
  va_start(ap, zDate);
  do{
    N = va_arg(ap, int);
    min = va_arg(ap, int);
    max = va_arg(ap, int);
    nextC = va_arg(ap, int);
    pVal = va_arg(ap, int*);
    val = 0;
    while( N-- ){
      if( !sqlite3Isdigit(*zDate) ){
        goto end_getDigits;
      }
      val = val*10 + *zDate - '0';
      zDate++;
    }
    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
      goto end_getDigits;
    }
    *pVal = val;
    zDate++;
    cnt++;
  }while( nextC );
end_getDigits:
  va_end(ap);
  return cnt;
}

/*
** Read text from z[] and convert into a floating point number.  Return
** the number of digits converted.
*/
#define getValue sqlite3AtoF

/*
** Parse a timezone extension on the end of a date-time.
** The extension is of the form:
**
**        (+/-)HH:MM
**
** Or the "zulu" notation:
**
**        Z
**
** If the parse is successful, write the number of minutes
** of change in p->tz and return 0.  If a parser error occurs,
** return non-zero.
**
** A missing specifier is not considered an error.
*/
static int parseTimezone(const char *zDate, DateTime *p){
  int sgn = 0;
  int nHr, nMn;
  int c;
  while( sqlite3Isspace(*zDate) ){ zDate++; }
  p->tz = 0;
  c = *zDate;
  if( c=='-' ){
    sgn = -1;
  }else if( c=='+' ){
    sgn = +1;
  }else if( c=='Z' || c=='z' ){
    zDate++;
    goto zulu_time;
  }else{
    return c!=0;
  }
  zDate++;
  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
    return 1;
  }
  zDate += 5;
  p->tz = sgn*(nMn + nHr*60);
zulu_time:
  while( sqlite3Isspace(*zDate) ){ zDate++; }
  return *zDate!=0;
}

/*
** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
** The HH, MM, and SS must each be exactly 2 digits.  The
** fractional seconds FFFF can be one or more digits.
**
** Return 1 if there is a parsing error and 0 on success.
*/
static int parseHhMmSs(const char *zDate, DateTime *p){
  int h, m, s;
  double ms = 0.0;
  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
    return 1;
  }
  zDate += 5;
  if( *zDate==':' ){
    zDate++;
    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
      return 1;
    }
    zDate += 2;
    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
      double rScale = 1.0;
      zDate++;
      while( sqlite3Isdigit(*zDate) ){
        ms = ms*10.0 + *zDate - '0';
        rScale *= 10.0;
        zDate++;
      }
      ms /= rScale;
    }
  }else{
    s = 0;
  }
  p->validJD = 0;
  p->validHMS = 1;
  p->h = h;
  p->m = m;
  p->s = s + ms;
  if( parseTimezone(zDate, p) ) return 1;
  p->validTZ = (p->tz!=0)?1:0;
  return 0;
}

/*
** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
** that the YYYY-MM-DD is according to the Gregorian calendar.
**
** Reference:  Meeus page 61
*/
static void computeJD(DateTime *p){
  int Y, M, D, A, B, X1, X2;

  if( p->validJD ) return;
  if( p->validYMD ){
    Y = p->Y;
    M = p->M;
    D = p->D;
  }else{
    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
    M = 1;
    D = 1;
  }
  if( M<=2 ){
    Y--;
    M += 12;
  }
  A = Y/100;
  B = 2 - A + (A/4);
  X1 = 36525*(Y+4716)/100;
  X2 = 306001*(M+1)/10000;
  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  p->validJD = 1;
  if( p->validHMS ){
    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
    if( p->validTZ ){
      p->iJD -= p->tz*60000;
      p->validYMD = 0;
      p->validHMS = 0;
      p->validTZ = 0;
    }
  }
}

/*
** Parse dates of the form
**
**     YYYY-MM-DD HH:MM:SS.FFF
**     YYYY-MM-DD HH:MM:SS
**     YYYY-MM-DD HH:MM
**     YYYY-MM-DD
**
** Write the result into the DateTime structure and return 0
** on success and 1 if the input string is not a well-formed
** date.
*/
static int parseYyyyMmDd(const char *zDate, DateTime *p){
  int Y, M, D, neg;

  if( zDate[0]=='-' ){
    zDate++;
    neg = 1;
  }else{
    neg = 0;
  }
  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
    return 1;
  }
  zDate += 10;
  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  if( parseHhMmSs(zDate, p)==0 ){
    /* We got the time */
  }else if( *zDate==0 ){
    p->validHMS = 0;
  }else{
    return 1;
  }
  p->validJD = 0;
  p->validYMD = 1;
  p->Y = neg ? -Y : Y;
  p->M = M;
  p->D = D;
  if( p->validTZ ){
    computeJD(p);
  }
  return 0;
}

/*
** Set the time to the current time reported by the VFS
*/
static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  double r;
  sqlite3 *db = sqlite3_context_db_handle(context);
  sqlite3OsCurrentTime(db->pVfs, &r);
  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  p->validJD = 1;
}

/*
** Attempt to parse the given string into a Julian Day Number.  Return
** the number of errors.
**
** The following are acceptable forms for the input string:
**
**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
**      DDDD.DD 
**      now
**
** In the first form, the +/-HH:MM is always optional.  The fractional
** seconds extension (the ".FFF") is optional.  The seconds portion
** (":SS.FFF") is option.  The year and date can be omitted as long
** as there is a time string.  The time string can be omitted as long
** as there is a year and date.
*/
static int parseDateOrTime(
  sqlite3_context *context, 
  const char *zDate, 
  DateTime *p
){
  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
  if( parseYyyyMmDd(zDate,p)==0 ){
    return 0;
  }else if( parseHhMmSs(zDate, p)==0 ){
    return 0;
  }else if( sqlite3StrICmp(zDate,"now")==0){
    setDateTimeToCurrent(context, p);
    return 0;
  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
    double r;
    getValue(zDate, &r);
    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
    p->validJD = 1;
    return 0;
  }
  return 1;
}

/*
** Compute the Year, Month, and Day from the julian day number.
*/
static void computeYMD(DateTime *p){
  int Z, A, B, C, D, E, X1;
  if( p->validYMD ) return;
  if( !p->validJD ){
    p->Y = 2000;
    p->M = 1;
    p->D = 1;
  }else{
    Z = (int)((p->iJD + 43200000)/86400000);
    A = (int)((Z - 1867216.25)/36524.25);
    A = Z + 1 + A - (A/4);
    B = A + 1524;
    C = (int)((B - 122.1)/365.25);
    D = (36525*C)/100;
    E = (int)((B-D)/30.6001);
    X1 = (int)(30.6001*E);
    p->D = B - D - X1;
    p->M = E<14 ? E-1 : E-13;
    p->Y = p->M>2 ? C - 4716 : C - 4715;
  }
  p->validYMD = 1;
}

/*
** Compute the Hour, Minute, and Seconds from the julian day number.
*/
static void computeHMS(DateTime *p){
  int s;
  if( p->validHMS ) return;
  computeJD(p);
  s = (int)((p->iJD + 43200000) % 86400000);
  p->s = s/1000.0;
  s = (int)p->s;
  p->s -= s;
  p->h = s/3600;
  s -= p->h*3600;
  p->m = s/60;
  p->s += s - p->m*60;
  p->validHMS = 1;
}

/*
** Compute both YMD and HMS
*/
static void computeYMD_HMS(DateTime *p){
  computeYMD(p);
  computeHMS(p);
}

/*
** Clear the YMD and HMS and the TZ
*/
static void clearYMD_HMS_TZ(DateTime *p){
  p->validYMD = 0;
  p->validHMS = 0;
  p->validTZ = 0;
}

#ifndef SQLITE_OMIT_LOCALTIME
/*
** Compute the difference (in milliseconds)
** between localtime and UTC (a.k.a. GMT)
** for the time value p where p is in UTC.
*/
static sqlite3_int64 localtimeOffset(DateTime *p){
  DateTime x, y;
  time_t t;
  x = *p;
  computeYMD_HMS(&x);
  if( x.Y<1971 || x.Y>=2038 ){
    x.Y = 2000;
    x.M = 1;
    x.D = 1;
    x.h = 0;
    x.m = 0;
    x.s = 0.0;
  } else {
    int s = (int)(x.s + 0.5);
    x.s = s;
  }
  x.tz = 0;
  x.validJD = 0;
  computeJD(&x);
  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
#ifdef HAVE_LOCALTIME_R
  {
    struct tm sLocal;
    localtime_r(&t, &sLocal);
    y.Y = sLocal.tm_year + 1900;
    y.M = sLocal.tm_mon + 1;
    y.D = sLocal.tm_mday;
    y.h = sLocal.tm_hour;
    y.m = sLocal.tm_min;
    y.s = sLocal.tm_sec;
  }
#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
  {
    struct tm sLocal;
    localtime_s(&sLocal, &t);
    y.Y = sLocal.tm_year + 1900;
    y.M = sLocal.tm_mon + 1;
    y.D = sLocal.tm_mday;
    y.h = sLocal.tm_hour;
    y.m = sLocal.tm_min;
    y.s = sLocal.tm_sec;
  }
#else
  {
    struct tm *pTm;
    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
    pTm = localtime(&t);
    y.Y = pTm->tm_year + 1900;
    y.M = pTm->tm_mon + 1;
    y.D = pTm->tm_mday;
    y.h = pTm->tm_hour;
    y.m = pTm->tm_min;
    y.s = pTm->tm_sec;
    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  }
#endif
  y.validYMD = 1;
  y.validHMS = 1;
  y.validJD = 0;
  y.validTZ = 0;
  computeJD(&y);
  return y.iJD - x.iJD;
}
#endif /* SQLITE_OMIT_LOCALTIME */

/*
** Process a modifier to a date-time stamp.  The modifiers are
** as follows:
**
**     NNN days
**     NNN hours
**     NNN minutes
**     NNN.NNNN seconds
**     NNN months
**     NNN years
**     start of month
**     start of year
**     start of week
**     start of day
**     weekday N
**     unixepoch
**     localtime
**     utc
**
** Return 0 on success and 1 if there is any kind of error.
*/
static int parseModifier(const char *zMod, DateTime *p){
  int rc = 1;
  int n;
  double r;
  char *z, zBuf[30];
  z = zBuf;
  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  }
  z[n] = 0;
  switch( z[0] ){
#ifndef SQLITE_OMIT_LOCALTIME
    case 'l': {
      /*    localtime
      **
      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
      ** show local time.
      */
      if( strcmp(z, "localtime")==0 ){
        computeJD(p);
        p->iJD += localtimeOffset(p);
        clearYMD_HMS_TZ(p);
        rc = 0;
      }
      break;
    }
#endif
    case 'u': {
      /*
      **    unixepoch
      **
      ** Treat the current value of p->iJD as the number of
      ** seconds since 1970.  Convert to a real julian day number.
      */
      if( strcmp(z, "unixepoch")==0 && p->validJD ){
        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
        clearYMD_HMS_TZ(p);
        rc = 0;
      }
#ifndef SQLITE_OMIT_LOCALTIME
      else if( strcmp(z, "utc")==0 ){
        sqlite3_int64 c1;
        computeJD(p);
        c1 = localtimeOffset(p);
        p->iJD -= c1;
        clearYMD_HMS_TZ(p);
        p->iJD += c1 - localtimeOffset(p);
        rc = 0;
      }
#endif
      break;
    }
    case 'w': {
      /*
      **    weekday N
      **
      ** Move the date to the same time on the next occurrence of
      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
      ** date is already on the appropriate weekday, this is a no-op.
      */
      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
                 && (n=(int)r)==r && n>=0 && r<7 ){
        sqlite3_int64 Z;
        computeYMD_HMS(p);
        p->validTZ = 0;
        p->validJD = 0;
        computeJD(p);
        Z = ((p->iJD + 129600000)/86400000) % 7;
        if( Z>n ) Z -= 7;
        p->iJD += (n - Z)*86400000;
        clearYMD_HMS_TZ(p);
        rc = 0;
      }
      break;
    }
    case 's': {
      /*
      **    start of TTTTT
      **
      ** Move the date backwards to the beginning of the current day,
      ** or month or year.
      */
      if( strncmp(z, "start of ", 9)!=0 ) break;
      z += 9;
      computeYMD(p);
      p->validHMS = 1;
      p->h = p->m = 0;
      p->s = 0.0;
      p->validTZ = 0;
      p->validJD = 0;
      if( strcmp(z,"month")==0 ){
        p->D = 1;
        rc = 0;
      }else if( strcmp(z,"year")==0 ){
        computeYMD(p);
        p->M = 1;
        p->D = 1;
        rc = 0;
      }else if( strcmp(z,"day")==0 ){
        rc = 0;
      }
      break;
    }
    case '+':
    case '-':
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': {
      double rRounder;
      n = getValue(z, &r);
      assert( n>=1 );
      if( z[n]==':' ){
        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
        ** specified number of hours, minutes, seconds, and fractional seconds
        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
        ** omitted.
        */
        const char *z2 = z;
        DateTime tx;
        sqlite3_int64 day;
        if( !sqlite3Isdigit(*z2) ) z2++;
        memset(&tx, 0, sizeof(tx));
        if( parseHhMmSs(z2, &tx) ) break;
        computeJD(&tx);
        tx.iJD -= 43200000;
        day = tx.iJD/86400000;
        tx.iJD -= day*86400000;
        if( z[0]=='-' ) tx.iJD = -tx.iJD;
        computeJD(p);
        clearYMD_HMS_TZ(p);
        p->iJD += tx.iJD;
        rc = 0;
        break;
      }
      z += n;
      while( sqlite3Isspace(*z) ) z++;
      n = sqlite3Strlen30(z);
      if( n>10 || n<3 ) break;
      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
      computeJD(p);
      rc = 0;
      rRounder = r<0 ? -0.5 : +0.5;
      if( n==3 && strcmp(z,"day")==0 ){
        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
      }else if( n==4 && strcmp(z,"hour")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
      }else if( n==6 && strcmp(z,"minute")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
      }else if( n==6 && strcmp(z,"second")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
      }else if( n==5 && strcmp(z,"month")==0 ){
        int x, y;
        computeYMD_HMS(p);
        p->M += (int)r;
        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
        p->Y += x;
        p->M -= x*12;
        p->validJD = 0;
        computeJD(p);
        y = (int)r;
        if( y!=r ){
          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
        }
      }else if( n==4 && strcmp(z,"year")==0 ){
        int y = (int)r;
        computeYMD_HMS(p);
        p->Y += y;
        p->validJD = 0;
        computeJD(p);
        if( y!=r ){
          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
        }
      }else{
        rc = 1;
      }
      clearYMD_HMS_TZ(p);
      break;
    }
    default: {
      break;
    }
  }
  return rc;
}

/*
** Process time function arguments.  argv[0] is a date-time stamp.
** argv[1] and following are modifiers.  Parse them all and write
** the resulting time into the DateTime structure p.  Return 0
** on success and 1 if there are any errors.
**
** If there are zero parameters (if even argv[0] is undefined)
** then assume a default value of "now" for argv[0].
*/
static int isDate(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv, 
  DateTime *p
){
  int i;
  const unsigned char *z;
  int eType;
  memset(p, 0, sizeof(*p));
  if( argc==0 ){
    setDateTimeToCurrent(context, p);
  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
                   || eType==SQLITE_INTEGER ){
    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
    p->validJD = 1;
  }else{
    z = sqlite3_value_text(argv[0]);
    if( !z || parseDateOrTime(context, (char*)z, p) ){
      return 1;
    }
  }
  for(i=1; i<argc; i++){
    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
      return 1;
    }
  }
  return 0;
}


/*
** The following routines implement the various date and time functions
** of SQLite.
*/

/*
**    julianday( TIMESTRING, MOD, MOD, ...)
**
** Return the julian day number of the date specified in the arguments
*/
static void juliandayFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    computeJD(&x);
    sqlite3_result_double(context, x.iJD/86400000.0);
  }
}

/*
**    datetime( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD HH:MM:SS
*/
static void datetimeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
*/
static void timeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
*/
static void dateFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
** Return a string described by FORMAT.  Conversions as follows:
**
**   %d  day of month
**   %f  ** fractional seconds  SS.SSS
**   %H  hour 00-24
**   %j  day of year 000-366
**   %J  ** Julian day number
**   %m  month 01-12
**   %M  minute 00-59
**   %s  seconds since 1970-01-01
**   %S  seconds 00-59
**   %w  day of week 0-6  sunday==0
**   %W  week of year 00-53
**   %Y  year 0000-9999
**   %%  %
*/
static void strftimeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  u64 n;
  size_t i,j;
  char *z;
  sqlite3 *db;
  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  char zBuf[100];
  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  db = sqlite3_context_db_handle(context);
  for(i=0, n=1; zFmt[i]; i++, n++){
    if( zFmt[i]=='%' ){
      switch( zFmt[i+1] ){
        case 'd':
        case 'H':
        case 'm':
        case 'M':
        case 'S':
        case 'W':
          n++;
          /* fall thru */
        case 'w':
        case '%':
          break;
        case 'f':
          n += 8;
          break;
        case 'j':
          n += 3;
          break;
        case 'Y':
          n += 8;
          break;
        case 's':
        case 'J':
          n += 50;
          break;
        default:
          return;  /* ERROR.  return a NULL */
      }
      i++;
    }
  }
  testcase( n==sizeof(zBuf)-1 );
  testcase( n==sizeof(zBuf) );
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  if( n<sizeof(zBuf) ){
    z = zBuf;
  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite3_result_error_toobig(context);
    return;
  }else{
    z = sqlite3DbMallocRaw(db, (int)n);
    if( z==0 ){
      sqlite3_result_error_nomem(context);
      return;
    }
  }
  computeJD(&x);
  computeYMD_HMS(&x);
  for(i=j=0; zFmt[i]; i++){
    if( zFmt[i]!='%' ){
      z[j++] = zFmt[i];
    }else{
      i++;
      switch( zFmt[i] ){
        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
        case 'f': {
          double s = x.s;
          if( s>59.999 ) s = 59.999;
          sqlite3_snprintf(7, &z[j],"%06.3f", s);
          j += sqlite3Strlen30(&z[j]);
          break;
        }
        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
        case 'W': /* Fall thru */
        case 'j': {
          int nDay;             /* Number of days since 1st day of year */
          DateTime y = x;
          y.validJD = 0;
          y.M = 1;
          y.D = 1;
          computeJD(&y);
          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
          if( zFmt[i]=='W' ){
            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
            wd = (int)(((x.iJD+43200000)/86400000)%7);
            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
            j += 2;
          }else{
            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
            j += 3;
          }
          break;
        }
        case 'J': {
          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
          j+=sqlite3Strlen30(&z[j]);
          break;
        }
        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
        case 's': {
          sqlite3_snprintf(30,&z[j],"%lld",
                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
          j += sqlite3Strlen30(&z[j]);
          break;
        }
        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
        case 'w': {
          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
          break;
        }
        case 'Y': {
          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
          break;
        }
        default:   z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;
  sqlite3_result_text(context, z, -1,
                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
}

/*
** current_time()
**
** This function returns the same value as time('now').
*/
static void ctimeFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  timeFunc(context, 0, 0);
}

/*
** current_date()
**
** This function returns the same value as date('now').
*/
static void cdateFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  dateFunc(context, 0, 0);
}

/*
** current_timestamp()
**
** This function returns the same value as datetime('now').
*/
static void ctimestampFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  datetimeFunc(context, 0, 0);
}
#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */

#ifdef SQLITE_OMIT_DATETIME_FUNCS
/*
** If the library is compiled to omit the full-scale date and time
** handling (to get a smaller binary), the following minimal version
** of the functions current_time(), current_date() and current_timestamp()
** are included instead. This is to support column declarations that
** include "DEFAULT CURRENT_TIME" etc.
**
** This function uses the C-library functions time(), gmtime()
** and strftime(). The format string to pass to strftime() is supplied
** as the user-data for the function.
*/
static void currentTimeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  time_t t;
  char *zFormat = (char *)sqlite3_user_data(context);
  sqlite3 *db;
  double rT;
  char zBuf[20];

  UNUSED_PARAMETER(argc);
  UNUSED_PARAMETER(argv);

  db = sqlite3_context_db_handle(context);
  sqlite3OsCurrentTime(db->pVfs, &rT);
#ifndef SQLITE_OMIT_FLOATING_POINT
  t = 86400.0*(rT - 2440587.5) + 0.5;
#else
  /* without floating point support, rT will have
  ** already lost fractional day precision.
  */
  t = 86400 * (rT - 2440587) - 43200;
#endif
#ifdef HAVE_GMTIME_R
  {
    struct tm sNow;
    gmtime_r(&t, &sNow);
    strftime(zBuf, 20, zFormat, &sNow);
  }
#else
  {
    struct tm *pTm;
    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
    pTm = gmtime(&t);
    strftime(zBuf, 20, zFormat, pTm);
    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  }
#endif

  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
}
#endif

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
void sqlite3RegisterDateTimeFunctions(void){
  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
#ifndef SQLITE_OMIT_DATETIME_FUNCS
    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
    FUNCTION(date,             -1, 0, 0, dateFunc      ),
    FUNCTION(time,             -1, 0, 0, timeFunc      ),
    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
#else
    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
    STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
#endif
  };
  int i;
  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);

  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
  }
}

Added src/delete.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
**
** $Id: delete.c,v 1.207 2009/08/08 18:01:08 drh Exp $
*/
#include "sqliteInt.h"

/*
** Look up every table that is named in pSrc.  If any table is not found,
** add an error message to pParse->zErrMsg and return NULL.  If all tables
** are found, return a pointer to the last table.
*/
Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  struct SrcList_item *pItem = pSrc->a;
  Table *pTab;
  assert( pItem && pSrc->nSrc==1 );
  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  sqlite3DeleteTable(pItem->pTab);
  pItem->pTab = pTab;
  if( pTab ){
    pTab->nRef++;
  }
  if( sqlite3IndexedByLookup(pParse, pItem) ){
    pTab = 0;
  }
  return pTab;
}

/*
** Check to make sure the given table is writable.  If it is not
** writable, generate an error message and return 1.  If it is
** writable return 0;
*/
int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  /* A table is not writable under the following circumstances:
  **
  **   1) It is a virtual table and no implementation of the xUpdate method
  **      has been provided, or
  **   2) It is a system table (i.e. sqlite_master), this call is not
  **      part of a nested parse and writable_schema pragma has not 
  **      been specified.
  **
  ** In either case leave an error message in pParse and return non-zero.
  */
  if( ( IsVirtual(pTab) 
     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   || ( (pTab->tabFlags & TF_Readonly)!=0
     && (pParse->db->flags & SQLITE_WriteSchema)==0
     && pParse->nested==0 )
  ){
    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
    return 1;
  }

#ifndef SQLITE_OMIT_VIEW
  if( !viewOk && pTab->pSelect ){
    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
    return 1;
  }
#endif
  return 0;
}


#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
/*
** Evaluate a view and store its result in an ephemeral table.  The
** pWhere argument is an optional WHERE clause that restricts the
** set of rows in the view that are to be added to the ephemeral table.
*/
void sqlite3MaterializeView(
  Parse *pParse,       /* Parsing context */
  Table *pView,        /* View definition */
  Expr *pWhere,        /* Optional WHERE clause to be added */
  int iCur             /* Cursor number for ephemerial table */
){
  SelectDest dest;
  Select *pDup;
  sqlite3 *db = pParse->db;

  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
  if( pWhere ){
    SrcList *pFrom;
    
    pWhere = sqlite3ExprDup(db, pWhere, 0);
    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
    if( pFrom ){
      assert( pFrom->nSrc==1 );
      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
      pFrom->a[0].pSelect = pDup;
      assert( pFrom->a[0].pOn==0 );
      assert( pFrom->a[0].pUsing==0 );
    }else{
      sqlite3SelectDelete(db, pDup);
    }
    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  }
  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  sqlite3Select(pParse, pDup, &dest);
  sqlite3SelectDelete(db, pDup);
}
#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */

#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
/*
** Generate an expression tree to implement the WHERE, ORDER BY,
** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
**
**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
**                            \__________________________/
**                               pLimitWhere (pInClause)
*/
Expr *sqlite3LimitWhere(
  Parse *pParse,               /* The parser context */
  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
  Expr *pWhere,                /* The WHERE clause.  May be null */
  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
  Expr *pLimit,                /* The LIMIT clause.  May be null */
  Expr *pOffset,               /* The OFFSET clause.  May be null */
  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
){
  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
  Select *pSelect = NULL;      /* Complete SELECT tree */

  /* Check that there isn't an ORDER BY without a LIMIT clause.
  */
  if( pOrderBy && (pLimit == 0) ) {
    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
    pParse->parseError = 1;
    goto limit_where_cleanup_2;
  }

  /* We only need to generate a select expression if there
  ** is a limit/offset term to enforce.
  */
  if( pLimit == 0 ) {
    /* if pLimit is null, pOffset will always be null as well. */
    assert( pOffset == 0 );
    return pWhere;
  }

  /* Generate a select expression tree to enforce the limit/offset 
  ** term for the DELETE or UPDATE statement.  For example:
  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  ** becomes:
  **   DELETE FROM table_a WHERE rowid IN ( 
  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  **   );
  */

  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  if( pEList == 0 ) goto limit_where_cleanup_2;

  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  ** and the SELECT subtree. */
  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  if( pSelectSrc == 0 ) {
    sqlite3ExprListDelete(pParse->db, pEList);
    goto limit_where_cleanup_2;
  }

  /* generate the SELECT expression tree. */
  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
                             pOrderBy,0,pLimit,pOffset);
  if( pSelect == 0 ) return 0;

  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  if( pInClause == 0 ) goto limit_where_cleanup_1;

  pInClause->x.pSelect = pSelect;
  pInClause->flags |= EP_xIsSelect;
  sqlite3ExprSetHeight(pParse, pInClause);
  return pInClause;

  /* something went wrong. clean up anything allocated. */
limit_where_cleanup_1:
  sqlite3SelectDelete(pParse->db, pSelect);
  return 0;

limit_where_cleanup_2:
  sqlite3ExprDelete(pParse->db, pWhere);
  sqlite3ExprListDelete(pParse->db, pOrderBy);
  sqlite3ExprDelete(pParse->db, pLimit);
  sqlite3ExprDelete(pParse->db, pOffset);
  return 0;
}
#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */

/*
** Generate code for a DELETE FROM statement.
**
**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
**                 \________/       \________________/
**                  pTabList              pWhere
*/
void sqlite3DeleteFrom(
  Parse *pParse,         /* The parser context */
  SrcList *pTabList,     /* The table from which we should delete things */
  Expr *pWhere           /* The WHERE clause.  May be null */
){
  Vdbe *v;               /* The virtual database engine */
  Table *pTab;           /* The table from which records will be deleted */
  const char *zDb;       /* Name of database holding pTab */
  int end, addr = 0;     /* A couple addresses of generated code */
  int i;                 /* Loop counter */
  WhereInfo *pWInfo;     /* Information about the WHERE clause */
  Index *pIdx;           /* For looping over indices of the table */
  int iCur;              /* VDBE Cursor number for pTab */
  sqlite3 *db;           /* Main database structure */
  AuthContext sContext;  /* Authorization context */
  NameContext sNC;       /* Name context to resolve expressions in */
  int iDb;               /* Database number */
  int memCnt = -1;       /* Memory cell used for change counting */
  int rcauth;            /* Value returned by authorization callback */

#ifndef SQLITE_OMIT_TRIGGER
  int isView;                  /* True if attempting to delete from a view */
  Trigger *pTrigger;           /* List of table triggers, if required */
#endif

  memset(&sContext, 0, sizeof(sContext));
  db = pParse->db;
  if( pParse->nErr || db->mallocFailed ){
    goto delete_from_cleanup;
  }
  assert( pTabList->nSrc==1 );

  /* Locate the table which we want to delete.  This table has to be
  ** put in an SrcList structure because some of the subroutines we
  ** will be calling are designed to work with multiple tables and expect
  ** an SrcList* parameter instead of just a Table* parameter.
  */
  pTab = sqlite3SrcListLookup(pParse, pTabList);
  if( pTab==0 )  goto delete_from_cleanup;

  /* Figure out if we have any triggers and if the table being
  ** deleted from is a view
  */
#ifndef SQLITE_OMIT_TRIGGER
  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  isView = pTab->pSelect!=0;
#else
# define pTrigger 0
# define isView 0
#endif
#ifdef SQLITE_OMIT_VIEW
# undef isView
# define isView 0
#endif

  /* If pTab is really a view, make sure it has been initialized.
  */
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto delete_from_cleanup;
  }

  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
    goto delete_from_cleanup;
  }
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  assert( iDb<db->nDb );
  zDb = db->aDb[iDb].zName;
  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  if( rcauth==SQLITE_DENY ){
    goto delete_from_cleanup;
  }
  assert(!isView || pTrigger);

  /* Assign  cursor number to the table and all its indices.
  */
  assert( pTabList->nSrc==1 );
  iCur = pTabList->a[0].iCursor = pParse->nTab++;
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
    pParse->nTab++;
  }

  /* Start the view context
  */
  if( isView ){
    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  }

  /* Begin generating code.
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ){
    goto delete_from_cleanup;
  }
  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  sqlite3BeginWriteOperation(pParse, 1, iDb);

  /* If we are trying to delete from a view, realize that view into
  ** a ephemeral table.
  */
#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  if( isView ){
    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  }
#endif

  /* Resolve the column names in the WHERE clause.
  */
  memset(&sNC, 0, sizeof(sNC));
  sNC.pParse = pParse;
  sNC.pSrcList = pTabList;
  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
    goto delete_from_cleanup;
  }

  /* Initialize the counter of the number of rows deleted, if
  ** we are counting rows.
  */
  if( db->flags & SQLITE_CountRows ){
    memCnt = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  }

#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  /* Special case: A DELETE without a WHERE clause deletes everything.
  ** It is easier just to erase the whole table. Prior to version 3.6.5,
  ** this optimization caused the row change count (the value returned by 
  ** API function sqlite3_count_changes) to be set incorrectly.  */
  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  ){
    assert( !isView );
    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
                      pTab->zName, P4_STATIC);
    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
      assert( pIdx->pSchema==pTab->pSchema );
      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
    }
  }else
#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  /* The usual case: There is a WHERE clause so we have to scan through
  ** the table and pick which records to delete.
  */
  {
    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
    int regRowid;                   /* Actual register containing rowids */

    /* Collect rowids of every row to be deleted.
    */
    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
    if( pWInfo==0 ) goto delete_from_cleanup;
    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
    if( db->flags & SQLITE_CountRows ){
      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
    }
    sqlite3WhereEnd(pWInfo);

    /* Delete every item whose key was written to the list during the
    ** database scan.  We have to delete items after the scan is complete
    ** because deleting an item can change the scan order.  */
    end = sqlite3VdbeMakeLabel(v);

    /* Unless this is a view, open cursors for the table we are 
    ** deleting from and all its indices. If this is a view, then the
    ** only effect this statement has is to fire the INSTEAD OF 
    ** triggers.  */
    if( !isView ){
      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
    }

    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);

    /* Delete the row */
#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( IsVirtual(pTab) ){
      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
      sqlite3VtabMakeWritable(pParse, pTab);
      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
      sqlite3MayAbort(pParse);
    }else
#endif
    {
      int count = (pParse->nested==0);    /* True to count changes */
      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
    }

    /* End of the delete loop */
    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
    sqlite3VdbeResolveLabel(v, end);

    /* Close the cursors open on the table and its indexes. */
    if( !isView && !IsVirtual(pTab) ){
      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
      }
      sqlite3VdbeAddOp1(v, OP_Close, iCur);
    }
  }

  /* Update the sqlite_sequence table by storing the content of the
  ** maximum rowid counter values recorded while inserting into
  ** autoincrement tables.
  */
  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
    sqlite3AutoincrementEnd(pParse);
  }

  /* Return the number of rows that were deleted. If this routine is 
  ** generating code because of a call to sqlite3NestedParse(), do not
  ** invoke the callback function.
  */
  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  }

delete_from_cleanup:
  sqlite3AuthContextPop(&sContext);
  sqlite3SrcListDelete(db, pTabList);
  sqlite3ExprDelete(db, pWhere);
  return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation).  */
#ifdef isView
 #undef isView
#endif
#ifdef pTrigger
 #undef pTrigger
#endif

/*
** This routine generates VDBE code that causes a single row of a
** single table to be deleted.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
**   1.  A read/write cursor pointing to pTab, the table containing the row
**       to be deleted, must be opened as cursor number $iCur.
**
**   2.  Read/write cursors for all indices of pTab must be open as
**       cursor number base+i for the i-th index.
**
**   3.  The record number of the row to be deleted must be stored in
**       memory cell iRowid.
**
** This routine generates code to remove both the table record and all 
** index entries that point to that record.
*/
void sqlite3GenerateRowDelete(
  Parse *pParse,     /* Parsing context */
  Table *pTab,       /* Table containing the row to be deleted */
  int iCur,          /* Cursor number for the table */
  int iRowid,        /* Memory cell that contains the rowid to delete */
  int count,         /* If non-zero, increment the row change counter */
  Trigger *pTrigger, /* List of triggers to (potentially) fire */
  int onconf         /* Default ON CONFLICT policy for triggers */
){
  Vdbe *v = pParse->pVdbe;        /* Vdbe */
  int iOld = 0;                   /* First register in OLD.* array */
  int iLabel;                     /* Label resolved to end of generated code */

  /* Vdbe is guaranteed to have been allocated by this stage. */
  assert( v );

  /* Seek cursor iCur to the row to delete. If this row no longer exists 
  ** (this can happen if a trigger program has already deleted it), do
  ** not attempt to delete it or fire any DELETE triggers.  */
  iLabel = sqlite3VdbeMakeLabel(v);
  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
 
  /* If there are any triggers to fire, allocate a range of registers to
  ** use for the old.* references in the triggers.  */
  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
    u32 mask;                     /* Mask of OLD.* columns in use */
    int iCol;                     /* Iterator used while populating OLD.* */

    /* TODO: Could use temporary registers here. Also could attempt to
    ** avoid copying the contents of the rowid register.  */
    mask = sqlite3TriggerOldmask(pParse, pTrigger, 0, pTab, onconf);
    mask |= sqlite3FkOldmask(pParse, pTab);
    iOld = pParse->nMem+1;
    pParse->nMem += (1 + pTab->nCol);

    /* Populate the OLD.* pseudo-table register array. These values will be 
    ** used by any BEFORE and AFTER triggers that exist.  */
    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
    for(iCol=0; iCol<pTab->nCol; iCol++){
      if( mask==0xffffffff || mask&(1<<iCol) ){
        int iTarget = iOld + iCol + 1;
        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
      }
    }

    /* Invoke BEFORE DELETE trigger programs. */
    sqlite3CodeRowTrigger(pParse, pTrigger, 
        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
    );

    /* Seek the cursor to the row to be deleted again. It may be that
    ** the BEFORE triggers coded above have already removed the row
    ** being deleted. Do not attempt to delete the row a second time, and 
    ** do not fire AFTER triggers.  */
    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);

    /* Do FK processing. This call checks that any FK constraints that
    ** refer to this table (i.e. constraints attached to other tables) 
    ** are not violated by deleting this row.  */
    sqlite3FkCheck(pParse, pTab, iOld, 0);
  }

  /* Delete the index and table entries. Skip this step if pTab is really
  ** a view (in which case the only effect of the DELETE statement is to
  ** fire the INSTEAD OF triggers).  */ 
  if( pTab->pSelect==0 ){
    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
    if( count ){
      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
    }
  }

  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  ** handle rows (possibly in other tables) that refer via a foreign key
  ** to the row just deleted. */ 
  sqlite3FkActions(pParse, pTab, 0, iOld);

  /* Invoke AFTER DELETE trigger programs. */
  sqlite3CodeRowTrigger(pParse, pTrigger, 
      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  );

  /* Jump here if the row had already been deleted before any BEFORE
  ** trigger programs were invoked. Or if a trigger program throws a 
  ** RAISE(IGNORE) exception.  */
  sqlite3VdbeResolveLabel(v, iLabel);
}

/*
** This routine generates VDBE code that causes the deletion of all
** index entries associated with a single row of a single table.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
**   1.  A read/write cursor pointing to pTab, the table containing the row
**       to be deleted, must be opened as cursor number "iCur".
**
**   2.  Read/write cursors for all indices of pTab must be open as
**       cursor number iCur+i for the i-th index.
**
**   3.  The "iCur" cursor must be pointing to the row that is to be
**       deleted.
*/
void sqlite3GenerateRowIndexDelete(
  Parse *pParse,     /* Parsing and code generating context */
  Table *pTab,       /* Table containing the row to be deleted */
  int iCur,          /* Cursor number for the table */
  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
){
  int i;
  Index *pIdx;
  int r1;

  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
  }
}

/*
** Generate code that will assemble an index key and put it in register
** regOut.  The key with be for index pIdx which is an index on pTab.
** iCur is the index of a cursor open on the pTab table and pointing to
** the entry that needs indexing.
**
** Return a register number which is the first in a block of
** registers that holds the elements of the index key.  The
** block of registers has already been deallocated by the time
** this routine returns.
*/
int sqlite3GenerateIndexKey(
  Parse *pParse,     /* Parsing context */
  Index *pIdx,       /* The index for which to generate a key */
  int iCur,          /* Cursor number for the pIdx->pTable table */
  int regOut,        /* Write the new index key to this register */
  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
){
  Vdbe *v = pParse->pVdbe;
  int j;
  Table *pTab = pIdx->pTable;
  int regBase;
  int nCol;

  nCol = pIdx->nColumn;
  regBase = sqlite3GetTempRange(pParse, nCol+1);
  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  for(j=0; j<nCol; j++){
    int idx = pIdx->aiColumn[j];
    if( idx==pTab->iPKey ){
      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
    }else{
      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
      sqlite3ColumnDefault(v, pTab, idx, -1);
    }
  }
  if( doMakeRec ){
    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
    sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
  }
  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  return regBase;
}

Added src/expr.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
*/
#include "sqliteInt.h"

/*
** Return the 'affinity' of the expression pExpr if any.
**
** If pExpr is a column, a reference to a column via an 'AS' alias,
** or a sub-select with a column as the return value, then the 
** affinity of that column is returned. Otherwise, 0x00 is returned,
** indicating no affinity for the expression.
**
** i.e. the WHERE clause expresssions in the following statements all
** have an affinity:
**
** CREATE TABLE t1(a);
** SELECT * FROM t1 WHERE a;
** SELECT a AS b FROM t1 WHERE b;
** SELECT * FROM t1 WHERE (select a from t1);
*/
char sqlite3ExprAffinity(Expr *pExpr){
  int op = pExpr->op;
  if( op==TK_SELECT ){
    assert( pExpr->flags&EP_xIsSelect );
    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  }
#ifndef SQLITE_OMIT_CAST
  if( op==TK_CAST ){
    assert( !ExprHasProperty(pExpr, EP_IntValue) );
    return sqlite3AffinityType(pExpr->u.zToken);
  }
#endif
  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
   && pExpr->pTab!=0
  ){
    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
    ** a TK_COLUMN but was previously evaluated and cached in a register */
    int j = pExpr->iColumn;
    if( j<0 ) return SQLITE_AFF_INTEGER;
    assert( pExpr->pTab && j<pExpr->pTab->nCol );
    return pExpr->pTab->aCol[j].affinity;
  }
  return pExpr->affinity;
}

/*
** Set the collating sequence for expression pExpr to be the collating
** sequence named by pToken.   Return a pointer to the revised expression.
** The collating sequence is marked as "explicit" using the EP_ExpCollate
** flag.  An explicit collating sequence will override implicit
** collating sequences.
*/
Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
  char *zColl = 0;            /* Dequoted name of collation sequence */
  CollSeq *pColl;
  sqlite3 *db = pParse->db;
  zColl = sqlite3NameFromToken(db, pCollName);
  if( pExpr && zColl ){
    pColl = sqlite3LocateCollSeq(pParse, zColl);
    if( pColl ){
      pExpr->pColl = pColl;
      pExpr->flags |= EP_ExpCollate;
    }
  }
  sqlite3DbFree(db, zColl);
  return pExpr;
}

/*
** Return the default collation sequence for the expression pExpr. If
** there is no default collation type, return 0.
*/
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  CollSeq *pColl = 0;
  Expr *p = pExpr;
  while( ALWAYS(p) ){
    int op;
    pColl = p->pColl;
    if( pColl ) break;
    op = p->op;
    if( p->pTab!=0 && (
        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
    )){
      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
      ** a TK_COLUMN but was previously evaluated and cached in a register */
      const char *zColl;
      int j = p->iColumn;
      if( j>=0 ){
        sqlite3 *db = pParse->db;
        zColl = p->pTab->aCol[j].zColl;
        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
        pExpr->pColl = pColl;
      }
      break;
    }
    if( op!=TK_CAST && op!=TK_UPLUS ){
      break;
    }
    p = p->pLeft;
  }
  if( sqlite3CheckCollSeq(pParse, pColl) ){ 
    pColl = 0;
  }
  return pColl;
}

/*
** pExpr is an operand of a comparison operator.  aff2 is the
** type affinity of the other operand.  This routine returns the
** type affinity that should be used for the comparison operator.
*/
char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  char aff1 = sqlite3ExprAffinity(pExpr);
  if( aff1 && aff2 ){
    /* Both sides of the comparison are columns. If one has numeric
    ** affinity, use that. Otherwise use no affinity.
    */
    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
      return SQLITE_AFF_NUMERIC;
    }else{
      return SQLITE_AFF_NONE;
    }
  }else if( !aff1 && !aff2 ){
    /* Neither side of the comparison is a column.  Compare the
    ** results directly.
    */
    return SQLITE_AFF_NONE;
  }else{
    /* One side is a column, the other is not. Use the columns affinity. */
    assert( aff1==0 || aff2==0 );
    return (aff1 + aff2);
  }
}

/*
** pExpr is a comparison operator.  Return the type affinity that should
** be applied to both operands prior to doing the comparison.
*/
static char comparisonAffinity(Expr *pExpr){
  char aff;
  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  assert( pExpr->pLeft );
  aff = sqlite3ExprAffinity(pExpr->pLeft);
  if( pExpr->pRight ){
    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  }else if( !aff ){
    aff = SQLITE_AFF_NONE;
  }
  return aff;
}

/*
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
** idx_affinity is the affinity of an indexed column. Return true
** if the index with affinity idx_affinity may be used to implement
** the comparison in pExpr.
*/
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  char aff = comparisonAffinity(pExpr);
  switch( aff ){
    case SQLITE_AFF_NONE:
      return 1;
    case SQLITE_AFF_TEXT:
      return idx_affinity==SQLITE_AFF_TEXT;
    default:
      return sqlite3IsNumericAffinity(idx_affinity);
  }
}

/*
** Return the P5 value that should be used for a binary comparison
** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
*/
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  return aff;
}

/*
** Return a pointer to the collation sequence that should be used by
** a binary comparison operator comparing pLeft and pRight.
**
** If the left hand expression has a collating sequence type, then it is
** used. Otherwise the collation sequence for the right hand expression
** is used, or the default (BINARY) if neither expression has a collating
** type.
**
** Argument pRight (but not pLeft) may be a null pointer. In this case,
** it is not considered.
*/
CollSeq *sqlite3BinaryCompareCollSeq(
  Parse *pParse, 
  Expr *pLeft, 
  Expr *pRight
){
  CollSeq *pColl;
  assert( pLeft );
  if( pLeft->flags & EP_ExpCollate ){
    assert( pLeft->pColl );
    pColl = pLeft->pColl;
  }else if( pRight && pRight->flags & EP_ExpCollate ){
    assert( pRight->pColl );
    pColl = pRight->pColl;
  }else{
    pColl = sqlite3ExprCollSeq(pParse, pLeft);
    if( !pColl ){
      pColl = sqlite3ExprCollSeq(pParse, pRight);
    }
  }
  return pColl;
}

/*
** Generate the operands for a comparison operation.  Before
** generating the code for each operand, set the EP_AnyAff
** flag on the expression so that it will be able to used a
** cached column value that has previously undergone an
** affinity change.
*/
static void codeCompareOperands(
  Parse *pParse,    /* Parsing and code generating context */
  Expr *pLeft,      /* The left operand */
  int *pRegLeft,    /* Register where left operand is stored */
  int *pFreeLeft,   /* Free this register when done */
  Expr *pRight,     /* The right operand */
  int *pRegRight,   /* Register where right operand is stored */
  int *pFreeRight   /* Write temp register for right operand there */
){
  while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
  pLeft->flags |= EP_AnyAff;
  *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
  while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
  pRight->flags |= EP_AnyAff;
  *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
}

/*
** Generate code for a comparison operator.
*/
static int codeCompare(
  Parse *pParse,    /* The parsing (and code generating) context */
  Expr *pLeft,      /* The left operand */
  Expr *pRight,     /* The right operand */
  int opcode,       /* The comparison opcode */
  int in1, int in2, /* Register holding operands */
  int dest,         /* Jump here if true.  */
  int jumpIfNull    /* If true, jump if either operand is NULL */
){
  int p5;
  int addr;
  CollSeq *p4;

  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
                           (void*)p4, P4_COLLSEQ);
  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
    sqlite3ExprCacheAffinityChange(pParse, in1, 1);
    sqlite3ExprCacheAffinityChange(pParse, in2, 1);
  }
  return addr;
}

#if SQLITE_MAX_EXPR_DEPTH>0
/*
** Check that argument nHeight is less than or equal to the maximum
** expression depth allowed. If it is not, leave an error message in
** pParse.
*/
int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  int rc = SQLITE_OK;
  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  if( nHeight>mxHeight ){
    sqlite3ErrorMsg(pParse, 
       "Expression tree is too large (maximum depth %d)", mxHeight
    );
    rc = SQLITE_ERROR;
  }
  return rc;
}

/* The following three functions, heightOfExpr(), heightOfExprList()
** and heightOfSelect(), are used to determine the maximum height
** of any expression tree referenced by the structure passed as the
** first argument.
**
** If this maximum height is greater than the current value pointed
** to by pnHeight, the second parameter, then set *pnHeight to that
** value.
*/
static void heightOfExpr(Expr *p, int *pnHeight){
  if( p ){
    if( p->nHeight>*pnHeight ){
      *pnHeight = p->nHeight;
    }
  }
}
static void heightOfExprList(ExprList *p, int *pnHeight){
  if( p ){
    int i;
    for(i=0; i<p->nExpr; i++){
      heightOfExpr(p->a[i].pExpr, pnHeight);
    }
  }
}
static void heightOfSelect(Select *p, int *pnHeight){
  if( p ){
    heightOfExpr(p->pWhere, pnHeight);
    heightOfExpr(p->pHaving, pnHeight);
    heightOfExpr(p->pLimit, pnHeight);
    heightOfExpr(p->pOffset, pnHeight);
    heightOfExprList(p->pEList, pnHeight);
    heightOfExprList(p->pGroupBy, pnHeight);
    heightOfExprList(p->pOrderBy, pnHeight);
    heightOfSelect(p->pPrior, pnHeight);
  }
}

/*
** Set the Expr.nHeight variable in the structure passed as an 
** argument. An expression with no children, Expr.pList or 
** Expr.pSelect member has a height of 1. Any other expression
** has a height equal to the maximum height of any other 
** referenced Expr plus one.
*/
static void exprSetHeight(Expr *p){
  int nHeight = 0;
  heightOfExpr(p->pLeft, &nHeight);
  heightOfExpr(p->pRight, &nHeight);
  if( ExprHasProperty(p, EP_xIsSelect) ){
    heightOfSelect(p->x.pSelect, &nHeight);
  }else{
    heightOfExprList(p->x.pList, &nHeight);
  }
  p->nHeight = nHeight + 1;
}

/*
** Set the Expr.nHeight variable using the exprSetHeight() function. If
** the height is greater than the maximum allowed expression depth,
** leave an error in pParse.
*/
void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  exprSetHeight(p);
  sqlite3ExprCheckHeight(pParse, p->nHeight);
}

/*
** Return the maximum height of any expression tree referenced
** by the select statement passed as an argument.
*/
int sqlite3SelectExprHeight(Select *p){
  int nHeight = 0;
  heightOfSelect(p, &nHeight);
  return nHeight;
}
#else
  #define exprSetHeight(y)
#endif /* SQLITE_MAX_EXPR_DEPTH>0 */

/*
** This routine is the core allocator for Expr nodes.
**
** Construct a new expression node and return a pointer to it.  Memory
** for this node and for the pToken argument is a single allocation
** obtained from sqlite3DbMalloc().  The calling function
** is responsible for making sure the node eventually gets freed.
**
** If dequote is true, then the token (if it exists) is dequoted.
** If dequote is false, no dequoting is performance.  The deQuote
** parameter is ignored if pToken is NULL or if the token does not
** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
** then the EP_DblQuoted flag is set on the expression node.
**
** Special case:  If op==TK_INTEGER and pToken points to a string that
** can be translated into a 32-bit integer, then the token is not
** stored in u.zToken.  Instead, the integer values is written
** into u.iValue and the EP_IntValue flag is set.  No extra storage
** is allocated to hold the integer text and the dequote flag is ignored.
*/
Expr *sqlite3ExprAlloc(
  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
  int op,                 /* Expression opcode */
  const Token *pToken,    /* Token argument.  Might be NULL */
  int dequote             /* True to dequote */
){
  Expr *pNew;
  int nExtra = 0;
  int iValue = 0;

  if( pToken ){
    if( op!=TK_INTEGER || pToken->z==0
          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
      nExtra = pToken->n+1;
    }
  }
  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  if( pNew ){
    pNew->op = (u8)op;
    pNew->iAgg = -1;
    if( pToken ){
      if( nExtra==0 ){
        pNew->flags |= EP_IntValue;
        pNew->u.iValue = iValue;
      }else{
        int c;
        pNew->u.zToken = (char*)&pNew[1];
        memcpy(pNew->u.zToken, pToken->z, pToken->n);
        pNew->u.zToken[pToken->n] = 0;
        if( dequote && nExtra>=3 
             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
          sqlite3Dequote(pNew->u.zToken);
          if( c=='"' ) pNew->flags |= EP_DblQuoted;
        }
      }
    }
#if SQLITE_MAX_EXPR_DEPTH>0
    pNew->nHeight = 1;
#endif  
  }
  return pNew;
}

/*
** Allocate a new expression node from a zero-terminated token that has
** already been dequoted.
*/
Expr *sqlite3Expr(
  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
  int op,                 /* Expression opcode */
  const char *zToken      /* Token argument.  Might be NULL */
){
  Token x;
  x.z = zToken;
  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  return sqlite3ExprAlloc(db, op, &x, 0);
}

/*
** Attach subtrees pLeft and pRight to the Expr node pRoot.
**
** If pRoot==NULL that means that a memory allocation error has occurred.
** In that case, delete the subtrees pLeft and pRight.
*/
void sqlite3ExprAttachSubtrees(
  sqlite3 *db,
  Expr *pRoot,
  Expr *pLeft,
  Expr *pRight
){
  if( pRoot==0 ){
    assert( db->mallocFailed );
    sqlite3ExprDelete(db, pLeft);
    sqlite3ExprDelete(db, pRight);
  }else{
    if( pRight ){
      pRoot->pRight = pRight;
      if( pRight->flags & EP_ExpCollate ){
        pRoot->flags |= EP_ExpCollate;
        pRoot->pColl = pRight->pColl;
      }
    }
    if( pLeft ){
      pRoot->pLeft = pLeft;
      if( pLeft->flags & EP_ExpCollate ){
        pRoot->flags |= EP_ExpCollate;
        pRoot->pColl = pLeft->pColl;
      }
    }
    exprSetHeight(pRoot);
  }
}

/*
** Allocate a Expr node which joins as many as two subtrees.
**
** One or both of the subtrees can be NULL.  Return a pointer to the new
** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
** free the subtrees and return NULL.
*/
Expr *sqlite3PExpr(
  Parse *pParse,          /* Parsing context */
  int op,                 /* Expression opcode */
  Expr *pLeft,            /* Left operand */
  Expr *pRight,           /* Right operand */
  const Token *pToken     /* Argument token */
){
  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  return p;
}

/*
** Join two expressions using an AND operator.  If either expression is
** NULL, then just return the other expression.
*/
Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  if( pLeft==0 ){
    return pRight;
  }else if( pRight==0 ){
    return pLeft;
  }else{
    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
    return pNew;
  }
}

/*
** Construct a new expression node for a function with multiple
** arguments.
*/
Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  Expr *pNew;
  sqlite3 *db = pParse->db;
  assert( pToken );
  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  if( pNew==0 ){
    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
    return 0;
  }
  pNew->x.pList = pList;
  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  sqlite3ExprSetHeight(pParse, pNew);
  return pNew;
}

/*
** Assign a variable number to an expression that encodes a wildcard
** in the original SQL statement.  
**
** Wildcards consisting of a single "?" are assigned the next sequential
** variable number.
**
** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
** sure "nnn" is not too be to avoid a denial of service attack when
** the SQL statement comes from an external source.
**
** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
** as the previous instance of the same wildcard.  Or if this is the first
** instance of the wildcard, the next sequenial variable number is
** assigned.
*/
void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  sqlite3 *db = pParse->db;
  const char *z;

  if( pExpr==0 ) return;
  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  z = pExpr->u.zToken;
  assert( z!=0 );
  assert( z[0]!=0 );
  if( z[1]==0 ){
    /* Wildcard of the form "?".  Assign the next variable number */
    assert( z[0]=='?' );
    pExpr->iColumn = (ynVar)(++pParse->nVar);
  }else if( z[0]=='?' ){
    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
    ** use it as the variable number */
    int i = atoi((char*)&z[1]);
    pExpr->iColumn = (ynVar)i;
    testcase( i==0 );
    testcase( i==1 );
    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
    }
    if( i>pParse->nVar ){
      pParse->nVar = i;
    }
  }else{
    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
    ** number as the prior appearance of the same name, or if the name
    ** has never appeared before, reuse the same variable number
    */
    int i;
    u32 n;
    n = sqlite3Strlen30(z);
    for(i=0; i<pParse->nVarExpr; i++){
      Expr *pE = pParse->apVarExpr[i];
      assert( pE!=0 );
      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
        pExpr->iColumn = pE->iColumn;
        break;
      }
    }
    if( i>=pParse->nVarExpr ){
      pExpr->iColumn = (ynVar)(++pParse->nVar);
      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
        pParse->apVarExpr =
            sqlite3DbReallocOrFree(
              db,
              pParse->apVarExpr,
              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
            );
      }
      if( !db->mallocFailed ){
        assert( pParse->apVarExpr!=0 );
        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
      }
    }
  } 
  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
    sqlite3ErrorMsg(pParse, "too many SQL variables");
  }
}

/*
** Clear an expression structure without deleting the structure itself.
** Substructure is deleted.
*/
void sqlite3ExprClear(sqlite3 *db, Expr *p){
  assert( p!=0 );
  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
    sqlite3ExprDelete(db, p->pLeft);
    sqlite3ExprDelete(db, p->pRight);
    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
      sqlite3DbFree(db, p->u.zToken);
    }
    if( ExprHasProperty(p, EP_xIsSelect) ){
      sqlite3SelectDelete(db, p->x.pSelect);
    }else{
      sqlite3ExprListDelete(db, p->x.pList);
    }
  }
}

/*
** Recursively delete an expression tree.
*/
void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  if( p==0 ) return;
  sqlite3ExprClear(db, p);
  if( !ExprHasProperty(p, EP_Static) ){
    sqlite3DbFree(db, p);
  }
}

/*
** Return the number of bytes allocated for the expression structure 
** passed as the first argument. This is always one of EXPR_FULLSIZE,
** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
*/
static int exprStructSize(Expr *p){
  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  return EXPR_FULLSIZE;
}

/*
** The dupedExpr*Size() routines each return the number of bytes required
** to store a copy of an expression or expression tree.  They differ in
** how much of the tree is measured.
**
**     dupedExprStructSize()     Size of only the Expr structure 
**     dupedExprNodeSize()       Size of Expr + space for token
**     dupedExprSize()           Expr + token + subtree components
**
***************************************************************************
**
** The dupedExprStructSize() function returns two values OR-ed together:  
** (1) the space required for a copy of the Expr structure only and 
** (2) the EP_xxx flags that indicate what the structure size should be.
** The return values is always one of:
**
**      EXPR_FULLSIZE
**      EXPR_REDUCEDSIZE   | EP_Reduced
**      EXPR_TOKENONLYSIZE | EP_TokenOnly
**
** The size of the structure can be found by masking the return value
** of this routine with 0xfff.  The flags can be found by masking the
** return value with EP_Reduced|EP_TokenOnly.
**
** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
** (unreduced) Expr objects as they or originally constructed by the parser.
** During expression analysis, extra information is computed and moved into
** later parts of teh Expr object and that extra information might get chopped
** off if the expression is reduced.  Note also that it does not work to
** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
** to reduce a pristine expression tree from the parser.  The implementation
** of dupedExprStructSize() contain multiple assert() statements that attempt
** to enforce this constraint.
*/
static int dupedExprStructSize(Expr *p, int flags){
  int nSize;
  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  if( 0==(flags&EXPRDUP_REDUCE) ){
    nSize = EXPR_FULLSIZE;
  }else{
    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
    assert( !ExprHasProperty(p, EP_FromJoin) ); 
    assert( (p->flags2 & EP2_MallocedToken)==0 );
    assert( (p->flags2 & EP2_Irreducible)==0 );
    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
    }else{
      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
    }
  }
  return nSize;
}

/*
** This function returns the space in bytes required to store the copy 
** of the Expr structure and a copy of the Expr.u.zToken string (if that
** string is defined.)
*/
static int dupedExprNodeSize(Expr *p, int flags){
  int nByte = dupedExprStructSize(p, flags) & 0xfff;
  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
    nByte += sqlite3Strlen30(p->u.zToken)+1;
  }
  return ROUND8(nByte);
}

/*
** Return the number of bytes required to create a duplicate of the 
** expression passed as the first argument. The second argument is a
** mask containing EXPRDUP_XXX flags.
**
** The value returned includes space to create a copy of the Expr struct
** itself and the buffer referred to by Expr.u.zToken, if any.
**
** If the EXPRDUP_REDUCE flag is set, then the return value includes 
** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
** and Expr.pRight variables (but not for any structures pointed to or 
** descended from the Expr.x.pList or Expr.x.pSelect variables).
*/
static int dupedExprSize(Expr *p, int flags){
  int nByte = 0;
  if( p ){
    nByte = dupedExprNodeSize(p, flags);
    if( flags&EXPRDUP_REDUCE ){
      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
    }
  }
  return nByte;
}

/*
** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
** to store the copy of expression p, the copies of p->u.zToken
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
** if any. Before returning, *pzBuffer is set to the first byte passed the
** portion of the buffer copied into by this function.
*/
static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  Expr *pNew = 0;                      /* Value to return */
  if( p ){
    const int isReduced = (flags&EXPRDUP_REDUCE);
    u8 *zAlloc;
    u32 staticFlag = 0;

    assert( pzBuffer==0 || isReduced );

    /* Figure out where to write the new Expr structure. */
    if( pzBuffer ){
      zAlloc = *pzBuffer;
      staticFlag = EP_Static;
    }else{
      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
    }
    pNew = (Expr *)zAlloc;

    if( pNew ){
      /* Set nNewSize to the size allocated for the structure pointed to
      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
      ** by the copy of the p->u.zToken string (if any).
      */
      const unsigned nStructSize = dupedExprStructSize(p, flags);
      const int nNewSize = nStructSize & 0xfff;
      int nToken;
      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
        nToken = sqlite3Strlen30(p->u.zToken) + 1;
      }else{
        nToken = 0;
      }
      if( isReduced ){
        assert( ExprHasProperty(p, EP_Reduced)==0 );
        memcpy(zAlloc, p, nNewSize);
      }else{
        int nSize = exprStructSize(p);
        memcpy(zAlloc, p, nSize);
        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
      }

      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
      pNew->flags |= staticFlag;

      /* Copy the p->u.zToken string, if any. */
      if( nToken ){
        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
        memcpy(zToken, p->u.zToken, nToken);
      }

      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
        if( ExprHasProperty(p, EP_xIsSelect) ){
          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
        }else{
          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
        }
      }

      /* Fill in pNew->pLeft and pNew->pRight. */
      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
        zAlloc += dupedExprNodeSize(p, flags);
        if( ExprHasProperty(pNew, EP_Reduced) ){
          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
        }
        if( pzBuffer ){
          *pzBuffer = zAlloc;
        }
      }else{
        pNew->flags2 = 0;
        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
        }
      }

    }
  }
  return pNew;
}

/*
** The following group of routines make deep copies of expressions,
** expression lists, ID lists, and select statements.  The copies can
** be deleted (by being passed to their respective ...Delete() routines)
** without effecting the originals.
**
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
** by subsequent calls to sqlite*ListAppend() routines.
**
** Any tables that the SrcList might point to are not duplicated.
**
** The flags parameter contains a combination of the EXPRDUP_XXX flags.
** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
** truncated version of the usual Expr structure that will be stored as
** part of the in-memory representation of the database schema.
*/
Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  return exprDup(db, p, flags, 0);
}
ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  ExprList *pNew;
  struct ExprList_item *pItem, *pOldItem;
  int i;
  if( p==0 ) return 0;
  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  if( pNew==0 ) return 0;
  pNew->iECursor = 0;
  pNew->nExpr = pNew->nAlloc = p->nExpr;
  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
  if( pItem==0 ){
    sqlite3DbFree(db, pNew);
    return 0;
  } 
  pOldItem = p->a;
  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
    Expr *pOldExpr = pOldItem->pExpr;
    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
    pItem->sortOrder = pOldItem->sortOrder;
    pItem->done = 0;
    pItem->iCol = pOldItem->iCol;
    pItem->iAlias = pOldItem->iAlias;
  }
  return pNew;
}

/*
** If cursors, triggers, views and subqueries are all omitted from
** the build, then none of the following routines, except for 
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
** called with a NULL argument.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
 || !defined(SQLITE_OMIT_SUBQUERY)
SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  SrcList *pNew;
  int i;
  int nByte;
  if( p==0 ) return 0;
  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  pNew = sqlite3DbMallocRaw(db, nByte );
  if( pNew==0 ) return 0;
  pNew->nSrc = pNew->nAlloc = p->nSrc;
  for(i=0; i<p->nSrc; i++){
    struct SrcList_item *pNewItem = &pNew->a[i];
    struct SrcList_item *pOldItem = &p->a[i];
    Table *pTab;
    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
    pNewItem->jointype = pOldItem->jointype;
    pNewItem->iCursor = pOldItem->iCursor;
    pNewItem->isPopulated = pOldItem->isPopulated;
    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
    pNewItem->notIndexed = pOldItem->notIndexed;
    pNewItem->pIndex = pOldItem->pIndex;
    pTab = pNewItem->pTab = pOldItem->pTab;
    if( pTab ){
      pTab->nRef++;
    }
    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
    pNewItem->colUsed = pOldItem->colUsed;
  }
  return pNew;
}
IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  IdList *pNew;
  int i;
  if( p==0 ) return 0;
  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  if( pNew==0 ) return 0;
  pNew->nId = pNew->nAlloc = p->nId;
  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  if( pNew->a==0 ){
    sqlite3DbFree(db, pNew);
    return 0;
  }
  for(i=0; i<p->nId; i++){
    struct IdList_item *pNewItem = &pNew->a[i];
    struct IdList_item *pOldItem = &p->a[i];
    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
    pNewItem->idx = pOldItem->idx;
  }
  return pNew;
}
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  Select *pNew;
  if( p==0 ) return 0;
  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  if( pNew==0 ) return 0;
  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  pNew->op = p->op;
  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  pNew->iLimit = 0;
  pNew->iOffset = 0;
  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  pNew->pRightmost = 0;
  pNew->addrOpenEphm[0] = -1;
  pNew->addrOpenEphm[1] = -1;
  pNew->addrOpenEphm[2] = -1;
  return pNew;
}
#else
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  assert( p==0 );
  return 0;
}
#endif


/*
** Add a new element to the end of an expression list.  If pList is
** initially NULL, then create a new expression list.
**
** If a memory allocation error occurs, the entire list is freed and
** NULL is returned.  If non-NULL is returned, then it is guaranteed
** that the new entry was successfully appended.
*/
ExprList *sqlite3ExprListAppend(
  Parse *pParse,          /* Parsing context */
  ExprList *pList,        /* List to which to append. Might be NULL */
  Expr *pExpr             /* Expression to be appended. Might be NULL */
){
  sqlite3 *db = pParse->db;
  if( pList==0 ){
    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
    if( pList==0 ){
      goto no_mem;
    }
    assert( pList->nAlloc==0 );
  }
  if( pList->nAlloc<=pList->nExpr ){
    struct ExprList_item *a;
    int n = pList->nAlloc*2 + 4;
    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
    if( a==0 ){
      goto no_mem;
    }
    pList->a = a;
    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
  }
  assert( pList->a!=0 );
  if( 1 ){
    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
    memset(pItem, 0, sizeof(*pItem));
    pItem->pExpr = pExpr;
  }
  return pList;

no_mem:     
  /* Avoid leaking memory if malloc has failed. */
  sqlite3ExprDelete(db, pExpr);
  sqlite3ExprListDelete(db, pList);
  return 0;
}

/*
** Set the ExprList.a[].zName element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error.  But pName should never be
** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetName(
  Parse *pParse,          /* Parsing context */
  ExprList *pList,        /* List to which to add the span. */
  Token *pName,           /* Name to be added */
  int dequote             /* True to cause the name to be dequoted */
){
  assert( pList!=0 || pParse->db->mallocFailed!=0 );
  if( pList ){
    struct ExprList_item *pItem;
    assert( pList->nExpr>0 );
    pItem = &pList->a[pList->nExpr-1];
    assert( pItem->zName==0 );
    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  }
}

/*
** Set the ExprList.a[].zSpan element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error.  But pSpan should never be
** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetSpan(
  Parse *pParse,          /* Parsing context */
  ExprList *pList,        /* List to which to add the span. */
  ExprSpan *pSpan         /* The span to be added */
){
  sqlite3 *db = pParse->db;
  assert( pList!=0 || db->mallocFailed!=0 );
  if( pList ){
    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
    assert( pList->nExpr>0 );
    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
    sqlite3DbFree(db, pItem->zSpan);
    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
                                    (int)(pSpan->zEnd - pSpan->zStart));
  }
}

/*
** If the expression list pEList contains more than iLimit elements,
** leave an error message in pParse.
*/
void sqlite3ExprListCheckLength(
  Parse *pParse,
  ExprList *pEList,
  const char *zObject
){
  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  testcase( pEList && pEList->nExpr==mx );
  testcase( pEList && pEList->nExpr==mx+1 );
  if( pEList && pEList->nExpr>mx ){
    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  }
}

/*
** Delete an entire expression list.
*/
void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  int i;
  struct ExprList_item *pItem;
  if( pList==0 ) return;
  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
  assert( pList->nExpr<=pList->nAlloc );
  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
    sqlite3ExprDelete(db, pItem->pExpr);
    sqlite3DbFree(db, pItem->zName);
    sqlite3DbFree(db, pItem->zSpan);
  }
  sqlite3DbFree(db, pList->a);
  sqlite3DbFree(db, pList);
}

/*
** These routines are Walker callbacks.  Walker.u.pi is a pointer
** to an integer.  These routines are checking an expression to see
** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
** not constant.
**
** These callback routines are used to implement the following:
**
**     sqlite3ExprIsConstant()
**     sqlite3ExprIsConstantNotJoin()
**     sqlite3ExprIsConstantOrFunction()
**
*/
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){

  /* If pWalker->u.i is 3 then any term of the expression that comes from
  ** the ON or USING clauses of a join disqualifies the expression
  ** from being considered constant. */
  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
    pWalker->u.i = 0;
    return WRC_Abort;
  }

  switch( pExpr->op ){
    /* Consider functions to be constant if all their arguments are constant
    ** and pWalker->u.i==2 */
    case TK_FUNCTION:
      if( pWalker->u.i==2 ) return 0;
      /* Fall through */
    case TK_ID:
    case TK_COLUMN:
    case TK_AGG_FUNCTION:
    case TK_AGG_COLUMN:
      testcase( pExpr->op==TK_ID );
      testcase( pExpr->op==TK_COLUMN );
      testcase( pExpr->op==TK_AGG_FUNCTION );
      testcase( pExpr->op==TK_AGG_COLUMN );
      pWalker->u.i = 0;
      return WRC_Abort;
    default:
      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
      return WRC_Continue;
  }
}
static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  pWalker->u.i = 0;
  return WRC_Abort;
}
static int exprIsConst(Expr *p, int initFlag){
  Walker w;
  w.u.i = initFlag;
  w.xExprCallback = exprNodeIsConstant;
  w.xSelectCallback = selectNodeIsConstant;
  sqlite3WalkExpr(&w, p);
  return w.u.i;
}

/*
** Walk an expression tree.  Return 1 if the expression is constant
** and 0 if it involves variables or function calls.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstant(Expr *p){
  return exprIsConst(p, 1);
}

/*
** Walk an expression tree.  Return 1 if the expression is constant
** that does no originate from the ON or USING clauses of a join.
** Return 0 if it involves variables or function calls or terms from
** an ON or USING clause.
*/
int sqlite3ExprIsConstantNotJoin(Expr *p){
  return exprIsConst(p, 3);
}

/*
** Walk an expression tree.  Return 1 if the expression is constant
** or a function call with constant arguments.  Return and 0 if there
** are any variables.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstantOrFunction(Expr *p){
  return exprIsConst(p, 2);
}

/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue.  If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
*/
int sqlite3ExprIsInteger(Expr *p, int *pValue){
  int rc = 0;
  if( p->flags & EP_IntValue ){
    *pValue = p->u.iValue;
    return 1;
  }
  switch( p->op ){
    case TK_INTEGER: {
      rc = sqlite3GetInt32(p->u.zToken, pValue);
      assert( rc==0 );
      break;
    }
    case TK_UPLUS: {
      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
      break;
    }
    case TK_UMINUS: {
      int v;
      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
        *pValue = -v;
        rc = 1;
      }
      break;
    }
    default: break;
  }
  if( rc ){
    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
               || (p->flags2 & EP2_MallocedToken)==0 );
    p->op = TK_INTEGER;
    p->flags |= EP_IntValue;
    p->u.iValue = *pValue;
  }
  return rc;
}

/*
** Return TRUE if the given string is a row-id column name.
*/
int sqlite3IsRowid(const char *z){
  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  return 0;
}

/*
** Return true if we are able to the IN operator optimization on a
** query of the form
**
**       x IN (SELECT ...)
**
** Where the SELECT... clause is as specified by the parameter to this
** routine.
**
** The Select object passed in has already been preprocessed and no
** errors have been found.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static int isCandidateForInOpt(Select *p){
  SrcList *pSrc;
  ExprList *pEList;
  Table *pTab;
  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
  if( p->pPrior ) return 0;              /* Not a compound SELECT */
  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
    return 0; /* No DISTINCT keyword and no aggregate functions */
  }
  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
  if( p->pWhere ) return 0;              /* Has no WHERE clause */
  pSrc = p->pSrc;
  assert( pSrc!=0 );
  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
  pTab = pSrc->a[0].pTab;
  if( NEVER(pTab==0) ) return 0;
  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
  pEList = p->pEList;
  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  return 1;
}
#endif /* SQLITE_OMIT_SUBQUERY */

/*
** This function is used by the implementation of the IN (...) operator.
** It's job is to find or create a b-tree structure that may be used
** either to test for membership of the (...) set or to iterate through
** its members, skipping duplicates.
**
** The index of the cursor opened on the b-tree (database table, database index 
** or ephermal table) is stored in pX->iTable before this function returns.
** The returned value of this function indicates the b-tree type, as follows:
**
**   IN_INDEX_ROWID - The cursor was opened on a database table.
**   IN_INDEX_INDEX - The cursor was opened on a database index.
**   IN_INDEX_EPH -   The cursor was opened on a specially created and
**                    populated epheremal table.
**
** An existing b-tree may only be used if the SELECT is of the simple
** form:
**
**     SELECT <column> FROM <table>
**
** If the prNotFound parameter is 0, then the b-tree will be used to iterate
** through the set members, skipping any duplicates. In this case an
** epheremal table must be used unless the selected <column> is guaranteed
** to be unique - either because it is an INTEGER PRIMARY KEY or it
** has a UNIQUE constraint or UNIQUE index.
**
** If the prNotFound parameter is not 0, then the b-tree will be used 
** for fast set membership tests. In this case an epheremal table must 
** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
** be found with <column> as its left-most column.
**
** When the b-tree is being used for membership tests, the calling function
** needs to know whether or not the structure contains an SQL NULL 
** value in order to correctly evaluate expressions like "X IN (Y, Z)".
** If there is a chance that the b-tree might contain a NULL value at
** runtime, then a register is allocated and the register number written
** to *prNotFound. If there is no chance that the b-tree contains a
** NULL value, then *prNotFound is left unchanged.
**
** If a register is allocated and its location stored in *prNotFound, then
** its initial value is NULL. If the b-tree does not remain constant
** for the duration of the query (i.e. the SELECT that generates the b-tree
** is a correlated subquery) then the value of the allocated register is
** reset to NULL each time the b-tree is repopulated. This allows the
** caller to use vdbe code equivalent to the following:
**
**   if( register==NULL ){
**     has_null = <test if data structure contains null>
**     register = 1
**   }
**
** in order to avoid running the <test if data structure contains null>
** test more often than is necessary.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  Select *p;                            /* SELECT to the right of IN operator */
  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */

  assert( pX->op==TK_IN );

  /* Check to see if an existing table or index can be used to
  ** satisfy the query.  This is preferable to generating a new 
  ** ephemeral table.
  */
  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
    sqlite3 *db = pParse->db;              /* Database connection */
    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
    int iCol = pExpr->iColumn;             /* Index of column <column> */
    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
    int iDb;                               /* Database idx for pTab */
   
    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
    sqlite3CodeVerifySchema(pParse, iDb);
    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);

    /* This function is only called from two places. In both cases the vdbe
    ** has already been allocated. So assume sqlite3GetVdbe() is always
    ** successful here.
    */
    assert(v);
    if( iCol<0 ){
      int iMem = ++pParse->nMem;
      int iAddr;

      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);

      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
      eType = IN_INDEX_ROWID;

      sqlite3VdbeJumpHere(v, iAddr);
    }else{
      Index *pIdx;                         /* Iterator variable */

      /* The collation sequence used by the comparison. If an index is to
      ** be used in place of a temp-table, it must be ordered according
      ** to this collation sequence.  */
      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);

      /* Check that the affinity that will be used to perform the 
      ** comparison is the same as the affinity of the column. If
      ** it is not, it is not possible to use any index.
      */
      char aff = comparisonAffinity(pX);
      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);

      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
        if( (pIdx->aiColumn[0]==iCol)
         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
        ){
          int iMem = ++pParse->nMem;
          int iAddr;
          char *pKey;
  
          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  
          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
                               pKey,P4_KEYINFO_HANDOFF);
          VdbeComment((v, "%s", pIdx->zName));
          eType = IN_INDEX_INDEX;

          sqlite3VdbeJumpHere(v, iAddr);
          if( prNotFound && !pTab->aCol[iCol].notNull ){
            *prNotFound = ++pParse->nMem;
          }
        }
      }
    }
  }

  if( eType==0 ){
    /* Could not found an existing table or index to use as the RHS b-tree.
    ** We will have to generate an ephemeral table to do the job.
    */
    int rMayHaveNull = 0;
    eType = IN_INDEX_EPH;
    if( prNotFound ){
      *prNotFound = rMayHaveNull = ++pParse->nMem;
    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
      eType = IN_INDEX_ROWID;
    }
    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  }else{
    pX->iTable = iTab;
  }
  return eType;
}
#endif

/*
** Generate code for scalar subqueries used as an expression
** and IN operators.  Examples:
**
**     (SELECT a FROM b)          -- subquery
**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
**     x IN (4,5,11)              -- IN operator with list on right-hand side
**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
**
** The pExpr parameter describes the expression that contains the IN
** operator or subquery.
**
** If parameter isRowid is non-zero, then expression pExpr is guaranteed
** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
** to some integer key column of a table B-Tree. In this case, use an
** intkey B-Tree to store the set of IN(...) values instead of the usual
** (slower) variable length keys B-Tree.
**
** If rMayHaveNull is non-zero, that means that the operation is an IN
** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
** Furthermore, the IN is in a WHERE clause and that we really want
** to iterate over the RHS of the IN operator in order to quickly locate
** all corresponding LHS elements.  All this routine does is initialize
** the register given by rMayHaveNull to NULL.  Calling routines will take
** care of changing this register value to non-NULL if the RHS is NULL-free.
**
** If rMayHaveNull is zero, that means that the subquery is being used
** for membership testing only.  There is no need to initialize any
** registers to indicate the presense or absence of NULLs on the RHS.
**
** For a SELECT or EXISTS operator, return the register that holds the
** result.  For IN operators or if an error occurs, the return value is 0.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3CodeSubselect(
  Parse *pParse,          /* Parsing context */
  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
  int isRowid             /* If true, LHS of IN operator is a rowid */
){
  int testAddr = 0;                       /* One-time test address */
  int rReg = 0;                           /* Register storing resulting */
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( NEVER(v==0) ) return 0;
  sqlite3ExprCachePush(pParse);

  /* This code must be run in its entirety every time it is encountered
  ** if any of the following is true:
  **
  **    *  The right-hand side is a correlated subquery
  **    *  The right-hand side is an expression list containing variables
  **    *  We are inside a trigger
  **
  ** If all of the above are false, then we can run this code just once
  ** save the results, and reuse the same result on subsequent invocations.
  */
  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
    int mem = ++pParse->nMem;
    sqlite3VdbeAddOp1(v, OP_If, mem);
    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
    assert( testAddr>0 || pParse->db->mallocFailed );
  }

  switch( pExpr->op ){
    case TK_IN: {
      char affinity;
      KeyInfo keyInfo;
      int addr;        /* Address of OP_OpenEphemeral instruction */
      Expr *pLeft = pExpr->pLeft;

      if( rMayHaveNull ){
        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
      }

      affinity = sqlite3ExprAffinity(pLeft);

      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
      ** expression it is handled the same way. A virtual table is 
      ** filled with single-field index keys representing the results
      ** from the SELECT or the <exprlist>.
      **
      ** If the 'x' expression is a column value, or the SELECT...
      ** statement returns a column value, then the affinity of that
      ** column is used to build the index keys. If both 'x' and the
      ** SELECT... statement are columns, then numeric affinity is used
      ** if either column has NUMERIC or INTEGER affinity. If neither
      ** 'x' nor the SELECT... statement are columns, then numeric affinity
      ** is used.
      */
      pExpr->iTable = pParse->nTab++;
      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
      memset(&keyInfo, 0, sizeof(keyInfo));
      keyInfo.nField = 1;

      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
        /* Case 1:     expr IN (SELECT ...)
        **
        ** Generate code to write the results of the select into the temporary
        ** table allocated and opened above.
        */
        SelectDest dest;
        ExprList *pEList;

        assert( !isRowid );
        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
        dest.affinity = (u8)affinity;
        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
          return 0;
        }
        pEList = pExpr->x.pSelect->pEList;
        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
              pEList->a[0].pExpr);
        }
      }else if( pExpr->x.pList!=0 ){
        /* Case 2:     expr IN (exprlist)
        **
        ** For each expression, build an index key from the evaluation and
        ** store it in the temporary table. If <expr> is a column, then use
        ** that columns affinity when building index keys. If <expr> is not
        ** a column, use numeric affinity.
        */
        int i;
        ExprList *pList = pExpr->x.pList;
        struct ExprList_item *pItem;
        int r1, r2, r3;

        if( !affinity ){
          affinity = SQLITE_AFF_NONE;
        }
        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);

        /* Loop through each expression in <exprlist>. */
        r1 = sqlite3GetTempReg(pParse);
        r2 = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
          Expr *pE2 = pItem->pExpr;
          int iValToIns;

          /* If the expression is not constant then we will need to
          ** disable the test that was generated above that makes sure
          ** this code only executes once.  Because for a non-constant
          ** expression we need to rerun this code each time.
          */
          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
            testAddr = 0;
          }

          /* Evaluate the expression and insert it into the temp table */
          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
          }else{
            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
            if( isRowid ){
              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
                                sqlite3VdbeCurrentAddr(v)+2);
              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
            }else{
              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
            }
          }
        }
        sqlite3ReleaseTempReg(pParse, r1);
        sqlite3ReleaseTempReg(pParse, r2);
      }
      if( !isRowid ){
        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
      }
      break;
    }

    case TK_EXISTS:
    case TK_SELECT:
    default: {
      /* If this has to be a scalar SELECT.  Generate code to put the
      ** value of this select in a memory cell and record the number
      ** of the memory cell in iColumn.  If this is an EXISTS, write
      ** an integer 0 (not exists) or 1 (exists) into a memory cell
      ** and record that memory cell in iColumn.
      */
      static const Token one = { "1", 1 };  /* Token for literal value 1 */
      Select *pSel;                         /* SELECT statement to encode */
      SelectDest dest;                      /* How to deal with SELECt result */

      testcase( pExpr->op==TK_EXISTS );
      testcase( pExpr->op==TK_SELECT );
      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );

      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
      pSel = pExpr->x.pSelect;
      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
      if( pExpr->op==TK_SELECT ){
        dest.eDest = SRT_Mem;
        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
        VdbeComment((v, "Init subquery result"));
      }else{
        dest.eDest = SRT_Exists;
        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
        VdbeComment((v, "Init EXISTS result"));
      }
      sqlite3ExprDelete(pParse->db, pSel->pLimit);
      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
      if( sqlite3Select(pParse, pSel, &dest) ){
        return 0;
      }
      rReg = dest.iParm;
      ExprSetIrreducible(pExpr);
      break;
    }
  }

  if( testAddr ){
    sqlite3VdbeJumpHere(v, testAddr-1);
  }
  sqlite3ExprCachePop(pParse, 1);

  return rReg;
}
#endif /* SQLITE_OMIT_SUBQUERY */

/*
** Duplicate an 8-byte value
*/
static char *dup8bytes(Vdbe *v, const char *in){
  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  if( out ){
    memcpy(out, in, 8);
  }
  return out;
}

/*
** Generate an instruction that will put the floating point
** value described by z[0..n-1] into register iMem.
**
** The z[] string will probably not be zero-terminated.  But the 
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  if( ALWAYS(z!=0) ){
    double value;
    char *zV;
    sqlite3AtoF(z, &value);
    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
    if( negateFlag ) value = -value;
    zV = dup8bytes(v, (char*)&value);
    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  }
}


/*
** Generate an instruction that will put the integer describe by
** text z[0..n-1] into register iMem.
**
** The z[] string will probably not be zero-terminated.  But the 
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
  if( pExpr->flags & EP_IntValue ){
    int i = pExpr->u.iValue;
    if( negFlag ) i = -i;
    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  }else{
    const char *z = pExpr->u.zToken;
    assert( z!=0 );
    if( sqlite3FitsIn64Bits(z, negFlag) ){
      i64 value;
      char *zV;
      sqlite3Atoi64(z, &value);
      if( negFlag ) value = -value;
      zV = dup8bytes(v, (char*)&value);
      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
    }else{
      codeReal(v, z, negFlag, iMem);
    }
  }
}

/*
** Clear a cache entry.
*/
static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  if( p->tempReg ){
    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
    }
    p->tempReg = 0;
  }
}


/*
** Record in the column cache that a particular column from a
** particular table is stored in a particular register.
*/
void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  int i;
  int minLru;
  int idxLru;
  struct yColCache *p;

  assert( iReg>0 );  /* Register numbers are always positive */
  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */

  /* First replace any existing entry */
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
      cacheEntryClear(pParse, p);
      p->iLevel = pParse->iCacheLevel;
      p->iReg = iReg;
      p->affChange = 0;
      p->lru = pParse->iCacheCnt++;
      return;
    }
  }

  /* Find an empty slot and replace it */
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg==0 ){
      p->iLevel = pParse->iCacheLevel;
      p->iTable = iTab;
      p->iColumn = iCol;
      p->iReg = iReg;
      p->affChange = 0;
      p->tempReg = 0;
      p->lru = pParse->iCacheCnt++;
      return;
    }
  }

  /* Replace the last recently used */
  minLru = 0x7fffffff;
  idxLru = -1;
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->lru<minLru ){
      idxLru = i;
      minLru = p->lru;
    }
  }
  if( ALWAYS(idxLru>=0) ){
    p = &pParse->aColCache[idxLru];
    p->iLevel = pParse->iCacheLevel;
    p->iTable = iTab;
    p->iColumn = iCol;
    p->iReg = iReg;
    p->affChange = 0;
    p->tempReg = 0;
    p->lru = pParse->iCacheCnt++;
    return;
  }
}

/*
** Indicate that a register is being overwritten.  Purge the register
** from the column cache.
*/
void sqlite3ExprCacheRemove(Parse *pParse, int iReg){
  int i;
  struct yColCache *p;
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg==iReg ){
      cacheEntryClear(pParse, p);
      p->iReg = 0;
    }
  }
}

/*
** Remember the current column cache context.  Any new entries added
** added to the column cache after this call are removed when the
** corresponding pop occurs.
*/
void sqlite3ExprCachePush(Parse *pParse){
  pParse->iCacheLevel++;
}

/*
** Remove from the column cache any entries that were added since the
** the previous N Push operations.  In other words, restore the cache
** to the state it was in N Pushes ago.
*/
void sqlite3ExprCachePop(Parse *pParse, int N){
  int i;
  struct yColCache *p;
  assert( N>0 );
  assert( pParse->iCacheLevel>=N );
  pParse->iCacheLevel -= N;
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
      cacheEntryClear(pParse, p);
      p->iReg = 0;
    }
  }
}

/*
** When a cached column is reused, make sure that its register is
** no longer available as a temp register.  ticket #3879:  that same
** register might be in the cache in multiple places, so be sure to
** get them all.
*/
static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  int i;
  struct yColCache *p;
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg==iReg ){
      p->tempReg = 0;
    }
  }
}

/*
** Generate code that will extract the iColumn-th column from
** table pTab and store the column value in a register.  An effort
** is made to store the column value in register iReg, but this is
** not guaranteed.  The location of the column value is returned.
**
** There must be an open cursor to pTab in iTable when this routine
** is called.  If iColumn<0 then code is generated that extracts the rowid.
**
** This routine might attempt to reuse the value of the column that
** has already been loaded into a register.  The value will always
** be used if it has not undergone any affinity changes.  But if
** an affinity change has occurred, then the cached value will only be
** used if allowAffChng is true.
*/
int sqlite3ExprCodeGetColumn(
  Parse *pParse,   /* Parsing and code generating context */
  Table *pTab,     /* Description of the table we are reading from */
  int iColumn,     /* Index of the table column */
  int iTable,      /* The cursor pointing to the table */
  int iReg,        /* Store results here */
  int allowAffChng /* True if prior affinity changes are OK */
){
  Vdbe *v = pParse->pVdbe;
  int i;
  struct yColCache *p;

  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn
           && (!p->affChange || allowAffChng) ){
      p->lru = pParse->iCacheCnt++;
      sqlite3ExprCachePinRegister(pParse, p->iReg);
      return p->iReg;
    }
  }  
  assert( v!=0 );
  if( iColumn<0 ){
    sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
  }else if( ALWAYS(pTab!=0) ){
    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
    sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
    sqlite3ColumnDefault(v, pTab, iColumn, iReg);
  }
  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  return iReg;
}

/*
** Clear all column cache entries.
*/
void sqlite3ExprCacheClear(Parse *pParse){
  int i;
  struct yColCache *p;

  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    if( p->iReg ){
      cacheEntryClear(pParse, p);
      p->iReg = 0;
    }
  }
}

/*
** Record the fact that an affinity change has occurred on iCount
** registers starting with iStart.
*/
void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  int iEnd = iStart + iCount - 1;
  int i;
  struct yColCache *p;
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    int r = p->iReg;
    if( r>=iStart && r<=iEnd ){
      p->affChange = 1;
    }
  }
}

/*
** Generate code to move content from registers iFrom...iFrom+nReg-1
** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
*/
void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  int i;
  struct yColCache *p;
  if( NEVER(iFrom==iTo) ) return;
  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    int x = p->iReg;
    if( x>=iFrom && x<iFrom+nReg ){
      p->iReg += iTo-iFrom;
    }
  }
}

/*
** Generate code to copy content from registers iFrom...iFrom+nReg-1
** over to iTo..iTo+nReg-1.
*/
void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
  int i;
  if( NEVER(iFrom==iTo) ) return;
  for(i=0; i<nReg; i++){
    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
  }
}

/*
** Return true if any register in the range iFrom..iTo (inclusive)
** is used as part of the column cache.
*/
static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  int i;
  struct yColCache *p;
  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
    int r = p->iReg;
    if( r>=iFrom && r<=iTo ) return 1;
  }
  return 0;
}

/*
** If the last instruction coded is an ephemeral copy of any of
** the registers in the nReg registers beginning with iReg, then
** convert the last instruction from OP_SCopy to OP_Copy.
*/
void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
  VdbeOp *pOp;
  Vdbe *v;

  assert( pParse->db->mallocFailed==0 );
  v = pParse->pVdbe;
  assert( v!=0 );
  pOp = sqlite3VdbeGetOp(v, -1);
  assert( pOp!=0 );
  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
    pOp->opcode = OP_Copy;
  }
}

/*
** Generate code to store the value of the iAlias-th alias in register
** target.  The first time this is called, pExpr is evaluated to compute
** the value of the alias.  The value is stored in an auxiliary register
** and the number of that register is returned.  On subsequent calls,
** the register number is returned without generating any code.
**
** Note that in order for this to work, code must be generated in the
** same order that it is executed.
**
** Aliases are numbered starting with 1.  So iAlias is in the range
** of 1 to pParse->nAlias inclusive.  
**
** pParse->aAlias[iAlias-1] records the register number where the value
** of the iAlias-th alias is stored.  If zero, that means that the
** alias has not yet been computed.
*/
static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
#if 0
  sqlite3 *db = pParse->db;
  int iReg;
  if( pParse->nAliasAlloc<pParse->nAlias ){
    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
    if( db->mallocFailed ) return 0;
    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
    pParse->nAliasAlloc = pParse->nAlias;
  }
  assert( iAlias>0 && iAlias<=pParse->nAlias );
  iReg = pParse->aAlias[iAlias-1];
  if( iReg==0 ){
    if( pParse->iCacheLevel>0 ){
      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
    }else{
      iReg = ++pParse->nMem;
      sqlite3ExprCode(pParse, pExpr, iReg);
      pParse->aAlias[iAlias-1] = iReg;
    }
  }
  return iReg;
#else
  UNUSED_PARAMETER(iAlias);
  return sqlite3ExprCodeTarget(pParse, pExpr, target);
#endif
}

/*
** Generate code into the current Vdbe to evaluate the given
** expression.  Attempt to store the results in register "target".
** Return the register where results are stored.
**
** With this routine, there is no guarantee that results will
** be stored in target.  The result might be stored in some other
** register if it is convenient to do so.  The calling function
** must check the return code and move the results to the desired
** register.
*/
int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
  int op;                   /* The opcode being coded */
  int inReg = target;       /* Results stored in register inReg */
  int regFree1 = 0;         /* If non-zero free this temporary register */
  int regFree2 = 0;         /* If non-zero free this temporary register */
  int r1, r2, r3, r4;       /* Various register numbers */
  sqlite3 *db = pParse->db; /* The database connection */

  assert( target>0 && target<=pParse->nMem );
  if( v==0 ){
    assert( pParse->db->mallocFailed );
    return 0;
  }

  if( pExpr==0 ){
    op = TK_NULL;
  }else{
    op = pExpr->op;
  }
  switch( op ){
    case TK_AGG_COLUMN: {
      AggInfo *pAggInfo = pExpr->pAggInfo;
      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
      if( !pAggInfo->directMode ){
        assert( pCol->iMem>0 );
        inReg = pCol->iMem;
        break;
      }else if( pAggInfo->useSortingIdx ){
        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
                              pCol->iSorterColumn, target);
        break;
      }
      /* Otherwise, fall thru into the TK_COLUMN case */
    }
    case TK_COLUMN: {
      if( pExpr->iTable<0 ){
        /* This only happens when coding check constraints */
        assert( pParse->ckBase>0 );
        inReg = pExpr->iColumn + pParse->ckBase;
      }else{
        testcase( (pExpr->flags & EP_AnyAff)!=0 );
        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
                                 pExpr->iColumn, pExpr->iTable, target,
                                 pExpr->flags & EP_AnyAff);
      }
      break;
    }
    case TK_INTEGER: {
      codeInteger(v, pExpr, 0, target);
      break;
    }
    case TK_FLOAT: {
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      codeReal(v, pExpr->u.zToken, 0, target);
      break;
    }
    case TK_STRING: {
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
      break;
    }
    case TK_NULL: {
      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
      break;
    }
#ifndef SQLITE_OMIT_BLOB_LITERAL
    case TK_BLOB: {
      int n;
      const char *z;
      char *zBlob;
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
      assert( pExpr->u.zToken[1]=='\'' );
      z = &pExpr->u.zToken[2];
      n = sqlite3Strlen30(z) - 1;
      assert( z[n]=='\'' );
      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
      break;
    }
#endif
    case TK_VARIABLE: {
      VdbeOp *pOp;
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      assert( pExpr->u.zToken!=0 );
      assert( pExpr->u.zToken[0]!=0 );
      if( pExpr->u.zToken[1]==0
         && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
         && pOp->p1+pOp->p3==pExpr->iColumn
         && pOp->p2+pOp->p3==target
         && pOp->p4.z==0
      ){
        /* If the previous instruction was a copy of the previous unnamed
        ** parameter into the previous register, then simply increment the
        ** repeat count on the prior instruction rather than making a new
        ** instruction.
        */
        pOp->p3++;
      }else{
        sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
        if( pExpr->u.zToken[1]!=0 ){
          sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
        }
      }
      break;
    }
    case TK_REGISTER: {
      inReg = pExpr->iTable;
      break;
    }
    case TK_AS: {
      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
      break;
    }
#ifndef SQLITE_OMIT_CAST
    case TK_CAST: {
      /* Expressions of the form:   CAST(pLeft AS token) */
      int aff, to_op;
      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      aff = sqlite3AffinityType(pExpr->u.zToken);
      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
      testcase( to_op==OP_ToText );
      testcase( to_op==OP_ToBlob );
      testcase( to_op==OP_ToNumeric );
      testcase( to_op==OP_ToInt );
      testcase( to_op==OP_ToReal );
      if( inReg!=target ){
        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
        inReg = target;
      }
      sqlite3VdbeAddOp1(v, to_op, inReg);
      testcase( usedAsColumnCache(pParse, inReg, inReg) );
      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
      break;
    }
#endif /* SQLITE_OMIT_CAST */
    case TK_LT:
    case TK_LE:
    case TK_GT:
    case TK_GE:
    case TK_NE:
    case TK_EQ: {
      assert( TK_LT==OP_Lt );
      assert( TK_LE==OP_Le );
      assert( TK_GT==OP_Gt );
      assert( TK_GE==OP_Ge );
      assert( TK_EQ==OP_Eq );
      assert( TK_NE==OP_Ne );
      testcase( op==TK_LT );
      testcase( op==TK_LE );
      testcase( op==TK_GT );
      testcase( op==TK_GE );
      testcase( op==TK_EQ );
      testcase( op==TK_NE );
      codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
                                  pExpr->pRight, &r2, &regFree2);
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
                  r1, r2, inReg, SQLITE_STOREP2);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_IS:
    case TK_ISNOT: {
      testcase( op==TK_IS );
      testcase( op==TK_ISNOT );
      codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
                                  pExpr->pRight, &r2, &regFree2);
      op = (op==TK_IS) ? TK_EQ : TK_NE;
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_AND:
    case TK_OR:
    case TK_PLUS:
    case TK_STAR:
    case TK_MINUS:
    case TK_REM:
    case TK_BITAND:
    case TK_BITOR:
    case TK_SLASH:
    case TK_LSHIFT:
    case TK_RSHIFT: 
    case TK_CONCAT: {
      assert( TK_AND==OP_And );
      assert( TK_OR==OP_Or );
      assert( TK_PLUS==OP_Add );
      assert( TK_MINUS==OP_Subtract );
      assert( TK_REM==OP_Remainder );
      assert( TK_BITAND==OP_BitAnd );
      assert( TK_BITOR==OP_BitOr );
      assert( TK_SLASH==OP_Divide );
      assert( TK_LSHIFT==OP_ShiftLeft );
      assert( TK_RSHIFT==OP_ShiftRight );
      assert( TK_CONCAT==OP_Concat );
      testcase( op==TK_AND );
      testcase( op==TK_OR );
      testcase( op==TK_PLUS );
      testcase( op==TK_MINUS );
      testcase( op==TK_REM );
      testcase( op==TK_BITAND );
      testcase( op==TK_BITOR );
      testcase( op==TK_SLASH );
      testcase( op==TK_LSHIFT );
      testcase( op==TK_RSHIFT );
      testcase( op==TK_CONCAT );
      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
      sqlite3VdbeAddOp3(v, op, r2, r1, target);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_UMINUS: {
      Expr *pLeft = pExpr->pLeft;
      assert( pLeft );
      if( pLeft->op==TK_FLOAT ){
        assert( !ExprHasProperty(pExpr, EP_IntValue) );
        codeReal(v, pLeft->u.zToken, 1, target);
      }else if( pLeft->op==TK_INTEGER ){
        codeInteger(v, pLeft, 1, target);
      }else{
        regFree1 = r1 = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
        testcase( regFree2==0 );
      }
      inReg = target;
      break;
    }
    case TK_BITNOT:
    case TK_NOT: {
      assert( TK_BITNOT==OP_BitNot );
      assert( TK_NOT==OP_Not );
      testcase( op==TK_BITNOT );
      testcase( op==TK_NOT );
      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
      testcase( regFree1==0 );
      inReg = target;
      sqlite3VdbeAddOp2(v, op, r1, inReg);
      break;
    }
    case TK_ISNULL:
    case TK_NOTNULL: {
      int addr;
      assert( TK_ISNULL==OP_IsNull );
      assert( TK_NOTNULL==OP_NotNull );
      testcase( op==TK_ISNULL );
      testcase( op==TK_NOTNULL );
      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
      testcase( regFree1==0 );
      addr = sqlite3VdbeAddOp1(v, op, r1);
      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
      sqlite3VdbeJumpHere(v, addr);
      break;
    }
    case TK_AGG_FUNCTION: {
      AggInfo *pInfo = pExpr->pAggInfo;
      if( pInfo==0 ){
        assert( !ExprHasProperty(pExpr, EP_IntValue) );
        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
      }else{
        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
      }
      break;
    }
    case TK_CONST_FUNC:
    case TK_FUNCTION: {
      ExprList *pFarg;       /* List of function arguments */
      int nFarg;             /* Number of function arguments */
      FuncDef *pDef;         /* The function definition object */
      int nId;               /* Length of the function name in bytes */
      const char *zId;       /* The function name */
      int constMask = 0;     /* Mask of function arguments that are constant */
      int i;                 /* Loop counter */
      u8 enc = ENC(db);      /* The text encoding used by this database */
      CollSeq *pColl = 0;    /* A collating sequence */

      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
      testcase( op==TK_CONST_FUNC );
      testcase( op==TK_FUNCTION );
      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
        pFarg = 0;
      }else{
        pFarg = pExpr->x.pList;
      }
      nFarg = pFarg ? pFarg->nExpr : 0;
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      zId = pExpr->u.zToken;
      nId = sqlite3Strlen30(zId);
      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
      if( pDef==0 ){
        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
        break;
      }
      if( pFarg ){
        r1 = sqlite3GetTempRange(pParse, nFarg);
        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
      }else{
        r1 = 0;
      }
#ifndef SQLITE_OMIT_VIRTUALTABLE
      /* Possibly overload the function if the first argument is
      ** a virtual table column.
      **
      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
      ** second argument, not the first, as the argument to test to
      ** see if it is a column in a virtual table.  This is done because
      ** the left operand of infix functions (the operand we want to
      ** control overloading) ends up as the second argument to the
      ** function.  The expression "A glob B" is equivalent to 
      ** "glob(B,A).  We want to use the A in "A glob B" to test
      ** for function overloading.  But we use the B term in "glob(B,A)".
      */
      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
      }else if( nFarg>0 ){
        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
      }
#endif
      for(i=0; i<nFarg; i++){
        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
          constMask |= (1<<i);
        }
        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
        }
      }
      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
        if( !pColl ) pColl = db->pDfltColl; 
        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
      }
      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
                        (char*)pDef, P4_FUNCDEF);
      sqlite3VdbeChangeP5(v, (u8)nFarg);
      if( nFarg ){
        sqlite3ReleaseTempRange(pParse, r1, nFarg);
      }
      sqlite3ExprCacheAffinityChange(pParse, r1, nFarg);
      break;
    }
#ifndef SQLITE_OMIT_SUBQUERY
    case TK_EXISTS:
    case TK_SELECT: {
      testcase( op==TK_EXISTS );
      testcase( op==TK_SELECT );
      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
      break;
    }
    case TK_IN: {
      int rNotFound = 0;
      int rMayHaveNull = 0;
      int j2, j3, j4, j5;
      char affinity;
      int eType;

      VdbeNoopComment((v, "begin IN expr r%d", target));
      eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
      if( rMayHaveNull ){
        rNotFound = ++pParse->nMem;
      }

      /* Figure out the affinity to use to create a key from the results
      ** of the expression. affinityStr stores a static string suitable for
      ** P4 of OP_MakeRecord.
      */
      affinity = comparisonAffinity(pExpr);


      /* Code the <expr> from "<expr> IN (...)". The temporary table
      ** pExpr->iTable contains the values that make up the (...) set.
      */
      sqlite3ExprCachePush(pParse);
      sqlite3ExprCode(pParse, pExpr->pLeft, target);
      j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
      if( eType==IN_INDEX_ROWID ){
        j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
        j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
        j5 = sqlite3VdbeAddOp0(v, OP_Goto);
        sqlite3VdbeJumpHere(v, j3);
        sqlite3VdbeJumpHere(v, j4);
        sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
      }else{
        r2 = regFree2 = sqlite3GetTempReg(pParse);

        /* Create a record and test for set membership. If the set contains
        ** the value, then jump to the end of the test code. The target
        ** register still contains the true (1) value written to it earlier.
        */
        sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
        j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);

        /* If the set membership test fails, then the result of the 
        ** "x IN (...)" expression must be either 0 or NULL. If the set
        ** contains no NULL values, then the result is 0. If the set 
        ** contains one or more NULL values, then the result of the
        ** expression is also NULL.
        */
        if( rNotFound==0 ){
          /* This branch runs if it is known at compile time (now) that 
          ** the set contains no NULL values. This happens as the result
          ** of a "NOT NULL" constraint in the database schema. No need
          ** to test the data structure at runtime in this case.
          */
          sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
        }else{
          /* This block populates the rNotFound register with either NULL
          ** or 0 (an integer value). If the data structure contains one
          ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
          ** to 0. If register rMayHaveNull is already set to some value
          ** other than NULL, then the test has already been run and 
          ** rNotFound is already populated.
          */
          static const char nullRecord[] = { 0x02, 0x00 };
          j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
          sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
          sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
                             nullRecord, P4_STATIC);
          j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
          sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
          sqlite3VdbeJumpHere(v, j4);
          sqlite3VdbeJumpHere(v, j3);

          /* Copy the value of register rNotFound (which is either NULL or 0)
          ** into the target register. This will be the result of the
          ** expression.
          */
          sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
        }
      }
      sqlite3VdbeJumpHere(v, j2);
      sqlite3VdbeJumpHere(v, j5);
      sqlite3ExprCachePop(pParse, 1);
      VdbeComment((v, "end IN expr r%d", target));
      break;
    }
#endif
    /*
    **    x BETWEEN y AND z
    **
    ** This is equivalent to
    **
    **    x>=y AND x<=z
    **
    ** X is stored in pExpr->pLeft.
    ** Y is stored in pExpr->pList->a[0].pExpr.
    ** Z is stored in pExpr->pList->a[1].pExpr.
    */
    case TK_BETWEEN: {
      Expr *pLeft = pExpr->pLeft;
      struct ExprList_item *pLItem = pExpr->x.pList->a;
      Expr *pRight = pLItem->pExpr;

      codeCompareOperands(pParse, pLeft, &r1, &regFree1,
                                  pRight, &r2, &regFree2);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      r3 = sqlite3GetTempReg(pParse);
      r4 = sqlite3GetTempReg(pParse);
      codeCompare(pParse, pLeft, pRight, OP_Ge,
                  r1, r2, r3, SQLITE_STOREP2);
      pLItem++;
      pRight = pLItem->pExpr;
      sqlite3ReleaseTempReg(pParse, regFree2);
      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
      testcase( regFree2==0 );
      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
      sqlite3ReleaseTempReg(pParse, r3);
      sqlite3ReleaseTempReg(pParse, r4);
      break;
    }
    case TK_UPLUS: {
      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
      break;
    }

    case TK_TRIGGER: {
      /* If the opcode is TK_TRIGGER, then the expression is a reference
      ** to a column in the new.* or old.* pseudo-tables available to
      ** trigger programs. In this case Expr.iTable is set to 1 for the
      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
      ** is set to the column of the pseudo-table to read, or to -1 to
      ** read the rowid field.
      **
      ** The expression is implemented using an OP_Param opcode. The p1
      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
      ** to reference another column of the old.* pseudo-table, where 
      ** i is the index of the column. For a new.rowid reference, p1 is
      ** set to (n+1), where n is the number of columns in each pseudo-table.
      ** For a reference to any other column in the new.* pseudo-table, p1
      ** is set to (n+2+i), where n and i are as defined previously. For
      ** example, if the table on which triggers are being fired is
      ** declared as:
      **
      **   CREATE TABLE t1(a, b);
      **
      ** Then p1 is interpreted as follows:
      **
      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
      **   p1==1   ->    old.a         p1==4   ->    new.a
      **   p1==2   ->    old.b         p1==5   ->    new.b       
      */
      Table *pTab = pExpr->pTab;
      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;

      assert( pExpr->iTable==0 || pExpr->iTable==1 );
      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
      assert( p1>=0 && p1<(pTab->nCol*2+2) );

      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
      VdbeComment((v, "%s.%s -> $%d",
        (pExpr->iTable ? "new" : "old"),
        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
        target
      ));

      /* If the column has REAL affinity, it may currently be stored as an
      ** integer. Use OP_RealAffinity to make sure it is really real.  */
      if( pExpr->iColumn>=0 
       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
      ){
        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
      }
      break;
    }


    /*
    ** Form A:
    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
    **
    ** Form B:
    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
    **
    ** Form A is can be transformed into the equivalent form B as follows:
    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
    **        WHEN x=eN THEN rN ELSE y END
    **
    ** X (if it exists) is in pExpr->pLeft.
    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
    ** ELSE clause and no other term matches, then the result of the
    ** exprssion is NULL.
    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
    **
    ** The result of the expression is the Ri for the first matching Ei,
    ** or if there is no matching Ei, the ELSE term Y, or if there is
    ** no ELSE term, NULL.
    */
    default: assert( op==TK_CASE ); {
      int endLabel;                     /* GOTO label for end of CASE stmt */
      int nextCase;                     /* GOTO label for next WHEN clause */
      int nExpr;                        /* 2x number of WHEN terms */
      int i;                            /* Loop counter */
      ExprList *pEList;                 /* List of WHEN terms */
      struct ExprList_item *aListelem;  /* Array of WHEN terms */
      Expr opCompare;                   /* The X==Ei expression */
      Expr cacheX;                      /* Cached expression X */
      Expr *pX;                         /* The X expression */
      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )

      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
      assert((pExpr->x.pList->nExpr % 2) == 0);
      assert(pExpr->x.pList->nExpr > 0);
      pEList = pExpr->x.pList;
      aListelem = pEList->a;
      nExpr = pEList->nExpr;
      endLabel = sqlite3VdbeMakeLabel(v);
      if( (pX = pExpr->pLeft)!=0 ){
        cacheX = *pX;
        testcase( pX->op==TK_COLUMN );
        testcase( pX->op==TK_REGISTER );
        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
        testcase( regFree1==0 );
        cacheX.op = TK_REGISTER;
        opCompare.op = TK_EQ;
        opCompare.pLeft = &cacheX;
        pTest = &opCompare;
      }
      for(i=0; i<nExpr; i=i+2){
        sqlite3ExprCachePush(pParse);
        if( pX ){
          assert( pTest!=0 );
          opCompare.pRight = aListelem[i].pExpr;
        }else{
          pTest = aListelem[i].pExpr;
        }
        nextCase = sqlite3VdbeMakeLabel(v);
        testcase( pTest->op==TK_COLUMN );
        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
        sqlite3ExprCachePop(pParse, 1);
        sqlite3VdbeResolveLabel(v, nextCase);
      }
      if( pExpr->pRight ){
        sqlite3ExprCachePush(pParse);
        sqlite3ExprCode(pParse, pExpr->pRight, target);
        sqlite3ExprCachePop(pParse, 1);
      }else{
        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
      }
      assert( db->mallocFailed || pParse->nErr>0 
           || pParse->iCacheLevel==iCacheLevel );
      sqlite3VdbeResolveLabel(v, endLabel);
      break;
    }
#ifndef SQLITE_OMIT_TRIGGER
    case TK_RAISE: {
      assert( pExpr->affinity==OE_Rollback 
           || pExpr->affinity==OE_Abort
           || pExpr->affinity==OE_Fail
           || pExpr->affinity==OE_Ignore
      );
      if( !pParse->pTriggerTab ){
        sqlite3ErrorMsg(pParse,
                       "RAISE() may only be used within a trigger-program");
        return 0;
      }
      if( pExpr->affinity==OE_Abort ){
        sqlite3MayAbort(pParse);
      }
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      if( pExpr->affinity==OE_Ignore ){
        sqlite3VdbeAddOp4(
            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
      }else{
        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
      }

      break;
    }
#endif
  }
  sqlite3ReleaseTempReg(pParse, regFree1);
  sqlite3ReleaseTempReg(pParse, regFree2);
  return inReg;
}

/*
** Generate code to evaluate an expression and store the results
** into a register.  Return the register number where the results
** are stored.
**
** If the register is a temporary register that can be deallocated,
** then write its number into *pReg.  If the result register is not
** a temporary, then set *pReg to zero.
*/
int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  int r1 = sqlite3GetTempReg(pParse);
  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  if( r2==r1 ){
    *pReg = r1;
  }else{
    sqlite3ReleaseTempReg(pParse, r1);
    *pReg = 0;
  }
  return r2;
}

/*
** Generate code that will evaluate expression pExpr and store the
** results in register target.  The results are guaranteed to appear
** in register target.
*/
int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  int inReg;

  assert( target>0 && target<=pParse->nMem );
  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  assert( pParse->pVdbe || pParse->db->mallocFailed );
  if( inReg!=target && pParse->pVdbe ){
    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  }
  return target;
}

/*
** Generate code that evalutes the given expression and puts the result
** in register target.
**
** Also make a copy of the expression results into another "cache" register
** and modify the expression so that the next time it is evaluated,
** the result is a copy of the cache register.
**
** This routine is used for expressions that are used multiple 
** times.  They are evaluated once and the results of the expression
** are reused.
*/
int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  Vdbe *v = pParse->pVdbe;
  int inReg;
  inReg = sqlite3ExprCode(pParse, pExpr, target);
  assert( target>0 );
  /* This routine is called for terms to INSERT or UPDATE.  And the only
  ** other place where expressions can be converted into TK_REGISTER is
  ** in WHERE clause processing.  So as currently implemented, there is
  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
  ** keep the ALWAYS() in case the conditions above change with future
  ** modifications or enhancements. */
  if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
    int iMem;
    iMem = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
    pExpr->iTable = iMem;
    pExpr->op2 = pExpr->op;
    pExpr->op = TK_REGISTER;
  }
  return inReg;
}

/*
** Return TRUE if pExpr is an constant expression that is appropriate
** for factoring out of a loop.  Appropriate expressions are:
**
**    *  Any expression that evaluates to two or more opcodes.
**
**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
**       or OP_Variable that does not need to be placed in a 
**       specific register.
**
** There is no point in factoring out single-instruction constant
** expressions that need to be placed in a particular register.  
** We could factor them out, but then we would end up adding an
** OP_SCopy instruction to move the value into the correct register
** later.  We might as well just use the original instruction and
** avoid the OP_SCopy.
*/
static int isAppropriateForFactoring(Expr *p){
  if( !sqlite3ExprIsConstantNotJoin(p) ){
    return 0;  /* Only constant expressions are appropriate for factoring */
  }
  if( (p->flags & EP_FixedDest)==0 ){
    return 1;  /* Any constant without a fixed destination is appropriate */
  }
  while( p->op==TK_UPLUS ) p = p->pLeft;
  switch( p->op ){
#ifndef SQLITE_OMIT_BLOB_LITERAL
    case TK_BLOB:
#endif
    case TK_VARIABLE:
    case TK_INTEGER:
    case TK_FLOAT:
    case TK_NULL:
    case TK_STRING: {
      testcase( p->op==TK_BLOB );
      testcase( p->op==TK_VARIABLE );
      testcase( p->op==TK_INTEGER );
      testcase( p->op==TK_FLOAT );
      testcase( p->op==TK_NULL );
      testcase( p->op==TK_STRING );
      /* Single-instruction constants with a fixed destination are
      ** better done in-line.  If we factor them, they will just end
      ** up generating an OP_SCopy to move the value to the destination
      ** register. */
      return 0;
    }
    case TK_UMINUS: {
      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
        return 0;
      }
      break;
    }
    default: {
      break;
    }
  }
  return 1;
}

/*
** If pExpr is a constant expression that is appropriate for
** factoring out of a loop, then evaluate the expression
** into a register and convert the expression into a TK_REGISTER
** expression.
*/
static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  Parse *pParse = pWalker->pParse;
  switch( pExpr->op ){
    case TK_IN:
    case TK_REGISTER: {
      return WRC_Prune;
    }
    case TK_FUNCTION:
    case TK_AGG_FUNCTION:
    case TK_CONST_FUNC: {
      /* The arguments to a function have a fixed destination.
      ** Mark them this way to avoid generated unneeded OP_SCopy
      ** instructions. 
      */
      ExprList *pList = pExpr->x.pList;
      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
      if( pList ){
        int i = pList->nExpr;
        struct ExprList_item *pItem = pList->a;
        for(; i>0; i--, pItem++){
          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
        }
      }
      break;
    }
  }
  if( isAppropriateForFactoring(pExpr) ){
    int r1 = ++pParse->nMem;
    int r2;
    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
    pExpr->op2 = pExpr->op;
    pExpr->op = TK_REGISTER;
    pExpr->iTable = r2;
    return WRC_Prune;
  }
  return WRC_Continue;
}

/*
** Preevaluate constant subexpressions within pExpr and store the
** results in registers.  Modify pExpr so that the constant subexpresions
** are TK_REGISTER opcodes that refer to the precomputed values.
*/
void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  Walker w;
  w.xExprCallback = evalConstExpr;
  w.xSelectCallback = 0;
  w.pParse = pParse;
  sqlite3WalkExpr(&w, pExpr);
}


/*
** Generate code that pushes the value of every element of the given
** expression list into a sequence of registers beginning at target.
**
** Return the number of elements evaluated.
*/
int sqlite3ExprCodeExprList(
  Parse *pParse,     /* Parsing context */
  ExprList *pList,   /* The expression list to be coded */
  int target,        /* Where to write results */
  int doHardCopy     /* Make a hard copy of every element */
){
  struct ExprList_item *pItem;
  int i, n;
  assert( pList!=0 );
  assert( target>0 );
  n = pList->nExpr;
  for(pItem=pList->a, i=0; i<n; i++, pItem++){
    if( pItem->iAlias ){
      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
      Vdbe *v = sqlite3GetVdbe(pParse);
      if( iReg!=target+i ){
        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
      }
    }else{
      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
    }
    if( doHardCopy && !pParse->db->mallocFailed ){
      sqlite3ExprHardCopy(pParse, target, n);
    }
  }
  return n;
}

/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is true but execution
** continues straight thru if the expression is false.
**
** If the expression evaluates to NULL (neither true nor false), then
** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
**
** This code depends on the fact that certain token values (ex: TK_EQ)
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
** the make process cause these values to align.  Assert()s in the code
** below verify that the numbers are aligned correctly.
*/
void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  Vdbe *v = pParse->pVdbe;
  int op = 0;
  int regFree1 = 0;
  int regFree2 = 0;
  int r1, r2;

  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
  op = pExpr->op;
  switch( op ){
    case TK_AND: {
      int d2 = sqlite3VdbeMakeLabel(v);
      testcase( jumpIfNull==0 );
      sqlite3ExprCachePush(pParse);
      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
      sqlite3VdbeResolveLabel(v, d2);
      sqlite3ExprCachePop(pParse, 1);
      break;
    }
    case TK_OR: {
      testcase( jumpIfNull==0 );
      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
      break;
    }
    case TK_NOT: {
      testcase( jumpIfNull==0 );
      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
      break;
    }
    case TK_LT:
    case TK_LE:
    case TK_GT:
    case TK_GE:
    case TK_NE:
    case TK_EQ: {
      assert( TK_LT==OP_Lt );
      assert( TK_LE==OP_Le );
      assert( TK_GT==OP_Gt );
      assert( TK_GE==OP_Ge );
      assert( TK_EQ==OP_Eq );
      assert( TK_NE==OP_Ne );
      testcase( op==TK_LT );
      testcase( op==TK_LE );
      testcase( op==TK_GT );
      testcase( op==TK_GE );
      testcase( op==TK_EQ );
      testcase( op==TK_NE );
      testcase( jumpIfNull==0 );
      codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
                                  pExpr->pRight, &r2, &regFree2);
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
                  r1, r2, dest, jumpIfNull);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_IS:
    case TK_ISNOT: {
      testcase( op==TK_IS );
      testcase( op==TK_ISNOT );
      codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
                                  pExpr->pRight, &r2, &regFree2);
      op = (op==TK_IS) ? TK_EQ : TK_NE;
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
                  r1, r2, dest, SQLITE_NULLEQ);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_ISNULL:
    case TK_NOTNULL: {
      assert( TK_ISNULL==OP_IsNull );
      assert( TK_NOTNULL==OP_NotNull );
      testcase( op==TK_ISNULL );
      testcase( op==TK_NOTNULL );
      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
      sqlite3VdbeAddOp2(v, op, r1, dest);
      testcase( regFree1==0 );
      break;
    }
    case TK_BETWEEN: {
      /*    x BETWEEN y AND z
      **
      ** Is equivalent to 
      **
      **    x>=y AND x<=z
      **
      ** Code it as such, taking care to do the common subexpression
      ** elementation of x.
      */
      Expr exprAnd;
      Expr compLeft;
      Expr compRight;
      Expr exprX;

      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
      exprX = *pExpr->pLeft;
      exprAnd.op = TK_AND;
      exprAnd.pLeft = &compLeft;
      exprAnd.pRight = &compRight;
      compLeft.op = TK_GE;
      compLeft.pLeft = &exprX;
      compLeft.pRight = pExpr->x.pList->a[0].pExpr;
      compRight.op = TK_LE;
      compRight.pLeft = &exprX;
      compRight.pRight = pExpr->x.pList->a[1].pExpr;
      exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
      testcase( regFree1==0 );
      exprX.op = TK_REGISTER;
      testcase( jumpIfNull==0 );
      sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
      break;
    }
    default: {
      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
      testcase( regFree1==0 );
      testcase( jumpIfNull==0 );
      break;
    }
  }
  sqlite3ReleaseTempReg(pParse, regFree1);
  sqlite3ReleaseTempReg(pParse, regFree2);  
}

/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is false but execution
** continues straight thru if the expression is true.
**
** If the expression evaluates to NULL (neither true nor false) then
** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
** is 0.
*/
void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  Vdbe *v = pParse->pVdbe;
  int op = 0;
  int regFree1 = 0;
  int regFree2 = 0;
  int r1, r2;

  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
  if( pExpr==0 )    return;

  /* The value of pExpr->op and op are related as follows:
  **
  **       pExpr->op            op
  **       ---------          ----------
  **       TK_ISNULL          OP_NotNull
  **       TK_NOTNULL         OP_IsNull
  **       TK_NE              OP_Eq
  **       TK_EQ              OP_Ne
  **       TK_GT              OP_Le
  **       TK_LE              OP_Gt
  **       TK_GE              OP_Lt
  **       TK_LT              OP_Ge
  **
  ** For other values of pExpr->op, op is undefined and unused.
  ** The value of TK_ and OP_ constants are arranged such that we
  ** can compute the mapping above using the following expression.
  ** Assert()s verify that the computation is correct.
  */
  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);

  /* Verify correct alignment of TK_ and OP_ constants
  */
  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  assert( pExpr->op!=TK_NE || op==OP_Eq );
  assert( pExpr->op!=TK_EQ || op==OP_Ne );
  assert( pExpr->op!=TK_LT || op==OP_Ge );
  assert( pExpr->op!=TK_LE || op==OP_Gt );
  assert( pExpr->op!=TK_GT || op==OP_Le );
  assert( pExpr->op!=TK_GE || op==OP_Lt );

  switch( pExpr->op ){
    case TK_AND: {
      testcase( jumpIfNull==0 );
      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
      break;
    }
    case TK_OR: {
      int d2 = sqlite3VdbeMakeLabel(v);
      testcase( jumpIfNull==0 );
      sqlite3ExprCachePush(pParse);
      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
      sqlite3VdbeResolveLabel(v, d2);
      sqlite3ExprCachePop(pParse, 1);
      break;
    }
    case TK_NOT: {
      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
      break;
    }
    case TK_LT:
    case TK_LE:
    case TK_GT:
    case TK_GE:
    case TK_NE:
    case TK_EQ: {
      testcase( op==TK_LT );
      testcase( op==TK_LE );
      testcase( op==TK_GT );
      testcase( op==TK_GE );
      testcase( op==TK_EQ );
      testcase( op==TK_NE );
      testcase( jumpIfNull==0 );
      codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
                                  pExpr->pRight, &r2, &regFree2);
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
                  r1, r2, dest, jumpIfNull);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_IS:
    case TK_ISNOT: {
      testcase( pExpr->op==TK_IS );
      testcase( pExpr->op==TK_ISNOT );
      codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
                                  pExpr->pRight, &r2, &regFree2);
      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
                  r1, r2, dest, SQLITE_NULLEQ);
      testcase( regFree1==0 );
      testcase( regFree2==0 );
      break;
    }
    case TK_ISNULL:
    case TK_NOTNULL: {
      testcase( op==TK_ISNULL );
      testcase( op==TK_NOTNULL );
      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
      sqlite3VdbeAddOp2(v, op, r1, dest);
      testcase( regFree1==0 );
      break;
    }
    case TK_BETWEEN: {
      /*    x BETWEEN y AND z
      **
      ** Is equivalent to 
      **
      **    x>=y AND x<=z
      **
      ** Code it as such, taking care to do the common subexpression
      ** elementation of x.
      */
      Expr exprAnd;
      Expr compLeft;
      Expr compRight;
      Expr exprX;

      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
      exprX = *pExpr->pLeft;
      exprAnd.op = TK_AND;
      exprAnd.pLeft = &compLeft;
      exprAnd.pRight = &compRight;
      compLeft.op = TK_GE;
      compLeft.pLeft = &exprX;
      compLeft.pRight = pExpr->x.pList->a[0].pExpr;
      compRight.op = TK_LE;
      compRight.pLeft = &exprX;
      compRight.pRight = pExpr->x.pList->a[1].pExpr;
      exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
      testcase( regFree1==0 );
      exprX.op = TK_REGISTER;
      testcase( jumpIfNull==0 );
      sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
      break;
    }
    default: {
      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
      testcase( regFree1==0 );
      testcase( jumpIfNull==0 );
      break;
    }
  }
  sqlite3ReleaseTempReg(pParse, regFree1);
  sqlite3ReleaseTempReg(pParse, regFree2);
}

/*
** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
** if they are identical and return FALSE if they differ in any way.
**
** Sometimes this routine will return FALSE even if the two expressions
** really are equivalent.  If we cannot prove that the expressions are
** identical, we return FALSE just to be safe.  So if this routine
** returns false, then you do not really know for certain if the two
** expressions are the same.  But if you get a TRUE return, then you
** can be sure the expressions are the same.  In the places where
** this routine is used, it does not hurt to get an extra FALSE - that
** just might result in some slightly slower code.  But returning
** an incorrect TRUE could lead to a malfunction.
*/
int sqlite3ExprCompare(Expr *pA, Expr *pB){
  int i;
  if( pA==0||pB==0 ){
    return pB==pA;
  }
  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
    return 0;
  }
  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
  if( pA->op!=pB->op ) return 0;
  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
  if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;

  if( pA->x.pList && pB->x.pList ){
    if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
    for(i=0; i<pA->x.pList->nExpr; i++){
      Expr *pExprA = pA->x.pList->a[i].pExpr;
      Expr *pExprB = pB->x.pList->a[i].pExpr;
      if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
    }
  }else if( pA->x.pList || pB->x.pList ){
    return 0;
  }

  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
  if( ExprHasProperty(pA, EP_IntValue) ){
    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
      return 0;
    }
  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
      return 0;
    }
  }
  return 1;
}


/*
** Add a new element to the pAggInfo->aCol[] array.  Return the index of
** the new element.  Return a negative number if malloc fails.
*/
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  int i;
  pInfo->aCol = sqlite3ArrayAllocate(
       db,
       pInfo->aCol,
       sizeof(pInfo->aCol[0]),
       3,
       &pInfo->nColumn,
       &pInfo->nColumnAlloc,
       &i
  );
  return i;
}    

/*
** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
** the new element.  Return a negative number if malloc fails.
*/
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  int i;
  pInfo->aFunc = sqlite3ArrayAllocate(
       db, 
       pInfo->aFunc,
       sizeof(pInfo->aFunc[0]),
       3,
       &pInfo->nFunc,
       &pInfo->nFuncAlloc,
       &i
  );
  return i;
}    

/*
** This is the xExprCallback for a tree walker.  It is used to
** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
** for additional information.
*/
static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  int i;
  NameContext *pNC = pWalker->u.pNC;
  Parse *pParse = pNC->pParse;
  SrcList *pSrcList = pNC->pSrcList;
  AggInfo *pAggInfo = pNC->pAggInfo;

  switch( pExpr->op ){
    case TK_AGG_COLUMN:
    case TK_COLUMN: {
      testcase( pExpr->op==TK_AGG_COLUMN );
      testcase( pExpr->op==TK_COLUMN );
      /* Check to see if the column is in one of the tables in the FROM
      ** clause of the aggregate query */
      if( ALWAYS(pSrcList!=0) ){
        struct SrcList_item *pItem = pSrcList->a;
        for(i=0; i<pSrcList->nSrc; i++, pItem++){
          struct AggInfo_col *pCol;
          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
          if( pExpr->iTable==pItem->iCursor ){
            /* If we reach this point, it means that pExpr refers to a table
            ** that is in the FROM clause of the aggregate query.  
            **
            ** Make an entry for the column in pAggInfo->aCol[] if there
            ** is not an entry there already.
            */
            int k;
            pCol = pAggInfo->aCol;
            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
              if( pCol->iTable==pExpr->iTable &&
                  pCol->iColumn==pExpr->iColumn ){
                break;
              }
            }
            if( (k>=pAggInfo->nColumn)
             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
            ){
              pCol = &pAggInfo->aCol[k];
              pCol->pTab = pExpr->pTab;
              pCol->iTable = pExpr->iTable;
              pCol->iColumn = pExpr->iColumn;
              pCol->iMem = ++pParse->nMem;
              pCol->iSorterColumn = -1;
              pCol->pExpr = pExpr;
              if( pAggInfo->pGroupBy ){
                int j, n;
                ExprList *pGB = pAggInfo->pGroupBy;
                struct ExprList_item *pTerm = pGB->a;
                n = pGB->nExpr;
                for(j=0; j<n; j++, pTerm++){
                  Expr *pE = pTerm->pExpr;
                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
                      pE->iColumn==pExpr->iColumn ){
                    pCol->iSorterColumn = j;
                    break;
                  }
                }
              }
              if( pCol->iSorterColumn<0 ){
                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
              }
            }
            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
            ** because it was there before or because we just created it).
            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
            ** pAggInfo->aCol[] entry.
            */
            ExprSetIrreducible(pExpr);
            pExpr->pAggInfo = pAggInfo;
            pExpr->op = TK_AGG_COLUMN;
            pExpr->iAgg = (i16)k;
            break;
          } /* endif pExpr->iTable==pItem->iCursor */
        } /* end loop over pSrcList */
      }
      return WRC_Prune;
    }
    case TK_AGG_FUNCTION: {
      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
      ** to be ignored */
      if( pNC->nDepth==0 ){
        /* Check to see if pExpr is a duplicate of another aggregate 
        ** function that is already in the pAggInfo structure
        */
        struct AggInfo_func *pItem = pAggInfo->aFunc;
        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
          if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
            break;
          }
        }
        if( i>=pAggInfo->nFunc ){
          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
          */
          u8 enc = ENC(pParse->db);
          i = addAggInfoFunc(pParse->db, pAggInfo);
          if( i>=0 ){
            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
            pItem = &pAggInfo->aFunc[i];
            pItem->pExpr = pExpr;
            pItem->iMem = ++pParse->nMem;
            assert( !ExprHasProperty(pExpr, EP_IntValue) );
            pItem->pFunc = sqlite3FindFunction(pParse->db,
                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
            if( pExpr->flags & EP_Distinct ){
              pItem->iDistinct = pParse->nTab++;
            }else{
              pItem->iDistinct = -1;
            }
          }
        }
        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
        */
        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
        ExprSetIrreducible(pExpr);
        pExpr->iAgg = (i16)i;
        pExpr->pAggInfo = pAggInfo;
        return WRC_Prune;
      }
    }
  }
  return WRC_Continue;
}
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  NameContext *pNC = pWalker->u.pNC;
  if( pNC->nDepth==0 ){
    pNC->nDepth++;
    sqlite3WalkSelect(pWalker, pSelect);
    pNC->nDepth--;
    return WRC_Prune;
  }else{
    return WRC_Continue;
  }
}

/*
** Analyze the given expression looking for aggregate functions and
** for variables that need to be added to the pParse->aAgg[] array.
** Make additional entries to the pParse->aAgg[] array as necessary.
**
** This routine should only be called after the expression has been
** analyzed by sqlite3ResolveExprNames().
*/
void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  Walker w;
  w.xExprCallback = analyzeAggregate;
  w.xSelectCallback = analyzeAggregatesInSelect;
  w.u.pNC = pNC;
  assert( pNC->pSrcList!=0 );
  sqlite3WalkExpr(&w, pExpr);
}

/*
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
** expression list.  Return the number of errors.
**
** If an error is found, the analysis is cut short.
*/
void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  struct ExprList_item *pItem;
  int i;
  if( pList ){
    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
    }
  }
}

/*
** Allocate a single new register for use to hold some intermediate result.
*/
int sqlite3GetTempReg(Parse *pParse){
  if( pParse->nTempReg==0 ){
    return ++pParse->nMem;
  }
  return pParse->aTempReg[--pParse->nTempReg];
}

/*
** Deallocate a register, making available for reuse for some other
** purpose.
**
** If a register is currently being used by the column cache, then
** the dallocation is deferred until the column cache line that uses
** the register becomes stale.
*/
void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
    int i;
    struct yColCache *p;
    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
      if( p->iReg==iReg ){
        p->tempReg = 1;
        return;
      }
    }
    pParse->aTempReg[pParse->nTempReg++] = iReg;
  }
}

/*
** Allocate or deallocate a block of nReg consecutive registers
*/
int sqlite3GetTempRange(Parse *pParse, int nReg){
  int i, n;
  i = pParse->iRangeReg;
  n = pParse->nRangeReg;
  if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
    pParse->iRangeReg += nReg;
    pParse->nRangeReg -= nReg;
  }else{
    i = pParse->nMem+1;
    pParse->nMem += nReg;
  }
  return i;
}
void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  if( nReg>pParse->nRangeReg ){
    pParse->nRangeReg = nReg;
    pParse->iRangeReg = iReg;
  }
}

Added src/fault.c.























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
** 2008 Jan 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
*/

/*
** This file contains code to support the concept of "benign" 
** malloc failures (when the xMalloc() or xRealloc() method of the
** sqlite3_mem_methods structure fails to allocate a block of memory
** and returns 0). 
**
** Most malloc failures are non-benign. After they occur, SQLite
** abandons the current operation and returns an error code (usually
** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
** fatal. For example, if a malloc fails while resizing a hash table, this 
** is completely recoverable simply by not carrying out the resize. The 
** hash table will continue to function normally.  So a malloc failure 
** during a hash table resize is a benign fault.
*/

#include "sqliteInt.h"

#ifndef SQLITE_OMIT_BUILTIN_TEST

/*
** Global variables.
*/
typedef struct BenignMallocHooks BenignMallocHooks;
static SQLITE_WSD struct BenignMallocHooks {
  void (*xBenignBegin)(void);
  void (*xBenignEnd)(void);
} sqlite3Hooks = { 0, 0 };

/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
** structure.  If writable static data is unsupported on the target,
** we have to locate the state vector at run-time.  In the more common
** case where writable static data is supported, wsdHooks can refer directly
** to the "sqlite3Hooks" state vector declared above.
*/
#ifdef SQLITE_OMIT_WSD
# define wsdHooksInit \
  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
# define wsdHooks x[0]
#else
# define wsdHooksInit
# define wsdHooks sqlite3Hooks
#endif


/*
** Register hooks to call when sqlite3BeginBenignMalloc() and
** sqlite3EndBenignMalloc() are called, respectively.
*/
void sqlite3BenignMallocHooks(
  void (*xBenignBegin)(void),
  void (*xBenignEnd)(void)
){
  wsdHooksInit;
  wsdHooks.xBenignBegin = xBenignBegin;
  wsdHooks.xBenignEnd = xBenignEnd;
}

/*
** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
** indicates that subsequent malloc failures are non-benign.
*/
void sqlite3BeginBenignMalloc(void){
  wsdHooksInit;
  if( wsdHooks.xBenignBegin ){
    wsdHooks.xBenignBegin();
  }
}
void sqlite3EndBenignMalloc(void){
  wsdHooksInit;
  if( wsdHooks.xBenignEnd ){
    wsdHooks.xBenignEnd();
  }
}

#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */

Added src/fkey.c.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
/*
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used by the compiler to add foreign key
** support to compiled SQL statements.
*/
#include "sqliteInt.h"

#ifndef SQLITE_OMIT_FOREIGN_KEY
#ifndef SQLITE_OMIT_TRIGGER

/*
** Deferred and Immediate FKs
** --------------------------
**
** Foreign keys in SQLite come in two flavours: deferred and immediate.
** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
** is returned and the current statement transaction rolled back. If a 
** deferred foreign key constraint is violated, no action is taken 
** immediately. However if the application attempts to commit the 
** transaction before fixing the constraint violation, the attempt fails.
**
** Deferred constraints are implemented using a simple counter associated
** with the database handle. The counter is set to zero each time a 
** database transaction is opened. Each time a statement is executed 
** that causes a foreign key violation, the counter is incremented. Each
** time a statement is executed that removes an existing violation from
** the database, the counter is decremented. When the transaction is
** committed, the commit fails if the current value of the counter is
** greater than zero. This scheme has two big drawbacks:
**
**   * When a commit fails due to a deferred foreign key constraint, 
**     there is no way to tell which foreign constraint is not satisfied,
**     or which row it is not satisfied for.
**
**   * If the database contains foreign key violations when the 
**     transaction is opened, this may cause the mechanism to malfunction.
**
** Despite these problems, this approach is adopted as it seems simpler
** than the alternatives.
**
** INSERT operations:
**
**   I.1) For each FK for which the table is the child table, search
**        the parent table for a match. If none is found increment the
**        constraint counter.
**
**   I.2) For each FK for which the table is the parent table, 
**        search the child table for rows that correspond to the new
**        row in the parent table. Decrement the counter for each row
**        found (as the constraint is now satisfied).
**
** DELETE operations:
**
**   D.1) For each FK for which the table is the child table, 
**        search the parent table for a row that corresponds to the 
**        deleted row in the child table. If such a row is not found, 
**        decrement the counter.
**
**   D.2) For each FK for which the table is the parent table, search 
**        the child table for rows that correspond to the deleted row 
**        in the parent table. For each found increment the counter.
**
** UPDATE operations:
**
**   An UPDATE command requires that all 4 steps above are taken, but only
**   for FK constraints for which the affected columns are actually 
**   modified (values must be compared at runtime).
**
** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
** This simplifies the implementation a bit.
**
** For the purposes of immediate FK constraints, the OR REPLACE conflict
** resolution is considered to delete rows before the new row is inserted.
** If a delete caused by OR REPLACE violates an FK constraint, an exception
** is thrown, even if the FK constraint would be satisfied after the new 
** row is inserted.
**
** Immediate constraints are usually handled similarly. The only difference 
** is that the counter used is stored as part of each individual statement
** object (struct Vdbe). If, after the statement has run, its immediate
** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
** and the statement transaction is rolled back. An exception is an INSERT
** statement that inserts a single row only (no triggers). In this case,
** instead of using a counter, an exception is thrown immediately if the
** INSERT violates a foreign key constraint. This is necessary as such
** an INSERT does not open a statement transaction.
**
** TODO: How should dropping a table be handled? How should renaming a 
** table be handled?
**
**
** Query API Notes
** ---------------
**
** Before coding an UPDATE or DELETE row operation, the code-generator
** for those two operations needs to know whether or not the operation
** requires any FK processing and, if so, which columns of the original
** row are required by the FK processing VDBE code (i.e. if FKs were
** implemented using triggers, which of the old.* columns would be 
** accessed). No information is required by the code-generator before
** coding an INSERT operation. The functions used by the UPDATE/DELETE
** generation code to query for this information are:
**
**   sqlite3FkRequired() - Test to see if FK processing is required.
**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
**
**
** Externally accessible module functions
** --------------------------------------
**
**   sqlite3FkCheck()    - Check for foreign key violations.
**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
**   sqlite3FkDelete()   - Delete an FKey structure.
*/

/*
** VDBE Calling Convention
** -----------------------
**
** Example:
**
**   For the following INSERT statement:
**
**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
**     INSERT INTO t1 VALUES(1, 2, 3.1);
**
**   Register (x):        2    (type integer)
**   Register (x+1):      1    (type integer)
**   Register (x+2):      NULL (type NULL)
**   Register (x+3):      3.1  (type real)
*/

/*
** A foreign key constraint requires that the key columns in the parent
** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
** Given that pParent is the parent table for foreign key constraint pFKey, 
** search the schema a unique index on the parent key columns. 
**
** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
** is set to point to the unique index. 
** 
** If the parent key consists of a single column (the foreign key constraint
** is not a composite foreign key), output variable *paiCol is set to NULL.
** Otherwise, it is set to point to an allocated array of size N, where
** N is the number of columns in the parent key. The first element of the
** array is the index of the child table column that is mapped by the FK
** constraint to the parent table column stored in the left-most column
** of index *ppIdx. The second element of the array is the index of the
** child table column that corresponds to the second left-most column of
** *ppIdx, and so on.
**
** If the required index cannot be found, either because:
**
**   1) The named parent key columns do not exist, or
**
**   2) The named parent key columns do exist, but are not subject to a
**      UNIQUE or PRIMARY KEY constraint, or
**
**   3) No parent key columns were provided explicitly as part of the
**      foreign key definition, and the parent table does not have a
**      PRIMARY KEY, or
**
**   4) No parent key columns were provided explicitly as part of the
**      foreign key definition, and the PRIMARY KEY of the parent table 
**      consists of a a different number of columns to the child key in 
**      the child table.
**
** then non-zero is returned, and a "foreign key mismatch" error loaded
** into pParse. If an OOM error occurs, non-zero is returned and the
** pParse->db->mallocFailed flag is set.
*/
static int locateFkeyIndex(
  Parse *pParse,                  /* Parse context to store any error in */
  Table *pParent,                 /* Parent table of FK constraint pFKey */
  FKey *pFKey,                    /* Foreign key to find index for */
  Index **ppIdx,                  /* OUT: Unique index on parent table */
  int **paiCol                    /* OUT: Map of index columns in pFKey */
){
  Index *pIdx = 0;                    /* Value to return via *ppIdx */
  int *aiCol = 0;                     /* Value to return via *paiCol */
  int nCol = pFKey->nCol;             /* Number of columns in parent key */
  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */

  /* The caller is responsible for zeroing output parameters. */
  assert( ppIdx && *ppIdx==0 );
  assert( !paiCol || *paiCol==0 );
  assert( pParse );

  /* If this is a non-composite (single column) foreign key, check if it 
  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
  ** and *paiCol set to zero and return early. 
  **
  ** Otherwise, for a composite foreign key (more than one column), allocate
  ** space for the aiCol array (returned via output parameter *paiCol).
  ** Non-composite foreign keys do not require the aiCol array.
  */
  if( nCol==1 ){
    /* The FK maps to the IPK if any of the following are true:
    **
    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
    **      mapped to the primary key of table pParent, or
    **   2) The FK is explicitly mapped to a column declared as INTEGER
    **      PRIMARY KEY.
    */
    if( pParent->iPKey>=0 ){
      if( !zKey ) return 0;
      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
    }
  }else if( paiCol ){
    assert( nCol>1 );
    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
    if( !aiCol ) return 1;
    *paiCol = aiCol;
  }

  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
      ** of columns. If each indexed column corresponds to a foreign key
      ** column of pFKey, then this index is a winner.  */

      if( zKey==0 ){
        /* If zKey is NULL, then this foreign key is implicitly mapped to 
        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
        ** identified by the test (Index.autoIndex==2).  */
        if( pIdx->autoIndex==2 ){
          if( aiCol ){
            int i;
            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
          }
          break;
        }
      }else{
        /* If zKey is non-NULL, then this foreign key was declared to
        ** map to an explicit list of columns in table pParent. Check if this
        ** index matches those columns. Also, check that the index uses
        ** the default collation sequences for each column. */
        int i, j;
        for(i=0; i<nCol; i++){
          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
          char *zDfltColl;                  /* Def. collation for column */
          char *zIdxCol;                    /* Name of indexed column */

          /* If the index uses a collation sequence that is different from
          ** the default collation sequence for the column, this index is
          ** unusable. Bail out early in this case.  */
          zDfltColl = pParent->aCol[iCol].zColl;
          if( !zDfltColl ){
            zDfltColl = "BINARY";
          }
          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;

          zIdxCol = pParent->aCol[iCol].zName;
          for(j=0; j<nCol; j++){
            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
              break;
            }
          }
          if( j==nCol ) break;
        }
        if( i==nCol ) break;      /* pIdx is usable */
      }
    }
  }

  if( !pIdx ){
    if( !pParse->disableTriggers ){
      sqlite3ErrorMsg(pParse, "foreign key mismatch");
    }
    sqlite3DbFree(pParse->db, aiCol);
    return 1;
  }

  *ppIdx = pIdx;
  return 0;
}

/*
** This function is called when a row is inserted into or deleted from the 
** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
** on the child table of pFKey, this function is invoked twice for each row
** affected - once to "delete" the old row, and then again to "insert" the
** new row.
**
** Each time it is called, this function generates VDBE code to locate the
** row in the parent table that corresponds to the row being inserted into 
** or deleted from the child table. If the parent row can be found, no 
** special action is taken. Otherwise, if the parent row can *not* be
** found in the parent table:
**
**   Operation | FK type   | Action taken
**   --------------------------------------------------------------------------
**   INSERT      immediate   Increment the "immediate constraint counter".
**
**   DELETE      immediate   Decrement the "immediate constraint counter".
**
**   INSERT      deferred    Increment the "deferred constraint counter".
**
**   DELETE      deferred    Decrement the "deferred constraint counter".
**
** These operations are identified in the comment at the top of this file 
** (fkey.c) as "I.1" and "D.1".
*/
static void fkLookupParent(
  Parse *pParse,        /* Parse context */
  int iDb,              /* Index of database housing pTab */
  Table *pTab,          /* Parent table of FK pFKey */
  Index *pIdx,          /* Unique index on parent key columns in pTab */
  FKey *pFKey,          /* Foreign key constraint */
  int *aiCol,           /* Map from parent key columns to child table columns */
  int regData,          /* Address of array containing child table row */
  int nIncr,            /* Increment constraint counter by this */
  int isIgnore          /* If true, pretend pTab contains all NULL values */
){
  int i;                                    /* Iterator variable */
  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
  int iCur = pParse->nTab - 1;              /* Cursor number to use */
  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */

  /* If nIncr is less than zero, then check at runtime if there are any
  ** outstanding constraints to resolve. If there are not, there is no need
  ** to check if deleting this row resolves any outstanding violations.
  **
  ** Check if any of the key columns in the child table row are NULL. If 
  ** any are, then the constraint is considered satisfied. No need to 
  ** search for a matching row in the parent table.  */
  if( nIncr<0 ){
    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  }
  for(i=0; i<pFKey->nCol; i++){
    int iReg = aiCol[i] + regData + 1;
    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  }

  if( isIgnore==0 ){
    if( pIdx==0 ){
      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
      ** column of the parent table (table pTab).  */
      int iMustBeInt;               /* Address of MustBeInt instruction */
      int regTemp = sqlite3GetTempReg(pParse);
  
      /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
      ** apply the affinity of the parent key). If this fails, then there
      ** is no matching parent key. Before using MustBeInt, make a copy of
      ** the value. Otherwise, the value inserted into the child key column
      ** will have INTEGER affinity applied to it, which may not be correct.  */
      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  
      /* If the parent table is the same as the child table, and we are about
      ** to increment the constraint-counter (i.e. this is an INSERT operation),
      ** then check if the row being inserted matches itself. If so, do not
      ** increment the constraint-counter.  */
      if( pTab==pFKey->pFrom && nIncr==1 ){
        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
      }
  
      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
      sqlite3VdbeJumpHere(v, iMustBeInt);
      sqlite3ReleaseTempReg(pParse, regTemp);
    }else{
      int nCol = pFKey->nCol;
      int regTemp = sqlite3GetTempRange(pParse, nCol);
      int regRec = sqlite3GetTempReg(pParse);
      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  
      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
      for(i=0; i<nCol; i++){
        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
      }
  
      /* If the parent table is the same as the child table, and we are about
      ** to increment the constraint-counter (i.e. this is an INSERT operation),
      ** then check if the row being inserted matches itself. If so, do not
      ** increment the constraint-counter.  */
      if( pTab==pFKey->pFrom && nIncr==1 ){
        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
        for(i=0; i<nCol; i++){
          int iChild = aiCol[i]+1+regData;
          int iParent = pIdx->aiColumn[i]+1+regData;
          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
        }
        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
      }
  
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
      sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
  
      sqlite3ReleaseTempReg(pParse, regRec);
      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
    }
  }

  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
    /* Special case: If this is an INSERT statement that will insert exactly
    ** one row into the table, raise a constraint immediately instead of
    ** incrementing a counter. This is necessary as the VM code is being
    ** generated for will not open a statement transaction.  */
    assert( nIncr==1 );
    sqlite3HaltConstraint(
        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
    );
  }else{
    if( nIncr>0 && pFKey->isDeferred==0 ){
      sqlite3ParseToplevel(pParse)->mayAbort = 1;
    }
    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  }

  sqlite3VdbeResolveLabel(v, iOk);
  sqlite3VdbeAddOp1(v, OP_Close, iCur);
}

/*
** This function is called to generate code executed when a row is deleted
** from the parent table of foreign key constraint pFKey and, if pFKey is 
** deferred, when a row is inserted into the same table. When generating
** code for an SQL UPDATE operation, this function may be called twice -
** once to "delete" the old row and once to "insert" the new row.
**
** The code generated by this function scans through the rows in the child
** table that correspond to the parent table row being deleted or inserted.
** For each child row found, one of the following actions is taken:
**
**   Operation | FK type   | Action taken
**   --------------------------------------------------------------------------
**   DELETE      immediate   Increment the "immediate constraint counter".
**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
**                           throw a "foreign key constraint failed" exception.
**
**   INSERT      immediate   Decrement the "immediate constraint counter".
**
**   DELETE      deferred    Increment the "deferred constraint counter".
**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
**                           throw a "foreign key constraint failed" exception.
**
**   INSERT      deferred    Decrement the "deferred constraint counter".
**
** These operations are identified in the comment at the top of this file 
** (fkey.c) as "I.2" and "D.2".
*/
static void fkScanChildren(
  Parse *pParse,                  /* Parse context */
  SrcList *pSrc,                  /* SrcList containing the table to scan */
  Table *pTab,
  Index *pIdx,                    /* Foreign key index */
  FKey *pFKey,                    /* Foreign key relationship */
  int *aiCol,                     /* Map from pIdx cols to child table cols */
  int regData,                    /* Referenced table data starts here */
  int nIncr                       /* Amount to increment deferred counter by */
){
  sqlite3 *db = pParse->db;       /* Database handle */
  int i;                          /* Iterator variable */
  Expr *pWhere = 0;               /* WHERE clause to scan with */
  NameContext sNameContext;       /* Context used to resolve WHERE clause */
  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
  Vdbe *v = sqlite3GetVdbe(pParse);

  assert( !pIdx || pIdx->pTable==pTab );

  if( nIncr<0 ){
    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  }

  /* Create an Expr object representing an SQL expression like:
  **
  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  **
  ** The collation sequence used for the comparison should be that of
  ** the parent key columns. The affinity of the parent key column should
  ** be applied to each child key value before the comparison takes place.
  */
  for(i=0; i<pFKey->nCol; i++){
    Expr *pLeft;                  /* Value from parent table row */
    Expr *pRight;                 /* Column ref to child table */
    Expr *pEq;                    /* Expression (pLeft = pRight) */
    int iCol;                     /* Index of column in child table */ 
    const char *zCol;             /* Name of column in child table */

    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
    if( pLeft ){
      /* Set the collation sequence and affinity of the LHS of each TK_EQ
      ** expression to the parent key column defaults.  */
      if( pIdx ){
        Column *pCol;
        iCol = pIdx->aiColumn[i];
        pCol = &pIdx->pTable->aCol[iCol];
        pLeft->iTable = regData+iCol+1;
        pLeft->affinity = pCol->affinity;
        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
      }else{
        pLeft->iTable = regData;
        pLeft->affinity = SQLITE_AFF_INTEGER;
      }
    }
    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
    assert( iCol>=0 );
    zCol = pFKey->pFrom->aCol[iCol].zName;
    pRight = sqlite3Expr(db, TK_ID, zCol);
    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  }

  /* If the child table is the same as the parent table, and this scan
  ** is taking place as part of a DELETE operation (operation D.2), omit the
  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
  ** clause, where $rowid is the rowid of the row being deleted.  */
  if( pTab==pFKey->pFrom && nIncr>0 ){
    Expr *pEq;                    /* Expression (pLeft = pRight) */
    Expr *pLeft;                  /* Value from parent table row */
    Expr *pRight;                 /* Column ref to child table */
    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
    pRight = sqlite3Expr(db, TK_COLUMN, 0);
    if( pLeft && pRight ){
      pLeft->iTable = regData;
      pLeft->affinity = SQLITE_AFF_INTEGER;
      pRight->iTable = pSrc->a[0].iCursor;
      pRight->iColumn = -1;
    }
    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  }

  /* Resolve the references in the WHERE clause. */
  memset(&sNameContext, 0, sizeof(NameContext));
  sNameContext.pSrcList = pSrc;
  sNameContext.pParse = pParse;
  sqlite3ResolveExprNames(&sNameContext, pWhere);

  /* Create VDBE to loop through the entries in pSrc that match the WHERE
  ** clause. If the constraint is not deferred, throw an exception for
  ** each row found. Otherwise, for deferred constraints, increment the
  ** deferred constraint counter by nIncr for each row selected.  */
  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
  if( nIncr>0 && pFKey->isDeferred==0 ){
    sqlite3ParseToplevel(pParse)->mayAbort = 1;
  }
  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  if( pWInfo ){
    sqlite3WhereEnd(pWInfo);
  }

  /* Clean up the WHERE clause constructed above. */
  sqlite3ExprDelete(db, pWhere);
  if( iFkIfZero ){
    sqlite3VdbeJumpHere(v, iFkIfZero);
  }
}

/*
** This function returns a pointer to the head of a linked list of FK
** constraints for which table pTab is the parent table. For example,
** given the following schema:
**
**   CREATE TABLE t1(a PRIMARY KEY);
**   CREATE TABLE t2(b REFERENCES t1(a);
**
** Calling this function with table "t1" as an argument returns a pointer
** to the FKey structure representing the foreign key constraint on table
** "t2". Calling this function with "t2" as the argument would return a
** NULL pointer (as there are no FK constraints for which t2 is the parent
** table).
*/
FKey *sqlite3FkReferences(Table *pTab){
  int nName = sqlite3Strlen30(pTab->zName);
  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
}

/*
** The second argument is a Trigger structure allocated by the 
** fkActionTrigger() routine. This function deletes the Trigger structure
** and all of its sub-components.
**
** The Trigger structure or any of its sub-components may be allocated from
** the lookaside buffer belonging to database handle dbMem.
*/
static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  if( p ){
    TriggerStep *pStep = p->step_list;
    sqlite3ExprDelete(dbMem, pStep->pWhere);
    sqlite3ExprListDelete(dbMem, pStep->pExprList);
    sqlite3SelectDelete(dbMem, pStep->pSelect);
    sqlite3ExprDelete(dbMem, p->pWhen);
    sqlite3DbFree(dbMem, p);
  }
}

/*
** This function is called to generate code that runs when table pTab is
** being dropped from the database. The SrcList passed as the second argument
** to this function contains a single entry guaranteed to resolve to
** table pTab.
**
** Normally, no code is required. However, if either
**
**   (a) The table is the parent table of a FK constraint, or
**   (b) The table is the child table of a deferred FK constraint and it is
**       determined at runtime that there are outstanding deferred FK 
**       constraint violations in the database,
**
** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
** the table from the database. Triggers are disabled while running this
** DELETE, but foreign key actions are not.
*/
void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  sqlite3 *db = pParse->db;
  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
    int iSkip = 0;
    Vdbe *v = sqlite3GetVdbe(pParse);

    assert( v );                  /* VDBE has already been allocated */
    if( sqlite3FkReferences(pTab)==0 ){
      /* Search for a deferred foreign key constraint for which this table
      ** is the child table. If one cannot be found, return without 
      ** generating any VDBE code. If one can be found, then jump over
      ** the entire DELETE if there are no outstanding deferred constraints
      ** when this statement is run.  */
      FKey *p;
      for(p=pTab->pFKey; p; p=p->pNextFrom){
        if( p->isDeferred ) break;
      }
      if( !p ) return;
      iSkip = sqlite3VdbeMakeLabel(v);
      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
    }

    pParse->disableTriggers = 1;
    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
    pParse->disableTriggers = 0;

    /* If the DELETE has generated immediate foreign key constraint 
    ** violations, halt the VDBE and return an error at this point, before
    ** any modifications to the schema are made. This is because statement
    ** transactions are not able to rollback schema changes.  */
    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
    sqlite3HaltConstraint(
        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
    );

    if( iSkip ){
      sqlite3VdbeResolveLabel(v, iSkip);
    }
  }
}

/*
** This function is called when inserting, deleting or updating a row of
** table pTab to generate VDBE code to perform foreign key constraint 
** processing for the operation.
**
** For a DELETE operation, parameter regOld is passed the index of the
** first register in an array of (pTab->nCol+1) registers containing the
** rowid of the row being deleted, followed by each of the column values
** of the row being deleted, from left to right. Parameter regNew is passed
** zero in this case.
**
** For an INSERT operation, regOld is passed zero and regNew is passed the
** first register of an array of (pTab->nCol+1) registers containing the new
** row data.
**
** For an UPDATE operation, this function is called twice. Once before
** the original record is deleted from the table using the calling convention
** described for DELETE. Then again after the original record is deleted
** but before the new record is inserted using the INSERT convention. 
*/
void sqlite3FkCheck(
  Parse *pParse,                  /* Parse context */
  Table *pTab,                    /* Row is being deleted from this table */ 
  int regOld,                     /* Previous row data is stored here */
  int regNew                      /* New row data is stored here */
){
  sqlite3 *db = pParse->db;       /* Database handle */
  Vdbe *v;                        /* VM to write code to */
  FKey *pFKey;                    /* Used to iterate through FKs */
  int iDb;                        /* Index of database containing pTab */
  const char *zDb;                /* Name of database containing pTab */
  int isIgnoreErrors = pParse->disableTriggers;

  /* Exactly one of regOld and regNew should be non-zero. */
  assert( (regOld==0)!=(regNew==0) );

  /* If foreign-keys are disabled, this function is a no-op. */
  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;

  v = sqlite3GetVdbe(pParse);
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  zDb = db->aDb[iDb].zName;

  /* Loop through all the foreign key constraints for which pTab is the
  ** child table (the table that the foreign key definition is part of).  */
  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
    Table *pTo;                   /* Parent table of foreign key pFKey */
    Index *pIdx = 0;              /* Index on key columns in pTo */
    int *aiFree = 0;
    int *aiCol;
    int iCol;
    int i;
    int isIgnore = 0;

    /* Find the parent table of this foreign key. Also find a unique index 
    ** on the parent key columns in the parent table. If either of these 
    ** schema items cannot be located, set an error in pParse and return 
    ** early.  */
    if( pParse->disableTriggers ){
      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
    }else{
      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
    }
    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
      if( !isIgnoreErrors || db->mallocFailed ) return;
      continue;
    }
    assert( pFKey->nCol==1 || (aiFree && pIdx) );

    if( aiFree ){
      aiCol = aiFree;
    }else{
      iCol = pFKey->aCol[0].iFrom;
      aiCol = &iCol;
    }
    for(i=0; i<pFKey->nCol; i++){
      if( aiCol[i]==pTab->iPKey ){
        aiCol[i] = -1;
      }
#ifndef SQLITE_OMIT_AUTHORIZATION
      /* Request permission to read the parent key columns. If the 
      ** authorization callback returns SQLITE_IGNORE, behave as if any
      ** values read from the parent table are NULL. */
      if( db->xAuth ){
        int rcauth;
        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
        isIgnore = (rcauth==SQLITE_IGNORE);
      }
#endif
    }

    /* Take a shared-cache advisory read-lock on the parent table. Allocate 
    ** a cursor to use to search the unique index on the parent key columns 
    ** in the parent table.  */
    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
    pParse->nTab++;

    if( regOld!=0 ){
      /* A row is being removed from the child table. Search for the parent.
      ** If the parent does not exist, removing the child row resolves an 
      ** outstanding foreign key constraint violation. */
      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
    }
    if( regNew!=0 ){
      /* A row is being added to the child table. If a parent row cannot
      ** be found, adding the child row has violated the FK constraint. */ 
      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
    }

    sqlite3DbFree(db, aiFree);
  }

  /* Loop through all the foreign key constraints that refer to this table */
  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
    Index *pIdx = 0;              /* Foreign key index for pFKey */
    SrcList *pSrc;
    int *aiCol = 0;

    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
      assert( regOld==0 && regNew!=0 );
      /* Inserting a single row into a parent table cannot cause an immediate
      ** foreign key violation. So do nothing in this case.  */
      continue;
    }

    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
      if( !isIgnoreErrors || db->mallocFailed ) return;
      continue;
    }
    assert( aiCol || pFKey->nCol==1 );

    /* Create a SrcList structure containing a single table (the table 
    ** the foreign key that refers to this table is attached to). This
    ** is required for the sqlite3WhereXXX() interface.  */
    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
    if( pSrc ){
      struct SrcList_item *pItem = pSrc->a;
      pItem->pTab = pFKey->pFrom;
      pItem->zName = pFKey->pFrom->zName;
      pItem->pTab->nRef++;
      pItem->iCursor = pParse->nTab++;
  
      if( regNew!=0 ){
        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
      }
      if( regOld!=0 ){
        /* If there is a RESTRICT action configured for the current operation
        ** on the parent table of this FK, then throw an exception 
        ** immediately if the FK constraint is violated, even if this is a
        ** deferred trigger. That's what RESTRICT means. To defer checking
        ** the constraint, the FK should specify NO ACTION (represented
        ** using OE_None). NO ACTION is the default.  */
        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
      }
      pItem->zName = 0;
      sqlite3SrcListDelete(db, pSrc);
    }
    sqlite3DbFree(db, aiCol);
  }
}

#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))

/*
** This function is called before generating code to update or delete a 
** row contained in table pTab.
*/
u32 sqlite3FkOldmask(
  Parse *pParse,                  /* Parse context */
  Table *pTab                     /* Table being modified */
){
  u32 mask = 0;
  if( pParse->db->flags&SQLITE_ForeignKeys ){
    FKey *p;
    int i;
    for(p=pTab->pFKey; p; p=p->pNextFrom){
      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
    }
    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
      Index *pIdx = 0;
      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
      if( pIdx ){
        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
      }
    }
  }
  return mask;
}

/*
** This function is called before generating code to update or delete a 
** row contained in table pTab. If the operation is a DELETE, then
** parameter aChange is passed a NULL value. For an UPDATE, aChange points
** to an array of size N, where N is the number of columns in table pTab.
** If the i'th column is not modified by the UPDATE, then the corresponding 
** entry in the aChange[] array is set to -1. If the column is modified,
** the value is 0 or greater. Parameter chngRowid is set to true if the
** UPDATE statement modifies the rowid fields of the table.
**
** If any foreign key processing will be required, this function returns
** true. If there is no foreign key related processing, this function 
** returns false.
*/
int sqlite3FkRequired(
  Parse *pParse,                  /* Parse context */
  Table *pTab,                    /* Table being modified */
  int *aChange,                   /* Non-NULL for UPDATE operations */
  int chngRowid                   /* True for UPDATE that affects rowid */
){
  if( pParse->db->flags&SQLITE_ForeignKeys ){
    if( !aChange ){
      /* A DELETE operation. Foreign key processing is required if the 
      ** table in question is either the child or parent table for any 
      ** foreign key constraint.  */
      return (sqlite3FkReferences(pTab) || pTab->pFKey);
    }else{
      /* This is an UPDATE. Foreign key processing is only required if the
      ** operation modifies one or more child or parent key columns. */
      int i;
      FKey *p;

      /* Check if any child key columns are being modified. */
      for(p=pTab->pFKey; p; p=p->pNextFrom){
        for(i=0; i<p->nCol; i++){
          int iChildKey = p->aCol[i].iFrom;
          if( aChange[iChildKey]>=0 ) return 1;
          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
        }
      }

      /* Check if any parent key columns are being modified. */
      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
        for(i=0; i<p->nCol; i++){
          char *zKey = p->aCol[i].zCol;
          int iKey;
          for(iKey=0; iKey<pTab->nCol; iKey++){
            Column *pCol = &pTab->aCol[iKey];
            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
              if( aChange[iKey]>=0 ) return 1;
              if( iKey==pTab->iPKey && chngRowid ) return 1;
            }
          }
        }
      }
    }
  }
  return 0;
}

/*
** This function is called when an UPDATE or DELETE operation is being 
** compiled on table pTab, which is the parent table of foreign-key pFKey.
** If the current operation is an UPDATE, then the pChanges parameter is
** passed a pointer to the list of columns being modified. If it is a
** DELETE, pChanges is passed a NULL pointer.
**
** It returns a pointer to a Trigger structure containing a trigger
** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
** returned (these actions require no special handling by the triggers
** sub-system, code for them is created by fkScanChildren()).
**
** For example, if pFKey is the foreign key and pTab is table "p" in 
** the following schema:
**
**   CREATE TABLE p(pk PRIMARY KEY);
**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
**
** then the returned trigger structure is equivalent to:
**
**   CREATE TRIGGER ... DELETE ON p BEGIN
**     DELETE FROM c WHERE ck = old.pk;
**   END;
**
** The returned pointer is cached as part of the foreign key object. It
** is eventually freed along with the rest of the foreign key object by 
** sqlite3FkDelete().
*/
static Trigger *fkActionTrigger(
  Parse *pParse,                  /* Parse context */
  Table *pTab,                    /* Table being updated or deleted from */
  FKey *pFKey,                    /* Foreign key to get action for */
  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
){
  sqlite3 *db = pParse->db;       /* Database handle */
  int action;                     /* One of OE_None, OE_Cascade etc. */
  Trigger *pTrigger;              /* Trigger definition to return */
  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */

  action = pFKey->aAction[iAction];
  pTrigger = pFKey->apTrigger[iAction];

  if( action!=OE_None && !pTrigger ){
    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
    char const *zFrom;            /* Name of child table */
    int nFrom;                    /* Length in bytes of zFrom */
    Index *pIdx = 0;              /* Parent key index for this FK */
    int *aiCol = 0;               /* child table cols -> parent key cols */
    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
    Expr *pWhere = 0;             /* WHERE clause of trigger step */
    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
    int i;                        /* Iterator variable */
    Expr *pWhen = 0;              /* WHEN clause for the trigger */

    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
    assert( aiCol || pFKey->nCol==1 );

    for(i=0; i<pFKey->nCol; i++){
      Token tOld = { "old", 3 };  /* Literal "old" token */
      Token tNew = { "new", 3 };  /* Literal "new" token */
      Token tFromCol;             /* Name of column in child table */
      Token tToCol;               /* Name of column in parent table */
      int iFromCol;               /* Idx of column in child table */
      Expr *pEq;                  /* tFromCol = OLD.tToCol */

      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
      assert( iFromCol>=0 );
      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;

      tToCol.n = sqlite3Strlen30(tToCol.z);
      tFromCol.n = sqlite3Strlen30(tFromCol.z);

      /* Create the expression "OLD.zToCol = zFromCol". It is important
      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
      ** that the affinity and collation sequence associated with the
      ** parent table are used for the comparison. */
      pEq = sqlite3PExpr(pParse, TK_EQ,
          sqlite3PExpr(pParse, TK_DOT, 
            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
          , 0),
          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
      , 0);
      pWhere = sqlite3ExprAnd(db, pWhere, pEq);

      /* For ON UPDATE, construct the next term of the WHEN clause.
      ** The final WHEN clause will be like this:
      **
      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
      */
      if( pChanges ){
        pEq = sqlite3PExpr(pParse, TK_IS,
            sqlite3PExpr(pParse, TK_DOT, 
              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
              0),
            sqlite3PExpr(pParse, TK_DOT, 
              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
              0),
            0);
        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
      }
  
      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
        Expr *pNew;
        if( action==OE_Cascade ){
          pNew = sqlite3PExpr(pParse, TK_DOT, 
            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
          , 0);
        }else if( action==OE_SetDflt ){
          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
          if( pDflt ){
            pNew = sqlite3ExprDup(db, pDflt, 0);
          }else{
            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
          }
        }else{
          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
        }
        pList = sqlite3ExprListAppend(pParse, pList, pNew);
        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
      }
    }
    sqlite3DbFree(db, aiCol);

    zFrom = pFKey->pFrom->zName;
    nFrom = sqlite3Strlen30(zFrom);

    if( action==OE_Restrict ){
      Token tFrom;
      Expr *pRaise; 

      tFrom.z = zFrom;
      tFrom.n = nFrom;
      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
      if( pRaise ){
        pRaise->affinity = OE_Abort;
      }
      pSelect = sqlite3SelectNew(pParse, 
          sqlite3ExprListAppend(pParse, 0, pRaise),
          sqlite3SrcListAppend(db, 0, &tFrom, 0),
          pWhere,
          0, 0, 0, 0, 0, 0
      );
      pWhere = 0;
    }

    /* In the current implementation, pTab->dbMem==0 for all tables except
    ** for temporary tables used to describe subqueries.  And temporary
    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
    ** should always be 0 there.
    */
    enableLookaside = db->lookaside.bEnabled;
    db->lookaside.bEnabled = 0;

    pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
        sizeof(Trigger) +         /* struct Trigger */
        sizeof(TriggerStep) +     /* Single step in trigger program */
        nFrom + 1                 /* Space for pStep->target.z */
    );
    if( pTrigger ){
      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
      pStep->target.z = (char *)&pStep[1];
      pStep->target.n = nFrom;
      memcpy((char *)pStep->target.z, zFrom, nFrom);
  
      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
      if( pWhen ){
        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
      }
    }

    /* Re-enable the lookaside buffer, if it was disabled earlier. */
    db->lookaside.bEnabled = enableLookaside;

    sqlite3ExprDelete(db, pWhere);
    sqlite3ExprDelete(db, pWhen);
    sqlite3ExprListDelete(db, pList);
    sqlite3SelectDelete(db, pSelect);
    if( db->mallocFailed==1 ){
      fkTriggerDelete(db, pTrigger);
      return 0;
    }

    switch( action ){
      case OE_Restrict:
        pStep->op = TK_SELECT; 
        break;
      case OE_Cascade: 
        if( !pChanges ){ 
          pStep->op = TK_DELETE; 
          break; 
        }
      default:
        pStep->op = TK_UPDATE;
    }
    pStep->pTrig = pTrigger;
    pTrigger->pSchema = pTab->pSchema;
    pTrigger->pTabSchema = pTab->pSchema;
    pFKey->apTrigger[iAction] = pTrigger;
    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  }

  return pTrigger;
}

/*
** This function is called when deleting or updating a row to implement
** any required CASCADE, SET NULL or SET DEFAULT actions.
*/
void sqlite3FkActions(
  Parse *pParse,                  /* Parse context */
  Table *pTab,                    /* Table being updated or deleted from */
  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
  int regOld                      /* Address of array containing old row */
){
  /* If foreign-key support is enabled, iterate through all FKs that 
  ** refer to table pTab. If there is an action associated with the FK 
  ** for this operation (either update or delete), invoke the associated 
  ** trigger sub-program.  */
  if( pParse->db->flags&SQLITE_ForeignKeys ){
    FKey *pFKey;                  /* Iterator variable */
    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
      if( pAction ){
        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
      }
    }
  }
}

#endif /* ifndef SQLITE_OMIT_TRIGGER */

/*
** Free all memory associated with foreign key definitions attached to
** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
** hash table.
*/
void sqlite3FkDelete(Table *pTab){
  FKey *pFKey;                    /* Iterator variable */
  FKey *pNext;                    /* Copy of pFKey->pNextFrom */

  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){

    /* Remove the FK from the fkeyHash hash table. */
    if( pFKey->pPrevTo ){
      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
    }else{
      void *data = (void *)pFKey->pNextTo;
      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
    }
    if( pFKey->pNextTo ){
      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
    }

    /* Delete any triggers created to implement actions for this FK. */
#ifndef SQLITE_OMIT_TRIGGER
    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
#endif

    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
    ** classified as either immediate or deferred.
    */
    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );

    pNext = pFKey->pNextFrom;
    sqlite3DbFree(pTab->dbMem, pFKey);
  }
}
#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */

Added src/func.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
/*
** 2002 February 23
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement various SQL
** functions of SQLite.  
**
** There is only one exported symbol in this file - the function
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
** All other code has file scope.
*/
#include "sqliteInt.h"
#include <stdlib.h>
#include <assert.h>
#include "vdbeInt.h"

/*
** Return the collating function associated with a function.
*/
static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  return context->pColl;
}

/*
** Implementation of the non-aggregate min() and max() functions
*/
static void minmaxFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int i;
  int mask;    /* 0 for min() or 0xffffffff for max() */
  int iBest;
  CollSeq *pColl;

  assert( argc>1 );
  mask = sqlite3_user_data(context)==0 ? 0 : -1;
  pColl = sqlite3GetFuncCollSeq(context);
  assert( pColl );
  assert( mask==-1 || mask==0 );
  iBest = 0;
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  for(i=1; i<argc; i++){
    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
      testcase( mask==0 );
      iBest = i;
    }
  }
  sqlite3_result_value(context, argv[iBest]);
}

/*
** Return the type of the argument.
*/
static void typeofFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  const char *z = 0;
  UNUSED_PARAMETER(NotUsed);
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_INTEGER: z = "integer"; break;
    case SQLITE_TEXT:    z = "text";    break;
    case SQLITE_FLOAT:   z = "real";    break;
    case SQLITE_BLOB:    z = "blob";    break;
    default:             z = "null";    break;
  }
  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
}


/*
** Implementation of the length() function
*/
static void lengthFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int len;

  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_BLOB:
    case SQLITE_INTEGER:
    case SQLITE_FLOAT: {
      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
      break;
    }
    case SQLITE_TEXT: {
      const unsigned char *z = sqlite3_value_text(argv[0]);
      if( z==0 ) return;
      len = 0;
      while( *z ){
        len++;
        SQLITE_SKIP_UTF8(z);
      }
      sqlite3_result_int(context, len);
      break;
    }
    default: {
      sqlite3_result_null(context);
      break;
    }
  }
}

/*
** Implementation of the abs() function
*/
static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_INTEGER: {
      i64 iVal = sqlite3_value_int64(argv[0]);
      if( iVal<0 ){
        if( (iVal<<1)==0 ){
          sqlite3_result_error(context, "integer overflow", -1);
          return;
        }
        iVal = -iVal;
      } 
      sqlite3_result_int64(context, iVal);
      break;
    }
    case SQLITE_NULL: {
      sqlite3_result_null(context);
      break;
    }
    default: {
      double rVal = sqlite3_value_double(argv[0]);
      if( rVal<0 ) rVal = -rVal;
      sqlite3_result_double(context, rVal);
      break;
    }
  }
}

/*
** Implementation of the substr() function.
**
** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
** p1 is 1-indexed.  So substr(x,1,1) returns the first character
** of x.  If x is text, then we actually count UTF-8 characters.
** If x is a blob, then we count bytes.
**
** If p1 is negative, then we begin abs(p1) from the end of x[].
*/
static void substrFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const unsigned char *z;
  const unsigned char *z2;
  int len;
  int p0type;
  i64 p1, p2;
  int negP2 = 0;

  assert( argc==3 || argc==2 );
  if( sqlite3_value_type(argv[1])==SQLITE_NULL
   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  ){
    return;
  }
  p0type = sqlite3_value_type(argv[0]);
  if( p0type==SQLITE_BLOB ){
    len = sqlite3_value_bytes(argv[0]);
    z = sqlite3_value_blob(argv[0]);
    if( z==0 ) return;
    assert( len==sqlite3_value_bytes(argv[0]) );
  }else{
    z = sqlite3_value_text(argv[0]);
    if( z==0 ) return;
    len = 0;
    for(z2=z; *z2; len++){
      SQLITE_SKIP_UTF8(z2);
    }
  }
  p1 = sqlite3_value_int(argv[1]);
  if( argc==3 ){
    p2 = sqlite3_value_int(argv[2]);
    if( p2<0 ){
      p2 = -p2;
      negP2 = 1;
    }
  }else{
    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  }
  if( p1<0 ){
    p1 += len;
    if( p1<0 ){
      p2 += p1;
      if( p2<0 ) p2 = 0;
      p1 = 0;
    }
  }else if( p1>0 ){
    p1--;
  }else if( p2>0 ){
    p2--;
  }
  if( negP2 ){
    p1 -= p2;
    if( p1<0 ){
      p2 += p1;
      p1 = 0;
    }
  }
  assert( p1>=0 && p2>=0 );
  if( p1+p2>len ){
    p2 = len-p1;
    if( p2<0 ) p2 = 0;
  }
  if( p0type!=SQLITE_BLOB ){
    while( *z && p1 ){
      SQLITE_SKIP_UTF8(z);
      p1--;
    }
    for(z2=z; *z2 && p2; p2--){
      SQLITE_SKIP_UTF8(z2);
    }
    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  }else{
    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  }
}

/*
** Implementation of the round() function
*/
#ifndef SQLITE_OMIT_FLOATING_POINT
static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  int n = 0;
  double r;
  char *zBuf;
  assert( argc==1 || argc==2 );
  if( argc==2 ){
    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
    n = sqlite3_value_int(argv[1]);
    if( n>30 ) n = 30;
    if( n<0 ) n = 0;
  }
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  r = sqlite3_value_double(argv[0]);
  zBuf = sqlite3_mprintf("%.*f",n,r);
  if( zBuf==0 ){
    sqlite3_result_error_nomem(context);
  }else{
    sqlite3AtoF(zBuf, &r);
    sqlite3_free(zBuf);
    sqlite3_result_double(context, r);
  }
}
#endif

/*
** Allocate nByte bytes of space using sqlite3_malloc(). If the
** allocation fails, call sqlite3_result_error_nomem() to notify
** the database handle that malloc() has failed and return NULL.
** If nByte is larger than the maximum string or blob length, then
** raise an SQLITE_TOOBIG exception and return NULL.
*/
static void *contextMalloc(sqlite3_context *context, i64 nByte){
  char *z;
  sqlite3 *db = sqlite3_context_db_handle(context);
  assert( nByte>0 );
  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite3_result_error_toobig(context);
    z = 0;
  }else{
    z = sqlite3Malloc((int)nByte);
    if( !z ){
      sqlite3_result_error_nomem(context);
    }
  }
  return z;
}

/*
** Implementation of the upper() and lower() SQL functions.
*/
static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  char *z1;
  const char *z2;
  int i, n;
  UNUSED_PARAMETER(argc);
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = (char)sqlite3Toupper(z1[i]);
      }
      sqlite3_result_text(context, z1, -1, sqlite3_free);
    }
  }
}
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  u8 *z1;
  const char *z2;
  int i, n;
  UNUSED_PARAMETER(argc);
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = sqlite3Tolower(z1[i]);
      }
      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
    }
  }
}

/*
** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
** All three do the same thing.  They return the first non-NULL
** argument.
*/
static void ifnullFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
      sqlite3_result_value(context, argv[i]);
      break;
    }
  }
}

/*
** Implementation of random().  Return a random integer.  
*/
static void randomFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  sqlite_int64 r;
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_randomness(sizeof(r), &r);
  if( r<0 ){
    /* We need to prevent a random number of 0x8000000000000000 
    ** (or -9223372036854775808) since when you do abs() of that
    ** number of you get the same value back again.  To do this
    ** in a way that is testable, mask the sign bit off of negative
    ** values, resulting in a positive value.  Then take the 
    ** 2s complement of that positive value.  The end result can
    ** therefore be no less than -9223372036854775807.
    */
    r = -(r ^ (((sqlite3_int64)1)<<63));
  }
  sqlite3_result_int64(context, r);
}

/*
** Implementation of randomblob(N).  Return a random blob
** that is N bytes long.
*/
static void randomBlob(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int n;
  unsigned char *p;
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  n = sqlite3_value_int(argv[0]);
  if( n<1 ){
    n = 1;
  }
  p = contextMalloc(context, n);
  if( p ){
    sqlite3_randomness(n, p);
    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  }
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite3_last_insert_rowid() API function.
*/
static void last_insert_rowid(
  sqlite3_context *context, 
  int NotUsed, 
  sqlite3_value **NotUsed2
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
}

/*
** Implementation of the changes() SQL function.  The return value is the
** same as the sqlite3_changes() API function.
*/
static void changes(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_result_int(context, sqlite3_changes(db));
}

/*
** Implementation of the total_changes() SQL function.  The return value is
** the same as the sqlite3_total_changes() API function.
*/
static void total_changes(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_result_int(context, sqlite3_total_changes(db));
}

/*
** A structure defining how to do GLOB-style comparisons.
*/
struct compareInfo {
  u8 matchAll;
  u8 matchOne;
  u8 matchSet;
  u8 noCase;
};

/*
** For LIKE and GLOB matching on EBCDIC machines, assume that every
** character is exactly one byte in size.  Also, all characters are
** able to participate in upper-case-to-lower-case mappings in EBCDIC
** whereas only characters less than 0x80 do in ASCII.
*/
#if defined(SQLITE_EBCDIC)
# define sqlite3Utf8Read(A,C)    (*(A++))
# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
#else
# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
#endif

static const struct compareInfo globInfo = { '*', '?', '[', 0 };
/* The correct SQL-92 behavior is for the LIKE operator to ignore
** case.  Thus  'a' LIKE 'A' would be true. */
static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
** is case sensitive causing 'a' LIKE 'A' to be false */
static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };

/*
** Compare two UTF-8 strings for equality where the first string can
** potentially be a "glob" expression.  Return true (1) if they
** are the same and false (0) if they are different.
**
** Globbing rules:
**
**      '*'       Matches any sequence of zero or more characters.
**
**      '?'       Matches exactly one character.
**
**     [...]      Matches one character from the enclosed list of
**                characters.
**
**     [^...]     Matches one character not in the enclosed list.
**
** With the [...] and [^...] matching, a ']' character can be included
** in the list by making it the first character after '[' or '^'.  A
** range of characters can be specified using '-'.  Example:
** "[a-z]" matches any single lower-case letter.  To match a '-', make
** it the last character in the list.
**
** This routine is usually quick, but can be N**2 in the worst case.
**
** Hints: to match '*' or '?', put them in "[]".  Like this:
**
**         abc[*]xyz        Matches "abc*xyz" only
*/
static int patternCompare(
  const u8 *zPattern,              /* The glob pattern */
  const u8 *zString,               /* The string to compare against the glob */
  const struct compareInfo *pInfo, /* Information about how to do the compare */
  const int esc                    /* The escape character */
){
  int c, c2;
  int invert;
  int seen;
  u8 matchOne = pInfo->matchOne;
  u8 matchAll = pInfo->matchAll;
  u8 matchSet = pInfo->matchSet;
  u8 noCase = pInfo->noCase; 
  int prevEscape = 0;     /* True if the previous character was 'escape' */

  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
    if( !prevEscape && c==matchAll ){
      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
               || c == matchOne ){
        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
          return 0;
        }
      }
      if( c==0 ){
        return 1;
      }else if( c==esc ){
        c = sqlite3Utf8Read(zPattern, &zPattern);
        if( c==0 ){
          return 0;
        }
      }else if( c==matchSet ){
        assert( esc==0 );         /* This is GLOB, not LIKE */
        assert( matchSet<0x80 );  /* '[' is a single-byte character */
        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
          SQLITE_SKIP_UTF8(zString);
        }
        return *zString!=0;
      }
      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
        if( noCase ){
          GlogUpperToLower(c2);
          GlogUpperToLower(c);
          while( c2 != 0 && c2 != c ){
            c2 = sqlite3Utf8Read(zString, &zString);
            GlogUpperToLower(c2);
          }
        }else{
          while( c2 != 0 && c2 != c ){
            c2 = sqlite3Utf8Read(zString, &zString);
          }
        }
        if( c2==0 ) return 0;
        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
      }
      return 0;
    }else if( !prevEscape && c==matchOne ){
      if( sqlite3Utf8Read(zString, &zString)==0 ){
        return 0;
      }
    }else if( c==matchSet ){
      int prior_c = 0;
      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
      seen = 0;
      invert = 0;
      c = sqlite3Utf8Read(zString, &zString);
      if( c==0 ) return 0;
      c2 = sqlite3Utf8Read(zPattern, &zPattern);
      if( c2=='^' ){
        invert = 1;
        c2 = sqlite3Utf8Read(zPattern, &zPattern);
      }
      if( c2==']' ){
        if( c==']' ) seen = 1;
        c2 = sqlite3Utf8Read(zPattern, &zPattern);
      }
      while( c2 && c2!=']' ){
        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
          c2 = sqlite3Utf8Read(zPattern, &zPattern);
          if( c>=prior_c && c<=c2 ) seen = 1;
          prior_c = 0;
        }else{
          if( c==c2 ){
            seen = 1;
          }
          prior_c = c2;
        }
        c2 = sqlite3Utf8Read(zPattern, &zPattern);
      }
      if( c2==0 || (seen ^ invert)==0 ){
        return 0;
      }
    }else if( esc==c && !prevEscape ){
      prevEscape = 1;
    }else{
      c2 = sqlite3Utf8Read(zString, &zString);
      if( noCase ){
        GlogUpperToLower(c);
        GlogUpperToLower(c2);
      }
      if( c!=c2 ){
        return 0;
      }
      prevEscape = 0;
    }
  }
  return *zString==0;
}

/*
** Count the number of times that the LIKE operator (or GLOB which is
** just a variation of LIKE) gets called.  This is used for testing
** only.
*/
#ifdef SQLITE_TEST
int sqlite3_like_count = 0;
#endif


/*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A LIKE B
**
** is implemented as like(B,A).
**
** This same function (with a different compareInfo structure) computes
** the GLOB operator.
*/
static void likeFunc(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  const unsigned char *zA, *zB;
  int escape = 0;
  int nPat;
  sqlite3 *db = sqlite3_context_db_handle(context);

  zB = sqlite3_value_text(argv[0]);
  zA = sqlite3_value_text(argv[1]);

  /* Limit the length of the LIKE or GLOB pattern to avoid problems
  ** of deep recursion and N*N behavior in patternCompare().
  */
  nPat = sqlite3_value_bytes(argv[0]);
  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
    return;
  }
  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */

  if( argc==3 ){
    /* The escape character string must consist of a single UTF-8 character.
    ** Otherwise, return an error.
    */
    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
    if( zEsc==0 ) return;
    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
      sqlite3_result_error(context, 
          "ESCAPE expression must be a single character", -1);
      return;
    }
    escape = sqlite3Utf8Read(zEsc, &zEsc);
  }
  if( zA && zB ){
    struct compareInfo *pInfo = sqlite3_user_data(context);
#ifdef SQLITE_TEST
    sqlite3_like_count++;
#endif
    
    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  }
}

/*
** Implementation of the NULLIF(x,y) function.  The result is the first
** argument if the arguments are different.  The result is NULL if the
** arguments are equal to each other.
*/
static void nullifFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  UNUSED_PARAMETER(NotUsed);
  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
    sqlite3_result_value(context, argv[0]);
  }
}

/*
** Implementation of the sqlite_version() function.  The result is the version
** of the SQLite library that is running.
*/
static void versionFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
}

/*
** Implementation of the sqlite_source_id() function. The result is a string
** that identifies the particular version of the source code used to build
** SQLite.
*/
static void sourceidFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
}

/* Array for converting from half-bytes (nybbles) into ASCII hex
** digits. */
static const char hexdigits[] = {
  '0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
};

/*
** EXPERIMENTAL - This is not an official function.  The interface may
** change.  This function may disappear.  Do not write code that depends
** on this function.
**
** Implementation of the QUOTE() function.  This function takes a single
** argument.  If the argument is numeric, the return value is the same as
** the argument.  If the argument is NULL, the return value is the string
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_INTEGER:
    case SQLITE_FLOAT: {
      sqlite3_result_value(context, argv[0]);
      break;
    }
    case SQLITE_BLOB: {
      char *zText = 0;
      char const *zBlob = sqlite3_value_blob(argv[0]);
      int nBlob = sqlite3_value_bytes(argv[0]);
      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
      if( zText ){
        int i;
        for(i=0; i<nBlob; i++){
          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
        }
        zText[(nBlob*2)+2] = '\'';
        zText[(nBlob*2)+3] = '\0';
        zText[0] = 'X';
        zText[1] = '\'';
        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
        sqlite3_free(zText);
      }
      break;
    }
    case SQLITE_TEXT: {
      int i,j;
      u64 n;
      const unsigned char *zArg = sqlite3_value_text(argv[0]);
      char *z;

      if( zArg==0 ) return;
      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
      if( z ){
        z[0] = '\'';
        for(i=0, j=1; zArg[i]; i++){
          z[j++] = zArg[i];
          if( zArg[i]=='\'' ){
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite3_result_text(context, z, j, sqlite3_free);
      }
      break;
    }
    default: {
      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
      break;
    }
  }
}

/*
** The hex() function.  Interpret the argument as a blob.  Return
** a hexadecimal rendering as text.
*/
static void hexFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int i, n;
  const unsigned char *pBlob;
  char *zHex, *z;
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  pBlob = sqlite3_value_blob(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  if( zHex ){
    for(i=0; i<n; i++, pBlob++){
      unsigned char c = *pBlob;
      *(z++) = hexdigits[(c>>4)&0xf];
      *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  }
}

/*
** The zeroblob(N) function returns a zero-filled blob of size N bytes.
*/
static void zeroblobFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  i64 n;
  sqlite3 *db = sqlite3_context_db_handle(context);
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  n = sqlite3_value_int64(argv[0]);
  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite3_result_error_toobig(context);
  }else{
    sqlite3_result_zeroblob(context, (int)n);
  }
}

/*
** The replace() function.  Three arguments are all strings: call
** them A, B, and C. The result is also a string which is derived
** from A by replacing every occurance of B with C.  The match
** must be exact.  Collating sequences are not used.
*/
static void replaceFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const unsigned char *zStr;        /* The input string A */
  const unsigned char *zPattern;    /* The pattern string B */
  const unsigned char *zRep;        /* The replacement string C */
  unsigned char *zOut;              /* The output */
  int nStr;                /* Size of zStr */
  int nPattern;            /* Size of zPattern */
  int nRep;                /* Size of zRep */
  i64 nOut;                /* Maximum size of zOut */
  int loopLimit;           /* Last zStr[] that might match zPattern[] */
  int i, j;                /* Loop counters */

  assert( argc==3 );
  UNUSED_PARAMETER(argc);
  zStr = sqlite3_value_text(argv[0]);
  if( zStr==0 ) return;
  nStr = sqlite3_value_bytes(argv[0]);
  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
  zPattern = sqlite3_value_text(argv[1]);
  if( zPattern==0 ){
    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
            || sqlite3_context_db_handle(context)->mallocFailed );
    return;
  }
  if( zPattern[0]==0 ){
    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
    sqlite3_result_value(context, argv[0]);
    return;
  }
  nPattern = sqlite3_value_bytes(argv[1]);
  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
  zRep = sqlite3_value_text(argv[2]);
  if( zRep==0 ) return;
  nRep = sqlite3_value_bytes(argv[2]);
  assert( zRep==sqlite3_value_text(argv[2]) );
  nOut = nStr + 1;
  assert( nOut<SQLITE_MAX_LENGTH );
  zOut = contextMalloc(context, (i64)nOut);
  if( zOut==0 ){
    return;
  }
  loopLimit = nStr - nPattern;  
  for(i=j=0; i<=loopLimit; i++){
    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
      zOut[j++] = zStr[i];
    }else{
      u8 *zOld;
      sqlite3 *db = sqlite3_context_db_handle(context);
      nOut += nRep - nPattern;
      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
        sqlite3_result_error_toobig(context);
        sqlite3DbFree(db, zOut);
        return;
      }
      zOld = zOut;
      zOut = sqlite3_realloc(zOut, (int)nOut);
      if( zOut==0 ){
        sqlite3_result_error_nomem(context);
        sqlite3DbFree(db, zOld);
        return;
      }
      memcpy(&zOut[j], zRep, nRep);
      j += nRep;
      i += nPattern-1;
    }
  }
  assert( j+nStr-i+1==nOut );
  memcpy(&zOut[j], &zStr[i], nStr-i);
  j += nStr - i;
  assert( j<=nOut );
  zOut[j] = 0;
  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
}

/*
** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
*/
static void trimFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const unsigned char *zIn;         /* Input string */
  const unsigned char *zCharSet;    /* Set of characters to trim */
  int nIn;                          /* Number of bytes in input */
  int flags;                        /* 1: trimleft  2: trimright  3: trim */
  int i;                            /* Loop counter */
  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
  int nChar;                        /* Number of characters in zCharSet */

  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
    return;
  }
  zIn = sqlite3_value_text(argv[0]);
  if( zIn==0 ) return;
  nIn = sqlite3_value_bytes(argv[0]);
  assert( zIn==sqlite3_value_text(argv[0]) );
  if( argc==1 ){
    static const unsigned char lenOne[] = { 1 };
    static unsigned char * const azOne[] = { (u8*)" " };
    nChar = 1;
    aLen = (u8*)lenOne;
    azChar = (unsigned char **)azOne;
    zCharSet = 0;
  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
    return;
  }else{
    const unsigned char *z;
    for(z=zCharSet, nChar=0; *z; nChar++){
      SQLITE_SKIP_UTF8(z);
    }
    if( nChar>0 ){
      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
      if( azChar==0 ){
        return;
      }
      aLen = (unsigned char*)&azChar[nChar];
      for(z=zCharSet, nChar=0; *z; nChar++){
        azChar[nChar] = (unsigned char *)z;
        SQLITE_SKIP_UTF8(z);
        aLen[nChar] = (u8)(z - azChar[nChar]);
      }
    }
  }
  if( nChar>0 ){
    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
    if( flags & 1 ){
      while( nIn>0 ){
        int len = 0;
        for(i=0; i<nChar; i++){
          len = aLen[i];
          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
        }
        if( i>=nChar ) break;
        zIn += len;
        nIn -= len;
      }
    }
    if( flags & 2 ){
      while( nIn>0 ){
        int len = 0;
        for(i=0; i<nChar; i++){
          len = aLen[i];
          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
        }
        if( i>=nChar ) break;
        nIn -= len;
      }
    }
    if( zCharSet ){
      sqlite3_free(azChar);
    }
  }
  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
}


#ifdef SQLITE_SOUNDEX
/*
** Compute the soundex encoding of a word.
*/
static void soundexFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  char zResult[8];
  const u8 *zIn;
  int i, j;
  static const unsigned char iCode[] = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  };
  assert( argc==1 );
  zIn = (u8*)sqlite3_value_text(argv[0]);
  if( zIn==0 ) zIn = (u8*)"";
  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  if( zIn[i] ){
    u8 prevcode = iCode[zIn[i]&0x7f];
    zResult[0] = sqlite3Toupper(zIn[i]);
    for(j=1; j<4 && zIn[i]; i++){
      int code = iCode[zIn[i]&0x7f];
      if( code>0 ){
        if( code!=prevcode ){
          prevcode = code;
          zResult[j++] = code + '0';
        }
      }else{
        prevcode = 0;
      }
    }
    while( j<4 ){
      zResult[j++] = '0';
    }
    zResult[j] = 0;
    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  }else{
    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  }
}
#endif

#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** A function that loads a shared-library extension then returns NULL.
*/
static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  const char *zProc;
  sqlite3 *db = sqlite3_context_db_handle(context);
  char *zErrMsg = 0;

  if( argc==2 ){
    zProc = (const char *)sqlite3_value_text(argv[1]);
  }else{
    zProc = 0;
  }
  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
    sqlite3_result_error(context, zErrMsg, -1);
    sqlite3_free(zErrMsg);
  }
}
#endif


/*
** An instance of the following structure holds the context of a
** sum() or avg() aggregate computation.
*/
typedef struct SumCtx SumCtx;
struct SumCtx {
  double rSum;      /* Floating point sum */
  i64 iSum;         /* Integer sum */   
  i64 cnt;          /* Number of elements summed */
  u8 overflow;      /* True if integer overflow seen */
  u8 approx;        /* True if non-integer value was input to the sum */
};

/*
** Routines used to compute the sum, average, and total.
**
** The SUM() function follows the (broken) SQL standard which means
** that it returns NULL if it sums over no inputs.  TOTAL returns
** 0.0 in that case.  In addition, TOTAL always returns a float where
** SUM might return an integer if it never encounters a floating point
** value.  TOTAL never fails, but SUM might through an exception if
** it overflows an integer.
*/
static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  SumCtx *p;
  int type;
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  p = sqlite3_aggregate_context(context, sizeof(*p));
  type = sqlite3_value_numeric_type(argv[0]);
  if( p && type!=SQLITE_NULL ){
    p->cnt++;
    if( type==SQLITE_INTEGER ){
      i64 v = sqlite3_value_int64(argv[0]);
      p->rSum += v;
      if( (p->approx|p->overflow)==0 ){
        i64 iNewSum = p->iSum + v;
        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
        int s2 = (int)(v       >> (sizeof(i64)*8-1));
        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
        p->iSum = iNewSum;
      }
    }else{
      p->rSum += sqlite3_value_double(argv[0]);
      p->approx = 1;
    }
  }
}
static void sumFinalize(sqlite3_context *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, 0);
  if( p && p->cnt>0 ){
    if( p->overflow ){
      sqlite3_result_error(context,"integer overflow",-1);
    }else if( p->approx ){
      sqlite3_result_double(context, p->rSum);
    }else{
      sqlite3_result_int64(context, p->iSum);
    }
  }
}
static void avgFinalize(sqlite3_context *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, 0);
  if( p && p->cnt>0 ){
    sqlite3_result_double(context, p->rSum/(double)p->cnt);
  }
}
static void totalFinalize(sqlite3_context *context){
  SumCtx *p;
  p = sqlite3_aggregate_context(context, 0);
  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  sqlite3_result_double(context, p ? p->rSum : (double)0);
}

/*
** The following structure keeps track of state information for the
** count() aggregate function.
*/
typedef struct CountCtx CountCtx;
struct CountCtx {
  i64 n;
};

/*
** Routines to implement the count() aggregate function.
*/
static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
    p->n++;
  }

#ifndef SQLITE_OMIT_DEPRECATED
  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
  ** sure it still operates correctly, verify that its count agrees with our 
  ** internal count when using count(*) and when the total count can be
  ** expressed as a 32-bit integer. */
  assert( argc==1 || p==0 || p->n>0x7fffffff
          || p->n==sqlite3_aggregate_count(context) );
#endif
}   
static void countFinalize(sqlite3_context *context){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, 0);
  sqlite3_result_int64(context, p ? p->n : 0);
}

/*
** Routines to implement min() and max() aggregate functions.
*/
static void minmaxStep(
  sqlite3_context *context, 
  int NotUsed, 
  sqlite3_value **argv
){
  Mem *pArg  = (Mem *)argv[0];
  Mem *pBest;
  UNUSED_PARAMETER(NotUsed);

  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  if( !pBest ) return;

  if( pBest->flags ){
    int max;
    int cmp;
    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
    /* This step function is used for both the min() and max() aggregates,
    ** the only difference between the two being that the sense of the
    ** comparison is inverted. For the max() aggregate, the
    ** sqlite3_user_data() function returns (void *)-1. For min() it
    ** returns (void *)db, where db is the sqlite3* database pointer.
    ** Therefore the next statement sets variable 'max' to 1 for the max()
    ** aggregate, or 0 for min().
    */
    max = sqlite3_user_data(context)!=0;
    cmp = sqlite3MemCompare(pBest, pArg, pColl);
    if( (max && cmp<0) || (!max && cmp>0) ){
      sqlite3VdbeMemCopy(pBest, pArg);
    }
  }else{
    sqlite3VdbeMemCopy(pBest, pArg);
  }
}
static void minMaxFinalize(sqlite3_context *context){
  sqlite3_value *pRes;
  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  if( pRes ){
    if( ALWAYS(pRes->flags) ){
      sqlite3_result_value(context, pRes);
    }
    sqlite3VdbeMemRelease(pRes);
  }
}

/*
** group_concat(EXPR, ?SEPARATOR?)
*/
static void groupConcatStep(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zVal;
  StrAccum *pAccum;
  const char *zSep;
  int nVal, nSep;
  assert( argc==1 || argc==2 );
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));

  if( pAccum ){
    sqlite3 *db = sqlite3_context_db_handle(context);
    int firstTerm = pAccum->useMalloc==0;
    pAccum->useMalloc = 1;
    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
    if( !firstTerm ){
      if( argc==2 ){
        zSep = (char*)sqlite3_value_text(argv[1]);
        nSep = sqlite3_value_bytes(argv[1]);
      }else{
        zSep = ",";
        nSep = 1;
      }
      sqlite3StrAccumAppend(pAccum, zSep, nSep);
    }
    zVal = (char*)sqlite3_value_text(argv[0]);
    nVal = sqlite3_value_bytes(argv[0]);
    sqlite3StrAccumAppend(pAccum, zVal, nVal);
  }
}
static void groupConcatFinalize(sqlite3_context *context){
  StrAccum *pAccum;
  pAccum = sqlite3_aggregate_context(context, 0);
  if( pAccum ){
    if( pAccum->tooBig ){
      sqlite3_result_error_toobig(context);
    }else if( pAccum->mallocFailed ){
      sqlite3_result_error_nomem(context);
    }else{    
      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
                          sqlite3_free);
    }
  }
}

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
#ifndef SQLITE_OMIT_ALTERTABLE
  sqlite3AlterFunctions(db);
#endif
  if( !db->mallocFailed ){
    int rc = sqlite3_overload_function(db, "MATCH", 2);
    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
    if( rc==SQLITE_NOMEM ){
      db->mallocFailed = 1;
    }
  }
}

/*
** Set the LIKEOPT flag on the 2-argument function with the given name.
*/
static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  FuncDef *pDef;
  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
                             2, SQLITE_UTF8, 0);
  if( ALWAYS(pDef) ){
    pDef->flags = flagVal;
  }
}

/*
** Register the built-in LIKE and GLOB functions.  The caseSensitive
** parameter determines whether or not the LIKE operator is case
** sensitive.  GLOB is always case sensitive.
*/
void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  struct compareInfo *pInfo;
  if( caseSensitive ){
    pInfo = (struct compareInfo*)&likeInfoAlt;
  }else{
    pInfo = (struct compareInfo*)&likeInfoNorm;
  }
  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
      (struct compareInfo*)&globInfo, likeFunc, 0,0);
  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  setLikeOptFlag(db, "like", 
      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
}

/*
** pExpr points to an expression which implements a function.  If
** it is appropriate to apply the LIKE optimization to that function
** then set aWc[0] through aWc[2] to the wildcard characters and
** return TRUE.  If the function is not a LIKE-style function then
** return FALSE.
*/
int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  FuncDef *pDef;
  if( pExpr->op!=TK_FUNCTION 
   || !pExpr->x.pList 
   || pExpr->x.pList->nExpr!=2
  ){
    return 0;
  }
  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
                             sqlite3Strlen30(pExpr->u.zToken),
                             2, SQLITE_UTF8, 0);
  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
    return 0;
  }

  /* The memcpy() statement assumes that the wildcard characters are
  ** the first three statements in the compareInfo structure.  The
  ** asserts() that follow verify that assumption
  */
  memcpy(aWc, pDef->pUserData, 3);
  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  return 1;
}

/*
** All all of the FuncDef structures in the aBuiltinFunc[] array above
** to the global function hash table.  This occurs at start-time (as
** a consequence of calling sqlite3_initialize()).
**
** After this routine runs
*/
void sqlite3RegisterGlobalFunctions(void){
  /*
  ** The following array holds FuncDef structures for all of the functions
  ** defined in this file.
  **
  ** The array cannot be constant since changes are made to the
  ** FuncDef.pHash elements at start-time.  The elements of this array
  ** are read-only after initialization is complete.
  */
  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
    FUNCTION(trim,               1, 3, 0, trimFunc         ),
    FUNCTION(trim,               2, 3, 0, trimFunc         ),
    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
    FUNCTION(min,                0, 0, 1, 0                ),
    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
    FUNCTION(max,                0, 1, 1, 0                ),
    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
    FUNCTION(length,             1, 0, 0, lengthFunc       ),
    FUNCTION(substr,             2, 0, 0, substrFunc       ),
    FUNCTION(substr,             3, 0, 0, substrFunc       ),
    FUNCTION(abs,                1, 0, 0, absFunc          ),
#ifndef SQLITE_OMIT_FLOATING_POINT
    FUNCTION(round,              1, 0, 0, roundFunc        ),
    FUNCTION(round,              2, 0, 0, roundFunc        ),
#endif
    FUNCTION(upper,              1, 0, 0, upperFunc        ),
    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
    FUNCTION(coalesce,           1, 0, 0, 0                ),
    FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
    FUNCTION(coalesce,           0, 0, 0, 0                ),
    FUNCTION(hex,                1, 0, 0, hexFunc          ),
    FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
    FUNCTION(random,             0, 0, 0, randomFunc       ),
    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
    FUNCTION(changes,            0, 0, 0, changes          ),
    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
  #ifdef SQLITE_SOUNDEX
    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
  #endif
  #ifndef SQLITE_OMIT_LOAD_EXTENSION
    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
  #endif
    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
  
    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  #ifdef SQLITE_CASE_SENSITIVE_LIKE
    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  #else
    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  #endif
  };

  int i;
  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);

  for(i=0; i<ArraySize(aBuiltinFunc); i++){
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
  }
  sqlite3RegisterDateTimeFunctions();
}

Added src/global.c.





























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/*
** 2008 June 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains definitions of global variables and contants.
*/
#include "sqliteInt.h"


/* An array to map all upper-case characters into their corresponding
** lower-case character. 
**
** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
** handle case conversions for the UTF character set since the tables
** involved are nearly as big or bigger than SQLite itself.
*/
const unsigned char sqlite3UpperToLower[] = {
#ifdef SQLITE_ASCII
      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
    252,253,254,255
#endif
#ifdef SQLITE_EBCDIC
      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
#endif
};

/*
** The following 256 byte lookup table is used to support SQLites built-in
** equivalents to the following standard library functions:
**
**   isspace()                        0x01
**   isalpha()                        0x02
**   isdigit()                        0x04
**   isalnum()                        0x06
**   isxdigit()                       0x08
**   toupper()                        0x20
**
** Bit 0x20 is set if the mapped character requires translation to upper
** case. i.e. if the character is a lower-case ASCII character.
** If x is a lower-case ASCII character, then its upper-case equivalent
** is (x - 0x20). Therefore toupper() can be implemented as:
**
**   (x & ~(map[x]&0x20))
**
** Standard function tolower() is implemented using the sqlite3UpperToLower[]
** array. tolower() is used more often than toupper() by SQLite.
**
** SQLite's versions are identical to the standard versions assuming a
** locale of "C". They are implemented as macros in sqliteInt.h.
*/
#ifdef SQLITE_ASCII
const unsigned char sqlite3CtypeMap[256] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
  0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */

  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 58..5f    XYZ[\]^_ */
  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */

  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 80..87    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 88..8f    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 90..97    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 98..9f    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* a0..a7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* a8..af    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* b0..b7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* b8..bf    ........ */

  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* c0..c7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* c8..cf    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* d0..d7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* d8..df    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* e0..e7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* e8..ef    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* f0..f7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00   /* f8..ff    ........ */
};
#endif



/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   1,                         /* bCoreMutex */
   SQLITE_THREADSAFE==1,      /* bFullMutex */
   0x7ffffffe,                /* mxStrlen */
   100,                       /* szLookaside */
   500,                       /* nLookaside */
   {0,0,0,0,0,0,0,0},         /* m */
   {0,0,0,0,0,0,0,0,0},       /* mutex */
   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
   (void*)0,                  /* pHeap */
   0,                         /* nHeap */
   0, 0,                      /* mnHeap, mxHeap */
   (void*)0,                  /* pScratch */
   0,                         /* szScratch */
   0,                         /* nScratch */
   (void*)0,                  /* pPage */
   0,                         /* szPage */
   0,                         /* nPage */
   0,                         /* mxParserStack */
   0,                         /* sharedCacheEnabled */
   /* All the rest should always be initialized to zero */
   0,                         /* isInit */
   0,                         /* inProgress */
   0,                         /* isMutexInit */
   0,                         /* isMallocInit */
   0,                         /* isPCacheInit */
   0,                         /* pInitMutex */
   0,                         /* nRefInitMutex */
};


/*
** Hash table for global functions - functions common to all
** database connections.  After initialization, this table is
** read-only.
*/
SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;

/*
** The value of the "pending" byte must be 0x40000000 (1 byte past the
** 1-gibabyte boundary) in a compatible database.  SQLite never uses
** the database page that contains the pending byte.  It never attempts
** to read or write that page.  The pending byte page is set assign
** for use by the VFS layers as space for managing file locks.
**
** During testing, it is often desirable to move the pending byte to
** a different position in the file.  This allows code that has to
** deal with the pending byte to run on files that are much smaller
** than 1 GiB.  The sqlite3_test_control() interface can be used to
** move the pending byte.
**
** IMPORTANT:  Changing the pending byte to any value other than
** 0x40000000 results in an incompatible database file format!
** Changing the pending byte during operating results in undefined
** and dileterious behavior.
*/
int sqlite3PendingByte = 0x40000000;

Added src/hash.c.















































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables
** used in SQLite.
**
** $Id: hash.c,v 1.38 2009/05/09 23:29:12 drh Exp $
*/
#include "sqliteInt.h"
#include <assert.h>

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
void sqlite3HashInit(Hash *pNew){
  assert( pNew!=0 );
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite3HashClear(Hash *pH){
  HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  sqlite3_free(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    HashElem *next_elem = elem->next;
    sqlite3_free(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** The hashing function.
*/
static unsigned int strHash(const char *z, int nKey){
  int h = 0;
  assert( nKey>=0 );
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
    nKey--;
  }
  return h;
}


/* Link pNew element into the hash table pH.  If pEntry!=0 then also
** insert pNew into the pEntry hash bucket.
*/
static void insertElement(
  Hash *pH,              /* The complete hash table */
  struct _ht *pEntry,    /* The entry into which pNew is inserted */
  HashElem *pNew         /* The element to be inserted */
){
  HashElem *pHead;       /* First element already in pEntry */
  if( pEntry ){
    pHead = pEntry->count ? pEntry->chain : 0;
    pEntry->count++;
    pEntry->chain = pNew;
  }else{
    pHead = 0;
  }
  if( pHead ){
    pNew->next = pHead;
    pNew->prev = pHead->prev;
    if( pHead->prev ){ pHead->prev->next = pNew; }
    else             { pH->first = pNew; }
    pHead->prev = pNew;
  }else{
    pNew->next = pH->first;
    if( pH->first ){ pH->first->prev = pNew; }
    pNew->prev = 0;
    pH->first = pNew;
  }
}


/* Resize the hash table so that it cantains "new_size" buckets.
**
** The hash table might fail to resize if sqlite3_malloc() fails or
** if the new size is the same as the prior size.
** Return TRUE if the resize occurs and false if not.
*/
static int rehash(Hash *pH, unsigned int new_size){
  struct _ht *new_ht;            /* The new hash table */
  HashElem *elem, *next_elem;    /* For looping over existing elements */

#if SQLITE_MALLOC_SOFT_LIMIT>0
  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  }
  if( new_size==pH->htsize ) return 0;
#endif

  /* The inability to allocates space for a larger hash table is
  ** a performance hit but it is not a fatal error.  So mark the
  ** allocation as a benign.
  */
  sqlite3BeginBenignMalloc();
  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  sqlite3EndBenignMalloc();

  if( new_ht==0 ) return 0;
  sqlite3_free(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
}

/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static HashElem *findElementGivenHash(
  const Hash *pH,     /* The pH to be searched */
  const char *pKey,   /* The key we are searching for */
  int nKey,           /* Bytes in key (not counting zero terminator) */
  unsigned int h      /* The hash for this key. */
){
  HashElem *elem;                /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */

  if( pH->ht ){
    struct _ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
  }else{
    elem = pH->first;
    count = pH->count;
  }
  while( count-- && ALWAYS(elem) ){
    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
      return elem;
    }
    elem = elem->next;
  }
  return 0;
}

/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
  Hash *pH,         /* The pH containing "elem" */
  HashElem* elem,   /* The element to be removed from the pH */
  unsigned int h    /* Hash value for the element */
){
  struct _ht *pEntry;
  if( elem->prev ){
    elem->prev->next = elem->next; 
  }else{
    pH->first = elem->next;
  }
  if( elem->next ){
    elem->next->prev = elem->prev;
  }
  if( pH->ht ){
    pEntry = &pH->ht[h];
    if( pEntry->chain==elem ){
      pEntry->chain = elem->next;
    }
    pEntry->count--;
    assert( pEntry->count>=0 );
  }
  sqlite3_free( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    sqlite3HashClear(pH);
  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  HashElem *elem;    /* The element that matches key */
  unsigned int h;    /* A hash on key */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->ht ){
    h = strHash(pKey, nKey) % pH->htsize;
  }else{
    h = 0;
  }
  elem = findElementGivenHash(pH, pKey, nKey, h);
  return elem ? elem->data : 0;
}

/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created and NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  unsigned int h;       /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->htsize ){
    h = strHash(pKey, nKey) % pH->htsize;
  }else{
    h = 0;
  }
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
      elem->pKey = pKey;
      assert(nKey==elem->nKey);
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  new_elem->pKey = pKey;
  new_elem->nKey = nKey;
  new_elem->data = data;
  pH->count++;
  if( pH->count>=10 && pH->count > 2*pH->htsize ){
    if( rehash(pH, pH->count*2) ){
      assert( pH->htsize>0 );
      h = strHash(pKey, nKey) % pH->htsize;
    }
  }
  if( pH->ht ){
    insertElement(pH, &pH->ht[h], new_elem);
  }else{
    insertElement(pH, 0, new_elem);
  }
  return 0;
}

Added src/hash.h.





































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in SQLite.
**
** $Id: hash.h,v 1.15 2009/05/02 13:29:38 drh Exp $
*/
#ifndef _SQLITE_HASH_H_
#define _SQLITE_HASH_H_

/* Forward declarations of structures. */
typedef struct Hash Hash;
typedef struct HashElem HashElem;

/* A complete hash table is an instance of the following structure.
** The internals of this structure are intended to be opaque -- client
** code should not attempt to access or modify the fields of this structure
** directly.  Change this structure only by using the routines below.
** However, some of the "procedures" and "functions" for modifying and
** accessing this structure are really macros, so we can't really make
** this structure opaque.
**
** All elements of the hash table are on a single doubly-linked list.
** Hash.first points to the head of this list.
**
** There are Hash.htsize buckets.  Each bucket points to a spot in
** the global doubly-linked list.  The contents of the bucket are the
** element pointed to plus the next _ht.count-1 elements in the list.
**
** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
** by a linear search of the global list.  For small tables, the 
** Hash.ht table is never allocated because if there are few elements
** in the table, it is faster to do a linear search than to manage
** the hash table.
*/
struct Hash {
  unsigned int htsize;      /* Number of buckets in the hash table */
  unsigned int count;       /* Number of entries in this table */
  HashElem *first;          /* The first element of the array */
  struct _ht {              /* the hash table */
    int count;                 /* Number of entries with this hash */
    HashElem *chain;           /* Pointer to first entry with this hash */
  } *ht;
};

/* Each element in the hash table is an instance of the following 
** structure.  All elements are stored on a single doubly-linked list.
**
** Again, this structure is intended to be opaque, but it can't really
** be opaque because it is used by macros.
*/
struct HashElem {
  HashElem *next, *prev;       /* Next and previous elements in the table */
  void *data;                  /* Data associated with this element */
  const char *pKey; int nKey;  /* Key associated with this element */
};

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite3HashInit(Hash*);
void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
void sqlite3HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   Hash h;
**   HashElem *p;
**   ...
**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
**     SomeStructure *pData = sqliteHashData(p);
**     // do something with pData
**   }
*/
#define sqliteHashFirst(H)  ((H)->first)
#define sqliteHashNext(E)   ((E)->next)
#define sqliteHashData(E)   ((E)->data)
/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */

/*
** Number of entries in a hash table
*/
/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */

#endif /* _SQLITE_HASH_H_ */

Added src/hwtime.h.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
** 2008 May 27
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains inline asm code for retrieving "high-performance"
** counters for x86 class CPUs.
**
** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
*/
#ifndef _HWTIME_H_
#define _HWTIME_H_

/*
** The following routine only works on pentium-class (or newer) processors.
** It uses the RDTSC opcode to read the cycle count value out of the
** processor and returns that value.  This can be used for high-res
** profiling.
*/
#if (defined(__GNUC__) || defined(_MSC_VER)) && \
      (defined(i386) || defined(__i386__) || defined(_M_IX86))

  #if defined(__GNUC__)

  __inline__ sqlite_uint64 sqlite3Hwtime(void){
     unsigned int lo, hi;
     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
     return (sqlite_uint64)hi << 32 | lo;
  }

  #elif defined(_MSC_VER)

  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
     __asm {
        rdtsc
        ret       ; return value at EDX:EAX
     }
  }

  #endif

#elif (defined(__GNUC__) && defined(__x86_64__))

  __inline__ sqlite_uint64 sqlite3Hwtime(void){
      unsigned long val;
      __asm__ __volatile__ ("rdtsc" : "=A" (val));
      return val;
  }
 
#elif (defined(__GNUC__) && defined(__ppc__))

  __inline__ sqlite_uint64 sqlite3Hwtime(void){
      unsigned long long retval;
      unsigned long junk;
      __asm__ __volatile__ ("\n\
          1:      mftbu   %1\n\
                  mftb    %L0\n\
                  mftbu   %0\n\
                  cmpw    %0,%1\n\
                  bne     1b"
                  : "=r" (retval), "=r" (junk));
      return retval;
  }

#else

  #error Need implementation of sqlite3Hwtime() for your platform.

  /*
  ** To compile without implementing sqlite3Hwtime() for your platform,
  ** you can remove the above #error and use the following
  ** stub function.  You will lose timing support for many
  ** of the debugging and testing utilities, but it should at
  ** least compile and run.
  */
  sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }

#endif

#endif /* !defined(_HWTIME_H_) */

Added src/insert.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle INSERT statements in SQLite.
**
** $Id: insert.c,v 1.270 2009/07/24 17:58:53 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** Generate code that will open a table for reading.
*/
void sqlite3OpenTable(
  Parse *p,       /* Generate code into this VDBE */
  int iCur,       /* The cursor number of the table */
  int iDb,        /* The database index in sqlite3.aDb[] */
  Table *pTab,    /* The table to be opened */
  int opcode      /* OP_OpenRead or OP_OpenWrite */
){
  Vdbe *v;
  if( IsVirtual(pTab) ) return;
  v = sqlite3GetVdbe(p);
  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  VdbeComment((v, "%s", pTab->zName));
}

/*
** Return a pointer to the column affinity string associated with index
** pIdx. A column affinity string has one character for each column in 
** the table, according to the affinity of the column:
**
**  Character      Column affinity
**  ------------------------------
**  'a'            TEXT
**  'b'            NONE
**  'c'            NUMERIC
**  'd'            INTEGER
**  'e'            REAL
**
** An extra 'b' is appended to the end of the string to cover the
** rowid that appears as the last column in every index.
**
** Memory for the buffer containing the column index affinity string
** is managed along with the rest of the Index structure. It will be
** released when sqlite3DeleteIndex() is called.
*/
const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  if( !pIdx->zColAff ){
    /* The first time a column affinity string for a particular index is
    ** required, it is allocated and populated here. It is then stored as
    ** a member of the Index structure for subsequent use.
    **
    ** The column affinity string will eventually be deleted by
    ** sqliteDeleteIndex() when the Index structure itself is cleaned
    ** up.
    */
    int n;
    Table *pTab = pIdx->pTable;
    sqlite3 *db = sqlite3VdbeDb(v);
    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
    if( !pIdx->zColAff ){
      db->mallocFailed = 1;
      return 0;
    }
    for(n=0; n<pIdx->nColumn; n++){
      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
    }
    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
    pIdx->zColAff[n] = 0;
  }
 
  return pIdx->zColAff;
}

/*
** Set P4 of the most recently inserted opcode to a column affinity
** string for table pTab. A column affinity string has one character
** for each column indexed by the index, according to the affinity of the
** column:
**
**  Character      Column affinity
**  ------------------------------
**  'a'            TEXT
**  'b'            NONE
**  'c'            NUMERIC
**  'd'            INTEGER
**  'e'            REAL
*/
void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  /* The first time a column affinity string for a particular table
  ** is required, it is allocated and populated here. It is then 
  ** stored as a member of the Table structure for subsequent use.
  **
  ** The column affinity string will eventually be deleted by
  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  */
  if( !pTab->zColAff ){
    char *zColAff;
    int i;
    sqlite3 *db = sqlite3VdbeDb(v);

    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
    if( !zColAff ){
      db->mallocFailed = 1;
      return;
    }

    for(i=0; i<pTab->nCol; i++){
      zColAff[i] = pTab->aCol[i].affinity;
    }
    zColAff[pTab->nCol] = '\0';

    pTab->zColAff = zColAff;
  }

  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
}

/*
** Return non-zero if the table pTab in database iDb or any of its indices
** have been opened at any point in the VDBE program beginning at location
** iStartAddr throught the end of the program.  This is used to see if 
** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
** run without using temporary table for the results of the SELECT. 
*/
static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  Vdbe *v = sqlite3GetVdbe(p);
  int i;
  int iEnd = sqlite3VdbeCurrentAddr(v);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
#endif

  for(i=iStartAddr; i<iEnd; i++){
    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
    assert( pOp!=0 );
    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
      Index *pIndex;
      int tnum = pOp->p2;
      if( tnum==pTab->tnum ){
        return 1;
      }
      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
        if( tnum==pIndex->tnum ){
          return 1;
        }
      }
    }
#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
      assert( pOp->p4.pVtab!=0 );
      assert( pOp->p4type==P4_VTAB );
      return 1;
    }
#endif
  }
  return 0;
}

#ifndef SQLITE_OMIT_AUTOINCREMENT
/*
** Locate or create an AutoincInfo structure associated with table pTab
** which is in database iDb.  Return the register number for the register
** that holds the maximum rowid.
**
** There is at most one AutoincInfo structure per table even if the
** same table is autoincremented multiple times due to inserts within
** triggers.  A new AutoincInfo structure is created if this is the
** first use of table pTab.  On 2nd and subsequent uses, the original
** AutoincInfo structure is used.
**
** Three memory locations are allocated:
**
**   (1)  Register to hold the name of the pTab table.
**   (2)  Register to hold the maximum ROWID of pTab.
**   (3)  Register to hold the rowid in sqlite_sequence of pTab
**
** The 2nd register is the one that is returned.  That is all the
** insert routine needs to know about.
*/
static int autoIncBegin(
  Parse *pParse,      /* Parsing context */
  int iDb,            /* Index of the database holding pTab */
  Table *pTab         /* The table we are writing to */
){
  int memId = 0;      /* Register holding maximum rowid */
  if( pTab->tabFlags & TF_Autoincrement ){
    Parse *pToplevel = sqlite3ParseToplevel(pParse);
    AutoincInfo *pInfo;

    pInfo = pToplevel->pAinc;
    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
    if( pInfo==0 ){
      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
      if( pInfo==0 ) return 0;
      pInfo->pNext = pToplevel->pAinc;
      pToplevel->pAinc = pInfo;
      pInfo->pTab = pTab;
      pInfo->iDb = iDb;
      pToplevel->nMem++;                  /* Register to hold name of table */
      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
    }
    memId = pInfo->regCtr;
  }
  return memId;
}

/*
** This routine generates code that will initialize all of the
** register used by the autoincrement tracker.  
*/
void sqlite3AutoincrementBegin(Parse *pParse){
  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
  sqlite3 *db = pParse->db;  /* The database connection */
  Db *pDb;                   /* Database only autoinc table */
  int memId;                 /* Register holding max rowid */
  int addr;                  /* A VDBE address */
  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */

  /* This routine is never called during trigger-generation.  It is
  ** only called from the top-level */
  assert( pParse->pTriggerTab==0 );
  assert( pParse==sqlite3ParseToplevel(pParse) );

  assert( v );   /* We failed long ago if this is not so */
  for(p = pParse->pAinc; p; p = p->pNext){
    pDb = &db->aDb[p->iDb];
    memId = p->regCtr;
    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
    addr = sqlite3VdbeCurrentAddr(v);
    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
    sqlite3VdbeAddOp0(v, OP_Close);
  }
}

/*
** Update the maximum rowid for an autoincrement calculation.
**
** This routine should be called when the top of the stack holds a
** new rowid that is about to be inserted.  If that new rowid is
** larger than the maximum rowid in the memId memory cell, then the
** memory cell is updated.  The stack is unchanged.
*/
static void autoIncStep(Parse *pParse, int memId, int regRowid){
  if( memId>0 ){
    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  }
}

/*
** This routine generates the code needed to write autoincrement
** maximum rowid values back into the sqlite_sequence register.
** Every statement that might do an INSERT into an autoincrement
** table (either directly or through triggers) needs to call this
** routine just before the "exit" code.
*/
void sqlite3AutoincrementEnd(Parse *pParse){
  AutoincInfo *p;
  Vdbe *v = pParse->pVdbe;
  sqlite3 *db = pParse->db;

  assert( v );
  for(p = pParse->pAinc; p; p = p->pNext){
    Db *pDb = &db->aDb[p->iDb];
    int j1, j2, j3, j4, j5;
    int iRec;
    int memId = p->regCtr;

    iRec = sqlite3GetTempReg(pParse);
    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
    sqlite3VdbeJumpHere(v, j2);
    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
    sqlite3VdbeJumpHere(v, j4);
    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
    sqlite3VdbeJumpHere(v, j1);
    sqlite3VdbeJumpHere(v, j5);
    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
    sqlite3VdbeAddOp0(v, OP_Close);
    sqlite3ReleaseTempReg(pParse, iRec);
  }
}
#else
/*
** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
** above are all no-ops
*/
# define autoIncBegin(A,B,C) (0)
# define autoIncStep(A,B,C)
#endif /* SQLITE_OMIT_AUTOINCREMENT */


/* Forward declaration */
static int xferOptimization(
  Parse *pParse,        /* Parser context */
  Table *pDest,         /* The table we are inserting into */
  Select *pSelect,      /* A SELECT statement to use as the data source */
  int onError,          /* How to handle constraint errors */
  int iDbDest           /* The database of pDest */
);

/*
** This routine is call to handle SQL of the following forms:
**
**    insert into TABLE (IDLIST) values(EXPRLIST)
**    insert into TABLE (IDLIST) select
**
** The IDLIST following the table name is always optional.  If omitted,
** then a list of all columns for the table is substituted.  The IDLIST
** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
**
** The pList parameter holds EXPRLIST in the first form of the INSERT
** statement above, and pSelect is NULL.  For the second form, pList is
** NULL and pSelect is a pointer to the select statement used to generate
** data for the insert.
**
** The code generated follows one of four templates.  For a simple
** select with data coming from a VALUES clause, the code executes
** once straight down through.  Pseudo-code follows (we call this
** the "1st template"):
**
**         open write cursor to <table> and its indices
**         puts VALUES clause expressions onto the stack
**         write the resulting record into <table>
**         cleanup
**
** The three remaining templates assume the statement is of the form
**
**   INSERT INTO <table> SELECT ...
**
** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
** in other words if the SELECT pulls all columns from a single table
** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
** if <table2> and <table1> are distinct tables but have identical
** schemas, including all the same indices, then a special optimization
** is invoked that copies raw records from <table2> over to <table1>.
** See the xferOptimization() function for the implementation of this
** template.  This is the 2nd template.
**
**         open a write cursor to <table>
**         open read cursor on <table2>
**         transfer all records in <table2> over to <table>
**         close cursors
**         foreach index on <table>
**           open a write cursor on the <table> index
**           open a read cursor on the corresponding <table2> index
**           transfer all records from the read to the write cursors
**           close cursors
**         end foreach
**
** The 3rd template is for when the second template does not apply
** and the SELECT clause does not read from <table> at any time.
** The generated code follows this template:
**
**         EOF <- 0
**         X <- A
**         goto B
**      A: setup for the SELECT
**         loop over the rows in the SELECT
**           load values into registers R..R+n
**           yield X
**         end loop
**         cleanup after the SELECT
**         EOF <- 1
**         yield X
**         goto A
**      B: open write cursor to <table> and its indices
**      C: yield X
**         if EOF goto D
**         insert the select result into <table> from R..R+n
**         goto C
**      D: cleanup
**
** The 4th template is used if the insert statement takes its
** values from a SELECT but the data is being inserted into a table
** that is also read as part of the SELECT.  In the third form,
** we have to use a intermediate table to store the results of
** the select.  The template is like this:
**
**         EOF <- 0
**         X <- A
**         goto B
**      A: setup for the SELECT
**         loop over the tables in the SELECT
**           load value into register R..R+n
**           yield X
**         end loop
**         cleanup after the SELECT
**         EOF <- 1
**         yield X
**         halt-error
**      B: open temp table
**      L: yield X
**         if EOF goto M
**         insert row from R..R+n into temp table
**         goto L
**      M: open write cursor to <table> and its indices
**         rewind temp table
**      C: loop over rows of intermediate table
**           transfer values form intermediate table into <table>
**         end loop
**      D: cleanup
*/
void sqlite3Insert(
  Parse *pParse,        /* Parser context */
  SrcList *pTabList,    /* Name of table into which we are inserting */
  ExprList *pList,      /* List of values to be inserted */
  Select *pSelect,      /* A SELECT statement to use as the data source */
  IdList *pColumn,      /* Column names corresponding to IDLIST. */
  int onError           /* How to handle constraint errors */
){
  sqlite3 *db;          /* The main database structure */
  Table *pTab;          /* The table to insert into.  aka TABLE */
  char *zTab;           /* Name of the table into which we are inserting */
  const char *zDb;      /* Name of the database holding this table */
  int i, j, idx;        /* Loop counters */
  Vdbe *v;              /* Generate code into this virtual machine */
  Index *pIdx;          /* For looping over indices of the table */
  int nColumn;          /* Number of columns in the data */
  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
  int baseCur = 0;      /* VDBE Cursor number for pTab */
  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
  int endOfLoop;        /* Label for the end of the insertion loop */
  int useTempTable = 0; /* Store SELECT results in intermediate table */
  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
  int addrInsTop = 0;   /* Jump to label "D" */
  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
  int iDb;              /* Index of database holding TABLE */
  Db *pDb;              /* The database containing table being inserted into */
  int appendFlag = 0;   /* True if the insert is likely to be an append */

  /* Register allocations */
  int regFromSelect = 0;/* Base register for data coming from SELECT */
  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
  int regRowCount = 0;  /* Memory cell used for the row counter */
  int regIns;           /* Block of regs holding rowid+data being inserted */
  int regRowid;         /* registers holding insert rowid */
  int regData;          /* register holding first column to insert */
  int regRecord;        /* Holds the assemblied row record */
  int regEof = 0;       /* Register recording end of SELECT data */
  int *aRegIdx = 0;     /* One register allocated to each index */

#ifndef SQLITE_OMIT_TRIGGER
  int isView;                 /* True if attempting to insert into a view */
  Trigger *pTrigger;          /* List of triggers on pTab, if required */
  int tmask;                  /* Mask of trigger times */
#endif

  db = pParse->db;
  memset(&dest, 0, sizeof(dest));
  if( pParse->nErr || db->mallocFailed ){
    goto insert_cleanup;
  }

  /* Locate the table into which we will be inserting new information.
  */
  assert( pTabList->nSrc==1 );
  zTab = pTabList->a[0].zName;
  if( NEVER(zTab==0) ) goto insert_cleanup;
  pTab = sqlite3SrcListLookup(pParse, pTabList);
  if( pTab==0 ){
    goto insert_cleanup;
  }
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  assert( iDb<db->nDb );
  pDb = &db->aDb[iDb];
  zDb = pDb->zName;
  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
    goto insert_cleanup;
  }

  /* Figure out if we have any triggers and if the table being
  ** inserted into is a view
  */
#ifndef SQLITE_OMIT_TRIGGER
  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  isView = pTab->pSelect!=0;
#else
# define pTrigger 0
# define tmask 0
# define isView 0
#endif
#ifdef SQLITE_OMIT_VIEW
# undef isView
# define isView 0
#endif
  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );

  /* If pTab is really a view, make sure it has been initialized.
  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
  ** module table).
  */
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto insert_cleanup;
  }

  /* Ensure that:
  *  (a) the table is not read-only, 
  *  (b) that if it is a view then ON INSERT triggers exist
  */
  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
    goto insert_cleanup;
  }

  /* Allocate a VDBE
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ) goto insert_cleanup;
  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);

#ifndef SQLITE_OMIT_XFER_OPT
  /* If the statement is of the form
  **
  **       INSERT INTO <table1> SELECT * FROM <table2>;
  **
  ** Then special optimizations can be applied that make the transfer
  ** very fast and which reduce fragmentation of indices.
  **
  ** This is the 2nd template.
  */
  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
    assert( !pTrigger );
    assert( pList==0 );
    goto insert_end;
  }
#endif /* SQLITE_OMIT_XFER_OPT */

  /* If this is an AUTOINCREMENT table, look up the sequence number in the
  ** sqlite_sequence table and store it in memory cell regAutoinc.
  */
  regAutoinc = autoIncBegin(pParse, iDb, pTab);

  /* Figure out how many columns of data are supplied.  If the data
  ** is coming from a SELECT statement, then generate a co-routine that
  ** produces a single row of the SELECT on each invocation.  The
  ** co-routine is the common header to the 3rd and 4th templates.
  */
  if( pSelect ){
    /* Data is coming from a SELECT.  Generate code to implement that SELECT
    ** as a co-routine.  The code is common to both the 3rd and 4th
    ** templates:
    **
    **         EOF <- 0
    **         X <- A
    **         goto B
    **      A: setup for the SELECT
    **         loop over the tables in the SELECT
    **           load value into register R..R+n
    **           yield X
    **         end loop
    **         cleanup after the SELECT
    **         EOF <- 1
    **         yield X
    **         halt-error
    **
    ** On each invocation of the co-routine, it puts a single row of the
    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
    ** (These output registers are allocated by sqlite3Select().)  When
    ** the SELECT completes, it sets the EOF flag stored in regEof.
    */
    int rc, j1;

    regEof = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
    VdbeComment((v, "SELECT eof flag"));
    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
    VdbeComment((v, "Jump over SELECT coroutine"));

    /* Resolve the expressions in the SELECT statement and execute it. */
    rc = sqlite3Select(pParse, pSelect, &dest);
    assert( pParse->nErr==0 || rc );
    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
      goto insert_cleanup;
    }
    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
    VdbeComment((v, "End of SELECT coroutine"));
    sqlite3VdbeJumpHere(v, j1);                          /* label B: */

    regFromSelect = dest.iMem;
    assert( pSelect->pEList );
    nColumn = pSelect->pEList->nExpr;
    assert( dest.nMem==nColumn );

    /* Set useTempTable to TRUE if the result of the SELECT statement
    ** should be written into a temporary table (template 4).  Set to
    ** FALSE if each* row of the SELECT can be written directly into
    ** the destination table (template 3).
    **
    ** A temp table must be used if the table being updated is also one
    ** of the tables being read by the SELECT statement.  Also use a 
    ** temp table in the case of row triggers.
    */
    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
      useTempTable = 1;
    }

    if( useTempTable ){
      /* Invoke the coroutine to extract information from the SELECT
      ** and add it to a transient table srcTab.  The code generated
      ** here is from the 4th template:
      **
      **      B: open temp table
      **      L: yield X
      **         if EOF goto M
      **         insert row from R..R+n into temp table
      **         goto L
      **      M: ...
      */
      int regRec;          /* Register to hold packed record */
      int regTempRowid;    /* Register to hold temp table ROWID */
      int addrTop;         /* Label "L" */
      int addrIf;          /* Address of jump to M */

      srcTab = pParse->nTab++;
      regRec = sqlite3GetTempReg(pParse);
      regTempRowid = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
      sqlite3VdbeJumpHere(v, addrIf);
      sqlite3ReleaseTempReg(pParse, regRec);
      sqlite3ReleaseTempReg(pParse, regTempRowid);
    }
  }else{
    /* This is the case if the data for the INSERT is coming from a VALUES
    ** clause
    */
    NameContext sNC;
    memset(&sNC, 0, sizeof(sNC));
    sNC.pParse = pParse;
    srcTab = -1;
    assert( useTempTable==0 );
    nColumn = pList ? pList->nExpr : 0;
    for(i=0; i<nColumn; i++){
      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
        goto insert_cleanup;
      }
    }
  }

  /* Make sure the number of columns in the source data matches the number
  ** of columns to be inserted into the table.
  */
  if( IsVirtual(pTab) ){
    for(i=0; i<pTab->nCol; i++){
      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
    }
  }
  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
    sqlite3ErrorMsg(pParse, 
       "table %S has %d columns but %d values were supplied",
       pTabList, 0, pTab->nCol-nHidden, nColumn);
    goto insert_cleanup;
  }
  if( pColumn!=0 && nColumn!=pColumn->nId ){
    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
    goto insert_cleanup;
  }

  /* If the INSERT statement included an IDLIST term, then make sure
  ** all elements of the IDLIST really are columns of the table and 
  ** remember the column indices.
  **
  ** If the table has an INTEGER PRIMARY KEY column and that column
  ** is named in the IDLIST, then record in the keyColumn variable
  ** the index into IDLIST of the primary key column.  keyColumn is
  ** the index of the primary key as it appears in IDLIST, not as
  ** is appears in the original table.  (The index of the primary
  ** key in the original table is pTab->iPKey.)
  */
  if( pColumn ){
    for(i=0; i<pColumn->nId; i++){
      pColumn->a[i].idx = -1;
    }
    for(i=0; i<pColumn->nId; i++){
      for(j=0; j<pTab->nCol; j++){
        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
          pColumn->a[i].idx = j;
          if( j==pTab->iPKey ){
            keyColumn = i;
          }
          break;
        }
      }
      if( j>=pTab->nCol ){
        if( sqlite3IsRowid(pColumn->a[i].zName) ){
          keyColumn = i;
        }else{
          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
              pTabList, 0, pColumn->a[i].zName);
          pParse->nErr++;
          goto insert_cleanup;
        }
      }
    }
  }

  /* If there is no IDLIST term but the table has an integer primary
  ** key, the set the keyColumn variable to the primary key column index
  ** in the original table definition.
  */
  if( pColumn==0 && nColumn>0 ){
    keyColumn = pTab->iPKey;
  }
    
  /* Initialize the count of rows to be inserted
  */
  if( db->flags & SQLITE_CountRows ){
    regRowCount = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  }

  /* If this is not a view, open the table and and all indices */
  if( !isView ){
    int nIdx;

    baseCur = pParse->nTab;
    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
    if( aRegIdx==0 ){
      goto insert_cleanup;
    }
    for(i=0; i<nIdx; i++){
      aRegIdx[i] = ++pParse->nMem;
    }
  }

  /* This is the top of the main insertion loop */
  if( useTempTable ){
    /* This block codes the top of loop only.  The complete loop is the
    ** following pseudocode (template 4):
    **
    **         rewind temp table
    **      C: loop over rows of intermediate table
    **           transfer values form intermediate table into <table>
    **         end loop
    **      D: ...
    */
    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
    addrCont = sqlite3VdbeCurrentAddr(v);
  }else if( pSelect ){
    /* This block codes the top of loop only.  The complete loop is the
    ** following pseudocode (template 3):
    **
    **      C: yield X
    **         if EOF goto D
    **         insert the select result into <table> from R..R+n
    **         goto C
    **      D: ...
    */
    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  }

  /* Allocate registers for holding the rowid of the new row,
  ** the content of the new row, and the assemblied row record.
  */
  regRecord = ++pParse->nMem;
  regRowid = regIns = pParse->nMem+1;
  pParse->nMem += pTab->nCol + 1;
  if( IsVirtual(pTab) ){
    regRowid++;
    pParse->nMem++;
  }
  regData = regRowid+1;

  /* Run the BEFORE and INSTEAD OF triggers, if there are any
  */
  endOfLoop = sqlite3VdbeMakeLabel(v);
  if( tmask & TRIGGER_BEFORE ){
    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);

    /* build the NEW.* reference row.  Note that if there is an INTEGER
    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
    ** translated into a unique ID for the row.  But on a BEFORE trigger,
    ** we do not know what the unique ID will be (because the insert has
    ** not happened yet) so we substitute a rowid of -1
    */
    if( keyColumn<0 ){
      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
    }else{
      int j1;
      if( useTempTable ){
        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
      }else{
        assert( pSelect==0 );  /* Otherwise useTempTable is true */
        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
      }
      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
      sqlite3VdbeJumpHere(v, j1);
      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
    }

    /* Cannot have triggers on a virtual table. If it were possible,
    ** this block would have to account for hidden column.
    */
    assert( !IsVirtual(pTab) );

    /* Create the new column data
    */
    for(i=0; i<pTab->nCol; i++){
      if( pColumn==0 ){
        j = i;
      }else{
        for(j=0; j<pColumn->nId; j++){
          if( pColumn->a[j].idx==i ) break;
        }
      }
      if( pColumn && j>=pColumn->nId ){
        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
      }else if( useTempTable ){
        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
      }else{
        assert( pSelect==0 ); /* Otherwise useTempTable is true */
        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
      }
    }

    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
    ** do not attempt any conversions before assembling the record.
    ** If this is a real table, attempt conversions as required by the
    ** table column affinities.
    */
    if( !isView ){
      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
      sqlite3TableAffinityStr(v, pTab);
    }

    /* Fire BEFORE or INSTEAD OF triggers */
    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
        pTab, regCols-pTab->nCol-1, onError, endOfLoop);

    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  }

  /* Push the record number for the new entry onto the stack.  The
  ** record number is a randomly generate integer created by NewRowid
  ** except when the table has an INTEGER PRIMARY KEY column, in which
  ** case the record number is the same as that column. 
  */
  if( !isView ){
    if( IsVirtual(pTab) ){
      /* The row that the VUpdate opcode will delete: none */
      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
    }
    if( keyColumn>=0 ){
      if( useTempTable ){
        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
      }else if( pSelect ){
        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
      }else{
        VdbeOp *pOp;
        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
        pOp = sqlite3VdbeGetOp(v, -1);
        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
          appendFlag = 1;
          pOp->opcode = OP_NewRowid;
          pOp->p1 = baseCur;
          pOp->p2 = regRowid;
          pOp->p3 = regAutoinc;
        }
      }
      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
      ** to generate a unique primary key value.
      */
      if( !appendFlag ){
        int j1;
        if( !IsVirtual(pTab) ){
          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
          sqlite3VdbeJumpHere(v, j1);
        }else{
          j1 = sqlite3VdbeCurrentAddr(v);
          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
        }
        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
      }
    }else if( IsVirtual(pTab) ){
      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
    }else{
      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
      appendFlag = 1;
    }
    autoIncStep(pParse, regAutoinc, regRowid);

    /* Push onto the stack, data for all columns of the new entry, beginning
    ** with the first column.
    */
    nHidden = 0;
    for(i=0; i<pTab->nCol; i++){
      int iRegStore = regRowid+1+i;
      if( i==pTab->iPKey ){
        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
        ** Whenever this column is read, the record number will be substituted
        ** in its place.  So will fill this column with a NULL to avoid
        ** taking up data space with information that will never be used. */
        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
        continue;
      }
      if( pColumn==0 ){
        if( IsHiddenColumn(&pTab->aCol[i]) ){
          assert( IsVirtual(pTab) );
          j = -1;
          nHidden++;
        }else{
          j = i - nHidden;
        }
      }else{
        for(j=0; j<pColumn->nId; j++){
          if( pColumn->a[j].idx==i ) break;
        }
      }
      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
      }else if( useTempTable ){
        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
      }else if( pSelect ){
        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
      }else{
        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
      }
    }

    /* Generate code to check constraints and generate index keys and
    ** do the insertion.
    */
#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( IsVirtual(pTab) ){
      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
      sqlite3VtabMakeWritable(pParse, pTab);
      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
      sqlite3MayAbort(pParse);
    }else
#endif
    {
      int isReplace;    /* Set to true if constraints may cause a replace */
      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
          keyColumn>=0, 0, onError, endOfLoop, &isReplace
      );
      sqlite3FkCheck(pParse, pTab, 0, regIns);
      sqlite3CompleteInsertion(
          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
      );
    }
  }

  /* Update the count of rows that are inserted
  */
  if( (db->flags & SQLITE_CountRows)!=0 ){
    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  }

  if( pTrigger ){
    /* Code AFTER triggers */
    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
        pTab, regData-2-pTab->nCol, onError, endOfLoop);
  }

  /* The bottom of the main insertion loop, if the data source
  ** is a SELECT statement.
  */
  sqlite3VdbeResolveLabel(v, endOfLoop);
  if( useTempTable ){
    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
    sqlite3VdbeJumpHere(v, addrInsTop);
    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  }else if( pSelect ){
    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
    sqlite3VdbeJumpHere(v, addrInsTop);
  }

  if( !IsVirtual(pTab) && !isView ){
    /* Close all tables opened */
    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
    }
  }

insert_end:
  /* Update the sqlite_sequence table by storing the content of the
  ** maximum rowid counter values recorded while inserting into
  ** autoincrement tables.
  */
  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
    sqlite3AutoincrementEnd(pParse);
  }

  /*
  ** Return the number of rows inserted. If this routine is 
  ** generating code because of a call to sqlite3NestedParse(), do not
  ** invoke the callback function.
  */
  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  }

insert_cleanup:
  sqlite3SrcListDelete(db, pTabList);
  sqlite3ExprListDelete(db, pList);
  sqlite3SelectDelete(db, pSelect);
  sqlite3IdListDelete(db, pColumn);
  sqlite3DbFree(db, aRegIdx);
}

/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation).  */
#ifdef isView
 #undef isView
#endif
#ifdef pTrigger
 #undef pTrigger
#endif
#ifdef tmask
 #undef tmask
#endif


/*
** Generate code to do constraint checks prior to an INSERT or an UPDATE.
**
** The input is a range of consecutive registers as follows:
**
**    1.  The rowid of the row after the update.
**
**    2.  The data in the first column of the entry after the update.
**
**    i.  Data from middle columns...
**
**    N.  The data in the last column of the entry after the update.
**
** The regRowid parameter is the index of the register containing (1).
**
** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
** the address of a register containing the rowid before the update takes
** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
** is false, indicating an INSERT statement, then a non-zero rowidChng 
** indicates that the rowid was explicitly specified as part of the
** INSERT statement. If rowidChng is false, it means that  the rowid is
** computed automatically in an insert or that the rowid value is not 
** modified by an update.
**
** The code generated by this routine store new index entries into
** registers identified by aRegIdx[].  No index entry is created for
** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
** the same as the order of indices on the linked list of indices
** attached to the table.
**
** This routine also generates code to check constraints.  NOT NULL,
** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
** then the appropriate action is performed.  There are five possible
** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
**
**  Constraint type  Action       What Happens
**  ---------------  ----------   ----------------------------------------
**  any              ROLLBACK     The current transaction is rolled back and
**                                sqlite3_exec() returns immediately with a
**                                return code of SQLITE_CONSTRAINT.
**
**  any              ABORT        Back out changes from the current command
**                                only (do not do a complete rollback) then
**                                cause sqlite3_exec() to return immediately
**                                with SQLITE_CONSTRAINT.
**
**  any              FAIL         Sqlite_exec() returns immediately with a
**                                return code of SQLITE_CONSTRAINT.  The
**                                transaction is not rolled back and any
**                                prior changes are retained.
**
**  any              IGNORE       The record number and data is popped from
**                                the stack and there is an immediate jump
**                                to label ignoreDest.
**
**  NOT NULL         REPLACE      The NULL value is replace by the default
**                                value for that column.  If the default value
**                                is NULL, the action is the same as ABORT.
**
**  UNIQUE           REPLACE      The other row that conflicts with the row
**                                being inserted is removed.
**
**  CHECK            REPLACE      Illegal.  The results in an exception.
**
** Which action to take is determined by the overrideError parameter.
** Or if overrideError==OE_Default, then the pParse->onError parameter
** is used.  Or if pParse->onError==OE_Default then the onError value
** for the constraint is used.
**
** The calling routine must open a read/write cursor for pTab with
** cursor number "baseCur".  All indices of pTab must also have open
** read/write cursors with cursor number baseCur+i for the i-th cursor.
** Except, if there is no possibility of a REPLACE action then
** cursors do not need to be open for indices where aRegIdx[i]==0.
*/
void sqlite3GenerateConstraintChecks(
  Parse *pParse,      /* The parser context */
  Table *pTab,        /* the table into which we are inserting */
  int baseCur,        /* Index of a read/write cursor pointing at pTab */
  int regRowid,       /* Index of the range of input registers */
  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
  int rowidChng,      /* True if the rowid might collide with existing entry */
  int isUpdate,       /* True for UPDATE, False for INSERT */
  int overrideError,  /* Override onError to this if not OE_Default */
  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
){
  int i;              /* loop counter */
  Vdbe *v;            /* VDBE under constrution */
  int nCol;           /* Number of columns */
  int onError;        /* Conflict resolution strategy */
  int j1;             /* Addresss of jump instruction */
  int j2 = 0, j3;     /* Addresses of jump instructions */
  int regData;        /* Register containing first data column */
  int iCur;           /* Table cursor number */
  Index *pIdx;         /* Pointer to one of the indices */
  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;

  v = sqlite3GetVdbe(pParse);
  assert( v!=0 );
  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  nCol = pTab->nCol;
  regData = regRowid + 1;

  /* Test all NOT NULL constraints.
  */
  for(i=0; i<nCol; i++){
    if( i==pTab->iPKey ){
      continue;
    }
    onError = pTab->aCol[i].notNull;
    if( onError==OE_None ) continue;
    if( overrideError!=OE_Default ){
      onError = overrideError;
    }else if( onError==OE_Default ){
      onError = OE_Abort;
    }
    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
      onError = OE_Abort;
    }
    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
        || onError==OE_Ignore || onError==OE_Replace );
    switch( onError ){
      case OE_Abort:
        sqlite3MayAbort(pParse);
      case OE_Rollback:
      case OE_Fail: {
        char *zMsg;
        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
                                  SQLITE_CONSTRAINT, onError, regData+i);
        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
                              pTab->zName, pTab->aCol[i].zName);
        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
        break;
      }
      case OE_Ignore: {
        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
        break;
      }
      default: {
        assert( onError==OE_Replace );
        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
        sqlite3VdbeJumpHere(v, j1);
        break;
      }
    }
  }

  /* Test all CHECK constraints
  */
#ifndef SQLITE_OMIT_CHECK
  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
    int allOk = sqlite3VdbeMakeLabel(v);
    pParse->ckBase = regData;
    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
    if( onError==OE_Ignore ){
      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
    }else{
      sqlite3HaltConstraint(pParse, onError, 0, 0);
    }
    sqlite3VdbeResolveLabel(v, allOk);
  }
#endif /* !defined(SQLITE_OMIT_CHECK) */

  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  ** of the new record does not previously exist.  Except, if this
  ** is an UPDATE and the primary key is not changing, that is OK.
  */
  if( rowidChng ){
    onError = pTab->keyConf;
    if( overrideError!=OE_Default ){
      onError = overrideError;
    }else if( onError==OE_Default ){
      onError = OE_Abort;
    }
    
    if( isUpdate ){
      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
    }
    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
    switch( onError ){
      default: {
        onError = OE_Abort;
        /* Fall thru into the next case */
      }
      case OE_Rollback:
      case OE_Abort:
      case OE_Fail: {
        sqlite3HaltConstraint(
          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
        break;
      }
      case OE_Replace: {
        /* If there are DELETE triggers on this table and the
        ** recursive-triggers flag is set, call GenerateRowDelete() to
        ** remove the conflicting row from the the table. This will fire
        ** the triggers and remove both the table and index b-tree entries.
        **
        ** Otherwise, if there are no triggers or the recursive-triggers
        ** flag is not set, call GenerateRowIndexDelete(). This removes
        ** the index b-tree entries only. The table b-tree entry will be 
        ** replaced by the new entry when it is inserted.  */
        Trigger *pTrigger = 0;
        if( pParse->db->flags&SQLITE_RecTriggers ){
          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
        }
        sqlite3MultiWrite(pParse);
        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
          sqlite3GenerateRowDelete(
              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
          );
        }else{
          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
        }
        seenReplace = 1;
        break;
      }
      case OE_Ignore: {
        assert( seenReplace==0 );
        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
        break;
      }
    }
    sqlite3VdbeJumpHere(v, j3);
    if( isUpdate ){
      sqlite3VdbeJumpHere(v, j2);
    }
  }

  /* Test all UNIQUE constraints by creating entries for each UNIQUE
  ** index and making sure that duplicate entries do not already exist.
  ** Add the new records to the indices as we go.
  */
  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
    int regIdx;
    int regR;

    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */

    /* Create a key for accessing the index entry */
    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
    for(i=0; i<pIdx->nColumn; i++){
      int idx = pIdx->aiColumn[i];
      if( idx==pTab->iPKey ){
        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
      }else{
        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
      }
    }
    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);

    /* Find out what action to take in case there is an indexing conflict */
    onError = pIdx->onError;
    if( onError==OE_None ){ 
      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
      continue;  /* pIdx is not a UNIQUE index */
    }
    if( overrideError!=OE_Default ){
      onError = overrideError;
    }else if( onError==OE_Default ){
      onError = OE_Abort;
    }
    if( seenReplace ){
      if( onError==OE_Ignore ) onError = OE_Replace;
      else if( onError==OE_Fail ) onError = OE_Abort;
    }
    
    /* Check to see if the new index entry will be unique */
    regR = sqlite3GetTempReg(pParse);
    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
                           regR, SQLITE_INT_TO_PTR(regIdx),
                           P4_INT32);
    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);

    /* Generate code that executes if the new index entry is not unique */
    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
        || onError==OE_Ignore || onError==OE_Replace );
    switch( onError ){
      case OE_Rollback:
      case OE_Abort:
      case OE_Fail: {
        int j;
        StrAccum errMsg;
        const char *zSep;
        char *zErr;

        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
        errMsg.db = pParse->db;
        zSep = pIdx->nColumn>1 ? "columns " : "column ";
        for(j=0; j<pIdx->nColumn; j++){
          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
          sqlite3StrAccumAppend(&errMsg, zSep, -1);
          zSep = ", ";
          sqlite3StrAccumAppend(&errMsg, zCol, -1);
        }
        sqlite3StrAccumAppend(&errMsg,
            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
        zErr = sqlite3StrAccumFinish(&errMsg);
        sqlite3HaltConstraint(pParse, onError, zErr, 0);
        sqlite3DbFree(errMsg.db, zErr);
        break;
      }
      case OE_Ignore: {
        assert( seenReplace==0 );
        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
        break;
      }
      default: {
        Trigger *pTrigger = 0;
        assert( onError==OE_Replace );
        sqlite3MultiWrite(pParse);
        if( pParse->db->flags&SQLITE_RecTriggers ){
          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
        }
        sqlite3GenerateRowDelete(
            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
        );
        seenReplace = 1;
        break;
      }
    }
    sqlite3VdbeJumpHere(v, j3);
    sqlite3ReleaseTempReg(pParse, regR);
  }
  
  if( pbMayReplace ){
    *pbMayReplace = seenReplace;
  }
}

/*
** This routine generates code to finish the INSERT or UPDATE operation
** that was started by a prior call to sqlite3GenerateConstraintChecks.
** A consecutive range of registers starting at regRowid contains the
** rowid and the content to be inserted.
**
** The arguments to this routine should be the same as the first six
** arguments to sqlite3GenerateConstraintChecks.
*/
void sqlite3CompleteInsertion(
  Parse *pParse,      /* The parser context */
  Table *pTab,        /* the table into which we are inserting */
  int baseCur,        /* Index of a read/write cursor pointing at pTab */
  int regRowid,       /* Range of content */
  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
  int isUpdate,       /* True for UPDATE, False for INSERT */
  int appendBias,     /* True if this is likely to be an append */
  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
){
  int i;
  Vdbe *v;
  int nIdx;
  Index *pIdx;
  u8 pik_flags;
  int regData;
  int regRec;

  v = sqlite3GetVdbe(pParse);
  assert( v!=0 );
  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  for(i=nIdx-1; i>=0; i--){
    if( aRegIdx[i]==0 ) continue;
    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
    if( useSeekResult ){
      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
    }
  }
  regData = regRowid + 1;
  regRec = sqlite3GetTempReg(pParse);
  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  sqlite3TableAffinityStr(v, pTab);
  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  if( pParse->nested ){
    pik_flags = 0;
  }else{
    pik_flags = OPFLAG_NCHANGE;
    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  }
  if( appendBias ){
    pik_flags |= OPFLAG_APPEND;
  }
  if( useSeekResult ){
    pik_flags |= OPFLAG_USESEEKRESULT;
  }
  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  if( !pParse->nested ){
    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  }
  sqlite3VdbeChangeP5(v, pik_flags);
}

/*
** Generate code that will open cursors for a table and for all
** indices of that table.  The "baseCur" parameter is the cursor number used
** for the table.  Indices are opened on subsequent cursors.
**
** Return the number of indices on the table.
*/
int sqlite3OpenTableAndIndices(
  Parse *pParse,   /* Parsing context */
  Table *pTab,     /* Table to be opened */
  int baseCur,     /* Cursor number assigned to the table */
  int op           /* OP_OpenRead or OP_OpenWrite */
){
  int i;
  int iDb;
  Index *pIdx;
  Vdbe *v;

  if( IsVirtual(pTab) ) return 0;
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  v = sqlite3GetVdbe(pParse);
  assert( v!=0 );
  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
    assert( pIdx->pSchema==pTab->pSchema );
    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
                      (char*)pKey, P4_KEYINFO_HANDOFF);
    VdbeComment((v, "%s", pIdx->zName));
  }
  if( pParse->nTab<baseCur+i ){
    pParse->nTab = baseCur+i;
  }
  return i-1;
}


#ifdef SQLITE_TEST
/*
** The following global variable is incremented whenever the
** transfer optimization is used.  This is used for testing
** purposes only - to make sure the transfer optimization really
** is happening when it is suppose to.
*/
int sqlite3_xferopt_count;
#endif /* SQLITE_TEST */


#ifndef SQLITE_OMIT_XFER_OPT
/*
** Check to collation names to see if they are compatible.
*/
static int xferCompatibleCollation(const char *z1, const char *z2){
  if( z1==0 ){
    return z2==0;
  }
  if( z2==0 ){
    return 0;
  }
  return sqlite3StrICmp(z1, z2)==0;
}


/*
** Check to see if index pSrc is compatible as a source of data
** for index pDest in an insert transfer optimization.  The rules
** for a compatible index:
**
**    *   The index is over the same set of columns
**    *   The same DESC and ASC markings occurs on all columns
**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
**    *   The same collating sequence on each column
*/
static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  int i;
  assert( pDest && pSrc );
  assert( pDest->pTable!=pSrc->pTable );
  if( pDest->nColumn!=pSrc->nColumn ){
    return 0;   /* Different number of columns */
  }
  if( pDest->onError!=pSrc->onError ){
    return 0;   /* Different conflict resolution strategies */
  }
  for(i=0; i<pSrc->nColumn; i++){
    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
      return 0;   /* Different columns indexed */
    }
    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
      return 0;   /* Different sort orders */
    }
    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
      return 0;   /* Different collating sequences */
    }
  }

  /* If no test above fails then the indices must be compatible */
  return 1;
}

/*
** Attempt the transfer optimization on INSERTs of the form
**
**     INSERT INTO tab1 SELECT * FROM tab2;
**
** This optimization is only attempted if
**
**    (1)  tab1 and tab2 have identical schemas including all the
**         same indices and constraints
**
**    (2)  tab1 and tab2 are different tables
**
**    (3)  There must be no triggers on tab1
**
**    (4)  The result set of the SELECT statement is "*"
**
**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
**         or LIMIT clause.
**
**    (6)  The SELECT statement is a simple (not a compound) select that
**         contains only tab2 in its FROM clause
**
** This method for implementing the INSERT transfers raw records from
** tab2 over to tab1.  The columns are not decoded.  Raw records from
** the indices of tab2 are transfered to tab1 as well.  In so doing,
** the resulting tab1 has much less fragmentation.
**
** This routine returns TRUE if the optimization is attempted.  If any
** of the conditions above fail so that the optimization should not
** be attempted, then this routine returns FALSE.
*/
static int xferOptimization(
  Parse *pParse,        /* Parser context */
  Table *pDest,         /* The table we are inserting into */
  Select *pSelect,      /* A SELECT statement to use as the data source */
  int onError,          /* How to handle constraint errors */
  int iDbDest           /* The database of pDest */
){
  ExprList *pEList;                /* The result set of the SELECT */
  Table *pSrc;                     /* The table in the FROM clause of SELECT */
  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
  int i;                           /* Loop counter */
  int iDbSrc;                      /* The database of pSrc */
  int iSrc, iDest;                 /* Cursors from source and destination */
  int addr1, addr2;                /* Loop addresses */
  int emptyDestTest;               /* Address of test for empty pDest */
  int emptySrcTest;                /* Address of test for empty pSrc */
  Vdbe *v;                         /* The VDBE we are building */
  KeyInfo *pKey;                   /* Key information for an index */
  int regAutoinc;                  /* Memory register used by AUTOINC */
  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
  int regData, regRowid;           /* Registers holding data and rowid */

  if( pSelect==0 ){
    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
  }
  if( sqlite3TriggerList(pParse, pDest) ){
    return 0;   /* tab1 must not have triggers */
  }
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( pDest->tabFlags & TF_Virtual ){
    return 0;   /* tab1 must not be a virtual table */
  }
#endif
  if( onError==OE_Default ){
    onError = OE_Abort;
  }
  if( onError!=OE_Abort && onError!=OE_Rollback ){
    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
  }
  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
  if( pSelect->pSrc->nSrc!=1 ){
    return 0;   /* FROM clause must have exactly one term */
  }
  if( pSelect->pSrc->a[0].pSelect ){
    return 0;   /* FROM clause cannot contain a subquery */
  }
  if( pSelect->pWhere ){
    return 0;   /* SELECT may not have a WHERE clause */
  }
  if( pSelect->pOrderBy ){
    return 0;   /* SELECT may not have an ORDER BY clause */
  }
  /* Do not need to test for a HAVING clause.  If HAVING is present but
  ** there is no ORDER BY, we will get an error. */
  if( pSelect->pGroupBy ){
    return 0;   /* SELECT may not have a GROUP BY clause */
  }
  if( pSelect->pLimit ){
    return 0;   /* SELECT may not have a LIMIT clause */
  }
  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
  if( pSelect->pPrior ){
    return 0;   /* SELECT may not be a compound query */
  }
  if( pSelect->selFlags & SF_Distinct ){
    return 0;   /* SELECT may not be DISTINCT */
  }
  pEList = pSelect->pEList;
  assert( pEList!=0 );
  if( pEList->nExpr!=1 ){
    return 0;   /* The result set must have exactly one column */
  }
  assert( pEList->a[0].pExpr );
  if( pEList->a[0].pExpr->op!=TK_ALL ){
    return 0;   /* The result set must be the special operator "*" */
  }

  /* At this point we have established that the statement is of the
  ** correct syntactic form to participate in this optimization.  Now
  ** we have to check the semantics.
  */
  pItem = pSelect->pSrc->a;
  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  if( pSrc==0 ){
    return 0;   /* FROM clause does not contain a real table */
  }
  if( pSrc==pDest ){
    return 0;   /* tab1 and tab2 may not be the same table */
  }
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( pSrc->tabFlags & TF_Virtual ){
    return 0;   /* tab2 must not be a virtual table */
  }
#endif
  if( pSrc->pSelect ){
    return 0;   /* tab2 may not be a view */
  }
  if( pDest->nCol!=pSrc->nCol ){
    return 0;   /* Number of columns must be the same in tab1 and tab2 */
  }
  if( pDest->iPKey!=pSrc->iPKey ){
    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
  }
  for(i=0; i<pDest->nCol; i++){
    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
      return 0;    /* Affinity must be the same on all columns */
    }
    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
      return 0;    /* Collating sequence must be the same on all columns */
    }
    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
      return 0;    /* tab2 must be NOT NULL if tab1 is */
    }
  }
  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
    if( pDestIdx->onError!=OE_None ){
      destHasUniqueIdx = 1;
    }
    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
    }
    if( pSrcIdx==0 ){
      return 0;    /* pDestIdx has no corresponding index in pSrc */
    }
  }
#ifndef SQLITE_OMIT_CHECK
  if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
  }
#endif

  /* If we get this far, it means either:
  **
  **    *   We can always do the transfer if the table contains an
  **        an integer primary key
  **
  **    *   We can conditionally do the transfer if the destination
  **        table is empty.
  */
#ifdef SQLITE_TEST
  sqlite3_xferopt_count++;
#endif
  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  v = sqlite3GetVdbe(pParse);
  sqlite3CodeVerifySchema(pParse, iDbSrc);
  iSrc = pParse->nTab++;
  iDest = pParse->nTab++;
  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
    /* If tables do not have an INTEGER PRIMARY KEY and there
    ** are indices to be copied and the destination is not empty,
    ** we have to disallow the transfer optimization because the
    ** the rowids might change which will mess up indexing.
    **
    ** Or if the destination has a UNIQUE index and is not empty,
    ** we also disallow the transfer optimization because we cannot
    ** insure that all entries in the union of DEST and SRC will be
    ** unique.
    */
    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
    sqlite3VdbeJumpHere(v, addr1);
  }else{
    emptyDestTest = 0;
  }
  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  regData = sqlite3GetTempReg(pParse);
  regRowid = sqlite3GetTempReg(pParse);
  if( pDest->iPKey>=0 ){
    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
    sqlite3HaltConstraint(
        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
    sqlite3VdbeJumpHere(v, addr2);
    autoIncStep(pParse, regAutoinc, regRowid);
  }else if( pDest->pIndex==0 ){
    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  }else{
    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  }
  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
    }
    assert( pSrcIdx );
    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
                      (char*)pKey, P4_KEYINFO_HANDOFF);
    VdbeComment((v, "%s", pSrcIdx->zName));
    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
                      (char*)pKey, P4_KEYINFO_HANDOFF);
    VdbeComment((v, "%s", pDestIdx->zName));
    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
    sqlite3VdbeJumpHere(v, addr1);
  }
  sqlite3VdbeJumpHere(v, emptySrcTest);
  sqlite3ReleaseTempReg(pParse, regRowid);
  sqlite3ReleaseTempReg(pParse, regData);
  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  if( emptyDestTest ){
    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
    sqlite3VdbeJumpHere(v, emptyDestTest);
    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
    return 0;
  }else{
    return 1;
  }
}
#endif /* SQLITE_OMIT_XFER_OPT */

Added src/journal.c.

































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
** 2007 August 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** @(#) $Id: journal.c,v 1.9 2009/01/20 17:06:27 danielk1977 Exp $
*/

#ifdef SQLITE_ENABLE_ATOMIC_WRITE

/*
** This file implements a special kind of sqlite3_file object used
** by SQLite to create journal files if the atomic-write optimization
** is enabled.
**
** The distinctive characteristic of this sqlite3_file is that the
** actual on disk file is created lazily. When the file is created,
** the caller specifies a buffer size for an in-memory buffer to
** be used to service read() and write() requests. The actual file
** on disk is not created or populated until either:
**
**   1) The in-memory representation grows too large for the allocated 
**      buffer, or
**   2) The sqlite3JournalCreate() function is called.
*/

#include "sqliteInt.h"


/*
** A JournalFile object is a subclass of sqlite3_file used by
** as an open file handle for journal files.
*/
struct JournalFile {
  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
  int nBuf;                       /* Size of zBuf[] in bytes */
  char *zBuf;                     /* Space to buffer journal writes */
  int iSize;                      /* Amount of zBuf[] currently used */
  int flags;                      /* xOpen flags */
  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
  const char *zJournal;           /* Name of the journal file */
};
typedef struct JournalFile JournalFile;

/*
** If it does not already exists, create and populate the on-disk file 
** for JournalFile p.
*/
static int createFile(JournalFile *p){
  int rc = SQLITE_OK;
  if( !p->pReal ){
    sqlite3_file *pReal = (sqlite3_file *)&p[1];
    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
    if( rc==SQLITE_OK ){
      p->pReal = pReal;
      if( p->iSize>0 ){
        assert(p->iSize<=p->nBuf);
        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
      }
    }
  }
  return rc;
}

/*
** Close the file.
*/
static int jrnlClose(sqlite3_file *pJfd){
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    sqlite3OsClose(p->pReal);
  }
  sqlite3_free(p->zBuf);
  return SQLITE_OK;
}

/*
** Read data from the file.
*/
static int jrnlRead(
  sqlite3_file *pJfd,    /* The journal file from which to read */
  void *zBuf,            /* Put the results here */
  int iAmt,              /* Number of bytes to read */
  sqlite_int64 iOfst     /* Begin reading at this offset */
){
  int rc = SQLITE_OK;
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  }else if( (iAmt+iOfst)>p->iSize ){
    rc = SQLITE_IOERR_SHORT_READ;
  }else{
    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  }
  return rc;
}

/*
** Write data to the file.
*/
static int jrnlWrite(
  sqlite3_file *pJfd,    /* The journal file into which to write */
  const void *zBuf,      /* Take data to be written from here */
  int iAmt,              /* Number of bytes to write */
  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
){
  int rc = SQLITE_OK;
  JournalFile *p = (JournalFile *)pJfd;
  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
    rc = createFile(p);
  }
  if( rc==SQLITE_OK ){
    if( p->pReal ){
      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
    }else{
      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
      if( p->iSize<(iOfst+iAmt) ){
        p->iSize = (iOfst+iAmt);
      }
    }
  }
  return rc;
}

/*
** Truncate the file.
*/
static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  int rc = SQLITE_OK;
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    rc = sqlite3OsTruncate(p->pReal, size);
  }else if( size<p->iSize ){
    p->iSize = size;
  }
  return rc;
}

/*
** Sync the file.
*/
static int jrnlSync(sqlite3_file *pJfd, int flags){
  int rc;
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    rc = sqlite3OsSync(p->pReal, flags);
  }else{
    rc = SQLITE_OK;
  }
  return rc;
}

/*
** Query the size of the file in bytes.
*/
static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  int rc = SQLITE_OK;
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    rc = sqlite3OsFileSize(p->pReal, pSize);
  }else{
    *pSize = (sqlite_int64) p->iSize;
  }
  return rc;
}

/*
** Table of methods for JournalFile sqlite3_file object.
*/
static struct sqlite3_io_methods JournalFileMethods = {
  1,             /* iVersion */
  jrnlClose,     /* xClose */
  jrnlRead,      /* xRead */
  jrnlWrite,     /* xWrite */
  jrnlTruncate,  /* xTruncate */
  jrnlSync,      /* xSync */
  jrnlFileSize,  /* xFileSize */
  0,             /* xLock */
  0,             /* xUnlock */
  0,             /* xCheckReservedLock */
  0,             /* xFileControl */
  0,             /* xSectorSize */
  0              /* xDeviceCharacteristics */
};

/* 
** Open a journal file.
*/
int sqlite3JournalOpen(
  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
  const char *zName,         /* Name of the journal file */
  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
  int flags,                 /* Opening flags */
  int nBuf                   /* Bytes buffered before opening the file */
){
  JournalFile *p = (JournalFile *)pJfd;
  memset(p, 0, sqlite3JournalSize(pVfs));
  if( nBuf>0 ){
    p->zBuf = sqlite3MallocZero(nBuf);
    if( !p->zBuf ){
      return SQLITE_NOMEM;
    }
  }else{
    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  }
  p->pMethod = &JournalFileMethods;
  p->nBuf = nBuf;
  p->flags = flags;
  p->zJournal = zName;
  p->pVfs = pVfs;
  return SQLITE_OK;
}

/*
** If the argument p points to a JournalFile structure, and the underlying
** file has not yet been created, create it now.
*/
int sqlite3JournalCreate(sqlite3_file *p){
  if( p->pMethods!=&JournalFileMethods ){
    return SQLITE_OK;
  }
  return createFile((JournalFile *)p);
}

/* 
** Return the number of bytes required to store a JournalFile that uses vfs
** pVfs to create the underlying on-disk files.
*/
int sqlite3JournalSize(sqlite3_vfs *pVfs){
  return (pVfs->szOsFile+sizeof(JournalFile));
}
#endif

Added src/legacy.c.





































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: legacy.c,v 1.35 2009/08/07 16:56:00 danielk1977 Exp $
*/

#include "sqliteInt.h"

/*
** Execute SQL code.  Return one of the SQLITE_ success/failure
** codes.  Also write an error message into memory obtained from
** malloc() and make *pzErrMsg point to that message.
**
** If the SQL is a query, then for each row in the query result
** the xCallback() function is called.  pArg becomes the first
** argument to xCallback().  If xCallback=NULL then no callback
** is invoked, even for queries.
*/
int sqlite3_exec(
  sqlite3 *db,                /* The database on which the SQL executes */
  const char *zSql,           /* The SQL to be executed */
  sqlite3_callback xCallback, /* Invoke this callback routine */
  void *pArg,                 /* First argument to xCallback() */
  char **pzErrMsg             /* Write error messages here */
){
  int rc = SQLITE_OK;         /* Return code */
  const char *zLeftover;      /* Tail of unprocessed SQL */
  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
  char **azCols = 0;          /* Names of result columns */
  int nRetry = 0;             /* Number of retry attempts */
  int callbackIsInit;         /* True if callback data is initialized */

  if( zSql==0 ) zSql = "";

  sqlite3_mutex_enter(db->mutex);
  sqlite3Error(db, SQLITE_OK, 0);
  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
    int nCol;
    char **azVals = 0;

    pStmt = 0;
    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
    assert( rc==SQLITE_OK || pStmt==0 );
    if( rc!=SQLITE_OK ){
      continue;
    }
    if( !pStmt ){
      /* this happens for a comment or white-space */
      zSql = zLeftover;
      continue;
    }

    callbackIsInit = 0;
    nCol = sqlite3_column_count(pStmt);

    while( 1 ){
      int i;
      rc = sqlite3_step(pStmt);

      /* Invoke the callback function if required */
      if( xCallback && (SQLITE_ROW==rc || 
          (SQLITE_DONE==rc && !callbackIsInit
                           && db->flags&SQLITE_NullCallback)) ){
        if( !callbackIsInit ){
          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
          if( azCols==0 ){
            goto exec_out;
          }
          for(i=0; i<nCol; i++){
            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
            /* sqlite3VdbeSetColName() installs column names as UTF8
            ** strings so there is no way for sqlite3_column_name() to fail. */
            assert( azCols[i]!=0 );
          }
          callbackIsInit = 1;
        }
        if( rc==SQLITE_ROW ){
          azVals = &azCols[nCol];
          for(i=0; i<nCol; i++){
            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
              db->mallocFailed = 1;
              goto exec_out;
            }
          }
        }
        if( xCallback(pArg, nCol, azVals, azCols) ){
          rc = SQLITE_ABORT;
          sqlite3VdbeFinalize((Vdbe *)pStmt);
          pStmt = 0;
          sqlite3Error(db, SQLITE_ABORT, 0);
          goto exec_out;
        }
      }

      if( rc!=SQLITE_ROW ){
        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
        pStmt = 0;
        if( rc!=SQLITE_SCHEMA ){
          nRetry = 0;
          zSql = zLeftover;
          while( sqlite3Isspace(zSql[0]) ) zSql++;
        }
        break;
      }
    }

    sqlite3DbFree(db, azCols);
    azCols = 0;
  }

exec_out:
  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  sqlite3DbFree(db, azCols);

  rc = sqlite3ApiExit(db, rc);
  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
    *pzErrMsg = sqlite3Malloc(nErrMsg);
    if( *pzErrMsg ){
      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
    }else{
      rc = SQLITE_NOMEM;
      sqlite3Error(db, SQLITE_NOMEM, 0);
    }
  }else if( pzErrMsg ){
    *pzErrMsg = 0;
  }

  assert( (rc&db->errMask)==rc );
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

Added src/lempar.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
/* Driver template for the LEMON parser generator.
** The author disclaims copyright to this source code.
**
** This version of "lempar.c" is modified, slightly, for use by SQLite.
** The only modifications are the addition of a couple of NEVER()
** macros to disable tests that are needed in the case of a general
** LALR(1) grammar but which are always false in the
** specific grammar used by SQLite.
*/
/* First off, code is included that follows the "include" declaration
** in the input grammar file. */
#include <stdio.h>
%%
/* Next is all token values, in a form suitable for use by makeheaders.
** This section will be null unless lemon is run with the -m switch.
*/
/* 
** These constants (all generated automatically by the parser generator)
** specify the various kinds of tokens (terminals) that the parser
** understands. 
**
** Each symbol here is a terminal symbol in the grammar.
*/
%%
/* Make sure the INTERFACE macro is defined.
*/
#ifndef INTERFACE
# define INTERFACE 1
#endif
/* The next thing included is series of defines which control
** various aspects of the generated parser.
**    YYCODETYPE         is the data type used for storing terminal
**                       and nonterminal numbers.  "unsigned char" is
**                       used if there are fewer than 250 terminals
**                       and nonterminals.  "int" is used otherwise.
**    YYNOCODE           is a number of type YYCODETYPE which corresponds
**                       to no legal terminal or nonterminal number.  This
**                       number is used to fill in empty slots of the hash 
**                       table.
**    YYFALLBACK         If defined, this indicates that one or more tokens
**                       have fall-back values which should be used if the
**                       original value of the token will not parse.
**    YYACTIONTYPE       is the data type used for storing terminal
**                       and nonterminal numbers.  "unsigned char" is
**                       used if there are fewer than 250 rules and
**                       states combined.  "int" is used otherwise.
**    ParseTOKENTYPE     is the data type used for minor tokens given 
**                       directly to the parser from the tokenizer.
**    YYMINORTYPE        is the data type used for all minor tokens.
**                       This is typically a union of many types, one of
**                       which is ParseTOKENTYPE.  The entry in the union
**                       for base tokens is called "yy0".
**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
**                       zero the stack is dynamically sized using realloc()
**    ParseARG_SDECL     A static variable declaration for the %extra_argument
**    ParseARG_PDECL     A parameter declaration for the %extra_argument
**    ParseARG_STORE     Code to store %extra_argument into yypParser
**    ParseARG_FETCH     Code to extract %extra_argument from yypParser
**    YYNSTATE           the combined number of states.
**    YYNRULE            the number of rules in the grammar
**    YYERRORSYMBOL      is the code number of the error symbol.  If not
**                       defined, then do no error processing.
*/
%%
#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)

/* The yyzerominor constant is used to initialize instances of
** YYMINORTYPE objects to zero. */
static const YYMINORTYPE yyzerominor = { 0 };

/* Define the yytestcase() macro to be a no-op if is not already defined
** otherwise.
**
** Applications can choose to define yytestcase() in the %include section
** to a macro that can assist in verifying code coverage.  For production
** code the yytestcase() macro should be turned off.  But it is useful
** for testing.
*/
#ifndef yytestcase
# define yytestcase(X)
#endif


/* Next are the tables used to determine what action to take based on the
** current state and lookahead token.  These tables are used to implement
** functions that take a state number and lookahead value and return an
** action integer.  
**
** Suppose the action integer is N.  Then the action is determined as
** follows
**
**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
**                                      token onto the stack and goto state N.
**
**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
**
**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
**
**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
**
**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
**                                      slots in the yy_action[] table.
**
** The action table is constructed as a single large table named yy_action[].
** Given state S and lookahead X, the action is computed as
**
**      yy_action[ yy_shift_ofst[S] + X ]
**
** If the index value yy_shift_ofst[S]+X is out of range or if the value
** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
** and that yy_default[S] should be used instead.  
**
** The formula above is for computing the action when the lookahead is
** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
** a reduce action) then the yy_reduce_ofst[] array is used in place of
** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
** YY_SHIFT_USE_DFLT.
**
** The following are the tables generated in this section:
**
**  yy_action[]        A single table containing all actions.
**  yy_lookahead[]     A table containing the lookahead for each entry in
**                     yy_action.  Used to detect hash collisions.
**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
*/
%%

/* The next table maps tokens into fallback tokens.  If a construct
** like the following:
** 
**      %fallback ID X Y Z.
**
** appears in the grammar, then ID becomes a fallback token for X, Y,
** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
** but it does not parse, the type of the token is changed to ID and
** the parse is retried before an error is thrown.
*/
#ifdef YYFALLBACK
static const YYCODETYPE yyFallback[] = {
%%
};
#endif /* YYFALLBACK */

/* The following structure represents a single element of the
** parser's stack.  Information stored includes:
**
**   +  The state number for the parser at this level of the stack.
**
**   +  The value of the token stored at this level of the stack.
**      (In other words, the "major" token.)
**
**   +  The semantic value stored at this level of the stack.  This is
**      the information used by the action routines in the grammar.
**      It is sometimes called the "minor" token.
*/
struct yyStackEntry {
  YYACTIONTYPE stateno;  /* The state-number */
  YYCODETYPE major;      /* The major token value.  This is the code
                         ** number for the token at this stack level */
  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
                         ** is the value of the token  */
};
typedef struct yyStackEntry yyStackEntry;

/* The state of the parser is completely contained in an instance of
** the following structure */
struct yyParser {
  int yyidx;                    /* Index of top element in stack */
#ifdef YYTRACKMAXSTACKDEPTH
  int yyidxMax;                 /* Maximum value of yyidx */
#endif
  int yyerrcnt;                 /* Shifts left before out of the error */
  ParseARG_SDECL                /* A place to hold %extra_argument */
#if YYSTACKDEPTH<=0
  int yystksz;                  /* Current side of the stack */
  yyStackEntry *yystack;        /* The parser's stack */
#else
  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
#endif
};
typedef struct yyParser yyParser;

#ifndef NDEBUG
#include <stdio.h>
static FILE *yyTraceFILE = 0;
static char *yyTracePrompt = 0;
#endif /* NDEBUG */

#ifndef NDEBUG
/* 
** Turn parser tracing on by giving a stream to which to write the trace
** and a prompt to preface each trace message.  Tracing is turned off
** by making either argument NULL 
**
** Inputs:
** <ul>
** <li> A FILE* to which trace output should be written.
**      If NULL, then tracing is turned off.
** <li> A prefix string written at the beginning of every
**      line of trace output.  If NULL, then tracing is
**      turned off.
** </ul>
**
** Outputs:
** None.
*/
void ParseTrace(FILE *TraceFILE, char *zTracePrompt){
  yyTraceFILE = TraceFILE;
  yyTracePrompt = zTracePrompt;
  if( yyTraceFILE==0 ) yyTracePrompt = 0;
  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
}
#endif /* NDEBUG */

#ifndef NDEBUG
/* For tracing shifts, the names of all terminals and nonterminals
** are required.  The following table supplies these names */
static const char *const yyTokenName[] = { 
%%
};
#endif /* NDEBUG */

#ifndef NDEBUG
/* For tracing reduce actions, the names of all rules are required.
*/
static const char *const yyRuleName[] = {
%%
};
#endif /* NDEBUG */


#if YYSTACKDEPTH<=0
/*
** Try to increase the size of the parser stack.
*/
static void yyGrowStack(yyParser *p){
  int newSize;
  yyStackEntry *pNew;

  newSize = p->yystksz*2 + 100;
  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  if( pNew ){
    p->yystack = pNew;
    p->yystksz = newSize;
#ifndef NDEBUG
    if( yyTraceFILE ){
      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
              yyTracePrompt, p->yystksz);
    }
#endif
  }
}
#endif

/* 
** This function allocates a new parser.
** The only argument is a pointer to a function which works like
** malloc.
**
** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser.  This pointer is used in subsequent calls
** to Parse and ParseFree.
*/
void *ParseAlloc(void *(*mallocProc)(size_t)){
  yyParser *pParser;
  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  if( pParser ){
    pParser->yyidx = -1;
#ifdef YYTRACKMAXSTACKDEPTH
    pParser->yyidxMax = 0;
#endif
#if YYSTACKDEPTH<=0
    pParser->yystack = NULL;
    pParser->yystksz = 0;
    yyGrowStack(pParser);
#endif
  }
  return pParser;
}

/* The following function deletes the value associated with a
** symbol.  The symbol can be either a terminal or nonterminal.
** "yymajor" is the symbol code, and "yypminor" is a pointer to
** the value.
*/
static void yy_destructor(
  yyParser *yypParser,    /* The parser */
  YYCODETYPE yymajor,     /* Type code for object to destroy */
  YYMINORTYPE *yypminor   /* The object to be destroyed */
){
  ParseARG_FETCH;
  switch( yymajor ){
    /* Here is inserted the actions which take place when a
    ** terminal or non-terminal is destroyed.  This can happen
    ** when the symbol is popped from the stack during a
    ** reduce or during error processing or when a parser is 
    ** being destroyed before it is finished parsing.
    **
    ** Note: during a reduce, the only symbols destroyed are those
    ** which appear on the RHS of the rule, but which are not used
    ** inside the C code.
    */
%%
    default:  break;   /* If no destructor action specified: do nothing */
  }
}

/*
** Pop the parser's stack once.
**
** If there is a destructor routine associated with the token which
** is popped from the stack, then call it.
**
** Return the major token number for the symbol popped.
*/
static int yy_pop_parser_stack(yyParser *pParser){
  YYCODETYPE yymajor;
  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];

  /* There is no mechanism by which the parser stack can be popped below
  ** empty in SQLite.  */
  if( NEVER(pParser->yyidx<0) ) return 0;
#ifndef NDEBUG
  if( yyTraceFILE && pParser->yyidx>=0 ){
    fprintf(yyTraceFILE,"%sPopping %s\n",
      yyTracePrompt,
      yyTokenName[yytos->major]);
  }
#endif
  yymajor = yytos->major;
  yy_destructor(pParser, yymajor, &yytos->minor);
  pParser->yyidx--;
  return yymajor;
}

/* 
** Deallocate and destroy a parser.  Destructors are all called for
** all stack elements before shutting the parser down.
**
** Inputs:
** <ul>
** <li>  A pointer to the parser.  This should be a pointer
**       obtained from ParseAlloc.
** <li>  A pointer to a function used to reclaim memory obtained
**       from malloc.
** </ul>
*/
void ParseFree(
  void *p,                    /* The parser to be deleted */
  void (*freeProc)(void*)     /* Function used to reclaim memory */
){
  yyParser *pParser = (yyParser*)p;
  /* In SQLite, we never try to destroy a parser that was not successfully
  ** created in the first place. */
  if( NEVER(pParser==0) ) return;
  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
  free(pParser->yystack);
#endif
  (*freeProc)((void*)pParser);
}

/*
** Return the peak depth of the stack for a parser.
*/
#ifdef YYTRACKMAXSTACKDEPTH
int ParseStackPeak(void *p){
  yyParser *pParser = (yyParser*)p;
  return pParser->yyidxMax;
}
#endif

/*
** Find the appropriate action for a parser given the terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead.  If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_shift_action(
  yyParser *pParser,        /* The parser */
  YYCODETYPE iLookAhead     /* The look-ahead token */
){
  int i;
  int stateno = pParser->yystack[pParser->yyidx].stateno;
 
  if( stateno>YY_SHIFT_COUNT
   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
    return yy_default[stateno];
  }
  assert( iLookAhead!=YYNOCODE );
  i += iLookAhead;
  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
    if( iLookAhead>0 ){
#ifdef YYFALLBACK
      YYCODETYPE iFallback;            /* Fallback token */
      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
             && (iFallback = yyFallback[iLookAhead])!=0 ){
#ifndef NDEBUG
        if( yyTraceFILE ){
          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
        }
#endif
        return yy_find_shift_action(pParser, iFallback);
      }
#endif
#ifdef YYWILDCARD
      {
        int j = i - iLookAhead + YYWILDCARD;
        if( 
#if YY_SHIFT_MIN+YYWILDCARD<0
          j>=0 &&
#endif
#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
          j<YY_ACTTAB_COUNT &&
#endif
          yy_lookahead[j]==YYWILDCARD
        ){
#ifndef NDEBUG
          if( yyTraceFILE ){
            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
          }
#endif /* NDEBUG */
          return yy_action[j];
        }
      }
#endif /* YYWILDCARD */
    }
    return yy_default[stateno];
  }else{
    return yy_action[i];
  }
}

/*
** Find the appropriate action for a parser given the non-terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead.  If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_reduce_action(
  int stateno,              /* Current state number */
  YYCODETYPE iLookAhead     /* The look-ahead token */
){
  int i;
#ifdef YYERRORSYMBOL
  if( stateno>YY_REDUCE_COUNT ){
    return yy_default[stateno];
  }
#else
  assert( stateno<=YY_REDUCE_COUNT );
#endif
  i = yy_reduce_ofst[stateno];
  assert( i!=YY_REDUCE_USE_DFLT );
  assert( iLookAhead!=YYNOCODE );
  i += iLookAhead;
#ifdef YYERRORSYMBOL
  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
    return yy_default[stateno];
  }
#else
  assert( i>=0 && i<YY_ACTTAB_COUNT );
  assert( yy_lookahead[i]==iLookAhead );
#endif
  return yy_action[i];
}

/*
** The following routine is called if the stack overflows.
*/
static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   ParseARG_FETCH;
   yypParser->yyidx--;
#ifndef NDEBUG
   if( yyTraceFILE ){
     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   }
#endif
   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   /* Here code is inserted which will execute if the parser
   ** stack every overflows */
%%
   ParseARG_STORE; /* Suppress warning about unused %extra_argument var */
}

/*
** Perform a shift action.
*/
static void yy_shift(
  yyParser *yypParser,          /* The parser to be shifted */
  int yyNewState,               /* The new state to shift in */
  int yyMajor,                  /* The major token to shift in */
  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
){
  yyStackEntry *yytos;
  yypParser->yyidx++;
#ifdef YYTRACKMAXSTACKDEPTH
  if( yypParser->yyidx>yypParser->yyidxMax ){
    yypParser->yyidxMax = yypParser->yyidx;
  }
#endif
#if YYSTACKDEPTH>0 
  if( yypParser->yyidx>=YYSTACKDEPTH ){
    yyStackOverflow(yypParser, yypMinor);
    return;
  }
#else
  if( yypParser->yyidx>=yypParser->yystksz ){
    yyGrowStack(yypParser);
    if( yypParser->yyidx>=yypParser->yystksz ){
      yyStackOverflow(yypParser, yypMinor);
      return;
    }
  }
#endif
  yytos = &yypParser->yystack[yypParser->yyidx];
  yytos->stateno = (YYACTIONTYPE)yyNewState;
  yytos->major = (YYCODETYPE)yyMajor;
  yytos->minor = *yypMinor;
#ifndef NDEBUG
  if( yyTraceFILE && yypParser->yyidx>0 ){
    int i;
    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
    for(i=1; i<=yypParser->yyidx; i++)
      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
    fprintf(yyTraceFILE,"\n");
  }
#endif
}

/* The following table contains information about every rule that
** is used during the reduce.
*/
static const struct {
  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
} yyRuleInfo[] = {
%%
};

static void yy_accept(yyParser*);  /* Forward Declaration */

/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
*/
static void yy_reduce(
  yyParser *yypParser,         /* The parser */
  int yyruleno                 /* Number of the rule by which to reduce */
){
  int yygoto;                     /* The next state */
  int yyact;                      /* The next action */
  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
  yyStackEntry *yymsp;            /* The top of the parser's stack */
  int yysize;                     /* Amount to pop the stack */
  ParseARG_FETCH;
  yymsp = &yypParser->yystack[yypParser->yyidx];
#ifndef NDEBUG
  if( yyTraceFILE && yyruleno>=0 
        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
      yyRuleName[yyruleno]);
  }
#endif /* NDEBUG */

  /* Silence complaints from purify about yygotominor being uninitialized
  ** in some cases when it is copied into the stack after the following
  ** switch.  yygotominor is uninitialized when a rule reduces that does
  ** not set the value of its left-hand side nonterminal.  Leaving the
  ** value of the nonterminal uninitialized is utterly harmless as long
  ** as the value is never used.  So really the only thing this code
  ** accomplishes is to quieten purify.  
  **
  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
  ** without this code, their parser segfaults.  I'm not sure what there
  ** parser is doing to make this happen.  This is the second bug report
  ** from wireshark this week.  Clearly they are stressing Lemon in ways
  ** that it has not been previously stressed...  (SQLite ticket #2172)
  */
  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  yygotominor = yyzerominor;


  switch( yyruleno ){
  /* Beginning here are the reduction cases.  A typical example
  ** follows:
  **   case 0:
  **  #line <lineno> <grammarfile>
  **     { ... }           // User supplied code
  **  #line <lineno> <thisfile>
  **     break;
  */
%%
  };
  yygoto = yyRuleInfo[yyruleno].lhs;
  yysize = yyRuleInfo[yyruleno].nrhs;
  yypParser->yyidx -= yysize;
  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  if( yyact < YYNSTATE ){
#ifdef NDEBUG
    /* If we are not debugging and the reduce action popped at least
    ** one element off the stack, then we can push the new element back
    ** onto the stack here, and skip the stack overflow test in yy_shift().
    ** That gives a significant speed improvement. */
    if( yysize ){
      yypParser->yyidx++;
      yymsp -= yysize-1;
      yymsp->stateno = (YYACTIONTYPE)yyact;
      yymsp->major = (YYCODETYPE)yygoto;
      yymsp->minor = yygotominor;
    }else
#endif
    {
      yy_shift(yypParser,yyact,yygoto,&yygotominor);
    }
  }else{
    assert( yyact == YYNSTATE + YYNRULE + 1 );
    yy_accept(yypParser);
  }
}

/*
** The following code executes when the parse fails
*/
#ifndef YYNOERRORRECOVERY
static void yy_parse_failed(
  yyParser *yypParser           /* The parser */
){
  ParseARG_FETCH;
#ifndef NDEBUG
  if( yyTraceFILE ){
    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  }
#endif
  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  /* Here code is inserted which will be executed whenever the
  ** parser fails */
%%
  ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
#endif /* YYNOERRORRECOVERY */

/*
** The following code executes when a syntax error first occurs.
*/
static void yy_syntax_error(
  yyParser *yypParser,           /* The parser */
  int yymajor,                   /* The major type of the error token */
  YYMINORTYPE yyminor            /* The minor type of the error token */
){
  ParseARG_FETCH;
#define TOKEN (yyminor.yy0)
%%
  ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}

/*
** The following is executed when the parser accepts
*/
static void yy_accept(
  yyParser *yypParser           /* The parser */
){
  ParseARG_FETCH;
#ifndef NDEBUG
  if( yyTraceFILE ){
    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  }
#endif
  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  /* Here code is inserted which will be executed whenever the
  ** parser accepts */
%%
  ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}

/* The main parser program.
** The first argument is a pointer to a structure obtained from
** "ParseAlloc" which describes the current state of the parser.
** The second argument is the major token number.  The third is
** the minor token.  The fourth optional argument is whatever the
** user wants (and specified in the grammar) and is available for
** use by the action routines.
**
** Inputs:
** <ul>
** <li> A pointer to the parser (an opaque structure.)
** <li> The major token number.
** <li> The minor token number.
** <li> An option argument of a grammar-specified type.
** </ul>
**
** Outputs:
** None.
*/
void Parse(
  void *yyp,                   /* The parser */
  int yymajor,                 /* The major token code number */
  ParseTOKENTYPE yyminor       /* The value for the token */
  ParseARG_PDECL               /* Optional %extra_argument parameter */
){
  YYMINORTYPE yyminorunion;
  int yyact;            /* The parser action. */
  int yyendofinput;     /* True if we are at the end of input */
#ifdef YYERRORSYMBOL
  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
#endif
  yyParser *yypParser;  /* The parser */

  /* (re)initialize the parser, if necessary */
  yypParser = (yyParser*)yyp;
  if( yypParser->yyidx<0 ){
#if YYSTACKDEPTH<=0
    if( yypParser->yystksz <=0 ){
      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
      yyminorunion = yyzerominor;
      yyStackOverflow(yypParser, &yyminorunion);
      return;
    }
#endif
    yypParser->yyidx = 0;
    yypParser->yyerrcnt = -1;
    yypParser->yystack[0].stateno = 0;
    yypParser->yystack[0].major = 0;
  }
  yyminorunion.yy0 = yyminor;
  yyendofinput = (yymajor==0);
  ParseARG_STORE;

#ifndef NDEBUG
  if( yyTraceFILE ){
    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  }
#endif

  do{
    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
    if( yyact<YYNSTATE ){
      assert( !yyendofinput );  /* Impossible to shift the $ token */
      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
      yypParser->yyerrcnt--;
      yymajor = YYNOCODE;
    }else if( yyact < YYNSTATE + YYNRULE ){
      yy_reduce(yypParser,yyact-YYNSTATE);
    }else{
      assert( yyact == YY_ERROR_ACTION );
#ifdef YYERRORSYMBOL
      int yymx;
#endif
#ifndef NDEBUG
      if( yyTraceFILE ){
        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
      }
#endif
#ifdef YYERRORSYMBOL
      /* A syntax error has occurred.
      ** The response to an error depends upon whether or not the
      ** grammar defines an error token "ERROR".  
      **
      ** This is what we do if the grammar does define ERROR:
      **
      **  * Call the %syntax_error function.
      **
      **  * Begin popping the stack until we enter a state where
      **    it is legal to shift the error symbol, then shift
      **    the error symbol.
      **
      **  * Set the error count to three.
      **
      **  * Begin accepting and shifting new tokens.  No new error
      **    processing will occur until three tokens have been
      **    shifted successfully.
      **
      */
      if( yypParser->yyerrcnt<0 ){
        yy_syntax_error(yypParser,yymajor,yyminorunion);
      }
      yymx = yypParser->yystack[yypParser->yyidx].major;
      if( yymx==YYERRORSYMBOL || yyerrorhit ){
#ifndef NDEBUG
        if( yyTraceFILE ){
          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
             yyTracePrompt,yyTokenName[yymajor]);
        }
#endif
        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
        yymajor = YYNOCODE;
      }else{
         while(
          yypParser->yyidx >= 0 &&
          yymx != YYERRORSYMBOL &&
          (yyact = yy_find_reduce_action(
                        yypParser->yystack[yypParser->yyidx].stateno,
                        YYERRORSYMBOL)) >= YYNSTATE
        ){
          yy_pop_parser_stack(yypParser);
        }
        if( yypParser->yyidx < 0 || yymajor==0 ){
          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
          yy_parse_failed(yypParser);
          yymajor = YYNOCODE;
        }else if( yymx!=YYERRORSYMBOL ){
          YYMINORTYPE u2;
          u2.YYERRSYMDT = 0;
          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
        }
      }
      yypParser->yyerrcnt = 3;
      yyerrorhit = 1;
#elif defined(YYNOERRORRECOVERY)
      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
      ** do any kind of error recovery.  Instead, simply invoke the syntax
      ** error routine and continue going as if nothing had happened.
      **
      ** Applications can set this macro (for example inside %include) if
      ** they intend to abandon the parse upon the first syntax error seen.
      */
      yy_syntax_error(yypParser,yymajor,yyminorunion);
      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
      yymajor = YYNOCODE;
      
#else  /* YYERRORSYMBOL is not defined */
      /* This is what we do if the grammar does not define ERROR:
      **
      **  * Report an error message, and throw away the input token.
      **
      **  * If the input token is $, then fail the parse.
      **
      ** As before, subsequent error messages are suppressed until
      ** three input tokens have been successfully shifted.
      */
      if( yypParser->yyerrcnt<=0 ){
        yy_syntax_error(yypParser,yymajor,yyminorunion);
      }
      yypParser->yyerrcnt = 3;
      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
      if( yyendofinput ){
        yy_parse_failed(yypParser);
      }
      yymajor = YYNOCODE;
#endif
    }
  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  return;
}

Added src/loadext.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
** 2006 June 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to dynamically load extensions into
** the SQLite library.
**
** $Id: loadext.c,v 1.60 2009/06/03 01:24:54 drh Exp $
*/

#ifndef SQLITE_CORE
  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
#endif
#include "sqlite3ext.h"
#include "sqliteInt.h"
#include <string.h>

#ifndef SQLITE_OMIT_LOAD_EXTENSION

/*
** Some API routines are omitted when various features are
** excluded from a build of SQLite.  Substitute a NULL pointer
** for any missing APIs.
*/
#ifndef SQLITE_ENABLE_COLUMN_METADATA
# define sqlite3_column_database_name   0
# define sqlite3_column_database_name16 0
# define sqlite3_column_table_name      0
# define sqlite3_column_table_name16    0
# define sqlite3_column_origin_name     0
# define sqlite3_column_origin_name16   0
# define sqlite3_table_column_metadata  0
#endif

#ifdef SQLITE_OMIT_AUTHORIZATION
# define sqlite3_set_authorizer         0
#endif

#ifdef SQLITE_OMIT_UTF16
# define sqlite3_bind_text16            0
# define sqlite3_collation_needed16     0
# define sqlite3_column_decltype16      0
# define sqlite3_column_name16          0
# define sqlite3_column_text16          0
# define sqlite3_complete16             0
# define sqlite3_create_collation16     0
# define sqlite3_create_function16      0
# define sqlite3_errmsg16               0
# define sqlite3_open16                 0
# define sqlite3_prepare16              0
# define sqlite3_prepare16_v2           0
# define sqlite3_result_error16         0
# define sqlite3_result_text16          0
# define sqlite3_result_text16be        0
# define sqlite3_result_text16le        0
# define sqlite3_value_text16           0
# define sqlite3_value_text16be         0
# define sqlite3_value_text16le         0
# define sqlite3_column_database_name16 0
# define sqlite3_column_table_name16    0
# define sqlite3_column_origin_name16   0
#endif

#ifdef SQLITE_OMIT_COMPLETE
# define sqlite3_complete 0
# define sqlite3_complete16 0
#endif

#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
# define sqlite3_progress_handler 0
#endif

#ifdef SQLITE_OMIT_VIRTUALTABLE
# define sqlite3_create_module 0
# define sqlite3_create_module_v2 0
# define sqlite3_declare_vtab 0
#endif

#ifdef SQLITE_OMIT_SHARED_CACHE
# define sqlite3_enable_shared_cache 0
#endif

#ifdef SQLITE_OMIT_TRACE
# define sqlite3_profile       0
# define sqlite3_trace         0
#endif

#ifdef SQLITE_OMIT_GET_TABLE
# define sqlite3_free_table    0
# define sqlite3_get_table     0
#endif

#ifdef SQLITE_OMIT_INCRBLOB
#define sqlite3_bind_zeroblob  0
#define sqlite3_blob_bytes     0
#define sqlite3_blob_close     0
#define sqlite3_blob_open      0
#define sqlite3_blob_read      0
#define sqlite3_blob_write     0
#endif

/*
** The following structure contains pointers to all SQLite API routines.
** A pointer to this structure is passed into extensions when they are
** loaded so that the extension can make calls back into the SQLite
** library.
**
** When adding new APIs, add them to the bottom of this structure
** in order to preserve backwards compatibility.
**
** Extensions that use newer APIs should first call the
** sqlite3_libversion_number() to make sure that the API they
** intend to use is supported by the library.  Extensions should
** also check to make sure that the pointer to the function is
** not NULL before calling it.
*/
static const sqlite3_api_routines sqlite3Apis = {
  sqlite3_aggregate_context,
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_aggregate_count,
#else
  0,
#endif
  sqlite3_bind_blob,
  sqlite3_bind_double,
  sqlite3_bind_int,
  sqlite3_bind_int64,
  sqlite3_bind_null,
  sqlite3_bind_parameter_count,
  sqlite3_bind_parameter_index,
  sqlite3_bind_parameter_name,
  sqlite3_bind_text,
  sqlite3_bind_text16,
  sqlite3_bind_value,
  sqlite3_busy_handler,
  sqlite3_busy_timeout,
  sqlite3_changes,
  sqlite3_close,
  sqlite3_collation_needed,
  sqlite3_collation_needed16,
  sqlite3_column_blob,
  sqlite3_column_bytes,
  sqlite3_column_bytes16,
  sqlite3_column_count,
  sqlite3_column_database_name,
  sqlite3_column_database_name16,
  sqlite3_column_decltype,
  sqlite3_column_decltype16,
  sqlite3_column_double,
  sqlite3_column_int,
  sqlite3_column_int64,
  sqlite3_column_name,
  sqlite3_column_name16,
  sqlite3_column_origin_name,
  sqlite3_column_origin_name16,
  sqlite3_column_table_name,
  sqlite3_column_table_name16,
  sqlite3_column_text,
  sqlite3_column_text16,
  sqlite3_column_type,
  sqlite3_column_value,
  sqlite3_commit_hook,
  sqlite3_complete,
  sqlite3_complete16,
  sqlite3_create_collation,
  sqlite3_create_collation16,
  sqlite3_create_function,
  sqlite3_create_function16,
  sqlite3_create_module,
  sqlite3_data_count,
  sqlite3_db_handle,
  sqlite3_declare_vtab,
  sqlite3_enable_shared_cache,
  sqlite3_errcode,
  sqlite3_errmsg,
  sqlite3_errmsg16,
  sqlite3_exec,
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_expired,
#else
  0,
#endif
  sqlite3_finalize,
  sqlite3_free,
  sqlite3_free_table,
  sqlite3_get_autocommit,
  sqlite3_get_auxdata,
  sqlite3_get_table,
  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
  sqlite3_interrupt,
  sqlite3_last_insert_rowid,
  sqlite3_libversion,
  sqlite3_libversion_number,
  sqlite3_malloc,
  sqlite3_mprintf,
  sqlite3_open,
  sqlite3_open16,
  sqlite3_prepare,
  sqlite3_prepare16,
  sqlite3_profile,
  sqlite3_progress_handler,
  sqlite3_realloc,
  sqlite3_reset,
  sqlite3_result_blob,
  sqlite3_result_double,
  sqlite3_result_error,
  sqlite3_result_error16,
  sqlite3_result_int,
  sqlite3_result_int64,
  sqlite3_result_null,
  sqlite3_result_text,
  sqlite3_result_text16,
  sqlite3_result_text16be,
  sqlite3_result_text16le,
  sqlite3_result_value,
  sqlite3_rollback_hook,
  sqlite3_set_authorizer,
  sqlite3_set_auxdata,
  sqlite3_snprintf,
  sqlite3_step,
  sqlite3_table_column_metadata,
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_thread_cleanup,
#else
  0,
#endif
  sqlite3_total_changes,
  sqlite3_trace,
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_transfer_bindings,
#else
  0,
#endif
  sqlite3_update_hook,
  sqlite3_user_data,
  sqlite3_value_blob,
  sqlite3_value_bytes,
  sqlite3_value_bytes16,
  sqlite3_value_double,
  sqlite3_value_int,
  sqlite3_value_int64,
  sqlite3_value_numeric_type,
  sqlite3_value_text,
  sqlite3_value_text16,
  sqlite3_value_text16be,
  sqlite3_value_text16le,
  sqlite3_value_type,
  sqlite3_vmprintf,
  /*
  ** The original API set ends here.  All extensions can call any
  ** of the APIs above provided that the pointer is not NULL.  But
  ** before calling APIs that follow, extension should check the
  ** sqlite3_libversion_number() to make sure they are dealing with
  ** a library that is new enough to support that API.
  *************************************************************************
  */
  sqlite3_overload_function,

  /*
  ** Added after 3.3.13
  */
  sqlite3_prepare_v2,
  sqlite3_prepare16_v2,
  sqlite3_clear_bindings,

  /*
  ** Added for 3.4.1
  */
  sqlite3_create_module_v2,

  /*
  ** Added for 3.5.0
  */
  sqlite3_bind_zeroblob,
  sqlite3_blob_bytes,
  sqlite3_blob_close,
  sqlite3_blob_open,
  sqlite3_blob_read,
  sqlite3_blob_write,
  sqlite3_create_collation_v2,
  sqlite3_file_control,
  sqlite3_memory_highwater,
  sqlite3_memory_used,
#ifdef SQLITE_MUTEX_OMIT
  0, 
  0, 
  0,
  0,
  0,
#else
  sqlite3_mutex_alloc,
  sqlite3_mutex_enter,
  sqlite3_mutex_free,
  sqlite3_mutex_leave,
  sqlite3_mutex_try,
#endif
  sqlite3_open_v2,
  sqlite3_release_memory,
  sqlite3_result_error_nomem,
  sqlite3_result_error_toobig,
  sqlite3_sleep,
  sqlite3_soft_heap_limit,
  sqlite3_vfs_find,
  sqlite3_vfs_register,
  sqlite3_vfs_unregister,

  /*
  ** Added for 3.5.8
  */
  sqlite3_threadsafe,
  sqlite3_result_zeroblob,
  sqlite3_result_error_code,
  sqlite3_test_control,
  sqlite3_randomness,
  sqlite3_context_db_handle,

  /*
  ** Added for 3.6.0
  */
  sqlite3_extended_result_codes,
  sqlite3_limit,
  sqlite3_next_stmt,
  sqlite3_sql,
  sqlite3_status,
};

/*
** Attempt to load an SQLite extension library contained in the file
** zFile.  The entry point is zProc.  zProc may be 0 in which case a
** default entry point name (sqlite3_extension_init) is used.  Use
** of the default name is recommended.
**
** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
**
** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
** error message text.  The calling function should free this memory
** by calling sqlite3DbFree(db, ).
*/
static int sqlite3LoadExtension(
  sqlite3 *db,          /* Load the extension into this database connection */
  const char *zFile,    /* Name of the shared library containing extension */
  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
  char **pzErrMsg       /* Put error message here if not 0 */
){
  sqlite3_vfs *pVfs = db->pVfs;
  void *handle;
  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  char *zErrmsg = 0;
  void **aHandle;
  const int nMsg = 300;

  if( pzErrMsg ) *pzErrMsg = 0;

  /* Ticket #1863.  To avoid a creating security problems for older
  ** applications that relink against newer versions of SQLite, the
  ** ability to run load_extension is turned off by default.  One
  ** must call sqlite3_enable_load_extension() to turn on extension
  ** loading.  Otherwise you get the following error.
  */
  if( (db->flags & SQLITE_LoadExtension)==0 ){
    if( pzErrMsg ){
      *pzErrMsg = sqlite3_mprintf("not authorized");
    }
    return SQLITE_ERROR;
  }

  if( zProc==0 ){
    zProc = "sqlite3_extension_init";
  }

  handle = sqlite3OsDlOpen(pVfs, zFile);
  if( handle==0 ){
    if( pzErrMsg ){
      zErrmsg = sqlite3StackAllocZero(db, nMsg);
      if( zErrmsg ){
        sqlite3_snprintf(nMsg, zErrmsg, 
            "unable to open shared library [%s]", zFile);
        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
        sqlite3StackFree(db, zErrmsg);
      }
    }
    return SQLITE_ERROR;
  }
  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
                   sqlite3OsDlSym(pVfs, handle, zProc);
  if( xInit==0 ){
    if( pzErrMsg ){
      zErrmsg = sqlite3StackAllocZero(db, nMsg);
      if( zErrmsg ){
        sqlite3_snprintf(nMsg, zErrmsg,
            "no entry point [%s] in shared library [%s]", zProc,zFile);
        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
        sqlite3StackFree(db, zErrmsg);
      }
      sqlite3OsDlClose(pVfs, handle);
    }
    return SQLITE_ERROR;
  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
    if( pzErrMsg ){
      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
    }
    sqlite3_free(zErrmsg);
    sqlite3OsDlClose(pVfs, handle);
    return SQLITE_ERROR;
  }

  /* Append the new shared library handle to the db->aExtension array. */
  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  if( aHandle==0 ){
    return SQLITE_NOMEM;
  }
  if( db->nExtension>0 ){
    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  }
  sqlite3DbFree(db, db->aExtension);
  db->aExtension = aHandle;

  db->aExtension[db->nExtension++] = handle;
  return SQLITE_OK;
}
int sqlite3_load_extension(
  sqlite3 *db,          /* Load the extension into this database connection */
  const char *zFile,    /* Name of the shared library containing extension */
  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
  char **pzErrMsg       /* Put error message here if not 0 */
){
  int rc;
  sqlite3_mutex_enter(db->mutex);
  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** Call this routine when the database connection is closing in order
** to clean up loaded extensions
*/
void sqlite3CloseExtensions(sqlite3 *db){
  int i;
  assert( sqlite3_mutex_held(db->mutex) );
  for(i=0; i<db->nExtension; i++){
    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  }
  sqlite3DbFree(db, db->aExtension);
}

/*
** Enable or disable extension loading.  Extension loading is disabled by
** default so as not to open security holes in older applications.
*/
int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  sqlite3_mutex_enter(db->mutex);
  if( onoff ){
    db->flags |= SQLITE_LoadExtension;
  }else{
    db->flags &= ~SQLITE_LoadExtension;
  }
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}

#endif /* SQLITE_OMIT_LOAD_EXTENSION */

/*
** The auto-extension code added regardless of whether or not extension
** loading is supported.  We need a dummy sqlite3Apis pointer for that
** code if regular extension loading is not available.  This is that
** dummy pointer.
*/
#ifdef SQLITE_OMIT_LOAD_EXTENSION
static const sqlite3_api_routines sqlite3Apis = { 0 };
#endif


/*
** The following object holds the list of automatically loaded
** extensions.
**
** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
** mutex must be held while accessing this list.
*/
typedef struct sqlite3AutoExtList sqlite3AutoExtList;
static SQLITE_WSD struct sqlite3AutoExtList {
  int nExt;              /* Number of entries in aExt[] */          
  void (**aExt)(void);   /* Pointers to the extension init functions */
} sqlite3Autoext = { 0, 0 };

/* The "wsdAutoext" macro will resolve to the autoextension
** state vector.  If writable static data is unsupported on the target,
** we have to locate the state vector at run-time.  In the more common
** case where writable static data is supported, wsdStat can refer directly
** to the "sqlite3Autoext" state vector declared above.
*/
#ifdef SQLITE_OMIT_WSD
# define wsdAutoextInit \
  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
# define wsdAutoext x[0]
#else
# define wsdAutoextInit
# define wsdAutoext sqlite3Autoext
#endif


/*
** Register a statically linked extension that is automatically
** loaded by every new database connection.
*/
int sqlite3_auto_extension(void (*xInit)(void)){
  int rc = SQLITE_OK;
#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite3_initialize();
  if( rc ){
    return rc;
  }else
#endif
  {
    int i;
#if SQLITE_THREADSAFE
    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
    wsdAutoextInit;
    sqlite3_mutex_enter(mutex);
    for(i=0; i<wsdAutoext.nExt; i++){
      if( wsdAutoext.aExt[i]==xInit ) break;
    }
    if( i==wsdAutoext.nExt ){
      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
      void (**aNew)(void);
      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
      if( aNew==0 ){
        rc = SQLITE_NOMEM;
      }else{
        wsdAutoext.aExt = aNew;
        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
        wsdAutoext.nExt++;
      }
    }
    sqlite3_mutex_leave(mutex);
    assert( (rc&0xff)==rc );
    return rc;
  }
}

/*
** Reset the automatic extension loading mechanism.
*/
void sqlite3_reset_auto_extension(void){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite3_initialize()==SQLITE_OK )
#endif
  {
#if SQLITE_THREADSAFE
    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
    wsdAutoextInit;
    sqlite3_mutex_enter(mutex);
    sqlite3_free(wsdAutoext.aExt);
    wsdAutoext.aExt = 0;
    wsdAutoext.nExt = 0;
    sqlite3_mutex_leave(mutex);
  }
}

/*
** Load all automatic extensions.
**
** If anything goes wrong, set an error in the database connection.
*/
void sqlite3AutoLoadExtensions(sqlite3 *db){
  int i;
  int go = 1;
  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);

  wsdAutoextInit;
  if( wsdAutoext.nExt==0 ){
    /* Common case: early out without every having to acquire a mutex */
    return;
  }
  for(i=0; go; i++){
    char *zErrmsg;
#if SQLITE_THREADSAFE
    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
    sqlite3_mutex_enter(mutex);
    if( i>=wsdAutoext.nExt ){
      xInit = 0;
      go = 0;
    }else{
      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
              wsdAutoext.aExt[i];
    }
    sqlite3_mutex_leave(mutex);
    zErrmsg = 0;
    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
      sqlite3Error(db, SQLITE_ERROR,
            "automatic extension loading failed: %s", zErrmsg);
      go = 0;
    }
    sqlite3_free(zErrmsg);
  }
}

Added src/main.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
*/
#include "sqliteInt.h"

#ifdef SQLITE_ENABLE_FTS3
# include "fts3.h"
#endif
#ifdef SQLITE_ENABLE_RTREE
# include "rtree.h"
#endif
#ifdef SQLITE_ENABLE_ICU
# include "sqliteicu.h"
#endif

/*
** The version of the library
*/
#ifndef SQLITE_AMALGAMATION
const char sqlite3_version[] = SQLITE_VERSION;
#endif
const char *sqlite3_libversion(void){ return sqlite3_version; }
const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }

#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** If the following function pointer is not NULL and if
** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
** I/O active are written using this function.  These messages
** are intended for debugging activity only.
*/
void (*sqlite3IoTrace)(const char*, ...) = 0;
#endif

/*
** If the following global variable points to a string which is the
** name of a directory, then that directory will be used to store
** temporary files.
**
** See also the "PRAGMA temp_store_directory" SQL command.
*/
char *sqlite3_temp_directory = 0;

/*
** Initialize SQLite.  
**
** This routine must be called to initialize the memory allocation,
** VFS, and mutex subsystems prior to doing any serious work with
** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
** this routine will be called automatically by key routines such as
** sqlite3_open().  
**
** This routine is a no-op except on its very first call for the process,
** or for the first call after a call to sqlite3_shutdown.
**
** The first thread to call this routine runs the initialization to
** completion.  If subsequent threads call this routine before the first
** thread has finished the initialization process, then the subsequent
** threads must block until the first thread finishes with the initialization.
**
** The first thread might call this routine recursively.  Recursive
** calls to this routine should not block, of course.  Otherwise the
** initialization process would never complete.
**
** Let X be the first thread to enter this routine.  Let Y be some other
** thread.  Then while the initial invocation of this routine by X is
** incomplete, it is required that:
**
**    *  Calls to this routine from Y must block until the outer-most
**       call by X completes.
**
**    *  Recursive calls to this routine from thread X return immediately
**       without blocking.
*/
int sqlite3_initialize(void){
  sqlite3_mutex *pMaster;                      /* The main static mutex */
  int rc;                                      /* Result code */

#ifdef SQLITE_OMIT_WSD
  rc = sqlite3_wsd_init(4096, 24);
  if( rc!=SQLITE_OK ){
    return rc;
  }
#endif

  /* If SQLite is already completely initialized, then this call
  ** to sqlite3_initialize() should be a no-op.  But the initialization
  ** must be complete.  So isInit must not be set until the very end
  ** of this routine.
  */
  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;

  /* Make sure the mutex subsystem is initialized.  If unable to 
  ** initialize the mutex subsystem, return early with the error.
  ** If the system is so sick that we are unable to allocate a mutex,
  ** there is not much SQLite is going to be able to do.
  **
  ** The mutex subsystem must take care of serializing its own
  ** initialization.
  */
  rc = sqlite3MutexInit();
  if( rc ) return rc;

  /* Initialize the malloc() system and the recursive pInitMutex mutex.
  ** This operation is protected by the STATIC_MASTER mutex.  Note that
  ** MutexAlloc() is called for a static mutex prior to initializing the
  ** malloc subsystem - this implies that the allocation of a static
  ** mutex must not require support from the malloc subsystem.
  */
  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  sqlite3_mutex_enter(pMaster);
  sqlite3GlobalConfig.isMutexInit = 1;
  if( !sqlite3GlobalConfig.isMallocInit ){
    rc = sqlite3MallocInit();
  }
  if( rc==SQLITE_OK ){
    sqlite3GlobalConfig.isMallocInit = 1;
    if( !sqlite3GlobalConfig.pInitMutex ){
      sqlite3GlobalConfig.pInitMutex =
           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
        rc = SQLITE_NOMEM;
      }
    }
  }
  if( rc==SQLITE_OK ){
    sqlite3GlobalConfig.nRefInitMutex++;
  }
  sqlite3_mutex_leave(pMaster);

  /* If rc is not SQLITE_OK at this point, then either the malloc
  ** subsystem could not be initialized or the system failed to allocate
  ** the pInitMutex mutex. Return an error in either case.  */
  if( rc!=SQLITE_OK ){
    return rc;
  }

  /* Do the rest of the initialization under the recursive mutex so
  ** that we will be able to handle recursive calls into
  ** sqlite3_initialize().  The recursive calls normally come through
  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  ** recursive calls might also be possible.
  */
  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
    sqlite3GlobalConfig.inProgress = 1;
    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
    sqlite3RegisterGlobalFunctions();
    if( sqlite3GlobalConfig.isPCacheInit==0 ){
      rc = sqlite3PcacheInitialize();
    }
    if( rc==SQLITE_OK ){
      sqlite3GlobalConfig.isPCacheInit = 1;
      rc = sqlite3OsInit();
    }
    if( rc==SQLITE_OK ){
      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
      sqlite3GlobalConfig.isInit = 1;
    }
    sqlite3GlobalConfig.inProgress = 0;
  }
  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);

  /* Go back under the static mutex and clean up the recursive
  ** mutex to prevent a resource leak.
  */
  sqlite3_mutex_enter(pMaster);
  sqlite3GlobalConfig.nRefInitMutex--;
  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
    sqlite3GlobalConfig.pInitMutex = 0;
  }
  sqlite3_mutex_leave(pMaster);

  /* The following is just a sanity check to make sure SQLite has
  ** been compiled correctly.  It is important to run this code, but
  ** we don't want to run it too often and soak up CPU cycles for no
  ** reason.  So we run it once during initialization.
  */
#ifndef NDEBUG
#ifndef SQLITE_OMIT_FLOATING_POINT
  /* This section of code's only "output" is via assert() statements. */
  if ( rc==SQLITE_OK ){
    u64 x = (((u64)1)<<63)-1;
    double y;
    assert(sizeof(x)==8);
    assert(sizeof(x)==sizeof(y));
    memcpy(&y, &x, 8);
    assert( sqlite3IsNaN(y) );
  }
#endif
#endif

  return rc;
}

/*
** Undo the effects of sqlite3_initialize().  Must not be called while
** there are outstanding database connections or memory allocations or
** while any part of SQLite is otherwise in use in any thread.  This
** routine is not threadsafe.  But it is safe to invoke this routine
** on when SQLite is already shut down.  If SQLite is already shut down
** when this routine is invoked, then this routine is a harmless no-op.
*/
int sqlite3_shutdown(void){
  if( sqlite3GlobalConfig.isInit ){
    sqlite3_os_end();
    sqlite3_reset_auto_extension();
    sqlite3GlobalConfig.isInit = 0;
  }
  if( sqlite3GlobalConfig.isPCacheInit ){
    sqlite3PcacheShutdown();
    sqlite3GlobalConfig.isPCacheInit = 0;
  }
  if( sqlite3GlobalConfig.isMallocInit ){
    sqlite3MallocEnd();
    sqlite3GlobalConfig.isMallocInit = 0;
  }
  if( sqlite3GlobalConfig.isMutexInit ){
    sqlite3MutexEnd();
    sqlite3GlobalConfig.isMutexInit = 0;
  }

  return SQLITE_OK;
}

/*
** This API allows applications to modify the global configuration of
** the SQLite library at run-time.
**
** This routine should only be called when there are no outstanding
** database connections or memory allocations.  This routine is not
** threadsafe.  Failure to heed these warnings can lead to unpredictable
** behavior.
*/
int sqlite3_config(int op, ...){
  va_list ap;
  int rc = SQLITE_OK;

  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  ** the SQLite library is in use. */
  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;

  va_start(ap, op);
  switch( op ){

    /* Mutex configuration options are only available in a threadsafe
    ** compile. 
    */
#if SQLITE_THREADSAFE
    case SQLITE_CONFIG_SINGLETHREAD: {
      /* Disable all mutexing */
      sqlite3GlobalConfig.bCoreMutex = 0;
      sqlite3GlobalConfig.bFullMutex = 0;
      break;
    }
    case SQLITE_CONFIG_MULTITHREAD: {
      /* Disable mutexing of database connections */
      /* Enable mutexing of core data structures */
      sqlite3GlobalConfig.bCoreMutex = 1;
      sqlite3GlobalConfig.bFullMutex = 0;
      break;
    }
    case SQLITE_CONFIG_SERIALIZED: {
      /* Enable all mutexing */
      sqlite3GlobalConfig.bCoreMutex = 1;
      sqlite3GlobalConfig.bFullMutex = 1;
      break;
    }
    case SQLITE_CONFIG_MUTEX: {
      /* Specify an alternative mutex implementation */
      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
      break;
    }
    case SQLITE_CONFIG_GETMUTEX: {
      /* Retrieve the current mutex implementation */
      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
      break;
    }
#endif


    case SQLITE_CONFIG_MALLOC: {
      /* Specify an alternative malloc implementation */
      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
      break;
    }
    case SQLITE_CONFIG_GETMALLOC: {
      /* Retrieve the current malloc() implementation */
      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
      break;
    }
    case SQLITE_CONFIG_MEMSTATUS: {
      /* Enable or disable the malloc status collection */
      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
      break;
    }
    case SQLITE_CONFIG_SCRATCH: {
      /* Designate a buffer for scratch memory space */
      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
      break;
    }
    case SQLITE_CONFIG_PAGECACHE: {
      /* Designate a buffer for page cache memory space */
      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
      sqlite3GlobalConfig.szPage = va_arg(ap, int);
      sqlite3GlobalConfig.nPage = va_arg(ap, int);
      break;
    }

    case SQLITE_CONFIG_PCACHE: {
      /* Specify an alternative page cache implementation */
      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
      break;
    }

    case SQLITE_CONFIG_GETPCACHE: {
      if( sqlite3GlobalConfig.pcache.xInit==0 ){
        sqlite3PCacheSetDefault();
      }
      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
      break;
    }

#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
    case SQLITE_CONFIG_HEAP: {
      /* Designate a buffer for heap memory space */
      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
      sqlite3GlobalConfig.mnReq = va_arg(ap, int);

      if( sqlite3GlobalConfig.pHeap==0 ){
        /* If the heap pointer is NULL, then restore the malloc implementation
        ** back to NULL pointers too.  This will cause the malloc to go
        ** back to its default implementation when sqlite3_initialize() is
        ** run.
        */
        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
      }else{
        /* The heap pointer is not NULL, then install one of the
        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
        ** ENABLE_MEMSYS5 is defined, return an error.
        */
#ifdef SQLITE_ENABLE_MEMSYS3
        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
#endif
#ifdef SQLITE_ENABLE_MEMSYS5
        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
#endif
      }
      break;
    }
#endif

    case SQLITE_CONFIG_LOOKASIDE: {
      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
      break;
    }

    default: {
      rc = SQLITE_ERROR;
      break;
    }
  }
  va_end(ap);
  return rc;
}

/*
** Set up the lookaside buffers for a database connection.
** Return SQLITE_OK on success.  
** If lookaside is already active, return SQLITE_BUSY.
**
** The sz parameter is the number of bytes in each lookaside slot.
** The cnt parameter is the number of slots.  If pStart is NULL the
** space for the lookaside memory is obtained from sqlite3_malloc().
** If pStart is not NULL then it is sz*cnt bytes of memory to use for
** the lookaside memory.
*/
static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  void *pStart;
  if( db->lookaside.nOut ){
    return SQLITE_BUSY;
  }
  /* Free any existing lookaside buffer for this handle before
  ** allocating a new one so we don't have to have space for 
  ** both at the same time.
  */
  if( db->lookaside.bMalloced ){
    sqlite3_free(db->lookaside.pStart);
  }
  /* The size of a lookaside slot needs to be larger than a pointer
  ** to be useful.
  */
  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  if( cnt<0 ) cnt = 0;
  if( sz==0 || cnt==0 ){
    sz = 0;
    pStart = 0;
  }else if( pBuf==0 ){
    sz = ROUND8(sz);
    sqlite3BeginBenignMalloc();
    pStart = sqlite3Malloc( sz*cnt );
    sqlite3EndBenignMalloc();
  }else{
    sz = ROUNDDOWN8(sz);
    pStart = pBuf;
  }
  db->lookaside.pStart = pStart;
  db->lookaside.pFree = 0;
  db->lookaside.sz = (u16)sz;
  if( pStart ){
    int i;
    LookasideSlot *p;
    assert( sz > (int)sizeof(LookasideSlot*) );
    p = (LookasideSlot*)pStart;
    for(i=cnt-1; i>=0; i--){
      p->pNext = db->lookaside.pFree;
      db->lookaside.pFree = p;
      p = (LookasideSlot*)&((u8*)p)[sz];
    }
    db->lookaside.pEnd = p;
    db->lookaside.bEnabled = 1;
    db->lookaside.bMalloced = pBuf==0 ?1:0;
  }else{
    db->lookaside.pEnd = 0;
    db->lookaside.bEnabled = 0;
    db->lookaside.bMalloced = 0;
  }
  return SQLITE_OK;
}

/*
** Return the mutex associated with a database connection.
*/
sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  return db->mutex;
}

/*
** Configuration settings for an individual database connection
*/
int sqlite3_db_config(sqlite3 *db, int op, ...){
  va_list ap;
  int rc;
  va_start(ap, op);
  switch( op ){
    case SQLITE_DBCONFIG_LOOKASIDE: {
      void *pBuf = va_arg(ap, void*);
      int sz = va_arg(ap, int);
      int cnt = va_arg(ap, int);
      rc = setupLookaside(db, pBuf, sz, cnt);
      break;
    }
    default: {
      rc = SQLITE_ERROR;
      break;
    }
  }
  va_end(ap);
  return rc;
}


/*
** Return true if the buffer z[0..n-1] contains all spaces.
*/
static int allSpaces(const char *z, int n){
  while( n>0 && z[n-1]==' ' ){ n--; }
  return n==0;
}

/*
** This is the default collating function named "BINARY" which is always
** available.
**
** If the padFlag argument is not NULL then space padding at the end
** of strings is ignored.  This implements the RTRIM collation.
*/
static int binCollFunc(
  void *padFlag,
  int nKey1, const void *pKey1,
  int nKey2, const void *pKey2
){
  int rc, n;
  n = nKey1<nKey2 ? nKey1 : nKey2;
  rc = memcmp(pKey1, pKey2, n);
  if( rc==0 ){
    if( padFlag
     && allSpaces(((char*)pKey1)+n, nKey1-n)
     && allSpaces(((char*)pKey2)+n, nKey2-n)
    ){
      /* Leave rc unchanged at 0 */
    }else{
      rc = nKey1 - nKey2;
    }
  }
  return rc;
}

/*
** Another built-in collating sequence: NOCASE. 
**
** This collating sequence is intended to be used for "case independant
** comparison". SQLite's knowledge of upper and lower case equivalents
** extends only to the 26 characters used in the English language.
**
** At the moment there is only a UTF-8 implementation.
*/
static int nocaseCollatingFunc(
  void *NotUsed,
  int nKey1, const void *pKey1,
  int nKey2, const void *pKey2
){
  int r = sqlite3StrNICmp(
      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  UNUSED_PARAMETER(NotUsed);
  if( 0==r ){
    r = nKey1-nKey2;
  }
  return r;
}

/*
** Return the ROWID of the most recent insert
*/
sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  return db->lastRowid;
}

/*
** Return the number of changes in the most recent call to sqlite3_exec().
*/
int sqlite3_changes(sqlite3 *db){
  return db->nChange;
}

/*
** Return the number of changes since the database handle was opened.
*/
int sqlite3_total_changes(sqlite3 *db){
  return db->nTotalChange;
}

/*
** Close all open savepoints. This function only manipulates fields of the
** database handle object, it does not close any savepoints that may be open
** at the b-tree/pager level.
*/
void sqlite3CloseSavepoints(sqlite3 *db){
  while( db->pSavepoint ){
    Savepoint *pTmp = db->pSavepoint;
    db->pSavepoint = pTmp->pNext;
    sqlite3DbFree(db, pTmp);
  }
  db->nSavepoint = 0;
  db->nStatement = 0;
  db->isTransactionSavepoint = 0;
}

/*
** Close an existing SQLite database
*/
int sqlite3_close(sqlite3 *db){
  HashElem *i;
  int j;

  if( !db ){
    return SQLITE_OK;
  }
  if( !sqlite3SafetyCheckSickOrOk(db) ){
    return SQLITE_MISUSE;
  }
  sqlite3_mutex_enter(db->mutex);

  sqlite3ResetInternalSchema(db, 0);

  /* If a transaction is open, the ResetInternalSchema() call above
  ** will not have called the xDisconnect() method on any virtual
  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  ** call will do so. We need to do this before the check for active
  ** SQL statements below, as the v-table implementation may be storing
  ** some prepared statements internally.
  */
  sqlite3VtabRollback(db);

  /* If there are any outstanding VMs, return SQLITE_BUSY. */
  if( db->pVdbe ){
    sqlite3Error(db, SQLITE_BUSY, 
        "unable to close due to unfinalised statements");
    sqlite3_mutex_leave(db->mutex);
    return SQLITE_BUSY;
  }
  assert( sqlite3SafetyCheckSickOrOk(db) );

  for(j=0; j<db->nDb; j++){
    Btree *pBt = db->aDb[j].pBt;
    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
      sqlite3Error(db, SQLITE_BUSY, 
          "unable to close due to unfinished backup operation");
      sqlite3_mutex_leave(db->mutex);
      return SQLITE_BUSY;
    }
  }

  /* Free any outstanding Savepoint structures. */
  sqlite3CloseSavepoints(db);

  for(j=0; j<db->nDb; j++){
    struct Db *pDb = &db->aDb[j];
    if( pDb->pBt ){
      sqlite3BtreeClose(pDb->pBt);
      pDb->pBt = 0;
      if( j!=1 ){
        pDb->pSchema = 0;
      }
    }
  }
  sqlite3ResetInternalSchema(db, 0);

  /* Tell the code in notify.c that the connection no longer holds any
  ** locks and does not require any further unlock-notify callbacks.
  */
  sqlite3ConnectionClosed(db);

  assert( db->nDb<=2 );
  assert( db->aDb==db->aDbStatic );
  for(j=0; j<ArraySize(db->aFunc.a); j++){
    FuncDef *pNext, *pHash, *p;
    for(p=db->aFunc.a[j]; p; p=pHash){
      pHash = p->pHash;
      while( p ){
        pNext = p->pNext;
        sqlite3DbFree(db, p);
        p = pNext;
      }
    }
  }
  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
    /* Invoke any destructors registered for collation sequence user data. */
    for(j=0; j<3; j++){
      if( pColl[j].xDel ){
        pColl[j].xDel(pColl[j].pUser);
      }
    }
    sqlite3DbFree(db, pColl);
  }
  sqlite3HashClear(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
    Module *pMod = (Module *)sqliteHashData(i);
    if( pMod->xDestroy ){
      pMod->xDestroy(pMod->pAux);
    }
    sqlite3DbFree(db, pMod);
  }
  sqlite3HashClear(&db->aModule);
#endif

  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  if( db->pErr ){
    sqlite3ValueFree(db->pErr);
  }
  sqlite3CloseExtensions(db);

  db->magic = SQLITE_MAGIC_ERROR;

  /* The temp-database schema is allocated differently from the other schema
  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  ** So it needs to be freed here. Todo: Why not roll the temp schema into
  ** the same sqliteMalloc() as the one that allocates the database 
  ** structure?
  */
  sqlite3DbFree(db, db->aDb[1].pSchema);
  sqlite3_mutex_leave(db->mutex);
  db->magic = SQLITE_MAGIC_CLOSED;
  sqlite3_mutex_free(db->mutex);
  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
  if( db->lookaside.bMalloced ){
    sqlite3_free(db->lookaside.pStart);
  }
  sqlite3_free(db);
  return SQLITE_OK;
}

/*
** Rollback all database files.
*/
void sqlite3RollbackAll(sqlite3 *db){
  int i;
  int inTrans = 0;
  assert( sqlite3_mutex_held(db->mutex) );
  sqlite3BeginBenignMalloc();
  for(i=0; i<db->nDb; i++){
    if( db->aDb[i].pBt ){
      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
        inTrans = 1;
      }
      sqlite3BtreeRollback(db->aDb[i].pBt);
      db->aDb[i].inTrans = 0;
    }
  }
  sqlite3VtabRollback(db);
  sqlite3EndBenignMalloc();

  if( db->flags&SQLITE_InternChanges ){
    sqlite3ExpirePreparedStatements(db);
    sqlite3ResetInternalSchema(db, 0);
  }

  /* Any deferred constraint violations have now been resolved. */
  db->nDeferredCons = 0;

  /* If one has been configured, invoke the rollback-hook callback */
  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
    db->xRollbackCallback(db->pRollbackArg);
  }
}

/*
** Return a static string that describes the kind of error specified in the
** argument.
*/
const char *sqlite3ErrStr(int rc){
  static const char* const aMsg[] = {
    /* SQLITE_OK          */ "not an error",
    /* SQLITE_ERROR       */ "SQL logic error or missing database",
    /* SQLITE_INTERNAL    */ 0,
    /* SQLITE_PERM        */ "access permission denied",
    /* SQLITE_ABORT       */ "callback requested query abort",
    /* SQLITE_BUSY        */ "database is locked",
    /* SQLITE_LOCKED      */ "database table is locked",
    /* SQLITE_NOMEM       */ "out of memory",
    /* SQLITE_READONLY    */ "attempt to write a readonly database",
    /* SQLITE_INTERRUPT   */ "interrupted",
    /* SQLITE_IOERR       */ "disk I/O error",
    /* SQLITE_CORRUPT     */ "database disk image is malformed",
    /* SQLITE_NOTFOUND    */ 0,
    /* SQLITE_FULL        */ "database or disk is full",
    /* SQLITE_CANTOPEN    */ "unable to open database file",
    /* SQLITE_PROTOCOL    */ 0,
    /* SQLITE_EMPTY       */ "table contains no data",
    /* SQLITE_SCHEMA      */ "database schema has changed",
    /* SQLITE_TOOBIG      */ "string or blob too big",
    /* SQLITE_CONSTRAINT  */ "constraint failed",
    /* SQLITE_MISMATCH    */ "datatype mismatch",
    /* SQLITE_MISUSE      */ "library routine called out of sequence",
    /* SQLITE_NOLFS       */ "large file support is disabled",
    /* SQLITE_AUTH        */ "authorization denied",
    /* SQLITE_FORMAT      */ "auxiliary database format error",
    /* SQLITE_RANGE       */ "bind or column index out of range",
    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
  };
  rc &= 0xff;
  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
    return aMsg[rc];
  }else{
    return "unknown error";
  }
}

/*
** This routine implements a busy callback that sleeps and tries
** again until a timeout value is reached.  The timeout value is
** an integer number of milliseconds passed in as the first
** argument.
*/
static int sqliteDefaultBusyCallback(
 void *ptr,               /* Database connection */
 int count                /* Number of times table has been busy */
){
#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  static const u8 delays[] =
     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
  static const u8 totals[] =
     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
# define NDELAY (sizeof(delays)/sizeof(delays[0]))
  sqlite3 *db = (sqlite3 *)ptr;
  int timeout = db->busyTimeout;
  int delay, prior;

  assert( count>=0 );
  if( count < NDELAY ){
    delay = delays[count];
    prior = totals[count];
  }else{
    delay = delays[NDELAY-1];
    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  }
  if( prior + delay > timeout ){
    delay = timeout - prior;
    if( delay<=0 ) return 0;
  }
  sqlite3OsSleep(db->pVfs, delay*1000);
  return 1;
#else
  sqlite3 *db = (sqlite3 *)ptr;
  int timeout = ((sqlite3 *)ptr)->busyTimeout;
  if( (count+1)*1000 > timeout ){
    return 0;
  }
  sqlite3OsSleep(db->pVfs, 1000000);
  return 1;
#endif
}

/*
** Invoke the given busy handler.
**
** This routine is called when an operation failed with a lock.
** If this routine returns non-zero, the lock is retried.  If it
** returns 0, the operation aborts with an SQLITE_BUSY error.
*/
int sqlite3InvokeBusyHandler(BusyHandler *p){
  int rc;
  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  rc = p->xFunc(p->pArg, p->nBusy);
  if( rc==0 ){
    p->nBusy = -1;
  }else{
    p->nBusy++;
  }
  return rc; 
}

/*
** This routine sets the busy callback for an Sqlite database to the
** given callback function with the given argument.
*/
int sqlite3_busy_handler(
  sqlite3 *db,
  int (*xBusy)(void*,int),
  void *pArg
){
  sqlite3_mutex_enter(db->mutex);
  db->busyHandler.xFunc = xBusy;
  db->busyHandler.pArg = pArg;
  db->busyHandler.nBusy = 0;
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}

#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
/*
** This routine sets the progress callback for an Sqlite database to the
** given callback function with the given argument. The progress callback will
** be invoked every nOps opcodes.
*/
void sqlite3_progress_handler(
  sqlite3 *db, 
  int nOps,
  int (*xProgress)(void*), 
  void *pArg
){
  sqlite3_mutex_enter(db->mutex);
  if( nOps>0 ){
    db->xProgress = xProgress;
    db->nProgressOps = nOps;
    db->pProgressArg = pArg;
  }else{
    db->xProgress = 0;
    db->nProgressOps = 0;
    db->pProgressArg = 0;
  }
  sqlite3_mutex_leave(db->mutex);
}
#endif


/*
** This routine installs a default busy handler that waits for the
** specified number of milliseconds before returning 0.
*/
int sqlite3_busy_timeout(sqlite3 *db, int ms){
  if( ms>0 ){
    db->busyTimeout = ms;
    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  }else{
    sqlite3_busy_handler(db, 0, 0);
  }
  return SQLITE_OK;
}

/*
** Cause any pending operation to stop at its earliest opportunity.
*/
void sqlite3_interrupt(sqlite3 *db){
  db->u1.isInterrupted = 1;
}


/*
** This function is exactly the same as sqlite3_create_function(), except
** that it is designed to be called by internal code. The difference is
** that if a malloc() fails in sqlite3_create_function(), an error code
** is returned and the mallocFailed flag cleared. 
*/
int sqlite3CreateFunc(
  sqlite3 *db,
  const char *zFunctionName,
  int nArg,
  int enc,
  void *pUserData,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  void (*xFinal)(sqlite3_context*)
){
  FuncDef *p;
  int nName;

  assert( sqlite3_mutex_held(db->mutex) );
  if( zFunctionName==0 ||
      (xFunc && (xFinal || xStep)) || 
      (!xFunc && (xFinal && !xStep)) ||
      (!xFunc && (!xFinal && xStep)) ||
      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
    return SQLITE_MISUSE;
  }
  
#ifndef SQLITE_OMIT_UTF16
  /* If SQLITE_UTF16 is specified as the encoding type, transform this
  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  **
  ** If SQLITE_ANY is specified, add three versions of the function
  ** to the hash table.
  */
  if( enc==SQLITE_UTF16 ){
    enc = SQLITE_UTF16NATIVE;
  }else if( enc==SQLITE_ANY ){
    int rc;
    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
         pUserData, xFunc, xStep, xFinal);
    if( rc==SQLITE_OK ){
      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
          pUserData, xFunc, xStep, xFinal);
    }
    if( rc!=SQLITE_OK ){
      return rc;
    }
    enc = SQLITE_UTF16BE;
  }
#else
  enc = SQLITE_UTF8;
#endif
  
  /* Check if an existing function is being overridden or deleted. If so,
  ** and there are active VMs, then return SQLITE_BUSY. If a function
  ** is being overridden/deleted but there are no active VMs, allow the
  ** operation to continue but invalidate all precompiled statements.
  */
  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
    if( db->activeVdbeCnt ){
      sqlite3Error(db, SQLITE_BUSY, 
        "unable to delete/modify user-function due to active statements");
      assert( !db->mallocFailed );
      return SQLITE_BUSY;
    }else{
      sqlite3ExpirePreparedStatements(db);
    }
  }

  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  assert(p || db->mallocFailed);
  if( !p ){
    return SQLITE_NOMEM;
  }
  p->flags = 0;
  p->xFunc = xFunc;
  p->xStep = xStep;
  p->xFinalize = xFinal;
  p->pUserData = pUserData;
  p->nArg = (u16)nArg;
  return SQLITE_OK;
}

/*
** Create new user functions.
*/
int sqlite3_create_function(
  sqlite3 *db,
  const char *zFunctionName,
  int nArg,
  int enc,
  void *p,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  void (*xFinal)(sqlite3_context*)
){
  int rc;
  sqlite3_mutex_enter(db->mutex);
  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

#ifndef SQLITE_OMIT_UTF16
int sqlite3_create_function16(
  sqlite3 *db,
  const void *zFunctionName,
  int nArg,
  int eTextRep,
  void *p,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  void (*xFinal)(sqlite3_context*)
){
  int rc;
  char *zFunc8;
  sqlite3_mutex_enter(db->mutex);
  assert( !db->mallocFailed );
  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
  sqlite3DbFree(db, zFunc8);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}
#endif


/*
** Declare that a function has been overloaded by a virtual table.
**
** If the function already exists as a regular global function, then
** this routine is a no-op.  If the function does not exist, then create
** a new one that always throws a run-time error.  
**
** When virtual tables intend to provide an overloaded function, they
** should call this routine to make sure the global function exists.
** A global function must exist in order for name resolution to work
** properly.
*/
int sqlite3_overload_function(
  sqlite3 *db,
  const char *zName,
  int nArg
){
  int nName = sqlite3Strlen30(zName);
  int rc;
  sqlite3_mutex_enter(db->mutex);
  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
                      0, sqlite3InvalidFunction, 0, 0);
  }
  rc = sqlite3ApiExit(db, SQLITE_OK);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

#ifndef SQLITE_OMIT_TRACE
/*
** Register a trace function.  The pArg from the previously registered trace
** is returned.  
**
** A NULL trace function means that no tracing is executes.  A non-NULL
** trace is a pointer to a function that is invoked at the start of each
** SQL statement.
*/
void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  void *pOld;
  sqlite3_mutex_enter(db->mutex);
  pOld = db->pTraceArg;
  db->xTrace = xTrace;
  db->pTraceArg = pArg;
  sqlite3_mutex_leave(db->mutex);
  return pOld;
}
/*
** Register a profile function.  The pArg from the previously registered 
** profile function is returned.  
**
** A NULL profile function means that no profiling is executes.  A non-NULL
** profile is a pointer to a function that is invoked at the conclusion of
** each SQL statement that is run.
*/
void *sqlite3_profile(
  sqlite3 *db,
  void (*xProfile)(void*,const char*,sqlite_uint64),
  void *pArg
){
  void *pOld;
  sqlite3_mutex_enter(db->mutex);
  pOld = db->pProfileArg;
  db->xProfile = xProfile;
  db->pProfileArg = pArg;
  sqlite3_mutex_leave(db->mutex);
  return pOld;
}
#endif /* SQLITE_OMIT_TRACE */

/*** EXPERIMENTAL ***
**
** Register a function to be invoked when a transaction comments.
** If the invoked function returns non-zero, then the commit becomes a
** rollback.
*/
void *sqlite3_commit_hook(
  sqlite3 *db,              /* Attach the hook to this database */
  int (*xCallback)(void*),  /* Function to invoke on each commit */
  void *pArg                /* Argument to the function */
){
  void *pOld;
  sqlite3_mutex_enter(db->mutex);
  pOld = db->pCommitArg;
  db->xCommitCallback = xCallback;
  db->pCommitArg = pArg;
  sqlite3_mutex_leave(db->mutex);
  return pOld;
}

/*
** Register a callback to be invoked each time a row is updated,
** inserted or deleted using this database connection.
*/
void *sqlite3_update_hook(
  sqlite3 *db,              /* Attach the hook to this database */
  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  void *pArg                /* Argument to the function */
){
  void *pRet;
  sqlite3_mutex_enter(db->mutex);
  pRet = db->pUpdateArg;
  db->xUpdateCallback = xCallback;
  db->pUpdateArg = pArg;
  sqlite3_mutex_leave(db->mutex);
  return pRet;
}

/*
** Register a callback to be invoked each time a transaction is rolled
** back by this database connection.
*/
void *sqlite3_rollback_hook(
  sqlite3 *db,              /* Attach the hook to this database */
  void (*xCallback)(void*), /* Callback function */
  void *pArg                /* Argument to the function */
){
  void *pRet;
  sqlite3_mutex_enter(db->mutex);
  pRet = db->pRollbackArg;
  db->xRollbackCallback = xCallback;
  db->pRollbackArg = pArg;
  sqlite3_mutex_leave(db->mutex);
  return pRet;
}

/*
** This function returns true if main-memory should be used instead of
** a temporary file for transient pager files and statement journals.
** The value returned depends on the value of db->temp_store (runtime
** parameter) and the compile time value of SQLITE_TEMP_STORE. The
** following table describes the relationship between these two values
** and this functions return value.
**
**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
**   -----------------     --------------     ------------------------------
**   0                     any                file      (return 0)
**   1                     1                  file      (return 0)
**   1                     2                  memory    (return 1)
**   1                     0                  file      (return 0)
**   2                     1                  file      (return 0)
**   2                     2                  memory    (return 1)
**   2                     0                  memory    (return 1)
**   3                     any                memory    (return 1)
*/
int sqlite3TempInMemory(const sqlite3 *db){
#if SQLITE_TEMP_STORE==1
  return ( db->temp_store==2 );
#endif
#if SQLITE_TEMP_STORE==2
  return ( db->temp_store!=1 );
#endif
#if SQLITE_TEMP_STORE==3
  return 1;
#endif
#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  return 0;
#endif
}

/*
** This routine is called to create a connection to a database BTree
** driver.  If zFilename is the name of a file, then that file is
** opened and used.  If zFilename is the magic name ":memory:" then
** the database is stored in memory (and is thus forgotten as soon as
** the connection is closed.)  If zFilename is NULL then the database
** is a "virtual" database for transient use only and is deleted as
** soon as the connection is closed.
**
** A virtual database can be either a disk file (that is automatically
** deleted when the file is closed) or it an be held entirely in memory.
** The sqlite3TempInMemory() function is used to determine which.
*/
int sqlite3BtreeFactory(
  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
  const char *zFilename,    /* Name of the file containing the BTree database */
  int omitJournal,          /* if TRUE then do not journal this file */
  int nCache,               /* How many pages in the page cache */
  int vfsFlags,             /* Flags passed through to vfsOpen */
  Btree **ppBtree           /* Pointer to new Btree object written here */
){
  int btFlags = 0;
  int rc;
  
  assert( sqlite3_mutex_held(db->mutex) );
  assert( ppBtree != 0);
  if( omitJournal ){
    btFlags |= BTREE_OMIT_JOURNAL;
  }
  if( db->flags & SQLITE_NoReadlock ){
    btFlags |= BTREE_NO_READLOCK;
  }
#ifndef SQLITE_OMIT_MEMORYDB
  if( zFilename==0 && sqlite3TempInMemory(db) ){
    zFilename = ":memory:";
  }
#endif

  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  }
  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);

  /* If the B-Tree was successfully opened, set the pager-cache size to the
  ** default value. Except, if the call to BtreeOpen() returned a handle
  ** open on an existing shared pager-cache, do not change the pager-cache 
  ** size.
  */
  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
  }
  return rc;
}

/*
** Return UTF-8 encoded English language explanation of the most recent
** error.
*/
const char *sqlite3_errmsg(sqlite3 *db){
  const char *z;
  if( !db ){
    return sqlite3ErrStr(SQLITE_NOMEM);
  }
  if( !sqlite3SafetyCheckSickOrOk(db) ){
    return sqlite3ErrStr(SQLITE_MISUSE);
  }
  sqlite3_mutex_enter(db->mutex);
  if( db->mallocFailed ){
    z = sqlite3ErrStr(SQLITE_NOMEM);
  }else{
    z = (char*)sqlite3_value_text(db->pErr);
    assert( !db->mallocFailed );
    if( z==0 ){
      z = sqlite3ErrStr(db->errCode);
    }
  }
  sqlite3_mutex_leave(db->mutex);
  return z;
}

#ifndef SQLITE_OMIT_UTF16
/*
** Return UTF-16 encoded English language explanation of the most recent
** error.
*/
const void *sqlite3_errmsg16(sqlite3 *db){
  static const u16 outOfMem[] = {
    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  };
  static const u16 misuse[] = {
    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
    'c', 'a', 'l', 'l', 'e', 'd', ' ', 
    'o', 'u', 't', ' ', 
    'o', 'f', ' ', 
    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  };

  const void *z;
  if( !db ){
    return (void *)outOfMem;
  }
  if( !sqlite3SafetyCheckSickOrOk(db) ){
    return (void *)misuse;
  }
  sqlite3_mutex_enter(db->mutex);
  if( db->mallocFailed ){
    z = (void *)outOfMem;
  }else{
    z = sqlite3_value_text16(db->pErr);
    if( z==0 ){
      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
           SQLITE_UTF8, SQLITE_STATIC);
      z = sqlite3_value_text16(db->pErr);
    }
    /* A malloc() may have failed within the call to sqlite3_value_text16()
    ** above. If this is the case, then the db->mallocFailed flag needs to
    ** be cleared before returning. Do this directly, instead of via
    ** sqlite3ApiExit(), to avoid setting the database handle error message.
    */
    db->mallocFailed = 0;
  }
  sqlite3_mutex_leave(db->mutex);
  return z;
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Return the most recent error code generated by an SQLite routine. If NULL is
** passed to this function, we assume a malloc() failed during sqlite3_open().
*/
int sqlite3_errcode(sqlite3 *db){
  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
    return SQLITE_MISUSE;
  }
  if( !db || db->mallocFailed ){
    return SQLITE_NOMEM;
  }
  return db->errCode & db->errMask;
}
int sqlite3_extended_errcode(sqlite3 *db){
  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
    return SQLITE_MISUSE;
  }
  if( !db || db->mallocFailed ){
    return SQLITE_NOMEM;
  }
  return db->errCode;
}

/*
** Create a new collating function for database "db".  The name is zName
** and the encoding is enc.
*/
static int createCollation(
  sqlite3* db,
  const char *zName, 
  u8 enc,
  u8 collType,
  void* pCtx,
  int(*xCompare)(void*,int,const void*,int,const void*),
  void(*xDel)(void*)
){
  CollSeq *pColl;
  int enc2;
  int nName = sqlite3Strlen30(zName);
  
  assert( sqlite3_mutex_held(db->mutex) );

  /* If SQLITE_UTF16 is specified as the encoding type, transform this
  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  */
  enc2 = enc;
  testcase( enc2==SQLITE_UTF16 );
  testcase( enc2==SQLITE_UTF16_ALIGNED );
  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
    enc2 = SQLITE_UTF16NATIVE;
  }
  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
    return SQLITE_MISUSE;
  }

  /* Check if this call is removing or replacing an existing collation 
  ** sequence. If so, and there are active VMs, return busy. If there
  ** are no active VMs, invalidate any pre-compiled statements.
  */
  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  if( pColl && pColl->xCmp ){
    if( db->activeVdbeCnt ){
      sqlite3Error(db, SQLITE_BUSY, 
        "unable to delete/modify collation sequence due to active statements");
      return SQLITE_BUSY;
    }
    sqlite3ExpirePreparedStatements(db);

    /* If collation sequence pColl was created directly by a call to
    ** sqlite3_create_collation, and not generated by synthCollSeq(),
    ** then any copies made by synthCollSeq() need to be invalidated.
    ** Also, collation destructor - CollSeq.xDel() - function may need
    ** to be called.
    */ 
    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
      int j;
      for(j=0; j<3; j++){
        CollSeq *p = &aColl[j];
        if( p->enc==pColl->enc ){
          if( p->xDel ){
            p->xDel(p->pUser);
          }
          p->xCmp = 0;
        }
      }
    }
  }

  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  if( pColl ){
    pColl->xCmp = xCompare;
    pColl->pUser = pCtx;
    pColl->xDel = xDel;
    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
    pColl->type = collType;
  }
  sqlite3Error(db, SQLITE_OK, 0);
  return SQLITE_OK;
}


/*
** This array defines hard upper bounds on limit values.  The
** initializer must be kept in sync with the SQLITE_LIMIT_*
** #defines in sqlite3.h.
*/
static const int aHardLimit[] = {
  SQLITE_MAX_LENGTH,
  SQLITE_MAX_SQL_LENGTH,
  SQLITE_MAX_COLUMN,
  SQLITE_MAX_EXPR_DEPTH,
  SQLITE_MAX_COMPOUND_SELECT,
  SQLITE_MAX_VDBE_OP,
  SQLITE_MAX_FUNCTION_ARG,
  SQLITE_MAX_ATTACHED,
  SQLITE_MAX_LIKE_PATTERN_LENGTH,
  SQLITE_MAX_VARIABLE_NUMBER,
  SQLITE_MAX_TRIGGER_DEPTH,
};

/*
** Make sure the hard limits are set to reasonable values
*/
#if SQLITE_MAX_LENGTH<100
# error SQLITE_MAX_LENGTH must be at least 100
#endif
#if SQLITE_MAX_SQL_LENGTH<100
# error SQLITE_MAX_SQL_LENGTH must be at least 100
#endif
#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
#endif
#if SQLITE_MAX_COMPOUND_SELECT<2
# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
#endif
#if SQLITE_MAX_VDBE_OP<40
# error SQLITE_MAX_VDBE_OP must be at least 40
#endif
#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
#endif
#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
# error SQLITE_MAX_ATTACHED must be between 0 and 30
#endif
#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
#endif
#if SQLITE_MAX_COLUMN>32767
# error SQLITE_MAX_COLUMN must not exceed 32767
#endif
#if SQLITE_MAX_TRIGGER_DEPTH<1
# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
#endif


/*
** Change the value of a limit.  Report the old value.
** If an invalid limit index is supplied, report -1.
** Make no changes but still report the old value if the
** new limit is negative.
**
** A new lower limit does not shrink existing constructs.
** It merely prevents new constructs that exceed the limit
** from forming.
*/
int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  int oldLimit;
  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
    return -1;
  }
  oldLimit = db->aLimit[limitId];
  if( newLimit>=0 ){
    if( newLimit>aHardLimit[limitId] ){
      newLimit = aHardLimit[limitId];
    }
    db->aLimit[limitId] = newLimit;
  }
  return oldLimit;
}

/*
** This routine does the work of opening a database on behalf of
** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
** is UTF-8 encoded.
*/
static int openDatabase(
  const char *zFilename, /* Database filename UTF-8 encoded */
  sqlite3 **ppDb,        /* OUT: Returned database handle */
  unsigned flags,        /* Operational flags */
  const char *zVfs       /* Name of the VFS to use */
){
  sqlite3 *db;
  int rc;
  int isThreadsafe;

  *ppDb = 0;
#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite3_initialize();
  if( rc ) return rc;
#endif

  if( sqlite3GlobalConfig.bCoreMutex==0 ){
    isThreadsafe = 0;
  }else if( flags & SQLITE_OPEN_NOMUTEX ){
    isThreadsafe = 0;
  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
    isThreadsafe = 1;
  }else{
    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  }
  if( flags & SQLITE_OPEN_PRIVATECACHE ){
    flags &= ~SQLITE_OPEN_SHAREDCACHE;
  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
    flags |= SQLITE_OPEN_SHAREDCACHE;
  }

  /* Remove harmful bits from the flags parameter
  **
  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  ** dealt with in the previous code block.  Besides these, the only
  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
  ** off all other flags.
  */
  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
               SQLITE_OPEN_EXCLUSIVE |
               SQLITE_OPEN_MAIN_DB |
               SQLITE_OPEN_TEMP_DB | 
               SQLITE_OPEN_TRANSIENT_DB | 
               SQLITE_OPEN_MAIN_JOURNAL | 
               SQLITE_OPEN_TEMP_JOURNAL | 
               SQLITE_OPEN_SUBJOURNAL | 
               SQLITE_OPEN_MASTER_JOURNAL |
               SQLITE_OPEN_NOMUTEX |
               SQLITE_OPEN_FULLMUTEX
             );

  /* Allocate the sqlite data structure */
  db = sqlite3MallocZero( sizeof(sqlite3) );
  if( db==0 ) goto opendb_out;
  if( isThreadsafe ){
    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    if( db->mutex==0 ){
      sqlite3_free(db);
      db = 0;
      goto opendb_out;
    }
  }
  sqlite3_mutex_enter(db->mutex);
  db->errMask = 0xff;
  db->nDb = 2;
  db->magic = SQLITE_MAGIC_BUSY;
  db->aDb = db->aDbStatic;

  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  db->autoCommit = 1;
  db->nextAutovac = -1;
  db->nextPagesize = 0;
  db->flags |= SQLITE_ShortColNames
#if SQLITE_DEFAULT_FILE_FORMAT<4
                 | SQLITE_LegacyFileFmt
#endif
#ifdef SQLITE_ENABLE_LOAD_EXTENSION
                 | SQLITE_LoadExtension
#endif
#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
                 | SQLITE_RecTriggers
#endif
      ;
  sqlite3HashInit(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3HashInit(&db->aModule);
#endif

  db->pVfs = sqlite3_vfs_find(zVfs);
  if( !db->pVfs ){
    rc = SQLITE_ERROR;
    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
    goto opendb_out;
  }

  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  ** and UTF-16, so add a version for each to avoid any unnecessary
  ** conversions. The only error that can occur here is a malloc() failure.
  */
  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
                  binCollFunc, 0);
  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
                  binCollFunc, 0);
  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
                  binCollFunc, 0);
  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
                  binCollFunc, 0);
  if( db->mallocFailed ){
    goto opendb_out;
  }
  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  assert( db->pDfltColl!=0 );

  /* Also add a UTF-8 case-insensitive collation sequence. */
  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
                  nocaseCollatingFunc, 0);

  /* Open the backend database driver */
  db->openFlags = flags;
  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
                           flags | SQLITE_OPEN_MAIN_DB,
                           &db->aDb[0].pBt);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_IOERR_NOMEM ){
      rc = SQLITE_NOMEM;
    }
    sqlite3Error(db, rc, 0);
    goto opendb_out;
  }
  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);


  /* The default safety_level for the main database is 'full'; for the temp
  ** database it is 'NONE'. This matches the pager layer defaults.  
  */
  db->aDb[0].zName = "main";
  db->aDb[0].safety_level = 3;
  db->aDb[1].zName = "temp";
  db->aDb[1].safety_level = 1;

  db->magic = SQLITE_MAGIC_OPEN;
  if( db->mallocFailed ){
    goto opendb_out;
  }

  /* Register all built-in functions, but do not attempt to read the
  ** database schema yet. This is delayed until the first time the database
  ** is accessed.
  */
  sqlite3Error(db, SQLITE_OK, 0);
  sqlite3RegisterBuiltinFunctions(db);

  /* Load automatic extensions - extensions that have been registered
  ** using the sqlite3_automatic_extension() API.
  */
  sqlite3AutoLoadExtensions(db);
  rc = sqlite3_errcode(db);
  if( rc!=SQLITE_OK ){
    goto opendb_out;
  }

#ifdef SQLITE_ENABLE_FTS1
  if( !db->mallocFailed ){
    extern int sqlite3Fts1Init(sqlite3*);
    rc = sqlite3Fts1Init(db);
  }
#endif

#ifdef SQLITE_ENABLE_FTS2
  if( !db->mallocFailed && rc==SQLITE_OK ){
    extern int sqlite3Fts2Init(sqlite3*);
    rc = sqlite3Fts2Init(db);
  }
#endif

#ifdef SQLITE_ENABLE_FTS3
  if( !db->mallocFailed && rc==SQLITE_OK ){
    rc = sqlite3Fts3Init(db);
  }
#endif

#ifdef SQLITE_ENABLE_ICU
  if( !db->mallocFailed && rc==SQLITE_OK ){
    rc = sqlite3IcuInit(db);
  }
#endif

#ifdef SQLITE_ENABLE_RTREE
  if( !db->mallocFailed && rc==SQLITE_OK){
    rc = sqlite3RtreeInit(db);
  }
#endif

  sqlite3Error(db, rc, 0);

  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  ** mode.  Doing nothing at all also makes NORMAL the default.
  */
#ifdef SQLITE_DEFAULT_LOCKING_MODE
  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
                          SQLITE_DEFAULT_LOCKING_MODE);
#endif

  /* Enable the lookaside-malloc subsystem */
  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
                        sqlite3GlobalConfig.nLookaside);

opendb_out:
  if( db ){
    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
    sqlite3_mutex_leave(db->mutex);
  }
  rc = sqlite3_errcode(db);
  if( rc==SQLITE_NOMEM ){
    sqlite3_close(db);
    db = 0;
  }else if( rc!=SQLITE_OK ){
    db->magic = SQLITE_MAGIC_SICK;
  }
  *ppDb = db;
  return sqlite3ApiExit(0, rc);
}

/*
** Open a new database handle.
*/
int sqlite3_open(
  const char *zFilename, 
  sqlite3 **ppDb 
){
  return openDatabase(zFilename, ppDb,
                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
}
int sqlite3_open_v2(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb,         /* OUT: SQLite db handle */
  int flags,              /* Flags */
  const char *zVfs        /* Name of VFS module to use */
){
  return openDatabase(filename, ppDb, flags, zVfs);
}

#ifndef SQLITE_OMIT_UTF16
/*
** Open a new database handle.
*/
int sqlite3_open16(
  const void *zFilename, 
  sqlite3 **ppDb
){
  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
  sqlite3_value *pVal;
  int rc;

  assert( zFilename );
  assert( ppDb );
  *ppDb = 0;
#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite3_initialize();
  if( rc ) return rc;
#endif
  pVal = sqlite3ValueNew(0);
  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  if( zFilename8 ){
    rc = openDatabase(zFilename8, ppDb,
                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
    assert( *ppDb || rc==SQLITE_NOMEM );
    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
      ENC(*ppDb) = SQLITE_UTF16NATIVE;
    }
  }else{
    rc = SQLITE_NOMEM;
  }
  sqlite3ValueFree(pVal);

  return sqlite3ApiExit(0, rc);
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Register a new collation sequence with the database handle db.
*/
int sqlite3_create_collation(
  sqlite3* db, 
  const char *zName, 
  int enc, 
  void* pCtx,
  int(*xCompare)(void*,int,const void*,int,const void*)
){
  int rc;
  sqlite3_mutex_enter(db->mutex);
  assert( !db->mallocFailed );
  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** Register a new collation sequence with the database handle db.
*/
int sqlite3_create_collation_v2(
  sqlite3* db, 
  const char *zName, 
  int enc, 
  void* pCtx,
  int(*xCompare)(void*,int,const void*,int,const void*),
  void(*xDel)(void*)
){
  int rc;
  sqlite3_mutex_enter(db->mutex);
  assert( !db->mallocFailed );
  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

#ifndef SQLITE_OMIT_UTF16
/*
** Register a new collation sequence with the database handle db.
*/
int sqlite3_create_collation16(
  sqlite3* db, 
  const void *zName,
  int enc, 
  void* pCtx,
  int(*xCompare)(void*,int,const void*,int,const void*)
){
  int rc = SQLITE_OK;
  char *zName8;
  sqlite3_mutex_enter(db->mutex);
  assert( !db->mallocFailed );
  zName8 = sqlite3Utf16to8(db, zName, -1);
  if( zName8 ){
    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
    sqlite3DbFree(db, zName8);
  }
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Register a collation sequence factory callback with the database handle
** db. Replace any previously installed collation sequence factory.
*/
int sqlite3_collation_needed(
  sqlite3 *db, 
  void *pCollNeededArg, 
  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
){
  sqlite3_mutex_enter(db->mutex);
  db->xCollNeeded = xCollNeeded;
  db->xCollNeeded16 = 0;
  db->pCollNeededArg = pCollNeededArg;
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}

#ifndef SQLITE_OMIT_UTF16
/*
** Register a collation sequence factory callback with the database handle
** db. Replace any previously installed collation sequence factory.
*/
int sqlite3_collation_needed16(
  sqlite3 *db, 
  void *pCollNeededArg, 
  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
){
  sqlite3_mutex_enter(db->mutex);
  db->xCollNeeded = 0;
  db->xCollNeeded16 = xCollNeeded16;
  db->pCollNeededArg = pCollNeededArg;
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}
#endif /* SQLITE_OMIT_UTF16 */

#ifndef SQLITE_OMIT_GLOBALRECOVER
#ifndef SQLITE_OMIT_DEPRECATED
/*
** This function is now an anachronism. It used to be used to recover from a
** malloc() failure, but SQLite now does this automatically.
*/
int sqlite3_global_recover(void){
  return SQLITE_OK;
}
#endif
#endif

/*
** Test to see whether or not the database connection is in autocommit
** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
** by default.  Autocommit is disabled by a BEGIN statement and reenabled
** by the next COMMIT or ROLLBACK.
**
******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
*/
int sqlite3_get_autocommit(sqlite3 *db){
  return db->autoCommit;
}

#ifdef SQLITE_DEBUG
/*
** The following routine is subtituted for constant SQLITE_CORRUPT in
** debugging builds.  This provides a way to set a breakpoint for when
** corruption is first detected.
*/
int sqlite3Corrupt(void){
  return SQLITE_CORRUPT;
}
#endif

#ifndef SQLITE_OMIT_DEPRECATED
/*
** This is a convenience routine that makes sure that all thread-specific
** data for this thread has been deallocated.
**
** SQLite no longer uses thread-specific data so this routine is now a
** no-op.  It is retained for historical compatibility.
*/
void sqlite3_thread_cleanup(void){
}
#endif

/*
** Return meta information about a specific column of a database table.
** See comment in sqlite3.h (sqlite.h.in) for details.
*/
#ifdef SQLITE_ENABLE_COLUMN_METADATA
int sqlite3_table_column_metadata(
  sqlite3 *db,                /* Connection handle */
  const char *zDbName,        /* Database name or NULL */
  const char *zTableName,     /* Table name */
  const char *zColumnName,    /* Column name */
  char const **pzDataType,    /* OUTPUT: Declared data type */
  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
){
  int rc;
  char *zErrMsg = 0;
  Table *pTab = 0;
  Column *pCol = 0;
  int iCol;

  char const *zDataType = 0;
  char const *zCollSeq = 0;
  int notnull = 0;
  int primarykey = 0;
  int autoinc = 0;

  /* Ensure the database schema has been loaded */
  sqlite3_mutex_enter(db->mutex);
  (void)sqlite3SafetyOn(db);
  sqlite3BtreeEnterAll(db);
  rc = sqlite3Init(db, &zErrMsg);
  if( SQLITE_OK!=rc ){
    goto error_out;
  }

  /* Locate the table in question */
  pTab = sqlite3FindTable(db, zTableName, zDbName);
  if( !pTab || pTab->pSelect ){
    pTab = 0;
    goto error_out;
  }

  /* Find the column for which info is requested */
  if( sqlite3IsRowid(zColumnName) ){
    iCol = pTab->iPKey;
    if( iCol>=0 ){
      pCol = &pTab->aCol[iCol];
    }
  }else{
    for(iCol=0; iCol<pTab->nCol; iCol++){
      pCol = &pTab->aCol[iCol];
      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
        break;
      }
    }
    if( iCol==pTab->nCol ){
      pTab = 0;
      goto error_out;
    }
  }

  /* The following block stores the meta information that will be returned
  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  ** and autoinc. At this point there are two possibilities:
  ** 
  **     1. The specified column name was rowid", "oid" or "_rowid_" 
  **        and there is no explicitly declared IPK column. 
  **
  **     2. The table is not a view and the column name identified an 
  **        explicitly declared column. Copy meta information from *pCol.
  */ 
  if( pCol ){
    zDataType = pCol->zType;
    zCollSeq = pCol->zColl;
    notnull = pCol->notNull!=0;
    primarykey  = pCol->isPrimKey!=0;
    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  }else{
    zDataType = "INTEGER";
    primarykey = 1;
  }
  if( !zCollSeq ){
    zCollSeq = "BINARY";
  }

error_out:
  sqlite3BtreeLeaveAll(db);
  (void)sqlite3SafetyOff(db);

  /* Whether the function call succeeded or failed, set the output parameters
  ** to whatever their local counterparts contain. If an error did occur,
  ** this has the effect of zeroing all output parameters.
  */
  if( pzDataType ) *pzDataType = zDataType;
  if( pzCollSeq ) *pzCollSeq = zCollSeq;
  if( pNotNull ) *pNotNull = notnull;
  if( pPrimaryKey ) *pPrimaryKey = primarykey;
  if( pAutoinc ) *pAutoinc = autoinc;

  if( SQLITE_OK==rc && !pTab ){
    sqlite3DbFree(db, zErrMsg);
    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
        zColumnName);
    rc = SQLITE_ERROR;
  }
  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  sqlite3DbFree(db, zErrMsg);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}
#endif

/*
** Sleep for a little while.  Return the amount of time slept.
*/
int sqlite3_sleep(int ms){
  sqlite3_vfs *pVfs;
  int rc;
  pVfs = sqlite3_vfs_find(0);
  if( pVfs==0 ) return 0;

  /* This function works in milliseconds, but the underlying OsSleep() 
  ** API uses microseconds. Hence the 1000's.
  */
  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  return rc;
}

/*
** Enable or disable the extended result codes.
*/
int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  sqlite3_mutex_enter(db->mutex);
  db->errMask = onoff ? 0xffffffff : 0xff;
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}

/*
** Invoke the xFileControl method on a particular database.
*/
int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  int rc = SQLITE_ERROR;
  int iDb;
  sqlite3_mutex_enter(db->mutex);
  if( zDbName==0 ){
    iDb = 0;
  }else{
    for(iDb=0; iDb<db->nDb; iDb++){
      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
    }
  }
  if( iDb<db->nDb ){
    Btree *pBtree = db->aDb[iDb].pBt;
    if( pBtree ){
      Pager *pPager;
      sqlite3_file *fd;
      sqlite3BtreeEnter(pBtree);
      pPager = sqlite3BtreePager(pBtree);
      assert( pPager!=0 );
      fd = sqlite3PagerFile(pPager);
      assert( fd!=0 );
      if( fd->pMethods ){
        rc = sqlite3OsFileControl(fd, op, pArg);
      }
      sqlite3BtreeLeave(pBtree);
    }
  }
  sqlite3_mutex_leave(db->mutex);
  return rc;   
}

/*
** Interface to the testing logic.
*/
int sqlite3_test_control(int op, ...){
  int rc = 0;
#ifndef SQLITE_OMIT_BUILTIN_TEST
  va_list ap;
  va_start(ap, op);
  switch( op ){

    /*
    ** Save the current state of the PRNG.
    */
    case SQLITE_TESTCTRL_PRNG_SAVE: {
      sqlite3PrngSaveState();
      break;
    }

    /*
    ** Restore the state of the PRNG to the last state saved using
    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
    ** this verb acts like PRNG_RESET.
    */
    case SQLITE_TESTCTRL_PRNG_RESTORE: {
      sqlite3PrngRestoreState();
      break;
    }

    /*
    ** Reset the PRNG back to its uninitialized state.  The next call
    ** to sqlite3_randomness() will reseed the PRNG using a single call
    ** to the xRandomness method of the default VFS.
    */
    case SQLITE_TESTCTRL_PRNG_RESET: {
      sqlite3PrngResetState();
      break;
    }

    /*
    **  sqlite3_test_control(BITVEC_TEST, size, program)
    **
    ** Run a test against a Bitvec object of size.  The program argument
    ** is an array of integers that defines the test.  Return -1 on a
    ** memory allocation error, 0 on success, or non-zero for an error.
    ** See the sqlite3BitvecBuiltinTest() for additional information.
    */
    case SQLITE_TESTCTRL_BITVEC_TEST: {
      int sz = va_arg(ap, int);
      int *aProg = va_arg(ap, int*);
      rc = sqlite3BitvecBuiltinTest(sz, aProg);
      break;
    }

    /*
    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
    **
    ** Register hooks to call to indicate which malloc() failures 
    ** are benign.
    */
    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
      typedef void (*void_function)(void);
      void_function xBenignBegin;
      void_function xBenignEnd;
      xBenignBegin = va_arg(ap, void_function);
      xBenignEnd = va_arg(ap, void_function);
      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
      break;
    }

    /*
    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
    **
    ** Set the PENDING byte to the value in the argument, if X>0.
    ** Make no changes if X==0.  Return the value of the pending byte
    ** as it existing before this routine was called.
    **
    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
    ** an incompatible database file format.  Changing the PENDING byte
    ** while any database connection is open results in undefined and
    ** dileterious behavior.
    */
    case SQLITE_TESTCTRL_PENDING_BYTE: {
      unsigned int newVal = va_arg(ap, unsigned int);
      rc = sqlite3PendingByte;
      if( newVal ) sqlite3PendingByte = newVal;
      break;
    }

    /*
    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
    **
    ** This action provides a run-time test to see whether or not
    ** assert() was enabled at compile-time.  If X is true and assert()
    ** is enabled, then the return value is true.  If X is true and
    ** assert() is disabled, then the return value is zero.  If X is
    ** false and assert() is enabled, then the assertion fires and the
    ** process aborts.  If X is false and assert() is disabled, then the
    ** return value is zero.
    */
    case SQLITE_TESTCTRL_ASSERT: {
      volatile int x = 0;
      assert( (x = va_arg(ap,int))!=0 );
      rc = x;
      break;
    }


    /*
    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
    **
    ** This action provides a run-time test to see how the ALWAYS and
    ** NEVER macros were defined at compile-time.
    **
    ** The return value is ALWAYS(X).  
    **
    ** The recommended test is X==2.  If the return value is 2, that means
    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
    ** default setting.  If the return value is 1, then ALWAYS() is either
    ** hard-coded to true or else it asserts if its argument is false.
    ** The first behavior (hard-coded to true) is the case if
    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
    ** behavior (assert if the argument to ALWAYS() is false) is the case if
    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
    **
    ** The run-time test procedure might look something like this:
    **
    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
    **      // ALWAYS() and NEVER() are no-op pass-through macros
    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
    **    }else{
    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
    **    }
    */
    case SQLITE_TESTCTRL_ALWAYS: {
      int x = va_arg(ap,int);
      rc = ALWAYS(x);
      break;
    }

    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
    **
    ** Set the nReserve size to N for the main database on the database
    ** connection db.
    */
    case SQLITE_TESTCTRL_RESERVE: {
      sqlite3 *db = va_arg(ap, sqlite3*);
      int x = va_arg(ap,int);
      sqlite3_mutex_enter(db->mutex);
      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
      sqlite3_mutex_leave(db->mutex);
      break;
    }

  }
  va_end(ap);
#endif /* SQLITE_OMIT_BUILTIN_TEST */
  return rc;
}

Added src/malloc.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
**
** $Id: malloc.c,v 1.66 2009/07/17 11:44:07 drh Exp $
*/
#include "sqliteInt.h"
#include <stdarg.h>

/*
** This routine runs when the memory allocator sees that the
** total memory allocation is about to exceed the soft heap
** limit.
*/
static void softHeapLimitEnforcer(
  void *NotUsed, 
  sqlite3_int64 NotUsed2,
  int allocSize
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_release_memory(allocSize);
}

/*
** Set the soft heap-size limit for the library. Passing a zero or 
** negative value indicates no limit.
*/
void sqlite3_soft_heap_limit(int n){
  sqlite3_uint64 iLimit;
  int overage;
  if( n<0 ){
    iLimit = 0;
  }else{
    iLimit = n;
  }
#ifndef SQLITE_OMIT_AUTOINIT
  sqlite3_initialize();
#endif
  if( iLimit>0 ){
    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
  }else{
    sqlite3MemoryAlarm(0, 0, 0);
  }
  overage = (int)(sqlite3_memory_used() - (i64)n);
  if( overage>0 ){
    sqlite3_release_memory(overage);
  }
}

/*
** Attempt to release up to n bytes of non-essential memory currently
** held by SQLite. An example of non-essential memory is memory used to
** cache database pages that are not currently in use.
*/
int sqlite3_release_memory(int n){
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  int nRet = 0;
  nRet += sqlite3PcacheReleaseMemory(n-nRet);
  return nRet;
#else
  UNUSED_PARAMETER(n);
  return SQLITE_OK;
#endif
}

/*
** State information local to the memory allocation subsystem.
*/
static SQLITE_WSD struct Mem0Global {
  /* Number of free pages for scratch and page-cache memory */
  u32 nScratchFree;
  u32 nPageFree;

  sqlite3_mutex *mutex;         /* Mutex to serialize access */

  /*
  ** The alarm callback and its arguments.  The mem0.mutex lock will
  ** be held while the callback is running.  Recursive calls into
  ** the memory subsystem are allowed, but no new callbacks will be
  ** issued.
  */
  sqlite3_int64 alarmThreshold;
  void (*alarmCallback)(void*, sqlite3_int64,int);
  void *alarmArg;

  /*
  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
  ** sqlite3GlobalConfig.pPage to a block of memory that records
  ** which pages are available.
  */
  u32 *aScratchFree;
  u32 *aPageFree;
} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };

#define mem0 GLOBAL(struct Mem0Global, mem0)

/*
** Initialize the memory allocation subsystem.
*/
int sqlite3MallocInit(void){
  if( sqlite3GlobalConfig.m.xMalloc==0 ){
    sqlite3MemSetDefault();
  }
  memset(&mem0, 0, sizeof(mem0));
  if( sqlite3GlobalConfig.bCoreMutex ){
    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
      && sqlite3GlobalConfig.nScratch>=0 ){
    int i;
    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
  }else{
    sqlite3GlobalConfig.pScratch = 0;
    sqlite3GlobalConfig.szScratch = 0;
  }
  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
      && sqlite3GlobalConfig.nPage>=1 ){
    int i;
    int overhead;
    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
    int n = sqlite3GlobalConfig.nPage;
    overhead = (4*n + sz - 1)/sz;
    sqlite3GlobalConfig.nPage -= overhead;
    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
    mem0.nPageFree = sqlite3GlobalConfig.nPage;
  }else{
    sqlite3GlobalConfig.pPage = 0;
    sqlite3GlobalConfig.szPage = 0;
  }
  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite3MallocEnd(void){
  if( sqlite3GlobalConfig.m.xShutdown ){
    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  }
  memset(&mem0, 0, sizeof(mem0));
}

/*
** Return the amount of memory currently checked out.
*/
sqlite3_int64 sqlite3_memory_used(void){
  int n, mx;
  sqlite3_int64 res;
  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
  return res;
}

/*
** Return the maximum amount of memory that has ever been
** checked out since either the beginning of this process
** or since the most recent reset.
*/
sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  int n, mx;
  sqlite3_int64 res;
  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
  return res;
}

/*
** Change the alarm callback
*/
int sqlite3MemoryAlarm(
  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  void *pArg,
  sqlite3_int64 iThreshold
){
  sqlite3_mutex_enter(mem0.mutex);
  mem0.alarmCallback = xCallback;
  mem0.alarmArg = pArg;
  mem0.alarmThreshold = iThreshold;
  sqlite3_mutex_leave(mem0.mutex);
  return SQLITE_OK;
}

#ifndef SQLITE_OMIT_DEPRECATED
/*
** Deprecated external interface.  Internal/core SQLite code
** should call sqlite3MemoryAlarm.
*/
int sqlite3_memory_alarm(
  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  void *pArg,
  sqlite3_int64 iThreshold
){
  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
}
#endif

/*
** Trigger the alarm 
*/
static void sqlite3MallocAlarm(int nByte){
  void (*xCallback)(void*,sqlite3_int64,int);
  sqlite3_int64 nowUsed;
  void *pArg;
  if( mem0.alarmCallback==0 ) return;
  xCallback = mem0.alarmCallback;
  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  pArg = mem0.alarmArg;
  mem0.alarmCallback = 0;
  sqlite3_mutex_leave(mem0.mutex);
  xCallback(pArg, nowUsed, nByte);
  sqlite3_mutex_enter(mem0.mutex);
  mem0.alarmCallback = xCallback;
  mem0.alarmArg = pArg;
}

/*
** Do a memory allocation with statistics and alarms.  Assume the
** lock is already held.
*/
static int mallocWithAlarm(int n, void **pp){
  int nFull;
  void *p;
  assert( sqlite3_mutex_held(mem0.mutex) );
  nFull = sqlite3GlobalConfig.m.xRoundup(n);
  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  if( mem0.alarmCallback!=0 ){
    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
    if( nUsed+nFull >= mem0.alarmThreshold ){
      sqlite3MallocAlarm(nFull);
    }
  }
  p = sqlite3GlobalConfig.m.xMalloc(nFull);
  if( p==0 && mem0.alarmCallback ){
    sqlite3MallocAlarm(nFull);
    p = sqlite3GlobalConfig.m.xMalloc(nFull);
  }
  if( p ){
    nFull = sqlite3MallocSize(p);
    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  }
  *pp = p;
  return nFull;
}

/*
** Allocate memory.  This routine is like sqlite3_malloc() except that it
** assumes the memory subsystem has already been initialized.
*/
void *sqlite3Malloc(int n){
  void *p;
  if( n<=0 || n>=0x7fffff00 ){
    /* A memory allocation of a number of bytes which is near the maximum
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
    p = 0;
  }else if( sqlite3GlobalConfig.bMemstat ){
    sqlite3_mutex_enter(mem0.mutex);
    mallocWithAlarm(n, &p);
    sqlite3_mutex_leave(mem0.mutex);
  }else{
    p = sqlite3GlobalConfig.m.xMalloc(n);
  }
  return p;
}

/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
void *sqlite3_malloc(int n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite3_initialize() ) return 0;
#endif
  return sqlite3Malloc(n);
}

/*
** Each thread may only have a single outstanding allocation from
** xScratchMalloc().  We verify this constraint in the single-threaded
** case by setting scratchAllocOut to 1 when an allocation
** is outstanding clearing it when the allocation is freed.
*/
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
static int scratchAllocOut = 0;
#endif


/*
** Allocate memory that is to be used and released right away.
** This routine is similar to alloca() in that it is not intended
** for situations where the memory might be held long-term.  This
** routine is intended to get memory to old large transient data
** structures that would not normally fit on the stack of an
** embedded processor.
*/
void *sqlite3ScratchMalloc(int n){
  void *p;
  assert( n>0 );

#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  /* Verify that no more than one scratch allocation per thread
  ** is outstanding at one time.  (This is only checked in the
  ** single-threaded case since checking in the multi-threaded case
  ** would be much more complicated.) */
  assert( scratchAllocOut==0 );
#endif

  if( sqlite3GlobalConfig.szScratch<n ){
    goto scratch_overflow;
  }else{  
    sqlite3_mutex_enter(mem0.mutex);
    if( mem0.nScratchFree==0 ){
      sqlite3_mutex_leave(mem0.mutex);
      goto scratch_overflow;
    }else{
      int i;
      i = mem0.aScratchFree[--mem0.nScratchFree];
      i *= sqlite3GlobalConfig.szScratch;
      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
      sqlite3_mutex_leave(mem0.mutex);
      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
      assert(  (((u8*)p - (u8*)0) & 7)==0 );
    }
  }
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  scratchAllocOut = p!=0;
#endif

  return p;

scratch_overflow:
  if( sqlite3GlobalConfig.bMemstat ){
    sqlite3_mutex_enter(mem0.mutex);
    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
    n = mallocWithAlarm(n, &p);
    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
    sqlite3_mutex_leave(mem0.mutex);
  }else{
    p = sqlite3GlobalConfig.m.xMalloc(n);
  }
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  scratchAllocOut = p!=0;
#endif
  return p;    
}
void sqlite3ScratchFree(void *p){
  if( p ){

#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
    /* Verify that no more than one scratch allocation per thread
    ** is outstanding at one time.  (This is only checked in the
    ** single-threaded case since checking in the multi-threaded case
    ** would be much more complicated.) */
    assert( scratchAllocOut==1 );
    scratchAllocOut = 0;
#endif

    if( sqlite3GlobalConfig.pScratch==0
           || p<sqlite3GlobalConfig.pScratch
           || p>=(void*)mem0.aScratchFree ){
      if( sqlite3GlobalConfig.bMemstat ){
        int iSize = sqlite3MallocSize(p);
        sqlite3_mutex_enter(mem0.mutex);
        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
        sqlite3GlobalConfig.m.xFree(p);
        sqlite3_mutex_leave(mem0.mutex);
      }else{
        sqlite3GlobalConfig.m.xFree(p);
      }
    }else{
      int i;
      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
      i /= sqlite3GlobalConfig.szScratch;
      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
      sqlite3_mutex_enter(mem0.mutex);
      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
      mem0.aScratchFree[mem0.nScratchFree++] = i;
      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
      sqlite3_mutex_leave(mem0.mutex);
    }
  }
}

/*
** TRUE if p is a lookaside memory allocation from db
*/
#ifndef SQLITE_OMIT_LOOKASIDE
static int isLookaside(sqlite3 *db, void *p){
  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
}
#else
#define isLookaside(A,B) 0
#endif

/*
** Return the size of a memory allocation previously obtained from
** sqlite3Malloc() or sqlite3_malloc().
*/
int sqlite3MallocSize(void *p){
  return sqlite3GlobalConfig.m.xSize(p);
}
int sqlite3DbMallocSize(sqlite3 *db, void *p){
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
  if( isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{
    return sqlite3GlobalConfig.m.xSize(p);
  }
}

/*
** Free memory previously obtained from sqlite3Malloc().
*/
void sqlite3_free(void *p){
  if( p==0 ) return;
  if( sqlite3GlobalConfig.bMemstat ){
    sqlite3_mutex_enter(mem0.mutex);
    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
    sqlite3GlobalConfig.m.xFree(p);
    sqlite3_mutex_leave(mem0.mutex);
  }else{
    sqlite3GlobalConfig.m.xFree(p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
void sqlite3DbFree(sqlite3 *db, void *p){
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
  if( isLookaside(db, p) ){
    LookasideSlot *pBuf = (LookasideSlot*)p;
    pBuf->pNext = db->lookaside.pFree;
    db->lookaside.pFree = pBuf;
    db->lookaside.nOut--;
  }else{
    sqlite3_free(p);
  }
}

/*
** Change the size of an existing memory allocation
*/
void *sqlite3Realloc(void *pOld, int nBytes){
  int nOld, nNew;
  void *pNew;
  if( pOld==0 ){
    return sqlite3Malloc(nBytes);
  }
  if( nBytes<=0 ){
    sqlite3_free(pOld);
    return 0;
  }
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
    return 0;
  }
  nOld = sqlite3MallocSize(pOld);
  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  if( nOld==nNew ){
    pNew = pOld;
  }else if( sqlite3GlobalConfig.bMemstat ){
    sqlite3_mutex_enter(mem0.mutex);
    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
          mem0.alarmThreshold ){
      sqlite3MallocAlarm(nNew-nOld);
    }
    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
    if( pNew==0 && mem0.alarmCallback ){
      sqlite3MallocAlarm(nBytes);
      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
    }
    if( pNew ){
      nNew = sqlite3MallocSize(pNew);
      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite3_mutex_leave(mem0.mutex);
  }else{
    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  }
  return pNew;
}

/*
** The public interface to sqlite3Realloc.  Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
void *sqlite3_realloc(void *pOld, int n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite3_initialize() ) return 0;
#endif
  return sqlite3Realloc(pOld, n);
}


/*
** Allocate and zero memory.
*/ 
void *sqlite3MallocZero(int n){
  void *p = sqlite3Malloc(n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}

/*
** Allocate and zero memory.  If the allocation fails, make
** the mallocFailed flag in the connection pointer.
*/
void *sqlite3DbMallocZero(sqlite3 *db, int n){
  void *p = sqlite3DbMallocRaw(db, n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}

/*
** Allocate and zero memory.  If the allocation fails, make
** the mallocFailed flag in the connection pointer.
**
** If db!=0 and db->mallocFailed is true (indicating a prior malloc
** failure on the same database connection) then always return 0.
** Hence for a particular database connection, once malloc starts
** failing, it fails consistently until mallocFailed is reset.
** This is an important assumption.  There are many places in the
** code that do things like this:
**
**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
**         if( b ) a[10] = 9;
**
** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
** that all prior mallocs (ex: "a") worked too.
*/
void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  void *p;
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
#ifndef SQLITE_OMIT_LOOKASIDE
  if( db ){
    LookasideSlot *pBuf;
    if( db->mallocFailed ){
      return 0;
    }
    if( db->lookaside.bEnabled && n<=db->lookaside.sz
         && (pBuf = db->lookaside.pFree)!=0 ){
      db->lookaside.pFree = pBuf->pNext;
      db->lookaside.nOut++;
      if( db->lookaside.nOut>db->lookaside.mxOut ){
        db->lookaside.mxOut = db->lookaside.nOut;
      }
      return (void*)pBuf;
    }
  }
#else
  if( db && db->mallocFailed ){
    return 0;
  }
#endif
  p = sqlite3Malloc(n);
  if( !p && db ){
    db->mallocFailed = 1;
  }
  return p;
}

/*
** Resize the block of memory pointed to by p to n bytes. If the
** resize fails, set the mallocFailed flag in the connection object.
*/
void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  void *pNew = 0;
  assert( db!=0 );
  assert( sqlite3_mutex_held(db->mutex) );
  if( db->mallocFailed==0 ){
    if( p==0 ){
      return sqlite3DbMallocRaw(db, n);
    }
    if( isLookaside(db, p) ){
      if( n<=db->lookaside.sz ){
        return p;
      }
      pNew = sqlite3DbMallocRaw(db, n);
      if( pNew ){
        memcpy(pNew, p, db->lookaside.sz);
        sqlite3DbFree(db, p);
      }
    }else{
      pNew = sqlite3_realloc(p, n);
      if( !pNew ){
        db->mallocFailed = 1;
      }
    }
  }
  return pNew;
}

/*
** Attempt to reallocate p.  If the reallocation fails, then free p
** and set the mallocFailed flag in the database connection.
*/
void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  void *pNew;
  pNew = sqlite3DbRealloc(db, p, n);
  if( !pNew ){
    sqlite3DbFree(db, p);
  }
  return pNew;
}

/*
** Make a copy of a string in memory obtained from sqliteMalloc(). These 
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
** is because when memory debugging is turned on, these two functions are 
** called via macros that record the current file and line number in the
** ThreadData structure.
*/
char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  char *zNew;
  size_t n;
  if( z==0 ){
    return 0;
  }
  n = sqlite3Strlen30(z) + 1;
  assert( (n&0x7fffffff)==n );
  zNew = sqlite3DbMallocRaw(db, (int)n);
  if( zNew ){
    memcpy(zNew, z, n);
  }
  return zNew;
}
char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  char *zNew;
  if( z==0 ){
    return 0;
  }
  assert( (n&0x7fffffff)==n );
  zNew = sqlite3DbMallocRaw(db, n+1);
  if( zNew ){
    memcpy(zNew, z, n);
    zNew[n] = 0;
  }
  return zNew;
}

/*
** Create a string from the zFromat argument and the va_list that follows.
** Store the string in memory obtained from sqliteMalloc() and make *pz
** point to that string.
*/
void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  va_list ap;
  char *z;

  va_start(ap, zFormat);
  z = sqlite3VMPrintf(db, zFormat, ap);
  va_end(ap);
  sqlite3DbFree(db, *pz);
  *pz = z;
}


/*
** This function must be called before exiting any API function (i.e. 
** returning control to the user) that has called sqlite3_malloc or
** sqlite3_realloc.
**
** The returned value is normally a copy of the second argument to this
** function. However, if a malloc() failure has occurred since the previous
** invocation SQLITE_NOMEM is returned instead. 
**
** If the first argument, db, is not NULL and a malloc() error has occurred,
** then the connection error-code (the value returned by sqlite3_errcode())
** is set to SQLITE_NOMEM.
*/
int sqlite3ApiExit(sqlite3* db, int rc){
  /* If the db handle is not NULL, then we must hold the connection handle
  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
  ** is unsafe, as is the call to sqlite3Error().
  */
  assert( !db || sqlite3_mutex_held(db->mutex) );
  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
    sqlite3Error(db, SQLITE_NOMEM, 0);
    db->mallocFailed = 0;
    rc = SQLITE_NOMEM;
  }
  return rc & (db ? db->errMask : 0xff);
}

Added src/mem0.c.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
** 2008 October 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains a no-op memory allocation drivers for use when
** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
** here always fail.  SQLite will not operate with these drivers.  These
** are merely placeholders.  Real drivers must be substituted using
** sqlite3_config() before SQLite will operate.
**
** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $
*/
#include "sqliteInt.h"

/*
** This version of the memory allocator is the default.  It is
** used when no other memory allocator is specified using compile-time
** macros.
*/
#ifdef SQLITE_ZERO_MALLOC

/*
** No-op versions of all memory allocation routines
*/
static void *sqlite3MemMalloc(int nByte){ return 0; }
static void sqlite3MemFree(void *pPrior){ return; }
static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
static int sqlite3MemSize(void *pPrior){ return 0; }
static int sqlite3MemRoundup(int n){ return n; }
static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
static void sqlite3MemShutdown(void *NotUsed){ return; }

/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
** sqlite3GlobalConfig.m with pointers to the routines in this file.
*/
void sqlite3MemSetDefault(void){
  static const sqlite3_mem_methods defaultMethods = {
     sqlite3MemMalloc,
     sqlite3MemFree,
     sqlite3MemRealloc,
     sqlite3MemSize,
     sqlite3MemRoundup,
     sqlite3MemInit,
     sqlite3MemShutdown,
     0
  };
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
}

#endif /* SQLITE_ZERO_MALLOC */

Added src/mem1.c.



































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
** 2007 August 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains low-level memory allocation drivers for when
** SQLite will use the standard C-library malloc/realloc/free interface
** to obtain the memory it needs.
**
** This file contains implementations of the low-level memory allocation
** routines specified in the sqlite3_mem_methods object.
**
** $Id: mem1.c,v 1.30 2009/03/23 04:33:33 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** This version of the memory allocator is the default.  It is
** used when no other memory allocator is specified using compile-time
** macros.
*/
#ifdef SQLITE_SYSTEM_MALLOC

/*
** Like malloc(), but remember the size of the allocation
** so that we can find it later using sqlite3MemSize().
**
** For this low-level routine, we are guaranteed that nByte>0 because
** cases of nByte<=0 will be intercepted and dealt with by higher level
** routines.
*/
static void *sqlite3MemMalloc(int nByte){
  sqlite3_int64 *p;
  assert( nByte>0 );
  nByte = ROUND8(nByte);
  p = malloc( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }
  return (void *)p;
}

/*
** Like free() but works for allocations obtained from sqlite3MemMalloc()
** or sqlite3MemRealloc().
**
** For this low-level routine, we already know that pPrior!=0 since
** cases where pPrior==0 will have been intecepted and dealt with
** by higher-level routines.
*/
static void sqlite3MemFree(void *pPrior){
  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  assert( pPrior!=0 );
  p--;
  free(p);
}

/*
** Like realloc().  Resize an allocation previously obtained from
** sqlite3MemMalloc().
**
** For this low-level interface, we know that pPrior!=0.  Cases where
** pPrior==0 while have been intercepted by higher-level routine and
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
** cases where nByte<=0 will have been intercepted by higher-level
** routines and redirected to xFree.
*/
static void *sqlite3MemRealloc(void *pPrior, int nByte){
  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
  nByte = ROUND8(nByte);
  p = (sqlite3_int64*)pPrior;
  p--;
  p = realloc(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }
  return (void*)p;
}

/*
** Report the allocated size of a prior return from xMalloc()
** or xRealloc().
*/
static int sqlite3MemSize(void *pPrior){
  sqlite3_int64 *p;
  if( pPrior==0 ) return 0;
  p = (sqlite3_int64*)pPrior;
  p--;
  return (int)p[0];
}

/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite3MemRoundup(int n){
  return ROUND8(n);
}

/*
** Initialize this module.
*/
static int sqlite3MemInit(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  return SQLITE_OK;
}

/*
** Deinitialize this module.
*/
static void sqlite3MemShutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  return;
}

/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
** sqlite3GlobalConfig.m with pointers to the routines in this file.
*/
void sqlite3MemSetDefault(void){
  static const sqlite3_mem_methods defaultMethods = {
     sqlite3MemMalloc,
     sqlite3MemFree,
     sqlite3MemRealloc,
     sqlite3MemSize,
     sqlite3MemRoundup,
     sqlite3MemInit,
     sqlite3MemShutdown,
     0
  };
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
}

#endif /* SQLITE_SYSTEM_MALLOC */

Added src/mem2.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
** 2007 August 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains low-level memory allocation drivers for when
** SQLite will use the standard C-library malloc/realloc/free interface
** to obtain the memory it needs while adding lots of additional debugging
** information to each allocation in order to help detect and fix memory
** leaks and memory usage errors.
**
** This file contains implementations of the low-level memory allocation
** routines specified in the sqlite3_mem_methods object.
**
** $Id: mem2.c,v 1.45 2009/03/23 04:33:33 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** This version of the memory allocator is used only if the
** SQLITE_MEMDEBUG macro is defined
*/
#ifdef SQLITE_MEMDEBUG

/*
** The backtrace functionality is only available with GLIBC
*/
#ifdef __GLIBC__
  extern int backtrace(void**,int);
  extern void backtrace_symbols_fd(void*const*,int,int);
#else
# define backtrace(A,B) 1
# define backtrace_symbols_fd(A,B,C)
#endif
#include <stdio.h>

/*
** Each memory allocation looks like this:
**
**  ------------------------------------------------------------------------
**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
**  ------------------------------------------------------------------------
**
** The application code sees only a pointer to the allocation.  We have
** to back up from the allocation pointer to find the MemBlockHdr.  The
** MemBlockHdr tells us the size of the allocation and the number of
** backtrace pointers.  There is also a guard word at the end of the
** MemBlockHdr.
*/
struct MemBlockHdr {
  i64 iSize;                          /* Size of this allocation */
  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
  char nBacktrace;                    /* Number of backtraces on this alloc */
  char nBacktraceSlots;               /* Available backtrace slots */
  short nTitle;                       /* Bytes of title; includes '\0' */
  int iForeGuard;                     /* Guard word for sanity */
};

/*
** Guard words
*/
#define FOREGUARD 0x80F5E153
#define REARGUARD 0xE4676B53

/*
** Number of malloc size increments to track.
*/
#define NCSIZE  1000

/*
** All of the static variables used by this module are collected
** into a single structure named "mem".  This is to keep the
** static variables organized and to reduce namespace pollution
** when this module is combined with other in the amalgamation.
*/
static struct {
  
  /*
  ** Mutex to control access to the memory allocation subsystem.
  */
  sqlite3_mutex *mutex;

  /*
  ** Head and tail of a linked list of all outstanding allocations
  */
  struct MemBlockHdr *pFirst;
  struct MemBlockHdr *pLast;
  
  /*
  ** The number of levels of backtrace to save in new allocations.
  */
  int nBacktrace;
  void (*xBacktrace)(int, int, void **);

  /*
  ** Title text to insert in front of each block
  */
  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
  char zTitle[100];  /* The title text */

  /* 
  ** sqlite3MallocDisallow() increments the following counter.
  ** sqlite3MallocAllow() decrements it.
  */
  int disallow; /* Do not allow memory allocation */

  /*
  ** Gather statistics on the sizes of memory allocations.
  ** nAlloc[i] is the number of allocation attempts of i*8
  ** bytes.  i==NCSIZE is the number of allocation attempts for
  ** sizes more than NCSIZE*8 bytes.
  */
  int nAlloc[NCSIZE];      /* Total number of allocations */
  int nCurrent[NCSIZE];    /* Current number of allocations */
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */

} mem;


/*
** Adjust memory usage statistics
*/
static void adjustStats(int iSize, int increment){
  int i = ROUND8(iSize)/8;
  if( i>NCSIZE-1 ){
    i = NCSIZE - 1;
  }
  if( increment>0 ){
    mem.nAlloc[i]++;
    mem.nCurrent[i]++;
    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
      mem.mxCurrent[i] = mem.nCurrent[i];
    }
  }else{
    mem.nCurrent[i]--;
    assert( mem.nCurrent[i]>=0 );
  }
}

/*
** Given an allocation, find the MemBlockHdr for that allocation.
**
** This routine checks the guards at either end of the allocation and
** if they are incorrect it asserts.
*/
static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  struct MemBlockHdr *p;
  int *pInt;
  u8 *pU8;
  int nReserve;

  p = (struct MemBlockHdr*)pAllocation;
  p--;
  assert( p->iForeGuard==(int)FOREGUARD );
  nReserve = ROUND8(p->iSize);
  pInt = (int*)pAllocation;
  pU8 = (u8*)pAllocation;
  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  /* This checks any of the "extra" bytes allocated due
  ** to rounding up to an 8 byte boundary to ensure 
  ** they haven't been overwritten.
  */
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  return p;
}

/*
** Return the number of bytes currently allocated at address p.
*/
static int sqlite3MemSize(void *p){
  struct MemBlockHdr *pHdr;
  if( !p ){
    return 0;
  }
  pHdr = sqlite3MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite3MemInit(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !sqlite3GlobalConfig.bMemstat ){
    /* If memory status is enabled, then the malloc.c wrapper will already
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return SQLITE_OK;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite3MemShutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  mem.mutex = 0;
}

/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite3MemRoundup(int n){
  return ROUND8(n);
}

/*
** Allocate nByte bytes of memory.
*/
static void *sqlite3MemMalloc(int nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  int *pInt;
  void *p = 0;
  int totalSize;
  int nReserve;
  sqlite3_mutex_enter(mem.mutex);
  assert( mem.disallow==0 );
  nReserve = ROUND8(nByte);
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
               mem.nBacktrace*sizeof(void*) + mem.nTitle;
  p = malloc(totalSize);
  if( p ){
    z = p;
    pBt = (void**)&z[mem.nTitle];
    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
    pHdr->pNext = 0;
    pHdr->pPrev = mem.pLast;
    if( mem.pLast ){
      mem.pLast->pNext = pHdr;
    }else{
      mem.pFirst = pHdr;
    }
    mem.pLast = pHdr;
    pHdr->iForeGuard = FOREGUARD;
    pHdr->nBacktraceSlots = mem.nBacktrace;
    pHdr->nTitle = mem.nTitle;
    if( mem.nBacktrace ){
      void *aAddr[40];
      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
      assert(pBt[0]);
      if( mem.xBacktrace ){
        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
      }
    }else{
      pHdr->nBacktrace = 0;
    }
    if( mem.nTitle ){
      memcpy(z, mem.zTitle, mem.nTitle);
    }
    pHdr->iSize = nByte;
    adjustStats(nByte, +1);
    pInt = (int*)&pHdr[1];
    pInt[nReserve/sizeof(int)] = REARGUARD;
    memset(pInt, 0x65, nReserve);
    p = (void*)pInt;
  }
  sqlite3_mutex_leave(mem.mutex);
  return p; 
}

/*
** Free memory.
*/
static void sqlite3MemFree(void *pPrior){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
  pHdr = sqlite3MemsysGetHeader(pPrior);
  pBt = (void**)pHdr;
  pBt -= pHdr->nBacktraceSlots;
  sqlite3_mutex_enter(mem.mutex);
  if( pHdr->pPrev ){
    assert( pHdr->pPrev->pNext==pHdr );
    pHdr->pPrev->pNext = pHdr->pNext;
  }else{
    assert( mem.pFirst==pHdr );
    mem.pFirst = pHdr->pNext;
  }
  if( pHdr->pNext ){
    assert( pHdr->pNext->pPrev==pHdr );
    pHdr->pNext->pPrev = pHdr->pPrev;
  }else{
    assert( mem.pLast==pHdr );
    mem.pLast = pHdr->pPrev;
  }
  z = (char*)pBt;
  z -= pHdr->nTitle;
  adjustStats(pHdr->iSize, -1);
  memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
                  pHdr->iSize + sizeof(int) + pHdr->nTitle);
  free(z);
  sqlite3_mutex_leave(mem.mutex);  
}

/*
** Change the size of an existing memory allocation.
**
** For this debugging implementation, we *always* make a copy of the
** allocation into a new place in memory.  In this way, if the 
** higher level code is using pointer to the old allocation, it is 
** much more likely to break and we are much more liking to find
** the error.
*/
static void *sqlite3MemRealloc(void *pPrior, int nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;
  assert( mem.disallow==0 );
  pOldHdr = sqlite3MemsysGetHeader(pPrior);
  pNew = sqlite3MemMalloc(nByte);
  if( pNew ){
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
    if( nByte>pOldHdr->iSize ){
      memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
    }
    sqlite3MemFree(pPrior);
  }
  return pNew;
}

/*
** Populate the low-level memory allocation function pointers in
** sqlite3GlobalConfig.m with pointers to the routines in this file.
*/
void sqlite3MemSetDefault(void){
  static const sqlite3_mem_methods defaultMethods = {
     sqlite3MemMalloc,
     sqlite3MemFree,
     sqlite3MemRealloc,
     sqlite3MemSize,
     sqlite3MemRoundup,
     sqlite3MemInit,
     sqlite3MemShutdown,
     0
  };
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
}

/*
** Set the number of backtrace levels kept for each allocation.
** A value of zero turns off backtracing.  The number is always rounded
** up to a multiple of 2.
*/
void sqlite3MemdebugBacktrace(int depth){
  if( depth<0 ){ depth = 0; }
  if( depth>20 ){ depth = 20; }
  depth = (depth+1)&0xfe;
  mem.nBacktrace = depth;
}

void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  mem.xBacktrace = xBacktrace;
}

/*
** Set the title string for subsequent allocations.
*/
void sqlite3MemdebugSettitle(const char *zTitle){
  unsigned int n = sqlite3Strlen30(zTitle) + 1;
  sqlite3_mutex_enter(mem.mutex);
  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  memcpy(mem.zTitle, zTitle, n);
  mem.zTitle[n] = 0;
  mem.nTitle = ROUND8(n);
  sqlite3_mutex_leave(mem.mutex);
}

void sqlite3MemdebugSync(){
  struct MemBlockHdr *pHdr;
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
    void **pBt = (void**)pHdr;
    pBt -= pHdr->nBacktraceSlots;
    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  }
}

/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
void sqlite3MemdebugDump(const char *zFilename){
  FILE *out;
  struct MemBlockHdr *pHdr;
  void **pBt;
  int i;
  out = fopen(zFilename, "w");
  if( out==0 ){
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                    zFilename);
    return;
  }
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
    char *z = (char*)pHdr;
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
    if( pHdr->nBacktrace ){
      fflush(out);
      pBt = (void**)pHdr;
      pBt -= pHdr->nBacktraceSlots;
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
      fprintf(out, "\n");
    }
  }
  fprintf(out, "COUNTS:\n");
  for(i=0; i<NCSIZE-1; i++){
    if( mem.nAlloc[i] ){
      fprintf(out, "   %5d: %10d %10d %10d\n", 
            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
    }
  }
  if( mem.nAlloc[NCSIZE-1] ){
    fprintf(out, "   %5d: %10d %10d %10d\n",
             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  }
  fclose(out);
}

/*
** Return the number of times sqlite3MemMalloc() has been called.
*/
int sqlite3MemdebugMallocCount(){
  int i;
  int nTotal = 0;
  for(i=0; i<NCSIZE; i++){
    nTotal += mem.nAlloc[i];
  }
  return nTotal;
}


#endif /* SQLITE_MEMDEBUG */

Added src/mem3.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/*
** 2007 October 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement a memory
** allocation subsystem for use by SQLite. 
**
** This version of the memory allocation subsystem omits all
** use of malloc(). The SQLite user supplies a block of memory
** before calling sqlite3_initialize() from which allocations
** are made and returned by the xMalloc() and xRealloc() 
** implementations. Once sqlite3_initialize() has been called,
** the amount of memory available to SQLite is fixed and cannot
** be changed.
**
** This version of the memory allocation subsystem is included
** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
**
** $Id: mem3.c,v 1.25 2008/11/19 16:52:44 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** This version of the memory allocator is only built into the library
** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
** mean that the library will use a memory-pool by default, just that
** it is available. The mempool allocator is activated by calling
** sqlite3_config().
*/
#ifdef SQLITE_ENABLE_MEMSYS3

/*
** Maximum size (in Mem3Blocks) of a "small" chunk.
*/
#define MX_SMALL 10


/*
** Number of freelist hash slots
*/
#define N_HASH  61

/*
** A memory allocation (also called a "chunk") consists of two or 
** more blocks where each block is 8 bytes.  The first 8 bytes are 
** a header that is not returned to the user.
**
** A chunk is two or more blocks that is either checked out or
** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
** size of the allocation in blocks if the allocation is free.
** The u.hdr.size4x&1 bit is true if the chunk is checked out and
** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
** is true if the previous chunk is checked out and false if the
** previous chunk is free.  The u.hdr.prevSize field is the size of
** the previous chunk in blocks if the previous chunk is on the
** freelist. If the previous chunk is checked out, then
** u.hdr.prevSize can be part of the data for that chunk and should
** not be read or written.
**
** We often identify a chunk by its index in mem3.aPool[].  When
** this is done, the chunk index refers to the second block of
** the chunk.  In this way, the first chunk has an index of 1.
** A chunk index of 0 means "no such chunk" and is the equivalent
** of a NULL pointer.
**
** The second block of free chunks is of the form u.list.  The
** two fields form a double-linked list of chunks of related sizes.
** Pointers to the head of the list are stored in mem3.aiSmall[] 
** for smaller chunks and mem3.aiHash[] for larger chunks.
**
** The second block of a chunk is user data if the chunk is checked 
** out.  If a chunk is checked out, the user data may extend into
** the u.hdr.prevSize value of the following chunk.
*/
typedef struct Mem3Block Mem3Block;
struct Mem3Block {
  union {
    struct {
      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
    } hdr;
    struct {
      u32 next;       /* Index in mem3.aPool[] of next free chunk */
      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
    } list;
  } u;
};

/*
** All of the static variables used by this module are collected
** into a single structure named "mem3".  This is to keep the
** static variables organized and to reduce namespace pollution
** when this module is combined with other in the amalgamation.
*/
static SQLITE_WSD struct Mem3Global {
  /*
  ** Memory available for allocation. nPool is the size of the array
  ** (in Mem3Blocks) pointed to by aPool less 2.
  */
  u32 nPool;
  Mem3Block *aPool;

  /*
  ** True if we are evaluating an out-of-memory callback.
  */
  int alarmBusy;
  
  /*
  ** Mutex to control access to the memory allocation subsystem.
  */
  sqlite3_mutex *mutex;
  
  /*
  ** The minimum amount of free space that we have seen.
  */
  u32 mnMaster;

  /*
  ** iMaster is the index of the master chunk.  Most new allocations
  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
  ** of the current master.  iMaster is 0 if there is not master chunk.
  ** The master chunk is not in either the aiHash[] or aiSmall[].
  */
  u32 iMaster;
  u32 szMaster;

  /*
  ** Array of lists of free blocks according to the block size 
  ** for smaller chunks, or a hash on the block size for larger
  ** chunks.
  */
  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
} mem3 = { 97535575 };

#define mem3 GLOBAL(struct Mem3Global, mem3)

/*
** Unlink the chunk at mem3.aPool[i] from list it is currently
** on.  *pRoot is the list that i is a member of.
*/
static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  u32 next = mem3.aPool[i].u.list.next;
  u32 prev = mem3.aPool[i].u.list.prev;
  assert( sqlite3_mutex_held(mem3.mutex) );
  if( prev==0 ){
    *pRoot = next;
  }else{
    mem3.aPool[prev].u.list.next = next;
  }
  if( next ){
    mem3.aPool[next].u.list.prev = prev;
  }
  mem3.aPool[i].u.list.next = 0;
  mem3.aPool[i].u.list.prev = 0;
}

/*
** Unlink the chunk at index i from 
** whatever list is currently a member of.
*/
static void memsys3Unlink(u32 i){
  u32 size, hash;
  assert( sqlite3_mutex_held(mem3.mutex) );
  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  assert( i>=1 );
  size = mem3.aPool[i-1].u.hdr.size4x/4;
  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  assert( size>=2 );
  if( size <= MX_SMALL ){
    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  }else{
    hash = size % N_HASH;
    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  }
}

/*
** Link the chunk at mem3.aPool[i] so that is on the list rooted
** at *pRoot.
*/
static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  assert( sqlite3_mutex_held(mem3.mutex) );
  mem3.aPool[i].u.list.next = *pRoot;
  mem3.aPool[i].u.list.prev = 0;
  if( *pRoot ){
    mem3.aPool[*pRoot].u.list.prev = i;
  }
  *pRoot = i;
}

/*
** Link the chunk at index i into either the appropriate
** small chunk list, or into the large chunk hash table.
*/
static void memsys3Link(u32 i){
  u32 size, hash;
  assert( sqlite3_mutex_held(mem3.mutex) );
  assert( i>=1 );
  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  size = mem3.aPool[i-1].u.hdr.size4x/4;
  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  assert( size>=2 );
  if( size <= MX_SMALL ){
    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  }else{
    hash = size % N_HASH;
    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  }
}

/*
** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
** will already be held (obtained by code in malloc.c) if
** sqlite3GlobalConfig.bMemStat is true.
*/
static void memsys3Enter(void){
  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  sqlite3_mutex_enter(mem3.mutex);
}
static void memsys3Leave(void){
  sqlite3_mutex_leave(mem3.mutex);
}

/*
** Called when we are unable to satisfy an allocation of nBytes.
*/
static void memsys3OutOfMemory(int nByte){
  if( !mem3.alarmBusy ){
    mem3.alarmBusy = 1;
    assert( sqlite3_mutex_held(mem3.mutex) );
    sqlite3_mutex_leave(mem3.mutex);
    sqlite3_release_memory(nByte);
    sqlite3_mutex_enter(mem3.mutex);
    mem3.alarmBusy = 0;
  }
}


/*
** Chunk i is a free chunk that has been unlinked.  Adjust its 
** size parameters for check-out and return a pointer to the 
** user portion of the chunk.
*/
static void *memsys3Checkout(u32 i, u32 nBlock){
  u32 x;
  assert( sqlite3_mutex_held(mem3.mutex) );
  assert( i>=1 );
  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  x = mem3.aPool[i-1].u.hdr.size4x;
  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  return &mem3.aPool[i];
}

/*
** Carve a piece off of the end of the mem3.iMaster free chunk.
** Return a pointer to the new allocation.  Or, if the master chunk
** is not large enough, return 0.
*/
static void *memsys3FromMaster(u32 nBlock){
  assert( sqlite3_mutex_held(mem3.mutex) );
  assert( mem3.szMaster>=nBlock );
  if( nBlock>=mem3.szMaster-1 ){
    /* Use the entire master */
    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
    mem3.iMaster = 0;
    mem3.szMaster = 0;
    mem3.mnMaster = 0;
    return p;
  }else{
    /* Split the master block.  Return the tail. */
    u32 newi, x;
    newi = mem3.iMaster + mem3.szMaster - nBlock;
    assert( newi > mem3.iMaster+1 );
    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
    mem3.szMaster -= nBlock;
    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
    if( mem3.szMaster < mem3.mnMaster ){
      mem3.mnMaster = mem3.szMaster;
    }
    return (void*)&mem3.aPool[newi];
  }
}

/*
** *pRoot is the head of a list of free chunks of the same size
** or same size hash.  In other words, *pRoot is an entry in either
** mem3.aiSmall[] or mem3.aiHash[].  
**
** This routine examines all entries on the given list and tries
** to coalesce each entries with adjacent free chunks.  
**
** If it sees a chunk that is larger than mem3.iMaster, it replaces 
** the current mem3.iMaster with the new larger chunk.  In order for
** this mem3.iMaster replacement to work, the master chunk must be
** linked into the hash tables.  That is not the normal state of
** affairs, of course.  The calling routine must link the master
** chunk before invoking this routine, then must unlink the (possibly
** changed) master chunk once this routine has finished.
*/
static void memsys3Merge(u32 *pRoot){
  u32 iNext, prev, size, i, x;

  assert( sqlite3_mutex_held(mem3.mutex) );
  for(i=*pRoot; i>0; i=iNext){
    iNext = mem3.aPool[i].u.list.next;
    size = mem3.aPool[i-1].u.hdr.size4x;
    assert( (size&1)==0 );
    if( (size&2)==0 ){
      memsys3UnlinkFromList(i, pRoot);
      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
      if( prev==iNext ){
        iNext = mem3.aPool[prev].u.list.next;
      }
      memsys3Unlink(prev);
      size = i + size/4 - prev;
      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
      memsys3Link(prev);
      i = prev;
    }else{
      size /= 4;
    }
    if( size>mem3.szMaster ){
      mem3.iMaster = i;
      mem3.szMaster = size;
    }
  }
}

/*
** Return a block of memory of at least nBytes in size.
** Return NULL if unable.
**
** This function assumes that the necessary mutexes, if any, are
** already held by the caller. Hence "Unsafe".
*/
static void *memsys3MallocUnsafe(int nByte){
  u32 i;
  u32 nBlock;
  u32 toFree;

  assert( sqlite3_mutex_held(mem3.mutex) );
  assert( sizeof(Mem3Block)==8 );
  if( nByte<=12 ){
    nBlock = 2;
  }else{
    nBlock = (nByte + 11)/8;
  }
  assert( nBlock>=2 );

  /* STEP 1:
  ** Look for an entry of the correct size in either the small
  ** chunk table or in the large chunk hash table.  This is
  ** successful most of the time (about 9 times out of 10).
  */
  if( nBlock <= MX_SMALL ){
    i = mem3.aiSmall[nBlock-2];
    if( i>0 ){
      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
      return memsys3Checkout(i, nBlock);
    }
  }else{
    int hash = nBlock % N_HASH;
    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
        return memsys3Checkout(i, nBlock);
      }
    }
  }

  /* STEP 2:
  ** Try to satisfy the allocation by carving a piece off of the end
  ** of the master chunk.  This step usually works if step 1 fails.
  */
  if( mem3.szMaster>=nBlock ){
    return memsys3FromMaster(nBlock);
  }


  /* STEP 3:  
  ** Loop through the entire memory pool.  Coalesce adjacent free
  ** chunks.  Recompute the master chunk as the largest free chunk.
  ** Then try again to satisfy the allocation by carving a piece off
  ** of the end of the master chunk.  This step happens very
  ** rarely (we hope!)
  */
  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
    memsys3OutOfMemory(toFree);
    if( mem3.iMaster ){
      memsys3Link(mem3.iMaster);
      mem3.iMaster = 0;
      mem3.szMaster = 0;
    }
    for(i=0; i<N_HASH; i++){
      memsys3Merge(&mem3.aiHash[i]);
    }
    for(i=0; i<MX_SMALL-1; i++){
      memsys3Merge(&mem3.aiSmall[i]);
    }
    if( mem3.szMaster ){
      memsys3Unlink(mem3.iMaster);
      if( mem3.szMaster>=nBlock ){
        return memsys3FromMaster(nBlock);
      }
    }
  }

  /* If none of the above worked, then we fail. */
  return 0;
}

/*
** Free an outstanding memory allocation.
**
** This function assumes that the necessary mutexes, if any, are
** already held by the caller. Hence "Unsafe".
*/
void memsys3FreeUnsafe(void *pOld){
  Mem3Block *p = (Mem3Block*)pOld;
  int i;
  u32 size, x;
  assert( sqlite3_mutex_held(mem3.mutex) );
  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  i = p - mem3.aPool;
  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  size = mem3.aPool[i-1].u.hdr.size4x/4;
  assert( i+size<=mem3.nPool+1 );
  mem3.aPool[i-1].u.hdr.size4x &= ~1;
  mem3.aPool[i+size-1].u.hdr.prevSize = size;
  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  memsys3Link(i);

  /* Try to expand the master using the newly freed chunk */
  if( mem3.iMaster ){
    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
      mem3.iMaster -= size;
      mem3.szMaster += size;
      memsys3Unlink(mem3.iMaster);
      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
    }
    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
      memsys3Unlink(mem3.iMaster+mem3.szMaster);
      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
    }
  }
}

/*
** Return the size of an outstanding allocation, in bytes.  The
** size returned omits the 8-byte header overhead.  This only
** works for chunks that are currently checked out.
*/
static int memsys3Size(void *p){
  Mem3Block *pBlock;
  if( p==0 ) return 0;
  pBlock = (Mem3Block*)p;
  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
}

/*
** Round up a request size to the next valid allocation size.
*/
static int memsys3Roundup(int n){
  if( n<=12 ){
    return 12;
  }else{
    return ((n+11)&~7) - 4;
  }
}

/*
** Allocate nBytes of memory.
*/
static void *memsys3Malloc(int nBytes){
  sqlite3_int64 *p;
  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
  memsys3Enter();
  p = memsys3MallocUnsafe(nBytes);
  memsys3Leave();
  return (void*)p; 
}

/*
** Free memory.
*/
void memsys3Free(void *pPrior){
  assert( pPrior );
  memsys3Enter();
  memsys3FreeUnsafe(pPrior);
  memsys3Leave();
}

/*
** Change the size of an existing memory allocation
*/
void *memsys3Realloc(void *pPrior, int nBytes){
  int nOld;
  void *p;
  if( pPrior==0 ){
    return sqlite3_malloc(nBytes);
  }
  if( nBytes<=0 ){
    sqlite3_free(pPrior);
    return 0;
  }
  nOld = memsys3Size(pPrior);
  if( nBytes<=nOld && nBytes>=nOld-128 ){
    return pPrior;
  }
  memsys3Enter();
  p = memsys3MallocUnsafe(nBytes);
  if( p ){
    if( nOld<nBytes ){
      memcpy(p, pPrior, nOld);
    }else{
      memcpy(p, pPrior, nBytes);
    }
    memsys3FreeUnsafe(pPrior);
  }
  memsys3Leave();
  return p;
}

/*
** Initialize this module.
*/
static int memsys3Init(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  if( !sqlite3GlobalConfig.pHeap ){
    return SQLITE_ERROR;
  }

  /* Store a pointer to the memory block in global structure mem3. */
  assert( sizeof(Mem3Block)==8 );
  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;

  /* Initialize the master block. */
  mem3.szMaster = mem3.nPool;
  mem3.mnMaster = mem3.szMaster;
  mem3.iMaster = 1;
  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;

  return SQLITE_OK;
}

/*
** Deinitialize this module.
*/
static void memsys3Shutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  mem3.mutex = 0;
  return;
}



/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
void sqlite3Memsys3Dump(const char *zFilename){
#ifdef SQLITE_DEBUG
  FILE *out;
  u32 i, j;
  u32 size;
  if( zFilename==0 || zFilename[0]==0 ){
    out = stdout;
  }else{
    out = fopen(zFilename, "w");
    if( out==0 ){
      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                      zFilename);
      return;
    }
  }
  memsys3Enter();
  fprintf(out, "CHUNKS:\n");
  for(i=1; i<=mem3.nPool; i+=size/4){
    size = mem3.aPool[i-1].u.hdr.size4x;
    if( size/4<=1 ){
      fprintf(out, "%p size error\n", &mem3.aPool[i]);
      assert( 0 );
      break;
    }
    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
      assert( 0 );
      break;
    }
    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
      assert( 0 );
      break;
    }
    if( size&1 ){
      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
    }else{
      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
                  i==mem3.iMaster ? " **master**" : "");
    }
  }
  for(i=0; i<MX_SMALL-1; i++){
    if( mem3.aiSmall[i]==0 ) continue;
    fprintf(out, "small(%2d):", i);
    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
      fprintf(out, " %p(%d)", &mem3.aPool[j],
              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
    }
    fprintf(out, "\n"); 
  }
  for(i=0; i<N_HASH; i++){
    if( mem3.aiHash[i]==0 ) continue;
    fprintf(out, "hash(%2d):", i);
    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
      fprintf(out, " %p(%d)", &mem3.aPool[j],
              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
    }
    fprintf(out, "\n"); 
  }
  fprintf(out, "master=%d\n", mem3.iMaster);
  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  sqlite3_mutex_leave(mem3.mutex);
  if( out==stdout ){
    fflush(stdout);
  }else{
    fclose(out);
  }
#else
  UNUSED_PARAMETER(zFilename);
#endif
}

/*
** This routine is the only routine in this file with external 
** linkage.
**
** Populate the low-level memory allocation function pointers in
** sqlite3GlobalConfig.m with pointers to the routines in this file. The
** arguments specify the block of memory to manage.
**
** This routine is only called by sqlite3_config(), and therefore
** is not required to be threadsafe (it is not).
*/
const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  static const sqlite3_mem_methods mempoolMethods = {
     memsys3Malloc,
     memsys3Free,
     memsys3Realloc,
     memsys3Size,
     memsys3Roundup,
     memsys3Init,
     memsys3Shutdown,
     0
  };
  return &mempoolMethods;
}

#endif /* SQLITE_ENABLE_MEMSYS3 */

Added src/mem5.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
** 2007 October 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement a memory
** allocation subsystem for use by SQLite. 
**
** This version of the memory allocation subsystem omits all
** use of malloc(). The application gives SQLite a block of memory
** before calling sqlite3_initialize() from which allocations
** are made and returned by the xMalloc() and xRealloc() 
** implementations. Once sqlite3_initialize() has been called,
** the amount of memory available to SQLite is fixed and cannot
** be changed.
**
** This version of the memory allocation subsystem is included
** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
**
** This memory allocator uses the following algorithm:
**
**   1.  All memory allocations sizes are rounded up to a power of 2.
**
**   2.  If two adjacent free blocks are the halves of a larger block,
**       then the two blocks are coalesed into the single larger block.
**
**   3.  New memory is allocated from the first available free block.
**
** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
** Concerning Dynamic Storage Allocation". Journal of the Association for
** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
** 
** Let n be the size of the largest allocation divided by the minimum
** allocation size (after rounding all sizes up to a power of 2.)  Let M
** be the maximum amount of memory ever outstanding at one time.  Let
** N be the total amount of memory available for allocation.  Robson
** proved that this memory allocator will never breakdown due to 
** fragmentation as long as the following constraint holds:
**
**      N >=  M*(1 + log2(n)/2) - n + 1
**
** The sqlite3_status() logic tracks the maximum values of n and M so
** that an application can, at any time, verify this constraint.
*/
#include "sqliteInt.h"

/*
** This version of the memory allocator is used only when 
** SQLITE_ENABLE_MEMSYS5 is defined.
*/
#ifdef SQLITE_ENABLE_MEMSYS5

/*
** A minimum allocation is an instance of the following structure.
** Larger allocations are an array of these structures where the
** size of the array is a power of 2.
**
** The size of this object must be a power of two.  That fact is
** verified in memsys5Init().
*/
typedef struct Mem5Link Mem5Link;
struct Mem5Link {
  int next;       /* Index of next free chunk */
  int prev;       /* Index of previous free chunk */
};

/*
** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
** mem5.szAtom is always at least 8 and 32-bit integers are used,
** it is not actually possible to reach this limit.
*/
#define LOGMAX 30

/*
** Masks used for mem5.aCtrl[] elements.
*/
#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
#define CTRL_FREE     0x20    /* True if not checked out */

/*
** All of the static variables used by this module are collected
** into a single structure named "mem5".  This is to keep the
** static variables organized and to reduce namespace pollution
** when this module is combined with other in the amalgamation.
*/
static SQLITE_WSD struct Mem5Global {
  /*
  ** Memory available for allocation
  */
  int szAtom;      /* Smallest possible allocation in bytes */
  int nBlock;      /* Number of szAtom sized blocks in zPool */
  u8 *zPool;       /* Memory available to be allocated */
  
  /*
  ** Mutex to control access to the memory allocation subsystem.
  */
  sqlite3_mutex *mutex;

  /*
  ** Performance statistics
  */
  u64 nAlloc;         /* Total number of calls to malloc */
  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
  u64 totalExcess;    /* Total internal fragmentation */
  u32 currentOut;     /* Current checkout, including internal fragmentation */
  u32 currentCount;   /* Current number of distinct checkouts */
  u32 maxOut;         /* Maximum instantaneous currentOut */
  u32 maxCount;       /* Maximum instantaneous currentCount */
  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
  
  /*
  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
  ** and so forth.
  */
  int aiFreelist[LOGMAX+1];

  /*
  ** Space for tracking which blocks are checked out and the size
  ** of each block.  One byte per block.
  */
  u8 *aCtrl;

} mem5 = { 0 };

/*
** Access the static variable through a macro for SQLITE_OMIT_WSD
*/
#define mem5 GLOBAL(struct Mem5Global, mem5)

/*
** Assuming mem5.zPool is divided up into an array of Mem5Link
** structures, return a pointer to the idx-th such lik.
*/
#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))

/*
** Unlink the chunk at mem5.aPool[i] from list it is currently
** on.  It should be found on mem5.aiFreelist[iLogsize].
*/
static void memsys5Unlink(int i, int iLogsize){
  int next, prev;
  assert( i>=0 && i<mem5.nBlock );
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );

  next = MEM5LINK(i)->next;
  prev = MEM5LINK(i)->prev;
  if( prev<0 ){
    mem5.aiFreelist[iLogsize] = next;
  }else{
    MEM5LINK(prev)->next = next;
  }
  if( next>=0 ){
    MEM5LINK(next)->prev = prev;
  }
}

/*
** Link the chunk at mem5.aPool[i] so that is on the iLogsize
** free list.
*/
static void memsys5Link(int i, int iLogsize){
  int x;
  assert( sqlite3_mutex_held(mem5.mutex) );
  assert( i>=0 && i<mem5.nBlock );
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );

  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  MEM5LINK(i)->prev = -1;
  if( x>=0 ){
    assert( x<mem5.nBlock );
    MEM5LINK(x)->prev = i;
  }
  mem5.aiFreelist[iLogsize] = i;
}

/*
** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
** will already be held (obtained by code in malloc.c) if
** sqlite3GlobalConfig.bMemStat is true.
*/
static void memsys5Enter(void){
  sqlite3_mutex_enter(mem5.mutex);
}
static void memsys5Leave(void){
  sqlite3_mutex_leave(mem5.mutex);
}

/*
** Return the size of an outstanding allocation, in bytes.  The
** size returned omits the 8-byte header overhead.  This only
** works for chunks that are currently checked out.
*/
static int memsys5Size(void *p){
  int iSize = 0;
  if( p ){
    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
    assert( i>=0 && i<mem5.nBlock );
    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  }
  return iSize;
}

/*
** Find the first entry on the freelist iLogsize.  Unlink that
** entry and return its index. 
*/
static int memsys5UnlinkFirst(int iLogsize){
  int i;
  int iFirst;

  assert( iLogsize>=0 && iLogsize<=LOGMAX );
  i = iFirst = mem5.aiFreelist[iLogsize];
  assert( iFirst>=0 );
  while( i>0 ){
    if( i<iFirst ) iFirst = i;
    i = MEM5LINK(i)->next;
  }
  memsys5Unlink(iFirst, iLogsize);
  return iFirst;
}

/*
** Return a block of memory of at least nBytes in size.
** Return NULL if unable.  Return NULL if nBytes==0.
**
** The caller guarantees that nByte positive.
**
** The caller has obtained a mutex prior to invoking this
** routine so there is never any chance that two or more
** threads can be in this routine at the same time.
*/
static void *memsys5MallocUnsafe(int nByte){
  int i;           /* Index of a mem5.aPool[] slot */
  int iBin;        /* Index into mem5.aiFreelist[] */
  int iFullSz;     /* Size of allocation rounded up to power of 2 */
  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */

  /* nByte must be a positive */
  assert( nByte>0 );

  /* Keep track of the maximum allocation request.  Even unfulfilled
  ** requests are counted */
  if( (u32)nByte>mem5.maxRequest ){
    mem5.maxRequest = nByte;
  }

  /* Abort if the requested allocation size is larger than the largest
  ** power of two that we can represent using 32-bit signed integers.
  */
  if( nByte > 0x40000000 ){
    return 0;
  }

  /* Round nByte up to the next valid power of two */
  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}

  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  ** block.  If not, then split a block of the next larger power of
  ** two in order to create a new free block of size iLogsize.
  */
  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  if( iBin>LOGMAX ) return 0;
  i = memsys5UnlinkFirst(iBin);
  while( iBin>iLogsize ){
    int newSize;

    iBin--;
    newSize = 1 << iBin;
    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
    memsys5Link(i+newSize, iBin);
  }
  mem5.aCtrl[i] = iLogsize;

  /* Update allocator performance statistics. */
  mem5.nAlloc++;
  mem5.totalAlloc += iFullSz;
  mem5.totalExcess += iFullSz - nByte;
  mem5.currentCount++;
  mem5.currentOut += iFullSz;
  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;

  /* Return a pointer to the allocated memory. */
  return (void*)&mem5.zPool[i*mem5.szAtom];
}

/*
** Free an outstanding memory allocation.
*/
static void memsys5FreeUnsafe(void *pOld){
  u32 size, iLogsize;
  int iBlock;

  /* Set iBlock to the index of the block pointed to by pOld in 
  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  */
  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;

  /* Check that the pointer pOld points to a valid, non-free block. */
  assert( iBlock>=0 && iBlock<mem5.nBlock );
  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );

  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  size = 1<<iLogsize;
  assert( iBlock+size-1<(u32)mem5.nBlock );

  mem5.aCtrl[iBlock] |= CTRL_FREE;
  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  assert( mem5.currentCount>0 );
  assert( mem5.currentOut>=(size*mem5.szAtom) );
  mem5.currentCount--;
  mem5.currentOut -= size*mem5.szAtom;
  assert( mem5.currentOut>0 || mem5.currentCount==0 );
  assert( mem5.currentCount>0 || mem5.currentOut==0 );

  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  while( ALWAYS(iLogsize<LOGMAX) ){
    int iBuddy;
    if( (iBlock>>iLogsize) & 1 ){
      iBuddy = iBlock - size;
    }else{
      iBuddy = iBlock + size;
    }
    assert( iBuddy>=0 );
    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
    memsys5Unlink(iBuddy, iLogsize);
    iLogsize++;
    if( iBuddy<iBlock ){
      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
      mem5.aCtrl[iBlock] = 0;
      iBlock = iBuddy;
    }else{
      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
      mem5.aCtrl[iBuddy] = 0;
    }
    size *= 2;
  }
  memsys5Link(iBlock, iLogsize);
}

/*
** Allocate nBytes of memory
*/
static void *memsys5Malloc(int nBytes){
  sqlite3_int64 *p = 0;
  if( nBytes>0 ){
    memsys5Enter();
    p = memsys5MallocUnsafe(nBytes);
    memsys5Leave();
  }
  return (void*)p; 
}

/*
** Free memory.
**
** The outer layer memory allocator prevents this routine from
** being called with pPrior==0.
*/
static void memsys5Free(void *pPrior){
  assert( pPrior!=0 );
  memsys5Enter();
  memsys5FreeUnsafe(pPrior);
  memsys5Leave();  
}

/*
** Change the size of an existing memory allocation.
**
** The outer layer memory allocator prevents this routine from
** being called with pPrior==0.  
**
** nBytes is always a value obtained from a prior call to
** memsys5Round().  Hence nBytes is always a non-negative power
** of two.  If nBytes==0 that means that an oversize allocation
** (an allocation larger than 0x40000000) was requested and this
** routine should return 0 without freeing pPrior.
*/
static void *memsys5Realloc(void *pPrior, int nBytes){
  int nOld;
  void *p;
  assert( pPrior!=0 );
  assert( (nBytes&(nBytes-1))==0 );
  assert( nBytes>=0 );
  if( nBytes==0 ){
    return 0;
  }
  nOld = memsys5Size(pPrior);
  if( nBytes<=nOld ){
    return pPrior;
  }
  memsys5Enter();
  p = memsys5MallocUnsafe(nBytes);
  if( p ){
    memcpy(p, pPrior, nOld);
    memsys5FreeUnsafe(pPrior);
  }
  memsys5Leave();
  return p;
}

/*
** Round up a request size to the next valid allocation size.  If
** the allocation is too large to be handled by this allocation system,
** return 0.
**
** All allocations must be a power of two and must be expressed by a
** 32-bit signed integer.  Hence the largest allocation is 0x40000000
** or 1073741824 bytes.
*/
static int memsys5Roundup(int n){
  int iFullSz;
  if( n > 0x40000000 ) return 0;
  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  return iFullSz;
}

/*
** Return the ceiling of the logarithm base 2 of iValue.
**
** Examples:   memsys5Log(1) -> 0
**             memsys5Log(2) -> 1
**             memsys5Log(4) -> 2
**             memsys5Log(5) -> 3
**             memsys5Log(8) -> 3
**             memsys5Log(9) -> 4
*/
static int memsys5Log(int iValue){
  int iLog;
  for(iLog=0; (1<<iLog)<iValue; iLog++);
  return iLog;
}

/*
** Initialize the memory allocator.
**
** This routine is not threadsafe.  The caller must be holding a mutex
** to prevent multiple threads from entering at the same time.
*/
static int memsys5Init(void *NotUsed){
  int ii;            /* Loop counter */
  int nByte;         /* Number of bytes of memory available to this allocator */
  u8 *zByte;         /* Memory usable by this allocator */
  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
  int iOffset;       /* An offset into mem5.aCtrl[] */

  UNUSED_PARAMETER(NotUsed);

  /* For the purposes of this routine, disable the mutex */
  mem5.mutex = 0;

  /* The size of a Mem5Link object must be a power of two.  Verify that
  ** this is case.
  */
  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );

  nByte = sqlite3GlobalConfig.nHeap;
  zByte = (u8*)sqlite3GlobalConfig.pHeap;
  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */

  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  mem5.szAtom = (1<<nMinLog);
  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
    mem5.szAtom = mem5.szAtom << 1;
  }

  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  mem5.zPool = zByte;
  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];

  for(ii=0; ii<=LOGMAX; ii++){
    mem5.aiFreelist[ii] = -1;
  }

  iOffset = 0;
  for(ii=LOGMAX; ii>=0; ii--){
    int nAlloc = (1<<ii);
    if( (iOffset+nAlloc)<=mem5.nBlock ){
      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
      memsys5Link(iOffset, ii);
      iOffset += nAlloc;
    }
    assert((iOffset+nAlloc)>mem5.nBlock);
  }

  /* If a mutex is required for normal operation, allocate one */
  if( sqlite3GlobalConfig.bMemstat==0 ){
    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }

  return SQLITE_OK;
}

/*
** Deinitialize this module.
*/
static void memsys5Shutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  mem5.mutex = 0;
  return;
}

#ifdef SQLITE_TEST
/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
void sqlite3Memsys5Dump(const char *zFilename){
  FILE *out;
  int i, j, n;
  int nMinLog;

  if( zFilename==0 || zFilename[0]==0 ){
    out = stdout;
  }else{
    out = fopen(zFilename, "w");
    if( out==0 ){
      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                      zFilename);
      return;
    }
  }
  memsys5Enter();
  nMinLog = memsys5Log(mem5.szAtom);
  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  }
  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
  memsys5Leave();
  if( out==stdout ){
    fflush(stdout);
  }else{
    fclose(out);
  }
}
#endif

/*
** This routine is the only routine in this file with external 
** linkage. It returns a pointer to a static sqlite3_mem_methods
** struct populated with the memsys5 methods.
*/
const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  static const sqlite3_mem_methods memsys5Methods = {
     memsys5Malloc,
     memsys5Free,
     memsys5Realloc,
     memsys5Size,
     memsys5Roundup,
     memsys5Init,
     memsys5Shutdown,
     0
  };
  return &memsys5Methods;
}

#endif /* SQLITE_ENABLE_MEMSYS5 */

Added src/memjournal.c.







































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
** 2008 October 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code use to implement an in-memory rollback journal.
** The in-memory rollback journal is used to journal transactions for
** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
**
** @(#) $Id: memjournal.c,v 1.12 2009/05/04 11:42:30 danielk1977 Exp $
*/
#include "sqliteInt.h"

/* Forward references to internal structures */
typedef struct MemJournal MemJournal;
typedef struct FilePoint FilePoint;
typedef struct FileChunk FileChunk;

/* Space to hold the rollback journal is allocated in increments of
** this many bytes.
**
** The size chosen is a little less than a power of two.  That way,
** the FileChunk object will have a size that almost exactly fills
** a power-of-two allocation.  This mimimizes wasted space in power-of-two
** memory allocators.
*/
#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))

/* Macro to find the minimum of two numeric values.
*/
#ifndef MIN
# define MIN(x,y) ((x)<(y)?(x):(y))
#endif

/*
** The rollback journal is composed of a linked list of these structures.
*/
struct FileChunk {
  FileChunk *pNext;               /* Next chunk in the journal */
  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
};

/*
** An instance of this object serves as a cursor into the rollback journal.
** The cursor can be either for reading or writing.
*/
struct FilePoint {
  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
  FileChunk *pChunk;              /* Specific chunk into which cursor points */
};

/*
** This subclass is a subclass of sqlite3_file.  Each open memory-journal
** is an instance of this class.
*/
struct MemJournal {
  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
  FileChunk *pFirst;              /* Head of in-memory chunk-list */
  FilePoint endpoint;             /* Pointer to the end of the file */
  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
};

/*
** Read data from the in-memory journal file.  This is the implementation
** of the sqlite3_vfs.xRead method.
*/
static int memjrnlRead(
  sqlite3_file *pJfd,    /* The journal file from which to read */
  void *zBuf,            /* Put the results here */
  int iAmt,              /* Number of bytes to read */
  sqlite_int64 iOfst     /* Begin reading at this offset */
){
  MemJournal *p = (MemJournal *)pJfd;
  u8 *zOut = zBuf;
  int nRead = iAmt;
  int iChunkOffset;
  FileChunk *pChunk;

  /* SQLite never tries to read past the end of a rollback journal file */
  assert( iOfst+iAmt<=p->endpoint.iOffset );

  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
    sqlite3_int64 iOff = 0;
    for(pChunk=p->pFirst; 
        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
        pChunk=pChunk->pNext
    ){
      iOff += JOURNAL_CHUNKSIZE;
    }
  }else{
    pChunk = p->readpoint.pChunk;
  }

  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  do {
    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
    zOut += nCopy;
    nRead -= iSpace;
    iChunkOffset = 0;
  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  p->readpoint.iOffset = iOfst+iAmt;
  p->readpoint.pChunk = pChunk;

  return SQLITE_OK;
}

/*
** Write data to the file.
*/
static int memjrnlWrite(
  sqlite3_file *pJfd,    /* The journal file into which to write */
  const void *zBuf,      /* Take data to be written from here */
  int iAmt,              /* Number of bytes to write */
  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
){
  MemJournal *p = (MemJournal *)pJfd;
  int nWrite = iAmt;
  u8 *zWrite = (u8 *)zBuf;

  /* An in-memory journal file should only ever be appended to. Random
  ** access writes are not required by sqlite.
  */
  assert( iOfst==p->endpoint.iOffset );
  UNUSED_PARAMETER(iOfst);

  while( nWrite>0 ){
    FileChunk *pChunk = p->endpoint.pChunk;
    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);

    if( iChunkOffset==0 ){
      /* New chunk is required to extend the file. */
      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
      if( !pNew ){
        return SQLITE_IOERR_NOMEM;
      }
      pNew->pNext = 0;
      if( pChunk ){
        assert( p->pFirst );
        pChunk->pNext = pNew;
      }else{
        assert( !p->pFirst );
        p->pFirst = pNew;
      }
      p->endpoint.pChunk = pNew;
    }

    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
    zWrite += iSpace;
    nWrite -= iSpace;
    p->endpoint.iOffset += iSpace;
  }

  return SQLITE_OK;
}

/*
** Truncate the file.
*/
static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  MemJournal *p = (MemJournal *)pJfd;
  FileChunk *pChunk;
  assert(size==0);
  UNUSED_PARAMETER(size);
  pChunk = p->pFirst;
  while( pChunk ){
    FileChunk *pTmp = pChunk;
    pChunk = pChunk->pNext;
    sqlite3_free(pTmp);
  }
  sqlite3MemJournalOpen(pJfd);
  return SQLITE_OK;
}

/*
** Close the file.
*/
static int memjrnlClose(sqlite3_file *pJfd){
  memjrnlTruncate(pJfd, 0);
  return SQLITE_OK;
}


/*
** Sync the file.
**
** Syncing an in-memory journal is a no-op.  And, in fact, this routine
** is never called in a working implementation.  This implementation
** exists purely as a contingency, in case some malfunction in some other
** part of SQLite causes Sync to be called by mistake.
*/
static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
  UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
  assert( 0 );                                                 /*NO_TEST*/
  return SQLITE_OK;                                            /*NO_TEST*/
}                                                              /*NO_TEST*/

/*
** Query the size of the file in bytes.
*/
static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  MemJournal *p = (MemJournal *)pJfd;
  *pSize = (sqlite_int64) p->endpoint.iOffset;
  return SQLITE_OK;
}

/*
** Table of methods for MemJournal sqlite3_file object.
*/
static struct sqlite3_io_methods MemJournalMethods = {
  1,                /* iVersion */
  memjrnlClose,     /* xClose */
  memjrnlRead,      /* xRead */
  memjrnlWrite,     /* xWrite */
  memjrnlTruncate,  /* xTruncate */
  memjrnlSync,      /* xSync */
  memjrnlFileSize,  /* xFileSize */
  0,                /* xLock */
  0,                /* xUnlock */
  0,                /* xCheckReservedLock */
  0,                /* xFileControl */
  0,                /* xSectorSize */
  0                 /* xDeviceCharacteristics */
};

/* 
** Open a journal file.
*/
void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  MemJournal *p = (MemJournal *)pJfd;
  assert( EIGHT_BYTE_ALIGNMENT(p) );
  memset(p, 0, sqlite3MemJournalSize());
  p->pMethod = &MemJournalMethods;
}

/*
** Return true if the file-handle passed as an argument is 
** an in-memory journal 
*/
int sqlite3IsMemJournal(sqlite3_file *pJfd){
  return pJfd->pMethods==&MemJournalMethods;
}

/* 
** Return the number of bytes required to store a MemJournal that uses vfs
** pVfs to create the underlying on-disk files.
*/
int sqlite3MemJournalSize(void){
  return sizeof(MemJournal);
}

Added src/mutex.c.



















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*
** 2007 August 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes.
**
** This file contains code that is common across all mutex implementations.

**
** $Id: mutex.c,v 1.31 2009/07/16 18:21:18 drh Exp $
*/
#include "sqliteInt.h"

#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
/*
** For debugging purposes, record when the mutex subsystem is initialized
** and uninitialized so that we can assert() if there is an attempt to
** allocate a mutex while the system is uninitialized.
*/
static SQLITE_WSD int mutexIsInit = 0;
#endif /* SQLITE_DEBUG */


#ifndef SQLITE_MUTEX_OMIT
/*
** Initialize the mutex system.
*/
int sqlite3MutexInit(void){ 
  int rc = SQLITE_OK;
  if( sqlite3GlobalConfig.bCoreMutex ){
    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
      /* If the xMutexAlloc method has not been set, then the user did not
      ** install a mutex implementation via sqlite3_config() prior to 
      ** sqlite3_initialize() being called. This block copies pointers to
      ** the default implementation into the sqlite3GlobalConfig structure.
      */
      sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;

      memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
      memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
             sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
      pTo->xMutexAlloc = pFrom->xMutexAlloc;
    }
    rc = sqlite3GlobalConfig.mutex.xMutexInit();
  }

#ifdef SQLITE_DEBUG
  GLOBAL(int, mutexIsInit) = 1;
#endif

  return rc;
}

/*
** Shutdown the mutex system. This call frees resources allocated by
** sqlite3MutexInit().
*/
int sqlite3MutexEnd(void){
  int rc = SQLITE_OK;
  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  }

#ifdef SQLITE_DEBUG
  GLOBAL(int, mutexIsInit) = 0;
#endif

  return rc;
}

/*
** Retrieve a pointer to a static mutex or allocate a new dynamic one.
*/
sqlite3_mutex *sqlite3_mutex_alloc(int id){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite3_initialize() ) return 0;
#endif
  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
}

sqlite3_mutex *sqlite3MutexAlloc(int id){
  if( !sqlite3GlobalConfig.bCoreMutex ){
    return 0;
  }
  assert( GLOBAL(int, mutexIsInit) );
  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
}

/*
** Free a dynamic mutex.
*/
void sqlite3_mutex_free(sqlite3_mutex *p){
  if( p ){
    sqlite3GlobalConfig.mutex.xMutexFree(p);
  }
}

/*
** Obtain the mutex p. If some other thread already has the mutex, block
** until it can be obtained.
*/
void sqlite3_mutex_enter(sqlite3_mutex *p){
  if( p ){
    sqlite3GlobalConfig.mutex.xMutexEnter(p);
  }
}

/*
** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
*/
int sqlite3_mutex_try(sqlite3_mutex *p){
  int rc = SQLITE_OK;
  if( p ){
    return sqlite3GlobalConfig.mutex.xMutexTry(p);
  }
  return rc;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was previously
** entered by the same thread.  The behavior is undefined if the mutex 
** is not currently entered. If a NULL pointer is passed as an argument
** this function is a no-op.
*/
void sqlite3_mutex_leave(sqlite3_mutex *p){
  if( p ){
    sqlite3GlobalConfig.mutex.xMutexLeave(p);
  }
}

#ifndef NDEBUG
/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
int sqlite3_mutex_held(sqlite3_mutex *p){
  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
}
int sqlite3_mutex_notheld(sqlite3_mutex *p){
  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
}
#endif

#endif /* SQLITE_MUTEX_OMIT */

Added src/mutex.h.



















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
** 2007 August 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains the common header for all mutex implementations.
** The sqliteInt.h header #includes this file so that it is available
** to all source files.  We break it out in an effort to keep the code
** better organized.
**
** NOTE:  source files should *not* #include this header file directly.
** Source files should #include the sqliteInt.h file and let that file
** include this one indirectly.
**
** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $
*/


/*
** Figure out what version of the code to use.  The choices are
**
**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
**                             mutexes implemention cannot be overridden
**                             at start-time.
**
**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
**                             mutual exclusion is provided.  But this
**                             implementation can be overridden at
**                             start-time.
**
**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
**
**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
**
**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
*/
#if !SQLITE_THREADSAFE
# define SQLITE_MUTEX_OMIT
#endif
#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
#  if SQLITE_OS_UNIX
#    define SQLITE_MUTEX_PTHREADS
#  elif SQLITE_OS_WIN
#    define SQLITE_MUTEX_W32
#  elif SQLITE_OS_OS2
#    define SQLITE_MUTEX_OS2
#  else
#    define SQLITE_MUTEX_NOOP
#  endif
#endif

#ifdef SQLITE_MUTEX_OMIT
/*
** If this is a no-op implementation, implement everything as macros.
*/
#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
#define sqlite3_mutex_free(X)
#define sqlite3_mutex_enter(X)
#define sqlite3_mutex_try(X)      SQLITE_OK
#define sqlite3_mutex_leave(X)
#define sqlite3_mutex_held(X)     1
#define sqlite3_mutex_notheld(X)  1
#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
#define sqlite3MutexInit()        SQLITE_OK
#define sqlite3MutexEnd()
#endif /* defined(SQLITE_MUTEX_OMIT) */

Added src/mutex_noop.c.





















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/*
** 2008 October 07
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes.
**
** This implementation in this file does not provide any mutual
** exclusion and is thus suitable for use only in applications
** that use SQLite in a single thread.  The routines defined
** here are place-holders.  Applications can substitute working
** mutex routines at start-time using the
**
**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
**
** interface.
**
** If compiled with SQLITE_DEBUG, then additional logic is inserted
** that does error checking on mutexes to make sure they are being
** called correctly.
**
** $Id: mutex_noop.c,v 1.3 2008/12/05 17:17:08 drh Exp $
*/
#include "sqliteInt.h"


#if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
/*
** Stub routines for all mutex methods.
**
** This routines provide no mutual exclusion or error checking.
*/
static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
static int noopMutexInit(void){ return SQLITE_OK; }
static int noopMutexEnd(void){ return SQLITE_OK; }
static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
static void noopMutexFree(sqlite3_mutex *p){ return; }
static void noopMutexEnter(sqlite3_mutex *p){ return; }
static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
static void noopMutexLeave(sqlite3_mutex *p){ return; }

sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  static sqlite3_mutex_methods sMutex = {
    noopMutexInit,
    noopMutexEnd,
    noopMutexAlloc,
    noopMutexFree,
    noopMutexEnter,
    noopMutexTry,
    noopMutexLeave,

    noopMutexHeld,
    noopMutexNotheld
  };

  return &sMutex;
}
#endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */

#if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
/*
** In this implementation, error checking is provided for testing
** and debugging purposes.  The mutexes still do not provide any
** mutual exclusion.
*/

/*
** The mutex object
*/
struct sqlite3_mutex {
  int id;     /* The mutex type */
  int cnt;    /* Number of entries without a matching leave */
};

/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
static int debugMutexHeld(sqlite3_mutex *p){
  return p==0 || p->cnt>0;
}
static int debugMutexNotheld(sqlite3_mutex *p){
  return p==0 || p->cnt==0;
}

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int debugMutexInit(void){ return SQLITE_OK; }
static int debugMutexEnd(void){ return SQLITE_OK; }

/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated. 
*/
static sqlite3_mutex *debugMutexAlloc(int id){
  static sqlite3_mutex aStatic[6];
  sqlite3_mutex *pNew = 0;
  switch( id ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      pNew = sqlite3Malloc(sizeof(*pNew));
      if( pNew ){
        pNew->id = id;
        pNew->cnt = 0;
      }
      break;
    }
    default: {
      assert( id-2 >= 0 );
      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
      pNew = &aStatic[id-2];
      pNew->id = id;
      break;
    }
  }
  return pNew;
}

/*
** This routine deallocates a previously allocated mutex.
*/
static void debugMutexFree(sqlite3_mutex *p){
  assert( p->cnt==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  sqlite3_free(p);
}

/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void debugMutexEnter(sqlite3_mutex *p){
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  p->cnt++;
}
static int debugMutexTry(sqlite3_mutex *p){
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  p->cnt++;
  return SQLITE_OK;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void debugMutexLeave(sqlite3_mutex *p){
  assert( debugMutexHeld(p) );
  p->cnt--;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
}

sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  static sqlite3_mutex_methods sMutex = {
    debugMutexInit,
    debugMutexEnd,
    debugMutexAlloc,
    debugMutexFree,
    debugMutexEnter,
    debugMutexTry,
    debugMutexLeave,

    debugMutexHeld,
    debugMutexNotheld
  };

  return &sMutex;
}
#endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */

Added src/mutex_os2.c.



































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
** 2007 August 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes for OS/2
**
** $Id: mutex_os2.c,v 1.11 2008/11/22 19:50:54 pweilbacher Exp $
*/
#include "sqliteInt.h"

/*
** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
** See the mutex.h file for details.
*/
#ifdef SQLITE_MUTEX_OS2

/********************** OS/2 Mutex Implementation **********************
**
** This implementation of mutexes is built using the OS/2 API.
*/

/*
** The mutex object
** Each recursive mutex is an instance of the following structure.
*/
struct sqlite3_mutex {
  HMTX mutex;       /* Mutex controlling the lock */
  int  id;          /* Mutex type */
  int  nRef;        /* Number of references */
  TID  owner;       /* Thread holding this mutex */
};

#define OS2_MUTEX_INITIALIZER   0,0,0,0

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int os2MutexInit(void){ return SQLITE_OK; }
static int os2MutexEnd(void){ return SQLITE_OK; }

/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated. 
** SQLite will unwind its stack and return an error.  The argument
** to sqlite3_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li>  SQLITE_MUTEX_FAST               0
** <li>  SQLITE_MUTEX_RECURSIVE          1
** <li>  SQLITE_MUTEX_STATIC_MASTER      2
** <li>  SQLITE_MUTEX_STATIC_MEM         3
** <li>  SQLITE_MUTEX_STATIC_PRNG        4
** </ul>
**
** The first two constants cause sqlite3_mutex_alloc() to create
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to.  But SQLite will only request a recursive mutex in
** cases where it really needs one.  If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** The other allowed parameters to sqlite3_mutex_alloc() each return
** a pointer to a static preexisting mutex.  Three static mutexes are
** used by the current version of SQLite.  Future versions of SQLite
** may add additional static mutexes.  Static mutexes are for internal
** use by SQLite only.  Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
** returns a different mutex on every call.  But for the static
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite3_mutex *os2MutexAlloc(int iType){
  sqlite3_mutex *p = NULL;
  switch( iType ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite3MallocZero( sizeof(*p) );
      if( p ){
        p->id = iType;
        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
          sqlite3_free( p );
          p = NULL;
        }
      }
      break;
    }
    default: {
      static volatile int isInit = 0;
      static sqlite3_mutex staticMutexes[] = {
        { OS2_MUTEX_INITIALIZER, },
        { OS2_MUTEX_INITIALIZER, },
        { OS2_MUTEX_INITIALIZER, },
        { OS2_MUTEX_INITIALIZER, },
        { OS2_MUTEX_INITIALIZER, },
        { OS2_MUTEX_INITIALIZER, },
      };
      if ( !isInit ){
        APIRET rc;
        PTIB ptib;
        PPIB ppib;
        HMTX mutex;
        char name[32];
        DosGetInfoBlocks( &ptib, &ppib );
        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
                          ppib->pib_ulpid );
        while( !isInit ){
          mutex = 0;
          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
          if( rc == NO_ERROR ){
            unsigned int i;
            if( !isInit ){
              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
              }
              isInit = 1;
            }
            DosCloseMutexSem( mutex );
          }else if( rc == ERROR_DUPLICATE_NAME ){
            DosSleep( 1 );
          }else{
            return p;
          }
        }
      }
      assert( iType-2 >= 0 );
      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
      p = &staticMutexes[iType-2];
      p->id = iType;
      break;
    }
  }
  return p;
}


/*
** This routine deallocates a previously allocated mutex.
** SQLite is careful to deallocate every mutex that it allocates.
*/
static void os2MutexFree(sqlite3_mutex *p){
  if( p==0 ) return;
  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  DosCloseMutexSem( p->mutex );
  sqlite3_free( p );
}

/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void os2MutexEnter(sqlite3_mutex *p){
  TID tid;
  PID holder1;
  ULONG holder2;
  if( p==0 ) return;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  p->owner = tid;
  p->nRef++;
}
static int os2MutexTry(sqlite3_mutex *p){
  int rc;
  TID tid;
  PID holder1;
  ULONG holder2;
  if( p==0 ) return SQLITE_OK;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
    p->owner = tid;
    p->nRef++;
    rc = SQLITE_OK;
  } else {
    rc = SQLITE_BUSY;
  }

  return rc;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void os2MutexLeave(sqlite3_mutex *p){
  TID tid;
  PID holder1;
  ULONG holder2;
  if( p==0 ) return;
  assert( p->nRef>0 );
  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  assert( p->owner==tid );
  p->nRef--;
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  DosReleaseMutexSem(p->mutex);
}

#ifdef SQLITE_DEBUG
/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
static int os2MutexHeld(sqlite3_mutex *p){
  TID tid;
  PID pid;
  ULONG ulCount;
  PTIB ptib;
  if( p!=0 ) {
    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  } else {
    DosGetInfoBlocks(&ptib, NULL);
    tid = ptib->tib_ptib2->tib2_ultid;
  }
  return p==0 || (p->nRef!=0 && p->owner==tid);
}
static int os2MutexNotheld(sqlite3_mutex *p){
  TID tid;
  PID pid;
  ULONG ulCount;
  PTIB ptib;
  if( p!= 0 ) {
    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  } else {
    DosGetInfoBlocks(&ptib, NULL);
    tid = ptib->tib_ptib2->tib2_ultid;
  }
  return p==0 || p->nRef==0 || p->owner!=tid;
}
#endif

sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  static sqlite3_mutex_methods sMutex = {
    os2MutexInit,
    os2MutexEnd,
    os2MutexAlloc,
    os2MutexFree,
    os2MutexEnter,
    os2MutexTry,
    os2MutexLeave,
#ifdef SQLITE_DEBUG
    os2MutexHeld,
    os2MutexNotheld
#endif
  };

  return &sMutex;
}
#endif /* SQLITE_MUTEX_OS2 */

Added src/mutex_unix.c.



















































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
** 2007 August 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes for pthreads
**
** $Id: mutex_unix.c,v 1.16 2008/12/08 18:19:18 drh Exp $
*/
#include "sqliteInt.h"

/*
** The code in this file is only used if we are compiling threadsafe
** under unix with pthreads.
**
** Note that this implementation requires a version of pthreads that
** supports recursive mutexes.
*/
#ifdef SQLITE_MUTEX_PTHREADS

#include <pthread.h>


/*
** Each recursive mutex is an instance of the following structure.
*/
struct sqlite3_mutex {
  pthread_mutex_t mutex;     /* Mutex controlling the lock */
  int id;                    /* Mutex type */
  int nRef;                  /* Number of entrances */
  pthread_t owner;           /* Thread that is within this mutex */
#ifdef SQLITE_DEBUG
  int trace;                 /* True to trace changes */
#endif
};
#ifdef SQLITE_DEBUG
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
#else
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
#endif

/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use only inside assert() statements.  On some platforms,
** there might be race conditions that can cause these routines to
** deliver incorrect results.  In particular, if pthread_equal() is
** not an atomic operation, then these routines might delivery
** incorrect results.  On most platforms, pthread_equal() is a 
** comparison of two integers and is therefore atomic.  But we are
** told that HPUX is not such a platform.  If so, then these routines
** will not always work correctly on HPUX.
**
** On those platforms where pthread_equal() is not atomic, SQLite
** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
** make sure no assert() statements are evaluated and hence these
** routines are never called.
*/
#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
static int pthreadMutexHeld(sqlite3_mutex *p){
  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
}
static int pthreadMutexNotheld(sqlite3_mutex *p){
  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
}
#endif

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int pthreadMutexInit(void){ return SQLITE_OK; }
static int pthreadMutexEnd(void){ return SQLITE_OK; }

/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated.  SQLite
** will unwind its stack and return an error.  The argument
** to sqlite3_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li>  SQLITE_MUTEX_FAST
** <li>  SQLITE_MUTEX_RECURSIVE
** <li>  SQLITE_MUTEX_STATIC_MASTER
** <li>  SQLITE_MUTEX_STATIC_MEM
** <li>  SQLITE_MUTEX_STATIC_MEM2
** <li>  SQLITE_MUTEX_STATIC_PRNG
** <li>  SQLITE_MUTEX_STATIC_LRU
** <li>  SQLITE_MUTEX_STATIC_LRU2
** </ul>
**
** The first two constants cause sqlite3_mutex_alloc() to create
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to.  But SQLite will only request a recursive mutex in
** cases where it really needs one.  If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** The other allowed parameters to sqlite3_mutex_alloc() each return
** a pointer to a static preexisting mutex.  Six static mutexes are
** used by the current version of SQLite.  Future versions of SQLite
** may add additional static mutexes.  Static mutexes are for internal
** use by SQLite only.  Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
** returns a different mutex on every call.  But for the static 
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite3_mutex *pthreadMutexAlloc(int iType){
  static sqlite3_mutex staticMutexes[] = {
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER
  };
  sqlite3_mutex *p;
  switch( iType ){
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite3MallocZero( sizeof(*p) );
      if( p ){
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
        /* If recursive mutexes are not available, we will have to
        ** build our own.  See below. */
        pthread_mutex_init(&p->mutex, 0);
#else
        /* Use a recursive mutex if it is available */
        pthread_mutexattr_t recursiveAttr;
        pthread_mutexattr_init(&recursiveAttr);
        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&p->mutex, &recursiveAttr);
        pthread_mutexattr_destroy(&recursiveAttr);
#endif
        p->id = iType;
      }
      break;
    }
    case SQLITE_MUTEX_FAST: {
      p = sqlite3MallocZero( sizeof(*p) );
      if( p ){
        p->id = iType;
        pthread_mutex_init(&p->mutex, 0);
      }
      break;
    }
    default: {
      assert( iType-2 >= 0 );
      assert( iType-2 < ArraySize(staticMutexes) );
      p = &staticMutexes[iType-2];
      p->id = iType;
      break;
    }
  }
  return p;
}


/*
** This routine deallocates a previously
** allocated mutex.  SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void pthreadMutexFree(sqlite3_mutex *p){
  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  pthread_mutex_destroy(&p->mutex);
  sqlite3_free(p);
}

/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void pthreadMutexEnter(sqlite3_mutex *p){
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  /* If recursive mutexes are not available, then we have to grow
  ** our own.  This implementation assumes that pthread_equal()
  ** is atomic - that it cannot be deceived into thinking self
  ** and p->owner are equal if p->owner changes between two values
  ** that are not equal to self while the comparison is taking place.
  ** This implementation also assumes a coherent cache - that 
  ** separate processes cannot read different values from the same
  ** address at the same time.  If either of these two conditions
  ** are not met, then the mutexes will fail and problems will result.
  */
  {
    pthread_t self = pthread_self();
    if( p->nRef>0 && pthread_equal(p->owner, self) ){
      p->nRef++;
    }else{
      pthread_mutex_lock(&p->mutex);
      assert( p->nRef==0 );
      p->owner = self;
      p->nRef = 1;
    }
  }
#else
  /* Use the built-in recursive mutexes if they are available.
  */
  pthread_mutex_lock(&p->mutex);
  p->owner = pthread_self();
  p->nRef++;
#endif

#ifdef SQLITE_DEBUG
  if( p->trace ){
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  }
#endif
}
static int pthreadMutexTry(sqlite3_mutex *p){
  int rc;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  /* If recursive mutexes are not available, then we have to grow
  ** our own.  This implementation assumes that pthread_equal()
  ** is atomic - that it cannot be deceived into thinking self
  ** and p->owner are equal if p->owner changes between two values
  ** that are not equal to self while the comparison is taking place.
  ** This implementation also assumes a coherent cache - that 
  ** separate processes cannot read different values from the same
  ** address at the same time.  If either of these two conditions
  ** are not met, then the mutexes will fail and problems will result.
  */
  {
    pthread_t self = pthread_self();
    if( p->nRef>0 && pthread_equal(p->owner, self) ){
      p->nRef++;
      rc = SQLITE_OK;
    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
      assert( p->nRef==0 );
      p->owner = self;
      p->nRef = 1;
      rc = SQLITE_OK;
    }else{
      rc = SQLITE_BUSY;
    }
  }
#else
  /* Use the built-in recursive mutexes if they are available.
  */
  if( pthread_mutex_trylock(&p->mutex)==0 ){
    p->owner = pthread_self();
    p->nRef++;
    rc = SQLITE_OK;
  }else{
    rc = SQLITE_BUSY;
  }
#endif

#ifdef SQLITE_DEBUG
  if( rc==SQLITE_OK && p->trace ){
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  }
#endif
  return rc;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void pthreadMutexLeave(sqlite3_mutex *p){
  assert( pthreadMutexHeld(p) );
  p->nRef--;
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  if( p->nRef==0 ){
    pthread_mutex_unlock(&p->mutex);
  }
#else
  pthread_mutex_unlock(&p->mutex);
#endif

#ifdef SQLITE_DEBUG
  if( p->trace ){
    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  }
#endif
}

sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  static sqlite3_mutex_methods sMutex = {
    pthreadMutexInit,
    pthreadMutexEnd,
    pthreadMutexAlloc,
    pthreadMutexFree,
    pthreadMutexEnter,
    pthreadMutexTry,
    pthreadMutexLeave,
#ifdef SQLITE_DEBUG
    pthreadMutexHeld,
    pthreadMutexNotheld
#else
    0,
    0
#endif
  };

  return &sMutex;
}

#endif /* SQLITE_MUTEX_PTHREAD */

Added src/mutex_w32.c.

























































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
** 2007 August 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes for win32
**
** $Id: mutex_w32.c,v 1.18 2009/08/10 03:23:21 shane Exp $
*/
#include "sqliteInt.h"

/*
** The code in this file is only used if we are compiling multithreaded
** on a win32 system.
*/
#ifdef SQLITE_MUTEX_W32

/*
** Each recursive mutex is an instance of the following structure.
*/
struct sqlite3_mutex {
  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
  int id;                    /* Mutex type */
  int nRef;                  /* Number of enterances */
  DWORD owner;               /* Thread holding this mutex */
};

/*
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
**
** Here is an interesting observation:  Win95, Win98, and WinME lack
** the LockFileEx() API.  But we can still statically link against that
** API as long as we don't call it win running Win95/98/ME.  A call to
** this routine is used to determine if the host is Win95/98/ME or
** WinNT/2K/XP so that we will know whether or not we can safely call
** the LockFileEx() API.
**
** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
** which is only available if your application was compiled with 
** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
** this out as well.
*/
#if 0
#if SQLITE_OS_WINCE
# define mutexIsNT()  (1)
#else
  static int mutexIsNT(void){
    static int osType = 0;
    if( osType==0 ){
      OSVERSIONINFO sInfo;
      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
      GetVersionEx(&sInfo);
      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
    }
    return osType==2;
  }
#endif /* SQLITE_OS_WINCE */
#endif

#ifdef SQLITE_DEBUG
/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use only inside assert() statements.
*/
static int winMutexHeld(sqlite3_mutex *p){
  return p->nRef!=0 && p->owner==GetCurrentThreadId();
}
static int winMutexNotheld(sqlite3_mutex *p){
  return p->nRef==0 || p->owner!=GetCurrentThreadId();
}
#endif


/*
** Initialize and deinitialize the mutex subsystem.
*/
static sqlite3_mutex winMutex_staticMutexes[6];
static int winMutex_isInit = 0;
/* As winMutexInit() and winMutexEnd() are called as part
** of the sqlite3_initialize and sqlite3_shutdown()
** processing, the "interlocked" magic is probably not
** strictly necessary.
*/
static long winMutex_lock = 0;

static int winMutexInit(void){ 
  /* The first to increment to 1 does actual initialization */
  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
    int i;
    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
    }
    winMutex_isInit = 1;
  }else{
    /* Someone else is in the process of initing the static mutexes */
    while( !winMutex_isInit ){
      Sleep(1);
    }
  }
  return SQLITE_OK; 
}

static int winMutexEnd(void){ 
  /* The first to decrement to 0 does actual shutdown 
  ** (which should be the last to shutdown.) */
  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
    if( winMutex_isInit==1 ){
      int i;
      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
      }
      winMutex_isInit = 0;
    }
  }
  return SQLITE_OK; 
}

/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated.  SQLite
** will unwind its stack and return an error.  The argument
** to sqlite3_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li>  SQLITE_MUTEX_FAST
** <li>  SQLITE_MUTEX_RECURSIVE
** <li>  SQLITE_MUTEX_STATIC_MASTER
** <li>  SQLITE_MUTEX_STATIC_MEM
** <li>  SQLITE_MUTEX_STATIC_MEM2
** <li>  SQLITE_MUTEX_STATIC_PRNG
** <li>  SQLITE_MUTEX_STATIC_LRU
** <li>  SQLITE_MUTEX_STATIC_LRU2
** </ul>
**
** The first two constants cause sqlite3_mutex_alloc() to create
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to.  But SQLite will only request a recursive mutex in
** cases where it really needs one.  If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** The other allowed parameters to sqlite3_mutex_alloc() each return
** a pointer to a static preexisting mutex.  Six static mutexes are
** used by the current version of SQLite.  Future versions of SQLite
** may add additional static mutexes.  Static mutexes are for internal
** use by SQLite only.  Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
** returns a different mutex on every call.  But for the static 
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite3_mutex *winMutexAlloc(int iType){
  sqlite3_mutex *p;

  switch( iType ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite3MallocZero( sizeof(*p) );
      if( p ){  
        p->id = iType;
        InitializeCriticalSection(&p->mutex);
      }
      break;
    }
    default: {
      assert( winMutex_isInit==1 );
      assert( iType-2 >= 0 );
      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
      p = &winMutex_staticMutexes[iType-2];
      p->id = iType;
      break;
    }
  }
  return p;
}


/*
** This routine deallocates a previously
** allocated mutex.  SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void winMutexFree(sqlite3_mutex *p){
  assert( p );
  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  DeleteCriticalSection(&p->mutex);
  sqlite3_free(p);
}

/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void winMutexEnter(sqlite3_mutex *p){
  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
  EnterCriticalSection(&p->mutex);
  p->owner = GetCurrentThreadId(); 
  p->nRef++;
}
static int winMutexTry(sqlite3_mutex *p){
  int rc = SQLITE_BUSY;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
  /*
  ** The sqlite3_mutex_try() routine is very rarely used, and when it
  ** is used it is merely an optimization.  So it is OK for it to always
  ** fail.  
  **
  ** The TryEnterCriticalSection() interface is only available on WinNT.
  ** And some windows compilers complain if you try to use it without
  ** first doing some #defines that prevent SQLite from building on Win98.
  ** For that reason, we will omit this optimization for now.  See
  ** ticket #2685.
  */
#if 0
  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
    p->owner = GetCurrentThreadId();
    p->nRef++;
    rc = SQLITE_OK;
  }
#else
  UNUSED_PARAMETER(p);
#endif
  return rc;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void winMutexLeave(sqlite3_mutex *p){
  assert( p->nRef>0 );
  assert( p->owner==GetCurrentThreadId() );
  p->nRef--;
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  LeaveCriticalSection(&p->mutex);
}

sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  static sqlite3_mutex_methods sMutex = {
    winMutexInit,
    winMutexEnd,
    winMutexAlloc,
    winMutexFree,
    winMutexEnter,
    winMutexTry,
    winMutexLeave,
#ifdef SQLITE_DEBUG
    winMutexHeld,
    winMutexNotheld
#else
    0,
    0
#endif
  };

  return &sMutex;
}
#endif /* SQLITE_MUTEX_W32 */

Added src/notify.c.



























































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
** 2009 March 3
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains the implementation of the sqlite3_unlock_notify()
** API method and its associated functionality.
**
** $Id: notify.c,v 1.4 2009/04/07 22:06:57 drh Exp $
*/
#include "sqliteInt.h"
#include "btreeInt.h"

/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY

/*
** Public interfaces:
**
**   sqlite3ConnectionBlocked()
**   sqlite3ConnectionUnlocked()
**   sqlite3ConnectionClosed()
**   sqlite3_unlock_notify()
*/

#define assertMutexHeld() \
  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )

/*
** Head of a linked list of all sqlite3 objects created by this process
** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
** is not NULL. This variable may only accessed while the STATIC_MASTER
** mutex is held.
*/
static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;

#ifndef NDEBUG
/*
** This function is a complex assert() that verifies the following 
** properties of the blocked connections list:
**
**   1) Each entry in the list has a non-NULL value for either 
**      pUnlockConnection or pBlockingConnection, or both.
**
**   2) All entries in the list that share a common value for 
**      xUnlockNotify are grouped together.
**
**   3) If the argument db is not NULL, then none of the entries in the
**      blocked connections list have pUnlockConnection or pBlockingConnection
**      set to db. This is used when closing connection db.
*/
static void checkListProperties(sqlite3 *db){
  sqlite3 *p;
  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
    int seen = 0;
    sqlite3 *p2;

    /* Verify property (1) */
    assert( p->pUnlockConnection || p->pBlockingConnection );

    /* Verify property (2) */
    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
      assert( db==0 || p->pUnlockConnection!=db );
      assert( db==0 || p->pBlockingConnection!=db );
    }
  }
}
#else
# define checkListProperties(x)
#endif

/*
** Remove connection db from the blocked connections list. If connection
** db is not currently a part of the list, this function is a no-op.
*/
static void removeFromBlockedList(sqlite3 *db){
  sqlite3 **pp;
  assertMutexHeld();
  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
    if( *pp==db ){
      *pp = (*pp)->pNextBlocked;
      break;
    }
  }
}

/*
** Add connection db to the blocked connections list. It is assumed
** that it is not already a part of the list.
*/
static void addToBlockedList(sqlite3 *db){
  sqlite3 **pp;
  assertMutexHeld();
  for(
    pp=&sqlite3BlockedList; 
    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
    pp=&(*pp)->pNextBlocked
  );
  db->pNextBlocked = *pp;
  *pp = db;
}

/*
** Obtain the STATIC_MASTER mutex.
*/
static void enterMutex(void){
  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  checkListProperties(0);
}

/*
** Release the STATIC_MASTER mutex.
*/
static void leaveMutex(void){
  assertMutexHeld();
  checkListProperties(0);
  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
}

/*
** Register an unlock-notify callback.
**
** This is called after connection "db" has attempted some operation
** but has received an SQLITE_LOCKED error because another connection
** (call it pOther) in the same process was busy using the same shared
** cache.  pOther is found by looking at db->pBlockingConnection.
**
** If there is no blocking connection, the callback is invoked immediately,
** before this routine returns.
**
** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
** a deadlock.
**
** Otherwise, make arrangements to invoke xNotify when pOther drops
** its locks.
**
** Each call to this routine overrides any prior callbacks registered
** on the same "db".  If xNotify==0 then any prior callbacks are immediately
** cancelled.
*/
int sqlite3_unlock_notify(
  sqlite3 *db,
  void (*xNotify)(void **, int),
  void *pArg
){
  int rc = SQLITE_OK;

  sqlite3_mutex_enter(db->mutex);
  enterMutex();

  if( xNotify==0 ){
    removeFromBlockedList(db);
    db->pUnlockConnection = 0;
    db->xUnlockNotify = 0;
    db->pUnlockArg = 0;
  }else if( 0==db->pBlockingConnection ){
    /* The blocking transaction has been concluded. Or there never was a 
    ** blocking transaction. In either case, invoke the notify callback
    ** immediately. 
    */
    xNotify(&pArg, 1);
  }else{
    sqlite3 *p;

    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
    if( p ){
      rc = SQLITE_LOCKED;              /* Deadlock detected. */
    }else{
      db->pUnlockConnection = db->pBlockingConnection;
      db->xUnlockNotify = xNotify;
      db->pUnlockArg = pArg;
      removeFromBlockedList(db);
      addToBlockedList(db);
    }
  }

  leaveMutex();
  assert( !db->mallocFailed );
  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** This function is called while stepping or preparing a statement 
** associated with connection db. The operation will return SQLITE_LOCKED
** to the user because it requires a lock that will not be available
** until connection pBlocker concludes its current transaction.
*/
void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  enterMutex();
  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
    addToBlockedList(db);
  }
  db->pBlockingConnection = pBlocker;
  leaveMutex();
}

/*
** This function is called when
** the transaction opened by database db has just finished. Locks held 
** by database connection db have been released.
**
** This function loops through each entry in the blocked connections
** list and does the following:
**
**   1) If the sqlite3.pBlockingConnection member of a list entry is
**      set to db, then set pBlockingConnection=0.
**
**   2) If the sqlite3.pUnlockConnection member of a list entry is
**      set to db, then invoke the configured unlock-notify callback and
**      set pUnlockConnection=0.
**
**   3) If the two steps above mean that pBlockingConnection==0 and
**      pUnlockConnection==0, remove the entry from the blocked connections
**      list.
*/
void sqlite3ConnectionUnlocked(sqlite3 *db){
  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  int nArg = 0;                            /* Number of entries in aArg[] */
  sqlite3 **pp;                            /* Iterator variable */
  void **aArg;               /* Arguments to the unlock callback */
  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */

  aArg = aStatic;
  enterMutex();         /* Enter STATIC_MASTER mutex */

  /* This loop runs once for each entry in the blocked-connections list. */
  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
    sqlite3 *p = *pp;

    /* Step 1. */
    if( p->pBlockingConnection==db ){
      p->pBlockingConnection = 0;
    }

    /* Step 2. */
    if( p->pUnlockConnection==db ){
      assert( p->xUnlockNotify );
      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
        xUnlockNotify(aArg, nArg);
        nArg = 0;
      }

      sqlite3BeginBenignMalloc();
      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
      if( (!aDyn && nArg==(int)ArraySize(aStatic))
       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
      ){
        /* The aArg[] array needs to grow. */
        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
        if( pNew ){
          memcpy(pNew, aArg, nArg*sizeof(void *));
          sqlite3_free(aDyn);
          aDyn = aArg = pNew;
        }else{
          /* This occurs when the array of context pointers that need to
          ** be passed to the unlock-notify callback is larger than the
          ** aStatic[] array allocated on the stack and the attempt to 
          ** allocate a larger array from the heap has failed.
          **
          ** This is a difficult situation to handle. Returning an error
          ** code to the caller is insufficient, as even if an error code
          ** is returned the transaction on connection db will still be
          ** closed and the unlock-notify callbacks on blocked connections
          ** will go unissued. This might cause the application to wait
          ** indefinitely for an unlock-notify callback that will never 
          ** arrive.
          **
          ** Instead, invoke the unlock-notify callback with the context
          ** array already accumulated. We can then clear the array and
          ** begin accumulating any further context pointers without 
          ** requiring any dynamic allocation. This is sub-optimal because
          ** it means that instead of one callback with a large array of
          ** context pointers the application will receive two or more
          ** callbacks with smaller arrays of context pointers, which will
          ** reduce the applications ability to prioritize multiple 
          ** connections. But it is the best that can be done under the
          ** circumstances.
          */
          xUnlockNotify(aArg, nArg);
          nArg = 0;
        }
      }
      sqlite3EndBenignMalloc();

      aArg[nArg++] = p->pUnlockArg;
      xUnlockNotify = p->xUnlockNotify;
      p->pUnlockConnection = 0;
      p->xUnlockNotify = 0;
      p->pUnlockArg = 0;
    }

    /* Step 3. */
    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
      /* Remove connection p from the blocked connections list. */
      *pp = p->pNextBlocked;
      p->pNextBlocked = 0;
    }else{
      pp = &p->pNextBlocked;
    }
  }

  if( nArg!=0 ){
    xUnlockNotify(aArg, nArg);
  }
  sqlite3_free(aDyn);
  leaveMutex();         /* Leave STATIC_MASTER mutex */
}

/*
** This is called when the database connection passed as an argument is 
** being closed. The connection is removed from the blocked list.
*/
void sqlite3ConnectionClosed(sqlite3 *db){
  sqlite3ConnectionUnlocked(db);
  enterMutex();
  removeFromBlockedList(db);
  checkListProperties(db);
  leaveMutex();
}
#endif

Added src/os.c.





















































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
** 2005 November 29
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains OS interface code that is common to all
** architectures.
**
** $Id: os.c,v 1.127 2009/07/27 11:41:21 danielk1977 Exp $
*/
#define _SQLITE_OS_C_ 1
#include "sqliteInt.h"
#undef _SQLITE_OS_C_

/*
** The default SQLite sqlite3_vfs implementations do not allocate
** memory (actually, os_unix.c allocates a small amount of memory
** from within OsOpen()), but some third-party implementations may.
** So we test the effects of a malloc() failing and the sqlite3OsXXX()
** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
**
** The following functions are instrumented for malloc() failure 
** testing:
**
**     sqlite3OsOpen()
**     sqlite3OsRead()
**     sqlite3OsWrite()
**     sqlite3OsSync()
**     sqlite3OsLock()
**
*/
#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
    void *pTstAlloc = sqlite3Malloc(10);                             \
    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
    sqlite3_free(pTstAlloc);                                         \
  }
#else
  #define DO_OS_MALLOC_TEST(x)
#endif

/*
** The following routines are convenience wrappers around methods
** of the sqlite3_file object.  This is mostly just syntactic sugar. All
** of this would be completely automatic if SQLite were coded using
** C++ instead of plain old C.
*/
int sqlite3OsClose(sqlite3_file *pId){
  int rc = SQLITE_OK;
  if( pId->pMethods ){
    rc = pId->pMethods->xClose(pId);
    pId->pMethods = 0;
  }
  return rc;
}
int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  DO_OS_MALLOC_TEST(id);
  return id->pMethods->xRead(id, pBuf, amt, offset);
}
int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  DO_OS_MALLOC_TEST(id);
  return id->pMethods->xWrite(id, pBuf, amt, offset);
}
int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  return id->pMethods->xTruncate(id, size);
}
int sqlite3OsSync(sqlite3_file *id, int flags){
  DO_OS_MALLOC_TEST(id);
  return id->pMethods->xSync(id, flags);
}
int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  DO_OS_MALLOC_TEST(id);
  return id->pMethods->xFileSize(id, pSize);
}
int sqlite3OsLock(sqlite3_file *id, int lockType){
  DO_OS_MALLOC_TEST(id);
  return id->pMethods->xLock(id, lockType);
}
int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  return id->pMethods->xUnlock(id, lockType);
}
int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  DO_OS_MALLOC_TEST(id);
  return id->pMethods->xCheckReservedLock(id, pResOut);
}
int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  return id->pMethods->xFileControl(id, op, pArg);
}
int sqlite3OsSectorSize(sqlite3_file *id){
  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
}
int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  return id->pMethods->xDeviceCharacteristics(id);
}

/*
** The next group of routines are convenience wrappers around the
** VFS methods.
*/
int sqlite3OsOpen(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  sqlite3_file *pFile, 
  int flags, 
  int *pFlagsOut
){
  int rc;
  DO_OS_MALLOC_TEST(0);
  /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  ** reaching the VFS. */
  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
  assert( rc==SQLITE_OK || pFile->pMethods==0 );
  return rc;
}
int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  return pVfs->xDelete(pVfs, zPath, dirSync);
}
int sqlite3OsAccess(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int flags, 
  int *pResOut
){
  DO_OS_MALLOC_TEST(0);
  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
}
int sqlite3OsFullPathname(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int nPathOut, 
  char *zPathOut
){
  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
}
#ifndef SQLITE_OMIT_LOAD_EXTENSION
void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  return pVfs->xDlOpen(pVfs, zPath);
}
void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  pVfs->xDlError(pVfs, nByte, zBufOut);
}
void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  return pVfs->xDlSym(pVfs, pHdle, zSym);
}
void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  pVfs->xDlClose(pVfs, pHandle);
}
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  return pVfs->xRandomness(pVfs, nByte, zBufOut);
}
int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  return pVfs->xSleep(pVfs, nMicro);
}
int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  return pVfs->xCurrentTime(pVfs, pTimeOut);
}

int sqlite3OsOpenMalloc(
  sqlite3_vfs *pVfs, 
  const char *zFile, 
  sqlite3_file **ppFile, 
  int flags,
  int *pOutFlags
){
  int rc = SQLITE_NOMEM;
  sqlite3_file *pFile;
  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
  if( pFile ){
    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
    if( rc!=SQLITE_OK ){
      sqlite3_free(pFile);
    }else{
      *ppFile = pFile;
    }
  }
  return rc;
}
int sqlite3OsCloseFree(sqlite3_file *pFile){
  int rc = SQLITE_OK;
  assert( pFile );
  rc = sqlite3OsClose(pFile);
  sqlite3_free(pFile);
  return rc;
}

/*
** This function is a wrapper around the OS specific implementation of
** sqlite3_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite3_os_init() by the upper layers can be tested.
*/
int sqlite3OsInit(void){
  void *p = sqlite3_malloc(10);
  if( p==0 ) return SQLITE_NOMEM;
  sqlite3_free(p);
  return sqlite3_os_init();
}

/*
** The list of all registered VFS implementations.
*/
static sqlite3_vfs * SQLITE_WSD vfsList = 0;
#define vfsList GLOBAL(sqlite3_vfs *, vfsList)

/*
** Locate a VFS by name.  If no name is given, simply return the
** first VFS on the list.
*/
sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  sqlite3_vfs *pVfs = 0;
#if SQLITE_THREADSAFE
  sqlite3_mutex *mutex;
#endif
#ifndef SQLITE_OMIT_AUTOINIT
  int rc = sqlite3_initialize();
  if( rc ) return 0;
#endif
#if SQLITE_THREADSAFE
  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
  sqlite3_mutex_enter(mutex);
  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
    if( zVfs==0 ) break;
    if( strcmp(zVfs, pVfs->zName)==0 ) break;
  }
  sqlite3_mutex_leave(mutex);
  return pVfs;
}

/*
** Unlink a VFS from the linked list
*/
static void vfsUnlink(sqlite3_vfs *pVfs){
  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  if( pVfs==0 ){
    /* No-op */
  }else if( vfsList==pVfs ){
    vfsList = pVfs->pNext;
  }else if( vfsList ){
    sqlite3_vfs *p = vfsList;
    while( p->pNext && p->pNext!=pVfs ){
      p = p->pNext;
    }
    if( p->pNext==pVfs ){
      p->pNext = pVfs->pNext;
    }
  }
}

/*
** Register a VFS with the system.  It is harmless to register the same
** VFS multiple times.  The new VFS becomes the default if makeDflt is
** true.
*/
int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  sqlite3_mutex *mutex = 0;
#ifndef SQLITE_OMIT_AUTOINIT
  int rc = sqlite3_initialize();
  if( rc ) return rc;
#endif
  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  sqlite3_mutex_enter(mutex);
  vfsUnlink(pVfs);
  if( makeDflt || vfsList==0 ){
    pVfs->pNext = vfsList;
    vfsList = pVfs;
  }else{
    pVfs->pNext = vfsList->pNext;
    vfsList->pNext = pVfs;
  }
  assert(vfsList);
  sqlite3_mutex_leave(mutex);
  return SQLITE_OK;
}

/*
** Unregister a VFS so that it is no longer accessible.
*/
int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
#if SQLITE_THREADSAFE
  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
  sqlite3_mutex_enter(mutex);
  vfsUnlink(pVfs);
  sqlite3_mutex_leave(mutex);
  return SQLITE_OK;
}

Added src/os.h.



































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
** 2001 September 16
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file (together with is companion C source-code file
** "os.c") attempt to abstract the underlying operating system so that
** the SQLite library will work on both POSIX and windows systems.
**
** This header file is #include-ed by sqliteInt.h and thus ends up
** being included by every source file.
**
** $Id: os.h,v 1.108 2009/02/05 16:31:46 drh Exp $
*/
#ifndef _SQLITE_OS_H_
#define _SQLITE_OS_H_

/*
** Figure out if we are dealing with Unix, Windows, or some other
** operating system.  After the following block of preprocess macros,
** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
** will defined to either 1 or 0.  One of the four will be 1.  The other 
** three will be 0.
*/
#if defined(SQLITE_OS_OTHER)
# if SQLITE_OS_OTHER==1
#   undef SQLITE_OS_UNIX
#   define SQLITE_OS_UNIX 0
#   undef SQLITE_OS_WIN
#   define SQLITE_OS_WIN 0
#   undef SQLITE_OS_OS2
#   define SQLITE_OS_OS2 0
# else
#   undef SQLITE_OS_OTHER
# endif
#endif
#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
# define SQLITE_OS_OTHER 0
# ifndef SQLITE_OS_WIN
#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
#     define SQLITE_OS_WIN 1
#     define SQLITE_OS_UNIX 0
#     define SQLITE_OS_OS2 0
#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
#     define SQLITE_OS_WIN 0
#     define SQLITE_OS_UNIX 0
#     define SQLITE_OS_OS2 1
#   else
#     define SQLITE_OS_WIN 0
#     define SQLITE_OS_UNIX 1
#     define SQLITE_OS_OS2 0
#  endif
# else
#  define SQLITE_OS_UNIX 0
#  define SQLITE_OS_OS2 0
# endif
#else
# ifndef SQLITE_OS_WIN
#  define SQLITE_OS_WIN 0
# endif
#endif

/*
** Determine if we are dealing with WindowsCE - which has a much
** reduced API.
*/
#if defined(_WIN32_WCE)
# define SQLITE_OS_WINCE 1
#else
# define SQLITE_OS_WINCE 0
#endif


/*
** Define the maximum size of a temporary filename
*/
#if SQLITE_OS_WIN
# include <windows.h>
# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
#elif SQLITE_OS_OS2
# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
#  include <os2safe.h> /* has to be included before os2.h for linking to work */
# endif
# define INCL_DOSDATETIME
# define INCL_DOSFILEMGR
# define INCL_DOSERRORS
# define INCL_DOSMISC
# define INCL_DOSPROCESS
# define INCL_DOSMODULEMGR
# define INCL_DOSSEMAPHORES
# include <os2.h>
# include <uconv.h>
# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
#else
# define SQLITE_TEMPNAME_SIZE 200
#endif

/* If the SET_FULLSYNC macro is not defined above, then make it
** a no-op
*/
#ifndef SET_FULLSYNC
# define SET_FULLSYNC(x,y)
#endif

/*
** The default size of a disk sector
*/
#ifndef SQLITE_DEFAULT_SECTOR_SIZE
# define SQLITE_DEFAULT_SECTOR_SIZE 512
#endif

/*
** Temporary files are named starting with this prefix followed by 16 random
** alphanumeric characters, and no file extension. They are stored in the
** OS's standard temporary file directory, and are deleted prior to exit.
** If sqlite is being embedded in another program, you may wish to change the
** prefix to reflect your program's name, so that if your program exits
** prematurely, old temporary files can be easily identified. This can be done
** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
**
** 2006-10-31:  The default prefix used to be "sqlite_".  But then
** Mcafee started using SQLite in their anti-virus product and it
** started putting files with the "sqlite" name in the c:/temp folder.
** This annoyed many windows users.  Those users would then do a 
** Google search for "sqlite", find the telephone numbers of the
** developers and call to wake them up at night and complain.
** For this reason, the default name prefix is changed to be "sqlite" 
** spelled backwards.  So the temp files are still identified, but
** anybody smart enough to figure out the code is also likely smart
** enough to know that calling the developer will not help get rid
** of the file.
*/
#ifndef SQLITE_TEMP_FILE_PREFIX
# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
#endif

/*
** The following values may be passed as the second argument to
** sqlite3OsLock(). The various locks exhibit the following semantics:
**
** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
** RESERVED:  A single process may hold a RESERVED lock on a file at
**            any time. Other processes may hold and obtain new SHARED locks.
** PENDING:   A single process may hold a PENDING lock on a file at
**            any one time. Existing SHARED locks may persist, but no new
**            SHARED locks may be obtained by other processes.
** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
**
** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
** process that requests an EXCLUSIVE lock may actually obtain a PENDING
** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
** sqlite3OsLock().
*/
#define NO_LOCK         0
#define SHARED_LOCK     1
#define RESERVED_LOCK   2
#define PENDING_LOCK    3
#define EXCLUSIVE_LOCK  4

/*
** File Locking Notes:  (Mostly about windows but also some info for Unix)
**
** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
** those functions are not available.  So we use only LockFile() and
** UnlockFile().
**
** LockFile() prevents not just writing but also reading by other processes.
** A SHARED_LOCK is obtained by locking a single randomly-chosen 
** byte out of a specific range of bytes. The lock byte is obtained at 
** random so two separate readers can probably access the file at the 
** same time, unless they are unlucky and choose the same lock byte.
** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
** There can only be one writer.  A RESERVED_LOCK is obtained by locking
** a single byte of the file that is designated as the reserved lock byte.
** A PENDING_LOCK is obtained by locking a designated byte different from
** the RESERVED_LOCK byte.
**
** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
** which means we can use reader/writer locks.  When reader/writer locks
** are used, the lock is placed on the same range of bytes that is used
** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
** will support two or more Win95 readers or two or more WinNT readers.
** But a single Win95 reader will lock out all WinNT readers and a single
** WinNT reader will lock out all other Win95 readers.
**
** The following #defines specify the range of bytes used for locking.
** SHARED_SIZE is the number of bytes available in the pool from which
** a random byte is selected for a shared lock.  The pool of bytes for
** shared locks begins at SHARED_FIRST. 
**
** The same locking strategy and
** byte ranges are used for Unix.  This leaves open the possiblity of having
** clients on win95, winNT, and unix all talking to the same shared file
** and all locking correctly.  To do so would require that samba (or whatever
** tool is being used for file sharing) implements locks correctly between
** windows and unix.  I'm guessing that isn't likely to happen, but by
** using the same locking range we are at least open to the possibility.
**
** Locking in windows is manditory.  For this reason, we cannot store
** actual data in the bytes used for locking.  The pager never allocates
** the pages involved in locking therefore.  SHARED_SIZE is selected so
** that all locks will fit on a single page even at the minimum page size.
** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
** is set high so that we don't have to allocate an unused page except
** for very large databases.  But one should test the page skipping logic 
** by setting PENDING_BYTE low and running the entire regression suite.
**
** Changing the value of PENDING_BYTE results in a subtly incompatible
** file format.  Depending on how it is changed, you might not notice
** the incompatibility right away, even running a full regression test.
** The default location of PENDING_BYTE is the first byte past the
** 1GB boundary.
**
*/
#define PENDING_BYTE      sqlite3PendingByte
#define RESERVED_BYTE     (PENDING_BYTE+1)
#define SHARED_FIRST      (PENDING_BYTE+2)
#define SHARED_SIZE       510

/*
** Wrapper around OS specific sqlite3_os_init() function.
*/
int sqlite3OsInit(void);

/* 
** Functions for accessing sqlite3_file methods 
*/
int sqlite3OsClose(sqlite3_file*);
int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
int sqlite3OsTruncate(sqlite3_file*, i64 size);
int sqlite3OsSync(sqlite3_file*, int);
int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
int sqlite3OsLock(sqlite3_file*, int);
int sqlite3OsUnlock(sqlite3_file*, int);
int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
int sqlite3OsFileControl(sqlite3_file*,int,void*);
#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
int sqlite3OsSectorSize(sqlite3_file *id);
int sqlite3OsDeviceCharacteristics(sqlite3_file *id);

/* 
** Functions for accessing sqlite3_vfs methods 
*/
int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
void sqlite3OsDlError(sqlite3_vfs *, int, char *);
void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
void sqlite3OsDlClose(sqlite3_vfs *, void *);
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
int sqlite3OsSleep(sqlite3_vfs *, int);
int sqlite3OsCurrentTime(sqlite3_vfs *, double*);

/*
** Convenience functions for opening and closing files using 
** sqlite3_malloc() to obtain space for the file-handle structure.
*/
int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
int sqlite3OsCloseFree(sqlite3_file *);

#endif /* _SQLITE_OS_H_ */

Added src/os_common.h.

































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains macros and a little bit of code that is common to
** all of the platform-specific files (os_*.c) and is #included into those
** files.
**
** This file should be #included by the os_*.c files only.  It is not a
** general purpose header file.
**
** $Id: os_common.h,v 1.38 2009/02/24 18:40:50 danielk1977 Exp $
*/
#ifndef _OS_COMMON_H_
#define _OS_COMMON_H_

/*
** At least two bugs have slipped in because we changed the MEMORY_DEBUG
** macro to SQLITE_DEBUG and some older makefiles have not yet made the
** switch.  The following code should catch this problem at compile-time.
*/
#ifdef MEMORY_DEBUG
# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
#endif

#ifdef SQLITE_DEBUG
int sqlite3OSTrace = 0;
#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C) \
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D) \
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
#else
#define OSTRACE1(X)
#define OSTRACE2(X,Y)
#define OSTRACE3(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D)
#endif

/*
** Macros for performance tracing.  Normally turned off.  Only works
** on i486 hardware.
*/
#ifdef SQLITE_PERFORMANCE_TRACE

/* 
** hwtime.h contains inline assembler code for implementing 
** high-performance timing routines.
*/
#include "hwtime.h"

static sqlite_uint64 g_start;
static sqlite_uint64 g_elapsed;
#define TIMER_START       g_start=sqlite3Hwtime()
#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
#define TIMER_ELAPSED     g_elapsed
#else
#define TIMER_START
#define TIMER_END
#define TIMER_ELAPSED     ((sqlite_uint64)0)
#endif

/*
** If we compile with the SQLITE_TEST macro set, then the following block
** of code will give us the ability to simulate a disk I/O error.  This
** is used for testing the I/O recovery logic.
*/
#ifdef SQLITE_TEST
int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
int sqlite3_io_error_benign = 0;         /* True if errors are benign */
int sqlite3_diskfull_pending = 0;
int sqlite3_diskfull = 0;
#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
#define SimulateIOError(CODE)  \
  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
       || sqlite3_io_error_pending-- == 1 )  \
              { local_ioerr(); CODE; }
static void local_ioerr(){
  IOTRACE(("IOERR\n"));
  sqlite3_io_error_hit++;
  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
}
#define SimulateDiskfullError(CODE) \
   if( sqlite3_diskfull_pending ){ \
     if( sqlite3_diskfull_pending == 1 ){ \
       local_ioerr(); \
       sqlite3_diskfull = 1; \
       sqlite3_io_error_hit = 1; \
       CODE; \
     }else{ \
       sqlite3_diskfull_pending--; \
     } \
   }
#else
#define SimulateIOErrorBenign(X)
#define SimulateIOError(A)
#define SimulateDiskfullError(A)
#endif

/*
** When testing, keep a count of the number of open files.
*/
#ifdef SQLITE_TEST
int sqlite3_open_file_count = 0;
#define OpenCounter(X)  sqlite3_open_file_count+=(X)
#else
#define OpenCounter(X)
#endif

#endif /* !defined(_OS_COMMON_H_) */

Added src/os_os2.c.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
/*
** 2006 Feb 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to OS/2.
**
** $Id: os_os2.c,v 1.63 2008/12/10 19:26:24 drh Exp $
*/

#include "sqliteInt.h"

#if SQLITE_OS_OS2

/*
** A Note About Memory Allocation:
**
** This driver uses malloc()/free() directly rather than going through
** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
** are designed for use on embedded systems where memory is scarce and
** malloc failures happen frequently.  OS/2 does not typically run on
** embedded systems, and when it does the developers normally have bigger
** problems to worry about than running out of memory.  So there is not
** a compelling need to use the wrappers.
**
** But there is a good reason to not use the wrappers.  If we use the
** wrappers then we will get simulated malloc() failures within this
** driver.  And that causes all kinds of problems for our tests.  We
** could enhance SQLite to deal with simulated malloc failures within
** the OS driver, but the code to deal with those failure would not
** be exercised on Linux (which does not need to malloc() in the driver)
** and so we would have difficulty writing coverage tests for that
** code.  Better to leave the code out, we think.
**
** The point of this discussion is as follows:  When creating a new
** OS layer for an embedded system, if you use this file as an example,
** avoid the use of malloc()/free().  Those routines work ok on OS/2
** desktops but not so well in embedded systems.
*/

/*
** Macros used to determine whether or not to use threads.
*/
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
# define SQLITE_OS2_THREADS 1
#endif

/*
** Include code that is common to all os_*.c files
*/
#include "os_common.h"

/*
** The os2File structure is subclass of sqlite3_file specific for the OS/2
** protability layer.
*/
typedef struct os2File os2File;
struct os2File {
  const sqlite3_io_methods *pMethod;  /* Always the first entry */
  HFILE h;                  /* Handle for accessing the file */
  char* pathToDel;          /* Name of file to delete on close, NULL if not */
  unsigned char locktype;   /* Type of lock currently held on this file */
};

#define LOCK_TIMEOUT 10L /* the default locking timeout */

/*****************************************************************************
** The next group of routines implement the I/O methods specified
** by the sqlite3_io_methods object.
******************************************************************************/

/*
** Close a file.
*/
static int os2Close( sqlite3_file *id ){
  APIRET rc = NO_ERROR;
  os2File *pFile;
  if( id && (pFile = (os2File*)id) != 0 ){
    OSTRACE2( "CLOSE %d\n", pFile->h );
    rc = DosClose( pFile->h );
    pFile->locktype = NO_LOCK;
    if( pFile->pathToDel != NULL ){
      rc = DosForceDelete( (PSZ)pFile->pathToDel );
      free( pFile->pathToDel );
      pFile->pathToDel = NULL;
    }
    id = 0;
    OpenCounter( -1 );
  }

  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
}

/*
** Read data from a file into a buffer.  Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
static int os2Read(
  sqlite3_file *id,               /* File to read from */
  void *pBuf,                     /* Write content into this buffer */
  int amt,                        /* Number of bytes to read */
  sqlite3_int64 offset            /* Begin reading at this offset */
){
  ULONG fileLocation = 0L;
  ULONG got;
  os2File *pFile = (os2File*)id;
  assert( id!=0 );
  SimulateIOError( return SQLITE_IOERR_READ );
  OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
    return SQLITE_IOERR;
  }
  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
    return SQLITE_IOERR_READ;
  }
  if( got == (ULONG)amt )
    return SQLITE_OK;
  else {
    /* Unread portions of the input buffer must be zero-filled */
    memset(&((char*)pBuf)[got], 0, amt-got);
    return SQLITE_IOERR_SHORT_READ;
  }
}

/*
** Write data from a buffer into a file.  Return SQLITE_OK on success
** or some other error code on failure.
*/
static int os2Write(
  sqlite3_file *id,               /* File to write into */
  const void *pBuf,               /* The bytes to be written */
  int amt,                        /* Number of bytes to write */
  sqlite3_int64 offset            /* Offset into the file to begin writing at */
){
  ULONG fileLocation = 0L;
  APIRET rc = NO_ERROR;
  ULONG wrote;
  os2File *pFile = (os2File*)id;
  assert( id!=0 );
  SimulateIOError( return SQLITE_IOERR_WRITE );
  SimulateDiskfullError( return SQLITE_FULL );
  OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
    return SQLITE_IOERR;
  }
  assert( amt>0 );
  while( amt > 0 &&
         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
         wrote > 0
  ){
    amt -= wrote;
    pBuf = &((char*)pBuf)[wrote];
  }

  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
}

/*
** Truncate an open file to a specified size
*/
static int os2Truncate( sqlite3_file *id, i64 nByte ){
  APIRET rc = NO_ERROR;
  os2File *pFile = (os2File*)id;
  OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  rc = DosSetFileSize( pFile->h, nByte );
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
}

#ifdef SQLITE_TEST
/*
** Count the number of fullsyncs and normal syncs.  This is used to test
** that syncs and fullsyncs are occuring at the right times.
*/
int sqlite3_sync_count = 0;
int sqlite3_fullsync_count = 0;
#endif

/*
** Make sure all writes to a particular file are committed to disk.
*/
static int os2Sync( sqlite3_file *id, int flags ){
  os2File *pFile = (os2File*)id;
  OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
#ifdef SQLITE_TEST
  if( flags & SQLITE_SYNC_FULL){
    sqlite3_fullsync_count++;
  }
  sqlite3_sync_count++;
#endif
  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  ** no-op
  */
#ifdef SQLITE_NO_SYNC
  UNUSED_PARAMETER(pFile);
  return SQLITE_OK;
#else
  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
#endif
}

/*
** Determine the current size of a file in bytes
*/
static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
  APIRET rc = NO_ERROR;
  FILESTATUS3 fsts3FileInfo;
  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
  assert( id!=0 );
  SimulateIOError( return SQLITE_IOERR_FSTAT );
  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
  if( rc == NO_ERROR ){
    *pSize = fsts3FileInfo.cbFile;
    return SQLITE_OK;
  }else{
    return SQLITE_IOERR_FSTAT;
  }
}

/*
** Acquire a reader lock.
*/
static int getReadLock( os2File *pFile ){
  FILELOCK  LockArea,
            UnlockArea;
  APIRET res;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  LockArea.lOffset = SHARED_FIRST;
  LockArea.lRange = SHARED_SIZE;
  UnlockArea.lOffset = 0L;
  UnlockArea.lRange = 0L;
  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
  return res;
}

/*
** Undo a readlock
*/
static int unlockReadLock( os2File *id ){
  FILELOCK  LockArea,
            UnlockArea;
  APIRET res;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  LockArea.lOffset = 0L;
  LockArea.lRange = 0L;
  UnlockArea.lOffset = SHARED_FIRST;
  UnlockArea.lRange = SHARED_SIZE;
  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
  return res;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  The os2Unlock() routine
** erases all locks at once and returns us immediately to locking level 0.
** It is not possible to lower the locking level one step at a time.  You
** must go straight to locking level 0.
*/
static int os2Lock( sqlite3_file *id, int locktype ){
  int rc = SQLITE_OK;       /* Return code from subroutines */
  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
  int newLocktype;       /* Set pFile->locktype to this value before exiting */
  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  FILELOCK  LockArea,
            UnlockArea;
  os2File *pFile = (os2File*)id;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  assert( pFile!=0 );
  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );

  /* If there is already a lock of this type or more restrictive on the
  ** os2File, do nothing. Don't use the end_lock: exit path, as
  ** sqlite3_mutex_enter() hasn't been called yet.
  */
  if( pFile->locktype>=locktype ){
    OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
    return SQLITE_OK;
  }

  /* Make sure the locking sequence is correct
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
  ** the PENDING_LOCK byte is temporary.
  */
  newLocktype = pFile->locktype;
  if( pFile->locktype==NO_LOCK
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  ){
    LockArea.lOffset = PENDING_BYTE;
    LockArea.lRange = 1L;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;

    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
    if( res == NO_ERROR ){
      gotPendingLock = 1;
      OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
    }
  }

  /* Acquire a shared lock
  */
  if( locktype==SHARED_LOCK && res == NO_ERROR ){
    assert( pFile->locktype==NO_LOCK );
    res = getReadLock(pFile);
    if( res == NO_ERROR ){
      newLocktype = SHARED_LOCK;
    }
    OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
  }

  /* Acquire a RESERVED lock
  */
  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
    assert( pFile->locktype==SHARED_LOCK );
    LockArea.lOffset = RESERVED_BYTE;
    LockArea.lRange = 1L;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    if( res == NO_ERROR ){
      newLocktype = RESERVED_LOCK;
    }
    OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
  }

  /* Acquire a PENDING lock
  */
  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
    newLocktype = PENDING_LOCK;
    gotPendingLock = 0;
    OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
  }

  /* Acquire an EXCLUSIVE lock
  */
  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
    assert( pFile->locktype>=SHARED_LOCK );
    res = unlockReadLock(pFile);
    OSTRACE2( "unreadlock = %d\n", res );
    LockArea.lOffset = SHARED_FIRST;
    LockArea.lRange = SHARED_SIZE;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    if( res == NO_ERROR ){
      newLocktype = EXCLUSIVE_LOCK;
    }else{
      OSTRACE2( "OS/2 error-code = %d\n", res );
      getReadLock(pFile);
    }
    OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
  }

  /* If we are holding a PENDING lock that ought to be released, then
  ** release it now.
  */
  if( gotPendingLock && locktype==SHARED_LOCK ){
    int r;
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = PENDING_BYTE;
    UnlockArea.lRange = 1L;
    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
  }

  /* Update the state of the lock has held in the file descriptor then
  ** return the appropriate result code.
  */
  if( res == NO_ERROR ){
    rc = SQLITE_OK;
  }else{
    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
              locktype, newLocktype );
    rc = SQLITE_BUSY;
  }
  pFile->locktype = newLocktype;
  OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
  return rc;
}

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero, otherwise zero.
*/
static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
  int r = 0;
  os2File *pFile = (os2File*)id;
  assert( pFile!=0 );
  if( pFile->locktype>=RESERVED_LOCK ){
    r = 1;
    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
  }else{
    FILELOCK  LockArea,
              UnlockArea;
    APIRET rc = NO_ERROR;
    memset(&LockArea, 0, sizeof(LockArea));
    memset(&UnlockArea, 0, sizeof(UnlockArea));
    LockArea.lOffset = RESERVED_BYTE;
    LockArea.lRange = 1L;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;
    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
    if( rc == NO_ERROR ){
      APIRET rcu = NO_ERROR; /* return code for unlocking */
      LockArea.lOffset = 0L;
      LockArea.lRange = 0L;
      UnlockArea.lOffset = RESERVED_BYTE;
      UnlockArea.lRange = 1L;
      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
      OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
    }
    r = !(rc == NO_ERROR);
    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
  }
  *pOut = r;
  return SQLITE_OK;
}

/*
** Lower the locking level on file descriptor id to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
**
** It is not possible for this routine to fail if the second argument
** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
** might return SQLITE_IOERR;
*/
static int os2Unlock( sqlite3_file *id, int locktype ){
  int type;
  os2File *pFile = (os2File*)id;
  APIRET rc = SQLITE_OK;
  APIRET res = NO_ERROR;
  FILELOCK  LockArea,
            UnlockArea;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  assert( pFile!=0 );
  assert( locktype<=SHARED_LOCK );
  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
  type = pFile->locktype;
  if( type>=EXCLUSIVE_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = SHARED_FIRST;
    UnlockArea.lRange = SHARED_SIZE;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
      /* This should never happen.  We should always be able to
      ** reacquire the read lock */
      OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
      rc = SQLITE_IOERR_UNLOCK;
    }
  }
  if( type>=RESERVED_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = RESERVED_BYTE;
    UnlockArea.lRange = 1L;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
  }
  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
    res = unlockReadLock(pFile);
    OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
  }
  if( type>=PENDING_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = PENDING_BYTE;
    UnlockArea.lRange = 1L;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
    OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
  }
  pFile->locktype = locktype;
  OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
  return rc;
}

/*
** Control and query of the open file handle.
*/
static int os2FileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_FCNTL_LOCKSTATE: {
      *(int*)pArg = ((os2File*)id)->locktype;
      OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
      return SQLITE_OK;
    }
  }
  return SQLITE_ERROR;
}

/*
** Return the sector size in bytes of the underlying block device for
** the specified file. This is almost always 512 bytes, but may be
** larger for some devices.
**
** SQLite code assumes this function cannot fail. It also assumes that
** if two files are created in the same file-system directory (i.e.
** a database and its journal file) that the sector size will be the
** same for both.
*/
static int os2SectorSize(sqlite3_file *id){
  return SQLITE_DEFAULT_SECTOR_SIZE;
}

/*
** Return a vector of device characteristics.
*/
static int os2DeviceCharacteristics(sqlite3_file *id){
  return 0;
}


/*
** Character set conversion objects used by conversion routines.
*/
static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */

/*
** Helper function to initialize the conversion objects from and to UTF-8.
*/
static void initUconvObjects( void ){
  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
    ucUtf8 = NULL;
  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
    uclCp = NULL;
}

/*
** Helper function to free the conversion objects from and to UTF-8.
*/
static void freeUconvObjects( void ){
  if ( ucUtf8 )
    UniFreeUconvObject( ucUtf8 );
  if ( uclCp )
    UniFreeUconvObject( uclCp );
  ucUtf8 = NULL;
  uclCp = NULL;
}

/*
** Helper function to convert UTF-8 filenames to local OS/2 codepage.
** The two-step process: first convert the incoming UTF-8 string
** into UCS-2 and then from UCS-2 to the current codepage.
** The returned char pointer has to be freed.
*/
static char *convertUtf8PathToCp( const char *in ){
  UniChar tempPath[CCHMAXPATH];
  char *out = (char *)calloc( CCHMAXPATH, 1 );

  if( !out )
    return NULL;

  if( !ucUtf8 || !uclCp )
    initUconvObjects();

  /* determine string for the conversion of UTF-8 which is CP1208 */
  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
    return out; /* if conversion fails, return the empty string */

  /* conversion for current codepage which can be used for paths */
  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );

  return out;
}

/*
** Helper function to convert filenames from local codepage to UTF-8.
** The two-step process: first convert the incoming codepage-specific
** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
** The returned char pointer has to be freed.
**
** This function is non-static to be able to use this in shell.c and
** similar applications that take command line arguments.
*/
char *convertCpPathToUtf8( const char *in ){
  UniChar tempPath[CCHMAXPATH];
  char *out = (char *)calloc( CCHMAXPATH, 1 );

  if( !out )
    return NULL;

  if( !ucUtf8 || !uclCp )
    initUconvObjects();

  /* conversion for current codepage which can be used for paths */
  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
    return out; /* if conversion fails, return the empty string */

  /* determine string for the conversion of UTF-8 which is CP1208 */
  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );

  return out;
}

/*
** This vector defines all the methods that can operate on an
** sqlite3_file for os2.
*/
static const sqlite3_io_methods os2IoMethod = {
  1,                        /* iVersion */
  os2Close,
  os2Read,
  os2Write,
  os2Truncate,
  os2Sync,
  os2FileSize,
  os2Lock,
  os2Unlock,
  os2CheckReservedLock,
  os2FileControl,
  os2SectorSize,
  os2DeviceCharacteristics
};

/***************************************************************************
** Here ends the I/O methods that form the sqlite3_io_methods object.
**
** The next block of code implements the VFS methods.
****************************************************************************/

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at pVfs->mxPathname characters.
*/
static int getTempname(int nBuf, char *zBuf ){
  static const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  int i, j;
  char zTempPathBuf[3];
  PSZ zTempPath = (PSZ)&zTempPathBuf;
  if( sqlite3_temp_directory ){
    zTempPath = sqlite3_temp_directory;
  }else{
    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
           ULONG ulDriveNum = 0, ulDriveMap = 0;
           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
        }
      }
    }
  }
  /* Strip off a trailing slashes or backslashes, otherwise we would get *
   * multiple (back)slashes which causes DosOpen() to fail.              *
   * Trailing spaces are not allowed, either.                            */
  j = sqlite3Strlen30(zTempPath);
  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
                    || zTempPath[j-1] == ' ' ) ){
    j--;
  }
  zTempPath[j] = '\0';
  if( !sqlite3_temp_directory ){
    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
    sqlite3_snprintf( nBuf-30, zBuf,
                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
    free( zTempPathUTF );
  }else{
    sqlite3_snprintf( nBuf-30, zBuf,
                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
  }
  j = sqlite3Strlen30( zBuf );
  sqlite3_randomness( 20, &zBuf[j] );
  for( i = 0; i < 20; i++, j++ ){
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  }
  zBuf[j] = 0;
  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
  return SQLITE_OK;
}


/*
** Turn a relative pathname into a full pathname.  Write the full
** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
** bytes in size.
*/
static int os2FullPathname(
  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
  const char *zRelative,      /* Possibly relative input path */
  int nFull,                  /* Size of output buffer in bytes */
  char *zFull                 /* Output buffer */
){
  char *zRelativeCp = convertUtf8PathToCp( zRelative );
  char zFullCp[CCHMAXPATH] = "\0";
  char *zFullUTF;
  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
                                CCHMAXPATH );
  free( zRelativeCp );
  zFullUTF = convertCpPathToUtf8( zFullCp );
  sqlite3_snprintf( nFull, zFull, zFullUTF );
  free( zFullUTF );
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
}


/*
** Open a file.
*/
static int os2Open(
  sqlite3_vfs *pVfs,            /* Not used */
  const char *zName,            /* Name of the file */
  sqlite3_file *id,             /* Write the SQLite file handle here */
  int flags,                    /* Open mode flags */
  int *pOutFlags                /* Status return flags */
){
  HFILE h;
  ULONG ulFileAttribute = FILE_NORMAL;
  ULONG ulOpenFlags = 0;
  ULONG ulOpenMode = 0;
  os2File *pFile = (os2File*)id;
  APIRET rc = NO_ERROR;
  ULONG ulAction;
  char *zNameCp;
  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */

  /* If the second argument to this function is NULL, generate a 
  ** temporary file name to use 
  */
  if( !zName ){
    int rc = getTempname(CCHMAXPATH+1, zTmpname);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    zName = zTmpname;
  }


  memset( pFile, 0, sizeof(*pFile) );

  OSTRACE2( "OPEN want %d\n", flags );

  if( flags & SQLITE_OPEN_READWRITE ){
    ulOpenMode |= OPEN_ACCESS_READWRITE;
    OSTRACE1( "OPEN read/write\n" );
  }else{
    ulOpenMode |= OPEN_ACCESS_READONLY;
    OSTRACE1( "OPEN read only\n" );
  }

  if( flags & SQLITE_OPEN_CREATE ){
    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
    OSTRACE1( "OPEN open new/create\n" );
  }else{
    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
    OSTRACE1( "OPEN open existing\n" );
  }

  if( flags & SQLITE_OPEN_MAIN_DB ){
    ulOpenMode |= OPEN_SHARE_DENYNONE;
    OSTRACE1( "OPEN share read/write\n" );
  }else{
    ulOpenMode |= OPEN_SHARE_DENYWRITE;
    OSTRACE1( "OPEN share read only\n" );
  }

  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
    char pathUtf8[CCHMAXPATH];
#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
    ulFileAttribute = FILE_HIDDEN;
#endif
    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
    OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
  }else{
    pFile->pathToDel = NULL;
    OSTRACE1( "OPEN normal file attribute\n" );
  }

  /* always open in random access mode for possibly better speed */
  ulOpenMode |= OPEN_FLAGS_RANDOM;
  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
  ulOpenMode |= OPEN_FLAGS_NOINHERIT;

  zNameCp = convertUtf8PathToCp( zName );
  rc = DosOpen( (PSZ)zNameCp,
                &h,
                &ulAction,
                0L,
                ulFileAttribute,
                ulOpenFlags,
                ulOpenMode,
                (PEAOP2)NULL );
  free( zNameCp );
  if( rc != NO_ERROR ){
    OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
    if( pFile->pathToDel )
      free( pFile->pathToDel );
    pFile->pathToDel = NULL;
    if( flags & SQLITE_OPEN_READWRITE ){
      OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
      return os2Open( pVfs, zName, id,
                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
                      pOutFlags );
    }else{
      return SQLITE_CANTOPEN;
    }
  }

  if( pOutFlags ){
    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
  }

  pFile->pMethod = &os2IoMethod;
  pFile->h = h;
  OpenCounter(+1);
  OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
  return SQLITE_OK;
}

/*
** Delete the named file.
*/
static int os2Delete(
  sqlite3_vfs *pVfs,                     /* Not used on os2 */
  const char *zFilename,                 /* Name of file to delete */
  int syncDir                            /* Not used on os2 */
){
  APIRET rc = NO_ERROR;
  char *zFilenameCp = convertUtf8PathToCp( zFilename );
  SimulateIOError( return SQLITE_IOERR_DELETE );
  rc = DosDelete( (PSZ)zFilenameCp );
  free( zFilenameCp );
  OSTRACE2( "DELETE \"%s\"\n", zFilename );
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
}

/*
** Check the existance and status of a file.
*/
static int os2Access(
  sqlite3_vfs *pVfs,        /* Not used on os2 */
  const char *zFilename,    /* Name of file to check */
  int flags,                /* Type of test to make on this file */
  int *pOut                 /* Write results here */
){
  FILESTATUS3 fsts3ConfigInfo;
  APIRET rc = NO_ERROR;
  char *zFilenameCp = convertUtf8PathToCp( zFilename );

  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  free( zFilenameCp );
  OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
            fsts3ConfigInfo.attrFile, flags, rc );
  switch( flags ){
    case SQLITE_ACCESS_READ:
    case SQLITE_ACCESS_EXISTS:
      rc = (rc == NO_ERROR);
      OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
      break;
    case SQLITE_ACCESS_READWRITE:
      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
      OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
      break;
    default:
      assert( !"Invalid flags argument" );
  }
  *pOut = rc;
  return SQLITE_OK;
}


#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  UCHAR loadErr[256];
  HMODULE hmod;
  APIRET rc;
  char *zFilenameCp = convertUtf8PathToCp(zFilename);
  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
  free(zFilenameCp);
  return rc != NO_ERROR ? 0 : (void*)hmod;
}
/*
** A no-op since the error code is returned on the DosLoadModule call.
** os2Dlopen returns zero if DosLoadModule is not successful.
*/
static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
/* no-op */
}
static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
  PFN pfn;
  APIRET rc;
  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
  if( rc != NO_ERROR ){
    /* if the symbol itself was not found, search again for the same
     * symbol with an extra underscore, that might be needed depending
     * on the calling convention */
    char _zSymbol[256] = "_";
    strncat(_zSymbol, zSymbol, 255);
    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
  }
  return rc != NO_ERROR ? 0 : (void*)pfn;
}
static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
  DosFreeModule((HMODULE)pHandle);
}
#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  #define os2DlOpen 0
  #define os2DlError 0
  #define os2DlSym 0
  #define os2DlClose 0
#endif


/*
** Write up to nBuf bytes of randomness into zBuf.
*/
static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
  int n = 0;
#if defined(SQLITE_TEST)
  n = nBuf;
  memset(zBuf, 0, nBuf);
#else
  int sizeofULong = sizeof(ULONG);
  if( (int)sizeof(DATETIME) <= nBuf - n ){
    DATETIME x;
    DosGetDateTime(&x);
    memcpy(&zBuf[n], &x, sizeof(x));
    n += sizeof(x);
  }

  if( sizeofULong <= nBuf - n ){
    PPIB ppib;
    DosGetInfoBlocks(NULL, &ppib);
    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
    n += sizeofULong;
  }

  if( sizeofULong <= nBuf - n ){
    PTIB ptib;
    DosGetInfoBlocks(&ptib, NULL);
    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
    n += sizeofULong;
  }

  /* if we still haven't filled the buffer yet the following will */
  /* grab everything once instead of making several calls for a single item */
  if( sizeofULong <= nBuf - n ){
    ULONG ulSysInfo[QSV_MAX];
    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);

    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
    n += sizeofULong;

    if( sizeofULong <= nBuf - n ){
      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
      n += sizeofULong;
    }
    if( sizeofULong <= nBuf - n ){
      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
      n += sizeofULong;
    }
    if( sizeofULong <= nBuf - n ){
      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
      n += sizeofULong;
    }
    if( sizeofULong <= nBuf - n ){
      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
      n += sizeofULong;
    }
  }
#endif

  return n;
}

/*
** Sleep for a little while.  Return the amount of time slept.
** The argument is the number of microseconds we want to sleep.
** The return value is the number of microseconds of sleep actually
** requested from the underlying operating system, a number which
** might be greater than or equal to the argument, but not less
** than the argument.
*/
static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
  DosSleep( (microsec/1000) );
  return microsec;
}

/*
** The following variable, if set to a non-zero value, becomes the result
** returned from sqlite3OsCurrentTime().  This is used for testing.
*/
#ifdef SQLITE_TEST
int sqlite3_current_time = 0;
#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
  double now;
  SHORT minute; /* needs to be able to cope with negative timezone offset */
  USHORT second, hour,
         day, month, year;
  DATETIME dt;
  DosGetDateTime( &dt );
  second = (USHORT)dt.seconds;
  minute = (SHORT)dt.minutes + dt.timezone;
  hour = (USHORT)dt.hours;
  day = (USHORT)dt.day;
  month = (USHORT)dt.month;
  year = (USHORT)dt.year;

  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
  /* Calculate the Julian days */
  now = day - 32076 +
    1461*(year + 4800 + (month - 14)/12)/4 +
    367*(month - 2 - (month - 14)/12*12)/12 -
    3*((year + 4900 + (month - 14)/12)/100)/4;

  /* Add the fractional hours, mins and seconds */
  now += (hour + 12.0)/24.0;
  now += minute/1440.0;
  now += second/86400.0;
  *prNow = now;
#ifdef SQLITE_TEST
  if( sqlite3_current_time ){
    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  }
#endif
  return 0;
}

static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  return 0;
}

/*
** Initialize and deinitialize the operating system interface.
*/
int sqlite3_os_init(void){
  static sqlite3_vfs os2Vfs = {
    1,                 /* iVersion */
    sizeof(os2File),   /* szOsFile */
    CCHMAXPATH,        /* mxPathname */
    0,                 /* pNext */
    "os2",             /* zName */
    0,                 /* pAppData */

    os2Open,           /* xOpen */
    os2Delete,         /* xDelete */
    os2Access,         /* xAccess */
    os2FullPathname,   /* xFullPathname */
    os2DlOpen,         /* xDlOpen */
    os2DlError,        /* xDlError */
    os2DlSym,          /* xDlSym */
    os2DlClose,        /* xDlClose */
    os2Randomness,     /* xRandomness */
    os2Sleep,          /* xSleep */
    os2CurrentTime,    /* xCurrentTime */
    os2GetLastError    /* xGetLastError */
  };
  sqlite3_vfs_register(&os2Vfs, 1);
  initUconvObjects();
  return SQLITE_OK;
}
int sqlite3_os_end(void){
  freeUconvObjects();
  return SQLITE_OK;
}

#endif /* SQLITE_OS_OS2 */

Added src/os_unix.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains the VFS implementation for unix-like operating systems
** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
**
** There are actually several different VFS implementations in this file.
** The differences are in the way that file locking is done.  The default
** implementation uses Posix Advisory Locks.  Alternative implementations
** use flock(), dot-files, various proprietary locking schemas, or simply
** skip locking all together.
**
** This source file is organized into divisions where the logic for various
** subfunctions is contained within the appropriate division.  PLEASE
** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
** in the correct division and should be clearly labeled.
**
** The layout of divisions is as follows:
**
**   *  General-purpose declarations and utility functions.
**   *  Unique file ID logic used by VxWorks.
**   *  Various locking primitive implementations (all except proxy locking):
**      + for Posix Advisory Locks
**      + for no-op locks
**      + for dot-file locks
**      + for flock() locking
**      + for named semaphore locks (VxWorks only)
**      + for AFP filesystem locks (MacOSX only)
**   *  sqlite3_file methods not associated with locking.
**   *  Definitions of sqlite3_io_methods objects for all locking
**      methods plus "finder" functions for each locking method.
**   *  sqlite3_vfs method implementations.
**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
**   *  Definitions of sqlite3_vfs objects for all locking methods
**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
*/
#include "sqliteInt.h"
#if SQLITE_OS_UNIX              /* This file is used on unix only */

/*
** There are various methods for file locking used for concurrency
** control:
**
**   1. POSIX locking (the default),
**   2. No locking,
**   3. Dot-file locking,
**   4. flock() locking,
**   5. AFP locking (OSX only),
**   6. Named POSIX semaphores (VXWorks only),
**   7. proxy locking. (OSX only)
**
** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
** selection of the appropriate locking style based on the filesystem
** where the database is located.  
*/
#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
#  if defined(__APPLE__)
#    define SQLITE_ENABLE_LOCKING_STYLE 1
#  else
#    define SQLITE_ENABLE_LOCKING_STYLE 0
#  endif
#endif

/*
** Define the OS_VXWORKS pre-processor macro to 1 if building on 
** vxworks, or 0 otherwise.
*/
#ifndef OS_VXWORKS
#  if defined(__RTP__) || defined(_WRS_KERNEL)
#    define OS_VXWORKS 1
#  else
#    define OS_VXWORKS 0
#  endif
#endif

/*
** These #defines should enable >2GB file support on Posix if the
** underlying operating system supports it.  If the OS lacks
** large file support, these should be no-ops.
**
** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
** on the compiler command line.  This is necessary if you are compiling
** on a recent machine (ex: RedHat 7.2) but you want your code to work
** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
** without this option, LFS is enable.  But LFS does not exist in the kernel
** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
** portability you should omit LFS.
**
** The previous paragraph was written in 2005.  (This paragraph is written
** on 2008-11-28.) These days, all Linux kernels support large files, so
** you should probably leave LFS enabled.  But some embedded platforms might
** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
*/
#ifndef SQLITE_DISABLE_LFS
# define _LARGE_FILE       1
# ifndef _FILE_OFFSET_BITS
#   define _FILE_OFFSET_BITS 64
# endif
# define _LARGEFILE_SOURCE 1
#endif

/*
** standard include files.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>

#if SQLITE_ENABLE_LOCKING_STYLE
# include <sys/ioctl.h>
# if OS_VXWORKS
#  include <semaphore.h>
#  include <limits.h>
# else
#  include <sys/file.h>
#  include <sys/param.h>
#  include <sys/mount.h>
# endif
#endif /* SQLITE_ENABLE_LOCKING_STYLE */

/*
** If we are to be thread-safe, include the pthreads header and define
** the SQLITE_UNIX_THREADS macro.
*/
#if SQLITE_THREADSAFE
# include <pthread.h>
# define SQLITE_UNIX_THREADS 1
#endif

/*
** Default permissions when creating a new file
*/
#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
#endif

/*
 ** Default permissions when creating auto proxy dir
 */
#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
#endif

/*
** Maximum supported path-length.
*/
#define MAX_PATHNAME 512

/*
** Only set the lastErrno if the error code is a real error and not 
** a normal expected return code of SQLITE_BUSY or SQLITE_OK
*/
#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))


/*
** Sometimes, after a file handle is closed by SQLite, the file descriptor
** cannot be closed immediately. In these cases, instances of the following
** structure are used to store the file descriptor while waiting for an
** opportunity to either close or reuse it.
*/
typedef struct UnixUnusedFd UnixUnusedFd;
struct UnixUnusedFd {
  int fd;                   /* File descriptor to close */
  int flags;                /* Flags this file descriptor was opened with */
  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
};

/*
** The unixFile structure is subclass of sqlite3_file specific to the unix
** VFS implementations.
*/
typedef struct unixFile unixFile;
struct unixFile {
  sqlite3_io_methods const *pMethod;  /* Always the first entry */
  struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
  struct unixLockInfo *pLock;      /* Info about locks on this inode */
  int h;                           /* The file descriptor */
  int dirfd;                       /* File descriptor for the directory */
  unsigned char locktype;          /* The type of lock held on this fd */
  int lastErrno;                   /* The unix errno from the last I/O error */
  void *lockingContext;            /* Locking style specific state */
  UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
  int fileFlags;                   /* Miscellanous flags */
#if SQLITE_ENABLE_LOCKING_STYLE
  int openFlags;                   /* The flags specified at open() */
#endif
#if SQLITE_THREADSAFE && defined(__linux__)
  pthread_t tid;                   /* The thread that "owns" this unixFile */
#endif
#if OS_VXWORKS
  int isDelete;                    /* Delete on close if true */
  struct vxworksFileId *pId;       /* Unique file ID */
#endif
#ifndef NDEBUG
  /* The next group of variables are used to track whether or not the
  ** transaction counter in bytes 24-27 of database files are updated
  ** whenever any part of the database changes.  An assertion fault will
  ** occur if a file is updated without also updating the transaction
  ** counter.  This test is made to avoid new problems similar to the
  ** one described by ticket #3584. 
  */
  unsigned char transCntrChng;   /* True if the transaction counter changed */
  unsigned char dbUpdate;        /* True if any part of database file changed */
  unsigned char inNormalWrite;   /* True if in a normal write operation */
#endif
#ifdef SQLITE_TEST
  /* In test mode, increase the size of this structure a bit so that 
  ** it is larger than the struct CrashFile defined in test6.c.
  */
  char aPadding[32];
#endif
};

/*
** The following macros define bits in unixFile.fileFlags
*/
#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */

/*
** Include code that is common to all os_*.c files
*/
#include "os_common.h"

/*
** Define various macros that are missing from some systems.
*/
#ifndef O_LARGEFILE
# define O_LARGEFILE 0
#endif
#ifdef SQLITE_DISABLE_LFS
# undef O_LARGEFILE
# define O_LARGEFILE 0
#endif
#ifndef O_NOFOLLOW
# define O_NOFOLLOW 0
#endif
#ifndef O_BINARY
# define O_BINARY 0
#endif

/*
** The DJGPP compiler environment looks mostly like Unix, but it
** lacks the fcntl() system call.  So redefine fcntl() to be something
** that always succeeds.  This means that locking does not occur under
** DJGPP.  But it is DOS - what did you expect?
*/
#ifdef __DJGPP__
# define fcntl(A,B,C) 0
#endif

/*
** The threadid macro resolves to the thread-id or to 0.  Used for
** testing and debugging only.
*/
#if SQLITE_THREADSAFE
#define threadid pthread_self()
#else
#define threadid 0
#endif


/*
** Helper functions to obtain and relinquish the global mutex. The
** global mutex is used to protect the unixOpenCnt, unixLockInfo and
** vxworksFileId objects used by this file, all of which may be 
** shared by multiple threads.
**
** Function unixMutexHeld() is used to assert() that the global mutex 
** is held when required. This function is only used as part of assert() 
** statements. e.g.
**
**   unixEnterMutex()
**     assert( unixMutexHeld() );
**   unixEnterLeave()
*/
static void unixEnterMutex(void){
  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
}
static void unixLeaveMutex(void){
  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
}
#ifdef SQLITE_DEBUG
static int unixMutexHeld(void) {
  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
}
#endif


#ifdef SQLITE_DEBUG
/*
** Helper function for printing out trace information from debugging
** binaries. This returns the string represetation of the supplied
** integer lock-type.
*/
static const char *locktypeName(int locktype){
  switch( locktype ){
    case NO_LOCK: return "NONE";
    case SHARED_LOCK: return "SHARED";
    case RESERVED_LOCK: return "RESERVED";
    case PENDING_LOCK: return "PENDING";
    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  }
  return "ERROR";
}
#endif

#ifdef SQLITE_LOCK_TRACE
/*
** Print out information about all locking operations.
**
** This routine is used for troubleshooting locks on multithreaded
** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
** command-line option on the compiler.  This code is normally
** turned off.
*/
static int lockTrace(int fd, int op, struct flock *p){
  char *zOpName, *zType;
  int s;
  int savedErrno;
  if( op==F_GETLK ){
    zOpName = "GETLK";
  }else if( op==F_SETLK ){
    zOpName = "SETLK";
  }else{
    s = fcntl(fd, op, p);
    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
    return s;
  }
  if( p->l_type==F_RDLCK ){
    zType = "RDLCK";
  }else if( p->l_type==F_WRLCK ){
    zType = "WRLCK";
  }else if( p->l_type==F_UNLCK ){
    zType = "UNLCK";
  }else{
    assert( 0 );
  }
  assert( p->l_whence==SEEK_SET );
  s = fcntl(fd, op, p);
  savedErrno = errno;
  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
     (int)p->l_pid, s);
  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
    struct flock l2;
    l2 = *p;
    fcntl(fd, F_GETLK, &l2);
    if( l2.l_type==F_RDLCK ){
      zType = "RDLCK";
    }else if( l2.l_type==F_WRLCK ){
      zType = "WRLCK";
    }else if( l2.l_type==F_UNLCK ){
      zType = "UNLCK";
    }else{
      assert( 0 );
    }
    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  }
  errno = savedErrno;
  return s;
}
#define fcntl lockTrace
#endif /* SQLITE_LOCK_TRACE */



/*
** This routine translates a standard POSIX errno code into something
** useful to the clients of the sqlite3 functions.  Specifically, it is
** intended to translate a variety of "try again" errors into SQLITE_BUSY
** and a variety of "please close the file descriptor NOW" errors into 
** SQLITE_IOERR
** 
** Errors during initialization of locks, or file system support for locks,
** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
*/
static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  switch (posixError) {
  case 0: 
    return SQLITE_OK;
    
  case EAGAIN:
  case ETIMEDOUT:
  case EBUSY:
  case EINTR:
  case ENOLCK:  
    /* random NFS retry error, unless during file system support 
     * introspection, in which it actually means what it says */
    return SQLITE_BUSY;
    
  case EACCES: 
    /* EACCES is like EAGAIN during locking operations, but not any other time*/
    if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
	(sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
      return SQLITE_BUSY;
    }
    /* else fall through */
  case EPERM: 
    return SQLITE_PERM;
    
  case EDEADLK:
    return SQLITE_IOERR_BLOCKED;
    
#if EOPNOTSUPP!=ENOTSUP
  case EOPNOTSUPP: 
    /* something went terribly awry, unless during file system support 
     * introspection, in which it actually means what it says */
#endif
#ifdef ENOTSUP
  case ENOTSUP: 
    /* invalid fd, unless during file system support introspection, in which 
     * it actually means what it says */
#endif
  case EIO:
  case EBADF:
  case EINVAL:
  case ENOTCONN:
  case ENODEV:
  case ENXIO:
  case ENOENT:
  case ESTALE:
  case ENOSYS:
    /* these should force the client to close the file and reconnect */
    
  default: 
    return sqliteIOErr;
  }
}



/******************************************************************************
****************** Begin Unique File ID Utility Used By VxWorks ***************
**
** On most versions of unix, we can get a unique ID for a file by concatenating
** the device number and the inode number.  But this does not work on VxWorks.
** On VxWorks, a unique file id must be based on the canonical filename.
**
** A pointer to an instance of the following structure can be used as a
** unique file ID in VxWorks.  Each instance of this structure contains
** a copy of the canonical filename.  There is also a reference count.  
** The structure is reclaimed when the number of pointers to it drops to
** zero.
**
** There are never very many files open at one time and lookups are not
** a performance-critical path, so it is sufficient to put these
** structures on a linked list.
*/
struct vxworksFileId {
  struct vxworksFileId *pNext;  /* Next in a list of them all */
  int nRef;                     /* Number of references to this one */
  int nName;                    /* Length of the zCanonicalName[] string */
  char *zCanonicalName;         /* Canonical filename */
};

#if OS_VXWORKS
/* 
** All unique filenames are held on a linked list headed by this
** variable:
*/
static struct vxworksFileId *vxworksFileList = 0;

/*
** Simplify a filename into its canonical form
** by making the following changes:
**
**  * removing any trailing and duplicate /
**  * convert /./ into just /
**  * convert /A/../ where A is any simple name into just /
**
** Changes are made in-place.  Return the new name length.
**
** The original filename is in z[0..n-1].  Return the number of
** characters in the simplified name.
*/
static int vxworksSimplifyName(char *z, int n){
  int i, j;
  while( n>1 && z[n-1]=='/' ){ n--; }
  for(i=j=0; i<n; i++){
    if( z[i]=='/' ){
      if( z[i+1]=='/' ) continue;
      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
        i += 1;
        continue;
      }
      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
        while( j>0 && z[j-1]!='/' ){ j--; }
        if( j>0 ){ j--; }
        i += 2;
        continue;
      }
    }
    z[j++] = z[i];
  }
  z[j] = 0;
  return j;
}

/*
** Find a unique file ID for the given absolute pathname.  Return
** a pointer to the vxworksFileId object.  This pointer is the unique
** file ID.
**
** The nRef field of the vxworksFileId object is incremented before
** the object is returned.  A new vxworksFileId object is created
** and added to the global list if necessary.
**
** If a memory allocation error occurs, return NULL.
*/
static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  struct vxworksFileId *pNew;         /* search key and new file ID */
  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
  int n;                              /* Length of zAbsoluteName string */

  assert( zAbsoluteName[0]=='/' );
  n = (int)strlen(zAbsoluteName);
  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  if( pNew==0 ) return 0;
  pNew->zCanonicalName = (char*)&pNew[1];
  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  n = vxworksSimplifyName(pNew->zCanonicalName, n);

  /* Search for an existing entry that matching the canonical name.
  ** If found, increment the reference count and return a pointer to
  ** the existing file ID.
  */
  unixEnterMutex();
  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
    if( pCandidate->nName==n 
     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
    ){
       sqlite3_free(pNew);
       pCandidate->nRef++;
       unixLeaveMutex();
       return pCandidate;
    }
  }

  /* No match was found.  We will make a new file ID */
  pNew->nRef = 1;
  pNew->nName = n;
  pNew->pNext = vxworksFileList;
  vxworksFileList = pNew;
  unixLeaveMutex();
  return pNew;
}

/*
** Decrement the reference count on a vxworksFileId object.  Free
** the object when the reference count reaches zero.
*/
static void vxworksReleaseFileId(struct vxworksFileId *pId){
  unixEnterMutex();
  assert( pId->nRef>0 );
  pId->nRef--;
  if( pId->nRef==0 ){
    struct vxworksFileId **pp;
    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
    assert( *pp==pId );
    *pp = pId->pNext;
    sqlite3_free(pId);
  }
  unixLeaveMutex();
}
#endif /* OS_VXWORKS */
/*************** End of Unique File ID Utility Used By VxWorks ****************
******************************************************************************/


/******************************************************************************
*************************** Posix Advisory Locking ****************************
**
** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
** section 6.5.2.2 lines 483 through 490 specify that when a process
** sets or clears a lock, that operation overrides any prior locks set
** by the same process.  It does not explicitly say so, but this implies
** that it overrides locks set by the same process using a different
** file descriptor.  Consider this test case:
**
**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
**
** Suppose ./file1 and ./file2 are really the same file (because
** one is a hard or symbolic link to the other) then if you set
** an exclusive lock on fd1, then try to get an exclusive lock
** on fd2, it works.  I would have expected the second lock to
** fail since there was already a lock on the file due to fd1.
** But not so.  Since both locks came from the same process, the
** second overrides the first, even though they were on different
** file descriptors opened on different file names.
**
** This means that we cannot use POSIX locks to synchronize file access
** among competing threads of the same process.  POSIX locks will work fine
** to synchronize access for threads in separate processes, but not
** threads within the same process.
**
** To work around the problem, SQLite has to manage file locks internally
** on its own.  Whenever a new database is opened, we have to find the
** specific inode of the database file (the inode is determined by the
** st_dev and st_ino fields of the stat structure that fstat() fills in)
** and check for locks already existing on that inode.  When locks are
** created or removed, we have to look at our own internal record of the
** locks to see if another thread has previously set a lock on that same
** inode.
**
** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
** For VxWorks, we have to use the alternative unique ID system based on
** canonical filename and implemented in the previous division.)
**
** The sqlite3_file structure for POSIX is no longer just an integer file
** descriptor.  It is now a structure that holds the integer file
** descriptor and a pointer to a structure that describes the internal
** locks on the corresponding inode.  There is one locking structure
** per inode, so if the same inode is opened twice, both unixFile structures
** point to the same locking structure.  The locking structure keeps
** a reference count (so we will know when to delete it) and a "cnt"
** field that tells us its internal lock status.  cnt==0 means the
** file is unlocked.  cnt==-1 means the file has an exclusive lock.
** cnt>0 means there are cnt shared locks on the file.
**
** Any attempt to lock or unlock a file first checks the locking
** structure.  The fcntl() system call is only invoked to set a 
** POSIX lock if the internal lock structure transitions between
** a locked and an unlocked state.
**
** But wait:  there are yet more problems with POSIX advisory locks.
**
** If you close a file descriptor that points to a file that has locks,
** all locks on that file that are owned by the current process are
** released.  To work around this problem, each unixFile structure contains
** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
** per open inode, which means that multiple unixFile can point to a single
** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
** other unixFile open on the same inode that are holding locks, the call
** to close() the file descriptor is deferred until all of the locks clear.
** The unixOpenCnt structure keeps a list of file descriptors that need to
** be closed and that list is walked (and cleared) when the last lock
** clears.
**
** Yet another problem:  LinuxThreads do not play well with posix locks.
**
** Many older versions of linux use the LinuxThreads library which is
** not posix compliant.  Under LinuxThreads, a lock created by thread
** A cannot be modified or overridden by a different thread B.
** Only thread A can modify the lock.  Locking behavior is correct
** if the appliation uses the newer Native Posix Thread Library (NPTL)
** on linux - with NPTL a lock created by thread A can override locks
** in thread B.  But there is no way to know at compile-time which
** threading library is being used.  So there is no way to know at
** compile-time whether or not thread A can override locks on thread B.
** We have to do a run-time check to discover the behavior of the
** current process.
**
** On systems where thread A is unable to modify locks created by
** thread B, we have to keep track of which thread created each
** lock.  Hence there is an extra field in the key to the unixLockInfo
** structure to record this information.  And on those systems it
** is illegal to begin a transaction in one thread and finish it
** in another.  For this latter restriction, there is no work-around.
** It is a limitation of LinuxThreads.
*/

/*
** Set or check the unixFile.tid field.  This field is set when an unixFile
** is first opened.  All subsequent uses of the unixFile verify that the
** same thread is operating on the unixFile.  Some operating systems do
** not allow locks to be overridden by other threads and that restriction
** means that sqlite3* database handles cannot be moved from one thread
** to another while locks are held.
**
** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
** another as long as we are running on a system that supports threads
** overriding each others locks (which is now the most common behavior)
** or if no locks are held.  But the unixFile.pLock field needs to be
** recomputed because its key includes the thread-id.  See the 
** transferOwnership() function below for additional information
*/
#if SQLITE_THREADSAFE && defined(__linux__)
# define SET_THREADID(X)   (X)->tid = pthread_self()
# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
                            !pthread_equal((X)->tid, pthread_self()))
#else
# define SET_THREADID(X)
# define CHECK_THREADID(X) 0
#endif

/*
** An instance of the following structure serves as the key used
** to locate a particular unixOpenCnt structure given its inode.  This
** is the same as the unixLockKey except that the thread ID is omitted.
*/
struct unixFileId {
  dev_t dev;                  /* Device number */
#if OS_VXWORKS
  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
#else
  ino_t ino;                  /* Inode number */
#endif
};

/*
** An instance of the following structure serves as the key used
** to locate a particular unixLockInfo structure given its inode.
**
** If threads cannot override each others locks (LinuxThreads), then we
** set the unixLockKey.tid field to the thread ID.  If threads can override
** each others locks (Posix and NPTL) then tid is always set to zero.
** tid is omitted if we compile without threading support or on an OS
** other than linux.
*/
struct unixLockKey {
  struct unixFileId fid;  /* Unique identifier for the file */
#if SQLITE_THREADSAFE && defined(__linux__)
  pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
#endif
};

/*
** An instance of the following structure is allocated for each open
** inode.  Or, on LinuxThreads, there is one of these structures for
** each inode opened by each thread.
**
** A single inode can have multiple file descriptors, so each unixFile
** structure contains a pointer to an instance of this object and this
** object keeps a count of the number of unixFile pointing to it.
*/
struct unixLockInfo {
  struct unixLockKey lockKey;     /* The lookup key */
  int cnt;                        /* Number of SHARED locks held */
  int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  int nRef;                       /* Number of pointers to this structure */
  struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
  struct unixLockInfo *pPrev;     /*    .... doubly linked */
};

/*
** An instance of the following structure is allocated for each open
** inode.  This structure keeps track of the number of locks on that
** inode.  If a close is attempted against an inode that is holding
** locks, the close is deferred until all locks clear by adding the
** file descriptor to be closed to the pending list.
**
** TODO:  Consider changing this so that there is only a single file
** descriptor for each open file, even when it is opened multiple times.
** The close() system call would only occur when the last database
** using the file closes.
*/
struct unixOpenCnt {
  struct unixFileId fileId;   /* The lookup key */
  int nRef;                   /* Number of pointers to this structure */
  int nLock;                  /* Number of outstanding locks */
  UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
#if OS_VXWORKS
  sem_t *pSem;                     /* Named POSIX semaphore */
  char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
#endif
  struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
};

/*
** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
** tables.  But the number of objects is rarely more than a dozen and
** never exceeds a few thousand.  And lookup is not on a critical
** path so a simple linked list will suffice.
*/
static struct unixLockInfo *lockList = 0;
static struct unixOpenCnt *openList = 0;

/*
** This variable remembers whether or not threads can override each others
** locks.
**
**    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
**    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
**   -1:  We don't know yet.
**
** On some systems, we know at compile-time if threads can override each
** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
** will be set appropriately.  On other systems, we have to check at
** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
** undefined.
**
** This variable normally has file scope only.  But during testing, we make
** it a global so that the test code can change its value in order to verify
** that the right stuff happens in either case.
*/
#if SQLITE_THREADSAFE && defined(__linux__)
#  ifndef SQLITE_THREAD_OVERRIDE_LOCK
#    define SQLITE_THREAD_OVERRIDE_LOCK -1
#  endif
#  ifdef SQLITE_TEST
int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
#  else
static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
#  endif
#endif

/*
** This structure holds information passed into individual test
** threads by the testThreadLockingBehavior() routine.
*/
struct threadTestData {
  int fd;                /* File to be locked */
  struct flock lock;     /* The locking operation */
  int result;            /* Result of the locking operation */
};

#if SQLITE_THREADSAFE && defined(__linux__)
/*
** This function is used as the main routine for a thread launched by
** testThreadLockingBehavior(). It tests whether the shared-lock obtained
** by the main thread in testThreadLockingBehavior() conflicts with a
** hypothetical write-lock obtained by this thread on the same file.
**
** The write-lock is not actually acquired, as this is not possible if 
** the file is open in read-only mode (see ticket #3472).
*/ 
static void *threadLockingTest(void *pArg){
  struct threadTestData *pData = (struct threadTestData*)pArg;
  pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
  return pArg;
}
#endif /* SQLITE_THREADSAFE && defined(__linux__) */


#if SQLITE_THREADSAFE && defined(__linux__)
/*
** This procedure attempts to determine whether or not threads
** can override each others locks then sets the 
** threadsOverrideEachOthersLocks variable appropriately.
*/
static void testThreadLockingBehavior(int fd_orig){
  int fd;
  int rc;
  struct threadTestData d;
  struct flock l;
  pthread_t t;

  fd = dup(fd_orig);
  if( fd<0 ) return;
  memset(&l, 0, sizeof(l));
  l.l_type = F_RDLCK;
  l.l_len = 1;
  l.l_start = 0;
  l.l_whence = SEEK_SET;
  rc = fcntl(fd_orig, F_SETLK, &l);
  if( rc!=0 ) return;
  memset(&d, 0, sizeof(d));
  d.fd = fd;
  d.lock = l;
  d.lock.l_type = F_WRLCK;
  if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
    pthread_join(t, 0);
  }
  close(fd);
  if( d.result!=0 ) return;
  threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
}
#endif /* SQLITE_THREADSAFE && defined(__linux__) */

/*
** Release a unixLockInfo structure previously allocated by findLockInfo().
**
** The mutex entered using the unixEnterMutex() function must be held
** when this function is called.
*/
static void releaseLockInfo(struct unixLockInfo *pLock){
  assert( unixMutexHeld() );
  if( pLock ){
    pLock->nRef--;
    if( pLock->nRef==0 ){
      if( pLock->pPrev ){
        assert( pLock->pPrev->pNext==pLock );
        pLock->pPrev->pNext = pLock->pNext;
      }else{
        assert( lockList==pLock );
        lockList = pLock->pNext;
      }
      if( pLock->pNext ){
        assert( pLock->pNext->pPrev==pLock );
        pLock->pNext->pPrev = pLock->pPrev;
      }
      sqlite3_free(pLock);
    }
  }
}

/*
** Release a unixOpenCnt structure previously allocated by findLockInfo().
**
** The mutex entered using the unixEnterMutex() function must be held
** when this function is called.
*/
static void releaseOpenCnt(struct unixOpenCnt *pOpen){
  assert( unixMutexHeld() );
  if( pOpen ){
    pOpen->nRef--;
    if( pOpen->nRef==0 ){
      if( pOpen->pPrev ){
        assert( pOpen->pPrev->pNext==pOpen );
        pOpen->pPrev->pNext = pOpen->pNext;
      }else{
        assert( openList==pOpen );
        openList = pOpen->pNext;
      }
      if( pOpen->pNext ){
        assert( pOpen->pNext->pPrev==pOpen );
        pOpen->pNext->pPrev = pOpen->pPrev;
      }
#if SQLITE_THREADSAFE && defined(__linux__)
      assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
#endif

      /* If pOpen->pUnused is not null, then memory and file-descriptors
      ** are leaked.
      **
      ** This will only happen if, under Linuxthreads, the user has opened
      ** a transaction in one thread, then attempts to close the database
      ** handle from another thread (without first unlocking the db file).
      ** This is a misuse.  */
      sqlite3_free(pOpen);
    }
  }
}

/*
** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
** describes that file descriptor.  Create new ones if necessary.  The
** return values might be uninitialized if an error occurs.
**
** The mutex entered using the unixEnterMutex() function must be held
** when this function is called.
**
** Return an appropriate error code.
*/
static int findLockInfo(
  unixFile *pFile,               /* Unix file with file desc used in the key */
  struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
  struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
){
  int rc;                        /* System call return code */
  int fd;                        /* The file descriptor for pFile */
  struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
  struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
  struct stat statbuf;           /* Low-level file information */
  struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
  struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */

  assert( unixMutexHeld() );

  /* Get low-level information about the file that we can used to
  ** create a unique name for the file.
  */
  fd = pFile->h;
  rc = fstat(fd, &statbuf);
  if( rc!=0 ){
    pFile->lastErrno = errno;
#ifdef EOVERFLOW
    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
#endif
    return SQLITE_IOERR;
  }

#ifdef __APPLE__
  /* On OS X on an msdos filesystem, the inode number is reported
  ** incorrectly for zero-size files.  See ticket #3260.  To work
  ** around this problem (we consider it a bug in OS X, not SQLite)
  ** we always increase the file size to 1 by writing a single byte
  ** prior to accessing the inode number.  The one byte written is
  ** an ASCII 'S' character which also happens to be the first byte
  ** in the header of every SQLite database.  In this way, if there
  ** is a race condition such that another thread has already populated
  ** the first page of the database, no damage is done.
  */
  if( statbuf.st_size==0 ){
    rc = write(fd, "S", 1);
    if( rc!=1 ){
      return SQLITE_IOERR;
    }
    rc = fstat(fd, &statbuf);
    if( rc!=0 ){
      pFile->lastErrno = errno;
      return SQLITE_IOERR;
    }
  }
#endif

  memset(&lockKey, 0, sizeof(lockKey));
  lockKey.fid.dev = statbuf.st_dev;
#if OS_VXWORKS
  lockKey.fid.pId = pFile->pId;
#else
  lockKey.fid.ino = statbuf.st_ino;
#endif
#if SQLITE_THREADSAFE && defined(__linux__)
  if( threadsOverrideEachOthersLocks<0 ){
    testThreadLockingBehavior(fd);
  }
  lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
#endif
  fileId = lockKey.fid;
  if( ppLock!=0 ){
    pLock = lockList;
    while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
      pLock = pLock->pNext;
    }
    if( pLock==0 ){
      pLock = sqlite3_malloc( sizeof(*pLock) );
      if( pLock==0 ){
        rc = SQLITE_NOMEM;
        goto exit_findlockinfo;
      }
      memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
      pLock->nRef = 1;
      pLock->cnt = 0;
      pLock->locktype = 0;
      pLock->pNext = lockList;
      pLock->pPrev = 0;
      if( lockList ) lockList->pPrev = pLock;
      lockList = pLock;
    }else{
      pLock->nRef++;
    }
    *ppLock = pLock;
  }
  if( ppOpen!=0 ){
    pOpen = openList;
    while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
      pOpen = pOpen->pNext;
    }
    if( pOpen==0 ){
      pOpen = sqlite3_malloc( sizeof(*pOpen) );
      if( pOpen==0 ){
        releaseLockInfo(pLock);
        rc = SQLITE_NOMEM;
        goto exit_findlockinfo;
      }
      memset(pOpen, 0, sizeof(*pOpen));
      pOpen->fileId = fileId;
      pOpen->nRef = 1;
      pOpen->pNext = openList;
      if( openList ) openList->pPrev = pOpen;
      openList = pOpen;
    }else{
      pOpen->nRef++;
    }
    *ppOpen = pOpen;
  }

exit_findlockinfo:
  return rc;
}

/*
** If we are currently in a different thread than the thread that the
** unixFile argument belongs to, then transfer ownership of the unixFile
** over to the current thread.
**
** A unixFile is only owned by a thread on systems that use LinuxThreads.
**
** Ownership transfer is only allowed if the unixFile is currently unlocked.
** If the unixFile is locked and an ownership is wrong, then return
** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
*/
#if SQLITE_THREADSAFE && defined(__linux__)
static int transferOwnership(unixFile *pFile){
  int rc;
  pthread_t hSelf;
  if( threadsOverrideEachOthersLocks ){
    /* Ownership transfers not needed on this system */
    return SQLITE_OK;
  }
  hSelf = pthread_self();
  if( pthread_equal(pFile->tid, hSelf) ){
    /* We are still in the same thread */
    OSTRACE1("No-transfer, same thread\n");
    return SQLITE_OK;
  }
  if( pFile->locktype!=NO_LOCK ){
    /* We cannot change ownership while we are holding a lock! */
    return SQLITE_MISUSE;
  }
  OSTRACE4("Transfer ownership of %d from %d to %d\n",
            pFile->h, pFile->tid, hSelf);
  pFile->tid = hSelf;
  if (pFile->pLock != NULL) {
    releaseLockInfo(pFile->pLock);
    rc = findLockInfo(pFile, &pFile->pLock, 0);
    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
           locktypeName(pFile->locktype),
           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
    return rc;
  } else {
    return SQLITE_OK;
  }
}
#else  /* if not SQLITE_THREADSAFE */
  /* On single-threaded builds, ownership transfer is a no-op */
# define transferOwnership(X) SQLITE_OK
#endif /* SQLITE_THREADSAFE */


/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  int rc = SQLITE_OK;
  int reserved = 0;
  unixFile *pFile = (unixFile*)id;

  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );

  assert( pFile );
  unixEnterMutex(); /* Because pFile->pLock is shared across threads */

  /* Check if a thread in this process holds such a lock */
  if( pFile->pLock->locktype>SHARED_LOCK ){
    reserved = 1;
  }

  /* Otherwise see if some other process holds it.
  */
#ifndef __DJGPP__
  if( !reserved ){
    struct flock lock;
    lock.l_whence = SEEK_SET;
    lock.l_start = RESERVED_BYTE;
    lock.l_len = 1;
    lock.l_type = F_WRLCK;
    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
      int tErrno = errno;
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
      pFile->lastErrno = tErrno;
    } else if( lock.l_type!=F_UNLCK ){
      reserved = 1;
    }
  }
#endif
  
  unixLeaveMutex();
  OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);

  *pResOut = reserved;
  return rc;
}

/*
** Perform a file locking operation on a range of bytes in a file.
** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
** Return 0 on success or -1 for failure.  On failure, write the error
** code into *pErrcode.
**
** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
** the range of bytes on the locking page between SHARED_FIRST and
** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
** bytes from 0 up to but not including PENDING_BYTE, and all bytes
** that follow SHARED_FIRST.
**
** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
** default case) then only lock a small range of bytes from SHARED_FIRST
** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
** true then lock every byte in the file except for PENDING_BYTE and
** RESERVED_BYTE.
**
** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
** and so the locking schemes are compatible.  One type of lock will
** effectively exclude the other type.  The reason for using the
** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
** of bytes to be read or written, we give hints to NFS to help it
** maintain cache coherency.  On the other hand, whole file locking
** is slower, so we don't want to use it except for NFS.
*/
static int rangeLock(unixFile *pFile, int op, int *pErrcode){
  struct flock lock;
  int rc;
  lock.l_type = op;
  lock.l_start = SHARED_FIRST;
  lock.l_whence = SEEK_SET;
  if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
    lock.l_len = SHARED_SIZE;
    rc = fcntl(pFile->h, F_SETLK, &lock);
    *pErrcode = errno;
  }else{
    lock.l_len = 0;
    rc = fcntl(pFile->h, F_SETLK, &lock);
    *pErrcode = errno;
    if( NEVER(op==F_UNLCK) || rc!=(-1) ){
      lock.l_start = 0;
      lock.l_len = PENDING_BYTE;
      rc = fcntl(pFile->h, F_SETLK, &lock);
      if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
        *pErrcode = errno;
        lock.l_type = F_UNLCK;
        lock.l_start = SHARED_FIRST;
        lock.l_len = 0;
        fcntl(pFile->h, F_SETLK, &lock);
      }
    }
  }
  return rc;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
** routine to lower a locking level.
*/
static int unixLock(sqlite3_file *id, int locktype){
  /* The following describes the implementation of the various locks and
  ** lock transitions in terms of the POSIX advisory shared and exclusive
  ** lock primitives (called read-locks and write-locks below, to avoid
  ** confusion with SQLite lock names). The algorithms are complicated
  ** slightly in order to be compatible with windows systems simultaneously
  ** accessing the same database file, in case that is ever required.
  **
  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  ** byte', each single bytes at well known offsets, and the 'shared byte
  ** range', a range of 510 bytes at a well known offset.
  **
  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  ** byte'.  If this is successful, a random byte from the 'shared byte
  ** range' is read-locked and the lock on the 'pending byte' released.
  **
  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  ** A RESERVED lock is implemented by grabbing a write-lock on the
  ** 'reserved byte'. 
  **
  ** A process may only obtain a PENDING lock after it has obtained a
  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  ** on the 'pending byte'. This ensures that no new SHARED locks can be
  ** obtained, but existing SHARED locks are allowed to persist. A process
  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  ** This property is used by the algorithm for rolling back a journal file
  ** after a crash.
  **
  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  ** implemented by obtaining a write-lock on the entire 'shared byte
  ** range'. Since all other locks require a read-lock on one of the bytes
  ** within this range, this ensures that no other locks are held on the
  ** database. 
  **
  ** The reason a single byte cannot be used instead of the 'shared byte
  ** range' is that some versions of windows do not support read-locks. By
  ** locking a random byte from a range, concurrent SHARED locks may exist
  ** even if the locking primitive used is always a write-lock.
  */
  int rc = SQLITE_OK;
  unixFile *pFile = (unixFile*)id;
  struct unixLockInfo *pLock = pFile->pLock;
  struct flock lock;
  int s = 0;
  int tErrno;

  assert( pFile );
  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
      locktypeName(locktype), locktypeName(pFile->locktype),
      locktypeName(pLock->locktype), pLock->cnt , getpid());

  /* If there is already a lock of this type or more restrictive on the
  ** unixFile, do nothing. Don't use the end_lock: exit path, as
  ** unixEnterMutex() hasn't been called yet.
  */
  if( pFile->locktype>=locktype ){
    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
            locktypeName(locktype));
    return SQLITE_OK;
  }

  /* Make sure the locking sequence is correct.
  **  (1) We never move from unlocked to anything higher than shared lock.
  **  (2) SQLite never explicitly requests a pendig lock.
  **  (3) A shared lock is always held when a reserve lock is requested.
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* This mutex is needed because pFile->pLock is shared across threads
  */
  unixEnterMutex();

  /* Make sure the current thread owns the pFile.
  */
  rc = transferOwnership(pFile);
  if( rc!=SQLITE_OK ){
    unixLeaveMutex();
    return rc;
  }
  pLock = pFile->pLock;

  /* If some thread using this PID has a lock via a different unixFile*
  ** handle that precludes the requested lock, return BUSY.
  */
  if( (pFile->locktype!=pLock->locktype && 
          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
  ){
    rc = SQLITE_BUSY;
    goto end_lock;
  }

  /* If a SHARED lock is requested, and some thread using this PID already
  ** has a SHARED or RESERVED lock, then increment reference counts and
  ** return SQLITE_OK.
  */
  if( locktype==SHARED_LOCK && 
      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
    assert( locktype==SHARED_LOCK );
    assert( pFile->locktype==0 );
    assert( pLock->cnt>0 );
    pFile->locktype = SHARED_LOCK;
    pLock->cnt++;
    pFile->pOpen->nLock++;
    goto end_lock;
  }


  /* A PENDING lock is needed before acquiring a SHARED lock and before
  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  ** be released.
  */
  lock.l_len = 1L;
  lock.l_whence = SEEK_SET;
  if( locktype==SHARED_LOCK 
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  ){
    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
    lock.l_start = PENDING_BYTE;
    s = fcntl(pFile->h, F_SETLK, &lock);
    if( s==(-1) ){
      tErrno = errno;
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
      if( IS_LOCK_ERROR(rc) ){
        pFile->lastErrno = tErrno;
      }
      goto end_lock;
    }
  }


  /* If control gets to this point, then actually go ahead and make
  ** operating system calls for the specified lock.
  */
  if( locktype==SHARED_LOCK ){
    assert( pLock->cnt==0 );
    assert( pLock->locktype==0 );

    /* Now get the read-lock */
    s = rangeLock(pFile, F_RDLCK, &tErrno);

    /* Drop the temporary PENDING lock */
    lock.l_start = PENDING_BYTE;
    lock.l_len = 1L;
    lock.l_type = F_UNLCK;
    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
      if( s != -1 ){
        /* This could happen with a network mount */
        tErrno = errno; 
        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
        if( IS_LOCK_ERROR(rc) ){
          pFile->lastErrno = tErrno;
        }
        goto end_lock;
      }
    }
    if( s==(-1) ){
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
      if( IS_LOCK_ERROR(rc) ){
        pFile->lastErrno = tErrno;
      }
    }else{
      pFile->locktype = SHARED_LOCK;
      pFile->pOpen->nLock++;
      pLock->cnt = 1;
    }
  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
    /* We are trying for an exclusive lock but another thread in this
    ** same process is still holding a shared lock. */
    rc = SQLITE_BUSY;
  }else{
    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
    ** assumed that there is a SHARED or greater lock on the file
    ** already.
    */
    assert( 0!=pFile->locktype );
    lock.l_type = F_WRLCK;
    switch( locktype ){
      case RESERVED_LOCK:
        lock.l_start = RESERVED_BYTE;
        s = fcntl(pFile->h, F_SETLK, &lock);
        tErrno = errno;
        break;
      case EXCLUSIVE_LOCK:
        s = rangeLock(pFile, F_WRLCK, &tErrno);
        break;
      default:
        assert(0);
    }
    if( s==(-1) ){
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
      if( IS_LOCK_ERROR(rc) ){
        pFile->lastErrno = tErrno;
      }
    }
  }
  

#ifndef NDEBUG
  /* Set up the transaction-counter change checking flags when
  ** transitioning from a SHARED to a RESERVED lock.  The change
  ** from SHARED to RESERVED marks the beginning of a normal
  ** write operation (not a hot journal rollback).
  */
  if( rc==SQLITE_OK
   && pFile->locktype<=SHARED_LOCK
   && locktype==RESERVED_LOCK
  ){
    pFile->transCntrChng = 0;
    pFile->dbUpdate = 0;
    pFile->inNormalWrite = 1;
  }
#endif


  if( rc==SQLITE_OK ){
    pFile->locktype = locktype;
    pLock->locktype = locktype;
  }else if( locktype==EXCLUSIVE_LOCK ){
    pFile->locktype = PENDING_LOCK;
    pLock->locktype = PENDING_LOCK;
  }

end_lock:
  unixLeaveMutex();
  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
      rc==SQLITE_OK ? "ok" : "failed");
  return rc;
}

/*
** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
** If all such file descriptors are closed without error, the list is
** cleared and SQLITE_OK returned.
**
** Otherwise, if an error occurs, then successfully closed file descriptor
** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
** not deleted and SQLITE_IOERR_CLOSE returned.
*/ 
static int closePendingFds(unixFile *pFile){
  int rc = SQLITE_OK;
  struct unixOpenCnt *pOpen = pFile->pOpen;
  UnixUnusedFd *pError = 0;
  UnixUnusedFd *p;
  UnixUnusedFd *pNext;
  for(p=pOpen->pUnused; p; p=pNext){
    pNext = p->pNext;
    if( close(p->fd) ){
      pFile->lastErrno = errno;
      rc = SQLITE_IOERR_CLOSE;
      p->pNext = pError;
      pError = p;
    }else{
      sqlite3_free(p);
    }
  }
  pOpen->pUnused = pError;
  return rc;
}

/*
** Add the file descriptor used by file handle pFile to the corresponding
** pUnused list.
*/
static void setPendingFd(unixFile *pFile){
  struct unixOpenCnt *pOpen = pFile->pOpen;
  UnixUnusedFd *p = pFile->pUnused;
  p->pNext = pOpen->pUnused;
  pOpen->pUnused = p;
  pFile->h = -1;
  pFile->pUnused = 0;
}

/*
** Lower the locking level on file descriptor pFile to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
*/
static int unixUnlock(sqlite3_file *id, int locktype){
  unixFile *pFile = (unixFile*)id; /* The open file */
  struct unixLockInfo *pLock;      /* Structure describing current lock state */
  struct flock lock;               /* Information passed into fcntl() */
  int rc = SQLITE_OK;              /* Return code from this interface */
  int h;                           /* The underlying file descriptor */
  int tErrno;                      /* Error code from system call errors */

  assert( pFile );
  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());

  assert( locktype<=SHARED_LOCK );
  if( pFile->locktype<=locktype ){
    return SQLITE_OK;
  }
  if( CHECK_THREADID(pFile) ){
    return SQLITE_MISUSE;
  }
  unixEnterMutex();
  h = pFile->h;
  pLock = pFile->pLock;
  assert( pLock->cnt!=0 );
  if( pFile->locktype>SHARED_LOCK ){
    assert( pLock->locktype==pFile->locktype );
    SimulateIOErrorBenign(1);
    SimulateIOError( h=(-1) )
    SimulateIOErrorBenign(0);

#ifndef NDEBUG
    /* When reducing a lock such that other processes can start
    ** reading the database file again, make sure that the
    ** transaction counter was updated if any part of the database
    ** file changed.  If the transaction counter is not updated,
    ** other connections to the same file might not realize that
    ** the file has changed and hence might not know to flush their
    ** cache.  The use of a stale cache can lead to database corruption.
    */
    assert( pFile->inNormalWrite==0
         || pFile->dbUpdate==0
         || pFile->transCntrChng==1 );
    pFile->inNormalWrite = 0;
#endif


    if( locktype==SHARED_LOCK ){
      if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
        if( IS_LOCK_ERROR(rc) ){
          pFile->lastErrno = tErrno;
        }
        goto end_unlock;
      }
    }
    lock.l_type = F_UNLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = PENDING_BYTE;
    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
      pLock->locktype = SHARED_LOCK;
    }else{
      tErrno = errno;
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
      if( IS_LOCK_ERROR(rc) ){
        pFile->lastErrno = tErrno;
      }
      goto end_unlock;
    }
  }
  if( locktype==NO_LOCK ){
    struct unixOpenCnt *pOpen;

    /* Decrement the shared lock counter.  Release the lock using an
    ** OS call only when all threads in this same process have released
    ** the lock.
    */
    pLock->cnt--;
    if( pLock->cnt==0 ){
      lock.l_type = F_UNLCK;
      lock.l_whence = SEEK_SET;
      lock.l_start = lock.l_len = 0L;
      SimulateIOErrorBenign(1);
      SimulateIOError( h=(-1) )
      SimulateIOErrorBenign(0);
      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
        pLock->locktype = NO_LOCK;
      }else{
        tErrno = errno;
        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
        if( IS_LOCK_ERROR(rc) ){
          pFile->lastErrno = tErrno;
        }
        pLock->locktype = NO_LOCK;
        pFile->locktype = NO_LOCK;
      }
    }

    /* Decrement the count of locks against this same file.  When the
    ** count reaches zero, close any other file descriptors whose close
    ** was deferred because of outstanding locks.
    */
    pOpen = pFile->pOpen;
    pOpen->nLock--;
    assert( pOpen->nLock>=0 );
    if( pOpen->nLock==0 ){
      int rc2 = closePendingFds(pFile);
      if( rc==SQLITE_OK ){
        rc = rc2;
      }
    }
  }
	
end_unlock:
  unixLeaveMutex();
  if( rc==SQLITE_OK ) pFile->locktype = locktype;
  return rc;
}

/*
** This function performs the parts of the "close file" operation 
** common to all locking schemes. It closes the directory and file
** handles, if they are valid, and sets all fields of the unixFile
** structure to 0.
**
** It is *not* necessary to hold the mutex when this routine is called,
** even on VxWorks.  A mutex will be acquired on VxWorks by the
** vxworksReleaseFileId() routine.
*/
static int closeUnixFile(sqlite3_file *id){
  unixFile *pFile = (unixFile*)id;
  if( pFile ){
    if( pFile->dirfd>=0 ){
      int err = close(pFile->dirfd);
      if( err ){
        pFile->lastErrno = errno;
        return SQLITE_IOERR_DIR_CLOSE;
      }else{
        pFile->dirfd=-1;
      }
    }
    if( pFile->h>=0 ){
      int err = close(pFile->h);
      if( err ){
        pFile->lastErrno = errno;
        return SQLITE_IOERR_CLOSE;
      }
    }
#if OS_VXWORKS
    if( pFile->pId ){
      if( pFile->isDelete ){
        unlink(pFile->pId->zCanonicalName);
      }
      vxworksReleaseFileId(pFile->pId);
      pFile->pId = 0;
    }
#endif
    OSTRACE2("CLOSE   %-3d\n", pFile->h);
    OpenCounter(-1);
    sqlite3_free(pFile->pUnused);
    memset(pFile, 0, sizeof(unixFile));
  }
  return SQLITE_OK;
}

/*
** Close a file.
*/
static int unixClose(sqlite3_file *id){
  int rc = SQLITE_OK;
  if( id ){
    unixFile *pFile = (unixFile *)id;
    unixUnlock(id, NO_LOCK);
    unixEnterMutex();
    if( pFile->pOpen && pFile->pOpen->nLock ){
      /* If there are outstanding locks, do not actually close the file just
      ** yet because that would clear those locks.  Instead, add the file
      ** descriptor to pOpen->pUnused list.  It will be automatically closed 
      ** when the last lock is cleared.
      */
      setPendingFd(pFile);
    }
    releaseLockInfo(pFile->pLock);
    releaseOpenCnt(pFile->pOpen);
    rc = closeUnixFile(id);
    unixLeaveMutex();
  }
  return rc;
}

/************** End of the posix advisory lock implementation *****************
******************************************************************************/

/******************************************************************************
****************************** No-op Locking **********************************
**
** Of the various locking implementations available, this is by far the
** simplest:  locking is ignored.  No attempt is made to lock the database
** file for reading or writing.
**
** This locking mode is appropriate for use on read-only databases
** (ex: databases that are burned into CD-ROM, for example.)  It can
** also be used if the application employs some external mechanism to
** prevent simultaneous access of the same database by two or more
** database connections.  But there is a serious risk of database
** corruption if this locking mode is used in situations where multiple
** database connections are accessing the same database file at the same
** time and one or more of those connections are writing.
*/

static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  UNUSED_PARAMETER(NotUsed);
  *pResOut = 0;
  return SQLITE_OK;
}
static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  return SQLITE_OK;
}
static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  return SQLITE_OK;
}

/*
** Close the file.
*/
static int nolockClose(sqlite3_file *id) {
  return closeUnixFile(id);
}

/******************* End of the no-op lock implementation *********************
******************************************************************************/

/******************************************************************************
************************* Begin dot-file Locking ******************************
**
** The dotfile locking implementation uses the existance of separate lock
** files in order to control access to the database.  This works on just
** about every filesystem imaginable.  But there are serious downsides:
**
**    (1)  There is zero concurrency.  A single reader blocks all other
**         connections from reading or writing the database.
**
**    (2)  An application crash or power loss can leave stale lock files
**         sitting around that need to be cleared manually.
**
** Nevertheless, a dotlock is an appropriate locking mode for use if no
** other locking strategy is available.
**
** Dotfile locking works by creating a file in the same directory as the
** database and with the same name but with a ".lock" extension added.
** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
*/

/*
** The file suffix added to the data base filename in order to create the
** lock file.
*/
#define DOTLOCK_SUFFIX ".lock"

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
**
** In dotfile locking, either a lock exists or it does not.  So in this
** variation of CheckReservedLock(), *pResOut is set to true if any lock
** is held on the file and false if the file is unlocked.
*/
static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  int rc = SQLITE_OK;
  int reserved = 0;
  unixFile *pFile = (unixFile*)id;

  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  
  assert( pFile );

  /* Check if a thread in this process holds such a lock */
  if( pFile->locktype>SHARED_LOCK ){
    /* Either this connection or some other connection in the same process
    ** holds a lock on the file.  No need to check further. */
    reserved = 1;
  }else{
    /* The lock is held if and only if the lockfile exists */
    const char *zLockFile = (const char*)pFile->lockingContext;
    reserved = access(zLockFile, 0)==0;
  }
  OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  *pResOut = reserved;
  return rc;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
** routine to lower a locking level.
**
** With dotfile locking, we really only support state (4): EXCLUSIVE.
** But we track the other locking levels internally.
*/
static int dotlockLock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  int fd;
  char *zLockFile = (char *)pFile->lockingContext;
  int rc = SQLITE_OK;


  /* If we have any lock, then the lock file already exists.  All we have
  ** to do is adjust our internal record of the lock level.
  */
  if( pFile->locktype > NO_LOCK ){
    pFile->locktype = locktype;
#if !OS_VXWORKS
    /* Always update the timestamp on the old file */
    utimes(zLockFile, NULL);
#endif
    return SQLITE_OK;
  }
  
  /* grab an exclusive lock */
  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
  if( fd<0 ){
    /* failed to open/create the file, someone else may have stolen the lock */
    int tErrno = errno;
    if( EEXIST == tErrno ){
      rc = SQLITE_BUSY;
    } else {
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
      if( IS_LOCK_ERROR(rc) ){
        pFile->lastErrno = tErrno;
      }
    }
    return rc;
  } 
  if( close(fd) ){
    pFile->lastErrno = errno;
    rc = SQLITE_IOERR_CLOSE;
  }
  
  /* got it, set the type and return ok */
  pFile->locktype = locktype;
  return rc;
}

/*
** Lower the locking level on file descriptor pFile to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
**
** When the locking level reaches NO_LOCK, delete the lock file.
*/
static int dotlockUnlock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  char *zLockFile = (char *)pFile->lockingContext;

  assert( pFile );
  OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
	   pFile->locktype, getpid());
  assert( locktype<=SHARED_LOCK );
  
  /* no-op if possible */
  if( pFile->locktype==locktype ){
    return SQLITE_OK;
  }

  /* To downgrade to shared, simply update our internal notion of the
  ** lock state.  No need to mess with the file on disk.
  */
  if( locktype==SHARED_LOCK ){
    pFile->locktype = SHARED_LOCK;
    return SQLITE_OK;
  }
  
  /* To fully unlock the database, delete the lock file */
  assert( locktype==NO_LOCK );
  if( unlink(zLockFile) ){
    int rc = 0;
    int tErrno = errno;
    if( ENOENT != tErrno ){
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
    }
    if( IS_LOCK_ERROR(rc) ){
      pFile->lastErrno = tErrno;
    }
    return rc; 
  }
  pFile->locktype = NO_LOCK;
  return SQLITE_OK;
}

/*
** Close a file.  Make sure the lock has been released before closing.
*/
static int dotlockClose(sqlite3_file *id) {
  int rc;
  if( id ){
    unixFile *pFile = (unixFile*)id;
    dotlockUnlock(id, NO_LOCK);
    sqlite3_free(pFile->lockingContext);
  }
  rc = closeUnixFile(id);
  return rc;
}
/****************** End of the dot-file lock implementation *******************
******************************************************************************/

/******************************************************************************
************************** Begin flock Locking ********************************
**
** Use the flock() system call to do file locking.
**
** flock() locking is like dot-file locking in that the various
** fine-grain locking levels supported by SQLite are collapsed into
** a single exclusive lock.  In other words, SHARED, RESERVED, and
** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
** still works when you do this, but concurrency is reduced since
** only a single process can be reading the database at a time.
**
** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
** compiling for VXWORKS.
*/
#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  int rc = SQLITE_OK;
  int reserved = 0;
  unixFile *pFile = (unixFile*)id;
  
  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  
  assert( pFile );
  
  /* Check if a thread in this process holds such a lock */
  if( pFile->locktype>SHARED_LOCK ){
    reserved = 1;
  }
  
  /* Otherwise see if some other process holds it. */
  if( !reserved ){
    /* attempt to get the lock */
    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
    if( !lrc ){
      /* got the lock, unlock it */
      lrc = flock(pFile->h, LOCK_UN);
      if ( lrc ) {
        int tErrno = errno;
        /* unlock failed with an error */
        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
        if( IS_LOCK_ERROR(lrc) ){
          pFile->lastErrno = tErrno;
          rc = lrc;
        }
      }
    } else {
      int tErrno = errno;
      reserved = 1;
      /* someone else might have it reserved */
      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
      if( IS_LOCK_ERROR(lrc) ){
        pFile->lastErrno = tErrno;
        rc = lrc;
      }
    }
  }
  OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);

#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
    rc = SQLITE_OK;
    reserved=1;
  }
#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  *pResOut = reserved;
  return rc;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** flock() only really support EXCLUSIVE locks.  We track intermediate
** lock states in the sqlite3_file structure, but all locks SHARED or
** above are really EXCLUSIVE locks and exclude all other processes from
** access the file.
**
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
** routine to lower a locking level.
*/
static int flockLock(sqlite3_file *id, int locktype) {
  int rc = SQLITE_OK;
  unixFile *pFile = (unixFile*)id;

  assert( pFile );

  /* if we already have a lock, it is exclusive.  
  ** Just adjust level and punt on outta here. */
  if (pFile->locktype > NO_LOCK) {
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
  
  /* grab an exclusive lock */
  
  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
    int tErrno = errno;
    /* didn't get, must be busy */
    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
    if( IS_LOCK_ERROR(rc) ){
      pFile->lastErrno = tErrno;
    }
  } else {
    /* got it, set the type and return ok */
    pFile->locktype = locktype;
  }
  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
           rc==SQLITE_OK ? "ok" : "failed");
#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
    rc = SQLITE_BUSY;
  }
#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  return rc;
}


/*
** Lower the locking level on file descriptor pFile to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
*/
static int flockUnlock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  
  assert( pFile );
  OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
           pFile->locktype, getpid());
  assert( locktype<=SHARED_LOCK );
  
  /* no-op if possible */
  if( pFile->locktype==locktype ){
    return SQLITE_OK;
  }
  
  /* shared can just be set because we always have an exclusive */
  if (locktype==SHARED_LOCK) {
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
  
  /* no, really, unlock. */
  int rc = flock(pFile->h, LOCK_UN);
  if (rc) {
    int r, tErrno = errno;
    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
    if( IS_LOCK_ERROR(r) ){
      pFile->lastErrno = tErrno;
    }
#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
      r = SQLITE_BUSY;
    }
#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
    
    return r;
  } else {
    pFile->locktype = NO_LOCK;
    return SQLITE_OK;
  }
}

/*
** Close a file.
*/
static int flockClose(sqlite3_file *id) {
  if( id ){
    flockUnlock(id, NO_LOCK);
  }
  return closeUnixFile(id);
}

#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */

/******************* End of the flock lock implementation *********************
******************************************************************************/

/******************************************************************************
************************ Begin Named Semaphore Locking ************************
**
** Named semaphore locking is only supported on VxWorks.
**
** Semaphore locking is like dot-lock and flock in that it really only
** supports EXCLUSIVE locking.  Only a single process can read or write
** the database file at a time.  This reduces potential concurrency, but
** makes the lock implementation much easier.
*/
#if OS_VXWORKS

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  int rc = SQLITE_OK;
  int reserved = 0;
  unixFile *pFile = (unixFile*)id;

  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  
  assert( pFile );

  /* Check if a thread in this process holds such a lock */
  if( pFile->locktype>SHARED_LOCK ){
    reserved = 1;
  }
  
  /* Otherwise see if some other process holds it. */
  if( !reserved ){
    sem_t *pSem = pFile->pOpen->pSem;
    struct stat statBuf;

    if( sem_trywait(pSem)==-1 ){
      int tErrno = errno;
      if( EAGAIN != tErrno ){
        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
        pFile->lastErrno = tErrno;
      } else {
        /* someone else has the lock when we are in NO_LOCK */
        reserved = (pFile->locktype < SHARED_LOCK);
      }
    }else{
      /* we could have it if we want it */
      sem_post(pSem);
    }
  }
  OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);

  *pResOut = reserved;
  return rc;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
** lock states in the sqlite3_file structure, but all locks SHARED or
** above are really EXCLUSIVE locks and exclude all other processes from
** access the file.
**
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
** routine to lower a locking level.
*/
static int semLock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  int fd;
  sem_t *pSem = pFile->pOpen->pSem;
  int rc = SQLITE_OK;

  /* if we already have a lock, it is exclusive.  
  ** Just adjust level and punt on outta here. */
  if (pFile->locktype > NO_LOCK) {
    pFile->locktype = locktype;
    rc = SQLITE_OK;
    goto sem_end_lock;
  }
  
  /* lock semaphore now but bail out when already locked. */
  if( sem_trywait(pSem)==-1 ){
    rc = SQLITE_BUSY;
    goto sem_end_lock;
  }

  /* got it, set the type and return ok */
  pFile->locktype = locktype;

 sem_end_lock:
  return rc;
}

/*
** Lower the locking level on file descriptor pFile to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
*/
static int semUnlock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  sem_t *pSem = pFile->pOpen->pSem;

  assert( pFile );
  assert( pSem );
  OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
	   pFile->locktype, getpid());
  assert( locktype<=SHARED_LOCK );
  
  /* no-op if possible */
  if( pFile->locktype==locktype ){
    return SQLITE_OK;
  }
  
  /* shared can just be set because we always have an exclusive */
  if (locktype==SHARED_LOCK) {
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
  
  /* no, really unlock. */
  if ( sem_post(pSem)==-1 ) {
    int rc, tErrno = errno;
    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
    if( IS_LOCK_ERROR(rc) ){
      pFile->lastErrno = tErrno;
    }
    return rc; 
  }
  pFile->locktype = NO_LOCK;
  return SQLITE_OK;
}

/*
 ** Close a file.
 */
static int semClose(sqlite3_file *id) {
  if( id ){
    unixFile *pFile = (unixFile*)id;
    semUnlock(id, NO_LOCK);
    assert( pFile );
    unixEnterMutex();
    releaseLockInfo(pFile->pLock);
    releaseOpenCnt(pFile->pOpen);
    unixLeaveMutex();
    closeUnixFile(id);
  }
  return SQLITE_OK;
}

#endif /* OS_VXWORKS */
/*
** Named semaphore locking is only available on VxWorks.
**
*************** End of the named semaphore lock implementation ****************
******************************************************************************/


/******************************************************************************
*************************** Begin AFP Locking *********************************
**
** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
** on Apple Macintosh computers - both OS9 and OSX.
**
** Third-party implementations of AFP are available.  But this code here
** only works on OSX.
*/

#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
/*
** The afpLockingContext structure contains all afp lock specific state
*/
typedef struct afpLockingContext afpLockingContext;
struct afpLockingContext {
  unsigned long long sharedByte;
  const char *dbPath;             /* Name of the open file */
};

struct ByteRangeLockPB2
{
  unsigned long long offset;        /* offset to first byte to lock */
  unsigned long long length;        /* nbr of bytes to lock */
  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
  int fd;                           /* file desc to assoc this lock with */
};

#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)

/*
** This is a utility for setting or clearing a bit-range lock on an
** AFP filesystem.
** 
** Return SQLITE_OK on success, SQLITE_BUSY on failure.
*/
static int afpSetLock(
  const char *path,              /* Name of the file to be locked or unlocked */
  unixFile *pFile,               /* Open file descriptor on path */
  unsigned long long offset,     /* First byte to be locked */
  unsigned long long length,     /* Number of bytes to lock */
  int setLockFlag                /* True to set lock.  False to clear lock */
){
  struct ByteRangeLockPB2 pb;
  int err;
  
  pb.unLockFlag = setLockFlag ? 0 : 1;
  pb.startEndFlag = 0;
  pb.offset = offset;
  pb.length = length; 
  pb.fd = pFile->h;
  
  OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
    offset, length);
  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  if ( err==-1 ) {
    int rc;
    int tErrno = errno;
    OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
             path, tErrno, strerror(tErrno));
#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
    rc = SQLITE_BUSY;
#else
    rc = sqliteErrorFromPosixError(tErrno,
                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
    if( IS_LOCK_ERROR(rc) ){
      pFile->lastErrno = tErrno;
    }
    return rc;
  } else {
    return SQLITE_OK;
  }
}

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  int rc = SQLITE_OK;
  int reserved = 0;
  unixFile *pFile = (unixFile*)id;
  
  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  
  assert( pFile );
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  
  /* Check if a thread in this process holds such a lock */
  if( pFile->locktype>SHARED_LOCK ){
    reserved = 1;
  }
  
  /* Otherwise see if some other process holds it.
   */
  if( !reserved ){
    /* lock the RESERVED byte */
    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
    if( SQLITE_OK==lrc ){
      /* if we succeeded in taking the reserved lock, unlock it to restore
      ** the original state */
      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
    } else {
      /* if we failed to get the lock then someone else must have it */
      reserved = 1;
    }
    if( IS_LOCK_ERROR(lrc) ){
      rc=lrc;
    }
  }
  
  OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  
  *pResOut = reserved;
  return rc;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
** routine to lower a locking level.
*/
static int afpLock(sqlite3_file *id, int locktype){
  int rc = SQLITE_OK;
  unixFile *pFile = (unixFile*)id;
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  
  assert( pFile );
  OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
         locktypeName(locktype), locktypeName(pFile->locktype), getpid());

  /* If there is already a lock of this type or more restrictive on the
  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  ** unixEnterMutex() hasn't been called yet.
  */
  if( pFile->locktype>=locktype ){
    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
           locktypeName(locktype));
    return SQLITE_OK;
  }

  /* Make sure the locking sequence is correct
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  
  /* This mutex is needed because pFile->pLock is shared across threads
  */
  unixEnterMutex();

  /* Make sure the current thread owns the pFile.
  */
  rc = transferOwnership(pFile);
  if( rc!=SQLITE_OK ){
    unixLeaveMutex();
    return rc;
  }
    
  /* A PENDING lock is needed before acquiring a SHARED lock and before
  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  ** be released.
  */
  if( locktype==SHARED_LOCK 
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  ){
    int failed;
    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
    if (failed) {
      rc = failed;
      goto afp_end_lock;
    }
  }
  
  /* If control gets to this point, then actually go ahead and make
  ** operating system calls for the specified lock.
  */
  if( locktype==SHARED_LOCK ){
    int lk, lrc1, lrc2;
    int lrc1Errno = 0;
    
    /* Now get the read-lock SHARED_LOCK */
    /* note that the quality of the randomness doesn't matter that much */
    lk = random(); 
    context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
    lrc1 = afpSetLock(context->dbPath, pFile, 
          SHARED_FIRST+context->sharedByte, 1, 1);
    if( IS_LOCK_ERROR(lrc1) ){
      lrc1Errno = pFile->lastErrno;
    }
    /* Drop the temporary PENDING lock */
    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
    
    if( IS_LOCK_ERROR(lrc1) ) {
      pFile->lastErrno = lrc1Errno;
      rc = lrc1;
      goto afp_end_lock;
    } else if( IS_LOCK_ERROR(lrc2) ){
      rc = lrc2;
      goto afp_end_lock;
    } else if( lrc1 != SQLITE_OK ) {
      rc = lrc1;
    } else {
      pFile->locktype = SHARED_LOCK;
      pFile->pOpen->nLock++;
    }
  }else{
    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
    ** assumed that there is a SHARED or greater lock on the file
    ** already.
    */
    int failed = 0;
    assert( 0!=pFile->locktype );
    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
        /* Acquire a RESERVED lock */
        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
    }
    if (!failed && locktype == EXCLUSIVE_LOCK) {
      /* Acquire an EXCLUSIVE lock */
        
      /* Remove the shared lock before trying the range.  we'll need to 
      ** reestablish the shared lock if we can't get the  afpUnlock
      */
      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
                         context->sharedByte, 1, 0)) ){
        int failed2 = SQLITE_OK;
        /* now attemmpt to get the exclusive lock range */
        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
                               SHARED_SIZE, 1);
        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
                       SHARED_FIRST + context->sharedByte, 1, 1)) ){
          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
          ** a critical I/O error
          */
          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
               SQLITE_IOERR_LOCK;
          goto afp_end_lock;
        } 
      }else{
        rc = failed; 
      }
    }
    if( failed ){
      rc = failed;
    }
  }
  
  if( rc==SQLITE_OK ){
    pFile->locktype = locktype;
  }else if( locktype==EXCLUSIVE_LOCK ){
    pFile->locktype = PENDING_LOCK;
  }
  
afp_end_lock:
  unixLeaveMutex();
  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
         rc==SQLITE_OK ? "ok" : "failed");
  return rc;
}

/*
** Lower the locking level on file descriptor pFile to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
*/
static int afpUnlock(sqlite3_file *id, int locktype) {
  int rc = SQLITE_OK;
  unixFile *pFile = (unixFile*)id;
  afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;

  assert( pFile );
  OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
         pFile->locktype, getpid());

  assert( locktype<=SHARED_LOCK );
  if( pFile->locktype<=locktype ){
    return SQLITE_OK;
  }
  if( CHECK_THREADID(pFile) ){
    return SQLITE_MISUSE;
  }
  unixEnterMutex();
  if( pFile->locktype>SHARED_LOCK ){
    
    if( pFile->locktype==EXCLUSIVE_LOCK ){
      rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
      if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
        /* only re-establish the shared lock if necessary */
        int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
        rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
      }
    }
    if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
      rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
    } 
    if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
      rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
    }
  }else if( locktype==NO_LOCK ){
    /* clear the shared lock */
    int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
    rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
  }

  if( rc==SQLITE_OK ){
    if( locktype==NO_LOCK ){
      struct unixOpenCnt *pOpen = pFile->pOpen;
      pOpen->nLock--;
      assert( pOpen->nLock>=0 );
      if( pOpen->nLock==0 ){
        rc = closePendingFds(pFile);
      }
    }
  }
  unixLeaveMutex();
  if( rc==SQLITE_OK ){
    pFile->locktype = locktype;
  }
  return rc;
}

/*
** Close a file & cleanup AFP specific locking context 
*/
static int afpClose(sqlite3_file *id) {
  if( id ){
    unixFile *pFile = (unixFile*)id;
    afpUnlock(id, NO_LOCK);
    unixEnterMutex();
    if( pFile->pOpen && pFile->pOpen->nLock ){
      /* If there are outstanding locks, do not actually close the file just
      ** yet because that would clear those locks.  Instead, add the file
      ** descriptor to pOpen->aPending.  It will be automatically closed when
      ** the last lock is cleared.
      */
      setPendingFd(pFile);
    }
    releaseOpenCnt(pFile->pOpen);
    sqlite3_free(pFile->lockingContext);
    closeUnixFile(id);
    unixLeaveMutex();
  }
  return SQLITE_OK;
}

#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
/*
** The code above is the AFP lock implementation.  The code is specific
** to MacOSX and does not work on other unix platforms.  No alternative
** is available.  If you don't compile for a mac, then the "unix-afp"
** VFS is not available.
**
********************* End of the AFP lock implementation **********************
******************************************************************************/


/******************************************************************************
**************** Non-locking sqlite3_file methods *****************************
**
** The next division contains implementations for all methods of the 
** sqlite3_file object other than the locking methods.  The locking
** methods were defined in divisions above (one locking method per
** division).  Those methods that are common to all locking modes
** are gather together into this division.
*/

/*
** Seek to the offset passed as the second argument, then read cnt 
** bytes into pBuf. Return the number of bytes actually read.
**
** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
** one system to another.  Since SQLite does not define USE_PREAD
** any any form by default, we will not attempt to define _XOPEN_SOURCE.
** See tickets #2741 and #2681.
**
** To avoid stomping the errno value on a failed read the lastErrno value
** is set before returning.
*/
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  int got;
  i64 newOffset;
  TIMER_START;
#if defined(USE_PREAD)
  got = pread(id->h, pBuf, cnt, offset);
  SimulateIOError( got = -1 );
#elif defined(USE_PREAD64)
  got = pread64(id->h, pBuf, cnt, offset);
  SimulateIOError( got = -1 );
#else
  newOffset = lseek(id->h, offset, SEEK_SET);
  SimulateIOError( newOffset-- );
  if( newOffset!=offset ){
    if( newOffset == -1 ){
      ((unixFile*)id)->lastErrno = errno;
    }else{
      ((unixFile*)id)->lastErrno = 0;			
    }
    return -1;
  }
  got = read(id->h, pBuf, cnt);
#endif
  TIMER_END;
  if( got<0 ){
    ((unixFile*)id)->lastErrno = errno;
  }
  OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
  return got;
}

/*
** Read data from a file into a buffer.  Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
static int unixRead(
  sqlite3_file *id, 
  void *pBuf, 
  int amt,
  sqlite3_int64 offset
){
  unixFile *pFile = (unixFile *)id;
  int got;
  assert( id );

  /* If this is a database file (not a journal, master-journal or temp
  ** file), the bytes in the locking range should never be read or written. */
  assert( pFile->pUnused==0
       || offset>=PENDING_BYTE+512
       || offset+amt<=PENDING_BYTE 
  );

  got = seekAndRead(pFile, offset, pBuf, amt);
  if( got==amt ){
    return SQLITE_OK;
  }else if( got<0 ){
    /* lastErrno set by seekAndRead */
    return SQLITE_IOERR_READ;
  }else{
    pFile->lastErrno = 0; /* not a system error */
    /* Unread parts of the buffer must be zero-filled */
    memset(&((char*)pBuf)[got], 0, amt-got);
    return SQLITE_IOERR_SHORT_READ;
  }
}

/*
** Seek to the offset in id->offset then read cnt bytes into pBuf.
** Return the number of bytes actually read.  Update the offset.
**
** To avoid stomping the errno value on a failed write the lastErrno value
** is set before returning.
*/
static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  int got;
  i64 newOffset;
  TIMER_START;
#if defined(USE_PREAD)
  got = pwrite(id->h, pBuf, cnt, offset);
#elif defined(USE_PREAD64)
  got = pwrite64(id->h, pBuf, cnt, offset);
#else
  newOffset = lseek(id->h, offset, SEEK_SET);
  if( newOffset!=offset ){
    if( newOffset == -1 ){
      ((unixFile*)id)->lastErrno = errno;
    }else{
      ((unixFile*)id)->lastErrno = 0;			
    }
    return -1;
  }
  got = write(id->h, pBuf, cnt);
#endif
  TIMER_END;
  if( got<0 ){
    ((unixFile*)id)->lastErrno = errno;
  }

  OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
  return got;
}


/*
** Write data from a buffer into a file.  Return SQLITE_OK on success
** or some other error code on failure.
*/
static int unixWrite(
  sqlite3_file *id, 
  const void *pBuf, 
  int amt,
  sqlite3_int64 offset 
){
  unixFile *pFile = (unixFile*)id;
  int wrote = 0;
  assert( id );
  assert( amt>0 );

  /* If this is a database file (not a journal, master-journal or temp
  ** file), the bytes in the locking range should never be read or written. */
  assert( pFile->pUnused==0
       || offset>=PENDING_BYTE+512
       || offset+amt<=PENDING_BYTE 
  );

#ifndef NDEBUG
  /* If we are doing a normal write to a database file (as opposed to
  ** doing a hot-journal rollback or a write to some file other than a
  ** normal database file) then record the fact that the database
  ** has changed.  If the transaction counter is modified, record that
  ** fact too.
  */
  if( pFile->inNormalWrite ){
    pFile->dbUpdate = 1;  /* The database has been modified */
    if( offset<=24 && offset+amt>=27 ){
      int rc;
      char oldCntr[4];
      SimulateIOErrorBenign(1);
      rc = seekAndRead(pFile, 24, oldCntr, 4);
      SimulateIOErrorBenign(0);
      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
        pFile->transCntrChng = 1;  /* The transaction counter has changed */
      }
    }
  }
#endif

  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
    amt -= wrote;
    offset += wrote;
    pBuf = &((char*)pBuf)[wrote];
  }
  SimulateIOError(( wrote=(-1), amt=1 ));
  SimulateDiskfullError(( wrote=0, amt=1 ));
  if( amt>0 ){
    if( wrote<0 ){
      /* lastErrno set by seekAndWrite */
      return SQLITE_IOERR_WRITE;
    }else{
      pFile->lastErrno = 0; /* not a system error */
      return SQLITE_FULL;
    }
  }
  return SQLITE_OK;
}

#ifdef SQLITE_TEST
/*
** Count the number of fullsyncs and normal syncs.  This is used to test
** that syncs and fullsyncs are occurring at the right times.
*/
int sqlite3_sync_count = 0;
int sqlite3_fullsync_count = 0;
#endif

/*
** We do not trust systems to provide a working fdatasync().  Some do.
** Others do no.  To be safe, we will stick with the (slower) fsync().
** If you know that your system does support fdatasync() correctly,
** then simply compile with -Dfdatasync=fdatasync
*/
#if !defined(fdatasync) && !defined(__linux__)
# define fdatasync fsync
#endif

/*
** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
** only available on Mac OS X.  But that could change.
*/
#ifdef F_FULLFSYNC
# define HAVE_FULLFSYNC 1
#else
# define HAVE_FULLFSYNC 0
#endif


/*
** The fsync() system call does not work as advertised on many
** unix systems.  The following procedure is an attempt to make
** it work better.
**
** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
** for testing when we want to run through the test suite quickly.
** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
** or power failure will likely corrupt the database file.
**
** SQLite sets the dataOnly flag if the size of the file is unchanged.
** The idea behind dataOnly is that it should only write the file content
** to disk, not the inode.  We only set dataOnly if the file size is 
** unchanged since the file size is part of the inode.  However, 
** Ted Ts'o tells us that fdatasync() will also write the inode if the
** file size has changed.  The only real difference between fdatasync()
** and fsync(), Ted tells us, is that fdatasync() will not flush the
** inode if the mtime or owner or other inode attributes have changed.
** We only care about the file size, not the other file attributes, so
** as far as SQLite is concerned, an fdatasync() is always adequate.
** So, we always use fdatasync() if it is available, regardless of
** the value of the dataOnly flag.
*/
static int full_fsync(int fd, int fullSync, int dataOnly){
  int rc;

  /* The following "ifdef/elif/else/" block has the same structure as
  ** the one below. It is replicated here solely to avoid cluttering 
  ** up the real code with the UNUSED_PARAMETER() macros.
  */
#ifdef SQLITE_NO_SYNC
  UNUSED_PARAMETER(fd);
  UNUSED_PARAMETER(fullSync);
  UNUSED_PARAMETER(dataOnly);
#elif HAVE_FULLFSYNC
  UNUSED_PARAMETER(dataOnly);
#else
  UNUSED_PARAMETER(fullSync);
  UNUSED_PARAMETER(dataOnly);
#endif

  /* Record the number of times that we do a normal fsync() and 
  ** FULLSYNC.  This is used during testing to verify that this procedure
  ** gets called with the correct arguments.
  */
#ifdef SQLITE_TEST
  if( fullSync ) sqlite3_fullsync_count++;
  sqlite3_sync_count++;
#endif

  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  ** no-op
  */
#ifdef SQLITE_NO_SYNC
  rc = SQLITE_OK;
#elif HAVE_FULLFSYNC
  if( fullSync ){
    rc = fcntl(fd, F_FULLFSYNC, 0);
  }else{
    rc = 1;
  }
  /* If the FULLFSYNC failed, fall back to attempting an fsync().
  ** It shouldn't be possible for fullfsync to fail on the local 
  ** file system (on OSX), so failure indicates that FULLFSYNC
  ** isn't supported for this file system. So, attempt an fsync 
  ** and (for now) ignore the overhead of a superfluous fcntl call.  
  ** It'd be better to detect fullfsync support once and avoid 
  ** the fcntl call every time sync is called.
  */
  if( rc ) rc = fsync(fd);

#else 
  rc = fdatasync(fd);
#if OS_VXWORKS
  if( rc==-1 && errno==ENOTSUP ){
    rc = fsync(fd);
  }
#endif /* OS_VXWORKS */
#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */

  if( OS_VXWORKS && rc!= -1 ){
    rc = 0;
  }
  return rc;
}

/*
** Make sure all writes to a particular file are committed to disk.
**
** If dataOnly==0 then both the file itself and its metadata (file
** size, access time, etc) are synced.  If dataOnly!=0 then only the
** file data is synced.
**
** Under Unix, also make sure that the directory entry for the file
** has been created by fsync-ing the directory that contains the file.
** If we do not do this and we encounter a power failure, the directory
** entry for the journal might not exist after we reboot.  The next
** SQLite to access the file will not know that the journal exists (because
** the directory entry for the journal was never created) and the transaction
** will not roll back - possibly leading to database corruption.
*/
static int unixSync(sqlite3_file *id, int flags){
  int rc;
  unixFile *pFile = (unixFile*)id;

  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;

  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
      || (flags&0x0F)==SQLITE_SYNC_FULL
  );

  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  ** line is to test that doing so does not cause any problems.
  */
  SimulateDiskfullError( return SQLITE_FULL );

  assert( pFile );
  OSTRACE2("SYNC    %-3d\n", pFile->h);
  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  SimulateIOError( rc=1 );
  if( rc ){
    pFile->lastErrno = errno;
    return SQLITE_IOERR_FSYNC;
  }
  if( pFile->dirfd>=0 ){
    int err;
    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
            HAVE_FULLFSYNC, isFullsync);
#ifndef SQLITE_DISABLE_DIRSYNC
    /* The directory sync is only attempted if full_fsync is
    ** turned off or unavailable.  If a full_fsync occurred above,
    ** then the directory sync is superfluous.
    */
    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
       /*
       ** We have received multiple reports of fsync() returning
       ** errors when applied to directories on certain file systems.
       ** A failed directory sync is not a big deal.  So it seems
       ** better to ignore the error.  Ticket #1657
       */
       /* pFile->lastErrno = errno; */
       /* return SQLITE_IOERR; */
    }
#endif
    err = close(pFile->dirfd); /* Only need to sync once, so close the */
    if( err==0 ){              /* directory when we are done */
      pFile->dirfd = -1;
    }else{
      pFile->lastErrno = errno;
      rc = SQLITE_IOERR_DIR_CLOSE;
    }
  }
  return rc;
}

/*
** Truncate an open file to a specified size
*/
static int unixTruncate(sqlite3_file *id, i64 nByte){
  int rc;
  assert( id );
  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  if( rc ){
    ((unixFile*)id)->lastErrno = errno;
    return SQLITE_IOERR_TRUNCATE;
  }else{
    return SQLITE_OK;
  }
}

/*
** Determine the current size of a file in bytes
*/
static int unixFileSize(sqlite3_file *id, i64 *pSize){
  int rc;
  struct stat buf;
  assert( id );
  rc = fstat(((unixFile*)id)->h, &buf);
  SimulateIOError( rc=1 );
  if( rc!=0 ){
    ((unixFile*)id)->lastErrno = errno;
    return SQLITE_IOERR_FSTAT;
  }
  *pSize = buf.st_size;

  /* When opening a zero-size database, the findLockInfo() procedure
  ** writes a single byte into that file in order to work around a bug
  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
  ** layers, we need to report this file size as zero even though it is
  ** really 1.   Ticket #3260.
  */
  if( *pSize==1 ) *pSize = 0;


  return SQLITE_OK;
}

#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
/*
** Handler for proxy-locking file-control verbs.  Defined below in the
** proxying locking division.
*/
static int proxyFileControl(sqlite3_file*,int,void*);
#endif


/*
** Information and control of an open file handle.
*/
static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_FCNTL_LOCKSTATE: {
      *(int*)pArg = ((unixFile*)id)->locktype;
      return SQLITE_OK;
    }
    case SQLITE_LAST_ERRNO: {
      *(int*)pArg = ((unixFile*)id)->lastErrno;
      return SQLITE_OK;
    }
#ifndef NDEBUG
    /* The pager calls this method to signal that it has done
    ** a rollback and that the database is therefore unchanged and
    ** it hence it is OK for the transaction change counter to be
    ** unchanged.
    */
    case SQLITE_FCNTL_DB_UNCHANGED: {
      ((unixFile*)id)->dbUpdate = 0;
      return SQLITE_OK;
    }
#endif
#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
    case SQLITE_SET_LOCKPROXYFILE:
    case SQLITE_GET_LOCKPROXYFILE: {
      return proxyFileControl(id,op,pArg);
    }
#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  }
  return SQLITE_ERROR;
}

/*
** Return the sector size in bytes of the underlying block device for
** the specified file. This is almost always 512 bytes, but may be
** larger for some devices.
**
** SQLite code assumes this function cannot fail. It also assumes that
** if two files are created in the same file-system directory (i.e.
** a database and its journal file) that the sector size will be the
** same for both.
*/
static int unixSectorSize(sqlite3_file *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  return SQLITE_DEFAULT_SECTOR_SIZE;
}

/*
** Return the device characteristics for the file. This is always 0 for unix.
*/
static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  return 0;
}

/*
** Here ends the implementation of all sqlite3_file methods.
**
********************** End sqlite3_file Methods *******************************
******************************************************************************/

/*
** This division contains definitions of sqlite3_io_methods objects that
** implement various file locking strategies.  It also contains definitions
** of "finder" functions.  A finder-function is used to locate the appropriate
** sqlite3_io_methods object for a particular database file.  The pAppData
** field of the sqlite3_vfs VFS objects are initialized to be pointers to
** the correct finder-function for that VFS.
**
** Most finder functions return a pointer to a fixed sqlite3_io_methods
** object.  The only interesting finder-function is autolockIoFinder, which
** looks at the filesystem type and tries to guess the best locking
** strategy from that.
**
** For finder-funtion F, two objects are created:
**
**    (1) The real finder-function named "FImpt()".
**
**    (2) A constant pointer to this function named just "F".
**
**
** A pointer to the F pointer is used as the pAppData value for VFS
** objects.  We have to do this instead of letting pAppData point
** directly at the finder-function since C90 rules prevent a void*
** from be cast into a function pointer.
**
**
** Each instance of this macro generates two objects:
**
**   *  A constant sqlite3_io_methods object call METHOD that has locking
**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
**
**   *  An I/O method finder function called FINDER that returns a pointer
**      to the METHOD object in the previous bullet.
*/
#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
static const sqlite3_io_methods METHOD = {                                   \
   1,                          /* iVersion */                                \
   CLOSE,                      /* xClose */                                  \
   unixRead,                   /* xRead */                                   \
   unixWrite,                  /* xWrite */                                  \
   unixTruncate,               /* xTruncate */                               \
   unixSync,                   /* xSync */                                   \
   unixFileSize,               /* xFileSize */                               \
   LOCK,                       /* xLock */                                   \
   UNLOCK,                     /* xUnlock */                                 \
   CKLOCK,                     /* xCheckReservedLock */                      \
   unixFileControl,            /* xFileControl */                            \
   unixSectorSize,             /* xSectorSize */                             \
   unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
};                                                                           \
static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
  return &METHOD;                                                            \
}                                                                            \
static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
    = FINDER##Impl;

/*
** Here are all of the sqlite3_io_methods objects for each of the
** locking strategies.  Functions that return pointers to these methods
** are also created.
*/
IOMETHODS(
  posixIoFinder,            /* Finder function name */
  posixIoMethods,           /* sqlite3_io_methods object name */
  unixClose,                /* xClose method */
  unixLock,                 /* xLock method */
  unixUnlock,               /* xUnlock method */
  unixCheckReservedLock     /* xCheckReservedLock method */
)
IOMETHODS(
  nolockIoFinder,           /* Finder function name */
  nolockIoMethods,          /* sqlite3_io_methods object name */
  nolockClose,              /* xClose method */
  nolockLock,               /* xLock method */
  nolockUnlock,             /* xUnlock method */
  nolockCheckReservedLock   /* xCheckReservedLock method */
)
IOMETHODS(
  dotlockIoFinder,          /* Finder function name */
  dotlockIoMethods,         /* sqlite3_io_methods object name */
  dotlockClose,             /* xClose method */
  dotlockLock,              /* xLock method */
  dotlockUnlock,            /* xUnlock method */
  dotlockCheckReservedLock  /* xCheckReservedLock method */
)

#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
IOMETHODS(
  flockIoFinder,            /* Finder function name */
  flockIoMethods,           /* sqlite3_io_methods object name */
  flockClose,               /* xClose method */
  flockLock,                /* xLock method */
  flockUnlock,              /* xUnlock method */
  flockCheckReservedLock    /* xCheckReservedLock method */
)
#endif

#if OS_VXWORKS
IOMETHODS(
  semIoFinder,              /* Finder function name */
  semIoMethods,             /* sqlite3_io_methods object name */
  semClose,                 /* xClose method */
  semLock,                  /* xLock method */
  semUnlock,                /* xUnlock method */
  semCheckReservedLock      /* xCheckReservedLock method */
)
#endif

#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
IOMETHODS(
  afpIoFinder,              /* Finder function name */
  afpIoMethods,             /* sqlite3_io_methods object name */
  afpClose,                 /* xClose method */
  afpLock,                  /* xLock method */
  afpUnlock,                /* xUnlock method */
  afpCheckReservedLock      /* xCheckReservedLock method */
)
#endif

/*
** The "Whole File Locking" finder returns the same set of methods as
** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
** flag to force the posix advisory locks to cover the whole file instead
** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
** is useful on NFS-mounted files since it helps NFS to maintain cache
** coherency.  But it is a detriment to other filesystems since it runs
** slower.
*/
static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
  UNUSED_PARAMETER(z);
  p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
  return &posixIoMethods;
}
static const sqlite3_io_methods 
  *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;

/*
** The proxy locking method is a "super-method" in the sense that it
** opens secondary file descriptors for the conch and lock files and
** it uses proxy, dot-file, AFP, and flock() locking methods on those
** secondary files.  For this reason, the division that implements
** proxy locking is located much further down in the file.  But we need
** to go ahead and define the sqlite3_io_methods and finder function
** for proxy locking here.  So we forward declare the I/O methods.
*/
#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
static int proxyClose(sqlite3_file*);
static int proxyLock(sqlite3_file*, int);
static int proxyUnlock(sqlite3_file*, int);
static int proxyCheckReservedLock(sqlite3_file*, int*);
IOMETHODS(
  proxyIoFinder,            /* Finder function name */
  proxyIoMethods,           /* sqlite3_io_methods object name */
  proxyClose,               /* xClose method */
  proxyLock,                /* xLock method */
  proxyUnlock,              /* xUnlock method */
  proxyCheckReservedLock    /* xCheckReservedLock method */
)
#endif


#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
/* 
** This "finder" function attempts to determine the best locking strategy 
** for the database file "filePath".  It then returns the sqlite3_io_methods
** object that implements that strategy.
**
** This is for MacOSX only.
*/
static const sqlite3_io_methods *autolockIoFinderImpl(
  const char *filePath,    /* name of the database file */
  unixFile *pNew           /* open file object for the database file */
){
  static const struct Mapping {
    const char *zFilesystem;              /* Filesystem type name */
    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
  } aMap[] = {
    { "hfs",    &posixIoMethods },
    { "ufs",    &posixIoMethods },
    { "afpfs",  &afpIoMethods },
#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
    { "smbfs",  &afpIoMethods },
#else
    { "smbfs",  &flockIoMethods },
#endif
    { "webdav", &nolockIoMethods },
    { 0, 0 }
  };
  int i;
  struct statfs fsInfo;
  struct flock lockInfo;

  if( !filePath ){
    /* If filePath==NULL that means we are dealing with a transient file
    ** that does not need to be locked. */
    return &nolockIoMethods;
  }
  if( statfs(filePath, &fsInfo) != -1 ){
    if( fsInfo.f_flags & MNT_RDONLY ){
      return &nolockIoMethods;
    }
    for(i=0; aMap[i].zFilesystem; i++){
      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
        return aMap[i].pMethods;
      }
    }
  }

  /* Default case. Handles, amongst others, "nfs".
  ** Test byte-range lock using fcntl(). If the call succeeds, 
  ** assume that the file-system supports POSIX style locks. 
  */
  lockInfo.l_len = 1;
  lockInfo.l_start = 0;
  lockInfo.l_whence = SEEK_SET;
  lockInfo.l_type = F_RDLCK;
  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
    pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
    return &posixIoMethods;
  }else{
    return &dotlockIoMethods;
  }
}
static const sqlite3_io_methods 
  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;

#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */

#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
/* 
** This "finder" function attempts to determine the best locking strategy 
** for the database file "filePath".  It then returns the sqlite3_io_methods
** object that implements that strategy.
**
** This is for VXWorks only.
*/
static const sqlite3_io_methods *autolockIoFinderImpl(
  const char *filePath,    /* name of the database file */
  unixFile *pNew           /* the open file object */
){
  struct flock lockInfo;

  if( !filePath ){
    /* If filePath==NULL that means we are dealing with a transient file
    ** that does not need to be locked. */
    return &nolockIoMethods;
  }

  /* Test if fcntl() is supported and use POSIX style locks.
  ** Otherwise fall back to the named semaphore method.
  */
  lockInfo.l_len = 1;
  lockInfo.l_start = 0;
  lockInfo.l_whence = SEEK_SET;
  lockInfo.l_type = F_RDLCK;
  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
    return &posixIoMethods;
  }else{
    return &semIoMethods;
  }
}
static const sqlite3_io_methods 
  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;

#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */

/*
** An abstract type for a pointer to a IO method finder function:
*/
typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);


/****************************************************************************
**************************** sqlite3_vfs methods ****************************
**
** This division contains the implementation of methods on the
** sqlite3_vfs object.
*/

/*
** Initialize the contents of the unixFile structure pointed to by pId.
*/
static int fillInUnixFile(
  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
  int h,                  /* Open file descriptor of file being opened */
  int dirfd,              /* Directory file descriptor */
  sqlite3_file *pId,      /* Write to the unixFile structure here */
  const char *zFilename,  /* Name of the file being opened */
  int noLock,             /* Omit locking if true */
  int isDelete            /* Delete on close if true */
){
  const sqlite3_io_methods *pLockingStyle;
  unixFile *pNew = (unixFile *)pId;
  int rc = SQLITE_OK;

  assert( pNew->pLock==NULL );
  assert( pNew->pOpen==NULL );

  /* Parameter isDelete is only used on vxworks. Express this explicitly 
  ** here to prevent compiler warnings about unused parameters.
  */
  UNUSED_PARAMETER(isDelete);

  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
  pNew->h = h;
  pNew->dirfd = dirfd;
  SET_THREADID(pNew);
  pNew->fileFlags = 0;

#if OS_VXWORKS
  pNew->pId = vxworksFindFileId(zFilename);
  if( pNew->pId==0 ){
    noLock = 1;
    rc = SQLITE_NOMEM;
  }
#endif

  if( noLock ){
    pLockingStyle = &nolockIoMethods;
  }else{
    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
#if SQLITE_ENABLE_LOCKING_STYLE
    /* Cache zFilename in the locking context (AFP and dotlock override) for
    ** proxyLock activation is possible (remote proxy is based on db name)
    ** zFilename remains valid until file is closed, to support */
    pNew->lockingContext = (void*)zFilename;
#endif
  }

  if( pLockingStyle == &posixIoMethods ){
    unixEnterMutex();
    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
    if( rc!=SQLITE_OK ){
      /* If an error occured in findLockInfo(), close the file descriptor
      ** immediately, before releasing the mutex. findLockInfo() may fail
      ** in two scenarios:
      **
      **   (a) A call to fstat() failed.
      **   (b) A malloc failed.
      **
      ** Scenario (b) may only occur if the process is holding no other
      ** file descriptors open on the same file. If there were other file
      ** descriptors on this file, then no malloc would be required by
      ** findLockInfo(). If this is the case, it is quite safe to close
      ** handle h - as it is guaranteed that no posix locks will be released
      ** by doing so.
      **
      ** If scenario (a) caused the error then things are not so safe. The
      ** implicit assumption here is that if fstat() fails, things are in
      ** such bad shape that dropping a lock or two doesn't matter much.
      */
      close(h);
      h = -1;
    }
    unixLeaveMutex();
  }

#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  else if( pLockingStyle == &afpIoMethods ){
    /* AFP locking uses the file path so it needs to be included in
    ** the afpLockingContext.
    */
    afpLockingContext *pCtx;
    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
    if( pCtx==0 ){
      rc = SQLITE_NOMEM;
    }else{
      /* NB: zFilename exists and remains valid until the file is closed
      ** according to requirement F11141.  So we do not need to make a
      ** copy of the filename. */
      pCtx->dbPath = zFilename;
      srandomdev();
      unixEnterMutex();
      rc = findLockInfo(pNew, NULL, &pNew->pOpen);
      unixLeaveMutex();        
    }
  }
#endif

  else if( pLockingStyle == &dotlockIoMethods ){
    /* Dotfile locking uses the file path so it needs to be included in
    ** the dotlockLockingContext 
    */
    char *zLockFile;
    int nFilename;
    nFilename = (int)strlen(zFilename) + 6;
    zLockFile = (char *)sqlite3_malloc(nFilename);
    if( zLockFile==0 ){
      rc = SQLITE_NOMEM;
    }else{
      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
    }
    pNew->lockingContext = zLockFile;
  }

#if OS_VXWORKS
  else if( pLockingStyle == &semIoMethods ){
    /* Named semaphore locking uses the file path so it needs to be
    ** included in the semLockingContext
    */
    unixEnterMutex();
    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
    if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
      char *zSemName = pNew->pOpen->aSemName;
      int n;
      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
                       pNew->pId->zCanonicalName);
      for( n=1; zSemName[n]; n++ )
        if( zSemName[n]=='/' ) zSemName[n] = '_';
      pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
      if( pNew->pOpen->pSem == SEM_FAILED ){
        rc = SQLITE_NOMEM;
        pNew->pOpen->aSemName[0] = '\0';
      }
    }
    unixLeaveMutex();
  }
#endif
  
  pNew->lastErrno = 0;
#if OS_VXWORKS
  if( rc!=SQLITE_OK ){
    unlink(zFilename);
    isDelete = 0;
  }
  pNew->isDelete = isDelete;
#endif
  if( rc!=SQLITE_OK ){
    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
    if( h>=0 ) close(h);
  }else{
    pNew->pMethod = pLockingStyle;
    OpenCounter(+1);
  }
  return rc;
}

/*
** Open a file descriptor to the directory containing file zFilename.
** If successful, *pFd is set to the opened file descriptor and
** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
** value.
**
** If SQLITE_OK is returned, the caller is responsible for closing
** the file descriptor *pFd using close().
*/
static int openDirectory(const char *zFilename, int *pFd){
  int ii;
  int fd = -1;
  char zDirname[MAX_PATHNAME+1];

  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  if( ii>0 ){
    zDirname[ii] = '\0';
    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
    if( fd>=0 ){
#ifdef FD_CLOEXEC
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
#endif
      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
    }
  }
  *pFd = fd;
  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
}

/*
** Create a temporary file name in zBuf.  zBuf must be allocated
** by the calling process and must be big enough to hold at least
** pVfs->mxPathname bytes.
*/
static int getTempname(int nBuf, char *zBuf){
  static const char *azDirs[] = {
     0,
     0,
     "/var/tmp",
     "/usr/tmp",
     "/tmp",
     ".",
  };
  static const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  unsigned int i, j;
  struct stat buf;
  const char *zDir = ".";

  /* It's odd to simulate an io-error here, but really this is just
  ** using the io-error infrastructure to test that SQLite handles this
  ** function failing. 
  */
  SimulateIOError( return SQLITE_IOERR );

  azDirs[0] = sqlite3_temp_directory;
  if (NULL == azDirs[1]) {
    azDirs[1] = getenv("TMPDIR");
  }
  
  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
    if( azDirs[i]==0 ) continue;
    if( stat(azDirs[i], &buf) ) continue;
    if( !S_ISDIR(buf.st_mode) ) continue;
    if( access(azDirs[i], 07) ) continue;
    zDir = azDirs[i];
    break;
  }

  /* Check that the output buffer is large enough for the temporary file 
  ** name. If it is not, return SQLITE_ERROR.
  */
  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
    return SQLITE_ERROR;
  }

  do{
    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
    j = (int)strlen(zBuf);
    sqlite3_randomness(15, &zBuf[j]);
    for(i=0; i<15; i++, j++){
      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
    }
    zBuf[j] = 0;
  }while( access(zBuf,0)==0 );
  return SQLITE_OK;
}

#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
/*
** Routine to transform a unixFile into a proxy-locking unixFile.
** Implementation in the proxy-lock division, but used by unixOpen()
** if SQLITE_PREFER_PROXY_LOCKING is defined.
*/
static int proxyTransformUnixFile(unixFile*, const char*);
#endif

/*
** Search for an unused file descriptor that was opened on the database 
** file (not a journal or master-journal file) identified by pathname
** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
** argument to this function.
**
** Such a file descriptor may exist if a database connection was closed
** but the associated file descriptor could not be closed because some
** other file descriptor open on the same file is holding a file-lock.
** Refer to comments in the unixClose() function and the lengthy comment
** describing "Posix Advisory Locking" at the start of this file for 
** further details. Also, ticket #4018.
**
** If a suitable file descriptor is found, then it is returned. If no
** such file descriptor is located, -1 is returned.
*/
static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  UnixUnusedFd *pUnused = 0;

  /* Do not search for an unused file descriptor on vxworks. Not because
  ** vxworks would not benefit from the change (it might, we're not sure),
  ** but because no way to test it is currently available. It is better 
  ** not to risk breaking vxworks support for the sake of such an obscure 
  ** feature.  */
#if !OS_VXWORKS
  struct stat sStat;                   /* Results of stat() call */

  /* A stat() call may fail for various reasons. If this happens, it is
  ** almost certain that an open() call on the same path will also fail.
  ** For this reason, if an error occurs in the stat() call here, it is
  ** ignored and -1 is returned. The caller will try to open a new file
  ** descriptor on the same path, fail, and return an error to SQLite.
  **
  ** Even if a subsequent open() call does succeed, the consequences of
  ** not searching for a resusable file descriptor are not dire.  */
  if( 0==stat(zPath, &sStat) ){
    struct unixOpenCnt *pO;
    struct unixFileId id;
    id.dev = sStat.st_dev;
    id.ino = sStat.st_ino;

    unixEnterMutex();
    for(pO=openList; pO && memcmp(&id, &pO->fileId, sizeof(id)); pO=pO->pNext);
    if( pO ){
      UnixUnusedFd **pp;
      for(pp=&pO->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
      pUnused = *pp;
      if( pUnused ){
        *pp = pUnused->pNext;
      }
    }
    unixLeaveMutex();
  }
#endif    /* if !OS_VXWORKS */
  return pUnused;
}

/*
** Open the file zPath.
** 
** Previously, the SQLite OS layer used three functions in place of this
** one:
**
**     sqlite3OsOpenReadWrite();
**     sqlite3OsOpenReadOnly();
**     sqlite3OsOpenExclusive();
**
** These calls correspond to the following combinations of flags:
**
**     ReadWrite() ->     (READWRITE | CREATE)
**     ReadOnly()  ->     (READONLY) 
**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
**
** The old OpenExclusive() accepted a boolean argument - "delFlag". If
** true, the file was configured to be automatically deleted when the
** file handle closed. To achieve the same effect using this new 
** interface, add the DELETEONCLOSE flag to those specified above for 
** OpenExclusive().
*/
static int unixOpen(
  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
  const char *zPath,           /* Pathname of file to be opened */
  sqlite3_file *pFile,         /* The file descriptor to be filled in */
  int flags,                   /* Input flags to control the opening */
  int *pOutFlags               /* Output flags returned to SQLite core */
){
  unixFile *p = (unixFile *)pFile;
  int fd = -1;                   /* File descriptor returned by open() */
  int dirfd = -1;                /* Directory file descriptor */
  int openFlags = 0;             /* Flags to pass to open() */
  int eType = flags&0xFFFFFF00;  /* Type of file to open */
  int noLock;                    /* True to omit locking primitives */
  int rc = SQLITE_OK;            /* Function Return Code */

  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
  int isCreate     = (flags & SQLITE_OPEN_CREATE);
  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);

  /* If creating a master or main-file journal, this function will open
  ** a file-descriptor on the directory too. The first time unixSync()
  ** is called the directory file descriptor will be fsync()ed and close()d.
  */
  int isOpenDirectory = (isCreate && 
      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
  );

  /* If argument zPath is a NULL pointer, this function is required to open
  ** a temporary file. Use this buffer to store the file name in.
  */
  char zTmpname[MAX_PATHNAME+1];
  const char *zName = zPath;

  /* Check the following statements are true: 
  **
  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
  **   (b) if CREATE is set, then READWRITE must also be set, and
  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
  */
  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  assert(isCreate==0 || isReadWrite);
  assert(isExclusive==0 || isCreate);
  assert(isDelete==0 || isCreate);

  /* The main DB, main journal, and master journal are never automatically
  ** deleted. Nor are they ever temporary files.  */
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );

  /* Assert that the upper layer has set one of the "file-type" flags. */
  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
       || eType==SQLITE_OPEN_TRANSIENT_DB
  );

  memset(p, 0, sizeof(unixFile));

  if( eType==SQLITE_OPEN_MAIN_DB ){
    UnixUnusedFd *pUnused;
    pUnused = findReusableFd(zName, flags);
    if( pUnused ){
      fd = pUnused->fd;
    }else{
      pUnused = sqlite3_malloc(sizeof(*pUnused));
      if( !pUnused ){
        return SQLITE_NOMEM;
      }
    }
    p->pUnused = pUnused;
  }else if( !zName ){
    /* If zName is NULL, the upper layer is requesting a temp file. */
    assert(isDelete && !isOpenDirectory);
    rc = getTempname(MAX_PATHNAME+1, zTmpname);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    zName = zTmpname;
  }

  /* Determine the value of the flags parameter passed to POSIX function
  ** open(). These must be calculated even if open() is not called, as
  ** they may be stored as part of the file handle and used by the 
  ** 'conch file' locking functions later on.  */
  if( isReadonly )  openFlags |= O_RDONLY;
  if( isReadWrite ) openFlags |= O_RDWR;
  if( isCreate )    openFlags |= O_CREAT;
  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  openFlags |= (O_LARGEFILE|O_BINARY);

  if( fd<0 ){
    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
    fd = open(zName, openFlags, openMode);
    OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
      /* Failed to open the file for read/write access. Try read-only. */
      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
      openFlags &= ~(O_RDWR|O_CREAT);
      flags |= SQLITE_OPEN_READONLY;
      openFlags |= O_RDONLY;
      fd = open(zName, openFlags, openMode);
    }
    if( fd<0 ){
      rc = SQLITE_CANTOPEN;
      goto open_finished;
    }
  }
  assert( fd>=0 );
  if( pOutFlags ){
    *pOutFlags = flags;
  }

  if( p->pUnused ){
    p->pUnused->fd = fd;
    p->pUnused->flags = flags;
  }

  if( isDelete ){
#if OS_VXWORKS
    zPath = zName;
#else
    unlink(zName);
#endif
  }
#if SQLITE_ENABLE_LOCKING_STYLE
  else{
    p->openFlags = openFlags;
  }
#endif

  if( isOpenDirectory ){
    rc = openDirectory(zPath, &dirfd);
    if( rc!=SQLITE_OK ){
      /* It is safe to close fd at this point, because it is guaranteed not
      ** to be open on a database file. If it were open on a database file,
      ** it would not be safe to close as this would release any locks held
      ** on the file by this process.  */
      assert( eType!=SQLITE_OPEN_MAIN_DB );
      close(fd);             /* silently leak if fail, already in error */
      goto open_finished;
    }
  }

#ifdef FD_CLOEXEC
  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
#endif

  noLock = eType!=SQLITE_OPEN_MAIN_DB;

#if SQLITE_PREFER_PROXY_LOCKING
  if( zPath!=NULL && !noLock && pVfs->xOpen ){
    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
    int useProxy = 0;

    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
    ** never use proxy, NULL means use proxy for non-local files only.  */
    if( envforce!=NULL ){
      useProxy = atoi(envforce)>0;
    }else{
      struct statfs fsInfo;
      if( statfs(zPath, &fsInfo) == -1 ){
        /* In theory, the close(fd) call is sub-optimal. If the file opened
        ** with fd is a database file, and there are other connections open
        ** on that file that are currently holding advisory locks on it,
        ** then the call to close() will cancel those locks. In practice,
        ** we're assuming that statfs() doesn't fail very often. At least
        ** not while other file descriptors opened by the same process on
        ** the same file are working.  */
        p->lastErrno = errno;
        if( dirfd>=0 ){
          close(dirfd); /* silently leak if fail, in error */
        }
        close(fd); /* silently leak if fail, in error */
        rc = SQLITE_IOERR_ACCESS;
        goto open_finished;
      }
      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
    }
    if( useProxy ){
      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
      if( rc==SQLITE_OK ){
        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
      }
      goto open_finished;
    }
  }
#endif
  
  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
open_finished:
  if( rc!=SQLITE_OK ){
    sqlite3_free(p->pUnused);
  }
  return rc;
}


/*
** Delete the file at zPath. If the dirSync argument is true, fsync()
** the directory after deleting the file.
*/
static int unixDelete(
  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
  const char *zPath,        /* Name of file to be deleted */
  int dirSync               /* If true, fsync() directory after deleting file */
){
  int rc = SQLITE_OK;
  UNUSED_PARAMETER(NotUsed);
  SimulateIOError(return SQLITE_IOERR_DELETE);
  unlink(zPath);
#ifndef SQLITE_DISABLE_DIRSYNC
  if( dirSync ){
    int fd;
    rc = openDirectory(zPath, &fd);
    if( rc==SQLITE_OK ){
#if OS_VXWORKS
      if( fsync(fd)==-1 )
#else
      if( fsync(fd) )
#endif
      {
        rc = SQLITE_IOERR_DIR_FSYNC;
      }
      if( close(fd)&&!rc ){
        rc = SQLITE_IOERR_DIR_CLOSE;
      }
    }
  }
#endif
  return rc;
}

/*
** Test the existance of or access permissions of file zPath. The
** test performed depends on the value of flags:
**
**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
**
** Otherwise return 0.
*/
static int unixAccess(
  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
  const char *zPath,      /* Path of the file to examine */
  int flags,              /* What do we want to learn about the zPath file? */
  int *pResOut            /* Write result boolean here */
){
  int amode = 0;
  UNUSED_PARAMETER(NotUsed);
  SimulateIOError( return SQLITE_IOERR_ACCESS; );
  switch( flags ){
    case SQLITE_ACCESS_EXISTS:
      amode = F_OK;
      break;
    case SQLITE_ACCESS_READWRITE:
      amode = W_OK|R_OK;
      break;
    case SQLITE_ACCESS_READ:
      amode = R_OK;
      break;

    default:
      assert(!"Invalid flags argument");
  }
  *pResOut = (access(zPath, amode)==0);
  return SQLITE_OK;
}


/*
** Turn a relative pathname into a full pathname. The relative path
** is stored as a nul-terminated string in the buffer pointed to by
** zPath. 
**
** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
** (in this case, MAX_PATHNAME bytes). The full-path is written to
** this buffer before returning.
*/
static int unixFullPathname(
  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
  const char *zPath,            /* Possibly relative input path */
  int nOut,                     /* Size of output buffer in bytes */
  char *zOut                    /* Output buffer */
){

  /* It's odd to simulate an io-error here, but really this is just
  ** using the io-error infrastructure to test that SQLite handles this
  ** function failing. This function could fail if, for example, the
  ** current working directory has been unlinked.
  */
  SimulateIOError( return SQLITE_ERROR );

  assert( pVfs->mxPathname==MAX_PATHNAME );
  UNUSED_PARAMETER(pVfs);

  zOut[nOut-1] = '\0';
  if( zPath[0]=='/' ){
    sqlite3_snprintf(nOut, zOut, "%s", zPath);
  }else{
    int nCwd;
    if( getcwd(zOut, nOut-1)==0 ){
      return SQLITE_CANTOPEN;
    }
    nCwd = (int)strlen(zOut);
    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  }
  return SQLITE_OK;
}


#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
#include <dlfcn.h>
static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  UNUSED_PARAMETER(NotUsed);
  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
}

/*
** SQLite calls this function immediately after a call to unixDlSym() or
** unixDlOpen() fails (returns a null pointer). If a more detailed error
** message is available, it is written to zBufOut. If no error message
** is available, zBufOut is left unmodified and SQLite uses a default
** error message.
*/
static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  char *zErr;
  UNUSED_PARAMETER(NotUsed);
  unixEnterMutex();
  zErr = dlerror();
  if( zErr ){
    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  }
  unixLeaveMutex();
}
static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  /* 
  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  ** cast into a pointer to a function.  And yet the library dlsym() routine
  ** returns a void* which is really a pointer to a function.  So how do we
  ** use dlsym() with -pedantic-errors?
  **
  ** Variable x below is defined to be a pointer to a function taking
  ** parameters void* and const char* and returning a pointer to a function.
  ** We initialize x by assigning it a pointer to the dlsym() function.
  ** (That assignment requires a cast.)  Then we call the function that
  ** x points to.  
  **
  ** This work-around is unlikely to work correctly on any system where
  ** you really cannot cast a function pointer into void*.  But then, on the
  ** other hand, dlsym() will not work on such a system either, so we have
  ** not really lost anything.
  */
  void (*(*x)(void*,const char*))(void);
  UNUSED_PARAMETER(NotUsed);
  x = (void(*(*)(void*,const char*))(void))dlsym;
  return (*x)(p, zSym);
}
static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  UNUSED_PARAMETER(NotUsed);
  dlclose(pHandle);
}
#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  #define unixDlOpen  0
  #define unixDlError 0
  #define unixDlSym   0
  #define unixDlClose 0
#endif

/*
** Write nBuf bytes of random data to the supplied buffer zBuf.
*/
static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  UNUSED_PARAMETER(NotUsed);
  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));

  /* We have to initialize zBuf to prevent valgrind from reporting
  ** errors.  The reports issued by valgrind are incorrect - we would
  ** prefer that the randomness be increased by making use of the
  ** uninitialized space in zBuf - but valgrind errors tend to worry
  ** some users.  Rather than argue, it seems easier just to initialize
  ** the whole array and silence valgrind, even if that means less randomness
  ** in the random seed.
  **
  ** When testing, initializing zBuf[] to zero is all we do.  That means
  ** that we always use the same random number sequence.  This makes the
  ** tests repeatable.
  */
  memset(zBuf, 0, nBuf);
#if !defined(SQLITE_TEST)
  {
    int pid, fd;
    fd = open("/dev/urandom", O_RDONLY);
    if( fd<0 ){
      time_t t;
      time(&t);
      memcpy(zBuf, &t, sizeof(t));
      pid = getpid();
      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
      nBuf = sizeof(t) + sizeof(pid);
    }else{
      nBuf = read(fd, zBuf, nBuf);
      close(fd);
    }
  }
#endif
  return nBuf;
}


/*
** Sleep for a little while.  Return the amount of time slept.
** The argument is the number of microseconds we want to sleep.
** The return value is the number of microseconds of sleep actually
** requested from the underlying operating system, a number which
** might be greater than or equal to the argument, but not less
** than the argument.
*/
static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
#if OS_VXWORKS
  struct timespec sp;

  sp.tv_sec = microseconds / 1000000;
  sp.tv_nsec = (microseconds % 1000000) * 1000;
  nanosleep(&sp, NULL);
  UNUSED_PARAMETER(NotUsed);
  return microseconds;
#elif defined(HAVE_USLEEP) && HAVE_USLEEP
  usleep(microseconds);
  UNUSED_PARAMETER(NotUsed);
  return microseconds;
#else
  int seconds = (microseconds+999999)/1000000;
  sleep(seconds);
  UNUSED_PARAMETER(NotUsed);
  return seconds*1000000;
#endif
}

/*
** The following variable, if set to a non-zero value, is interpreted as
** the number of seconds since 1970 and is used to set the result of
** sqlite3OsCurrentTime() during testing.
*/
#ifdef SQLITE_TEST
int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
#if defined(SQLITE_OMIT_FLOATING_POINT)
  time_t t;
  time(&t);
  *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
#elif defined(NO_GETTOD)
  time_t t;
  time(&t);
  *prNow = t/86400.0 + 2440587.5;
#elif OS_VXWORKS
  struct timespec sNow;
  clock_gettime(CLOCK_REALTIME, &sNow);
  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
#else
  struct timeval sNow;
  gettimeofday(&sNow, 0);
  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
#endif

#ifdef SQLITE_TEST
  if( sqlite3_current_time ){
    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  }
#endif
  UNUSED_PARAMETER(NotUsed);
  return 0;
}

/*
** We added the xGetLastError() method with the intention of providing
** better low-level error messages when operating-system problems come up
** during SQLite operation.  But so far, none of that has been implemented
** in the core.  So this routine is never called.  For now, it is merely
** a place-holder.
*/
static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  UNUSED_PARAMETER(NotUsed);
  UNUSED_PARAMETER(NotUsed2);
  UNUSED_PARAMETER(NotUsed3);
  return 0;
}

/*
************************ End of sqlite3_vfs methods ***************************
******************************************************************************/

/******************************************************************************
************************** Begin Proxy Locking ********************************
**
** Proxy locking is a "uber-locking-method" in this sense:  It uses the
** other locking methods on secondary lock files.  Proxy locking is a
** meta-layer over top of the primitive locking implemented above.  For
** this reason, the division that implements of proxy locking is deferred
** until late in the file (here) after all of the other I/O methods have
** been defined - so that the primitive locking methods are available
** as services to help with the implementation of proxy locking.
**
****
**
** The default locking schemes in SQLite use byte-range locks on the
** database file to coordinate safe, concurrent access by multiple readers
** and writers [http://sqlite.org/lockingv3.html].  The five file locking
** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
** as POSIX read & write locks over fixed set of locations (via fsctl),
** on AFP and SMB only exclusive byte-range locks are available via fsctl
** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
** address in the shared range is taken for a SHARED lock, the entire
** shared range is taken for an EXCLUSIVE lock):
**
**      PENDING_BYTE        0x40000000		   	
**      RESERVED_BYTE       0x40000001
**      SHARED_RANGE        0x40000002 -> 0x40000200
**
** This works well on the local file system, but shows a nearly 100x
** slowdown in read performance on AFP because the AFP client disables
** the read cache when byte-range locks are present.  Enabling the read
** cache exposes a cache coherency problem that is present on all OS X
** supported network file systems.  NFS and AFP both observe the
** close-to-open semantics for ensuring cache coherency
** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
** address the requirements for concurrent database access by multiple
** readers and writers
** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
**
** To address the performance and cache coherency issues, proxy file locking
** changes the way database access is controlled by limiting access to a
** single host at a time and moving file locks off of the database file
** and onto a proxy file on the local file system.  
**
**
** Using proxy locks
** -----------------
**
** C APIs
**
**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
**                       <proxy_path> | ":auto:");
**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
**
**
** SQL pragmas
**
**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
**  PRAGMA [database.]lock_proxy_file
**
** Specifying ":auto:" means that if there is a conch file with a matching
** host ID in it, the proxy path in the conch file will be used, otherwise
** a proxy path based on the user's temp dir
** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
** actual proxy file name is generated from the name and path of the
** database file.  For example:
**
**       For database path "/Users/me/foo.db" 
**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
**
** Once a lock proxy is configured for a database connection, it can not
** be removed, however it may be switched to a different proxy path via
** the above APIs (assuming the conch file is not being held by another
** connection or process). 
**
**
** How proxy locking works
** -----------------------
**
** Proxy file locking relies primarily on two new supporting files: 
**
**   *  conch file to limit access to the database file to a single host
**      at a time
**
**   *  proxy file to act as a proxy for the advisory locks normally
**      taken on the database
**
** The conch file - to use a proxy file, sqlite must first "hold the conch"
** by taking an sqlite-style shared lock on the conch file, reading the
** contents and comparing the host's unique host ID (see below) and lock
** proxy path against the values stored in the conch.  The conch file is
** stored in the same directory as the database file and the file name
** is patterned after the database file name as ".<databasename>-conch".
** If the conch file does not exist, or it's contents do not match the
** host ID and/or proxy path, then the lock is escalated to an exclusive
** lock and the conch file contents is updated with the host ID and proxy
** path and the lock is downgraded to a shared lock again.  If the conch
** is held by another process (with a shared lock), the exclusive lock
** will fail and SQLITE_BUSY is returned.
**
** The proxy file - a single-byte file used for all advisory file locks
** normally taken on the database file.   This allows for safe sharing
** of the database file for multiple readers and writers on the same
** host (the conch ensures that they all use the same local lock file).
**
** There is a third file - the host ID file - used as a persistent record
** of a unique identifier for the host, a 128-byte unique host id file
** in the path defined by the HOSTIDPATH macro (default value is
** /Library/Caches/.com.apple.sqliteConchHostId).
**
** Requesting the lock proxy does not immediately take the conch, it is
** only taken when the first request to lock database file is made.  
** This matches the semantics of the traditional locking behavior, where
** opening a connection to a database file does not take a lock on it.
** The shared lock and an open file descriptor are maintained until 
** the connection to the database is closed. 
**
** The proxy file and the lock file are never deleted so they only need
** to be created the first time they are used.
**
** Configuration options
** ---------------------
**
**  SQLITE_PREFER_PROXY_LOCKING
**
**       Database files accessed on non-local file systems are
**       automatically configured for proxy locking, lock files are
**       named automatically using the same logic as
**       PRAGMA lock_proxy_file=":auto:"
**    
**  SQLITE_PROXY_DEBUG
**
**       Enables the logging of error messages during host id file
**       retrieval and creation
**
**  HOSTIDPATH
**
**       Overrides the default host ID file path location
**
**  LOCKPROXYDIR
**
**       Overrides the default directory used for lock proxy files that
**       are named automatically via the ":auto:" setting
**
**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
**
**       Permissions to use when creating a directory for storing the
**       lock proxy files, only used when LOCKPROXYDIR is not set.
**    
**    
** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
** force proxy locking to be used for every database file opened, and 0
** will force automatic proxy locking to be disabled for all database
** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
*/

/*
** Proxy locking is only available on MacOSX 
*/
#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE

#ifdef SQLITE_TEST
/* simulate multiple hosts by creating unique hostid file paths */
int sqlite3_hostid_num = 0;
#endif

/*
** The proxyLockingContext has the path and file structures for the remote 
** and local proxy files in it
*/
typedef struct proxyLockingContext proxyLockingContext;
struct proxyLockingContext {
  unixFile *conchFile;         /* Open conch file */
  char *conchFilePath;         /* Name of the conch file */
  unixFile *lockProxy;         /* Open proxy lock file */
  char *lockProxyPath;         /* Name of the proxy lock file */
  char *dbPath;                /* Name of the open file */
  int conchHeld;               /* True if the conch is currently held */
  void *oldLockingContext;     /* Original lockingcontext to restore on close */
  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
};

/* HOSTIDLEN and CONCHLEN both include space for the string 
** terminating nul 
*/
#define HOSTIDLEN         128
#define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
#ifndef HOSTIDPATH
# define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
#endif

/* basically a copy of unixRandomness with different
** test behavior built in */
static int proxyGenerateHostID(char *pHostID){
  int pid, fd, len;
  unsigned char *key = (unsigned char *)pHostID;
  
  memset(key, 0, HOSTIDLEN);
  len = 0;
  fd = open("/dev/urandom", O_RDONLY);
  if( fd>=0 ){
    len = read(fd, key, HOSTIDLEN);
    close(fd); /* silently leak the fd if it fails */
  }
  if( len < HOSTIDLEN ){
    time_t t;
    time(&t);
    memcpy(key, &t, sizeof(t));
    pid = getpid();
    memcpy(&key[sizeof(t)], &pid, sizeof(pid));
  }
  
#ifdef MAKE_PRETTY_HOSTID
  {
    int i;
    /* filter the bytes into printable ascii characters and NUL terminate */
    key[(HOSTIDLEN-1)] = 0x00;
    for( i=0; i<(HOSTIDLEN-1); i++ ){
      unsigned char pa = key[i]&0x7F;
      if( pa<0x20 ){
        key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
      }else if( pa==0x7F ){
        key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
      }
    }
  }
#endif
  return SQLITE_OK;
}

/* writes the host id path to path, path should be an pre-allocated buffer
** with enough space for a path 
*/
static void proxyGetHostIDPath(char *path, size_t len){
  strlcpy(path, HOSTIDPATH, len);
#ifdef SQLITE_TEST
  if( sqlite3_hostid_num>0 ){
    char suffix[2] = "1";
    suffix[0] = suffix[0] + sqlite3_hostid_num;
    strlcat(path, suffix, len);
  }
#endif
  OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
}

/* get the host ID from a sqlite hostid file stored in the 
** user-specific tmp directory, create the ID if it's not there already 
*/
static int proxyGetHostID(char *pHostID, int *pError){
  int fd;
  char path[MAXPATHLEN]; 
  size_t len;
  int rc=SQLITE_OK;

  proxyGetHostIDPath(path, MAXPATHLEN);
  /* try to create the host ID file, if it already exists read the contents */
  fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
  if( fd<0 ){
    int err=errno;
		
    if( err!=EEXIST ){
#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
      fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
              path, strerror(err));
#endif
      return SQLITE_PERM;
    }
    /* couldn't create the file, read it instead */
    fd = open(path, O_RDONLY|O_EXCL);
    if( fd<0 ){
#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
      int err = errno;
      fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
              path, strerror(err));
#endif
      return SQLITE_PERM;
    }
    len = pread(fd, pHostID, HOSTIDLEN, 0);
    if( len<0 ){
      *pError = errno;
      rc = SQLITE_IOERR_READ;
    }else if( len<HOSTIDLEN ){
      *pError = 0;
      rc = SQLITE_IOERR_SHORT_READ;
    }
    close(fd); /* silently leak the fd if it fails */
    OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
    return rc;
  }else{
    /* we're creating the host ID file (use a random string of bytes) */
    proxyGenerateHostID(pHostID);
    len = pwrite(fd, pHostID, HOSTIDLEN, 0);
    if( len<0 ){
      *pError = errno;
      rc = SQLITE_IOERR_WRITE;
    }else if( len<HOSTIDLEN ){
      *pError = 0;
      rc = SQLITE_IOERR_WRITE;
    }
    close(fd); /* silently leak the fd if it fails */
    OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
    return rc;
  }
}

static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  int len;
  int dbLen;
  int i;

#ifdef LOCKPROXYDIR
  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
#else
# ifdef _CS_DARWIN_USER_TEMP_DIR
  {
    confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
    len = strlcat(lPath, "sqliteplocks", maxLen);
    if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
      /* if mkdir fails, handle as lock file creation failure */
#  ifdef SQLITE_DEBUG
      int err = errno;
      if( err!=EEXIST ){
        fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
                SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
      }
#  endif
    }else{
      OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
    }
    
  }
# else
  len = strlcpy(lPath, "/tmp/", maxLen);
# endif
#endif

  if( lPath[len-1]!='/' ){
    len = strlcat(lPath, "/", maxLen);
  }
  
  /* transform the db path to a unique cache name */
  dbLen = (int)strlen(dbPath);
  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
    char c = dbPath[i];
    lPath[i+len] = (c=='/')?'_':c;
  }
  lPath[i+len]='\0';
  strlcat(lPath, ":auto:", maxLen);
  return SQLITE_OK;
}

/*
** Create a new VFS file descriptor (stored in memory obtained from
** sqlite3_malloc) and open the file named "path" in the file descriptor.
**
** The caller is responsible not only for closing the file descriptor
** but also for freeing the memory associated with the file descriptor.
*/
static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
  unixFile *pNew;
  int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
  int rc = SQLITE_OK;
  sqlite3_vfs dummyVfs;

  pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
  if( !pNew ){
    return SQLITE_NOMEM;
  }
  memset(pNew, 0, sizeof(unixFile));

  /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
  ** suggest that the file being opened is a "main database". This is
  ** necessary as other file types do not necessarily support locking. It
  ** is better to use unixOpen() instead of opening the file directly with
  ** open(), as unixOpen() sets up the various mechanisms required to
  ** make sure a call to close() does not cause the system to discard
  ** POSIX locks prematurely.
  **
  ** It is important that the xOpen member of the VFS object passed to 
  ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file 
  ** for the proxy-file (creating a potential infinite loop).
  */
  dummyVfs.pAppData = (void*)&autolockIoFinder;
  dummyVfs.xOpen = 0;
  rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
  if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
    pNew->pMethod->xClose((sqlite3_file *)pNew);
    rc = SQLITE_CANTOPEN;
  }

  if( rc!=SQLITE_OK ){
    sqlite3_free(pNew);
    pNew = 0;
  }

  *ppFile = pNew;
  return rc;
}

/* takes the conch by taking a shared lock and read the contents conch, if 
** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
** lockPath means that the lockPath in the conch file will be used if the 
** host IDs match, or a new lock path will be generated automatically 
** and written to the conch file.
*/
static int proxyTakeConch(unixFile *pFile){
  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
  
  if( pCtx->conchHeld>0 ){
    return SQLITE_OK;
  }else{
    unixFile *conchFile = pCtx->conchFile;
    char testValue[CONCHLEN];
    char conchValue[CONCHLEN];
    char lockPath[MAXPATHLEN];
    char *tLockPath = NULL;
    int rc = SQLITE_OK;
    int readRc = SQLITE_OK;
    int syncPerms = 0;

    OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());

    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
    if( rc==SQLITE_OK ){
      int pError = 0;
      memset(testValue, 0, CONCHLEN); /* conch is fixed size */
      rc = proxyGetHostID(testValue, &pError);
      if( (rc&0xff)==SQLITE_IOERR ){
        pFile->lastErrno = pError;
      }
      if( pCtx->lockProxyPath ){
        strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
      }
    }
    if( rc!=SQLITE_OK ){
      goto end_takeconch;
    }
    
    readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
    if( readRc!=SQLITE_IOERR_SHORT_READ ){
      if( readRc!=SQLITE_OK ){
        if( (rc&0xff)==SQLITE_IOERR ){
          pFile->lastErrno = conchFile->lastErrno;
        }
        rc = readRc;
        goto end_takeconch;
      }
      /* if the conch has data compare the contents */
      if( !pCtx->lockProxyPath ){
        /* for auto-named local lock file, just check the host ID and we'll
         ** use the local lock file path that's already in there */
        if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
          tLockPath = (char *)&conchValue[HOSTIDLEN];
          goto end_takeconch;
        }
      }else{
        /* we've got the conch if conchValue matches our path and host ID */
        if( !memcmp(testValue, conchValue, CONCHLEN) ){
          goto end_takeconch;
        }
      }
    }else{
      /* a short read means we're "creating" the conch (even though it could 
      ** have been user-intervention), if we acquire the exclusive lock,
      ** we'll try to match the current on-disk permissions of the database
      */
      syncPerms = 1;
    }
    
    /* either conch was emtpy or didn't match */
    if( !pCtx->lockProxyPath ){
      proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
      tLockPath = lockPath;
      strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
    }
    
    /* update conch with host and path (this will fail if other process
     ** has a shared lock already) */
    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
    if( rc==SQLITE_OK ){
      rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
      if( rc==SQLITE_OK && syncPerms ){
        struct stat buf;
        int err = fstat(pFile->h, &buf);
        if( err==0 ){
          /* try to match the database file permissions, ignore failure */
#ifndef SQLITE_PROXY_DEBUG
          fchmod(conchFile->h, buf.st_mode);
#else
          if( fchmod(conchFile->h, buf.st_mode)!=0 ){
            int code = errno;
            fprintf(stderr, "fchmod %o FAILED with %d %s\n",
                             buf.st_mode, code, strerror(code));
          } else {
            fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
          }
        }else{
          int code = errno;
          fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
                          err, code, strerror(code));
#endif
        }
      }
    }
    conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  
end_takeconch:
    OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
    if( rc==SQLITE_OK && pFile->openFlags ){
      if( pFile->h>=0 ){
#ifdef STRICT_CLOSE_ERROR
        if( close(pFile->h) ){
          pFile->lastErrno = errno;
          return SQLITE_IOERR_CLOSE;
        }
#else
        close(pFile->h); /* silently leak fd if fail */
#endif
      }
      pFile->h = -1;
      int fd = open(pCtx->dbPath, pFile->openFlags,
                    SQLITE_DEFAULT_FILE_PERMISSIONS);
      OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
      if( fd>=0 ){
        pFile->h = fd;
      }else{
        rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
                               during locking */
      }
    }
    if( rc==SQLITE_OK && !pCtx->lockProxy ){
      char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
      /* ACS: Need to make a copy of path sometimes */
      rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
    }
    if( rc==SQLITE_OK ){
      pCtx->conchHeld = 1;

      if( tLockPath ){
        pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
          ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
                     pCtx->lockProxyPath;
        }
      }
    } else {
      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
    }
    OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
    return rc;
  }
}

/*
** If pFile holds a lock on a conch file, then release that lock.
*/
static int proxyReleaseConch(unixFile *pFile){
  int rc;                     /* Subroutine return code */
  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
  unixFile *conchFile;        /* Name of the conch file */

  pCtx = (proxyLockingContext *)pFile->lockingContext;
  conchFile = pCtx->conchFile;
  OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
           getpid());
  pCtx->conchHeld = 0;
  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
           (rc==SQLITE_OK ? "ok" : "failed"));
  return rc;
}

/*
** Given the name of a database file, compute the name of its conch file.
** Store the conch filename in memory obtained from sqlite3_malloc().
** Make *pConchPath point to the new name.  Return SQLITE_OK on success
** or SQLITE_NOMEM if unable to obtain memory.
**
** The caller is responsible for ensuring that the allocated memory
** space is eventually freed.
**
** *pConchPath is set to NULL if a memory allocation error occurs.
*/
static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  int i;                        /* Loop counter */
  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  char *conchPath;              /* buffer in which to construct conch name */

  /* Allocate space for the conch filename and initialize the name to
  ** the name of the original database file. */  
  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  if( conchPath==0 ){
    return SQLITE_NOMEM;
  }
  memcpy(conchPath, dbPath, len+1);
  
  /* now insert a "." before the last / character */
  for( i=(len-1); i>=0; i-- ){
    if( conchPath[i]=='/' ){
      i++;
      break;
    }
  }
  conchPath[i]='.';
  while ( i<len ){
    conchPath[i+1]=dbPath[i];
    i++;
  }

  /* append the "-conch" suffix to the file */
  memcpy(&conchPath[i+1], "-conch", 7);
  assert( (int)strlen(conchPath) == len+7 );

  return SQLITE_OK;
}


/* Takes a fully configured proxy locking-style unix file and switches
** the local lock file path 
*/
static int switchLockProxyPath(unixFile *pFile, const char *path) {
  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  char *oldPath = pCtx->lockProxyPath;
  int rc = SQLITE_OK;

  if( pFile->locktype!=NO_LOCK ){
    return SQLITE_BUSY;
  }  

  /* nothing to do if the path is NULL, :auto: or matches the existing path */
  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
    return SQLITE_OK;
  }else{
    unixFile *lockProxy = pCtx->lockProxy;
    pCtx->lockProxy=NULL;
    pCtx->conchHeld = 0;
    if( lockProxy!=NULL ){
      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
      if( rc ) return rc;
      sqlite3_free(lockProxy);
    }
    sqlite3_free(oldPath);
    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  }
  
  return rc;
}

/*
** pFile is a file that has been opened by a prior xOpen call.  dbPath
** is a string buffer at least MAXPATHLEN+1 characters in size.
**
** This routine find the filename associated with pFile and writes it
** int dbPath.
*/
static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
#if defined(__APPLE__)
  if( pFile->pMethod == &afpIoMethods ){
    /* afp style keeps a reference to the db path in the filePath field 
    ** of the struct */
    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
    strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
  }else
#endif
  if( pFile->pMethod == &dotlockIoMethods ){
    /* dot lock style uses the locking context to store the dot lock
    ** file path */
    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  }else{
    /* all other styles use the locking context to store the db file path */
    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
    strcpy(dbPath, (char *)pFile->lockingContext);
  }
  return SQLITE_OK;
}

/*
** Takes an already filled in unix file and alters it so all file locking 
** will be performed on the local proxy lock file.  The following fields
** are preserved in the locking context so that they can be restored and 
** the unix structure properly cleaned up at close time:
**  ->lockingContext
**  ->pMethod
*/
static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  proxyLockingContext *pCtx;
  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
  char *lockPath=NULL;
  int rc = SQLITE_OK;
  
  if( pFile->locktype!=NO_LOCK ){
    return SQLITE_BUSY;
  }
  proxyGetDbPathForUnixFile(pFile, dbPath);
  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
    lockPath=NULL;
  }else{
    lockPath=(char *)path;
  }
  
  OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
           (lockPath ? lockPath : ":auto:"), getpid());

  pCtx = sqlite3_malloc( sizeof(*pCtx) );
  if( pCtx==0 ){
    return SQLITE_NOMEM;
  }
  memset(pCtx, 0, sizeof(*pCtx));

  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  if( rc==SQLITE_OK ){
    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
  }  
  if( rc==SQLITE_OK && lockPath ){
    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  }

  if( rc==SQLITE_OK ){
    /* all memory is allocated, proxys are created and assigned, 
    ** switch the locking context and pMethod then return.
    */
    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
    pCtx->oldLockingContext = pFile->lockingContext;
    pFile->lockingContext = pCtx;
    pCtx->pOldMethod = pFile->pMethod;
    pFile->pMethod = &proxyIoMethods;
  }else{
    if( pCtx->conchFile ){ 
      rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
      if( rc ) return rc;
      sqlite3_free(pCtx->conchFile);
    }
    sqlite3_free(pCtx->conchFilePath); 
    sqlite3_free(pCtx);
  }
  OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
           (rc==SQLITE_OK ? "ok" : "failed"));
  return rc;
}


/*
** This routine handles sqlite3_file_control() calls that are specific
** to proxy locking.
*/
static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_GET_LOCKPROXYFILE: {
      unixFile *pFile = (unixFile*)id;
      if( pFile->pMethod == &proxyIoMethods ){
        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
        proxyTakeConch(pFile);
        if( pCtx->lockProxyPath ){
          *(const char **)pArg = pCtx->lockProxyPath;
        }else{
          *(const char **)pArg = ":auto: (not held)";
        }
      } else {
        *(const char **)pArg = NULL;
      }
      return SQLITE_OK;
    }
    case SQLITE_SET_LOCKPROXYFILE: {
      unixFile *pFile = (unixFile*)id;
      int rc = SQLITE_OK;
      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
      if( pArg==NULL || (const char *)pArg==0 ){
        if( isProxyStyle ){
          /* turn off proxy locking - not supported */
          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
        }else{
          /* turn off proxy locking - already off - NOOP */
          rc = SQLITE_OK;
        }
      }else{
        const char *proxyPath = (const char *)pArg;
        if( isProxyStyle ){
          proxyLockingContext *pCtx = 
            (proxyLockingContext*)pFile->lockingContext;
          if( !strcmp(pArg, ":auto:") 
           || (pCtx->lockProxyPath &&
               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
          ){
            rc = SQLITE_OK;
          }else{
            rc = switchLockProxyPath(pFile, proxyPath);
          }
        }else{
          /* turn on proxy file locking */
          rc = proxyTransformUnixFile(pFile, proxyPath);
        }
      }
      return rc;
    }
    default: {
      assert( 0 );  /* The call assures that only valid opcodes are sent */
    }
  }
  /*NOTREACHED*/
  return SQLITE_ERROR;
}

/*
** Within this division (the proxying locking implementation) the procedures
** above this point are all utilities.  The lock-related methods of the
** proxy-locking sqlite3_io_method object follow.
*/


/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  unixFile *pFile = (unixFile*)id;
  int rc = proxyTakeConch(pFile);
  if( rc==SQLITE_OK ){
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
    unixFile *proxy = pCtx->lockProxy;
    return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  }
  return rc;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
** routine to lower a locking level.
*/
static int proxyLock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  int rc = proxyTakeConch(pFile);
  if( rc==SQLITE_OK ){
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
    unixFile *proxy = pCtx->lockProxy;
    rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
    pFile->locktype = proxy->locktype;
  }
  return rc;
}


/*
** Lower the locking level on file descriptor pFile to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
*/
static int proxyUnlock(sqlite3_file *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  int rc = proxyTakeConch(pFile);
  if( rc==SQLITE_OK ){
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
    unixFile *proxy = pCtx->lockProxy;
    rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
    pFile->locktype = proxy->locktype;
  }
  return rc;
}

/*
** Close a file that uses proxy locks.
*/
static int proxyClose(sqlite3_file *id) {
  if( id ){
    unixFile *pFile = (unixFile*)id;
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
    unixFile *lockProxy = pCtx->lockProxy;
    unixFile *conchFile = pCtx->conchFile;
    int rc = SQLITE_OK;
    
    if( lockProxy ){
      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
      if( rc ) return rc;
      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
      if( rc ) return rc;
      sqlite3_free(lockProxy);
      pCtx->lockProxy = 0;
    }
    if( conchFile ){
      if( pCtx->conchHeld ){
        rc = proxyReleaseConch(pFile);
        if( rc ) return rc;
      }
      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
      if( rc ) return rc;
      sqlite3_free(conchFile);
    }
    sqlite3_free(pCtx->lockProxyPath);
    sqlite3_free(pCtx->conchFilePath);
    sqlite3_free(pCtx->dbPath);
    /* restore the original locking context and pMethod then close it */
    pFile->lockingContext = pCtx->oldLockingContext;
    pFile->pMethod = pCtx->pOldMethod;
    sqlite3_free(pCtx);
    return pFile->pMethod->xClose(id);
  }
  return SQLITE_OK;
}



#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
/*
** The proxy locking style is intended for use with AFP filesystems.
** And since AFP is only supported on MacOSX, the proxy locking is also
** restricted to MacOSX.
** 
**
******************* End of the proxy lock implementation **********************
******************************************************************************/

/*
** Initialize the operating system interface.
**
** This routine registers all VFS implementations for unix-like operating
** systems.  This routine, and the sqlite3_os_end() routine that follows,
** should be the only routines in this file that are visible from other
** files.
**
** This routine is called once during SQLite initialization and by a
** single thread.  The memory allocation and mutex subsystems have not
** necessarily been initialized when this routine is called, and so they
** should not be used.
*/
int sqlite3_os_init(void){ 
  /* 
  ** The following macro defines an initializer for an sqlite3_vfs object.
  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
  ** to the "finder" function.  (pAppData is a pointer to a pointer because
  ** silly C90 rules prohibit a void* from being cast to a function pointer
  ** and so we have to go through the intermediate pointer to avoid problems
  ** when compiling with -pedantic-errors on GCC.)
  **
  ** The FINDER parameter to this macro is the name of the pointer to the
  ** finder-function.  The finder-function returns a pointer to the
  ** sqlite_io_methods object that implements the desired locking
  ** behaviors.  See the division above that contains the IOMETHODS
  ** macro for addition information on finder-functions.
  **
  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  ** object.  But the "autolockIoFinder" available on MacOSX does a little
  ** more than that; it looks at the filesystem type that hosts the 
  ** database file and tries to choose an locking method appropriate for
  ** that filesystem time.
  */
  #define UNIXVFS(VFSNAME, FINDER) {                        \
    1,                    /* iVersion */                    \
    sizeof(unixFile),     /* szOsFile */                    \
    MAX_PATHNAME,         /* mxPathname */                  \
    0,                    /* pNext */                       \
    VFSNAME,              /* zName */                       \
    (void*)&FINDER,       /* pAppData */                    \
    unixOpen,             /* xOpen */                       \
    unixDelete,           /* xDelete */                     \
    unixAccess,           /* xAccess */                     \
    unixFullPathname,     /* xFullPathname */               \
    unixDlOpen,           /* xDlOpen */                     \
    unixDlError,          /* xDlError */                    \
    unixDlSym,            /* xDlSym */                      \
    unixDlClose,          /* xDlClose */                    \
    unixRandomness,       /* xRandomness */                 \
    unixSleep,            /* xSleep */                      \
    unixCurrentTime,      /* xCurrentTime */                \
    unixGetLastError      /* xGetLastError */               \
  }

  /*
  ** All default VFSes for unix are contained in the following array.
  **
  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  ** by the SQLite core when the VFS is registered.  So the following
  ** array cannot be const.
  */
  static sqlite3_vfs aVfs[] = {
#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
    UNIXVFS("unix",          autolockIoFinder ),
#else
    UNIXVFS("unix",          posixIoFinder ),
#endif
    UNIXVFS("unix-none",     nolockIoFinder ),
    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
    UNIXVFS("unix-wfl",      posixWflIoFinder ),
#if OS_VXWORKS
    UNIXVFS("unix-namedsem", semIoFinder ),
#endif
#if SQLITE_ENABLE_LOCKING_STYLE
    UNIXVFS("unix-posix",    posixIoFinder ),
#if !OS_VXWORKS
    UNIXVFS("unix-flock",    flockIoFinder ),
#endif
#endif
#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
    UNIXVFS("unix-afp",      afpIoFinder ),
    UNIXVFS("unix-proxy",    proxyIoFinder ),
#endif
  };
  unsigned int i;          /* Loop counter */

  /* Register all VFSes defined in the aVfs[] array */
  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
    sqlite3_vfs_register(&aVfs[i], i==0);
  }
  return SQLITE_OK; 
}

/*
** Shutdown the operating system interface.
**
** Some operating systems might need to do some cleanup in this routine,
** to release dynamically allocated objects.  But not on unix.
** This routine is a no-op for unix.
*/
int sqlite3_os_end(void){ 
  return SQLITE_OK; 
}
 
#endif /* SQLITE_OS_UNIX */

Added src/os_win.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to windows.
*/
#include "sqliteInt.h"
#if SQLITE_OS_WIN               /* This file is used for windows only */


/*
** A Note About Memory Allocation:
**
** This driver uses malloc()/free() directly rather than going through
** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
** are designed for use on embedded systems where memory is scarce and
** malloc failures happen frequently.  Win32 does not typically run on
** embedded systems, and when it does the developers normally have bigger
** problems to worry about than running out of memory.  So there is not
** a compelling need to use the wrappers.
**
** But there is a good reason to not use the wrappers.  If we use the
** wrappers then we will get simulated malloc() failures within this
** driver.  And that causes all kinds of problems for our tests.  We
** could enhance SQLite to deal with simulated malloc failures within
** the OS driver, but the code to deal with those failure would not
** be exercised on Linux (which does not need to malloc() in the driver)
** and so we would have difficulty writing coverage tests for that
** code.  Better to leave the code out, we think.
**
** The point of this discussion is as follows:  When creating a new
** OS layer for an embedded system, if you use this file as an example,
** avoid the use of malloc()/free().  Those routines work ok on windows
** desktops but not so well in embedded systems.
*/

#include <winbase.h>

#ifdef __CYGWIN__
# include <sys/cygwin.h>
#endif

/*
** Macros used to determine whether or not to use threads.
*/
#if defined(THREADSAFE) && THREADSAFE
# define SQLITE_W32_THREADS 1
#endif

/*
** Include code that is common to all os_*.c files
*/
#include "os_common.h"

/*
** Some microsoft compilers lack this definition.
*/
#ifndef INVALID_FILE_ATTRIBUTES
# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
#endif

/*
** Determine if we are dealing with WindowsCE - which has a much
** reduced API.
*/
#if SQLITE_OS_WINCE
# define AreFileApisANSI() 1
# define FormatMessageW(a,b,c,d,e,f,g) 0
#endif

/*
** WinCE lacks native support for file locking so we have to fake it
** with some code of our own.
*/
#if SQLITE_OS_WINCE
typedef struct winceLock {
  int nReaders;       /* Number of reader locks obtained */
  BOOL bPending;      /* Indicates a pending lock has been obtained */
  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
} winceLock;
#endif

/*
** The winFile structure is a subclass of sqlite3_file* specific to the win32
** portability layer.
*/
typedef struct winFile winFile;
struct winFile {
  const sqlite3_io_methods *pMethod;/* Must be first */
  HANDLE h;               /* Handle for accessing the file */
  unsigned char locktype; /* Type of lock currently held on this file */
  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
  DWORD lastErrno;        /* The Windows errno from the last I/O error */
  DWORD sectorSize;       /* Sector size of the device file is on */
#if SQLITE_OS_WINCE
  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
  HANDLE hShared;         /* Shared memory segment used for locking */
  winceLock local;        /* Locks obtained by this instance of winFile */
  winceLock *shared;      /* Global shared lock memory for the file  */
#endif
};

/*
** Forward prototypes.
*/
static int getSectorSize(
    sqlite3_vfs *pVfs,
    const char *zRelative     /* UTF-8 file name */
);

/*
** The following variable is (normally) set once and never changes
** thereafter.  It records whether the operating system is Win95
** or WinNT.
**
** 0:   Operating system unknown.
** 1:   Operating system is Win95.
** 2:   Operating system is WinNT.
**
** In order to facilitate testing on a WinNT system, the test fixture
** can manually set this value to 1 to emulate Win98 behavior.
*/
#ifdef SQLITE_TEST
int sqlite3_os_type = 0;
#else
static int sqlite3_os_type = 0;
#endif

/*
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
**
** Here is an interesting observation:  Win95, Win98, and WinME lack
** the LockFileEx() API.  But we can still statically link against that
** API as long as we don't call it when running Win95/98/ME.  A call to
** this routine is used to determine if the host is Win95/98/ME or
** WinNT/2K/XP so that we will know whether or not we can safely call
** the LockFileEx() API.
*/
#if SQLITE_OS_WINCE
# define isNT()  (1)
#else
  static int isNT(void){
    if( sqlite3_os_type==0 ){
      OSVERSIONINFO sInfo;
      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
      GetVersionEx(&sInfo);
      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
    }
    return sqlite3_os_type==2;
  }
#endif /* SQLITE_OS_WINCE */

/*
** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
**
** Space to hold the returned string is obtained from malloc.
*/
static WCHAR *utf8ToUnicode(const char *zFilename){
  int nChar;
  WCHAR *zWideFilename;

  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
  if( zWideFilename==0 ){
    return 0;
  }
  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
  if( nChar==0 ){
    free(zWideFilename);
    zWideFilename = 0;
  }
  return zWideFilename;
}

/*
** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
** obtained from malloc().
*/
static char *unicodeToUtf8(const WCHAR *zWideFilename){
  int nByte;
  char *zFilename;

  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  zFilename = malloc( nByte );
  if( zFilename==0 ){
    return 0;
  }
  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
                              0, 0);
  if( nByte == 0 ){
    free(zFilename);
    zFilename = 0;
  }
  return zFilename;
}

/*
** Convert an ansi string to microsoft unicode, based on the
** current codepage settings for file apis.
** 
** Space to hold the returned string is obtained
** from malloc.
*/
static WCHAR *mbcsToUnicode(const char *zFilename){
  int nByte;
  WCHAR *zMbcsFilename;
  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;

  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
  if( zMbcsFilename==0 ){
    return 0;
  }
  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
  if( nByte==0 ){
    free(zMbcsFilename);
    zMbcsFilename = 0;
  }
  return zMbcsFilename;
}

/*
** Convert microsoft unicode to multibyte character string, based on the
** user's Ansi codepage.
**
** Space to hold the returned string is obtained from
** malloc().
*/
static char *unicodeToMbcs(const WCHAR *zWideFilename){
  int nByte;
  char *zFilename;
  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;

  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  zFilename = malloc( nByte );
  if( zFilename==0 ){
    return 0;
  }
  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
                              0, 0);
  if( nByte == 0 ){
    free(zFilename);
    zFilename = 0;
  }
  return zFilename;
}

/*
** Convert multibyte character string to UTF-8.  Space to hold the
** returned string is obtained from malloc().
*/
char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  char *zFilenameUtf8;
  WCHAR *zTmpWide;

  zTmpWide = mbcsToUnicode(zFilename);
  if( zTmpWide==0 ){
    return 0;
  }
  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  free(zTmpWide);
  return zFilenameUtf8;
}

/*
** Convert UTF-8 to multibyte character string.  Space to hold the 
** returned string is obtained from malloc().
*/
static char *utf8ToMbcs(const char *zFilename){
  char *zFilenameMbcs;
  WCHAR *zTmpWide;

  zTmpWide = utf8ToUnicode(zFilename);
  if( zTmpWide==0 ){
    return 0;
  }
  zFilenameMbcs = unicodeToMbcs(zTmpWide);
  free(zTmpWide);
  return zFilenameMbcs;
}

#if SQLITE_OS_WINCE
/*************************************************************************
** This section contains code for WinCE only.
*/
/*
** WindowsCE does not have a localtime() function.  So create a
** substitute.
*/
#include <time.h>
struct tm *__cdecl localtime(const time_t *t)
{
  static struct tm y;
  FILETIME uTm, lTm;
  SYSTEMTIME pTm;
  sqlite3_int64 t64;
  t64 = *t;
  t64 = (t64 + 11644473600)*10000000;
  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  FileTimeToLocalFileTime(&uTm,&lTm);
  FileTimeToSystemTime(&lTm,&pTm);
  y.tm_year = pTm.wYear - 1900;
  y.tm_mon = pTm.wMonth - 1;
  y.tm_wday = pTm.wDayOfWeek;
  y.tm_mday = pTm.wDay;
  y.tm_hour = pTm.wHour;
  y.tm_min = pTm.wMinute;
  y.tm_sec = pTm.wSecond;
  return &y;
}

/* This will never be called, but defined to make the code compile */
#define GetTempPathA(a,b)

#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)

#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]

/*
** Acquire a lock on the handle h
*/
static void winceMutexAcquire(HANDLE h){
   DWORD dwErr;
   do {
     dwErr = WaitForSingleObject(h, INFINITE);
   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
}
/*
** Release a lock acquired by winceMutexAcquire()
*/
#define winceMutexRelease(h) ReleaseMutex(h)

/*
** Create the mutex and shared memory used for locking in the file
** descriptor pFile
*/
static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
  WCHAR *zTok;
  WCHAR *zName = utf8ToUnicode(zFilename);
  BOOL bInit = TRUE;

  /* Initialize the local lockdata */
  ZeroMemory(&pFile->local, sizeof(pFile->local));

  /* Replace the backslashes from the filename and lowercase it
  ** to derive a mutex name. */
  zTok = CharLowerW(zName);
  for (;*zTok;zTok++){
    if (*zTok == '\\') *zTok = '_';
  }

  /* Create/open the named mutex */
  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  if (!pFile->hMutex){
    pFile->lastErrno = GetLastError();
    free(zName);
    return FALSE;
  }

  /* Acquire the mutex before continuing */
  winceMutexAcquire(pFile->hMutex);
  
  /* Since the names of named mutexes, semaphores, file mappings etc are 
  ** case-sensitive, take advantage of that by uppercasing the mutex name
  ** and using that as the shared filemapping name.
  */
  CharUpperW(zName);
  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
                                       PAGE_READWRITE, 0, sizeof(winceLock),
                                       zName);  

  /* Set a flag that indicates we're the first to create the memory so it 
  ** must be zero-initialized */
  if (GetLastError() == ERROR_ALREADY_EXISTS){
    bInit = FALSE;
  }

  free(zName);

  /* If we succeeded in making the shared memory handle, map it. */
  if (pFile->hShared){
    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
    /* If mapping failed, close the shared memory handle and erase it */
    if (!pFile->shared){
      pFile->lastErrno = GetLastError();
      CloseHandle(pFile->hShared);
      pFile->hShared = NULL;
    }
  }

  /* If shared memory could not be created, then close the mutex and fail */
  if (pFile->hShared == NULL){
    winceMutexRelease(pFile->hMutex);
    CloseHandle(pFile->hMutex);
    pFile->hMutex = NULL;
    return FALSE;
  }
  
  /* Initialize the shared memory if we're supposed to */
  if (bInit) {
    ZeroMemory(pFile->shared, sizeof(winceLock));
  }

  winceMutexRelease(pFile->hMutex);
  return TRUE;
}

/*
** Destroy the part of winFile that deals with wince locks
*/
static void winceDestroyLock(winFile *pFile){
  if (pFile->hMutex){
    /* Acquire the mutex */
    winceMutexAcquire(pFile->hMutex);

    /* The following blocks should probably assert in debug mode, but they
       are to cleanup in case any locks remained open */
    if (pFile->local.nReaders){
      pFile->shared->nReaders --;
    }
    if (pFile->local.bReserved){
      pFile->shared->bReserved = FALSE;
    }
    if (pFile->local.bPending){
      pFile->shared->bPending = FALSE;
    }
    if (pFile->local.bExclusive){
      pFile->shared->bExclusive = FALSE;
    }

    /* De-reference and close our copy of the shared memory handle */
    UnmapViewOfFile(pFile->shared);
    CloseHandle(pFile->hShared);

    /* Done with the mutex */
    winceMutexRelease(pFile->hMutex);    
    CloseHandle(pFile->hMutex);
    pFile->hMutex = NULL;
  }
}

/* 
** An implementation of the LockFile() API of windows for wince
*/
static BOOL winceLockFile(
  HANDLE *phFile,
  DWORD dwFileOffsetLow,
  DWORD dwFileOffsetHigh,
  DWORD nNumberOfBytesToLockLow,
  DWORD nNumberOfBytesToLockHigh
){
  winFile *pFile = HANDLE_TO_WINFILE(phFile);
  BOOL bReturn = FALSE;

  UNUSED_PARAMETER(dwFileOffsetHigh);
  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);

  if (!pFile->hMutex) return TRUE;
  winceMutexAcquire(pFile->hMutex);

  /* Wanting an exclusive lock? */
  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
       pFile->shared->bExclusive = TRUE;
       pFile->local.bExclusive = TRUE;
       bReturn = TRUE;
    }
  }

  /* Want a read-only lock? */
  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
           nNumberOfBytesToLockLow == 1){
    if (pFile->shared->bExclusive == 0){
      pFile->local.nReaders ++;
      if (pFile->local.nReaders == 1){
        pFile->shared->nReaders ++;
      }
      bReturn = TRUE;
    }
  }

  /* Want a pending lock? */
  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
    /* If no pending lock has been acquired, then acquire it */
    if (pFile->shared->bPending == 0) {
      pFile->shared->bPending = TRUE;
      pFile->local.bPending = TRUE;
      bReturn = TRUE;
    }
  }

  /* Want a reserved lock? */
  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
    if (pFile->shared->bReserved == 0) {
      pFile->shared->bReserved = TRUE;
      pFile->local.bReserved = TRUE;
      bReturn = TRUE;
    }
  }

  winceMutexRelease(pFile->hMutex);
  return bReturn;
}

/*
** An implementation of the UnlockFile API of windows for wince
*/
static BOOL winceUnlockFile(
  HANDLE *phFile,
  DWORD dwFileOffsetLow,
  DWORD dwFileOffsetHigh,
  DWORD nNumberOfBytesToUnlockLow,
  DWORD nNumberOfBytesToUnlockHigh
){
  winFile *pFile = HANDLE_TO_WINFILE(phFile);
  BOOL bReturn = FALSE;

  UNUSED_PARAMETER(dwFileOffsetHigh);
  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);

  if (!pFile->hMutex) return TRUE;
  winceMutexAcquire(pFile->hMutex);

  /* Releasing a reader lock or an exclusive lock */
  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
    /* Did we have an exclusive lock? */
    if (pFile->local.bExclusive){
      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
      pFile->local.bExclusive = FALSE;
      pFile->shared->bExclusive = FALSE;
      bReturn = TRUE;
    }

    /* Did we just have a reader lock? */
    else if (pFile->local.nReaders){
      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
      pFile->local.nReaders --;
      if (pFile->local.nReaders == 0)
      {
        pFile->shared->nReaders --;
      }
      bReturn = TRUE;
    }
  }

  /* Releasing a pending lock */
  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
    if (pFile->local.bPending){
      pFile->local.bPending = FALSE;
      pFile->shared->bPending = FALSE;
      bReturn = TRUE;
    }
  }
  /* Releasing a reserved lock */
  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
    if (pFile->local.bReserved) {
      pFile->local.bReserved = FALSE;
      pFile->shared->bReserved = FALSE;
      bReturn = TRUE;
    }
  }

  winceMutexRelease(pFile->hMutex);
  return bReturn;
}

/*
** An implementation of the LockFileEx() API of windows for wince
*/
static BOOL winceLockFileEx(
  HANDLE *phFile,
  DWORD dwFlags,
  DWORD dwReserved,
  DWORD nNumberOfBytesToLockLow,
  DWORD nNumberOfBytesToLockHigh,
  LPOVERLAPPED lpOverlapped
){
  UNUSED_PARAMETER(dwReserved);
  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);

  /* If the caller wants a shared read lock, forward this call
  ** to winceLockFile */
  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
      dwFlags == 1 &&
      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
  }
  return FALSE;
}
/*
** End of the special code for wince
*****************************************************************************/
#endif /* SQLITE_OS_WINCE */

/*****************************************************************************
** The next group of routines implement the I/O methods specified
** by the sqlite3_io_methods object.
******************************************************************************/

/*
** Close a file.
**
** It is reported that an attempt to close a handle might sometimes
** fail.  This is a very unreasonable result, but windows is notorious
** for being unreasonable so I do not doubt that it might happen.  If
** the close fails, we pause for 100 milliseconds and try again.  As
** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
** giving up and returning an error.
*/
#define MX_CLOSE_ATTEMPT 3
static int winClose(sqlite3_file *id){
  int rc, cnt = 0;
  winFile *pFile = (winFile*)id;

  assert( id!=0 );
  OSTRACE2("CLOSE %d\n", pFile->h);
  do{
    rc = CloseHandle(pFile->h);
  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
#if SQLITE_OS_WINCE
#define WINCE_DELETION_ATTEMPTS 3
  winceDestroyLock(pFile);
  if( pFile->zDeleteOnClose ){
    int cnt = 0;
    while(
           DeleteFileW(pFile->zDeleteOnClose)==0
        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
        && cnt++ < WINCE_DELETION_ATTEMPTS
    ){
       Sleep(100);  /* Wait a little before trying again */
    }
    free(pFile->zDeleteOnClose);
  }
#endif
  OpenCounter(-1);
  return rc ? SQLITE_OK : SQLITE_IOERR;
}

/*
** Some microsoft compilers lack this definition.
*/
#ifndef INVALID_SET_FILE_POINTER
# define INVALID_SET_FILE_POINTER ((DWORD)-1)
#endif

/*
** Read data from a file into a buffer.  Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
static int winRead(
  sqlite3_file *id,          /* File to read from */
  void *pBuf,                /* Write content into this buffer */
  int amt,                   /* Number of bytes to read */
  sqlite3_int64 offset       /* Begin reading at this offset */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  winFile *pFile = (winFile*)id;
  DWORD error;
  DWORD got;

  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_READ);
  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
    pFile->lastErrno = error;
    return SQLITE_FULL;
  }
  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
    pFile->lastErrno = GetLastError();
    return SQLITE_IOERR_READ;
  }
  if( got==(DWORD)amt ){
    return SQLITE_OK;
  }else{
    /* Unread parts of the buffer must be zero-filled */
    memset(&((char*)pBuf)[got], 0, amt-got);
    return SQLITE_IOERR_SHORT_READ;
  }
}

/*
** Write data from a buffer into a file.  Return SQLITE_OK on success
** or some other error code on failure.
*/
static int winWrite(
  sqlite3_file *id,         /* File to write into */
  const void *pBuf,         /* The bytes to be written */
  int amt,                  /* Number of bytes to write */
  sqlite3_int64 offset      /* Offset into the file to begin writing at */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  winFile *pFile = (winFile*)id;
  DWORD error;
  DWORD wrote = 0;

  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_WRITE);
  SimulateDiskfullError(return SQLITE_FULL);
  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
    pFile->lastErrno = error;
    return SQLITE_FULL;
  }
  assert( amt>0 );
  while(
     amt>0
     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
     && wrote>0
  ){
    amt -= wrote;
    pBuf = &((char*)pBuf)[wrote];
  }
  if( !rc || amt>(int)wrote ){
    pFile->lastErrno = GetLastError();
    return SQLITE_FULL;
  }
  return SQLITE_OK;
}

/*
** Truncate an open file to a specified size
*/
static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(nByte & 0xffffffff);
  DWORD rc;
  winFile *pFile = (winFile*)id;
  DWORD error;

  assert( id!=0 );
  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
    pFile->lastErrno = error;
    return SQLITE_IOERR_TRUNCATE;
  }
  /* SetEndOfFile will fail if nByte is negative */
  if( !SetEndOfFile(pFile->h) ){
    pFile->lastErrno = GetLastError();
    return SQLITE_IOERR_TRUNCATE;
  }
  return SQLITE_OK;
}

#ifdef SQLITE_TEST
/*
** Count the number of fullsyncs and normal syncs.  This is used to test
** that syncs and fullsyncs are occuring at the right times.
*/
int sqlite3_sync_count = 0;
int sqlite3_fullsync_count = 0;
#endif

/*
** Make sure all writes to a particular file are committed to disk.
*/
static int winSync(sqlite3_file *id, int flags){
#ifndef SQLITE_NO_SYNC
  winFile *pFile = (winFile*)id;

  assert( id!=0 );
  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
#else
  UNUSED_PARAMETER(id);
#endif
#ifndef SQLITE_TEST
  UNUSED_PARAMETER(flags);
#else
  if( flags & SQLITE_SYNC_FULL ){
    sqlite3_fullsync_count++;
  }
  sqlite3_sync_count++;
#endif
  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  ** no-op
  */
#ifdef SQLITE_NO_SYNC
    return SQLITE_OK;
#else
  if( FlushFileBuffers(pFile->h) ){
    return SQLITE_OK;
  }else{
    pFile->lastErrno = GetLastError();
    return SQLITE_IOERR;
  }
#endif
}

/*
** Determine the current size of a file in bytes
*/
static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  DWORD upperBits;
  DWORD lowerBits;
  winFile *pFile = (winFile*)id;
  DWORD error;

  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_FSTAT);
  lowerBits = GetFileSize(pFile->h, &upperBits);
  if(   (lowerBits == INVALID_FILE_SIZE)
     && ((error = GetLastError()) != NO_ERROR) )
  {
    pFile->lastErrno = error;
    return SQLITE_IOERR_FSTAT;
  }
  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  return SQLITE_OK;
}

/*
** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
*/
#ifndef LOCKFILE_FAIL_IMMEDIATELY
# define LOCKFILE_FAIL_IMMEDIATELY 1
#endif

/*
** Acquire a reader lock.
** Different API routines are called depending on whether or not this
** is Win95 or WinNT.
*/
static int getReadLock(winFile *pFile){
  int res;
  if( isNT() ){
    OVERLAPPED ovlp;
    ovlp.Offset = SHARED_FIRST;
    ovlp.OffsetHigh = 0;
    ovlp.hEvent = 0;
    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
                     0, SHARED_SIZE, 0, &ovlp);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
*/
#if SQLITE_OS_WINCE==0
  }else{
    int lk;
    sqlite3_randomness(sizeof(lk), &lk);
    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
#endif
  }
  if( res == 0 ){
    pFile->lastErrno = GetLastError();
  }
  return res;
}

/*
** Undo a readlock
*/
static int unlockReadLock(winFile *pFile){
  int res;
  if( isNT() ){
    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
*/
#if SQLITE_OS_WINCE==0
  }else{
    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
#endif
  }
  if( res == 0 ){
    pFile->lastErrno = GetLastError();
  }
  return res;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  The winUnlock() routine
** erases all locks at once and returns us immediately to locking level 0.
** It is not possible to lower the locking level one step at a time.  You
** must go straight to locking level 0.
*/
static int winLock(sqlite3_file *id, int locktype){
  int rc = SQLITE_OK;    /* Return code from subroutines */
  int res = 1;           /* Result of a windows lock call */
  int newLocktype;       /* Set pFile->locktype to this value before exiting */
  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  winFile *pFile = (winFile*)id;
  DWORD error = NO_ERROR;

  assert( id!=0 );
  OSTRACE5("LOCK %d %d was %d(%d)\n",
          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);

  /* If there is already a lock of this type or more restrictive on the
  ** OsFile, do nothing. Don't use the end_lock: exit path, as
  ** sqlite3OsEnterMutex() hasn't been called yet.
  */
  if( pFile->locktype>=locktype ){
    return SQLITE_OK;
  }

  /* Make sure the locking sequence is correct
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
  ** the PENDING_LOCK byte is temporary.
  */
  newLocktype = pFile->locktype;
  if(   (pFile->locktype==NO_LOCK)
     || (   (locktype==EXCLUSIVE_LOCK)
         && (pFile->locktype==RESERVED_LOCK))
  ){
    int cnt = 3;
    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
      /* Try 3 times to get the pending lock.  The pending lock might be
      ** held by another reader process who will release it momentarily.
      */
      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
      Sleep(1);
    }
    gotPendingLock = res;
    if( !res ){
      error = GetLastError();
    }
  }

  /* Acquire a shared lock
  */
  if( locktype==SHARED_LOCK && res ){
    assert( pFile->locktype==NO_LOCK );
    res = getReadLock(pFile);
    if( res ){
      newLocktype = SHARED_LOCK;
    }else{
      error = GetLastError();
    }
  }

  /* Acquire a RESERVED lock
  */
  if( locktype==RESERVED_LOCK && res ){
    assert( pFile->locktype==SHARED_LOCK );
    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
    if( res ){
      newLocktype = RESERVED_LOCK;
    }else{
      error = GetLastError();
    }
  }

  /* Acquire a PENDING lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    newLocktype = PENDING_LOCK;
    gotPendingLock = 0;
  }

  /* Acquire an EXCLUSIVE lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    assert( pFile->locktype>=SHARED_LOCK );
    res = unlockReadLock(pFile);
    OSTRACE2("unreadlock = %d\n", res);
    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
    if( res ){
      newLocktype = EXCLUSIVE_LOCK;
    }else{
      error = GetLastError();
      OSTRACE2("error-code = %d\n", error);
      getReadLock(pFile);
    }
  }

  /* If we are holding a PENDING lock that ought to be released, then
  ** release it now.
  */
  if( gotPendingLock && locktype==SHARED_LOCK ){
    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  }

  /* Update the state of the lock has held in the file descriptor then
  ** return the appropriate result code.
  */
  if( res ){
    rc = SQLITE_OK;
  }else{
    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
           locktype, newLocktype);
    pFile->lastErrno = error;
    rc = SQLITE_BUSY;
  }
  pFile->locktype = (u8)newLocktype;
  return rc;
}

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero, otherwise zero.
*/
static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  int rc;
  winFile *pFile = (winFile*)id;

  assert( id!=0 );
  if( pFile->locktype>=RESERVED_LOCK ){
    rc = 1;
    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
  }else{
    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
    if( rc ){
      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
    }
    rc = !rc;
    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
  }
  *pResOut = rc;
  return SQLITE_OK;
}

/*
** Lower the locking level on file descriptor id to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
**
** It is not possible for this routine to fail if the second argument
** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
** might return SQLITE_IOERR;
*/
static int winUnlock(sqlite3_file *id, int locktype){
  int type;
  winFile *pFile = (winFile*)id;
  int rc = SQLITE_OK;
  assert( pFile!=0 );
  assert( locktype<=SHARED_LOCK );
  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
          pFile->locktype, pFile->sharedLockByte);
  type = pFile->locktype;
  if( type>=EXCLUSIVE_LOCK ){
    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
      /* This should never happen.  We should always be able to
      ** reacquire the read lock */
      rc = SQLITE_IOERR_UNLOCK;
    }
  }
  if( type>=RESERVED_LOCK ){
    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  }
  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
    unlockReadLock(pFile);
  }
  if( type>=PENDING_LOCK ){
    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  }
  pFile->locktype = (u8)locktype;
  return rc;
}

/*
** Control and query of the open file handle.
*/
static int winFileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_FCNTL_LOCKSTATE: {
      *(int*)pArg = ((winFile*)id)->locktype;
      return SQLITE_OK;
    }
    case SQLITE_LAST_ERRNO: {
      *(int*)pArg = (int)((winFile*)id)->lastErrno;
      return SQLITE_OK;
    }
  }
  return SQLITE_ERROR;
}

/*
** Return the sector size in bytes of the underlying block device for
** the specified file. This is almost always 512 bytes, but may be
** larger for some devices.
**
** SQLite code assumes this function cannot fail. It also assumes that
** if two files are created in the same file-system directory (i.e.
** a database and its journal file) that the sector size will be the
** same for both.
*/
static int winSectorSize(sqlite3_file *id){
  assert( id!=0 );
  return (int)(((winFile*)id)->sectorSize);
}

/*
** Return a vector of device characteristics.
*/
static int winDeviceCharacteristics(sqlite3_file *id){
  UNUSED_PARAMETER(id);
  return 0;
}

/*
** This vector defines all the methods that can operate on an
** sqlite3_file for win32.
*/
static const sqlite3_io_methods winIoMethod = {
  1,                        /* iVersion */
  winClose,
  winRead,
  winWrite,
  winTruncate,
  winSync,
  winFileSize,
  winLock,
  winUnlock,
  winCheckReservedLock,
  winFileControl,
  winSectorSize,
  winDeviceCharacteristics
};

/***************************************************************************
** Here ends the I/O methods that form the sqlite3_io_methods object.
**
** The next block of code implements the VFS methods.
****************************************************************************/

/*
** Convert a UTF-8 filename into whatever form the underlying
** operating system wants filenames in.  Space to hold the result
** is obtained from malloc and must be freed by the calling
** function.
*/
static void *convertUtf8Filename(const char *zFilename){
  void *zConverted = 0;
  if( isNT() ){
    zConverted = utf8ToUnicode(zFilename);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
*/
#if SQLITE_OS_WINCE==0
  }else{
    zConverted = utf8ToMbcs(zFilename);
#endif
  }
  /* caller will handle out of memory */
  return zConverted;
}

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at pVfs->mxPathname characters.
*/
static int getTempname(int nBuf, char *zBuf){
  static char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  size_t i, j;
  char zTempPath[MAX_PATH+1];
  if( sqlite3_temp_directory ){
    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  }else if( isNT() ){
    char *zMulti;
    WCHAR zWidePath[MAX_PATH];
    GetTempPathW(MAX_PATH-30, zWidePath);
    zMulti = unicodeToUtf8(zWidePath);
    if( zMulti ){
      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
      free(zMulti);
    }else{
      return SQLITE_NOMEM;
    }
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    char *zUtf8;
    char zMbcsPath[MAX_PATH];
    GetTempPathA(MAX_PATH-30, zMbcsPath);
    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
    if( zUtf8 ){
      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
      free(zUtf8);
    }else{
      return SQLITE_NOMEM;
    }
#endif
  }
  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
  zTempPath[i] = 0;
  sqlite3_snprintf(nBuf-30, zBuf,
                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  j = sqlite3Strlen30(zBuf);
  sqlite3_randomness(20, &zBuf[j]);
  for(i=0; i<20; i++, j++){
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  }
  zBuf[j] = 0;
  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
  return SQLITE_OK; 
}

/*
** The return value of getLastErrorMsg
** is zero if the error message fits in the buffer, or non-zero
** otherwise (if the message was truncated).
*/
static int getLastErrorMsg(int nBuf, char *zBuf){
  /* FormatMessage returns 0 on failure.  Otherwise it
  ** returns the number of TCHARs written to the output
  ** buffer, excluding the terminating null char.
  */
  DWORD error = GetLastError();
  DWORD dwLen = 0;
  char *zOut = 0;

  if( isNT() ){
    WCHAR *zTempWide = NULL;
    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                           NULL,
                           error,
                           0,
                           (LPWSTR) &zTempWide,
                           0,
                           0);
    if( dwLen > 0 ){
      /* allocate a buffer and convert to UTF8 */
      zOut = unicodeToUtf8(zTempWide);
      /* free the system buffer allocated by FormatMessage */
      LocalFree(zTempWide);
    }
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    char *zTemp = NULL;
    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                           NULL,
                           error,
                           0,
                           (LPSTR) &zTemp,
                           0,
                           0);
    if( dwLen > 0 ){
      /* allocate a buffer and convert to UTF8 */
      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
      /* free the system buffer allocated by FormatMessage */
      LocalFree(zTemp);
    }
#endif
  }
  if( 0 == dwLen ){
    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
  }else{
    /* copy a maximum of nBuf chars to output buffer */
    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
    /* free the UTF8 buffer */
    free(zOut);
  }
  return 0;
}

/*
** Open a file.
*/
static int winOpen(
  sqlite3_vfs *pVfs,        /* Not used */
  const char *zName,        /* Name of the file (UTF-8) */
  sqlite3_file *id,         /* Write the SQLite file handle here */
  int flags,                /* Open mode flags */
  int *pOutFlags            /* Status return flags */
){
  HANDLE h;
  DWORD dwDesiredAccess;
  DWORD dwShareMode;
  DWORD dwCreationDisposition;
  DWORD dwFlagsAndAttributes = 0;
#if SQLITE_OS_WINCE
  int isTemp = 0;
#endif
  winFile *pFile = (winFile*)id;
  void *zConverted;                 /* Filename in OS encoding */
  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */

  assert( id!=0 );
  UNUSED_PARAMETER(pVfs);

  /* If the second argument to this function is NULL, generate a 
  ** temporary file name to use 
  */
  if( !zUtf8Name ){
    int rc = getTempname(MAX_PATH+1, zTmpname);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    zUtf8Name = zTmpname;
  }

  /* Convert the filename to the system encoding. */
  zConverted = convertUtf8Filename(zUtf8Name);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }

  if( flags & SQLITE_OPEN_READWRITE ){
    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  }else{
    dwDesiredAccess = GENERIC_READ;
  }
  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
  ** created. SQLite doesn't use it to indicate "exclusive access" 
  ** as it is usually understood.
  */
  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
  if( flags & SQLITE_OPEN_EXCLUSIVE ){
    /* Creates a new file, only if it does not already exist. */
    /* If the file exists, it fails. */
    dwCreationDisposition = CREATE_NEW;
  }else if( flags & SQLITE_OPEN_CREATE ){
    /* Open existing file, or create if it doesn't exist */
    dwCreationDisposition = OPEN_ALWAYS;
  }else{
    /* Opens a file, only if it exists. */
    dwCreationDisposition = OPEN_EXISTING;
  }
  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
#if SQLITE_OS_WINCE
    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
    isTemp = 1;
#else
    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
                               | FILE_ATTRIBUTE_HIDDEN
                               | FILE_FLAG_DELETE_ON_CLOSE;
#endif
  }else{
    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  }
  /* Reports from the internet are that performance is always
  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
#if SQLITE_OS_WINCE
  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
#endif
  if( isNT() ){
    h = CreateFileW((WCHAR*)zConverted,
       dwDesiredAccess,
       dwShareMode,
       NULL,
       dwCreationDisposition,
       dwFlagsAndAttributes,
       NULL
    );
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    h = CreateFileA((char*)zConverted,
       dwDesiredAccess,
       dwShareMode,
       NULL,
       dwCreationDisposition,
       dwFlagsAndAttributes,
       NULL
    );
#endif
  }
  if( h==INVALID_HANDLE_VALUE ){
    free(zConverted);
    if( flags & SQLITE_OPEN_READWRITE ){
      return winOpen(pVfs, zName, id, 
             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
    }else{
      return SQLITE_CANTOPEN;
    }
  }
  if( pOutFlags ){
    if( flags & SQLITE_OPEN_READWRITE ){
      *pOutFlags = SQLITE_OPEN_READWRITE;
    }else{
      *pOutFlags = SQLITE_OPEN_READONLY;
    }
  }
  memset(pFile, 0, sizeof(*pFile));
  pFile->pMethod = &winIoMethod;
  pFile->h = h;
  pFile->lastErrno = NO_ERROR;
  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
#if SQLITE_OS_WINCE
  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
       && !winceCreateLock(zName, pFile)
  ){
    CloseHandle(h);
    free(zConverted);
    return SQLITE_CANTOPEN;
  }
  if( isTemp ){
    pFile->zDeleteOnClose = zConverted;
  }else
#endif
  {
    free(zConverted);
  }
  OpenCounter(+1);
  return SQLITE_OK;
}

/*
** Delete the named file.
**
** Note that windows does not allow a file to be deleted if some other
** process has it open.  Sometimes a virus scanner or indexing program
** will open a journal file shortly after it is created in order to do
** whatever it does.  While this other process is holding the
** file open, we will be unable to delete it.  To work around this
** problem, we delay 100 milliseconds and try to delete again.  Up
** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
** up and returning an error.
*/
#define MX_DELETION_ATTEMPTS 5
static int winDelete(
  sqlite3_vfs *pVfs,          /* Not used on win32 */
  const char *zFilename,      /* Name of file to delete */
  int syncDir                 /* Not used on win32 */
){
  int cnt = 0;
  DWORD rc;
  DWORD error = 0;
  void *zConverted = convertUtf8Filename(zFilename);
  UNUSED_PARAMETER(pVfs);
  UNUSED_PARAMETER(syncDir);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }
  SimulateIOError(return SQLITE_IOERR_DELETE);
  if( isNT() ){
    do{
      DeleteFileW(zConverted);
    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
           && (++cnt < MX_DELETION_ATTEMPTS)
           && (Sleep(100), 1) );
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    do{
      DeleteFileA(zConverted);
    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
           && (++cnt < MX_DELETION_ATTEMPTS)
           && (Sleep(100), 1) );
#endif
  }
  free(zConverted);
  OSTRACE2("DELETE \"%s\"\n", zFilename);
  return (   (rc == INVALID_FILE_ATTRIBUTES) 
          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
}

/*
** Check the existance and status of a file.
*/
static int winAccess(
  sqlite3_vfs *pVfs,         /* Not used on win32 */
  const char *zFilename,     /* Name of file to check */
  int flags,                 /* Type of test to make on this file */
  int *pResOut               /* OUT: Result */
){
  DWORD attr;
  int rc = 0;
  void *zConverted = convertUtf8Filename(zFilename);
  UNUSED_PARAMETER(pVfs);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }
  if( isNT() ){
    attr = GetFileAttributesW((WCHAR*)zConverted);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    attr = GetFileAttributesA((char*)zConverted);
#endif
  }
  free(zConverted);
  switch( flags ){
    case SQLITE_ACCESS_READ:
    case SQLITE_ACCESS_EXISTS:
      rc = attr!=INVALID_FILE_ATTRIBUTES;
      break;
    case SQLITE_ACCESS_READWRITE:
      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
      break;
    default:
      assert(!"Invalid flags argument");
  }
  *pResOut = rc;
  return SQLITE_OK;
}


/*
** Turn a relative pathname into a full pathname.  Write the full
** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
** bytes in size.
*/
static int winFullPathname(
  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
  const char *zRelative,        /* Possibly relative input path */
  int nFull,                    /* Size of output buffer in bytes */
  char *zFull                   /* Output buffer */
){
  
#if defined(__CYGWIN__)
  UNUSED_PARAMETER(nFull);
  cygwin_conv_to_full_win32_path(zRelative, zFull);
  return SQLITE_OK;
#endif

#if SQLITE_OS_WINCE
  UNUSED_PARAMETER(nFull);
  /* WinCE has no concept of a relative pathname, or so I am told. */
  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
  return SQLITE_OK;
#endif

#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
  int nByte;
  void *zConverted;
  char *zOut;
  UNUSED_PARAMETER(nFull);
  zConverted = convertUtf8Filename(zRelative);
  if( isNT() ){
    WCHAR *zTemp;
    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
    zTemp = malloc( nByte*sizeof(zTemp[0]) );
    if( zTemp==0 ){
      free(zConverted);
      return SQLITE_NOMEM;
    }
    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
    free(zConverted);
    zOut = unicodeToUtf8(zTemp);
    free(zTemp);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    char *zTemp;
    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
    zTemp = malloc( nByte*sizeof(zTemp[0]) );
    if( zTemp==0 ){
      free(zConverted);
      return SQLITE_NOMEM;
    }
    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
    free(zConverted);
    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
    free(zTemp);
#endif
  }
  if( zOut ){
    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
    free(zOut);
    return SQLITE_OK;
  }else{
    return SQLITE_NOMEM;
  }
#endif
}

/*
** Get the sector size of the device used to store
** file.
*/
static int getSectorSize(
    sqlite3_vfs *pVfs,
    const char *zRelative     /* UTF-8 file name */
){
  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  /* GetDiskFreeSpace is not supported under WINCE */
#if SQLITE_OS_WINCE
  UNUSED_PARAMETER(pVfs);
  UNUSED_PARAMETER(zRelative);
#else
  char zFullpath[MAX_PATH+1];
  int rc;
  DWORD dwRet = 0;
  DWORD dwDummy;

  /*
  ** We need to get the full path name of the file
  ** to get the drive letter to look up the sector
  ** size.
  */
  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
  if( rc == SQLITE_OK )
  {
    void *zConverted = convertUtf8Filename(zFullpath);
    if( zConverted ){
      if( isNT() ){
        /* trim path to just drive reference */
        WCHAR *p = zConverted;
        for(;*p;p++){
          if( *p == '\\' ){
            *p = '\0';
            break;
          }
        }
        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
                                  &dwDummy,
                                  &bytesPerSector,
                                  &dwDummy,
                                  &dwDummy);
      }else{
        /* trim path to just drive reference */
        char *p = (char *)zConverted;
        for(;*p;p++){
          if( *p == '\\' ){
            *p = '\0';
            break;
          }
        }
        dwRet = GetDiskFreeSpaceA((char*)zConverted,
                                  &dwDummy,
                                  &bytesPerSector,
                                  &dwDummy,
                                  &dwDummy);
      }
      free(zConverted);
    }
    if( !dwRet ){
      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
    }
  }
#endif
  return (int) bytesPerSector; 
}

#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  HANDLE h;
  void *zConverted = convertUtf8Filename(zFilename);
  UNUSED_PARAMETER(pVfs);
  if( zConverted==0 ){
    return 0;
  }
  if( isNT() ){
    h = LoadLibraryW((WCHAR*)zConverted);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
#if SQLITE_OS_WINCE==0
  }else{
    h = LoadLibraryA((char*)zConverted);
#endif
  }
  free(zConverted);
  return (void*)h;
}
static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  UNUSED_PARAMETER(pVfs);
  getLastErrorMsg(nBuf, zBufOut);
}
void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  UNUSED_PARAMETER(pVfs);
#if SQLITE_OS_WINCE
  /* The GetProcAddressA() routine is only available on wince. */
  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
#else
  /* All other windows platforms expect GetProcAddress() to take
  ** an Ansi string regardless of the _UNICODE setting */
  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
#endif
}
void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  UNUSED_PARAMETER(pVfs);
  FreeLibrary((HANDLE)pHandle);
}
#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  #define winDlOpen  0
  #define winDlError 0
  #define winDlSym   0
  #define winDlClose 0
#endif


/*
** Write up to nBuf bytes of randomness into zBuf.
*/
static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  int n = 0;
  UNUSED_PARAMETER(pVfs);
#if defined(SQLITE_TEST)
  n = nBuf;
  memset(zBuf, 0, nBuf);
#else
  if( sizeof(SYSTEMTIME)<=nBuf-n ){
    SYSTEMTIME x;
    GetSystemTime(&x);
    memcpy(&zBuf[n], &x, sizeof(x));
    n += sizeof(x);
  }
  if( sizeof(DWORD)<=nBuf-n ){
    DWORD pid = GetCurrentProcessId();
    memcpy(&zBuf[n], &pid, sizeof(pid));
    n += sizeof(pid);
  }
  if( sizeof(DWORD)<=nBuf-n ){
    DWORD cnt = GetTickCount();
    memcpy(&zBuf[n], &cnt, sizeof(cnt));
    n += sizeof(cnt);
  }
  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
    LARGE_INTEGER i;
    QueryPerformanceCounter(&i);
    memcpy(&zBuf[n], &i, sizeof(i));
    n += sizeof(i);
  }
#endif
  return n;
}


/*
** Sleep for a little while.  Return the amount of time slept.
*/
static int winSleep(sqlite3_vfs *pVfs, int microsec){
  Sleep((microsec+999)/1000);
  UNUSED_PARAMETER(pVfs);
  return ((microsec+999)/1000)*1000;
}

/*
** The following variable, if set to a non-zero value, becomes the result
** returned from sqlite3OsCurrentTime().  This is used for testing.
*/
#ifdef SQLITE_TEST
int sqlite3_current_time = 0;
#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  FILETIME ft;
  /* FILETIME structure is a 64-bit value representing the number of 
     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
  */
  sqlite3_int64 timeW;   /* Whole days */
  sqlite3_int64 timeF;   /* Fractional Days */

  /* Number of 100-nanosecond intervals in a single day */
  static const sqlite3_int64 ntuPerDay = 
      10000000*(sqlite3_int64)86400;

  /* Number of 100-nanosecond intervals in half of a day */
  static const sqlite3_int64 ntuPerHalfDay = 
      10000000*(sqlite3_int64)43200;

  /* 2^32 - to avoid use of LL and warnings in gcc */
  static const sqlite3_int64 max32BitValue = 
      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;

#if SQLITE_OS_WINCE
  SYSTEMTIME time;
  GetSystemTime(&time);
  /* if SystemTimeToFileTime() fails, it returns zero. */
  if (!SystemTimeToFileTime(&time,&ft)){
    return 1;
  }
#else
  GetSystemTimeAsFileTime( &ft );
#endif
  UNUSED_PARAMETER(pVfs);
  timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
  timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
  timeW = timeW / ntuPerDay;          /* whole days */
  timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
  timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
  timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
  timeF = timeF % ntuPerDay;          /* compute new fractional days */
  *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
#ifdef SQLITE_TEST
  if( sqlite3_current_time ){
    *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
  }
#endif
  return 0;
}

/*
** The idea is that this function works like a combination of
** GetLastError() and FormatMessage() on windows (or errno and
** strerror_r() on unix). After an error is returned by an OS
** function, SQLite calls this function with zBuf pointing to
** a buffer of nBuf bytes. The OS layer should populate the
** buffer with a nul-terminated UTF-8 encoded error message
** describing the last IO error to have occurred within the calling
** thread.
**
** If the error message is too large for the supplied buffer,
** it should be truncated. The return value of xGetLastError
** is zero if the error message fits in the buffer, or non-zero
** otherwise (if the message was truncated). If non-zero is returned,
** then it is not necessary to include the nul-terminator character
** in the output buffer.
**
** Not supplying an error message will have no adverse effect
** on SQLite. It is fine to have an implementation that never
** returns an error message:
**
**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
**     assert(zBuf[0]=='\0');
**     return 0;
**   }
**
** However if an error message is supplied, it will be incorporated
** by sqlite into the error message available to the user using
** sqlite3_errmsg(), possibly making IO errors easier to debug.
*/
static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  UNUSED_PARAMETER(pVfs);
  return getLastErrorMsg(nBuf, zBuf);
}

/*
** Initialize and deinitialize the operating system interface.
*/
int sqlite3_os_init(void){
  static sqlite3_vfs winVfs = {
    1,                 /* iVersion */
    sizeof(winFile),   /* szOsFile */
    MAX_PATH,          /* mxPathname */
    0,                 /* pNext */
    "win32",           /* zName */
    0,                 /* pAppData */
 
    winOpen,           /* xOpen */
    winDelete,         /* xDelete */
    winAccess,         /* xAccess */
    winFullPathname,   /* xFullPathname */
    winDlOpen,         /* xDlOpen */
    winDlError,        /* xDlError */
    winDlSym,          /* xDlSym */
    winDlClose,        /* xDlClose */
    winRandomness,     /* xRandomness */
    winSleep,          /* xSleep */
    winCurrentTime,    /* xCurrentTime */
    winGetLastError    /* xGetLastError */
  };

  sqlite3_vfs_register(&winVfs, 1);
  return SQLITE_OK; 
}
int sqlite3_os_end(void){ 
  return SQLITE_OK;
}

#endif /* SQLITE_OS_WIN */

Added src/pager.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of the page cache subsystem or "pager".
** 
** The pager is used to access a database disk file.  It implements
** atomic commit and rollback through the use of a journal file that
** is separate from the database file.  The pager also implements file
** locking to prevent two processes from writing the same database
** file simultaneously, or one process from reading the database while
** another is writing.
**
** @(#) $Id: pager.c,v 1.629 2009/08/10 17:48:57 drh Exp $
*/
#ifndef SQLITE_OMIT_DISKIO
#include "sqliteInt.h"

/*
** Macros for troubleshooting.  Normally turned off
*/
#if 0
int sqlite3PagerTrace=1;  /* True to enable tracing */
#define sqlite3DebugPrintf printf
#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
#else
#define PAGERTRACE(X)
#endif

/*
** The following two macros are used within the PAGERTRACE() macros above
** to print out file-descriptors. 
**
** PAGERID() takes a pointer to a Pager struct as its argument. The
** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
** struct as its argument.
*/
#define PAGERID(p) ((int)(p->fd))
#define FILEHANDLEID(fd) ((int)fd)

/*
** The page cache as a whole is always in one of the following
** states:
**
**   PAGER_UNLOCK        The page cache is not currently reading or 
**                       writing the database file.  There is no
**                       data held in memory.  This is the initial
**                       state.
**
**   PAGER_SHARED        The page cache is reading the database.
**                       Writing is not permitted.  There can be
**                       multiple readers accessing the same database
**                       file at the same time.
**
**   PAGER_RESERVED      This process has reserved the database for writing
**                       but has not yet made any changes.  Only one process
**                       at a time can reserve the database.  The original
**                       database file has not been modified so other
**                       processes may still be reading the on-disk
**                       database file.
**
**   PAGER_EXCLUSIVE     The page cache is writing the database.
**                       Access is exclusive.  No other processes or
**                       threads can be reading or writing while one
**                       process is writing.
**
**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
**                       after all dirty pages have been written to the
**                       database file and the file has been synced to
**                       disk. All that remains to do is to remove or
**                       truncate the journal file and the transaction 
**                       will be committed.
**
** The page cache comes up in PAGER_UNLOCK.  The first time a
** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
** After all pages have been released using sqlite_page_unref(),
** the state transitions back to PAGER_UNLOCK.  The first time
** that sqlite3PagerWrite() is called, the state transitions to
** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
** called on an outstanding page which means that the pager must
** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
** PAGER_RESERVED means that there is an open rollback journal.
** The transition to PAGER_EXCLUSIVE occurs before any changes
** are made to the database file, though writes to the rollback
** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
*/
#define PAGER_UNLOCK      0
#define PAGER_SHARED      1   /* same as SHARED_LOCK */
#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
#define PAGER_SYNCED      5

/*
** A macro used for invoking the codec if there is one
*/
#ifdef SQLITE_HAS_CODEC
# define CODEC1(P,D,N,X,E) \
    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
# define CODEC2(P,D,N,X,E,O) \
    if( P->xCodec==0 ){ O=(char*)D; }else \
    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
#else
# define CODEC1(P,D,N,X,E)   /* NO-OP */
# define CODEC2(P,D,N,X,E,O) O=(char*)D
#endif

/*
** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
** This could conceivably cause corruption following a power failure on
** such a system. This is currently an undocumented limit.
*/
#define MAX_SECTOR_SIZE 0x10000

/*
** An instance of the following structure is allocated for each active
** savepoint and statement transaction in the system. All such structures
** are stored in the Pager.aSavepoint[] array, which is allocated and
** resized using sqlite3Realloc().
**
** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
** set to 0. If a journal-header is written into the main journal while
** the savepoint is active, then iHdrOffset is set to the byte offset 
** immediately following the last journal record written into the main
** journal before the journal-header. This is required during savepoint
** rollback (see pagerPlaybackSavepoint()).
*/
typedef struct PagerSavepoint PagerSavepoint;
struct PagerSavepoint {
  i64 iOffset;                 /* Starting offset in main journal */
  i64 iHdrOffset;              /* See above */
  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
  Pgno nOrig;                  /* Original number of pages in file */
  Pgno iSubRec;                /* Index of first record in sub-journal */
};

/*
** A open page cache is an instance of the following structure.
**
** errCode
**
**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
**   and is returned as the result of every major pager API call.  The
**   SQLITE_FULL return code is slightly different. It persists only until the
**   next successful rollback is performed on the pager cache. Also,
**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
**   APIs, they may still be used successfully.
**
** dbSizeValid, dbSize, dbOrigSize, dbFileSize
**
**   Managing the size of the database file in pages is a little complicated.
**   The variable Pager.dbSize contains the number of pages that the database
**   image currently contains. As the database image grows or shrinks this
**   variable is updated. The variable Pager.dbFileSize contains the number
**   of pages in the database file. This may be different from Pager.dbSize
**   if some pages have been appended to the database image but not yet written
**   out from the cache to the actual file on disk. Or if the image has been
**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
**   contains the number of pages in the database image when the current
**   transaction was opened. The contents of all three of these variables is
**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
**
**   TODO: Under what conditions is dbSizeValid set? Cleared?
**
** changeCountDone
**
**   This boolean variable is used to make sure that the change-counter 
**   (the 4-byte header field at byte offset 24 of the database file) is 
**   not updated more often than necessary. 
**
**   It is set to true when the change-counter field is updated, which 
**   can only happen if an exclusive lock is held on the database file.
**   It is cleared (set to false) whenever an exclusive lock is 
**   relinquished on the database file. Each time a transaction is committed,
**   The changeCountDone flag is inspected. If it is true, the work of
**   updating the change-counter is omitted for the current transaction.
**
**   This mechanism means that when running in exclusive mode, a connection 
**   need only update the change-counter once, for the first transaction
**   committed.
**
** dbModified
**
**   The dbModified flag is set whenever a database page is dirtied.
**   It is cleared at the end of each transaction.
**
**   It is used when committing or otherwise ending a transaction. If
**   the dbModified flag is clear then less work has to be done.
**
** journalStarted
**
**   This flag is set whenever the the main journal is synced. 
**
**   The point of this flag is that it must be set after the 
**   first journal header in a journal file has been synced to disk.
**   After this has happened, new pages appended to the database 
**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
**   to wait for a journal sync before they can be written out to
**   the database file (see function pager_write()).
**   
** setMaster
**
**   This variable is used to ensure that the master journal file name
**   (if any) is only written into the journal file once.
**
**   When committing a transaction, the master journal file name (if any)
**   may be written into the journal file while the pager is still in
**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
**   then attempts to upgrade to an exclusive lock. If this attempt
**   fails, then SQLITE_BUSY may be returned to the user and the user
**   may attempt to commit the transaction again later (calling
**   CommitPhaseOne() again). This flag is used to ensure that the 
**   master journal name is only written to the journal file the first
**   time CommitPhaseOne() is called.
**
** doNotSync
**
**   This variable is set and cleared by sqlite3PagerWrite().
**
** needSync
**
**   TODO: It might be easier to set this variable in writeJournalHdr()
**   and writeMasterJournal() only. Change its meaning to "unsynced data
**   has been written to the journal".
**
** subjInMemory
**
**   This is a boolean variable. If true, then any required sub-journal
**   is opened as an in-memory journal file. If false, then in-memory
**   sub-journals are only used for in-memory pager files.
*/
struct Pager {
  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
  u8 useJournal;              /* Use a rollback journal on this file */
  u8 noReadlock;              /* Do not bother to obtain readlocks */
  u8 noSync;                  /* Do not sync the journal if true */
  u8 fullSync;                /* Do extra syncs of the journal for robustness */
  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
  u8 tempFile;                /* zFilename is a temporary file */
  u8 readOnly;                /* True for a read-only database */
  u8 memDb;                   /* True to inhibit all file I/O */

  /* The following block contains those class members that are dynamically
  ** modified during normal operations. The other variables in this structure
  ** are either constant throughout the lifetime of the pager, or else
  ** used to store configuration parameters that affect the way the pager 
  ** operates.
  **
  ** The 'state' variable is described in more detail along with the
  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
  ** other variables in this block are described in the comment directly 
  ** above this class definition.
  */
  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
  u8 dbModified;              /* True if there are any changes to the Db */
  u8 needSync;                /* True if an fsync() is needed on the journal */
  u8 journalStarted;          /* True if header of journal is synced */
  u8 changeCountDone;         /* Set after incrementing the change-counter */
  u8 setMaster;               /* True if a m-j name has been written to jrnl */
  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
  u8 dbSizeValid;             /* Set when dbSize is correct */
  u8 subjInMemory;            /* True to use in-memory sub-journals */
  Pgno dbSize;                /* Number of pages in the database */
  Pgno dbOrigSize;            /* dbSize before the current transaction */
  Pgno dbFileSize;            /* Number of pages in the database file */
  int errCode;                /* One of several kinds of errors */
  int nRec;                   /* Pages journalled since last j-header written */
  u32 cksumInit;              /* Quasi-random value added to every checksum */
  u32 nSubRec;                /* Number of records written to sub-journal */
  Bitvec *pInJournal;         /* One bit for each page in the database file */
  sqlite3_file *fd;           /* File descriptor for database */
  sqlite3_file *jfd;          /* File descriptor for main journal */
  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
  i64 journalOff;             /* Current write offset in the journal file */
  i64 journalHdr;             /* Byte offset to previous journal header */
  PagerSavepoint *aSavepoint; /* Array of active savepoints */
  int nSavepoint;             /* Number of elements in aSavepoint[] */
  char dbFileVers[16];        /* Changes whenever database file changes */
  u32 sectorSize;             /* Assumed sector size during rollback */

  u16 nExtra;                 /* Add this many bytes to each in-memory page */
  i16 nReserve;               /* Number of unused bytes at end of each page */
  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
  int pageSize;               /* Number of bytes in a page */
  Pgno mxPgno;                /* Maximum allowed size of the database */
  char *zFilename;            /* Name of the database file */
  char *zJournal;             /* Name of the journal file */
  int (*xBusyHandler)(void*); /* Function to call when busy */
  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
#ifdef SQLITE_TEST
  int nHit, nMiss;            /* Cache hits and missing */
  int nRead, nWrite;          /* Database pages read/written */
#endif
  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
#ifdef SQLITE_HAS_CODEC
  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  void (*xCodecFree)(void*);             /* Destructor for the codec */
  void *pCodec;               /* First argument to xCodec... methods */
#endif
  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
  i64 journalSizeLimit;       /* Size limit for persistent journal files */
  PCache *pPCache;            /* Pointer to page cache object */
  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
};

/*
** The following global variables hold counters used for
** testing purposes only.  These variables do not exist in
** a non-testing build.  These variables are not thread-safe.
*/
#ifdef SQLITE_TEST
int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
# define PAGER_INCR(v)  v++
#else
# define PAGER_INCR(v)
#endif



/*
** Journal files begin with the following magic string.  The data
** was obtained from /dev/random.  It is used only as a sanity check.
**
** Since version 2.8.0, the journal format contains additional sanity
** checking information.  If the power fails while the journal is being
** written, semi-random garbage data might appear in the journal
** file after power is restored.  If an attempt is then made
** to roll the journal back, the database could be corrupted.  The additional
** sanity checking data is an attempt to discover the garbage in the
** journal and ignore it.
**
** The sanity checking information for the new journal format consists
** of a 32-bit checksum on each page of data.  The checksum covers both
** the page number and the pPager->pageSize bytes of data for the page.
** This cksum is initialized to a 32-bit random value that appears in the
** journal file right after the header.  The random initializer is important,
** because garbage data that appears at the end of a journal is likely
** data that was once in other files that have now been deleted.  If the
** garbage data came from an obsolete journal file, the checksums might
** be correct.  But by initializing the checksum to random value which
** is different for every journal, we minimize that risk.
*/
static const unsigned char aJournalMagic[] = {
  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
};

/*
** The size of the of each page record in the journal is given by
** the following macro.
*/
#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)

/*
** The journal header size for this pager. This is usually the same 
** size as a single disk sector. See also setSectorSize().
*/
#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)

/*
** The macro MEMDB is true if we are dealing with an in-memory database.
** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
** the value of MEMDB will be a constant and the compiler will optimize
** out code that would never execute.
*/
#ifdef SQLITE_OMIT_MEMORYDB
# define MEMDB 0
#else
# define MEMDB pPager->memDb
#endif

/*
** The maximum legal page number is (2^31 - 1).
*/
#define PAGER_MAX_PGNO 2147483647

#ifndef NDEBUG 
/*
** Usage:
**
**   assert( assert_pager_state(pPager) );
*/
static int assert_pager_state(Pager *pPager){

  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );

  /* The changeCountDone flag is always set for temp-files */
  assert( pPager->tempFile==0 || pPager->changeCountDone );

  return 1;
}
#endif

/*
** Return true if it is necessary to write page *pPg into the sub-journal.
** A page needs to be written into the sub-journal if there exists one
** or more open savepoints for which:
**
**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
**   * The bit corresponding to the page-number is not set in
**     PagerSavepoint.pInSavepoint.
*/
static int subjRequiresPage(PgHdr *pPg){
  Pgno pgno = pPg->pgno;
  Pager *pPager = pPg->pPager;
  int i;
  for(i=0; i<pPager->nSavepoint; i++){
    PagerSavepoint *p = &pPager->aSavepoint[i];
    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
      return 1;
    }
  }
  return 0;
}

/*
** Return true if the page is already in the journal file.
*/
static int pageInJournal(PgHdr *pPg){
  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
}

/*
** Read a 32-bit integer from the given file descriptor.  Store the integer
** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
** error code is something goes wrong.
**
** All values are stored on disk as big-endian.
*/
static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  unsigned char ac[4];
  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  if( rc==SQLITE_OK ){
    *pRes = sqlite3Get4byte(ac);
  }
  return rc;
}

/*
** Write a 32-bit integer into a string buffer in big-endian byte order.
*/
#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)

/*
** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
** on success or an error code is something goes wrong.
*/
static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  char ac[4];
  put32bits(ac, val);
  return sqlite3OsWrite(fd, ac, 4, offset);
}

/*
** The argument to this macro is a file descriptor (type sqlite3_file*).
** Return 0 if it is not open, or non-zero (but not 1) if it is.
**
** This is so that expressions can be written as:
**
**   if( isOpen(pPager->jfd) ){ ...
**
** instead of
**
**   if( pPager->jfd->pMethods ){ ...
*/
#define isOpen(pFd) ((pFd)->pMethods)

/*
** If file pFd is open, call sqlite3OsUnlock() on it.
*/
static int osUnlock(sqlite3_file *pFd, int eLock){
  if( !isOpen(pFd) ){
    return SQLITE_OK;
  }
  return sqlite3OsUnlock(pFd, eLock);
}

/*
** This function determines whether or not the atomic-write optimization
** can be used with this pager. The optimization can be used if:
**
**  (a) the value returned by OsDeviceCharacteristics() indicates that
**      a database page may be written atomically, and
**  (b) the value returned by OsSectorSize() is less than or equal
**      to the page size.
**
** The optimization is also always enabled for temporary files. It is
** an error to call this function if pPager is opened on an in-memory
** database.
**
** If the optimization cannot be used, 0 is returned. If it can be used,
** then the value returned is the size of the journal file when it
** contains rollback data for exactly one page.
*/
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
static int jrnlBufferSize(Pager *pPager){
  assert( !MEMDB );
  if( !pPager->tempFile ){
    int dc;                           /* Device characteristics */
    int nSector;                      /* Sector size */
    int szPage;                       /* Page size */

    assert( isOpen(pPager->fd) );
    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
    nSector = pPager->sectorSize;
    szPage = pPager->pageSize;

    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
      return 0;
    }
  }

  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
}
#endif

/*
** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
** on the cache using a hash function.  This is used for testing
** and debugging only.
*/
#ifdef SQLITE_CHECK_PAGES
/*
** Return a 32-bit hash of the page data for pPage.
*/
static u32 pager_datahash(int nByte, unsigned char *pData){
  u32 hash = 0;
  int i;
  for(i=0; i<nByte; i++){
    hash = (hash*1039) + pData[i];
  }
  return hash;
}
static u32 pager_pagehash(PgHdr *pPage){
  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
}
static void pager_set_pagehash(PgHdr *pPage){
  pPage->pageHash = pager_pagehash(pPage);
}

/*
** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
** is defined, and NDEBUG is not defined, an assert() statement checks
** that the page is either dirty or still matches the calculated page-hash.
*/
#define CHECK_PAGE(x) checkPage(x)
static void checkPage(PgHdr *pPg){
  Pager *pPager = pPg->pPager;
  assert( !pPg->pageHash || pPager->errCode
      || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
}

#else
#define pager_datahash(X,Y)  0
#define pager_pagehash(X)  0
#define CHECK_PAGE(x)
#endif  /* SQLITE_CHECK_PAGES */

/*
** When this is called the journal file for pager pPager must be open.
** This function attempts to read a master journal file name from the 
** end of the file and, if successful, copies it into memory supplied 
** by the caller. See comments above writeMasterJournal() for the format
** used to store a master journal file name at the end of a journal file.
**
** zMaster must point to a buffer of at least nMaster bytes allocated by
** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
** enough space to write the master journal name). If the master journal
** name in the journal is longer than nMaster bytes (including a
** nul-terminator), then this is handled as if no master journal name
** were present in the journal.
**
** If a master journal file name is present at the end of the journal
** file, then it is copied into the buffer pointed to by zMaster. A
** nul-terminator byte is appended to the buffer following the master
** journal file name.
**
** If it is determined that no master journal file name is present 
** zMaster[0] is set to 0 and SQLITE_OK returned.
**
** If an error occurs while reading from the journal file, an SQLite
** error code is returned.
*/
static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  int rc;                    /* Return code */
  u32 len;                   /* Length in bytes of master journal name */
  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
  u32 cksum;                 /* MJ checksum value read from journal */
  u32 u;                     /* Unsigned loop counter */
  unsigned char aMagic[8];   /* A buffer to hold the magic header */
  zMaster[0] = '\0';

  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   || szJ<16
   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   || len>=nMaster 
   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   || memcmp(aMagic, aJournalMagic, 8)
   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  ){
    return rc;
  }

  /* See if the checksum matches the master journal name */
  for(u=0; u<len; u++){
    cksum -= zMaster[u];
  }
  if( cksum ){
    /* If the checksum doesn't add up, then one or more of the disk sectors
    ** containing the master journal filename is corrupted. This means
    ** definitely roll back, so just return SQLITE_OK and report a (nul)
    ** master-journal filename.
    */
    len = 0;
  }
  zMaster[len] = '\0';
   
  return SQLITE_OK;
}

/*
** Return the offset of the sector boundary at or immediately 
** following the value in pPager->journalOff, assuming a sector 
** size of pPager->sectorSize bytes.
**
** i.e for a sector size of 512:
**
**   Pager.journalOff          Return value
**   ---------------------------------------
**   0                         0
**   512                       512
**   100                       512
**   2000                      2048
** 
*/
static i64 journalHdrOffset(Pager *pPager){
  i64 offset = 0;
  i64 c = pPager->journalOff;
  if( c ){
    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  }
  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  assert( offset>=c );
  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  return offset;
}

/*
** The journal file must be open when this function is called.
**
** This function is a no-op if the journal file has not been written to
** within the current transaction (i.e. if Pager.journalOff==0).
**
** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
** zero the 28-byte header at the start of the journal file. In either case, 
** if the pager is not in no-sync mode, sync the journal file immediately 
** after writing or truncating it.
**
** If Pager.journalSizeLimit is set to a positive, non-zero value, and
** following the truncation or zeroing described above the size of the 
** journal file in bytes is larger than this value, then truncate the
** journal file to Pager.journalSizeLimit bytes. The journal file does
** not need to be synced following this operation.
**
** If an IO error occurs, abandon processing and return the IO error code.
** Otherwise, return SQLITE_OK.
*/
static int zeroJournalHdr(Pager *pPager, int doTruncate){
  int rc = SQLITE_OK;                               /* Return code */
  assert( isOpen(pPager->jfd) );
  if( pPager->journalOff ){
    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */

    IOTRACE(("JZEROHDR %p\n", pPager))
    if( doTruncate || iLimit==0 ){
      rc = sqlite3OsTruncate(pPager->jfd, 0);
    }else{
      static const char zeroHdr[28] = {0};
      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
    }
    if( rc==SQLITE_OK && !pPager->noSync ){
      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
    }

    /* At this point the transaction is committed but the write lock 
    ** is still held on the file. If there is a size limit configured for 
    ** the persistent journal and the journal file currently consumes more
    ** space than that limit allows for, truncate it now. There is no need
    ** to sync the file following this operation.
    */
    if( rc==SQLITE_OK && iLimit>0 ){
      i64 sz;
      rc = sqlite3OsFileSize(pPager->jfd, &sz);
      if( rc==SQLITE_OK && sz>iLimit ){
        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
      }
    }
  }
  return rc;
}

/*
** The journal file must be open when this routine is called. A journal
** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
** current location.
**
** The format for the journal header is as follows:
** - 8 bytes: Magic identifying journal format.
** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
** - 4 bytes: Random number used for page hash.
** - 4 bytes: Initial database page count.
** - 4 bytes: Sector size used by the process that wrote this journal.
** - 4 bytes: Database page size.
** 
** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
*/
static int writeJournalHdr(Pager *pPager){
  int rc = SQLITE_OK;                 /* Return code */
  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
  u32 nWrite;                         /* Bytes of header sector written */
  int ii;                             /* Loop counter */

  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */

  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
    nHeader = JOURNAL_HDR_SZ(pPager);
  }

  /* If there are active savepoints and any of them were created 
  ** since the most recent journal header was written, update the 
  ** PagerSavepoint.iHdrOffset fields now.
  */
  for(ii=0; ii<pPager->nSavepoint; ii++){
    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
    }
  }

  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);

  /* 
  ** Write the nRec Field - the number of page records that follow this
  ** journal header. Normally, zero is written to this value at this time.
  ** After the records are added to the journal (and the journal synced, 
  ** if in full-sync mode), the zero is overwritten with the true number
  ** of records (see syncJournal()).
  **
  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  ** reading the journal this value tells SQLite to assume that the
  ** rest of the journal file contains valid page records. This assumption
  ** is dangerous, as if a failure occurred whilst writing to the journal
  ** file it may contain some garbage data. There are two scenarios
  ** where this risk can be ignored:
  **
  **   * When the pager is in no-sync mode. Corruption can follow a
  **     power failure in this case anyway.
  **
  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  **     that garbage data is never appended to the journal file.
  */
  assert( isOpen(pPager->fd) || pPager->noSync );
  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
  ){
    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  }else{
    memset(zHeader, 0, sizeof(aJournalMagic)+4);
  }

  /* The random check-hash initialiser */ 
  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  /* The initial database size */
  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  /* The assumed sector size for this process */
  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);

  /* The page size */
  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);

  /* Initializing the tail of the buffer is not necessary.  Everything
  ** works find if the following memset() is omitted.  But initializing
  ** the memory prevents valgrind from complaining, so we are willing to
  ** take the performance hit.
  */
  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
         nHeader-(sizeof(aJournalMagic)+20));

  /* In theory, it is only necessary to write the 28 bytes that the 
  ** journal header consumes to the journal file here. Then increment the 
  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
  ** record is written to the following sector (leaving a gap in the file
  ** that will be implicitly filled in by the OS).
  **
  ** However it has been discovered that on some systems this pattern can 
  ** be significantly slower than contiguously writing data to the file,
  ** even if that means explicitly writing data to the block of 
  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  ** is done. 
  **
  ** The loop is required here in case the sector-size is larger than the 
  ** database page size. Since the zHeader buffer is only Pager.pageSize
  ** bytes in size, more than one call to sqlite3OsWrite() may be required
  ** to populate the entire journal header sector.
  */ 
  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
    pPager->journalOff += nHeader;
  }

  return rc;
}

/*
** The journal file must be open when this is called. A journal header file
** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
** file. The current location in the journal file is given by
** pPager->journalOff. See comments above function writeJournalHdr() for
** a description of the journal header format.
**
** If the header is read successfully, *pNRec is set to the number of
** page records following this header and *pDbSize is set to the size of the
** database before the transaction began, in pages. Also, pPager->cksumInit
** is set to the value read from the journal header. SQLITE_OK is returned
** in this case.
**
** If the journal header file appears to be corrupted, SQLITE_DONE is
** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
** cannot be read from the journal file an error code is returned.
*/
static int readJournalHdr(
  Pager *pPager,               /* Pager object */
  int isHot,
  i64 journalSize,             /* Size of the open journal file in bytes */
  u32 *pNRec,                  /* OUT: Value read from the nRec field */
  u32 *pDbSize                 /* OUT: Value of original database size field */
){
  int rc;                      /* Return code */
  unsigned char aMagic[8];     /* A buffer to hold the magic header */
  i64 iHdrOff;                 /* Offset of journal header being read */

  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */

  /* Advance Pager.journalOff to the start of the next sector. If the
  ** journal file is too small for there to be a header stored at this
  ** point, return SQLITE_DONE.
  */
  pPager->journalOff = journalHdrOffset(pPager);
  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
    return SQLITE_DONE;
  }
  iHdrOff = pPager->journalOff;

  /* Read in the first 8 bytes of the journal header. If they do not match
  ** the  magic string found at the start of each journal header, return
  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  ** proceed.
  */
  if( isHot || iHdrOff!=pPager->journalHdr ){
    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
    if( rc ){
      return rc;
    }
    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
      return SQLITE_DONE;
    }
  }

  /* Read the first three 32-bit fields of the journal header: The nRec
  ** field, the checksum-initializer and the database size at the start
  ** of the transaction. Return an error code if anything goes wrong.
  */
  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  ){
    return rc;
  }

  if( pPager->journalOff==0 ){
    u32 iPageSize;               /* Page-size field of journal header */
    u32 iSectorSize;             /* Sector-size field of journal header */
    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */

    /* Read the page-size and sector-size journal header fields. */
    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
    ){
      return rc;
    }

    /* Check that the values read from the page-size and sector-size fields
    ** are within range. To be 'in range', both values need to be a power
    ** of two greater than or equal to 512, and not greater than their 
    ** respective compile time maximum limits.
    */
    if( iPageSize<512                  || iSectorSize<512
     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
    ){
      /* If the either the page-size or sector-size in the journal-header is 
      ** invalid, then the process that wrote the journal-header must have 
      ** crashed before the header was synced. In this case stop reading 
      ** the journal file here.
      */
      return SQLITE_DONE;
    }

    /* Update the page-size to match the value read from the journal. 
    ** Use a testcase() macro to make sure that malloc failure within 
    ** PagerSetPagesize() is tested.
    */
    iPageSize16 = (u16)iPageSize;
    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
    testcase( rc!=SQLITE_OK );
    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );

    /* Update the assumed sector-size to match the value used by 
    ** the process that created this journal. If this journal was
    ** created by a process other than this one, then this routine
    ** is being called from within pager_playback(). The local value
    ** of Pager.sectorSize is restored at the end of that routine.
    */
    pPager->sectorSize = iSectorSize;
  }

  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  return rc;
}


/*
** Write the supplied master journal name into the journal file for pager
** pPager at the current location. The master journal name must be the last
** thing written to a journal file. If the pager is in full-sync mode, the
** journal file descriptor is advanced to the next sector boundary before
** anything is written. The format is:
**
**   + 4 bytes: PAGER_MJ_PGNO.
**   + N bytes: Master journal filename in utf-8.
**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
**   + 4 bytes: Master journal name checksum.
**   + 8 bytes: aJournalMagic[].
**
** The master journal page checksum is the sum of the bytes in the master
** journal name, where each byte is interpreted as a signed 8-bit integer.
**
** If zMaster is a NULL pointer (occurs for a single database transaction), 
** this call is a no-op.
*/
static int writeMasterJournal(Pager *pPager, const char *zMaster){
  int rc;                          /* Return code */
  int nMaster;                     /* Length of string zMaster */
  i64 iHdrOff;                     /* Offset of header in journal file */
  i64 jrnlSize;                    /* Size of journal file on disk */
  u32 cksum = 0;                   /* Checksum of string zMaster */

  if( !zMaster || pPager->setMaster
   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
   || pPager->journalMode==PAGER_JOURNALMODE_OFF 
  ){
    return SQLITE_OK;
  }
  pPager->setMaster = 1;
  assert( isOpen(pPager->jfd) );

  /* Calculate the length in bytes and the checksum of zMaster */
  for(nMaster=0; zMaster[nMaster]; nMaster++){
    cksum += zMaster[nMaster];
  }

  /* If in full-sync mode, advance to the next disk sector before writing
  ** the master journal name. This is in case the previous page written to
  ** the journal has already been synced.
  */
  if( pPager->fullSync ){
    pPager->journalOff = journalHdrOffset(pPager);
  }
  iHdrOff = pPager->journalOff;

  /* Write the master journal data to the end of the journal file. If
  ** an error occurs, return the error code to the caller.
  */
  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  ){
    return rc;
  }
  pPager->journalOff += (nMaster+20);
  pPager->needSync = !pPager->noSync;

  /* If the pager is in peristent-journal mode, then the physical 
  ** journal-file may extend past the end of the master-journal name
  ** and 8 bytes of magic data just written to the file. This is 
  ** dangerous because the code to rollback a hot-journal file
  ** will not be able to find the master-journal name to determine 
  ** whether or not the journal is hot. 
  **
  ** Easiest thing to do in this scenario is to truncate the journal 
  ** file to the required size.
  */ 
  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   && jrnlSize>pPager->journalOff
  ){
    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  }
  return rc;
}

/*
** Find a page in the hash table given its page number. Return
** a pointer to the page or NULL if the requested page is not 
** already in memory.
*/
static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  PgHdr *p;                         /* Return value */

  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  ** fail, since no attempt to allocate dynamic memory will be made.
  */
  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  return p;
}

/*
** Unless the pager is in error-state, discard all in-memory pages. If
** the pager is in error-state, then this call is a no-op.
**
** TODO: Why can we not reset the pager while in error state?
*/
static void pager_reset(Pager *pPager){
  if( SQLITE_OK==pPager->errCode ){
    sqlite3BackupRestart(pPager->pBackup);
    sqlite3PcacheClear(pPager->pPCache);
    pPager->dbSizeValid = 0;
  }
}

/*
** Free all structures in the Pager.aSavepoint[] array and set both
** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
** if it is open and the pager is not in exclusive mode.
*/
static void releaseAllSavepoints(Pager *pPager){
  int ii;               /* Iterator for looping through Pager.aSavepoint */
  for(ii=0; ii<pPager->nSavepoint; ii++){
    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  }
  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
    sqlite3OsClose(pPager->sjfd);
  }
  sqlite3_free(pPager->aSavepoint);
  pPager->aSavepoint = 0;
  pPager->nSavepoint = 0;
  pPager->nSubRec = 0;
}

/*
** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
** bitvecs of all open savepoints. Return SQLITE_OK if successful
** or SQLITE_NOMEM if a malloc failure occurs.
*/
static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  int ii;                   /* Loop counter */
  int rc = SQLITE_OK;       /* Result code */

  for(ii=0; ii<pPager->nSavepoint; ii++){
    PagerSavepoint *p = &pPager->aSavepoint[ii];
    if( pgno<=p->nOrig ){
      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
      testcase( rc==SQLITE_NOMEM );
      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
    }
  }
  return rc;
}

/*
** Unlock the database file. This function is a no-op if the pager
** is in exclusive mode.
**
** If the pager is currently in error state, discard the contents of 
** the cache and reset the Pager structure internal state. If there is
** an open journal-file, then the next time a shared-lock is obtained
** on the pager file (by this or any other process), it will be
** treated as a hot-journal and rolled back.
*/
static void pager_unlock(Pager *pPager){
  if( !pPager->exclusiveMode ){
    int rc;                      /* Return code */

    /* Always close the journal file when dropping the database lock.
    ** Otherwise, another connection with journal_mode=delete might
    ** delete the file out from under us.
    */
    sqlite3OsClose(pPager->jfd);
    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;
    releaseAllSavepoints(pPager);

    /* If the file is unlocked, somebody else might change it. The
    ** values stored in Pager.dbSize etc. might become invalid if
    ** this happens. TODO: Really, this doesn't need to be cleared
    ** until the change-counter check fails in PagerSharedLock().
    */
    pPager->dbSizeValid = 0;

    rc = osUnlock(pPager->fd, NO_LOCK);
    if( rc ){
      pPager->errCode = rc;
    }
    IOTRACE(("UNLOCK %p\n", pPager))

    /* If Pager.errCode is set, the contents of the pager cache cannot be
    ** trusted. Now that the pager file is unlocked, the contents of the
    ** cache can be discarded and the error code safely cleared.
    */
    if( pPager->errCode ){
      if( rc==SQLITE_OK ){
        pPager->errCode = SQLITE_OK;
      }
      pager_reset(pPager);
    }

    pPager->changeCountDone = 0;
    pPager->state = PAGER_UNLOCK;
  }
}

/*
** This function should be called when an IOERR, CORRUPT or FULL error
** may have occurred. The first argument is a pointer to the pager 
** structure, the second the error-code about to be returned by a pager 
** API function. The value returned is a copy of the second argument 
** to this function. 
**
** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
** the error becomes persistent. Until the persisten error is cleared,
** subsequent API calls on this Pager will immediately return the same 
** error code.
**
** A persistent error indicates that the contents of the pager-cache 
** cannot be trusted. This state can be cleared by completely discarding 
** the contents of the pager-cache. If a transaction was active when
** the persistent error occurred, then the rollback journal may need
** to be replayed to restore the contents of the database file (as if
** it were a hot-journal).
*/
static int pager_error(Pager *pPager, int rc){
  int rc2 = rc & 0xff;
  assert( rc==SQLITE_OK || !MEMDB );
  assert(
       pPager->errCode==SQLITE_FULL ||
       pPager->errCode==SQLITE_OK ||
       (pPager->errCode & 0xff)==SQLITE_IOERR
  );
  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
    pPager->errCode = rc;
  }
  return rc;
}

/*
** Execute a rollback if a transaction is active and unlock the 
** database file. 
**
** If the pager has already entered the error state, do not attempt 
** the rollback at this time. Instead, pager_unlock() is called. The
** call to pager_unlock() will discard all in-memory pages, unlock
** the database file and clear the error state. If this means that
** there is a hot-journal left in the file-system, the next connection
** to obtain a shared lock on the pager (which may be this one) will
** roll it back.
**
** If the pager has not already entered the error state, but an IO or
** malloc error occurs during a rollback, then this will itself cause 
** the pager to enter the error state. Which will be cleared by the
** call to pager_unlock(), as described above.
*/
static void pagerUnlockAndRollback(Pager *pPager){
  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
    sqlite3BeginBenignMalloc();
    sqlite3PagerRollback(pPager);
    sqlite3EndBenignMalloc();
  }
  pager_unlock(pPager);
}

/*
** This routine ends a transaction. A transaction is usually ended by 
** either a COMMIT or a ROLLBACK operation. This routine may be called 
** after rollback of a hot-journal, or if an error occurs while opening
** the journal file or writing the very first journal-header of a
** database transaction.
** 
** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
** routine is called, it is a no-op (returns SQLITE_OK).
**
** Otherwise, any active savepoints are released.
**
** If the journal file is open, then it is "finalized". Once a journal 
** file has been finalized it is not possible to use it to roll back a 
** transaction. Nor will it be considered to be a hot-journal by this
** or any other database connection. Exactly how a journal is finalized
** depends on whether or not the pager is running in exclusive mode and
** the current journal-mode (Pager.journalMode value), as follows:
**
**   journalMode==MEMORY
**     Journal file descriptor is simply closed. This destroys an 
**     in-memory journal.
**
**   journalMode==TRUNCATE
**     Journal file is truncated to zero bytes in size.
**
**   journalMode==PERSIST
**     The first 28 bytes of the journal file are zeroed. This invalidates
**     the first journal header in the file, and hence the entire journal
**     file. An invalid journal file cannot be rolled back.
**
**   journalMode==DELETE
**     The journal file is closed and deleted using sqlite3OsDelete().
**
**     If the pager is running in exclusive mode, this method of finalizing
**     the journal file is never used. Instead, if the journalMode is
**     DELETE and the pager is in exclusive mode, the method described under
**     journalMode==PERSIST is used instead.
**
** After the journal is finalized, if running in non-exclusive mode, the
** pager moves to PAGER_SHARED state (and downgrades the lock on the
** database file accordingly).
**
** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
** exclusive mode.
**
** SQLITE_OK is returned if no error occurs. If an error occurs during
** any of the IO operations to finalize the journal file or unlock the
** database then the IO error code is returned to the user. If the 
** operation to finalize the journal file fails, then the code still
** tries to unlock the database file if not in exclusive mode. If the
** unlock operation fails as well, then the first error code related
** to the first error encountered (the journal finalization one) is
** returned.
*/
static int pager_end_transaction(Pager *pPager, int hasMaster){
  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */

  if( pPager->state<PAGER_RESERVED ){
    return SQLITE_OK;
  }
  releaseAllSavepoints(pPager);

  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  if( isOpen(pPager->jfd) ){

    /* Finalize the journal file. */
    if( sqlite3IsMemJournal(pPager->jfd) ){
      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
      sqlite3OsClose(pPager->jfd);
    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
      if( pPager->journalOff==0 ){
        rc = SQLITE_OK;
      }else{
        rc = sqlite3OsTruncate(pPager->jfd, 0);
      }
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
    }else if( pPager->exclusiveMode 
     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
    ){
      rc = zeroJournalHdr(pPager, hasMaster);
      pager_error(pPager, rc);
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
    }else{
      /* This branch may be executed with Pager.journalMode==MEMORY if
      ** a hot-journal was just rolled back. In this case the journal
      ** file should be closed and deleted. If this connection writes to
      ** the database file, it will do so using an in-memory journal.  */
      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
      );
      sqlite3OsClose(pPager->jfd);
      if( !pPager->tempFile ){
        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
      }
    }

#ifdef SQLITE_CHECK_PAGES
    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
#endif

    sqlite3PcacheCleanAll(pPager->pPCache);
    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;
    pPager->nRec = 0;
  }

  if( !pPager->exclusiveMode ){
    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
    pPager->state = PAGER_SHARED;
    pPager->changeCountDone = 0;
  }else if( pPager->state==PAGER_SYNCED ){
    pPager->state = PAGER_EXCLUSIVE;
  }
  pPager->setMaster = 0;
  pPager->needSync = 0;
  pPager->dbModified = 0;

  /* TODO: Is this optimal? Why is the db size invalidated here 
  ** when the database file is not unlocked? */
  pPager->dbOrigSize = 0;
  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  if( !MEMDB ){
    pPager->dbSizeValid = 0;
  }

  return (rc==SQLITE_OK?rc2:rc);
}

/*
** Parameter aData must point to a buffer of pPager->pageSize bytes
** of data. Compute and return a checksum based ont the contents of the 
** page of data and the current value of pPager->cksumInit.
**
** This is not a real checksum. It is really just the sum of the 
** random initial value (pPager->cksumInit) and every 200th byte
** of the page data, starting with byte offset (pPager->pageSize%200).
** Each byte is interpreted as an 8-bit unsigned integer.
**
** Changing the formula used to compute this checksum results in an
** incompatible journal file format.
**
** If journal corruption occurs due to a power failure, the most likely 
** scenario is that one end or the other of the record will be changed. 
** It is much less likely that the two ends of the journal record will be
** correct and the middle be corrupt.  Thus, this "checksum" scheme,
** though fast and simple, catches the mostly likely kind of corruption.
*/
static u32 pager_cksum(Pager *pPager, const u8 *aData){
  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
  int i = pPager->pageSize-200;          /* Loop counter */
  while( i>0 ){
    cksum += aData[i];
    i -= 200;
  }
  return cksum;
}

/*
** Read a single page from either the journal file (if isMainJrnl==1) or
** from the sub-journal (if isMainJrnl==0) and playback that page.
** The page begins at offset *pOffset into the file. The *pOffset
** value is increased to the start of the next page in the journal.
**
** The isMainJrnl flag is true if this is the main rollback journal and
** false for the statement journal.  The main rollback journal uses
** checksums - the statement journal does not.
**
** If the page number of the page record read from the (sub-)journal file
** is greater than the current value of Pager.dbSize, then playback is
** skipped and SQLITE_OK is returned.
**
** If pDone is not NULL, then it is a record of pages that have already
** been played back.  If the page at *pOffset has already been played back
** (if the corresponding pDone bit is set) then skip the playback.
** Make sure the pDone bit corresponding to the *pOffset page is set
** prior to returning.
**
** If the page record is successfully read from the (sub-)journal file
** and played back, then SQLITE_OK is returned. If an IO error occurs
** while reading the record from the (sub-)journal file or while writing
** to the database file, then the IO error code is returned. If data
** is successfully read from the (sub-)journal file but appears to be
** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
** two circumstances:
** 
**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
**   * If the record is being rolled back from the main journal file
**     and the checksum field does not match the record content.
**
** Neither of these two scenarios are possible during a savepoint rollback.
**
** If this is a savepoint rollback, then memory may have to be dynamically
** allocated by this function. If this is the case and an allocation fails,
** SQLITE_NOMEM is returned.
*/
static int pager_playback_one_page(
  Pager *pPager,                /* The pager being played back */
  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
  int isUnsync,                 /* True if reading from unsynced main journal */
  i64 *pOffset,                 /* Offset of record to playback */
  int isSavepnt,                /* True for a savepoint rollback */
  Bitvec *pDone                 /* Bitvec of pages already played back */
){
  int rc;
  PgHdr *pPg;                   /* An existing page in the cache */
  Pgno pgno;                    /* The page number of a page in journal */
  u32 cksum;                    /* Checksum used for sanity checking */
  u8 *aData;                    /* Temporary storage for the page */
  sqlite3_file *jfd;            /* The file descriptor for the journal file */

  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */

  aData = (u8*)pPager->pTmpSpace;
  assert( aData );         /* Temp storage must have already been allocated */

  /* Read the page number and page data from the journal or sub-journal
  ** file. Return an error code to the caller if an IO error occurs.
  */
  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  rc = read32bits(jfd, *pOffset, &pgno);
  if( rc!=SQLITE_OK ) return rc;
  rc = sqlite3OsRead(jfd, aData, pPager->pageSize, (*pOffset)+4);
  if( rc!=SQLITE_OK ) return rc;
  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;

  /* Sanity checking on the page.  This is more important that I originally
  ** thought.  If a power failure occurs while the journal is being written,
  ** it could cause invalid data to be written into the journal.  We need to
  ** detect this invalid data (with high probability) and ignore it.
  */
  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
    assert( !isSavepnt );
    return SQLITE_DONE;
  }
  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
    return SQLITE_OK;
  }
  if( isMainJrnl ){
    rc = read32bits(jfd, (*pOffset)-4, &cksum);
    if( rc ) return rc;
    if( !isSavepnt && pager_cksum(pPager, aData)!=cksum ){
      return SQLITE_DONE;
    }
  }

  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
    return rc;
  }

  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );

  /* If the pager is in RESERVED state, then there must be a copy of this
  ** page in the pager cache. In this case just update the pager cache,
  ** not the database file. The page is left marked dirty in this case.
  **
  ** An exception to the above rule: If the database is in no-sync mode
  ** and a page is moved during an incremental vacuum then the page may
  ** not be in the pager cache. Later: if a malloc() or IO error occurs
  ** during a Movepage() call, then the page may not be in the cache
  ** either. So the condition described in the above paragraph is not
  ** assert()able.
  **
  ** If in EXCLUSIVE state, then we update the pager cache if it exists
  ** and the main file. The page is then marked not dirty.
  **
  ** Ticket #1171:  The statement journal might contain page content that is
  ** different from the page content at the start of the transaction.
  ** This occurs when a page is changed prior to the start of a statement
  ** then changed again within the statement.  When rolling back such a
  ** statement we must not write to the original database unless we know
  ** for certain that original page contents are synced into the main rollback
  ** journal.  Otherwise, a power loss might leave modified data in the
  ** database file without an entry in the rollback journal that can
  ** restore the database to its original form.  Two conditions must be
  ** met before writing to the database files. (1) the database must be
  ** locked.  (2) we know that the original page content is fully synced
  ** in the main journal either because the page is not in cache or else
  ** the page is marked as needSync==0.
  **
  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
  ** is possible to fail a statement on a database that does not yet exist.
  ** Do not attempt to write if database file has never been opened.
  */
  pPg = pager_lookup(pPager, pgno);
  assert( pPg || !MEMDB );
  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
               PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData),
               (isMainJrnl?"main-journal":"sub-journal")
  ));
  if( (pPager->state>=PAGER_EXCLUSIVE)
   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
   && isOpen(pPager->fd)
   && !isUnsync
  ){
    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
    rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
    if( pgno>pPager->dbFileSize ){
      pPager->dbFileSize = pgno;
    }
    if( pPager->pBackup ){
      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
      sqlite3BackupUpdate(pPager->pBackup, pgno, aData);
      CODEC1(pPager, aData, pgno, 0, rc=SQLITE_NOMEM);
    }
  }else if( !isMainJrnl && pPg==0 ){
    /* If this is a rollback of a savepoint and data was not written to
    ** the database and the page is not in-memory, there is a potential
    ** problem. When the page is next fetched by the b-tree layer, it 
    ** will be read from the database file, which may or may not be 
    ** current. 
    **
    ** There are a couple of different ways this can happen. All are quite
    ** obscure. When running in synchronous mode, this can only happen 
    ** if the page is on the free-list at the start of the transaction, then
    ** populated, then moved using sqlite3PagerMovepage().
    **
    ** The solution is to add an in-memory page to the cache containing
    ** the data just read from the sub-journal. Mark the page as dirty 
    ** and if the pager requires a journal-sync, then mark the page as 
    ** requiring a journal-sync before it is written.
    */
    assert( isSavepnt );
    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
      return rc;
    }
    pPg->flags &= ~PGHDR_NEED_READ;
    sqlite3PcacheMakeDirty(pPg);
  }
  if( pPg ){
    /* No page should ever be explicitly rolled back that is in use, except
    ** for page 1 which is held in use in order to keep the lock on the
    ** database active. However such a page may be rolled back as a result
    ** of an internal error resulting in an automatic call to
    ** sqlite3PagerRollback().
    */
    void *pData;
    pData = pPg->pData;
    memcpy(pData, aData, pPager->pageSize);
    pPager->xReiniter(pPg);
    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
      /* If the contents of this page were just restored from the main 
      ** journal file, then its content must be as they were when the 
      ** transaction was first opened. In this case we can mark the page
      ** as clean, since there will be no need to write it out to the.
      **
      ** There is one exception to this rule. If the page is being rolled
      ** back as part of a savepoint (or statement) rollback from an 
      ** unsynced portion of the main journal file, then it is not safe
      ** to mark the page as clean. This is because marking the page as
      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
      ** already in the journal file (recorded in Pager.pInJournal) and
      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
      ** again within this transaction, it will be marked as dirty but
      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
      ** be written out into the database file before its journal file
      ** segment is synced. If a crash occurs during or following this,
      ** database corruption may ensue.
      */
      sqlite3PcacheMakeClean(pPg);
    }
#ifdef SQLITE_CHECK_PAGES
    pPg->pageHash = pager_pagehash(pPg);
#endif
    /* If this was page 1, then restore the value of Pager.dbFileVers.
    ** Do this before any decoding. */
    if( pgno==1 ){
      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
    }

    /* Decode the page just read from disk */
    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
    sqlite3PcacheRelease(pPg);
  }
  return rc;
}

/*
** Parameter zMaster is the name of a master journal file. A single journal
** file that referred to the master journal file has just been rolled back.
** This routine checks if it is possible to delete the master journal file,
** and does so if it is.
**
** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
** available for use within this function.
**
** When a master journal file is created, it is populated with the names 
** of all of its child journals, one after another, formatted as utf-8 
** encoded text. The end of each child journal file is marked with a 
** nul-terminator byte (0x00). i.e. the entire contents of a master journal
** file for a transaction involving two databases might be:
**
**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
**
** A master journal file may only be deleted once all of its child 
** journals have been rolled back.
**
** This function reads the contents of the master-journal file into 
** memory and loops through each of the child journal names. For
** each child journal, it checks if:
**
**   * if the child journal exists, and if so
**   * if the child journal contains a reference to master journal 
**     file zMaster
**
** If a child journal can be found that matches both of the criteria
** above, this function returns without doing anything. Otherwise, if
** no such child journal can be found, file zMaster is deleted from
** the file-system using sqlite3OsDelete().
**
** If an IO error within this function, an error code is returned. This
** function allocates memory by calling sqlite3Malloc(). If an allocation
** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
** occur, SQLITE_OK is returned.
**
** TODO: This function allocates a single block of memory to load
** the entire contents of the master journal file. This could be
** a couple of kilobytes or so - potentially larger than the page 
** size.
*/
static int pager_delmaster(Pager *pPager, const char *zMaster){
  sqlite3_vfs *pVfs = pPager->pVfs;
  int rc;                   /* Return code */
  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
  char *zMasterJournal = 0; /* Contents of master journal file */
  i64 nMasterJournal;       /* Size of master journal file */

  /* Allocate space for both the pJournal and pMaster file descriptors.
  ** If successful, open the master journal file for reading.
  */
  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  if( !pMaster ){
    rc = SQLITE_NOMEM;
  }else{
    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  }
  if( rc!=SQLITE_OK ) goto delmaster_out;

  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  if( rc!=SQLITE_OK ) goto delmaster_out;

  if( nMasterJournal>0 ){
    char *zJournal;
    char *zMasterPtr = 0;
    int nMasterPtr = pVfs->mxPathname+1;

    /* Load the entire master journal file into space obtained from
    ** sqlite3_malloc() and pointed to by zMasterJournal. 
    */
    zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
    if( !zMasterJournal ){
      rc = SQLITE_NOMEM;
      goto delmaster_out;
    }
    zMasterPtr = &zMasterJournal[nMasterJournal+1];
    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
    if( rc!=SQLITE_OK ) goto delmaster_out;
    zMasterJournal[nMasterJournal] = 0;

    zJournal = zMasterJournal;
    while( (zJournal-zMasterJournal)<nMasterJournal ){
      int exists;
      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
      if( rc!=SQLITE_OK ){
        goto delmaster_out;
      }
      if( exists ){
        /* One of the journals pointed to by the master journal exists.
        ** Open it and check if it points at the master journal. If
        ** so, return without deleting the master journal file.
        */
        int c;
        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
        if( rc!=SQLITE_OK ){
          goto delmaster_out;
        }

        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
        sqlite3OsClose(pJournal);
        if( rc!=SQLITE_OK ){
          goto delmaster_out;
        }

        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
        if( c ){
          /* We have a match. Do not delete the master journal file. */
          goto delmaster_out;
        }
      }
      zJournal += (sqlite3Strlen30(zJournal)+1);
    }
  }
  
  rc = sqlite3OsDelete(pVfs, zMaster, 0);

delmaster_out:
  if( zMasterJournal ){
    sqlite3_free(zMasterJournal);
  }  
  if( pMaster ){
    sqlite3OsClose(pMaster);
    assert( !isOpen(pJournal) );
  }
  sqlite3_free(pMaster);
  return rc;
}


/*
** This function is used to change the actual size of the database 
** file in the file-system. This only happens when committing a transaction,
** or rolling back a transaction (including rolling back a hot-journal).
**
** If the main database file is not open, or an exclusive lock is not
** held, this function is a no-op. Otherwise, the size of the file is
** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
** on disk is currently larger than nPage pages, then use the VFS
** xTruncate() method to truncate it.
**
** Or, it might might be the case that the file on disk is smaller than 
** nPage pages. Some operating system implementations can get confused if 
** you try to truncate a file to some size that is larger than it 
** currently is, so detect this case and write a single zero byte to 
** the end of the new file instead.
**
** If successful, return SQLITE_OK. If an IO error occurs while modifying
** the database file, return the error code to the caller.
*/
static int pager_truncate(Pager *pPager, Pgno nPage){
  int rc = SQLITE_OK;
  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
    i64 currentSize, newSize;
    /* TODO: Is it safe to use Pager.dbFileSize here? */
    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
    newSize = pPager->pageSize*(i64)nPage;
    if( rc==SQLITE_OK && currentSize!=newSize ){
      if( currentSize>newSize ){
        rc = sqlite3OsTruncate(pPager->fd, newSize);
      }else{
        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
      }
      if( rc==SQLITE_OK ){
        pPager->dbFileSize = nPage;
      }
    }
  }
  return rc;
}

/*
** Set the value of the Pager.sectorSize variable for the given
** pager based on the value returned by the xSectorSize method
** of the open database file. The sector size will be used used 
** to determine the size and alignment of journal header and 
** master journal pointers within created journal files.
**
** For temporary files the effective sector size is always 512 bytes.
**
** Otherwise, for non-temporary files, the effective sector size is
** the value returned by the xSectorSize() method rounded up to 512 if
** it is less than 512, or rounded down to MAX_SECTOR_SIZE if it
** is greater than MAX_SECTOR_SIZE.
*/
static void setSectorSize(Pager *pPager){
  assert( isOpen(pPager->fd) || pPager->tempFile );

  if( !pPager->tempFile ){
    /* Sector size doesn't matter for temporary files. Also, the file
    ** may not have been opened yet, in which case the OsSectorSize()
    ** call will segfault.
    */
    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  }
  if( pPager->sectorSize<512 ){
    pPager->sectorSize = 512;
  }
  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
    assert( MAX_SECTOR_SIZE>=512 );
    pPager->sectorSize = MAX_SECTOR_SIZE;
  }
}

/*
** Playback the journal and thus restore the database file to
** the state it was in before we started making changes.  
**
** The journal file format is as follows: 
**
**  (1)  8 byte prefix.  A copy of aJournalMagic[].
**  (2)  4 byte big-endian integer which is the number of valid page records
**       in the journal.  If this value is 0xffffffff, then compute the
**       number of page records from the journal size.
**  (3)  4 byte big-endian integer which is the initial value for the 
**       sanity checksum.
**  (4)  4 byte integer which is the number of pages to truncate the
**       database to during a rollback.
**  (5)  4 byte big-endian integer which is the sector size.  The header
**       is this many bytes in size.
**  (6)  4 byte big-endian integer which is the page size.
**  (7)  zero padding out to the next sector size.
**  (8)  Zero or more pages instances, each as follows:
**        +  4 byte page number.
**        +  pPager->pageSize bytes of data.
**        +  4 byte checksum
**
** When we speak of the journal header, we mean the first 7 items above.
** Each entry in the journal is an instance of the 8th item.
**
** Call the value from the second bullet "nRec".  nRec is the number of
** valid page entries in the journal.  In most cases, you can compute the
** value of nRec from the size of the journal file.  But if a power
** failure occurred while the journal was being written, it could be the
** case that the size of the journal file had already been increased but
** the extra entries had not yet made it safely to disk.  In such a case,
** the value of nRec computed from the file size would be too large.  For
** that reason, we always use the nRec value in the header.
**
** If the nRec value is 0xffffffff it means that nRec should be computed
** from the file size.  This value is used when the user selects the
** no-sync option for the journal.  A power failure could lead to corruption
** in this case.  But for things like temporary table (which will be
** deleted when the power is restored) we don't care.  
**
** If the file opened as the journal file is not a well-formed
** journal file then all pages up to the first corrupted page are rolled
** back (or no pages if the journal header is corrupted). The journal file
** is then deleted and SQLITE_OK returned, just as if no corruption had
** been encountered.
**
** If an I/O or malloc() error occurs, the journal-file is not deleted
** and an error code is returned.
**
** The isHot parameter indicates that we are trying to rollback a journal
** that might be a hot journal.  Or, it could be that the journal is 
** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
** If the journal really is hot, reset the pager cache prior rolling
** back any content.  If the journal is merely persistent, no reset is
** needed.
*/
static int pager_playback(Pager *pPager, int isHot){
  sqlite3_vfs *pVfs = pPager->pVfs;
  i64 szJ;                 /* Size of the journal file in bytes */
  u32 nRec;                /* Number of Records in the journal */
  u32 u;                   /* Unsigned loop counter */
  Pgno mxPg = 0;           /* Size of the original file in pages */
  int rc;                  /* Result code of a subroutine */
  int res = 1;             /* Value returned by sqlite3OsAccess() */
  char *zMaster = 0;       /* Name of master journal file if any */
  int needPagerReset;      /* True to reset page prior to first page rollback */

  /* Figure out how many records are in the journal.  Abort early if
  ** the journal is empty.
  */
  assert( isOpen(pPager->jfd) );
  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  if( rc!=SQLITE_OK || szJ==0 ){
    goto end_playback;
  }

  /* Read the master journal name from the journal, if it is present.
  ** If a master journal file name is specified, but the file is not
  ** present on disk, then the journal is not hot and does not need to be
  ** played back.
  **
  ** TODO: Technically the following is an error because it assumes that
  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  **  mxPathname is 512, which is the same as the minimum allowable value
  ** for pageSize.
  */
  zMaster = pPager->pTmpSpace;
  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  if( rc==SQLITE_OK && zMaster[0] ){
    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  }
  zMaster = 0;
  if( rc!=SQLITE_OK || !res ){
    goto end_playback;
  }
  pPager->journalOff = 0;
  needPagerReset = isHot;

  /* This loop terminates either when a readJournalHdr() or 
  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
  ** occurs. 
  */
  while( 1 ){
    int isUnsync = 0;

    /* Read the next journal header from the journal file.  If there are
    ** not enough bytes left in the journal file for a complete header, or
    ** it is corrupted, then a process must of failed while writing it.
    ** This indicates nothing more needs to be rolled back.
    */
    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
    if( rc!=SQLITE_OK ){ 
      if( rc==SQLITE_DONE ){
        rc = SQLITE_OK;
      }
      goto end_playback;
    }

    /* If nRec is 0xffffffff, then this journal was created by a process
    ** working in no-sync mode. This means that the rest of the journal
    ** file consists of pages, there are no more journal headers. Compute
    ** the value of nRec based on this assumption.
    */
    if( nRec==0xffffffff ){
      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
    }

    /* If nRec is 0 and this rollback is of a transaction created by this
    ** process and if this is the final header in the journal, then it means
    ** that this part of the journal was being filled but has not yet been
    ** synced to disk.  Compute the number of pages based on the remaining
    ** size of the file.
    **
    ** The third term of the test was added to fix ticket #2565.
    ** When rolling back a hot journal, nRec==0 always means that the next
    ** chunk of the journal contains zero pages to be rolled back.  But
    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
    ** the journal, it means that the journal might contain additional
    ** pages that need to be rolled back and that the number of pages 
    ** should be computed based on the journal file size.
    */
    if( nRec==0 && !isHot &&
        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
      isUnsync = 1;
    }

    /* If this is the first header read from the journal, truncate the
    ** database file back to its original size.
    */
    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
      rc = pager_truncate(pPager, mxPg);
      if( rc!=SQLITE_OK ){
        goto end_playback;
      }
      pPager->dbSize = mxPg;
    }

    /* Copy original pages out of the journal and back into the 
    ** database file and/or page cache.
    */
    for(u=0; u<nRec; u++){
      if( needPagerReset ){
        pager_reset(pPager);
        needPagerReset = 0;
      }
      rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
      if( rc!=SQLITE_OK ){
        if( rc==SQLITE_DONE ){
          rc = SQLITE_OK;
          pPager->journalOff = szJ;
          break;
        }else{
          /* If we are unable to rollback, quit and return the error
          ** code.  This will cause the pager to enter the error state
          ** so that no further harm will be done.  Perhaps the next
          ** process to come along will be able to rollback the database.
          */
          goto end_playback;
        }
      }
    }
  }
  /*NOTREACHED*/
  assert( 0 );

end_playback:
  /* Following a rollback, the database file should be back in its original
  ** state prior to the start of the transaction, so invoke the
  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  ** assertion that the transaction counter was modified.
  */
  assert(
    pPager->fd->pMethods==0 ||
    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
  );

  /* If this playback is happening automatically as a result of an IO or 
  ** malloc error that occurred after the change-counter was updated but 
  ** before the transaction was committed, then the change-counter 
  ** modification may just have been reverted. If this happens in exclusive 
  ** mode, then subsequent transactions performed by the connection will not
  ** update the change-counter at all. This may lead to cache inconsistency
  ** problems for other processes at some point in the future. So, just
  ** in case this has happened, clear the changeCountDone flag now.
  */
  pPager->changeCountDone = pPager->tempFile;

  if( rc==SQLITE_OK ){
    zMaster = pPager->pTmpSpace;
    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
    testcase( rc!=SQLITE_OK );
  }
  if( rc==SQLITE_OK ){
    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
    testcase( rc!=SQLITE_OK );
  }
  if( rc==SQLITE_OK && zMaster[0] && res ){
    /* If there was a master journal and this routine will return success,
    ** see if it is possible to delete the master journal.
    */
    rc = pager_delmaster(pPager, zMaster);
    testcase( rc!=SQLITE_OK );
  }

  /* The Pager.sectorSize variable may have been updated while rolling
  ** back a journal created by a process with a different sector size
  ** value. Reset it to the correct value for this process.
  */
  setSectorSize(pPager);
  return rc;
}

/*
** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
** the entire master journal file. The case pSavepoint==NULL occurs when 
** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
** savepoint.
**
** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
** being rolled back), then the rollback consists of up to three stages,
** performed in the order specified:
**
**   * Pages are played back from the main journal starting at byte
**     offset PagerSavepoint.iOffset and continuing to 
**     PagerSavepoint.iHdrOffset, or to the end of the main journal
**     file if PagerSavepoint.iHdrOffset is zero.
**
**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
**     back starting from the journal header immediately following 
**     PagerSavepoint.iHdrOffset to the end of the main journal file.
**
**   * Pages are then played back from the sub-journal file, starting
**     with the PagerSavepoint.iSubRec and continuing to the end of
**     the journal file.
**
** Throughout the rollback process, each time a page is rolled back, the
** corresponding bit is set in a bitvec structure (variable pDone in the
** implementation below). This is used to ensure that a page is only
** rolled back the first time it is encountered in either journal.
**
** If pSavepoint is NULL, then pages are only played back from the main
** journal file. There is no need for a bitvec in this case.
**
** In either case, before playback commences the Pager.dbSize variable
** is reset to the value that it held at the start of the savepoint 
** (or transaction). No page with a page-number greater than this value
** is played back. If one is encountered it is simply skipped.
*/
static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  i64 szJ;                 /* Effective size of the main journal */
  i64 iHdrOff;             /* End of first segment of main-journal records */
  int rc = SQLITE_OK;      /* Return code */
  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */

  assert( pPager->state>=PAGER_SHARED );

  /* Allocate a bitvec to use to store the set of pages rolled back */
  if( pSavepoint ){
    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
    if( !pDone ){
      return SQLITE_NOMEM;
    }
  }

  /* Set the database size back to the value it was before the savepoint 
  ** being reverted was opened.
  */
  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;

  /* Use pPager->journalOff as the effective size of the main rollback
  ** journal.  The actual file might be larger than this in
  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
  ** past pPager->journalOff is off-limits to us.
  */
  szJ = pPager->journalOff;

  /* Begin by rolling back records from the main journal starting at
  ** PagerSavepoint.iOffset and continuing to the next journal header.
  ** There might be records in the main journal that have a page number
  ** greater than the current database size (pPager->dbSize) but those
  ** will be skipped automatically.  Pages are added to pDone as they
  ** are played back.
  */
  if( pSavepoint ){
    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
    pPager->journalOff = pSavepoint->iOffset;
    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
    }
    assert( rc!=SQLITE_DONE );
  }else{
    pPager->journalOff = 0;
  }

  /* Continue rolling back records out of the main journal starting at
  ** the first journal header seen and continuing until the effective end
  ** of the main journal file.  Continue to skip out-of-range pages and
  ** continue adding pages rolled back to pDone.
  */
  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
    u32 ii;            /* Loop counter */
    u32 nJRec = 0;     /* Number of Journal Records */
    u32 dummy;
    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
    assert( rc!=SQLITE_DONE );

    /*
    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
    ** test is related to ticket #2565.  See the discussion in the
    ** pager_playback() function for additional information.
    */
    if( nJRec==0 
     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
    ){
      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
    }
    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
    }
    assert( rc!=SQLITE_DONE );
  }
  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );

  /* Finally,  rollback pages from the sub-journal.  Page that were
  ** previously rolled back out of the main journal (and are hence in pDone)
  ** will be skipped.  Out-of-range pages are also skipped.
  */
  if( pSavepoint ){
    u32 ii;            /* Loop counter */
    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
      assert( offset==ii*(4+pPager->pageSize) );
      rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
    }
    assert( rc!=SQLITE_DONE );
  }

  sqlite3BitvecDestroy(pDone);
  if( rc==SQLITE_OK ){
    pPager->journalOff = szJ;
  }
  return rc;
}

/*
** Change the maximum number of in-memory pages that are allowed.
*/
void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
}

/*
** Adjust the robustness of the database to damage due to OS crashes
** or power failures by changing the number of syncs()s when writing
** the rollback journal.  There are three levels:
**
**    OFF       sqlite3OsSync() is never called.  This is the default
**              for temporary and transient files.
**
**    NORMAL    The journal is synced once before writes begin on the
**              database.  This is normally adequate protection, but
**              it is theoretically possible, though very unlikely,
**              that an inopertune power failure could leave the journal
**              in a state which would cause damage to the database
**              when it is rolled back.
**
**    FULL      The journal is synced twice before writes begin on the
**              database (with some additional information - the nRec field
**              of the journal header - being written in between the two
**              syncs).  If we assume that writing a
**              single disk sector is atomic, then this mode provides
**              assurance that the journal will not be corrupted to the
**              point of causing damage to the database during rollback.
**
** Numeric values associated with these states are OFF==1, NORMAL=2,
** and FULL=3.
*/
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
  if( pPager->noSync ) pPager->needSync = 0;
}
#endif

/*
** The following global variable is incremented whenever the library
** attempts to open a temporary file.  This information is used for
** testing and analysis only.  
*/
#ifdef SQLITE_TEST
int sqlite3_opentemp_count = 0;
#endif

/*
** Open a temporary file.
**
** Write the file descriptor into *pFile. Return SQLITE_OK on success 
** or some other error code if we fail. The OS will automatically 
** delete the temporary file when it is closed.
**
** The flags passed to the VFS layer xOpen() call are those specified
** by parameter vfsFlags ORed with the following:
**
**     SQLITE_OPEN_READWRITE
**     SQLITE_OPEN_CREATE
**     SQLITE_OPEN_EXCLUSIVE
**     SQLITE_OPEN_DELETEONCLOSE
*/
static int pagerOpentemp(
  Pager *pPager,        /* The pager object */
  sqlite3_file *pFile,  /* Write the file descriptor here */
  int vfsFlags          /* Flags passed through to the VFS */
){
  int rc;               /* Return code */

#ifdef SQLITE_TEST
  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
#endif

  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  assert( rc!=SQLITE_OK || isOpen(pFile) );
  return rc;
}

/*
** Set the busy handler function.
**
** The pager invokes the busy-handler if sqlite3OsLock() returns 
** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
** lock. It does *not* invoke the busy handler when upgrading from
** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
** (which occurs during hot-journal rollback). Summary:
**
**   Transition                        | Invokes xBusyHandler
**   --------------------------------------------------------
**   NO_LOCK       -> SHARED_LOCK      | Yes
**   SHARED_LOCK   -> RESERVED_LOCK    | No
**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
**
** If the busy-handler callback returns non-zero, the lock is 
** retried. If it returns zero, then the SQLITE_BUSY error is
** returned to the caller of the pager API function.
*/
void sqlite3PagerSetBusyhandler(
  Pager *pPager,                       /* Pager object */
  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
){  
  pPager->xBusyHandler = xBusyHandler;
  pPager->pBusyHandlerArg = pBusyHandlerArg;
}

/*
** Report the current page size and number of reserved bytes back
** to the codec.
*/
#ifdef SQLITE_HAS_CODEC
static void pagerReportSize(Pager *pPager){
  if( pPager->xCodecSizeChng ){
    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
                           (int)pPager->nReserve);
  }
}
#else
# define pagerReportSize(X)     /* No-op if we do not support a codec */
#endif

/*
** Change the page size used by the Pager object. The new page size 
** is passed in *pPageSize.
**
** If the pager is in the error state when this function is called, it
** is a no-op. The value returned is the error state error code (i.e. 
** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
**
** Otherwise, if all of the following are true:
**
**   * the new page size (value of *pPageSize) is valid (a power 
**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
**
**   * there are no outstanding page references, and
**
**   * the database is either not an in-memory database or it is
**     an in-memory database that currently consists of zero pages.
**
** then the pager object page size is set to *pPageSize.
**
** If the page size is changed, then this function uses sqlite3PagerMalloc() 
** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
** In all other cases, SQLITE_OK is returned.
**
** If the page size is not changed, either because one of the enumerated
** conditions above is not true, the pager was in error state when this
** function was called, or because the memory allocation attempt failed, 
** then *pPageSize is set to the old, retained page size before returning.
*/
int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
  int rc = pPager->errCode;

  if( rc==SQLITE_OK ){
    u16 pageSize = *pPageSize;
    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
    if( (pPager->memDb==0 || pPager->dbSize==0)
     && sqlite3PcacheRefCount(pPager->pPCache)==0 
     && pageSize && pageSize!=pPager->pageSize 
    ){
      char *pNew = (char *)sqlite3PageMalloc(pageSize);
      if( !pNew ){
        rc = SQLITE_NOMEM;
      }else{
        pager_reset(pPager);
        pPager->pageSize = pageSize;
        sqlite3PageFree(pPager->pTmpSpace);
        pPager->pTmpSpace = pNew;
        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
      }
    }
    *pPageSize = (u16)pPager->pageSize;
    if( nReserve<0 ) nReserve = pPager->nReserve;
    assert( nReserve>=0 && nReserve<1000 );
    pPager->nReserve = (i16)nReserve;
    pagerReportSize(pPager);
  }
  return rc;
}

/*
** Return a pointer to the "temporary page" buffer held internally
** by the pager.  This is a buffer that is big enough to hold the
** entire content of a database page.  This buffer is used internally
** during rollback and will be overwritten whenever a rollback
** occurs.  But other modules are free to use it too, as long as
** no rollbacks are happening.
*/
void *sqlite3PagerTempSpace(Pager *pPager){
  return pPager->pTmpSpace;
}

/*
** Attempt to set the maximum database page count if mxPage is positive. 
** Make no changes if mxPage is zero or negative.  And never reduce the
** maximum page count below the current size of the database.
**
** Regardless of mxPage, return the current maximum page count.
*/
int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  if( mxPage>0 ){
    pPager->mxPgno = mxPage;
  }
  sqlite3PagerPagecount(pPager, 0);
  return pPager->mxPgno;
}

/*
** The following set of routines are used to disable the simulated
** I/O error mechanism.  These routines are used to avoid simulated
** errors in places where we do not care about errors.
**
** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
** and generate no code.
*/
#ifdef SQLITE_TEST
extern int sqlite3_io_error_pending;
extern int sqlite3_io_error_hit;
static int saved_cnt;
void disable_simulated_io_errors(void){
  saved_cnt = sqlite3_io_error_pending;
  sqlite3_io_error_pending = -1;
}
void enable_simulated_io_errors(void){
  sqlite3_io_error_pending = saved_cnt;
}
#else
# define disable_simulated_io_errors()
# define enable_simulated_io_errors()
#endif

/*
** Read the first N bytes from the beginning of the file into memory
** that pDest points to. 
**
** If the pager was opened on a transient file (zFilename==""), or
** opened on a file less than N bytes in size, the output buffer is
** zeroed and SQLITE_OK returned. The rationale for this is that this 
** function is used to read database headers, and a new transient or
** zero sized database has a header than consists entirely of zeroes.
**
** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
** the error code is returned to the caller and the contents of the
** output buffer undefined.
*/
int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  int rc = SQLITE_OK;
  memset(pDest, 0, N);
  assert( isOpen(pPager->fd) || pPager->tempFile );
  if( isOpen(pPager->fd) ){
    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
    if( rc==SQLITE_IOERR_SHORT_READ ){
      rc = SQLITE_OK;
    }
  }
  return rc;
}

/*
** Return the total number of pages in the database file associated 
** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
** However, if the file is between 1 and <page-size> bytes in size, then 
** this is considered a 1 page file.
**
** If the pager is in error state when this function is called, then the
** error state error code is returned and *pnPage left unchanged. Or,
** if the file system has to be queried for the size of the file and
** the query attempt returns an IO error, the IO error code is returned
** and *pnPage is left unchanged.
**
** Otherwise, if everything is successful, then SQLITE_OK is returned
** and *pnPage is set to the number of pages in the database.
*/
int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  Pgno nPage;               /* Value to return via *pnPage */

  /* If the pager is already in the error state, return the error code. */
  if( pPager->errCode ){
    return pPager->errCode;
  }

  /* Determine the number of pages in the file. Store this in nPage. */
  if( pPager->dbSizeValid ){
    nPage = pPager->dbSize;
  }else{
    int rc;                 /* Error returned by OsFileSize() */
    i64 n = 0;              /* File size in bytes returned by OsFileSize() */

    assert( isOpen(pPager->fd) || pPager->tempFile );
    if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
      pager_error(pPager, rc);
      return rc;
    }
    if( n>0 && n<pPager->pageSize ){
      nPage = 1;
    }else{
      nPage = (Pgno)(n / pPager->pageSize);
    }
    if( pPager->state!=PAGER_UNLOCK ){
      pPager->dbSize = nPage;
      pPager->dbFileSize = nPage;
      pPager->dbSizeValid = 1;
    }
  }

  /* If the current number of pages in the file is greater than the 
  ** configured maximum pager number, increase the allowed limit so
  ** that the file can be read.
  */
  if( nPage>pPager->mxPgno ){
    pPager->mxPgno = (Pgno)nPage;
  }

  /* Set the output variable and return SQLITE_OK */
  if( pnPage ){
    *pnPage = nPage;
  }
  return SQLITE_OK;
}


/*
** Try to obtain a lock of type locktype on the database file. If
** a similar or greater lock is already held, this function is a no-op
** (returning SQLITE_OK immediately).
**
** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
** the busy callback if the lock is currently not available. Repeat 
** until the busy callback returns false or until the attempt to 
** obtain the lock succeeds.
**
** Return SQLITE_OK on success and an error code if we cannot obtain
** the lock. If the lock is obtained successfully, set the Pager.state 
** variable to locktype before returning.
*/
static int pager_wait_on_lock(Pager *pPager, int locktype){
  int rc;                              /* Return code */

  /* The OS lock values must be the same as the Pager lock values */
  assert( PAGER_SHARED==SHARED_LOCK );
  assert( PAGER_RESERVED==RESERVED_LOCK );
  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );

  /* If the file is currently unlocked then the size must be unknown */
  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );

  /* Check that this is either a no-op (because the requested lock is 
  ** already held, or one of the transistions that the busy-handler
  ** may be invoked during, according to the comment above
  ** sqlite3PagerSetBusyhandler().
  */
  assert( (pPager->state>=locktype)
       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
  );

  if( pPager->state>=locktype ){
    rc = SQLITE_OK;
  }else{
    do {
      rc = sqlite3OsLock(pPager->fd, locktype);
    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
    if( rc==SQLITE_OK ){
      pPager->state = (u8)locktype;
      IOTRACE(("LOCK %p %d\n", pPager, locktype))
    }
  }
  return rc;
}

/*
** Function assertTruncateConstraint(pPager) checks that one of the 
** following is true for all dirty pages currently in the page-cache:
**
**   a) The page number is less than or equal to the size of the 
**      current database image, in pages, OR
**
**   b) if the page content were written at this time, it would not
**      be necessary to write the current content out to the sub-journal
**      (as determined by function subjRequiresPage()).
**
** If the condition asserted by this function were not true, and the
** dirty page were to be discarded from the cache via the pagerStress()
** routine, pagerStress() would not write the current page content to
** the database file. If a savepoint transaction were rolled back after
** this happened, the correct behaviour would be to restore the current
** content of the page. However, since this content is not present in either
** the database file or the portion of the rollback journal and 
** sub-journal rolled back the content could not be restored and the
** database image would become corrupt. It is therefore fortunate that 
** this circumstance cannot arise.
*/
#if defined(SQLITE_DEBUG)
static void assertTruncateConstraintCb(PgHdr *pPg){
  assert( pPg->flags&PGHDR_DIRTY );
  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
}
static void assertTruncateConstraint(Pager *pPager){
  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
}
#else
# define assertTruncateConstraint(pPager)
#endif

/*
** Truncate the in-memory database file image to nPage pages. This 
** function does not actually modify the database file on disk. It 
** just sets the internal state of the pager object so that the 
** truncation will be done when the current transaction is committed.
*/
void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  assert( pPager->dbSizeValid );
  assert( pPager->dbSize>=nPage );
  assert( pPager->state>=PAGER_RESERVED );
  pPager->dbSize = nPage;
  assertTruncateConstraint(pPager);
}

/*
** Shutdown the page cache.  Free all memory and close all files.
**
** If a transaction was in progress when this routine is called, that
** transaction is rolled back.  All outstanding pages are invalidated
** and their memory is freed.  Any attempt to use a page associated
** with this page cache after this function returns will likely
** result in a coredump.
**
** This function always succeeds. If a transaction is active an attempt
** is made to roll it back. If an error occurs during the rollback 
** a hot journal may be left in the filesystem but no error is returned
** to the caller.
*/
int sqlite3PagerClose(Pager *pPager){
  disable_simulated_io_errors();
  sqlite3BeginBenignMalloc();
  pPager->errCode = 0;
  pPager->exclusiveMode = 0;
  pager_reset(pPager);
  if( MEMDB ){
    pager_unlock(pPager);
  }else{
    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
    ** call which may be made from within pagerUnlockAndRollback(). If it
    ** is not -1, then the unsynced portion of an open journal file may
    ** be played back into the database. If a power failure occurs while
    ** this is happening, the database may become corrupt.
    */
    pPager->journalHdr = -1;
    pagerUnlockAndRollback(pPager);
  }
  sqlite3EndBenignMalloc();
  enable_simulated_io_errors();
  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  IOTRACE(("CLOSE %p\n", pPager))
  sqlite3OsClose(pPager->fd);
  sqlite3PageFree(pPager->pTmpSpace);
  sqlite3PcacheClose(pPager->pPCache);

#ifdef SQLITE_HAS_CODEC
  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
#endif

  assert( !pPager->aSavepoint && !pPager->pInJournal );
  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );

  sqlite3_free(pPager);
  return SQLITE_OK;
}

#if !defined(NDEBUG) || defined(SQLITE_TEST)
/*
** Return the page number for page pPg.
*/
Pgno sqlite3PagerPagenumber(DbPage *pPg){
  return pPg->pgno;
}
#endif

/*
** Increment the reference count for page pPg.
*/
void sqlite3PagerRef(DbPage *pPg){
  sqlite3PcacheRef(pPg);
}

/*
** Sync the journal. In other words, make sure all the pages that have
** been written to the journal have actually reached the surface of the
** disk and can be restored in the event of a hot-journal rollback.
**
** If the Pager.needSync flag is not set, then this function is a
** no-op. Otherwise, the actions required depend on the journal-mode
** and the device characteristics of the the file-system, as follows:
**
**   * If the journal file is an in-memory journal file, no action need
**     be taken.
**
**   * Otherwise, if the device does not support the SAFE_APPEND property,
**     then the nRec field of the most recently written journal header
**     is updated to contain the number of journal records that have
**     been written following it. If the pager is operating in full-sync
**     mode, then the journal file is synced before this field is updated.
**
**   * If the device does not support the SEQUENTIAL property, then 
**     journal file is synced.
**
** Or, in pseudo-code:
**
**   if( NOT <in-memory journal> ){
**     if( NOT SAFE_APPEND ){
**       if( <full-sync mode> ) xSync(<journal file>);
**       <update nRec field>
**     } 
**     if( NOT SEQUENTIAL ) xSync(<journal file>);
**   }
**
** The Pager.needSync flag is never be set for temporary files, or any
** file operating in no-sync mode (Pager.noSync set to non-zero).
**
** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
** page currently held in memory before returning SQLITE_OK. If an IO
** error is encountered, then the IO error code is returned to the caller.
*/
static int syncJournal(Pager *pPager){
  if( pPager->needSync ){
    assert( !pPager->tempFile );
    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
      int rc;                              /* Return code */
      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
      assert( isOpen(pPager->jfd) );

      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
        /* This block deals with an obscure problem. If the last connection
        ** that wrote to this database was operating in persistent-journal
        ** mode, then the journal file may at this point actually be larger
        ** than Pager.journalOff bytes. If the next thing in the journal
        ** file happens to be a journal-header (written as part of the
        ** previous connections transaction), and a crash or power-failure 
        ** occurs after nRec is updated but before this connection writes 
        ** anything else to the journal file (or commits/rolls back its 
        ** transaction), then SQLite may become confused when doing the 
        ** hot-journal rollback following recovery. It may roll back all
        ** of this connections data, then proceed to rolling back the old,
        ** out-of-date data that follows it. Database corruption.
        **
        ** To work around this, if the journal file does appear to contain
        ** a valid header following Pager.journalOff, then write a 0x00
        ** byte to the start of it to prevent it from being recognized.
        **
        ** Variable iNextHdrOffset is set to the offset at which this
        ** problematic header will occur, if it exists. aMagic is used 
        ** as a temporary buffer to inspect the first couple of bytes of
        ** the potential journal header.
        */
        i64 iNextHdrOffset;
        u8 aMagic[8];
	u8 zHeader[sizeof(aJournalMagic)+4];

	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);

        iNextHdrOffset = journalHdrOffset(pPager);
        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
          static const u8 zerobyte = 0;
          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
        }
        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
          return rc;
        }

        /* Write the nRec value into the journal file header. If in
        ** full-synchronous mode, sync the journal first. This ensures that
        ** all data has really hit the disk before nRec is updated to mark
        ** it as a candidate for rollback.
        **
        ** This is not required if the persistent media supports the
        ** SAFE_APPEND property. Because in this case it is not possible 
        ** for garbage data to be appended to the file, the nRec field
        ** is populated with 0xFFFFFFFF when the journal header is written
        ** and never needs to be updated.
        */
        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
          IOTRACE(("JSYNC %p\n", pPager))
          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
          if( rc!=SQLITE_OK ) return rc;
        }
        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
        rc = sqlite3OsWrite(
            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
	);
        if( rc!=SQLITE_OK ) return rc;
      }
      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
        IOTRACE(("JSYNC %p\n", pPager))
        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
        );
        if( rc!=SQLITE_OK ) return rc;
      }
    }

    /* The journal file was just successfully synced. Set Pager.needSync 
    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
    */
    pPager->needSync = 0;
    pPager->journalStarted = 1;
    sqlite3PcacheClearSyncFlags(pPager->pPCache);
  }

  return SQLITE_OK;
}

/*
** The argument is the first in a linked list of dirty pages connected
** by the PgHdr.pDirty pointer. This function writes each one of the
** in-memory pages in the list to the database file. The argument may
** be NULL, representing an empty list. In this case this function is
** a no-op.
**
** The pager must hold at least a RESERVED lock when this function
** is called. Before writing anything to the database file, this lock
** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
** SQLITE_BUSY is returned and no data is written to the database file.
** 
** If the pager is a temp-file pager and the actual file-system file
** is not yet open, it is created and opened before any data is 
** written out.
**
** Once the lock has been upgraded and, if necessary, the file opened,
** the pages are written out to the database file in list order. Writing
** a page is skipped if it meets either of the following criteria:
**
**   * The page number is greater than Pager.dbSize, or
**   * The PGHDR_DONT_WRITE flag is set on the page.
**
** If writing out a page causes the database file to grow, Pager.dbFileSize
** is updated accordingly. If page 1 is written out, then the value cached
** in Pager.dbFileVers[] is updated to match the new value stored in
** the database file.
**
** If everything is successful, SQLITE_OK is returned. If an IO error 
** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
** be obtained, SQLITE_BUSY is returned.
*/
static int pager_write_pagelist(PgHdr *pList){
  Pager *pPager;                       /* Pager object */
  int rc;                              /* Return code */

  if( NEVER(pList==0) ) return SQLITE_OK;
  pPager = pList->pPager;

  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
  ** database file. If there is already an EXCLUSIVE lock, the following
  ** call is a no-op.
  **
  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
  ** through an intermediate state PENDING.   A PENDING lock prevents new
  ** readers from attaching to the database but is unsufficient for us to
  ** write.  The idea of a PENDING lock is to prevent new readers from
  ** coming in while we wait for existing readers to clear.
  **
  ** While the pager is in the RESERVED state, the original database file
  ** is unchanged and we can rollback without having to playback the
  ** journal into the original database file.  Once we transition to
  ** EXCLUSIVE, it means the database file has been changed and any rollback
  ** will require a journal playback.
  */
  assert( pPager->state>=PAGER_RESERVED );
  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);

  /* If the file is a temp-file has not yet been opened, open it now. It
  ** is not possible for rc to be other than SQLITE_OK if this branch
  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  */
  if( !isOpen(pPager->fd) ){
    assert( pPager->tempFile && rc==SQLITE_OK );
    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  }

  while( rc==SQLITE_OK && pList ){
    Pgno pgno = pList->pgno;

    /* If there are dirty pages in the page cache with page numbers greater
    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
    ** make the file smaller (presumably by auto-vacuum code). Do not write
    ** any such pages to the file.
    **
    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
    ** set (set by sqlite3PagerDontWrite()).
    */
    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
      char *pData;                                   /* Data to write */    

      /* Encode the database */
      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);

      /* Write out the page data. */
      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);

      /* If page 1 was just written, update Pager.dbFileVers to match
      ** the value now stored in the database file. If writing this 
      ** page caused the database file to grow, update dbFileSize. 
      */
      if( pgno==1 ){
        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
      }
      if( pgno>pPager->dbFileSize ){
        pPager->dbFileSize = pgno;
      }

      /* Update any backup objects copying the contents of this pager. */
      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);

      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
                   PAGERID(pPager), pgno, pager_pagehash(pList)));
      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
      PAGER_INCR(sqlite3_pager_writedb_count);
      PAGER_INCR(pPager->nWrite);
    }else{
      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
    }
#ifdef SQLITE_CHECK_PAGES
    pList->pageHash = pager_pagehash(pList);
#endif
    pList = pList->pDirty;
  }

  return rc;
}

/*
** Append a record of the current state of page pPg to the sub-journal. 
** It is the callers responsibility to use subjRequiresPage() to check 
** that it is really required before calling this function.
**
** If successful, set the bit corresponding to pPg->pgno in the bitvecs
** for all open savepoints before returning.
**
** This function returns SQLITE_OK if everything is successful, an IO
** error code if the attempt to write to the sub-journal fails, or 
** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
** bitvec.
*/
static int subjournalPage(PgHdr *pPg){
  int rc = SQLITE_OK;
  Pager *pPager = pPg->pPager;
  if( isOpen(pPager->sjfd) ){
    void *pData = pPg->pData;
    i64 offset = pPager->nSubRec*(4+pPager->pageSize);
    char *pData2;

    CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
    PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  
    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
    rc = write32bits(pPager->sjfd, offset, pPg->pgno);
    if( rc==SQLITE_OK ){
      rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
    }
  }
  if( rc==SQLITE_OK ){
    pPager->nSubRec++;
    assert( pPager->nSavepoint>0 );
    rc = addToSavepointBitvecs(pPager, pPg->pgno);
  }
  return rc;
}


/*
** This function is called by the pcache layer when it has reached some
** soft memory limit. The first argument is a pointer to a Pager object
** (cast as a void*). The pager is always 'purgeable' (not an in-memory
** database). The second argument is a reference to a page that is 
** currently dirty but has no outstanding references. The page
** is always associated with the Pager object passed as the first 
** argument.
**
** The job of this function is to make pPg clean by writing its contents
** out to the database file, if possible. This may involve syncing the
** journal file. 
**
** If successful, sqlite3PcacheMakeClean() is called on the page and
** SQLITE_OK returned. If an IO error occurs while trying to make the
** page clean, the IO error code is returned. If the page cannot be
** made clean for some other reason, but no error occurs, then SQLITE_OK
** is returned by sqlite3PcacheMakeClean() is not called.
*/
static int pagerStress(void *p, PgHdr *pPg){
  Pager *pPager = (Pager *)p;
  int rc = SQLITE_OK;

  assert( pPg->pPager==pPager );
  assert( pPg->flags&PGHDR_DIRTY );

  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
  ** is journalling a set of two or more database pages that are stored
  ** on the same disk sector. Syncing the journal is not allowed while
  ** this is happening as it is important that all members of such a
  ** set of pages are synced to disk together. So, if the page this function
  ** is trying to make clean will require a journal sync and the doNotSync
  ** flag is set, return without doing anything. The pcache layer will
  ** just have to go ahead and allocate a new page buffer instead of
  ** reusing pPg.
  **
  ** Similarly, if the pager has already entered the error state, do not
  ** try to write the contents of pPg to disk.
  */
  if( NEVER(pPager->errCode)
   || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
  ){
    return SQLITE_OK;
  }

  /* Sync the journal file if required. */
  if( pPg->flags&PGHDR_NEED_SYNC ){
    rc = syncJournal(pPager);
    if( rc==SQLITE_OK && pPager->fullSync && 
      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
    ){
      pPager->nRec = 0;
      rc = writeJournalHdr(pPager);
    }
  }

  /* If the page number of this page is larger than the current size of
  ** the database image, it may need to be written to the sub-journal.
  ** This is because the call to pager_write_pagelist() below will not
  ** actually write data to the file in this case.
  **
  ** Consider the following sequence of events:
  **
  **   BEGIN;
  **     <journal page X>
  **     <modify page X>
  **     SAVEPOINT sp;
  **       <shrink database file to Y pages>
  **       pagerStress(page X)
  **     ROLLBACK TO sp;
  **
  ** If (X>Y), then when pagerStress is called page X will not be written
  ** out to the database file, but will be dropped from the cache. Then,
  ** following the "ROLLBACK TO sp" statement, reading page X will read
  ** data from the database file. This will be the copy of page X as it
  ** was when the transaction started, not as it was when "SAVEPOINT sp"
  ** was executed.
  **
  ** The solution is to write the current data for page X into the 
  ** sub-journal file now (if it is not already there), so that it will
  ** be restored to its current value when the "ROLLBACK TO sp" is 
  ** executed.
  */
  if( NEVER(
      rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  ) ){
    rc = subjournalPage(pPg);
  }

  /* Write the contents of the page out to the database file. */
  if( rc==SQLITE_OK ){
    pPg->pDirty = 0;
    rc = pager_write_pagelist(pPg);
  }

  /* Mark the page as clean. */
  if( rc==SQLITE_OK ){
    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
    sqlite3PcacheMakeClean(pPg);
  }

  return pager_error(pPager, rc);
}


/*
** Allocate and initialize a new Pager object and put a pointer to it
** in *ppPager. The pager should eventually be freed by passing it
** to sqlite3PagerClose().
**
** The zFilename argument is the path to the database file to open.
** If zFilename is NULL then a randomly-named temporary file is created
** and used as the file to be cached. Temporary files are be deleted
** automatically when they are closed. If zFilename is ":memory:" then 
** all information is held in cache. It is never written to disk. 
** This can be used to implement an in-memory database.
**
** The nExtra parameter specifies the number of bytes of space allocated
** along with each page reference. This space is available to the user
** via the sqlite3PagerGetExtra() API.
**
** The flags argument is used to specify properties that affect the
** operation of the pager. It should be passed some bitwise combination
** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
**
** The vfsFlags parameter is a bitmask to pass to the flags parameter
** of the xOpen() method of the supplied VFS when opening files. 
**
** If the pager object is allocated and the specified file opened 
** successfully, SQLITE_OK is returned and *ppPager set to point to
** the new pager object. If an error occurs, *ppPager is set to NULL
** and error code returned. This function may return SQLITE_NOMEM
** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
** various SQLITE_IO_XXX errors.
*/
int sqlite3PagerOpen(
  sqlite3_vfs *pVfs,       /* The virtual file system to use */
  Pager **ppPager,         /* OUT: Return the Pager structure here */
  const char *zFilename,   /* Name of the database file to open */
  int nExtra,              /* Extra bytes append to each in-memory page */
  int flags,               /* flags controlling this file */
  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
){
  u8 *pPtr;
  Pager *pPager = 0;       /* Pager object to allocate and return */
  int rc = SQLITE_OK;      /* Return code */
  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
  int memDb = 0;           /* True if this is an in-memory file */
  int readOnly = 0;        /* True if this is a read-only file */
  int journalFileSize;     /* Bytes to allocate for each journal fd */
  char *zPathname = 0;     /* Full path to database file */
  int nPathname = 0;       /* Number of bytes in zPathname */
  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */

  /* Figure out how much space is required for each journal file-handle
  ** (there are two of them, the main journal and the sub-journal). This
  ** is the maximum space required for an in-memory journal file handle 
  ** and a regular journal file-handle. Note that a "regular journal-handle"
  ** may be a wrapper capable of caching the first portion of the journal
  ** file in memory to implement the atomic-write optimization (see 
  ** source file journal.c).
  */
  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  }else{
    journalFileSize = ROUND8(sqlite3MemJournalSize());
  }

  /* Set the output variable to NULL in case an error occurs. */
  *ppPager = 0;

  /* Compute and store the full pathname in an allocated buffer pointed
  ** to by zPathname, length nPathname. Or, if this is a temporary file,
  ** leave both nPathname and zPathname set to 0.
  */
  if( zFilename && zFilename[0] ){
    nPathname = pVfs->mxPathname+1;
    zPathname = sqlite3Malloc(nPathname*2);
    if( zPathname==0 ){
      return SQLITE_NOMEM;
    }
#ifndef SQLITE_OMIT_MEMORYDB
    if( strcmp(zFilename,":memory:")==0 ){
      memDb = 1;
      zPathname[0] = 0;
    }else
#endif
    {
      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
    }

    nPathname = sqlite3Strlen30(zPathname);
    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
      /* This branch is taken when the journal path required by
      ** the database being opened will be more than pVfs->mxPathname
      ** bytes in length. This means the database cannot be opened,
      ** as it will not be possible to open the journal file or even
      ** check for a hot-journal before reading.
      */
      rc = SQLITE_CANTOPEN;
    }
    if( rc!=SQLITE_OK ){
      sqlite3_free(zPathname);
      return rc;
    }
  }

  /* Allocate memory for the Pager structure, PCache object, the
  ** three file descriptors, the database file name and the journal 
  ** file name. The layout in memory is as follows:
  **
  **     Pager object                    (sizeof(Pager) bytes)
  **     PCache object                   (sqlite3PcacheSize() bytes)
  **     Database file handle            (pVfs->szOsFile bytes)
  **     Sub-journal file handle         (journalFileSize bytes)
  **     Main journal file handle        (journalFileSize bytes)
  **     Database file name              (nPathname+1 bytes)
  **     Journal file name               (nPathname+8+1 bytes)
  */
  pPtr = (u8 *)sqlite3MallocZero(
    ROUND8(sizeof(*pPager)) +      /* Pager structure */
    ROUND8(pcacheSize) +           /* PCache object */
    ROUND8(pVfs->szOsFile) +       /* The main db file */
    journalFileSize * 2 +          /* The two journal files */ 
    nPathname + 1 +                /* zFilename */
    nPathname + 8 + 1              /* zJournal */
  );
  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  if( !pPtr ){
    sqlite3_free(zPathname);
    return SQLITE_NOMEM;
  }
  pPager =              (Pager*)(pPtr);
  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
  pPager->zFilename =    (char*)(pPtr += journalFileSize);
  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );

  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  if( zPathname ){
    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
    memcpy(pPager->zFilename, zPathname, nPathname);
    memcpy(pPager->zJournal, zPathname, nPathname);
    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
    sqlite3_free(zPathname);
  }
  pPager->pVfs = pVfs;
  pPager->vfsFlags = vfsFlags;

  /* Open the pager file.
  */
  if( zFilename && zFilename[0] && !memDb ){
    int fout = 0;                    /* VFS flags returned by xOpen() */
    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
    readOnly = (fout&SQLITE_OPEN_READONLY);

    /* If the file was successfully opened for read/write access,
    ** choose a default page size in case we have to create the
    ** database file. The default page size is the maximum of:
    **
    **    + SQLITE_DEFAULT_PAGE_SIZE,
    **    + The value returned by sqlite3OsSectorSize()
    **    + The largest page size that can be written atomically.
    */
    if( rc==SQLITE_OK && !readOnly ){
      setSectorSize(pPager);
      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
      if( szPageDflt<pPager->sectorSize ){
        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
        }else{
          szPageDflt = (u16)pPager->sectorSize;
        }
      }
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
      {
        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
        int ii;
        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
            szPageDflt = ii;
          }
        }
      }
#endif
    }
  }else{
    /* If a temporary file is requested, it is not opened immediately.
    ** In this case we accept the default page size and delay actually
    ** opening the file until the first call to OsWrite().
    **
    ** This branch is also run for an in-memory database. An in-memory
    ** database is the same as a temp-file that is never written out to
    ** disk and uses an in-memory rollback journal.
    */ 
    tempFile = 1;
    pPager->state = PAGER_EXCLUSIVE;
    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  }

  /* The following call to PagerSetPagesize() serves to set the value of 
  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  */
  if( rc==SQLITE_OK ){
    assert( pPager->memDb==0 );
    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
    testcase( rc!=SQLITE_OK );
  }

  /* If an error occurred in either of the blocks above, free the 
  ** Pager structure and close the file.
  */
  if( rc!=SQLITE_OK ){
    assert( !pPager->pTmpSpace );
    sqlite3OsClose(pPager->fd);
    sqlite3_free(pPager);
    return rc;
  }

  /* Initialize the PCache object. */
  assert( nExtra<1000 );
  nExtra = ROUND8(nExtra);
  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);

  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))

  pPager->useJournal = (u8)useJournal;
  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
  /* pPager->stmtOpen = 0; */
  /* pPager->stmtInUse = 0; */
  /* pPager->nRef = 0; */
  pPager->dbSizeValid = (u8)memDb;
  /* pPager->stmtSize = 0; */
  /* pPager->stmtJSize = 0; */
  /* pPager->nPage = 0; */
  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  /* pPager->state = PAGER_UNLOCK; */
  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  /* pPager->errMask = 0; */
  pPager->tempFile = (u8)tempFile;
  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  pPager->exclusiveMode = (u8)tempFile; 
  pPager->changeCountDone = pPager->tempFile;
  pPager->memDb = (u8)memDb;
  pPager->readOnly = (u8)readOnly;
  /* pPager->needSync = 0; */
  assert( useJournal || pPager->tempFile );
  pPager->noSync = pPager->tempFile;
  pPager->fullSync = pPager->noSync ?0:1;
  pPager->sync_flags = SQLITE_SYNC_NORMAL;
  /* pPager->pFirst = 0; */
  /* pPager->pFirstSynced = 0; */
  /* pPager->pLast = 0; */
  pPager->nExtra = (u16)nExtra;
  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  assert( isOpen(pPager->fd) || tempFile );
  setSectorSize(pPager);
  if( !useJournal ){
    pPager->journalMode = PAGER_JOURNALMODE_OFF;
  }else if( memDb ){
    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  }
  /* pPager->xBusyHandler = 0; */
  /* pPager->pBusyHandlerArg = 0; */
  pPager->xReiniter = xReinit;
  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  *ppPager = pPager;
  return SQLITE_OK;
}



/*
** This function is called after transitioning from PAGER_UNLOCK to
** PAGER_SHARED state. It tests if there is a hot journal present in
** the file-system for the given pager. A hot journal is one that 
** needs to be played back. According to this function, a hot-journal
** file exists if the following criteria are met:
**
**   * The journal file exists in the file system, and
**   * No process holds a RESERVED or greater lock on the database file, and
**   * The database file itself is greater than 0 bytes in size, and
**   * The first byte of the journal file exists and is not 0x00.
**
** If the current size of the database file is 0 but a journal file
** exists, that is probably an old journal left over from a prior
** database with the same name. In this case the journal file is
** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
** is returned.
**
** This routine does not check if there is a master journal filename
** at the end of the file. If there is, and that master journal file
** does not exist, then the journal file is not really hot. In this
** case this routine will return a false-positive. The pager_playback()
** routine will discover that the journal file is not really hot and 
** will not roll it back. 
**
** If a hot-journal file is found to exist, *pExists is set to 1 and 
** SQLITE_OK returned. If no hot-journal file is present, *pExists is
** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
** to determine whether or not a hot-journal file exists, the IO error
** code is returned and the value of *pExists is undefined.
*/
static int hasHotJournal(Pager *pPager, int *pExists){
  sqlite3_vfs * const pVfs = pPager->pVfs;
  int rc;                       /* Return code */
  int exists;                   /* True if a journal file is present */

  assert( pPager!=0 );
  assert( pPager->useJournal );
  assert( isOpen(pPager->fd) );
  assert( !isOpen(pPager->jfd) );
  assert( pPager->state <= PAGER_SHARED );

  *pExists = 0;
  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  if( rc==SQLITE_OK && exists ){
    int locked;                 /* True if some process holds a RESERVED lock */

    /* Race condition here:  Another process might have been holding the
    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
    ** call above, but then delete the journal and drop the lock before
    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
    ** is the case, this routine might think there is a hot journal when
    ** in fact there is none.  This results in a false-positive which will
    ** be dealt with by the playback routine.  Ticket #3883.
    */
    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
    if( rc==SQLITE_OK && !locked ){
      int nPage;

      /* Check the size of the database file. If it consists of 0 pages,
      ** then delete the journal file. See the header comment above for 
      ** the reasoning here.  Delete the obsolete journal file under
      ** a RESERVED lock to avoid race conditions and to avoid violating
      ** [H33020].
      */
      rc = sqlite3PagerPagecount(pPager, &nPage);
      if( rc==SQLITE_OK ){
        if( nPage==0 ){
          sqlite3BeginBenignMalloc();
          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
          }
          sqlite3EndBenignMalloc();
        }else{
          /* The journal file exists and no other connection has a reserved
          ** or greater lock on the database file. Now check that there is
          ** at least one non-zero bytes at the start of the journal file.
          ** If there is, then we consider this journal to be hot. If not, 
          ** it can be ignored.
          */
          int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
          if( rc==SQLITE_OK ){
            u8 first = 0;
            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
            if( rc==SQLITE_IOERR_SHORT_READ ){
              rc = SQLITE_OK;
            }
            sqlite3OsClose(pPager->jfd);
            *pExists = (first!=0);
          }else if( rc==SQLITE_CANTOPEN ){
            /* If we cannot open the rollback journal file in order to see if
            ** its has a zero header, that might be due to an I/O error, or
            ** it might be due to the race condition described above and in
            ** ticket #3883.  Either way, assume that the journal is hot.
            ** This might be a false positive.  But if it is, then the
            ** automatic journal playback and recovery mechanism will deal
            ** with it under an EXCLUSIVE lock where we do not need to
            ** worry so much with race conditions.
            */
            *pExists = 1;
            rc = SQLITE_OK;
          }
        }
      }
    }
  }

  return rc;
}

/*
** Read the content for page pPg out of the database file and into 
** pPg->pData. A shared lock or greater must be held on the database
** file before this function is called.
**
** If page 1 is read, then the value of Pager.dbFileVers[] is set to
** the value read from the database file.
**
** If an IO error occurs, then the IO error is returned to the caller.
** Otherwise, SQLITE_OK is returned.
*/
static int readDbPage(PgHdr *pPg){
  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  Pgno pgno = pPg->pgno;       /* Page number to read */
  int rc;                      /* Return code */
  i64 iOffset;                 /* Byte offset of file to read from */

  assert( pPager->state>=PAGER_SHARED && !MEMDB );
  assert( isOpen(pPager->fd) );

  if( NEVER(!isOpen(pPager->fd)) ){
    assert( pPager->tempFile );
    memset(pPg->pData, 0, pPager->pageSize);
    return SQLITE_OK;
  }
  iOffset = (pgno-1)*(i64)pPager->pageSize;
  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  if( rc==SQLITE_IOERR_SHORT_READ ){
    rc = SQLITE_OK;
  }
  if( pgno==1 ){
    u8 *dbFileVers = &((u8*)pPg->pData)[24];
    memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  }
  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);

  PAGER_INCR(sqlite3_pager_readdb_count);
  PAGER_INCR(pPager->nRead);
  IOTRACE(("PGIN %p %d\n", pPager, pgno));
  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
               PAGERID(pPager), pgno, pager_pagehash(pPg)));

  return rc;
}

/*
** This function is called to obtain a shared lock on the database file.
** It is illegal to call sqlite3PagerAcquire() until after this function
** has been successfully called. If a shared-lock is already held when
** this function is called, it is a no-op.
**
** The following operations are also performed by this function.
**
**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
**      on the database file), then an attempt is made to obtain a
**      SHARED lock on the database file. Immediately after obtaining
**      the SHARED lock, the file-system is checked for a hot-journal,
**      which is played back if present. Following any hot-journal 
**      rollback, the contents of the cache are validated by checking
**      the 'change-counter' field of the database file header and
**      discarded if they are found to be invalid.
**
**   2) If the pager is running in exclusive-mode, and there are currently
**      no outstanding references to any pages, and is in the error state,
**      then an attempt is made to clear the error state by discarding
**      the contents of the page cache and rolling back any open journal
**      file.
**
** If the operation described by (2) above is not attempted, and if the
** pager is in an error state other than SQLITE_FULL when this is called,
** the error state error code is returned. It is permitted to read the
** database when in SQLITE_FULL error state.
**
** Otherwise, if everything is successful, SQLITE_OK is returned. If an
** IO error occurs while locking the database, checking for a hot-journal
** file or rolling back a journal file, the IO error code is returned.
*/
int sqlite3PagerSharedLock(Pager *pPager){
  int rc = SQLITE_OK;                /* Return code */
  int isErrorReset = 0;              /* True if recovering from error state */

  /* This routine is only called from b-tree and only when there are no
  ** outstanding pages */
  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }

  /* If this database is in an error-state, now is a chance to clear
  ** the error. Discard the contents of the pager-cache and rollback
  ** any hot journal in the file-system.
  */
  if( pPager->errCode ){
    if( isOpen(pPager->jfd) || pPager->zJournal ){
      isErrorReset = 1;
    }
    pPager->errCode = SQLITE_OK;
    pager_reset(pPager);
  }

  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
    sqlite3_vfs * const pVfs = pPager->pVfs;
    int isHotJournal = 0;
    assert( !MEMDB );
    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
    if( pPager->noReadlock ){
      assert( pPager->readOnly );
      pPager->state = PAGER_SHARED;
    }else{
      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
      if( rc!=SQLITE_OK ){
        assert( pPager->state==PAGER_UNLOCK );
        return pager_error(pPager, rc);
      }
    }
    assert( pPager->state>=SHARED_LOCK );

    /* If a journal file exists, and there is no RESERVED lock on the
    ** database file, then it either needs to be played back or deleted.
    */
    if( !isErrorReset ){
      assert( pPager->state <= PAGER_SHARED );
      rc = hasHotJournal(pPager, &isHotJournal);
      if( rc!=SQLITE_OK ){
        goto failed;
      }
    }
    if( isErrorReset || isHotJournal ){
      /* Get an EXCLUSIVE lock on the database file. At this point it is
      ** important that a RESERVED lock is not obtained on the way to the
      ** EXCLUSIVE lock. If it were, another process might open the
      ** database file, detect the RESERVED lock, and conclude that the
      ** database is safe to read while this process is still rolling the 
      ** hot-journal back.
      ** 
      ** Because the intermediate RESERVED lock is not requested, any
      ** other process attempting to access the database file will get to 
      ** this point in the code and fail to obtain its own EXCLUSIVE lock 
      ** on the database file.
      */
      if( pPager->state<EXCLUSIVE_LOCK ){
        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
        if( rc!=SQLITE_OK ){
          rc = pager_error(pPager, rc);
          goto failed;
        }
        pPager->state = PAGER_EXCLUSIVE;
      }
 
      /* Open the journal for read/write access. This is because in 
      ** exclusive-access mode the file descriptor will be kept open and
      ** possibly used for a transaction later on. On some systems, the
      ** OsTruncate() call used in exclusive-access mode also requires
      ** a read/write file handle.
      */
      if( !isOpen(pPager->jfd) ){
        int res;
        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
        if( rc==SQLITE_OK ){
          if( res ){
            int fout = 0;
            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
            assert( !pPager->tempFile );
            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
              rc = SQLITE_CANTOPEN;
              sqlite3OsClose(pPager->jfd);
            }
          }else{
            /* If the journal does not exist, it usually means that some 
            ** other connection managed to get in and roll it back before 
            ** this connection obtained the exclusive lock above. Or, it 
            ** may mean that the pager was in the error-state when this
            ** function was called and the journal file does not exist.  */
            rc = pager_end_transaction(pPager, 0);
          }
        }
      }
      if( rc!=SQLITE_OK ){
        goto failed;
      }

      /* TODO: Why are these cleared here? Is it necessary? */
      pPager->journalStarted = 0;
      pPager->journalOff = 0;
      pPager->setMaster = 0;
      pPager->journalHdr = 0;
 
      /* Playback and delete the journal.  Drop the database write
      ** lock and reacquire the read lock. Purge the cache before
      ** playing back the hot-journal so that we don't end up with
      ** an inconsistent cache.
      */
      if( isOpen(pPager->jfd) ){
        rc = pager_playback(pPager, 1);
        if( rc!=SQLITE_OK ){
          rc = pager_error(pPager, rc);
          goto failed;
        }
      }
      assert( (pPager->state==PAGER_SHARED)
           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
      );
    }

    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
      /* The shared-lock has just been acquired on the database file
      ** and there are already pages in the cache (from a previous
      ** read or write transaction).  Check to see if the database
      ** has been modified.  If the database has changed, flush the
      ** cache.
      **
      ** Database changes is detected by looking at 15 bytes beginning
      ** at offset 24 into the file.  The first 4 of these 16 bytes are
      ** a 32-bit counter that is incremented with each change.  The
      ** other bytes change randomly with each file change when
      ** a codec is in use.
      ** 
      ** There is a vanishingly small chance that a change will not be 
      ** detected.  The chance of an undetected change is so small that
      ** it can be neglected.
      */
      char dbFileVers[sizeof(pPager->dbFileVers)];
      sqlite3PagerPagecount(pPager, 0);

      if( pPager->errCode ){
        rc = pPager->errCode;
        goto failed;
      }

      assert( pPager->dbSizeValid );
      if( pPager->dbSize>0 ){
        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
        if( rc!=SQLITE_OK ){
          goto failed;
        }
      }else{
        memset(dbFileVers, 0, sizeof(dbFileVers));
      }

      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
        pager_reset(pPager);
      }
    }
    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
  }

 failed:
  if( rc!=SQLITE_OK ){
    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
    pager_unlock(pPager);
  }
  return rc;
}

/*
** If the reference count has reached zero, rollback any active
** transaction and unlock the pager.
**
** Except, in locking_mode=EXCLUSIVE when there is nothing to in
** the rollback journal, the unlock is not performed and there is
** nothing to rollback, so this routine is a no-op.
*/ 
static void pagerUnlockIfUnused(Pager *pPager){
  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
   && (!pPager->exclusiveMode || pPager->journalOff>0) 
  ){
    pagerUnlockAndRollback(pPager);
  }
}

/*
** Acquire a reference to page number pgno in pager pPager (a page
** reference has type DbPage*). If the requested reference is 
** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
**
** If the requested page is already in the cache, it is returned. 
** Otherwise, a new page object is allocated and populated with data
** read from the database file. In some cases, the pcache module may
** choose not to allocate a new page object and may reuse an existing
** object with no outstanding references.
**
** The extra data appended to a page is always initialized to zeros the 
** first time a page is loaded into memory. If the page requested is 
** already in the cache when this function is called, then the extra
** data is left as it was when the page object was last used.
**
** If the database image is smaller than the requested page or if a 
** non-zero value is passed as the noContent parameter and the 
** requested page is not already stored in the cache, then no 
** actual disk read occurs. In this case the memory image of the 
** page is initialized to all zeros. 
**
** If noContent is true, it means that we do not care about the contents
** of the page. This occurs in two seperate scenarios:
**
**   a) When reading a free-list leaf page from the database, and
**
**   b) When a savepoint is being rolled back and we need to load
**      a new page into the cache to populate with the data read
**      from the savepoint journal.
**
** If noContent is true, then the data returned is zeroed instead of
** being read from the database. Additionally, the bits corresponding
** to pgno in Pager.pInJournal (bitvec of pages already written to the
** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
** savepoints are set. This means if the page is made writable at any
** point in the future, using a call to sqlite3PagerWrite(), its contents
** will not be journaled. This saves IO.
**
** The acquisition might fail for several reasons.  In all cases,
** an appropriate error code is returned and *ppPage is set to NULL.
**
** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
** to find a page in the in-memory cache first.  If the page is not already
** in memory, this routine goes to disk to read it in whereas Lookup()
** just returns 0.  This routine acquires a read-lock the first time it
** has to go to disk, and could also playback an old journal if necessary.
** Since Lookup() never goes to disk, it never has to deal with locks
** or journal files.
*/
int sqlite3PagerAcquire(
  Pager *pPager,      /* The pager open on the database file */
  Pgno pgno,          /* Page number to fetch */
  DbPage **ppPage,    /* Write a pointer to the page here */
  int noContent       /* Do not bother reading content from disk if true */
){
  int rc;
  PgHdr *pPg;

  assert( assert_pager_state(pPager) );
  assert( pPager->state>PAGER_UNLOCK );

  if( pgno==0 ){
    return SQLITE_CORRUPT_BKPT;
  }

  /* If the pager is in the error state, return an error immediately. 
  ** Otherwise, request the page from the PCache layer. */
  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
    rc = pPager->errCode;
  }else{
    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  }

  if( rc!=SQLITE_OK ){
    /* Either the call to sqlite3PcacheFetch() returned an error or the
    ** pager was already in the error-state when this function was called.
    ** Set pPg to 0 and jump to the exception handler.  */
    pPg = 0;
    goto pager_acquire_err;
  }
  assert( (*ppPage)->pgno==pgno );
  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );

  if( (*ppPage)->pPager ){
    /* In this case the pcache already contains an initialized copy of
    ** the page. Return without further ado.  */
    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
    PAGER_INCR(pPager->nHit);
    return SQLITE_OK;

  }else{
    /* The pager cache has created a new page. Its content needs to 
    ** be initialized.  */
    int nMax;

    PAGER_INCR(pPager->nMiss);
    pPg = *ppPage;
    pPg->pPager = pPager;

    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
    ** number greater than this, or the unused locking-page, is requested. */
    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
      rc = SQLITE_CORRUPT_BKPT;
      goto pager_acquire_err;
    }

    rc = sqlite3PagerPagecount(pPager, &nMax);
    if( rc!=SQLITE_OK ){
      goto pager_acquire_err;
    }

    if( nMax<(int)pgno || MEMDB || noContent ){
      if( pgno>pPager->mxPgno ){
	rc = SQLITE_FULL;
	goto pager_acquire_err;
      }
      if( noContent ){
        /* Failure to set the bits in the InJournal bit-vectors is benign.
        ** It merely means that we might do some extra work to journal a 
        ** page that does not need to be journaled.  Nevertheless, be sure 
        ** to test the case where a malloc error occurs while trying to set 
        ** a bit in a bit vector.
        */
        sqlite3BeginBenignMalloc();
        if( pgno<=pPager->dbOrigSize ){
          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
          testcase( rc==SQLITE_NOMEM );
        }
        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
        testcase( rc==SQLITE_NOMEM );
        sqlite3EndBenignMalloc();
      }else{
        memset(pPg->pData, 0, pPager->pageSize);
      }
      IOTRACE(("ZERO %p %d\n", pPager, pgno));
    }else{
      assert( pPg->pPager==pPager );
      rc = readDbPage(pPg);
      if( rc!=SQLITE_OK ){
        goto pager_acquire_err;
      }
    }
#ifdef SQLITE_CHECK_PAGES
    pPg->pageHash = pager_pagehash(pPg);
#endif
  }

  return SQLITE_OK;

pager_acquire_err:
  assert( rc!=SQLITE_OK );
  if( pPg ){
    sqlite3PcacheDrop(pPg);
  }
  pagerUnlockIfUnused(pPager);

  *ppPage = 0;
  return rc;
}

/*
** Acquire a page if it is already in the in-memory cache.  Do
** not read the page from disk.  Return a pointer to the page,
** or 0 if the page is not in cache. Also, return 0 if the 
** pager is in PAGER_UNLOCK state when this function is called,
** or if the pager is in an error state other than SQLITE_FULL.
**
** See also sqlite3PagerGet().  The difference between this routine
** and sqlite3PagerGet() is that _get() will go to the disk and read
** in the page if the page is not already in cache.  This routine
** returns NULL if the page is not in cache or if a disk I/O error 
** has ever happened.
*/
DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  PgHdr *pPg = 0;
  assert( pPager!=0 );
  assert( pgno!=0 );
  assert( pPager->pPCache!=0 );
  assert( pPager->state > PAGER_UNLOCK );
  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  return pPg;
}

/*
** Release a page reference.
**
** If the number of references to the page drop to zero, then the
** page is added to the LRU list.  When all references to all pages
** are released, a rollback occurs and the lock on the database is
** removed.
*/
void sqlite3PagerUnref(DbPage *pPg){
  if( pPg ){
    Pager *pPager = pPg->pPager;
    sqlite3PcacheRelease(pPg);
    pagerUnlockIfUnused(pPager);
  }
}

/*
** If the main journal file has already been opened, ensure that the
** sub-journal file is open too. If the main journal is not open,
** this function is a no-op.
**
** SQLITE_OK is returned if everything goes according to plan. 
** An SQLITE_IOERR_XXX error code is returned if a call to 
** sqlite3OsOpen() fails.
*/
static int openSubJournal(Pager *pPager){
  int rc = SQLITE_OK;
  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
      sqlite3MemJournalOpen(pPager->sjfd);
    }else{
      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
    }
  }
  return rc;
}

/*
** This function is called at the start of every write transaction.
** There must already be a RESERVED or EXCLUSIVE lock on the database 
** file when this routine is called.
**
** Open the journal file for pager pPager and write a journal header
** to the start of it. If there are active savepoints, open the sub-journal
** as well. This function is only used when the journal file is being 
** opened to write a rollback log for a transaction. It is not used 
** when opening a hot journal file to roll it back.
**
** If the journal file is already open (as it may be in exclusive mode),
** then this function just writes a journal header to the start of the
** already open file. 
**
** Whether or not the journal file is opened by this function, the
** Pager.pInJournal bitvec structure is allocated.
**
** Return SQLITE_OK if everything is successful. Otherwise, return 
** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
** an IO error code if opening or writing the journal file fails.
*/
static int pager_open_journal(Pager *pPager){
  int rc = SQLITE_OK;                        /* Return code */
  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */

  assert( pPager->state>=PAGER_RESERVED );
  assert( pPager->useJournal );
  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
  assert( pPager->pInJournal==0 );
  
  /* If already in the error state, this function is a no-op.  But on
  ** the other hand, this routine is never called if we are already in
  ** an error state. */
  if( NEVER(pPager->errCode) ) return pPager->errCode;

  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
  ** the call to PagerPagecount() can be removed.
  */
  testcase( pPager->dbSizeValid==0 );
  sqlite3PagerPagecount(pPager, 0);

  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  if( pPager->pInJournal==0 ){
    return SQLITE_NOMEM;
  }

  /* Open the journal file if it is not already open. */
  if( !isOpen(pPager->jfd) ){
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      sqlite3MemJournalOpen(pPager->jfd);
    }else{
      const int flags =                   /* VFS flags to open journal file */
        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
        (pPager->tempFile ? 
          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
          (SQLITE_OPEN_MAIN_JOURNAL)
        );
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
      rc = sqlite3JournalOpen(
          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
      );
#else
      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
#endif
    }
    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  }


  /* Write the first journal header to the journal file and open 
  ** the sub-journal if necessary.
  */
  if( rc==SQLITE_OK ){
    /* TODO: Check if all of these are really required. */
    pPager->dbOrigSize = pPager->dbSize;
    pPager->journalStarted = 0;
    pPager->needSync = 0;
    pPager->nRec = 0;
    pPager->journalOff = 0;
    pPager->setMaster = 0;
    pPager->journalHdr = 0;
    rc = writeJournalHdr(pPager);
  }
  if( rc==SQLITE_OK && pPager->nSavepoint ){
    rc = openSubJournal(pPager);
  }

  if( rc!=SQLITE_OK ){
    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;
  }
  return rc;
}

/*
** Begin a write-transaction on the specified pager object. If a 
** write-transaction has already been opened, this function is a no-op.
**
** If the exFlag argument is false, then acquire at least a RESERVED
** lock on the database file. If exFlag is true, then acquire at least
** an EXCLUSIVE lock. If such a lock is already held, no locking 
** functions need be called.
**
** If this is not a temporary or in-memory file and, the journal file is 
** opened if it has not been already. For a temporary file, the opening 
** of the journal file is deferred until there is an actual need to 
** write to the journal. TODO: Why handle temporary files differently?
**
** If the journal file is opened (or if it is already open), then a
** journal-header is written to the start of it.
**
** If the subjInMemory argument is non-zero, then any sub-journal opened
** within this transaction will be opened as an in-memory file. This
** has no effect if the sub-journal is already opened (as it may be when
** running in exclusive mode) or if the transaction does not require a
** sub-journal. If the subjInMemory argument is zero, then any required
** sub-journal is implemented in-memory if pPager is an in-memory database, 
** or using a temporary file otherwise.
*/
int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  int rc = SQLITE_OK;
  assert( pPager->state!=PAGER_UNLOCK );
  pPager->subjInMemory = (u8)subjInMemory;
  if( pPager->state==PAGER_SHARED ){
    assert( pPager->pInJournal==0 );
    assert( !MEMDB && !pPager->tempFile );

    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
    ** lock, but not when obtaining the RESERVED lock.
    */
    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
    if( rc==SQLITE_OK ){
      pPager->state = PAGER_RESERVED;
      if( exFlag ){
        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
      }
    }

    /* If the required locks were successfully obtained, open the journal
    ** file and write the first journal-header to it.
    */
    if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
      rc = pager_open_journal(pPager);
    }
  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
    /* This happens when the pager was in exclusive-access mode the last
    ** time a (read or write) transaction was successfully concluded
    ** by this connection. Instead of deleting the journal file it was 
    ** kept open and either was truncated to 0 bytes or its header was
    ** overwritten with zeros.
    */
    assert( pPager->nRec==0 );
    assert( pPager->dbOrigSize==0 );
    assert( pPager->pInJournal==0 );
    rc = pager_open_journal(pPager);
  }

  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
  if( rc!=SQLITE_OK ){
    assert( !pPager->dbModified );
    /* Ignore any IO error that occurs within pager_end_transaction(). The
    ** purpose of this call is to reset the internal state of the pager
    ** sub-system. It doesn't matter if the journal-file is not properly
    ** finalized at this point (since it is not a valid journal file anyway).
    */
    pager_end_transaction(pPager, 0);
  }
  return rc;
}

/*
** Mark a single data page as writeable. The page is written into the 
** main journal or sub-journal as required. If the page is written into
** one of the journals, the corresponding bit is set in the 
** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
** of any open savepoints as appropriate.
*/
static int pager_write(PgHdr *pPg){
  void *pData = pPg->pData;
  Pager *pPager = pPg->pPager;
  int rc = SQLITE_OK;

  /* This routine is not called unless a transaction has already been
  ** started.
  */
  assert( pPager->state>=PAGER_RESERVED );

  /* If an error has been previously detected, we should not be
  ** calling this routine.  Repeat the error for robustness.
  */
  if( NEVER(pPager->errCode) )  return pPager->errCode;

  /* Higher-level routines never call this function if database is not
  ** writable.  But check anyway, just for robustness. */
  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;

  assert( !pPager->setMaster );

  CHECK_PAGE(pPg);

  /* Mark the page as dirty.  If the page has already been written
  ** to the journal then we can return right away.
  */
  sqlite3PcacheMakeDirty(pPg);
  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
    pPager->dbModified = 1;
  }else{

    /* If we get this far, it means that the page needs to be
    ** written to the transaction journal or the ckeckpoint journal
    ** or both.
    **
    ** Higher level routines should have already started a transaction,
    ** which means they have acquired the necessary locks and opened
    ** a rollback journal.  Double-check to makes sure this is the case.
    */
    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
    if( NEVER(rc!=SQLITE_OK) ){
      return rc;
    }
    if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
      assert( pPager->useJournal );
      rc = pager_open_journal(pPager);
      if( rc!=SQLITE_OK ) return rc;
    }
    pPager->dbModified = 1;
  
    /* The transaction journal now exists and we have a RESERVED or an
    ** EXCLUSIVE lock on the main database file.  Write the current page to
    ** the transaction journal if it is not there already.
    */
    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
      if( pPg->pgno<=pPager->dbOrigSize ){
        u32 cksum;
        char *pData2;

        /* We should never write to the journal file the page that
        ** contains the database locks.  The following assert verifies
        ** that we do not. */
        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
        cksum = pager_cksum(pPager, (u8*)pData2);
        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
        if( rc==SQLITE_OK ){
          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
                              pPager->journalOff + 4);
          pPager->journalOff += pPager->pageSize+4;
        }
        if( rc==SQLITE_OK ){
          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
          pPager->journalOff += 4;
        }
        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
                 pPager->journalOff, pPager->pageSize));
        PAGER_INCR(sqlite3_pager_writej_count);
        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
             PAGERID(pPager), pPg->pgno, 
             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));

        /* Even if an IO or diskfull error occurred while journalling the
        ** page in the block above, set the need-sync flag for the page.
        ** Otherwise, when the transaction is rolled back, the logic in
        ** playback_one_page() will think that the page needs to be restored
        ** in the database file. And if an IO error occurs while doing so,
        ** then corruption may follow.
        */
        if( !pPager->noSync ){
          pPg->flags |= PGHDR_NEED_SYNC;
          pPager->needSync = 1;
        }

        /* An error has occurred writing to the journal file. The 
        ** transaction will be rolled back by the layer above.
        */
        if( rc!=SQLITE_OK ){
          return rc;
        }

        pPager->nRec++;
        assert( pPager->pInJournal!=0 );
        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
        testcase( rc==SQLITE_NOMEM );
        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
        if( rc!=SQLITE_OK ){
          assert( rc==SQLITE_NOMEM );
          return rc;
        }
      }else{
        if( !pPager->journalStarted && !pPager->noSync ){
          pPg->flags |= PGHDR_NEED_SYNC;
          pPager->needSync = 1;
        }
        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
                PAGERID(pPager), pPg->pgno,
               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
      }
    }
  
    /* If the statement journal is open and the page is not in it,
    ** then write the current page to the statement journal.  Note that
    ** the statement journal format differs from the standard journal format
    ** in that it omits the checksums and the header.
    */
    if( subjRequiresPage(pPg) ){
      rc = subjournalPage(pPg);
    }
  }

  /* Update the database size and return.
  */
  assert( pPager->state>=PAGER_SHARED );
  if( pPager->dbSize<pPg->pgno ){
    pPager->dbSize = pPg->pgno;
  }
  return rc;
}

/*
** Mark a data page as writeable. This routine must be called before 
** making changes to a page. The caller must check the return value 
** of this function and be careful not to change any page data unless 
** this routine returns SQLITE_OK.
**
** The difference between this function and pager_write() is that this
** function also deals with the special case where 2 or more pages
** fit on a single disk sector. In this case all co-resident pages
** must have been written to the journal file before returning.
**
** If an error occurs, SQLITE_NOMEM or an IO error code is returned
** as appropriate. Otherwise, SQLITE_OK.
*/
int sqlite3PagerWrite(DbPage *pDbPage){
  int rc = SQLITE_OK;

  PgHdr *pPg = pDbPage;
  Pager *pPager = pPg->pPager;
  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);

  if( nPagePerSector>1 ){
    Pgno nPageCount;          /* Total number of pages in database file */
    Pgno pg1;                 /* First page of the sector pPg is located on. */
    int nPage;                /* Number of pages starting at pg1 to journal */
    int ii;                   /* Loop counter */
    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */

    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
    ** header to be written between the pages journaled by this function.
    */
    assert( !MEMDB );
    assert( pPager->doNotSync==0 );
    pPager->doNotSync = 1;

    /* This trick assumes that both the page-size and sector-size are
    ** an integer power of 2. It sets variable pg1 to the identifier
    ** of the first page of the sector pPg is located on.
    */
    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;

    sqlite3PagerPagecount(pPager, (int *)&nPageCount);
    if( pPg->pgno>nPageCount ){
      nPage = (pPg->pgno - pg1)+1;
    }else if( (pg1+nPagePerSector-1)>nPageCount ){
      nPage = nPageCount+1-pg1;
    }else{
      nPage = nPagePerSector;
    }
    assert(nPage>0);
    assert(pg1<=pPg->pgno);
    assert((pg1+nPage)>pPg->pgno);

    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
      Pgno pg = pg1+ii;
      PgHdr *pPage;
      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
        if( pg!=PAGER_MJ_PGNO(pPager) ){
          rc = sqlite3PagerGet(pPager, pg, &pPage);
          if( rc==SQLITE_OK ){
            rc = pager_write(pPage);
            if( pPage->flags&PGHDR_NEED_SYNC ){
              needSync = 1;
              assert(pPager->needSync);
            }
            sqlite3PagerUnref(pPage);
          }
        }
      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
        if( pPage->flags&PGHDR_NEED_SYNC ){
          needSync = 1;
        }
        sqlite3PagerUnref(pPage);
      }
    }

    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
    ** starting at pg1, then it needs to be set for all of them. Because
    ** writing to any of these nPage pages may damage the others, the
    ** journal file must contain sync()ed copies of all of them
    ** before any of them can be written out to the database file.
    */
    if( rc==SQLITE_OK && needSync ){
      assert( !MEMDB && pPager->noSync==0 );
      for(ii=0; ii<nPage; ii++){
        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
        if( pPage ){
          pPage->flags |= PGHDR_NEED_SYNC;
          sqlite3PagerUnref(pPage);
        }
      }
      assert(pPager->needSync);
    }

    assert( pPager->doNotSync==1 );
    pPager->doNotSync = 0;
  }else{
    rc = pager_write(pDbPage);
  }
  return rc;
}

/*
** Return TRUE if the page given in the argument was previously passed
** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
** to change the content of the page.
*/
#ifndef NDEBUG
int sqlite3PagerIswriteable(DbPage *pPg){
  return pPg->flags&PGHDR_DIRTY;
}
#endif

/*
** A call to this routine tells the pager that it is not necessary to
** write the information on page pPg back to the disk, even though
** that page might be marked as dirty.  This happens, for example, when
** the page has been added as a leaf of the freelist and so its
** content no longer matters.
**
** The overlying software layer calls this routine when all of the data
** on the given page is unused. The pager marks the page as clean so
** that it does not get written to disk.
**
** Tests show that this optimization can quadruple the speed of large 
** DELETE operations.
*/
void sqlite3PagerDontWrite(PgHdr *pPg){
  Pager *pPager = pPg->pPager;
  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
    pPg->flags |= PGHDR_DONT_WRITE;
#ifdef SQLITE_CHECK_PAGES
    pPg->pageHash = pager_pagehash(pPg);
#endif
  }
}

/*
** This routine is called to increment the value of the database file 
** change-counter, stored as a 4-byte big-endian integer starting at 
** byte offset 24 of the pager file.
**
** If the isDirectMode flag is zero, then this is done by calling 
** sqlite3PagerWrite() on page 1, then modifying the contents of the
** page data. In this case the file will be updated when the current
** transaction is committed.
**
** The isDirectMode flag may only be non-zero if the library was compiled
** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
** if isDirect is non-zero, then the database file is updated directly
** by writing an updated version of page 1 using a call to the 
** sqlite3OsWrite() function.
*/
static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  int rc = SQLITE_OK;

  /* Declare and initialize constant integer 'isDirect'. If the
  ** atomic-write optimization is enabled in this build, then isDirect
  ** is initialized to the value passed as the isDirectMode parameter
  ** to this function. Otherwise, it is always set to zero.
  **
  ** The idea is that if the atomic-write optimization is not
  ** enabled at compile time, the compiler can omit the tests of
  ** 'isDirect' below, as well as the block enclosed in the
  ** "if( isDirect )" condition.
  */
#ifndef SQLITE_ENABLE_ATOMIC_WRITE
# define DIRECT_MODE 0
  assert( isDirectMode==0 );
  UNUSED_PARAMETER(isDirectMode);
#else
# define DIRECT_MODE isDirectMode
#endif

  assert( pPager->state>=PAGER_RESERVED );
  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
    PgHdr *pPgHdr;                /* Reference to page 1 */
    u32 change_counter;           /* Initial value of change-counter field */

    assert( !pPager->tempFile && isOpen(pPager->fd) );

    /* Open page 1 of the file for writing. */
    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
    assert( pPgHdr==0 || rc==SQLITE_OK );

    /* If page one was fetched successfully, and this function is not
    ** operating in direct-mode, make page 1 writable.  When not in 
    ** direct mode, page 1 is always held in cache and hence the PagerGet()
    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
    */
    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
      rc = sqlite3PagerWrite(pPgHdr);
    }

    if( rc==SQLITE_OK ){
      /* Increment the value just read and write it back to byte 24. */
      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
      change_counter++;
      put32bits(((char*)pPgHdr->pData)+24, change_counter);

      /* If running in direct mode, write the contents of page 1 to the file. */
      if( DIRECT_MODE ){
        const void *zBuf = pPgHdr->pData;
        assert( pPager->dbFileSize>0 );
        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
        if( rc==SQLITE_OK ){
          pPager->changeCountDone = 1;
        }
      }else{
        pPager->changeCountDone = 1;
      }
    }

    /* Release the page reference. */
    sqlite3PagerUnref(pPgHdr);
  }
  return rc;
}

/*
** Sync the pager file to disk. This is a no-op for in-memory files
** or pages with the Pager.noSync flag set.
**
** If successful, or called on a pager for which it is a no-op, this
** function returns SQLITE_OK. Otherwise, an IO error code is returned.
*/
int sqlite3PagerSync(Pager *pPager){
  int rc;                              /* Return code */
  assert( !MEMDB );
  if( pPager->noSync ){
    rc = SQLITE_OK;
  }else{
    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  }
  return rc;
}

/*
** Sync the database file for the pager pPager. zMaster points to the name
** of a master journal file that should be written into the individual
** journal file. zMaster may be NULL, which is interpreted as no master
** journal (a single database transaction).
**
** This routine ensures that:
**
**   * The database file change-counter is updated,
**   * the journal is synced (unless the atomic-write optimization is used),
**   * all dirty pages are written to the database file, 
**   * the database file is truncated (if required), and
**   * the database file synced. 
**
** The only thing that remains to commit the transaction is to finalize 
** (delete, truncate or zero the first part of) the journal file (or 
** delete the master journal file if specified).
**
** Note that if zMaster==NULL, this does not overwrite a previous value
** passed to an sqlite3PagerCommitPhaseOne() call.
**
** If the final parameter - noSync - is true, then the database file itself
** is not synced. The caller must call sqlite3PagerSync() directly to
** sync the database file before calling CommitPhaseTwo() to delete the
** journal file in this case.
*/
int sqlite3PagerCommitPhaseOne(
  Pager *pPager,                  /* Pager object */
  const char *zMaster,            /* If not NULL, the master journal name */
  int noSync                      /* True to omit the xSync on the db file */
){
  int rc = SQLITE_OK;             /* Return code */

  /* The dbOrigSize is never set if journal_mode=OFF */
  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );

  /* If a prior error occurred, this routine should not be called.  ROLLBACK
  ** is the appropriate response to an error, not COMMIT.  Guard against
  ** coding errors by repeating the prior error. */
  if( NEVER(pPager->errCode) ) return pPager->errCode;

  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
      pPager->zFilename, zMaster, pPager->dbSize));

  if( MEMDB && pPager->dbModified ){
    /* If this is an in-memory db, or no pages have been written to, or this
    ** function has already been called, it is mostly a no-op.  However, any
    ** backup in progress needs to be restarted.
    */
    sqlite3BackupRestart(pPager->pBackup);
  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){

    /* The following block updates the change-counter. Exactly how it
    ** does this depends on whether or not the atomic-update optimization
    ** was enabled at compile time, and if this transaction meets the 
    ** runtime criteria to use the operation: 
    **
    **    * The file-system supports the atomic-write property for
    **      blocks of size page-size, and 
    **    * This commit is not part of a multi-file transaction, and
    **    * Exactly one page has been modified and store in the journal file.
    **
    ** If the optimization was not enabled at compile time, then the
    ** pager_incr_changecounter() function is called to update the change
    ** counter in 'indirect-mode'. If the optimization is compiled in but
    ** is not applicable to this transaction, call sqlite3JournalCreate()
    ** to make sure the journal file has actually been created, then call
    ** pager_incr_changecounter() to update the change-counter in indirect
    ** mode. 
    **
    ** Otherwise, if the optimization is both enabled and applicable,
    ** then call pager_incr_changecounter() to update the change-counter
    ** in 'direct' mode. In this case the journal file will never be
    ** created for this transaction.
    */
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
    PgHdr *pPg;
    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
    if( !zMaster && isOpen(pPager->jfd) 
     && pPager->journalOff==jrnlBufferSize(pPager) 
     && pPager->dbSize>=pPager->dbFileSize
     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
    ){
      /* Update the db file change counter via the direct-write method. The 
      ** following call will modify the in-memory representation of page 1 
      ** to include the updated change counter and then write page 1 
      ** directly to the database file. Because of the atomic-write 
      ** property of the host file-system, this is safe.
      */
      rc = pager_incr_changecounter(pPager, 1);
    }else{
      rc = sqlite3JournalCreate(pPager->jfd);
      if( rc==SQLITE_OK ){
        rc = pager_incr_changecounter(pPager, 0);
      }
    }
#else
    rc = pager_incr_changecounter(pPager, 0);
#endif
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;

    /* If this transaction has made the database smaller, then all pages
    ** being discarded by the truncation must be written to the journal
    ** file. This can only happen in auto-vacuum mode.
    **
    ** Before reading the pages with page numbers larger than the 
    ** current value of Pager.dbSize, set dbSize back to the value
    ** that it took at the start of the transaction. Otherwise, the
    ** calls to sqlite3PagerGet() return zeroed pages instead of 
    ** reading data from the database file.
    **
    ** When journal_mode==OFF the dbOrigSize is always zero, so this
    ** block never runs if journal_mode=OFF.
    */
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pPager->dbSize<pPager->dbOrigSize 
     && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
    ){
      Pgno i;                                   /* Iterator variable */
      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
      const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
      pPager->dbSize = pPager->dbOrigSize;
      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
          PgHdr *pPage;             /* Page to journal */
          rc = sqlite3PagerGet(pPager, i, &pPage);
          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
          rc = sqlite3PagerWrite(pPage);
          sqlite3PagerUnref(pPage);
          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
        }
      } 
      pPager->dbSize = dbSize;
    }
#endif

    /* Write the master journal name into the journal file. If a master 
    ** journal file name has already been written to the journal file, 
    ** or if zMaster is NULL (no master journal), then this call is a no-op.
    */
    rc = writeMasterJournal(pPager, zMaster);
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;

    /* Sync the journal file. If the atomic-update optimization is being
    ** used, this call will not create the journal file or perform any
    ** real IO.
    */
    rc = syncJournal(pPager);
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;

    /* Write all dirty pages to the database file. */
    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
    if( rc!=SQLITE_OK ){
      assert( rc!=SQLITE_IOERR_BLOCKED );
      goto commit_phase_one_exit;
    }
    sqlite3PcacheCleanAll(pPager->pPCache);

    /* If the file on disk is not the same size as the database image,
    ** then use pager_truncate to grow or shrink the file here.
    */
    if( pPager->dbSize!=pPager->dbFileSize ){
      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
      assert( pPager->state>=PAGER_EXCLUSIVE );
      rc = pager_truncate(pPager, nNew);
      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
    }

    /* Finally, sync the database file. */
    if( !pPager->noSync && !noSync ){
      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
    }
    IOTRACE(("DBSYNC %p\n", pPager))

    pPager->state = PAGER_SYNCED;
  }

commit_phase_one_exit:
  return rc;
}


/*
** When this function is called, the database file has been completely
** updated to reflect the changes made by the current transaction and
** synced to disk. The journal file still exists in the file-system 
** though, and if a failure occurs at this point it will eventually
** be used as a hot-journal and the current transaction rolled back.
**
** This function finalizes the journal file, either by deleting, 
** truncating or partially zeroing it, so that it cannot be used 
** for hot-journal rollback. Once this is done the transaction is
** irrevocably committed.
**
** If an error occurs, an IO error code is returned and the pager
** moves into the error state. Otherwise, SQLITE_OK is returned.
*/
int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  int rc = SQLITE_OK;                  /* Return code */

  /* This routine should not be called if a prior error has occurred.
  ** But if (due to a coding error elsewhere in the system) it does get
  ** called, just return the same error code without doing anything. */
  if( NEVER(pPager->errCode) ) return pPager->errCode;

  /* This function should not be called if the pager is not in at least
  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
  ** nice to have this defensive test here anyway.
  */
  if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;

  /* An optimization. If the database was not actually modified during
  ** this transaction, the pager is running in exclusive-mode and is
  ** using persistent journals, then this function is a no-op.
  **
  ** The start of the journal file currently contains a single journal 
  ** header with the nRec field set to 0. If such a journal is used as
  ** a hot-journal during hot-journal rollback, 0 changes will be made
  ** to the database file. So there is no need to zero the journal 
  ** header. Since the pager is in exclusive mode, there is no need
  ** to drop any locks either.
  */
  if( pPager->dbModified==0 && pPager->exclusiveMode 
   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  ){
    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
    return SQLITE_OK;
  }

  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
  rc = pager_end_transaction(pPager, pPager->setMaster);
  return pager_error(pPager, rc);
}

/*
** Rollback all changes. The database falls back to PAGER_SHARED mode.
**
** This function performs two tasks:
**
**   1) It rolls back the journal file, restoring all database file and 
**      in-memory cache pages to the state they were in when the transaction
**      was opened, and
**   2) It finalizes the journal file, so that it is not used for hot
**      rollback at any point in the future.
**
** subject to the following qualifications:
**
** * If the journal file is not yet open when this function is called,
**   then only (2) is performed. In this case there is no journal file
**   to roll back.
**
** * If in an error state other than SQLITE_FULL, then task (1) is 
**   performed. If successful, task (2). Regardless of the outcome
**   of either, the error state error code is returned to the caller
**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
**
** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
**   or not (1) is succussful, also attempt (2). If successful, return
**   SQLITE_OK. Otherwise, enter the error state and return the first 
**   error code encountered. 
**
**   In this case there is no chance that the database was written to. 
**   So is safe to finalize the journal file even if the playback 
**   (operation 1) failed. However the pager must enter the error state
**   as the contents of the in-memory cache are now suspect.
**
** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
**   otherwise enter the error state and return the error code from the 
**   failing operation.
**
**   In this case the database file may have been written to. So if the
**   playback operation did not succeed it would not be safe to finalize
**   the journal file. It needs to be left in the file-system so that
**   some other process can use it to restore the database state (by
**   hot-journal rollback).
*/
int sqlite3PagerRollback(Pager *pPager){
  int rc = SQLITE_OK;                  /* Return code */
  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
    rc = pager_end_transaction(pPager, pPager->setMaster);
  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
    if( pPager->state>=PAGER_EXCLUSIVE ){
      pager_playback(pPager, 0);
    }
    rc = pPager->errCode;
  }else{
    if( pPager->state==PAGER_RESERVED ){
      int rc2;
      rc = pager_playback(pPager, 0);
      rc2 = pager_end_transaction(pPager, pPager->setMaster);
      if( rc==SQLITE_OK ){
        rc = rc2;
      }
    }else{
      rc = pager_playback(pPager, 0);
    }

    if( !MEMDB ){
      pPager->dbSizeValid = 0;
    }

    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
    ** cache. So call pager_error() on the way out to make any error 
    ** persistent.
    */
    rc = pager_error(pPager, rc);
  }
  return rc;
}

/*
** Return TRUE if the database file is opened read-only.  Return FALSE
** if the database is (in theory) writable.
*/
u8 sqlite3PagerIsreadonly(Pager *pPager){
  return pPager->readOnly;
}

/*
** Return the number of references to the pager.
*/
int sqlite3PagerRefcount(Pager *pPager){
  return sqlite3PcacheRefCount(pPager->pPCache);
}

/*
** Return the number of references to the specified page.
*/
int sqlite3PagerPageRefcount(DbPage *pPage){
  return sqlite3PcachePageRefcount(pPage);
}

#ifdef SQLITE_TEST
/*
** This routine is used for testing and analysis only.
*/
int *sqlite3PagerStats(Pager *pPager){
  static int a[11];
  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  a[1] = sqlite3PcachePagecount(pPager->pPCache);
  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
  a[4] = pPager->state;
  a[5] = pPager->errCode;
  a[6] = pPager->nHit;
  a[7] = pPager->nMiss;
  a[8] = 0;  /* Used to be pPager->nOvfl */
  a[9] = pPager->nRead;
  a[10] = pPager->nWrite;
  return a;
}
#endif

/*
** Return true if this is an in-memory pager.
*/
int sqlite3PagerIsMemdb(Pager *pPager){
  return MEMDB;
}

/*
** Check that there are at least nSavepoint savepoints open. If there are
** currently less than nSavepoints open, then open one or more savepoints
** to make up the difference. If the number of savepoints is already
** equal to nSavepoint, then this function is a no-op.
**
** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
** occurs while opening the sub-journal file, then an IO error code is
** returned. Otherwise, SQLITE_OK.
*/
int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  int rc = SQLITE_OK;                       /* Return code */
  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */

  if( nSavepoint>nCurrent && pPager->useJournal ){
    int ii;                                 /* Iterator variable */
    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */

    /* Either there is no active journal or the sub-journal is open or 
    ** the journal is always stored in memory */
    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );

    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
    ** if the allocation fails. Otherwise, zero the new portion in case a 
    ** malloc failure occurs while populating it in the for(...) loop below.
    */
    aNew = (PagerSavepoint *)sqlite3Realloc(
        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
    );
    if( !aNew ){
      return SQLITE_NOMEM;
    }
    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
    pPager->aSavepoint = aNew;
    pPager->nSavepoint = nSavepoint;

    /* Populate the PagerSavepoint structures just allocated. */
    for(ii=nCurrent; ii<nSavepoint; ii++){
      assert( pPager->dbSizeValid );
      aNew[ii].nOrig = pPager->dbSize;
      if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
        aNew[ii].iOffset = pPager->journalOff;
      }else{
        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
      }
      aNew[ii].iSubRec = pPager->nSubRec;
      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
      if( !aNew[ii].pInSavepoint ){
        return SQLITE_NOMEM;
      }
    }

    /* Open the sub-journal, if it is not already opened. */
    rc = openSubJournal(pPager);
    assertTruncateConstraint(pPager);
  }

  return rc;
}

/*
** This function is called to rollback or release (commit) a savepoint.
** The savepoint to release or rollback need not be the most recently 
** created savepoint.
**
** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
** that have occurred since the specified savepoint was created.
**
** The savepoint to rollback or release is identified by parameter 
** iSavepoint. A value of 0 means to operate on the outermost savepoint
** (the first created). A value of (Pager.nSavepoint-1) means operate
** on the most recently created savepoint. If iSavepoint is greater than
** (Pager.nSavepoint-1), then this function is a no-op.
**
** If a negative value is passed to this function, then the current
** transaction is rolled back. This is different to calling 
** sqlite3PagerRollback() because this function does not terminate
** the transaction or unlock the database, it just restores the 
** contents of the database to its original state. 
**
** In any case, all savepoints with an index greater than iSavepoint 
** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
** then savepoint iSavepoint is also destroyed.
**
** This function may return SQLITE_NOMEM if a memory allocation fails,
** or an IO error code if an IO error occurs while rolling back a 
** savepoint. If no errors occur, SQLITE_OK is returned.
*/ 
int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  int rc = SQLITE_OK;

  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );

  if( iSavepoint<pPager->nSavepoint ){
    int ii;            /* Iterator variable */
    int nNew;          /* Number of remaining savepoints after this op. */

    /* Figure out how many savepoints will still be active after this
    ** operation. Store this value in nNew. Then free resources associated 
    ** with any savepoints that are destroyed by this operation.
    */
    nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
    for(ii=nNew; ii<pPager->nSavepoint; ii++){
      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
    }
    pPager->nSavepoint = nNew;

    /* If this is a rollback operation, playback the specified savepoint.
    ** If this is a temp-file, it is possible that the journal file has
    ** not yet been opened. In this case there have been no changes to
    ** the database file, so the playback operation can be skipped.
    */
    if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
      assert(rc!=SQLITE_DONE);
    }
  
    /* If this is a release of the outermost savepoint, truncate 
    ** the sub-journal to zero bytes in size. */
    if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
      assert( rc==SQLITE_OK );
      rc = sqlite3OsTruncate(pPager->sjfd, 0);
      pPager->nSubRec = 0;
    }
  }
  return rc;
}

/*
** Return the full pathname of the database file.
*/
const char *sqlite3PagerFilename(Pager *pPager){
  return pPager->zFilename;
}

/*
** Return the VFS structure for the pager.
*/
const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  return pPager->pVfs;
}

/*
** Return the file handle for the database file associated
** with the pager.  This might return NULL if the file has
** not yet been opened.
*/
sqlite3_file *sqlite3PagerFile(Pager *pPager){
  return pPager->fd;
}

/*
** Return the full pathname of the journal file.
*/
const char *sqlite3PagerJournalname(Pager *pPager){
  return pPager->zJournal;
}

/*
** Return true if fsync() calls are disabled for this pager.  Return FALSE
** if fsync()s are executed normally.
*/
int sqlite3PagerNosync(Pager *pPager){
  return pPager->noSync;
}

#ifdef SQLITE_HAS_CODEC
/*
** Set or retrieve the codec for this pager
*/
static void sqlite3PagerSetCodec(
  Pager *pPager,
  void *(*xCodec)(void*,void*,Pgno,int),
  void (*xCodecSizeChng)(void*,int,int),
  void (*xCodecFree)(void*),
  void *pCodec
){
  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  pPager->xCodec = xCodec;
  pPager->xCodecSizeChng = xCodecSizeChng;
  pPager->xCodecFree = xCodecFree;
  pPager->pCodec = pCodec;
  pagerReportSize(pPager);
}
static void *sqlite3PagerGetCodec(Pager *pPager){
  return pPager->pCodec;
}
#endif

#ifndef SQLITE_OMIT_AUTOVACUUM
/*
** Move the page pPg to location pgno in the file.
**
** There must be no references to the page previously located at
** pgno (which we call pPgOld) though that page is allowed to be
** in cache.  If the page previously located at pgno is not already
** in the rollback journal, it is not put there by by this routine.
**
** References to the page pPg remain valid. Updating any
** meta-data associated with pPg (i.e. data stored in the nExtra bytes
** allocated along with the page) is the responsibility of the caller.
**
** A transaction must be active when this routine is called. It used to be
** required that a statement transaction was not active, but this restriction
** has been removed (CREATE INDEX needs to move a page when a statement
** transaction is active).
**
** If the fourth argument, isCommit, is non-zero, then this page is being
** moved as part of a database reorganization just before the transaction 
** is being committed. In this case, it is guaranteed that the database page 
** pPg refers to will not be written to again within this transaction.
**
** This function may return SQLITE_NOMEM or an IO error code if an error
** occurs. Otherwise, it returns SQLITE_OK.
*/
int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  PgHdr *pPgOld;               /* The page being overwritten. */
  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
  int rc;                      /* Return code */
  Pgno origPgno;               /* The original page number */

  assert( pPg->nRef>0 );

  /* If the page being moved is dirty and has not been saved by the latest
  ** savepoint, then save the current contents of the page into the 
  ** sub-journal now. This is required to handle the following scenario:
  **
  **   BEGIN;
  **     <journal page X, then modify it in memory>
  **     SAVEPOINT one;
  **       <Move page X to location Y>
  **     ROLLBACK TO one;
  **
  ** If page X were not written to the sub-journal here, it would not
  ** be possible to restore its contents when the "ROLLBACK TO one"
  ** statement were is processed.
  **
  ** subjournalPage() may need to allocate space to store pPg->pgno into
  ** one or more savepoint bitvecs. This is the reason this function
  ** may return SQLITE_NOMEM.
  */
  if( pPg->flags&PGHDR_DIRTY 
   && subjRequiresPage(pPg)
   && SQLITE_OK!=(rc = subjournalPage(pPg))
  ){
    return rc;
  }

  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))

  /* If the journal needs to be sync()ed before page pPg->pgno can
  ** be written to, store pPg->pgno in local variable needSyncPgno.
  **
  ** If the isCommit flag is set, there is no need to remember that
  ** the journal needs to be sync()ed before database page pPg->pgno 
  ** can be written to. The caller has already promised not to write to it.
  */
  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
    needSyncPgno = pPg->pgno;
    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
    assert( pPg->flags&PGHDR_DIRTY );
    assert( pPager->needSync );
  }

  /* If the cache contains a page with page-number pgno, remove it
  ** from its hash chain. Also, if the PgHdr.needSync was set for 
  ** page pgno before the 'move' operation, it needs to be retained 
  ** for the page moved there.
  */
  pPg->flags &= ~PGHDR_NEED_SYNC;
  pPgOld = pager_lookup(pPager, pgno);
  assert( !pPgOld || pPgOld->nRef==1 );
  if( pPgOld ){
    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
    sqlite3PcacheDrop(pPgOld);
  }

  origPgno = pPg->pgno;
  sqlite3PcacheMove(pPg, pgno);
  sqlite3PcacheMakeDirty(pPg);
  pPager->dbModified = 1;

  if( needSyncPgno ){
    /* If needSyncPgno is non-zero, then the journal file needs to be 
    ** sync()ed before any data is written to database file page needSyncPgno.
    ** Currently, no such page exists in the page-cache and the 
    ** "is journaled" bitvec flag has been set. This needs to be remedied by
    ** loading the page into the pager-cache and setting the PgHdr.needSync 
    ** flag.
    **
    ** If the attempt to load the page into the page-cache fails, (due
    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
    ** array. Otherwise, if the page is loaded and written again in
    ** this transaction, it may be written to the database file before
    ** it is synced into the journal file. This way, it may end up in
    ** the journal file twice, but that is not a problem.
    **
    ** The sqlite3PagerGet() call may cause the journal to sync. So make
    ** sure the Pager.needSync flag is set too.
    */
    PgHdr *pPgHdr;
    assert( pPager->needSync );
    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
    if( rc!=SQLITE_OK ){
      if( needSyncPgno<=pPager->dbOrigSize ){
        assert( pPager->pTmpSpace!=0 );
        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
      }
      return rc;
    }
    pPager->needSync = 1;
    assert( pPager->noSync==0 && !MEMDB );
    pPgHdr->flags |= PGHDR_NEED_SYNC;
    sqlite3PcacheMakeDirty(pPgHdr);
    sqlite3PagerUnref(pPgHdr);
  }

  /*
  ** For an in-memory database, make sure the original page continues
  ** to exist, in case the transaction needs to roll back.  We allocate
  ** the page now, instead of at rollback, because we can better deal
  ** with an out-of-memory error now.  Ticket #3761.
  */
  if( MEMDB ){
    DbPage *pNew;
    rc = sqlite3PagerAcquire(pPager, origPgno, &pNew, 1);
    if( rc!=SQLITE_OK ){
      sqlite3PcacheMove(pPg, origPgno);
      return rc;
    }
    sqlite3PagerUnref(pNew);
  }

  return SQLITE_OK;
}
#endif

/*
** Return a pointer to the data for the specified page.
*/
void *sqlite3PagerGetData(DbPage *pPg){
  assert( pPg->nRef>0 || pPg->pPager->memDb );
  return pPg->pData;
}

/*
** Return a pointer to the Pager.nExtra bytes of "extra" space 
** allocated along with the specified page.
*/
void *sqlite3PagerGetExtra(DbPage *pPg){
  return pPg->pExtra;
}

/*
** Get/set the locking-mode for this pager. Parameter eMode must be one
** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
** the locking-mode is set to the value specified.
**
** The returned value is either PAGER_LOCKINGMODE_NORMAL or
** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
** locking-mode.
*/
int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  assert( eMode==PAGER_LOCKINGMODE_QUERY
            || eMode==PAGER_LOCKINGMODE_NORMAL
            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  assert( PAGER_LOCKINGMODE_QUERY<0 );
  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  if( eMode>=0 && !pPager->tempFile ){
    pPager->exclusiveMode = (u8)eMode;
  }
  return (int)pPager->exclusiveMode;
}

/*
** Get/set the journal-mode for this pager. Parameter eMode must be one of:
**
**    PAGER_JOURNALMODE_QUERY
**    PAGER_JOURNALMODE_DELETE
**    PAGER_JOURNALMODE_TRUNCATE
**    PAGER_JOURNALMODE_PERSIST
**    PAGER_JOURNALMODE_OFF
**    PAGER_JOURNALMODE_MEMORY
**
** If the parameter is not _QUERY, then the journal_mode is set to the
** value specified if the change is allowed.  The change is disallowed
** for the following reasons:
**
**   *  An in-memory database can only have its journal_mode set to _OFF
**      or _MEMORY.
**
**   *  The journal mode may not be changed while a transaction is active.
**
** The returned indicate the current (possibly updated) journal-mode.
*/
int sqlite3PagerJournalMode(Pager *pPager, int eMode){
  assert( eMode==PAGER_JOURNALMODE_QUERY
            || eMode==PAGER_JOURNALMODE_DELETE
            || eMode==PAGER_JOURNALMODE_TRUNCATE
            || eMode==PAGER_JOURNALMODE_PERSIST
            || eMode==PAGER_JOURNALMODE_OFF 
            || eMode==PAGER_JOURNALMODE_MEMORY );
  assert( PAGER_JOURNALMODE_QUERY<0 );
  if( eMode>=0
   && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY 
              || eMode==PAGER_JOURNALMODE_OFF)
   && !pPager->dbModified
   && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
  ){
    if( isOpen(pPager->jfd) ){
      sqlite3OsClose(pPager->jfd);
    }
    pPager->journalMode = (u8)eMode;
  }
  return (int)pPager->journalMode;
}

/*
** Get/set the size-limit used for persistent journal files.
**
** Setting the size limit to -1 means no limit is enforced.
** An attempt to set a limit smaller than -1 is a no-op.
*/
i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  if( iLimit>=-1 ){
    pPager->journalSizeLimit = iLimit;
  }
  return pPager->journalSizeLimit;
}

/*
** Return a pointer to the pPager->pBackup variable. The backup module
** in backup.c maintains the content of this variable. This module
** uses it opaquely as an argument to sqlite3BackupRestart() and
** sqlite3BackupUpdate() only.
*/
sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  return &pPager->pBackup;
}

#endif /* SQLITE_OMIT_DISKIO */

Added src/pager.h.















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem.  The page cache subsystem reads and writes a file a page
** at a time and provides a journal for rollback.
**
** @(#) $Id: pager.h,v 1.104 2009/07/24 19:01:19 drh Exp $
*/

#ifndef _PAGER_H_
#define _PAGER_H_

/*
** Default maximum size for persistent journal files. A negative 
** value means no limit. This value may be overridden using the 
** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
*/
#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
#endif

/*
** The type used to represent a page number.  The first page in a file
** is called page 1.  0 is used to represent "not a page".
*/
typedef u32 Pgno;

/*
** Each open file is managed by a separate instance of the "Pager" structure.
*/
typedef struct Pager Pager;

/*
** Handle type for pages.
*/
typedef struct PgHdr DbPage;

/*
** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
** reserved for working around a windows/posix incompatibility). It is
** used in the journal to signify that the remainder of the journal file 
** is devoted to storing a master journal name - there are no more pages to
** roll back. See comments for function writeMasterJournal() in pager.c 
** for details.
*/
#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))

/*
** Allowed values for the flags parameter to sqlite3PagerOpen().
**
** NOTE: These values must match the corresponding BTREE_ values in btree.h.
*/
#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */

/*
** Valid values for the second argument to sqlite3PagerLockingMode().
*/
#define PAGER_LOCKINGMODE_QUERY      -1
#define PAGER_LOCKINGMODE_NORMAL      0
#define PAGER_LOCKINGMODE_EXCLUSIVE   1

/*
** Valid values for the second argument to sqlite3PagerJournalMode().
*/
#define PAGER_JOURNALMODE_QUERY      -1
#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */

/*
** The remainder of this file contains the declarations of the functions
** that make up the Pager sub-system API. See source code comments for 
** a detailed description of each routine.
*/

/* Open and close a Pager connection. */ 
int sqlite3PagerOpen(
  sqlite3_vfs*,
  Pager **ppPager,
  const char*,
  int,
  int,
  int,
  void(*)(DbPage*)
);
int sqlite3PagerClose(Pager *pPager);
int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);

/* Functions used to configure a Pager object. */
void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
int sqlite3PagerSetPagesize(Pager*, u16*, int);
int sqlite3PagerMaxPageCount(Pager*, int);
void sqlite3PagerSetCachesize(Pager*, int);
void sqlite3PagerSetSafetyLevel(Pager*,int,int);
int sqlite3PagerLockingMode(Pager *, int);
int sqlite3PagerJournalMode(Pager *, int);
i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
sqlite3_backup **sqlite3PagerBackupPtr(Pager*);

/* Functions used to obtain and release page references. */ 
int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
void sqlite3PagerRef(DbPage*);
void sqlite3PagerUnref(DbPage*);

/* Operations on page references. */
int sqlite3PagerWrite(DbPage*);
void sqlite3PagerDontWrite(DbPage*);
int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
int sqlite3PagerPageRefcount(DbPage*);
void *sqlite3PagerGetData(DbPage *); 
void *sqlite3PagerGetExtra(DbPage *); 

/* Functions used to manage pager transactions and savepoints. */
int sqlite3PagerPagecount(Pager*, int*);
int sqlite3PagerBegin(Pager*, int exFlag, int);
int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
int sqlite3PagerSync(Pager *pPager);
int sqlite3PagerCommitPhaseTwo(Pager*);
int sqlite3PagerRollback(Pager*);
int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
int sqlite3PagerSharedLock(Pager *pPager);

/* Functions used to query pager state and configuration. */
u8 sqlite3PagerIsreadonly(Pager*);
int sqlite3PagerRefcount(Pager*);
const char *sqlite3PagerFilename(Pager*);
const sqlite3_vfs *sqlite3PagerVfs(Pager*);
sqlite3_file *sqlite3PagerFile(Pager*);
const char *sqlite3PagerJournalname(Pager*);
int sqlite3PagerNosync(Pager*);
void *sqlite3PagerTempSpace(Pager*);
int sqlite3PagerIsMemdb(Pager*);

/* Functions used to truncate the database file. */
void sqlite3PagerTruncateImage(Pager*,Pgno);

/* Functions to support testing and debugging. */
#if !defined(NDEBUG) || defined(SQLITE_TEST)
  Pgno sqlite3PagerPagenumber(DbPage*);
  int sqlite3PagerIswriteable(DbPage*);
#endif
#ifdef SQLITE_TEST
  int *sqlite3PagerStats(Pager*);
  void sqlite3PagerRefdump(Pager*);
  void disable_simulated_io_errors(void);
  void enable_simulated_io_errors(void);
#else
# define disable_simulated_io_errors()
# define enable_simulated_io_errors()
#endif

#endif /* _PAGER_H_ */

Added src/parse.y.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains SQLite's grammar for SQL.  Process this file
** using the lemon parser generator to generate C code that runs
** the parser.  Lemon will also generate a header file containing
** numeric codes for all of the tokens.
**
** @(#) $Id: parse.y,v 1.286 2009/08/10 03:57:58 shane Exp $
*/

// All token codes are small integers with #defines that begin with "TK_"
%token_prefix TK_

// The type of the data attached to each token is Token.  This is also the
// default type for non-terminals.
//
%token_type {Token}
%default_type {Token}

// The generated parser function takes a 4th argument as follows:
%extra_argument {Parse *pParse}

// This code runs whenever there is a syntax error
//
%syntax_error {
  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  pParse->parseError = 1;
}
%stack_overflow {
  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  sqlite3ErrorMsg(pParse, "parser stack overflow");
  pParse->parseError = 1;
}

// The name of the generated procedure that implements the parser
// is as follows:
%name sqlite3Parser

// The following text is included near the beginning of the C source
// code file that implements the parser.
//
%include {
#include "sqliteInt.h"

/*
** Disable all error recovery processing in the parser push-down
** automaton.
*/
#define YYNOERRORRECOVERY 1

/*
** Make yytestcase() the same as testcase()
*/
#define yytestcase(X) testcase(X)

/*
** An instance of this structure holds information about the
** LIMIT clause of a SELECT statement.
*/
struct LimitVal {
  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
};

/*
** An instance of this structure is used to store the LIKE,
** GLOB, NOT LIKE, and NOT GLOB operators.
*/
struct LikeOp {
  Token eOperator;  /* "like" or "glob" or "regexp" */
  int not;         /* True if the NOT keyword is present */
};

/*
** An instance of the following structure describes the event of a
** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
** TK_DELETE, or TK_INSTEAD.  If the event is of the form
**
**      UPDATE ON (a,b,c)
**
** Then the "b" IdList records the list "a,b,c".
*/
struct TrigEvent { int a; IdList * b; };

/*
** An instance of this structure holds the ATTACH key and the key type.
*/
struct AttachKey { int type;  Token key; };

} // end %include

// Input is a single SQL command
input ::= cmdlist.
cmdlist ::= cmdlist ecmd.
cmdlist ::= ecmd.
ecmd ::= SEMI.
ecmd ::= explain cmdx SEMI.
explain ::= .           { sqlite3BeginParse(pParse, 0); }
%ifndef SQLITE_OMIT_EXPLAIN
explain ::= EXPLAIN.              { sqlite3BeginParse(pParse, 1); }
explain ::= EXPLAIN QUERY PLAN.   { sqlite3BeginParse(pParse, 2); }
%endif  SQLITE_OMIT_EXPLAIN
cmdx ::= cmd.           { sqlite3FinishCoding(pParse); }

///////////////////// Begin and end transactions. ////////////////////////////
//

cmd ::= BEGIN transtype(Y) trans_opt.  {sqlite3BeginTransaction(pParse, Y);}
trans_opt ::= .
trans_opt ::= TRANSACTION.
trans_opt ::= TRANSACTION nm.
%type transtype {int}
transtype(A) ::= .             {A = TK_DEFERRED;}
transtype(A) ::= DEFERRED(X).  {A = @X;}
transtype(A) ::= IMMEDIATE(X). {A = @X;}
transtype(A) ::= EXCLUSIVE(X). {A = @X;}
cmd ::= COMMIT trans_opt.      {sqlite3CommitTransaction(pParse);}
cmd ::= END trans_opt.         {sqlite3CommitTransaction(pParse);}
cmd ::= ROLLBACK trans_opt.    {sqlite3RollbackTransaction(pParse);}

savepoint_opt ::= SAVEPOINT.
savepoint_opt ::= .
cmd ::= SAVEPOINT nm(X). {
  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &X);
}
cmd ::= RELEASE savepoint_opt nm(X). {
  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &X);
}
cmd ::= ROLLBACK trans_opt TO savepoint_opt nm(X). {
  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &X);
}

///////////////////// The CREATE TABLE statement ////////////////////////////
//
cmd ::= create_table create_table_args.
create_table ::= createkw temp(T) TABLE ifnotexists(E) nm(Y) dbnm(Z). {
   sqlite3StartTable(pParse,&Y,&Z,T,0,0,E);
}
createkw(A) ::= CREATE(X).  {
  pParse->db->lookaside.bEnabled = 0;
  A = X;
}
%type ifnotexists {int}
ifnotexists(A) ::= .              {A = 0;}
ifnotexists(A) ::= IF NOT EXISTS. {A = 1;}
%type temp {int}
%ifndef SQLITE_OMIT_TEMPDB
temp(A) ::= TEMP.  {A = 1;}
%endif  SQLITE_OMIT_TEMPDB
temp(A) ::= .      {A = 0;}
create_table_args ::= LP columnlist conslist_opt(X) RP(Y). {
  sqlite3EndTable(pParse,&X,&Y,0);
}
create_table_args ::= AS select(S). {
  sqlite3EndTable(pParse,0,0,S);
  sqlite3SelectDelete(pParse->db, S);
}
columnlist ::= columnlist COMMA column.
columnlist ::= column.

// A "column" is a complete description of a single column in a
// CREATE TABLE statement.  This includes the column name, its
// datatype, and other keywords such as PRIMARY KEY, UNIQUE, REFERENCES,
// NOT NULL and so forth.
//
column(A) ::= columnid(X) type carglist. {
  A.z = X.z;
  A.n = (int)(pParse->sLastToken.z-X.z) + pParse->sLastToken.n;
}
columnid(A) ::= nm(X). {
  sqlite3AddColumn(pParse,&X);
  A = X;
}


// An IDENTIFIER can be a generic identifier, or one of several
// keywords.  Any non-standard keyword can also be an identifier.
//
%type id {Token}
id(A) ::= ID(X).         {A = X;}
id(A) ::= INDEXED(X).    {A = X;}

// The following directive causes tokens ABORT, AFTER, ASC, etc. to
// fallback to ID if they will not parse as their original value.
// This obviates the need for the "id" nonterminal.
//
%fallback ID
  ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST COLUMNKW
  CONFLICT DATABASE DEFERRED DESC DETACH EACH END EXCLUSIVE EXPLAIN FAIL FOR
  IGNORE IMMEDIATE INITIALLY INSTEAD LIKE_KW MATCH NO PLAN
  QUERY KEY OF OFFSET PRAGMA RAISE RELEASE REPLACE RESTRICT ROW ROLLBACK
  SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL
%ifdef SQLITE_OMIT_COMPOUND_SELECT
  EXCEPT INTERSECT UNION
%endif SQLITE_OMIT_COMPOUND_SELECT
  REINDEX RENAME CTIME_KW IF
  .
%wildcard ANY.

// Define operator precedence early so that this is the first occurance
// of the operator tokens in the grammer.  Keeping the operators together
// causes them to be assigned integer values that are close together,
// which keeps parser tables smaller.
//
// The token values assigned to these symbols is determined by the order
// in which lemon first sees them.  It must be the case that ISNULL/NOTNULL,
// NE/EQ, GT/LE, and GE/LT are separated by only a single value.  See
// the sqlite3ExprIfFalse() routine for additional information on this
// constraint.
//
%left OR.
%left AND.
%right NOT.
%left IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
%left GT LE LT GE.
%right ESCAPE.
%left BITAND BITOR LSHIFT RSHIFT.
%left PLUS MINUS.
%left STAR SLASH REM.
%left CONCAT.
%left COLLATE.
%right BITNOT.

// And "ids" is an identifer-or-string.
//
%type ids {Token}
ids(A) ::= ID|STRING(X).   {A = X;}

// The name of a column or table can be any of the following:
//
%type nm {Token}
nm(A) ::= id(X).         {A = X;}
nm(A) ::= STRING(X).     {A = X;}
nm(A) ::= JOIN_KW(X).    {A = X;}

// A typetoken is really one or more tokens that form a type name such
// as can be found after the column name in a CREATE TABLE statement.
// Multiple tokens are concatenated to form the value of the typetoken.
//
%type typetoken {Token}
type ::= .
type ::= typetoken(X).                   {sqlite3AddColumnType(pParse,&X);}
typetoken(A) ::= typename(X).   {A = X;}
typetoken(A) ::= typename(X) LP signed RP(Y). {
  A.z = X.z;
  A.n = (int)(&Y.z[Y.n] - X.z);
}
typetoken(A) ::= typename(X) LP signed COMMA signed RP(Y). {
  A.z = X.z;
  A.n = (int)(&Y.z[Y.n] - X.z);
}
%type typename {Token}
typename(A) ::= ids(X).             {A = X;}
typename(A) ::= typename(X) ids(Y). {A.z=X.z; A.n=Y.n+(int)(Y.z-X.z);}
signed ::= plus_num.
signed ::= minus_num.

// "carglist" is a list of additional constraints that come after the
// column name and column type in a CREATE TABLE statement.
//
carglist ::= carglist carg.
carglist ::= .
carg ::= CONSTRAINT nm ccons.
carg ::= ccons.
ccons ::= DEFAULT term(X).            {sqlite3AddDefaultValue(pParse,&X);}
ccons ::= DEFAULT LP expr(X) RP.      {sqlite3AddDefaultValue(pParse,&X);}
ccons ::= DEFAULT PLUS term(X).       {sqlite3AddDefaultValue(pParse,&X);}
ccons ::= DEFAULT MINUS(A) term(X).      {
  ExprSpan v;
  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, X.pExpr, 0, 0);
  v.zStart = A.z;
  v.zEnd = X.zEnd;
  sqlite3AddDefaultValue(pParse,&v);
}
ccons ::= DEFAULT id(X).              {
  ExprSpan v;
  spanExpr(&v, pParse, TK_STRING, &X);
  sqlite3AddDefaultValue(pParse,&v);
}

// In addition to the type name, we also care about the primary key and
// UNIQUE constraints.
//
ccons ::= NULL onconf.
ccons ::= NOT NULL onconf(R).    {sqlite3AddNotNull(pParse, R);}
ccons ::= PRIMARY KEY sortorder(Z) onconf(R) autoinc(I).
                                 {sqlite3AddPrimaryKey(pParse,0,R,I,Z);}
ccons ::= UNIQUE onconf(R).      {sqlite3CreateIndex(pParse,0,0,0,0,R,0,0,0,0);}
ccons ::= CHECK LP expr(X) RP.   {sqlite3AddCheckConstraint(pParse,X.pExpr);}
ccons ::= REFERENCES nm(T) idxlist_opt(TA) refargs(R).
                                 {sqlite3CreateForeignKey(pParse,0,&T,TA,R);}
ccons ::= defer_subclause(D).    {sqlite3DeferForeignKey(pParse,D);}
ccons ::= COLLATE ids(C).        {sqlite3AddCollateType(pParse, &C);}

// The optional AUTOINCREMENT keyword
%type autoinc {int}
autoinc(X) ::= .          {X = 0;}
autoinc(X) ::= AUTOINCR.  {X = 1;}

// The next group of rules parses the arguments to a REFERENCES clause
// that determine if the referential integrity checking is deferred or
// or immediate and which determine what action to take if a ref-integ
// check fails.
//
%type refargs {int}
refargs(A) ::= .                  { A = OE_None*0x0101; /* EV: R-19803-45884 */}
refargs(A) ::= refargs(X) refarg(Y). { A = (X & ~Y.mask) | Y.value; }
%type refarg {struct {int value; int mask;}}
refarg(A) ::= MATCH nm.              { A.value = 0;     A.mask = 0x000000; }
refarg(A) ::= ON DELETE refact(X).   { A.value = X;     A.mask = 0x0000ff; }
refarg(A) ::= ON UPDATE refact(X).   { A.value = X<<8;  A.mask = 0x00ff00; }
%type refact {int}
refact(A) ::= SET NULL.              { A = OE_SetNull;  /* EV: R-33326-45252 */}
refact(A) ::= SET DEFAULT.           { A = OE_SetDflt;  /* EV: R-33326-45252 */}
refact(A) ::= CASCADE.               { A = OE_Cascade;  /* EV: R-33326-45252 */}
refact(A) ::= RESTRICT.              { A = OE_Restrict; /* EV: R-33326-45252 */}
refact(A) ::= NO ACTION.             { A = OE_None;     /* EV: R-33326-45252 */}
%type defer_subclause {int}
defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt.     {A = 0;}
defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X).      {A = X;}
%type init_deferred_pred_opt {int}
init_deferred_pred_opt(A) ::= .                       {A = 0;}
init_deferred_pred_opt(A) ::= INITIALLY DEFERRED.     {A = 1;}
init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE.    {A = 0;}

// For the time being, the only constraint we care about is the primary
// key and UNIQUE.  Both create indices.
//
conslist_opt(A) ::= .                   {A.n = 0; A.z = 0;}
conslist_opt(A) ::= COMMA(X) conslist.  {A = X;}
conslist ::= conslist COMMA tcons.
conslist ::= conslist tcons.
conslist ::= tcons.
tcons ::= CONSTRAINT nm.
tcons ::= PRIMARY KEY LP idxlist(X) autoinc(I) RP onconf(R).
                                 {sqlite3AddPrimaryKey(pParse,X,R,I,0);}
tcons ::= UNIQUE LP idxlist(X) RP onconf(R).
                                 {sqlite3CreateIndex(pParse,0,0,0,X,R,0,0,0,0);}
tcons ::= CHECK LP expr(E) RP onconf.
                                 {sqlite3AddCheckConstraint(pParse,E.pExpr);}
tcons ::= FOREIGN KEY LP idxlist(FA) RP
          REFERENCES nm(T) idxlist_opt(TA) refargs(R) defer_subclause_opt(D). {
    sqlite3CreateForeignKey(pParse, FA, &T, TA, R);
    sqlite3DeferForeignKey(pParse, D);
}
%type defer_subclause_opt {int}
defer_subclause_opt(A) ::= .                    {A = 0;}
defer_subclause_opt(A) ::= defer_subclause(X).  {A = X;}

// The following is a non-standard extension that allows us to declare the
// default behavior when there is a constraint conflict.
//
%type onconf {int}
%type orconf {u8}
%type resolvetype {int}
onconf(A) ::= .                              {A = OE_Default;}
onconf(A) ::= ON CONFLICT resolvetype(X).    {A = X;}
orconf(A) ::= .                              {A = OE_Default;}
orconf(A) ::= OR resolvetype(X).             {A = (u8)X;}
resolvetype(A) ::= raisetype(X).             {A = X;}
resolvetype(A) ::= IGNORE.                   {A = OE_Ignore;}
resolvetype(A) ::= REPLACE.                  {A = OE_Replace;}

////////////////////////// The DROP TABLE /////////////////////////////////////
//
cmd ::= DROP TABLE ifexists(E) fullname(X). {
  sqlite3DropTable(pParse, X, 0, E);
}
%type ifexists {int}
ifexists(A) ::= IF EXISTS.   {A = 1;}
ifexists(A) ::= .            {A = 0;}

///////////////////// The CREATE VIEW statement /////////////////////////////
//
%ifndef SQLITE_OMIT_VIEW
cmd ::= createkw(X) temp(T) VIEW ifnotexists(E) nm(Y) dbnm(Z) AS select(S). {
  sqlite3CreateView(pParse, &X, &Y, &Z, S, T, E);
}
cmd ::= DROP VIEW ifexists(E) fullname(X). {
  sqlite3DropTable(pParse, X, 1, E);
}
%endif  SQLITE_OMIT_VIEW

//////////////////////// The SELECT statement /////////////////////////////////
//
cmd ::= select(X).  {
  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  sqlite3Select(pParse, X, &dest);
  sqlite3SelectDelete(pParse->db, X);
}

%type select {Select*}
%destructor select {sqlite3SelectDelete(pParse->db, $$);}
%type oneselect {Select*}
%destructor oneselect {sqlite3SelectDelete(pParse->db, $$);}

select(A) ::= oneselect(X).                      {A = X;}
%ifndef SQLITE_OMIT_COMPOUND_SELECT
select(A) ::= select(X) multiselect_op(Y) oneselect(Z).  {
  if( Z ){
    Z->op = (u8)Y;
    Z->pPrior = X;
  }else{
    sqlite3SelectDelete(pParse->db, X);
  }
  A = Z;
}
%type multiselect_op {int}
multiselect_op(A) ::= UNION(OP).             {A = @OP;}
multiselect_op(A) ::= UNION ALL.             {A = TK_ALL;}
multiselect_op(A) ::= EXCEPT|INTERSECT(OP).  {A = @OP;}
%endif SQLITE_OMIT_COMPOUND_SELECT
oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
                 groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). {
  A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L.pLimit,L.pOffset);
}

// The "distinct" nonterminal is true (1) if the DISTINCT keyword is
// present and false (0) if it is not.
//
%type distinct {int}
distinct(A) ::= DISTINCT.   {A = 1;}
distinct(A) ::= ALL.        {A = 0;}
distinct(A) ::= .           {A = 0;}

// selcollist is a list of expressions that are to become the return
// values of the SELECT statement.  The "*" in statements like
// "SELECT * FROM ..." is encoded as a special expression with an
// opcode of TK_ALL.
//
%type selcollist {ExprList*}
%destructor selcollist {sqlite3ExprListDelete(pParse->db, $$);}
%type sclp {ExprList*}
%destructor sclp {sqlite3ExprListDelete(pParse->db, $$);}
sclp(A) ::= selcollist(X) COMMA.             {A = X;}
sclp(A) ::= .                                {A = 0;}
selcollist(A) ::= sclp(P) expr(X) as(Y).     {
   A = sqlite3ExprListAppend(pParse, P, X.pExpr);
   if( Y.n>0 ) sqlite3ExprListSetName(pParse, A, &Y, 1);
   sqlite3ExprListSetSpan(pParse,A,&X);
}
selcollist(A) ::= sclp(P) STAR. {
  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  A = sqlite3ExprListAppend(pParse, P, p);
}
selcollist(A) ::= sclp(P) nm(X) DOT STAR(Y). {
  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &Y);
  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &X);
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  A = sqlite3ExprListAppend(pParse,P, pDot);
}

// An option "AS <id>" phrase that can follow one of the expressions that
// define the result set, or one of the tables in the FROM clause.
//
%type as {Token}
as(X) ::= AS nm(Y).    {X = Y;}
as(X) ::= ids(Y).      {X = Y;}
as(X) ::= .            {X.n = 0;}


%type seltablist {SrcList*}
%destructor seltablist {sqlite3SrcListDelete(pParse->db, $$);}
%type stl_prefix {SrcList*}
%destructor stl_prefix {sqlite3SrcListDelete(pParse->db, $$);}
%type from {SrcList*}
%destructor from {sqlite3SrcListDelete(pParse->db, $$);}

// A complete FROM clause.
//
from(A) ::= .                {A = sqlite3DbMallocZero(pParse->db, sizeof(*A));}
from(A) ::= FROM seltablist(X). {
  A = X;
  sqlite3SrcListShiftJoinType(A);
}

// "seltablist" is a "Select Table List" - the content of the FROM clause
// in a SELECT statement.  "stl_prefix" is a prefix of this list.
//
stl_prefix(A) ::= seltablist(X) joinop(Y).    {
   A = X;
   if( ALWAYS(A && A->nSrc>0) ) A->a[A->nSrc-1].jointype = (u8)Y;
}
stl_prefix(A) ::= .                           {A = 0;}
seltablist(A) ::= stl_prefix(X) nm(Y) dbnm(D) as(Z) indexed_opt(I) on_opt(N) using_opt(U). {
  A = sqlite3SrcListAppendFromTerm(pParse,X,&Y,&D,&Z,0,N,U);
  sqlite3SrcListIndexedBy(pParse, A, &I);
}
%ifndef SQLITE_OMIT_SUBQUERY
  seltablist(A) ::= stl_prefix(X) LP select(S) RP
                    as(Z) on_opt(N) using_opt(U). {
    A = sqlite3SrcListAppendFromTerm(pParse,X,0,0,&Z,S,N,U);
  }
  seltablist(A) ::= stl_prefix(X) LP seltablist(F) RP
                    as(Z) on_opt(N) using_opt(U). {
    if( X==0 && Z.n==0 && N==0 && U==0 ){
      A = F;
    }else{
      Select *pSubquery;
      sqlite3SrcListShiftJoinType(F);
      pSubquery = sqlite3SelectNew(pParse,0,F,0,0,0,0,0,0,0);
      A = sqlite3SrcListAppendFromTerm(pParse,X,0,0,&Z,pSubquery,N,U);
    }
  }
  
  // A seltablist_paren nonterminal represents anything in a FROM that
  // is contained inside parentheses.  This can be either a subquery or
  // a grouping of table and subqueries.
  //
//  %type seltablist_paren {Select*}
//  %destructor seltablist_paren {sqlite3SelectDelete(pParse->db, $$);}
//  seltablist_paren(A) ::= select(S).      {A = S;}
//  seltablist_paren(A) ::= seltablist(F).  {
//     sqlite3SrcListShiftJoinType(F);
//     A = sqlite3SelectNew(pParse,0,F,0,0,0,0,0,0,0);
//  }
%endif  SQLITE_OMIT_SUBQUERY

%type dbnm {Token}
dbnm(A) ::= .          {A.z=0; A.n=0;}
dbnm(A) ::= DOT nm(X). {A = X;}

%type fullname {SrcList*}
%destructor fullname {sqlite3SrcListDelete(pParse->db, $$);}
fullname(A) ::= nm(X) dbnm(Y).  {A = sqlite3SrcListAppend(pParse->db,0,&X,&Y);}

%type joinop {int}
%type joinop2 {int}
joinop(X) ::= COMMA|JOIN.              { X = JT_INNER; }
joinop(X) ::= JOIN_KW(A) JOIN.         { X = sqlite3JoinType(pParse,&A,0,0); }
joinop(X) ::= JOIN_KW(A) nm(B) JOIN.   { X = sqlite3JoinType(pParse,&A,&B,0); }
joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
                                       { X = sqlite3JoinType(pParse,&A,&B,&C); }

%type on_opt {Expr*}
%destructor on_opt {sqlite3ExprDelete(pParse->db, $$);}
on_opt(N) ::= ON expr(E).   {N = E.pExpr;}
on_opt(N) ::= .             {N = 0;}

// Note that this block abuses the Token type just a little. If there is
// no "INDEXED BY" clause, the returned token is empty (z==0 && n==0). If
// there is an INDEXED BY clause, then the token is populated as per normal,
// with z pointing to the token data and n containing the number of bytes
// in the token.
//
// If there is a "NOT INDEXED" clause, then (z==0 && n==1), which is 
// normally illegal. The sqlite3SrcListIndexedBy() function 
// recognizes and interprets this as a special case.
//
%type indexed_opt {Token}
indexed_opt(A) ::= .                 {A.z=0; A.n=0;}
indexed_opt(A) ::= INDEXED BY nm(X). {A = X;}
indexed_opt(A) ::= NOT INDEXED.      {A.z=0; A.n=1;}

%type using_opt {IdList*}
%destructor using_opt {sqlite3IdListDelete(pParse->db, $$);}
using_opt(U) ::= USING LP inscollist(L) RP.  {U = L;}
using_opt(U) ::= .                        {U = 0;}


%type orderby_opt {ExprList*}
%destructor orderby_opt {sqlite3ExprListDelete(pParse->db, $$);}
%type sortlist {ExprList*}
%destructor sortlist {sqlite3ExprListDelete(pParse->db, $$);}
%type sortitem {Expr*}
%destructor sortitem {sqlite3ExprDelete(pParse->db, $$);}

orderby_opt(A) ::= .                          {A = 0;}
orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
sortlist(A) ::= sortlist(X) COMMA sortitem(Y) sortorder(Z). {
  A = sqlite3ExprListAppend(pParse,X,Y);
  if( A ) A->a[A->nExpr-1].sortOrder = (u8)Z;
}
sortlist(A) ::= sortitem(Y) sortorder(Z). {
  A = sqlite3ExprListAppend(pParse,0,Y);
  if( A && ALWAYS(A->a) ) A->a[0].sortOrder = (u8)Z;
}
sortitem(A) ::= expr(X).   {A = X.pExpr;}

%type sortorder {int}

sortorder(A) ::= ASC.           {A = SQLITE_SO_ASC;}
sortorder(A) ::= DESC.          {A = SQLITE_SO_DESC;}
sortorder(A) ::= .              {A = SQLITE_SO_ASC;}

%type groupby_opt {ExprList*}
%destructor groupby_opt {sqlite3ExprListDelete(pParse->db, $$);}
groupby_opt(A) ::= .                      {A = 0;}
groupby_opt(A) ::= GROUP BY nexprlist(X). {A = X;}

%type having_opt {Expr*}
%destructor having_opt {sqlite3ExprDelete(pParse->db, $$);}
having_opt(A) ::= .                {A = 0;}
having_opt(A) ::= HAVING expr(X).  {A = X.pExpr;}

%type limit_opt {struct LimitVal}

// The destructor for limit_opt will never fire in the current grammar.
// The limit_opt non-terminal only occurs at the end of a single production
// rule for SELECT statements.  As soon as the rule that create the 
// limit_opt non-terminal reduces, the SELECT statement rule will also
// reduce.  So there is never a limit_opt non-terminal on the stack 
// except as a transient.  So there is never anything to destroy.
//
//%destructor limit_opt {
//  sqlite3ExprDelete(pParse->db, $$.pLimit);
//  sqlite3ExprDelete(pParse->db, $$.pOffset);
//}
limit_opt(A) ::= .                    {A.pLimit = 0; A.pOffset = 0;}
limit_opt(A) ::= LIMIT expr(X).       {A.pLimit = X.pExpr; A.pOffset = 0;}
limit_opt(A) ::= LIMIT expr(X) OFFSET expr(Y). 
                                      {A.pLimit = X.pExpr; A.pOffset = Y.pExpr;}
limit_opt(A) ::= LIMIT expr(X) COMMA expr(Y). 
                                      {A.pOffset = X.pExpr; A.pLimit = Y.pExpr;}

/////////////////////////// The DELETE statement /////////////////////////////
//
%ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
cmd ::= DELETE FROM fullname(X) indexed_opt(I) where_opt(W) 
        orderby_opt(O) limit_opt(L). {
  sqlite3SrcListIndexedBy(pParse, X, &I);
  W = sqlite3LimitWhere(pParse, X, W, O, L.pLimit, L.pOffset, "DELETE");
  sqlite3DeleteFrom(pParse,X,W);
}
%endif
%ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
cmd ::= DELETE FROM fullname(X) indexed_opt(I) where_opt(W). {
  sqlite3SrcListIndexedBy(pParse, X, &I);
  sqlite3DeleteFrom(pParse,X,W);
}
%endif

%type where_opt {Expr*}
%destructor where_opt {sqlite3ExprDelete(pParse->db, $$);}

where_opt(A) ::= .                    {A = 0;}
where_opt(A) ::= WHERE expr(X).       {A = X.pExpr;}

////////////////////////// The UPDATE command ////////////////////////////////
//
%ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
cmd ::= UPDATE orconf(R) fullname(X) indexed_opt(I) SET setlist(Y) where_opt(W) orderby_opt(O) limit_opt(L).  {
  sqlite3SrcListIndexedBy(pParse, X, &I);
  sqlite3ExprListCheckLength(pParse,Y,"set list"); 
  W = sqlite3LimitWhere(pParse, X, W, O, L.pLimit, L.pOffset, "UPDATE");
  sqlite3Update(pParse,X,Y,W,R);
}
%endif
%ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
cmd ::= UPDATE orconf(R) fullname(X) indexed_opt(I) SET setlist(Y) where_opt(W).  {
  sqlite3SrcListIndexedBy(pParse, X, &I);
  sqlite3ExprListCheckLength(pParse,Y,"set list"); 
  sqlite3Update(pParse,X,Y,W,R);
}
%endif

%type setlist {ExprList*}
%destructor setlist {sqlite3ExprListDelete(pParse->db, $$);}

setlist(A) ::= setlist(Z) COMMA nm(X) EQ expr(Y). {
  A = sqlite3ExprListAppend(pParse, Z, Y.pExpr);
  sqlite3ExprListSetName(pParse, A, &X, 1);
}
setlist(A) ::= nm(X) EQ expr(Y). {
  A = sqlite3ExprListAppend(pParse, 0, Y.pExpr);
  sqlite3ExprListSetName(pParse, A, &X, 1);
}

////////////////////////// The INSERT command /////////////////////////////////
//
cmd ::= insert_cmd(R) INTO fullname(X) inscollist_opt(F) 
        VALUES LP itemlist(Y) RP.
            {sqlite3Insert(pParse, X, Y, 0, F, R);}
cmd ::= insert_cmd(R) INTO fullname(X) inscollist_opt(F) select(S).
            {sqlite3Insert(pParse, X, 0, S, F, R);}
cmd ::= insert_cmd(R) INTO fullname(X) inscollist_opt(F) DEFAULT VALUES.
            {sqlite3Insert(pParse, X, 0, 0, F, R);}

%type insert_cmd {u8}
insert_cmd(A) ::= INSERT orconf(R).   {A = R;}
insert_cmd(A) ::= REPLACE.            {A = OE_Replace;}


%type itemlist {ExprList*}
%destructor itemlist {sqlite3ExprListDelete(pParse->db, $$);}

itemlist(A) ::= itemlist(X) COMMA expr(Y).
    {A = sqlite3ExprListAppend(pParse,X,Y.pExpr);}
itemlist(A) ::= expr(X).
    {A = sqlite3ExprListAppend(pParse,0,X.pExpr);}

%type inscollist_opt {IdList*}
%destructor inscollist_opt {sqlite3IdListDelete(pParse->db, $$);}
%type inscollist {IdList*}
%destructor inscollist {sqlite3IdListDelete(pParse->db, $$);}

inscollist_opt(A) ::= .                       {A = 0;}
inscollist_opt(A) ::= LP inscollist(X) RP.    {A = X;}
inscollist(A) ::= inscollist(X) COMMA nm(Y).
    {A = sqlite3IdListAppend(pParse->db,X,&Y);}
inscollist(A) ::= nm(Y).
    {A = sqlite3IdListAppend(pParse->db,0,&Y);}

/////////////////////////// Expression Processing /////////////////////////////
//

%type expr {ExprSpan}
%destructor expr {sqlite3ExprDelete(pParse->db, $$.pExpr);}
%type term {ExprSpan}
%destructor term {sqlite3ExprDelete(pParse->db, $$.pExpr);}

%include {
  /* This is a utility routine used to set the ExprSpan.zStart and
  ** ExprSpan.zEnd values of pOut so that the span covers the complete
  ** range of text beginning with pStart and going to the end of pEnd.
  */
  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
    pOut->zStart = pStart->z;
    pOut->zEnd = &pEnd->z[pEnd->n];
  }

  /* Construct a new Expr object from a single identifier.  Use the
  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
  ** that created the expression.
  */
  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
    pOut->zStart = pValue->z;
    pOut->zEnd = &pValue->z[pValue->n];
  }
}

expr(A) ::= term(X).             {A = X;}
expr(A) ::= LP(B) expr(X) RP(E). {A.pExpr = X.pExpr; spanSet(&A,&B,&E);}
term(A) ::= NULL(X).             {spanExpr(&A, pParse, @X, &X);}
expr(A) ::= id(X).               {spanExpr(&A, pParse, TK_ID, &X);}
expr(A) ::= JOIN_KW(X).          {spanExpr(&A, pParse, TK_ID, &X);}
expr(A) ::= nm(X) DOT nm(Y). {
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &X);
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &Y);
  A.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  spanSet(&A,&X,&Y);
}
expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &X);
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &Y);
  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &Z);
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  A.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  spanSet(&A,&X,&Z);
}
term(A) ::= INTEGER|FLOAT|BLOB(X).  {spanExpr(&A, pParse, @X, &X);}
term(A) ::= STRING(X).              {spanExpr(&A, pParse, @X, &X);}
expr(A) ::= REGISTER(X).     {
  /* When doing a nested parse, one can include terms in an expression
  ** that look like this:   #1 #2 ...  These terms refer to registers
  ** in the virtual machine.  #N is the N-th register. */
  if( pParse->nested==0 ){
    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &X);
    A.pExpr = 0;
  }else{
    A.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &X);
    if( A.pExpr ) sqlite3GetInt32(&X.z[1], &A.pExpr->iTable);
  }
  spanSet(&A, &X, &X);
}
expr(A) ::= VARIABLE(X).     {
  spanExpr(&A, pParse, TK_VARIABLE, &X);
  sqlite3ExprAssignVarNumber(pParse, A.pExpr);
  spanSet(&A, &X, &X);
}
expr(A) ::= expr(E) COLLATE ids(C). {
  A.pExpr = sqlite3ExprSetColl(pParse, E.pExpr, &C);
  A.zStart = E.zStart;
  A.zEnd = &C.z[C.n];
}
%ifndef SQLITE_OMIT_CAST
expr(A) ::= CAST(X) LP expr(E) AS typetoken(T) RP(Y). {
  A.pExpr = sqlite3PExpr(pParse, TK_CAST, E.pExpr, 0, &T);
  spanSet(&A,&X,&Y);
}
%endif  SQLITE_OMIT_CAST
expr(A) ::= ID(X) LP distinct(D) exprlist(Y) RP(E). {
  if( Y && Y->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &X);
  }
  A.pExpr = sqlite3ExprFunction(pParse, Y, &X);
  spanSet(&A,&X,&E);
  if( D && A.pExpr ){
    A.pExpr->flags |= EP_Distinct;
  }
}
expr(A) ::= ID(X) LP STAR RP(E). {
  A.pExpr = sqlite3ExprFunction(pParse, 0, &X);
  spanSet(&A,&X,&E);
}
term(A) ::= CTIME_KW(OP). {
  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  ** treated as functions that return constants */
  A.pExpr = sqlite3ExprFunction(pParse, 0,&OP);
  if( A.pExpr ){
    A.pExpr->op = TK_CONST_FUNC;  
  }
  spanSet(&A, &OP, &OP);
}

%include {
  /* This routine constructs a binary expression node out of two ExprSpan
  ** objects and uses the result to populate a new ExprSpan object.
  */
  static void spanBinaryExpr(
    ExprSpan *pOut,     /* Write the result here */
    Parse *pParse,      /* The parsing context.  Errors accumulate here */
    int op,             /* The binary operation */
    ExprSpan *pLeft,    /* The left operand */
    ExprSpan *pRight    /* The right operand */
  ){
    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
    pOut->zStart = pLeft->zStart;
    pOut->zEnd = pRight->zEnd;
  }
}

expr(A) ::= expr(X) AND(OP) expr(Y).    {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) OR(OP) expr(Y).     {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) LT|GT|GE|LE(OP) expr(Y).
                                        {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) EQ|NE(OP) expr(Y).  {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) BITAND|BITOR|LSHIFT|RSHIFT(OP) expr(Y).
                                        {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) PLUS|MINUS(OP) expr(Y).
                                        {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) STAR|SLASH|REM(OP) expr(Y).
                                        {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
expr(A) ::= expr(X) CONCAT(OP) expr(Y). {spanBinaryExpr(&A,pParse,@OP,&X,&Y);}
%type likeop {struct LikeOp}
likeop(A) ::= LIKE_KW(X).     {A.eOperator = X; A.not = 0;}
likeop(A) ::= NOT LIKE_KW(X). {A.eOperator = X; A.not = 1;}
likeop(A) ::= MATCH(X).       {A.eOperator = X; A.not = 0;}
likeop(A) ::= NOT MATCH(X).   {A.eOperator = X; A.not = 1;}
%type escape {ExprSpan}
%destructor escape {sqlite3ExprDelete(pParse->db, $$.pExpr);}
escape(X) ::= ESCAPE expr(A). [ESCAPE] {X = A;}
escape(X) ::= .               [ESCAPE] {memset(&X,0,sizeof(X));}
expr(A) ::= expr(X) likeop(OP) expr(Y) escape(E).  [LIKE_KW]  {
  ExprList *pList;
  pList = sqlite3ExprListAppend(pParse,0, Y.pExpr);
  pList = sqlite3ExprListAppend(pParse,pList, X.pExpr);
  if( E.pExpr ){
    pList = sqlite3ExprListAppend(pParse,pList, E.pExpr);
  }
  A.pExpr = sqlite3ExprFunction(pParse, pList, &OP.eOperator);
  if( OP.not ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0);
  A.zStart = X.zStart;
  A.zEnd = Y.zEnd;
  if( A.pExpr ) A.pExpr->flags |= EP_InfixFunc;
}

%include {
  /* Construct an expression node for a unary postfix operator
  */
  static void spanUnaryPostfix(
    ExprSpan *pOut,        /* Write the new expression node here */
    Parse *pParse,         /* Parsing context to record errors */
    int op,                /* The operator */
    ExprSpan *pOperand,    /* The operand */
    Token *pPostOp         /* The operand token for setting the span */
  ){
    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
    pOut->zStart = pOperand->zStart;
    pOut->zEnd = &pPostOp->z[pPostOp->n];
  }                           
}

expr(A) ::= expr(X) ISNULL|NOTNULL(E).   {spanUnaryPostfix(&A,pParse,@E,&X,&E);}
expr(A) ::= expr(X) NOT NULL(E). {spanUnaryPostfix(&A,pParse,TK_NOTNULL,&X,&E);}

//    expr1 IS expr2
//    expr1 IS NOT expr2
//
// If expr2 is NULL then code as TK_ISNULL or TK_NOTNULL.  If expr2
// is any other expression, code as TK_IS or TK_ISNOT.
// 
expr(A) ::= expr(X) IS expr(Y).     {
  spanBinaryExpr(&A,pParse,TK_IS,&X,&Y);
  if( pParse->db->mallocFailed==0  && Y.pExpr->op==TK_NULL ){
    A.pExpr->op = TK_ISNULL;
  }
}
expr(A) ::= expr(X) IS NOT expr(Y). {
  spanBinaryExpr(&A,pParse,TK_ISNOT,&X,&Y);
  if( pParse->db->mallocFailed==0  && Y.pExpr->op==TK_NULL ){
    A.pExpr->op = TK_NOTNULL;
  }
}

%include {
  /* Construct an expression node for a unary prefix operator
  */
  static void spanUnaryPrefix(
    ExprSpan *pOut,        /* Write the new expression node here */
    Parse *pParse,         /* Parsing context to record errors */
    int op,                /* The operator */
    ExprSpan *pOperand,    /* The operand */
    Token *pPreOp         /* The operand token for setting the span */
  ){
    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
    pOut->zStart = pPreOp->z;
    pOut->zEnd = pOperand->zEnd;
  }
}



expr(A) ::= NOT(B) expr(X).    {spanUnaryPrefix(&A,pParse,@B,&X,&B);}
expr(A) ::= BITNOT(B) expr(X). {spanUnaryPrefix(&A,pParse,@B,&X,&B);}
expr(A) ::= MINUS(B) expr(X). [BITNOT]
                               {spanUnaryPrefix(&A,pParse,TK_UMINUS,&X,&B);}
expr(A) ::= PLUS(B) expr(X). [BITNOT]
                               {spanUnaryPrefix(&A,pParse,TK_UPLUS,&X,&B);}

%type between_op {int}
between_op(A) ::= BETWEEN.     {A = 0;}
between_op(A) ::= NOT BETWEEN. {A = 1;}
expr(A) ::= expr(W) between_op(N) expr(X) AND expr(Y). [BETWEEN] {
  ExprList *pList = sqlite3ExprListAppend(pParse,0, X.pExpr);
  pList = sqlite3ExprListAppend(pParse,pList, Y.pExpr);
  A.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, W.pExpr, 0, 0);
  if( A.pExpr ){
    A.pExpr->x.pList = pList;
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  } 
  if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0);
  A.zStart = W.zStart;
  A.zEnd = Y.zEnd;
}
%ifndef SQLITE_OMIT_SUBQUERY
  %type in_op {int}
  in_op(A) ::= IN.      {A = 0;}
  in_op(A) ::= NOT IN.  {A = 1;}
  expr(A) ::= expr(X) in_op(N) LP exprlist(Y) RP(E). [IN] {
    A.pExpr = sqlite3PExpr(pParse, TK_IN, X.pExpr, 0, 0);
    if( A.pExpr ){
      A.pExpr->x.pList = Y;
      sqlite3ExprSetHeight(pParse, A.pExpr);
    }else{
      sqlite3ExprListDelete(pParse->db, Y);
    }
    if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0);
    A.zStart = X.zStart;
    A.zEnd = &E.z[E.n];
  }
  expr(A) ::= LP(B) select(X) RP(E). {
    A.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
    if( A.pExpr ){
      A.pExpr->x.pSelect = X;
      ExprSetProperty(A.pExpr, EP_xIsSelect);
      sqlite3ExprSetHeight(pParse, A.pExpr);
    }else{
      sqlite3SelectDelete(pParse->db, X);
    }
    A.zStart = B.z;
    A.zEnd = &E.z[E.n];
  }
  expr(A) ::= expr(X) in_op(N) LP select(Y) RP(E).  [IN] {
    A.pExpr = sqlite3PExpr(pParse, TK_IN, X.pExpr, 0, 0);
    if( A.pExpr ){
      A.pExpr->x.pSelect = Y;
      ExprSetProperty(A.pExpr, EP_xIsSelect);
      sqlite3ExprSetHeight(pParse, A.pExpr);
    }else{
      sqlite3SelectDelete(pParse->db, Y);
    }
    if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0);
    A.zStart = X.zStart;
    A.zEnd = &E.z[E.n];
  }
  expr(A) ::= expr(X) in_op(N) nm(Y) dbnm(Z). [IN] {
    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&Y,&Z);
    A.pExpr = sqlite3PExpr(pParse, TK_IN, X.pExpr, 0, 0);
    if( A.pExpr ){
      A.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
      ExprSetProperty(A.pExpr, EP_xIsSelect);
      sqlite3ExprSetHeight(pParse, A.pExpr);
    }else{
      sqlite3SrcListDelete(pParse->db, pSrc);
    }
    if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0);
    A.zStart = X.zStart;
    A.zEnd = Z.z ? &Z.z[Z.n] : &Y.z[Y.n];
  }
  expr(A) ::= EXISTS(B) LP select(Y) RP(E). {
    Expr *p = A.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
    if( p ){
      p->x.pSelect = Y;
      ExprSetProperty(p, EP_xIsSelect);
      sqlite3ExprSetHeight(pParse, p);
    }else{
      sqlite3SelectDelete(pParse->db, Y);
    }
    A.zStart = B.z;
    A.zEnd = &E.z[E.n];
  }
%endif SQLITE_OMIT_SUBQUERY

/* CASE expressions */
expr(A) ::= CASE(C) case_operand(X) case_exprlist(Y) case_else(Z) END(E). {
  A.pExpr = sqlite3PExpr(pParse, TK_CASE, X, Z, 0);
  if( A.pExpr ){
    A.pExpr->x.pList = Y;
    sqlite3ExprSetHeight(pParse, A.pExpr);
  }else{
    sqlite3ExprListDelete(pParse->db, Y);
  }
  A.zStart = C.z;
  A.zEnd = &E.z[E.n];
}
%type case_exprlist {ExprList*}
%destructor case_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
case_exprlist(A) ::= case_exprlist(X) WHEN expr(Y) THEN expr(Z). {
  A = sqlite3ExprListAppend(pParse,X, Y.pExpr);
  A = sqlite3ExprListAppend(pParse,A, Z.pExpr);
}
case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
  A = sqlite3ExprListAppend(pParse,0, Y.pExpr);
  A = sqlite3ExprListAppend(pParse,A, Z.pExpr);
}
%type case_else {Expr*}
%destructor case_else {sqlite3ExprDelete(pParse->db, $$);}
case_else(A) ::=  ELSE expr(X).         {A = X.pExpr;}
case_else(A) ::=  .                     {A = 0;} 
%type case_operand {Expr*}
%destructor case_operand {sqlite3ExprDelete(pParse->db, $$);}
case_operand(A) ::= expr(X).            {A = X.pExpr;} 
case_operand(A) ::= .                   {A = 0;} 

%type exprlist {ExprList*}
%destructor exprlist {sqlite3ExprListDelete(pParse->db, $$);}
%type nexprlist {ExprList*}
%destructor nexprlist {sqlite3ExprListDelete(pParse->db, $$);}

exprlist(A) ::= nexprlist(X).                {A = X;}
exprlist(A) ::= .                            {A = 0;}
nexprlist(A) ::= nexprlist(X) COMMA expr(Y).
    {A = sqlite3ExprListAppend(pParse,X,Y.pExpr);}
nexprlist(A) ::= expr(Y).
    {A = sqlite3ExprListAppend(pParse,0,Y.pExpr);}


///////////////////////////// The CREATE INDEX command ///////////////////////
//
cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D)
        ON nm(Y) LP idxlist(Z) RP(E). {
  sqlite3CreateIndex(pParse, &X, &D, 
                     sqlite3SrcListAppend(pParse->db,0,&Y,0), Z, U,
                      &S, &E, SQLITE_SO_ASC, NE);
}

%type uniqueflag {int}
uniqueflag(A) ::= UNIQUE.  {A = OE_Abort;}
uniqueflag(A) ::= .        {A = OE_None;}

%type idxlist {ExprList*}
%destructor idxlist {sqlite3ExprListDelete(pParse->db, $$);}
%type idxlist_opt {ExprList*}
%destructor idxlist_opt {sqlite3ExprListDelete(pParse->db, $$);}

idxlist_opt(A) ::= .                         {A = 0;}
idxlist_opt(A) ::= LP idxlist(X) RP.         {A = X;}
idxlist(A) ::= idxlist(X) COMMA nm(Y) collate(C) sortorder(Z).  {
  Expr *p = 0;
  if( C.n>0 ){
    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
    sqlite3ExprSetColl(pParse, p, &C);
  }
  A = sqlite3ExprListAppend(pParse,X, p);
  sqlite3ExprListSetName(pParse,A,&Y,1);
  sqlite3ExprListCheckLength(pParse, A, "index");
  if( A ) A->a[A->nExpr-1].sortOrder = (u8)Z;
}
idxlist(A) ::= nm(Y) collate(C) sortorder(Z). {
  Expr *p = 0;
  if( C.n>0 ){
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
    sqlite3ExprSetColl(pParse, p, &C);
  }
  A = sqlite3ExprListAppend(pParse,0, p);
  sqlite3ExprListSetName(pParse, A, &Y, 1);
  sqlite3ExprListCheckLength(pParse, A, "index");
  if( A ) A->a[A->nExpr-1].sortOrder = (u8)Z;
}

%type collate {Token}
collate(C) ::= .                 {C.z = 0; C.n = 0;}
collate(C) ::= COLLATE ids(X).   {C = X;}


///////////////////////////// The DROP INDEX command /////////////////////////
//
cmd ::= DROP INDEX ifexists(E) fullname(X).   {sqlite3DropIndex(pParse, X, E);}

///////////////////////////// The VACUUM command /////////////////////////////
//
%ifndef SQLITE_OMIT_VACUUM
%ifndef SQLITE_OMIT_ATTACH
cmd ::= VACUUM.                {sqlite3Vacuum(pParse);}
cmd ::= VACUUM nm.             {sqlite3Vacuum(pParse);}
%endif  SQLITE_OMIT_ATTACH
%endif  SQLITE_OMIT_VACUUM

///////////////////////////// The PRAGMA command /////////////////////////////
//
%ifndef SQLITE_OMIT_PRAGMA
cmd ::= PRAGMA nm(X) dbnm(Z).                {sqlite3Pragma(pParse,&X,&Z,0,0);}
cmd ::= PRAGMA nm(X) dbnm(Z) EQ nmnum(Y).    {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
cmd ::= PRAGMA nm(X) dbnm(Z) LP nmnum(Y) RP. {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
cmd ::= PRAGMA nm(X) dbnm(Z) EQ minus_num(Y). 
                                             {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
cmd ::= PRAGMA nm(X) dbnm(Z) LP minus_num(Y) RP.
                                             {sqlite3Pragma(pParse,&X,&Z,&Y,1);}

nmnum(A) ::= plus_num(X).             {A = X;}
nmnum(A) ::= nm(X).                   {A = X;}
nmnum(A) ::= ON(X).                   {A = X;}
nmnum(A) ::= DELETE(X).               {A = X;}
nmnum(A) ::= DEFAULT(X).              {A = X;}
%endif SQLITE_OMIT_PRAGMA
plus_num(A) ::= plus_opt number(X).   {A = X;}
minus_num(A) ::= MINUS number(X).     {A = X;}
number(A) ::= INTEGER|FLOAT(X).       {A = X;}
plus_opt ::= PLUS.
plus_opt ::= .

//////////////////////////// The CREATE TRIGGER command /////////////////////

%ifndef SQLITE_OMIT_TRIGGER

cmd ::= createkw trigger_decl(A) BEGIN trigger_cmd_list(S) END(Z). {
  Token all;
  all.z = A.z;
  all.n = (int)(Z.z - A.z) + Z.n;
  sqlite3FinishTrigger(pParse, S, &all);
}

trigger_decl(A) ::= temp(T) TRIGGER ifnotexists(NOERR) nm(B) dbnm(Z) 
                    trigger_time(C) trigger_event(D)
                    ON fullname(E) foreach_clause when_clause(G). {
  sqlite3BeginTrigger(pParse, &B, &Z, C, D.a, D.b, E, G, T, NOERR);
  A = (Z.n==0?B:Z);
}

%type trigger_time {int}
trigger_time(A) ::= BEFORE.      { A = TK_BEFORE; }
trigger_time(A) ::= AFTER.       { A = TK_AFTER;  }
trigger_time(A) ::= INSTEAD OF.  { A = TK_INSTEAD;}
trigger_time(A) ::= .            { A = TK_BEFORE; }

%type trigger_event {struct TrigEvent}
%destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);}
trigger_event(A) ::= DELETE|INSERT(OP).       {A.a = @OP; A.b = 0;}
trigger_event(A) ::= UPDATE(OP).              {A.a = @OP; A.b = 0;}
trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X;}

foreach_clause ::= .
foreach_clause ::= FOR EACH ROW.

%type when_clause {Expr*}
%destructor when_clause {sqlite3ExprDelete(pParse->db, $$);}
when_clause(A) ::= .             { A = 0; }
when_clause(A) ::= WHEN expr(X). { A = X.pExpr; }

%type trigger_cmd_list {TriggerStep*}
%destructor trigger_cmd_list {sqlite3DeleteTriggerStep(pParse->db, $$);}
trigger_cmd_list(A) ::= trigger_cmd_list(Y) trigger_cmd(X) SEMI. {
  assert( Y!=0 );
  Y->pLast->pNext = X;
  Y->pLast = X;
  A = Y;
}
trigger_cmd_list(A) ::= trigger_cmd(X) SEMI. { 
  assert( X!=0 );
  X->pLast = X;
  A = X;
}

// Disallow qualified table names on INSERT, UPDATE, and DELETE statements
// within a trigger.  The table to INSERT, UPDATE, or DELETE is always in 
// the same database as the table that the trigger fires on.
//
%type trnm {Token}
trnm(A) ::= nm(X).   {A = X;}
trnm(A) ::= nm DOT nm(X). {
  A = X;
  sqlite3ErrorMsg(pParse, 
        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
        "statements within triggers");
}

// Disallow the INDEX BY and NOT INDEXED clauses on UPDATE and DELETE
// statements within triggers.  We make a specific error message for this
// since it is an exception to the default grammar rules.
//
tridxby ::= .
tridxby ::= INDEXED BY nm. {
  sqlite3ErrorMsg(pParse,
        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
tridxby ::= NOT INDEXED. {
  sqlite3ErrorMsg(pParse,
        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}



%type trigger_cmd {TriggerStep*}
%destructor trigger_cmd {sqlite3DeleteTriggerStep(pParse->db, $$);}
// UPDATE 
trigger_cmd(A) ::=
   UPDATE orconf(R) trnm(X) tridxby SET setlist(Y) where_opt(Z).  
   { A = sqlite3TriggerUpdateStep(pParse->db, &X, Y, Z, R); }

// INSERT
trigger_cmd(A) ::=
   insert_cmd(R) INTO trnm(X) inscollist_opt(F) VALUES LP itemlist(Y) RP.  
   {A = sqlite3TriggerInsertStep(pParse->db, &X, F, Y, 0, R);}

trigger_cmd(A) ::= insert_cmd(R) INTO trnm(X) inscollist_opt(F) select(S).
               {A = sqlite3TriggerInsertStep(pParse->db, &X, F, 0, S, R);}

// DELETE
trigger_cmd(A) ::= DELETE FROM trnm(X) tridxby where_opt(Y).
               {A = sqlite3TriggerDeleteStep(pParse->db, &X, Y);}

// SELECT
trigger_cmd(A) ::= select(X).  {A = sqlite3TriggerSelectStep(pParse->db, X); }

// The special RAISE expression that may occur in trigger programs
expr(A) ::= RAISE(X) LP IGNORE RP(Y).  {
  A.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
  if( A.pExpr ){
    A.pExpr->affinity = OE_Ignore;
  }
  A.zStart = X.z;
  A.zEnd = &Y.z[Y.n];
}
expr(A) ::= RAISE(X) LP raisetype(T) COMMA nm(Z) RP(Y).  {
  A.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &Z); 
  if( A.pExpr ) {
    A.pExpr->affinity = (char)T;
  }
  A.zStart = X.z;
  A.zEnd = &Y.z[Y.n];
}
%endif  !SQLITE_OMIT_TRIGGER

%type raisetype {int}
raisetype(A) ::= ROLLBACK.  {A = OE_Rollback;}
raisetype(A) ::= ABORT.     {A = OE_Abort;}
raisetype(A) ::= FAIL.      {A = OE_Fail;}


////////////////////////  DROP TRIGGER statement //////////////////////////////
%ifndef SQLITE_OMIT_TRIGGER
cmd ::= DROP TRIGGER ifexists(NOERR) fullname(X). {
  sqlite3DropTrigger(pParse,X,NOERR);
}
%endif  !SQLITE_OMIT_TRIGGER

//////////////////////// ATTACH DATABASE file AS name /////////////////////////
%ifndef SQLITE_OMIT_ATTACH
cmd ::= ATTACH database_kw_opt expr(F) AS expr(D) key_opt(K). {
  sqlite3Attach(pParse, F.pExpr, D.pExpr, K);
}
cmd ::= DETACH database_kw_opt expr(D). {
  sqlite3Detach(pParse, D.pExpr);
}

%type key_opt {Expr*}
%destructor key_opt {sqlite3ExprDelete(pParse->db, $$);}
key_opt(A) ::= .                     { A = 0; }
key_opt(A) ::= KEY expr(X).          { A = X.pExpr; }

database_kw_opt ::= DATABASE.
database_kw_opt ::= .
%endif SQLITE_OMIT_ATTACH

////////////////////////// REINDEX collation //////////////////////////////////
%ifndef SQLITE_OMIT_REINDEX
cmd ::= REINDEX.                {sqlite3Reindex(pParse, 0, 0);}
cmd ::= REINDEX nm(X) dbnm(Y).  {sqlite3Reindex(pParse, &X, &Y);}
%endif  SQLITE_OMIT_REINDEX

/////////////////////////////////// ANALYZE ///////////////////////////////////
%ifndef SQLITE_OMIT_ANALYZE
cmd ::= ANALYZE.                {sqlite3Analyze(pParse, 0, 0);}
cmd ::= ANALYZE nm(X) dbnm(Y).  {sqlite3Analyze(pParse, &X, &Y);}
%endif

//////////////////////// ALTER TABLE table ... ////////////////////////////////
%ifndef SQLITE_OMIT_ALTERTABLE
cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). {
  sqlite3AlterRenameTable(pParse,X,&Z);
}
cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column(Y). {
  sqlite3AlterFinishAddColumn(pParse, &Y);
}
add_column_fullname ::= fullname(X). {
  pParse->db->lookaside.bEnabled = 0;
  sqlite3AlterBeginAddColumn(pParse, X);
}
kwcolumn_opt ::= .
kwcolumn_opt ::= COLUMNKW.
%endif  SQLITE_OMIT_ALTERTABLE

//////////////////////// CREATE VIRTUAL TABLE ... /////////////////////////////
%ifndef SQLITE_OMIT_VIRTUALTABLE
cmd ::= create_vtab.                       {sqlite3VtabFinishParse(pParse,0);}
cmd ::= create_vtab LP vtabarglist RP(X).  {sqlite3VtabFinishParse(pParse,&X);}
create_vtab ::= createkw VIRTUAL TABLE nm(X) dbnm(Y) USING nm(Z). {
    sqlite3VtabBeginParse(pParse, &X, &Y, &Z);
}
vtabarglist ::= vtabarg.
vtabarglist ::= vtabarglist COMMA vtabarg.
vtabarg ::= .                       {sqlite3VtabArgInit(pParse);}
vtabarg ::= vtabarg vtabargtoken.
vtabargtoken ::= ANY(X).            {sqlite3VtabArgExtend(pParse,&X);}
vtabargtoken ::= lp anylist RP(X).  {sqlite3VtabArgExtend(pParse,&X);}
lp ::= LP(X).                       {sqlite3VtabArgExtend(pParse,&X);}
anylist ::= .
anylist ::= anylist LP anylist RP.
anylist ::= anylist ANY.
%endif  SQLITE_OMIT_VIRTUALTABLE

Added src/pcache.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
** 2008 August 05
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements that page cache.
**
** @(#) $Id: pcache.c,v 1.47 2009/07/25 11:46:49 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** A complete page cache is an instance of this structure.
*/
struct PCache {
  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
  PgHdr *pSynced;                     /* Last synced page in dirty page list */
  int nRef;                           /* Number of referenced pages */
  int nMax;                           /* Configured cache size */
  int szPage;                         /* Size of every page in this cache */
  int szExtra;                        /* Size of extra space for each page */
  int bPurgeable;                     /* True if pages are on backing store */
  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
  void *pStress;                      /* Argument to xStress */
  sqlite3_pcache *pCache;             /* Pluggable cache module */
  PgHdr *pPage1;                      /* Reference to page 1 */
};

/*
** Some of the assert() macros in this code are too expensive to run
** even during normal debugging.  Use them only rarely on long-running
** tests.  Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
*/
#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
# define expensive_assert(X)  assert(X)
#else
# define expensive_assert(X)
#endif

/********************************** Linked List Management ********************/

#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
/*
** Check that the pCache->pSynced variable is set correctly. If it
** is not, either fail an assert or return zero. Otherwise, return
** non-zero. This is only used in debugging builds, as follows:
**
**   expensive_assert( pcacheCheckSynced(pCache) );
*/
static int pcacheCheckSynced(PCache *pCache){
  PgHdr *p;
  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  }
  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
}
#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */

/*
** Remove page pPage from the list of dirty pages.
*/
static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  PCache *p = pPage->pCache;

  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  assert( pPage->pDirtyPrev || pPage==p->pDirty );

  /* Update the PCache1.pSynced variable if necessary. */
  if( p->pSynced==pPage ){
    PgHdr *pSynced = pPage->pDirtyPrev;
    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
      pSynced = pSynced->pDirtyPrev;
    }
    p->pSynced = pSynced;
  }

  if( pPage->pDirtyNext ){
    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  }else{
    assert( pPage==p->pDirtyTail );
    p->pDirtyTail = pPage->pDirtyPrev;
  }
  if( pPage->pDirtyPrev ){
    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  }else{
    assert( pPage==p->pDirty );
    p->pDirty = pPage->pDirtyNext;
  }
  pPage->pDirtyNext = 0;
  pPage->pDirtyPrev = 0;

  expensive_assert( pcacheCheckSynced(p) );
}

/*
** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
** pPage).
*/
static void pcacheAddToDirtyList(PgHdr *pPage){
  PCache *p = pPage->pCache;

  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );

  pPage->pDirtyNext = p->pDirty;
  if( pPage->pDirtyNext ){
    assert( pPage->pDirtyNext->pDirtyPrev==0 );
    pPage->pDirtyNext->pDirtyPrev = pPage;
  }
  p->pDirty = pPage;
  if( !p->pDirtyTail ){
    p->pDirtyTail = pPage;
  }
  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
    p->pSynced = pPage;
  }
  expensive_assert( pcacheCheckSynced(p) );
}

/*
** Wrapper around the pluggable caches xUnpin method. If the cache is
** being used for an in-memory database, this function is a no-op.
*/
static void pcacheUnpin(PgHdr *p){
  PCache *pCache = p->pCache;
  if( pCache->bPurgeable ){
    if( p->pgno==1 ){
      pCache->pPage1 = 0;
    }
    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
  }
}

/*************************************************** General Interfaces ******
**
** Initialize and shutdown the page cache subsystem. Neither of these 
** functions are threadsafe.
*/
int sqlite3PcacheInitialize(void){
  if( sqlite3GlobalConfig.pcache.xInit==0 ){
    sqlite3PCacheSetDefault();
  }
  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
}
void sqlite3PcacheShutdown(void){
  if( sqlite3GlobalConfig.pcache.xShutdown ){
    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
  }
}

/*
** Return the size in bytes of a PCache object.
*/
int sqlite3PcacheSize(void){ return sizeof(PCache); }

/*
** Create a new PCache object. Storage space to hold the object
** has already been allocated and is passed in as the p pointer. 
** The caller discovers how much space needs to be allocated by 
** calling sqlite3PcacheSize().
*/
void sqlite3PcacheOpen(
  int szPage,                  /* Size of every page */
  int szExtra,                 /* Extra space associated with each page */
  int bPurgeable,              /* True if pages are on backing store */
  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  void *pStress,               /* Argument to xStress */
  PCache *p                    /* Preallocated space for the PCache */
){
  memset(p, 0, sizeof(PCache));
  p->szPage = szPage;
  p->szExtra = szExtra;
  p->bPurgeable = bPurgeable;
  p->xStress = xStress;
  p->pStress = pStress;
  p->nMax = 100;
}

/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  assert( pCache->nRef==0 && pCache->pDirty==0 );
  if( pCache->pCache ){
    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
    pCache->pCache = 0;
  }
  pCache->szPage = szPage;
}

/*
** Try to obtain a page from the cache.
*/
int sqlite3PcacheFetch(
  PCache *pCache,       /* Obtain the page from this cache */
  Pgno pgno,            /* Page number to obtain */
  int createFlag,       /* If true, create page if it does not exist already */
  PgHdr **ppPage        /* Write the page here */
){
  PgHdr *pPage = 0;
  int eCreate;

  assert( pCache!=0 );
  assert( createFlag==1 || createFlag==0 );
  assert( pgno>0 );

  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  ** allocate it now.
  */
  if( !pCache->pCache && createFlag ){
    sqlite3_pcache *p;
    int nByte;
    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
    if( !p ){
      return SQLITE_NOMEM;
    }
    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
    pCache->pCache = p;
  }

  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  if( pCache->pCache ){
    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
  }

  if( !pPage && eCreate==1 ){
    PgHdr *pPg;

    /* Find a dirty page to write-out and recycle. First try to find a 
    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
    ** cleared), but if that is not possible settle for any other 
    ** unreferenced dirty page.
    */
    expensive_assert( pcacheCheckSynced(pCache) );
    for(pPg=pCache->pSynced; 
        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
        pPg=pPg->pDirtyPrev
    );
    if( !pPg ){
      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
    }
    if( pPg ){
      int rc;
      rc = pCache->xStress(pCache->pStress, pPg);
      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
        return rc;
      }
    }

    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
  }

  if( pPage ){
    if( !pPage->pData ){
      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
      pPage->pExtra = (void*)&pPage[1];
      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
      pPage->pCache = pCache;
      pPage->pgno = pgno;
    }
    assert( pPage->pCache==pCache );
    assert( pPage->pgno==pgno );
    assert( pPage->pExtra==(void *)&pPage[1] );

    if( 0==pPage->nRef ){
      pCache->nRef++;
    }
    pPage->nRef++;
    if( pgno==1 ){
      pCache->pPage1 = pPage;
    }
  }
  *ppPage = pPage;
  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
}

/*
** Decrement the reference count on a page. If the page is clean and the
** reference count drops to 0, then it is made elible for recycling.
*/
void sqlite3PcacheRelease(PgHdr *p){
  assert( p->nRef>0 );
  p->nRef--;
  if( p->nRef==0 ){
    PCache *pCache = p->pCache;
    pCache->nRef--;
    if( (p->flags&PGHDR_DIRTY)==0 ){
      pcacheUnpin(p);
    }else{
      /* Move the page to the head of the dirty list. */
      pcacheRemoveFromDirtyList(p);
      pcacheAddToDirtyList(p);
    }
  }
}

/*
** Increase the reference count of a supplied page by 1.
*/
void sqlite3PcacheRef(PgHdr *p){
  assert(p->nRef>0);
  p->nRef++;
}

/*
** Drop a page from the cache. There must be exactly one reference to the
** page. This function deletes that reference, so after it returns the
** page pointed to by p is invalid.
*/
void sqlite3PcacheDrop(PgHdr *p){
  PCache *pCache;
  assert( p->nRef==1 );
  if( p->flags&PGHDR_DIRTY ){
    pcacheRemoveFromDirtyList(p);
  }
  pCache = p->pCache;
  pCache->nRef--;
  if( p->pgno==1 ){
    pCache->pPage1 = 0;
  }
  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
}

/*
** Make sure the page is marked as dirty. If it isn't dirty already,
** make it so.
*/
void sqlite3PcacheMakeDirty(PgHdr *p){
  p->flags &= ~PGHDR_DONT_WRITE;
  assert( p->nRef>0 );
  if( 0==(p->flags & PGHDR_DIRTY) ){
    p->flags |= PGHDR_DIRTY;
    pcacheAddToDirtyList( p);
  }
}

/*
** Make sure the page is marked as clean. If it isn't clean already,
** make it so.
*/
void sqlite3PcacheMakeClean(PgHdr *p){
  if( (p->flags & PGHDR_DIRTY) ){
    pcacheRemoveFromDirtyList(p);
    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
    if( p->nRef==0 ){
      pcacheUnpin(p);
    }
  }
}

/*
** Make every page in the cache clean.
*/
void sqlite3PcacheCleanAll(PCache *pCache){
  PgHdr *p;
  while( (p = pCache->pDirty)!=0 ){
    sqlite3PcacheMakeClean(p);
  }
}

/*
** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
*/
void sqlite3PcacheClearSyncFlags(PCache *pCache){
  PgHdr *p;
  for(p=pCache->pDirty; p; p=p->pDirtyNext){
    p->flags &= ~PGHDR_NEED_SYNC;
  }
  pCache->pSynced = pCache->pDirtyTail;
}

/*
** Change the page number of page p to newPgno. 
*/
void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  PCache *pCache = p->pCache;
  assert( p->nRef>0 );
  assert( newPgno>0 );
  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
  p->pgno = newPgno;
  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
    pcacheRemoveFromDirtyList(p);
    pcacheAddToDirtyList(p);
  }
}

/*
** Drop every cache entry whose page number is greater than "pgno". The
** caller must ensure that there are no outstanding references to any pages
** other than page 1 with a page number greater than pgno.
**
** If there is a reference to page 1 and the pgno parameter passed to this
** function is 0, then the data area associated with page 1 is zeroed, but
** the page object is not dropped.
*/
void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  if( pCache->pCache ){
    PgHdr *p;
    PgHdr *pNext;
    for(p=pCache->pDirty; p; p=pNext){
      pNext = p->pDirtyNext;
      if( p->pgno>pgno ){
        assert( p->flags&PGHDR_DIRTY );
        sqlite3PcacheMakeClean(p);
      }
    }
    if( pgno==0 && pCache->pPage1 ){
      memset(pCache->pPage1->pData, 0, pCache->szPage);
      pgno = 1;
    }
    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
  }
}

/*
** Close a cache.
*/
void sqlite3PcacheClose(PCache *pCache){
  if( pCache->pCache ){
    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  }
}

/* 
** Discard the contents of the cache.
*/
void sqlite3PcacheClear(PCache *pCache){
  sqlite3PcacheTruncate(pCache, 0);
}

/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  PgHdr result, *pTail;
  pTail = &result;
  while( pA && pB ){
    if( pA->pgno<pB->pgno ){
      pTail->pDirty = pA;
      pTail = pA;
      pA = pA->pDirty;
    }else{
      pTail->pDirty = pB;
      pTail = pB;
      pB = pB->pDirty;
    }
  }
  if( pA ){
    pTail->pDirty = pA;
  }else if( pB ){
    pTail->pDirty = pB;
  }else{
    pTail->pDirty = 0;
  }
  return result.pDirty;
}

/*
** Sort the list of pages in accending order by pgno.  Pages are
** connected by pDirty pointers.  The pDirtyPrev pointers are
** corrupted by this sort.
**
** Since there cannot be more than 2^31 distinct pages in a database,
** there cannot be more than 31 buckets required by the merge sorter.
** One extra bucket is added to catch overflow in case something
** ever changes to make the previous sentence incorrect.
*/
#define N_SORT_BUCKET  32
static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  PgHdr *a[N_SORT_BUCKET], *p;
  int i;
  memset(a, 0, sizeof(a));
  while( pIn ){
    p = pIn;
    pIn = p->pDirty;
    p->pDirty = 0;
    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
      if( a[i]==0 ){
        a[i] = p;
        break;
      }else{
        p = pcacheMergeDirtyList(a[i], p);
        a[i] = 0;
      }
    }
    if( NEVER(i==N_SORT_BUCKET-1) ){
      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
      ** the input list.  But that is impossible.
      */
      a[i] = pcacheMergeDirtyList(a[i], p);
    }
  }
  p = a[0];
  for(i=1; i<N_SORT_BUCKET; i++){
    p = pcacheMergeDirtyList(p, a[i]);
  }
  return p;
}

/*
** Return a list of all dirty pages in the cache, sorted by page number.
*/
PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  PgHdr *p;
  for(p=pCache->pDirty; p; p=p->pDirtyNext){
    p->pDirty = p->pDirtyNext;
  }
  return pcacheSortDirtyList(pCache->pDirty);
}

/* 
** Return the total number of referenced pages held by the cache.
*/
int sqlite3PcacheRefCount(PCache *pCache){
  return pCache->nRef;
}

/*
** Return the number of references to the page supplied as an argument.
*/
int sqlite3PcachePageRefcount(PgHdr *p){
  return p->nRef;
}

/* 
** Return the total number of pages in the cache.
*/
int sqlite3PcachePagecount(PCache *pCache){
  int nPage = 0;
  if( pCache->pCache ){
    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
  }
  return nPage;
}

#ifdef SQLITE_TEST
/*
** Get the suggested cache-size value.
*/
int sqlite3PcacheGetCachesize(PCache *pCache){
  return pCache->nMax;
}
#endif

/*
** Set the suggested cache-size value.
*/
void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  pCache->nMax = mxPage;
  if( pCache->pCache ){
    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
  }
}

#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
/*
** For all dirty pages currently in the cache, invoke the specified
** callback. This is only used if the SQLITE_CHECK_PAGES macro is
** defined.
*/
void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  PgHdr *pDirty;
  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
    xIter(pDirty);
  }
}
#endif

Added src/pcache.h.



























































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*
** 2008 August 05
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem. 
**
** @(#) $Id: pcache.h,v 1.20 2009/07/25 11:46:49 danielk1977 Exp $
*/

#ifndef _PCACHE_H_

typedef struct PgHdr PgHdr;
typedef struct PCache PCache;

/*
** Every page in the cache is controlled by an instance of the following
** structure.
*/
struct PgHdr {
  void *pData;                   /* Content of this page */
  void *pExtra;                  /* Extra content */
  PgHdr *pDirty;                 /* Transient list of dirty pages */
  Pgno pgno;                     /* Page number for this page */
  Pager *pPager;                 /* The pager this page is part of */
#ifdef SQLITE_CHECK_PAGES
  u32 pageHash;                  /* Hash of page content */
#endif
  u16 flags;                     /* PGHDR flags defined below */

  /**********************************************************************
  ** Elements above are public.  All that follows is private to pcache.c
  ** and should not be accessed by other modules.
  */
  i16 nRef;                      /* Number of users of this page */
  PCache *pCache;                /* Cache that owns this page */

  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
};

/* Bit values for PgHdr.flags */
#define PGHDR_DIRTY             0x002  /* Page has changed */
#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
                                       ** writing this page to the database */
#define PGHDR_NEED_READ         0x008  /* Content is unread */
#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */

/* Initialize and shutdown the page cache subsystem */
int sqlite3PcacheInitialize(void);
void sqlite3PcacheShutdown(void);

/* Page cache buffer management:
** These routines implement SQLITE_CONFIG_PAGECACHE.
*/
void sqlite3PCacheBufferSetup(void *, int sz, int n);

/* Create a new pager cache.
** Under memory stress, invoke xStress to try to make pages clean.
** Only clean and unpinned pages can be reclaimed.
*/
void sqlite3PcacheOpen(
  int szPage,                    /* Size of every page */
  int szExtra,                   /* Extra space associated with each page */
  int bPurgeable,                /* True if pages are on backing store */
  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  void *pStress,                 /* Argument to xStress */
  PCache *pToInit                /* Preallocated space for the PCache */
);

/* Modify the page-size after the cache has been created. */
void sqlite3PcacheSetPageSize(PCache *, int);

/* Return the size in bytes of a PCache object.  Used to preallocate
** storage space.
*/
int sqlite3PcacheSize(void);

/* One release per successful fetch.  Page is pinned until released.
** Reference counted. 
*/
int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
void sqlite3PcacheRelease(PgHdr*);

void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */

/* Change a page number.  Used by incr-vacuum. */
void sqlite3PcacheMove(PgHdr*, Pgno);

/* Remove all pages with pgno>x.  Reset the cache if x==0 */
void sqlite3PcacheTruncate(PCache*, Pgno x);

/* Get a list of all dirty pages in the cache, sorted by page number */
PgHdr *sqlite3PcacheDirtyList(PCache*);

/* Reset and close the cache object */
void sqlite3PcacheClose(PCache*);

/* Clear flags from pages of the page cache */
void sqlite3PcacheClearSyncFlags(PCache *);

/* Discard the contents of the cache */
void sqlite3PcacheClear(PCache*);

/* Return the total number of outstanding page references */
int sqlite3PcacheRefCount(PCache*);

/* Increment the reference count of an existing page */
void sqlite3PcacheRef(PgHdr*);

int sqlite3PcachePageRefcount(PgHdr*);

/* Return the total number of pages stored in the cache */
int sqlite3PcachePagecount(PCache*);

#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
/* Iterate through all dirty pages currently stored in the cache. This
** interface is only available if SQLITE_CHECK_PAGES is defined when the 
** library is built.
*/
void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
#endif

/* Set and get the suggested cache-size for the specified pager-cache.
**
** If no global maximum is configured, then the system attempts to limit
** the total number of pages cached by purgeable pager-caches to the sum
** of the suggested cache-sizes.
*/
void sqlite3PcacheSetCachesize(PCache *, int);
#ifdef SQLITE_TEST
int sqlite3PcacheGetCachesize(PCache *);
#endif

#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
/* Try to return memory used by the pcache module to the main memory heap */
int sqlite3PcacheReleaseMemory(int);
#endif

#ifdef SQLITE_TEST
void sqlite3PcacheStats(int*,int*,int*,int*);
#endif

void sqlite3PCacheSetDefault(void);

#endif /* _PCACHE_H_ */

Added src/pcache1.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/*
** 2008 November 05
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file implements the default page cache implementation (the
** sqlite3_pcache interface). It also contains part of the implementation
** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
** If the default page cache implementation is overriden, then neither of
** these two features are available.
**
** @(#) $Id: pcache1.c,v 1.19 2009/07/17 11:44:07 drh Exp $
*/

#include "sqliteInt.h"

typedef struct PCache1 PCache1;
typedef struct PgHdr1 PgHdr1;
typedef struct PgFreeslot PgFreeslot;

/* Pointers to structures of this type are cast and returned as 
** opaque sqlite3_pcache* handles
*/
struct PCache1 {
  /* Cache configuration parameters. Page size (szPage) and the purgeable
  ** flag (bPurgeable) are set when the cache is created. nMax may be 
  ** modified at any time by a call to the pcache1CacheSize() method.
  ** The global mutex must be held when accessing nMax.
  */
  int szPage;                         /* Size of allocated pages in bytes */
  int bPurgeable;                     /* True if cache is purgeable */
  unsigned int nMin;                  /* Minimum number of pages reserved */
  unsigned int nMax;                  /* Configured "cache_size" value */

  /* Hash table of all pages. The following variables may only be accessed
  ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
  ** and pcache1LeaveMutex()).
  */
  unsigned int nRecyclable;           /* Number of pages in the LRU list */
  unsigned int nPage;                 /* Total number of pages in apHash */
  unsigned int nHash;                 /* Number of slots in apHash[] */
  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */

  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
};

/*
** Each cache entry is represented by an instance of the following 
** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
** macro below).
*/
struct PgHdr1 {
  unsigned int iKey;             /* Key value (page number) */
  PgHdr1 *pNext;                 /* Next in hash table chain */
  PCache1 *pCache;               /* Cache that currently owns this page */
  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
};

/*
** Free slots in the allocator used to divide up the buffer provided using
** the SQLITE_CONFIG_PAGECACHE mechanism.
*/
struct PgFreeslot {
  PgFreeslot *pNext;  /* Next free slot */
};

/*
** Global data used by this cache.
*/
static SQLITE_WSD struct PCacheGlobal {
  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */

  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
  int nCurrentPage;                   /* Number of purgeable pages allocated */
  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */

  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
  int szSlot;                         /* Size of each free slot */
  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
  PgFreeslot *pFree;                  /* Free page blocks */
  int isInit;                         /* True if initialized */
} pcache1_g;

/*
** All code in this file should access the global structure above via the
** alias "pcache1". This ensures that the WSD emulation is used when
** compiling for systems that do not support real WSD.
*/
#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))

/*
** When a PgHdr1 structure is allocated, the associated PCache1.szPage
** bytes of data are located directly before it in memory (i.e. the total
** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
** an argument and returns a pointer to the associated block of szPage
** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
** a pointer to a block of szPage bytes of data and the return value is
** a pointer to the associated PgHdr1 structure.
**
**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
*/
#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)

/*
** Macros to enter and leave the global LRU mutex.
*/
#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)

/******************************************************************************/
/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/

/*
** This function is called during initialization if a static buffer is 
** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
** verb to sqlite3_config(). Parameter pBuf points to an allocation large
** enough to contain 'n' buffers of 'sz' bytes each.
*/
void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  if( pcache1.isInit ){
    PgFreeslot *p;
    sz = ROUNDDOWN8(sz);
    pcache1.szSlot = sz;
    pcache1.pStart = pBuf;
    pcache1.pFree = 0;
    while( n-- ){
      p = (PgFreeslot*)pBuf;
      p->pNext = pcache1.pFree;
      pcache1.pFree = p;
      pBuf = (void*)&((char*)pBuf)[sz];
    }
    pcache1.pEnd = pBuf;
  }
}

/*
** Malloc function used within this file to allocate space from the buffer
** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
** such buffer exists or there is no space left in it, this function falls 
** back to sqlite3Malloc().
*/
static void *pcache1Alloc(int nByte){
  void *p;
  assert( sqlite3_mutex_held(pcache1.mutex) );
  if( nByte<=pcache1.szSlot && pcache1.pFree ){
    assert( pcache1.isInit );
    p = (PgHdr1 *)pcache1.pFree;
    pcache1.pFree = pcache1.pFree->pNext;
    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  }else{

    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
    ** global pcache mutex and unlock the pager-cache object pCache. This is 
    ** so that if the attempt to allocate a new buffer causes the the 
    ** configured soft-heap-limit to be breached, it will be possible to
    ** reclaim memory from this pager-cache.
    */
    pcache1LeaveMutex();
    p = sqlite3Malloc(nByte);
    pcache1EnterMutex();
    if( p ){
      int sz = sqlite3MallocSize(p);
      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
    }
  }
  return p;
}

/*
** Free an allocated buffer obtained from pcache1Alloc().
*/
static void pcache1Free(void *p){
  assert( sqlite3_mutex_held(pcache1.mutex) );
  if( p==0 ) return;
  if( p>=pcache1.pStart && p<pcache1.pEnd ){
    PgFreeslot *pSlot;
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
    pSlot = (PgFreeslot*)p;
    pSlot->pNext = pcache1.pFree;
    pcache1.pFree = pSlot;
  }else{
    int iSize = sqlite3MallocSize(p);
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
    sqlite3_free(p);
  }
}

/*
** Allocate a new page object initially associated with cache pCache.
*/
static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  int nByte = sizeof(PgHdr1) + pCache->szPage;
  void *pPg = pcache1Alloc(nByte);
  PgHdr1 *p;
  if( pPg ){
    p = PAGE_TO_PGHDR1(pCache, pPg);
    if( pCache->bPurgeable ){
      pcache1.nCurrentPage++;
    }
  }else{
    p = 0;
  }
  return p;
}

/*
** Free a page object allocated by pcache1AllocPage().
**
** The pointer is allowed to be NULL, which is prudent.  But it turns out
** that the current implementation happens to never call this routine
** with a NULL pointer, so we mark the NULL test with ALWAYS().
*/
static void pcache1FreePage(PgHdr1 *p){
  if( ALWAYS(p) ){
    if( p->pCache->bPurgeable ){
      pcache1.nCurrentPage--;
    }
    pcache1Free(PGHDR1_TO_PAGE(p));
  }
}

/*
** Malloc function used by SQLite to obtain space from the buffer configured
** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
** exists, this function falls back to sqlite3Malloc().
*/
void *sqlite3PageMalloc(int sz){
  void *p;
  pcache1EnterMutex();
  p = pcache1Alloc(sz);
  pcache1LeaveMutex();
  return p;
}

/*
** Free an allocated buffer obtained from sqlite3PageMalloc().
*/
void sqlite3PageFree(void *p){
  pcache1EnterMutex();
  pcache1Free(p);
  pcache1LeaveMutex();
}

/******************************************************************************/
/******** General Implementation Functions ************************************/

/*
** This function is used to resize the hash table used by the cache passed
** as the first argument.
**
** The global mutex must be held when this function is called.
*/
static int pcache1ResizeHash(PCache1 *p){
  PgHdr1 **apNew;
  unsigned int nNew;
  unsigned int i;

  assert( sqlite3_mutex_held(pcache1.mutex) );

  nNew = p->nHash*2;
  if( nNew<256 ){
    nNew = 256;
  }

  pcache1LeaveMutex();
  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
  if( p->nHash ){ sqlite3EndBenignMalloc(); }
  pcache1EnterMutex();
  if( apNew ){
    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
    for(i=0; i<p->nHash; i++){
      PgHdr1 *pPage;
      PgHdr1 *pNext = p->apHash[i];
      while( (pPage = pNext)!=0 ){
        unsigned int h = pPage->iKey % nNew;
        pNext = pPage->pNext;
        pPage->pNext = apNew[h];
        apNew[h] = pPage;
      }
    }
    sqlite3_free(p->apHash);
    p->apHash = apNew;
    p->nHash = nNew;
  }

  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
}

/*
** This function is used internally to remove the page pPage from the 
** global LRU list, if is part of it. If pPage is not part of the global
** LRU list, then this function is a no-op.
**
** The global mutex must be held when this function is called.
*/
static void pcache1PinPage(PgHdr1 *pPage){
  assert( sqlite3_mutex_held(pcache1.mutex) );
  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
    if( pPage->pLruPrev ){
      pPage->pLruPrev->pLruNext = pPage->pLruNext;
    }
    if( pPage->pLruNext ){
      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
    }
    if( pcache1.pLruHead==pPage ){
      pcache1.pLruHead = pPage->pLruNext;
    }
    if( pcache1.pLruTail==pPage ){
      pcache1.pLruTail = pPage->pLruPrev;
    }
    pPage->pLruNext = 0;
    pPage->pLruPrev = 0;
    pPage->pCache->nRecyclable--;
  }
}


/*
** Remove the page supplied as an argument from the hash table 
** (PCache1.apHash structure) that it is currently stored in.
**
** The global mutex must be held when this function is called.
*/
static void pcache1RemoveFromHash(PgHdr1 *pPage){
  unsigned int h;
  PCache1 *pCache = pPage->pCache;
  PgHdr1 **pp;

  h = pPage->iKey % pCache->nHash;
  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  *pp = (*pp)->pNext;

  pCache->nPage--;
}

/*
** If there are currently more than pcache.nMaxPage pages allocated, try
** to recycle pages to reduce the number allocated to pcache.nMaxPage.
*/
static void pcache1EnforceMaxPage(void){
  assert( sqlite3_mutex_held(pcache1.mutex) );
  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
    PgHdr1 *p = pcache1.pLruTail;
    pcache1PinPage(p);
    pcache1RemoveFromHash(p);
    pcache1FreePage(p);
  }
}

/*
** Discard all pages from cache pCache with a page number (key value) 
** greater than or equal to iLimit. Any pinned pages that meet this 
** criteria are unpinned before they are discarded.
**
** The global mutex must be held when this function is called.
*/
static void pcache1TruncateUnsafe(
  PCache1 *pCache, 
  unsigned int iLimit 
){
  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
  unsigned int h;
  assert( sqlite3_mutex_held(pcache1.mutex) );
  for(h=0; h<pCache->nHash; h++){
    PgHdr1 **pp = &pCache->apHash[h]; 
    PgHdr1 *pPage;
    while( (pPage = *pp)!=0 ){
      if( pPage->iKey>=iLimit ){
        pCache->nPage--;
        *pp = pPage->pNext;
        pcache1PinPage(pPage);
        pcache1FreePage(pPage);
      }else{
        pp = &pPage->pNext;
        TESTONLY( nPage++; )
      }
    }
  }
  assert( pCache->nPage==nPage );
}

/******************************************************************************/
/******** sqlite3_pcache Methods **********************************************/

/*
** Implementation of the sqlite3_pcache.xInit method.
*/
static int pcache1Init(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  assert( pcache1.isInit==0 );
  memset(&pcache1, 0, sizeof(pcache1));
  if( sqlite3GlobalConfig.bCoreMutex ){
    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  }
  pcache1.isInit = 1;
  return SQLITE_OK;
}

/*
** Implementation of the sqlite3_pcache.xShutdown method.
** Note that the static mutex allocated in xInit does 
** not need to be freed.
*/
static void pcache1Shutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  assert( pcache1.isInit!=0 );
  memset(&pcache1, 0, sizeof(pcache1));
}

/*
** Implementation of the sqlite3_pcache.xCreate method.
**
** Allocate a new cache.
*/
static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
  PCache1 *pCache;

  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
  if( pCache ){
    memset(pCache, 0, sizeof(PCache1));
    pCache->szPage = szPage;
    pCache->bPurgeable = (bPurgeable ? 1 : 0);
    if( bPurgeable ){
      pCache->nMin = 10;
      pcache1EnterMutex();
      pcache1.nMinPage += pCache->nMin;
      pcache1LeaveMutex();
    }
  }
  return (sqlite3_pcache *)pCache;
}

/*
** Implementation of the sqlite3_pcache.xCachesize method. 
**
** Configure the cache_size limit for a cache.
*/
static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  PCache1 *pCache = (PCache1 *)p;
  if( pCache->bPurgeable ){
    pcache1EnterMutex();
    pcache1.nMaxPage += (nMax - pCache->nMax);
    pCache->nMax = nMax;
    pcache1EnforceMaxPage();
    pcache1LeaveMutex();
  }
}

/*
** Implementation of the sqlite3_pcache.xPagecount method. 
*/
static int pcache1Pagecount(sqlite3_pcache *p){
  int n;
  pcache1EnterMutex();
  n = ((PCache1 *)p)->nPage;
  pcache1LeaveMutex();
  return n;
}

/*
** Implementation of the sqlite3_pcache.xFetch method. 
**
** Fetch a page by key value.
**
** Whether or not a new page may be allocated by this function depends on
** the value of the createFlag argument.  0 means do not allocate a new
** page.  1 means allocate a new page if space is easily available.  2 
** means to try really hard to allocate a new page.
**
** For a non-purgeable cache (a cache used as the storage for an in-memory
** database) there is really no difference between createFlag 1 and 2.  So
** the calling function (pcache.c) will never have a createFlag of 1 on
** a non-purgable cache.
**
** There are three different approaches to obtaining space for a page,
** depending on the value of parameter createFlag (which may be 0, 1 or 2).
**
**   1. Regardless of the value of createFlag, the cache is searched for a 
**      copy of the requested page. If one is found, it is returned.
**
**   2. If createFlag==0 and the page is not already in the cache, NULL is
**      returned.
**
**   3. If createFlag is 1, and the page is not already in the cache,
**      and if either of the following are true, return NULL:
**
**       (a) the number of pages pinned by the cache is greater than
**           PCache1.nMax, or
**       (b) the number of pages pinned by the cache is greater than
**           the sum of nMax for all purgeable caches, less the sum of 
**           nMin for all other purgeable caches. 
**
**   4. If none of the first three conditions apply and the cache is marked
**      as purgeable, and if one of the following is true:
**
**       (a) The number of pages allocated for the cache is already 
**           PCache1.nMax, or
**
**       (b) The number of pages allocated for all purgeable caches is
**           already equal to or greater than the sum of nMax for all
**           purgeable caches,
**
**      then attempt to recycle a page from the LRU list. If it is the right
**      size, return the recycled buffer. Otherwise, free the buffer and
**      proceed to step 5. 
**
**   5. Otherwise, allocate and return a new page buffer.
*/
static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
  unsigned int nPinned;
  PCache1 *pCache = (PCache1 *)p;
  PgHdr1 *pPage = 0;

  assert( pCache->bPurgeable || createFlag!=1 );
  pcache1EnterMutex();
  if( createFlag==1 ) sqlite3BeginBenignMalloc();

  /* Search the hash table for an existing entry. */
  if( pCache->nHash>0 ){
    unsigned int h = iKey % pCache->nHash;
    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  }

  if( pPage || createFlag==0 ){
    pcache1PinPage(pPage);
    goto fetch_out;
  }

  /* Step 3 of header comment. */
  nPinned = pCache->nPage - pCache->nRecyclable;
  if( createFlag==1 && (
        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
     || nPinned>=(pCache->nMax * 9 / 10)
  )){
    goto fetch_out;
  }

  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
    goto fetch_out;
  }

  /* Step 4. Try to recycle a page buffer if appropriate. */
  if( pCache->bPurgeable && pcache1.pLruTail && (
     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
  )){
    pPage = pcache1.pLruTail;
    pcache1RemoveFromHash(pPage);
    pcache1PinPage(pPage);
    if( pPage->pCache->szPage!=pCache->szPage ){
      pcache1FreePage(pPage);
      pPage = 0;
    }else{
      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
    }
  }

  /* Step 5. If a usable page buffer has still not been found, 
  ** attempt to allocate a new one. 
  */
  if( !pPage ){
    pPage = pcache1AllocPage(pCache);
  }

  if( pPage ){
    unsigned int h = iKey % pCache->nHash;
    pCache->nPage++;
    pPage->iKey = iKey;
    pPage->pNext = pCache->apHash[h];
    pPage->pCache = pCache;
    pPage->pLruPrev = 0;
    pPage->pLruNext = 0;
    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
    pCache->apHash[h] = pPage;
  }

fetch_out:
  if( pPage && iKey>pCache->iMaxKey ){
    pCache->iMaxKey = iKey;
  }
  if( createFlag==1 ) sqlite3EndBenignMalloc();
  pcache1LeaveMutex();
  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
}


/*
** Implementation of the sqlite3_pcache.xUnpin method.
**
** Mark a page as unpinned (eligible for asynchronous recycling).
*/
static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
  PCache1 *pCache = (PCache1 *)p;
  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
 
  assert( pPage->pCache==pCache );
  pcache1EnterMutex();

  /* It is an error to call this function if the page is already 
  ** part of the global LRU list.
  */
  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );

  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
    pcache1RemoveFromHash(pPage);
    pcache1FreePage(pPage);
  }else{
    /* Add the page to the global LRU list. Normally, the page is added to
    ** the head of the list (last page to be recycled). However, if the 
    ** reuseUnlikely flag passed to this function is true, the page is added
    ** to the tail of the list (first page to be recycled).
    */
    if( pcache1.pLruHead ){
      pcache1.pLruHead->pLruPrev = pPage;
      pPage->pLruNext = pcache1.pLruHead;
      pcache1.pLruHead = pPage;
    }else{
      pcache1.pLruTail = pPage;
      pcache1.pLruHead = pPage;
    }
    pCache->nRecyclable++;
  }

  pcache1LeaveMutex();
}

/*
** Implementation of the sqlite3_pcache.xRekey method. 
*/
static void pcache1Rekey(
  sqlite3_pcache *p,
  void *pPg,
  unsigned int iOld,
  unsigned int iNew
){
  PCache1 *pCache = (PCache1 *)p;
  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
  PgHdr1 **pp;
  unsigned int h; 
  assert( pPage->iKey==iOld );
  assert( pPage->pCache==pCache );

  pcache1EnterMutex();

  h = iOld%pCache->nHash;
  pp = &pCache->apHash[h];
  while( (*pp)!=pPage ){
    pp = &(*pp)->pNext;
  }
  *pp = pPage->pNext;

  h = iNew%pCache->nHash;
  pPage->iKey = iNew;
  pPage->pNext = pCache->apHash[h];
  pCache->apHash[h] = pPage;

  /* The xRekey() interface is only used to move pages earlier in the
  ** database file (in order to move all free pages to the end of the
  ** file where they can be truncated off.)  Hence, it is not possible
  ** for the new page number to be greater than the largest previously
  ** fetched page.  But we retain the following test in case xRekey()
  ** begins to be used in different ways in the future.
  */
  if( NEVER(iNew>pCache->iMaxKey) ){
    pCache->iMaxKey = iNew;
  }

  pcache1LeaveMutex();
}

/*
** Implementation of the sqlite3_pcache.xTruncate method. 
**
** Discard all unpinned pages in the cache with a page number equal to
** or greater than parameter iLimit. Any pinned pages with a page number
** equal to or greater than iLimit are implicitly unpinned.
*/
static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  PCache1 *pCache = (PCache1 *)p;
  pcache1EnterMutex();
  if( iLimit<=pCache->iMaxKey ){
    pcache1TruncateUnsafe(pCache, iLimit);
    pCache->iMaxKey = iLimit-1;
  }
  pcache1LeaveMutex();
}

/*
** Implementation of the sqlite3_pcache.xDestroy method. 
**
** Destroy a cache allocated using pcache1Create().
*/
static void pcache1Destroy(sqlite3_pcache *p){
  PCache1 *pCache = (PCache1 *)p;
  pcache1EnterMutex();
  pcache1TruncateUnsafe(pCache, 0);
  pcache1.nMaxPage -= pCache->nMax;
  pcache1.nMinPage -= pCache->nMin;
  pcache1EnforceMaxPage();
  pcache1LeaveMutex();
  sqlite3_free(pCache->apHash);
  sqlite3_free(pCache);
}

/*
** This function is called during initialization (sqlite3_initialize()) to
** install the default pluggable cache module, assuming the user has not
** already provided an alternative.
*/
void sqlite3PCacheSetDefault(void){
  static sqlite3_pcache_methods defaultMethods = {
    0,                       /* pArg */
    pcache1Init,             /* xInit */
    pcache1Shutdown,         /* xShutdown */
    pcache1Create,           /* xCreate */
    pcache1Cachesize,        /* xCachesize */
    pcache1Pagecount,        /* xPagecount */
    pcache1Fetch,            /* xFetch */
    pcache1Unpin,            /* xUnpin */
    pcache1Rekey,            /* xRekey */
    pcache1Truncate,         /* xTruncate */
    pcache1Destroy           /* xDestroy */
  };
  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
}

#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
/*
** This function is called to free superfluous dynamically allocated memory
** held by the pager system. Memory in use by any SQLite pager allocated
** by the current thread may be sqlite3_free()ed.
**
** nReq is the number of bytes of memory required. Once this much has
** been released, the function returns. The return value is the total number 
** of bytes of memory released.
*/
int sqlite3PcacheReleaseMemory(int nReq){
  int nFree = 0;
  if( pcache1.pStart==0 ){
    PgHdr1 *p;
    pcache1EnterMutex();
    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
      nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
      pcache1PinPage(p);
      pcache1RemoveFromHash(p);
      pcache1FreePage(p);
    }
    pcache1LeaveMutex();
  }
  return nFree;
}
#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */

#ifdef SQLITE_TEST
/*
** This function is used by test procedures to inspect the internal state
** of the global cache.
*/
void sqlite3PcacheStats(
  int *pnCurrent,      /* OUT: Total number of pages cached */
  int *pnMax,          /* OUT: Global maximum cache size */
  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
){
  PgHdr1 *p;
  int nRecyclable = 0;
  for(p=pcache1.pLruHead; p; p=p->pLruNext){
    nRecyclable++;
  }
  *pnCurrent = pcache1.nCurrentPage;
  *pnMax = pcache1.nMaxPage;
  *pnMin = pcache1.nMinPage;
  *pnRecyclable = nRecyclable;
}
#endif

Added src/pragma.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
/*
** 2003 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the PRAGMA command.
**
** $Id: pragma.c,v 1.214 2009/07/02 07:47:33 danielk1977 Exp $
*/
#include "sqliteInt.h"

/* Ignore this whole file if pragmas are disabled
*/
#if !defined(SQLITE_OMIT_PRAGMA)

/*
** Interpret the given string as a safety level.  Return 0 for OFF,
** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
** unrecognized string argument.
**
** Note that the values returned are one less that the values that
** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
** to support legacy SQL code.  The safety level used to be boolean
** and older scripts may have used numbers 0 for OFF and 1 for ON.
*/
static u8 getSafetyLevel(const char *z){
                             /* 123456789 123456789 */
  static const char zText[] = "onoffalseyestruefull";
  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
  int i, n;
  if( sqlite3Isdigit(*z) ){
    return (u8)atoi(z);
  }
  n = sqlite3Strlen30(z);
  for(i=0; i<ArraySize(iLength); i++){
    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
      return iValue[i];
    }
  }
  return 1;
}

/*
** Interpret the given string as a boolean value.
*/
static u8 getBoolean(const char *z){
  return getSafetyLevel(z)&1;
}

/*
** Interpret the given string as a locking mode value.
*/
static int getLockingMode(const char *z){
  if( z ){
    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  }
  return PAGER_LOCKINGMODE_QUERY;
}

#ifndef SQLITE_OMIT_AUTOVACUUM
/*
** Interpret the given string as an auto-vacuum mode value.
**
** The following strings, "none", "full" and "incremental" are 
** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
*/
static int getAutoVacuum(const char *z){
  int i;
  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  i = atoi(z);
  return (u8)((i>=0&&i<=2)?i:0);
}
#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */

#ifndef SQLITE_OMIT_PAGER_PRAGMAS
/*
** Interpret the given string as a temp db location. Return 1 for file
** backed temporary databases, 2 for the Red-Black tree in memory database
** and 0 to use the compile-time default.
*/
static int getTempStore(const char *z){
  if( z[0]>='0' && z[0]<='2' ){
    return z[0] - '0';
  }else if( sqlite3StrICmp(z, "file")==0 ){
    return 1;
  }else if( sqlite3StrICmp(z, "memory")==0 ){
    return 2;
  }else{
    return 0;
  }
}
#endif /* SQLITE_PAGER_PRAGMAS */

#ifndef SQLITE_OMIT_PAGER_PRAGMAS
/*
** Invalidate temp storage, either when the temp storage is changed
** from default, or when 'file' and the temp_store_directory has changed
*/
static int invalidateTempStorage(Parse *pParse){
  sqlite3 *db = pParse->db;
  if( db->aDb[1].pBt!=0 ){
    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
        "from within a transaction");
      return SQLITE_ERROR;
    }
    sqlite3BtreeClose(db->aDb[1].pBt);
    db->aDb[1].pBt = 0;
    sqlite3ResetInternalSchema(db, 0);
  }
  return SQLITE_OK;
}
#endif /* SQLITE_PAGER_PRAGMAS */

#ifndef SQLITE_OMIT_PAGER_PRAGMAS
/*
** If the TEMP database is open, close it and mark the database schema
** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
** or DEFAULT_TEMP_STORE pragmas.
*/
static int changeTempStorage(Parse *pParse, const char *zStorageType){
  int ts = getTempStore(zStorageType);
  sqlite3 *db = pParse->db;
  if( db->temp_store==ts ) return SQLITE_OK;
  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
    return SQLITE_ERROR;
  }
  db->temp_store = (u8)ts;
  return SQLITE_OK;
}
#endif /* SQLITE_PAGER_PRAGMAS */

/*
** Generate code to return a single integer value.
*/
static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  Vdbe *v = sqlite3GetVdbe(pParse);
  int mem = ++pParse->nMem;
  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  if( pI64 ){
    memcpy(pI64, &value, sizeof(value));
  }
  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  sqlite3VdbeSetNumCols(v, 1);
  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
}

#ifndef SQLITE_OMIT_FLAG_PRAGMAS
/*
** Check to see if zRight and zLeft refer to a pragma that queries
** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
** Also, implement the pragma.
*/
static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  static const struct sPragmaType {
    const char *zName;  /* Name of the pragma */
    int mask;           /* Mask for the db->flags value */
  } aPragma[] = {
    { "full_column_names",        SQLITE_FullColNames  },
    { "short_column_names",       SQLITE_ShortColNames },
    { "count_changes",            SQLITE_CountRows     },
    { "empty_result_callbacks",   SQLITE_NullCallback  },
    { "legacy_file_format",       SQLITE_LegacyFileFmt },
    { "fullfsync",                SQLITE_FullFSync     },
    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
#ifdef SQLITE_DEBUG
    { "sql_trace",                SQLITE_SqlTrace      },
    { "vdbe_listing",             SQLITE_VdbeListing   },
    { "vdbe_trace",               SQLITE_VdbeTrace     },
#endif
#ifndef SQLITE_OMIT_CHECK
    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
#endif
    /* The following is VERY experimental */
    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
    { "omit_readlock",            SQLITE_NoReadlock    },

    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
    ** flag if there are any active statements. */
    { "read_uncommitted",         SQLITE_ReadUncommitted },
    { "recursive_triggers",       SQLITE_RecTriggers },

    /* This flag may only be set if both foreign-key and trigger support
    ** are present in the build.  */
#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
    { "foreign_keys",             SQLITE_ForeignKeys },
#endif
  };
  int i;
  const struct sPragmaType *p;
  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
      sqlite3 *db = pParse->db;
      Vdbe *v;
      v = sqlite3GetVdbe(pParse);
      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
      if( ALWAYS(v) ){
        if( zRight==0 ){
          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
        }else{
          int mask = p->mask;          /* Mask of bits to set or clear. */
          if( db->autoCommit==0 ){
            /* Foreign key support may not be enabled or disabled while not
            ** in auto-commit mode.  */
            mask &= ~(SQLITE_ForeignKeys);
          }

          if( getBoolean(zRight) ){
            db->flags |= mask;
          }else{
            db->flags &= ~mask;
          }

          /* Many of the flag-pragmas modify the code generated by the SQL 
          ** compiler (eg. count_changes). So add an opcode to expire all
          ** compiled SQL statements after modifying a pragma value.
          */
          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
        }
      }

      return 1;
    }
  }
  return 0;
}
#endif /* SQLITE_OMIT_FLAG_PRAGMAS */

/*
** Return a human-readable name for a constraint resolution action.
*/
#ifndef SQLITE_OMIT_FOREIGN_KEY
static const char *actionName(u8 action){
  const char *zName;
  switch( action ){
    case OE_SetNull:  zName = "SET NULL";        break;
    case OE_SetDflt:  zName = "SET DEFAULT";     break;
    case OE_Cascade:  zName = "CASCADE";         break;
    case OE_Restrict: zName = "RESTRICT";        break;
    default:          zName = "NO ACTION";  
                      assert( action==OE_None ); break;
  }
  return zName;
}
#endif

/*
** Process a pragma statement.  
**
** Pragmas are of this form:
**
**      PRAGMA [database.]id [= value]
**
** The identifier might also be a string.  The value is a string, and
** identifier, or a number.  If minusFlag is true, then the value is
** a number that was preceded by a minus sign.
**
** If the left side is "database.id" then pId1 is the database name
** and pId2 is the id.  If the left side is just "id" then pId1 is the
** id and pId2 is any empty string.
*/
void sqlite3Pragma(
  Parse *pParse, 
  Token *pId1,        /* First part of [database.]id field */
  Token *pId2,        /* Second part of [database.]id field, or NULL */
  Token *pValue,      /* Token for <value>, or NULL */
  int minusFlag       /* True if a '-' sign preceded <value> */
){
  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
  const char *zDb = 0;   /* The database name */
  Token *pId;            /* Pointer to <id> token */
  int iDb;               /* Database index for <database> */
  sqlite3 *db = pParse->db;
  Db *pDb;
  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
  if( v==0 ) return;
  pParse->nMem = 2;

  /* Interpret the [database.] part of the pragma statement. iDb is the
  ** index of the database this pragma is being applied to in db.aDb[]. */
  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  if( iDb<0 ) return;
  pDb = &db->aDb[iDb];

  /* If the temp database has been explicitly named as part of the 
  ** pragma, make sure it is open. 
  */
  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
    return;
  }

  zLeft = sqlite3NameFromToken(db, pId);
  if( !zLeft ) return;
  if( minusFlag ){
    zRight = sqlite3MPrintf(db, "-%T", pValue);
  }else{
    zRight = sqlite3NameFromToken(db, pValue);
  }

  assert( pId2 );
  zDb = pId2->n>0 ? pDb->zName : 0;
  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
    goto pragma_out;
  }
 
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
  /*
  **  PRAGMA [database.]default_cache_size
  **  PRAGMA [database.]default_cache_size=N
  **
  ** The first form reports the current persistent setting for the
  ** page cache size.  The value returned is the maximum number of
  ** pages in the page cache.  The second form sets both the current
  ** page cache size value and the persistent page cache size value
  ** stored in the database file.
  **
  ** The default cache size is stored in meta-value 2 of page 1 of the
  ** database file.  The cache size is actually the absolute value of
  ** this memory location.  The sign of meta-value 2 determines the
  ** synchronous setting.  A negative value means synchronous is off
  ** and a positive value means synchronous is on.
  */
  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
    static const VdbeOpList getCacheSize[] = {
      { OP_Transaction, 0, 0,        0},                         /* 0 */
      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
      { OP_IfPos,       1, 7,        0},
      { OP_Integer,     0, 2,        0},
      { OP_Subtract,    1, 2,        1},
      { OP_IfPos,       1, 7,        0},
      { OP_Integer,     0, 1,        0},                         /* 6 */
      { OP_ResultRow,   1, 1,        0},
    };
    int addr;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    sqlite3VdbeUsesBtree(v, iDb);
    if( !zRight ){
      sqlite3VdbeSetNumCols(v, 1);
      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
      pParse->nMem += 2;
      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
      sqlite3VdbeChangeP1(v, addr, iDb);
      sqlite3VdbeChangeP1(v, addr+1, iDb);
      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
    }else{
      int size = atoi(zRight);
      if( size<0 ) size = -size;
      sqlite3BeginWriteOperation(pParse, 0, iDb);
      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
      addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
      sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
      sqlite3VdbeJumpHere(v, addr);
      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
      pDb->pSchema->cache_size = size;
      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
    }
  }else

  /*
  **  PRAGMA [database.]page_size
  **  PRAGMA [database.]page_size=N
  **
  ** The first form reports the current setting for the
  ** database page size in bytes.  The second form sets the
  ** database page size value.  The value can only be set if
  ** the database has not yet been created.
  */
  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
    Btree *pBt = pDb->pBt;
    assert( pBt!=0 );
    if( !zRight ){
      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
      returnSingleInt(pParse, "page_size", size);
    }else{
      /* Malloc may fail when setting the page-size, as there is an internal
      ** buffer that the pager module resizes using sqlite3_realloc().
      */
      db->nextPagesize = atoi(zRight);
      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
        db->mallocFailed = 1;
      }
    }
  }else

  /*
  **  PRAGMA [database.]max_page_count
  **  PRAGMA [database.]max_page_count=N
  **
  ** The first form reports the current setting for the
  ** maximum number of pages in the database file.  The 
  ** second form attempts to change this setting.  Both
  ** forms return the current setting.
  */
  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
    Btree *pBt = pDb->pBt;
    int newMax = 0;
    assert( pBt!=0 );
    if( zRight ){
      newMax = atoi(zRight);
    }
    if( ALWAYS(pBt) ){
      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
    }
    returnSingleInt(pParse, "max_page_count", newMax);
  }else

  /*
  **  PRAGMA [database.]page_count
  **
  ** Return the number of pages in the specified database.
  */
  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
    int iReg;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    sqlite3CodeVerifySchema(pParse, iDb);
    iReg = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
  }else

  /*
  **  PRAGMA [database.]locking_mode
  **  PRAGMA [database.]locking_mode = (normal|exclusive)
  */
  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
    const char *zRet = "normal";
    int eMode = getLockingMode(zRight);

    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
      /* Simple "PRAGMA locking_mode;" statement. This is a query for
      ** the current default locking mode (which may be different to
      ** the locking-mode of the main database).
      */
      eMode = db->dfltLockMode;
    }else{
      Pager *pPager;
      if( pId2->n==0 ){
        /* This indicates that no database name was specified as part
        ** of the PRAGMA command. In this case the locking-mode must be
        ** set on all attached databases, as well as the main db file.
        **
        ** Also, the sqlite3.dfltLockMode variable is set so that
        ** any subsequently attached databases also use the specified
        ** locking mode.
        */
        int ii;
        assert(pDb==&db->aDb[0]);
        for(ii=2; ii<db->nDb; ii++){
          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
          sqlite3PagerLockingMode(pPager, eMode);
        }
        db->dfltLockMode = (u8)eMode;
      }
      pPager = sqlite3BtreePager(pDb->pBt);
      eMode = sqlite3PagerLockingMode(pPager, eMode);
    }

    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
      zRet = "exclusive";
    }
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  }else

  /*
  **  PRAGMA [database.]journal_mode
  **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
  */
  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
    int eMode;
    static char * const azModeName[] = {
      "delete", "persist", "off", "truncate", "memory"
    };

    if( zRight==0 ){
      eMode = PAGER_JOURNALMODE_QUERY;
    }else{
      int n = sqlite3Strlen30(zRight);
      eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
      while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
        eMode--;
      }
    }
    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
      /* Simple "PRAGMA journal_mode;" statement. This is a query for
      ** the current default journal mode (which may be different to
      ** the journal-mode of the main database).
      */
      eMode = db->dfltJournalMode;
    }else{
      Pager *pPager;
      if( pId2->n==0 ){
        /* This indicates that no database name was specified as part
        ** of the PRAGMA command. In this case the journal-mode must be
        ** set on all attached databases, as well as the main db file.
        **
        ** Also, the sqlite3.dfltJournalMode variable is set so that
        ** any subsequently attached databases also use the specified
        ** journal mode.
        */
        int ii;
        assert(pDb==&db->aDb[0]);
        for(ii=1; ii<db->nDb; ii++){
          if( db->aDb[ii].pBt ){
            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
            sqlite3PagerJournalMode(pPager, eMode);
          }
        }
        db->dfltJournalMode = (u8)eMode;
      }
      pPager = sqlite3BtreePager(pDb->pBt);
      eMode = sqlite3PagerJournalMode(pPager, eMode);
    }
    assert( eMode==PAGER_JOURNALMODE_DELETE
              || eMode==PAGER_JOURNALMODE_TRUNCATE
              || eMode==PAGER_JOURNALMODE_PERSIST
              || eMode==PAGER_JOURNALMODE_OFF
              || eMode==PAGER_JOURNALMODE_MEMORY );
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
           azModeName[eMode], P4_STATIC);
    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  }else

  /*
  **  PRAGMA [database.]journal_size_limit
  **  PRAGMA [database.]journal_size_limit=N
  **
  ** Get or set the size limit on rollback journal files.
  */
  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
    Pager *pPager = sqlite3BtreePager(pDb->pBt);
    i64 iLimit = -2;
    if( zRight ){
      sqlite3Atoi64(zRight, &iLimit);
      if( iLimit<-1 ) iLimit = -1;
    }
    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
    returnSingleInt(pParse, "journal_size_limit", iLimit);
  }else

#endif /* SQLITE_OMIT_PAGER_PRAGMAS */

  /*
  **  PRAGMA [database.]auto_vacuum
  **  PRAGMA [database.]auto_vacuum=N
  **
  ** Get or set the value of the database 'auto-vacuum' parameter.
  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
  */
#ifndef SQLITE_OMIT_AUTOVACUUM
  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
    Btree *pBt = pDb->pBt;
    assert( pBt!=0 );
    if( sqlite3ReadSchema(pParse) ){
      goto pragma_out;
    }
    if( !zRight ){
      int auto_vacuum;
      if( ALWAYS(pBt) ){
         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
      }else{
         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
      }
      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
    }else{
      int eAuto = getAutoVacuum(zRight);
      assert( eAuto>=0 && eAuto<=2 );
      db->nextAutovac = (u8)eAuto;
      if( ALWAYS(eAuto>=0) ){
        /* Call SetAutoVacuum() to set initialize the internal auto and
        ** incr-vacuum flags. This is required in case this connection
        ** creates the database file. It is important that it is created
        ** as an auto-vacuum capable db.
        */
        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
          /* When setting the auto_vacuum mode to either "full" or 
          ** "incremental", write the value of meta[6] in the database
          ** file. Before writing to meta[6], check that meta[3] indicates
          ** that this really is an auto-vacuum capable database.
          */
          static const VdbeOpList setMeta6[] = {
            { OP_Transaction,    0,         1,                 0},    /* 0 */
            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
            { OP_If,             1,         0,                 0},    /* 2 */
            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
            { OP_Integer,        0,         1,                 0},    /* 4 */
            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
          };
          int iAddr;
          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
          sqlite3VdbeChangeP1(v, iAddr, iDb);
          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
          sqlite3VdbeUsesBtree(v, iDb);
        }
      }
    }
  }else
#endif

  /*
  **  PRAGMA [database.]incremental_vacuum(N)
  **
  ** Do N steps of incremental vacuuming on a database.
  */
#ifndef SQLITE_OMIT_AUTOVACUUM
  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
    int iLimit, addr;
    if( sqlite3ReadSchema(pParse) ){
      goto pragma_out;
    }
    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
      iLimit = 0x7fffffff;
    }
    sqlite3BeginWriteOperation(pParse, 0, iDb);
    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
    sqlite3VdbeJumpHere(v, addr);
  }else
#endif

#ifndef SQLITE_OMIT_PAGER_PRAGMAS
  /*
  **  PRAGMA [database.]cache_size
  **  PRAGMA [database.]cache_size=N
  **
  ** The first form reports the current local setting for the
  ** page cache size.  The local setting can be different from
  ** the persistent cache size value that is stored in the database
  ** file itself.  The value returned is the maximum number of
  ** pages in the page cache.  The second form sets the local
  ** page cache size value.  It does not change the persistent
  ** cache size stored on the disk so the cache size will revert
  ** to its default value when the database is closed and reopened.
  ** N should be a positive integer.
  */
  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    if( !zRight ){
      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
    }else{
      int size = atoi(zRight);
      if( size<0 ) size = -size;
      pDb->pSchema->cache_size = size;
      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
    }
  }else

  /*
  **   PRAGMA temp_store
  **   PRAGMA temp_store = "default"|"memory"|"file"
  **
  ** Return or set the local value of the temp_store flag.  Changing
  ** the local value does not make changes to the disk file and the default
  ** value will be restored the next time the database is opened.
  **
  ** Note that it is possible for the library compile-time options to
  ** override this setting
  */
  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
    if( !zRight ){
      returnSingleInt(pParse, "temp_store", db->temp_store);
    }else{
      changeTempStorage(pParse, zRight);
    }
  }else

  /*
  **   PRAGMA temp_store_directory
  **   PRAGMA temp_store_directory = ""|"directory_name"
  **
  ** Return or set the local value of the temp_store_directory flag.  Changing
  ** the value sets a specific directory to be used for temporary files.
  ** Setting to a null string reverts to the default temporary directory search.
  ** If temporary directory is changed, then invalidateTempStorage.
  **
  */
  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
    if( !zRight ){
      if( sqlite3_temp_directory ){
        sqlite3VdbeSetNumCols(v, 1);
        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
            "temp_store_directory", SQLITE_STATIC);
        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
      }
    }else{
#ifndef SQLITE_OMIT_WSD
      if( zRight[0] ){
        int rc;
        int res;
        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
        if( rc!=SQLITE_OK || res==0 ){
          sqlite3ErrorMsg(pParse, "not a writable directory");
          goto pragma_out;
        }
      }
      if( SQLITE_TEMP_STORE==0
       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
      ){
        invalidateTempStorage(pParse);
      }
      sqlite3_free(sqlite3_temp_directory);
      if( zRight[0] ){
        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
      }else{
        sqlite3_temp_directory = 0;
      }
#endif /* SQLITE_OMIT_WSD */
    }
  }else

#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
#  if defined(__APPLE__)
#    define SQLITE_ENABLE_LOCKING_STYLE 1
#  else
#    define SQLITE_ENABLE_LOCKING_STYLE 0
#  endif
#endif
#if SQLITE_ENABLE_LOCKING_STYLE
  /*
   **   PRAGMA [database.]lock_proxy_file
   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   **
   ** Return or set the value of the lock_proxy_file flag.  Changing
   ** the value sets a specific file to be used for database access locks.
   **
   */
  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
    if( !zRight ){
      Pager *pPager = sqlite3BtreePager(pDb->pBt);
      char *proxy_file_path = NULL;
      sqlite3_file *pFile = sqlite3PagerFile(pPager);
      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
                           &proxy_file_path);
      
      if( proxy_file_path ){
        sqlite3VdbeSetNumCols(v, 1);
        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
                              "lock_proxy_file", SQLITE_STATIC);
        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
      }
    }else{
      Pager *pPager = sqlite3BtreePager(pDb->pBt);
      sqlite3_file *pFile = sqlite3PagerFile(pPager);
      int res;
      if( zRight[0] ){
        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
                                     zRight);
      } else {
        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
                                     NULL);
      }
      if( res!=SQLITE_OK ){
        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
        goto pragma_out;
      }
    }
  }else
#endif /* SQLITE_ENABLE_LOCKING_STYLE */      
    
  /*
  **   PRAGMA [database.]synchronous
  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  **
  ** Return or set the local value of the synchronous flag.  Changing
  ** the local value does not make changes to the disk file and the
  ** default value will be restored the next time the database is
  ** opened.
  */
  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    if( !zRight ){
      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
    }else{
      if( !db->autoCommit ){
        sqlite3ErrorMsg(pParse, 
            "Safety level may not be changed inside a transaction");
      }else{
        pDb->safety_level = getSafetyLevel(zRight)+1;
      }
    }
  }else
#endif /* SQLITE_OMIT_PAGER_PRAGMAS */

#ifndef SQLITE_OMIT_FLAG_PRAGMAS
  if( flagPragma(pParse, zLeft, zRight) ){
    /* The flagPragma() subroutine also generates any necessary code
    ** there is nothing more to do here */
  }else
#endif /* SQLITE_OMIT_FLAG_PRAGMAS */

#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  /*
  **   PRAGMA table_info(<table>)
  **
  ** Return a single row for each column of the named table. The columns of
  ** the returned data set are:
  **
  ** cid:        Column id (numbered from left to right, starting at 0)
  ** name:       Column name
  ** type:       Column declaration type.
  ** notnull:    True if 'NOT NULL' is part of column declaration
  ** dflt_value: The default value for the column, if any.
  */
  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
    Table *pTab;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    pTab = sqlite3FindTable(db, zRight, zDb);
    if( pTab ){
      int i;
      int nHidden = 0;
      Column *pCol;
      sqlite3VdbeSetNumCols(v, 6);
      pParse->nMem = 6;
      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
      sqlite3ViewGetColumnNames(pParse, pTab);
      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
        if( IsHiddenColumn(pCol) ){
          nHidden++;
          continue;
        }
        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
           pCol->zType ? pCol->zType : "", 0);
        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
        if( pCol->zDflt ){
          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
        }else{
          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
        }
        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
      }
    }
  }else

  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
    Index *pIdx;
    Table *pTab;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    pIdx = sqlite3FindIndex(db, zRight, zDb);
    if( pIdx ){
      int i;
      pTab = pIdx->pTable;
      sqlite3VdbeSetNumCols(v, 3);
      pParse->nMem = 3;
      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
      for(i=0; i<pIdx->nColumn; i++){
        int cnum = pIdx->aiColumn[i];
        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
        assert( pTab->nCol>cnum );
        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
      }
    }
  }else

  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
    Index *pIdx;
    Table *pTab;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    pTab = sqlite3FindTable(db, zRight, zDb);
    if( pTab ){
      v = sqlite3GetVdbe(pParse);
      pIdx = pTab->pIndex;
      if( pIdx ){
        int i = 0; 
        sqlite3VdbeSetNumCols(v, 3);
        pParse->nMem = 3;
        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
        while(pIdx){
          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
          ++i;
          pIdx = pIdx->pNext;
        }
      }
    }
  }else

  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
    int i;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    sqlite3VdbeSetNumCols(v, 3);
    pParse->nMem = 3;
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
    for(i=0; i<db->nDb; i++){
      if( db->aDb[i].pBt==0 ) continue;
      assert( db->aDb[i].zName!=0 );
      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
    }
  }else

  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
    int i = 0;
    HashElem *p;
    sqlite3VdbeSetNumCols(v, 2);
    pParse->nMem = 2;
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
    }
  }else
#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */

#ifndef SQLITE_OMIT_FOREIGN_KEY
  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
    FKey *pFK;
    Table *pTab;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    pTab = sqlite3FindTable(db, zRight, zDb);
    if( pTab ){
      v = sqlite3GetVdbe(pParse);
      pFK = pTab->pFKey;
      if( pFK ){
        int i = 0; 
        sqlite3VdbeSetNumCols(v, 8);
        pParse->nMem = 8;
        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
        while(pFK){
          int j;
          for(j=0; j<pFK->nCol; j++){
            char *zCol = pFK->aCol[j].zCol;
            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
          }
          ++i;
          pFK = pFK->pNextFrom;
        }
      }
    }
  }else
#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */

#ifndef NDEBUG
  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
    if( zRight ){
      if( getBoolean(zRight) ){
        sqlite3ParserTrace(stderr, "parser: ");
      }else{
        sqlite3ParserTrace(0, 0);
      }
    }
  }else
#endif

  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
  ** used will be case sensitive or not depending on the RHS.
  */
  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
    if( zRight ){
      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
    }
  }else

#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
#endif

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
  /* Pragma "quick_check" is an experimental reduced version of 
  ** integrity_check designed to detect most database corruption
  ** without most of the overhead of a full integrity-check.
  */
  if( sqlite3StrICmp(zLeft, "integrity_check")==0
   || sqlite3StrICmp(zLeft, "quick_check")==0 
  ){
    int i, j, addr, mxErr;

    /* Code that appears at the end of the integrity check.  If no error
    ** messages have been generated, output OK.  Otherwise output the
    ** error message
    */
    static const VdbeOpList endCode[] = {
      { OP_AddImm,      1, 0,        0},    /* 0 */
      { OP_IfNeg,       1, 0,        0},    /* 1 */
      { OP_String8,     0, 3,        0},    /* 2 */
      { OP_ResultRow,   3, 1,        0},
    };

    int isQuick = (zLeft[0]=='q');

    /* Initialize the VDBE program */
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    pParse->nMem = 6;
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);

    /* Set the maximum error count */
    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
    if( zRight ){
      mxErr = atoi(zRight);
      if( mxErr<=0 ){
        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
      }
    }
    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */

    /* Do an integrity check on each database file */
    for(i=0; i<db->nDb; i++){
      HashElem *x;
      Hash *pTbls;
      int cnt = 0;

      if( OMIT_TEMPDB && i==1 ) continue;

      sqlite3CodeVerifySchema(pParse, i);
      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
      sqlite3VdbeJumpHere(v, addr);

      /* Do an integrity check of the B-Tree
      **
      ** Begin by filling registers 2, 3, ... with the root pages numbers
      ** for all tables and indices in the database.
      */
      pTbls = &db->aDb[i].pSchema->tblHash;
      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
        Table *pTab = sqliteHashData(x);
        Index *pIdx;
        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
        cnt++;
        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
          cnt++;
        }
      }

      /* Make sure sufficient number of registers have been allocated */
      if( pParse->nMem < cnt+4 ){
        pParse->nMem = cnt+4;
      }

      /* Do the b-tree integrity checks */
      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
      sqlite3VdbeChangeP5(v, (u8)i);
      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
         P4_DYNAMIC);
      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
      sqlite3VdbeJumpHere(v, addr);

      /* Make sure all the indices are constructed correctly.
      */
      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
        Table *pTab = sqliteHashData(x);
        Index *pIdx;
        int loopTop;

        if( pTab->pIndex==0 ) continue;
        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
        sqlite3VdbeJumpHere(v, addr);
        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
          int jmp2;
          static const VdbeOpList idxErr[] = {
            { OP_AddImm,      1, -1,  0},
            { OP_String8,     0,  3,  0},    /* 1 */
            { OP_Rowid,       1,  4,  0},
            { OP_String8,     0,  5,  0},    /* 3 */
            { OP_String8,     0,  6,  0},    /* 4 */
            { OP_Concat,      4,  3,  3},
            { OP_Concat,      5,  3,  3},
            { OP_Concat,      6,  3,  3},
            { OP_ResultRow,   3,  1,  0},
            { OP_IfPos,       1,  0,  0},    /* 9 */
            { OP_Halt,        0,  0,  0},
          };
          sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
          jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
          sqlite3VdbeJumpHere(v, addr+9);
          sqlite3VdbeJumpHere(v, jmp2);
        }
        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
        sqlite3VdbeJumpHere(v, loopTop);
        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
          static const VdbeOpList cntIdx[] = {
             { OP_Integer,      0,  3,  0},
             { OP_Rewind,       0,  0,  0},  /* 1 */
             { OP_AddImm,       3,  1,  0},
             { OP_Next,         0,  0,  0},  /* 3 */
             { OP_Eq,           2,  0,  3},  /* 4 */
             { OP_AddImm,       1, -1,  0},
             { OP_String8,      0,  2,  0},  /* 6 */
             { OP_String8,      0,  3,  0},  /* 7 */
             { OP_Concat,       3,  2,  2},
             { OP_ResultRow,    2,  1,  0},
          };
          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
          sqlite3VdbeJumpHere(v, addr);
          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
          sqlite3VdbeChangeP1(v, addr+1, j+2);
          sqlite3VdbeChangeP2(v, addr+1, addr+4);
          sqlite3VdbeChangeP1(v, addr+3, j+2);
          sqlite3VdbeChangeP2(v, addr+3, addr+2);
          sqlite3VdbeJumpHere(v, addr+4);
          sqlite3VdbeChangeP4(v, addr+6, 
                     "wrong # of entries in index ", P4_STATIC);
          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
        }
      } 
    }
    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
    sqlite3VdbeChangeP2(v, addr, -mxErr);
    sqlite3VdbeJumpHere(v, addr+1);
    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  }else
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

#ifndef SQLITE_OMIT_UTF16
  /*
  **   PRAGMA encoding
  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  **
  ** In its first form, this pragma returns the encoding of the main
  ** database. If the database is not initialized, it is initialized now.
  **
  ** The second form of this pragma is a no-op if the main database file
  ** has not already been initialized. In this case it sets the default
  ** encoding that will be used for the main database file if a new file
  ** is created. If an existing main database file is opened, then the
  ** default text encoding for the existing database is used.
  ** 
  ** In all cases new databases created using the ATTACH command are
  ** created to use the same default text encoding as the main database. If
  ** the main database has not been initialized and/or created when ATTACH
  ** is executed, this is done before the ATTACH operation.
  **
  ** In the second form this pragma sets the text encoding to be used in
  ** new database files created using this database handle. It is only
  ** useful if invoked immediately after the main database i
  */
  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
    static const struct EncName {
      char *zName;
      u8 enc;
    } encnames[] = {
      { "UTF8",     SQLITE_UTF8        },
      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
      { "UTF16le",  SQLITE_UTF16LE     },
      { "UTF16be",  SQLITE_UTF16BE     },
      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
      { 0, 0 }
    };
    const struct EncName *pEnc;
    if( !zRight ){    /* "PRAGMA encoding" */
      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
      sqlite3VdbeSetNumCols(v, 1);
      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
    }else{                        /* "PRAGMA encoding = XXX" */
      /* Only change the value of sqlite.enc if the database handle is not
      ** initialized. If the main database exists, the new sqlite.enc value
      ** will be overwritten when the schema is next loaded. If it does not
      ** already exists, it will be created to use the new encoding value.
      */
      if( 
        !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
        DbHasProperty(db, 0, DB_Empty) 
      ){
        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
            break;
          }
        }
        if( !pEnc->zName ){
          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
        }
      }
    }
  }else
#endif /* SQLITE_OMIT_UTF16 */

#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  /*
  **   PRAGMA [database.]schema_version
  **   PRAGMA [database.]schema_version = <integer>
  **
  **   PRAGMA [database.]user_version
  **   PRAGMA [database.]user_version = <integer>
  **
  ** The pragma's schema_version and user_version are used to set or get
  ** the value of the schema-version and user-version, respectively. Both
  ** the schema-version and the user-version are 32-bit signed integers
  ** stored in the database header.
  **
  ** The schema-cookie is usually only manipulated internally by SQLite. It
  ** is incremented by SQLite whenever the database schema is modified (by
  ** creating or dropping a table or index). The schema version is used by
  ** SQLite each time a query is executed to ensure that the internal cache
  ** of the schema used when compiling the SQL query matches the schema of
  ** the database against which the compiled query is actually executed.
  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  ** the schema-version is potentially dangerous and may lead to program
  ** crashes or database corruption. Use with caution!
  **
  ** The user-version is not used internally by SQLite. It may be used by
  ** applications for any purpose.
  */
  if( sqlite3StrICmp(zLeft, "schema_version")==0 
   || sqlite3StrICmp(zLeft, "user_version")==0 
   || sqlite3StrICmp(zLeft, "freelist_count")==0 
  ){
    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
    sqlite3VdbeUsesBtree(v, iDb);
    switch( zLeft[0] ){
      case 'f': case 'F':
        iCookie = BTREE_FREE_PAGE_COUNT;
        break;
      case 's': case 'S':
        iCookie = BTREE_SCHEMA_VERSION;
        break;
      default:
        iCookie = BTREE_USER_VERSION;
        break;
    }

    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
      /* Write the specified cookie value */
      static const VdbeOpList setCookie[] = {
        { OP_Transaction,    0,  1,  0},    /* 0 */
        { OP_Integer,        0,  1,  0},    /* 1 */
        { OP_SetCookie,      0,  0,  1},    /* 2 */
      };
      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
      sqlite3VdbeChangeP1(v, addr, iDb);
      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
      sqlite3VdbeChangeP1(v, addr+2, iDb);
      sqlite3VdbeChangeP2(v, addr+2, iCookie);
    }else{
      /* Read the specified cookie value */
      static const VdbeOpList readCookie[] = {
        { OP_Transaction,     0,  0,  0},    /* 0 */
        { OP_ReadCookie,      0,  1,  0},    /* 1 */
        { OP_ResultRow,       1,  1,  0}
      };
      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
      sqlite3VdbeChangeP1(v, addr, iDb);
      sqlite3VdbeChangeP1(v, addr+1, iDb);
      sqlite3VdbeChangeP3(v, addr+1, iCookie);
      sqlite3VdbeSetNumCols(v, 1);
      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
    }
  }else
#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */

#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  /*
  ** Report the current state of file logs for all databases
  */
  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
    static const char *const azLockName[] = {
      "unlocked", "shared", "reserved", "pending", "exclusive"
    };
    int i;
    sqlite3VdbeSetNumCols(v, 2);
    pParse->nMem = 2;
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
    for(i=0; i<db->nDb; i++){
      Btree *pBt;
      Pager *pPager;
      const char *zState = "unknown";
      int j;
      if( db->aDb[i].zName==0 ) continue;
      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
      pBt = db->aDb[i].pBt;
      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
        zState = "closed";
      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
         zState = azLockName[j];
      }
      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
    }

  }else
#endif

#if SQLITE_HAS_CODEC
  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
  }else
  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
  }else
  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
    int i, h1, h2;
    char zKey[40];
    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
      h1 += 9*(1&(h1>>6));
      h2 += 9*(1&(h2>>6));
      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
    }
    if( (zLeft[3] & 0xf)==0xb ){
      sqlite3_key(db, zKey, i/2);
    }else{
      sqlite3_rekey(db, zKey, i/2);
    }
  }else
#endif
#if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
#if SQLITE_HAS_CODEC
    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
      extern void sqlite3_activate_see(const char*);
      sqlite3_activate_see(&zRight[4]);
    }
#endif
#ifdef SQLITE_ENABLE_CEROD
    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
      extern void sqlite3_activate_cerod(const char*);
      sqlite3_activate_cerod(&zRight[6]);
    }
#endif
  }else
#endif

 
  {/* Empty ELSE clause */}

  /* Code an OP_Expire at the end of each PRAGMA program to cause
  ** the VDBE implementing the pragma to expire. Most (all?) pragmas
  ** are only valid for a single execution.
  */
  sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);

  /*
  ** Reset the safety level, in case the fullfsync flag or synchronous
  ** setting changed.
  */
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
  if( db->autoCommit ){
    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
               (db->flags&SQLITE_FullFSync)!=0);
  }
#endif
pragma_out:
  sqlite3DbFree(db, zLeft);
  sqlite3DbFree(db, zRight);
}

#endif /* SQLITE_OMIT_PRAGMA */

Added src/prepare.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
/*
** 2005 May 25
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_prepare()
** interface, and routines that contribute to loading the database schema
** from disk.
**
** $Id: prepare.c,v 1.131 2009/08/06 17:43:31 drh Exp $
*/
#include "sqliteInt.h"

/*
** Fill the InitData structure with an error message that indicates
** that the database is corrupt.
*/
static void corruptSchema(
  InitData *pData,     /* Initialization context */
  const char *zObj,    /* Object being parsed at the point of error */
  const char *zExtra   /* Error information */
){
  sqlite3 *db = pData->db;
  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
    if( zObj==0 ) zObj = "?";
    sqlite3SetString(pData->pzErrMsg, db,
      "malformed database schema (%s)", zObj);
    if( zExtra ){
      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
                                 "%s - %s", *pData->pzErrMsg, zExtra);
    }
  }
  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
}

/*
** This is the callback routine for the code that initializes the
** database.  See sqlite3Init() below for additional information.
** This routine is also called from the OP_ParseSchema opcode of the VDBE.
**
** Each callback contains the following information:
**
**     argv[0] = name of thing being created
**     argv[1] = root page number for table or index. 0 for trigger or view.
**     argv[2] = SQL text for the CREATE statement.
**
*/
int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  InitData *pData = (InitData*)pInit;
  sqlite3 *db = pData->db;
  int iDb = pData->iDb;

  assert( argc==3 );
  UNUSED_PARAMETER2(NotUsed, argc);
  assert( sqlite3_mutex_held(db->mutex) );
  DbClearProperty(db, iDb, DB_Empty);
  if( db->mallocFailed ){
    corruptSchema(pData, argv[0], 0);
    return 1;
  }

  assert( iDb>=0 && iDb<db->nDb );
  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  if( argv[1]==0 ){
    corruptSchema(pData, argv[0], 0);
  }else if( argv[2] && argv[2][0] ){
    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
    ** But because db->init.busy is set to 1, no VDBE code is generated
    ** or executed.  All the parser does is build the internal data
    ** structures that describe the table, index, or view.
    */
    char *zErr;
    int rc;
    assert( db->init.busy );
    db->init.iDb = iDb;
    db->init.newTnum = atoi(argv[1]);
    db->init.orphanTrigger = 0;
    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
    db->init.iDb = 0;
    assert( rc!=SQLITE_OK || zErr==0 );
    if( SQLITE_OK!=rc ){
      if( db->init.orphanTrigger ){
        assert( iDb==1 );
      }else{
        pData->rc = rc;
        if( rc==SQLITE_NOMEM ){
          db->mallocFailed = 1;
        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
          corruptSchema(pData, argv[0], zErr);
        }
      }
      sqlite3DbFree(db, zErr);
    }
  }else if( argv[0]==0 ){
    corruptSchema(pData, 0, 0);
  }else{
    /* If the SQL column is blank it means this is an index that
    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
    ** constraint for a CREATE TABLE.  The index should have already
    ** been created when we processed the CREATE TABLE.  All we have
    ** to do here is record the root page number for that index.
    */
    Index *pIndex;
    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
    if( pIndex==0 ){
      /* This can occur if there exists an index on a TEMP table which
      ** has the same name as another index on a permanent index.  Since
      ** the permanent table is hidden by the TEMP table, we can also
      ** safely ignore the index on the permanent table.
      */
      /* Do Nothing */;
    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
      corruptSchema(pData, argv[0], "invalid rootpage");
    }
  }
  return 0;
}

/*
** Attempt to read the database schema and initialize internal
** data structures for a single database file.  The index of the
** database file is given by iDb.  iDb==0 is used for the main
** database.  iDb==1 should never be used.  iDb>=2 is used for
** auxiliary databases.  Return one of the SQLITE_ error codes to
** indicate success or failure.
*/
static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  int rc;
  int i;
  int size;
  Table *pTab;
  Db *pDb;
  char const *azArg[4];
  int meta[5];
  InitData initData;
  char const *zMasterSchema;
  char const *zMasterName = SCHEMA_TABLE(iDb);
  int openedTransaction = 0;

  /*
  ** The master database table has a structure like this
  */
  static const char master_schema[] = 
     "CREATE TABLE sqlite_master(\n"
     "  type text,\n"
     "  name text,\n"
     "  tbl_name text,\n"
     "  rootpage integer,\n"
     "  sql text\n"
     ")"
  ;
#ifndef SQLITE_OMIT_TEMPDB
  static const char temp_master_schema[] = 
     "CREATE TEMP TABLE sqlite_temp_master(\n"
     "  type text,\n"
     "  name text,\n"
     "  tbl_name text,\n"
     "  rootpage integer,\n"
     "  sql text\n"
     ")"
  ;
#else
  #define temp_master_schema 0
#endif

  assert( iDb>=0 && iDb<db->nDb );
  assert( db->aDb[iDb].pSchema );
  assert( sqlite3_mutex_held(db->mutex) );
  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );

  /* zMasterSchema and zInitScript are set to point at the master schema
  ** and initialisation script appropriate for the database being
  ** initialised. zMasterName is the name of the master table.
  */
  if( !OMIT_TEMPDB && iDb==1 ){
    zMasterSchema = temp_master_schema;
  }else{
    zMasterSchema = master_schema;
  }
  zMasterName = SCHEMA_TABLE(iDb);

  /* Construct the schema tables.  */
  azArg[0] = zMasterName;
  azArg[1] = "1";
  azArg[2] = zMasterSchema;
  azArg[3] = 0;
  initData.db = db;
  initData.iDb = iDb;
  initData.rc = SQLITE_OK;
  initData.pzErrMsg = pzErrMsg;
  (void)sqlite3SafetyOff(db);
  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  (void)sqlite3SafetyOn(db);
  if( initData.rc ){
    rc = initData.rc;
    goto error_out;
  }
  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  if( ALWAYS(pTab) ){
    pTab->tabFlags |= TF_Readonly;
  }

  /* Create a cursor to hold the database open
  */
  pDb = &db->aDb[iDb];
  if( pDb->pBt==0 ){
    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
      DbSetProperty(db, 1, DB_SchemaLoaded);
    }
    return SQLITE_OK;
  }

  /* If there is not already a read-only (or read-write) transaction opened
  ** on the b-tree database, open one now. If a transaction is opened, it 
  ** will be closed before this function returns.  */
  sqlite3BtreeEnter(pDb->pBt);
  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
    if( rc!=SQLITE_OK ){
      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
      goto initone_error_out;
    }
    openedTransaction = 1;
  }

  /* Get the database meta information.
  **
  ** Meta values are as follows:
  **    meta[0]   Schema cookie.  Changes with each schema change.
  **    meta[1]   File format of schema layer.
  **    meta[2]   Size of the page cache.
  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  **    meta[5]   User version
  **    meta[6]   Incremental vacuum mode
  **    meta[7]   unused
  **    meta[8]   unused
  **    meta[9]   unused
  **
  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  ** the possible values of meta[4].
  */
  for(i=0; i<ArraySize(meta); i++){
    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  }
  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];

  /* If opening a non-empty database, check the text encoding. For the
  ** main database, set sqlite3.enc to the encoding of the main database.
  ** For an attached db, it is an error if the encoding is not the same
  ** as sqlite3.enc.
  */
  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
    if( iDb==0 ){
      u8 encoding;
      /* If opening the main database, set ENC(db). */
      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
      if( encoding==0 ) encoding = SQLITE_UTF8;
      ENC(db) = encoding;
      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
    }else{
      /* If opening an attached database, the encoding much match ENC(db) */
      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
            " text encoding as main database");
        rc = SQLITE_ERROR;
        goto initone_error_out;
      }
    }
  }else{
    DbSetProperty(db, iDb, DB_Empty);
  }
  pDb->pSchema->enc = ENC(db);

  if( pDb->pSchema->cache_size==0 ){
    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
    if( size<0 ) size = -size;
    pDb->pSchema->cache_size = size;
    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  }

  /*
  ** file_format==1    Version 3.0.0.
  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
  */
  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  if( pDb->pSchema->file_format==0 ){
    pDb->pSchema->file_format = 1;
  }
  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
    sqlite3SetString(pzErrMsg, db, "unsupported file format");
    rc = SQLITE_ERROR;
    goto initone_error_out;
  }

  /* Ticket #2804:  When we open a database in the newer file format,
  ** clear the legacy_file_format pragma flag so that a VACUUM will
  ** not downgrade the database and thus invalidate any descending
  ** indices that the user might have created.
  */
  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
    db->flags &= ~SQLITE_LegacyFileFmt;
  }

  /* Read the schema information out of the schema tables
  */
  assert( db->init.busy );
  {
    char *zSql;
    zSql = sqlite3MPrintf(db, 
        "SELECT name, rootpage, sql FROM '%q'.%s",
        db->aDb[iDb].zName, zMasterName);
    (void)sqlite3SafetyOff(db);
#ifndef SQLITE_OMIT_AUTHORIZATION
    {
      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
      xAuth = db->xAuth;
      db->xAuth = 0;
#endif
      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
#ifndef SQLITE_OMIT_AUTHORIZATION
      db->xAuth = xAuth;
    }
#endif
    if( rc==SQLITE_OK ) rc = initData.rc;
    (void)sqlite3SafetyOn(db);
    sqlite3DbFree(db, zSql);
#ifndef SQLITE_OMIT_ANALYZE
    if( rc==SQLITE_OK ){
      sqlite3AnalysisLoad(db, iDb);
    }
#endif
  }
  if( db->mallocFailed ){
    rc = SQLITE_NOMEM;
    sqlite3ResetInternalSchema(db, 0);
  }
  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
    ** the schema loaded, even if errors occurred. In this situation the 
    ** current sqlite3_prepare() operation will fail, but the following one
    ** will attempt to compile the supplied statement against whatever subset
    ** of the schema was loaded before the error occurred. The primary
    ** purpose of this is to allow access to the sqlite_master table
    ** even when its contents have been corrupted.
    */
    DbSetProperty(db, iDb, DB_SchemaLoaded);
    rc = SQLITE_OK;
  }

  /* Jump here for an error that occurs after successfully allocating
  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  ** before that point, jump to error_out.
  */
initone_error_out:
  if( openedTransaction ){
    sqlite3BtreeCommit(pDb->pBt);
  }
  sqlite3BtreeLeave(pDb->pBt);

error_out:
  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
    db->mallocFailed = 1;
  }
  return rc;
}

/*
** Initialize all database files - the main database file, the file
** used to store temporary tables, and any additional database files
** created using ATTACH statements.  Return a success code.  If an
** error occurs, write an error message into *pzErrMsg.
**
** After a database is initialized, the DB_SchemaLoaded bit is set
** bit is set in the flags field of the Db structure. If the database
** file was of zero-length, then the DB_Empty flag is also set.
*/
int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  int i, rc;
  int commit_internal = !(db->flags&SQLITE_InternChanges);
  
  assert( sqlite3_mutex_held(db->mutex) );
  rc = SQLITE_OK;
  db->init.busy = 1;
  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
    rc = sqlite3InitOne(db, i, pzErrMsg);
    if( rc ){
      sqlite3ResetInternalSchema(db, i);
    }
  }

  /* Once all the other databases have been initialised, load the schema
  ** for the TEMP database. This is loaded last, as the TEMP database
  ** schema may contain references to objects in other databases.
  */
#ifndef SQLITE_OMIT_TEMPDB
  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
    rc = sqlite3InitOne(db, 1, pzErrMsg);
    if( rc ){
      sqlite3ResetInternalSchema(db, 1);
    }
  }
#endif

  db->init.busy = 0;
  if( rc==SQLITE_OK && commit_internal ){
    sqlite3CommitInternalChanges(db);
  }

  return rc; 
}

/*
** This routine is a no-op if the database schema is already initialised.
** Otherwise, the schema is loaded. An error code is returned.
*/
int sqlite3ReadSchema(Parse *pParse){
  int rc = SQLITE_OK;
  sqlite3 *db = pParse->db;
  assert( sqlite3_mutex_held(db->mutex) );
  if( !db->init.busy ){
    rc = sqlite3Init(db, &pParse->zErrMsg);
  }
  if( rc!=SQLITE_OK ){
    pParse->rc = rc;
    pParse->nErr++;
  }
  return rc;
}


/*
** Check schema cookies in all databases.  If any cookie is out
** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
** make no changes to pParse->rc.
*/
static void schemaIsValid(Parse *pParse){
  sqlite3 *db = pParse->db;
  int iDb;
  int rc;
  int cookie;

  assert( pParse->checkSchema );
  assert( sqlite3_mutex_held(db->mutex) );
  for(iDb=0; iDb<db->nDb; iDb++){
    int openedTransaction = 0;         /* True if a transaction is opened */
    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
    if( pBt==0 ) continue;

    /* If there is not already a read-only (or read-write) transaction opened
    ** on the b-tree database, open one now. If a transaction is opened, it 
    ** will be closed immediately after reading the meta-value. */
    if( !sqlite3BtreeIsInReadTrans(pBt) ){
      rc = sqlite3BtreeBeginTrans(pBt, 0);
      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
        db->mallocFailed = 1;
      }
      if( rc!=SQLITE_OK ) return;
      openedTransaction = 1;
    }

    /* Read the schema cookie from the database. If it does not match the 
    ** value stored as part of the in the in-memory schema representation,
    ** set Parse.rc to SQLITE_SCHEMA. */
    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
      pParse->rc = SQLITE_SCHEMA;
    }

    /* Close the transaction, if one was opened. */
    if( openedTransaction ){
      sqlite3BtreeCommit(pBt);
    }
  }
}

/*
** Convert a schema pointer into the iDb index that indicates
** which database file in db->aDb[] the schema refers to.
**
** If the same database is attached more than once, the first
** attached database is returned.
*/
int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  int i = -1000000;

  /* If pSchema is NULL, then return -1000000. This happens when code in 
  ** expr.c is trying to resolve a reference to a transient table (i.e. one
  ** created by a sub-select). In this case the return value of this 
  ** function should never be used.
  **
  ** We return -1000000 instead of the more usual -1 simply because using
  ** -1000000 as the incorrect index into db->aDb[] is much 
  ** more likely to cause a segfault than -1 (of course there are assert()
  ** statements too, but it never hurts to play the odds).
  */
  assert( sqlite3_mutex_held(db->mutex) );
  if( pSchema ){
    for(i=0; ALWAYS(i<db->nDb); i++){
      if( db->aDb[i].pSchema==pSchema ){
        break;
      }
    }
    assert( i>=0 && i<db->nDb );
  }
  return i;
}

/*
** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
*/
static int sqlite3Prepare(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
  Vdbe *pReprepare,         /* VM being reprepared */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pzTail       /* OUT: End of parsed string */
){
  Parse *pParse;            /* Parsing context */
  char *zErrMsg = 0;        /* Error message */
  int rc = SQLITE_OK;       /* Result code */
  int i;                    /* Loop counter */

  /* Allocate the parsing context */
  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  if( pParse==0 ){
    rc = SQLITE_NOMEM;
    goto end_prepare;
  }
  pParse->pReprepare = pReprepare;

  if( sqlite3SafetyOn(db) ){
    rc = SQLITE_MISUSE;
    goto end_prepare;
  }
  assert( ppStmt && *ppStmt==0 );
  assert( !db->mallocFailed );
  assert( sqlite3_mutex_held(db->mutex) );

  /* Check to verify that it is possible to get a read lock on all
  ** database schemas.  The inability to get a read lock indicates that
  ** some other database connection is holding a write-lock, which in
  ** turn means that the other connection has made uncommitted changes
  ** to the schema.
  **
  ** Were we to proceed and prepare the statement against the uncommitted
  ** schema changes and if those schema changes are subsequently rolled
  ** back and different changes are made in their place, then when this
  ** prepared statement goes to run the schema cookie would fail to detect
  ** the schema change.  Disaster would follow.
  **
  ** This thread is currently holding mutexes on all Btrees (because
  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  ** is not possible for another thread to start a new schema change
  ** while this routine is running.  Hence, we do not need to hold 
  ** locks on the schema, we just need to make sure nobody else is 
  ** holding them.
  **
  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  ** but it does *not* override schema lock detection, so this all still
  ** works even if READ_UNCOMMITTED is set.
  */
  for(i=0; i<db->nDb; i++) {
    Btree *pBt = db->aDb[i].pBt;
    if( pBt ){
      assert( sqlite3BtreeHoldsMutex(pBt) );
      rc = sqlite3BtreeSchemaLocked(pBt);
      if( rc ){
        const char *zDb = db->aDb[i].zName;
        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
        (void)sqlite3SafetyOff(db);
        testcase( db->flags & SQLITE_ReadUncommitted );
        goto end_prepare;
      }
    }
  }

  sqlite3VtabUnlockList(db);

  pParse->db = db;
  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
    char *zSqlCopy;
    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
    testcase( nBytes==mxLen );
    testcase( nBytes==mxLen+1 );
    if( nBytes>mxLen ){
      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
      (void)sqlite3SafetyOff(db);
      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
      goto end_prepare;
    }
    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
    if( zSqlCopy ){
      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
      sqlite3DbFree(db, zSqlCopy);
      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
    }else{
      pParse->zTail = &zSql[nBytes];
    }
  }else{
    sqlite3RunParser(pParse, zSql, &zErrMsg);
  }

  if( db->mallocFailed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  if( pParse->checkSchema ){
    schemaIsValid(pParse);
  }
  if( pParse->rc==SQLITE_SCHEMA ){
    sqlite3ResetInternalSchema(db, 0);
  }
  if( db->mallocFailed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pzTail ){
    *pzTail = pParse->zTail;
  }
  rc = pParse->rc;

#ifndef SQLITE_OMIT_EXPLAIN
  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
    static const char * const azColName[] = {
       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
       "order", "from", "detail"
    };
    int iFirst, mx;
    if( pParse->explain==2 ){
      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
      iFirst = 8;
      mx = 11;
    }else{
      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
      iFirst = 0;
      mx = 8;
    }
    for(i=iFirst; i<mx; i++){
      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
                            azColName[i], SQLITE_STATIC);
    }
  }
#endif

  if( sqlite3SafetyOff(db) ){
    rc = SQLITE_MISUSE;
  }

  assert( db->init.busy==0 || saveSqlFlag==0 );
  if( db->init.busy==0 ){
    Vdbe *pVdbe = pParse->pVdbe;
    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  }
  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
    sqlite3VdbeFinalize(pParse->pVdbe);
    assert(!(*ppStmt));
  }else{
    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  }

  if( zErrMsg ){
    sqlite3Error(db, rc, "%s", zErrMsg);
    sqlite3DbFree(db, zErrMsg);
  }else{
    sqlite3Error(db, rc, 0);
  }

  /* Delete any TriggerPrg structures allocated while parsing this statement. */
  while( pParse->pTriggerPrg ){
    TriggerPrg *pT = pParse->pTriggerPrg;
    pParse->pTriggerPrg = pT->pNext;
    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
    sqlite3DbFree(db, pT);
  }

end_prepare:

  sqlite3StackFree(db, pParse);
  rc = sqlite3ApiExit(db, rc);
  assert( (rc&db->errMask)==rc );
  return rc;
}
static int sqlite3LockAndPrepare(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
  Vdbe *pOld,               /* VM being reprepared */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pzTail       /* OUT: End of parsed string */
){
  int rc;
  assert( ppStmt!=0 );
  *ppStmt = 0;
  if( !sqlite3SafetyCheckOk(db) ){
    return SQLITE_MISUSE;
  }
  sqlite3_mutex_enter(db->mutex);
  sqlite3BtreeEnterAll(db);
  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  if( rc==SQLITE_SCHEMA ){
    sqlite3_finalize(*ppStmt);
    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  }
  sqlite3BtreeLeaveAll(db);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** Rerun the compilation of a statement after a schema change.
**
** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
** if the statement cannot be recompiled because another connection has
** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
** occurs, return SQLITE_SCHEMA.
*/
int sqlite3Reprepare(Vdbe *p){
  int rc;
  sqlite3_stmt *pNew;
  const char *zSql;
  sqlite3 *db;

  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  zSql = sqlite3_sql((sqlite3_stmt *)p);
  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
  db = sqlite3VdbeDb(p);
  assert( sqlite3_mutex_held(db->mutex) );
  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  if( rc ){
    if( rc==SQLITE_NOMEM ){
      db->mallocFailed = 1;
    }
    assert( pNew==0 );
    return (rc==SQLITE_LOCKED) ? SQLITE_LOCKED : SQLITE_SCHEMA;
  }else{
    assert( pNew!=0 );
  }
  sqlite3VdbeSwap((Vdbe*)pNew, p);
  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  sqlite3VdbeResetStepResult((Vdbe*)pNew);
  sqlite3VdbeFinalize((Vdbe*)pNew);
  return SQLITE_OK;
}


/*
** Two versions of the official API.  Legacy and new use.  In the legacy
** version, the original SQL text is not saved in the prepared statement
** and so if a schema change occurs, SQLITE_SCHEMA is returned by
** sqlite3_step().  In the new version, the original SQL text is retained
** and the statement is automatically recompiled if an schema change
** occurs.
*/
int sqlite3_prepare(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pzTail       /* OUT: End of parsed string */
){
  int rc;
  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
  return rc;
}
int sqlite3_prepare_v2(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pzTail       /* OUT: End of parsed string */
){
  int rc;
  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
  return rc;
}


#ifndef SQLITE_OMIT_UTF16
/*
** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
*/
static int sqlite3Prepare16(
  sqlite3 *db,              /* Database handle. */ 
  const void *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const void **pzTail       /* OUT: End of parsed string */
){
  /* This function currently works by first transforming the UTF-16
  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  ** tricky bit is figuring out the pointer to return in *pzTail.
  */
  char *zSql8;
  const char *zTail8 = 0;
  int rc = SQLITE_OK;

  assert( ppStmt );
  *ppStmt = 0;
  if( !sqlite3SafetyCheckOk(db) ){
    return SQLITE_MISUSE;
  }
  sqlite3_mutex_enter(db->mutex);
  zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
  if( zSql8 ){
    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  }

  if( zTail8 && pzTail ){
    /* If sqlite3_prepare returns a tail pointer, we calculate the
    ** equivalent pointer into the UTF-16 string by counting the unicode
    ** characters between zSql8 and zTail8, and then returning a pointer
    ** the same number of characters into the UTF-16 string.
    */
    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  }
  sqlite3DbFree(db, zSql8); 
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** Two versions of the official API.  Legacy and new use.  In the legacy
** version, the original SQL text is not saved in the prepared statement
** and so if a schema change occurs, SQLITE_SCHEMA is returned by
** sqlite3_step().  In the new version, the original SQL text is retained
** and the statement is automatically recompiled if an schema change
** occurs.
*/
int sqlite3_prepare16(
  sqlite3 *db,              /* Database handle. */ 
  const void *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const void **pzTail       /* OUT: End of parsed string */
){
  int rc;
  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
  return rc;
}
int sqlite3_prepare16_v2(
  sqlite3 *db,              /* Database handle. */ 
  const void *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const void **pzTail       /* OUT: End of parsed string */
){
  int rc;
  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
  return rc;
}

#endif /* SQLITE_OMIT_UTF16 */

Added src/printf.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
/*
** The "printf" code that follows dates from the 1980's.  It is in
** the public domain.  The original comments are included here for
** completeness.  They are very out-of-date but might be useful as
** an historical reference.  Most of the "enhancements" have been backed
** out so that the functionality is now the same as standard printf().
**
** $Id: printf.c,v 1.104 2009/06/03 01:24:54 drh Exp $
**
**************************************************************************
**
** The following modules is an enhanced replacement for the "printf" subroutines
** found in the standard C library.  The following enhancements are
** supported:
**
**      +  Additional functions.  The standard set of "printf" functions
**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
**         vsprintf.  This module adds the following:
**
**           *  snprintf -- Works like sprintf, but has an extra argument
**                          which is the size of the buffer written to.
**
**           *  mprintf --  Similar to sprintf.  Writes output to memory
**                          obtained from malloc.
**
**           *  xprintf --  Calls a function to dispose of output.
**
**           *  nprintf --  No output, but returns the number of characters
**                          that would have been output by printf.
**
**           *  A v- version (ex: vsnprintf) of every function is also
**              supplied.
**
**      +  A few extensions to the formatting notation are supported:
**
**           *  The "=" flag (similar to "-") causes the output to be
**              be centered in the appropriately sized field.
**
**           *  The %b field outputs an integer in binary notation.
**
**           *  The %c field now accepts a precision.  The character output
**              is repeated by the number of times the precision specifies.
**
**           *  The %' field works like %c, but takes as its character the
**              next character of the format string, instead of the next
**              argument.  For example,  printf("%.78'-")  prints 78 minus
**              signs, the same as  printf("%.78c",'-').
**
**      +  When compiled using GCC on a SPARC, this version of printf is
**         faster than the library printf for SUN OS 4.1.
**
**      +  All functions are fully reentrant.
**
*/
#include "sqliteInt.h"

/*
** Conversion types fall into various categories as defined by the
** following enumeration.
*/
#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
#define etFLOAT       2 /* Floating point.  %f */
#define etEXP         3 /* Exponentional notation. %e and %E */
#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
#define etSIZE        5 /* Return number of characters processed so far. %n */
#define etSTRING      6 /* Strings. %s */
#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
#define etPERCENT     8 /* Percent symbol. %% */
#define etCHARX       9 /* Characters. %c */
/* The rest are extensions, not normally found in printf() */
#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
                          NULL pointers replaced by SQL NULL.  %Q */
#define etTOKEN      12 /* a pointer to a Token structure */
#define etSRCLIST    13 /* a pointer to a SrcList */
#define etPOINTER    14 /* The %p conversion */
#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */

#define etINVALID     0 /* Any unrecognized conversion type */


/*
** An "etByte" is an 8-bit unsigned value.
*/
typedef unsigned char etByte;

/*
** Each builtin conversion character (ex: the 'd' in "%d") is described
** by an instance of the following structure
*/
typedef struct et_info {   /* Information about each format field */
  char fmttype;            /* The format field code letter */
  etByte base;             /* The base for radix conversion */
  etByte flags;            /* One or more of FLAG_ constants below */
  etByte type;             /* Conversion paradigm */
  etByte charset;          /* Offset into aDigits[] of the digits string */
  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
} et_info;

/*
** Allowed values for et_info.flags
*/
#define FLAG_SIGNED  1     /* True if the value to convert is signed */
#define FLAG_INTERN  2     /* True if for internal use only */
#define FLAG_STRING  4     /* Allow infinity precision */


/*
** The following table is searched linearly, so it is good to put the
** most frequently used conversion types first.
*/
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
static const char aPrefix[] = "-x0\000X0";
static const et_info fmtinfo[] = {
  {  'd', 10, 1, etRADIX,      0,  0 },
  {  's',  0, 4, etSTRING,     0,  0 },
  {  'g',  0, 1, etGENERIC,    30, 0 },
  {  'z',  0, 4, etDYNSTRING,  0,  0 },
  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
  {  'c',  0, 0, etCHARX,      0,  0 },
  {  'o',  8, 0, etRADIX,      0,  2 },
  {  'u', 10, 0, etRADIX,      0,  0 },
  {  'x', 16, 0, etRADIX,      16, 1 },
  {  'X', 16, 0, etRADIX,      0,  4 },
#ifndef SQLITE_OMIT_FLOATING_POINT
  {  'f',  0, 1, etFLOAT,      0,  0 },
  {  'e',  0, 1, etEXP,        30, 0 },
  {  'E',  0, 1, etEXP,        14, 0 },
  {  'G',  0, 1, etGENERIC,    14, 0 },
#endif
  {  'i', 10, 1, etRADIX,      0,  0 },
  {  'n',  0, 0, etSIZE,       0,  0 },
  {  '%',  0, 0, etPERCENT,    0,  0 },
  {  'p', 16, 0, etPOINTER,    0,  1 },

/* All the rest have the FLAG_INTERN bit set and are thus for internal
** use only */
  {  'T',  0, 2, etTOKEN,      0,  0 },
  {  'S',  0, 2, etSRCLIST,    0,  0 },
  {  'r', 10, 3, etORDINAL,    0,  0 },
};

/*
** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
** conversions will work.
*/
#ifndef SQLITE_OMIT_FLOATING_POINT
/*
** "*val" is a double such that 0.1 <= *val < 10.0
** Return the ascii code for the leading digit of *val, then
** multiply "*val" by 10.0 to renormalize.
**
** Example:
**     input:     *val = 3.14159
**     output:    *val = 1.4159    function return = '3'
**
** The counter *cnt is incremented each time.  After counter exceeds
** 16 (the number of significant digits in a 64-bit float) '0' is
** always returned.
*/
static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  int digit;
  LONGDOUBLE_TYPE d;
  if( (*cnt)++ >= 16 ) return '0';
  digit = (int)*val;
  d = digit;
  digit += '0';
  *val = (*val - d)*10.0;
  return (char)digit;
}
#endif /* SQLITE_OMIT_FLOATING_POINT */

/*
** Append N space characters to the given string buffer.
*/
static void appendSpace(StrAccum *pAccum, int N){
  static const char zSpaces[] = "                             ";
  while( N>=(int)sizeof(zSpaces)-1 ){
    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
    N -= sizeof(zSpaces)-1;
  }
  if( N>0 ){
    sqlite3StrAccumAppend(pAccum, zSpaces, N);
  }
}

/*
** On machines with a small stack size, you can redefine the
** SQLITE_PRINT_BUF_SIZE to be less than 350.
*/
#ifndef SQLITE_PRINT_BUF_SIZE
# if defined(SQLITE_SMALL_STACK)
#   define SQLITE_PRINT_BUF_SIZE 50
# else
#   define SQLITE_PRINT_BUF_SIZE 350
# endif
#endif
#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */

/*
** The root program.  All variations call this core.
**
** INPUTS:
**   func   This is a pointer to a function taking three arguments
**            1. A pointer to anything.  Same as the "arg" parameter.
**            2. A pointer to the list of characters to be output
**               (Note, this list is NOT null terminated.)
**            3. An integer number of characters to be output.
**               (Note: This number might be zero.)
**
**   arg    This is the pointer to anything which will be passed as the
**          first argument to "func".  Use it for whatever you like.
**
**   fmt    This is the format string, as in the usual print.
**
**   ap     This is a pointer to a list of arguments.  Same as in
**          vfprint.
**
** OUTPUTS:
**          The return value is the total number of characters sent to
**          the function "func".  Returns -1 on a error.
**
** Note that the order in which automatic variables are declared below
** seems to make a big difference in determining how fast this beast
** will run.
*/
void sqlite3VXPrintf(
  StrAccum *pAccum,                  /* Accumulate results here */
  int useExtended,                   /* Allow extended %-conversions */
  const char *fmt,                   /* Format string */
  va_list ap                         /* arguments */
){
  int c;                     /* Next character in the format string */
  char *bufpt;               /* Pointer to the conversion buffer */
  int precision;             /* Precision of the current field */
  int length;                /* Length of the field */
  int idx;                   /* A general purpose loop counter */
  int width;                 /* Width of the current field */
  etByte flag_leftjustify;   /* True if "-" flag is present */
  etByte flag_plussign;      /* True if "+" flag is present */
  etByte flag_blanksign;     /* True if " " flag is present */
  etByte flag_alternateform; /* True if "#" flag is present */
  etByte flag_altform2;      /* True if "!" flag is present */
  etByte flag_zeropad;       /* True if field width constant starts with zero */
  etByte flag_long;          /* True if "l" flag is present */
  etByte flag_longlong;      /* True if the "ll" flag is present */
  etByte done;               /* Loop termination flag */
  sqlite_uint64 longvalue;   /* Value for integer types */
  LONGDOUBLE_TYPE realvalue; /* Value for real types */
  const et_info *infop;      /* Pointer to the appropriate info structure */
  char buf[etBUFSIZE];       /* Conversion buffer */
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
  etByte xtype = 0;          /* Conversion paradigm */
  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
#ifndef SQLITE_OMIT_FLOATING_POINT
  int  exp, e2;              /* exponent of real numbers */
  double rounder;            /* Used for rounding floating point values */
  etByte flag_dp;            /* True if decimal point should be shown */
  etByte flag_rtz;           /* True if trailing zeros should be removed */
  etByte flag_exp;           /* True to force display of the exponent */
  int nsd;                   /* Number of significant digits returned */
#endif

  length = 0;
  bufpt = 0;
  for(; (c=(*fmt))!=0; ++fmt){
    if( c!='%' ){
      int amt;
      bufpt = (char *)fmt;
      amt = 1;
      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
      sqlite3StrAccumAppend(pAccum, bufpt, amt);
      if( c==0 ) break;
    }
    if( (c=(*++fmt))==0 ){
      sqlite3StrAccumAppend(pAccum, "%", 1);
      break;
    }
    /* Find out what flags are present */
    flag_leftjustify = flag_plussign = flag_blanksign = 
     flag_alternateform = flag_altform2 = flag_zeropad = 0;
    done = 0;
    do{
      switch( c ){
        case '-':   flag_leftjustify = 1;     break;
        case '+':   flag_plussign = 1;        break;
        case ' ':   flag_blanksign = 1;       break;
        case '#':   flag_alternateform = 1;   break;
        case '!':   flag_altform2 = 1;        break;
        case '0':   flag_zeropad = 1;         break;
        default:    done = 1;                 break;
      }
    }while( !done && (c=(*++fmt))!=0 );
    /* Get the field width */
    width = 0;
    if( c=='*' ){
      width = va_arg(ap,int);
      if( width<0 ){
        flag_leftjustify = 1;
        width = -width;
      }
      c = *++fmt;
    }else{
      while( c>='0' && c<='9' ){
        width = width*10 + c - '0';
        c = *++fmt;
      }
    }
    if( width > etBUFSIZE-10 ){
      width = etBUFSIZE-10;
    }
    /* Get the precision */
    if( c=='.' ){
      precision = 0;
      c = *++fmt;
      if( c=='*' ){
        precision = va_arg(ap,int);
        if( precision<0 ) precision = -precision;
        c = *++fmt;
      }else{
        while( c>='0' && c<='9' ){
          precision = precision*10 + c - '0';
          c = *++fmt;
        }
      }
    }else{
      precision = -1;
    }
    /* Get the conversion type modifier */
    if( c=='l' ){
      flag_long = 1;
      c = *++fmt;
      if( c=='l' ){
        flag_longlong = 1;
        c = *++fmt;
      }else{
        flag_longlong = 0;
      }
    }else{
      flag_long = flag_longlong = 0;
    }
    /* Fetch the info entry for the field */
    infop = &fmtinfo[0];
    xtype = etINVALID;
    for(idx=0; idx<ArraySize(fmtinfo); idx++){
      if( c==fmtinfo[idx].fmttype ){
        infop = &fmtinfo[idx];
        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
          xtype = infop->type;
        }else{
          return;
        }
        break;
      }
    }
    zExtra = 0;


    /* Limit the precision to prevent overflowing buf[] during conversion */
    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
      precision = etBUFSIZE-40;
    }

    /*
    ** At this point, variables are initialized as follows:
    **
    **   flag_alternateform          TRUE if a '#' is present.
    **   flag_altform2               TRUE if a '!' is present.
    **   flag_plussign               TRUE if a '+' is present.
    **   flag_leftjustify            TRUE if a '-' is present or if the
    **                               field width was negative.
    **   flag_zeropad                TRUE if the width began with 0.
    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
    **                               the conversion character.
    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
    **                               the conversion character.
    **   flag_blanksign              TRUE if a ' ' is present.
    **   width                       The specified field width.  This is
    **                               always non-negative.  Zero is the default.
    **   precision                   The specified precision.  The default
    **                               is -1.
    **   xtype                       The class of the conversion.
    **   infop                       Pointer to the appropriate info struct.
    */
    switch( xtype ){
      case etPOINTER:
        flag_longlong = sizeof(char*)==sizeof(i64);
        flag_long = sizeof(char*)==sizeof(long int);
        /* Fall through into the next case */
      case etORDINAL:
      case etRADIX:
        if( infop->flags & FLAG_SIGNED ){
          i64 v;
          if( flag_longlong ){
            v = va_arg(ap,i64);
          }else if( flag_long ){
            v = va_arg(ap,long int);
          }else{
            v = va_arg(ap,int);
          }
          if( v<0 ){
            longvalue = -v;
            prefix = '-';
          }else{
            longvalue = v;
            if( flag_plussign )        prefix = '+';
            else if( flag_blanksign )  prefix = ' ';
            else                       prefix = 0;
          }
        }else{
          if( flag_longlong ){
            longvalue = va_arg(ap,u64);
          }else if( flag_long ){
            longvalue = va_arg(ap,unsigned long int);
          }else{
            longvalue = va_arg(ap,unsigned int);
          }
          prefix = 0;
        }
        if( longvalue==0 ) flag_alternateform = 0;
        if( flag_zeropad && precision<width-(prefix!=0) ){
          precision = width-(prefix!=0);
        }
        bufpt = &buf[etBUFSIZE-1];
        if( xtype==etORDINAL ){
          static const char zOrd[] = "thstndrd";
          int x = (int)(longvalue % 10);
          if( x>=4 || (longvalue/10)%10==1 ){
            x = 0;
          }
          buf[etBUFSIZE-3] = zOrd[x*2];
          buf[etBUFSIZE-2] = zOrd[x*2+1];
          bufpt -= 2;
        }
        {
          register const char *cset;      /* Use registers for speed */
          register int base;
          cset = &aDigits[infop->charset];
          base = infop->base;
          do{                                           /* Convert to ascii */
            *(--bufpt) = cset[longvalue%base];
            longvalue = longvalue/base;
          }while( longvalue>0 );
        }
        length = (int)(&buf[etBUFSIZE-1]-bufpt);
        for(idx=precision-length; idx>0; idx--){
          *(--bufpt) = '0';                             /* Zero pad */
        }
        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
          const char *pre;
          char x;
          pre = &aPrefix[infop->prefix];
          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
        }
        length = (int)(&buf[etBUFSIZE-1]-bufpt);
        break;
      case etFLOAT:
      case etEXP:
      case etGENERIC:
        realvalue = va_arg(ap,double);
#ifndef SQLITE_OMIT_FLOATING_POINT
        if( precision<0 ) precision = 6;         /* Set default precision */
        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
        if( realvalue<0.0 ){
          realvalue = -realvalue;
          prefix = '-';
        }else{
          if( flag_plussign )          prefix = '+';
          else if( flag_blanksign )    prefix = ' ';
          else                         prefix = 0;
        }
        if( xtype==etGENERIC && precision>0 ) precision--;
#if 0
        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
#else
        /* It makes more sense to use 0.5 */
        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
#endif
        if( xtype==etFLOAT ) realvalue += rounder;
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
        exp = 0;
        if( sqlite3IsNaN((double)realvalue) ){
          bufpt = "NaN";
          length = 3;
          break;
        }
        if( realvalue>0.0 ){
          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
          if( exp>350 ){
            if( prefix=='-' ){
              bufpt = "-Inf";
            }else if( prefix=='+' ){
              bufpt = "+Inf";
            }else{
              bufpt = "Inf";
            }
            length = sqlite3Strlen30(bufpt);
            break;
          }
        }
        bufpt = buf;
        /*
        ** If the field type is etGENERIC, then convert to either etEXP
        ** or etFLOAT, as appropriate.
        */
        flag_exp = xtype==etEXP;
        if( xtype!=etFLOAT ){
          realvalue += rounder;
          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
        }
        if( xtype==etGENERIC ){
          flag_rtz = !flag_alternateform;
          if( exp<-4 || exp>precision ){
            xtype = etEXP;
          }else{
            precision = precision - exp;
            xtype = etFLOAT;
          }
        }else{
          flag_rtz = 0;
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }
        nsd = 0;
        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
        /* The sign in front of the number */
        if( prefix ){
          *(bufpt++) = prefix;
        }
        /* Digits prior to the decimal point */
        if( e2<0 ){
          *(bufpt++) = '0';
        }else{
          for(; e2>=0; e2--){
            *(bufpt++) = et_getdigit(&realvalue,&nsd);
          }
        }
        /* The decimal point */
        if( flag_dp ){
          *(bufpt++) = '.';
        }
        /* "0" digits after the decimal point but before the first
        ** significant digit of the number */
        for(e2++; e2<0; precision--, e2++){
          assert( precision>0 );
          *(bufpt++) = '0';
        }
        /* Significant digits after the decimal point */
        while( (precision--)>0 ){
          *(bufpt++) = et_getdigit(&realvalue,&nsd);
        }
        /* Remove trailing zeros and the "." if no digits follow the "." */
        if( flag_rtz && flag_dp ){
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
          assert( bufpt>buf );
          if( bufpt[-1]=='.' ){
            if( flag_altform2 ){
              *(bufpt++) = '0';
            }else{
              *(--bufpt) = 0;
            }
          }
        }
        /* Add the "eNNN" suffix */
        if( flag_exp || xtype==etEXP ){
          *(bufpt++) = aDigits[infop->charset];
          if( exp<0 ){
            *(bufpt++) = '-'; exp = -exp;
          }else{
            *(bufpt++) = '+';
          }
          if( exp>=100 ){
            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
            exp %= 100;
          }
          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
        }
        *bufpt = 0;

        /* The converted number is in buf[] and zero terminated. Output it.
        ** Note that the number is in the usual order, not reversed as with
        ** integer conversions. */
        length = (int)(bufpt-buf);
        bufpt = buf;

        /* Special case:  Add leading zeros if the flag_zeropad flag is
        ** set and we are not left justified */
        if( flag_zeropad && !flag_leftjustify && length < width){
          int i;
          int nPad = width - length;
          for(i=width; i>=nPad; i--){
            bufpt[i] = bufpt[i-nPad];
          }
          i = prefix!=0;
          while( nPad-- ) bufpt[i++] = '0';
          length = width;
        }
#endif
        break;
      case etSIZE:
        *(va_arg(ap,int*)) = pAccum->nChar;
        length = width = 0;
        break;
      case etPERCENT:
        buf[0] = '%';
        bufpt = buf;
        length = 1;
        break;
      case etCHARX:
        c = va_arg(ap,int);
        buf[0] = (char)c;
        if( precision>=0 ){
          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
          length = precision;
        }else{
          length =1;
        }
        bufpt = buf;
        break;
      case etSTRING:
      case etDYNSTRING:
        bufpt = va_arg(ap,char*);
        if( bufpt==0 ){
          bufpt = "";
        }else if( xtype==etDYNSTRING ){
          zExtra = bufpt;
        }
        if( precision>=0 ){
          for(length=0; length<precision && bufpt[length]; length++){}
        }else{
          length = sqlite3Strlen30(bufpt);
        }
        break;
      case etSQLESCAPE:
      case etSQLESCAPE2:
      case etSQLESCAPE3: {
        int i, j, n, isnull;
        int needQuote;
        char ch;
        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
        char *escarg = va_arg(ap,char*);
        isnull = escarg==0;
        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
        for(i=n=0; (ch=escarg[i])!=0; i++){
          if( ch==q )  n++;
        }
        needQuote = !isnull && xtype==etSQLESCAPE2;
        n += i + 1 + needQuote*2;
        if( n>etBUFSIZE ){
          bufpt = zExtra = sqlite3Malloc( n );
          if( bufpt==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }else{
          bufpt = buf;
        }
        j = 0;
        if( needQuote ) bufpt[j++] = q;
        for(i=0; (ch=escarg[i])!=0; i++){
          bufpt[j++] = ch;
          if( ch==q ) bufpt[j++] = ch;
        }
        if( needQuote ) bufpt[j++] = q;
        bufpt[j] = 0;
        length = j;
        /* The precision is ignored on %q and %Q */
        /* if( precision>=0 && precision<length ) length = precision; */
        break;
      }
      case etTOKEN: {
        Token *pToken = va_arg(ap, Token*);
        if( pToken ){
          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
        }
        length = width = 0;
        break;
      }
      case etSRCLIST: {
        SrcList *pSrc = va_arg(ap, SrcList*);
        int k = va_arg(ap, int);
        struct SrcList_item *pItem = &pSrc->a[k];
        assert( k>=0 && k<pSrc->nSrc );
        if( pItem->zDatabase ){
          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
          sqlite3StrAccumAppend(pAccum, ".", 1);
        }
        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
        length = width = 0;
        break;
      }
      default: {
        assert( xtype==etINVALID );
        return;
      }
    }/* End switch over the format type */
    /*
    ** The text of the conversion is pointed to by "bufpt" and is
    ** "length" characters long.  The field width is "width".  Do
    ** the output.
    */
    if( !flag_leftjustify ){
      register int nspace;
      nspace = width-length;
      if( nspace>0 ){
        appendSpace(pAccum, nspace);
      }
    }
    if( length>0 ){
      sqlite3StrAccumAppend(pAccum, bufpt, length);
    }
    if( flag_leftjustify ){
      register int nspace;
      nspace = width-length;
      if( nspace>0 ){
        appendSpace(pAccum, nspace);
      }
    }
    if( zExtra ){
      sqlite3_free(zExtra);
    }
  }/* End for loop over the format string */
} /* End of function */

/*
** Append N bytes of text from z to the StrAccum object.
*/
void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  assert( z!=0 || N==0 );
  if( p->tooBig | p->mallocFailed ){
    testcase(p->tooBig);
    testcase(p->mallocFailed);
    return;
  }
  if( N<0 ){
    N = sqlite3Strlen30(z);
  }
  if( N==0 || NEVER(z==0) ){
    return;
  }
  if( p->nChar+N >= p->nAlloc ){
    char *zNew;
    if( !p->useMalloc ){
      p->tooBig = 1;
      N = p->nAlloc - p->nChar - 1;
      if( N<=0 ){
        return;
      }
    }else{
      i64 szNew = p->nChar;
      szNew += N + 1;
      if( szNew > p->mxAlloc ){
        sqlite3StrAccumReset(p);
        p->tooBig = 1;
        return;
      }else{
        p->nAlloc = (int)szNew;
      }
      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
      if( zNew ){
        memcpy(zNew, p->zText, p->nChar);
        sqlite3StrAccumReset(p);
        p->zText = zNew;
      }else{
        p->mallocFailed = 1;
        sqlite3StrAccumReset(p);
        return;
      }
    }
  }
  memcpy(&p->zText[p->nChar], z, N);
  p->nChar += N;
}

/*
** Finish off a string by making sure it is zero-terminated.
** Return a pointer to the resulting string.  Return a NULL
** pointer if any kind of error was encountered.
*/
char *sqlite3StrAccumFinish(StrAccum *p){
  if( p->zText ){
    p->zText[p->nChar] = 0;
    if( p->useMalloc && p->zText==p->zBase ){
      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
      if( p->zText ){
        memcpy(p->zText, p->zBase, p->nChar+1);
      }else{
        p->mallocFailed = 1;
      }
    }
  }
  return p->zText;
}

/*
** Reset an StrAccum string.  Reclaim all malloced memory.
*/
void sqlite3StrAccumReset(StrAccum *p){
  if( p->zText!=p->zBase ){
    sqlite3DbFree(p->db, p->zText);
  }
  p->zText = 0;
}

/*
** Initialize a string accumulator
*/
void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  p->zText = p->zBase = zBase;
  p->db = 0;
  p->nChar = 0;
  p->nAlloc = n;
  p->mxAlloc = mx;
  p->useMalloc = 1;
  p->tooBig = 0;
  p->mallocFailed = 0;
}

/*
** Print into memory obtained from sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  char *z;
  char zBase[SQLITE_PRINT_BUF_SIZE];
  StrAccum acc;
  assert( db!=0 );
  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
                      db->aLimit[SQLITE_LIMIT_LENGTH]);
  acc.db = db;
  sqlite3VXPrintf(&acc, 1, zFormat, ap);
  z = sqlite3StrAccumFinish(&acc);
  if( acc.mallocFailed ){
    db->mallocFailed = 1;
  }
  return z;
}

/*
** Print into memory obtained from sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  va_list ap;
  char *z;
  va_start(ap, zFormat);
  z = sqlite3VMPrintf(db, zFormat, ap);
  va_end(ap);
  return z;
}

/*
** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
** the string and before returnning.  This routine is intended to be used
** to modify an existing string.  For example:
**
**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
**
*/
char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  va_list ap;
  char *z;
  va_start(ap, zFormat);
  z = sqlite3VMPrintf(db, zFormat, ap);
  va_end(ap);
  sqlite3DbFree(db, zStr);
  return z;
}

/*
** Print into memory obtained from sqlite3_malloc().  Omit the internal
** %-conversion extensions.
*/
char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  char *z;
  char zBase[SQLITE_PRINT_BUF_SIZE];
  StrAccum acc;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite3_initialize() ) return 0;
#endif
  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
  z = sqlite3StrAccumFinish(&acc);
  return z;
}

/*
** Print into memory obtained from sqlite3_malloc()().  Omit the internal
** %-conversion extensions.
*/
char *sqlite3_mprintf(const char *zFormat, ...){
  va_list ap;
  char *z;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite3_initialize() ) return 0;
#endif
  va_start(ap, zFormat);
  z = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  return z;
}

/*
** sqlite3_snprintf() works like snprintf() except that it ignores the
** current locale settings.  This is important for SQLite because we
** are not able to use a "," as the decimal point in place of "." as
** specified by some locales.
*/
char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  char *z;
  va_list ap;
  StrAccum acc;

  if( n<=0 ){
    return zBuf;
  }
  sqlite3StrAccumInit(&acc, zBuf, n, 0);
  acc.useMalloc = 0;
  va_start(ap,zFormat);
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
  va_end(ap);
  z = sqlite3StrAccumFinish(&acc);
  return z;
}

#if defined(SQLITE_DEBUG)
/*
** A version of printf() that understands %lld.  Used for debugging.
** The printf() built into some versions of windows does not understand %lld
** and segfaults if you give it a long long int.
*/
void sqlite3DebugPrintf(const char *zFormat, ...){
  va_list ap;
  StrAccum acc;
  char zBuf[500];
  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  acc.useMalloc = 0;
  va_start(ap,zFormat);
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
  va_end(ap);
  sqlite3StrAccumFinish(&acc);
  fprintf(stdout,"%s", zBuf);
  fflush(stdout);
}
#endif

Added src/random.c.







































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement a pseudo-random number
** generator (PRNG) for SQLite.
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
**
** $Id: random.c,v 1.29 2008/12/10 19:26:24 drh Exp $
*/
#include "sqliteInt.h"


/* All threads share a single random number generator.
** This structure is the current state of the generator.
*/
static SQLITE_WSD struct sqlite3PrngType {
  unsigned char isInit;          /* True if initialized */
  unsigned char i, j;            /* State variables */
  unsigned char s[256];          /* State variables */
} sqlite3Prng;

/*
** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
** must be held while executing this routine.
**
** Why not just use a library random generator like lrand48() for this?
** Because the OP_NewRowid opcode in the VDBE depends on having a very
** good source of random numbers.  The lrand48() library function may
** well be good enough.  But maybe not.  Or maybe lrand48() has some
** subtle problems on some systems that could cause problems.  It is hard
** to know.  To minimize the risk of problems due to bad lrand48()
** implementations, SQLite uses this random number generator based
** on RC4, which we know works very well.
**
** (Later):  Actually, OP_NewRowid does not depend on a good source of
** randomness any more.  But we will leave this code in all the same.
*/
static u8 randomByte(void){
  unsigned char t;


  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  ** state vector.  If writable static data is unsupported on the target,
  ** we have to locate the state vector at run-time.  In the more common
  ** case where writable static data is supported, wsdPrng can refer directly
  ** to the "sqlite3Prng" state vector declared above.
  */
#ifdef SQLITE_OMIT_WSD
  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
# define wsdPrng p[0]
#else
# define wsdPrng sqlite3Prng
#endif


  /* Initialize the state of the random number generator once,
  ** the first time this routine is called.  The seed value does
  ** not need to contain a lot of randomness since we are not
  ** trying to do secure encryption or anything like that...
  **
  ** Nothing in this file or anywhere else in SQLite does any kind of
  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
  ** number generator) not as an encryption device.
  */
  if( !wsdPrng.isInit ){
    int i;
    char k[256];
    wsdPrng.j = 0;
    wsdPrng.i = 0;
    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
    for(i=0; i<256; i++){
      wsdPrng.s[i] = (u8)i;
    }
    for(i=0; i<256; i++){
      wsdPrng.j += wsdPrng.s[i] + k[i];
      t = wsdPrng.s[wsdPrng.j];
      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
      wsdPrng.s[i] = t;
    }
    wsdPrng.isInit = 1;
  }

  /* Generate and return single random byte
  */
  wsdPrng.i++;
  t = wsdPrng.s[wsdPrng.i];
  wsdPrng.j += t;
  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  wsdPrng.s[wsdPrng.j] = t;
  t += wsdPrng.s[wsdPrng.i];
  return wsdPrng.s[t];
}

/*
** Return N random bytes.
*/
void sqlite3_randomness(int N, void *pBuf){
  unsigned char *zBuf = pBuf;
#if SQLITE_THREADSAFE
  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
#endif
  sqlite3_mutex_enter(mutex);
  while( N-- ){
    *(zBuf++) = randomByte();
  }
  sqlite3_mutex_leave(mutex);
}

#ifndef SQLITE_OMIT_BUILTIN_TEST
/*
** For testing purposes, we sometimes want to preserve the state of
** PRNG and restore the PRNG to its saved state at a later time, or
** to reset the PRNG to its initial state.  These routines accomplish
** those tasks.
**
** The sqlite3_test_control() interface calls these routines to
** control the PRNG.
*/
static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
void sqlite3PrngSaveState(void){
  memcpy(
    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
    sizeof(sqlite3Prng)
  );
}
void sqlite3PrngRestoreState(void){
  memcpy(
    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
    sizeof(sqlite3Prng)
  );
}
void sqlite3PrngResetState(void){
  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
}
#endif /* SQLITE_OMIT_BUILTIN_TEST */

Added src/resolve.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
/*
** 2008 August 18
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains routines used for walking the parser tree and
** resolve all identifiers by associating them with a particular
** table and column.
**
** $Id: resolve.c,v 1.30 2009/06/15 23:15:59 drh Exp $
*/
#include "sqliteInt.h"
#include <stdlib.h>
#include <string.h>

/*
** Turn the pExpr expression into an alias for the iCol-th column of the
** result set in pEList.
**
** If the result set column is a simple column reference, then this routine
** makes an exact copy.  But for any other kind of expression, this
** routine make a copy of the result set column as the argument to the
** TK_AS operator.  The TK_AS operator causes the expression to be
** evaluated just once and then reused for each alias.
**
** The reason for suppressing the TK_AS term when the expression is a simple
** column reference is so that the column reference will be recognized as
** usable by indices within the WHERE clause processing logic. 
**
** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
**
**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
**
** Is equivalent to:
**
**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
**
** The result of random()%5 in the GROUP BY clause is probably different
** from the result in the result-set.  We might fix this someday.  Or
** then again, we might not...
*/
static void resolveAlias(
  Parse *pParse,         /* Parsing context */
  ExprList *pEList,      /* A result set */
  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
  Expr *pExpr,           /* Transform this into an alias to the result set */
  const char *zType      /* "GROUP" or "ORDER" or "" */
){
  Expr *pOrig;           /* The iCol-th column of the result set */
  Expr *pDup;            /* Copy of pOrig */
  sqlite3 *db;           /* The database connection */

  assert( iCol>=0 && iCol<pEList->nExpr );
  pOrig = pEList->a[iCol].pExpr;
  assert( pOrig!=0 );
  assert( pOrig->flags & EP_Resolved );
  db = pParse->db;
  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
    pDup = sqlite3ExprDup(db, pOrig, 0);
    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
    if( pDup==0 ) return;
    if( pEList->a[iCol].iAlias==0 ){
      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
    }
    pDup->iTable = pEList->a[iCol].iAlias;
  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
    pDup = sqlite3ExprDup(db, pOrig, 0);
    if( pDup==0 ) return;
  }else{
    char *zToken = pOrig->u.zToken;
    assert( zToken!=0 );
    pOrig->u.zToken = 0;
    pDup = sqlite3ExprDup(db, pOrig, 0);
    pOrig->u.zToken = zToken;
    if( pDup==0 ) return;
    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
    pDup->flags2 |= EP2_MallocedToken;
    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
  }
  if( pExpr->flags & EP_ExpCollate ){
    pDup->pColl = pExpr->pColl;
    pDup->flags |= EP_ExpCollate;
  }
  sqlite3ExprClear(db, pExpr);
  memcpy(pExpr, pDup, sizeof(*pExpr));
  sqlite3DbFree(db, pDup);
}

/*
** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
** that name in the set of source tables in pSrcList and make the pExpr 
** expression node refer back to that source column.  The following changes
** are made to pExpr:
**
**    pExpr->iDb           Set the index in db->aDb[] of the database X
**                         (even if X is implied).
**    pExpr->iTable        Set to the cursor number for the table obtained
**                         from pSrcList.
**    pExpr->pTab          Points to the Table structure of X.Y (even if
**                         X and/or Y are implied.)
**    pExpr->iColumn       Set to the column number within the table.
**    pExpr->op            Set to TK_COLUMN.
**    pExpr->pLeft         Any expression this points to is deleted
**    pExpr->pRight        Any expression this points to is deleted.
**
** The zDb variable is the name of the database (the "X").  This value may be
** NULL meaning that name is of the form Y.Z or Z.  Any available database
** can be used.  The zTable variable is the name of the table (the "Y").  This
** value can be NULL if zDb is also NULL.  If zTable is NULL it
** means that the form of the name is Z and that columns from any table
** can be used.
**
** If the name cannot be resolved unambiguously, leave an error message
** in pParse and return WRC_Abort.  Return WRC_Prune on success.
*/
static int lookupName(
  Parse *pParse,       /* The parsing context */
  const char *zDb,     /* Name of the database containing table, or NULL */
  const char *zTab,    /* Name of table containing column, or NULL */
  const char *zCol,    /* Name of the column. */
  NameContext *pNC,    /* The name context used to resolve the name */
  Expr *pExpr          /* Make this EXPR node point to the selected column */
){
  int i, j;            /* Loop counters */
  int cnt = 0;                      /* Number of matching column names */
  int cntTab = 0;                   /* Number of matching table names */
  sqlite3 *db = pParse->db;         /* The database connection */
  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
  NameContext *pTopNC = pNC;        /* First namecontext in the list */
  Schema *pSchema = 0;              /* Schema of the expression */
  int isTrigger = 0;

  assert( pNC );     /* the name context cannot be NULL. */
  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );

  /* Initialize the node to no-match */
  pExpr->iTable = -1;
  pExpr->pTab = 0;
  ExprSetIrreducible(pExpr);

  /* Start at the inner-most context and move outward until a match is found */
  while( pNC && cnt==0 ){
    ExprList *pEList;
    SrcList *pSrcList = pNC->pSrcList;

    if( pSrcList ){
      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
        Table *pTab;
        int iDb;
        Column *pCol;
  
        pTab = pItem->pTab;
        assert( pTab!=0 && pTab->zName!=0 );
        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
        assert( pTab->nCol>0 );
        if( zTab ){
          if( pItem->zAlias ){
            char *zTabName = pItem->zAlias;
            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
          }else{
            char *zTabName = pTab->zName;
            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
              continue;
            }
            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
              continue;
            }
          }
        }
        if( 0==(cntTab++) ){
          pExpr->iTable = pItem->iCursor;
          pExpr->pTab = pTab;
          pSchema = pTab->pSchema;
          pMatch = pItem;
        }
        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
            IdList *pUsing;
            cnt++;
            pExpr->iTable = pItem->iCursor;
            pExpr->pTab = pTab;
            pMatch = pItem;
            pSchema = pTab->pSchema;
            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
            if( i<pSrcList->nSrc-1 ){
              if( pItem[1].jointype & JT_NATURAL ){
                /* If this match occurred in the left table of a natural join,
                ** then skip the right table to avoid a duplicate match */
                pItem++;
                i++;
              }else if( (pUsing = pItem[1].pUsing)!=0 ){
                /* If this match occurs on a column that is in the USING clause
                ** of a join, skip the search of the right table of the join
                ** to avoid a duplicate match there. */
                int k;
                for(k=0; k<pUsing->nId; k++){
                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
                    pItem++;
                    i++;
                    break;
                  }
                }
              }
            }
            break;
          }
        }
      }
    }

#ifndef SQLITE_OMIT_TRIGGER
    /* If we have not already resolved the name, then maybe 
    ** it is a new.* or old.* trigger argument reference
    */
    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
      int op = pParse->eTriggerOp;
      Table *pTab = 0;
      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
        pExpr->iTable = 1;
        pTab = pParse->pTriggerTab;
      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
        pExpr->iTable = 0;
        pTab = pParse->pTriggerTab;
      }

      if( pTab ){ 
        int iCol;
        pSchema = pTab->pSchema;
        cntTab++;
        if( sqlite3IsRowid(zCol) ){
          iCol = -1;
        }else{
          for(iCol=0; iCol<pTab->nCol; iCol++){
            Column *pCol = &pTab->aCol[iCol];
            if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
              if( iCol==pTab->iPKey ){
                iCol = -1;
              }
              break;
            }
          }
        }
        if( iCol<pTab->nCol ){
          cnt++;
          if( iCol<0 ){
            pExpr->affinity = SQLITE_AFF_INTEGER;
          }else if( pExpr->iTable==0 ){
            testcase( iCol==31 );
            testcase( iCol==32 );
            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
          }
          pExpr->iColumn = (i16)iCol;
          pExpr->pTab = pTab;
          isTrigger = 1;
        }
      }
    }
#endif /* !defined(SQLITE_OMIT_TRIGGER) */

    /*
    ** Perhaps the name is a reference to the ROWID
    */
    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
      cnt = 1;
      pExpr->iColumn = -1;
      pExpr->affinity = SQLITE_AFF_INTEGER;
    }

    /*
    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
    ** might refer to an result-set alias.  This happens, for example, when
    ** we are resolving names in the WHERE clause of the following command:
    **
    **     SELECT a+b AS x FROM table WHERE x<10;
    **
    ** In cases like this, replace pExpr with a copy of the expression that
    ** forms the result set entry ("a+b" in the example) and return immediately.
    ** Note that the expression in the result set should have already been
    ** resolved by the time the WHERE clause is resolved.
    */
    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
      for(j=0; j<pEList->nExpr; j++){
        char *zAs = pEList->a[j].zName;
        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
          Expr *pOrig;
          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
          assert( pExpr->x.pList==0 );
          assert( pExpr->x.pSelect==0 );
          pOrig = pEList->a[j].pExpr;
          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
            return WRC_Abort;
          }
          resolveAlias(pParse, pEList, j, pExpr, "");
          cnt = 1;
          pMatch = 0;
          assert( zTab==0 && zDb==0 );
          goto lookupname_end;
        }
      } 
    }

    /* Advance to the next name context.  The loop will exit when either
    ** we have a match (cnt>0) or when we run out of name contexts.
    */
    if( cnt==0 ){
      pNC = pNC->pNext;
    }
  }

  /*
  ** If X and Y are NULL (in other words if only the column name Z is
  ** supplied) and the value of Z is enclosed in double-quotes, then
  ** Z is a string literal if it doesn't match any column names.  In that
  ** case, we need to return right away and not make any changes to
  ** pExpr.
  **
  ** Because no reference was made to outer contexts, the pNC->nRef
  ** fields are not changed in any context.
  */
  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
    pExpr->op = TK_STRING;
    pExpr->pTab = 0;
    return WRC_Prune;
  }

  /*
  ** cnt==0 means there was not match.  cnt>1 means there were two or
  ** more matches.  Either way, we have an error.
  */
  if( cnt!=1 ){
    const char *zErr;
    zErr = cnt==0 ? "no such column" : "ambiguous column name";
    if( zDb ){
      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
    }else if( zTab ){
      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
    }else{
      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
    }
    pTopNC->nErr++;
  }

  /* If a column from a table in pSrcList is referenced, then record
  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
  ** column number is greater than the number of bits in the bitmask
  ** then set the high-order bit of the bitmask.
  */
  if( pExpr->iColumn>=0 && pMatch!=0 ){
    int n = pExpr->iColumn;
    testcase( n==BMS-1 );
    if( n>=BMS ){
      n = BMS-1;
    }
    assert( pMatch->iCursor==pExpr->iTable );
    pMatch->colUsed |= ((Bitmask)1)<<n;
  }

  /* Clean up and return
  */
  sqlite3ExprDelete(db, pExpr->pLeft);
  pExpr->pLeft = 0;
  sqlite3ExprDelete(db, pExpr->pRight);
  pExpr->pRight = 0;
  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
lookupname_end:
  if( cnt==1 ){
    assert( pNC!=0 );
    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
    /* Increment the nRef value on all name contexts from TopNC up to
    ** the point where the name matched. */
    for(;;){
      assert( pTopNC!=0 );
      pTopNC->nRef++;
      if( pTopNC==pNC ) break;
      pTopNC = pTopNC->pNext;
    }
    return WRC_Prune;
  } else {
    return WRC_Abort;
  }
}

/*
** Allocate and return a pointer to an expression to load the column iCol
** from datasource iSrc datasource in SrcList pSrc.
*/
Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  if( p ){
    struct SrcList_item *pItem = &pSrc->a[iSrc];
    p->pTab = pItem->pTab;
    p->iTable = pItem->iCursor;
    if( p->pTab->iPKey==iCol ){
      p->iColumn = -1;
    }else{
      p->iColumn = (ynVar)iCol;
      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
    }
    ExprSetProperty(p, EP_Resolved);
  }
  return p;
}

/*
** This routine is callback for sqlite3WalkExpr().
**
** Resolve symbolic names into TK_COLUMN operators for the current
** node in the expression tree.  Return 0 to continue the search down
** the tree or 2 to abort the tree walk.
**
** This routine also does error checking and name resolution for
** function names.  The operator for aggregate functions is changed
** to TK_AGG_FUNCTION.
*/
static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  NameContext *pNC;
  Parse *pParse;

  pNC = pWalker->u.pNC;
  assert( pNC!=0 );
  pParse = pNC->pParse;
  assert( pParse==pWalker->pParse );

  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  ExprSetProperty(pExpr, EP_Resolved);
#ifndef NDEBUG
  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
    SrcList *pSrcList = pNC->pSrcList;
    int i;
    for(i=0; i<pNC->pSrcList->nSrc; i++){
      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
    }
  }
#endif
  switch( pExpr->op ){

#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
    /* The special operator TK_ROW means use the rowid for the first
    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
    ** clause processing on UPDATE and DELETE statements.
    */
    case TK_ROW: {
      SrcList *pSrcList = pNC->pSrcList;
      struct SrcList_item *pItem;
      assert( pSrcList && pSrcList->nSrc==1 );
      pItem = pSrcList->a; 
      pExpr->op = TK_COLUMN;
      pExpr->pTab = pItem->pTab;
      pExpr->iTable = pItem->iCursor;
      pExpr->iColumn = -1;
      pExpr->affinity = SQLITE_AFF_INTEGER;
      break;
    }
#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */

    /* A lone identifier is the name of a column.
    */
    case TK_ID: {
      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
    }
  
    /* A table name and column name:     ID.ID
    ** Or a database, table and column:  ID.ID.ID
    */
    case TK_DOT: {
      const char *zColumn;
      const char *zTable;
      const char *zDb;
      Expr *pRight;

      /* if( pSrcList==0 ) break; */
      pRight = pExpr->pRight;
      if( pRight->op==TK_ID ){
        zDb = 0;
        zTable = pExpr->pLeft->u.zToken;
        zColumn = pRight->u.zToken;
      }else{
        assert( pRight->op==TK_DOT );
        zDb = pExpr->pLeft->u.zToken;
        zTable = pRight->pLeft->u.zToken;
        zColumn = pRight->pRight->u.zToken;
      }
      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
    }

    /* Resolve function names
    */
    case TK_CONST_FUNC:
    case TK_FUNCTION: {
      ExprList *pList = pExpr->x.pList;    /* The argument list */
      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
      int no_such_func = 0;       /* True if no such function exists */
      int wrong_num_args = 0;     /* True if wrong number of arguments */
      int is_agg = 0;             /* True if is an aggregate function */
      int auth;                   /* Authorization to use the function */
      int nId;                    /* Number of characters in function name */
      const char *zId;            /* The function name. */
      FuncDef *pDef;              /* Information about the function */
      u8 enc = ENC(pParse->db);   /* The database encoding */

      testcase( pExpr->op==TK_CONST_FUNC );
      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
      zId = pExpr->u.zToken;
      nId = sqlite3Strlen30(zId);
      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
      if( pDef==0 ){
        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
        if( pDef==0 ){
          no_such_func = 1;
        }else{
          wrong_num_args = 1;
        }
      }else{
        is_agg = pDef->xFunc==0;
      }
#ifndef SQLITE_OMIT_AUTHORIZATION
      if( pDef ){
        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
        if( auth!=SQLITE_OK ){
          if( auth==SQLITE_DENY ){
            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
                                    pDef->zName);
            pNC->nErr++;
          }
          pExpr->op = TK_NULL;
          return WRC_Prune;
        }
      }
#endif
      if( is_agg && !pNC->allowAgg ){
        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
        pNC->nErr++;
        is_agg = 0;
      }else if( no_such_func ){
        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
        pNC->nErr++;
      }else if( wrong_num_args ){
        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
             nId, zId);
        pNC->nErr++;
      }
      if( is_agg ){
        pExpr->op = TK_AGG_FUNCTION;
        pNC->hasAgg = 1;
      }
      if( is_agg ) pNC->allowAgg = 0;
      sqlite3WalkExprList(pWalker, pList);
      if( is_agg ) pNC->allowAgg = 1;
      /* FIX ME:  Compute pExpr->affinity based on the expected return
      ** type of the function 
      */
      return WRC_Prune;
    }
#ifndef SQLITE_OMIT_SUBQUERY
    case TK_SELECT:
    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
#endif
    case TK_IN: {
      testcase( pExpr->op==TK_IN );
      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
        int nRef = pNC->nRef;
#ifndef SQLITE_OMIT_CHECK
        if( pNC->isCheck ){
          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
        }
#endif
        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
        assert( pNC->nRef>=nRef );
        if( nRef!=pNC->nRef ){
          ExprSetProperty(pExpr, EP_VarSelect);
        }
      }
      break;
    }
#ifndef SQLITE_OMIT_CHECK
    case TK_VARIABLE: {
      if( pNC->isCheck ){
        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
      }
      break;
    }
#endif
  }
  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
}

/*
** pEList is a list of expressions which are really the result set of the
** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
** This routine checks to see if pE is a simple identifier which corresponds
** to the AS-name of one of the terms of the expression list.  If it is,
** this routine return an integer between 1 and N where N is the number of
** elements in pEList, corresponding to the matching entry.  If there is
** no match, or if pE is not a simple identifier, then this routine
** return 0.
**
** pEList has been resolved.  pE has not.
*/
static int resolveAsName(
  Parse *pParse,     /* Parsing context for error messages */
  ExprList *pEList,  /* List of expressions to scan */
  Expr *pE           /* Expression we are trying to match */
){
  int i;             /* Loop counter */

  UNUSED_PARAMETER(pParse);

  if( pE->op==TK_ID ){
    char *zCol = pE->u.zToken;
    for(i=0; i<pEList->nExpr; i++){
      char *zAs = pEList->a[i].zName;
      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
        return i+1;
      }
    }
  }
  return 0;
}

/*
** pE is a pointer to an expression which is a single term in the
** ORDER BY of a compound SELECT.  The expression has not been
** name resolved.
**
** At the point this routine is called, we already know that the
** ORDER BY term is not an integer index into the result set.  That
** case is handled by the calling routine.
**
** Attempt to match pE against result set columns in the left-most
** SELECT statement.  Return the index i of the matching column,
** as an indication to the caller that it should sort by the i-th column.
** The left-most column is 1.  In other words, the value returned is the
** same integer value that would be used in the SQL statement to indicate
** the column.
**
** If there is no match, return 0.  Return -1 if an error occurs.
*/
static int resolveOrderByTermToExprList(
  Parse *pParse,     /* Parsing context for error messages */
  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
  Expr *pE           /* The specific ORDER BY term */
){
  int i;             /* Loop counter */
  ExprList *pEList;  /* The columns of the result set */
  NameContext nc;    /* Name context for resolving pE */

  assert( sqlite3ExprIsInteger(pE, &i)==0 );
  pEList = pSelect->pEList;

  /* Resolve all names in the ORDER BY term expression
  */
  memset(&nc, 0, sizeof(nc));
  nc.pParse = pParse;
  nc.pSrcList = pSelect->pSrc;
  nc.pEList = pEList;
  nc.allowAgg = 1;
  nc.nErr = 0;
  if( sqlite3ResolveExprNames(&nc, pE) ){
    sqlite3ErrorClear(pParse);
    return 0;
  }

  /* Try to match the ORDER BY expression against an expression
  ** in the result set.  Return an 1-based index of the matching
  ** result-set entry.
  */
  for(i=0; i<pEList->nExpr; i++){
    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
      return i+1;
    }
  }

  /* If no match, return 0. */
  return 0;
}

/*
** Generate an ORDER BY or GROUP BY term out-of-range error.
*/
static void resolveOutOfRangeError(
  Parse *pParse,         /* The error context into which to write the error */
  const char *zType,     /* "ORDER" or "GROUP" */
  int i,                 /* The index (1-based) of the term out of range */
  int mx                 /* Largest permissible value of i */
){
  sqlite3ErrorMsg(pParse, 
    "%r %s BY term out of range - should be "
    "between 1 and %d", i, zType, mx);
}

/*
** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
** each term of the ORDER BY clause is a constant integer between 1
** and N where N is the number of columns in the compound SELECT.
**
** ORDER BY terms that are already an integer between 1 and N are
** unmodified.  ORDER BY terms that are integers outside the range of
** 1 through N generate an error.  ORDER BY terms that are expressions
** are matched against result set expressions of compound SELECT
** beginning with the left-most SELECT and working toward the right.
** At the first match, the ORDER BY expression is transformed into
** the integer column number.
**
** Return the number of errors seen.
*/
static int resolveCompoundOrderBy(
  Parse *pParse,        /* Parsing context.  Leave error messages here */
  Select *pSelect       /* The SELECT statement containing the ORDER BY */
){
  int i;
  ExprList *pOrderBy;
  ExprList *pEList;
  sqlite3 *db;
  int moreToDo = 1;

  pOrderBy = pSelect->pOrderBy;
  if( pOrderBy==0 ) return 0;
  db = pParse->db;
#if SQLITE_MAX_COLUMN
  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
    return 1;
  }
#endif
  for(i=0; i<pOrderBy->nExpr; i++){
    pOrderBy->a[i].done = 0;
  }
  pSelect->pNext = 0;
  while( pSelect->pPrior ){
    pSelect->pPrior->pNext = pSelect;
    pSelect = pSelect->pPrior;
  }
  while( pSelect && moreToDo ){
    struct ExprList_item *pItem;
    moreToDo = 0;
    pEList = pSelect->pEList;
    assert( pEList!=0 );
    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
      int iCol = -1;
      Expr *pE, *pDup;
      if( pItem->done ) continue;
      pE = pItem->pExpr;
      if( sqlite3ExprIsInteger(pE, &iCol) ){
        if( iCol<=0 || iCol>pEList->nExpr ){
          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
          return 1;
        }
      }else{
        iCol = resolveAsName(pParse, pEList, pE);
        if( iCol==0 ){
          pDup = sqlite3ExprDup(db, pE, 0);
          if( !db->mallocFailed ){
            assert(pDup);
            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
          }
          sqlite3ExprDelete(db, pDup);
        }
      }
      if( iCol>0 ){
        CollSeq *pColl = pE->pColl;
        int flags = pE->flags & EP_ExpCollate;
        sqlite3ExprDelete(db, pE);
        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
        if( pE==0 ) return 1;
        pE->pColl = pColl;
        pE->flags |= EP_IntValue | flags;
        pE->u.iValue = iCol;
        pItem->iCol = (u16)iCol;
        pItem->done = 1;
      }else{
        moreToDo = 1;
      }
    }
    pSelect = pSelect->pNext;
  }
  for(i=0; i<pOrderBy->nExpr; i++){
    if( pOrderBy->a[i].done==0 ){
      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
            "column in the result set", i+1);
      return 1;
    }
  }
  return 0;
}

/*
** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
** the SELECT statement pSelect.  If any term is reference to a
** result set expression (as determined by the ExprList.a.iCol field)
** then convert that term into a copy of the corresponding result set
** column.
**
** If any errors are detected, add an error message to pParse and
** return non-zero.  Return zero if no errors are seen.
*/
int sqlite3ResolveOrderGroupBy(
  Parse *pParse,        /* Parsing context.  Leave error messages here */
  Select *pSelect,      /* The SELECT statement containing the clause */
  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
  const char *zType     /* "ORDER" or "GROUP" */
){
  int i;
  sqlite3 *db = pParse->db;
  ExprList *pEList;
  struct ExprList_item *pItem;

  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
#if SQLITE_MAX_COLUMN
  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
    return 1;
  }
#endif
  pEList = pSelect->pEList;
  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
    if( pItem->iCol ){
      if( pItem->iCol>pEList->nExpr ){
        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
        return 1;
      }
      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
    }
  }
  return 0;
}

/*
** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
** The Name context of the SELECT statement is pNC.  zType is either
** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
**
** This routine resolves each term of the clause into an expression.
** If the order-by term is an integer I between 1 and N (where N is the
** number of columns in the result set of the SELECT) then the expression
** in the resolution is a copy of the I-th result-set expression.  If
** the order-by term is an identify that corresponds to the AS-name of
** a result-set expression, then the term resolves to a copy of the
** result-set expression.  Otherwise, the expression is resolved in
** the usual way - using sqlite3ResolveExprNames().
**
** This routine returns the number of errors.  If errors occur, then
** an appropriate error message might be left in pParse.  (OOM errors
** excepted.)
*/
static int resolveOrderGroupBy(
  NameContext *pNC,     /* The name context of the SELECT statement */
  Select *pSelect,      /* The SELECT statement holding pOrderBy */
  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
){
  int i;                         /* Loop counter */
  int iCol;                      /* Column number */
  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
  Parse *pParse;                 /* Parsing context */
  int nResult;                   /* Number of terms in the result set */

  if( pOrderBy==0 ) return 0;
  nResult = pSelect->pEList->nExpr;
  pParse = pNC->pParse;
  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
    Expr *pE = pItem->pExpr;
    iCol = resolveAsName(pParse, pSelect->pEList, pE);
    if( iCol>0 ){
      /* If an AS-name match is found, mark this ORDER BY column as being
      ** a copy of the iCol-th result-set column.  The subsequent call to
      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
      ** copy of the iCol-th result-set expression. */
      pItem->iCol = (u16)iCol;
      continue;
    }
    if( sqlite3ExprIsInteger(pE, &iCol) ){
      /* The ORDER BY term is an integer constant.  Again, set the column
      ** number so that sqlite3ResolveOrderGroupBy() will convert the
      ** order-by term to a copy of the result-set expression */
      if( iCol<1 ){
        resolveOutOfRangeError(pParse, zType, i+1, nResult);
        return 1;
      }
      pItem->iCol = (u16)iCol;
      continue;
    }

    /* Otherwise, treat the ORDER BY term as an ordinary expression */
    pItem->iCol = 0;
    if( sqlite3ResolveExprNames(pNC, pE) ){
      return 1;
    }
  }
  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
}

/*
** Resolve names in the SELECT statement p and all of its descendents.
*/
static int resolveSelectStep(Walker *pWalker, Select *p){
  NameContext *pOuterNC;  /* Context that contains this SELECT */
  NameContext sNC;        /* Name context of this SELECT */
  int isCompound;         /* True if p is a compound select */
  int nCompound;          /* Number of compound terms processed so far */
  Parse *pParse;          /* Parsing context */
  ExprList *pEList;       /* Result set expression list */
  int i;                  /* Loop counter */
  ExprList *pGroupBy;     /* The GROUP BY clause */
  Select *pLeftmost;      /* Left-most of SELECT of a compound */
  sqlite3 *db;            /* Database connection */
  

  assert( p!=0 );
  if( p->selFlags & SF_Resolved ){
    return WRC_Prune;
  }
  pOuterNC = pWalker->u.pNC;
  pParse = pWalker->pParse;
  db = pParse->db;

  /* Normally sqlite3SelectExpand() will be called first and will have
  ** already expanded this SELECT.  However, if this is a subquery within
  ** an expression, sqlite3ResolveExprNames() will be called without a
  ** prior call to sqlite3SelectExpand().  When that happens, let
  ** sqlite3SelectPrep() do all of the processing for this SELECT.
  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  ** this routine in the correct order.
  */
  if( (p->selFlags & SF_Expanded)==0 ){
    sqlite3SelectPrep(pParse, p, pOuterNC);
    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  }

  isCompound = p->pPrior!=0;
  nCompound = 0;
  pLeftmost = p;
  while( p ){
    assert( (p->selFlags & SF_Expanded)!=0 );
    assert( (p->selFlags & SF_Resolved)==0 );
    p->selFlags |= SF_Resolved;

    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
    ** are not allowed to refer to any names, so pass an empty NameContext.
    */
    memset(&sNC, 0, sizeof(sNC));
    sNC.pParse = pParse;
    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
      return WRC_Abort;
    }
  
    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
    ** resolve the result-set expression list.
    */
    sNC.allowAgg = 1;
    sNC.pSrcList = p->pSrc;
    sNC.pNext = pOuterNC;
  
    /* Resolve names in the result set. */
    pEList = p->pEList;
    assert( pEList!=0 );
    for(i=0; i<pEList->nExpr; i++){
      Expr *pX = pEList->a[i].pExpr;
      if( sqlite3ResolveExprNames(&sNC, pX) ){
        return WRC_Abort;
      }
    }
  
    /* Recursively resolve names in all subqueries
    */
    for(i=0; i<p->pSrc->nSrc; i++){
      struct SrcList_item *pItem = &p->pSrc->a[i];
      if( pItem->pSelect ){
        const char *zSavedContext = pParse->zAuthContext;
        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
        pParse->zAuthContext = zSavedContext;
        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
      }
    }
  
    /* If there are no aggregate functions in the result-set, and no GROUP BY 
    ** expression, do not allow aggregates in any of the other expressions.
    */
    assert( (p->selFlags & SF_Aggregate)==0 );
    pGroupBy = p->pGroupBy;
    if( pGroupBy || sNC.hasAgg ){
      p->selFlags |= SF_Aggregate;
    }else{
      sNC.allowAgg = 0;
    }
  
    /* If a HAVING clause is present, then there must be a GROUP BY clause.
    */
    if( p->pHaving && !pGroupBy ){
      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
      return WRC_Abort;
    }
  
    /* Add the expression list to the name-context before parsing the
    ** other expressions in the SELECT statement. This is so that
    ** expressions in the WHERE clause (etc.) can refer to expressions by
    ** aliases in the result set.
    **
    ** Minor point: If this is the case, then the expression will be
    ** re-evaluated for each reference to it.
    */
    sNC.pEList = p->pEList;
    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
       sqlite3ResolveExprNames(&sNC, p->pHaving)
    ){
      return WRC_Abort;
    }

    /* The ORDER BY and GROUP BY clauses may not refer to terms in
    ** outer queries 
    */
    sNC.pNext = 0;
    sNC.allowAgg = 1;

    /* Process the ORDER BY clause for singleton SELECT statements.
    ** The ORDER BY clause for compounds SELECT statements is handled
    ** below, after all of the result-sets for all of the elements of
    ** the compound have been resolved.
    */
    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
      return WRC_Abort;
    }
    if( db->mallocFailed ){
      return WRC_Abort;
    }
  
    /* Resolve the GROUP BY clause.  At the same time, make sure 
    ** the GROUP BY clause does not contain aggregate functions.
    */
    if( pGroupBy ){
      struct ExprList_item *pItem;
    
      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
        return WRC_Abort;
      }
      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
              "the GROUP BY clause");
          return WRC_Abort;
        }
      }
    }

    /* Advance to the next term of the compound
    */
    p = p->pPrior;
    nCompound++;
  }

  /* Resolve the ORDER BY on a compound SELECT after all terms of
  ** the compound have been resolved.
  */
  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
    return WRC_Abort;
  }

  return WRC_Prune;
}

/*
** This routine walks an expression tree and resolves references to
** table columns and result-set columns.  At the same time, do error
** checking on function usage and set a flag if any aggregate functions
** are seen.
**
** To resolve table columns references we look for nodes (or subtrees) of the 
** form X.Y.Z or Y.Z or just Z where
**
**      X:   The name of a database.  Ex:  "main" or "temp" or
**           the symbolic name assigned to an ATTACH-ed database.
**
**      Y:   The name of a table in a FROM clause.  Or in a trigger
**           one of the special names "old" or "new".
**
**      Z:   The name of a column in table Y.
**
** The node at the root of the subtree is modified as follows:
**
**    Expr.op        Changed to TK_COLUMN
**    Expr.pTab      Points to the Table object for X.Y
**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
**    Expr.iTable    The VDBE cursor number for X.Y
**
**
** To resolve result-set references, look for expression nodes of the
** form Z (with no X and Y prefix) where the Z matches the right-hand
** size of an AS clause in the result-set of a SELECT.  The Z expression
** is replaced by a copy of the left-hand side of the result-set expression.
** Table-name and function resolution occurs on the substituted expression
** tree.  For example, in:
**
**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
**
** The "x" term of the order by is replaced by "a+b" to render:
**
**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
**
** Function calls are checked to make sure that the function is 
** defined and that the correct number of arguments are specified.
** If the function is an aggregate function, then the pNC->hasAgg is
** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
** If an expression contains aggregate functions then the EP_Agg
** property on the expression is set.
**
** An error message is left in pParse if anything is amiss.  The number
** if errors is returned.
*/
int sqlite3ResolveExprNames( 
  NameContext *pNC,       /* Namespace to resolve expressions in. */
  Expr *pExpr             /* The expression to be analyzed. */
){
  int savedHasAgg;
  Walker w;

  if( pExpr==0 ) return 0;
#if SQLITE_MAX_EXPR_DEPTH>0
  {
    Parse *pParse = pNC->pParse;
    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
      return 1;
    }
    pParse->nHeight += pExpr->nHeight;
  }
#endif
  savedHasAgg = pNC->hasAgg;
  pNC->hasAgg = 0;
  w.xExprCallback = resolveExprStep;
  w.xSelectCallback = resolveSelectStep;
  w.pParse = pNC->pParse;
  w.u.pNC = pNC;
  sqlite3WalkExpr(&w, pExpr);
#if SQLITE_MAX_EXPR_DEPTH>0
  pNC->pParse->nHeight -= pExpr->nHeight;
#endif
  if( pNC->nErr>0 || w.pParse->nErr>0 ){
    ExprSetProperty(pExpr, EP_Error);
  }
  if( pNC->hasAgg ){
    ExprSetProperty(pExpr, EP_Agg);
  }else if( savedHasAgg ){
    pNC->hasAgg = 1;
  }
  return ExprHasProperty(pExpr, EP_Error);
}


/*
** Resolve all names in all expressions of a SELECT and in all
** decendents of the SELECT, including compounds off of p->pPrior,
** subqueries in expressions, and subqueries used as FROM clause
** terms.
**
** See sqlite3ResolveExprNames() for a description of the kinds of
** transformations that occur.
**
** All SELECT statements should have been expanded using
** sqlite3SelectExpand() prior to invoking this routine.
*/
void sqlite3ResolveSelectNames(
  Parse *pParse,         /* The parser context */
  Select *p,             /* The SELECT statement being coded. */
  NameContext *pOuterNC  /* Name context for parent SELECT statement */
){
  Walker w;

  assert( p!=0 );
  w.xExprCallback = resolveExprStep;
  w.xSelectCallback = resolveSelectStep;
  w.pParse = pParse;
  w.u.pNC = pOuterNC;
  sqlite3WalkSelect(&w, p);
}

Added src/rowset.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*
** 2008 December 3
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This module implements an object we call a "RowSet".
**
** The RowSet object is a collection of rowids.  Rowids
** are inserted into the RowSet in an arbitrary order.  Inserts
** can be intermixed with tests to see if a given rowid has been
** previously inserted into the RowSet.
**
** After all inserts are finished, it is possible to extract the
** elements of the RowSet in sorted order.  Once this extraction
** process has started, no new elements may be inserted.
**
** Hence, the primitive operations for a RowSet are:
**
**    CREATE
**    INSERT
**    TEST
**    SMALLEST
**    DESTROY
**
** The CREATE and DESTROY primitives are the constructor and destructor,
** obviously.  The INSERT primitive adds a new element to the RowSet.
** TEST checks to see if an element is already in the RowSet.  SMALLEST
** extracts the least value from the RowSet.
**
** The INSERT primitive might allocate additional memory.  Memory is
** allocated in chunks so most INSERTs do no allocation.  There is an 
** upper bound on the size of allocated memory.  No memory is freed
** until DESTROY.
**
** The TEST primitive includes a "batch" number.  The TEST primitive
** will only see elements that were inserted before the last change
** in the batch number.  In other words, if an INSERT occurs between
** two TESTs where the TESTs have the same batch nubmer, then the
** value added by the INSERT will not be visible to the second TEST.
** The initial batch number is zero, so if the very first TEST contains
** a non-zero batch number, it will see all prior INSERTs.
**
** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
** that is attempted.
**
** The cost of an INSERT is roughly constant.  (Sometime new memory
** has to be allocated on an INSERT.)  The cost of a TEST with a new
** batch number is O(NlogN) where N is the number of elements in the RowSet.
** The cost of a TEST using the same batch number is O(logN).  The cost
** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
** primitives are constant time.  The cost of DESTROY is O(N).
**
** There is an added cost of O(N) when switching between TEST and
** SMALLEST primitives.
**
** $Id: rowset.c,v 1.7 2009/05/22 01:00:13 drh Exp $
*/
#include "sqliteInt.h"


/*
** Target size for allocation chunks.
*/
#define ROWSET_ALLOCATION_SIZE 1024

/*
** The number of rowset entries per allocation chunk.
*/
#define ROWSET_ENTRY_PER_CHUNK  \
                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))

/*
** Each entry in a RowSet is an instance of the following object.
*/
struct RowSetEntry {            
  i64 v;                        /* ROWID value for this entry */
  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
};

/*
** RowSetEntry objects are allocated in large chunks (instances of the
** following structure) to reduce memory allocation overhead.  The
** chunks are kept on a linked list so that they can be deallocated
** when the RowSet is destroyed.
*/
struct RowSetChunk {
  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
};

/*
** A RowSet in an instance of the following structure.
**
** A typedef of this structure if found in sqliteInt.h.
*/
struct RowSet {
  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
  sqlite3 *db;                   /* The database connection */
  struct RowSetEntry *pEntry;    /* List of entries using pRight */
  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
  struct RowSetEntry *pFresh;    /* Source of new entry objects */
  struct RowSetEntry *pTree;     /* Binary tree of entries */
  u16 nFresh;                    /* Number of objects on pFresh */
  u8 isSorted;                   /* True if pEntry is sorted */
  u8 iBatch;                     /* Current insert batch */
};

/*
** Turn bulk memory into a RowSet object.  N bytes of memory
** are available at pSpace.  The db pointer is used as a memory context
** for any subsequent allocations that need to occur.
** Return a pointer to the new RowSet object.
**
** It must be the case that N is sufficient to make a Rowset.  If not
** an assertion fault occurs.
** 
** If N is larger than the minimum, use the surplus as an initial
** allocation of entries available to be filled.
*/
RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  RowSet *p;
  assert( N >= ROUND8(sizeof(*p)) );
  p = pSpace;
  p->pChunk = 0;
  p->db = db;
  p->pEntry = 0;
  p->pLast = 0;
  p->pTree = 0;
  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  p->isSorted = 1;
  p->iBatch = 0;
  return p;
}

/*
** Deallocate all chunks from a RowSet.  This frees all memory that
** the RowSet has allocated over its lifetime.  This routine is
** the destructor for the RowSet.
*/
void sqlite3RowSetClear(RowSet *p){
  struct RowSetChunk *pChunk, *pNextChunk;
  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
    pNextChunk = pChunk->pNextChunk;
    sqlite3DbFree(p->db, pChunk);
  }
  p->pChunk = 0;
  p->nFresh = 0;
  p->pEntry = 0;
  p->pLast = 0;
  p->pTree = 0;
  p->isSorted = 1;
}

/*
** Insert a new value into a RowSet.
**
** The mallocFailed flag of the database connection is set if a
** memory allocation fails.
*/
void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  struct RowSetEntry *pEntry;  /* The new entry */
  struct RowSetEntry *pLast;   /* The last prior entry */
  assert( p!=0 );
  if( p->nFresh==0 ){
    struct RowSetChunk *pNew;
    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
    if( pNew==0 ){
      return;
    }
    pNew->pNextChunk = p->pChunk;
    p->pChunk = pNew;
    p->pFresh = pNew->aEntry;
    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  }
  pEntry = p->pFresh++;
  p->nFresh--;
  pEntry->v = rowid;
  pEntry->pRight = 0;
  pLast = p->pLast;
  if( pLast ){
    if( p->isSorted && rowid<=pLast->v ){
      p->isSorted = 0;
    }
    pLast->pRight = pEntry;
  }else{
    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
    p->pEntry = pEntry;
  }
  p->pLast = pEntry;
}

/*
** Merge two lists of RowSetEntry objects.  Remove duplicates.
**
** The input lists are connected via pRight pointers and are 
** assumed to each already be in sorted order.
*/
static struct RowSetEntry *rowSetMerge(
  struct RowSetEntry *pA,    /* First sorted list to be merged */
  struct RowSetEntry *pB     /* Second sorted list to be merged */
){
  struct RowSetEntry head;
  struct RowSetEntry *pTail;

  pTail = &head;
  while( pA && pB ){
    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
    if( pA->v<pB->v ){
      pTail->pRight = pA;
      pA = pA->pRight;
      pTail = pTail->pRight;
    }else if( pB->v<pA->v ){
      pTail->pRight = pB;
      pB = pB->pRight;
      pTail = pTail->pRight;
    }else{
      pA = pA->pRight;
    }
  }
  if( pA ){
    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
    pTail->pRight = pA;
  }else{
    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
    pTail->pRight = pB;
  }
  return head.pRight;
}

/*
** Sort all elements on the pEntry list of the RowSet into ascending order.
*/ 
static void rowSetSort(RowSet *p){
  unsigned int i;
  struct RowSetEntry *pEntry;
  struct RowSetEntry *aBucket[40];

  assert( p->isSorted==0 );
  memset(aBucket, 0, sizeof(aBucket));
  while( p->pEntry ){
    pEntry = p->pEntry;
    p->pEntry = pEntry->pRight;
    pEntry->pRight = 0;
    for(i=0; aBucket[i]; i++){
      pEntry = rowSetMerge(aBucket[i], pEntry);
      aBucket[i] = 0;
    }
    aBucket[i] = pEntry;
  }
  pEntry = 0;
  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
    pEntry = rowSetMerge(pEntry, aBucket[i]);
  }
  p->pEntry = pEntry;
  p->pLast = 0;
  p->isSorted = 1;
}


/*
** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
** Convert this tree into a linked list connected by the pRight pointers
** and return pointers to the first and last elements of the new list.
*/
static void rowSetTreeToList(
  struct RowSetEntry *pIn,         /* Root of the input tree */
  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
  struct RowSetEntry **ppLast      /* Write tail of the output list here */
){
  assert( pIn!=0 );
  if( pIn->pLeft ){
    struct RowSetEntry *p;
    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
    p->pRight = pIn;
  }else{
    *ppFirst = pIn;
  }
  if( pIn->pRight ){
    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  }else{
    *ppLast = pIn;
  }
  assert( (*ppLast)->pRight==0 );
}


/*
** Convert a sorted list of elements (connected by pRight) into a binary
** tree with depth of iDepth.  A depth of 1 means the tree contains a single
** node taken from the head of *ppList.  A depth of 2 means a tree with
** three nodes.  And so forth.
**
** Use as many entries from the input list as required and update the
** *ppList to point to the unused elements of the list.  If the input
** list contains too few elements, then construct an incomplete tree
** and leave *ppList set to NULL.
**
** Return a pointer to the root of the constructed binary tree.
*/
static struct RowSetEntry *rowSetNDeepTree(
  struct RowSetEntry **ppList,
  int iDepth
){
  struct RowSetEntry *p;         /* Root of the new tree */
  struct RowSetEntry *pLeft;     /* Left subtree */
  if( *ppList==0 ){
    return 0;
  }
  if( iDepth==1 ){
    p = *ppList;
    *ppList = p->pRight;
    p->pLeft = p->pRight = 0;
    return p;
  }
  pLeft = rowSetNDeepTree(ppList, iDepth-1);
  p = *ppList;
  if( p==0 ){
    return pLeft;
  }
  p->pLeft = pLeft;
  *ppList = p->pRight;
  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  return p;
}

/*
** Convert a sorted list of elements into a binary tree. Make the tree
** as deep as it needs to be in order to contain the entire list.
*/
static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  int iDepth;           /* Depth of the tree so far */
  struct RowSetEntry *p;       /* Current tree root */
  struct RowSetEntry *pLeft;   /* Left subtree */

  assert( pList!=0 );
  p = pList;
  pList = p->pRight;
  p->pLeft = p->pRight = 0;
  for(iDepth=1; pList; iDepth++){
    pLeft = p;
    p = pList;
    pList = p->pRight;
    p->pLeft = pLeft;
    p->pRight = rowSetNDeepTree(&pList, iDepth);
  }
  return p;
}

/*
** Convert the list in p->pEntry into a sorted list if it is not
** sorted already.  If there is a binary tree on p->pTree, then
** convert it into a list too and merge it into the p->pEntry list.
*/
static void rowSetToList(RowSet *p){
  if( !p->isSorted ){
    rowSetSort(p);
  }
  if( p->pTree ){
    struct RowSetEntry *pHead, *pTail;
    rowSetTreeToList(p->pTree, &pHead, &pTail);
    p->pTree = 0;
    p->pEntry = rowSetMerge(p->pEntry, pHead);
  }
}

/*
** Extract the smallest element from the RowSet.
** Write the element into *pRowid.  Return 1 on success.  Return
** 0 if the RowSet is already empty.
**
** After this routine has been called, the sqlite3RowSetInsert()
** routine may not be called again.  
*/
int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  rowSetToList(p);
  if( p->pEntry ){
    *pRowid = p->pEntry->v;
    p->pEntry = p->pEntry->pRight;
    if( p->pEntry==0 ){
      sqlite3RowSetClear(p);
    }
    return 1;
  }else{
    return 0;
  }
}

/*
** Check to see if element iRowid was inserted into the the rowset as
** part of any insert batch prior to iBatch.  Return 1 or 0.
*/
int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  struct RowSetEntry *p;
  if( iBatch!=pRowSet->iBatch ){
    if( pRowSet->pEntry ){
      rowSetToList(pRowSet);
      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
      pRowSet->pEntry = 0;
      pRowSet->pLast = 0;
    }
    pRowSet->iBatch = iBatch;
  }
  p = pRowSet->pTree;
  while( p ){
    if( p->v<iRowid ){
      p = p->pRight;
    }else if( p->v>iRowid ){
      p = p->pLeft;
    }else{
      return 1;
    }
  }
  return 0;
}

Added src/select.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle SELECT statements in SQLite.
**
** $Id: select.c,v 1.526 2009/08/01 15:09:58 drh Exp $
*/
#include "sqliteInt.h"


/*
** Delete all the content of a Select structure but do not deallocate
** the select structure itself.
*/
static void clearSelect(sqlite3 *db, Select *p){
  sqlite3ExprListDelete(db, p->pEList);
  sqlite3SrcListDelete(db, p->pSrc);
  sqlite3ExprDelete(db, p->pWhere);
  sqlite3ExprListDelete(db, p->pGroupBy);
  sqlite3ExprDelete(db, p->pHaving);
  sqlite3ExprListDelete(db, p->pOrderBy);
  sqlite3SelectDelete(db, p->pPrior);
  sqlite3ExprDelete(db, p->pLimit);
  sqlite3ExprDelete(db, p->pOffset);
}

/*
** Initialize a SelectDest structure.
*/
void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  pDest->eDest = (u8)eDest;
  pDest->iParm = iParm;
  pDest->affinity = 0;
  pDest->iMem = 0;
  pDest->nMem = 0;
}


/*
** Allocate a new Select structure and return a pointer to that
** structure.
*/
Select *sqlite3SelectNew(
  Parse *pParse,        /* Parsing context */
  ExprList *pEList,     /* which columns to include in the result */
  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
  Expr *pWhere,         /* the WHERE clause */
  ExprList *pGroupBy,   /* the GROUP BY clause */
  Expr *pHaving,        /* the HAVING clause */
  ExprList *pOrderBy,   /* the ORDER BY clause */
  int isDistinct,       /* true if the DISTINCT keyword is present */
  Expr *pLimit,         /* LIMIT value.  NULL means not used */
  Expr *pOffset         /* OFFSET value.  NULL means no offset */
){
  Select *pNew;
  Select standin;
  sqlite3 *db = pParse->db;
  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  if( pNew==0 ){
    pNew = &standin;
    memset(pNew, 0, sizeof(*pNew));
  }
  if( pEList==0 ){
    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  }
  pNew->pEList = pEList;
  pNew->pSrc = pSrc;
  pNew->pWhere = pWhere;
  pNew->pGroupBy = pGroupBy;
  pNew->pHaving = pHaving;
  pNew->pOrderBy = pOrderBy;
  pNew->selFlags = isDistinct ? SF_Distinct : 0;
  pNew->op = TK_SELECT;
  pNew->pLimit = pLimit;
  pNew->pOffset = pOffset;
  assert( pOffset==0 || pLimit!=0 );
  pNew->addrOpenEphm[0] = -1;
  pNew->addrOpenEphm[1] = -1;
  pNew->addrOpenEphm[2] = -1;
  if( db->mallocFailed ) {
    clearSelect(db, pNew);
    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
    pNew = 0;
  }
  return pNew;
}

/*
** Delete the given Select structure and all of its substructures.
*/
void sqlite3SelectDelete(sqlite3 *db, Select *p){
  if( p ){
    clearSelect(db, p);
    sqlite3DbFree(db, p);
  }
}

/*
** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
** type of join.  Return an integer constant that expresses that type
** in terms of the following bit values:
**
**     JT_INNER
**     JT_CROSS
**     JT_OUTER
**     JT_NATURAL
**     JT_LEFT
**     JT_RIGHT
**
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
**
** If an illegal or unsupported join type is seen, then still return
** a join type, but put an error in the pParse structure.
*/
int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  int jointype = 0;
  Token *apAll[3];
  Token *p;
                             /*   0123456789 123456789 123456789 123 */
  static const char zKeyText[] = "naturaleftouterightfullinnercross";
  static const struct {
    u8 i;        /* Beginning of keyword text in zKeyText[] */
    u8 nChar;    /* Length of the keyword in characters */
    u8 code;     /* Join type mask */
  } aKeyword[] = {
    /* natural */ { 0,  7, JT_NATURAL                },
    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
    /* outer   */ { 10, 5, JT_OUTER                  },
    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
    /* inner   */ { 23, 5, JT_INNER                  },
    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
  };
  int i, j;
  apAll[0] = pA;
  apAll[1] = pB;
  apAll[2] = pC;
  for(i=0; i<3 && apAll[i]; i++){
    p = apAll[i];
    for(j=0; j<ArraySize(aKeyword); j++){
      if( p->n==aKeyword[j].nChar 
          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
        jointype |= aKeyword[j].code;
        break;
      }
    }
    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
    if( j>=ArraySize(aKeyword) ){
      jointype |= JT_ERROR;
      break;
    }
  }
  if(
     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
     (jointype & JT_ERROR)!=0
  ){
    const char *zSp = " ";
    assert( pB!=0 );
    if( pC==0 ){ zSp++; }
    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
       "%T %T%s%T", pA, pB, zSp, pC);
    jointype = JT_INNER;
  }else if( (jointype & JT_OUTER)!=0 
         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
    sqlite3ErrorMsg(pParse, 
      "RIGHT and FULL OUTER JOINs are not currently supported");
    jointype = JT_INNER;
  }
  return jointype;
}

/*
** Return the index of a column in a table.  Return -1 if the column
** is not contained in the table.
*/
static int columnIndex(Table *pTab, const char *zCol){
  int i;
  for(i=0; i<pTab->nCol; i++){
    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  }
  return -1;
}

/*
** This function is used to add terms implied by JOIN syntax to the
** WHERE clause expression of a SELECT statement. The new term, which
** is ANDed with the existing WHERE clause, is of the form:
**
**    (tab1.col1 = tab2.col2)
**
** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
** column iColRight of tab2.
*/
static void addWhereTerm(
  Parse *pParse,                  /* Parsing context */
  SrcList *pSrc,                  /* List of tables in FROM clause */
  int iSrc,                       /* Index of first table to join in pSrc */
  int iColLeft,                   /* Index of column in first table */
  int iColRight,                  /* Index of column in second table */
  int isOuterJoin,                /* True if this is an OUTER join */
  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
){
  sqlite3 *db = pParse->db;
  Expr *pE1;
  Expr *pE2;
  Expr *pEq;

  assert( pSrc->nSrc>(iSrc+1) );
  assert( pSrc->a[iSrc].pTab );
  assert( pSrc->a[iSrc+1].pTab );

  pE1 = sqlite3CreateColumnExpr(db, pSrc, iSrc, iColLeft);
  pE2 = sqlite3CreateColumnExpr(db, pSrc, iSrc+1, iColRight);

  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  if( pEq && isOuterJoin ){
    ExprSetProperty(pEq, EP_FromJoin);
    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
    ExprSetIrreducible(pEq);
    pEq->iRightJoinTable = (i16)pE2->iTable;
  }
  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
}

/*
** Set the EP_FromJoin property on all terms of the given expression.
** And set the Expr.iRightJoinTable to iTable for every term in the
** expression.
**
** The EP_FromJoin property is used on terms of an expression to tell
** the LEFT OUTER JOIN processing logic that this term is part of the
** join restriction specified in the ON or USING clause and not a part
** of the more general WHERE clause.  These terms are moved over to the
** WHERE clause during join processing but we need to remember that they
** originated in the ON or USING clause.
**
** The Expr.iRightJoinTable tells the WHERE clause processing that the
** expression depends on table iRightJoinTable even if that table is not
** explicitly mentioned in the expression.  That information is needed
** for cases like this:
**
**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
**
** The where clause needs to defer the handling of the t1.x=5
** term until after the t2 loop of the join.  In that way, a
** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
** defer the handling of t1.x=5, it will be processed immediately
** after the t1 loop and rows with t1.x!=5 will never appear in
** the output, which is incorrect.
*/
static void setJoinExpr(Expr *p, int iTable){
  while( p ){
    ExprSetProperty(p, EP_FromJoin);
    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
    ExprSetIrreducible(p);
    p->iRightJoinTable = (i16)iTable;
    setJoinExpr(p->pLeft, iTable);
    p = p->pRight;
  } 
}

/*
** This routine processes the join information for a SELECT statement.
** ON and USING clauses are converted into extra terms of the WHERE clause.
** NATURAL joins also create extra WHERE clause terms.
**
** The terms of a FROM clause are contained in the Select.pSrc structure.
** The left most table is the first entry in Select.pSrc.  The right-most
** table is the last entry.  The join operator is held in the entry to
** the left.  Thus entry 0 contains the join operator for the join between
** entries 0 and 1.  Any ON or USING clauses associated with the join are
** also attached to the left entry.
**
** This routine returns the number of errors encountered.
*/
static int sqliteProcessJoin(Parse *pParse, Select *p){
  SrcList *pSrc;                  /* All tables in the FROM clause */
  int i, j;                       /* Loop counters */
  struct SrcList_item *pLeft;     /* Left table being joined */
  struct SrcList_item *pRight;    /* Right table being joined */

  pSrc = p->pSrc;
  pLeft = &pSrc->a[0];
  pRight = &pLeft[1];
  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
    Table *pLeftTab = pLeft->pTab;
    Table *pRightTab = pRight->pTab;
    int isOuter;

    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
    isOuter = (pRight->jointype & JT_OUTER)!=0;

    /* When the NATURAL keyword is present, add WHERE clause terms for
    ** every column that the two tables have in common.
    */
    if( pRight->jointype & JT_NATURAL ){
      if( pRight->pOn || pRight->pUsing ){
        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
           "an ON or USING clause", 0);
        return 1;
      }
      for(j=0; j<pLeftTab->nCol; j++){
        char *zName = pLeftTab->aCol[j].zName;
        int iRightCol = columnIndex(pRightTab, zName);
        if( iRightCol>=0 ){
          addWhereTerm(pParse, pSrc, i, j, iRightCol, isOuter, &p->pWhere);
        }
      }
    }

    /* Disallow both ON and USING clauses in the same join
    */
    if( pRight->pOn && pRight->pUsing ){
      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
        "clauses in the same join");
      return 1;
    }

    /* Add the ON clause to the end of the WHERE clause, connected by
    ** an AND operator.
    */
    if( pRight->pOn ){
      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
      pRight->pOn = 0;
    }

    /* Create extra terms on the WHERE clause for each column named
    ** in the USING clause.  Example: If the two tables to be joined are 
    ** A and B and the USING clause names X, Y, and Z, then add this
    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
    ** Report an error if any column mentioned in the USING clause is
    ** not contained in both tables to be joined.
    */
    if( pRight->pUsing ){
      IdList *pList = pRight->pUsing;
      for(j=0; j<pList->nId; j++){
        char *zName = pList->a[j].zName;
        int iLeftCol = columnIndex(pLeftTab, zName);
        int iRightCol = columnIndex(pRightTab, zName);
        if( iLeftCol<0 || iRightCol<0 ){
          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
            "not present in both tables", zName);
          return 1;
        }
        addWhereTerm(pParse, pSrc, i, iLeftCol, iRightCol, isOuter, &p->pWhere);
      }
    }
  }
  return 0;
}

/*
** Insert code into "v" that will push the record on the top of the
** stack into the sorter.
*/
static void pushOntoSorter(
  Parse *pParse,         /* Parser context */
  ExprList *pOrderBy,    /* The ORDER BY clause */
  Select *pSelect,       /* The whole SELECT statement */
  int regData            /* Register holding data to be sorted */
){
  Vdbe *v = pParse->pVdbe;
  int nExpr = pOrderBy->nExpr;
  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  int regRecord = sqlite3GetTempReg(pParse);
  sqlite3ExprCacheClear(pParse);
  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
  sqlite3ReleaseTempReg(pParse, regRecord);
  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  if( pSelect->iLimit ){
    int addr1, addr2;
    int iLimit;
    if( pSelect->iOffset ){
      iLimit = pSelect->iOffset+1;
    }else{
      iLimit = pSelect->iLimit;
    }
    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
    sqlite3VdbeJumpHere(v, addr1);
    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
    sqlite3VdbeJumpHere(v, addr2);
    pSelect->iLimit = 0;
  }
}

/*
** Add code to implement the OFFSET
*/
static void codeOffset(
  Vdbe *v,          /* Generate code into this VM */
  Select *p,        /* The SELECT statement being coded */
  int iContinue     /* Jump here to skip the current record */
){
  if( p->iOffset && iContinue!=0 ){
    int addr;
    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
    VdbeComment((v, "skip OFFSET records"));
    sqlite3VdbeJumpHere(v, addr);
  }
}

/*
** Add code that will check to make sure the N registers starting at iMem
** form a distinct entry.  iTab is a sorting index that holds previously
** seen combinations of the N values.  A new entry is made in iTab
** if the current N values are new.
**
** A jump to addrRepeat is made and the N+1 values are popped from the
** stack if the top N elements are not distinct.
*/
static void codeDistinct(
  Parse *pParse,     /* Parsing and code generating context */
  int iTab,          /* A sorting index used to test for distinctness */
  int addrRepeat,    /* Jump to here if not distinct */
  int N,             /* Number of elements */
  int iMem           /* First element */
){
  Vdbe *v;
  int r1;

  v = pParse->pVdbe;
  r1 = sqlite3GetTempReg(pParse);
  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  sqlite3ReleaseTempReg(pParse, r1);
}

/*
** Generate an error message when a SELECT is used within a subexpression
** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
** column.  We do this in a subroutine because the error occurs in multiple
** places.
*/
static int checkForMultiColumnSelectError(
  Parse *pParse,       /* Parse context. */
  SelectDest *pDest,   /* Destination of SELECT results */
  int nExpr            /* Number of result columns returned by SELECT */
){
  int eDest = pDest->eDest;
  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
    sqlite3ErrorMsg(pParse, "only a single result allowed for "
       "a SELECT that is part of an expression");
    return 1;
  }else{
    return 0;
  }
}

/*
** This routine generates the code for the inside of the inner loop
** of a SELECT.
**
** If srcTab and nColumn are both zero, then the pEList expressions
** are evaluated in order to get the data for this row.  If nColumn>0
** then data is pulled from srcTab and pEList is used only to get the
** datatypes for each column.
*/
static void selectInnerLoop(
  Parse *pParse,          /* The parser context */
  Select *p,              /* The complete select statement being coded */
  ExprList *pEList,       /* List of values being extracted */
  int srcTab,             /* Pull data from this table */
  int nColumn,            /* Number of columns in the source table */
  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
  int distinct,           /* If >=0, make sure results are distinct */
  SelectDest *pDest,      /* How to dispose of the results */
  int iContinue,          /* Jump here to continue with next row */
  int iBreak              /* Jump here to break out of the inner loop */
){
  Vdbe *v = pParse->pVdbe;
  int i;
  int hasDistinct;        /* True if the DISTINCT keyword is present */
  int regResult;              /* Start of memory holding result set */
  int eDest = pDest->eDest;   /* How to dispose of results */
  int iParm = pDest->iParm;   /* First argument to disposal method */
  int nResultCol;             /* Number of result columns */

  assert( v );
  if( NEVER(v==0) ) return;
  assert( pEList!=0 );
  hasDistinct = distinct>=0;
  if( pOrderBy==0 && !hasDistinct ){
    codeOffset(v, p, iContinue);
  }

  /* Pull the requested columns.
  */
  if( nColumn>0 ){
    nResultCol = nColumn;
  }else{
    nResultCol = pEList->nExpr;
  }
  if( pDest->iMem==0 ){
    pDest->iMem = pParse->nMem+1;
    pDest->nMem = nResultCol;
    pParse->nMem += nResultCol;
  }else{ 
    assert( pDest->nMem==nResultCol );
  }
  regResult = pDest->iMem;
  if( nColumn>0 ){
    for(i=0; i<nColumn; i++){
      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
    }
  }else if( eDest!=SRT_Exists ){
    /* If the destination is an EXISTS(...) expression, the actual
    ** values returned by the SELECT are not required.
    */
    sqlite3ExprCacheClear(pParse);
    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  }
  nColumn = nResultCol;

  /* If the DISTINCT keyword was present on the SELECT statement
  ** and this row has been seen before, then do not make this row
  ** part of the result.
  */
  if( hasDistinct ){
    assert( pEList!=0 );
    assert( pEList->nExpr==nColumn );
    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
    if( pOrderBy==0 ){
      codeOffset(v, p, iContinue);
    }
  }

  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
    return;
  }

  switch( eDest ){
    /* In this mode, write each query result to the key of the temporary
    ** table iParm.
    */
#ifndef SQLITE_OMIT_COMPOUND_SELECT
    case SRT_Union: {
      int r1;
      r1 = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
      sqlite3ReleaseTempReg(pParse, r1);
      break;
    }

    /* Construct a record from the query result, but instead of
    ** saving that record, use it as a key to delete elements from
    ** the temporary table iParm.
    */
    case SRT_Except: {
      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
      break;
    }
#endif

    /* Store the result as data using a unique key.
    */
    case SRT_Table:
    case SRT_EphemTab: {
      int r1 = sqlite3GetTempReg(pParse);
      testcase( eDest==SRT_Table );
      testcase( eDest==SRT_EphemTab );
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
      if( pOrderBy ){
        pushOntoSorter(pParse, pOrderBy, p, r1);
      }else{
        int r2 = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
        sqlite3ReleaseTempReg(pParse, r2);
      }
      sqlite3ReleaseTempReg(pParse, r1);
      break;
    }

#ifndef SQLITE_OMIT_SUBQUERY
    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
    ** then there should be a single item on the stack.  Write this
    ** item into the set table with bogus data.
    */
    case SRT_Set: {
      assert( nColumn==1 );
      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
      if( pOrderBy ){
        /* At first glance you would think we could optimize out the
        ** ORDER BY in this case since the order of entries in the set
        ** does not matter.  But there might be a LIMIT clause, in which
        ** case the order does matter */
        pushOntoSorter(pParse, pOrderBy, p, regResult);
      }else{
        int r1 = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
        sqlite3ReleaseTempReg(pParse, r1);
      }
      break;
    }

    /* If any row exist in the result set, record that fact and abort.
    */
    case SRT_Exists: {
      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
      /* The LIMIT clause will terminate the loop for us */
      break;
    }

    /* If this is a scalar select that is part of an expression, then
    ** store the results in the appropriate memory cell and break out
    ** of the scan loop.
    */
    case SRT_Mem: {
      assert( nColumn==1 );
      if( pOrderBy ){
        pushOntoSorter(pParse, pOrderBy, p, regResult);
      }else{
        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
        /* The LIMIT clause will jump out of the loop for us */
      }
      break;
    }
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */

    /* Send the data to the callback function or to a subroutine.  In the
    ** case of a subroutine, the subroutine itself is responsible for
    ** popping the data from the stack.
    */
    case SRT_Coroutine:
    case SRT_Output: {
      testcase( eDest==SRT_Coroutine );
      testcase( eDest==SRT_Output );
      if( pOrderBy ){
        int r1 = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
        pushOntoSorter(pParse, pOrderBy, p, r1);
        sqlite3ReleaseTempReg(pParse, r1);
      }else if( eDest==SRT_Coroutine ){
        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
      }else{
        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
      }
      break;
    }

#if !defined(SQLITE_OMIT_TRIGGER)
    /* Discard the results.  This is used for SELECT statements inside
    ** the body of a TRIGGER.  The purpose of such selects is to call
    ** user-defined functions that have side effects.  We do not care
    ** about the actual results of the select.
    */
    default: {
      assert( eDest==SRT_Discard );
      break;
    }
#endif
  }

  /* Jump to the end of the loop if the LIMIT is reached.
  */
  if( p->iLimit ){
    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
                            ** pushOntoSorter() would have cleared p->iLimit */
    sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
    sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  }
}

/*
** Given an expression list, generate a KeyInfo structure that records
** the collating sequence for each expression in that expression list.
**
** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
** KeyInfo structure is appropriate for initializing a virtual index to
** implement that clause.  If the ExprList is the result set of a SELECT
** then the KeyInfo structure is appropriate for initializing a virtual
** index to implement a DISTINCT test.
**
** Space to hold the KeyInfo structure is obtain from malloc.  The calling
** function is responsible for seeing that this structure is eventually
** freed.  Add the KeyInfo structure to the P4 field of an opcode using
** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
*/
static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  sqlite3 *db = pParse->db;
  int nExpr;
  KeyInfo *pInfo;
  struct ExprList_item *pItem;
  int i;

  nExpr = pList->nExpr;
  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  if( pInfo ){
    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
    pInfo->nField = (u16)nExpr;
    pInfo->enc = ENC(db);
    pInfo->db = db;
    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
      CollSeq *pColl;
      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
      if( !pColl ){
        pColl = db->pDfltColl;
      }
      pInfo->aColl[i] = pColl;
      pInfo->aSortOrder[i] = pItem->sortOrder;
    }
  }
  return pInfo;
}


/*
** If the inner loop was generated using a non-null pOrderBy argument,
** then the results were placed in a sorter.  After the loop is terminated
** we need to run the sorter and output the results.  The following
** routine generates the code needed to do that.
*/
static void generateSortTail(
  Parse *pParse,    /* Parsing context */
  Select *p,        /* The SELECT statement */
  Vdbe *v,          /* Generate code into this VDBE */
  int nColumn,      /* Number of columns of data */
  SelectDest *pDest /* Write the sorted results here */
){
  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
  int addr;
  int iTab;
  int pseudoTab = 0;
  ExprList *pOrderBy = p->pOrderBy;

  int eDest = pDest->eDest;
  int iParm = pDest->iParm;

  int regRow;
  int regRowid;

  iTab = pOrderBy->iECursor;
  regRow = sqlite3GetTempReg(pParse);
  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
    pseudoTab = pParse->nTab++;
    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
    regRowid = 0;
  }else{
    regRowid = sqlite3GetTempReg(pParse);
  }
  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  codeOffset(v, p, addrContinue);
  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
  switch( eDest ){
    case SRT_Table:
    case SRT_EphemTab: {
      testcase( eDest==SRT_Table );
      testcase( eDest==SRT_EphemTab );
      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
      break;
    }
#ifndef SQLITE_OMIT_SUBQUERY
    case SRT_Set: {
      assert( nColumn==1 );
      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
      break;
    }
    case SRT_Mem: {
      assert( nColumn==1 );
      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
      /* The LIMIT clause will terminate the loop for us */
      break;
    }
#endif
    default: {
      int i;
      assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
      testcase( eDest==SRT_Output );
      testcase( eDest==SRT_Coroutine );
      for(i=0; i<nColumn; i++){
        assert( regRow!=pDest->iMem+i );
        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
        if( i==0 ){
          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
        }
      }
      if( eDest==SRT_Output ){
        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
      }else{
        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
      }
      break;
    }
  }
  sqlite3ReleaseTempReg(pParse, regRow);
  sqlite3ReleaseTempReg(pParse, regRowid);

  /* LIMIT has been implemented by the pushOntoSorter() routine.
  */
  assert( p->iLimit==0 );

  /* The bottom of the loop
  */
  sqlite3VdbeResolveLabel(v, addrContinue);
  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  sqlite3VdbeResolveLabel(v, addrBreak);
  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  }
}

/*
** Return a pointer to a string containing the 'declaration type' of the
** expression pExpr. The string may be treated as static by the caller.
**
** The declaration type is the exact datatype definition extracted from the
** original CREATE TABLE statement if the expression is a column. The
** declaration type for a ROWID field is INTEGER. Exactly when an expression
** is considered a column can be complex in the presence of subqueries. The
** result-set expression in all of the following SELECT statements is 
** considered a column by this function.
**
**   SELECT col FROM tbl;
**   SELECT (SELECT col FROM tbl;
**   SELECT (SELECT col FROM tbl);
**   SELECT abc FROM (SELECT col AS abc FROM tbl);
** 
** The declaration type for any expression other than a column is NULL.
*/
static const char *columnType(
  NameContext *pNC, 
  Expr *pExpr,
  const char **pzOriginDb,
  const char **pzOriginTab,
  const char **pzOriginCol
){
  char const *zType = 0;
  char const *zOriginDb = 0;
  char const *zOriginTab = 0;
  char const *zOriginCol = 0;
  int j;
  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;

  switch( pExpr->op ){
    case TK_AGG_COLUMN:
    case TK_COLUMN: {
      /* The expression is a column. Locate the table the column is being
      ** extracted from in NameContext.pSrcList. This table may be real
      ** database table or a subquery.
      */
      Table *pTab = 0;            /* Table structure column is extracted from */
      Select *pS = 0;             /* Select the column is extracted from */
      int iCol = pExpr->iColumn;  /* Index of column in pTab */
      testcase( pExpr->op==TK_AGG_COLUMN );
      testcase( pExpr->op==TK_COLUMN );
      while( pNC && !pTab ){
        SrcList *pTabList = pNC->pSrcList;
        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
        if( j<pTabList->nSrc ){
          pTab = pTabList->a[j].pTab;
          pS = pTabList->a[j].pSelect;
        }else{
          pNC = pNC->pNext;
        }
      }

      if( pTab==0 ){
        /* At one time, code such as "SELECT new.x" within a trigger would
        ** cause this condition to run.  Since then, we have restructured how
        ** trigger code is generated and so this condition is no longer 
        ** possible. However, it can still be true for statements like
        ** the following:
        **
        **   CREATE TABLE t1(col INTEGER);
        **   SELECT (SELECT t1.col) FROM FROM t1;
        **
        ** when columnType() is called on the expression "t1.col" in the 
        ** sub-select. In this case, set the column type to NULL, even
        ** though it should really be "INTEGER".
        **
        ** This is not a problem, as the column type of "t1.col" is never
        ** used. When columnType() is called on the expression 
        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
        ** branch below.  */
        break;
      }

      assert( pTab && pExpr->pTab==pTab );
      if( pS ){
        /* The "table" is actually a sub-select or a view in the FROM clause
        ** of the SELECT statement. Return the declaration type and origin
        ** data for the result-set column of the sub-select.
        */
        if( ALWAYS(iCol>=0 && iCol<pS->pEList->nExpr) ){
          /* If iCol is less than zero, then the expression requests the
          ** rowid of the sub-select or view. This expression is legal (see 
          ** test case misc2.2.2) - it always evaluates to NULL.
          */
          NameContext sNC;
          Expr *p = pS->pEList->a[iCol].pExpr;
          sNC.pSrcList = pS->pSrc;
          sNC.pNext = pNC;
          sNC.pParse = pNC->pParse;
          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
        }
      }else if( ALWAYS(pTab->pSchema) ){
        /* A real table */
        assert( !pS );
        if( iCol<0 ) iCol = pTab->iPKey;
        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
        if( iCol<0 ){
          zType = "INTEGER";
          zOriginCol = "rowid";
        }else{
          zType = pTab->aCol[iCol].zType;
          zOriginCol = pTab->aCol[iCol].zName;
        }
        zOriginTab = pTab->zName;
        if( pNC->pParse ){
          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
        }
      }
      break;
    }
#ifndef SQLITE_OMIT_SUBQUERY
    case TK_SELECT: {
      /* The expression is a sub-select. Return the declaration type and
      ** origin info for the single column in the result set of the SELECT
      ** statement.
      */
      NameContext sNC;
      Select *pS = pExpr->x.pSelect;
      Expr *p = pS->pEList->a[0].pExpr;
      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
      sNC.pSrcList = pS->pSrc;
      sNC.pNext = pNC;
      sNC.pParse = pNC->pParse;
      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
      break;
    }
#endif
  }
  
  if( pzOriginDb ){
    assert( pzOriginTab && pzOriginCol );
    *pzOriginDb = zOriginDb;
    *pzOriginTab = zOriginTab;
    *pzOriginCol = zOriginCol;
  }
  return zType;
}

/*
** Generate code that will tell the VDBE the declaration types of columns
** in the result set.
*/
static void generateColumnTypes(
  Parse *pParse,      /* Parser context */
  SrcList *pTabList,  /* List of tables */
  ExprList *pEList    /* Expressions defining the result set */
){
#ifndef SQLITE_OMIT_DECLTYPE
  Vdbe *v = pParse->pVdbe;
  int i;
  NameContext sNC;
  sNC.pSrcList = pTabList;
  sNC.pParse = pParse;
  for(i=0; i<pEList->nExpr; i++){
    Expr *p = pEList->a[i].pExpr;
    const char *zType;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
    const char *zOrigDb = 0;
    const char *zOrigTab = 0;
    const char *zOrigCol = 0;
    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);

    /* The vdbe must make its own copy of the column-type and other 
    ** column specific strings, in case the schema is reset before this
    ** virtual machine is deleted.
    */
    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
#else
    zType = columnType(&sNC, p, 0, 0, 0);
#endif
    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  }
#endif /* SQLITE_OMIT_DECLTYPE */
}

/*
** Generate code that will tell the VDBE the names of columns
** in the result set.  This information is used to provide the
** azCol[] values in the callback.
*/
static void generateColumnNames(
  Parse *pParse,      /* Parser context */
  SrcList *pTabList,  /* List of tables */
  ExprList *pEList    /* Expressions defining the result set */
){
  Vdbe *v = pParse->pVdbe;
  int i, j;
  sqlite3 *db = pParse->db;
  int fullNames, shortNames;

#ifndef SQLITE_OMIT_EXPLAIN
  /* If this is an EXPLAIN, skip this step */
  if( pParse->explain ){
    return;
  }
#endif

  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  pParse->colNamesSet = 1;
  fullNames = (db->flags & SQLITE_FullColNames)!=0;
  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  sqlite3VdbeSetNumCols(v, pEList->nExpr);
  for(i=0; i<pEList->nExpr; i++){
    Expr *p;
    p = pEList->a[i].pExpr;
    if( NEVER(p==0) ) continue;
    if( pEList->a[i].zName ){
      char *zName = pEList->a[i].zName;
      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
      Table *pTab;
      char *zCol;
      int iCol = p->iColumn;
      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
        if( pTabList->a[j].iCursor==p->iTable ) break;
      }
      assert( j<pTabList->nSrc );
      pTab = pTabList->a[j].pTab;
      if( iCol<0 ) iCol = pTab->iPKey;
      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
      if( iCol<0 ){
        zCol = "rowid";
      }else{
        zCol = pTab->aCol[iCol].zName;
      }
      if( !shortNames && !fullNames ){
        sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
      }else if( fullNames ){
        char *zName = 0;
        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
      }else{
        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
      }
    }else{
      sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
    }
  }
  generateColumnTypes(pParse, pTabList, pEList);
}

#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** Name of the connection operator, used for error messages.
*/
static const char *selectOpName(int id){
  char *z;
  switch( id ){
    case TK_ALL:       z = "UNION ALL";   break;
    case TK_INTERSECT: z = "INTERSECT";   break;
    case TK_EXCEPT:    z = "EXCEPT";      break;
    default:           z = "UNION";       break;
  }
  return z;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */

/*
** Given a an expression list (which is really the list of expressions
** that form the result set of a SELECT statement) compute appropriate
** column names for a table that would hold the expression list.
**
** All column names will be unique.
**
** Only the column names are computed.  Column.zType, Column.zColl,
** and other fields of Column are zeroed.
**
** Return SQLITE_OK on success.  If a memory allocation error occurs,
** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
*/
static int selectColumnsFromExprList(
  Parse *pParse,          /* Parsing context */
  ExprList *pEList,       /* Expr list from which to derive column names */
  int *pnCol,             /* Write the number of columns here */
  Column **paCol          /* Write the new column list here */
){
  sqlite3 *db = pParse->db;   /* Database connection */
  int i, j;                   /* Loop counters */
  int cnt;                    /* Index added to make the name unique */
  Column *aCol, *pCol;        /* For looping over result columns */
  int nCol;                   /* Number of columns in the result set */
  Expr *p;                    /* Expression for a single result column */
  char *zName;                /* Column name */
  int nName;                  /* Size of name in zName[] */

  *pnCol = nCol = pEList->nExpr;
  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  if( aCol==0 ) return SQLITE_NOMEM;
  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
    /* Get an appropriate name for the column
    */
    p = pEList->a[i].pExpr;
    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
    if( (zName = pEList->a[i].zName)!=0 ){
      /* If the column contains an "AS <name>" phrase, use <name> as the name */
      zName = sqlite3DbStrDup(db, zName);
    }else{
      Expr *pColExpr = p;  /* The expression that is the result column name */
      Table *pTab;         /* Table associated with this expression */
      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
        /* For columns use the column name name */
        int iCol = pColExpr->iColumn;
        pTab = pColExpr->pTab;
        if( iCol<0 ) iCol = pTab->iPKey;
        zName = sqlite3MPrintf(db, "%s",
                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
      }else if( pColExpr->op==TK_ID ){
        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
      }else{
        /* Use the original text of the column expression as its name */
        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
      }
    }
    if( db->mallocFailed ){
      sqlite3DbFree(db, zName);
      break;
    }

    /* Make sure the column name is unique.  If the name is not unique,
    ** append a integer to the name so that it becomes unique.
    */
    nName = sqlite3Strlen30(zName);
    for(j=cnt=0; j<i; j++){
      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
        char *zNewName;
        zName[nName] = 0;
        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
        sqlite3DbFree(db, zName);
        zName = zNewName;
        j = -1;
        if( zName==0 ) break;
      }
    }
    pCol->zName = zName;
  }
  if( db->mallocFailed ){
    for(j=0; j<i; j++){
      sqlite3DbFree(db, aCol[j].zName);
    }
    sqlite3DbFree(db, aCol);
    *paCol = 0;
    *pnCol = 0;
    return SQLITE_NOMEM;
  }
  return SQLITE_OK;
}

/*
** Add type and collation information to a column list based on
** a SELECT statement.
** 
** The column list presumably came from selectColumnNamesFromExprList().
** The column list has only names, not types or collations.  This
** routine goes through and adds the types and collations.
**
** This routine requires that all identifiers in the SELECT
** statement be resolved.
*/
static void selectAddColumnTypeAndCollation(
  Parse *pParse,        /* Parsing contexts */
  int nCol,             /* Number of columns */
  Column *aCol,         /* List of columns */
  Select *pSelect       /* SELECT used to determine types and collations */
){
  sqlite3 *db = pParse->db;
  NameContext sNC;
  Column *pCol;
  CollSeq *pColl;
  int i;
  Expr *p;
  struct ExprList_item *a;

  assert( pSelect!=0 );
  assert( (pSelect->selFlags & SF_Resolved)!=0 );
  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  if( db->mallocFailed ) return;
  memset(&sNC, 0, sizeof(sNC));
  sNC.pSrcList = pSelect->pSrc;
  a = pSelect->pEList->a;
  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
    p = a[i].pExpr;
    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
    pCol->affinity = sqlite3ExprAffinity(p);
    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
    pColl = sqlite3ExprCollSeq(pParse, p);
    if( pColl ){
      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
    }
  }
}

/*
** Given a SELECT statement, generate a Table structure that describes
** the result set of that SELECT.
*/
Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  Table *pTab;
  sqlite3 *db = pParse->db;
  int savedFlags;

  savedFlags = db->flags;
  db->flags &= ~SQLITE_FullColNames;
  db->flags |= SQLITE_ShortColNames;
  sqlite3SelectPrep(pParse, pSelect, 0);
  if( pParse->nErr ) return 0;
  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  db->flags = savedFlags;
  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  if( pTab==0 ){
    return 0;
  }
  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
  assert( db->lookaside.bEnabled==0 );
  pTab->dbMem = 0;
  pTab->nRef = 1;
  pTab->zName = 0;
  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  pTab->iPKey = -1;
  if( db->mallocFailed ){
    sqlite3DeleteTable(pTab);
    return 0;
  }
  return pTab;
}

/*
** Get a VDBE for the given parser context.  Create a new one if necessary.
** If an error occurs, return NULL and leave a message in pParse.
*/
Vdbe *sqlite3GetVdbe(Parse *pParse){
  Vdbe *v = pParse->pVdbe;
  if( v==0 ){
    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
#ifndef SQLITE_OMIT_TRACE
    if( v ){
      sqlite3VdbeAddOp0(v, OP_Trace);
    }
#endif
  }
  return v;
}


/*
** Compute the iLimit and iOffset fields of the SELECT based on the
** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
** that appear in the original SQL statement after the LIMIT and OFFSET
** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
** are the integer memory register numbers for counters used to compute 
** the limit and offset.  If there is no limit and/or offset, then 
** iLimit and iOffset are negative.
**
** This routine changes the values of iLimit and iOffset only if
** a limit or offset is defined by pLimit and pOffset.  iLimit and
** iOffset should have been preset to appropriate default values
** (usually but not always -1) prior to calling this routine.
** Only if pLimit!=0 or pOffset!=0 do the limit registers get
** redefined.  The UNION ALL operator uses this property to force
** the reuse of the same limit and offset registers across multiple
** SELECT statements.
*/
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  Vdbe *v = 0;
  int iLimit = 0;
  int iOffset;
  int addr1;
  if( p->iLimit ) return;

  /* 
  ** "LIMIT -1" always shows all rows.  There is some
  ** contraversy about what the correct behavior should be.
  ** The current implementation interprets "LIMIT 0" to mean
  ** no rows.
  */
  sqlite3ExprCacheClear(pParse);
  assert( p->pOffset==0 || p->pLimit!=0 );
  if( p->pLimit ){
    p->iLimit = iLimit = ++pParse->nMem;
    v = sqlite3GetVdbe(pParse);
    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
    sqlite3ExprCode(pParse, p->pLimit, iLimit);
    sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
    VdbeComment((v, "LIMIT counter"));
    sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
    if( p->pOffset ){
      p->iOffset = iOffset = ++pParse->nMem;
      pParse->nMem++;   /* Allocate an extra register for limit+offset */
      sqlite3ExprCode(pParse, p->pOffset, iOffset);
      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
      VdbeComment((v, "OFFSET counter"));
      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
      sqlite3VdbeJumpHere(v, addr1);
      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
      VdbeComment((v, "LIMIT+OFFSET"));
      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
      sqlite3VdbeJumpHere(v, addr1);
    }
  }
}

#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** Return the appropriate collating sequence for the iCol-th column of
** the result set for the compound-select statement "p".  Return NULL if
** the column has no default collating sequence.
**
** The collating sequence for the compound select is taken from the
** left-most term of the select that has a collating sequence.
*/
static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  CollSeq *pRet;
  if( p->pPrior ){
    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  }else{
    pRet = 0;
  }
  assert( iCol>=0 );
  if( pRet==0 && iCol<p->pEList->nExpr ){
    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  }
  return pRet;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */

/* Forward reference */
static int multiSelectOrderBy(
  Parse *pParse,        /* Parsing context */
  Select *p,            /* The right-most of SELECTs to be coded */
  SelectDest *pDest     /* What to do with query results */
);


#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** This routine is called to process a compound query form from
** two or more separate queries using UNION, UNION ALL, EXCEPT, or
** INTERSECT
**
** "p" points to the right-most of the two queries.  the query on the
** left is p->pPrior.  The left query could also be a compound query
** in which case this routine will be called recursively. 
**
** The results of the total query are to be written into a destination
** of type eDest with parameter iParm.
**
** Example 1:  Consider a three-way compound SQL statement.
**
**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
**
** This statement is parsed up as follows:
**
**     SELECT c FROM t3
**      |
**      `----->  SELECT b FROM t2
**                |
**                `------>  SELECT a FROM t1
**
** The arrows in the diagram above represent the Select.pPrior pointer.
** So if this routine is called with p equal to the t3 query, then
** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
**
** Notice that because of the way SQLite parses compound SELECTs, the
** individual selects always group from left to right.
*/
static int multiSelect(
  Parse *pParse,        /* Parsing context */
  Select *p,            /* The right-most of SELECTs to be coded */
  SelectDest *pDest     /* What to do with query results */
){
  int rc = SQLITE_OK;   /* Success code from a subroutine */
  Select *pPrior;       /* Another SELECT immediately to our left */
  Vdbe *v;              /* Generate code to this VDBE */
  SelectDest dest;      /* Alternative data destination */
  Select *pDelete = 0;  /* Chain of simple selects to delete */
  sqlite3 *db;          /* Database connection */

  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  */
  assert( p && p->pPrior );  /* Calling function guarantees this much */
  db = pParse->db;
  pPrior = p->pPrior;
  assert( pPrior->pRightmost!=pPrior );
  assert( pPrior->pRightmost==p->pRightmost );
  dest = *pDest;
  if( pPrior->pOrderBy ){
    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
      selectOpName(p->op));
    rc = 1;
    goto multi_select_end;
  }
  if( pPrior->pLimit ){
    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
      selectOpName(p->op));
    rc = 1;
    goto multi_select_end;
  }

  v = sqlite3GetVdbe(pParse);
  assert( v!=0 );  /* The VDBE already created by calling function */

  /* Create the destination temporary table if necessary
  */
  if( dest.eDest==SRT_EphemTab ){
    assert( p->pEList );
    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
    dest.eDest = SRT_Table;
  }

  /* Make sure all SELECTs in the statement have the same number of elements
  ** in their result sets.
  */
  assert( p->pEList && pPrior->pEList );
  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
      " do not have the same number of result columns", selectOpName(p->op));
    rc = 1;
    goto multi_select_end;
  }

  /* Compound SELECTs that have an ORDER BY clause are handled separately.
  */
  if( p->pOrderBy ){
    return multiSelectOrderBy(pParse, p, pDest);
  }

  /* Generate code for the left and right SELECT statements.
  */
  switch( p->op ){
    case TK_ALL: {
      int addr = 0;
      assert( !pPrior->pLimit );
      pPrior->pLimit = p->pLimit;
      pPrior->pOffset = p->pOffset;
      rc = sqlite3Select(pParse, pPrior, &dest);
      p->pLimit = 0;
      p->pOffset = 0;
      if( rc ){
        goto multi_select_end;
      }
      p->pPrior = 0;
      p->iLimit = pPrior->iLimit;
      p->iOffset = pPrior->iOffset;
      if( p->iLimit ){
        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
        VdbeComment((v, "Jump ahead if LIMIT reached"));
      }
      rc = sqlite3Select(pParse, p, &dest);
      testcase( rc!=SQLITE_OK );
      pDelete = p->pPrior;
      p->pPrior = pPrior;
      if( addr ){
        sqlite3VdbeJumpHere(v, addr);
      }
      break;
    }
    case TK_EXCEPT:
    case TK_UNION: {
      int unionTab;    /* Cursor number of the temporary table holding result */
      u8 op = 0;       /* One of the SRT_ operations to apply to self */
      int priorOp;     /* The SRT_ operation to apply to prior selects */
      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
      int addr;
      SelectDest uniondest;

      testcase( p->op==TK_EXCEPT );
      testcase( p->op==TK_UNION );
      priorOp = SRT_Union;
      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
        /* We can reuse a temporary table generated by a SELECT to our
        ** right.
        */
        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
                                     ** of a 3-way or more compound */
        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
        unionTab = dest.iParm;
      }else{
        /* We will need to create our own temporary table to hold the
        ** intermediate results.
        */
        unionTab = pParse->nTab++;
        assert( p->pOrderBy==0 );
        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
        assert( p->addrOpenEphm[0] == -1 );
        p->addrOpenEphm[0] = addr;
        p->pRightmost->selFlags |= SF_UsesEphemeral;
        assert( p->pEList );
      }

      /* Code the SELECT statements to our left
      */
      assert( !pPrior->pOrderBy );
      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
      rc = sqlite3Select(pParse, pPrior, &uniondest);
      if( rc ){
        goto multi_select_end;
      }

      /* Code the current SELECT statement
      */
      if( p->op==TK_EXCEPT ){
        op = SRT_Except;
      }else{
        assert( p->op==TK_UNION );
        op = SRT_Union;
      }
      p->pPrior = 0;
      pLimit = p->pLimit;
      p->pLimit = 0;
      pOffset = p->pOffset;
      p->pOffset = 0;
      uniondest.eDest = op;
      rc = sqlite3Select(pParse, p, &uniondest);
      testcase( rc!=SQLITE_OK );
      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
      sqlite3ExprListDelete(db, p->pOrderBy);
      pDelete = p->pPrior;
      p->pPrior = pPrior;
      p->pOrderBy = 0;
      sqlite3ExprDelete(db, p->pLimit);
      p->pLimit = pLimit;
      p->pOffset = pOffset;
      p->iLimit = 0;
      p->iOffset = 0;

      /* Convert the data in the temporary table into whatever form
      ** it is that we currently need.
      */
      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
      if( dest.eDest!=priorOp ){
        int iCont, iBreak, iStart;
        assert( p->pEList );
        if( dest.eDest==SRT_Output ){
          Select *pFirst = p;
          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
          generateColumnNames(pParse, 0, pFirst->pEList);
        }
        iBreak = sqlite3VdbeMakeLabel(v);
        iCont = sqlite3VdbeMakeLabel(v);
        computeLimitRegisters(pParse, p, iBreak);
        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
        iStart = sqlite3VdbeCurrentAddr(v);
        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
                        0, -1, &dest, iCont, iBreak);
        sqlite3VdbeResolveLabel(v, iCont);
        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
        sqlite3VdbeResolveLabel(v, iBreak);
        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
      }
      break;
    }
    default: assert( p->op==TK_INTERSECT ); {
      int tab1, tab2;
      int iCont, iBreak, iStart;
      Expr *pLimit, *pOffset;
      int addr;
      SelectDest intersectdest;
      int r1;

      /* INTERSECT is different from the others since it requires
      ** two temporary tables.  Hence it has its own case.  Begin
      ** by allocating the tables we will need.
      */
      tab1 = pParse->nTab++;
      tab2 = pParse->nTab++;
      assert( p->pOrderBy==0 );

      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
      assert( p->addrOpenEphm[0] == -1 );
      p->addrOpenEphm[0] = addr;
      p->pRightmost->selFlags |= SF_UsesEphemeral;
      assert( p->pEList );

      /* Code the SELECTs to our left into temporary table "tab1".
      */
      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
      rc = sqlite3Select(pParse, pPrior, &intersectdest);
      if( rc ){
        goto multi_select_end;
      }

      /* Code the current SELECT into temporary table "tab2"
      */
      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
      assert( p->addrOpenEphm[1] == -1 );
      p->addrOpenEphm[1] = addr;
      p->pPrior = 0;
      pLimit = p->pLimit;
      p->pLimit = 0;
      pOffset = p->pOffset;
      p->pOffset = 0;
      intersectdest.iParm = tab2;
      rc = sqlite3Select(pParse, p, &intersectdest);
      testcase( rc!=SQLITE_OK );
      pDelete = p->pPrior;
      p->pPrior = pPrior;
      sqlite3ExprDelete(db, p->pLimit);
      p->pLimit = pLimit;
      p->pOffset = pOffset;

      /* Generate code to take the intersection of the two temporary
      ** tables.
      */
      assert( p->pEList );
      if( dest.eDest==SRT_Output ){
        Select *pFirst = p;
        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
        generateColumnNames(pParse, 0, pFirst->pEList);
      }
      iBreak = sqlite3VdbeMakeLabel(v);
      iCont = sqlite3VdbeMakeLabel(v);
      computeLimitRegisters(pParse, p, iBreak);
      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
      r1 = sqlite3GetTempReg(pParse);
      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
      sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
      sqlite3ReleaseTempReg(pParse, r1);
      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
                      0, -1, &dest, iCont, iBreak);
      sqlite3VdbeResolveLabel(v, iCont);
      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
      sqlite3VdbeResolveLabel(v, iBreak);
      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
      break;
    }
  }

  /* Compute collating sequences used by 
  ** temporary tables needed to implement the compound select.
  ** Attach the KeyInfo structure to all temporary tables.
  **
  ** This section is run by the right-most SELECT statement only.
  ** SELECT statements to the left always skip this part.  The right-most
  ** SELECT might also skip this part if it has no ORDER BY clause and
  ** no temp tables are required.
  */
  if( p->selFlags & SF_UsesEphemeral ){
    int i;                        /* Loop counter */
    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
    Select *pLoop;                /* For looping through SELECT statements */
    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
    int nCol;                     /* Number of columns in result set */

    assert( p->pRightmost==p );
    nCol = p->pEList->nExpr;
    pKeyInfo = sqlite3DbMallocZero(db,
                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
    if( !pKeyInfo ){
      rc = SQLITE_NOMEM;
      goto multi_select_end;
    }

    pKeyInfo->enc = ENC(db);
    pKeyInfo->nField = (u16)nCol;

    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
      *apColl = multiSelectCollSeq(pParse, p, i);
      if( 0==*apColl ){
        *apColl = db->pDfltColl;
      }
    }

    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
      for(i=0; i<2; i++){
        int addr = pLoop->addrOpenEphm[i];
        if( addr<0 ){
          /* If [0] is unused then [1] is also unused.  So we can
          ** always safely abort as soon as the first unused slot is found */
          assert( pLoop->addrOpenEphm[1]<0 );
          break;
        }
        sqlite3VdbeChangeP2(v, addr, nCol);
        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
        pLoop->addrOpenEphm[i] = -1;
      }
    }
    sqlite3DbFree(db, pKeyInfo);
  }

multi_select_end:
  pDest->iMem = dest.iMem;
  pDest->nMem = dest.nMem;
  sqlite3SelectDelete(db, pDelete);
  return rc;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */

/*
** Code an output subroutine for a coroutine implementation of a
** SELECT statment.
**
** The data to be output is contained in pIn->iMem.  There are
** pIn->nMem columns to be output.  pDest is where the output should
** be sent.
**
** regReturn is the number of the register holding the subroutine
** return address.
**
** If regPrev>0 then it is a the first register in a vector that
** records the previous output.  mem[regPrev] is a flag that is false
** if there has been no previous output.  If regPrev>0 then code is
** generated to suppress duplicates.  pKeyInfo is used for comparing
** keys.
**
** If the LIMIT found in p->iLimit is reached, jump immediately to
** iBreak.
*/
static int generateOutputSubroutine(
  Parse *pParse,          /* Parsing context */
  Select *p,              /* The SELECT statement */
  SelectDest *pIn,        /* Coroutine supplying data */
  SelectDest *pDest,      /* Where to send the data */
  int regReturn,          /* The return address register */
  int regPrev,            /* Previous result register.  No uniqueness if 0 */
  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
  int p4type,             /* The p4 type for pKeyInfo */
  int iBreak              /* Jump here if we hit the LIMIT */
){
  Vdbe *v = pParse->pVdbe;
  int iContinue;
  int addr;

  addr = sqlite3VdbeCurrentAddr(v);
  iContinue = sqlite3VdbeMakeLabel(v);

  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
  */
  if( regPrev ){
    int j1, j2;
    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
                              (char*)pKeyInfo, p4type);
    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
    sqlite3VdbeJumpHere(v, j1);
    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  }
  if( pParse->db->mallocFailed ) return 0;

  /* Suppress the the first OFFSET entries if there is an OFFSET clause
  */
  codeOffset(v, p, iContinue);

  switch( pDest->eDest ){
    /* Store the result as data using a unique key.
    */
    case SRT_Table:
    case SRT_EphemTab: {
      int r1 = sqlite3GetTempReg(pParse);
      int r2 = sqlite3GetTempReg(pParse);
      testcase( pDest->eDest==SRT_Table );
      testcase( pDest->eDest==SRT_EphemTab );
      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
      sqlite3ReleaseTempReg(pParse, r2);
      sqlite3ReleaseTempReg(pParse, r1);
      break;
    }

#ifndef SQLITE_OMIT_SUBQUERY
    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
    ** then there should be a single item on the stack.  Write this
    ** item into the set table with bogus data.
    */
    case SRT_Set: {
      int r1;
      assert( pIn->nMem==1 );
      p->affinity = 
         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
      r1 = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
      sqlite3ReleaseTempReg(pParse, r1);
      break;
    }

#if 0  /* Never occurs on an ORDER BY query */
    /* If any row exist in the result set, record that fact and abort.
    */
    case SRT_Exists: {
      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
      /* The LIMIT clause will terminate the loop for us */
      break;
    }
#endif

    /* If this is a scalar select that is part of an expression, then
    ** store the results in the appropriate memory cell and break out
    ** of the scan loop.
    */
    case SRT_Mem: {
      assert( pIn->nMem==1 );
      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
      /* The LIMIT clause will jump out of the loop for us */
      break;
    }
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */

    /* The results are stored in a sequence of registers
    ** starting at pDest->iMem.  Then the co-routine yields.
    */
    case SRT_Coroutine: {
      if( pDest->iMem==0 ){
        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
        pDest->nMem = pIn->nMem;
      }
      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
      break;
    }

    /* If none of the above, then the result destination must be
    ** SRT_Output.  This routine is never called with any other
    ** destination other than the ones handled above or SRT_Output.
    **
    ** For SRT_Output, results are stored in a sequence of registers.  
    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
    ** return the next row of result.
    */
    default: {
      assert( pDest->eDest==SRT_Output );
      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
      break;
    }
  }

  /* Jump to the end of the loop if the LIMIT is reached.
  */
  if( p->iLimit ){
    sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
    sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  }

  /* Generate the subroutine return
  */
  sqlite3VdbeResolveLabel(v, iContinue);
  sqlite3VdbeAddOp1(v, OP_Return, regReturn);

  return addr;
}

/*
** Alternative compound select code generator for cases when there
** is an ORDER BY clause.
**
** We assume a query of the following form:
**
**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
**
** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
** is to code both <selectA> and <selectB> with the ORDER BY clause as
** co-routines.  Then run the co-routines in parallel and merge the results
** into the output.  In addition to the two coroutines (called selectA and
** selectB) there are 7 subroutines:
**
**    outA:    Move the output of the selectA coroutine into the output
**             of the compound query.
**
**    outB:    Move the output of the selectB coroutine into the output
**             of the compound query.  (Only generated for UNION and
**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
**             appears only in B.)
**
**    AltB:    Called when there is data from both coroutines and A<B.
**
**    AeqB:    Called when there is data from both coroutines and A==B.
**
**    AgtB:    Called when there is data from both coroutines and A>B.
**
**    EofA:    Called when data is exhausted from selectA.
**
**    EofB:    Called when data is exhausted from selectB.
**
** The implementation of the latter five subroutines depend on which 
** <operator> is used:
**
**
**             UNION ALL         UNION            EXCEPT          INTERSECT
**          -------------  -----------------  --------------  -----------------
**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
**
**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
**
**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
**
**   EofA:   outB, nextB      outB, nextB          halt             halt
**
**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
**
** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
** causes an immediate jump to EofA and an EOF on B following nextB causes
** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
** following nextX causes a jump to the end of the select processing.
**
** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
** within the output subroutine.  The regPrev register set holds the previously
** output value.  A comparison is made against this value and the output
** is skipped if the next results would be the same as the previous.
**
** The implementation plan is to implement the two coroutines and seven
** subroutines first, then put the control logic at the bottom.  Like this:
**
**          goto Init
**     coA: coroutine for left query (A)
**     coB: coroutine for right query (B)
**    outA: output one row of A
**    outB: output one row of B (UNION and UNION ALL only)
**    EofA: ...
**    EofB: ...
**    AltB: ...
**    AeqB: ...
**    AgtB: ...
**    Init: initialize coroutine registers
**          yield coA
**          if eof(A) goto EofA
**          yield coB
**          if eof(B) goto EofB
**    Cmpr: Compare A, B
**          Jump AltB, AeqB, AgtB
**     End: ...
**
** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
** actually called using Gosub and they do not Return.  EofA and EofB loop
** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
** and AgtB jump to either L2 or to one of EofA or EofB.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
static int multiSelectOrderBy(
  Parse *pParse,        /* Parsing context */
  Select *p,            /* The right-most of SELECTs to be coded */
  SelectDest *pDest     /* What to do with query results */
){
  int i, j;             /* Loop counters */
  Select *pPrior;       /* Another SELECT immediately to our left */
  Vdbe *v;              /* Generate code to this VDBE */
  SelectDest destA;     /* Destination for coroutine A */
  SelectDest destB;     /* Destination for coroutine B */
  int regAddrA;         /* Address register for select-A coroutine */
  int regEofA;          /* Flag to indicate when select-A is complete */
  int regAddrB;         /* Address register for select-B coroutine */
  int regEofB;          /* Flag to indicate when select-B is complete */
  int addrSelectA;      /* Address of the select-A coroutine */
  int addrSelectB;      /* Address of the select-B coroutine */
  int regOutA;          /* Address register for the output-A subroutine */
  int regOutB;          /* Address register for the output-B subroutine */
  int addrOutA;         /* Address of the output-A subroutine */
  int addrOutB = 0;     /* Address of the output-B subroutine */
  int addrEofA;         /* Address of the select-A-exhausted subroutine */
  int addrEofB;         /* Address of the select-B-exhausted subroutine */
  int addrAltB;         /* Address of the A<B subroutine */
  int addrAeqB;         /* Address of the A==B subroutine */
  int addrAgtB;         /* Address of the A>B subroutine */
  int regLimitA;        /* Limit register for select-A */
  int regLimitB;        /* Limit register for select-A */
  int regPrev;          /* A range of registers to hold previous output */
  int savedLimit;       /* Saved value of p->iLimit */
  int savedOffset;      /* Saved value of p->iOffset */
  int labelCmpr;        /* Label for the start of the merge algorithm */
  int labelEnd;         /* Label for the end of the overall SELECT stmt */
  int j1;               /* Jump instructions that get retargetted */
  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
  sqlite3 *db;          /* Database connection */
  ExprList *pOrderBy;   /* The ORDER BY clause */
  int nOrderBy;         /* Number of terms in the ORDER BY clause */
  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */

  assert( p->pOrderBy!=0 );
  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
  db = pParse->db;
  v = pParse->pVdbe;
  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
  labelEnd = sqlite3VdbeMakeLabel(v);
  labelCmpr = sqlite3VdbeMakeLabel(v);


  /* Patch up the ORDER BY clause
  */
  op = p->op;  
  pPrior = p->pPrior;
  assert( pPrior->pOrderBy==0 );
  pOrderBy = p->pOrderBy;
  assert( pOrderBy );
  nOrderBy = pOrderBy->nExpr;

  /* For operators other than UNION ALL we have to make sure that
  ** the ORDER BY clause covers every term of the result set.  Add
  ** terms to the ORDER BY clause as necessary.
  */
  if( op!=TK_ALL ){
    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
      struct ExprList_item *pItem;
      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
        assert( pItem->iCol>0 );
        if( pItem->iCol==i ) break;
      }
      if( j==nOrderBy ){
        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
        if( pNew==0 ) return SQLITE_NOMEM;
        pNew->flags |= EP_IntValue;
        pNew->u.iValue = i;
        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
        pOrderBy->a[nOrderBy++].iCol = (u16)i;
      }
    }
  }

  /* Compute the comparison permutation and keyinfo that is used with
  ** the permutation used to determine if the next
  ** row of results comes from selectA or selectB.  Also add explicit
  ** collations to the ORDER BY clause terms so that when the subqueries
  ** to the right and the left are evaluated, they use the correct
  ** collation.
  */
  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  if( aPermute ){
    struct ExprList_item *pItem;
    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
      aPermute[i] = pItem->iCol - 1;
    }
    pKeyMerge =
      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
    if( pKeyMerge ){
      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
      pKeyMerge->nField = (u16)nOrderBy;
      pKeyMerge->enc = ENC(db);
      for(i=0; i<nOrderBy; i++){
        CollSeq *pColl;
        Expr *pTerm = pOrderBy->a[i].pExpr;
        if( pTerm->flags & EP_ExpCollate ){
          pColl = pTerm->pColl;
        }else{
          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
          pTerm->flags |= EP_ExpCollate;
          pTerm->pColl = pColl;
        }
        pKeyMerge->aColl[i] = pColl;
        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
      }
    }
  }else{
    pKeyMerge = 0;
  }

  /* Reattach the ORDER BY clause to the query.
  */
  p->pOrderBy = pOrderBy;
  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);

  /* Allocate a range of temporary registers and the KeyInfo needed
  ** for the logic that removes duplicate result rows when the
  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  */
  if( op==TK_ALL ){
    regPrev = 0;
  }else{
    int nExpr = p->pEList->nExpr;
    assert( nOrderBy>=nExpr || db->mallocFailed );
    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
    pKeyDup = sqlite3DbMallocZero(db,
                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
    if( pKeyDup ){
      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
      pKeyDup->nField = (u16)nExpr;
      pKeyDup->enc = ENC(db);
      for(i=0; i<nExpr; i++){
        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
        pKeyDup->aSortOrder[i] = 0;
      }
    }
  }
 
  /* Separate the left and the right query from one another
  */
  p->pPrior = 0;
  pPrior->pRightmost = 0;
  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  if( pPrior->pPrior==0 ){
    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  }

  /* Compute the limit registers */
  computeLimitRegisters(pParse, p, labelEnd);
  if( p->iLimit && op==TK_ALL ){
    regLimitA = ++pParse->nMem;
    regLimitB = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
                                  regLimitA);
    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  }else{
    regLimitA = regLimitB = 0;
  }
  sqlite3ExprDelete(db, p->pLimit);
  p->pLimit = 0;
  sqlite3ExprDelete(db, p->pOffset);
  p->pOffset = 0;

  regAddrA = ++pParse->nMem;
  regEofA = ++pParse->nMem;
  regAddrB = ++pParse->nMem;
  regEofB = ++pParse->nMem;
  regOutA = ++pParse->nMem;
  regOutB = ++pParse->nMem;
  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);

  /* Jump past the various subroutines and coroutines to the main
  ** merge loop
  */
  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  addrSelectA = sqlite3VdbeCurrentAddr(v);


  /* Generate a coroutine to evaluate the SELECT statement to the
  ** left of the compound operator - the "A" select.
  */
  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  pPrior->iLimit = regLimitA;
  sqlite3Select(pParse, pPrior, &destA);
  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  VdbeNoopComment((v, "End coroutine for left SELECT"));

  /* Generate a coroutine to evaluate the SELECT statement on 
  ** the right - the "B" select
  */
  addrSelectB = sqlite3VdbeCurrentAddr(v);
  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  savedLimit = p->iLimit;
  savedOffset = p->iOffset;
  p->iLimit = regLimitB;
  p->iOffset = 0;  
  sqlite3Select(pParse, p, &destB);
  p->iLimit = savedLimit;
  p->iOffset = savedOffset;
  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  VdbeNoopComment((v, "End coroutine for right SELECT"));

  /* Generate a subroutine that outputs the current row of the A
  ** select as the next output row of the compound select.
  */
  VdbeNoopComment((v, "Output routine for A"));
  addrOutA = generateOutputSubroutine(pParse,
                 p, &destA, pDest, regOutA,
                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  
  /* Generate a subroutine that outputs the current row of the B
  ** select as the next output row of the compound select.
  */
  if( op==TK_ALL || op==TK_UNION ){
    VdbeNoopComment((v, "Output routine for B"));
    addrOutB = generateOutputSubroutine(pParse,
                 p, &destB, pDest, regOutB,
                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  }

  /* Generate a subroutine to run when the results from select A
  ** are exhausted and only data in select B remains.
  */
  VdbeNoopComment((v, "eof-A subroutine"));
  if( op==TK_EXCEPT || op==TK_INTERSECT ){
    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  }else{  
    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  }

  /* Generate a subroutine to run when the results from select B
  ** are exhausted and only data in select A remains.
  */
  if( op==TK_INTERSECT ){
    addrEofB = addrEofA;
  }else{  
    VdbeNoopComment((v, "eof-B subroutine"));
    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  }

  /* Generate code to handle the case of A<B
  */
  VdbeNoopComment((v, "A-lt-B subroutine"));
  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);

  /* Generate code to handle the case of A==B
  */
  if( op==TK_ALL ){
    addrAeqB = addrAltB;
  }else if( op==TK_INTERSECT ){
    addrAeqB = addrAltB;
    addrAltB++;
  }else{
    VdbeNoopComment((v, "A-eq-B subroutine"));
    addrAeqB =
    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  }

  /* Generate code to handle the case of A>B
  */
  VdbeNoopComment((v, "A-gt-B subroutine"));
  addrAgtB = sqlite3VdbeCurrentAddr(v);
  if( op==TK_ALL || op==TK_UNION ){
    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  }
  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);

  /* This code runs once to initialize everything.
  */
  sqlite3VdbeJumpHere(v, j1);
  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);

  /* Implement the main merge loop
  */
  sqlite3VdbeResolveLabel(v, labelCmpr);
  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);

  /* Release temporary registers
  */
  if( regPrev ){
    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  }

  /* Jump to the this point in order to terminate the query.
  */
  sqlite3VdbeResolveLabel(v, labelEnd);

  /* Set the number of output columns
  */
  if( pDest->eDest==SRT_Output ){
    Select *pFirst = pPrior;
    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
    generateColumnNames(pParse, 0, pFirst->pEList);
  }

  /* Reassembly the compound query so that it will be freed correctly
  ** by the calling function */
  if( p->pPrior ){
    sqlite3SelectDelete(db, p->pPrior);
  }
  p->pPrior = pPrior;

  /*** TBD:  Insert subroutine calls to close cursors on incomplete
  **** subqueries ****/
  return SQLITE_OK;
}
#endif

#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* Forward Declarations */
static void substExprList(sqlite3*, ExprList*, int, ExprList*);
static void substSelect(sqlite3*, Select *, int, ExprList *);

/*
** Scan through the expression pExpr.  Replace every reference to
** a column in table number iTable with a copy of the iColumn-th
** entry in pEList.  (But leave references to the ROWID column 
** unchanged.)
**
** This routine is part of the flattening procedure.  A subquery
** whose result set is defined by pEList appears as entry in the
** FROM clause of a SELECT such that the VDBE cursor assigned to that
** FORM clause entry is iTable.  This routine make the necessary 
** changes to pExpr so that it refers directly to the source table
** of the subquery rather the result set of the subquery.
*/
static Expr *substExpr(
  sqlite3 *db,        /* Report malloc errors to this connection */
  Expr *pExpr,        /* Expr in which substitution occurs */
  int iTable,         /* Table to be substituted */
  ExprList *pEList    /* Substitute expressions */
){
  if( pExpr==0 ) return 0;
  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
    if( pExpr->iColumn<0 ){
      pExpr->op = TK_NULL;
    }else{
      Expr *pNew;
      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
      if( pNew && pExpr->pColl ){
        pNew->pColl = pExpr->pColl;
      }
      sqlite3ExprDelete(db, pExpr);
      pExpr = pNew;
    }
  }else{
    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
      substSelect(db, pExpr->x.pSelect, iTable, pEList);
    }else{
      substExprList(db, pExpr->x.pList, iTable, pEList);
    }
  }
  return pExpr;
}
static void substExprList(
  sqlite3 *db,         /* Report malloc errors here */
  ExprList *pList,     /* List to scan and in which to make substitutes */
  int iTable,          /* Table to be substituted */
  ExprList *pEList     /* Substitute values */
){
  int i;
  if( pList==0 ) return;
  for(i=0; i<pList->nExpr; i++){
    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  }
}
static void substSelect(
  sqlite3 *db,         /* Report malloc errors here */
  Select *p,           /* SELECT statement in which to make substitutions */
  int iTable,          /* Table to be replaced */
  ExprList *pEList     /* Substitute values */
){
  SrcList *pSrc;
  struct SrcList_item *pItem;
  int i;
  if( !p ) return;
  substExprList(db, p->pEList, iTable, pEList);
  substExprList(db, p->pGroupBy, iTable, pEList);
  substExprList(db, p->pOrderBy, iTable, pEList);
  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  substSelect(db, p->pPrior, iTable, pEList);
  pSrc = p->pSrc;
  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  if( ALWAYS(pSrc) ){
    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
      substSelect(db, pItem->pSelect, iTable, pEList);
    }
  }
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */

#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** This routine attempts to flatten subqueries in order to speed
** execution.  It returns 1 if it makes changes and 0 if no flattening
** occurs.
**
** To understand the concept of flattening, consider the following
** query:
**
**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
**
** The default way of implementing this query is to execute the
** subquery first and store the results in a temporary table, then
** run the outer query on that temporary table.  This requires two
** passes over the data.  Furthermore, because the temporary table
** has no indices, the WHERE clause on the outer query cannot be
** optimized.
**
** This routine attempts to rewrite queries such as the above into
** a single flat select, like this:
**
**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
**
** The code generated for this simpification gives the same result
** but only has to scan the data once.  And because indices might 
** exist on the table t1, a complete scan of the data might be
** avoided.
**
** Flattening is only attempted if all of the following are true:
**
**   (1)  The subquery and the outer query do not both use aggregates.
**
**   (2)  The subquery is not an aggregate or the outer query is not a join.
**
**   (3)  The subquery is not the right operand of a left outer join
**        (Originally ticket #306.  Strenghtened by ticket #3300)
**
**   (4)  The subquery is not DISTINCT or the outer query is not a join.
**
**   (5)  The subquery is not DISTINCT or the outer query does not use
**        aggregates.
**
**   (6)  The subquery does not use aggregates or the outer query is not
**        DISTINCT.
**
**   (7)  The subquery has a FROM clause.
**
**   (8)  The subquery does not use LIMIT or the outer query is not a join.
**
**   (9)  The subquery does not use LIMIT or the outer query does not use
**        aggregates.
**
**  (10)  The subquery does not use aggregates or the outer query does not
**        use LIMIT.
**
**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
**
**  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
**        a separate restriction deriving from ticket #350.
**
**  (13)  The subquery and outer query do not both use LIMIT
**
**  (14)  The subquery does not use OFFSET
**
**  (15)  The outer query is not part of a compound select or the
**        subquery does not have both an ORDER BY and a LIMIT clause.
**        (See ticket #2339)
**
**  (16)  The outer query is not an aggregate or the subquery does
**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
**        until we introduced the group_concat() function.  
**
**  (17)  The sub-query is not a compound select, or it is a UNION ALL 
**        compound clause made up entirely of non-aggregate queries, and 
**        the parent query:
**
**          * is not itself part of a compound select,
**          * is not an aggregate or DISTINCT query, and
**          * has no other tables or sub-selects in the FROM clause.
**
**        The parent and sub-query may contain WHERE clauses. Subject to
**        rules (11), (13) and (14), they may also contain ORDER BY,
**        LIMIT and OFFSET clauses.
**
**  (18)  If the sub-query is a compound select, then all terms of the
**        ORDER by clause of the parent must be simple references to 
**        columns of the sub-query.
**
**  (19)  The subquery does not use LIMIT or the outer query does not
**        have a WHERE clause.
**
**  (20)  If the sub-query is a compound select, then it must not use
**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
**        somewhat by saying that the terms of the ORDER BY clause must
**        appear as unmodified result columns in the outer query.  But
**        have other optimizations in mind to deal with that case.
**
** In this routine, the "p" parameter is a pointer to the outer query.
** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
**
** If flattening is not attempted, this routine is a no-op and returns 0.
** If flattening is attempted this routine returns 1.
**
** All of the expression analysis must occur on both the outer query and
** the subquery before this routine runs.
*/
static int flattenSubquery(
  Parse *pParse,       /* Parsing context */
  Select *p,           /* The parent or outer SELECT statement */
  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
  int isAgg,           /* True if outer SELECT uses aggregate functions */
  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
){
  const char *zSavedAuthContext = pParse->zAuthContext;
  Select *pParent;
  Select *pSub;       /* The inner query or "subquery" */
  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
  SrcList *pSrc;      /* The FROM clause of the outer query */
  SrcList *pSubSrc;   /* The FROM clause of the subquery */
  ExprList *pList;    /* The result set of the outer query */
  int iParent;        /* VDBE cursor number of the pSub result set temp table */
  int i;              /* Loop counter */
  Expr *pWhere;                    /* The WHERE clause */
  struct SrcList_item *pSubitem;   /* The subquery */
  sqlite3 *db = pParse->db;

  /* Check to see if flattening is permitted.  Return 0 if not.
  */
  assert( p!=0 );
  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
  pSrc = p->pSrc;
  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  pSubitem = &pSrc->a[iFrom];
  iParent = pSubitem->iCursor;
  pSub = pSubitem->pSelect;
  assert( pSub!=0 );
  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
  pSubSrc = pSub->pSrc;
  assert( pSubSrc );
  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
  ** became arbitrary expressions, we were forced to add restrictions (13)
  ** and (14). */
  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
    return 0;                                            /* Restriction (15) */
  }
  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
     return 0;       
  }
  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
     return 0;         /* Restriction (6)  */
  }
  if( p->pOrderBy && pSub->pOrderBy ){
     return 0;                                           /* Restriction (11) */
  }
  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */

  /* OBSOLETE COMMENT 1:
  ** Restriction 3:  If the subquery is a join, make sure the subquery is 
  ** not used as the right operand of an outer join.  Examples of why this
  ** is not allowed:
  **
  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
  **
  ** If we flatten the above, we would get
  **
  **         (t1 LEFT OUTER JOIN t2) JOIN t3
  **
  ** which is not at all the same thing.
  **
  ** OBSOLETE COMMENT 2:
  ** Restriction 12:  If the subquery is the right operand of a left outer
  ** join, make sure the subquery has no WHERE clause.
  ** An examples of why this is not allowed:
  **
  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  **
  ** If we flatten the above, we would get
  **
  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  **
  ** But the t2.x>0 test will always fail on a NULL row of t2, which
  ** effectively converts the OUTER JOIN into an INNER JOIN.
  **
  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  ** is fraught with danger.  Best to avoid the whole thing.  If the
  ** subquery is the right term of a LEFT JOIN, then do not flatten.
  */
  if( (pSubitem->jointype & JT_OUTER)!=0 ){
    return 0;
  }

  /* Restriction 17: If the sub-query is a compound SELECT, then it must
  ** use only the UNION ALL operator. And none of the simple select queries
  ** that make up the compound SELECT are allowed to be aggregate or distinct
  ** queries.
  */
  if( pSub->pPrior ){
    if( pSub->pOrderBy ){
      return 0;  /* Restriction 20 */
    }
    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
      return 0;
    }
    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
       || (pSub1->pPrior && pSub1->op!=TK_ALL) 
       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
      ){
        return 0;
      }
    }

    /* Restriction 18. */
    if( p->pOrderBy ){
      int ii;
      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
      }
    }
  }

  /***** If we reach this point, flattening is permitted. *****/

  /* Authorize the subquery */
  pParse->zAuthContext = pSubitem->zName;
  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  pParse->zAuthContext = zSavedAuthContext;

  /* If the sub-query is a compound SELECT statement, then (by restrictions
  ** 17 and 18 above) it must be a UNION ALL and the parent query must 
  ** be of the form:
  **
  **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
  **
  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
  ** OFFSET clauses and joins them to the left-hand-side of the original
  ** using UNION ALL operators. In this case N is the number of simple
  ** select statements in the compound sub-query.
  **
  ** Example:
  **
  **     SELECT a+1 FROM (
  **        SELECT x FROM tab
  **        UNION ALL
  **        SELECT y FROM tab
  **        UNION ALL
  **        SELECT abs(z*2) FROM tab2
  **     ) WHERE a!=5 ORDER BY 1
  **
  ** Transformed into:
  **
  **     SELECT x+1 FROM tab WHERE x+1!=5
  **     UNION ALL
  **     SELECT y+1 FROM tab WHERE y+1!=5
  **     UNION ALL
  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  **     ORDER BY 1
  **
  ** We call this the "compound-subquery flattening".
  */
  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
    Select *pNew;
    ExprList *pOrderBy = p->pOrderBy;
    Expr *pLimit = p->pLimit;
    Select *pPrior = p->pPrior;
    p->pOrderBy = 0;
    p->pSrc = 0;
    p->pPrior = 0;
    p->pLimit = 0;
    pNew = sqlite3SelectDup(db, p, 0);
    p->pLimit = pLimit;
    p->pOrderBy = pOrderBy;
    p->pSrc = pSrc;
    p->op = TK_ALL;
    p->pRightmost = 0;
    if( pNew==0 ){
      pNew = pPrior;
    }else{
      pNew->pPrior = pPrior;
      pNew->pRightmost = 0;
    }
    p->pPrior = pNew;
    if( db->mallocFailed ) return 1;
  }

  /* Begin flattening the iFrom-th entry of the FROM clause 
  ** in the outer query.
  */
  pSub = pSub1 = pSubitem->pSelect;

  /* Delete the transient table structure associated with the
  ** subquery
  */
  sqlite3DbFree(db, pSubitem->zDatabase);
  sqlite3DbFree(db, pSubitem->zName);
  sqlite3DbFree(db, pSubitem->zAlias);
  pSubitem->zDatabase = 0;
  pSubitem->zName = 0;
  pSubitem->zAlias = 0;
  pSubitem->pSelect = 0;

  /* Defer deleting the Table object associated with the
  ** subquery until code generation is
  ** complete, since there may still exist Expr.pTab entries that
  ** refer to the subquery even after flattening.  Ticket #3346.
  **
  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  */
  if( ALWAYS(pSubitem->pTab!=0) ){
    Table *pTabToDel = pSubitem->pTab;
    if( pTabToDel->nRef==1 ){
      Parse *pToplevel = sqlite3ParseToplevel(pParse);
      pTabToDel->pNextZombie = pToplevel->pZombieTab;
      pToplevel->pZombieTab = pTabToDel;
    }else{
      pTabToDel->nRef--;
    }
    pSubitem->pTab = 0;
  }

  /* The following loop runs once for each term in a compound-subquery
  ** flattening (as described above).  If we are doing a different kind
  ** of flattening - a flattening other than a compound-subquery flattening -
  ** then this loop only runs once.
  **
  ** This loop moves all of the FROM elements of the subquery into the
  ** the FROM clause of the outer query.  Before doing this, remember
  ** the cursor number for the original outer query FROM element in
  ** iParent.  The iParent cursor will never be used.  Subsequent code
  ** will scan expressions looking for iParent references and replace
  ** those references with expressions that resolve to the subquery FROM
  ** elements we are now copying in.
  */
  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
    int nSubSrc;
    u8 jointype = 0;
    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
    pSrc = pParent->pSrc;     /* FROM clause of the outer query */

    if( pSrc ){
      assert( pParent==p );  /* First time through the loop */
      jointype = pSubitem->jointype;
    }else{
      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
      if( pSrc==0 ){
        assert( db->mallocFailed );
        break;
      }
    }

    /* The subquery uses a single slot of the FROM clause of the outer
    ** query.  If the subquery has more than one element in its FROM clause,
    ** then expand the outer query to make space for it to hold all elements
    ** of the subquery.
    **
    ** Example:
    **
    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
    **
    ** The outer query has 3 slots in its FROM clause.  One slot of the
    ** outer query (the middle slot) is used by the subquery.  The next
    ** block of code will expand the out query to 4 slots.  The middle
    ** slot is expanded to two slots in order to make space for the
    ** two elements in the FROM clause of the subquery.
    */
    if( nSubSrc>1 ){
      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
      if( db->mallocFailed ){
        break;
      }
    }

    /* Transfer the FROM clause terms from the subquery into the
    ** outer query.
    */
    for(i=0; i<nSubSrc; i++){
      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
      pSrc->a[i+iFrom] = pSubSrc->a[i];
      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
    }
    pSrc->a[iFrom].jointype = jointype;
  
    /* Now begin substituting subquery result set expressions for 
    ** references to the iParent in the outer query.
    ** 
    ** Example:
    **
    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
    **   \                     \_____________ subquery __________/          /
    **    \_____________________ outer query ______________________________/
    **
    ** We look at every expression in the outer query and every place we see
    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
    */
    pList = pParent->pEList;
    for(i=0; i<pList->nExpr; i++){
      if( pList->a[i].zName==0 ){
        const char *zSpan = pList->a[i].zSpan;
        if( ALWAYS(zSpan) ){
          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
        }
      }
    }
    substExprList(db, pParent->pEList, iParent, pSub->pEList);
    if( isAgg ){
      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
    }
    if( pSub->pOrderBy ){
      assert( pParent->pOrderBy==0 );
      pParent->pOrderBy = pSub->pOrderBy;
      pSub->pOrderBy = 0;
    }else if( pParent->pOrderBy ){
      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
    }
    if( pSub->pWhere ){
      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
    }else{
      pWhere = 0;
    }
    if( subqueryIsAgg ){
      assert( pParent->pHaving==0 );
      pParent->pHaving = pParent->pWhere;
      pParent->pWhere = pWhere;
      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
                                  sqlite3ExprDup(db, pSub->pHaving, 0));
      assert( pParent->pGroupBy==0 );
      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
    }else{
      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
    }
  
    /* The flattened query is distinct if either the inner or the
    ** outer query is distinct. 
    */
    pParent->selFlags |= pSub->selFlags & SF_Distinct;
  
    /*
    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
    **
    ** One is tempted to try to add a and b to combine the limits.  But this
    ** does not work if either limit is negative.
    */
    if( pSub->pLimit ){
      pParent->pLimit = pSub->pLimit;
      pSub->pLimit = 0;
    }
  }

  /* Finially, delete what is left of the subquery and return
  ** success.
  */
  sqlite3SelectDelete(db, pSub1);

  return 1;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */

/*
** Analyze the SELECT statement passed as an argument to see if it
** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
** it is, or 0 otherwise. At present, a query is considered to be
** a min()/max() query if:
**
**   1. There is a single object in the FROM clause.
**
**   2. There is a single expression in the result set, and it is
**      either min(x) or max(x), where x is a column reference.
*/
static u8 minMaxQuery(Select *p){
  Expr *pExpr;
  ExprList *pEList = p->pEList;

  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
  pExpr = pEList->a[0].pExpr;
  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
  pEList = pExpr->x.pList;
  if( pEList==0 || pEList->nExpr!=1 ) return 0;
  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
  assert( !ExprHasProperty(pExpr, EP_IntValue) );
  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
    return WHERE_ORDERBY_MIN;
  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
    return WHERE_ORDERBY_MAX;
  }
  return WHERE_ORDERBY_NORMAL;
}

/*
** The select statement passed as the first argument is an aggregate query.
** The second argment is the associated aggregate-info object. This 
** function tests if the SELECT is of the form:
**
**   SELECT count(*) FROM <tbl>
**
** where table is a database table, not a sub-select or view. If the query
** does match this pattern, then a pointer to the Table object representing
** <tbl> is returned. Otherwise, 0 is returned.
*/
static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  Table *pTab;
  Expr *pExpr;

  assert( !p->pGroupBy );

  if( p->pWhere || p->pEList->nExpr!=1 
   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  ){
    return 0;
  }
  pTab = p->pSrc->a[0].pTab;
  pExpr = p->pEList->a[0].pExpr;
  assert( pTab && !pTab->pSelect && pExpr );

  if( IsVirtual(pTab) ) return 0;
  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
  if( pExpr->flags&EP_Distinct ) return 0;

  return pTab;
}

/*
** If the source-list item passed as an argument was augmented with an
** INDEXED BY clause, then try to locate the specified index. If there
** was such a clause and the named index cannot be found, return 
** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
** pFrom->pIndex and return SQLITE_OK.
*/
int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  if( pFrom->pTab && pFrom->zIndex ){
    Table *pTab = pFrom->pTab;
    char *zIndex = pFrom->zIndex;
    Index *pIdx;
    for(pIdx=pTab->pIndex; 
        pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
        pIdx=pIdx->pNext
    );
    if( !pIdx ){
      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
      return SQLITE_ERROR;
    }
    pFrom->pIndex = pIdx;
  }
  return SQLITE_OK;
}

/*
** This routine is a Walker callback for "expanding" a SELECT statement.
** "Expanding" means to do the following:
**
**    (1)  Make sure VDBE cursor numbers have been assigned to every
**         element of the FROM clause.
**
**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
**         defines FROM clause.  When views appear in the FROM clause,
**         fill pTabList->a[].pSelect with a copy of the SELECT statement
**         that implements the view.  A copy is made of the view's SELECT
**         statement so that we can freely modify or delete that statement
**         without worrying about messing up the presistent representation
**         of the view.
**
**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
**         on joins and the ON and USING clause of joins.
**
**    (4)  Scan the list of columns in the result set (pEList) looking
**         for instances of the "*" operator or the TABLE.* operator.
**         If found, expand each "*" to be every column in every table
**         and TABLE.* to be every column in TABLE.
**
*/
static int selectExpander(Walker *pWalker, Select *p){
  Parse *pParse = pWalker->pParse;
  int i, j, k;
  SrcList *pTabList;
  ExprList *pEList;
  struct SrcList_item *pFrom;
  sqlite3 *db = pParse->db;

  if( db->mallocFailed  ){
    return WRC_Abort;
  }
  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
    return WRC_Prune;
  }
  p->selFlags |= SF_Expanded;
  pTabList = p->pSrc;
  pEList = p->pEList;

  /* Make sure cursor numbers have been assigned to all entries in
  ** the FROM clause of the SELECT statement.
  */
  sqlite3SrcListAssignCursors(pParse, pTabList);

  /* Look up every table named in the FROM clause of the select.  If
  ** an entry of the FROM clause is a subquery instead of a table or view,
  ** then create a transient table structure to describe the subquery.
  */
  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
    Table *pTab;
    if( pFrom->pTab!=0 ){
      /* This statement has already been prepared.  There is no need
      ** to go further. */
      assert( i==0 );
      return WRC_Prune;
    }
    if( pFrom->zName==0 ){
#ifndef SQLITE_OMIT_SUBQUERY
      Select *pSel = pFrom->pSelect;
      /* A sub-query in the FROM clause of a SELECT */
      assert( pSel!=0 );
      assert( pFrom->pTab==0 );
      sqlite3WalkSelect(pWalker, pSel);
      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
      if( pTab==0 ) return WRC_Abort;
      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
      pTab->nRef = 1;
      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
      while( pSel->pPrior ){ pSel = pSel->pPrior; }
      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
      pTab->iPKey = -1;
      pTab->tabFlags |= TF_Ephemeral;
#endif
    }else{
      /* An ordinary table or view name in the FROM clause */
      assert( pFrom->pTab==0 );
      pFrom->pTab = pTab = 
        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
      if( pTab==0 ) return WRC_Abort;
      pTab->nRef++;
#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
      if( pTab->pSelect || IsVirtual(pTab) ){
        /* We reach here if the named table is a really a view */
        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
        assert( pFrom->pSelect==0 );
        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
        sqlite3WalkSelect(pWalker, pFrom->pSelect);
      }
#endif
    }

    /* Locate the index named by the INDEXED BY clause, if any. */
    if( sqlite3IndexedByLookup(pParse, pFrom) ){
      return WRC_Abort;
    }
  }

  /* Process NATURAL keywords, and ON and USING clauses of joins.
  */
  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
    return WRC_Abort;
  }

  /* For every "*" that occurs in the column list, insert the names of
  ** all columns in all tables.  And for every TABLE.* insert the names
  ** of all columns in TABLE.  The parser inserted a special expression
  ** with the TK_ALL operator for each "*" that it found in the column list.
  ** The following code just has to locate the TK_ALL expressions and expand
  ** each one to the list of all columns in all tables.
  **
  ** The first loop just checks to see if there are any "*" operators
  ** that need expanding.
  */
  for(k=0; k<pEList->nExpr; k++){
    Expr *pE = pEList->a[k].pExpr;
    if( pE->op==TK_ALL ) break;
    assert( pE->op!=TK_DOT || pE->pRight!=0 );
    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  }
  if( k<pEList->nExpr ){
    /*
    ** If we get here it means the result set contains one or more "*"
    ** operators that need to be expanded.  Loop through each expression
    ** in the result set and expand them one by one.
    */
    struct ExprList_item *a = pEList->a;
    ExprList *pNew = 0;
    int flags = pParse->db->flags;
    int longNames = (flags & SQLITE_FullColNames)!=0
                      && (flags & SQLITE_ShortColNames)==0;

    for(k=0; k<pEList->nExpr; k++){
      Expr *pE = a[k].pExpr;
      assert( pE->op!=TK_DOT || pE->pRight!=0 );
      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
        /* This particular expression does not need to be expanded.
        */
        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
        if( pNew ){
          pNew->a[pNew->nExpr-1].zName = a[k].zName;
          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
          a[k].zName = 0;
          a[k].zSpan = 0;
        }
        a[k].pExpr = 0;
      }else{
        /* This expression is a "*" or a "TABLE.*" and needs to be
        ** expanded. */
        int tableSeen = 0;      /* Set to 1 when TABLE matches */
        char *zTName;            /* text of name of TABLE */
        if( pE->op==TK_DOT ){
          assert( pE->pLeft!=0 );
          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
          zTName = pE->pLeft->u.zToken;
        }else{
          zTName = 0;
        }
        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
          Table *pTab = pFrom->pTab;
          char *zTabName = pFrom->zAlias;
          if( zTabName==0 ){
            zTabName = pTab->zName;
          }
          if( db->mallocFailed ) break;
          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
            continue;
          }
          tableSeen = 1;
          for(j=0; j<pTab->nCol; j++){
            Expr *pExpr, *pRight;
            char *zName = pTab->aCol[j].zName;
            char *zColname;  /* The computed column name */
            char *zToFree;   /* Malloced string that needs to be freed */
            Token sColname;  /* Computed column name as a token */

            /* If a column is marked as 'hidden' (currently only possible
            ** for virtual tables), do not include it in the expanded
            ** result-set list.
            */
            if( IsHiddenColumn(&pTab->aCol[j]) ){
              assert(IsVirtual(pTab));
              continue;
            }

            if( i>0 && zTName==0 ){
              struct SrcList_item *pLeft = &pTabList->a[i-1];
              if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
                        columnIndex(pLeft->pTab, zName)>=0 ){
                /* In a NATURAL join, omit the join columns from the 
                ** table on the right */
                continue;
              }
              if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
                /* In a join with a USING clause, omit columns in the
                ** using clause from the table on the right. */
                continue;
              }
            }
            pRight = sqlite3Expr(db, TK_ID, zName);
            zColname = zName;
            zToFree = 0;
            if( longNames || pTabList->nSrc>1 ){
              Expr *pLeft;
              pLeft = sqlite3Expr(db, TK_ID, zTabName);
              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
              if( longNames ){
                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
                zToFree = zColname;
              }
            }else{
              pExpr = pRight;
            }
            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
            sColname.z = zColname;
            sColname.n = sqlite3Strlen30(zColname);
            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
            sqlite3DbFree(db, zToFree);
          }
        }
        if( !tableSeen ){
          if( zTName ){
            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
          }else{
            sqlite3ErrorMsg(pParse, "no tables specified");
          }
        }
      }
    }
    sqlite3ExprListDelete(db, pEList);
    p->pEList = pNew;
  }
#if SQLITE_MAX_COLUMN
  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
    sqlite3ErrorMsg(pParse, "too many columns in result set");
  }
#endif
  return WRC_Continue;
}

/*
** No-op routine for the parse-tree walker.
**
** When this routine is the Walker.xExprCallback then expression trees
** are walked without any actions being taken at each node.  Presumably,
** when this routine is used for Walker.xExprCallback then 
** Walker.xSelectCallback is set to do something useful for every 
** subquery in the parser tree.
*/
static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  return WRC_Continue;
}

/*
** This routine "expands" a SELECT statement and all of its subqueries.
** For additional information on what it means to "expand" a SELECT
** statement, see the comment on the selectExpand worker callback above.
**
** Expanding a SELECT statement is the first step in processing a
** SELECT statement.  The SELECT statement must be expanded before
** name resolution is performed.
**
** If anything goes wrong, an error message is written into pParse.
** The calling function can detect the problem by looking at pParse->nErr
** and/or pParse->db->mallocFailed.
*/
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  Walker w;
  w.xSelectCallback = selectExpander;
  w.xExprCallback = exprWalkNoop;
  w.pParse = pParse;
  sqlite3WalkSelect(&w, pSelect);
}


#ifndef SQLITE_OMIT_SUBQUERY
/*
** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
** interface.
**
** For each FROM-clause subquery, add Column.zType and Column.zColl
** information to the Table structure that represents the result set
** of that subquery.
**
** The Table structure that represents the result set was constructed
** by selectExpander() but the type and collation information was omitted
** at that point because identifiers had not yet been resolved.  This
** routine is called after identifier resolution.
*/
static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  Parse *pParse;
  int i;
  SrcList *pTabList;
  struct SrcList_item *pFrom;

  assert( p->selFlags & SF_Resolved );
  assert( (p->selFlags & SF_HasTypeInfo)==0 );
  p->selFlags |= SF_HasTypeInfo;
  pParse = pWalker->pParse;
  pTabList = p->pSrc;
  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
    Table *pTab = pFrom->pTab;
    if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
      /* A sub-query in the FROM clause of a SELECT */
      Select *pSel = pFrom->pSelect;
      assert( pSel );
      while( pSel->pPrior ) pSel = pSel->pPrior;
      selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
    }
  }
  return WRC_Continue;
}
#endif


/*
** This routine adds datatype and collating sequence information to
** the Table structures of all FROM-clause subqueries in a
** SELECT statement.
**
** Use this routine after name resolution.
*/
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
#ifndef SQLITE_OMIT_SUBQUERY
  Walker w;
  w.xSelectCallback = selectAddSubqueryTypeInfo;
  w.xExprCallback = exprWalkNoop;
  w.pParse = pParse;
  sqlite3WalkSelect(&w, pSelect);
#endif
}


/*
** This routine sets of a SELECT statement for processing.  The
** following is accomplished:
**
**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
**     *  ON and USING clauses are shifted into WHERE statements
**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
**     *  Identifiers in expression are matched to tables.
**
** This routine acts recursively on all subqueries within the SELECT.
*/
void sqlite3SelectPrep(
  Parse *pParse,         /* The parser context */
  Select *p,             /* The SELECT statement being coded. */
  NameContext *pOuterNC  /* Name context for container */
){
  sqlite3 *db;
  if( NEVER(p==0) ) return;
  db = pParse->db;
  if( p->selFlags & SF_HasTypeInfo ) return;
  sqlite3SelectExpand(pParse, p);
  if( pParse->nErr || db->mallocFailed ) return;
  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  if( pParse->nErr || db->mallocFailed ) return;
  sqlite3SelectAddTypeInfo(pParse, p);
}

/*
** Reset the aggregate accumulator.
**
** The aggregate accumulator is a set of memory cells that hold
** intermediate results while calculating an aggregate.  This
** routine simply stores NULLs in all of those memory cells.
*/
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  Vdbe *v = pParse->pVdbe;
  int i;
  struct AggInfo_func *pFunc;
  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
    return;
  }
  for(i=0; i<pAggInfo->nColumn; i++){
    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  }
  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
    if( pFunc->iDistinct>=0 ){
      Expr *pE = pFunc->pExpr;
      assert( !ExprHasProperty(pE, EP_xIsSelect) );
      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
           "argument");
        pFunc->iDistinct = -1;
      }else{
        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
      }
    }
  }
}

/*
** Invoke the OP_AggFinalize opcode for every aggregate function
** in the AggInfo structure.
*/
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  Vdbe *v = pParse->pVdbe;
  int i;
  struct AggInfo_func *pF;
  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
    ExprList *pList = pF->pExpr->x.pList;
    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
                      (void*)pF->pFunc, P4_FUNCDEF);
  }
}

/*
** Update the accumulator memory cells for an aggregate based on
** the current cursor position.
*/
static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  Vdbe *v = pParse->pVdbe;
  int i;
  struct AggInfo_func *pF;
  struct AggInfo_col *pC;

  pAggInfo->directMode = 1;
  sqlite3ExprCacheClear(pParse);
  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
    int nArg;
    int addrNext = 0;
    int regAgg;
    ExprList *pList = pF->pExpr->x.pList;
    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
    if( pList ){
      nArg = pList->nExpr;
      regAgg = sqlite3GetTempRange(pParse, nArg);
      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
    }else{
      nArg = 0;
      regAgg = 0;
    }
    if( pF->iDistinct>=0 ){
      addrNext = sqlite3VdbeMakeLabel(v);
      assert( nArg==1 );
      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
    }
    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
      CollSeq *pColl = 0;
      struct ExprList_item *pItem;
      int j;
      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
      }
      if( !pColl ){
        pColl = pParse->db->pDfltColl;
      }
      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
    }
    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
                      (void*)pF->pFunc, P4_FUNCDEF);
    sqlite3VdbeChangeP5(v, (u8)nArg);
    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
    if( addrNext ){
      sqlite3VdbeResolveLabel(v, addrNext);
      sqlite3ExprCacheClear(pParse);
    }
  }
  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  }
  pAggInfo->directMode = 0;
  sqlite3ExprCacheClear(pParse);
}

/*
** Generate code for the SELECT statement given in the p argument.  
**
** The results are distributed in various ways depending on the
** contents of the SelectDest structure pointed to by argument pDest
** as follows:
**
**     pDest->eDest    Result
**     ------------    -------------------------------------------
**     SRT_Output      Generate a row of output (using the OP_ResultRow
**                     opcode) for each row in the result set.
**
**     SRT_Mem         Only valid if the result is a single column.
**                     Store the first column of the first result row
**                     in register pDest->iParm then abandon the rest
**                     of the query.  This destination implies "LIMIT 1".
**
**     SRT_Set         The result must be a single column.  Store each
**                     row of result as the key in table pDest->iParm. 
**                     Apply the affinity pDest->affinity before storing
**                     results.  Used to implement "IN (SELECT ...)".
**
**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
**
**     SRT_Except      Remove results from the temporary table pDest->iParm.
**
**     SRT_Table       Store results in temporary table pDest->iParm.
**                     This is like SRT_EphemTab except that the table
**                     is assumed to already be open.
**
**     SRT_EphemTab    Create an temporary table pDest->iParm and store
**                     the result there. The cursor is left open after
**                     returning.  This is like SRT_Table except that
**                     this destination uses OP_OpenEphemeral to create
**                     the table first.
**
**     SRT_Coroutine   Generate a co-routine that returns a new row of
**                     results each time it is invoked.  The entry point
**                     of the co-routine is stored in register pDest->iParm.
**
**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
**                     set is not empty.
**
**     SRT_Discard     Throw the results away.  This is used by SELECT
**                     statements within triggers whose only purpose is
**                     the side-effects of functions.
**
** This routine returns the number of errors.  If any errors are
** encountered, then an appropriate error message is left in
** pParse->zErrMsg.
**
** This routine does NOT free the Select structure passed in.  The
** calling function needs to do that.
*/
int sqlite3Select(
  Parse *pParse,         /* The parser context */
  Select *p,             /* The SELECT statement being coded. */
  SelectDest *pDest      /* What to do with the query results */
){
  int i, j;              /* Loop counters */
  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
  Vdbe *v;               /* The virtual machine under construction */
  int isAgg;             /* True for select lists like "count(*)" */
  ExprList *pEList;      /* List of columns to extract. */
  SrcList *pTabList;     /* List of tables to select from */
  Expr *pWhere;          /* The WHERE clause.  May be NULL */
  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
  Expr *pHaving;         /* The HAVING clause.  May be NULL */
  int isDistinct;        /* True if the DISTINCT keyword is present */
  int distinct;          /* Table to use for the distinct set */
  int rc = 1;            /* Value to return from this function */
  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
  AggInfo sAggInfo;      /* Information used by aggregate queries */
  int iEnd;              /* Address of the end of the query */
  sqlite3 *db;           /* The database connection */

  db = pParse->db;
  if( p==0 || db->mallocFailed || pParse->nErr ){
    return 1;
  }
  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  memset(&sAggInfo, 0, sizeof(sAggInfo));

  if( IgnorableOrderby(pDest) ){
    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
    /* If ORDER BY makes no difference in the output then neither does
    ** DISTINCT so it can be removed too. */
    sqlite3ExprListDelete(db, p->pOrderBy);
    p->pOrderBy = 0;
    p->selFlags &= ~SF_Distinct;
  }
  sqlite3SelectPrep(pParse, p, 0);
  pOrderBy = p->pOrderBy;
  pTabList = p->pSrc;
  pEList = p->pEList;
  if( pParse->nErr || db->mallocFailed ){
    goto select_end;
  }
  isAgg = (p->selFlags & SF_Aggregate)!=0;
  assert( pEList!=0 );

  /* Begin generating code.
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ) goto select_end;

  /* Generate code for all sub-queries in the FROM clause
  */
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
    struct SrcList_item *pItem = &pTabList->a[i];
    SelectDest dest;
    Select *pSub = pItem->pSelect;
    int isAggSub;

    if( pSub==0 || pItem->isPopulated ) continue;

    /* Increment Parse.nHeight by the height of the largest expression
    ** tree refered to by this, the parent select. The child select
    ** may contain expression trees of at most
    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
    ** more conservative than necessary, but much easier than enforcing
    ** an exact limit.
    */
    pParse->nHeight += sqlite3SelectExprHeight(p);

    /* Check to see if the subquery can be absorbed into the parent. */
    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
      if( isAggSub ){
        isAgg = 1;
        p->selFlags |= SF_Aggregate;
      }
      i = -1;
    }else{
      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
      assert( pItem->isPopulated==0 );
      sqlite3Select(pParse, pSub, &dest);
      pItem->isPopulated = 1;
    }
    if( /*pParse->nErr ||*/ db->mallocFailed ){
      goto select_end;
    }
    pParse->nHeight -= sqlite3SelectExprHeight(p);
    pTabList = p->pSrc;
    if( !IgnorableOrderby(pDest) ){
      pOrderBy = p->pOrderBy;
    }
  }
  pEList = p->pEList;
#endif
  pWhere = p->pWhere;
  pGroupBy = p->pGroupBy;
  pHaving = p->pHaving;
  isDistinct = (p->selFlags & SF_Distinct)!=0;

#ifndef SQLITE_OMIT_COMPOUND_SELECT
  /* If there is are a sequence of queries, do the earlier ones first.
  */
  if( p->pPrior ){
    if( p->pRightmost==0 ){
      Select *pLoop, *pRight = 0;
      int cnt = 0;
      int mxSelect;
      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
        pLoop->pRightmost = p;
        pLoop->pNext = pRight;
        pRight = pLoop;
      }
      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
      if( mxSelect && cnt>mxSelect ){
        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
        return 1;
      }
    }
    return multiSelect(pParse, p, pDest);
  }
#endif

  /* If writing to memory or generating a set
  ** only a single column may be output.
  */
#ifndef SQLITE_OMIT_SUBQUERY
  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
    goto select_end;
  }
#endif

  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
  ** GROUP BY might use an index, DISTINCT never does.
  */
  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
    pGroupBy = p->pGroupBy;
    p->selFlags &= ~SF_Distinct;
    isDistinct = 0;
  }

  /* If there is an ORDER BY clause, then this sorting
  ** index might end up being unused if the data can be 
  ** extracted in pre-sorted order.  If that is the case, then the
  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  ** we figure out that the sorting index is not needed.  The addrSortIndex
  ** variable is used to facilitate that change.
  */
  if( pOrderBy ){
    KeyInfo *pKeyInfo;
    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
    pOrderBy->iECursor = pParse->nTab++;
    p->addrOpenEphm[2] = addrSortIndex =
      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  }else{
    addrSortIndex = -1;
  }

  /* If the output is destined for a temporary table, open that table.
  */
  if( pDest->eDest==SRT_EphemTab ){
    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
  }

  /* Set the limiter.
  */
  iEnd = sqlite3VdbeMakeLabel(v);
  computeLimitRegisters(pParse, p, iEnd);

  /* Open a virtual index to use for the distinct set.
  */
  if( isDistinct ){
    KeyInfo *pKeyInfo;
    assert( isAgg || pGroupBy );
    distinct = pParse->nTab++;
    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  }else{
    distinct = -1;
  }

  /* Aggregate and non-aggregate queries are handled differently */
  if( !isAgg && pGroupBy==0 ){
    /* This case is for non-aggregate queries
    ** Begin the database scan
    */
    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
    if( pWInfo==0 ) goto select_end;

    /* If sorting index that was created by a prior OP_OpenEphemeral 
    ** instruction ended up not being needed, then change the OP_OpenEphemeral
    ** into an OP_Noop.
    */
    if( addrSortIndex>=0 && pOrderBy==0 ){
      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
      p->addrOpenEphm[2] = -1;
    }

    /* Use the standard inner loop
    */
    assert(!isDistinct);
    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
                    pWInfo->iContinue, pWInfo->iBreak);

    /* End the database scan loop.
    */
    sqlite3WhereEnd(pWInfo);
  }else{
    /* This is the processing for aggregate queries */
    NameContext sNC;    /* Name context for processing aggregate information */
    int iAMem;          /* First Mem address for storing current GROUP BY */
    int iBMem;          /* First Mem address for previous GROUP BY */
    int iUseFlag;       /* Mem address holding flag indicating that at least
                        ** one row of the input to the aggregator has been
                        ** processed */
    int iAbortFlag;     /* Mem address which causes query abort if positive */
    int groupBySort;    /* Rows come from source in GROUP BY order */
    int addrEnd;        /* End of processing for this SELECT */

    /* Remove any and all aliases between the result set and the
    ** GROUP BY clause.
    */
    if( pGroupBy ){
      int k;                        /* Loop counter */
      struct ExprList_item *pItem;  /* For looping over expression in a list */

      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
        pItem->iAlias = 0;
      }
      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
        pItem->iAlias = 0;
      }
    }

 
    /* Create a label to jump to when we want to abort the query */
    addrEnd = sqlite3VdbeMakeLabel(v);

    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
    ** SELECT statement.
    */
    memset(&sNC, 0, sizeof(sNC));
    sNC.pParse = pParse;
    sNC.pSrcList = pTabList;
    sNC.pAggInfo = &sAggInfo;
    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
    sAggInfo.pGroupBy = pGroupBy;
    sqlite3ExprAnalyzeAggList(&sNC, pEList);
    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
    if( pHaving ){
      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
    }
    sAggInfo.nAccumulator = sAggInfo.nColumn;
    for(i=0; i<sAggInfo.nFunc; i++){
      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
    }
    if( db->mallocFailed ) goto select_end;

    /* Processing for aggregates with GROUP BY is very different and
    ** much more complex than aggregates without a GROUP BY.
    */
    if( pGroupBy ){
      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
      int j1;             /* A-vs-B comparision jump */
      int addrOutputRow;  /* Start of subroutine that outputs a result row */
      int regOutputRow;   /* Return address register for output subroutine */
      int addrSetAbort;   /* Set the abort flag and return */
      int addrTopOfLoop;  /* Top of the input loop */
      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
      int addrReset;      /* Subroutine for resetting the accumulator */
      int regReset;       /* Return address register for reset subroutine */

      /* If there is a GROUP BY clause we might need a sorting index to
      ** implement it.  Allocate that sorting index now.  If it turns out
      ** that we do not need it after all, the OpenEphemeral instruction
      ** will be converted into a Noop.  
      */
      sAggInfo.sortingIdx = pParse->nTab++;
      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
          sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);

      /* Initialize memory locations used by GROUP BY aggregate processing
      */
      iUseFlag = ++pParse->nMem;
      iAbortFlag = ++pParse->nMem;
      regOutputRow = ++pParse->nMem;
      addrOutputRow = sqlite3VdbeMakeLabel(v);
      regReset = ++pParse->nMem;
      addrReset = sqlite3VdbeMakeLabel(v);
      iAMem = pParse->nMem + 1;
      pParse->nMem += pGroupBy->nExpr;
      iBMem = pParse->nMem + 1;
      pParse->nMem += pGroupBy->nExpr;
      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
      VdbeComment((v, "clear abort flag"));
      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
      VdbeComment((v, "indicate accumulator empty"));

      /* Begin a loop that will extract all source rows in GROUP BY order.
      ** This might involve two separate loops with an OP_Sort in between, or
      ** it might be a single loop that uses an index to extract information
      ** in the right order to begin with.
      */
      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
      if( pWInfo==0 ) goto select_end;
      if( pGroupBy==0 ){
        /* The optimizer is able to deliver rows in group by order so
        ** we do not have to sort.  The OP_OpenEphemeral table will be
        ** cancelled later because we still need to use the pKeyInfo
        */
        pGroupBy = p->pGroupBy;
        groupBySort = 0;
      }else{
        /* Rows are coming out in undetermined order.  We have to push
        ** each row into a sorting index, terminate the first loop,
        ** then loop over the sorting index in order to get the output
        ** in sorted order
        */
        int regBase;
        int regRecord;
        int nCol;
        int nGroupBy;

        groupBySort = 1;
        nGroupBy = pGroupBy->nExpr;
        nCol = nGroupBy + 1;
        j = nGroupBy+1;
        for(i=0; i<sAggInfo.nColumn; i++){
          if( sAggInfo.aCol[i].iSorterColumn>=j ){
            nCol++;
            j++;
          }
        }
        regBase = sqlite3GetTempRange(pParse, nCol);
        sqlite3ExprCacheClear(pParse);
        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
        j = nGroupBy+1;
        for(i=0; i<sAggInfo.nColumn; i++){
          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
          if( pCol->iSorterColumn>=j ){
            int r1 = j + regBase;
            int r2;

            r2 = sqlite3ExprCodeGetColumn(pParse, 
                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
            if( r1!=r2 ){
              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
            }
            j++;
          }
        }
        regRecord = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
        sqlite3ReleaseTempReg(pParse, regRecord);
        sqlite3ReleaseTempRange(pParse, regBase, nCol);
        sqlite3WhereEnd(pWInfo);
        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
        VdbeComment((v, "GROUP BY sort"));
        sAggInfo.useSortingIdx = 1;
        sqlite3ExprCacheClear(pParse);
      }

      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
      ** Then compare the current GROUP BY terms against the GROUP BY terms
      ** from the previous row currently stored in a0, a1, a2...
      */
      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
      sqlite3ExprCacheClear(pParse);
      for(j=0; j<pGroupBy->nExpr; j++){
        if( groupBySort ){
          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
        }else{
          sAggInfo.directMode = 1;
          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
        }
      }
      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
                          (char*)pKeyInfo, P4_KEYINFO);
      j1 = sqlite3VdbeCurrentAddr(v);
      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);

      /* Generate code that runs whenever the GROUP BY changes.
      ** Changes in the GROUP BY are detected by the previous code
      ** block.  If there were no changes, this block is skipped.
      **
      ** This code copies current group by terms in b0,b1,b2,...
      ** over to a0,a1,a2.  It then calls the output subroutine
      ** and resets the aggregate accumulator registers in preparation
      ** for the next GROUP BY batch.
      */
      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
      VdbeComment((v, "output one row"));
      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
      VdbeComment((v, "check abort flag"));
      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
      VdbeComment((v, "reset accumulator"));

      /* Update the aggregate accumulators based on the content of
      ** the current row
      */
      sqlite3VdbeJumpHere(v, j1);
      updateAccumulator(pParse, &sAggInfo);
      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
      VdbeComment((v, "indicate data in accumulator"));

      /* End of the loop
      */
      if( groupBySort ){
        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
      }else{
        sqlite3WhereEnd(pWInfo);
        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
      }

      /* Output the final row of result
      */
      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
      VdbeComment((v, "output final row"));

      /* Jump over the subroutines
      */
      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);

      /* Generate a subroutine that outputs a single row of the result
      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
      ** is less than or equal to zero, the subroutine is a no-op.  If
      ** the processing calls for the query to abort, this subroutine
      ** increments the iAbortFlag memory location before returning in
      ** order to signal the caller to abort.
      */
      addrSetAbort = sqlite3VdbeCurrentAddr(v);
      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
      VdbeComment((v, "set abort flag"));
      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
      sqlite3VdbeResolveLabel(v, addrOutputRow);
      addrOutputRow = sqlite3VdbeCurrentAddr(v);
      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
      VdbeComment((v, "Groupby result generator entry point"));
      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
      finalizeAggFunctions(pParse, &sAggInfo);
      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
                      distinct, pDest,
                      addrOutputRow+1, addrSetAbort);
      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
      VdbeComment((v, "end groupby result generator"));

      /* Generate a subroutine that will reset the group-by accumulator
      */
      sqlite3VdbeResolveLabel(v, addrReset);
      resetAccumulator(pParse, &sAggInfo);
      sqlite3VdbeAddOp1(v, OP_Return, regReset);
     
    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
    else {
      ExprList *pDel = 0;
#ifndef SQLITE_OMIT_BTREECOUNT
      Table *pTab;
      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
        /* If isSimpleCount() returns a pointer to a Table structure, then
        ** the SQL statement is of the form:
        **
        **   SELECT count(*) FROM <tbl>
        **
        ** where the Table structure returned represents table <tbl>.
        **
        ** This statement is so common that it is optimized specially. The
        ** OP_Count instruction is executed either on the intkey table that
        ** contains the data for table <tbl> or on one of its indexes. It
        ** is better to execute the op on an index, as indexes are almost
        ** always spread across less pages than their corresponding tables.
        */
        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
        Index *pIdx;                         /* Iterator variable */
        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
        Index *pBest = 0;                    /* Best index found so far */
        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */

        sqlite3CodeVerifySchema(pParse, iDb);
        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);

        /* Search for the index that has the least amount of columns. If
        ** there is such an index, and it has less columns than the table
        ** does, then we can assume that it consumes less space on disk and
        ** will therefore be cheaper to scan to determine the query result.
        ** In this case set iRoot to the root page number of the index b-tree
        ** and pKeyInfo to the KeyInfo structure required to navigate the
        ** index.
        **
        ** In practice the KeyInfo structure will not be used. It is only 
        ** passed to keep OP_OpenRead happy.
        */
        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
          if( !pBest || pIdx->nColumn<pBest->nColumn ){
            pBest = pIdx;
          }
        }
        if( pBest && pBest->nColumn<pTab->nCol ){
          iRoot = pBest->tnum;
          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
        }

        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
        if( pKeyInfo ){
          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
        }
        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
      }else
#endif /* SQLITE_OMIT_BTREECOUNT */
      {
        /* Check if the query is of one of the following forms:
        **
        **   SELECT min(x) FROM ...
        **   SELECT max(x) FROM ...
        **
        ** If it is, then ask the code in where.c to attempt to sort results
        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
        ** If where.c is able to produce results sorted in this order, then
        ** add vdbe code to break out of the processing loop after the 
        ** first iteration (since the first iteration of the loop is 
        ** guaranteed to operate on the row with the minimum or maximum 
        ** value of x, the only row required).
        **
        ** A special flag must be passed to sqlite3WhereBegin() to slightly
        ** modify behaviour as follows:
        **
        **   + If the query is a "SELECT min(x)", then the loop coded by
        **     where.c should not iterate over any values with a NULL value
        **     for x.
        **
        **   + The optimizer code in where.c (the thing that decides which
        **     index or indices to use) should place a different priority on 
        **     satisfying the 'ORDER BY' clause than it does in other cases.
        **     Refer to code and comments in where.c for details.
        */
        ExprList *pMinMax = 0;
        u8 flag = minMaxQuery(p);
        if( flag ){
          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
          pDel = pMinMax;
          if( pMinMax && !db->mallocFailed ){
            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
            pMinMax->a[0].pExpr->op = TK_COLUMN;
          }
        }
  
        /* This case runs if the aggregate has no GROUP BY clause.  The
        ** processing is much simpler since there is only a single row
        ** of output.
        */
        resetAccumulator(pParse, &sAggInfo);
        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
        if( pWInfo==0 ){
          sqlite3ExprListDelete(db, pDel);
          goto select_end;
        }
        updateAccumulator(pParse, &sAggInfo);
        if( !pMinMax && flag ){
          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
          VdbeComment((v, "%s() by index",
                (flag==WHERE_ORDERBY_MIN?"min":"max")));
        }
        sqlite3WhereEnd(pWInfo);
        finalizeAggFunctions(pParse, &sAggInfo);
      }

      pOrderBy = 0;
      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
                      pDest, addrEnd, addrEnd);
      sqlite3ExprListDelete(db, pDel);
    }
    sqlite3VdbeResolveLabel(v, addrEnd);
    
  } /* endif aggregate query */

  /* If there is an ORDER BY clause, then we need to sort the results
  ** and send them to the callback one by one.
  */
  if( pOrderBy ){
    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  }

  /* Jump here to skip this query
  */
  sqlite3VdbeResolveLabel(v, iEnd);

  /* The SELECT was successfully coded.   Set the return code to 0
  ** to indicate no errors.
  */
  rc = 0;

  /* Control jumps to here if an error is encountered above, or upon
  ** successful coding of the SELECT.
  */
select_end:

  /* Identify column names if results of the SELECT are to be output.
  */
  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
    generateColumnNames(pParse, pTabList, pEList);
  }

  sqlite3DbFree(db, sAggInfo.aCol);
  sqlite3DbFree(db, sAggInfo.aFunc);
  return rc;
}

#if defined(SQLITE_DEBUG)
/*
*******************************************************************************
** The following code is used for testing and debugging only.  The code
** that follows does not appear in normal builds.
**
** These routines are used to print out the content of all or part of a 
** parse structures such as Select or Expr.  Such printouts are useful
** for helping to understand what is happening inside the code generator
** during the execution of complex SELECT statements.
**
** These routine are not called anywhere from within the normal
** code base.  Then are intended to be called from within the debugger
** or from temporary "printf" statements inserted for debugging.
*/
void sqlite3PrintExpr(Expr *p){
  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
    sqlite3DebugPrintf("(%s", p->u.zToken);
  }else{
    sqlite3DebugPrintf("(%d", p->op);
  }
  if( p->pLeft ){
    sqlite3DebugPrintf(" ");
    sqlite3PrintExpr(p->pLeft);
  }
  if( p->pRight ){
    sqlite3DebugPrintf(" ");
    sqlite3PrintExpr(p->pRight);
  }
  sqlite3DebugPrintf(")");
}
void sqlite3PrintExprList(ExprList *pList){
  int i;
  for(i=0; i<pList->nExpr; i++){
    sqlite3PrintExpr(pList->a[i].pExpr);
    if( i<pList->nExpr-1 ){
      sqlite3DebugPrintf(", ");
    }
  }
}
void sqlite3PrintSelect(Select *p, int indent){
  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  sqlite3PrintExprList(p->pEList);
  sqlite3DebugPrintf("\n");
  if( p->pSrc ){
    char *zPrefix;
    int i;
    zPrefix = "FROM";
    for(i=0; i<p->pSrc->nSrc; i++){
      struct SrcList_item *pItem = &p->pSrc->a[i];
      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
      zPrefix = "";
      if( pItem->pSelect ){
        sqlite3DebugPrintf("(\n");
        sqlite3PrintSelect(pItem->pSelect, indent+10);
        sqlite3DebugPrintf("%*s)", indent+8, "");
      }else if( pItem->zName ){
        sqlite3DebugPrintf("%s", pItem->zName);
      }
      if( pItem->pTab ){
        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
      }
      if( pItem->zAlias ){
        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
      }
      if( i<p->pSrc->nSrc-1 ){
        sqlite3DebugPrintf(",");
      }
      sqlite3DebugPrintf("\n");
    }
  }
  if( p->pWhere ){
    sqlite3DebugPrintf("%*s WHERE ", indent, "");
    sqlite3PrintExpr(p->pWhere);
    sqlite3DebugPrintf("\n");
  }
  if( p->pGroupBy ){
    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
    sqlite3PrintExprList(p->pGroupBy);
    sqlite3DebugPrintf("\n");
  }
  if( p->pHaving ){
    sqlite3DebugPrintf("%*s HAVING ", indent, "");
    sqlite3PrintExpr(p->pHaving);
    sqlite3DebugPrintf("\n");
  }
  if( p->pOrderBy ){
    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
    sqlite3PrintExprList(p->pOrderBy);
    sqlite3DebugPrintf("\n");
  }
}
/* End of the structure debug printing code
*****************************************************************************/
#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */

Added src/shell.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement the "sqlite" command line
** utility for accessing SQLite databases.
**
** $Id: shell.c,v 1.210 2009/05/31 17:16:10 drh Exp $
*/
#if defined(_WIN32) || defined(WIN32)
/* This needs to come before any includes for MSVC compiler */
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "sqlite3.h"
#include <ctype.h>
#include <stdarg.h>

#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
# include <signal.h>
# if !defined(__RTP__) && !defined(_WRS_KERNEL)
#  include <pwd.h>
# endif
# include <unistd.h>
# include <sys/types.h>
#endif

#ifdef __OS2__
# include <unistd.h>
#endif

#if defined(HAVE_READLINE) && HAVE_READLINE==1
# include <readline/readline.h>
# include <readline/history.h>
#else
# define readline(p) local_getline(p,stdin)
# define add_history(X)
# define read_history(X)
# define write_history(X)
# define stifle_history(X)
#endif

#if defined(_WIN32) || defined(WIN32)
# include <io.h>
#define isatty(h) _isatty(h)
#define access(f,m) _access((f),(m))
#else
/* Make sure isatty() has a prototype.
*/
extern int isatty();
#endif

#if defined(_WIN32_WCE)
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
 * thus we always assume that we have a console. That can be
 * overridden with the -batch command line option.
 */
#define isatty(x) 1
#endif

#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL)
#include <sys/time.h>
#include <sys/resource.h>

/* Saved resource information for the beginning of an operation */
static struct rusage sBegin;

/* True if the timer is enabled */
static int enableTimer = 0;

/*
** Begin timing an operation
*/
static void beginTimer(void){
  if( enableTimer ){
    getrusage(RUSAGE_SELF, &sBegin);
  }
}

/* Return the difference of two time_structs in seconds */
static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 
         (double)(pEnd->tv_sec - pStart->tv_sec);
}

/*
** Print the timing results.
*/
static void endTimer(void){
  if( enableTimer ){
    struct rusage sEnd;
    getrusage(RUSAGE_SELF, &sEnd);
    printf("CPU Time: user %f sys %f\n",
       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  }
}

#define BEGIN_TIMER beginTimer()
#define END_TIMER endTimer()
#define HAS_TIMER 1

#elif (defined(_WIN32) || defined(WIN32))

#include <windows.h>

/* Saved resource information for the beginning of an operation */
static HANDLE hProcess;
static FILETIME ftKernelBegin;
static FILETIME ftUserBegin;
typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
static GETPROCTIMES getProcessTimesAddr = NULL;

/* True if the timer is enabled */
static int enableTimer = 0;

/*
** Check to see if we have timer support.  Return 1 if necessary
** support found (or found previously).
*/
static int hasTimer(void){
  if( getProcessTimesAddr ){
    return 1;
  } else {
    /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
    ** See if the version we are running on has it, and if it does, save off
    ** a pointer to it and the current process handle.
    */
    hProcess = GetCurrentProcess();
    if( hProcess ){
      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
      if( NULL != hinstLib ){
        getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
        if( NULL != getProcessTimesAddr ){
          return 1;
        }
        FreeLibrary(hinstLib); 
      }
    }
  }
  return 0;
}

/*
** Begin timing an operation
*/
static void beginTimer(void){
  if( enableTimer && getProcessTimesAddr ){
    FILETIME ftCreation, ftExit;
    getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
  }
}

/* Return the difference of two FILETIME structs in seconds */
static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  return (double) ((i64End - i64Start) / 10000000.0);
}

/*
** Print the timing results.
*/
static void endTimer(void){
  if( enableTimer && getProcessTimesAddr){
    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
    getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
    printf("CPU Time: user %f sys %f\n",
       timeDiff(&ftUserBegin, &ftUserEnd),
       timeDiff(&ftKernelBegin, &ftKernelEnd));
  }
}

#define BEGIN_TIMER beginTimer()
#define END_TIMER endTimer()
#define HAS_TIMER hasTimer()

#else
#define BEGIN_TIMER 
#define END_TIMER
#define HAS_TIMER 0
#endif

/*
** Used to prevent warnings about unused parameters
*/
#define UNUSED_PARAMETER(x) (void)(x)


/**************************************************************************
***************************************************************************
** Begin genfkey logic.
*/
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined SQLITE_OMIT_SUBQUERY

#define GENFKEY_ERROR         1
#define GENFKEY_DROPTRIGGER   2
#define GENFKEY_CREATETRIGGER 3
static int genfkey_create_triggers(sqlite3 *, const char *, void *,
  int (*)(void *, int, const char *)
);

struct GenfkeyCb {
  void *pCtx;
  int eType;
  int (*xData)(void *, int, const char *);
};
typedef struct GenfkeyCb GenfkeyCb;

/* The code in this file defines a sqlite3 virtual-table module that
** provides a read-only view of the current database schema. There is one
** row in the schema table for each column in the database schema.
*/
#define SCHEMA \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "tablename,"         /* Name of table */                                   \
  "cid,"               /* Column number (from left-to-right, 0 upward) */    \
  "name,"              /* Column name */                                     \
  "type,"              /* Specified type (i.e. VARCHAR(32)) */               \
  "not_null,"          /* Boolean. True if NOT NULL was specified */         \
  "dflt_value,"        /* Default value for this column */                   \
  "pk"                 /* True if this column is part of the primary key */  \
")"

#define SCHEMA2 \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "from_tbl,"          /* Name of table */                                   \
  "fkid,"                                                                    \
  "seq,"                                                                     \
  "to_tbl,"                                                                  \
  "from_col,"                                                                \
  "to_col,"                                                                  \
  "on_update,"                                                               \
  "on_delete,"                                                               \
  "match"                                                                    \
")"

#define SCHEMA3 \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "tablename,"         /* Name of table */                                   \
  "seq,"                                                                     \
  "name,"                                                                    \
  "isunique"                                                                 \
")"

#define SCHEMA4 \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "indexname,"         /* Name of table */                                   \
  "seqno,"                                                                   \
  "cid,"                                                                     \
  "name"                                                                     \
")"

#define SCHEMA5 \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "triggername,"       /* Name of trigger */                                 \
  "dummy"              /* Unused */                                          \
")"

typedef struct SchemaTable SchemaTable;
static struct SchemaTable {
  const char *zName;
  const char *zObject;
  const char *zPragma;
  const char *zSchema;
} aSchemaTable[] = {
  { "table_info",       "table", "PRAGMA %Q.table_info(%Q)",       SCHEMA },
  { "foreign_key_list", "table", "PRAGMA %Q.foreign_key_list(%Q)", SCHEMA2 },
  { "index_list",       "table", "PRAGMA %Q.index_list(%Q)",       SCHEMA3 },
  { "index_info",       "index", "PRAGMA %Q.index_info(%Q)",       SCHEMA4 },
  { "trigger_list",     "trigger", "SELECT 1",                     SCHEMA5 },
  { 0, 0, 0, 0 }
};

typedef struct schema_vtab schema_vtab;
typedef struct schema_cursor schema_cursor;

/* A schema table object */
struct schema_vtab {
  sqlite3_vtab base;
  sqlite3 *db;
  SchemaTable *pType;
};

/* A schema table cursor object */
struct schema_cursor {
  sqlite3_vtab_cursor base;
  sqlite3_stmt *pDbList;
  sqlite3_stmt *pTableList;
  sqlite3_stmt *pColumnList;
  int rowid;
};

/*
** Table destructor for the schema module.
*/
static int schemaDestroy(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return 0;
}

/*
** Table constructor for the schema module.
*/
static int schemaCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  int rc = SQLITE_NOMEM;
  schema_vtab *pVtab;
  SchemaTable *pType = &aSchemaTable[0];

  UNUSED_PARAMETER(pzErr);
  if( argc>3 ){
    int i;
    pType = 0;
    for(i=0; aSchemaTable[i].zName; i++){ 
      if( 0==strcmp(argv[3], aSchemaTable[i].zName) ){
        pType = &aSchemaTable[i];
      }
    }
    if( !pType ){
      return SQLITE_ERROR;
    }
  }

  pVtab = sqlite3_malloc(sizeof(schema_vtab));
  if( pVtab ){
    memset(pVtab, 0, sizeof(schema_vtab));
    pVtab->db = (sqlite3 *)pAux;
    pVtab->pType = pType;
    rc = sqlite3_declare_vtab(db, pType->zSchema);
  }
  *ppVtab = (sqlite3_vtab *)pVtab;
  return rc;
}

/*
** Open a new cursor on the schema table.
*/
static int schemaOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  int rc = SQLITE_NOMEM;
  schema_cursor *pCur;
  UNUSED_PARAMETER(pVTab);
  pCur = sqlite3_malloc(sizeof(schema_cursor));
  if( pCur ){
    memset(pCur, 0, sizeof(schema_cursor));
    *ppCursor = (sqlite3_vtab_cursor *)pCur;
    rc = SQLITE_OK;
  }
  return rc;
}

/*
** Close a schema table cursor.
*/
static int schemaClose(sqlite3_vtab_cursor *cur){
  schema_cursor *pCur = (schema_cursor *)cur;
  sqlite3_finalize(pCur->pDbList);
  sqlite3_finalize(pCur->pTableList);
  sqlite3_finalize(pCur->pColumnList);
  sqlite3_free(pCur);
  return SQLITE_OK;
}

static void columnToResult(sqlite3_context *ctx, sqlite3_stmt *pStmt, int iCol){
  switch( sqlite3_column_type(pStmt, iCol) ){
    case SQLITE_NULL:
      sqlite3_result_null(ctx);
      break;
    case SQLITE_INTEGER:
      sqlite3_result_int64(ctx, sqlite3_column_int64(pStmt, iCol));
      break;
    case SQLITE_FLOAT:
      sqlite3_result_double(ctx, sqlite3_column_double(pStmt, iCol));
      break;
    case SQLITE_TEXT: {
      const char *z = (const char *)sqlite3_column_text(pStmt, iCol);
      sqlite3_result_text(ctx, z, -1, SQLITE_TRANSIENT);
      break;
    }
  }
}

/*
** Retrieve a column of data.
*/
static int schemaColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  schema_cursor *pCur = (schema_cursor *)cur;
  switch( i ){
    case 0:
      columnToResult(ctx, pCur->pDbList, 1);
      break;
    case 1:
      columnToResult(ctx, pCur->pTableList, 0);
      break;
    default:
      columnToResult(ctx, pCur->pColumnList, i-2);
      break;
  }
  return SQLITE_OK;
}

/*
** Retrieve the current rowid.
*/
static int schemaRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  schema_cursor *pCur = (schema_cursor *)cur;
  *pRowid = pCur->rowid;
  return SQLITE_OK;
}

static int finalize(sqlite3_stmt **ppStmt){
  int rc = sqlite3_finalize(*ppStmt);
  *ppStmt = 0;
  return rc;
}

static int schemaEof(sqlite3_vtab_cursor *cur){
  schema_cursor *pCur = (schema_cursor *)cur;
  return (pCur->pDbList ? 0 : 1);
}

/*
** Advance the cursor to the next row.
*/
static int schemaNext(sqlite3_vtab_cursor *cur){
  int rc = SQLITE_OK;
  schema_cursor *pCur = (schema_cursor *)cur;
  schema_vtab *pVtab = (schema_vtab *)(cur->pVtab);
  char *zSql = 0;

  while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){
    if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit;

    while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){
      if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit;

      assert(pCur->pDbList);
      while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){
        rc = finalize(&pCur->pDbList);
        goto next_exit;
      }

      /* Set zSql to the SQL to pull the list of tables from the 
      ** sqlite_master (or sqlite_temp_master) table of the database
      ** identfied by the row pointed to by the SQL statement pCur->pDbList
      ** (iterating through a "PRAGMA database_list;" statement).
      */
      if( sqlite3_column_int(pCur->pDbList, 0)==1 ){
        zSql = sqlite3_mprintf(
            "SELECT name FROM sqlite_temp_master WHERE type=%Q",
            pVtab->pType->zObject
        );
      }else{
        sqlite3_stmt *pDbList = pCur->pDbList;
        zSql = sqlite3_mprintf(
            "SELECT name FROM %Q.sqlite_master WHERE type=%Q",
             sqlite3_column_text(pDbList, 1), pVtab->pType->zObject
        );
      }
      if( !zSql ){
        rc = SQLITE_NOMEM;
        goto next_exit;
      }

      rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0);
      sqlite3_free(zSql);
      if( rc!=SQLITE_OK ) goto next_exit;
    }

    /* Set zSql to the SQL to the table_info pragma for the table currently
    ** identified by the rows pointed to by statements pCur->pDbList and
    ** pCur->pTableList.
    */
    zSql = sqlite3_mprintf(pVtab->pType->zPragma,
        sqlite3_column_text(pCur->pDbList, 1),
        sqlite3_column_text(pCur->pTableList, 0)
    );

    if( !zSql ){
      rc = SQLITE_NOMEM;
      goto next_exit;
    }
    rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0);
    sqlite3_free(zSql);
    if( rc!=SQLITE_OK ) goto next_exit;
  }
  pCur->rowid++;

next_exit:
  /* TODO: Handle rc */
  return rc;
}

/*
** Reset a schema table cursor.
*/
static int schemaFilter(
  sqlite3_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite3_value **argv
){
  int rc;
  schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab);
  schema_cursor *pCur = (schema_cursor *)pVtabCursor;
  UNUSED_PARAMETER(idxNum);
  UNUSED_PARAMETER(idxStr);
  UNUSED_PARAMETER(argc);
  UNUSED_PARAMETER(argv);
  pCur->rowid = 0;
  finalize(&pCur->pTableList);
  finalize(&pCur->pColumnList);
  finalize(&pCur->pDbList);
  rc = sqlite3_prepare(pVtab->db,"SELECT 0, 'main'", -1, &pCur->pDbList, 0);
  return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc);
}

/*
** Analyse the WHERE condition.
*/
static int schemaBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  UNUSED_PARAMETER(tab);
  UNUSED_PARAMETER(pIdxInfo);
  return SQLITE_OK;
}

/*
** A virtual table module that merely echos method calls into TCL
** variables.
*/
static sqlite3_module schemaModule = {
  0,                           /* iVersion */
  schemaCreate,
  schemaCreate,
  schemaBestIndex,
  schemaDestroy,
  schemaDestroy,
  schemaOpen,                  /* xOpen - open a cursor */
  schemaClose,                 /* xClose - close a cursor */
  schemaFilter,                /* xFilter - configure scan constraints */
  schemaNext,                  /* xNext - advance a cursor */
  schemaEof,                   /* xEof */
  schemaColumn,                /* xColumn - read data */
  schemaRowid,                 /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

/*
** Extension load function.
*/
static int installSchemaModule(sqlite3 *db, sqlite3 *sdb){
  sqlite3_create_module(db, "schema", &schemaModule, (void *)sdb);
  return 0;
}

/*
**   sj(zValue, zJoin)
**
** The following block contains the implementation of an aggregate 
** function that returns a string. Each time the function is stepped, 
** it appends data to an internal buffer. When the aggregate is finalized,
** the contents of the buffer are returned.
**
** The first time the aggregate is stepped the buffer is set to a copy
** of the first argument. The second time and subsequent times it is
** stepped a copy of the second argument is appended to the buffer, then
** a copy of the first.
**
** Example:
**
**   INSERT INTO t1(a) VALUES('1');
**   INSERT INTO t1(a) VALUES('2');
**   INSERT INTO t1(a) VALUES('3');
**   SELECT sj(a, ', ') FROM t1;
**
**     =>  "1, 2, 3"
**
*/
struct StrBuffer {
  char *zBuf;
};
typedef struct StrBuffer StrBuffer;
static void joinFinalize(sqlite3_context *context){
  StrBuffer *p;
  p = (StrBuffer *)sqlite3_aggregate_context(context, sizeof(StrBuffer));
  sqlite3_result_text(context, p->zBuf, -1, SQLITE_TRANSIENT);
  sqlite3_free(p->zBuf);
}
static void joinStep(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  StrBuffer *p;
  UNUSED_PARAMETER(argc);
  p = (StrBuffer *)sqlite3_aggregate_context(context, sizeof(StrBuffer));
  if( p->zBuf==0 ){
    p->zBuf = sqlite3_mprintf("%s", sqlite3_value_text(argv[0]));
  }else{
    char *zTmp = p->zBuf;
    p->zBuf = sqlite3_mprintf("%s%s%s", 
        zTmp, sqlite3_value_text(argv[1]), sqlite3_value_text(argv[0])
    );
    sqlite3_free(zTmp);
  }
}

/*
**   dq(zString)
**
** This scalar function accepts a single argument and interprets it as
** a text value. The return value is the argument enclosed in double
** quotes. If any double quote characters are present in the argument, 
** these are escaped.
**
**   dq('the raven "Nevermore."') == '"the raven ""Nevermore."""'
*/
static void doublequote(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  int ii;
  char *zOut;
  char *zCsr;
  const char *zIn = (const char *)sqlite3_value_text(argv[0]);
  int nIn = sqlite3_value_bytes(argv[0]);

  UNUSED_PARAMETER(argc);
  zOut = sqlite3_malloc(nIn*2+3);
  zCsr = zOut;
  *zCsr++ = '"';
  for(ii=0; ii<nIn; ii++){
    *zCsr++ = zIn[ii];
    if( zIn[ii]=='"' ){
      *zCsr++ = '"';
    }
  }
  *zCsr++ = '"';
  *zCsr++ = '\0';

  sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT);
  sqlite3_free(zOut);
}

/*
**   multireplace(zString, zSearch1, zReplace1, ...)
*/
static void multireplace(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  int i = 0;
  char *zOut = 0;
  int nOut = 0;
  int nMalloc = 0;
  const char *zIn = (const char *)sqlite3_value_text(argv[0]);
  int nIn = sqlite3_value_bytes(argv[0]);

  while( i<nIn ){
    const char *zCopy = &zIn[i];
    int nCopy = 1;
    int nReplace = 1;
    int j;
    for(j=1; j<(argc-1); j+=2){
      const char *z = (const char *)sqlite3_value_text(argv[j]);
      int n = sqlite3_value_bytes(argv[j]);
      if( n<=(nIn-i) && 0==strncmp(z, zCopy, n) ){
        zCopy = (const char *)sqlite3_value_text(argv[j+1]);
        nCopy = sqlite3_value_bytes(argv[j+1]);
        nReplace = n;
        break;
      }
    }
    if( (nOut+nCopy)>nMalloc ){
      char *zNew;
      nMalloc = 16 + (nOut+nCopy)*2;
      zNew = (char*)sqlite3_realloc(zOut, nMalloc);
      if( zNew==0 ){
        sqlite3_result_error_nomem(context);
        return;
      }else{
        zOut = zNew;
      }
    }
    assert( nMalloc>=(nOut+nCopy) );
    memcpy(&zOut[nOut], zCopy, nCopy);
    i += nReplace;
    nOut += nCopy;
  }

  sqlite3_result_text(context, zOut, nOut, SQLITE_TRANSIENT);
  sqlite3_free(zOut);
}

/*
** A callback for sqlite3_exec() invokes the callback specified by the
** GenfkeyCb structure pointed to by the void* passed as the first argument.
*/
static int invokeCallback(void *p, int nArg, char **azArg, char **azCol){
  GenfkeyCb *pCb = (GenfkeyCb *)p;
  UNUSED_PARAMETER(nArg);
  UNUSED_PARAMETER(azCol);
  return pCb->xData(pCb->pCtx, pCb->eType, azArg[0]);
}

static int detectSchemaProblem(
  sqlite3 *db,                   /* Database connection */
  const char *zMessage,          /* English language error message */
  const char *zSql,              /* SQL statement to run */
  GenfkeyCb *pCb
){
  sqlite3_stmt *pStmt;
  int rc;
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    char *zDel;
    int iFk = sqlite3_column_int(pStmt, 0);
    const char *zTab = (const char *)sqlite3_column_text(pStmt, 1);
    zDel = sqlite3_mprintf("Error in table %s: %s", zTab, zMessage);
    rc = pCb->xData(pCb->pCtx, pCb->eType, zDel);
    sqlite3_free(zDel);
    if( rc!=SQLITE_OK ) return rc;
    zDel = sqlite3_mprintf(
        "DELETE FROM temp.fkey WHERE from_tbl = %Q AND fkid = %d"
        , zTab, iFk
    );
    sqlite3_exec(db, zDel, 0, 0, 0);
    sqlite3_free(zDel);
  }
  sqlite3_finalize(pStmt);
  return SQLITE_OK;
}

/*
** Create and populate temporary table "fkey".
*/
static int populateTempTable(sqlite3 *db, GenfkeyCb *pCallback){
  int rc;
  
  rc = sqlite3_exec(db, 
      "CREATE VIRTUAL TABLE temp.v_fkey USING schema(foreign_key_list);"
      "CREATE VIRTUAL TABLE temp.v_col USING schema(table_info);"
      "CREATE VIRTUAL TABLE temp.v_idxlist USING schema(index_list);"
      "CREATE VIRTUAL TABLE temp.v_idxinfo USING schema(index_info);"
      "CREATE VIRTUAL TABLE temp.v_triggers USING schema(trigger_list);"
      "CREATE TABLE temp.fkey AS "
        "SELECT from_tbl, to_tbl, fkid, from_col, to_col, on_update, on_delete "
        "FROM temp.v_fkey WHERE database = 'main';"
      , 0, 0, 0
  );
  if( rc!=SQLITE_OK ) return rc;

  rc = detectSchemaProblem(db, "foreign key columns do not exist",
    "SELECT fkid, from_tbl "
    "FROM temp.fkey "
    "WHERE to_col IS NOT NULL AND NOT EXISTS (SELECT 1 "
        "FROM temp.v_col WHERE tablename=to_tbl AND name==to_col"
    ")", pCallback
  );
  if( rc!=SQLITE_OK ) return rc;

  /* At this point the temp.fkey table is mostly populated. If any foreign
  ** keys were specified so that they implicitly refer to they primary
  ** key of the parent table, the "to_col" values of the temp.fkey rows
  ** are still set to NULL.
  **
  ** This is easily fixed for single column primary keys, but not for
  ** composites. With a composite primary key, there is no way to reliably
  ** query sqlite for the order in which the columns that make up the
  ** composite key were declared i.e. there is no way to tell if the
  ** schema actually contains "PRIMARY KEY(a, b)" or "PRIMARY KEY(b, a)".
  ** Therefore, this case is not handled. The following function call
  ** detects instances of this case.
  */
  rc = detectSchemaProblem(db, "implicit mapping to composite primary key",
    "SELECT fkid, from_tbl "
    "FROM temp.fkey "
    "WHERE to_col IS NULL "
    "GROUP BY fkid, from_tbl HAVING count(*) > 1", pCallback
  );
  if( rc!=SQLITE_OK ) return rc;

  /* Detect attempts to implicitly map to the primary key of a table 
  ** that has no primary key column.
  */
  rc = detectSchemaProblem(db, "implicit mapping to non-existant primary key",
    "SELECT fkid, from_tbl "
    "FROM temp.fkey "
    "WHERE to_col IS NULL AND NOT EXISTS "
      "(SELECT 1 FROM temp.v_col WHERE pk AND tablename = temp.fkey.to_tbl)"
    , pCallback
  );
  if( rc!=SQLITE_OK ) return rc;

  /* Fix all the implicit primary key mappings in the temp.fkey table. */
  rc = sqlite3_exec(db, 
    "UPDATE temp.fkey SET to_col = "
      "(SELECT name FROM temp.v_col WHERE pk AND tablename=temp.fkey.to_tbl)"
    " WHERE to_col IS NULL;"
    , 0, 0, 0
  );
  if( rc!=SQLITE_OK ) return rc;

  /* Now check that all all parent keys are either primary keys or 
  ** subject to a unique constraint.
  */
  rc = sqlite3_exec(db, 
    "CREATE TABLE temp.idx2 AS SELECT "
      "il.tablename AS tablename,"
      "ii.indexname AS indexname,"
      "ii.name AS col "
      "FROM temp.v_idxlist AS il, temp.v_idxinfo AS ii "
      "WHERE il.isunique AND il.database='main' AND ii.indexname = il.name;"
    "INSERT INTO temp.idx2 "
      "SELECT tablename, 'pk', name FROM temp.v_col WHERE pk;"

    "CREATE TABLE temp.idx AS SELECT "
      "tablename, indexname, sj(dq(col),',') AS cols "
      "FROM (SELECT * FROM temp.idx2 ORDER BY col) " 
      "GROUP BY tablename, indexname;"

    "CREATE TABLE temp.fkey2 AS SELECT "
        "fkid, from_tbl, to_tbl, sj(dq(to_col),',') AS cols "
        "FROM (SELECT * FROM temp.fkey ORDER BY to_col) " 
        "GROUP BY fkid, from_tbl;"

    "CREATE TABLE temp.triggers AS SELECT "
        "triggername FROM temp.v_triggers WHERE database='main' AND "
        "triggername LIKE 'genfkey%';"
    , 0, 0, 0
  );
  if( rc!=SQLITE_OK ) return rc;
  rc = detectSchemaProblem(db, "foreign key is not unique",
    "SELECT fkid, from_tbl "
    "FROM temp.fkey2 "
    "WHERE NOT EXISTS (SELECT 1 "
        "FROM temp.idx WHERE tablename=to_tbl AND fkey2.cols==idx.cols"
    ")", pCallback
  );
  if( rc!=SQLITE_OK ) return rc;

  return rc;
}

#define GENFKEY_ERROR         1
#define GENFKEY_DROPTRIGGER   2
#define GENFKEY_CREATETRIGGER 3
static int genfkey_create_triggers(
  sqlite3 *sdb,                        /* Connection to read schema from */
  const char *zDb,                     /* Name of db to read ("main", "temp") */
  void *pCtx,                          /* Context pointer to pass to xData */
  int (*xData)(void *, int, const char *)
){
  const char *zSql =
    "SELECT multireplace('"

      "-- Triggers for foreign key mapping:\n"
      "--\n"
      "--     /from_readable/ REFERENCES /to_readable/\n"
      "--     on delete /on_delete/\n"
      "--     on update /on_update/\n"
      "--\n"

      /* The "BEFORE INSERT ON <referencing>" trigger. This trigger's job is to
      ** throw an exception if the user tries to insert a row into the
      ** referencing table for which there is no corresponding row in
      ** the referenced table.
      */
      "CREATE TRIGGER /name/_insert_referencing BEFORE INSERT ON /tbl/ WHEN \n"
      "    /key_notnull/ AND NOT EXISTS (SELECT 1 FROM /ref/ WHERE /cond1/)\n" 
      "BEGIN\n"
        "  SELECT RAISE(ABORT, ''constraint failed'');\n"
      "END;\n"

      /* The "BEFORE UPDATE ON <referencing>" trigger. This trigger's job 
      ** is to throw an exception if the user tries to update a row in the
      ** referencing table causing it to correspond to no row in the
      ** referenced table.
      */
      "CREATE TRIGGER /name/_update_referencing BEFORE\n"
      "    UPDATE OF /rkey_list/ ON /tbl/ WHEN \n"
      "    /key_notnull/ AND \n"
      "    NOT EXISTS (SELECT 1 FROM /ref/ WHERE /cond1/)\n" 
      "BEGIN\n"
        "  SELECT RAISE(ABORT, ''constraint failed'');\n"
      "END;\n"


      /* The "BEFORE DELETE ON <referenced>" trigger. This trigger's job 
      ** is to detect when a row is deleted from the referenced table to 
      ** which rows in the referencing table correspond. The action taken
      ** depends on the value of the 'ON DELETE' clause.
      */
      "CREATE TRIGGER /name/_delete_referenced BEFORE DELETE ON /ref/ WHEN\n"
      "    EXISTS (SELECT 1 FROM /tbl/ WHERE /cond2/)\n"
      "BEGIN\n"
      "  /delete_action/\n"
      "END;\n"

      /* The "AFTER UPDATE ON <referenced>" trigger. This trigger's job 
      ** is to detect when the key columns of a row in the referenced table 
      ** to which one or more rows in the referencing table correspond are
      ** updated. The action taken depends on the value of the 'ON UPDATE' 
      ** clause.
      */
      "CREATE TRIGGER /name/_update_referenced AFTER\n"
      "    UPDATE OF /fkey_list/ ON /ref/ WHEN \n"
      "    EXISTS (SELECT 1 FROM /tbl/ WHERE /cond2/)\n"
      "BEGIN\n"
      "  /update_action/\n"
      "END;\n"
    "'"

    /* These are used in the SQL comment written above each set of triggers */
    ", '/from_readable/',  from_tbl || '(' || sj(from_col, ', ') || ')'"
    ", '/to_readable/',    to_tbl || '(' || sj(to_col, ', ') || ')'"
    ", '/on_delete/', on_delete"
    ", '/on_update/', on_update"

    ", '/name/',   'genfkey' || min(rowid)"
    ", '/tbl/',    dq(from_tbl)"
    ", '/ref/',    dq(to_tbl)"
    ", '/key_notnull/', sj('new.' || dq(from_col) || ' IS NOT NULL', ' AND ')"

    ", '/fkey_list/', sj(dq(to_col), ', ')"
    ", '/rkey_list/', sj(dq(from_col), ', ')"

    ", '/cond1/',  sj(multireplace('new./from/ == /to/'"
                   ", '/from/', dq(from_col)"
                   ", '/to/',   dq(to_col)"
                   "), ' AND ')"
    ", '/cond2/',  sj(multireplace('old./to/ == /from/'"
                   ", '/from/', dq(from_col)"
                   ", '/to/',   dq(to_col)"
                   "), ' AND ')"

    ", '/update_action/', CASE on_update "
      "WHEN 'SET NULL' THEN "
        "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
        ", '/setlist/', sj(dq(from_col)||' = NULL',', ')"
        ", '/tbl/',     dq(from_tbl)"
        ", '/where/',   sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
        ")"
      "WHEN 'CASCADE' THEN "
        "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
        ", '/setlist/', sj(dq(from_col)||' = new.'||dq(to_col),', ')"
        ", '/tbl/',     dq(from_tbl)"
        ", '/where/',   sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
        ")"
      "ELSE "
      "  'SELECT RAISE(ABORT, ''constraint failed'');'"
      "END "

    ", '/delete_action/', CASE on_delete "
      "WHEN 'SET NULL' THEN "
        "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
        ", '/setlist/', sj(dq(from_col)||' = NULL',', ')"
        ", '/tbl/',     dq(from_tbl)"
        ", '/where/',   sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
        ")"
      "WHEN 'CASCADE' THEN "
        "multireplace('DELETE FROM /tbl/ WHERE /where/;' "
        ", '/tbl/',     dq(from_tbl)"
        ", '/where/',   sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
        ")"
      "ELSE "
      "  'SELECT RAISE(ABORT, ''constraint failed'');'"
      "END "

    ") FROM temp.fkey "
    "GROUP BY from_tbl, fkid"
  ;

  int rc;
  const int enc = SQLITE_UTF8;
  sqlite3 *db = 0;

  GenfkeyCb cb;
  cb.xData = xData;
  cb.pCtx = pCtx;

  UNUSED_PARAMETER(zDb);

  /* Open the working database handle. */
  rc = sqlite3_open(":memory:", &db);
  if( rc!=SQLITE_OK ) goto genfkey_exit;

  /* Create the special scalar and aggregate functions used by this program. */
  sqlite3_create_function(db, "dq", 1, enc, 0, doublequote, 0, 0);
  sqlite3_create_function(db, "multireplace", -1, enc, db, multireplace, 0, 0);
  sqlite3_create_function(db, "sj", 2, enc, 0, 0, joinStep, joinFinalize);

  /* Install the "schema" virtual table module */
  installSchemaModule(db, sdb);

  /* Create and populate a temp table with the information required to
  ** build the foreign key triggers. See function populateTempTable()
  ** for details.
  */
  cb.eType = GENFKEY_ERROR;
  rc = populateTempTable(db, &cb);
  if( rc!=SQLITE_OK ) goto genfkey_exit;

  /* Unless the --no-drop option was specified, generate DROP TRIGGER
  ** statements to drop any triggers in the database generated by a
  ** previous run of this program.
  */
  cb.eType = GENFKEY_DROPTRIGGER;
  rc = sqlite3_exec(db, 
    "SELECT 'DROP TRIGGER main.' || dq(triggername) || ';' FROM triggers"
    ,invokeCallback, (void *)&cb, 0
  );
  if( rc!=SQLITE_OK ) goto genfkey_exit;

  /* Run the main query to create the trigger definitions. */
  cb.eType = GENFKEY_CREATETRIGGER;
  rc = sqlite3_exec(db, zSql, invokeCallback, (void *)&cb, 0);
  if( rc!=SQLITE_OK ) goto genfkey_exit;

genfkey_exit:
  sqlite3_close(db);
  return rc;
}


#endif
/* End genfkey logic. */
/*************************************************************************/
/*************************************************************************/

/*
** If the following flag is set, then command execution stops
** at an error if we are not interactive.
*/
static int bail_on_error = 0;

/*
** Threat stdin as an interactive input if the following variable
** is true.  Otherwise, assume stdin is connected to a file or pipe.
*/
static int stdin_is_interactive = 1;

/*
** The following is the open SQLite database.  We make a pointer
** to this database a static variable so that it can be accessed
** by the SIGINT handler to interrupt database processing.
*/
static sqlite3 *db = 0;

/*
** True if an interrupt (Control-C) has been received.
*/
static volatile int seenInterrupt = 0;

/*
** This is the name of our program. It is set in main(), used
** in a number of other places, mostly for error messages.
*/
static char *Argv0;

/*
** Prompt strings. Initialized in main. Settable with
**   .prompt main continue
*/
static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */

/*
** Write I/O traces to the following stream.
*/
#ifdef SQLITE_ENABLE_IOTRACE
static FILE *iotrace = 0;
#endif

/*
** This routine works like printf in that its first argument is a
** format string and subsequent arguments are values to be substituted
** in place of % fields.  The result of formatting this string
** is written to iotrace.
*/
#ifdef SQLITE_ENABLE_IOTRACE
static void iotracePrintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  if( iotrace==0 ) return;
  va_start(ap, zFormat);
  z = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  fprintf(iotrace, "%s", z);
  sqlite3_free(z);
}
#endif


/*
** Determines if a string is a number of not.
*/
static int isNumber(const char *z, int *realnum){
  if( *z=='-' || *z=='+' ) z++;
  if( !isdigit(*z) ){
    return 0;
  }
  z++;
  if( realnum ) *realnum = 0;
  while( isdigit(*z) ){ z++; }
  if( *z=='.' ){
    z++;
    if( !isdigit(*z) ) return 0;
    while( isdigit(*z) ){ z++; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z++;
    if( *z=='+' || *z=='-' ) z++;
    if( !isdigit(*z) ) return 0;
    while( isdigit(*z) ){ z++; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

/*
** A global char* and an SQL function to access its current value 
** from within an SQL statement. This program used to use the 
** sqlite_exec_printf() API to substitue a string into an SQL statement.
** The correct way to do this with sqlite3 is to use the bind API, but
** since the shell is built around the callback paradigm it would be a lot
** of work. Instead just use this hack, which is quite harmless.
*/
static const char *zShellStatic = 0;
static void shellstaticFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  assert( 0==argc );
  assert( zShellStatic );
  UNUSED_PARAMETER(argc);
  UNUSED_PARAMETER(argv);
  sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
}


/*
** This routine reads a line of text from FILE in, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text.  NULL is returned at end of file, or if malloc()
** fails.
**
** The interface is like "readline" but no command-line editing
** is done.
*/
static char *local_getline(char *zPrompt, FILE *in){
  char *zLine;
  int nLine;
  int n;
  int eol;

  if( zPrompt && *zPrompt ){
    printf("%s",zPrompt);
    fflush(stdout);
  }
  nLine = 100;
  zLine = malloc( nLine );
  if( zLine==0 ) return 0;
  n = 0;
  eol = 0;
  while( !eol ){
    if( n+100>nLine ){
      nLine = nLine*2 + 100;
      zLine = realloc(zLine, nLine);
      if( zLine==0 ) return 0;
    }
    if( fgets(&zLine[n], nLine - n, in)==0 ){
      if( n==0 ){
        free(zLine);
        return 0;
      }
      zLine[n] = 0;
      eol = 1;
      break;
    }
    while( zLine[n] ){ n++; }
    if( n>0 && zLine[n-1]=='\n' ){
      n--;
      zLine[n] = 0;
      eol = 1;
    }
  }
  zLine = realloc( zLine, n+1 );
  return zLine;
}

/*
** Retrieve a single line of input text.
**
** zPrior is a string of prior text retrieved.  If not the empty
** string, then issue a continuation prompt.
*/
static char *one_input_line(const char *zPrior, FILE *in){
  char *zPrompt;
  char *zResult;
  if( in!=0 ){
    return local_getline(0, in);
  }
  if( zPrior && zPrior[0] ){
    zPrompt = continuePrompt;
  }else{
    zPrompt = mainPrompt;
  }
  zResult = readline(zPrompt);
#if defined(HAVE_READLINE) && HAVE_READLINE==1
  if( zResult && *zResult ) add_history(zResult);
#endif
  return zResult;
}

struct previous_mode_data {
  int valid;        /* Is there legit data in here? */
  int mode;
  int showHeader;
  int colWidth[100];
};

/*
** An pointer to an instance of this structure is passed from
** the main program to the callback.  This is used to communicate
** state and mode information.
*/
struct callback_data {
  sqlite3 *db;           /* The database */
  int echoOn;            /* True to echo input commands */
  int cnt;               /* Number of records displayed so far */
  FILE *out;             /* Write results here */
  int mode;              /* An output mode setting */
  int writableSchema;    /* True if PRAGMA writable_schema=ON */
  int showHeader;        /* True to show column names in List or Column mode */
  char *zDestTable;      /* Name of destination table when MODE_Insert */
  char separator[20];    /* Separator character for MODE_List */
  int colWidth[100];     /* Requested width of each column when in column mode*/
  int actualWidth[100];  /* Actual width of each column */
  char nullvalue[20];    /* The text to print when a NULL comes back from
                         ** the database */
  struct previous_mode_data explainPrev;
                         /* Holds the mode information just before
                         ** .explain ON */
  char outfile[FILENAME_MAX]; /* Filename for *out */
  const char *zDbFilename;    /* name of the database file */
  sqlite3_stmt *pStmt;   /* Current statement if any. */
};

/*
** These are the allowed modes.
*/
#define MODE_Line     0  /* One column per line.  Blank line between records */
#define MODE_Column   1  /* One record per line in neat columns */
#define MODE_List     2  /* One record per line with a separator */
#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
#define MODE_Html     4  /* Generate an XHTML table */
#define MODE_Insert   5  /* Generate SQL "insert" statements */
#define MODE_Tcl      6  /* Generate ANSI-C or TCL quoted elements */
#define MODE_Csv      7  /* Quote strings, numbers are plain */
#define MODE_Explain  8  /* Like MODE_Column, but do not truncate data */

static const char *modeDescr[] = {
  "line",
  "column",
  "list",
  "semi",
  "html",
  "insert",
  "tcl",
  "csv",
  "explain",
};

/*
** Number of elements in an array
*/
#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))

/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
*/
static int strlen30(const char *z){
  const char *z2 = z;
  while( *z2 ){ z2++; }
  return 0x3fffffff & (int)(z2 - z);
}

/*
** Output the given string as a hex-encoded blob (eg. X'1234' )
*/
static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  int i;
  char *zBlob = (char *)pBlob;
  fprintf(out,"X'");
  for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]); }
  fprintf(out,"'");
}

/*
** Output the given string as a quoted string using SQL quoting conventions.
*/
static void output_quoted_string(FILE *out, const char *z){
  int i;
  int nSingle = 0;
  for(i=0; z[i]; i++){
    if( z[i]=='\'' ) nSingle++;
  }
  if( nSingle==0 ){
    fprintf(out,"'%s'",z);
  }else{
    fprintf(out,"'");
    while( *z ){
      for(i=0; z[i] && z[i]!='\''; i++){}
      if( i==0 ){
        fprintf(out,"''");
        z++;
      }else if( z[i]=='\'' ){
        fprintf(out,"%.*s''",i,z);
        z += i+1;
      }else{
        fprintf(out,"%s",z);
        break;
      }
    }
    fprintf(out,"'");
  }
}

/*
** Output the given string as a quoted according to C or TCL quoting rules.
*/
static void output_c_string(FILE *out, const char *z){
  unsigned int c;
  fputc('"', out);
  while( (c = *(z++))!=0 ){
    if( c=='\\' ){
      fputc(c, out);
      fputc(c, out);
    }else if( c=='\t' ){
      fputc('\\', out);
      fputc('t', out);
    }else if( c=='\n' ){
      fputc('\\', out);
      fputc('n', out);
    }else if( c=='\r' ){
      fputc('\\', out);
      fputc('r', out);
    }else if( !isprint(c) ){
      fprintf(out, "\\%03o", c&0xff);
    }else{
      fputc(c, out);
    }
  }
  fputc('"', out);
}

/*
** Output the given string with characters that are special to
** HTML escaped.
*/
static void output_html_string(FILE *out, const char *z){
  int i;
  while( *z ){
    for(i=0;   z[i] 
            && z[i]!='<' 
            && z[i]!='&' 
            && z[i]!='>' 
            && z[i]!='\"' 
            && z[i]!='\'';
        i++){}
    if( i>0 ){
      fprintf(out,"%.*s",i,z);
    }
    if( z[i]=='<' ){
      fprintf(out,"&lt;");
    }else if( z[i]=='&' ){
      fprintf(out,"&amp;");
    }else if( z[i]=='>' ){
      fprintf(out,"&gt;");
    }else if( z[i]=='\"' ){
      fprintf(out,"&quot;");
    }else if( z[i]=='\'' ){
      fprintf(out,"&#39;");
    }else{
      break;
    }
    z += i + 1;
  }
}

/*
** If a field contains any character identified by a 1 in the following
** array, then the string must be quoted for CSV.
*/
static const char needCsvQuote[] = {
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1, 
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
};

/*
** Output a single term of CSV.  Actually, p->separator is used for
** the separator, which may or may not be a comma.  p->nullvalue is
** the null value.  Strings are quoted using ANSI-C rules.  Numbers
** appear outside of quotes.
*/
static void output_csv(struct callback_data *p, const char *z, int bSep){
  FILE *out = p->out;
  if( z==0 ){
    fprintf(out,"%s",p->nullvalue);
  }else{
    int i;
    int nSep = strlen30(p->separator);
    for(i=0; z[i]; i++){
      if( needCsvQuote[((unsigned char*)z)[i]] 
         || (z[i]==p->separator[0] && 
             (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
        i = 0;
        break;
      }
    }
    if( i==0 ){
      putc('"', out);
      for(i=0; z[i]; i++){
        if( z[i]=='"' ) putc('"', out);
        putc(z[i], out);
      }
      putc('"', out);
    }else{
      fprintf(out, "%s", z);
    }
  }
  if( bSep ){
    fprintf(p->out, "%s", p->separator);
  }
}

#ifdef SIGINT
/*
** This routine runs when the user presses Ctrl-C
*/
static void interrupt_handler(int NotUsed){
  UNUSED_PARAMETER(NotUsed);
  seenInterrupt = 1;
  if( db ) sqlite3_interrupt(db);
}
#endif

/*
** This is the callback routine that the shell
** invokes for each row of a query result.
*/
static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
  int i;
  struct callback_data *p = (struct callback_data*)pArg;

  if( p->echoOn && p->cnt==0  && p->pStmt){
    printf("%s\n", sqlite3_sql(p->pStmt));
  }

  switch( p->mode ){
    case MODE_Line: {
      int w = 5;
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        int len = strlen30(azCol[i] ? azCol[i] : "");
        if( len>w ) w = len;
      }
      if( p->cnt++>0 ) fprintf(p->out,"\n");
      for(i=0; i<nArg; i++){
        fprintf(p->out,"%*s = %s\n", w, azCol[i],
                azArg[i] ? azArg[i] : p->nullvalue);
      }
      break;
    }
    case MODE_Explain:
    case MODE_Column: {
      if( p->cnt++==0 ){
        for(i=0; i<nArg; i++){
          int w, n;
          if( i<ArraySize(p->colWidth) ){
            w = p->colWidth[i];
          }else{
            w = 0;
          }
          if( w<=0 ){
            w = strlen30(azCol[i] ? azCol[i] : "");
            if( w<10 ) w = 10;
            n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
            if( w<n ) w = n;
          }
          if( i<ArraySize(p->actualWidth) ){
            p->actualWidth[i] = w;
          }
          if( p->showHeader ){
            fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": "  ");
          }
        }
        if( p->showHeader ){
          for(i=0; i<nArg; i++){
            int w;
            if( i<ArraySize(p->actualWidth) ){
               w = p->actualWidth[i];
            }else{
               w = 10;
            }
            fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
                   "----------------------------------------------------------",
                    i==nArg-1 ? "\n": "  ");
          }
        }
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        int w;
        if( i<ArraySize(p->actualWidth) ){
           w = p->actualWidth[i];
        }else{
           w = 10;
        }
        if( p->mode==MODE_Explain && azArg[i] && 
           strlen30(azArg[i])>w ){
          w = strlen30(azArg[i]);
        }
        fprintf(p->out,"%-*.*s%s",w,w,
            azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": "  ");
      }
      break;
    }
    case MODE_Semi:
    case MODE_List: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
          fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
        }
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        char *z = azArg[i];
        if( z==0 ) z = p->nullvalue;
        fprintf(p->out, "%s", z);
        if( i<nArg-1 ){
          fprintf(p->out, "%s", p->separator);
        }else if( p->mode==MODE_Semi ){
          fprintf(p->out, ";\n");
        }else{
          fprintf(p->out, "\n");
        }
      }
      break;
    }
    case MODE_Html: {
      if( p->cnt++==0 && p->showHeader ){
        fprintf(p->out,"<TR>");
        for(i=0; i<nArg; i++){
          fprintf(p->out,"<TH>");
          output_html_string(p->out, azCol[i]);
          fprintf(p->out,"</TH>\n");
        }
        fprintf(p->out,"</TR>\n");
      }
      if( azArg==0 ) break;
      fprintf(p->out,"<TR>");
      for(i=0; i<nArg; i++){
        fprintf(p->out,"<TD>");
        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
        fprintf(p->out,"</TD>\n");
      }
      fprintf(p->out,"</TR>\n");
      break;
    }
    case MODE_Tcl: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
          output_c_string(p->out,azCol[i] ? azCol[i] : "");
          fprintf(p->out, "%s", p->separator);
        }
        fprintf(p->out,"\n");
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
        fprintf(p->out, "%s", p->separator);
      }
      fprintf(p->out,"\n");
      break;
    }
    case MODE_Csv: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
        }
        fprintf(p->out,"\n");
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        output_csv(p, azArg[i], i<nArg-1);
      }
      fprintf(p->out,"\n");
      break;
    }
    case MODE_Insert: {
      p->cnt++;
      if( azArg==0 ) break;
      fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
      for(i=0; i<nArg; i++){
        char *zSep = i>0 ? ",": "";
        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
          fprintf(p->out,"%sNULL",zSep);
        }else if( aiType && aiType[i]==SQLITE_TEXT ){
          if( zSep[0] ) fprintf(p->out,"%s",zSep);
          output_quoted_string(p->out, azArg[i]);
        }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
          fprintf(p->out,"%s%s",zSep, azArg[i]);
        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
          int nBlob = sqlite3_column_bytes(p->pStmt, i);
          if( zSep[0] ) fprintf(p->out,"%s",zSep);
          output_hex_blob(p->out, pBlob, nBlob);
        }else if( isNumber(azArg[i], 0) ){
          fprintf(p->out,"%s%s",zSep, azArg[i]);
        }else{
          if( zSep[0] ) fprintf(p->out,"%s",zSep);
          output_quoted_string(p->out, azArg[i]);
        }
      }
      fprintf(p->out,");\n");
      break;
    }
  }
  return 0;
}

/*
** This is the callback routine that the SQLite library
** invokes for each row of a query result.
*/
static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  /* since we don't have type info, call the shell_callback with a NULL value */
  return shell_callback(pArg, nArg, azArg, azCol, NULL);
}

/*
** Set the destination table field of the callback_data structure to
** the name of the table given.  Escape any quote characters in the
** table name.
*/
static void set_table_name(struct callback_data *p, const char *zName){
  int i, n;
  int needQuote;
  char *z;

  if( p->zDestTable ){
    free(p->zDestTable);
    p->zDestTable = 0;
  }
  if( zName==0 ) return;
  needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  for(i=n=0; zName[i]; i++, n++){
    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
      needQuote = 1;
      if( zName[i]=='\'' ) n++;
    }
  }
  if( needQuote ) n += 2;
  z = p->zDestTable = malloc( n+1 );
  if( z==0 ){
    fprintf(stderr,"Error: out of memory\n");
    exit(1);
  }
  n = 0;
  if( needQuote ) z[n++] = '\'';
  for(i=0; zName[i]; i++){
    z[n++] = zName[i];
    if( zName[i]=='\'' ) z[n++] = '\'';
  }
  if( needQuote ) z[n++] = '\'';
  z[n] = 0;
}

/* zIn is either a pointer to a NULL-terminated string in memory obtained
** from malloc(), or a NULL pointer. The string pointed to by zAppend is
** added to zIn, and the result returned in memory obtained from malloc().
** zIn, if it was not NULL, is freed.
**
** If the third argument, quote, is not '\0', then it is used as a 
** quote character for zAppend.
*/
static char *appendText(char *zIn, char const *zAppend, char quote){
  int len;
  int i;
  int nAppend = strlen30(zAppend);
  int nIn = (zIn?strlen30(zIn):0);

  len = nAppend+nIn+1;
  if( quote ){
    len += 2;
    for(i=0; i<nAppend; i++){
      if( zAppend[i]==quote ) len++;
    }
  }

  zIn = (char *)realloc(zIn, len);
  if( !zIn ){
    return 0;
  }

  if( quote ){
    char *zCsr = &zIn[nIn];
    *zCsr++ = quote;
    for(i=0; i<nAppend; i++){
      *zCsr++ = zAppend[i];
      if( zAppend[i]==quote ) *zCsr++ = quote;
    }
    *zCsr++ = quote;
    *zCsr++ = '\0';
    assert( (zCsr-zIn)==len );
  }else{
    memcpy(&zIn[nIn], zAppend, nAppend);
    zIn[len-1] = '\0';
  }

  return zIn;
}


/*
** Execute a query statement that has a single result column.  Print
** that result column on a line by itself with a semicolon terminator.
**
** This is used, for example, to show the schema of the database by
** querying the SQLITE_MASTER table.
*/
static int run_table_dump_query(
  FILE *out,              /* Send output here */
  sqlite3 *db,            /* Database to query */
  const char *zSelect,    /* SELECT statement to extract content */
  const char *zFirstRow   /* Print before first row, if not NULL */
){
  sqlite3_stmt *pSelect;
  int rc;
  rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0);
  if( rc!=SQLITE_OK || !pSelect ){
    return rc;
  }
  rc = sqlite3_step(pSelect);
  while( rc==SQLITE_ROW ){
    if( zFirstRow ){
      fprintf(out, "%s", zFirstRow);
      zFirstRow = 0;
    }
    fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0));
    rc = sqlite3_step(pSelect);
  }
  return sqlite3_finalize(pSelect);
}

/*
** Allocate space and save off current error string.
*/
static char *save_err_msg(
  sqlite3 *db            /* Database to query */
){
  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  char *zErrMsg = sqlite3_malloc(nErrMsg);
  if( zErrMsg ){
    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  }
  return zErrMsg;
}

/*
** Execute a statement or set of statements.  Print 
** any result rows/columns depending on the current mode 
** set via the supplied callback.
**
** This is very similar to SQLite's built-in sqlite3_exec() 
** function except it takes a slightly different callback 
** and callback data argument.
*/
static int shell_exec(
  sqlite3 *db,                                /* An open database */
  const char *zSql,                           /* SQL to be evaluated */
  int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
                                              /* (not the same as sqlite3_exec) */
  struct callback_data *pArg,                 /* Pointer to struct callback_data */
  char **pzErrMsg                             /* Error msg written here */
){
  sqlite3_stmt *pStmt = NULL;
  int rc = SQLITE_OK;
  int rc2;
  const char *zLeftover;      /* Tail of unprocessed SQL */

  if( pzErrMsg ){
    *pzErrMsg = NULL;
  }

  while( zSql[0] && (SQLITE_OK == rc) ){
    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
    if( SQLITE_OK != rc ){
      if( pzErrMsg ){
        *pzErrMsg = save_err_msg(db);
      }
    }else{
      if( !pStmt ){
        /* this happens for a comment or white-space */
        zSql = zLeftover;
        while( isspace(zSql[0]) ) zSql++;
        continue;
      }

      /* perform the first step.  this will tell us if we
      ** have a result set or not and how wide it is.
      */
      rc = sqlite3_step(pStmt);
      /* if we have a result set... */
      if( SQLITE_ROW == rc ){
        /* if we have a callback... */
        if( xCallback ){
          /* allocate space for col name ptr, value ptr, and type */
          int nCol = sqlite3_column_count(pStmt);
          void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
          if( !pData ){
            rc = SQLITE_NOMEM;
          }else{
            char **azCols = (char **)pData;      /* Names of result columns */
            char **azVals = &azCols[nCol];       /* Results */
            int *aiTypes = (int *)&azVals[nCol]; /* Result types */
            int i;
            assert(sizeof(int) <= sizeof(char *)); 
            /* save off ptrs to column names */
            for(i=0; i<nCol; i++){
              azCols[i] = (char *)sqlite3_column_name(pStmt, i);
            }
            /* save off the prepared statment handle and reset row count */
            if( pArg ){
              pArg->pStmt = pStmt;
              pArg->cnt = 0;
            }
            do{
              /* extract the data and data types */
              for(i=0; i<nCol; i++){
                azVals[i] = (char *)sqlite3_column_text(pStmt, i);
                aiTypes[i] = sqlite3_column_type(pStmt, i);
                if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
                  rc = SQLITE_NOMEM;
                  break; /* from for */
                }
              } /* end for */

              /* if data and types extracted successfully... */
              if( SQLITE_ROW == rc ){ 
                /* call the supplied callback with the result row data */
                if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
                  rc = SQLITE_ABORT;
                }else{
                  rc = sqlite3_step(pStmt);
                }
              }
            } while( SQLITE_ROW == rc );
            sqlite3_free(pData);
            if( pArg ){
              pArg->pStmt = NULL;
            }
          }
        }else{
          do{
            rc = sqlite3_step(pStmt);
          } while( rc == SQLITE_ROW );
        }
      }

      /* if the last sqlite3_step() didn't complete successfully... */
      if( (SQLITE_OK != rc) && (SQLITE_DONE != rc) ){ 
        if( pzErrMsg ){
          *pzErrMsg = save_err_msg(db);
        }
      }else{
        rc = SQLITE_OK;
      }

      rc2 = sqlite3_finalize(pStmt);
      /* if the last sqlite3_finalize() didn't complete successfully 
      ** AND we don't have a saved error from sqlite3_step ... */
      if( (SQLITE_OK != rc2) && (SQLITE_OK == rc) ){
        rc = rc2;
        if( pzErrMsg ){
          *pzErrMsg = save_err_msg(db);
        }
      }

      if( SQLITE_OK == rc ){ 
        zSql = zLeftover;
        while( isspace(zSql[0]) ) zSql++;
      }
    }
  } /* end while */

  return rc;
}


/*
** This is a different callback routine used for dumping the database.
** Each row received by this callback consists of a table name,
** the table type ("index" or "table") and SQL to create the table.
** This routine should print text sufficient to recreate the table.
*/
static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  int rc;
  const char *zTable;
  const char *zType;
  const char *zSql;
  const char *zPrepStmt = 0;
  struct callback_data *p = (struct callback_data *)pArg;

  UNUSED_PARAMETER(azCol);
  if( nArg!=3 ) return 1;
  zTable = azArg[0];
  zType = azArg[1];
  zSql = azArg[2];
  
  if( strcmp(zTable, "sqlite_sequence")==0 ){
    zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  }else if( strcmp(zTable, "sqlite_stat1")==0 ){
    fprintf(p->out, "ANALYZE sqlite_master;\n");
  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
    return 0;
  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
    char *zIns;
    if( !p->writableSchema ){
      fprintf(p->out, "PRAGMA writable_schema=ON;\n");
      p->writableSchema = 1;
    }
    zIns = sqlite3_mprintf(
       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
       "VALUES('table','%q','%q',0,'%q');",
       zTable, zTable, zSql);
    fprintf(p->out, "%s\n", zIns);
    sqlite3_free(zIns);
    return 0;
  }else{
    fprintf(p->out, "%s;\n", zSql);
  }

  if( strcmp(zType, "table")==0 ){
    sqlite3_stmt *pTableInfo = 0;
    char *zSelect = 0;
    char *zTableInfo = 0;
    char *zTmp = 0;
    int nRow = 0;
   
    zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
    zTableInfo = appendText(zTableInfo, zTable, '"');
    zTableInfo = appendText(zTableInfo, ");", 0);

    rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
    free(zTableInfo);
    if( rc!=SQLITE_OK || !pTableInfo ){
      return 1;
    }

    zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
    zTmp = appendText(zTmp, zTable, '"');
    if( zTmp ){
      zSelect = appendText(zSelect, zTmp, '\'');
    }
    zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
    rc = sqlite3_step(pTableInfo);
    while( rc==SQLITE_ROW ){
      const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
      zSelect = appendText(zSelect, "quote(", 0);
      zSelect = appendText(zSelect, zText, '"');
      rc = sqlite3_step(pTableInfo);
      if( rc==SQLITE_ROW ){
        zSelect = appendText(zSelect, ") || ',' || ", 0);
      }else{
        zSelect = appendText(zSelect, ") ", 0);
      }
      nRow++;
    }
    rc = sqlite3_finalize(pTableInfo);
    if( rc!=SQLITE_OK || nRow==0 ){
      free(zSelect);
      return 1;
    }
    zSelect = appendText(zSelect, "|| ')' FROM  ", 0);
    zSelect = appendText(zSelect, zTable, '"');

    rc = run_table_dump_query(p->out, p->db, zSelect, zPrepStmt);
    if( rc==SQLITE_CORRUPT ){
      zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
      rc = run_table_dump_query(p->out, p->db, zSelect, 0);
    }
    if( zSelect ) free(zSelect);
  }
  return 0;
}

/*
** Run zQuery.  Use dump_callback() as the callback routine so that
** the contents of the query are output as SQL statements.
**
** If we get a SQLITE_CORRUPT error, rerun the query after appending
** "ORDER BY rowid DESC" to the end.
*/
static int run_schema_dump_query(
  struct callback_data *p, 
  const char *zQuery,
  char **pzErrMsg
){
  int rc;
  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg);
  if( rc==SQLITE_CORRUPT ){
    char *zQ2;
    int len = strlen30(zQuery);
    if( pzErrMsg ) sqlite3_free(*pzErrMsg);
    zQ2 = malloc( len+100 );
    if( zQ2==0 ) return rc;
    sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, pzErrMsg);
    free(zQ2);
  }
  return rc;
}

#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_SUBQUERY)
struct GenfkeyCmd {
  sqlite3 *db;                   /* Database handle */
  struct callback_data *pCb;     /* Callback data */
  int isIgnoreErrors;            /* True for --ignore-errors */
  int isExec;                    /* True for --exec */
  int isNoDrop;                  /* True for --no-drop */
  int nErr;                      /* Number of errors seen so far */
};
typedef struct GenfkeyCmd GenfkeyCmd;

static int genfkeyParseArgs(GenfkeyCmd *p, char **azArg, int nArg){
  int ii;
  memset(p, 0, sizeof(GenfkeyCmd));

  for(ii=0; ii<nArg; ii++){
    int n = strlen30(azArg[ii]);

    if( n>2 && n<10 && 0==strncmp(azArg[ii], "--no-drop", n) ){
      p->isNoDrop = 1;
    }else if( n>2 && n<16 && 0==strncmp(azArg[ii], "--ignore-errors", n) ){
      p->isIgnoreErrors = 1;
    }else if( n>2 && n<7 && 0==strncmp(azArg[ii], "--exec", n) ){
      p->isExec = 1;
    }else{
      fprintf(stderr, "unknown option: %s\n", azArg[ii]);
      return -1;
    }
  }

  return SQLITE_OK;
}

static int genfkeyCmdCb(void *pCtx, int eType, const char *z){
  GenfkeyCmd *p = (GenfkeyCmd *)pCtx;
  if( eType==GENFKEY_ERROR && !p->isIgnoreErrors ){
    p->nErr++;
    fprintf(stderr, "%s\n", z);
  } 

  if( p->nErr==0 && (
        (eType==GENFKEY_CREATETRIGGER)
     || (eType==GENFKEY_DROPTRIGGER && !p->isNoDrop)
  )){
    if( p->isExec ){
      sqlite3_exec(p->db, z, 0, 0, 0);
    }else{
      char *zCol = "sql";
      callback((void *)p->pCb, 1, (char **)&z, (char **)&zCol);
    }
  }

  return SQLITE_OK;
}
#endif

/*
** Text of a help message
*/
static char zHelp[] =
  ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
  ".bail ON|OFF           Stop after hitting an error.  Default OFF\n"
  ".databases             List names and files of attached databases\n"
  ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
  "                         If TABLE specified, only dump tables matching\n"
  "                         LIKE pattern TABLE.\n"
  ".echo ON|OFF           Turn command echo on or off\n"
  ".exit                  Exit this program\n"
  ".explain ON|OFF        Turn output mode suitable for EXPLAIN on or off.\n"
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_SUBQUERY)
  ".genfkey ?OPTIONS?     Options are:\n"
  "                         --no-drop: Do not drop old fkey triggers.\n"
  "                         --ignore-errors: Ignore tables with fkey errors\n"
  "                         --exec: Execute generated SQL immediately\n"
  "                       See file tool/genfkey.README in the source \n"
  "                       distribution for further information.\n"
#endif
  ".header(s) ON|OFF      Turn display of headers on or off\n"
  ".help                  Show this message\n"
  ".import FILE TABLE     Import data from FILE into TABLE\n"
  ".indices ?TABLE?       Show names of all indices\n"
  "                         If TABLE specified, only show indices for tables\n"
  "                         matching LIKE pattern TABLE.\n"
#ifdef SQLITE_ENABLE_IOTRACE
  ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
#endif
#ifndef SQLITE_OMIT_LOAD_EXTENSION
  ".load FILE ?ENTRY?     Load an extension library\n"
#endif
  ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
  "                         csv      Comma-separated values\n"
  "                         column   Left-aligned columns.  (See .width)\n"
  "                         html     HTML <table> code\n"
  "                         insert   SQL insert statements for TABLE\n"
  "                         line     One value per line\n"
  "                         list     Values delimited by .separator string\n"
  "                         tabs     Tab-separated values\n"
  "                         tcl      TCL list elements\n"
  ".nullvalue STRING      Print STRING in place of NULL values\n"
  ".output FILENAME       Send output to FILENAME\n"
  ".output stdout         Send output to the screen\n"
  ".prompt MAIN CONTINUE  Replace the standard prompts\n"
  ".quit                  Exit this program\n"
  ".read FILENAME         Execute SQL in FILENAME\n"
  ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
  ".schema ?TABLE?        Show the CREATE statements\n"
  "                         If TABLE specified, only show tables matching\n"
  "                         LIKE pattern TABLE.\n"
  ".separator STRING      Change separator used by output mode and .import\n"
  ".show                  Show the current values for various settings\n"
  ".tables ?TABLE?        List names of tables\n"
  "                         If TABLE specified, only list tables matching\n"
  "                         LIKE pattern TABLE.\n"
  ".timeout MS            Try opening locked tables for MS milliseconds\n"
  ".width NUM NUM ...     Set column widths for \"column\" mode\n"
;

static char zTimerHelp[] =
  ".timer ON|OFF          Turn the CPU timer measurement on or off\n"
;

/* Forward reference */
static int process_input(struct callback_data *p, FILE *in);

/*
** Make sure the database is open.  If it is not, then open it.  If
** the database fails to open, print an error message and exit.
*/
static void open_db(struct callback_data *p){
  if( p->db==0 ){
    sqlite3_open(p->zDbFilename, &p->db);
    db = p->db;
    if( db && sqlite3_errcode(db)==SQLITE_OK ){
      sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
          shellstaticFunc, 0, 0);
    }
    if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
      fprintf(stderr,"Error: unable to open database \"%s\": %s\n", 
          p->zDbFilename, sqlite3_errmsg(db));
      exit(1);
    }
#ifndef SQLITE_OMIT_LOAD_EXTENSION
    sqlite3_enable_load_extension(p->db, 1);
#endif
  }
}

/*
** Do C-language style dequoting.
**
**    \t    -> tab
**    \n    -> newline
**    \r    -> carriage return
**    \NNN  -> ascii character NNN in octal
**    \\    -> backslash
*/
static void resolve_backslashes(char *z){
  int i, j;
  char c;
  for(i=j=0; (c = z[i])!=0; i++, j++){
    if( c=='\\' ){
      c = z[++i];
      if( c=='n' ){
        c = '\n';
      }else if( c=='t' ){
        c = '\t';
      }else if( c=='r' ){
        c = '\r';
      }else if( c>='0' && c<='7' ){
        c -= '0';
        if( z[i+1]>='0' && z[i+1]<='7' ){
          i++;
          c = (c<<3) + z[i] - '0';
          if( z[i+1]>='0' && z[i+1]<='7' ){
            i++;
            c = (c<<3) + z[i] - '0';
          }
        }
      }
    }
    z[j] = c;
  }
  z[j] = 0;
}

/*
** Interpret zArg as a boolean value.  Return either 0 or 1.
*/
static int booleanValue(char *zArg){
  int val = atoi(zArg);
  int j;
  for(j=0; zArg[j]; j++){
    zArg[j] = (char)tolower(zArg[j]);
  }
  if( strcmp(zArg,"on")==0 ){
    val = 1;
  }else if( strcmp(zArg,"yes")==0 ){
    val = 1;
  }
  return val;
}

/*
** If an input line begins with "." then invoke this routine to
** process that line.
**
** Return 1 on error, 2 to exit, and 0 otherwise.
*/
static int do_meta_command(char *zLine, struct callback_data *p){
  int i = 1;
  int nArg = 0;
  int n, c;
  int rc = 0;
  char *azArg[50];

  /* Parse the input line into tokens.
  */
  while( zLine[i] && nArg<ArraySize(azArg) ){
    while( isspace((unsigned char)zLine[i]) ){ i++; }
    if( zLine[i]==0 ) break;
    if( zLine[i]=='\'' || zLine[i]=='"' ){
      int delim = zLine[i++];
      azArg[nArg++] = &zLine[i];
      while( zLine[i] && zLine[i]!=delim ){ i++; }
      if( zLine[i]==delim ){
        zLine[i++] = 0;
      }
      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
    }else{
      azArg[nArg++] = &zLine[i];
      while( zLine[i] && !isspace((unsigned char)zLine[i]) ){ i++; }
      if( zLine[i] ) zLine[i++] = 0;
      resolve_backslashes(azArg[nArg-1]);
    }
  }

  /* Process the input line.
  */
  if( nArg==0 ) return 0; /* no tokens, no error */
  n = strlen30(azArg[0]);
  c = azArg[0][0];
  if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 ){
    const char *zDestFile;
    const char *zDb;
    sqlite3 *pDest;
    sqlite3_backup *pBackup;
    if( nArg==2 ){
      zDestFile = azArg[1];
      zDb = "main";
    }else{
      zDestFile = azArg[2];
      zDb = azArg[1];
    }
    rc = sqlite3_open(zDestFile, &pDest);
    if( rc!=SQLITE_OK ){
      fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
      sqlite3_close(pDest);
      return 1;
    }
    open_db(p);
    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
    if( pBackup==0 ){
      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
      sqlite3_close(pDest);
      return 1;
    }
    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
    sqlite3_backup_finish(pBackup);
    if( rc==SQLITE_DONE ){
      rc = 0;
    }else{
      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
      rc = 1;
    }
    sqlite3_close(pDest);
  }else

  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 ){
    bail_on_error = booleanValue(azArg[1]);
  }else

  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
    struct callback_data data;
    char *zErrMsg = 0;
    open_db(p);
    memcpy(&data, p, sizeof(data));
    data.showHeader = 1;
    data.mode = MODE_Column;
    data.colWidth[0] = 3;
    data.colWidth[1] = 15;
    data.colWidth[2] = 58;
    data.cnt = 0;
    sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }
  }else

  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
    char *zErrMsg = 0;
    open_db(p);
    /* When playing back a "dump", the content might appear in an order
    ** which causes immediate foreign key constraints to be violated.
    ** So disable foreign-key constraint enforcement to prevent problems. */
    fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
    fprintf(p->out, "BEGIN TRANSACTION;\n");
    p->writableSchema = 0;
    sqlite3_exec(p->db, "PRAGMA writable_schema=ON", 0, 0, 0);
    if( nArg==1 ){
      run_schema_dump_query(p, 
        "SELECT name, type, sql FROM sqlite_master "
        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'", 0
      );
      run_schema_dump_query(p, 
        "SELECT name, type, sql FROM sqlite_master "
        "WHERE name=='sqlite_sequence'", 0
      );
      run_table_dump_query(p->out, p->db,
        "SELECT sql FROM sqlite_master "
        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
      );
    }else{
      int i;
      for(i=1; i<nArg; i++){
        zShellStatic = azArg[i];
        run_schema_dump_query(p,
          "SELECT name, type, sql FROM sqlite_master "
          "WHERE tbl_name LIKE shellstatic() AND type=='table'"
          "  AND sql NOT NULL", 0);
        run_table_dump_query(p->out, p->db,
          "SELECT sql FROM sqlite_master "
          "WHERE sql NOT NULL"
          "  AND type IN ('index','trigger','view')"
          "  AND tbl_name LIKE shellstatic()", 0
        );
        zShellStatic = 0;
      }
    }
    if( p->writableSchema ){
      fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
      p->writableSchema = 0;
    }
    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF", 0, 0, 0);
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
    }else{
      fprintf(p->out, "COMMIT;\n");
    }
  }else

  if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){
    p->echoOn = booleanValue(azArg[1]);
  }else

  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
    rc = 2;
  }else

  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
    int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
    if(val == 1) {
      if(!p->explainPrev.valid) {
        p->explainPrev.valid = 1;
        p->explainPrev.mode = p->mode;
        p->explainPrev.showHeader = p->showHeader;
        memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
      }
      /* We could put this code under the !p->explainValid
      ** condition so that it does not execute if we are already in
      ** explain mode. However, always executing it allows us an easy
      ** was to reset to explain mode in case the user previously
      ** did an .explain followed by a .width, .mode or .header
      ** command.
      */
      p->mode = MODE_Explain;
      p->showHeader = 1;
      memset(p->colWidth,0,ArraySize(p->colWidth));
      p->colWidth[0] = 4;                  /* addr */
      p->colWidth[1] = 13;                 /* opcode */
      p->colWidth[2] = 4;                  /* P1 */
      p->colWidth[3] = 4;                  /* P2 */
      p->colWidth[4] = 4;                  /* P3 */
      p->colWidth[5] = 13;                 /* P4 */
      p->colWidth[6] = 2;                  /* P5 */
      p->colWidth[7] = 13;                  /* Comment */
    }else if (p->explainPrev.valid) {
      p->explainPrev.valid = 0;
      p->mode = p->explainPrev.mode;
      p->showHeader = p->explainPrev.showHeader;
      memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
    }
  }else

#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_SUBQUERY)
  if( c=='g' && strncmp(azArg[0], "genfkey", n)==0 ){
    GenfkeyCmd cmd;
    if( 0==genfkeyParseArgs(&cmd, &azArg[1], nArg-1) ){
      cmd.db = p->db;
      cmd.pCb = p;
      genfkey_create_triggers(p->db, "main", (void *)&cmd, genfkeyCmdCb);
    }
  }else
#endif

  if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
                 strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){
    p->showHeader = booleanValue(azArg[1]);
  }else

  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
    fprintf(stderr,"%s",zHelp);
    if( HAS_TIMER ){
      fprintf(stderr,"%s",zTimerHelp);
    }
  }else

  if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg>=3 ){
    char *zTable = azArg[2];    /* Insert data into this table */
    char *zFile = azArg[1];     /* The file from which to extract data */
    sqlite3_stmt *pStmt = NULL; /* A statement */
    int nCol;                   /* Number of columns in the table */
    int nByte;                  /* Number of bytes in an SQL string */
    int i, j;                   /* Loop counters */
    int nSep;                   /* Number of bytes in p->separator[] */
    char *zSql;                 /* An SQL statement */
    char *zLine;                /* A single line of input from the file */
    char **azCol;               /* zLine[] broken up into columns */
    char *zCommit;              /* How to commit changes */   
    FILE *in;                   /* The input file */
    int lineno = 0;             /* Line number of input file */

    open_db(p);
    nSep = strlen30(p->separator);
    if( nSep==0 ){
      fprintf(stderr, "Error: non-null separator required for import\n");
      return 1;
    }
    zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
    if( zSql==0 ){
      fprintf(stderr, "Error: out of memory\n");
      return 1;
    }
    nByte = strlen30(zSql);
    rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    if( rc ){
      if (pStmt) sqlite3_finalize(pStmt);
      fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
      return 1;
    }
    nCol = sqlite3_column_count(pStmt);
    sqlite3_finalize(pStmt);
    pStmt = 0;
    if( nCol==0 ) return 0; /* no columns, no error */
    zSql = malloc( nByte + 20 + nCol*2 );
    if( zSql==0 ){
      fprintf(stderr, "Error: out of memory\n");
      return 1;
    }
    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable);
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
    rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
    free(zSql);
    if( rc ){
      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
      if (pStmt) sqlite3_finalize(pStmt);
      return 1;
    }
    in = fopen(zFile, "rb");
    if( in==0 ){
      fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
      sqlite3_finalize(pStmt);
      return 1;
    }
    azCol = malloc( sizeof(azCol[0])*(nCol+1) );
    if( azCol==0 ){
      fprintf(stderr, "Error: out of memory\n");
      fclose(in);
      sqlite3_finalize(pStmt);
      return 1;
    }
    sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
    zCommit = "COMMIT";
    while( (zLine = local_getline(0, in))!=0 ){
      char *z;
      i = 0;
      lineno++;
      azCol[0] = zLine;
      for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){
        if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){
          *z = 0;
          i++;
          if( i<nCol ){
            azCol[i] = &z[nSep];
            z += nSep-1;
          }
        }
      } /* end for */
      *z = 0;
      if( i+1!=nCol ){
        fprintf(stderr,
                "Error: %s line %d: expected %d columns of data but found %d\n",
                zFile, lineno, nCol, i+1);
        zCommit = "ROLLBACK";
        free(zLine);
        rc = 1;
        break; /* from while */
      }
      for(i=0; i<nCol; i++){
        sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
      }
      sqlite3_step(pStmt);
      rc = sqlite3_reset(pStmt);
      free(zLine);
      if( rc!=SQLITE_OK ){
        fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
        zCommit = "ROLLBACK";
        rc = 1;
        break; /* from while */
      }
    } /* end while */
    free(azCol);
    fclose(in);
    sqlite3_finalize(pStmt);
    sqlite3_exec(p->db, zCommit, 0, 0, 0);
  }else

  if( c=='i' && strncmp(azArg[0], "indices", n)==0 ){
    struct callback_data data;
    char *zErrMsg = 0;
    open_db(p);
    memcpy(&data, p, sizeof(data));
    data.showHeader = 0;
    data.mode = MODE_List;
    if( nArg==1 ){
      rc = sqlite3_exec(p->db,
        "SELECT name FROM sqlite_master "
        "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
        "UNION ALL "
        "SELECT name FROM sqlite_temp_master "
        "WHERE type='index' "
        "ORDER BY 1",
        callback, &data, &zErrMsg
      );
    }else{
      zShellStatic = azArg[1];
      rc = sqlite3_exec(p->db,
        "SELECT name FROM sqlite_master "
        "WHERE type='index' AND tbl_name LIKE shellstatic() "
        "UNION ALL "
        "SELECT name FROM sqlite_temp_master "
        "WHERE type='index' AND tbl_name LIKE shellstatic() "
        "ORDER BY 1",
        callback, &data, &zErrMsg
      );
      zShellStatic = 0;
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
      rc = 1;
    }
  }else

#ifdef SQLITE_ENABLE_IOTRACE
  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
    extern void (*sqlite3IoTrace)(const char*, ...);
    if( iotrace && iotrace!=stdout ) fclose(iotrace);
    iotrace = 0;
    if( nArg<2 ){
      sqlite3IoTrace = 0;
    }else if( strcmp(azArg[1], "-")==0 ){
      sqlite3IoTrace = iotracePrintf;
      iotrace = stdout;
    }else{
      iotrace = fopen(azArg[1], "w");
      if( iotrace==0 ){
        fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
        sqlite3IoTrace = 0;
        rc = 1;
      }else{
        sqlite3IoTrace = iotracePrintf;
      }
    }
  }else
#endif

#ifndef SQLITE_OMIT_LOAD_EXTENSION
  if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
    const char *zFile, *zProc;
    char *zErrMsg = 0;
    zFile = azArg[1];
    zProc = nArg>=3 ? azArg[2] : 0;
    open_db(p);
    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
    if( rc!=SQLITE_OK ){
      fprintf(stderr, "Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }
  }else
#endif

  if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){
    int n2 = strlen30(azArg[1]);
    if( strncmp(azArg[1],"line",n2)==0
        ||
        strncmp(azArg[1],"lines",n2)==0 ){
      p->mode = MODE_Line;
    }else if( strncmp(azArg[1],"column",n2)==0
              ||
              strncmp(azArg[1],"columns",n2)==0 ){
      p->mode = MODE_Column;
    }else if( strncmp(azArg[1],"list",n2)==0 ){
      p->mode = MODE_List;
    }else if( strncmp(azArg[1],"html",n2)==0 ){
      p->mode = MODE_Html;
    }else if( strncmp(azArg[1],"tcl",n2)==0 ){
      p->mode = MODE_Tcl;
    }else if( strncmp(azArg[1],"csv",n2)==0 ){
      p->mode = MODE_Csv;
      sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
    }else if( strncmp(azArg[1],"tabs",n2)==0 ){
      p->mode = MODE_List;
      sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
    }else if( strncmp(azArg[1],"insert",n2)==0 ){
      p->mode = MODE_Insert;
      if( nArg>=3 ){
        set_table_name(p, azArg[2]);
      }else{
        set_table_name(p, "table");
      }
    }else {
      fprintf(stderr,"Error: mode should be one of: "
         "column csv html insert line list tabs tcl\n");
      rc = 1;
    }
  }else

  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
    sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
                     "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  }else

  if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
    if( p->out!=stdout ){
      fclose(p->out);
    }
    if( strcmp(azArg[1],"stdout")==0 ){
      p->out = stdout;
      sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout");
    }else{
      p->out = fopen(azArg[1], "wb");
      if( p->out==0 ){
        fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
        p->out = stdout;
        rc = 1;
      } else {
         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
      }
    }
  }else

  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
    if( nArg >= 2) {
      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
    }
    if( nArg >= 3) {
      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
    }
  }else

  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
    rc = 2;
  }else

  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
    FILE *alt = fopen(azArg[1], "rb");
    if( alt==0 ){
      fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
      rc = 1;
    }else{
      rc = process_input(p, alt);
      fclose(alt);
    }
  }else

  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 ){
    const char *zSrcFile;
    const char *zDb;
    sqlite3 *pSrc;
    sqlite3_backup *pBackup;
    int nTimeout = 0;

    if( nArg==2 ){
      zSrcFile = azArg[1];
      zDb = "main";
    }else{
      zSrcFile = azArg[2];
      zDb = azArg[1];
    }
    rc = sqlite3_open(zSrcFile, &pSrc);
    if( rc!=SQLITE_OK ){
      fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
      sqlite3_close(pSrc);
      return 1;
    }
    open_db(p);
    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
    if( pBackup==0 ){
      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
      sqlite3_close(pSrc);
      return 1;
    }
    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
          || rc==SQLITE_BUSY  ){
      if( rc==SQLITE_BUSY ){
        if( nTimeout++ >= 3 ) break;
        sqlite3_sleep(100);
      }
    }
    sqlite3_backup_finish(pBackup);
    if( rc==SQLITE_DONE ){
      rc = 0;
    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
      fprintf(stderr, "Error: source database is busy\n");
      rc = 1;
    }else{
      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
      rc = 1;
    }
    sqlite3_close(pSrc);
  }else

  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
    struct callback_data data;
    char *zErrMsg = 0;
    open_db(p);
    memcpy(&data, p, sizeof(data));
    data.showHeader = 0;
    data.mode = MODE_Semi;
    if( nArg>1 ){
      int i;
      for(i=0; azArg[1][i]; i++) azArg[1][i] = (char)tolower(azArg[1][i]);
      if( strcmp(azArg[1],"sqlite_master")==0 ){
        char *new_argv[2], *new_colv[2];
        new_argv[0] = "CREATE TABLE sqlite_master (\n"
                      "  type text,\n"
                      "  name text,\n"
                      "  tbl_name text,\n"
                      "  rootpage integer,\n"
                      "  sql text\n"
                      ")";
        new_argv[1] = 0;
        new_colv[0] = "sql";
        new_colv[1] = 0;
        callback(&data, 1, new_argv, new_colv);
        rc = SQLITE_OK;
      }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
        char *new_argv[2], *new_colv[2];
        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
                      "  type text,\n"
                      "  name text,\n"
                      "  tbl_name text,\n"
                      "  rootpage integer,\n"
                      "  sql text\n"
                      ")";
        new_argv[1] = 0;
        new_colv[0] = "sql";
        new_colv[1] = 0;
        callback(&data, 1, new_argv, new_colv);
        rc = SQLITE_OK;
      }else{
        zShellStatic = azArg[1];
        rc = sqlite3_exec(p->db,
          "SELECT sql FROM "
          "  (SELECT sql sql, type type, tbl_name tbl_name, name name"
          "     FROM sqlite_master UNION ALL"
          "   SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
          "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
          "ORDER BY substr(type,2,1), name",
          callback, &data, &zErrMsg);
        zShellStatic = 0;
      }
    }else{
      rc = sqlite3_exec(p->db,
         "SELECT sql FROM "
         "  (SELECT sql sql, type type, tbl_name tbl_name, name name"
         "     FROM sqlite_master UNION ALL"
         "   SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
         "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
         "ORDER BY substr(type,2,1), name",
         callback, &data, &zErrMsg
      );
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying schema information\n");
      rc = 1;
    }else{
      rc = 0;
    }
  }else

  if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
    sqlite3_snprintf(sizeof(p->separator), p->separator,
                     "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  }else

  if( c=='s' && strncmp(azArg[0], "show", n)==0){
    int i;
    fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
    fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
    fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
    fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
    fprintf(p->out,"%9.9s: ", "nullvalue");
      output_c_string(p->out, p->nullvalue);
      fprintf(p->out, "\n");
    fprintf(p->out,"%9.9s: %s\n","output",
            strlen30(p->outfile) ? p->outfile : "stdout");
    fprintf(p->out,"%9.9s: ", "separator");
      output_c_string(p->out, p->separator);
      fprintf(p->out, "\n");
    fprintf(p->out,"%9.9s: ","width");
    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
      fprintf(p->out,"%d ",p->colWidth[i]);
    }
    fprintf(p->out,"\n");
  }else

  if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
    char **azResult;
    int nRow;
    char *zErrMsg;
    open_db(p);
    if( nArg==1 ){
      rc = sqlite3_get_table(p->db,
        "SELECT name FROM sqlite_master "
        "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
        "UNION ALL "
        "SELECT name FROM sqlite_temp_master "
        "WHERE type IN ('table','view') "
        "ORDER BY 1",
        &azResult, &nRow, 0, &zErrMsg
      );
    }else{
      zShellStatic = azArg[1];
      rc = sqlite3_get_table(p->db,
        "SELECT name FROM sqlite_master "
        "WHERE type IN ('table','view') AND name LIKE shellstatic() "
        "UNION ALL "
        "SELECT name FROM sqlite_temp_master "
        "WHERE type IN ('table','view') AND name LIKE shellstatic() "
        "ORDER BY 1",
        &azResult, &nRow, 0, &zErrMsg
      );
      zShellStatic = 0;
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
      rc = 1;
    }else{
      int len, maxlen = 0;
      int i, j;
      int nPrintCol, nPrintRow;
      for(i=1; i<=nRow; i++){
        if( azResult[i]==0 ) continue;
        len = strlen30(azResult[i]);
        if( len>maxlen ) maxlen = len;
      }
      nPrintCol = 80/(maxlen+2);
      if( nPrintCol<1 ) nPrintCol = 1;
      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
      for(i=0; i<nPrintRow; i++){
        for(j=i+1; j<=nRow; j+=nPrintRow){
          char *zSp = j<=nPrintRow ? "" : "  ";
          printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
        }
        printf("\n");
      }
    }
    sqlite3_free_table(azResult);
  }else

  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){
    open_db(p);
    sqlite3_busy_timeout(p->db, atoi(azArg[1]));
  }else if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg>1 ){
    enableTimer = booleanValue(azArg[1]);
  }else if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
    int j;
    assert( nArg<=ArraySize(azArg) );
    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
      p->colWidth[j-1] = atoi(azArg[j]);
    }
  }else

  {
    fprintf(stderr, "Error: unknown command or invalid arguments: "
      " \"%s\". Enter \".help\" for help\n", azArg[0]);
    rc = 1;
  }

  return rc;
}

/*
** Return TRUE if a semicolon occurs anywhere in the first N characters
** of string z[].
*/
static int _contains_semicolon(const char *z, int N){
  int i;
  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
  return 0;
}

/*
** Test to see if a line consists entirely of whitespace.
*/
static int _all_whitespace(const char *z){
  for(; *z; z++){
    if( isspace(*(unsigned char*)z) ) continue;
    if( *z=='/' && z[1]=='*' ){
      z += 2;
      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
      if( *z==0 ) return 0;
      z++;
      continue;
    }
    if( *z=='-' && z[1]=='-' ){
      z += 2;
      while( *z && *z!='\n' ){ z++; }
      if( *z==0 ) return 1;
      continue;
    }
    return 0;
  }
  return 1;
}

/*
** Return TRUE if the line typed in is an SQL command terminator other
** than a semi-colon.  The SQL Server style "go" command is understood
** as is the Oracle "/".
*/
static int _is_command_terminator(const char *zLine){
  while( isspace(*(unsigned char*)zLine) ){ zLine++; };
  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
    return 1;  /* Oracle */
  }
  if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o'
         && _all_whitespace(&zLine[2]) ){
    return 1;  /* SQL Server */
  }
  return 0;
}

/*
** Return true if zSql is a complete SQL statement.  Return false if it
** ends in the middle of a string literal or C-style comment.
*/
static int _is_complete(char *zSql, int nSql){
  int rc;
  if( zSql==0 ) return 1;
  zSql[nSql] = ';';
  zSql[nSql+1] = 0;
  rc = sqlite3_complete(zSql);
  zSql[nSql] = 0;
  return rc;
}

/*
** Read input from *in and process it.  If *in==0 then input
** is interactive - the user is typing it it.  Otherwise, input
** is coming from a file or device.  A prompt is issued and history
** is saved only if input is interactive.  An interrupt signal will
** cause this routine to exit immediately, unless input is interactive.
**
** Return the number of errors.
*/
static int process_input(struct callback_data *p, FILE *in){
  char *zLine = 0;
  char *zSql = 0;
  int nSql = 0;
  int nSqlPrior = 0;
  char *zErrMsg;
  int rc;
  int errCnt = 0;
  int lineno = 0;
  int startline = 0;

  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
    fflush(p->out);
    free(zLine);
    zLine = one_input_line(zSql, in);
    if( zLine==0 ){
      break;  /* We have reached EOF */
    }
    if( seenInterrupt ){
      if( in!=0 ) break;
      seenInterrupt = 0;
    }
    lineno++;
    if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
    if( zLine && zLine[0]=='.' && nSql==0 ){
      if( p->echoOn ) printf("%s\n", zLine);
      rc = do_meta_command(zLine, p);
      if( rc==2 ){ /* exit requested */
        break;
      }else if( rc ){
        errCnt++;
      }
      continue;
    }
    if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
      memcpy(zLine,";",2);
    }
    nSqlPrior = nSql;
    if( zSql==0 ){
      int i;
      for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){}
      if( zLine[i]!=0 ){
        nSql = strlen30(zLine);
        zSql = malloc( nSql+3 );
        if( zSql==0 ){
          fprintf(stderr, "Error: out of memory\n");
          exit(1);
        }
        memcpy(zSql, zLine, nSql+1);
        startline = lineno;
      }
    }else{
      int len = strlen30(zLine);
      zSql = realloc( zSql, nSql + len + 4 );
      if( zSql==0 ){
        fprintf(stderr,"Error: out of memory\n");
        exit(1);
      }
      zSql[nSql++] = '\n';
      memcpy(&zSql[nSql], zLine, len+1);
      nSql += len;
    }
    if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
                && sqlite3_complete(zSql) ){
      p->cnt = 0;
      open_db(p);
      BEGIN_TIMER;
      rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
      END_TIMER;
      if( rc || zErrMsg ){
        char zPrefix[100];
        if( in!=0 || !stdin_is_interactive ){
          sqlite3_snprintf(sizeof(zPrefix), zPrefix, 
                           "Error: near line %d:", startline);
        }else{
          sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
        }
        if( zErrMsg!=0 ){
          fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
          sqlite3_free(zErrMsg);
          zErrMsg = 0;
        }else{
          fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
        }
        errCnt++;
      }
      free(zSql);
      zSql = 0;
      nSql = 0;
    }
  }
  if( zSql ){
    if( !_all_whitespace(zSql) ) fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
    free(zSql);
  }
  free(zLine);
  return errCnt;
}

/*
** Return a pathname which is the user's home directory.  A
** 0 return indicates an error of some kind.  Space to hold the
** resulting string is obtained from malloc().  The calling
** function should free the result.
*/
static char *find_home_dir(void){
  char *home_dir = NULL;

#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  struct passwd *pwent;
  uid_t uid = getuid();
  if( (pwent=getpwuid(uid)) != NULL) {
    home_dir = pwent->pw_dir;
  }
#endif

#if defined(_WIN32_WCE)
  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
   */
  home_dir = strdup("/");
#else

#if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  if (!home_dir) {
    home_dir = getenv("USERPROFILE");
  }
#endif

  if (!home_dir) {
    home_dir = getenv("HOME");
  }

#if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  if (!home_dir) {
    char *zDrive, *zPath;
    int n;
    zDrive = getenv("HOMEDRIVE");
    zPath = getenv("HOMEPATH");
    if( zDrive && zPath ){
      n = strlen30(zDrive) + strlen30(zPath) + 1;
      home_dir = malloc( n );
      if( home_dir==0 ) return 0;
      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
      return home_dir;
    }
    home_dir = "c:\\";
  }
#endif

#endif /* !_WIN32_WCE */

  if( home_dir ){
    int n = strlen30(home_dir) + 1;
    char *z = malloc( n );
    if( z ) memcpy(z, home_dir, n);
    home_dir = z;
  }

  return home_dir;
}

/*
** Read input from the file given by sqliterc_override.  Or if that
** parameter is NULL, take input from ~/.sqliterc
**
** Returns the number of errors.
*/
static int process_sqliterc(
  struct callback_data *p,        /* Configuration data */
  const char *sqliterc_override   /* Name of config file. NULL to use default */
){
  char *home_dir = NULL;
  const char *sqliterc = sqliterc_override;
  char *zBuf = 0;
  FILE *in = NULL;
  int nBuf;
  int rc = 0;

  if (sqliterc == NULL) {
    home_dir = find_home_dir();
    if( home_dir==0 ){
#if !defined(__RTP__) && !defined(_WRS_KERNEL)
      fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
#endif
      return 1;
    }
    nBuf = strlen30(home_dir) + 16;
    zBuf = malloc( nBuf );
    if( zBuf==0 ){
      fprintf(stderr,"%s: Error: out of memory\n",Argv0);
      return 1;
    }
    sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
    free(home_dir);
    sqliterc = (const char*)zBuf;
  }
  in = fopen(sqliterc,"rb");
  if( in ){
    if( stdin_is_interactive ){
      fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
    }
    rc = process_input(p,in);
    fclose(in);
  }
  free(zBuf);
  return rc;
}

/*
** Show available command line options
*/
static const char zOptions[] = 
  "   -init filename       read/process named file\n"
  "   -echo                print commands before execution\n"
  "   -[no]header          turn headers on or off\n"
  "   -bail                stop after hitting an error\n"
  "   -interactive         force interactive I/O\n"
  "   -batch               force batch I/O\n"
  "   -column              set output mode to 'column'\n"
  "   -csv                 set output mode to 'csv'\n"
  "   -html                set output mode to HTML\n"
  "   -line                set output mode to 'line'\n"
  "   -list                set output mode to 'list'\n"
  "   -separator 'x'       set output field separator (|)\n"
  "   -nullvalue 'text'    set text string for NULL values\n"
  "   -version             show SQLite version\n"
;
static void usage(int showDetail){
  fprintf(stderr,
      "Usage: %s [OPTIONS] FILENAME [SQL]\n"  
      "FILENAME is the name of an SQLite database. A new database is created\n"
      "if the file does not previously exist.\n", Argv0);
  if( showDetail ){
    fprintf(stderr, "OPTIONS include:\n%s", zOptions);
  }else{
    fprintf(stderr, "Use the -help option for additional information\n");
  }
  exit(1);
}

/*
** Initialize the state information in data
*/
static void main_init(struct callback_data *data) {
  memset(data, 0, sizeof(*data));
  data->mode = MODE_List;
  memcpy(data->separator,"|", 2);
  data->showHeader = 0;
  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
}

int main(int argc, char **argv){
  char *zErrMsg = 0;
  struct callback_data data;
  const char *zInitFile = 0;
  char *zFirstCmd = 0;
  int i;
  int rc = 0;

  Argv0 = argv[0];
  main_init(&data);
  stdin_is_interactive = isatty(0);

  /* Make sure we have a valid signal handler early, before anything
  ** else is done.
  */
#ifdef SIGINT
  signal(SIGINT, interrupt_handler);
#endif

  /* Do an initial pass through the command-line argument to locate
  ** the name of the database file, the name of the initialization file,
  ** and the first command to execute.
  */
  for(i=1; i<argc-1; i++){
    char *z;
    if( argv[i][0]!='-' ) break;
    z = argv[i];
    if( z[0]=='-' && z[1]=='-' ) z++;
    if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
      i++;
    }else if( strcmp(argv[i],"-init")==0 ){
      i++;
      zInitFile = argv[i];
    /* Need to check for batch mode here to so we can avoid printing
    ** informational messages (like from process_sqliterc) before 
    ** we do the actual processing of arguments later in a second pass.
    */
    }else if( strcmp(argv[i],"-batch")==0 ){
      i++;
      stdin_is_interactive = 0;
    }
  }
  if( i<argc ){
#if defined(SQLITE_OS_OS2) && SQLITE_OS_OS2
    data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] );
#else
    data.zDbFilename = argv[i++];
#endif
  }else{
#ifndef SQLITE_OMIT_MEMORYDB
    data.zDbFilename = ":memory:";
#else
    data.zDbFilename = 0;
#endif
  }
  if( i<argc ){
    zFirstCmd = argv[i++];
  }
  data.out = stdout;

#ifdef SQLITE_OMIT_MEMORYDB
  if( data.zDbFilename==0 ){
    fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
    return 1;
  }
#endif

  /* Go ahead and open the database file if it already exists.  If the
  ** file does not exist, delay opening it.  This prevents empty database
  ** files from being created if a user mistypes the database name argument
  ** to the sqlite command-line tool.
  */
  if( access(data.zDbFilename, 0)==0 ){
    open_db(&data);
  }

  /* Process the initialization file if there is one.  If no -init option
  ** is given on the command line, look for a file named ~/.sqliterc and
  ** try to process it.
  */
  rc = process_sqliterc(&data,zInitFile);
  if( rc>0 ){
    return rc;
  }

  /* Make a second pass through the command-line argument and set
  ** options.  This second pass is delayed until after the initialization
  ** file is processed so that the command-line arguments will override
  ** settings in the initialization file.
  */
  for(i=1; i<argc && argv[i][0]=='-'; i++){
    char *z = argv[i];
    if( z[1]=='-' ){ z++; }
    if( strcmp(z,"-init")==0 ){
      i++;
    }else if( strcmp(z,"-html")==0 ){
      data.mode = MODE_Html;
    }else if( strcmp(z,"-list")==0 ){
      data.mode = MODE_List;
    }else if( strcmp(z,"-line")==0 ){
      data.mode = MODE_Line;
    }else if( strcmp(z,"-column")==0 ){
      data.mode = MODE_Column;
    }else if( strcmp(z,"-csv")==0 ){
      data.mode = MODE_Csv;
      memcpy(data.separator,",",2);
    }else if( strcmp(z,"-separator")==0 ){
      i++;
      sqlite3_snprintf(sizeof(data.separator), data.separator,
                       "%.*s",(int)sizeof(data.separator)-1,argv[i]);
    }else if( strcmp(z,"-nullvalue")==0 ){
      i++;
      sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
                       "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
    }else if( strcmp(z,"-header")==0 ){
      data.showHeader = 1;
    }else if( strcmp(z,"-noheader")==0 ){
      data.showHeader = 0;
    }else if( strcmp(z,"-echo")==0 ){
      data.echoOn = 1;
    }else if( strcmp(z,"-bail")==0 ){
      bail_on_error = 1;
    }else if( strcmp(z,"-version")==0 ){
      printf("%s\n", sqlite3_libversion());
      return 0;
    }else if( strcmp(z,"-interactive")==0 ){
      stdin_is_interactive = 1;
    }else if( strcmp(z,"-batch")==0 ){
      stdin_is_interactive = 0;
    }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){
      usage(1);
    }else{
      fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
      fprintf(stderr,"Use -help for a list of options.\n");
      return 1;
    }
  }

  if( zFirstCmd ){
    /* Run just the command that follows the database name
    */
    if( zFirstCmd[0]=='.' ){
      rc = do_meta_command(zFirstCmd, &data);
      return rc;
    }else{
      open_db(&data);
      rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
      if( zErrMsg!=0 ){
        fprintf(stderr,"Error: %s\n", zErrMsg);
        return rc!=0 ? rc : 1;
      }else if( rc!=0 ){
        fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
        return rc;
      }
    }
  }else{
    /* Run commands received from standard input
    */
    if( stdin_is_interactive ){
      char *zHome;
      char *zHistory = 0;
      int nHistory;
      printf(
        "SQLite version %s\n"
        "Enter \".help\" for instructions\n"
        "Enter SQL statements terminated with a \";\"\n",
        sqlite3_libversion()
      );
      zHome = find_home_dir();
      if( zHome ){
        nHistory = strlen30(zHome) + 20;
        if( (zHistory = malloc(nHistory))!=0 ){
          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
        }
      }
#if defined(HAVE_READLINE) && HAVE_READLINE==1
      if( zHistory ) read_history(zHistory);
#endif
      rc = process_input(&data, 0);
      if( zHistory ){
        stifle_history(100);
        write_history(zHistory);
        free(zHistory);
      }
      free(zHome);
    }else{
      rc = process_input(&data, stdin);
    }
  }
  set_table_name(&data, 0);
  if( db ){
    if( sqlite3_close(db)!=SQLITE_OK ){
      fprintf(stderr,"Error: cannot close database \"%s\"\n", sqlite3_errmsg(db));
      rc++;
    }
  }
  return rc;
}

Added src/sqlite.h.in.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the SQLite library
** presents to client programs.  If a C-function, structure, datatype,
** or constant definition does not appear in this file, then it is
** not a published API of SQLite, is subject to change without
** notice, and should not be referenced by programs that use SQLite.
**
** Some of the definitions that are in this file are marked as
** "experimental".  Experimental interfaces are normally new
** features recently added to SQLite.  We do not anticipate changes
** to experimental interfaces but reserve the right to make minor changes
** if experience from use "in the wild" suggest such changes are prudent.
**
** The official C-language API documentation for SQLite is derived
** from comments in this file.  This file is the authoritative source
** on how SQLite interfaces are suppose to operate.
**
** The name of this file under configuration management is "sqlite.h.in".
** The makefile makes some minor changes to this file (such as inserting
** the version number) and changes its name to "sqlite3.h" as
** part of the build process.
*/
#ifndef _SQLITE3_H_
#define _SQLITE3_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
*/
#ifdef __cplusplus
extern "C" {
#endif


/*
** Add the ability to override 'extern'
*/
#ifndef SQLITE_EXTERN
# define SQLITE_EXTERN extern
#endif

/*
** These no-op macros are used in front of interfaces to mark those
** interfaces as either deprecated or experimental.  New applications
** should not use deprecated interfaces - they are support for backwards
** compatibility only.  Application writers should be aware that
** experimental interfaces are subject to change in point releases.
**
** These macros used to resolve to various kinds of compiler magic that
** would generate warning messages when they were used.  But that
** compiler magic ended up generating such a flurry of bug reports
** that we have taken it all out and gone back to using simple
** noop macros.
*/
#define SQLITE_DEPRECATED
#define SQLITE_EXPERIMENTAL

/*
** Ensure these symbols were not defined by some previous header file.
*/
#ifdef SQLITE_VERSION
# undef SQLITE_VERSION
#endif
#ifdef SQLITE_VERSION_NUMBER
# undef SQLITE_VERSION_NUMBER
#endif

/*
** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
**
** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
** the sqlite3.h file specify the version of SQLite with which
** that header file is associated.
**
** The "version" of SQLite is a string of the form "W.X.Y" or "W.X.Y.Z".
** The W value is major version number and is always 3 in SQLite3.
** The W value only changes when backwards compatibility is
** broken and we intend to never break backwards compatibility.
** The X value is the minor version number and only changes when
** there are major feature enhancements that are forwards compatible
** but not backwards compatible.
** The Y value is the release number and is incremented with
** each release but resets back to 0 whenever X is incremented.
** The Z value only appears on branch releases.
**
** The SQLITE_VERSION_NUMBER is an integer that is computed as
** follows:
**
** <blockquote><pre>
** SQLITE_VERSION_NUMBER = W*1000000 + X*1000 + Y
** </pre></blockquote>
**
** Since version 3.6.18, SQLite source code has been stored in the
** <a href="http://www.fossil-scm.org/">fossil configuration management
** system</a>.  The SQLITE_SOURCE_ID
** macro is a string which identifies a particular check-in of SQLite
** within its configuration management system.  The string contains the
** date and time of the check-in (UTC) and an SHA1 hash of the entire
** source tree.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
**
** Requirements: [H10011] [H10014]
*/
#define SQLITE_VERSION        "--VERS--"
#define SQLITE_VERSION_NUMBER --VERSION-NUMBER--
#define SQLITE_SOURCE_ID      "--SOURCE-ID--"

/*
** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
** KEYWORDS: sqlite3_version
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] #defines in the header,
** but are associated with the library instead of the header file.  Cautious
** programmers might include assert() statements in their application to
** verify that values returned by these interfaces match the macros in
** the header, and thus insure that the application is
** compiled with matching library and header files.
**
** <blockquote><pre>
** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
** assert( strcmp(sqlite3_libversion,SQLITE_VERSION)==0 );
** </pre></blockquote>
**
** The sqlite3_libversion() function returns the same information as is
** in the sqlite3_version[] string constant.  The function is provided
** for use in DLLs since DLL users usually do not have direct access to string
** constants within the DLL.  Similarly, the sqlite3_sourceid() function
** returns the same information as is in the [SQLITE_SOURCE_ID] #define of
** the header file.
**
** See also: [sqlite_version()] and [sqlite_source_id()].
**
** Requirements: [H10021] [H10022] [H10023]
*/
SQLITE_EXTERN const char sqlite3_version[];
const char *sqlite3_libversion(void);
const char *sqlite3_sourceid(void);
int sqlite3_libversion_number(void);

/*
** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
**
** SQLite can be compiled with or without mutexes.  When
** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
** are enabled and SQLite is threadsafe.  When the
** [SQLITE_THREADSAFE] macro is 0, 
** the mutexes are omitted.  Without the mutexes, it is not safe
** to use SQLite concurrently from more than one thread.
**
** Enabling mutexes incurs a measurable performance penalty.
** So if speed is of utmost importance, it makes sense to disable
** the mutexes.  But for maximum safety, mutexes should be enabled.
** The default behavior is for mutexes to be enabled.
**
** This interface can be used by an application to make sure that the
** version of SQLite that it is linking against was compiled with
** the desired setting of the [SQLITE_THREADSAFE] macro.
**
** This interface only reports on the compile-time mutex setting
** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
** can be fully or partially disabled using a call to [sqlite3_config()]
** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
** or [SQLITE_CONFIG_MUTEX].  The return value of this function shows
** only the default compile-time setting, not any run-time changes
** to that setting.
**
** See the [threading mode] documentation for additional information.
**
** Requirements: [H10101] [H10102]
*/
int sqlite3_threadsafe(void);

/*
** CAPI3REF: Database Connection Handle {H12000} <S40200>
** KEYWORDS: {database connection} {database connections}
**
** Each open SQLite database is represented by a pointer to an instance of
** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
** is its destructor.  There are many other interfaces (such as
** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
** [sqlite3_busy_timeout()] to name but three) that are methods on an
** sqlite3 object.
*/
typedef struct sqlite3 sqlite3;

/*
** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
** KEYWORDS: sqlite_int64 sqlite_uint64
**
** Because there is no cross-platform way to specify 64-bit integer types
** SQLite includes typedefs for 64-bit signed and unsigned integers.
**
** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
** The sqlite_int64 and sqlite_uint64 types are supported for backwards
** compatibility only.
**
** Requirements: [H10201] [H10202]
*/
#ifdef SQLITE_INT64_TYPE
  typedef SQLITE_INT64_TYPE sqlite_int64;
  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
#elif defined(_MSC_VER) || defined(__BORLANDC__)
  typedef __int64 sqlite_int64;
  typedef unsigned __int64 sqlite_uint64;
#else
  typedef long long int sqlite_int64;
  typedef unsigned long long int sqlite_uint64;
#endif
typedef sqlite_int64 sqlite3_int64;
typedef sqlite_uint64 sqlite3_uint64;

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point.
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite3_int64
#endif

/*
** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
**
** This routine is the destructor for the [sqlite3] object.
**
** Applications must [sqlite3_finalize | finalize] all [prepared statements]
** and [sqlite3_blob_close | close] all [BLOB handles] associated with
** the [sqlite3] object prior to attempting to close the object.
**
** If [sqlite3_close()] is invoked while a transaction is open,
** the transaction is automatically rolled back.
**
** The C parameter to [sqlite3_close(C)] must be either a NULL
** pointer or an [sqlite3] object pointer obtained
** from [sqlite3_open()], [sqlite3_open16()], or
** [sqlite3_open_v2()], and not previously closed.
**
** Requirements:
** [H12011] [H12012] [H12013] [H12014] [H12015] [H12019]
*/
int sqlite3_close(sqlite3 *);

/*
** The type for a callback function.
** This is legacy and deprecated.  It is included for historical
** compatibility and is not documented.
*/
typedef int (*sqlite3_callback)(void*,int,char**, char**);

/*
** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
**
** The sqlite3_exec() interface is a convenient way of running one or more
** SQL statements without having to write a lot of C code.  The UTF-8 encoded
** SQL statements are passed in as the second parameter to sqlite3_exec().
** The statements are evaluated one by one until either an error or
** an interrupt is encountered, or until they are all done.  The 3rd parameter
** is an optional callback that is invoked once for each row of any query
** results produced by the SQL statements.  The 5th parameter tells where
** to write any error messages.
**
** The error message passed back through the 5th parameter is held
** in memory obtained from [sqlite3_malloc()].  To avoid a memory leak,
** the calling application should call [sqlite3_free()] on any error
** message returned through the 5th parameter when it has finished using
** the error message.
**
** If the SQL statement in the 2nd parameter is NULL or an empty string
** or a string containing only whitespace and comments, then no SQL
** statements are evaluated and the database is not changed.
**
** The sqlite3_exec() interface is implemented in terms of
** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
** The sqlite3_exec() routine does nothing to the database that cannot be done
** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
**
** The first parameter to [sqlite3_exec()] must be an valid and open
** [database connection].
**
** The database connection must not be closed while
** [sqlite3_exec()] is running.
**
** The calling function should use [sqlite3_free()] to free
** the memory that *errmsg is left pointing at once the error
** message is no longer needed.
**
** The SQL statement text in the 2nd parameter to [sqlite3_exec()]
** must remain unchanged while [sqlite3_exec()] is running.
**
** Requirements:
** [H12101] [H12102] [H12104] [H12105] [H12107] [H12110] [H12113] [H12116]
** [H12119] [H12122] [H12125] [H12131] [H12134] [H12137] [H12138]
*/
int sqlite3_exec(
  sqlite3*,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluated */
  int (*callback)(void*,int,char**,char**),  /* Callback function */
  void *,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
);

/*
** CAPI3REF: Result Codes {H10210} <S10700>
** KEYWORDS: SQLITE_OK {error code} {error codes}
** KEYWORDS: {result code} {result codes}
**
** Many SQLite functions return an integer result code from the set shown
** here in order to indicates success or failure.
**
** New error codes may be added in future versions of SQLite.
**
** See also: [SQLITE_IOERR_READ | extended result codes]
*/
#define SQLITE_OK           0   /* Successful result */
/* beginning-of-error-codes */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
#define SQLITE_EMPTY       16   /* Database is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_FORMAT      24   /* Auxiliary database format error */
#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
#define SQLITE_NOTADB      26   /* File opened that is not a database file */
#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
/* end-of-error-codes */

/*
** CAPI3REF: Extended Result Codes {H10220} <S10700>
** KEYWORDS: {extended error code} {extended error codes}
** KEYWORDS: {extended result code} {extended result codes}
**
** In its default configuration, SQLite API routines return one of 26 integer
** [SQLITE_OK | result codes].  However, experience has shown that many of
** these result codes are too coarse-grained.  They do not provide as
** much information about problems as programmers might like.  In an effort to
** address this, newer versions of SQLite (version 3.3.8 and later) include
** support for additional result codes that provide more detailed information
** about errors. The extended result codes are enabled or disabled
** on a per database connection basis using the
** [sqlite3_extended_result_codes()] API.
**
** Some of the available extended result codes are listed here.
** One may expect the number of extended result codes will be expand
** over time.  Software that uses extended result codes should expect
** to see new result codes in future releases of SQLite.
**
** The SQLITE_OK result code will never be extended.  It will always
** be exactly zero.
*/
#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )

/*
** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
**
** These bit values are intended for use in the
** 3rd parameter to the [sqlite3_open_v2()] interface and
** in the 4th parameter to the xOpen method of the
** [sqlite3_vfs] object.
*/
#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */

/*
** CAPI3REF: Device Characteristics {H10240} <H11120>
**
** The xDeviceCapabilities method of the [sqlite3_io_methods]
** object returns an integer which is a vector of the these
** bit values expressing I/O characteristics of the mass storage
** device that holds the file that the [sqlite3_io_methods]
** refers to.
**
** The SQLITE_IOCAP_ATOMIC property means that all writes of
** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
** mean that writes of blocks that are nnn bytes in size and
** are aligned to an address which is an integer multiple of
** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
** that when data is appended to a file, the data is appended
** first then the size of the file is extended, never the other
** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
** information is written to disk in the same order as calls
** to xWrite().
*/
#define SQLITE_IOCAP_ATOMIC          0x00000001
#define SQLITE_IOCAP_ATOMIC512       0x00000002
#define SQLITE_IOCAP_ATOMIC1K        0x00000004
#define SQLITE_IOCAP_ATOMIC2K        0x00000008
#define SQLITE_IOCAP_ATOMIC4K        0x00000010
#define SQLITE_IOCAP_ATOMIC8K        0x00000020
#define SQLITE_IOCAP_ATOMIC16K       0x00000040
#define SQLITE_IOCAP_ATOMIC32K       0x00000080
#define SQLITE_IOCAP_ATOMIC64K       0x00000100
#define SQLITE_IOCAP_SAFE_APPEND     0x00000200
#define SQLITE_IOCAP_SEQUENTIAL      0x00000400

/*
** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
**
** SQLite uses one of these integer values as the second
** argument to calls it makes to the xLock() and xUnlock() methods
** of an [sqlite3_io_methods] object.
*/
#define SQLITE_LOCK_NONE          0
#define SQLITE_LOCK_SHARED        1
#define SQLITE_LOCK_RESERVED      2
#define SQLITE_LOCK_PENDING       3
#define SQLITE_LOCK_EXCLUSIVE     4

/*
** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
**
** When SQLite invokes the xSync() method of an
** [sqlite3_io_methods] object it uses a combination of
** these integer values as the second argument.
**
** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
** sync operation only needs to flush data to mass storage.  Inode
** information need not be flushed. If the lower four bits of the flag
** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
** If the lower four bits equal SQLITE_SYNC_FULL, that means
** to use Mac OS X style fullsync instead of fsync().
*/
#define SQLITE_SYNC_NORMAL        0x00002
#define SQLITE_SYNC_FULL          0x00003
#define SQLITE_SYNC_DATAONLY      0x00010

/*
** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
**
** An [sqlite3_file] object represents an open file in the 
** [sqlite3_vfs | OS interface layer].  Individual OS interface
** implementations will
** want to subclass this object by appending additional fields
** for their own use.  The pMethods entry is a pointer to an
** [sqlite3_io_methods] object that defines methods for performing
** I/O operations on the open file.
*/
typedef struct sqlite3_file sqlite3_file;
struct sqlite3_file {
  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
};

/*
** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
**
** Every file opened by the [sqlite3_vfs] xOpen method populates an
** [sqlite3_file] object (or, more commonly, a subclass of the
** [sqlite3_file] object) with a pointer to an instance of this object.
** This object defines the methods used to perform various operations
** against the open file represented by the [sqlite3_file] object.
**
** If the xOpen method sets the sqlite3_file.pMethods element 
** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
** may be invoked even if the xOpen reported that it failed.  The
** only way to prevent a call to xClose following a failed xOpen
** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
**
** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
** flag may be ORed in to indicate that only the data of the file
** and not its inode needs to be synced.
**
** The integer values to xLock() and xUnlock() are one of
** <ul>
** <li> [SQLITE_LOCK_NONE],
** <li> [SQLITE_LOCK_SHARED],
** <li> [SQLITE_LOCK_RESERVED],
** <li> [SQLITE_LOCK_PENDING], or
** <li> [SQLITE_LOCK_EXCLUSIVE].
** </ul>
** xLock() increases the lock. xUnlock() decreases the lock.
** The xCheckReservedLock() method checks whether any database connection,
** either in this process or in some other process, is holding a RESERVED,
** PENDING, or EXCLUSIVE lock on the file.  It returns true
** if such a lock exists and false otherwise.
**
** The xFileControl() method is a generic interface that allows custom
** VFS implementations to directly control an open file using the
** [sqlite3_file_control()] interface.  The second "op" argument is an
** integer opcode.  The third argument is a generic pointer intended to
** point to a structure that may contain arguments or space in which to
** write return values.  Potential uses for xFileControl() might be
** functions to enable blocking locks with timeouts, to change the
** locking strategy (for example to use dot-file locks), to inquire
** about the status of a lock, or to break stale locks.  The SQLite
** core reserves all opcodes less than 100 for its own use.
** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
** Applications that define a custom xFileControl method should use opcodes
** greater than 100 to avoid conflicts.
**
** The xSectorSize() method returns the sector size of the
** device that underlies the file.  The sector size is the
** minimum write that can be performed without disturbing
** other bytes in the file.  The xDeviceCharacteristics()
** method returns a bit vector describing behaviors of the
** underlying device:
**
** <ul>
** <li> [SQLITE_IOCAP_ATOMIC]
** <li> [SQLITE_IOCAP_ATOMIC512]
** <li> [SQLITE_IOCAP_ATOMIC1K]
** <li> [SQLITE_IOCAP_ATOMIC2K]
** <li> [SQLITE_IOCAP_ATOMIC4K]
** <li> [SQLITE_IOCAP_ATOMIC8K]
** <li> [SQLITE_IOCAP_ATOMIC16K]
** <li> [SQLITE_IOCAP_ATOMIC32K]
** <li> [SQLITE_IOCAP_ATOMIC64K]
** <li> [SQLITE_IOCAP_SAFE_APPEND]
** <li> [SQLITE_IOCAP_SEQUENTIAL]
** </ul>
**
** The SQLITE_IOCAP_ATOMIC property means that all writes of
** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
** mean that writes of blocks that are nnn bytes in size and
** are aligned to an address which is an integer multiple of
** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
** that when data is appended to a file, the data is appended
** first then the size of the file is extended, never the other
** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
** information is written to disk in the same order as calls
** to xWrite().
**
** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
** in the unread portions of the buffer with zeros.  A VFS that
** fails to zero-fill short reads might seem to work.  However,
** failure to zero-fill short reads will eventually lead to
** database corruption.
*/
typedef struct sqlite3_io_methods sqlite3_io_methods;
struct sqlite3_io_methods {
  int iVersion;
  int (*xClose)(sqlite3_file*);
  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  int (*xSync)(sqlite3_file*, int flags);
  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  int (*xLock)(sqlite3_file*, int);
  int (*xUnlock)(sqlite3_file*, int);
  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  int (*xSectorSize)(sqlite3_file*);
  int (*xDeviceCharacteristics)(sqlite3_file*);
  /* Additional methods may be added in future releases */
};

/*
** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
**
** These integer constants are opcodes for the xFileControl method
** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
** interface.
**
** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
** opcode causes the xFileControl method to write the current state of
** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
** into an integer that the pArg argument points to. This capability
** is used during testing and only needs to be supported when SQLITE_TEST
** is defined.
*/
#define SQLITE_FCNTL_LOCKSTATE        1
#define SQLITE_GET_LOCKPROXYFILE      2
#define SQLITE_SET_LOCKPROXYFILE      3
#define SQLITE_LAST_ERRNO             4

/*
** CAPI3REF: Mutex Handle {H17110} <S20130>
**
** The mutex module within SQLite defines [sqlite3_mutex] to be an
** abstract type for a mutex object.  The SQLite core never looks
** at the internal representation of an [sqlite3_mutex].  It only
** deals with pointers to the [sqlite3_mutex] object.
**
** Mutexes are created using [sqlite3_mutex_alloc()].
*/
typedef struct sqlite3_mutex sqlite3_mutex;

/*
** CAPI3REF: OS Interface Object {H11140} <S20100>
**
** An instance of the sqlite3_vfs object defines the interface between
** the SQLite core and the underlying operating system.  The "vfs"
** in the name of the object stands for "virtual file system".
**
** The value of the iVersion field is initially 1 but may be larger in
** future versions of SQLite.  Additional fields may be appended to this
** object when the iVersion value is increased.  Note that the structure
** of the sqlite3_vfs object changes in the transaction between
** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
** modified.
**
** The szOsFile field is the size of the subclassed [sqlite3_file]
** structure used by this VFS.  mxPathname is the maximum length of
** a pathname in this VFS.
**
** Registered sqlite3_vfs objects are kept on a linked list formed by
** the pNext pointer.  The [sqlite3_vfs_register()]
** and [sqlite3_vfs_unregister()] interfaces manage this list
** in a thread-safe way.  The [sqlite3_vfs_find()] interface
** searches the list.  Neither the application code nor the VFS
** implementation should use the pNext pointer.
**
** The pNext field is the only field in the sqlite3_vfs
** structure that SQLite will ever modify.  SQLite will only access
** or modify this field while holding a particular static mutex.
** The application should never modify anything within the sqlite3_vfs
** object once the object has been registered.
**
** The zName field holds the name of the VFS module.  The name must
** be unique across all VFS modules.
**
** SQLite will guarantee that the zFilename parameter to xOpen
** is either a NULL pointer or string obtained
** from xFullPathname().  SQLite further guarantees that
** the string will be valid and unchanged until xClose() is
** called. Because of the previous sentence,
** the [sqlite3_file] can safely store a pointer to the
** filename if it needs to remember the filename for some reason.
** If the zFilename parameter is xOpen is a NULL pointer then xOpen
** must invent its own temporary name for the file.  Whenever the 
** xFilename parameter is NULL it will also be the case that the
** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
**
** The flags argument to xOpen() includes all bits set in
** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
** or [sqlite3_open16()] is used, then flags includes at least
** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
** If xOpen() opens a file read-only then it sets *pOutFlags to
** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
**
** SQLite will also add one of the following flags to the xOpen()
** call, depending on the object being opened:
**
** <ul>
** <li>  [SQLITE_OPEN_MAIN_DB]
** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
** <li>  [SQLITE_OPEN_TEMP_DB]
** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
** <li>  [SQLITE_OPEN_TRANSIENT_DB]
** <li>  [SQLITE_OPEN_SUBJOURNAL]
** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
** </ul>
**
** The file I/O implementation can use the object type flags to
** change the way it deals with files.  For example, an application
** that does not care about crash recovery or rollback might make
** the open of a journal file a no-op.  Writes to this journal would
** also be no-ops, and any attempt to read the journal would return
** SQLITE_IOERR.  Or the implementation might recognize that a database
** file will be doing page-aligned sector reads and writes in a random
** order and set up its I/O subsystem accordingly.
**
** SQLite might also add one of the following flags to the xOpen method:
**
** <ul>
** <li> [SQLITE_OPEN_DELETEONCLOSE]
** <li> [SQLITE_OPEN_EXCLUSIVE]
** </ul>
**
** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
** will be set for TEMP  databases, journals and for subjournals.
**
** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
** with the [SQLITE_OPEN_CREATE] flag, which are both directly
** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
** SQLITE_OPEN_CREATE, is used to indicate that file should always
** be created, and that it is an error if it already exists.
** It is <i>not</i> used to indicate the file should be opened 
** for exclusive access.
**
** At least szOsFile bytes of memory are allocated by SQLite
** to hold the  [sqlite3_file] structure passed as the third
** argument to xOpen.  The xOpen method does not have to
** allocate the structure; it should just fill it in.  Note that
** the xOpen method must set the sqlite3_file.pMethods to either
** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
** element will be valid after xOpen returns regardless of the success
** or failure of the xOpen call.
**
** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
** to test whether a file is at least readable.   The file can be a
** directory.
**
** SQLite will always allocate at least mxPathname+1 bytes for the
** output buffer xFullPathname.  The exact size of the output buffer
** is also passed as a parameter to both  methods. If the output buffer
** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
** handled as a fatal error by SQLite, vfs implementations should endeavor
** to prevent this by setting mxPathname to a sufficiently large value.
**
** The xRandomness(), xSleep(), and xCurrentTime() interfaces
** are not strictly a part of the filesystem, but they are
** included in the VFS structure for completeness.
** The xRandomness() function attempts to return nBytes bytes
** of good-quality randomness into zOut.  The return value is
** the actual number of bytes of randomness obtained.
** The xSleep() method causes the calling thread to sleep for at
** least the number of microseconds given.  The xCurrentTime()
** method returns a Julian Day Number for the current date and time.
**
*/
typedef struct sqlite3_vfs sqlite3_vfs;
struct sqlite3_vfs {
  int iVersion;            /* Structure version number */
  int szOsFile;            /* Size of subclassed sqlite3_file */
  int mxPathname;          /* Maximum file pathname length */
  sqlite3_vfs *pNext;      /* Next registered VFS */
  const char *zName;       /* Name of this virtual file system */
  void *pAppData;          /* Pointer to application-specific data */
  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
               int flags, int *pOutFlags);
  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  void (*xDlClose)(sqlite3_vfs*, void*);
  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  int (*xSleep)(sqlite3_vfs*, int microseconds);
  int (*xCurrentTime)(sqlite3_vfs*, double*);
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
  /* New fields may be appended in figure versions.  The iVersion
  ** value will increment whenever this happens. */
};

/*
** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
**
** These integer constants can be used as the third parameter to
** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
** what kind of permissions the xAccess method is looking for.
** With SQLITE_ACCESS_EXISTS, the xAccess method
** simply checks whether the file exists.
** With SQLITE_ACCESS_READWRITE, the xAccess method
** checks whether the file is both readable and writable.
** With SQLITE_ACCESS_READ, the xAccess method
** checks whether the file is readable.
*/
#define SQLITE_ACCESS_EXISTS    0
#define SQLITE_ACCESS_READWRITE 1
#define SQLITE_ACCESS_READ      2

/*
** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
**
** The sqlite3_initialize() routine initializes the
** SQLite library.  The sqlite3_shutdown() routine
** deallocates any resources that were allocated by sqlite3_initialize().
** These routines are designed to aid in process initialization and
** shutdown on embedded systems.  Workstation applications using
** SQLite normally do not need to invoke either of these routines.
**
** A call to sqlite3_initialize() is an "effective" call if it is
** the first time sqlite3_initialize() is invoked during the lifetime of
** the process, or if it is the first time sqlite3_initialize() is invoked
** following a call to sqlite3_shutdown().  Only an effective call
** of sqlite3_initialize() does any initialization.  All other calls
** are harmless no-ops.
**
** A call to sqlite3_shutdown() is an "effective" call if it is the first
** call to sqlite3_shutdown() since the last sqlite3_initialize().  Only
** an effective call to sqlite3_shutdown() does any deinitialization.
** All other valid calls to sqlite3_shutdown() are harmless no-ops.
**
** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
** is not.  The sqlite3_shutdown() interface must only be called from a
** single thread.  All open [database connections] must be closed and all
** other SQLite resources must be deallocated prior to invoking
** sqlite3_shutdown().
**
** Among other things, sqlite3_initialize() will invoke
** sqlite3_os_init().  Similarly, sqlite3_shutdown()
** will invoke sqlite3_os_end().
**
** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
** If for some reason, sqlite3_initialize() is unable to initialize
** the library (perhaps it is unable to allocate a needed resource such
** as a mutex) it returns an [error code] other than [SQLITE_OK].
**
** The sqlite3_initialize() routine is called internally by many other
** SQLite interfaces so that an application usually does not need to
** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
** calls sqlite3_initialize() so the SQLite library will be automatically
** initialized when [sqlite3_open()] is called if it has not be initialized
** already.  However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
** compile-time option, then the automatic calls to sqlite3_initialize()
** are omitted and the application must call sqlite3_initialize() directly
** prior to using any other SQLite interface.  For maximum portability,
** it is recommended that applications always invoke sqlite3_initialize()
** directly prior to using any other SQLite interface.  Future releases
** of SQLite may require this.  In other words, the behavior exhibited
** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
** default behavior in some future release of SQLite.
**
** The sqlite3_os_init() routine does operating-system specific
** initialization of the SQLite library.  The sqlite3_os_end()
** routine undoes the effect of sqlite3_os_init().  Typical tasks
** performed by these routines include allocation or deallocation
** of static resources, initialization of global variables,
** setting up a default [sqlite3_vfs] module, or setting up
** a default configuration using [sqlite3_config()].
**
** The application should never invoke either sqlite3_os_init()
** or sqlite3_os_end() directly.  The application should only invoke
** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
** interface is called automatically by sqlite3_initialize() and
** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
** implementations for sqlite3_os_init() and sqlite3_os_end()
** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
** When [custom builds | built for other platforms]
** (using the [SQLITE_OS_OTHER=1] compile-time
** option) the application must supply a suitable implementation for
** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
** implementation of sqlite3_os_init() or sqlite3_os_end()
** must return [SQLITE_OK] on success and some other [error code] upon
** failure.
*/
int sqlite3_initialize(void);
int sqlite3_shutdown(void);
int sqlite3_os_init(void);
int sqlite3_os_end(void);

/*
** CAPI3REF: Configuring The SQLite Library {H14100} <S20000><S30200>
** EXPERIMENTAL
**
** The sqlite3_config() interface is used to make global configuration
** changes to SQLite in order to tune SQLite to the specific needs of
** the application.  The default configuration is recommended for most
** applications and so this routine is usually not necessary.  It is
** provided to support rare applications with unusual needs.
**
** The sqlite3_config() interface is not threadsafe.  The application
** must insure that no other SQLite interfaces are invoked by other
** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
** may only be invoked prior to library initialization using
** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
** Note, however, that sqlite3_config() can be called as part of the
** implementation of an application-defined [sqlite3_os_init()].
**
** The first argument to sqlite3_config() is an integer
** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
** what property of SQLite is to be configured.  Subsequent arguments
** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
** in the first argument.
**
** When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
** If the option is unknown or SQLite is unable to set the option
** then this routine returns a non-zero [error code].
**
** Requirements:
** [H14103] [H14106] [H14120] [H14123] [H14126] [H14129] [H14132] [H14135]
** [H14138] [H14141] [H14144] [H14147] [H14150] [H14153] [H14156] [H14159]
** [H14162] [H14165] [H14168]
*/
SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);

/*
** CAPI3REF: Configure database connections  {H14200} <S20000>
** EXPERIMENTAL
**
** The sqlite3_db_config() interface is used to make configuration
** changes to a [database connection].  The interface is similar to
** [sqlite3_config()] except that the changes apply to a single
** [database connection] (specified in the first argument).  The
** sqlite3_db_config() interface can only be used immediately after
** the database connection is created using [sqlite3_open()],
** [sqlite3_open16()], or [sqlite3_open_v2()].  
**
** The second argument to sqlite3_db_config(D,V,...)  is the
** configuration verb - an integer code that indicates what
** aspect of the [database connection] is being configured.
** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
** New verbs are likely to be added in future releases of SQLite.
** Additional arguments depend on the verb.
**
** Requirements:
** [H14203] [H14206] [H14209] [H14212] [H14215]
*/
SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);

/*
** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
** EXPERIMENTAL
**
** An instance of this object defines the interface between SQLite
** and low-level memory allocation routines.
**
** This object is used in only one place in the SQLite interface.
** A pointer to an instance of this object is the argument to
** [sqlite3_config()] when the configuration option is
** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
** By creating an instance of this object
** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
** during configuration, an application can specify an alternative
** memory allocation subsystem for SQLite to use for all of its
** dynamic memory needs.
**
** Note that SQLite comes with several [built-in memory allocators]
** that are perfectly adequate for the overwhelming majority of applications
** and that this object is only useful to a tiny minority of applications
** with specialized memory allocation requirements.  This object is
** also used during testing of SQLite in order to specify an alternative
** memory allocator that simulates memory out-of-memory conditions in
** order to verify that SQLite recovers gracefully from such
** conditions.
**
** The xMalloc and xFree methods must work like the
** malloc() and free() functions from the standard C library.
** The xRealloc method must work like realloc() from the standard C library
** with the exception that if the second argument to xRealloc is zero,
** xRealloc must be a no-op - it must not perform any allocation or
** deallocation.  SQLite guaranteeds that the second argument to
** xRealloc is always a value returned by a prior call to xRoundup.
** And so in cases where xRoundup always returns a positive number,
** xRealloc can perform exactly as the standard library realloc() and
** still be in compliance with this specification.
**
** xSize should return the allocated size of a memory allocation
** previously obtained from xMalloc or xRealloc.  The allocated size
** is always at least as big as the requested size but may be larger.
**
** The xRoundup method returns what would be the allocated size of
** a memory allocation given a particular requested size.  Most memory
** allocators round up memory allocations at least to the next multiple
** of 8.  Some allocators round up to a larger multiple or to a power of 2.
** Every memory allocation request coming in through [sqlite3_malloc()]
** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
** that causes the corresponding memory allocation to fail.
**
** The xInit method initializes the memory allocator.  (For example,
** it might allocate any require mutexes or initialize internal data
** structures.  The xShutdown method is invoked (indirectly) by
** [sqlite3_shutdown()] and should deallocate any resources acquired
** by xInit.  The pAppData pointer is used as the only parameter to
** xInit and xShutdown.
**
** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
** the xInit method, so the xInit method need not be threadsafe.  The
** xShutdown method is only called from [sqlite3_shutdown()] so it does
** not need to be threadsafe either.  For all other methods, SQLite
** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
** it is by default) and so the methods are automatically serialized.
** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
** methods must be threadsafe or else make their own arrangements for
** serialization.
**
** SQLite will never invoke xInit() more than once without an intervening
** call to xShutdown().
*/
typedef struct sqlite3_mem_methods sqlite3_mem_methods;
struct sqlite3_mem_methods {
  void *(*xMalloc)(int);         /* Memory allocation function */
  void (*xFree)(void*);          /* Free a prior allocation */
  void *(*xRealloc)(void*,int);  /* Resize an allocation */
  int (*xSize)(void*);           /* Return the size of an allocation */
  int (*xRoundup)(int);          /* Round up request size to allocation size */
  int (*xInit)(void*);           /* Initialize the memory allocator */
  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
  void *pAppData;                /* Argument to xInit() and xShutdown() */
};

/*
** CAPI3REF: Configuration Options {H10160} <S20000>
** EXPERIMENTAL
**
** These constants are the available integer configuration options that
** can be passed as the first argument to the [sqlite3_config()] interface.
**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite3_config()] to make sure that
** the call worked.  The [sqlite3_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.
**
** <dl>
** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
** <dd>There are no arguments to this option.  This option disables
** all mutexing and puts SQLite into a mode where it can only be used
** by a single thread.</dd>
**
** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
** <dd>There are no arguments to this option.  This option disables
** mutexing on [database connection] and [prepared statement] objects.
** The application is responsible for serializing access to
** [database connections] and [prepared statements].  But other mutexes
** are enabled so that SQLite will be safe to use in a multi-threaded
** environment as long as no two threads attempt to use the same
** [database connection] at the same time.  See the [threading mode]
** documentation for additional information.</dd>
**
** <dt>SQLITE_CONFIG_SERIALIZED</dt>
** <dd>There are no arguments to this option.  This option enables
** all mutexes including the recursive
** mutexes on [database connection] and [prepared statement] objects.
** In this mode (which is the default when SQLite is compiled with
** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
** to [database connections] and [prepared statements] so that the
** application is free to use the same [database connection] or the
** same [prepared statement] in different threads at the same time.
** See the [threading mode] documentation for additional information.</dd>
**
** <dt>SQLITE_CONFIG_MALLOC</dt>
** <dd>This option takes a single argument which is a pointer to an
** instance of the [sqlite3_mem_methods] structure.  The argument specifies
** alternative low-level memory allocation routines to be used in place of
** the memory allocation routines built into SQLite.</dd>
**
** <dt>SQLITE_CONFIG_GETMALLOC</dt>
** <dd>This option takes a single argument which is a pointer to an
** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
** structure is filled with the currently defined memory allocation routines.
** This option can be used to overload the default memory allocation
** routines with a wrapper that simulations memory allocation failure or
** tracks memory usage, for example.</dd>
**
** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
** <dd>This option takes single argument of type int, interpreted as a 
** boolean, which enables or disables the collection of memory allocation 
** statistics. When disabled, the following SQLite interfaces become 
** non-operational:
**   <ul>
**   <li> [sqlite3_memory_used()]
**   <li> [sqlite3_memory_highwater()]
**   <li> [sqlite3_soft_heap_limit()]
**   <li> [sqlite3_status()]
**   </ul>
** </dd>
**
** <dt>SQLITE_CONFIG_SCRATCH</dt>
** <dd>This option specifies a static memory buffer that SQLite can use for
** scratch memory.  There are three arguments:  A pointer an 8-byte
** aligned memory buffer from which the scrach allocations will be
** drawn, the size of each scratch allocation (sz),
** and the maximum number of scratch allocations (N).  The sz
** argument must be a multiple of 16. The sz parameter should be a few bytes
** larger than the actual scratch space required due to internal overhead.
** The first argument should pointer to an 8-byte aligned buffer
** of at least sz*N bytes of memory.
** SQLite will use no more than one scratch buffer at once per thread, so
** N should be set to the expected maximum number of threads.  The sz
** parameter should be 6 times the size of the largest database page size.
** Scratch buffers are used as part of the btree balance operation.  If
** The btree balancer needs additional memory beyond what is provided by
** scratch buffers or if no scratch buffer space is specified, then SQLite
** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
**
** <dt>SQLITE_CONFIG_PAGECACHE</dt>
** <dd>This option specifies a static memory buffer that SQLite can use for
** the database page cache with the default page cache implemenation.  
** This configuration should not be used if an application-define page
** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
** There are three arguments to this option: A pointer to 8-byte aligned
** memory, the size of each page buffer (sz), and the number of pages (N).
** The sz argument should be the size of the largest database page
** (a power of two between 512 and 32768) plus a little extra for each
** page header.  The page header size is 20 to 40 bytes depending on
** the host architecture.  It is harmless, apart from the wasted memory,
** to make sz a little too large.  The first
** argument should point to an allocation of at least sz*N bytes of memory.
** SQLite will use the memory provided by the first argument to satisfy its
** memory needs for the first N pages that it adds to cache.  If additional
** page cache memory is needed beyond what is provided by this option, then
** SQLite goes to [sqlite3_malloc()] for the additional storage space.
** The implementation might use one or more of the N buffers to hold 
** memory accounting information. The pointer in the first argument must
** be aligned to an 8-byte boundary or subsequent behavior of SQLite
** will be undefined.</dd>
**
** <dt>SQLITE_CONFIG_HEAP</dt>
** <dd>This option specifies a static memory buffer that SQLite will use
** for all of its dynamic memory allocation needs beyond those provided
** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
** There are three arguments: An 8-byte aligned pointer to the memory,
** the number of bytes in the memory buffer, and the minimum allocation size.
** If the first pointer (the memory pointer) is NULL, then SQLite reverts
** to using its default memory allocator (the system malloc() implementation),
** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  If the
** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
** allocator is engaged to handle all of SQLites memory allocation needs.
** The first pointer (the memory pointer) must be aligned to an 8-byte
** boundary or subsequent behavior of SQLite will be undefined.</dd>
**
** <dt>SQLITE_CONFIG_MUTEX</dt>
** <dd>This option takes a single argument which is a pointer to an
** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
** alternative low-level mutex routines to be used in place
** the mutex routines built into SQLite.</dd>
**
** <dt>SQLITE_CONFIG_GETMUTEX</dt>
** <dd>This option takes a single argument which is a pointer to an
** instance of the [sqlite3_mutex_methods] structure.  The
** [sqlite3_mutex_methods]
** structure is filled with the currently defined mutex routines.
** This option can be used to overload the default mutex allocation
** routines with a wrapper used to track mutex usage for performance
** profiling or testing, for example.</dd>
**
** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
** <dd>This option takes two arguments that determine the default
** memory allocation lookaside optimization.  The first argument is the
** size of each lookaside buffer slot and the second is the number of
** slots allocated to each database connection.  This option sets the
** <i>default</i> lookaside size.  The [SQLITE_DBCONFIG_LOOKASIDE]
** verb to [sqlite3_db_config()] can be used to change the lookaside
** configuration on individual connections.</dd>
**
** <dt>SQLITE_CONFIG_PCACHE</dt>
** <dd>This option takes a single argument which is a pointer to
** an [sqlite3_pcache_methods] object.  This object specifies the interface
** to a custom page cache implementation.  SQLite makes a copy of the
** object and uses it for page cache memory allocations.</dd>
**
** <dt>SQLITE_CONFIG_GETPCACHE</dt>
** <dd>This option takes a single argument which is a pointer to an
** [sqlite3_pcache_methods] object.  SQLite copies of the current
** page cache implementation into that object.</dd>
**
** </dl>
*/
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */

/*
** CAPI3REF: Configuration Options {H10170} <S20000>
** EXPERIMENTAL
**
** These constants are the available integer configuration options that
** can be passed as the second argument to the [sqlite3_db_config()] interface.
**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite3_db_config()] to make sure that
** the call worked.  The [sqlite3_db_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.
**
** <dl>
** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
** <dd>This option takes three additional arguments that determine the 
** [lookaside memory allocator] configuration for the [database connection].
** The first argument (the third parameter to [sqlite3_db_config()] is a
** pointer to an memory buffer to use for lookaside memory.
** The first argument may be NULL in which case SQLite will allocate the
** lookaside buffer itself using [sqlite3_malloc()].  The second argument is the
** size of each lookaside buffer slot and the third argument is the number of
** slots.  The size of the buffer in the first argument must be greater than
** or equal to the product of the second and third arguments.  The buffer
** must be aligned to an 8-byte boundary.  If the second argument is not
** a multiple of 8, it is internally rounded down to the next smaller
** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
**
** </dl>
*/
#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */


/*
** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
**
** The sqlite3_extended_result_codes() routine enables or disables the
** [extended result codes] feature of SQLite. The extended result
** codes are disabled by default for historical compatibility considerations.
**
** Requirements:
** [H12201] [H12202]
*/
int sqlite3_extended_result_codes(sqlite3*, int onoff);

/*
** CAPI3REF: Last Insert Rowid {H12220} <S10700>
**
** Each entry in an SQLite table has a unique 64-bit signed
** integer key called the [ROWID | "rowid"]. The rowid is always available
** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
** names are not also used by explicitly declared columns. If
** the table has a column of type [INTEGER PRIMARY KEY] then that column
** is another alias for the rowid.
**
** This routine returns the [rowid] of the most recent
** successful [INSERT] into the database from the [database connection]
** in the first argument.  If no successful [INSERT]s
** have ever occurred on that database connection, zero is returned.
**
** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
** row is returned by this routine as long as the trigger is running.
** But once the trigger terminates, the value returned by this routine
** reverts to the last value inserted before the trigger fired.
**
** An [INSERT] that fails due to a constraint violation is not a
** successful [INSERT] and does not change the value returned by this
** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
** and INSERT OR ABORT make no changes to the return value of this
** routine when their insertion fails.  When INSERT OR REPLACE
** encounters a constraint violation, it does not fail.  The
** INSERT continues to completion after deleting rows that caused
** the constraint problem so INSERT OR REPLACE will always change
** the return value of this interface.
**
** For the purposes of this routine, an [INSERT] is considered to
** be successful even if it is subsequently rolled back.
**
** Requirements:
** [H12221] [H12223]
**
** If a separate thread performs a new [INSERT] on the same
** database connection while the [sqlite3_last_insert_rowid()]
** function is running and thus changes the last insert [rowid],
** then the value returned by [sqlite3_last_insert_rowid()] is
** unpredictable and might not equal either the old or the new
** last insert [rowid].
*/
sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);

/*
** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
**
** This function returns the number of database rows that were changed
** or inserted or deleted by the most recently completed SQL statement
** on the [database connection] specified by the first parameter.
** Only changes that are directly specified by the [INSERT], [UPDATE],
** or [DELETE] statement are counted.  Auxiliary changes caused by
** triggers or [foreign key actions] are not counted. Use the
** [sqlite3_total_changes()] function to find the total number of changes
** including changes caused by triggers and foreign key actions.
**
** Changes to a view that are simulated by an [INSTEAD OF trigger]
** are not counted.  Only real table changes are counted.
**
** A "row change" is a change to a single row of a single table
** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
** are changed as side effects of [REPLACE] constraint resolution,
** rollback, ABORT processing, [DROP TABLE], or by any other
** mechanisms do not count as direct row changes.
**
** A "trigger context" is a scope of execution that begins and
** ends with the script of a [CREATE TRIGGER | trigger]. 
** Most SQL statements are
** evaluated outside of any trigger.  This is the "top level"
** trigger context.  If a trigger fires from the top level, a
** new trigger context is entered for the duration of that one
** trigger.  Subtriggers create subcontexts for their duration.
**
** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
** not create a new trigger context.
**
** This function returns the number of direct row changes in the
** most recent INSERT, UPDATE, or DELETE statement within the same
** trigger context.
**
** Thus, when called from the top level, this function returns the
** number of changes in the most recent INSERT, UPDATE, or DELETE
** that also occurred at the top level.  Within the body of a trigger,
** the sqlite3_changes() interface can be called to find the number of
** changes in the most recently completed INSERT, UPDATE, or DELETE
** statement within the body of the same trigger.
** However, the number returned does not include changes
** caused by subtriggers since those have their own context.
**
** See also the [sqlite3_total_changes()] interface and the
** [count_changes pragma].
**
** Requirements:
** [H12241] [H12243]
**
** If a separate thread makes changes on the same database connection
** while [sqlite3_changes()] is running then the value returned
** is unpredictable and not meaningful.
*/
int sqlite3_changes(sqlite3*);

/*
** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
**
** This function returns the number of row changes caused by [INSERT],
** [UPDATE] or [DELETE] statements since the [database connection] was opened.
** The count includes all changes from all [CREATE TRIGGER | trigger] 
** contexts and changes made by [foreign key actions]. However,
** the count does not include changes used to implement [REPLACE] constraints,
** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
** count does not include rows of views that fire an [INSTEAD OF trigger],
** though if the INSTEAD OF trigger makes changes of its own, those changes 
** are counted.
** The changes are counted as soon as the statement that makes them is
** completed (when the statement handle is passed to [sqlite3_reset()] or
** [sqlite3_finalize()]).
**
** See also the [sqlite3_changes()] interface and the
** [count_changes pragma].
**
** Requirements:
** [H12261] [H12263]
**
** If a separate thread makes changes on the same database connection
** while [sqlite3_total_changes()] is running then the value
** returned is unpredictable and not meaningful.
*/
int sqlite3_total_changes(sqlite3*);

/*
** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
**
** This function causes any pending database operation to abort and
** return at its earliest opportunity. This routine is typically
** called in response to a user action such as pressing "Cancel"
** or Ctrl-C where the user wants a long query operation to halt
** immediately.
**
** It is safe to call this routine from a thread different from the
** thread that is currently running the database operation.  But it
** is not safe to call this routine with a [database connection] that
** is closed or might close before sqlite3_interrupt() returns.
**
** If an SQL operation is very nearly finished at the time when
** sqlite3_interrupt() is called, then it might not have an opportunity
** to be interrupted and might continue to completion.
**
** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
** that is inside an explicit transaction, then the entire transaction
** will be rolled back automatically.
**
** The sqlite3_interrupt(D) call is in effect until all currently running
** SQL statements on [database connection] D complete.  Any new SQL statements
** that are started after the sqlite3_interrupt() call and before the 
** running statements reaches zero are interrupted as if they had been
** running prior to the sqlite3_interrupt() call.  New SQL statements
** that are started after the running statement count reaches zero are
** not effected by the sqlite3_interrupt().
** A call to sqlite3_interrupt(D) that occurs when there are no running
** SQL statements is a no-op and has no effect on SQL statements
** that are started after the sqlite3_interrupt() call returns.
**
** Requirements:
** [H12271] [H12272]
**
** If the database connection closes while [sqlite3_interrupt()]
** is running then bad things will likely happen.
*/
void sqlite3_interrupt(sqlite3*);

/*
** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
**
** These routines are useful during command-line input to determine if the
** currently entered text seems to form a complete SQL statement or
** if additional input is needed before sending the text into
** SQLite for parsing.  These routines return 1 if the input string
** appears to be a complete SQL statement.  A statement is judged to be
** complete if it ends with a semicolon token and is not a prefix of a
** well-formed CREATE TRIGGER statement.  Semicolons that are embedded within
** string literals or quoted identifier names or comments are not
** independent tokens (they are part of the token in which they are
** embedded) and thus do not count as a statement terminator.  Whitespace
** and comments that follow the final semicolon are ignored.
**
** These routines return 0 if the statement is incomplete.  If a
** memory allocation fails, then SQLITE_NOMEM is returned.
**
** These routines do not parse the SQL statements thus
** will not detect syntactically incorrect SQL.
**
** If SQLite has not been initialized using [sqlite3_initialize()] prior 
** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
** automatically by sqlite3_complete16().  If that initialization fails,
** then the return value from sqlite3_complete16() will be non-zero
** regardless of whether or not the input SQL is complete.
**
** Requirements: [H10511] [H10512]
**
** The input to [sqlite3_complete()] must be a zero-terminated
** UTF-8 string.
**
** The input to [sqlite3_complete16()] must be a zero-terminated
** UTF-16 string in native byte order.
*/
int sqlite3_complete(const char *sql);
int sqlite3_complete16(const void *sql);

/*
** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
**
** This routine sets a callback function that might be invoked whenever
** an attempt is made to open a database table that another thread
** or process has locked.
**
** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
** is returned immediately upon encountering the lock. If the busy callback
** is not NULL, then the callback will be invoked with two arguments.
**
** The first argument to the handler is a copy of the void* pointer which
** is the third argument to sqlite3_busy_handler().  The second argument to
** the handler callback is the number of times that the busy handler has
** been invoked for this locking event.  If the
** busy callback returns 0, then no additional attempts are made to
** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
** If the callback returns non-zero, then another attempt
** is made to open the database for reading and the cycle repeats.
**
** The presence of a busy handler does not guarantee that it will be invoked
** when there is lock contention. If SQLite determines that invoking the busy
** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
** Consider a scenario where one process is holding a read lock that
** it is trying to promote to a reserved lock and
** a second process is holding a reserved lock that it is trying
** to promote to an exclusive lock.  The first process cannot proceed
** because it is blocked by the second and the second process cannot
** proceed because it is blocked by the first.  If both processes
** invoke the busy handlers, neither will make any progress.  Therefore,
** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
** will induce the first process to release its read lock and allow
** the second process to proceed.
**
** The default busy callback is NULL.
**
** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
** when SQLite is in the middle of a large transaction where all the
** changes will not fit into the in-memory cache.  SQLite will
** already hold a RESERVED lock on the database file, but it needs
** to promote this lock to EXCLUSIVE so that it can spill cache
** pages into the database file without harm to concurrent
** readers.  If it is unable to promote the lock, then the in-memory
** cache will be left in an inconsistent state and so the error
** code is promoted from the relatively benign [SQLITE_BUSY] to
** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
** forces an automatic rollback of the changes.  See the
** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
** CorruptionFollowingBusyError</a> wiki page for a discussion of why
** this is important.
**
** There can only be a single busy handler defined for each
** [database connection].  Setting a new busy handler clears any
** previously set handler.  Note that calling [sqlite3_busy_timeout()]
** will also set or clear the busy handler.
**
** The busy callback should not take any actions which modify the
** database connection that invoked the busy handler.  Any such actions
** result in undefined behavior.
** 
** Requirements:
** [H12311] [H12312] [H12314] [H12316] [H12318]
**
** A busy handler must not close the database connection
** or [prepared statement] that invoked the busy handler.
*/
int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);

/*
** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
**
** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
** for a specified amount of time when a table is locked.  The handler
** will sleep multiple times until at least "ms" milliseconds of sleeping
** have accumulated. {H12343} After "ms" milliseconds of sleeping,
** the handler returns 0 which causes [sqlite3_step()] to return
** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
**
** Calling this routine with an argument less than or equal to zero
** turns off all busy handlers.
**
** There can only be a single busy handler for a particular
** [database connection] any any given moment.  If another busy handler
** was defined  (using [sqlite3_busy_handler()]) prior to calling
** this routine, that other busy handler is cleared.
**
** Requirements:
** [H12341] [H12343] [H12344]
*/
int sqlite3_busy_timeout(sqlite3*, int ms);

/*
** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
**
** Definition: A <b>result table</b> is memory data structure created by the
** [sqlite3_get_table()] interface.  A result table records the
** complete query results from one or more queries.
**
** The table conceptually has a number of rows and columns.  But
** these numbers are not part of the result table itself.  These
** numbers are obtained separately.  Let N be the number of rows
** and M be the number of columns.
**
** A result table is an array of pointers to zero-terminated UTF-8 strings.
** There are (N+1)*M elements in the array.  The first M pointers point
** to zero-terminated strings that  contain the names of the columns.
** The remaining entries all point to query results.  NULL values result
** in NULL pointers.  All other values are in their UTF-8 zero-terminated
** string representation as returned by [sqlite3_column_text()].
**
** A result table might consist of one or more memory allocations.
** It is not safe to pass a result table directly to [sqlite3_free()].
** A result table should be deallocated using [sqlite3_free_table()].
**
** As an example of the result table format, suppose a query result
** is as follows:
**
** <blockquote><pre>
**        Name        | Age
**        -----------------------
**        Alice       | 43
**        Bob         | 28
**        Cindy       | 21
** </pre></blockquote>
**
** There are two column (M==2) and three rows (N==3).  Thus the
** result table has 8 entries.  Suppose the result table is stored
** in an array names azResult.  Then azResult holds this content:
**
** <blockquote><pre>
**        azResult&#91;0] = "Name";
**        azResult&#91;1] = "Age";
**        azResult&#91;2] = "Alice";
**        azResult&#91;3] = "43";
**        azResult&#91;4] = "Bob";
**        azResult&#91;5] = "28";
**        azResult&#91;6] = "Cindy";
**        azResult&#91;7] = "21";
** </pre></blockquote>
**
** The sqlite3_get_table() function evaluates one or more
** semicolon-separated SQL statements in the zero-terminated UTF-8
** string of its 2nd parameter.  It returns a result table to the
** pointer given in its 3rd parameter.
**
** After the calling function has finished using the result, it should
** pass the pointer to the result table to sqlite3_free_table() in order to
** release the memory that was malloced.  Because of the way the
** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
** function must not try to call [sqlite3_free()] directly.  Only
** [sqlite3_free_table()] is able to release the memory properly and safely.
**
** The sqlite3_get_table() interface is implemented as a wrapper around
** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
** to any internal data structures of SQLite.  It uses only the public
** interface defined here.  As a consequence, errors that occur in the
** wrapper layer outside of the internal [sqlite3_exec()] call are not
** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
**
** Requirements:
** [H12371] [H12373] [H12374] [H12376] [H12379] [H12382]
*/
int sqlite3_get_table(
  sqlite3 *db,          /* An open database */
  const char *zSql,     /* SQL to be evaluated */
  char ***pazResult,    /* Results of the query */
  int *pnRow,           /* Number of result rows written here */
  int *pnColumn,        /* Number of result columns written here */
  char **pzErrmsg       /* Error msg written here */
);
void sqlite3_free_table(char **result);

/*
** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
**
** These routines are work-alikes of the "printf()" family of functions
** from the standard C library.
**
** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
** results into memory obtained from [sqlite3_malloc()].
** The strings returned by these two routines should be
** released by [sqlite3_free()].  Both routines return a
** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
** memory to hold the resulting string.
**
** In sqlite3_snprintf() routine is similar to "snprintf()" from
** the standard C library.  The result is written into the
** buffer supplied as the second parameter whose size is given by
** the first parameter. Note that the order of the
** first two parameters is reversed from snprintf().  This is an
** historical accident that cannot be fixed without breaking
** backwards compatibility.  Note also that sqlite3_snprintf()
** returns a pointer to its buffer instead of the number of
** characters actually written into the buffer.  We admit that
** the number of characters written would be a more useful return
** value but we cannot change the implementation of sqlite3_snprintf()
** now without breaking compatibility.
**
** As long as the buffer size is greater than zero, sqlite3_snprintf()
** guarantees that the buffer is always zero-terminated.  The first
** parameter "n" is the total size of the buffer, including space for
** the zero terminator.  So the longest string that can be completely
** written will be n-1 characters.
**
** These routines all implement some additional formatting
** options that are useful for constructing SQL statements.
** All of the usual printf() formatting options apply.  In addition, there
** is are "%q", "%Q", and "%z" options.
**
** The %q option works like %s in that it substitutes a null-terminated
** string from the argument list.  But %q also doubles every '\'' character.
** %q is designed for use inside a string literal.  By doubling each '\''
** character it escapes that character and allows it to be inserted into
** the string.
**
** For example, assume the string variable zText contains text as follows:
**
** <blockquote><pre>
**  char *zText = "It's a happy day!";
** </pre></blockquote>
**
** One can use this text in an SQL statement as follows:
**
** <blockquote><pre>
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** </pre></blockquote>
**
** Because the %q format string is used, the '\'' character in zText
** is escaped and the SQL generated is as follows:
**
** <blockquote><pre>
**  INSERT INTO table1 VALUES('It''s a happy day!')
** </pre></blockquote>
**
** This is correct.  Had we used %s instead of %q, the generated SQL
** would have looked like this:
**
** <blockquote><pre>
**  INSERT INTO table1 VALUES('It's a happy day!');
** </pre></blockquote>
**
** This second example is an SQL syntax error.  As a general rule you should
** always use %q instead of %s when inserting text into a string literal.
**
** The %Q option works like %q except it also adds single quotes around
** the outside of the total string.  Additionally, if the parameter in the
** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
** single quotes) in place of the %Q option.  So, for example, one could say:
**
** <blockquote><pre>
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** </pre></blockquote>
**
** The code above will render a correct SQL statement in the zSQL
** variable even if the zText variable is a NULL pointer.
**
** The "%z" formatting option works exactly like "%s" with the
** addition that after the string has been read and copied into
** the result, [sqlite3_free()] is called on the input string. {END}
**
** Requirements:
** [H17403] [H17406] [H17407]
*/
char *sqlite3_mprintf(const char*,...);
char *sqlite3_vmprintf(const char*, va_list);
char *sqlite3_snprintf(int,char*,const char*, ...);

/*
** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
**
** The SQLite core  uses these three routines for all of its own
** internal memory allocation needs. "Core" in the previous sentence
** does not include operating-system specific VFS implementation.  The
** Windows VFS uses native malloc() and free() for some operations.
**
** The sqlite3_malloc() routine returns a pointer to a block
** of memory at least N bytes in length, where N is the parameter.
** If sqlite3_malloc() is unable to obtain sufficient free
** memory, it returns a NULL pointer.  If the parameter N to
** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
** a NULL pointer.
**
** Calling sqlite3_free() with a pointer previously returned
** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
** that it might be reused.  The sqlite3_free() routine is
** a no-op if is called with a NULL pointer.  Passing a NULL pointer
** to sqlite3_free() is harmless.  After being freed, memory
** should neither be read nor written.  Even reading previously freed
** memory might result in a segmentation fault or other severe error.
** Memory corruption, a segmentation fault, or other severe error
** might result if sqlite3_free() is called with a non-NULL pointer that
** was not obtained from sqlite3_malloc() or sqlite3_realloc().
**
** The sqlite3_realloc() interface attempts to resize a
** prior memory allocation to be at least N bytes, where N is the
** second parameter.  The memory allocation to be resized is the first
** parameter.  If the first parameter to sqlite3_realloc()
** is a NULL pointer then its behavior is identical to calling
** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
** If the second parameter to sqlite3_realloc() is zero or
** negative then the behavior is exactly the same as calling
** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
** sqlite3_realloc() returns a pointer to a memory allocation
** of at least N bytes in size or NULL if sufficient memory is unavailable.
** If M is the size of the prior allocation, then min(N,M) bytes
** of the prior allocation are copied into the beginning of buffer returned
** by sqlite3_realloc() and the prior allocation is freed.
** If sqlite3_realloc() returns NULL, then the prior allocation
** is not freed.
**
** The memory returned by sqlite3_malloc() and sqlite3_realloc()
** is always aligned to at least an 8 byte boundary. {END}
**
** The default implementation of the memory allocation subsystem uses
** the malloc(), realloc() and free() provided by the standard C library.
** {H17382} However, if SQLite is compiled with the
** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
** is an integer), then SQLite create a static array of at least
** <i>NNN</i> bytes in size and uses that array for all of its dynamic
** memory allocation needs. {END}  Additional memory allocator options
** may be added in future releases.
**
** In SQLite version 3.5.0 and 3.5.1, it was possible to define
** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
** implementation of these routines to be omitted.  That capability
** is no longer provided.  Only built-in memory allocators can be used.
**
** The Windows OS interface layer calls
** the system malloc() and free() directly when converting
** filenames between the UTF-8 encoding used by SQLite
** and whatever filename encoding is used by the particular Windows
** installation.  Memory allocation errors are detected, but
** they are reported back as [SQLITE_CANTOPEN] or
** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
**
** Requirements:
** [H17303] [H17304] [H17305] [H17306] [H17310] [H17312] [H17315] [H17318]
** [H17321] [H17322] [H17323]
**
** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
** must be either NULL or else pointers obtained from a prior
** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
** not yet been released.
**
** The application must not read or write any part of
** a block of memory after it has been released using
** [sqlite3_free()] or [sqlite3_realloc()].
*/
void *sqlite3_malloc(int);
void *sqlite3_realloc(void*, int);
void sqlite3_free(void*);

/*
** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
**
** SQLite provides these two interfaces for reporting on the status
** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
** routines, which form the built-in memory allocation subsystem.
**
** Requirements:
** [H17371] [H17373] [H17374] [H17375]
*/
sqlite3_int64 sqlite3_memory_used(void);
sqlite3_int64 sqlite3_memory_highwater(int resetFlag);

/*
** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
**
** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
** select random [ROWID | ROWIDs] when inserting new records into a table that
** already uses the largest possible [ROWID].  The PRNG is also used for
** the build-in random() and randomblob() SQL functions.  This interface allows
** applications to access the same PRNG for other purposes.
**
** A call to this routine stores N bytes of randomness into buffer P.
**
** The first time this routine is invoked (either internally or by
** the application) the PRNG is seeded using randomness obtained
** from the xRandomness method of the default [sqlite3_vfs] object.
** On all subsequent invocations, the pseudo-randomness is generated
** internally and without recourse to the [sqlite3_vfs] xRandomness
** method.
**
** Requirements:
** [H17392]
*/
void sqlite3_randomness(int N, void *P);

/*
** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
**
** This routine registers a authorizer callback with a particular
** [database connection], supplied in the first argument.
** The authorizer callback is invoked as SQL statements are being compiled
** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
** points during the compilation process, as logic is being created
** to perform various actions, the authorizer callback is invoked to
** see if those actions are allowed.  The authorizer callback should
** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
** specific action but allow the SQL statement to continue to be
** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
** rejected with an error.  If the authorizer callback returns
** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
** then the [sqlite3_prepare_v2()] or equivalent call that triggered
** the authorizer will fail with an error message.
**
** When the callback returns [SQLITE_OK], that means the operation
** requested is ok.  When the callback returns [SQLITE_DENY], the
** [sqlite3_prepare_v2()] or equivalent call that triggered the
** authorizer will fail with an error message explaining that
** access is denied. 
**
** The first parameter to the authorizer callback is a copy of the third
** parameter to the sqlite3_set_authorizer() interface. The second parameter
** to the callback is an integer [SQLITE_COPY | action code] that specifies
** the particular action to be authorized. The third through sixth parameters
** to the callback are zero-terminated strings that contain additional
** details about the action to be authorized.
**
** If the action code is [SQLITE_READ]
** and the callback returns [SQLITE_IGNORE] then the
** [prepared statement] statement is constructed to substitute
** a NULL value in place of the table column that would have
** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
** return can be used to deny an untrusted user access to individual
** columns of a table.
** If the action code is [SQLITE_DELETE] and the callback returns
** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
** [truncate optimization] is disabled and all rows are deleted individually.
**
** An authorizer is used when [sqlite3_prepare | preparing]
** SQL statements from an untrusted source, to ensure that the SQL statements
** do not try to access data they are not allowed to see, or that they do not
** try to execute malicious statements that damage the database.  For
** example, an application may allow a user to enter arbitrary
** SQL queries for evaluation by a database.  But the application does
** not want the user to be able to make arbitrary changes to the
** database.  An authorizer could then be put in place while the
** user-entered SQL is being [sqlite3_prepare | prepared] that
** disallows everything except [SELECT] statements.
**
** Applications that need to process SQL from untrusted sources
** might also consider lowering resource limits using [sqlite3_limit()]
** and limiting database size using the [max_page_count] [PRAGMA]
** in addition to using an authorizer.
**
** Only a single authorizer can be in place on a database connection
** at a time.  Each call to sqlite3_set_authorizer overrides the
** previous call.  Disable the authorizer by installing a NULL callback.
** The authorizer is disabled by default.
**
** The authorizer callback must not do anything that will modify
** the database connection that invoked the authorizer callback.
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
** database connections for the meaning of "modify" in this paragraph.
**
** When [sqlite3_prepare_v2()] is used to prepare a statement, the
** statement might be re-prepared during [sqlite3_step()] due to a 
** schema change.  Hence, the application should ensure that the
** correct authorizer callback remains in place during the [sqlite3_step()].
**
** Note that the authorizer callback is invoked only during
** [sqlite3_prepare()] or its variants.  Authorization is not
** performed during statement evaluation in [sqlite3_step()], unless
** as stated in the previous paragraph, sqlite3_step() invokes
** sqlite3_prepare_v2() to reprepare a statement after a schema change.
**
** Requirements:
** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
** [H12511] [H12512] [H12520] [H12521] [H12522]
*/
int sqlite3_set_authorizer(
  sqlite3*,
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  void *pUserData
);

/*
** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
**
** The [sqlite3_set_authorizer | authorizer callback function] must
** return either [SQLITE_OK] or one of these two constants in order
** to signal SQLite whether or not the action is permitted.  See the
** [sqlite3_set_authorizer | authorizer documentation] for additional
** information.
*/
#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */

/*
** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
**
** The [sqlite3_set_authorizer()] interface registers a callback function
** that is invoked to authorize certain SQL statement actions.  The
** second parameter to the callback is an integer code that specifies
** what action is being authorized.  These are the integer action codes that
** the authorizer callback may be passed.
**
** These action code values signify what kind of operation is to be
** authorized.  The 3rd and 4th parameters to the authorization
** callback function will be parameters or NULL depending on which of these
** codes is used as the second parameter.  The 5th parameter to the
** authorizer callback is the name of the database ("main", "temp",
** etc.) if applicable.  The 6th parameter to the authorizer callback
** is the name of the inner-most trigger or view that is responsible for
** the access attempt or NULL if this access attempt is directly from
** top-level SQL code.
**
** Requirements:
** [H12551] [H12552] [H12553] [H12554]
*/
/******************************************* 3rd ************ 4th ***********/
#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
#define SQLITE_DELETE                9   /* Table Name      NULL            */
#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
#define SQLITE_INSERT               18   /* Table Name      NULL            */
#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
#define SQLITE_READ                 20   /* Table Name      Column Name     */
#define SQLITE_SELECT               21   /* NULL            NULL            */
#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
#define SQLITE_ATTACH               24   /* Filename        NULL            */
#define SQLITE_DETACH               25   /* Database Name   NULL            */
#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
#define SQLITE_REINDEX              27   /* Index Name      NULL            */
#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
#define SQLITE_COPY                  0   /* No longer used */

/*
** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
** EXPERIMENTAL
**
** These routines register callback functions that can be used for
** tracing and profiling the execution of SQL statements.
**
** The callback function registered by sqlite3_trace() is invoked at
** various times when an SQL statement is being run by [sqlite3_step()].
** The callback returns a UTF-8 rendering of the SQL statement text
** as the statement first begins executing.  Additional callbacks occur
** as each triggered subprogram is entered.  The callbacks for triggers
** contain a UTF-8 SQL comment that identifies the trigger.
**
** The callback function registered by sqlite3_profile() is invoked
** as each SQL statement finishes.  The profile callback contains
** the original statement text and an estimate of wall-clock time
** of how long that statement took to run.
**
** Requirements:
** [H12281] [H12282] [H12283] [H12284] [H12285] [H12287] [H12288] [H12289]
** [H12290]
*/
SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);

/*
** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
**
** This routine configures a callback function - the
** progress callback - that is invoked periodically during long
** running calls to [sqlite3_exec()], [sqlite3_step()] and
** [sqlite3_get_table()].  An example use for this
** interface is to keep a GUI updated during a large query.
**
** If the progress callback returns non-zero, the operation is
** interrupted.  This feature can be used to implement a
** "Cancel" button on a GUI progress dialog box.
**
** The progress handler must not do anything that will modify
** the database connection that invoked the progress handler.
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
** database connections for the meaning of "modify" in this paragraph.
**
** Requirements:
** [H12911] [H12912] [H12913] [H12914] [H12915] [H12916] [H12917] [H12918]
**
*/
void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);

/*
** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
**
** These routines open an SQLite database file whose name is given by the
** filename argument. The filename argument is interpreted as UTF-8 for
** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
** order for sqlite3_open16(). A [database connection] handle is usually
** returned in *ppDb, even if an error occurs.  The only exception is that
** if SQLite is unable to allocate memory to hold the [sqlite3] object,
** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
** object. If the database is opened (and/or created) successfully, then
** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.  The
** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
** an English language description of the error.
**
** The default encoding for the database will be UTF-8 if
** sqlite3_open() or sqlite3_open_v2() is called and
** UTF-16 in the native byte order if sqlite3_open16() is used.
**
** Whether or not an error occurs when it is opened, resources
** associated with the [database connection] handle should be released by
** passing it to [sqlite3_close()] when it is no longer required.
**
** The sqlite3_open_v2() interface works like sqlite3_open()
** except that it accepts two additional parameters for additional control
** over the new database connection.  The flags parameter can take one of
** the following three values, optionally combined with the 
** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
** and/or [SQLITE_OPEN_PRIVATECACHE] flags:
**
** <dl>
** <dt>[SQLITE_OPEN_READONLY]</dt>
** <dd>The database is opened in read-only mode.  If the database does not
** already exist, an error is returned.</dd>
**
** <dt>[SQLITE_OPEN_READWRITE]</dt>
** <dd>The database is opened for reading and writing if possible, or reading
** only if the file is write protected by the operating system.  In either
** case the database must already exist, otherwise an error is returned.</dd>
**
** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
** <dd>The database is opened for reading and writing, and is creates it if
** it does not already exist. This is the behavior that is always used for
** sqlite3_open() and sqlite3_open16().</dd>
** </dl>
**
** If the 3rd parameter to sqlite3_open_v2() is not one of the
** combinations shown above or one of the combinations shown above combined
** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
** then the behavior is undefined.
**
** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
** opens in the multi-thread [threading mode] as long as the single-thread
** mode has not been set at compile-time or start-time.  If the
** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
** in the serialized [threading mode] unless single-thread was
** previously selected at compile-time or start-time.
** The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
** eligible to use [shared cache mode], regardless of whether or not shared
** cache is enabled using [sqlite3_enable_shared_cache()].  The
** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
** participate in [shared cache mode] even if it is enabled.
**
** If the filename is ":memory:", then a private, temporary in-memory database
** is created for the connection.  This in-memory database will vanish when
** the database connection is closed.  Future versions of SQLite might
** make use of additional special filenames that begin with the ":" character.
** It is recommended that when a database filename actually does begin with
** a ":" character you should prefix the filename with a pathname such as
** "./" to avoid ambiguity.
**
** If the filename is an empty string, then a private, temporary
** on-disk database will be created.  This private database will be
** automatically deleted as soon as the database connection is closed.
**
** The fourth parameter to sqlite3_open_v2() is the name of the
** [sqlite3_vfs] object that defines the operating system interface that
** the new database connection should use.  If the fourth parameter is
** a NULL pointer then the default [sqlite3_vfs] object is used.
**
** <b>Note to Windows users:</b>  The encoding used for the filename argument
** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
** codepage is currently defined.  Filenames containing international
** characters must be converted to UTF-8 prior to passing them into
** sqlite3_open() or sqlite3_open_v2().
**
** Requirements:
** [H12701] [H12702] [H12703] [H12704] [H12706] [H12707] [H12709] [H12711]
** [H12712] [H12713] [H12714] [H12717] [H12719] [H12721] [H12723]
*/
int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);
int sqlite3_open16(
  const void *filename,   /* Database filename (UTF-16) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);
int sqlite3_open_v2(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb,         /* OUT: SQLite db handle */
  int flags,              /* Flags */
  const char *zVfs        /* Name of VFS module to use */
);

/*
** CAPI3REF: Error Codes And Messages {H12800} <S60200>
**
** The sqlite3_errcode() interface returns the numeric [result code] or
** [extended result code] for the most recent failed sqlite3_* API call
** associated with a [database connection]. If a prior API call failed
** but the most recent API call succeeded, the return value from
** sqlite3_errcode() is undefined.  The sqlite3_extended_errcode()
** interface is the same except that it always returns the 
** [extended result code] even when extended result codes are
** disabled.
**
** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
** text that describes the error, as either UTF-8 or UTF-16 respectively.
** Memory to hold the error message string is managed internally.
** The application does not need to worry about freeing the result.
** However, the error string might be overwritten or deallocated by
** subsequent calls to other SQLite interface functions.
**
** When the serialized [threading mode] is in use, it might be the
** case that a second error occurs on a separate thread in between
** the time of the first error and the call to these interfaces.
** When that happens, the second error will be reported since these
** interfaces always report the most recent result.  To avoid
** this, each thread can obtain exclusive use of the [database connection] D
** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
** all calls to the interfaces listed here are completed.
**
** If an interface fails with SQLITE_MISUSE, that means the interface
** was invoked incorrectly by the application.  In that case, the
** error code and message may or may not be set.
**
** Requirements:
** [H12801] [H12802] [H12803] [H12807] [H12808] [H12809]
*/
int sqlite3_errcode(sqlite3 *db);
int sqlite3_extended_errcode(sqlite3 *db);
const char *sqlite3_errmsg(sqlite3*);
const void *sqlite3_errmsg16(sqlite3*);

/*
** CAPI3REF: SQL Statement Object {H13000} <H13010>
** KEYWORDS: {prepared statement} {prepared statements}
**
** An instance of this object represents a single SQL statement.
** This object is variously known as a "prepared statement" or a
** "compiled SQL statement" or simply as a "statement".
**
** The life of a statement object goes something like this:
**
** <ol>
** <li> Create the object using [sqlite3_prepare_v2()] or a related
**      function.
** <li> Bind values to [host parameters] using the sqlite3_bind_*()
**      interfaces.
** <li> Run the SQL by calling [sqlite3_step()] one or more times.
** <li> Reset the statement using [sqlite3_reset()] then go back
**      to step 2.  Do this zero or more times.
** <li> Destroy the object using [sqlite3_finalize()].
** </ol>
**
** Refer to documentation on individual methods above for additional
** information.
*/
typedef struct sqlite3_stmt sqlite3_stmt;

/*
** CAPI3REF: Run-time Limits {H12760} <S20600>
**
** This interface allows the size of various constructs to be limited
** on a connection by connection basis.  The first parameter is the
** [database connection] whose limit is to be set or queried.  The
** second parameter is one of the [limit categories] that define a
** class of constructs to be size limited.  The third parameter is the
** new limit for that construct.  The function returns the old limit.
**
** If the new limit is a negative number, the limit is unchanged.
** For the limit category of SQLITE_LIMIT_XYZ there is a 
** [limits | hard upper bound]
** set by a compile-time C preprocessor macro named 
** [limits | SQLITE_MAX_XYZ].
** (The "_LIMIT_" in the name is changed to "_MAX_".)
** Attempts to increase a limit above its hard upper bound are
** silently truncated to the hard upper limit.
**
** Run time limits are intended for use in applications that manage
** both their own internal database and also databases that are controlled
** by untrusted external sources.  An example application might be a
** web browser that has its own databases for storing history and
** separate databases controlled by JavaScript applications downloaded
** off the Internet.  The internal databases can be given the
** large, default limits.  Databases managed by external sources can
** be given much smaller limits designed to prevent a denial of service
** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
** interface to further control untrusted SQL.  The size of the database
** created by an untrusted script can be contained using the
** [max_page_count] [PRAGMA].
**
** New run-time limit categories may be added in future releases.
**
** Requirements:
** [H12762] [H12766] [H12769]
*/
int sqlite3_limit(sqlite3*, int id, int newVal);

/*
** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
** KEYWORDS: {limit category} {*limit categories}
**
** These constants define various performance limits
** that can be lowered at run-time using [sqlite3_limit()].
** The synopsis of the meanings of the various limits is shown below.
** Additional information is available at [limits | Limits in SQLite].
**
** <dl>
** <dt>SQLITE_LIMIT_LENGTH</dt>
** <dd>The maximum size of any string or BLOB or table row.<dd>
**
** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
** <dd>The maximum length of an SQL statement.</dd>
**
** <dt>SQLITE_LIMIT_COLUMN</dt>
** <dd>The maximum number of columns in a table definition or in the
** result set of a [SELECT] or the maximum number of columns in an index
** or in an ORDER BY or GROUP BY clause.</dd>
**
** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
** <dd>The maximum depth of the parse tree on any expression.</dd>
**
** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
** <dd>The maximum number of terms in a compound SELECT statement.</dd>
**
** <dt>SQLITE_LIMIT_VDBE_OP</dt>
** <dd>The maximum number of instructions in a virtual machine program
** used to implement an SQL statement.</dd>
**
** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
** <dd>The maximum number of arguments on a function.</dd>
**
** <dt>SQLITE_LIMIT_ATTACHED</dt>
** <dd>The maximum number of [ATTACH | attached databases].</dd>
**
** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
** <dd>The maximum length of the pattern argument to the [LIKE] or
** [GLOB] operators.</dd>
**
** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
** <dd>The maximum number of variables in an SQL statement that can
** be bound.</dd>
**
** <dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
** <dd>The maximum depth of recursion for triggers.</dd>
** </dl>
*/
#define SQLITE_LIMIT_LENGTH                    0
#define SQLITE_LIMIT_SQL_LENGTH                1
#define SQLITE_LIMIT_COLUMN                    2
#define SQLITE_LIMIT_EXPR_DEPTH                3
#define SQLITE_LIMIT_COMPOUND_SELECT           4
#define SQLITE_LIMIT_VDBE_OP                   5
#define SQLITE_LIMIT_FUNCTION_ARG              6
#define SQLITE_LIMIT_ATTACHED                  7
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
#define SQLITE_LIMIT_VARIABLE_NUMBER           9
#define SQLITE_LIMIT_TRIGGER_DEPTH            10

/*
** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
** KEYWORDS: {SQL statement compiler}
**
** To execute an SQL query, it must first be compiled into a byte-code
** program using one of these routines.
**
** The first argument, "db", is a [database connection] obtained from a
** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
** [sqlite3_open16()].  The database connection must not have been closed.
**
** The second argument, "zSql", is the statement to be compiled, encoded
** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
** use UTF-16.
**
** If the nByte argument is less than zero, then zSql is read up to the
** first zero terminator. If nByte is non-negative, then it is the maximum
** number of  bytes read from zSql.  When nByte is non-negative, the
** zSql string ends at either the first '\000' or '\u0000' character or
** the nByte-th byte, whichever comes first. If the caller knows
** that the supplied string is nul-terminated, then there is a small
** performance advantage to be gained by passing an nByte parameter that
** is equal to the number of bytes in the input string <i>including</i>
** the nul-terminator bytes.
**
** If pzTail is not NULL then *pzTail is made to point to the first byte
** past the end of the first SQL statement in zSql.  These routines only
** compile the first statement in zSql, so *pzTail is left pointing to
** what remains uncompiled.
**
** *ppStmt is left pointing to a compiled [prepared statement] that can be
** executed using [sqlite3_step()].  If there is an error, *ppStmt is set
** to NULL.  If the input text contains no SQL (if the input is an empty
** string or a comment) then *ppStmt is set to NULL.
** The calling procedure is responsible for deleting the compiled
** SQL statement using [sqlite3_finalize()] after it has finished with it.
** ppStmt may not be NULL.
**
** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
**
** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
** recommended for all new programs. The two older interfaces are retained
** for backwards compatibility, but their use is discouraged.
** In the "v2" interfaces, the prepared statement
** that is returned (the [sqlite3_stmt] object) contains a copy of the
** original SQL text. This causes the [sqlite3_step()] interface to
** behave differently in three ways:
**
** <ol>
** <li>
** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
** always used to do, [sqlite3_step()] will automatically recompile the SQL
** statement and try to run it again.  If the schema has changed in
** a way that makes the statement no longer valid, [sqlite3_step()] will still
** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
** error go away.  Note: use [sqlite3_errmsg()] to find the text
** of the parsing error that results in an [SQLITE_SCHEMA] return.
** </li>
**
** <li>
** When an error occurs, [sqlite3_step()] will return one of the detailed
** [error codes] or [extended error codes].  The legacy behavior was that
** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
** and you would have to make a second call to [sqlite3_reset()] in order
** to find the underlying cause of the problem. With the "v2" prepare
** interfaces, the underlying reason for the error is returned immediately.
** </li>
**
** <li>
** ^If the value of a [parameter | host parameter] in the WHERE clause might
** change the query plan for a statement, then the statement may be
** automatically recompiled (as if there had been a schema change) on the first 
** [sqlite3_step()] call following any change to the 
** [sqlite3_bind_text | bindings] of the [parameter]. 
** </li>
** </ol>
**
** Requirements:
** [H13011] [H13012] [H13013] [H13014] [H13015] [H13016] [H13019] [H13021]
**
*/
int sqlite3_prepare(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare_v2(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare16(
  sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare16_v2(
  sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);

/*
** CAPI3REF: Retrieving Statement SQL {H13100} <H13000>
**
** This interface can be used to retrieve a saved copy of the original
** SQL text used to create a [prepared statement] if that statement was
** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
**
** Requirements:
** [H13101] [H13102] [H13103]
*/
const char *sqlite3_sql(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
**
** SQLite uses the sqlite3_value object to represent all values
** that can be stored in a database table. SQLite uses dynamic typing
** for the values it stores. Values stored in sqlite3_value objects
** can be integers, floating point values, strings, BLOBs, or NULL.
**
** An sqlite3_value object may be either "protected" or "unprotected".
** Some interfaces require a protected sqlite3_value.  Other interfaces
** will accept either a protected or an unprotected sqlite3_value.
** Every interface that accepts sqlite3_value arguments specifies
** whether or not it requires a protected sqlite3_value.
**
** The terms "protected" and "unprotected" refer to whether or not
** a mutex is held.  A internal mutex is held for a protected
** sqlite3_value object but no mutex is held for an unprotected
** sqlite3_value object.  If SQLite is compiled to be single-threaded
** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
** or if SQLite is run in one of reduced mutex modes 
** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
** then there is no distinction between protected and unprotected
** sqlite3_value objects and they can be used interchangeably.  However,
** for maximum code portability it is recommended that applications
** still make the distinction between between protected and unprotected
** sqlite3_value objects even when not strictly required.
**
** The sqlite3_value objects that are passed as parameters into the
** implementation of [application-defined SQL functions] are protected.
** The sqlite3_value object returned by
** [sqlite3_column_value()] is unprotected.
** Unprotected sqlite3_value objects may only be used with
** [sqlite3_result_value()] and [sqlite3_bind_value()].
** The [sqlite3_value_blob | sqlite3_value_type()] family of
** interfaces require protected sqlite3_value objects.
*/
typedef struct Mem sqlite3_value;

/*
** CAPI3REF: SQL Function Context Object {H16001} <S20200>
**
** The context in which an SQL function executes is stored in an
** sqlite3_context object.  A pointer to an sqlite3_context object
** is always first parameter to [application-defined SQL functions].
** The application-defined SQL function implementation will pass this
** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
** [sqlite3_aggregate_context()], [sqlite3_user_data()],
** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
** and/or [sqlite3_set_auxdata()].
*/
typedef struct sqlite3_context sqlite3_context;

/*
** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
** KEYWORDS: {host parameter} {host parameters} {host parameter name}
** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
**
** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
** literals may be replaced by a [parameter] that matches one of following
** templates:
**
** <ul>
** <li>  ?
** <li>  ?NNN
** <li>  :VVV
** <li>  @VVV
** <li>  $VVV
** </ul>
**
** In the templates above, NNN represents an integer literal,
** and VVV represents an alphanumeric identifer.  The values of these
** parameters (also called "host parameter names" or "SQL parameters")
** can be set using the sqlite3_bind_*() routines defined here.
**
** The first argument to the sqlite3_bind_*() routines is always
** a pointer to the [sqlite3_stmt] object returned from
** [sqlite3_prepare_v2()] or its variants.
**
** The second argument is the index of the SQL parameter to be set.
** The leftmost SQL parameter has an index of 1.  When the same named
** SQL parameter is used more than once, second and subsequent
** occurrences have the same index as the first occurrence.
** The index for named parameters can be looked up using the
** [sqlite3_bind_parameter_index()] API if desired.  The index
** for "?NNN" parameters is the value of NNN.
** The NNN value must be between 1 and the [sqlite3_limit()]
** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
**
** The third argument is the value to bind to the parameter.
**
** In those routines that have a fourth argument, its value is the
** number of bytes in the parameter.  To be clear: the value is the
** number of <u>bytes</u> in the value, not the number of characters.
** If the fourth parameter is negative, the length of the string is
** the number of bytes up to the first zero terminator.
**
** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
** string after SQLite has finished with it. If the fifth argument is
** the special value [SQLITE_STATIC], then SQLite assumes that the
** information is in static, unmanaged space and does not need to be freed.
** If the fifth argument has the value [SQLITE_TRANSIENT], then
** SQLite makes its own private copy of the data immediately, before
** the sqlite3_bind_*() routine returns.
**
** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
** is filled with zeroes.  A zeroblob uses a fixed amount of memory
** (just an integer to hold its size) while it is being processed.
** Zeroblobs are intended to serve as placeholders for BLOBs whose
** content is later written using
** [sqlite3_blob_open | incremental BLOB I/O] routines.
** A negative value for the zeroblob results in a zero-length BLOB.
**
** The sqlite3_bind_*() routines must be called after
** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
** before [sqlite3_step()].
** Bindings are not cleared by the [sqlite3_reset()] routine.
** Unbound parameters are interpreted as NULL.
**
** These routines return [SQLITE_OK] on success or an error code if
** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
** index is out of range.  [SQLITE_NOMEM] is returned if malloc() fails.
** [SQLITE_MISUSE] might be returned if these routines are called on a
** virtual machine that is the wrong state or which has already been finalized.
** Detection of misuse is unreliable.  Applications should not depend
** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
** a logic error in the application.  Future versions of SQLite might
** panic rather than return SQLITE_MISUSE.
**
** See also: [sqlite3_bind_parameter_count()],
** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
**
** Requirements:
** [H13506] [H13509] [H13512] [H13515] [H13518] [H13521] [H13524] [H13527]
** [H13530] [H13533] [H13536] [H13539] [H13542] [H13545] [H13548] [H13551]
**
*/
int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
int sqlite3_bind_double(sqlite3_stmt*, int, double);
int sqlite3_bind_int(sqlite3_stmt*, int, int);
int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
int sqlite3_bind_null(sqlite3_stmt*, int);
int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);

/*
** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
**
** This routine can be used to find the number of [SQL parameters]
** in a [prepared statement].  SQL parameters are tokens of the
** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
** placeholders for values that are [sqlite3_bind_blob | bound]
** to the parameters at a later time.
**
** This routine actually returns the index of the largest (rightmost)
** parameter. For all forms except ?NNN, this will correspond to the
** number of unique parameters.  If parameters of the ?NNN are used,
** there may be gaps in the list.
**
** See also: [sqlite3_bind_blob|sqlite3_bind()],
** [sqlite3_bind_parameter_name()], and
** [sqlite3_bind_parameter_index()].
**
** Requirements:
** [H13601]
*/
int sqlite3_bind_parameter_count(sqlite3_stmt*);

/*
** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
**
** This routine returns a pointer to the name of the n-th
** [SQL parameter] in a [prepared statement].
** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
** respectively.
** In other words, the initial ":" or "$" or "@" or "?"
** is included as part of the name.
** Parameters of the form "?" without a following integer have no name
** and are also referred to as "anonymous parameters".
**
** The first host parameter has an index of 1, not 0.
**
** If the value n is out of range or if the n-th parameter is
** nameless, then NULL is returned.  The returned string is
** always in UTF-8 encoding even if the named parameter was
** originally specified as UTF-16 in [sqlite3_prepare16()] or
** [sqlite3_prepare16_v2()].
**
** See also: [sqlite3_bind_blob|sqlite3_bind()],
** [sqlite3_bind_parameter_count()], and
** [sqlite3_bind_parameter_index()].
**
** Requirements:
** [H13621]
*/
const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);

/*
** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
**
** Return the index of an SQL parameter given its name.  The
** index value returned is suitable for use as the second
** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
** is returned if no matching parameter is found.  The parameter
** name must be given in UTF-8 even if the original statement
** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
**
** See also: [sqlite3_bind_blob|sqlite3_bind()],
** [sqlite3_bind_parameter_count()], and
** [sqlite3_bind_parameter_index()].
**
** Requirements:
** [H13641]
*/
int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);

/*
** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
**
** Contrary to the intuition of many, [sqlite3_reset()] does not reset
** the [sqlite3_bind_blob | bindings] on a [prepared statement].
** Use this routine to reset all host parameters to NULL.
**
** Requirements:
** [H13661]
*/
int sqlite3_clear_bindings(sqlite3_stmt*);

/*
** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
**
** Return the number of columns in the result set returned by the
** [prepared statement]. This routine returns 0 if pStmt is an SQL
** statement that does not return data (for example an [UPDATE]).
**
** Requirements:
** [H13711]
*/
int sqlite3_column_count(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
**
** These routines return the name assigned to a particular column
** in the result set of a [SELECT] statement.  The sqlite3_column_name()
** interface returns a pointer to a zero-terminated UTF-8 string
** and sqlite3_column_name16() returns a pointer to a zero-terminated
** UTF-16 string.  The first parameter is the [prepared statement]
** that implements the [SELECT] statement. The second parameter is the
** column number.  The leftmost column is number 0.
**
** The returned string pointer is valid until either the [prepared statement]
** is destroyed by [sqlite3_finalize()] or until the next call to
** sqlite3_column_name() or sqlite3_column_name16() on the same column.
**
** If sqlite3_malloc() fails during the processing of either routine
** (for example during a conversion from UTF-8 to UTF-16) then a
** NULL pointer is returned.
**
** The name of a result column is the value of the "AS" clause for
** that column, if there is an AS clause.  If there is no AS clause
** then the name of the column is unspecified and may change from
** one release of SQLite to the next.
**
** Requirements:
** [H13721] [H13723] [H13724] [H13725] [H13726] [H13727]
*/
const char *sqlite3_column_name(sqlite3_stmt*, int N);
const void *sqlite3_column_name16(sqlite3_stmt*, int N);

/*
** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
**
** These routines provide a means to determine what column of what
** table in which database a result of a [SELECT] statement comes from.
** The name of the database or table or column can be returned as
** either a UTF-8 or UTF-16 string.  The _database_ routines return
** the database name, the _table_ routines return the table name, and
** the origin_ routines return the column name.
** The returned string is valid until the [prepared statement] is destroyed
** using [sqlite3_finalize()] or until the same information is requested
** again in a different encoding.
**
** The names returned are the original un-aliased names of the
** database, table, and column.
**
** The first argument to the following calls is a [prepared statement].
** These functions return information about the Nth column returned by
** the statement, where N is the second function argument.
**
** If the Nth column returned by the statement is an expression or
** subquery and is not a column value, then all of these functions return
** NULL.  These routine might also return NULL if a memory allocation error
** occurs.  Otherwise, they return the name of the attached database, table
** and column that query result column was extracted from.
**
** As with all other SQLite APIs, those postfixed with "16" return
** UTF-16 encoded strings, the other functions return UTF-8. {END}
**
** These APIs are only available if the library was compiled with the
** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
**
** {A13751}
** If two or more threads call one or more of these routines against the same
** prepared statement and column at the same time then the results are
** undefined.
**
** Requirements:
** [H13741] [H13742] [H13743] [H13744] [H13745] [H13746] [H13748]
**
** If two or more threads call one or more
** [sqlite3_column_database_name | column metadata interfaces]
** for the same [prepared statement] and result column
** at the same time then the results are undefined.
*/
const char *sqlite3_column_database_name(sqlite3_stmt*,int);
const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
const char *sqlite3_column_table_name(sqlite3_stmt*,int);
const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);

/*
** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
**
** The first parameter is a [prepared statement].
** If this statement is a [SELECT] statement and the Nth column of the
** returned result set of that [SELECT] is a table column (not an
** expression or subquery) then the declared type of the table
** column is returned.  If the Nth column of the result set is an
** expression or subquery, then a NULL pointer is returned.
** The returned string is always UTF-8 encoded. {END}
**
** For example, given the database schema:
**
** CREATE TABLE t1(c1 VARIANT);
**
** and the following statement to be compiled:
**
** SELECT c1 + 1, c1 FROM t1;
**
** this routine would return the string "VARIANT" for the second result
** column (i==1), and a NULL pointer for the first result column (i==0).
**
** SQLite uses dynamic run-time typing.  So just because a column
** is declared to contain a particular type does not mean that the
** data stored in that column is of the declared type.  SQLite is
** strongly typed, but the typing is dynamic not static.  Type
** is associated with individual values, not with the containers
** used to hold those values.
**
** Requirements:
** [H13761] [H13762] [H13763]
*/
const char *sqlite3_column_decltype(sqlite3_stmt*,int);
const void *sqlite3_column_decltype16(sqlite3_stmt*,int);

/*
** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
**
** After a [prepared statement] has been prepared using either
** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
** must be called one or more times to evaluate the statement.
**
** The details of the behavior of the sqlite3_step() interface depend
** on whether the statement was prepared using the newer "v2" interface
** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
** new "v2" interface is recommended for new applications but the legacy
** interface will continue to be supported.
**
** In the legacy interface, the return value will be either [SQLITE_BUSY],
** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
** With the "v2" interface, any of the other [result codes] or
** [extended result codes] might be returned as well.
**
** [SQLITE_BUSY] means that the database engine was unable to acquire the
** database locks it needs to do its job.  If the statement is a [COMMIT]
** or occurs outside of an explicit transaction, then you can retry the
** statement.  If the statement is not a [COMMIT] and occurs within a
** explicit transaction then you should rollback the transaction before
** continuing.
**
** [SQLITE_DONE] means that the statement has finished executing
** successfully.  sqlite3_step() should not be called again on this virtual
** machine without first calling [sqlite3_reset()] to reset the virtual
** machine back to its initial state.
**
** If the SQL statement being executed returns any data, then [SQLITE_ROW]
** is returned each time a new row of data is ready for processing by the
** caller. The values may be accessed using the [column access functions].
** sqlite3_step() is called again to retrieve the next row of data.
**
** [SQLITE_ERROR] means that a run-time error (such as a constraint
** violation) has occurred.  sqlite3_step() should not be called again on
** the VM. More information may be found by calling [sqlite3_errmsg()].
** With the legacy interface, a more specific error code (for example,
** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
** can be obtained by calling [sqlite3_reset()] on the
** [prepared statement].  In the "v2" interface,
** the more specific error code is returned directly by sqlite3_step().
**
** [SQLITE_MISUSE] means that the this routine was called inappropriately.
** Perhaps it was called on a [prepared statement] that has
** already been [sqlite3_finalize | finalized] or on one that had
** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
** be the case that the same database connection is being used by two or
** more threads at the same moment in time.
**
** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
** API always returns a generic error code, [SQLITE_ERROR], following any
** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
** specific [error codes] that better describes the error.
** We admit that this is a goofy design.  The problem has been fixed
** with the "v2" interface.  If you prepare all of your SQL statements
** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
** then the more specific [error codes] are returned directly
** by sqlite3_step().  The use of the "v2" interface is recommended.
**
** Requirements:
** [H13202] [H15304] [H15306] [H15308] [H15310]
*/
int sqlite3_step(sqlite3_stmt*);

/*
** CAPI3REF: Number of columns in a result set {H13770} <S10700>
**
** Returns the number of values in the current row of the result set.
**
** Requirements:
** [H13771] [H13772]
*/
int sqlite3_data_count(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
** KEYWORDS: SQLITE_TEXT
**
** {H10266} Every value in SQLite has one of five fundamental datatypes:
**
** <ul>
** <li> 64-bit signed integer
** <li> 64-bit IEEE floating point number
** <li> string
** <li> BLOB
** <li> NULL
** </ul> {END}
**
** These constants are codes for each of those types.
**
** Note that the SQLITE_TEXT constant was also used in SQLite version 2
** for a completely different meaning.  Software that links against both
** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
** SQLITE_TEXT.
*/
#define SQLITE_INTEGER  1
#define SQLITE_FLOAT    2
#define SQLITE_BLOB     4
#define SQLITE_NULL     5
#ifdef SQLITE_TEXT
# undef SQLITE_TEXT
#else
# define SQLITE_TEXT     3
#endif
#define SQLITE3_TEXT     3

/*
** CAPI3REF: Result Values From A Query {H13800} <S10700>
** KEYWORDS: {column access functions}
**
** These routines form the "result set query" interface.
**
** These routines return information about a single column of the current
** result row of a query.  In every case the first argument is a pointer
** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
** that was returned from [sqlite3_prepare_v2()] or one of its variants)
** and the second argument is the index of the column for which information
** should be returned.  The leftmost column of the result set has the index 0.
** The number of columns in the result can be determined using
** [sqlite3_column_count()].
**
** If the SQL statement does not currently point to a valid row, or if the
** column index is out of range, the result is undefined.
** These routines may only be called when the most recent call to
** [sqlite3_step()] has returned [SQLITE_ROW] and neither
** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
** If any of these routines are called after [sqlite3_reset()] or
** [sqlite3_finalize()] or after [sqlite3_step()] has returned
** something other than [SQLITE_ROW], the results are undefined.
** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
** are called from a different thread while any of these routines
** are pending, then the results are undefined.
**
** The sqlite3_column_type() routine returns the
** [SQLITE_INTEGER | datatype code] for the initial data type
** of the result column.  The returned value is one of [SQLITE_INTEGER],
** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
** returned by sqlite3_column_type() is only meaningful if no type
** conversions have occurred as described below.  After a type conversion,
** the value returned by sqlite3_column_type() is undefined.  Future
** versions of SQLite may change the behavior of sqlite3_column_type()
** following a type conversion.
**
** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
** routine returns the number of bytes in that BLOB or string.
** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
** the string to UTF-8 and then returns the number of bytes.
** If the result is a numeric value then sqlite3_column_bytes() uses
** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
** the number of bytes in that string.
** The value returned does not include the zero terminator at the end
** of the string.  For clarity: the value returned is the number of
** bytes in the string, not the number of characters.
**
** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
** even empty strings, are always zero terminated.  The return
** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
** pointer, possibly even a NULL pointer.
**
** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
** but leaves the result in UTF-16 in native byte order instead of UTF-8.
** The zero terminator is not included in this count.
**
** The object returned by [sqlite3_column_value()] is an
** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
** If the [unprotected sqlite3_value] object returned by
** [sqlite3_column_value()] is used in any other way, including calls
** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
** or [sqlite3_value_bytes()], then the behavior is undefined.
**
** These routines attempt to convert the value where appropriate.  For
** example, if the internal representation is FLOAT and a text result
** is requested, [sqlite3_snprintf()] is used internally to perform the
** conversion automatically.  The following table details the conversions
** that are applied:
**
** <blockquote>
** <table border="1">
** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
**
** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
** <tr><td>  TEXT    <td>   BLOB    <td> No change
** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
** </table>
** </blockquote>
**
** The table above makes reference to standard C library functions atoi()
** and atof().  SQLite does not really use these functions.  It has its
** own equivalent internal routines.  The atoi() and atof() names are
** used in the table for brevity and because they are familiar to most
** C programmers.
**
** Note that when type conversions occur, pointers returned by prior
** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
** sqlite3_column_text16() may be invalidated.
** Type conversions and pointer invalidations might occur
** in the following cases:
**
** <ul>
** <li> The initial content is a BLOB and sqlite3_column_text() or
**      sqlite3_column_text16() is called.  A zero-terminator might
**      need to be added to the string.</li>
** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
**      sqlite3_column_text16() is called.  The content must be converted
**      to UTF-16.</li>
** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
**      sqlite3_column_text() is called.  The content must be converted
**      to UTF-8.</li>
** </ul>
**
** Conversions between UTF-16be and UTF-16le are always done in place and do
** not invalidate a prior pointer, though of course the content of the buffer
** that the prior pointer points to will have been modified.  Other kinds
** of conversion are done in place when it is possible, but sometimes they
** are not possible and in those cases prior pointers are invalidated.
**
** The safest and easiest to remember policy is to invoke these routines
** in one of the following ways:
**
** <ul>
**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
** </ul>
**
** In other words, you should call sqlite3_column_text(),
** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
** into the desired format, then invoke sqlite3_column_bytes() or
** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
** to sqlite3_column_text() or sqlite3_column_blob() with calls to
** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
** with calls to sqlite3_column_bytes().
**
** The pointers returned are valid until a type conversion occurs as
** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
** [sqlite3_finalize()] is called.  The memory space used to hold strings
** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
** [sqlite3_free()].
**
** If a memory allocation error occurs during the evaluation of any
** of these routines, a default value is returned.  The default value
** is either the integer 0, the floating point number 0.0, or a NULL
** pointer.  Subsequent calls to [sqlite3_errcode()] will return
** [SQLITE_NOMEM].
**
** Requirements:
** [H13803] [H13806] [H13809] [H13812] [H13815] [H13818] [H13821] [H13824]
** [H13827] [H13830]
*/
const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
double sqlite3_column_double(sqlite3_stmt*, int iCol);
int sqlite3_column_int(sqlite3_stmt*, int iCol);
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
int sqlite3_column_type(sqlite3_stmt*, int iCol);
sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);

/*
** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
**
** The sqlite3_finalize() function is called to delete a [prepared statement].
** If the statement was executed successfully or not executed at all, then
** SQLITE_OK is returned. If execution of the statement failed then an
** [error code] or [extended error code] is returned.
**
** This routine can be called at any point during the execution of the
** [prepared statement].  If the virtual machine has not
** completed execution when this routine is called, that is like
** encountering an error or an [sqlite3_interrupt | interrupt].
** Incomplete updates may be rolled back and transactions canceled,
** depending on the circumstances, and the
** [error code] returned will be [SQLITE_ABORT].
**
** Requirements:
** [H11302] [H11304]
*/
int sqlite3_finalize(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
**
** The sqlite3_reset() function is called to reset a [prepared statement]
** object back to its initial state, ready to be re-executed.
** Any SQL statement variables that had values bound to them using
** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
** Use [sqlite3_clear_bindings()] to reset the bindings.
**
** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
**          back to the beginning of its program.
**
** {H11334} If the most recent call to [sqlite3_step(S)] for the
**          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
**          or if [sqlite3_step(S)] has never before been called on S,
**          then [sqlite3_reset(S)] returns [SQLITE_OK].
**
** {H11336} If the most recent call to [sqlite3_step(S)] for the
**          [prepared statement] S indicated an error, then
**          [sqlite3_reset(S)] returns an appropriate [error code].
**
** {H11338} The [sqlite3_reset(S)] interface does not change the values
**          of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
*/
int sqlite3_reset(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
** KEYWORDS: {function creation routines}
** KEYWORDS: {application-defined SQL function}
** KEYWORDS: {application-defined SQL functions}
**
** These two functions (collectively known as "function creation routines")
** are used to add SQL functions or aggregates or to redefine the behavior
** of existing SQL functions or aggregates.  The only difference between the
** two is that the second parameter, the name of the (scalar) function or
** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
** for sqlite3_create_function16().
**
** The first parameter is the [database connection] to which the SQL
** function is to be added.  If a single program uses more than one database
** connection internally, then SQL functions must be added individually to
** each database connection.
**
** The second parameter is the name of the SQL function to be created or
** redefined.  The length of the name is limited to 255 bytes, exclusive of
** the zero-terminator.  Note that the name length limit is in bytes, not
** characters.  Any attempt to create a function with a longer name
** will result in [SQLITE_ERROR] being returned.
**
** The third parameter (nArg)
** is the number of arguments that the SQL function or
** aggregate takes. If this parameter is -1, then the SQL function or
** aggregate may take any number of arguments between 0 and the limit
** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
** parameter is less than -1 or greater than 127 then the behavior is
** undefined.
**
** The fourth parameter, eTextRep, specifies what
** [SQLITE_UTF8 | text encoding] this SQL function prefers for
** its parameters.  Any SQL function implementation should be able to work
** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
** more efficient with one encoding than another.  An application may
** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
** times with the same function but with different values of eTextRep.
** When multiple implementations of the same function are available, SQLite
** will pick the one that involves the least amount of data conversion.
** If there is only a single implementation which does not care what text
** encoding is used, then the fourth argument should be [SQLITE_ANY].
**
** The fifth parameter is an arbitrary pointer.  The implementation of the
** function can gain access to this pointer using [sqlite3_user_data()].
**
** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
** pointers to C-language functions that implement the SQL function or
** aggregate. A scalar SQL function requires an implementation of the xFunc
** callback only, NULL pointers should be passed as the xStep and xFinal
** parameters. An aggregate SQL function requires an implementation of xStep
** and xFinal and NULL should be passed for xFunc. To delete an existing
** SQL function or aggregate, pass NULL for all three function callbacks.
**
** It is permitted to register multiple implementations of the same
** functions with the same name but with either differing numbers of
** arguments or differing preferred text encodings.  SQLite will use
** the implementation that most closely matches the way in which the
** SQL function is used.  A function implementation with a non-negative
** nArg parameter is a better match than a function implementation with
** a negative nArg.  A function where the preferred text encoding
** matches the database encoding is a better
** match than a function where the encoding is different.  
** A function where the encoding difference is between UTF16le and UTF16be
** is a closer match than a function where the encoding difference is
** between UTF8 and UTF16.
**
** Built-in functions may be overloaded by new application-defined functions.
** The first application-defined function with a given name overrides all
** built-in functions in the same [database connection] with the same name.
** Subsequent application-defined functions of the same name only override 
** prior application-defined functions that are an exact match for the
** number of parameters and preferred encoding.
**
** An application-defined function is permitted to call other
** SQLite interfaces.  However, such calls must not
** close the database connection nor finalize or reset the prepared
** statement in which the function is running.
**
** Requirements:
** [H16103] [H16106] [H16109] [H16112] [H16118] [H16121] [H16127]
** [H16130] [H16133] [H16136] [H16139] [H16142]
*/
int sqlite3_create_function(
  sqlite3 *db,
  const char *zFunctionName,
  int nArg,
  int eTextRep,
  void *pApp,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  void (*xFinal)(sqlite3_context*)
);
int sqlite3_create_function16(
  sqlite3 *db,
  const void *zFunctionName,
  int nArg,
  int eTextRep,
  void *pApp,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  void (*xFinal)(sqlite3_context*)
);

/*
** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
**
** These constant define integer codes that represent the various
** text encodings supported by SQLite.
*/
#define SQLITE_UTF8           1
#define SQLITE_UTF16LE        2
#define SQLITE_UTF16BE        3
#define SQLITE_UTF16          4    /* Use native byte order */
#define SQLITE_ANY            5    /* sqlite3_create_function only */
#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */

/*
** CAPI3REF: Deprecated Functions
** DEPRECATED
**
** These functions are [deprecated].  In order to maintain
** backwards compatibility with older code, these functions continue 
** to be supported.  However, new applications should avoid
** the use of these functions.  To help encourage people to avoid
** using these functions, we are not going to tell you what they do.
*/
#ifndef SQLITE_OMIT_DEPRECATED
SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
SQLITE_DEPRECATED int sqlite3_global_recover(void);
SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
#endif

/*
** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
**
** The C-language implementation of SQL functions and aggregates uses
** this set of interface routines to access the parameter values on
** the function or aggregate.
**
** The xFunc (for scalar functions) or xStep (for aggregates) parameters
** to [sqlite3_create_function()] and [sqlite3_create_function16()]
** define callbacks that implement the SQL functions and aggregates.
** The 4th parameter to these callbacks is an array of pointers to
** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
** each parameter to the SQL function.  These routines are used to
** extract values from the [sqlite3_value] objects.
**
** These routines work only with [protected sqlite3_value] objects.
** Any attempt to use these routines on an [unprotected sqlite3_value]
** object results in undefined behavior.
**
** These routines work just like the corresponding [column access functions]
** except that  these routines take a single [protected sqlite3_value] object
** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
**
** The sqlite3_value_text16() interface extracts a UTF-16 string
** in the native byte-order of the host machine.  The
** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
** extract UTF-16 strings as big-endian and little-endian respectively.
**
** The sqlite3_value_numeric_type() interface attempts to apply
** numeric affinity to the value.  This means that an attempt is
** made to convert the value to an integer or floating point.  If
** such a conversion is possible without loss of information (in other
** words, if the value is a string that looks like a number)
** then the conversion is performed.  Otherwise no conversion occurs.
** The [SQLITE_INTEGER | datatype] after conversion is returned.
**
** Please pay particular attention to the fact that the pointer returned
** from [sqlite3_value_blob()], [sqlite3_value_text()], or
** [sqlite3_value_text16()] can be invalidated by a subsequent call to
** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
** or [sqlite3_value_text16()].
**
** These routines must be called from the same thread as
** the SQL function that supplied the [sqlite3_value*] parameters.
**
** Requirements:
** [H15103] [H15106] [H15109] [H15112] [H15115] [H15118] [H15121] [H15124]
** [H15127] [H15130] [H15133] [H15136]
*/
const void *sqlite3_value_blob(sqlite3_value*);
int sqlite3_value_bytes(sqlite3_value*);
int sqlite3_value_bytes16(sqlite3_value*);
double sqlite3_value_double(sqlite3_value*);
int sqlite3_value_int(sqlite3_value*);
sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
const unsigned char *sqlite3_value_text(sqlite3_value*);
const void *sqlite3_value_text16(sqlite3_value*);
const void *sqlite3_value_text16le(sqlite3_value*);
const void *sqlite3_value_text16be(sqlite3_value*);
int sqlite3_value_type(sqlite3_value*);
int sqlite3_value_numeric_type(sqlite3_value*);

/*
** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
**
** The implementation of aggregate SQL functions use this routine to allocate
** a structure for storing their state.
**
** The first time the sqlite3_aggregate_context() routine is called for a
** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
** memory, and returns a pointer to it. On second and subsequent calls to
** sqlite3_aggregate_context() for the same aggregate function index,
** the same buffer is returned. The implementation of the aggregate can use
** the returned buffer to accumulate data.
**
** SQLite automatically frees the allocated buffer when the aggregate
** query concludes.
**
** The first parameter should be a copy of the
** [sqlite3_context | SQL function context] that is the first parameter
** to the callback routine that implements the aggregate function.
**
** This routine must be called from the same thread in which
** the aggregate SQL function is running.
**
** Requirements:
** [H16211] [H16213] [H16215] [H16217]
*/
void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);

/*
** CAPI3REF: User Data For Functions {H16240} <S20200>
**
** The sqlite3_user_data() interface returns a copy of
** the pointer that was the pUserData parameter (the 5th parameter)
** of the [sqlite3_create_function()]
** and [sqlite3_create_function16()] routines that originally
** registered the application defined function. {END}
**
** This routine must be called from the same thread in which
** the application-defined function is running.
**
** Requirements:
** [H16243]
*/
void *sqlite3_user_data(sqlite3_context*);

/*
** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
**
** The sqlite3_context_db_handle() interface returns a copy of
** the pointer to the [database connection] (the 1st parameter)
** of the [sqlite3_create_function()]
** and [sqlite3_create_function16()] routines that originally
** registered the application defined function.
**
** Requirements:
** [H16253]
*/
sqlite3 *sqlite3_context_db_handle(sqlite3_context*);

/*
** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
**
** The following two functions may be used by scalar SQL functions to
** associate metadata with argument values. If the same value is passed to
** multiple invocations of the same SQL function during query execution, under
** some circumstances the associated metadata may be preserved. This may
** be used, for example, to add a regular-expression matching scalar
** function. The compiled version of the regular expression is stored as
** metadata associated with the SQL value passed as the regular expression
** pattern.  The compiled regular expression can be reused on multiple
** invocations of the same function so that the original pattern string
** does not need to be recompiled on each invocation.
**
** The sqlite3_get_auxdata() interface returns a pointer to the metadata
** associated by the sqlite3_set_auxdata() function with the Nth argument
** value to the application-defined function. If no metadata has been ever
** been set for the Nth argument of the function, or if the corresponding
** function parameter has changed since the meta-data was set,
** then sqlite3_get_auxdata() returns a NULL pointer.
**
** The sqlite3_set_auxdata() interface saves the metadata
** pointed to by its 3rd parameter as the metadata for the N-th
** argument of the application-defined function.  Subsequent
** calls to sqlite3_get_auxdata() might return this data, if it has
** not been destroyed.
** If it is not NULL, SQLite will invoke the destructor
** function given by the 4th parameter to sqlite3_set_auxdata() on
** the metadata when the corresponding function parameter changes
** or when the SQL statement completes, whichever comes first.
**
** SQLite is free to call the destructor and drop metadata on any
** parameter of any function at any time.  The only guarantee is that
** the destructor will be called before the metadata is dropped.
**
** In practice, metadata is preserved between function calls for
** expressions that are constant at compile time. This includes literal
** values and SQL variables.
**
** These routines must be called from the same thread in which
** the SQL function is running.
**
** Requirements:
** [H16272] [H16274] [H16276] [H16277] [H16278] [H16279]
*/
void *sqlite3_get_auxdata(sqlite3_context*, int N);
void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));


/*
** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
**
** These are special values for the destructor that is passed in as the
** final argument to routines like [sqlite3_result_blob()].  If the destructor
** argument is SQLITE_STATIC, it means that the content pointer is constant
** and will never change.  It does not need to be destroyed.  The
** SQLITE_TRANSIENT value means that the content will likely change in
** the near future and that SQLite should make its own private copy of
** the content before returning.
**
** The typedef is necessary to work around problems in certain
** C++ compilers.  See ticket #2191.
*/
typedef void (*sqlite3_destructor_type)(void*);
#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)

/*
** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
**
** These routines are used by the xFunc or xFinal callbacks that
** implement SQL functions and aggregates.  See
** [sqlite3_create_function()] and [sqlite3_create_function16()]
** for additional information.
**
** These functions work very much like the [parameter binding] family of
** functions used to bind values to host parameters in prepared statements.
** Refer to the [SQL parameter] documentation for additional information.
**
** The sqlite3_result_blob() interface sets the result from
** an application-defined function to be the BLOB whose content is pointed
** to by the second parameter and which is N bytes long where N is the
** third parameter.
**
** The sqlite3_result_zeroblob() interfaces set the result of
** the application-defined function to be a BLOB containing all zero
** bytes and N bytes in size, where N is the value of the 2nd parameter.
**
** The sqlite3_result_double() interface sets the result from
** an application-defined function to be a floating point value specified
** by its 2nd argument.
**
** The sqlite3_result_error() and sqlite3_result_error16() functions
** cause the implemented SQL function to throw an exception.
** SQLite uses the string pointed to by the
** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
** as the text of an error message.  SQLite interprets the error
** message string from sqlite3_result_error() as UTF-8. SQLite
** interprets the string from sqlite3_result_error16() as UTF-16 in native
** byte order.  If the third parameter to sqlite3_result_error()
** or sqlite3_result_error16() is negative then SQLite takes as the error
** message all text up through the first zero character.
** If the third parameter to sqlite3_result_error() or
** sqlite3_result_error16() is non-negative then SQLite takes that many
** bytes (not characters) from the 2nd parameter as the error message.
** The sqlite3_result_error() and sqlite3_result_error16()
** routines make a private copy of the error message text before
** they return.  Hence, the calling function can deallocate or
** modify the text after they return without harm.
** The sqlite3_result_error_code() function changes the error code
** returned by SQLite as a result of an error in a function.  By default,
** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
**
** The sqlite3_result_toobig() interface causes SQLite to throw an error
** indicating that a string or BLOB is to long to represent.
**
** The sqlite3_result_nomem() interface causes SQLite to throw an error
** indicating that a memory allocation failed.
**
** The sqlite3_result_int() interface sets the return value
** of the application-defined function to be the 32-bit signed integer
** value given in the 2nd argument.
** The sqlite3_result_int64() interface sets the return value
** of the application-defined function to be the 64-bit signed integer
** value given in the 2nd argument.
**
** The sqlite3_result_null() interface sets the return value
** of the application-defined function to be NULL.
**
** The sqlite3_result_text(), sqlite3_result_text16(),
** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
** set the return value of the application-defined function to be
** a text string which is represented as UTF-8, UTF-16 native byte order,
** UTF-16 little endian, or UTF-16 big endian, respectively.
** SQLite takes the text result from the application from
** the 2nd parameter of the sqlite3_result_text* interfaces.
** If the 3rd parameter to the sqlite3_result_text* interfaces
** is negative, then SQLite takes result text from the 2nd parameter
** through the first zero character.
** If the 3rd parameter to the sqlite3_result_text* interfaces
** is non-negative, then as many bytes (not characters) of the text
** pointed to by the 2nd parameter are taken as the application-defined
** function result.
** If the 4th parameter to the sqlite3_result_text* interfaces
** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
** function as the destructor on the text or BLOB result when it has
** finished using that result.
** If the 4th parameter to the sqlite3_result_text* interfaces or to
** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
** assumes that the text or BLOB result is in constant space and does not
** copy the content of the parameter nor call a destructor on the content
** when it has finished using that result.
** If the 4th parameter to the sqlite3_result_text* interfaces
** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
** then SQLite makes a copy of the result into space obtained from
** from [sqlite3_malloc()] before it returns.
**
** The sqlite3_result_value() interface sets the result of
** the application-defined function to be a copy the
** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
** so that the [sqlite3_value] specified in the parameter may change or
** be deallocated after sqlite3_result_value() returns without harm.
** A [protected sqlite3_value] object may always be used where an
** [unprotected sqlite3_value] object is required, so either
** kind of [sqlite3_value] object can be used with this interface.
**
** If these routines are called from within the different thread
** than the one containing the application-defined function that received
** the [sqlite3_context] pointer, the results are undefined.
**
** Requirements:
** [H16403] [H16406] [H16409] [H16412] [H16415] [H16418] [H16421] [H16424]
** [H16427] [H16430] [H16433] [H16436] [H16439] [H16442] [H16445] [H16448]
** [H16451] [H16454] [H16457] [H16460] [H16463]
*/
void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
void sqlite3_result_double(sqlite3_context*, double);
void sqlite3_result_error(sqlite3_context*, const char*, int);
void sqlite3_result_error16(sqlite3_context*, const void*, int);
void sqlite3_result_error_toobig(sqlite3_context*);
void sqlite3_result_error_nomem(sqlite3_context*);
void sqlite3_result_error_code(sqlite3_context*, int);
void sqlite3_result_int(sqlite3_context*, int);
void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
void sqlite3_result_null(sqlite3_context*);
void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
void sqlite3_result_zeroblob(sqlite3_context*, int n);

/*
** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
**
** These functions are used to add new collation sequences to the
** [database connection] specified as the first argument.
**
** The name of the new collation sequence is specified as a UTF-8 string
** for sqlite3_create_collation() and sqlite3_create_collation_v2()
** and a UTF-16 string for sqlite3_create_collation16(). In all cases
** the name is passed as the second function argument.
**
** The third argument may be one of the constants [SQLITE_UTF8],
** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
** routine expects to be passed pointers to strings encoded using UTF-8,
** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
** third argument might also be [SQLITE_UTF16] to indicate that the routine
** expects pointers to be UTF-16 strings in the native byte order, or the
** argument can be [SQLITE_UTF16_ALIGNED] if the
** the routine expects pointers to 16-bit word aligned strings
** of UTF-16 in the native byte order.
**
** A pointer to the user supplied routine must be passed as the fifth
** argument.  If it is NULL, this is the same as deleting the collation
** sequence (so that SQLite cannot call it anymore).
** Each time the application supplied function is invoked, it is passed
** as its first parameter a copy of the void* passed as the fourth argument
** to sqlite3_create_collation() or sqlite3_create_collation16().
**
** The remaining arguments to the application-supplied routine are two strings,
** each represented by a (length, data) pair and encoded in the encoding
** that was passed as the third argument when the collation sequence was
** registered. {END}  The application defined collation routine should
** return negative, zero or positive if the first string is less than,
** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
**
** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
** except that it takes an extra argument which is a destructor for
** the collation.  The destructor is called when the collation is
** destroyed and is passed a copy of the fourth parameter void* pointer
** of the sqlite3_create_collation_v2().
** Collations are destroyed when they are overridden by later calls to the
** collation creation functions or when the [database connection] is closed
** using [sqlite3_close()].
**
** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
**
** Requirements:
** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
** [H16624] [H16627] [H16630]
*/
int sqlite3_create_collation(
  sqlite3*, 
  const char *zName, 
  int eTextRep, 
  void*,
  int(*xCompare)(void*,int,const void*,int,const void*)
);
int sqlite3_create_collation_v2(
  sqlite3*, 
  const char *zName, 
  int eTextRep, 
  void*,
  int(*xCompare)(void*,int,const void*,int,const void*),
  void(*xDestroy)(void*)
);
int sqlite3_create_collation16(
  sqlite3*, 
  const void *zName,
  int eTextRep, 
  void*,
  int(*xCompare)(void*,int,const void*,int,const void*)
);

/*
** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
**
** To avoid having to register all collation sequences before a database
** can be used, a single callback function may be registered with the
** [database connection] to be called whenever an undefined collation
** sequence is required.
**
** If the function is registered using the sqlite3_collation_needed() API,
** then it is passed the names of undefined collation sequences as strings
** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
** the names are passed as UTF-16 in machine native byte order.
** A call to either function replaces any existing callback.
**
** When the callback is invoked, the first argument passed is a copy
** of the second argument to sqlite3_collation_needed() or
** sqlite3_collation_needed16().  The second argument is the database
** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
** sequence function required.  The fourth parameter is the name of the
** required collation sequence.
**
** The callback function should register the desired collation using
** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
** [sqlite3_create_collation_v2()].
**
** Requirements:
** [H16702] [H16704] [H16706]
*/
int sqlite3_collation_needed(
  sqlite3*, 
  void*, 
  void(*)(void*,sqlite3*,int eTextRep,const char*)
);
int sqlite3_collation_needed16(
  sqlite3*, 
  void*,
  void(*)(void*,sqlite3*,int eTextRep,const void*)
);

/*
** Specify the key for an encrypted database.  This routine should be
** called right after sqlite3_open().
**
** The code to implement this API is not available in the public release
** of SQLite.
*/
int sqlite3_key(
  sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The key */
);

/*
** Change the key on an open database.  If the current database is not
** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
** database is decrypted.
**
** The code to implement this API is not available in the public release
** of SQLite.
*/
int sqlite3_rekey(
  sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The new key */
);

/*
** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
**
** The sqlite3_sleep() function causes the current thread to suspend execution
** for at least a number of milliseconds specified in its parameter.
**
** If the operating system does not support sleep requests with
** millisecond time resolution, then the time will be rounded up to
** the nearest second. The number of milliseconds of sleep actually
** requested from the operating system is returned.
**
** SQLite implements this interface by calling the xSleep()
** method of the default [sqlite3_vfs] object.
**
** Requirements: [H10533] [H10536]
*/
int sqlite3_sleep(int);

/*
** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
**
** If this global variable is made to point to a string which is
** the name of a folder (a.k.a. directory), then all temporary files
** created by SQLite will be placed in that directory.  If this variable
** is a NULL pointer, then SQLite performs a search for an appropriate
** temporary file directory.
**
** It is not safe to read or modify this variable in more than one
** thread at a time.  It is not safe to read or modify this variable
** if a [database connection] is being used at the same time in a separate
** thread.
** It is intended that this variable be set once
** as part of process initialization and before any SQLite interface
** routines have been called and that this variable remain unchanged
** thereafter.
**
** The [temp_store_directory pragma] may modify this variable and cause
** it to point to memory obtained from [sqlite3_malloc].  Furthermore,
** the [temp_store_directory pragma] always assumes that any string
** that this variable points to is held in memory obtained from 
** [sqlite3_malloc] and the pragma may attempt to free that memory
** using [sqlite3_free].
** Hence, if this variable is modified directly, either it should be
** made NULL or made to point to memory obtained from [sqlite3_malloc]
** or else the use of the [temp_store_directory pragma] should be avoided.
*/
SQLITE_EXTERN char *sqlite3_temp_directory;

/*
** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
** KEYWORDS: {autocommit mode}
**
** The sqlite3_get_autocommit() interface returns non-zero or
** zero if the given database connection is or is not in autocommit mode,
** respectively.  Autocommit mode is on by default.
** Autocommit mode is disabled by a [BEGIN] statement.
** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
**
** If certain kinds of errors occur on a statement within a multi-statement
** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
** transaction might be rolled back automatically.  The only way to
** find out whether SQLite automatically rolled back the transaction after
** an error is to use this function.
**
** If another thread changes the autocommit status of the database
** connection while this routine is running, then the return value
** is undefined.
**
** Requirements: [H12931] [H12932] [H12933] [H12934]
*/
int sqlite3_get_autocommit(sqlite3*);

/*
** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
**
** The sqlite3_db_handle interface returns the [database connection] handle
** to which a [prepared statement] belongs.  The [database connection]
** returned by sqlite3_db_handle is the same [database connection] that was the first argument
** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
** create the statement in the first place.
**
** Requirements: [H13123]
*/
sqlite3 *sqlite3_db_handle(sqlite3_stmt*);

/*
** CAPI3REF: Find the next prepared statement {H13140} <S60600>
**
** This interface returns a pointer to the next [prepared statement] after
** pStmt associated with the [database connection] pDb.  If pStmt is NULL
** then this interface returns a pointer to the first prepared statement
** associated with the database connection pDb.  If no prepared statement
** satisfies the conditions of this routine, it returns NULL.
**
** The [database connection] pointer D in a call to
** [sqlite3_next_stmt(D,S)] must refer to an open database
** connection and in particular must not be a NULL pointer.
**
** Requirements: [H13143] [H13146] [H13149] [H13152]
*/
sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);

/*
** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
**
** The sqlite3_commit_hook() interface registers a callback
** function to be invoked whenever a transaction is [COMMIT | committed].
** Any callback set by a previous call to sqlite3_commit_hook()
** for the same database connection is overridden.
** The sqlite3_rollback_hook() interface registers a callback
** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
** Any callback set by a previous call to sqlite3_commit_hook()
** for the same database connection is overridden.
** The pArg argument is passed through to the callback.
** If the callback on a commit hook function returns non-zero,
** then the commit is converted into a rollback.
**
** If another function was previously registered, its
** pArg value is returned.  Otherwise NULL is returned.
**
** The callback implementation must not do anything that will modify
** the database connection that invoked the callback.  Any actions
** to modify the database connection must be deferred until after the
** completion of the [sqlite3_step()] call that triggered the commit
** or rollback hook in the first place.
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
** database connections for the meaning of "modify" in this paragraph.
**
** Registering a NULL function disables the callback.
**
** When the commit hook callback routine returns zero, the [COMMIT]
** operation is allowed to continue normally.  If the commit hook
** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
** The rollback hook is invoked on a rollback that results from a commit
** hook returning non-zero, just as it would be with any other rollback.
**
** For the purposes of this API, a transaction is said to have been
** rolled back if an explicit "ROLLBACK" statement is executed, or
** an error or constraint causes an implicit rollback to occur.
** The rollback callback is not invoked if a transaction is
** automatically rolled back because the database connection is closed.
** The rollback callback is not invoked if a transaction is
** rolled back because a commit callback returned non-zero.
** <todo> Check on this </todo>
**
** See also the [sqlite3_update_hook()] interface.
**
** Requirements:
** [H12951] [H12952] [H12953] [H12954] [H12955]
** [H12961] [H12962] [H12963] [H12964]
*/
void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);

/*
** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
**
** The sqlite3_update_hook() interface registers a callback function
** with the [database connection] identified by the first argument
** to be invoked whenever a row is updated, inserted or deleted.
** Any callback set by a previous call to this function
** for the same database connection is overridden.
**
** The second argument is a pointer to the function to invoke when a
** row is updated, inserted or deleted.
** The first argument to the callback is a copy of the third argument
** to sqlite3_update_hook().
** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
** or [SQLITE_UPDATE], depending on the operation that caused the callback
** to be invoked.
** The third and fourth arguments to the callback contain pointers to the
** database and table name containing the affected row.
** The final callback parameter is the [rowid] of the row.
** In the case of an update, this is the [rowid] after the update takes place.
**
** The update hook is not invoked when internal system tables are
** modified (i.e. sqlite_master and sqlite_sequence).
**
** In the current implementation, the update hook
** is not invoked when duplication rows are deleted because of an
** [ON CONFLICT | ON CONFLICT REPLACE] clause.  Nor is the update hook
** invoked when rows are deleted using the [truncate optimization].
** The exceptions defined in this paragraph might change in a future
** release of SQLite.
**
** The update hook implementation must not do anything that will modify
** the database connection that invoked the update hook.  Any actions
** to modify the database connection must be deferred until after the
** completion of the [sqlite3_step()] call that triggered the update hook.
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
** database connections for the meaning of "modify" in this paragraph.
**
** If another function was previously registered, its pArg value
** is returned.  Otherwise NULL is returned.
**
** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
** interfaces.
**
** Requirements:
** [H12971] [H12973] [H12975] [H12977] [H12979] [H12981] [H12983] [H12986]
*/
void *sqlite3_update_hook(
  sqlite3*, 
  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  void*
);

/*
** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
** KEYWORDS: {shared cache}
**
** This routine enables or disables the sharing of the database cache
** and schema data structures between [database connection | connections]
** to the same database. Sharing is enabled if the argument is true
** and disabled if the argument is false.
**
** Cache sharing is enabled and disabled for an entire process.
** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
** sharing was enabled or disabled for each thread separately.
**
** The cache sharing mode set by this interface effects all subsequent
** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
** Existing database connections continue use the sharing mode
** that was in effect at the time they were opened.
**
** Virtual tables cannot be used with a shared cache.  When shared
** cache is enabled, the [sqlite3_create_module()] API used to register
** virtual tables will always return an error.
**
** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
** successfully.  An [error code] is returned otherwise.
**
** Shared cache is disabled by default. But this might change in
** future releases of SQLite.  Applications that care about shared
** cache setting should set it explicitly.
**
** See Also:  [SQLite Shared-Cache Mode]
**
** Requirements: [H10331] [H10336] [H10337] [H10339]
*/
int sqlite3_enable_shared_cache(int);

/*
** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
**
** The sqlite3_release_memory() interface attempts to free N bytes
** of heap memory by deallocating non-essential memory allocations
** held by the database library. {END}  Memory used to cache database
** pages to improve performance is an example of non-essential memory.
** sqlite3_release_memory() returns the number of bytes actually freed,
** which might be more or less than the amount requested.
**
** Requirements: [H17341] [H17342]
*/
int sqlite3_release_memory(int);

/*
** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
**
** The sqlite3_soft_heap_limit() interface places a "soft" limit
** on the amount of heap memory that may be allocated by SQLite.
** If an internal allocation is requested that would exceed the
** soft heap limit, [sqlite3_release_memory()] is invoked one or
** more times to free up some space before the allocation is performed.
**
** The limit is called "soft", because if [sqlite3_release_memory()]
** cannot free sufficient memory to prevent the limit from being exceeded,
** the memory is allocated anyway and the current operation proceeds.
**
** A negative or zero value for N means that there is no soft heap limit and
** [sqlite3_release_memory()] will only be called when memory is exhausted.
** The default value for the soft heap limit is zero.
**
** SQLite makes a best effort to honor the soft heap limit.
** But if the soft heap limit cannot be honored, execution will
** continue without error or notification.  This is why the limit is
** called a "soft" limit.  It is advisory only.
**
** Prior to SQLite version 3.5.0, this routine only constrained the memory
** allocated by a single thread - the same thread in which this routine
** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
** applied to all threads. The value specified for the soft heap limit
** is an upper bound on the total memory allocation for all threads. In
** version 3.5.0 there is no mechanism for limiting the heap usage for
** individual threads.
**
** Requirements:
** [H16351] [H16352] [H16353] [H16354] [H16355] [H16358]
*/
void sqlite3_soft_heap_limit(int);

/*
** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
**
** This routine returns metadata about a specific column of a specific
** database table accessible using the [database connection] handle
** passed as the first function argument.
**
** The column is identified by the second, third and fourth parameters to
** this function. The second parameter is either the name of the database
** (i.e. "main", "temp" or an attached database) containing the specified
** table or NULL. If it is NULL, then all attached databases are searched
** for the table using the same algorithm used by the database engine to
** resolve unqualified table references.
**
** The third and fourth parameters to this function are the table and column
** name of the desired column, respectively. Neither of these parameters
** may be NULL.
**
** Metadata is returned by writing to the memory locations passed as the 5th
** and subsequent parameters to this function. Any of these arguments may be
** NULL, in which case the corresponding element of metadata is omitted.
**
** <blockquote>
** <table border="1">
** <tr><th> Parameter <th> Output<br>Type <th>  Description
**
** <tr><td> 5th <td> const char* <td> Data type
** <tr><td> 6th <td> const char* <td> Name of default collation sequence
** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
** </table>
** </blockquote>
**
** The memory pointed to by the character pointers returned for the
** declaration type and collation sequence is valid only until the next
** call to any SQLite API function.
**
** If the specified table is actually a view, an [error code] is returned.
**
** If the specified column is "rowid", "oid" or "_rowid_" and an
** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
** parameters are set for the explicitly declared column. If there is no
** explicitly declared [INTEGER PRIMARY KEY] column, then the output
** parameters are set as follows:
**
** <pre>
**     data type: "INTEGER"
**     collation sequence: "BINARY"
**     not null: 0
**     primary key: 1
**     auto increment: 0
** </pre>
**
** This function may load one or more schemas from database files. If an
** error occurs during this process, or if the requested table or column
** cannot be found, an [error code] is returned and an error message left
** in the [database connection] (to be retrieved using sqlite3_errmsg()).
**
** This API is only available if the library was compiled with the
** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
*/
int sqlite3_table_column_metadata(
  sqlite3 *db,                /* Connection handle */
  const char *zDbName,        /* Database name or NULL */
  const char *zTableName,     /* Table name */
  const char *zColumnName,    /* Column name */
  char const **pzDataType,    /* OUTPUT: Declared data type */
  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
);

/*
** CAPI3REF: Load An Extension {H12600} <S20500>
**
** This interface loads an SQLite extension library from the named file.
**
** {H12601} The sqlite3_load_extension() interface attempts to load an
**          SQLite extension library contained in the file zFile.
**
** {H12602} The entry point is zProc.
**
** {H12603} zProc may be 0, in which case the name of the entry point
**          defaults to "sqlite3_extension_init".
**
** {H12604} The sqlite3_load_extension() interface shall return
**          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
**
** {H12605} If an error occurs and pzErrMsg is not 0, then the
**          [sqlite3_load_extension()] interface shall attempt to
**          fill *pzErrMsg with error message text stored in memory
**          obtained from [sqlite3_malloc()]. {END}  The calling function
**          should free this memory by calling [sqlite3_free()].
**
** {H12606} Extension loading must be enabled using
**          [sqlite3_enable_load_extension()] prior to calling this API,
**          otherwise an error will be returned.
*/
int sqlite3_load_extension(
  sqlite3 *db,          /* Load the extension into this database connection */
  const char *zFile,    /* Name of the shared library containing extension */
  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
  char **pzErrMsg       /* Put error message here if not 0 */
);

/*
** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
**
** So as not to open security holes in older applications that are
** unprepared to deal with extension loading, and as a means of disabling
** extension loading while evaluating user-entered SQL, the following API
** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
**
** Extension loading is off by default. See ticket #1863.
**
** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
**          to turn extension loading on and call it with onoff==0 to turn
**          it back off again.
**
** {H12622} Extension loading is off by default.
*/
int sqlite3_enable_load_extension(sqlite3 *db, int onoff);

/*
** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
**
** This API can be invoked at program startup in order to register
** one or more statically linked extensions that will be available
** to all new [database connections]. {END}
**
** This routine stores a pointer to the extension in an array that is
** obtained from [sqlite3_malloc()].  If you run a memory leak checker
** on your program and it reports a leak because of this array, invoke
** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
**
** {H12641} This function registers an extension entry point that is
**          automatically invoked whenever a new [database connection]
**          is opened using [sqlite3_open()], [sqlite3_open16()],
**          or [sqlite3_open_v2()].
**
** {H12642} Duplicate extensions are detected so calling this routine
**          multiple times with the same extension is harmless.
**
** {H12643} This routine stores a pointer to the extension in an array
**          that is obtained from [sqlite3_malloc()].
**
** {H12644} Automatic extensions apply across all threads.
*/
int sqlite3_auto_extension(void (*xEntryPoint)(void));

/*
** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
**
** This function disables all previously registered automatic
** extensions. {END}  It undoes the effect of all prior
** [sqlite3_auto_extension()] calls.
**
** {H12661} This function disables all previously registered
**          automatic extensions.
**
** {H12662} This function disables automatic extensions in all threads.
*/
void sqlite3_reset_auto_extension(void);

/*
****** EXPERIMENTAL - subject to change without notice **************
**
** The interface to the virtual-table mechanism is currently considered
** to be experimental.  The interface might change in incompatible ways.
** If this is a problem for you, do not use the interface at this time.
**
** When the virtual-table mechanism stabilizes, we will declare the
** interface fixed, support it indefinitely, and remove this comment.
*/

/*
** Structures used by the virtual table interface
*/
typedef struct sqlite3_vtab sqlite3_vtab;
typedef struct sqlite3_index_info sqlite3_index_info;
typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
typedef struct sqlite3_module sqlite3_module;

/*
** CAPI3REF: Virtual Table Object {H18000} <S20400>
** KEYWORDS: sqlite3_module {virtual table module}
** EXPERIMENTAL
**
** This structure, sometimes called a a "virtual table module", 
** defines the implementation of a [virtual tables].  
** This structure consists mostly of methods for the module.
**
** A virtual table module is created by filling in a persistent
** instance of this structure and passing a pointer to that instance
** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
** The registration remains valid until it is replaced by a different
** module or until the [database connection] closes.  The content
** of this structure must not change while it is registered with
** any database connection.
*/
struct sqlite3_module {
  int iVersion;
  int (*xCreate)(sqlite3*, void *pAux,
               int argc, const char *const*argv,
               sqlite3_vtab **ppVTab, char**);
  int (*xConnect)(sqlite3*, void *pAux,
               int argc, const char *const*argv,
               sqlite3_vtab **ppVTab, char**);
  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  int (*xDisconnect)(sqlite3_vtab *pVTab);
  int (*xDestroy)(sqlite3_vtab *pVTab);
  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  int (*xClose)(sqlite3_vtab_cursor*);
  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
                int argc, sqlite3_value **argv);
  int (*xNext)(sqlite3_vtab_cursor*);
  int (*xEof)(sqlite3_vtab_cursor*);
  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  int (*xBegin)(sqlite3_vtab *pVTab);
  int (*xSync)(sqlite3_vtab *pVTab);
  int (*xCommit)(sqlite3_vtab *pVTab);
  int (*xRollback)(sqlite3_vtab *pVTab);
  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
                       void **ppArg);
  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
};

/*
** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
** KEYWORDS: sqlite3_index_info
** EXPERIMENTAL
**
** The sqlite3_index_info structure and its substructures is used to
** pass information into and receive the reply from the [xBestIndex]
** method of a [virtual table module].  The fields under **Inputs** are the
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
** results into the **Outputs** fields.
**
** The aConstraint[] array records WHERE clause constraints of the form:
**
** <pre>column OP expr</pre>
**
** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  The particular operator is
** stored in aConstraint[].op.  The index of the column is stored in
** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
** expr on the right-hand side can be evaluated (and thus the constraint
** is usable) and false if it cannot.
**
** The optimizer automatically inverts terms of the form "expr OP column"
** and makes other simplifications to the WHERE clause in an attempt to
** get as many WHERE clause terms into the form shown above as possible.
** The aConstraint[] array only reports WHERE clause terms in the correct
** form that refer to the particular virtual table being queried.
**
** Information about the ORDER BY clause is stored in aOrderBy[].
** Each term of aOrderBy records a column of the ORDER BY clause.
**
** The [xBestIndex] method must fill aConstraintUsage[] with information
** about what parameters to pass to xFilter.  If argvIndex>0 then
** the right-hand side of the corresponding aConstraint[] is evaluated
** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
** is true, then the constraint is assumed to be fully handled by the
** virtual table and is not checked again by SQLite.
**
** The idxNum and idxPtr values are recorded and passed into the
** [xFilter] method.
** [sqlite3_free()] is used to free idxPtr if and only iff
** needToFreeIdxPtr is true.
**
** The orderByConsumed means that output from [xFilter]/[xNext] will occur in
** the correct order to satisfy the ORDER BY clause so that no separate
** sorting step is required.
**
** The estimatedCost value is an estimate of the cost of doing the
** particular lookup.  A full scan of a table with N entries should have
** a cost of N.  A binary search of a table of N entries should have a
** cost of approximately log(N).
*/
struct sqlite3_index_info {
  /* Inputs */
  int nConstraint;           /* Number of entries in aConstraint */
  struct sqlite3_index_constraint {
     int iColumn;              /* Column on left-hand side of constraint */
     unsigned char op;         /* Constraint operator */
     unsigned char usable;     /* True if this constraint is usable */
     int iTermOffset;          /* Used internally - xBestIndex should ignore */
  } *aConstraint;            /* Table of WHERE clause constraints */
  int nOrderBy;              /* Number of terms in the ORDER BY clause */
  struct sqlite3_index_orderby {
     int iColumn;              /* Column number */
     unsigned char desc;       /* True for DESC.  False for ASC. */
  } *aOrderBy;               /* The ORDER BY clause */
  /* Outputs */
  struct sqlite3_index_constraint_usage {
    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
    unsigned char omit;      /* Do not code a test for this constraint */
  } *aConstraintUsage;
  int idxNum;                /* Number used to identify the index */
  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
  int orderByConsumed;       /* True if output is already ordered */
  double estimatedCost;      /* Estimated cost of using this index */
};
#define SQLITE_INDEX_CONSTRAINT_EQ    2
#define SQLITE_INDEX_CONSTRAINT_GT    4
#define SQLITE_INDEX_CONSTRAINT_LE    8
#define SQLITE_INDEX_CONSTRAINT_LT    16
#define SQLITE_INDEX_CONSTRAINT_GE    32
#define SQLITE_INDEX_CONSTRAINT_MATCH 64

/*
** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
** EXPERIMENTAL
**
** This routine is used to register a new [virtual table module] name.
** Module names must be registered before
** creating a new [virtual table] using the module, or before using a
** preexisting [virtual table] for the module.
**
** The module name is registered on the [database connection] specified
** by the first parameter.  The name of the module is given by the 
** second parameter.  The third parameter is a pointer to
** the implementation of the [virtual table module].   The fourth
** parameter is an arbitrary client data pointer that is passed through
** into the [xCreate] and [xConnect] methods of the virtual table module
** when a new virtual table is be being created or reinitialized.
**
** This interface has exactly the same effect as calling
** [sqlite3_create_module_v2()] with a NULL client data destructor.
*/
SQLITE_EXPERIMENTAL int sqlite3_create_module(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *p,   /* Methods for the module */
  void *pClientData          /* Client data for xCreate/xConnect */
);

/*
** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
** EXPERIMENTAL
**
** This routine is identical to the [sqlite3_create_module()] method,
** except that it has an extra parameter to specify 
** a destructor function for the client data pointer.  SQLite will
** invoke the destructor function (if it is not NULL) when SQLite
** no longer needs the pClientData pointer.  
*/
SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *p,   /* Methods for the module */
  void *pClientData,         /* Client data for xCreate/xConnect */
  void(*xDestroy)(void*)     /* Module destructor function */
);

/*
** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
** KEYWORDS: sqlite3_vtab
** EXPERIMENTAL
**
** Every [virtual table module] implementation uses a subclass
** of the following structure to describe a particular instance
** of the [virtual table].  Each subclass will
** be tailored to the specific needs of the module implementation.
** The purpose of this superclass is to define certain fields that are
** common to all module implementations.
**
** Virtual tables methods can set an error message by assigning a
** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
** take care that any prior string is freed by a call to [sqlite3_free()]
** prior to assigning a new string to zErrMsg.  After the error message
** is delivered up to the client application, the string will be automatically
** freed by sqlite3_free() and the zErrMsg field will be zeroed.
*/
struct sqlite3_vtab {
  const sqlite3_module *pModule;  /* The module for this virtual table */
  int nRef;                       /* NO LONGER USED */
  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
  /* Virtual table implementations will typically add additional fields */
};

/*
** CAPI3REF: Virtual Table Cursor Object  {H18020} <S20400>
** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
** EXPERIMENTAL
**
** Every [virtual table module] implementation uses a subclass of the
** following structure to describe cursors that point into the
** [virtual table] and are used
** to loop through the virtual table.  Cursors are created using the
** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
** by the [sqlite3_module.xClose | xClose] method.  Cussors are used
** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
** of the module.  Each module implementation will define
** the content of a cursor structure to suit its own needs.
**
** This superclass exists in order to define fields of the cursor that
** are common to all implementations.
*/
struct sqlite3_vtab_cursor {
  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
  /* Virtual table implementations will typically add additional fields */
};

/*
** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
** EXPERIMENTAL
**
** The [xCreate] and [xConnect] methods of a
** [virtual table module] call this interface
** to declare the format (the names and datatypes of the columns) of
** the virtual tables they implement.
*/
SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);

/*
** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
** EXPERIMENTAL
**
** Virtual tables can provide alternative implementations of functions
** using the [xFindFunction] method of the [virtual table module].  
** But global versions of those functions
** must exist in order to be overloaded.
**
** This API makes sure a global version of a function with a particular
** name and number of parameters exists.  If no such function exists
** before this API is called, a new function is created.  The implementation
** of the new function always causes an exception to be thrown.  So
** the new function is not good for anything by itself.  Its only
** purpose is to be a placeholder function that can be overloaded
** by a [virtual table].
*/
SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);

/*
** The interface to the virtual-table mechanism defined above (back up
** to a comment remarkably similar to this one) is currently considered
** to be experimental.  The interface might change in incompatible ways.
** If this is a problem for you, do not use the interface at this time.
**
** When the virtual-table mechanism stabilizes, we will declare the
** interface fixed, support it indefinitely, and remove this comment.
**
****** EXPERIMENTAL - subject to change without notice **************
*/

/*
** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
** KEYWORDS: {BLOB handle} {BLOB handles}
**
** An instance of this object represents an open BLOB on which
** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
** Objects of this type are created by [sqlite3_blob_open()]
** and destroyed by [sqlite3_blob_close()].
** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
** can be used to read or write small subsections of the BLOB.
** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
*/
typedef struct sqlite3_blob sqlite3_blob;

/*
** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
**
** This interfaces opens a [BLOB handle | handle] to the BLOB located
** in row iRow, column zColumn, table zTable in database zDb;
** in other words, the same BLOB that would be selected by:
**
** <pre>
**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
** </pre> {END}
**
** If the flags parameter is non-zero, then the BLOB is opened for read
** and write access. If it is zero, the BLOB is opened for read access.
** It is not possible to open a column that is part of an index or primary 
** key for writing. ^If [foreign key constraints] are enabled, it is 
** not possible to open a column that is part of a [child key] for writing.
**
** Note that the database name is not the filename that contains
** the database but rather the symbolic name of the database that
** is assigned when the database is connected using [ATTACH].
** For the main database file, the database name is "main".
** For TEMP tables, the database name is "temp".
**
** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
** to be a null pointer.
** This function sets the [database connection] error code and message
** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
** functions.  Note that the *ppBlob variable is always initialized in a
** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
** regardless of the success or failure of this routine.
**
** If the row that a BLOB handle points to is modified by an
** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
** then the BLOB handle is marked as "expired".
** This is true if any column of the row is changed, even a column
** other than the one the BLOB handle is open on.
** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
** Changes written into a BLOB prior to the BLOB expiring are not
** rollback by the expiration of the BLOB.  Such changes will eventually
** commit if the transaction continues to completion.
**
** Use the [sqlite3_blob_bytes()] interface to determine the size of
** the opened blob.  The size of a blob may not be changed by this
** interface.  Use the [UPDATE] SQL command to change the size of a
** blob.
**
** The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
** and the built-in [zeroblob] SQL function can be used, if desired,
** to create an empty, zero-filled blob in which to read or write using
** this interface.
**
** To avoid a resource leak, every open [BLOB handle] should eventually
** be released by a call to [sqlite3_blob_close()].
**
** Requirements:
** [H17813] [H17814] [H17816] [H17819] [H17821] [H17824]
*/
int sqlite3_blob_open(
  sqlite3*,
  const char *zDb,
  const char *zTable,
  const char *zColumn,
  sqlite3_int64 iRow,
  int flags,
  sqlite3_blob **ppBlob
);

/*
** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
**
** Closes an open [BLOB handle].
**
** Closing a BLOB shall cause the current transaction to commit
** if there are no other BLOBs, no pending prepared statements, and the
** database connection is in [autocommit mode].
** If any writes were made to the BLOB, they might be held in cache
** until the close operation if they will fit.
**
** Closing the BLOB often forces the changes
** out to disk and so if any I/O errors occur, they will likely occur
** at the time when the BLOB is closed.  Any errors that occur during
** closing are reported as a non-zero return value.
**
** The BLOB is closed unconditionally.  Even if this routine returns
** an error code, the BLOB is still closed.
**
** Calling this routine with a null pointer (which as would be returned
** by failed call to [sqlite3_blob_open()]) is a harmless no-op.
**
** Requirements:
** [H17833] [H17836] [H17839]
*/
int sqlite3_blob_close(sqlite3_blob *);

/*
** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
**
** Returns the size in bytes of the BLOB accessible via the 
** successfully opened [BLOB handle] in its only argument.  The
** incremental blob I/O routines can only read or overwriting existing
** blob content; they cannot change the size of a blob.
**
** This routine only works on a [BLOB handle] which has been created
** by a prior successful call to [sqlite3_blob_open()] and which has not
** been closed by [sqlite3_blob_close()].  Passing any other pointer in
** to this routine results in undefined and probably undesirable behavior.
**
** Requirements:
** [H17843]
*/
int sqlite3_blob_bytes(sqlite3_blob *);

/*
** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
**
** This function is used to read data from an open [BLOB handle] into a
** caller-supplied buffer. N bytes of data are copied into buffer Z
** from the open BLOB, starting at offset iOffset.
**
** If offset iOffset is less than N bytes from the end of the BLOB,
** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
** less than zero, [SQLITE_ERROR] is returned and no data is read.
** The size of the blob (and hence the maximum value of N+iOffset)
** can be determined using the [sqlite3_blob_bytes()] interface.
**
** An attempt to read from an expired [BLOB handle] fails with an
** error code of [SQLITE_ABORT].
**
** On success, SQLITE_OK is returned.
** Otherwise, an [error code] or an [extended error code] is returned.
**
** This routine only works on a [BLOB handle] which has been created
** by a prior successful call to [sqlite3_blob_open()] and which has not
** been closed by [sqlite3_blob_close()].  Passing any other pointer in
** to this routine results in undefined and probably undesirable behavior.
**
** See also: [sqlite3_blob_write()].
**
** Requirements:
** [H17853] [H17856] [H17859] [H17862] [H17863] [H17865] [H17868]
*/
int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);

/*
** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
**
** This function is used to write data into an open [BLOB handle] from a
** caller-supplied buffer. N bytes of data are copied from the buffer Z
** into the open BLOB, starting at offset iOffset.
**
** If the [BLOB handle] passed as the first argument was not opened for
** writing (the flags parameter to [sqlite3_blob_open()] was zero),
** this function returns [SQLITE_READONLY].
**
** This function may only modify the contents of the BLOB; it is
** not possible to increase the size of a BLOB using this API.
** If offset iOffset is less than N bytes from the end of the BLOB,
** [SQLITE_ERROR] is returned and no data is written.  If N is
** less than zero [SQLITE_ERROR] is returned and no data is written.
** The size of the BLOB (and hence the maximum value of N+iOffset)
** can be determined using the [sqlite3_blob_bytes()] interface.
**
** An attempt to write to an expired [BLOB handle] fails with an
** error code of [SQLITE_ABORT].  Writes to the BLOB that occurred
** before the [BLOB handle] expired are not rolled back by the
** expiration of the handle, though of course those changes might
** have been overwritten by the statement that expired the BLOB handle
** or by other independent statements.
**
** On success, SQLITE_OK is returned.
** Otherwise, an  [error code] or an [extended error code] is returned.
**
** This routine only works on a [BLOB handle] which has been created
** by a prior successful call to [sqlite3_blob_open()] and which has not
** been closed by [sqlite3_blob_close()].  Passing any other pointer in
** to this routine results in undefined and probably undesirable behavior.
**
** See also: [sqlite3_blob_read()].
**
** Requirements:
** [H17873] [H17874] [H17875] [H17876] [H17877] [H17879] [H17882] [H17885]
** [H17888]
*/
int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);

/*
** CAPI3REF: Virtual File System Objects {H11200} <S20100>
**
** A virtual filesystem (VFS) is an [sqlite3_vfs] object
** that SQLite uses to interact
** with the underlying operating system.  Most SQLite builds come with a
** single default VFS that is appropriate for the host computer.
** New VFSes can be registered and existing VFSes can be unregistered.
** The following interfaces are provided.
**
** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
** Names are case sensitive.
** Names are zero-terminated UTF-8 strings.
** If there is no match, a NULL pointer is returned.
** If zVfsName is NULL then the default VFS is returned.
**
** New VFSes are registered with sqlite3_vfs_register().
** Each new VFS becomes the default VFS if the makeDflt flag is set.
** The same VFS can be registered multiple times without injury.
** To make an existing VFS into the default VFS, register it again
** with the makeDflt flag set.  If two different VFSes with the
** same name are registered, the behavior is undefined.  If a
** VFS is registered with a name that is NULL or an empty string,
** then the behavior is undefined.
**
** Unregister a VFS with the sqlite3_vfs_unregister() interface.
** If the default VFS is unregistered, another VFS is chosen as
** the default.  The choice for the new VFS is arbitrary.
**
** Requirements:
** [H11203] [H11206] [H11209] [H11212] [H11215] [H11218]
*/
sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
int sqlite3_vfs_unregister(sqlite3_vfs*);

/*
** CAPI3REF: Mutexes {H17000} <S20000>
**
** The SQLite core uses these routines for thread
** synchronization. Though they are intended for internal
** use by SQLite, code that links against SQLite is
** permitted to use any of these routines.
**
** The SQLite source code contains multiple implementations
** of these mutex routines.  An appropriate implementation
** is selected automatically at compile-time.  The following
** implementations are available in the SQLite core:
**
** <ul>
** <li>   SQLITE_MUTEX_OS2
** <li>   SQLITE_MUTEX_PTHREAD
** <li>   SQLITE_MUTEX_W32
** <li>   SQLITE_MUTEX_NOOP
** </ul>
**
** The SQLITE_MUTEX_NOOP implementation is a set of routines
** that does no real locking and is appropriate for use in
** a single-threaded application.  The SQLITE_MUTEX_OS2,
** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
** are appropriate for use on OS/2, Unix, and Windows.
**
** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
** implementation is included with the library. In this case the
** application must supply a custom mutex implementation using the
** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
** before calling sqlite3_initialize() or any other public sqlite3_
** function that calls sqlite3_initialize().
**
** {H17011} The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it. {H17012} If it returns NULL
** that means that a mutex could not be allocated. {H17013} SQLite
** will unwind its stack and return an error. {H17014} The argument
** to sqlite3_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li>  SQLITE_MUTEX_FAST
** <li>  SQLITE_MUTEX_RECURSIVE
** <li>  SQLITE_MUTEX_STATIC_MASTER
** <li>  SQLITE_MUTEX_STATIC_MEM
** <li>  SQLITE_MUTEX_STATIC_MEM2
** <li>  SQLITE_MUTEX_STATIC_PRNG
** <li>  SQLITE_MUTEX_STATIC_LRU
** <li>  SQLITE_MUTEX_STATIC_LRU2
** </ul>
**
** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to.  {H17016} But SQLite will only request a recursive mutex in
** cases where it really needs one.  {END} If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
** a pointer to a static preexisting mutex. {END}  Six static mutexes are
** used by the current version of SQLite.  Future versions of SQLite
** may add additional static mutexes.  Static mutexes are for internal
** use by SQLite only.  Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
** returns a different mutex on every call.  {H17034} But for the static
** mutex types, the same mutex is returned on every call that has
** the same type number.
**
** {H17019} The sqlite3_mutex_free() routine deallocates a previously
** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
** use when they are deallocated. {A17022} Attempting to deallocate a static
** mutex results in undefined behavior. {H17023} SQLite never deallocates
** a static mutex. {END}
**
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex. {H17024} If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY. {H17025}  The sqlite3_mutex_try() interface returns [SQLITE_OK]
** upon successful entry.  {H17026} Mutexes created using
** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
** {H17027} In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  {A17028} If the same thread tries to enter any other
** kind of mutex more than once, the behavior is undefined.
** {H17029} SQLite will never exhibit
** such behavior in its own use of mutexes.
**
** Some systems (for example, Windows 95) do not support the operation
** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
** will always return SQLITE_BUSY.  {H17030} The SQLite core only ever uses
** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
**
** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  {A17032} The behavior
** is undefined if the mutex is not currently entered by the
** calling thread or is not currently allocated.  {H17033} SQLite will
** never do either. {END}
**
** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
** sqlite3_mutex_leave() is a NULL pointer, then all three routines
** behave as no-ops.
**
** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
*/
sqlite3_mutex *sqlite3_mutex_alloc(int);
void sqlite3_mutex_free(sqlite3_mutex*);
void sqlite3_mutex_enter(sqlite3_mutex*);
int sqlite3_mutex_try(sqlite3_mutex*);
void sqlite3_mutex_leave(sqlite3_mutex*);

/*
** CAPI3REF: Mutex Methods Object {H17120} <S20130>
** EXPERIMENTAL
**
** An instance of this structure defines the low-level routines
** used to allocate and use mutexes.
**
** Usually, the default mutex implementations provided by SQLite are
** sufficient, however the user has the option of substituting a custom
** implementation for specialized deployments or systems for which SQLite
** does not provide a suitable implementation. In this case, the user
** creates and populates an instance of this structure to pass
** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
** Additionally, an instance of this structure can be used as an
** output variable when querying the system for the current mutex
** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
**
** The xMutexInit method defined by this structure is invoked as
** part of system initialization by the sqlite3_initialize() function.
** {H17001} The xMutexInit routine shall be called by SQLite once for each
** effective call to [sqlite3_initialize()].
**
** The xMutexEnd method defined by this structure is invoked as
** part of system shutdown by the sqlite3_shutdown() function. The
** implementation of this method is expected to release all outstanding
** resources obtained by the mutex methods implementation, especially
** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
** interface shall be invoked once for each call to [sqlite3_shutdown()].
**
** The remaining seven methods defined by this structure (xMutexAlloc,
** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
** xMutexNotheld) implement the following interfaces (respectively):
**
** <ul>
**   <li>  [sqlite3_mutex_alloc()] </li>
**   <li>  [sqlite3_mutex_free()] </li>
**   <li>  [sqlite3_mutex_enter()] </li>
**   <li>  [sqlite3_mutex_try()] </li>
**   <li>  [sqlite3_mutex_leave()] </li>
**   <li>  [sqlite3_mutex_held()] </li>
**   <li>  [sqlite3_mutex_notheld()] </li>
** </ul>
**
** The only difference is that the public sqlite3_XXX functions enumerated
** above silently ignore any invocations that pass a NULL pointer instead
** of a valid mutex handle. The implementations of the methods defined
** by this structure are not required to handle this case, the results
** of passing a NULL pointer instead of a valid mutex handle are undefined
** (i.e. it is acceptable to provide an implementation that segfaults if
** it is passed a NULL pointer).
**
** The xMutexInit() method must be threadsafe.  It must be harmless to
** invoke xMutexInit() mutiple times within the same process and without
** intervening calls to xMutexEnd().  Second and subsequent calls to
** xMutexInit() must be no-ops.
**
** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
** allocation for a static mutex.  However xMutexAlloc() may use SQLite
** memory allocation for a fast or recursive mutex.
**
** SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
** called, but only if the prior call to xMutexInit returned SQLITE_OK.
** If xMutexInit fails in any way, it is expected to clean up after itself
** prior to returning.
*/
typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
struct sqlite3_mutex_methods {
  int (*xMutexInit)(void);
  int (*xMutexEnd)(void);
  sqlite3_mutex *(*xMutexAlloc)(int);
  void (*xMutexFree)(sqlite3_mutex *);
  void (*xMutexEnter)(sqlite3_mutex *);
  int (*xMutexTry)(sqlite3_mutex *);
  void (*xMutexLeave)(sqlite3_mutex *);
  int (*xMutexHeld)(sqlite3_mutex *);
  int (*xMutexNotheld)(sqlite3_mutex *);
};

/*
** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
**
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
** are intended for use inside assert() statements. {H17081} The SQLite core
** never uses these routines except inside an assert() and applications
** are advised to follow the lead of the core.  {H17082} The core only
** provides implementations for these routines when it is compiled
** with the SQLITE_DEBUG flag.  {A17087} External mutex implementations
** are only required to provide these routines if SQLITE_DEBUG is
** defined and if NDEBUG is not defined.
**
** {H17083} These routines should return true if the mutex in their argument
** is held or not held, respectively, by the calling thread.
**
** {X17084} The implementation is not required to provided versions of these
** routines that actually work. If the implementation does not provide working
** versions of these routines, it should at least provide stubs that always
** return true so that one does not get spurious assertion failures.
**
** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
** the routine should return 1.  {END} This seems counter-intuitive since
** clearly the mutex cannot be held if it does not exist.  But the
** the reason the mutex does not exist is because the build is not
** using mutexes.  And we do not want the assert() containing the
** call to sqlite3_mutex_held() to fail, so a non-zero return is
** the appropriate thing to do.  {H17086} The sqlite3_mutex_notheld()
** interface should also return 1 when given a NULL pointer.
*/
int sqlite3_mutex_held(sqlite3_mutex*);
int sqlite3_mutex_notheld(sqlite3_mutex*);

/*
** CAPI3REF: Mutex Types {H17001} <H17000>
**
** The [sqlite3_mutex_alloc()] interface takes a single argument
** which is one of these integer constants.
**
** The set of static mutexes may change from one SQLite release to the
** next.  Applications that override the built-in mutex logic must be
** prepared to accommodate additional static mutexes.
*/
#define SQLITE_MUTEX_FAST             0
#define SQLITE_MUTEX_RECURSIVE        1
#define SQLITE_MUTEX_STATIC_MASTER    2
#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
#define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */

/*
** CAPI3REF: Retrieve the mutex for a database connection {H17002} <H17000>
**
** This interface returns a pointer the [sqlite3_mutex] object that 
** serializes access to the [database connection] given in the argument
** when the [threading mode] is Serialized.
** If the [threading mode] is Single-thread or Multi-thread then this
** routine returns a NULL pointer.
*/
sqlite3_mutex *sqlite3_db_mutex(sqlite3*);

/*
** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
**
** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
** xFileControl method for the [sqlite3_io_methods] object associated
** with a particular database identified by the second argument. {H11302} The
** name of the database is the name assigned to the database by the
** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
** database. {H11303} To control the main database file, use the name "main"
** or a NULL pointer. {H11304} The third and fourth parameters to this routine
** are passed directly through to the second and third parameters of
** the xFileControl method.  {H11305} The return value of the xFileControl
** method becomes the return value of this routine.
**
** {H11306} If the second parameter (zDbName) does not match the name of any
** open database file, then SQLITE_ERROR is returned. {H11307} This error
** code is not remembered and will not be recalled by [sqlite3_errcode()]
** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
** also return SQLITE_ERROR.  {A11309} There is no way to distinguish between
** an incorrect zDbName and an SQLITE_ERROR return from the underlying
** xFileControl method. {END}
**
** See also: [SQLITE_FCNTL_LOCKSTATE]
*/
int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);

/*
** CAPI3REF: Testing Interface {H11400} <S30800>
**
** The sqlite3_test_control() interface is used to read out internal
** state of SQLite and to inject faults into SQLite for testing
** purposes.  The first parameter is an operation code that determines
** the number, meaning, and operation of all subsequent parameters.
**
** This interface is not for use by applications.  It exists solely
** for verifying the correct operation of the SQLite library.  Depending
** on how the SQLite library is compiled, this interface might not exist.
**
** The details of the operation codes, their meanings, the parameters
** they take, and what they do are all subject to change without notice.
** Unlike most of the SQLite API, this function is not guaranteed to
** operate consistently from one release to the next.
*/
int sqlite3_test_control(int op, ...);

/*
** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
**
** These constants are the valid operation code parameters used
** as the first argument to [sqlite3_test_control()].
**
** These parameters and their meanings are subject to change
** without notice.  These values are for testing purposes only.
** Applications should not use any of these parameters or the
** [sqlite3_test_control()] interface.
*/
#define SQLITE_TESTCTRL_PRNG_SAVE                5
#define SQLITE_TESTCTRL_PRNG_RESTORE             6
#define SQLITE_TESTCTRL_PRNG_RESET               7
#define SQLITE_TESTCTRL_BITVEC_TEST              8
#define SQLITE_TESTCTRL_FAULT_INSTALL            9
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
#define SQLITE_TESTCTRL_PENDING_BYTE            11
#define SQLITE_TESTCTRL_ASSERT                  12
#define SQLITE_TESTCTRL_ALWAYS                  13
#define SQLITE_TESTCTRL_RESERVE                 14

/*
** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
** EXPERIMENTAL
**
** This interface is used to retrieve runtime status information
** about the preformance of SQLite, and optionally to reset various
** highwater marks.  The first argument is an integer code for
** the specific parameter to measure.  Recognized integer codes
** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
** The current value of the parameter is returned into *pCurrent.
** The highest recorded value is returned in *pHighwater.  If the
** resetFlag is true, then the highest record value is reset after
** *pHighwater is written. Some parameters do not record the highest
** value.  For those parameters
** nothing is written into *pHighwater and the resetFlag is ignored.
** Other parameters record only the highwater mark and not the current
** value.  For these latter parameters nothing is written into *pCurrent.
**
** This routine returns SQLITE_OK on success and a non-zero
** [error code] on failure.
**
** This routine is threadsafe but is not atomic.  This routine can be
** called while other threads are running the same or different SQLite
** interfaces.  However the values returned in *pCurrent and
** *pHighwater reflect the status of SQLite at different points in time
** and it is possible that another thread might change the parameter
** in between the times when *pCurrent and *pHighwater are written.
**
** See also: [sqlite3_db_status()]
*/
SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);


/*
** CAPI3REF: Status Parameters {H17250} <H17200>
** EXPERIMENTAL
**
** These integer constants designate various run-time status parameters
** that can be returned by [sqlite3_status()].
**
** <dl>
** <dt>SQLITE_STATUS_MEMORY_USED</dt>
** <dd>This parameter is the current amount of memory checked out
** using [sqlite3_malloc()], either directly or indirectly.  The
** figure includes calls made to [sqlite3_malloc()] by the application
** and internal memory usage by the SQLite library.  Scratch memory
** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
** this parameter.  The amount returned is the sum of the allocation
** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
**
** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
** <dd>This parameter records the largest memory allocation request
** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
** internal equivalents).  Only the value returned in the
** *pHighwater parameter to [sqlite3_status()] is of interest.  
** The value written into the *pCurrent parameter is undefined.</dd>
**
** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
** <dd>This parameter returns the number of pages used out of the
** [pagecache memory allocator] that was configured using 
** [SQLITE_CONFIG_PAGECACHE].  The
** value returned is in pages, not in bytes.</dd>
**
** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
** <dd>This parameter returns the number of bytes of page cache
** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
** buffer and where forced to overflow to [sqlite3_malloc()].  The
** returned value includes allocations that overflowed because they
** where too large (they were larger than the "sz" parameter to
** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
** no space was left in the page cache.</dd>
**
** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
** <dd>This parameter records the largest memory allocation request
** handed to [pagecache memory allocator].  Only the value returned in the
** *pHighwater parameter to [sqlite3_status()] is of interest.  
** The value written into the *pCurrent parameter is undefined.</dd>
**
** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
** <dd>This parameter returns the number of allocations used out of the
** [scratch memory allocator] configured using
** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
** in bytes.  Since a single thread may only have one scratch allocation
** outstanding at time, this parameter also reports the number of threads
** using scratch memory at the same time.</dd>
**
** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
** <dd>This parameter returns the number of bytes of scratch memory
** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
** buffer and where forced to overflow to [sqlite3_malloc()].  The values
** returned include overflows because the requested allocation was too
** larger (that is, because the requested allocation was larger than the
** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
** slots were available.
** </dd>
**
** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
** <dd>This parameter records the largest memory allocation request
** handed to [scratch memory allocator].  Only the value returned in the
** *pHighwater parameter to [sqlite3_status()] is of interest.  
** The value written into the *pCurrent parameter is undefined.</dd>
**
** <dt>SQLITE_STATUS_PARSER_STACK</dt>
** <dd>This parameter records the deepest parser stack.  It is only
** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
** </dl>
**
** New status parameters may be added from time to time.
*/
#define SQLITE_STATUS_MEMORY_USED          0
#define SQLITE_STATUS_PAGECACHE_USED       1
#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
#define SQLITE_STATUS_SCRATCH_USED         3
#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
#define SQLITE_STATUS_MALLOC_SIZE          5
#define SQLITE_STATUS_PARSER_STACK         6
#define SQLITE_STATUS_PAGECACHE_SIZE       7
#define SQLITE_STATUS_SCRATCH_SIZE         8

/*
** CAPI3REF: Database Connection Status {H17500} <S60200>
** EXPERIMENTAL
**
** This interface is used to retrieve runtime status information 
** about a single [database connection].  The first argument is the
** database connection object to be interrogated.  The second argument
** is the parameter to interrogate.  Currently, the only allowed value
** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
** Additional options will likely appear in future releases of SQLite.
**
** The current value of the requested parameter is written into *pCur
** and the highest instantaneous value is written into *pHiwtr.  If
** the resetFlg is true, then the highest instantaneous value is
** reset back down to the current value.
**
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
*/
SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);

/*
** CAPI3REF: Status Parameters for database connections {H17520} <H17500>
** EXPERIMENTAL
**
** These constants are the available integer "verbs" that can be passed as
** the second argument to the [sqlite3_db_status()] interface.
**
** New verbs may be added in future releases of SQLite. Existing verbs
** might be discontinued. Applications should check the return code from
** [sqlite3_db_status()] to make sure that the call worked.
** The [sqlite3_db_status()] interface will return a non-zero error code
** if a discontinued or unsupported verb is invoked.
**
** <dl>
** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
** <dd>This parameter returns the number of lookaside memory slots currently
** checked out.</dd>
** </dl>
*/
#define SQLITE_DBSTATUS_LOOKASIDE_USED     0


/*
** CAPI3REF: Prepared Statement Status {H17550} <S60200>
** EXPERIMENTAL
**
** Each prepared statement maintains various
** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
** of times it has performed specific operations.  These counters can
** be used to monitor the performance characteristics of the prepared
** statements.  For example, if the number of table steps greatly exceeds
** the number of table searches or result rows, that would tend to indicate
** that the prepared statement is using a full table scan rather than
** an index.  
**
** This interface is used to retrieve and reset counter values from
** a [prepared statement].  The first argument is the prepared statement
** object to be interrogated.  The second argument
** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
** to be interrogated. 
** The current value of the requested counter is returned.
** If the resetFlg is true, then the counter is reset to zero after this
** interface call returns.
**
** See also: [sqlite3_status()] and [sqlite3_db_status()].
*/
SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);

/*
** CAPI3REF: Status Parameters for prepared statements {H17570} <H17550>
** EXPERIMENTAL
**
** These preprocessor macros define integer codes that name counter
** values associated with the [sqlite3_stmt_status()] interface.
** The meanings of the various counters are as follows:
**
** <dl>
** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
** <dd>This is the number of times that SQLite has stepped forward in
** a table as part of a full table scan.  Large numbers for this counter
** may indicate opportunities for performance improvement through 
** careful use of indices.</dd>
**
** <dt>SQLITE_STMTSTATUS_SORT</dt>
** <dd>This is the number of sort operations that have occurred.
** A non-zero value in this counter may indicate an opportunity to
** improvement performance through careful use of indices.</dd>
**
** </dl>
*/
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
#define SQLITE_STMTSTATUS_SORT              2

/*
** CAPI3REF: Custom Page Cache Object
** EXPERIMENTAL
**
** The sqlite3_pcache type is opaque.  It is implemented by
** the pluggable module.  The SQLite core has no knowledge of
** its size or internal structure and never deals with the
** sqlite3_pcache object except by holding and passing pointers
** to the object.
**
** See [sqlite3_pcache_methods] for additional information.
*/
typedef struct sqlite3_pcache sqlite3_pcache;

/*
** CAPI3REF: Application Defined Page Cache.
** KEYWORDS: {page cache}
** EXPERIMENTAL
**
** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
** register an alternative page cache implementation by passing in an 
** instance of the sqlite3_pcache_methods structure. The majority of the 
** heap memory used by SQLite is used by the page cache to cache data read 
** from, or ready to be written to, the database file. By implementing a 
** custom page cache using this API, an application can control more 
** precisely the amount of memory consumed by SQLite, the way in which 
** that memory is allocated and released, and the policies used to 
** determine exactly which parts of a database file are cached and for 
** how long.
**
** The contents of the sqlite3_pcache_methods structure are copied to an
** internal buffer by SQLite within the call to [sqlite3_config].  Hence
** the application may discard the parameter after the call to
** [sqlite3_config()] returns.
**
** The xInit() method is called once for each call to [sqlite3_initialize()]
** (usually only once during the lifetime of the process). It is passed
** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set
** up global structures and mutexes required by the custom page cache 
** implementation. 
**
** The xShutdown() method is called from within [sqlite3_shutdown()], 
** if the application invokes this API. It can be used to clean up 
** any outstanding resources before process shutdown, if required.
**
** SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
** the xInit method, so the xInit method need not be threadsafe.  The
** xShutdown method is only called from [sqlite3_shutdown()] so it does
** not need to be threadsafe either.  All other methods must be threadsafe
** in multithreaded applications.
**
** SQLite will never invoke xInit() more than once without an intervening
** call to xShutdown().
**
** The xCreate() method is used to construct a new cache instance.  SQLite
** will typically create one cache instance for each open database file,
** though this is not guaranteed. The
** first parameter, szPage, is the size in bytes of the pages that must
** be allocated by the cache.  szPage will not be a power of two.  szPage
** will the page size of the database file that is to be cached plus an
** increment (here called "R") of about 100 or 200.  SQLite will use the
** extra R bytes on each page to store metadata about the underlying
** database page on disk.  The value of R depends
** on the SQLite version, the target platform, and how SQLite was compiled.
** R is constant for a particular build of SQLite.  The second argument to
** xCreate(), bPurgeable, is true if the cache being created will
** be used to cache database pages of a file stored on disk, or
** false if it is used for an in-memory database. The cache implementation
** does not have to do anything special based with the value of bPurgeable;
** it is purely advisory.  On a cache where bPurgeable is false, SQLite will
** never invoke xUnpin() except to deliberately delete a page.
** In other words, a cache created with bPurgeable set to false will
** never contain any unpinned pages.
**
** The xCachesize() method may be called at any time by SQLite to set the
** suggested maximum cache-size (number of pages stored by) the cache
** instance passed as the first argument. This is the value configured using
** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter,
** the implementation is not required to do anything with this
** value; it is advisory only.
**
** The xPagecount() method should return the number of pages currently
** stored in the cache.
** 
** The xFetch() method is used to fetch a page and return a pointer to it. 
** A 'page', in this context, is a buffer of szPage bytes aligned at an
** 8-byte boundary. The page to be fetched is determined by the key. The
** mimimum key value is 1. After it has been retrieved using xFetch, the page 
** is considered to be "pinned".
**
** If the requested page is already in the page cache, then the page cache
** implementation must return a pointer to the page buffer with its content
** intact.  If the requested page is not already in the cache, then the
** behavior of the cache implementation is determined by the value of the
** createFlag parameter passed to xFetch, according to the following table:
**
** <table border=1 width=85% align=center>
** <tr><th> createFlag <th> Behaviour when page is not already in cache
** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
**                 Otherwise return NULL.
** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
**                 NULL if allocating a new page is effectively impossible.
** </table>
**
** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
** attempt to unpin one or more cache pages by spilling the content of
** pinned pages to disk and synching the operating system disk cache. After
** attempting to unpin pages, the xFetch() method will be invoked again with
** a createFlag of 2.
**
** xUnpin() is called by SQLite with a pointer to a currently pinned page
** as its second argument. If the third parameter, discard, is non-zero,
** then the page should be evicted from the cache. In this case SQLite 
** assumes that the next time the page is retrieved from the cache using
** the xFetch() method, it will be zeroed. If the discard parameter is
** zero, then the page is considered to be unpinned. The cache implementation
** may choose to evict unpinned pages at any time.
**
** The cache is not required to perform any reference counting. A single 
** call to xUnpin() unpins the page regardless of the number of prior calls 
** to xFetch().
**
** The xRekey() method is used to change the key value associated with the
** page passed as the second argument from oldKey to newKey. If the cache
** previously contains an entry associated with newKey, it should be
** discarded. Any prior cache entry associated with newKey is guaranteed not
** to be pinned.
**
** When SQLite calls the xTruncate() method, the cache must discard all
** existing cache entries with page numbers (keys) greater than or equal
** to the value of the iLimit parameter passed to xTruncate(). If any
** of these pages are pinned, they are implicitly unpinned, meaning that
** they can be safely discarded.
**
** The xDestroy() method is used to delete a cache allocated by xCreate().
** All resources associated with the specified cache should be freed. After
** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
** handle invalid, and will not use it with any other sqlite3_pcache_methods
** functions.
*/
typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
struct sqlite3_pcache_methods {
  void *pArg;
  int (*xInit)(void*);
  void (*xShutdown)(void*);
  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  int (*xPagecount)(sqlite3_pcache*);
  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  void (*xDestroy)(sqlite3_pcache*);
};

/*
** CAPI3REF: Online Backup Object
** EXPERIMENTAL
**
** The sqlite3_backup object records state information about an ongoing
** online backup operation.  The sqlite3_backup object is created by
** a call to [sqlite3_backup_init()] and is destroyed by a call to
** [sqlite3_backup_finish()].
**
** See Also: [Using the SQLite Online Backup API]
*/
typedef struct sqlite3_backup sqlite3_backup;

/*
** CAPI3REF: Online Backup API.
** EXPERIMENTAL
**
** This API is used to overwrite the contents of one database with that
** of another. It is useful either for creating backups of databases or
** for copying in-memory databases to or from persistent files. 
**
** See Also: [Using the SQLite Online Backup API]
**
** Exclusive access is required to the destination database for the 
** duration of the operation. However the source database is only
** read-locked while it is actually being read, it is not locked
** continuously for the entire operation. Thus, the backup may be
** performed on a live database without preventing other users from
** writing to the database for an extended period of time.
** 
** To perform a backup operation: 
**   <ol>
**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
**         backup, 
**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
**         the data between the two databases, and finally
**     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
**         associated with the backup operation. 
**   </ol>
** There should be exactly one call to sqlite3_backup_finish() for each
** successful call to sqlite3_backup_init().
**
** <b>sqlite3_backup_init()</b>
**
** The first two arguments passed to [sqlite3_backup_init()] are the database
** handle associated with the destination database and the database name 
** used to attach the destination database to the handle. The database name
** is "main" for the main database, "temp" for the temporary database, or
** the name specified as part of the [ATTACH] statement if the destination is
** an attached database. The third and fourth arguments passed to 
** sqlite3_backup_init() identify the [database connection]
** and database name used
** to access the source database. The values passed for the source and 
** destination [database connection] parameters must not be the same.
**
** If an error occurs within sqlite3_backup_init(), then NULL is returned
** and an error code and error message written into the [database connection] 
** passed as the first argument. They may be retrieved using the
** [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] functions.
** Otherwise, if successful, a pointer to an [sqlite3_backup] object is
** returned. This pointer may be used with the sqlite3_backup_step() and
** sqlite3_backup_finish() functions to perform the specified backup 
** operation.
**
** <b>sqlite3_backup_step()</b>
**
** Function [sqlite3_backup_step()] is used to copy up to nPage pages between 
** the source and destination databases, where nPage is the value of the 
** second parameter passed to sqlite3_backup_step(). If nPage is a negative
** value, all remaining source pages are copied. If the required pages are 
** succesfully copied, but there are still more pages to copy before the 
** backup is complete, it returns [SQLITE_OK]. If no error occured and there 
** are no more pages to copy, then [SQLITE_DONE] is returned. If an error 
** occurs, then an SQLite error code is returned. As well as [SQLITE_OK] and
** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
**
** As well as the case where the destination database file was opened for
** read-only access, sqlite3_backup_step() may return [SQLITE_READONLY] if
** the destination is an in-memory database with a different page size
** from the source database.
**
** If sqlite3_backup_step() cannot obtain a required file-system lock, then
** the [sqlite3_busy_handler | busy-handler function]
** is invoked (if one is specified). If the 
** busy-handler returns non-zero before the lock is available, then 
** [SQLITE_BUSY] is returned to the caller. In this case the call to
** sqlite3_backup_step() can be retried later. If the source
** [database connection]
** is being used to write to the source database when sqlite3_backup_step()
** is called, then [SQLITE_LOCKED] is returned immediately. Again, in this
** case the call to sqlite3_backup_step() can be retried later on. If
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
** [SQLITE_READONLY] is returned, then 
** there is no point in retrying the call to sqlite3_backup_step(). These 
** errors are considered fatal. At this point the application must accept 
** that the backup operation has failed and pass the backup operation handle 
** to the sqlite3_backup_finish() to release associated resources.
**
** Following the first call to sqlite3_backup_step(), an exclusive lock is
** obtained on the destination file. It is not released until either 
** sqlite3_backup_finish() is called or the backup operation is complete 
** and sqlite3_backup_step() returns [SQLITE_DONE]. Additionally, each time 
** a call to sqlite3_backup_step() is made a [shared lock] is obtained on
** the source database file. This lock is released before the
** sqlite3_backup_step() call returns. Because the source database is not
** locked between calls to sqlite3_backup_step(), it may be modified mid-way
** through the backup procedure. If the source database is modified by an
** external process or via a database connection other than the one being
** used by the backup operation, then the backup will be transparently
** restarted by the next call to sqlite3_backup_step(). If the source 
** database is modified by the using the same database connection as is used
** by the backup operation, then the backup database is transparently 
** updated at the same time.
**
** <b>sqlite3_backup_finish()</b>
**
** Once sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
** application wishes to abandon the backup operation, the [sqlite3_backup]
** object should be passed to sqlite3_backup_finish(). This releases all
** resources associated with the backup operation. If sqlite3_backup_step()
** has not yet returned [SQLITE_DONE], then any active write-transaction on the
** destination database is rolled back. The [sqlite3_backup] object is invalid
** and may not be used following a call to sqlite3_backup_finish().
**
** The value returned by sqlite3_backup_finish is [SQLITE_OK] if no error
** occurred, regardless or whether or not sqlite3_backup_step() was called
** a sufficient number of times to complete the backup operation. Or, if
** an out-of-memory condition or IO error occured during a call to
** sqlite3_backup_step() then [SQLITE_NOMEM] or an
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] error code
** is returned. In this case the error code and an error message are
** written to the destination [database connection].
**
** A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() is
** not a permanent error and does not affect the return value of
** sqlite3_backup_finish().
**
** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
**
** Each call to sqlite3_backup_step() sets two values stored internally
** by an [sqlite3_backup] object. The number of pages still to be backed
** up, which may be queried by sqlite3_backup_remaining(), and the total
** number of pages in the source database file, which may be queried by
** sqlite3_backup_pagecount().
**
** The values returned by these functions are only updated by
** sqlite3_backup_step(). If the source database is modified during a backup
** operation, then the values are not updated to account for any extra
** pages that need to be updated or the size of the source database file
** changing.
**
** <b>Concurrent Usage of Database Handles</b>
**
** The source [database connection] may be used by the application for other
** purposes while a backup operation is underway or being initialized.
** If SQLite is compiled and configured to support threadsafe database
** connections, then the source database connection may be used concurrently
** from within other threads.
**
** However, the application must guarantee that the destination database
** connection handle is not passed to any other API (by any thread) after 
** sqlite3_backup_init() is called and before the corresponding call to
** sqlite3_backup_finish(). Unfortunately SQLite does not currently check
** for this, if the application does use the destination [database connection]
** for some other purpose during a backup operation, things may appear to
** work correctly but in fact be subtly malfunctioning.  Use of the
** destination database connection while a backup is in progress might
** also cause a mutex deadlock.
**
** Furthermore, if running in [shared cache mode], the application must
** guarantee that the shared cache used by the destination database
** is not accessed while the backup is running. In practice this means
** that the application must guarantee that the file-system file being 
** backed up to is not accessed by any connection within the process,
** not just the specific connection that was passed to sqlite3_backup_init().
**
** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
** threads may safely make multiple concurrent calls to sqlite3_backup_step().
** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
** APIs are not strictly speaking threadsafe. If they are invoked at the
** same time as another thread is invoking sqlite3_backup_step() it is
** possible that they return invalid values.
*/
sqlite3_backup *sqlite3_backup_init(
  sqlite3 *pDest,                        /* Destination database handle */
  const char *zDestName,                 /* Destination database name */
  sqlite3 *pSource,                      /* Source database handle */
  const char *zSourceName                /* Source database name */
);
int sqlite3_backup_step(sqlite3_backup *p, int nPage);
int sqlite3_backup_finish(sqlite3_backup *p);
int sqlite3_backup_remaining(sqlite3_backup *p);
int sqlite3_backup_pagecount(sqlite3_backup *p);

/*
** CAPI3REF: Unlock Notification
** EXPERIMENTAL
**
** When running in shared-cache mode, a database operation may fail with
** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
** individual tables within the shared-cache cannot be obtained. See
** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
** This API may be used to register a callback that SQLite will invoke 
** when the connection currently holding the required lock relinquishes it.
** This API is only available if the library was compiled with the
** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
**
** See Also: [Using the SQLite Unlock Notification Feature].
**
** Shared-cache locks are released when a database connection concludes
** its current transaction, either by committing it or rolling it back. 
**
** When a connection (known as the blocked connection) fails to obtain a
** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
** identity of the database connection (the blocking connection) that
** has locked the required resource is stored internally. After an 
** application receives an SQLITE_LOCKED error, it may call the
** sqlite3_unlock_notify() method with the blocked connection handle as 
** the first argument to register for a callback that will be invoked
** when the blocking connections current transaction is concluded. The
** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
** call that concludes the blocking connections transaction.
**
** If sqlite3_unlock_notify() is called in a multi-threaded application,
** there is a chance that the blocking connection will have already
** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
** If this happens, then the specified callback is invoked immediately,
** from within the call to sqlite3_unlock_notify().
**
** If the blocked connection is attempting to obtain a write-lock on a
** shared-cache table, and more than one other connection currently holds
** a read-lock on the same table, then SQLite arbitrarily selects one of 
** the other connections to use as the blocking connection.
**
** There may be at most one unlock-notify callback registered by a 
** blocked connection. If sqlite3_unlock_notify() is called when the
** blocked connection already has a registered unlock-notify callback,
** then the new callback replaces the old. If sqlite3_unlock_notify() is
** called with a NULL pointer as its second argument, then any existing
** unlock-notify callback is cancelled. The blocked connections 
** unlock-notify callback may also be canceled by closing the blocked
** connection using [sqlite3_close()].
**
** The unlock-notify callback is not reentrant. If an application invokes
** any sqlite3_xxx API functions from within an unlock-notify callback, a
** crash or deadlock may be the result.
**
** Unless deadlock is detected (see below), sqlite3_unlock_notify() always
** returns SQLITE_OK.
**
** <b>Callback Invocation Details</b>
**
** When an unlock-notify callback is registered, the application provides a 
** single void* pointer that is passed to the callback when it is invoked.
** However, the signature of the callback function allows SQLite to pass
** it an array of void* context pointers. The first argument passed to
** an unlock-notify callback is a pointer to an array of void* pointers,
** and the second is the number of entries in the array.
**
** When a blocking connections transaction is concluded, there may be
** more than one blocked connection that has registered for an unlock-notify
** callback. If two or more such blocked connections have specified the
** same callback function, then instead of invoking the callback function
** multiple times, it is invoked once with the set of void* context pointers
** specified by the blocked connections bundled together into an array.
** This gives the application an opportunity to prioritize any actions 
** related to the set of unblocked database connections.
**
** <b>Deadlock Detection</b>
**
** Assuming that after registering for an unlock-notify callback a 
** database waits for the callback to be issued before taking any further
** action (a reasonable assumption), then using this API may cause the
** application to deadlock. For example, if connection X is waiting for
** connection Y's transaction to be concluded, and similarly connection
** Y is waiting on connection X's transaction, then neither connection
** will proceed and the system may remain deadlocked indefinitely.
**
** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
** detection. If a given call to sqlite3_unlock_notify() would put the
** system in a deadlocked state, then SQLITE_LOCKED is returned and no
** unlock-notify callback is registered. The system is said to be in
** a deadlocked state if connection A has registered for an unlock-notify
** callback on the conclusion of connection B's transaction, and connection
** B has itself registered for an unlock-notify callback when connection
** A's transaction is concluded. Indirect deadlock is also detected, so
** the system is also considered to be deadlocked if connection B has
** registered for an unlock-notify callback on the conclusion of connection
** C's transaction, where connection C is waiting on connection A. Any
** number of levels of indirection are allowed.
**
** <b>The "DROP TABLE" Exception</b>
**
** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
** always appropriate to call sqlite3_unlock_notify(). There is however,
** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
** SQLite checks if there are any currently executing SELECT statements
** that belong to the same connection. If there are, SQLITE_LOCKED is
** returned. In this case there is no "blocking connection", so invoking
** sqlite3_unlock_notify() results in the unlock-notify callback being
** invoked immediately. If the application then re-attempts the "DROP TABLE"
** or "DROP INDEX" query, an infinite loop might be the result.
**
** One way around this problem is to check the extended error code returned
** by an sqlite3_step() call. If there is a blocking connection, then the
** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
** the special "DROP TABLE/INDEX" case, the extended error code is just 
** SQLITE_LOCKED.
*/
int sqlite3_unlock_notify(
  sqlite3 *pBlocked,                          /* Waiting connection */
  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
  void *pNotifyArg                            /* Argument to pass to xNotify */
);


/*
** CAPI3REF: String Comparison
** EXPERIMENTAL
**
** The [sqlite3_strnicmp()] API allows applications and extensions to
** compare the contents of two buffers containing UTF-8 strings in a
** case-indendent fashion, using the same definition of case independence 
** that SQLite uses internally when comparing identifiers.
*/
int sqlite3_strnicmp(const char *, const char *, int);

/*
** Undo the hack that converts floating point types to integer for
** builds on processors without floating point support.
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# undef double
#endif

#ifdef __cplusplus
}  /* End of the 'extern "C"' block */
#endif
#endif

Added src/sqlite3ext.h.

























































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
** 2006 June 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
**
** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $
*/
#ifndef _SQLITE3EXT_H_
#define _SQLITE3EXT_H_
#include "sqlite3.h"

typedef struct sqlite3_api_routines sqlite3_api_routines;

/*
** The following structure holds pointers to all of the SQLite API
** routines.
**
** WARNING:  In order to maintain backwards compatibility, add new
** interfaces to the end of this structure only.  If you insert new
** interfaces in the middle of this structure, then older different
** versions of SQLite will not be able to load each others' shared
** libraries!
*/
struct sqlite3_api_routines {
  void * (*aggregate_context)(sqlite3_context*,int nBytes);
  int  (*aggregate_count)(sqlite3_context*);
  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  int  (*bind_double)(sqlite3_stmt*,int,double);
  int  (*bind_int)(sqlite3_stmt*,int,int);
  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  int  (*bind_null)(sqlite3_stmt*,int);
  int  (*bind_parameter_count)(sqlite3_stmt*);
  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  int  (*busy_timeout)(sqlite3*,int ms);
  int  (*changes)(sqlite3*);
  int  (*close)(sqlite3*);
  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
  const void * (*column_blob)(sqlite3_stmt*,int iCol);
  int  (*column_bytes)(sqlite3_stmt*,int iCol);
  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
  int  (*column_count)(sqlite3_stmt*pStmt);
  const char * (*column_database_name)(sqlite3_stmt*,int);
  const void * (*column_database_name16)(sqlite3_stmt*,int);
  const char * (*column_decltype)(sqlite3_stmt*,int i);
  const void * (*column_decltype16)(sqlite3_stmt*,int);
  double  (*column_double)(sqlite3_stmt*,int iCol);
  int  (*column_int)(sqlite3_stmt*,int iCol);
  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
  const char * (*column_name)(sqlite3_stmt*,int);
  const void * (*column_name16)(sqlite3_stmt*,int);
  const char * (*column_origin_name)(sqlite3_stmt*,int);
  const void * (*column_origin_name16)(sqlite3_stmt*,int);
  const char * (*column_table_name)(sqlite3_stmt*,int);
  const void * (*column_table_name16)(sqlite3_stmt*,int);
  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  const void * (*column_text16)(sqlite3_stmt*,int iCol);
  int  (*column_type)(sqlite3_stmt*,int iCol);
  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  int  (*complete)(const char*sql);
  int  (*complete16)(const void*sql);
  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
  int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  int  (*data_count)(sqlite3_stmt*pStmt);
  sqlite3 * (*db_handle)(sqlite3_stmt*);
  int (*declare_vtab)(sqlite3*,const char*);
  int  (*enable_shared_cache)(int);
  int  (*errcode)(sqlite3*db);
  const char * (*errmsg)(sqlite3*);
  const void * (*errmsg16)(sqlite3*);
  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  int  (*expired)(sqlite3_stmt*);
  int  (*finalize)(sqlite3_stmt*pStmt);
  void  (*free)(void*);
  void  (*free_table)(char**result);
  int  (*get_autocommit)(sqlite3*);
  void * (*get_auxdata)(sqlite3_context*,int);
  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  int  (*global_recover)(void);
  void  (*interruptx)(sqlite3*);
  sqlite_int64  (*last_insert_rowid)(sqlite3*);
  const char * (*libversion)(void);
  int  (*libversion_number)(void);
  void *(*malloc)(int);
  char * (*mprintf)(const char*,...);
  int  (*open)(const char*,sqlite3**);
  int  (*open16)(const void*,sqlite3**);
  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  void *(*realloc)(void*,int);
  int  (*reset)(sqlite3_stmt*pStmt);
  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_double)(sqlite3_context*,double);
  void  (*result_error)(sqlite3_context*,const char*,int);
  void  (*result_error16)(sqlite3_context*,const void*,int);
  void  (*result_int)(sqlite3_context*,int);
  void  (*result_int64)(sqlite3_context*,sqlite_int64);
  void  (*result_null)(sqlite3_context*);
  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_value)(sqlite3_context*,sqlite3_value*);
  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  char * (*snprintf)(int,char*,const char*,...);
  int  (*step)(sqlite3_stmt*);
  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
  void  (*thread_cleanup)(void);
  int  (*total_changes)(sqlite3*);
  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
  void * (*user_data)(sqlite3_context*);
  const void * (*value_blob)(sqlite3_value*);
  int  (*value_bytes)(sqlite3_value*);
  int  (*value_bytes16)(sqlite3_value*);
  double  (*value_double)(sqlite3_value*);
  int  (*value_int)(sqlite3_value*);
  sqlite_int64  (*value_int64)(sqlite3_value*);
  int  (*value_numeric_type)(sqlite3_value*);
  const unsigned char * (*value_text)(sqlite3_value*);
  const void * (*value_text16)(sqlite3_value*);
  const void * (*value_text16be)(sqlite3_value*);
  const void * (*value_text16le)(sqlite3_value*);
  int  (*value_type)(sqlite3_value*);
  char *(*vmprintf)(const char*,va_list);
  /* Added ??? */
  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  /* Added by 3.3.13 */
  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  int (*clear_bindings)(sqlite3_stmt*);
  /* Added by 3.4.1 */
  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
  /* Added by 3.5.0 */
  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  int (*blob_bytes)(sqlite3_blob*);
  int (*blob_close)(sqlite3_blob*);
  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
  int (*blob_read)(sqlite3_blob*,void*,int,int);
  int (*blob_write)(sqlite3_blob*,const void*,int,int);
  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
  int (*file_control)(sqlite3*,const char*,int,void*);
  sqlite3_int64 (*memory_highwater)(int);
  sqlite3_int64 (*memory_used)(void);
  sqlite3_mutex *(*mutex_alloc)(int);
  void (*mutex_enter)(sqlite3_mutex*);
  void (*mutex_free)(sqlite3_mutex*);
  void (*mutex_leave)(sqlite3_mutex*);
  int (*mutex_try)(sqlite3_mutex*);
  int (*open_v2)(const char*,sqlite3**,int,const char*);
  int (*release_memory)(int);
  void (*result_error_nomem)(sqlite3_context*);
  void (*result_error_toobig)(sqlite3_context*);
  int (*sleep)(int);
  void (*soft_heap_limit)(int);
  sqlite3_vfs *(*vfs_find)(const char*);
  int (*vfs_register)(sqlite3_vfs*,int);
  int (*vfs_unregister)(sqlite3_vfs*);
  int (*xthreadsafe)(void);
  void (*result_zeroblob)(sqlite3_context*,int);
  void (*result_error_code)(sqlite3_context*,int);
  int (*test_control)(int, ...);
  void (*randomness)(int,void*);
  sqlite3 *(*context_db_handle)(sqlite3_context*);
  int (*extended_result_codes)(sqlite3*,int);
  int (*limit)(sqlite3*,int,int);
  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  const char *(*sql)(sqlite3_stmt*);
  int (*status)(int,int*,int*,int);
};

/*
** The following macros redefine the API routines so that they are
** redirected throught the global sqlite3_api structure.
**
** This header file is also used by the loadext.c source file
** (part of the main SQLite library - not an extension) so that
** it can get access to the sqlite3_api_routines structure
** definition.  But the main library does not want to redefine
** the API.  So the redefinition macros are only valid if the
** SQLITE_CORE macros is undefined.
*/
#ifndef SQLITE_CORE
#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
#endif
#define sqlite3_bind_blob              sqlite3_api->bind_blob
#define sqlite3_bind_double            sqlite3_api->bind_double
#define sqlite3_bind_int               sqlite3_api->bind_int
#define sqlite3_bind_int64             sqlite3_api->bind_int64
#define sqlite3_bind_null              sqlite3_api->bind_null
#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
#define sqlite3_bind_text              sqlite3_api->bind_text
#define sqlite3_bind_text16            sqlite3_api->bind_text16
#define sqlite3_bind_value             sqlite3_api->bind_value
#define sqlite3_busy_handler           sqlite3_api->busy_handler
#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
#define sqlite3_changes                sqlite3_api->changes
#define sqlite3_close                  sqlite3_api->close
#define sqlite3_collation_needed       sqlite3_api->collation_needed
#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
#define sqlite3_column_blob            sqlite3_api->column_blob
#define sqlite3_column_bytes           sqlite3_api->column_bytes
#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
#define sqlite3_column_count           sqlite3_api->column_count
#define sqlite3_column_database_name   sqlite3_api->column_database_name
#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
#define sqlite3_column_decltype        sqlite3_api->column_decltype
#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
#define sqlite3_column_double          sqlite3_api->column_double
#define sqlite3_column_int             sqlite3_api->column_int
#define sqlite3_column_int64           sqlite3_api->column_int64
#define sqlite3_column_name            sqlite3_api->column_name
#define sqlite3_column_name16          sqlite3_api->column_name16
#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
#define sqlite3_column_table_name      sqlite3_api->column_table_name
#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
#define sqlite3_column_text            sqlite3_api->column_text
#define sqlite3_column_text16          sqlite3_api->column_text16
#define sqlite3_column_type            sqlite3_api->column_type
#define sqlite3_column_value           sqlite3_api->column_value
#define sqlite3_commit_hook            sqlite3_api->commit_hook
#define sqlite3_complete               sqlite3_api->complete
#define sqlite3_complete16             sqlite3_api->complete16
#define sqlite3_create_collation       sqlite3_api->create_collation
#define sqlite3_create_collation16     sqlite3_api->create_collation16
#define sqlite3_create_function        sqlite3_api->create_function
#define sqlite3_create_function16      sqlite3_api->create_function16
#define sqlite3_create_module          sqlite3_api->create_module
#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
#define sqlite3_data_count             sqlite3_api->data_count
#define sqlite3_db_handle              sqlite3_api->db_handle
#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
#define sqlite3_errcode                sqlite3_api->errcode
#define sqlite3_errmsg                 sqlite3_api->errmsg
#define sqlite3_errmsg16               sqlite3_api->errmsg16
#define sqlite3_exec                   sqlite3_api->exec
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_expired                sqlite3_api->expired
#endif
#define sqlite3_finalize               sqlite3_api->finalize
#define sqlite3_free                   sqlite3_api->free
#define sqlite3_free_table             sqlite3_api->free_table
#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
#define sqlite3_get_table              sqlite3_api->get_table
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_global_recover         sqlite3_api->global_recover
#endif
#define sqlite3_interrupt              sqlite3_api->interruptx
#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
#define sqlite3_libversion             sqlite3_api->libversion
#define sqlite3_libversion_number      sqlite3_api->libversion_number
#define sqlite3_malloc                 sqlite3_api->malloc
#define sqlite3_mprintf                sqlite3_api->mprintf
#define sqlite3_open                   sqlite3_api->open
#define sqlite3_open16                 sqlite3_api->open16
#define sqlite3_prepare                sqlite3_api->prepare
#define sqlite3_prepare16              sqlite3_api->prepare16
#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
#define sqlite3_profile                sqlite3_api->profile
#define sqlite3_progress_handler       sqlite3_api->progress_handler
#define sqlite3_realloc                sqlite3_api->realloc
#define sqlite3_reset                  sqlite3_api->reset
#define sqlite3_result_blob            sqlite3_api->result_blob
#define sqlite3_result_double          sqlite3_api->result_double
#define sqlite3_result_error           sqlite3_api->result_error
#define sqlite3_result_error16         sqlite3_api->result_error16
#define sqlite3_result_int             sqlite3_api->result_int
#define sqlite3_result_int64           sqlite3_api->result_int64
#define sqlite3_result_null            sqlite3_api->result_null
#define sqlite3_result_text            sqlite3_api->result_text
#define sqlite3_result_text16          sqlite3_api->result_text16
#define sqlite3_result_text16be        sqlite3_api->result_text16be
#define sqlite3_result_text16le        sqlite3_api->result_text16le
#define sqlite3_result_value           sqlite3_api->result_value
#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
#define sqlite3_snprintf               sqlite3_api->snprintf
#define sqlite3_step                   sqlite3_api->step
#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
#define sqlite3_total_changes          sqlite3_api->total_changes
#define sqlite3_trace                  sqlite3_api->trace
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
#endif
#define sqlite3_update_hook            sqlite3_api->update_hook
#define sqlite3_user_data              sqlite3_api->user_data
#define sqlite3_value_blob             sqlite3_api->value_blob
#define sqlite3_value_bytes            sqlite3_api->value_bytes
#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
#define sqlite3_value_double           sqlite3_api->value_double
#define sqlite3_value_int              sqlite3_api->value_int
#define sqlite3_value_int64            sqlite3_api->value_int64
#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
#define sqlite3_value_text             sqlite3_api->value_text
#define sqlite3_value_text16           sqlite3_api->value_text16
#define sqlite3_value_text16be         sqlite3_api->value_text16be
#define sqlite3_value_text16le         sqlite3_api->value_text16le
#define sqlite3_value_type             sqlite3_api->value_type
#define sqlite3_vmprintf               sqlite3_api->vmprintf
#define sqlite3_overload_function      sqlite3_api->overload_function
#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
#define sqlite3_blob_close             sqlite3_api->blob_close
#define sqlite3_blob_open              sqlite3_api->blob_open
#define sqlite3_blob_read              sqlite3_api->blob_read
#define sqlite3_blob_write             sqlite3_api->blob_write
#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
#define sqlite3_file_control           sqlite3_api->file_control
#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
#define sqlite3_memory_used            sqlite3_api->memory_used
#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
#define sqlite3_mutex_free             sqlite3_api->mutex_free
#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
#define sqlite3_mutex_try              sqlite3_api->mutex_try
#define sqlite3_open_v2                sqlite3_api->open_v2
#define sqlite3_release_memory         sqlite3_api->release_memory
#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
#define sqlite3_sleep                  sqlite3_api->sleep
#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
#define sqlite3_vfs_find               sqlite3_api->vfs_find
#define sqlite3_vfs_register           sqlite3_api->vfs_register
#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
#define sqlite3_result_error_code      sqlite3_api->result_error_code
#define sqlite3_test_control           sqlite3_api->test_control
#define sqlite3_randomness             sqlite3_api->randomness
#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
#define sqlite3_limit                  sqlite3_api->limit
#define sqlite3_next_stmt              sqlite3_api->next_stmt
#define sqlite3_sql                    sqlite3_api->sql
#define sqlite3_status                 sqlite3_api->status
#endif /* SQLITE_CORE */

#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;

#endif /* _SQLITE3EXT_H_ */

Added src/sqliteInt.h.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Internal interface definitions for SQLite.
**
*/
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_

/*
** These #defines should enable >2GB file support on POSIX if the
** underlying operating system supports it.  If the OS lacks
** large file support, or if the OS is windows, these should be no-ops.
**
** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
** system #includes.  Hence, this block of code must be the very first
** code in all source files.
**
** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
** on the compiler command line.  This is necessary if you are compiling
** on a recent machine (ex: Red Hat 7.2) but you want your code to work
** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
** without this option, LFS is enable.  But LFS does not exist in the kernel
** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
** portability you should omit LFS.
**
** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
*/
#ifndef SQLITE_DISABLE_LFS
# define _LARGE_FILE       1
# ifndef _FILE_OFFSET_BITS
#   define _FILE_OFFSET_BITS 64
# endif
# define _LARGEFILE_SOURCE 1
#endif

/*
** Include the configuration header output by 'configure' if we're using the
** autoconf-based build
*/
#ifdef _HAVE_SQLITE_CONFIG_H
#include "config.h"
#endif

#include "sqliteLimit.h"

/* Disable nuisance warnings on Borland compilers */
#if defined(__BORLANDC__)
#pragma warn -rch /* unreachable code */
#pragma warn -ccc /* Condition is always true or false */
#pragma warn -aus /* Assigned value is never used */
#pragma warn -csu /* Comparing signed and unsigned */
#pragma warn -spa /* Suspicious pointer arithmetic */
#endif

/* Needed for various definitions... */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif

/*
** Include standard header files as necessary
*/
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif

#define SQLITE_INDEX_SAMPLES 10

/*
** This macro is used to "hide" some ugliness in casting an int
** value to a ptr value under the MSVC 64-bit compiler.   Casting
** non 64-bit values to ptr types results in a "hard" error with 
** the MSVC 64-bit compiler which this attempts to avoid.  
**
** A simple compiler pragma or casting sequence could not be found
** to correct this in all situations, so this macro was introduced.
**
** It could be argued that the intptr_t type could be used in this
** case, but that type is not available on all compilers, or 
** requires the #include of specific headers which differs between
** platforms.
**
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
** So we have to define the macros in different ways depending on the
** compiler.
*/
#if defined(__GNUC__)
# if defined(HAVE_STDINT_H)
#   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
#   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
# else
#   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
#   define SQLITE_PTR_TO_INT(X)  ((int)(X))
# endif
#else
# define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
# define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
#endif


/*
** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
** Older versions of SQLite used an optional THREADSAFE macro.
** We support that for legacy
*/
#if !defined(SQLITE_THREADSAFE)
#if defined(THREADSAFE)
# define SQLITE_THREADSAFE THREADSAFE
#else
# define SQLITE_THREADSAFE 1
#endif
#endif

/*
** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
** It determines whether or not the features related to 
** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
** be overridden at runtime using the sqlite3_config() API.
*/
#if !defined(SQLITE_DEFAULT_MEMSTATUS)
# define SQLITE_DEFAULT_MEMSTATUS 1
#endif

/*
** Exactly one of the following macros must be defined in order to
** specify which memory allocation subsystem to use.
**
**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
**     SQLITE_MEMORY_SIZE            // internal allocator #1
**     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
**     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
**
** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
** the default.
*/
#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
    defined(SQLITE_POW2_MEMORY_SIZE)>1
# error "At most one of the following compile-time configuration options\
 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
 SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
#endif
#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
    defined(SQLITE_POW2_MEMORY_SIZE)==0
# define SQLITE_SYSTEM_MALLOC 1
#endif

/*
** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
** sizes of memory allocations below this value where possible.
*/
#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
# define SQLITE_MALLOC_SOFT_LIMIT 1024
#endif

/*
** We need to define _XOPEN_SOURCE as follows in order to enable
** recursive mutexes on most Unix systems.  But Mac OS X is different.
** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
** so it is omitted there.  See ticket #2673.
**
** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
** implemented on some systems.  So we avoid defining it at all
** if it is already defined or if it is unneeded because we are
** not doing a threadsafe build.  Ticket #2681.
**
** See also ticket #2741.
*/
#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
#endif

/*
** The TCL headers are only needed when compiling the TCL bindings.
*/
#if defined(SQLITE_TCL) || defined(TCLSH)
# include <tcl.h>
#endif

/*
** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
** Setting NDEBUG makes the code smaller and run faster.  So the following
** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
** feature.
*/
#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
# define NDEBUG 1
#endif

/*
** The testcase() macro is used to aid in coverage testing.  When 
** doing coverage testing, the condition inside the argument to
** testcase() must be evaluated both true and false in order to
** get full branch coverage.  The testcase() macro is inserted
** to help ensure adequate test coverage in places where simple
** condition/decision coverage is inadequate.  For example, testcase()
** can be used to make sure boundary values are tested.  For
** bitmask tests, testcase() can be used to make sure each bit
** is significant and used at least once.  On switch statements
** where multiple cases go to the same block of code, testcase()
** can insure that all cases are evaluated.
**
*/
#ifdef SQLITE_COVERAGE_TEST
  void sqlite3Coverage(int);
# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
#else
# define testcase(X)
#endif

/*
** The TESTONLY macro is used to enclose variable declarations or
** other bits of code that are needed to support the arguments
** within testcase() and assert() macros.
*/
#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
# define TESTONLY(X)  X
#else
# define TESTONLY(X)
#endif

/*
** Sometimes we need a small amount of code such as a variable initialization
** to setup for a later assert() statement.  We do not want this code to
** appear when assert() is disabled.  The following macro is therefore
** used to contain that setup code.  The "VVA" acronym stands for
** "Verification, Validation, and Accreditation".  In other words, the
** code within VVA_ONLY() will only run during verification processes.
*/
#ifndef NDEBUG
# define VVA_ONLY(X)  X
#else
# define VVA_ONLY(X)
#endif

/*
** The ALWAYS and NEVER macros surround boolean expressions which 
** are intended to always be true or false, respectively.  Such
** expressions could be omitted from the code completely.  But they
** are included in a few cases in order to enhance the resilience
** of SQLite to unexpected behavior - to make the code "self-healing"
** or "ductile" rather than being "brittle" and crashing at the first
** hint of unplanned behavior.
**
** In other words, ALWAYS and NEVER are added for defensive code.
**
** When doing coverage testing ALWAYS and NEVER are hard-coded to
** be true and false so that the unreachable code then specify will
** not be counted as untested code.
*/
#if defined(SQLITE_COVERAGE_TEST)
# define ALWAYS(X)      (1)
# define NEVER(X)       (0)
#elif !defined(NDEBUG)
# define ALWAYS(X)      ((X)?1:(assert(0),0))
# define NEVER(X)       ((X)?(assert(0),1):0)
#else
# define ALWAYS(X)      (X)
# define NEVER(X)       (X)
#endif

/*
** The macro unlikely() is a hint that surrounds a boolean
** expression that is usually false.  Macro likely() surrounds
** a boolean expression that is usually true.  GCC is able to
** use these hints to generate better code, sometimes.
*/
#if defined(__GNUC__) && 0
# define likely(X)    __builtin_expect((X),1)
# define unlikely(X)  __builtin_expect((X),0)
#else
# define likely(X)    !!(X)
# define unlikely(X)  !!(X)
#endif

#include "sqlite3.h"
#include "hash.h"
#include "parse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite_int64
# define LONGDOUBLE_TYPE sqlite_int64
# ifndef SQLITE_BIG_DBL
#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
# endif
# define SQLITE_OMIT_DATETIME_FUNCS 1
# define SQLITE_OMIT_TRACE 1
# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
# undef SQLITE_HAVE_ISNAN
#endif
#ifndef SQLITE_BIG_DBL
# define SQLITE_BIG_DBL (1e99)
#endif

/*
** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
** afterward. Having this macro allows us to cause the C compiler 
** to omit code used by TEMP tables without messy #ifndef statements.
*/
#ifdef SQLITE_OMIT_TEMPDB
#define OMIT_TEMPDB 1
#else
#define OMIT_TEMPDB 0
#endif

/*
** If the following macro is set to 1, then NULL values are considered
** distinct when determining whether or not two entries are the same
** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
** is the way things are suppose to work.
**
** If the following macro is set to 0, the NULLs are indistinct for
** a UNIQUE index.  In this mode, you can only have a single NULL entry
** for a column declared UNIQUE.  This is the way Informix and SQL Server
** work.
*/
#define NULL_DISTINCT_FOR_UNIQUE 1

/*
** The "file format" number is an integer that is incremented whenever
** the VDBE-level file format changes.  The following macros define the
** the default file format for new databases and the maximum file format
** that the library can read.
*/
#define SQLITE_MAX_FILE_FORMAT 4
#ifndef SQLITE_DEFAULT_FILE_FORMAT
# define SQLITE_DEFAULT_FILE_FORMAT 1
#endif

#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
#endif

/*
** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
** on the command-line
*/
#ifndef SQLITE_TEMP_STORE
# define SQLITE_TEMP_STORE 1
#endif

/*
** GCC does not define the offsetof() macro so we'll have to do it
** ourselves.
*/
#ifndef offsetof
#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
#endif

/*
** Check to see if this machine uses EBCDIC.  (Yes, believe it or
** not, there are still machines out there that use EBCDIC.)
*/
#if 'A' == '\301'
# define SQLITE_EBCDIC 1
#else
# define SQLITE_ASCII 1
#endif

/*
** Integers of known sizes.  These typedefs might change for architectures
** where the sizes very.  Preprocessor macros are available so that the
** types can be conveniently redefined at compile-type.  Like this:
**
**         cc '-DUINTPTR_TYPE=long long int' ...
*/
#ifndef UINT32_TYPE
# ifdef HAVE_UINT32_T
#  define UINT32_TYPE uint32_t
# else
#  define UINT32_TYPE unsigned int
# endif
#endif
#ifndef UINT16_TYPE
# ifdef HAVE_UINT16_T
#  define UINT16_TYPE uint16_t
# else
#  define UINT16_TYPE unsigned short int
# endif
#endif
#ifndef INT16_TYPE
# ifdef HAVE_INT16_T
#  define INT16_TYPE int16_t
# else
#  define INT16_TYPE short int
# endif
#endif
#ifndef UINT8_TYPE
# ifdef HAVE_UINT8_T
#  define UINT8_TYPE uint8_t
# else
#  define UINT8_TYPE unsigned char
# endif
#endif
#ifndef INT8_TYPE
# ifdef HAVE_INT8_T
#  define INT8_TYPE int8_t
# else
#  define INT8_TYPE signed char
# endif
#endif
#ifndef LONGDOUBLE_TYPE
# define LONGDOUBLE_TYPE long double
#endif
typedef sqlite_int64 i64;          /* 8-byte signed integer */
typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
typedef INT16_TYPE i16;            /* 2-byte signed integer */
typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
typedef INT8_TYPE i8;              /* 1-byte signed integer */

/*
** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
** that can be stored in a u32 without loss of data.  The value
** is 0x00000000ffffffff.  But because of quirks of some compilers, we
** have to specify the value in the less intuitive manner shown:
*/
#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)

/*
** Macros to determine whether the machine is big or little endian,
** evaluated at runtime.
*/
#ifdef SQLITE_AMALGAMATION
const int sqlite3one = 1;
#else
extern const int sqlite3one;
#endif
#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
                             || defined(__x86_64) || defined(__x86_64__)
# define SQLITE_BIGENDIAN    0
# define SQLITE_LITTLEENDIAN 1
# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
#else
# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
#endif

/*
** Constants for the largest and smallest possible 64-bit signed integers.
** These macros are designed to work correctly on both 32-bit and 64-bit
** compilers.
*/
#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)

/* 
** Round up a number to the next larger multiple of 8.  This is used
** to force 8-byte alignment on 64-bit architectures.
*/
#define ROUND8(x)     (((x)+7)&~7)

/*
** Round down to the nearest multiple of 8
*/
#define ROUNDDOWN8(x) ((x)&~7)

/*
** Assert that the pointer X is aligned to an 8-byte boundary.
*/
#define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)


/*
** An instance of the following structure is used to store the busy-handler
** callback for a given sqlite handle. 
**
** The sqlite.busyHandler member of the sqlite struct contains the busy
** callback for the database handle. Each pager opened via the sqlite
** handle is passed a pointer to sqlite.busyHandler. The busy-handler
** callback is currently invoked only from within pager.c.
*/
typedef struct BusyHandler BusyHandler;
struct BusyHandler {
  int (*xFunc)(void *,int);  /* The busy callback */
  void *pArg;                /* First arg to busy callback */
  int nBusy;                 /* Incremented with each busy call */
};

/*
** Name of the master database table.  The master database table
** is a special table that holds the names and attributes of all
** user tables and indices.
*/
#define MASTER_NAME       "sqlite_master"
#define TEMP_MASTER_NAME  "sqlite_temp_master"

/*
** The root-page of the master database table.
*/
#define MASTER_ROOT       1

/*
** The name of the schema table.
*/
#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)

/*
** A convenience macro that returns the number of elements in
** an array.
*/
#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))

/*
** The following value as a destructor means to use sqlite3DbFree().
** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
*/
#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)

/*
** When SQLITE_OMIT_WSD is defined, it means that the target platform does
** not support Writable Static Data (WSD) such as global and static variables.
** All variables must either be on the stack or dynamically allocated from
** the heap.  When WSD is unsupported, the variable declarations scattered
** throughout the SQLite code must become constants instead.  The SQLITE_WSD
** macro is used for this purpose.  And instead of referencing the variable
** directly, we use its constant as a key to lookup the run-time allocated
** buffer that holds real variable.  The constant is also the initializer
** for the run-time allocated buffer.
**
** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
** macros become no-ops and have zero performance impact.
*/
#ifdef SQLITE_OMIT_WSD
  #define SQLITE_WSD const
  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  int sqlite3_wsd_init(int N, int J);
  void *sqlite3_wsd_find(void *K, int L);
#else
  #define SQLITE_WSD 
  #define GLOBAL(t,v) v
  #define sqlite3GlobalConfig sqlite3Config
#endif

/*
** The following macros are used to suppress compiler warnings and to
** make it clear to human readers when a function parameter is deliberately 
** left unused within the body of a function. This usually happens when
** a function is called via a function pointer. For example the 
** implementation of an SQL aggregate step callback may not use the
** parameter indicating the number of arguments passed to the aggregate,
** if it knows that this is enforced elsewhere.
**
** When a function parameter is not used at all within the body of a function,
** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
** However, these macros may also be used to suppress warnings related to
** parameters that may or may not be used depending on compilation options.
** For example those parameters only used in assert() statements. In these
** cases the parameters are named as per the usual conventions.
*/
#define UNUSED_PARAMETER(x) (void)(x)
#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)

/*
** Forward references to structures
*/
typedef struct AggInfo AggInfo;
typedef struct AuthContext AuthContext;
typedef struct AutoincInfo AutoincInfo;
typedef struct Bitvec Bitvec;
typedef struct RowSet RowSet;
typedef struct CollSeq CollSeq;
typedef struct Column Column;
typedef struct Db Db;
typedef struct Schema Schema;
typedef struct Expr Expr;
typedef struct ExprList ExprList;
typedef struct ExprSpan ExprSpan;
typedef struct FKey FKey;
typedef struct FuncDef FuncDef;
typedef struct FuncDefHash FuncDefHash;
typedef struct IdList IdList;
typedef struct Index Index;
typedef struct IndexSample IndexSample;
typedef struct KeyClass KeyClass;
typedef struct KeyInfo KeyInfo;
typedef struct Lookaside Lookaside;
typedef struct LookasideSlot LookasideSlot;
typedef struct Module Module;
typedef struct NameContext NameContext;
typedef struct Parse Parse;
typedef struct Savepoint Savepoint;
typedef struct Select Select;
typedef struct SrcList SrcList;
typedef struct StrAccum StrAccum;
typedef struct Table Table;
typedef struct TableLock TableLock;
typedef struct Token Token;
typedef struct TriggerPrg TriggerPrg;
typedef struct TriggerStep TriggerStep;
typedef struct Trigger Trigger;
typedef struct UnpackedRecord UnpackedRecord;
typedef struct VTable VTable;
typedef struct Walker Walker;
typedef struct WherePlan WherePlan;
typedef struct WhereInfo WhereInfo;
typedef struct WhereLevel WhereLevel;

/*
** Defer sourcing vdbe.h and btree.h until after the "u8" and 
** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
** pointer types (i.e. FuncDef) defined above.
*/
#include "btree.h"
#include "vdbe.h"
#include "pager.h"
#include "pcache.h"

#include "os.h"
#include "mutex.h"


/*
** Each database file to be accessed by the system is an instance
** of the following structure.  There are normally two of these structures
** in the sqlite.aDb[] array.  aDb[0] is the main database file and
** aDb[1] is the database file used to hold temporary tables.  Additional
** databases may be attached.
*/
struct Db {
  char *zName;         /* Name of this database */
  Btree *pBt;          /* The B*Tree structure for this database file */
  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
  u8 safety_level;     /* How aggressive at syncing data to disk */
  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
};

/*
** An instance of the following structure stores a database schema.
**
** If there are no virtual tables configured in this schema, the
** Schema.db variable is set to NULL. After the first virtual table
** has been added, it is set to point to the database connection 
** used to create the connection. Once a virtual table has been
** added to the Schema structure and the Schema.db variable populated, 
** only that database connection may use the Schema to prepare 
** statements.
*/
struct Schema {
  int schema_cookie;   /* Database schema version number for this file */
  Hash tblHash;        /* All tables indexed by name */
  Hash idxHash;        /* All (named) indices indexed by name */
  Hash trigHash;       /* All triggers indexed by name */
  Hash fkeyHash;       /* All foreign keys by referenced table name */
  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
  u8 file_format;      /* Schema format version for this file */
  u8 enc;              /* Text encoding used by this database */
  u16 flags;           /* Flags associated with this schema */
  int cache_size;      /* Number of pages to use in the cache */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3 *db;         /* "Owner" connection. See comment above */
#endif
};

/*
** These macros can be used to test, set, or clear bits in the 
** Db.flags field.
*/
#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)

/*
** Allowed values for the DB.flags field.
**
** The DB_SchemaLoaded flag is set after the database schema has been
** read into internal hash tables.
**
** DB_UnresetViews means that one or more views have column names that
** have been filled out.  If the schema changes, these column names might
** changes and so the view will need to be reset.
*/
#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
#define DB_UnresetViews    0x0002  /* Some views have defined column names */
#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */

/*
** The number of different kinds of things that can be limited
** using the sqlite3_limit() interface.
*/
#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)

/*
** Lookaside malloc is a set of fixed-size buffers that can be used
** to satisfy small transient memory allocation requests for objects
** associated with a particular database connection.  The use of
** lookaside malloc provides a significant performance enhancement
** (approx 10%) by avoiding numerous malloc/free requests while parsing
** SQL statements.
**
** The Lookaside structure holds configuration information about the
** lookaside malloc subsystem.  Each available memory allocation in
** the lookaside subsystem is stored on a linked list of LookasideSlot
** objects.
**
** Lookaside allocations are only allowed for objects that are associated
** with a particular database connection.  Hence, schema information cannot
** be stored in lookaside because in shared cache mode the schema information
** is shared by multiple database connections.  Therefore, while parsing
** schema information, the Lookaside.bEnabled flag is cleared so that
** lookaside allocations are not used to construct the schema objects.
*/
struct Lookaside {
  u16 sz;                 /* Size of each buffer in bytes */
  u8 bEnabled;            /* False to disable new lookaside allocations */
  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
  int nOut;               /* Number of buffers currently checked out */
  int mxOut;              /* Highwater mark for nOut */
  LookasideSlot *pFree;   /* List of available buffers */
  void *pStart;           /* First byte of available memory space */
  void *pEnd;             /* First byte past end of available space */
};
struct LookasideSlot {
  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
};

/*
** A hash table for function definitions.
**
** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
** Collisions are on the FuncDef.pHash chain.
*/
struct FuncDefHash {
  FuncDef *a[23];       /* Hash table for functions */
};

/*
** Each database is an instance of the following structure.
**
** The sqlite.lastRowid records the last insert rowid generated by an
** insert statement.  Inserts on views do not affect its value.  Each
** trigger has its own context, so that lastRowid can be updated inside
** triggers as usual.  The previous value will be restored once the trigger
** exits.  Upon entering a before or instead of trigger, lastRowid is no
** longer (since after version 2.8.12) reset to -1.
**
** The sqlite.nChange does not count changes within triggers and keeps no
** context.  It is reset at start of sqlite3_exec.
** The sqlite.lsChange represents the number of changes made by the last
** insert, update, or delete statement.  It remains constant throughout the
** length of a statement and is then updated by OP_SetCounts.  It keeps a
** context stack just like lastRowid so that the count of changes
** within a trigger is not seen outside the trigger.  Changes to views do not
** affect the value of lsChange.
** The sqlite.csChange keeps track of the number of current changes (since
** the last statement) and is used to update sqlite_lsChange.
**
** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
** store the most recent error code and, if applicable, string. The
** internal function sqlite3Error() is used to set these variables
** consistently.
*/
struct sqlite3 {
  sqlite3_vfs *pVfs;            /* OS Interface */
  int nDb;                      /* Number of backends currently in use */
  Db *aDb;                      /* All backends */
  int flags;                    /* Miscellaneous flags. See below */
  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
  int errCode;                  /* Most recent error code (SQLITE_*) */
  int errMask;                  /* & result codes with this before returning */
  u8 autoCommit;                /* The auto-commit flag. */
  u8 temp_store;                /* 1: file 2: memory 0: default */
  u8 mallocFailed;              /* True if we have seen a malloc failure */
  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
  int nextPagesize;             /* Pagesize after VACUUM if >0 */
  int nTable;                   /* Number of tables in the database */
  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
  i64 lastRowid;                /* ROWID of most recent insert (see above) */
  u32 magic;                    /* Magic number for detect library misuse */
  int nChange;                  /* Value returned by sqlite3_changes() */
  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
  sqlite3_mutex *mutex;         /* Connection mutex */
  int aLimit[SQLITE_N_LIMIT];   /* Limits */
  struct sqlite3InitInfo {      /* Information used during initialization */
    int iDb;                    /* When back is being initialized */
    int newTnum;                /* Rootpage of table being initialized */
    u8 busy;                    /* TRUE if currently initializing */
    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
  } init;
  int nExtension;               /* Number of loaded extensions */
  void **aExtension;            /* Array of shared library handles */
  struct Vdbe *pVdbe;           /* List of active virtual machines */
  int activeVdbeCnt;            /* Number of VDBEs currently executing */
  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
  void (*xTrace)(void*,const char*);        /* Trace function */
  void *pTraceArg;                          /* Argument to the trace function */
  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
  void *pProfileArg;                        /* Argument to profile function */
  void *pCommitArg;                 /* Argument to xCommitCallback() */   
  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
  void *pRollbackArg;               /* Argument to xRollbackCallback() */   
  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  void *pUpdateArg;
  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  void *pCollNeededArg;
  sqlite3_value *pErr;          /* Most recent error message */
  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
  union {
    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
    double notUsed1;            /* Spacer */
  } u1;
  Lookaside lookaside;          /* Lookaside malloc configuration */
#ifndef SQLITE_OMIT_AUTHORIZATION
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
                                /* Access authorization function */
  void *pAuthArg;               /* 1st argument to the access auth function */
#endif
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  int (*xProgress)(void *);     /* The progress callback */
  void *pProgressArg;           /* Argument to the progress callback */
  int nProgressOps;             /* Number of opcodes for progress callback */
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
  Hash aModule;                 /* populated by sqlite3_create_module() */
  Table *pVTab;                 /* vtab with active Connect/Create method */
  VTable **aVTrans;             /* Virtual tables with open transactions */
  int nVTrans;                  /* Allocated size of aVTrans */
  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
#endif
  FuncDefHash aFunc;            /* Hash table of connection functions */
  Hash aCollSeq;                /* All collating sequences */
  BusyHandler busyHandler;      /* Busy callback */
  int busyTimeout;              /* Busy handler timeout, in msec */
  Db aDbStatic[2];              /* Static space for the 2 default backends */
  Savepoint *pSavepoint;        /* List of active savepoints */
  int nSavepoint;               /* Number of non-transaction savepoints */
  int nStatement;               /* Number of nested statement-transactions  */
  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */

#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  /* The following variables are all protected by the STATIC_MASTER 
  ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
  **
  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  ** unlock so that it can proceed.
  **
  ** When X.pBlockingConnection==Y, that means that something that X tried
  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  ** held by Y.
  */
  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
  void *pUnlockArg;                     /* Argument to xUnlockNotify */
  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
#endif
};

/*
** A macro to discover the encoding of a database.
*/
#define ENC(db) ((db)->aDb[0].pSchema->enc)

/*
** Possible values for the sqlite.flags and or Db.flags fields.
**
** On sqlite.flags, the SQLITE_InTrans value means that we have
** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
** transaction is active on that particular database file.
*/
#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
#define SQLITE_InTrans        0x00000008  /* True if in a transaction */
#define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
#define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
                                          /*   DELETE, or UPDATE and return */
                                          /*   the count using a callback. */
#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
                                          /*   result set is empty */
#define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
#define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
#define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
#define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
                                          ** accessing read-only databases */
#define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
#define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
#define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
#define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
#define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */

#define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
#define SQLITE_ReverseOrder   0x00100000  /* Reverse unordered SELECTs */
#define SQLITE_RecTriggers    0x00200000  /* Enable recursive triggers */
#define SQLITE_ForeignKeys    0x00400000  /* Enforce foreign key constraints  */

/*
** Possible values for the sqlite.magic field.
** The numbers are obtained at random and have no special meaning, other
** than being distinct from one another.
*/
#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */

/*
** Each SQL function is defined by an instance of the following
** structure.  A pointer to this structure is stored in the sqlite.aFunc
** hash table.  When multiple functions have the same name, the hash table
** points to a linked list of these structures.
*/
struct FuncDef {
  i16 nArg;            /* Number of arguments.  -1 means unlimited */
  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  u8 flags;            /* Some combination of SQLITE_FUNC_* */
  void *pUserData;     /* User data parameter */
  FuncDef *pNext;      /* Next function with same name */
  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
  char *zName;         /* SQL name of the function. */
  FuncDef *pHash;      /* Next with a different name but the same hash */
};

/*
** Possible values for FuncDef.flags
*/
#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */

/*
** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
** used to create the initializers for the FuncDef structures.
**
**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
**     Used to create a scalar function definition of a function zName 
**     implemented by C function xFunc that accepts nArg arguments. The
**     value passed as iArg is cast to a (void*) and made available
**     as the user-data (sqlite3_user_data()) for the function. If 
**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
**
**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
**     Used to create an aggregate function definition implemented by
**     the C functions xStep and xFinal. The first four parameters
**     are interpreted in the same way as the first 4 parameters to
**     FUNCTION().
**
**   LIKEFUNC(zName, nArg, pArg, flags)
**     Used to create a scalar function definition of a function zName 
**     that accepts nArg arguments and is implemented by a call to C 
**     function likeFunc. Argument pArg is cast to a (void *) and made
**     available as the function user-data (sqlite3_user_data()). The
**     FuncDef.flags variable is set to the value passed as the flags
**     parameter.
*/
#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   pArg, 0, xFunc, 0, 0, #zName, 0}
#define LIKEFUNC(zName, nArg, arg, flags) \
  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}

/*
** All current savepoints are stored in a linked list starting at
** sqlite3.pSavepoint. The first element in the list is the most recently
** opened savepoint. Savepoints are added to the list by the vdbe
** OP_Savepoint instruction.
*/
struct Savepoint {
  char *zName;                        /* Savepoint name (nul-terminated) */
  i64 nDeferredCons;                  /* Number of deferred fk violations */
  Savepoint *pNext;                   /* Parent savepoint (if any) */
};

/*
** The following are used as the second parameter to sqlite3Savepoint(),
** and as the P1 argument to the OP_Savepoint instruction.
*/
#define SAVEPOINT_BEGIN      0
#define SAVEPOINT_RELEASE    1
#define SAVEPOINT_ROLLBACK   2


/*
** Each SQLite module (virtual table definition) is defined by an
** instance of the following structure, stored in the sqlite3.aModule
** hash table.
*/
struct Module {
  const sqlite3_module *pModule;       /* Callback pointers */
  const char *zName;                   /* Name passed to create_module() */
  void *pAux;                          /* pAux passed to create_module() */
  void (*xDestroy)(void *);            /* Module destructor function */
};

/*
** information about each column of an SQL table is held in an instance
** of this structure.
*/
struct Column {
  char *zName;     /* Name of this column */
  Expr *pDflt;     /* Default value of this column */
  char *zDflt;     /* Original text of the default value */
  char *zType;     /* Data type for this column */
  char *zColl;     /* Collating sequence.  If NULL, use the default */
  u8 notNull;      /* True if there is a NOT NULL constraint */
  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
  char affinity;   /* One of the SQLITE_AFF_... values */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  u8 isHidden;     /* True if this column is 'hidden' */
#endif
};

/*
** A "Collating Sequence" is defined by an instance of the following
** structure. Conceptually, a collating sequence consists of a name and
** a comparison routine that defines the order of that sequence.
**
** There may two separate implementations of the collation function, one
** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
** native byte order. When a collation sequence is invoked, SQLite selects
** the version that will require the least expensive encoding
** translations, if any.
**
** The CollSeq.pUser member variable is an extra parameter that passed in
** as the first argument to the UTF-8 comparison function, xCmp.
** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
** xCmp16.
**
** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
** collating sequence is undefined.  Indices built on an undefined
** collating sequence may not be read or written.
*/
struct CollSeq {
  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
  u8 enc;               /* Text encoding handled by xCmp() */
  u8 type;              /* One of the SQLITE_COLL_... values below */
  void *pUser;          /* First argument to xCmp() */
  int (*xCmp)(void*,int, const void*, int, const void*);
  void (*xDel)(void*);  /* Destructor for pUser */
};

/*
** Allowed values of CollSeq.type:
*/
#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */

/*
** A sort order can be either ASC or DESC.
*/
#define SQLITE_SO_ASC       0  /* Sort in ascending order */
#define SQLITE_SO_DESC      1  /* Sort in ascending order */

/*
** Column affinity types.
**
** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
** the speed a little by numbering the values consecutively.  
**
** But rather than start with 0 or 1, we begin with 'a'.  That way,
** when multiple affinity types are concatenated into a string and
** used as the P4 operand, they will be more readable.
**
** Note also that the numeric types are grouped together so that testing
** for a numeric type is a single comparison.
*/
#define SQLITE_AFF_TEXT     'a'
#define SQLITE_AFF_NONE     'b'
#define SQLITE_AFF_NUMERIC  'c'
#define SQLITE_AFF_INTEGER  'd'
#define SQLITE_AFF_REAL     'e'

#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)

/*
** The SQLITE_AFF_MASK values masks off the significant bits of an
** affinity value. 
*/
#define SQLITE_AFF_MASK     0x67

/*
** Additional bit values that can be ORed with an affinity without
** changing the affinity.
*/
#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
#define SQLITE_NULLEQ       0x80  /* NULL=NULL */

/*
** An object of this type is created for each virtual table present in
** the database schema. 
**
** If the database schema is shared, then there is one instance of this
** structure for each database connection (sqlite3*) that uses the shared
** schema. This is because each database connection requires its own unique
** instance of the sqlite3_vtab* handle used to access the virtual table 
** implementation. sqlite3_vtab* handles can not be shared between 
** database connections, even when the rest of the in-memory database 
** schema is shared, as the implementation often stores the database
** connection handle passed to it via the xConnect() or xCreate() method
** during initialization internally. This database connection handle may
** then used by the virtual table implementation to access real tables 
** within the database. So that they appear as part of the callers 
** transaction, these accesses need to be made via the same database 
** connection as that used to execute SQL operations on the virtual table.
**
** All VTable objects that correspond to a single table in a shared
** database schema are initially stored in a linked-list pointed to by
** the Table.pVTable member variable of the corresponding Table object.
** When an sqlite3_prepare() operation is required to access the virtual
** table, it searches the list for the VTable that corresponds to the
** database connection doing the preparing so as to use the correct
** sqlite3_vtab* handle in the compiled query.
**
** When an in-memory Table object is deleted (for example when the
** schema is being reloaded for some reason), the VTable objects are not 
** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
** immediately. Instead, they are moved from the Table.pVTable list to
** another linked list headed by the sqlite3.pDisconnect member of the
** corresponding sqlite3 structure. They are then deleted/xDisconnected 
** next time a statement is prepared using said sqlite3*. This is done
** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
** Refer to comments above function sqlite3VtabUnlockList() for an
** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
** list without holding the corresponding sqlite3.mutex mutex.
**
** The memory for objects of this type is always allocated by 
** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
** the first argument.
*/
struct VTable {
  sqlite3 *db;              /* Database connection associated with this table */
  Module *pMod;             /* Pointer to module implementation */
  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
  int nRef;                 /* Number of pointers to this structure */
  VTable *pNext;            /* Next in linked list (see above) */
};

/*
** Each SQL table is represented in memory by an instance of the
** following structure.
**
** Table.zName is the name of the table.  The case of the original
** CREATE TABLE statement is stored, but case is not significant for
** comparisons.
**
** Table.nCol is the number of columns in this table.  Table.aCol is a
** pointer to an array of Column structures, one for each column.
**
** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
** the column that is that key.   Otherwise Table.iPKey is negative.  Note
** that the datatype of the PRIMARY KEY must be INTEGER for this field to
** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
** is generated for each row of the table.  TF_HasPrimaryKey is set if
** the table has any PRIMARY KEY, INTEGER or otherwise.
**
** Table.tnum is the page number for the root BTree page of the table in the
** database file.  If Table.iDb is the index of the database table backend
** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
** holds temporary tables and indices.  If TF_Ephemeral is set
** then the table is stored in a file that is automatically deleted
** when the VDBE cursor to the table is closed.  In this case Table.tnum 
** refers VDBE cursor number that holds the table open, not to the root
** page number.  Transient tables are used to hold the results of a
** sub-query that appears instead of a real table name in the FROM clause 
** of a SELECT statement.
*/
struct Table {
  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
  char *zName;         /* Name of the table or view */
  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
  int nCol;            /* Number of columns in this table */
  Column *aCol;        /* Information about each column */
  Index *pIndex;       /* List of SQL indexes on this table. */
  int tnum;            /* Root BTree node for this table (see note above) */
  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
  u16 nRef;            /* Number of pointers to this Table */
  u8 tabFlags;         /* Mask of TF_* values */
  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
  FKey *pFKey;         /* Linked list of all foreign keys in this table */
  char *zColAff;       /* String defining the affinity of each column */
#ifndef SQLITE_OMIT_CHECK
  Expr *pCheck;        /* The AND of all CHECK constraints */
#endif
#ifndef SQLITE_OMIT_ALTERTABLE
  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
  VTable *pVTable;     /* List of VTable objects. */
  int nModuleArg;      /* Number of arguments to the module */
  char **azModuleArg;  /* Text of all module args. [0] is module name */
#endif
  Trigger *pTrigger;   /* List of triggers stored in pSchema */
  Schema *pSchema;     /* Schema that contains this table */
  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
};

/*
** Allowed values for Tabe.tabFlags.
*/
#define TF_Readonly        0x01    /* Read-only system table */
#define TF_Ephemeral       0x02    /* An ephemeral table */
#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
#define TF_Virtual         0x10    /* Is a virtual table */
#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */



/*
** Test to see whether or not a table is a virtual table.  This is
** done as a macro so that it will be optimized out when virtual
** table support is omitted from the build.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
#  define IsHiddenColumn(X) ((X)->isHidden)
#else
#  define IsVirtual(X)      0
#  define IsHiddenColumn(X) 0
#endif

/*
** Each foreign key constraint is an instance of the following structure.
**
** A foreign key is associated with two tables.  The "from" table is
** the table that contains the REFERENCES clause that creates the foreign
** key.  The "to" table is the table that is named in the REFERENCES clause.
** Consider this example:
**
**     CREATE TABLE ex1(
**       a INTEGER PRIMARY KEY,
**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
**     );
**
** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
**
** Each REFERENCES clause generates an instance of the following structure
** which is attached to the from-table.  The to-table need not exist when
** the from-table is created.  The existence of the to-table is not checked.
*/
struct FKey {
  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
  FKey *pNextFrom;  /* Next foreign key in pFrom */
  char *zTo;        /* Name of table that the key points to (aka: Parent) */
  FKey *pNextTo;    /* Next foreign key on table named zTo */
  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
  int nCol;         /* Number of columns in this key */
  /* EV: R-30323-21917 */
  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
    int iFrom;         /* Index of column in pFrom */
    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
  } aCol[1];        /* One entry for each of nCol column s */
};

/*
** SQLite supports many different ways to resolve a constraint
** error.  ROLLBACK processing means that a constraint violation
** causes the operation in process to fail and for the current transaction
** to be rolled back.  ABORT processing means the operation in process
** fails and any prior changes from that one operation are backed out,
** but the transaction is not rolled back.  FAIL processing means that
** the operation in progress stops and returns an error code.  But prior
** changes due to the same operation are not backed out and no rollback
** occurs.  IGNORE means that the particular row that caused the constraint
** error is not inserted or updated.  Processing continues and no error
** is returned.  REPLACE means that preexisting database rows that caused
** a UNIQUE constraint violation are removed so that the new insert or
** update can proceed.  Processing continues and no error is reported.
**
** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
** referenced table row is propagated into the row that holds the
** foreign key.
** 
** The following symbolic values are used to record which type
** of action to take.
*/
#define OE_None     0   /* There is no constraint to check */
#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
#define OE_Abort    2   /* Back out changes but do no rollback transaction */
#define OE_Fail     3   /* Stop the operation but leave all prior changes */
#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */

#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
#define OE_SetNull  7   /* Set the foreign key value to NULL */
#define OE_SetDflt  8   /* Set the foreign key value to its default */
#define OE_Cascade  9   /* Cascade the changes */

#define OE_Default  99  /* Do whatever the default action is */


/*
** An instance of the following structure is passed as the first
** argument to sqlite3VdbeKeyCompare and is used to control the 
** comparison of the two index keys.
*/
struct KeyInfo {
  sqlite3 *db;        /* The database connection */
  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
  u16 nField;         /* Number of entries in aColl[] */
  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
};

/*
** An instance of the following structure holds information about a
** single index record that has already been parsed out into individual
** values.
**
** A record is an object that contains one or more fields of data.
** Records are used to store the content of a table row and to store
** the key of an index.  A blob encoding of a record is created by
** the OP_MakeRecord opcode of the VDBE and is disassembled by the
** OP_Column opcode.
**
** This structure holds a record that has already been disassembled
** into its constituent fields.
*/
struct UnpackedRecord {
  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
  u16 nField;         /* Number of entries in apMem[] */
  u16 flags;          /* Boolean settings.  UNPACKED_... below */
  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
  Mem *aMem;          /* Values */
};

/*
** Allowed values of UnpackedRecord.flags
*/
#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */

/*
** Each SQL index is represented in memory by an
** instance of the following structure.
**
** The columns of the table that are to be indexed are described
** by the aiColumn[] field of this structure.  For example, suppose
** we have the following table and index:
**
**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
**     CREATE INDEX Ex2 ON Ex1(c3,c1);
**
** In the Table structure describing Ex1, nCol==3 because there are
** three columns in the table.  In the Index structure describing
** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
** The second column to be indexed (c1) has an index of 0 in
** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
**
** The Index.onError field determines whether or not the indexed columns
** must be unique and what to do if they are not.  When Index.onError=OE_None,
** it means this is not a unique index.  Otherwise it is a unique index
** and the value of Index.onError indicate the which conflict resolution 
** algorithm to employ whenever an attempt is made to insert a non-unique
** element.
*/
struct Index {
  char *zName;     /* Name of this index */
  int nColumn;     /* Number of columns in the table used by this index */
  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  Table *pTable;   /* The SQL table being indexed */
  int tnum;        /* Page containing root of this index in database file */
  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
  char *zColAff;   /* String defining the affinity of each column */
  Index *pNext;    /* The next index associated with the same table */
  Schema *pSchema; /* Schema containing this index */
  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
  char **azColl;   /* Array of collation sequence names for index */
  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
};

/*
** Each sample stored in the sqlite_stat2 table is represented in memory 
** using a structure of this type.
*/
struct IndexSample {
  union {
    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
  } u;
  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
  u8 nByte;         /* Size in byte of text or blob. */
};

/*
** Each token coming out of the lexer is an instance of
** this structure.  Tokens are also used as part of an expression.
**
** Note if Token.z==0 then Token.dyn and Token.n are undefined and
** may contain random values.  Do not make any assumptions about Token.dyn
** and Token.n when Token.z==0.
*/
struct Token {
  const char *z;     /* Text of the token.  Not NULL-terminated! */
  unsigned int n;    /* Number of characters in this token */
};

/*
** An instance of this structure contains information needed to generate
** code for a SELECT that contains aggregate functions.
**
** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
** pointer to this structure.  The Expr.iColumn field is the index in
** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
** code for that node.
**
** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
** original Select structure that describes the SELECT statement.  These
** fields do not need to be freed when deallocating the AggInfo structure.
*/
struct AggInfo {
  u8 directMode;          /* Direct rendering mode means take data directly
                          ** from source tables rather than from accumulators */
  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
                          ** than the source table */
  int sortingIdx;         /* Cursor number of the sorting index */
  ExprList *pGroupBy;     /* The group by clause */
  int nSortingColumn;     /* Number of columns in the sorting index */
  struct AggInfo_col {    /* For each column used in source tables */
    Table *pTab;             /* Source table */
    int iTable;              /* Cursor number of the source table */
    int iColumn;             /* Column number within the source table */
    int iSorterColumn;       /* Column number in the sorting index */
    int iMem;                /* Memory location that acts as accumulator */
    Expr *pExpr;             /* The original expression */
  } *aCol;
  int nColumn;            /* Number of used entries in aCol[] */
  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
  int nAccumulator;       /* Number of columns that show through to the output.
                          ** Additional columns are used only as parameters to
                          ** aggregate functions */
  struct AggInfo_func {   /* For each aggregate function */
    Expr *pExpr;             /* Expression encoding the function */
    FuncDef *pFunc;          /* The aggregate function implementation */
    int iMem;                /* Memory location that acts as accumulator */
    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
  } *aFunc;
  int nFunc;              /* Number of entries in aFunc[] */
  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
};

/*
** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
** than 32767 we have to make it 32-bit.  16-bit is preferred because
** it uses less memory in the Expr object, which is a big memory user
** in systems with lots of prepared statements.  And few applications
** need more than about 10 or 20 variables.  But some extreme users want
** to have prepared statements with over 32767 variables, and for them
** the option is available (at compile-time).
*/
#if SQLITE_MAX_VARIABLE_NUMBER<=32767
typedef i64 ynVar;
#else
typedef int ynVar;
#endif

/*
** Each node of an expression in the parse tree is an instance
** of this structure.
**
** Expr.op is the opcode. The integer parser token codes are reused
** as opcodes here. For example, the parser defines TK_GE to be an integer
** code representing the ">=" operator. This same integer code is reused
** to represent the greater-than-or-equal-to operator in the expression
** tree.
**
** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
** or TK_STRING), then Expr.token contains the text of the SQL literal. If
** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
** then Expr.token contains the name of the function.
**
** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
** binary operator. Either or both may be NULL.
**
** Expr.x.pList is a list of arguments if the expression is an SQL function,
** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
** Expr.x.pSelect is used if the expression is a sub-select or an expression of
** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
** valid.
**
** An expression of the form ID or ID.ID refers to a column in a table.
** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
** the integer cursor number of a VDBE cursor pointing to that table and
** Expr.iColumn is the column number for the specific column.  If the
** expression is used as a result in an aggregate SELECT, then the
** value is also stored in the Expr.iAgg column in the aggregate so that
** it can be accessed after all aggregates are computed.
**
** If the expression is an unbound variable marker (a question mark 
** character '?' in the original SQL) then the Expr.iTable holds the index 
** number for that variable.
**
** If the expression is a subquery then Expr.iColumn holds an integer
** register number containing the result of the subquery.  If the
** subquery gives a constant result, then iTable is -1.  If the subquery
** gives a different answer at different times during statement processing
** then iTable is the address of a subroutine that computes the subquery.
**
** If the Expr is of type OP_Column, and the table it is selecting from
** is a disk table or the "old.*" pseudo-table, then pTab points to the
** corresponding table definition.
**
** ALLOCATION NOTES:
**
** Expr objects can use a lot of memory space in database schema.  To
** help reduce memory requirements, sometimes an Expr object will be
** truncated.  And to reduce the number of memory allocations, sometimes
** two or more Expr objects will be stored in a single memory allocation,
** together with Expr.zToken strings.
**
** If the EP_Reduced and EP_TokenOnly flags are set when
** an Expr object is truncated.  When EP_Reduced is set, then all
** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
** are contained within the same memory allocation.  Note, however, that
** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
** allocated, regardless of whether or not EP_Reduced is set.
*/
struct Expr {
  u8 op;                 /* Operation performed by this node */
  char affinity;         /* The affinity of the column or 0 if not a column */
  u16 flags;             /* Various flags.  EP_* See below */
  union {
    char *zToken;          /* Token value. Zero terminated and dequoted */
    int iValue;            /* Integer value if EP_IntValue */
  } u;

  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  ** space is allocated for the fields below this point. An attempt to
  ** access them will result in a segfault or malfunction. 
  *********************************************************************/

  Expr *pLeft;           /* Left subnode */
  Expr *pRight;          /* Right subnode */
  union {
    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
  } x;
  CollSeq *pColl;        /* The collation type of the column or 0 */

  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  ** space is allocated for the fields below this point. An attempt to
  ** access them will result in a segfault or malfunction.
  *********************************************************************/

  int iTable;            /* TK_COLUMN: cursor number of table holding column
                         ** TK_REGISTER: register number
                         ** TK_TRIGGER: 1 -> new, 0 -> old */
  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
                         ** TK_VARIABLE: variable number (always >= 1). */
  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
  u8 flags2;             /* Second set of flags.  EP2_... */
  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  Table *pTab;           /* Table for TK_COLUMN expressions. */
#if SQLITE_MAX_EXPR_DEPTH>0
  int nHeight;           /* Height of the tree headed by this node */
#endif
};

/*
** The following are the meanings of bits in the Expr.flags field.
*/
#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
#define EP_Error      0x0008  /* Expression contains one or more errors */
#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
#define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
#define EP_FixedDest  0x0400  /* Result needed in a specific register */
#define EP_IntValue   0x0800  /* Integer value contained in u.iValue */
#define EP_xIsSelect  0x1000  /* x.pSelect is valid (otherwise x.pList is) */

#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
#define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
#define EP_Static     0x8000  /* Held in memory not obtained from malloc() */

/*
** The following are the meanings of bits in the Expr.flags2 field.
*/
#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */

/*
** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
** flag on an expression structure.  This flag is used for VV&A only.  The
** routine is implemented as a macro that only works when in debugging mode,
** so as not to burden production code.
*/
#ifdef SQLITE_DEBUG
# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
#else
# define ExprSetIrreducible(X)
#endif

/*
** These macros can be used to test, set, or clear bits in the 
** Expr.flags field.
*/
#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
#define ExprSetProperty(E,P)     (E)->flags|=(P)
#define ExprClearProperty(E,P)   (E)->flags&=~(P)

/*
** Macros to determine the number of bytes required by a normal Expr 
** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
** and an Expr struct with the EP_TokenOnly flag set.
*/
#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */

/*
** Flags passed to the sqlite3ExprDup() function. See the header comment 
** above sqlite3ExprDup() for details.
*/
#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */

/*
** A list of expressions.  Each expression may optionally have a
** name.  An expr/name combination can be used in several ways, such
** as the list of "expr AS ID" fields following a "SELECT" or in the
** list of "ID = expr" items in an UPDATE.  A list of expressions can
** also be used as the argument to a function, in which case the a.zName
** field is not used.
*/
struct ExprList {
  int nExpr;             /* Number of expressions on the list */
  int nAlloc;            /* Number of entries allocated below */
  int iECursor;          /* VDBE Cursor associated with this ExprList */
  struct ExprList_item {
    Expr *pExpr;           /* The list of expressions */
    char *zName;           /* Token associated with this expression */
    char *zSpan;           /* Original text of the expression */
    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
    u8 done;               /* A flag to indicate when processing is finished */
    u16 iCol;              /* For ORDER BY, column number in result set */
    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
  } *a;                  /* One entry for each expression */
};

/*
** An instance of this structure is used by the parser to record both
** the parse tree for an expression and the span of input text for an
** expression.
*/
struct ExprSpan {
  Expr *pExpr;          /* The expression parse tree */
  const char *zStart;   /* First character of input text */
  const char *zEnd;     /* One character past the end of input text */
};

/*
** An instance of this structure can hold a simple list of identifiers,
** such as the list "a,b,c" in the following statements:
**
**      INSERT INTO t(a,b,c) VALUES ...;
**      CREATE INDEX idx ON t(a,b,c);
**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
**
** The IdList.a.idx field is used when the IdList represents the list of
** column names after a table name in an INSERT statement.  In the statement
**
**     INSERT INTO t(a,b,c) ...
**
** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
*/
struct IdList {
  struct IdList_item {
    char *zName;      /* Name of the identifier */
    int idx;          /* Index in some Table.aCol[] of a column named zName */
  } *a;
  int nId;         /* Number of identifiers on the list */
  int nAlloc;      /* Number of entries allocated for a[] below */
};

/*
** The bitmask datatype defined below is used for various optimizations.
**
** Changing this from a 64-bit to a 32-bit type limits the number of
** tables in a join to 32 instead of 64.  But it also reduces the size
** of the library by 738 bytes on ix86.
*/
typedef u64 Bitmask;

/*
** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
*/
#define BMS  ((int)(sizeof(Bitmask)*8))

/*
** The following structure describes the FROM clause of a SELECT statement.
** Each table or subquery in the FROM clause is a separate element of
** the SrcList.a[] array.
**
** With the addition of multiple database support, the following structure
** can also be used to describe a particular table such as the table that
** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
** such a table must be a simple name: ID.  But in SQLite, the table can
** now be identified by a database name, a dot, then the table name: ID.ID.
**
** The jointype starts out showing the join type between the current table
** and the next table on the list.  The parser builds the list this way.
** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
** jointype expresses the join between the table and the previous table.
*/
struct SrcList {
  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
  i16 nAlloc;      /* Number of entries allocated in a[] below */
  struct SrcList_item {
    char *zDatabase;  /* Name of database holding this table */
    char *zName;      /* Name of the table */
    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
    Table *pTab;      /* An SQL table corresponding to zName */
    Select *pSelect;  /* A SELECT statement used in place of a table name */
    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
    u8 jointype;      /* Type of join between this able and the previous */
    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
    int iCursor;      /* The VDBE cursor number used to access this table */
    Expr *pOn;        /* The ON clause of a join */
    IdList *pUsing;   /* The USING clause of a join */
    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
  } a[1];             /* One entry for each identifier on the list */
};

/*
** Permitted values of the SrcList.a.jointype field
*/
#define JT_INNER     0x0001    /* Any kind of inner or cross join */
#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
#define JT_NATURAL   0x0004    /* True for a "natural" join */
#define JT_LEFT      0x0008    /* Left outer join */
#define JT_RIGHT     0x0010    /* Right outer join */
#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
#define JT_ERROR     0x0040    /* unknown or unsupported join type */


/*
** A WherePlan object holds information that describes a lookup
** strategy.
**
** This object is intended to be opaque outside of the where.c module.
** It is included here only so that that compiler will know how big it
** is.  None of the fields in this object should be used outside of
** the where.c module.
**
** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
** case that more than one of these conditions is true.
*/
struct WherePlan {
  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
  u32 nEq;                       /* Number of == constraints */
  union {
    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
  } u;
};

/*
** For each nested loop in a WHERE clause implementation, the WhereInfo
** structure contains a single instance of this structure.  This structure
** is intended to be private the the where.c module and should not be
** access or modified by other modules.
**
** The pIdxInfo field is used to help pick the best index on a
** virtual table.  The pIdxInfo pointer contains indexing
** information for the i-th table in the FROM clause before reordering.
** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
** All other information in the i-th WhereLevel object for the i-th table
** after FROM clause ordering.
*/
struct WhereLevel {
  WherePlan plan;       /* query plan for this element of the FROM clause */
  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
  int iTabCur;          /* The VDBE cursor used to access the table */
  int iIdxCur;          /* The VDBE cursor used to access pIdx */
  int addrBrk;          /* Jump here to break out of the loop */
  int addrNxt;          /* Jump here to start the next IN combination */
  int addrCont;         /* Jump here to continue with the next loop cycle */
  int addrFirst;        /* First instruction of interior of the loop */
  u8 iFrom;             /* Which entry in the FROM clause */
  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
  int p1, p2;           /* Operands of the opcode used to ends the loop */
  union {               /* Information that depends on plan.wsFlags */
    struct {
      int nIn;              /* Number of entries in aInLoop[] */
      struct InLoop {
        int iCur;              /* The VDBE cursor used by this IN operator */
        int addrInTop;         /* Top of the IN loop */
      } *aInLoop;           /* Information about each nested IN operator */
    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
  } u;

  /* The following field is really not part of the current level.  But
  ** we need a place to cache virtual table index information for each
  ** virtual table in the FROM clause and the WhereLevel structure is
  ** a convenient place since there is one WhereLevel for each FROM clause
  ** element.
  */
  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
};

/*
** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
** and the WhereInfo.wctrlFlags member.
*/
#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
#define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */

/*
** The WHERE clause processing routine has two halves.  The
** first part does the start of the WHERE loop and the second
** half does the tail of the WHERE loop.  An instance of
** this structure is returned by the first half and passed
** into the second half to give some continuity.
*/
struct WhereInfo {
  Parse *pParse;       /* Parsing and code generating context */
  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
  SrcList *pTabList;             /* List of tables in the join */
  int iTop;                      /* The very beginning of the WHERE loop */
  int iContinue;                 /* Jump here to continue with next record */
  int iBreak;                    /* Jump here to break out of the loop */
  int nLevel;                    /* Number of nested loop */
  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
  WhereLevel a[1];               /* Information about each nest loop in WHERE */
};

/*
** A NameContext defines a context in which to resolve table and column
** names.  The context consists of a list of tables (the pSrcList) field and
** a list of named expression (pEList).  The named expression list may
** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
** to the table being operated on by INSERT, UPDATE, or DELETE.  The
** pEList corresponds to the result set of a SELECT and is NULL for
** other statements.
**
** NameContexts can be nested.  When resolving names, the inner-most 
** context is searched first.  If no match is found, the next outer
** context is checked.  If there is still no match, the next context
** is checked.  This process continues until either a match is found
** or all contexts are check.  When a match is found, the nRef member of
** the context containing the match is incremented. 
**
** Each subquery gets a new NameContext.  The pNext field points to the
** NameContext in the parent query.  Thus the process of scanning the
** NameContext list corresponds to searching through successively outer
** subqueries looking for a match.
*/
struct NameContext {
  Parse *pParse;       /* The parser */
  SrcList *pSrcList;   /* One or more tables used to resolve names */
  ExprList *pEList;    /* Optional list of named expressions */
  int nRef;            /* Number of names resolved by this context */
  int nErr;            /* Number of errors encountered while resolving names */
  u8 allowAgg;         /* Aggregate functions allowed here */
  u8 hasAgg;           /* True if aggregates are seen */
  u8 isCheck;          /* True if resolving names in a CHECK constraint */
  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
  AggInfo *pAggInfo;   /* Information about aggregates at this level */
  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
};

/*
** An instance of the following structure contains all information
** needed to generate code for a single SELECT statement.
**
** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
** If there is a LIMIT clause, the parser sets nLimit to the value of the
** limit and nOffset to the value of the offset (or 0 if there is not
** offset).  But later on, nLimit and nOffset become the memory locations
** in the VDBE that record the limit and offset counters.
**
** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
** These addresses must be stored so that we can go back and fill in
** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
** the number of columns in P2 can be computed at the same time
** as the OP_OpenEphm instruction is coded because not
** enough information about the compound query is known at that point.
** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
** sequences for the ORDER BY clause.
*/
struct Select {
  ExprList *pEList;      /* The fields of the result */
  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  char affinity;         /* MakeRecord with this affinity for SRT_Set */
  u16 selFlags;          /* Various SF_* values */
  SrcList *pSrc;         /* The FROM clause */
  Expr *pWhere;          /* The WHERE clause */
  ExprList *pGroupBy;    /* The GROUP BY clause */
  Expr *pHaving;         /* The HAVING clause */
  ExprList *pOrderBy;    /* The ORDER BY clause */
  Select *pPrior;        /* Prior select in a compound select statement */
  Select *pNext;         /* Next select to the left in a compound */
  Select *pRightmost;    /* Right-most select in a compound select statement */
  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
};

/*
** Allowed values for Select.selFlags.  The "SF" prefix stands for
** "Select Flag".
*/
#define SF_Distinct        0x0001  /* Output should be DISTINCT */
#define SF_Resolved        0x0002  /* Identifiers have been resolved */
#define SF_Aggregate       0x0004  /* Contains aggregate functions */
#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */


/*
** The results of a select can be distributed in several ways.  The
** "SRT" prefix means "SELECT Result Type".
*/
#define SRT_Union        1  /* Store result as keys in an index */
#define SRT_Except       2  /* Remove result from a UNION index */
#define SRT_Exists       3  /* Store 1 if the result is not empty */
#define SRT_Discard      4  /* Do not save the results anywhere */

/* The ORDER BY clause is ignored for all of the above */
#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)

#define SRT_Output       5  /* Output each row of result */
#define SRT_Mem          6  /* Store result in a memory cell */
#define SRT_Set          7  /* Store results as keys in an index */
#define SRT_Table        8  /* Store result as data with an automatic rowid */
#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
#define SRT_Coroutine   10  /* Generate a single row of result */

/*
** A structure used to customize the behavior of sqlite3Select(). See
** comments above sqlite3Select() for details.
*/
typedef struct SelectDest SelectDest;
struct SelectDest {
  u8 eDest;         /* How to dispose of the results */
  u8 affinity;      /* Affinity used when eDest==SRT_Set */
  int iParm;        /* A parameter used by the eDest disposal method */
  int iMem;         /* Base register where results are written */
  int nMem;         /* Number of registers allocated */
};

/*
** During code generation of statements that do inserts into AUTOINCREMENT 
** tables, the following information is attached to the Table.u.autoInc.p
** pointer of each autoincrement table to record some side information that
** the code generator needs.  We have to keep per-table autoincrement
** information in case inserts are down within triggers.  Triggers do not
** normally coordinate their activities, but we do need to coordinate the
** loading and saving of autoincrement information.
*/
struct AutoincInfo {
  AutoincInfo *pNext;   /* Next info block in a list of them all */
  Table *pTab;          /* Table this info block refers to */
  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
  int regCtr;           /* Memory register holding the rowid counter */
};

/*
** Size of the column cache
*/
#ifndef SQLITE_N_COLCACHE
# define SQLITE_N_COLCACHE 10
#endif

/*
** At least one instance of the following structure is created for each 
** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
** statement. All such objects are stored in the linked list headed at
** Parse.pTriggerPrg and deleted once statement compilation has been
** completed.
**
** A Vdbe sub-program that implements the body and WHEN clause of trigger
** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
** The Parse.pTriggerPrg list never contains two entries with the same
** values for both pTrigger and orconf.
**
** The TriggerPrg.oldmask variable is set to a mask of old.* columns
** accessed (or set to 0 for triggers fired as a result of INSERT 
** statements).
*/
struct TriggerPrg {
  Trigger *pTrigger;      /* Trigger this program was coded from */
  int orconf;             /* Default ON CONFLICT policy */
  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
  u32 oldmask;            /* Mask of old.* columns accessed */
  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
};

/*
** An SQL parser context.  A copy of this structure is passed through
** the parser and down into all the parser action routine in order to
** carry around information that is global to the entire parse.
**
** The structure is divided into two parts.  When the parser and code
** generate call themselves recursively, the first part of the structure
** is constant but the second part is reset at the beginning and end of
** each recursion.
**
** The nTableLock and aTableLock variables are only used if the shared-cache 
** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
** used to store the set of table-locks required by the statement being
** compiled. Function sqlite3TableLock() is used to add entries to the
** list.
*/
struct Parse {
  sqlite3 *db;         /* The main database structure */
  int rc;              /* Return code from execution */
  char *zErrMsg;       /* An error message */
  Vdbe *pVdbe;         /* An engine for executing database bytecode */
  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
  u8 nameClash;        /* A permanent table name clashes with temp table name */
  u8 checkSchema;      /* Causes schema cookie check after an error */
  u8 nested;           /* Number of nested calls to the parser/code generator */
  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
  int aTempReg[8];     /* Holding area for temporary registers */
  int nRangeReg;       /* Size of the temporary register block */
  int iRangeReg;       /* First register in temporary register block */
  int nErr;            /* Number of errors seen */
  int nTab;            /* Number of previously allocated VDBE cursors */
  int nMem;            /* Number of memory cells used so far */
  int nSet;            /* Number of sets used so far */
  int ckBase;          /* Base register of data during check constraints */
  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
  u8 nColCache;        /* Number of entries in the column cache */
  u8 iColCache;        /* Next entry of the cache to replace */
  struct yColCache {
    int iTable;           /* Table cursor number */
    int iColumn;          /* Table column number */
    u8 affChange;         /* True if this register has had an affinity change */
    u8 tempReg;           /* iReg is a temp register that needs to be freed */
    int iLevel;           /* Nesting level */
    int iReg;             /* Reg with value of this column. 0 means none. */
    int lru;              /* Least recently used entry has the smallest value */
  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
  u32 writeMask;       /* Start a write transaction on these databases */
  u32 cookieMask;      /* Bitmask of schema verified databases */
  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
  u8 mayAbort;         /* True if statement may throw an ABORT exception */
  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
#ifndef SQLITE_OMIT_SHARED_CACHE
  int nTableLock;        /* Number of locks in aTableLock */
  TableLock *aTableLock; /* Required table locks for shared-cache mode */
#endif
  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
  int regRoot;         /* Register holding root page number for new objects */
  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
  int nMaxArg;         /* Max args passed to user function by sub-program */

  /* Information used while coding trigger programs. */
  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
  Table *pTriggerTab;  /* Table triggers are being coded for */
  u32 oldmask;         /* Mask of old.* columns referenced */
  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
  u8 disableTriggers;  /* True to disable triggers */

  /* Above is constant between recursions.  Below is reset before and after
  ** each recursion */

  int nVar;            /* Number of '?' variables seen in the SQL so far */
  int nVarExpr;        /* Number of used slots in apVarExpr[] */
  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
  int nAlias;          /* Number of aliased result set columns */
  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
  int *aAlias;         /* Register used to hold aliased result */
  u8 explain;          /* True if the EXPLAIN flag is found on the query */
  Token sNameToken;    /* Token with unqualified schema object name */
  Token sLastToken;    /* The last token parsed */
  const char *zTail;   /* All SQL text past the last semicolon parsed */
  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  Token sArg;                /* Complete text of a module argument */
  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
  int nVtabLock;             /* Number of virtual tables to lock */
  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
#endif
  int nHeight;            /* Expression tree height of current sub-select */
  Table *pZombieTab;      /* List of Table objects to delete after code gen */
  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
};

#ifdef SQLITE_OMIT_VIRTUALTABLE
  #define IN_DECLARE_VTAB 0
#else
  #define IN_DECLARE_VTAB (pParse->declareVtab)
#endif

/*
** An instance of the following structure can be declared on a stack and used
** to save the Parse.zAuthContext value so that it can be restored later.
*/
struct AuthContext {
  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
  Parse *pParse;              /* The Parse structure */
};

/*
** Bitfield flags for P5 value in OP_Insert and OP_Delete
*/
#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */

/*
 * Each trigger present in the database schema is stored as an instance of
 * struct Trigger. 
 *
 * Pointers to instances of struct Trigger are stored in two ways.
 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
 *    database). This allows Trigger structures to be retrieved by name.
 * 2. All triggers associated with a single table form a linked list, using the
 *    pNext member of struct Trigger. A pointer to the first element of the
 *    linked list is stored as the "pTrigger" member of the associated
 *    struct Table.
 *
 * The "step_list" member points to the first element of a linked list
 * containing the SQL statements specified as the trigger program.
 */
struct Trigger {
  char *zName;            /* The name of the trigger                        */
  char *table;            /* The table or view to which the trigger applies */
  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
                             the <column-list> is stored here */
  Schema *pSchema;        /* Schema containing the trigger */
  Schema *pTabSchema;     /* Schema containing the table */
  TriggerStep *step_list; /* Link list of trigger program steps             */
  Trigger *pNext;         /* Next trigger associated with the table */
};

/*
** A trigger is either a BEFORE or an AFTER trigger.  The following constants
** determine which. 
**
** If there are multiple triggers, you might of some BEFORE and some AFTER.
** In that cases, the constants below can be ORed together.
*/
#define TRIGGER_BEFORE  1
#define TRIGGER_AFTER   2

/*
 * An instance of struct TriggerStep is used to store a single SQL statement
 * that is a part of a trigger-program. 
 *
 * Instances of struct TriggerStep are stored in a singly linked list (linked
 * using the "pNext" member) referenced by the "step_list" member of the 
 * associated struct Trigger instance. The first element of the linked list is
 * the first step of the trigger-program.
 * 
 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
 * "SELECT" statement. The meanings of the other members is determined by the 
 * value of "op" as follows:
 *
 * (op == TK_INSERT)
 * orconf    -> stores the ON CONFLICT algorithm
 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
 *              this stores a pointer to the SELECT statement. Otherwise NULL.
 * target    -> A token holding the quoted name of the table to insert into.
 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
 *              this stores values to be inserted. Otherwise NULL.
 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
 *              statement, then this stores the column-names to be
 *              inserted into.
 *
 * (op == TK_DELETE)
 * target    -> A token holding the quoted name of the table to delete from.
 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
 *              Otherwise NULL.
 * 
 * (op == TK_UPDATE)
 * target    -> A token holding the quoted name of the table to update rows of.
 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
 *              Otherwise NULL.
 * pExprList -> A list of the columns to update and the expressions to update
 *              them to. See sqlite3Update() documentation of "pChanges"
 *              argument.
 * 
 */
struct TriggerStep {
  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  u8 orconf;           /* OE_Rollback etc. */
  Trigger *pTrig;      /* The trigger that this step is a part of */
  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  Token target;        /* Target table for DELETE, UPDATE, INSERT */
  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
  IdList *pIdList;     /* Column names for INSERT */
  TriggerStep *pNext;  /* Next in the link-list */
  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
};

/*
** The following structure contains information used by the sqliteFix...
** routines as they walk the parse tree to make database references
** explicit.  
*/
typedef struct DbFixer DbFixer;
struct DbFixer {
  Parse *pParse;      /* The parsing context.  Error messages written here */
  const char *zDb;    /* Make sure all objects are contained in this database */
  const char *zType;  /* Type of the container - used for error messages */
  const Token *pName; /* Name of the container - used for error messages */
};

/*
** An objected used to accumulate the text of a string where we
** do not necessarily know how big the string will be in the end.
*/
struct StrAccum {
  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
  char *zBase;         /* A base allocation.  Not from malloc. */
  char *zText;         /* The string collected so far */
  int  nChar;          /* Length of the string so far */
  int  nAlloc;         /* Amount of space allocated in zText */
  int  mxAlloc;        /* Maximum allowed string length */
  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
  u8   useMalloc;      /* True if zText is enlargeable using realloc */
  u8   tooBig;         /* Becomes true if string size exceeds limits */
};

/*
** A pointer to this structure is used to communicate information
** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
*/
typedef struct {
  sqlite3 *db;        /* The database being initialized */
  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
  char **pzErrMsg;    /* Error message stored here */
  int rc;             /* Result code stored here */
} InitData;

/*
** Structure containing global configuration data for the SQLite library.
**
** This structure also contains some state information.
*/
struct Sqlite3Config {
  int bMemstat;                     /* True to enable memory status */
  int bCoreMutex;                   /* True to enable core mutexing */
  int bFullMutex;                   /* True to enable full mutexing */
  int mxStrlen;                     /* Maximum string length */
  int szLookaside;                  /* Default lookaside buffer size */
  int nLookaside;                   /* Default lookaside buffer count */
  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
  void *pHeap;                      /* Heap storage space */
  int nHeap;                        /* Size of pHeap[] */
  int mnReq, mxReq;                 /* Min and max heap requests sizes */
  void *pScratch;                   /* Scratch memory */
  int szScratch;                    /* Size of each scratch buffer */
  int nScratch;                     /* Number of scratch buffers */
  void *pPage;                      /* Page cache memory */
  int szPage;                       /* Size of each page in pPage[] */
  int nPage;                        /* Number of pages in pPage[] */
  int mxParserStack;                /* maximum depth of the parser stack */
  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
  /* The above might be initialized to non-zero.  The following need to always
  ** initially be zero, however. */
  int isInit;                       /* True after initialization has finished */
  int inProgress;                   /* True while initialization in progress */
  int isMutexInit;                  /* True after mutexes are initialized */
  int isMallocInit;                 /* True after malloc is initialized */
  int isPCacheInit;                 /* True after malloc is initialized */
  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
  int nRefInitMutex;                /* Number of users of pInitMutex */
};

/*
** Context pointer passed down through the tree-walk.
*/
struct Walker {
  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
  Parse *pParse;                            /* Parser context.  */
  union {                                   /* Extra data for callback */
    NameContext *pNC;                          /* Naming context */
    int i;                                     /* Integer value */
  } u;
};

/* Forward declarations */
int sqlite3WalkExpr(Walker*, Expr*);
int sqlite3WalkExprList(Walker*, ExprList*);
int sqlite3WalkSelect(Walker*, Select*);
int sqlite3WalkSelectExpr(Walker*, Select*);
int sqlite3WalkSelectFrom(Walker*, Select*);

/*
** Return code from the parse-tree walking primitives and their
** callbacks.
*/
#define WRC_Continue    0   /* Continue down into children */
#define WRC_Prune       1   /* Omit children but continue walking siblings */
#define WRC_Abort       2   /* Abandon the tree walk */

/*
** Assuming zIn points to the first byte of a UTF-8 character,
** advance zIn to point to the first byte of the next UTF-8 character.
*/
#define SQLITE_SKIP_UTF8(zIn) {                        \
  if( (*(zIn++))>=0xc0 ){                              \
    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
  }                                                    \
}

/*
** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
** builds) or a function call (for debugging).  If it is a function call,
** it allows the operator to set a breakpoint at the spot where database
** corruption is first detected.
*/
#ifdef SQLITE_DEBUG
  int sqlite3Corrupt(void);
# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
#else
# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
#endif

/*
** The ctype.h header is needed for non-ASCII systems.  It is also
** needed by FTS3 when FTS3 is included in the amalgamation.
*/
#if !defined(SQLITE_ASCII) || \
    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
# include <ctype.h>
#endif

/*
** The following macros mimic the standard library functions toupper(),
** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
** sqlite versions only work for ASCII characters, regardless of locale.
*/
#ifdef SQLITE_ASCII
# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
#else
# define sqlite3Toupper(x)   toupper((unsigned char)(x))
# define sqlite3Isspace(x)   isspace((unsigned char)(x))
# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
# define sqlite3Tolower(x)   tolower((unsigned char)(x))
#endif

/*
** Internal function prototypes
*/
int sqlite3StrICmp(const char *, const char *);
int sqlite3IsNumber(const char*, int*, u8);
int sqlite3Strlen30(const char*);
#define sqlite3StrNICmp sqlite3_strnicmp

int sqlite3MallocInit(void);
void sqlite3MallocEnd(void);
void *sqlite3Malloc(int);
void *sqlite3MallocZero(int);
void *sqlite3DbMallocZero(sqlite3*, int);
void *sqlite3DbMallocRaw(sqlite3*, int);
char *sqlite3DbStrDup(sqlite3*,const char*);
char *sqlite3DbStrNDup(sqlite3*,const char*, int);
void *sqlite3Realloc(void*, int);
void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
void *sqlite3DbRealloc(sqlite3 *, void *, int);
void sqlite3DbFree(sqlite3*, void*);
int sqlite3MallocSize(void*);
int sqlite3DbMallocSize(sqlite3*, void*);
void *sqlite3ScratchMalloc(int);
void sqlite3ScratchFree(void*);
void *sqlite3PageMalloc(int);
void sqlite3PageFree(void*);
void sqlite3MemSetDefault(void);
void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);

/*
** On systems with ample stack space and that support alloca(), make
** use of alloca() to obtain space for large automatic objects.  By default,
** obtain space from malloc().
**
** The alloca() routine never returns NULL.  This will cause code paths
** that deal with sqlite3StackAlloc() failures to be unreachable.
*/
#ifdef SQLITE_USE_ALLOCA
# define sqlite3StackAllocRaw(D,N)   alloca(N)
# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
# define sqlite3StackFree(D,P)       
#else
# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
#endif

#ifdef SQLITE_ENABLE_MEMSYS3
const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
#endif
#ifdef SQLITE_ENABLE_MEMSYS5
const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
#endif


#ifndef SQLITE_MUTEX_OMIT
  sqlite3_mutex_methods *sqlite3DefaultMutex(void);
  sqlite3_mutex *sqlite3MutexAlloc(int);
  int sqlite3MutexInit(void);
  int sqlite3MutexEnd(void);
#endif

int sqlite3StatusValue(int);
void sqlite3StatusAdd(int, int);
void sqlite3StatusSet(int, int);

int sqlite3IsNaN(double);

void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
char *sqlite3MPrintf(sqlite3*,const char*, ...);
char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  void sqlite3DebugPrintf(const char*, ...);
#endif
#if defined(SQLITE_TEST)
  void *sqlite3TestTextToPtr(const char*);
#endif
void sqlite3SetString(char **, sqlite3*, const char*, ...);
void sqlite3ErrorMsg(Parse*, const char*, ...);
void sqlite3ErrorClear(Parse*);
int sqlite3Dequote(char*);
int sqlite3KeywordCode(const unsigned char*, int);
int sqlite3RunParser(Parse*, const char*, char **);
void sqlite3FinishCoding(Parse*);
int sqlite3GetTempReg(Parse*);
void sqlite3ReleaseTempReg(Parse*,int);
int sqlite3GetTempRange(Parse*,int);
void sqlite3ReleaseTempRange(Parse*,int,int);
Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
Expr *sqlite3Expr(sqlite3*,int,const char*);
void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
void sqlite3ExprAssignVarNumber(Parse*, Expr*);
void sqlite3ExprClear(sqlite3*, Expr*);
void sqlite3ExprDelete(sqlite3*, Expr*);
ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
void sqlite3ExprListDelete(sqlite3*, ExprList*);
int sqlite3Init(sqlite3*, char**);
int sqlite3InitCallback(void*, int, char**, char**);
void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
void sqlite3ResetInternalSchema(sqlite3*, int);
void sqlite3BeginParse(Parse*,int);
void sqlite3CommitInternalChanges(sqlite3*);
Table *sqlite3ResultSetOfSelect(Parse*,Select*);
void sqlite3OpenMasterTable(Parse *, int);
void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
void sqlite3AddColumn(Parse*,Token*);
void sqlite3AddNotNull(Parse*, int);
void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
void sqlite3AddCheckConstraint(Parse*, Expr*);
void sqlite3AddColumnType(Parse*,Token*);
void sqlite3AddDefaultValue(Parse*,ExprSpan*);
void sqlite3AddCollateType(Parse*, Token*);
void sqlite3EndTable(Parse*,Token*,Token*,Select*);

Bitvec *sqlite3BitvecCreate(u32);
int sqlite3BitvecTest(Bitvec*, u32);
int sqlite3BitvecSet(Bitvec*, u32);
void sqlite3BitvecClear(Bitvec*, u32, void*);
void sqlite3BitvecDestroy(Bitvec*);
u32 sqlite3BitvecSize(Bitvec*);
int sqlite3BitvecBuiltinTest(int,int*);

RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
void sqlite3RowSetClear(RowSet*);
void sqlite3RowSetInsert(RowSet*, i64);
int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
int sqlite3RowSetNext(RowSet*, i64*);

void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);

#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  int sqlite3ViewGetColumnNames(Parse*,Table*);
#else
# define sqlite3ViewGetColumnNames(A,B) 0
#endif

void sqlite3DropTable(Parse*, SrcList*, int, int);
void sqlite3DeleteTable(Table*);
#ifndef SQLITE_OMIT_AUTOINCREMENT
  void sqlite3AutoincrementBegin(Parse *pParse);
  void sqlite3AutoincrementEnd(Parse *pParse);
#else
# define sqlite3AutoincrementBegin(X)
# define sqlite3AutoincrementEnd(X)
#endif
void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
int sqlite3IdListIndex(IdList*,const char*);
SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
                                      Token*, Select*, Expr*, IdList*);
void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
void sqlite3SrcListShiftJoinType(SrcList*);
void sqlite3SrcListAssignCursors(Parse*, SrcList*);
void sqlite3IdListDelete(sqlite3*, IdList*);
void sqlite3SrcListDelete(sqlite3*, SrcList*);
Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
                        Token*, int, int);
void sqlite3DropIndex(Parse*, SrcList*, int);
int sqlite3Select(Parse*, Select*, SelectDest*);
Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
                         Expr*,ExprList*,int,Expr*,Expr*);
void sqlite3SelectDelete(sqlite3*, Select*);
Table *sqlite3SrcListLookup(Parse*, SrcList*);
int sqlite3IsReadOnly(Parse*, Table*, int);
void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
#endif
void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
void sqlite3WhereEnd(WhereInfo*);
int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
void sqlite3ExprCodeMove(Parse*, int, int, int);
void sqlite3ExprCodeCopy(Parse*, int, int, int);
void sqlite3ExprCacheStore(Parse*, int, int, int);
void sqlite3ExprCachePush(Parse*);
void sqlite3ExprCachePop(Parse*, int);
void sqlite3ExprCacheRemove(Parse*, int);
void sqlite3ExprCacheClear(Parse*);
void sqlite3ExprCacheAffinityChange(Parse*, int, int);
void sqlite3ExprHardCopy(Parse*,int,int);
int sqlite3ExprCode(Parse*, Expr*, int);
int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
int sqlite3ExprCodeTarget(Parse*, Expr*, int);
int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
void sqlite3ExprCodeConstants(Parse*, Expr*);
int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
Table *sqlite3FindTable(sqlite3*,const char*, const char*);
Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
void sqlite3Vacuum(Parse*);
int sqlite3RunVacuum(char**, sqlite3*);
char *sqlite3NameFromToken(sqlite3*, Token*);
int sqlite3ExprCompare(Expr*, Expr*);
void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
Vdbe *sqlite3GetVdbe(Parse*);
void sqlite3PrngSaveState(void);
void sqlite3PrngRestoreState(void);
void sqlite3PrngResetState(void);
void sqlite3RollbackAll(sqlite3*);
void sqlite3CodeVerifySchema(Parse*, int);
void sqlite3BeginTransaction(Parse*, int);
void sqlite3CommitTransaction(Parse*);
void sqlite3RollbackTransaction(Parse*);
void sqlite3Savepoint(Parse*, int, Token*);
void sqlite3CloseSavepoints(sqlite3 *);
int sqlite3ExprIsConstant(Expr*);
int sqlite3ExprIsConstantNotJoin(Expr*);
int sqlite3ExprIsConstantOrFunction(Expr*);
int sqlite3ExprIsInteger(Expr*, int*);
int sqlite3IsRowid(const char*);
void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
                                     int*,int,int,int,int,int*);
void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
void sqlite3BeginWriteOperation(Parse*, int, int);
void sqlite3MultiWrite(Parse*);
void sqlite3MayAbort(Parse*);
void sqlite3HaltConstraint(Parse*, int, char*, int);
Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
IdList *sqlite3IdListDup(sqlite3*,IdList*);
Select *sqlite3SelectDup(sqlite3*,Select*,int);
void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
void sqlite3RegisterBuiltinFunctions(sqlite3*);
void sqlite3RegisterDateTimeFunctions(void);
void sqlite3RegisterGlobalFunctions(void);
#ifdef SQLITE_DEBUG
  int sqlite3SafetyOn(sqlite3*);
  int sqlite3SafetyOff(sqlite3*);
#else
# define sqlite3SafetyOn(A) 0
# define sqlite3SafetyOff(A) 0
#endif
int sqlite3SafetyCheckOk(sqlite3*);
int sqlite3SafetyCheckSickOrOk(sqlite3*);
void sqlite3ChangeCookie(Parse*, int);

#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
#endif

#ifndef SQLITE_OMIT_TRIGGER
  void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
                           Expr*,int, int);
  void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  void sqlite3DropTrigger(Parse*, SrcList*, int);
  void sqlite3DropTriggerPtr(Parse*, Trigger*);
  Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  Trigger *sqlite3TriggerList(Parse *, Table *);
  void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
                            int, int, int);
  void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
                                        ExprList*,Select*,u8);
  TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  u32 sqlite3TriggerOldmask(Parse*,Trigger*,ExprList*,Table*,int);
# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
#else
# define sqlite3TriggersExist(B,C,D,E,F) 0
# define sqlite3DeleteTrigger(A,B)
# define sqlite3DropTriggerPtr(A,B)
# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
# define sqlite3TriggerList(X, Y) 0
# define sqlite3ParseToplevel(p) p
# define sqlite3TriggerOldmask(A,B,C,D,E) 0
#endif

int sqlite3JoinType(Parse*, Token*, Token*, Token*);
void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
void sqlite3DeferForeignKey(Parse*, int);
#ifndef SQLITE_OMIT_AUTHORIZATION
  void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  void sqlite3AuthContextPop(AuthContext*);
  int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
#else
# define sqlite3AuthRead(a,b,c,d)
# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
# define sqlite3AuthContextPush(a,b,c)
# define sqlite3AuthContextPop(a)  ((void)(a))
#endif
void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
void sqlite3Detach(Parse*, Expr*);
int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
                       int omitJournal, int nCache, int flags, Btree **ppBtree);
int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
int sqlite3FixSrcList(DbFixer*, SrcList*);
int sqlite3FixSelect(DbFixer*, Select*);
int sqlite3FixExpr(DbFixer*, Expr*);
int sqlite3FixExprList(DbFixer*, ExprList*);
int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
int sqlite3AtoF(const char *z, double*);
int sqlite3GetInt32(const char *, int*);
int sqlite3FitsIn64Bits(const char *, int);
int sqlite3Utf16ByteLen(const void *pData, int nChar);
int sqlite3Utf8CharLen(const char *pData, int nByte);
int sqlite3Utf8Read(const u8*, const u8**);

/*
** Routines to read and write variable-length integers.  These used to
** be defined locally, but now we use the varint routines in the util.c
** file.  Code should use the MACRO forms below, as the Varint32 versions
** are coded to assume the single byte case is already handled (which 
** the MACRO form does).
*/
int sqlite3PutVarint(unsigned char*, u64);
int sqlite3PutVarint32(unsigned char*, u32);
u8 sqlite3GetVarint(const unsigned char *, u64 *);
u8 sqlite3GetVarint32(const unsigned char *, u32 *);
int sqlite3VarintLen(u64 v);

/*
** The header of a record consists of a sequence variable-length integers.
** These integers are almost always small and are encoded as a single byte.
** The following macros take advantage this fact to provide a fast encode
** and decode of the integers in a record header.  It is faster for the common
** case where the integer is a single byte.  It is a little slower when the
** integer is two or more bytes.  But overall it is faster.
**
** The following expressions are equivalent:
**
**     x = sqlite3GetVarint32( A, &B );
**     x = sqlite3PutVarint32( A, B );
**
**     x = getVarint32( A, B );
**     x = putVarint32( A, B );
**
*/
#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
#define getVarint    sqlite3GetVarint
#define putVarint    sqlite3PutVarint


const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
void sqlite3TableAffinityStr(Vdbe *, Table *);
char sqlite3CompareAffinity(Expr *pExpr, char aff2);
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
char sqlite3ExprAffinity(Expr *pExpr);
int sqlite3Atoi64(const char*, i64*);
void sqlite3Error(sqlite3*, int, const char*,...);
void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
const char *sqlite3ErrStr(int);
int sqlite3ReadSchema(Parse *pParse);
CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
int sqlite3CheckCollSeq(Parse *, CollSeq *);
int sqlite3CheckObjectName(Parse *, const char *);
void sqlite3VdbeSetChanges(sqlite3 *, int);

const void *sqlite3ValueText(sqlite3_value*, u8);
int sqlite3ValueBytes(sqlite3_value*, u8);
void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
                        void(*)(void*));
void sqlite3ValueFree(sqlite3_value*);
sqlite3_value *sqlite3ValueNew(sqlite3 *);
char *sqlite3Utf16to8(sqlite3 *, const void*, int);
#ifdef SQLITE_ENABLE_STAT2
char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
#endif
int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
#ifndef SQLITE_AMALGAMATION
extern const unsigned char sqlite3UpperToLower[];
extern const unsigned char sqlite3CtypeMap[];
extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
extern int sqlite3PendingByte;
#endif
void sqlite3RootPageMoved(Db*, int, int);
void sqlite3Reindex(Parse*, Token*, Token*);
void sqlite3AlterFunctions(sqlite3*);
void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
int sqlite3GetToken(const unsigned char *, int *);
void sqlite3NestedParse(Parse*, const char*, ...);
void sqlite3ExpirePreparedStatements(sqlite3*);
int sqlite3CodeSubselect(Parse *, Expr *, int, int);
void sqlite3SelectPrep(Parse*, Select*, NameContext*);
int sqlite3ResolveExprNames(NameContext*, Expr*);
void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
void sqlite3AlterFinishAddColumn(Parse *, Token *);
void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
char sqlite3AffinityType(const char*);
void sqlite3Analyze(Parse*, Token*, Token*);
int sqlite3InvokeBusyHandler(BusyHandler*);
int sqlite3FindDb(sqlite3*, Token*);
int sqlite3FindDbName(sqlite3 *, const char *);
int sqlite3AnalysisLoad(sqlite3*,int iDB);
void sqlite3DeleteIndexSamples(Index*);
void sqlite3DefaultRowEst(Index*);
void sqlite3RegisterLikeFunctions(sqlite3*, int);
int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
void sqlite3MinimumFileFormat(Parse*, int, int);
void sqlite3SchemaFree(void *);
Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
  void (*)(sqlite3_context*,int,sqlite3_value **),
  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
int sqlite3ApiExit(sqlite3 *db, int);
int sqlite3OpenTempDatabase(Parse *);

void sqlite3StrAccumInit(StrAccum*, char*, int, int);
void sqlite3StrAccumAppend(StrAccum*,const char*,int);
char *sqlite3StrAccumFinish(StrAccum*);
void sqlite3StrAccumReset(StrAccum*);
void sqlite3SelectDestInit(SelectDest*,int,int);
Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);

void sqlite3BackupRestart(sqlite3_backup *);
void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);

/*
** The interface to the LEMON-generated parser
*/
void *sqlite3ParserAlloc(void*(*)(size_t));
void sqlite3ParserFree(void*, void(*)(void*));
void sqlite3Parser(void*, int, Token, Parse*);
#ifdef YYTRACKMAXSTACKDEPTH
  int sqlite3ParserStackPeak(void*);
#endif

void sqlite3AutoLoadExtensions(sqlite3*);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
  void sqlite3CloseExtensions(sqlite3*);
#else
# define sqlite3CloseExtensions(X)
#endif

#ifndef SQLITE_OMIT_SHARED_CACHE
  void sqlite3TableLock(Parse *, int, int, u8, const char *);
#else
  #define sqlite3TableLock(v,w,x,y,z)
#endif

#ifdef SQLITE_TEST
  int sqlite3Utf8To8(unsigned char*);
#endif

#ifdef SQLITE_OMIT_VIRTUALTABLE
#  define sqlite3VtabClear(Y)
#  define sqlite3VtabSync(X,Y) SQLITE_OK
#  define sqlite3VtabRollback(X)
#  define sqlite3VtabCommit(X)
#  define sqlite3VtabInSync(db) 0
#  define sqlite3VtabLock(X) 
#  define sqlite3VtabUnlock(X)
#  define sqlite3VtabUnlockList(X)
#else
   void sqlite3VtabClear(Table*);
   int sqlite3VtabSync(sqlite3 *db, char **);
   int sqlite3VtabRollback(sqlite3 *db);
   int sqlite3VtabCommit(sqlite3 *db);
   void sqlite3VtabLock(VTable *);
   void sqlite3VtabUnlock(VTable *);
   void sqlite3VtabUnlockList(sqlite3*);
#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
#endif
void sqlite3VtabMakeWritable(Parse*,Table*);
void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
void sqlite3VtabFinishParse(Parse*, Token*);
void sqlite3VtabArgInit(Parse*);
void sqlite3VtabArgExtend(Parse*, Token*);
int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
int sqlite3VtabCallConnect(Parse*, Table*);
int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
int sqlite3VtabBegin(sqlite3 *, VTable *);
FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
int sqlite3Reprepare(Vdbe*);
void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
int sqlite3TempInMemory(const sqlite3*);
VTable *sqlite3GetVTable(sqlite3*, Table*);

/* Declarations for functions in fkey.c. All of these are replaced by
** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
** key functionality is available. If OMIT_TRIGGER is defined but
** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
** this case foreign keys are parsed, but no other functionality is 
** provided (enforcement of FK constraints requires the triggers sub-system).
*/
#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  void sqlite3FkCheck(Parse*, Table*, int, int);
  void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  void sqlite3FkActions(Parse*, Table*, ExprList*, int);
  int sqlite3FkRequired(Parse*, Table*, int*, int);
  u32 sqlite3FkOldmask(Parse*, Table*);
  FKey *sqlite3FkReferences(Table *);
#else
  #define sqlite3FkActions(a,b,c,d)
  #define sqlite3FkCheck(a,b,c,d)
  #define sqlite3FkDropTable(a,b,c)
  #define sqlite3FkOldmask(a,b)      0
  #define sqlite3FkRequired(a,b,c,d) 0
#endif
#ifndef SQLITE_OMIT_FOREIGN_KEY
  void sqlite3FkDelete(Table*);
#else
  #define sqlite3FkDelete(a)
#endif


/*
** Available fault injectors.  Should be numbered beginning with 0.
*/
#define SQLITE_FAULTINJECTOR_MALLOC     0
#define SQLITE_FAULTINJECTOR_COUNT      1

/*
** The interface to the code in fault.c used for identifying "benign"
** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
** is not defined.
*/
#ifndef SQLITE_OMIT_BUILTIN_TEST
  void sqlite3BeginBenignMalloc(void);
  void sqlite3EndBenignMalloc(void);
#else
  #define sqlite3BeginBenignMalloc()
  #define sqlite3EndBenignMalloc()
#endif

#define IN_INDEX_ROWID           1
#define IN_INDEX_EPH             2
#define IN_INDEX_INDEX           3
int sqlite3FindInIndex(Parse *, Expr *, int*);

#ifdef SQLITE_ENABLE_ATOMIC_WRITE
  int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  int sqlite3JournalSize(sqlite3_vfs *);
  int sqlite3JournalCreate(sqlite3_file *);
#else
  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
#endif

void sqlite3MemJournalOpen(sqlite3_file *);
int sqlite3MemJournalSize(void);
int sqlite3IsMemJournal(sqlite3_file *);

#if SQLITE_MAX_EXPR_DEPTH>0
  void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  int sqlite3SelectExprHeight(Select *);
  int sqlite3ExprCheckHeight(Parse*, int);
#else
  #define sqlite3ExprSetHeight(x,y)
  #define sqlite3SelectExprHeight(x) 0
  #define sqlite3ExprCheckHeight(x,y)
#endif

u32 sqlite3Get4byte(const u8*);
void sqlite3Put4byte(u8*, u32);

#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  void sqlite3ConnectionUnlocked(sqlite3 *db);
  void sqlite3ConnectionClosed(sqlite3 *db);
#else
  #define sqlite3ConnectionBlocked(x,y)
  #define sqlite3ConnectionUnlocked(x)
  #define sqlite3ConnectionClosed(x)
#endif

#ifdef SQLITE_DEBUG
  void sqlite3ParserTrace(FILE*, char *);
#endif

/*
** If the SQLITE_ENABLE IOTRACE exists then the global variable
** sqlite3IoTrace is a pointer to a printf-like routine used to
** print I/O tracing messages. 
*/
#ifdef SQLITE_ENABLE_IOTRACE
# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  void sqlite3VdbeIOTraceSql(Vdbe*);
SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
#else
# define IOTRACE(A)
# define sqlite3VdbeIOTraceSql(X)
#endif

#endif

Added src/sqliteLimit.h.



























































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*
** 2007 May 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** 
** This file defines various limits of what SQLite can process.
**
** @(#) $Id: sqliteLimit.h,v 1.10 2009/01/10 16:15:09 danielk1977 Exp $
*/

/*
** The maximum length of a TEXT or BLOB in bytes.   This also
** limits the size of a row in a table or index.
**
** The hard limit is the ability of a 32-bit signed integer
** to count the size: 2^31-1 or 2147483647.
*/
#ifndef SQLITE_MAX_LENGTH
# define SQLITE_MAX_LENGTH 1000000000
#endif

/*
** This is the maximum number of
**
**    * Columns in a table
**    * Columns in an index
**    * Columns in a view
**    * Terms in the SET clause of an UPDATE statement
**    * Terms in the result set of a SELECT statement
**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
**    * Terms in the VALUES clause of an INSERT statement
**
** The hard upper limit here is 32676.  Most database people will
** tell you that in a well-normalized database, you usually should
** not have more than a dozen or so columns in any table.  And if
** that is the case, there is no point in having more than a few
** dozen values in any of the other situations described above.
*/
#ifndef SQLITE_MAX_COLUMN
# define SQLITE_MAX_COLUMN 2000
#endif

/*
** The maximum length of a single SQL statement in bytes.
**
** It used to be the case that setting this value to zero would
** turn the limit off.  That is no longer true.  It is not possible
** to turn this limit off.
*/
#ifndef SQLITE_MAX_SQL_LENGTH
# define SQLITE_MAX_SQL_LENGTH 1000000000
#endif

/*
** The maximum depth of an expression tree. This is limited to 
** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
** want to place more severe limits on the complexity of an 
** expression.
**
** A value of 0 used to mean that the limit was not enforced.
** But that is no longer true.  The limit is now strictly enforced
** at all times.
*/
#ifndef SQLITE_MAX_EXPR_DEPTH
# define SQLITE_MAX_EXPR_DEPTH 1000
#endif

/*
** The maximum number of terms in a compound SELECT statement.
** The code generator for compound SELECT statements does one
** level of recursion for each term.  A stack overflow can result
** if the number of terms is too large.  In practice, most SQL
** never has more than 3 or 4 terms.  Use a value of 0 to disable
** any limit on the number of terms in a compount SELECT.
*/
#ifndef SQLITE_MAX_COMPOUND_SELECT
# define SQLITE_MAX_COMPOUND_SELECT 500
#endif

/*
** The maximum number of opcodes in a VDBE program.
** Not currently enforced.
*/
#ifndef SQLITE_MAX_VDBE_OP
# define SQLITE_MAX_VDBE_OP 25000
#endif

/*
** The maximum number of arguments to an SQL function.
*/
#ifndef SQLITE_MAX_FUNCTION_ARG
# define SQLITE_MAX_FUNCTION_ARG 127
#endif

/*
** The maximum number of in-memory pages to use for the main database
** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
*/
#ifndef SQLITE_DEFAULT_CACHE_SIZE
# define SQLITE_DEFAULT_CACHE_SIZE  2000
#endif
#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
#endif

/*
** The maximum number of attached databases.  This must be between 0
** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
** is used internally to track attached databases.
*/
#ifndef SQLITE_MAX_ATTACHED
# define SQLITE_MAX_ATTACHED 10
#endif


/*
** The maximum value of a ?nnn wildcard that the parser will accept.
*/
#ifndef SQLITE_MAX_VARIABLE_NUMBER
# define SQLITE_MAX_VARIABLE_NUMBER 999
#endif

/* Maximum page size.  The upper bound on this value is 32768.  This a limit
** imposed by the necessity of storing the value in a 2-byte unsigned integer
** and the fact that the page size must be a power of 2.
**
** If this limit is changed, then the compiled library is technically
** incompatible with an SQLite library compiled with a different limit. If
** a process operating on a database with a page-size of 65536 bytes 
** crashes, then an instance of SQLite compiled with the default page-size 
** limit will not be able to rollback the aborted transaction. This could
** lead to database corruption.
*/
#ifndef SQLITE_MAX_PAGE_SIZE
# define SQLITE_MAX_PAGE_SIZE 32768
#endif


/*
** The default size of a database page.
*/
#ifndef SQLITE_DEFAULT_PAGE_SIZE
# define SQLITE_DEFAULT_PAGE_SIZE 1024
#endif
#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
# undef SQLITE_DEFAULT_PAGE_SIZE
# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
#endif

/*
** Ordinarily, if no value is explicitly provided, SQLite creates databases
** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
** device characteristics (sector-size and atomic write() support),
** SQLite may choose a larger value. This constant is the maximum value
** SQLite will choose on its own.
*/
#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
#endif
#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
#endif


/*
** Maximum number of pages in one database file.
**
** This is really just the default value for the max_page_count pragma.
** This value can be lowered (or raised) at run-time using that the
** max_page_count macro.
*/
#ifndef SQLITE_MAX_PAGE_COUNT
# define SQLITE_MAX_PAGE_COUNT 1073741823
#endif

/*
** Maximum length (in bytes) of the pattern in a LIKE or GLOB
** operator.
*/
#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
#endif

/*
** Maximum depth of recursion for triggers.
**
** A value of 1 means that a trigger program will not be able to itself
** fire any triggers. A value of 0 means that no trigger programs at all 
** may be executed.
*/
#ifndef SQLITE_MAX_TRIGGER_DEPTH
#if defined(SQLITE_SMALL_STACK)
# define SQLITE_MAX_TRIGGER_DEPTH 10
#else
# define SQLITE_MAX_TRIGGER_DEPTH 1000
#endif
#endif

Added src/status.c.





















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
** 2008 June 18
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This module implements the sqlite3_status() interface and related
** functionality.
**
** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
*/
#include "sqliteInt.h"

/*
** Variables in which to record status information.
*/
typedef struct sqlite3StatType sqlite3StatType;
static SQLITE_WSD struct sqlite3StatType {
  int nowValue[9];         /* Current value */
  int mxValue[9];          /* Maximum value */
} sqlite3Stat = { {0,}, {0,} };


/* The "wsdStat" macro will resolve to the status information
** state vector.  If writable static data is unsupported on the target,
** we have to locate the state vector at run-time.  In the more common
** case where writable static data is supported, wsdStat can refer directly
** to the "sqlite3Stat" state vector declared above.
*/
#ifdef SQLITE_OMIT_WSD
# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
# define wsdStat x[0]
#else
# define wsdStatInit
# define wsdStat sqlite3Stat
#endif

/*
** Return the current value of a status parameter.
*/
int sqlite3StatusValue(int op){
  wsdStatInit;
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  return wsdStat.nowValue[op];
}

/*
** Add N to the value of a status record.  It is assumed that the
** caller holds appropriate locks.
*/
void sqlite3StatusAdd(int op, int N){
  wsdStatInit;
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  wsdStat.nowValue[op] += N;
  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
  }
}

/*
** Set the value of a status to X.
*/
void sqlite3StatusSet(int op, int X){
  wsdStatInit;
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  wsdStat.nowValue[op] = X;
  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
  }
}

/*
** Query status information.
**
** This implementation assumes that reading or writing an aligned
** 32-bit integer is an atomic operation.  If that assumption is not true,
** then this routine is not threadsafe.
*/
int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  wsdStatInit;
  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
    return SQLITE_MISUSE;
  }
  *pCurrent = wsdStat.nowValue[op];
  *pHighwater = wsdStat.mxValue[op];
  if( resetFlag ){
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
  }
  return SQLITE_OK;
}

/*
** Query status information for a single database connection
*/
int sqlite3_db_status(
  sqlite3 *db,          /* The database connection whose status is desired */
  int op,               /* Status verb */
  int *pCurrent,        /* Write current value here */
  int *pHighwater,      /* Write high-water mark here */
  int resetFlag         /* Reset high-water mark if true */
){
  switch( op ){
    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
      *pCurrent = db->lookaside.nOut;
      *pHighwater = db->lookaside.mxOut;
      if( resetFlag ){
        db->lookaside.mxOut = db->lookaside.nOut;
      }
      break;
    }
    default: {
      return SQLITE_ERROR;
    }
  }
  return SQLITE_OK;
}

Added src/table.c.















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the sqlite3_get_table() and sqlite3_free_table()
** interface routines.  These are just wrappers around the main
** interface routine of sqlite3_exec().
**
** These routines are in a separate files so that they will not be linked
** if they are not used.
**
** $Id: table.c,v 1.40 2009/04/10 14:28:00 drh Exp $
*/
#include "sqliteInt.h"
#include <stdlib.h>
#include <string.h>

#ifndef SQLITE_OMIT_GET_TABLE

/*
** This structure is used to pass data from sqlite3_get_table() through
** to the callback function is uses to build the result.
*/
typedef struct TabResult {
  char **azResult;   /* Accumulated output */
  char *zErrMsg;     /* Error message text, if an error occurs */
  int nAlloc;        /* Slots allocated for azResult[] */
  int nRow;          /* Number of rows in the result */
  int nColumn;       /* Number of columns in the result */
  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
  int rc;            /* Return code from sqlite3_exec() */
} TabResult;

/*
** This routine is called once for each row in the result table.  Its job
** is to fill in the TabResult structure appropriately, allocating new
** memory as necessary.
*/
static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
  int need;                         /* Slots needed in p->azResult[] */
  int i;                            /* Loop counter */
  char *z;                          /* A single column of result */

  /* Make sure there is enough space in p->azResult to hold everything
  ** we need to remember from this invocation of the callback.
  */
  if( p->nRow==0 && argv!=0 ){
    need = nCol*2;
  }else{
    need = nCol;
  }
  if( p->nData + need > p->nAlloc ){
    char **azNew;
    p->nAlloc = p->nAlloc*2 + need;
    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
    if( azNew==0 ) goto malloc_failed;
    p->azResult = azNew;
  }

  /* If this is the first row, then generate an extra row containing
  ** the names of all columns.
  */
  if( p->nRow==0 ){
    p->nColumn = nCol;
    for(i=0; i<nCol; i++){
      z = sqlite3_mprintf("%s", colv[i]);
      if( z==0 ) goto malloc_failed;
      p->azResult[p->nData++] = z;
    }
  }else if( p->nColumn!=nCol ){
    sqlite3_free(p->zErrMsg);
    p->zErrMsg = sqlite3_mprintf(
       "sqlite3_get_table() called with two or more incompatible queries"
    );
    p->rc = SQLITE_ERROR;
    return 1;
  }

  /* Copy over the row data
  */
  if( argv!=0 ){
    for(i=0; i<nCol; i++){
      if( argv[i]==0 ){
        z = 0;
      }else{
        int n = sqlite3Strlen30(argv[i])+1;
        z = sqlite3_malloc( n );
        if( z==0 ) goto malloc_failed;
        memcpy(z, argv[i], n);
      }
      p->azResult[p->nData++] = z;
    }
    p->nRow++;
  }
  return 0;

malloc_failed:
  p->rc = SQLITE_NOMEM;
  return 1;
}

/*
** Query the database.  But instead of invoking a callback for each row,
** malloc() for space to hold the result and return the entire results
** at the conclusion of the call.
**
** The result that is written to ***pazResult is held in memory obtained
** from malloc().  But the caller cannot free this memory directly.  
** Instead, the entire table should be passed to sqlite3_free_table() when
** the calling procedure is finished using it.
*/
int sqlite3_get_table(
  sqlite3 *db,                /* The database on which the SQL executes */
  const char *zSql,           /* The SQL to be executed */
  char ***pazResult,          /* Write the result table here */
  int *pnRow,                 /* Write the number of rows in the result here */
  int *pnColumn,              /* Write the number of columns of result here */
  char **pzErrMsg             /* Write error messages here */
){
  int rc;
  TabResult res;

  *pazResult = 0;
  if( pnColumn ) *pnColumn = 0;
  if( pnRow ) *pnRow = 0;
  if( pzErrMsg ) *pzErrMsg = 0;
  res.zErrMsg = 0;
  res.nRow = 0;
  res.nColumn = 0;
  res.nData = 1;
  res.nAlloc = 20;
  res.rc = SQLITE_OK;
  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  if( res.azResult==0 ){
     db->errCode = SQLITE_NOMEM;
     return SQLITE_NOMEM;
  }
  res.azResult[0] = 0;
  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  if( (rc&0xff)==SQLITE_ABORT ){
    sqlite3_free_table(&res.azResult[1]);
    if( res.zErrMsg ){
      if( pzErrMsg ){
        sqlite3_free(*pzErrMsg);
        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
      }
      sqlite3_free(res.zErrMsg);
    }
    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
    return res.rc;
  }
  sqlite3_free(res.zErrMsg);
  if( rc!=SQLITE_OK ){
    sqlite3_free_table(&res.azResult[1]);
    return rc;
  }
  if( res.nAlloc>res.nData ){
    char **azNew;
    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
    if( azNew==0 ){
      sqlite3_free_table(&res.azResult[1]);
      db->errCode = SQLITE_NOMEM;
      return SQLITE_NOMEM;
    }
    res.azResult = azNew;
  }
  *pazResult = &res.azResult[1];
  if( pnColumn ) *pnColumn = res.nColumn;
  if( pnRow ) *pnRow = res.nRow;
  return rc;
}

/*
** This routine frees the space the sqlite3_get_table() malloced.
*/
void sqlite3_free_table(
  char **azResult            /* Result returned from from sqlite3_get_table() */
){
  if( azResult ){
    int i, n;
    azResult--;
    assert( azResult!=0 );
    n = SQLITE_PTR_TO_INT(azResult[0]);
    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
    sqlite3_free(azResult);
  }
}

#endif /* SQLITE_OMIT_GET_TABLE */

Added src/tclsqlite.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** A TCL Interface to SQLite.  Append this file to sqlite3.c and
** compile the whole thing to build a TCL-enabled version of SQLite.
**
** Compile-time options:
**
**  -DTCLSH=1             Add a "main()" routine that works as a tclsh.
**
**  -DSQLITE_TCLMD5       When used in conjuction with -DTCLSH=1, add
**                        four new commands to the TCL interpreter for
**                        generating MD5 checksums:  md5, md5file,
**                        md5-10x8, and md5file-10x8.
**
**  -DSQLITE_TEST         When used in conjuction with -DTCLSH=1, add
**                        hundreds of new commands used for testing
**                        SQLite.  This option implies -DSQLITE_TCLMD5.
*/
#include "tcl.h"
#include <errno.h>

/*
** Some additional include files are needed if this file is not
** appended to the amalgamation.
*/
#ifndef SQLITE_AMALGAMATION
# include "sqliteInt.h"
# include <stdlib.h>
# include <string.h>
# include <assert.h>
#endif
#include <ctype.h>

/*
 * Windows needs to know which symbols to export.  Unix does not.
 * BUILD_sqlite should be undefined for Unix.
 */
#ifdef BUILD_sqlite
#undef TCL_STORAGE_CLASS
#define TCL_STORAGE_CLASS DLLEXPORT
#endif /* BUILD_sqlite */

#define NUM_PREPARED_STMTS 10
#define MAX_PREPARED_STMTS 100

/*
** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
** have to do a translation when going between the two.  Set the 
** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
** this translation.  
*/
#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
# define UTF_TRANSLATION_NEEDED 1
#endif

/*
** New SQL functions can be created as TCL scripts.  Each such function
** is described by an instance of the following structure.
*/
typedef struct SqlFunc SqlFunc;
struct SqlFunc {
  Tcl_Interp *interp;   /* The TCL interpret to execute the function */
  Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
  int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
  char *zName;          /* Name of this function */
  SqlFunc *pNext;       /* Next function on the list of them all */
};

/*
** New collation sequences function can be created as TCL scripts.  Each such
** function is described by an instance of the following structure.
*/
typedef struct SqlCollate SqlCollate;
struct SqlCollate {
  Tcl_Interp *interp;   /* The TCL interpret to execute the function */
  char *zScript;        /* The script to be run */
  SqlCollate *pNext;    /* Next function on the list of them all */
};

/*
** Prepared statements are cached for faster execution.  Each prepared
** statement is described by an instance of the following structure.
*/
typedef struct SqlPreparedStmt SqlPreparedStmt;
struct SqlPreparedStmt {
  SqlPreparedStmt *pNext;  /* Next in linked list */
  SqlPreparedStmt *pPrev;  /* Previous on the list */
  sqlite3_stmt *pStmt;     /* The prepared statement */
  int nSql;                /* chars in zSql[] */
  const char *zSql;        /* Text of the SQL statement */
  int nParm;               /* Size of apParm array */
  Tcl_Obj **apParm;        /* Array of referenced object pointers */
};

typedef struct IncrblobChannel IncrblobChannel;

/*
** There is one instance of this structure for each SQLite database
** that has been opened by the SQLite TCL interface.
*/
typedef struct SqliteDb SqliteDb;
struct SqliteDb {
  sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
  Tcl_Interp *interp;        /* The interpreter used for this database */
  char *zBusy;               /* The busy callback routine */
  char *zCommit;             /* The commit hook callback routine */
  char *zTrace;              /* The trace callback routine */
  char *zProfile;            /* The profile callback routine */
  char *zProgress;           /* The progress callback routine */
  char *zAuth;               /* The authorization callback routine */
  int disableAuth;           /* Disable the authorizer if it exists */
  char *zNull;               /* Text to substitute for an SQL NULL value */
  SqlFunc *pFunc;            /* List of SQL functions */
  Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
  Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
  Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
  SqlCollate *pCollate;      /* List of SQL collation functions */
  int rc;                    /* Return code of most recent sqlite3_exec() */
  Tcl_Obj *pCollateNeeded;   /* Collation needed script */
  SqlPreparedStmt *stmtList; /* List of prepared statements*/
  SqlPreparedStmt *stmtLast; /* Last statement in the list */
  int maxStmt;               /* The next maximum number of stmtList */
  int nStmt;                 /* Number of statements in stmtList */
  IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
  int nStep, nSort;          /* Statistics for most recent operation */
  int nTransaction;          /* Number of nested [transaction] methods */
};

struct IncrblobChannel {
  sqlite3_blob *pBlob;      /* sqlite3 blob handle */
  SqliteDb *pDb;            /* Associated database connection */
  int iSeek;                /* Current seek offset */
  Tcl_Channel channel;      /* Channel identifier */
  IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
  IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
};

/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
*/
static int strlen30(const char *z){
  const char *z2 = z;
  while( *z2 ){ z2++; }
  return 0x3fffffff & (int)(z2 - z);
}


#ifndef SQLITE_OMIT_INCRBLOB
/*
** Close all incrblob channels opened using database connection pDb.
** This is called when shutting down the database connection.
*/
static void closeIncrblobChannels(SqliteDb *pDb){
  IncrblobChannel *p;
  IncrblobChannel *pNext;

  for(p=pDb->pIncrblob; p; p=pNext){
    pNext = p->pNext;

    /* Note: Calling unregister here call Tcl_Close on the incrblob channel, 
    ** which deletes the IncrblobChannel structure at *p. So do not
    ** call Tcl_Free() here.
    */
    Tcl_UnregisterChannel(pDb->interp, p->channel);
  }
}

/*
** Close an incremental blob channel.
*/
static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
  IncrblobChannel *p = (IncrblobChannel *)instanceData;
  int rc = sqlite3_blob_close(p->pBlob);
  sqlite3 *db = p->pDb->db;

  /* Remove the channel from the SqliteDb.pIncrblob list. */
  if( p->pNext ){
    p->pNext->pPrev = p->pPrev;
  }
  if( p->pPrev ){
    p->pPrev->pNext = p->pNext;
  }
  if( p->pDb->pIncrblob==p ){
    p->pDb->pIncrblob = p->pNext;
  }

  /* Free the IncrblobChannel structure */
  Tcl_Free((char *)p);

  if( rc!=SQLITE_OK ){
    Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Read data from an incremental blob channel.
*/
static int incrblobInput(
  ClientData instanceData, 
  char *buf, 
  int bufSize,
  int *errorCodePtr
){
  IncrblobChannel *p = (IncrblobChannel *)instanceData;
  int nRead = bufSize;         /* Number of bytes to read */
  int nBlob;                   /* Total size of the blob */
  int rc;                      /* sqlite error code */

  nBlob = sqlite3_blob_bytes(p->pBlob);
  if( (p->iSeek+nRead)>nBlob ){
    nRead = nBlob-p->iSeek;
  }
  if( nRead<=0 ){
    return 0;
  }

  rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
  if( rc!=SQLITE_OK ){
    *errorCodePtr = rc;
    return -1;
  }

  p->iSeek += nRead;
  return nRead;
}

/*
** Write data to an incremental blob channel.
*/
static int incrblobOutput(
  ClientData instanceData, 
  CONST char *buf, 
  int toWrite,
  int *errorCodePtr
){
  IncrblobChannel *p = (IncrblobChannel *)instanceData;
  int nWrite = toWrite;        /* Number of bytes to write */
  int nBlob;                   /* Total size of the blob */
  int rc;                      /* sqlite error code */

  nBlob = sqlite3_blob_bytes(p->pBlob);
  if( (p->iSeek+nWrite)>nBlob ){
    *errorCodePtr = EINVAL;
    return -1;
  }
  if( nWrite<=0 ){
    return 0;
  }

  rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
  if( rc!=SQLITE_OK ){
    *errorCodePtr = EIO;
    return -1;
  }

  p->iSeek += nWrite;
  return nWrite;
}

/*
** Seek an incremental blob channel.
*/
static int incrblobSeek(
  ClientData instanceData, 
  long offset,
  int seekMode,
  int *errorCodePtr
){
  IncrblobChannel *p = (IncrblobChannel *)instanceData;

  switch( seekMode ){
    case SEEK_SET:
      p->iSeek = offset;
      break;
    case SEEK_CUR:
      p->iSeek += offset;
      break;
    case SEEK_END:
      p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
      break;

    default: assert(!"Bad seekMode");
  }

  return p->iSeek;
}


static void incrblobWatch(ClientData instanceData, int mode){ 
  /* NO-OP */ 
}
static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
  return TCL_ERROR;
}

static Tcl_ChannelType IncrblobChannelType = {
  "incrblob",                        /* typeName                             */
  TCL_CHANNEL_VERSION_2,             /* version                              */
  incrblobClose,                     /* closeProc                            */
  incrblobInput,                     /* inputProc                            */
  incrblobOutput,                    /* outputProc                           */
  incrblobSeek,                      /* seekProc                             */
  0,                                 /* setOptionProc                        */
  0,                                 /* getOptionProc                        */
  incrblobWatch,                     /* watchProc (this is a no-op)          */
  incrblobHandle,                    /* getHandleProc (always returns error) */
  0,                                 /* close2Proc                           */
  0,                                 /* blockModeProc                        */
  0,                                 /* flushProc                            */
  0,                                 /* handlerProc                          */
  0,                                 /* wideSeekProc                         */
};

/*
** Create a new incrblob channel.
*/
static int createIncrblobChannel(
  Tcl_Interp *interp, 
  SqliteDb *pDb, 
  const char *zDb,
  const char *zTable, 
  const char *zColumn, 
  sqlite_int64 iRow,
  int isReadonly
){
  IncrblobChannel *p;
  sqlite3 *db = pDb->db;
  sqlite3_blob *pBlob;
  int rc;
  int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);

  /* This variable is used to name the channels: "incrblob_[incr count]" */
  static int count = 0;
  char zChannel[64];

  rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
  if( rc!=SQLITE_OK ){
    Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
    return TCL_ERROR;
  }

  p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
  p->iSeek = 0;
  p->pBlob = pBlob;

  sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
  p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
  Tcl_RegisterChannel(interp, p->channel);

  /* Link the new channel into the SqliteDb.pIncrblob list. */
  p->pNext = pDb->pIncrblob;
  p->pPrev = 0;
  if( p->pNext ){
    p->pNext->pPrev = p;
  }
  pDb->pIncrblob = p;
  p->pDb = pDb;

  Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
  return TCL_OK;
}
#else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
  #define closeIncrblobChannels(pDb)
#endif

/*
** Look at the script prefix in pCmd.  We will be executing this script
** after first appending one or more arguments.  This routine analyzes
** the script to see if it is safe to use Tcl_EvalObjv() on the script
** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
** faster.
**
** Scripts that are safe to use with Tcl_EvalObjv() consists of a
** command name followed by zero or more arguments with no [...] or $
** or {...} or ; to be seen anywhere.  Most callback scripts consist
** of just a single procedure name and they meet this requirement.
*/
static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
  /* We could try to do something with Tcl_Parse().  But we will instead
  ** just do a search for forbidden characters.  If any of the forbidden
  ** characters appear in pCmd, we will report the string as unsafe.
  */
  const char *z;
  int n;
  z = Tcl_GetStringFromObj(pCmd, &n);
  while( n-- > 0 ){
    int c = *(z++);
    if( c=='$' || c=='[' || c==';' ) return 0;
  }
  return 1;
}

/*
** Find an SqlFunc structure with the given name.  Or create a new
** one if an existing one cannot be found.  Return a pointer to the
** structure.
*/
static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
  SqlFunc *p, *pNew;
  int i;
  pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
  pNew->zName = (char*)&pNew[1];
  for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
  pNew->zName[i] = 0;
  for(p=pDb->pFunc; p; p=p->pNext){ 
    if( strcmp(p->zName, pNew->zName)==0 ){
      Tcl_Free((char*)pNew);
      return p;
    }
  }
  pNew->interp = pDb->interp;
  pNew->pScript = 0;
  pNew->pNext = pDb->pFunc;
  pDb->pFunc = pNew;
  return pNew;
}

/*
** Finalize and free a list of prepared statements
*/
static void flushStmtCache( SqliteDb *pDb ){
  SqlPreparedStmt *pPreStmt;

  while(  pDb->stmtList ){
    sqlite3_finalize( pDb->stmtList->pStmt );
    pPreStmt = pDb->stmtList;
    pDb->stmtList = pDb->stmtList->pNext;
    Tcl_Free( (char*)pPreStmt );
  }
  pDb->nStmt = 0;
  pDb->stmtLast = 0;
}

/*
** TCL calls this procedure when an sqlite3 database command is
** deleted.
*/
static void DbDeleteCmd(void *db){
  SqliteDb *pDb = (SqliteDb*)db;
  flushStmtCache(pDb);
  closeIncrblobChannels(pDb);
  sqlite3_close(pDb->db);
  while( pDb->pFunc ){
    SqlFunc *pFunc = pDb->pFunc;
    pDb->pFunc = pFunc->pNext;
    Tcl_DecrRefCount(pFunc->pScript);
    Tcl_Free((char*)pFunc);
  }
  while( pDb->pCollate ){
    SqlCollate *pCollate = pDb->pCollate;
    pDb->pCollate = pCollate->pNext;
    Tcl_Free((char*)pCollate);
  }
  if( pDb->zBusy ){
    Tcl_Free(pDb->zBusy);
  }
  if( pDb->zTrace ){
    Tcl_Free(pDb->zTrace);
  }
  if( pDb->zProfile ){
    Tcl_Free(pDb->zProfile);
  }
  if( pDb->zAuth ){
    Tcl_Free(pDb->zAuth);
  }
  if( pDb->zNull ){
    Tcl_Free(pDb->zNull);
  }
  if( pDb->pUpdateHook ){
    Tcl_DecrRefCount(pDb->pUpdateHook);
  }
  if( pDb->pRollbackHook ){
    Tcl_DecrRefCount(pDb->pRollbackHook);
  }
  if( pDb->pCollateNeeded ){
    Tcl_DecrRefCount(pDb->pCollateNeeded);
  }
  Tcl_Free((char*)pDb);
}

/*
** This routine is called when a database file is locked while trying
** to execute SQL.
*/
static int DbBusyHandler(void *cd, int nTries){
  SqliteDb *pDb = (SqliteDb*)cd;
  int rc;
  char zVal[30];

  sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
  rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
  if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
    return 0;
  }
  return 1;
}

#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
/*
** This routine is invoked as the 'progress callback' for the database.
*/
static int DbProgressHandler(void *cd){
  SqliteDb *pDb = (SqliteDb*)cd;
  int rc;

  assert( pDb->zProgress );
  rc = Tcl_Eval(pDb->interp, pDb->zProgress);
  if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
    return 1;
  }
  return 0;
}
#endif

#ifndef SQLITE_OMIT_TRACE
/*
** This routine is called by the SQLite trace handler whenever a new
** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
*/
static void DbTraceHandler(void *cd, const char *zSql){
  SqliteDb *pDb = (SqliteDb*)cd;
  Tcl_DString str;

  Tcl_DStringInit(&str);
  Tcl_DStringAppend(&str, pDb->zTrace, -1);
  Tcl_DStringAppendElement(&str, zSql);
  Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  Tcl_ResetResult(pDb->interp);
}
#endif

#ifndef SQLITE_OMIT_TRACE
/*
** This routine is called by the SQLite profile handler after a statement
** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
*/
static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
  SqliteDb *pDb = (SqliteDb*)cd;
  Tcl_DString str;
  char zTm[100];

  sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
  Tcl_DStringInit(&str);
  Tcl_DStringAppend(&str, pDb->zProfile, -1);
  Tcl_DStringAppendElement(&str, zSql);
  Tcl_DStringAppendElement(&str, zTm);
  Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  Tcl_ResetResult(pDb->interp);
}
#endif

/*
** This routine is called when a transaction is committed.  The
** TCL script in pDb->zCommit is executed.  If it returns non-zero or
** if it throws an exception, the transaction is rolled back instead
** of being committed.
*/
static int DbCommitHandler(void *cd){
  SqliteDb *pDb = (SqliteDb*)cd;
  int rc;

  rc = Tcl_Eval(pDb->interp, pDb->zCommit);
  if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
    return 1;
  }
  return 0;
}

static void DbRollbackHandler(void *clientData){
  SqliteDb *pDb = (SqliteDb*)clientData;
  assert(pDb->pRollbackHook);
  if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
    Tcl_BackgroundError(pDb->interp);
  }
}

#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
  char zBuf[64];
  sprintf(zBuf, "%d", iArg);
  Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
  sprintf(zBuf, "%d", nArg);
  Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
}
#else
# define setTestUnlockNotifyVars(x,y,z)
#endif

#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
static void DbUnlockNotify(void **apArg, int nArg){
  int i;
  for(i=0; i<nArg; i++){
    const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
    SqliteDb *pDb = (SqliteDb *)apArg[i];
    setTestUnlockNotifyVars(pDb->interp, i, nArg);
    assert( pDb->pUnlockNotify);
    Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
    Tcl_DecrRefCount(pDb->pUnlockNotify);
    pDb->pUnlockNotify = 0;
  }
}
#endif

static void DbUpdateHandler(
  void *p, 
  int op,
  const char *zDb, 
  const char *zTbl, 
  sqlite_int64 rowid
){
  SqliteDb *pDb = (SqliteDb *)p;
  Tcl_Obj *pCmd;

  assert( pDb->pUpdateHook );
  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );

  pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
  Tcl_IncrRefCount(pCmd);
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
    ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
}

static void tclCollateNeeded(
  void *pCtx,
  sqlite3 *db,
  int enc,
  const char *zName
){
  SqliteDb *pDb = (SqliteDb *)pCtx;
  Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
  Tcl_IncrRefCount(pScript);
  Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
  Tcl_EvalObjEx(pDb->interp, pScript, 0);
  Tcl_DecrRefCount(pScript);
}

/*
** This routine is called to evaluate an SQL collation function implemented
** using TCL script.
*/
static int tclSqlCollate(
  void *pCtx,
  int nA,
  const void *zA,
  int nB,
  const void *zB
){
  SqlCollate *p = (SqlCollate *)pCtx;
  Tcl_Obj *pCmd;

  pCmd = Tcl_NewStringObj(p->zScript, -1);
  Tcl_IncrRefCount(pCmd);
  Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
  Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
  Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
  return (atoi(Tcl_GetStringResult(p->interp)));
}

/*
** This routine is called to evaluate an SQL function implemented
** using TCL script.
*/
static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
  SqlFunc *p = sqlite3_user_data(context);
  Tcl_Obj *pCmd;
  int i;
  int rc;

  if( argc==0 ){
    /* If there are no arguments to the function, call Tcl_EvalObjEx on the
    ** script object directly.  This allows the TCL compiler to generate
    ** bytecode for the command on the first invocation and thus make
    ** subsequent invocations much faster. */
    pCmd = p->pScript;
    Tcl_IncrRefCount(pCmd);
    rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
    Tcl_DecrRefCount(pCmd);
  }else{
    /* If there are arguments to the function, make a shallow copy of the
    ** script object, lappend the arguments, then evaluate the copy.
    **
    ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
    ** The new Tcl_Obj contains pointers to the original list elements. 
    ** That way, when Tcl_EvalObjv() is run and shimmers the first element
    ** of the list to tclCmdNameType, that alternate representation will
    ** be preserved and reused on the next invocation.
    */
    Tcl_Obj **aArg;
    int nArg;
    if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
      sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
      return;
    }     
    pCmd = Tcl_NewListObj(nArg, aArg);
    Tcl_IncrRefCount(pCmd);
    for(i=0; i<argc; i++){
      sqlite3_value *pIn = argv[i];
      Tcl_Obj *pVal;
            
      /* Set pVal to contain the i'th column of this row. */
      switch( sqlite3_value_type(pIn) ){
        case SQLITE_BLOB: {
          int bytes = sqlite3_value_bytes(pIn);
          pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
          break;
        }
        case SQLITE_INTEGER: {
          sqlite_int64 v = sqlite3_value_int64(pIn);
          if( v>=-2147483647 && v<=2147483647 ){
            pVal = Tcl_NewIntObj(v);
          }else{
            pVal = Tcl_NewWideIntObj(v);
          }
          break;
        }
        case SQLITE_FLOAT: {
          double r = sqlite3_value_double(pIn);
          pVal = Tcl_NewDoubleObj(r);
          break;
        }
        case SQLITE_NULL: {
          pVal = Tcl_NewStringObj("", 0);
          break;
        }
        default: {
          int bytes = sqlite3_value_bytes(pIn);
          pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
          break;
        }
      }
      rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
      if( rc ){
        Tcl_DecrRefCount(pCmd);
        sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
        return;
      }
    }
    if( !p->useEvalObjv ){
      /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
      ** is a list without a string representation.  To prevent this from
      ** happening, make sure pCmd has a valid string representation */
      Tcl_GetString(pCmd);
    }
    rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
    Tcl_DecrRefCount(pCmd);
  }

  if( rc && rc!=TCL_RETURN ){
    sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
  }else{
    Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
    int n;
    u8 *data;
    const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
    char c = zType[0];
    if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
      /* Only return a BLOB type if the Tcl variable is a bytearray and
      ** has no string representation. */
      data = Tcl_GetByteArrayFromObj(pVar, &n);
      sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
    }else if( c=='b' && strcmp(zType,"boolean")==0 ){
      Tcl_GetIntFromObj(0, pVar, &n);
      sqlite3_result_int(context, n);
    }else if( c=='d' && strcmp(zType,"double")==0 ){
      double r;
      Tcl_GetDoubleFromObj(0, pVar, &r);
      sqlite3_result_double(context, r);
    }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
          (c=='i' && strcmp(zType,"int")==0) ){
      Tcl_WideInt v;
      Tcl_GetWideIntFromObj(0, pVar, &v);
      sqlite3_result_int64(context, v);
    }else{
      data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
      sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
    }
  }
}

#ifndef SQLITE_OMIT_AUTHORIZATION
/*
** This is the authentication function.  It appends the authentication
** type code and the two arguments to zCmd[] then invokes the result
** on the interpreter.  The reply is examined to determine if the
** authentication fails or succeeds.
*/
static int auth_callback(
  void *pArg,
  int code,
  const char *zArg1,
  const char *zArg2,
  const char *zArg3,
  const char *zArg4
){
  char *zCode;
  Tcl_DString str;
  int rc;
  const char *zReply;
  SqliteDb *pDb = (SqliteDb*)pArg;
  if( pDb->disableAuth ) return SQLITE_OK;

  switch( code ){
    case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
    case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
    case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
    case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
    case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
    case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
    case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
    case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
    case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
    case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
    case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
    case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
    case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
    case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
    case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
    case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
    case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
    case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
    case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
    case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
    case SQLITE_READ              : zCode="SQLITE_READ"; break;
    case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
    case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
    case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
    case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
    case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
    case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
    case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
    case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
    case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
    case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
    case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
    case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
    default                       : zCode="????"; break;
  }
  Tcl_DStringInit(&str);
  Tcl_DStringAppend(&str, pDb->zAuth, -1);
  Tcl_DStringAppendElement(&str, zCode);
  Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
  Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
  Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
  Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
  rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  zReply = Tcl_GetStringResult(pDb->interp);
  if( strcmp(zReply,"SQLITE_OK")==0 ){
    rc = SQLITE_OK;
  }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
    rc = SQLITE_DENY;
  }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
    rc = SQLITE_IGNORE;
  }else{
    rc = 999;
  }
  return rc;
}
#endif /* SQLITE_OMIT_AUTHORIZATION */

/*
** zText is a pointer to text obtained via an sqlite3_result_text()
** or similar interface. This routine returns a Tcl string object, 
** reference count set to 0, containing the text. If a translation
** between iso8859 and UTF-8 is required, it is preformed.
*/
static Tcl_Obj *dbTextToObj(char const *zText){
  Tcl_Obj *pVal;
#ifdef UTF_TRANSLATION_NEEDED
  Tcl_DString dCol;
  Tcl_DStringInit(&dCol);
  Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
  pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
  Tcl_DStringFree(&dCol);
#else
  pVal = Tcl_NewStringObj(zText, -1);
#endif
  return pVal;
}

/*
** This routine reads a line of text from FILE in, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text.  NULL is returned at end of file, or if malloc()
** fails.
**
** The interface is like "readline" but no command-line editing
** is done.
**
** copied from shell.c from '.import' command
*/
static char *local_getline(char *zPrompt, FILE *in){
  char *zLine;
  int nLine;
  int n;
  int eol;

  nLine = 100;
  zLine = malloc( nLine );
  if( zLine==0 ) return 0;
  n = 0;
  eol = 0;
  while( !eol ){
    if( n+100>nLine ){
      nLine = nLine*2 + 100;
      zLine = realloc(zLine, nLine);
      if( zLine==0 ) return 0;
    }
    if( fgets(&zLine[n], nLine - n, in)==0 ){
      if( n==0 ){
        free(zLine);
        return 0;
      }
      zLine[n] = 0;
      eol = 1;
      break;
    }
    while( zLine[n] ){ n++; }
    if( n>0 && zLine[n-1]=='\n' ){
      n--;
      zLine[n] = 0;
      eol = 1;
    }
  }
  zLine = realloc( zLine, n+1 );
  return zLine;
}


/*
** This function is part of the implementation of the command:
**
**   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
**
** It is invoked after evaluating the script SCRIPT to commit or rollback
** the transaction or savepoint opened by the [transaction] command.
*/
static int DbTransPostCmd(
  ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
  Tcl_Interp *interp,                  /* Tcl interpreter */
  int result                           /* Result of evaluating SCRIPT */
){
  static const char *azEnd[] = {
    "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
    "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
    "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
    "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
  };
  SqliteDb *pDb = (SqliteDb*)data[0];
  int rc = result;
  const char *zEnd;

  pDb->nTransaction--;
  zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];

  pDb->disableAuth++;
  if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
      /* This is a tricky scenario to handle. The most likely cause of an
      ** error is that the exec() above was an attempt to commit the 
      ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
      ** that an IO-error has occured. In either case, throw a Tcl exception
      ** and try to rollback the transaction.
      **
      ** But it could also be that the user executed one or more BEGIN, 
      ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
      ** this method's logic. Not clear how this would be best handled.
      */
    if( rc!=TCL_ERROR ){
      Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
      rc = TCL_ERROR;
    }
    sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
  }
  pDb->disableAuth--;

  return rc;
}

/*
** Search the cache for a prepared-statement object that implements the
** first SQL statement in the buffer pointed to by parameter zIn. If
** no such prepared-statement can be found, allocate and prepare a new
** one. In either case, bind the current values of the relevant Tcl
** variables to any $var, :var or @var variables in the statement. Before
** returning, set *ppPreStmt to point to the prepared-statement object.
**
** Output parameter *pzOut is set to point to the next SQL statement in
** buffer zIn, or to the '\0' byte at the end of zIn if there is no
** next statement.
**
** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
** and an error message loaded into interpreter pDb->interp.
*/
static int dbPrepareAndBind(
  SqliteDb *pDb,                  /* Database object */
  char const *zIn,                /* SQL to compile */
  char const **pzOut,             /* OUT: Pointer to next SQL statement */
  SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
){
  const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
  sqlite3_stmt *pStmt;            /* Prepared statement object */
  SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
  int nSql;                       /* Length of zSql in bytes */
  int nVar;                       /* Number of variables in statement */
  int iParm = 0;                  /* Next free entry in apParm */
  int i;
  Tcl_Interp *interp = pDb->interp;

  *ppPreStmt = 0;

  /* Trim spaces from the start of zSql and calculate the remaining length. */
  while( isspace(zSql[0]) ){ zSql++; }
  nSql = strlen30(zSql);

  for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
    int n = pPreStmt->nSql;
    if( nSql>=n 
        && memcmp(pPreStmt->zSql, zSql, n)==0
        && (zSql[n]==0 || zSql[n-1]==';')
    ){
      pStmt = pPreStmt->pStmt;
      *pzOut = &zSql[pPreStmt->nSql];

      /* When a prepared statement is found, unlink it from the
      ** cache list.  It will later be added back to the beginning
      ** of the cache list in order to implement LRU replacement.
      */
      if( pPreStmt->pPrev ){
        pPreStmt->pPrev->pNext = pPreStmt->pNext;
      }else{
        pDb->stmtList = pPreStmt->pNext;
      }
      if( pPreStmt->pNext ){
        pPreStmt->pNext->pPrev = pPreStmt->pPrev;
      }else{
        pDb->stmtLast = pPreStmt->pPrev;
      }
      pDb->nStmt--;
      nVar = sqlite3_bind_parameter_count(pStmt);
      break;
    }
  }
  
  /* If no prepared statement was found. Compile the SQL text. Also allocate
  ** a new SqlPreparedStmt structure.  */
  if( pPreStmt==0 ){
    int nByte;

    if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
      Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
      return TCL_ERROR;
    }
    if( pStmt==0 ){
      if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
        /* A compile-time error in the statement. */
        Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
        return TCL_ERROR;
      }else{
        /* The statement was a no-op.  Continue to the next statement
        ** in the SQL string.
        */
        return TCL_OK;
      }
    }

    assert( pPreStmt==0 );
    nVar = sqlite3_bind_parameter_count(pStmt);
    nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
    pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
    memset(pPreStmt, 0, nByte);

    pPreStmt->pStmt = pStmt;
    pPreStmt->nSql = (*pzOut - zSql);
    pPreStmt->zSql = sqlite3_sql(pStmt);
    pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
  }
  assert( pPreStmt );
  assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
  assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );

  /* Bind values to parameters that begin with $ or : */  
  for(i=1; i<=nVar; i++){
    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
    if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
      Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
      if( pVar ){
        int n;
        u8 *data;
        const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
        char c = zType[0];
        if( zVar[0]=='@' ||
           (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
          /* Load a BLOB type if the Tcl variable is a bytearray and
          ** it has no string representation or the host
          ** parameter name begins with "@". */
          data = Tcl_GetByteArrayFromObj(pVar, &n);
          sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }else if( c=='b' && strcmp(zType,"boolean")==0 ){
          Tcl_GetIntFromObj(interp, pVar, &n);
          sqlite3_bind_int(pStmt, i, n);
        }else if( c=='d' && strcmp(zType,"double")==0 ){
          double r;
          Tcl_GetDoubleFromObj(interp, pVar, &r);
          sqlite3_bind_double(pStmt, i, r);
        }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
              (c=='i' && strcmp(zType,"int")==0) ){
          Tcl_WideInt v;
          Tcl_GetWideIntFromObj(interp, pVar, &v);
          sqlite3_bind_int64(pStmt, i, v);
        }else{
          data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
          sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }
      }else{
        sqlite3_bind_null(pStmt, i);
      }
    }
  }
  pPreStmt->nParm = iParm;
  *ppPreStmt = pPreStmt;

  return TCL_OK;
}


/*
** Release a statement reference obtained by calling dbPrepareAndBind().
** There should be exactly one call to this function for each call to
** dbPrepareAndBind().
**
** If the discard parameter is non-zero, then the statement is deleted
** immediately. Otherwise it is added to the LRU list and may be returned
** by a subsequent call to dbPrepareAndBind().
*/
static void dbReleaseStmt(
  SqliteDb *pDb,                  /* Database handle */
  SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
  int discard                     /* True to delete (not cache) the pPreStmt */
){
  int i;

  /* Free the bound string and blob parameters */
  for(i=0; i<pPreStmt->nParm; i++){
    Tcl_DecrRefCount(pPreStmt->apParm[i]);
  }
  pPreStmt->nParm = 0;

  if( pDb->maxStmt<=0 || discard ){
    /* If the cache is turned off, deallocated the statement */
    sqlite3_finalize(pPreStmt->pStmt);
    Tcl_Free((char *)pPreStmt);
  }else{
    /* Add the prepared statement to the beginning of the cache list. */
    pPreStmt->pNext = pDb->stmtList;
    pPreStmt->pPrev = 0;
    if( pDb->stmtList ){
     pDb->stmtList->pPrev = pPreStmt;
    }
    pDb->stmtList = pPreStmt;
    if( pDb->stmtLast==0 ){
      assert( pDb->nStmt==0 );
      pDb->stmtLast = pPreStmt;
    }else{
      assert( pDb->nStmt>0 );
    }
    pDb->nStmt++;
   
    /* If we have too many statement in cache, remove the surplus from 
    ** the end of the cache list.  */
    while( pDb->nStmt>pDb->maxStmt ){
      sqlite3_finalize(pDb->stmtLast->pStmt);
      pDb->stmtLast = pDb->stmtLast->pPrev;
      Tcl_Free((char*)pDb->stmtLast->pNext);
      pDb->stmtLast->pNext = 0;
      pDb->nStmt--;
    }
  }
}

/*
** Structure used with dbEvalXXX() functions:
**
**   dbEvalInit()
**   dbEvalStep()
**   dbEvalFinalize()
**   dbEvalRowInfo()
**   dbEvalColumnValue()
*/
typedef struct DbEvalContext DbEvalContext;
struct DbEvalContext {
  SqliteDb *pDb;                  /* Database handle */
  Tcl_Obj *pSql;                  /* Object holding string zSql */
  const char *zSql;               /* Remaining SQL to execute */
  SqlPreparedStmt *pPreStmt;      /* Current statement */
  int nCol;                       /* Number of columns returned by pStmt */
  Tcl_Obj *pArray;                /* Name of array variable */
  Tcl_Obj **apColName;            /* Array of column names */
};

/*
** Release any cache of column names currently held as part of
** the DbEvalContext structure passed as the first argument.
*/
static void dbReleaseColumnNames(DbEvalContext *p){
  if( p->apColName ){
    int i;
    for(i=0; i<p->nCol; i++){
      Tcl_DecrRefCount(p->apColName[i]);
    }
    Tcl_Free((char *)p->apColName);
    p->apColName = 0;
  }
  p->nCol = 0;
}

/*
** Initialize a DbEvalContext structure.
**
** If pArray is not NULL, then it contains the name of a Tcl array
** variable. The "*" member of this array is set to a list containing
** the names of the columns returned by the statement as part of each
** call to dbEvalStep(), in order from left to right. e.g. if the names 
** of the returned columns are a, b and c, it does the equivalent of the 
** tcl command:
**
**     set ${pArray}(*) {a b c}
*/
static void dbEvalInit(
  DbEvalContext *p,               /* Pointer to structure to initialize */
  SqliteDb *pDb,                  /* Database handle */
  Tcl_Obj *pSql,                  /* Object containing SQL script */
  Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
){
  memset(p, 0, sizeof(DbEvalContext));
  p->pDb = pDb;
  p->zSql = Tcl_GetString(pSql);
  p->pSql = pSql;
  Tcl_IncrRefCount(pSql);
  if( pArray ){
    p->pArray = pArray;
    Tcl_IncrRefCount(pArray);
  }
}

/*
** Obtain information about the row that the DbEvalContext passed as the
** first argument currently points to.
*/
static void dbEvalRowInfo(
  DbEvalContext *p,               /* Evaluation context */
  int *pnCol,                     /* OUT: Number of column names */
  Tcl_Obj ***papColName           /* OUT: Array of column names */
){
  /* Compute column names */
  if( 0==p->apColName ){
    sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
    int i;                        /* Iterator variable */
    int nCol;                     /* Number of columns returned by pStmt */
    Tcl_Obj **apColName = 0;      /* Array of column names */

    p->nCol = nCol = sqlite3_column_count(pStmt);
    if( nCol>0 && (papColName || p->pArray) ){
      apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
      for(i=0; i<nCol; i++){
        apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
        Tcl_IncrRefCount(apColName[i]);
      }
      p->apColName = apColName;
    }

    /* If results are being stored in an array variable, then create
    ** the array(*) entry for that array
    */
    if( p->pArray ){
      Tcl_Interp *interp = p->pDb->interp;
      Tcl_Obj *pColList = Tcl_NewObj();
      Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);

      for(i=0; i<nCol; i++){
        Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
      }
      Tcl_IncrRefCount(pStar);
      Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
      Tcl_DecrRefCount(pStar);
    }
  }

  if( papColName ){
    *papColName = p->apColName;
  }
  if( pnCol ){
    *pnCol = p->nCol;
  }
}

/*
** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
** returned, then an error message is stored in the interpreter before
** returning.
**
** A return value of TCL_OK means there is a row of data available. The
** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
** is returned, then the SQL script has finished executing and there are
** no further rows available. This is similar to SQLITE_DONE.
*/
static int dbEvalStep(DbEvalContext *p){
  while( p->zSql[0] || p->pPreStmt ){
    int rc;
    if( p->pPreStmt==0 ){
      rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
      if( rc!=TCL_OK ) return rc;
    }else{
      int rcs;
      SqliteDb *pDb = p->pDb;
      SqlPreparedStmt *pPreStmt = p->pPreStmt;
      sqlite3_stmt *pStmt = pPreStmt->pStmt;

      rcs = sqlite3_step(pStmt);
      if( rcs==SQLITE_ROW ){
        return TCL_OK;
      }
      if( p->pArray ){
        dbEvalRowInfo(p, 0, 0);
      }
      rcs = sqlite3_reset(pStmt);

      pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
      pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
      dbReleaseColumnNames(p);
      p->pPreStmt = 0;

      if( rcs!=SQLITE_OK ){
        /* If a run-time error occurs, report the error and stop reading
        ** the SQL.  */
        Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
        dbReleaseStmt(pDb, pPreStmt, 1);
        return TCL_ERROR;
      }else{
        dbReleaseStmt(pDb, pPreStmt, 0);
      }
    }
  }

  /* Finished */
  return TCL_BREAK;
}

/*
** Free all resources currently held by the DbEvalContext structure passed
** as the first argument. There should be exactly one call to this function
** for each call to dbEvalInit().
*/
static void dbEvalFinalize(DbEvalContext *p){
  if( p->pPreStmt ){
    sqlite3_reset(p->pPreStmt->pStmt);
    dbReleaseStmt(p->pDb, p->pPreStmt, 0);
    p->pPreStmt = 0;
  }
  if( p->pArray ){
    Tcl_DecrRefCount(p->pArray);
    p->pArray = 0;
  }
  Tcl_DecrRefCount(p->pSql);
  dbReleaseColumnNames(p);
}

/*
** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
** the value for the iCol'th column of the row currently pointed to by
** the DbEvalContext structure passed as the first argument.
*/
static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
  sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
  switch( sqlite3_column_type(pStmt, iCol) ){
    case SQLITE_BLOB: {
      int bytes = sqlite3_column_bytes(pStmt, iCol);
      const char *zBlob = sqlite3_column_blob(pStmt, iCol);
      if( !zBlob ) bytes = 0;
      return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
    }
    case SQLITE_INTEGER: {
      sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
      if( v>=-2147483647 && v<=2147483647 ){
        return Tcl_NewIntObj(v);
      }else{
        return Tcl_NewWideIntObj(v);
      }
    }
    case SQLITE_FLOAT: {
      return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
    }
    case SQLITE_NULL: {
      return dbTextToObj(p->pDb->zNull);
    }
  }

  return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
}

/*
** If using Tcl version 8.6 or greater, use the NR functions to avoid
** recursive evalution of scripts by the [db eval] and [db trans]
** commands. Even if the headers used while compiling the extension
** are 8.6 or newer, the code still tests the Tcl version at runtime.
** This allows stubs-enabled builds to be used with older Tcl libraries.
*/
#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
# define SQLITE_TCL_NRE 1
static int DbUseNre(void){
  int major, minor;
  Tcl_GetVersion(&major, &minor, 0, 0);
  return( (major==8 && minor>=6) || major>8 );
}
#else
/* 
** Compiling using headers earlier than 8.6. In this case NR cannot be
** used, so DbUseNre() to always return zero. Add #defines for the other
** Tcl_NRxxx() functions to prevent them from causing compilation errors,
** even though the only invocations of them are within conditional blocks 
** of the form:
**
**   if( DbUseNre() ) { ... }
*/
# define SQLITE_TCL_NRE 0
# define DbUseNre() 0
# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
# define Tcl_NREvalObj(a,b,c) 0
# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
#endif

/*
** This function is part of the implementation of the command:
**
**   $db eval SQL ?ARRAYNAME? SCRIPT
*/
static int DbEvalNextCmd(
  ClientData data[],                   /* data[0] is the (DbEvalContext*) */
  Tcl_Interp *interp,                  /* Tcl interpreter */
  int result                           /* Result so far */
){
  int rc = result;                     /* Return code */

  /* The first element of the data[] array is a pointer to a DbEvalContext
  ** structure allocated using Tcl_Alloc(). The second element of data[]
  ** is a pointer to a Tcl_Obj containing the script to run for each row
  ** returned by the queries encapsulated in data[0]. */
  DbEvalContext *p = (DbEvalContext *)data[0];
  Tcl_Obj *pScript = (Tcl_Obj *)data[1];
  Tcl_Obj *pArray = p->pArray;

  while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
    int i;
    int nCol;
    Tcl_Obj **apColName;
    dbEvalRowInfo(p, &nCol, &apColName);
    for(i=0; i<nCol; i++){
      Tcl_Obj *pVal = dbEvalColumnValue(p, i);
      if( pArray==0 ){
        Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
      }else{
        Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
      }
    }

    /* The required interpreter variables are now populated with the data 
    ** from the current row. If using NRE, schedule callbacks to evaluate
    ** script pScript, then to invoke this function again to fetch the next
    ** row (or clean up if there is no next row or the script throws an
    ** exception). After scheduling the callbacks, return control to the 
    ** caller.
    **
    ** If not using NRE, evaluate pScript directly and continue with the
    ** next iteration of this while(...) loop.  */
    if( DbUseNre() ){
      Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
      return Tcl_NREvalObj(interp, pScript, 0);
    }else{
      rc = Tcl_EvalObjEx(interp, pScript, 0);
    }
  }

  Tcl_DecrRefCount(pScript);
  dbEvalFinalize(p);
  Tcl_Free((char *)p);

  if( rc==TCL_OK || rc==TCL_BREAK ){
    Tcl_ResetResult(interp);
    rc = TCL_OK;
  }
  return rc;
}

/*
** The "sqlite" command below creates a new Tcl command for each
** connection it opens to an SQLite database.  This routine is invoked
** whenever one of those connection-specific commands is executed
** in Tcl.  For example, if you run Tcl code like this:
**
**       sqlite3 db1  "my_database"
**       db1 close
**
** The first command opens a connection to the "my_database" database
** and calls that connection "db1".  The second command causes this
** subroutine to be invoked.
*/
static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
  SqliteDb *pDb = (SqliteDb*)cd;
  int choice;
  int rc = TCL_OK;
  static const char *DB_strs[] = {
    "authorizer",         "backup",            "busy",
    "cache",              "changes",           "close",
    "collate",            "collation_needed",  "commit_hook",
    "complete",           "copy",              "enable_load_extension",
    "errorcode",          "eval",              "exists",
    "function",           "incrblob",          "interrupt",
    "last_insert_rowid",  "nullvalue",         "onecolumn",
    "profile",            "progress",          "rekey",
    "restore",            "rollback_hook",     "status",
    "timeout",            "total_changes",     "trace",
    "transaction",        "unlock_notify",     "update_hook",
    "version",            0                    
  };
  enum DB_enum {
    DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
    DB_CACHE,             DB_CHANGES,          DB_CLOSE,
    DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
    DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
    DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
    DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
    DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
    DB_PROFILE,           DB_PROGRESS,         DB_REKEY,
    DB_RESTORE,           DB_ROLLBACK_HOOK,    DB_STATUS,
    DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
    DB_TRANSACTION,       DB_UNLOCK_NOTIFY,    DB_UPDATE_HOOK,
    DB_VERSION,
  };
  /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
    return TCL_ERROR;
  }
  if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
    return TCL_ERROR;
  }

  switch( (enum DB_enum)choice ){

  /*    $db authorizer ?CALLBACK?
  **
  ** Invoke the given callback to authorize each SQL operation as it is
  ** compiled.  5 arguments are appended to the callback before it is
  ** invoked:
  **
  **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
  **   (2) First descriptive name (depends on authorization type)
  **   (3) Second descriptive name
  **   (4) Name of the database (ex: "main", "temp")
  **   (5) Name of trigger that is doing the access
  **
  ** The callback should return on of the following strings: SQLITE_OK,
  ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
  **
  ** If this method is invoked with no arguments, the current authorization
  ** callback string is returned.
  */
  case DB_AUTHORIZER: {
#ifdef SQLITE_OMIT_AUTHORIZATION
    Tcl_AppendResult(interp, "authorization not available in this build", 0);
    return TCL_ERROR;
#else
    if( objc>3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
      return TCL_ERROR;
    }else if( objc==2 ){
      if( pDb->zAuth ){
        Tcl_AppendResult(interp, pDb->zAuth, 0);
      }
    }else{
      char *zAuth;
      int len;
      if( pDb->zAuth ){
        Tcl_Free(pDb->zAuth);
      }
      zAuth = Tcl_GetStringFromObj(objv[2], &len);
      if( zAuth && len>0 ){
        pDb->zAuth = Tcl_Alloc( len + 1 );
        memcpy(pDb->zAuth, zAuth, len+1);
      }else{
        pDb->zAuth = 0;
      }
      if( pDb->zAuth ){
        pDb->interp = interp;
        sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
      }else{
        sqlite3_set_authorizer(pDb->db, 0, 0);
      }
    }
#endif
    break;
  }

  /*    $db backup ?DATABASE? FILENAME
  **
  ** Open or create a database file named FILENAME.  Transfer the
  ** content of local database DATABASE (default: "main") into the
  ** FILENAME database.
  */
  case DB_BACKUP: {
    const char *zDestFile;
    const char *zSrcDb;
    sqlite3 *pDest;
    sqlite3_backup *pBackup;

    if( objc==3 ){
      zSrcDb = "main";
      zDestFile = Tcl_GetString(objv[2]);
    }else if( objc==4 ){
      zSrcDb = Tcl_GetString(objv[2]);
      zDestFile = Tcl_GetString(objv[3]);
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
      return TCL_ERROR;
    }
    rc = sqlite3_open(zDestFile, &pDest);
    if( rc!=SQLITE_OK ){
      Tcl_AppendResult(interp, "cannot open target database: ",
           sqlite3_errmsg(pDest), (char*)0);
      sqlite3_close(pDest);
      return TCL_ERROR;
    }
    pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
    if( pBackup==0 ){
      Tcl_AppendResult(interp, "backup failed: ",
           sqlite3_errmsg(pDest), (char*)0);
      sqlite3_close(pDest);
      return TCL_ERROR;
    }
    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
    sqlite3_backup_finish(pBackup);
    if( rc==SQLITE_DONE ){
      rc = TCL_OK;
    }else{
      Tcl_AppendResult(interp, "backup failed: ",
           sqlite3_errmsg(pDest), (char*)0);
      rc = TCL_ERROR;
    }
    sqlite3_close(pDest);
    break;
  }

  /*    $db busy ?CALLBACK?
  **
  ** Invoke the given callback if an SQL statement attempts to open
  ** a locked database file.
  */
  case DB_BUSY: {
    if( objc>3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
      return TCL_ERROR;
    }else if( objc==2 ){
      if( pDb->zBusy ){
        Tcl_AppendResult(interp, pDb->zBusy, 0);
      }
    }else{
      char *zBusy;
      int len;
      if( pDb->zBusy ){
        Tcl_Free(pDb->zBusy);
      }
      zBusy = Tcl_GetStringFromObj(objv[2], &len);
      if( zBusy && len>0 ){
        pDb->zBusy = Tcl_Alloc( len + 1 );
        memcpy(pDb->zBusy, zBusy, len+1);
      }else{
        pDb->zBusy = 0;
      }
      if( pDb->zBusy ){
        pDb->interp = interp;
        sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
      }else{
        sqlite3_busy_handler(pDb->db, 0, 0);
      }
    }
    break;
  }

  /*     $db cache flush
  **     $db cache size n
  **
  ** Flush the prepared statement cache, or set the maximum number of
  ** cached statements.
  */
  case DB_CACHE: {
    char *subCmd;
    int n;

    if( objc<=2 ){
      Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
      return TCL_ERROR;
    }
    subCmd = Tcl_GetStringFromObj( objv[2], 0 );
    if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
      if( objc!=3 ){
        Tcl_WrongNumArgs(interp, 2, objv, "flush");
        return TCL_ERROR;
      }else{
        flushStmtCache( pDb );
      }
    }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
      if( objc!=4 ){
        Tcl_WrongNumArgs(interp, 2, objv, "size n");
        return TCL_ERROR;
      }else{
        if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
          Tcl_AppendResult( interp, "cannot convert \"", 
               Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
          return TCL_ERROR;
        }else{
          if( n<0 ){
            flushStmtCache( pDb );
            n = 0;
          }else if( n>MAX_PREPARED_STMTS ){
            n = MAX_PREPARED_STMTS;
          }
          pDb->maxStmt = n;
        }
      }
    }else{
      Tcl_AppendResult( interp, "bad option \"", 
          Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
      return TCL_ERROR;
    }
    break;
  }

  /*     $db changes
  **
  ** Return the number of rows that were modified, inserted, or deleted by
  ** the most recent INSERT, UPDATE or DELETE statement, not including 
  ** any changes made by trigger programs.
  */
  case DB_CHANGES: {
    Tcl_Obj *pResult;
    if( objc!=2 ){
      Tcl_WrongNumArgs(interp, 2, objv, "");
      return TCL_ERROR;
    }
    pResult = Tcl_GetObjResult(interp);
    Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
    break;
  }

  /*    $db close
  **
  ** Shutdown the database
  */
  case DB_CLOSE: {
    Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
    break;
  }

  /*
  **     $db collate NAME SCRIPT
  **
  ** Create a new SQL collation function called NAME.  Whenever
  ** that function is called, invoke SCRIPT to evaluate the function.
  */
  case DB_COLLATE: {
    SqlCollate *pCollate;
    char *zName;
    char *zScript;
    int nScript;
    if( objc!=4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
      return TCL_ERROR;
    }
    zName = Tcl_GetStringFromObj(objv[2], 0);
    zScript = Tcl_GetStringFromObj(objv[3], &nScript);
    pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
    if( pCollate==0 ) return TCL_ERROR;
    pCollate->interp = interp;
    pCollate->pNext = pDb->pCollate;
    pCollate->zScript = (char*)&pCollate[1];
    pDb->pCollate = pCollate;
    memcpy(pCollate->zScript, zScript, nScript+1);
    if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8, 
        pCollate, tclSqlCollate) ){
      Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
      return TCL_ERROR;
    }
    break;
  }

  /*
  **     $db collation_needed SCRIPT
  **
  ** Create a new SQL collation function called NAME.  Whenever
  ** that function is called, invoke SCRIPT to evaluate the function.
  */
  case DB_COLLATION_NEEDED: {
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
      return TCL_ERROR;
    }
    if( pDb->pCollateNeeded ){
      Tcl_DecrRefCount(pDb->pCollateNeeded);
    }
    pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
    Tcl_IncrRefCount(pDb->pCollateNeeded);
    sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
    break;
  }

  /*    $db commit_hook ?CALLBACK?
  **
  ** Invoke the given callback just before committing every SQL transaction.
  ** If the callback throws an exception or returns non-zero, then the
  ** transaction is aborted.  If CALLBACK is an empty string, the callback
  ** is disabled.
  */
  case DB_COMMIT_HOOK: {
    if( objc>3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
      return TCL_ERROR;
    }else if( objc==2 ){
      if( pDb->zCommit ){
        Tcl_AppendResult(interp, pDb->zCommit, 0);
      }
    }else{
      char *zCommit;
      int len;
      if( pDb->zCommit ){
        Tcl_Free(pDb->zCommit);
      }
      zCommit = Tcl_GetStringFromObj(objv[2], &len);
      if( zCommit && len>0 ){
        pDb->zCommit = Tcl_Alloc( len + 1 );
        memcpy(pDb->zCommit, zCommit, len+1);
      }else{
        pDb->zCommit = 0;
      }
      if( pDb->zCommit ){
        pDb->interp = interp;
        sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
      }else{
        sqlite3_commit_hook(pDb->db, 0, 0);
      }
    }
    break;
  }

  /*    $db complete SQL
  **
  ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
  ** additional lines of input are needed.  This is similar to the
  ** built-in "info complete" command of Tcl.
  */
  case DB_COMPLETE: {
#ifndef SQLITE_OMIT_COMPLETE
    Tcl_Obj *pResult;
    int isComplete;
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "SQL");
      return TCL_ERROR;
    }
    isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
    pResult = Tcl_GetObjResult(interp);
    Tcl_SetBooleanObj(pResult, isComplete);
#endif
    break;
  }

  /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
  **
  ** Copy data into table from filename, optionally using SEPARATOR
  ** as column separators.  If a column contains a null string, or the
  ** value of NULLINDICATOR, a NULL is inserted for the column.
  ** conflict-algorithm is one of the sqlite conflict algorithms:
  **    rollback, abort, fail, ignore, replace
  ** On success, return the number of lines processed, not necessarily same
  ** as 'db changes' due to conflict-algorithm selected.
  **
  ** This code is basically an implementation/enhancement of
  ** the sqlite3 shell.c ".import" command.
  **
  ** This command usage is equivalent to the sqlite2.x COPY statement,
  ** which imports file data into a table using the PostgreSQL COPY file format:
  **   $db copy $conflit_algo $table_name $filename \t \\N
  */
  case DB_COPY: {
    char *zTable;               /* Insert data into this table */
    char *zFile;                /* The file from which to extract data */
    char *zConflict;            /* The conflict algorithm to use */
    sqlite3_stmt *pStmt;        /* A statement */
    int nCol;                   /* Number of columns in the table */
    int nByte;                  /* Number of bytes in an SQL string */
    int i, j;                   /* Loop counters */
    int nSep;                   /* Number of bytes in zSep[] */
    int nNull;                  /* Number of bytes in zNull[] */
    char *zSql;                 /* An SQL statement */
    char *zLine;                /* A single line of input from the file */
    char **azCol;               /* zLine[] broken up into columns */
    char *zCommit;              /* How to commit changes */
    FILE *in;                   /* The input file */
    int lineno = 0;             /* Line number of input file */
    char zLineNum[80];          /* Line number print buffer */
    Tcl_Obj *pResult;           /* interp result */

    char *zSep;
    char *zNull;
    if( objc<5 || objc>7 ){
      Tcl_WrongNumArgs(interp, 2, objv, 
         "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
      return TCL_ERROR;
    }
    if( objc>=6 ){
      zSep = Tcl_GetStringFromObj(objv[5], 0);
    }else{
      zSep = "\t";
    }
    if( objc>=7 ){
      zNull = Tcl_GetStringFromObj(objv[6], 0);
    }else{
      zNull = "";
    }
    zConflict = Tcl_GetStringFromObj(objv[2], 0);
    zTable = Tcl_GetStringFromObj(objv[3], 0);
    zFile = Tcl_GetStringFromObj(objv[4], 0);
    nSep = strlen30(zSep);
    nNull = strlen30(zNull);
    if( nSep==0 ){
      Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
      return TCL_ERROR;
    }
    if(strcmp(zConflict, "rollback") != 0 &&
       strcmp(zConflict, "abort"   ) != 0 &&
       strcmp(zConflict, "fail"    ) != 0 &&
       strcmp(zConflict, "ignore"  ) != 0 &&
       strcmp(zConflict, "replace" ) != 0 ) {
      Tcl_AppendResult(interp, "Error: \"", zConflict, 
            "\", conflict-algorithm must be one of: rollback, "
            "abort, fail, ignore, or replace", 0);
      return TCL_ERROR;
    }
    zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
    if( zSql==0 ){
      Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
      return TCL_ERROR;
    }
    nByte = strlen30(zSql);
    rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
      nCol = 0;
    }else{
      nCol = sqlite3_column_count(pStmt);
    }
    sqlite3_finalize(pStmt);
    if( nCol==0 ) {
      return TCL_ERROR;
    }
    zSql = malloc( nByte + 50 + nCol*2 );
    if( zSql==0 ) {
      Tcl_AppendResult(interp, "Error: can't malloc()", 0);
      return TCL_ERROR;
    }
    sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
         zConflict, zTable);
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
    rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
    free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
      sqlite3_finalize(pStmt);
      return TCL_ERROR;
    }
    in = fopen(zFile, "rb");
    if( in==0 ){
      Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
      sqlite3_finalize(pStmt);
      return TCL_ERROR;
    }
    azCol = malloc( sizeof(azCol[0])*(nCol+1) );
    if( azCol==0 ) {
      Tcl_AppendResult(interp, "Error: can't malloc()", 0);
      fclose(in);
      return TCL_ERROR;
    }
    (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
    zCommit = "COMMIT";
    while( (zLine = local_getline(0, in))!=0 ){
      char *z;
      i = 0;
      lineno++;
      azCol[0] = zLine;
      for(i=0, z=zLine; *z; z++){
        if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
          *z = 0;
          i++;
          if( i<nCol ){
            azCol[i] = &z[nSep];
            z += nSep-1;
          }
        }
      }
      if( i+1!=nCol ){
        char *zErr;
        int nErr = strlen30(zFile) + 200;
        zErr = malloc(nErr);
        if( zErr ){
          sqlite3_snprintf(nErr, zErr,
             "Error: %s line %d: expected %d columns of data but found %d",
             zFile, lineno, nCol, i+1);
          Tcl_AppendResult(interp, zErr, 0);
          free(zErr);
        }
        zCommit = "ROLLBACK";
        break;
      }
      for(i=0; i<nCol; i++){
        /* check for null data, if so, bind as null */
        if( (nNull>0 && strcmp(azCol[i], zNull)==0)
          || strlen30(azCol[i])==0 
        ){
          sqlite3_bind_null(pStmt, i+1);
        }else{
          sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
        }
      }
      sqlite3_step(pStmt);
      rc = sqlite3_reset(pStmt);
      free(zLine);
      if( rc!=SQLITE_OK ){
        Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
        zCommit = "ROLLBACK";
        break;
      }
    }
    free(azCol);
    fclose(in);
    sqlite3_finalize(pStmt);
    (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);

    if( zCommit[0] == 'C' ){
      /* success, set result as number of lines processed */
      pResult = Tcl_GetObjResult(interp);
      Tcl_SetIntObj(pResult, lineno);
      rc = TCL_OK;
    }else{
      /* failure, append lineno where failed */
      sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
      Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
      rc = TCL_ERROR;
    }
    break;
  }

  /*
  **    $db enable_load_extension BOOLEAN
  **
  ** Turn the extension loading feature on or off.  It if off by
  ** default.
  */
  case DB_ENABLE_LOAD_EXTENSION: {
#ifndef SQLITE_OMIT_LOAD_EXTENSION
    int onoff;
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
      return TCL_ERROR;
    }
    if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
      return TCL_ERROR;
    }
    sqlite3_enable_load_extension(pDb->db, onoff);
    break;
#else
    Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
                     0);
    return TCL_ERROR;
#endif
  }

  /*
  **    $db errorcode
  **
  ** Return the numeric error code that was returned by the most recent
  ** call to sqlite3_exec().
  */
  case DB_ERRORCODE: {
    Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
    break;
  }

  /*
  **    $db exists $sql
  **    $db onecolumn $sql
  **
  ** The onecolumn method is the equivalent of:
  **     lindex [$db eval $sql] 0
  */
  case DB_EXISTS: 
  case DB_ONECOLUMN: {
    DbEvalContext sEval;
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "SQL");
      return TCL_ERROR;
    }

    dbEvalInit(&sEval, pDb, objv[2], 0);
    rc = dbEvalStep(&sEval);
    if( choice==DB_ONECOLUMN ){
      if( rc==TCL_OK ){
        Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
      }
    }else if( rc==TCL_BREAK || rc==TCL_OK ){
      Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
    }
    dbEvalFinalize(&sEval);

    if( rc==TCL_BREAK ){
      rc = TCL_OK;
    }
    break;
  }
   
  /*
  **    $db eval $sql ?array? ?{  ...code... }?
  **
  ** The SQL statement in $sql is evaluated.  For each row, the values are
  ** placed in elements of the array named "array" and ...code... is executed.
  ** If "array" and "code" are omitted, then no callback is every invoked.
  ** If "array" is an empty string, then the values are placed in variables
  ** that have the same name as the fields extracted by the query.
  */
  case DB_EVAL: {
    if( objc<3 || objc>5 ){
      Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
      return TCL_ERROR;
    }

    if( objc==3 ){
      DbEvalContext sEval;
      Tcl_Obj *pRet = Tcl_NewObj();
      Tcl_IncrRefCount(pRet);
      dbEvalInit(&sEval, pDb, objv[2], 0);
      while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
        int i;
        int nCol;
        dbEvalRowInfo(&sEval, &nCol, 0);
        for(i=0; i<nCol; i++){
          Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
        }
      }
      dbEvalFinalize(&sEval);
      if( rc==TCL_BREAK ){
        Tcl_SetObjResult(interp, pRet);
        rc = TCL_OK;
      }
      Tcl_DecrRefCount(pRet);
    }else{
      ClientData cd[2];
      DbEvalContext *p;
      Tcl_Obj *pArray = 0;
      Tcl_Obj *pScript;

      if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
        pArray = objv[3];
      }
      pScript = objv[objc-1];
      Tcl_IncrRefCount(pScript);
      
      p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
      dbEvalInit(p, pDb, objv[2], pArray);

      cd[0] = (void *)p;
      cd[1] = (void *)pScript;
      rc = DbEvalNextCmd(cd, interp, TCL_OK);
    }
    break;
  }

  /*
  **     $db function NAME [-argcount N] SCRIPT
  **
  ** Create a new SQL function called NAME.  Whenever that function is
  ** called, invoke SCRIPT to evaluate the function.
  */
  case DB_FUNCTION: {
    SqlFunc *pFunc;
    Tcl_Obj *pScript;
    char *zName;
    int nArg = -1;
    if( objc==6 ){
      const char *z = Tcl_GetString(objv[3]);
      int n = strlen30(z);
      if( n>2 && strncmp(z, "-argcount",n)==0 ){
        if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
        if( nArg<0 ){
          Tcl_AppendResult(interp, "number of arguments must be non-negative",
                           (char*)0);
          return TCL_ERROR;
        }
      }
      pScript = objv[5];
    }else if( objc!=4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
      return TCL_ERROR;
    }else{
      pScript = objv[3];
    }
    zName = Tcl_GetStringFromObj(objv[2], 0);
    pFunc = findSqlFunc(pDb, zName);
    if( pFunc==0 ) return TCL_ERROR;
    if( pFunc->pScript ){
      Tcl_DecrRefCount(pFunc->pScript);
    }
    pFunc->pScript = pScript;
    Tcl_IncrRefCount(pScript);
    pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
    rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
        pFunc, tclSqlFunc, 0, 0);
    if( rc!=SQLITE_OK ){
      rc = TCL_ERROR;
      Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
    }
    break;
  }

  /*
  **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
  */
  case DB_INCRBLOB: {
#ifdef SQLITE_OMIT_INCRBLOB
    Tcl_AppendResult(interp, "incrblob not available in this build", 0);
    return TCL_ERROR;
#else
    int isReadonly = 0;
    const char *zDb = "main";
    const char *zTable;
    const char *zColumn;
    sqlite_int64 iRow;

    /* Check for the -readonly option */
    if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
      isReadonly = 1;
    }

    if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
      Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
      return TCL_ERROR;
    }

    if( objc==(6+isReadonly) ){
      zDb = Tcl_GetString(objv[2]);
    }
    zTable = Tcl_GetString(objv[objc-3]);
    zColumn = Tcl_GetString(objv[objc-2]);
    rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);

    if( rc==TCL_OK ){
      rc = createIncrblobChannel(
          interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
      );
    }
#endif
    break;
  }

  /*
  **     $db interrupt
  **
  ** Interrupt the execution of the inner-most SQL interpreter.  This
  ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
  */
  case DB_INTERRUPT: {
    sqlite3_interrupt(pDb->db);
    break;
  }

  /*
  **     $db nullvalue ?STRING?
  **
  ** Change text used when a NULL comes back from the database. If ?STRING?
  ** is not present, then the current string used for NULL is returned.
  ** If STRING is present, then STRING is returned.
  **
  */
  case DB_NULLVALUE: {
    if( objc!=2 && objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
      return TCL_ERROR;
    }
    if( objc==3 ){
      int len;
      char *zNull = Tcl_GetStringFromObj(objv[2], &len);
      if( pDb->zNull ){
        Tcl_Free(pDb->zNull);
      }
      if( zNull && len>0 ){
        pDb->zNull = Tcl_Alloc( len + 1 );
        strncpy(pDb->zNull, zNull, len);
        pDb->zNull[len] = '\0';
      }else{
        pDb->zNull = 0;
      }
    }
    Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
    break;
  }

  /*
  **     $db last_insert_rowid 
  **
  ** Return an integer which is the ROWID for the most recent insert.
  */
  case DB_LAST_INSERT_ROWID: {
    Tcl_Obj *pResult;
    Tcl_WideInt rowid;
    if( objc!=2 ){
      Tcl_WrongNumArgs(interp, 2, objv, "");
      return TCL_ERROR;
    }
    rowid = sqlite3_last_insert_rowid(pDb->db);
    pResult = Tcl_GetObjResult(interp);
    Tcl_SetWideIntObj(pResult, rowid);
    break;
  }

  /*
  ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
  */

  /*    $db progress ?N CALLBACK?
  ** 
  ** Invoke the given callback every N virtual machine opcodes while executing
  ** queries.
  */
  case DB_PROGRESS: {
    if( objc==2 ){
      if( pDb->zProgress ){
        Tcl_AppendResult(interp, pDb->zProgress, 0);
      }
    }else if( objc==4 ){
      char *zProgress;
      int len;
      int N;
      if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
        return TCL_ERROR;
      };
      if( pDb->zProgress ){
        Tcl_Free(pDb->zProgress);
      }
      zProgress = Tcl_GetStringFromObj(objv[3], &len);
      if( zProgress && len>0 ){
        pDb->zProgress = Tcl_Alloc( len + 1 );
        memcpy(pDb->zProgress, zProgress, len+1);
      }else{
        pDb->zProgress = 0;
      }
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
      if( pDb->zProgress ){
        pDb->interp = interp;
        sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
      }else{
        sqlite3_progress_handler(pDb->db, 0, 0, 0);
      }
#endif
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
      return TCL_ERROR;
    }
    break;
  }

  /*    $db profile ?CALLBACK?
  **
  ** Make arrangements to invoke the CALLBACK routine after each SQL statement
  ** that has run.  The text of the SQL and the amount of elapse time are
  ** appended to CALLBACK before the script is run.
  */
  case DB_PROFILE: {
    if( objc>3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
      return TCL_ERROR;
    }else if( objc==2 ){
      if( pDb->zProfile ){
        Tcl_AppendResult(interp, pDb->zProfile, 0);
      }
    }else{
      char *zProfile;
      int len;
      if( pDb->zProfile ){
        Tcl_Free(pDb->zProfile);
      }
      zProfile = Tcl_GetStringFromObj(objv[2], &len);
      if( zProfile && len>0 ){
        pDb->zProfile = Tcl_Alloc( len + 1 );
        memcpy(pDb->zProfile, zProfile, len+1);
      }else{
        pDb->zProfile = 0;
      }
#ifndef SQLITE_OMIT_TRACE
      if( pDb->zProfile ){
        pDb->interp = interp;
        sqlite3_profile(pDb->db, DbProfileHandler, pDb);
      }else{
        sqlite3_profile(pDb->db, 0, 0);
      }
#endif
    }
    break;
  }

  /*
  **     $db rekey KEY
  **
  ** Change the encryption key on the currently open database.
  */
  case DB_REKEY: {
    int nKey;
    void *pKey;
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "KEY");
      return TCL_ERROR;
    }
    pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
#ifdef SQLITE_HAS_CODEC
    rc = sqlite3_rekey(pDb->db, pKey, nKey);
    if( rc ){
      Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
      rc = TCL_ERROR;
    }
#endif
    break;
  }

  /*    $db restore ?DATABASE? FILENAME
  **
  ** Open a database file named FILENAME.  Transfer the content 
  ** of FILENAME into the local database DATABASE (default: "main").
  */
  case DB_RESTORE: {
    const char *zSrcFile;
    const char *zDestDb;
    sqlite3 *pSrc;
    sqlite3_backup *pBackup;
    int nTimeout = 0;

    if( objc==3 ){
      zDestDb = "main";
      zSrcFile = Tcl_GetString(objv[2]);
    }else if( objc==4 ){
      zDestDb = Tcl_GetString(objv[2]);
      zSrcFile = Tcl_GetString(objv[3]);
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
      return TCL_ERROR;
    }
    rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
    if( rc!=SQLITE_OK ){
      Tcl_AppendResult(interp, "cannot open source database: ",
           sqlite3_errmsg(pSrc), (char*)0);
      sqlite3_close(pSrc);
      return TCL_ERROR;
    }
    pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
    if( pBackup==0 ){
      Tcl_AppendResult(interp, "restore failed: ",
           sqlite3_errmsg(pDb->db), (char*)0);
      sqlite3_close(pSrc);
      return TCL_ERROR;
    }
    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
              || rc==SQLITE_BUSY ){
      if( rc==SQLITE_BUSY ){
        if( nTimeout++ >= 3 ) break;
        sqlite3_sleep(100);
      }
    }
    sqlite3_backup_finish(pBackup);
    if( rc==SQLITE_DONE ){
      rc = TCL_OK;
    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
      Tcl_AppendResult(interp, "restore failed: source database busy",
                       (char*)0);
      rc = TCL_ERROR;
    }else{
      Tcl_AppendResult(interp, "restore failed: ",
           sqlite3_errmsg(pDb->db), (char*)0);
      rc = TCL_ERROR;
    }
    sqlite3_close(pSrc);
    break;
  }

  /*
  **     $db status (step|sort)
  **
  ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or 
  ** SQLITE_STMTSTATUS_SORT for the most recent eval.
  */
  case DB_STATUS: {
    int v;
    const char *zOp;
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
      return TCL_ERROR;
    }
    zOp = Tcl_GetString(objv[2]);
    if( strcmp(zOp, "step")==0 ){
      v = pDb->nStep;
    }else if( strcmp(zOp, "sort")==0 ){
      v = pDb->nSort;
    }else{
      Tcl_AppendResult(interp, "bad argument: should be step or sort", 
            (char*)0);
      return TCL_ERROR;
    }
    Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
    break;
  }
  
  /*
  **     $db timeout MILLESECONDS
  **
  ** Delay for the number of milliseconds specified when a file is locked.
  */
  case DB_TIMEOUT: {
    int ms;
    if( objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
      return TCL_ERROR;
    }
    if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
    sqlite3_busy_timeout(pDb->db, ms);
    break;
  }
  
  /*
  **     $db total_changes
  **
  ** Return the number of rows that were modified, inserted, or deleted 
  ** since the database handle was created.
  */
  case DB_TOTAL_CHANGES: {
    Tcl_Obj *pResult;
    if( objc!=2 ){
      Tcl_WrongNumArgs(interp, 2, objv, "");
      return TCL_ERROR;
    }
    pResult = Tcl_GetObjResult(interp);
    Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
    break;
  }

  /*    $db trace ?CALLBACK?
  **
  ** Make arrangements to invoke the CALLBACK routine for each SQL statement
  ** that is executed.  The text of the SQL is appended to CALLBACK before
  ** it is executed.
  */
  case DB_TRACE: {
    if( objc>3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
      return TCL_ERROR;
    }else if( objc==2 ){
      if( pDb->zTrace ){
        Tcl_AppendResult(interp, pDb->zTrace, 0);
      }
    }else{
      char *zTrace;
      int len;
      if( pDb->zTrace ){
        Tcl_Free(pDb->zTrace);
      }
      zTrace = Tcl_GetStringFromObj(objv[2], &len);
      if( zTrace && len>0 ){
        pDb->zTrace = Tcl_Alloc( len + 1 );
        memcpy(pDb->zTrace, zTrace, len+1);
      }else{
        pDb->zTrace = 0;
      }
#ifndef SQLITE_OMIT_TRACE
      if( pDb->zTrace ){
        pDb->interp = interp;
        sqlite3_trace(pDb->db, DbTraceHandler, pDb);
      }else{
        sqlite3_trace(pDb->db, 0, 0);
      }
#endif
    }
    break;
  }

  /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
  **
  ** Start a new transaction (if we are not already in the midst of a
  ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
  ** completes, either commit the transaction or roll it back if SCRIPT
  ** throws an exception.  Or if no new transation was started, do nothing.
  ** pass the exception on up the stack.
  **
  ** This command was inspired by Dave Thomas's talk on Ruby at the
  ** 2005 O'Reilly Open Source Convention (OSCON).
  */
  case DB_TRANSACTION: {
    Tcl_Obj *pScript;
    const char *zBegin = "SAVEPOINT _tcl_transaction";
    if( objc!=3 && objc!=4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
      return TCL_ERROR;
    }

    if( pDb->nTransaction==0 && objc==4 ){
      static const char *TTYPE_strs[] = {
        "deferred",   "exclusive",  "immediate", 0
      };
      enum TTYPE_enum {
        TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
      };
      int ttype;
      if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
                              0, &ttype) ){
        return TCL_ERROR;
      }
      switch( (enum TTYPE_enum)ttype ){
        case TTYPE_DEFERRED:    /* no-op */;                 break;
        case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
        case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
      }
    }
    pScript = objv[objc-1];

    /* Run the SQLite BEGIN command to open a transaction or savepoint. */
    pDb->disableAuth++;
    rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
    pDb->disableAuth--;
    if( rc!=SQLITE_OK ){
      Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
      return TCL_ERROR;
    }
    pDb->nTransaction++;

    /* If using NRE, schedule a callback to invoke the script pScript, then
    ** a second callback to commit (or rollback) the transaction or savepoint
    ** opened above. If not using NRE, evaluate the script directly, then
    ** call function DbTransPostCmd() to commit (or rollback) the transaction 
    ** or savepoint.  */
    if( DbUseNre() ){
      Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
      Tcl_NREvalObj(interp, pScript, 0);
    }else{
      rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
    }
    break;
  }

  /*
  **    $db unlock_notify ?script?
  */
  case DB_UNLOCK_NOTIFY: {
#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
    Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
    rc = TCL_ERROR;
#else
    if( objc!=2 && objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
      rc = TCL_ERROR;
    }else{
      void (*xNotify)(void **, int) = 0;
      void *pNotifyArg = 0;

      if( pDb->pUnlockNotify ){
        Tcl_DecrRefCount(pDb->pUnlockNotify);
        pDb->pUnlockNotify = 0;
      }
  
      if( objc==3 ){
        xNotify = DbUnlockNotify;
        pNotifyArg = (void *)pDb;
        pDb->pUnlockNotify = objv[2];
        Tcl_IncrRefCount(pDb->pUnlockNotify);
      }
  
      if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
        Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
        rc = TCL_ERROR;
      }
    }
#endif
    break;
  }

  /*
  **    $db update_hook ?script?
  **    $db rollback_hook ?script?
  */
  case DB_UPDATE_HOOK: 
  case DB_ROLLBACK_HOOK: {

    /* set ppHook to point at pUpdateHook or pRollbackHook, depending on 
    ** whether [$db update_hook] or [$db rollback_hook] was invoked.
    */
    Tcl_Obj **ppHook; 
    if( choice==DB_UPDATE_HOOK ){
      ppHook = &pDb->pUpdateHook;
    }else{
      ppHook = &pDb->pRollbackHook;
    }

    if( objc!=2 && objc!=3 ){
       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
       return TCL_ERROR;
    }
    if( *ppHook ){
      Tcl_SetObjResult(interp, *ppHook);
      if( objc==3 ){
        Tcl_DecrRefCount(*ppHook);
        *ppHook = 0;
      }
    }
    if( objc==3 ){
      assert( !(*ppHook) );
      if( Tcl_GetCharLength(objv[2])>0 ){
        *ppHook = objv[2];
        Tcl_IncrRefCount(*ppHook);
      }
    }

    sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
    sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);

    break;
  }

  /*    $db version
  **
  ** Return the version string for this database.
  */
  case DB_VERSION: {
    Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
    break;
  }


  } /* End of the SWITCH statement */
  return rc;
}

#if SQLITE_TCL_NRE
/*
** Adaptor that provides an objCmd interface to the NRE-enabled
** interface implementation.
*/
static int DbObjCmdAdaptor(
  void *cd,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *const*objv
){
  return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
}
#endif /* SQLITE_TCL_NRE */

/*
**   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
**                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
**
** This is the main Tcl command.  When the "sqlite" Tcl command is
** invoked, this routine runs to process that command.
**
** The first argument, DBNAME, is an arbitrary name for a new
** database connection.  This command creates a new command named
** DBNAME that is used to control that connection.  The database
** connection is deleted when the DBNAME command is deleted.
**
** The second argument is the name of the database file.
**
*/
static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
  SqliteDb *p;
  void *pKey = 0;
  int nKey = 0;
  const char *zArg;
  char *zErrMsg;
  int i;
  const char *zFile;
  const char *zVfs = 0;
  int flags;
  Tcl_DString translatedFilename;

  /* In normal use, each TCL interpreter runs in a single thread.  So
  ** by default, we can turn of mutexing on SQLite database connections.
  ** However, for testing purposes it is useful to have mutexes turned
  ** on.  So, by default, mutexes default off.  But if compiled with
  ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
  */
#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
  flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
#else
  flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
#endif

  if( objc==2 ){
    zArg = Tcl_GetStringFromObj(objv[1], 0);
    if( strcmp(zArg,"-version")==0 ){
      Tcl_AppendResult(interp,sqlite3_version,0);
      return TCL_OK;
    }
    if( strcmp(zArg,"-has-codec")==0 ){
#ifdef SQLITE_HAS_CODEC
      Tcl_AppendResult(interp,"1",0);
#else
      Tcl_AppendResult(interp,"0",0);
#endif
      return TCL_OK;
    }
  }
  for(i=3; i+1<objc; i+=2){
    zArg = Tcl_GetString(objv[i]);
    if( strcmp(zArg,"-key")==0 ){
      pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
    }else if( strcmp(zArg, "-vfs")==0 ){
      i++;
      zVfs = Tcl_GetString(objv[i]);
    }else if( strcmp(zArg, "-readonly")==0 ){
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b ){
        flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        flags |= SQLITE_OPEN_READONLY;
      }else{
        flags &= ~SQLITE_OPEN_READONLY;
        flags |= SQLITE_OPEN_READWRITE;
      }
    }else if( strcmp(zArg, "-create")==0 ){
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
        flags |= SQLITE_OPEN_CREATE;
      }else{
        flags &= ~SQLITE_OPEN_CREATE;
      }
    }else if( strcmp(zArg, "-nomutex")==0 ){
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b ){
        flags |= SQLITE_OPEN_NOMUTEX;
        flags &= ~SQLITE_OPEN_FULLMUTEX;
      }else{
        flags &= ~SQLITE_OPEN_NOMUTEX;
      }
   }else if( strcmp(zArg, "-fullmutex")==0 ){
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b ){
        flags |= SQLITE_OPEN_FULLMUTEX;
        flags &= ~SQLITE_OPEN_NOMUTEX;
      }else{
        flags &= ~SQLITE_OPEN_FULLMUTEX;
      }
    }else{
      Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
      return TCL_ERROR;
    }
  }
  if( objc<3 || (objc&1)!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, 
      "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
      " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
#ifdef SQLITE_HAS_CODEC
      " ?-key CODECKEY?"
#endif
    );
    return TCL_ERROR;
  }
  zErrMsg = 0;
  p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
  if( p==0 ){
    Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
    return TCL_ERROR;
  }
  memset(p, 0, sizeof(*p));
  zFile = Tcl_GetStringFromObj(objv[2], 0);
  zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
  sqlite3_open_v2(zFile, &p->db, flags, zVfs);
  Tcl_DStringFree(&translatedFilename);
  if( SQLITE_OK!=sqlite3_errcode(p->db) ){
    zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
    sqlite3_close(p->db);
    p->db = 0;
  }
#ifdef SQLITE_HAS_CODEC
  if( p->db ){
    sqlite3_key(p->db, pKey, nKey);
  }
#endif
  if( p->db==0 ){
    Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
    Tcl_Free((char*)p);
    sqlite3_free(zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->interp = interp;
  zArg = Tcl_GetStringFromObj(objv[1], 0);
  if( DbUseNre() ){
    Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
                        (char*)p, DbDeleteCmd);
  }else{
    Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
  }
  return TCL_OK;
}

/*
** Provide a dummy Tcl_InitStubs if we are using this as a static
** library.
*/
#ifndef USE_TCL_STUBS
# undef  Tcl_InitStubs
# define Tcl_InitStubs(a,b,c)
#endif

/*
** Make sure we have a PACKAGE_VERSION macro defined.  This will be
** defined automatically by the TEA makefile.  But other makefiles
** do not define it.
*/
#ifndef PACKAGE_VERSION
# define PACKAGE_VERSION SQLITE_VERSION
#endif

/*
** Initialize this module.
**
** This Tcl module contains only a single new Tcl command named "sqlite".
** (Hence there is no namespace.  There is no point in using a namespace
** if the extension only supplies one new name!)  The "sqlite" command is
** used to open a new SQLite database.  See the DbMain() routine above
** for additional information.
*/
EXTERN int Sqlite3_Init(Tcl_Interp *interp){
  Tcl_InitStubs(interp, "8.4", 0);
  Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
  Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
  Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
  Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
  return TCL_OK;
}
EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}


#ifndef SQLITE_3_SUFFIX_ONLY
EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
#endif

#ifdef TCLSH
/*****************************************************************************
** All of the code that follows is used to build standalone TCL interpreters
** that are statically linked with SQLite.  Enable these by compiling
** with -DTCLSH=n where n can be 1 or 2.  An n of 1 generates a standard
** tclsh but with SQLite built in.  An n of 2 generates the SQLite space
** analysis program.
*/

#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
/*
 * This code implements the MD5 message-digest algorithm.
 * The algorithm is due to Ron Rivest.  This code was
 * written by Colin Plumb in 1993, no copyright is claimed.
 * This code is in the public domain; do with it what you wish.
 *
 * Equivalent code is available from RSA Data Security, Inc.
 * This code has been tested against that, and is equivalent,
 * except that you don't need to include two pages of legalese
 * with every copy.
 *
 * To compute the message digest of a chunk of bytes, declare an
 * MD5Context structure, pass it to MD5Init, call MD5Update as
 * needed on buffers full of bytes, and then call MD5Final, which
 * will fill a supplied 16-byte array with the digest.
 */

/*
 * If compiled on a machine that doesn't have a 32-bit integer,
 * you just set "uint32" to the appropriate datatype for an
 * unsigned 32-bit integer.  For example:
 *
 *       cc -Duint32='unsigned long' md5.c
 *
 */
#ifndef uint32
#  define uint32 unsigned int
#endif

struct MD5Context {
  int isInit;
  uint32 buf[4];
  uint32 bits[2];
  unsigned char in[64];
};
typedef struct MD5Context MD5Context;

/*
 * Note: this code is harmless on little-endian machines.
 */
static void byteReverse (unsigned char *buf, unsigned longs){
        uint32 t;
        do {
                t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
                            ((unsigned)buf[1]<<8 | buf[0]);
                *(uint32 *)buf = t;
                buf += 4;
        } while (--longs);
}
/* The four core functions - F1 is optimized somewhat */

/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
        ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )

/*
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
 * the data and converts bytes into longwords for this routine.
 */
static void MD5Transform(uint32 buf[4], const uint32 in[16]){
        register uint32 a, b, c, d;

        a = buf[0];
        b = buf[1];
        c = buf[2];
        d = buf[3];

        MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
        MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
        MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
        MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
        MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
        MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
        MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
        MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
        MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
        MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
        MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
        MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
        MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
        MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
        MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
        MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);

        MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
        MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
        MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
        MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
        MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
        MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
        MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
        MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
        MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
        MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
        MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
        MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
        MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
        MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
        MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
        MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);

        MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
        MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
        MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
        MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
        MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
        MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
        MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
        MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
        MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
        MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
        MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
        MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
        MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
        MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
        MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
        MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);

        MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
        MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
        MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
        MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
        MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
        MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
        MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
        MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
        MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
        MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
        MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
        MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
        MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
        MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
        MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
        MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);

        buf[0] += a;
        buf[1] += b;
        buf[2] += c;
        buf[3] += d;
}

/*
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
static void MD5Init(MD5Context *ctx){
        ctx->isInit = 1;
        ctx->buf[0] = 0x67452301;
        ctx->buf[1] = 0xefcdab89;
        ctx->buf[2] = 0x98badcfe;
        ctx->buf[3] = 0x10325476;
        ctx->bits[0] = 0;
        ctx->bits[1] = 0;
}

/*
 * Update context to reflect the concatenation of another buffer full
 * of bytes.
 */
static 
void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
        uint32 t;

        /* Update bitcount */

        t = ctx->bits[0];
        if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
                ctx->bits[1]++; /* Carry from low to high */
        ctx->bits[1] += len >> 29;

        t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */

        /* Handle any leading odd-sized chunks */

        if ( t ) {
                unsigned char *p = (unsigned char *)ctx->in + t;

                t = 64-t;
                if (len < t) {
                        memcpy(p, buf, len);
                        return;
                }
                memcpy(p, buf, t);
                byteReverse(ctx->in, 16);
                MD5Transform(ctx->buf, (uint32 *)ctx->in);
                buf += t;
                len -= t;
        }

        /* Process data in 64-byte chunks */

        while (len >= 64) {
                memcpy(ctx->in, buf, 64);
                byteReverse(ctx->in, 16);
                MD5Transform(ctx->buf, (uint32 *)ctx->in);
                buf += 64;
                len -= 64;
        }

        /* Handle any remaining bytes of data. */

        memcpy(ctx->in, buf, len);
}

/*
 * Final wrapup - pad to 64-byte boundary with the bit pattern 
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
static void MD5Final(unsigned char digest[16], MD5Context *ctx){
        unsigned count;
        unsigned char *p;

        /* Compute number of bytes mod 64 */
        count = (ctx->bits[0] >> 3) & 0x3F;

        /* Set the first char of padding to 0x80.  This is safe since there is
           always at least one byte free */
        p = ctx->in + count;
        *p++ = 0x80;

        /* Bytes of padding needed to make 64 bytes */
        count = 64 - 1 - count;

        /* Pad out to 56 mod 64 */
        if (count < 8) {
                /* Two lots of padding:  Pad the first block to 64 bytes */
                memset(p, 0, count);
                byteReverse(ctx->in, 16);
                MD5Transform(ctx->buf, (uint32 *)ctx->in);

                /* Now fill the next block with 56 bytes */
                memset(ctx->in, 0, 56);
        } else {
                /* Pad block to 56 bytes */
                memset(p, 0, count-8);
        }
        byteReverse(ctx->in, 14);

        /* Append length in bits and transform */
        ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
        ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];

        MD5Transform(ctx->buf, (uint32 *)ctx->in);
        byteReverse((unsigned char *)ctx->buf, 4);
        memcpy(digest, ctx->buf, 16);
        memset(ctx, 0, sizeof(ctx));    /* In case it is sensitive */
}

/*
** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
*/
static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
  static char const zEncode[] = "0123456789abcdef";
  int i, j;

  for(j=i=0; i<16; i++){
    int a = digest[i];
    zBuf[j++] = zEncode[(a>>4)&0xf];
    zBuf[j++] = zEncode[a & 0xf];
  }
  zBuf[j] = 0;
}


/*
** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
** each representing 16 bits of the digest and separated from each
** other by a "-" character.
*/
static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
  int i, j;
  unsigned int x;
  for(i=j=0; i<16; i+=2){
    x = digest[i]*256 + digest[i+1];
    if( i>0 ) zDigest[j++] = '-';
    sprintf(&zDigest[j], "%05u", x);
    j += 5;
  }
  zDigest[j] = 0;
}

/*
** A TCL command for md5.  The argument is the text to be hashed.  The
** Result is the hash in base64.  
*/
static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
  MD5Context ctx;
  unsigned char digest[16];
  char zBuf[50];
  void (*converter)(unsigned char*, char*);

  if( argc!=2 ){
    Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], 
        " TEXT\"", 0);
    return TCL_ERROR;
  }
  MD5Init(&ctx);
  MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
  MD5Final(digest, &ctx);
  converter = (void(*)(unsigned char*,char*))cd;
  converter(digest, zBuf);
  Tcl_AppendResult(interp, zBuf, (char*)0);
  return TCL_OK;
}

/*
** A TCL command to take the md5 hash of a file.  The argument is the
** name of the file.
*/
static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
  FILE *in;
  MD5Context ctx;
  void (*converter)(unsigned char*, char*);
  unsigned char digest[16];
  char zBuf[10240];

  if( argc!=2 ){
    Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], 
        " FILENAME\"", 0);
    return TCL_ERROR;
  }
  in = fopen(argv[1],"rb");
  if( in==0 ){
    Tcl_AppendResult(interp,"unable to open file \"", argv[1], 
         "\" for reading", 0);
    return TCL_ERROR;
  }
  MD5Init(&ctx);
  for(;;){
    int n;
    n = fread(zBuf, 1, sizeof(zBuf), in);
    if( n<=0 ) break;
    MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
  }
  fclose(in);
  MD5Final(digest, &ctx);
  converter = (void(*)(unsigned char*,char*))cd;
  converter(digest, zBuf);
  Tcl_AppendResult(interp, zBuf, (char*)0);
  return TCL_OK;
}

/*
** Register the four new TCL commands for generating MD5 checksums
** with the TCL interpreter.
*/
int Md5_Init(Tcl_Interp *interp){
  Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
                    MD5DigestToBase16, 0);
  Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
                    MD5DigestToBase10x8, 0);
  Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
                    MD5DigestToBase16, 0);
  Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
                    MD5DigestToBase10x8, 0);
  return TCL_OK;
}
#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */

#if defined(SQLITE_TEST)
/*
** During testing, the special md5sum() aggregate function is available.
** inside SQLite.  The following routines implement that function.
*/
static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
  MD5Context *p;
  int i;
  if( argc<1 ) return;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( p==0 ) return;
  if( !p->isInit ){
    MD5Init(p);
  }
  for(i=0; i<argc; i++){
    const char *zData = (char*)sqlite3_value_text(argv[i]);
    if( zData ){
      MD5Update(p, (unsigned char*)zData, strlen(zData));
    }
  }
}
static void md5finalize(sqlite3_context *context){
  MD5Context *p;
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite3_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  MD5DigestToBase16(digest, zBuf);
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
}
int Md5_Register(sqlite3 *db){
  int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0, 
                                 md5step, md5finalize);
  sqlite3_overload_function(db, "md5sum", -1);  /* To exercise this API */
  return rc;
}
#endif /* defined(SQLITE_TEST) */


/*
** If the macro TCLSH is one, then put in code this for the
** "main" routine that will initialize Tcl and take input from
** standard input, or if a file is named on the command line
** the TCL interpreter reads and evaluates that file.
*/
#if TCLSH==1
static char zMainloop[] =
  "set line {}\n"
  "while {![eof stdin]} {\n"
    "if {$line!=\"\"} {\n"
      "puts -nonewline \"> \"\n"
    "} else {\n"
      "puts -nonewline \"% \"\n"
    "}\n"
    "flush stdout\n"
    "append line [gets stdin]\n"
    "if {[info complete $line]} {\n"
      "if {[catch {uplevel #0 $line} result]} {\n"
        "puts stderr \"Error: $result\"\n"
      "} elseif {$result!=\"\"} {\n"
        "puts $result\n"
      "}\n"
      "set line {}\n"
    "} else {\n"
      "append line \\n\n"
    "}\n"
  "}\n"
;
#endif

/*
** If the macro TCLSH is two, then get the main loop code out of
** the separate file "spaceanal_tcl.h".
*/
#if TCLSH==2
static char zMainloop[] = 
#include "spaceanal_tcl.h"
;
#endif

#define TCLSH_MAIN main   /* Needed to fake out mktclapp */
int TCLSH_MAIN(int argc, char **argv){
  Tcl_Interp *interp;
  
  /* Call sqlite3_shutdown() once before doing anything else. This is to
  ** test that sqlite3_shutdown() can be safely called by a process before
  ** sqlite3_initialize() is. */
  sqlite3_shutdown();

  Tcl_FindExecutable(argv[0]);
  interp = Tcl_CreateInterp();
  Sqlite3_Init(interp);
#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
  Md5_Init(interp);
#endif
#ifdef SQLITE_TEST
  {
    extern int Sqliteconfig_Init(Tcl_Interp*);
    extern int Sqlitetest1_Init(Tcl_Interp*);
    extern int Sqlitetest2_Init(Tcl_Interp*);
    extern int Sqlitetest3_Init(Tcl_Interp*);
    extern int Sqlitetest4_Init(Tcl_Interp*);
    extern int Sqlitetest5_Init(Tcl_Interp*);
    extern int Sqlitetest6_Init(Tcl_Interp*);
    extern int Sqlitetest7_Init(Tcl_Interp*);
    extern int Sqlitetest8_Init(Tcl_Interp*);
    extern int Sqlitetest9_Init(Tcl_Interp*);
    extern int Sqlitetestasync_Init(Tcl_Interp*);
    extern int Sqlitetest_autoext_Init(Tcl_Interp*);
    extern int Sqlitetest_func_Init(Tcl_Interp*);
    extern int Sqlitetest_hexio_Init(Tcl_Interp*);
    extern int Sqlitetest_init_Init(Tcl_Interp*);
    extern int Sqlitetest_malloc_Init(Tcl_Interp*);
    extern int Sqlitetest_mutex_Init(Tcl_Interp*);
    extern int Sqlitetestschema_Init(Tcl_Interp*);
    extern int Sqlitetestsse_Init(Tcl_Interp*);
    extern int Sqlitetesttclvar_Init(Tcl_Interp*);
    extern int SqlitetestThread_Init(Tcl_Interp*);
    extern int SqlitetestOnefile_Init();
    extern int SqlitetestOsinst_Init(Tcl_Interp*);
    extern int Sqlitetestbackup_Init(Tcl_Interp*);

    Sqliteconfig_Init(interp);
    Sqlitetest1_Init(interp);
    Sqlitetest2_Init(interp);
    Sqlitetest3_Init(interp);
    Sqlitetest4_Init(interp);
    Sqlitetest5_Init(interp);
    Sqlitetest6_Init(interp);
    Sqlitetest7_Init(interp);
    Sqlitetest8_Init(interp);
    Sqlitetest9_Init(interp);
    Sqlitetestasync_Init(interp);
    Sqlitetest_autoext_Init(interp);
    Sqlitetest_func_Init(interp);
    Sqlitetest_hexio_Init(interp);
    Sqlitetest_init_Init(interp);
    Sqlitetest_malloc_Init(interp);
    Sqlitetest_mutex_Init(interp);
    Sqlitetestschema_Init(interp);
    Sqlitetesttclvar_Init(interp);
    SqlitetestThread_Init(interp);
    SqlitetestOnefile_Init(interp);
    SqlitetestOsinst_Init(interp);
    Sqlitetestbackup_Init(interp);

#ifdef SQLITE_SSE
    Sqlitetestsse_Init(interp);
#endif
  }
#endif
  if( argc>=2 || TCLSH==2 ){
    int i;
    char zArgc[32];
    sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
    Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
    Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
    Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
    for(i=3-TCLSH; i<argc; i++){
      Tcl_SetVar(interp, "argv", argv[i],
          TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
    }
    if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
      const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
      if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
      fprintf(stderr,"%s: %s\n", *argv, zInfo);
      return 1;
    }
  }
  if( argc<=1 || TCLSH==2 ){
    Tcl_GlobalEval(interp, zMainloop);
  }
  return 0;
}
#endif /* TCLSH */

Added src/test1.c.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing all sorts of SQLite interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test1.c,v 1.354 2009/08/10 04:37:50 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
** This is a copy of the first part of the SqliteDb structure in 
** tclsqlite.c.  We need it here so that the get_sqlite_pointer routine
** can extract the sqlite3* pointer from an existing Tcl SQLite
** connection.
*/
struct SqliteDb {
  sqlite3 *db;
};

/*
** Convert text generated by the "%p" conversion format back into
** a pointer.
*/
static int testHexToInt(int h){
  if( h>='0' && h<='9' ){
    return h - '0';
  }else if( h>='a' && h<='f' ){
    return h - 'a' + 10;
  }else{
    assert( h>='A' && h<='F' );
    return h - 'A' + 10;
  }
}
void *sqlite3TestTextToPtr(const char *z){
  void *p;
  u64 v;
  u32 v2;
  if( z[0]=='0' && z[1]=='x' ){
    z += 2;
  }
  v = 0;
  while( *z ){
    v = (v<<4) + testHexToInt(*z);
    z++;
  }
  if( sizeof(p)==sizeof(v) ){
    memcpy(&p, &v, sizeof(p));
  }else{
    assert( sizeof(p)==sizeof(v2) );
    v2 = (u32)v;
    memcpy(&p, &v2, sizeof(p));
  }
  return p;
}


/*
** A TCL command that returns the address of the sqlite* pointer
** for an sqlite connection instance.  Bad things happen if the
** input is not an sqlite connection.
*/
static int get_sqlite_pointer(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  struct SqliteDb *p;
  Tcl_CmdInfo cmdInfo;
  char zBuf[100];
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SQLITE-CONNECTION");
    return TCL_ERROR;
  }
  if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
    Tcl_AppendResult(interp, "command not found: ",
           Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  p = (struct SqliteDb*)cmdInfo.objClientData;
  sprintf(zBuf, "%p", p->db);
  if( strncmp(zBuf,"0x",2) ){
    sprintf(zBuf, "0x%p", p->db);
  }
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Decode a pointer to an sqlite3 object.
*/
int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb){
  struct SqliteDb *p;
  Tcl_CmdInfo cmdInfo;
  if( Tcl_GetCommandInfo(interp, zA, &cmdInfo) ){
    p = (struct SqliteDb*)cmdInfo.objClientData;
    *ppDb = p->db;
  }else{
    *ppDb = (sqlite3*)sqlite3TestTextToPtr(zA);
  }
  return TCL_OK;
}


const char *sqlite3TestErrorName(int rc){
  const char *zName = 0;
  switch( rc ){
    case SQLITE_OK:                  zName = "SQLITE_OK";                break;
    case SQLITE_ERROR:               zName = "SQLITE_ERROR";             break;
    case SQLITE_INTERNAL:            zName = "SQLITE_INTERNAL";          break;
    case SQLITE_PERM:                zName = "SQLITE_PERM";              break;
    case SQLITE_ABORT:               zName = "SQLITE_ABORT";             break;
    case SQLITE_BUSY:                zName = "SQLITE_BUSY";              break;
    case SQLITE_LOCKED:              zName = "SQLITE_LOCKED";            break;
    case SQLITE_LOCKED_SHAREDCACHE:  zName = "SQLITE_LOCKED_SHAREDCACHE";break;
    case SQLITE_NOMEM:               zName = "SQLITE_NOMEM";             break;
    case SQLITE_READONLY:            zName = "SQLITE_READONLY";          break;
    case SQLITE_INTERRUPT:           zName = "SQLITE_INTERRUPT";         break;
    case SQLITE_IOERR:               zName = "SQLITE_IOERR";             break;
    case SQLITE_CORRUPT:             zName = "SQLITE_CORRUPT";           break;
    case SQLITE_NOTFOUND:            zName = "SQLITE_NOTFOUND";          break;
    case SQLITE_FULL:                zName = "SQLITE_FULL";              break;
    case SQLITE_CANTOPEN:            zName = "SQLITE_CANTOPEN";          break;
    case SQLITE_PROTOCOL:            zName = "SQLITE_PROTOCOL";          break;
    case SQLITE_EMPTY:               zName = "SQLITE_EMPTY";             break;
    case SQLITE_SCHEMA:              zName = "SQLITE_SCHEMA";            break;
    case SQLITE_TOOBIG:              zName = "SQLITE_TOOBIG";            break;
    case SQLITE_CONSTRAINT:          zName = "SQLITE_CONSTRAINT";        break;
    case SQLITE_MISMATCH:            zName = "SQLITE_MISMATCH";          break;
    case SQLITE_MISUSE:              zName = "SQLITE_MISUSE";            break;
    case SQLITE_NOLFS:               zName = "SQLITE_NOLFS";             break;
    case SQLITE_AUTH:                zName = "SQLITE_AUTH";              break;
    case SQLITE_FORMAT:              zName = "SQLITE_FORMAT";            break;
    case SQLITE_RANGE:               zName = "SQLITE_RANGE";             break;
    case SQLITE_NOTADB:              zName = "SQLITE_NOTADB";            break;
    case SQLITE_ROW:                 zName = "SQLITE_ROW";               break;
    case SQLITE_DONE:                zName = "SQLITE_DONE";              break;
    case SQLITE_IOERR_READ:          zName = "SQLITE_IOERR_READ";        break;
    case SQLITE_IOERR_SHORT_READ:    zName = "SQLITE_IOERR_SHORT_READ";  break;
    case SQLITE_IOERR_WRITE:         zName = "SQLITE_IOERR_WRITE";       break;
    case SQLITE_IOERR_FSYNC:         zName = "SQLITE_IOERR_FSYNC";       break;
    case SQLITE_IOERR_DIR_FSYNC:     zName = "SQLITE_IOERR_DIR_FSYNC";   break;
    case SQLITE_IOERR_TRUNCATE:      zName = "SQLITE_IOERR_TRUNCATE";    break;
    case SQLITE_IOERR_FSTAT:         zName = "SQLITE_IOERR_FSTAT";       break;
    case SQLITE_IOERR_UNLOCK:        zName = "SQLITE_IOERR_UNLOCK";      break;
    case SQLITE_IOERR_RDLOCK:        zName = "SQLITE_IOERR_RDLOCK";      break;
    case SQLITE_IOERR_DELETE:        zName = "SQLITE_IOERR_DELETE";      break;
    case SQLITE_IOERR_BLOCKED:       zName = "SQLITE_IOERR_BLOCKED";     break;
    case SQLITE_IOERR_NOMEM:         zName = "SQLITE_IOERR_NOMEM";       break;
    case SQLITE_IOERR_ACCESS:        zName = "SQLITE_IOERR_ACCESS";      break;
    case SQLITE_IOERR_CHECKRESERVEDLOCK:
                               zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
    case SQLITE_IOERR_LOCK:          zName = "SQLITE_IOERR_LOCK";        break;
    default:                         zName = "SQLITE_Unknown";           break;
  }
  return zName;
}
#define t1ErrorName sqlite3TestErrorName

/*
** Convert an sqlite3_stmt* into an sqlite3*.  This depends on the
** fact that the sqlite3* is the first field in the Vdbe structure.
*/
#define StmtToDb(X)   sqlite3_db_handle(X)

/*
** Check a return value to make sure it agrees with the results
** from sqlite3_errcode.
*/
int sqlite3TestErrCode(Tcl_Interp *interp, sqlite3 *db, int rc){
  if( sqlite3_threadsafe()==0 && rc!=SQLITE_MISUSE && rc!=SQLITE_OK
   && sqlite3_errcode(db)!=rc ){
    char zBuf[200];
    int r2 = sqlite3_errcode(db);
    sprintf(zBuf, "error code %s (%d) does not match sqlite3_errcode %s (%d)",
       t1ErrorName(rc), rc, t1ErrorName(r2), r2);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, zBuf, 0);
    return 1;
  }
  return 0;
}

/*
** Decode a pointer to an sqlite3_stmt object.
*/
static int getStmtPointer(
  Tcl_Interp *interp, 
  const char *zArg,  
  sqlite3_stmt **ppStmt
){
  *ppStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(zArg);
  return TCL_OK;
}

/*
** Generate a text representation of a pointer that can be understood
** by the getDbPointer and getVmPointer routines above.
**
** The problem is, on some machines (Solaris) if you do a printf with
** "%p" you cannot turn around and do a scanf with the same "%p" and
** get your pointer back.  You have to prepend a "0x" before it will
** work.  Or at least that is what is reported to me (drh).  But this
** behavior varies from machine to machine.  The solution used her is
** to test the string right after it is generated to see if it can be
** understood by scanf, and if not, try prepending an "0x" to see if
** that helps.  If nothing works, a fatal error is generated.
*/
int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p){
  sqlite3_snprintf(100, zPtr, "%p", p);
  return TCL_OK;
}

/*
** The callback routine for sqlite3_exec_printf().
*/
static int exec_printf_cb(void *pArg, int argc, char **argv, char **name){
  Tcl_DString *str = (Tcl_DString*)pArg;
  int i;

  if( Tcl_DStringLength(str)==0 ){
    for(i=0; i<argc; i++){
      Tcl_DStringAppendElement(str, name[i] ? name[i] : "NULL");
    }
  }
  for(i=0; i<argc; i++){
    Tcl_DStringAppendElement(str, argv[i] ? argv[i] : "NULL");
  }
  return 0;
}

/*
** The I/O tracing callback.
*/
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
static FILE *iotrace_file = 0;
static void io_trace_callback(const char *zFormat, ...){
  va_list ap;
  va_start(ap, zFormat);
  vfprintf(iotrace_file, zFormat, ap);
  va_end(ap);
  fflush(iotrace_file);
}
#endif

/*
** Usage:  io_trace FILENAME
**
** Turn I/O tracing on or off.  If FILENAME is not an empty string,
** I/O tracing begins going into FILENAME. If FILENAME is an empty
** string, I/O tracing is turned off.
*/
static int test_io_trace(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
          " FILENAME\"", 0);
    return TCL_ERROR;
  }
  if( iotrace_file ){
    if( iotrace_file!=stdout && iotrace_file!=stderr ){
      fclose(iotrace_file);
    }
    iotrace_file = 0;
    sqlite3IoTrace = 0;
  }
  if( argv[1][0] ){
    if( strcmp(argv[1],"stdout")==0 ){
      iotrace_file = stdout;
    }else if( strcmp(argv[1],"stderr")==0 ){
      iotrace_file = stderr;
    }else{
      iotrace_file = fopen(argv[1], "w");
    }
    sqlite3IoTrace = io_trace_callback;
  }
#endif
  return TCL_OK;
}


/*
** Usage:  sqlite3_exec_printf  DB  FORMAT  STRING
**
** Invoke the sqlite3_exec_printf() interface using the open database
** DB.  The SQL is the string FORMAT.  The format string should contain
** one %s or %q.  STRING is the value inserted into %s or %q.
*/
static int test_exec_printf(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  Tcl_DString str;
  int rc;
  char *zErr = 0;
  char *zSql;
  char zBuf[30];
  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB FORMAT STRING", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite3_mprintf(argv[2], argv[3]);
  rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sqlite3_free(zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite3_free(zErr);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite3_exec_hex  DB  HEX
**
** Invoke the sqlite3_exec() on a string that is obtained by translating
** HEX into ASCII.  Most characters are translated as is.  %HH becomes
** a hex character.
*/
static int test_exec_hex(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  Tcl_DString str;
  int rc, i, j;
  char *zErr = 0;
  char *zHex;
  char zSql[500];
  char zBuf[30];
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB HEX", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  zHex = argv[2];
  for(i=j=0; i<sizeof(zSql) && zHex[j]; i++, j++){
    if( zHex[j]=='%' && zHex[j+2] && zHex[j+2] ){
      zSql[i] = (testHexToInt(zHex[j+1])<<4) + testHexToInt(zHex[j+2]);
      j += 2;
    }else{
      zSql[i] = zHex[j];
    }
  }
  zSql[i] = 0;
  Tcl_DStringInit(&str);
  rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite3_free(zErr);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  db_enter DB
**         db_leave DB
**
** Enter or leave the mutex on a database connection.
*/
static int db_enter(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  sqlite3_mutex_enter(db->mutex);
  return TCL_OK;
}
static int db_leave(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  sqlite3_mutex_leave(db->mutex);
  return TCL_OK;
}

/*
** Usage:  sqlite3_exec  DB  SQL
**
** Invoke the sqlite3_exec interface using the open database DB
*/
static int test_exec(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  Tcl_DString str;
  int rc;
  char *zErr = 0;
  char *zSql;
  int i, j;
  char zBuf[30];
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB SQL", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite3_mprintf("%s", argv[2]);
  for(i=j=0; zSql[i];){
    if( zSql[i]=='%' ){
      zSql[j++] = (testHexToInt(zSql[i+1])<<4) + testHexToInt(zSql[i+2]);
      i += 3;
    }else{
      zSql[j++] = zSql[i++];
    }
  }
  zSql[j] = 0;
  rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sqlite3_free(zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite3_free(zErr);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite3_exec_nr  DB  SQL
**
** Invoke the sqlite3_exec interface using the open database DB.  Discard
** all results
*/
static int test_exec_nr(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  int rc;
  char *zErr = 0;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB SQL", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_z_test  SEPARATOR  ARG0  ARG1 ...
**
** Test the %z format of sqlite_mprintf().  Use multiple mprintf() calls to 
** concatenate arg0 through argn using separator as the separator.
** Return the result.
*/
static int test_mprintf_z(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *zResult = 0;
  int i;

  for(i=2; i<argc && (i==2 || zResult); i++){
    zResult = sqlite3_mprintf("%z%s%s", zResult, argv[1], argv[i]);
  }
  Tcl_AppendResult(interp, zResult, 0);
  sqlite3_free(zResult);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_n_test  STRING
**
** Test the %n format of sqlite_mprintf().  Return the length of the
** input string.
*/
static int test_mprintf_n(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *zStr;
  int n = 0;
  zStr = sqlite3_mprintf("%s%n", argv[1], &n);
  sqlite3_free(zStr);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(n));
  return TCL_OK;
}

/*
** Usage:  sqlite3_snprintf_int  SIZE FORMAT  INT
**
** Test the of sqlite3_snprintf() routine.  SIZE is the size of the
** output buffer in bytes.  The maximum size is 100.  FORMAT is the
** format string.  INT is a single integer argument.  The FORMAT
** string must require no more than this one integer argument.  If
** You pass in a format string that requires more than one argument,
** bad things will happen.
*/
static int test_snprintf_int(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char zStr[100];
  int n = atoi(argv[1]);
  const char *zFormat = argv[2];
  int a1 = atoi(argv[3]);
  if( n>sizeof(zStr) ) n = sizeof(zStr);
  sqlite3_snprintf(sizeof(zStr), zStr, "abcdefghijklmnopqrstuvwxyz");
  sqlite3_snprintf(n, zStr, zFormat, a1);
  Tcl_AppendResult(interp, zStr, 0);
  return TCL_OK;
}

#ifndef SQLITE_OMIT_GET_TABLE

/*
** Usage:  sqlite3_get_table_printf  DB  FORMAT  STRING  ?--no-counts?
**
** Invoke the sqlite3_get_table_printf() interface using the open database
** DB.  The SQL is the string FORMAT.  The format string should contain
** one %s or %q.  STRING is the value inserted into %s or %q.
*/
static int test_get_table_printf(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  Tcl_DString str;
  int rc;
  char *zErr = 0;
  int nRow, nCol;
  char **aResult;
  int i;
  char zBuf[30];
  char *zSql;
  int resCount = -1;
  if( argc==5 ){
    if( Tcl_GetInt(interp, argv[4], &resCount) ) return TCL_ERROR;
  }
  if( argc!=4 && argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB FORMAT STRING ?COUNT?", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite3_mprintf(argv[2],argv[3]);
  if( argc==5 ){
    rc = sqlite3_get_table(db, zSql, &aResult, 0, 0, &zErr);
  }else{
    rc = sqlite3_get_table(db, zSql, &aResult, &nRow, &nCol, &zErr);
    resCount = (nRow+1)*nCol;
  }
  sqlite3_free(zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  if( rc==SQLITE_OK ){
    if( argc==4 ){
      sprintf(zBuf, "%d", nRow);
      Tcl_AppendElement(interp, zBuf);
      sprintf(zBuf, "%d", nCol);
      Tcl_AppendElement(interp, zBuf);
    }
    for(i=0; i<resCount; i++){
      Tcl_AppendElement(interp, aResult[i] ? aResult[i] : "NULL");
    }
  }else{
    Tcl_AppendElement(interp, zErr);
  }
  sqlite3_free_table(aResult);
  if( zErr ) sqlite3_free(zErr);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

#endif /* SQLITE_OMIT_GET_TABLE */


/*
** Usage:  sqlite3_last_insert_rowid DB
**
** Returns the integer ROWID of the most recent insert.
*/
static int test_last_rowid(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  char zBuf[30];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " DB\"", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  sprintf(zBuf, "%lld", sqlite3_last_insert_rowid(db));
  Tcl_AppendResult(interp, zBuf, 0);
  return SQLITE_OK;
}

/*
** Usage:  sqlite3_key DB KEY
**
** Set the codec key.
*/
static int test_key(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  const char *zKey;
  int nKey;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME\"", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  zKey = argv[2];
  nKey = strlen(zKey);
#ifdef SQLITE_HAS_CODEC
  sqlite3_key(db, zKey, nKey);
#endif
  return TCL_OK;
}

/*
** Usage:  sqlite3_rekey DB KEY
**
** Change the codec key.
*/
static int test_rekey(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  const char *zKey;
  int nKey;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME\"", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  zKey = argv[2];
  nKey = strlen(zKey);
#ifdef SQLITE_HAS_CODEC
  sqlite3_rekey(db, zKey, nKey);
#endif
  return TCL_OK;
}

/*
** Usage:  sqlite3_close DB
**
** Closes the database opened by sqlite3_open.
*/
static int sqlite_test_close(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME\"", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_close(db);
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
  return TCL_OK;
}

/*
** Implementation of the x_coalesce() function.
** Return the first argument non-NULL argument.
*/
static void t1_ifnullFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
      int n = sqlite3_value_bytes(argv[i]);
      sqlite3_result_text(context, (char*)sqlite3_value_text(argv[i]),
          n, SQLITE_TRANSIENT);
      break;
    }
  }
}

/*
** These are test functions.    hex8() interprets its argument as
** UTF8 and returns a hex encoding.  hex16le() interprets its argument
** as UTF16le and returns a hex encoding.
*/
static void hex8Func(sqlite3_context *p, int argc, sqlite3_value **argv){
  const unsigned char *z;
  int i;
  char zBuf[200];
  z = sqlite3_value_text(argv[0]);
  for(i=0; i<sizeof(zBuf)/2 - 2 && z[i]; i++){
    sprintf(&zBuf[i*2], "%02x", z[i]&0xff);
  }
  zBuf[i*2] = 0;
  sqlite3_result_text(p, (char*)zBuf, -1, SQLITE_TRANSIENT);
}
#ifndef SQLITE_OMIT_UTF16
static void hex16Func(sqlite3_context *p, int argc, sqlite3_value **argv){
  const unsigned short int *z;
  int i;
  char zBuf[400];
  z = sqlite3_value_text16(argv[0]);
  for(i=0; i<sizeof(zBuf)/4 - 4 && z[i]; i++){
    sprintf(&zBuf[i*4], "%04x", z[i]&0xff);
  }
  zBuf[i*4] = 0;
  sqlite3_result_text(p, (char*)zBuf, -1, SQLITE_TRANSIENT);
}
#endif

/*
** A structure into which to accumulate text.
*/
struct dstr {
  int nAlloc;  /* Space allocated */
  int nUsed;   /* Space used */
  char *z;     /* The space */
};

/*
** Append text to a dstr
*/
static void dstrAppend(struct dstr *p, const char *z, int divider){
  int n = strlen(z);
  if( p->nUsed + n + 2 > p->nAlloc ){
    char *zNew;
    p->nAlloc = p->nAlloc*2 + n + 200;
    zNew = sqlite3_realloc(p->z, p->nAlloc);
    if( zNew==0 ){
      sqlite3_free(p->z);
      memset(p, 0, sizeof(*p));
      return;
    }
    p->z = zNew;
  }
  if( divider && p->nUsed>0 ){
    p->z[p->nUsed++] = divider;
  }
  memcpy(&p->z[p->nUsed], z, n+1);
  p->nUsed += n;
}

/*
** Invoked for each callback from sqlite3ExecFunc
*/
static int execFuncCallback(void *pData, int argc, char **argv, char **NotUsed){
  struct dstr *p = (struct dstr*)pData;
  int i;
  for(i=0; i<argc; i++){
    if( argv[i]==0 ){
      dstrAppend(p, "NULL", ' ');
    }else{
      dstrAppend(p, argv[i], ' ');
    }
  }
  return 0;
}

/*
** Implementation of the x_sqlite_exec() function.  This function takes
** a single argument and attempts to execute that argument as SQL code.
** This is illegal and should set the SQLITE_MISUSE flag on the database.
**
** 2004-Jan-07:  We have changed this to make it legal to call sqlite3_exec()
** from within a function call.  
** 
** This routine simulates the effect of having two threads attempt to
** use the same database at the same time.
*/
static void sqlite3ExecFunc(
  sqlite3_context *context, 
  int argc,  
  sqlite3_value **argv
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  (void)sqlite3_exec((sqlite3*)sqlite3_user_data(context),
      (char*)sqlite3_value_text(argv[0]),
      execFuncCallback, &x, 0);
  sqlite3_result_text(context, x.z, x.nUsed, SQLITE_TRANSIENT);
  sqlite3_free(x.z);
}

/*
** Implementation of tkt2213func(), a scalar function that takes exactly
** one argument. It has two interesting features:
**
** * It calls sqlite3_value_text() 3 times on the argument sqlite3_value*.
**   If the three pointers returned are not the same an SQL error is raised.
**
** * Otherwise it returns a copy of the text representation of its 
**   argument in such a way as the VDBE representation is a Mem* cell 
**   with the MEM_Term flag clear. 
**
** Ticket #2213 can therefore be tested by evaluating the following
** SQL expression:
**
**   tkt2213func(tkt2213func('a string'));
*/
static void tkt2213Function(
  sqlite3_context *context, 
  int argc,  
  sqlite3_value **argv
){
  int nText;
  unsigned char const *zText1;
  unsigned char const *zText2;
  unsigned char const *zText3;

  nText = sqlite3_value_bytes(argv[0]);
  zText1 = sqlite3_value_text(argv[0]);
  zText2 = sqlite3_value_text(argv[0]);
  zText3 = sqlite3_value_text(argv[0]);

  if( zText1!=zText2 || zText2!=zText3 ){
    sqlite3_result_error(context, "tkt2213 is not fixed", -1);
  }else{
    char *zCopy = (char *)sqlite3_malloc(nText);
    memcpy(zCopy, zText1, nText);
    sqlite3_result_text(context, zCopy, nText, sqlite3_free);
  }
}

/*
** The following SQL function takes 4 arguments.  The 2nd and
** 4th argument must be one of these strings:  'text', 'text16',
** or 'blob' corresponding to API functions
**
**      sqlite3_value_text()
**      sqlite3_value_text16()
**      sqlite3_value_blob()
**
** The third argument is a string, either 'bytes' or 'bytes16' or 'noop',
** corresponding to APIs:
**
**      sqlite3_value_bytes()
**      sqlite3_value_bytes16()
**      noop
**
** The APIs designated by the 2nd through 4th arguments are applied
** to the first argument in order.  If the pointers returned by the
** second and fourth are different, this routine returns 1.  Otherwise,
** this routine returns 0.
**
** This function is used to test to see when returned pointers from
** the _text(), _text16() and _blob() APIs become invalidated.
*/
static void ptrChngFunction(
  sqlite3_context *context, 
  int argc,  
  sqlite3_value **argv
){
  const void *p1, *p2;
  const char *zCmd;
  if( argc!=4 ) return;
  zCmd = (const char*)sqlite3_value_text(argv[1]);
  if( zCmd==0 ) return;
  if( strcmp(zCmd,"text")==0 ){
    p1 = (const void*)sqlite3_value_text(argv[0]);
#ifndef SQLITE_OMIT_UTF16
  }else if( strcmp(zCmd, "text16")==0 ){
    p1 = (const void*)sqlite3_value_text16(argv[0]);
#endif
  }else if( strcmp(zCmd, "blob")==0 ){
    p1 = (const void*)sqlite3_value_blob(argv[0]);
  }else{
    return;
  }
  zCmd = (const char*)sqlite3_value_text(argv[2]);
  if( zCmd==0 ) return;
  if( strcmp(zCmd,"bytes")==0 ){
    sqlite3_value_bytes(argv[0]);
#ifndef SQLITE_OMIT_UTF16
  }else if( strcmp(zCmd, "bytes16")==0 ){
    sqlite3_value_bytes16(argv[0]);
#endif
  }else if( strcmp(zCmd, "noop")==0 ){
    /* do nothing */
  }else{
    return;
  }
  zCmd = (const char*)sqlite3_value_text(argv[3]);
  if( zCmd==0 ) return;
  if( strcmp(zCmd,"text")==0 ){
    p2 = (const void*)sqlite3_value_text(argv[0]);
#ifndef SQLITE_OMIT_UTF16
  }else if( strcmp(zCmd, "text16")==0 ){
    p2 = (const void*)sqlite3_value_text16(argv[0]);
#endif
  }else if( strcmp(zCmd, "blob")==0 ){
    p2 = (const void*)sqlite3_value_blob(argv[0]);
  }else{
    return;
  }
  sqlite3_result_int(context, p1!=p2);
}


/*
** Usage:  sqlite_test_create_function DB
**
** Call the sqlite3_create_function API on the given database in order
** to create a function named "x_coalesce".  This function does the same thing
** as the "coalesce" function.  This function also registers an SQL function
** named "x_sqlite_exec" that invokes sqlite3_exec().  Invoking sqlite3_exec()
** in this way is illegal recursion and should raise an SQLITE_MISUSE error.
** The effect is similar to trying to use the same database connection from
** two threads at the same time.
**
** The original motivation for this routine was to be able to call the
** sqlite3_create_function function while a query is in progress in order
** to test the SQLITE_MISUSE detection logic.
*/
static int test_create_function(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int rc;
  sqlite3 *db;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " DB\"", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_create_function(db, "x_coalesce", -1, SQLITE_ANY, 0, 
        t1_ifnullFunc, 0, 0);
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "hex8", 1, SQLITE_ANY, 0, 
          hex8Func, 0, 0);
  }
#ifndef SQLITE_OMIT_UTF16
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "hex16", 1, SQLITE_ANY, 0, 
          hex16Func, 0, 0);
  }
#endif
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "tkt2213func", 1, SQLITE_ANY, 0, 
          tkt2213Function, 0, 0);
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "pointer_change", 4, SQLITE_ANY, 0, 
          ptrChngFunction, 0, 0);
  }

#ifndef SQLITE_OMIT_UTF16
  /* Use the sqlite3_create_function16() API here. Mainly for fun, but also 
  ** because it is not tested anywhere else. */
  if( rc==SQLITE_OK ){
    const void *zUtf16;
    sqlite3_value *pVal;
    sqlite3_mutex_enter(db->mutex);
    pVal = sqlite3ValueNew(db);
    sqlite3ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE_UTF8, SQLITE_STATIC);
    zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
    if( db->mallocFailed ){
      rc = SQLITE_NOMEM;
    }else{
      rc = sqlite3_create_function16(db, zUtf16, 
                1, SQLITE_UTF16, db, sqlite3ExecFunc, 0, 0);
    }
    sqlite3ValueFree(pVal);
    sqlite3_mutex_leave(db->mutex);
  }
#endif

  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}

/*
** Routines to implement the x_count() aggregate function.
**
** x_count() counts the number of non-null arguments.  But there are
** some twists for testing purposes.
**
** If the argument to x_count() is 40 then a UTF-8 error is reported
** on the step function.  If x_count(41) is seen, then a UTF-16 error
** is reported on the step function.  If the total count is 42, then
** a UTF-8 error is reported on the finalize function.
*/
typedef struct t1CountCtx t1CountCtx;
struct t1CountCtx {
  int n;
};
static void t1CountStep(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  t1CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0]) ) && p ){
    p->n++;
  }
  if( argc>0 ){
    int v = sqlite3_value_int(argv[0]);
    if( v==40 ){
      sqlite3_result_error(context, "value of 40 handed to x_count", -1);
#ifndef SQLITE_OMIT_UTF16
    }else if( v==41 ){
      const char zUtf16ErrMsg[] = { 0, 0x61, 0, 0x62, 0, 0x63, 0, 0, 0};
      sqlite3_result_error16(context, &zUtf16ErrMsg[1-SQLITE_BIGENDIAN], -1);
#endif
    }
  }
}   
static void t1CountFinalize(sqlite3_context *context){
  t1CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( p ){
    if( p->n==42 ){
      sqlite3_result_error(context, "x_count totals to 42", -1);
    }else{
      sqlite3_result_int(context, p ? p->n : 0);
    }
  }
}

#ifndef SQLITE_OMIT_DEPRECATED
static void legacyCountStep(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  /* no-op */
}

static void legacyCountFinalize(sqlite3_context *context){
  sqlite3_result_int(context, sqlite3_aggregate_count(context));
}
#endif

/*
** Usage:  sqlite3_create_aggregate DB
**
** Call the sqlite3_create_function API on the given database in order
** to create a function named "x_count".  This function is similar
** to the built-in count() function, with a few special quirks
** for testing the sqlite3_result_error() APIs.
**
** The original motivation for this routine was to be able to call the
** sqlite3_create_aggregate function while a query is in progress in order
** to test the SQLITE_MISUSE detection logic.  See misuse.test.
**
** This routine was later extended to test the use of sqlite3_result_error()
** within aggregate functions.
**
** Later: It is now also extended to register the aggregate function
** "legacy_count()" with the supplied database handle. This is used
** to test the deprecated sqlite3_aggregate_count() API.
*/
static int test_create_aggregate(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME\"", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_create_function(db, "x_count", 0, SQLITE_UTF8, 0, 0,
      t1CountStep,t1CountFinalize);
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "x_count", 1, SQLITE_UTF8, 0, 0,
        t1CountStep,t1CountFinalize);
  }
#ifndef SQLITE_OMIT_DEPRECATED
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "legacy_count", 0, SQLITE_ANY, 0, 0,
        legacyCountStep, legacyCountFinalize
    );
  }
#endif
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}


/*
** Usage:  printf TEXT
**
** Send output to printf.  Use this rather than puts to merge the output
** in the correct sequence with debugging printfs inserted into C code.
** Puts uses a separate buffer and debugging statements will be out of
** sequence if it is used.
*/
static int test_printf(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " TEXT\"", 0);
    return TCL_ERROR;
  }
  printf("%s\n", argv[1]);
  return TCL_OK;
}



/*
** Usage:  sqlite3_mprintf_int FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three integer arguments
*/
static int sqlite3_mprintf_int(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int a[3], i;
  char *z;
  if( argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT INT\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_int64 FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three 64-bit integer arguments
*/
static int sqlite3_mprintf_int64(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int i;
  sqlite_int64 a[3];
  char *z;
  if( argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT INT\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( !sqlite3Atoi64(argv[i], &a[i-2]) ){
      Tcl_AppendResult(interp, "argument is not a valid 64-bit integer", 0);
      return TCL_ERROR;
    }
  }
  z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_long FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three long integer arguments.   This might be the
** same as sqlite3_mprintf_int or sqlite3_mprintf_int64, depending on
** platform.
*/
static int sqlite3_mprintf_long(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int i;
  long int a[3];
  int b[3];
  char *z;
  if( argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT INT\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &b[i-2]) ) return TCL_ERROR;
    a[i-2] = (long int)b[i-2];
    a[i-2] &= (((u64)1)<<(sizeof(int)*8))-1;
  }
  z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_str FORMAT INTEGER INTEGER STRING
**
** Call mprintf with two integer arguments and one string argument
*/
static int sqlite3_mprintf_str(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int a[3], i;
  char *z;
  if( argc<4 || argc>5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT ?STRING?\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  z = sqlite3_mprintf(argv[1], a[0], a[1], argc>4 ? argv[4] : NULL);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_snprintf_str INTEGER FORMAT INTEGER INTEGER STRING
**
** Call mprintf with two integer arguments and one string argument
*/
static int sqlite3_snprintf_str(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int a[3], i;
  int n;
  char *z;
  if( argc<5 || argc>6 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " INT FORMAT INT INT ?STRING?\"", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR;
  if( n<0 ){
    Tcl_AppendResult(interp, "N must be non-negative", 0);
    return TCL_ERROR;
  }
  for(i=3; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-3]) ) return TCL_ERROR;
  }
  z = sqlite3_malloc( n+1 );
  sqlite3_snprintf(n, z, argv[2], a[0], a[1], argc>4 ? argv[5] : NULL);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_double FORMAT INTEGER INTEGER DOUBLE
**
** Call mprintf with two integer arguments and one double argument
*/
static int sqlite3_mprintf_double(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int a[3], i;
  double r;
  char *z;
  if( argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT DOUBLE\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR;
  z = sqlite3_mprintf(argv[1], a[0], a[1], r);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_scaled FORMAT DOUBLE DOUBLE
**
** Call mprintf with a single double argument which is the product of the
** two arguments given above.  This is used to generate overflow and underflow
** doubles to test that they are converted properly.
*/
static int sqlite3_mprintf_scaled(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  int i;
  double r[2];
  char *z;
  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT DOUBLE DOUBLE\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetDouble(interp, argv[i], &r[i-2]) ) return TCL_ERROR;
  }
  z = sqlite3_mprintf(argv[1], r[0]*r[1]);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_stronly FORMAT STRING
**
** Call mprintf with a single double argument which is the product of the
** two arguments given above.  This is used to generate overflow and underflow
** doubles to test that they are converted properly.
*/
static int sqlite3_mprintf_stronly(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *z;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT STRING\"", 0);
    return TCL_ERROR;
  }
  z = sqlite3_mprintf(argv[1], argv[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite3_mprintf_hexdouble FORMAT HEX
**
** Call mprintf with a single double argument which is derived from the
** hexadecimal encoding of an IEEE double.
*/
static int sqlite3_mprintf_hexdouble(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *z;
  double r;
  unsigned int x1, x2;
  sqlite_uint64 d;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT STRING\"", 0);
    return TCL_ERROR;
  }
  if( sscanf(argv[2], "%08x%08x", &x2, &x1)!=2 ){
    Tcl_AppendResult(interp, "2nd argument should be 16-characters of hex", 0);
    return TCL_ERROR;
  }
  d = x2;
  d = (d<<32) + x1;
  memcpy(&r, &d, sizeof(r));
  z = sqlite3_mprintf(argv[1], r);
  Tcl_AppendResult(interp, z, 0);
  sqlite3_free(z);
  return TCL_OK;
}

/*
** Usage: sqlite3_enable_shared_cache ?BOOLEAN?
**
*/
#if !defined(SQLITE_OMIT_SHARED_CACHE)
static int test_enable_shared(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int rc;
  int enable;
  int ret = 0;

  if( objc!=2 && objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "?BOOLEAN?");
    return TCL_ERROR;
  }
  ret = sqlite3GlobalConfig.sharedCacheEnabled;

  if( objc==2 ){
    if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ){
      return TCL_ERROR;
    }
    rc = sqlite3_enable_shared_cache(enable);
    if( rc!=SQLITE_OK ){
      Tcl_SetResult(interp, (char *)sqlite3ErrStr(rc), TCL_STATIC);
      return TCL_ERROR;
    }
  }
  Tcl_SetObjResult(interp, Tcl_NewBooleanObj(ret));
  return TCL_OK;
}
#endif



/*
** Usage: sqlite3_extended_result_codes   DB    BOOLEAN
**
*/
static int test_extended_result_codes(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int enable;
  sqlite3 *db;

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  if( Tcl_GetBooleanFromObj(interp, objv[2], &enable) ) return TCL_ERROR;
  sqlite3_extended_result_codes(db, enable);
  return TCL_OK;
}

/*
** Usage: sqlite3_libversion_number
**
*/
static int test_libversion_number(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_libversion_number()));
  return TCL_OK;
}

/*
** Usage: sqlite3_table_column_metadata DB dbname tblname colname
**
*/
#ifdef SQLITE_ENABLE_COLUMN_METADATA
static int test_table_column_metadata(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  const char *zDb;
  const char *zTbl;
  const char *zCol;
  int rc;
  Tcl_Obj *pRet;

  const char *zDatatype;
  const char *zCollseq;
  int notnull;
  int primarykey;
  int autoincrement;

  if( objc!=5 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB dbname tblname colname");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zDb = Tcl_GetString(objv[2]);
  zTbl = Tcl_GetString(objv[3]);
  zCol = Tcl_GetString(objv[4]);

  if( strlen(zDb)==0 ) zDb = 0;

  rc = sqlite3_table_column_metadata(db, zDb, zTbl, zCol, 
      &zDatatype, &zCollseq, &notnull, &primarykey, &autoincrement);

  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3_errmsg(db), 0);
    return TCL_ERROR;
  }

  pRet = Tcl_NewObj();
  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zDatatype, -1));
  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zCollseq, -1));
  Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(notnull));
  Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(primarykey));
  Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(autoincrement));
  Tcl_SetObjResult(interp, pRet);

  return TCL_OK;
}
#endif

#ifndef SQLITE_OMIT_INCRBLOB

/*
** sqlite3_blob_read  CHANNEL OFFSET N
**
**   This command is used to test the sqlite3_blob_read() in ways that
**   the Tcl channel interface does not. The first argument should
**   be the name of a valid channel created by the [incrblob] method
**   of a database handle. This function calls sqlite3_blob_read()
**   to read N bytes from offset OFFSET from the underlying SQLite
**   blob handle.
**
**   On success, a byte-array object containing the read data is 
**   returned. On failure, the interpreter result is set to the
**   text representation of the returned error code (i.e. "SQLITE_NOMEM")
**   and a Tcl exception is thrown.
*/
static int test_blob_read(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_Channel channel;
  ClientData instanceData;
  sqlite3_blob *pBlob;
  int notUsed;
  int nByte;
  int iOffset;
  unsigned char *zBuf;
  int rc;
  
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET N");
    return TCL_ERROR;
  }

  channel = Tcl_GetChannel(interp, Tcl_GetString(objv[1]), &notUsed);
  if( !channel
   || TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset)
   || TCL_OK!=Tcl_GetIntFromObj(interp, objv[3], &nByte)
   || nByte<0 || iOffset<0
  ){ 
    return TCL_ERROR;
  }

  instanceData = Tcl_GetChannelInstanceData(channel);
  pBlob = *((sqlite3_blob **)instanceData);

  zBuf = (unsigned char *)Tcl_Alloc(nByte);
  rc = sqlite3_blob_read(pBlob, zBuf, nByte, iOffset);
  if( rc==SQLITE_OK ){
    Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zBuf, nByte));
  }else{
    Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  }
  Tcl_Free((char *)zBuf);

  return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR);
}

/*
** sqlite3_blob_write CHANNEL OFFSET DATA ?NDATA?
**
**   This command is used to test the sqlite3_blob_write() in ways that
**   the Tcl channel interface does not. The first argument should
**   be the name of a valid channel created by the [incrblob] method
**   of a database handle. This function calls sqlite3_blob_write()
**   to write the DATA byte-array to the underlying SQLite blob handle.
**   at offset OFFSET.
**
**   On success, an empty string is returned. On failure, the interpreter
**   result is set to the text representation of the returned error code 
**   (i.e. "SQLITE_NOMEM") and a Tcl exception is thrown.
*/
static int test_blob_write(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_Channel channel;
  ClientData instanceData;
  sqlite3_blob *pBlob;
  int notUsed;
  int iOffset;
  int rc;

  unsigned char *zBuf;
  int nBuf;
  
  if( objc!=4 && objc!=5 ){
    Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET DATA ?NDATA?");
    return TCL_ERROR;
  }

  channel = Tcl_GetChannel(interp, Tcl_GetString(objv[1]), &notUsed);
  if( !channel || TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset) ){ 
    return TCL_ERROR;
  }

  instanceData = Tcl_GetChannelInstanceData(channel);
  pBlob = *((sqlite3_blob **)instanceData);

  zBuf = Tcl_GetByteArrayFromObj(objv[3], &nBuf);
  if( objc==5 && Tcl_GetIntFromObj(interp, objv[4], &nBuf) ){
    return TCL_ERROR;
  }
  rc = sqlite3_blob_write(pBlob, zBuf, nBuf, iOffset);
  if( rc!=SQLITE_OK ){
    Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  }

  return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR);
}
#endif

/*
** Usage: sqlite3_create_collation_v2 DB-HANDLE NAME CMP-PROC DEL-PROC
**
**   This Tcl proc is used for testing the experimental
**   sqlite3_create_collation_v2() interface.
*/
struct TestCollationX {
  Tcl_Interp *interp;
  Tcl_Obj *pCmp;
  Tcl_Obj *pDel;
};
typedef struct TestCollationX TestCollationX;
static void testCreateCollationDel(void *pCtx){
  TestCollationX *p = (TestCollationX *)pCtx;

  int rc = Tcl_EvalObjEx(p->interp, p->pDel, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
  if( rc!=TCL_OK ){
    Tcl_BackgroundError(p->interp);
  }

  Tcl_DecrRefCount(p->pCmp);
  Tcl_DecrRefCount(p->pDel);
  sqlite3_free((void *)p);
}
static int testCreateCollationCmp(
  void *pCtx,
  int nLeft,
  const void *zLeft,
  int nRight,
  const void *zRight
){
  TestCollationX *p = (TestCollationX *)pCtx;
  Tcl_Obj *pScript = Tcl_DuplicateObj(p->pCmp);
  int iRes = 0;

  Tcl_IncrRefCount(pScript);
  Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zLeft, nLeft));
  Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zRight,nRight));

  if( TCL_OK!=Tcl_EvalObjEx(p->interp, pScript, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL)
   || TCL_OK!=Tcl_GetIntFromObj(p->interp, Tcl_GetObjResult(p->interp), &iRes)
  ){
    Tcl_BackgroundError(p->interp);
  }
  Tcl_DecrRefCount(pScript);

  return iRes;
}
static int test_create_collation_v2(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  TestCollationX *p;
  sqlite3 *db;
  int rc;

  if( objc!=5 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE NAME CMP-PROC DEL-PROC");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  p = (TestCollationX *)sqlite3_malloc(sizeof(TestCollationX));
  p->pCmp = objv[3];
  p->pDel = objv[4];
  p->interp = interp;
  Tcl_IncrRefCount(p->pCmp);
  Tcl_IncrRefCount(p->pDel);

  rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), 16, 
      (void *)p, testCreateCollationCmp, testCreateCollationDel
  );
  if( rc!=SQLITE_MISUSE ){
    Tcl_AppendResult(interp, "sqlite3_create_collate_v2() failed to detect "
      "an invalid encoding", (char*)0);
    return TCL_ERROR;
  }
  rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), SQLITE_UTF8, 
      (void *)p, testCreateCollationCmp, testCreateCollationDel
  );
  return TCL_OK;
}

/*
** Usage: sqlite3_load_extension DB-HANDLE FILE ?PROC?
*/
static int test_load_extension(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_CmdInfo cmdInfo;
  sqlite3 *db;
  int rc;
  char *zDb;
  char *zFile;
  char *zProc = 0;
  char *zErr = 0;

  if( objc!=4 && objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE FILE ?PROC?");
    return TCL_ERROR;
  }
  zDb = Tcl_GetString(objv[1]);
  zFile = Tcl_GetString(objv[2]);
  if( objc==4 ){
    zProc = Tcl_GetString(objv[3]);
  }

  /* Extract the C database handle from the Tcl command name */
  if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){
    Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0);
    return TCL_ERROR;
  }
  db = ((struct SqliteDb*)cmdInfo.objClientData)->db;
  assert(db);

  /* Call the underlying C function. If an error occurs, set rc to 
  ** TCL_ERROR and load any error string into the interpreter. If no 
  ** error occurs, set rc to TCL_OK.
  */
#ifdef SQLITE_OMIT_LOAD_EXTENSION
  rc = SQLITE_ERROR;
  zErr = sqlite3_mprintf("this build omits sqlite3_load_extension()");
#else
  rc = sqlite3_load_extension(db, zFile, zProc, &zErr);
#endif
  if( rc!=SQLITE_OK ){
    Tcl_SetResult(interp, zErr ? zErr : "", TCL_VOLATILE);
    rc = TCL_ERROR;
  }else{
    rc = TCL_OK;
  }
  sqlite3_free(zErr);

  return rc;
}

/*
** Usage: sqlite3_enable_load_extension DB-HANDLE ONOFF
*/
static int test_enable_load(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_CmdInfo cmdInfo;
  sqlite3 *db;
  char *zDb;
  int onoff;

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE ONOFF");
    return TCL_ERROR;
  }
  zDb = Tcl_GetString(objv[1]);

  /* Extract the C database handle from the Tcl command name */
  if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){
    Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0);
    return TCL_ERROR;
  }
  db = ((struct SqliteDb*)cmdInfo.objClientData)->db;
  assert(db);

  /* Get the onoff parameter */
  if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
    return TCL_ERROR;
  }

#ifdef SQLITE_OMIT_LOAD_EXTENSION
  Tcl_AppendResult(interp, "this build omits sqlite3_load_extension()");
  return TCL_ERROR;
#else
  sqlite3_enable_load_extension(db, onoff);
  return TCL_OK;
#endif
}

/*
** Usage:  sqlite_abort
**
** Shutdown the process immediately.  This is not a clean shutdown.
** This command is used to test the recoverability of a database in
** the event of a program crash.
*/
static int sqlite_abort(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  assert( interp==0 );   /* This will always fail */
  return TCL_OK;
}

/*
** The following routine is a user-defined SQL function whose purpose
** is to test the sqlite_set_result() API.
*/
static void testFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  while( argc>=2 ){
    const char *zArg0 = (char*)sqlite3_value_text(argv[0]);
    if( zArg0 ){
      if( 0==sqlite3StrICmp(zArg0, "int") ){
        sqlite3_result_int(context, sqlite3_value_int(argv[1]));
      }else if( sqlite3StrICmp(zArg0,"int64")==0 ){
        sqlite3_result_int64(context, sqlite3_value_int64(argv[1]));
      }else if( sqlite3StrICmp(zArg0,"string")==0 ){
        sqlite3_result_text(context, (char*)sqlite3_value_text(argv[1]), -1,
            SQLITE_TRANSIENT);
      }else if( sqlite3StrICmp(zArg0,"double")==0 ){
        sqlite3_result_double(context, sqlite3_value_double(argv[1]));
      }else if( sqlite3StrICmp(zArg0,"null")==0 ){
        sqlite3_result_null(context);
      }else if( sqlite3StrICmp(zArg0,"value")==0 ){
        sqlite3_result_value(context, argv[sqlite3_value_int(argv[1])]);
      }else{
        goto error_out;
      }
    }else{
      goto error_out;
    }
    argc -= 2;
    argv += 2;
  }
  return;

error_out:
  sqlite3_result_error(context,"first argument should be one of: "
      "int int64 string double null value", -1);
}

/*
** Usage:   sqlite_register_test_function  DB  NAME
**
** Register the test SQL function on the database DB under the name NAME.
*/
static int test_register_func(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3 *db;
  int rc;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB FUNCTION-NAME", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, 
      testFunc, 0, 0);
  if( rc!=0 ){
    Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
    return TCL_ERROR;
  }
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite3_finalize  STMT 
**
** Finalize a statement handle.
*/
static int test_finalize(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int rc;
  sqlite3 *db = 0;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;

  if( pStmt ){
    db = StmtToDb(pStmt);
  }
  rc = sqlite3_finalize(pStmt);
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
  if( db && sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite3_stmt_status  STMT  CODE  RESETFLAG
**
** Get the value of a status counter from a statement.
*/
static int test_stmt_status(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int iValue;
  int i, op, resetFlag;
  const char *zOpName;
  sqlite3_stmt *pStmt;

  static const struct {
    const char *zName;
    int op;
  } aOp[] = {
    { "SQLITE_STMTSTATUS_FULLSCAN_STEP",   SQLITE_STMTSTATUS_FULLSCAN_STEP   },
    { "SQLITE_STMTSTATUS_SORT",            SQLITE_STMTSTATUS_SORT            },
  };
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT PARAMETER RESETFLAG");
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  zOpName = Tcl_GetString(objv[2]);
  for(i=0; i<ArraySize(aOp); i++){
    if( strcmp(aOp[i].zName, zOpName)==0 ){
      op = aOp[i].op;
      break;
    }
  }
  if( i>=ArraySize(aOp) ){
    if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR;
  }
  if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR;
  iValue = sqlite3_stmt_status(pStmt, op, resetFlag);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(iValue));
  return TCL_OK;
}

/*
** Usage:  sqlite3_next_stmt  DB  STMT
**
** Return the next statment in sequence after STMT.
*/
static int test_next_stmt(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  sqlite3 *db = 0;
  char zBuf[50];

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " DB STMT", 0);
    return TCL_ERROR;
  }

  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt) ) return TCL_ERROR;
  pStmt = sqlite3_next_stmt(db, pStmt);
  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}


/*
** Usage:  sqlite3_reset  STMT 
**
** Reset a statement handle.
*/
static int test_reset(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;

  rc = sqlite3_reset(pStmt);
  if( pStmt && sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ){
    return TCL_ERROR;
  }
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
/*
  if( rc ){
    return TCL_ERROR;
  }
*/
  return TCL_OK;
}

/*
** Usage:  sqlite3_expired STMT 
**
** Return TRUE if a recompilation of the statement is recommended.
*/
static int test_expired(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_stmt *pStmt;
  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sqlite3_expired(pStmt)));
#endif
  return TCL_OK;
}

/*
** Usage:  sqlite3_transfer_bindings FROMSTMT TOSTMT
**
** Transfer all bindings from FROMSTMT over to TOSTMT
*/
static int test_transfer_bind(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_stmt *pStmt1, *pStmt2;
  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " FROM-STMT TO-STMT", 0);
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt1)) return TCL_ERROR;
  if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt2)) return TCL_ERROR;
  Tcl_SetObjResult(interp, 
     Tcl_NewIntObj(sqlite3_transfer_bindings(pStmt1,pStmt2)));
#endif
  return TCL_OK;
}

/*
** Usage:  sqlite3_changes DB
**
** Return the number of changes made to the database by the last SQL
** execution.
*/
static int test_changes(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
       Tcl_GetString(objv[0]), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_changes(db)));
  return TCL_OK;
}

/*
** This is the "static_bind_value" that variables are bound to when
** the FLAG option of sqlite3_bind is "static"
*/
static char *sqlite_static_bind_value = 0;
static int sqlite_static_bind_nbyte = 0;

/*
** Usage:  sqlite3_bind  VM  IDX  VALUE  FLAGS
**
** Sets the value of the IDX-th occurance of "?" in the original SQL
** string.  VALUE is the new value.  If FLAGS=="null" then VALUE is
** ignored and the value is set to NULL.  If FLAGS=="static" then
** the value is set to the value of a static variable named
** "sqlite_static_bind_value".  If FLAGS=="normal" then a copy
** of the VALUE is made.  If FLAGS=="blob10" then a VALUE is ignored
** an a 10-byte blob "abc\000xyz\000pq" is inserted.
*/
static int test_bind(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite3_stmt *pStmt;
  int rc;
  int idx;
  if( argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " VM IDX VALUE (null|static|normal)\"", 0);
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, argv[1], &pStmt) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[2], &idx) ) return TCL_ERROR;
  if( strcmp(argv[4],"null")==0 ){
    rc = sqlite3_bind_null(pStmt, idx);
  }else if( strcmp(argv[4],"static")==0 ){
    rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value, -1, 0);
  }else if( strcmp(argv[4],"static-nbytes")==0 ){
    rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value,
                                       sqlite_static_bind_nbyte, 0);
  }else if( strcmp(argv[4],"normal")==0 ){
    rc = sqlite3_bind_text(pStmt, idx, argv[3], -1, SQLITE_TRANSIENT);
  }else if( strcmp(argv[4],"blob10")==0 ){
    rc = sqlite3_bind_text(pStmt, idx, "abc\000xyz\000pq", 10, SQLITE_STATIC);
  }else{
    Tcl_AppendResult(interp, "4th argument should be "
        "\"null\" or \"static\" or \"normal\"", 0);
    return TCL_ERROR;
  }
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc ){
    char zBuf[50];
    sprintf(zBuf, "(%d) ", rc);
    Tcl_AppendResult(interp, zBuf, sqlite3ErrStr(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

#ifndef SQLITE_OMIT_UTF16
/*
** Usage: add_test_collate <db ptr> <utf8> <utf16le> <utf16be>
**
** This function is used to test that SQLite selects the correct collation
** sequence callback when multiple versions (for different text encodings)
** are available.
**
** Calling this routine registers the collation sequence "test_collate"
** with database handle <db>. The second argument must be a list of three
** boolean values. If the first is true, then a version of test_collate is
** registered for UTF-8, if the second is true, a version is registered for
** UTF-16le, if the third is true, a UTF-16be version is available.
** Previous versions of test_collate are deleted.
**
** The collation sequence test_collate is implemented by calling the
** following TCL script:
**
**   "test_collate <enc> <lhs> <rhs>"
**
** The <lhs> and <rhs> are the two values being compared, encoded in UTF-8.
** The <enc> parameter is the encoding of the collation function that
** SQLite selected to call. The TCL test script implements the
** "test_collate" proc.
**
** Note that this will only work with one intepreter at a time, as the
** interp pointer to use when evaluating the TCL script is stored in
** pTestCollateInterp.
*/
static Tcl_Interp* pTestCollateInterp;
static int test_collate_func(
  void *pCtx, 
  int nA, const void *zA,
  int nB, const void *zB
){
  Tcl_Interp *i = pTestCollateInterp;
  int encin = (int)pCtx;
  int res;
  int n;

  sqlite3_value *pVal;
  Tcl_Obj *pX;

  pX = Tcl_NewStringObj("test_collate", -1);
  Tcl_IncrRefCount(pX);

  switch( encin ){
    case SQLITE_UTF8:
      Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-8",-1));
      break;
    case SQLITE_UTF16LE:
      Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16LE",-1));
      break;
    case SQLITE_UTF16BE:
      Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16BE",-1));
      break;
    default:
      assert(0);
  }

  sqlite3BeginBenignMalloc();
  pVal = sqlite3ValueNew(0);
  if( pVal ){
    sqlite3ValueSetStr(pVal, nA, zA, encin, SQLITE_STATIC);
    n = sqlite3_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n));
    sqlite3ValueSetStr(pVal, nB, zB, encin, SQLITE_STATIC);
    n = sqlite3_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n));
    sqlite3ValueFree(pVal);
  }
  sqlite3EndBenignMalloc();

  Tcl_EvalObjEx(i, pX, 0);
  Tcl_DecrRefCount(pX);
  Tcl_GetIntFromObj(i, Tcl_GetObjResult(i), &res);
  return res;
}
static int test_collate(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  int val;
  sqlite3_value *pVal;
  int rc;

  if( objc!=5 ) goto bad_args;
  pTestCollateInterp = interp;
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR;
  rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF8, 
          (void *)SQLITE_UTF8, val?test_collate_func:0);
  if( rc==SQLITE_OK ){
    const void *zUtf16;
    if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR;
    rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF16LE, 
            (void *)SQLITE_UTF16LE, val?test_collate_func:0);
    if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR;

#if 0
    if( sqlite3_iMallocFail>0 ){
      sqlite3_iMallocFail++;
    }
#endif
    sqlite3_mutex_enter(db->mutex);
    pVal = sqlite3ValueNew(db);
    sqlite3ValueSetStr(pVal, -1, "test_collate", SQLITE_UTF8, SQLITE_STATIC);
    zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
    if( db->mallocFailed ){
      rc = SQLITE_NOMEM;
    }else{
      rc = sqlite3_create_collation16(db, zUtf16, SQLITE_UTF16BE, 
          (void *)SQLITE_UTF16BE, val?test_collate_func:0);
    }
    sqlite3ValueFree(pVal);
    sqlite3_mutex_leave(db->mutex);
  }
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;

bad_args:
  Tcl_AppendResult(interp, "wrong # args: should be \"",
      Tcl_GetStringFromObj(objv[0], 0), " <DB> <utf8> <utf16le> <utf16be>", 0);
  return TCL_ERROR;
}

/*
** When the collation needed callback is invoked, record the name of 
** the requested collating function here.  The recorded name is linked
** to a TCL variable and used to make sure that the requested collation
** name is correct.
*/
static char zNeededCollation[200];
static char *pzNeededCollation = zNeededCollation;


/*
** Called when a collating sequence is needed.  Registered using
** sqlite3_collation_needed16().
*/
static void test_collate_needed_cb(
  void *pCtx, 
  sqlite3 *db,
  int eTextRep,
  const void *pName
){
  int enc = ENC(db);
  int i;
  char *z;
  for(z = (char*)pName, i=0; *z || z[1]; z++){
    if( *z ) zNeededCollation[i++] = *z;
  }
  zNeededCollation[i] = 0;
  sqlite3_create_collation(
      db, "test_collate", ENC(db), (void *)enc, test_collate_func);
}

/*
** Usage: add_test_collate_needed DB
*/
static int test_collate_needed(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  int rc;

  if( objc!=2 ) goto bad_args;
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite3_collation_needed16(db, 0, test_collate_needed_cb);
  zNeededCollation[0] = 0;
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;

bad_args:
  Tcl_WrongNumArgs(interp, 1, objv, "DB");
  return TCL_ERROR;
}

/*
** tclcmd:   add_alignment_test_collations  DB
**
** Add two new collating sequences to the database DB
**
**     utf16_aligned
**     utf16_unaligned
**
** Both collating sequences use the same sort order as BINARY.
** The only difference is that the utf16_aligned collating
** sequence is declared with the SQLITE_UTF16_ALIGNED flag.
** Both collating functions increment the unaligned utf16 counter
** whenever they see a string that begins on an odd byte boundary.
*/
static int unaligned_string_counter = 0;
static int alignmentCollFunc(
  void *NotUsed,
  int nKey1, const void *pKey1,
  int nKey2, const void *pKey2
){
  int rc, n;
  n = nKey1<nKey2 ? nKey1 : nKey2;
  if( nKey1>0 && 1==(1&(int)pKey1) ) unaligned_string_counter++;
  if( nKey2>0 && 1==(1&(int)pKey2) ) unaligned_string_counter++;
  rc = memcmp(pKey1, pKey2, n);
  if( rc==0 ){
    rc = nKey1 - nKey2;
  }
  return rc;
}
static int add_alignment_test_collations(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  if( objc>=2 ){
    if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
    sqlite3_create_collation(db, "utf16_unaligned", SQLITE_UTF16, 
        0, alignmentCollFunc);
    sqlite3_create_collation(db, "utf16_aligned", SQLITE_UTF16_ALIGNED, 
        0, alignmentCollFunc);
  }
  return SQLITE_OK;
}
#endif /* !defined(SQLITE_OMIT_UTF16) */

/*
** Usage: add_test_function <db ptr> <utf8> <utf16le> <utf16be>
**
** This function is used to test that SQLite selects the correct user
** function callback when multiple versions (for different text encodings)
** are available.
**
** Calling this routine registers up to three versions of the user function
** "test_function" with database handle <db>.  If the second argument is
** true, then a version of test_function is registered for UTF-8, if the
** third is true, a version is registered for UTF-16le, if the fourth is
** true, a UTF-16be version is available.  Previous versions of
** test_function are deleted.
**
** The user function is implemented by calling the following TCL script:
**
**   "test_function <enc> <arg>"
**
** Where <enc> is one of UTF-8, UTF-16LE or UTF16BE, and <arg> is the
** single argument passed to the SQL function. The value returned by
** the TCL script is used as the return value of the SQL function. It
** is passed to SQLite using UTF-16BE for a UTF-8 test_function(), UTF-8
** for a UTF-16LE test_function(), and UTF-16LE for an implementation that
** prefers UTF-16BE.
*/
#ifndef SQLITE_OMIT_UTF16
static void test_function_utf8(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  Tcl_Interp *interp;
  Tcl_Obj *pX;
  sqlite3_value *pVal;
  interp = (Tcl_Interp *)sqlite3_user_data(pCtx);
  pX = Tcl_NewStringObj("test_function", -1);
  Tcl_IncrRefCount(pX);
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-8", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  sqlite3_result_text(pCtx, Tcl_GetStringResult(interp), -1, SQLITE_TRANSIENT);
  pVal = sqlite3ValueNew(0);
  sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE_UTF8, SQLITE_STATIC);
  sqlite3_result_text16be(pCtx, sqlite3_value_text16be(pVal),
      -1, SQLITE_TRANSIENT);
  sqlite3ValueFree(pVal);
}
static void test_function_utf16le(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  Tcl_Interp *interp;
  Tcl_Obj *pX;
  sqlite3_value *pVal;
  interp = (Tcl_Interp *)sqlite3_user_data(pCtx);
  pX = Tcl_NewStringObj("test_function", -1);
  Tcl_IncrRefCount(pX);
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16LE", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  pVal = sqlite3ValueNew(0);
  sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE_UTF8, SQLITE_STATIC);
  sqlite3_result_text(pCtx,(char*)sqlite3_value_text(pVal),-1,SQLITE_TRANSIENT);
  sqlite3ValueFree(pVal);
}
static void test_function_utf16be(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  Tcl_Interp *interp;
  Tcl_Obj *pX;
  sqlite3_value *pVal;
  interp = (Tcl_Interp *)sqlite3_user_data(pCtx);
  pX = Tcl_NewStringObj("test_function", -1);
  Tcl_IncrRefCount(pX);
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16BE", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  pVal = sqlite3ValueNew(0);
  sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE_UTF8, SQLITE_STATIC);
  sqlite3_result_text16(pCtx, sqlite3_value_text16le(pVal),
      -1, SQLITE_TRANSIENT);
  sqlite3_result_text16be(pCtx, sqlite3_value_text16le(pVal),
      -1, SQLITE_TRANSIENT);
  sqlite3_result_text16le(pCtx, sqlite3_value_text16le(pVal),
      -1, SQLITE_TRANSIENT);
  sqlite3ValueFree(pVal);
}
#endif /* SQLITE_OMIT_UTF16 */
static int test_function(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3 *db;
  int val;

  if( objc!=5 ) goto bad_args;
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR;
  if( val ){
    sqlite3_create_function(db, "test_function", 1, SQLITE_UTF8, 
        interp, test_function_utf8, 0, 0);
  }
  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR;
  if( val ){
    sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16LE, 
        interp, test_function_utf16le, 0, 0);
  }
  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR;
  if( val ){
    sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16BE, 
        interp, test_function_utf16be, 0, 0);
  }

  return TCL_OK;
bad_args:
  Tcl_AppendResult(interp, "wrong # args: should be \"",
      Tcl_GetStringFromObj(objv[0], 0), " <DB> <utf8> <utf16le> <utf16be>", 0);
#endif /* SQLITE_OMIT_UTF16 */
  return TCL_ERROR;
}

/*
** Usage:         test_errstr <err code>
**
** Test that the english language string equivalents for sqlite error codes
** are sane. The parameter is an integer representing an sqlite error code.
** The result is a list of two elements, the string representation of the
** error code and the english language explanation.
*/
static int test_errstr(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  char *zCode;
  int i;
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "<error code>");
  }

  zCode = Tcl_GetString(objv[1]);
  for(i=0; i<200; i++){
    if( 0==strcmp(t1ErrorName(i), zCode) ) break;
  }
  Tcl_SetResult(interp, (char *)sqlite3ErrStr(i), 0);
  return TCL_OK;
}

/*
** Usage:    breakpoint
**
** This routine exists for one purpose - to provide a place to put a
** breakpoint with GDB that can be triggered using TCL code.  The use
** for this is when a particular test fails on (say) the 1485th iteration.
** In the TCL test script, we can add code like this:
**
**     if {$i==1485} breakpoint
**
** Then run testfixture in the debugger and wait for the breakpoint to
** fire.  Then additional breakpoints can be set to trace down the bug.
*/
static int test_breakpoint(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return TCL_OK;         /* Do nothing */
}

/*
** Usage:   sqlite3_bind_zeroblob  STMT IDX N
**
** Test the sqlite3_bind_zeroblob interface.  STMT is a prepared statement.
** IDX is the index of a wildcard in the prepared statement.  This command
** binds a N-byte zero-filled BLOB to the wildcard.
*/
static int test_bind_zeroblob(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  int n;
  int rc;

  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT IDX N");
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &n) ) return TCL_ERROR;

  rc = sqlite3_bind_zeroblob(pStmt, idx, n);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_int  STMT N VALUE
**
** Test the sqlite3_bind_int interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a 32-bit integer VALUE to that wildcard.
*/
static int test_bind_int(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  int value;
  int rc;

  if( objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &value) ) return TCL_ERROR;

  rc = sqlite3_bind_int(pStmt, idx, value);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}


/*
** Usage:   sqlite3_bind_int64  STMT N VALUE
**
** Test the sqlite3_bind_int64 interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a 64-bit integer VALUE to that wildcard.
*/
static int test_bind_int64(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  i64 value;
  int rc;

  if( objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  if( Tcl_GetWideIntFromObj(interp, objv[3], &value) ) return TCL_ERROR;

  rc = sqlite3_bind_int64(pStmt, idx, value);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}


/*
** Usage:   sqlite3_bind_double  STMT N VALUE
**
** Test the sqlite3_bind_double interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a 64-bit integer VALUE to that wildcard.
*/
static int test_bind_double(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  double value;
  int rc;
  const char *zVal;
  int i;
  static const struct {
    const char *zName;     /* Name of the special floating point value */
    unsigned int iUpper;   /* Upper 32 bits */
    unsigned int iLower;   /* Lower 32 bits */
  } aSpecialFp[] = {
    {  "NaN",      0x7fffffff, 0xffffffff },
    {  "SNaN",     0x7ff7ffff, 0xffffffff },
    {  "-NaN",     0xffffffff, 0xffffffff },
    {  "-SNaN",    0xfff7ffff, 0xffffffff },
    {  "+Inf",     0x7ff00000, 0x00000000 },
    {  "-Inf",     0xfff00000, 0x00000000 },
    {  "Epsilon",  0x00000000, 0x00000001 },
    {  "-Epsilon", 0x80000000, 0x00000001 },
    {  "NaN0",     0x7ff80000, 0x00000000 },
    {  "-NaN0",    0xfff80000, 0x00000000 },
  };

  if( objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;

  /* Intercept the string "NaN" and generate a NaN value for it.
  ** All other strings are passed through to Tcl_GetDoubleFromObj().
  ** Tcl_GetDoubleFromObj() should understand "NaN" but some versions
  ** contain a bug.
  */
  zVal = Tcl_GetString(objv[3]);
  for(i=0; i<sizeof(aSpecialFp)/sizeof(aSpecialFp[0]); i++){
    if( strcmp(aSpecialFp[i].zName, zVal)==0 ){
      sqlite3_uint64 x;
      x = aSpecialFp[i].iUpper;
      x <<= 32;
      x |= aSpecialFp[i].iLower;
      assert( sizeof(value)==8 );
      assert( sizeof(x)==8 );
      memcpy(&value, &x, 8);
      break;
    }
  }
  if( i>=sizeof(aSpecialFp)/sizeof(aSpecialFp[0]) &&
         Tcl_GetDoubleFromObj(interp, objv[3], &value) ){
    return TCL_ERROR;
  }
  rc = sqlite3_bind_double(pStmt, idx, value);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_null  STMT N
**
** Test the sqlite3_bind_null interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a NULL to the wildcard.
*/
static int test_bind_null(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  int rc;

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;

  rc = sqlite3_bind_null(pStmt, idx);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_text  STMT N STRING BYTES
**
** Test the sqlite3_bind_text interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a UTF-8 string STRING to the wildcard.  The string is BYTES bytes
** long.
*/
static int test_bind_text(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  int bytes;
  char *value;
  int rc;

  if( objc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  value = (char*)Tcl_GetByteArrayFromObj(objv[3], &bytes);
  if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;

  rc = sqlite3_bind_text(pStmt, idx, value, bytes, SQLITE_TRANSIENT);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_text16 ?-static? STMT N STRING BYTES
**
** Test the sqlite3_bind_text16 interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a UTF-16 string STRING to the wildcard.  The string is BYTES bytes
** long.
*/
static int test_bind_text16(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3_stmt *pStmt;
  int idx;
  int bytes;
  char *value;
  int rc;

  void (*xDel)() = (objc==6?SQLITE_STATIC:SQLITE_TRANSIENT);
  Tcl_Obj *oStmt    = objv[objc-4];
  Tcl_Obj *oN       = objv[objc-3];
  Tcl_Obj *oString  = objv[objc-2];
  Tcl_Obj *oBytes   = objv[objc-1];

  if( objc!=5 && objc!=6){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(oStmt), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, oN, &idx) ) return TCL_ERROR;
  value = (char*)Tcl_GetByteArrayFromObj(oString, 0);
  if( Tcl_GetIntFromObj(interp, oBytes, &bytes) ) return TCL_ERROR;

  rc = sqlite3_bind_text16(pStmt, idx, (void *)value, bytes, xDel);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
    return TCL_ERROR;
  }

#endif /* SQLITE_OMIT_UTF16 */
  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_blob ?-static? STMT N DATA BYTES
**
** Test the sqlite3_bind_blob interface.  STMT is a prepared statement.
** N is the index of a wildcard in the prepared statement.  This command
** binds a BLOB to the wildcard.  The BLOB is BYTES bytes in size.
*/
static int test_bind_blob(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int idx;
  int bytes;
  char *value;
  int rc;
  sqlite3_destructor_type xDestructor = SQLITE_TRANSIENT;

  if( objc!=5 && objc!=6 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " STMT N DATA BYTES", 0);
    return TCL_ERROR;
  }

  if( objc==6 ){
    xDestructor = SQLITE_STATIC;
    objv++;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  value = Tcl_GetString(objv[3]);
  if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;

  rc = sqlite3_bind_blob(pStmt, idx, value, bytes, xDestructor);
  if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_parameter_count  STMT
**
** Return the number of wildcards in the given statement.
*/
static int test_bind_parameter_count(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT");
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_bind_parameter_count(pStmt)));
  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_parameter_name  STMT  N
**
** Return the name of the Nth wildcard.  The first wildcard is 1.
** An empty string is returned if N is out of range or if the wildcard
** is nameless.
*/
static int test_bind_parameter_name(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int i;

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT N");
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &i) ) return TCL_ERROR;
  Tcl_SetObjResult(interp, 
     Tcl_NewStringObj(sqlite3_bind_parameter_name(pStmt,i),-1)
  );
  return TCL_OK;
}

/*
** Usage:   sqlite3_bind_parameter_index  STMT  NAME
**
** Return the index of the wildcard called NAME.  Return 0 if there is
** no such wildcard.
*/
static int test_bind_parameter_index(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT NAME");
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  Tcl_SetObjResult(interp, 
     Tcl_NewIntObj(
       sqlite3_bind_parameter_index(pStmt,Tcl_GetString(objv[2]))
     )
  );
  return TCL_OK;
}

/*
** Usage:   sqlite3_clear_bindings STMT
**
*/
static int test_clear_bindings(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT");
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_clear_bindings(pStmt)));
  return TCL_OK;
}

/*
** Usage:   sqlite3_sleep MILLISECONDS
*/
static int test_sleep(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int ms;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "MILLISECONDS");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &ms) ){
    return TCL_ERROR;
  }
  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_sleep(ms)));
  return TCL_OK;
}

/*
** Usage: sqlite3_extended_errcode DB
**
** Return the string representation of the most recent sqlite3_* API
** error code. e.g. "SQLITE_ERROR".
*/
static int test_ex_errcode(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite3_extended_errcode(db);
  Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}


/*
** Usage: sqlite3_errcode DB
**
** Return the string representation of the most recent sqlite3_* API
** error code. e.g. "SQLITE_ERROR".
*/
static int test_errcode(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite3_errcode(db);
  Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}

/*
** Usage:   sqlite3_errmsg DB
**
** Returns the UTF-8 representation of the error message string for the
** most recent sqlite3_* API call.
*/
static int test_errmsg(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  const char *zErr;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  zErr = sqlite3_errmsg(db);
  Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1));
  return TCL_OK;
}

/*
** Usage:   test_errmsg16 DB
**
** Returns the UTF-16 representation of the error message string for the
** most recent sqlite3_* API call. This is a byte array object at the TCL 
** level, and it includes the 0x00 0x00 terminator bytes at the end of the
** UTF-16 string.
*/
static int test_errmsg16(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3 *db;
  const void *zErr;
  const char *z;
  int bytes = 0;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  zErr = sqlite3_errmsg16(db);
  if( zErr ){
    z = zErr;
    for(bytes=0; z[bytes] || z[bytes+1]; bytes+=2){}
  }
  Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zErr, bytes));
#endif /* SQLITE_OMIT_UTF16 */
  return TCL_OK;
}

/*
** Usage: sqlite3_prepare DB sql bytes ?tailvar?
**
** Compile up to <bytes> bytes of the supplied SQL string <sql> using
** database handle <DB>. The parameter <tailval> is the name of a global
** variable that is set to the unused portion of <sql> (if any). A
** STMT handle is returned.
*/
static int test_prepare(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  const char *zSql;
  int bytes;
  const char *zTail = 0;
  sqlite3_stmt *pStmt = 0;
  char zBuf[50];
  int rc;

  if( objc!=5 && objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zSql = Tcl_GetString(objv[2]);
  if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;

  rc = sqlite3_prepare(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
  Tcl_ResetResult(interp);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  if( zTail && objc>=5 ){
    if( bytes>=0 ){
      bytes = bytes - (zTail-zSql);
    }
    if( strlen(zTail)<bytes ){
      bytes = strlen(zTail);
    }
    Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0);
  }
  if( rc!=SQLITE_OK ){
    assert( pStmt==0 );
    sprintf(zBuf, "(%d) ", rc);
    Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
    return TCL_ERROR;
  }

  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}

/*
** Usage: sqlite3_prepare_v2 DB sql bytes ?tailvar?
**
** Compile up to <bytes> bytes of the supplied SQL string <sql> using
** database handle <DB>. The parameter <tailval> is the name of a global
** variable that is set to the unused portion of <sql> (if any). A
** STMT handle is returned.
*/
static int test_prepare_v2(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  const char *zSql;
  int bytes;
  const char *zTail = 0;
  sqlite3_stmt *pStmt = 0;
  char zBuf[50];
  int rc;

  if( objc!=5 && objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zSql = Tcl_GetString(objv[2]);
  if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;

  rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
  assert(rc==SQLITE_OK || pStmt==0);
  Tcl_ResetResult(interp);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  if( zTail && objc>=5 ){
    if( bytes>=0 ){
      bytes = bytes - (zTail-zSql);
    }
    Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0);
  }
  if( rc!=SQLITE_OK ){
    assert( pStmt==0 );
    sprintf(zBuf, "(%d) ", rc);
    Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
    return TCL_ERROR;
  }

  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}

/*
** Usage: sqlite3_prepare_tkt3134 DB
**
** Generate a prepared statement for a zero-byte string as a test
** for ticket #3134.  The string should be preceeded by a zero byte.
*/
static int test_prepare_tkt3134(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  static const char zSql[] = "\000SELECT 1";
  sqlite3_stmt *pStmt = 0;
  char zBuf[50];
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite3_prepare_v2(db, &zSql[1], 0, &pStmt, 0);
  assert(rc==SQLITE_OK || pStmt==0);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  if( rc!=SQLITE_OK ){
    assert( pStmt==0 );
    sprintf(zBuf, "(%d) ", rc);
    Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
    return TCL_ERROR;
  }

  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}

/*
** Usage: sqlite3_prepare16 DB sql bytes tailvar
**
** Compile up to <bytes> bytes of the supplied SQL string <sql> using
** database handle <DB>. The parameter <tailval> is the name of a global
** variable that is set to the unused portion of <sql> (if any). A
** STMT handle is returned.
*/
static int test_prepare16(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3 *db;
  const void *zSql;
  const void *zTail = 0;
  Tcl_Obj *pTail = 0;
  sqlite3_stmt *pStmt = 0;
  char zBuf[50]; 
  int rc;
  int bytes;                /* The integer specified as arg 3 */
  int objlen;               /* The byte-array length of arg 2 */

  if( objc!=5 && objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen);
  if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;

  rc = sqlite3_prepare16(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  if( rc ){
    return TCL_ERROR;
  }

  if( objc>=5 ){
    if( zTail ){
      objlen = objlen - ((u8 *)zTail-(u8 *)zSql);
    }else{
      objlen = 0;
    }
    pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen);
    Tcl_IncrRefCount(pTail);
    Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0);
    Tcl_DecrRefCount(pTail);
  }

  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
  }
  Tcl_AppendResult(interp, zBuf, 0);
#endif /* SQLITE_OMIT_UTF16 */
  return TCL_OK;
}

/*
** Usage: sqlite3_prepare16_v2 DB sql bytes ?tailvar?
**
** Compile up to <bytes> bytes of the supplied SQL string <sql> using
** database handle <DB>. The parameter <tailval> is the name of a global
** variable that is set to the unused portion of <sql> (if any). A
** STMT handle is returned.
*/
static int test_prepare16_v2(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3 *db;
  const void *zSql;
  const void *zTail = 0;
  Tcl_Obj *pTail = 0;
  sqlite3_stmt *pStmt = 0;
  char zBuf[50]; 
  int rc;
  int bytes;                /* The integer specified as arg 3 */
  int objlen;               /* The byte-array length of arg 2 */

  if( objc!=5 && objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen);
  if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;

  rc = sqlite3_prepare16_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  if( rc ){
    return TCL_ERROR;
  }

  if( objc>=5 ){
    if( zTail ){
      objlen = objlen - ((u8 *)zTail-(u8 *)zSql);
    }else{
      objlen = 0;
    }
    pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen);
    Tcl_IncrRefCount(pTail);
    Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0);
    Tcl_DecrRefCount(pTail);
  }

  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
  }
  Tcl_AppendResult(interp, zBuf, 0);
#endif /* SQLITE_OMIT_UTF16 */
  return TCL_OK;
}

/*
** Usage: sqlite3_open filename ?options-list?
*/
static int test_open(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  const char *zFilename;
  sqlite3 *db;
  int rc;
  char zBuf[100];

  if( objc!=3 && objc!=2 && objc!=1 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " filename options-list", 0);
    return TCL_ERROR;
  }

  zFilename = objc>1 ? Tcl_GetString(objv[1]) : 0;
  rc = sqlite3_open(zFilename, &db);
  
  if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage: sqlite3_open16 filename options
*/
static int test_open16(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  const void *zFilename;
  sqlite3 *db;
  int rc;
  char zBuf[100];

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " filename options-list", 0);
    return TCL_ERROR;
  }

  zFilename = Tcl_GetByteArrayFromObj(objv[1], 0);
  rc = sqlite3_open16(zFilename, &db);
  
  if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
  Tcl_AppendResult(interp, zBuf, 0);
#endif /* SQLITE_OMIT_UTF16 */
  return TCL_OK;
}

/*
** Usage: sqlite3_complete16 <UTF-16 string>
**
** Return 1 if the supplied argument is a complete SQL statement, or zero
** otherwise.
*/
static int test_complete16(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#if !defined(SQLITE_OMIT_COMPLETE) && !defined(SQLITE_OMIT_UTF16)
  char *zBuf;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "<utf-16 sql>");
    return TCL_ERROR;
  }

  zBuf = (char*)Tcl_GetByteArrayFromObj(objv[1], 0);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_complete16(zBuf)));
#endif /* SQLITE_OMIT_COMPLETE && SQLITE_OMIT_UTF16 */
  return TCL_OK;
}

/*
** Usage: sqlite3_step STMT
**
** Advance the statement to the next row.
*/
static int test_step(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  rc = sqlite3_step(pStmt);

  /* if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ) return TCL_ERROR; */
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}

static int test_sql(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT");
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  Tcl_SetResult(interp, (char *)sqlite3_sql(pStmt), TCL_VOLATILE);
  return TCL_OK;
}

/*
** Usage: sqlite3_column_count STMT 
**
** Return the number of columns returned by the sql statement STMT.
*/
static int test_column_count(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;

  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_column_count(pStmt)));
  return TCL_OK;
}

/*
** Usage: sqlite3_column_type STMT column
**
** Return the type of the data in column 'column' of the current row.
*/
static int test_column_type(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int col;
  int tp;

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;

  tp = sqlite3_column_type(pStmt, col);
  switch( tp ){
    case SQLITE_INTEGER: 
      Tcl_SetResult(interp, "INTEGER", TCL_STATIC); 
      break;
    case SQLITE_NULL:
      Tcl_SetResult(interp, "NULL", TCL_STATIC); 
      break;
    case SQLITE_FLOAT:
      Tcl_SetResult(interp, "FLOAT", TCL_STATIC); 
      break;
    case SQLITE_TEXT:
      Tcl_SetResult(interp, "TEXT", TCL_STATIC); 
      break;
    case SQLITE_BLOB:
      Tcl_SetResult(interp, "BLOB", TCL_STATIC); 
      break;
    default:
      assert(0);
  }

  return TCL_OK;
}

/*
** Usage: sqlite3_column_int64 STMT column
**
** Return the data in column 'column' of the current row cast as an
** wide (64-bit) integer.
*/
static int test_column_int64(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int col;
  i64 iVal;

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;

  iVal = sqlite3_column_int64(pStmt, col);
  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(iVal));
  return TCL_OK;
}

/*
** Usage: sqlite3_column_blob STMT column
*/
static int test_column_blob(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int col;

  int len;
  const void *pBlob;

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;

  len = sqlite3_column_bytes(pStmt, col);
  pBlob = sqlite3_column_blob(pStmt, col);
  Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pBlob, len));
  return TCL_OK;
}

/*
** Usage: sqlite3_column_double STMT column
**
** Return the data in column 'column' of the current row cast as a double.
*/
static int test_column_double(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int col;
  double rVal;

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;

  rVal = sqlite3_column_double(pStmt, col);
  Tcl_SetObjResult(interp, Tcl_NewDoubleObj(rVal));
  return TCL_OK;
}

/*
** Usage: sqlite3_data_count STMT 
**
** Return the number of columns returned by the sql statement STMT.
*/
static int test_data_count(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;

  Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_data_count(pStmt)));
  return TCL_OK;
}

/*
** Usage: sqlite3_column_text STMT column
**
** Usage: sqlite3_column_decltype STMT column
**
** Usage: sqlite3_column_name STMT column
*/
static int test_stmt_utf8(
  void * clientData,        /* Pointer to SQLite API function to be invoke */
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int col;
  const char *(*xFunc)(sqlite3_stmt*, int);
  const char *zRet;

  xFunc = (const char *(*)(sqlite3_stmt*, int))clientData;
  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
  zRet = xFunc(pStmt, col);
  if( zRet ){
    Tcl_SetResult(interp, (char *)zRet, 0);
  }
  return TCL_OK;
}

static int test_global_recover(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_GLOBALRECOVER
#ifndef SQLITE_OMIT_DEPRECATED
  int rc;
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }
  rc = sqlite3_global_recover();
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
#endif
#endif
  return TCL_OK;
}

/*
** Usage: sqlite3_column_text STMT column
**
** Usage: sqlite3_column_decltype STMT column
**
** Usage: sqlite3_column_name STMT column
*/
static int test_stmt_utf16(
  void * clientData,     /* Pointer to SQLite API function to be invoked */
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3_stmt *pStmt;
  int col;
  Tcl_Obj *pRet;
  const void *zName16;
  const void *(*xFunc)(sqlite3_stmt*, int);

  xFunc = (const void *(*)(sqlite3_stmt*, int))clientData;
  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;

  zName16 = xFunc(pStmt, col);
  if( zName16 ){
    int n;
    const char *z = zName16;
    for(n=0; z[n] || z[n+1]; n+=2){}
    pRet = Tcl_NewByteArrayObj(zName16, n+2);
    Tcl_SetObjResult(interp, pRet);
  }
#endif /* SQLITE_OMIT_UTF16 */

  return TCL_OK;
}

/*
** Usage: sqlite3_column_int STMT column
**
** Usage: sqlite3_column_bytes STMT column
**
** Usage: sqlite3_column_bytes16 STMT column
**
*/
static int test_stmt_int(
  void * clientData,    /* Pointer to SQLite API function to be invoked */
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int col;
  int (*xFunc)(sqlite3_stmt*, int);

  xFunc = (int (*)(sqlite3_stmt*, int))clientData;
  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " STMT column", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;

  Tcl_SetObjResult(interp, Tcl_NewIntObj(xFunc(pStmt, col)));
  return TCL_OK;
}

/*
** Usage:  sqlite_set_magic  DB  MAGIC-NUMBER
**
** Set the db->magic value.  This is used to test error recovery logic.
*/
static int sqlite_set_magic(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  sqlite3 *db;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
         " DB MAGIC", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  if( strcmp(argv[2], "SQLITE_MAGIC_OPEN")==0 ){
    db->magic = SQLITE_MAGIC_OPEN;
  }else if( strcmp(argv[2], "SQLITE_MAGIC_CLOSED")==0 ){
    db->magic = SQLITE_MAGIC_CLOSED;
  }else if( strcmp(argv[2], "SQLITE_MAGIC_BUSY")==0 ){
    db->magic = SQLITE_MAGIC_BUSY;
  }else if( strcmp(argv[2], "SQLITE_MAGIC_ERROR")==0 ){
    db->magic = SQLITE_MAGIC_ERROR;
  }else if( Tcl_GetInt(interp, argv[2], (int*)&db->magic) ){
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:  sqlite3_interrupt  DB 
**
** Trigger an interrupt on DB
*/
static int test_interrupt(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  sqlite3 *db;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  sqlite3_interrupt(db);
  return TCL_OK;
}

static u8 *sqlite3_stack_baseline = 0;

/*
** Fill the stack with a known bitpattern.
*/
static void prepStack(void){
  int i;
  u32 bigBuf[65536];
  for(i=0; i<sizeof(bigBuf); i++) bigBuf[i] = 0xdeadbeef;
  sqlite3_stack_baseline = (u8*)&bigBuf[65536];
}

/*
** Get the current stack depth.  Used for debugging only.
*/
u64 sqlite3StackDepth(void){
  u8 x;
  return (u64)(sqlite3_stack_baseline - &x);
}

/*
** Usage:  sqlite3_stack_used DB SQL
**
** Try to measure the amount of stack space used by a call to sqlite3_exec
*/
static int test_stack_used(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  sqlite3 *db;
  int i;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
        " DB SQL", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  prepStack();
  (void)sqlite3_exec(db, argv[2], 0, 0, 0);
  for(i=65535; i>=0 && ((u32*)sqlite3_stack_baseline)[-i]==0xdeadbeef; i--){}
  Tcl_SetObjResult(interp, Tcl_NewIntObj(i*4));
  return TCL_OK;
}

/*
** Usage: sqlite_delete_function DB function-name
**
** Delete the user function 'function-name' from database handle DB. It
** is assumed that the user function was created as UTF8, any number of
** arguments (the way the TCL interface does it).
*/
static int delete_function(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  int rc;
  sqlite3 *db;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
        " DB function-name", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, 0, 0, 0);
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
  return TCL_OK;
}

/*
** Usage: sqlite_delete_collation DB collation-name
**
** Delete the collation sequence 'collation-name' from database handle 
** DB. It is assumed that the collation sequence was created as UTF8 (the 
** way the TCL interface does it).
*/
static int delete_collation(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  int rc;
  sqlite3 *db;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
        " DB function-name", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite3_create_collation(db, argv[2], SQLITE_UTF8, 0, 0);
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
  return TCL_OK;
}

/*
** Usage: sqlite3_get_autocommit DB
**
** Return true if the database DB is currently in auto-commit mode.
** Return false if not.
*/
static int get_autocommit(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  char zBuf[30];
  sqlite3 *db;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
        " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  sprintf(zBuf, "%d", sqlite3_get_autocommit(db));
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage: sqlite3_busy_timeout DB MS
**
** Set the busy timeout.  This is more easily done using the timeout
** method of the TCL interface.  But we need a way to test the case
** where it returns SQLITE_MISUSE.
*/
static int test_busy_timeout(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  int rc, ms;
  sqlite3 *db;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
        " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[2], &ms) ) return TCL_ERROR;
  rc = sqlite3_busy_timeout(db, ms);
  Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
  return TCL_OK;
}

/*
** Usage:  tcl_variable_type VARIABLENAME
**
** Return the name of the internal representation for the
** value of the given variable.
*/
static int tcl_variable_type(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_Obj *pVar;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "VARIABLE");
    return TCL_ERROR;
  }
  pVar = Tcl_GetVar2Ex(interp, Tcl_GetString(objv[1]), 0, TCL_LEAVE_ERR_MSG);
  if( pVar==0 ) return TCL_ERROR;
  if( pVar->typePtr ){
    Tcl_SetObjResult(interp, Tcl_NewStringObj(pVar->typePtr->name, -1));
  }
  return TCL_OK;
}

/*
** Usage:  sqlite3_release_memory ?N?
**
** Attempt to release memory currently held but not actually required.
** The integer N is the number of bytes we are trying to release.  The 
** return value is the amount of memory actually released.
*/
static int test_release_memory(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
  int N;
  int amt;
  if( objc!=1 && objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "?N?");
    return TCL_ERROR;
  }
  if( objc==2 ){
    if( Tcl_GetIntFromObj(interp, objv[1], &N) ) return TCL_ERROR;
  }else{
    N = -1;
  }
  amt = sqlite3_release_memory(N);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(amt));
#endif
  return TCL_OK;
}

/*
** Usage:  sqlite3_soft_heap_limit ?N?
**
** Query or set the soft heap limit for the current thread.  The
** limit is only changed if the N is present.  The previous limit
** is returned.
*/
static int test_soft_heap_limit(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  static int softHeapLimit = 0;
  int amt;
  if( objc!=1 && objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "?N?");
    return TCL_ERROR;
  }
  amt = softHeapLimit;
  if( objc==2 ){
    int N;
    if( Tcl_GetIntFromObj(interp, objv[1], &N) ) return TCL_ERROR;
    sqlite3_soft_heap_limit(N);
    softHeapLimit = N;
  }
  Tcl_SetObjResult(interp, Tcl_NewIntObj(amt));
  return TCL_OK;
}

/*
** Usage:   sqlite3_thread_cleanup
**
** Call the sqlite3_thread_cleanup API.
*/
static int test_thread_cleanup(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_thread_cleanup();
#endif
  return TCL_OK;
}

/*
** Usage:   sqlite3_pager_refcounts  DB
**
** Return a list of numbers which are the PagerRefcount for all
** pagers on each database connection.
*/
static int test_pager_refcounts(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  int i;
  int v, *a;
  Tcl_Obj *pResult;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  pResult = Tcl_NewObj();
  for(i=0; i<db->nDb; i++){
    if( db->aDb[i].pBt==0 ){
      v = -1;
    }else{
      sqlite3_mutex_enter(db->mutex);
      a = sqlite3PagerStats(sqlite3BtreePager(db->aDb[i].pBt));
      v = a[0];
      sqlite3_mutex_leave(db->mutex);
    }
    Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(v));
  }
  Tcl_SetObjResult(interp, pResult);
  return TCL_OK;
}


/*
** tclcmd:   working_64bit_int
**
** Some TCL builds (ex: cygwin) do not support 64-bit integers.  This
** leads to a number of test failures.  The present command checks the
** TCL build to see whether or not it supports 64-bit integers.  It
** returns TRUE if it does and FALSE if not.
**
** This command is used to warn users that their TCL build is defective
** and that the errors they are seeing in the test scripts might be
** a result of their defective TCL rather than problems in SQLite.
*/
static int working_64bit_int(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_Obj *pTestObj;
  int working = 0;

  pTestObj = Tcl_NewWideIntObj(1000000*(i64)1234567890);
  working = strcmp(Tcl_GetString(pTestObj), "1234567890000000")==0;
  Tcl_DecrRefCount(pTestObj);
  Tcl_SetObjResult(interp, Tcl_NewBooleanObj(working));
  return TCL_OK;
}


/*
** tclcmd:   vfs_unlink_test
**
** This TCL command unregisters the primary VFS and then registers
** it back again.  This is used to test the ability to register a
** VFS when none are previously registered, and the ability to 
** unregister the only available VFS.  Ticket #2738
*/
static int vfs_unlink_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int i;
  sqlite3_vfs *pMain;
  sqlite3_vfs *apVfs[20];
  sqlite3_vfs one, two;

  sqlite3_vfs_unregister(0);   /* Unregister of NULL is harmless */
  one.zName = "__one";
  two.zName = "__two";

  /* Calling sqlite3_vfs_register with 2nd argument of 0 does not
  ** change the default VFS
  */
  pMain = sqlite3_vfs_find(0);
  sqlite3_vfs_register(&one, 0);
  assert( pMain==0 || pMain==sqlite3_vfs_find(0) );
  sqlite3_vfs_register(&two, 0);
  assert( pMain==0 || pMain==sqlite3_vfs_find(0) );

  /* We can find a VFS by its name */
  assert( sqlite3_vfs_find("__one")==&one );
  assert( sqlite3_vfs_find("__two")==&two );

  /* Calling sqlite_vfs_register with non-zero second parameter changes the
  ** default VFS, even if the 1st parameter is an existig VFS that is
  ** previously registered as the non-default.
  */
  sqlite3_vfs_register(&one, 1);
  assert( sqlite3_vfs_find("__one")==&one );
  assert( sqlite3_vfs_find("__two")==&two );
  assert( sqlite3_vfs_find(0)==&one );
  sqlite3_vfs_register(&two, 1);
  assert( sqlite3_vfs_find("__one")==&one );
  assert( sqlite3_vfs_find("__two")==&two );
  assert( sqlite3_vfs_find(0)==&two );
  if( pMain ){
    sqlite3_vfs_register(pMain, 1);
    assert( sqlite3_vfs_find("__one")==&one );
    assert( sqlite3_vfs_find("__two")==&two );
    assert( sqlite3_vfs_find(0)==pMain );
  }
  
  /* Unlink the default VFS.  Repeat until there are no more VFSes
  ** registered.
  */
  for(i=0; i<sizeof(apVfs)/sizeof(apVfs[0]); i++){
    apVfs[i] = sqlite3_vfs_find(0);
    if( apVfs[i] ){
      assert( apVfs[i]==sqlite3_vfs_find(apVfs[i]->zName) );
      sqlite3_vfs_unregister(apVfs[i]);
      assert( 0==sqlite3_vfs_find(apVfs[i]->zName) );
    }
  }
  assert( 0==sqlite3_vfs_find(0) );
  
  /* Register the main VFS as non-default (will be made default, since
  ** it'll be the only one in existence).
  */
  sqlite3_vfs_register(pMain, 0);
  assert( sqlite3_vfs_find(0)==pMain );
  
  /* Un-register the main VFS again to restore an empty VFS list */
  sqlite3_vfs_unregister(pMain);
  assert( 0==sqlite3_vfs_find(0) );

  /* Relink all VFSes in reverse order. */  
  for(i=sizeof(apVfs)/sizeof(apVfs[0])-1; i>=0; i--){
    if( apVfs[i] ){
      sqlite3_vfs_register(apVfs[i], 1);
      assert( apVfs[i]==sqlite3_vfs_find(0) );
      assert( apVfs[i]==sqlite3_vfs_find(apVfs[i]->zName) );
    }
  }

  /* Unregister out sample VFSes. */
  sqlite3_vfs_unregister(&one);
  sqlite3_vfs_unregister(&two);

  /* Unregistering a VFS that is not currently registered is harmless */
  sqlite3_vfs_unregister(&one);
  sqlite3_vfs_unregister(&two);
  assert( sqlite3_vfs_find("__one")==0 );
  assert( sqlite3_vfs_find("__two")==0 );

  /* We should be left with the original default VFS back as the
  ** original */
  assert( sqlite3_vfs_find(0)==pMain );

  return TCL_OK;
}

/*
** tclcmd:   vfs_initfail_test
**
** This TCL command attempts to vfs_find and vfs_register when the
** sqlite3_initialize() interface is failing.  All calls should fail.
*/
static int vfs_initfail_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3_vfs one;
  one.zName = "__one";

  if( sqlite3_vfs_find(0) ) return TCL_ERROR;
  sqlite3_vfs_register(&one, 0);
  if( sqlite3_vfs_find(0) ) return TCL_ERROR;
  sqlite3_vfs_register(&one, 1);
  if( sqlite3_vfs_find(0) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Saved VFSes
*/
static sqlite3_vfs *apVfs[20];
static int nVfs = 0;

/*
** tclcmd:   vfs_unregister_all
**
** Unregister all VFSes.
*/
static int vfs_unregister_all(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int i;
  for(i=0; i<ArraySize(apVfs); i++){
    apVfs[i] = sqlite3_vfs_find(0);
    if( apVfs[i]==0 ) break;
    sqlite3_vfs_unregister(apVfs[i]);
  }
  nVfs = i;
  return TCL_OK;
}
/*
** tclcmd:   vfs_reregister_all
**
** Restore all VFSes that were removed using vfs_unregister_all
*/
static int vfs_reregister_all(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int i;
  for(i=0; i<nVfs; i++){
    sqlite3_vfs_register(apVfs[i], i==0);
  }
  return TCL_OK;
}


/*
** tclcmd:   file_control_test DB
**
** This TCL command runs the sqlite3_file_control interface and
** verifies correct operation of the same.
*/
static int file_control_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int iArg = 0;
  sqlite3 *db;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite3_file_control(db, 0, 0, &iArg);
  assert( rc==SQLITE_ERROR );
  rc = sqlite3_file_control(db, "notadatabase", SQLITE_FCNTL_LOCKSTATE, &iArg);
  assert( rc==SQLITE_ERROR );
  rc = sqlite3_file_control(db, "main", -1, &iArg);
  assert( rc==SQLITE_ERROR );
  rc = sqlite3_file_control(db, "temp", -1, &iArg);
  assert( rc==SQLITE_ERROR );

  return TCL_OK;
}


/*
** tclcmd:   file_control_lasterrno_test DB
**
** This TCL command runs the sqlite3_file_control interface and
** verifies correct operation of the SQLITE_LAST_ERRNO verb.
*/
static int file_control_lasterrno_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int iArg = 0;
  sqlite3 *db;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
    return TCL_ERROR;
  }
  rc = sqlite3_file_control(db, NULL, SQLITE_LAST_ERRNO, &iArg);
  if( rc ){ 
    Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); 
    return TCL_ERROR; 
  }
  if( iArg!=0 ) {
    Tcl_AppendResult(interp, "Unexpected non-zero errno: ",
                     Tcl_GetStringFromObj(Tcl_NewIntObj(iArg), 0), " ", 0);
    return TCL_ERROR;
  }
  return TCL_OK;  
}

/*
** tclcmd:   file_control_lockproxy_test DB
**
** This TCL command runs the sqlite3_file_control interface and
** verifies correct operation of the SQLITE_GET_LOCKPROXYFILE and
** SQLITE_SET_LOCKPROXYFILE verbs.
*/
static int file_control_lockproxy_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  
  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
                     Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
   return TCL_ERROR;
  }
  
#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
#  if defined(__APPLE__)
#    define SQLITE_ENABLE_LOCKING_STYLE 1
#  else
#    define SQLITE_ENABLE_LOCKING_STYLE 0
#  endif
#endif
#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  {
    char *proxyPath = "test.proxy";
    char *testPath;
    int rc;
    rc = sqlite3_file_control(db, NULL, SQLITE_SET_LOCKPROXYFILE, proxyPath);
    if( rc ){
      Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); 
      return TCL_ERROR;
    }
    rc = sqlite3_file_control(db, NULL, SQLITE_GET_LOCKPROXYFILE, &testPath);
    if( strncmp(proxyPath,testPath,11) ){
      Tcl_AppendResult(interp, "Lock proxy file did not match the "
                               "previously assigned value", 0);
      return TCL_ERROR;
    }
    if( rc ){
      Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
      return TCL_ERROR;
    }
    rc = sqlite3_file_control(db, NULL, SQLITE_SET_LOCKPROXYFILE, proxyPath);
    if( rc ){
      Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
      return TCL_ERROR;
    }
  }
#endif
  return TCL_OK;  
}


/*
** tclcmd:   sqlite3_vfs_list
**
**   Return a tcl list containing the names of all registered vfs's.
*/
static int vfs_list(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3_vfs *pVfs;
  Tcl_Obj *pRet = Tcl_NewObj();
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }
  for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(pVfs->zName, -1));
  }
  Tcl_SetObjResult(interp, pRet);
  return TCL_OK;  
}

/*
** tclcmd:   sqlite3_limit DB ID VALUE
**
** This TCL command runs the sqlite3_limit interface and
** verifies correct operation of the same.
*/
static int test_limit(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  int rc;
  static const struct {
     char *zName;
     int id;
  } aId[] = {
    { "SQLITE_LIMIT_LENGTH",              SQLITE_LIMIT_LENGTH               },
    { "SQLITE_LIMIT_SQL_LENGTH",          SQLITE_LIMIT_SQL_LENGTH           },
    { "SQLITE_LIMIT_COLUMN",              SQLITE_LIMIT_COLUMN               },
    { "SQLITE_LIMIT_EXPR_DEPTH",          SQLITE_LIMIT_EXPR_DEPTH           },
    { "SQLITE_LIMIT_COMPOUND_SELECT",     SQLITE_LIMIT_COMPOUND_SELECT      },
    { "SQLITE_LIMIT_VDBE_OP",             SQLITE_LIMIT_VDBE_OP              },
    { "SQLITE_LIMIT_FUNCTION_ARG",        SQLITE_LIMIT_FUNCTION_ARG         },
    { "SQLITE_LIMIT_ATTACHED",            SQLITE_LIMIT_ATTACHED             },
    { "SQLITE_LIMIT_LIKE_PATTERN_LENGTH", SQLITE_LIMIT_LIKE_PATTERN_LENGTH  },
    { "SQLITE_LIMIT_VARIABLE_NUMBER",     SQLITE_LIMIT_VARIABLE_NUMBER      },
    { "SQLITE_LIMIT_TRIGGER_DEPTH",       SQLITE_LIMIT_TRIGGER_DEPTH        },
    
    /* Out of range test cases */
    { "SQLITE_LIMIT_TOOSMALL",            -1,                               },
    { "SQLITE_LIMIT_TOOBIG",              SQLITE_LIMIT_TRIGGER_DEPTH+1      },
  };
  int i, id;
  int val;
  const char *zId;

  if( objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " DB ID VALUE", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zId = Tcl_GetString(objv[2]);
  for(i=0; i<sizeof(aId)/sizeof(aId[0]); i++){
    if( strcmp(zId, aId[i].zName)==0 ){
      id = aId[i].id;
      break;
    }
  }
  if( i>=sizeof(aId)/sizeof(aId[0]) ){
    Tcl_AppendResult(interp, "unknown limit type: ", zId, (char*)0);
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[3], &val) ) return TCL_ERROR;
  rc = sqlite3_limit(db, id, val);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;  
}

/*
** tclcmd:  save_prng_state
**
** Save the state of the pseudo-random number generator.
** At the same time, verify that sqlite3_test_control works even when
** called with an out-of-range opcode.
*/
static int save_prng_state(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int rc = sqlite3_test_control(9999);
  assert( rc==0 );
  rc = sqlite3_test_control(-1);
  assert( rc==0 );
  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SAVE);
  return TCL_OK;
}
/*
** tclcmd:  restore_prng_state
*/
static int restore_prng_state(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESTORE);
  return TCL_OK;
}
/*
** tclcmd:  reset_prng_state
*/
static int reset_prng_state(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESET);
  return TCL_OK;
}

/*
** tclcmd:  pcache_stats
*/
static int test_pcache_stats(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int nMin;
  int nMax;
  int nCurrent;
  int nRecyclable;
  Tcl_Obj *pRet;

  sqlite3PcacheStats(&nCurrent, &nMax, &nMin, &nRecyclable);

  pRet = Tcl_NewObj();
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("current", -1));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nCurrent));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("max", -1));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMax));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("min", -1));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMin));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("recyclable", -1));
  Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nRecyclable));

  Tcl_SetObjResult(interp, pRet);

  return TCL_OK;
}

#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
static void test_unlock_notify_cb(void **aArg, int nArg){
  int ii;
  for(ii=0; ii<nArg; ii++){
    Tcl_EvalEx((Tcl_Interp *)aArg[ii], "unlock_notify", -1, TCL_EVAL_GLOBAL);
  }
}
#endif /* SQLITE_ENABLE_UNLOCK_NOTIFY */

/*
** tclcmd:  sqlite3_unlock_notify db
*/
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
static int test_unlock_notify(
  ClientData clientData, /* Unused */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  int rc;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }

  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
    return TCL_ERROR;
  }
  rc = sqlite3_unlock_notify(db, test_unlock_notify_cb, (void *)interp);
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
  return TCL_OK;
}
#endif


/*
**     tcl_objproc COMMANDNAME ARGS...
**
** Run a TCL command using its objProc interface.  Throw an error if
** the command has no objProc interface.
*/
static int runAsObjProc(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_CmdInfo cmdInfo;
  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "COMMAND ...");
    return TCL_ERROR;
  }
  if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
    Tcl_AppendResult(interp, "command not found: ",
           Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  if( cmdInfo.objProc==0 ){
    Tcl_AppendResult(interp, "command has no objProc: ",
           Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  return cmdInfo.objProc(cmdInfo.objClientData, interp, objc-1, objv+1);
}


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest1_Init(Tcl_Interp *interp){
  extern int sqlite3_search_count;
  extern int sqlite3_found_count;
  extern int sqlite3_interrupt_count;
  extern int sqlite3_open_file_count;
  extern int sqlite3_sort_count;
  extern int sqlite3_current_time;
#if SQLITE_OS_UNIX && defined(__APPLE__)
  extern int sqlite3_hostid_num;
#endif
  extern int sqlite3_max_blobsize;
  extern int sqlite3BtreeSharedCacheReport(void*,
                                          Tcl_Interp*,int,Tcl_Obj*CONST*);
  static struct {
     char *zName;
     Tcl_CmdProc *xProc;
  } aCmd[] = {
     { "db_enter",                      (Tcl_CmdProc*)db_enter               },
     { "db_leave",                      (Tcl_CmdProc*)db_leave               },
     { "sqlite3_mprintf_int",           (Tcl_CmdProc*)sqlite3_mprintf_int    },
     { "sqlite3_mprintf_int64",         (Tcl_CmdProc*)sqlite3_mprintf_int64  },
     { "sqlite3_mprintf_long",          (Tcl_CmdProc*)sqlite3_mprintf_long   },
     { "sqlite3_mprintf_str",           (Tcl_CmdProc*)sqlite3_mprintf_str    },
     { "sqlite3_snprintf_str",          (Tcl_CmdProc*)sqlite3_snprintf_str   },
     { "sqlite3_mprintf_stronly",       (Tcl_CmdProc*)sqlite3_mprintf_stronly},
     { "sqlite3_mprintf_double",        (Tcl_CmdProc*)sqlite3_mprintf_double },
     { "sqlite3_mprintf_scaled",        (Tcl_CmdProc*)sqlite3_mprintf_scaled },
     { "sqlite3_mprintf_hexdouble",   (Tcl_CmdProc*)sqlite3_mprintf_hexdouble},
     { "sqlite3_mprintf_z_test",        (Tcl_CmdProc*)test_mprintf_z        },
     { "sqlite3_mprintf_n_test",        (Tcl_CmdProc*)test_mprintf_n        },
     { "sqlite3_snprintf_int",          (Tcl_CmdProc*)test_snprintf_int     },
     { "sqlite3_last_insert_rowid",     (Tcl_CmdProc*)test_last_rowid       },
     { "sqlite3_exec_printf",           (Tcl_CmdProc*)test_exec_printf      },
     { "sqlite3_exec_hex",              (Tcl_CmdProc*)test_exec_hex         },
     { "sqlite3_exec",                  (Tcl_CmdProc*)test_exec             },
     { "sqlite3_exec_nr",               (Tcl_CmdProc*)test_exec_nr          },
#ifndef SQLITE_OMIT_GET_TABLE
     { "sqlite3_get_table_printf",      (Tcl_CmdProc*)test_get_table_printf },
#endif
     { "sqlite3_close",                 (Tcl_CmdProc*)sqlite_test_close     },
     { "sqlite3_create_function",       (Tcl_CmdProc*)test_create_function  },
     { "sqlite3_create_aggregate",      (Tcl_CmdProc*)test_create_aggregate },
     { "sqlite_register_test_function", (Tcl_CmdProc*)test_register_func    },
     { "sqlite_abort",                  (Tcl_CmdProc*)sqlite_abort          },
     { "sqlite_bind",                   (Tcl_CmdProc*)test_bind             },
     { "breakpoint",                    (Tcl_CmdProc*)test_breakpoint       },
     { "sqlite3_key",                   (Tcl_CmdProc*)test_key              },
     { "sqlite3_rekey",                 (Tcl_CmdProc*)test_rekey            },
     { "sqlite_set_magic",              (Tcl_CmdProc*)sqlite_set_magic      },
     { "sqlite3_interrupt",             (Tcl_CmdProc*)test_interrupt        },
     { "sqlite_delete_function",        (Tcl_CmdProc*)delete_function       },
     { "sqlite_delete_collation",       (Tcl_CmdProc*)delete_collation      },
     { "sqlite3_get_autocommit",        (Tcl_CmdProc*)get_autocommit        },
     { "sqlite3_stack_used",            (Tcl_CmdProc*)test_stack_used       },
     { "sqlite3_busy_timeout",          (Tcl_CmdProc*)test_busy_timeout     },
     { "printf",                        (Tcl_CmdProc*)test_printf           },
     { "sqlite3IoTrace",              (Tcl_CmdProc*)test_io_trace         },
  };
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "sqlite3_connection_pointer",    get_sqlite_pointer, 0 },
     { "sqlite3_bind_int",              test_bind_int,      0 },
     { "sqlite3_bind_zeroblob",         test_bind_zeroblob, 0 },
     { "sqlite3_bind_int64",            test_bind_int64,    0 },
     { "sqlite3_bind_double",           test_bind_double,   0 },
     { "sqlite3_bind_null",             test_bind_null     ,0 },
     { "sqlite3_bind_text",             test_bind_text     ,0 },
     { "sqlite3_bind_text16",           test_bind_text16   ,0 },
     { "sqlite3_bind_blob",             test_bind_blob     ,0 },
     { "sqlite3_bind_parameter_count",  test_bind_parameter_count, 0},
     { "sqlite3_bind_parameter_name",   test_bind_parameter_name,  0},
     { "sqlite3_bind_parameter_index",  test_bind_parameter_index, 0},
     { "sqlite3_clear_bindings",        test_clear_bindings, 0},
     { "sqlite3_sleep",                 test_sleep,          0},
     { "sqlite3_errcode",               test_errcode       ,0 },
     { "sqlite3_extended_errcode",      test_ex_errcode    ,0 },
     { "sqlite3_errmsg",                test_errmsg        ,0 },
     { "sqlite3_errmsg16",              test_errmsg16      ,0 },
     { "sqlite3_open",                  test_open          ,0 },
     { "sqlite3_open16",                test_open16        ,0 },
     { "sqlite3_complete16",            test_complete16    ,0 },

     { "sqlite3_prepare",               test_prepare       ,0 },
     { "sqlite3_prepare16",             test_prepare16     ,0 },
     { "sqlite3_prepare_v2",            test_prepare_v2    ,0 },
     { "sqlite3_prepare_tkt3134",       test_prepare_tkt3134, 0},
     { "sqlite3_prepare16_v2",          test_prepare16_v2  ,0 },
     { "sqlite3_finalize",              test_finalize      ,0 },
     { "sqlite3_stmt_status",           test_stmt_status   ,0 },
     { "sqlite3_reset",                 test_reset         ,0 },
     { "sqlite3_expired",               test_expired       ,0 },
     { "sqlite3_transfer_bindings",     test_transfer_bind ,0 },
     { "sqlite3_changes",               test_changes       ,0 },
     { "sqlite3_step",                  test_step          ,0 },
     { "sqlite3_sql",                   test_sql           ,0 },
     { "sqlite3_next_stmt",             test_next_stmt     ,0 },

     { "sqlite3_release_memory",        test_release_memory,     0},
     { "sqlite3_soft_heap_limit",       test_soft_heap_limit,    0},
     { "sqlite3_thread_cleanup",        test_thread_cleanup,     0},
     { "sqlite3_pager_refcounts",       test_pager_refcounts,    0},

     { "sqlite3_load_extension",        test_load_extension,     0},
     { "sqlite3_enable_load_extension", test_enable_load,        0},
     { "sqlite3_extended_result_codes", test_extended_result_codes, 0},
     { "sqlite3_limit",                 test_limit,                 0},

     { "save_prng_state",               save_prng_state,    0 },
     { "restore_prng_state",            restore_prng_state, 0 },
     { "reset_prng_state",              reset_prng_state,   0 },
     { "tcl_objproc",                   runAsObjProc,       0 },

     /* sqlite3_column_*() API */
     { "sqlite3_column_count",          test_column_count  ,0 },
     { "sqlite3_data_count",            test_data_count    ,0 },
     { "sqlite3_column_type",           test_column_type   ,0 },
     { "sqlite3_column_blob",           test_column_blob   ,0 },
     { "sqlite3_column_double",         test_column_double ,0 },
     { "sqlite3_column_int64",          test_column_int64  ,0 },
     { "sqlite3_column_text",   test_stmt_utf8,  (void*)sqlite3_column_text },
     { "sqlite3_column_name",   test_stmt_utf8,  (void*)sqlite3_column_name },
     { "sqlite3_column_int",    test_stmt_int,   (void*)sqlite3_column_int  },
     { "sqlite3_column_bytes",  test_stmt_int,   (void*)sqlite3_column_bytes},
#ifndef SQLITE_OMIT_DECLTYPE
     { "sqlite3_column_decltype",test_stmt_utf8,(void*)sqlite3_column_decltype},
#endif
#ifdef SQLITE_ENABLE_COLUMN_METADATA
{ "sqlite3_column_database_name",test_stmt_utf8,(void*)sqlite3_column_database_name},
{ "sqlite3_column_table_name",test_stmt_utf8,(void*)sqlite3_column_table_name},
{ "sqlite3_column_origin_name",test_stmt_utf8,(void*)sqlite3_column_origin_name},
#endif

#ifndef SQLITE_OMIT_UTF16
     { "sqlite3_column_bytes16", test_stmt_int, (void*)sqlite3_column_bytes16 },
     { "sqlite3_column_text16",  test_stmt_utf16, (void*)sqlite3_column_text16},
     { "sqlite3_column_name16",  test_stmt_utf16, (void*)sqlite3_column_name16},
     { "add_alignment_test_collations", add_alignment_test_collations, 0      },
#ifndef SQLITE_OMIT_DECLTYPE
     { "sqlite3_column_decltype16",test_stmt_utf16,(void*)sqlite3_column_decltype16},
#endif
#ifdef SQLITE_ENABLE_COLUMN_METADATA
{"sqlite3_column_database_name16",
  test_stmt_utf16, sqlite3_column_database_name16},
{"sqlite3_column_table_name16", test_stmt_utf16, (void*)sqlite3_column_table_name16},
{"sqlite3_column_origin_name16", test_stmt_utf16, (void*)sqlite3_column_origin_name16},
#endif
#endif
     { "sqlite3_create_collation_v2", test_create_collation_v2, 0 },
     { "sqlite3_global_recover",     test_global_recover, 0   },
     { "working_64bit_int",          working_64bit_int,   0   },
     { "vfs_unlink_test",            vfs_unlink_test,     0   },
     { "vfs_initfail_test",          vfs_initfail_test,   0   },
     { "vfs_unregister_all",         vfs_unregister_all,  0   },
     { "vfs_reregister_all",         vfs_reregister_all,  0   },
     { "file_control_test",          file_control_test,   0   },
     { "file_control_lasterrno_test", file_control_lasterrno_test,  0   },
     { "file_control_lockproxy_test", file_control_lockproxy_test,  0   },
     { "sqlite3_vfs_list",           vfs_list,     0   },

     /* Functions from os.h */
#ifndef SQLITE_OMIT_UTF16
     { "add_test_collate",        test_collate, 0            },
     { "add_test_collate_needed", test_collate_needed, 0     },
     { "add_test_function",       test_function, 0           },
#endif
     { "sqlite3_test_errstr",     test_errstr, 0             },
     { "tcl_variable_type",       tcl_variable_type, 0       },
#ifndef SQLITE_OMIT_SHARED_CACHE
     { "sqlite3_enable_shared_cache", test_enable_shared, 0  },
     { "sqlite3_shared_cache_report", sqlite3BtreeSharedCacheReport, 0},
#endif
     { "sqlite3_libversion_number", test_libversion_number, 0  },
#ifdef SQLITE_ENABLE_COLUMN_METADATA
     { "sqlite3_table_column_metadata", test_table_column_metadata, 0  },
#endif
#ifndef SQLITE_OMIT_INCRBLOB
     { "sqlite3_blob_read",  test_blob_read, 0  },
     { "sqlite3_blob_write", test_blob_write, 0  },
#endif
     { "pcache_stats",       test_pcache_stats, 0  },
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
     { "sqlite3_unlock_notify", test_unlock_notify, 0  },
#endif
  };
  static int bitmask_size = sizeof(Bitmask)*8;
  int i;
  extern int sqlite3_sync_count, sqlite3_fullsync_count;
  extern int sqlite3_opentemp_count;
  extern int sqlite3_like_count;
  extern int sqlite3_xferopt_count;
  extern int sqlite3_pager_readdb_count;
  extern int sqlite3_pager_writedb_count;
  extern int sqlite3_pager_writej_count;
#if defined(__linux__) && defined(SQLITE_TEST) && SQLITE_THREADSAFE
  extern int threadsOverrideEachOthersLocks;
#endif
#if SQLITE_OS_WIN
  extern int sqlite3_os_type;
#endif
#ifdef SQLITE_DEBUG
  extern int sqlite3WhereTrace;
  extern int sqlite3OSTrace;
  extern int sqlite3VdbeAddopTrace;
#endif
#ifdef SQLITE_TEST
  extern char sqlite3_query_plan[];
  static char *query_plan = sqlite3_query_plan;
#ifdef SQLITE_ENABLE_FTS3
  extern int sqlite3_fts3_enable_parentheses;
#endif
#endif

  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  Tcl_LinkVar(interp, "sqlite_search_count", 
      (char*)&sqlite3_search_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_found_count", 
      (char*)&sqlite3_found_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_sort_count", 
      (char*)&sqlite3_sort_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite3_max_blobsize", 
      (char*)&sqlite3_max_blobsize, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_like_count", 
      (char*)&sqlite3_like_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_interrupt_count", 
      (char*)&sqlite3_interrupt_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_open_file_count", 
      (char*)&sqlite3_open_file_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_current_time", 
      (char*)&sqlite3_current_time, TCL_LINK_INT);
#if SQLITE_OS_UNIX && defined(__APPLE__)
  Tcl_LinkVar(interp, "sqlite_hostid_num", 
      (char*)&sqlite3_hostid_num, TCL_LINK_INT);
#endif
  Tcl_LinkVar(interp, "sqlite3_xferopt_count",
      (char*)&sqlite3_xferopt_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite3_pager_readdb_count",
      (char*)&sqlite3_pager_readdb_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite3_pager_writedb_count",
      (char*)&sqlite3_pager_writedb_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite3_pager_writej_count",
      (char*)&sqlite3_pager_writej_count, TCL_LINK_INT);
#ifndef SQLITE_OMIT_UTF16
  Tcl_LinkVar(interp, "unaligned_string_counter",
      (char*)&unaligned_string_counter, TCL_LINK_INT);
#endif
#if defined(__linux__) && defined(SQLITE_TEST) && SQLITE_THREADSAFE
  Tcl_LinkVar(interp, "threadsOverrideEachOthersLocks",
      (char*)&threadsOverrideEachOthersLocks, TCL_LINK_INT);
#endif
#ifndef SQLITE_OMIT_UTF16
  Tcl_LinkVar(interp, "sqlite_last_needed_collation",
      (char*)&pzNeededCollation, TCL_LINK_STRING|TCL_LINK_READ_ONLY);
#endif
#if SQLITE_OS_WIN
  Tcl_LinkVar(interp, "sqlite_os_type",
      (char*)&sqlite3_os_type, TCL_LINK_INT);
#endif
#ifdef SQLITE_TEST
  Tcl_LinkVar(interp, "sqlite_query_plan",
      (char*)&query_plan, TCL_LINK_STRING|TCL_LINK_READ_ONLY);
#endif
#ifdef SQLITE_DEBUG
  Tcl_LinkVar(interp, "sqlite_addop_trace",
      (char*)&sqlite3VdbeAddopTrace, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_where_trace",
      (char*)&sqlite3WhereTrace, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_os_trace",
      (char*)&sqlite3OSTrace, TCL_LINK_INT);
#endif
#ifndef SQLITE_OMIT_DISKIO
  Tcl_LinkVar(interp, "sqlite_opentemp_count",
      (char*)&sqlite3_opentemp_count, TCL_LINK_INT);
#endif
  Tcl_LinkVar(interp, "sqlite_static_bind_value",
      (char*)&sqlite_static_bind_value, TCL_LINK_STRING);
  Tcl_LinkVar(interp, "sqlite_static_bind_nbyte",
      (char*)&sqlite_static_bind_nbyte, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_temp_directory",
      (char*)&sqlite3_temp_directory, TCL_LINK_STRING);
  Tcl_LinkVar(interp, "bitmask_size",
      (char*)&bitmask_size, TCL_LINK_INT|TCL_LINK_READ_ONLY);
  Tcl_LinkVar(interp, "sqlite_sync_count",
      (char*)&sqlite3_sync_count, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_fullsync_count",
      (char*)&sqlite3_fullsync_count, TCL_LINK_INT);
#if defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_TEST)
  Tcl_LinkVar(interp, "sqlite_fts3_enable_parentheses",
      (char*)&sqlite3_fts3_enable_parentheses, TCL_LINK_INT);
#endif
  return TCL_OK;
}

Added src/test2.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the pager.c module in SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test2.c,v 1.74 2009/07/24 19:01:20 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/*
** Interpret an SQLite error number
*/
static char *errorName(int rc){
  char *zName;
  switch( rc ){
    case SQLITE_OK:         zName = "SQLITE_OK";          break;
    case SQLITE_ERROR:      zName = "SQLITE_ERROR";       break;
    case SQLITE_PERM:       zName = "SQLITE_PERM";        break;
    case SQLITE_ABORT:      zName = "SQLITE_ABORT";       break;
    case SQLITE_BUSY:       zName = "SQLITE_BUSY";        break;
    case SQLITE_NOMEM:      zName = "SQLITE_NOMEM";       break;
    case SQLITE_READONLY:   zName = "SQLITE_READONLY";    break;
    case SQLITE_INTERRUPT:  zName = "SQLITE_INTERRUPT";   break;
    case SQLITE_IOERR:      zName = "SQLITE_IOERR";       break;
    case SQLITE_CORRUPT:    zName = "SQLITE_CORRUPT";     break;
    case SQLITE_FULL:       zName = "SQLITE_FULL";        break;
    case SQLITE_CANTOPEN:   zName = "SQLITE_CANTOPEN";    break;
    case SQLITE_PROTOCOL:   zName = "SQLITE_PROTOCOL";    break;
    case SQLITE_EMPTY:      zName = "SQLITE_EMPTY";       break;
    case SQLITE_SCHEMA:     zName = "SQLITE_SCHEMA";      break;
    case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT";  break;
    case SQLITE_MISMATCH:   zName = "SQLITE_MISMATCH";    break;
    case SQLITE_MISUSE:     zName = "SQLITE_MISUSE";      break;
    case SQLITE_NOLFS:      zName = "SQLITE_NOLFS";       break;
    default:                zName = "SQLITE_Unknown";     break;
  }
  return zName;
}

/*
** Page size and reserved size used for testing.
*/
static int test_pagesize = 1024;

/*
** Dummy page reinitializer
*/
static void pager_test_reiniter(DbPage *pNotUsed){
  return;
}

/*
** Usage:   pager_open FILENAME N-PAGE
**
** Open a new pager
*/
static int pager_open(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  u16 pageSize;
  Pager *pPager;
  int nPage;
  int rc;
  char zBuf[100];
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME N-PAGE\"", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &nPage) ) return TCL_ERROR;
  rc = sqlite3PagerOpen(sqlite3_vfs_find(0), &pPager, argv[1], 0, 0,
      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB,
      pager_test_reiniter);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3PagerSetCachesize(pPager, nPage);
  pageSize = test_pagesize;
  sqlite3PagerSetPagesize(pPager, &pageSize, -1);
  sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPager);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage:   pager_close ID
**
** Close the given pager.
*/
static int pager_close(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerClose(pPager);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   pager_rollback ID
**
** Rollback changes
*/
static int pager_rollback(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerRollback(pPager);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   pager_commit ID
**
** Commit all changes
*/
static int pager_commit(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerCommitPhaseOne(pPager, 0, 0);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  rc = sqlite3PagerCommitPhaseTwo(pPager);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   pager_stmt_begin ID
**
** Start a new checkpoint.
*/
static int pager_stmt_begin(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerOpenSavepoint(pPager, 1);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   pager_stmt_rollback ID
**
** Rollback changes to a checkpoint
*/
static int pager_stmt_rollback(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, 0);
  sqlite3PagerSavepoint(pPager, SAVEPOINT_RELEASE, 0);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   pager_stmt_commit ID
**
** Commit changes to a checkpoint
*/
static int pager_stmt_commit(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_RELEASE, 0);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   pager_stats ID
**
** Return pager statistics.
*/
static int pager_stats(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int i, *a;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  a = sqlite3PagerStats(pPager);
  for(i=0; i<9; i++){
    static char *zName[] = {
      "ref", "page", "max", "size", "state", "err",
      "hit", "miss", "ovfl",
    };
    char zBuf[100];
    Tcl_AppendElement(interp, zName[i]);
    sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",a[i]);
    Tcl_AppendElement(interp, zBuf);
  }
  return TCL_OK;
}

/*
** Usage:   pager_pagecount ID
**
** Return the size of the database file.
*/
static int pager_pagecount(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  char zBuf[100];
  int nPage;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  sqlite3PagerPagecount(pPager, &nPage);
  sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nPage);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage:   page_get ID PGNO
**
** Return a pointer to a page from the database.
*/
static int page_get(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  char zBuf[100];
  DbPage *pPage;
  int pgno;
  int rc;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID PGNO\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR;
  rc = sqlite3PagerSharedLock(pPager);
  if( rc==SQLITE_OK ){
    rc = sqlite3PagerGet(pPager, pgno, &pPage);
  }
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPage);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage:   page_lookup ID PGNO
**
** Return a pointer to a page if the page is already in cache.
** If not in cache, return an empty string.
*/
static int page_lookup(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  char zBuf[100];
  DbPage *pPage;
  int pgno;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID PGNO\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR;
  pPage = sqlite3PagerLookup(pPager, pgno);
  if( pPage ){
    sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPage);
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}

/*
** Usage:   pager_truncate ID PGNO
*/
static int pager_truncate(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Pager *pPager;
  int pgno;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID PGNO\"", 0);
    return TCL_ERROR;
  }
  pPager = sqlite3TestTextToPtr(argv[1]);
  if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR;
  sqlite3PagerTruncateImage(pPager, pgno);
  return TCL_OK;
}


/*
** Usage:   page_unref PAGE
**
** Drop a pointer to a page.
*/
static int page_unref(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  DbPage *pPage;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " PAGE\"", 0);
    return TCL_ERROR;
  }
  pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]);
  sqlite3PagerUnref(pPage);
  return TCL_OK;
}

/*
** Usage:   page_read PAGE
**
** Return the content of a page
*/
static int page_read(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  char zBuf[100];
  DbPage *pPage;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " PAGE\"", 0);
    return TCL_ERROR;
  }
  pPage = sqlite3TestTextToPtr(argv[1]);
  memcpy(zBuf, sqlite3PagerGetData(pPage), sizeof(zBuf));
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage:   page_number PAGE
**
** Return the page number for a page.
*/
static int page_number(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  char zBuf[100];
  DbPage *pPage;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " PAGE\"", 0);
    return TCL_ERROR;
  }
  pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]);
  sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", sqlite3PagerPagenumber(pPage));
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage:   page_write PAGE DATA
**
** Write something into a page.
*/
static int page_write(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  DbPage *pPage;
  char *pData;
  int rc;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " PAGE DATA\"", 0);
    return TCL_ERROR;
  }
  pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3PagerWrite(pPage);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  pData = sqlite3PagerGetData(pPage);
  strncpy(pData, argv[2], test_pagesize-1);
  pData[test_pagesize-1] = 0;
  return TCL_OK;
}

#ifndef SQLITE_OMIT_DISKIO
/*
** Usage:   fake_big_file  N  FILENAME
**
** Write a few bytes at the N megabyte point of FILENAME.  This will
** create a large file.  If the file was a valid SQLite database, then
** the next time the database is opened, SQLite will begin allocating
** new pages after N.  If N is 2096 or bigger, this will test the
** ability of SQLite to write to large files.
*/
static int fake_big_file(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  sqlite3_vfs *pVfs;
  sqlite3_file *fd = 0;
  int rc;
  int n;
  i64 offset;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " N-MEGABYTES FILE\"", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR;

  pVfs = sqlite3_vfs_find(0);
  rc = sqlite3OsOpenMalloc(pVfs, argv[2], &fd, 
      (SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB), 0
  );
  if( rc ){
    Tcl_AppendResult(interp, "open failed: ", errorName(rc), 0);
    return TCL_ERROR;
  }
  offset = n;
  offset *= 1024*1024;
  rc = sqlite3OsWrite(fd, "Hello, World!", 14, offset);
  sqlite3OsCloseFree(fd);
  if( rc ){
    Tcl_AppendResult(interp, "write failed: ", errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}
#endif


/*
** test_control_pending_byte  PENDING_BYTE
**
** Set the PENDING_BYTE using the sqlite3_test_control() interface.
*/
static int testPendingByte(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int pbyte;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                     " PENDING-BYTE\"", (void*)0);
  }
  if( Tcl_GetInt(interp, argv[1], &pbyte) ) return TCL_ERROR;
  rc = sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, pbyte);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;
}  

/*
** sqlite3BitvecBuiltinTest SIZE PROGRAM
**
** Invoke the SQLITE_TESTCTRL_BITVEC_TEST operator on test_control.
** See comments on sqlite3BitvecBuiltinTest() for additional information.
*/
static int testBitvecBuiltinTest(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int sz, rc;
  int nProg = 0;
  int aProg[100];
  const char *z;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                     " SIZE PROGRAM\"", (void*)0);
  }
  if( Tcl_GetInt(interp, argv[1], &sz) ) return TCL_ERROR;
  z = argv[2];
  while( nProg<99 && *z ){
    while( *z && !sqlite3Isdigit(*z) ){ z++; }
    if( *z==0 ) break;
    aProg[nProg++] = atoi(z);
    while( sqlite3Isdigit(*z) ){ z++; }
  }
  aProg[nProg] = 0;
  rc = sqlite3_test_control(SQLITE_TESTCTRL_BITVEC_TEST, sz, aProg);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;
}  

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest2_Init(Tcl_Interp *interp){
  extern int sqlite3_io_error_persist;
  extern int sqlite3_io_error_pending;
  extern int sqlite3_io_error_hit;
  extern int sqlite3_io_error_hardhit;
  extern int sqlite3_diskfull_pending;
  extern int sqlite3_diskfull;
  static struct {
    char *zName;
    Tcl_CmdProc *xProc;
  } aCmd[] = {
    { "pager_open",              (Tcl_CmdProc*)pager_open          },
    { "pager_close",             (Tcl_CmdProc*)pager_close         },
    { "pager_commit",            (Tcl_CmdProc*)pager_commit        },
    { "pager_rollback",          (Tcl_CmdProc*)pager_rollback      },
    { "pager_stmt_begin",        (Tcl_CmdProc*)pager_stmt_begin    },
    { "pager_stmt_commit",       (Tcl_CmdProc*)pager_stmt_commit   },
    { "pager_stmt_rollback",     (Tcl_CmdProc*)pager_stmt_rollback },
    { "pager_stats",             (Tcl_CmdProc*)pager_stats         },
    { "pager_pagecount",         (Tcl_CmdProc*)pager_pagecount     },
    { "page_get",                (Tcl_CmdProc*)page_get            },
    { "page_lookup",             (Tcl_CmdProc*)page_lookup         },
    { "page_unref",              (Tcl_CmdProc*)page_unref          },
    { "page_read",               (Tcl_CmdProc*)page_read           },
    { "page_write",              (Tcl_CmdProc*)page_write          },
    { "page_number",             (Tcl_CmdProc*)page_number         },
    { "pager_truncate",          (Tcl_CmdProc*)pager_truncate      },
#ifndef SQLITE_OMIT_DISKIO
    { "fake_big_file",           (Tcl_CmdProc*)fake_big_file       },
#endif
    { "sqlite3BitvecBuiltinTest",(Tcl_CmdProc*)testBitvecBuiltinTest     },
    { "sqlite3_test_control_pending_byte", (Tcl_CmdProc*)testPendingByte },
  };
  int i;
  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }
  Tcl_LinkVar(interp, "sqlite_io_error_pending",
     (char*)&sqlite3_io_error_pending, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_io_error_persist",
     (char*)&sqlite3_io_error_persist, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_io_error_hit",
     (char*)&sqlite3_io_error_hit, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_io_error_hardhit",
     (char*)&sqlite3_io_error_hardhit, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_diskfull_pending",
     (char*)&sqlite3_diskfull_pending, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_diskfull",
     (char*)&sqlite3_diskfull, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_pending_byte",
     (char*)&sqlite3PendingByte, TCL_LINK_INT | TCL_LINK_READ_ONLY);
  return TCL_OK;
}

Added src/test3.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the btree.c module in SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test3.c,v 1.111 2009/07/09 05:07:38 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "btreeInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
** Interpret an SQLite error number
*/
static char *errorName(int rc){
  char *zName;
  switch( rc ){
    case SQLITE_OK:         zName = "SQLITE_OK";          break;
    case SQLITE_ERROR:      zName = "SQLITE_ERROR";       break;
    case SQLITE_PERM:       zName = "SQLITE_PERM";        break;
    case SQLITE_ABORT:      zName = "SQLITE_ABORT";       break;
    case SQLITE_BUSY:       zName = "SQLITE_BUSY";        break;
    case SQLITE_NOMEM:      zName = "SQLITE_NOMEM";       break;
    case SQLITE_READONLY:   zName = "SQLITE_READONLY";    break;
    case SQLITE_INTERRUPT:  zName = "SQLITE_INTERRUPT";   break;
    case SQLITE_IOERR:      zName = "SQLITE_IOERR";       break;
    case SQLITE_CORRUPT:    zName = "SQLITE_CORRUPT";     break;
    case SQLITE_FULL:       zName = "SQLITE_FULL";        break;
    case SQLITE_CANTOPEN:   zName = "SQLITE_CANTOPEN";    break;
    case SQLITE_PROTOCOL:   zName = "SQLITE_PROTOCOL";    break;
    case SQLITE_EMPTY:      zName = "SQLITE_EMPTY";       break;
    case SQLITE_LOCKED:     zName = "SQLITE_LOCKED";      break;
    default:                zName = "SQLITE_Unknown";     break;
  }
  return zName;
}

/*
** A bogus sqlite3 connection structure for use in the btree
** tests.
*/
static sqlite3 sDb;
static int nRefSqlite3 = 0;

/*
** Usage:   btree_open FILENAME NCACHE FLAGS
**
** Open a new database
*/
static int btree_open(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int rc, nCache, flags;
  char zBuf[100];
  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME NCACHE FLAGS\"", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[3], &flags) ) return TCL_ERROR;
  nRefSqlite3++;
  if( nRefSqlite3==1 ){
    sDb.pVfs = sqlite3_vfs_find(0);
    sDb.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    sqlite3_mutex_enter(sDb.mutex);
  }
  rc = sqlite3BtreeOpen(argv[1], &sDb, &pBt, flags,
     SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3BtreeSetCacheSize(pBt, nCache);
  sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pBt);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage:   btree_close ID
**
** Close the given database.
*/
static int btree_close(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
  rc = sqlite3BtreeClose(pBt);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  nRefSqlite3--;
  if( nRefSqlite3==0 ){
    sqlite3_mutex_leave(sDb.mutex);
    sqlite3_mutex_free(sDb.mutex);
    sDb.mutex = 0;
    sDb.pVfs = 0;
  }
  return TCL_OK;
}


/*
** Usage:   btree_begin_transaction ID
**
** Start a new transaction
*/
static int btree_begin_transaction(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int rc;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
  sqlite3BtreeEnter(pBt);
  rc = sqlite3BtreeBeginTrans(pBt, 1);
  sqlite3BtreeLeave(pBt);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Usage:   btree_pager_stats ID
**
** Returns pager statistics
*/
static int btree_pager_stats(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int i;
  int *a;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
 
  /* Normally in this file, with a b-tree handle opened using the 
  ** [btree_open] command it is safe to call sqlite3BtreeEnter() directly.
  ** But this function is sometimes called with a btree handle obtained
  ** from an open SQLite connection (using [btree_from_db]). In this case
  ** we need to obtain the mutex for the controlling SQLite handle before
  ** it is safe to call sqlite3BtreeEnter().
  */
  sqlite3_mutex_enter(pBt->db->mutex);

  sqlite3BtreeEnter(pBt);
  a = sqlite3PagerStats(sqlite3BtreePager(pBt));
  for(i=0; i<11; i++){
    static char *zName[] = {
      "ref", "page", "max", "size", "state", "err",
      "hit", "miss", "ovfl", "read", "write"
    };
    char zBuf[100];
    Tcl_AppendElement(interp, zName[i]);
    sqlite3_snprintf(sizeof(zBuf), zBuf,"%d",a[i]);
    Tcl_AppendElement(interp, zBuf);
  }
  sqlite3BtreeLeave(pBt);

  /* Release the mutex on the SQLite handle that controls this b-tree */
  sqlite3_mutex_leave(pBt->db->mutex);
  return TCL_OK;
}

/*
** Usage:   btree_cursor ID TABLENUM WRITEABLE
**
** Create a new cursor.  Return the ID for the cursor.
*/
static int btree_cursor(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int iTable;
  BtCursor *pCur;
  int rc;
  int wrFlag;
  char zBuf[30];

  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID TABLENUM WRITEABLE\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
  if( Tcl_GetInt(interp, argv[2], &iTable) ) return TCL_ERROR;
  if( Tcl_GetBoolean(interp, argv[3], &wrFlag) ) return TCL_ERROR;
  pCur = (BtCursor *)ckalloc(sqlite3BtreeCursorSize());
  memset(pCur, 0, sqlite3BtreeCursorSize());
  sqlite3BtreeEnter(pBt);
  rc = sqlite3BtreeLockTable(pBt, iTable, wrFlag);
  if( rc==SQLITE_OK ){
    rc = sqlite3BtreeCursor(pBt, iTable, wrFlag, 0, pCur);
  }
  sqlite3BtreeLeave(pBt);
  if( rc ){
    ckfree((char *)pCur);
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pCur);
  Tcl_AppendResult(interp, zBuf, 0);
  return SQLITE_OK;
}

/*
** Usage:   btree_close_cursor ID
**
** Close a cursor opened using btree_cursor.
*/
static int btree_close_cursor(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  BtCursor *pCur;
  Btree *pBt;
  int rc;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pCur = sqlite3TestTextToPtr(argv[1]);
  pBt = pCur->pBtree;
  sqlite3BtreeEnter(pBt);
  rc = sqlite3BtreeCloseCursor(pCur);
  sqlite3BtreeLeave(pBt);
  ckfree((char *)pCur);
  if( rc ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  return SQLITE_OK;
}

/*
** Usage:   btree_next ID
**
** Move the cursor to the next entry in the table.  Return 0 on success
** or 1 if the cursor was already on the last entry in the table or if
** the table is empty.
*/
static int btree_next(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  BtCursor *pCur;
  int rc;
  int res = 0;
  char zBuf[100];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pCur = sqlite3TestTextToPtr(argv[1]);
  sqlite3BtreeEnter(pCur->pBtree);
  rc = sqlite3BtreeNext(pCur, &res);
  sqlite3BtreeLeave(pCur->pBtree);
  if( rc ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",res);
  Tcl_AppendResult(interp, zBuf, 0);
  return SQLITE_OK;
}

/*
** Usage:   btree_first ID
**
** Move the cursor to the first entry in the table.  Return 0 if the
** cursor was left point to something and 1 if the table is empty.
*/
static int btree_first(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  BtCursor *pCur;
  int rc;
  int res = 0;
  char zBuf[100];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pCur = sqlite3TestTextToPtr(argv[1]);
  sqlite3BtreeEnter(pCur->pBtree);
  rc = sqlite3BtreeFirst(pCur, &res);
  sqlite3BtreeLeave(pCur->pBtree);
  if( rc ){
    Tcl_AppendResult(interp, errorName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",res);
  Tcl_AppendResult(interp, zBuf, 0);
  return SQLITE_OK;
}

/*
** Usage:   btree_eof ID
**
** Return TRUE if the given cursor is not pointing at a valid entry.
** Return FALSE if the cursor does point to a valid entry.
*/
static int btree_eof(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  BtCursor *pCur;
  int rc;
  char zBuf[50];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pCur = sqlite3TestTextToPtr(argv[1]);
  sqlite3BtreeEnter(pCur->pBtree);
  rc = sqlite3BtreeEof(pCur);
  sqlite3BtreeLeave(pCur->pBtree);
  sqlite3_snprintf(sizeof(zBuf),zBuf, "%d", rc);
  Tcl_AppendResult(interp, zBuf, 0);
  return SQLITE_OK;
}

/*
** Usage:   btree_payload_size ID
**
** Return the number of bytes of payload
*/
static int btree_payload_size(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  BtCursor *pCur;
  int n2;
  u64 n1;
  char zBuf[50];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pCur = sqlite3TestTextToPtr(argv[1]);
  sqlite3BtreeEnter(pCur->pBtree);

  /* The cursor may be in "require-seek" state. If this is the case, the
  ** call to BtreeDataSize() will fix it. */
  sqlite3BtreeDataSize(pCur, (u32*)&n2);
  if( pCur->apPage[pCur->iPage]->intKey ){
    n1 = 0;
  }else{
    sqlite3BtreeKeySize(pCur, (i64*)&n1);
  }
  sqlite3BtreeLeave(pCur->pBtree);
  sqlite3_snprintf(sizeof(zBuf),zBuf, "%d", (int)(n1+n2));
  Tcl_AppendResult(interp, zBuf, 0);
  return SQLITE_OK;
}

/*
** usage:   varint_test  START  MULTIPLIER  COUNT  INCREMENT
**
** This command tests the putVarint() and getVarint()
** routines, both for accuracy and for speed.
**
** An integer is written using putVarint() and read back with
** getVarint() and varified to be unchanged.  This repeats COUNT
** times.  The first integer is START*MULTIPLIER.  Each iteration
** increases the integer by INCREMENT.
**
** This command returns nothing if it works.  It returns an error message
** if something goes wrong.
*/
static int btree_varint_test(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  u32 start, mult, count, incr;
  u64 in, out;
  int n1, n2, i, j;
  unsigned char zBuf[100];
  if( argc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " START MULTIPLIER COUNT INCREMENT\"", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[1], (int*)&start) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[2], (int*)&mult) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[3], (int*)&count) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[4], (int*)&incr) ) return TCL_ERROR;
  in = start;
  in *= mult;
  for(i=0; i<count; i++){
    char zErr[200];
    n1 = putVarint(zBuf, in);
    if( n1>9 || n1<1 ){
      sprintf(zErr, "putVarint returned %d - should be between 1 and 9", n1);
      Tcl_AppendResult(interp, zErr, 0);
      return TCL_ERROR;
    }
    n2 = getVarint(zBuf, &out);
    if( n1!=n2 ){
      sprintf(zErr, "putVarint returned %d and getVarint returned %d", n1, n2);
      Tcl_AppendResult(interp, zErr, 0);
      return TCL_ERROR;
    }
    if( in!=out ){
      sprintf(zErr, "Wrote 0x%016llx and got back 0x%016llx", in, out);
      Tcl_AppendResult(interp, zErr, 0);
      return TCL_ERROR;
    }
    if( (in & 0xffffffff)==in ){
      u32 out32;
      n2 = getVarint32(zBuf, out32);
      out = out32;
      if( n1!=n2 ){
        sprintf(zErr, "putVarint returned %d and GetVarint32 returned %d", 
                  n1, n2);
        Tcl_AppendResult(interp, zErr, 0);
        return TCL_ERROR;
      }
      if( in!=out ){
        sprintf(zErr, "Wrote 0x%016llx and got back 0x%016llx from GetVarint32",
            in, out);
        Tcl_AppendResult(interp, zErr, 0);
        return TCL_ERROR;
      }
    }

    /* In order to get realistic timings, run getVarint 19 more times.
    ** This is because getVarint is called about 20 times more often
    ** than putVarint.
    */
    for(j=0; j<19; j++){
      getVarint(zBuf, &out);
    }
    in += incr;
  }
  return TCL_OK;
}

/*
** usage:   btree_from_db  DB-HANDLE
**
** This command returns the btree handle for the main database associated
** with the database-handle passed as the argument. Example usage:
**
** sqlite3 db test.db
** set bt [btree_from_db db]
*/
static int btree_from_db(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  char zBuf[100];
  Tcl_CmdInfo info;
  sqlite3 *db;
  Btree *pBt;
  int iDb = 0;

  if( argc!=2 && argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " DB-HANDLE ?N?\"", 0);
    return TCL_ERROR;
  }

  if( 1!=Tcl_GetCommandInfo(interp, argv[1], &info) ){
    Tcl_AppendResult(interp, "No such db-handle: \"", argv[1], "\"", 0);
    return TCL_ERROR;
  }
  if( argc==3 ){
    iDb = atoi(argv[2]);
  }

  db = *((sqlite3 **)info.objClientData);
  assert( db );

  pBt = db->aDb[iDb].pBt;
  sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", pBt);
  Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
  return TCL_OK;
}

/*
** Usage:   btree_ismemdb ID
**
** Return true if the B-Tree is in-memory.
*/
static int btree_ismemdb(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int res;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
  sqlite3_mutex_enter(pBt->db->mutex);
  sqlite3BtreeEnter(pBt);
  res = sqlite3PagerIsMemdb(sqlite3BtreePager(pBt));
  sqlite3BtreeLeave(pBt);
  sqlite3_mutex_leave(pBt->db->mutex);
  Tcl_SetObjResult(interp, Tcl_NewBooleanObj(res));
  return SQLITE_OK;
}

/*
** usage:   btree_set_cache_size ID NCACHE
**
** Set the size of the cache used by btree $ID.
*/
static int btree_set_cache_size(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int nCache;
  Btree *pBt;
  
  if( argc!=3 ){
    Tcl_AppendResult(
        interp, "wrong # args: should be \"", argv[0], " BT NCACHE\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
  if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR;

  sqlite3_mutex_enter(pBt->db->mutex);
  sqlite3BtreeEnter(pBt);
  sqlite3BtreeSetCacheSize(pBt, nCache);
  sqlite3BtreeLeave(pBt);
  sqlite3_mutex_leave(pBt->db->mutex);
  return TCL_OK;
}      



/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest3_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_CmdProc *xProc;
  } aCmd[] = {
     { "btree_open",               (Tcl_CmdProc*)btree_open               },
     { "btree_close",              (Tcl_CmdProc*)btree_close              },
     { "btree_begin_transaction",  (Tcl_CmdProc*)btree_begin_transaction  },
     { "btree_pager_stats",        (Tcl_CmdProc*)btree_pager_stats        },
     { "btree_cursor",             (Tcl_CmdProc*)btree_cursor             },
     { "btree_close_cursor",       (Tcl_CmdProc*)btree_close_cursor       },
     { "btree_next",               (Tcl_CmdProc*)btree_next               },
     { "btree_eof",                (Tcl_CmdProc*)btree_eof                },
     { "btree_payload_size",       (Tcl_CmdProc*)btree_payload_size       },
     { "btree_first",              (Tcl_CmdProc*)btree_first              },
     { "btree_varint_test",        (Tcl_CmdProc*)btree_varint_test        },
     { "btree_from_db",            (Tcl_CmdProc*)btree_from_db            },
     { "btree_ismemdb",            (Tcl_CmdProc*)btree_ismemdb            },
     { "btree_set_cache_size",     (Tcl_CmdProc*)btree_set_cache_size     }
  };
  int i;

  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }

  return TCL_OK;
}

Added src/test4.c.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/*
** 2003 December 18
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the the SQLite library in a multithreaded environment.
**
** $Id: test4.c,v 1.24 2008/10/12 00:27:54 shane Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#if defined(SQLITE_OS_UNIX) && OS_UNIX==1 && SQLITE_THREADSAFE
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <ctype.h>

/*
** Each thread is controlled by an instance of the following
** structure.
*/
typedef struct Thread Thread;
struct Thread {
  /* The first group of fields are writable by the master and read-only
  ** to the thread. */
  char *zFilename;       /* Name of database file */
  void (*xOp)(Thread*);  /* next operation to do */
  char *zArg;            /* argument usable by xOp */
  int opnum;             /* Operation number */
  int busy;              /* True if this thread is in use */

  /* The next group of fields are writable by the thread but read-only to the
  ** master. */
  int completed;        /* Number of operations completed */
  sqlite3 *db;           /* Open database */
  sqlite3_stmt *pStmt;     /* Pending operation */
  char *zErr;           /* operation error */
  char *zStaticErr;     /* Static error message */
  int rc;               /* operation return code */
  int argc;             /* number of columns in result */
  const char *argv[100];    /* result columns */
  const char *colv[100];    /* result column names */
};

/*
** There can be as many as 26 threads running at once.  Each is named
** by a capital letter: A, B, C, ..., Y, Z.
*/
#define N_THREAD 26
static Thread threadset[N_THREAD];


/*
** The main loop for a thread.  Threads use busy waiting. 
*/
static void *thread_main(void *pArg){
  Thread *p = (Thread*)pArg;
  if( p->db ){
    sqlite3_close(p->db);
  }
  sqlite3_open(p->zFilename, &p->db);
  if( SQLITE_OK!=sqlite3_errcode(p->db) ){
    p->zErr = strdup(sqlite3_errmsg(p->db));
    sqlite3_close(p->db);
    p->db = 0;
  }
  p->pStmt = 0;
  p->completed = 1;
  while( p->opnum<=p->completed ) sched_yield();
  while( p->xOp ){
    if( p->zErr && p->zErr!=p->zStaticErr ){
      sqlite3_free(p->zErr);
      p->zErr = 0;
    }
    (*p->xOp)(p);
    p->completed++;
    while( p->opnum<=p->completed ) sched_yield();
  }
  if( p->pStmt ){
    sqlite3_finalize(p->pStmt);
    p->pStmt = 0;
  }
  if( p->db ){
    sqlite3_close(p->db);
    p->db = 0;
  }
  if( p->zErr && p->zErr!=p->zStaticErr ){
    sqlite3_free(p->zErr);
    p->zErr = 0;
  }
  p->completed++;
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_thread_cleanup();
#endif
  return 0;
}

/*
** Get a thread ID which is an upper case letter.  Return the index.
** If the argument is not a valid thread ID put an error message in
** the interpreter and return -1.
*/
static int parse_thread_id(Tcl_Interp *interp, const char *zArg){
  if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){
    Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0);
    return -1;
  }
  return zArg[0] - 'A';
}

/*
** Usage:    thread_create NAME  FILENAME
**
** NAME should be an upper case letter.  Start the thread running with
** an open connection to the given database.
*/
static int tcl_thread_create(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  pthread_t x;
  int rc;

  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID FILENAME", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( threadset[i].busy ){
    Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0);
    return TCL_ERROR;
  }
  threadset[i].busy = 1;
  sqlite3_free(threadset[i].zFilename);
  threadset[i].zFilename = sqlite3DbStrDup(0, argv[2]);
  threadset[i].opnum = 1;
  threadset[i].completed = 0;
  rc = pthread_create(&x, 0, thread_main, &threadset[i]);
  if( rc ){
    Tcl_AppendResult(interp, "failed to create the thread", 0);
    sqlite3_free(threadset[i].zFilename);
    threadset[i].busy = 0;
    return TCL_ERROR;
  }
  pthread_detach(x);
  return TCL_OK;
}

/*
** Wait for a thread to reach its idle state.
*/
static void thread_wait(Thread *p){
  while( p->opnum>p->completed ) sched_yield();
}

/*
** Usage:  thread_wait ID
**
** Wait on thread ID to reach its idle state.
*/
static int tcl_thread_wait(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  return TCL_OK;
}

/*
** Stop a thread.
*/
static void stop_thread(Thread *p){
  thread_wait(p);
  p->xOp = 0;
  p->opnum++;
  thread_wait(p);
  sqlite3_free(p->zArg);
  p->zArg = 0;
  sqlite3_free(p->zFilename);
  p->zFilename = 0;
  p->busy = 0;
}

/*
** Usage:  thread_halt ID
**
** Cause a thread to shut itself down.  Wait for the shutdown to be
** completed.  If ID is "*" then stop all threads.
*/
static int tcl_thread_halt(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  if( argv[1][0]=='*' && argv[1][1]==0 ){
    for(i=0; i<N_THREAD; i++){
      if( threadset[i].busy ) stop_thread(&threadset[i]);
    }
  }else{
    i = parse_thread_id(interp, argv[1]);
    if( i<0 ) return TCL_ERROR;
    if( !threadset[i].busy ){
      Tcl_AppendResult(interp, "no such thread", 0);
      return TCL_ERROR;
    }
    stop_thread(&threadset[i]);
  }
  return TCL_OK;
}

/*
** Usage: thread_argc  ID
**
** Wait on the most recent thread_step to complete, then return the
** number of columns in the result set.
*/
static int tcl_thread_argc(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  char zBuf[100];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  sprintf(zBuf, "%d", threadset[i].argc);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage: thread_argv  ID   N
**
** Wait on the most recent thread_step to complete, then return the
** value of the N-th columns in the result set.
*/
static int tcl_thread_argv(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  int n;

  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID N", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR;
  thread_wait(&threadset[i]);
  if( n<0 || n>=threadset[i].argc ){
    Tcl_AppendResult(interp, "column number out of range", 0);
    return TCL_ERROR;
  }
  Tcl_AppendResult(interp, threadset[i].argv[n], 0);
  return TCL_OK;
}

/*
** Usage: thread_colname  ID   N
**
** Wait on the most recent thread_step to complete, then return the
** name of the N-th columns in the result set.
*/
static int tcl_thread_colname(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  int n;

  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID N", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR;
  thread_wait(&threadset[i]);
  if( n<0 || n>=threadset[i].argc ){
    Tcl_AppendResult(interp, "column number out of range", 0);
    return TCL_ERROR;
  }
  Tcl_AppendResult(interp, threadset[i].colv[n], 0);
  return TCL_OK;
}

/*
** Usage: thread_result  ID
**
** Wait on the most recent operation to complete, then return the
** result code from that operation.
*/
static int tcl_thread_result(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  const char *zName;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  switch( threadset[i].rc ){
    case SQLITE_OK:         zName = "SQLITE_OK";          break;
    case SQLITE_ERROR:      zName = "SQLITE_ERROR";       break;
    case SQLITE_PERM:       zName = "SQLITE_PERM";        break;
    case SQLITE_ABORT:      zName = "SQLITE_ABORT";       break;
    case SQLITE_BUSY:       zName = "SQLITE_BUSY";        break;
    case SQLITE_LOCKED:     zName = "SQLITE_LOCKED";      break;
    case SQLITE_NOMEM:      zName = "SQLITE_NOMEM";       break;
    case SQLITE_READONLY:   zName = "SQLITE_READONLY";    break;
    case SQLITE_INTERRUPT:  zName = "SQLITE_INTERRUPT";   break;
    case SQLITE_IOERR:      zName = "SQLITE_IOERR";       break;
    case SQLITE_CORRUPT:    zName = "SQLITE_CORRUPT";     break;
    case SQLITE_FULL:       zName = "SQLITE_FULL";        break;
    case SQLITE_CANTOPEN:   zName = "SQLITE_CANTOPEN";    break;
    case SQLITE_PROTOCOL:   zName = "SQLITE_PROTOCOL";    break;
    case SQLITE_EMPTY:      zName = "SQLITE_EMPTY";       break;
    case SQLITE_SCHEMA:     zName = "SQLITE_SCHEMA";      break;
    case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT";  break;
    case SQLITE_MISMATCH:   zName = "SQLITE_MISMATCH";    break;
    case SQLITE_MISUSE:     zName = "SQLITE_MISUSE";      break;
    case SQLITE_NOLFS:      zName = "SQLITE_NOLFS";       break;
    case SQLITE_AUTH:       zName = "SQLITE_AUTH";        break;
    case SQLITE_FORMAT:     zName = "SQLITE_FORMAT";      break;
    case SQLITE_RANGE:      zName = "SQLITE_RANGE";       break;
    case SQLITE_ROW:        zName = "SQLITE_ROW";         break;
    case SQLITE_DONE:       zName = "SQLITE_DONE";        break;
    default:                zName = "SQLITE_Unknown";     break;
  }
  Tcl_AppendResult(interp, zName, 0);
  return TCL_OK;
}

/*
** Usage: thread_error  ID
**
** Wait on the most recent operation to complete, then return the
** error string.
*/
static int tcl_thread_error(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  Tcl_AppendResult(interp, threadset[i].zErr, 0);
  return TCL_OK;
}

/*
** This procedure runs in the thread to compile an SQL statement.
*/
static void do_compile(Thread *p){
  if( p->db==0 ){
    p->zErr = p->zStaticErr = "no database is open";
    p->rc = SQLITE_ERROR;
    return;
  }
  if( p->pStmt ){
    sqlite3_finalize(p->pStmt);
    p->pStmt = 0;
  }
  p->rc = sqlite3_prepare(p->db, p->zArg, -1, &p->pStmt, 0);
}

/*
** Usage: thread_compile ID SQL
**
** Compile a new virtual machine.
*/
static int tcl_thread_compile(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID SQL", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_compile;
  sqlite3_free(threadset[i].zArg);
  threadset[i].zArg = sqlite3DbStrDup(0, argv[2]);
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to step the virtual machine.
*/
static void do_step(Thread *p){
  int i;
  if( p->pStmt==0 ){
    p->zErr = p->zStaticErr = "no virtual machine available";
    p->rc = SQLITE_ERROR;
    return;
  }
  p->rc = sqlite3_step(p->pStmt);
  if( p->rc==SQLITE_ROW ){
    p->argc = sqlite3_column_count(p->pStmt);
    for(i=0; i<sqlite3_data_count(p->pStmt); i++){
      p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i);
    }
    for(i=0; i<p->argc; i++){
      p->colv[i] = sqlite3_column_name(p->pStmt, i);
    }
  }
}

/*
** Usage: thread_step ID
**
** Advance the virtual machine by one step
*/
static int tcl_thread_step(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " IDL", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_step;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to finalize a virtual machine.
*/
static void do_finalize(Thread *p){
  if( p->pStmt==0 ){
    p->zErr = p->zStaticErr = "no virtual machine available";
    p->rc = SQLITE_ERROR;
    return;
  }
  p->rc = sqlite3_finalize(p->pStmt);
  p->pStmt = 0;
}

/*
** Usage: thread_finalize ID
**
** Finalize the virtual machine.
*/
static int tcl_thread_finalize(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " IDL", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_finalize;
  sqlite3_free(threadset[i].zArg);
  threadset[i].zArg = 0;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** Usage: thread_swap ID ID
**
** Interchange the sqlite* pointer between two threads.
*/
static int tcl_thread_swap(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i, j;
  sqlite3 *temp;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID1 ID2", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  j = parse_thread_id(interp, argv[2]);
  if( j<0 ) return TCL_ERROR;
  if( !threadset[j].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[j]);
  temp = threadset[i].db;
  threadset[i].db = threadset[j].db;
  threadset[j].db = temp;
  return TCL_OK;
}

/*
** Usage: thread_db_get ID
**
** Return the database connection pointer for the given thread.  Then
** remove the pointer from the thread itself.  Afterwards, the thread
** can be stopped and the connection can be used by the main thread.
*/
static int tcl_thread_db_get(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  char zBuf[100];
  extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  sqlite3TestMakePointerStr(interp, zBuf, threadset[i].db);
  threadset[i].db = 0;
  Tcl_AppendResult(interp, zBuf, (char*)0);
  return TCL_OK;
}

/*
** Usage: thread_db_put ID DB
**
*/
static int tcl_thread_db_put(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
  extern void *sqlite3TestTextToPtr(const char *);
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID DB", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  assert( !threadset[i].db );
  threadset[i].db = (sqlite3*)sqlite3TestTextToPtr(argv[2]);
  return TCL_OK;
}

/*
** Usage: thread_stmt_get ID
**
** Return the database stmt pointer for the given thread.  Then
** remove the pointer from the thread itself. 
*/
static int tcl_thread_stmt_get(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  char zBuf[100];
  extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  sqlite3TestMakePointerStr(interp, zBuf, threadset[i].pStmt);
  threadset[i].pStmt = 0;
  Tcl_AppendResult(interp, zBuf, (char*)0);
  return TCL_OK;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest4_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_CmdProc *xProc;
  } aCmd[] = {
     { "thread_create",     (Tcl_CmdProc*)tcl_thread_create     },
     { "thread_wait",       (Tcl_CmdProc*)tcl_thread_wait       },
     { "thread_halt",       (Tcl_CmdProc*)tcl_thread_halt       },
     { "thread_argc",       (Tcl_CmdProc*)tcl_thread_argc       },
     { "thread_argv",       (Tcl_CmdProc*)tcl_thread_argv       },
     { "thread_colname",    (Tcl_CmdProc*)tcl_thread_colname    },
     { "thread_result",     (Tcl_CmdProc*)tcl_thread_result     },
     { "thread_error",      (Tcl_CmdProc*)tcl_thread_error      },
     { "thread_compile",    (Tcl_CmdProc*)tcl_thread_compile    },
     { "thread_step",       (Tcl_CmdProc*)tcl_thread_step       },
     { "thread_finalize",   (Tcl_CmdProc*)tcl_thread_finalize   },
     { "thread_swap",       (Tcl_CmdProc*)tcl_thread_swap       },
     { "thread_db_get",     (Tcl_CmdProc*)tcl_thread_db_get     },
     { "thread_db_put",     (Tcl_CmdProc*)tcl_thread_db_put     },
     { "thread_stmt_get",   (Tcl_CmdProc*)tcl_thread_stmt_get   },
  };
  int i;

  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }
  return TCL_OK;
}
#else
int Sqlitetest4_Init(Tcl_Interp *interp){ return TCL_OK; }
#endif /* SQLITE_OS_UNIX */

Added src/test5.c.

























































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the utf.c module in SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library. Specifically, the code in this file
** is used for testing the SQLite routines for converting between
** the various supported unicode encodings.
**
** $Id: test5.c,v 1.22 2008/08/12 15:04:59 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "vdbeInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
** The first argument is a TCL UTF-8 string. Return the byte array
** object with the encoded representation of the string, including
** the NULL terminator.
*/
static int binarize(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int len;
  char *bytes;
  Tcl_Obj *pRet;
  assert(objc==2);

  bytes = Tcl_GetStringFromObj(objv[1], &len);
  pRet = Tcl_NewByteArrayObj((u8*)bytes, len+1);
  Tcl_SetObjResult(interp, pRet);
  return TCL_OK;
}

/*
** Usage: test_value_overhead <repeat-count> <do-calls>.
**
** This routine is used to test the overhead of calls to
** sqlite3_value_text(), on a value that contains a UTF-8 string. The idea
** is to figure out whether or not it is a problem to use sqlite3_value
** structures with collation sequence functions.
**
** If <do-calls> is 0, then the calls to sqlite3_value_text() are not
** actually made.
*/
static int test_value_overhead(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int do_calls;
  int repeat_count;
  int i;
  Mem val;
  const char *zVal;

  if( objc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " <repeat-count> <do-calls>", 0);
    return TCL_ERROR;
  }

  if( Tcl_GetIntFromObj(interp, objv[1], &repeat_count) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &do_calls) ) return TCL_ERROR;

  val.flags = MEM_Str|MEM_Term|MEM_Static;
  val.z = "hello world";
  val.type = SQLITE_TEXT;
  val.enc = SQLITE_UTF8;

  for(i=0; i<repeat_count; i++){
    if( do_calls ){
      zVal = (char*)sqlite3_value_text(&val);
    }
  }

  return TCL_OK;
}

static u8 name_to_enc(Tcl_Interp *interp, Tcl_Obj *pObj){
  struct EncName {
    char *zName;
    u8 enc;
  } encnames[] = {
    { "UTF8", SQLITE_UTF8 },
    { "UTF16LE", SQLITE_UTF16LE },
    { "UTF16BE", SQLITE_UTF16BE },
    { "UTF16", SQLITE_UTF16 },
    { 0, 0 }
  };
  struct EncName *pEnc;
  char *z = Tcl_GetString(pObj);
  for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
    if( 0==sqlite3StrICmp(z, pEnc->zName) ){
      break;
    }
  }
  if( !pEnc->enc ){
    Tcl_AppendResult(interp, "No such encoding: ", z, 0);
  }
  if( pEnc->enc==SQLITE_UTF16 ){
    return SQLITE_UTF16NATIVE;
  }
  return pEnc->enc;
}

/*
** Usage:   test_translate <string/blob> <from enc> <to enc> ?<transient>?
**
*/
static int test_translate(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  u8 enc_from;
  u8 enc_to;
  sqlite3_value *pVal;

  char *z;
  int len;
  void (*xDel)(void *p) = SQLITE_STATIC;

  if( objc!=4 && objc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), 
        " <string/blob> <from enc> <to enc>", 0
    );
    return TCL_ERROR;
  }
  if( objc==5 ){
    xDel = sqlite3_free;
  }

  enc_from = name_to_enc(interp, objv[2]);
  if( !enc_from ) return TCL_ERROR;
  enc_to = name_to_enc(interp, objv[3]);
  if( !enc_to ) return TCL_ERROR;

  pVal = sqlite3ValueNew(0);

  if( enc_from==SQLITE_UTF8 ){
    z = Tcl_GetString(objv[1]);
    if( objc==5 ){
      z = sqlite3DbStrDup(0, z);
    }
    sqlite3ValueSetStr(pVal, -1, z, enc_from, xDel);
  }else{
    z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len);
    if( objc==5 ){
      char *zTmp = z;
      z = sqlite3_malloc(len);
      memcpy(z, zTmp, len);
    }
    sqlite3ValueSetStr(pVal, -1, z, enc_from, xDel);
  }

  z = (char *)sqlite3ValueText(pVal, enc_to);
  len = sqlite3ValueBytes(pVal, enc_to) + (enc_to==SQLITE_UTF8?1:2);
  Tcl_SetObjResult(interp, Tcl_NewByteArrayObj((u8*)z, len));

  sqlite3ValueFree(pVal);

  return TCL_OK;
}

/*
** Usage: translate_selftest
**
** Call sqlite3UtfSelfTest() to run the internal tests for unicode
** translation. If there is a problem an assert() will fail.
**/
void sqlite3UtfSelfTest(void);
static int test_translate_selftest(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3UtfSelfTest();
#endif
  return SQLITE_OK;
}


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest5_Init(Tcl_Interp *interp){
  static struct {
    char *zName;
    Tcl_ObjCmdProc *xProc;
  } aCmd[] = {
    { "binarize",                (Tcl_ObjCmdProc*)binarize },
    { "test_value_overhead",     (Tcl_ObjCmdProc*)test_value_overhead },
    { "test_translate",          (Tcl_ObjCmdProc*)test_translate     },
    { "translate_selftest",      (Tcl_ObjCmdProc*)test_translate_selftest},
  };
  int i;
  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }
  return SQLITE_OK;
}

Added src/test6.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that modified the OS layer in order to simulate
** the effect on the database file of an OS crash or power failure.  This
** is used to test the ability of SQLite to recover from those situations.
**
** $Id: test6.c,v 1.43 2009/02/11 14:27:04 danielk1977 Exp $
*/
#if SQLITE_TEST          /* This file is used for testing only */
#include "sqliteInt.h"
#include "tcl.h"

#ifndef SQLITE_OMIT_DISKIO  /* This file is a no-op if disk I/O is disabled */

/* #define TRACE_CRASHTEST */

typedef struct CrashFile CrashFile;
typedef struct CrashGlobal CrashGlobal;
typedef struct WriteBuffer WriteBuffer;

/*
** Method:
**
**   This layer is implemented as a wrapper around the "real" 
**   sqlite3_file object for the host system. Each time data is 
**   written to the file object, instead of being written to the
**   underlying file, the write operation is stored in an in-memory 
**   structure (type WriteBuffer). This structure is placed at the
**   end of a global ordered list (the write-list).
**
**   When data is read from a file object, the requested region is
**   first retrieved from the real file. The write-list is then 
**   traversed and data copied from any overlapping WriteBuffer 
**   structures to the output buffer. i.e. a read() operation following
**   one or more write() operations works as expected, even if no
**   data has actually been written out to the real file.
**
**   When a fsync() operation is performed, an operating system crash 
**   may be simulated, in which case exit(-1) is called (the call to 
**   xSync() never returns). Whether or not a crash is simulated,
**   the data associated with a subset of the WriteBuffer structures 
**   stored in the write-list is written to the real underlying files 
**   and the entries removed from the write-list. If a crash is simulated,
**   a subset of the buffers may be corrupted before the data is written.
**
**   The exact subset of the write-list written and/or corrupted is
**   determined by the simulated device characteristics and sector-size.
**
** "Normal" mode:
**
**   Normal mode is used when the simulated device has none of the
**   SQLITE_IOCAP_XXX flags set.
**
**   In normal mode, if the fsync() is not a simulated crash, the 
**   write-list is traversed from beginning to end. Each WriteBuffer
**   structure associated with the file handle used to call xSync()
**   is written to the real file and removed from the write-list.
**
**   If a crash is simulated, one of the following takes place for 
**   each WriteBuffer in the write-list, regardless of which 
**   file-handle it is associated with:
**
**     1. The buffer is correctly written to the file, just as if
**        a crash were not being simulated.
**
**     2. Nothing is done.
**
**     3. Garbage data is written to all sectors of the file that 
**        overlap the region specified by the WriteBuffer. Or garbage
**        data is written to some contiguous section within the 
**        overlapped sectors.
**
** Device Characteristic flag handling:
**
**   If the IOCAP_ATOMIC flag is set, then option (3) above is 
**   never selected.
**
**   If the IOCAP_ATOMIC512 flag is set, and the WriteBuffer represents
**   an aligned write() of an integer number of 512 byte regions, then
**   option (3) above is never selected. Instead, each 512 byte region
**   is either correctly written or left completely untouched. Similar
**   logic governs the behaviour if any of the other ATOMICXXX flags
**   is set.
**
**   If either the IOCAP_SAFEAPPEND or IOCAP_SEQUENTIAL flags are set
**   and a crash is being simulated, then an entry of the write-list is
**   selected at random. Everything in the list after the selected entry 
**   is discarded before processing begins.
**
**   If IOCAP_SEQUENTIAL is set and a crash is being simulated, option 
**   (1) is selected for all write-list entries except the last. If a 
**   crash is not being simulated, then all entries in the write-list
**   that occur before at least one write() on the file-handle specified
**   as part of the xSync() are written to their associated real files.
**
**   If IOCAP_SAFEAPPEND is set and the first byte written by the write()
**   operation is one byte past the current end of the file, then option
**   (1) is always selected.
*/

/*
** Each write operation in the write-list is represented by an instance
** of the following structure.
**
** If zBuf is 0, then this structure represents a call to xTruncate(), 
** not xWrite(). In that case, iOffset is the size that the file is
** truncated to.
*/
struct WriteBuffer {
  i64 iOffset;                 /* Byte offset of the start of this write() */
  int nBuf;                    /* Number of bytes written */
  u8 *zBuf;                    /* Pointer to copy of written data */
  CrashFile *pFile;            /* File this write() applies to */

  WriteBuffer *pNext;          /* Next in CrashGlobal.pWriteList */
};

struct CrashFile {
  const sqlite3_io_methods *pMethod;   /* Must be first */
  sqlite3_file *pRealFile;             /* Underlying "real" file handle */
  char *zName;
  int flags;                           /* Flags the file was opened with */

  /* Cache of the entire file. This is used to speed up OsRead() and 
  ** OsFileSize() calls. Although both could be done by traversing the
  ** write-list, in practice this is impractically slow.
  */
  int iSize;                           /* Size of file in bytes */
  int nData;                           /* Size of buffer allocated at zData */
  u8 *zData;                           /* Buffer containing file contents */
};

struct CrashGlobal {
  WriteBuffer *pWriteList;     /* Head of write-list */
  WriteBuffer *pWriteListEnd;  /* End of write-list */

  int iSectorSize;             /* Value of simulated sector size */
  int iDeviceCharacteristics;  /* Value of simulated device characteristics */

  int iCrash;                  /* Crash on the iCrash'th call to xSync() */
  char zCrashFile[500];        /* Crash during an xSync() on this file */ 
};

static CrashGlobal g = {0, 0, SQLITE_DEFAULT_SECTOR_SIZE, 0, 0};

/*
** Set this global variable to 1 to enable crash testing.
*/
static int sqlite3CrashTestEnable = 0;

static void *crash_malloc(int nByte){
  return (void *)Tcl_Alloc((size_t)nByte);
}
static void crash_free(void *p){
  Tcl_Free(p);
}
static void *crash_realloc(void *p, int n){
  return (void *)Tcl_Realloc(p, (size_t)n);
}

/*
** Wrapper around the sqlite3OsWrite() function that avoids writing to the
** 512 byte block begining at offset PENDING_BYTE.
*/
static int writeDbFile(CrashFile *p, u8 *z, i64 iAmt, i64 iOff){
  int rc;
  int iSkip = 0;
  if( iOff==PENDING_BYTE && (p->flags&SQLITE_OPEN_MAIN_DB) ){
    iSkip = 512;
  }
  if( (iAmt-iSkip)>0 ){
    rc = sqlite3OsWrite(p->pRealFile, &z[iSkip], iAmt-iSkip, iOff+iSkip);
  }
  return rc;
}

/*
** Flush the write-list as if xSync() had been called on file handle
** pFile. If isCrash is true, simulate a crash.
*/
static int writeListSync(CrashFile *pFile, int isCrash){
  int rc = SQLITE_OK;
  int iDc = g.iDeviceCharacteristics;

  WriteBuffer *pWrite;
  WriteBuffer **ppPtr;

  /* If this is not a crash simulation, set pFinal to point to the 
  ** last element of the write-list that is associated with file handle
  ** pFile.
  **
  ** If this is a crash simulation, set pFinal to an arbitrarily selected
  ** element of the write-list.
  */
  WriteBuffer *pFinal = 0;
  if( !isCrash ){
    for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext){
      if( pWrite->pFile==pFile ){
        pFinal = pWrite;
      }
    }
  }else if( iDc&(SQLITE_IOCAP_SEQUENTIAL|SQLITE_IOCAP_SAFE_APPEND) ){
    int nWrite = 0;
    int iFinal;
    for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext) nWrite++;
    sqlite3_randomness(sizeof(int), &iFinal);
    iFinal = ((iFinal<0)?-1*iFinal:iFinal)%nWrite;
    for(pWrite=g.pWriteList; iFinal>0; pWrite=pWrite->pNext) iFinal--;
    pFinal = pWrite;
  }

#ifdef TRACE_CRASHTEST
  printf("Sync %s (is %s crash)\n", pFile->zName, (isCrash?"a":"not a"));
#endif

  ppPtr = &g.pWriteList;
  for(pWrite=*ppPtr; rc==SQLITE_OK && pWrite; pWrite=*ppPtr){
    sqlite3_file *pRealFile = pWrite->pFile->pRealFile;

    /* (eAction==1)      -> write block out normally,
    ** (eAction==2)      -> do nothing,
    ** (eAction==3)      -> trash sectors.
    */
    int eAction = 0;
    if( !isCrash ){
      eAction = 2;
      if( (pWrite->pFile==pFile || iDc&SQLITE_IOCAP_SEQUENTIAL) ){
        eAction = 1;
      }
    }else{
      char random;
      sqlite3_randomness(1, &random);

      /* Do not select option 3 (sector trashing) if the IOCAP_ATOMIC flag 
      ** is set or this is an OsTruncate(), not an Oswrite().
      */
      if( (iDc&SQLITE_IOCAP_ATOMIC) || (pWrite->zBuf==0) ){
        random &= 0x01;
      }

      /* If IOCAP_SEQUENTIAL is set and this is not the final entry
      ** in the truncated write-list, always select option 1 (write
      ** out correctly).
      */
      if( (iDc&SQLITE_IOCAP_SEQUENTIAL && pWrite!=pFinal) ){
        random = 0;
      }

      /* If IOCAP_SAFE_APPEND is set and this OsWrite() operation is
      ** an append (first byte of the written region is 1 byte past the
      ** current EOF), always select option 1 (write out correctly).
      */
      if( iDc&SQLITE_IOCAP_SAFE_APPEND && pWrite->zBuf ){
        i64 iSize;
        sqlite3OsFileSize(pRealFile, &iSize);
        if( iSize==pWrite->iOffset ){
          random = 0;
        }
      }

      if( (random&0x06)==0x06 ){
        eAction = 3;
      }else{
        eAction = ((random&0x01)?2:1);
      }
    }

    switch( eAction ){
      case 1: {               /* Write out correctly */
        if( pWrite->zBuf ){
          rc = writeDbFile(
              pWrite->pFile, pWrite->zBuf, pWrite->nBuf, pWrite->iOffset
          );
        }else{
          rc = sqlite3OsTruncate(pRealFile, pWrite->iOffset);
        }
        *ppPtr = pWrite->pNext;
#ifdef TRACE_CRASHTEST
        if( isCrash ){
          printf("Writing %d bytes @ %d (%s)\n", 
            pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName
          );
        }
#endif
        crash_free(pWrite);
        break;
      }
      case 2: {               /* Do nothing */
        ppPtr = &pWrite->pNext;
#ifdef TRACE_CRASHTEST
        if( isCrash ){
          printf("Omiting %d bytes @ %d (%s)\n", 
            pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName
          );
        }
#endif
        break;
      }
      case 3: {               /* Trash sectors */
        u8 *zGarbage;
        int iFirst = (pWrite->iOffset/g.iSectorSize);
        int iLast = (pWrite->iOffset+pWrite->nBuf-1)/g.iSectorSize;

        assert(pWrite->zBuf);

#ifdef TRACE_CRASHTEST
        printf("Trashing %d sectors @ sector %d (%s)\n", 
            1+iLast-iFirst, iFirst, pWrite->pFile->zName
        );
#endif

        zGarbage = crash_malloc(g.iSectorSize);
        if( zGarbage ){
          sqlite3_int64 i;
          for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
            sqlite3_randomness(g.iSectorSize, zGarbage); 
            rc = writeDbFile(
              pWrite->pFile, zGarbage, g.iSectorSize, i*g.iSectorSize
            );
          }
          crash_free(zGarbage);
        }else{
          rc = SQLITE_NOMEM;
        }

        ppPtr = &pWrite->pNext;
        break;
      }

      default:
        assert(!"Cannot happen");
    }

    if( pWrite==pFinal ) break;
  }

  if( rc==SQLITE_OK && isCrash ){
    exit(-1);
  }

  for(pWrite=g.pWriteList; pWrite && pWrite->pNext; pWrite=pWrite->pNext);
  g.pWriteListEnd = pWrite;

  return rc;
}

/*
** Add an entry to the end of the write-list.
*/
static int writeListAppend(
  sqlite3_file *pFile,
  sqlite3_int64 iOffset,
  const u8 *zBuf,
  int nBuf
){
  WriteBuffer *pNew;

  assert((zBuf && nBuf) || (!nBuf && !zBuf));

  pNew = (WriteBuffer *)crash_malloc(sizeof(WriteBuffer) + nBuf);
  if( pNew==0 ){
    fprintf(stderr, "out of memory in the crash simulator\n");
  }
  memset(pNew, 0, sizeof(WriteBuffer)+nBuf);
  pNew->iOffset = iOffset;
  pNew->nBuf = nBuf;
  pNew->pFile = (CrashFile *)pFile;
  if( zBuf ){
    pNew->zBuf = (u8 *)&pNew[1];
    memcpy(pNew->zBuf, zBuf, nBuf);
  }

  if( g.pWriteList ){
    assert(g.pWriteListEnd);
    g.pWriteListEnd->pNext = pNew;
  }else{
    g.pWriteList = pNew;
  }
  g.pWriteListEnd = pNew;
  
  return SQLITE_OK;
}

/*
** Close a crash-file.
*/
static int cfClose(sqlite3_file *pFile){
  CrashFile *pCrash = (CrashFile *)pFile;
  writeListSync(pCrash, 0);
  sqlite3OsClose(pCrash->pRealFile);
  return SQLITE_OK;
}

/*
** Read data from a crash-file.
*/
static int cfRead(
  sqlite3_file *pFile, 
  void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  CrashFile *pCrash = (CrashFile *)pFile;

  /* Check the file-size to see if this is a short-read */
  if( pCrash->iSize<(iOfst+iAmt) ){
    return SQLITE_IOERR_SHORT_READ;
  }

  memcpy(zBuf, &pCrash->zData[iOfst], iAmt);
  return SQLITE_OK;
}

/*
** Write data to a crash-file.
*/
static int cfWrite(
  sqlite3_file *pFile, 
  const void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  CrashFile *pCrash = (CrashFile *)pFile;
  if( iAmt+iOfst>pCrash->iSize ){
    pCrash->iSize = iAmt+iOfst;
  }
  while( pCrash->iSize>pCrash->nData ){
    u8 *zNew;
    int nNew = (pCrash->nData*2) + 4096;
    zNew = crash_realloc(pCrash->zData, nNew);
    if( !zNew ){
      return SQLITE_NOMEM;
    }
    memset(&zNew[pCrash->nData], 0, nNew-pCrash->nData);
    pCrash->nData = nNew;
    pCrash->zData = zNew;
  }
  memcpy(&pCrash->zData[iOfst], zBuf, iAmt);
  return writeListAppend(pFile, iOfst, zBuf, iAmt);
}

/*
** Truncate a crash-file.
*/
static int cfTruncate(sqlite3_file *pFile, sqlite_int64 size){
  CrashFile *pCrash = (CrashFile *)pFile;
  assert(size>=0);
  if( pCrash->iSize>size ){
    pCrash->iSize = size;
  }
  return writeListAppend(pFile, size, 0, 0);
}

/*
** Sync a crash-file.
*/
static int cfSync(sqlite3_file *pFile, int flags){
  CrashFile *pCrash = (CrashFile *)pFile;
  int isCrash = 0;

  const char *zName = pCrash->zName;
  const char *zCrashFile = g.zCrashFile;
  int nName = strlen(zName);
  int nCrashFile = strlen(zCrashFile);

  if( nCrashFile>0 && zCrashFile[nCrashFile-1]=='*' ){
    nCrashFile--;
    if( nName>nCrashFile ) nName = nCrashFile;
  }

  if( nName==nCrashFile && 0==memcmp(zName, zCrashFile, nName) ){
    if( (--g.iCrash)==0 ) isCrash = 1;
  }

  return writeListSync(pCrash, isCrash);
}

/*
** Return the current file-size of the crash-file.
*/
static int cfFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  CrashFile *pCrash = (CrashFile *)pFile;
  *pSize = (i64)pCrash->iSize;
  return SQLITE_OK;
}

/*
** Calls related to file-locks are passed on to the real file handle.
*/
static int cfLock(sqlite3_file *pFile, int eLock){
  return sqlite3OsLock(((CrashFile *)pFile)->pRealFile, eLock);
}
static int cfUnlock(sqlite3_file *pFile, int eLock){
  return sqlite3OsUnlock(((CrashFile *)pFile)->pRealFile, eLock);
}
static int cfCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  return sqlite3OsCheckReservedLock(((CrashFile *)pFile)->pRealFile, pResOut);
}
static int cfFileControl(sqlite3_file *pFile, int op, void *pArg){
  return sqlite3OsFileControl(((CrashFile *)pFile)->pRealFile, op, pArg);
}

/*
** The xSectorSize() and xDeviceCharacteristics() functions return
** the global values configured by the [sqlite_crashparams] tcl
*  interface.
*/
static int cfSectorSize(sqlite3_file *pFile){
  return g.iSectorSize;
}
static int cfDeviceCharacteristics(sqlite3_file *pFile){
  return g.iDeviceCharacteristics;
}

static const sqlite3_io_methods CrashFileVtab = {
  1,                            /* iVersion */
  cfClose,                      /* xClose */
  cfRead,                       /* xRead */
  cfWrite,                      /* xWrite */
  cfTruncate,                   /* xTruncate */
  cfSync,                       /* xSync */
  cfFileSize,                   /* xFileSize */
  cfLock,                       /* xLock */
  cfUnlock,                     /* xUnlock */
  cfCheckReservedLock,          /* xCheckReservedLock */
  cfFileControl,                /* xFileControl */
  cfSectorSize,                 /* xSectorSize */
  cfDeviceCharacteristics       /* xDeviceCharacteristics */
};

/*
** Application data for the crash VFS
*/
struct crashAppData {
  sqlite3_vfs *pOrig;                   /* Wrapped vfs structure */
};

/*
** Open a crash-file file handle.
**
** The caller will have allocated pVfs->szOsFile bytes of space
** at pFile. This file uses this space for the CrashFile structure
** and allocates space for the "real" file structure using 
** sqlite3_malloc(). The assumption here is (pVfs->szOsFile) is
** equal or greater than sizeof(CrashFile).
*/
static int cfOpen(
  sqlite3_vfs *pCfVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  int rc;
  CrashFile *pWrapper = (CrashFile *)pFile;
  sqlite3_file *pReal = (sqlite3_file*)&pWrapper[1];

  memset(pWrapper, 0, sizeof(CrashFile));
  rc = sqlite3OsOpen(pVfs, zName, pReal, flags, pOutFlags);

  if( rc==SQLITE_OK ){
    i64 iSize;
    pWrapper->pMethod = &CrashFileVtab;
    pWrapper->zName = (char *)zName;
    pWrapper->pRealFile = pReal;
    rc = sqlite3OsFileSize(pReal, &iSize);
    pWrapper->iSize = (int)iSize;
    pWrapper->flags = flags;
  }
  if( rc==SQLITE_OK ){
    pWrapper->nData = (4096 + pWrapper->iSize);
    pWrapper->zData = crash_malloc(pWrapper->nData);
    if( pWrapper->zData ){
      /* os_unix.c contains an assert() that fails if the caller attempts
      ** to read data from the 512-byte locking region of a file opened
      ** with the SQLITE_OPEN_MAIN_DB flag. This region of a database file
      ** never contains valid data anyhow. So avoid doing such a read here.
      */
      const int isDb = (flags&SQLITE_OPEN_MAIN_DB);
      i64 iChunk = pWrapper->iSize;
      if( iChunk>PENDING_BYTE && isDb ){
        iChunk = PENDING_BYTE;
      }
      memset(pWrapper->zData, 0, pWrapper->nData);
      rc = sqlite3OsRead(pReal, pWrapper->zData, iChunk, 0); 
      if( SQLITE_OK==rc && pWrapper->iSize>(PENDING_BYTE+512) && isDb ){
        i64 iOff = PENDING_BYTE+512;
        iChunk = pWrapper->iSize - iOff;
        rc = sqlite3OsRead(pReal, &pWrapper->zData[iOff], iChunk, iOff);
      }
    }else{
      rc = SQLITE_NOMEM;
    }
  }
  if( rc!=SQLITE_OK && pWrapper->pMethod ){
    sqlite3OsClose(pFile);
  }
  return rc;
}

static int cfDelete(sqlite3_vfs *pCfVfs, const char *zPath, int dirSync){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xDelete(pVfs, zPath, dirSync);
}
static int cfAccess(
  sqlite3_vfs *pCfVfs, 
  const char *zPath, 
  int flags, 
  int *pResOut
){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
}
static int cfFullPathname(
  sqlite3_vfs *pCfVfs, 
  const char *zPath, 
  int nPathOut,
  char *zPathOut
){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
}
static void *cfDlOpen(sqlite3_vfs *pCfVfs, const char *zPath){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xDlOpen(pVfs, zPath);
}
static void cfDlError(sqlite3_vfs *pCfVfs, int nByte, char *zErrMsg){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  pVfs->xDlError(pVfs, nByte, zErrMsg);
}
static void (*cfDlSym(sqlite3_vfs *pCfVfs, void *pH, const char *zSym))(void){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xDlSym(pVfs, pH, zSym);
}
static void cfDlClose(sqlite3_vfs *pCfVfs, void *pHandle){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  pVfs->xDlClose(pVfs, pHandle);
}
static int cfRandomness(sqlite3_vfs *pCfVfs, int nByte, char *zBufOut){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xRandomness(pVfs, nByte, zBufOut);
}
static int cfSleep(sqlite3_vfs *pCfVfs, int nMicro){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xSleep(pVfs, nMicro);
}
static int cfCurrentTime(sqlite3_vfs *pCfVfs, double *pTimeOut){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  return pVfs->xCurrentTime(pVfs, pTimeOut);
}

static int processDevSymArgs(
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[],
  int *piDeviceChar,
  int *piSectorSize
){
  struct DeviceFlag {
    char *zName;
    int iValue;
  } aFlag[] = {
    { "atomic",      SQLITE_IOCAP_ATOMIC      },
    { "atomic512",   SQLITE_IOCAP_ATOMIC512   },
    { "atomic1k",    SQLITE_IOCAP_ATOMIC1K    },
    { "atomic2k",    SQLITE_IOCAP_ATOMIC2K    },
    { "atomic4k",    SQLITE_IOCAP_ATOMIC4K    },
    { "atomic8k",    SQLITE_IOCAP_ATOMIC8K    },
    { "atomic16k",   SQLITE_IOCAP_ATOMIC16K   },
    { "atomic32k",   SQLITE_IOCAP_ATOMIC32K   },
    { "atomic64k",   SQLITE_IOCAP_ATOMIC64K   },
    { "sequential",  SQLITE_IOCAP_SEQUENTIAL  },
    { "safe_append", SQLITE_IOCAP_SAFE_APPEND },
    { 0, 0 }
  };

  int i;
  int iDc = 0;
  int iSectorSize = 0;
  int setSectorsize = 0;
  int setDeviceChar = 0;

  for(i=0; i<objc; i+=2){
    int nOpt;
    char *zOpt = Tcl_GetStringFromObj(objv[i], &nOpt);

    if( (nOpt>11 || nOpt<2 || strncmp("-sectorsize", zOpt, nOpt)) 
     && (nOpt>16 || nOpt<2 || strncmp("-characteristics", zOpt, nOpt))
    ){
      Tcl_AppendResult(interp, 
        "Bad option: \"", zOpt, 
        "\" - must be \"-characteristics\" or \"-sectorsize\"", 0
      );
      return TCL_ERROR;
    }
    if( i==objc-1 ){
      Tcl_AppendResult(interp, "Option requires an argument: \"", zOpt, "\"",0);
      return TCL_ERROR;
    }

    if( zOpt[1]=='s' ){
      if( Tcl_GetIntFromObj(interp, objv[i+1], &iSectorSize) ){
        return TCL_ERROR;
      }
      setSectorsize = 1;
    }else{
      int j;
      Tcl_Obj **apObj;
      int nObj;
      if( Tcl_ListObjGetElements(interp, objv[i+1], &nObj, &apObj) ){
        return TCL_ERROR;
      }
      for(j=0; j<nObj; j++){
        int rc;
        int iChoice;
        Tcl_Obj *pFlag = Tcl_DuplicateObj(apObj[j]);
        Tcl_IncrRefCount(pFlag);
        Tcl_UtfToLower(Tcl_GetString(pFlag));
 
        rc = Tcl_GetIndexFromObjStruct(
            interp, pFlag, aFlag, sizeof(aFlag[0]), "no such flag", 0, &iChoice
        );
        Tcl_DecrRefCount(pFlag);
        if( rc ){
          return TCL_ERROR;
        }

        iDc |= aFlag[iChoice].iValue;
      }
      setDeviceChar = 1;
    }
  }

  if( setDeviceChar ){
    *piDeviceChar = iDc;
  }
  if( setSectorsize ){
    *piSectorSize = iSectorSize;
  }

  return TCL_OK;
}

/*
** tclcmd:   sqlite_crash_enable ENABLE
**
** Parameter ENABLE must be a boolean value. If true, then the "crash"
** vfs is added to the system. If false, it is removed.
*/
static int crashEnableCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int isEnable;
  static sqlite3_vfs crashVfs = {
    1,                  /* iVersion */
    0,                  /* szOsFile */
    0,                  /* mxPathname */
    0,                  /* pNext */
    "crash",            /* zName */
    0,                  /* pAppData */
  
    cfOpen,               /* xOpen */
    cfDelete,             /* xDelete */
    cfAccess,             /* xAccess */
    cfFullPathname,       /* xFullPathname */
    cfDlOpen,             /* xDlOpen */
    cfDlError,            /* xDlError */
    cfDlSym,              /* xDlSym */
    cfDlClose,            /* xDlClose */
    cfRandomness,         /* xRandomness */
    cfSleep,              /* xSleep */
    cfCurrentTime         /* xCurrentTime */
  };

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "ENABLE");
    return TCL_ERROR;
  }

  if( Tcl_GetBooleanFromObj(interp, objv[1], &isEnable) ){
    return TCL_ERROR;
  }

  if( (isEnable && crashVfs.pAppData) || (!isEnable && !crashVfs.pAppData) ){
    return TCL_OK;
  }

  if( crashVfs.pAppData==0 ){
    sqlite3_vfs *pOriginalVfs = sqlite3_vfs_find(0);
    crashVfs.mxPathname = pOriginalVfs->mxPathname;
    crashVfs.pAppData = (void *)pOriginalVfs;
    crashVfs.szOsFile = sizeof(CrashFile) + pOriginalVfs->szOsFile;
    sqlite3_vfs_register(&crashVfs, 0);
  }else{
    crashVfs.pAppData = 0;
    sqlite3_vfs_unregister(&crashVfs);
  }

  return TCL_OK;
}

/*
** tclcmd:   sqlite_crashparams ?OPTIONS? DELAY CRASHFILE
**
** This procedure implements a TCL command that enables crash testing
** in testfixture.  Once enabled, crash testing cannot be disabled.
**
** Available options are "-characteristics" and "-sectorsize". Both require
** an argument. For -sectorsize, this is the simulated sector size in
** bytes. For -characteristics, the argument must be a list of io-capability
** flags to simulate. Valid flags are "atomic", "atomic512", "atomic1K",
** "atomic2K", "atomic4K", "atomic8K", "atomic16K", "atomic32K", 
** "atomic64K", "sequential" and "safe_append".
**
** Example:
**
**   sqlite_crashparams -sect 1024 -char {atomic sequential} ./test.db 1
**
*/
static int crashParamsObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int iDelay;
  const char *zCrashFile;
  int nCrashFile, iDc, iSectorSize;

  iDc = -1;
  iSectorSize = -1;

  if( objc<3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "?OPTIONS? DELAY CRASHFILE");
    goto error;
  }

  zCrashFile = Tcl_GetStringFromObj(objv[objc-1], &nCrashFile);
  if( nCrashFile>=sizeof(g.zCrashFile) ){
    Tcl_AppendResult(interp, "Filename is too long: \"", zCrashFile, "\"", 0);
    goto error;
  }
  if( Tcl_GetIntFromObj(interp, objv[objc-2], &iDelay) ){
    goto error;
  }

  if( processDevSymArgs(interp, objc-3, &objv[1], &iDc, &iSectorSize) ){
    return TCL_ERROR;
  }

  if( iDc>=0 ){
    g.iDeviceCharacteristics = iDc;
  }
  if( iSectorSize>=0 ){
    g.iSectorSize = iSectorSize;
  }

  g.iCrash = iDelay;
  memcpy(g.zCrashFile, zCrashFile, nCrashFile+1);
  sqlite3CrashTestEnable = 1;
  return TCL_OK;

error:
  return TCL_ERROR;
}

static int devSymObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  void devsym_register(int iDeviceChar, int iSectorSize);

  int iDc = -1;
  int iSectorSize = -1;

  if( processDevSymArgs(interp, objc-1, &objv[1], &iDc, &iSectorSize) ){
    return TCL_ERROR;
  }
  devsym_register(iDc, iSectorSize);

  return TCL_OK;
}

/*
** tclcmd: register_jt_vfs ?-default? PARENT-VFS
*/
static int jtObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int jt_register(char *, int);
  char *zParent = 0;

  if( objc!=2 && objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "?-default? PARENT-VFS");
    return TCL_ERROR;
  }
  zParent = Tcl_GetString(objv[1]);
  if( objc==3 ){
    if( strcmp(zParent, "-default") ){
      Tcl_AppendResult(interp, 
          "bad option \"", zParent, "\": must be -default", 0
      );
      return TCL_ERROR;
    }
    zParent = Tcl_GetString(objv[2]);
  }

  if( !(*zParent) ){
    zParent = 0;
  }
  if( jt_register(zParent, objc==3) ){
    Tcl_AppendResult(interp, "Error in jt_register", 0);
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** tclcmd: unregister_jt_vfs
*/
static int jtUnregisterObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  void jt_unregister(void);

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  jt_unregister();
  return TCL_OK;
}

#endif /* SQLITE_OMIT_DISKIO */

/*
** This procedure registers the TCL procedures defined in this file.
*/
int Sqlitetest6_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_DISKIO
  Tcl_CreateObjCommand(interp, "sqlite3_crash_enable", crashEnableCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlite3_crashparams", crashParamsObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlite3_simulate_device", devSymObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "register_jt_vfs", jtObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "unregister_jt_vfs", jtUnregisterObjCmd, 0, 0);
#endif
  return TCL_OK;
}

#endif /* SQLITE_TEST */

Added src/test7.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/*
** 2006 January 09
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the client/server version of the SQLite library.
** Derived from test4.c.
**
** $Id: test7.c,v 1.13 2008/10/12 00:27:54 shane Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"

/*
** This test only works on UNIX with a SQLITE_THREADSAFE build that includes
** the SQLITE_SERVER option.
*/
#if defined(SQLITE_SERVER) && !defined(SQLITE_OMIT_SHARED_CACHE) && \
    defined(SQLITE_OS_UNIX) && OS_UNIX && SQLITE_THREADSAFE

#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <ctype.h>

/*
** Interfaces defined in server.c
*/
int sqlite3_client_open(const char*, sqlite3**);
int sqlite3_client_prepare(sqlite3*,const char*,int,
                           sqlite3_stmt**,const char**);
int sqlite3_client_step(sqlite3_stmt*);
int sqlite3_client_reset(sqlite3_stmt*);
int sqlite3_client_finalize(sqlite3_stmt*);
int sqlite3_client_close(sqlite3*);
int sqlite3_server_start(void);
int sqlite3_server_stop(void);

/*
** Each thread is controlled by an instance of the following
** structure.
*/
typedef struct Thread Thread;
struct Thread {
  /* The first group of fields are writable by the supervisor thread
  ** and read-only to the client threads
  */
  char *zFilename;         /* Name of database file */
  void (*xOp)(Thread*);    /* next operation to do */
  char *zArg;              /* argument usable by xOp */
  volatile int opnum;      /* Operation number */
  volatile int busy;       /* True if this thread is in use */

  /* The next group of fields are writable by the client threads 
  ** but read-only to the superviser thread.
  */
  volatile int completed;  /* Number of operations completed */
  sqlite3 *db;             /* Open database */
  sqlite3_stmt *pStmt;     /* Pending operation */
  char *zErr;              /* operation error */
  char *zStaticErr;        /* Static error message */
  int rc;                  /* operation return code */
  int argc;                /* number of columns in result */
  const char *argv[100];   /* result columns */
  const char *colv[100];   /* result column names */
};

/*
** There can be as many as 26 threads running at once.  Each is named
** by a capital letter: A, B, C, ..., Y, Z.
*/
#define N_THREAD 26
static Thread threadset[N_THREAD];

/*
** The main loop for a thread.  Threads use busy waiting. 
*/
static void *client_main(void *pArg){
  Thread *p = (Thread*)pArg;
  if( p->db ){
    sqlite3_client_close(p->db);
  }
  sqlite3_client_open(p->zFilename, &p->db);
  if( SQLITE_OK!=sqlite3_errcode(p->db) ){
    p->zErr = strdup(sqlite3_errmsg(p->db));
    sqlite3_client_close(p->db);
    p->db = 0;
  }
  p->pStmt = 0;
  p->completed = 1;
  while( p->opnum<=p->completed ) sched_yield();
  while( p->xOp ){
    if( p->zErr && p->zErr!=p->zStaticErr ){
      sqlite3_free(p->zErr);
      p->zErr = 0;
    }
    (*p->xOp)(p);
    p->completed++;
    while( p->opnum<=p->completed ) sched_yield();
  }
  if( p->pStmt ){
    sqlite3_client_finalize(p->pStmt);
    p->pStmt = 0;
  }
  if( p->db ){
    sqlite3_client_close(p->db);
    p->db = 0;
  }
  if( p->zErr && p->zErr!=p->zStaticErr ){
    sqlite3_free(p->zErr);
    p->zErr = 0;
  }
  p->completed++;
#ifndef SQLITE_OMIT_DEPRECATED
  sqlite3_thread_cleanup();
#endif
  return 0;
}

/*
** Get a thread ID which is an upper case letter.  Return the index.
** If the argument is not a valid thread ID put an error message in
** the interpreter and return -1.
*/
static int parse_client_id(Tcl_Interp *interp, const char *zArg){
  if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){
    Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0);
    return -1;
  }
  return zArg[0] - 'A';
}

/*
** Usage:    client_create NAME  FILENAME
**
** NAME should be an upper case letter.  Start the thread running with
** an open connection to the given database.
*/
static int tcl_client_create(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  pthread_t x;
  int rc;

  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID FILENAME", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( threadset[i].busy ){
    Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0);
    return TCL_ERROR;
  }
  threadset[i].busy = 1;
  sqlite3_free(threadset[i].zFilename);
  threadset[i].zFilename = sqlite3DbStrDup(0, argv[2]);
  threadset[i].opnum = 1;
  threadset[i].completed = 0;
  rc = pthread_create(&x, 0, client_main, &threadset[i]);
  if( rc ){
    Tcl_AppendResult(interp, "failed to create the thread", 0);
    sqlite3_free(threadset[i].zFilename);
    threadset[i].busy = 0;
    return TCL_ERROR;
  }
  pthread_detach(x);
  sqlite3_server_start();
  return TCL_OK;
}

/*
** Wait for a thread to reach its idle state.
*/
static void client_wait(Thread *p){
  while( p->opnum>p->completed ) sched_yield();
}

/*
** Usage:  client_wait ID
**
** Wait on thread ID to reach its idle state.
*/
static int tcl_client_wait(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  return TCL_OK;
}

/*
** Stop a thread.
*/
static void stop_thread(Thread *p){
  client_wait(p);
  p->xOp = 0;
  p->opnum++;
  client_wait(p);
  sqlite3_free(p->zArg);
  p->zArg = 0;
  sqlite3_free(p->zFilename);
  p->zFilename = 0;
  p->busy = 0;
}

/*
** Usage:  client_halt ID
**
** Cause a client thread to shut itself down.  Wait for the shutdown to be
** completed.  If ID is "*" then stop all client threads.
*/
static int tcl_client_halt(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  if( argv[1][0]=='*' && argv[1][1]==0 ){
    for(i=0; i<N_THREAD; i++){
      if( threadset[i].busy ){
        stop_thread(&threadset[i]);
      }
    }
  }else{
    i = parse_client_id(interp, argv[1]);
    if( i<0 ) return TCL_ERROR;
    if( !threadset[i].busy ){
      Tcl_AppendResult(interp, "no such thread", 0);
      return TCL_ERROR;
    }
    stop_thread(&threadset[i]);
  }

  /* If no client threads are still running, also stop the server */
  for(i=0; i<N_THREAD && threadset[i].busy==0; i++){}
  if( i>=N_THREAD ){
    sqlite3_server_stop();
  }
  return TCL_OK;
}

/*
** Usage: client_argc  ID
**
** Wait on the most recent client_step to complete, then return the
** number of columns in the result set.
*/
static int tcl_client_argc(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  char zBuf[100];

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  sprintf(zBuf, "%d", threadset[i].argc);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}

/*
** Usage: client_argv  ID   N
**
** Wait on the most recent client_step to complete, then return the
** value of the N-th columns in the result set.
*/
static int tcl_client_argv(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  int n;

  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID N", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR;
  client_wait(&threadset[i]);
  if( n<0 || n>=threadset[i].argc ){
    Tcl_AppendResult(interp, "column number out of range", 0);
    return TCL_ERROR;
  }
  Tcl_AppendResult(interp, threadset[i].argv[n], 0);
  return TCL_OK;
}

/*
** Usage: client_colname  ID   N
**
** Wait on the most recent client_step to complete, then return the
** name of the N-th columns in the result set.
*/
static int tcl_client_colname(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  int n;

  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID N", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR;
  client_wait(&threadset[i]);
  if( n<0 || n>=threadset[i].argc ){
    Tcl_AppendResult(interp, "column number out of range", 0);
    return TCL_ERROR;
  }
  Tcl_AppendResult(interp, threadset[i].colv[n], 0);
  return TCL_OK;
}

/*
** Usage: client_result  ID
**
** Wait on the most recent operation to complete, then return the
** result code from that operation.
*/
static int tcl_client_result(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  const char *zName;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  switch( threadset[i].rc ){
    case SQLITE_OK:         zName = "SQLITE_OK";          break;
    case SQLITE_ERROR:      zName = "SQLITE_ERROR";       break;
    case SQLITE_PERM:       zName = "SQLITE_PERM";        break;
    case SQLITE_ABORT:      zName = "SQLITE_ABORT";       break;
    case SQLITE_BUSY:       zName = "SQLITE_BUSY";        break;
    case SQLITE_LOCKED:     zName = "SQLITE_LOCKED";      break;
    case SQLITE_NOMEM:      zName = "SQLITE_NOMEM";       break;
    case SQLITE_READONLY:   zName = "SQLITE_READONLY";    break;
    case SQLITE_INTERRUPT:  zName = "SQLITE_INTERRUPT";   break;
    case SQLITE_IOERR:      zName = "SQLITE_IOERR";       break;
    case SQLITE_CORRUPT:    zName = "SQLITE_CORRUPT";     break;
    case SQLITE_FULL:       zName = "SQLITE_FULL";        break;
    case SQLITE_CANTOPEN:   zName = "SQLITE_CANTOPEN";    break;
    case SQLITE_PROTOCOL:   zName = "SQLITE_PROTOCOL";    break;
    case SQLITE_EMPTY:      zName = "SQLITE_EMPTY";       break;
    case SQLITE_SCHEMA:     zName = "SQLITE_SCHEMA";      break;
    case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT";  break;
    case SQLITE_MISMATCH:   zName = "SQLITE_MISMATCH";    break;
    case SQLITE_MISUSE:     zName = "SQLITE_MISUSE";      break;
    case SQLITE_NOLFS:      zName = "SQLITE_NOLFS";       break;
    case SQLITE_AUTH:       zName = "SQLITE_AUTH";        break;
    case SQLITE_FORMAT:     zName = "SQLITE_FORMAT";      break;
    case SQLITE_RANGE:      zName = "SQLITE_RANGE";       break;
    case SQLITE_ROW:        zName = "SQLITE_ROW";         break;
    case SQLITE_DONE:       zName = "SQLITE_DONE";        break;
    default:                zName = "SQLITE_Unknown";     break;
  }
  Tcl_AppendResult(interp, zName, 0);
  return TCL_OK;
}

/*
** Usage: client_error  ID
**
** Wait on the most recent operation to complete, then return the
** error string.
*/
static int tcl_client_error(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  Tcl_AppendResult(interp, threadset[i].zErr, 0);
  return TCL_OK;
}

/*
** This procedure runs in the thread to compile an SQL statement.
*/
static void do_compile(Thread *p){
  if( p->db==0 ){
    p->zErr = p->zStaticErr = "no database is open";
    p->rc = SQLITE_ERROR;
    return;
  }
  if( p->pStmt ){
    sqlite3_client_finalize(p->pStmt);
    p->pStmt = 0;
  }
  p->rc = sqlite3_client_prepare(p->db, p->zArg, -1, &p->pStmt, 0);
}

/*
** Usage: client_compile ID SQL
**
** Compile a new virtual machine.
*/
static int tcl_client_compile(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID SQL", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  threadset[i].xOp = do_compile;
  sqlite3_free(threadset[i].zArg);
  threadset[i].zArg = sqlite3DbStrDup(0, argv[2]);
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to step the virtual machine.
*/
static void do_step(Thread *p){
  int i;
  if( p->pStmt==0 ){
    p->zErr = p->zStaticErr = "no virtual machine available";
    p->rc = SQLITE_ERROR;
    return;
  }
  p->rc = sqlite3_client_step(p->pStmt);
  if( p->rc==SQLITE_ROW ){
    p->argc = sqlite3_column_count(p->pStmt);
    for(i=0; i<sqlite3_data_count(p->pStmt); i++){
      p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i);
    }
    for(i=0; i<p->argc; i++){
      p->colv[i] = sqlite3_column_name(p->pStmt, i);
    }
  }
}

/*
** Usage: client_step ID
**
** Advance the virtual machine by one step
*/
static int tcl_client_step(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " IDL", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  threadset[i].xOp = do_step;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to finalize a virtual machine.
*/
static void do_finalize(Thread *p){
  if( p->pStmt==0 ){
    p->zErr = p->zStaticErr = "no virtual machine available";
    p->rc = SQLITE_ERROR;
    return;
  }
  p->rc = sqlite3_client_finalize(p->pStmt);
  p->pStmt = 0;
}

/*
** Usage: client_finalize ID
**
** Finalize the virtual machine.
*/
static int tcl_client_finalize(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " IDL", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  threadset[i].xOp = do_finalize;
  sqlite3_free(threadset[i].zArg);
  threadset[i].zArg = 0;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to reset a virtual machine.
*/
static void do_reset(Thread *p){
  if( p->pStmt==0 ){
    p->zErr = p->zStaticErr = "no virtual machine available";
    p->rc = SQLITE_ERROR;
    return;
  }
  p->rc = sqlite3_client_reset(p->pStmt);
  p->pStmt = 0;
}

/*
** Usage: client_reset ID
**
** Finalize the virtual machine.
*/
static int tcl_client_reset(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " IDL", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  threadset[i].xOp = do_reset;
  sqlite3_free(threadset[i].zArg);
  threadset[i].zArg = 0;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** Usage: client_swap ID ID
**
** Interchange the sqlite* pointer between two threads.
*/
static int tcl_client_swap(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i, j;
  sqlite3 *temp;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID1 ID2", 0);
    return TCL_ERROR;
  }
  i = parse_client_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[i]);
  j = parse_client_id(interp, argv[2]);
  if( j<0 ) return TCL_ERROR;
  if( !threadset[j].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  client_wait(&threadset[j]);
  temp = threadset[i].db;
  threadset[i].db = threadset[j].db;
  threadset[j].db = temp;
  return TCL_OK;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest7_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_CmdProc *xProc;
  } aCmd[] = {
     { "client_create",     (Tcl_CmdProc*)tcl_client_create     },
     { "client_wait",       (Tcl_CmdProc*)tcl_client_wait       },
     { "client_halt",       (Tcl_CmdProc*)tcl_client_halt       },
     { "client_argc",       (Tcl_CmdProc*)tcl_client_argc       },
     { "client_argv",       (Tcl_CmdProc*)tcl_client_argv       },
     { "client_colname",    (Tcl_CmdProc*)tcl_client_colname    },
     { "client_result",     (Tcl_CmdProc*)tcl_client_result     },
     { "client_error",      (Tcl_CmdProc*)tcl_client_error      },
     { "client_compile",    (Tcl_CmdProc*)tcl_client_compile    },
     { "client_step",       (Tcl_CmdProc*)tcl_client_step       },
     { "client_reset",      (Tcl_CmdProc*)tcl_client_reset      },
     { "client_finalize",   (Tcl_CmdProc*)tcl_client_finalize   },
     { "client_swap",       (Tcl_CmdProc*)tcl_client_swap       },
  };
  int i;

  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }
  return TCL_OK;
}
#else
int Sqlitetest7_Init(Tcl_Interp *interp){ return TCL_OK; }
#endif /* SQLITE_OS_UNIX */

Added src/test8.c.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
/*
** 2006 June 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the virtual table interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test8.c,v 1.78 2009/04/29 11:50:54 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

typedef struct echo_vtab echo_vtab;
typedef struct echo_cursor echo_cursor;

/*
** The test module defined in this file uses four global Tcl variables to
** commicate with test-scripts:
**
**     $::echo_module
**     $::echo_module_sync_fail
**     $::echo_module_begin_fail
**     $::echo_module_cost
**
** The variable ::echo_module is a list. Each time one of the following
** methods is called, one or more elements are appended to the list.
** This is used for automated testing of virtual table modules.
**
** The ::echo_module_sync_fail variable is set by test scripts and read
** by code in this file. If it is set to the name of a real table in the
** the database, then all xSync operations on echo virtual tables that
** use the named table as a backing store will fail.
*/

/*
** Errors can be provoked within the following echo virtual table methods:
**
**   xBestIndex   xOpen     xFilter   xNext   
**   xColumn      xRowid    xUpdate   xSync   
**   xBegin       xRename
**
** This is done by setting the global tcl variable:
**
**   echo_module_fail($method,$tbl)
**
** where $method is set to the name of the virtual table method to fail
** (i.e. "xBestIndex") and $tbl is the name of the table being echoed (not
** the name of the virtual table, the name of the underlying real table).
*/

/* 
** An echo virtual-table object.
**
** echo.vtab.aIndex is an array of booleans. The nth entry is true if 
** the nth column of the real table is the left-most column of an index
** (implicit or otherwise). In other words, if SQLite can optimize
** a query like "SELECT * FROM real_table WHERE col = ?".
**
** Member variable aCol[] contains copies of the column names of the real
** table.
*/
struct echo_vtab {
  sqlite3_vtab base;
  Tcl_Interp *interp;     /* Tcl interpreter containing debug variables */
  sqlite3 *db;            /* Database connection */

  int isPattern;
  int inTransaction;      /* True if within a transaction */
  char *zThis;            /* Name of the echo table */
  char *zTableName;       /* Name of the real table */
  char *zLogName;         /* Name of the log table */
  int nCol;               /* Number of columns in the real table */
  int *aIndex;            /* Array of size nCol. True if column has an index */
  char **aCol;            /* Array of size nCol. Column names */
};

/* An echo cursor object */
struct echo_cursor {
  sqlite3_vtab_cursor base;
  sqlite3_stmt *pStmt;
};

static int simulateVtabError(echo_vtab *p, const char *zMethod){
  const char *zErr;
  char zVarname[128];
  zVarname[127] = '\0';
  sqlite3_snprintf(127, zVarname, "echo_module_fail(%s,%s)", zMethod, p->zTableName);
  zErr = Tcl_GetVar(p->interp, zVarname, TCL_GLOBAL_ONLY);
  if( zErr ){
    p->base.zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", zErr);
  }
  return (zErr!=0);
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** Examples:
**
**     "abc"   becomes   abc
**     'xyz'   becomes   xyz
**     [pqr]   becomes   pqr
**     `mno`   becomes   mno
*/
static void dequoteString(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return;
  }
  for(i=1, j=0; z[i]; i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = quote;
        i++;
      }else{
        z[j++] = 0;
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
}

/*
** Retrieve the column names for the table named zTab via database
** connection db. SQLITE_OK is returned on success, or an sqlite error
** code otherwise.
**
** If successful, the number of columns is written to *pnCol. *paCol is
** set to point at sqlite3_malloc()'d space containing the array of
** nCol column names. The caller is responsible for calling sqlite3_free
** on *paCol.
*/
static int getColumnNames(
  sqlite3 *db, 
  const char *zTab,
  char ***paCol, 
  int *pnCol
){
  char **aCol = 0;
  char *zSql;
  sqlite3_stmt *pStmt = 0;
  int rc = SQLITE_OK;
  int nCol = 0;

  /* Prepare the statement "SELECT * FROM <tbl>". The column names
  ** of the result set of the compiled SELECT will be the same as
  ** the column names of table <tbl>.
  */
  zSql = sqlite3_mprintf("SELECT * FROM %Q", zTab);
  if( !zSql ){
    rc = SQLITE_NOMEM;
    goto out;
  }
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  sqlite3_free(zSql);

  if( rc==SQLITE_OK ){
    int ii;
    int nBytes;
    char *zSpace;
    nCol = sqlite3_column_count(pStmt);

    /* Figure out how much space to allocate for the array of column names 
    ** (including space for the strings themselves). Then allocate it.
    */
    nBytes = sizeof(char *) * nCol;
    for(ii=0; ii<nCol; ii++){
      const char *zName = sqlite3_column_name(pStmt, ii);
      if( !zName ){
        rc = SQLITE_NOMEM;
        goto out;
      }
      nBytes += strlen(zName)+1;
    }
    aCol = (char **)sqlite3MallocZero(nBytes);
    if( !aCol ){
      rc = SQLITE_NOMEM;
      goto out;
    }

    /* Copy the column names into the allocated space and set up the
    ** pointers in the aCol[] array.
    */
    zSpace = (char *)(&aCol[nCol]);
    for(ii=0; ii<nCol; ii++){
      aCol[ii] = zSpace;
      zSpace += sprintf(zSpace, "%s", sqlite3_column_name(pStmt, ii));
      zSpace++;
    }
    assert( (zSpace-nBytes)==(char *)aCol );
  }

  *paCol = aCol;
  *pnCol = nCol;

out:
  sqlite3_finalize(pStmt);
  return rc;
}

/*
** Parameter zTab is the name of a table in database db with nCol 
** columns. This function allocates an array of integers nCol in 
** size and populates it according to any implicit or explicit 
** indices on table zTab.
**
** If successful, SQLITE_OK is returned and *paIndex set to point 
** at the allocated array. Otherwise, an error code is returned.
**
** See comments associated with the member variable aIndex above 
** "struct echo_vtab" for details of the contents of the array.
*/
static int getIndexArray(
  sqlite3 *db,             /* Database connection */
  const char *zTab,        /* Name of table in database db */
  int nCol,
  int **paIndex
){
  sqlite3_stmt *pStmt = 0;
  int *aIndex = 0;
  int rc;
  char *zSql;

  /* Allocate space for the index array */
  aIndex = (int *)sqlite3MallocZero(sizeof(int) * nCol);
  if( !aIndex ){
    rc = SQLITE_NOMEM;
    goto get_index_array_out;
  }

  /* Compile an sqlite pragma to loop through all indices on table zTab */
  zSql = sqlite3_mprintf("PRAGMA index_list(%s)", zTab);
  if( !zSql ){
    rc = SQLITE_NOMEM;
    goto get_index_array_out;
  }
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  sqlite3_free(zSql);

  /* For each index, figure out the left-most column and set the 
  ** corresponding entry in aIndex[] to 1.
  */
  while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
    const char *zIdx = (const char *)sqlite3_column_text(pStmt, 1);
    sqlite3_stmt *pStmt2 = 0;
    zSql = sqlite3_mprintf("PRAGMA index_info(%s)", zIdx);
    if( !zSql ){
      rc = SQLITE_NOMEM;
      goto get_index_array_out;
    }
    rc = sqlite3_prepare(db, zSql, -1, &pStmt2, 0);
    sqlite3_free(zSql);
    if( pStmt2 && sqlite3_step(pStmt2)==SQLITE_ROW ){
      int cid = sqlite3_column_int(pStmt2, 1);
      assert( cid>=0 && cid<nCol );
      aIndex[cid] = 1;
    }
    if( pStmt2 ){
      rc = sqlite3_finalize(pStmt2);
    }
    if( rc!=SQLITE_OK ){
      goto get_index_array_out;
    }
  }


get_index_array_out:
  if( pStmt ){
    int rc2 = sqlite3_finalize(pStmt);
    if( rc==SQLITE_OK ){
      rc = rc2;
    }
  }
  if( rc!=SQLITE_OK ){
    sqlite3_free(aIndex);
    aIndex = 0;
  }
  *paIndex = aIndex;
  return rc;
}

/*
** Global Tcl variable $echo_module is a list. This routine appends
** the string element zArg to that list in interpreter interp.
*/
static void appendToEchoModule(Tcl_Interp *interp, const char *zArg){
  int flags = (TCL_APPEND_VALUE | TCL_LIST_ELEMENT | TCL_GLOBAL_ONLY);
  Tcl_SetVar(interp, "echo_module", (zArg?zArg:""), flags);
}

/*
** This function is called from within the echo-modules xCreate and
** xConnect methods. The argc and argv arguments are copies of those 
** passed to the calling method. This function is responsible for
** calling sqlite3_declare_vtab() to declare the schema of the virtual
** table being created or connected.
**
** If the constructor was passed just one argument, i.e.:
**
**   CREATE TABLE t1 AS echo(t2);
**
** Then t2 is assumed to be the name of a *real* database table. The
** schema of the virtual table is declared by passing a copy of the 
** CREATE TABLE statement for the real table to sqlite3_declare_vtab().
** Hence, the virtual table should have exactly the same column names and 
** types as the real table.
*/
static int echoDeclareVtab(
  echo_vtab *pVtab, 
  sqlite3 *db 
){
  int rc = SQLITE_OK;

  if( pVtab->zTableName ){
    sqlite3_stmt *pStmt = 0;
    rc = sqlite3_prepare(db, 
        "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",
        -1, &pStmt, 0);
    if( rc==SQLITE_OK ){
      sqlite3_bind_text(pStmt, 1, pVtab->zTableName, -1, 0);
      if( sqlite3_step(pStmt)==SQLITE_ROW ){
        int rc2;
        const char *zCreateTable = (const char *)sqlite3_column_text(pStmt, 0);
        rc = sqlite3_declare_vtab(db, zCreateTable);
        rc2 = sqlite3_finalize(pStmt);
        if( rc==SQLITE_OK ){
          rc = rc2;
        }
      } else {
        rc = sqlite3_finalize(pStmt);
        if( rc==SQLITE_OK ){ 
          rc = SQLITE_ERROR;
        }
      }
      if( rc==SQLITE_OK ){
        rc = getColumnNames(db, pVtab->zTableName, &pVtab->aCol, &pVtab->nCol);
      }
      if( rc==SQLITE_OK ){
        rc = getIndexArray(db, pVtab->zTableName, pVtab->nCol, &pVtab->aIndex);
      }
    }
  }

  return rc;
}

/*
** This function frees all runtime structures associated with the virtual
** table pVtab.
*/
static int echoDestructor(sqlite3_vtab *pVtab){
  echo_vtab *p = (echo_vtab*)pVtab;
  sqlite3_free(p->aIndex);
  sqlite3_free(p->aCol);
  sqlite3_free(p->zThis);
  sqlite3_free(p->zTableName);
  sqlite3_free(p->zLogName);
  sqlite3_free(p);
  return 0;
}

typedef struct EchoModule EchoModule;
struct EchoModule {
  Tcl_Interp *interp;
};

/*
** This function is called to do the work of the xConnect() method -
** to allocate the required in-memory structures for a newly connected
** virtual table.
*/
static int echoConstructor(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  int rc;
  int i;
  echo_vtab *pVtab;

  /* Allocate the sqlite3_vtab/echo_vtab structure itself */
  pVtab = sqlite3MallocZero( sizeof(*pVtab) );
  if( !pVtab ){
    return SQLITE_NOMEM;
  }
  pVtab->interp = ((EchoModule *)pAux)->interp;
  pVtab->db = db;

  /* Allocate echo_vtab.zThis */
  pVtab->zThis = sqlite3_mprintf("%s", argv[2]);
  if( !pVtab->zThis ){
    echoDestructor((sqlite3_vtab *)pVtab);
    return SQLITE_NOMEM;
  }

  /* Allocate echo_vtab.zTableName */
  if( argc>3 ){
    pVtab->zTableName = sqlite3_mprintf("%s", argv[3]);
    dequoteString(pVtab->zTableName);
    if( pVtab->zTableName && pVtab->zTableName[0]=='*' ){
      char *z = sqlite3_mprintf("%s%s", argv[2], &(pVtab->zTableName[1]));
      sqlite3_free(pVtab->zTableName);
      pVtab->zTableName = z;
      pVtab->isPattern = 1;
    }
    if( !pVtab->zTableName ){
      echoDestructor((sqlite3_vtab *)pVtab);
      return SQLITE_NOMEM;
    }
  }

  /* Log the arguments to this function to Tcl var ::echo_module */
  for(i=0; i<argc; i++){
    appendToEchoModule(pVtab->interp, argv[i]);
  }

  /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab
  ** structure. If an error occurs, delete the sqlite3_vtab structure and
  ** return an error code.
  */
  rc = echoDeclareVtab(pVtab, db);
  if( rc!=SQLITE_OK ){
    echoDestructor((sqlite3_vtab *)pVtab);
    return rc;
  }

  /* Success. Set *ppVtab and return */
  *ppVtab = &pVtab->base;
  return SQLITE_OK;
}

/* 
** Echo virtual table module xCreate method.
*/
static int echoCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  int rc = SQLITE_OK;
  appendToEchoModule(((EchoModule *)pAux)->interp, "xCreate");
  rc = echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);

  /* If there were two arguments passed to the module at the SQL level 
  ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then 
  ** the second argument is used as a table name. Attempt to create
  ** such a table with a single column, "logmsg". This table will
  ** be used to log calls to the xUpdate method. It will be deleted
  ** when the virtual table is DROPed.
  **
  ** Note: The main point of this is to test that we can drop tables
  ** from within an xDestroy method call.
  */
  if( rc==SQLITE_OK && argc==5 ){
    char *zSql;
    echo_vtab *pVtab = *(echo_vtab **)ppVtab;
    pVtab->zLogName = sqlite3_mprintf("%s", argv[4]);
    zSql = sqlite3_mprintf("CREATE TABLE %Q(logmsg)", pVtab->zLogName);
    rc = sqlite3_exec(db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
    if( rc!=SQLITE_OK ){
      *pzErr = sqlite3DbStrDup(0, sqlite3_errmsg(db));
    }
  }

  if( *ppVtab && rc!=SQLITE_OK ){
    echoDestructor(*ppVtab);
    *ppVtab = 0;
  }

  if( rc==SQLITE_OK ){
    (*(echo_vtab**)ppVtab)->inTransaction = 1;
  }

  return rc;
}

/* 
** Echo virtual table module xConnect method.
*/
static int echoConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  appendToEchoModule(((EchoModule *)pAux)->interp, "xConnect");
  return echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);
}

/* 
** Echo virtual table module xDisconnect method.
*/
static int echoDisconnect(sqlite3_vtab *pVtab){
  appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDisconnect");
  return echoDestructor(pVtab);
}

/* 
** Echo virtual table module xDestroy method.
*/
static int echoDestroy(sqlite3_vtab *pVtab){
  int rc = SQLITE_OK;
  echo_vtab *p = (echo_vtab *)pVtab;
  appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDestroy");

  /* Drop the "log" table, if one exists (see echoCreate() for details) */
  if( p && p->zLogName ){
    char *zSql;
    zSql = sqlite3_mprintf("DROP TABLE %Q", p->zLogName);
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }

  if( rc==SQLITE_OK ){
    rc = echoDestructor(pVtab);
  }
  return rc;
}

/* 
** Echo virtual table module xOpen method.
*/
static int echoOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  echo_cursor *pCur;
  if( simulateVtabError((echo_vtab *)pVTab, "xOpen") ){
    return SQLITE_ERROR;
  }
  pCur = sqlite3MallocZero(sizeof(echo_cursor));
  *ppCursor = (sqlite3_vtab_cursor *)pCur;
  return (pCur ? SQLITE_OK : SQLITE_NOMEM);
}

/* 
** Echo virtual table module xClose method.
*/
static int echoClose(sqlite3_vtab_cursor *cur){
  int rc;
  echo_cursor *pCur = (echo_cursor *)cur;
  sqlite3_stmt *pStmt = pCur->pStmt;
  pCur->pStmt = 0;
  sqlite3_free(pCur);
  rc = sqlite3_finalize(pStmt);
  return rc;
}

/*
** Return non-zero if the cursor does not currently point to a valid record
** (i.e if the scan has finished), or zero otherwise.
*/
static int echoEof(sqlite3_vtab_cursor *cur){
  return (((echo_cursor *)cur)->pStmt ? 0 : 1);
}

/* 
** Echo virtual table module xNext method.
*/
static int echoNext(sqlite3_vtab_cursor *cur){
  int rc = SQLITE_OK;
  echo_cursor *pCur = (echo_cursor *)cur;

  if( simulateVtabError((echo_vtab *)(cur->pVtab), "xNext") ){
    return SQLITE_ERROR;
  }

  if( pCur->pStmt ){
    rc = sqlite3_step(pCur->pStmt);
    if( rc==SQLITE_ROW ){
      rc = SQLITE_OK;
    }else{
      rc = sqlite3_finalize(pCur->pStmt);
      pCur->pStmt = 0;
    }
  }

  return rc;
}

/* 
** Echo virtual table module xColumn method.
*/
static int echoColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  int iCol = i + 1;
  sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt;

  if( simulateVtabError((echo_vtab *)(cur->pVtab), "xColumn") ){
    return SQLITE_ERROR;
  }

  if( !pStmt ){
    sqlite3_result_null(ctx);
  }else{
    assert( sqlite3_data_count(pStmt)>iCol );
    sqlite3_result_value(ctx, sqlite3_column_value(pStmt, iCol));
  }
  return SQLITE_OK;
}

/* 
** Echo virtual table module xRowid method.
*/
static int echoRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt;

  if( simulateVtabError((echo_vtab *)(cur->pVtab), "xRowid") ){
    return SQLITE_ERROR;
  }

  *pRowid = sqlite3_column_int64(pStmt, 0);
  return SQLITE_OK;
}

/*
** Compute a simple hash of the null terminated string zString.
**
** This module uses only sqlite3_index_info.idxStr, not 
** sqlite3_index_info.idxNum. So to test idxNum, when idxStr is set
** in echoBestIndex(), idxNum is set to the corresponding hash value.
** In echoFilter(), code assert()s that the supplied idxNum value is
** indeed the hash of the supplied idxStr.
*/
static int hashString(const char *zString){
  int val = 0;
  int ii;
  for(ii=0; zString[ii]; ii++){
    val = (val << 3) + (int)zString[ii];
  }
  return val;
}

/* 
** Echo virtual table module xFilter method.
*/
static int echoFilter(
  sqlite3_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite3_value **argv
){
  int rc;
  int i;

  echo_cursor *pCur = (echo_cursor *)pVtabCursor;
  echo_vtab *pVtab = (echo_vtab *)pVtabCursor->pVtab;
  sqlite3 *db = pVtab->db;

  if( simulateVtabError(pVtab, "xFilter") ){
    return SQLITE_ERROR;
  }

  /* Check that idxNum matches idxStr */
  assert( idxNum==hashString(idxStr) );

  /* Log arguments to the ::echo_module Tcl variable */
  appendToEchoModule(pVtab->interp, "xFilter");
  appendToEchoModule(pVtab->interp, idxStr);
  for(i=0; i<argc; i++){
    appendToEchoModule(pVtab->interp, (const char*)sqlite3_value_text(argv[i]));
  }

  sqlite3_finalize(pCur->pStmt);
  pCur->pStmt = 0;

  /* Prepare the SQL statement created by echoBestIndex and bind the
  ** runtime parameters passed to this function to it.
  */
  rc = sqlite3_prepare(db, idxStr, -1, &pCur->pStmt, 0);
  assert( pCur->pStmt || rc!=SQLITE_OK );
  for(i=0; rc==SQLITE_OK && i<argc; i++){
    rc = sqlite3_bind_value(pCur->pStmt, i+1, argv[i]);
  }

  /* If everything was successful, advance to the first row of the scan */
  if( rc==SQLITE_OK ){
    rc = echoNext(pVtabCursor);
  }

  return rc;
}


/*
** A helper function used by echoUpdate() and echoBestIndex() for
** manipulating strings in concert with the sqlite3_mprintf() function.
**
** Parameter pzStr points to a pointer to a string allocated with
** sqlite3_mprintf. The second parameter, zAppend, points to another
** string. The two strings are concatenated together and *pzStr
** set to point at the result. The initial buffer pointed to by *pzStr
** is deallocated via sqlite3_free().
**
** If the third argument, doFree, is true, then sqlite3_free() is
** also called to free the buffer pointed to by zAppend.
*/
static void string_concat(char **pzStr, char *zAppend, int doFree, int *pRc){
  char *zIn = *pzStr;
  if( !zAppend && doFree && *pRc==SQLITE_OK ){
    *pRc = SQLITE_NOMEM;
  }
  if( *pRc!=SQLITE_OK ){
    sqlite3_free(zIn);
    zIn = 0;
  }else{
    if( zIn ){
      char *zTemp = zIn;
      zIn = sqlite3_mprintf("%s%s", zIn, zAppend);
      sqlite3_free(zTemp);
    }else{
      zIn = sqlite3_mprintf("%s", zAppend);
    }
    if( !zIn ){
      *pRc = SQLITE_NOMEM;
    }
  }
  *pzStr = zIn;
  if( doFree ){
    sqlite3_free(zAppend);
  }
}

/*
** The echo module implements the subset of query constraints and sort
** orders that may take advantage of SQLite indices on the underlying
** real table. For example, if the real table is declared as:
**
**     CREATE TABLE real(a, b, c);
**     CREATE INDEX real_index ON real(b);
**
** then the echo module handles WHERE or ORDER BY clauses that refer
** to the column "b", but not "a" or "c". If a multi-column index is
** present, only its left most column is considered. 
**
** This xBestIndex method encodes the proposed search strategy as
** an SQL query on the real table underlying the virtual echo module 
** table and stores the query in sqlite3_index_info.idxStr. The SQL
** statement is of the form:
**
**   SELECT rowid, * FROM <real-table> ?<where-clause>? ?<order-by-clause>?
**
** where the <where-clause> and <order-by-clause> are determined
** by the contents of the structure pointed to by the pIdxInfo argument.
*/
static int echoBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  int ii;
  char *zQuery = 0;
  char *zNew;
  int nArg = 0;
  const char *zSep = "WHERE";
  echo_vtab *pVtab = (echo_vtab *)tab;
  sqlite3_stmt *pStmt = 0;
  Tcl_Interp *interp = pVtab->interp;

  int nRow;
  int useIdx = 0;
  int rc = SQLITE_OK;
  int useCost = 0;
  double cost;
  int isIgnoreUsable = 0;
  if( Tcl_GetVar(interp, "echo_module_ignore_usable", TCL_GLOBAL_ONLY) ){
    isIgnoreUsable = 1;
  }

  if( simulateVtabError(pVtab, "xBestIndex") ){
    return SQLITE_ERROR;
  }

  /* Determine the number of rows in the table and store this value in local
  ** variable nRow. The 'estimated-cost' of the scan will be the number of
  ** rows in the table for a linear scan, or the log (base 2) of the 
  ** number of rows if the proposed scan uses an index.  
  */
  if( Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY) ){
    cost = atof(Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY));
    useCost = 1;
  } else {
    zQuery = sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName);
    if( !zQuery ){
      return SQLITE_NOMEM;
    }
    rc = sqlite3_prepare(pVtab->db, zQuery, -1, &pStmt, 0);
    sqlite3_free(zQuery);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    sqlite3_step(pStmt);
    nRow = sqlite3_column_int(pStmt, 0);
    rc = sqlite3_finalize(pStmt);
    if( rc!=SQLITE_OK ){
      return rc;
    }
  }

  zQuery = sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName);
  if( !zQuery ){
    return SQLITE_NOMEM;
  }
  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    const struct sqlite3_index_constraint *pConstraint;
    struct sqlite3_index_constraint_usage *pUsage;
    int iCol;

    pConstraint = &pIdxInfo->aConstraint[ii];
    pUsage = &pIdxInfo->aConstraintUsage[ii];

    if( !isIgnoreUsable && !pConstraint->usable ) continue;

    iCol = pConstraint->iColumn;
    if( pVtab->aIndex[iCol] || iCol<0 ){
      char *zCol = pVtab->aCol[iCol];
      char *zOp = 0;
      useIdx = 1;
      if( iCol<0 ){
        zCol = "rowid";
      }
      switch( pConstraint->op ){
        case SQLITE_INDEX_CONSTRAINT_EQ:
          zOp = "="; break;
        case SQLITE_INDEX_CONSTRAINT_LT:
          zOp = "<"; break;
        case SQLITE_INDEX_CONSTRAINT_GT:
          zOp = ">"; break;
        case SQLITE_INDEX_CONSTRAINT_LE:
          zOp = "<="; break;
        case SQLITE_INDEX_CONSTRAINT_GE:
          zOp = ">="; break;
        case SQLITE_INDEX_CONSTRAINT_MATCH:
          zOp = "LIKE"; break;
      }
      if( zOp[0]=='L' ){
        zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')", 
                               zSep, zCol);
      } else {
        zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp);
      }
      string_concat(&zQuery, zNew, 1, &rc);

      zSep = "AND";
      pUsage->argvIndex = ++nArg;
      pUsage->omit = 1;
    }
  }

  /* If there is only one term in the ORDER BY clause, and it is
  ** on a column that this virtual table has an index for, then consume 
  ** the ORDER BY clause.
  */
  if( pIdxInfo->nOrderBy==1 && pVtab->aIndex[pIdxInfo->aOrderBy->iColumn] ){
    int iCol = pIdxInfo->aOrderBy->iColumn;
    char *zCol = pVtab->aCol[iCol];
    char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC";
    if( iCol<0 ){
      zCol = "rowid";
    }
    zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir);
    string_concat(&zQuery, zNew, 1, &rc);
    pIdxInfo->orderByConsumed = 1;
  }

  appendToEchoModule(pVtab->interp, "xBestIndex");;
  appendToEchoModule(pVtab->interp, zQuery);

  if( !zQuery ){
    return rc;
  }
  pIdxInfo->idxNum = hashString(zQuery);
  pIdxInfo->idxStr = zQuery;
  pIdxInfo->needToFreeIdxStr = 1;
  if( useCost ){
    pIdxInfo->estimatedCost = cost;
  }else if( useIdx ){
    /* Approximation of log2(nRow). */
    for( ii=0; ii<(sizeof(int)*8); ii++ ){
      if( nRow & (1<<ii) ){
        pIdxInfo->estimatedCost = (double)ii;
      }
    }
  }else{
    pIdxInfo->estimatedCost = (double)nRow;
  }
  return rc;
}

/*
** The xUpdate method for echo module virtual tables.
** 
**    apData[0]  apData[1]  apData[2..]
**
**    INTEGER                              DELETE            
**
**    INTEGER    NULL       (nCol args)    UPDATE (do not set rowid)
**    INTEGER    INTEGER    (nCol args)    UPDATE (with SET rowid = <arg1>)
**
**    NULL       NULL       (nCol args)    INSERT INTO (automatic rowid value)
**    NULL       INTEGER    (nCol args)    INSERT (incl. rowid value)
**
*/
int echoUpdate(
  sqlite3_vtab *tab, 
  int nData, 
  sqlite3_value **apData, 
  sqlite_int64 *pRowid
){
  echo_vtab *pVtab = (echo_vtab *)tab;
  sqlite3 *db = pVtab->db;
  int rc = SQLITE_OK;

  sqlite3_stmt *pStmt;
  char *z = 0;               /* SQL statement to execute */
  int bindArgZero = 0;       /* True to bind apData[0] to sql var no. nData */
  int bindArgOne = 0;        /* True to bind apData[1] to sql var no. 1 */
  int i;                     /* Counter variable used by for loops */

  assert( nData==pVtab->nCol+2 || nData==1 );

  /* Ticket #3083 - make sure we always start a transaction prior to
  ** making any changes to a virtual table */
  assert( pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xUpdate") ){
    return SQLITE_ERROR;
  }

  /* If apData[0] is an integer and nData>1 then do an UPDATE */
  if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
    char *zSep = " SET";
    z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName);
    if( !z ){
      rc = SQLITE_NOMEM;
    }

    bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER);
    bindArgZero = 1;

    if( bindArgOne ){
       string_concat(&z, " SET rowid=?1 ", 0, &rc);
       zSep = ",";
    }
    for(i=2; i<nData; i++){
      if( apData[i]==0 ) continue;
      string_concat(&z, sqlite3_mprintf(
          "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1, &rc);
      zSep = ",";
    }
    string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1, &rc);
  }

  /* If apData[0] is an integer and nData==1 then do a DELETE */
  else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
    z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName);
    if( !z ){
      rc = SQLITE_NOMEM;
    }
    bindArgZero = 1;
  }

  /* If the first argument is NULL and there are more than two args, INSERT */
  else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){
    int ii;
    char *zInsert = 0;
    char *zValues = 0;
  
    zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName);
    if( !zInsert ){
      rc = SQLITE_NOMEM;
    }
    if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){
      bindArgOne = 1;
      zValues = sqlite3_mprintf("?");
      string_concat(&zInsert, "rowid", 0, &rc);
    }

    assert((pVtab->nCol+2)==nData);
    for(ii=2; ii<nData; ii++){
      string_concat(&zInsert, 
          sqlite3_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1, &rc);
      string_concat(&zValues, 
          sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc);
    }

    string_concat(&z, zInsert, 1, &rc);
    string_concat(&z, ") VALUES(", 0, &rc);
    string_concat(&z, zValues, 1, &rc);
    string_concat(&z, ")", 0, &rc);
  }

  /* Anything else is an error */
  else{
    assert(0);
    return SQLITE_ERROR;
  }

  if( rc==SQLITE_OK ){
    rc = sqlite3_prepare(db, z, -1, &pStmt, 0);
  }
  assert( rc!=SQLITE_OK || pStmt );
  sqlite3_free(z);
  if( rc==SQLITE_OK ) {
    if( bindArgZero ){
      sqlite3_bind_value(pStmt, nData, apData[0]);
    }
    if( bindArgOne ){
      sqlite3_bind_value(pStmt, 1, apData[1]);
    }
    for(i=2; i<nData && rc==SQLITE_OK; i++){
      if( apData[i] ) rc = sqlite3_bind_value(pStmt, i, apData[i]);
    }
    if( rc==SQLITE_OK ){
      sqlite3_step(pStmt);
      rc = sqlite3_finalize(pStmt);
    }else{
      sqlite3_finalize(pStmt);
    }
  }

  if( pRowid && rc==SQLITE_OK ){
    *pRowid = sqlite3_last_insert_rowid(db);
  }
  if( rc!=SQLITE_OK ){
    tab->zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", sqlite3_errmsg(db));
  }

  return rc;
}

/*
** xBegin, xSync, xCommit and xRollback callbacks for echo module
** virtual tables. Do nothing other than add the name of the callback
** to the $::echo_module Tcl variable.
*/
static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){
  char *z;
  echo_vtab *pVtab = (echo_vtab *)tab;
  z = sqlite3_mprintf("echo(%s)", pVtab->zTableName);
  if( z==0 ) return SQLITE_NOMEM;
  appendToEchoModule(pVtab->interp, zCall);
  appendToEchoModule(pVtab->interp, z);
  sqlite3_free(z);
  return SQLITE_OK;
}
static int echoBegin(sqlite3_vtab *tab){
  int rc;
  echo_vtab *pVtab = (echo_vtab *)tab;
  Tcl_Interp *interp = pVtab->interp;
  const char *zVal; 

  /* Ticket #3083 - do not start a transaction if we are already in
  ** a transaction */
  assert( !pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xBegin") ){
    return SQLITE_ERROR;
  }

  rc = echoTransactionCall(tab, "xBegin");

  if( rc==SQLITE_OK ){
    /* Check if the $::echo_module_begin_fail variable is defined. If it is,
    ** and it is set to the name of the real table underlying this virtual
    ** echo module table, then cause this xSync operation to fail.
    */
    zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
    if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
      rc = SQLITE_ERROR;
    }
  }
  if( rc==SQLITE_OK ){
    pVtab->inTransaction = 1;
  }
  return rc;
}
static int echoSync(sqlite3_vtab *tab){
  int rc;
  echo_vtab *pVtab = (echo_vtab *)tab;
  Tcl_Interp *interp = pVtab->interp;
  const char *zVal; 

  /* Ticket #3083 - Only call xSync if we have previously started a
  ** transaction */
  assert( pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xSync") ){
    return SQLITE_ERROR;
  }

  rc = echoTransactionCall(tab, "xSync");

  if( rc==SQLITE_OK ){
    /* Check if the $::echo_module_sync_fail variable is defined. If it is,
    ** and it is set to the name of the real table underlying this virtual
    ** echo module table, then cause this xSync operation to fail.
    */
    zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
    if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
      rc = -1;
    }
  }
  return rc;
}
static int echoCommit(sqlite3_vtab *tab){
  echo_vtab *pVtab = (echo_vtab*)tab;
  int rc;

  /* Ticket #3083 - Only call xCommit if we have previously started
  ** a transaction */
  assert( pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xCommit") ){
    return SQLITE_ERROR;
  }

  sqlite3BeginBenignMalloc();
  rc = echoTransactionCall(tab, "xCommit");
  sqlite3EndBenignMalloc();
  pVtab->inTransaction = 0;
  return rc;
}
static int echoRollback(sqlite3_vtab *tab){
  int rc;
  echo_vtab *pVtab = (echo_vtab*)tab;

  /* Ticket #3083 - Only call xRollback if we have previously started
  ** a transaction */
  assert( pVtab->inTransaction );

  rc = echoTransactionCall(tab, "xRollback");
  pVtab->inTransaction = 0;
  return rc;
}

/*
** Implementation of "GLOB" function on the echo module.  Pass
** all arguments to the ::echo_glob_overload procedure of TCL
** and return the result of that procedure as a string.
*/
static void overloadedGlobFunction(
  sqlite3_context *pContext,
  int nArg,
  sqlite3_value **apArg
){
  Tcl_Interp *interp = sqlite3_user_data(pContext);
  Tcl_DString str;
  int i;
  int rc;
  Tcl_DStringInit(&str);
  Tcl_DStringAppendElement(&str, "::echo_glob_overload");
  for(i=0; i<nArg; i++){
    Tcl_DStringAppendElement(&str, (char*)sqlite3_value_text(apArg[i]));
  }
  rc = Tcl_Eval(interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  if( rc ){
    sqlite3_result_error(pContext, Tcl_GetStringResult(interp), -1);
  }else{
    sqlite3_result_text(pContext, Tcl_GetStringResult(interp),
                        -1, SQLITE_TRANSIENT);
  }
  Tcl_ResetResult(interp);
}

/*
** This is the xFindFunction implementation for the echo module.
** SQLite calls this routine when the first argument of a function
** is a column of an echo virtual table.  This routine can optionally
** override the implementation of that function.  It will choose to
** do so if the function is named "glob", and a TCL command named
** ::echo_glob_overload exists.
*/
static int echoFindFunction(
  sqlite3_vtab *vtab,
  int nArg,
  const char *zFuncName,
  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  void **ppArg
){
  echo_vtab *pVtab = (echo_vtab *)vtab;
  Tcl_Interp *interp = pVtab->interp;
  Tcl_CmdInfo info;
  if( strcmp(zFuncName,"glob")!=0 ){
    return 0;
  }
  if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){
    return 0;
  }
  *pxFunc = overloadedGlobFunction;
  *ppArg = interp;
  return 1;
}

static int echoRename(sqlite3_vtab *vtab, const char *zNewName){
  int rc = SQLITE_OK;
  echo_vtab *p = (echo_vtab *)vtab;

  if( simulateVtabError(p, "xRename") ){
    return SQLITE_ERROR;
  }

  if( p->isPattern ){
    int nThis = strlen(p->zThis);
    char *zSql = sqlite3_mprintf("ALTER TABLE %s RENAME TO %s%s", 
        p->zTableName, zNewName, &p->zTableName[nThis]
    );
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }

  return rc;
}

/*
** A virtual table module that merely "echos" the contents of another
** table (like an SQL VIEW).
*/
static sqlite3_module echoModule = {
  0,                         /* iVersion */
  echoCreate,
  echoConnect,
  echoBestIndex,
  echoDisconnect, 
  echoDestroy,
  echoOpen,                  /* xOpen - open a cursor */
  echoClose,                 /* xClose - close a cursor */
  echoFilter,                /* xFilter - configure scan constraints */
  echoNext,                  /* xNext - advance a cursor */
  echoEof,                   /* xEof */
  echoColumn,                /* xColumn - read data */
  echoRowid,                 /* xRowid - read data */
  echoUpdate,                /* xUpdate - write data */
  echoBegin,                 /* xBegin - begin transaction */
  echoSync,                  /* xSync - sync transaction */
  echoCommit,                /* xCommit - commit transaction */
  echoRollback,              /* xRollback - rollback transaction */
  echoFindFunction,          /* xFindFunction - function overloading */
  echoRename,                /* xRename - rename the table */
};

/*
** Decode a pointer to an sqlite3 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);

static void moduleDestroy(void *p){
  sqlite3_free(p);
}

/*
** Register the echo virtual table module.
*/
static int register_echo_module(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  EchoModule *pMod;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  pMod = sqlite3_malloc(sizeof(EchoModule));
  pMod->interp = interp;
  sqlite3_create_module_v2(db, "echo", &echoModule, (void*)pMod, moduleDestroy);
  return TCL_OK;
}

/*
** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl:
**
** sqlite3_declare_vtab DB SQL
*/
static int declare_vtab(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  int rc;
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB SQL");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite3_declare_vtab(db, Tcl_GetString(objv[2]));
  if( rc!=SQLITE_OK ){
    Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
    return TCL_ERROR;
  }
  return TCL_OK;
}

#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest8_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_echo_module",   register_echo_module, 0 },
     { "sqlite3_declare_vtab",   declare_vtab, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
#endif
  return TCL_OK;
}

Added src/test9.c.





















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
** 2007 March 29
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains obscure tests of the C-interface required
** for completeness. Test code is written in C for these cases
** as there is not much point in binding to Tcl.
**
** $Id: test9.c,v 1.7 2009/04/02 18:32:27 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
** c_collation_test
*/
static int c_collation_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  const char *zErrFunction = "N/A";
  sqlite3 *db;

  int rc;
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  /* Open a database. */
  rc = sqlite3_open(":memory:", &db);
  if( rc!=SQLITE_OK ){
    zErrFunction = "sqlite3_open";
    goto error_out;
  }

  rc = sqlite3_create_collation(db, "collate", 456, 0, 0);
  if( rc!=SQLITE_MISUSE ){
    sqlite3_close(db);
    zErrFunction = "sqlite3_create_collation";
    goto error_out;
  }

  sqlite3_close(db);
  return TCL_OK;

error_out:
  Tcl_ResetResult(interp);
  Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0);
  return TCL_ERROR;
}

/*
** c_realloc_test
*/
static int c_realloc_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  void *p;
  const char *zErrFunction = "N/A";

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  p = sqlite3_malloc(5);
  if( !p ){
    zErrFunction = "sqlite3_malloc";
    goto error_out;
  }

  /* Test that realloc()ing a block of memory to a negative size is
  ** the same as free()ing that memory.
  */
  p = sqlite3_realloc(p, -1);
  if( p ){
    zErrFunction = "sqlite3_realloc";
    goto error_out;
  }

  return TCL_OK;

error_out:
  Tcl_ResetResult(interp);
  Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0);
  return TCL_ERROR;
}


/*
** c_misuse_test
*/
static int c_misuse_test(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  const char *zErrFunction = "N/A";
  sqlite3 *db = 0;
  sqlite3_stmt *pStmt;
  int rc;

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  /* Open a database. Then close it again. We need to do this so that
  ** we have a "closed database handle" to pass to various API functions.
  */
  rc = sqlite3_open(":memory:", &db);
  if( rc!=SQLITE_OK ){
    zErrFunction = "sqlite3_open";
    goto error_out;
  }
  sqlite3_close(db);


  rc = sqlite3_errcode(db);
  if( rc!=SQLITE_MISUSE ){
    zErrFunction = "sqlite3_errcode";
    goto error_out;
  }

  pStmt = (sqlite3_stmt*)1234;
  rc = sqlite3_prepare(db, 0, 0, &pStmt, 0);
  if( rc!=SQLITE_MISUSE ){
    zErrFunction = "sqlite3_prepare";
    goto error_out;
  }
  assert( pStmt==0 ); /* Verify that pStmt is zeroed even on a MISUSE error */

  pStmt = (sqlite3_stmt*)1234;
  rc = sqlite3_prepare_v2(db, 0, 0, &pStmt, 0);
  if( rc!=SQLITE_MISUSE ){
    zErrFunction = "sqlite3_prepare_v2";
    goto error_out;
  }
  assert( pStmt==0 );

#ifndef SQLITE_OMIT_UTF16
  pStmt = (sqlite3_stmt*)1234;
  rc = sqlite3_prepare16(db, 0, 0, &pStmt, 0);
  if( rc!=SQLITE_MISUSE ){
    zErrFunction = "sqlite3_prepare16";
    goto error_out;
  }
  assert( pStmt==0 );
  pStmt = (sqlite3_stmt*)1234;
  rc = sqlite3_prepare16_v2(db, 0, 0, &pStmt, 0);
  if( rc!=SQLITE_MISUSE ){
    zErrFunction = "sqlite3_prepare16_v2";
    goto error_out;
  }
  assert( pStmt==0 );
#endif

  return TCL_OK;

error_out:
  Tcl_ResetResult(interp);
  Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0);
  return TCL_ERROR;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest9_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "c_misuse_test",    c_misuse_test, 0 },
     { "c_realloc_test",   c_realloc_test, 0 },
     { "c_collation_test", c_collation_test, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  return TCL_OK;
}

Added src/test_async.c.





































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
** 2005 December 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** $Id: test_async.c,v 1.62 2009/04/28 13:01:09 drh Exp $
**
** This file contains a binding of the asynchronous IO extension interface
** (defined in ext/async/sqlite3async.h) to Tcl.
*/

#define TCL_THREADS 
#include <tcl.h>

#ifdef SQLITE_ENABLE_ASYNCIO

#include "sqlite3async.h"
#include "sqlite3.h"
#include <assert.h>

/* From test1.c */
const char *sqlite3TestErrorName(int);


struct TestAsyncGlobal {
  int isInstalled;                     /* True when async VFS is installed */
} testasync_g = { 0 };

TCL_DECLARE_MUTEX(testasync_g_writerMutex);

/*
** sqlite3async_initialize PARENT-VFS ISDEFAULT
*/
static int testAsyncInit(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  const char *zParent;
  int isDefault;
  int rc;

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "PARENT-VFS ISDEFAULT");
    return TCL_ERROR;
  }
  zParent = Tcl_GetString(objv[1]);
  if( !*zParent ) {
    zParent = 0;
  }
  if( Tcl_GetBooleanFromObj(interp, objv[2], &isDefault) ){
    return TCL_ERROR;
  }

  rc = sqlite3async_initialize(zParent, isDefault);
  if( rc!=SQLITE_OK ){
    Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3TestErrorName(rc), -1));
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** sqlite3async_shutdown
*/
static int testAsyncShutdown(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3async_shutdown();
  return TCL_OK;
}

static Tcl_ThreadCreateType tclWriterThread(ClientData pIsStarted){
  Tcl_MutexLock(&testasync_g_writerMutex);
  *((int *)pIsStarted) = 1;
  sqlite3async_run();
  Tcl_MutexUnlock(&testasync_g_writerMutex);
  TCL_THREAD_CREATE_RETURN;
}

/*
** sqlite3async_start
**
** Start a new writer thread.
*/
static int testAsyncStart(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  volatile int isStarted = 0;
  ClientData threadData = (ClientData)&isStarted;

  Tcl_ThreadId x;
  const int nStack = TCL_THREAD_STACK_DEFAULT;
  const int flags = TCL_THREAD_NOFLAGS;
  int rc;

  rc = Tcl_CreateThread(&x, tclWriterThread, threadData, nStack, flags);
  if( rc!=TCL_OK ){
    Tcl_AppendResult(interp, "Tcl_CreateThread() failed", 0);
    return TCL_ERROR;
  }

  while( isStarted==0 ) { /* Busy loop */ }
  return TCL_OK;
}

/*
** sqlite3async_wait
**
** Wait for the current writer thread to terminate.
**
** If the current writer thread is set to run forever then this
** command would block forever.  To prevent that, an error is returned. 
*/
static int testAsyncWait(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int eCond;
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  sqlite3async_control(SQLITEASYNC_GET_HALT, &eCond);
  if( eCond==SQLITEASYNC_HALT_NEVER ){
    Tcl_AppendResult(interp, "would block forever", (char*)0);
    return TCL_ERROR;
  }

  Tcl_MutexLock(&testasync_g_writerMutex);
  Tcl_MutexUnlock(&testasync_g_writerMutex);
  return TCL_OK;
}

/*
** sqlite3async_control OPTION ?VALUE?
*/
static int testAsyncControl(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = SQLITE_OK;
  int aeOpt[] = { SQLITEASYNC_HALT, SQLITEASYNC_DELAY, SQLITEASYNC_LOCKFILES };
  const char *azOpt[] = { "halt", "delay", "lockfiles", 0 };
  const char *az[] = { "never", "now", "idle", 0 };
  int iVal;
  int eOpt;

  if( objc!=2 && objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "OPTION ?VALUE?");
    return TCL_ERROR;
  }
  if( Tcl_GetIndexFromObj(interp, objv[1], azOpt, "option", 0, &eOpt) ){
    return TCL_ERROR;
  }
  eOpt = aeOpt[eOpt];

  if( objc==3 ){
    switch( eOpt ){
      case SQLITEASYNC_HALT: {
        assert( SQLITEASYNC_HALT_NEVER==0 );
        assert( SQLITEASYNC_HALT_NOW==1 );
        assert( SQLITEASYNC_HALT_IDLE==2 );
        if( Tcl_GetIndexFromObj(interp, objv[2], az, "value", 0, &iVal) ){
          return TCL_ERROR;
        }
        break;
      }
      case SQLITEASYNC_DELAY:
        if( Tcl_GetIntFromObj(interp, objv[2], &iVal) ){
          return TCL_ERROR;
        }
        break;

      case SQLITEASYNC_LOCKFILES:
        if( Tcl_GetBooleanFromObj(interp, objv[2], &iVal) ){
          return TCL_ERROR;
        }
        break;
    }

    rc = sqlite3async_control(eOpt, iVal);
  }

  if( rc==SQLITE_OK ){
    rc = sqlite3async_control(
        eOpt==SQLITEASYNC_HALT ? SQLITEASYNC_GET_HALT :
        eOpt==SQLITEASYNC_DELAY ? SQLITEASYNC_GET_DELAY :
        SQLITEASYNC_GET_LOCKFILES, &iVal);
  }

  if( rc!=SQLITE_OK ){
    Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3TestErrorName(rc), -1));
    return TCL_ERROR;
  }

  if( eOpt==SQLITEASYNC_HALT ){
    Tcl_SetObjResult(interp, Tcl_NewStringObj(az[iVal], -1));
  }else{
    Tcl_SetObjResult(interp, Tcl_NewIntObj(iVal));
  }

  return TCL_OK;
}

#endif  /* SQLITE_ENABLE_ASYNCIO */

/*
** This routine registers the custom TCL commands defined in this
** module.  This should be the only procedure visible from outside
** of this module.
*/
int Sqlitetestasync_Init(Tcl_Interp *interp){
#if SQLITE_ENABLE_ASYNCIO
  Tcl_CreateObjCommand(interp,"sqlite3async_start",testAsyncStart,0,0);
  Tcl_CreateObjCommand(interp,"sqlite3async_wait",testAsyncWait,0,0);

  Tcl_CreateObjCommand(interp,"sqlite3async_control",testAsyncControl,0,0);
  Tcl_CreateObjCommand(interp,"sqlite3async_initialize",testAsyncInit,0,0);
  Tcl_CreateObjCommand(interp,"sqlite3async_shutdown",testAsyncShutdown,0,0);
#endif  /* SQLITE_ENABLE_ASYNCIO */
  return TCL_OK;
}

Added src/test_autoext.c.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/*
** 2006 August 23
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Test extension for testing the sqlite3_auto_extension() function.
**
** $Id: test_autoext.c,v 1.5 2008/07/08 02:12:37 drh Exp $
*/
#include "tcl.h"
#include "sqlite3ext.h"

#ifndef SQLITE_OMIT_LOAD_EXTENSION
static SQLITE_EXTENSION_INIT1

/*
** The sqr() SQL function returns the square of its input value.
*/
static void sqrFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  double r = sqlite3_value_double(argv[0]);
  sqlite3_result_double(context, r*r);
}

/*
** This is the entry point to register the extension for the sqr() function.
*/
static int sqr_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi);
  sqlite3_create_function(db, "sqr", 1, SQLITE_ANY, 0, sqrFunc, 0, 0);
  return 0;
}

/*
** The cube() SQL function returns the cube of its input value.
*/
static void cubeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  double r = sqlite3_value_double(argv[0]);
  sqlite3_result_double(context, r*r*r);
}

/*
** This is the entry point to register the extension for the cube() function.
*/
static int cube_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi);
  sqlite3_create_function(db, "cube", 1, SQLITE_ANY, 0, cubeFunc, 0, 0);
  return 0;
}

/*
** This is a broken extension entry point
*/
static int broken_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  char *zErr;
  SQLITE_EXTENSION_INIT2(pApi);
  zErr = sqlite3_mprintf("broken autoext!");
  *pzErrMsg = zErr;
  return 1;
}

/*
** tclcmd:   sqlite3_auto_extension_sqr
**
** Register the "sqr" extension to be loaded automatically.
*/
static int autoExtSqrObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = sqlite3_auto_extension((void*)sqr_init);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return SQLITE_OK;
}

/*
** tclcmd:   sqlite3_auto_extension_cube
**
** Register the "cube" extension to be loaded automatically.
*/
static int autoExtCubeObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = sqlite3_auto_extension((void*)cube_init);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return SQLITE_OK;
}

/*
** tclcmd:   sqlite3_auto_extension_broken
**
** Register the broken extension to be loaded automatically.
*/
static int autoExtBrokenObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = sqlite3_auto_extension((void*)broken_init);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return SQLITE_OK;
}

#endif /* SQLITE_OMIT_LOAD_EXTENSION */


/*
** tclcmd:   sqlite3_reset_auto_extension
**
** Reset all auto-extensions
*/
static int resetAutoExtObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_reset_auto_extension();
  return SQLITE_OK;
}


/*
** This procedure registers the TCL procs defined in this file.
*/
int Sqlitetest_autoext_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_LOAD_EXTENSION
  Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_sqr",
          autoExtSqrObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_cube",
          autoExtCubeObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_broken",
          autoExtBrokenObjCmd, 0, 0);
#endif
  Tcl_CreateObjCommand(interp, "sqlite3_reset_auto_extension",
          resetAutoExtObjCmd, 0, 0);
  return TCL_OK;
}

Added src/test_backup.c.









































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
** 2009 January 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** $Id: test_backup.c,v 1.3 2009/03/30 12:56:52 drh Exp $
*/

#include "tcl.h"
#include <sqlite3.h>
#include <assert.h>

/* These functions are implemented in test1.c. */
int getDbPointer(Tcl_Interp *, const char *, sqlite3 **);
const char *sqlite3TestErrorName(int);

static int backupTestCmd(
  ClientData clientData, 
  Tcl_Interp *interp, 
  int objc,
  Tcl_Obj *const*objv
){
  enum BackupSubCommandEnum {
    BACKUP_STEP, BACKUP_FINISH, BACKUP_REMAINING, BACKUP_PAGECOUNT
  };
  struct BackupSubCommand {
    const char *zCmd;
    enum BackupSubCommandEnum eCmd;
    int nArg;
    const char *zArg;
  } aSub[] = {
    {"step",      BACKUP_STEP      , 1, "npage" },
    {"finish",    BACKUP_FINISH    , 0, ""      },
    {"remaining", BACKUP_REMAINING , 0, ""      },
    {"pagecount", BACKUP_PAGECOUNT , 0, ""      },
    {0, 0, 0, 0}
  };

  sqlite3_backup *p = (sqlite3_backup *)clientData;
  int iCmd;
  int rc;

  rc = Tcl_GetIndexFromObjStruct(
      interp, objv[1], aSub, sizeof(aSub[0]), "option", 0, &iCmd
  );
  if( rc!=TCL_OK ){
    return rc;
  }
  if( objc!=(2 + aSub[iCmd].nArg) ){
    Tcl_WrongNumArgs(interp, 2, objv, aSub[iCmd].zArg);
    return TCL_ERROR;
  }

  switch( aSub[iCmd].eCmd ){

    case BACKUP_FINISH: {
      const char *zCmdName;
      Tcl_CmdInfo cmdInfo;
      zCmdName = Tcl_GetString(objv[0]);
      Tcl_GetCommandInfo(interp, zCmdName, &cmdInfo);
      cmdInfo.deleteProc = 0;
      Tcl_SetCommandInfo(interp, zCmdName, &cmdInfo);
      Tcl_DeleteCommand(interp, zCmdName);

      rc = sqlite3_backup_finish(p);
      Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
      break;
    }

    case BACKUP_STEP: {
      int nPage;
      if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &nPage) ){
        return TCL_ERROR;
      }
      rc = sqlite3_backup_step(p, nPage);
      Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
      break;
    }

    case BACKUP_REMAINING:
      Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_remaining(p)));
      break;

    case BACKUP_PAGECOUNT:
      Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_pagecount(p)));
      break;
  }

  return TCL_OK;
}

static void backupTestFinish(ClientData clientData){
  sqlite3_backup *pBackup = (sqlite3_backup *)clientData;
  sqlite3_backup_finish(pBackup);
}

/*
**     sqlite3_backup CMDNAME DESTHANDLE DESTNAME SRCHANDLE SRCNAME
**
*/
static int backupTestInit(
  ClientData clientData, 
  Tcl_Interp *interp, 
  int objc,
  Tcl_Obj *const*objv
){
  sqlite3_backup *pBackup;
  sqlite3 *pDestDb;
  sqlite3 *pSrcDb;
  const char *zDestName;
  const char *zSrcName;
  const char *zCmd;

  if( objc!=6 ){
    Tcl_WrongNumArgs(
      interp, 1, objv, "CMDNAME DESTHANDLE DESTNAME SRCHANDLE SRCNAME"
    );
    return TCL_ERROR;
  }

  zCmd = Tcl_GetString(objv[1]);
  getDbPointer(interp, Tcl_GetString(objv[2]), &pDestDb);
  zDestName = Tcl_GetString(objv[3]);
  getDbPointer(interp, Tcl_GetString(objv[4]), &pSrcDb);
  zSrcName = Tcl_GetString(objv[5]);

  pBackup = sqlite3_backup_init(pDestDb, zDestName, pSrcDb, zSrcName);
  if( !pBackup ){
    Tcl_AppendResult(interp, "sqlite3_backup_init() failed", 0);
    return TCL_ERROR;
  }

  Tcl_CreateObjCommand(interp, zCmd, backupTestCmd, pBackup, backupTestFinish);
  Tcl_SetObjResult(interp, objv[1]);
  return TCL_OK;
}

int Sqlitetestbackup_Init(Tcl_Interp *interp){
  Tcl_CreateObjCommand(interp, "sqlite3_backup", backupTestInit, 0, 0);
  return TCL_OK;
}

Added src/test_btree.c.

































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
** 2007 May 05
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the btree.c module in SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test_btree.c,v 1.9 2009/07/09 02:48:24 shane Exp $
*/
#include "btreeInt.h"
#include <tcl.h>

/*
** Usage: sqlite3_shared_cache_report
**
** Return a list of file that are shared and the number of
** references to each file.
*/
int sqlite3BtreeSharedCacheReport(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_OMIT_SHARED_CACHE
  extern BtShared *sqlite3SharedCacheList;
  BtShared *pBt;
  Tcl_Obj *pRet = Tcl_NewObj();
  for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
    const char *zFile = sqlite3PagerFilename(pBt->pPager);
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(zFile, -1));
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(pBt->nRef));
  }
  Tcl_SetObjResult(interp, pRet);
#endif
  return TCL_OK;
}

/*
** Print debugging information about all cursors to standard output.
*/
void sqlite3BtreeCursorList(Btree *p){
#ifdef SQLITE_DEBUG
  BtCursor *pCur;
  BtShared *pBt = p->pBt;
  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
    MemPage *pPage = pCur->apPage[pCur->iPage];
    char *zMode = pCur->wrFlag ? "rw" : "ro";
    sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
       pCur, pCur->pgnoRoot, zMode,
       pPage ? pPage->pgno : 0, pCur->aiIdx[pCur->iPage],
       (pCur->eState==CURSOR_VALID) ? "" : " eof"
    );
  }
#endif
}

Added src/test_config.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/*
** 2007 May 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** 
** This file contains code used for testing the SQLite system.
** None of the code in this file goes into a deliverable build.
** 
** The focus of this file is providing the TCL testing layer
** access to compile-time constants.
**
** $Id: test_config.c,v 1.50 2009/06/19 14:06:03 drh Exp $
*/

#include "sqliteLimit.h"

#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
** Macro to stringify the results of the evaluation a pre-processor
** macro. i.e. so that STRINGVALUE(SQLITE_NOMEM) -> "7".
*/
#define STRINGVALUE2(x) #x
#define STRINGVALUE(x) STRINGVALUE2(x)

/*
** This routine sets entries in the global ::sqlite_options() array variable
** according to the compile-time configuration of the database.  Test
** procedures use this to determine when tests should be omitted.
*/
static void set_options(Tcl_Interp *interp){
#ifdef SQLITE_32BIT_ROWID
  Tcl_SetVar2(interp, "sqlite_options", "rowid32", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "rowid32", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_CASE_SENSITIVE_LIKE
  Tcl_SetVar2(interp, "sqlite_options","casesensitivelike","1",TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options","casesensitivelike","0",TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_DEBUG
  Tcl_SetVar2(interp, "sqlite_options", "debug", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "debug", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_DISABLE_DIRSYNC
  Tcl_SetVar2(interp, "sqlite_options", "dirsync", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "dirsync", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_DISABLE_LFS
  Tcl_SetVar2(interp, "sqlite_options", "lfs", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "lfs", "1", TCL_GLOBAL_ONLY);
#endif

#if 1 /* def SQLITE_MEMDEBUG */
  Tcl_SetVar2(interp, "sqlite_options", "memdebug", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "memdebug", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_MEMSYS3
  Tcl_SetVar2(interp, "sqlite_options", "mem3", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "mem3", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_MEMSYS5
  Tcl_SetVar2(interp, "sqlite_options", "mem5", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "mem5", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_MUTEX_OMIT
  Tcl_SetVar2(interp, "sqlite_options", "mutex", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "mutex", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_ALTERTABLE
  Tcl_SetVar2(interp, "sqlite_options", "altertable", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "altertable", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_ANALYZE
  Tcl_SetVar2(interp, "sqlite_options", "analyze", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "analyze", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_ATOMIC_WRITE
  Tcl_SetVar2(interp, "sqlite_options", "atomicwrite", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "atomicwrite", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_ATTACH
  Tcl_SetVar2(interp, "sqlite_options", "attach", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "attach", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_AUTHORIZATION
  Tcl_SetVar2(interp, "sqlite_options", "auth", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "auth", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_AUTOINCREMENT
  Tcl_SetVar2(interp, "sqlite_options", "autoinc", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "autoinc", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_AUTOVACUUM
  Tcl_SetVar2(interp, "sqlite_options", "autovacuum", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "autovacuum", "1", TCL_GLOBAL_ONLY);
#endif /* SQLITE_OMIT_AUTOVACUUM */
#if !defined(SQLITE_DEFAULT_AUTOVACUUM)
  Tcl_SetVar2(interp,"sqlite_options","default_autovacuum","0",TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "default_autovacuum", 
      STRINGVALUE(SQLITE_DEFAULT_AUTOVACUUM), TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  Tcl_SetVar2(interp, "sqlite_options", "between_opt", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "between_opt", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_BUILTIN_TEST
  Tcl_SetVar2(interp, "sqlite_options", "builtin_test", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "builtin_test", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_BLOB_LITERAL
  Tcl_SetVar2(interp, "sqlite_options", "bloblit", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "bloblit", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_CAST
  Tcl_SetVar2(interp, "sqlite_options", "cast", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "cast", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_CHECK
  Tcl_SetVar2(interp, "sqlite_options", "check", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "check", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_COLUMN_METADATA
  Tcl_SetVar2(interp, "sqlite_options", "columnmetadata", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "columnmetadata", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  Tcl_SetVar2(interp, "sqlite_options", "oversize_cell_check", "1",
              TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "oversize_cell_check", "0",
              TCL_GLOBAL_ONLY);
#endif



#ifdef SQLITE_OMIT_COMPLETE
  Tcl_SetVar2(interp, "sqlite_options", "complete", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "complete", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_COMPOUND_SELECT
  Tcl_SetVar2(interp, "sqlite_options", "compound", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "compound", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_CONFLICT_CLAUSE
  Tcl_SetVar2(interp, "sqlite_options", "conflict", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "conflict", "1", TCL_GLOBAL_ONLY);
#endif

#if SQLITE_OS_UNIX
  Tcl_SetVar2(interp, "sqlite_options", "crashtest", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "crashtest", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_DATETIME_FUNCS
  Tcl_SetVar2(interp, "sqlite_options", "datetime", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "datetime", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_DECLTYPE
  Tcl_SetVar2(interp, "sqlite_options", "decltype", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "decltype", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_DEPRECATED
  Tcl_SetVar2(interp, "sqlite_options", "deprecated", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "deprecated", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_DISKIO
  Tcl_SetVar2(interp, "sqlite_options", "diskio", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "diskio", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_EXPLAIN
  Tcl_SetVar2(interp, "sqlite_options", "explain", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "explain", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_FLOATING_POINT
  Tcl_SetVar2(interp, "sqlite_options", "floatingpoint", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "floatingpoint", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_FOREIGN_KEY
  Tcl_SetVar2(interp, "sqlite_options", "foreignkey", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "foreignkey", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_FTS1
  Tcl_SetVar2(interp, "sqlite_options", "fts1", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "fts1", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_FTS2
  Tcl_SetVar2(interp, "sqlite_options", "fts2", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "fts2", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_FTS3
  Tcl_SetVar2(interp, "sqlite_options", "fts3", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "fts3", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_GET_TABLE
  Tcl_SetVar2(interp, "sqlite_options", "gettable", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "gettable", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_GLOBALRECOVER
  Tcl_SetVar2(interp, "sqlite_options", "globalrecover", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "globalrecover", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_ICU
  Tcl_SetVar2(interp, "sqlite_options", "icu", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "icu", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_INCRBLOB
  Tcl_SetVar2(interp, "sqlite_options", "incrblob", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "incrblob", "1", TCL_GLOBAL_ONLY);
#endif /* SQLITE_OMIT_AUTOVACUUM */

#ifdef SQLITE_OMIT_INTEGRITY_CHECK
  Tcl_SetVar2(interp, "sqlite_options", "integrityck", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "integrityck", "1", TCL_GLOBAL_ONLY);
#endif

#if defined(SQLITE_DEFAULT_FILE_FORMAT) && SQLITE_DEFAULT_FILE_FORMAT==1
  Tcl_SetVar2(interp, "sqlite_options", "legacyformat", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "legacyformat", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  Tcl_SetVar2(interp, "sqlite_options", "like_opt", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "like_opt", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_LOAD_EXTENSION
  Tcl_SetVar2(interp, "sqlite_options", "load_ext", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "load_ext", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_LOCALTIME
  Tcl_SetVar2(interp, "sqlite_options", "localtime", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "localtime", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_LOOKASIDE
  Tcl_SetVar2(interp, "sqlite_options", "lookaside", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "lookaside", "1", TCL_GLOBAL_ONLY);
#endif

Tcl_SetVar2(interp, "sqlite_options", "long_double",
              sizeof(LONGDOUBLE_TYPE)>sizeof(double) ? "1" : "0",
              TCL_GLOBAL_ONLY);

#ifdef SQLITE_OMIT_MEMORYDB
  Tcl_SetVar2(interp, "sqlite_options", "memorydb", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "memorydb", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  Tcl_SetVar2(interp, "sqlite_options", "memorymanage", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "memorymanage", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_OR_OPTIMIZATION
  Tcl_SetVar2(interp, "sqlite_options", "or_opt", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "or_opt", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_PAGER_PRAGMAS
  Tcl_SetVar2(interp, "sqlite_options", "pager_pragmas", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "pager_pragmas", "1", TCL_GLOBAL_ONLY);
#endif

#if defined(SQLITE_OMIT_PRAGMA) || defined(SQLITE_OMIT_FLAG_PRAGMAS)
  Tcl_SetVar2(interp, "sqlite_options", "pragma", "0", TCL_GLOBAL_ONLY);
  Tcl_SetVar2(interp, "sqlite_options", "integrityck", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "pragma", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  Tcl_SetVar2(interp, "sqlite_options", "progress", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "progress", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_REINDEX
  Tcl_SetVar2(interp, "sqlite_options", "reindex", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "reindex", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_RTREE
  Tcl_SetVar2(interp, "sqlite_options", "rtree", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "rtree", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  Tcl_SetVar2(interp, "sqlite_options", "schema_pragmas", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "schema_pragmas", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  Tcl_SetVar2(interp, "sqlite_options", "schema_version", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "schema_version", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_ENABLE_STAT2
  Tcl_SetVar2(interp, "sqlite_options", "stat2", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "stat2", "0", TCL_GLOBAL_ONLY);
#endif

#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
#  if defined(__APPLE__)
#    define SQLITE_ENABLE_LOCKING_STYLE 1
#  else
#    define SQLITE_ENABLE_LOCKING_STYLE 0
#  endif
#endif
#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  Tcl_SetVar2(interp,"sqlite_options","lock_proxy_pragmas","1",TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp,"sqlite_options","lock_proxy_pragmas","0",TCL_GLOBAL_ONLY);
#endif
#if defined(SQLITE_PREFER_PROXY_LOCKING) && defined(__APPLE__)
  Tcl_SetVar2(interp,"sqlite_options","prefer_proxy_locking","1",TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp,"sqlite_options","prefer_proxy_locking","0",TCL_GLOBAL_ONLY);
#endif
    
    
#ifdef SQLITE_OMIT_SHARED_CACHE
  Tcl_SetVar2(interp, "sqlite_options", "shared_cache", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "shared_cache", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_SUBQUERY
  Tcl_SetVar2(interp, "sqlite_options", "subquery", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "subquery", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_TCL_VARIABLE
  Tcl_SetVar2(interp, "sqlite_options", "tclvar", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "tclvar", "1", TCL_GLOBAL_ONLY);
#endif

  Tcl_SetVar2(interp, "sqlite_options", "threadsafe", 
      STRINGVALUE(SQLITE_THREADSAFE), TCL_GLOBAL_ONLY);
  assert( sqlite3_threadsafe()==SQLITE_THREADSAFE );

#ifdef SQLITE_OMIT_TEMPDB
  Tcl_SetVar2(interp, "sqlite_options", "tempdb", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "tempdb", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_TRACE
  Tcl_SetVar2(interp, "sqlite_options", "trace", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "trace", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_TRIGGER
  Tcl_SetVar2(interp, "sqlite_options", "trigger", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "trigger", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_TRUCATE_OPTIMIZATION
  Tcl_SetVar2(interp, "sqlite_options", "truncate_opt", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "truncate_opt", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_UTF16
  Tcl_SetVar2(interp, "sqlite_options", "utf16", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "utf16", "1", TCL_GLOBAL_ONLY);
#endif

#if defined(SQLITE_OMIT_VACUUM) || defined(SQLITE_OMIT_ATTACH)
  Tcl_SetVar2(interp, "sqlite_options", "vacuum", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "vacuum", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_VIEW
  Tcl_SetVar2(interp, "sqlite_options", "view", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "view", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_VIRTUALTABLE
  Tcl_SetVar2(interp, "sqlite_options", "vtab", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "vtab", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_WSD
  Tcl_SetVar2(interp, "sqlite_options", "wsd", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "wsd", "1", TCL_GLOBAL_ONLY);
#endif

#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  Tcl_SetVar2(interp, "sqlite_options", "update_delete_limit", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "update_delete_limit", "0", TCL_GLOBAL_ONLY);
#endif

#if defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
  Tcl_SetVar2(interp, "sqlite_options", "unlock_notify", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "unlock_notify", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_SECURE_DELETE
  Tcl_SetVar2(interp, "sqlite_options", "secure_delete", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "secure_delete", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef YYTRACKMAXSTACKDEPTH
  Tcl_SetVar2(interp, "sqlite_options", "yytrackmaxstackdepth", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "yytrackmaxstackdepth", "0", TCL_GLOBAL_ONLY);
#endif

#define LINKVAR(x) { \
    static const int cv_ ## x = SQLITE_ ## x; \
    Tcl_LinkVar(interp, "SQLITE_" #x, (char *)&(cv_ ## x), \
                TCL_LINK_INT | TCL_LINK_READ_ONLY); }

  LINKVAR( MAX_LENGTH );
  LINKVAR( MAX_COLUMN );
  LINKVAR( MAX_SQL_LENGTH );
  LINKVAR( MAX_EXPR_DEPTH );
  LINKVAR( MAX_COMPOUND_SELECT );
  LINKVAR( MAX_VDBE_OP );
  LINKVAR( MAX_FUNCTION_ARG );
  LINKVAR( MAX_VARIABLE_NUMBER );
  LINKVAR( MAX_PAGE_SIZE );
  LINKVAR( MAX_PAGE_COUNT );
  LINKVAR( MAX_LIKE_PATTERN_LENGTH );
  LINKVAR( MAX_TRIGGER_DEPTH );
  LINKVAR( DEFAULT_TEMP_CACHE_SIZE );
  LINKVAR( DEFAULT_CACHE_SIZE );
  LINKVAR( DEFAULT_PAGE_SIZE );
  LINKVAR( DEFAULT_FILE_FORMAT );
  LINKVAR( MAX_ATTACHED );

  {
    static const int cv_TEMP_STORE = SQLITE_TEMP_STORE;
    Tcl_LinkVar(interp, "TEMP_STORE", (char *)&(cv_TEMP_STORE),
                TCL_LINK_INT | TCL_LINK_READ_ONLY);
  }
}


/*
** Register commands with the TCL interpreter.
*/
int Sqliteconfig_Init(Tcl_Interp *interp){
  set_options(interp);
  return TCL_OK;
}

Added src/test_devsym.c.











































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
** 2008 Jan 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that modified the OS layer in order to simulate
** different device types (by overriding the return values of the 
** xDeviceCharacteristics() and xSectorSize() methods).
**
** $Id: test_devsym.c,v 1.9 2008/12/09 01:32:03 drh Exp $
*/
#if SQLITE_TEST          /* This file is used for testing only */

#include "sqlite3.h"
#include "sqliteInt.h"

/*
** Maximum pathname length supported by the devsym backend.
*/
#define DEVSYM_MAX_PATHNAME 512

/*
** Name used to identify this VFS.
*/
#define DEVSYM_VFS_NAME "devsym"

typedef struct devsym_file devsym_file;
struct devsym_file {
  sqlite3_file base;
  sqlite3_file *pReal;
};

/*
** Method declarations for devsym_file.
*/
static int devsymClose(sqlite3_file*);
static int devsymRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
static int devsymWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
static int devsymTruncate(sqlite3_file*, sqlite3_int64 size);
static int devsymSync(sqlite3_file*, int flags);
static int devsymFileSize(sqlite3_file*, sqlite3_int64 *pSize);
static int devsymLock(sqlite3_file*, int);
static int devsymUnlock(sqlite3_file*, int);
static int devsymCheckReservedLock(sqlite3_file*, int *);
static int devsymFileControl(sqlite3_file*, int op, void *pArg);
static int devsymSectorSize(sqlite3_file*);
static int devsymDeviceCharacteristics(sqlite3_file*);

/*
** Method declarations for devsym_vfs.
*/
static int devsymOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
static int devsymDelete(sqlite3_vfs*, const char *zName, int syncDir);
static int devsymAccess(sqlite3_vfs*, const char *zName, int flags, int *);
static int devsymFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
static void *devsymDlOpen(sqlite3_vfs*, const char *zFilename);
static void devsymDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
static void (*devsymDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
static void devsymDlClose(sqlite3_vfs*, void*);
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
static int devsymRandomness(sqlite3_vfs*, int nByte, char *zOut);
static int devsymSleep(sqlite3_vfs*, int microseconds);
static int devsymCurrentTime(sqlite3_vfs*, double*);

static sqlite3_vfs devsym_vfs = {
  1,                     /* iVersion */
  sizeof(devsym_file),      /* szOsFile */
  DEVSYM_MAX_PATHNAME,      /* mxPathname */
  0,                     /* pNext */
  DEVSYM_VFS_NAME,          /* zName */
  0,                     /* pAppData */
  devsymOpen,               /* xOpen */
  devsymDelete,             /* xDelete */
  devsymAccess,             /* xAccess */
  devsymFullPathname,       /* xFullPathname */
#ifndef SQLITE_OMIT_LOAD_EXTENSION
  devsymDlOpen,             /* xDlOpen */
  devsymDlError,            /* xDlError */
  devsymDlSym,              /* xDlSym */
  devsymDlClose,            /* xDlClose */
#else
  0,                        /* xDlOpen */
  0,                        /* xDlError */
  0,                        /* xDlSym */
  0,                        /* xDlClose */
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
  devsymRandomness,         /* xRandomness */
  devsymSleep,              /* xSleep */
  devsymCurrentTime         /* xCurrentTime */
};

static sqlite3_io_methods devsym_io_methods = {
  1,                            /* iVersion */
  devsymClose,                      /* xClose */
  devsymRead,                       /* xRead */
  devsymWrite,                      /* xWrite */
  devsymTruncate,                   /* xTruncate */
  devsymSync,                       /* xSync */
  devsymFileSize,                   /* xFileSize */
  devsymLock,                       /* xLock */
  devsymUnlock,                     /* xUnlock */
  devsymCheckReservedLock,          /* xCheckReservedLock */
  devsymFileControl,                /* xFileControl */
  devsymSectorSize,                 /* xSectorSize */
  devsymDeviceCharacteristics       /* xDeviceCharacteristics */
};

struct DevsymGlobal {
  sqlite3_vfs *pVfs;
  int iDeviceChar;
  int iSectorSize;
};
struct DevsymGlobal g = {0, 0, 512};

/*
** Close an devsym-file.
*/
static int devsymClose(sqlite3_file *pFile){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsClose(p->pReal);
}

/*
** Read data from an devsym-file.
*/
static int devsymRead(
  sqlite3_file *pFile, 
  void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
}

/*
** Write data to an devsym-file.
*/
static int devsymWrite(
  sqlite3_file *pFile, 
  const void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
}

/*
** Truncate an devsym-file.
*/
static int devsymTruncate(sqlite3_file *pFile, sqlite_int64 size){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsTruncate(p->pReal, size);
}

/*
** Sync an devsym-file.
*/
static int devsymSync(sqlite3_file *pFile, int flags){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsSync(p->pReal, flags);
}

/*
** Return the current file-size of an devsym-file.
*/
static int devsymFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsFileSize(p->pReal, pSize);
}

/*
** Lock an devsym-file.
*/
static int devsymLock(sqlite3_file *pFile, int eLock){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsLock(p->pReal, eLock);
}

/*
** Unlock an devsym-file.
*/
static int devsymUnlock(sqlite3_file *pFile, int eLock){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsUnlock(p->pReal, eLock);
}

/*
** Check if another file-handle holds a RESERVED lock on an devsym-file.
*/
static int devsymCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsCheckReservedLock(p->pReal, pResOut);
}

/*
** File control method. For custom operations on an devsym-file.
*/
static int devsymFileControl(sqlite3_file *pFile, int op, void *pArg){
  devsym_file *p = (devsym_file *)pFile;
  return sqlite3OsFileControl(p->pReal, op, pArg);
}

/*
** Return the sector-size in bytes for an devsym-file.
*/
static int devsymSectorSize(sqlite3_file *pFile){
  return g.iSectorSize;
}

/*
** Return the device characteristic flags supported by an devsym-file.
*/
static int devsymDeviceCharacteristics(sqlite3_file *pFile){
  return g.iDeviceChar;
}

/*
** Open an devsym file handle.
*/
static int devsymOpen(
  sqlite3_vfs *pVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  int rc;
  devsym_file *p = (devsym_file *)pFile;
  p->pReal = (sqlite3_file *)&p[1];
  rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags);
  if( p->pReal->pMethods ){
    pFile->pMethods = &devsym_io_methods;
  }
  return rc;
}

/*
** Delete the file located at zPath. If the dirSync argument is true,
** ensure the file-system modifications are synced to disk before
** returning.
*/
static int devsymDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  return sqlite3OsDelete(g.pVfs, zPath, dirSync);
}

/*
** Test for access permissions. Return true if the requested permission
** is available, or false otherwise.
*/
static int devsymAccess(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int flags, 
  int *pResOut
){
  return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut);
}

/*
** Populate buffer zOut with the full canonical pathname corresponding
** to the pathname in zPath. zOut is guaranteed to point to a buffer
** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
*/
static int devsymFullPathname(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int nOut, 
  char *zOut
){
  return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut);
}

#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** Open the dynamic library located at zPath and return a handle.
*/
static void *devsymDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  return sqlite3OsDlOpen(g.pVfs, zPath);
}

/*
** Populate the buffer zErrMsg (size nByte bytes) with a human readable
** utf-8 string describing the most recent error encountered associated 
** with dynamic libraries.
*/
static void devsymDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  sqlite3OsDlError(g.pVfs, nByte, zErrMsg);
}

/*
** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
*/
static void (*devsymDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  return sqlite3OsDlSym(g.pVfs, p, zSym);
}

/*
** Close the dynamic library handle pHandle.
*/
static void devsymDlClose(sqlite3_vfs *pVfs, void *pHandle){
  sqlite3OsDlClose(g.pVfs, pHandle);
}
#endif /* SQLITE_OMIT_LOAD_EXTENSION */

/*
** Populate the buffer pointed to by zBufOut with nByte bytes of 
** random data.
*/
static int devsymRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  return sqlite3OsRandomness(g.pVfs, nByte, zBufOut);
}

/*
** Sleep for nMicro microseconds. Return the number of microseconds 
** actually slept.
*/
static int devsymSleep(sqlite3_vfs *pVfs, int nMicro){
  return sqlite3OsSleep(g.pVfs, nMicro);
}

/*
** Return the current time as a Julian Day number in *pTimeOut.
*/
static int devsymCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  return sqlite3OsCurrentTime(g.pVfs, pTimeOut);
}

/*
** This procedure registers the devsym vfs with SQLite. If the argument is
** true, the devsym vfs becomes the new default vfs. It is the only publicly
** available function in this file.
*/
void devsym_register(int iDeviceChar, int iSectorSize){
  if( g.pVfs==0 ){
    g.pVfs = sqlite3_vfs_find(0);
    devsym_vfs.szOsFile += g.pVfs->szOsFile;
    sqlite3_vfs_register(&devsym_vfs, 0);
  }
  if( iDeviceChar>=0 ){
    g.iDeviceChar = iDeviceChar;
  }
  if( iSectorSize>=0 ){
    g.iSectorSize = iSectorSize;
  }
}

#endif

Added src/test_func.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
** 2008 March 19
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing all sorts of SQLite interfaces.  This code
** implements new SQL functions used by the test scripts.
**
** $Id: test_func.c,v 1.16 2009/07/22 07:27:57 danielk1977 Exp $
*/
#include "sqlite3.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>


/*
** Allocate nByte bytes of space using sqlite3_malloc(). If the
** allocation fails, call sqlite3_result_error_nomem() to notify
** the database handle that malloc() has failed.
*/
static void *testContextMalloc(sqlite3_context *context, int nByte){
  char *z = sqlite3_malloc(nByte);
  if( !z && nByte>0 ){
    sqlite3_result_error_nomem(context);
  }
  return z;
}

/*
** This function generates a string of random characters.  Used for
** generating test data.
*/
static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
  static const unsigned char zSrc[] = 
     "abcdefghijklmnopqrstuvwxyz"
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     "0123456789"
     ".-!,:*^+=_|?/<> ";
  int iMin, iMax, n, r, i;
  unsigned char zBuf[1000];

  /* It used to be possible to call randstr() with any number of arguments,
  ** but now it is registered with SQLite as requiring exactly 2.
  */
  assert(argc==2);

  iMin = sqlite3_value_int(argv[0]);
  if( iMin<0 ) iMin = 0;
  if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
  iMax = sqlite3_value_int(argv[1]);
  if( iMax<iMin ) iMax = iMin;
  if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
  n = iMin;
  if( iMax>iMin ){
    sqlite3_randomness(sizeof(r), &r);
    r &= 0x7fffffff;
    n += r%(iMax + 1 - iMin);
  }
  assert( n<sizeof(zBuf) );
  sqlite3_randomness(n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
}

/*
** The following two SQL functions are used to test returning a text
** result with a destructor. Function 'test_destructor' takes one argument
** and returns the same argument interpreted as TEXT. A destructor is
** passed with the sqlite3_result_text() call.
**
** SQL function 'test_destructor_count' returns the number of outstanding 
** allocations made by 'test_destructor';
**
** WARNING: Not threadsafe.
*/
static int test_destructor_count_var = 0;
static void destructor(void *p){
  char *zVal = (char *)p;
  assert(zVal);
  zVal--;
  sqlite3_free(zVal);
  test_destructor_count_var--;
}
static void test_destructor(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  char *zVal;
  int len;
  
  test_destructor_count_var++;
  assert( nArg==1 );
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  len = sqlite3_value_bytes(argv[0]); 
  zVal = testContextMalloc(pCtx, len+3);
  if( !zVal ){
    return;
  }
  zVal[len+1] = 0;
  zVal[len+2] = 0;
  zVal++;
  memcpy(zVal, sqlite3_value_text(argv[0]), len);
  sqlite3_result_text(pCtx, zVal, -1, destructor);
}
#ifndef SQLITE_OMIT_UTF16
static void test_destructor16(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  char *zVal;
  int len;
  
  test_destructor_count_var++;
  assert( nArg==1 );
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  len = sqlite3_value_bytes16(argv[0]); 
  zVal = testContextMalloc(pCtx, len+3);
  if( !zVal ){
    return;
  }
  zVal[len+1] = 0;
  zVal[len+2] = 0;
  zVal++;
  memcpy(zVal, sqlite3_value_text16(argv[0]), len);
  sqlite3_result_text16(pCtx, zVal, -1, destructor);
}
#endif
static void test_destructor_count(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  sqlite3_result_int(pCtx, test_destructor_count_var);
}

/*
** The following aggregate function, test_agg_errmsg16(), takes zero 
** arguments. It returns the text value returned by the sqlite3_errmsg16()
** API function.
*/
void sqlite3BeginBenignMalloc(void);
void sqlite3EndBenignMalloc(void);
static void test_agg_errmsg16_step(sqlite3_context *a, int b,sqlite3_value **c){
}
static void test_agg_errmsg16_final(sqlite3_context *ctx){
#ifndef SQLITE_OMIT_UTF16
  const void *z;
  sqlite3 * db = sqlite3_context_db_handle(ctx);
  sqlite3_aggregate_context(ctx, 2048);
  sqlite3BeginBenignMalloc();
  z = sqlite3_errmsg16(db);
  sqlite3EndBenignMalloc();
  sqlite3_result_text16(ctx, z, -1, SQLITE_TRANSIENT);
#endif
}

/*
** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
** interface.
**
** The test_auxdata() SQL function attempts to register each of its arguments
** as auxiliary data.  If there are no prior registrations of aux data for
** that argument (meaning the argument is not a constant or this is its first
** call) then the result for that argument is 0.  If there is a prior
** registration, the result for that argument is 1.  The overall result
** is the individual argument results separated by spaces.
*/
static void free_test_auxdata(void *p) {sqlite3_free(p);}
static void test_auxdata(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  int i;
  char *zRet = testContextMalloc(pCtx, nArg*2);
  if( !zRet ) return;
  memset(zRet, 0, nArg*2);
  for(i=0; i<nArg; i++){
    char const *z = (char*)sqlite3_value_text(argv[i]);
    if( z ){
      int n;
      char *zAux = sqlite3_get_auxdata(pCtx, i);
      if( zAux ){
        zRet[i*2] = '1';
        assert( strcmp(zAux,z)==0 );
      }else {
        zRet[i*2] = '0';
      }
      n = strlen(z) + 1;
      zAux = testContextMalloc(pCtx, n);
      if( zAux ){
        memcpy(zAux, z, n);
        sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
      }
      zRet[i*2+1] = ' ';
    }
  }
  sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
}

/*
** A function to test error reporting from user functions. This function
** returns a copy of its first argument as the error message.  If the
** second argument exists, it becomes the error code.
*/
static void test_error(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), -1);
  if( nArg==2 ){
    sqlite3_result_error_code(pCtx, sqlite3_value_int(argv[1]));
  }
}

/*
** Implementation of the counter(X) function.  If X is an integer
** constant, then the first invocation will return X.  The second X+1.
** and so forth.  Can be used (for example) to provide a sequence number
** in a result set.
*/
static void counterFunc(
  sqlite3_context *pCtx,   /* Function context */
  int nArg,                /* Number of function arguments */
  sqlite3_value **argv     /* Values for all function arguments */
){
  int *pCounter = (int*)sqlite3_get_auxdata(pCtx, 0);
  if( pCounter==0 ){
    pCounter = sqlite3_malloc( sizeof(*pCounter) );
    if( pCounter==0 ){
      sqlite3_result_error_nomem(pCtx);
      return;
    }
    *pCounter = sqlite3_value_int(argv[0]);
    sqlite3_set_auxdata(pCtx, 0, pCounter, sqlite3_free);
  }else{
    ++*pCounter;
  }
  sqlite3_result_int(pCtx, *pCounter);
}


/*
** This function takes two arguments.  It performance UTF-8/16 type
** conversions on the first argument then returns a copy of the second
** argument.
**
** This function is used in cases such as the following:
**
**      SELECT test_isolation(x,x) FROM t1;
**
** We want to verify that the type conversions that occur on the
** first argument do not invalidate the second argument.
*/
static void test_isolation(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
#ifndef SQLITE_OMIT_UTF16
  sqlite3_value_text16(argv[0]);
  sqlite3_value_text(argv[0]);
  sqlite3_value_text16(argv[0]);
  sqlite3_value_text(argv[0]);
#endif
  sqlite3_result_value(pCtx, argv[1]);
}

/*
** Invoke an SQL statement recursively.  The function result is the 
** first column of the first row of the result set.
*/
static void test_eval(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  sqlite3_stmt *pStmt;
  int rc;
  sqlite3 *db = sqlite3_context_db_handle(pCtx);
  const char *zSql;

  zSql = (char*)sqlite3_value_text(argv[0]);
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc==SQLITE_OK ){
    rc = sqlite3_step(pStmt);
    if( rc==SQLITE_ROW ){
      sqlite3_result_value(pCtx, sqlite3_column_value(pStmt, 0));
    }
    rc = sqlite3_finalize(pStmt);
  }
  if( rc ){
    char *zErr;
    assert( pStmt==0 );
    zErr = sqlite3_mprintf("sqlite3_prepare_v2() error: %s",sqlite3_errmsg(db));
    sqlite3_result_text(pCtx, zErr, -1, sqlite3_free);
    sqlite3_result_error_code(pCtx, rc);
  }
}


/*
** convert one character from hex to binary
*/
static int testHexChar(char c){
  if( c>='0' && c<='9' ){
    return c - '0';
  }else if( c>='a' && c<='f' ){
    return c - 'a' + 10;
  }else if( c>='A' && c<='F' ){
    return c - 'A' + 10;
  }
  return 0;
}

/*
** Convert hex to binary.
*/
static void testHexToBin(const char *zIn, char *zOut){
  while( zIn[0] && zIn[1] ){
    *(zOut++) = (testHexChar(zIn[0])<<4) + testHexChar(zIn[1]);
    zIn += 2;
  }
}

/*
**      hex_to_utf16be(HEX)
**
** Convert the input string from HEX into binary.  Then return the
** result using sqlite3_result_text16le().
*/
static void testHexToUtf16be(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite3_value_bytes(argv[0]);
  zIn = (const char*)sqlite3_value_text(argv[0]);
  zOut = sqlite3_malloc( n/2 );
  if( zOut==0 ){
    sqlite3_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite3_result_text16be(pCtx, zOut, n/2, sqlite3_free);
  }
}

/*
**      hex_to_utf8(HEX)
**
** Convert the input string from HEX into binary.  Then return the
** result using sqlite3_result_text16le().
*/
static void testHexToUtf8(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite3_value_bytes(argv[0]);
  zIn = (const char*)sqlite3_value_text(argv[0]);
  zOut = sqlite3_malloc( n/2 );
  if( zOut==0 ){
    sqlite3_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite3_result_text(pCtx, zOut, n/2, sqlite3_free);
  }
}

/*
**      hex_to_utf16le(HEX)
**
** Convert the input string from HEX into binary.  Then return the
** result using sqlite3_result_text16le().
*/
static void testHexToUtf16le(
  sqlite3_context *pCtx, 
  int nArg,
  sqlite3_value **argv
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite3_value_bytes(argv[0]);
  zIn = (const char*)sqlite3_value_text(argv[0]);
  zOut = sqlite3_malloc( n/2 );
  if( zOut==0 ){
    sqlite3_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite3_result_text16le(pCtx, zOut, n/2, sqlite3_free);
  }
}

static int registerTestFunctions(sqlite3 *db){
  static const struct {
     char *zName;
     signed char nArg;
     unsigned char eTextRep; /* 1: UTF-16.  0: UTF-8 */
     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
  } aFuncs[] = {
    { "randstr",               2, SQLITE_UTF8, randStr    },
    { "test_destructor",       1, SQLITE_UTF8, test_destructor},
#ifndef SQLITE_OMIT_UTF16
    { "test_destructor16",     1, SQLITE_UTF8, test_destructor16},
    { "hex_to_utf16be",        1, SQLITE_UTF8, testHexToUtf16be},
    { "hex_to_utf16le",        1, SQLITE_UTF8, testHexToUtf16le},
#endif
    { "hex_to_utf8",           1, SQLITE_UTF8, testHexToUtf8},
    { "test_destructor_count", 0, SQLITE_UTF8, test_destructor_count},
    { "test_auxdata",         -1, SQLITE_UTF8, test_auxdata},
    { "test_error",            1, SQLITE_UTF8, test_error},
    { "test_error",            2, SQLITE_UTF8, test_error},
    { "test_eval",             1, SQLITE_UTF8, test_eval},
    { "test_isolation",        2, SQLITE_UTF8, test_isolation},
    { "test_counter",          1, SQLITE_UTF8, counterFunc},
  };
  int i;

  for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
    sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
        aFuncs[i].eTextRep, 0, aFuncs[i].xFunc, 0, 0);
  }

  sqlite3_create_function(db, "test_agg_errmsg16", 0, SQLITE_ANY, 0, 0, 
      test_agg_errmsg16_step, test_agg_errmsg16_final);
      
  return SQLITE_OK;
}

/*
** TCLCMD:  autoinstall_test_functions
**
** Invoke this TCL command to use sqlite3_auto_extension() to cause
** the standard set of test functions to be loaded into each new
** database connection.
*/
static int autoinstall_test_funcs(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  extern int Md5_Register(sqlite3*);
  int rc = sqlite3_auto_extension((void*)registerTestFunctions);
  if( rc==SQLITE_OK ){
    rc = sqlite3_auto_extension((void*)Md5_Register);
  }
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;
}

/*
** A bogus step function and finalizer function.
*/
static void tStep(sqlite3_context *a, int b, sqlite3_value **c){}
static void tFinal(sqlite3_context *a){}


/*
** tclcmd:  abuse_create_function
**
** Make various calls to sqlite3_create_function that do not have valid
** parameters.  Verify that the error condition is detected and reported.
*/
static int abuse_create_function(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
  sqlite3 *db;
  int rc;
  int mxArg;

  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep,tStep,tFinal);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep, tStep, 0);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, tStep, 0, tFinal);
  if( rc!=SQLITE_MISUSE) goto abuse_err;

  rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, 0, 0, tFinal);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  rc = sqlite3_create_function(db, "tx", 1, SQLITE_UTF8, 0, 0, tStep, 0);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  rc = sqlite3_create_function(db, "tx", -2, SQLITE_UTF8, 0, tStep, 0, 0);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  rc = sqlite3_create_function(db, "tx", 128, SQLITE_UTF8, 0, tStep, 0, 0);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  rc = sqlite3_create_function(db, "funcxx"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789",
       1, SQLITE_UTF8, 0, tStep, 0, 0);
  if( rc!=SQLITE_MISUSE ) goto abuse_err;

  /* This last function registration should actually work.  Generate
  ** a no-op function (that always returns NULL) and which has the
  ** maximum-length function name and the maximum number of parameters.
  */
  sqlite3_limit(db, SQLITE_LIMIT_FUNCTION_ARG, 10000);
  mxArg = sqlite3_limit(db, SQLITE_LIMIT_FUNCTION_ARG, -1);
  rc = sqlite3_create_function(db, "nullx"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789"
       "_123456789_123456789_123456789_123456789_123456789",
       mxArg, SQLITE_UTF8, 0, tStep, 0, 0);
  if( rc!=SQLITE_OK ) goto abuse_err;
                                
  return TCL_OK;

abuse_err:
  Tcl_AppendResult(interp, "sqlite3_create_function abused test failed", 
                   (char*)0);
  return TCL_ERROR;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest_func_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
  } aObjCmd[] = {
     { "autoinstall_test_functions",    autoinstall_test_funcs },
     { "abuse_create_function",         abuse_create_function  },
  };
  int i;
  extern int Md5_Register(sqlite3*);

  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, 0, 0);
  }
  sqlite3_initialize();
  sqlite3_auto_extension((void*)registerTestFunctions);
  sqlite3_auto_extension((void*)Md5_Register);
  return TCL_OK;
}

Added src/test_hexio.c.













































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
** 2007 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing all sorts of SQLite interfaces.  This code
** implements TCL commands for reading and writing the binary
** database files and displaying the content of those files as
** hexadecimal.  We could, in theory, use the built-in "binary"
** command of TCL to do a lot of this, but there are some issues
** with historical versions of the "binary" command.  So it seems
** easier and safer to build our own mechanism.
**
** $Id: test_hexio.c,v 1.7 2008/05/12 16:17:42 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>


/*
** Convert binary to hex.  The input zBuf[] contains N bytes of
** binary data.  zBuf[] is 2*n+1 bytes long.  Overwrite zBuf[]
** with a hexadecimal representation of its original binary input.
*/
void sqlite3TestBinToHex(unsigned char *zBuf, int N){
  const unsigned char zHex[] = "0123456789ABCDEF";
  int i, j;
  unsigned char c;
  i = N*2;
  zBuf[i--] = 0;
  for(j=N-1; j>=0; j--){
    c = zBuf[j];
    zBuf[i--] = zHex[c&0xf];
    zBuf[i--] = zHex[c>>4];
  }
  assert( i==-1 );
}

/*
** Convert hex to binary.  The input zIn[] contains N bytes of
** hexadecimal.  Convert this into binary and write aOut[] with
** the binary data.  Spaces in the original input are ignored.
** Return the number of bytes of binary rendered.
*/
int sqlite3TestHexToBin(const unsigned char *zIn, int N, unsigned char *aOut){
  const unsigned char aMap[] = {
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     1, 2, 3, 4, 5, 6, 7, 8,  9,10, 0, 0, 0, 0, 0, 0,
     0,11,12,13,14,15,16, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0,11,12,13,14,15,16, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0,
  };
  int i, j;
  int hi=1;
  unsigned char c;

  for(i=j=0; i<N; i++){
    c = aMap[zIn[i]];
    if( c==0 ) continue;
    if( hi ){
      aOut[j] = (c-1)<<4;
      hi = 0;
    }else{
      aOut[j++] |= c-1;
      hi = 1;
    }
  }
  return j;
}


/*
** Usage:   hexio_read  FILENAME  OFFSET  AMT
**
** Read AMT bytes from file FILENAME beginning at OFFSET from the
** beginning of the file.  Convert that information to hexadecimal
** and return the resulting HEX string.
*/
static int hexio_read(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int offset;
  int amt, got;
  const char *zFile;
  unsigned char *zBuf;
  FILE *in;

  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME OFFSET AMT");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &offset) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &amt) ) return TCL_ERROR;
  zFile = Tcl_GetString(objv[1]);
  zBuf = sqlite3_malloc( amt*2+1 );
  if( zBuf==0 ){
    return TCL_ERROR;
  }
  in = fopen(zFile, "rb");
  if( in==0 ){
    in = fopen(zFile, "r");
  }
  if( in==0 ){
    Tcl_AppendResult(interp, "cannot open input file ", zFile, 0);
    return TCL_ERROR;
  }
  fseek(in, offset, SEEK_SET);
  got = fread(zBuf, 1, amt, in);
  fclose(in);
  if( got<0 ){
    got = 0;
  }
  sqlite3TestBinToHex(zBuf, got);
  Tcl_AppendResult(interp, zBuf, 0);
  sqlite3_free(zBuf);
  return TCL_OK;
}


/*
** Usage:   hexio_write  FILENAME  OFFSET  DATA
**
** Write DATA into file FILENAME beginning at OFFSET from the
** beginning of the file.  DATA is expressed in hexadecimal.
*/
static int hexio_write(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int offset;
  int nIn, nOut, written;
  const char *zFile;
  const unsigned char *zIn;
  unsigned char *aOut;
  FILE *out;

  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME OFFSET HEXDATA");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &offset) ) return TCL_ERROR;
  zFile = Tcl_GetString(objv[1]);
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[3], &nIn);
  aOut = sqlite3_malloc( nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite3TestHexToBin(zIn, nIn, aOut);
  out = fopen(zFile, "r+b");
  if( out==0 ){
    out = fopen(zFile, "r+");
  }
  if( out==0 ){
    Tcl_AppendResult(interp, "cannot open output file ", zFile, 0);
    return TCL_ERROR;
  }
  fseek(out, offset, SEEK_SET);
  written = fwrite(aOut, 1, nOut, out);
  sqlite3_free(aOut);
  fclose(out);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(written));
  return TCL_OK;
}

/*
** USAGE:   hexio_get_int   HEXDATA
**
** Interpret the HEXDATA argument as a big-endian integer.  Return
** the value of that integer.  HEXDATA can contain between 2 and 8
** hexadecimal digits.
*/
static int hexio_get_int(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int val;
  int nIn, nOut;
  const unsigned char *zIn;
  unsigned char *aOut;
  unsigned char aNum[4];

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEXDATA");
    return TCL_ERROR;
  }
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[1], &nIn);
  aOut = sqlite3_malloc( nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite3TestHexToBin(zIn, nIn, aOut);
  if( nOut>=4 ){
    memcpy(aNum, aOut, 4);
  }else{
    memset(aNum, 0, sizeof(aNum));
    memcpy(&aNum[4-nOut], aOut, nOut);
  }
  sqlite3_free(aOut);
  val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3];
  Tcl_SetObjResult(interp, Tcl_NewIntObj(val));
  return TCL_OK;
}


/*
** USAGE:   hexio_render_int16   INTEGER
**
** Render INTEGER has a 16-bit big-endian integer in hexadecimal.
*/
static int hexio_render_int16(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int val;
  unsigned char aNum[10];

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "INTEGER");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &val) ) return TCL_ERROR;
  aNum[0] = val>>8;
  aNum[1] = val;
  sqlite3TestBinToHex(aNum, 2);
  Tcl_SetObjResult(interp, Tcl_NewStringObj((char*)aNum, 4));
  return TCL_OK;
}


/*
** USAGE:   hexio_render_int32   INTEGER
**
** Render INTEGER has a 32-bit big-endian integer in hexadecimal.
*/
static int hexio_render_int32(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int val;
  unsigned char aNum[10];

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "INTEGER");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &val) ) return TCL_ERROR;
  aNum[0] = val>>24;
  aNum[1] = val>>16;
  aNum[2] = val>>8;
  aNum[3] = val;
  sqlite3TestBinToHex(aNum, 4);
  Tcl_SetObjResult(interp, Tcl_NewStringObj((char*)aNum, 8));
  return TCL_OK;
}

/*
** USAGE:  utf8_to_utf8  HEX
**
** The argument is a UTF8 string represented in hexadecimal.
** The UTF8 might not be well-formed.  Run this string through
** sqlite3Utf8to8() convert it back to hex and return the result.
*/
static int utf8_to_utf8(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifdef SQLITE_DEBUG
  int n;
  int nOut;
  const unsigned char *zOrig;
  unsigned char *z;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEX");
    return TCL_ERROR;
  }
  zOrig = (unsigned char *)Tcl_GetStringFromObj(objv[1], &n);
  z = sqlite3_malloc( n+3 );
  n = sqlite3TestHexToBin(zOrig, n, z);
  z[n] = 0;
  nOut = sqlite3Utf8To8(z);
  sqlite3TestBinToHex(z,nOut);
  Tcl_AppendResult(interp, (char*)z, 0);
  sqlite3_free(z);
#endif
  return TCL_OK;
}


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest_hexio_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
  } aObjCmd[] = {
     { "hexio_read",                   hexio_read            },
     { "hexio_write",                  hexio_write           },
     { "hexio_get_int",                hexio_get_int         },
     { "hexio_render_int16",           hexio_render_int16    },
     { "hexio_render_int32",           hexio_render_int32    },
     { "utf8_to_utf8",                 utf8_to_utf8          },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, 0, 0);
  }
  return TCL_OK;
}

Added src/test_init.c.

































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
** 2009 August 17
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** The code in this file is used for testing SQLite. It is not part of
** the source code used in production systems.
**
** Specifically, this file tests the effect of errors while initializing
** the various pluggable sub-systems from within sqlite3_initialize().
** If an error occurs in sqlite3_initialize() the following should be
** true:
**
**   1) An error code is returned to the user, and
**   2) A subsequent call to sqlite3_shutdown() calls the shutdown method
**      of those subsystems that were initialized, and
**   3) A subsequent call to sqlite3_initialize() attempts to initialize
**      the remaining, uninitialized, subsystems.
*/

#include "sqliteInt.h"
#include <string.h>
#include <tcl.h>

static struct Wrapped {
  sqlite3_pcache_methods pcache;
  sqlite3_mem_methods    mem;
  sqlite3_mutex_methods  mutex;

  int mem_init;                /* True if mem subsystem is initalized */
  int mem_fail;                /* True to fail mem subsystem inialization */
  int mutex_init;              /* True if mutex subsystem is initalized */
  int mutex_fail;              /* True to fail mutex subsystem inialization */
  int pcache_init;             /* True if pcache subsystem is initalized */
  int pcache_fail;             /* True to fail pcache subsystem inialization */
} wrapped;

static int wrMemInit(void *pAppData){
  int rc;
  if( wrapped.mem_fail ){
    rc = SQLITE_ERROR;
  }else{
    rc = wrapped.mem.xInit(wrapped.mem.pAppData);
  }
  if( rc==SQLITE_OK ){
    wrapped.mem_init = 1;
  }
  return rc;
}
static void wrMemShutdown(void *pAppData){
  wrapped.mem.xShutdown(wrapped.mem.pAppData);
  wrapped.mem_init = 0;
}
static void *wrMemMalloc(int n)           {return wrapped.mem.xMalloc(n);}
static void wrMemFree(void *p)            {wrapped.mem.xFree(p);}
static void *wrMemRealloc(void *p, int n) {return wrapped.mem.xRealloc(p, n);}
static int wrMemSize(void *p)             {return wrapped.mem.xSize(p);}
static int wrMemRoundup(int n)            {return wrapped.mem.xRoundup(n);}


static int wrMutexInit(void){
  int rc;
  if( wrapped.mutex_fail ){
    rc = SQLITE_ERROR;
  }else{
    rc = wrapped.mutex.xMutexInit();
  }
  if( rc==SQLITE_OK ){
    wrapped.mutex_init = 1;
  }
  return rc;
}
static int wrMutexEnd(void){
  wrapped.mutex.xMutexEnd();
  wrapped.mutex_init = 0;
  return SQLITE_OK;
}
static sqlite3_mutex *wrMutexAlloc(int e){
  return wrapped.mutex.xMutexAlloc(e);
}
static void wrMutexFree(sqlite3_mutex *p){
  wrapped.mutex.xMutexFree(p);
}
static void wrMutexEnter(sqlite3_mutex *p){
  wrapped.mutex.xMutexEnter(p);
}
static int wrMutexTry(sqlite3_mutex *p){
  return wrapped.mutex.xMutexTry(p);
}
static void wrMutexLeave(sqlite3_mutex *p){
  wrapped.mutex.xMutexLeave(p);
}
static int wrMutexHeld(sqlite3_mutex *p){
  return wrapped.mutex.xMutexHeld(p);
}
static int wrMutexNotheld(sqlite3_mutex *p){
  return wrapped.mutex.xMutexNotheld(p);
}



static int wrPCacheInit(void *pArg){
  int rc;
  if( wrapped.pcache_fail ){
    rc = SQLITE_ERROR;
  }else{
    rc = wrapped.pcache.xInit(wrapped.pcache.pArg);
  }
  if( rc==SQLITE_OK ){
    wrapped.pcache_init = 1;
  }
  return rc;
}
static void wrPCacheShutdown(void *pArg){
  wrapped.pcache.xShutdown(wrapped.pcache.pArg);
  wrapped.pcache_init = 0;
}

static sqlite3_pcache *wrPCacheCreate(int a, int b){
  return wrapped.pcache.xCreate(a, b);
}  
static void wrPCacheCachesize(sqlite3_pcache *p, int n){
  wrapped.pcache.xCachesize(p, n);
}  
static int wrPCachePagecount(sqlite3_pcache *p){
  return wrapped.pcache.xPagecount(p);
}  
static void *wrPCacheFetch(sqlite3_pcache *p, unsigned a, int b){
  return wrapped.pcache.xFetch(p, a, b);
}  
static void wrPCacheUnpin(sqlite3_pcache *p, void *a, int b){
  wrapped.pcache.xUnpin(p, a, b);
}  
static void wrPCacheRekey(sqlite3_pcache *p, void *a, unsigned b, unsigned c){
  wrapped.pcache.xRekey(p, a, b, c);
}  
static void wrPCacheTruncate(sqlite3_pcache *p, unsigned a){
  wrapped.pcache.xTruncate(p, a);
}  
static void wrPCacheDestroy(sqlite3_pcache *p){
  wrapped.pcache.xDestroy(p);
}  

static void installInitWrappers(void){
  sqlite3_mutex_methods mutexmethods = {
    wrMutexInit,  wrMutexEnd,   wrMutexAlloc,
    wrMutexFree,  wrMutexEnter, wrMutexTry,
    wrMutexLeave, wrMutexHeld,  wrMutexNotheld
  };
  sqlite3_pcache_methods pcachemethods = {
    0,
    wrPCacheInit,      wrPCacheShutdown,  wrPCacheCreate, 
    wrPCacheCachesize, wrPCachePagecount, wrPCacheFetch,
    wrPCacheUnpin,     wrPCacheRekey,     wrPCacheTruncate,  
    wrPCacheDestroy
  };
  sqlite3_mem_methods memmethods = {
    wrMemMalloc,   wrMemFree,    wrMemRealloc,
    wrMemSize,     wrMemRoundup, wrMemInit,
    wrMemShutdown,
    0
  };

  memset(&wrapped, 0, sizeof(wrapped));

  sqlite3_shutdown();
  sqlite3_config(SQLITE_CONFIG_GETMUTEX, &wrapped.mutex);
  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &wrapped.mem);
  sqlite3_config(SQLITE_CONFIG_GETPCACHE, &wrapped.pcache);
  sqlite3_config(SQLITE_CONFIG_MUTEX, &mutexmethods);
  sqlite3_config(SQLITE_CONFIG_MALLOC, &memmethods);
  sqlite3_config(SQLITE_CONFIG_PCACHE, &pcachemethods);
}

static int init_wrapper_install(
  ClientData clientData, /* Unused */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int i;
  installInitWrappers();
  for(i=1; i<objc; i++){
    char *z = Tcl_GetString(objv[i]);
    if( strcmp(z, "mem")==0 ){
      wrapped.mem_fail = 1;
    }else if( strcmp(z, "mutex")==0 ){
      wrapped.mutex_fail = 1;
    }else if( strcmp(z, "pcache")==0 ){
      wrapped.pcache_fail = 1;
    }else{
      Tcl_AppendResult(interp, "Unknown argument: \"", z, "\"");
      return TCL_ERROR;
    }
  }
  return TCL_OK;
}

static int init_wrapper_uninstall(
  ClientData clientData, /* Unused */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  memset(&wrapped, 0, sizeof(&wrapped));
  sqlite3_shutdown();
  sqlite3_config(SQLITE_CONFIG_MUTEX, &wrapped.mutex);
  sqlite3_config(SQLITE_CONFIG_MALLOC, &wrapped.mem);
  sqlite3_config(SQLITE_CONFIG_PCACHE, &wrapped.pcache);
  return TCL_OK;
}

static int init_wrapper_clear(
  ClientData clientData, /* Unused */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  wrapped.mem_fail = 0;
  wrapped.mutex_fail = 0;
  wrapped.pcache_fail = 0;
  return TCL_OK;
}

static int init_wrapper_query(
  ClientData clientData, /* Unused */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  Tcl_Obj *pRet;

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  pRet = Tcl_NewObj();
  if( wrapped.mutex_init ){
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("mutex", -1));
  }
  if( wrapped.mem_init ){
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("mem", -1));
  }
  if( wrapped.pcache_init ){
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("pcache", -1));
  }

  Tcl_SetObjResult(interp, pRet);
  return TCL_OK;
}

int Sqlitetest_init_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
  } aObjCmd[] = {
    {"init_wrapper_install",   init_wrapper_install},
    {"init_wrapper_query",     init_wrapper_query  },
    {"init_wrapper_uninstall", init_wrapper_uninstall},
    {"init_wrapper_clear",     init_wrapper_clear}
  };
  int i;

  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, 0, 0);
  }

  return TCL_OK;
}

Added src/test_journal.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*
** 2008 Jan 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code for a VFS layer that acts as a wrapper around
** an existing VFS. The code in this file attempts to verify that SQLite
** correctly populates and syncs a journal file before writing to a
** corresponding database file.
**
** $Id: test_journal.c,v 1.17 2009/06/26 10:39:36 danielk1977 Exp $
*/
#if SQLITE_TEST          /* This file is used for testing only */

#include "sqlite3.h"
#include "sqliteInt.h"

/*
** INTERFACE
**
**   The public interface to this wrapper VFS is two functions:
**
**     jt_register()
**     jt_unregister()
**
**   See header comments associated with those two functions below for 
**   details.
**
** LIMITATIONS
**
**   This wrapper will not work if "PRAGMA synchronous = off" is used.
**
** OPERATION
**
**  Starting a Transaction:
**
**   When a write-transaction is started, the contents of the database is
**   inspected and the following data stored as part of the database file 
**   handle (type struct jt_file):
**
**     a) The page-size of the database file.
**     b) The number of pages that are in the database file.
**     c) The set of page numbers corresponding to free-list leaf pages.
**     d) A check-sum for every page in the database file.
**
**   The start of a write-transaction is deemed to have occurred when a 
**   28-byte journal header is written to byte offset 0 of the journal 
**   file.
**
**  Syncing the Journal File:
**
**   Whenever the xSync method is invoked to sync a journal-file, the
**   contents of the journal file are read. For each page written to
**   the journal file, a check-sum is calculated and compared to the  
**   check-sum calculated for the corresponding database page when the
**   write-transaction was initialized. The success of the comparison
**   is assert()ed. So if SQLite has written something other than the
**   original content to the database file, an assert() will fail.
**
**   Additionally, the set of page numbers for which records exist in
**   the journal file is added to (unioned with) the set of page numbers
**   corresponding to free-list leaf pages collected when the 
**   write-transaction was initialized. This set comprises the page-numbers 
**   corresponding to those pages that SQLite may now safely modify.
**
**  Writing to the Database File:
**
**   When a block of data is written to a database file, the following
**   invariants are asserted:
**
**     a) That the block of data is an aligned block of page-size bytes.
**
**     b) That if the page being written did not exist when the 
**        transaction was started (i.e. the database file is growing), then
**        the journal-file must have been synced at least once since
**        the start of the transaction.
**
**     c) That if the page being written did exist when the transaction 
**        was started, then the page must have either been a free-list
**        leaf page at the start of the transaction, or else must have
**        been stored in the journal file prior to the most recent sync.
**
**  Closing a Transaction:
**
**   When a transaction is closed, all data collected at the start of
**   the transaction, or following an xSync of a journal-file, is 
**   discarded. The end of a transaction is recognized when any one 
**   of the following occur:
**
**     a) A block of zeroes (or anything else that is not a valid 
**        journal-header) is written to the start of the journal file.
**
**     b) A journal file is truncated to zero bytes in size using xTruncate.
**
**     c) The journal file is deleted using xDelete.
*/

/*
** Maximum pathname length supported by the jt backend.
*/
#define JT_MAX_PATHNAME 512

/*
** Name used to identify this VFS.
*/
#define JT_VFS_NAME "jt"

typedef struct jt_file jt_file;
struct jt_file {
  sqlite3_file base;
  const char *zName;       /* Name of open file */
  int flags;               /* Flags the file was opened with */

  /* The following are only used by database file file handles */
  int eLock;               /* Current lock held on the file */
  u32 nPage;               /* Size of file in pages when transaction started */
  u32 nPagesize;           /* Page size when transaction started */
  Bitvec *pWritable;       /* Bitvec of pages that may be written to the file */
  u32 *aCksum;             /* Checksum for first nPage pages */
  int nSync;               /* Number of times journal file has been synced */

  /* Only used by journal file-handles */
  sqlite3_int64 iMaxOff;   /* Maximum offset written to this transaction */

  jt_file *pNext;          /* All files are stored in a linked list */
  sqlite3_file *pReal;     /* The file handle for the underlying vfs */
};

/*
** Method declarations for jt_file.
*/
static int jtClose(sqlite3_file*);
static int jtRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
static int jtWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
static int jtTruncate(sqlite3_file*, sqlite3_int64 size);
static int jtSync(sqlite3_file*, int flags);
static int jtFileSize(sqlite3_file*, sqlite3_int64 *pSize);
static int jtLock(sqlite3_file*, int);
static int jtUnlock(sqlite3_file*, int);
static int jtCheckReservedLock(sqlite3_file*, int *);
static int jtFileControl(sqlite3_file*, int op, void *pArg);
static int jtSectorSize(sqlite3_file*);
static int jtDeviceCharacteristics(sqlite3_file*);

/*
** Method declarations for jt_vfs.
*/
static int jtOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
static int jtDelete(sqlite3_vfs*, const char *zName, int syncDir);
static int jtAccess(sqlite3_vfs*, const char *zName, int flags, int *);
static int jtFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
static void *jtDlOpen(sqlite3_vfs*, const char *zFilename);
static void jtDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
static void (*jtDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
static void jtDlClose(sqlite3_vfs*, void*);
static int jtRandomness(sqlite3_vfs*, int nByte, char *zOut);
static int jtSleep(sqlite3_vfs*, int microseconds);
static int jtCurrentTime(sqlite3_vfs*, double*);

static sqlite3_vfs jt_vfs = {
  1,                             /* iVersion */
  sizeof(jt_file),               /* szOsFile */
  JT_MAX_PATHNAME,               /* mxPathname */
  0,                             /* pNext */
  JT_VFS_NAME,                   /* zName */
  0,                             /* pAppData */
  jtOpen,                        /* xOpen */
  jtDelete,                      /* xDelete */
  jtAccess,                      /* xAccess */
  jtFullPathname,                /* xFullPathname */
  jtDlOpen,                      /* xDlOpen */
  jtDlError,                     /* xDlError */
  jtDlSym,                       /* xDlSym */
  jtDlClose,                     /* xDlClose */
  jtRandomness,                  /* xRandomness */
  jtSleep,                       /* xSleep */
  jtCurrentTime                  /* xCurrentTime */
};

static sqlite3_io_methods jt_io_methods = {
  1,                             /* iVersion */
  jtClose,                       /* xClose */
  jtRead,                        /* xRead */
  jtWrite,                       /* xWrite */
  jtTruncate,                    /* xTruncate */
  jtSync,                        /* xSync */
  jtFileSize,                    /* xFileSize */
  jtLock,                        /* xLock */
  jtUnlock,                      /* xUnlock */
  jtCheckReservedLock,           /* xCheckReservedLock */
  jtFileControl,                 /* xFileControl */
  jtSectorSize,                  /* xSectorSize */
  jtDeviceCharacteristics        /* xDeviceCharacteristics */
};

struct JtGlobal {
  sqlite3_vfs *pVfs;             /* Parent VFS */
  jt_file *pList;                /* List of all open files */
};
static struct JtGlobal g = {0, 0};

/*
** Functions to obtain and relinquish a mutex to protect g.pList. The
** STATIC_PRNG mutex is reused, purely for the sake of convenience.
*/
static void enterJtMutex(void){
  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG));
}
static void leaveJtMutex(void){
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG));
}

extern int sqlite3_io_error_pending;
extern int sqlite3_io_error_hit;
static void stop_ioerr_simulation(int *piSave, int *piSave2){
  *piSave = sqlite3_io_error_pending;
  *piSave2 = sqlite3_io_error_hit;
  sqlite3_io_error_pending = -1;
  sqlite3_io_error_hit = 0;
}
static void start_ioerr_simulation(int iSave, int iSave2){
  sqlite3_io_error_pending = iSave;
  sqlite3_io_error_hit = iSave2;
}

/*
** The jt_file pointed to by the argument may or may not be a file-handle
** open on a main database file. If it is, and a transaction is currently
** opened on the file, then discard all transaction related data.
*/
static void closeTransaction(jt_file *p){
  sqlite3BitvecDestroy(p->pWritable);
  sqlite3_free(p->aCksum);
  p->pWritable = 0;
  p->aCksum = 0;
  p->nSync = 0;
}

/*
** Close an jt-file.
*/
static int jtClose(sqlite3_file *pFile){
  jt_file **pp;
  jt_file *p = (jt_file *)pFile;

  closeTransaction(p);
  enterJtMutex();
  if( p->zName ){
    for(pp=&g.pList; *pp!=p; pp=&(*pp)->pNext);
    *pp = p->pNext;
  }
  leaveJtMutex();
  return sqlite3OsClose(p->pReal);
}

/*
** Read data from an jt-file.
*/
static int jtRead(
  sqlite3_file *pFile, 
  void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  jt_file *p = (jt_file *)pFile;
  return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
}

/*
** Parameter zJournal is the name of a journal file that is currently 
** open. This function locates and returns the handle opened on the
** corresponding database file by the pager that currently has the
** journal file opened. This file-handle is identified by the 
** following properties:
**
**   a) SQLITE_OPEN_MAIN_DB was specified when the file was opened.
**
**   b) The file-name specified when the file was opened matches
**      all but the final 8 characters of the journal file name.
**
**   c) There is currently a reserved lock on the file.
**/
static jt_file *locateDatabaseHandle(const char *zJournal){
  jt_file *pMain = 0;
  enterJtMutex();
  for(pMain=g.pList; pMain; pMain=pMain->pNext){
    int nName = strlen(zJournal) - strlen("-journal");
    if( (pMain->flags&SQLITE_OPEN_MAIN_DB)
     && (strlen(pMain->zName)==nName)
     && 0==memcmp(pMain->zName, zJournal, nName)
     && (pMain->eLock>=SQLITE_LOCK_RESERVED)
    ){
      break;
    }
  }
  leaveJtMutex();
  return pMain;
}

/*
** Parameter z points to a buffer of 4 bytes in size containing a 
** unsigned 32-bit integer stored in big-endian format. Decode the 
** integer and return its value.
*/
static u32 decodeUint32(const unsigned char *z){
  return (z[0]<<24) + (z[1]<<16) + (z[2]<<8) + z[3];
}

/*
** Calculate a checksum from the buffer of length n bytes pointed to
** by parameter z.
*/
static u32 genCksum(const unsigned char *z, int n){
  int i;
  u32 cksum = 0;
  for(i=0; i<n; i++){
    cksum = cksum + z[i] + (cksum<<3);
  }
  return cksum;
}

/*
** The first argument, zBuf, points to a buffer containing a 28 byte
** serialized journal header. This function deserializes four of the
** integer fields contained in the journal header and writes their
** values to the output variables.
**
** SQLITE_OK is returned if the journal-header is successfully 
** decoded. Otherwise, SQLITE_ERROR.
*/
static int decodeJournalHdr(
  const unsigned char *zBuf,         /* Input: 28 byte journal header */
  u32 *pnRec,                        /* Out: Number of journalled records */
  u32 *pnPage,                       /* Out: Original database page count */
  u32 *pnSector,                     /* Out: Sector size in bytes */
  u32 *pnPagesize                    /* Out: Page size in bytes */
){
  unsigned char aMagic[] = { 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7 };
  if( memcmp(aMagic, zBuf, 8) ) return SQLITE_ERROR;
  if( pnRec ) *pnRec = decodeUint32(&zBuf[8]);
  if( pnPage ) *pnPage = decodeUint32(&zBuf[16]);
  if( pnSector ) *pnSector = decodeUint32(&zBuf[20]);
  if( pnPagesize ) *pnPagesize = decodeUint32(&zBuf[24]);
  return SQLITE_OK;
}

/*
** This function is called when a new transaction is opened, just after
** the first journal-header is written to the journal file.
*/
static int openTransaction(jt_file *pMain, jt_file *pJournal){
  unsigned char *aData;
  sqlite3_file *p = pMain->pReal;
  int rc = SQLITE_OK;

  aData = sqlite3_malloc(pMain->nPagesize);
  pMain->pWritable = sqlite3BitvecCreate(pMain->nPage);
  pMain->aCksum = sqlite3_malloc(sizeof(u32) * (pMain->nPage + 1));
  pJournal->iMaxOff = 0;

  if( !pMain->pWritable || !pMain->aCksum || !aData ){
    rc = SQLITE_IOERR_NOMEM;
  }else if( pMain->nPage>0 ){
    u32 iTrunk;
    int iSave;
    int iSave2;

    stop_ioerr_simulation(&iSave, &iSave2);

    /* Read the database free-list. Add the page-number for each free-list
    ** leaf to the jt_file.pWritable bitvec.
    */
    rc = sqlite3OsRead(p, aData, pMain->nPagesize, 0);
    iTrunk = decodeUint32(&aData[32]);
    while( rc==SQLITE_OK && iTrunk>0 ){
      u32 nLeaf;
      u32 iLeaf;
      sqlite3_int64 iOff = (iTrunk-1)*pMain->nPagesize;
      rc = sqlite3OsRead(p, aData, pMain->nPagesize, iOff);
      nLeaf = decodeUint32(&aData[4]);
      for(iLeaf=0; rc==SQLITE_OK && iLeaf<nLeaf; iLeaf++){
        u32 pgno = decodeUint32(&aData[8+4*iLeaf]);
        sqlite3BitvecSet(pMain->pWritable, pgno);
      }
      iTrunk = decodeUint32(aData);
    }

    /* Calculate and store a checksum for each page in the database file. */
    if( rc==SQLITE_OK ){
      int ii;
      for(ii=0; rc==SQLITE_OK && ii<pMain->nPage; ii++){
        i64 iOff = (i64)(pMain->nPagesize) * (i64)ii;
        if( iOff==PENDING_BYTE ) continue;
        rc = sqlite3OsRead(pMain->pReal, aData, pMain->nPagesize, iOff);
        pMain->aCksum[ii] = genCksum(aData, pMain->nPagesize);
      }
    }

    start_ioerr_simulation(iSave, iSave2);
  }

  sqlite3_free(aData);
  return rc;
}

/*
** The first argument to this function is a handle open on a journal file.
** This function reads the journal file and adds the page number for each
** page in the journal to the Bitvec object passed as the second argument.
*/
static int readJournalFile(jt_file *p, jt_file *pMain){
  int rc = SQLITE_OK;
  unsigned char zBuf[28];
  sqlite3_file *pReal = p->pReal;
  sqlite3_int64 iOff = 0;
  sqlite3_int64 iSize = p->iMaxOff;
  unsigned char *aPage;
  int iSave;
  int iSave2;

  aPage = sqlite3_malloc(pMain->nPagesize);
  if( !aPage ){
    return SQLITE_IOERR_NOMEM;
  }

  stop_ioerr_simulation(&iSave, &iSave2);

  while( rc==SQLITE_OK && iOff<iSize ){
    u32 nRec, nPage, nSector, nPagesize;
    u32 ii;

    /* Read and decode the next journal-header from the journal file. */
    rc = sqlite3OsRead(pReal, zBuf, 28, iOff);
    if( rc!=SQLITE_OK 
     || decodeJournalHdr(zBuf, &nRec, &nPage, &nSector, &nPagesize) 
    ){
      goto finish_rjf;
    }
    iOff += nSector;

    if( nRec==0 ){
      /* A trick. There might be another journal-header immediately 
      ** following this one. In this case, 0 records means 0 records, 
      ** not "read until the end of the file". See also ticket #2565.
      */
      if( iSize>=(iOff+nSector) ){
        rc = sqlite3OsRead(pReal, zBuf, 28, iOff);
        if( rc!=SQLITE_OK || 0==decodeJournalHdr(zBuf, 0, 0, 0, 0) ){
          continue;
        }
      }
      nRec = (iSize-iOff) / (pMain->nPagesize+8);
    }

    /* Read all the records that follow the journal-header just read. */
    for(ii=0; rc==SQLITE_OK && ii<nRec && iOff<iSize; ii++){
      u32 pgno;
      rc = sqlite3OsRead(pReal, zBuf, 4, iOff);
      if( rc==SQLITE_OK ){
        pgno = decodeUint32(zBuf);
        if( pgno>0 && pgno<=pMain->nPage ){
          if( 0==sqlite3BitvecTest(pMain->pWritable, pgno) ){
            rc = sqlite3OsRead(pReal, aPage, pMain->nPagesize, iOff+4);
            if( rc==SQLITE_OK ){
              u32 cksum = genCksum(aPage, pMain->nPagesize);
              assert( cksum==pMain->aCksum[pgno-1] );
            }
          }
          sqlite3BitvecSet(pMain->pWritable, pgno);
        }
        iOff += (8 + pMain->nPagesize);
      }
    }

    iOff = ((iOff + (nSector-1)) / nSector) * nSector;
  }

finish_rjf:
  start_ioerr_simulation(iSave, iSave2);
  sqlite3_free(aPage);
  if( rc==SQLITE_IOERR_SHORT_READ ){
    rc = SQLITE_OK;
  }
  return rc;
}


/*
** Write data to an jt-file.
*/
static int jtWrite(
  sqlite3_file *pFile, 
  const void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  int rc;
  jt_file *p = (jt_file *)pFile;
  if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){
    if( iOfst==0 ){
      jt_file *pMain = locateDatabaseHandle(p->zName);
      assert( pMain );
  
      if( iAmt==28 ){
        /* Zeroing the first journal-file header. This is the end of a
        ** transaction. */
        closeTransaction(pMain);
      }else if( iAmt!=12 ){
        /* Writing the first journal header to a journal file. This happens
        ** when a transaction is first started.  */
        u8 *z = (u8 *)zBuf;
        pMain->nPage = decodeUint32(&z[16]);
        pMain->nPagesize = decodeUint32(&z[24]);
        if( SQLITE_OK!=(rc=openTransaction(pMain, p)) ){
          return rc;
        }
      }
    }
    if( p->iMaxOff<(iOfst + iAmt) ){
      p->iMaxOff = iOfst + iAmt;
    }
  }

  if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){
    if( iAmt<p->nPagesize 
     && p->nPagesize%iAmt==0 
     && iOfst>=(PENDING_BYTE+512) 
     && iOfst+iAmt<=PENDING_BYTE+p->nPagesize
    ){
      /* No-op. This special case is hit when the backup code is copying a
      ** to a database with a larger page-size than the source database and
      ** it needs to fill in the non-locking-region part of the original
      ** pending-byte page.
      */
    }else{
      u32 pgno = iOfst/p->nPagesize + 1;
      assert( (iAmt==1||iAmt==p->nPagesize) && ((iOfst+iAmt)%p->nPagesize)==0 );
      assert( pgno<=p->nPage || p->nSync>0 );
      assert( pgno>p->nPage || sqlite3BitvecTest(p->pWritable, pgno) );
    }
  }

  rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  if( (p->flags&SQLITE_OPEN_MAIN_JOURNAL) && iAmt==12 ){
    jt_file *pMain = locateDatabaseHandle(p->zName);
    int rc2 = readJournalFile(p, pMain);
    if( rc==SQLITE_OK ) rc = rc2;
  }
  return rc;
}

/*
** Truncate an jt-file.
*/
static int jtTruncate(sqlite3_file *pFile, sqlite_int64 size){
  jt_file *p = (jt_file *)pFile;
  if( p->flags&SQLITE_OPEN_MAIN_JOURNAL && size==0 ){
    /* Truncating a journal file. This is the end of a transaction. */
    jt_file *pMain = locateDatabaseHandle(p->zName);
    closeTransaction(pMain);
  }
  if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){
    u32 pgno;
    u32 locking_page = (u32)(PENDING_BYTE/p->nPagesize+1);
    for(pgno=size/p->nPagesize+1; pgno<=p->nPage; pgno++){
      assert( pgno==locking_page || sqlite3BitvecTest(p->pWritable, pgno) );
    }
  }
  return sqlite3OsTruncate(p->pReal, size);
}

/*
** Sync an jt-file.
*/
static int jtSync(sqlite3_file *pFile, int flags){
  jt_file *p = (jt_file *)pFile;

  if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){
    int rc;
    jt_file *pMain;                   /* The associated database file */

    /* The journal file is being synced. At this point, we inspect the 
    ** contents of the file up to this point and set each bit in the 
    ** jt_file.pWritable bitvec of the main database file associated with
    ** this journal file.
    */
    pMain = locateDatabaseHandle(p->zName);
    assert(pMain);

    /* Set the bitvec values */
    if( pMain->pWritable ){
      pMain->nSync++;
      rc = readJournalFile(p, pMain);
      if( rc!=SQLITE_OK ){
        return rc;
      }
    }
  }

  return sqlite3OsSync(p->pReal, flags);
}

/*
** Return the current file-size of an jt-file.
*/
static int jtFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  jt_file *p = (jt_file *)pFile;
  return sqlite3OsFileSize(p->pReal, pSize);
}

/*
** Lock an jt-file.
*/
static int jtLock(sqlite3_file *pFile, int eLock){
  int rc;
  jt_file *p = (jt_file *)pFile;
  rc = sqlite3OsLock(p->pReal, eLock);
  if( rc==SQLITE_OK && eLock>p->eLock ){
    p->eLock = eLock;
  }
  return rc;
}

/*
** Unlock an jt-file.
*/
static int jtUnlock(sqlite3_file *pFile, int eLock){
  int rc;
  jt_file *p = (jt_file *)pFile;
  rc = sqlite3OsUnlock(p->pReal, eLock);
  if( rc==SQLITE_OK && eLock<p->eLock ){
    p->eLock = eLock;
  }
  return rc;
}

/*
** Check if another file-handle holds a RESERVED lock on an jt-file.
*/
static int jtCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  jt_file *p = (jt_file *)pFile;
  return sqlite3OsCheckReservedLock(p->pReal, pResOut);
}

/*
** File control method. For custom operations on an jt-file.
*/
static int jtFileControl(sqlite3_file *pFile, int op, void *pArg){
  jt_file *p = (jt_file *)pFile;
  return sqlite3OsFileControl(p->pReal, op, pArg);
}

/*
** Return the sector-size in bytes for an jt-file.
*/
static int jtSectorSize(sqlite3_file *pFile){
  jt_file *p = (jt_file *)pFile;
  return sqlite3OsSectorSize(p->pReal);
}

/*
** Return the device characteristic flags supported by an jt-file.
*/
static int jtDeviceCharacteristics(sqlite3_file *pFile){
  jt_file *p = (jt_file *)pFile;
  return sqlite3OsDeviceCharacteristics(p->pReal);
}

/*
** Open an jt file handle.
*/
static int jtOpen(
  sqlite3_vfs *pVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  int rc;
  jt_file *p = (jt_file *)pFile;
  pFile->pMethods = 0;
  p->pReal = (sqlite3_file *)&p[1];
  p->pReal->pMethods = 0;
  rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags);
  assert( rc==SQLITE_OK || p->pReal->pMethods==0 );
  if( rc==SQLITE_OK ){
    pFile->pMethods = &jt_io_methods;
    p->eLock = 0;
    p->zName = zName;
    p->flags = flags;
    p->pNext = 0;
    p->pWritable = 0;
    p->aCksum = 0;
    enterJtMutex();
    if( zName ){
      p->pNext = g.pList;
      g.pList = p;
    }
    leaveJtMutex();
  }
  return rc;
}

/*
** Delete the file located at zPath. If the dirSync argument is true,
** ensure the file-system modifications are synced to disk before
** returning.
*/
static int jtDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  int nPath = strlen(zPath);
  if( nPath>8 && 0==strcmp("-journal", &zPath[nPath-8]) ){
    /* Deleting a journal file. The end of a transaction. */
    jt_file *pMain = locateDatabaseHandle(zPath);
    if( pMain ){
      closeTransaction(pMain);
    }
  }

  return sqlite3OsDelete(g.pVfs, zPath, dirSync);
}

/*
** Test for access permissions. Return true if the requested permission
** is available, or false otherwise.
*/
static int jtAccess(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int flags, 
  int *pResOut
){
  return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut);
}

/*
** Populate buffer zOut with the full canonical pathname corresponding
** to the pathname in zPath. zOut is guaranteed to point to a buffer
** of at least (JT_MAX_PATHNAME+1) bytes.
*/
static int jtFullPathname(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int nOut, 
  char *zOut
){
  return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut);
}

/*
** Open the dynamic library located at zPath and return a handle.
*/
static void *jtDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  return g.pVfs->xDlOpen(g.pVfs, zPath);
}

/*
** Populate the buffer zErrMsg (size nByte bytes) with a human readable
** utf-8 string describing the most recent error encountered associated 
** with dynamic libraries.
*/
static void jtDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  g.pVfs->xDlError(g.pVfs, nByte, zErrMsg);
}

/*
** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
*/
static void (*jtDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  return g.pVfs->xDlSym(g.pVfs, p, zSym);
}

/*
** Close the dynamic library handle pHandle.
*/
static void jtDlClose(sqlite3_vfs *pVfs, void *pHandle){
  g.pVfs->xDlClose(g.pVfs, pHandle);
}

/*
** Populate the buffer pointed to by zBufOut with nByte bytes of 
** random data.
*/
static int jtRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  return sqlite3OsRandomness(g.pVfs, nByte, zBufOut);
}

/*
** Sleep for nMicro microseconds. Return the number of microseconds 
** actually slept.
*/
static int jtSleep(sqlite3_vfs *pVfs, int nMicro){
  return sqlite3OsSleep(g.pVfs, nMicro);
}

/*
** Return the current time as a Julian Day number in *pTimeOut.
*/
static int jtCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  return sqlite3OsCurrentTime(g.pVfs, pTimeOut);
}

/**************************************************************************
** Start of public API.
*/

/*
** Configure the jt VFS as a wrapper around the VFS named by parameter 
** zWrap. If the isDefault parameter is true, then the jt VFS is installed
** as the new default VFS for SQLite connections. If isDefault is not
** true, then the jt VFS is installed as non-default. In this case it
** is available via its name, "jt".
*/
int jt_register(char *zWrap, int isDefault){
  g.pVfs = sqlite3_vfs_find(zWrap);
  if( g.pVfs==0 ){
    return SQLITE_ERROR;
  }
  jt_vfs.szOsFile = sizeof(jt_file) + g.pVfs->szOsFile;
  sqlite3_vfs_register(&jt_vfs, isDefault);
  return SQLITE_OK;
}

/*
** Uninstall the jt VFS, if it is installed.
*/
void jt_unregister(void){
  sqlite3_vfs_unregister(&jt_vfs);
}

#endif

Added src/test_loadext.c.

























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
** 2006 June 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Test extension for testing the sqlite3_load_extension() function.
**
** $Id: test_loadext.c,v 1.3 2008/08/02 03:50:39 drh Exp $
*/
#include <string.h>
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1

/*
** The half() SQL function returns half of its input value.
*/
static void halfFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  sqlite3_result_double(context, 0.5*sqlite3_value_double(argv[0]));
}

/*
** SQL functions to call the sqlite3_status function and return results.
*/
static void statusFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int op, mx, cur, resetFlag, rc;
  if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
    op = sqlite3_value_int(argv[0]);
  }else if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){
    int i;
    const char *zName;
    static const struct {
      const char *zName;
      int op;
    } aOp[] = {
      { "MEMORY_USED",         SQLITE_STATUS_MEMORY_USED         },
      { "PAGECACHE_USED",      SQLITE_STATUS_PAGECACHE_USED      },
      { "PAGECACHE_OVERFLOW",  SQLITE_STATUS_PAGECACHE_OVERFLOW  },
      { "SCRATCH_USED",        SQLITE_STATUS_SCRATCH_USED        },
      { "SCRATCH_OVERFLOW",    SQLITE_STATUS_SCRATCH_OVERFLOW    },
      { "MALLOC_SIZE",         SQLITE_STATUS_MALLOC_SIZE         },
    };
    int nOp = sizeof(aOp)/sizeof(aOp[0]);
    zName = (const char*)sqlite3_value_text(argv[0]);
    for(i=0; i<nOp; i++){
      if( strcmp(aOp[i].zName, zName)==0 ){
        op = aOp[i].op;
        break;
      }
    }
    if( i>=nOp ){
      char *zMsg = sqlite3_mprintf("unknown status property: %s", zName);
      sqlite3_result_error(context, zMsg, -1);
      sqlite3_free(zMsg);
      return;
    }
  }else{
    sqlite3_result_error(context, "unknown status type", -1);
    return;
  }
  if( argc==2 ){
    resetFlag = sqlite3_value_int(argv[1]);
  }else{
    resetFlag = 0;
  }
  rc = sqlite3_status(op, &cur, &mx, resetFlag);
  if( rc!=SQLITE_OK ){
    char *zMsg = sqlite3_mprintf("sqlite3_status(%d,...) returns %d", op, rc);
    sqlite3_result_error(context, zMsg, -1);
    sqlite3_free(zMsg);
    return;
  } 
  if( argc==2 ){
    sqlite3_result_int(context, mx);
  }else{
    sqlite3_result_int(context, cur);
  }
}

/*
** Extension load function.
*/
int testloadext_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  int nErr = 0;
  SQLITE_EXTENSION_INIT2(pApi);
  nErr |= sqlite3_create_function(db, "half", 1, SQLITE_ANY, 0, halfFunc, 0, 0);
  nErr |= sqlite3_create_function(db, "sqlite3_status", 1, SQLITE_ANY, 0,
                          statusFunc, 0, 0);
  nErr |= sqlite3_create_function(db, "sqlite3_status", 2, SQLITE_ANY, 0,
                          statusFunc, 0, 0);
  return nErr ? SQLITE_ERROR : SQLITE_OK;
}

/*
** Another extension entry point. This one always fails.
*/
int testbrokenext_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  char *zErr;
  SQLITE_EXTENSION_INIT2(pApi);
  zErr = sqlite3_mprintf("broken!");
  *pzErrMsg = zErr;
  return 1;
}

Added src/test_malloc.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
/*
** 2007 August 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to implement test interfaces to the
** memory allocation subsystem.
**
** $Id: test_malloc.c,v 1.55 2009/07/01 18:09:02 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/*
** This structure is used to encapsulate the global state variables used 
** by malloc() fault simulation.
*/
static struct MemFault {
  int iCountdown;         /* Number of pending successes before a failure */
  int nRepeat;            /* Number of times to repeat the failure */
  int nBenign;            /* Number of benign failures seen since last config */
  int nFail;              /* Number of failures seen since last config */
  u8 enable;              /* True if enabled */
  int isInstalled;        /* True if the fault simulation layer is installed */
  int isBenignMode;       /* True if malloc failures are considered benign */
  sqlite3_mem_methods m;  /* 'Real' malloc implementation */
} memfault;

/*
** This routine exists as a place to set a breakpoint that will
** fire on any simulated malloc() failure.
*/
static void sqlite3Fault(void){
  static int cnt = 0;
  cnt++;
}

/*
** Check to see if a fault should be simulated.  Return true to simulate
** the fault.  Return false if the fault should not be simulated.
*/
static int faultsimStep(void){
  if( likely(!memfault.enable) ){
    return 0;
  }
  if( memfault.iCountdown>0 ){
    memfault.iCountdown--;
    return 0;
  }
  sqlite3Fault();
  memfault.nFail++;
  if( memfault.isBenignMode>0 ){
    memfault.nBenign++;
  }
  memfault.nRepeat--;
  if( memfault.nRepeat<=0 ){
    memfault.enable = 0;
  }
  return 1;  
}

/*
** A version of sqlite3_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(int n){
  void *p = 0;
  if( !faultsimStep() ){
    p = memfault.m.xMalloc(n);
  }
  return p;
}


/*
** A version of sqlite3_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pOld, int n){
  void *p = 0;
  if( !faultsimStep() ){
    p = memfault.m.xRealloc(pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
**
**     xFree
**     xSize
**     xRoundup
**     xInit
**     xShutdown
*/
static void faultsimFree(void *p){
  memfault.m.xFree(p);
}
static int faultsimSize(void *p){
  return memfault.m.xSize(p);
}
static int faultsimRoundup(int n){
  return memfault.m.xRoundup(n);
}
static int faultsimInit(void *p){
  return memfault.m.xInit(memfault.m.pAppData);
}
static void faultsimShutdown(void *p){
  memfault.m.xShutdown(memfault.m.pAppData);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
** to succeed again.
*/
static void faultsimConfig(int nDelay, int nRepeat){
  memfault.iCountdown = nDelay;
  memfault.nRepeat = nRepeat;
  memfault.nBenign = 0;
  memfault.nFail = 0;
  memfault.enable = nDelay>=0;

  /* Sometimes, when running multi-threaded tests, the isBenignMode 
  ** variable is not properly incremented/decremented so that it is
  ** 0 when not inside a benign malloc block. This doesn't affect
  ** the multi-threaded tests, as they do not use this system. But
  ** it does affect OOM tests run later in the same process. So
  ** zero the variable here, just to be sure.
  */
  memfault.isBenignMode = 0;
}

/*
** Return the number of faults (both hard and benign faults) that have
** occurred since the injector was last configured.
*/
static int faultsimFailures(void){
  return memfault.nFail;
}

/*
** Return the number of benign faults that have occurred since the
** injector was last configured.
*/
static int faultsimBenignFailures(void){
  return memfault.nBenign;
}

/*
** Return the number of successes that will occur before the next failure.
** If no failures are scheduled, return -1.
*/
static int faultsimPending(void){
  if( memfault.enable ){
    return memfault.iCountdown;
  }else{
    return -1;
  }
}


static void faultsimBeginBenign(void){
  memfault.isBenignMode++;
}
static void faultsimEndBenign(void){
  memfault.isBenignMode--;
}

/*
** Add or remove the fault-simulation layer using sqlite3_config(). If
** the argument is non-zero, the 
*/
static int faultsimInstall(int install){
  static struct sqlite3_mem_methods m = {
    faultsimMalloc,                   /* xMalloc */
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */
    faultsimRoundup,                  /* xRoundup */
    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */
    0                                 /* pAppData */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
    return SQLITE_ERROR;
  }

  if( install ){
    rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &m);
    }
    sqlite3_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 
        faultsimBeginBenign, faultsimEndBenign
    );
  }else{
    sqlite3_mem_methods m;
    assert(memfault.m.xMalloc);

    /* One should be able to reset the default memory allocator by storing
    ** a zeroed allocator then calling GETMALLOC. */
    memset(&m, 0, sizeof(m));
    sqlite3_config(SQLITE_CONFIG_MALLOC, &m);
    sqlite3_config(SQLITE_CONFIG_GETMALLOC, &m);
    assert( memcmp(&m, &memfault.m, sizeof(m))==0 );

    rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memfault.m);
    sqlite3_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 0, 0);
  }

  if( rc==SQLITE_OK ){
    memfault.isInstalled = 1;
  }
  return rc;
}

#ifdef SQLITE_TEST

/*
** This function is implemented in test1.c. Returns a pointer to a static
** buffer containing the symbolic SQLite error code that corresponds to
** the least-significant 8-bits of the integer passed as an argument.
** For example:
**
**   sqlite3TestErrorName(1) -> "SQLITE_ERROR"
*/
const char *sqlite3TestErrorName(int);

/*
** Transform pointers to text and back again
*/
static void pointerToText(void *p, char *z){
  static const char zHex[] = "0123456789abcdef";
  int i, k;
  unsigned int u;
  sqlite3_uint64 n;
  if( p==0 ){
    strcpy(z, "0");
    return;
  }
  if( sizeof(n)==sizeof(p) ){
    memcpy(&n, &p, sizeof(p));
  }else if( sizeof(u)==sizeof(p) ){
    memcpy(&u, &p, sizeof(u));
    n = u;
  }else{
    assert( 0 );
  }
  for(i=0, k=sizeof(p)*2-1; i<sizeof(p)*2; i++, k--){
    z[k] = zHex[n&0xf];
    n >>= 4;
  }
  z[sizeof(p)*2] = 0;
}
static int hexToInt(int h){
  if( h>='0' && h<='9' ){
    return h - '0';
  }else if( h>='a' && h<='f' ){
    return h - 'a' + 10;
  }else{
    return -1;
  }
}
static int textToPointer(const char *z, void **pp){
  sqlite3_uint64 n = 0;
  int i;
  unsigned int u;
  for(i=0; i<sizeof(void*)*2 && z[0]; i++){
    int v;
    v = hexToInt(*z++);
    if( v<0 ) return TCL_ERROR;
    n = n*16 + v;
  }
  if( *z!=0 ) return TCL_ERROR;
  if( sizeof(n)==sizeof(*pp) ){
    memcpy(pp, &n, sizeof(n));
  }else if( sizeof(u)==sizeof(*pp) ){
    u = (unsigned int)n;
    memcpy(pp, &u, sizeof(u));
  }else{
    assert( 0 );
  }
  return TCL_OK;
}

/*
** Usage:    sqlite3_malloc  NBYTES
**
** Raw test interface for sqlite3_malloc().
*/
static int test_malloc(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int nByte;
  void *p;
  char zOut[100];
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "NBYTES");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &nByte) ) return TCL_ERROR;
  p = sqlite3_malloc((unsigned)nByte);
  pointerToText(p, zOut);
  Tcl_AppendResult(interp, zOut, NULL);
  return TCL_OK;
}

/*
** Usage:    sqlite3_realloc  PRIOR  NBYTES
**
** Raw test interface for sqlite3_realloc().
*/
static int test_realloc(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int nByte;
  void *pPrior, *p;
  char zOut[100];
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "PRIOR NBYTES");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &nByte) ) return TCL_ERROR;
  if( textToPointer(Tcl_GetString(objv[1]), &pPrior) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  p = sqlite3_realloc(pPrior, (unsigned)nByte);
  pointerToText(p, zOut);
  Tcl_AppendResult(interp, zOut, NULL);
  return TCL_OK;
}

/*
** Usage:    sqlite3_free  PRIOR
**
** Raw test interface for sqlite3_free().
*/
static int test_free(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  void *pPrior;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "PRIOR");
    return TCL_ERROR;
  }
  if( textToPointer(Tcl_GetString(objv[1]), &pPrior) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  sqlite3_free(pPrior);
  return TCL_OK;
}

/*
** These routines are in test_hexio.c
*/
int sqlite3TestHexToBin(const char *, int, char *);
int sqlite3TestBinToHex(char*,int);

/*
** Usage:    memset  ADDRESS  SIZE  HEX
**
** Set a chunk of memory (obtained from malloc, probably) to a
** specified hex pattern.
*/
static int test_memset(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  void *p;
  int size, n, i;
  char *zHex;
  char *zOut;
  char zBin[100];

  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "ADDRESS SIZE HEX");
    return TCL_ERROR;
  }
  if( textToPointer(Tcl_GetString(objv[1]), &p) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &size) ){
    return TCL_ERROR;
  }
  if( size<=0 ){
    Tcl_AppendResult(interp, "size must be positive", (char*)0);
    return TCL_ERROR;
  }
  zHex = Tcl_GetStringFromObj(objv[3], &n);
  if( n>sizeof(zBin)*2 ) n = sizeof(zBin)*2;
  n = sqlite3TestHexToBin(zHex, n, zBin);
  if( n==0 ){
    Tcl_AppendResult(interp, "no data", (char*)0);
    return TCL_ERROR;
  }
  zOut = p;
  for(i=0; i<size; i++){
    zOut[i] = zBin[i%n];
  }
  return TCL_OK;
}

/*
** Usage:    memget  ADDRESS  SIZE
**
** Return memory as hexadecimal text.
*/
static int test_memget(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  void *p;
  int size, n;
  char *zBin;
  char zHex[100];

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "ADDRESS SIZE");
    return TCL_ERROR;
  }
  if( textToPointer(Tcl_GetString(objv[1]), &p) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &size) ){
    return TCL_ERROR;
  }
  if( size<=0 ){
    Tcl_AppendResult(interp, "size must be positive", (char*)0);
    return TCL_ERROR;
  }
  zBin = p;
  while( size>0 ){
    if( size>(sizeof(zHex)-1)/2 ){
      n = (sizeof(zHex)-1)/2;
    }else{
      n = size;
    }
    memcpy(zHex, zBin, n);
    zBin += n;
    size -= n;
    sqlite3TestBinToHex(zHex, n);
    Tcl_AppendResult(interp, zHex, (char*)0);
  }
  return TCL_OK;
}

/*
** Usage:    sqlite3_memory_used
**
** Raw test interface for sqlite3_memory_used().
*/
static int test_memory_used(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(sqlite3_memory_used()));
  return TCL_OK;
}

/*
** Usage:    sqlite3_memory_highwater ?RESETFLAG?
**
** Raw test interface for sqlite3_memory_highwater().
*/
static int test_memory_highwater(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int resetFlag = 0;
  if( objc!=1 && objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "?RESET?");
    return TCL_ERROR;
  }
  if( objc==2 ){
    if( Tcl_GetBooleanFromObj(interp, objv[1], &resetFlag) ) return TCL_ERROR;
  } 
  Tcl_SetObjResult(interp, 
     Tcl_NewWideIntObj(sqlite3_memory_highwater(resetFlag)));
  return TCL_OK;
}

/*
** Usage:    sqlite3_memdebug_backtrace DEPTH
**
** Set the depth of backtracing.  If SQLITE_MEMDEBUG is not defined
** then this routine is a no-op.
*/
static int test_memdebug_backtrace(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int depth;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DEPT");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &depth) ) return TCL_ERROR;
#ifdef SQLITE_MEMDEBUG
  {
    extern void sqlite3MemdebugBacktrace(int);
    sqlite3MemdebugBacktrace(depth);
  }
#endif
  return TCL_OK;
}

/*
** Usage:    sqlite3_memdebug_dump  FILENAME
**
** Write a summary of unfreed memory to FILENAME.
*/
static int test_memdebug_dump(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME");
    return TCL_ERROR;
  }
#if defined(SQLITE_MEMDEBUG) || defined(SQLITE_MEMORY_SIZE) \
     || defined(SQLITE_POW2_MEMORY_SIZE)
  {
    extern void sqlite3MemdebugDump(const char*);
    sqlite3MemdebugDump(Tcl_GetString(objv[1]));
  }
#endif
  return TCL_OK;
}

/*
** Usage:    sqlite3_memdebug_malloc_count
**
** Return the total number of times malloc() has been called.
*/
static int test_memdebug_malloc_count(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int nMalloc = -1;
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }
#if defined(SQLITE_MEMDEBUG)
  {
    extern int sqlite3MemdebugMallocCount();
    nMalloc = sqlite3MemdebugMallocCount();
  }
#endif
  Tcl_SetObjResult(interp, Tcl_NewIntObj(nMalloc));
  return TCL_OK;
}


/*
** Usage:    sqlite3_memdebug_fail  COUNTER  ?OPTIONS?
**
** where options are:
**
**     -repeat    <count>
**     -benigncnt <varname>
**
** Arrange for a simulated malloc() failure after COUNTER successes.
** If a repeat count is specified, the fault is repeated that many
** times.
**
** Each call to this routine overrides the prior counter value.
** This routine returns the number of simulated failures that have
** happened since the previous call to this routine.
**
** To disable simulated failures, use a COUNTER of -1.
*/
static int test_memdebug_fail(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int ii;
  int iFail;
  int nRepeat = 1;
  Tcl_Obj *pBenignCnt = 0;
  int nBenign;
  int nFail = 0;

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "COUNTER ?OPTIONS?");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &iFail) ) return TCL_ERROR;

  for(ii=2; ii<objc; ii+=2){
    int nOption;
    char *zOption = Tcl_GetStringFromObj(objv[ii], &nOption);
    char *zErr = 0;

    if( nOption>1 && strncmp(zOption, "-repeat", nOption)==0 ){
      if( ii==(objc-1) ){
        zErr = "option requires an argument: ";
      }else{
        if( Tcl_GetIntFromObj(interp, objv[ii+1], &nRepeat) ){
          return TCL_ERROR;
        }
      }
    }else if( nOption>1 && strncmp(zOption, "-benigncnt", nOption)==0 ){
      if( ii==(objc-1) ){
        zErr = "option requires an argument: ";
      }else{
        pBenignCnt = objv[ii+1];
      }
    }else{
      zErr = "unknown option: ";
    }

    if( zErr ){
      Tcl_AppendResult(interp, zErr, zOption, 0);
      return TCL_ERROR;
    }
  }
  
  nBenign = faultsimBenignFailures();
  nFail = faultsimFailures();
  faultsimConfig(iFail, nRepeat);

  if( pBenignCnt ){
    Tcl_ObjSetVar2(interp, pBenignCnt, 0, Tcl_NewIntObj(nBenign), 0);
  }
  Tcl_SetObjResult(interp, Tcl_NewIntObj(nFail));
  return TCL_OK;
}

/*
** Usage:    sqlite3_memdebug_pending
**
** Return the number of malloc() calls that will succeed before a 
** simulated failure occurs. A negative return value indicates that
** no malloc() failure is scheduled.
*/
static int test_memdebug_pending(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int nPending;
  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }
  nPending = faultsimPending();
  Tcl_SetObjResult(interp, Tcl_NewIntObj(nPending));
  return TCL_OK;
}


/*
** Usage:    sqlite3_memdebug_settitle TITLE
**
** Set a title string stored with each allocation.  The TITLE is
** typically the name of the test that was running when the
** allocation occurred.  The TITLE is stored with the allocation
** and can be used to figure out which tests are leaking memory.
**
** Each title overwrite the previous.
*/
static int test_memdebug_settitle(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  const char *zTitle;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "TITLE");
    return TCL_ERROR;
  }
  zTitle = Tcl_GetString(objv[1]);
#ifdef SQLITE_MEMDEBUG
  {
    extern int sqlite3MemdebugSettitle(const char*);
    sqlite3MemdebugSettitle(zTitle);
  }
#endif
  return TCL_OK;
}

#define MALLOC_LOG_FRAMES 10 
static Tcl_HashTable aMallocLog;
static int mallocLogEnabled = 0;

typedef struct MallocLog MallocLog;
struct MallocLog {
  int nCall;
  int nByte;
};

#ifdef SQLITE_MEMDEBUG
static void test_memdebug_callback(int nByte, int nFrame, void **aFrame){
  if( mallocLogEnabled ){
    MallocLog *pLog;
    Tcl_HashEntry *pEntry;
    int isNew;

    int aKey[MALLOC_LOG_FRAMES];
    int nKey = sizeof(int)*MALLOC_LOG_FRAMES;

    memset(aKey, 0, nKey);
    if( (sizeof(void*)*nFrame)<nKey ){
      nKey = nFrame*sizeof(void*);
    }
    memcpy(aKey, aFrame, nKey);

    pEntry = Tcl_CreateHashEntry(&aMallocLog, (const char *)aKey, &isNew);
    if( isNew ){
      pLog = (MallocLog *)Tcl_Alloc(sizeof(MallocLog));
      memset(pLog, 0, sizeof(MallocLog));
      Tcl_SetHashValue(pEntry, (ClientData)pLog);
    }else{
      pLog = (MallocLog *)Tcl_GetHashValue(pEntry);
    }

    pLog->nCall++;
    pLog->nByte += nByte;
  }
}
#endif /* SQLITE_MEMDEBUG */

static void test_memdebug_log_clear(void){
  Tcl_HashSearch search;
  Tcl_HashEntry *pEntry;
  for(
    pEntry=Tcl_FirstHashEntry(&aMallocLog, &search);
    pEntry;
    pEntry=Tcl_NextHashEntry(&search)
  ){
    MallocLog *pLog = (MallocLog *)Tcl_GetHashValue(pEntry);
    Tcl_Free((char *)pLog);
  }
  Tcl_DeleteHashTable(&aMallocLog);
  Tcl_InitHashTable(&aMallocLog, MALLOC_LOG_FRAMES);
}

static int test_memdebug_log(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  static int isInit = 0;
  int iSub;

  static const char *MB_strs[] = { "start", "stop", "dump", "clear", "sync" };
  enum MB_enum { 
      MB_LOG_START, MB_LOG_STOP, MB_LOG_DUMP, MB_LOG_CLEAR, MB_LOG_SYNC 
  };

  if( !isInit ){
#ifdef SQLITE_MEMDEBUG
    extern void sqlite3MemdebugBacktraceCallback(
        void (*xBacktrace)(int, int, void **));
    sqlite3MemdebugBacktraceCallback(test_memdebug_callback);
#endif
    Tcl_InitHashTable(&aMallocLog, MALLOC_LOG_FRAMES);
    isInit = 1;
  }

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ...");
  }
  if( Tcl_GetIndexFromObj(interp, objv[1], MB_strs, "sub-command", 0, &iSub) ){
    return TCL_ERROR;
  }

  switch( (enum MB_enum)iSub ){
    case MB_LOG_START:
      mallocLogEnabled = 1;
      break;
    case MB_LOG_STOP:
      mallocLogEnabled = 0;
      break;
    case MB_LOG_DUMP: {
      Tcl_HashSearch search;
      Tcl_HashEntry *pEntry;
      Tcl_Obj *pRet = Tcl_NewObj();

      assert(sizeof(int)==sizeof(void*));

      for(
        pEntry=Tcl_FirstHashEntry(&aMallocLog, &search);
        pEntry;
        pEntry=Tcl_NextHashEntry(&search)
      ){
        Tcl_Obj *apElem[MALLOC_LOG_FRAMES+2];
        MallocLog *pLog = (MallocLog *)Tcl_GetHashValue(pEntry);
        int *aKey = (int *)Tcl_GetHashKey(&aMallocLog, pEntry);
        int ii;
  
        apElem[0] = Tcl_NewIntObj(pLog->nCall);
        apElem[1] = Tcl_NewIntObj(pLog->nByte);
        for(ii=0; ii<MALLOC_LOG_FRAMES; ii++){
          apElem[ii+2] = Tcl_NewIntObj(aKey[ii]);
        }

        Tcl_ListObjAppendElement(interp, pRet,
            Tcl_NewListObj(MALLOC_LOG_FRAMES+2, apElem)
        );
      }

      Tcl_SetObjResult(interp, pRet);
      break;
    }
    case MB_LOG_CLEAR: {
      test_memdebug_log_clear();
      break;
    }

    case MB_LOG_SYNC: {
#ifdef SQLITE_MEMDEBUG
      extern void sqlite3MemdebugSync();
      test_memdebug_log_clear();
      mallocLogEnabled = 1;
      sqlite3MemdebugSync();
#endif
      break;
    }
  }

  return TCL_OK;
}

/*
** Usage:    sqlite3_config_scratch SIZE N
**
** Set the scratch memory buffer using SQLITE_CONFIG_SCRATCH.
** The buffer is static and is of limited size.  N might be
** adjusted downward as needed to accomodate the requested size.
** The revised value of N is returned.
**
** A negative SIZE causes the buffer pointer to be NULL.
*/
static int test_config_scratch(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int sz, N, rc;
  Tcl_Obj *pResult;
  static char *buf = 0;
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SIZE N");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &sz) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &N) ) return TCL_ERROR;
  free(buf);
  if( sz<0 ){
    buf = 0;
    rc = sqlite3_config(SQLITE_CONFIG_SCRATCH, 0, 0, 0);
  }else{
    buf = malloc( sz*N + 1 );
    rc = sqlite3_config(SQLITE_CONFIG_SCRATCH, buf, sz, N);
  }
  pResult = Tcl_NewObj();
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc));
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(N));
  Tcl_SetObjResult(interp, pResult);
  return TCL_OK;
}

/*
** Usage:    sqlite3_config_pagecache SIZE N
**
** Set the page-cache memory buffer using SQLITE_CONFIG_PAGECACHE.
** The buffer is static and is of limited size.  N might be
** adjusted downward as needed to accomodate the requested size.
** The revised value of N is returned.
**
** A negative SIZE causes the buffer pointer to be NULL.
*/
static int test_config_pagecache(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int sz, N, rc;
  Tcl_Obj *pResult;
  static char *buf = 0;
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SIZE N");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &sz) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &N) ) return TCL_ERROR;
  free(buf);
  if( sz<0 ){
    buf = 0;
    rc = sqlite3_config(SQLITE_CONFIG_PAGECACHE, 0, 0, 0);
  }else{
    buf = malloc( sz*N );
    rc = sqlite3_config(SQLITE_CONFIG_PAGECACHE, buf, sz, N);
  }
  pResult = Tcl_NewObj();
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc));
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(N));
  Tcl_SetObjResult(interp, pResult);
  return TCL_OK;
}

/*
** Usage:    sqlite3_config_alt_pcache INSTALL_FLAG DISCARD_CHANCE PRNG_SEED
**
** Set up the alternative test page cache.  Install if INSTALL_FLAG is
** true and uninstall (reverting to the default page cache) if INSTALL_FLAG
** is false.  DISCARD_CHANGE is an integer between 0 and 100 inclusive
** which determines the chance of discarding a page when unpinned.  100
** is certainty.  0 is never.  PRNG_SEED is the pseudo-random number generator
** seed.
*/
static int test_alt_pcache(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int installFlag;
  int discardChance = 0;
  int prngSeed = 0;
  int highStress = 0;
  extern void installTestPCache(int,unsigned,unsigned,unsigned);
  if( objc<2 || objc>5 ){
    Tcl_WrongNumArgs(interp, 1, objv, 
        "INSTALLFLAG DISCARDCHANCE PRNGSEEED HIGHSTRESS");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &installFlag) ) return TCL_ERROR;
  if( objc>=3 && Tcl_GetIntFromObj(interp, objv[2], &discardChance) ){
     return TCL_ERROR;
  }
  if( objc>=4 && Tcl_GetIntFromObj(interp, objv[3], &prngSeed) ){
     return TCL_ERROR;
  }
  if( objc>=5 && Tcl_GetIntFromObj(interp, objv[4], &highStress) ){
    return TCL_ERROR;
  }
  if( discardChance<0 || discardChance>100 ){
    Tcl_AppendResult(interp, "discard-chance should be between 0 and 100",
                     (char*)0);
    return TCL_ERROR;
  }
  installTestPCache(installFlag, (unsigned)discardChance, (unsigned)prngSeed,
                    (unsigned)highStress);
  return TCL_OK;
}

/*
** Usage:    sqlite3_config_memstatus BOOLEAN
**
** Enable or disable memory status reporting using SQLITE_CONFIG_MEMSTATUS.
*/
static int test_config_memstatus(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int enable, rc;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN");
    return TCL_ERROR;
  }
  if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ) return TCL_ERROR;
  rc = sqlite3_config(SQLITE_CONFIG_MEMSTATUS, enable);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;
}

/*
** Usage:    sqlite3_config_lookaside  SIZE  COUNT
**
*/
static int test_config_lookaside(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc;
  int sz, cnt;
  Tcl_Obj *pRet;
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SIZE COUNT");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &sz) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &cnt) ) return TCL_ERROR;
  pRet = Tcl_NewObj();
  Tcl_ListObjAppendElement(
      interp, pRet, Tcl_NewIntObj(sqlite3GlobalConfig.szLookaside)
  );
  Tcl_ListObjAppendElement(
      interp, pRet, Tcl_NewIntObj(sqlite3GlobalConfig.nLookaside)
  );
  rc = sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, cnt);
  Tcl_SetObjResult(interp, pRet);
  return TCL_OK;
}


/*
** Usage:    sqlite3_db_config_lookaside  CONNECTION  BUFID  SIZE  COUNT
**
** There are two static buffers with BUFID 1 and 2.   Each static buffer
** is 10KB in size.  A BUFID of 0 indicates that the buffer should be NULL
** which will cause sqlite3_db_config() to allocate space on its own.
*/
static int test_db_config_lookaside(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc;
  int sz, cnt;
  sqlite3 *db;
  int bufid;
  static char azBuf[2][10000];
  int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
  if( objc!=5 ){
    Tcl_WrongNumArgs(interp, 1, objv, "BUFID SIZE COUNT");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &bufid) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &sz) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[4], &cnt) ) return TCL_ERROR;
  if( bufid==0 ){
    rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, 0, sz, cnt);
  }else if( bufid>=1 && bufid<=2 && sz*cnt<=sizeof(azBuf[0]) ){
    rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, azBuf[bufid], sz,cnt);
  }else{
    Tcl_AppendResult(interp, "illegal arguments - see documentation", (char*)0);
    return TCL_ERROR;
  }
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;
}

/*
** Usage:
**
**   sqlite3_config_heap NBYTE NMINALLOC
*/
static int test_config_heap(
  void * clientData, 
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  static char *zBuf; /* Use this memory */
  static int szBuf;  /* Bytes allocated for zBuf */
  int nByte;         /* Size of buffer to pass to sqlite3_config() */
  int nMinAlloc;     /* Size of minimum allocation */
  int rc;            /* Return code of sqlite3_config() */

  Tcl_Obj * CONST *aArg = &objv[1];
  int nArg = objc-1;

  if( nArg!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "NBYTE NMINALLOC");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, aArg[0], &nByte) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, aArg[1], &nMinAlloc) ) return TCL_ERROR;

  if( nByte==0 ){
    free( zBuf );
    zBuf = 0;
    szBuf = 0;
    rc = sqlite3_config(SQLITE_CONFIG_HEAP, (void*)0, 0, 0);
  }else{
    zBuf = realloc(zBuf, nByte);
    szBuf = nByte;
    rc = sqlite3_config(SQLITE_CONFIG_HEAP, zBuf, nByte, nMinAlloc);
  }

  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

/*
** tclcmd:     sqlite3_config_error  [DB]
**
** Invoke sqlite3_config() or sqlite3_db_config() with invalid
** opcodes and verify that they return errors.
*/
static int test_config_error(
  void * clientData, 
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  int getDbPointer(Tcl_Interp*, const char*, sqlite3**);

  if( objc!=2 && objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "[DB]");
    return TCL_ERROR;
  }
  if( objc==2 ){
    if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
    if( sqlite3_db_config(db, 99999)!=SQLITE_ERROR ){
      Tcl_AppendResult(interp, 
            "sqlite3_db_config(db, 99999) does not return SQLITE_ERROR",
            (char*)0);
      return TCL_ERROR;
    }
  }else{
    if( sqlite3_config(99999)!=SQLITE_ERROR ){
      Tcl_AppendResult(interp, 
          "sqlite3_config(99999) does not return SQLITE_ERROR",
          (char*)0);
      return TCL_ERROR;
    }
  }
  return TCL_OK;
}

/*
** Usage:    
**
**   sqlite3_dump_memsys3  FILENAME
**   sqlite3_dump_memsys5  FILENAME
**
** Write a summary of unfreed memsys3 allocations to FILENAME.
*/
static int test_dump_memsys3(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME");
    return TCL_ERROR;
  }

  switch( (int)clientData ){
    case 3: {
#ifdef SQLITE_ENABLE_MEMSYS3
      extern void sqlite3Memsys3Dump(const char*);
      sqlite3Memsys3Dump(Tcl_GetString(objv[1]));
      break;
#endif
    }
    case 5: {
#ifdef SQLITE_ENABLE_MEMSYS5
      extern void sqlite3Memsys5Dump(const char*);
      sqlite3Memsys5Dump(Tcl_GetString(objv[1]));
      break;
#endif
    }
  }
  return TCL_OK;
}

/*
** Usage:    sqlite3_status  OPCODE  RESETFLAG
**
** Return a list of three elements which are the sqlite3_status() return
** code, the current value, and the high-water mark value.
*/
static int test_status(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc, iValue, mxValue;
  int i, op, resetFlag;
  const char *zOpName;
  static const struct {
    const char *zName;
    int op;
  } aOp[] = {
    { "SQLITE_STATUS_MEMORY_USED",         SQLITE_STATUS_MEMORY_USED         },
    { "SQLITE_STATUS_MALLOC_SIZE",         SQLITE_STATUS_MALLOC_SIZE         },
    { "SQLITE_STATUS_PAGECACHE_USED",      SQLITE_STATUS_PAGECACHE_USED      },
    { "SQLITE_STATUS_PAGECACHE_OVERFLOW",  SQLITE_STATUS_PAGECACHE_OVERFLOW  },
    { "SQLITE_STATUS_PAGECACHE_SIZE",      SQLITE_STATUS_PAGECACHE_SIZE      },
    { "SQLITE_STATUS_SCRATCH_USED",        SQLITE_STATUS_SCRATCH_USED        },
    { "SQLITE_STATUS_SCRATCH_OVERFLOW",    SQLITE_STATUS_SCRATCH_OVERFLOW    },
    { "SQLITE_STATUS_SCRATCH_SIZE",        SQLITE_STATUS_SCRATCH_SIZE        },
    { "SQLITE_STATUS_PARSER_STACK",        SQLITE_STATUS_PARSER_STACK        },
  };
  Tcl_Obj *pResult;
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "PARAMETER RESETFLAG");
    return TCL_ERROR;
  }
  zOpName = Tcl_GetString(objv[1]);
  for(i=0; i<ArraySize(aOp); i++){
    if( strcmp(aOp[i].zName, zOpName)==0 ){
      op = aOp[i].op;
      break;
    }
  }
  if( i>=ArraySize(aOp) ){
    if( Tcl_GetIntFromObj(interp, objv[1], &op) ) return TCL_ERROR;
  }
  if( Tcl_GetBooleanFromObj(interp, objv[2], &resetFlag) ) return TCL_ERROR;
  iValue = 0;
  mxValue = 0;
  rc = sqlite3_status(op, &iValue, &mxValue, resetFlag);
  pResult = Tcl_NewObj();
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc));
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(iValue));
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(mxValue));
  Tcl_SetObjResult(interp, pResult);
  return TCL_OK;
}

/*
** Usage:    sqlite3_db_status  DATABASE  OPCODE  RESETFLAG
**
** Return a list of three elements which are the sqlite3_db_status() return
** code, the current value, and the high-water mark value.
*/
static int test_db_status(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc, iValue, mxValue;
  int i, op, resetFlag;
  const char *zOpName;
  sqlite3 *db;
  int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
  static const struct {
    const char *zName;
    int op;
  } aOp[] = {
    { "SQLITE_DBSTATUS_LOOKASIDE_USED",    SQLITE_DBSTATUS_LOOKASIDE_USED   },
  };
  Tcl_Obj *pResult;
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "PARAMETER RESETFLAG");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zOpName = Tcl_GetString(objv[2]);
  for(i=0; i<ArraySize(aOp); i++){
    if( strcmp(aOp[i].zName, zOpName)==0 ){
      op = aOp[i].op;
      break;
    }
  }
  if( i>=ArraySize(aOp) ){
    if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR;
  }
  if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR;
  iValue = 0;
  mxValue = 0;
  rc = sqlite3_db_status(db, op, &iValue, &mxValue, resetFlag);
  pResult = Tcl_NewObj();
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc));
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(iValue));
  Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(mxValue));
  Tcl_SetObjResult(interp, pResult);
  return TCL_OK;
}

/*
** install_malloc_faultsim BOOLEAN
*/
static int test_install_malloc_faultsim(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc;
  int isInstall;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN");
    return TCL_ERROR;
  }
  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){
    return TCL_ERROR;
  }
  rc = faultsimInstall(isInstall);
  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

/*
** sqlite3_install_memsys3
*/
static int test_install_memsys3(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = SQLITE_MISUSE;
#ifdef SQLITE_ENABLE_MEMSYS3
  const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  rc = sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetMemsys3());
#endif
  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest_malloc_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     int clientData;
  } aObjCmd[] = {
     { "sqlite3_malloc",             test_malloc                   ,0 },
     { "sqlite3_realloc",            test_realloc                  ,0 },
     { "sqlite3_free",               test_free                     ,0 },
     { "memset",                     test_memset                   ,0 },
     { "memget",                     test_memget                   ,0 },
     { "sqlite3_memory_used",        test_memory_used              ,0 },
     { "sqlite3_memory_highwater",   test_memory_highwater         ,0 },
     { "sqlite3_memdebug_backtrace", test_memdebug_backtrace       ,0 },
     { "sqlite3_memdebug_dump",      test_memdebug_dump            ,0 },
     { "sqlite3_memdebug_fail",      test_memdebug_fail            ,0 },
     { "sqlite3_memdebug_pending",   test_memdebug_pending         ,0 },
     { "sqlite3_memdebug_settitle",  test_memdebug_settitle        ,0 },
     { "sqlite3_memdebug_malloc_count", test_memdebug_malloc_count ,0 },
     { "sqlite3_memdebug_log",       test_memdebug_log             ,0 },
     { "sqlite3_config_scratch",     test_config_scratch           ,0 },
     { "sqlite3_config_pagecache",   test_config_pagecache         ,0 },
     { "sqlite3_config_alt_pcache",  test_alt_pcache               ,0 },
     { "sqlite3_status",             test_status                   ,0 },
     { "sqlite3_db_status",          test_db_status                ,0 },
     { "install_malloc_faultsim",    test_install_malloc_faultsim  ,0 },
     { "sqlite3_config_heap",        test_config_heap              ,0 },
     { "sqlite3_config_memstatus",   test_config_memstatus         ,0 },
     { "sqlite3_config_lookaside",   test_config_lookaside         ,0 },
     { "sqlite3_config_error",       test_config_error             ,0 },
     { "sqlite3_db_config_lookaside",test_db_config_lookaside      ,0 },
     { "sqlite3_dump_memsys3",       test_dump_memsys3             ,3 },
     { "sqlite3_dump_memsys5",       test_dump_memsys3             ,5 },
     { "sqlite3_install_memsys3",    test_install_memsys3          ,0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    ClientData c = (ClientData)aObjCmd[i].clientData;
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, c, 0);
  }
  return TCL_OK;
}
#endif

Added src/test_mutex.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
** 2008 June 18
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** 
** $Id: test_mutex.c,v 1.15 2009/03/20 13:15:30 drh Exp $
*/

#include "tcl.h"
#include "sqlite3.h"
#include "sqliteInt.h"
#include <stdlib.h>
#include <assert.h>
#include <string.h>

/* defined in test1.c */
const char *sqlite3TestErrorName(int);

/* A countable mutex */
struct sqlite3_mutex {
  sqlite3_mutex *pReal;
  int eType;
};

/* State variables */
static struct test_mutex_globals {
  int isInstalled;              /* True if installed */
  int disableInit;              /* True to cause sqlite3_initalize() to fail */
  int disableTry;               /* True to force sqlite3_mutex_try() to fail */
  int isInit;                   /* True if initialized */
  sqlite3_mutex_methods m;      /* Interface to "real" mutex system */
  int aCounter[8];              /* Number of grabs of each type of mutex */
  sqlite3_mutex aStatic[6];     /* The six static mutexes */
} g = {0};

/* Return true if the countable mutex is currently held */
static int counterMutexHeld(sqlite3_mutex *p){
  return g.m.xMutexHeld(p->pReal);
}

/* Return true if the countable mutex is not currently held */
static int counterMutexNotheld(sqlite3_mutex *p){
  return g.m.xMutexNotheld(p->pReal);
}

/* Initialize the countable mutex interface
** Or, if g.disableInit is non-zero, then do not initialize but instead
** return the value of g.disableInit as the result code.  This can be used
** to simulate an initialization failure.
*/
static int counterMutexInit(void){ 
  int rc;
  if( g.disableInit ) return g.disableInit;
  rc = g.m.xMutexInit();
  g.isInit = 1;
  return rc;
}

/*
** Uninitialize the mutex subsystem
*/
static int counterMutexEnd(void){ 
  g.isInit = 0;
  return g.m.xMutexEnd();
}

/*
** Allocate a countable mutex
*/
static sqlite3_mutex *counterMutexAlloc(int eType){
  sqlite3_mutex *pReal;
  sqlite3_mutex *pRet = 0;

  assert( g.isInit );
  assert(eType<8 && eType>=0);

  pReal = g.m.xMutexAlloc(eType);
  if( !pReal ) return 0;

  if( eType==SQLITE_MUTEX_FAST || eType==SQLITE_MUTEX_RECURSIVE ){
    pRet = (sqlite3_mutex *)malloc(sizeof(sqlite3_mutex));
  }else{
    pRet = &g.aStatic[eType-2];
  }

  pRet->eType = eType;
  pRet->pReal = pReal;
  return pRet;
}

/*
** Free a countable mutex
*/
static void counterMutexFree(sqlite3_mutex *p){
  assert( g.isInit );
  g.m.xMutexFree(p->pReal);
  if( p->eType==SQLITE_MUTEX_FAST || p->eType==SQLITE_MUTEX_RECURSIVE ){
    free(p);
  }
}

/*
** Enter a countable mutex.  Block until entry is safe.
*/
static void counterMutexEnter(sqlite3_mutex *p){
  assert( g.isInit );
  g.aCounter[p->eType]++;
  g.m.xMutexEnter(p->pReal);
}

/*
** Try to enter a mutex.  Return true on success.
*/
static int counterMutexTry(sqlite3_mutex *p){
  assert( g.isInit );
  g.aCounter[p->eType]++;
  if( g.disableTry ) return SQLITE_BUSY;
  return g.m.xMutexTry(p->pReal);
}

/* Leave a mutex
*/
static void counterMutexLeave(sqlite3_mutex *p){
  assert( g.isInit );
  g.m.xMutexLeave(p->pReal);
}

/*
** sqlite3_shutdown
*/
static int test_shutdown(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc;

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  rc = sqlite3_shutdown();
  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

/*
** sqlite3_initialize
*/
static int test_initialize(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc;

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  rc = sqlite3_initialize();
  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

/*
** install_mutex_counters BOOLEAN
*/
static int test_install_mutex_counters(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = SQLITE_OK;
  int isInstall;

  sqlite3_mutex_methods counter_methods = {
    counterMutexInit,
    counterMutexEnd,
    counterMutexAlloc,
    counterMutexFree,
    counterMutexEnter,
    counterMutexTry,
    counterMutexLeave,
    counterMutexHeld,
    counterMutexNotheld
  };

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN");
    return TCL_ERROR;
  }
  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){
    return TCL_ERROR;
  }

  assert(isInstall==0 || isInstall==1);
  assert(g.isInstalled==0 || g.isInstalled==1);
  if( isInstall==g.isInstalled ){
    Tcl_AppendResult(interp, "mutex counters are ", 0);
    Tcl_AppendResult(interp, isInstall?"already installed":"not installed", 0);
    return TCL_ERROR;
  }

  if( isInstall ){
    assert( g.m.xMutexAlloc==0 );
    rc = sqlite3_config(SQLITE_CONFIG_GETMUTEX, &g.m);
    if( rc==SQLITE_OK ){
      sqlite3_config(SQLITE_CONFIG_MUTEX, &counter_methods);
    }
    g.disableTry = 0;
  }else{
    assert( g.m.xMutexAlloc );
    rc = sqlite3_config(SQLITE_CONFIG_MUTEX, &g.m);
    memset(&g.m, 0, sizeof(sqlite3_mutex_methods));
  }

  if( rc==SQLITE_OK ){
    g.isInstalled = isInstall;
  }

  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

/*
** read_mutex_counters
*/
static int test_read_mutex_counters(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_Obj *pRet;
  int ii;
  char *aName[8] = {
    "fast",        "recursive",   "static_master", "static_mem", 
    "static_open", "static_prng", "static_lru",    "static_lru2"
  };

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  pRet = Tcl_NewObj();
  Tcl_IncrRefCount(pRet);
  for(ii=0; ii<8; ii++){
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(aName[ii], -1));
    Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(g.aCounter[ii]));
  }
  Tcl_SetObjResult(interp, pRet);
  Tcl_DecrRefCount(pRet);

  return TCL_OK;
}

/*
** clear_mutex_counters
*/
static int test_clear_mutex_counters(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int ii;

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  for(ii=0; ii<8; ii++){
    g.aCounter[ii] = 0;
  }
  return TCL_OK;
}

/*
** Create and free a mutex.  Return the mutex pointer.  The pointer
** will be invalid since the mutex has already been freed.  The
** return pointer just checks to see if the mutex really was allocated.
*/
static int test_alloc_mutex(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#if SQLITE_THREADSAFE
  sqlite3_mutex *p = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  char zBuf[100];
  sqlite3_mutex_free(p);
  sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", p);
  Tcl_AppendResult(interp, zBuf, (char*)0);
#endif
  return TCL_OK;
}

/*
** sqlite3_config OPTION
**
** OPTION can be either one of the keywords:
**
**            SQLITE_CONFIG_SINGLETHREAD
**            SQLITE_CONFIG_MULTITHREAD
**            SQLITE_CONFIG_SERIALIZED
**
** Or OPTION can be an raw integer.
*/
static int test_config(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  struct ConfigOption {
    const char *zName;
    int iValue;
  } aOpt[] = {
    {"singlethread", SQLITE_CONFIG_SINGLETHREAD},
    {"multithread",  SQLITE_CONFIG_MULTITHREAD},
    {"serialized",   SQLITE_CONFIG_SERIALIZED},
    {0, 0}
  };
  int s = sizeof(struct ConfigOption);
  int i;
  int rc;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  if( Tcl_GetIndexFromObjStruct(interp, objv[1], aOpt, s, "flag", 0, &i) ){
    if( Tcl_GetIntFromObj(interp, objv[1], &i) ){
      return TCL_ERROR;
    }
  }else{
    i = aOpt[i].iValue;
  }

  rc = sqlite3_config(i);
  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
  return TCL_OK;
}

static sqlite3 *getDbPointer(Tcl_Interp *pInterp, Tcl_Obj *pObj){
  sqlite3 *db;
  Tcl_CmdInfo info;
  char *zCmd = Tcl_GetString(pObj);
  if( Tcl_GetCommandInfo(pInterp, zCmd, &info) ){
    db = *((sqlite3 **)info.objClientData);
  }else{
    db = (sqlite3*)sqlite3TestTextToPtr(zCmd);
  }
  assert( db );
  return db;
}

static int test_enter_db_mutex(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  db = getDbPointer(interp, objv[1]);
  if( !db ){
    return TCL_ERROR;
  }
  sqlite3_mutex_enter(sqlite3_db_mutex(db));
  return TCL_OK;
}

static int test_leave_db_mutex(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  db = getDbPointer(interp, objv[1]);
  if( !db ){
    return TCL_ERROR;
  }
  sqlite3_mutex_leave(sqlite3_db_mutex(db));
  return TCL_OK;
}

int Sqlitetest_mutex_Init(Tcl_Interp *interp){
  static struct {
    char *zName;
    Tcl_ObjCmdProc *xProc;
  } aCmd[] = {
    { "sqlite3_shutdown",        (Tcl_ObjCmdProc*)test_shutdown },
    { "sqlite3_initialize",      (Tcl_ObjCmdProc*)test_initialize },
    { "sqlite3_config",          (Tcl_ObjCmdProc*)test_config },

    { "enter_db_mutex",          (Tcl_ObjCmdProc*)test_enter_db_mutex },
    { "leave_db_mutex",          (Tcl_ObjCmdProc*)test_leave_db_mutex },

    { "alloc_dealloc_mutex",     (Tcl_ObjCmdProc*)test_alloc_mutex },
    { "install_mutex_counters",  (Tcl_ObjCmdProc*)test_install_mutex_counters },
    { "read_mutex_counters",     (Tcl_ObjCmdProc*)test_read_mutex_counters },
    { "clear_mutex_counters",    (Tcl_ObjCmdProc*)test_clear_mutex_counters },
  };
  int i;
  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
  }

  Tcl_LinkVar(interp, "disable_mutex_init", 
              (char*)&g.disableInit, TCL_LINK_INT);
  Tcl_LinkVar(interp, "disable_mutex_try", 
              (char*)&g.disableTry, TCL_LINK_INT);
  return SQLITE_OK;
}

Added src/test_onefile.c.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
/*
** 2007 September 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** $Id: test_onefile.c,v 1.12 2009/04/07 11:21:29 danielk1977 Exp $
**
** OVERVIEW:
**
**   This file contains some example code demonstrating how the SQLite 
**   vfs feature can be used to have SQLite operate directly on an 
**   embedded media, without using an intermediate file system.
**
**   Because this is only a demo designed to run on a workstation, the
**   underlying media is simulated using a regular file-system file. The
**   size of the file is fixed when it is first created (default size 10 MB).
**   From SQLite's point of view, this space is used to store a single
**   database file and the journal file. 
**
**   Any statement journal created is stored in volatile memory obtained 
**   from sqlite3_malloc(). Any attempt to create a temporary database file 
**   will fail (SQLITE_IOERR). To prevent SQLite from attempting this,
**   it should be configured to store all temporary database files in 
**   main memory (see pragma "temp_store" or the SQLITE_TEMP_STORE compile 
**   time option).
**
** ASSUMPTIONS:
**
**   After it has been created, the blob file is accessed using the
**   following three functions only:
**
**       mediaRead();            - Read a 512 byte block from the file.
**       mediaWrite();           - Write a 512 byte block to the file.
**       mediaSync();            - Tell the media hardware to sync.
**
**   It is assumed that these can be easily implemented by any "real"
**   media vfs driver adapting this code.
**
** FILE FORMAT:
**
**   The basic principle is that the "database file" is stored at the
**   beginning of the 10 MB blob and grows in a forward direction. The 
**   "journal file" is stored at the end of the 10MB blob and grows
**   in the reverse direction. If, during a transaction, insufficient
**   space is available to expand either the journal or database file,
**   an SQLITE_FULL error is returned. The database file is never allowed
**   to consume more than 90% of the blob space. If SQLite tries to
**   create a file larger than this, SQLITE_FULL is returned.
**
**   No allowance is made for "wear-leveling", as is required by.
**   embedded devices in the absence of equivalent hardware features.
**
**   The first 512 block byte of the file is reserved for storing the
**   size of the "database file". It is updated as part of the sync()
**   operation. On startup, it can only be trusted if no journal file
**   exists. If a journal-file does exist, then it stores the real size
**   of the database region. The second and subsequent blocks store the 
**   actual database content.
**
**   The size of the "journal file" is not stored persistently in the 
**   file. When the system is running, the size of the journal file is
**   stored in volatile memory. When recovering from a crash, this vfs
**   reports a very large size for the journal file. The normal journal
**   header and checksum mechanisms serve to prevent SQLite from 
**   processing any data that lies past the logical end of the journal.
**
**   When SQLite calls OsDelete() to delete the journal file, the final
**   512 bytes of the blob (the area containing the first journal header)
**   are zeroed.
**
** LOCKING:
**
**   File locking is a no-op. Only one connection may be open at any one
**   time using this demo vfs.
*/

#include "sqlite3.h"
#include <assert.h>
#include <string.h>

/*
** Maximum pathname length supported by the fs backend.
*/
#define BLOCKSIZE 512
#define BLOBSIZE 10485760

/*
** Name used to identify this VFS.
*/
#define FS_VFS_NAME "fs"

typedef struct fs_real_file fs_real_file;
struct fs_real_file {
  sqlite3_file *pFile;
  const char *zName;
  int nDatabase;              /* Current size of database region */
  int nJournal;               /* Current size of journal region */
  int nBlob;                  /* Total size of allocated blob */
  int nRef;                   /* Number of pointers to this structure */
  fs_real_file *pNext;
  fs_real_file **ppThis;
};

typedef struct fs_file fs_file;
struct fs_file {
  sqlite3_file base;
  int eType;
  fs_real_file *pReal;
};

typedef struct tmp_file tmp_file;
struct tmp_file {
  sqlite3_file base;
  int nSize;
  int nAlloc;
  char *zAlloc;
};

/* Values for fs_file.eType. */
#define DATABASE_FILE   1
#define JOURNAL_FILE    2

/*
** Method declarations for fs_file.
*/
static int fsClose(sqlite3_file*);
static int fsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
static int fsWrite(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
static int fsTruncate(sqlite3_file*, sqlite3_int64 size);
static int fsSync(sqlite3_file*, int flags);
static int fsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
static int fsLock(sqlite3_file*, int);
static int fsUnlock(sqlite3_file*, int);
static int fsCheckReservedLock(sqlite3_file*, int *pResOut);
static int fsFileControl(sqlite3_file*, int op, void *pArg);
static int fsSectorSize(sqlite3_file*);
static int fsDeviceCharacteristics(sqlite3_file*);

/*
** Method declarations for tmp_file.
*/
static int tmpClose(sqlite3_file*);
static int tmpRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
static int tmpWrite(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
static int tmpTruncate(sqlite3_file*, sqlite3_int64 size);
static int tmpSync(sqlite3_file*, int flags);
static int tmpFileSize(sqlite3_file*, sqlite3_int64 *pSize);
static int tmpLock(sqlite3_file*, int);
static int tmpUnlock(sqlite3_file*, int);
static int tmpCheckReservedLock(sqlite3_file*, int *pResOut);
static int tmpFileControl(sqlite3_file*, int op, void *pArg);
static int tmpSectorSize(sqlite3_file*);
static int tmpDeviceCharacteristics(sqlite3_file*);

/*
** Method declarations for fs_vfs.
*/
static int fsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
static int fsDelete(sqlite3_vfs*, const char *zName, int syncDir);
static int fsAccess(sqlite3_vfs*, const char *zName, int flags, int *);
static int fsFullPathname(sqlite3_vfs*, const char *zName, int nOut,char *zOut);
static void *fsDlOpen(sqlite3_vfs*, const char *zFilename);
static void fsDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
static void (*fsDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
static void fsDlClose(sqlite3_vfs*, void*);
static int fsRandomness(sqlite3_vfs*, int nByte, char *zOut);
static int fsSleep(sqlite3_vfs*, int microseconds);
static int fsCurrentTime(sqlite3_vfs*, double*);


typedef struct fs_vfs_t fs_vfs_t;
struct fs_vfs_t {
  sqlite3_vfs base;
  fs_real_file *pFileList;
  sqlite3_vfs *pParent;
};

static fs_vfs_t fs_vfs = {
  {
    1,                                          /* iVersion */
    0,                                          /* szOsFile */
    0,                                          /* mxPathname */
    0,                                          /* pNext */
    FS_VFS_NAME,                                /* zName */
    0,                                          /* pAppData */
    fsOpen,                                     /* xOpen */
    fsDelete,                                   /* xDelete */
    fsAccess,                                   /* xAccess */
    fsFullPathname,                             /* xFullPathname */
    fsDlOpen,                                   /* xDlOpen */
    fsDlError,                                  /* xDlError */
    fsDlSym,                                    /* xDlSym */
    fsDlClose,                                  /* xDlClose */
    fsRandomness,                               /* xRandomness */
    fsSleep,                                    /* xSleep */
    fsCurrentTime                               /* xCurrentTime */
  }, 
  0,                                            /* pFileList */
  0                                             /* pParent */
};

static sqlite3_io_methods fs_io_methods = {
  1,                            /* iVersion */
  fsClose,                      /* xClose */
  fsRead,                       /* xRead */
  fsWrite,                      /* xWrite */
  fsTruncate,                   /* xTruncate */
  fsSync,                       /* xSync */
  fsFileSize,                   /* xFileSize */
  fsLock,                       /* xLock */
  fsUnlock,                     /* xUnlock */
  fsCheckReservedLock,          /* xCheckReservedLock */
  fsFileControl,                /* xFileControl */
  fsSectorSize,                 /* xSectorSize */
  fsDeviceCharacteristics       /* xDeviceCharacteristics */
};


static sqlite3_io_methods tmp_io_methods = {
  1,                            /* iVersion */
  tmpClose,                     /* xClose */
  tmpRead,                      /* xRead */
  tmpWrite,                     /* xWrite */
  tmpTruncate,                  /* xTruncate */
  tmpSync,                      /* xSync */
  tmpFileSize,                  /* xFileSize */
  tmpLock,                      /* xLock */
  tmpUnlock,                    /* xUnlock */
  tmpCheckReservedLock,         /* xCheckReservedLock */
  tmpFileControl,               /* xFileControl */
  tmpSectorSize,                /* xSectorSize */
  tmpDeviceCharacteristics      /* xDeviceCharacteristics */
};

/* Useful macros used in several places */
#define MIN(x,y) ((x)<(y)?(x):(y))
#define MAX(x,y) ((x)>(y)?(x):(y))


/*
** Close a tmp-file.
*/
static int tmpClose(sqlite3_file *pFile){
  tmp_file *pTmp = (tmp_file *)pFile;
  sqlite3_free(pTmp->zAlloc);
  return SQLITE_OK;
}

/*
** Read data from a tmp-file.
*/
static int tmpRead(
  sqlite3_file *pFile, 
  void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  tmp_file *pTmp = (tmp_file *)pFile;
  if( (iAmt+iOfst)>pTmp->nSize ){
    return SQLITE_IOERR_SHORT_READ;
  }
  memcpy(zBuf, &pTmp->zAlloc[iOfst], iAmt);
  return SQLITE_OK;
}

/*
** Write data to a tmp-file.
*/
static int tmpWrite(
  sqlite3_file *pFile, 
  const void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  tmp_file *pTmp = (tmp_file *)pFile;
  if( (iAmt+iOfst)>pTmp->nAlloc ){
    int nNew = 2*(iAmt+iOfst+pTmp->nAlloc);
    char *zNew = sqlite3_realloc(pTmp->zAlloc, nNew);
    if( !zNew ){
      return SQLITE_NOMEM;
    }
    pTmp->zAlloc = zNew;
    pTmp->nAlloc = nNew;
  }
  memcpy(&pTmp->zAlloc[iOfst], zBuf, iAmt);
  pTmp->nSize = MAX(pTmp->nSize, iOfst+iAmt);
  return SQLITE_OK;
}

/*
** Truncate a tmp-file.
*/
static int tmpTruncate(sqlite3_file *pFile, sqlite_int64 size){
  tmp_file *pTmp = (tmp_file *)pFile;
  pTmp->nSize = MIN(pTmp->nSize, size);
  return SQLITE_OK;
}

/*
** Sync a tmp-file.
*/
static int tmpSync(sqlite3_file *pFile, int flags){
  return SQLITE_OK;
}

/*
** Return the current file-size of a tmp-file.
*/
static int tmpFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  tmp_file *pTmp = (tmp_file *)pFile;
  *pSize = pTmp->nSize;
  return SQLITE_OK;
}

/*
** Lock a tmp-file.
*/
static int tmpLock(sqlite3_file *pFile, int eLock){
  return SQLITE_OK;
}

/*
** Unlock a tmp-file.
*/
static int tmpUnlock(sqlite3_file *pFile, int eLock){
  return SQLITE_OK;
}

/*
** Check if another file-handle holds a RESERVED lock on a tmp-file.
*/
static int tmpCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  *pResOut = 0;
  return SQLITE_OK;
}

/*
** File control method. For custom operations on a tmp-file.
*/
static int tmpFileControl(sqlite3_file *pFile, int op, void *pArg){
  return SQLITE_OK;
}

/*
** Return the sector-size in bytes for a tmp-file.
*/
static int tmpSectorSize(sqlite3_file *pFile){
  return 0;
}

/*
** Return the device characteristic flags supported by a tmp-file.
*/
static int tmpDeviceCharacteristics(sqlite3_file *pFile){
  return 0;
}

/*
** Close an fs-file.
*/
static int fsClose(sqlite3_file *pFile){
  int rc = SQLITE_OK;
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = p->pReal;

  /* Decrement the real_file ref-count. */
  pReal->nRef--;
  assert(pReal->nRef>=0);

  /* When the ref-count reaches 0, destroy the structure */
  if( pReal->nRef==0 ){
    *pReal->ppThis = pReal->pNext;
    if( pReal->pNext ){
      pReal->pNext->ppThis = pReal->ppThis;
    }
    rc = pReal->pFile->pMethods->xClose(pReal->pFile);
    sqlite3_free(pReal);
  }

  return rc;
}

/*
** Read data from an fs-file.
*/
static int fsRead(
  sqlite3_file *pFile, 
  void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  int rc = SQLITE_OK;
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = p->pReal;
  sqlite3_file *pF = pReal->pFile;

  if( (p->eType==DATABASE_FILE && (iAmt+iOfst)>pReal->nDatabase)
   || (p->eType==JOURNAL_FILE && (iAmt+iOfst)>pReal->nJournal)
  ){
    rc = SQLITE_IOERR_SHORT_READ;
  }else if( p->eType==DATABASE_FILE ){
    rc = pF->pMethods->xRead(pF, zBuf, iAmt, iOfst+BLOCKSIZE);
  }else{
    /* Journal file. */
    int iRem = iAmt;
    int iBuf = 0;
    int ii = iOfst;
    while( iRem>0 && rc==SQLITE_OK ){
      int iRealOff = pReal->nBlob - BLOCKSIZE*((ii/BLOCKSIZE)+1) + ii%BLOCKSIZE;
      int iRealAmt = MIN(iRem, BLOCKSIZE - (iRealOff%BLOCKSIZE));

      rc = pF->pMethods->xRead(pF, &((char *)zBuf)[iBuf], iRealAmt, iRealOff);
      ii += iRealAmt;
      iBuf += iRealAmt;
      iRem -= iRealAmt;
    }
  }

  return rc;
}

/*
** Write data to an fs-file.
*/
static int fsWrite(
  sqlite3_file *pFile, 
  const void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  int rc = SQLITE_OK;
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = p->pReal;
  sqlite3_file *pF = pReal->pFile;

  if( p->eType==DATABASE_FILE ){
    if( (iAmt+iOfst+BLOCKSIZE)>(pReal->nBlob-pReal->nJournal) ){
      rc = SQLITE_FULL;
    }else{
      rc = pF->pMethods->xWrite(pF, zBuf, iAmt, iOfst+BLOCKSIZE);
      if( rc==SQLITE_OK ){
        pReal->nDatabase = MAX(pReal->nDatabase, iAmt+iOfst);
      }
    }
  }else{
    /* Journal file. */
    int iRem = iAmt;
    int iBuf = 0;
    int ii = iOfst;
    while( iRem>0 && rc==SQLITE_OK ){
      int iRealOff = pReal->nBlob - BLOCKSIZE*((ii/BLOCKSIZE)+1) + ii%BLOCKSIZE;
      int iRealAmt = MIN(iRem, BLOCKSIZE - (iRealOff%BLOCKSIZE));

      if( iRealOff<(pReal->nDatabase+BLOCKSIZE) ){
        rc = SQLITE_FULL;
      }else{
        rc = pF->pMethods->xWrite(pF, &((char *)zBuf)[iBuf], iRealAmt,iRealOff);
        ii += iRealAmt;
        iBuf += iRealAmt;
        iRem -= iRealAmt;
      }
    }
    if( rc==SQLITE_OK ){
      pReal->nJournal = MAX(pReal->nJournal, iAmt+iOfst);
    }
  }

  return rc;
}

/*
** Truncate an fs-file.
*/
static int fsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = p->pReal;
  if( p->eType==DATABASE_FILE ){
    pReal->nDatabase = MIN(pReal->nDatabase, size);
  }else{
    pReal->nJournal = MIN(pReal->nJournal, size);
  }
  return SQLITE_OK;
}

/*
** Sync an fs-file.
*/
static int fsSync(sqlite3_file *pFile, int flags){
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = p->pReal;
  sqlite3_file *pRealFile = pReal->pFile;
  int rc = SQLITE_OK;

  if( p->eType==DATABASE_FILE ){
    unsigned char zSize[4];
    zSize[0] = (pReal->nDatabase&0xFF000000)>>24;
    zSize[1] = (pReal->nDatabase&0x00FF0000)>>16;
    zSize[2] = (pReal->nDatabase&0x0000FF00)>>8;
    zSize[3] = (pReal->nDatabase&0x000000FF);
    rc = pRealFile->pMethods->xWrite(pRealFile, zSize, 4, 0);
  }
  if( rc==SQLITE_OK ){
    rc = pRealFile->pMethods->xSync(pRealFile, flags&(~SQLITE_SYNC_DATAONLY));
  }

  return rc;
}

/*
** Return the current file-size of an fs-file.
*/
static int fsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = p->pReal;
  if( p->eType==DATABASE_FILE ){
    *pSize = pReal->nDatabase;
  }else{
    *pSize = pReal->nJournal;
  }
  return SQLITE_OK;
}

/*
** Lock an fs-file.
*/
static int fsLock(sqlite3_file *pFile, int eLock){
  return SQLITE_OK;
}

/*
** Unlock an fs-file.
*/
static int fsUnlock(sqlite3_file *pFile, int eLock){
  return SQLITE_OK;
}

/*
** Check if another file-handle holds a RESERVED lock on an fs-file.
*/
static int fsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  *pResOut = 0;
  return SQLITE_OK;
}

/*
** File control method. For custom operations on an fs-file.
*/
static int fsFileControl(sqlite3_file *pFile, int op, void *pArg){
  return SQLITE_OK;
}

/*
** Return the sector-size in bytes for an fs-file.
*/
static int fsSectorSize(sqlite3_file *pFile){
  return BLOCKSIZE;
}

/*
** Return the device characteristic flags supported by an fs-file.
*/
static int fsDeviceCharacteristics(sqlite3_file *pFile){
  return 0;
}

/*
** Open an fs file handle.
*/
static int fsOpen(
  sqlite3_vfs *pVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs;
  fs_file *p = (fs_file *)pFile;
  fs_real_file *pReal = 0;
  int eType;
  int nName;
  int rc = SQLITE_OK;

  if( 0==(flags&(SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_MAIN_JOURNAL)) ){
    tmp_file *p = (tmp_file *)pFile;
    memset(p, 0, sizeof(*p));
    p->base.pMethods = &tmp_io_methods;
    return SQLITE_OK;
  }

  eType = ((flags&(SQLITE_OPEN_MAIN_DB))?DATABASE_FILE:JOURNAL_FILE);
  p->base.pMethods = &fs_io_methods;
  p->eType = eType;

  assert(strlen("-journal")==8);
  nName = strlen(zName)-((eType==JOURNAL_FILE)?8:0);
  pReal=pFsVfs->pFileList; 
  for(; pReal && strncmp(pReal->zName, zName, nName); pReal=pReal->pNext);

  if( !pReal ){
    int real_flags = (flags&~(SQLITE_OPEN_MAIN_DB))|SQLITE_OPEN_TEMP_DB;
    sqlite3_int64 size;
    sqlite3_file *pRealFile;
    sqlite3_vfs *pParent = pFsVfs->pParent;
    assert(eType==DATABASE_FILE);

    pReal = (fs_real_file *)sqlite3_malloc(sizeof(*pReal)+pParent->szOsFile);
    if( !pReal ){
      rc = SQLITE_NOMEM;
      goto open_out;
    }
    memset(pReal, 0, sizeof(*pReal)+pParent->szOsFile);
    pReal->zName = zName;
    pReal->pFile = (sqlite3_file *)(&pReal[1]);

    rc = pParent->xOpen(pParent, zName, pReal->pFile, real_flags, pOutFlags);
    if( rc!=SQLITE_OK ){
      goto open_out;
    }
    pRealFile = pReal->pFile;

    rc = pRealFile->pMethods->xFileSize(pRealFile, &size);
    if( rc!=SQLITE_OK ){
      goto open_out;
    }
    if( size==0 ){
      rc = pRealFile->pMethods->xWrite(pRealFile, "\0", 1, BLOBSIZE-1);
      pReal->nBlob = BLOBSIZE;
    }else{
      unsigned char zS[4];
      pReal->nBlob = size;
      rc = pRealFile->pMethods->xRead(pRealFile, zS, 4, 0);
      pReal->nDatabase = (zS[0]<<24)+(zS[1]<<16)+(zS[2]<<8)+zS[3];
      if( rc==SQLITE_OK ){
        rc = pRealFile->pMethods->xRead(pRealFile, zS, 4, pReal->nBlob-4);
        if( zS[0] || zS[1] || zS[2] || zS[3] ){
          pReal->nJournal = pReal->nBlob;
        }
      }
    }

    if( rc==SQLITE_OK ){
      pReal->pNext = pFsVfs->pFileList;
      if( pReal->pNext ){
        pReal->pNext->ppThis = &pReal->pNext;
      }
      pReal->ppThis = &pFsVfs->pFileList;
      pFsVfs->pFileList = pReal;
    }
  }

open_out:
  if( pReal ){
    if( rc==SQLITE_OK ){
      p->pReal = pReal;
      pReal->nRef++;
    }else{
      if( pReal->pFile->pMethods ){
        pReal->pFile->pMethods->xClose(pReal->pFile);
      }
      sqlite3_free(pReal);
    }
  }
  return rc;
}

/*
** Delete the file located at zPath. If the dirSync argument is true,
** ensure the file-system modifications are synced to disk before
** returning.
*/
static int fsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  int rc = SQLITE_OK;
  fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs;
  fs_real_file *pReal;
  sqlite3_file *pF;
  int nName = strlen(zPath) - 8;

  assert(strlen("-journal")==8);
  assert(strcmp("-journal", &zPath[nName])==0);

  pReal = pFsVfs->pFileList; 
  for(; pReal && strncmp(pReal->zName, zPath, nName); pReal=pReal->pNext);
  if( pReal ){
    pF = pReal->pFile;
    rc = pF->pMethods->xWrite(pF, "\0\0\0\0", 4, pReal->nBlob-BLOCKSIZE);
    if( rc==SQLITE_OK ){
      pReal->nJournal = 0;
    }
  }
  return rc;
}

/*
** Test for access permissions. Return true if the requested permission
** is available, or false otherwise.
*/
static int fsAccess(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int flags, 
  int *pResOut
){
  fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs;
  fs_real_file *pReal;
  int isJournal = 0;
  int nName = strlen(zPath);

  if( flags!=SQLITE_ACCESS_EXISTS ){
    sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
    return pParent->xAccess(pParent, zPath, flags, pResOut);
  }

  assert(strlen("-journal")==8);
  if( nName>8 && strcmp("-journal", &zPath[nName-8])==0 ){
    nName -= 8;
    isJournal = 1;
  }

  pReal = pFsVfs->pFileList; 
  for(; pReal && strncmp(pReal->zName, zPath, nName); pReal=pReal->pNext);

  *pResOut = (pReal && (!isJournal || pReal->nJournal>0));
  return SQLITE_OK;
}

/*
** Populate buffer zOut with the full canonical pathname corresponding
** to the pathname in zPath. zOut is guaranteed to point to a buffer
** of at least (FS_MAX_PATHNAME+1) bytes.
*/
static int fsFullPathname(
  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
  const char *zPath,            /* Possibly relative input path */
  int nOut,                     /* Size of output buffer in bytes */
  char *zOut                    /* Output buffer */
){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  return pParent->xFullPathname(pParent, zPath, nOut, zOut);
}

/*
** Open the dynamic library located at zPath and return a handle.
*/
static void *fsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  return pParent->xDlOpen(pParent, zPath);
}

/*
** Populate the buffer zErrMsg (size nByte bytes) with a human readable
** utf-8 string describing the most recent error encountered associated 
** with dynamic libraries.
*/
static void fsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  pParent->xDlError(pParent, nByte, zErrMsg);
}

/*
** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
*/
static void (*fsDlSym(sqlite3_vfs *pVfs, void *pH, const char *zSym))(void){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  return pParent->xDlSym(pParent, pH, zSym);
}

/*
** Close the dynamic library handle pHandle.
*/
static void fsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  pParent->xDlClose(pParent, pHandle);
}

/*
** Populate the buffer pointed to by zBufOut with nByte bytes of 
** random data.
*/
static int fsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  return pParent->xRandomness(pParent, nByte, zBufOut);
}

/*
** Sleep for nMicro microseconds. Return the number of microseconds 
** actually slept.
*/
static int fsSleep(sqlite3_vfs *pVfs, int nMicro){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  return pParent->xSleep(pParent, nMicro);
}

/*
** Return the current time as a Julian Day number in *pTimeOut.
*/
static int fsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent;
  return pParent->xCurrentTime(pParent, pTimeOut);
}

/*
** This procedure registers the fs vfs with SQLite. If the argument is
** true, the fs vfs becomes the new default vfs. It is the only publicly
** available function in this file.
*/
int fs_register(void){
  if( fs_vfs.pParent ) return SQLITE_OK;
  fs_vfs.pParent = sqlite3_vfs_find(0);
  fs_vfs.base.mxPathname = fs_vfs.pParent->mxPathname;
  fs_vfs.base.szOsFile = MAX(sizeof(tmp_file), sizeof(fs_file));
  return sqlite3_vfs_register(&fs_vfs.base, 0);
}

#ifdef SQLITE_TEST
  int SqlitetestOnefile_Init() {return fs_register();}
#endif

Added src/test_osinst.c.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
/*
** 2008 April 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains the implementation of an SQLite vfs wrapper that
** adds instrumentation to all vfs and file methods. C and Tcl interfaces
** are provided to control the instrumentation.
**
** $Id: test_osinst.c,v 1.19 2009/01/08 17:57:32 danielk1977 Exp $
*/

#ifdef SQLITE_ENABLE_INSTVFS
/*
** C interface:
**
**   sqlite3_instvfs_create()
**   sqlite3_instvfs_destroy()
**   sqlite3_instvfs_configure()
**
**   sqlite3_instvfs_reset()
**   sqlite3_instvfs_get()
**
**   sqlite3_instvfs_binarylog
**   sqlite3_instvfs_binarylog_marker
**
** Tcl interface (omitted if SQLITE_TEST is not set):
** 
**   sqlite3_instvfs create NAME ?PARENT?
**
**       Create and register new vfs called $NAME, which is a wrapper around
**       the existing vfs $PARENT. If the PARENT argument is omitted, the
**       new vfs is a wrapper around the current default vfs.
**
**   sqlite3_instvfs destroy NAME
**
**       Deregister and destroy the vfs named $NAME, which must have been
**       created by an earlier invocation of [sqlite3_instvfs create].
**
**   sqlite3_instvfs configure NAME SCRIPT
**
**       Configure the callback script for the vfs $NAME, which much have
**       been created by an earlier invocation of [sqlite3_instvfs create].
**       After a callback script has been configured, it is invoked each
**       time a vfs or file method is called by SQLite. Before invoking
**       the callback script, five arguments are appended to it:
**
**         * The name of the invoked method - i.e. "xRead".
**
**         * The time consumed by the method call as measured by 
**           sqlite3Hwtime() (an integer value)
**
**         * A string value with a different meaning for different calls. 
**           For file methods, the name of the file being operated on. For
**           other methods it is the filename argument, if any.
**
**         * A 32-bit integer value with a call-specific meaning.
**
**         * A 64-bit integer value. For xRead() and xWrite() calls this
**           is the file offset being written to or read from. Unused by
**           all other calls.
**
**   sqlite3_instvfs reset NAME
**
**       Zero the internal event counters associated with vfs $NAME, 
**       which must have been created by an earlier invocation of 
**       [sqlite3_instvfs create].
**
**   sqlite3_instvfs report NAME
**
**       Return the values of the internal event counters associated 
**       with vfs $NAME. The report format is a list with one element
**       for each method call (xWrite, xRead etc.). Each element is
**       itself a list with three elements:
**
**         * The name of the method call - i.e. "xWrite",
**         * The total number of calls to the method (an integer).
**         * The aggregate time consumed by all calls to the method as
**           measured by sqlite3Hwtime() (an integer).
*/

#include "sqlite3.h"
#include <string.h>
#include <assert.h>

/*
** Maximum pathname length supported by the inst backend.
*/
#define INST_MAX_PATHNAME 512


/* File methods */
/* Vfs methods */
#define OS_ACCESS            1
#define OS_CHECKRESERVEDLOCK 2
#define OS_CLOSE             3
#define OS_CURRENTTIME       4
#define OS_DELETE            5
#define OS_DEVCHAR           6
#define OS_FILECONTROL       7
#define OS_FILESIZE          8
#define OS_FULLPATHNAME      9
#define OS_LOCK              11
#define OS_OPEN              12
#define OS_RANDOMNESS        13
#define OS_READ              14 
#define OS_SECTORSIZE        15
#define OS_SLEEP             16
#define OS_SYNC              17
#define OS_TRUNCATE          18
#define OS_UNLOCK            19
#define OS_WRITE             20

#define OS_NUMEVENTS         21

#define BINARYLOG_STRING     30
#define BINARYLOG_MARKER     31

#define BINARYLOG_PREPARE_V2 64
#define BINARYLOG_STEP       65
#define BINARYLOG_FINALIZE   66

struct InstVfs {
  sqlite3_vfs base;
  sqlite3_vfs *pVfs;

  void *pClient;
  void (*xDel)(void *);
  void (*xCall)(void *, int, int, sqlite3_int64, int, const char *, int, int, sqlite3_int64);

  /* Counters */
  sqlite3_int64 aTime[OS_NUMEVENTS];
  int aCount[OS_NUMEVENTS];

  int iNextFileId;
};
typedef struct InstVfs InstVfs;

#define REALVFS(p) (((InstVfs *)(p))->pVfs)

typedef struct inst_file inst_file;
struct inst_file {
  sqlite3_file base;
  sqlite3_file *pReal;
  InstVfs *pInstVfs;
  const char *zName;
  int iFileId;               /* File id number */
  int flags;
};

/*
** Method declarations for inst_file.
*/
static int instClose(sqlite3_file*);
static int instRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
static int instWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
static int instTruncate(sqlite3_file*, sqlite3_int64 size);
static int instSync(sqlite3_file*, int flags);
static int instFileSize(sqlite3_file*, sqlite3_int64 *pSize);
static int instLock(sqlite3_file*, int);
static int instUnlock(sqlite3_file*, int);
static int instCheckReservedLock(sqlite3_file*, int *pResOut);
static int instFileControl(sqlite3_file*, int op, void *pArg);
static int instSectorSize(sqlite3_file*);
static int instDeviceCharacteristics(sqlite3_file*);

/*
** Method declarations for inst_vfs.
*/
static int instOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
static int instDelete(sqlite3_vfs*, const char *zName, int syncDir);
static int instAccess(sqlite3_vfs*, const char *zName, int flags, int *);
static int instFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
static void *instDlOpen(sqlite3_vfs*, const char *zFilename);
static void instDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
static void (*instDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
static void instDlClose(sqlite3_vfs*, void*);
static int instRandomness(sqlite3_vfs*, int nByte, char *zOut);
static int instSleep(sqlite3_vfs*, int microseconds);
static int instCurrentTime(sqlite3_vfs*, double*);

static void binarylog_blob(sqlite3_vfs *, const char *, int, int); 

static sqlite3_vfs inst_vfs = {
  1,                      /* iVersion */
  sizeof(inst_file),      /* szOsFile */
  INST_MAX_PATHNAME,      /* mxPathname */
  0,                      /* pNext */
  0,                      /* zName */
  0,                      /* pAppData */
  instOpen,               /* xOpen */
  instDelete,             /* xDelete */
  instAccess,             /* xAccess */
  instFullPathname,       /* xFullPathname */
  instDlOpen,             /* xDlOpen */
  instDlError,            /* xDlError */
  instDlSym,              /* xDlSym */
  instDlClose,            /* xDlClose */
  instRandomness,         /* xRandomness */
  instSleep,              /* xSleep */
  instCurrentTime         /* xCurrentTime */
};

static sqlite3_io_methods inst_io_methods = {
  1,                            /* iVersion */
  instClose,                      /* xClose */
  instRead,                       /* xRead */
  instWrite,                      /* xWrite */
  instTruncate,                   /* xTruncate */
  instSync,                       /* xSync */
  instFileSize,                   /* xFileSize */
  instLock,                       /* xLock */
  instUnlock,                     /* xUnlock */
  instCheckReservedLock,          /* xCheckReservedLock */
  instFileControl,                /* xFileControl */
  instSectorSize,                 /* xSectorSize */
  instDeviceCharacteristics       /* xDeviceCharacteristics */
};

/* 
** hwtime.h contains inline assembler code for implementing 
** high-performance timing routines.
*/
#include "hwtime.h"

#define OS_TIME_IO(eEvent, A, B, Call) {     \
  inst_file *p = (inst_file *)pFile;         \
  InstVfs *pInstVfs = p->pInstVfs;           \
  int rc;                                    \
  sqlite_uint64 t = sqlite3Hwtime();         \
  rc = Call;                                 \
  t = sqlite3Hwtime() - t;                   \
  pInstVfs->aTime[eEvent] += t;              \
  pInstVfs->aCount[eEvent] += 1;             \
  if( pInstVfs->xCall ){                     \
    pInstVfs->xCall(                         \
      pInstVfs->pClient,eEvent,p->iFileId,t,rc,p->zName,p->flags,A,B  \
    );                                       \
  }                                          \
  return rc;                                 \
}

#define OS_TIME_VFS(eEvent, Z, flags, A, B, Call) {      \
  InstVfs *pInstVfs = (InstVfs *)pVfs;   \
  int rc;                                \
  sqlite_uint64 t = sqlite3Hwtime();     \
  rc = Call;                             \
  t = sqlite3Hwtime() - t;               \
  pInstVfs->aTime[eEvent] += t;          \
  pInstVfs->aCount[eEvent] += 1;         \
  if( pInstVfs->xCall ){                 \
    pInstVfs->xCall(pInstVfs->pClient,eEvent,0, t, rc, Z, flags, A, B); \
  }                                      \
  return rc;                             \
}

/*
** Close an inst-file.
*/
static int instClose(sqlite3_file *pFile){
  OS_TIME_IO(OS_CLOSE, 0, 0, 
    (p->pReal->pMethods ? p->pReal->pMethods->xClose(p->pReal) : SQLITE_OK)
  );
}

/*
** Read data from an inst-file.
*/
static int instRead(
  sqlite3_file *pFile, 
  void *zBuf, 
  int iAmt, 
  sqlite_int64 iOfst
){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)(((inst_file *)pFile)->pInstVfs);
  OS_TIME_IO(OS_READ, iAmt, (binarylog_blob(pVfs, zBuf, iAmt, 1), iOfst), 
      p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst)
  );
}

/*
** Write data to an inst-file.
*/
static int instWrite(
  sqlite3_file *pFile,
  const void *z,
  int iAmt,
  sqlite_int64 iOfst
){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)(((inst_file *)pFile)->pInstVfs);
  binarylog_blob(pVfs, z, iAmt, 1);
  OS_TIME_IO(OS_WRITE, iAmt, iOfst, 
      p->pReal->pMethods->xWrite(p->pReal, z, iAmt, iOfst)
  );
}

/*
** Truncate an inst-file.
*/
static int instTruncate(sqlite3_file *pFile, sqlite_int64 size){
  OS_TIME_IO(OS_TRUNCATE, 0, (int)size, 
    p->pReal->pMethods->xTruncate(p->pReal, size)
  );
}

/*
** Sync an inst-file.
*/
static int instSync(sqlite3_file *pFile, int flags){
  OS_TIME_IO(OS_SYNC, flags, 0, p->pReal->pMethods->xSync(p->pReal, flags));
}

/*
** Return the current file-size of an inst-file.
*/
static int instFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  OS_TIME_IO(OS_FILESIZE, (int)(*pSize), 0, 
    p->pReal->pMethods->xFileSize(p->pReal, pSize)
  );
}

/*
** Lock an inst-file.
*/
static int instLock(sqlite3_file *pFile, int eLock){
  OS_TIME_IO(OS_LOCK, eLock, 0, p->pReal->pMethods->xLock(p->pReal, eLock));
}

/*
** Unlock an inst-file.
*/
static int instUnlock(sqlite3_file *pFile, int eLock){
  OS_TIME_IO(OS_UNLOCK, eLock, 0, p->pReal->pMethods->xUnlock(p->pReal, eLock));
}

/*
** Check if another file-handle holds a RESERVED lock on an inst-file.
*/
static int instCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  OS_TIME_IO(OS_CHECKRESERVEDLOCK, 0, 0, 
      p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut)
  );
}

/*
** File control method. For custom operations on an inst-file.
*/
static int instFileControl(sqlite3_file *pFile, int op, void *pArg){
  OS_TIME_IO(OS_FILECONTROL, 0, 0, p->pReal->pMethods->xFileControl(p->pReal, op, pArg));
}

/*
** Return the sector-size in bytes for an inst-file.
*/
static int instSectorSize(sqlite3_file *pFile){
  OS_TIME_IO(OS_SECTORSIZE, 0, 0, p->pReal->pMethods->xSectorSize(p->pReal));
}

/*
** Return the device characteristic flags supported by an inst-file.
*/
static int instDeviceCharacteristics(sqlite3_file *pFile){
  OS_TIME_IO(OS_DEVCHAR, 0, 0, p->pReal->pMethods->xDeviceCharacteristics(p->pReal));
}

/*
** Open an inst file handle.
*/
static int instOpen(
  sqlite3_vfs *pVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  inst_file *p = (inst_file *)pFile;
  pFile->pMethods = &inst_io_methods;
  p->pReal = (sqlite3_file *)&p[1];
  p->pInstVfs = (InstVfs *)pVfs;
  p->zName = zName;
  p->flags = flags;
  p->iFileId = ++p->pInstVfs->iNextFileId;

  binarylog_blob(pVfs, zName, -1, 0);
  OS_TIME_VFS(OS_OPEN, zName, flags, p->iFileId, 0,
    REALVFS(pVfs)->xOpen(REALVFS(pVfs), zName, p->pReal, flags, pOutFlags)
  );
}

/*
** Delete the file located at zPath. If the dirSync argument is true,
** ensure the file-system modifications are synced to disk before
** returning.
*/
static int instDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  binarylog_blob(pVfs, zPath, -1, 0);
  OS_TIME_VFS(OS_DELETE, zPath, 0, dirSync, 0,
    REALVFS(pVfs)->xDelete(REALVFS(pVfs), zPath, dirSync) 
  );
}

/*
** Test for access permissions. Return true if the requested permission
** is available, or false otherwise.
*/
static int instAccess(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int flags, 
  int *pResOut
){
  binarylog_blob(pVfs, zPath, -1, 0);
  OS_TIME_VFS(OS_ACCESS, zPath, 0, flags, *pResOut, 
    REALVFS(pVfs)->xAccess(REALVFS(pVfs), zPath, flags, pResOut) 
  );
}

/*
** Populate buffer zOut with the full canonical pathname corresponding
** to the pathname in zPath. zOut is guaranteed to point to a buffer
** of at least (INST_MAX_PATHNAME+1) bytes.
*/
static int instFullPathname(
  sqlite3_vfs *pVfs, 
  const char *zPath, 
  int nOut, 
  char *zOut
){
  OS_TIME_VFS( OS_FULLPATHNAME, zPath, 0, 0, 0,
    REALVFS(pVfs)->xFullPathname(REALVFS(pVfs), zPath, nOut, zOut);
  );
}

/*
** Open the dynamic library located at zPath and return a handle.
*/
static void *instDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  return REALVFS(pVfs)->xDlOpen(REALVFS(pVfs), zPath);
}

/*
** Populate the buffer zErrMsg (size nByte bytes) with a human readable
** utf-8 string describing the most recent error encountered associated 
** with dynamic libraries.
*/
static void instDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  REALVFS(pVfs)->xDlError(REALVFS(pVfs), nByte, zErrMsg);
}

/*
** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
*/
static void (*instDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  return REALVFS(pVfs)->xDlSym(REALVFS(pVfs), p, zSym);
}

/*
** Close the dynamic library handle pHandle.
*/
static void instDlClose(sqlite3_vfs *pVfs, void *pHandle){
  REALVFS(pVfs)->xDlClose(REALVFS(pVfs), pHandle);
}

/*
** Populate the buffer pointed to by zBufOut with nByte bytes of 
** random data.
*/
static int instRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  OS_TIME_VFS( OS_RANDOMNESS, 0, 0, nByte, 0,
    REALVFS(pVfs)->xRandomness(REALVFS(pVfs), nByte, zBufOut);
  );
}

/*
** Sleep for nMicro microseconds. Return the number of microseconds 
** actually slept.
*/
static int instSleep(sqlite3_vfs *pVfs, int nMicro){
  OS_TIME_VFS( OS_SLEEP, 0, 0, nMicro, 0, 
    REALVFS(pVfs)->xSleep(REALVFS(pVfs), nMicro) 
  );
}

/*
** Return the current time as a Julian Day number in *pTimeOut.
*/
static int instCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  OS_TIME_VFS( OS_CURRENTTIME, 0, 0, 0, 0,
    REALVFS(pVfs)->xCurrentTime(REALVFS(pVfs), pTimeOut) 
  );
}

sqlite3_vfs *sqlite3_instvfs_create(const char *zName, const char *zParent){
  int nByte;
  InstVfs *p;
  sqlite3_vfs *pParent;

  pParent = sqlite3_vfs_find(zParent);
  if( !pParent ){
    return 0;
  }

  nByte = strlen(zName) + 1 + sizeof(InstVfs);
  p = (InstVfs *)sqlite3_malloc(nByte);
  if( p ){
    char *zCopy = (char *)&p[1];
    memset(p, 0, nByte);
    memcpy(p, &inst_vfs, sizeof(sqlite3_vfs));
    p->pVfs = pParent;
    memcpy(zCopy, zName, strlen(zName));
    p->base.zName = (const char *)zCopy;
    p->base.szOsFile += pParent->szOsFile;
    sqlite3_vfs_register((sqlite3_vfs *)p, 0);
  }

  return (sqlite3_vfs *)p;
}

void sqlite3_instvfs_configure(
  sqlite3_vfs *pVfs,
  void (*xCall)(
      void*, 
      int,                           /* File id */
      int,                           /* Event code */
      sqlite3_int64, 
      int,                           /* Return code */
      const char*,                   /* File name */
      int, 
      int, 
      sqlite3_int64
  ),
  void *pClient,
  void (*xDel)(void *)
){
  InstVfs *p = (InstVfs *)pVfs;
  assert( pVfs->xOpen==instOpen );
  if( p->xDel ){
    p->xDel(p->pClient);
  }
  p->xCall = xCall;
  p->xDel = xDel;
  p->pClient = pClient;
}

void sqlite3_instvfs_destroy(sqlite3_vfs *pVfs){
  if( pVfs ){
    sqlite3_vfs_unregister(pVfs);
    sqlite3_instvfs_configure(pVfs, 0, 0, 0);
    sqlite3_free(pVfs);
  }
}

void sqlite3_instvfs_reset(sqlite3_vfs *pVfs){
  InstVfs *p = (InstVfs *)pVfs;
  assert( pVfs->xOpen==instOpen );
  memset(p->aTime, 0, sizeof(sqlite3_int64)*OS_NUMEVENTS);
  memset(p->aCount, 0, sizeof(int)*OS_NUMEVENTS);
}

const char *sqlite3_instvfs_name(int eEvent){
  const char *zEvent = 0;

  switch( eEvent ){
    case OS_CLOSE:             zEvent = "xClose"; break;
    case OS_READ:              zEvent = "xRead"; break;
    case OS_WRITE:             zEvent = "xWrite"; break;
    case OS_TRUNCATE:          zEvent = "xTruncate"; break;
    case OS_SYNC:              zEvent = "xSync"; break;
    case OS_FILESIZE:          zEvent = "xFilesize"; break;
    case OS_LOCK:              zEvent = "xLock"; break;
    case OS_UNLOCK:            zEvent = "xUnlock"; break;
    case OS_CHECKRESERVEDLOCK: zEvent = "xCheckReservedLock"; break;
    case OS_FILECONTROL:       zEvent = "xFileControl"; break;
    case OS_SECTORSIZE:        zEvent = "xSectorSize"; break;
    case OS_DEVCHAR:           zEvent = "xDeviceCharacteristics"; break;
    case OS_OPEN:              zEvent = "xOpen"; break;
    case OS_DELETE:            zEvent = "xDelete"; break;
    case OS_ACCESS:            zEvent = "xAccess"; break;
    case OS_FULLPATHNAME:      zEvent = "xFullPathname"; break;
    case OS_RANDOMNESS:        zEvent = "xRandomness"; break;
    case OS_SLEEP:             zEvent = "xSleep"; break;
    case OS_CURRENTTIME:       zEvent = "xCurrentTime"; break;
  }

  return zEvent;
}

void sqlite3_instvfs_get(
  sqlite3_vfs *pVfs, 
  int eEvent, 
  const char **pzEvent, 
  sqlite3_int64 *pnClick, 
  int *pnCall
){
  InstVfs *p = (InstVfs *)pVfs;
  assert( pVfs->xOpen==instOpen );
  if( eEvent<1 || eEvent>=OS_NUMEVENTS ){
    *pzEvent = 0;
    *pnClick = 0;
    *pnCall = 0;
    return;
  }

  *pzEvent = sqlite3_instvfs_name(eEvent);
  *pnClick = p->aTime[eEvent];
  *pnCall = p->aCount[eEvent];
}

#define BINARYLOG_BUFFERSIZE 8192

struct InstVfsBinaryLog {
  int nBuf;
  char *zBuf;
  sqlite3_int64 iOffset;
  int log_data;
  sqlite3_file *pOut;
  char *zOut;                       /* Log file name */
};
typedef struct InstVfsBinaryLog InstVfsBinaryLog;

static void put32bits(unsigned char *p, unsigned int v){
  p[0] = v>>24;
  p[1] = v>>16;
  p[2] = v>>8;
  p[3] = v;
}

static void binarylog_flush(InstVfsBinaryLog *pLog){
  sqlite3_file *pFile = pLog->pOut;

#ifdef SQLITE_TEST
  extern int sqlite3_io_error_pending;
  extern int sqlite3_io_error_persist;
  extern int sqlite3_diskfull_pending;

  int pending = sqlite3_io_error_pending;
  int persist = sqlite3_io_error_persist;
  int diskfull = sqlite3_diskfull_pending;

  sqlite3_io_error_pending = 0;
  sqlite3_io_error_persist = 0;
  sqlite3_diskfull_pending = 0;
#endif

  pFile->pMethods->xWrite(pFile, pLog->zBuf, pLog->nBuf, pLog->iOffset);
  pLog->iOffset += pLog->nBuf;
  pLog->nBuf = 0;

#ifdef SQLITE_TEST
  sqlite3_io_error_pending = pending;
  sqlite3_io_error_persist = persist;
  sqlite3_diskfull_pending = diskfull;
#endif
}

static void binarylog_xcall(
  void *p,
  int eEvent,
  int iFileId,
  sqlite3_int64 nClick,
  int return_code,
  const char *zName,
  int flags,
  int nByte,
  sqlite3_int64 iOffset
){
  InstVfsBinaryLog *pLog = (InstVfsBinaryLog *)p;
  unsigned char *zRec;
  if( (28+pLog->nBuf)>BINARYLOG_BUFFERSIZE ){
    binarylog_flush(pLog);
  }
  zRec = (unsigned char *)&pLog->zBuf[pLog->nBuf];
  put32bits(&zRec[0], eEvent);
  put32bits(&zRec[4], (int)iFileId);
  put32bits(&zRec[8], (int)nClick);
  put32bits(&zRec[12], return_code);
  put32bits(&zRec[16], flags);
  put32bits(&zRec[20], nByte);
  put32bits(&zRec[24], (int)iOffset);
  pLog->nBuf += 28;
}

static void binarylog_xdel(void *p){
  /* Close the log file and free the memory allocated for the 
  ** InstVfsBinaryLog structure.
  */
  InstVfsBinaryLog *pLog = (InstVfsBinaryLog *)p;
  sqlite3_file *pFile = pLog->pOut;
  if( pLog->nBuf ){
    binarylog_flush(pLog);
  }
  pFile->pMethods->xClose(pFile);
  sqlite3_free(pLog->pOut);
  sqlite3_free(pLog->zBuf);
  sqlite3_free(pLog);
}

static void binarylog_blob(
  sqlite3_vfs *pVfs,
  const char *zBlob,
  int nBlob,
  int isBinary
){
  InstVfsBinaryLog *pLog;
  InstVfs *pInstVfs = (InstVfs *)pVfs;

  if( pVfs->xOpen!=instOpen || pInstVfs->xCall!=binarylog_xcall ){
    return;
  }
  pLog = (InstVfsBinaryLog *)pInstVfs->pClient;
  if( zBlob && (!isBinary || pLog->log_data) ){
    unsigned char *zRec;
    int nWrite;

    if( nBlob<0 ){
      nBlob = strlen(zBlob);
    }
    nWrite = nBlob + 28;
  
    if( (nWrite+pLog->nBuf)>BINARYLOG_BUFFERSIZE ){
      binarylog_flush(pLog);
    }
  
    zRec = (unsigned char *)&pLog->zBuf[pLog->nBuf];
    memset(zRec, 0, nWrite);
    put32bits(&zRec[0], BINARYLOG_STRING);
    put32bits(&zRec[4], (int)nBlob);
    put32bits(&zRec[8], (int)isBinary);
    memcpy(&zRec[28], zBlob, nBlob);
    pLog->nBuf += nWrite;
  }
}

void sqlite3_instvfs_binarylog_call(
  sqlite3_vfs *pVfs,
  int eEvent,
  sqlite3_int64 nClick,
  int return_code,
  const char *zString
){
  InstVfs *pInstVfs = (InstVfs *)pVfs;
  InstVfsBinaryLog *pLog = (InstVfsBinaryLog *)pInstVfs->pClient;

  if( zString ){
    binarylog_blob(pVfs, zString, -1, 0);
  }
  binarylog_xcall(pLog, eEvent, 0, nClick, return_code, 0, 0, 0, 0);
}

void sqlite3_instvfs_binarylog_marker(
  sqlite3_vfs *pVfs,
  const char *zMarker
){
  InstVfs *pInstVfs = (InstVfs *)pVfs;
  InstVfsBinaryLog *pLog = (InstVfsBinaryLog *)pInstVfs->pClient;
  binarylog_blob(pVfs, zMarker, -1, 0);
  binarylog_xcall(pLog, BINARYLOG_MARKER, 0, 0, 0, 0, 0, 0, 0);
}

sqlite3_vfs *sqlite3_instvfs_binarylog(
  const char *zVfs,
  const char *zParentVfs, 
  const char *zLog,
  int log_data
){
  InstVfsBinaryLog *p;
  sqlite3_vfs *pVfs;
  sqlite3_vfs *pParent;
  int nByte;
  int flags;
  int rc;

  pParent = sqlite3_vfs_find(zParentVfs);
  if( !pParent ){
    return 0;
  }

  nByte = sizeof(InstVfsBinaryLog) + pParent->mxPathname+1;
  p = (InstVfsBinaryLog *)sqlite3_malloc(nByte);
  memset(p, 0, nByte);
  p->zBuf = sqlite3_malloc(BINARYLOG_BUFFERSIZE);
  p->zOut = (char *)&p[1];
  p->pOut = (sqlite3_file *)sqlite3_malloc(pParent->szOsFile);
  p->log_data = log_data;
  pParent->xFullPathname(pParent, zLog, pParent->mxPathname, p->zOut);
  flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MASTER_JOURNAL;
  pParent->xDelete(pParent, p->zOut, 0);
  rc = pParent->xOpen(pParent, p->zOut, p->pOut, flags, &flags);
  if( rc==SQLITE_OK ){
    memcpy(p->zBuf, "sqlite_ostrace1.....", 20);
    p->iOffset = 0;
    p->nBuf = 20;
  }
  if( rc ){
    binarylog_xdel(p);
    return 0;
  }

  pVfs = sqlite3_instvfs_create(zVfs, zParentVfs);
  if( pVfs ){
    sqlite3_instvfs_configure(pVfs, binarylog_xcall, p, binarylog_xdel);
  }

  return pVfs;
}
#endif /* SQLITE_ENABLE_INSTVFS */

/**************************************************************************
***************************************************************************
** Tcl interface starts here.
*/
#if SQLITE_TEST

#include <tcl.h>

#ifdef SQLITE_ENABLE_INSTVFS
struct InstVfsCall {
  Tcl_Interp *interp;
  Tcl_Obj *pScript;
};
typedef struct InstVfsCall InstVfsCall;

static void test_instvfs_xcall(
  void *p,
  int eEvent,
  int iFileId,
  sqlite3_int64 nClick,
  int return_code,
  const char *zName,
  int flags,
  int nByte,
  sqlite3_int64 iOffset
){
  int rc;
  InstVfsCall *pCall = (InstVfsCall *)p;
  Tcl_Obj *pObj = Tcl_DuplicateObj( pCall->pScript);
  const char *zEvent = sqlite3_instvfs_name(eEvent);

  Tcl_IncrRefCount(pObj);
  Tcl_ListObjAppendElement(0, pObj, Tcl_NewStringObj(zEvent, -1));
  Tcl_ListObjAppendElement(0, pObj, Tcl_NewWideIntObj(nClick));
  Tcl_ListObjAppendElement(0, pObj, Tcl_NewStringObj(zName, -1));
  Tcl_ListObjAppendElement(0, pObj, Tcl_NewIntObj(nByte));
  Tcl_ListObjAppendElement(0, pObj, Tcl_NewWideIntObj(iOffset));

  rc = Tcl_EvalObjEx(pCall->interp, pObj, TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
  if( rc ){
    Tcl_BackgroundError(pCall->interp);
  }
  Tcl_DecrRefCount(pObj);
}

static void test_instvfs_xdel(void *p){
  InstVfsCall *pCall = (InstVfsCall *)p;
  Tcl_DecrRefCount(pCall->pScript);
  sqlite3_free(pCall);
}

static int test_sqlite3_instvfs(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  static const char *IV_strs[] = 
               { "create",  "destroy",  "reset",  "report", "configure", "binarylog", "marker", 0 };
  enum IV_enum { IV_CREATE, IV_DESTROY, IV_RESET, IV_REPORT, IV_CONFIGURE, IV_BINARYLOG, IV_MARKER };
  int iSub;

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ...");
  }
  if( Tcl_GetIndexFromObj(interp, objv[1], IV_strs, "sub-command", 0, &iSub) ){
    return TCL_ERROR;
  }

  switch( (enum IV_enum)iSub ){
    case IV_CREATE: {
      char *zParent = 0;
      sqlite3_vfs *p;
      int isDefault = 0;
      if( objc>2 && 0==strcmp("-default", Tcl_GetString(objv[2])) ){
        isDefault = 1;
      }
      if( (objc-isDefault)!=4 && (objc-isDefault)!=3 ){
        Tcl_WrongNumArgs(interp, 2, objv, "?-default? NAME ?PARENT-VFS?");
        return TCL_ERROR;
      }
      if( objc==(4+isDefault) ){
        zParent = Tcl_GetString(objv[3+isDefault]);
      }
      p = sqlite3_instvfs_create(Tcl_GetString(objv[2+isDefault]), zParent);
      if( !p ){
        Tcl_AppendResult(interp, "error creating vfs ", 0);
        return TCL_ERROR;
      }
      if( isDefault ){
        sqlite3_vfs_register(p, 1);
      }
      Tcl_SetObjResult(interp, objv[2]);
      break;
    }
    case IV_BINARYLOG: {
      char *zName = 0;
      char *zLog = 0;
      char *zParent = 0;
      sqlite3_vfs *p;
      int isDefault = 0;
      int isLogdata = 0;
      int argbase = 2;

      for(argbase=2; argbase<(objc-2); argbase++){
        if( 0==strcmp("-default", Tcl_GetString(objv[argbase])) ){
          isDefault = 1;
        }
        else if( 0==strcmp("-parent", Tcl_GetString(objv[argbase])) ){
          argbase++;
          zParent = Tcl_GetString(objv[argbase]);
        }
        else if( 0==strcmp("-logdata", Tcl_GetString(objv[argbase])) ){
          isLogdata = 1;
        }else{
          break;
        }
      }

      if( (objc-argbase)!=2 ){
        Tcl_WrongNumArgs(
            interp, 2, objv, "?-default? ?-parent VFS? ?-logdata? NAME LOGFILE"
        );
        return TCL_ERROR;
      }
      zName = Tcl_GetString(objv[argbase]);
      zLog = Tcl_GetString(objv[argbase+1]);
      p = sqlite3_instvfs_binarylog(zName, zParent, zLog, isLogdata);
      if( !p ){
        Tcl_AppendResult(interp, "error creating vfs ", 0);
        return TCL_ERROR;
      }
      if( isDefault ){
        sqlite3_vfs_register(p, 1);
      }
      Tcl_SetObjResult(interp, objv[2]);
      break;
    }

    case IV_MARKER: {
      sqlite3_vfs *p;
      if( objc!=4 ){
        Tcl_WrongNumArgs(interp, 2, objv, "VFS MARKER");
        return TCL_ERROR;
      }
      p = sqlite3_vfs_find(Tcl_GetString(objv[2]));
      if( !p || p->xOpen!=instOpen ){
        Tcl_AppendResult(interp, "no such vfs: ", Tcl_GetString(objv[2]), 0);
        return TCL_ERROR;
      }
      sqlite3_instvfs_binarylog_marker(p, Tcl_GetString(objv[3]));
      Tcl_ResetResult(interp);
      break;
    }

    case IV_CONFIGURE: {
      InstVfsCall *pCall;

      sqlite3_vfs *p;
      if( objc!=4 ){
        Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
        return TCL_ERROR;
      }
      p = sqlite3_vfs_find(Tcl_GetString(objv[2]));
      if( !p || p->xOpen!=instOpen ){
        Tcl_AppendResult(interp, "no such vfs: ", Tcl_GetString(objv[2]), 0);
        return TCL_ERROR;
      }

      if( strlen(Tcl_GetString(objv[3])) ){
        pCall = (InstVfsCall *)sqlite3_malloc(sizeof(InstVfsCall));
        pCall->interp = interp;
        pCall->pScript = Tcl_DuplicateObj(objv[3]);
        Tcl_IncrRefCount(pCall->pScript);
        sqlite3_instvfs_configure(p, 
            test_instvfs_xcall, (void *)pCall, test_instvfs_xdel
        );
      }else{
        sqlite3_instvfs_configure(p, 0, 0, 0);
      }
      break;
    }

    case IV_REPORT:
    case IV_DESTROY:
    case IV_RESET: {
      sqlite3_vfs *p;
      if( objc!=3 ){
        Tcl_WrongNumArgs(interp, 2, objv, "NAME");
        return TCL_ERROR;
      }
      p = sqlite3_vfs_find(Tcl_GetString(objv[2]));
      if( !p || p->xOpen!=instOpen ){
        Tcl_AppendResult(interp, "no such vfs: ", Tcl_GetString(objv[2]), 0);
        return TCL_ERROR;
      }

      if( ((enum IV_enum)iSub)==IV_DESTROY ){
        sqlite3_instvfs_destroy(p);
      }
      if( ((enum IV_enum)iSub)==IV_RESET ){
        sqlite3_instvfs_reset(p);
      }
      if( ((enum IV_enum)iSub)==IV_REPORT ){
        int ii;
        Tcl_Obj *pRet = Tcl_NewObj();

        const char *zName = (char *)1;
        sqlite3_int64 nClick;
        int nCall;
        for(ii=1; zName; ii++){
          sqlite3_instvfs_get(p, ii, &zName, &nClick, &nCall);
          if( zName ){
            Tcl_Obj *pElem = Tcl_NewObj();
            Tcl_ListObjAppendElement(0, pElem, Tcl_NewStringObj(zName, -1));
            Tcl_ListObjAppendElement(0, pElem, Tcl_NewIntObj(nCall));
            Tcl_ListObjAppendElement(0, pElem, Tcl_NewWideIntObj(nClick));
            Tcl_ListObjAppendElement(0, pRet, pElem);
          }
        }

        Tcl_SetObjResult(interp, pRet);
      }

      break;
    }
  }

  return TCL_OK;
}
#endif /* SQLITE_ENABLE_INSTVFS */

/* Alternative implementation of sqlite3_instvfs when the real
** implementation is unavailable. 
*/
#ifndef SQLITE_ENABLE_INSTVFS
static int test_sqlite3_instvfs(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_AppendResult(interp, 
     "not compiled with -DSQLITE_ENABLE_INSTVFS; sqlite3_instvfs is "
     "unavailable", (char*)0);
  return TCL_ERROR;
}
#endif /* !defined(SQLITE_ENABLE_INSTVFS) */

int SqlitetestOsinst_Init(Tcl_Interp *interp){
  Tcl_CreateObjCommand(interp, "sqlite3_instvfs", test_sqlite3_instvfs, 0, 0);
  return TCL_OK;
}

#endif /* SQLITE_TEST */

Added src/test_pcache.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
** 2008 November 18
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** 
** This file contains code used for testing the SQLite system.
** None of the code in this file goes into a deliverable build.
** 
** This file contains an application-defined pager cache
** implementation that can be plugged in in place of the
** default pcache.  This alternative pager cache will throw
** some errors that the default cache does not.
**
** This pagecache implementation is designed for simplicity
** not speed.  
**
** $Id: test_pcache.c,v 1.3 2009/04/11 11:38:54 drh Exp $
*/
#include "sqlite3.h"
#include <string.h>
#include <assert.h>

/*
** Global data used by this test implementation.  There is no
** mutexing, which means this page cache will not work in a
** multi-threaded test.
*/
typedef struct testpcacheGlobalType testpcacheGlobalType;
struct testpcacheGlobalType {
  void *pDummy;             /* Dummy allocation to simulate failures */
  int nInstance;            /* Number of current instances */
  unsigned discardChance;   /* Chance of discarding on an unpin (0-100) */
  unsigned prngSeed;        /* Seed for the PRNG */
  unsigned highStress;      /* Call xStress agressively */
};
static testpcacheGlobalType testpcacheGlobal;

/*
** Initializer.
**
** Verify that the initializer is only called when the system is
** uninitialized.  Allocate some memory and report SQLITE_NOMEM if
** the allocation fails.  This provides a means to test the recovery
** from a failed initialization attempt.  It also verifies that the
** the destructor always gets call - otherwise there would be a
** memory leak.
*/
static int testpcacheInit(void *pArg){
  assert( pArg==(void*)&testpcacheGlobal );
  assert( testpcacheGlobal.pDummy==0 );
  assert( testpcacheGlobal.nInstance==0 );
  testpcacheGlobal.pDummy = sqlite3_malloc(10);
  return testpcacheGlobal.pDummy==0 ? SQLITE_NOMEM : SQLITE_OK;
}

/*
** Destructor
**
** Verify that this is only called after initialization.
** Free the memory allocated by the initializer.
*/
static void testpcacheShutdown(void *pArg){
  assert( pArg==(void*)&testpcacheGlobal );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance==0 );
  sqlite3_free( testpcacheGlobal.pDummy );
  testpcacheGlobal.pDummy = 0;
}

/*
** Number of pages in a cache.
**
** The number of pages is a hard upper bound in this test module.
** If more pages are requested, sqlite3PcacheFetch() returns NULL.
**
** If testing with in-memory temp tables, provide a larger pcache.
** Some of the test cases need this.
*/
#if defined(SQLITE_TEMP_STORE) && SQLITE_TEMP_STORE>=2
# define TESTPCACHE_NPAGE    499
#else
# define TESTPCACHE_NPAGE    217
#endif
#define TESTPCACHE_RESERVE   17

/*
** Magic numbers used to determine validity of the page cache.
*/
#define TESTPCACHE_VALID  0x364585fd
#define TESTPCACHE_CLEAR  0xd42670d4

/*
** Private implementation of a page cache.
*/
typedef struct testpcache testpcache;
struct testpcache {
  int szPage;               /* Size of each page.  Multiple of 8. */
  int bPurgeable;           /* True if the page cache is purgeable */
  int nFree;                /* Number of unused slots in a[] */
  int nPinned;              /* Number of pinned slots in a[] */
  unsigned iRand;           /* State of the PRNG */
  unsigned iMagic;          /* Magic number for sanity checking */
  struct testpcachePage {
    unsigned key;              /* The key for this page. 0 means unallocated */
    int isPinned;              /* True if the page is pinned */
    void *pData;               /* Data for this page */
  } a[TESTPCACHE_NPAGE];    /* All pages in the cache */
};

/*
** Get a random number using the PRNG in the given page cache.
*/
static unsigned testpcacheRandom(testpcache *p){
  unsigned x = 0;
  int i;
  for(i=0; i<4; i++){
    p->iRand = (p->iRand*69069 + 5);
    x = (x<<8) | ((p->iRand>>16)&0xff);
  }
  return x;
}


/*
** Allocate a new page cache instance.
*/
static sqlite3_pcache *testpcacheCreate(int szPage, int bPurgeable){
  int nMem;
  char *x;
  testpcache *p;
  int i;
  assert( testpcacheGlobal.pDummy!=0 );
  szPage = (szPage+7)&~7;
  nMem = sizeof(testpcache) + TESTPCACHE_NPAGE*szPage;
  p = sqlite3_malloc( nMem );
  if( p==0 ) return 0;
  x = (char*)&p[1];
  p->szPage = szPage;
  p->nFree = TESTPCACHE_NPAGE;
  p->nPinned = 0;
  p->iRand = testpcacheGlobal.prngSeed;
  p->bPurgeable = bPurgeable;
  p->iMagic = TESTPCACHE_VALID;
  for(i=0; i<TESTPCACHE_NPAGE; i++, x += szPage){
    p->a[i].key = 0;
    p->a[i].isPinned = 0;
    p->a[i].pData = (void*)x;
  }
  testpcacheGlobal.nInstance++;
  return (sqlite3_pcache*)p;
}

/*
** Set the cache size
*/
static void testpcacheCachesize(sqlite3_pcache *pCache, int newSize){
  testpcache *p = (testpcache*)pCache;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( newSize>=1 );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );
}

/*
** Return the number of pages in the cache that are being used.
** This includes both pinned and unpinned pages.
*/
static int testpcachePagecount(sqlite3_pcache *pCache){
  testpcache *p = (testpcache*)pCache;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );
  return TESTPCACHE_NPAGE - p->nFree;
}

/*
** Fetch a page.
*/
static void *testpcacheFetch(
  sqlite3_pcache *pCache,
  unsigned key,
  int createFlag
){
  testpcache *p = (testpcache*)pCache;
  int i, j;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );

  /* See if the page is already in cache.  Return immediately if it is */
  for(i=0; i<TESTPCACHE_NPAGE; i++){
    if( p->a[i].key==key ){
      if( !p->a[i].isPinned ){
        p->nPinned++;
        assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree );
        p->a[i].isPinned = 1;
      }
      return p->a[i].pData;
    }
  }

  /* If createFlag is 0, never allocate a new page */
  if( createFlag==0 ){
    return 0;
  }

  /* If no pages are available, always fail */
  if( p->nPinned==TESTPCACHE_NPAGE ){
    return 0;
  }

  /* Do not allocate the last TESTPCACHE_RESERVE pages unless createFlag is 2 */
  if( p->nPinned>=TESTPCACHE_NPAGE-TESTPCACHE_RESERVE && createFlag<2 ){
    return 0;
  }

  /* Do not allocate if highStress is enabled and createFlag is not 2.  
  **
  ** The highStress setting causes pagerStress() to be called much more
  ** often, which exercises the pager logic more intensely.
  */
  if( testpcacheGlobal.highStress && createFlag<2 ){
    return 0;
  }

  /* Find a free page to allocate if there are any free pages.
  ** Withhold TESTPCACHE_RESERVE free pages until createFlag is 2.
  */
  if( p->nFree>TESTPCACHE_RESERVE || (createFlag==2 && p->nFree>0) ){
    j = testpcacheRandom(p) % TESTPCACHE_NPAGE;
    for(i=0; i<TESTPCACHE_NPAGE; i++, j = (j+1)%TESTPCACHE_NPAGE){
      if( p->a[j].key==0 ){
        p->a[j].key = key;
        p->a[j].isPinned = 1;
        memset(p->a[j].pData, 0, p->szPage);
        p->nPinned++;
        p->nFree--;
        assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree );
        return p->a[j].pData;
      }
    }

    /* The prior loop always finds a freepage to allocate */
    assert( 0 );
  }

  /* If this cache is not purgeable then we have to fail.
  */
  if( p->bPurgeable==0 ){
    return 0;
  }

  /* If there are no free pages, recycle a page.  The page to
  ** recycle is selected at random from all unpinned pages.
  */
  j = testpcacheRandom(p) % TESTPCACHE_NPAGE;
  for(i=0; i<TESTPCACHE_NPAGE; i++, j = (j+1)%TESTPCACHE_NPAGE){
    if( p->a[j].key>0 && p->a[j].isPinned==0 ){
      p->a[j].key = key;
      p->a[j].isPinned = 1;
      memset(p->a[j].pData, 0, p->szPage);
      p->nPinned++;
      assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree );
      return p->a[j].pData;
    }
  }

  /* The previous loop always finds a page to recycle. */
  assert(0);
  return 0;
}

/*
** Unpin a page.
*/
static void testpcacheUnpin(
  sqlite3_pcache *pCache,
  void *pOldPage,
  int discard
){
  testpcache *p = (testpcache*)pCache;
  int i;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );

  /* Randomly discard pages as they are unpinned according to the
  ** discardChance setting.  If discardChance is 0, the random discard
  ** never happens.  If discardChance is 100, it always happens.
  */
  if( p->bPurgeable
  && (100-testpcacheGlobal.discardChance) <= (testpcacheRandom(p)%100)
  ){
    discard = 1;
  }

  for(i=0; i<TESTPCACHE_NPAGE; i++){
    if( p->a[i].pData==pOldPage ){
      /* The pOldPage pointer always points to a pinned page */
      assert( p->a[i].isPinned );
      p->a[i].isPinned = 0;
      p->nPinned--;
      assert( p->nPinned>=0 );
      if( discard ){
        p->a[i].key = 0;
        p->nFree++;
        assert( p->nFree<=TESTPCACHE_NPAGE );
      }
      return;
    }
  }

  /* The pOldPage pointer always points to a valid page */
  assert( 0 );
}


/*
** Rekey a single page.
*/
static void testpcacheRekey(
  sqlite3_pcache *pCache,
  void *pOldPage,
  unsigned oldKey,
  unsigned newKey
){
  testpcache *p = (testpcache*)pCache;
  int i;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );

  /* If there already exists another page at newKey, verify that
  ** the other page is unpinned and discard it.
  */
  for(i=0; i<TESTPCACHE_NPAGE; i++){
    if( p->a[i].key==newKey ){
      /* The new key is never a page that is already pinned */
      assert( p->a[i].isPinned==0 );
      p->a[i].key = 0;
      p->nFree++;
      assert( p->nFree<=TESTPCACHE_NPAGE );
      break;
    }
  }

  /* Find the page to be rekeyed and rekey it.
  */
  for(i=0; i<TESTPCACHE_NPAGE; i++){
    if( p->a[i].key==oldKey ){
      /* The oldKey and pOldPage parameters match */
      assert( p->a[i].pData==pOldPage );
      /* Page to be rekeyed must be pinned */
      assert( p->a[i].isPinned );
      p->a[i].key = newKey;
      return;
    }
  }

  /* Rekey is always given a valid page to work with */
  assert( 0 );
}


/*
** Truncate the page cache.  Every page with a key of iLimit or larger
** is discarded.
*/
static void testpcacheTruncate(sqlite3_pcache *pCache, unsigned iLimit){
  testpcache *p = (testpcache*)pCache;
  unsigned int i;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );
  for(i=0; i<TESTPCACHE_NPAGE; i++){
    if( p->a[i].key>=iLimit ){
      p->a[i].key = 0;
      if( p->a[i].isPinned ){
        p->nPinned--;
        assert( p->nPinned>=0 );
      }
      p->nFree++;
      assert( p->nFree<=TESTPCACHE_NPAGE );
    }
  }
}

/*
** Destroy a page cache.
*/
static void testpcacheDestroy(sqlite3_pcache *pCache){
  testpcache *p = (testpcache*)pCache;
  assert( p->iMagic==TESTPCACHE_VALID );
  assert( testpcacheGlobal.pDummy!=0 );
  assert( testpcacheGlobal.nInstance>0 );
  p->iMagic = TESTPCACHE_CLEAR;
  sqlite3_free(p);
  testpcacheGlobal.nInstance--;
}


/*
** Invoke this routine to register or unregister the testing pager cache
** implemented by this file.
**
** Install the test pager cache if installFlag is 1 and uninstall it if
** installFlag is 0.
**
** When installing, discardChance is a number between 0 and 100 that
** indicates the probability of discarding a page when unpinning the
** page.  0 means never discard (unless the discard flag is set).
** 100 means always discard.
*/
void installTestPCache(
  int installFlag,            /* True to install.  False to uninstall. */
  unsigned discardChance,     /* 0-100.  Chance to discard on unpin */
  unsigned prngSeed,          /* Seed for the PRNG */
  unsigned highStress         /* Call xStress agressively */
){
  static const sqlite3_pcache_methods testPcache = {
    (void*)&testpcacheGlobal,
    testpcacheInit,
    testpcacheShutdown,
    testpcacheCreate,
    testpcacheCachesize,
    testpcachePagecount,
    testpcacheFetch,
    testpcacheUnpin,
    testpcacheRekey,
    testpcacheTruncate,
    testpcacheDestroy,
  };
  static sqlite3_pcache_methods defaultPcache;
  static int isInstalled = 0;

  assert( testpcacheGlobal.nInstance==0 );
  assert( testpcacheGlobal.pDummy==0 );
  assert( discardChance<=100 );
  testpcacheGlobal.discardChance = discardChance;
  testpcacheGlobal.prngSeed = prngSeed ^ (prngSeed<<16);
  testpcacheGlobal.highStress = highStress;
  if( installFlag!=isInstalled ){
    if( installFlag ){
      sqlite3_config(SQLITE_CONFIG_GETPCACHE, &defaultPcache);
      assert( defaultPcache.xCreate!=testpcacheCreate );
      sqlite3_config(SQLITE_CONFIG_PCACHE, &testPcache);
    }else{
      assert( defaultPcache.xCreate!=0 );
      sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultPcache);
    }
    isInstalled = installFlag;
  }
}

Added src/test_schema.c.



















































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
** 2006 June 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the virtual table interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test_schema.c,v 1.15 2008/07/07 14:50:14 drh Exp $
*/

/* The code in this file defines a sqlite3 virtual-table module that
** provides a read-only view of the current database schema. There is one
** row in the schema table for each column in the database schema.
*/
#define SCHEMA \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "tablename,"         /* Name of table */                                   \
  "cid,"               /* Column number (from left-to-right, 0 upward) */    \
  "name,"              /* Column name */                                     \
  "type,"              /* Specified type (i.e. VARCHAR(32)) */               \
  "not_null,"          /* Boolean. True if NOT NULL was specified */         \
  "dflt_value,"        /* Default value for this column */                   \
  "pk"                 /* True if this column is part of the primary key */  \
")"

/* If SQLITE_TEST is defined this code is preprocessed for use as part
** of the sqlite test binary "testfixture". Otherwise it is preprocessed
** to be compiled into an sqlite dynamic extension.
*/
#ifdef SQLITE_TEST
  #include "sqliteInt.h"
  #include "tcl.h"
#else
  #include "sqlite3ext.h"
  SQLITE_EXTENSION_INIT1
#endif

#include <stdlib.h>
#include <string.h>
#include <assert.h>

typedef struct schema_vtab schema_vtab;
typedef struct schema_cursor schema_cursor;

/* A schema table object */
struct schema_vtab {
  sqlite3_vtab base;
  sqlite3 *db;
};

/* A schema table cursor object */
struct schema_cursor {
  sqlite3_vtab_cursor base;
  sqlite3_stmt *pDbList;
  sqlite3_stmt *pTableList;
  sqlite3_stmt *pColumnList;
  int rowid;
};

/*
** None of this works unless we have virtual tables.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE

/*
** Table destructor for the schema module.
*/
static int schemaDestroy(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return 0;
}

/*
** Table constructor for the schema module.
*/
static int schemaCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  int rc = SQLITE_NOMEM;
  schema_vtab *pVtab = sqlite3_malloc(sizeof(schema_vtab));
  if( pVtab ){
    memset(pVtab, 0, sizeof(schema_vtab));
    pVtab->db = db;
#ifndef SQLITE_OMIT_VIRTUALTABLE
    rc = sqlite3_declare_vtab(db, SCHEMA);
#endif
  }
  *ppVtab = (sqlite3_vtab *)pVtab;
  return rc;
}

/*
** Open a new cursor on the schema table.
*/
static int schemaOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  int rc = SQLITE_NOMEM;
  schema_cursor *pCur;
  pCur = sqlite3_malloc(sizeof(schema_cursor));
  if( pCur ){
    memset(pCur, 0, sizeof(schema_cursor));
    *ppCursor = (sqlite3_vtab_cursor *)pCur;
    rc = SQLITE_OK;
  }
  return rc;
}

/*
** Close a schema table cursor.
*/
static int schemaClose(sqlite3_vtab_cursor *cur){
  schema_cursor *pCur = (schema_cursor *)cur;
  sqlite3_finalize(pCur->pDbList);
  sqlite3_finalize(pCur->pTableList);
  sqlite3_finalize(pCur->pColumnList);
  sqlite3_free(pCur);
  return SQLITE_OK;
}

/*
** Retrieve a column of data.
*/
static int schemaColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  schema_cursor *pCur = (schema_cursor *)cur;
  switch( i ){
    case 0:
      sqlite3_result_value(ctx, sqlite3_column_value(pCur->pDbList, 1));
      break;
    case 1:
      sqlite3_result_value(ctx, sqlite3_column_value(pCur->pTableList, 0));
      break;
    default:
      sqlite3_result_value(ctx, sqlite3_column_value(pCur->pColumnList, i-2));
      break;
  }
  return SQLITE_OK;
}

/*
** Retrieve the current rowid.
*/
static int schemaRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  schema_cursor *pCur = (schema_cursor *)cur;
  *pRowid = pCur->rowid;
  return SQLITE_OK;
}

static int finalize(sqlite3_stmt **ppStmt){
  int rc = sqlite3_finalize(*ppStmt);
  *ppStmt = 0;
  return rc;
}

static int schemaEof(sqlite3_vtab_cursor *cur){
  schema_cursor *pCur = (schema_cursor *)cur;
  return (pCur->pDbList ? 0 : 1);
}

/*
** Advance the cursor to the next row.
*/
static int schemaNext(sqlite3_vtab_cursor *cur){
  int rc = SQLITE_OK;
  schema_cursor *pCur = (schema_cursor *)cur;
  schema_vtab *pVtab = (schema_vtab *)(cur->pVtab);
  char *zSql = 0;

  while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){
    if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit;

    while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){
      if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit;

      assert(pCur->pDbList);
      while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){
        rc = finalize(&pCur->pDbList);
        goto next_exit;
      }

      /* Set zSql to the SQL to pull the list of tables from the 
      ** sqlite_master (or sqlite_temp_master) table of the database
      ** identfied by the row pointed to by the SQL statement pCur->pDbList
      ** (iterating through a "PRAGMA database_list;" statement).
      */
      if( sqlite3_column_int(pCur->pDbList, 0)==1 ){
        zSql = sqlite3_mprintf(
            "SELECT name FROM sqlite_temp_master WHERE type='table'"
        );
      }else{
        sqlite3_stmt *pDbList = pCur->pDbList;
        zSql = sqlite3_mprintf(
            "SELECT name FROM %Q.sqlite_master WHERE type='table'",
             sqlite3_column_text(pDbList, 1)
        );
      }
      if( !zSql ){
        rc = SQLITE_NOMEM;
        goto next_exit;
      }

      rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0);
      sqlite3_free(zSql);
      if( rc!=SQLITE_OK ) goto next_exit;
    }

    /* Set zSql to the SQL to the table_info pragma for the table currently
    ** identified by the rows pointed to by statements pCur->pDbList and
    ** pCur->pTableList.
    */
    zSql = sqlite3_mprintf("PRAGMA %Q.table_info(%Q)", 
        sqlite3_column_text(pCur->pDbList, 1),
        sqlite3_column_text(pCur->pTableList, 0)
    );

    if( !zSql ){
      rc = SQLITE_NOMEM;
      goto next_exit;
    }
    rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0);
    sqlite3_free(zSql);
    if( rc!=SQLITE_OK ) goto next_exit;
  }
  pCur->rowid++;

next_exit:
  /* TODO: Handle rc */
  return rc;
}

/*
** Reset a schema table cursor.
*/
static int schemaFilter(
  sqlite3_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite3_value **argv
){
  int rc;
  schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab);
  schema_cursor *pCur = (schema_cursor *)pVtabCursor;
  pCur->rowid = 0;
  finalize(&pCur->pTableList);
  finalize(&pCur->pColumnList);
  finalize(&pCur->pDbList);
  rc = sqlite3_prepare(pVtab->db,"PRAGMA database_list", -1, &pCur->pDbList, 0);
  return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc);
}

/*
** Analyse the WHERE condition.
*/
static int schemaBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  return SQLITE_OK;
}

/*
** A virtual table module that merely echos method calls into TCL
** variables.
*/
static sqlite3_module schemaModule = {
  0,                           /* iVersion */
  schemaCreate,
  schemaCreate,
  schemaBestIndex,
  schemaDestroy,
  schemaDestroy,
  schemaOpen,                  /* xOpen - open a cursor */
  schemaClose,                 /* xClose - close a cursor */
  schemaFilter,                /* xFilter - configure scan constraints */
  schemaNext,                  /* xNext - advance a cursor */
  schemaEof,                   /* xEof */
  schemaColumn,                /* xColumn - read data */
  schemaRowid,                 /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */

#ifdef SQLITE_TEST

/*
** Decode a pointer to an sqlite3 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);

/*
** Register the schema virtual table module.
*/
static int register_schema_module(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3_create_module(db, "schema", &schemaModule, 0);
#endif
  return TCL_OK;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetestschema_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_schema_module", register_schema_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  return TCL_OK;
}

#else

/*
** Extension load function.
*/
int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3_create_module(db, "schema", &schemaModule, 0);
#endif
  return 0;
}

#endif

Added src/test_server.c.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/*
** 2006 January 07
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** $Id: test_server.c,v 1.8 2008/06/26 10:41:19 danielk1977 Exp $
**
** This file contains demonstration code.  Nothing in this file gets compiled
** or linked into the SQLite library unless you use a non-standard option:
**
**      -DSQLITE_SERVER=1
**
** The configure script will never generate a Makefile with the option
** above.  You will need to manually modify the Makefile if you want to
** include any of the code from this file in your project.  Or, at your
** option, you may copy and paste the code from this file and
** thereby avoiding a recompile of SQLite.
**
**
** This source file demonstrates how to use SQLite to create an SQL database 
** server thread in a multiple-threaded program.  One or more client threads
** send messages to the server thread and the server thread processes those
** messages in the order received and returns the results to the client.
**
** One might ask:  "Why bother?  Why not just let each thread connect
** to the database directly?"  There are a several of reasons to
** prefer the client/server approach.
**
**    (1)  Some systems (ex: Redhat9) have broken threading implementations
**         that prevent SQLite database connections from being used in
**         a thread different from the one where they were created.  With
**         the client/server approach, all database connections are created
**         and used within the server thread.  Client calls to the database
**         can be made from multiple threads (though not at the same time!)
**
**    (2)  Beginning with SQLite version 3.3.0, when two or more 
**         connections to the same database occur within the same thread,
**         they can optionally share their database cache.  This reduces
**         I/O and memory requirements.  Cache shared is controlled using
**         the sqlite3_enable_shared_cache() API.
**
**    (3)  Database connections on a shared cache use table-level locking
**         instead of file-level locking for improved concurrency.
**
**    (4)  Database connections on a shared cache can by optionally
**         set to READ UNCOMMITTED isolation.  (The default isolation for
**         SQLite is SERIALIZABLE.)  When this occurs, readers will
**         never be blocked by a writer and writers will not be
**         blocked by readers.  There can still only be a single writer
**         at a time, but multiple readers can simultaneously exist with
**         that writer.  This is a huge increase in concurrency.
**
** To summarize the rational for using a client/server approach: prior
** to SQLite version 3.3.0 it probably was not worth the trouble.  But
** with SQLite version 3.3.0 and beyond you can get significant performance
** and concurrency improvements and memory usage reductions by going
** client/server.
**
** Note:  The extra features of version 3.3.0 described by points (2)
** through (4) above are only available if you compile without the
** option -DSQLITE_OMIT_SHARED_CACHE. 
**
** Here is how the client/server approach works:  The database server
** thread is started on this procedure:
**
**       void *sqlite3_server(void *NotUsed);
**
** The sqlite_server procedure runs as long as the g.serverHalt variable
** is false.  A mutex is used to make sure no more than one server runs
** at a time.  The server waits for messages to arrive on a message
** queue and processes the messages in order.
**
** Two convenience routines are provided for starting and stopping the
** server thread:
**
**       void sqlite3_server_start(void);
**       void sqlite3_server_stop(void);
**
** Both of the convenience routines return immediately.  Neither will
** ever give an error.  If a server is already started or already halted,
** then the routines are effectively no-ops.
**
** Clients use the following interfaces:
**
**       sqlite3_client_open
**       sqlite3_client_prepare
**       sqlite3_client_step
**       sqlite3_client_reset
**       sqlite3_client_finalize
**       sqlite3_client_close
**
** These interfaces work exactly like the standard core SQLite interfaces
** having the same names without the "_client_" infix.  Many other SQLite
** interfaces can be used directly without having to send messages to the
** server as long as SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined.
** The following interfaces fall into this second category:
**
**       sqlite3_bind_*
**       sqlite3_changes
**       sqlite3_clear_bindings
**       sqlite3_column_*
**       sqlite3_complete
**       sqlite3_create_collation
**       sqlite3_create_function
**       sqlite3_data_count
**       sqlite3_db_handle
**       sqlite3_errcode
**       sqlite3_errmsg
**       sqlite3_last_insert_rowid
**       sqlite3_total_changes
**       sqlite3_transfer_bindings
**
** A single SQLite connection (an sqlite3* object) or an SQLite statement
** (an sqlite3_stmt* object) should only be passed to a single interface
** function at a time.  The connections and statements can be passed from
** any thread to any of the functions listed in the second group above as
** long as the same connection is not in use by two threads at once and
** as long as SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined.  Additional
** information about the SQLITE_ENABLE_MEMORY_MANAGEMENT constraint is
** below.
**
** The busy handler for all database connections should remain turned
** off.  That means that any lock contention will cause the associated
** sqlite3_client_step() call to return immediately with an SQLITE_BUSY
** error code.  If a busy handler is enabled and lock contention occurs,
** then the entire server thread will block.  This will cause not only
** the requesting client to block but every other database client as
** well.  It is possible to enhance the code below so that lock
** contention will cause the message to be placed back on the top of
** the queue to be tried again later.  But such enhanced processing is
** not included here, in order to keep the example simple.
**
** This example code assumes the use of pthreads.  Pthreads
** implementations are available for windows.  (See, for example
** http://sourceware.org/pthreads-win32/announcement.html.)  Or, you
** can translate the locking and thread synchronization code to use
** windows primitives easily enough.  The details are left as an
** exercise to the reader.
**
**** Restrictions Associated With SQLITE_ENABLE_MEMORY_MANAGEMENT ****
**
** If you compile with SQLITE_ENABLE_MEMORY_MANAGEMENT defined, then
** SQLite includes code that tracks how much memory is being used by
** each thread.  These memory counts can become confused if memory
** is allocated by one thread and then freed by another.  For that
** reason, when SQLITE_ENABLE_MEMORY_MANAGEMENT is used, all operations
** that might allocate or free memory should be performanced in the same
** thread that originally created the database connection.  In that case,
** many of the operations that are listed above as safe to be performed
** in separate threads would need to be sent over to the server to be
** done there.  If SQLITE_ENABLE_MEMORY_MANAGEMENT is defined, then
** the following functions can be used safely from different threads
** without messing up the allocation counts:
**
**       sqlite3_bind_parameter_name
**       sqlite3_bind_parameter_index
**       sqlite3_changes
**       sqlite3_column_blob
**       sqlite3_column_count
**       sqlite3_complete
**       sqlite3_data_count
**       sqlite3_db_handle
**       sqlite3_errcode
**       sqlite3_errmsg
**       sqlite3_last_insert_rowid
**       sqlite3_total_changes
**
** The remaining functions are not thread-safe when memory management
** is enabled.  So one would have to define some new interface routines
** along the following lines:
**
**       sqlite3_client_bind_*
**       sqlite3_client_clear_bindings
**       sqlite3_client_column_*
**       sqlite3_client_create_collation
**       sqlite3_client_create_function
**       sqlite3_client_transfer_bindings
**
** The example code in this file is intended for use with memory
** management turned off.  So the implementation of these additional
** client interfaces is left as an exercise to the reader.
**
** It may seem surprising to the reader that the list of safe functions
** above does not include things like sqlite3_bind_int() or
** sqlite3_column_int().  But those routines might, in fact, allocate
** or deallocate memory.  In the case of sqlite3_bind_int(), if the
** parameter was previously bound to a string that string might need
** to be deallocated before the new integer value is inserted.  In
** the case of sqlite3_column_int(), the value of the column might be
** a UTF-16 string which will need to be converted to UTF-8 then into
** an integer.
*/

/* Include this to get the definition of SQLITE_THREADSAFE, in the
** case that default values are used.
*/
#include "sqliteInt.h"

/*
** Only compile the code in this file on UNIX with a SQLITE_THREADSAFE build
** and only if the SQLITE_SERVER macro is defined.
*/
#if defined(SQLITE_SERVER) && !defined(SQLITE_OMIT_SHARED_CACHE)
#if defined(SQLITE_OS_UNIX) && OS_UNIX && SQLITE_THREADSAFE

/*
** We require only pthreads and the public interface of SQLite.
*/
#include <pthread.h>
#include "sqlite3.h"

/*
** Messages are passed from client to server and back again as 
** instances of the following structure.
*/
typedef struct SqlMessage SqlMessage;
struct SqlMessage {
  int op;                      /* Opcode for the message */
  sqlite3 *pDb;                /* The SQLite connection */
  sqlite3_stmt *pStmt;         /* A specific statement */
  int errCode;                 /* Error code returned */
  const char *zIn;             /* Input filename or SQL statement */
  int nByte;                   /* Size of the zIn parameter for prepare() */
  const char *zOut;            /* Tail of the SQL statement */
  SqlMessage *pNext;           /* Next message in the queue */
  SqlMessage *pPrev;           /* Previous message in the queue */
  pthread_mutex_t clientMutex; /* Hold this mutex to access the message */
  pthread_cond_t clientWakeup; /* Signal to wake up the client */
};

/*
** Legal values for SqlMessage.op
*/
#define MSG_Open       1  /* sqlite3_open(zIn, &pDb) */
#define MSG_Prepare    2  /* sqlite3_prepare(pDb, zIn, nByte, &pStmt, &zOut) */
#define MSG_Step       3  /* sqlite3_step(pStmt) */
#define MSG_Reset      4  /* sqlite3_reset(pStmt) */
#define MSG_Finalize   5  /* sqlite3_finalize(pStmt) */
#define MSG_Close      6  /* sqlite3_close(pDb) */
#define MSG_Done       7  /* Server has finished with this message */


/*
** State information about the server is stored in a static variable
** named "g" as follows:
*/
static struct ServerState {
  pthread_mutex_t queueMutex;   /* Hold this mutex to access the msg queue */
  pthread_mutex_t serverMutex;  /* Held by the server while it is running */
  pthread_cond_t serverWakeup;  /* Signal this condvar to wake up the server */
  volatile int serverHalt;      /* Server halts itself when true */
  SqlMessage *pQueueHead;       /* Head of the message queue */
  SqlMessage *pQueueTail;       /* Tail of the message queue */
} g = {
  PTHREAD_MUTEX_INITIALIZER,
  PTHREAD_MUTEX_INITIALIZER,
  PTHREAD_COND_INITIALIZER,
};

/*
** Send a message to the server.  Block until we get a reply.
**
** The mutex and condition variable in the message are uninitialized
** when this routine is called.  This routine takes care of 
** initializing them and destroying them when it has finished.
*/
static void sendToServer(SqlMessage *pMsg){
  /* Initialize the mutex and condition variable on the message
  */
  pthread_mutex_init(&pMsg->clientMutex, 0);
  pthread_cond_init(&pMsg->clientWakeup, 0);

  /* Add the message to the head of the server's message queue.
  */
  pthread_mutex_lock(&g.queueMutex);
  pMsg->pNext = g.pQueueHead;
  if( g.pQueueHead==0 ){
    g.pQueueTail = pMsg;
  }else{
    g.pQueueHead->pPrev = pMsg;
  }
  pMsg->pPrev = 0;
  g.pQueueHead = pMsg;
  pthread_mutex_unlock(&g.queueMutex);

  /* Signal the server that the new message has be queued, then
  ** block waiting for the server to process the message.
  */
  pthread_mutex_lock(&pMsg->clientMutex);
  pthread_cond_signal(&g.serverWakeup);
  while( pMsg->op!=MSG_Done ){
    pthread_cond_wait(&pMsg->clientWakeup, &pMsg->clientMutex);
  }
  pthread_mutex_unlock(&pMsg->clientMutex);

  /* Destroy the mutex and condition variable of the message.
  */
  pthread_mutex_destroy(&pMsg->clientMutex);
  pthread_cond_destroy(&pMsg->clientWakeup);
}

/*
** The following 6 routines are client-side implementations of the
** core SQLite interfaces:
**
**        sqlite3_open
**        sqlite3_prepare
**        sqlite3_step
**        sqlite3_reset
**        sqlite3_finalize
**        sqlite3_close
**
** Clients should use the following client-side routines instead of 
** the core routines above.
**
**        sqlite3_client_open
**        sqlite3_client_prepare
**        sqlite3_client_step
**        sqlite3_client_reset
**        sqlite3_client_finalize
**        sqlite3_client_close
**
** Each of these routines creates a message for the desired operation,
** sends that message to the server, waits for the server to process
** then message and return a response.
*/
int sqlite3_client_open(const char *zDatabaseName, sqlite3 **ppDb){
  SqlMessage msg;
  msg.op = MSG_Open;
  msg.zIn = zDatabaseName;
  sendToServer(&msg);
  *ppDb = msg.pDb;
  return msg.errCode;
}
int sqlite3_client_prepare(
  sqlite3 *pDb,
  const char *zSql,
  int nByte,
  sqlite3_stmt **ppStmt,
  const char **pzTail
){
  SqlMessage msg;
  msg.op = MSG_Prepare;
  msg.pDb = pDb;
  msg.zIn = zSql;
  msg.nByte = nByte;
  sendToServer(&msg);
  *ppStmt = msg.pStmt;
  if( pzTail ) *pzTail = msg.zOut;
  return msg.errCode;
}
int sqlite3_client_step(sqlite3_stmt *pStmt){
  SqlMessage msg;
  msg.op = MSG_Step;
  msg.pStmt = pStmt;
  sendToServer(&msg);
  return msg.errCode;
}
int sqlite3_client_reset(sqlite3_stmt *pStmt){
  SqlMessage msg;
  msg.op = MSG_Reset;
  msg.pStmt = pStmt;
  sendToServer(&msg);
  return msg.errCode;
}
int sqlite3_client_finalize(sqlite3_stmt *pStmt){
  SqlMessage msg;
  msg.op = MSG_Finalize;
  msg.pStmt = pStmt;
  sendToServer(&msg);
  return msg.errCode;
}
int sqlite3_client_close(sqlite3 *pDb){
  SqlMessage msg;
  msg.op = MSG_Close;
  msg.pDb = pDb;
  sendToServer(&msg);
  return msg.errCode;
}

/*
** This routine implements the server.  To start the server, first
** make sure g.serverHalt is false, then create a new detached thread
** on this procedure.  See the sqlite3_server_start() routine below
** for an example.  This procedure loops until g.serverHalt becomes
** true.
*/
void *sqlite3_server(void *NotUsed){
  if( pthread_mutex_trylock(&g.serverMutex) ){
    return 0;  /* Another server is already running */
  }
  sqlite3_enable_shared_cache(1);
  while( !g.serverHalt ){
    SqlMessage *pMsg;

    /* Remove the last message from the message queue.
    */
    pthread_mutex_lock(&g.queueMutex);
    while( g.pQueueTail==0 && g.serverHalt==0 ){
      pthread_cond_wait(&g.serverWakeup, &g.queueMutex);
    }
    pMsg = g.pQueueTail;
    if( pMsg ){
      if( pMsg->pPrev ){
        pMsg->pPrev->pNext = 0;
      }else{
        g.pQueueHead = 0;
      }
      g.pQueueTail = pMsg->pPrev;
    }
    pthread_mutex_unlock(&g.queueMutex);
    if( pMsg==0 ) break;

    /* Process the message just removed
    */
    pthread_mutex_lock(&pMsg->clientMutex);
    switch( pMsg->op ){
      case MSG_Open: {
        pMsg->errCode = sqlite3_open(pMsg->zIn, &pMsg->pDb);
        break;
      }
      case MSG_Prepare: {
        pMsg->errCode = sqlite3_prepare(pMsg->pDb, pMsg->zIn, pMsg->nByte,
                                        &pMsg->pStmt, &pMsg->zOut);
        break;
      }
      case MSG_Step: {
        pMsg->errCode = sqlite3_step(pMsg->pStmt);
        break;
      }
      case MSG_Reset: {
        pMsg->errCode = sqlite3_reset(pMsg->pStmt);
        break;
      }
      case MSG_Finalize: {
        pMsg->errCode = sqlite3_finalize(pMsg->pStmt);
        break;
      }
      case MSG_Close: {
        pMsg->errCode = sqlite3_close(pMsg->pDb);
        break;
      }
    }

    /* Signal the client that the message has been processed.
    */
    pMsg->op = MSG_Done;
    pthread_mutex_unlock(&pMsg->clientMutex);
    pthread_cond_signal(&pMsg->clientWakeup);
  }
  sqlite3_thread_cleanup();
  pthread_mutex_unlock(&g.serverMutex);
  return 0;
}

/*
** Start a server thread if one is not already running.  If there
** is aleady a server thread running, the new thread will quickly
** die and this routine is effectively a no-op.
*/
void sqlite3_server_start(void){
  pthread_t x;
  int rc;
  g.serverHalt = 0;
  rc = pthread_create(&x, 0, sqlite3_server, 0);
  if( rc==0 ){
    pthread_detach(x);
  }
}

/*
** If a server thread is running, then stop it.  If no server is
** running, this routine is effectively a no-op.
**
** This routine waits until the server has actually stopped before
** returning.
*/
void sqlite3_server_stop(void){
  g.serverHalt = 1;
  pthread_cond_broadcast(&g.serverWakeup);
  pthread_mutex_lock(&g.serverMutex);
  pthread_mutex_unlock(&g.serverMutex);
}

#endif /* defined(SQLITE_OS_UNIX) && OS_UNIX && SQLITE_THREADSAFE */
#endif /* defined(SQLITE_SERVER) */

Added src/test_tclvar.c.











































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
** 2006 June 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the virtual table interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** The emphasis of this file is a virtual table that provides
** access to TCL variables.
**
** $Id: test_tclvar.c,v 1.17 2008/08/12 14:48:41 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

typedef struct tclvar_vtab tclvar_vtab;
typedef struct tclvar_cursor tclvar_cursor;

/* 
** A tclvar virtual-table object 
*/
struct tclvar_vtab {
  sqlite3_vtab base;
  Tcl_Interp *interp;
};

/* A tclvar cursor object */
struct tclvar_cursor {
  sqlite3_vtab_cursor base;

  Tcl_Obj *pList1;     /* Result of [info vars ?pattern?] */
  Tcl_Obj *pList2;     /* Result of [array names [lindex $pList1 $i1]] */
  int i1;              /* Current item in pList1 */
  int i2;              /* Current item (if any) in pList2 */
};

/* Methods for the tclvar module */
static int tclvarConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  tclvar_vtab *pVtab;
  static const char zSchema[] = 
     "CREATE TABLE whatever(name TEXT, arrayname TEXT, value TEXT)";
  pVtab = sqlite3MallocZero( sizeof(*pVtab) );
  if( pVtab==0 ) return SQLITE_NOMEM;
  *ppVtab = &pVtab->base;
  pVtab->interp = (Tcl_Interp *)pAux;
  sqlite3_declare_vtab(db, zSchema);
  return SQLITE_OK;
}
/* Note that for this virtual table, the xCreate and xConnect
** methods are identical. */

static int tclvarDisconnect(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return SQLITE_OK;
}
/* The xDisconnect and xDestroy methods are also the same */

/*
** Open a new tclvar cursor.
*/
static int tclvarOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  tclvar_cursor *pCur;
  pCur = sqlite3MallocZero(sizeof(tclvar_cursor));
  *ppCursor = &pCur->base;
  return SQLITE_OK;
}

/*
** Close a tclvar cursor.
*/
static int tclvarClose(sqlite3_vtab_cursor *cur){
  tclvar_cursor *pCur = (tclvar_cursor *)cur;
  if( pCur->pList1 ){
    Tcl_DecrRefCount(pCur->pList1);
  }
  if( pCur->pList2 ){
    Tcl_DecrRefCount(pCur->pList2);
  }
  sqlite3_free(pCur);
  return SQLITE_OK;
}

/*
** Returns 1 if data is ready, or 0 if not.
*/
static int next2(Tcl_Interp *interp, tclvar_cursor *pCur, Tcl_Obj *pObj){
  Tcl_Obj *p;

  if( pObj ){
    if( !pCur->pList2 ){
      p = Tcl_NewStringObj("array names", -1);
      Tcl_IncrRefCount(p);
      Tcl_ListObjAppendElement(0, p, pObj);
      Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL);
      Tcl_DecrRefCount(p);
      pCur->pList2 = Tcl_GetObjResult(interp);
      Tcl_IncrRefCount(pCur->pList2);
      assert( pCur->i2==0 );
    }else{
      int n = 0;
      pCur->i2++;
      Tcl_ListObjLength(0, pCur->pList2, &n);
      if( pCur->i2>=n ){
        Tcl_DecrRefCount(pCur->pList2);
        pCur->pList2 = 0;
        pCur->i2 = 0;
        return 0;
      }
    }
  }

  return 1;
}

static int tclvarNext(sqlite3_vtab_cursor *cur){
  Tcl_Obj *pObj;
  int n = 0;
  int ok = 0;

  tclvar_cursor *pCur = (tclvar_cursor *)cur;
  Tcl_Interp *interp = ((tclvar_vtab *)(cur->pVtab))->interp;

  Tcl_ListObjLength(0, pCur->pList1, &n);
  while( !ok && pCur->i1<n ){
    Tcl_ListObjIndex(0, pCur->pList1, pCur->i1, &pObj);
    ok = next2(interp, pCur, pObj);
    if( !ok ){
      pCur->i1++;
    }
  }

  return 0;
}

static int tclvarFilter(
  sqlite3_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite3_value **argv
){
  tclvar_cursor *pCur = (tclvar_cursor *)pVtabCursor;
  Tcl_Interp *interp = ((tclvar_vtab *)(pVtabCursor->pVtab))->interp;

  Tcl_Obj *p = Tcl_NewStringObj("info vars", -1);
  Tcl_IncrRefCount(p);

  assert( argc==0 || argc==1 );
  if( argc==1 ){
    Tcl_Obj *pArg = Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1);
    Tcl_ListObjAppendElement(0, p, pArg);
  }
  Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL);
  pCur->pList1 = Tcl_GetObjResult(interp);
  Tcl_IncrRefCount(pCur->pList1);
  assert( pCur->i1==0 && pCur->i2==0 && pCur->pList2==0 );

  Tcl_DecrRefCount(p);
  return tclvarNext(pVtabCursor);
}

static int tclvarColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  Tcl_Obj *p1;
  Tcl_Obj *p2;
  const char *z1; 
  const char *z2 = "";
  tclvar_cursor *pCur = (tclvar_cursor*)cur;
  Tcl_Interp *interp = ((tclvar_vtab *)cur->pVtab)->interp;

  Tcl_ListObjIndex(interp, pCur->pList1, pCur->i1, &p1);
  Tcl_ListObjIndex(interp, pCur->pList2, pCur->i2, &p2);
  z1 = Tcl_GetString(p1);
  if( p2 ){
    z2 = Tcl_GetString(p2);
  }
  switch (i) {
    case 0: {
      sqlite3_result_text(ctx, z1, -1, SQLITE_TRANSIENT);
      break;
    }
    case 1: {
      sqlite3_result_text(ctx, z2, -1, SQLITE_TRANSIENT);
      break;
    }
    case 2: {
      Tcl_Obj *pVal = Tcl_GetVar2Ex(interp, z1, *z2?z2:0, TCL_GLOBAL_ONLY);
      sqlite3_result_text(ctx, Tcl_GetString(pVal), -1, SQLITE_TRANSIENT);
      break;
    }
  }
  return SQLITE_OK;
}

static int tclvarRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  *pRowid = 0;
  return SQLITE_OK;
}

static int tclvarEof(sqlite3_vtab_cursor *cur){
  tclvar_cursor *pCur = (tclvar_cursor*)cur;
  return (pCur->pList2?0:1);
}

static int tclvarBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  int ii;

  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
    if( pCons->iColumn==0 && pCons->usable
           && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
      struct sqlite3_index_constraint_usage *pUsage;
      pUsage = &pIdxInfo->aConstraintUsage[ii];
      pUsage->omit = 0;
      pUsage->argvIndex = 1;
      return SQLITE_OK;
    }
  }

  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
    if( pCons->iColumn==0 && pCons->usable
           && pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
      struct sqlite3_index_constraint_usage *pUsage;
      pUsage = &pIdxInfo->aConstraintUsage[ii];
      pUsage->omit = 1;
      pUsage->argvIndex = 1;
      return SQLITE_OK;
    }
  }

  return SQLITE_OK;
}

/*
** A virtual table module that provides read-only access to a
** Tcl global variable namespace.
*/
static sqlite3_module tclvarModule = {
  0,                         /* iVersion */
  tclvarConnect,
  tclvarConnect,
  tclvarBestIndex,
  tclvarDisconnect, 
  tclvarDisconnect,
  tclvarOpen,                  /* xOpen - open a cursor */
  tclvarClose,                 /* xClose - close a cursor */
  tclvarFilter,                /* xFilter - configure scan constraints */
  tclvarNext,                  /* xNext - advance a cursor */
  tclvarEof,                   /* xEof - check for end of scan */
  tclvarColumn,                /* xColumn - read data */
  tclvarRowid,                 /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

/*
** Decode a pointer to an sqlite3 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);

/*
** Register the echo virtual table module.
*/
static int register_tclvar_module(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3_create_module(db, "tclvar", &tclvarModule, (void *)interp);
#endif
  return TCL_OK;
}

#endif


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetesttclvar_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_tclvar_module",   register_tclvar_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
#endif
  return TCL_OK;
}

Added src/test_thread.c.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
** 2007 September 9
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains the implementation of some Tcl commands used to
** test that sqlite3 database handles may be concurrently accessed by 
** multiple threads. Right now this only works on unix.
**
** $Id: test_thread.c,v 1.15 2009/03/27 12:32:56 drh Exp $
*/

#include "sqliteInt.h"
#include <tcl.h>

#if SQLITE_THREADSAFE

#include <errno.h>

#if !defined(_MSC_VER)
#include <unistd.h>
#endif

/*
** One of these is allocated for each thread created by [sqlthread spawn].
*/
typedef struct SqlThread SqlThread;
struct SqlThread {
  Tcl_ThreadId parent;     /* Thread id of parent thread */
  Tcl_Interp *interp;      /* Parent interpreter */
  char *zScript;           /* The script to execute. */
  char *zVarname;          /* Varname in parent script */
};

/*
** A custom Tcl_Event type used by this module. When the event is
** handled, script zScript is evaluated in interpreter interp. If
** the evaluation throws an exception (returns TCL_ERROR), then the
** error is handled by Tcl_BackgroundError(). If no error occurs,
** the result is simply discarded.
*/
typedef struct EvalEvent EvalEvent;
struct EvalEvent {
  Tcl_Event base;          /* Base class of type Tcl_Event */
  char *zScript;           /* The script to execute. */
  Tcl_Interp *interp;      /* The interpreter to execute it in. */
};

static Tcl_ObjCmdProc sqlthread_proc;
static Tcl_ObjCmdProc clock_seconds_proc;
#if defined(SQLITE_OS_UNIX) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
static Tcl_ObjCmdProc blocking_step_proc;
static Tcl_ObjCmdProc blocking_prepare_v2_proc;
#endif
int Sqlitetest1_Init(Tcl_Interp *);

/* Functions from test1.c */
void *sqlite3TestTextToPtr(const char *);
const char *sqlite3TestErrorName(int);
int getDbPointer(Tcl_Interp *, const char *, sqlite3 **);
int sqlite3TestMakePointerStr(Tcl_Interp *, char *, void *);
int sqlite3TestErrCode(Tcl_Interp *, sqlite3 *, int);

/*
** Handler for events of type EvalEvent.
*/
static int tclScriptEvent(Tcl_Event *evPtr, int flags){
  int rc;
  EvalEvent *p = (EvalEvent *)evPtr;
  rc = Tcl_Eval(p->interp, p->zScript);
  if( rc!=TCL_OK ){
    Tcl_BackgroundError(p->interp);
  }
  UNUSED_PARAMETER(flags);
  return 1;
}

/*
** Register an EvalEvent to evaluate the script pScript in the
** parent interpreter/thread of SqlThread p.
*/
static void postToParent(SqlThread *p, Tcl_Obj *pScript){
  EvalEvent *pEvent;
  char *zMsg;
  int nMsg;

  zMsg = Tcl_GetStringFromObj(pScript, &nMsg); 
  pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1);
  pEvent->base.nextPtr = 0;
  pEvent->base.proc = tclScriptEvent;
  pEvent->zScript = (char *)&pEvent[1];
  memcpy(pEvent->zScript, zMsg, nMsg+1);
  pEvent->interp = p->interp;

  Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL);
  Tcl_ThreadAlert(p->parent);
}

/*
** The main function for threads created with [sqlthread spawn].
*/
static Tcl_ThreadCreateType tclScriptThread(ClientData pSqlThread){
  Tcl_Interp *interp;
  Tcl_Obj *pRes;
  Tcl_Obj *pList;
  int rc;
  SqlThread *p = (SqlThread *)pSqlThread;
  extern int Sqlitetest_mutex_Init(Tcl_Interp*);

  interp = Tcl_CreateInterp();
  Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, pSqlThread, 0);
#if defined(SQLITE_OS_UNIX) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
  Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0);
  Tcl_CreateObjCommand(interp, 
      "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0);
  Tcl_CreateObjCommand(interp, 
      "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0);
#endif
  Sqlitetest1_Init(interp);
  Sqlitetest_mutex_Init(interp);

  rc = Tcl_Eval(interp, p->zScript);
  pRes = Tcl_GetObjResult(interp);
  pList = Tcl_NewObj();
  Tcl_IncrRefCount(pList);
  Tcl_IncrRefCount(pRes);

  if( rc!=TCL_OK ){
    Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("error", -1));
    Tcl_ListObjAppendElement(interp, pList, pRes);
    postToParent(p, pList);
    Tcl_DecrRefCount(pList);
    pList = Tcl_NewObj();
  }

  Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("set", -1));
  Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj(p->zVarname, -1));
  Tcl_ListObjAppendElement(interp, pList, pRes);
  postToParent(p, pList);

  ckfree((void *)p);
  Tcl_DecrRefCount(pList);
  Tcl_DecrRefCount(pRes);
  Tcl_DeleteInterp(interp);
  TCL_THREAD_CREATE_RETURN;
}

/*
** sqlthread spawn VARNAME SCRIPT
**
**     Spawn a new thread with its own Tcl interpreter and run the
**     specified SCRIPT(s) in it. The thread terminates after running
**     the script. The result of the script is stored in the variable
**     VARNAME.
**
**     The caller can wait for the script to terminate using [vwait VARNAME].
*/
static int sqlthread_spawn(
  ClientData clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_ThreadId x;
  SqlThread *pNew;
  int rc;

  int nVarname; char *zVarname;
  int nScript; char *zScript;

  /* Parameters for thread creation */
  const int nStack = TCL_THREAD_STACK_DEFAULT;
  const int flags = TCL_THREAD_NOFLAGS;

  assert(objc==4);
  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(objc);

  zVarname = Tcl_GetStringFromObj(objv[2], &nVarname);
  zScript = Tcl_GetStringFromObj(objv[3], &nScript);

  pNew = (SqlThread *)ckalloc(sizeof(SqlThread)+nVarname+nScript+2);
  pNew->zVarname = (char *)&pNew[1];
  pNew->zScript = (char *)&pNew->zVarname[nVarname+1];
  memcpy(pNew->zVarname, zVarname, nVarname+1);
  memcpy(pNew->zScript, zScript, nScript+1);
  pNew->parent = Tcl_GetCurrentThread();
  pNew->interp = interp;

  rc = Tcl_CreateThread(&x, tclScriptThread, (void *)pNew, nStack, flags);
  if( rc!=TCL_OK ){
    Tcl_AppendResult(interp, "Error in Tcl_CreateThread()", 0);
    ckfree((char *)pNew);
    return TCL_ERROR;
  }

  return TCL_OK;
}

/*
** sqlthread parent SCRIPT
**
**     This can be called by spawned threads only. It sends the specified
**     script back to the parent thread for execution. The result of
**     evaluating the SCRIPT is returned. The parent thread must enter
**     the event loop for this to work - otherwise the caller will
**     block indefinitely.
**
**     NOTE: At the moment, this doesn't work. FIXME.
*/
static int sqlthread_parent(
  ClientData clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  EvalEvent *pEvent;
  char *zMsg;
  int nMsg;
  SqlThread *p = (SqlThread *)clientData;

  assert(objc==3);
  UNUSED_PARAMETER(objc);

  if( p==0 ){
    Tcl_AppendResult(interp, "no parent thread", 0);
    return TCL_ERROR;
  }

  zMsg = Tcl_GetStringFromObj(objv[2], &nMsg);
  pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1);
  pEvent->base.nextPtr = 0;
  pEvent->base.proc = tclScriptEvent;
  pEvent->zScript = (char *)&pEvent[1];
  memcpy(pEvent->zScript, zMsg, nMsg+1);
  pEvent->interp = p->interp;
  Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL);
  Tcl_ThreadAlert(p->parent);

  return TCL_OK;
}

static int xBusy(void *pArg, int nBusy){
  UNUSED_PARAMETER(pArg);
  UNUSED_PARAMETER(nBusy);
  sqlite3_sleep(50);
  return 1;             /* Try again... */
}

/*
** sqlthread open
**
**     Open a database handle and return the string representation of
**     the pointer value.
*/
static int sqlthread_open(
  ClientData clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p);

  const char *zFilename;
  sqlite3 *db;
  int rc;
  char zBuf[100];
  extern void Md5_Register(sqlite3*);

  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(objc);

  zFilename = Tcl_GetString(objv[2]);
  rc = sqlite3_open(zFilename, &db);
  Md5_Register(db);
  sqlite3_busy_handler(db, xBusy, 0);
  
  if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
  Tcl_AppendResult(interp, zBuf, 0);

  return TCL_OK;
}


/*
** sqlthread open
**
**     Return the current thread-id (Tcl_GetCurrentThread()) cast to
**     an integer.
*/
static int sqlthread_id(
  ClientData clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_ThreadId id = Tcl_GetCurrentThread();
  Tcl_SetObjResult(interp, Tcl_NewIntObj((int)id));
  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(objc);
  UNUSED_PARAMETER(objv);
  return TCL_OK;
}


/*
** Dispatch routine for the sub-commands of [sqlthread].
*/
static int sqlthread_proc(
  ClientData clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  struct SubCommand {
    char *zName;
    Tcl_ObjCmdProc *xProc;
    int nArg;
    char *zUsage;
  } aSub[] = {
    {"parent", sqlthread_parent, 1, "SCRIPT"},
    {"spawn",  sqlthread_spawn,  2, "VARNAME SCRIPT"},
    {"open",   sqlthread_open,   1, "DBNAME"},
    {"id",     sqlthread_id,     0, ""},
    {0, 0, 0}
  };
  struct SubCommand *pSub;
  int rc;
  int iIndex;

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND");
    return TCL_ERROR;
  }

  rc = Tcl_GetIndexFromObjStruct(
      interp, objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iIndex
  );
  if( rc!=TCL_OK ) return rc;
  pSub = &aSub[iIndex];

  if( objc!=(pSub->nArg+2) ){
    Tcl_WrongNumArgs(interp, 2, objv, pSub->zUsage);
    return TCL_ERROR;
  }

  return pSub->xProc(clientData, interp, objc, objv);
}

/*
** The [clock_seconds] command. This is more or less the same as the
** regular tcl [clock seconds], except that it is available in testfixture
** when linked against both Tcl 8.4 and 8.5. Because [clock seconds] is
** implemented as a script in Tcl 8.5, it is not usually available to
** testfixture.
*/ 
static int clock_seconds_proc(
  ClientData clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  Tcl_Time now;
  Tcl_GetTime(&now);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(now.sec));
  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(objc);
  UNUSED_PARAMETER(objv);
  return TCL_OK;
}

/*************************************************************************
** This block contains the implementation of the [sqlite3_blocking_step]
** command available to threads created by [sqlthread spawn] commands. It
** is only available on UNIX for now. This is because pthread condition
** variables are used.
**
** The source code for the C functions sqlite3_blocking_step(),
** blocking_step_notify() and the structure UnlockNotification is
** automatically extracted from this file and used as part of the
** documentation for the sqlite3_unlock_notify() API function. This
** should be considered if these functions are to be extended (i.e. to 
** support windows) in the future.
*/ 
#if defined(SQLITE_OS_UNIX) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)

/* BEGIN_SQLITE_BLOCKING_STEP */
/* This example uses the pthreads API */
#include <pthread.h>

/*
** A pointer to an instance of this structure is passed as the user-context
** pointer when registering for an unlock-notify callback.
*/
typedef struct UnlockNotification UnlockNotification;
struct UnlockNotification {
  int fired;                           /* True after unlock event has occured */
  pthread_cond_t cond;                 /* Condition variable to wait on */
  pthread_mutex_t mutex;               /* Mutex to protect structure */
};

/*
** This function is an unlock-notify callback registered with SQLite.
*/
static void unlock_notify_cb(void **apArg, int nArg){
  int i;
  for(i=0; i<nArg; i++){
    UnlockNotification *p = (UnlockNotification *)apArg[i];
    pthread_mutex_lock(&p->mutex);
    p->fired = 1;
    pthread_cond_signal(&p->cond);
    pthread_mutex_unlock(&p->mutex);
  }
}

/*
** This function assumes that an SQLite API call (either sqlite3_prepare_v2() 
** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the
** associated database connection.
**
** This function calls sqlite3_unlock_notify() to register for an 
** unlock-notify callback, then blocks until that callback is delivered 
** and returns SQLITE_OK. The caller should then retry the failed operation.
**
** Or, if sqlite3_unlock_notify() indicates that to block would deadlock 
** the system, then this function returns SQLITE_LOCKED immediately. In 
** this case the caller should not retry the operation and should roll 
** back the current transaction (if any).
*/
static int wait_for_unlock_notify(sqlite3 *db){
  int rc;
  UnlockNotification un;

  /* Initialize the UnlockNotification structure. */
  un.fired = 0;
  pthread_mutex_init(&un.mutex, 0);
  pthread_cond_init(&un.cond, 0);

  /* Register for an unlock-notify callback. */
  rc = sqlite3_unlock_notify(db, unlock_notify_cb, (void *)&un);
  assert( rc==SQLITE_LOCKED || rc==SQLITE_OK );

  /* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED 
  ** or SQLITE_OK. 
  **
  ** If SQLITE_LOCKED was returned, then the system is deadlocked. In this
  ** case this function needs to return SQLITE_LOCKED to the caller so 
  ** that the current transaction can be rolled back. Otherwise, block
  ** until the unlock-notify callback is invoked, then return SQLITE_OK.
  */
  if( rc==SQLITE_OK ){
    pthread_mutex_lock(&un.mutex);
    if( !un.fired ){
      pthread_cond_wait(&un.cond, &un.mutex);
    }
    pthread_mutex_unlock(&un.mutex);
  }

  /* Destroy the mutex and condition variables. */
  pthread_cond_destroy(&un.cond);
  pthread_mutex_destroy(&un.mutex);

  return rc;
}

/*
** This function is a wrapper around the SQLite function sqlite3_step().
** It functions in the same way as step(), except that if a required
** shared-cache lock cannot be obtained, this function may block waiting for
** the lock to become available. In this scenario the normal API step()
** function always returns SQLITE_LOCKED.
**
** If this function returns SQLITE_LOCKED, the caller should rollback
** the current transaction (if any) and try again later. Otherwise, the
** system may become deadlocked.
*/
int sqlite3_blocking_step(sqlite3_stmt *pStmt){
  int rc;
  while( SQLITE_LOCKED==(rc = sqlite3_step(pStmt)) ){
    rc = wait_for_unlock_notify(sqlite3_db_handle(pStmt));
    if( rc!=SQLITE_OK ) break;
    sqlite3_reset(pStmt);
  }
  return rc;
}

/*
** This function is a wrapper around the SQLite function sqlite3_prepare_v2().
** It functions in the same way as prepare_v2(), except that if a required
** shared-cache lock cannot be obtained, this function may block waiting for
** the lock to become available. In this scenario the normal API prepare_v2()
** function always returns SQLITE_LOCKED.
**
** If this function returns SQLITE_LOCKED, the caller should rollback
** the current transaction (if any) and try again later. Otherwise, the
** system may become deadlocked.
*/
int sqlite3_blocking_prepare_v2(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nSql,                 /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pz           /* OUT: End of parsed string */
){
  int rc;
  while( SQLITE_LOCKED==(rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, pz)) ){
    rc = wait_for_unlock_notify(db);
    if( rc!=SQLITE_OK ) break;
  }
  return rc;
}
/* END_SQLITE_BLOCKING_STEP */

/*
** Usage: sqlite3_blocking_step STMT
**
** Advance the statement to the next row.
*/
static int blocking_step_proc(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){

  sqlite3_stmt *pStmt;
  int rc;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "STMT");
    return TCL_ERROR;
  }

  pStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(Tcl_GetString(objv[1]));
  rc = sqlite3_blocking_step(pStmt);

  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), 0);
  return TCL_OK;
}

/*
** Usage: sqlite3_blocking_prepare_v2 DB sql bytes ?tailvar?
** Usage: sqlite3_nonblocking_prepare_v2 DB sql bytes ?tailvar?
*/
static int blocking_prepare_v2_proc(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3 *db;
  const char *zSql;
  int bytes;
  const char *zTail = 0;
  sqlite3_stmt *pStmt = 0;
  char zBuf[50];
  int rc;
  int isBlocking = !(clientData==0);

  if( objc!=5 && objc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", 
       Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zSql = Tcl_GetString(objv[2]);
  if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;

  if( isBlocking ){
    rc = sqlite3_blocking_prepare_v2(db, zSql, bytes, &pStmt, &zTail);
  }else{
    rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, &zTail);
  }

  assert(rc==SQLITE_OK || pStmt==0);
  if( zTail && objc>=5 ){
    if( bytes>=0 ){
      bytes = bytes - (zTail-zSql);
    }
    Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0);
  }
  if( rc!=SQLITE_OK ){
    assert( pStmt==0 );
    sprintf(zBuf, "%s ", (char *)sqlite3TestErrorName(rc));
    Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
    return TCL_ERROR;
  }

  if( pStmt ){
    if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}

#endif /* SQLITE_OS_UNIX && SQLITE_ENABLE_UNLOCK_NOTIFY */
/*
** End of implementation of [sqlite3_blocking_step].
************************************************************************/

/*
** Register commands with the TCL interpreter.
*/
int SqlitetestThread_Init(Tcl_Interp *interp){
  Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, 0, 0);
  Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0);
#if defined(SQLITE_OS_UNIX) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
  Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0);
  Tcl_CreateObjCommand(interp, 
      "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0);
  Tcl_CreateObjCommand(interp, 
      "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0);
#endif
  return TCL_OK;
}
#else
int SqlitetestThread_Init(Tcl_Interp *interp){
  return TCL_OK;
}
#endif

Added src/test_wsd.c.













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
** 2008 September 1
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** The code in this file contains sample implementations of the 
** sqlite3_wsd_init() and sqlite3_wsd_find() functions required if the
** SQLITE_OMIT_WSD symbol is defined at build time.
**
** $Id: test_wsd.c,v 1.4 2009/03/23 04:33:33 danielk1977 Exp $
*/

#if defined(SQLITE_OMIT_WSD) && defined(SQLITE_TEST)

#include "sqliteInt.h"

#define PLS_HASHSIZE 43

typedef struct ProcessLocalStorage ProcessLocalStorage;
typedef struct ProcessLocalVar ProcessLocalVar;

struct ProcessLocalStorage {
  ProcessLocalVar *aData[PLS_HASHSIZE];
  int nFree;
  u8 *pFree;
};

struct ProcessLocalVar {
  void *pKey;
  ProcessLocalVar *pNext;
};

static ProcessLocalStorage *pGlobal = 0;

int sqlite3_wsd_init(int N, int J){
  if( !pGlobal ){
    int nMalloc = N + sizeof(ProcessLocalStorage) + J*sizeof(ProcessLocalVar);
    pGlobal = (ProcessLocalStorage *)malloc(nMalloc);
    if( pGlobal ){
      memset(pGlobal, 0, sizeof(ProcessLocalStorage));
      pGlobal->nFree = nMalloc - sizeof(ProcessLocalStorage);
      pGlobal->pFree = (u8 *)&pGlobal[1];
    }
  }

  return pGlobal ? SQLITE_OK : SQLITE_NOMEM;
}

void *sqlite3_wsd_find(void *K, int L){
  int i;
  int iHash = 0;
  ProcessLocalVar *pVar;

  /* Calculate a hash of K */
  for(i=0; i<sizeof(void*); i++){
    iHash = (iHash<<3) + ((unsigned char *)&K)[i];
  }
  iHash = iHash%PLS_HASHSIZE;

  /* Search the hash table for K. */
  for(pVar=pGlobal->aData[iHash]; pVar && pVar->pKey!=K; pVar=pVar->pNext);

  /* If no entry for K was found, create and populate a new one. */
  if( !pVar ){
    int nByte = ROUND8(sizeof(ProcessLocalVar) + L);
    assert( pGlobal->nFree>=nByte );
    pVar = (ProcessLocalVar *)pGlobal->pFree;
    pVar->pKey = K;
    pVar->pNext = pGlobal->aData[iHash];
    pGlobal->aData[iHash] = pVar;
    pGlobal->nFree -= nByte;
    pGlobal->pFree += nByte;
    memcpy(&pVar[1], K, L);
  }

  return (void *)&pVar[1];
}

#endif

Added src/tokenize.c.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
**
** $Id: tokenize.c,v 1.163 2009/07/03 22:54:37 drh Exp $
*/
#include "sqliteInt.h"
#include <stdlib.h>

/*
** The charMap() macro maps alphabetic characters into their
** lower-case ASCII equivalent.  On ASCII machines, this is just
** an upper-to-lower case map.  On EBCDIC machines we also need
** to adjust the encoding.  Only alphabetic characters and underscores
** need to be translated.
*/
#ifdef SQLITE_ASCII
# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
#endif
#ifdef SQLITE_EBCDIC
# define charMap(X) ebcdicToAscii[(unsigned char)X]
const unsigned char ebcdicToAscii[] = {
/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
};
#endif

/*
** The sqlite3KeywordCode function looks up an identifier to determine if
** it is a keyword.  If it is a keyword, the token code of that keyword is 
** returned.  If the input is not a keyword, TK_ID is returned.
**
** The implementation of this routine was generated by a program,
** mkkeywordhash.h, located in the tool subdirectory of the distribution.
** The output of the mkkeywordhash.c program is written into a file
** named keywordhash.h and then included into this source file by
** the #include below.
*/
#include "keywordhash.h"


/*
** If X is a character that can be used in an identifier then
** IdChar(X) will be true.  Otherwise it is false.
**
** For ASCII, any character with the high-order bit set is
** allowed in an identifier.  For 7-bit characters, 
** sqlite3IsIdChar[X] must be 1.
**
** For EBCDIC, the rules are more complex but have the same
** end result.
**
** Ticket #1066.  the SQL standard does not allow '$' in the
** middle of identfiers.  But many SQL implementations do. 
** SQLite will allow '$' in identifiers for compatibility.
** But the feature is undocumented.
*/
#ifdef SQLITE_ASCII
const char sqlite3IsAsciiIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
};
#define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
#endif
#ifdef SQLITE_EBCDIC
const char sqlite3IsEbcdicIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
};
#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
#endif


/*
** Return the length of the token that begins at z[0]. 
** Store the token type in *tokenType before returning.
*/
int sqlite3GetToken(const unsigned char *z, int *tokenType){
  int i, c;
  switch( *z ){
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      testcase( z[0]==' ' );
      testcase( z[0]=='\t' );
      testcase( z[0]=='\n' );
      testcase( z[0]=='\f' );
      testcase( z[0]=='\r' );
      for(i=1; sqlite3Isspace(z[i]); i++){}
      *tokenType = TK_SPACE;
      return i;
    }
    case '-': {
      if( z[1]=='-' ){
        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
        *tokenType = TK_SPACE;
        return i;
      }
      *tokenType = TK_MINUS;
      return 1;
    }
    case '(': {
      *tokenType = TK_LP;
      return 1;
    }
    case ')': {
      *tokenType = TK_RP;
      return 1;
    }
    case ';': {
      *tokenType = TK_SEMI;
      return 1;
    }
    case '+': {
      *tokenType = TK_PLUS;
      return 1;
    }
    case '*': {
      *tokenType = TK_STAR;
      return 1;
    }
    case '/': {
      if( z[1]!='*' || z[2]==0 ){
        *tokenType = TK_SLASH;
        return 1;
      }
      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
      if( c ) i++;
      *tokenType = TK_SPACE;
      return i;
    }
    case '%': {
      *tokenType = TK_REM;
      return 1;
    }
    case '=': {
      *tokenType = TK_EQ;
      return 1 + (z[1]=='=');
    }
    case '<': {
      if( (c=z[1])=='=' ){
        *tokenType = TK_LE;
        return 2;
      }else if( c=='>' ){
        *tokenType = TK_NE;
        return 2;
      }else if( c=='<' ){
        *tokenType = TK_LSHIFT;
        return 2;
      }else{
        *tokenType = TK_LT;
        return 1;
      }
    }
    case '>': {
      if( (c=z[1])=='=' ){
        *tokenType = TK_GE;
        return 2;
      }else if( c=='>' ){
        *tokenType = TK_RSHIFT;
        return 2;
      }else{
        *tokenType = TK_GT;
        return 1;
      }
    }
    case '!': {
      if( z[1]!='=' ){
        *tokenType = TK_ILLEGAL;
        return 2;
      }else{
        *tokenType = TK_NE;
        return 2;
      }
    }
    case '|': {
      if( z[1]!='|' ){
        *tokenType = TK_BITOR;
        return 1;
      }else{
        *tokenType = TK_CONCAT;
        return 2;
      }
    }
    case ',': {
      *tokenType = TK_COMMA;
      return 1;
    }
    case '&': {
      *tokenType = TK_BITAND;
      return 1;
    }
    case '~': {
      *tokenType = TK_BITNOT;
      return 1;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      testcase( delim=='`' );
      testcase( delim=='\'' );
      testcase( delim=='"' );
      for(i=1; (c=z[i])!=0; i++){
        if( c==delim ){
          if( z[i+1]==delim ){
            i++;
          }else{
            break;
          }
        }
      }
      if( c=='\'' ){
        *tokenType = TK_STRING;
        return i+1;
      }else if( c!=0 ){
        *tokenType = TK_ID;
        return i+1;
      }else{
        *tokenType = TK_ILLEGAL;
        return i;
      }
    }
    case '.': {
#ifndef SQLITE_OMIT_FLOATING_POINT
      if( !sqlite3Isdigit(z[1]) )
#endif
      {
        *tokenType = TK_DOT;
        return 1;
      }
      /* If the next character is a digit, this is a floating point
      ** number that begins with ".".  Fall thru into the next case */
    }
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9': {
      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
      testcase( z[0]=='9' );
      *tokenType = TK_INTEGER;
      for(i=0; sqlite3Isdigit(z[i]); i++){}
#ifndef SQLITE_OMIT_FLOATING_POINT
      if( z[i]=='.' ){
        i++;
        while( sqlite3Isdigit(z[i]) ){ i++; }
        *tokenType = TK_FLOAT;
      }
      if( (z[i]=='e' || z[i]=='E') &&
           ( sqlite3Isdigit(z[i+1]) 
            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
           )
      ){
        i += 2;
        while( sqlite3Isdigit(z[i]) ){ i++; }
        *tokenType = TK_FLOAT;
      }
#endif
      while( IdChar(z[i]) ){
        *tokenType = TK_ILLEGAL;
        i++;
      }
      return i;
    }
    case '[': {
      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
      return i;
    }
    case '?': {
      *tokenType = TK_VARIABLE;
      for(i=1; sqlite3Isdigit(z[i]); i++){}
      return i;
    }
    case '#': {
      for(i=1; sqlite3Isdigit(z[i]); i++){}
      if( i>1 ){
        /* Parameters of the form #NNN (where NNN is a number) are used
        ** internally by sqlite3NestedParse.  */
        *tokenType = TK_REGISTER;
        return i;
      }
      /* Fall through into the next case if the '#' is not followed by
      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
    }
#ifndef SQLITE_OMIT_TCL_VARIABLE
    case '$':
#endif
    case '@':  /* For compatibility with MS SQL Server */
    case ':': {
      int n = 0;
      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
      *tokenType = TK_VARIABLE;
      for(i=1; (c=z[i])!=0; i++){
        if( IdChar(c) ){
          n++;
#ifndef SQLITE_OMIT_TCL_VARIABLE
        }else if( c=='(' && n>0 ){
          do{
            i++;
          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
          if( c==')' ){
            i++;
          }else{
            *tokenType = TK_ILLEGAL;
          }
          break;
        }else if( c==':' && z[i+1]==':' ){
          i++;
#endif
        }else{
          break;
        }
      }
      if( n==0 ) *tokenType = TK_ILLEGAL;
      return i;
    }
#ifndef SQLITE_OMIT_BLOB_LITERAL
    case 'x': case 'X': {
      testcase( z[0]=='x' ); testcase( z[0]=='X' );
      if( z[1]=='\'' ){
        *tokenType = TK_BLOB;
        for(i=2; (c=z[i])!=0 && c!='\''; i++){
          if( !sqlite3Isxdigit(c) ){
            *tokenType = TK_ILLEGAL;
          }
        }
        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
        if( c ) i++;
        return i;
      }
      /* Otherwise fall through to the next case */
    }
#endif
    default: {
      if( !IdChar(*z) ){
        break;
      }
      for(i=1; IdChar(z[i]); i++){}
      *tokenType = keywordCode((char*)z, i);
      return i;
    }
  }
  *tokenType = TK_ILLEGAL;
  return 1;
}

/*
** Run the parser on the given SQL string.  The parser structure is
** passed in.  An SQLITE_ status code is returned.  If an error occurs
** then an and attempt is made to write an error message into 
** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
** error message.
*/
int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  int nErr = 0;                   /* Number of errors encountered */
  int i;                          /* Loop counter */
  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
  int tokenType;                  /* type of the next token */
  int lastTokenParsed = -1;       /* type of the previous token */
  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
  sqlite3 *db = pParse->db;       /* The database connection */
  int mxSqlLen;                   /* Max length of an SQL string */


  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  if( db->activeVdbeCnt==0 ){
    db->u1.isInterrupted = 0;
  }
  pParse->rc = SQLITE_OK;
  pParse->zTail = zSql;
  i = 0;
  assert( pzErrMsg!=0 );
  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  if( pEngine==0 ){
    db->mallocFailed = 1;
    return SQLITE_NOMEM;
  }
  assert( pParse->pNewTable==0 );
  assert( pParse->pNewTrigger==0 );
  assert( pParse->nVar==0 );
  assert( pParse->nVarExpr==0 );
  assert( pParse->nVarExprAlloc==0 );
  assert( pParse->apVarExpr==0 );
  enableLookaside = db->lookaside.bEnabled;
  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  while( !db->mallocFailed && zSql[i]!=0 ){
    assert( i>=0 );
    pParse->sLastToken.z = &zSql[i];
    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
    i += pParse->sLastToken.n;
    if( i>mxSqlLen ){
      pParse->rc = SQLITE_TOOBIG;
      break;
    }
    switch( tokenType ){
      case TK_SPACE: {
        if( db->u1.isInterrupted ){
          sqlite3ErrorMsg(pParse, "interrupt");
          pParse->rc = SQLITE_INTERRUPT;
          goto abort_parse;
        }
        break;
      }
      case TK_ILLEGAL: {
        sqlite3DbFree(db, *pzErrMsg);
        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
                        &pParse->sLastToken);
        nErr++;
        goto abort_parse;
      }
      case TK_SEMI: {
        pParse->zTail = &zSql[i];
        /* Fall thru into the default case */
      }
      default: {
        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
        lastTokenParsed = tokenType;
        if( pParse->rc!=SQLITE_OK ){
          goto abort_parse;
        }
        break;
      }
    }
  }
abort_parse:
  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
    if( lastTokenParsed!=TK_SEMI ){
      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
      pParse->zTail = &zSql[i];
    }
    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  }
#ifdef YYTRACKMAXSTACKDEPTH
  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
      sqlite3ParserStackPeak(pEngine)
  );
#endif /* YYDEBUG */
  sqlite3ParserFree(pEngine, sqlite3_free);
  db->lookaside.bEnabled = enableLookaside;
  if( db->mallocFailed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  }
  assert( pzErrMsg!=0 );
  if( pParse->zErrMsg ){
    *pzErrMsg = pParse->zErrMsg;
    pParse->zErrMsg = 0;
    nErr++;
  }
  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
    sqlite3VdbeDelete(pParse->pVdbe);
    pParse->pVdbe = 0;
  }
#ifndef SQLITE_OMIT_SHARED_CACHE
  if( pParse->nested==0 ){
    sqlite3DbFree(db, pParse->aTableLock);
    pParse->aTableLock = 0;
    pParse->nTableLock = 0;
  }
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3DbFree(db, pParse->apVtabLock);
#endif

  if( !IN_DECLARE_VTAB ){
    /* If the pParse->declareVtab flag is set, do not delete any table 
    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
    ** will take responsibility for freeing the Table structure.
    */
    sqlite3DeleteTable(pParse->pNewTable);
  }

  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  sqlite3DbFree(db, pParse->apVarExpr);
  sqlite3DbFree(db, pParse->aAlias);
  while( pParse->pAinc ){
    AutoincInfo *p = pParse->pAinc;
    pParse->pAinc = p->pNext;
    sqlite3DbFree(db, p);
  }
  while( pParse->pZombieTab ){
    Table *p = pParse->pZombieTab;
    pParse->pZombieTab = p->pNextZombie;
    sqlite3DeleteTable(p);
  }
  if( nErr>0 && pParse->rc==SQLITE_OK ){
    pParse->rc = SQLITE_ERROR;
  }
  return nErr;
}

Added src/trigger.c.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
/*
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
**
** $Id: trigger.c,v 1.143 2009/08/10 03:57:58 shane Exp $
*/
#include "sqliteInt.h"

#ifndef SQLITE_OMIT_TRIGGER
/*
** Delete a linked list of TriggerStep structures.
*/
void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  while( pTriggerStep ){
    TriggerStep * pTmp = pTriggerStep;
    pTriggerStep = pTriggerStep->pNext;

    sqlite3ExprDelete(db, pTmp->pWhere);
    sqlite3ExprListDelete(db, pTmp->pExprList);
    sqlite3SelectDelete(db, pTmp->pSelect);
    sqlite3IdListDelete(db, pTmp->pIdList);

    sqlite3DbFree(db, pTmp);
  }
}

/*
** Given table pTab, return a list of all the triggers attached to 
** the table. The list is connected by Trigger.pNext pointers.
**
** All of the triggers on pTab that are in the same database as pTab
** are already attached to pTab->pTrigger.  But there might be additional
** triggers on pTab in the TEMP schema.  This routine prepends all
** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
** and returns the combined list.
**
** To state it another way:  This routine returns a list of all triggers
** that fire off of pTab.  The list will include any TEMP triggers on
** pTab as well as the triggers lised in pTab->pTrigger.
*/
Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  Trigger *pList = 0;                  /* List of triggers to return */

  if( pParse->disableTriggers ){
    return 0;
  }

  if( pTmpSchema!=pTab->pSchema ){
    HashElem *p;
    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
      Trigger *pTrig = (Trigger *)sqliteHashData(p);
      if( pTrig->pTabSchema==pTab->pSchema
       && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
      ){
        pTrig->pNext = (pList ? pList : pTab->pTrigger);
        pList = pTrig;
      }
    }
  }

  return (pList ? pList : pTab->pTrigger);
}

/*
** This is called by the parser when it sees a CREATE TRIGGER statement
** up to the point of the BEGIN before the trigger actions.  A Trigger
** structure is generated based on the information available and stored
** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
** sqlite3FinishTrigger() function is called to complete the trigger
** construction process.
*/
void sqlite3BeginTrigger(
  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
  Token *pName1,      /* The name of the trigger */
  Token *pName2,      /* The name of the trigger */
  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
  SrcList *pTableName,/* The name of the table/view the trigger applies to */
  Expr *pWhen,        /* WHEN clause */
  int isTemp,         /* True if the TEMPORARY keyword is present */
  int noErr           /* Suppress errors if the trigger already exists */
){
  Trigger *pTrigger = 0;  /* The new trigger */
  Table *pTab;            /* Table that the trigger fires off of */
  char *zName = 0;        /* Name of the trigger */
  sqlite3 *db = pParse->db;  /* The database connection */
  int iDb;                /* The database to store the trigger in */
  Token *pName;           /* The unqualified db name */
  DbFixer sFix;           /* State vector for the DB fixer */
  int iTabDb;             /* Index of the database holding pTab */

  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
  assert( pName2!=0 );
  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  assert( op>0 && op<0xff );
  if( isTemp ){
    /* If TEMP was specified, then the trigger name may not be qualified. */
    if( pName2->n>0 ){
      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
      goto trigger_cleanup;
    }
    iDb = 1;
    pName = pName1;
  }else{
    /* Figure out the db that the the trigger will be created in */
    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
    if( iDb<0 ){
      goto trigger_cleanup;
    }
  }

  /* If the trigger name was unqualified, and the table is a temp table,
  ** then set iDb to 1 to create the trigger in the temporary database.
  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  ** exist, the error is caught by the block below.
  */
  if( !pTableName || db->mallocFailed ){
    goto trigger_cleanup;
  }
  pTab = sqlite3SrcListLookup(pParse, pTableName);
  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
    iDb = 1;
  }

  /* Ensure the table name matches database name and that the table exists */
  if( db->mallocFailed ) goto trigger_cleanup;
  assert( pTableName->nSrc==1 );
  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
      sqlite3FixSrcList(&sFix, pTableName) ){
    goto trigger_cleanup;
  }
  pTab = sqlite3SrcListLookup(pParse, pTableName);
  if( !pTab ){
    /* The table does not exist. */
    if( db->init.iDb==1 ){
      /* Ticket #3810.
      ** Normally, whenever a table is dropped, all associated triggers are
      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
      ** and the table is dropped by a different database connection, the
      ** trigger is not visible to the database connection that does the
      ** drop so the trigger cannot be dropped.  This results in an
      ** "orphaned trigger" - a trigger whose associated table is missing.
      */
      db->init.orphanTrigger = 1;
    }
    goto trigger_cleanup;
  }
  if( IsVirtual(pTab) ){
    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
    goto trigger_cleanup;
  }

  /* Check that the trigger name is not reserved and that no trigger of the
  ** specified name exists */
  zName = sqlite3NameFromToken(db, pName);
  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
    goto trigger_cleanup;
  }
  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
                      zName, sqlite3Strlen30(zName)) ){
    if( !noErr ){
      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
    }
    goto trigger_cleanup;
  }

  /* Do not create a trigger on a system table */
  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
    pParse->nErr++;
    goto trigger_cleanup;
  }

  /* INSTEAD of triggers are only for views and views only support INSTEAD
  ** of triggers.
  */
  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
    goto trigger_cleanup;
  }
  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
        " trigger on table: %S", pTableName, 0);
    goto trigger_cleanup;
  }
  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);

#ifndef SQLITE_OMIT_AUTHORIZATION
  {
    int code = SQLITE_CREATE_TRIGGER;
    const char *zDb = db->aDb[iTabDb].zName;
    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
      goto trigger_cleanup;
    }
    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
      goto trigger_cleanup;
    }
  }
#endif

  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  ** cannot appear on views.  So we might as well translate every
  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
  ** elsewhere.
  */
  if (tr_tm == TK_INSTEAD){
    tr_tm = TK_BEFORE;
  }

  /* Build the Trigger object */
  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  if( pTrigger==0 ) goto trigger_cleanup;
  pTrigger->zName = zName;
  zName = 0;
  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  pTrigger->pSchema = db->aDb[iDb].pSchema;
  pTrigger->pTabSchema = pTab->pSchema;
  pTrigger->op = (u8)op;
  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  assert( pParse->pNewTrigger==0 );
  pParse->pNewTrigger = pTrigger;

trigger_cleanup:
  sqlite3DbFree(db, zName);
  sqlite3SrcListDelete(db, pTableName);
  sqlite3IdListDelete(db, pColumns);
  sqlite3ExprDelete(db, pWhen);
  if( !pParse->pNewTrigger ){
    sqlite3DeleteTrigger(db, pTrigger);
  }else{
    assert( pParse->pNewTrigger==pTrigger );
  }
}

/*
** This routine is called after all of the trigger actions have been parsed
** in order to complete the process of building the trigger.
*/
void sqlite3FinishTrigger(
  Parse *pParse,          /* Parser context */
  TriggerStep *pStepList, /* The triggered program */
  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
){
  Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
  char *zName;                             /* Name of trigger */
  sqlite3 *db = pParse->db;                /* The database */
  DbFixer sFix;
  int iDb;                                 /* Database containing the trigger */
  Token nameToken;           /* Trigger name for error reporting */

  pTrig = pParse->pNewTrigger;
  pParse->pNewTrigger = 0;
  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  zName = pTrig->zName;
  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  pTrig->step_list = pStepList;
  while( pStepList ){
    pStepList->pTrig = pTrig;
    pStepList = pStepList->pNext;
  }
  nameToken.z = pTrig->zName;
  nameToken.n = sqlite3Strlen30(nameToken.z);
  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
    goto triggerfinish_cleanup;
  }

  /* if we are not initializing, and this trigger is not on a TEMP table, 
  ** build the sqlite_master entry
  */
  if( !db->init.busy ){
    Vdbe *v;
    char *z;

    /* Make an entry in the sqlite_master table */
    v = sqlite3GetVdbe(pParse);
    if( v==0 ) goto triggerfinish_cleanup;
    sqlite3BeginWriteOperation(pParse, 0, iDb);
    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
    sqlite3NestedParse(pParse,
       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
       pTrig->table, z);
    sqlite3DbFree(db, z);
    sqlite3ChangeCookie(pParse, iDb);
    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
    );
  }

  if( db->init.busy ){
    Trigger *pLink = pTrig;
    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
    if( pTrig ){
      db->mallocFailed = 1;
    }else if( pLink->pSchema==pLink->pTabSchema ){
      Table *pTab;
      int n = sqlite3Strlen30(pLink->table);
      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
      assert( pTab!=0 );
      pLink->pNext = pTab->pTrigger;
      pTab->pTrigger = pLink;
    }
  }

triggerfinish_cleanup:
  sqlite3DeleteTrigger(db, pTrig);
  assert( !pParse->pNewTrigger );
  sqlite3DeleteTriggerStep(db, pStepList);
}

/*
** Turn a SELECT statement (that the pSelect parameter points to) into
** a trigger step.  Return a pointer to a TriggerStep structure.
**
** The parser calls this routine when it finds a SELECT statement in
** body of a TRIGGER.  
*/
TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  if( pTriggerStep==0 ) {
    sqlite3SelectDelete(db, pSelect);
    return 0;
  }
  pTriggerStep->op = TK_SELECT;
  pTriggerStep->pSelect = pSelect;
  pTriggerStep->orconf = OE_Default;
  return pTriggerStep;
}

/*
** Allocate space to hold a new trigger step.  The allocated space
** holds both the TriggerStep object and the TriggerStep.target.z string.
**
** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
*/
static TriggerStep *triggerStepAllocate(
  sqlite3 *db,                /* Database connection */
  u8 op,                      /* Trigger opcode */
  Token *pName                /* The target name */
){
  TriggerStep *pTriggerStep;

  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  if( pTriggerStep ){
    char *z = (char*)&pTriggerStep[1];
    memcpy(z, pName->z, pName->n);
    pTriggerStep->target.z = z;
    pTriggerStep->target.n = pName->n;
    pTriggerStep->op = op;
  }
  return pTriggerStep;
}

/*
** Build a trigger step out of an INSERT statement.  Return a pointer
** to the new trigger step.
**
** The parser calls this routine when it sees an INSERT inside the
** body of a trigger.
*/
TriggerStep *sqlite3TriggerInsertStep(
  sqlite3 *db,        /* The database connection */
  Token *pTableName,  /* Name of the table into which we insert */
  IdList *pColumn,    /* List of columns in pTableName to insert into */
  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
  Select *pSelect,    /* A SELECT statement that supplies values */
  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
){
  TriggerStep *pTriggerStep;

  assert(pEList == 0 || pSelect == 0);
  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);

  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  if( pTriggerStep ){
    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
    pTriggerStep->pIdList = pColumn;
    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
    pTriggerStep->orconf = orconf;
  }else{
    sqlite3IdListDelete(db, pColumn);
  }
  sqlite3ExprListDelete(db, pEList);
  sqlite3SelectDelete(db, pSelect);

  return pTriggerStep;
}

/*
** Construct a trigger step that implements an UPDATE statement and return
** a pointer to that trigger step.  The parser calls this routine when it
** sees an UPDATE statement inside the body of a CREATE TRIGGER.
*/
TriggerStep *sqlite3TriggerUpdateStep(
  sqlite3 *db,         /* The database connection */
  Token *pTableName,   /* Name of the table to be updated */
  ExprList *pEList,    /* The SET clause: list of column and new values */
  Expr *pWhere,        /* The WHERE clause */
  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
){
  TriggerStep *pTriggerStep;

  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  if( pTriggerStep ){
    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
    pTriggerStep->orconf = orconf;
  }
  sqlite3ExprListDelete(db, pEList);
  sqlite3ExprDelete(db, pWhere);
  return pTriggerStep;
}

/*
** Construct a trigger step that implements a DELETE statement and return
** a pointer to that trigger step.  The parser calls this routine when it
** sees a DELETE statement inside the body of a CREATE TRIGGER.
*/
TriggerStep *sqlite3TriggerDeleteStep(
  sqlite3 *db,            /* Database connection */
  Token *pTableName,      /* The table from which rows are deleted */
  Expr *pWhere            /* The WHERE clause */
){
  TriggerStep *pTriggerStep;

  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  if( pTriggerStep ){
    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
    pTriggerStep->orconf = OE_Default;
  }
  sqlite3ExprDelete(db, pWhere);
  return pTriggerStep;
}

/* 
** Recursively delete a Trigger structure
*/
void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  if( pTrigger==0 ) return;
  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  sqlite3DbFree(db, pTrigger->zName);
  sqlite3DbFree(db, pTrigger->table);
  sqlite3ExprDelete(db, pTrigger->pWhen);
  sqlite3IdListDelete(db, pTrigger->pColumns);
  sqlite3DbFree(db, pTrigger);
}

/*
** This function is called to drop a trigger from the database schema. 
**
** This may be called directly from the parser and therefore identifies
** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
** same job as this routine except it takes a pointer to the trigger
** instead of the trigger name.
**/
void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  Trigger *pTrigger = 0;
  int i;
  const char *zDb;
  const char *zName;
  int nName;
  sqlite3 *db = pParse->db;

  if( db->mallocFailed ) goto drop_trigger_cleanup;
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    goto drop_trigger_cleanup;
  }

  assert( pName->nSrc==1 );
  zDb = pName->a[0].zDatabase;
  zName = pName->a[0].zName;
  nName = sqlite3Strlen30(zName);
  for(i=OMIT_TEMPDB; i<db->nDb; i++){
    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
    if( pTrigger ) break;
  }
  if( !pTrigger ){
    if( !noErr ){
      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
    }
    goto drop_trigger_cleanup;
  }
  sqlite3DropTriggerPtr(pParse, pTrigger);

drop_trigger_cleanup:
  sqlite3SrcListDelete(db, pName);
}

/*
** Return a pointer to the Table structure for the table that a trigger
** is set on.
*/
static Table *tableOfTrigger(Trigger *pTrigger){
  int n = sqlite3Strlen30(pTrigger->table);
  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
}


/*
** Drop a trigger given a pointer to that trigger. 
*/
void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  Table   *pTable;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  assert( iDb>=0 && iDb<db->nDb );
  pTable = tableOfTrigger(pTrigger);
  assert( pTable );
  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
#ifndef SQLITE_OMIT_AUTHORIZATION
  {
    int code = SQLITE_DROP_TRIGGER;
    const char *zDb = db->aDb[iDb].zName;
    const char *zTab = SCHEMA_TABLE(iDb);
    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
      return;
    }
  }
#endif

  /* Generate code to destroy the database record of the trigger.
  */
  assert( pTable!=0 );
  if( (v = sqlite3GetVdbe(pParse))!=0 ){
    int base;
    static const VdbeOpList dropTrigger[] = {
      { OP_Rewind,     0, ADDR(9),  0},
      { OP_String8,    0, 1,        0}, /* 1 */
      { OP_Column,     0, 1,        2},
      { OP_Ne,         2, ADDR(8),  1},
      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
      { OP_Column,     0, 0,        2},
      { OP_Ne,         2, ADDR(8),  1},
      { OP_Delete,     0, 0,        0},
      { OP_Next,       0, ADDR(1),  0}, /* 8 */
    };

    sqlite3BeginWriteOperation(pParse, 0, iDb);
    sqlite3OpenMasterTable(pParse, iDb);
    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
    sqlite3ChangeCookie(pParse, iDb);
    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
    if( pParse->nMem<3 ){
      pParse->nMem = 3;
    }
  }
}

/*
** Remove a trigger from the hash tables of the sqlite* pointer.
*/
void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
  Trigger *pTrigger;
  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  if( ALWAYS(pTrigger) ){
    if( pTrigger->pSchema==pTrigger->pTabSchema ){
      Table *pTab = tableOfTrigger(pTrigger);
      Trigger **pp;
      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
      *pp = (*pp)->pNext;
    }
    sqlite3DeleteTrigger(db, pTrigger);
    db->flags |= SQLITE_InternChanges;
  }
}

/*
** pEList is the SET clause of an UPDATE statement.  Each entry
** in pEList is of the format <id>=<expr>.  If any of the entries
** in pEList have an <id> which matches an identifier in pIdList,
** then return TRUE.  If pIdList==NULL, then it is considered a
** wildcard that matches anything.  Likewise if pEList==NULL then
** it matches anything so always return true.  Return false only
** if there is no match.
*/
static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  int e;
  if( pIdList==0 || NEVER(pEList==0) ) return 1;
  for(e=0; e<pEList->nExpr; e++){
    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  }
  return 0; 
}

/*
** Return a list of all triggers on table pTab if there exists at least
** one trigger that must be fired when an operation of type 'op' is 
** performed on the table, and, if that operation is an UPDATE, if at
** least one of the columns in pChanges is being modified.
*/
Trigger *sqlite3TriggersExist(
  Parse *pParse,          /* Parse context */
  Table *pTab,            /* The table the contains the triggers */
  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
){
  int mask = 0;
  Trigger *pList = sqlite3TriggerList(pParse, pTab);
  Trigger *p;
  assert( pList==0 || IsVirtual(pTab)==0 );
  for(p=pList; p; p=p->pNext){
    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
      mask |= p->tr_tm;
    }
  }
  if( pMask ){
    *pMask = mask;
  }
  return (mask ? pList : 0);
}

/*
** Convert the pStep->target token into a SrcList and return a pointer
** to that SrcList.
**
** This routine adds a specific database name, if needed, to the target when
** forming the SrcList.  This prevents a trigger in one database from
** referring to a target in another database.  An exception is when the
** trigger is in TEMP in which case it can refer to any other database it
** wants.
*/
static SrcList *targetSrcList(
  Parse *pParse,       /* The parsing context */
  TriggerStep *pStep   /* The trigger containing the target token */
){
  int iDb;             /* Index of the database to use */
  SrcList *pSrc;       /* SrcList to be returned */

  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  if( pSrc ){
    assert( pSrc->nSrc>0 );
    assert( pSrc->a!=0 );
    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
    if( iDb==0 || iDb>=2 ){
      sqlite3 *db = pParse->db;
      assert( iDb<pParse->db->nDb );
      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
    }
  }
  return pSrc;
}

/*
** Generate VDBE code for the statements inside the body of a single 
** trigger.
*/
static int codeTriggerProgram(
  Parse *pParse,            /* The parser context */
  TriggerStep *pStepList,   /* List of statements inside the trigger body */
  int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
){
  TriggerStep *pStep;
  Vdbe *v = pParse->pVdbe;
  sqlite3 *db = pParse->db;

  assert( pParse->pTriggerTab && pParse->pToplevel );
  assert( pStepList );
  assert( v!=0 );
  for(pStep=pStepList; pStep; pStep=pStep->pNext){
    /* Figure out the ON CONFLICT policy that will be used for this step
    ** of the trigger program. If the statement that caused this trigger
    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
    ** the ON CONFLICT policy that was specified as part of the trigger
    ** step statement. Example:
    **
    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
    **   END;
    **
    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
    */
    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;

    switch( pStep->op ){
      case TK_UPDATE: {
        sqlite3Update(pParse, 
          targetSrcList(pParse, pStep),
          sqlite3ExprListDup(db, pStep->pExprList, 0), 
          sqlite3ExprDup(db, pStep->pWhere, 0), 
          pParse->eOrconf
        );
        break;
      }
      case TK_INSERT: {
        sqlite3Insert(pParse, 
          targetSrcList(pParse, pStep),
          sqlite3ExprListDup(db, pStep->pExprList, 0), 
          sqlite3SelectDup(db, pStep->pSelect, 0), 
          sqlite3IdListDup(db, pStep->pIdList), 
          pParse->eOrconf
        );
        break;
      }
      case TK_DELETE: {
        sqlite3DeleteFrom(pParse, 
          targetSrcList(pParse, pStep),
          sqlite3ExprDup(db, pStep->pWhere, 0)
        );
        break;
      }
      default: assert( pStep->op==TK_SELECT ); {
        SelectDest sDest;
        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
        sqlite3Select(pParse, pSelect, &sDest);
        sqlite3SelectDelete(db, pSelect);
        break;
      }
    } 
    if( pStep->op!=TK_SELECT ){
      sqlite3VdbeAddOp0(v, OP_ResetCount);
    }
  }

  return 0;
}

#ifdef SQLITE_DEBUG
/*
** This function is used to add VdbeComment() annotations to a VDBE
** program. It is not used in production code, only for debugging.
*/
static const char *onErrorText(int onError){
  switch( onError ){
    case OE_Abort:    return "abort";
    case OE_Rollback: return "rollback";
    case OE_Fail:     return "fail";
    case OE_Replace:  return "replace";
    case OE_Ignore:   return "ignore";
    case OE_Default:  return "default";
  }
  return "n/a";
}
#endif

/*
** Parse context structure pFrom has just been used to create a sub-vdbe
** (trigger program). If an error has occurred, transfer error information
** from pFrom to pTo.
*/
static void transferParseError(Parse *pTo, Parse *pFrom){
  assert( pFrom->zErrMsg==0 || pFrom->nErr );
  assert( pTo->zErrMsg==0 || pTo->nErr );
  if( pTo->nErr==0 ){
    pTo->zErrMsg = pFrom->zErrMsg;
    pTo->nErr = pFrom->nErr;
  }else{
    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  }
}

/*
** Create and populate a new TriggerPrg object with a sub-program 
** implementing trigger pTrigger with ON CONFLICT policy orconf.
*/
static TriggerPrg *codeRowTrigger(
  Parse *pParse,       /* Current parse context */
  Trigger *pTrigger,   /* Trigger to code */
  Table *pTab,         /* The table pTrigger is attached to */
  int orconf           /* ON CONFLICT policy to code trigger program with */
){
  Parse *pTop = sqlite3ParseToplevel(pParse);
  sqlite3 *db = pParse->db;   /* Database handle */
  TriggerPrg *pPrg;           /* Value to return */
  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
  Vdbe *v;                    /* Temporary VM */
  NameContext sNC;            /* Name context for sub-vdbe */
  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
  Parse *pSubParse;           /* Parse context for sub-vdbe */
  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */

  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );

  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
  ** list of the top-level Parse object sooner rather than later.  */
  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  if( !pPrg ) return 0;
  pPrg->pNext = pTop->pTriggerPrg;
  pTop->pTriggerPrg = pPrg;
  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  if( !pProgram ) return 0;
  pProgram->nRef = 1;
  pPrg->pTrigger = pTrigger;
  pPrg->orconf = orconf;
  pPrg->oldmask = 0xffffffff;

  /* Allocate and populate a new Parse context to use for coding the 
  ** trigger sub-program.  */
  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  if( !pSubParse ) return 0;
  memset(&sNC, 0, sizeof(sNC));
  sNC.pParse = pSubParse;
  pSubParse->db = db;
  pSubParse->pTriggerTab = pTab;
  pSubParse->pToplevel = pTop;
  pSubParse->zAuthContext = pTrigger->zName;
  pSubParse->eTriggerOp = pTrigger->op;

  v = sqlite3GetVdbe(pSubParse);
  if( v ){
    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
      pTrigger->zName, onErrorText(orconf),
      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
      pTab->zName
    ));
#ifndef SQLITE_OMIT_TRACE
    sqlite3VdbeChangeP4(v, -1, 
      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
    );
#endif

    /* If one was specified, code the WHEN clause. If it evaluates to false
    ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
    ** OP_Halt inserted at the end of the program.  */
    if( pTrigger->pWhen ){
      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
       && db->mallocFailed==0 
      ){
        iEndTrigger = sqlite3VdbeMakeLabel(v);
        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
      }
      sqlite3ExprDelete(db, pWhen);
    }

    /* Code the trigger program into the sub-vdbe. */
    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);

    /* Insert an OP_Halt at the end of the sub-program. */
    if( iEndTrigger ){
      sqlite3VdbeResolveLabel(v, iEndTrigger);
    }
    sqlite3VdbeAddOp0(v, OP_Halt);
    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));

    transferParseError(pParse, pSubParse);
    if( db->mallocFailed==0 ){
      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
    }
    pProgram->nMem = pSubParse->nMem;
    pProgram->nCsr = pSubParse->nTab;
    pProgram->token = (void *)pTrigger;
    pPrg->oldmask = pSubParse->oldmask;
    sqlite3VdbeDelete(v);
  }

  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  sqlite3StackFree(db, pSubParse);

  return pPrg;
}
    
/*
** Return a pointer to a TriggerPrg object containing the sub-program for
** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
** TriggerPrg object exists, a new object is allocated and populated before
** being returned.
*/
static TriggerPrg *getRowTrigger(
  Parse *pParse,       /* Current parse context */
  Trigger *pTrigger,   /* Trigger to code */
  Table *pTab,         /* The table trigger pTrigger is attached to */
  int orconf           /* ON CONFLICT algorithm. */
){
  Parse *pRoot = sqlite3ParseToplevel(pParse);
  TriggerPrg *pPrg;

  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );

  /* It may be that this trigger has already been coded (or is in the
  ** process of being coded). If this is the case, then an entry with
  ** a matching TriggerPrg.pTrigger field will be present somewhere
  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
  for(pPrg=pRoot->pTriggerPrg; 
      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
      pPrg=pPrg->pNext
  );

  /* If an existing TriggerPrg could not be located, create a new one. */
  if( !pPrg ){
    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  }

  return pPrg;
}

/*
** Generate code for the trigger program associated with trigger p on 
** table pTab. The reg, orconf and ignoreJump parameters passed to this
** function are the same as those described in the header function for
** sqlite3CodeRowTrigger()
*/
void sqlite3CodeRowTriggerDirect(
  Parse *pParse,       /* Parse context */
  Trigger *p,          /* Trigger to code */
  Table *pTab,         /* The table to code triggers from */
  int reg,             /* Reg array containing OLD.* and NEW.* values */
  int orconf,          /* ON CONFLICT policy */
  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
){
  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  TriggerPrg *pPrg;
  pPrg = getRowTrigger(pParse, p, pTab, orconf);
  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );

  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
  ** is a pointer to the sub-vdbe containing the trigger program.  */
  if( pPrg ){
    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
    pPrg->pProgram->nRef++;
    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
    VdbeComment(
        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));

    /* Set the P5 operand of the OP_Program instruction to non-zero if
    ** recursive invocation of this trigger program is disallowed. Recursive
    ** invocation is disallowed if (a) the sub-program is really a trigger,
    ** not a foreign key action, and (b) the flag to enable recursive triggers
    ** is clear.  */
    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
  }
}

/*
** This is called to code the required FOR EACH ROW triggers for an operation
** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
** is given by the op paramater. The tr_tm parameter determines whether the
** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
** parameter pChanges is passed the list of columns being modified.
**
** If there are no triggers that fire at the specified time for the specified
** operation on pTab, this function is a no-op.
**
** The reg argument is the address of the first in an array of registers 
** that contain the values substituted for the new.* and old.* references
** in the trigger program. If N is the number of columns in table pTab
** (a copy of pTab->nCol), then registers are populated as follows:
**
**   Register       Contains
**   ------------------------------------------------------
**   reg+0          OLD.rowid
**   reg+1          OLD.* value of left-most column of pTab
**   ...            ...
**   reg+N          OLD.* value of right-most column of pTab
**   reg+N+1        NEW.rowid
**   reg+N+2        OLD.* value of left-most column of pTab
**   ...            ...
**   reg+N+N+1      NEW.* value of right-most column of pTab
**
** For ON DELETE triggers, the registers containing the NEW.* values will
** never be accessed by the trigger program, so they are not allocated or 
** populated by the caller (there is no data to populate them with anyway). 
** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
** are never accessed, and so are not allocated by the caller. So, for an
** ON INSERT trigger, the value passed to this function as parameter reg
** is not a readable register, although registers (reg+N) through 
** (reg+N+N+1) are.
**
** Parameter orconf is the default conflict resolution algorithm for the
** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
** is the instruction that control should jump to if a trigger program
** raises an IGNORE exception.
*/
void sqlite3CodeRowTrigger(
  Parse *pParse,       /* Parse context */
  Trigger *pTrigger,   /* List of triggers on table pTab */
  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  Table *pTab,         /* The table to code triggers from */
  int reg,             /* The first in an array of registers (see above) */
  int orconf,          /* ON CONFLICT policy */
  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
){
  Trigger *p;          /* Used to iterate through pTrigger list */

  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  assert( (op==TK_UPDATE)==(pChanges!=0) );

  for(p=pTrigger; p; p=p->pNext){

    /* Sanity checking:  The schema for the trigger and for the table are
    ** always defined.  The trigger must be in the same schema as the table
    ** or else it must be a TEMP trigger. */
    assert( p->pSchema!=0 );
    assert( p->pTabSchema!=0 );
    assert( p->pSchema==p->pTabSchema 
         || p->pSchema==pParse->db->aDb[1].pSchema );

    /* Determine whether we should code this trigger */
    if( p->op==op 
     && p->tr_tm==tr_tm 
     && checkColumnOverlap(p->pColumns, pChanges)
    ){
      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
    }
  }
}

/*
** Triggers fired by UPDATE or DELETE statements may access values stored
** in the old.* pseudo-table. This function returns a 32-bit bitmask
** indicating which columns of the old.* table actually are used by
** triggers. This information may be used by the caller to avoid having
** to load the entire old.* record into memory when executing an UPDATE
** or DELETE command.
**
** Bit 0 of the returned mask is set if the left-most column of the
** table may be accessed using an old.<col> reference. Bit 1 is set if
** the second leftmost column value is required, and so on. If there
** are more than 32 columns in the table, and at least one of the columns
** with an index greater than 32 may be accessed, 0xffffffff is returned.
**
** It is not possible to determine if the old.rowid column is accessed
** by triggers. The caller must always assume that it is.
**
** There is no equivalent function for new.* references.
*/
u32 sqlite3TriggerOldmask(
  Parse *pParse,       /* Parse context */
  Trigger *pTrigger,   /* List of triggers on table pTab */
  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
  Table *pTab,         /* The table to code triggers from */
  int orconf           /* Default ON CONFLICT policy for trigger steps */
){
  const int op = pChanges ? TK_UPDATE : TK_DELETE;
  u32 mask = 0;
  Trigger *p;

  for(p=pTrigger; p; p=p->pNext){
    if( p->op==op && checkColumnOverlap(p->pColumns,pChanges) ){
      TriggerPrg *pPrg;
      pPrg = getRowTrigger(pParse, p, pTab, orconf);
      if( pPrg ){
        mask |= pPrg->oldmask;
      }
    }
  }

  return mask;
}

#endif /* !defined(SQLITE_OMIT_TRIGGER) */

Added src/update.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle UPDATE statements.
**
** $Id: update.c,v 1.207 2009/08/08 18:01:08 drh Exp $
*/
#include "sqliteInt.h"

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Forward declaration */
static void updateVirtualTable(
  Parse *pParse,       /* The parsing context */
  SrcList *pSrc,       /* The virtual table to be modified */
  Table *pTab,         /* The virtual table */
  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
  Expr *pWhere         /* WHERE clause of the UPDATE statement */
);
#endif /* SQLITE_OMIT_VIRTUALTABLE */

/*
** The most recently coded instruction was an OP_Column to retrieve the
** i-th column of table pTab. This routine sets the P4 parameter of the 
** OP_Column to the default value, if any.
**
** The default value of a column is specified by a DEFAULT clause in the 
** column definition. This was either supplied by the user when the table
** was created, or added later to the table definition by an ALTER TABLE
** command. If the latter, then the row-records in the table btree on disk
** may not contain a value for the column and the default value, taken
** from the P4 parameter of the OP_Column instruction, is returned instead.
** If the former, then all row-records are guaranteed to include a value
** for the column and the P4 value is not required.
**
** Column definitions created by an ALTER TABLE command may only have 
** literal default values specified: a number, null or a string. (If a more
** complicated default expression value was provided, it is evaluated 
** when the ALTER TABLE is executed and one of the literal values written
** into the sqlite_master table.)
**
** Therefore, the P4 parameter is only required if the default value for
** the column is a literal number, string or null. The sqlite3ValueFromExpr()
** function is capable of transforming these types of expressions into
** sqlite3_value objects.
**
** If parameter iReg is not negative, code an OP_RealAffinity instruction
** on register iReg. This is used when an equivalent integer value is 
** stored in place of an 8-byte floating point value in order to save 
** space.
*/
void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  assert( pTab!=0 );
  if( !pTab->pSelect ){
    sqlite3_value *pValue;
    u8 enc = ENC(sqlite3VdbeDb(v));
    Column *pCol = &pTab->aCol[i];
    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
    assert( i<pTab->nCol );
    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
                         pCol->affinity, &pValue);
    if( pValue ){
      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
    }
#ifndef SQLITE_OMIT_FLOATING_POINT
    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
    }
#endif
  }
}

/*
** Process an UPDATE statement.
**
**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
**          \_______/ \________/     \______/       \________________/
*            onError   pTabList      pChanges             pWhere
*/
void sqlite3Update(
  Parse *pParse,         /* The parser context */
  SrcList *pTabList,     /* The table in which we should change things */
  ExprList *pChanges,    /* Things to be changed */
  Expr *pWhere,          /* The WHERE clause.  May be null */
  int onError            /* How to handle constraint errors */
){
  int i, j;              /* Loop counters */
  Table *pTab;           /* The table to be updated */
  int addr = 0;          /* VDBE instruction address of the start of the loop */
  WhereInfo *pWInfo;     /* Information about the WHERE clause */
  Vdbe *v;               /* The virtual database engine */
  Index *pIdx;           /* For looping over indices */
  int nIdx;              /* Number of indices that need updating */
  int iCur;              /* VDBE Cursor number of pTab */
  sqlite3 *db;           /* The database structure */
  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
                         ** an expression for the i-th column of the table.
                         ** aXRef[i]==-1 if the i-th column is not changed. */
  int chngRowid;         /* True if the record number is being changed */
  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
  int openAll = 0;       /* True if all indices need to be opened */
  AuthContext sContext;  /* The authorization context */
  NameContext sNC;       /* The name-context to resolve expressions in */
  int iDb;               /* Database containing the table being updated */
  int j1;                /* Addresses of jump instructions */
  int okOnePass;         /* True for one-pass algorithm without the FIFO */
  int hasFK;             /* True if foreign key processing is required */

#ifndef SQLITE_OMIT_TRIGGER
  int isView;                  /* Trying to update a view */
  Trigger *pTrigger;           /* List of triggers on pTab, if required */
#endif

  /* Register Allocations */
  int regRowCount = 0;   /* A count of rows changed */
  int regOldRowid;       /* The old rowid */
  int regNewRowid;       /* The new rowid */
  int regNew;
  int regOld = 0;
  int regRowSet = 0;     /* Rowset of rows to be updated */
  int regRec;            /* Register used for new table record to insert */

  memset(&sContext, 0, sizeof(sContext));
  db = pParse->db;
  if( pParse->nErr || db->mallocFailed ){
    goto update_cleanup;
  }
  assert( pTabList->nSrc==1 );

  /* Locate the table which we want to update. 
  */
  pTab = sqlite3SrcListLookup(pParse, pTabList);
  if( pTab==0 ) goto update_cleanup;
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);

  /* Figure out if we have any triggers and if the table being
  ** updated is a view.
  */
#ifndef SQLITE_OMIT_TRIGGER
  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, 0);
  isView = pTab->pSelect!=0;
#else
# define pTrigger 0
# define isView 0
#endif
#ifdef SQLITE_OMIT_VIEW
# undef isView
# define isView 0
#endif

  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto update_cleanup;
  }
  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
    goto update_cleanup;
  }
  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  if( aXRef==0 ) goto update_cleanup;
  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;

  /* Allocate a cursors for the main database table and for all indices.
  ** The index cursors might not be used, but if they are used they
  ** need to occur right after the database cursor.  So go ahead and
  ** allocate enough space, just in case.
  */
  pTabList->a[0].iCursor = iCur = pParse->nTab++;
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
    pParse->nTab++;
  }

  /* Initialize the name-context */
  memset(&sNC, 0, sizeof(sNC));
  sNC.pParse = pParse;
  sNC.pSrcList = pTabList;

  /* Resolve the column names in all the expressions of the
  ** of the UPDATE statement.  Also find the column index
  ** for each column to be updated in the pChanges array.  For each
  ** column to be updated, make sure we have authorization to change
  ** that column.
  */
  chngRowid = 0;
  for(i=0; i<pChanges->nExpr; i++){
    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
      goto update_cleanup;
    }
    for(j=0; j<pTab->nCol; j++){
      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
        if( j==pTab->iPKey ){
          chngRowid = 1;
          pRowidExpr = pChanges->a[i].pExpr;
        }
        aXRef[j] = i;
        break;
      }
    }
    if( j>=pTab->nCol ){
      if( sqlite3IsRowid(pChanges->a[i].zName) ){
        chngRowid = 1;
        pRowidExpr = pChanges->a[i].pExpr;
      }else{
        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
        goto update_cleanup;
      }
    }
#ifndef SQLITE_OMIT_AUTHORIZATION
    {
      int rc;
      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
                           pTab->aCol[j].zName, db->aDb[iDb].zName);
      if( rc==SQLITE_DENY ){
        goto update_cleanup;
      }else if( rc==SQLITE_IGNORE ){
        aXRef[j] = -1;
      }
    }
#endif
  }

  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);

  /* Allocate memory for the array aRegIdx[].  There is one entry in the
  ** array for each index associated with table being updated.  Fill in
  ** the value with a register number for indices that are to be used
  ** and with zero for unused indices.
  */
  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  if( nIdx>0 ){
    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
    if( aRegIdx==0 ) goto update_cleanup;
  }
  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
    int reg;
    if( chngRowid ){
      reg = ++pParse->nMem;
    }else{
      reg = 0;
      for(i=0; i<pIdx->nColumn; i++){
        if( aXRef[pIdx->aiColumn[i]]>=0 ){
          reg = ++pParse->nMem;
          break;
        }
      }
    }
    aRegIdx[j] = reg;
  }

  /* Begin generating code. */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ) goto update_cleanup;
  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  sqlite3BeginWriteOperation(pParse, 1, iDb);

#ifndef SQLITE_OMIT_VIRTUALTABLE
  /* Virtual tables must be handled separately */
  if( IsVirtual(pTab) ){
    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
                       pWhere);
    pWhere = 0;
    pTabList = 0;
    goto update_cleanup;
  }
#endif

  /* Allocate required registers. */
  regOldRowid = regNewRowid = ++pParse->nMem;
  if( pTrigger || hasFK ){
    regOld = pParse->nMem + 1;
    pParse->nMem += pTab->nCol;
  }
  if( chngRowid || pTrigger || hasFK ){
    regNewRowid = ++pParse->nMem;
  }
  regNew = pParse->nMem + 1;
  pParse->nMem += pTab->nCol;
  regRec = ++pParse->nMem;

  /* Start the view context. */
  if( isView ){
    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  }

  /* If we are trying to update a view, realize that view into
  ** a ephemeral table.
  */
#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  if( isView ){
    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  }
#endif

  /* Resolve the column names in all the expressions in the
  ** WHERE clause.
  */
  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
    goto update_cleanup;
  }

  /* Begin the database scan
  */
  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
  if( pWInfo==0 ) goto update_cleanup;
  okOnePass = pWInfo->okOnePass;

  /* Remember the rowid of every item to be updated.
  */
  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  if( !okOnePass ){
    regRowSet = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  }

  /* End the database scan loop.
  */
  sqlite3WhereEnd(pWInfo);

  /* Initialize the count of updated rows
  */
  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
    regRowCount = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  }

  if( !isView ){
    /* 
    ** Open every index that needs updating.  Note that if any
    ** index could potentially invoke a REPLACE conflict resolution 
    ** action, then we need to open all indices because we might need
    ** to be deleting some records.
    */
    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
    if( onError==OE_Replace ){
      openAll = 1;
    }else{
      openAll = 0;
      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
        if( pIdx->onError==OE_Replace ){
          openAll = 1;
          break;
        }
      }
    }
    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
      if( openAll || aRegIdx[i]>0 ){
        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
                       (char*)pKey, P4_KEYINFO_HANDOFF);
        assert( pParse->nTab>iCur+i+1 );
      }
    }
  }

  /* Top of the update loop */
  if( okOnePass ){
    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
    addr = sqlite3VdbeAddOp0(v, OP_Goto);
    sqlite3VdbeJumpHere(v, a1);
  }else{
    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  }

  /* Make cursor iCur point to the record that is being updated. If
  ** this record does not exist for some reason (deleted by a trigger,
  ** for example, then jump to the next iteration of the RowSet loop.  */
  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

  /* If the record number will change, set register regNewRowid to
  ** contain the new value. If the record number is not being modified,
  ** then regNewRowid is the same register as regOldRowid, which is
  ** already populated.  */
  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  if( chngRowid ){
    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  }

  /* If there are triggers on this table, populate an array of registers 
  ** with the required old.* column data.  */
  if( hasFK || pTrigger ){
    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
    oldmask |= sqlite3TriggerOldmask(pParse, pTrigger, pChanges, pTab, onError);
    for(i=0; i<pTab->nCol; i++){
      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
        sqlite3ColumnDefault(v, pTab, i, regOld+i);
      }else{
        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
      }
    }
    if( chngRowid==0 ){
      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
    }
  }

  /* Populate the array of registers beginning at regNew with the new
  ** row data. This array is used to check constaints, create the new
  ** table and index records, and as the values for any new.* references
  ** made by triggers.  */
  for(i=0; i<pTab->nCol; i++){
    if( i==pTab->iPKey ){
      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
    }else{
      j = aXRef[i];
      if( j<0 ){
        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
        sqlite3ColumnDefault(v, pTab, i, regNew+i);
      }else{
        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
      }
    }
  }

  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  ** verified. One could argue that this is wrong.  */
  if( pTrigger ){
    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
    sqlite3TableAffinityStr(v, pTab);
    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);

    /* The row-trigger may have deleted the row being updated. In this
    ** case, jump to the next row. No updates or AFTER triggers are 
    ** required. This behaviour - what happens when the row being updated
    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
    ** documentation.  */
    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  }

  if( !isView ){

    /* Do constraint checks. */
    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);

    /* Do FK constraint checks. */
    if( hasFK ){
      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
    }

    /* Delete the index entries associated with the current record.  */
    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  
    /* If changing the record number, delete the old record.  */
    if( hasFK || chngRowid ){
      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
    }
    sqlite3VdbeJumpHere(v, j1);

    if( hasFK ){
      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
    }
  
    /* Insert the new index entries and the new record. */
    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);

    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
    ** handle rows (possibly in other tables) that refer via a foreign key
    ** to the row just updated. */ 
    if( hasFK ){
      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
    }
  }

  /* Increment the row counter 
  */
  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  }

  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);

  /* Repeat the above with the next record to be updated, until
  ** all record selected by the WHERE clause have been updated.
  */
  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  sqlite3VdbeJumpHere(v, addr);

  /* Close all tables */
  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
    if( openAll || aRegIdx[i]>0 ){
      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
    }
  }
  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);

  /* Update the sqlite_sequence table by storing the content of the
  ** maximum rowid counter values recorded while inserting into
  ** autoincrement tables.
  */
  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
    sqlite3AutoincrementEnd(pParse);
  }

  /*
  ** Return the number of rows that were changed. If this routine is 
  ** generating code because of a call to sqlite3NestedParse(), do not
  ** invoke the callback function.
  */
  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  }

update_cleanup:
  sqlite3AuthContextPop(&sContext);
  sqlite3DbFree(db, aRegIdx);
  sqlite3DbFree(db, aXRef);
  sqlite3SrcListDelete(db, pTabList);
  sqlite3ExprListDelete(db, pChanges);
  sqlite3ExprDelete(db, pWhere);
  return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation).  */
#ifdef isView
 #undef isView
#endif
#ifdef pTrigger
 #undef pTrigger
#endif

#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Generate code for an UPDATE of a virtual table.
**
** The strategy is that we create an ephemerial table that contains
** for each row to be changed:
**
**   (A)  The original rowid of that row.
**   (B)  The revised rowid for the row. (note1)
**   (C)  The content of every column in the row.
**
** Then we loop over this ephemeral table and for each row in
** the ephermeral table call VUpdate.
**
** When finished, drop the ephemeral table.
**
** (note1) Actually, if we know in advance that (A) is always the same
** as (B) we only store (A), then duplicate (A) when pulling
** it out of the ephemeral table before calling VUpdate.
*/
static void updateVirtualTable(
  Parse *pParse,       /* The parsing context */
  SrcList *pSrc,       /* The virtual table to be modified */
  Table *pTab,         /* The virtual table */
  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
  Expr *pRowid,        /* Expression used to recompute the rowid */
  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
  Expr *pWhere         /* WHERE clause of the UPDATE statement */
){
  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
  ExprList *pEList = 0;     /* The result set of the SELECT statement */
  Select *pSelect = 0;      /* The SELECT statement */
  Expr *pExpr;              /* Temporary expression */
  int ephemTab;             /* Table holding the result of the SELECT */
  int i;                    /* Loop counter */
  int addr;                 /* Address of top of loop */
  int iReg;                 /* First register in set passed to OP_VUpdate */
  sqlite3 *db = pParse->db; /* Database connection */
  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  SelectDest dest;

  /* Construct the SELECT statement that will find the new values for
  ** all updated rows. 
  */
  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  if( pRowid ){
    pEList = sqlite3ExprListAppend(pParse, pEList,
                                   sqlite3ExprDup(db, pRowid, 0));
  }
  assert( pTab->iPKey<0 );
  for(i=0; i<pTab->nCol; i++){
    if( aXRef[i]>=0 ){
      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
    }else{
      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
    }
    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  }
  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  
  /* Create the ephemeral table into which the update results will
  ** be stored.
  */
  assert( v );
  ephemTab = pParse->nTab++;
  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));

  /* fill the ephemeral table 
  */
  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  sqlite3Select(pParse, pSelect, &dest);

  /* Generate code to scan the ephemeral table and call VUpdate. */
  iReg = ++pParse->nMem;
  pParse->nMem += pTab->nCol+1;
  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  for(i=0; i<pTab->nCol; i++){
    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  }
  sqlite3VtabMakeWritable(pParse, pTab);
  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  sqlite3MayAbort(pParse);
  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  sqlite3VdbeJumpHere(v, addr);
  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);

  /* Cleanup */
  sqlite3SelectDelete(db, pSelect);  
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

Added src/utf.c.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/*
** 2004 April 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used to translate between UTF-8, 
** UTF-16, UTF-16BE, and UTF-16LE.
**
** $Id: utf.c,v 1.73 2009/04/01 18:40:32 drh Exp $
**
** Notes on UTF-8:
**
**   Byte-0    Byte-1    Byte-2    Byte-3    Value
**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
**
**
** Notes on UTF-16:  (with wwww+1==uuuuu)
**
**      Word-0               Word-1          Value
**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
**
**
** BOM or Byte Order Mark:
**     0xff 0xfe   little-endian utf-16 follows
**     0xfe 0xff   big-endian utf-16 follows
**
*/
#include "sqliteInt.h"
#include <assert.h>
#include "vdbeInt.h"

#ifndef SQLITE_AMALGAMATION
/*
** The following constant value is used by the SQLITE_BIGENDIAN and
** SQLITE_LITTLEENDIAN macros.
*/
const int sqlite3one = 1;
#endif /* SQLITE_AMALGAMATION */

/*
** This lookup table is used to help decode the first byte of
** a multi-byte UTF8 character.
*/
static const unsigned char sqlite3Utf8Trans1[] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
};


#define WRITE_UTF8(zOut, c) {                          \
  if( c<0x00080 ){                                     \
    *zOut++ = (u8)(c&0xFF);                            \
  }                                                    \
  else if( c<0x00800 ){                                \
    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
  }                                                    \
  else if( c<0x10000 ){                                \
    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
  }else{                                               \
    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
  }                                                    \
}

#define WRITE_UTF16LE(zOut, c) {                                    \
  if( c<=0xFFFF ){                                                  \
    *zOut++ = (u8)(c&0x00FF);                                       \
    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
  }else{                                                            \
    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
    *zOut++ = (u8)(c&0x00FF);                                       \
    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
  }                                                                 \
}

#define WRITE_UTF16BE(zOut, c) {                                    \
  if( c<=0xFFFF ){                                                  \
    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
    *zOut++ = (u8)(c&0x00FF);                                       \
  }else{                                                            \
    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
    *zOut++ = (u8)(c&0x00FF);                                       \
  }                                                                 \
}

#define READ_UTF16LE(zIn, TERM, c){                                   \
  c = (*zIn++);                                                       \
  c += ((*zIn++)<<8);                                                 \
  if( c>=0xD800 && c<0xE000 && TERM ){                                \
    int c2 = (*zIn++);                                                \
    c2 += ((*zIn++)<<8);                                              \
    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
  }                                                                   \
}

#define READ_UTF16BE(zIn, TERM, c){                                   \
  c = ((*zIn++)<<8);                                                  \
  c += (*zIn++);                                                      \
  if( c>=0xD800 && c<0xE000 && TERM ){                                \
    int c2 = ((*zIn++)<<8);                                           \
    c2 += (*zIn++);                                                   \
    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
  }                                                                   \
}

/*
** Translate a single UTF-8 character.  Return the unicode value.
**
** During translation, assume that the byte that zTerm points
** is a 0x00.
**
** Write a pointer to the next unread byte back into *pzNext.
**
** Notes On Invalid UTF-8:
**
**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
**     be encoded as a multi-byte character.  Any multi-byte character that
**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
**
**  *  This routine never allows a UTF16 surrogate value to be encoded.
**     If a multi-byte character attempts to encode a value between
**     0xd800 and 0xe000 then it is rendered as 0xfffd.
**
**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
**     byte of a character are interpreted as single-byte characters
**     and rendered as themselves even though they are technically
**     invalid characters.
**
**  *  This routine accepts an infinite number of different UTF8 encodings
**     for unicode values 0x80 and greater.  It do not change over-length
**     encodings to 0xfffd as some systems recommend.
*/
#define READ_UTF8(zIn, zTerm, c)                           \
  c = *(zIn++);                                            \
  if( c>=0xc0 ){                                           \
    c = sqlite3Utf8Trans1[c-0xc0];                         \
    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
      c = (c<<6) + (0x3f & *(zIn++));                      \
    }                                                      \
    if( c<0x80                                             \
        || (c&0xFFFFF800)==0xD800                          \
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
  }
int sqlite3Utf8Read(
  const unsigned char *zIn,       /* First byte of UTF-8 character */
  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
){
  int c;

  /* Same as READ_UTF8() above but without the zTerm parameter.
  ** For this routine, we assume the UTF8 string is always zero-terminated.
  */
  c = *(zIn++);
  if( c>=0xc0 ){
    c = sqlite3Utf8Trans1[c-0xc0];
    while( (*zIn & 0xc0)==0x80 ){
      c = (c<<6) + (0x3f & *(zIn++));
    }
    if( c<0x80
        || (c&0xFFFFF800)==0xD800
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
  }
  *pzNext = zIn;
  return c;
}




/*
** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
*/ 
/* #define TRANSLATE_TRACE 1 */

#ifndef SQLITE_OMIT_UTF16
/*
** This routine transforms the internal text encoding used by pMem to
** desiredEnc. It is an error if the string is already of the desired
** encoding, or if *pMem does not contain a string value.
*/
int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  int len;                    /* Maximum length of output string in bytes */
  unsigned char *zOut;                  /* Output buffer */
  unsigned char *zIn;                   /* Input iterator */
  unsigned char *zTerm;                 /* End of input */
  unsigned char *z;                     /* Output iterator */
  unsigned int c;

  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( pMem->flags&MEM_Str );
  assert( pMem->enc!=desiredEnc );
  assert( pMem->enc!=0 );
  assert( pMem->n>=0 );

#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  {
    char zBuf[100];
    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
    fprintf(stderr, "INPUT:  %s\n", zBuf);
  }
#endif

  /* If the translation is between UTF-16 little and big endian, then 
  ** all that is required is to swap the byte order. This case is handled
  ** differently from the others.
  */
  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
    u8 temp;
    int rc;
    rc = sqlite3VdbeMemMakeWriteable(pMem);
    if( rc!=SQLITE_OK ){
      assert( rc==SQLITE_NOMEM );
      return SQLITE_NOMEM;
    }
    zIn = (u8*)pMem->z;
    zTerm = &zIn[pMem->n&~1];
    while( zIn<zTerm ){
      temp = *zIn;
      *zIn = *(zIn+1);
      zIn++;
      *zIn++ = temp;
    }
    pMem->enc = desiredEnc;
    goto translate_out;
  }

  /* Set len to the maximum number of bytes required in the output buffer. */
  if( desiredEnc==SQLITE_UTF8 ){
    /* When converting from UTF-16, the maximum growth results from
    ** translating a 2-byte character to a 4-byte UTF-8 character.
    ** A single byte is required for the output string
    ** nul-terminator.
    */
    pMem->n &= ~1;
    len = pMem->n * 2 + 1;
  }else{
    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
    ** character. Two bytes are required in the output buffer for the
    ** nul-terminator.
    */
    len = pMem->n * 2 + 2;
  }

  /* Set zIn to point at the start of the input buffer and zTerm to point 1
  ** byte past the end.
  **
  ** Variable zOut is set to point at the output buffer, space obtained
  ** from sqlite3_malloc().
  */
  zIn = (u8*)pMem->z;
  zTerm = &zIn[pMem->n];
  zOut = sqlite3DbMallocRaw(pMem->db, len);
  if( !zOut ){
    return SQLITE_NOMEM;
  }
  z = zOut;

  if( pMem->enc==SQLITE_UTF8 ){
    if( desiredEnc==SQLITE_UTF16LE ){
      /* UTF-8 -> UTF-16 Little-endian */
      while( zIn<zTerm ){
        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
        READ_UTF8(zIn, zTerm, c);
        WRITE_UTF16LE(z, c);
      }
    }else{
      assert( desiredEnc==SQLITE_UTF16BE );
      /* UTF-8 -> UTF-16 Big-endian */
      while( zIn<zTerm ){
        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
        READ_UTF8(zIn, zTerm, c);
        WRITE_UTF16BE(z, c);
      }
    }
    pMem->n = (int)(z - zOut);
    *z++ = 0;
  }else{
    assert( desiredEnc==SQLITE_UTF8 );
    if( pMem->enc==SQLITE_UTF16LE ){
      /* UTF-16 Little-endian -> UTF-8 */
      while( zIn<zTerm ){
        READ_UTF16LE(zIn, zIn<zTerm, c); 
        WRITE_UTF8(z, c);
      }
    }else{
      /* UTF-16 Big-endian -> UTF-8 */
      while( zIn<zTerm ){
        READ_UTF16BE(zIn, zIn<zTerm, c); 
        WRITE_UTF8(z, c);
      }
    }
    pMem->n = (int)(z - zOut);
  }
  *z = 0;
  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );

  sqlite3VdbeMemRelease(pMem);
  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  pMem->enc = desiredEnc;
  pMem->flags |= (MEM_Term|MEM_Dyn);
  pMem->z = (char*)zOut;
  pMem->zMalloc = pMem->z;

translate_out:
#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  {
    char zBuf[100];
    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
    fprintf(stderr, "OUTPUT: %s\n", zBuf);
  }
#endif
  return SQLITE_OK;
}

/*
** This routine checks for a byte-order mark at the beginning of the 
** UTF-16 string stored in *pMem. If one is present, it is removed and
** the encoding of the Mem adjusted. This routine does not do any
** byte-swapping, it just sets Mem.enc appropriately.
**
** The allocation (static, dynamic etc.) and encoding of the Mem may be
** changed by this function.
*/
int sqlite3VdbeMemHandleBom(Mem *pMem){
  int rc = SQLITE_OK;
  u8 bom = 0;

  assert( pMem->n>=0 );
  if( pMem->n>1 ){
    u8 b1 = *(u8 *)pMem->z;
    u8 b2 = *(((u8 *)pMem->z) + 1);
    if( b1==0xFE && b2==0xFF ){
      bom = SQLITE_UTF16BE;
    }
    if( b1==0xFF && b2==0xFE ){
      bom = SQLITE_UTF16LE;
    }
  }
  
  if( bom ){
    rc = sqlite3VdbeMemMakeWriteable(pMem);
    if( rc==SQLITE_OK ){
      pMem->n -= 2;
      memmove(pMem->z, &pMem->z[2], pMem->n);
      pMem->z[pMem->n] = '\0';
      pMem->z[pMem->n+1] = '\0';
      pMem->flags |= MEM_Term;
      pMem->enc = bom;
    }
  }
  return rc;
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
** return the number of unicode characters in pZ up to (but not including)
** the first 0x00 byte. If nByte is not less than zero, return the
** number of unicode characters in the first nByte of pZ (or up to 
** the first 0x00, whichever comes first).
*/
int sqlite3Utf8CharLen(const char *zIn, int nByte){
  int r = 0;
  const u8 *z = (const u8*)zIn;
  const u8 *zTerm;
  if( nByte>=0 ){
    zTerm = &z[nByte];
  }else{
    zTerm = (const u8*)(-1);
  }
  assert( z<=zTerm );
  while( *z!=0 && z<zTerm ){
    SQLITE_SKIP_UTF8(z);
    r++;
  }
  return r;
}

/* This test function is not currently used by the automated test-suite. 
** Hence it is only available in debug builds.
*/
#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
/*
** Translate UTF-8 to UTF-8.
**
** This has the effect of making sure that the string is well-formed
** UTF-8.  Miscoded characters are removed.
**
** The translation is done in-place (since it is impossible for the
** correct UTF-8 encoding to be longer than a malformed encoding).
*/
int sqlite3Utf8To8(unsigned char *zIn){
  unsigned char *zOut = zIn;
  unsigned char *zStart = zIn;
  u32 c;

  while( zIn[0] ){
    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
    if( c!=0xfffd ){
      WRITE_UTF8(zOut, c);
    }
  }
  *zOut = 0;
  return (int)(zOut - zStart);
}
#endif

#ifndef SQLITE_OMIT_UTF16
/*
** Convert a UTF-16 string in the native encoding into a UTF-8 string.
** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
** be freed by the calling function.
**
** NULL is returned if there is an allocation error.
*/
char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
  Mem m;
  memset(&m, 0, sizeof(m));
  m.db = db;
  sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  if( db->mallocFailed ){
    sqlite3VdbeMemRelease(&m);
    m.z = 0;
  }
  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
}

/*
** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
** enc. A pointer to the new string is returned, and the value of *pnOut
** is set to the length of the returned string in bytes. The call should
** arrange to call sqlite3DbFree() on the returned pointer when it is
** no longer required.
** 
** If a malloc failure occurs, NULL is returned and the db.mallocFailed
** flag set.
*/
#ifdef SQLITE_ENABLE_STAT2
char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
  Mem m;
  memset(&m, 0, sizeof(m));
  m.db = db;
  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
  if( sqlite3VdbeMemTranslate(&m, enc) ){
    assert( db->mallocFailed );
    return 0;
  }
  assert( m.z==m.zMalloc );
  *pnOut = m.n;
  return m.z;
}
#endif

/*
** zIn is a UTF-16 encoded unicode string at least nChar characters long.
** Return the number of bytes in the first nChar unicode characters
** in pZ.  nChar must be non-negative.
*/
int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  int c;
  unsigned char const *z = zIn;
  int n = 0;
  
  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
    while( n<nChar ){
      READ_UTF16BE(z, 1, c);
      n++;
    }
  }else{
    while( n<nChar ){
      READ_UTF16LE(z, 1, c);
      n++;
    }
  }
  return (int)(z-(unsigned char const *)zIn);
}

#if defined(SQLITE_TEST)
/*
** This routine is called from the TCL test function "translate_selftest".
** It checks that the primitives for serializing and deserializing
** characters in each encoding are inverses of each other.
*/
void sqlite3UtfSelfTest(void){
  unsigned int i, t;
  unsigned char zBuf[20];
  unsigned char *z;
  int n;
  unsigned int c;

  for(i=0; i<0x00110000; i++){
    z = zBuf;
    WRITE_UTF8(z, i);
    n = (int)(z-zBuf);
    assert( n>0 && n<=4 );
    z[0] = 0;
    z = zBuf;
    c = sqlite3Utf8Read(z, (const u8**)&z);
    t = i;
    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
    assert( c==t );
    assert( (z-zBuf)==n );
  }
  for(i=0; i<0x00110000; i++){
    if( i>=0xD800 && i<0xE000 ) continue;
    z = zBuf;
    WRITE_UTF16LE(z, i);
    n = (int)(z-zBuf);
    assert( n>0 && n<=4 );
    z[0] = 0;
    z = zBuf;
    READ_UTF16LE(z, 1, c);
    assert( c==i );
    assert( (z-zBuf)==n );
  }
  for(i=0; i<0x00110000; i++){
    if( i>=0xD800 && i<0xE000 ) continue;
    z = zBuf;
    WRITE_UTF16BE(z, i);
    n = (int)(z-zBuf);
    assert( n>0 && n<=4 );
    z[0] = 0;
    z = zBuf;
    READ_UTF16BE(z, 1, c);
    assert( c==i );
    assert( (z-zBuf)==n );
  }
}
#endif /* SQLITE_TEST */
#endif /* SQLITE_OMIT_UTF16 */

Added src/util.c.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
*/
#include "sqliteInt.h"
#include <stdarg.h>
#ifdef SQLITE_HAVE_ISNAN
# include <math.h>
#endif

/*
** Routine needed to support the testcase() macro.
*/
#ifdef SQLITE_COVERAGE_TEST
void sqlite3Coverage(int x){
  static int dummy = 0;
  dummy += x;
}
#endif

/*
** Return true if the floating point value is Not a Number (NaN).
**
** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
** Otherwise, we have our own implementation that works on most systems.
*/
int sqlite3IsNaN(double x){
  int rc;   /* The value return */
#if !defined(SQLITE_HAVE_ISNAN)
  /*
  ** Systems that support the isnan() library function should probably
  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
  ** found that many systems do not have a working isnan() function so
  ** this implementation is provided as an alternative.
  **
  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  ** On the other hand, the use of -ffast-math comes with the following
  ** warning:
  **
  **      This option [-ffast-math] should never be turned on by any
  **      -O option since it can result in incorrect output for programs
  **      which depend on an exact implementation of IEEE or ISO 
  **      rules/specifications for math functions.
  **
  ** Under MSVC, this NaN test may fail if compiled with a floating-
  ** point precision mode other than /fp:precise.  From the MSDN 
  ** documentation:
  **
  **      The compiler [with /fp:precise] will properly handle comparisons 
  **      involving NaN. For example, x != x evaluates to true if x is NaN 
  **      ...
  */
#ifdef __FAST_MATH__
# error SQLite will not work correctly with the -ffast-math option of GCC.
#endif
  volatile double y = x;
  volatile double z = y;
  rc = (y!=z);
#else  /* if defined(SQLITE_HAVE_ISNAN) */
  rc = isnan(x);
#endif /* SQLITE_HAVE_ISNAN */
  testcase( rc );
  return rc;
}

/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
**
** The value returned will never be negative.  Nor will it ever be greater
** than the actual length of the string.  For very long strings (greater
** than 1GiB) the value returned might be less than the true string length.
*/
int sqlite3Strlen30(const char *z){
  const char *z2 = z;
  if( z==0 ) return 0;
  while( *z2 ){ z2++; }
  return 0x3fffffff & (int)(z2 - z);
}

/*
** Set the most recent error code and error string for the sqlite
** handle "db". The error code is set to "err_code".
**
** If it is not NULL, string zFormat specifies the format of the
** error string in the style of the printf functions: The following
** format characters are allowed:
**
**      %s      Insert a string
**      %z      A string that should be freed after use
**      %d      Insert an integer
**      %T      Insert a token
**      %S      Insert the first element of a SrcList
**
** zFormat and any string tokens that follow it are assumed to be
** encoded in UTF-8.
**
** To clear the most recent error for sqlite handle "db", sqlite3Error
** should be called with err_code set to SQLITE_OK and zFormat set
** to NULL.
*/
void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
    db->errCode = err_code;
    if( zFormat ){
      char *z;
      va_list ap;
      va_start(ap, zFormat);
      z = sqlite3VMPrintf(db, zFormat, ap);
      va_end(ap);
      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
    }else{
      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
    }
  }
}

/*
** Add an error message to pParse->zErrMsg and increment pParse->nErr.
** The following formatting characters are allowed:
**
**      %s      Insert a string
**      %z      A string that should be freed after use
**      %d      Insert an integer
**      %T      Insert a token
**      %S      Insert the first element of a SrcList
**
** This function should be used to report any error that occurs whilst
** compiling an SQL statement (i.e. within sqlite3_prepare()). The
** last thing the sqlite3_prepare() function does is copy the error
** stored by this function into the database handle using sqlite3Error().
** Function sqlite3Error() should be used during statement execution
** (sqlite3_step() etc.).
*/
void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  va_list ap;
  sqlite3 *db = pParse->db;
  pParse->nErr++;
  sqlite3DbFree(db, pParse->zErrMsg);
  va_start(ap, zFormat);
  pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
  va_end(ap);
  pParse->rc = SQLITE_ERROR;
}

/*
** Clear the error message in pParse, if any
*/
void sqlite3ErrorClear(Parse *pParse){
  sqlite3DbFree(pParse->db, pParse->zErrMsg);
  pParse->zErrMsg = 0;
  pParse->nErr = 0;
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** The input string must be zero-terminated.  A new zero-terminator
** is added to the dequoted string.
**
** The return value is -1 if no dequoting occurs or the length of the
** dequoted string, exclusive of the zero terminator, if dequoting does
** occur.
**
** 2002-Feb-14: This routine is extended to remove MS-Access style
** brackets from around identifers.  For example:  "[a-b-c]" becomes
** "a-b-c".
*/
int sqlite3Dequote(char *z){
  char quote;
  int i, j;
  if( z==0 ) return -1;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return -1;
  }
  for(i=1, j=0; ALWAYS(z[i]); i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = quote;
        i++;
      }else{
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
  z[j] = 0;
  return j;
}

/* Convenient short-hand */
#define UpperToLower sqlite3UpperToLower

/*
** Some systems have stricmp().  Others have strcasecmp().  Because
** there is no consistency, we will define our own.
*/
int sqlite3StrICmp(const char *zLeft, const char *zRight){
  register unsigned char *a, *b;
  a = (unsigned char *)zLeft;
  b = (unsigned char *)zRight;
  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  return UpperToLower[*a] - UpperToLower[*b];
}
int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  register unsigned char *a, *b;
  a = (unsigned char *)zLeft;
  b = (unsigned char *)zRight;
  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
}

/*
** Return TRUE if z is a pure numeric string.  Return FALSE and leave
** *realnum unchanged if the string contains any character which is not
** part of a number.
**
** If the string is pure numeric, set *realnum to TRUE if the string
** contains the '.' character or an "E+000" style exponentiation suffix.
** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
** false does not mean that the number can be successfully converted into
** an integer - it might be too big.
**
** An empty string is considered non-numeric.
*/
int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
  int incr = (enc==SQLITE_UTF8?1:2);
  if( enc==SQLITE_UTF16BE ) z++;
  if( *z=='-' || *z=='+' ) z += incr;
  if( !sqlite3Isdigit(*z) ){
    return 0;
  }
  z += incr;
  *realnum = 0;
  while( sqlite3Isdigit(*z) ){ z += incr; }
  if( *z=='.' ){
    z += incr;
    if( !sqlite3Isdigit(*z) ) return 0;
    while( sqlite3Isdigit(*z) ){ z += incr; }
    *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z += incr;
    if( *z=='+' || *z=='-' ) z += incr;
    if( !sqlite3Isdigit(*z) ) return 0;
    while( sqlite3Isdigit(*z) ){ z += incr; }
    *realnum = 1;
  }
  return *z==0;
}

/*
** The string z[] is an ASCII representation of a real number.
** Convert this string to a double.
**
** This routine assumes that z[] really is a valid number.  If it
** is not, the result is undefined.
**
** This routine is used instead of the library atof() function because
** the library atof() might want to use "," as the decimal point instead
** of "." depending on how locale is set.  But that would cause problems
** for SQL.  So this routine always uses "." regardless of locale.
*/
int sqlite3AtoF(const char *z, double *pResult){
#ifndef SQLITE_OMIT_FLOATING_POINT
  const char *zBegin = z;
  /* sign * significand * (10 ^ (esign * exponent)) */
  int sign = 1;   /* sign of significand */
  i64 s = 0;      /* significand */
  int d = 0;      /* adjust exponent for shifting decimal point */
  int esign = 1;  /* sign of exponent */
  int e = 0;      /* exponent */
  double result;
  int nDigits = 0;

  /* skip leading spaces */
  while( sqlite3Isspace(*z) ) z++;
  /* get sign of significand */
  if( *z=='-' ){
    sign = -1;
    z++;
  }else if( *z=='+' ){
    z++;
  }
  /* skip leading zeroes */
  while( z[0]=='0' ) z++, nDigits++;

  /* copy max significant digits to significand */
  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
    s = s*10 + (*z - '0');
    z++, nDigits++;
  }
  /* skip non-significant significand digits
  ** (increase exponent by d to shift decimal left) */
  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;

  /* if decimal point is present */
  if( *z=='.' ){
    z++;
    /* copy digits from after decimal to significand
    ** (decrease exponent by d to shift decimal right) */
    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
      s = s*10 + (*z - '0');
      z++, nDigits++, d--;
    }
    /* skip non-significant digits */
    while( sqlite3Isdigit(*z) ) z++, nDigits++;
  }

  /* if exponent is present */
  if( *z=='e' || *z=='E' ){
    z++;
    /* get sign of exponent */
    if( *z=='-' ){
      esign = -1;
      z++;
    }else if( *z=='+' ){
      z++;
    }
    /* copy digits to exponent */
    while( sqlite3Isdigit(*z) ){
      e = e*10 + (*z - '0');
      z++;
    }
  }

  /* adjust exponent by d, and update sign */
  e = (e*esign) + d;
  if( e<0 ) {
    esign = -1;
    e *= -1;
  } else {
    esign = 1;
  }

  /* if 0 significand */
  if( !s ) {
    /* In the IEEE 754 standard, zero is signed.
    ** Add the sign if we've seen at least one digit */
    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  } else {
    /* attempt to reduce exponent */
    if( esign>0 ){
      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
    }else{
      while( !(s%10) && e>0 ) e--,s/=10;
    }

    /* adjust the sign of significand */
    s = sign<0 ? -s : s;

    /* if exponent, scale significand as appropriate
    ** and store in result. */
    if( e ){
      double scale = 1.0;
      /* attempt to handle extremely small/large numbers better */
      if( e>307 && e<342 ){
        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
        if( esign<0 ){
          result = s / scale;
          result /= 1.0e+308;
        }else{
          result = s * scale;
          result *= 1.0e+308;
        }
      }else{
        /* 1.0e+22 is the largest power of 10 than can be 
        ** represented exactly. */
        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
        if( esign<0 ){
          result = s / scale;
        }else{
          result = s * scale;
        }
      }
    } else {
      result = (double)s;
    }
  }

  /* store the result */
  *pResult = result;

  /* return number of characters used */
  return (int)(z - zBegin);
#else
  return sqlite3Atoi64(z, pResult);
#endif /* SQLITE_OMIT_FLOATING_POINT */
}

/*
** Compare the 19-character string zNum against the text representation
** value 2^63:  9223372036854775808.  Return negative, zero, or positive
** if zNum is less than, equal to, or greater than the string.
**
** Unlike memcmp() this routine is guaranteed to return the difference
** in the values of the last digit if the only difference is in the
** last digit.  So, for example,
**
**      compare2pow63("9223372036854775800")
**
** will return -8.
*/
static int compare2pow63(const char *zNum){
  int c;
  c = memcmp(zNum,"922337203685477580",18)*10;
  if( c==0 ){
    c = zNum[18] - '8';
  }
  return c;
}


/*
** Return TRUE if zNum is a 64-bit signed integer and write
** the value of the integer into *pNum.  If zNum is not an integer
** or is an integer that is too large to be expressed with 64 bits,
** then return false.
**
** When this routine was originally written it dealt with only
** 32-bit numbers.  At that time, it was much faster than the
** atoi() library routine in RedHat 7.2.
*/
int sqlite3Atoi64(const char *zNum, i64 *pNum){
  i64 v = 0;
  int neg;
  int i, c;
  const char *zStart;
  while( sqlite3Isspace(*zNum) ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum++;
  }else{
    neg = 0;
  }
  zStart = zNum;
  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
    v = v*10 + c - '0';
  }
  *pNum = neg ? -v : v;
  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
    /* zNum is empty or contains non-numeric text or is longer
    ** than 19 digits (thus guaranting that it is too large) */
    return 0;
  }else if( i<19 ){
    /* Less than 19 digits, so we know that it fits in 64 bits */
    return 1;
  }else{
    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
    ** is 2^63. */
    return compare2pow63(zNum)<neg;
  }
}

/*
** The string zNum represents an unsigned integer.  The zNum string
** consists of one or more digit characters and is terminated by
** a zero character.  Any stray characters in zNum result in undefined
** behavior.
**
** If the unsigned integer that zNum represents will fit in a
** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
**
** If the negFlag parameter is true, that means that zNum really represents
** a negative number.  (The leading "-" is omitted from zNum.)  This
** parameter is needed to determine a boundary case.  A string
** of "9223373036854775808" returns false if negFlag is false or true
** if negFlag is true.
**
** Leading zeros are ignored.
*/
int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
  int i;
  int neg = 0;

  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */

  if( negFlag ) neg = 1-neg;
  while( *zNum=='0' ){
    zNum++;   /* Skip leading zeros.  Ticket #2454 */
  }
  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
  if( i<19 ){
    /* Guaranteed to fit if less than 19 digits */
    return 1;
  }else if( i>19 ){
    /* Guaranteed to be too big if greater than 19 digits */
    return 0;
  }else{
    /* Compare against 2^63. */
    return compare2pow63(zNum)<neg;
  }
}

/*
** If zNum represents an integer that will fit in 32-bits, then set
** *pValue to that integer and return true.  Otherwise return false.
**
** Any non-numeric characters that following zNum are ignored.
** This is different from sqlite3Atoi64() which requires the
** input number to be zero-terminated.
*/
int sqlite3GetInt32(const char *zNum, int *pValue){
  sqlite_int64 v = 0;
  int i, c;
  int neg = 0;
  if( zNum[0]=='-' ){
    neg = 1;
    zNum++;
  }else if( zNum[0]=='+' ){
    zNum++;
  }
  while( zNum[0]=='0' ) zNum++;
  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
    v = v*10 + c;
  }

  /* The longest decimal representation of a 32 bit integer is 10 digits:
  **
  **             1234567890
  **     2^31 -> 2147483648
  */
  if( i>10 ){
    return 0;
  }
  if( v-neg>2147483647 ){
    return 0;
  }
  if( neg ){
    v = -v;
  }
  *pValue = (int)v;
  return 1;
}

/*
** The variable-length integer encoding is as follows:
**
** KEY:
**         A = 0xxxxxxx    7 bits of data and one flag bit
**         B = 1xxxxxxx    7 bits of data and one flag bit
**         C = xxxxxxxx    8 bits of data
**
**  7 bits - A
** 14 bits - BA
** 21 bits - BBA
** 28 bits - BBBA
** 35 bits - BBBBA
** 42 bits - BBBBBA
** 49 bits - BBBBBBA
** 56 bits - BBBBBBBA
** 64 bits - BBBBBBBBC
*/

/*
** Write a 64-bit variable-length integer to memory starting at p[0].
** The length of data write will be between 1 and 9 bytes.  The number
** of bytes written is returned.
**
** A variable-length integer consists of the lower 7 bits of each byte
** for all bytes that have the 8th bit set and one byte with the 8th
** bit clear.  Except, if we get to the 9th byte, it stores the full
** 8 bits and is the last byte.
*/
int sqlite3PutVarint(unsigned char *p, u64 v){
  int i, j, n;
  u8 buf[10];
  if( v & (((u64)0xff000000)<<32) ){
    p[8] = (u8)v;
    v >>= 8;
    for(i=7; i>=0; i--){
      p[i] = (u8)((v & 0x7f) | 0x80);
      v >>= 7;
    }
    return 9;
  }    
  n = 0;
  do{
    buf[n++] = (u8)((v & 0x7f) | 0x80);
    v >>= 7;
  }while( v!=0 );
  buf[0] &= 0x7f;
  assert( n<=9 );
  for(i=0, j=n-1; j>=0; j--, i++){
    p[i] = buf[j];
  }
  return n;
}

/*
** This routine is a faster version of sqlite3PutVarint() that only
** works for 32-bit positive integers and which is optimized for
** the common case of small integers.  A MACRO version, putVarint32,
** is provided which inlines the single-byte case.  All code should use
** the MACRO version as this function assumes the single-byte case has
** already been handled.
*/
int sqlite3PutVarint32(unsigned char *p, u32 v){
#ifndef putVarint32
  if( (v & ~0x7f)==0 ){
    p[0] = v;
    return 1;
  }
#endif
  if( (v & ~0x3fff)==0 ){
    p[0] = (u8)((v>>7) | 0x80);
    p[1] = (u8)(v & 0x7f);
    return 2;
  }
  return sqlite3PutVarint(p, v);
}

/*
** Read a 64-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read.  The value is stored in *v.
*/
u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  u32 a,b,s;

  a = *p;
  /* a: p0 (unmasked) */
  if (!(a&0x80))
  {
    *v = a;
    return 1;
  }

  p++;
  b = *p;
  /* b: p1 (unmasked) */
  if (!(b&0x80))
  {
    a &= 0x7f;
    a = a<<7;
    a |= b;
    *v = a;
    return 2;
  }

  p++;
  a = a<<14;
  a |= *p;
  /* a: p0<<14 | p2 (unmasked) */
  if (!(a&0x80))
  {
    a &= (0x7f<<14)|(0x7f);
    b &= 0x7f;
    b = b<<7;
    a |= b;
    *v = a;
    return 3;
  }

  /* CSE1 from below */
  a &= (0x7f<<14)|(0x7f);
  p++;
  b = b<<14;
  b |= *p;
  /* b: p1<<14 | p3 (unmasked) */
  if (!(b&0x80))
  {
    b &= (0x7f<<14)|(0x7f);
    /* moved CSE1 up */
    /* a &= (0x7f<<14)|(0x7f); */
    a = a<<7;
    a |= b;
    *v = a;
    return 4;
  }

  /* a: p0<<14 | p2 (masked) */
  /* b: p1<<14 | p3 (unmasked) */
  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  /* moved CSE1 up */
  /* a &= (0x7f<<14)|(0x7f); */
  b &= (0x7f<<14)|(0x7f);
  s = a;
  /* s: p0<<14 | p2 (masked) */

  p++;
  a = a<<14;
  a |= *p;
  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  if (!(a&0x80))
  {
    /* we can skip these cause they were (effectively) done above in calc'ing s */
    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
    /* b &= (0x7f<<14)|(0x7f); */
    b = b<<7;
    a |= b;
    s = s>>18;
    *v = ((u64)s)<<32 | a;
    return 5;
  }

  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  s = s<<7;
  s |= b;
  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */

  p++;
  b = b<<14;
  b |= *p;
  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  if (!(b&0x80))
  {
    /* we can skip this cause it was (effectively) done above in calc'ing s */
    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
    a &= (0x7f<<14)|(0x7f);
    a = a<<7;
    a |= b;
    s = s>>18;
    *v = ((u64)s)<<32 | a;
    return 6;
  }

  p++;
  a = a<<14;
  a |= *p;
  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  if (!(a&0x80))
  {
    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
    b &= (0x7f<<14)|(0x7f);
    b = b<<7;
    a |= b;
    s = s>>11;
    *v = ((u64)s)<<32 | a;
    return 7;
  }

  /* CSE2 from below */
  a &= (0x7f<<14)|(0x7f);
  p++;
  b = b<<14;
  b |= *p;
  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  if (!(b&0x80))
  {
    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
    /* moved CSE2 up */
    /* a &= (0x7f<<14)|(0x7f); */
    a = a<<7;
    a |= b;
    s = s>>4;
    *v = ((u64)s)<<32 | a;
    return 8;
  }

  p++;
  a = a<<15;
  a |= *p;
  /* a: p4<<29 | p6<<15 | p8 (unmasked) */

  /* moved CSE2 up */
  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  b &= (0x7f<<14)|(0x7f);
  b = b<<8;
  a |= b;

  s = s<<4;
  b = p[-4];
  b &= 0x7f;
  b = b>>3;
  s |= b;

  *v = ((u64)s)<<32 | a;

  return 9;
}

/*
** Read a 32-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read.  The value is stored in *v.
**
** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
** integer, then set *v to 0xffffffff.
**
** A MACRO version, getVarint32, is provided which inlines the 
** single-byte case.  All code should use the MACRO version as 
** this function assumes the single-byte case has already been handled.
*/
u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  u32 a,b;

  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
  ** by the getVarin32() macro */
  a = *p;
  /* a: p0 (unmasked) */
#ifndef getVarint32
  if (!(a&0x80))
  {
    /* Values between 0 and 127 */
    *v = a;
    return 1;
  }
#endif

  /* The 2-byte case */
  p++;
  b = *p;
  /* b: p1 (unmasked) */
  if (!(b&0x80))
  {
    /* Values between 128 and 16383 */
    a &= 0x7f;
    a = a<<7;
    *v = a | b;
    return 2;
  }

  /* The 3-byte case */
  p++;
  a = a<<14;
  a |= *p;
  /* a: p0<<14 | p2 (unmasked) */
  if (!(a&0x80))
  {
    /* Values between 16384 and 2097151 */
    a &= (0x7f<<14)|(0x7f);
    b &= 0x7f;
    b = b<<7;
    *v = a | b;
    return 3;
  }

  /* A 32-bit varint is used to store size information in btrees.
  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  ** A 3-byte varint is sufficient, for example, to record the size
  ** of a 1048569-byte BLOB or string.
  **
  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
  ** rare larger cases can be handled by the slower 64-bit varint
  ** routine.
  */
#if 1
  {
    u64 v64;
    u8 n;

    p -= 2;
    n = sqlite3GetVarint(p, &v64);
    assert( n>3 && n<=9 );
    if( (v64 & SQLITE_MAX_U32)!=v64 ){
      *v = 0xffffffff;
    }else{
      *v = (u32)v64;
    }
    return n;
  }

#else
  /* For following code (kept for historical record only) shows an
  ** unrolling for the 3- and 4-byte varint cases.  This code is
  ** slightly faster, but it is also larger and much harder to test.
  */
  p++;
  b = b<<14;
  b |= *p;
  /* b: p1<<14 | p3 (unmasked) */
  if (!(b&0x80))
  {
    /* Values between 2097152 and 268435455 */
    b &= (0x7f<<14)|(0x7f);
    a &= (0x7f<<14)|(0x7f);
    a = a<<7;
    *v = a | b;
    return 4;
  }

  p++;
  a = a<<14;
  a |= *p;
  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  if (!(a&0x80))
  {
    /* Walues  between 268435456 and 34359738367 */
    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
    b = b<<7;
    *v = a | b;
    return 5;
  }

  /* We can only reach this point when reading a corrupt database
  ** file.  In that case we are not in any hurry.  Use the (relatively
  ** slow) general-purpose sqlite3GetVarint() routine to extract the
  ** value. */
  {
    u64 v64;
    u8 n;

    p -= 4;
    n = sqlite3GetVarint(p, &v64);
    assert( n>5 && n<=9 );
    *v = (u32)v64;
    return n;
  }
#endif
}

/*
** Return the number of bytes that will be needed to store the given
** 64-bit integer.
*/
int sqlite3VarintLen(u64 v){
  int i = 0;
  do{
    i++;
    v >>= 7;
  }while( v!=0 && ALWAYS(i<9) );
  return i;
}


/*
** Read or write a four-byte big-endian integer value.
*/
u32 sqlite3Get4byte(const u8 *p){
  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
}
void sqlite3Put4byte(unsigned char *p, u32 v){
  p[0] = (u8)(v>>24);
  p[1] = (u8)(v>>16);
  p[2] = (u8)(v>>8);
  p[3] = (u8)v;
}



#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
/*
** Translate a single byte of Hex into an integer.
** This routine only works if h really is a valid hexadecimal
** character:  0..9a..fA..F
*/
static u8 hexToInt(int h){
  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
#ifdef SQLITE_ASCII
  h += 9*(1&(h>>6));
#endif
#ifdef SQLITE_EBCDIC
  h += 9*(1&~(h>>4));
#endif
  return (u8)(h & 0xf);
}
#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */

#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
/*
** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
** value.  Return a pointer to its binary value.  Space to hold the
** binary value has been obtained from malloc and must be freed by
** the calling routine.
*/
void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  char *zBlob;
  int i;

  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  n--;
  if( zBlob ){
    for(i=0; i<n; i+=2){
      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
    }
    zBlob[i/2] = 0;
  }
  return zBlob;
}
#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */


/*
** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
** when this routine is called.
**
** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
** value indicates that the database connection passed into the API is
** open and is not being used by another thread.  By changing the value
** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
** when the API exits. 
**
** This routine is a attempt to detect if two threads use the
** same sqlite* pointer at the same time.  There is a race 
** condition so it is possible that the error is not detected.
** But usually the problem will be seen.  The result will be an
** error which can be used to debug the application that is
** using SQLite incorrectly.
**
** Ticket #202:  If db->magic is not a valid open value, take care not
** to modify the db structure at all.  It could be that db is a stale
** pointer.  In other words, it could be that there has been a prior
** call to sqlite3_close(db) and db has been deallocated.  And we do
** not want to write into deallocated memory.
*/
#ifdef SQLITE_DEBUG
int sqlite3SafetyOn(sqlite3 *db){
  if( db->magic==SQLITE_MAGIC_OPEN ){
    db->magic = SQLITE_MAGIC_BUSY;
    assert( sqlite3_mutex_held(db->mutex) );
    return 0;
  }else if( db->magic==SQLITE_MAGIC_BUSY ){
    db->magic = SQLITE_MAGIC_ERROR;
    db->u1.isInterrupted = 1;
  }
  return 1;
}
#endif

/*
** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
** when this routine is called.
*/
#ifdef SQLITE_DEBUG
int sqlite3SafetyOff(sqlite3 *db){
  if( db->magic==SQLITE_MAGIC_BUSY ){
    db->magic = SQLITE_MAGIC_OPEN;
    assert( sqlite3_mutex_held(db->mutex) );
    return 0;
  }else{
    db->magic = SQLITE_MAGIC_ERROR;
    db->u1.isInterrupted = 1;
    return 1;
  }
}
#endif

/*
** Check to make sure we have a valid db pointer.  This test is not
** foolproof but it does provide some measure of protection against
** misuse of the interface such as passing in db pointers that are
** NULL or which have been previously closed.  If this routine returns
** 1 it means that the db pointer is valid and 0 if it should not be
** dereferenced for any reason.  The calling function should invoke
** SQLITE_MISUSE immediately.
**
** sqlite3SafetyCheckOk() requires that the db pointer be valid for
** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
** open properly and is not fit for general use but which can be
** used as an argument to sqlite3_errmsg() or sqlite3_close().
*/
int sqlite3SafetyCheckOk(sqlite3 *db){
  u32 magic;
  if( db==0 ) return 0;
  magic = db->magic;
  if( magic!=SQLITE_MAGIC_OPEN 
#ifdef SQLITE_DEBUG
     && magic!=SQLITE_MAGIC_BUSY
#endif
  ){
    return 0;
  }else{
    return 1;
  }
}
int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  u32 magic;
  magic = db->magic;
  if( magic!=SQLITE_MAGIC_SICK &&
      magic!=SQLITE_MAGIC_OPEN &&
      magic!=SQLITE_MAGIC_BUSY ) return 0;
  return 1;
}

Added src/vacuum.c.









































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
** 2003 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
**
** $Id: vacuum.c,v 1.91 2009/07/02 07:47:33 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "vdbeInt.h"

#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
/*
** Execute zSql on database db. Return an error code.
*/
static int execSql(sqlite3 *db, const char *zSql){
  sqlite3_stmt *pStmt;
  VVA_ONLY( int rc; )
  if( !zSql ){
    return SQLITE_NOMEM;
  }
  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
    return sqlite3_errcode(db);
  }
  VVA_ONLY( rc = ) sqlite3_step(pStmt);
  assert( rc!=SQLITE_ROW );
  return sqlite3_finalize(pStmt);
}

/*
** Execute zSql on database db. The statement returns exactly
** one column. Execute this as SQL on the same database.
*/
static int execExecSql(sqlite3 *db, const char *zSql){
  sqlite3_stmt *pStmt;
  int rc;

  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ) return rc;

  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
    if( rc!=SQLITE_OK ){
      sqlite3_finalize(pStmt);
      return rc;
    }
  }

  return sqlite3_finalize(pStmt);
}

/*
** The non-standard VACUUM command is used to clean up the database,
** collapse free space, etc.  It is modelled after the VACUUM command
** in PostgreSQL.
**
** In version 1.0.x of SQLite, the VACUUM command would call
** gdbm_reorganize() on all the database tables.  But beginning
** with 2.0.0, SQLite no longer uses GDBM so this command has
** become a no-op.
*/
void sqlite3Vacuum(Parse *pParse){
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  }
  return;
}

/*
** This routine implements the OP_Vacuum opcode of the VDBE.
*/
int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  int rc = SQLITE_OK;     /* Return code from service routines */
  Btree *pMain;           /* The database being vacuumed */
  Btree *pTemp;           /* The temporary database we vacuum into */
  char *zSql = 0;         /* SQL statements */
  int saved_flags;        /* Saved value of the db->flags */
  int saved_nChange;      /* Saved value of db->nChange */
  int saved_nTotalChange; /* Saved value of db->nTotalChange */
  Db *pDb = 0;            /* Database to detach at end of vacuum */
  int isMemDb;            /* True if vacuuming a :memory: database */
  int nRes;

  if( !db->autoCommit ){
    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
    return SQLITE_ERROR;
  }

  /* Save the current value of the database flags so that it can be 
  ** restored before returning. Then set the writable-schema flag, and
  ** disable CHECK and foreign key constraints.  */
  saved_flags = db->flags;
  saved_nChange = db->nChange;
  saved_nTotalChange = db->nTotalChange;
  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  db->flags &= ~SQLITE_ForeignKeys;

  pMain = db->aDb[0].pBt;
  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));

  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  ** can be set to 'off' for this file, as it is not recovered if a crash
  ** occurs anyway. The integrity of the database is maintained by a
  ** (possibly synchronous) transaction opened on the main database before
  ** sqlite3BtreeCopyFile() is called.
  **
  ** An optimisation would be to use a non-journaled pager.
  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  ** that actually made the VACUUM run slower.  Very little journalling
  ** actually occurs when doing a vacuum since the vacuum_db is initially
  ** empty.  Only the journal header is written.  Apparently it takes more
  ** time to parse and run the PRAGMA to turn journalling off than it does
  ** to write the journal header file.
  */
  zSql = "ATTACH '' AS vacuum_db;";
  rc = execSql(db, zSql);
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
  pDb = &db->aDb[db->nDb-1];
  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
  pTemp = db->aDb[db->nDb-1].pBt;

  /* The call to execSql() to attach the temp database has left the file
  ** locked (as there was more than one active statement when the transaction
  ** to read the schema was concluded. Unlock it here so that this doesn't
  ** cause problems for the call to BtreeSetPageSize() below.  */
  sqlite3BtreeCommit(pTemp);

  nRes = sqlite3BtreeGetReserve(pMain);

  /* A VACUUM cannot change the pagesize of an encrypted database. */
#ifdef SQLITE_HAS_CODEC
  if( db->nextPagesize ){
    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
    int nKey;
    char *zKey;
    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
    if( nKey ) db->nextPagesize = 0;
  }
#endif

  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   || NEVER(db->mallocFailed)
  ){
    rc = SQLITE_NOMEM;
    goto end_of_vacuum;
  }
  rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
  if( rc!=SQLITE_OK ){
    goto end_of_vacuum;
  }

#ifndef SQLITE_OMIT_AUTOVACUUM
  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
                                           sqlite3BtreeGetAutoVacuum(pMain));
#endif

  /* Begin a transaction */
  rc = execSql(db, "BEGIN EXCLUSIVE;");
  if( rc!=SQLITE_OK ) goto end_of_vacuum;

  /* Query the schema of the main database. Create a mirror schema
  ** in the temporary database.
  */
  rc = execExecSql(db, 
      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
      "   AND rootpage>0"
  );
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
  rc = execExecSql(db, 
      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
  rc = execExecSql(db, 
      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  if( rc!=SQLITE_OK ) goto end_of_vacuum;

  /* Loop through the tables in the main database. For each, do
  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  ** the contents to the temporary database.
  */
  rc = execExecSql(db, 
      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
      "|| ' SELECT * FROM main.' || quote(name) || ';'"
      "FROM main.sqlite_master "
      "WHERE type = 'table' AND name!='sqlite_sequence' "
      "  AND rootpage>0"

  );
  if( rc!=SQLITE_OK ) goto end_of_vacuum;

  /* Copy over the sequence table
  */
  rc = execExecSql(db, 
      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  );
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
  rc = execExecSql(db, 
      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
      "|| ' SELECT * FROM main.' || quote(name) || ';' "
      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  );
  if( rc!=SQLITE_OK ) goto end_of_vacuum;


  /* Copy the triggers, views, and virtual tables from the main database
  ** over to the temporary database.  None of these objects has any
  ** associated storage, so all we have to do is copy their entries
  ** from the SQLITE_MASTER table.
  */
  rc = execSql(db,
      "INSERT INTO vacuum_db.sqlite_master "
      "  SELECT type, name, tbl_name, rootpage, sql"
      "    FROM main.sqlite_master"
      "   WHERE type='view' OR type='trigger'"
      "      OR (type='table' AND rootpage=0)"
  );
  if( rc ) goto end_of_vacuum;

  /* At this point, unless the main db was completely empty, there is now a
  ** transaction open on the vacuum database, but not on the main database.
  ** Open a btree level transaction on the main database. This allows a
  ** call to sqlite3BtreeCopyFile(). The main database btree level
  ** transaction is then committed, so the SQL level never knows it was
  ** opened for writing. This way, the SQL transaction used to create the
  ** temporary database never needs to be committed.
  */
  {
    u32 meta;
    int i;

    /* This array determines which meta meta values are preserved in the
    ** vacuum.  Even entries are the meta value number and odd entries
    ** are an increment to apply to the meta value after the vacuum.
    ** The increment is used to increase the schema cookie so that other
    ** connections to the same database will know to reread the schema.
    */
    static const unsigned char aCopy[] = {
       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
       BTREE_USER_VERSION,       0,  /* Preserve the user version */
    };

    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
    assert( 1==sqlite3BtreeIsInTrans(pMain) );

    /* Copy Btree meta values */
    for(i=0; i<ArraySize(aCopy); i+=2){
      /* GetMeta() and UpdateMeta() cannot fail in this context because
      ** we already have page 1 loaded into cache and marked dirty. */
      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
    }

    rc = sqlite3BtreeCopyFile(pMain, pTemp);
    if( rc!=SQLITE_OK ) goto end_of_vacuum;
    rc = sqlite3BtreeCommit(pTemp);
    if( rc!=SQLITE_OK ) goto end_of_vacuum;
#ifndef SQLITE_OMIT_AUTOVACUUM
    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
#endif
  }

  assert( rc==SQLITE_OK );
  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);

end_of_vacuum:
  /* Restore the original value of db->flags */
  db->flags = saved_flags;
  db->nChange = saved_nChange;
  db->nTotalChange = saved_nTotalChange;

  /* Currently there is an SQL level transaction open on the vacuum
  ** database. No locks are held on any other files (since the main file
  ** was committed at the btree level). So it safe to end the transaction
  ** by manually setting the autoCommit flag to true and detaching the
  ** vacuum database. The vacuum_db journal file is deleted when the pager
  ** is closed by the DETACH.
  */
  db->autoCommit = 1;

  if( pDb ){
    sqlite3BtreeClose(pDb->pBt);
    pDb->pBt = 0;
    pDb->pSchema = 0;
  }

  sqlite3ResetInternalSchema(db, 0);

  return rc;
}
#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */

Added src/vdbe.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** The code in this file implements execution method of the 
** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
** handles housekeeping details such as creating and deleting
** VDBE instances.  This file is solely interested in executing
** the VDBE program.
**
** In the external interface, an "sqlite3_stmt*" is an opaque pointer
** to a VDBE.
**
** The SQL parser generates a program which is then executed by
** the VDBE to do the work of the SQL statement.  VDBE programs are 
** similar in form to assembly language.  The program consists of
** a linear sequence of operations.  Each operation has an opcode 
** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
** is a null-terminated string.  Operand P5 is an unsigned character.
** Few opcodes use all 5 operands.
**
** Computation results are stored on a set of registers numbered beginning
** with 1 and going up to Vdbe.nMem.  Each register can store
** either an integer, a null-terminated string, a floating point
** number, or the SQL "NULL" value.  An implicit conversion from one
** type to the other occurs as necessary.
** 
** Most of the code in this file is taken up by the sqlite3VdbeExec()
** function which does the work of interpreting a VDBE program.
** But other routines are also provided to help in building up
** a program instruction by instruction.
**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: vdbe.c,v 1.874 2009/07/24 17:58:53 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "vdbeInt.h"

/*
** The following global variable is incremented every time a cursor
** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
** procedures use this information to make sure that indices are
** working correctly.  This variable has no function other than to
** help verify the correct operation of the library.
*/
#ifdef SQLITE_TEST
int sqlite3_search_count = 0;
#endif

/*
** When this global variable is positive, it gets decremented once before
** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
** field of the sqlite3 structure is set in order to simulate and interrupt.
**
** This facility is used for testing purposes only.  It does not function
** in an ordinary build.
*/
#ifdef SQLITE_TEST
int sqlite3_interrupt_count = 0;
#endif

/*
** The next global variable is incremented each type the OP_Sort opcode
** is executed.  The test procedures use this information to make sure that
** sorting is occurring or not occurring at appropriate times.   This variable
** has no function other than to help verify the correct operation of the
** library.
*/
#ifdef SQLITE_TEST
int sqlite3_sort_count = 0;
#endif

/*
** The next global variable records the size of the largest MEM_Blob
** or MEM_Str that has been used by a VDBE opcode.  The test procedures
** use this information to make sure that the zero-blob functionality
** is working correctly.   This variable has no function other than to
** help verify the correct operation of the library.
*/
#ifdef SQLITE_TEST
int sqlite3_max_blobsize = 0;
static void updateMaxBlobsize(Mem *p){
  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
    sqlite3_max_blobsize = p->n;
  }
}
#endif

/*
** The next global variable is incremented each type the OP_Found opcode
** is executed. This is used to test whether or not the foreign key
** operation implemented using OP_FkIsZero is working. This variable
** has no function other than to help verify the correct operation of the
** library.
*/
#ifdef SQLITE_TEST
int sqlite3_found_count = 0;
#endif

/*
** Test a register to see if it exceeds the current maximum blob size.
** If it does, record the new maximum blob size.
*/
#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
#else
# define UPDATE_MAX_BLOBSIZE(P)
#endif

/*
** Convert the given register into a string if it isn't one
** already. Return non-zero if a malloc() fails.
*/
#define Stringify(P, enc) \
   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
     { goto no_mem; }

/*
** An ephemeral string value (signified by the MEM_Ephem flag) contains
** a pointer to a dynamically allocated string where some other entity
** is responsible for deallocating that string.  Because the register
** does not control the string, it might be deleted without the register
** knowing it.
**
** This routine converts an ephemeral string into a dynamically allocated
** string that the register itself controls.  In other words, it
** converts an MEM_Ephem string into an MEM_Dyn string.
*/
#define Deephemeralize(P) \
   if( ((P)->flags&MEM_Ephem)!=0 \
       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}

/*
** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
** P if required.
*/
#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)

/*
** Argument pMem points at a register that will be passed to a
** user-defined function or returned to the user as the result of a query.
** This routine sets the pMem->type variable used by the sqlite3_value_*() 
** routines.
*/
void sqlite3VdbeMemStoreType(Mem *pMem){
  int flags = pMem->flags;
  if( flags & MEM_Null ){
    pMem->type = SQLITE_NULL;
  }
  else if( flags & MEM_Int ){
    pMem->type = SQLITE_INTEGER;
  }
  else if( flags & MEM_Real ){
    pMem->type = SQLITE_FLOAT;
  }
  else if( flags & MEM_Str ){
    pMem->type = SQLITE_TEXT;
  }else{
    pMem->type = SQLITE_BLOB;
  }
}

/*
** Properties of opcodes.  The OPFLG_INITIALIZER macro is
** created by mkopcodeh.awk during compilation.  Data is obtained
** from the comments following the "case OP_xxxx:" statements in
** this file.  
*/
static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;

/*
** Return true if an opcode has any of the OPFLG_xxx properties
** specified by mask.
*/
int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
  assert( opcode>0 && opcode<(int)sizeof(opcodeProperty) );
  return (opcodeProperty[opcode]&mask)!=0;
}

/*
** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
** if we run out of memory.
*/
static VdbeCursor *allocateCursor(
  Vdbe *p,              /* The virtual machine */
  int iCur,             /* Index of the new VdbeCursor */
  int nField,           /* Number of fields in the table or index */
  int iDb,              /* When database the cursor belongs to, or -1 */
  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
){
  /* Find the memory cell that will be used to store the blob of memory
  ** required for this VdbeCursor structure. It is convenient to use a 
  ** vdbe memory cell to manage the memory allocation required for a
  ** VdbeCursor structure for the following reasons:
  **
  **   * Sometimes cursor numbers are used for a couple of different
  **     purposes in a vdbe program. The different uses might require
  **     different sized allocations. Memory cells provide growable
  **     allocations.
  **
  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  **     be freed lazily via the sqlite3_release_memory() API. This
  **     minimizes the number of malloc calls made by the system.
  **
  ** Memory cells for cursors are allocated at the top of the address
  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  */
  Mem *pMem = &p->aMem[p->nMem-iCur];

  int nByte;
  VdbeCursor *pCx = 0;
  nByte = 
      sizeof(VdbeCursor) + 
      (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
      2*nField*sizeof(u32);

  assert( iCur<p->nCursor );
  if( p->apCsr[iCur] ){
    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
    p->apCsr[iCur] = 0;
  }
  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
    memset(pMem->z, 0, nByte);
    pCx->iDb = iDb;
    pCx->nField = nField;
    if( nField ){
      pCx->aType = (u32 *)&pMem->z[sizeof(VdbeCursor)];
    }
    if( isBtreeCursor ){
      pCx->pCursor = (BtCursor*)
          &pMem->z[sizeof(VdbeCursor)+2*nField*sizeof(u32)];
    }
  }
  return pCx;
}

/*
** Try to convert a value into a numeric representation if we can
** do so without loss of information.  In other words, if the string
** looks like a number, convert it into a number.  If it does not
** look like a number, leave it alone.
*/
static void applyNumericAffinity(Mem *pRec){
  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
    int realnum;
    sqlite3VdbeMemNulTerminate(pRec);
    if( (pRec->flags&MEM_Str)
         && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
      i64 value;
      sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
      if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
        pRec->u.i = value;
        MemSetTypeFlag(pRec, MEM_Int);
      }else{
        sqlite3VdbeMemRealify(pRec);
      }
    }
  }
}

/*
** Processing is determine by the affinity parameter:
**
** SQLITE_AFF_INTEGER:
** SQLITE_AFF_REAL:
** SQLITE_AFF_NUMERIC:
**    Try to convert pRec to an integer representation or a 
**    floating-point representation if an integer representation
**    is not possible.  Note that the integer representation is
**    always preferred, even if the affinity is REAL, because
**    an integer representation is more space efficient on disk.
**
** SQLITE_AFF_TEXT:
**    Convert pRec to a text representation.
**
** SQLITE_AFF_NONE:
**    No-op.  pRec is unchanged.
*/
static void applyAffinity(
  Mem *pRec,          /* The value to apply affinity to */
  char affinity,      /* The affinity to be applied */
  u8 enc              /* Use this text encoding */
){
  if( affinity==SQLITE_AFF_TEXT ){
    /* Only attempt the conversion to TEXT if there is an integer or real
    ** representation (blob and NULL do not get converted) but no string
    ** representation.
    */
    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
      sqlite3VdbeMemStringify(pRec, enc);
    }
    pRec->flags &= ~(MEM_Real|MEM_Int);
  }else if( affinity!=SQLITE_AFF_NONE ){
    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
             || affinity==SQLITE_AFF_NUMERIC );
    applyNumericAffinity(pRec);
    if( pRec->flags & MEM_Real ){
      sqlite3VdbeIntegerAffinity(pRec);
    }
  }
}

/*
** Try to convert the type of a function argument or a result column
** into a numeric representation.  Use either INTEGER or REAL whichever
** is appropriate.  But only do the conversion if it is possible without
** loss of information and return the revised type of the argument.
**
** This is an EXPERIMENTAL api and is subject to change or removal.
*/
int sqlite3_value_numeric_type(sqlite3_value *pVal){
  Mem *pMem = (Mem*)pVal;
  applyNumericAffinity(pMem);
  sqlite3VdbeMemStoreType(pMem);
  return pMem->type;
}

/*
** Exported version of applyAffinity(). This one works on sqlite3_value*, 
** not the internal Mem* type.
*/
void sqlite3ValueApplyAffinity(
  sqlite3_value *pVal, 
  u8 affinity, 
  u8 enc
){
  applyAffinity((Mem *)pVal, affinity, enc);
}

#ifdef SQLITE_DEBUG
/*
** Write a nice string representation of the contents of cell pMem
** into buffer zBuf, length nBuf.
*/
void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  char *zCsr = zBuf;
  int f = pMem->flags;

  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};

  if( f&MEM_Blob ){
    int i;
    char c;
    if( f & MEM_Dyn ){
      c = 'z';
      assert( (f & (MEM_Static|MEM_Ephem))==0 );
    }else if( f & MEM_Static ){
      c = 't';
      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
    }else if( f & MEM_Ephem ){
      c = 'e';
      assert( (f & (MEM_Static|MEM_Dyn))==0 );
    }else{
      c = 's';
    }

    sqlite3_snprintf(100, zCsr, "%c", c);
    zCsr += sqlite3Strlen30(zCsr);
    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
    zCsr += sqlite3Strlen30(zCsr);
    for(i=0; i<16 && i<pMem->n; i++){
      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
      zCsr += sqlite3Strlen30(zCsr);
    }
    for(i=0; i<16 && i<pMem->n; i++){
      char z = pMem->z[i];
      if( z<32 || z>126 ) *zCsr++ = '.';
      else *zCsr++ = z;
    }

    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
    zCsr += sqlite3Strlen30(zCsr);
    if( f & MEM_Zero ){
      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
      zCsr += sqlite3Strlen30(zCsr);
    }
    *zCsr = '\0';
  }else if( f & MEM_Str ){
    int j, k;
    zBuf[0] = ' ';
    if( f & MEM_Dyn ){
      zBuf[1] = 'z';
      assert( (f & (MEM_Static|MEM_Ephem))==0 );
    }else if( f & MEM_Static ){
      zBuf[1] = 't';
      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
    }else if( f & MEM_Ephem ){
      zBuf[1] = 'e';
      assert( (f & (MEM_Static|MEM_Dyn))==0 );
    }else{
      zBuf[1] = 's';
    }
    k = 2;
    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
    k += sqlite3Strlen30(&zBuf[k]);
    zBuf[k++] = '[';
    for(j=0; j<15 && j<pMem->n; j++){
      u8 c = pMem->z[j];
      if( c>=0x20 && c<0x7f ){
        zBuf[k++] = c;
      }else{
        zBuf[k++] = '.';
      }
    }
    zBuf[k++] = ']';
    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
    k += sqlite3Strlen30(&zBuf[k]);
    zBuf[k++] = 0;
  }
}
#endif

#ifdef SQLITE_DEBUG
/*
** Print the value of a register for tracing purposes:
*/
static void memTracePrint(FILE *out, Mem *p){
  if( p->flags & MEM_Null ){
    fprintf(out, " NULL");
  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
    fprintf(out, " si:%lld", p->u.i);
  }else if( p->flags & MEM_Int ){
    fprintf(out, " i:%lld", p->u.i);
#ifndef SQLITE_OMIT_FLOATING_POINT
  }else if( p->flags & MEM_Real ){
    fprintf(out, " r:%g", p->r);
#endif
  }else if( p->flags & MEM_RowSet ){
    fprintf(out, " (rowset)");
  }else{
    char zBuf[200];
    sqlite3VdbeMemPrettyPrint(p, zBuf);
    fprintf(out, " ");
    fprintf(out, "%s", zBuf);
  }
}
static void registerTrace(FILE *out, int iReg, Mem *p){
  fprintf(out, "REG[%d] = ", iReg);
  memTracePrint(out, p);
  fprintf(out, "\n");
}
#endif

#ifdef SQLITE_DEBUG
#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
#else
#  define REGISTER_TRACE(R,M)
#endif


#ifdef VDBE_PROFILE

/* 
** hwtime.h contains inline assembler code for implementing 
** high-performance timing routines.
*/
#include "hwtime.h"

#endif

/*
** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
** sqlite3_interrupt() routine has been called.  If it has been, then
** processing of the VDBE program is interrupted.
**
** This macro added to every instruction that does a jump in order to
** implement a loop.  This test used to be on every single instruction,
** but that meant we more testing that we needed.  By only testing the
** flag on jump instructions, we get a (small) speed improvement.
*/
#define CHECK_FOR_INTERRUPT \
   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;

#ifdef SQLITE_DEBUG
static int fileExists(sqlite3 *db, const char *zFile){
  int res = 0;
  int rc = SQLITE_OK;
#ifdef SQLITE_TEST
  /* If we are currently testing IO errors, then do not call OsAccess() to
  ** test for the presence of zFile. This is because any IO error that
  ** occurs here will not be reported, causing the test to fail.
  */
  extern int sqlite3_io_error_pending;
  if( sqlite3_io_error_pending<=0 )
#endif
    rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
  return (res && rc==SQLITE_OK);
}
#endif

#ifndef NDEBUG
/*
** This function is only called from within an assert() expression. It
** checks that the sqlite3.nTransaction variable is correctly set to
** the number of non-transaction savepoints currently in the 
** linked list starting at sqlite3.pSavepoint.
** 
** Usage:
**
**     assert( checkSavepointCount(db) );
*/
static int checkSavepointCount(sqlite3 *db){
  int n = 0;
  Savepoint *p;
  for(p=db->pSavepoint; p; p=p->pNext) n++;
  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  return 1;
}
#endif

/*
** Execute as much of a VDBE program as we can then return.
**
** sqlite3VdbeMakeReady() must be called before this routine in order to
** close the program with a final OP_Halt and to set up the callbacks
** and the error message pointer.
**
** Whenever a row or result data is available, this routine will either
** invoke the result callback (if there is one) or return with
** SQLITE_ROW.
**
** If an attempt is made to open a locked database, then this routine
** will either invoke the busy callback (if there is one) or it will
** return SQLITE_BUSY.
**
** If an error occurs, an error message is written to memory obtained
** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
**
** If the callback ever returns non-zero, then the program exits
** immediately.  There will be no error message but the p->rc field is
** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
**
** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
** routine to return SQLITE_ERROR.
**
** Other fatal errors return SQLITE_ERROR.
**
** After this routine has finished, sqlite3VdbeFinalize() should be
** used to clean up the mess that was left behind.
*/
int sqlite3VdbeExec(
  Vdbe *p                    /* The VDBE */
){
  int pc;                    /* The program counter */
  Op *pOp;                   /* Current operation */
  int rc = SQLITE_OK;        /* Value to return */
  sqlite3 *db = p->db;       /* The database */
  u8 encoding = ENC(db);     /* The database encoding */
  Mem *pIn1 = 0;             /* 1st input operand */
  Mem *pIn2 = 0;             /* 2nd input operand */
  Mem *pIn3 = 0;             /* 3rd input operand */
  Mem *pOut = 0;             /* Output operand */
  u8 opProperty;
  int iCompare = 0;          /* Result of last OP_Compare operation */
  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
#ifdef VDBE_PROFILE
  u64 start;                 /* CPU clock count at start of opcode */
  int origPc;                /* Program counter at start of opcode */
#endif
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
#endif
  /*** INSERT STACK UNION HERE ***/

  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
  assert( db->magic==SQLITE_MAGIC_BUSY );
  sqlite3VdbeMutexArrayEnter(p);
  if( p->rc==SQLITE_NOMEM ){
    /* This happens if a malloc() inside a call to sqlite3_column_text() or
    ** sqlite3_column_text16() failed.  */
    goto no_mem;
  }
  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  p->rc = SQLITE_OK;
  assert( p->explain==0 );
  p->pResultSet = 0;
  db->busyHandler.nBusy = 0;
  CHECK_FOR_INTERRUPT;
  sqlite3VdbeIOTraceSql(p);
#ifdef SQLITE_DEBUG
  sqlite3BeginBenignMalloc();
  if( p->pc==0 
   && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
  ){
    int i;
    printf("VDBE Program Listing:\n");
    sqlite3VdbePrintSql(p);
    for(i=0; i<p->nOp; i++){
      sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
    }
  }
  if( fileExists(db, "vdbe_trace") ){
    p->trace = stdout;
  }
  sqlite3EndBenignMalloc();
#endif
  for(pc=p->pc; rc==SQLITE_OK; pc++){
    assert( pc>=0 && pc<p->nOp );
    if( db->mallocFailed ) goto no_mem;
#ifdef VDBE_PROFILE
    origPc = pc;
    start = sqlite3Hwtime();
#endif
    pOp = &p->aOp[pc];

    /* Only allow tracing if SQLITE_DEBUG is defined.
    */
#ifdef SQLITE_DEBUG
    if( p->trace ){
      if( pc==0 ){
        printf("VDBE Execution Trace:\n");
        sqlite3VdbePrintSql(p);
      }
      sqlite3VdbePrintOp(p->trace, pc, pOp);
    }
    if( p->trace==0 && pc==0 ){
      sqlite3BeginBenignMalloc();
      if( fileExists(db, "vdbe_sqltrace") ){
        sqlite3VdbePrintSql(p);
      }
      sqlite3EndBenignMalloc();
    }
#endif
      

    /* Check to see if we need to simulate an interrupt.  This only happens
    ** if we have a special test build.
    */
#ifdef SQLITE_TEST
    if( sqlite3_interrupt_count>0 ){
      sqlite3_interrupt_count--;
      if( sqlite3_interrupt_count==0 ){
        sqlite3_interrupt(db);
      }
    }
#endif

#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
    /* Call the progress callback if it is configured and the required number
    ** of VDBE ops have been executed (either since this invocation of
    ** sqlite3VdbeExec() or since last time the progress callback was called).
    ** If the progress callback returns non-zero, exit the virtual machine with
    ** a return code SQLITE_ABORT.
    */
    if( db->xProgress ){
      if( db->nProgressOps==nProgressOps ){
        int prc;
        if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
        prc =db->xProgress(db->pProgressArg);
        if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
        if( prc!=0 ){
          rc = SQLITE_INTERRUPT;
          goto vdbe_error_halt;
        }
        nProgressOps = 0;
      }
      nProgressOps++;
    }
#endif

    /* Do common setup processing for any opcode that is marked
    ** with the "out2-prerelease" tag.  Such opcodes have a single
    ** output which is specified by the P2 parameter.  The P2 register
    ** is initialized to a NULL.
    */
    opProperty = opcodeProperty[pOp->opcode];
    if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
      assert( pOp->p2>0 );
      assert( pOp->p2<=p->nMem );
      pOut = &p->aMem[pOp->p2];
      sqlite3VdbeMemReleaseExternal(pOut);
      pOut->flags = MEM_Null;
      pOut->n = 0;
    }else
 
    /* Do common setup for opcodes marked with one of the following
    ** combinations of properties.
    **
    **           in1
    **           in1 in2
    **           in1 in2 out3
    **           in1 in3
    **
    ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
    ** registers for inputs.  Variable pOut points to the output register.
    */
    if( (opProperty & OPFLG_IN1)!=0 ){
      assert( pOp->p1>0 );
      assert( pOp->p1<=p->nMem );
      pIn1 = &p->aMem[pOp->p1];
      REGISTER_TRACE(pOp->p1, pIn1);
      if( (opProperty & OPFLG_IN2)!=0 ){
        assert( pOp->p2>0 );
        assert( pOp->p2<=p->nMem );
        pIn2 = &p->aMem[pOp->p2];
        REGISTER_TRACE(pOp->p2, pIn2);
        /* As currently implemented, in2 implies out3.  There is no reason
        ** why this has to be, it just worked out that way. */
        assert( (opProperty & OPFLG_OUT3)!=0 );
        assert( pOp->p3>0 );
        assert( pOp->p3<=p->nMem );
        pOut = &p->aMem[pOp->p3];
      }else if( (opProperty & OPFLG_IN3)!=0 ){
        assert( pOp->p3>0 );
        assert( pOp->p3<=p->nMem );
        pIn3 = &p->aMem[pOp->p3];
        REGISTER_TRACE(pOp->p3, pIn3);
      }
    }else if( (opProperty & OPFLG_IN2)!=0 ){
      assert( pOp->p2>0 );
      assert( pOp->p2<=p->nMem );
      pIn2 = &p->aMem[pOp->p2];
      REGISTER_TRACE(pOp->p2, pIn2);
    }else if( (opProperty & OPFLG_IN3)!=0 ){
      assert( pOp->p3>0 );
      assert( pOp->p3<=p->nMem );
      pIn3 = &p->aMem[pOp->p3];
      REGISTER_TRACE(pOp->p3, pIn3);
    }

    switch( pOp->opcode ){

/*****************************************************************************
** What follows is a massive switch statement where each case implements a
** separate instruction in the virtual machine.  If we follow the usual
** indentation conventions, each case should be indented by 6 spaces.  But
** that is a lot of wasted space on the left margin.  So the code within
** the switch statement will break with convention and be flush-left. Another
** big comment (similar to this one) will mark the point in the code where
** we transition back to normal indentation.
**
** The formatting of each case is important.  The makefile for SQLite
** generates two C files "opcodes.h" and "opcodes.c" by scanning this
** file looking for lines that begin with "case OP_".  The opcodes.h files
** will be filled with #defines that give unique integer values to each
** opcode and the opcodes.c file is filled with an array of strings where
** each string is the symbolic name for the corresponding opcode.  If the
** case statement is followed by a comment of the form "/# same as ... #/"
** that comment is used to determine the particular value of the opcode.
**
** Other keywords in the comment that follows each case are used to
** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
** the mkopcodeh.awk script for additional information.
**
** Documentation about VDBE opcodes is generated by scanning this file
** for lines of that contain "Opcode:".  That line and all subsequent
** comment lines are used in the generation of the opcode.html documentation
** file.
**
** SUMMARY:
**
**     Formatting is important to scripts that scan this file.
**     Do not deviate from the formatting style currently in use.
**
*****************************************************************************/

/* Opcode:  Goto * P2 * * *
**
** An unconditional jump to address P2.
** The next instruction executed will be 
** the one at index P2 from the beginning of
** the program.
*/
case OP_Goto: {             /* jump */
  CHECK_FOR_INTERRUPT;
  pc = pOp->p2 - 1;
  break;
}

/* Opcode:  Gosub P1 P2 * * *
**
** Write the current address onto register P1
** and then jump to address P2.
*/
case OP_Gosub: {            /* jump */
  assert( pOp->p1>0 );
  assert( pOp->p1<=p->nMem );
  pIn1 = &p->aMem[pOp->p1];
  assert( (pIn1->flags & MEM_Dyn)==0 );
  pIn1->flags = MEM_Int;
  pIn1->u.i = pc;
  REGISTER_TRACE(pOp->p1, pIn1);
  pc = pOp->p2 - 1;
  break;
}

/* Opcode:  Return P1 * * * *
**
** Jump to the next instruction after the address in register P1.
*/
case OP_Return: {           /* in1 */
  assert( pIn1->flags & MEM_Int );
  pc = (int)pIn1->u.i;
  break;
}

/* Opcode:  Yield P1 * * * *
**
** Swap the program counter with the value in register P1.
*/
case OP_Yield: {            /* in1 */
  int pcDest;
  assert( (pIn1->flags & MEM_Dyn)==0 );
  pIn1->flags = MEM_Int;
  pcDest = (int)pIn1->u.i;
  pIn1->u.i = pc;
  REGISTER_TRACE(pOp->p1, pIn1);
  pc = pcDest;
  break;
}

/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
**
** Check the value in register P3.  If is is NULL then Halt using
** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
** value in register P3 is not NULL, then this routine is a no-op.
*/
case OP_HaltIfNull: {      /* in3 */
  if( (pIn3->flags & MEM_Null)==0 ) break;
  /* Fall through into OP_Halt */
}

/* Opcode:  Halt P1 P2 * P4 *
**
** Exit immediately.  All open cursors, etc are closed
** automatically.
**
** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
** For errors, it can be some other value.  If P1!=0 then P2 will determine
** whether or not to rollback the current transaction.  Do not rollback
** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
** then back out all changes that have occurred during this execution of the
** VDBE, but do not rollback the transaction. 
**
** If P4 is not null then it is an error message string.
**
** There is an implied "Halt 0 0 0" instruction inserted at the very end of
** every program.  So a jump past the last instruction of the program
** is the same as executing Halt.
*/
case OP_Halt: {
  if( pOp->p1==SQLITE_OK && p->pFrame ){
    /* Halt the sub-program. Return control to the parent frame. */
    VdbeFrame *pFrame = p->pFrame;
    p->pFrame = pFrame->pParent;
    p->nFrame--;
    sqlite3VdbeSetChanges(db, p->nChange);
    pc = sqlite3VdbeFrameRestore(pFrame);
    if( pOp->p2==OE_Ignore ){
      /* Instruction pc is the OP_Program that invoked the sub-program 
      ** currently being halted. If the p2 instruction of this OP_Halt
      ** instruction is set to OE_Ignore, then the sub-program is throwing
      ** an IGNORE exception. In this case jump to the address specified
      ** as the p2 of the calling OP_Program.  */
      pc = p->aOp[pc].p2-1;
    }
    break;
  }

  p->rc = pOp->p1;
  p->errorAction = (u8)pOp->p2;
  p->pc = pc;
  if( pOp->p4.z ){
    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  }
  rc = sqlite3VdbeHalt(p);
  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  if( rc==SQLITE_BUSY ){
    p->rc = rc = SQLITE_BUSY;
  }else{
    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  }
  goto vdbe_return;
}

/* Opcode: Integer P1 P2 * * *
**
** The 32-bit integer value P1 is written into register P2.
*/
case OP_Integer: {         /* out2-prerelease */
  pOut->flags = MEM_Int;
  pOut->u.i = pOp->p1;
  break;
}

/* Opcode: Int64 * P2 * P4 *
**
** P4 is a pointer to a 64-bit integer value.
** Write that value into register P2.
*/
case OP_Int64: {           /* out2-prerelease */
  assert( pOp->p4.pI64!=0 );
  pOut->flags = MEM_Int;
  pOut->u.i = *pOp->p4.pI64;
  break;
}

/* Opcode: Real * P2 * P4 *
**
** P4 is a pointer to a 64-bit floating point value.
** Write that value into register P2.
*/
case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
  pOut->flags = MEM_Real;
  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  pOut->r = *pOp->p4.pReal;
  break;
}

/* Opcode: String8 * P2 * P4 *
**
** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
** into an OP_String before it is executed for the first time.
*/
case OP_String8: {         /* same as TK_STRING, out2-prerelease */
  assert( pOp->p4.z!=0 );
  pOp->opcode = OP_String;
  pOp->p1 = sqlite3Strlen30(pOp->p4.z);

#ifndef SQLITE_OMIT_UTF16
  if( encoding!=SQLITE_UTF8 ){
    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
    if( rc==SQLITE_TOOBIG ) goto too_big;
    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
    assert( pOut->zMalloc==pOut->z );
    assert( pOut->flags & MEM_Dyn );
    pOut->zMalloc = 0;
    pOut->flags |= MEM_Static;
    pOut->flags &= ~MEM_Dyn;
    if( pOp->p4type==P4_DYNAMIC ){
      sqlite3DbFree(db, pOp->p4.z);
    }
    pOp->p4type = P4_DYNAMIC;
    pOp->p4.z = pOut->z;
    pOp->p1 = pOut->n;
  }
#endif
  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    goto too_big;
  }
  /* Fall through to the next case, OP_String */
}
  
/* Opcode: String P1 P2 * P4 *
**
** The string value P4 of length P1 (bytes) is stored in register P2.
*/
case OP_String: {          /* out2-prerelease */
  assert( pOp->p4.z!=0 );
  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  pOut->z = pOp->p4.z;
  pOut->n = pOp->p1;
  pOut->enc = encoding;
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Null * P2 * * *
**
** Write a NULL into register P2.
*/
case OP_Null: {           /* out2-prerelease */
  break;
}


/* Opcode: Blob P1 P2 * P4
**
** P4 points to a blob of data P1 bytes long.  Store this
** blob in register P2. This instruction is not coded directly
** by the compiler. Instead, the compiler layer specifies
** an OP_HexBlob opcode, with the hex string representation of
** the blob as P4. This opcode is transformed to an OP_Blob
** the first time it is executed.
*/
case OP_Blob: {                /* out2-prerelease */
  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  pOut->enc = encoding;
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Variable P1 P2 P3 P4 *
**
** Transfer the values of bound parameters P1..P1+P3-1 into registers
** P2..P2+P3-1.
**
** If the parameter is named, then its name appears in P4 and P3==1.
** The P4 value is used by sqlite3_bind_parameter_name().
*/
case OP_Variable: {
  int p1;          /* Variable to copy from */
  int p2;          /* Register to copy to */
  int n;           /* Number of values left to copy */
  Mem *pVar;       /* Value being transferred */

  p1 = pOp->p1 - 1;
  p2 = pOp->p2;
  n = pOp->p3;
  assert( p1>=0 && p1+n<=p->nVar );
  assert( p2>=1 && p2+n-1<=p->nMem );
  assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );

  while( n-- > 0 ){
    pVar = &p->aVar[p1++];
    if( sqlite3VdbeMemTooBig(pVar) ){
      goto too_big;
    }
    pOut = &p->aMem[p2++];
    sqlite3VdbeMemReleaseExternal(pOut);
    pOut->flags = MEM_Null;
    sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
    UPDATE_MAX_BLOBSIZE(pOut);
  }
  break;
}

/* Opcode: Move P1 P2 P3 * *
**
** Move the values in register P1..P1+P3-1 over into
** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
** left holding a NULL.  It is an error for register ranges
** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
*/
case OP_Move: {
  char *zMalloc;   /* Holding variable for allocated memory */
  int n;           /* Number of registers left to copy */
  int p1;          /* Register to copy from */
  int p2;          /* Register to copy to */

  n = pOp->p3;
  p1 = pOp->p1;
  p2 = pOp->p2;
  assert( n>0 && p1>0 && p2>0 );
  assert( p1+n<=p2 || p2+n<=p1 );

  pIn1 = &p->aMem[p1];
  pOut = &p->aMem[p2];
  while( n-- ){
    assert( pOut<=&p->aMem[p->nMem] );
    assert( pIn1<=&p->aMem[p->nMem] );
    zMalloc = pOut->zMalloc;
    pOut->zMalloc = 0;
    sqlite3VdbeMemMove(pOut, pIn1);
    pIn1->zMalloc = zMalloc;
    REGISTER_TRACE(p2++, pOut);
    pIn1++;
    pOut++;
  }
  break;
}

/* Opcode: Copy P1 P2 * * *
**
** Make a copy of register P1 into register P2.
**
** This instruction makes a deep copy of the value.  A duplicate
** is made of any string or blob constant.  See also OP_SCopy.
*/
case OP_Copy: {             /* in1 */
  assert( pOp->p2>0 );
  assert( pOp->p2<=p->nMem );
  pOut = &p->aMem[pOp->p2];
  assert( pOut!=pIn1 );
  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  Deephemeralize(pOut);
  REGISTER_TRACE(pOp->p2, pOut);
  break;
}

/* Opcode: SCopy P1 P2 * * *
**
** Make a shallow copy of register P1 into register P2.
**
** This instruction makes a shallow copy of the value.  If the value
** is a string or blob, then the copy is only a pointer to the
** original and hence if the original changes so will the copy.
** Worse, if the original is deallocated, the copy becomes invalid.
** Thus the program must guarantee that the original will not change
** during the lifetime of the copy.  Use OP_Copy to make a complete
** copy.
*/
case OP_SCopy: {            /* in1 */
  REGISTER_TRACE(pOp->p1, pIn1);
  assert( pOp->p2>0 );
  assert( pOp->p2<=p->nMem );
  pOut = &p->aMem[pOp->p2];
  assert( pOut!=pIn1 );
  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  REGISTER_TRACE(pOp->p2, pOut);
  break;
}

/* Opcode: ResultRow P1 P2 * * *
**
** The registers P1 through P1+P2-1 contain a single row of
** results. This opcode causes the sqlite3_step() call to terminate
** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
** structure to provide access to the top P1 values as the result
** row.
*/
case OP_ResultRow: {
  Mem *pMem;
  int i;
  assert( p->nResColumn==pOp->p2 );
  assert( pOp->p1>0 );
  assert( pOp->p1+pOp->p2<=p->nMem+1 );

  /* If this statement has violated immediate foreign key constraints, do
  ** not return the number of rows modified. And do not RELEASE the statement
  ** transaction. It needs to be rolled back.  */
  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
    assert( db->flags&SQLITE_CountRows );
    assert( p->usesStmtJournal );
    break;
  }

  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
  ** DML statements invoke this opcode to return the number of rows 
  ** modified to the user. This is the only way that a VM that
  ** opens a statement transaction may invoke this opcode.
  **
  ** In case this is such a statement, close any statement transaction
  ** opened by this VM before returning control to the user. This is to
  ** ensure that statement-transactions are always nested, not overlapping.
  ** If the open statement-transaction is not closed here, then the user
  ** may step another VM that opens its own statement transaction. This
  ** may lead to overlapping statement transactions.
  **
  ** The statement transaction is never a top-level transaction.  Hence
  ** the RELEASE call below can never fail.
  */
  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  if( NEVER(rc!=SQLITE_OK) ){
    break;
  }

  /* Invalidate all ephemeral cursor row caches */
  p->cacheCtr = (p->cacheCtr + 2)|1;

  /* Make sure the results of the current row are \000 terminated
  ** and have an assigned type.  The results are de-ephemeralized as
  ** as side effect.
  */
  pMem = p->pResultSet = &p->aMem[pOp->p1];
  for(i=0; i<pOp->p2; i++){
    sqlite3VdbeMemNulTerminate(&pMem[i]);
    sqlite3VdbeMemStoreType(&pMem[i]);
    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  }
  if( db->mallocFailed ) goto no_mem;

  /* Return SQLITE_ROW
  */
  p->pc = pc + 1;
  rc = SQLITE_ROW;
  goto vdbe_return;
}

/* Opcode: Concat P1 P2 P3 * *
**
** Add the text in register P1 onto the end of the text in
** register P2 and store the result in register P3.
** If either the P1 or P2 text are NULL then store NULL in P3.
**
**   P3 = P2 || P1
**
** It is illegal for P1 and P3 to be the same register. Sometimes,
** if P3 is the same register as P2, the implementation is able
** to avoid a memcpy().
*/
case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
  i64 nByte;

  assert( pIn1!=pOut );
  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
    sqlite3VdbeMemSetNull(pOut);
    break;
  }
  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  Stringify(pIn1, encoding);
  Stringify(pIn2, encoding);
  nByte = pIn1->n + pIn2->n;
  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    goto too_big;
  }
  MemSetTypeFlag(pOut, MEM_Str);
  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
    goto no_mem;
  }
  if( pOut!=pIn2 ){
    memcpy(pOut->z, pIn2->z, pIn2->n);
  }
  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  pOut->z[nByte] = 0;
  pOut->z[nByte+1] = 0;
  pOut->flags |= MEM_Term;
  pOut->n = (int)nByte;
  pOut->enc = encoding;
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Add P1 P2 P3 * *
**
** Add the value in register P1 to the value in register P2
** and store the result in register P3.
** If either input is NULL, the result is NULL.
*/
/* Opcode: Multiply P1 P2 P3 * *
**
**
** Multiply the value in register P1 by the value in register P2
** and store the result in register P3.
** If either input is NULL, the result is NULL.
*/
/* Opcode: Subtract P1 P2 P3 * *
**
** Subtract the value in register P1 from the value in register P2
** and store the result in register P3.
** If either input is NULL, the result is NULL.
*/
/* Opcode: Divide P1 P2 P3 * *
**
** Divide the value in register P1 by the value in register P2
** and store the result in register P3 (P3=P2/P1). If the value in 
** register P1 is zero, then the result is NULL. If either input is 
** NULL, the result is NULL.
*/
/* Opcode: Remainder P1 P2 P3 * *
**
** Compute the remainder after integer division of the value in
** register P1 by the value in register P2 and store the result in P3. 
** If the value in register P2 is zero the result is NULL.
** If either operand is NULL, the result is NULL.
*/
case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
  int flags;      /* Combined MEM_* flags from both inputs */
  i64 iA;         /* Integer value of left operand */
  i64 iB;         /* Integer value of right operand */
  double rA;      /* Real value of left operand */
  double rB;      /* Real value of right operand */

  applyNumericAffinity(pIn1);
  applyNumericAffinity(pIn2);
  flags = pIn1->flags | pIn2->flags;
  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
    iA = pIn1->u.i;
    iB = pIn2->u.i;
    switch( pOp->opcode ){
      case OP_Add:         iB += iA;       break;
      case OP_Subtract:    iB -= iA;       break;
      case OP_Multiply:    iB *= iA;       break;
      case OP_Divide: {
        if( iA==0 ) goto arithmetic_result_is_null;
        /* Dividing the largest possible negative 64-bit integer (1<<63) by 
        ** -1 returns an integer too large to store in a 64-bit data-type. On
        ** some architectures, the value overflows to (1<<63). On others,
        ** a SIGFPE is issued. The following statement normalizes this
        ** behavior so that all architectures behave as if integer 
        ** overflow occurred.
        */
        if( iA==-1 && iB==SMALLEST_INT64 ) iA = 1;
        iB /= iA;
        break;
      }
      default: {
        if( iA==0 ) goto arithmetic_result_is_null;
        if( iA==-1 ) iA = 1;
        iB %= iA;
        break;
      }
    }
    pOut->u.i = iB;
    MemSetTypeFlag(pOut, MEM_Int);
  }else{
    rA = sqlite3VdbeRealValue(pIn1);
    rB = sqlite3VdbeRealValue(pIn2);
    switch( pOp->opcode ){
      case OP_Add:         rB += rA;       break;
      case OP_Subtract:    rB -= rA;       break;
      case OP_Multiply:    rB *= rA;       break;
      case OP_Divide: {
        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
        if( rA==(double)0 ) goto arithmetic_result_is_null;
        rB /= rA;
        break;
      }
      default: {
        iA = (i64)rA;
        iB = (i64)rB;
        if( iA==0 ) goto arithmetic_result_is_null;
        if( iA==-1 ) iA = 1;
        rB = (double)(iB % iA);
        break;
      }
    }
    if( sqlite3IsNaN(rB) ){
      goto arithmetic_result_is_null;
    }
    pOut->r = rB;
    MemSetTypeFlag(pOut, MEM_Real);
    if( (flags & MEM_Real)==0 ){
      sqlite3VdbeIntegerAffinity(pOut);
    }
  }
  break;

arithmetic_result_is_null:
  sqlite3VdbeMemSetNull(pOut);
  break;
}

/* Opcode: CollSeq * * P4
**
** P4 is a pointer to a CollSeq struct. If the next call to a user function
** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
** be returned. This is used by the built-in min(), max() and nullif()
** functions.
**
** The interface used by the implementation of the aforementioned functions
** to retrieve the collation sequence set by this opcode is not available
** publicly, only to user functions defined in func.c.
*/
case OP_CollSeq: {
  assert( pOp->p4type==P4_COLLSEQ );
  break;
}

/* Opcode: Function P1 P2 P3 P4 P5
**
** Invoke a user function (P4 is a pointer to a Function structure that
** defines the function) with P5 arguments taken from register P2 and
** successors.  The result of the function is stored in register P3.
** Register P3 must not be one of the function inputs.
**
** P1 is a 32-bit bitmask indicating whether or not each argument to the 
** function was determined to be constant at compile time. If the first
** argument was constant then bit 0 of P1 is set. This is used to determine
** whether meta data associated with a user function argument using the
** sqlite3_set_auxdata() API may be safely retained until the next
** invocation of this opcode.
**
** See also: AggStep and AggFinal
*/
case OP_Function: {
  int i;
  Mem *pArg;
  sqlite3_context ctx;
  sqlite3_value **apVal;
  int n;

  n = pOp->p5;
  apVal = p->apArg;
  assert( apVal || n==0 );

  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem+1) );
  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  pArg = &p->aMem[pOp->p2];
  for(i=0; i<n; i++, pArg++){
    apVal[i] = pArg;
    sqlite3VdbeMemStoreType(pArg);
    REGISTER_TRACE(pOp->p2, pArg);
  }

  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
  if( pOp->p4type==P4_FUNCDEF ){
    ctx.pFunc = pOp->p4.pFunc;
    ctx.pVdbeFunc = 0;
  }else{
    ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
    ctx.pFunc = ctx.pVdbeFunc->pFunc;
  }

  assert( pOp->p3>0 && pOp->p3<=p->nMem );
  pOut = &p->aMem[pOp->p3];
  ctx.s.flags = MEM_Null;
  ctx.s.db = db;
  ctx.s.xDel = 0;
  ctx.s.zMalloc = 0;

  /* The output cell may already have a buffer allocated. Move
  ** the pointer to ctx.s so in case the user-function can use
  ** the already allocated buffer instead of allocating a new one.
  */
  sqlite3VdbeMemMove(&ctx.s, pOut);
  MemSetTypeFlag(&ctx.s, MEM_Null);

  ctx.isError = 0;
  if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
    assert( pOp>p->aOp );
    assert( pOp[-1].p4type==P4_COLLSEQ );
    assert( pOp[-1].opcode==OP_CollSeq );
    ctx.pColl = pOp[-1].p4.pColl;
  }
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  if( sqlite3SafetyOn(db) ){
    sqlite3VdbeMemRelease(&ctx.s);
    goto abort_due_to_misuse;
  }
  if( db->mallocFailed ){
    /* Even though a malloc() has failed, the implementation of the
    ** user function may have called an sqlite3_result_XXX() function
    ** to return a value. The following call releases any resources
    ** associated with such a value.
    **
    ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
    ** fails also (the if(...) statement above). But if people are
    ** misusing sqlite, they have bigger problems than a leaked value.
    */
    sqlite3VdbeMemRelease(&ctx.s);
    goto no_mem;
  }

  /* If any auxiliary data functions have been called by this user function,
  ** immediately call the destructor for any non-static values.
  */
  if( ctx.pVdbeFunc ){
    sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
    pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
    pOp->p4type = P4_VDBEFUNC;
  }

  /* If the function returned an error, throw an exception */
  if( ctx.isError ){
    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
    rc = ctx.isError;
  }

  /* Copy the result of the function into register P3 */
  sqlite3VdbeChangeEncoding(&ctx.s, encoding);
  sqlite3VdbeMemMove(pOut, &ctx.s);
  if( sqlite3VdbeMemTooBig(pOut) ){
    goto too_big;
  }
  REGISTER_TRACE(pOp->p3, pOut);
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: BitAnd P1 P2 P3 * *
**
** Take the bit-wise AND of the values in register P1 and P2 and
** store the result in register P3.
** If either input is NULL, the result is NULL.
*/
/* Opcode: BitOr P1 P2 P3 * *
**
** Take the bit-wise OR of the values in register P1 and P2 and
** store the result in register P3.
** If either input is NULL, the result is NULL.
*/
/* Opcode: ShiftLeft P1 P2 P3 * *
**
** Shift the integer value in register P2 to the left by the
** number of bits specified by the integer in regiser P1.
** Store the result in register P3.
** If either input is NULL, the result is NULL.
*/
/* Opcode: ShiftRight P1 P2 P3 * *
**
** Shift the integer value in register P2 to the right by the
** number of bits specified by the integer in register P1.
** Store the result in register P3.
** If either input is NULL, the result is NULL.
*/
case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
  i64 a;
  i64 b;

  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
    sqlite3VdbeMemSetNull(pOut);
    break;
  }
  a = sqlite3VdbeIntValue(pIn2);
  b = sqlite3VdbeIntValue(pIn1);
  switch( pOp->opcode ){
    case OP_BitAnd:      a &= b;     break;
    case OP_BitOr:       a |= b;     break;
    case OP_ShiftLeft:   a <<= b;    break;
    default:  assert( pOp->opcode==OP_ShiftRight );
                         a >>= b;    break;
  }
  pOut->u.i = a;
  MemSetTypeFlag(pOut, MEM_Int);
  break;
}

/* Opcode: AddImm  P1 P2 * * *
** 
** Add the constant P2 to the value in register P1.
** The result is always an integer.
**
** To force any register to be an integer, just add 0.
*/
case OP_AddImm: {            /* in1 */
  sqlite3VdbeMemIntegerify(pIn1);
  pIn1->u.i += pOp->p2;
  break;
}

/* Opcode: MustBeInt P1 P2 * * *
** 
** Force the value in register P1 to be an integer.  If the value
** in P1 is not an integer and cannot be converted into an integer
** without data loss, then jump immediately to P2, or if P2==0
** raise an SQLITE_MISMATCH exception.
*/
case OP_MustBeInt: {            /* jump, in1 */
  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  if( (pIn1->flags & MEM_Int)==0 ){
    if( pOp->p2==0 ){
      rc = SQLITE_MISMATCH;
      goto abort_due_to_error;
    }else{
      pc = pOp->p2 - 1;
    }
  }else{
    MemSetTypeFlag(pIn1, MEM_Int);
  }
  break;
}

/* Opcode: RealAffinity P1 * * * *
**
** If register P1 holds an integer convert it to a real value.
**
** This opcode is used when extracting information from a column that
** has REAL affinity.  Such column values may still be stored as
** integers, for space efficiency, but after extraction we want them
** to have only a real value.
*/
case OP_RealAffinity: {                  /* in1 */
  if( pIn1->flags & MEM_Int ){
    sqlite3VdbeMemRealify(pIn1);
  }
  break;
}

#ifndef SQLITE_OMIT_CAST
/* Opcode: ToText P1 * * * *
**
** Force the value in register P1 to be text.
** If the value is numeric, convert it to a string using the
** equivalent of printf().  Blob values are unchanged and
** are afterwards simply interpreted as text.
**
** A NULL value is not changed by this routine.  It remains NULL.
*/
case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
  if( pIn1->flags & MEM_Null ) break;
  assert( MEM_Str==(MEM_Blob>>3) );
  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  rc = ExpandBlob(pIn1);
  assert( pIn1->flags & MEM_Str || db->mallocFailed );
  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  UPDATE_MAX_BLOBSIZE(pIn1);
  break;
}

/* Opcode: ToBlob P1 * * * *
**
** Force the value in register P1 to be a BLOB.
** If the value is numeric, convert it to a string first.
** Strings are simply reinterpreted as blobs with no change
** to the underlying data.
**
** A NULL value is not changed by this routine.  It remains NULL.
*/
case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
  if( pIn1->flags & MEM_Null ) break;
  if( (pIn1->flags & MEM_Blob)==0 ){
    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
    assert( pIn1->flags & MEM_Str || db->mallocFailed );
    MemSetTypeFlag(pIn1, MEM_Blob);
  }else{
    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  }
  UPDATE_MAX_BLOBSIZE(pIn1);
  break;
}

/* Opcode: ToNumeric P1 * * * *
**
** Force the value in register P1 to be numeric (either an
** integer or a floating-point number.)
** If the value is text or blob, try to convert it to an using the
** equivalent of atoi() or atof() and store 0 if no such conversion 
** is possible.
**
** A NULL value is not changed by this routine.  It remains NULL.
*/
case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
    sqlite3VdbeMemNumerify(pIn1);
  }
  break;
}
#endif /* SQLITE_OMIT_CAST */

/* Opcode: ToInt P1 * * * *
**
** Force the value in register P1 be an integer.  If
** The value is currently a real number, drop its fractional part.
** If the value is text or blob, try to convert it to an integer using the
** equivalent of atoi() and store 0 if no such conversion is possible.
**
** A NULL value is not changed by this routine.  It remains NULL.
*/
case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
  if( (pIn1->flags & MEM_Null)==0 ){
    sqlite3VdbeMemIntegerify(pIn1);
  }
  break;
}

#ifndef SQLITE_OMIT_CAST
/* Opcode: ToReal P1 * * * *
**
** Force the value in register P1 to be a floating point number.
** If The value is currently an integer, convert it.
** If the value is text or blob, try to convert it to an integer using the
** equivalent of atoi() and store 0.0 if no such conversion is possible.
**
** A NULL value is not changed by this routine.  It remains NULL.
*/
case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
  if( (pIn1->flags & MEM_Null)==0 ){
    sqlite3VdbeMemRealify(pIn1);
  }
  break;
}
#endif /* SQLITE_OMIT_CAST */

/* Opcode: Lt P1 P2 P3 P4 P5
**
** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
** jump to address P2.  
**
** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
** bit is clear then fall thru if either operand is NULL.
**
** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
** to coerce both inputs according to this affinity before the
** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
** affinity is used. Note that the affinity conversions are stored
** back into the input registers P1 and P3.  So this opcode can cause
** persistent changes to registers P1 and P3.
**
** Once any conversions have taken place, and neither value is NULL, 
** the values are compared. If both values are blobs then memcmp() is
** used to determine the results of the comparison.  If both values
** are text, then the appropriate collating function specified in
** P4 is  used to do the comparison.  If P4 is not specified then
** memcmp() is used to compare text string.  If both values are
** numeric, then a numeric comparison is used. If the two values
** are of different types, then numbers are considered less than
** strings and strings are considered less than blobs.
**
** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
** store a boolean result (either 0, or 1, or NULL) in register P2.
*/
/* Opcode: Ne P1 P2 P3 P4 P5
**
** This works just like the Lt opcode except that the jump is taken if
** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
** additional information.
**
** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
** true or false and is never NULL.  If both operands are NULL then the result
** of comparison is false.  If either operand is NULL then the result is true.
** If neither operand is NULL the the result is the same as it would be if
** the SQLITE_NULLEQ flag were omitted from P5.
*/
/* Opcode: Eq P1 P2 P3 P4 P5
**
** This works just like the Lt opcode except that the jump is taken if
** the operands in registers P1 and P3 are equal.
** See the Lt opcode for additional information.
**
** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
** true or false and is never NULL.  If both operands are NULL then the result
** of comparison is true.  If either operand is NULL then the result is false.
** If neither operand is NULL the the result is the same as it would be if
** the SQLITE_NULLEQ flag were omitted from P5.
*/
/* Opcode: Le P1 P2 P3 P4 P5
**
** This works just like the Lt opcode except that the jump is taken if
** the content of register P3 is less than or equal to the content of
** register P1.  See the Lt opcode for additional information.
*/
/* Opcode: Gt P1 P2 P3 P4 P5
**
** This works just like the Lt opcode except that the jump is taken if
** the content of register P3 is greater than the content of
** register P1.  See the Lt opcode for additional information.
*/
/* Opcode: Ge P1 P2 P3 P4 P5
**
** This works just like the Lt opcode except that the jump is taken if
** the content of register P3 is greater than or equal to the content of
** register P1.  See the Lt opcode for additional information.
*/
case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
case OP_Le:               /* same as TK_LE, jump, in1, in3 */
case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
  int res;            /* Result of the comparison of pIn1 against pIn3 */
  char affinity;      /* Affinity to use for comparison */

  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
    /* One or both operands are NULL */
    if( pOp->p5 & SQLITE_NULLEQ ){
      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
      ** or not both operands are null.
      */
      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
      res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
    }else{
      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
      ** then the result is always NULL.
      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
      */
      if( pOp->p5 & SQLITE_STOREP2 ){
        pOut = &p->aMem[pOp->p2];
        MemSetTypeFlag(pOut, MEM_Null);
        REGISTER_TRACE(pOp->p2, pOut);
      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
        pc = pOp->p2-1;
      }
      break;
    }
  }else{
    /* Neither operand is NULL.  Do a comparison. */
    affinity = pOp->p5 & SQLITE_AFF_MASK;
    if( affinity ){
      applyAffinity(pIn1, affinity, encoding);
      applyAffinity(pIn3, affinity, encoding);
      if( db->mallocFailed ) goto no_mem;
    }

    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
    ExpandBlob(pIn1);
    ExpandBlob(pIn3);
    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  }
  switch( pOp->opcode ){
    case OP_Eq:    res = res==0;     break;
    case OP_Ne:    res = res!=0;     break;
    case OP_Lt:    res = res<0;      break;
    case OP_Le:    res = res<=0;     break;
    case OP_Gt:    res = res>0;      break;
    default:       res = res>=0;     break;
  }

  if( pOp->p5 & SQLITE_STOREP2 ){
    pOut = &p->aMem[pOp->p2];
    MemSetTypeFlag(pOut, MEM_Int);
    pOut->u.i = res;
    REGISTER_TRACE(pOp->p2, pOut);
  }else if( res ){
    pc = pOp->p2-1;
  }
  break;
}

/* Opcode: Permutation * * * P4 *
**
** Set the permutation used by the OP_Compare operator to be the array
** of integers in P4.
**
** The permutation is only valid until the next OP_Permutation, OP_Compare,
** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
** immediately prior to the OP_Compare.
*/
case OP_Permutation: {
  assert( pOp->p4type==P4_INTARRAY );
  assert( pOp->p4.ai );
  aPermute = pOp->p4.ai;
  break;
}

/* Opcode: Compare P1 P2 P3 P4 *
**
** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
** the comparison for use by the next OP_Jump instruct.
**
** P4 is a KeyInfo structure that defines collating sequences and sort
** orders for the comparison.  The permutation applies to registers
** only.  The KeyInfo elements are used sequentially.
**
** The comparison is a sort comparison, so NULLs compare equal,
** NULLs are less than numbers, numbers are less than strings,
** and strings are less than blobs.
*/
case OP_Compare: {
  int n;
  int i;
  int p1;
  int p2;
  const KeyInfo *pKeyInfo;
  int idx;
  CollSeq *pColl;    /* Collating sequence to use on this term */
  int bRev;          /* True for DESCENDING sort order */

  n = pOp->p3;
  pKeyInfo = pOp->p4.pKeyInfo;
  assert( n>0 );
  assert( pKeyInfo!=0 );
  p1 = pOp->p1;
  p2 = pOp->p2;
#if SQLITE_DEBUG
  if( aPermute ){
    int k, mx = 0;
    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
    assert( p1>0 && p1+mx<=p->nMem+1 );
    assert( p2>0 && p2+mx<=p->nMem+1 );
  }else{
    assert( p1>0 && p1+n<=p->nMem+1 );
    assert( p2>0 && p2+n<=p->nMem+1 );
  }
#endif /* SQLITE_DEBUG */
  for(i=0; i<n; i++){
    idx = aPermute ? aPermute[i] : i;
    REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
    REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
    assert( i<pKeyInfo->nField );
    pColl = pKeyInfo->aColl[i];
    bRev = pKeyInfo->aSortOrder[i];
    iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
    if( iCompare ){
      if( bRev ) iCompare = -iCompare;
      break;
    }
  }
  aPermute = 0;
  break;
}

/* Opcode: Jump P1 P2 P3 * *
**
** Jump to the instruction at address P1, P2, or P3 depending on whether
** in the most recent OP_Compare instruction the P1 vector was less than
** equal to, or greater than the P2 vector, respectively.
*/
case OP_Jump: {             /* jump */
  if( iCompare<0 ){
    pc = pOp->p1 - 1;
  }else if( iCompare==0 ){
    pc = pOp->p2 - 1;
  }else{
    pc = pOp->p3 - 1;
  }
  break;
}

/* Opcode: And P1 P2 P3 * *
**
** Take the logical AND of the values in registers P1 and P2 and
** write the result into register P3.
**
** If either P1 or P2 is 0 (false) then the result is 0 even if
** the other input is NULL.  A NULL and true or two NULLs give
** a NULL output.
*/
/* Opcode: Or P1 P2 P3 * *
**
** Take the logical OR of the values in register P1 and P2 and
** store the answer in register P3.
**
** If either P1 or P2 is nonzero (true) then the result is 1 (true)
** even if the other input is NULL.  A NULL and false or two NULLs
** give a NULL output.
*/
case OP_And:              /* same as TK_AND, in1, in2, out3 */
case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */

  if( pIn1->flags & MEM_Null ){
    v1 = 2;
  }else{
    v1 = sqlite3VdbeIntValue(pIn1)!=0;
  }
  if( pIn2->flags & MEM_Null ){
    v2 = 2;
  }else{
    v2 = sqlite3VdbeIntValue(pIn2)!=0;
  }
  if( pOp->opcode==OP_And ){
    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
    v1 = and_logic[v1*3+v2];
  }else{
    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
    v1 = or_logic[v1*3+v2];
  }
  if( v1==2 ){
    MemSetTypeFlag(pOut, MEM_Null);
  }else{
    pOut->u.i = v1;
    MemSetTypeFlag(pOut, MEM_Int);
  }
  break;
}

/* Opcode: Not P1 P2 * * *
**
** Interpret the value in register P1 as a boolean value.  Store the
** boolean complement in register P2.  If the value in register P1 is 
** NULL, then a NULL is stored in P2.
*/
case OP_Not: {                /* same as TK_NOT, in1 */
  pOut = &p->aMem[pOp->p2];
  if( pIn1->flags & MEM_Null ){
    sqlite3VdbeMemSetNull(pOut);
  }else{
    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  }
  break;
}

/* Opcode: BitNot P1 P2 * * *
**
** Interpret the content of register P1 as an integer.  Store the
** ones-complement of the P1 value into register P2.  If P1 holds
** a NULL then store a NULL in P2.
*/
case OP_BitNot: {             /* same as TK_BITNOT, in1 */
  pOut = &p->aMem[pOp->p2];
  if( pIn1->flags & MEM_Null ){
    sqlite3VdbeMemSetNull(pOut);
  }else{
    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  }
  break;
}

/* Opcode: If P1 P2 P3 * *
**
** Jump to P2 if the value in register P1 is true.  The value is
** is considered true if it is numeric and non-zero.  If the value
** in P1 is NULL then take the jump if P3 is true.
*/
/* Opcode: IfNot P1 P2 P3 * *
**
** Jump to P2 if the value in register P1 is False.  The value is
** is considered true if it has a numeric value of zero.  If the value
** in P1 is NULL then take the jump if P3 is true.
*/
case OP_If:                 /* jump, in1 */
case OP_IfNot: {            /* jump, in1 */
  int c;
  if( pIn1->flags & MEM_Null ){
    c = pOp->p3;
  }else{
#ifdef SQLITE_OMIT_FLOATING_POINT
    c = sqlite3VdbeIntValue(pIn1)!=0;
#else
    c = sqlite3VdbeRealValue(pIn1)!=0.0;
#endif
    if( pOp->opcode==OP_IfNot ) c = !c;
  }
  if( c ){
    pc = pOp->p2-1;
  }
  break;
}

/* Opcode: IsNull P1 P2 * * *
**
** Jump to P2 if the value in register P1 is NULL.
*/
case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
  if( (pIn1->flags & MEM_Null)!=0 ){
    pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: NotNull P1 P2 * * *
**
** Jump to P2 if the value in register P1 is not NULL.  
*/
case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
  if( (pIn1->flags & MEM_Null)==0 ){
    pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: Column P1 P2 P3 P4 P5
**
** Interpret the data that cursor P1 points to as a structure built using
** the MakeRecord instruction.  (See the MakeRecord opcode for additional
** information about the format of the data.)  Extract the P2-th column
** from this record.  If there are less that (P2+1) 
** values in the record, extract a NULL.
**
** The value extracted is stored in register P3.
**
** If the column contains fewer than P2 fields, then extract a NULL.  Or,
** if the P4 argument is a P4_MEM use the value of the P4 argument as
** the result.
**
** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
** then the cache of the cursor is reset prior to extracting the column.
** The first OP_Column against a pseudo-table after the value of the content
** register has changed should have this bit set.
*/
case OP_Column: {
  u32 payloadSize;   /* Number of bytes in the record */
  i64 payloadSize64; /* Number of bytes in the record */
  int p1;            /* P1 value of the opcode */
  int p2;            /* column number to retrieve */
  VdbeCursor *pC;    /* The VDBE cursor */
  char *zRec;        /* Pointer to complete record-data */
  BtCursor *pCrsr;   /* The BTree cursor */
  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
  int nField;        /* number of fields in the record */
  int len;           /* The length of the serialized data for the column */
  int i;             /* Loop counter */
  char *zData;       /* Part of the record being decoded */
  Mem *pDest;        /* Where to write the extracted value */
  Mem sMem;          /* For storing the record being decoded */
  u8 *zIdx;          /* Index into header */
  u8 *zEndHdr;       /* Pointer to first byte after the header */
  u32 offset;        /* Offset into the data */
  u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
  int szHdr;         /* Size of the header size field at start of record */
  int avail;         /* Number of bytes of available data */
  Mem *pReg;         /* PseudoTable input register */


  p1 = pOp->p1;
  p2 = pOp->p2;
  pC = 0;
  memset(&sMem, 0, sizeof(sMem));
  assert( p1<p->nCursor );
  assert( pOp->p3>0 && pOp->p3<=p->nMem );
  pDest = &p->aMem[pOp->p3];
  MemSetTypeFlag(pDest, MEM_Null);
  zRec = 0;

  /* This block sets the variable payloadSize to be the total number of
  ** bytes in the record.
  **
  ** zRec is set to be the complete text of the record if it is available.
  ** The complete record text is always available for pseudo-tables
  ** If the record is stored in a cursor, the complete record text
  ** might be available in the  pC->aRow cache.  Or it might not be.
  ** If the data is unavailable,  zRec is set to NULL.
  **
  ** We also compute the number of columns in the record.  For cursors,
  ** the number of columns is stored in the VdbeCursor.nField element.
  */
  pC = p->apCsr[p1];
  assert( pC!=0 );
#ifndef SQLITE_OMIT_VIRTUALTABLE
  assert( pC->pVtabCursor==0 );
#endif
  pCrsr = pC->pCursor;
  if( pCrsr!=0 ){
    /* The record is stored in a B-Tree */
    rc = sqlite3VdbeCursorMoveto(pC);
    if( rc ) goto abort_due_to_error;
    if( pC->nullRow ){
      payloadSize = 0;
    }else if( pC->cacheStatus==p->cacheCtr ){
      payloadSize = pC->payloadSize;
      zRec = (char*)pC->aRow;
    }else if( pC->isIndex ){
      assert( sqlite3BtreeCursorIsValid(pCrsr) );
      rc = sqlite3BtreeKeySize(pCrsr, &payloadSize64);
      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
      ** payload size, so it is impossible for payloadSize64 to be
      ** larger than 32 bits. */
      assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
      payloadSize = (u32)payloadSize64;
    }else{
      assert( sqlite3BtreeCursorIsValid(pCrsr) );
      rc = sqlite3BtreeDataSize(pCrsr, &payloadSize);
      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
    }
  }else if( pC->pseudoTableReg>0 ){
    pReg = &p->aMem[pC->pseudoTableReg];
    assert( pReg->flags & MEM_Blob );
    payloadSize = pReg->n;
    zRec = pReg->z;
    pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
    assert( payloadSize==0 || zRec!=0 );
  }else{
    /* Consider the row to be NULL */
    payloadSize = 0;
  }

  /* If payloadSize is 0, then just store a NULL */
  if( payloadSize==0 ){
    assert( pDest->flags&MEM_Null );
    goto op_column_out;
  }
  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  if( payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
    goto too_big;
  }

  nField = pC->nField;
  assert( p2<nField );

  /* Read and parse the table header.  Store the results of the parse
  ** into the record header cache fields of the cursor.
  */
  aType = pC->aType;
  if( pC->cacheStatus==p->cacheCtr ){
    aOffset = pC->aOffset;
  }else{
    assert(aType);
    avail = 0;
    pC->aOffset = aOffset = &aType[nField];
    pC->payloadSize = payloadSize;
    pC->cacheStatus = p->cacheCtr;

    /* Figure out how many bytes are in the header */
    if( zRec ){
      zData = zRec;
    }else{
      if( pC->isIndex ){
        zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
      }else{
        zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
      }
      /* If KeyFetch()/DataFetch() managed to get the entire payload,
      ** save the payload in the pC->aRow cache.  That will save us from
      ** having to make additional calls to fetch the content portion of
      ** the record.
      */
      assert( avail>=0 );
      if( payloadSize <= (u32)avail ){
        zRec = zData;
        pC->aRow = (u8*)zData;
      }else{
        pC->aRow = 0;
      }
    }
    /* The following assert is true in all cases accept when
    ** the database file has been corrupted externally.
    **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
    szHdr = getVarint32((u8*)zData, offset);

    /* Make sure a corrupt database has not given us an oversize header.
    ** Do this now to avoid an oversize memory allocation.
    **
    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
    ** types use so much data space that there can only be 4096 and 32 of
    ** them, respectively.  So the maximum header length results from a
    ** 3-byte type for each of the maximum of 32768 columns plus three
    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
    */
    if( offset > 98307 ){
      rc = SQLITE_CORRUPT_BKPT;
      goto op_column_out;
    }

    /* Compute in len the number of bytes of data we need to read in order
    ** to get nField type values.  offset is an upper bound on this.  But
    ** nField might be significantly less than the true number of columns
    ** in the table, and in that case, 5*nField+3 might be smaller than offset.
    ** We want to minimize len in order to limit the size of the memory
    ** allocation, especially if a corrupt database file has caused offset
    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
    ** still exceed Robson memory allocation limits on some configurations.
    ** On systems that cannot tolerate large memory allocations, nField*5+3
    ** will likely be much smaller since nField will likely be less than
    ** 20 or so.  This insures that Robson memory allocation limits are
    ** not exceeded even for corrupt database files.
    */
    len = nField*5 + 3;
    if( len > (int)offset ) len = (int)offset;

    /* The KeyFetch() or DataFetch() above are fast and will get the entire
    ** record header in most cases.  But they will fail to get the complete
    ** record header if the record header does not fit on a single page
    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
    ** acquire the complete header text.
    */
    if( !zRec && avail<len ){
      sMem.flags = 0;
      sMem.db = 0;
      rc = sqlite3VdbeMemFromBtree(pCrsr, 0, len, pC->isIndex, &sMem);
      if( rc!=SQLITE_OK ){
        goto op_column_out;
      }
      zData = sMem.z;
    }
    zEndHdr = (u8 *)&zData[len];
    zIdx = (u8 *)&zData[szHdr];

    /* Scan the header and use it to fill in the aType[] and aOffset[]
    ** arrays.  aType[i] will contain the type integer for the i-th
    ** column and aOffset[i] will contain the offset from the beginning
    ** of the record to the start of the data for the i-th column
    */
    offset64 = offset;
    for(i=0; i<nField; i++){
      if( zIdx<zEndHdr ){
        aOffset[i] = (u32)offset64;
        zIdx += getVarint32(zIdx, aType[i]);
        offset64 += sqlite3VdbeSerialTypeLen(aType[i]);
      }else{
        /* If i is less that nField, then there are less fields in this
        ** record than SetNumColumns indicated there are columns in the
        ** table. Set the offset for any extra columns not present in
        ** the record to 0. This tells code below to store a NULL
        ** instead of deserializing a value from the record.
        */
        aOffset[i] = 0;
      }
    }
    sqlite3VdbeMemRelease(&sMem);
    sMem.flags = MEM_Null;

    /* If we have read more header data than was contained in the header,
    ** or if the end of the last field appears to be past the end of the
    ** record, or if the end of the last field appears to be before the end
    ** of the record (when all fields present), then we must be dealing 
    ** with a corrupt database.
    */
    if( (zIdx > zEndHdr)|| (offset64 > payloadSize)
     || (zIdx==zEndHdr && offset64!=(u64)payloadSize) ){
      rc = SQLITE_CORRUPT_BKPT;
      goto op_column_out;
    }
  }

  /* Get the column information. If aOffset[p2] is non-zero, then 
  ** deserialize the value from the record. If aOffset[p2] is zero,
  ** then there are not enough fields in the record to satisfy the
  ** request.  In this case, set the value NULL or to P4 if P4 is
  ** a pointer to a Mem object.
  */
  if( aOffset[p2] ){
    assert( rc==SQLITE_OK );
    if( zRec ){
      sqlite3VdbeMemReleaseExternal(pDest);
      sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
    }else{
      len = sqlite3VdbeSerialTypeLen(aType[p2]);
      sqlite3VdbeMemMove(&sMem, pDest);
      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
      if( rc!=SQLITE_OK ){
        goto op_column_out;
      }
      zData = sMem.z;
      sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
    }
    pDest->enc = encoding;
  }else{
    if( pOp->p4type==P4_MEM ){
      sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
    }else{
      assert( pDest->flags&MEM_Null );
    }
  }

  /* If we dynamically allocated space to hold the data (in the
  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  ** dynamically allocated space over to the pDest structure.
  ** This prevents a memory copy.
  */
  if( sMem.zMalloc ){
    assert( sMem.z==sMem.zMalloc );
    assert( !(pDest->flags & MEM_Dyn) );
    assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
    pDest->flags &= ~(MEM_Ephem|MEM_Static);
    pDest->flags |= MEM_Term;
    pDest->z = sMem.z;
    pDest->zMalloc = sMem.zMalloc;
  }

  rc = sqlite3VdbeMemMakeWriteable(pDest);

op_column_out:
  UPDATE_MAX_BLOBSIZE(pDest);
  REGISTER_TRACE(pOp->p3, pDest);
  break;
}

/* Opcode: Affinity P1 P2 * P4 *
**
** Apply affinities to a range of P2 registers starting with P1.
**
** P4 is a string that is P2 characters long. The nth character of the
** string indicates the column affinity that should be used for the nth
** memory cell in the range.
*/
case OP_Affinity: {
  char *zAffinity;   /* The affinity to be applied */
  Mem *pData0;       /* First register to which to apply affinity */
  Mem *pLast;        /* Last register to which to apply affinity */
  Mem *pRec;         /* Current register */

  zAffinity = pOp->p4.z;
  pData0 = &p->aMem[pOp->p1];
  pLast = &pData0[pOp->p2-1];
  for(pRec=pData0; pRec<=pLast; pRec++){
    ExpandBlob(pRec);
    applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
  }
  break;
}

/* Opcode: MakeRecord P1 P2 P3 P4 *
**
** Convert P2 registers beginning with P1 into a single entry
** suitable for use as a data record in a database table or as a key
** in an index.  The details of the format are irrelevant as long as
** the OP_Column opcode can decode the record later.
** Refer to source code comments for the details of the record
** format.
**
** P4 may be a string that is P2 characters long.  The nth character of the
** string indicates the column affinity that should be used for the nth
** field of the index key.
**
** The mapping from character to affinity is given by the SQLITE_AFF_
** macros defined in sqliteInt.h.
**
** If P4 is NULL then all index fields have the affinity NONE.
*/
case OP_MakeRecord: {
  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
  Mem *pRec;             /* The new record */
  u64 nData;             /* Number of bytes of data space */
  int nHdr;              /* Number of bytes of header space */
  i64 nByte;             /* Data space required for this record */
  int nZero;             /* Number of zero bytes at the end of the record */
  int nVarint;           /* Number of bytes in a varint */
  u32 serial_type;       /* Type field */
  Mem *pData0;           /* First field to be combined into the record */
  Mem *pLast;            /* Last field of the record */
  int nField;            /* Number of fields in the record */
  char *zAffinity;       /* The affinity string for the record */
  int file_format;       /* File format to use for encoding */
  int i;                 /* Space used in zNewRecord[] */
  int len;               /* Length of a field */

  /* Assuming the record contains N fields, the record format looks
  ** like this:
  **
  ** ------------------------------------------------------------------------
  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
  ** ------------------------------------------------------------------------
  **
  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
  ** and so froth.
  **
  ** Each type field is a varint representing the serial type of the 
  ** corresponding data element (see sqlite3VdbeSerialType()). The
  ** hdr-size field is also a varint which is the offset from the beginning
  ** of the record to data0.
  */
  nData = 0;         /* Number of bytes of data space */
  nHdr = 0;          /* Number of bytes of header space */
  nByte = 0;         /* Data space required for this record */
  nZero = 0;         /* Number of zero bytes at the end of the record */
  nField = pOp->p1;
  zAffinity = pOp->p4.z;
  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem+1 );
  pData0 = &p->aMem[nField];
  nField = pOp->p2;
  pLast = &pData0[nField-1];
  file_format = p->minWriteFileFormat;

  /* Loop through the elements that will make up the record to figure
  ** out how much space is required for the new record.
  */
  for(pRec=pData0; pRec<=pLast; pRec++){
    if( zAffinity ){
      applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
    }
    if( pRec->flags&MEM_Zero && pRec->n>0 ){
      sqlite3VdbeMemExpandBlob(pRec);
    }
    serial_type = sqlite3VdbeSerialType(pRec, file_format);
    len = sqlite3VdbeSerialTypeLen(serial_type);
    nData += len;
    nHdr += sqlite3VarintLen(serial_type);
    if( pRec->flags & MEM_Zero ){
      /* Only pure zero-filled BLOBs can be input to this Opcode.
      ** We do not allow blobs with a prefix and a zero-filled tail. */
      nZero += pRec->u.nZero;
    }else if( len ){
      nZero = 0;
    }
  }

  /* Add the initial header varint and total the size */
  nHdr += nVarint = sqlite3VarintLen(nHdr);
  if( nVarint<sqlite3VarintLen(nHdr) ){
    nHdr++;
  }
  nByte = nHdr+nData-nZero;
  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    goto too_big;
  }

  /* Make sure the output register has a buffer large enough to store 
  ** the new record. The output register (pOp->p3) is not allowed to
  ** be one of the input registers (because the following call to
  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  */
  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  pOut = &p->aMem[pOp->p3];
  if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
    goto no_mem;
  }
  zNewRecord = (u8 *)pOut->z;

  /* Write the record */
  i = putVarint32(zNewRecord, nHdr);
  for(pRec=pData0; pRec<=pLast; pRec++){
    serial_type = sqlite3VdbeSerialType(pRec, file_format);
    i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
  }
  for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
    i += sqlite3VdbeSerialPut(&zNewRecord[i], (int)(nByte-i), pRec,file_format);
  }
  assert( i==nByte );

  assert( pOp->p3>0 && pOp->p3<=p->nMem );
  pOut->n = (int)nByte;
  pOut->flags = MEM_Blob | MEM_Dyn;
  pOut->xDel = 0;
  if( nZero ){
    pOut->u.nZero = nZero;
    pOut->flags |= MEM_Zero;
  }
  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
  REGISTER_TRACE(pOp->p3, pOut);
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Count P1 P2 * * *
**
** Store the number of entries (an integer value) in the table or index 
** opened by cursor P1 in register P2
*/
#ifndef SQLITE_OMIT_BTREECOUNT
case OP_Count: {         /* out2-prerelease */
  i64 nEntry;
  BtCursor *pCrsr;

  pCrsr = p->apCsr[pOp->p1]->pCursor;
  if( pCrsr ){
    rc = sqlite3BtreeCount(pCrsr, &nEntry);
  }else{
    nEntry = 0;
  }
  pOut->flags = MEM_Int;
  pOut->u.i = nEntry;
  break;
}
#endif

/* Opcode: Savepoint P1 * * P4 *
**
** Open, release or rollback the savepoint named by parameter P4, depending
** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
*/
case OP_Savepoint: {
  int p1;                         /* Value of P1 operand */
  char *zName;                    /* Name of savepoint */
  int nName;
  Savepoint *pNew;
  Savepoint *pSavepoint;
  Savepoint *pTmp;
  int iSavepoint;
  int ii;

  p1 = pOp->p1;
  zName = pOp->p4.z;

  /* Assert that the p1 parameter is valid. Also that if there is no open
  ** transaction, then there cannot be any savepoints. 
  */
  assert( db->pSavepoint==0 || db->autoCommit==0 );
  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  assert( checkSavepointCount(db) );

  if( p1==SAVEPOINT_BEGIN ){
    if( db->writeVdbeCnt>0 ){
      /* A new savepoint cannot be created if there are active write 
      ** statements (i.e. open read/write incremental blob handles).
      */
      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
        "SQL statements in progress");
      rc = SQLITE_BUSY;
    }else{
      nName = sqlite3Strlen30(zName);

      /* Create a new savepoint structure. */
      pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
      if( pNew ){
        pNew->zName = (char *)&pNew[1];
        memcpy(pNew->zName, zName, nName+1);
    
        /* If there is no open transaction, then mark this as a special
        ** "transaction savepoint". */
        if( db->autoCommit ){
          db->autoCommit = 0;
          db->isTransactionSavepoint = 1;
        }else{
          db->nSavepoint++;
        }
    
        /* Link the new savepoint into the database handle's list. */
        pNew->pNext = db->pSavepoint;
        db->pSavepoint = pNew;
        pNew->nDeferredCons = db->nDeferredCons;
      }
    }
  }else{
    iSavepoint = 0;

    /* Find the named savepoint. If there is no such savepoint, then an
    ** an error is returned to the user.  */
    for(
      pSavepoint = db->pSavepoint; 
      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
      pSavepoint = pSavepoint->pNext
    ){
      iSavepoint++;
    }
    if( !pSavepoint ){
      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
      rc = SQLITE_ERROR;
    }else if( 
        db->writeVdbeCnt>0 || (p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1) 
    ){
      /* It is not possible to release (commit) a savepoint if there are 
      ** active write statements. It is not possible to rollback a savepoint
      ** if there are any active statements at all.
      */
      sqlite3SetString(&p->zErrMsg, db, 
        "cannot %s savepoint - SQL statements in progress",
        (p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
      );
      rc = SQLITE_BUSY;
    }else{

      /* Determine whether or not this is a transaction savepoint. If so,
      ** and this is a RELEASE command, then the current transaction 
      ** is committed. 
      */
      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
      if( isTransaction && p1==SAVEPOINT_RELEASE ){
        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
          goto vdbe_return;
        }
        db->autoCommit = 1;
        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
          p->pc = pc;
          db->autoCommit = 0;
          p->rc = rc = SQLITE_BUSY;
          goto vdbe_return;
        }
        db->isTransactionSavepoint = 0;
        rc = p->rc;
      }else{
        iSavepoint = db->nSavepoint - iSavepoint - 1;
        for(ii=0; ii<db->nDb; ii++){
          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
          if( rc!=SQLITE_OK ){
            goto abort_due_to_error;
          }
        }
        if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
          sqlite3ExpirePreparedStatements(db);
          sqlite3ResetInternalSchema(db, 0);
        }
      }
  
      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
      ** savepoints nested inside of the savepoint being operated on. */
      while( db->pSavepoint!=pSavepoint ){
        pTmp = db->pSavepoint;
        db->pSavepoint = pTmp->pNext;
        sqlite3DbFree(db, pTmp);
        db->nSavepoint--;
      }

      /* If it is a RELEASE, then destroy the savepoint being operated on 
      ** too. If it is a ROLLBACK TO, then set the number of deferred 
      ** constraint violations present in the database to the value stored
      ** when the savepoint was created.  */
      if( p1==SAVEPOINT_RELEASE ){
        assert( pSavepoint==db->pSavepoint );
        db->pSavepoint = pSavepoint->pNext;
        sqlite3DbFree(db, pSavepoint);
        if( !isTransaction ){
          db->nSavepoint--;
        }
      }else{
        db->nDeferredCons = pSavepoint->nDeferredCons;
      }
    }
  }

  break;
}

/* Opcode: AutoCommit P1 P2 * * *
**
** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
** back any currently active btree transactions. If there are any active
** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
** there are active writing VMs or active VMs that use shared cache.
**
** This instruction causes the VM to halt.
*/
case OP_AutoCommit: {
  int desiredAutoCommit;
  int iRollback;
  int turnOnAC;

  desiredAutoCommit = pOp->p1;
  iRollback = pOp->p2;
  turnOnAC = desiredAutoCommit && !db->autoCommit;
  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  assert( desiredAutoCommit==1 || iRollback==0 );
  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */

  if( turnOnAC && iRollback && db->activeVdbeCnt>1 ){
    /* If this instruction implements a ROLLBACK and other VMs are
    ** still running, and a transaction is active, return an error indicating
    ** that the other VMs must complete first. 
    */
    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
        "SQL statements in progress");
    rc = SQLITE_BUSY;
  }else if( turnOnAC && !iRollback && db->writeVdbeCnt>0 ){
    /* If this instruction implements a COMMIT and other VMs are writing
    ** return an error indicating that the other VMs must complete first. 
    */
    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
        "SQL statements in progress");
    rc = SQLITE_BUSY;
  }else if( desiredAutoCommit!=db->autoCommit ){
    if( iRollback ){
      assert( desiredAutoCommit==1 );
      sqlite3RollbackAll(db);
      db->autoCommit = 1;
    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
      goto vdbe_return;
    }else{
      db->autoCommit = (u8)desiredAutoCommit;
      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
        p->pc = pc;
        db->autoCommit = (u8)(1-desiredAutoCommit);
        p->rc = rc = SQLITE_BUSY;
        goto vdbe_return;
      }
    }
    assert( db->nStatement==0 );
    sqlite3CloseSavepoints(db);
    if( p->rc==SQLITE_OK ){
      rc = SQLITE_DONE;
    }else{
      rc = SQLITE_ERROR;
    }
    goto vdbe_return;
  }else{
    sqlite3SetString(&p->zErrMsg, db,
        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
        (iRollback)?"cannot rollback - no transaction is active":
                   "cannot commit - no transaction is active"));
         
    rc = SQLITE_ERROR;
  }
  break;
}

/* Opcode: Transaction P1 P2 * * *
**
** Begin a transaction.  The transaction ends when a Commit or Rollback
** opcode is encountered.  Depending on the ON CONFLICT setting, the
** transaction might also be rolled back if an error is encountered.
**
** P1 is the index of the database file on which the transaction is
** started.  Index 0 is the main database file and index 1 is the
** file used for temporary tables.  Indices of 2 or more are used for
** attached databases.
**
** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
** obtained on the database file when a write-transaction is started.  No
** other process can start another write transaction while this transaction is
** underway.  Starting a write transaction also creates a rollback journal. A
** write transaction must be started before any changes can be made to the
** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
** on the file.
**
** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
** true (this flag is set if the Vdbe may modify more than one row and may
** throw an ABORT exception), a statement transaction may also be opened.
** More specifically, a statement transaction is opened iff the database
** connection is currently not in autocommit mode, or if there are other
** active statements. A statement transaction allows the affects of this
** VDBE to be rolled back after an error without having to roll back the
** entire transaction. If no error is encountered, the statement transaction
** will automatically commit when the VDBE halts.
**
** If P2 is zero, then a read-lock is obtained on the database file.
*/
case OP_Transaction: {
  Btree *pBt;

  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  pBt = db->aDb[pOp->p1].pBt;

  if( pBt ){
    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
    if( rc==SQLITE_BUSY ){
      p->pc = pc;
      p->rc = rc = SQLITE_BUSY;
      goto vdbe_return;
    }
    if( rc!=SQLITE_OK ){
      goto abort_due_to_error;
    }

    if( pOp->p2 && p->usesStmtJournal 
     && (db->autoCommit==0 || db->activeVdbeCnt>1) 
    ){
      assert( sqlite3BtreeIsInTrans(pBt) );
      if( p->iStatement==0 ){
        assert( db->nStatement>=0 && db->nSavepoint>=0 );
        db->nStatement++; 
        p->iStatement = db->nSavepoint + db->nStatement;
      }
      rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);

      /* Store the current value of the database handles deferred constraint
      ** counter. If the statement transaction needs to be rolled back,
      ** the value of this counter needs to be restored too.  */
      p->nStmtDefCons = db->nDeferredCons;
    }
  }
  break;
}

/* Opcode: ReadCookie P1 P2 P3 * *
**
** Read cookie number P3 from database P1 and write it into register P2.
** P3==1 is the schema version.  P3==2 is the database format.
** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
** the main database file and P1==1 is the database file used to store
** temporary tables.
**
** There must be a read-lock on the database (either a transaction
** must be started or there must be an open cursor) before
** executing this instruction.
*/
case OP_ReadCookie: {               /* out2-prerelease */
  int iMeta;
  int iDb;
  int iCookie;

  iDb = pOp->p1;
  iCookie = pOp->p3;
  assert( pOp->p3<SQLITE_N_BTREE_META );
  assert( iDb>=0 && iDb<db->nDb );
  assert( db->aDb[iDb].pBt!=0 );
  assert( (p->btreeMask & (1<<iDb))!=0 );

  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  pOut->u.i = iMeta;
  MemSetTypeFlag(pOut, MEM_Int);
  break;
}

/* Opcode: SetCookie P1 P2 P3 * *
**
** Write the content of register P3 (interpreted as an integer)
** into cookie number P2 of database P1.  P2==1 is the schema version.  
** P2==2 is the database format. P2==3 is the recommended pager cache 
** size, and so forth.  P1==0 is the main database file and P1==1 is the 
** database file used to store temporary tables.
**
** A transaction must be started before executing this opcode.
*/
case OP_SetCookie: {       /* in3 */
  Db *pDb;
  assert( pOp->p2<SQLITE_N_BTREE_META );
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  pDb = &db->aDb[pOp->p1];
  assert( pDb->pBt!=0 );
  sqlite3VdbeMemIntegerify(pIn3);
  /* See note about index shifting on OP_ReadCookie */
  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  if( pOp->p2==BTREE_SCHEMA_VERSION ){
    /* When the schema cookie changes, record the new cookie internally */
    pDb->pSchema->schema_cookie = (int)pIn3->u.i;
    db->flags |= SQLITE_InternChanges;
  }else if( pOp->p2==BTREE_FILE_FORMAT ){
    /* Record changes in the file format */
    pDb->pSchema->file_format = (u8)pIn3->u.i;
  }
  if( pOp->p1==1 ){
    /* Invalidate all prepared statements whenever the TEMP database
    ** schema is changed.  Ticket #1644 */
    sqlite3ExpirePreparedStatements(db);
    p->expired = 0;
  }
  break;
}

/* Opcode: VerifyCookie P1 P2 *
**
** Check the value of global database parameter number 0 (the
** schema version) and make sure it is equal to P2.  
** P1 is the database number which is 0 for the main database file
** and 1 for the file holding temporary tables and some higher number
** for auxiliary databases.
**
** The cookie changes its value whenever the database schema changes.
** This operation is used to detect when that the cookie has changed
** and that the current process needs to reread the schema.
**
** Either a transaction needs to have been started or an OP_Open needs
** to be executed (to establish a read lock) before this opcode is
** invoked.
*/
case OP_VerifyCookie: {
  int iMeta;
  Btree *pBt;
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  pBt = db->aDb[pOp->p1].pBt;
  if( pBt ){
    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  }else{
    iMeta = 0;
  }
  if( iMeta!=pOp->p2 ){
    sqlite3DbFree(db, p->zErrMsg);
    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
    /* If the schema-cookie from the database file matches the cookie 
    ** stored with the in-memory representation of the schema, do
    ** not reload the schema from the database file.
    **
    ** If virtual-tables are in use, this is not just an optimization.
    ** Often, v-tables store their data in other SQLite tables, which
    ** are queried from within xNext() and other v-table methods using
    ** prepared queries. If such a query is out-of-date, we do not want to
    ** discard the database schema, as the user code implementing the
    ** v-table would have to be ready for the sqlite3_vtab structure itself
    ** to be invalidated whenever sqlite3_step() is called from within 
    ** a v-table method.
    */
    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
      sqlite3ResetInternalSchema(db, pOp->p1);
    }

    sqlite3ExpirePreparedStatements(db);
    rc = SQLITE_SCHEMA;
  }
  break;
}

/* Opcode: OpenRead P1 P2 P3 P4 P5
**
** Open a read-only cursor for the database table whose root page is
** P2 in a database file.  The database file is determined by P3. 
** P3==0 means the main database, P3==1 means the database used for 
** temporary tables, and P3>1 means used the corresponding attached
** database.  Give the new cursor an identifier of P1.  The P1
** values need not be contiguous but all P1 values should be small integers.
** It is an error for P1 to be negative.
**
** If P5!=0 then use the content of register P2 as the root page, not
** the value of P2 itself.
**
** There will be a read lock on the database whenever there is an
** open cursor.  If the database was unlocked prior to this instruction
** then a read lock is acquired as part of this instruction.  A read
** lock allows other processes to read the database but prohibits
** any other process from modifying the database.  The read lock is
** released when all cursors are closed.  If this instruction attempts
** to get a read lock but fails, the script terminates with an
** SQLITE_BUSY error code.
**
** The P4 value may be either an integer (P4_INT32) or a pointer to
** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
** structure, then said structure defines the content and collating 
** sequence of the index being opened. Otherwise, if P4 is an integer 
** value, it is set to the number of columns in the table.
**
** See also OpenWrite.
*/
/* Opcode: OpenWrite P1 P2 P3 P4 P5
**
** Open a read/write cursor named P1 on the table or index whose root
** page is P2.  Or if P5!=0 use the content of register P2 to find the
** root page.
**
** The P4 value may be either an integer (P4_INT32) or a pointer to
** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
** structure, then said structure defines the content and collating 
** sequence of the index being opened. Otherwise, if P4 is an integer 
** value, it is set to the number of columns in the table, or to the
** largest index of any column of the table that is actually used.
**
** This instruction works just like OpenRead except that it opens the cursor
** in read/write mode.  For a given table, there can be one or more read-only
** cursors or a single read/write cursor but not both.
**
** See also OpenRead.
*/
case OP_OpenRead:
case OP_OpenWrite: {
  int nField;
  KeyInfo *pKeyInfo;
  int p2;
  int iDb;
  int wrFlag;
  Btree *pX;
  VdbeCursor *pCur;
  Db *pDb;

  if( p->expired ){
    rc = SQLITE_ABORT;
    break;
  }

  nField = 0;
  pKeyInfo = 0;
  p2 = pOp->p2;
  iDb = pOp->p3;
  assert( iDb>=0 && iDb<db->nDb );
  assert( (p->btreeMask & (1<<iDb))!=0 );
  pDb = &db->aDb[iDb];
  pX = pDb->pBt;
  assert( pX!=0 );
  if( pOp->opcode==OP_OpenWrite ){
    wrFlag = 1;
    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
      p->minWriteFileFormat = pDb->pSchema->file_format;
    }
  }else{
    wrFlag = 0;
  }
  if( pOp->p5 ){
    assert( p2>0 );
    assert( p2<=p->nMem );
    pIn2 = &p->aMem[p2];
    sqlite3VdbeMemIntegerify(pIn2);
    p2 = (int)pIn2->u.i;
    /* The p2 value always comes from a prior OP_CreateTable opcode and
    ** that opcode will always set the p2 value to 2 or more or else fail.
    ** If there were a failure, the prepared statement would have halted
    ** before reaching this instruction. */
    if( NEVER(p2<2) ) {
      rc = SQLITE_CORRUPT_BKPT;
      goto abort_due_to_error;
    }
  }
  if( pOp->p4type==P4_KEYINFO ){
    pKeyInfo = pOp->p4.pKeyInfo;
    pKeyInfo->enc = ENC(p->db);
    nField = pKeyInfo->nField+1;
  }else if( pOp->p4type==P4_INT32 ){
    nField = pOp->p4.i;
  }
  assert( pOp->p1>=0 );
  pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
  if( pCur==0 ) goto no_mem;
  pCur->nullRow = 1;
  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  pCur->pKeyInfo = pKeyInfo;

  /* Since it performs no memory allocation or IO, the only values that
  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK. 
  ** SQLITE_EMPTY is only returned when attempting to open the table
  ** rooted at page 1 of a zero-byte database.  */
  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
  if( rc==SQLITE_EMPTY ){
    pCur->pCursor = 0;
    rc = SQLITE_OK;
  }

  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  ** SQLite used to check if the root-page flags were sane at this point
  ** and report database corruption if they were not, but this check has
  ** since moved into the btree layer.  */  
  pCur->isTable = pOp->p4type!=P4_KEYINFO;
  pCur->isIndex = !pCur->isTable;
  break;
}

/* Opcode: OpenEphemeral P1 P2 * P4 *
**
** Open a new cursor P1 to a transient table.
** The cursor is always opened read/write even if 
** the main database is read-only.  The transient or virtual
** table is deleted automatically when the cursor is closed.
**
** P2 is the number of columns in the virtual table.
** The cursor points to a BTree table if P4==0 and to a BTree index
** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
** that defines the format of keys in the index.
**
** This opcode was once called OpenTemp.  But that created
** confusion because the term "temp table", might refer either
** to a TEMP table at the SQL level, or to a table opened by
** this opcode.  Then this opcode was call OpenVirtual.  But
** that created confusion with the whole virtual-table idea.
*/
case OP_OpenEphemeral: {
  VdbeCursor *pCx;
  static const int openFlags = 
      SQLITE_OPEN_READWRITE |
      SQLITE_OPEN_CREATE |
      SQLITE_OPEN_EXCLUSIVE |
      SQLITE_OPEN_DELETEONCLOSE |
      SQLITE_OPEN_TRANSIENT_DB;

  assert( pOp->p1>=0 );
  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  if( pCx==0 ) goto no_mem;
  pCx->nullRow = 1;
  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
                           &pCx->pBt);
  if( rc==SQLITE_OK ){
    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  }
  if( rc==SQLITE_OK ){
    /* If a transient index is required, create it by calling
    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
    ** opening it. If a transient table is required, just use the
    ** automatically created table with root-page 1 (an INTKEY table).
    */
    if( pOp->p4.pKeyInfo ){
      int pgno;
      assert( pOp->p4type==P4_KEYINFO );
      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
      if( rc==SQLITE_OK ){
        assert( pgno==MASTER_ROOT+1 );
        rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
                                (KeyInfo*)pOp->p4.z, pCx->pCursor);
        pCx->pKeyInfo = pOp->p4.pKeyInfo;
        pCx->pKeyInfo->enc = ENC(p->db);
      }
      pCx->isTable = 0;
    }else{
      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
      pCx->isTable = 1;
    }
  }
  pCx->isIndex = !pCx->isTable;
  break;
}

/* Opcode: OpenPseudo P1 P2 P3 * *
**
** Open a new cursor that points to a fake table that contains a single
** row of data.  The content of that one row in the content of memory
** register P2.  In other words, cursor P1 becomes an alias for the 
** MEM_Blob content contained in register P2.
**
** A pseudo-table created by this opcode is used to hold the a single
** row output from the sorter so that the row can be decomposed into
** individual columns using the OP_Column opcode.  The OP_Column opcode
** is the only cursor opcode that works with a pseudo-table.
**
** P3 is the number of fields in the records that will be stored by
** the pseudo-table.
*/
case OP_OpenPseudo: {
  VdbeCursor *pCx;

  assert( pOp->p1>=0 );
  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  if( pCx==0 ) goto no_mem;
  pCx->nullRow = 1;
  pCx->pseudoTableReg = pOp->p2;
  pCx->isTable = 1;
  pCx->isIndex = 0;
  break;
}

/* Opcode: Close P1 * * * *
**
** Close a cursor previously opened as P1.  If P1 is not
** currently open, this instruction is a no-op.
*/
case OP_Close: {
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  p->apCsr[pOp->p1] = 0;
  break;
}

/* Opcode: SeekGe P1 P2 P3 P4 *
**
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
** use the value in register P3 as the key.  If cursor P1 refers 
** to an SQL index, then P3 is the first in an array of P4 registers 
** that are used as an unpacked index key. 
**
** Reposition cursor P1 so that  it points to the smallest entry that 
** is greater than or equal to the key value. If there are no records 
** greater than or equal to the key and P2 is not zero, then jump to P2.
**
** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
*/
/* Opcode: SeekGt P1 P2 P3 P4 *
**
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
** use the value in register P3 as a key. If cursor P1 refers 
** to an SQL index, then P3 is the first in an array of P4 registers 
** that are used as an unpacked index key. 
**
** Reposition cursor P1 so that  it points to the smallest entry that 
** is greater than the key value. If there are no records greater than 
** the key and P2 is not zero, then jump to P2.
**
** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
*/
/* Opcode: SeekLt P1 P2 P3 P4 * 
**
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
** use the value in register P3 as a key. If cursor P1 refers 
** to an SQL index, then P3 is the first in an array of P4 registers 
** that are used as an unpacked index key. 
**
** Reposition cursor P1 so that  it points to the largest entry that 
** is less than the key value. If there are no records less than 
** the key and P2 is not zero, then jump to P2.
**
** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
*/
/* Opcode: SeekLe P1 P2 P3 P4 *
**
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
** use the value in register P3 as a key. If cursor P1 refers 
** to an SQL index, then P3 is the first in an array of P4 registers 
** that are used as an unpacked index key. 
**
** Reposition cursor P1 so that it points to the largest entry that 
** is less than or equal to the key value. If there are no records 
** less than or equal to the key and P2 is not zero, then jump to P2.
**
** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
*/
case OP_SeekLt:         /* jump, in3 */
case OP_SeekLe:         /* jump, in3 */
case OP_SeekGe:         /* jump, in3 */
case OP_SeekGt: {       /* jump, in3 */
  int res;
  int oc;
  VdbeCursor *pC;
  UnpackedRecord r;
  int nField;
  i64 iKey;      /* The rowid we are to seek to */

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  assert( pOp->p2!=0 );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  assert( pC->pseudoTableReg==0 );
  if( pC->pCursor!=0 ){
    oc = pOp->opcode;
    pC->nullRow = 0;
    if( pC->isTable ){
      /* The input value in P3 might be of any type: integer, real, string,
      ** blob, or NULL.  But it needs to be an integer before we can do
      ** the seek, so covert it. */
      applyNumericAffinity(pIn3);
      iKey = sqlite3VdbeIntValue(pIn3);
      pC->rowidIsValid = 0;

      /* If the P3 value could not be converted into an integer without
      ** loss of information, then special processing is required... */
      if( (pIn3->flags & MEM_Int)==0 ){
        if( (pIn3->flags & MEM_Real)==0 ){
          /* If the P3 value cannot be converted into any kind of a number,
          ** then the seek is not possible, so jump to P2 */
          pc = pOp->p2 - 1;
          break;
        }
        /* If we reach this point, then the P3 value must be a floating
        ** point number. */
        assert( (pIn3->flags & MEM_Real)!=0 );

        if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){
          /* The P3 value is too large in magnitude to be expressed as an
          ** integer. */
          res = 1;
          if( pIn3->r<0 ){
            if( oc==OP_SeekGt || oc==OP_SeekGe ){
              rc = sqlite3BtreeFirst(pC->pCursor, &res);
              if( rc!=SQLITE_OK ) goto abort_due_to_error;
            }
          }else{
            if( oc==OP_SeekLt || oc==OP_SeekLe ){
              rc = sqlite3BtreeLast(pC->pCursor, &res);
              if( rc!=SQLITE_OK ) goto abort_due_to_error;
            }
          }
          if( res ){
            pc = pOp->p2 - 1;
          }
          break;
        }else if( oc==OP_SeekLt || oc==OP_SeekGe ){
          /* Use the ceiling() function to convert real->int */
          if( pIn3->r > (double)iKey ) iKey++;
        }else{
          /* Use the floor() function to convert real->int */
          assert( oc==OP_SeekLe || oc==OP_SeekGt );
          if( pIn3->r < (double)iKey ) iKey--;
        }
      } 
      rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
      if( rc!=SQLITE_OK ){
        goto abort_due_to_error;
      }
      if( res==0 ){
        pC->rowidIsValid = 1;
        pC->lastRowid = iKey;
      }
    }else{
      nField = pOp->p4.i;
      assert( pOp->p4type==P4_INT32 );
      assert( nField>0 );
      r.pKeyInfo = pC->pKeyInfo;
      r.nField = (u16)nField;
      if( oc==OP_SeekGt || oc==OP_SeekLe ){
        r.flags = UNPACKED_INCRKEY;
      }else{
        r.flags = 0;
      }
      r.aMem = &p->aMem[pOp->p3];
      rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
      if( rc!=SQLITE_OK ){
        goto abort_due_to_error;
      }
      pC->rowidIsValid = 0;
    }
    pC->deferredMoveto = 0;
    pC->cacheStatus = CACHE_STALE;
#ifdef SQLITE_TEST
    sqlite3_search_count++;
#endif
    if( oc==OP_SeekGe || oc==OP_SeekGt ){
      if( res<0 || (res==0 && oc==OP_SeekGt) ){
        rc = sqlite3BtreeNext(pC->pCursor, &res);
        if( rc!=SQLITE_OK ) goto abort_due_to_error;
        pC->rowidIsValid = 0;
      }else{
        res = 0;
      }
    }else{
      assert( oc==OP_SeekLt || oc==OP_SeekLe );
      if( res>0 || (res==0 && oc==OP_SeekLt) ){
        rc = sqlite3BtreePrevious(pC->pCursor, &res);
        if( rc!=SQLITE_OK ) goto abort_due_to_error;
        pC->rowidIsValid = 0;
      }else{
        /* res might be negative because the table is empty.  Check to
        ** see if this is the case.
        */
        res = sqlite3BtreeEof(pC->pCursor);
      }
    }
    assert( pOp->p2>0 );
    if( res ){
      pc = pOp->p2 - 1;
    }
  }else{
    /* This happens when attempting to open the sqlite3_master table
    ** for read access returns SQLITE_EMPTY. In this case always
    ** take the jump (since there are no records in the table).
    */
    pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: Seek P1 P2 * * *
**
** P1 is an open table cursor and P2 is a rowid integer.  Arrange
** for P1 to move so that it points to the rowid given by P2.
**
** This is actually a deferred seek.  Nothing actually happens until
** the cursor is used to read a record.  That way, if no reads
** occur, no unnecessary I/O happens.
*/
case OP_Seek: {    /* in2 */
  VdbeCursor *pC;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  if( ALWAYS(pC->pCursor!=0) ){
    assert( pC->isTable );
    pC->nullRow = 0;
    pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
    pC->rowidIsValid = 0;
    pC->deferredMoveto = 1;
  }
  break;
}
  

/* Opcode: Found P1 P2 P3 * *
**
** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
** If an entry that matches the value in register p3 exists in P1 then
** jump to P2.  If the P3 value does not match any entry in P1
** then fall thru.  The P1 cursor is left pointing at the matching entry
** if it exists.
**
** This instruction is used to implement the IN operator where the
** left-hand side is a SELECT statement.  P1 may be a true index, or it
** may be a temporary index that holds the results of the SELECT
** statement.   This instruction is also used to implement the
** DISTINCT keyword in SELECT statements.
**
** This instruction checks if index P1 contains a record for which 
** the first N serialized values exactly match the N serialized values
** in the record in register P3, where N is the total number of values in
** the P3 record (the P3 record is a prefix of the P1 record). 
**
** See also: NotFound, IsUnique, NotExists
*/
/* Opcode: NotFound P1 P2 P3 * *
**
** Register P3 holds a blob constructed by MakeRecord.  P1 is
** an index.  If no entry exists in P1 that matches the blob then jump
** to P2.  If an entry does existing, fall through.  The cursor is left
** pointing to the entry that matches.
**
** See also: Found, NotExists, IsUnique
*/
case OP_NotFound:       /* jump, in3 */
case OP_Found: {        /* jump, in3 */
  int alreadyExists;
  VdbeCursor *pC;
  int res;
  UnpackedRecord *pIdxKey;
  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];

#ifdef SQLITE_TEST
  sqlite3_found_count++;
#endif

  alreadyExists = 0;
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  if( ALWAYS(pC->pCursor!=0) ){

    assert( pC->isTable==0 );
    assert( pIn3->flags & MEM_Blob );
    ExpandBlob(pIn3);
    pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
                                      aTempRec, sizeof(aTempRec));
    if( pIdxKey==0 ){
      goto no_mem;
    }
    if( pOp->opcode==OP_Found ){
      pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
    }
    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
    if( rc!=SQLITE_OK ){
      break;
    }
    alreadyExists = (res==0);
    pC->deferredMoveto = 0;
    pC->cacheStatus = CACHE_STALE;
  }
  if( pOp->opcode==OP_Found ){
    if( alreadyExists ) pc = pOp->p2 - 1;
  }else{
    if( !alreadyExists ) pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: IsUnique P1 P2 P3 P4 *
**
** Cursor P1 is open on an index.  So it has no data and its key consists 
** of a record generated by OP_MakeRecord where the last field is the 
** rowid of the entry that the index refers to.
**
** The P3 register contains an integer record number. Call this record 
** number R. Register P4 is the first in a set of N contiguous registers
** that make up an unpacked index key that can be used with cursor P1.
** The value of N can be inferred from the cursor. N includes the rowid
** value appended to the end of the index record. This rowid value may
** or may not be the same as R.
**
** If any of the N registers beginning with register P4 contains a NULL
** value, jump immediately to P2.
**
** Otherwise, this instruction checks if cursor P1 contains an entry
** where the first (N-1) fields match but the rowid value at the end
** of the index entry is not R. If there is no such entry, control jumps
** to instruction P2. Otherwise, the rowid of the conflicting index
** entry is copied to register P3 and control falls through to the next
** instruction.
**
** See also: NotFound, NotExists, Found
*/
case OP_IsUnique: {        /* jump, in3 */
  u16 ii;
  VdbeCursor *pCx;
  BtCursor *pCrsr;
  u16 nField;
  Mem *aMem;
  UnpackedRecord r;                  /* B-Tree index search key */
  i64 R;                             /* Rowid stored in register P3 */

  aMem = &p->aMem[pOp->p4.i];
  /* Assert that the values of parameters P1 and P4 are in range. */
  assert( pOp->p4type==P4_INT32 );
  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );

  /* Find the index cursor. */
  pCx = p->apCsr[pOp->p1];
  assert( pCx->deferredMoveto==0 );
  pCx->seekResult = 0;
  pCx->cacheStatus = CACHE_STALE;
  pCrsr = pCx->pCursor;

  /* If any of the values are NULL, take the jump. */
  nField = pCx->pKeyInfo->nField;
  for(ii=0; ii<nField; ii++){
    if( aMem[ii].flags & MEM_Null ){
      pc = pOp->p2 - 1;
      pCrsr = 0;
      break;
    }
  }
  assert( (aMem[nField].flags & MEM_Null)==0 );

  if( pCrsr!=0 ){
    /* Populate the index search key. */
    r.pKeyInfo = pCx->pKeyInfo;
    r.nField = nField + 1;
    r.flags = UNPACKED_PREFIX_SEARCH;
    r.aMem = aMem;

    /* Extract the value of R from register P3. */
    sqlite3VdbeMemIntegerify(pIn3);
    R = pIn3->u.i;

    /* Search the B-Tree index. If no conflicting record is found, jump
    ** to P2. Otherwise, copy the rowid of the conflicting record to
    ** register P3 and fall through to the next instruction.  */
    rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &pCx->seekResult);
    if( (r.flags & UNPACKED_PREFIX_SEARCH) || r.rowid==R ){
      pc = pOp->p2 - 1;
    }else{
      pIn3->u.i = r.rowid;
    }
  }
  break;
}

/* Opcode: NotExists P1 P2 P3 * *
**
** Use the content of register P3 as a integer key.  If a record 
** with that key does not exist in table of P1, then jump to P2. 
** If the record does exist, then fall thru.  The cursor is left 
** pointing to the record if it exists.
**
** The difference between this operation and NotFound is that this
** operation assumes the key is an integer and that P1 is a table whereas
** NotFound assumes key is a blob constructed from MakeRecord and
** P1 is an index.
**
** See also: Found, NotFound, IsUnique
*/
case OP_NotExists: {        /* jump, in3 */
  VdbeCursor *pC;
  BtCursor *pCrsr;
  int res;
  u64 iKey;

  assert( pIn3->flags & MEM_Int );
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  assert( pC->isTable );
  assert( pC->pseudoTableReg==0 );
  pCrsr = pC->pCursor;
  if( pCrsr!=0 ){
    res = 0;
    iKey = pIn3->u.i;
    rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
    pC->lastRowid = pIn3->u.i;
    pC->rowidIsValid = res==0 ?1:0;
    pC->nullRow = 0;
    pC->cacheStatus = CACHE_STALE;
    pC->deferredMoveto = 0;
    if( res!=0 ){
      pc = pOp->p2 - 1;
      assert( pC->rowidIsValid==0 );
    }
    pC->seekResult = res;
  }else{
    /* This happens when an attempt to open a read cursor on the 
    ** sqlite_master table returns SQLITE_EMPTY.
    */
    pc = pOp->p2 - 1;
    assert( pC->rowidIsValid==0 );
    pC->seekResult = 0;
  }
  break;
}

/* Opcode: Sequence P1 P2 * * *
**
** Find the next available sequence number for cursor P1.
** Write the sequence number into register P2.
** The sequence number on the cursor is incremented after this
** instruction.  
*/
case OP_Sequence: {           /* out2-prerelease */
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  assert( p->apCsr[pOp->p1]!=0 );
  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  MemSetTypeFlag(pOut, MEM_Int);
  break;
}


/* Opcode: NewRowid P1 P2 P3 * *
**
** Get a new integer record number (a.k.a "rowid") used as the key to a table.
** The record number is not previously used as a key in the database
** table that cursor P1 points to.  The new record number is written
** written to register P2.
**
** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
** the largest previously generated record number. No new record numbers are
** allowed to be less than this value. When this value reaches its maximum, 
** a SQLITE_FULL error is generated. The P3 register is updated with the '
** generated record number. This P3 mechanism is used to help implement the
** AUTOINCREMENT feature.
*/
case OP_NewRowid: {           /* out2-prerelease */
  i64 v;                 /* The new rowid */
  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
  int res;               /* Result of an sqlite3BtreeLast() */
  int cnt;               /* Counter to limit the number of searches */
  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
  VdbeFrame *pFrame;     /* Root frame of VDBE */

  v = 0;
  res = 0;
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  if( NEVER(pC->pCursor==0) ){
    /* The zero initialization above is all that is needed */
  }else{
    /* The next rowid or record number (different terms for the same
    ** thing) is obtained in a two-step algorithm.
    **
    ** First we attempt to find the largest existing rowid and add one
    ** to that.  But if the largest existing rowid is already the maximum
    ** positive integer, we have to fall through to the second
    ** probabilistic algorithm
    **
    ** The second algorithm is to select a rowid at random and see if
    ** it already exists in the table.  If it does not exist, we have
    ** succeeded.  If the random rowid does exist, we select a new one
    ** and try again, up to 100 times.
    */
    assert( pC->isTable );
    cnt = 0;

#ifdef SQLITE_32BIT_ROWID
#   define MAX_ROWID 0x7fffffff
#else
    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
    ** to provide the constant while making all compilers happy.
    */
#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
#endif

    if( !pC->useRandomRowid ){
      v = sqlite3BtreeGetCachedRowid(pC->pCursor);
      if( v==0 ){
        rc = sqlite3BtreeLast(pC->pCursor, &res);
        if( rc!=SQLITE_OK ){
          goto abort_due_to_error;
        }
        if( res ){
          v = 1;
        }else{
          assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
          rc = sqlite3BtreeKeySize(pC->pCursor, &v);
          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
          if( v==MAX_ROWID ){
            pC->useRandomRowid = 1;
          }else{
            v++;
          }
        }
      }

#ifndef SQLITE_OMIT_AUTOINCREMENT
      if( pOp->p3 ){
        /* Assert that P3 is a valid memory cell. */
        assert( pOp->p3>0 );
        if( p->pFrame ){
          for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
          /* Assert that P3 is a valid memory cell. */
          assert( pOp->p3<=pFrame->nMem );
          pMem = &pFrame->aMem[pOp->p3];
        }else{
          /* Assert that P3 is a valid memory cell. */
          assert( pOp->p3<=p->nMem );
          pMem = &p->aMem[pOp->p3];
        }

        REGISTER_TRACE(pOp->p3, pMem);
        sqlite3VdbeMemIntegerify(pMem);
        assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
        if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
          rc = SQLITE_FULL;
          goto abort_due_to_error;
        }
        if( v<pMem->u.i+1 ){
          v = pMem->u.i + 1;
        }
        pMem->u.i = v;
      }
#endif

      sqlite3BtreeSetCachedRowid(pC->pCursor, v<MAX_ROWID ? v+1 : 0);
    }
    if( pC->useRandomRowid ){
      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
                             ** an AUTOINCREMENT table. */
      v = db->lastRowid;
      cnt = 0;
      do{
        if( cnt==0 && (v&0xffffff)==v ){
          v++;
        }else{
          sqlite3_randomness(sizeof(v), &v);
          if( cnt<5 ) v &= 0xffffff;
        }
        rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v, 0, &res);
        cnt++;
      }while( cnt<100 && rc==SQLITE_OK && res==0 );
      if( rc==SQLITE_OK && res==0 ){
        rc = SQLITE_FULL;
        goto abort_due_to_error;
      }
    }
    pC->rowidIsValid = 0;
    pC->deferredMoveto = 0;
    pC->cacheStatus = CACHE_STALE;
  }
  MemSetTypeFlag(pOut, MEM_Int);
  pOut->u.i = v;
  break;
}

/* Opcode: Insert P1 P2 P3 P4 P5
**
** Write an entry into the table of cursor P1.  A new entry is
** created if it doesn't already exist or the data for an existing
** entry is overwritten.  The data is the value MEM_Blob stored in register
** number P2. The key is stored in register P3. The key must
** be a MEM_Int.
**
** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
** then rowid is stored for subsequent return by the
** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
**
** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
** the last seek operation (OP_NotExists) was a success, then this
** operation will not attempt to find the appropriate row before doing
** the insert but will instead overwrite the row that the cursor is
** currently pointing to.  Presumably, the prior OP_NotExists opcode
** has already positioned the cursor correctly.  This is an optimization
** that boosts performance by avoiding redundant seeks.
**
** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
** is part of an INSERT operation.  The difference is only important to
** the update hook.
**
** Parameter P4 may point to a string containing the table-name, or
** may be NULL. If it is not NULL, then the update-hook 
** (sqlite3.xUpdateCallback) is invoked following a successful insert.
**
** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
** allocated, then ownership of P2 is transferred to the pseudo-cursor
** and register P2 becomes ephemeral.  If the cursor is changed, the
** value of register P2 will then change.  Make sure this does not
** cause any problems.)
**
** This instruction only works on tables.  The equivalent instruction
** for indices is OP_IdxInsert.
*/
/* Opcode: InsertInt P1 P2 P3 P4 P5
**
** This works exactly like OP_Insert except that the key is the
** integer value P3, not the value of the integer stored in register P3.
*/
case OP_Insert: 
case OP_InsertInt: {
  Mem *pData;       /* MEM cell holding data for the record to be inserted */
  Mem *pKey;        /* MEM cell holding key  for the record */
  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
  VdbeCursor *pC;   /* Cursor to table into which insert is written */
  int nZero;        /* Number of zero-bytes to append */
  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
  const char *zDb;  /* database name - used by the update hook */
  const char *zTbl; /* Table name - used by the opdate hook */
  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */

  pData = &p->aMem[pOp->p2];
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  assert( pC->pCursor!=0 );
  assert( pC->pseudoTableReg==0 );
  assert( pC->isTable );
  REGISTER_TRACE(pOp->p2, pData);

  if( pOp->opcode==OP_Insert ){
    pKey = &p->aMem[pOp->p3];
    assert( pKey->flags & MEM_Int );
    REGISTER_TRACE(pOp->p3, pKey);
    iKey = pKey->u.i;
  }else{
    assert( pOp->opcode==OP_InsertInt );
    iKey = pOp->p3;
  }

  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = iKey;
  if( pData->flags & MEM_Null ){
    pData->z = 0;
    pData->n = 0;
  }else{
    assert( pData->flags & (MEM_Blob|MEM_Str) );
  }
  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  if( pData->flags & MEM_Zero ){
    nZero = pData->u.nZero;
  }else{
    nZero = 0;
  }
  sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
  rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
                          pData->z, pData->n, nZero,
                          pOp->p5 & OPFLAG_APPEND, seekResult
  );
  pC->rowidIsValid = 0;
  pC->deferredMoveto = 0;
  pC->cacheStatus = CACHE_STALE;

  /* Invoke the update-hook if required. */
  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
    zDb = db->aDb[pC->iDb].zName;
    zTbl = pOp->p4.z;
    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
    assert( pC->isTable );
    db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
    assert( pC->iDb>=0 );
  }
  break;
}

/* Opcode: Delete P1 P2 * P4 *
**
** Delete the record at which the P1 cursor is currently pointing.
**
** The cursor will be left pointing at either the next or the previous
** record in the table. If it is left pointing at the next record, then
** the next Next instruction will be a no-op.  Hence it is OK to delete
** a record from within an Next loop.
**
** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
** incremented (otherwise not).
**
** P1 must not be pseudo-table.  It has to be a real table with
** multiple rows.
**
** If P4 is not NULL, then it is the name of the table that P1 is
** pointing to.  The update hook will be invoked, if it exists.
** If P4 is not NULL then the P1 cursor must have been positioned
** using OP_NotFound prior to invoking this opcode.
*/
case OP_Delete: {
  i64 iKey;
  VdbeCursor *pC;

  iKey = 0;
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */

  /* If the update-hook will be invoked, set iKey to the rowid of the
  ** row being deleted.
  */
  if( db->xUpdateCallback && pOp->p4.z ){
    assert( pC->isTable );
    assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
    iKey = pC->lastRowid;
  }

  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  ** OP_Column on the same table without any intervening operations that
  ** might move or invalidate the cursor.  Hence cursor pC is always pointing
  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
  ** to guard against future changes to the code generator.
  **/
  assert( pC->deferredMoveto==0 );
  rc = sqlite3VdbeCursorMoveto(pC);
  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;

  sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
  rc = sqlite3BtreeDelete(pC->pCursor);
  pC->cacheStatus = CACHE_STALE;

  /* Invoke the update-hook if required. */
  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
    const char *zDb = db->aDb[pC->iDb].zName;
    const char *zTbl = pOp->p4.z;
    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
    assert( pC->iDb>=0 );
  }
  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  break;
}
/* Opcode: ResetCount * * * * *
**
** The value of the change counter is copied to the database handle
** change counter (returned by subsequent calls to sqlite3_changes()).
** Then the VMs internal change counter resets to 0.
** This is used by trigger programs.
*/
case OP_ResetCount: {
  sqlite3VdbeSetChanges(db, p->nChange);
  p->nChange = 0;
  break;
}

/* Opcode: RowData P1 P2 * * *
**
** Write into register P2 the complete row data for cursor P1.
** There is no interpretation of the data.  
** It is just copied onto the P2 register exactly as 
** it is found in the database file.
**
** If the P1 cursor must be pointing to a valid row (not a NULL row)
** of a real table, not a pseudo-table.
*/
/* Opcode: RowKey P1 P2 * * *
**
** Write into register P2 the complete row key for cursor P1.
** There is no interpretation of the data.  
** The key is copied onto the P3 register exactly as 
** it is found in the database file.
**
** If the P1 cursor must be pointing to a valid row (not a NULL row)
** of a real table, not a pseudo-table.
*/
case OP_RowKey:
case OP_RowData: {
  VdbeCursor *pC;
  BtCursor *pCrsr;
  u32 n;
  i64 n64;

  pOut = &p->aMem[pOp->p2];

  /* Note that RowKey and RowData are really exactly the same instruction */
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC->isTable || pOp->opcode==OP_RowKey );
  assert( pC->isIndex || pOp->opcode==OP_RowData );
  assert( pC!=0 );
  assert( pC->nullRow==0 );
  assert( pC->pseudoTableReg==0 );
  assert( pC->pCursor!=0 );
  pCrsr = pC->pCursor;
  assert( sqlite3BtreeCursorIsValid(pCrsr) );

  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
  ** a no-op and can never fail.  But we leave it in place as a safety.
  */
  assert( pC->deferredMoveto==0 );
  rc = sqlite3VdbeCursorMoveto(pC);
  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;

  if( pC->isIndex ){
    assert( !pC->isTable );
    rc = sqlite3BtreeKeySize(pCrsr, &n64);
    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
    if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
      goto too_big;
    }
    n = (u32)n64;
  }else{
    rc = sqlite3BtreeDataSize(pCrsr, &n);
    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
      goto too_big;
    }
  }
  if( sqlite3VdbeMemGrow(pOut, n, 0) ){
    goto no_mem;
  }
  pOut->n = n;
  MemSetTypeFlag(pOut, MEM_Blob);
  if( pC->isIndex ){
    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  }else{
    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  }
  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Rowid P1 P2 * * *
**
** Store in register P2 an integer which is the key of the table entry that
** P1 is currently point to.
**
** P1 can be either an ordinary table or a virtual table.  There used to
** be a separate OP_VRowid opcode for use with virtual tables, but this
** one opcode now works for both table types.
*/
case OP_Rowid: {                 /* out2-prerelease */
  VdbeCursor *pC;
  i64 v;
  sqlite3_vtab *pVtab;
  const sqlite3_module *pModule;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  assert( pC->pseudoTableReg==0 );
  if( pC->nullRow ){
    /* Do nothing so that reg[P2] remains NULL */
    break;
  }else if( pC->deferredMoveto ){
    v = pC->movetoTarget;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  }else if( pC->pVtabCursor ){
    pVtab = pC->pVtabCursor->pVtab;
    pModule = pVtab->pModule;
    assert( pModule->xRowid );
    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
    rc = pModule->xRowid(pC->pVtabCursor, &v);
    sqlite3DbFree(db, p->zErrMsg);
    p->zErrMsg = pVtab->zErrMsg;
    pVtab->zErrMsg = 0;
    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
#endif /* SQLITE_OMIT_VIRTUALTABLE */
  }else{
    assert( pC->pCursor!=0 );
    rc = sqlite3VdbeCursorMoveto(pC);
    if( rc ) goto abort_due_to_error;
    if( pC->rowidIsValid ){
      v = pC->lastRowid;
    }else{
      rc = sqlite3BtreeKeySize(pC->pCursor, &v);
      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
    }
  }
  pOut->u.i = v;
  MemSetTypeFlag(pOut, MEM_Int);
  break;
}

/* Opcode: NullRow P1 * * * *
**
** Move the cursor P1 to a null row.  Any OP_Column operations
** that occur while the cursor is on the null row will always
** write a NULL.
*/
case OP_NullRow: {
  VdbeCursor *pC;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  pC->nullRow = 1;
  pC->rowidIsValid = 0;
  if( pC->pCursor ){
    sqlite3BtreeClearCursor(pC->pCursor);
  }
  break;
}

/* Opcode: Last P1 P2 * * *
**
** The next use of the Rowid or Column or Next instruction for P1 
** will refer to the last entry in the database table or index.
** If the table or index is empty and P2>0, then jump immediately to P2.
** If P2 is 0 or if the table or index is not empty, fall through
** to the following instruction.
*/
case OP_Last: {        /* jump */
  VdbeCursor *pC;
  BtCursor *pCrsr;
  int res;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  pCrsr = pC->pCursor;
  if( pCrsr==0 ){
    res = 1;
  }else{
    rc = sqlite3BtreeLast(pCrsr, &res);
  }
  pC->nullRow = (u8)res;
  pC->deferredMoveto = 0;
  pC->rowidIsValid = 0;
  pC->cacheStatus = CACHE_STALE;
  if( pOp->p2>0 && res ){
    pc = pOp->p2 - 1;
  }
  break;
}


/* Opcode: Sort P1 P2 * * *
**
** This opcode does exactly the same thing as OP_Rewind except that
** it increments an undocumented global variable used for testing.
**
** Sorting is accomplished by writing records into a sorting index,
** then rewinding that index and playing it back from beginning to
** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
** rewinding so that the global variable will be incremented and
** regression tests can determine whether or not the optimizer is
** correctly optimizing out sorts.
*/
case OP_Sort: {        /* jump */
#ifdef SQLITE_TEST
  sqlite3_sort_count++;
  sqlite3_search_count--;
#endif
  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
  /* Fall through into OP_Rewind */
}
/* Opcode: Rewind P1 P2 * * *
**
** The next use of the Rowid or Column or Next instruction for P1 
** will refer to the first entry in the database table or index.
** If the table or index is empty and P2>0, then jump immediately to P2.
** If P2 is 0 or if the table or index is not empty, fall through
** to the following instruction.
*/
case OP_Rewind: {        /* jump */
  VdbeCursor *pC;
  BtCursor *pCrsr;
  int res;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  if( (pCrsr = pC->pCursor)!=0 ){
    rc = sqlite3BtreeFirst(pCrsr, &res);
    pC->atFirst = res==0 ?1:0;
    pC->deferredMoveto = 0;
    pC->cacheStatus = CACHE_STALE;
    pC->rowidIsValid = 0;
  }else{
    res = 1;
  }
  pC->nullRow = (u8)res;
  assert( pOp->p2>0 && pOp->p2<p->nOp );
  if( res ){
    pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: Next P1 P2 * * *
**
** Advance cursor P1 so that it points to the next key/data pair in its
** table or index.  If there are no more key/value pairs then fall through
** to the following instruction.  But if the cursor advance was successful,
** jump immediately to P2.
**
** The P1 cursor must be for a real table, not a pseudo-table.
**
** See also: Prev
*/
/* Opcode: Prev P1 P2 * * *
**
** Back up cursor P1 so that it points to the previous key/data pair in its
** table or index.  If there is no previous key/value pairs then fall through
** to the following instruction.  But if the cursor backup was successful,
** jump immediately to P2.
**
** The P1 cursor must be for a real table, not a pseudo-table.
*/
case OP_Prev:          /* jump */
case OP_Next: {        /* jump */
  VdbeCursor *pC;
  BtCursor *pCrsr;
  int res;

  CHECK_FOR_INTERRUPT;
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  if( pC==0 ){
    break;  /* See ticket #2273 */
  }
  pCrsr = pC->pCursor;
  if( pCrsr==0 ){
    pC->nullRow = 1;
    break;
  }
  res = 1;
  assert( pC->deferredMoveto==0 );
  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
                              sqlite3BtreePrevious(pCrsr, &res);
  pC->nullRow = (u8)res;
  pC->cacheStatus = CACHE_STALE;
  if( res==0 ){
    pc = pOp->p2 - 1;
    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
#ifdef SQLITE_TEST
    sqlite3_search_count++;
#endif
  }
  pC->rowidIsValid = 0;
  break;
}

/* Opcode: IdxInsert P1 P2 P3 * P5
**
** Register P2 holds a SQL index key made using the
** MakeRecord instructions.  This opcode writes that key
** into the index P1.  Data for the entry is nil.
**
** P3 is a flag that provides a hint to the b-tree layer that this
** insert is likely to be an append.
**
** This instruction only works for indices.  The equivalent instruction
** for tables is OP_Insert.
*/
case OP_IdxInsert: {        /* in2 */
  VdbeCursor *pC;
  BtCursor *pCrsr;
  int nKey;
  const char *zKey;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  assert( pIn2->flags & MEM_Blob );
  pCrsr = pC->pCursor;
  if( ALWAYS(pCrsr!=0) ){
    assert( pC->isTable==0 );
    rc = ExpandBlob(pIn2);
    if( rc==SQLITE_OK ){
      nKey = pIn2->n;
      zKey = pIn2->z;
      rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, 
          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
      );
      assert( pC->deferredMoveto==0 );
      pC->cacheStatus = CACHE_STALE;
    }
  }
  break;
}

/* Opcode: IdxDelete P1 P2 P3 * *
**
** The content of P3 registers starting at register P2 form
** an unpacked index key. This opcode removes that entry from the 
** index opened by cursor P1.
*/
case OP_IdxDelete: {
  VdbeCursor *pC;
  BtCursor *pCrsr;
  int res;
  UnpackedRecord r;

  assert( pOp->p3>0 );
  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  pCrsr = pC->pCursor;
  if( ALWAYS(pCrsr!=0) ){
    r.pKeyInfo = pC->pKeyInfo;
    r.nField = (u16)pOp->p3;
    r.flags = 0;
    r.aMem = &p->aMem[pOp->p2];
    rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
    if( rc==SQLITE_OK && res==0 ){
      rc = sqlite3BtreeDelete(pCrsr);
    }
    assert( pC->deferredMoveto==0 );
    pC->cacheStatus = CACHE_STALE;
  }
  break;
}

/* Opcode: IdxRowid P1 P2 * * *
**
** Write into register P2 an integer which is the last entry in the record at
** the end of the index key pointed to by cursor P1.  This integer should be
** the rowid of the table entry to which this index entry points.
**
** See also: Rowid, MakeRecord.
*/
case OP_IdxRowid: {              /* out2-prerelease */
  BtCursor *pCrsr;
  VdbeCursor *pC;
  i64 rowid;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  pCrsr = pC->pCursor;
  if( ALWAYS(pCrsr!=0) ){
    rc = sqlite3VdbeCursorMoveto(pC);
    if( NEVER(rc) ) goto abort_due_to_error;
    assert( pC->deferredMoveto==0 );
    assert( pC->isTable==0 );
    if( !pC->nullRow ){
      rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
      if( rc!=SQLITE_OK ){
        goto abort_due_to_error;
      }
      MemSetTypeFlag(pOut, MEM_Int);
      pOut->u.i = rowid;
    }
  }
  break;
}

/* Opcode: IdxGE P1 P2 P3 P4 P5
**
** The P4 register values beginning with P3 form an unpacked index 
** key that omits the ROWID.  Compare this key value against the index 
** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
**
** If the P1 index entry is greater than or equal to the key value
** then jump to P2.  Otherwise fall through to the next instruction.
**
** If P5 is non-zero then the key value is increased by an epsilon 
** prior to the comparison.  This make the opcode work like IdxGT except
** that if the key from register P3 is a prefix of the key in the cursor,
** the result is false whereas it would be true with IdxGT.
*/
/* Opcode: IdxLT P1 P2 P3 * P5
**
** The P4 register values beginning with P3 form an unpacked index 
** key that omits the ROWID.  Compare this key value against the index 
** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
**
** If the P1 index entry is less than the key value then jump to P2.
** Otherwise fall through to the next instruction.
**
** If P5 is non-zero then the key value is increased by an epsilon prior 
** to the comparison.  This makes the opcode work like IdxLE.
*/
case OP_IdxLT:          /* jump, in3 */
case OP_IdxGE: {        /* jump, in3 */
  VdbeCursor *pC;
  int res;
  UnpackedRecord r;

  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  if( ALWAYS(pC->pCursor!=0) ){
    assert( pC->deferredMoveto==0 );
    assert( pOp->p5==0 || pOp->p5==1 );
    assert( pOp->p4type==P4_INT32 );
    r.pKeyInfo = pC->pKeyInfo;
    r.nField = (u16)pOp->p4.i;
    if( pOp->p5 ){
      r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
    }else{
      r.flags = UNPACKED_IGNORE_ROWID;
    }
    r.aMem = &p->aMem[pOp->p3];
    rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
    if( pOp->opcode==OP_IdxLT ){
      res = -res;
    }else{
      assert( pOp->opcode==OP_IdxGE );
      res++;
    }
    if( res>0 ){
      pc = pOp->p2 - 1 ;
    }
  }
  break;
}

/* Opcode: Destroy P1 P2 P3 * *
**
** Delete an entire database table or index whose root page in the database
** file is given by P1.
**
** The table being destroyed is in the main database file if P3==0.  If
** P3==1 then the table to be clear is in the auxiliary database file
** that is used to store tables create using CREATE TEMPORARY TABLE.
**
** If AUTOVACUUM is enabled then it is possible that another root page
** might be moved into the newly deleted root page in order to keep all
** root pages contiguous at the beginning of the database.  The former
** value of the root page that moved - its value before the move occurred -
** is stored in register P2.  If no page 
** movement was required (because the table being dropped was already 
** the last one in the database) then a zero is stored in register P2.
** If AUTOVACUUM is disabled then a zero is stored in register P2.
**
** See also: Clear
*/
case OP_Destroy: {     /* out2-prerelease */
  int iMoved;
  int iCnt;
  Vdbe *pVdbe;
  int iDb;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  iCnt = 0;
  for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
    if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
      iCnt++;
    }
  }
#else
  iCnt = db->activeVdbeCnt;
#endif
  if( iCnt>1 ){
    rc = SQLITE_LOCKED;
    p->errorAction = OE_Abort;
  }else{
    iDb = pOp->p3;
    assert( iCnt==1 );
    assert( (p->btreeMask & (1<<iDb))!=0 );
    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
    MemSetTypeFlag(pOut, MEM_Int);
    pOut->u.i = iMoved;
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( rc==SQLITE_OK && iMoved!=0 ){
      sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
    }
#endif
  }
  break;
}

/* Opcode: Clear P1 P2 P3
**
** Delete all contents of the database table or index whose root page
** in the database file is given by P1.  But, unlike Destroy, do not
** remove the table or index from the database file.
**
** The table being clear is in the main database file if P2==0.  If
** P2==1 then the table to be clear is in the auxiliary database file
** that is used to store tables create using CREATE TEMPORARY TABLE.
**
** If the P3 value is non-zero, then the table referred to must be an
** intkey table (an SQL table, not an index). In this case the row change 
** count is incremented by the number of rows in the table being cleared. 
** If P3 is greater than zero, then the value stored in register P3 is
** also incremented by the number of rows in the table being cleared.
**
** See also: Destroy
*/
case OP_Clear: {
  int nChange;
 
  nChange = 0;
  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
  rc = sqlite3BtreeClearTable(
      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  );
  if( pOp->p3 ){
    p->nChange += nChange;
    if( pOp->p3>0 ){
      p->aMem[pOp->p3].u.i += nChange;
    }
  }
  break;
}

/* Opcode: CreateTable P1 P2 * * *
**
** Allocate a new table in the main database file if P1==0 or in the
** auxiliary database file if P1==1 or in an attached database if
** P1>1.  Write the root page number of the new table into
** register P2
**
** The difference between a table and an index is this:  A table must
** have a 4-byte integer key and can have arbitrary data.  An index
** has an arbitrary key but no data.
**
** See also: CreateIndex
*/
/* Opcode: CreateIndex P1 P2 * * *
**
** Allocate a new index in the main database file if P1==0 or in the
** auxiliary database file if P1==1 or in an attached database if
** P1>1.  Write the root page number of the new table into
** register P2.
**
** See documentation on OP_CreateTable for additional information.
*/
case OP_CreateIndex:            /* out2-prerelease */
case OP_CreateTable: {          /* out2-prerelease */
  int pgno;
  int flags;
  Db *pDb;

  pgno = 0;
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  pDb = &db->aDb[pOp->p1];
  assert( pDb->pBt!=0 );
  if( pOp->opcode==OP_CreateTable ){
    /* flags = BTREE_INTKEY; */
    flags = BTREE_LEAFDATA|BTREE_INTKEY;
  }else{
    flags = BTREE_ZERODATA;
  }
  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  pOut->u.i = pgno;
  MemSetTypeFlag(pOut, MEM_Int);
  break;
}

/* Opcode: ParseSchema P1 P2 * P4 *
**
** Read and parse all entries from the SQLITE_MASTER table of database P1
** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
** the parsing if P2 is true.  If P2 is false, then this routine is a
** no-op if the schema is not currently loaded.  In other words, if P2
** is false, the SQLITE_MASTER table is only parsed if the rest of the
** schema is already loaded into the symbol table.
**
** This opcode invokes the parser to create a new virtual machine,
** then runs the new virtual machine.  It is thus a re-entrant opcode.
*/
case OP_ParseSchema: {
  int iDb;
  const char *zMaster;
  char *zSql;
  InitData initData;

  iDb = pOp->p1;
  assert( iDb>=0 && iDb<db->nDb );

  /* If pOp->p2 is 0, then this opcode is being executed to read a
  ** single row, for example the row corresponding to a new index
  ** created by this VDBE, from the sqlite_master table. It only
  ** does this if the corresponding in-memory schema is currently
  ** loaded. Otherwise, the new index definition can be loaded along
  ** with the rest of the schema when it is required.
  **
  ** Although the mutex on the BtShared object that corresponds to
  ** database iDb (the database containing the sqlite_master table
  ** read by this instruction) is currently held, it is necessary to
  ** obtain the mutexes on all attached databases before checking if
  ** the schema of iDb is loaded. This is because, at the start of
  ** the sqlite3_exec() call below, SQLite will invoke 
  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
  ** iDb mutex may be temporarily released to avoid deadlock. If 
  ** this happens, then some other thread may delete the in-memory 
  ** schema of database iDb before the SQL statement runs. The schema
  ** will not be reloaded becuase the db->init.busy flag is set. This
  ** can result in a "no such table: sqlite_master" or "malformed
  ** database schema" error being returned to the user.
  */
  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  sqlite3BtreeEnterAll(db);
  if( pOp->p2 || DbHasProperty(db, iDb, DB_SchemaLoaded) ){
    zMaster = SCHEMA_TABLE(iDb);
    initData.db = db;
    initData.iDb = pOp->p1;
    initData.pzErrMsg = &p->zErrMsg;
    zSql = sqlite3MPrintf(db,
       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
       db->aDb[iDb].zName, zMaster, pOp->p4.z);
    if( zSql==0 ){
      rc = SQLITE_NOMEM;
    }else{
      (void)sqlite3SafetyOff(db);
      assert( db->init.busy==0 );
      db->init.busy = 1;
      initData.rc = SQLITE_OK;
      assert( !db->mallocFailed );
      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
      if( rc==SQLITE_OK ) rc = initData.rc;
      sqlite3DbFree(db, zSql);
      db->init.busy = 0;
      (void)sqlite3SafetyOn(db);
    }
  }
  sqlite3BtreeLeaveAll(db);
  if( rc==SQLITE_NOMEM ){
    goto no_mem;
  }
  break;  
}

#if !defined(SQLITE_OMIT_ANALYZE)
/* Opcode: LoadAnalysis P1 * * * *
**
** Read the sqlite_stat1 table for database P1 and load the content
** of that table into the internal index hash table.  This will cause
** the analysis to be used when preparing all subsequent queries.
*/
case OP_LoadAnalysis: {
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  rc = sqlite3AnalysisLoad(db, pOp->p1);
  break;  
}
#endif /* !defined(SQLITE_OMIT_ANALYZE) */

/* Opcode: DropTable P1 * * P4 *
**
** Remove the internal (in-memory) data structures that describe
** the table named P4 in database P1.  This is called after a table
** is dropped in order to keep the internal representation of the
** schema consistent with what is on disk.
*/
case OP_DropTable: {
  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  break;
}

/* Opcode: DropIndex P1 * * P4 *
**
** Remove the internal (in-memory) data structures that describe
** the index named P4 in database P1.  This is called after an index
** is dropped in order to keep the internal representation of the
** schema consistent with what is on disk.
*/
case OP_DropIndex: {
  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  break;
}

/* Opcode: DropTrigger P1 * * P4 *
**
** Remove the internal (in-memory) data structures that describe
** the trigger named P4 in database P1.  This is called after a trigger
** is dropped in order to keep the internal representation of the
** schema consistent with what is on disk.
*/
case OP_DropTrigger: {
  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  break;
}


#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/* Opcode: IntegrityCk P1 P2 P3 * P5
**
** Do an analysis of the currently open database.  Store in
** register P1 the text of an error message describing any problems.
** If no problems are found, store a NULL in register P1.
**
** The register P3 contains the maximum number of allowed errors.
** At most reg(P3) errors will be reported.
** In other words, the analysis stops as soon as reg(P1) errors are 
** seen.  Reg(P1) is updated with the number of errors remaining.
**
** The root page numbers of all tables in the database are integer
** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
** total.
**
** If P5 is not zero, the check is done on the auxiliary database
** file, not the main database file.
**
** This opcode is used to implement the integrity_check pragma.
*/
case OP_IntegrityCk: {
  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
  int j;          /* Loop counter */
  int nErr;       /* Number of errors reported */
  char *z;        /* Text of the error report */
  Mem *pnErr;     /* Register keeping track of errors remaining */
  
  nRoot = pOp->p2;
  assert( nRoot>0 );
  aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  if( aRoot==0 ) goto no_mem;
  assert( pOp->p3>0 && pOp->p3<=p->nMem );
  pnErr = &p->aMem[pOp->p3];
  assert( (pnErr->flags & MEM_Int)!=0 );
  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  pIn1 = &p->aMem[pOp->p1];
  for(j=0; j<nRoot; j++){
    aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  }
  aRoot[j] = 0;
  assert( pOp->p5<db->nDb );
  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
                                 (int)pnErr->u.i, &nErr);
  sqlite3DbFree(db, aRoot);
  pnErr->u.i -= nErr;
  sqlite3VdbeMemSetNull(pIn1);
  if( nErr==0 ){
    assert( z==0 );
  }else if( z==0 ){
    goto no_mem;
  }else{
    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  }
  UPDATE_MAX_BLOBSIZE(pIn1);
  sqlite3VdbeChangeEncoding(pIn1, encoding);
  break;
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

/* Opcode: RowSetAdd P1 P2 * * *
**
** Insert the integer value held by register P2 into a boolean index
** held in register P1.
**
** An assertion fails if P2 is not an integer.
*/
case OP_RowSetAdd: {       /* in2 */
  Mem *pIdx;
  Mem *pVal;
  assert( pOp->p1>0 && pOp->p1<=p->nMem );
  pIdx = &p->aMem[pOp->p1];
  assert( pOp->p2>0 && pOp->p2<=p->nMem );
  pVal = &p->aMem[pOp->p2];
  assert( (pVal->flags & MEM_Int)!=0 );
  if( (pIdx->flags & MEM_RowSet)==0 ){
    sqlite3VdbeMemSetRowSet(pIdx);
    if( (pIdx->flags & MEM_RowSet)==0 ) goto no_mem;
  }
  sqlite3RowSetInsert(pIdx->u.pRowSet, pVal->u.i);
  break;
}

/* Opcode: RowSetRead P1 P2 P3 * *
**
** Extract the smallest value from boolean index P1 and put that value into
** register P3.  Or, if boolean index P1 is initially empty, leave P3
** unchanged and jump to instruction P2.
*/
case OP_RowSetRead: {       /* jump, out3 */
  Mem *pIdx;
  i64 val;
  assert( pOp->p1>0 && pOp->p1<=p->nMem );
  CHECK_FOR_INTERRUPT;
  pIdx = &p->aMem[pOp->p1];
  pOut = &p->aMem[pOp->p3];
  if( (pIdx->flags & MEM_RowSet)==0 
   || sqlite3RowSetNext(pIdx->u.pRowSet, &val)==0
  ){
    /* The boolean index is empty */
    sqlite3VdbeMemSetNull(pIdx);
    pc = pOp->p2 - 1;
  }else{
    /* A value was pulled from the index */
    assert( pOp->p3>0 && pOp->p3<=p->nMem );
    sqlite3VdbeMemSetInt64(pOut, val);
  }
  break;
}

/* Opcode: RowSetTest P1 P2 P3 P4
**
** Register P3 is assumed to hold a 64-bit integer value. If register P1
** contains a RowSet object and that RowSet object contains
** the value held in P3, jump to register P2. Otherwise, insert the
** integer in P3 into the RowSet and continue on to the
** next opcode.
**
** The RowSet object is optimized for the case where successive sets
** of integers, where each set contains no duplicates. Each set
** of values is identified by a unique P4 value. The first set
** must have P4==0, the final set P4=-1.  P4 must be either -1 or
** non-negative.  For non-negative values of P4 only the lower 4
** bits are significant.
**
** This allows optimizations: (a) when P4==0 there is no need to test
** the rowset object for P3, as it is guaranteed not to contain it,
** (b) when P4==-1 there is no need to insert the value, as it will
** never be tested for, and (c) when a value that is part of set X is
** inserted, there is no need to search to see if the same value was
** previously inserted as part of set X (only if it was previously
** inserted as part of some other set).
*/
case OP_RowSetTest: {                     /* jump, in1, in3 */
  int iSet;
  int exists;

  iSet = pOp->p4.i;
  assert( pIn3->flags&MEM_Int );

  /* If there is anything other than a rowset object in memory cell P1,
  ** delete it now and initialize P1 with an empty rowset
  */
  if( (pIn1->flags & MEM_RowSet)==0 ){
    sqlite3VdbeMemSetRowSet(pIn1);
    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  }

  assert( pOp->p4type==P4_INT32 );
  assert( iSet==-1 || iSet>=0 );
  if( iSet ){
    exists = sqlite3RowSetTest(pIn1->u.pRowSet, 
                               (u8)(iSet>=0 ? iSet & 0xf : 0xff),
                               pIn3->u.i);
    if( exists ){
      pc = pOp->p2 - 1;
      break;
    }
  }
  if( iSet>=0 ){
    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  }
  break;
}


#ifndef SQLITE_OMIT_TRIGGER

/* Opcode: Program P1 P2 P3 P4 *
**
** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
**
** P1 contains the address of the memory cell that contains the first memory 
** cell in an array of values used as arguments to the sub-program. P2 
** contains the address to jump to if the sub-program throws an IGNORE 
** exception using the RAISE() function. Register P3 contains the address 
** of a memory cell in this (the parent) VM that is used to allocate the 
** memory required by the sub-vdbe at runtime.
**
** P4 is a pointer to the VM containing the trigger program.
*/
case OP_Program: {        /* jump */
  int nMem;               /* Number of memory registers for sub-program */
  int nByte;              /* Bytes of runtime space required for sub-program */
  Mem *pRt;               /* Register to allocate runtime space */
  Mem *pMem;              /* Used to iterate through memory cells */
  Mem *pEnd;              /* Last memory cell in new array */
  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
  SubProgram *pProgram;   /* Sub-program to execute */
  void *t;                /* Token identifying trigger */

  pProgram = pOp->p4.pProgram;
  pRt = &p->aMem[pOp->p3];
  assert( pProgram->nOp>0 );
  
  /* If the p5 flag is clear, then recursive invocation of triggers is 
  ** disabled for backwards compatibility (p5 is set if this sub-program
  ** is really a trigger, not a foreign key action, and the flag set
  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  ** 
  ** It is recursive invocation of triggers, at the SQL level, that is 
  ** disabled. In some cases a single trigger may generate more than one 
  ** SubProgram (if the trigger may be executed with more than one different 
  ** ON CONFLICT algorithm). SubProgram structures associated with a
  ** single trigger all have the same value for the SubProgram.token 
  ** variable.  */
  if( pOp->p5 ){
    t = pProgram->token;
    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
    if( pFrame ) break;
  }

  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
    rc = SQLITE_ERROR;
    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
    break;
  }

  /* Register pRt is used to store the memory required to save the state
  ** of the current program, and the memory required at runtime to execute
  ** the trigger program. If this trigger has been fired before, then pRt 
  ** is already allocated. Otherwise, it must be initialized.  */
  if( (pRt->flags&MEM_Frame)==0 ){
    /* SubProgram.nMem is set to the number of memory cells used by the 
    ** program stored in SubProgram.aOp. As well as these, one memory
    ** cell is required for each cursor used by the program. Set local
    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
    */
    nMem = pProgram->nMem + pProgram->nCsr;
    nByte = ROUND8(sizeof(VdbeFrame))
              + nMem * sizeof(Mem)
              + pProgram->nCsr * sizeof(VdbeCursor *);
    pFrame = sqlite3DbMallocZero(db, nByte);
    if( !pFrame ){
      goto no_mem;
    }
    sqlite3VdbeMemRelease(pRt);
    pRt->flags = MEM_Frame;
    pRt->u.pFrame = pFrame;

    pFrame->v = p;
    pFrame->nChildMem = nMem;
    pFrame->nChildCsr = pProgram->nCsr;
    pFrame->pc = pc;
    pFrame->aMem = p->aMem;
    pFrame->nMem = p->nMem;
    pFrame->apCsr = p->apCsr;
    pFrame->nCursor = p->nCursor;
    pFrame->aOp = p->aOp;
    pFrame->nOp = p->nOp;
    pFrame->token = pProgram->token;

    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
      pMem->flags = MEM_Null;
      pMem->db = db;
    }
  }else{
    pFrame = pRt->u.pFrame;
    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
    assert( pProgram->nCsr==pFrame->nChildCsr );
    assert( pc==pFrame->pc );
  }

  p->nFrame++;
  pFrame->pParent = p->pFrame;
  pFrame->lastRowid = db->lastRowid;
  pFrame->nChange = p->nChange;
  p->nChange = 0;
  p->pFrame = pFrame;
  p->aMem = &VdbeFrameMem(pFrame)[-1];
  p->nMem = pFrame->nChildMem;
  p->nCursor = (u16)pFrame->nChildCsr;
  p->apCsr = (VdbeCursor **)&p->aMem[p->nMem+1];
  p->aOp = pProgram->aOp;
  p->nOp = pProgram->nOp;
  pc = -1;

  break;
}

/* Opcode: Param P1 P2 * * *
**
** This opcode is only ever present in sub-programs called via the 
** OP_Program instruction. Copy a value currently stored in a memory 
** cell of the calling (parent) frame to cell P2 in the current frames 
** address space. This is used by trigger programs to access the new.* 
** and old.* values.
**
** The address of the cell in the parent frame is determined by adding
** the value of the P1 argument to the value of the P1 argument to the
** calling OP_Program instruction.
*/
case OP_Param: {           /* out2-prerelease */
  VdbeFrame *pFrame;
  Mem *pIn;
  pFrame = p->pFrame;
  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  break;
}

#endif /* #ifndef SQLITE_OMIT_TRIGGER */

#ifndef SQLITE_OMIT_FOREIGN_KEY
/* Opcode: FkCounter P1 P2 * * *
**
** Increment a "constraint counter" by P2 (P2 may be negative or positive).
** If P1 is non-zero, the database constraint counter is incremented 
** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
** statement counter is incremented (immediate foreign key constraints).
*/
case OP_FkCounter: {
  if( pOp->p1 ){
    db->nDeferredCons += pOp->p2;
  }else{
    p->nFkConstraint += pOp->p2;
  }
  break;
}

/* Opcode: FkIfZero P1 P2 * * *
**
** This opcode tests if a foreign key constraint-counter is currently zero.
** If so, jump to instruction P2. Otherwise, fall through to the next 
** instruction.
**
** If P1 is non-zero, then the jump is taken if the database constraint-counter
** is zero (the one that counts deferred constraint violations). If P1 is
** zero, the jump is taken if the statement constraint-counter is zero
** (immediate foreign key constraint violations).
*/
case OP_FkIfZero: {         /* jump */
  if( pOp->p1 ){
    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
  }else{
    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
  }
  break;
}
#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */

#ifndef SQLITE_OMIT_AUTOINCREMENT
/* Opcode: MemMax P1 P2 * * *
**
** P1 is a register in the root frame of this VM (the root frame is
** different from the current frame if this instruction is being executed
** within a sub-program). Set the value of register P1 to the maximum of 
** its current value and the value in register P2.
**
** This instruction throws an error if the memory cell is not initially
** an integer.
*/
case OP_MemMax: {        /* in2 */
  Mem *pIn1;
  VdbeFrame *pFrame;
  if( p->pFrame ){
    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
    pIn1 = &pFrame->aMem[pOp->p1];
  }else{
    pIn1 = &p->aMem[pOp->p1];
  }
  sqlite3VdbeMemIntegerify(pIn1);
  sqlite3VdbeMemIntegerify(pIn2);
  if( pIn1->u.i<pIn2->u.i){
    pIn1->u.i = pIn2->u.i;
  }
  break;
}
#endif /* SQLITE_OMIT_AUTOINCREMENT */

/* Opcode: IfPos P1 P2 * * *
**
** If the value of register P1 is 1 or greater, jump to P2.
**
** It is illegal to use this instruction on a register that does
** not contain an integer.  An assertion fault will result if you try.
*/
case OP_IfPos: {        /* jump, in1 */
  assert( pIn1->flags&MEM_Int );
  if( pIn1->u.i>0 ){
     pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: IfNeg P1 P2 * * *
**
** If the value of register P1 is less than zero, jump to P2. 
**
** It is illegal to use this instruction on a register that does
** not contain an integer.  An assertion fault will result if you try.
*/
case OP_IfNeg: {        /* jump, in1 */
  assert( pIn1->flags&MEM_Int );
  if( pIn1->u.i<0 ){
     pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: IfZero P1 P2 * * *
**
** If the value of register P1 is exactly 0, jump to P2. 
**
** It is illegal to use this instruction on a register that does
** not contain an integer.  An assertion fault will result if you try.
*/
case OP_IfZero: {        /* jump, in1 */
  assert( pIn1->flags&MEM_Int );
  if( pIn1->u.i==0 ){
     pc = pOp->p2 - 1;
  }
  break;
}

/* Opcode: AggStep * P2 P3 P4 P5
**
** Execute the step function for an aggregate.  The
** function has P5 arguments.   P4 is a pointer to the FuncDef
** structure that specifies the function.  Use register
** P3 as the accumulator.
**
** The P5 arguments are taken from register P2 and its
** successors.
*/
case OP_AggStep: {
  int n;
  int i;
  Mem *pMem;
  Mem *pRec;
  sqlite3_context ctx;
  sqlite3_value **apVal;

  n = pOp->p5;
  assert( n>=0 );
  pRec = &p->aMem[pOp->p2];
  apVal = p->apArg;
  assert( apVal || n==0 );
  for(i=0; i<n; i++, pRec++){
    apVal[i] = pRec;
    sqlite3VdbeMemStoreType(pRec);
  }
  ctx.pFunc = pOp->p4.pFunc;
  assert( pOp->p3>0 && pOp->p3<=p->nMem );
  ctx.pMem = pMem = &p->aMem[pOp->p3];
  pMem->n++;
  ctx.s.flags = MEM_Null;
  ctx.s.z = 0;
  ctx.s.zMalloc = 0;
  ctx.s.xDel = 0;
  ctx.s.db = db;
  ctx.isError = 0;
  ctx.pColl = 0;
  if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
    assert( pOp>p->aOp );
    assert( pOp[-1].p4type==P4_COLLSEQ );
    assert( pOp[-1].opcode==OP_CollSeq );
    ctx.pColl = pOp[-1].p4.pColl;
  }
  (ctx.pFunc->xStep)(&ctx, n, apVal);
  if( ctx.isError ){
    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
    rc = ctx.isError;
  }
  sqlite3VdbeMemRelease(&ctx.s);
  break;
}

/* Opcode: AggFinal P1 P2 * P4 *
**
** Execute the finalizer function for an aggregate.  P1 is
** the memory location that is the accumulator for the aggregate.
**
** P2 is the number of arguments that the step function takes and
** P4 is a pointer to the FuncDef for this function.  The P2
** argument is not used by this opcode.  It is only there to disambiguate
** functions that can take varying numbers of arguments.  The
** P4 argument is only needed for the degenerate case where
** the step function was not previously called.
*/
case OP_AggFinal: {
  Mem *pMem;
  assert( pOp->p1>0 && pOp->p1<=p->nMem );
  pMem = &p->aMem[pOp->p1];
  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  if( rc ){
    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
  }
  sqlite3VdbeChangeEncoding(pMem, encoding);
  UPDATE_MAX_BLOBSIZE(pMem);
  if( sqlite3VdbeMemTooBig(pMem) ){
    goto too_big;
  }
  break;
}


#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
/* Opcode: Vacuum * * * * *
**
** Vacuum the entire database.  This opcode will cause other virtual
** machines to be created and run.  It may not be called from within
** a transaction.
*/
case OP_Vacuum: {
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
  rc = sqlite3RunVacuum(&p->zErrMsg, db);
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  break;
}
#endif

#if !defined(SQLITE_OMIT_AUTOVACUUM)
/* Opcode: IncrVacuum P1 P2 * * *
**
** Perform a single step of the incremental vacuum procedure on
** the P1 database. If the vacuum has finished, jump to instruction
** P2. Otherwise, fall through to the next instruction.
*/
case OP_IncrVacuum: {        /* jump */
  Btree *pBt;

  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  pBt = db->aDb[pOp->p1].pBt;
  rc = sqlite3BtreeIncrVacuum(pBt);
  if( rc==SQLITE_DONE ){
    pc = pOp->p2 - 1;
    rc = SQLITE_OK;
  }
  break;
}
#endif

/* Opcode: Expire P1 * * * *
**
** Cause precompiled statements to become expired. An expired statement
** fails with an error code of SQLITE_SCHEMA if it is ever executed 
** (via sqlite3_step()).
** 
** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
** then only the currently executing statement is affected. 
*/
case OP_Expire: {
  if( !pOp->p1 ){
    sqlite3ExpirePreparedStatements(db);
  }else{
    p->expired = 1;
  }
  break;
}

#ifndef SQLITE_OMIT_SHARED_CACHE
/* Opcode: TableLock P1 P2 P3 P4 *
**
** Obtain a lock on a particular table. This instruction is only used when
** the shared-cache feature is enabled. 
**
** P1 is the index of the database in sqlite3.aDb[] of the database
** on which the lock is acquired.  A readlock is obtained if P3==0 or
** a write lock if P3==1.
**
** P2 contains the root-page of the table to lock.
**
** P4 contains a pointer to the name of the table being locked. This is only
** used to generate an error message if the lock cannot be obtained.
*/
case OP_TableLock: {
  u8 isWriteLock = (u8)pOp->p3;
  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
    int p1 = pOp->p1; 
    assert( p1>=0 && p1<db->nDb );
    assert( (p->btreeMask & (1<<p1))!=0 );
    assert( isWriteLock==0 || isWriteLock==1 );
    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
    if( (rc&0xFF)==SQLITE_LOCKED ){
      const char *z = pOp->p4.z;
      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
    }
  }
  break;
}
#endif /* SQLITE_OMIT_SHARED_CACHE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VBegin * * * P4 *
**
** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
** xBegin method for that table.
**
** Also, whether or not P4 is set, check that this is not being called from
** within a callback to a virtual table xSync() method. If it is, the error
** code will be set to SQLITE_LOCKED.
*/
case OP_VBegin: {
  VTable *pVTab;
  pVTab = pOp->p4.pVtab;
  rc = sqlite3VtabBegin(db, pVTab);
  if( pVTab ){
    sqlite3DbFree(db, p->zErrMsg);
    p->zErrMsg = pVTab->pVtab->zErrMsg;
    pVTab->pVtab->zErrMsg = 0;
  }
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VCreate P1 * * P4 *
**
** P4 is the name of a virtual table in database P1. Call the xCreate method
** for that table.
*/
case OP_VCreate: {
  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VDestroy P1 * * P4 *
**
** P4 is the name of a virtual table in database P1.  Call the xDestroy method
** of that table.
*/
case OP_VDestroy: {
  p->inVtabMethod = 2;
  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  p->inVtabMethod = 0;
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VOpen P1 * * P4 *
**
** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
** P1 is a cursor number.  This opcode opens a cursor to the virtual
** table and stores that cursor in P1.
*/
case OP_VOpen: {
  VdbeCursor *pCur;
  sqlite3_vtab_cursor *pVtabCursor;
  sqlite3_vtab *pVtab;
  sqlite3_module *pModule;

  pCur = 0;
  pVtabCursor = 0;
  pVtab = pOp->p4.pVtab->pVtab;
  pModule = (sqlite3_module *)pVtab->pModule;
  assert(pVtab && pModule);
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  rc = pModule->xOpen(pVtab, &pVtabCursor);
  sqlite3DbFree(db, p->zErrMsg);
  p->zErrMsg = pVtab->zErrMsg;
  pVtab->zErrMsg = 0;
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  if( SQLITE_OK==rc ){
    /* Initialize sqlite3_vtab_cursor base class */
    pVtabCursor->pVtab = pVtab;

    /* Initialise vdbe cursor object */
    pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
    if( pCur ){
      pCur->pVtabCursor = pVtabCursor;
      pCur->pModule = pVtabCursor->pVtab->pModule;
    }else{
      db->mallocFailed = 1;
      pModule->xClose(pVtabCursor);
    }
  }
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VFilter P1 P2 P3 P4 *
**
** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
** the filtered result set is empty.
**
** P4 is either NULL or a string that was generated by the xBestIndex
** method of the module.  The interpretation of the P4 string is left
** to the module implementation.
**
** This opcode invokes the xFilter method on the virtual table specified
** by P1.  The integer query plan parameter to xFilter is stored in register
** P3. Register P3+1 stores the argc parameter to be passed to the
** xFilter method. Registers P3+2..P3+1+argc are the argc
** additional parameters which are passed to
** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
**
** A jump is made to P2 if the result set after filtering would be empty.
*/
case OP_VFilter: {   /* jump */
  int nArg;
  int iQuery;
  const sqlite3_module *pModule;
  Mem *pQuery;
  Mem *pArgc;
  sqlite3_vtab_cursor *pVtabCursor;
  sqlite3_vtab *pVtab;
  VdbeCursor *pCur;
  int res;
  int i;
  Mem **apArg;

  pQuery = &p->aMem[pOp->p3];
  pArgc = &pQuery[1];
  pCur = p->apCsr[pOp->p1];
  REGISTER_TRACE(pOp->p3, pQuery);
  assert( pCur->pVtabCursor );
  pVtabCursor = pCur->pVtabCursor;
  pVtab = pVtabCursor->pVtab;
  pModule = pVtab->pModule;

  /* Grab the index number and argc parameters */
  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  nArg = (int)pArgc->u.i;
  iQuery = (int)pQuery->u.i;

  /* Invoke the xFilter method */
  {
    res = 0;
    apArg = p->apArg;
    for(i = 0; i<nArg; i++){
      apArg[i] = &pArgc[i+1];
      sqlite3VdbeMemStoreType(apArg[i]);
    }

    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
    p->inVtabMethod = 1;
    rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
    p->inVtabMethod = 0;
    sqlite3DbFree(db, p->zErrMsg);
    p->zErrMsg = pVtab->zErrMsg;
    pVtab->zErrMsg = 0;
    if( rc==SQLITE_OK ){
      res = pModule->xEof(pVtabCursor);
    }
    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;

    if( res ){
      pc = pOp->p2 - 1;
    }
  }
  pCur->nullRow = 0;

  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VColumn P1 P2 P3 * *
**
** Store the value of the P2-th column of
** the row of the virtual-table that the 
** P1 cursor is pointing to into register P3.
*/
case OP_VColumn: {
  sqlite3_vtab *pVtab;
  const sqlite3_module *pModule;
  Mem *pDest;
  sqlite3_context sContext;

  VdbeCursor *pCur = p->apCsr[pOp->p1];
  assert( pCur->pVtabCursor );
  assert( pOp->p3>0 && pOp->p3<=p->nMem );
  pDest = &p->aMem[pOp->p3];
  if( pCur->nullRow ){
    sqlite3VdbeMemSetNull(pDest);
    break;
  }
  pVtab = pCur->pVtabCursor->pVtab;
  pModule = pVtab->pModule;
  assert( pModule->xColumn );
  memset(&sContext, 0, sizeof(sContext));

  /* The output cell may already have a buffer allocated. Move
  ** the current contents to sContext.s so in case the user-function 
  ** can use the already allocated buffer instead of allocating a 
  ** new one.
  */
  sqlite3VdbeMemMove(&sContext.s, pDest);
  MemSetTypeFlag(&sContext.s, MEM_Null);

  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  sqlite3DbFree(db, p->zErrMsg);
  p->zErrMsg = pVtab->zErrMsg;
  pVtab->zErrMsg = 0;
  if( sContext.isError ){
    rc = sContext.isError;
  }

  /* Copy the result of the function to the P3 register. We
  ** do this regardless of whether or not an error occurred to ensure any
  ** dynamic allocation in sContext.s (a Mem struct) is  released.
  */
  sqlite3VdbeChangeEncoding(&sContext.s, encoding);
  REGISTER_TRACE(pOp->p3, pDest);
  sqlite3VdbeMemMove(pDest, &sContext.s);
  UPDATE_MAX_BLOBSIZE(pDest);

  if( sqlite3SafetyOn(db) ){
    goto abort_due_to_misuse;
  }
  if( sqlite3VdbeMemTooBig(pDest) ){
    goto too_big;
  }
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VNext P1 P2 * * *
**
** Advance virtual table P1 to the next row in its result set and
** jump to instruction P2.  Or, if the virtual table has reached
** the end of its result set, then fall through to the next instruction.
*/
case OP_VNext: {   /* jump */
  sqlite3_vtab *pVtab;
  const sqlite3_module *pModule;
  int res;
  VdbeCursor *pCur;

  res = 0;
  pCur = p->apCsr[pOp->p1];
  assert( pCur->pVtabCursor );
  if( pCur->nullRow ){
    break;
  }
  pVtab = pCur->pVtabCursor->pVtab;
  pModule = pVtab->pModule;
  assert( pModule->xNext );

  /* Invoke the xNext() method of the module. There is no way for the
  ** underlying implementation to return an error if one occurs during
  ** xNext(). Instead, if an error occurs, true is returned (indicating that 
  ** data is available) and the error code returned when xColumn or
  ** some other method is next invoked on the save virtual table cursor.
  */
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  p->inVtabMethod = 1;
  rc = pModule->xNext(pCur->pVtabCursor);
  p->inVtabMethod = 0;
  sqlite3DbFree(db, p->zErrMsg);
  p->zErrMsg = pVtab->zErrMsg;
  pVtab->zErrMsg = 0;
  if( rc==SQLITE_OK ){
    res = pModule->xEof(pCur->pVtabCursor);
  }
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;

  if( !res ){
    /* If there is data, jump to P2 */
    pc = pOp->p2 - 1;
  }
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VRename P1 * * P4 *
**
** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
** This opcode invokes the corresponding xRename method. The value
** in register P1 is passed as the zName argument to the xRename method.
*/
case OP_VRename: {
  sqlite3_vtab *pVtab;
  Mem *pName;

  pVtab = pOp->p4.pVtab->pVtab;
  pName = &p->aMem[pOp->p1];
  assert( pVtab->pModule->xRename );
  REGISTER_TRACE(pOp->p1, pName);
  assert( pName->flags & MEM_Str );
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  rc = pVtab->pModule->xRename(pVtab, pName->z);
  sqlite3DbFree(db, p->zErrMsg);
  p->zErrMsg = pVtab->zErrMsg;
  pVtab->zErrMsg = 0;
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;

  break;
}
#endif

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VUpdate P1 P2 P3 P4 *
**
** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
** This opcode invokes the corresponding xUpdate method. P2 values
** are contiguous memory cells starting at P3 to pass to the xUpdate 
** invocation. The value in register (P3+P2-1) corresponds to the 
** p2th element of the argv array passed to xUpdate.
**
** The xUpdate method will do a DELETE or an INSERT or both.
** The argv[0] element (which corresponds to memory cell P3)
** is the rowid of a row to delete.  If argv[0] is NULL then no 
** deletion occurs.  The argv[1] element is the rowid of the new 
** row.  This can be NULL to have the virtual table select the new 
** rowid for itself.  The subsequent elements in the array are 
** the values of columns in the new row.
**
** If P2==1 then no insert is performed.  argv[0] is the rowid of
** a row to delete.
**
** P1 is a boolean flag. If it is set to true and the xUpdate call
** is successful, then the value returned by sqlite3_last_insert_rowid() 
** is set to the value of the rowid for the row just inserted.
*/
case OP_VUpdate: {
  sqlite3_vtab *pVtab;
  sqlite3_module *pModule;
  int nArg;
  int i;
  sqlite_int64 rowid;
  Mem **apArg;
  Mem *pX;

  pVtab = pOp->p4.pVtab->pVtab;
  pModule = (sqlite3_module *)pVtab->pModule;
  nArg = pOp->p2;
  assert( pOp->p4type==P4_VTAB );
  if( ALWAYS(pModule->xUpdate) ){
    apArg = p->apArg;
    pX = &p->aMem[pOp->p3];
    for(i=0; i<nArg; i++){
      sqlite3VdbeMemStoreType(pX);
      apArg[i] = pX;
      pX++;
    }
    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
    sqlite3DbFree(db, p->zErrMsg);
    p->zErrMsg = pVtab->zErrMsg;
    pVtab->zErrMsg = 0;
    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
    if( rc==SQLITE_OK && pOp->p1 ){
      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
      db->lastRowid = rowid;
    }
    p->nChange++;
  }
  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
/* Opcode: Pagecount P1 P2 * * *
**
** Write the current number of pages in database P1 to memory cell P2.
*/
case OP_Pagecount: {            /* out2-prerelease */
  int p1;
  int nPage;
  Pager *pPager;

  p1 = pOp->p1; 
  pPager = sqlite3BtreePager(db->aDb[p1].pBt);
  rc = sqlite3PagerPagecount(pPager, &nPage);
  /* OP_Pagecount is always called from within a read transaction.  The
  ** page count has already been successfully read and cached.  So the
  ** sqlite3PagerPagecount() call above cannot fail. */
  if( ALWAYS(rc==SQLITE_OK) ){
    pOut->flags = MEM_Int;
    pOut->u.i = nPage;
  }
  break;
}
#endif

#ifndef SQLITE_OMIT_TRACE
/* Opcode: Trace * * * P4 *
**
** If tracing is enabled (by the sqlite3_trace()) interface, then
** the UTF-8 string contained in P4 is emitted on the trace callback.
*/
case OP_Trace: {
  char *zTrace;

  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  if( zTrace ){
    if( db->xTrace ){
      db->xTrace(db->pTraceArg, zTrace);
    }
#ifdef SQLITE_DEBUG
    if( (db->flags & SQLITE_SqlTrace)!=0 ){
      sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
    }
#endif /* SQLITE_DEBUG */
  }
  break;
}
#endif


/* Opcode: Noop * * * * *
**
** Do nothing.  This instruction is often useful as a jump
** destination.
*/
/*
** The magic Explain opcode are only inserted when explain==2 (which
** is to say when the EXPLAIN QUERY PLAN syntax is used.)
** This opcode records information from the optimizer.  It is the
** the same as a no-op.  This opcodesnever appears in a real VM program.
*/
default: {          /* This is really OP_Noop and OP_Explain */
  break;
}

/*****************************************************************************
** The cases of the switch statement above this line should all be indented
** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
** readability.  From this point on down, the normal indentation rules are
** restored.
*****************************************************************************/
    }

#ifdef VDBE_PROFILE
    {
      u64 elapsed = sqlite3Hwtime() - start;
      pOp->cycles += elapsed;
      pOp->cnt++;
#if 0
        fprintf(stdout, "%10llu ", elapsed);
        sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
#endif
    }
#endif

    /* The following code adds nothing to the actual functionality
    ** of the program.  It is only here for testing and debugging.
    ** On the other hand, it does burn CPU cycles every time through
    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
    */
#ifndef NDEBUG
    assert( pc>=-1 && pc<p->nOp );

#ifdef SQLITE_DEBUG
    if( p->trace ){
      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
      if( opProperty & OPFLG_OUT2_PRERELEASE ){
        registerTrace(p->trace, pOp->p2, pOut);
      }
      if( opProperty & OPFLG_OUT3 ){
        registerTrace(p->trace, pOp->p3, pOut);
      }
    }
#endif  /* SQLITE_DEBUG */
#endif  /* NDEBUG */
  }  /* The end of the for(;;) loop the loops through opcodes */

  /* If we reach this point, it means that execution is finished with
  ** an error of some kind.
  */
vdbe_error_halt:
  assert( rc );
  p->rc = rc;
  sqlite3VdbeHalt(p);
  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  rc = SQLITE_ERROR;

  /* This is the only way out of this procedure.  We have to
  ** release the mutexes on btrees that were acquired at the
  ** top. */
vdbe_return:
  sqlite3BtreeMutexArrayLeave(&p->aMutex);
  return rc;

  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  ** is encountered.
  */
too_big:
  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  rc = SQLITE_TOOBIG;
  goto vdbe_error_halt;

  /* Jump to here if a malloc() fails.
  */
no_mem:
  db->mallocFailed = 1;
  sqlite3SetString(&p->zErrMsg, db, "out of memory");
  rc = SQLITE_NOMEM;
  goto vdbe_error_halt;

  /* Jump to here for an SQLITE_MISUSE error.
  */
abort_due_to_misuse:
  rc = SQLITE_MISUSE;
  /* Fall thru into abort_due_to_error */

  /* Jump to here for any other kind of fatal error.  The "rc" variable
  ** should hold the error number.
  */
abort_due_to_error:
  assert( p->zErrMsg==0 );
  if( db->mallocFailed ) rc = SQLITE_NOMEM;
  if( rc!=SQLITE_IOERR_NOMEM ){
    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  }
  goto vdbe_error_halt;

  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  ** flag.
  */
abort_due_to_interrupt:
  assert( db->u1.isInterrupted );
  rc = SQLITE_INTERRUPT;
  p->rc = rc;
  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  goto vdbe_error_halt;
}

Added src/vdbe.h.































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Header file for the Virtual DataBase Engine (VDBE)
**
** This header defines the interface to the virtual database engine
** or VDBE.  The VDBE implements an abstract machine that runs a
** simple program to access and modify the underlying database.
**
** $Id: vdbe.h,v 1.142 2009/07/24 17:58:53 danielk1977 Exp $
*/
#ifndef _SQLITE_VDBE_H_
#define _SQLITE_VDBE_H_
#include <stdio.h>

/*
** A single VDBE is an opaque structure named "Vdbe".  Only routines
** in the source file sqliteVdbe.c are allowed to see the insides
** of this structure.
*/
typedef struct Vdbe Vdbe;

/*
** The names of the following types declared in vdbeInt.h are required
** for the VdbeOp definition.
*/
typedef struct VdbeFunc VdbeFunc;
typedef struct Mem Mem;
typedef struct SubProgram SubProgram;

/*
** A single instruction of the virtual machine has an opcode
** and as many as three operands.  The instruction is recorded
** as an instance of the following structure:
*/
struct VdbeOp {
  u8 opcode;          /* What operation to perform */
  signed char p4type; /* One of the P4_xxx constants for p4 */
  u8 opflags;         /* Not currently used */
  u8 p5;              /* Fifth parameter is an unsigned character */
  int p1;             /* First operand */
  int p2;             /* Second parameter (often the jump destination) */
  int p3;             /* The third parameter */
  union {             /* fourth parameter */
    int i;                 /* Integer value if p4type==P4_INT32 */
    void *p;               /* Generic pointer */
    char *z;               /* Pointer to data for string (char array) types */
    i64 *pI64;             /* Used when p4type is P4_INT64 */
    double *pReal;         /* Used when p4type is P4_REAL */
    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
    Mem *pMem;             /* Used when p4type is P4_MEM */
    VTable *pVtab;         /* Used when p4type is P4_VTAB */
    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
    int *ai;               /* Used when p4type is P4_INTARRAY */
    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
  } p4;
#ifdef SQLITE_DEBUG
  char *zComment;          /* Comment to improve readability */
#endif
#ifdef VDBE_PROFILE
  int cnt;                 /* Number of times this instruction was executed */
  u64 cycles;              /* Total time spent executing this instruction */
#endif
};
typedef struct VdbeOp VdbeOp;


/*
** A sub-routine used to implement a trigger program.
*/
struct SubProgram {
  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
  int nOp;                      /* Elements in aOp[] */
  int nMem;                     /* Number of memory cells required */
  int nCsr;                     /* Number of cursors required */
  int nRef;                     /* Number of pointers to this structure */
  void *token;                  /* id that may be used to recursive triggers */
};

/*
** A smaller version of VdbeOp used for the VdbeAddOpList() function because
** it takes up less space.
*/
struct VdbeOpList {
  u8 opcode;          /* What operation to perform */
  signed char p1;     /* First operand */
  signed char p2;     /* Second parameter (often the jump destination) */
  signed char p3;     /* Third parameter */
};
typedef struct VdbeOpList VdbeOpList;

/*
** Allowed values of VdbeOp.p4type
*/
#define P4_NOTUSED    0   /* The P4 parameter is not used */
#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
#define P4_STATIC   (-2)  /* Pointer to a static string */
#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */

/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
** is made.  That copy is freed when the Vdbe is finalized.  But if the
** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
** gets freed when the Vdbe is finalized so it still should be obtained
** from a single sqliteMalloc().  But no copy is made and the calling
** function should *not* try to free the KeyInfo.
*/
#define P4_KEYINFO_HANDOFF (-16)
#define P4_KEYINFO_STATIC  (-17)

/*
** The Vdbe.aColName array contains 5n Mem structures, where n is the 
** number of columns of data returned by the statement.
*/
#define COLNAME_NAME     0
#define COLNAME_DECLTYPE 1
#define COLNAME_DATABASE 2
#define COLNAME_TABLE    3
#define COLNAME_COLUMN   4
#ifdef SQLITE_ENABLE_COLUMN_METADATA
# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
#else
# ifdef SQLITE_OMIT_DECLTYPE
#   define COLNAME_N      1      /* Store only the name */
# else
#   define COLNAME_N      2      /* Store the name and decltype */
# endif
#endif

/*
** The following macro converts a relative address in the p2 field
** of a VdbeOp structure into a negative number so that 
** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
** the macro again restores the address.
*/
#define ADDR(X)  (-1-(X))

/*
** The makefile scans the vdbe.c source file and creates the "opcodes.h"
** header file that defines a number for each opcode used by the VDBE.
*/
#include "opcodes.h"

/*
** Prototypes for the VDBE interface.  See comments on the implementation
** for a description of what each of these routines does.
*/
Vdbe *sqlite3VdbeCreate(sqlite3*);
int sqlite3VdbeAddOp0(Vdbe*,int);
int sqlite3VdbeAddOp1(Vdbe*,int,int);
int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
void sqlite3VdbeJumpHere(Vdbe*, int addr);
void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
void sqlite3VdbeUsesBtree(Vdbe*, int);
VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
int sqlite3VdbeMakeLabel(Vdbe*);
void sqlite3VdbeDelete(Vdbe*);
void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
int sqlite3VdbeFinalize(Vdbe*);
void sqlite3VdbeResolveLabel(Vdbe*, int);
int sqlite3VdbeCurrentAddr(Vdbe*);
#ifdef SQLITE_DEBUG
  int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  void sqlite3VdbeTrace(Vdbe*,FILE*);
#endif
void sqlite3VdbeResetStepResult(Vdbe*);
int sqlite3VdbeReset(Vdbe*);
void sqlite3VdbeSetNumCols(Vdbe*,int);
int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
void sqlite3VdbeCountChanges(Vdbe*);
sqlite3 *sqlite3VdbeDb(Vdbe*);
void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
void sqlite3VdbeSwap(Vdbe*,Vdbe*);
VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
void sqlite3VdbeSetVarmask(Vdbe*, int);

UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);


#ifndef NDEBUG
  void sqlite3VdbeComment(Vdbe*, const char*, ...);
# define VdbeComment(X)  sqlite3VdbeComment X
  void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
#else
# define VdbeComment(X)
# define VdbeNoopComment(X)
#endif

#endif

Added src/vdbeInt.h.

































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
** 2003 September 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for information that is private to the
** VDBE.  This information used to all be at the top of the single
** source code file "vdbe.c".  When that file became too big (over
** 6000 lines long) it was split up into several smaller files and
** this header information was factored out.
**
** $Id: vdbeInt.h,v 1.174 2009/06/23 14:15:04 drh Exp $
*/
#ifndef _VDBEINT_H_
#define _VDBEINT_H_

/*
** SQL is translated into a sequence of instructions to be
** executed by a virtual machine.  Each instruction is an instance
** of the following structure.
*/
typedef struct VdbeOp Op;

/*
** Boolean values
*/
typedef unsigned char Bool;

/*
** A cursor is a pointer into a single BTree within a database file.
** The cursor can seek to a BTree entry with a particular key, or
** loop over all entries of the Btree.  You can also insert new BTree
** entries or retrieve the key or data from the entry that the cursor
** is currently pointing to.
** 
** Every cursor that the virtual machine has open is represented by an
** instance of the following structure.
**
** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
** really a single row that represents the NEW or OLD pseudo-table of
** a row trigger.  The data for the row is stored in VdbeCursor.pData and
** the rowid is in VdbeCursor.iKey.
*/
struct VdbeCursor {
  BtCursor *pCursor;    /* The cursor structure of the backend */
  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
  Bool zeroed;          /* True if zeroed out and ready for reuse */
  Bool rowidIsValid;    /* True if lastRowid is valid */
  Bool atFirst;         /* True if pointing to first entry */
  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
  Bool nullRow;         /* True if pointing to a row with no data */
  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
  Bool isTable;         /* True if a table requiring integer keys */
  Bool isIndex;         /* True if an index containing keys only - no data */
  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
  Btree *pBt;           /* Separate file holding temporary table */
  int pseudoTableReg;   /* Register holding pseudotable content. */
  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
  int nField;           /* Number of fields in the header */
  i64 seqCount;         /* Sequence counter */
  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */

  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
  ** OP_IsUnique opcode on this cursor. */
  int seekResult;

  /* Cached information about the header for the data record that the
  ** cursor is currently pointing to.  Only valid if cacheStatus matches
  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  ** the cache is out of date.
  **
  ** aRow might point to (ephemeral) data for the current row, or it might
  ** be NULL.
  */
  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
  int payloadSize;      /* Total number of bytes in the record */
  u32 *aType;           /* Type values for all entries in the record */
  u32 *aOffset;         /* Cached offsets to the start of each columns data */
  u8 *aRow;             /* Data for the current row, if all on one page */
};
typedef struct VdbeCursor VdbeCursor;

/*
** When a sub-program is executed (OP_Program), a structure of this type
** is allocated to store the current value of the program counter, as
** well as the current memory cell array and various other frame specific
** values stored in the Vdbe struct. When the sub-program is finished, 
** these values are copied back to the Vdbe from the VdbeFrame structure,
** restoring the state of the VM to as it was before the sub-program
** began executing.
**
** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
** is the parent of the current frame, or zero if the current frame
** is the main Vdbe program.
*/
typedef struct VdbeFrame VdbeFrame;
struct VdbeFrame {
  Vdbe *v;                /* VM this frame belongs to */
  int pc;                 /* Program Counter */
  Op *aOp;                /* Program instructions */
  int nOp;                /* Size of aOp array */
  Mem *aMem;              /* Array of memory cells */
  int nMem;               /* Number of entries in aMem */
  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
  u16 nCursor;            /* Number of entries in apCsr */
  void *token;            /* Copy of SubProgram.token */
  int nChildMem;          /* Number of memory cells for child frame */
  int nChildCsr;          /* Number of cursors for child frame */
  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
  int nChange;            /* Statement changes (Vdbe.nChanges)     */
  VdbeFrame *pParent;     /* Parent of this frame */
};

#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])

/*
** A value for VdbeCursor.cacheValid that means the cache is always invalid.
*/
#define CACHE_STALE 0

/*
** Internally, the vdbe manipulates nearly all SQL values as Mem
** structures. Each Mem struct may cache multiple representations (string,
** integer etc.) of the same value.  A value (and therefore Mem structure)
** has the following properties:
**
** Each value has a manifest type. The manifest type of the value stored
** in a Mem struct is returned by the MemType(Mem*) macro. The type is
** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
** SQLITE_BLOB.
*/
struct Mem {
  union {
    i64 i;              /* Integer value. */
    int nZero;          /* Used when bit MEM_Zero is set in flags */
    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
  } u;
  double r;           /* Real value */
  sqlite3 *db;        /* The associated database connection */
  char *z;            /* String or BLOB value */
  int n;              /* Number of characters in string value, excluding '\0' */
  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
};

/* One or more of the following flags are set to indicate the validOK
** representations of the value stored in the Mem struct.
**
** If the MEM_Null flag is set, then the value is an SQL NULL value.
** No other flags may be set in this case.
**
** If the MEM_Str flag is set then Mem.z points at a string representation.
** Usually this is encoded in the same unicode encoding as the main
** database (see below for exceptions). If the MEM_Term flag is also
** set, then the string is nul terminated. The MEM_Int and MEM_Real 
** flags may coexist with the MEM_Str flag.
**
** Multiple of these values can appear in Mem.flags.  But only one
** at a time can appear in Mem.type.
*/
#define MEM_Null      0x0001   /* Value is NULL */
#define MEM_Str       0x0002   /* Value is a string */
#define MEM_Int       0x0004   /* Value is an integer */
#define MEM_Real      0x0008   /* Value is a real number */
#define MEM_Blob      0x0010   /* Value is a BLOB */
#define MEM_RowSet    0x0020   /* Value is a RowSet object */
#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
#define MEM_TypeMask  0x00ff   /* Mask of type bits */

/* Whenever Mem contains a valid string or blob representation, one of
** the following flags must be set to determine the memory management
** policy for Mem.z.  The MEM_Term flag tells us whether or not the
** string is \000 or \u0000 terminated
*/
#define MEM_Term      0x0200   /* String rep is nul terminated */
#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
#define MEM_Static    0x0800   /* Mem.z points to a static string */
#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */

#ifdef SQLITE_OMIT_INCRBLOB
  #undef MEM_Zero
  #define MEM_Zero 0x0000
#endif


/*
** Clear any existing type flags from a Mem and replace them with f
*/
#define MemSetTypeFlag(p, f) \
   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)


/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
** additional information about auxiliary information bound to arguments
** of the function.  This is used to implement the sqlite3_get_auxdata()
** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
** that can be associated with a constant argument to a function.  This
** allows functions such as "regexp" to compile their constant regular
** expression argument once and reused the compiled code for multiple
** invocations.
*/
struct VdbeFunc {
  FuncDef *pFunc;               /* The definition of the function */
  int nAux;                     /* Number of entries allocated for apAux[] */
  struct AuxData {
    void *pAux;                   /* Aux data for the i-th argument */
    void (*xDelete)(void *);      /* Destructor for the aux data */
  } apAux[1];                   /* One slot for each function argument */
};

/*
** The "context" argument for a installable function.  A pointer to an
** instance of this structure is the first argument to the routines used
** implement the SQL functions.
**
** There is a typedef for this structure in sqlite.h.  So all routines,
** even the public interface to SQLite, can use a pointer to this structure.
** But this file is the only place where the internal details of this
** structure are known.
**
** This structure is defined inside of vdbeInt.h because it uses substructures
** (Mem) which are only defined there.
*/
struct sqlite3_context {
  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
  Mem s;                /* The return value is stored here */
  Mem *pMem;            /* Memory cell used to store aggregate context */
  int isError;          /* Error code returned by the function. */
  CollSeq *pColl;       /* Collating sequence */
};

/*
** A Set structure is used for quick testing to see if a value
** is part of a small set.  Sets are used to implement code like
** this:
**            x.y IN ('hi','hoo','hum')
*/
typedef struct Set Set;
struct Set {
  Hash hash;             /* A set is just a hash table */
  HashElem *prev;        /* Previously accessed hash elemen */
};

/*
** An instance of the virtual machine.  This structure contains the complete
** state of the virtual machine.
**
** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
** is really a pointer to an instance of this structure.
**
** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
** any virtual table method invocations made by the vdbe program. It is
** set to 2 for xDestroy method calls and 1 for all other methods. This
** variable is used for two purposes: to allow xDestroy methods to execute
** "DROP TABLE" statements and to prevent some nasty side effects of
** malloc failure when SQLite is invoked recursively by a virtual table 
** method function.
*/
struct Vdbe {
  sqlite3 *db;            /* The database connection that owns this statement */
  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
  int nOp;                /* Number of instructions in the program */
  int nOpAlloc;           /* Number of slots allocated for aOp[] */
  Op *aOp;                /* Space to hold the virtual machine's program */
  int nLabel;             /* Number of labels used */
  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
  int *aLabel;            /* Space to hold the labels */
  Mem **apArg;            /* Arguments to currently executing user function */
  Mem *aColName;          /* Column names to return */
  Mem *pResultSet;        /* Pointer to an array of results */
  u16 nResColumn;         /* Number of columns in one row of the result set */
  u16 nCursor;            /* Number of slots in apCsr[] */
  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
  u8 errorAction;         /* Recovery action to do in case of an error */
  u8 okVar;               /* True if azVar[] has been initialized */
  ynVar nVar;             /* Number of entries in aVar[] */
  Mem *aVar;              /* Values for the OP_Variable opcode. */
  char **azVar;           /* Name of variables */
  u32 magic;              /* Magic number for sanity checking */
  int nMem;               /* Number of memory locations currently allocated */
  Mem *aMem;              /* The memory locations */
  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
  int pc;                 /* The program counter */
  int rc;                 /* Value to return */
  char *zErrMsg;          /* Error message written here */
  u8 explain;             /* True if EXPLAIN present on SQL command */
  u8 changeCntOn;         /* True to update the change-counter */
  u8 expired;             /* True if the VM needs to be recompiled */
  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
  u8 inVtabMethod;        /* See comments above */
  u8 usesStmtJournal;     /* True if uses a statement journal */
  u8 readOnly;            /* True for read-only statements */
  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
  int nChange;            /* Number of db changes made since last reset */
  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
  i64 startTime;          /* Time when query started - used for profiling */
  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
  int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
  char *zSql;             /* Text of the SQL statement that generated this */
  void *pFree;            /* Free this when deleting the vdbe */
  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
#ifdef SQLITE_DEBUG
  FILE *trace;            /* Write an execution trace here, if not NULL */
#endif
  VdbeFrame *pFrame;      /* Parent frame */
  int nFrame;             /* Number of frames in pFrame list */
  u32 expmask;            /* Binding to these vars invalidates VM */
};

/*
** The following are allowed values for Vdbe.magic
*/
#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */

/*
** Function prototypes
*/
void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
void sqliteVdbePopStack(Vdbe*,int);
int sqlite3VdbeCursorMoveto(VdbeCursor*);
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
void sqlite3VdbePrintOp(FILE*, int, Op*);
#endif
u32 sqlite3VdbeSerialTypeLen(u32);
u32 sqlite3VdbeSerialType(Mem*, int);
u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);

int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
int sqlite3VdbeExec(Vdbe*);
int sqlite3VdbeList(Vdbe*);
int sqlite3VdbeHalt(Vdbe*);
int sqlite3VdbeChangeEncoding(Mem *, int);
int sqlite3VdbeMemTooBig(Mem*);
int sqlite3VdbeMemCopy(Mem*, const Mem*);
void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
void sqlite3VdbeMemMove(Mem*, Mem*);
int sqlite3VdbeMemNulTerminate(Mem*);
int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
void sqlite3VdbeMemSetInt64(Mem*, i64);
void sqlite3VdbeMemSetDouble(Mem*, double);
void sqlite3VdbeMemSetNull(Mem*);
void sqlite3VdbeMemSetZeroBlob(Mem*,int);
void sqlite3VdbeMemSetRowSet(Mem*);
int sqlite3VdbeMemMakeWriteable(Mem*);
int sqlite3VdbeMemStringify(Mem*, int);
i64 sqlite3VdbeIntValue(Mem*);
int sqlite3VdbeMemIntegerify(Mem*);
double sqlite3VdbeRealValue(Mem*);
void sqlite3VdbeIntegerAffinity(Mem*);
int sqlite3VdbeMemRealify(Mem*);
int sqlite3VdbeMemNumerify(Mem*);
int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
void sqlite3VdbeMemRelease(Mem *p);
void sqlite3VdbeMemReleaseExternal(Mem *p);
int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
const char *sqlite3OpcodeName(int);
int sqlite3VdbeOpcodeHasProperty(int, int);
int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
int sqlite3VdbeCloseStatement(Vdbe *, int);
void sqlite3VdbeFrameDelete(VdbeFrame*);
int sqlite3VdbeFrameRestore(VdbeFrame *);
void sqlite3VdbeMemStoreType(Mem *pMem);

#ifndef SQLITE_OMIT_FOREIGN_KEY
int sqlite3VdbeCheckFk(Vdbe *, int);
#else
# define sqlite3VdbeCheckFk(p,i) 0
#endif

#ifndef SQLITE_OMIT_SHARED_CACHE
void sqlite3VdbeMutexArrayEnter(Vdbe *p);
#else
# define sqlite3VdbeMutexArrayEnter(p)
#endif

int sqlite3VdbeMemTranslate(Mem*, u8);
#ifdef SQLITE_DEBUG
  void sqlite3VdbePrintSql(Vdbe*);
  void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
#endif
int sqlite3VdbeMemHandleBom(Mem *pMem);

#ifndef SQLITE_OMIT_INCRBLOB
  int sqlite3VdbeMemExpandBlob(Mem *);
#else
  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
#endif

#endif /* !defined(_VDBEINT_H_) */

Added src/vdbeapi.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
/*
** 2004 May 26
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code use to implement APIs that are part of the
** VDBE.
**
** $Id: vdbeapi.c,v 1.167 2009/06/25 01:47:12 drh Exp $
*/
#include "sqliteInt.h"
#include "vdbeInt.h"

#ifndef SQLITE_OMIT_DEPRECATED
/*
** Return TRUE (non-zero) of the statement supplied as an argument needs
** to be recompiled.  A statement needs to be recompiled whenever the
** execution environment changes in a way that would alter the program
** that sqlite3_prepare() generates.  For example, if new functions or
** collating sequences are registered or if an authorizer function is
** added or changed.
*/
int sqlite3_expired(sqlite3_stmt *pStmt){
  Vdbe *p = (Vdbe*)pStmt;
  return p==0 || p->expired;
}
#endif

/*
** The following routine destroys a virtual machine that is created by
** the sqlite3_compile() routine. The integer returned is an SQLITE_
** success/failure code that describes the result of executing the virtual
** machine.
**
** This routine sets the error code and string returned by
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
*/
int sqlite3_finalize(sqlite3_stmt *pStmt){
  int rc;
  if( pStmt==0 ){
    rc = SQLITE_OK;
  }else{
    Vdbe *v = (Vdbe*)pStmt;
    sqlite3 *db = v->db;
#if SQLITE_THREADSAFE
    sqlite3_mutex *mutex = v->db->mutex;
#endif
    sqlite3_mutex_enter(mutex);
    rc = sqlite3VdbeFinalize(v);
    rc = sqlite3ApiExit(db, rc);
    sqlite3_mutex_leave(mutex);
  }
  return rc;
}

/*
** Terminate the current execution of an SQL statement and reset it
** back to its starting state so that it can be reused. A success code from
** the prior execution is returned.
**
** This routine sets the error code and string returned by
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
*/
int sqlite3_reset(sqlite3_stmt *pStmt){
  int rc;
  if( pStmt==0 ){
    rc = SQLITE_OK;
  }else{
    Vdbe *v = (Vdbe*)pStmt;
    sqlite3_mutex_enter(v->db->mutex);
    rc = sqlite3VdbeReset(v);
    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
    assert( (rc & (v->db->errMask))==rc );
    rc = sqlite3ApiExit(v->db, rc);
    sqlite3_mutex_leave(v->db->mutex);
  }
  return rc;
}

/*
** Set all the parameters in the compiled SQL statement to NULL.
*/
int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  int i;
  int rc = SQLITE_OK;
  Vdbe *p = (Vdbe*)pStmt;
#if SQLITE_THREADSAFE
  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
#endif
  sqlite3_mutex_enter(mutex);
  for(i=0; i<p->nVar; i++){
    sqlite3VdbeMemRelease(&p->aVar[i]);
    p->aVar[i].flags = MEM_Null;
  }
  if( p->isPrepareV2 && p->expmask ){
    p->expired = 1;
  }
  sqlite3_mutex_leave(mutex);
  return rc;
}


/**************************** sqlite3_value_  *******************************
** The following routines extract information from a Mem or sqlite3_value
** structure.
*/
const void *sqlite3_value_blob(sqlite3_value *pVal){
  Mem *p = (Mem*)pVal;
  if( p->flags & (MEM_Blob|MEM_Str) ){
    sqlite3VdbeMemExpandBlob(p);
    p->flags &= ~MEM_Str;
    p->flags |= MEM_Blob;
    return p->z;
  }else{
    return sqlite3_value_text(pVal);
  }
}
int sqlite3_value_bytes(sqlite3_value *pVal){
  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
}
int sqlite3_value_bytes16(sqlite3_value *pVal){
  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
}
double sqlite3_value_double(sqlite3_value *pVal){
  return sqlite3VdbeRealValue((Mem*)pVal);
}
int sqlite3_value_int(sqlite3_value *pVal){
  return (int)sqlite3VdbeIntValue((Mem*)pVal);
}
sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  return sqlite3VdbeIntValue((Mem*)pVal);
}
const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_value_text16(sqlite3_value* pVal){
  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
}
const void *sqlite3_value_text16be(sqlite3_value *pVal){
  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
}
const void *sqlite3_value_text16le(sqlite3_value *pVal){
  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
}
#endif /* SQLITE_OMIT_UTF16 */
int sqlite3_value_type(sqlite3_value* pVal){
  return pVal->type;
}

/**************************** sqlite3_result_  *******************************
** The following routines are used by user-defined functions to specify
** the function result.
**
** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
** result as a string or blob but if the string or blob is too large, it
** then sets the error code to SQLITE_TOOBIG
*/
static void setResultStrOrError(
  sqlite3_context *pCtx,  /* Function context */
  const char *z,          /* String pointer */
  int n,                  /* Bytes in string, or negative */
  u8 enc,                 /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*)     /* Destructor function */
){
  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
    sqlite3_result_error_toobig(pCtx);
  }
}
void sqlite3_result_blob(
  sqlite3_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)
){
  assert( n>=0 );
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, 0, xDel);
}
void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
}
void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE_ERROR;
  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
}
#ifndef SQLITE_OMIT_UTF16
void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE_ERROR;
  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
}
#endif
void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
}
void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
}
void sqlite3_result_null(sqlite3_context *pCtx){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemSetNull(&pCtx->s);
}
void sqlite3_result_text(
  sqlite3_context *pCtx, 
  const char *z, 
  int n,
  void (*xDel)(void *)
){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
}
#ifndef SQLITE_OMIT_UTF16
void sqlite3_result_text16(
  sqlite3_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)
){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
}
void sqlite3_result_text16be(
  sqlite3_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)
){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
}
void sqlite3_result_text16le(
  sqlite3_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)
){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
}
#endif /* SQLITE_OMIT_UTF16 */
void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemCopy(&pCtx->s, pValue);
}
void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
}
void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  pCtx->isError = errCode;
  if( pCtx->s.flags & MEM_Null ){
    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
                         SQLITE_UTF8, SQLITE_STATIC);
  }
}

/* Force an SQLITE_TOOBIG error. */
void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE_TOOBIG;
  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
                       SQLITE_UTF8, SQLITE_STATIC);
}

/* An SQLITE_NOMEM error. */
void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  sqlite3VdbeMemSetNull(&pCtx->s);
  pCtx->isError = SQLITE_NOMEM;
  pCtx->s.db->mallocFailed = 1;
}

/*
** Execute the statement pStmt, either until a row of data is ready, the
** statement is completely executed or an error occurs.
**
** This routine implements the bulk of the logic behind the sqlite_step()
** API.  The only thing omitted is the automatic recompile if a 
** schema change has occurred.  That detail is handled by the
** outer sqlite3_step() wrapper procedure.
*/
static int sqlite3Step(Vdbe *p){
  sqlite3 *db;
  int rc;

  assert(p);
  if( p->magic!=VDBE_MAGIC_RUN ){
    return SQLITE_MISUSE;
  }

  /* Assert that malloc() has not failed */
  db = p->db;
  if( db->mallocFailed ){
    return SQLITE_NOMEM;
  }

  if( p->pc<=0 && p->expired ){
    if( ALWAYS(p->rc==SQLITE_OK || p->rc==SQLITE_SCHEMA) ){
      p->rc = SQLITE_SCHEMA;
    }
    rc = SQLITE_ERROR;
    goto end_of_step;
  }
  if( sqlite3SafetyOn(db) ){
    p->rc = SQLITE_MISUSE;
    return SQLITE_MISUSE;
  }
  if( p->pc<0 ){
    /* If there are no other statements currently running, then
    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
    ** from interrupting a statement that has not yet started.
    */
    if( db->activeVdbeCnt==0 ){
      db->u1.isInterrupted = 0;
    }

    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );

#ifndef SQLITE_OMIT_TRACE
    if( db->xProfile && !db->init.busy ){
      double rNow;
      sqlite3OsCurrentTime(db->pVfs, &rNow);
      p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
    }
#endif

    db->activeVdbeCnt++;
    if( p->readOnly==0 ) db->writeVdbeCnt++;
    p->pc = 0;
  }
#ifndef SQLITE_OMIT_EXPLAIN
  if( p->explain ){
    rc = sqlite3VdbeList(p);
  }else
#endif /* SQLITE_OMIT_EXPLAIN */
  {
    rc = sqlite3VdbeExec(p);
  }

  if( sqlite3SafetyOff(db) ){
    rc = SQLITE_MISUSE;
  }

#ifndef SQLITE_OMIT_TRACE
  /* Invoke the profile callback if there is one
  */
  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
    double rNow;
    u64 elapseTime;

    sqlite3OsCurrentTime(db->pVfs, &rNow);
    elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
    elapseTime -= p->startTime;
    db->xProfile(db->pProfileArg, p->zSql, elapseTime);
  }
#endif

  db->errCode = rc;
  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
    p->rc = SQLITE_NOMEM;
  }
end_of_step:
  /* At this point local variable rc holds the value that should be 
  ** returned if this statement was compiled using the legacy 
  ** sqlite3_prepare() interface. According to the docs, this can only
  ** be one of the values in the first assert() below. Variable p->rc 
  ** contains the value that would be returned if sqlite3_finalize() 
  ** were called on statement p.
  */
  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  );
  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
    /* If this statement was prepared using sqlite3_prepare_v2(), and an
    ** error has occured, then return the error code in p->rc to the
    ** caller. Set the error code in the database handle to the same value.
    */ 
    rc = db->errCode = p->rc;
  }
  return (rc&db->errMask);
}

/*
** This is the top-level implementation of sqlite3_step().  Call
** sqlite3Step() to do most of the work.  If a schema error occurs,
** call sqlite3Reprepare() and try again.
*/
int sqlite3_step(sqlite3_stmt *pStmt){
  int rc = SQLITE_MISUSE;
  if( pStmt ){
    int cnt = 0;
    Vdbe *v = (Vdbe*)pStmt;
    sqlite3 *db = v->db;
    sqlite3_mutex_enter(db->mutex);
    while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
           && cnt++ < 5
           && (rc = sqlite3Reprepare(v))==SQLITE_OK ){
      sqlite3_reset(pStmt);
      v->expired = 0;
    }
    if( rc==SQLITE_SCHEMA && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
      /* This case occurs after failing to recompile an sql statement. 
      ** The error message from the SQL compiler has already been loaded 
      ** into the database handle. This block copies the error message 
      ** from the database handle into the statement and sets the statement
      ** program counter to 0 to ensure that when the statement is 
      ** finalized or reset the parser error message is available via
      ** sqlite3_errmsg() and sqlite3_errcode().
      */
      const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
      sqlite3DbFree(db, v->zErrMsg);
      if( !db->mallocFailed ){
        v->zErrMsg = sqlite3DbStrDup(db, zErr);
      } else {
        v->zErrMsg = 0;
        v->rc = SQLITE_NOMEM;
      }
    }
    rc = sqlite3ApiExit(db, rc);
    sqlite3_mutex_leave(db->mutex);
  }
  return rc;
}

/*
** Extract the user data from a sqlite3_context structure and return a
** pointer to it.
*/
void *sqlite3_user_data(sqlite3_context *p){
  assert( p && p->pFunc );
  return p->pFunc->pUserData;
}

/*
** Extract the user data from a sqlite3_context structure and return a
** pointer to it.
*/
sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  assert( p && p->pFunc );
  return p->s.db;
}

/*
** The following is the implementation of an SQL function that always
** fails with an error message stating that the function is used in the
** wrong context.  The sqlite3_overload_function() API might construct
** SQL function that use this routine so that the functions will exist
** for name resolution but are actually overloaded by the xFindFunction
** method of virtual tables.
*/
void sqlite3InvalidFunction(
  sqlite3_context *context,  /* The function calling context */
  int NotUsed,               /* Number of arguments to the function */
  sqlite3_value **NotUsed2   /* Value of each argument */
){
  const char *zName = context->pFunc->zName;
  char *zErr;
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  zErr = sqlite3_mprintf(
      "unable to use function %s in the requested context", zName);
  sqlite3_result_error(context, zErr, -1);
  sqlite3_free(zErr);
}

/*
** Allocate or return the aggregate context for a user function.  A new
** context is allocated on the first call.  Subsequent calls return the
** same context that was returned on prior calls.
*/
void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  Mem *pMem;
  assert( p && p->pFunc && p->pFunc->xStep );
  assert( sqlite3_mutex_held(p->s.db->mutex) );
  pMem = p->pMem;
  if( (pMem->flags & MEM_Agg)==0 ){
    if( nByte==0 ){
      sqlite3VdbeMemReleaseExternal(pMem);
      pMem->flags = MEM_Null;
      pMem->z = 0;
    }else{
      sqlite3VdbeMemGrow(pMem, nByte, 0);
      pMem->flags = MEM_Agg;
      pMem->u.pDef = p->pFunc;
      if( pMem->z ){
        memset(pMem->z, 0, nByte);
      }
    }
  }
  return (void*)pMem->z;
}

/*
** Return the auxilary data pointer, if any, for the iArg'th argument to
** the user-function defined by pCtx.
*/
void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  VdbeFunc *pVdbeFunc;

  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  pVdbeFunc = pCtx->pVdbeFunc;
  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
    return 0;
  }
  return pVdbeFunc->apAux[iArg].pAux;
}

/*
** Set the auxilary data pointer and delete function, for the iArg'th
** argument to the user-function defined by pCtx. Any previous value is
** deleted by calling the delete function specified when it was set.
*/
void sqlite3_set_auxdata(
  sqlite3_context *pCtx, 
  int iArg, 
  void *pAux, 
  void (*xDelete)(void*)
){
  struct AuxData *pAuxData;
  VdbeFunc *pVdbeFunc;
  if( iArg<0 ) goto failed;

  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  pVdbeFunc = pCtx->pVdbeFunc;
  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
    if( !pVdbeFunc ){
      goto failed;
    }
    pCtx->pVdbeFunc = pVdbeFunc;
    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
    pVdbeFunc->nAux = iArg+1;
    pVdbeFunc->pFunc = pCtx->pFunc;
  }

  pAuxData = &pVdbeFunc->apAux[iArg];
  if( pAuxData->pAux && pAuxData->xDelete ){
    pAuxData->xDelete(pAuxData->pAux);
  }
  pAuxData->pAux = pAux;
  pAuxData->xDelete = xDelete;
  return;

failed:
  if( xDelete ){
    xDelete(pAux);
  }
}

#ifndef SQLITE_OMIT_DEPRECATED
/*
** Return the number of times the Step function of a aggregate has been 
** called.
**
** This function is deprecated.  Do not use it for new code.  It is
** provide only to avoid breaking legacy code.  New aggregate function
** implementations should keep their own counts within their aggregate
** context.
*/
int sqlite3_aggregate_count(sqlite3_context *p){
  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  return p->pMem->n;
}
#endif

/*
** Return the number of columns in the result set for the statement pStmt.
*/
int sqlite3_column_count(sqlite3_stmt *pStmt){
  Vdbe *pVm = (Vdbe *)pStmt;
  return pVm ? pVm->nResColumn : 0;
}

/*
** Return the number of values available from the current row of the
** currently executing statement pStmt.
*/
int sqlite3_data_count(sqlite3_stmt *pStmt){
  Vdbe *pVm = (Vdbe *)pStmt;
  if( pVm==0 || pVm->pResultSet==0 ) return 0;
  return pVm->nResColumn;
}


/*
** Check to see if column iCol of the given statement is valid.  If
** it is, return a pointer to the Mem for the value of that column.
** If iCol is not valid, return a pointer to a Mem which has a value
** of NULL.
*/
static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  Vdbe *pVm;
  int vals;
  Mem *pOut;

  pVm = (Vdbe *)pStmt;
  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
    sqlite3_mutex_enter(pVm->db->mutex);
    vals = sqlite3_data_count(pStmt);
    pOut = &pVm->pResultSet[i];
  }else{
    /* If the value passed as the second argument is out of range, return
    ** a pointer to the following static Mem object which contains the
    ** value SQL NULL. Even though the Mem structure contains an element
    ** of type i64, on certain architecture (x86) with certain compiler
    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
    ** instead of an 8-byte one. This all works fine, except that when
    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
    ** that a Mem structure is located on an 8-byte boundary. To prevent
    ** this assert() from failing, when building with SQLITE_DEBUG defined
    ** using gcc, force nullMem to be 8-byte aligned using the magical
    ** __attribute__((aligned(8))) macro.  */
    static const Mem nullMem 
#if defined(SQLITE_DEBUG) && defined(__GNUC__)
      __attribute__((aligned(8))) 
#endif
      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };

    if( pVm && ALWAYS(pVm->db) ){
      sqlite3_mutex_enter(pVm->db->mutex);
      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    }
    pOut = (Mem*)&nullMem;
  }
  return pOut;
}

/*
** This function is called after invoking an sqlite3_value_XXX function on a 
** column value (i.e. a value returned by evaluating an SQL expression in the
** select list of a SELECT statement) that may cause a malloc() failure. If 
** malloc() has failed, the threads mallocFailed flag is cleared and the result
** code of statement pStmt set to SQLITE_NOMEM.
**
** Specifically, this is called from within:
**
**     sqlite3_column_int()
**     sqlite3_column_int64()
**     sqlite3_column_text()
**     sqlite3_column_text16()
**     sqlite3_column_real()
**     sqlite3_column_bytes()
**     sqlite3_column_bytes16()
**
** But not for sqlite3_column_blob(), which never calls malloc().
*/
static void columnMallocFailure(sqlite3_stmt *pStmt)
{
  /* If malloc() failed during an encoding conversion within an
  ** sqlite3_column_XXX API, then set the return code of the statement to
  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  ** and _finalize() will return NOMEM.
  */
  Vdbe *p = (Vdbe *)pStmt;
  if( p ){
    p->rc = sqlite3ApiExit(p->db, p->rc);
    sqlite3_mutex_leave(p->db->mutex);
  }
}

/**************************** sqlite3_column_  *******************************
** The following routines are used to access elements of the current row
** in the result set.
*/
const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  const void *val;
  val = sqlite3_value_blob( columnMem(pStmt,i) );
  /* Even though there is no encoding conversion, value_blob() might
  ** need to call malloc() to expand the result of a zeroblob() 
  ** expression. 
  */
  columnMallocFailure(pStmt);
  return val;
}
int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  double val = sqlite3_value_double( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  int val = sqlite3_value_int( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  Mem *pOut = columnMem(pStmt, i);
  if( pOut->flags&MEM_Static ){
    pOut->flags &= ~MEM_Static;
    pOut->flags |= MEM_Ephem;
  }
  columnMallocFailure(pStmt);
  return (sqlite3_value *)pOut;
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return val;
}
#endif /* SQLITE_OMIT_UTF16 */
int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  int iType = sqlite3_value_type( columnMem(pStmt,i) );
  columnMallocFailure(pStmt);
  return iType;
}

/* The following function is experimental and subject to change or
** removal */
/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
**}
*/

/*
** Convert the N-th element of pStmt->pColName[] into a string using
** xFunc() then return that string.  If N is out of range, return 0.
**
** There are up to 5 names for each column.  useType determines which
** name is returned.  Here are the names:
**
**    0      The column name as it should be displayed for output
**    1      The datatype name for the column
**    2      The name of the database that the column derives from
**    3      The name of the table that the column derives from
**    4      The name of the table column that the result column derives from
**
** If the result is not a simple column reference (if it is an expression
** or a constant) then useTypes 2, 3, and 4 return NULL.
*/
static const void *columnName(
  sqlite3_stmt *pStmt,
  int N,
  const void *(*xFunc)(Mem*),
  int useType
){
  const void *ret = 0;
  Vdbe *p = (Vdbe *)pStmt;
  int n;
  sqlite3 *db = p->db;
  
  assert( db!=0 );
  n = sqlite3_column_count(pStmt);
  if( N<n && N>=0 ){
    N += useType*n;
    sqlite3_mutex_enter(db->mutex);
    assert( db->mallocFailed==0 );
    ret = xFunc(&p->aColName[N]);
     /* A malloc may have failed inside of the xFunc() call. If this
    ** is the case, clear the mallocFailed flag and return NULL.
    */
    if( db->mallocFailed ){
      db->mallocFailed = 0;
      ret = 0;
    }
    sqlite3_mutex_leave(db->mutex);
  }
  return ret;
}

/*
** Return the name of the Nth column of the result set returned by SQL
** statement pStmt.
*/
const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
}
#endif

/*
** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
** not define OMIT_DECLTYPE.
*/
#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
# error "Must not define both SQLITE_OMIT_DECLTYPE \
         and SQLITE_ENABLE_COLUMN_METADATA"
#endif

#ifndef SQLITE_OMIT_DECLTYPE
/*
** Return the column declaration type (if applicable) of the 'i'th column
** of the result set of SQL statement pStmt.
*/
const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
}
#endif /* SQLITE_OMIT_UTF16 */
#endif /* SQLITE_OMIT_DECLTYPE */

#ifdef SQLITE_ENABLE_COLUMN_METADATA
/*
** Return the name of the database from which a result column derives.
** NULL is returned if the result column is an expression or constant or
** anything else which is not an unabiguous reference to a database column.
*/
const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Return the name of the table from which a result column derives.
** NULL is returned if the result column is an expression or constant or
** anything else which is not an unabiguous reference to a database column.
*/
const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Return the name of the table column from which a result column derives.
** NULL is returned if the result column is an expression or constant or
** anything else which is not an unabiguous reference to a database column.
*/
const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  return columnName(
      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
}
#endif /* SQLITE_OMIT_UTF16 */
#endif /* SQLITE_ENABLE_COLUMN_METADATA */


/******************************* sqlite3_bind_  ***************************
** 
** Routines used to attach values to wildcards in a compiled SQL statement.
*/
/*
** Unbind the value bound to variable i in virtual machine p. This is the 
** the same as binding a NULL value to the column. If the "i" parameter is
** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
**
** A successful evaluation of this routine acquires the mutex on p.
** the mutex is released if any kind of error occurs.
**
** The error code stored in database p->db is overwritten with the return
** value in any case.
*/
static int vdbeUnbind(Vdbe *p, int i){
  Mem *pVar;
  if( p==0 ) return SQLITE_MISUSE;
  sqlite3_mutex_enter(p->db->mutex);
  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
    sqlite3Error(p->db, SQLITE_MISUSE, 0);
    sqlite3_mutex_leave(p->db->mutex);
    return SQLITE_MISUSE;
  }
  if( i<1 || i>p->nVar ){
    sqlite3Error(p->db, SQLITE_RANGE, 0);
    sqlite3_mutex_leave(p->db->mutex);
    return SQLITE_RANGE;
  }
  i--;
  pVar = &p->aVar[i];
  sqlite3VdbeMemRelease(pVar);
  pVar->flags = MEM_Null;
  sqlite3Error(p->db, SQLITE_OK, 0);

  /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
  ** binding a new value to this variable invalidates the current query plan.
  */
  if( p->isPrepareV2 &&
     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  ){
    p->expired = 1;
  }
  return SQLITE_OK;
}

/*
** Bind a text or BLOB value.
*/
static int bindText(
  sqlite3_stmt *pStmt,   /* The statement to bind against */
  int i,                 /* Index of the parameter to bind */
  const void *zData,     /* Pointer to the data to be bound */
  int nData,             /* Number of bytes of data to be bound */
  void (*xDel)(void*),   /* Destructor for the data */
  u8 encoding            /* Encoding for the data */
){
  Vdbe *p = (Vdbe *)pStmt;
  Mem *pVar;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc==SQLITE_OK ){
    if( zData!=0 ){
      pVar = &p->aVar[i-1];
      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
      if( rc==SQLITE_OK && encoding!=0 ){
        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
      }
      sqlite3Error(p->db, rc, 0);
      rc = sqlite3ApiExit(p->db, rc);
    }
    sqlite3_mutex_leave(p->db->mutex);
  }
  return rc;
}


/*
** Bind a blob value to an SQL statement variable.
*/
int sqlite3_bind_blob(
  sqlite3_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  void (*xDel)(void*)
){
  return bindText(pStmt, i, zData, nData, xDel, 0);
}
int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  int rc;
  Vdbe *p = (Vdbe *)pStmt;
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE_OK ){
    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
    sqlite3_mutex_leave(p->db->mutex);
  }
  return rc;
}
int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  return sqlite3_bind_int64(p, i, (i64)iValue);
}
int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  int rc;
  Vdbe *p = (Vdbe *)pStmt;
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE_OK ){
    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
    sqlite3_mutex_leave(p->db->mutex);
  }
  return rc;
}
int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  int rc;
  Vdbe *p = (Vdbe*)pStmt;
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE_OK ){
    sqlite3_mutex_leave(p->db->mutex);
  }
  return rc;
}
int sqlite3_bind_text( 
  sqlite3_stmt *pStmt, 
  int i, 
  const char *zData, 
  int nData, 
  void (*xDel)(void*)
){
  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
}
#ifndef SQLITE_OMIT_UTF16
int sqlite3_bind_text16(
  sqlite3_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  void (*xDel)(void*)
){
  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
}
#endif /* SQLITE_OMIT_UTF16 */
int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  int rc;
  switch( pValue->type ){
    case SQLITE_INTEGER: {
      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
      break;
    }
    case SQLITE_FLOAT: {
      rc = sqlite3_bind_double(pStmt, i, pValue->r);
      break;
    }
    case SQLITE_BLOB: {
      if( pValue->flags & MEM_Zero ){
        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
      }else{
        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
      }
      break;
    }
    case SQLITE_TEXT: {
      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
                              pValue->enc);
      break;
    }
    default: {
      rc = sqlite3_bind_null(pStmt, i);
      break;
    }
  }
  return rc;
}
int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  int rc;
  Vdbe *p = (Vdbe *)pStmt;
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE_OK ){
    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
    sqlite3_mutex_leave(p->db->mutex);
  }
  return rc;
}

/*
** Return the number of wildcards that can be potentially bound to.
** This routine is added to support DBD::SQLite.  
*/
int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  Vdbe *p = (Vdbe*)pStmt;
  return p ? p->nVar : 0;
}

/*
** Create a mapping from variable numbers to variable names
** in the Vdbe.azVar[] array, if such a mapping does not already
** exist.
*/
static void createVarMap(Vdbe *p){
  if( !p->okVar ){
    int j;
    Op *pOp;
    sqlite3_mutex_enter(p->db->mutex);
    /* The race condition here is harmless.  If two threads call this
    ** routine on the same Vdbe at the same time, they both might end
    ** up initializing the Vdbe.azVar[] array.  That is a little extra
    ** work but it results in the same answer.
    */
    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
      if( pOp->opcode==OP_Variable ){
        assert( pOp->p1>0 && pOp->p1<=p->nVar );
        p->azVar[pOp->p1-1] = pOp->p4.z;
      }
    }
    p->okVar = 1;
    sqlite3_mutex_leave(p->db->mutex);
  }
}

/*
** Return the name of a wildcard parameter.  Return NULL if the index
** is out of range or if the wildcard is unnamed.
**
** The result is always UTF-8.
*/
const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  Vdbe *p = (Vdbe*)pStmt;
  if( p==0 || i<1 || i>p->nVar ){
    return 0;
  }
  createVarMap(p);
  return p->azVar[i-1];
}

/*
** Given a wildcard parameter name, return the index of the variable
** with that name.  If there is no variable with the given name,
** return 0.
*/
int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  Vdbe *p = (Vdbe*)pStmt;
  int i;
  if( p==0 ){
    return 0;
  }
  createVarMap(p); 
  if( zName ){
    for(i=0; i<p->nVar; i++){
      const char *z = p->azVar[i];
      if( z && strcmp(z,zName)==0 ){
        return i+1;
      }
    }
  }
  return 0;
}

/*
** Transfer all bindings from the first statement over to the second.
*/
int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  Vdbe *pFrom = (Vdbe*)pFromStmt;
  Vdbe *pTo = (Vdbe*)pToStmt;
  int i;
  assert( pTo->db==pFrom->db );
  assert( pTo->nVar==pFrom->nVar );
  sqlite3_mutex_enter(pTo->db->mutex);
  for(i=0; i<pFrom->nVar; i++){
    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  }
  sqlite3_mutex_leave(pTo->db->mutex);
  return SQLITE_OK;
}

#ifndef SQLITE_OMIT_DEPRECATED
/*
** Deprecated external interface.  Internal/core SQLite code
** should call sqlite3TransferBindings.
**
** Is is misuse to call this routine with statements from different
** database connections.  But as this is a deprecated interface, we
** will not bother to check for that condition.
**
** If the two statements contain a different number of bindings, then
** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
** SQLITE_OK is returned.
*/
int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  Vdbe *pFrom = (Vdbe*)pFromStmt;
  Vdbe *pTo = (Vdbe*)pToStmt;
  if( pFrom->nVar!=pTo->nVar ){
    return SQLITE_ERROR;
  }
  if( pTo->isPrepareV2 && pTo->expmask ){
    pTo->expired = 1;
  }
  if( pFrom->isPrepareV2 && pFrom->expmask ){
    pFrom->expired = 1;
  }
  return sqlite3TransferBindings(pFromStmt, pToStmt);
}
#endif

/*
** Return the sqlite3* database handle to which the prepared statement given
** in the argument belongs.  This is the same database handle that was
** the first argument to the sqlite3_prepare() that was used to create
** the statement in the first place.
*/
sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  return pStmt ? ((Vdbe*)pStmt)->db : 0;
}

/*
** Return a pointer to the next prepared statement after pStmt associated
** with database connection pDb.  If pStmt is NULL, return the first
** prepared statement for the database connection.  Return NULL if there
** are no more.
*/
sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  sqlite3_stmt *pNext;
  sqlite3_mutex_enter(pDb->mutex);
  if( pStmt==0 ){
    pNext = (sqlite3_stmt*)pDb->pVdbe;
  }else{
    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  }
  sqlite3_mutex_leave(pDb->mutex);
  return pNext;
}

/*
** Return the value of a status counter for a prepared statement
*/
int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  Vdbe *pVdbe = (Vdbe*)pStmt;
  int v = pVdbe->aCounter[op-1];
  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
  return v;
}

Added src/vdbeaux.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
/*
** 2003 September 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used for creating, destroying, and populating
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
** to version 2.8.7, all this code was combined into the vdbe.c source file.
** But that file was getting too big so this subroutines were split out.
**
** $Id: vdbeaux.c,v 1.480 2009/08/08 18:01:08 drh Exp $
*/
#include "sqliteInt.h"
#include "vdbeInt.h"



/*
** When debugging the code generator in a symbolic debugger, one can
** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
** as they are added to the instruction stream.
*/
#ifdef SQLITE_DEBUG
int sqlite3VdbeAddopTrace = 0;
#endif


/*
** Create a new virtual database engine.
*/
Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  Vdbe *p;
  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  if( p==0 ) return 0;
  p->db = db;
  if( db->pVdbe ){
    db->pVdbe->pPrev = p;
  }
  p->pNext = db->pVdbe;
  p->pPrev = 0;
  db->pVdbe = p;
  p->magic = VDBE_MAGIC_INIT;
  return p;
}

/*
** Remember the SQL string for a prepared statement.
*/
void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  assert( isPrepareV2==1 || isPrepareV2==0 );
  if( p==0 ) return;
#ifdef SQLITE_OMIT_TRACE
  if( !isPrepareV2 ) return;
#endif
  assert( p->zSql==0 );
  p->zSql = sqlite3DbStrNDup(p->db, z, n);
  p->isPrepareV2 = (u8)isPrepareV2;
}

/*
** Return the SQL associated with a prepared statement
*/
const char *sqlite3_sql(sqlite3_stmt *pStmt){
  Vdbe *p = (Vdbe *)pStmt;
  return (p->isPrepareV2 ? p->zSql : 0);
}

/*
** Swap all content between two VDBE structures.
*/
void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  Vdbe tmp, *pTmp;
  char *zTmp;
  tmp = *pA;
  *pA = *pB;
  *pB = tmp;
  pTmp = pA->pNext;
  pA->pNext = pB->pNext;
  pB->pNext = pTmp;
  pTmp = pA->pPrev;
  pA->pPrev = pB->pPrev;
  pB->pPrev = pTmp;
  zTmp = pA->zSql;
  pA->zSql = pB->zSql;
  pB->zSql = zTmp;
  pB->isPrepareV2 = pA->isPrepareV2;
}

#ifdef SQLITE_DEBUG
/*
** Turn tracing on or off
*/
void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  p->trace = trace;
}
#endif

/*
** Resize the Vdbe.aOp array so that it is at least one op larger than 
** it was.
**
** If an out-of-memory error occurs while resizing the array, return
** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
** unchanged (this is so that any opcodes already allocated can be 
** correctly deallocated along with the rest of the Vdbe).
*/
static int growOpArray(Vdbe *p){
  VdbeOp *pNew;
  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  if( pNew ){
    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
    p->aOp = pNew;
  }
  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
}

/*
** Add a new instruction to the list of instructions current in the
** VDBE.  Return the address of the new instruction.
**
** Parameters:
**
**    p               Pointer to the VDBE
**
**    op              The opcode for this instruction
**
**    p1, p2, p3      Operands
**
** Use the sqlite3VdbeResolveLabel() function to fix an address and
** the sqlite3VdbeChangeP4() function to change the value of the P4
** operand.
*/
int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  int i;
  VdbeOp *pOp;

  i = p->nOp;
  assert( p->magic==VDBE_MAGIC_INIT );
  assert( op>0 && op<0xff );
  if( p->nOpAlloc<=i ){
    if( growOpArray(p) ){
      return 1;
    }
  }
  p->nOp++;
  pOp = &p->aOp[i];
  pOp->opcode = (u8)op;
  pOp->p5 = 0;
  pOp->p1 = p1;
  pOp->p2 = p2;
  pOp->p3 = p3;
  pOp->p4.p = 0;
  pOp->p4type = P4_NOTUSED;
  p->expired = 0;
#ifdef SQLITE_DEBUG
  pOp->zComment = 0;
  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
#endif
#ifdef VDBE_PROFILE
  pOp->cycles = 0;
  pOp->cnt = 0;
#endif
  return i;
}
int sqlite3VdbeAddOp0(Vdbe *p, int op){
  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
}
int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
}
int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
}


/*
** Add an opcode that includes the p4 value as a pointer.
*/
int sqlite3VdbeAddOp4(
  Vdbe *p,            /* Add the opcode to this VM */
  int op,             /* The new opcode */
  int p1,             /* The P1 operand */
  int p2,             /* The P2 operand */
  int p3,             /* The P3 operand */
  const char *zP4,    /* The P4 operand */
  int p4type          /* P4 operand type */
){
  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  return addr;
}

/*
** Create a new symbolic label for an instruction that has yet to be
** coded.  The symbolic label is really just a negative number.  The
** label can be used as the P2 value of an operation.  Later, when
** the label is resolved to a specific address, the VDBE will scan
** through its operation list and change all values of P2 which match
** the label into the resolved address.
**
** The VDBE knows that a P2 value is a label because labels are
** always negative and P2 values are suppose to be non-negative.
** Hence, a negative P2 value is a label that has yet to be resolved.
**
** Zero is returned if a malloc() fails.
*/
int sqlite3VdbeMakeLabel(Vdbe *p){
  int i;
  i = p->nLabel++;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( i>=p->nLabelAlloc ){
    int n = p->nLabelAlloc*2 + 5;
    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
                                       n*sizeof(p->aLabel[0]));
    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
  }
  if( p->aLabel ){
    p->aLabel[i] = -1;
  }
  return -1-i;
}

/*
** Resolve label "x" to be the address of the next instruction to
** be inserted.  The parameter "x" must have been obtained from
** a prior call to sqlite3VdbeMakeLabel().
*/
void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  int j = -1-x;
  assert( p->magic==VDBE_MAGIC_INIT );
  assert( j>=0 && j<p->nLabel );
  if( p->aLabel ){
    p->aLabel[j] = p->nOp;
  }
}

#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */

/*
** The following type and function are used to iterate through all opcodes
** in a Vdbe main program and each of the sub-programs (triggers) it may 
** invoke directly or indirectly. It should be used as follows:
**
**   Op *pOp;
**   VdbeOpIter sIter;
**
**   memset(&sIter, 0, sizeof(sIter));
**   sIter.v = v;                            // v is of type Vdbe* 
**   while( (pOp = opIterNext(&sIter)) ){
**     // Do something with pOp
**   }
**   sqlite3DbFree(v->db, sIter.apSub);
** 
*/
typedef struct VdbeOpIter VdbeOpIter;
struct VdbeOpIter {
  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
  SubProgram **apSub;        /* Array of subprograms */
  int nSub;                  /* Number of entries in apSub */
  int iAddr;                 /* Address of next instruction to return */
  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
};
static Op *opIterNext(VdbeOpIter *p){
  Vdbe *v = p->v;
  Op *pRet = 0;
  Op *aOp;
  int nOp;

  if( p->iSub<=p->nSub ){

    if( p->iSub==0 ){
      aOp = v->aOp;
      nOp = v->nOp;
    }else{
      aOp = p->apSub[p->iSub-1]->aOp;
      nOp = p->apSub[p->iSub-1]->nOp;
    }
    assert( p->iAddr<nOp );

    pRet = &aOp[p->iAddr];
    p->iAddr++;
    if( p->iAddr==nOp ){
      p->iSub++;
      p->iAddr = 0;
    }
  
    if( pRet->p4type==P4_SUBPROGRAM ){
      int nByte = (p->nSub+1)*sizeof(SubProgram*);
      int j;
      for(j=0; j<p->nSub; j++){
        if( p->apSub[j]==pRet->p4.pProgram ) break;
      }
      if( j==p->nSub ){
        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
        if( !p->apSub ){
          pRet = 0;
        }else{
          p->apSub[p->nSub++] = pRet->p4.pProgram;
        }
      }
    }
  }

  return pRet;
}

/*
** Check if the program stored in the VM associated with pParse may
** throw an ABORT exception (causing the statement, but not entire transaction
** to be rolled back). This condition is true if the main program or any
** sub-programs contains any of the following:
**
**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
**   *  OP_Destroy
**   *  OP_VUpdate
**   *  OP_VRename
**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
**
** Then check that the value of Parse.mayAbort is true if an
** ABORT may be thrown, or false otherwise. Return true if it does
** match, or false otherwise. This function is intended to be used as
** part of an assert statement in the compiler. Similar to:
**
**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
*/
int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  int hasAbort = 0;
  Op *pOp;
  VdbeOpIter sIter;
  memset(&sIter, 0, sizeof(sIter));
  sIter.v = v;

  while( (pOp = opIterNext(&sIter))!=0 ){
    int opcode = pOp->opcode;
    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
#ifndef SQLITE_OMIT_FOREIGN_KEY
     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
#endif
     || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
    ){
      hasAbort = 1;
      break;
    }
  }
  sqlite3DbFree(v->db, sIter.apSub);

  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
  ** If malloc failed, then the while() loop above may not have iterated
  ** through all opcodes and hasAbort may be set incorrectly. Return
  ** true for this case to prevent the assert() in the callers frame
  ** from failing.  */
  return ( v->db->mallocFailed || hasAbort==mayAbort );
}
#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */

/*
** Loop through the program looking for P2 values that are negative
** on jump instructions.  Each such value is a label.  Resolve the
** label by setting the P2 value to its correct non-zero value.
**
** This routine is called once after all opcodes have been inserted.
**
** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
*/
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  int i;
  int nMaxArgs = *pMaxFuncArgs;
  Op *pOp;
  int *aLabel = p->aLabel;
  p->readOnly = 1;
  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
    u8 opcode = pOp->opcode;

    if( opcode==OP_Function || opcode==OP_AggStep ){
      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
#ifndef SQLITE_OMIT_VIRTUALTABLE
    }else if( opcode==OP_VUpdate ){
      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
#endif
    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
      p->readOnly = 0;
#ifndef SQLITE_OMIT_VIRTUALTABLE
    }else if( opcode==OP_VFilter ){
      int n;
      assert( p->nOp - i >= 3 );
      assert( pOp[-1].opcode==OP_Integer );
      n = pOp[-1].p1;
      if( n>nMaxArgs ) nMaxArgs = n;
#endif
    }

    if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
      assert( -1-pOp->p2<p->nLabel );
      pOp->p2 = aLabel[-1-pOp->p2];
    }
  }
  sqlite3DbFree(p->db, p->aLabel);
  p->aLabel = 0;

  *pMaxFuncArgs = nMaxArgs;
}

/*
** Return the address of the next instruction to be inserted.
*/
int sqlite3VdbeCurrentAddr(Vdbe *p){
  assert( p->magic==VDBE_MAGIC_INIT );
  return p->nOp;
}

/*
** This function returns a pointer to the array of opcodes associated with
** the Vdbe passed as the first argument. It is the callers responsibility
** to arrange for the returned array to be eventually freed using the 
** vdbeFreeOpArray() function.
**
** Before returning, *pnOp is set to the number of entries in the returned
** array. Also, *pnMaxArg is set to the larger of its current value and 
** the number of entries in the Vdbe.apArg[] array required to execute the 
** returned program.
*/
VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  VdbeOp *aOp = p->aOp;
  assert( aOp && !p->db->mallocFailed );

  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  assert( p->aMutex.nMutex==0 );

  resolveP2Values(p, pnMaxArg);
  *pnOp = p->nOp;
  p->aOp = 0;
  return aOp;
}

/*
** Add a whole list of operations to the operation stack.  Return the
** address of the first operation added.
*/
int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  int addr;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
    return 0;
  }
  addr = p->nOp;
  if( ALWAYS(nOp>0) ){
    int i;
    VdbeOpList const *pIn = aOp;
    for(i=0; i<nOp; i++, pIn++){
      int p2 = pIn->p2;
      VdbeOp *pOut = &p->aOp[i+addr];
      pOut->opcode = pIn->opcode;
      pOut->p1 = pIn->p1;
      if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
        pOut->p2 = addr + ADDR(p2);
      }else{
        pOut->p2 = p2;
      }
      pOut->p3 = pIn->p3;
      pOut->p4type = P4_NOTUSED;
      pOut->p4.p = 0;
      pOut->p5 = 0;
#ifdef SQLITE_DEBUG
      pOut->zComment = 0;
      if( sqlite3VdbeAddopTrace ){
        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
      }
#endif
    }
    p->nOp += nOp;
  }
  return addr;
}

/*
** Change the value of the P1 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
*/
void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
  assert( p!=0 );
  assert( addr>=0 );
  if( p->nOp>addr ){
    p->aOp[addr].p1 = val;
  }
}

/*
** Change the value of the P2 operand for a specific instruction.
** This routine is useful for setting a jump destination.
*/
void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
  assert( p!=0 );
  assert( addr>=0 );
  if( p->nOp>addr ){
    p->aOp[addr].p2 = val;
  }
}

/*
** Change the value of the P3 operand for a specific instruction.
*/
void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
  assert( p!=0 );
  assert( addr>=0 );
  if( p->nOp>addr ){
    p->aOp[addr].p3 = val;
  }
}

/*
** Change the value of the P5 operand for the most recently
** added operation.
*/
void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  assert( p!=0 );
  if( p->aOp ){
    assert( p->nOp>0 );
    p->aOp[p->nOp-1].p5 = val;
  }
}

/*
** Change the P2 operand of instruction addr so that it points to
** the address of the next instruction to be coded.
*/
void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  sqlite3VdbeChangeP2(p, addr, p->nOp);
}


/*
** If the input FuncDef structure is ephemeral, then free it.  If
** the FuncDef is not ephermal, then do nothing.
*/
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
    sqlite3DbFree(db, pDef);
  }
}

/*
** Delete a P4 value if necessary.
*/
static void freeP4(sqlite3 *db, int p4type, void *p4){
  if( p4 ){
    switch( p4type ){
      case P4_REAL:
      case P4_INT64:
      case P4_MPRINTF:
      case P4_DYNAMIC:
      case P4_KEYINFO:
      case P4_INTARRAY:
      case P4_KEYINFO_HANDOFF: {
        sqlite3DbFree(db, p4);
        break;
      }
      case P4_VDBEFUNC: {
        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
        freeEphemeralFunction(db, pVdbeFunc->pFunc);
        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
        sqlite3DbFree(db, pVdbeFunc);
        break;
      }
      case P4_FUNCDEF: {
        freeEphemeralFunction(db, (FuncDef*)p4);
        break;
      }
      case P4_MEM: {
        sqlite3ValueFree((sqlite3_value*)p4);
        break;
      }
      case P4_VTAB : {
        sqlite3VtabUnlock((VTable *)p4);
        break;
      }
      case P4_SUBPROGRAM : {
        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
        break;
      }
    }
  }
}

/*
** Free the space allocated for aOp and any p4 values allocated for the
** opcodes contained within. If aOp is not NULL it is assumed to contain 
** nOp entries. 
*/
static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  if( aOp ){
    Op *pOp;
    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
      freeP4(db, pOp->p4type, pOp->p4.p);
#ifdef SQLITE_DEBUG
      sqlite3DbFree(db, pOp->zComment);
#endif     
    }
  }
  sqlite3DbFree(db, aOp);
}

/*
** Decrement the ref-count on the SubProgram structure passed as the
** second argument. If the ref-count reaches zero, free the structure.
**
** The array of VDBE opcodes stored as SubProgram.aOp is freed if
** either the ref-count reaches zero or parameter freeop is non-zero.
**
** Since the array of opcodes pointed to by SubProgram.aOp may directly
** or indirectly contain a reference to the SubProgram structure itself.
** By passing a non-zero freeop parameter, the caller may ensure that all
** SubProgram structures and their aOp arrays are freed, even when there
** are such circular references.
*/
void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
  if( p ){
    assert( p->nRef>0 );
    if( freeop || p->nRef==1 ){
      Op *aOp = p->aOp;
      p->aOp = 0;
      vdbeFreeOpArray(db, aOp, p->nOp);
      p->nOp = 0;
    }
    p->nRef--;
    if( p->nRef==0 ){
      sqlite3DbFree(db, p);
    }
  }
}


/*
** Change N opcodes starting at addr to No-ops.
*/
void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
  if( p->aOp ){
    VdbeOp *pOp = &p->aOp[addr];
    sqlite3 *db = p->db;
    while( N-- ){
      freeP4(db, pOp->p4type, pOp->p4.p);
      memset(pOp, 0, sizeof(pOp[0]));
      pOp->opcode = OP_Noop;
      pOp++;
    }
  }
}

/*
** Change the value of the P4 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
**
** If n>=0 then the P4 operand is dynamic, meaning that a copy of
** the string is made into memory obtained from sqlite3_malloc().
** A value of n==0 means copy bytes of zP4 up to and including the
** first null byte.  If n>0 then copy n+1 bytes of zP4.
**
** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
** A copy is made of the KeyInfo structure into memory obtained from
** sqlite3_malloc, to be freed when the Vdbe is finalized.
** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
** stored in memory that the caller has obtained from sqlite3_malloc. The 
** caller should not free the allocation, it will be freed when the Vdbe is
** finalized.
** 
** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
** to a string or structure that is guaranteed to exist for the lifetime of
** the Vdbe. In these cases we can just copy the pointer.
**
** If addr<0 then change P4 on the most recently inserted instruction.
*/
void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  Op *pOp;
  sqlite3 *db;
  assert( p!=0 );
  db = p->db;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( p->aOp==0 || db->mallocFailed ){
    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
      freeP4(db, n, (void*)*(char**)&zP4);
    }
    return;
  }
  assert( p->nOp>0 );
  assert( addr<p->nOp );
  if( addr<0 ){
    addr = p->nOp - 1;
  }
  pOp = &p->aOp[addr];
  freeP4(db, pOp->p4type, pOp->p4.p);
  pOp->p4.p = 0;
  if( n==P4_INT32 ){
    /* Note: this cast is safe, because the origin data point was an int
    ** that was cast to a (const char *). */
    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
    pOp->p4type = P4_INT32;
  }else if( zP4==0 ){
    pOp->p4.p = 0;
    pOp->p4type = P4_NOTUSED;
  }else if( n==P4_KEYINFO ){
    KeyInfo *pKeyInfo;
    int nField, nByte;

    nField = ((KeyInfo*)zP4)->nField;
    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
    pKeyInfo = sqlite3Malloc( nByte );
    pOp->p4.pKeyInfo = pKeyInfo;
    if( pKeyInfo ){
      u8 *aSortOrder;
      memcpy(pKeyInfo, zP4, nByte);
      aSortOrder = pKeyInfo->aSortOrder;
      if( aSortOrder ){
        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
      }
      pOp->p4type = P4_KEYINFO;
    }else{
      p->db->mallocFailed = 1;
      pOp->p4type = P4_NOTUSED;
    }
  }else if( n==P4_KEYINFO_HANDOFF ){
    pOp->p4.p = (void*)zP4;
    pOp->p4type = P4_KEYINFO;
  }else if( n==P4_VTAB ){
    pOp->p4.p = (void*)zP4;
    pOp->p4type = P4_VTAB;
    sqlite3VtabLock((VTable *)zP4);
    assert( ((VTable *)zP4)->db==p->db );
  }else if( n<0 ){
    pOp->p4.p = (void*)zP4;
    pOp->p4type = (signed char)n;
  }else{
    if( n==0 ) n = sqlite3Strlen30(zP4);
    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
    pOp->p4type = P4_DYNAMIC;
  }
}

#ifndef NDEBUG
/*
** Change the comment on the the most recently coded instruction.  Or
** insert a No-op and add the comment to that new instruction.  This
** makes the code easier to read during debugging.  None of this happens
** in a production build.
*/
void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  va_list ap;
  if( !p ) return;
  assert( p->nOp>0 || p->aOp==0 );
  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  if( p->nOp ){
    char **pz = &p->aOp[p->nOp-1].zComment;
    va_start(ap, zFormat);
    sqlite3DbFree(p->db, *pz);
    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
    va_end(ap);
  }
}
void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  va_list ap;
  if( !p ) return;
  sqlite3VdbeAddOp0(p, OP_Noop);
  assert( p->nOp>0 || p->aOp==0 );
  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  if( p->nOp ){
    char **pz = &p->aOp[p->nOp-1].zComment;
    va_start(ap, zFormat);
    sqlite3DbFree(p->db, *pz);
    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
    va_end(ap);
  }
}
#endif  /* NDEBUG */

/*
** Return the opcode for a given address.  If the address is -1, then
** return the most recently inserted opcode.
**
** If a memory allocation error has occurred prior to the calling of this
** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
** is readable and writable, but it has no effect.  The return of a dummy
** opcode allows the call to continue functioning after a OOM fault without
** having to check to see if the return from this routine is a valid pointer.
**
** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
** having to double-check to make sure that the result is non-negative. But
** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
** check the value of p->nOp-1 before continuing.
*/
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  static VdbeOp dummy;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( addr<0 ){
#ifdef SQLITE_OMIT_TRACE
    if( p->nOp==0 ) return &dummy;
#endif
    addr = p->nOp - 1;
  }
  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  if( p->db->mallocFailed ){
    return &dummy;
  }else{
    return &p->aOp[addr];
  }
}

#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Compute a string that describes the P4 parameter for an opcode.
** Use zTemp for any required temporary buffer space.
*/
static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  char *zP4 = zTemp;
  assert( nTemp>=20 );
  switch( pOp->p4type ){
    case P4_KEYINFO_STATIC:
    case P4_KEYINFO: {
      int i, j;
      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
      i = sqlite3Strlen30(zTemp);
      for(j=0; j<pKeyInfo->nField; j++){
        CollSeq *pColl = pKeyInfo->aColl[j];
        if( pColl ){
          int n = sqlite3Strlen30(pColl->zName);
          if( i+n>nTemp-6 ){
            memcpy(&zTemp[i],",...",4);
            break;
          }
          zTemp[i++] = ',';
          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
            zTemp[i++] = '-';
          }
          memcpy(&zTemp[i], pColl->zName,n+1);
          i += n;
        }else if( i+4<nTemp-6 ){
          memcpy(&zTemp[i],",nil",4);
          i += 4;
        }
      }
      zTemp[i++] = ')';
      zTemp[i] = 0;
      assert( i<nTemp );
      break;
    }
    case P4_COLLSEQ: {
      CollSeq *pColl = pOp->p4.pColl;
      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
      break;
    }
    case P4_FUNCDEF: {
      FuncDef *pDef = pOp->p4.pFunc;
      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
      break;
    }
    case P4_INT64: {
      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
      break;
    }
    case P4_INT32: {
      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
      break;
    }
    case P4_REAL: {
      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
      break;
    }
    case P4_MEM: {
      Mem *pMem = pOp->p4.pMem;
      assert( (pMem->flags & MEM_Null)==0 );
      if( pMem->flags & MEM_Str ){
        zP4 = pMem->z;
      }else if( pMem->flags & MEM_Int ){
        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
      }else if( pMem->flags & MEM_Real ){
        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
      }else{
        assert( pMem->flags & MEM_Blob );
        zP4 = "(blob)";
      }
      break;
    }
#ifndef SQLITE_OMIT_VIRTUALTABLE
    case P4_VTAB: {
      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
      break;
    }
#endif
    case P4_INTARRAY: {
      sqlite3_snprintf(nTemp, zTemp, "intarray");
      break;
    }
    case P4_SUBPROGRAM: {
      sqlite3_snprintf(nTemp, zTemp, "program");
      break;
    }
    default: {
      zP4 = pOp->p4.z;
      if( zP4==0 ){
        zP4 = zTemp;
        zTemp[0] = 0;
      }
    }
  }
  assert( zP4!=0 );
  return zP4;
}
#endif

/*
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
*/
void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  int mask;
  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
  assert( i<(int)sizeof(p->btreeMask)*8 );
  mask = ((u32)1)<<i;
  if( (p->btreeMask & mask)==0 ){
    p->btreeMask |= mask;
    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
  }
}


#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Print a single opcode.  This routine is used for debugging only.
*/
void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  char *zP4;
  char zPtr[50];
  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  if( pOut==0 ) pOut = stdout;
  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  fprintf(pOut, zFormat1, pc, 
      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
#ifdef SQLITE_DEBUG
      pOp->zComment ? pOp->zComment : ""
#else
      ""
#endif
  );
  fflush(pOut);
}
#endif

/*
** Release an array of N Mem elements
*/
static void releaseMemArray(Mem *p, int N){
  if( p && N ){
    Mem *pEnd;
    sqlite3 *db = p->db;
    u8 malloc_failed = db->mallocFailed;
    for(pEnd=&p[N]; p<pEnd; p++){
      assert( (&p[1])==pEnd || p[0].db==p[1].db );

      /* This block is really an inlined version of sqlite3VdbeMemRelease()
      ** that takes advantage of the fact that the memory cell value is 
      ** being set to NULL after releasing any dynamic resources.
      **
      ** The justification for duplicating code is that according to 
      ** callgrind, this causes a certain test case to hit the CPU 4.7 
      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
      ** sqlite3MemRelease() were called from here. With -O2, this jumps
      ** to 6.6 percent. The test case is inserting 1000 rows into a table 
      ** with no indexes using a single prepared INSERT statement, bind() 
      ** and reset(). Inserts are grouped into a transaction.
      */
      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
        sqlite3VdbeMemRelease(p);
      }else if( p->zMalloc ){
        sqlite3DbFree(db, p->zMalloc);
        p->zMalloc = 0;
      }

      p->flags = MEM_Null;
    }
    db->mallocFailed = malloc_failed;
  }
}

/*
** Delete a VdbeFrame object and its contents. VdbeFrame objects are
** allocated by the OP_Program opcode in sqlite3VdbeExec().
*/
void sqlite3VdbeFrameDelete(VdbeFrame *p){
  int i;
  Mem *aMem = VdbeFrameMem(p);
  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  for(i=0; i<p->nChildCsr; i++){
    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  }
  releaseMemArray(aMem, p->nChildMem);
  sqlite3DbFree(p->v->db, p);
}

#ifndef SQLITE_OMIT_EXPLAIN
/*
** Give a listing of the program in the virtual machine.
**
** The interface is the same as sqlite3VdbeExec().  But instead of
** running the code, it invokes the callback once for each instruction.
** This feature is used to implement "EXPLAIN".
**
** When p->explain==1, each instruction is listed.  When
** p->explain==2, only OP_Explain instructions are listed and these
** are shown in a different format.  p->explain==2 is used to implement
** EXPLAIN QUERY PLAN.
*/
int sqlite3VdbeList(
  Vdbe *p                   /* The VDBE */
){
  int nRow;                            /* Total number of rows to return */
  int nSub = 0;                        /* Number of sub-vdbes seen so far */
  SubProgram **apSub = 0;              /* Array of sub-vdbes */
  Mem *pSub = 0;
  sqlite3 *db = p->db;
  int i;
  int rc = SQLITE_OK;
  Mem *pMem = p->pResultSet = &p->aMem[1];

  assert( p->explain );
  assert( p->magic==VDBE_MAGIC_RUN );
  assert( db->magic==SQLITE_MAGIC_BUSY );
  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );

  /* Even though this opcode does not use dynamic strings for
  ** the result, result columns may become dynamic if the user calls
  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  */
  releaseMemArray(pMem, 8);

  if( p->rc==SQLITE_NOMEM ){
    /* This happens if a malloc() inside a call to sqlite3_column_text() or
    ** sqlite3_column_text16() failed.  */
    db->mallocFailed = 1;
    return SQLITE_ERROR;
  }

  /* Figure out total number of rows that will be returned by this 
  ** EXPLAIN program.  */
  nRow = p->nOp;
  if( p->explain==1 ){
    pSub = &p->aMem[9];
    if( pSub->flags&MEM_Blob ){
      nSub = pSub->n/sizeof(Vdbe*);
      apSub = (SubProgram **)pSub->z;
    }
    for(i=0; i<nSub; i++){
      nRow += apSub[i]->nOp;
    }
  }

  do{
    i = p->pc++;
  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  if( i>=nRow ){
    p->rc = SQLITE_OK;
    rc = SQLITE_DONE;
  }else if( db->u1.isInterrupted ){
    p->rc = SQLITE_INTERRUPT;
    rc = SQLITE_ERROR;
    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  }else{
    char *z;
    Op *pOp;
    if( i<p->nOp ){
      pOp = &p->aOp[i];
    }else{
      int j;
      i -= p->nOp;
      for(j=0; i>=apSub[j]->nOp; j++){
        i -= apSub[j]->nOp;
      }
      pOp = &apSub[j]->aOp[i];
    }
    if( p->explain==1 ){
      pMem->flags = MEM_Int;
      pMem->type = SQLITE_INTEGER;
      pMem->u.i = i;                                /* Program counter */
      pMem++;
  
      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
      assert( pMem->z!=0 );
      pMem->n = sqlite3Strlen30(pMem->z);
      pMem->type = SQLITE_TEXT;
      pMem->enc = SQLITE_UTF8;
      pMem++;

      if( pOp->p4type==P4_SUBPROGRAM ){
        int nByte = (nSub+1)*sizeof(SubProgram*);
        int j;
        for(j=0; j<nSub; j++){
          if( apSub[j]==pOp->p4.pProgram ) break;
        }
        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
          apSub = (SubProgram **)pSub->z;
          apSub[nSub++] = pOp->p4.pProgram;
          pSub->flags |= MEM_Blob;
          pSub->n = nSub*sizeof(SubProgram*);
        }
      }
    }

    pMem->flags = MEM_Int;
    pMem->u.i = pOp->p1;                          /* P1 */
    pMem->type = SQLITE_INTEGER;
    pMem++;

    pMem->flags = MEM_Int;
    pMem->u.i = pOp->p2;                          /* P2 */
    pMem->type = SQLITE_INTEGER;
    pMem++;

    if( p->explain==1 ){
      pMem->flags = MEM_Int;
      pMem->u.i = pOp->p3;                          /* P3 */
      pMem->type = SQLITE_INTEGER;
      pMem++;
    }

    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
      assert( p->db->mallocFailed );
      return SQLITE_ERROR;
    }
    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
    z = displayP4(pOp, pMem->z, 32);
    if( z!=pMem->z ){
      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
    }else{
      assert( pMem->z!=0 );
      pMem->n = sqlite3Strlen30(pMem->z);
      pMem->enc = SQLITE_UTF8;
    }
    pMem->type = SQLITE_TEXT;
    pMem++;

    if( p->explain==1 ){
      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
        assert( p->db->mallocFailed );
        return SQLITE_ERROR;
      }
      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
      pMem->n = 2;
      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
      pMem->type = SQLITE_TEXT;
      pMem->enc = SQLITE_UTF8;
      pMem++;
  
#ifdef SQLITE_DEBUG
      if( pOp->zComment ){
        pMem->flags = MEM_Str|MEM_Term;
        pMem->z = pOp->zComment;
        pMem->n = sqlite3Strlen30(pMem->z);
        pMem->enc = SQLITE_UTF8;
        pMem->type = SQLITE_TEXT;
      }else
#endif
      {
        pMem->flags = MEM_Null;                       /* Comment */
        pMem->type = SQLITE_NULL;
      }
    }

    p->nResColumn = 8 - 5*(p->explain-1);
    p->rc = SQLITE_OK;
    rc = SQLITE_ROW;
  }
  return rc;
}
#endif /* SQLITE_OMIT_EXPLAIN */

#ifdef SQLITE_DEBUG
/*
** Print the SQL that was used to generate a VDBE program.
*/
void sqlite3VdbePrintSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    const char *z = pOp->p4.z;
    while( sqlite3Isspace(*z) ) z++;
    printf("SQL: [%s]\n", z);
  }
}
#endif

#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** Print an IOTRACE message showing SQL content.
*/
void sqlite3VdbeIOTraceSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( sqlite3IoTrace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    int i, j;
    char z[1000];
    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
    for(i=0; sqlite3Isspace(z[i]); i++){}
    for(j=0; z[i]; i++){
      if( sqlite3Isspace(z[i]) ){
        if( z[i-1]!=' ' ){
          z[j++] = ' ';
        }
      }else{
        z[j++] = z[i];
      }
    }
    z[j] = 0;
    sqlite3IoTrace("SQL %s\n", z);
  }
}
#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */

/*
** Allocate space from a fixed size buffer.  Make *pp point to the
** allocated space.  (Note:  pp is a char* rather than a void** to
** work around the pointer aliasing rules of C.)  *pp should initially
** be zero.  If *pp is not zero, that means that the space has already
** been allocated and this routine is a noop.
**
** nByte is the number of bytes of space needed.
**
** *ppFrom point to available space and pEnd points to the end of the
** available space.
**
** *pnByte is a counter of the number of bytes of space that have failed
** to allocate.  If there is insufficient space in *ppFrom to satisfy the
** request, then increment *pnByte by the amount of the request.
*/
static void allocSpace(
  char *pp,            /* IN/OUT: Set *pp to point to allocated buffer */
  int nByte,           /* Number of bytes to allocate */
  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
  int *pnByte          /* If allocation cannot be made, increment *pnByte */
){
  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  if( (*(void**)pp)==0 ){
    nByte = ROUND8(nByte);
    if( &(*ppFrom)[nByte] <= pEnd ){
      *(void**)pp = (void *)*ppFrom;
      *ppFrom += nByte;
    }else{
      *pnByte += nByte;
    }
  }
}

/*
** Prepare a virtual machine for execution.  This involves things such
** as allocating stack space and initializing the program counter.
** After the VDBE has be prepped, it can be executed by one or more
** calls to sqlite3VdbeExec().  
**
** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
** VDBE_MAGIC_RUN.
**
** This function may be called more than once on a single virtual machine.
** The first call is made while compiling the SQL statement. Subsequent
** calls are made as part of the process of resetting a statement to be
** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
** and isExplain parameters are only passed correct values the first time
** the function is called. On subsequent calls, from sqlite3_reset(), nVar
** is passed -1 and nMem, nCursor and isExplain are all passed zero.
*/
void sqlite3VdbeMakeReady(
  Vdbe *p,                       /* The VDBE */
  int nVar,                      /* Number of '?' see in the SQL statement */
  int nMem,                      /* Number of memory cells to allocate */
  int nCursor,                   /* Number of cursors to allocate */
  int nArg,                      /* Maximum number of args in SubPrograms */
  int isExplain,                 /* True if the EXPLAIN keywords is present */
  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
){
  int n;
  sqlite3 *db = p->db;

  assert( p!=0 );
  assert( p->magic==VDBE_MAGIC_INIT );

  /* There should be at least one opcode.
  */
  assert( p->nOp>0 );

  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  p->magic = VDBE_MAGIC_RUN;

  /* For each cursor required, also allocate a memory cell. Memory
  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  ** the vdbe program. Instead they are used to allocate space for
  ** VdbeCursor/BtCursor structures. The blob of memory associated with 
  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  ** stores the blob of memory associated with cursor 1, etc.
  **
  ** See also: allocateCursor().
  */
  nMem += nCursor;

  /* Allocate space for memory registers, SQL variables, VDBE cursors and 
  ** an array to marshal SQL function arguments in. This is only done the
  ** first time this function is called for a given VDBE, not when it is
  ** being called from sqlite3_reset() to reset the virtual machine.
  */
  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
    u8 *zCsr = (u8 *)&p->aOp[p->nOp];
    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];
    int nByte;
    resolveP2Values(p, &nArg);
    p->usesStmtJournal = (u8)usesStmtJournal;
    if( isExplain && nMem<10 ){
      nMem = 10;
    }
    memset(zCsr, 0, zEnd-zCsr);
    zCsr += (zCsr - (u8*)0)&7;
    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );

    do {
      nByte = 0;
      allocSpace((char*)&p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
      allocSpace((char*)&p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
      allocSpace((char*)&p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
      allocSpace((char*)&p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
      allocSpace((char*)&p->apCsr, 
                 nCursor*sizeof(VdbeCursor*), &zCsr, zEnd, &nByte
      );
      if( nByte ){
        p->pFree = sqlite3DbMallocZero(db, nByte);
      }
      zCsr = p->pFree;
      zEnd = &zCsr[nByte];
    }while( nByte && !db->mallocFailed );

    p->nCursor = (u16)nCursor;
    if( p->aVar ){
      p->nVar = (ynVar)nVar;
      for(n=0; n<nVar; n++){
        p->aVar[n].flags = MEM_Null;
        p->aVar[n].db = db;
      }
    }
    if( p->aMem ){
      p->aMem--;                      /* aMem[] goes from 1..nMem */
      p->nMem = nMem;                 /*       not from 0..nMem-1 */
      for(n=1; n<=nMem; n++){
        p->aMem[n].flags = MEM_Null;
        p->aMem[n].db = db;
      }
    }
  }
#ifdef SQLITE_DEBUG
  for(n=1; n<p->nMem; n++){
    assert( p->aMem[n].db==db );
  }
#endif

  p->pc = -1;
  p->rc = SQLITE_OK;
  p->errorAction = OE_Abort;
  p->explain |= isExplain;
  p->magic = VDBE_MAGIC_RUN;
  p->nChange = 0;
  p->cacheCtr = 1;
  p->minWriteFileFormat = 255;
  p->iStatement = 0;
#ifdef VDBE_PROFILE
  {
    int i;
    for(i=0; i<p->nOp; i++){
      p->aOp[i].cnt = 0;
      p->aOp[i].cycles = 0;
    }
  }
#endif
}

/*
** Close a VDBE cursor and release all the resources that cursor 
** happens to hold.
*/
void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  if( pCx==0 ){
    return;
  }
  if( pCx->pBt ){
    sqlite3BtreeClose(pCx->pBt);
    /* The pCx->pCursor will be close automatically, if it exists, by
    ** the call above. */
  }else if( pCx->pCursor ){
    sqlite3BtreeCloseCursor(pCx->pCursor);
  }
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( pCx->pVtabCursor ){
    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
    const sqlite3_module *pModule = pCx->pModule;
    p->inVtabMethod = 1;
    (void)sqlite3SafetyOff(p->db);
    pModule->xClose(pVtabCursor);
    (void)sqlite3SafetyOn(p->db);
    p->inVtabMethod = 0;
  }
#endif
}

/*
** Copy the values stored in the VdbeFrame structure to its Vdbe. This
** is used, for example, when a trigger sub-program is halted to restore
** control to the main program.
*/
int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  Vdbe *v = pFrame->v;
  v->aOp = pFrame->aOp;
  v->nOp = pFrame->nOp;
  v->aMem = pFrame->aMem;
  v->nMem = pFrame->nMem;
  v->apCsr = pFrame->apCsr;
  v->nCursor = pFrame->nCursor;
  v->db->lastRowid = pFrame->lastRowid;
  v->nChange = pFrame->nChange;
  return pFrame->pc;
}

/*
** Close all cursors.
**
** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
** cell array. This is necessary as the memory cell array may contain
** pointers to VdbeFrame objects, which may in turn contain pointers to
** open cursors.
*/
static void closeAllCursors(Vdbe *p){
  if( p->pFrame ){
    VdbeFrame *pFrame = p->pFrame;
    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
    sqlite3VdbeFrameRestore(pFrame);
  }
  p->pFrame = 0;
  p->nFrame = 0;

  if( p->apCsr ){
    int i;
    for(i=0; i<p->nCursor; i++){
      VdbeCursor *pC = p->apCsr[i];
      if( pC ){
        sqlite3VdbeFreeCursor(p, pC);
        p->apCsr[i] = 0;
      }
    }
  }
  if( p->aMem ){
    releaseMemArray(&p->aMem[1], p->nMem);
  }
}

/*
** Clean up the VM after execution.
**
** This routine will automatically close any cursors, lists, and/or
** sorters that were left open.  It also deletes the values of
** variables in the aVar[] array.
*/
static void Cleanup(Vdbe *p){
  sqlite3 *db = p->db;

#ifdef SQLITE_DEBUG
  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
  ** Vdbe.aMem[] arrays have already been cleaned up.  */
  int i;
  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
#endif

  sqlite3DbFree(db, p->zErrMsg);
  p->zErrMsg = 0;
  p->pResultSet = 0;
}

/*
** Set the number of result columns that will be returned by this SQL
** statement. This is now set at compile time, rather than during
** execution of the vdbe program so that sqlite3_column_count() can
** be called on an SQL statement before sqlite3_step().
*/
void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  Mem *pColName;
  int n;
  sqlite3 *db = p->db;

  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  sqlite3DbFree(db, p->aColName);
  n = nResColumn*COLNAME_N;
  p->nResColumn = (u16)nResColumn;
  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  if( p->aColName==0 ) return;
  while( n-- > 0 ){
    pColName->flags = MEM_Null;
    pColName->db = p->db;
    pColName++;
  }
}

/*
** Set the name of the idx'th column to be returned by the SQL statement.
** zName must be a pointer to a nul terminated string.
**
** This call must be made after a call to sqlite3VdbeSetNumCols().
**
** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
*/
int sqlite3VdbeSetColName(
  Vdbe *p,                         /* Vdbe being configured */
  int idx,                         /* Index of column zName applies to */
  int var,                         /* One of the COLNAME_* constants */
  const char *zName,               /* Pointer to buffer containing name */
  void (*xDel)(void*)              /* Memory management strategy for zName */
){
  int rc;
  Mem *pColName;
  assert( idx<p->nResColumn );
  assert( var<COLNAME_N );
  if( p->db->mallocFailed ){
    assert( !zName || xDel!=SQLITE_DYNAMIC );
    return SQLITE_NOMEM;
  }
  assert( p->aColName!=0 );
  pColName = &(p->aColName[idx+var*p->nResColumn]);
  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  return rc;
}

/*
** A read or write transaction may or may not be active on database handle
** db. If a transaction is active, commit it. If there is a
** write-transaction spanning more than one database file, this routine
** takes care of the master journal trickery.
*/
static int vdbeCommit(sqlite3 *db, Vdbe *p){
  int i;
  int nTrans = 0;  /* Number of databases with an active write-transaction */
  int rc = SQLITE_OK;
  int needXcommit = 0;

#ifdef SQLITE_OMIT_VIRTUALTABLE
  /* With this option, sqlite3VtabSync() is defined to be simply 
  ** SQLITE_OK so p is not used. 
  */
  UNUSED_PARAMETER(p);
#endif

  /* Before doing anything else, call the xSync() callback for any
  ** virtual module tables written in this transaction. This has to
  ** be done before determining whether a master journal file is 
  ** required, as an xSync() callback may add an attached database
  ** to the transaction.
  */
  rc = sqlite3VtabSync(db, &p->zErrMsg);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  /* This loop determines (a) if the commit hook should be invoked and
  ** (b) how many database files have open write transactions, not 
  ** including the temp database. (b) is important because if more than 
  ** one database file has an open write transaction, a master journal
  ** file is required for an atomic commit.
  */ 
  for(i=0; i<db->nDb; i++){ 
    Btree *pBt = db->aDb[i].pBt;
    if( sqlite3BtreeIsInTrans(pBt) ){
      needXcommit = 1;
      if( i!=1 ) nTrans++;
    }
  }

  /* If there are any write-transactions at all, invoke the commit hook */
  if( needXcommit && db->xCommitCallback ){
    (void)sqlite3SafetyOff(db);
    rc = db->xCommitCallback(db->pCommitArg);
    (void)sqlite3SafetyOn(db);
    if( rc ){
      return SQLITE_CONSTRAINT;
    }
  }

  /* The simple case - no more than one database file (not counting the
  ** TEMP database) has a transaction active.   There is no need for the
  ** master-journal.
  **
  ** If the return value of sqlite3BtreeGetFilename() is a zero length
  ** string, it means the main database is :memory: or a temp file.  In 
  ** that case we do not support atomic multi-file commits, so use the 
  ** simple case then too.
  */
  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   || nTrans<=1
  ){
    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
      Btree *pBt = db->aDb[i].pBt;
      if( pBt ){
        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
      }
    }

    /* Do the commit only if all databases successfully complete phase 1. 
    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
    ** IO error while deleting or truncating a journal file. It is unlikely,
    ** but could happen. In this case abandon processing and return the error.
    */
    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
      Btree *pBt = db->aDb[i].pBt;
      if( pBt ){
        rc = sqlite3BtreeCommitPhaseTwo(pBt);
      }
    }
    if( rc==SQLITE_OK ){
      sqlite3VtabCommit(db);
    }
  }

  /* The complex case - There is a multi-file write-transaction active.
  ** This requires a master journal file to ensure the transaction is
  ** committed atomicly.
  */
#ifndef SQLITE_OMIT_DISKIO
  else{
    sqlite3_vfs *pVfs = db->pVfs;
    int needSync = 0;
    char *zMaster = 0;   /* File-name for the master journal */
    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
    sqlite3_file *pMaster = 0;
    i64 offset = 0;
    int res;

    /* Select a master journal file name */
    do {
      u32 iRandom;
      sqlite3DbFree(db, zMaster);
      sqlite3_randomness(sizeof(iRandom), &iRandom);
      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
      if( !zMaster ){
        return SQLITE_NOMEM;
      }
      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
    }while( rc==SQLITE_OK && res );
    if( rc==SQLITE_OK ){
      /* Open the master journal. */
      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
      );
    }
    if( rc!=SQLITE_OK ){
      sqlite3DbFree(db, zMaster);
      return rc;
    }
 
    /* Write the name of each database file in the transaction into the new
    ** master journal file. If an error occurs at this point close
    ** and delete the master journal file. All the individual journal files
    ** still have 'null' as the master journal pointer, so they will roll
    ** back independently if a failure occurs.
    */
    for(i=0; i<db->nDb; i++){
      Btree *pBt = db->aDb[i].pBt;
      if( i==1 ) continue;   /* Ignore the TEMP database */
      if( sqlite3BtreeIsInTrans(pBt) ){
        char const *zFile = sqlite3BtreeGetJournalname(pBt);
        if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
          needSync = 1;
        }
        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
        offset += sqlite3Strlen30(zFile)+1;
        if( rc!=SQLITE_OK ){
          sqlite3OsCloseFree(pMaster);
          sqlite3OsDelete(pVfs, zMaster, 0);
          sqlite3DbFree(db, zMaster);
          return rc;
        }
      }
    }

    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
    ** flag is set this is not required.
    */
    if( needSync 
     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
    ){
      sqlite3OsCloseFree(pMaster);
      sqlite3OsDelete(pVfs, zMaster, 0);
      sqlite3DbFree(db, zMaster);
      return rc;
    }

    /* Sync all the db files involved in the transaction. The same call
    ** sets the master journal pointer in each individual journal. If
    ** an error occurs here, do not delete the master journal file.
    **
    ** If the error occurs during the first call to
    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
    ** master journal file will be orphaned. But we cannot delete it,
    ** in case the master journal file name was written into the journal
    ** file before the failure occurred.
    */
    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
      Btree *pBt = db->aDb[i].pBt;
      if( pBt ){
        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
      }
    }
    sqlite3OsCloseFree(pMaster);
    if( rc!=SQLITE_OK ){
      sqlite3DbFree(db, zMaster);
      return rc;
    }

    /* Delete the master journal file. This commits the transaction. After
    ** doing this the directory is synced again before any individual
    ** transaction files are deleted.
    */
    rc = sqlite3OsDelete(pVfs, zMaster, 1);
    sqlite3DbFree(db, zMaster);
    zMaster = 0;
    if( rc ){
      return rc;
    }

    /* All files and directories have already been synced, so the following
    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
    ** deleting or truncating journals. If something goes wrong while
    ** this is happening we don't really care. The integrity of the
    ** transaction is already guaranteed, but some stray 'cold' journals
    ** may be lying around. Returning an error code won't help matters.
    */
    disable_simulated_io_errors();
    sqlite3BeginBenignMalloc();
    for(i=0; i<db->nDb; i++){ 
      Btree *pBt = db->aDb[i].pBt;
      if( pBt ){
        sqlite3BtreeCommitPhaseTwo(pBt);
      }
    }
    sqlite3EndBenignMalloc();
    enable_simulated_io_errors();

    sqlite3VtabCommit(db);
  }
#endif

  return rc;
}

/* 
** This routine checks that the sqlite3.activeVdbeCnt count variable
** matches the number of vdbe's in the list sqlite3.pVdbe that are
** currently active. An assertion fails if the two counts do not match.
** This is an internal self-check only - it is not an essential processing
** step.
**
** This is a no-op if NDEBUG is defined.
*/
#ifndef NDEBUG
static void checkActiveVdbeCnt(sqlite3 *db){
  Vdbe *p;
  int cnt = 0;
  int nWrite = 0;
  p = db->pVdbe;
  while( p ){
    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
      cnt++;
      if( p->readOnly==0 ) nWrite++;
    }
    p = p->pNext;
  }
  assert( cnt==db->activeVdbeCnt );
  assert( nWrite==db->writeVdbeCnt );
}
#else
#define checkActiveVdbeCnt(x)
#endif

/*
** For every Btree that in database connection db which 
** has been modified, "trip" or invalidate each cursor in
** that Btree might have been modified so that the cursor
** can never be used again.  This happens when a rollback
*** occurs.  We have to trip all the other cursors, even
** cursor from other VMs in different database connections,
** so that none of them try to use the data at which they
** were pointing and which now may have been changed due
** to the rollback.
**
** Remember that a rollback can delete tables complete and
** reorder rootpages.  So it is not sufficient just to save
** the state of the cursor.  We have to invalidate the cursor
** so that it is never used again.
*/
static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
  int i;
  for(i=0; i<db->nDb; i++){
    Btree *p = db->aDb[i].pBt;
    if( p && sqlite3BtreeIsInTrans(p) ){
      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
    }
  }
}

/*
** If the Vdbe passed as the first argument opened a statement-transaction,
** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
** statement transaction is commtted.
**
** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
** Otherwise SQLITE_OK.
*/
int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  sqlite3 *const db = p->db;
  int rc = SQLITE_OK;

  /* If p->iStatement is greater than zero, then this Vdbe opened a 
  ** statement transaction that should be closed here. The only exception
  ** is that an IO error may have occured, causing an emergency rollback.
  ** In this case (db->nStatement==0), and there is nothing to do.
  */
  if( db->nStatement && p->iStatement ){
    int i;
    const int iSavepoint = p->iStatement-1;

    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
    assert( db->nStatement>0 );
    assert( p->iStatement==(db->nStatement+db->nSavepoint) );

    for(i=0; i<db->nDb; i++){ 
      int rc2 = SQLITE_OK;
      Btree *pBt = db->aDb[i].pBt;
      if( pBt ){
        if( eOp==SAVEPOINT_ROLLBACK ){
          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
        }
        if( rc2==SQLITE_OK ){
          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
        }
        if( rc==SQLITE_OK ){
          rc = rc2;
        }
      }
    }
    db->nStatement--;
    p->iStatement = 0;

    /* If the statement transaction is being rolled back, also restore the 
    ** database handles deferred constraint counter to the value it had when 
    ** the statement transaction was opened.  */
    if( eOp==SAVEPOINT_ROLLBACK ){
      db->nDeferredCons = p->nStmtDefCons;
    }
  }
  return rc;
}

/*
** If SQLite is compiled to support shared-cache mode and to be threadsafe,
** this routine obtains the mutex associated with each BtShared structure
** that may be accessed by the VM passed as an argument. In doing so it
** sets the BtShared.db member of each of the BtShared structures, ensuring
** that the correct busy-handler callback is invoked if required.
**
** If SQLite is not threadsafe but does support shared-cache mode, then
** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
** of all of BtShared structures accessible via the database handle 
** associated with the VM. Of course only a subset of these structures
** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
** that subset out, but there is no advantage to doing so.
**
** If SQLite is not threadsafe and does not support shared-cache mode, this
** function is a no-op.
*/
#ifndef SQLITE_OMIT_SHARED_CACHE
void sqlite3VdbeMutexArrayEnter(Vdbe *p){
#if SQLITE_THREADSAFE
  sqlite3BtreeMutexArrayEnter(&p->aMutex);
#else
  sqlite3BtreeEnterAll(p->db);
#endif
}
#endif

/*
** This function is called when a transaction opened by the database 
** handle associated with the VM passed as an argument is about to be 
** committed. If there are outstanding deferred foreign key constraint
** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
**
** If there are outstanding FK violations and this function returns 
** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
** an error message to it. Then return SQLITE_ERROR.
*/
#ifndef SQLITE_OMIT_FOREIGN_KEY
int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  sqlite3 *db = p->db;
  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
    p->rc = SQLITE_CONSTRAINT;
    p->errorAction = OE_Abort;
    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}
#endif

/*
** This routine is called the when a VDBE tries to halt.  If the VDBE
** has made changes and is in autocommit mode, then commit those
** changes.  If a rollback is needed, then do the rollback.
**
** This routine is the only way to move the state of a VM from
** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
** call this on a VM that is in the SQLITE_MAGIC_HALT state.
**
** Return an error code.  If the commit could not complete because of
** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
** means the close did not happen and needs to be repeated.
*/
int sqlite3VdbeHalt(Vdbe *p){
  int rc;                         /* Used to store transient return codes */
  sqlite3 *db = p->db;

  /* This function contains the logic that determines if a statement or
  ** transaction will be committed or rolled back as a result of the
  ** execution of this virtual machine. 
  **
  ** If any of the following errors occur:
  **
  **     SQLITE_NOMEM
  **     SQLITE_IOERR
  **     SQLITE_FULL
  **     SQLITE_INTERRUPT
  **
  ** Then the internal cache might have been left in an inconsistent
  ** state.  We need to rollback the statement transaction, if there is
  ** one, or the complete transaction if there is no statement transaction.
  */

  if( p->db->mallocFailed ){
    p->rc = SQLITE_NOMEM;
  }
  closeAllCursors(p);
  if( p->magic!=VDBE_MAGIC_RUN ){
    return SQLITE_OK;
  }
  checkActiveVdbeCnt(db);

  /* No commit or rollback needed if the program never started */
  if( p->pc>=0 ){
    int mrc;   /* Primary error code from p->rc */
    int eStatementOp = 0;
    int isSpecialError;            /* Set to true if a 'special' error */

    /* Lock all btrees used by the statement */
    sqlite3VdbeMutexArrayEnter(p);

    /* Check for one of the special errors */
    mrc = p->rc & 0xff;
    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
    if( isSpecialError ){
      /* If the query was read-only, we need do no rollback at all. Otherwise,
      ** proceed with the special handling.
      */
      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
          eStatementOp = SAVEPOINT_ROLLBACK;
        }else{
          /* We are forced to roll back the active transaction. Before doing
          ** so, abort any other statements this handle currently has active.
          */
          invalidateCursorsOnModifiedBtrees(db);
          sqlite3RollbackAll(db);
          sqlite3CloseSavepoints(db);
          db->autoCommit = 1;
        }
      }
    }

    /* Check for immediate foreign key violations. */
    if( p->rc==SQLITE_OK ){
      sqlite3VdbeCheckFk(p, 0);
    }
  
    /* If the auto-commit flag is set and this is the only active writer 
    ** VM, then we do either a commit or rollback of the current transaction. 
    **
    ** Note: This block also runs if one of the special errors handled 
    ** above has occurred. 
    */
    if( !sqlite3VtabInSync(db) 
     && db->autoCommit 
     && db->writeVdbeCnt==(p->readOnly==0) 
    ){
      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
        if( sqlite3VdbeCheckFk(p, 1) ){
          sqlite3BtreeMutexArrayLeave(&p->aMutex);
          return SQLITE_ERROR;
        }
        /* The auto-commit flag is true, the vdbe program was successful 
        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
        ** key constraints to hold up the transaction. This means a commit 
        ** is required.  */
        rc = vdbeCommit(db, p);
        if( rc==SQLITE_BUSY ){
          sqlite3BtreeMutexArrayLeave(&p->aMutex);
          return SQLITE_BUSY;
        }else if( rc!=SQLITE_OK ){
          p->rc = rc;
          sqlite3RollbackAll(db);
        }else{
          db->nDeferredCons = 0;
          sqlite3CommitInternalChanges(db);
        }
      }else{
        sqlite3RollbackAll(db);
      }
      db->nStatement = 0;
    }else if( eStatementOp==0 ){
      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
        eStatementOp = SAVEPOINT_RELEASE;
      }else if( p->errorAction==OE_Abort ){
        eStatementOp = SAVEPOINT_ROLLBACK;
      }else{
        invalidateCursorsOnModifiedBtrees(db);
        sqlite3RollbackAll(db);
        sqlite3CloseSavepoints(db);
        db->autoCommit = 1;
      }
    }
  
    /* If eStatementOp is non-zero, then a statement transaction needs to
    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
    ** do so. If this operation returns an error, and the current statement
    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
    ** code to the new value.
    */
    if( eStatementOp ){
      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
      if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
        p->rc = rc;
        sqlite3DbFree(db, p->zErrMsg);
        p->zErrMsg = 0;
      }
    }
  
    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
    ** has been rolled back, update the database connection change-counter. 
    */
    if( p->changeCntOn ){
      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
        sqlite3VdbeSetChanges(db, p->nChange);
      }else{
        sqlite3VdbeSetChanges(db, 0);
      }
      p->nChange = 0;
    }
  
    /* Rollback or commit any schema changes that occurred. */
    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
      sqlite3ResetInternalSchema(db, 0);
      db->flags = (db->flags | SQLITE_InternChanges);
    }

    /* Release the locks */
    sqlite3BtreeMutexArrayLeave(&p->aMutex);
  }

  /* We have successfully halted and closed the VM.  Record this fact. */
  if( p->pc>=0 ){
    db->activeVdbeCnt--;
    if( !p->readOnly ){
      db->writeVdbeCnt--;
    }
    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
  }
  p->magic = VDBE_MAGIC_HALT;
  checkActiveVdbeCnt(db);
  if( p->db->mallocFailed ){
    p->rc = SQLITE_NOMEM;
  }

  /* If the auto-commit flag is set to true, then any locks that were held
  ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
  ** to invoke any required unlock-notify callbacks.
  */
  if( db->autoCommit ){
    sqlite3ConnectionUnlocked(db);
  }

  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
  return SQLITE_OK;
}


/*
** Each VDBE holds the result of the most recent sqlite3_step() call
** in p->rc.  This routine sets that result back to SQLITE_OK.
*/
void sqlite3VdbeResetStepResult(Vdbe *p){
  p->rc = SQLITE_OK;
}

/*
** Clean up a VDBE after execution but do not delete the VDBE just yet.
** Write any error messages into *pzErrMsg.  Return the result code.
**
** After this routine is run, the VDBE should be ready to be executed
** again.
**
** To look at it another way, this routine resets the state of the
** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
** VDBE_MAGIC_INIT.
*/
int sqlite3VdbeReset(Vdbe *p){
  sqlite3 *db;
  db = p->db;

  /* If the VM did not run to completion or if it encountered an
  ** error, then it might not have been halted properly.  So halt
  ** it now.
  */
  (void)sqlite3SafetyOn(db);
  sqlite3VdbeHalt(p);
  (void)sqlite3SafetyOff(db);

  /* If the VDBE has be run even partially, then transfer the error code
  ** and error message from the VDBE into the main database structure.  But
  ** if the VDBE has just been set to run but has not actually executed any
  ** instructions yet, leave the main database error information unchanged.
  */
  if( p->pc>=0 ){
    if( p->zErrMsg ){
      sqlite3BeginBenignMalloc();
      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
      sqlite3EndBenignMalloc();
      db->errCode = p->rc;
      sqlite3DbFree(db, p->zErrMsg);
      p->zErrMsg = 0;
    }else if( p->rc ){
      sqlite3Error(db, p->rc, 0);
    }else{
      sqlite3Error(db, SQLITE_OK, 0);
    }
  }else if( p->rc && p->expired ){
    /* The expired flag was set on the VDBE before the first call
    ** to sqlite3_step(). For consistency (since sqlite3_step() was
    ** called), set the database error in this case as well.
    */
    sqlite3Error(db, p->rc, 0);
    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
    sqlite3DbFree(db, p->zErrMsg);
    p->zErrMsg = 0;
  }

  /* Reclaim all memory used by the VDBE
  */
  Cleanup(p);

  /* Save profiling information from this VDBE run.
  */
#ifdef VDBE_PROFILE
  {
    FILE *out = fopen("vdbe_profile.out", "a");
    if( out ){
      int i;
      fprintf(out, "---- ");
      for(i=0; i<p->nOp; i++){
        fprintf(out, "%02x", p->aOp[i].opcode);
      }
      fprintf(out, "\n");
      for(i=0; i<p->nOp; i++){
        fprintf(out, "%6d %10lld %8lld ",
           p->aOp[i].cnt,
           p->aOp[i].cycles,
           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
        );
        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
      }
      fclose(out);
    }
  }
#endif
  p->magic = VDBE_MAGIC_INIT;
  return p->rc & db->errMask;
}
 
/*
** Clean up and delete a VDBE after execution.  Return an integer which is
** the result code.  Write any error message text into *pzErrMsg.
*/
int sqlite3VdbeFinalize(Vdbe *p){
  int rc = SQLITE_OK;
  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
    rc = sqlite3VdbeReset(p);
    assert( (rc & p->db->errMask)==rc );
  }
  sqlite3VdbeDelete(p);
  return rc;
}

/*
** Call the destructor for each auxdata entry in pVdbeFunc for which
** the corresponding bit in mask is clear.  Auxdata entries beyond 31
** are always destroyed.  To destroy all auxdata entries, call this
** routine with mask==0.
*/
void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  int i;
  for(i=0; i<pVdbeFunc->nAux; i++){
    struct AuxData *pAux = &pVdbeFunc->apAux[i];
    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
      if( pAux->xDelete ){
        pAux->xDelete(pAux->pAux);
      }
      pAux->pAux = 0;
    }
  }
}

/*
** Delete an entire VDBE.
*/
void sqlite3VdbeDelete(Vdbe *p){
  sqlite3 *db;

  if( NEVER(p==0) ) return;
  db = p->db;
  if( p->pPrev ){
    p->pPrev->pNext = p->pNext;
  }else{
    assert( db->pVdbe==p );
    db->pVdbe = p->pNext;
  }
  if( p->pNext ){
    p->pNext->pPrev = p->pPrev;
  }
  releaseMemArray(p->aVar, p->nVar);
  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  vdbeFreeOpArray(db, p->aOp, p->nOp);
  sqlite3DbFree(db, p->aLabel);
  sqlite3DbFree(db, p->aColName);
  sqlite3DbFree(db, p->zSql);
  p->magic = VDBE_MAGIC_DEAD;
  sqlite3DbFree(db, p->pFree);
  sqlite3DbFree(db, p);
}

/*
** Make sure the cursor p is ready to read or write the row to which it
** was last positioned.  Return an error code if an OOM fault or I/O error
** prevents us from positioning the cursor to its correct position.
**
** If a MoveTo operation is pending on the given cursor, then do that
** MoveTo now.  If no move is pending, check to see if the row has been
** deleted out from under the cursor and if it has, mark the row as
** a NULL row.
**
** If the cursor is already pointing to the correct row and that row has
** not been deleted out from under the cursor, then this routine is a no-op.
*/
int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  if( p->deferredMoveto ){
    int res, rc;
#ifdef SQLITE_TEST
    extern int sqlite3_search_count;
#endif
    assert( p->isTable );
    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
    if( rc ) return rc;
    p->lastRowid = p->movetoTarget;
    p->rowidIsValid = ALWAYS(res==0) ?1:0;
    if( NEVER(res<0) ){
      rc = sqlite3BtreeNext(p->pCursor, &res);
      if( rc ) return rc;
    }
#ifdef SQLITE_TEST
    sqlite3_search_count++;
#endif
    p->deferredMoveto = 0;
    p->cacheStatus = CACHE_STALE;
  }else if( ALWAYS(p->pCursor) ){
    int hasMoved;
    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
    if( rc ) return rc;
    if( hasMoved ){
      p->cacheStatus = CACHE_STALE;
      p->nullRow = 1;
    }
  }
  return SQLITE_OK;
}

/*
** The following functions:
**
** sqlite3VdbeSerialType()
** sqlite3VdbeSerialTypeLen()
** sqlite3VdbeSerialLen()
** sqlite3VdbeSerialPut()
** sqlite3VdbeSerialGet()
**
** encapsulate the code that serializes values for storage in SQLite
** data and index records. Each serialized value consists of a
** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
** integer, stored as a varint.
**
** In an SQLite index record, the serial type is stored directly before
** the blob of data that it corresponds to. In a table record, all serial
** types are stored at the start of the record, and the blobs of data at
** the end. Hence these functions allow the caller to handle the
** serial-type and data blob seperately.
**
** The following table describes the various storage classes for data:
**
**   serial type        bytes of data      type
**   --------------     ---------------    ---------------
**      0                     0            NULL
**      1                     1            signed integer
**      2                     2            signed integer
**      3                     3            signed integer
**      4                     4            signed integer
**      5                     6            signed integer
**      6                     8            signed integer
**      7                     8            IEEE float
**      8                     0            Integer constant 0
**      9                     0            Integer constant 1
**     10,11                               reserved for expansion
**    N>=12 and even       (N-12)/2        BLOB
**    N>=13 and odd        (N-13)/2        text
**
** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
** of SQLite will not understand those serial types.
*/

/*
** Return the serial-type for the value stored in pMem.
*/
u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  int flags = pMem->flags;
  int n;

  if( flags&MEM_Null ){
    return 0;
  }
  if( flags&MEM_Int ){
    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
    i64 i = pMem->u.i;
    u64 u;
    if( file_format>=4 && (i&1)==i ){
      return 8+(u32)i;
    }
    u = i<0 ? -i : i;
    if( u<=127 ) return 1;
    if( u<=32767 ) return 2;
    if( u<=8388607 ) return 3;
    if( u<=2147483647 ) return 4;
    if( u<=MAX_6BYTE ) return 5;
    return 6;
  }
  if( flags&MEM_Real ){
    return 7;
  }
  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  n = pMem->n;
  if( flags & MEM_Zero ){
    n += pMem->u.nZero;
  }
  assert( n>=0 );
  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
}

/*
** Return the length of the data corresponding to the supplied serial-type.
*/
u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  if( serial_type>=12 ){
    return (serial_type-12)/2;
  }else{
    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
    return aSize[serial_type];
  }
}

/*
** If we are on an architecture with mixed-endian floating 
** points (ex: ARM7) then swap the lower 4 bytes with the 
** upper 4 bytes.  Return the result.
**
** For most architectures, this is a no-op.
**
** (later):  It is reported to me that the mixed-endian problem
** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
** that early versions of GCC stored the two words of a 64-bit
** float in the wrong order.  And that error has been propagated
** ever since.  The blame is not necessarily with GCC, though.
** GCC might have just copying the problem from a prior compiler.
** I am also told that newer versions of GCC that follow a different
** ABI get the byte order right.
**
** Developers using SQLite on an ARM7 should compile and run their
** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
** enabled, some asserts below will ensure that the byte order of
** floating point values is correct.
**
** (2007-08-30)  Frank van Vugt has studied this problem closely
** and has send his findings to the SQLite developers.  Frank
** writes that some Linux kernels offer floating point hardware
** emulation that uses only 32-bit mantissas instead of a full 
** 48-bits as required by the IEEE standard.  (This is the
** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
** byte swapping becomes very complicated.  To avoid problems,
** the necessary byte swapping is carried out using a 64-bit integer
** rather than a 64-bit float.  Frank assures us that the code here
** works for him.  We, the developers, have no way to independently
** verify this, but Frank seems to know what he is talking about
** so we trust him.
*/
#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
static u64 floatSwap(u64 in){
  union {
    u64 r;
    u32 i[2];
  } u;
  u32 t;

  u.r = in;
  t = u.i[0];
  u.i[0] = u.i[1];
  u.i[1] = t;
  return u.r;
}
# define swapMixedEndianFloat(X)  X = floatSwap(X)
#else
# define swapMixedEndianFloat(X)
#endif

/*
** Write the serialized data blob for the value stored in pMem into 
** buf. It is assumed that the caller has allocated sufficient space.
** Return the number of bytes written.
**
** nBuf is the amount of space left in buf[].  nBuf must always be
** large enough to hold the entire field.  Except, if the field is
** a blob with a zero-filled tail, then buf[] might be just the right
** size to hold everything except for the zero-filled tail.  If buf[]
** is only big enough to hold the non-zero prefix, then only write that
** prefix into buf[].  But if buf[] is large enough to hold both the
** prefix and the tail then write the prefix and set the tail to all
** zeros.
**
** Return the number of bytes actually written into buf[].  The number
** of bytes in the zero-filled tail is included in the return value only
** if those bytes were zeroed in buf[].
*/ 
u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  u32 len;

  /* Integer and Real */
  if( serial_type<=7 && serial_type>0 ){
    u64 v;
    u32 i;
    if( serial_type==7 ){
      assert( sizeof(v)==sizeof(pMem->r) );
      memcpy(&v, &pMem->r, sizeof(v));
      swapMixedEndianFloat(v);
    }else{
      v = pMem->u.i;
    }
    len = i = sqlite3VdbeSerialTypeLen(serial_type);
    assert( len<=(u32)nBuf );
    while( i-- ){
      buf[i] = (u8)(v&0xFF);
      v >>= 8;
    }
    return len;
  }

  /* String or blob */
  if( serial_type>=12 ){
    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
    assert( pMem->n<=nBuf );
    len = pMem->n;
    memcpy(buf, pMem->z, len);
    if( pMem->flags & MEM_Zero ){
      len += pMem->u.nZero;
      assert( nBuf>=0 );
      if( len > (u32)nBuf ){
        len = (u32)nBuf;
      }
      memset(&buf[pMem->n], 0, len-pMem->n);
    }
    return len;
  }

  /* NULL or constants 0 or 1 */
  return 0;
}

/*
** Deserialize the data blob pointed to by buf as serial type serial_type
** and store the result in pMem.  Return the number of bytes read.
*/ 
u32 sqlite3VdbeSerialGet(
  const unsigned char *buf,     /* Buffer to deserialize from */
  u32 serial_type,              /* Serial type to deserialize */
  Mem *pMem                     /* Memory cell to write value into */
){
  switch( serial_type ){
    case 10:   /* Reserved for future use */
    case 11:   /* Reserved for future use */
    case 0: {  /* NULL */
      pMem->flags = MEM_Null;
      break;
    }
    case 1: { /* 1-byte signed integer */
      pMem->u.i = (signed char)buf[0];
      pMem->flags = MEM_Int;
      return 1;
    }
    case 2: { /* 2-byte signed integer */
      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
      pMem->flags = MEM_Int;
      return 2;
    }
    case 3: { /* 3-byte signed integer */
      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
      pMem->flags = MEM_Int;
      return 3;
    }
    case 4: { /* 4-byte signed integer */
      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
      pMem->flags = MEM_Int;
      return 4;
    }
    case 5: { /* 6-byte signed integer */
      u64 x = (((signed char)buf[0])<<8) | buf[1];
      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
      x = (x<<32) | y;
      pMem->u.i = *(i64*)&x;
      pMem->flags = MEM_Int;
      return 6;
    }
    case 6:   /* 8-byte signed integer */
    case 7: { /* IEEE floating point */
      u64 x;
      u32 y;
#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
      /* Verify that integers and floating point values use the same
      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
      ** defined that 64-bit floating point values really are mixed
      ** endian.
      */
      static const u64 t1 = ((u64)0x3ff00000)<<32;
      static const double r1 = 1.0;
      u64 t2 = t1;
      swapMixedEndianFloat(t2);
      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
#endif

      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
      x = (x<<32) | y;
      if( serial_type==6 ){
        pMem->u.i = *(i64*)&x;
        pMem->flags = MEM_Int;
      }else{
        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
        swapMixedEndianFloat(x);
        memcpy(&pMem->r, &x, sizeof(x));
        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
      }
      return 8;
    }
    case 8:    /* Integer 0 */
    case 9: {  /* Integer 1 */
      pMem->u.i = serial_type-8;
      pMem->flags = MEM_Int;
      return 0;
    }
    default: {
      u32 len = (serial_type-12)/2;
      pMem->z = (char *)buf;
      pMem->n = len;
      pMem->xDel = 0;
      if( serial_type&0x01 ){
        pMem->flags = MEM_Str | MEM_Ephem;
      }else{
        pMem->flags = MEM_Blob | MEM_Ephem;
      }
      return len;
    }
  }
  return 0;
}


/*
** Given the nKey-byte encoding of a record in pKey[], parse the
** record into a UnpackedRecord structure.  Return a pointer to
** that structure.
**
** The calling function might provide szSpace bytes of memory
** space at pSpace.  This space can be used to hold the returned
** VDbeParsedRecord structure if it is large enough.  If it is
** not big enough, space is obtained from sqlite3_malloc().
**
** The returned structure should be closed by a call to
** sqlite3VdbeDeleteUnpackedRecord().
*/ 
UnpackedRecord *sqlite3VdbeRecordUnpack(
  KeyInfo *pKeyInfo,     /* Information about the record format */
  int nKey,              /* Size of the binary record */
  const void *pKey,      /* The binary record */
  char *pSpace,          /* Unaligned space available to hold the object */
  int szSpace            /* Size of pSpace[] in bytes */
){
  const unsigned char *aKey = (const unsigned char *)pKey;
  UnpackedRecord *p;  /* The unpacked record that we will return */
  int nByte;          /* Memory space needed to hold p, in bytes */
  int d;
  u32 idx;
  u16 u;              /* Unsigned loop counter */
  u32 szHdr;
  Mem *pMem;
  int nOff;           /* Increase pSpace by this much to 8-byte align it */
  
  /*
  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
  */
  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  pSpace += nOff;
  szSpace -= nOff;
  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  if( nByte>szSpace ){
    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
    if( p==0 ) return 0;
    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
  }else{
    p = (UnpackedRecord*)pSpace;
    p->flags = UNPACKED_NEED_DESTROY;
  }
  p->pKeyInfo = pKeyInfo;
  p->nField = pKeyInfo->nField + 1;
  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  idx = getVarint32(aKey, szHdr);
  d = szHdr;
  u = 0;
  while( idx<szHdr && u<p->nField && d<=nKey ){
    u32 serial_type;

    idx += getVarint32(&aKey[idx], serial_type);
    pMem->enc = pKeyInfo->enc;
    pMem->db = pKeyInfo->db;
    pMem->flags = 0;
    pMem->zMalloc = 0;
    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
    pMem++;
    u++;
  }
  assert( u<=pKeyInfo->nField + 1 );
  p->nField = u;
  return (void*)p;
}

/*
** This routine destroys a UnpackedRecord object.
*/
void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
  int i;
  Mem *pMem;

  assert( p!=0 );
  assert( p->flags & UNPACKED_NEED_DESTROY );
  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
    /* The unpacked record is always constructed by the
    ** sqlite3VdbeUnpackRecord() function above, which makes all
    ** strings and blobs static.  And none of the elements are
    ** ever transformed, so there is never anything to delete.
    */
    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
  }
  if( p->flags & UNPACKED_NEED_FREE ){
    sqlite3DbFree(p->pKeyInfo->db, p);
  }
}

/*
** This function compares the two table rows or index records
** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
** or positive integer if key1 is less than, equal to or 
** greater than key2.  The {nKey1, pKey1} key must be a blob
** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
** key must be a parsed key such as obtained from
** sqlite3VdbeParseRecord.
**
** Key1 and Key2 do not have to contain the same number of fields.
** The key with fewer fields is usually compares less than the 
** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
** and the common prefixes are equal, then key1 is less than key2.
** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
** equal, then the keys are considered to be equal and
** the parts beyond the common prefix are ignored.
**
** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
** the header of pKey1 is ignored.  It is assumed that pKey1 is
** an index key, and thus ends with a rowid value.  The last byte
** of the header will therefore be the serial type of the rowid:
** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
** The serial type of the final rowid will always be a single byte.
** By ignoring this last byte of the header, we force the comparison
** to ignore the rowid at the end of key1.
*/
int sqlite3VdbeRecordCompare(
  int nKey1, const void *pKey1, /* Left key */
  UnpackedRecord *pPKey2        /* Right key */
){
  int d1;            /* Offset into aKey[] of next data element */
  u32 idx1;          /* Offset into aKey[] of next header element */
  u32 szHdr1;        /* Number of bytes in header */
  int i = 0;
  int nField;
  int rc = 0;
  const unsigned char *aKey1 = (const unsigned char *)pKey1;
  KeyInfo *pKeyInfo;
  Mem mem1;

  pKeyInfo = pPKey2->pKeyInfo;
  mem1.enc = pKeyInfo->enc;
  mem1.db = pKeyInfo->db;
  mem1.flags = 0;
  mem1.u.i = 0;  /* not needed, here to silence compiler warning */
  mem1.zMalloc = 0;
  
  idx1 = getVarint32(aKey1, szHdr1);
  d1 = szHdr1;
  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
    szHdr1--;
  }
  nField = pKeyInfo->nField;
  while( idx1<szHdr1 && i<pPKey2->nField ){
    u32 serial_type1;

    /* Read the serial types for the next element in each key. */
    idx1 += getVarint32( aKey1+idx1, serial_type1 );
    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;

    /* Extract the values to be compared.
    */
    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);

    /* Do the comparison
    */
    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
                           i<nField ? pKeyInfo->aColl[i] : 0);
    if( rc!=0 ){
      break;
    }
    i++;
  }

  /* No memory allocation is ever used on mem1. */
  if( NEVER(mem1.zMalloc) ) sqlite3VdbeMemRelease(&mem1);

  /* If the PREFIX_SEARCH flag is set and all fields except the final
  ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
  ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  ** This is used by the OP_IsUnique opcode.
  */
  if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
    assert( idx1==szHdr1 && rc );
    assert( mem1.flags & MEM_Int );
    pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
    pPKey2->rowid = mem1.u.i;
  }

  if( rc==0 ){
    /* rc==0 here means that one of the keys ran out of fields and
    ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
    ** flag is set, then break the tie by treating key2 as larger.
    ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
    ** are considered to be equal.  Otherwise, the longer key is the 
    ** larger.  As it happens, the pPKey2 will always be the longer
    ** if there is a difference.
    */
    if( pPKey2->flags & UNPACKED_INCRKEY ){
      rc = -1;
    }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
      /* Leave rc==0 */
    }else if( idx1<szHdr1 ){
      rc = 1;
    }
  }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
               && pKeyInfo->aSortOrder[i] ){
    rc = -rc;
  }

  return rc;
}
 

/*
** pCur points at an index entry created using the OP_MakeRecord opcode.
** Read the rowid (the last field in the record) and store it in *rowid.
** Return SQLITE_OK if everything works, or an error code otherwise.
**
** pCur might be pointing to text obtained from a corrupt database file.
** So the content cannot be trusted.  Do appropriate checks on the content.
*/
int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  i64 nCellKey = 0;
  int rc;
  u32 szHdr;        /* Size of the header */
  u32 typeRowid;    /* Serial type of the rowid */
  u32 lenRowid;     /* Size of the rowid */
  Mem m, v;

  UNUSED_PARAMETER(db);

  /* Get the size of the index entry.  Only indices entries of less
  ** than 2GiB are support - anything large must be database corruption.
  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  ** this code can safely assume that nCellKey is 32-bits  
  */
  assert( sqlite3BtreeCursorIsValid(pCur) );
  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );

  /* Read in the complete content of the index entry */
  memset(&m, 0, sizeof(m));
  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  if( rc ){
    return rc;
  }

  /* The index entry must begin with a header size */
  (void)getVarint32((u8*)m.z, szHdr);
  testcase( szHdr==3 );
  testcase( szHdr==m.n );
  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
    goto idx_rowid_corruption;
  }

  /* The last field of the index should be an integer - the ROWID.
  ** Verify that the last entry really is an integer. */
  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  testcase( typeRowid==1 );
  testcase( typeRowid==2 );
  testcase( typeRowid==3 );
  testcase( typeRowid==4 );
  testcase( typeRowid==5 );
  testcase( typeRowid==6 );
  testcase( typeRowid==8 );
  testcase( typeRowid==9 );
  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
    goto idx_rowid_corruption;
  }
  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  testcase( (u32)m.n==szHdr+lenRowid );
  if( unlikely((u32)m.n<szHdr+lenRowid) ){
    goto idx_rowid_corruption;
  }

  /* Fetch the integer off the end of the index record */
  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  *rowid = v.u.i;
  sqlite3VdbeMemRelease(&m);
  return SQLITE_OK;

  /* Jump here if database corruption is detected after m has been
  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
idx_rowid_corruption:
  testcase( m.zMalloc!=0 );
  sqlite3VdbeMemRelease(&m);
  return SQLITE_CORRUPT_BKPT;
}

/*
** Compare the key of the index entry that cursor pC is pointing to against
** the key string in pUnpacked.  Write into *pRes a number
** that is negative, zero, or positive if pC is less than, equal to,
** or greater than pUnpacked.  Return SQLITE_OK on success.
**
** pUnpacked is either created without a rowid or is truncated so that it
** omits the rowid at the end.  The rowid at the end of the index entry
** is ignored as well.  Hence, this routine only compares the prefixes 
** of the keys prior to the final rowid, not the entire key.
*/
int sqlite3VdbeIdxKeyCompare(
  VdbeCursor *pC,             /* The cursor to compare against */
  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
  int *res                    /* Write the comparison result here */
){
  i64 nCellKey = 0;
  int rc;
  BtCursor *pCur = pC->pCursor;
  Mem m;

  assert( sqlite3BtreeCursorIsValid(pCur) );
  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
  /* nCellKey will always be between 0 and 0xffffffff because of the say
  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  if( nCellKey<=0 || nCellKey>0x7fffffff ){
    *res = 0;
    return SQLITE_CORRUPT;
  }
  memset(&m, 0, sizeof(m));
  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  if( rc ){
    return rc;
  }
  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  sqlite3VdbeMemRelease(&m);
  return SQLITE_OK;
}

/*
** This routine sets the value to be returned by subsequent calls to
** sqlite3_changes() on the database handle 'db'. 
*/
void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  assert( sqlite3_mutex_held(db->mutex) );
  db->nChange = nChange;
  db->nTotalChange += nChange;
}

/*
** Set a flag in the vdbe to update the change counter when it is finalised
** or reset.
*/
void sqlite3VdbeCountChanges(Vdbe *v){
  v->changeCntOn = 1;
}

/*
** Mark every prepared statement associated with a database connection
** as expired.
**
** An expired statement means that recompilation of the statement is
** recommend.  Statements expire when things happen that make their
** programs obsolete.  Removing user-defined functions or collating
** sequences, or changing an authorization function are the types of
** things that make prepared statements obsolete.
*/
void sqlite3ExpirePreparedStatements(sqlite3 *db){
  Vdbe *p;
  for(p = db->pVdbe; p; p=p->pNext){
    p->expired = 1;
  }
}

/*
** Return the database associated with the Vdbe.
*/
sqlite3 *sqlite3VdbeDb(Vdbe *v){
  return v->db;
}

/*
** Return a pointer to an sqlite3_value structure containing the value bound
** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
** constants) to the value before returning it.
**
** The returned value must be freed by the caller using sqlite3ValueFree().
*/
sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
  assert( iVar>0 );
  if( v ){
    Mem *pMem = &v->aVar[iVar-1];
    if( 0==(pMem->flags & MEM_Null) ){
      sqlite3_value *pRet = sqlite3ValueNew(v->db);
      if( pRet ){
        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
        sqlite3VdbeMemStoreType((Mem *)pRet);
      }
      return pRet;
    }
  }
  return 0;
}

/*
** Configure SQL variable iVar so that binding a new value to it signals
** to sqlite3_reoptimize() that re-preparing the statement may result
** in a better query plan.
*/
void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  assert( iVar>0 );
  if( iVar>32 ){
    v->expmask = 0xffffffff;
  }else{
    v->expmask |= ((u32)1 << (iVar-1));
  }
}

Added src/vdbeblob.c.





















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
** 2007 May 1
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to implement incremental BLOB I/O.
**
** $Id: vdbeblob.c,v 1.35 2009/07/02 07:47:33 danielk1977 Exp $
*/

#include "sqliteInt.h"
#include "vdbeInt.h"

#ifndef SQLITE_OMIT_INCRBLOB

/*
** Valid sqlite3_blob* handles point to Incrblob structures.
*/
typedef struct Incrblob Incrblob;
struct Incrblob {
  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
  int nByte;              /* Size of open blob, in bytes */
  int iOffset;            /* Byte offset of blob in cursor data */
  BtCursor *pCsr;         /* Cursor pointing at blob row */
  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
  sqlite3 *db;            /* The associated database */
};

/*
** Open a blob handle.
*/
int sqlite3_blob_open(
  sqlite3* db,            /* The database connection */
  const char *zDb,        /* The attached database containing the blob */
  const char *zTable,     /* The table containing the blob */
  const char *zColumn,    /* The column containing the blob */
  sqlite_int64 iRow,      /* The row containing the glob */
  int flags,              /* True -> read/write access, false -> read-only */
  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
){
  int nAttempt = 0;
  int iCol;               /* Index of zColumn in row-record */

  /* This VDBE program seeks a btree cursor to the identified 
  ** db/table/row entry. The reason for using a vdbe program instead
  ** of writing code to use the b-tree layer directly is that the
  ** vdbe program will take advantage of the various transaction,
  ** locking and error handling infrastructure built into the vdbe.
  **
  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  ** Code external to the Vdbe then "borrows" the b-tree cursor and
  ** uses it to implement the blob_read(), blob_write() and 
  ** blob_bytes() functions.
  **
  ** The sqlite3_blob_close() function finalizes the vdbe program,
  ** which closes the b-tree cursor and (possibly) commits the 
  ** transaction.
  */
  static const VdbeOpList openBlob[] = {
    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */

    /* One of the following two instructions is replaced by an OP_Noop. */
    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */

    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
    {OP_Column, 0, 0, 1},          /* 7  */
    {OP_ResultRow, 1, 0, 0},       /* 8  */
    {OP_Close, 0, 0, 0},           /* 9  */
    {OP_Halt, 0, 0, 0},            /* 10 */
  };

  Vdbe *v = 0;
  int rc = SQLITE_OK;
  char *zErr = 0;
  Table *pTab;
  Parse *pParse;

  *ppBlob = 0;
  sqlite3_mutex_enter(db->mutex);
  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  if( pParse==0 ){
    rc = SQLITE_NOMEM;
    goto blob_open_out;
  }
  do {
    memset(pParse, 0, sizeof(Parse));
    pParse->db = db;

    if( sqlite3SafetyOn(db) ){
      sqlite3DbFree(db, zErr);
      sqlite3StackFree(db, pParse);
      sqlite3_mutex_leave(db->mutex);
      return SQLITE_MISUSE;
    }

    sqlite3BtreeEnterAll(db);
    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
    if( pTab && IsVirtual(pTab) ){
      pTab = 0;
      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
    }
#ifndef SQLITE_OMIT_VIEW
    if( pTab && pTab->pSelect ){
      pTab = 0;
      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
    }
#endif
    if( !pTab ){
      if( pParse->zErrMsg ){
        sqlite3DbFree(db, zErr);
        zErr = pParse->zErrMsg;
        pParse->zErrMsg = 0;
      }
      rc = SQLITE_ERROR;
      (void)sqlite3SafetyOff(db);
      sqlite3BtreeLeaveAll(db);
      goto blob_open_out;
    }

    /* Now search pTab for the exact column. */
    for(iCol=0; iCol < pTab->nCol; iCol++) {
      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
        break;
      }
    }
    if( iCol==pTab->nCol ){
      sqlite3DbFree(db, zErr);
      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
      rc = SQLITE_ERROR;
      (void)sqlite3SafetyOff(db);
      sqlite3BtreeLeaveAll(db);
      goto blob_open_out;
    }

    /* If the value is being opened for writing, check that the
    ** column is not indexed, and that it is not part of a foreign key. 
    ** It is against the rules to open a column to which either of these
    ** descriptions applies for writing.  */
    if( flags ){
      const char *zFault = 0;
      Index *pIdx;
#ifndef SQLITE_OMIT_FOREIGN_KEY
      if( db->flags&SQLITE_ForeignKeys ){
        /* Check that the column is not part of an FK child key definition. It
        ** is not necessary to check if it is part of a parent key, as parent
        ** key columns must be indexed. The check below will pick up this 
        ** case.  */
        FKey *pFKey;
        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
          int j;
          for(j=0; j<pFKey->nCol; j++){
            if( pFKey->aCol[j].iFrom==iCol ){
              zFault = "foreign key";
            }
          }
        }
      }
#endif
      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
        int j;
        for(j=0; j<pIdx->nColumn; j++){
          if( pIdx->aiColumn[j]==iCol ){
            zFault = "indexed";
          }
        }
      }
      if( zFault ){
        sqlite3DbFree(db, zErr);
        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
        rc = SQLITE_ERROR;
        (void)sqlite3SafetyOff(db);
        sqlite3BtreeLeaveAll(db);
        goto blob_open_out;
      }
    }

    v = sqlite3VdbeCreate(db);
    if( v ){
      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
      flags = !!flags;                 /* flags = (flags ? 1 : 0); */

      /* Configure the OP_Transaction */
      sqlite3VdbeChangeP1(v, 0, iDb);
      sqlite3VdbeChangeP2(v, 0, flags);

      /* Configure the OP_VerifyCookie */
      sqlite3VdbeChangeP1(v, 1, iDb);
      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);

      /* Make sure a mutex is held on the table to be accessed */
      sqlite3VdbeUsesBtree(v, iDb); 

      /* Configure the OP_TableLock instruction */
      sqlite3VdbeChangeP1(v, 2, iDb);
      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
      sqlite3VdbeChangeP3(v, 2, flags);
      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);

      /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
      ** parameter of the other to pTab->tnum.  */
      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
      sqlite3VdbeChangeP3(v, 3 + flags, iDb);

      /* Configure the number of columns. Configure the cursor to
      ** think that the table has one more column than it really
      ** does. An OP_Column to retrieve this imaginary column will
      ** always return an SQL NULL. This is useful because it means
      ** we can invoke OP_Column to fill in the vdbe cursors type 
      ** and offset cache without causing any IO.
      */
      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
      if( !db->mallocFailed ){
        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
      }
    }
   
    sqlite3BtreeLeaveAll(db);
    rc = sqlite3SafetyOff(db);
    if( NEVER(rc!=SQLITE_OK) || db->mallocFailed ){
      goto blob_open_out;
    }

    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
    rc = sqlite3_step((sqlite3_stmt *)v);
    if( rc!=SQLITE_ROW ){
      nAttempt++;
      rc = sqlite3_finalize((sqlite3_stmt *)v);
      sqlite3DbFree(db, zErr);
      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
      v = 0;
    }
  } while( nAttempt<5 && rc==SQLITE_SCHEMA );

  if( rc==SQLITE_ROW ){
    /* The row-record has been opened successfully. Check that the
    ** column in question contains text or a blob. If it contains
    ** text, it is up to the caller to get the encoding right.
    */
    Incrblob *pBlob;
    u32 type = v->apCsr[0]->aType[iCol];

    if( type<12 ){
      sqlite3DbFree(db, zErr);
      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
          type==0?"null": type==7?"real": "integer"
      );
      rc = SQLITE_ERROR;
      goto blob_open_out;
    }
    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
    if( db->mallocFailed ){
      sqlite3DbFree(db, pBlob);
      goto blob_open_out;
    }
    pBlob->flags = flags;
    pBlob->pCsr =  v->apCsr[0]->pCursor;
    sqlite3BtreeEnterCursor(pBlob->pCsr);
    sqlite3BtreeCacheOverflow(pBlob->pCsr);
    sqlite3BtreeLeaveCursor(pBlob->pCsr);
    pBlob->pStmt = (sqlite3_stmt *)v;
    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
    pBlob->db = db;
    *ppBlob = (sqlite3_blob *)pBlob;
    rc = SQLITE_OK;
  }else if( rc==SQLITE_OK ){
    sqlite3DbFree(db, zErr);
    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
    rc = SQLITE_ERROR;
  }

blob_open_out:
  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
    sqlite3VdbeFinalize(v);
  }
  sqlite3Error(db, rc, zErr);
  sqlite3DbFree(db, zErr);
  sqlite3StackFree(db, pParse);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** Close a blob handle that was previously created using
** sqlite3_blob_open().
*/
int sqlite3_blob_close(sqlite3_blob *pBlob){
  Incrblob *p = (Incrblob *)pBlob;
  int rc;
  sqlite3 *db;

  if( p ){
    db = p->db;
    sqlite3_mutex_enter(db->mutex);
    rc = sqlite3_finalize(p->pStmt);
    sqlite3DbFree(db, p);
    sqlite3_mutex_leave(db->mutex);
  }else{
    rc = SQLITE_OK;
  }
  return rc;
}

/*
** Perform a read or write operation on a blob
*/
static int blobReadWrite(
  sqlite3_blob *pBlob, 
  void *z, 
  int n, 
  int iOffset, 
  int (*xCall)(BtCursor*, u32, u32, void*)
){
  int rc;
  Incrblob *p = (Incrblob *)pBlob;
  Vdbe *v;
  sqlite3 *db;

  if( p==0 ) return SQLITE_MISUSE;
  db = p->db;
  sqlite3_mutex_enter(db->mutex);
  v = (Vdbe*)p->pStmt;

  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
    /* Request is out of range. Return a transient error. */
    rc = SQLITE_ERROR;
    sqlite3Error(db, SQLITE_ERROR, 0);
  } else if( v==0 ){
    /* If there is no statement handle, then the blob-handle has
    ** already been invalidated. Return SQLITE_ABORT in this case.
    */
    rc = SQLITE_ABORT;
  }else{
    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
    ** returned, clean-up the statement handle.
    */
    assert( db == v->db );
    sqlite3BtreeEnterCursor(p->pCsr);
    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
    sqlite3BtreeLeaveCursor(p->pCsr);
    if( rc==SQLITE_ABORT ){
      sqlite3VdbeFinalize(v);
      p->pStmt = 0;
    }else{
      db->errCode = rc;
      v->rc = rc;
    }
  }
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** Read data from a blob handle.
*/
int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
}

/*
** Write data to a blob handle.
*/
int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
}

/*
** Query a blob handle for the size of the data.
**
** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
** so no mutex is required for access.
*/
int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  Incrblob *p = (Incrblob *)pBlob;
  return p ? p->nByte : 0;
}

#endif /* #ifndef SQLITE_OMIT_INCRBLOB */

Added src/vdbemem.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
/*
** 2004 May 26
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code use to manipulate "Mem" structure.  A "Mem"
** stores a single value in the VDBE.  Mem is an opaque structure visible
** only within the VDBE.  Interface routines refer to a Mem using the
** name sqlite_value
**
** $Id: vdbemem.c,v 1.152 2009/07/22 18:07:41 drh Exp $
*/
#include "sqliteInt.h"
#include "vdbeInt.h"

/*
** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
** P if required.
*/
#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)

/*
** If pMem is an object with a valid string representation, this routine
** ensures the internal encoding for the string representation is
** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
**
** If pMem is not a string object, or the encoding of the string
** representation is already stored using the requested encoding, then this
** routine is a no-op.
**
** SQLITE_OK is returned if the conversion is successful (or not required).
** SQLITE_NOMEM may be returned if a malloc() fails during conversion
** between formats.
*/
int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  int rc;
  assert( (pMem->flags&MEM_RowSet)==0 );
  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
           || desiredEnc==SQLITE_UTF16BE );
  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
    return SQLITE_OK;
  }
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
#ifdef SQLITE_OMIT_UTF16
  return SQLITE_ERROR;
#else

  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  ** then the encoding of the value may not have changed.
  */
  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  return rc;
#endif
}

/*
** Make sure pMem->z points to a writable allocation of at least 
** n bytes.
**
** If the memory cell currently contains string or blob data
** and the third argument passed to this function is true, the 
** current content of the cell is preserved. Otherwise, it may
** be discarded.  
**
** This function sets the MEM_Dyn flag and clears any xDel callback.
** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
** not set, Mem.n is zeroed.
*/
int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  assert( 1 >=
    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
    ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
    ((pMem->flags&MEM_Static) ? 1 : 0)
  );
  assert( (pMem->flags&MEM_RowSet)==0 );

  if( n<32 ) n = 32;
  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
    if( preserve && pMem->z==pMem->zMalloc ){
      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
      preserve = 0;
    }else{
      sqlite3DbFree(pMem->db, pMem->zMalloc);
      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
    }
  }

  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
    memcpy(pMem->zMalloc, pMem->z, pMem->n);
  }
  if( pMem->flags&MEM_Dyn && pMem->xDel ){
    pMem->xDel((void *)(pMem->z));
  }

  pMem->z = pMem->zMalloc;
  if( pMem->z==0 ){
    pMem->flags = MEM_Null;
  }else{
    pMem->flags &= ~(MEM_Ephem|MEM_Static);
  }
  pMem->xDel = 0;
  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
}

/*
** Make the given Mem object MEM_Dyn.  In other words, make it so
** that any TEXT or BLOB content is stored in memory obtained from
** malloc().  In this way, we know that the memory is safe to be
** overwritten or altered.
**
** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
*/
int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  int f;
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( (pMem->flags&MEM_RowSet)==0 );
  expandBlob(pMem);
  f = pMem->flags;
  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
      return SQLITE_NOMEM;
    }
    pMem->z[pMem->n] = 0;
    pMem->z[pMem->n+1] = 0;
    pMem->flags |= MEM_Term;
  }

  return SQLITE_OK;
}

/*
** If the given Mem* has a zero-filled tail, turn it into an ordinary
** blob stored in dynamically allocated space.
*/
#ifndef SQLITE_OMIT_INCRBLOB
int sqlite3VdbeMemExpandBlob(Mem *pMem){
  if( pMem->flags & MEM_Zero ){
    int nByte;
    assert( pMem->flags&MEM_Blob );
    assert( (pMem->flags&MEM_RowSet)==0 );
    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );

    /* Set nByte to the number of bytes required to store the expanded blob. */
    nByte = pMem->n + pMem->u.nZero;
    if( nByte<=0 ){
      nByte = 1;
    }
    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
      return SQLITE_NOMEM;
    }

    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
    pMem->n += pMem->u.nZero;
    pMem->flags &= ~(MEM_Zero|MEM_Term);
  }
  return SQLITE_OK;
}
#endif


/*
** Make sure the given Mem is \u0000 terminated.
*/
int sqlite3VdbeMemNulTerminate(Mem *pMem){
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
    return SQLITE_OK;   /* Nothing to do */
  }
  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
    return SQLITE_NOMEM;
  }
  pMem->z[pMem->n] = 0;
  pMem->z[pMem->n+1] = 0;
  pMem->flags |= MEM_Term;
  return SQLITE_OK;
}

/*
** Add MEM_Str to the set of representations for the given Mem.  Numbers
** are converted using sqlite3_snprintf().  Converting a BLOB to a string
** is a no-op.
**
** Existing representations MEM_Int and MEM_Real are *not* invalidated.
**
** A MEM_Null value will never be passed to this function. This function is
** used for converting values to text for returning to the user (i.e. via
** sqlite3_value_text()), or for ensuring that values to be used as btree
** keys are strings. In the former case a NULL pointer is returned the
** user and the later is an internal programming error.
*/
int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  int rc = SQLITE_OK;
  int fg = pMem->flags;
  const int nByte = 32;

  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( !(fg&MEM_Zero) );
  assert( !(fg&(MEM_Str|MEM_Blob)) );
  assert( fg&(MEM_Int|MEM_Real) );
  assert( (pMem->flags&MEM_RowSet)==0 );
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );


  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
    return SQLITE_NOMEM;
  }

  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  ** string representation of the value. Then, if the required encoding
  ** is UTF-16le or UTF-16be do a translation.
  ** 
  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  */
  if( fg & MEM_Int ){
    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  }else{
    assert( fg & MEM_Real );
    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  }
  pMem->n = sqlite3Strlen30(pMem->z);
  pMem->enc = SQLITE_UTF8;
  pMem->flags |= MEM_Str|MEM_Term;
  sqlite3VdbeChangeEncoding(pMem, enc);
  return rc;
}

/*
** Memory cell pMem contains the context of an aggregate function.
** This routine calls the finalize method for that function.  The
** result of the aggregate is stored back into pMem.
**
** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
** otherwise.
*/
int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  int rc = SQLITE_OK;
  if( ALWAYS(pFunc && pFunc->xFinalize) ){
    sqlite3_context ctx;
    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
    memset(&ctx, 0, sizeof(ctx));
    ctx.s.flags = MEM_Null;
    ctx.s.db = pMem->db;
    ctx.pMem = pMem;
    ctx.pFunc = pFunc;
    pFunc->xFinalize(&ctx);
    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
    sqlite3DbFree(pMem->db, pMem->zMalloc);
    memcpy(pMem, &ctx.s, sizeof(ctx.s));
    rc = ctx.isError;
  }
  return rc;
}

/*
** If the memory cell contains a string value that must be freed by
** invoking an external callback, free it now. Calling this function
** does not free any Mem.zMalloc buffer.
*/
void sqlite3VdbeMemReleaseExternal(Mem *p){
  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  testcase( p->flags & MEM_Agg );
  testcase( p->flags & MEM_Dyn );
  testcase( p->flags & MEM_RowSet );
  testcase( p->flags & MEM_Frame );
  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
    if( p->flags&MEM_Agg ){
      sqlite3VdbeMemFinalize(p, p->u.pDef);
      assert( (p->flags & MEM_Agg)==0 );
      sqlite3VdbeMemRelease(p);
    }else if( p->flags&MEM_Dyn && p->xDel ){
      assert( (p->flags&MEM_RowSet)==0 );
      p->xDel((void *)p->z);
      p->xDel = 0;
    }else if( p->flags&MEM_RowSet ){
      sqlite3RowSetClear(p->u.pRowSet);
    }else if( p->flags&MEM_Frame ){
      sqlite3VdbeMemSetNull(p);
    }
  }
}

/*
** Release any memory held by the Mem. This may leave the Mem in an
** inconsistent state, for example with (Mem.z==0) and
** (Mem.type==SQLITE_TEXT).
*/
void sqlite3VdbeMemRelease(Mem *p){
  sqlite3VdbeMemReleaseExternal(p);
  sqlite3DbFree(p->db, p->zMalloc);
  p->z = 0;
  p->zMalloc = 0;
  p->xDel = 0;
}

/*
** Convert a 64-bit IEEE double into a 64-bit signed integer.
** If the double is too large, return 0x8000000000000000.
**
** Most systems appear to do this simply by assigning
** variables and without the extra range tests.  But
** there are reports that windows throws an expection
** if the floating point value is out of range. (See ticket #2880.)
** Because we do not completely understand the problem, we will
** take the conservative approach and always do range tests
** before attempting the conversion.
*/
static i64 doubleToInt64(double r){
  /*
  ** Many compilers we encounter do not define constants for the
  ** minimum and maximum 64-bit integers, or they define them
  ** inconsistently.  And many do not understand the "LL" notation.
  ** So we define our own static constants here using nothing
  ** larger than a 32-bit integer constant.
  */
  static const i64 maxInt = LARGEST_INT64;
  static const i64 minInt = SMALLEST_INT64;

  if( r<(double)minInt ){
    return minInt;
  }else if( r>(double)maxInt ){
    /* minInt is correct here - not maxInt.  It turns out that assigning
    ** a very large positive number to an integer results in a very large
    ** negative integer.  This makes no sense, but it is what x86 hardware
    ** does so for compatibility we will do the same in software. */
    return minInt;
  }else{
    return (i64)r;
  }
}

/*
** Return some kind of integer value which is the best we can do
** at representing the value that *pMem describes as an integer.
** If pMem is an integer, then the value is exact.  If pMem is
** a floating-point then the value returned is the integer part.
** If pMem is a string or blob, then we make an attempt to convert
** it into a integer and return that.  If pMem represents an
** an SQL-NULL value, return 0.
**
** If pMem represents a string value, its encoding might be changed.
*/
i64 sqlite3VdbeIntValue(Mem *pMem){
  int flags;
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  flags = pMem->flags;
  if( flags & MEM_Int ){
    return pMem->u.i;
  }else if( flags & MEM_Real ){
    return doubleToInt64(pMem->r);
  }else if( flags & (MEM_Str|MEM_Blob) ){
    i64 value;
    pMem->flags |= MEM_Str;
    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
       || sqlite3VdbeMemNulTerminate(pMem) ){
      return 0;
    }
    assert( pMem->z );
    sqlite3Atoi64(pMem->z, &value);
    return value;
  }else{
    return 0;
  }
}

/*
** Return the best representation of pMem that we can get into a
** double.  If pMem is already a double or an integer, return its
** value.  If it is a string or blob, try to convert it to a double.
** If it is a NULL, return 0.0.
*/
double sqlite3VdbeRealValue(Mem *pMem){
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  if( pMem->flags & MEM_Real ){
    return pMem->r;
  }else if( pMem->flags & MEM_Int ){
    return (double)pMem->u.i;
  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
    double val = (double)0;
    pMem->flags |= MEM_Str;
    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
       || sqlite3VdbeMemNulTerminate(pMem) ){
      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
      return (double)0;
    }
    assert( pMem->z );
    sqlite3AtoF(pMem->z, &val);
    return val;
  }else{
    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
    return (double)0;
  }
}

/*
** The MEM structure is already a MEM_Real.  Try to also make it a
** MEM_Int if we can.
*/
void sqlite3VdbeIntegerAffinity(Mem *pMem){
  assert( pMem->flags & MEM_Real );
  assert( (pMem->flags & MEM_RowSet)==0 );
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );

  pMem->u.i = doubleToInt64(pMem->r);

  /* Only mark the value as an integer if
  **
  **    (1) the round-trip conversion real->int->real is a no-op, and
  **    (2) The integer is neither the largest nor the smallest
  **        possible integer (ticket #3922)
  **
  ** The second and third terms in the following conditional enforces
  ** the second condition under the assumption that addition overflow causes
  ** values to wrap around.  On x86 hardware, the third term is always
  ** true and could be omitted.  But we leave it in because other
  ** architectures might behave differently.
  */
  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
    pMem->flags |= MEM_Int;
  }
}

/*
** Convert pMem to type integer.  Invalidate any prior representations.
*/
int sqlite3VdbeMemIntegerify(Mem *pMem){
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( (pMem->flags & MEM_RowSet)==0 );
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );

  pMem->u.i = sqlite3VdbeIntValue(pMem);
  MemSetTypeFlag(pMem, MEM_Int);
  return SQLITE_OK;
}

/*
** Convert pMem so that it is of type MEM_Real.
** Invalidate any prior representations.
*/
int sqlite3VdbeMemRealify(Mem *pMem){
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );

  pMem->r = sqlite3VdbeRealValue(pMem);
  MemSetTypeFlag(pMem, MEM_Real);
  return SQLITE_OK;
}

/*
** Convert pMem so that it has types MEM_Real or MEM_Int or both.
** Invalidate any prior representations.
*/
int sqlite3VdbeMemNumerify(Mem *pMem){
  double r1, r2;
  i64 i;
  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  r1 = sqlite3VdbeRealValue(pMem);
  i = doubleToInt64(r1);
  r2 = (double)i;
  if( r1==r2 ){
    sqlite3VdbeMemIntegerify(pMem);
  }else{
    pMem->r = r1;
    MemSetTypeFlag(pMem, MEM_Real);
  }
  return SQLITE_OK;
}

/*
** Delete any previous value and set the value stored in *pMem to NULL.
*/
void sqlite3VdbeMemSetNull(Mem *pMem){
  if( pMem->flags & MEM_Frame ){
    sqlite3VdbeFrameDelete(pMem->u.pFrame);
  }
  if( pMem->flags & MEM_RowSet ){
    sqlite3RowSetClear(pMem->u.pRowSet);
  }
  MemSetTypeFlag(pMem, MEM_Null);
  pMem->type = SQLITE_NULL;
}

/*
** Delete any previous value and set the value to be a BLOB of length
** n containing all zeros.
*/
void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  sqlite3VdbeMemRelease(pMem);
  pMem->flags = MEM_Blob|MEM_Zero;
  pMem->type = SQLITE_BLOB;
  pMem->n = 0;
  if( n<0 ) n = 0;
  pMem->u.nZero = n;
  pMem->enc = SQLITE_UTF8;

#ifdef SQLITE_OMIT_INCRBLOB
  sqlite3VdbeMemGrow(pMem, n, 0);
  if( pMem->z ){
    pMem->n = n;
    memset(pMem->z, 0, n);
  }
#endif
}

/*
** Delete any previous value and set the value stored in *pMem to val,
** manifest type INTEGER.
*/
void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  sqlite3VdbeMemRelease(pMem);
  pMem->u.i = val;
  pMem->flags = MEM_Int;
  pMem->type = SQLITE_INTEGER;
}

/*
** Delete any previous value and set the value stored in *pMem to val,
** manifest type REAL.
*/
void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  if( sqlite3IsNaN(val) ){
    sqlite3VdbeMemSetNull(pMem);
  }else{
    sqlite3VdbeMemRelease(pMem);
    pMem->r = val;
    pMem->flags = MEM_Real;
    pMem->type = SQLITE_FLOAT;
  }
}

/*
** Delete any previous value and set the value of pMem to be an
** empty boolean index.
*/
void sqlite3VdbeMemSetRowSet(Mem *pMem){
  sqlite3 *db = pMem->db;
  assert( db!=0 );
  assert( (pMem->flags & MEM_RowSet)==0 );
  sqlite3VdbeMemRelease(pMem);
  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  if( db->mallocFailed ){
    pMem->flags = MEM_Null;
  }else{
    assert( pMem->zMalloc );
    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
                                       sqlite3DbMallocSize(db, pMem->zMalloc));
    assert( pMem->u.pRowSet!=0 );
    pMem->flags = MEM_RowSet;
  }
}

/*
** Return true if the Mem object contains a TEXT or BLOB that is
** too large - whose size exceeds SQLITE_MAX_LENGTH.
*/
int sqlite3VdbeMemTooBig(Mem *p){
  assert( p->db!=0 );
  if( p->flags & (MEM_Str|MEM_Blob) ){
    int n = p->n;
    if( p->flags & MEM_Zero ){
      n += p->u.nZero;
    }
    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  }
  return 0; 
}

/*
** Size of struct Mem not including the Mem.zMalloc member.
*/
#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))

/*
** Make an shallow copy of pFrom into pTo.  Prior contents of
** pTo are freed.  The pFrom->z field is not duplicated.  If
** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
** and flags gets srcType (either MEM_Ephem or MEM_Static).
*/
void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  assert( (pFrom->flags & MEM_RowSet)==0 );
  sqlite3VdbeMemReleaseExternal(pTo);
  memcpy(pTo, pFrom, MEMCELLSIZE);
  pTo->xDel = 0;
  if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
    assert( srcType==MEM_Ephem || srcType==MEM_Static );
    pTo->flags |= srcType;
  }
}

/*
** Make a full copy of pFrom into pTo.  Prior contents of pTo are
** freed before the copy is made.
*/
int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  int rc = SQLITE_OK;

  assert( (pFrom->flags & MEM_RowSet)==0 );
  sqlite3VdbeMemReleaseExternal(pTo);
  memcpy(pTo, pFrom, MEMCELLSIZE);
  pTo->flags &= ~MEM_Dyn;

  if( pTo->flags&(MEM_Str|MEM_Blob) ){
    if( 0==(pFrom->flags&MEM_Static) ){
      pTo->flags |= MEM_Ephem;
      rc = sqlite3VdbeMemMakeWriteable(pTo);
    }
  }

  return rc;
}

/*
** Transfer the contents of pFrom to pTo. Any existing value in pTo is
** freed. If pFrom contains ephemeral data, a copy is made.
**
** pFrom contains an SQL NULL when this routine returns.
*/
void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );

  sqlite3VdbeMemRelease(pTo);
  memcpy(pTo, pFrom, sizeof(Mem));
  pFrom->flags = MEM_Null;
  pFrom->xDel = 0;
  pFrom->zMalloc = 0;
}

/*
** Change the value of a Mem to be a string or a BLOB.
**
** The memory management strategy depends on the value of the xDel
** parameter. If the value passed is SQLITE_TRANSIENT, then the 
** string is copied into a (possibly existing) buffer managed by the 
** Mem structure. Otherwise, any existing buffer is freed and the
** pointer copied.
**
** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
** size limit) then no memory allocation occurs.  If the string can be
** stored without allocating memory, then it is.  If a memory allocation
** is required to store the string, then value of pMem is unchanged.  In
** either case, SQLITE_TOOBIG is returned.
*/
int sqlite3VdbeMemSetStr(
  Mem *pMem,          /* Memory cell to set to string value */
  const char *z,      /* String pointer */
  int n,              /* Bytes in string, or negative */
  u8 enc,             /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*) /* Destructor function */
){
  int nByte = n;      /* New value for pMem->n */
  int iLimit;         /* Maximum allowed string or blob size */
  u16 flags = 0;      /* New value for pMem->flags */

  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  assert( (pMem->flags & MEM_RowSet)==0 );

  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  if( !z ){
    sqlite3VdbeMemSetNull(pMem);
    return SQLITE_OK;
  }

  if( pMem->db ){
    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  }else{
    iLimit = SQLITE_MAX_LENGTH;
  }
  flags = (enc==0?MEM_Blob:MEM_Str);
  if( nByte<0 ){
    assert( enc!=0 );
    if( enc==SQLITE_UTF8 ){
      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
    }else{
      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
    }
    flags |= MEM_Term;
  }

  /* The following block sets the new values of Mem.z and Mem.xDel. It
  ** also sets a flag in local variable "flags" to indicate the memory
  ** management (one of MEM_Dyn or MEM_Static).
  */
  if( xDel==SQLITE_TRANSIENT ){
    int nAlloc = nByte;
    if( flags&MEM_Term ){
      nAlloc += (enc==SQLITE_UTF8?1:2);
    }
    if( nByte>iLimit ){
      return SQLITE_TOOBIG;
    }
    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
      return SQLITE_NOMEM;
    }
    memcpy(pMem->z, z, nAlloc);
  }else if( xDel==SQLITE_DYNAMIC ){
    sqlite3VdbeMemRelease(pMem);
    pMem->zMalloc = pMem->z = (char *)z;
    pMem->xDel = 0;
  }else{
    sqlite3VdbeMemRelease(pMem);
    pMem->z = (char *)z;
    pMem->xDel = xDel;
    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  }

  pMem->n = nByte;
  pMem->flags = flags;
  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);

#ifndef SQLITE_OMIT_UTF16
  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
    return SQLITE_NOMEM;
  }
#endif

  if( nByte>iLimit ){
    return SQLITE_TOOBIG;
  }

  return SQLITE_OK;
}

/*
** Compare the values contained by the two memory cells, returning
** negative, zero or positive if pMem1 is less than, equal to, or greater
** than pMem2. Sorting order is NULL's first, followed by numbers (integers
** and reals) sorted numerically, followed by text ordered by the collating
** sequence pColl and finally blob's ordered by memcmp().
**
** Two NULL values are considered equal by this function.
*/
int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  int rc;
  int f1, f2;
  int combined_flags;

  /* Interchange pMem1 and pMem2 if the collating sequence specifies
  ** DESC order.
  */
  f1 = pMem1->flags;
  f2 = pMem2->flags;
  combined_flags = f1|f2;
  assert( (combined_flags & MEM_RowSet)==0 );
 
  /* If one value is NULL, it is less than the other. If both values
  ** are NULL, return 0.
  */
  if( combined_flags&MEM_Null ){
    return (f2&MEM_Null) - (f1&MEM_Null);
  }

  /* If one value is a number and the other is not, the number is less.
  ** If both are numbers, compare as reals if one is a real, or as integers
  ** if both values are integers.
  */
  if( combined_flags&(MEM_Int|MEM_Real) ){
    if( !(f1&(MEM_Int|MEM_Real)) ){
      return 1;
    }
    if( !(f2&(MEM_Int|MEM_Real)) ){
      return -1;
    }
    if( (f1 & f2 & MEM_Int)==0 ){
      double r1, r2;
      if( (f1&MEM_Real)==0 ){
        r1 = (double)pMem1->u.i;
      }else{
        r1 = pMem1->r;
      }
      if( (f2&MEM_Real)==0 ){
        r2 = (double)pMem2->u.i;
      }else{
        r2 = pMem2->r;
      }
      if( r1<r2 ) return -1;
      if( r1>r2 ) return 1;
      return 0;
    }else{
      assert( f1&MEM_Int );
      assert( f2&MEM_Int );
      if( pMem1->u.i < pMem2->u.i ) return -1;
      if( pMem1->u.i > pMem2->u.i ) return 1;
      return 0;
    }
  }

  /* If one value is a string and the other is a blob, the string is less.
  ** If both are strings, compare using the collating functions.
  */
  if( combined_flags&MEM_Str ){
    if( (f1 & MEM_Str)==0 ){
      return 1;
    }
    if( (f2 & MEM_Str)==0 ){
      return -1;
    }

    assert( pMem1->enc==pMem2->enc );
    assert( pMem1->enc==SQLITE_UTF8 || 
            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );

    /* The collation sequence must be defined at this point, even if
    ** the user deletes the collation sequence after the vdbe program is
    ** compiled (this was not always the case).
    */
    assert( !pColl || pColl->xCmp );

    if( pColl ){
      if( pMem1->enc==pColl->enc ){
        /* The strings are already in the correct encoding.  Call the
        ** comparison function directly */
        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
      }else{
        const void *v1, *v2;
        int n1, n2;
        Mem c1;
        Mem c2;
        memset(&c1, 0, sizeof(c1));
        memset(&c2, 0, sizeof(c2));
        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
        n1 = v1==0 ? 0 : c1.n;
        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
        n2 = v2==0 ? 0 : c2.n;
        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
        sqlite3VdbeMemRelease(&c1);
        sqlite3VdbeMemRelease(&c2);
        return rc;
      }
    }
    /* If a NULL pointer was passed as the collate function, fall through
    ** to the blob case and use memcmp().  */
  }
 
  /* Both values must be blobs.  Compare using memcmp().  */
  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  if( rc==0 ){
    rc = pMem1->n - pMem2->n;
  }
  return rc;
}

/*
** Move data out of a btree key or data field and into a Mem structure.
** The data or key is taken from the entry that pCur is currently pointing
** to.  offset and amt determine what portion of the data or key to retrieve.
** key is true to get the key or false to get data.  The result is written
** into the pMem element.
**
** The pMem structure is assumed to be uninitialized.  Any prior content
** is overwritten without being freed.
**
** If this routine fails for any reason (malloc returns NULL or unable
** to read from the disk) then the pMem is left in an inconsistent state.
*/
int sqlite3VdbeMemFromBtree(
  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
  int offset,       /* Offset from the start of data to return bytes from. */
  int amt,          /* Number of bytes to return. */
  int key,          /* If true, retrieve from the btree key, not data. */
  Mem *pMem         /* OUT: Return data in this Mem structure. */
){
  char *zData;        /* Data from the btree layer */
  int available = 0;  /* Number of bytes available on the local btree page */
  int rc = SQLITE_OK; /* Return code */

  assert( sqlite3BtreeCursorIsValid(pCur) );

  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
  ** that both the BtShared and database handle mutexes are held. */
  assert( (pMem->flags & MEM_RowSet)==0 );
  if( key ){
    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  }else{
    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  }
  assert( zData!=0 );

  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
    sqlite3VdbeMemRelease(pMem);
    pMem->z = &zData[offset];
    pMem->flags = MEM_Blob|MEM_Ephem;
  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
    pMem->enc = 0;
    pMem->type = SQLITE_BLOB;
    if( key ){
      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
    }else{
      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
    }
    pMem->z[amt] = 0;
    pMem->z[amt+1] = 0;
    if( rc!=SQLITE_OK ){
      sqlite3VdbeMemRelease(pMem);
    }
  }
  pMem->n = amt;

  return rc;
}

/* This function is only available internally, it is not part of the
** external API. It works in a similar way to sqlite3_value_text(),
** except the data returned is in the encoding specified by the second
** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
** SQLITE_UTF8.
**
** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
** If that is the case, then the result must be aligned on an even byte
** boundary.
*/
const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  if( !pVal ) return 0;

  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  assert( (pVal->flags & MEM_RowSet)==0 );

  if( pVal->flags&MEM_Null ){
    return 0;
  }
  assert( (MEM_Blob>>3) == MEM_Str );
  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  expandBlob(pVal);
  if( pVal->flags&MEM_Str ){
    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
        return 0;
      }
    }
    sqlite3VdbeMemNulTerminate(pVal);
  }else{
    assert( (pVal->flags&MEM_Blob)==0 );
    sqlite3VdbeMemStringify(pVal, enc);
    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  }
  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
              || pVal->db->mallocFailed );
  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
    return pVal->z;
  }else{
    return 0;
  }
}

/*
** Create a new sqlite3_value object.
*/
sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  if( p ){
    p->flags = MEM_Null;
    p->type = SQLITE_NULL;
    p->db = db;
  }
  return p;
}

/*
** Create a new sqlite3_value object, containing the value of pExpr.
**
** This only works for very simple expressions that consist of one constant
** token (i.e. "5", "5.1", "'a string'"). If the expression can
** be converted directly into a value, then the value is allocated and
** a pointer written to *ppVal. The caller is responsible for deallocating
** the value by passing it to sqlite3ValueFree() later on. If the expression
** cannot be converted to a value, then *ppVal is set to NULL.
*/
int sqlite3ValueFromExpr(
  sqlite3 *db,              /* The database connection */
  Expr *pExpr,              /* The expression to evaluate */
  u8 enc,                   /* Encoding to use */
  u8 affinity,              /* Affinity to use */
  sqlite3_value **ppVal     /* Write the new value here */
){
  int op;
  char *zVal = 0;
  sqlite3_value *pVal = 0;

  if( !pExpr ){
    *ppVal = 0;
    return SQLITE_OK;
  }
  op = pExpr->op;
  if( op==TK_REGISTER ){
    op = pExpr->op2;
  }

  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
    pVal = sqlite3ValueNew(db);
    if( pVal==0 ) goto no_mem;
    if( ExprHasProperty(pExpr, EP_IntValue) ){
      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
    }else{
      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
      if( zVal==0 ) goto no_mem;
      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
    }
    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
    }else{
      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
    }
    if( enc!=SQLITE_UTF8 ){
      sqlite3VdbeChangeEncoding(pVal, enc);
    }
  }else if( op==TK_UMINUS ) {
    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
      pVal->u.i = -1 * pVal->u.i;
      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
      pVal->r = (double)-1 * pVal->r;
    }
  }
#ifndef SQLITE_OMIT_BLOB_LITERAL
  else if( op==TK_BLOB ){
    int nVal;
    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
    assert( pExpr->u.zToken[1]=='\'' );
    pVal = sqlite3ValueNew(db);
    if( !pVal ) goto no_mem;
    zVal = &pExpr->u.zToken[2];
    nVal = sqlite3Strlen30(zVal)-1;
    assert( zVal[nVal]=='\'' );
    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
                         0, SQLITE_DYNAMIC);
  }
#endif

  if( pVal ){
    sqlite3VdbeMemStoreType(pVal);
  }
  *ppVal = pVal;
  return SQLITE_OK;

no_mem:
  db->mallocFailed = 1;
  sqlite3DbFree(db, zVal);
  sqlite3ValueFree(pVal);
  *ppVal = 0;
  return SQLITE_NOMEM;
}

/*
** Change the string value of an sqlite3_value object
*/
void sqlite3ValueSetStr(
  sqlite3_value *v,     /* Value to be set */
  int n,                /* Length of string z */
  const void *z,        /* Text of the new string */
  u8 enc,               /* Encoding to use */
  void (*xDel)(void*)   /* Destructor for the string */
){
  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
}

/*
** Free an sqlite3_value object
*/
void sqlite3ValueFree(sqlite3_value *v){
  if( !v ) return;
  sqlite3VdbeMemRelease((Mem *)v);
  sqlite3DbFree(((Mem*)v)->db, v);
}

/*
** Return the number of bytes in the sqlite3_value object assuming
** that it uses the encoding "enc"
*/
int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  Mem *p = (Mem*)pVal;
  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
    if( p->flags & MEM_Zero ){
      return p->n + p->u.nZero;
    }else{
      return p->n;
    }
  }
  return 0;
}

Added src/vtab.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
/*
** 2006 June 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to help implement virtual tables.
**
** $Id: vtab.c,v 1.94 2009/08/08 18:01:08 drh Exp $
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
#include "sqliteInt.h"

/*
** The actual function that does the work of creating a new module.
** This function implements the sqlite3_create_module() and
** sqlite3_create_module_v2() interfaces.
*/
static int createModule(
  sqlite3 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite3_module *pModule,  /* The definition of the module */
  void *pAux,                     /* Context pointer for xCreate/xConnect */
  void (*xDestroy)(void *)        /* Module destructor function */
){
  int rc, nName;
  Module *pMod;

  sqlite3_mutex_enter(db->mutex);
  nName = sqlite3Strlen30(zName);
  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  if( pMod ){
    Module *pDel;
    char *zCopy = (char *)(&pMod[1]);
    memcpy(zCopy, zName, nName+1);
    pMod->zName = zCopy;
    pMod->pModule = pModule;
    pMod->pAux = pAux;
    pMod->xDestroy = xDestroy;
    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
    if( pDel && pDel->xDestroy ){
      pDel->xDestroy(pDel->pAux);
    }
    sqlite3DbFree(db, pDel);
    if( pDel==pMod ){
      db->mallocFailed = 1;
    }
    sqlite3ResetInternalSchema(db, 0);
  }else if( xDestroy ){
    xDestroy(pAux);
  }
  rc = sqlite3ApiExit(db, SQLITE_OK);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}


/*
** External API function used to create a new virtual-table module.
*/
int sqlite3_create_module(
  sqlite3 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite3_module *pModule,  /* The definition of the module */
  void *pAux                      /* Context pointer for xCreate/xConnect */
){
  return createModule(db, zName, pModule, pAux, 0);
}

/*
** External API function used to create a new virtual-table module.
*/
int sqlite3_create_module_v2(
  sqlite3 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite3_module *pModule,  /* The definition of the module */
  void *pAux,                     /* Context pointer for xCreate/xConnect */
  void (*xDestroy)(void *)        /* Module destructor function */
){
  return createModule(db, zName, pModule, pAux, xDestroy);
}

/*
** Lock the virtual table so that it cannot be disconnected.
** Locks nest.  Every lock should have a corresponding unlock.
** If an unlock is omitted, resources leaks will occur.  
**
** If a disconnect is attempted while a virtual table is locked,
** the disconnect is deferred until all locks have been removed.
*/
void sqlite3VtabLock(VTable *pVTab){
  pVTab->nRef++;
}


/*
** pTab is a pointer to a Table structure representing a virtual-table.
** Return a pointer to the VTable object used by connection db to access 
** this virtual-table, if one has been created, or NULL otherwise.
*/
VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  VTable *pVtab;
  assert( IsVirtual(pTab) );
  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  return pVtab;
}

/*
** Decrement the ref-count on a virtual table object. When the ref-count
** reaches zero, call the xDisconnect() method to delete the object.
*/
void sqlite3VtabUnlock(VTable *pVTab){
  sqlite3 *db = pVTab->db;

  assert( db );
  assert( pVTab->nRef>0 );
  assert( sqlite3SafetyCheckOk(db) );

  pVTab->nRef--;
  if( pVTab->nRef==0 ){
    sqlite3_vtab *p = pVTab->pVtab;
    if( p ){
#ifdef SQLITE_DEBUG
      if( pVTab->db->magic==SQLITE_MAGIC_BUSY ){
        (void)sqlite3SafetyOff(db);
        p->pModule->xDisconnect(p);
        (void)sqlite3SafetyOn(db);
      } else
#endif
      {
        p->pModule->xDisconnect(p);
      }
    }
    sqlite3DbFree(db, pVTab);
  }
}

/*
** Table p is a virtual table. This function moves all elements in the
** p->pVTable list to the sqlite3.pDisconnect lists of their associated
** database connections to be disconnected at the next opportunity. 
** Except, if argument db is not NULL, then the entry associated with
** connection db is left in the p->pVTable list.
*/
static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  VTable *pRet = 0;
  VTable *pVTable = p->pVTable;
  p->pVTable = 0;

  /* Assert that the mutex (if any) associated with the BtShared database 
  ** that contains table p is held by the caller. See header comments 
  ** above function sqlite3VtabUnlockList() for an explanation of why
  ** this makes it safe to access the sqlite3.pDisconnect list of any
  ** database connection that may have an entry in the p->pVTable list.  */
  assert( db==0 ||
    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
  );

  while( pVTable ){
    sqlite3 *db2 = pVTable->db;
    VTable *pNext = pVTable->pNext;
    assert( db2 );
    if( db2==db ){
      pRet = pVTable;
      p->pVTable = pRet;
      pRet->pNext = 0;
    }else{
      pVTable->pNext = db2->pDisconnect;
      db2->pDisconnect = pVTable;
    }
    pVTable = pNext;
  }

  assert( !db || pRet );
  return pRet;
}


/*
** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
**
** This function may only be called when the mutexes associated with all
** shared b-tree databases opened using connection db are held by the 
** caller. This is done to protect the sqlite3.pDisconnect list. The
** sqlite3.pDisconnect list is accessed only as follows:
**
**   1) By this function. In this case, all BtShared mutexes and the mutex
**      associated with the database handle itself must be held.
**
**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
**      associated with the database the virtual table is stored in is held
**      or, if the virtual table is stored in a non-sharable database, then
**      the database handle mutex is held.
**
** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
** by multiple threads. It is thread-safe.
*/
void sqlite3VtabUnlockList(sqlite3 *db){
  VTable *p = db->pDisconnect;
  db->pDisconnect = 0;

  assert( sqlite3BtreeHoldsAllMutexes(db) );
  assert( sqlite3_mutex_held(db->mutex) );

  if( p ){
    sqlite3ExpirePreparedStatements(db);
    do {
      VTable *pNext = p->pNext;
      sqlite3VtabUnlock(p);
      p = pNext;
    }while( p );
  }
}

/*
** Clear any and all virtual-table information from the Table record.
** This routine is called, for example, just before deleting the Table
** record.
**
** Since it is a virtual-table, the Table structure contains a pointer
** to the head of a linked list of VTable structures. Each VTable 
** structure is associated with a single sqlite3* user of the schema.
** The reference count of the VTable structure associated with database 
** connection db is decremented immediately (which may lead to the 
** structure being xDisconnected and free). Any other VTable structures
** in the list are moved to the sqlite3.pDisconnect list of the associated 
** database connection.
*/
void sqlite3VtabClear(Table *p){
  vtabDisconnectAll(0, p);
  if( p->azModuleArg ){
    int i;
    for(i=0; i<p->nModuleArg; i++){
      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
    }
    sqlite3DbFree(p->dbMem, p->azModuleArg);
  }
}

/*
** Add a new module argument to pTable->azModuleArg[].
** The string is not copied - the pointer is stored.  The
** string will be freed automatically when the table is
** deleted.
*/
static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  int i = pTable->nModuleArg++;
  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  char **azModuleArg;
  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  if( azModuleArg==0 ){
    int j;
    for(j=0; j<i; j++){
      sqlite3DbFree(db, pTable->azModuleArg[j]);
    }
    sqlite3DbFree(db, zArg);
    sqlite3DbFree(db, pTable->azModuleArg);
    pTable->nModuleArg = 0;
  }else{
    azModuleArg[i] = zArg;
    azModuleArg[i+1] = 0;
  }
  pTable->azModuleArg = azModuleArg;
}

/*
** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
** statement.  The module name has been parsed, but the optional list
** of parameters that follow the module name are still pending.
*/
void sqlite3VtabBeginParse(
  Parse *pParse,        /* Parsing context */
  Token *pName1,        /* Name of new table, or database name */
  Token *pName2,        /* Name of new table or NULL */
  Token *pModuleName    /* Name of the module for the virtual table */
){
  int iDb;              /* The database the table is being created in */
  Table *pTable;        /* The new virtual table */
  sqlite3 *db;          /* Database connection */

  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
  pTable = pParse->pNewTable;
  if( pTable==0 ) return;
  assert( 0==pTable->pIndex );

  db = pParse->db;
  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  assert( iDb>=0 );

  pTable->tabFlags |= TF_Virtual;
  pTable->nModuleArg = 0;
  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);

#ifndef SQLITE_OMIT_AUTHORIZATION
  /* Creating a virtual table invokes the authorization callback twice.
  ** The first invocation, to obtain permission to INSERT a row into the
  ** sqlite_master table, has already been made by sqlite3StartTable().
  ** The second call, to obtain permission to create the table, is made now.
  */
  if( pTable->azModuleArg ){
    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  }
#endif
}

/*
** This routine takes the module argument that has been accumulating
** in pParse->zArg[] and appends it to the list of arguments on the
** virtual table currently under construction in pParse->pTable.
*/
static void addArgumentToVtab(Parse *pParse){
  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
    const char *z = (const char*)pParse->sArg.z;
    int n = pParse->sArg.n;
    sqlite3 *db = pParse->db;
    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  }
}

/*
** The parser calls this routine after the CREATE VIRTUAL TABLE statement
** has been completely parsed.
*/
void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  Table *pTab = pParse->pNewTable;  /* The table being constructed */
  sqlite3 *db = pParse->db;         /* The database connection */

  if( pTab==0 ) return;
  addArgumentToVtab(pParse);
  pParse->sArg.z = 0;
  if( pTab->nModuleArg<1 ) return;
  
  /* If the CREATE VIRTUAL TABLE statement is being entered for the
  ** first time (in other words if the virtual table is actually being
  ** created now instead of just being read out of sqlite_master) then
  ** do additional initialization work and store the statement text
  ** in the sqlite_master table.
  */
  if( !db->init.busy ){
    char *zStmt;
    char *zWhere;
    int iDb;
    Vdbe *v;

    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
    if( pEnd ){
      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
    }
    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);

    /* A slot for the record has already been allocated in the 
    ** SQLITE_MASTER table.  We just need to update that slot with all
    ** the information we've collected.  
    **
    ** The VM register number pParse->regRowid holds the rowid of an
    ** entry in the sqlite_master table tht was created for this vtab
    ** by sqlite3StartTable().
    */
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
    sqlite3NestedParse(pParse,
      "UPDATE %Q.%s "
         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
       "WHERE rowid=#%d",
      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
      pTab->zName,
      pTab->zName,
      zStmt,
      pParse->regRowid
    );
    sqlite3DbFree(db, zStmt);
    v = sqlite3GetVdbe(pParse);
    sqlite3ChangeCookie(pParse, iDb);

    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  }

  /* If we are rereading the sqlite_master table create the in-memory
  ** record of the table. The xConnect() method is not called until
  ** the first time the virtual table is used in an SQL statement. This
  ** allows a schema that contains virtual tables to be loaded before
  ** the required virtual table implementations are registered.  */
  else {
    Table *pOld;
    Schema *pSchema = pTab->pSchema;
    const char *zName = pTab->zName;
    int nName = sqlite3Strlen30(zName);
    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
    if( pOld ){
      db->mallocFailed = 1;
      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
      return;
    }
    pSchema->db = pParse->db;
    pParse->pNewTable = 0;
  }
}

/*
** The parser calls this routine when it sees the first token
** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
void sqlite3VtabArgInit(Parse *pParse){
  addArgumentToVtab(pParse);
  pParse->sArg.z = 0;
  pParse->sArg.n = 0;
}

/*
** The parser calls this routine for each token after the first token
** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  Token *pArg = &pParse->sArg;
  if( pArg->z==0 ){
    pArg->z = p->z;
    pArg->n = p->n;
  }else{
    assert(pArg->z < p->z);
    pArg->n = (int)(&p->z[p->n] - pArg->z);
  }
}

/*
** Invoke a virtual table constructor (either xCreate or xConnect). The
** pointer to the function to invoke is passed as the fourth parameter
** to this procedure.
*/
static int vtabCallConstructor(
  sqlite3 *db, 
  Table *pTab,
  Module *pMod,
  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  char **pzErr
){
  VTable *pVTable;
  int rc;
  const char *const*azArg = (const char *const*)pTab->azModuleArg;
  int nArg = pTab->nModuleArg;
  char *zErr = 0;
  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);

  if( !zModuleName ){
    return SQLITE_NOMEM;
  }

  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  if( !pVTable ){
    sqlite3DbFree(db, zModuleName);
    return SQLITE_NOMEM;
  }
  pVTable->db = db;
  pVTable->pMod = pMod;

  assert( !db->pVTab );
  assert( xConstruct );
  db->pVTab = pTab;

  /* Invoke the virtual table constructor */
  (void)sqlite3SafetyOff(db);
  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  (void)sqlite3SafetyOn(db);
  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;

  if( SQLITE_OK!=rc ){
    if( zErr==0 ){
      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
    }else {
      *pzErr = sqlite3MPrintf(db, "%s", zErr);
      sqlite3DbFree(db, zErr);
    }
    sqlite3DbFree(db, pVTable);
  }else if( ALWAYS(pVTable->pVtab) ){
    /* Justification of ALWAYS():  A correct vtab constructor must allocate
    ** the sqlite3_vtab object if successful.  */
    pVTable->pVtab->pModule = pMod->pModule;
    pVTable->nRef = 1;
    if( db->pVTab ){
      const char *zFormat = "vtable constructor did not declare schema: %s";
      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
      sqlite3VtabUnlock(pVTable);
      rc = SQLITE_ERROR;
    }else{
      int iCol;
      /* If everything went according to plan, link the new VTable structure
      ** into the linked list headed by pTab->pVTable. Then loop through the 
      ** columns of the table to see if any of them contain the token "hidden".
      ** If so, set the Column.isHidden flag and remove the token from
      ** the type string.  */
      pVTable->pNext = pTab->pVTable;
      pTab->pVTable = pVTable;

      for(iCol=0; iCol<pTab->nCol; iCol++){
        char *zType = pTab->aCol[iCol].zType;
        int nType;
        int i = 0;
        if( !zType ) continue;
        nType = sqlite3Strlen30(zType);
        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
          for(i=0; i<nType; i++){
            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
             && (zType[i+7]=='\0' || zType[i+7]==' ')
            ){
              i++;
              break;
            }
          }
        }
        if( i<nType ){
          int j;
          int nDel = 6 + (zType[i+6] ? 1 : 0);
          for(j=i; (j+nDel)<=nType; j++){
            zType[j] = zType[j+nDel];
          }
          if( zType[i]=='\0' && i>0 ){
            assert(zType[i-1]==' ');
            zType[i-1] = '\0';
          }
          pTab->aCol[iCol].isHidden = 1;
        }
      }
    }
  }

  sqlite3DbFree(db, zModuleName);
  db->pVTab = 0;
  return rc;
}

/*
** This function is invoked by the parser to call the xConnect() method
** of the virtual table pTab. If an error occurs, an error code is returned 
** and an error left in pParse.
**
** This call is a no-op if table pTab is not a virtual table.
*/
int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  sqlite3 *db = pParse->db;
  const char *zMod;
  Module *pMod;
  int rc;

  assert( pTab );
  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
    return SQLITE_OK;
  }

  /* Locate the required virtual table module */
  zMod = pTab->azModuleArg[0];
  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));

  if( !pMod ){
    const char *zModule = pTab->azModuleArg[0];
    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
    rc = SQLITE_ERROR;
  }else{
    char *zErr = 0;
    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
    if( rc!=SQLITE_OK ){
      sqlite3ErrorMsg(pParse, "%s", zErr);
    }
    sqlite3DbFree(db, zErr);
  }

  return rc;
}

/*
** Add the virtual table pVTab to the array sqlite3.aVTrans[].
*/
static int addToVTrans(sqlite3 *db, VTable *pVTab){
  const int ARRAY_INCR = 5;

  /* Grow the sqlite3.aVTrans array if required */
  if( (db->nVTrans%ARRAY_INCR)==0 ){
    VTable **aVTrans;
    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
    if( !aVTrans ){
      return SQLITE_NOMEM;
    }
    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
    db->aVTrans = aVTrans;
  }

  /* Add pVtab to the end of sqlite3.aVTrans */
  db->aVTrans[db->nVTrans++] = pVTab;
  sqlite3VtabLock(pVTab);
  return SQLITE_OK;
}

/*
** This function is invoked by the vdbe to call the xCreate method
** of the virtual table named zTab in database iDb. 
**
** If an error occurs, *pzErr is set to point an an English language
** description of the error and an SQLITE_XXX error code is returned.
** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
*/
int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  int rc = SQLITE_OK;
  Table *pTab;
  Module *pMod;
  const char *zMod;

  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );

  /* Locate the required virtual table module */
  zMod = pTab->azModuleArg[0];
  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));

  /* If the module has been registered and includes a Create method, 
  ** invoke it now. If the module has not been registered, return an 
  ** error. Otherwise, do nothing.
  */
  if( !pMod ){
    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
    rc = SQLITE_ERROR;
  }else{
    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  }

  /* Justification of ALWAYS():  The xConstructor method is required to
  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
  }

  return rc;
}

/*
** This function is used to set the schema of a virtual table.  It is only
** valid to call this function from within the xCreate() or xConnect() of a
** virtual table module.
*/
int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  Parse *pParse;

  int rc = SQLITE_OK;
  Table *pTab;
  char *zErr = 0;

  sqlite3_mutex_enter(db->mutex);
  pTab = db->pVTab;
  if( !pTab ){
    sqlite3Error(db, SQLITE_MISUSE, 0);
    sqlite3_mutex_leave(db->mutex);
    return SQLITE_MISUSE;
  }
  assert( (pTab->tabFlags & TF_Virtual)!=0 );

  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  if( pParse==0 ){
    rc = SQLITE_NOMEM;
  }else{
    pParse->declareVtab = 1;
    pParse->db = db;
  
    if( 
        SQLITE_OK == sqlite3RunParser(pParse, zCreateTable, &zErr) && 
        pParse->pNewTable && 
        !pParse->pNewTable->pSelect && 
        (pParse->pNewTable->tabFlags & TF_Virtual)==0
    ){
      if( !pTab->aCol ){
        pTab->aCol = pParse->pNewTable->aCol;
        pTab->nCol = pParse->pNewTable->nCol;
        pParse->pNewTable->nCol = 0;
        pParse->pNewTable->aCol = 0;
      }
      db->pVTab = 0;
    } else {
      sqlite3Error(db, SQLITE_ERROR, zErr);
      sqlite3DbFree(db, zErr);
      rc = SQLITE_ERROR;
    }
    pParse->declareVtab = 0;
  
    if( pParse->pVdbe ){
      sqlite3VdbeFinalize(pParse->pVdbe);
    }
    sqlite3DeleteTable(pParse->pNewTable);
    sqlite3StackFree(db, pParse);
  }

  assert( (rc&0xff)==rc );
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

/*
** This function is invoked by the vdbe to call the xDestroy method
** of the virtual table named zTab in database iDb. This occurs
** when a DROP TABLE is mentioned.
**
** This call is a no-op if zTab is not a virtual table.
*/
int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  int rc = SQLITE_OK;
  Table *pTab;

  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
    VTable *p = vtabDisconnectAll(db, pTab);

    rc = sqlite3SafetyOff(db);
    assert( rc==SQLITE_OK );
    rc = p->pMod->pModule->xDestroy(p->pVtab);
    (void)sqlite3SafetyOn(db);

    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
    if( rc==SQLITE_OK ){
      assert( pTab->pVTable==p && p->pNext==0 );
      p->pVtab = 0;
      pTab->pVTable = 0;
      sqlite3VtabUnlock(p);
    }
  }

  return rc;
}

/*
** This function invokes either the xRollback or xCommit method
** of each of the virtual tables in the sqlite3.aVTrans array. The method
** called is identified by the second argument, "offset", which is
** the offset of the method to call in the sqlite3_module structure.
**
** The array is cleared after invoking the callbacks. 
*/
static void callFinaliser(sqlite3 *db, int offset){
  int i;
  if( db->aVTrans ){
    for(i=0; i<db->nVTrans; i++){
      VTable *pVTab = db->aVTrans[i];
      sqlite3_vtab *p = pVTab->pVtab;
      if( p ){
        int (*x)(sqlite3_vtab *);
        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
        if( x ) x(p);
      }
      sqlite3VtabUnlock(pVTab);
    }
    sqlite3DbFree(db, db->aVTrans);
    db->nVTrans = 0;
    db->aVTrans = 0;
  }
}

/*
** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
** array. Return the error code for the first error that occurs, or
** SQLITE_OK if all xSync operations are successful.
**
** Set *pzErrmsg to point to a buffer that should be released using 
** sqlite3DbFree() containing an error message, if one is available.
*/
int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
  int i;
  int rc = SQLITE_OK;
  int rcsafety;
  VTable **aVTrans = db->aVTrans;

  rc = sqlite3SafetyOff(db);
  db->aVTrans = 0;
  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
    int (*x)(sqlite3_vtab *);
    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
      rc = x(pVtab);
      sqlite3DbFree(db, *pzErrmsg);
      *pzErrmsg = pVtab->zErrMsg;
      pVtab->zErrMsg = 0;
    }
  }
  db->aVTrans = aVTrans;
  rcsafety = sqlite3SafetyOn(db);

  if( rc==SQLITE_OK ){
    rc = rcsafety;
  }
  return rc;
}

/*
** Invoke the xRollback method of all virtual tables in the 
** sqlite3.aVTrans array. Then clear the array itself.
*/
int sqlite3VtabRollback(sqlite3 *db){
  callFinaliser(db, offsetof(sqlite3_module,xRollback));
  return SQLITE_OK;
}

/*
** Invoke the xCommit method of all virtual tables in the 
** sqlite3.aVTrans array. Then clear the array itself.
*/
int sqlite3VtabCommit(sqlite3 *db){
  callFinaliser(db, offsetof(sqlite3_module,xCommit));
  return SQLITE_OK;
}

/*
** If the virtual table pVtab supports the transaction interface
** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
** not currently open, invoke the xBegin method now.
**
** If the xBegin call is successful, place the sqlite3_vtab pointer
** in the sqlite3.aVTrans array.
*/
int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  int rc = SQLITE_OK;
  const sqlite3_module *pModule;

  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  ** than zero, then this function is being called from within a
  ** virtual module xSync() callback. It is illegal to write to 
  ** virtual module tables in this case, so return SQLITE_LOCKED.
  */
  if( sqlite3VtabInSync(db) ){
    return SQLITE_LOCKED;
  }
  if( !pVTab ){
    return SQLITE_OK;
  } 
  pModule = pVTab->pVtab->pModule;

  if( pModule->xBegin ){
    int i;


    /* If pVtab is already in the aVTrans array, return early */
    for(i=0; i<db->nVTrans; i++){
      if( db->aVTrans[i]==pVTab ){
        return SQLITE_OK;
      }
    }

    /* Invoke the xBegin method */
    rc = pModule->xBegin(pVTab->pVtab);
    if( rc==SQLITE_OK ){
      rc = addToVTrans(db, pVTab);
    }
  }
  return rc;
}

/*
** The first parameter (pDef) is a function implementation.  The
** second parameter (pExpr) is the first argument to this function.
** If pExpr is a column in a virtual table, then let the virtual
** table implementation have an opportunity to overload the function.
**
** This routine is used to allow virtual table implementations to
** overload MATCH, LIKE, GLOB, and REGEXP operators.
**
** Return either the pDef argument (indicating no change) or a 
** new FuncDef structure that is marked as ephemeral using the
** SQLITE_FUNC_EPHEM flag.
*/
FuncDef *sqlite3VtabOverloadFunction(
  sqlite3 *db,    /* Database connection for reporting malloc problems */
  FuncDef *pDef,  /* Function to possibly overload */
  int nArg,       /* Number of arguments to the function */
  Expr *pExpr     /* First argument to the function */
){
  Table *pTab;
  sqlite3_vtab *pVtab;
  sqlite3_module *pMod;
  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  void *pArg = 0;
  FuncDef *pNew;
  int rc = 0;
  char *zLowerName;
  unsigned char *z;


  /* Check to see the left operand is a column in a virtual table */
  if( NEVER(pExpr==0) ) return pDef;
  if( pExpr->op!=TK_COLUMN ) return pDef;
  pTab = pExpr->pTab;
  if( NEVER(pTab==0) ) return pDef;
  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  assert( pVtab!=0 );
  assert( pVtab->pModule!=0 );
  pMod = (sqlite3_module *)pVtab->pModule;
  if( pMod->xFindFunction==0 ) return pDef;
 
  /* Call the xFindFunction method on the virtual table implementation
  ** to see if the implementation wants to overload this function 
  */
  zLowerName = sqlite3DbStrDup(db, pDef->zName);
  if( zLowerName ){
    for(z=(unsigned char*)zLowerName; *z; z++){
      *z = sqlite3UpperToLower[*z];
    }
    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
    sqlite3DbFree(db, zLowerName);
  }
  if( rc==0 ){
    return pDef;
  }

  /* Create a new ephemeral function definition for the overloaded
  ** function */
  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
                             + sqlite3Strlen30(pDef->zName) + 1);
  if( pNew==0 ){
    return pDef;
  }
  *pNew = *pDef;
  pNew->zName = (char *)&pNew[1];
  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  pNew->xFunc = xFunc;
  pNew->pUserData = pArg;
  pNew->flags |= SQLITE_FUNC_EPHEM;
  return pNew;
}

/*
** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
** array so that an OP_VBegin will get generated for it.  Add pTab to the
** array if it is missing.  If pTab is already in the array, this routine
** is a no-op.
*/
void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  Parse *pToplevel = sqlite3ParseToplevel(pParse);
  int i, n;
  Table **apVtabLock;

  assert( IsVirtual(pTab) );
  for(i=0; i<pToplevel->nVtabLock; i++){
    if( pTab==pToplevel->apVtabLock[i] ) return;
  }
  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  if( apVtabLock ){
    pToplevel->apVtabLock = apVtabLock;
    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  }else{
    pToplevel->db->mallocFailed = 1;
  }
}

#endif /* SQLITE_OMIT_VIRTUALTABLE */

Added src/walker.c.





















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
** 2008 August 16
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for walking the parser tree for
** an SQL statement.
**
** $Id: walker.c,v 1.7 2009/06/15 23:15:59 drh Exp $
*/
#include "sqliteInt.h"
#include <stdlib.h>
#include <string.h>


/*
** Walk an expression tree.  Invoke the callback once for each node
** of the expression, while decending.  (In other words, the callback
** is invoked before visiting children.)
**
** The return value from the callback should be one of the WRC_*
** constants to specify how to proceed with the walk.
**
**    WRC_Continue      Continue descending down the tree.
**
**    WRC_Prune         Do not descend into child nodes.  But allow
**                      the walk to continue with sibling nodes.
**
**    WRC_Abort         Do no more callbacks.  Unwind the stack and
**                      return the top-level walk call.
**
** The return value from this routine is WRC_Abort to abandon the tree walk
** and WRC_Continue to continue.
*/
int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  int rc;
  if( pExpr==0 ) return WRC_Continue;
  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  testcase( ExprHasProperty(pExpr, EP_Reduced) );
  rc = pWalker->xExprCallback(pWalker, pExpr);
  if( rc==WRC_Continue
              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
    }else{
      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
    }
  }
  return rc & WRC_Abort;
}

/*
** Call sqlite3WalkExpr() for every expression in list p or until
** an abort request is seen.
*/
int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  int i;
  struct ExprList_item *pItem;
  if( p ){
    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
    }
  }
  return WRC_Continue;
}

/*
** Walk all expressions associated with SELECT statement p.  Do
** not invoke the SELECT callback on p, but do (of course) invoke
** any expr callbacks and SELECT callbacks that come from subqueries.
** Return WRC_Abort or WRC_Continue.
*/
int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  return WRC_Continue;
}

/*
** Walk the parse trees associated with all subqueries in the
** FROM clause of SELECT statement p.  Do not invoke the select
** callback on p, but do invoke it on each FROM clause subquery
** and on any subqueries further down in the tree.  Return 
** WRC_Abort or WRC_Continue;
*/
int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  SrcList *pSrc;
  int i;
  struct SrcList_item *pItem;

  pSrc = p->pSrc;
  if( ALWAYS(pSrc) ){
    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
        return WRC_Abort;
      }
    }
  }
  return WRC_Continue;
} 

/*
** Call sqlite3WalkExpr() for every expression in Select statement p.
** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
** on the compound select chain, p->pPrior.
**
** Return WRC_Continue under normal conditions.  Return WRC_Abort if
** there is an abort request.
**
** If the Walker does not have an xSelectCallback() then this routine
** is a no-op returning WRC_Continue.
*/
int sqlite3WalkSelect(Walker *pWalker, Select *p){
  int rc;
  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  rc = WRC_Continue;
  while( p  ){
    rc = pWalker->xSelectCallback(pWalker, p);
    if( rc ) break;
    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
    p = p->pPrior;
  }
  return rc & WRC_Abort;
}

Added src/where.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This module contains C code that generates VDBE code used to process
** the WHERE clause of SQL statements.  This module is responsible for
** generating the code that loops through a table looking for applicable
** rows.  Indices are selected and used to speed the search when doing
** so is applicable.  Because this module is responsible for selecting
** indices, you might also think of this module as the "query optimizer".
**
** $Id: where.c,v 1.411 2009/07/31 06:14:52 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** Trace output macros
*/
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
int sqlite3WhereTrace = 0;
#endif
#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
#else
# define WHERETRACE(X)
#endif

/* Forward reference
*/
typedef struct WhereClause WhereClause;
typedef struct WhereMaskSet WhereMaskSet;
typedef struct WhereOrInfo WhereOrInfo;
typedef struct WhereAndInfo WhereAndInfo;
typedef struct WhereCost WhereCost;

/*
** The query generator uses an array of instances of this structure to
** help it analyze the subexpressions of the WHERE clause.  Each WHERE
** clause subexpression is separated from the others by AND operators,
** usually, or sometimes subexpressions separated by OR.
**
** All WhereTerms are collected into a single WhereClause structure.  
** The following identity holds:
**
**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
**
** When a term is of the form:
**
**              X <op> <expr>
**
** where X is a column name and <op> is one of certain operators,
** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
** cursor number and column number for X.  WhereTerm.eOperator records
** the <op> using a bitmask encoding defined by WO_xxx below.  The
** use of a bitmask encoding for the operator allows us to search
** quickly for terms that match any of several different operators.
**
** A WhereTerm might also be two or more subterms connected by OR:
**
**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
**
** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
** and the WhereTerm.u.pOrInfo field points to auxiliary information that
** is collected about the
**
** If a term in the WHERE clause does not match either of the two previous
** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
** to the original subexpression content and wtFlags is set up appropriately
** but no other fields in the WhereTerm object are meaningful.
**
** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
** but they do so indirectly.  A single WhereMaskSet structure translates
** cursor number into bits and the translated bit is stored in the prereq
** fields.  The translation is used in order to maximize the number of
** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
** spread out over the non-negative integers.  For example, the cursor
** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
** translates these sparse cursor numbers into consecutive integers
** beginning with 0 in order to make the best possible use of the available
** bits in the Bitmask.  So, in the example above, the cursor numbers
** would be mapped into integers 0 through 7.
**
** The number of terms in a join is limited by the number of bits
** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
** is only able to process joins with 64 or fewer tables.
*/
typedef struct WhereTerm WhereTerm;
struct WhereTerm {
  Expr *pExpr;            /* Pointer to the subexpression that is this term */
  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
  union {
    int leftColumn;         /* Column number of X in "X <op> <expr>" */
    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
  } u;
  u16 eOperator;          /* A WO_xx value describing <op> */
  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
  u8 nChild;              /* Number of children that must disable us */
  WhereClause *pWC;       /* The clause this term is part of */
  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
};

/*
** Allowed values of WhereTerm.wtFlags
*/
#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
#define TERM_CODED      0x04   /* This term is already coded */
#define TERM_COPIED     0x08   /* Has a child */
#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
#define TERM_OR_OK      0x40   /* Used during OR-clause processing */

/*
** An instance of the following structure holds all information about a
** WHERE clause.  Mostly this is a container for one or more WhereTerms.
*/
struct WhereClause {
  Parse *pParse;           /* The parser context */
  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
  u8 op;                   /* Split operator.  TK_AND or TK_OR */
  int nTerm;               /* Number of terms */
  int nSlot;               /* Number of entries in a[] */
  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
#if defined(SQLITE_SMALL_STACK)
  WhereTerm aStatic[1];    /* Initial static space for a[] */
#else
  WhereTerm aStatic[8];    /* Initial static space for a[] */
#endif
};

/*
** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
** a dynamically allocated instance of the following structure.
*/
struct WhereOrInfo {
  WhereClause wc;          /* Decomposition into subterms */
  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
};

/*
** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
** a dynamically allocated instance of the following structure.
*/
struct WhereAndInfo {
  WhereClause wc;          /* The subexpression broken out */
};

/*
** An instance of the following structure keeps track of a mapping
** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
**
** The VDBE cursor numbers are small integers contained in 
** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
** clause, the cursor numbers might not begin with 0 and they might
** contain gaps in the numbering sequence.  But we want to make maximum
** use of the bits in our bitmasks.  This structure provides a mapping
** from the sparse cursor numbers into consecutive integers beginning
** with 0.
**
** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
**
** For example, if the WHERE clause expression used these VDBE
** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
** would map those cursor numbers into bits 0 through 5.
**
** Note that the mapping is not necessarily ordered.  In the example
** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
** 57->5, 73->4.  Or one of 719 other combinations might be used. It
** does not really matter.  What is important is that sparse cursor
** numbers all get mapped into bit numbers that begin with 0 and contain
** no gaps.
*/
struct WhereMaskSet {
  int n;                        /* Number of assigned cursor values */
  int ix[BMS];                  /* Cursor assigned to each bit */
};

/*
** A WhereCost object records a lookup strategy and the estimated
** cost of pursuing that strategy.
*/
struct WhereCost {
  WherePlan plan;    /* The lookup strategy */
  double rCost;      /* Overall cost of pursuing this search strategy */
  double nRow;       /* Estimated number of output rows */
  Bitmask used;      /* Bitmask of cursors used by this plan */
};

/*
** Bitmasks for the operators that indices are able to exploit.  An
** OR-ed combination of these values can be used when searching for
** terms in the where clause.
*/
#define WO_IN     0x001
#define WO_EQ     0x002
#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
#define WO_MATCH  0x040
#define WO_ISNULL 0x080
#define WO_OR     0x100       /* Two or more OR-connected terms */
#define WO_AND    0x200       /* Two or more AND-connected terms */

#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */

/*
** Value for wsFlags returned by bestIndex() and stored in
** WhereLevel.wsFlags.  These flags determine which search
** strategies are appropriate.
**
** The least significant 12 bits is reserved as a mask for WO_ values above.
** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
** But if the table is the right table of a left join, WhereLevel.wsFlags
** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
** the "op" parameter to findTerm when we are resolving equality constraints.
** ISNULL constraints will then not be used on the right table of a left
** join.  Tickets #2177 and #2189.
*/
#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */

/*
** Initialize a preallocated WhereClause structure.
*/
static void whereClauseInit(
  WhereClause *pWC,        /* The WhereClause to be initialized */
  Parse *pParse,           /* The parsing context */
  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
){
  pWC->pParse = pParse;
  pWC->pMaskSet = pMaskSet;
  pWC->nTerm = 0;
  pWC->nSlot = ArraySize(pWC->aStatic);
  pWC->a = pWC->aStatic;
  pWC->vmask = 0;
}

/* Forward reference */
static void whereClauseClear(WhereClause*);

/*
** Deallocate all memory associated with a WhereOrInfo object.
*/
static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  whereClauseClear(&p->wc);
  sqlite3DbFree(db, p);
}

/*
** Deallocate all memory associated with a WhereAndInfo object.
*/
static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  whereClauseClear(&p->wc);
  sqlite3DbFree(db, p);
}

/*
** Deallocate a WhereClause structure.  The WhereClause structure
** itself is not freed.  This routine is the inverse of whereClauseInit().
*/
static void whereClauseClear(WhereClause *pWC){
  int i;
  WhereTerm *a;
  sqlite3 *db = pWC->pParse->db;
  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
    if( a->wtFlags & TERM_DYNAMIC ){
      sqlite3ExprDelete(db, a->pExpr);
    }
    if( a->wtFlags & TERM_ORINFO ){
      whereOrInfoDelete(db, a->u.pOrInfo);
    }else if( a->wtFlags & TERM_ANDINFO ){
      whereAndInfoDelete(db, a->u.pAndInfo);
    }
  }
  if( pWC->a!=pWC->aStatic ){
    sqlite3DbFree(db, pWC->a);
  }
}

/*
** Add a single new WhereTerm entry to the WhereClause object pWC.
** The new WhereTerm object is constructed from Expr p and with wtFlags.
** The index in pWC->a[] of the new WhereTerm is returned on success.
** 0 is returned if the new WhereTerm could not be added due to a memory
** allocation error.  The memory allocation failure will be recorded in
** the db->mallocFailed flag so that higher-level functions can detect it.
**
** This routine will increase the size of the pWC->a[] array as necessary.
**
** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
** for freeing the expression p is assumed by the WhereClause object pWC.
** This is true even if this routine fails to allocate a new WhereTerm.
**
** WARNING:  This routine might reallocate the space used to store
** WhereTerms.  All pointers to WhereTerms should be invalidated after
** calling this routine.  Such pointers may be reinitialized by referencing
** the pWC->a[] array.
*/
static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  WhereTerm *pTerm;
  int idx;
  if( pWC->nTerm>=pWC->nSlot ){
    WhereTerm *pOld = pWC->a;
    sqlite3 *db = pWC->pParse->db;
    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
    if( pWC->a==0 ){
      if( wtFlags & TERM_DYNAMIC ){
        sqlite3ExprDelete(db, p);
      }
      pWC->a = pOld;
      return 0;
    }
    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
    if( pOld!=pWC->aStatic ){
      sqlite3DbFree(db, pOld);
    }
    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  }
  pTerm = &pWC->a[idx = pWC->nTerm++];
  pTerm->pExpr = p;
  pTerm->wtFlags = wtFlags;
  pTerm->pWC = pWC;
  pTerm->iParent = -1;
  return idx;
}

/*
** This routine identifies subexpressions in the WHERE clause where
** each subexpression is separated by the AND operator or some other
** operator specified in the op parameter.  The WhereClause structure
** is filled with pointers to subexpressions.  For example:
**
**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
**           \________/     \_______________/     \________________/
**            slot[0]            slot[1]               slot[2]
**
** The original WHERE clause in pExpr is unaltered.  All this routine
** does is make slot[] entries point to substructure within pExpr.
**
** In the previous sentence and in the diagram, "slot[]" refers to
** the WhereClause.a[] array.  The slot[] array grows as needed to contain
** all terms of the WHERE clause.
*/
static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  pWC->op = (u8)op;
  if( pExpr==0 ) return;
  if( pExpr->op!=op ){
    whereClauseInsert(pWC, pExpr, 0);
  }else{
    whereSplit(pWC, pExpr->pLeft, op);
    whereSplit(pWC, pExpr->pRight, op);
  }
}

/*
** Initialize an expression mask set (a WhereMaskSet object)
*/
#define initMaskSet(P)  memset(P, 0, sizeof(*P))

/*
** Return the bitmask for the given cursor number.  Return 0 if
** iCursor is not in the set.
*/
static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  int i;
  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
  for(i=0; i<pMaskSet->n; i++){
    if( pMaskSet->ix[i]==iCursor ){
      return ((Bitmask)1)<<i;
    }
  }
  return 0;
}

/*
** Create a new mask for cursor iCursor.
**
** There is one cursor per table in the FROM clause.  The number of
** tables in the FROM clause is limited by a test early in the
** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
** array will never overflow.
*/
static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  pMaskSet->ix[pMaskSet->n++] = iCursor;
}

/*
** This routine walks (recursively) an expression tree and generates
** a bitmask indicating which tables are used in that expression
** tree.
**
** In order for this routine to work, the calling function must have
** previously invoked sqlite3ResolveExprNames() on the expression.  See
** the header comment on that routine for additional information.
** The sqlite3ResolveExprNames() routines looks for column names and
** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
** the VDBE cursor number of the table.  This routine just has to
** translate the cursor numbers into bitmask values and OR all
** the bitmasks together.
*/
static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  Bitmask mask = 0;
  if( p==0 ) return 0;
  if( p->op==TK_COLUMN ){
    mask = getMask(pMaskSet, p->iTable);
    return mask;
  }
  mask = exprTableUsage(pMaskSet, p->pRight);
  mask |= exprTableUsage(pMaskSet, p->pLeft);
  if( ExprHasProperty(p, EP_xIsSelect) ){
    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  }else{
    mask |= exprListTableUsage(pMaskSet, p->x.pList);
  }
  return mask;
}
static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  int i;
  Bitmask mask = 0;
  if( pList ){
    for(i=0; i<pList->nExpr; i++){
      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
    }
  }
  return mask;
}
static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  Bitmask mask = 0;
  while( pS ){
    mask |= exprListTableUsage(pMaskSet, pS->pEList);
    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
    mask |= exprTableUsage(pMaskSet, pS->pWhere);
    mask |= exprTableUsage(pMaskSet, pS->pHaving);
    pS = pS->pPrior;
  }
  return mask;
}

/*
** Return TRUE if the given operator is one of the operators that is
** allowed for an indexable WHERE clause term.  The allowed operators are
** "=", "<", ">", "<=", ">=", and "IN".
*/
static int allowedOp(int op){
  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  assert( TK_GE==TK_EQ+4 );
  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
}

/*
** Swap two objects of type TYPE.
*/
#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}

/*
** Commute a comparison operator.  Expressions of the form "X op Y"
** are converted into "Y op X".
**
** If a collation sequence is associated with either the left or right
** side of the comparison, it remains associated with the same side after
** the commutation. So "Y collate NOCASE op X" becomes 
** "X collate NOCASE op Y". This is because any collation sequence on
** the left hand side of a comparison overrides any collation sequence 
** attached to the right. For the same reason the EP_ExpCollate flag
** is not commuted.
*/
static void exprCommute(Parse *pParse, Expr *pExpr){
  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  if( pExpr->op>=TK_GT ){
    assert( TK_LT==TK_GT+2 );
    assert( TK_GE==TK_LE+2 );
    assert( TK_GT>TK_EQ );
    assert( TK_GT<TK_LE );
    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  }
}

/*
** Translate from TK_xx operator to WO_xx bitmask.
*/
static u16 operatorMask(int op){
  u16 c;
  assert( allowedOp(op) );
  if( op==TK_IN ){
    c = WO_IN;
  }else if( op==TK_ISNULL ){
    c = WO_ISNULL;
  }else{
    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
    c = (u16)(WO_EQ<<(op-TK_EQ));
  }
  assert( op!=TK_ISNULL || c==WO_ISNULL );
  assert( op!=TK_IN || c==WO_IN );
  assert( op!=TK_EQ || c==WO_EQ );
  assert( op!=TK_LT || c==WO_LT );
  assert( op!=TK_LE || c==WO_LE );
  assert( op!=TK_GT || c==WO_GT );
  assert( op!=TK_GE || c==WO_GE );
  return c;
}

/*
** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
** where X is a reference to the iColumn of table iCur and <op> is one of
** the WO_xx operator codes specified by the op parameter.
** Return a pointer to the term.  Return 0 if not found.
*/
static WhereTerm *findTerm(
  WhereClause *pWC,     /* The WHERE clause to be searched */
  int iCur,             /* Cursor number of LHS */
  int iColumn,          /* Column number of LHS */
  Bitmask notReady,     /* RHS must not overlap with this mask */
  u32 op,               /* Mask of WO_xx values describing operator */
  Index *pIdx           /* Must be compatible with this index, if not NULL */
){
  WhereTerm *pTerm;
  int k;
  assert( iCur>=0 );
  op &= WO_ALL;
  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
    if( pTerm->leftCursor==iCur
       && (pTerm->prereqRight & notReady)==0
       && pTerm->u.leftColumn==iColumn
       && (pTerm->eOperator & op)!=0
    ){
      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
        Expr *pX = pTerm->pExpr;
        CollSeq *pColl;
        char idxaff;
        int j;
        Parse *pParse = pWC->pParse;

        idxaff = pIdx->pTable->aCol[iColumn].affinity;
        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;

        /* Figure out the collation sequence required from an index for
        ** it to be useful for optimising expression pX. Store this
        ** value in variable pColl.
        */
        assert(pX->pLeft);
        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
        assert(pColl || pParse->nErr);

        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
          if( NEVER(j>=pIdx->nColumn) ) return 0;
        }
        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
      }
      return pTerm;
    }
  }
  return 0;
}

/* Forward reference */
static void exprAnalyze(SrcList*, WhereClause*, int);

/*
** Call exprAnalyze on all terms in a WHERE clause.  
**
**
*/
static void exprAnalyzeAll(
  SrcList *pTabList,       /* the FROM clause */
  WhereClause *pWC         /* the WHERE clause to be analyzed */
){
  int i;
  for(i=pWC->nTerm-1; i>=0; i--){
    exprAnalyze(pTabList, pWC, i);
  }
}

#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
/*
** Check to see if the given expression is a LIKE or GLOB operator that
** can be optimized using inequality constraints.  Return TRUE if it is
** so and false if not.
**
** In order for the operator to be optimizible, the RHS must be a string
** literal that does not begin with a wildcard.  
*/
static int isLikeOrGlob(
  Parse *pParse,    /* Parsing and code generating context */
  Expr *pExpr,      /* Test this expression */
  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
  int *pisComplete, /* True if the only wildcard is % in the last character */
  int *pnoCase      /* True if uppercase is equivalent to lowercase */
){
  const char *z = 0;         /* String on RHS of LIKE operator */
  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
  ExprList *pList;           /* List of operands to the LIKE operator */
  int c;                     /* One character in z[] */
  int cnt;                   /* Number of non-wildcard prefix characters */
  char wc[3];                /* Wildcard characters */
  CollSeq *pColl;            /* Collating sequence for LHS */
  sqlite3 *db = pParse->db;  /* Database connection */
  sqlite3_value *pVal = 0;
  int op;                    /* Opcode of pRight */

  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
    return 0;
  }
#ifdef SQLITE_EBCDIC
  if( *pnoCase ) return 0;
#endif
  pList = pExpr->x.pList;
  pLeft = pList->a[1].pExpr;
  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
    ** be the name of an indexed column with TEXT affinity. */
    return 0;
  }
  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  pColl = sqlite3ExprCollSeq(pParse, pLeft);
  assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
    ** default BINARY collating sequence.
    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
    ** is enabled then the column must use the default BINARY collating
    ** sequence, or if case_sensitive_like mode is disabled then the column
    ** must use the built-in NOCASE collating sequence.
    */
    return 0;
  }

  pRight = pList->a[0].pExpr;
  op = pRight->op;
  if( op==TK_REGISTER ){
    op = pRight->op2;
  }
  if( op==TK_VARIABLE ){
    Vdbe *pReprepare = pParse->pReprepare;
    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
      z = (char *)sqlite3_value_text(pVal);
    }
    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  }else if( op==TK_STRING ){
    z = pRight->u.zToken;
  }
  if( z ){
    cnt = 0;
    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
      cnt++;
    }
    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
      Expr *pPrefix;
      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
      pPrefix = sqlite3Expr(db, TK_STRING, z);
      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
      *ppPrefix = pPrefix;
      if( op==TK_VARIABLE ){
        Vdbe *v = pParse->pVdbe;
        sqlite3VdbeSetVarmask(v, pRight->iColumn);
        if( *pisComplete && pRight->u.zToken[1] ){
          /* If the rhs of the LIKE expression is a variable, and the current
          ** value of the variable means there is no need to invoke the LIKE
          ** function, then no OP_Variable will be added to the program.
          ** This causes problems for the sqlite3_bind_parameter_name()
          ** API. To workaround them, add a dummy OP_Variable here.
          */ 
          int r1 = sqlite3GetTempReg(pParse);
          sqlite3ExprCodeTarget(pParse, pRight, r1);
          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
          sqlite3ReleaseTempReg(pParse, r1);
        }
      }
    }else{
      z = 0;
    }
  }

  sqlite3ValueFree(pVal);
  return (z!=0);
}
#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */


#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Check to see if the given expression is of the form
**
**         column MATCH expr
**
** If it is then return TRUE.  If not, return FALSE.
*/
static int isMatchOfColumn(
  Expr *pExpr      /* Test this expression */
){
  ExprList *pList;

  if( pExpr->op!=TK_FUNCTION ){
    return 0;
  }
  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
    return 0;
  }
  pList = pExpr->x.pList;
  if( pList->nExpr!=2 ){
    return 0;
  }
  if( pList->a[1].pExpr->op != TK_COLUMN ){
    return 0;
  }
  return 1;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

/*
** If the pBase expression originated in the ON or USING clause of
** a join, then transfer the appropriate markings over to derived.
*/
static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  pDerived->flags |= pBase->flags & EP_FromJoin;
  pDerived->iRightJoinTable = pBase->iRightJoinTable;
}

#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
/*
** Analyze a term that consists of two or more OR-connected
** subterms.  So in:
**
**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
**                          ^^^^^^^^^^^^^^^^^^^^
**
** This routine analyzes terms such as the middle term in the above example.
** A WhereOrTerm object is computed and attached to the term under
** analysis, regardless of the outcome of the analysis.  Hence:
**
**     WhereTerm.wtFlags   |=  TERM_ORINFO
**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
**
** The term being analyzed must have two or more of OR-connected subterms.
** A single subterm might be a set of AND-connected sub-subterms.
** Examples of terms under analysis:
**
**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
**     (B)     x=expr1 OR expr2=x OR x=expr3
**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
**
** CASE 1:
**
** If all subterms are of the form T.C=expr for some single column of C
** a single table T (as shown in example B above) then create a new virtual
** term that is an equivalent IN expression.  In other words, if the term
** being analyzed is:
**
**      x = expr1  OR  expr2 = x  OR  x = expr3
**
** then create a new virtual term like this:
**
**      x IN (expr1,expr2,expr3)
**
** CASE 2:
**
** If all subterms are indexable by a single table T, then set
**
**     WhereTerm.eOperator              =  WO_OR
**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
**
** A subterm is "indexable" if it is of the form
** "T.C <op> <expr>" where C is any column of table T and 
** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
** A subterm is also indexable if it is an AND of two or more
** subsubterms at least one of which is indexable.  Indexable AND 
** subterms have their eOperator set to WO_AND and they have
** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
**
** From another point of view, "indexable" means that the subterm could
** potentially be used with an index if an appropriate index exists.
** This analysis does not consider whether or not the index exists; that
** is something the bestIndex() routine will determine.  This analysis
** only looks at whether subterms appropriate for indexing exist.
**
** All examples A through E above all satisfy case 2.  But if a term
** also statisfies case 1 (such as B) we know that the optimizer will
** always prefer case 1, so in that case we pretend that case 2 is not
** satisfied.
**
** It might be the case that multiple tables are indexable.  For example,
** (E) above is indexable on tables P, Q, and R.
**
** Terms that satisfy case 2 are candidates for lookup by using
** separate indices to find rowids for each subterm and composing
** the union of all rowids using a RowSet object.  This is similar
** to "bitmap indices" in other database engines.
**
** OTHERWISE:
**
** If neither case 1 nor case 2 apply, then leave the eOperator set to
** zero.  This term is not useful for search.
*/
static void exprAnalyzeOrTerm(
  SrcList *pSrc,            /* the FROM clause */
  WhereClause *pWC,         /* the complete WHERE clause */
  int idxTerm               /* Index of the OR-term to be analyzed */
){
  Parse *pParse = pWC->pParse;            /* Parser context */
  sqlite3 *db = pParse->db;               /* Database connection */
  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
  int i;                                  /* Loop counters */
  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */

  /*
  ** Break the OR clause into its separate subterms.  The subterms are
  ** stored in a WhereClause structure containing within the WhereOrInfo
  ** object that is attached to the original OR clause term.
  */
  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  assert( pExpr->op==TK_OR );
  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  if( pOrInfo==0 ) return;
  pTerm->wtFlags |= TERM_ORINFO;
  pOrWc = &pOrInfo->wc;
  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
  whereSplit(pOrWc, pExpr, TK_OR);
  exprAnalyzeAll(pSrc, pOrWc);
  if( db->mallocFailed ) return;
  assert( pOrWc->nTerm>=2 );

  /*
  ** Compute the set of tables that might satisfy cases 1 or 2.
  */
  indexable = ~(Bitmask)0;
  chngToIN = ~(pWC->vmask);
  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
      WhereAndInfo *pAndInfo;
      assert( pOrTerm->eOperator==0 );
      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
      chngToIN = 0;
      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
      if( pAndInfo ){
        WhereClause *pAndWC;
        WhereTerm *pAndTerm;
        int j;
        Bitmask b = 0;
        pOrTerm->u.pAndInfo = pAndInfo;
        pOrTerm->wtFlags |= TERM_ANDINFO;
        pOrTerm->eOperator = WO_AND;
        pAndWC = &pAndInfo->wc;
        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
        exprAnalyzeAll(pSrc, pAndWC);
        testcase( db->mallocFailed );
        if( !db->mallocFailed ){
          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
            assert( pAndTerm->pExpr );
            if( allowedOp(pAndTerm->pExpr->op) ){
              b |= getMask(pMaskSet, pAndTerm->leftCursor);
            }
          }
        }
        indexable &= b;
      }
    }else if( pOrTerm->wtFlags & TERM_COPIED ){
      /* Skip this term for now.  We revisit it when we process the
      ** corresponding TERM_VIRTUAL term */
    }else{
      Bitmask b;
      b = getMask(pMaskSet, pOrTerm->leftCursor);
      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
        b |= getMask(pMaskSet, pOther->leftCursor);
      }
      indexable &= b;
      if( pOrTerm->eOperator!=WO_EQ ){
        chngToIN = 0;
      }else{
        chngToIN &= b;
      }
    }
  }

  /*
  ** Record the set of tables that satisfy case 2.  The set might be
  ** empty.
  */
  pOrInfo->indexable = indexable;
  pTerm->eOperator = indexable==0 ? 0 : WO_OR;

  /*
  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
  ** we have to do some additional checking to see if case 1 really
  ** is satisfied.
  **
  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
  ** that there is no possibility of transforming the OR clause into an
  ** IN operator because one or more terms in the OR clause contain
  ** something other than == on a column in the single table.  The 1-bit
  ** case means that every term of the OR clause is of the form
  ** "table.column=expr" for some single table.  The one bit that is set
  ** will correspond to the common table.  We still need to check to make
  ** sure the same column is used on all terms.  The 2-bit case is when
  ** the all terms are of the form "table1.column=table2.column".  It
  ** might be possible to form an IN operator with either table1.column
  ** or table2.column as the LHS if either is common to every term of
  ** the OR clause.
  **
  ** Note that terms of the form "table.column1=table.column2" (the
  ** same table on both sizes of the ==) cannot be optimized.
  */
  if( chngToIN ){
    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
    int iColumn = -1;         /* Column index on lhs of IN operator */
    int iCursor = -1;         /* Table cursor common to all terms */
    int j = 0;                /* Loop counter */

    /* Search for a table and column that appears on one side or the
    ** other of the == operator in every subterm.  That table and column
    ** will be recorded in iCursor and iColumn.  There might not be any
    ** such table and column.  Set okToChngToIN if an appropriate table
    ** and column is found but leave okToChngToIN false if not found.
    */
    for(j=0; j<2 && !okToChngToIN; j++){
      pOrTerm = pOrWc->a;
      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
        assert( pOrTerm->eOperator==WO_EQ );
        pOrTerm->wtFlags &= ~TERM_OR_OK;
        if( pOrTerm->leftCursor==iCursor ){
          /* This is the 2-bit case and we are on the second iteration and
          ** current term is from the first iteration.  So skip this term. */
          assert( j==1 );
          continue;
        }
        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
          /* This term must be of the form t1.a==t2.b where t2 is in the
          ** chngToIN set but t1 is not.  This term will be either preceeded
          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
          ** and use its inversion. */
          testcase( pOrTerm->wtFlags & TERM_COPIED );
          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
          continue;
        }
        iColumn = pOrTerm->u.leftColumn;
        iCursor = pOrTerm->leftCursor;
        break;
      }
      if( i<0 ){
        /* No candidate table+column was found.  This can only occur
        ** on the second iteration */
        assert( j==1 );
        assert( (chngToIN&(chngToIN-1))==0 );
        assert( chngToIN==getMask(pMaskSet, iCursor) );
        break;
      }
      testcase( j==1 );

      /* We have found a candidate table and column.  Check to see if that
      ** table and column is common to every term in the OR clause */
      okToChngToIN = 1;
      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
        assert( pOrTerm->eOperator==WO_EQ );
        if( pOrTerm->leftCursor!=iCursor ){
          pOrTerm->wtFlags &= ~TERM_OR_OK;
        }else if( pOrTerm->u.leftColumn!=iColumn ){
          okToChngToIN = 0;
        }else{
          int affLeft, affRight;
          /* If the right-hand side is also a column, then the affinities
          ** of both right and left sides must be such that no type
          ** conversions are required on the right.  (Ticket #2249)
          */
          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
          if( affRight!=0 && affRight!=affLeft ){
            okToChngToIN = 0;
          }else{
            pOrTerm->wtFlags |= TERM_OR_OK;
          }
        }
      }
    }

    /* At this point, okToChngToIN is true if original pTerm satisfies
    ** case 1.  In that case, construct a new virtual term that is 
    ** pTerm converted into an IN operator.
    */
    if( okToChngToIN ){
      Expr *pDup;            /* A transient duplicate expression */
      ExprList *pList = 0;   /* The RHS of the IN operator */
      Expr *pLeft = 0;       /* The LHS of the IN operator */
      Expr *pNew;            /* The complete IN operator */

      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
        assert( pOrTerm->eOperator==WO_EQ );
        assert( pOrTerm->leftCursor==iCursor );
        assert( pOrTerm->u.leftColumn==iColumn );
        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
        pLeft = pOrTerm->pExpr->pLeft;
      }
      assert( pLeft!=0 );
      pDup = sqlite3ExprDup(db, pLeft, 0);
      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
      if( pNew ){
        int idxNew;
        transferJoinMarkings(pNew, pExpr);
        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
        pNew->x.pList = pList;
        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
        testcase( idxNew==0 );
        exprAnalyze(pSrc, pWC, idxNew);
        pTerm = &pWC->a[idxTerm];
        pWC->a[idxNew].iParent = idxTerm;
        pTerm->nChild = 1;
      }else{
        sqlite3ExprListDelete(db, pList);
      }
      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
    }
  }
}
#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */


/*
** The input to this routine is an WhereTerm structure with only the
** "pExpr" field filled in.  The job of this routine is to analyze the
** subexpression and populate all the other fields of the WhereTerm
** structure.
**
** If the expression is of the form "<expr> <op> X" it gets commuted
** to the standard form of "X <op> <expr>".
**
** If the expression is of the form "X <op> Y" where both X and Y are
** columns, then the original expression is unchanged and a new virtual
** term of the form "Y <op> X" is added to the WHERE clause and
** analyzed separately.  The original term is marked with TERM_COPIED
** and the new term is marked with TERM_DYNAMIC (because it's pExpr
** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
** is a commuted copy of a prior term.)  The original term has nChild=1
** and the copy has idxParent set to the index of the original term.
*/
static void exprAnalyze(
  SrcList *pSrc,            /* the FROM clause */
  WhereClause *pWC,         /* the WHERE clause */
  int idxTerm               /* Index of the term to be analyzed */
){
  WhereTerm *pTerm;                /* The term to be analyzed */
  WhereMaskSet *pMaskSet;          /* Set of table index masks */
  Expr *pExpr;                     /* The expression to be analyzed */
  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
  Bitmask prereqAll;               /* Prerequesites of pExpr */
  Bitmask extraRight = 0;          /* */
  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
  int op;                          /* Top-level operator.  pExpr->op */
  Parse *pParse = pWC->pParse;     /* Parsing context */
  sqlite3 *db = pParse->db;        /* Database connection */

  if( db->mallocFailed ){
    return;
  }
  pTerm = &pWC->a[idxTerm];
  pMaskSet = pWC->pMaskSet;
  pExpr = pTerm->pExpr;
  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  op = pExpr->op;
  if( op==TK_IN ){
    assert( pExpr->pRight==0 );
    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
    }else{
      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
    }
  }else if( op==TK_ISNULL ){
    pTerm->prereqRight = 0;
  }else{
    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  }
  prereqAll = exprTableUsage(pMaskSet, pExpr);
  if( ExprHasProperty(pExpr, EP_FromJoin) ){
    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
    prereqAll |= x;
    extraRight = x-1;  /* ON clause terms may not be used with an index
                       ** on left table of a LEFT JOIN.  Ticket #3015 */
  }
  pTerm->prereqAll = prereqAll;
  pTerm->leftCursor = -1;
  pTerm->iParent = -1;
  pTerm->eOperator = 0;
  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
    Expr *pLeft = pExpr->pLeft;
    Expr *pRight = pExpr->pRight;
    if( pLeft->op==TK_COLUMN ){
      pTerm->leftCursor = pLeft->iTable;
      pTerm->u.leftColumn = pLeft->iColumn;
      pTerm->eOperator = operatorMask(op);
    }
    if( pRight && pRight->op==TK_COLUMN ){
      WhereTerm *pNew;
      Expr *pDup;
      if( pTerm->leftCursor>=0 ){
        int idxNew;
        pDup = sqlite3ExprDup(db, pExpr, 0);
        if( db->mallocFailed ){
          sqlite3ExprDelete(db, pDup);
          return;
        }
        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
        if( idxNew==0 ) return;
        pNew = &pWC->a[idxNew];
        pNew->iParent = idxTerm;
        pTerm = &pWC->a[idxTerm];
        pTerm->nChild = 1;
        pTerm->wtFlags |= TERM_COPIED;
      }else{
        pDup = pExpr;
        pNew = pTerm;
      }
      exprCommute(pParse, pDup);
      pLeft = pDup->pLeft;
      pNew->leftCursor = pLeft->iTable;
      pNew->u.leftColumn = pLeft->iColumn;
      pNew->prereqRight = prereqLeft;
      pNew->prereqAll = prereqAll;
      pNew->eOperator = operatorMask(pDup->op);
    }
  }

#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  /* If a term is the BETWEEN operator, create two new virtual terms
  ** that define the range that the BETWEEN implements.  For example:
  **
  **      a BETWEEN b AND c
  **
  ** is converted into:
  **
  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  **
  ** The two new terms are added onto the end of the WhereClause object.
  ** The new terms are "dynamic" and are children of the original BETWEEN
  ** term.  That means that if the BETWEEN term is coded, the children are
  ** skipped.  Or, if the children are satisfied by an index, the original
  ** BETWEEN term is skipped.
  */
  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
    ExprList *pList = pExpr->x.pList;
    int i;
    static const u8 ops[] = {TK_GE, TK_LE};
    assert( pList!=0 );
    assert( pList->nExpr==2 );
    for(i=0; i<2; i++){
      Expr *pNewExpr;
      int idxNew;
      pNewExpr = sqlite3PExpr(pParse, ops[i], 
                             sqlite3ExprDup(db, pExpr->pLeft, 0),
                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
      testcase( idxNew==0 );
      exprAnalyze(pSrc, pWC, idxNew);
      pTerm = &pWC->a[idxTerm];
      pWC->a[idxNew].iParent = idxTerm;
    }
    pTerm->nChild = 2;
  }
#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */

#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  /* Analyze a term that is composed of two or more subterms connected by
  ** an OR operator.
  */
  else if( pExpr->op==TK_OR ){
    assert( pWC->op==TK_AND );
    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
    pTerm = &pWC->a[idxTerm];
  }
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */

#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  /* Add constraints to reduce the search space on a LIKE or GLOB
  ** operator.
  **
  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  **
  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
  **
  ** The last character of the prefix "abc" is incremented to form the
  ** termination condition "abd".
  */
  if( pWC->op==TK_AND 
   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  ){
    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
    Expr *pNewExpr1;
    Expr *pNewExpr2;
    int idxNew1;
    int idxNew2;

    pLeft = pExpr->x.pList->a[1].pExpr;
    pStr2 = sqlite3ExprDup(db, pStr1, 0);
    if( !db->mallocFailed ){
      u8 c, *pC;       /* Last character before the first wildcard */
      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
      c = *pC;
      if( noCase ){
        /* The point is to increment the last character before the first
        ** wildcard.  But if we increment '@', that will push it into the
        ** alphabetic range where case conversions will mess up the 
        ** inequality.  To avoid this, make sure to also run the full
        ** LIKE on all candidate expressions by clearing the isComplete flag
        */
        if( c=='A'-1 ) isComplete = 0;

        c = sqlite3UpperToLower[c];
      }
      *pC = c + 1;
    }
    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
    testcase( idxNew1==0 );
    exprAnalyze(pSrc, pWC, idxNew1);
    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
    testcase( idxNew2==0 );
    exprAnalyze(pSrc, pWC, idxNew2);
    pTerm = &pWC->a[idxTerm];
    if( isComplete ){
      pWC->a[idxNew1].iParent = idxTerm;
      pWC->a[idxNew2].iParent = idxTerm;
      pTerm->nChild = 2;
    }
  }
#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */

#ifndef SQLITE_OMIT_VIRTUALTABLE
  /* Add a WO_MATCH auxiliary term to the constraint set if the
  ** current expression is of the form:  column MATCH expr.
  ** This information is used by the xBestIndex methods of
  ** virtual tables.  The native query optimizer does not attempt
  ** to do anything with MATCH functions.
  */
  if( isMatchOfColumn(pExpr) ){
    int idxNew;
    Expr *pRight, *pLeft;
    WhereTerm *pNewTerm;
    Bitmask prereqColumn, prereqExpr;

    pRight = pExpr->x.pList->a[0].pExpr;
    pLeft = pExpr->x.pList->a[1].pExpr;
    prereqExpr = exprTableUsage(pMaskSet, pRight);
    prereqColumn = exprTableUsage(pMaskSet, pLeft);
    if( (prereqExpr & prereqColumn)==0 ){
      Expr *pNewExpr;
      pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
                              0, sqlite3ExprDup(db, pRight, 0), 0);
      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
      testcase( idxNew==0 );
      pNewTerm = &pWC->a[idxNew];
      pNewTerm->prereqRight = prereqExpr;
      pNewTerm->leftCursor = pLeft->iTable;
      pNewTerm->u.leftColumn = pLeft->iColumn;
      pNewTerm->eOperator = WO_MATCH;
      pNewTerm->iParent = idxTerm;
      pTerm = &pWC->a[idxTerm];
      pTerm->nChild = 1;
      pTerm->wtFlags |= TERM_COPIED;
      pNewTerm->prereqAll = pTerm->prereqAll;
    }
  }
#endif /* SQLITE_OMIT_VIRTUALTABLE */

  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  ** an index for tables to the left of the join.
  */
  pTerm->prereqRight |= extraRight;
}

/*
** Return TRUE if any of the expressions in pList->a[iFirst...] contain
** a reference to any table other than the iBase table.
*/
static int referencesOtherTables(
  ExprList *pList,          /* Search expressions in ths list */
  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
  int iFirst,               /* Be searching with the iFirst-th expression */
  int iBase                 /* Ignore references to this table */
){
  Bitmask allowed = ~getMask(pMaskSet, iBase);
  while( iFirst<pList->nExpr ){
    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
      return 1;
    }
  }
  return 0;
}


/*
** This routine decides if pIdx can be used to satisfy the ORDER BY
** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
** ORDER BY clause, this routine returns 0.
**
** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
** left-most table in the FROM clause of that same SELECT statement and
** the table has a cursor number of "base".  pIdx is an index on pTab.
**
** nEqCol is the number of columns of pIdx that are used as equality
** constraints.  Any of these columns may be missing from the ORDER BY
** clause and the match can still be a success.
**
** All terms of the ORDER BY that match against the index must be either
** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
** index do not need to satisfy this constraint.)  The *pbRev value is
** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
** the ORDER BY clause is all ASC.
*/
static int isSortingIndex(
  Parse *pParse,          /* Parsing context */
  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
  Index *pIdx,            /* The index we are testing */
  int base,               /* Cursor number for the table to be sorted */
  ExprList *pOrderBy,     /* The ORDER BY clause */
  int nEqCol,             /* Number of index columns with == constraints */
  int *pbRev              /* Set to 1 if ORDER BY is DESC */
){
  int i, j;                       /* Loop counters */
  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
  int nTerm;                      /* Number of ORDER BY terms */
  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
  sqlite3 *db = pParse->db;

  assert( pOrderBy!=0 );
  nTerm = pOrderBy->nExpr;
  assert( nTerm>0 );

  /* Argument pIdx must either point to a 'real' named index structure, 
  ** or an index structure allocated on the stack by bestBtreeIndex() to
  ** represent the rowid index that is part of every table.  */
  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );

  /* Match terms of the ORDER BY clause against columns of
  ** the index.
  **
  ** Note that indices have pIdx->nColumn regular columns plus
  ** one additional column containing the rowid.  The rowid column
  ** of the index is also allowed to match against the ORDER BY
  ** clause.
  */
  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
    CollSeq *pColl;    /* The collating sequence of pExpr */
    int termSortOrder; /* Sort order for this term */
    int iColumn;       /* The i-th column of the index.  -1 for rowid */
    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
    const char *zColl; /* Name of the collating sequence for i-th index term */

    pExpr = pTerm->pExpr;
    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
      /* Can not use an index sort on anything that is not a column in the
      ** left-most table of the FROM clause */
      break;
    }
    pColl = sqlite3ExprCollSeq(pParse, pExpr);
    if( !pColl ){
      pColl = db->pDfltColl;
    }
    if( pIdx->zName && i<pIdx->nColumn ){
      iColumn = pIdx->aiColumn[i];
      if( iColumn==pIdx->pTable->iPKey ){
        iColumn = -1;
      }
      iSortOrder = pIdx->aSortOrder[i];
      zColl = pIdx->azColl[i];
    }else{
      iColumn = -1;
      iSortOrder = 0;
      zColl = pColl->zName;
    }
    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
      /* Term j of the ORDER BY clause does not match column i of the index */
      if( i<nEqCol ){
        /* If an index column that is constrained by == fails to match an
        ** ORDER BY term, that is OK.  Just ignore that column of the index
        */
        continue;
      }else if( i==pIdx->nColumn ){
        /* Index column i is the rowid.  All other terms match. */
        break;
      }else{
        /* If an index column fails to match and is not constrained by ==
        ** then the index cannot satisfy the ORDER BY constraint.
        */
        return 0;
      }
    }
    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
    assert( iSortOrder==0 || iSortOrder==1 );
    termSortOrder = iSortOrder ^ pTerm->sortOrder;
    if( i>nEqCol ){
      if( termSortOrder!=sortOrder ){
        /* Indices can only be used if all ORDER BY terms past the
        ** equality constraints are all either DESC or ASC. */
        return 0;
      }
    }else{
      sortOrder = termSortOrder;
    }
    j++;
    pTerm++;
    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
      /* If the indexed column is the primary key and everything matches
      ** so far and none of the ORDER BY terms to the right reference other
      ** tables in the join, then we are assured that the index can be used 
      ** to sort because the primary key is unique and so none of the other
      ** columns will make any difference
      */
      j = nTerm;
    }
  }

  *pbRev = sortOrder!=0;
  if( j>=nTerm ){
    /* All terms of the ORDER BY clause are covered by this index so
    ** this index can be used for sorting. */
    return 1;
  }
  if( pIdx->onError!=OE_None && i==pIdx->nColumn
      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
    /* All terms of this index match some prefix of the ORDER BY clause
    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
    ** clause reference other tables in a join.  If this is all true then
    ** the order by clause is superfluous. */
    return 1;
  }
  return 0;
}

/*
** Prepare a crude estimate of the logarithm of the input value.
** The results need not be exact.  This is only used for estimating
** the total cost of performing operations with O(logN) or O(NlogN)
** complexity.  Because N is just a guess, it is no great tragedy if
** logN is a little off.
*/
static double estLog(double N){
  double logN = 1;
  double x = 10;
  while( N>x ){
    logN += 1;
    x *= 10;
  }
  return logN;
}

/*
** Two routines for printing the content of an sqlite3_index_info
** structure.  Used for testing and debugging only.  If neither
** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
** are no-ops.
*/
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  int i;
  if( !sqlite3WhereTrace ) return;
  for(i=0; i<p->nConstraint; i++){
    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
       i,
       p->aConstraint[i].iColumn,
       p->aConstraint[i].iTermOffset,
       p->aConstraint[i].op,
       p->aConstraint[i].usable);
  }
  for(i=0; i<p->nOrderBy; i++){
    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
       i,
       p->aOrderBy[i].iColumn,
       p->aOrderBy[i].desc);
  }
}
static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  int i;
  if( !sqlite3WhereTrace ) return;
  for(i=0; i<p->nConstraint; i++){
    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
       i,
       p->aConstraintUsage[i].argvIndex,
       p->aConstraintUsage[i].omit);
  }
  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
}
#else
#define TRACE_IDX_INPUTS(A)
#define TRACE_IDX_OUTPUTS(A)
#endif

/* 
** Required because bestIndex() is called by bestOrClauseIndex() 
*/
static void bestIndex(
    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);

/*
** This routine attempts to find an scanning strategy that can be used 
** to optimize an 'OR' expression that is part of a WHERE clause. 
**
** The table associated with FROM clause term pSrc may be either a
** regular B-Tree table or a virtual table.
*/
static void bestOrClauseIndex(
  Parse *pParse,              /* The parsing context */
  WhereClause *pWC,           /* The WHERE clause */
  struct SrcList_item *pSrc,  /* The FROM clause term to search */
  Bitmask notReady,           /* Mask of cursors that are not available */
  ExprList *pOrderBy,         /* The ORDER BY clause */
  WhereCost *pCost            /* Lowest cost query plan */
){
#ifndef SQLITE_OMIT_OR_OPTIMIZATION
  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
  WhereTerm *pTerm;                 /* A single term of the WHERE clause */

  /* Search the WHERE clause terms for a usable WO_OR term. */
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
    if( pTerm->eOperator==WO_OR 
     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
    ){
      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
      WhereTerm *pOrTerm;
      int flags = WHERE_MULTI_OR;
      double rTotal = 0;
      double nRow = 0;
      Bitmask used = 0;

      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
        WhereCost sTermCost;
        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
        ));
        if( pOrTerm->eOperator==WO_AND ){
          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
        }else if( pOrTerm->leftCursor==iCur ){
          WhereClause tempWC;
          tempWC.pParse = pWC->pParse;
          tempWC.pMaskSet = pWC->pMaskSet;
          tempWC.op = TK_AND;
          tempWC.a = pOrTerm;
          tempWC.nTerm = 1;
          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
        }else{
          continue;
        }
        rTotal += sTermCost.rCost;
        nRow += sTermCost.nRow;
        used |= sTermCost.used;
        if( rTotal>=pCost->rCost ) break;
      }

      /* If there is an ORDER BY clause, increase the scan cost to account 
      ** for the cost of the sort. */
      if( pOrderBy!=0 ){
        rTotal += nRow*estLog(nRow);
        WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
      }

      /* If the cost of scanning using this OR term for optimization is
      ** less than the current cost stored in pCost, replace the contents
      ** of pCost. */
      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
      if( rTotal<pCost->rCost ){
        pCost->rCost = rTotal;
        pCost->nRow = nRow;
        pCost->used = used;
        pCost->plan.wsFlags = flags;
        pCost->plan.u.pTerm = pTerm;
      }
    }
  }
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
}

#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Allocate and populate an sqlite3_index_info structure. It is the 
** responsibility of the caller to eventually release the structure
** by passing the pointer returned by this function to sqlite3_free().
*/
static sqlite3_index_info *allocateIndexInfo(
  Parse *pParse, 
  WhereClause *pWC,
  struct SrcList_item *pSrc,
  ExprList *pOrderBy
){
  int i, j;
  int nTerm;
  struct sqlite3_index_constraint *pIdxCons;
  struct sqlite3_index_orderby *pIdxOrderBy;
  struct sqlite3_index_constraint_usage *pUsage;
  WhereTerm *pTerm;
  int nOrderBy;
  sqlite3_index_info *pIdxInfo;

  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));

  /* Count the number of possible WHERE clause constraints referring
  ** to this virtual table */
  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
    if( pTerm->leftCursor != pSrc->iCursor ) continue;
    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
    testcase( pTerm->eOperator==WO_IN );
    testcase( pTerm->eOperator==WO_ISNULL );
    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
    nTerm++;
  }

  /* If the ORDER BY clause contains only columns in the current 
  ** virtual table then allocate space for the aOrderBy part of
  ** the sqlite3_index_info structure.
  */
  nOrderBy = 0;
  if( pOrderBy ){
    for(i=0; i<pOrderBy->nExpr; i++){
      Expr *pExpr = pOrderBy->a[i].pExpr;
      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
    }
    if( i==pOrderBy->nExpr ){
      nOrderBy = pOrderBy->nExpr;
    }
  }

  /* Allocate the sqlite3_index_info structure
  */
  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
                           + sizeof(*pIdxOrderBy)*nOrderBy );
  if( pIdxInfo==0 ){
    sqlite3ErrorMsg(pParse, "out of memory");
    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
    return 0;
  }

  /* Initialize the structure.  The sqlite3_index_info structure contains
  ** many fields that are declared "const" to prevent xBestIndex from
  ** changing them.  We have to do some funky casting in order to
  ** initialize those fields.
  */
  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  *(int*)&pIdxInfo->nConstraint = nTerm;
  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
                                                                   pUsage;

  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
    if( pTerm->leftCursor != pSrc->iCursor ) continue;
    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
    testcase( pTerm->eOperator==WO_IN );
    testcase( pTerm->eOperator==WO_ISNULL );
    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
    pIdxCons[j].iColumn = pTerm->u.leftColumn;
    pIdxCons[j].iTermOffset = i;
    pIdxCons[j].op = (u8)pTerm->eOperator;
    /* The direct assignment in the previous line is possible only because
    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
    ** following asserts verify this fact. */
    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
    j++;
  }
  for(i=0; i<nOrderBy; i++){
    Expr *pExpr = pOrderBy->a[i].pExpr;
    pIdxOrderBy[i].iColumn = pExpr->iColumn;
    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  }

  return pIdxInfo;
}

/*
** The table object reference passed as the second argument to this function
** must represent a virtual table. This function invokes the xBestIndex()
** method of the virtual table with the sqlite3_index_info pointer passed
** as the argument.
**
** If an error occurs, pParse is populated with an error message and a
** non-zero value is returned. Otherwise, 0 is returned and the output
** part of the sqlite3_index_info structure is left populated.
**
** Whether or not an error is returned, it is the responsibility of the
** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
** that this is required.
*/
static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  int i;
  int rc;

  (void)sqlite3SafetyOff(pParse->db);
  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  TRACE_IDX_INPUTS(p);
  rc = pVtab->pModule->xBestIndex(pVtab, p);
  TRACE_IDX_OUTPUTS(p);
  (void)sqlite3SafetyOn(pParse->db);

  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ){
      pParse->db->mallocFailed = 1;
    }else if( !pVtab->zErrMsg ){
      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
    }else{
      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
    }
  }
  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
  pVtab->zErrMsg = 0;

  for(i=0; i<p->nConstraint; i++){
    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
      sqlite3ErrorMsg(pParse, 
          "table %s: xBestIndex returned an invalid plan", pTab->zName);
    }
  }

  return pParse->nErr;
}


/*
** Compute the best index for a virtual table.
**
** The best index is computed by the xBestIndex method of the virtual
** table module.  This routine is really just a wrapper that sets up
** the sqlite3_index_info structure that is used to communicate with
** xBestIndex.
**
** In a join, this routine might be called multiple times for the
** same virtual table.  The sqlite3_index_info structure is created
** and initialized on the first invocation and reused on all subsequent
** invocations.  The sqlite3_index_info structure is also used when
** code is generated to access the virtual table.  The whereInfoDelete() 
** routine takes care of freeing the sqlite3_index_info structure after
** everybody has finished with it.
*/
static void bestVirtualIndex(
  Parse *pParse,                  /* The parsing context */
  WhereClause *pWC,               /* The WHERE clause */
  struct SrcList_item *pSrc,      /* The FROM clause term to search */
  Bitmask notReady,               /* Mask of cursors that are not available */
  ExprList *pOrderBy,             /* The order by clause */
  WhereCost *pCost,               /* Lowest cost query plan */
  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
){
  Table *pTab = pSrc->pTab;
  sqlite3_index_info *pIdxInfo;
  struct sqlite3_index_constraint *pIdxCons;
  struct sqlite3_index_constraint_usage *pUsage;
  WhereTerm *pTerm;
  int i, j;
  int nOrderBy;

  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
  ** malloc in allocateIndexInfo() fails and this function returns leaving
  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
  */
  memset(pCost, 0, sizeof(*pCost));
  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;

  /* If the sqlite3_index_info structure has not been previously
  ** allocated and initialized, then allocate and initialize it now.
  */
  pIdxInfo = *ppIdxInfo;
  if( pIdxInfo==0 ){
    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
  }
  if( pIdxInfo==0 ){
    return;
  }

  /* At this point, the sqlite3_index_info structure that pIdxInfo points
  ** to will have been initialized, either during the current invocation or
  ** during some prior invocation.  Now we just have to customize the
  ** details of pIdxInfo for the current invocation and pass it to
  ** xBestIndex.
  */

  /* The module name must be defined. Also, by this point there must
  ** be a pointer to an sqlite3_vtab structure. Otherwise
  ** sqlite3ViewGetColumnNames() would have picked up the error. 
  */
  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  assert( sqlite3GetVTable(pParse->db, pTab) );

  /* Set the aConstraint[].usable fields and initialize all 
  ** output variables to zero.
  **
  ** aConstraint[].usable is true for constraints where the right-hand
  ** side contains only references to tables to the left of the current
  ** table.  In other words, if the constraint is of the form:
  **
  **           column = expr
  **
  ** and we are evaluating a join, then the constraint on column is 
  ** only valid if all tables referenced in expr occur to the left
  ** of the table containing column.
  **
  ** The aConstraints[] array contains entries for all constraints
  ** on the current table.  That way we only have to compute it once
  ** even though we might try to pick the best index multiple times.
  ** For each attempt at picking an index, the order of tables in the
  ** join might be different so we have to recompute the usable flag
  ** each time.
  */
  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  pUsage = pIdxInfo->aConstraintUsage;
  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
    j = pIdxCons->iTermOffset;
    pTerm = &pWC->a[j];
    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
  }
  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  if( pIdxInfo->needToFreeIdxStr ){
    sqlite3_free(pIdxInfo->idxStr);
  }
  pIdxInfo->idxStr = 0;
  pIdxInfo->idxNum = 0;
  pIdxInfo->needToFreeIdxStr = 0;
  pIdxInfo->orderByConsumed = 0;
  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
  nOrderBy = pIdxInfo->nOrderBy;
  if( !pOrderBy ){
    pIdxInfo->nOrderBy = 0;
  }

  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
    return;
  }

  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  for(i=0; i<pIdxInfo->nConstraint; i++){
    if( pUsage[i].argvIndex>0 ){
      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
    }
  }

  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  ** inital value of lowestCost in this loop. If it is, then the
  ** (cost<lowestCost) test below will never be true.
  ** 
  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
  ** is defined.
  */
  if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
  }else{
    pCost->rCost = pIdxInfo->estimatedCost;
  }
  pCost->plan.u.pVtabIdx = pIdxInfo;
  if( pIdxInfo->orderByConsumed ){
    pCost->plan.wsFlags |= WHERE_ORDERBY;
  }
  pCost->plan.nEq = 0;
  pIdxInfo->nOrderBy = nOrderBy;

  /* Try to find a more efficient access pattern by using multiple indexes
  ** to optimize an OR expression within the WHERE clause. 
  */
  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

/*
** Argument pIdx is a pointer to an index structure that has an array of
** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
** stored in Index.aSample. The domain of values stored in said column
** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
** Region 0 contains all values smaller than the first sample value. Region
** 1 contains values larger than or equal to the value of the first sample,
** but smaller than the value of the second. And so on.
**
** If successful, this function determines which of the regions value 
** pVal lies in, sets *piRegion to the region index (a value between 0
** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
** Or, if an OOM occurs while converting text values between encodings,
** SQLITE_NOMEM is returned and *piRegion is undefined.
*/
#ifdef SQLITE_ENABLE_STAT2
static int whereRangeRegion(
  Parse *pParse,              /* Database connection */
  Index *pIdx,                /* Index to consider domain of */
  sqlite3_value *pVal,        /* Value to consider */
  int *piRegion               /* OUT: Region of domain in which value lies */
){
  if( ALWAYS(pVal) ){
    IndexSample *aSample = pIdx->aSample;
    int i = 0;
    int eType = sqlite3_value_type(pVal);

    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
      double r = sqlite3_value_double(pVal);
      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
        if( aSample[i].eType==SQLITE_NULL ) continue;
        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
      }
    }else{ 
      sqlite3 *db = pParse->db;
      CollSeq *pColl;
      const u8 *z;
      int n;

      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );

      if( eType==SQLITE_BLOB ){
        z = (const u8 *)sqlite3_value_blob(pVal);
        pColl = db->pDfltColl;
        assert( pColl->enc==SQLITE_UTF8 );
      }else{
        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
        if( pColl==0 ){
          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
                          *pIdx->azColl);
          return SQLITE_ERROR;
        }
        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
        if( !z ){
          return SQLITE_NOMEM;
        }
        assert( z && pColl && pColl->xCmp );
      }
      n = sqlite3ValueBytes(pVal, pColl->enc);

      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
        int r;
        int eSampletype = aSample[i].eType;
        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
        if( (eSampletype!=eType) ) break;
#ifndef SQLITE_OMIT_UTF16
        if( pColl->enc!=SQLITE_UTF8 ){
          int nSample;
          char *zSample = sqlite3Utf8to16(
              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
          );
          if( !zSample ){
            assert( db->mallocFailed );
            return SQLITE_NOMEM;
          }
          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
          sqlite3DbFree(db, zSample);
        }else
#endif
        {
          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
        }
        if( r>0 ) break;
      }
    }

    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
    *piRegion = i;
  }
  return SQLITE_OK;
}
#endif   /* #ifdef SQLITE_ENABLE_STAT2 */

/*
** If expression pExpr represents a literal value, set *pp to point to
** an sqlite3_value structure containing the same value, with affinity
** aff applied to it, before returning. It is the responsibility of the 
** caller to eventually release this structure by passing it to 
** sqlite3ValueFree().
**
** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
** is an SQL variable that currently has a non-NULL value bound to it,
** create an sqlite3_value structure containing this value, again with
** affinity aff applied to it, instead.
**
** If neither of the above apply, set *pp to NULL.
**
** If an error occurs, return an error code. Otherwise, SQLITE_OK.
*/
#ifdef SQLITE_ENABLE_STAT2
static int valueFromExpr(
  Parse *pParse, 
  Expr *pExpr, 
  u8 aff, 
  sqlite3_value **pp
){
  /* The evalConstExpr() function will have already converted any TK_VARIABLE
  ** expression involved in an comparison into a TK_REGISTER. */
  assert( pExpr->op!=TK_VARIABLE );
  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
    int iVar = pExpr->iColumn;
    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
    return SQLITE_OK;
  }
  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
}
#endif

/*
** This function is used to estimate the number of rows that will be visited
** by scanning an index for a range of values. The range may have an upper
** bound, a lower bound, or both. The WHERE clause terms that set the upper
** and lower bounds are represented by pLower and pUpper respectively. For
** example, assuming that index p is on t1(a):
**
**   ... FROM t1 WHERE a > ? AND a < ? ...
**                    |_____|   |_____|
**                       |         |
**                     pLower    pUpper
**
** If either of the upper or lower bound is not present, then NULL is passed in
** place of the corresponding WhereTerm.
**
** The nEq parameter is passed the index of the index column subject to the
** range constraint. Or, equivalently, the number of equality constraints
** optimized by the proposed index scan. For example, assuming index p is
** on t1(a, b), and the SQL query is:
**
**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
**
** then nEq should be passed the value 1 (as the range restricted column,
** b, is the second left-most column of the index). Or, if the query is:
**
**   ... FROM t1 WHERE a > ? AND a < ? ...
**
** then nEq should be passed 0.
**
** The returned value is an integer between 1 and 100, inclusive. A return
** value of 1 indicates that the proposed range scan is expected to visit
** approximately 1/100th (1%) of the rows selected by the nEq equality
** constraints (if any). A return value of 100 indicates that it is expected
** that the range scan will visit every row (100%) selected by the equality
** constraints.
**
** In the absence of sqlite_stat2 ANALYZE data, each range inequality
** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
** results in a return of 33 and a range constraint (x>? AND x<?) results
** in a return of 11.
*/
static int whereRangeScanEst(
  Parse *pParse,       /* Parsing & code generating context */
  Index *p,            /* The index containing the range-compared column; "x" */
  int nEq,             /* index into p->aCol[] of the range-compared column */
  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
  int *piEst           /* OUT: Return value */
){
  int rc = SQLITE_OK;

#ifdef SQLITE_ENABLE_STAT2

  if( nEq==0 && p->aSample ){
    sqlite3_value *pLowerVal = 0;
    sqlite3_value *pUpperVal = 0;
    int iEst;
    int iLower = 0;
    int iUpper = SQLITE_INDEX_SAMPLES;
    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;

    if( pLower ){
      Expr *pExpr = pLower->pExpr->pRight;
      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
    }
    if( rc==SQLITE_OK && pUpper ){
      Expr *pExpr = pUpper->pExpr->pRight;
      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
    }

    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
      sqlite3ValueFree(pLowerVal);
      sqlite3ValueFree(pUpperVal);
      goto range_est_fallback;
    }else if( pLowerVal==0 ){
      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
      if( pLower ) iLower = iUpper/2;
    }else if( pUpperVal==0 ){
      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
    }else{
      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
      if( rc==SQLITE_OK ){
        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
      }
    }

    iEst = iUpper - iLower;
    testcase( iEst==SQLITE_INDEX_SAMPLES );
    assert( iEst<=SQLITE_INDEX_SAMPLES );
    if( iEst<1 ){
      iEst = 1;
    }

    sqlite3ValueFree(pLowerVal);
    sqlite3ValueFree(pUpperVal);
    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
    return rc;
  }
range_est_fallback:
#else
  UNUSED_PARAMETER(pParse);
  UNUSED_PARAMETER(p);
  UNUSED_PARAMETER(nEq);
#endif
  assert( pLower || pUpper );
  if( pLower && pUpper ){
    *piEst = 11;
  }else{
    *piEst = 33;
  }
  return rc;
}


/*
** Find the query plan for accessing a particular table.  Write the
** best query plan and its cost into the WhereCost object supplied as the
** last parameter.
**
** The lowest cost plan wins.  The cost is an estimate of the amount of
** CPU and disk I/O need to process the request using the selected plan.
** Factors that influence cost include:
**
**    *  The estimated number of rows that will be retrieved.  (The
**       fewer the better.)
**
**    *  Whether or not sorting must occur.
**
**    *  Whether or not there must be separate lookups in the
**       index and in the main table.
**
** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
** the SQL statement, then this function only considers plans using the 
** named index. If no such plan is found, then the returned cost is
** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
** then the cost is calculated in the usual way.
**
** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
** in the SELECT statement, then no indexes are considered. However, the 
** selected plan may still take advantage of the tables built-in rowid
** index.
*/
static void bestBtreeIndex(
  Parse *pParse,              /* The parsing context */
  WhereClause *pWC,           /* The WHERE clause */
  struct SrcList_item *pSrc,  /* The FROM clause term to search */
  Bitmask notReady,           /* Mask of cursors that are not available */
  ExprList *pOrderBy,         /* The ORDER BY clause */
  WhereCost *pCost            /* Lowest cost query plan */
){
  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
  Index *pProbe;              /* An index we are evaluating */
  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
  int eqTermMask;             /* Current mask of valid equality operators */
  int idxEqTermMask;          /* Index mask of valid equality operators */
  Index sPk;                  /* A fake index object for the primary key */
  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */

  /* Initialize the cost to a worst-case value */
  memset(pCost, 0, sizeof(*pCost));
  pCost->rCost = SQLITE_BIG_DBL;

  /* If the pSrc table is the right table of a LEFT JOIN then we may not
  ** use an index to satisfy IS NULL constraints on that table.  This is
  ** because columns might end up being NULL if the table does not match -
  ** a circumstance which the index cannot help us discover.  Ticket #2177.
  */
  if( pSrc->jointype & JT_LEFT ){
    idxEqTermMask = WO_EQ|WO_IN;
  }else{
    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  }

  if( pSrc->pIndex ){
    /* An INDEXED BY clause specifies a particular index to use */
    pIdx = pProbe = pSrc->pIndex;
    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
    eqTermMask = idxEqTermMask;
  }else{
    /* There is no INDEXED BY clause.  Create a fake Index object to
    ** represent the primary key */
    Index *pFirst;                /* Any other index on the table */
    memset(&sPk, 0, sizeof(Index));
    sPk.nColumn = 1;
    sPk.aiColumn = &aiColumnPk;
    sPk.aiRowEst = aiRowEstPk;
    aiRowEstPk[1] = 1;
    sPk.onError = OE_Replace;
    sPk.pTable = pSrc->pTab;
    pFirst = pSrc->pTab->pIndex;
    if( pSrc->notIndexed==0 ){
      sPk.pNext = pFirst;
    }
    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
    ** table.  Get this information from the ANALYZE information if it is
    ** available.  If not available, assume the table 1 million rows in size.
    */
    if( pFirst ){
      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
      aiRowEstPk[0] = pFirst->aiRowEst[0];
    }else{
      aiRowEstPk[0] = 1000000;
    }
    pProbe = &sPk;
    wsFlagMask = ~(
        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
    );
    eqTermMask = WO_EQ|WO_IN;
    pIdx = 0;
  }

  /* Loop over all indices looking for the best one to use
  */
  for(; pProbe; pIdx=pProbe=pProbe->pNext){
    const unsigned int * const aiRowEst = pProbe->aiRowEst;
    double cost;                /* Cost of using pProbe */
    double nRow;                /* Estimated number of rows in result set */
    int rev;                    /* True to scan in reverse order */
    int wsFlags = 0;
    Bitmask used = 0;

    /* The following variables are populated based on the properties of
    ** scan being evaluated. They are then used to determine the expected
    ** cost and number of rows returned.
    **
    **  nEq: 
    **    Number of equality terms that can be implemented using the index.
    **
    **  nInMul:  
    **    The "in-multiplier". This is an estimate of how many seek operations 
    **    SQLite must perform on the index in question. For example, if the 
    **    WHERE clause is:
    **
    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
    **
    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
    **    set to 9. Given the same schema and either of the following WHERE 
    **    clauses:
    **
    **      WHERE a =  1
    **      WHERE a >= 2
    **
    **    nInMul is set to 1.
    **
    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
    **    the sub-select is assumed to return 25 rows for the purposes of 
    **    determining nInMul.
    **
    **  bInEst:  
    **    Set to true if there was at least one "x IN (SELECT ...)" term used 
    **    in determining the value of nInMul.
    **
    **  nBound:
    **    An estimate on the amount of the table that must be searched.  A
    **    value of 100 means the entire table is searched.  Range constraints
    **    might reduce this to a value less than 100 to indicate that only
    **    a fraction of the table needs searching.  In the absence of
    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
    **    space to 1/3rd its original size.  So an x>? constraint reduces
    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
    **
    **  bSort:   
    **    Boolean. True if there is an ORDER BY clause that will require an 
    **    external sort (i.e. scanning the index being evaluated will not 
    **    correctly order records).
    **
    **  bLookup: 
    **    Boolean. True if for each index entry visited a lookup on the 
    **    corresponding table b-tree is required. This is always false 
    **    for the rowid index. For other indexes, it is true unless all the 
    **    columns of the table used by the SELECT statement are present in 
    **    the index (such an index is sometimes described as a covering index).
    **    For example, given the index on (a, b), the second of the following 
    **    two queries requires table b-tree lookups, but the first does not.
    **
    **             SELECT a, b    FROM tbl WHERE a = 1;
    **             SELECT a, b, c FROM tbl WHERE a = 1;
    */
    int nEq;
    int bInEst = 0;
    int nInMul = 1;
    int nBound = 100;
    int bSort = 0;
    int bLookup = 0;

    /* Determine the values of nEq and nInMul */
    for(nEq=0; nEq<pProbe->nColumn; nEq++){
      WhereTerm *pTerm;           /* A single term of the WHERE clause */
      int j = pProbe->aiColumn[nEq];
      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
      if( pTerm==0 ) break;
      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
      if( pTerm->eOperator & WO_IN ){
        Expr *pExpr = pTerm->pExpr;
        wsFlags |= WHERE_COLUMN_IN;
        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
          nInMul *= 25;
          bInEst = 1;
        }else if( pExpr->x.pList ){
          nInMul *= pExpr->x.pList->nExpr + 1;
        }
      }else if( pTerm->eOperator & WO_ISNULL ){
        wsFlags |= WHERE_COLUMN_NULL;
      }
      used |= pTerm->prereqRight;
    }

    /* Determine the value of nBound. */
    if( nEq<pProbe->nColumn ){
      int j = pProbe->aiColumn[nEq];
      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
        if( pTop ){
          wsFlags |= WHERE_TOP_LIMIT;
          used |= pTop->prereqRight;
        }
        if( pBtm ){
          wsFlags |= WHERE_BTM_LIMIT;
          used |= pBtm->prereqRight;
        }
        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
      }
    }else if( pProbe->onError!=OE_None ){
      testcase( wsFlags & WHERE_COLUMN_IN );
      testcase( wsFlags & WHERE_COLUMN_NULL );
      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
        wsFlags |= WHERE_UNIQUE;
      }
    }

    /* If there is an ORDER BY clause and the index being considered will
    ** naturally scan rows in the required order, set the appropriate flags
    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
    ** will scan rows in a different order, set the bSort variable.  */
    if( pOrderBy ){
      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
      ){
        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
        wsFlags |= (rev ? WHERE_REVERSE : 0);
      }else{
        bSort = 1;
      }
    }

    /* If currently calculating the cost of using an index (not the IPK
    ** index), determine if all required column data may be obtained without 
    ** seeking to entries in the main table (i.e. if the index is a covering
    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
    ** wsFlags. Otherwise, set the bLookup variable to true.  */
    if( pIdx && wsFlags ){
      Bitmask m = pSrc->colUsed;
      int j;
      for(j=0; j<pIdx->nColumn; j++){
        int x = pIdx->aiColumn[j];
        if( x<BMS-1 ){
          m &= ~(((Bitmask)1)<<x);
        }
      }
      if( m==0 ){
        wsFlags |= WHERE_IDX_ONLY;
      }else{
        bLookup = 1;
      }
    }

    /**** Begin adding up the cost of using this index (Needs improvements)
    **
    ** Estimate the number of rows of output.  For an IN operator,
    ** do not let the estimate exceed half the rows in the table.
    */
    nRow = (double)(aiRowEst[nEq] * nInMul);
    if( bInEst && nRow*2>aiRowEst[0] ){
      nRow = aiRowEst[0]/2;
      nInMul = (int)(nRow / aiRowEst[nEq]);
    }

    /* Assume constant cost to access a row and logarithmic cost to
    ** do a binary search.  Hence, the initial cost is the number of output
    ** rows plus log2(table-size) times the number of binary searches.
    */
    cost = nRow + nInMul*estLog(aiRowEst[0]);

    /* Adjust the number of rows and the cost downward to reflect rows
    ** that are excluded by range constraints.
    */
    nRow = (nRow * (double)nBound) / (double)100;
    cost = (cost * (double)nBound) / (double)100;

    /* Add in the estimated cost of sorting the result
    */
    if( bSort ){
      cost += cost*estLog(cost);
    }

    /* If all information can be taken directly from the index, we avoid
    ** doing table lookups.  This reduces the cost by half.  (Not really -
    ** this needs to be fixed.)
    */
    if( pIdx && bLookup==0 ){
      cost /= (double)2;
    }
    /**** Cost of using this index has now been computed ****/

    WHERETRACE((
      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
    ));

    /* If this index is the best we have seen so far, then record this
    ** index and its cost in the pCost structure.
    */
    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
      pCost->rCost = cost;
      pCost->nRow = nRow;
      pCost->used = used;
      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
      pCost->plan.nEq = nEq;
      pCost->plan.u.pIdx = pIdx;
    }

    /* If there was an INDEXED BY clause, then only that one index is
    ** considered. */
    if( pSrc->pIndex ) break;

    /* Reset masks for the next index in the loop */
    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
    eqTermMask = idxEqTermMask;
  }

  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
  ** is set, then reverse the order that the index will be scanned
  ** in. This is used for application testing, to help find cases
  ** where application behaviour depends on the (undefined) order that
  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
    pCost->plan.wsFlags |= WHERE_REVERSE;
  }

  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
  assert( pSrc->pIndex==0 
       || pCost->plan.u.pIdx==0 
       || pCost->plan.u.pIdx==pSrc->pIndex 
  );

  WHERETRACE(("best index is: %s\n", 
    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
  ));
  
  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
  pCost->plan.wsFlags |= eqTermMask;
}

/*
** Find the query plan for accessing table pSrc->pTab. Write the
** best query plan and its cost into the WhereCost object supplied 
** as the last parameter. This function may calculate the cost of
** both real and virtual table scans.
*/
static void bestIndex(
  Parse *pParse,              /* The parsing context */
  WhereClause *pWC,           /* The WHERE clause */
  struct SrcList_item *pSrc,  /* The FROM clause term to search */
  Bitmask notReady,           /* Mask of cursors that are not available */
  ExprList *pOrderBy,         /* The ORDER BY clause */
  WhereCost *pCost            /* Lowest cost query plan */
){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( IsVirtual(pSrc->pTab) ){
    sqlite3_index_info *p = 0;
    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
    if( p->needToFreeIdxStr ){
      sqlite3_free(p->idxStr);
    }
    sqlite3DbFree(pParse->db, p);
  }else
#endif
  {
    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
  }
}

/*
** Disable a term in the WHERE clause.  Except, do not disable the term
** if it controls a LEFT OUTER JOIN and it did not originate in the ON
** or USING clause of that join.
**
** Consider the term t2.z='ok' in the following queries:
**
**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
**
** The t2.z='ok' is disabled in the in (2) because it originates
** in the ON clause.  The term is disabled in (3) because it is not part
** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
**
** Disabling a term causes that term to not be tested in the inner loop
** of the join.  Disabling is an optimization.  When terms are satisfied
** by indices, we disable them to prevent redundant tests in the inner
** loop.  We would get the correct results if nothing were ever disabled,
** but joins might run a little slower.  The trick is to disable as much
** as we can without disabling too much.  If we disabled in (1), we'd get
** the wrong answer.  See ticket #813.
*/
static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  if( pTerm
      && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  ){
    pTerm->wtFlags |= TERM_CODED;
    if( pTerm->iParent>=0 ){
      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
      if( (--pOther->nChild)==0 ){
        disableTerm(pLevel, pOther);
      }
    }
  }
}

/*
** Code an OP_Affinity opcode to apply the column affinity string zAff
** to the n registers starting at base. 
**
** Buffer zAff was allocated using sqlite3DbMalloc(). It is the 
** responsibility of this function to arrange for it to be eventually
** freed using sqlite3DbFree().
*/
static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  Vdbe *v = pParse->pVdbe;
  assert( v!=0 );
  sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  sqlite3VdbeChangeP4(v, -1, zAff, P4_DYNAMIC);
  sqlite3ExprCacheAffinityChange(pParse, base, n);
}


/*
** Generate code for a single equality term of the WHERE clause.  An equality
** term can be either X=expr or X IN (...).   pTerm is the term to be 
** coded.
**
** The current value for the constraint is left in register iReg.
**
** For a constraint of the form X=expr, the expression is evaluated and its
** result is left on the stack.  For constraints of the form X IN (...)
** this routine sets up a loop that will iterate over all values of X.
*/
static int codeEqualityTerm(
  Parse *pParse,      /* The parsing context */
  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
  int iTarget         /* Attempt to leave results in this register */
){
  Expr *pX = pTerm->pExpr;
  Vdbe *v = pParse->pVdbe;
  int iReg;                  /* Register holding results */

  assert( iTarget>0 );
  if( pX->op==TK_EQ ){
    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  }else if( pX->op==TK_ISNULL ){
    iReg = iTarget;
    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
#ifndef SQLITE_OMIT_SUBQUERY
  }else{
    int eType;
    int iTab;
    struct InLoop *pIn;

    assert( pX->op==TK_IN );
    iReg = iTarget;
    eType = sqlite3FindInIndex(pParse, pX, 0);
    iTab = pX->iTable;
    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
    if( pLevel->u.in.nIn==0 ){
      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
    }
    pLevel->u.in.nIn++;
    pLevel->u.in.aInLoop =
       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
    pIn = pLevel->u.in.aInLoop;
    if( pIn ){
      pIn += pLevel->u.in.nIn - 1;
      pIn->iCur = iTab;
      if( eType==IN_INDEX_ROWID ){
        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
      }else{
        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
      }
      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
    }else{
      pLevel->u.in.nIn = 0;
    }
#endif
  }
  disableTerm(pLevel, pTerm);
  return iReg;
}

/*
** Generate code that will evaluate all == and IN constraints for an
** index.  The values for all constraints are left on the stack.
**
** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
** The index has as many as three equality constraints, but in this
** example, the third "c" value is an inequality.  So only two 
** constraints are coded.  This routine will generate code to evaluate
** a==5 and b IN (1,2,3).  The current values for a and b will be stored
** in consecutive registers and the index of the first register is returned.
**
** In the example above nEq==2.  But this subroutine works for any value
** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
** The only thing it does is allocate the pLevel->iMem memory cell.
**
** This routine always allocates at least one memory cell and returns
** the index of that memory cell. The code that
** calls this routine will use that memory cell to store the termination
** key value of the loop.  If one or more IN operators appear, then
** this routine allocates an additional nEq memory cells for internal
** use.
**
** Before returning, *pzAff is set to point to a buffer containing a
** copy of the column affinity string of the index allocated using
** sqlite3DbMalloc(). Except, entries in the copy of the string associated
** with equality constraints that use NONE affinity are set to
** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
**
**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
**
** In the example above, the index on t1(a) has TEXT affinity. But since
** the right hand side of the equality constraint (t2.b) has NONE affinity,
** no conversion should be attempted before using a t2.b value as part of
** a key to search the index. Hence the first byte in the returned affinity
** string in this example would be set to SQLITE_AFF_NONE.
*/
static int codeAllEqualityTerms(
  Parse *pParse,        /* Parsing context */
  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
  WhereClause *pWC,     /* The WHERE clause */
  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
  int nExtraReg,        /* Number of extra registers to allocate */
  char **pzAff          /* OUT: Set to point to affinity string */
){
  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
  Index *pIdx;                  /* The index being used for this loop */
  int iCur = pLevel->iTabCur;   /* The cursor of the table */
  WhereTerm *pTerm;             /* A single constraint term */
  int j;                        /* Loop counter */
  int regBase;                  /* Base register */
  int nReg;                     /* Number of registers to allocate */
  char *zAff;                   /* Affinity string to return */

  /* This module is only called on query plans that use an index. */
  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
  pIdx = pLevel->plan.u.pIdx;

  /* Figure out how many memory cells we will need then allocate them.
  */
  regBase = pParse->nMem + 1;
  nReg = pLevel->plan.nEq + nExtraReg;
  pParse->nMem += nReg;

  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  if( !zAff ){
    pParse->db->mallocFailed = 1;
  }

  /* Evaluate the equality constraints
  */
  assert( pIdx->nColumn>=nEq );
  for(j=0; j<nEq; j++){
    int r1;
    int k = pIdx->aiColumn[j];
    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
    if( NEVER(pTerm==0) ) break;
    assert( (pTerm->wtFlags & TERM_CODED)==0 );
    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
    if( r1!=regBase+j ){
      if( nReg==1 ){
        sqlite3ReleaseTempReg(pParse, regBase);
        regBase = r1;
      }else{
        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
      }
    }
    testcase( pTerm->eOperator & WO_ISNULL );
    testcase( pTerm->eOperator & WO_IN );
    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
      sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
      if( zAff 
       && sqlite3CompareAffinity(pTerm->pExpr->pRight, zAff[j])==SQLITE_AFF_NONE
      ){
        zAff[j] = SQLITE_AFF_NONE;
      }
    }
  }
  *pzAff = zAff;
  return regBase;
}

/*
** Generate code for the start of the iLevel-th loop in the WHERE clause
** implementation described by pWInfo.
*/
static Bitmask codeOneLoopStart(
  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
  int iLevel,          /* Which level of pWInfo->a[] should be coded */
  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
  Bitmask notReady     /* Which tables are currently available */
){
  int j, k;            /* Loop counters */
  int iCur;            /* The VDBE cursor for the table */
  int addrNxt;         /* Where to jump to continue with the next IN case */
  int omitTable;       /* True if we use the index only */
  int bRev;            /* True if we need to scan in reverse order */
  WhereLevel *pLevel;  /* The where level to be coded */
  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
  WhereTerm *pTerm;               /* A WHERE clause term */
  Parse *pParse;                  /* Parsing context */
  Vdbe *v;                        /* The prepared stmt under constructions */
  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
  int addrBrk;                    /* Jump here to break out of the loop */
  int addrCont;                   /* Jump here to continue with next cycle */
  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
  int iReleaseReg = 0;      /* Temp register to free before returning */

  pParse = pWInfo->pParse;
  v = pParse->pVdbe;
  pWC = pWInfo->pWC;
  pLevel = &pWInfo->a[iLevel];
  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  iCur = pTabItem->iCursor;
  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
           && (wctrlFlags & WHERE_FORCE_TABLE)==0;

  /* Create labels for the "break" and "continue" instructions
  ** for the current loop.  Jump to addrBrk to break out of a loop.
  ** Jump to cont to go immediately to the next iteration of the
  ** loop.
  **
  ** When there is an IN operator, we also have a "addrNxt" label that
  ** means to continue with the next IN value combination.  When
  ** there are no IN operators in the constraints, the "addrNxt" label
  ** is the same as "addrBrk".
  */
  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);

  /* If this is the right table of a LEFT OUTER JOIN, allocate and
  ** initialize a memory cell that records if this table matches any
  ** row of the left table of the join.
  */
  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
    pLevel->iLeftJoin = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
    VdbeComment((v, "init LEFT JOIN no-match flag"));
  }

#ifndef SQLITE_OMIT_VIRTUALTABLE
  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
    **          to access the data.
    */
    int iReg;   /* P3 Value for OP_VFilter */
    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
    int nConstraint = pVtabIdx->nConstraint;
    struct sqlite3_index_constraint_usage *aUsage =
                                                pVtabIdx->aConstraintUsage;
    const struct sqlite3_index_constraint *aConstraint =
                                                pVtabIdx->aConstraint;

    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
    for(j=1; j<=nConstraint; j++){
      for(k=0; k<nConstraint; k++){
        if( aUsage[k].argvIndex==j ){
          int iTerm = aConstraint[k].iTermOffset;
          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
          break;
        }
      }
      if( k==nConstraint ) break;
    }
    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
    pVtabIdx->needToFreeIdxStr = 0;
    for(j=0; j<nConstraint; j++){
      if( aUsage[j].omit ){
        int iTerm = aConstraint[j].iTermOffset;
        disableTerm(pLevel, &pWC->a[iTerm]);
      }
    }
    pLevel->op = OP_VNext;
    pLevel->p1 = iCur;
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  }else
#endif /* SQLITE_OMIT_VIRTUALTABLE */

  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
    /* Case 1:  We can directly reference a single row using an
    **          equality comparison against the ROWID field.  Or
    **          we reference multiple rows using a "rowid IN (...)"
    **          construct.
    */
    iReleaseReg = sqlite3GetTempReg(pParse);
    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
    assert( pTerm!=0 );
    assert( pTerm->pExpr!=0 );
    assert( pTerm->leftCursor==iCur );
    assert( omitTable==0 );
    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
    addrNxt = pLevel->addrNxt;
    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
    VdbeComment((v, "pk"));
    pLevel->op = OP_Noop;
  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
    /* Case 2:  We have an inequality comparison against the ROWID field.
    */
    int testOp = OP_Noop;
    int start;
    int memEndValue = 0;
    WhereTerm *pStart, *pEnd;

    assert( omitTable==0 );
    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
    if( bRev ){
      pTerm = pStart;
      pStart = pEnd;
      pEnd = pTerm;
    }
    if( pStart ){
      Expr *pX;             /* The expression that defines the start bound */
      int r1, rTemp;        /* Registers for holding the start boundary */

      /* The following constant maps TK_xx codes into corresponding 
      ** seek opcodes.  It depends on a particular ordering of TK_xx
      */
      const u8 aMoveOp[] = {
           /* TK_GT */  OP_SeekGt,
           /* TK_LE */  OP_SeekLe,
           /* TK_LT */  OP_SeekLt,
           /* TK_GE */  OP_SeekGe
      };
      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */

      pX = pStart->pExpr;
      assert( pX!=0 );
      assert( pStart->leftCursor==iCur );
      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
      VdbeComment((v, "pk"));
      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
      sqlite3ReleaseTempReg(pParse, rTemp);
      disableTerm(pLevel, pStart);
    }else{
      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
    }
    if( pEnd ){
      Expr *pX;
      pX = pEnd->pExpr;
      assert( pX!=0 );
      assert( pEnd->leftCursor==iCur );
      memEndValue = ++pParse->nMem;
      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
      if( pX->op==TK_LT || pX->op==TK_GT ){
        testOp = bRev ? OP_Le : OP_Ge;
      }else{
        testOp = bRev ? OP_Lt : OP_Gt;
      }
      disableTerm(pLevel, pEnd);
    }
    start = sqlite3VdbeCurrentAddr(v);
    pLevel->op = bRev ? OP_Prev : OP_Next;
    pLevel->p1 = iCur;
    pLevel->p2 = start;
    pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
    if( testOp!=OP_Noop ){
      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
    }
  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
    /* Case 3: A scan using an index.
    **
    **         The WHERE clause may contain zero or more equality 
    **         terms ("==" or "IN" operators) that refer to the N
    **         left-most columns of the index. It may also contain
    **         inequality constraints (>, <, >= or <=) on the indexed
    **         column that immediately follows the N equalities. Only 
    **         the right-most column can be an inequality - the rest must
    **         use the "==" and "IN" operators. For example, if the 
    **         index is on (x,y,z), then the following clauses are all 
    **         optimized:
    **
    **            x=5
    **            x=5 AND y=10
    **            x=5 AND y<10
    **            x=5 AND y>5 AND y<10
    **            x=5 AND y=5 AND z<=10
    **
    **         The z<10 term of the following cannot be used, only
    **         the x=5 term:
    **
    **            x=5 AND z<10
    **
    **         N may be zero if there are inequality constraints.
    **         If there are no inequality constraints, then N is at
    **         least one.
    **
    **         This case is also used when there are no WHERE clause
    **         constraints but an index is selected anyway, in order
    **         to force the output order to conform to an ORDER BY.
    */  
    int aStartOp[] = {
      0,
      0,
      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
    };
    int aEndOp[] = {
      OP_Noop,             /* 0: (!end_constraints) */
      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
      OP_IdxLT             /* 2: (end_constraints && bRev) */
    };
    int nEq = pLevel->plan.nEq;
    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
    int regBase;                 /* Base register holding constraint values */
    int r1;                      /* Temp register */
    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
    int startEq;                 /* True if range start uses ==, >= or <= */
    int endEq;                   /* True if range end uses ==, >= or <= */
    int start_constraints;       /* Start of range is constrained */
    int nConstraint;             /* Number of constraint terms */
    Index *pIdx;         /* The index we will be using */
    int iIdxCur;         /* The VDBE cursor for the index */
    int nExtraReg = 0;   /* Number of extra registers needed */
    int op;              /* Instruction opcode */
    char *zAff;

    pIdx = pLevel->plan.u.pIdx;
    iIdxCur = pLevel->iIdxCur;
    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */

    /* If this loop satisfies a sort order (pOrderBy) request that 
    ** was passed to this function to implement a "SELECT min(x) ..." 
    ** query, then the caller will only allow the loop to run for
    ** a single iteration. This means that the first row returned
    ** should not have a NULL value stored in 'x'. If column 'x' is
    ** the first one after the nEq equality constraints in the index,
    ** this requires some special handling.
    */
    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
     && (pIdx->nColumn>nEq)
    ){
      /* assert( pOrderBy->nExpr==1 ); */
      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
      isMinQuery = 1;
      nExtraReg = 1;
    }

    /* Find any inequality constraint terms for the start and end 
    ** of the range. 
    */
    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
      nExtraReg = 1;
    }
    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
      nExtraReg = 1;
    }

    /* Generate code to evaluate all constraint terms using == or IN
    ** and store the values of those terms in an array of registers
    ** starting at regBase.
    */
    regBase = codeAllEqualityTerms(
        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
    );
    addrNxt = pLevel->addrNxt;

    /* If we are doing a reverse order scan on an ascending index, or
    ** a forward order scan on a descending index, interchange the 
    ** start and end terms (pRangeStart and pRangeEnd).
    */
    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
    }

    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
    start_constraints = pRangeStart || nEq>0;

    /* Seek the index cursor to the start of the range. */
    nConstraint = nEq;
    if( pRangeStart ){
      Expr *pRight = pRangeStart->pExpr->pRight;
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
      sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
      if( zAff 
       && sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE
      ){
        /* Since the comparison is to be performed with no conversions applied
        ** to the operands, set the affinity to apply to pRight to 
        ** SQLITE_AFF_NONE.  */
        zAff[nConstraint] = SQLITE_AFF_NONE;
      }
      nConstraint++;
    }else if( isMinQuery ){
      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
      nConstraint++;
      startEq = 0;
      start_constraints = 1;
    }
    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
    assert( op!=0 );
    testcase( op==OP_Rewind );
    testcase( op==OP_Last );
    testcase( op==OP_SeekGt );
    testcase( op==OP_SeekGe );
    testcase( op==OP_SeekLe );
    testcase( op==OP_SeekLt );
    sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase, 
                      SQLITE_INT_TO_PTR(nConstraint), P4_INT32);

    /* Load the value for the inequality constraint at the end of the
    ** range (if any).
    */
    nConstraint = nEq;
    if( pRangeEnd ){
      Expr *pRight = pRangeEnd->pExpr->pRight;
      sqlite3ExprCacheRemove(pParse, regBase+nEq);
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
      sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
      zAff = sqlite3DbStrDup(pParse->db, zAff);
      if( zAff 
       && sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE
      ){
        /* Since the comparison is to be performed with no conversions applied
        ** to the operands, set the affinity to apply to pRight to 
        ** SQLITE_AFF_NONE.  */
        zAff[nConstraint] = SQLITE_AFF_NONE;
      }
      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
      nConstraint++;
    }

    /* Top of the loop body */
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);

    /* Check if the index cursor is past the end of the range. */
    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
    testcase( op==OP_Noop );
    testcase( op==OP_IdxGE );
    testcase( op==OP_IdxLT );
    if( op!=OP_Noop ){
      sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
                        SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
    }

    /* If there are inequality constraints, check that the value
    ** of the table column that the inequality contrains is not NULL.
    ** If it is, jump to the next iteration of the loop.
    */
    r1 = sqlite3GetTempReg(pParse);
    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
    }
    sqlite3ReleaseTempReg(pParse, r1);

    /* Seek the table cursor, if required */
    disableTerm(pLevel, pRangeStart);
    disableTerm(pLevel, pRangeEnd);
    if( !omitTable ){
      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
    }

    /* Record the instruction used to terminate the loop. Disable 
    ** WHERE clause terms made redundant by the index range scan.
    */
    pLevel->op = bRev ? OP_Prev : OP_Next;
    pLevel->p1 = iIdxCur;
  }else

#ifndef SQLITE_OMIT_OR_OPTIMIZATION
  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
    /* Case 4:  Two or more separately indexed terms connected by OR
    **
    ** Example:
    **
    **   CREATE TABLE t1(a,b,c,d);
    **   CREATE INDEX i1 ON t1(a);
    **   CREATE INDEX i2 ON t1(b);
    **   CREATE INDEX i3 ON t1(c);
    **
    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
    **
    ** In the example, there are three indexed terms connected by OR.
    ** The top of the loop looks like this:
    **
    **          Null       1                # Zero the rowset in reg 1
    **
    ** Then, for each indexed term, the following. The arguments to
    ** RowSetTest are such that the rowid of the current row is inserted
    ** into the RowSet. If it is already present, control skips the
    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
    **
    **        sqlite3WhereBegin(<term>)
    **          RowSetTest                  # Insert rowid into rowset
    **          Gosub      2 A
    **        sqlite3WhereEnd()
    **
    ** Following the above, code to terminate the loop. Label A, the target
    ** of the Gosub above, jumps to the instruction right after the Goto.
    **
    **          Null       1                # Zero the rowset in reg 1
    **          Goto       B                # The loop is finished.
    **
    **       A: <loop body>                 # Return data, whatever.
    **
    **          Return     2                # Jump back to the Gosub
    **
    **       B: <after the loop>
    **
    */
    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
    SrcList oneTab;        /* Shortened table list */

    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
    int regRowset = 0;                        /* Register for RowSet object */
    int regRowid = 0;                         /* Register holding rowid */
    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
    int iRetInit;                             /* Address of regReturn init */
    int ii;
   
    pTerm = pLevel->plan.u.pTerm;
    assert( pTerm!=0 );
    assert( pTerm->eOperator==WO_OR );
    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
    pOrWc = &pTerm->u.pOrInfo->wc;
    pFinal = &pOrWc->a[pOrWc->nTerm-1];

    /* Set up a SrcList containing just the table being scanned by this loop. */
    oneTab.nSrc = 1;
    oneTab.nAlloc = 1;
    oneTab.a[0] = *pTabItem;

    /* Initialize the rowset register to contain NULL. An SQL NULL is 
    ** equivalent to an empty rowset.
    **
    ** Also initialize regReturn to contain the address of the instruction 
    ** immediately following the OP_Return at the bottom of the loop. This
    ** is required in a few obscure LEFT JOIN cases where control jumps
    ** over the top of the loop into the body of it. In this case the 
    ** correct response for the end-of-loop code (the OP_Return) is to 
    ** fall through to the next instruction, just as an OP_Next does if
    ** called on an uninitialized cursor.
    */
    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
      regRowset = ++pParse->nMem;
      regRowid = ++pParse->nMem;
      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
    }
    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);

    for(ii=0; ii<pOrWc->nTerm; ii++){
      WhereTerm *pOrTerm = &pOrWc->a[ii];
      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
        /* Loop through table entries that match term pOrTerm. */
        pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE | WHERE_FORCE_TABLE);
        if( pSubWInfo ){
          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
            int r;
            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
                                         regRowid, 0);
            sqlite3VdbeAddOp4(v, OP_RowSetTest, regRowset,
                              sqlite3VdbeCurrentAddr(v)+2,
                              r, SQLITE_INT_TO_PTR(iSet), P4_INT32);
          }
          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);

          /* Finish the loop through table entries that match term pOrTerm. */
          sqlite3WhereEnd(pSubWInfo);
        }
      }
    }
    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
    /* sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); */
    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
    sqlite3VdbeResolveLabel(v, iLoopBody);

    pLevel->op = OP_Return;
    pLevel->p1 = regReturn;
    disableTerm(pLevel, pTerm);
  }else
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */

  {
    /* Case 5:  There is no usable index.  We must do a complete
    **          scan of the entire table.
    */
    static const u8 aStep[] = { OP_Next, OP_Prev };
    static const u8 aStart[] = { OP_Rewind, OP_Last };
    assert( bRev==0 || bRev==1 );
    assert( omitTable==0 );
    pLevel->op = aStep[bRev];
    pLevel->p1 = iCur;
    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  }
  notReady &= ~getMask(pWC->pMaskSet, iCur);

  /* Insert code to test every subexpression that can be completely
  ** computed using the current set of tables.
  */
  k = 0;
  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
    Expr *pE;
    testcase( pTerm->wtFlags & TERM_VIRTUAL );
    testcase( pTerm->wtFlags & TERM_CODED );
    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
    if( (pTerm->prereqAll & notReady)!=0 ) continue;
    pE = pTerm->pExpr;
    assert( pE!=0 );
    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
      continue;
    }
    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
    k = 1;
    pTerm->wtFlags |= TERM_CODED;
  }

  /* For a LEFT OUTER JOIN, generate code that will record the fact that
  ** at least one row of the right table has matched the left table.  
  */
  if( pLevel->iLeftJoin ){
    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
    VdbeComment((v, "record LEFT JOIN hit"));
    sqlite3ExprCacheClear(pParse);
    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
      testcase( pTerm->wtFlags & TERM_VIRTUAL );
      testcase( pTerm->wtFlags & TERM_CODED );
      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
      if( (pTerm->prereqAll & notReady)!=0 ) continue;
      assert( pTerm->pExpr );
      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
      pTerm->wtFlags |= TERM_CODED;
    }
  }
  sqlite3ReleaseTempReg(pParse, iReleaseReg);

  return notReady;
}

#if defined(SQLITE_TEST)
/*
** The following variable holds a text description of query plan generated
** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
** overwrites the previous.  This information is used for testing and
** analysis only.
*/
char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
static int nQPlan = 0;              /* Next free slow in _query_plan[] */

#endif /* SQLITE_TEST */


/*
** Free a WhereInfo structure
*/
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  if( pWInfo ){
    int i;
    for(i=0; i<pWInfo->nLevel; i++){
      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
      if( pInfo ){
        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
        if( pInfo->needToFreeIdxStr ){
          sqlite3_free(pInfo->idxStr);
        }
        sqlite3DbFree(db, pInfo);
      }
    }
    whereClauseClear(pWInfo->pWC);
    sqlite3DbFree(db, pWInfo);
  }
}


/*
** Generate the beginning of the loop used for WHERE clause processing.
** The return value is a pointer to an opaque structure that contains
** information needed to terminate the loop.  Later, the calling routine
** should invoke sqlite3WhereEnd() with the return value of this function
** in order to complete the WHERE clause processing.
**
** If an error occurs, this routine returns NULL.
**
** The basic idea is to do a nested loop, one loop for each table in
** the FROM clause of a select.  (INSERT and UPDATE statements are the
** same as a SELECT with only a single table in the FROM clause.)  For
** example, if the SQL is this:
**
**       SELECT * FROM t1, t2, t3 WHERE ...;
**
** Then the code generated is conceptually like the following:
**
**      foreach row1 in t1 do       \    Code generated
**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
**          foreach row3 in t3 do   /
**            ...
**          end                     \    Code generated
**        end                        |-- by sqlite3WhereEnd()
**      end                         /
**
** Note that the loops might not be nested in the order in which they
** appear in the FROM clause if a different order is better able to make
** use of indices.  Note also that when the IN operator appears in
** the WHERE clause, it might result in additional nested loops for
** scanning through all values on the right-hand side of the IN.
**
** There are Btree cursors associated with each table.  t1 uses cursor
** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
** And so forth.  This routine generates code to open those VDBE cursors
** and sqlite3WhereEnd() generates the code to close them.
**
** The code that sqlite3WhereBegin() generates leaves the cursors named
** in pTabList pointing at their appropriate entries.  The [...] code
** can use OP_Column and OP_Rowid opcodes on these cursors to extract
** data from the various tables of the loop.
**
** If the WHERE clause is empty, the foreach loops must each scan their
** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
** the tables have indices and there are terms in the WHERE clause that
** refer to those indices, a complete table scan can be avoided and the
** code will run much faster.  Most of the work of this routine is checking
** to see if there are indices that can be used to speed up the loop.
**
** Terms of the WHERE clause are also used to limit which rows actually
** make it to the "..." in the middle of the loop.  After each "foreach",
** terms of the WHERE clause that use only terms in that loop and outer
** loops are evaluated and if false a jump is made around all subsequent
** inner loops (or around the "..." if the test occurs within the inner-
** most loop)
**
** OUTER JOINS
**
** An outer join of tables t1 and t2 is conceptally coded as follows:
**
**    foreach row1 in t1 do
**      flag = 0
**      foreach row2 in t2 do
**        start:
**          ...
**          flag = 1
**      end
**      if flag==0 then
**        move the row2 cursor to a null row
**        goto start
**      fi
**    end
**
** ORDER BY CLAUSE PROCESSING
**
** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
** if there is one.  If there is no ORDER BY clause or if this routine
** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
**
** If an index can be used so that the natural output order of the table
** scan is correct for the ORDER BY clause, then that index is used and
** *ppOrderBy is set to NULL.  This is an optimization that prevents an
** unnecessary sort of the result set if an index appropriate for the
** ORDER BY clause already exists.
**
** If the where clause loops cannot be arranged to provide the correct
** output order, then the *ppOrderBy is unchanged.
*/
WhereInfo *sqlite3WhereBegin(
  Parse *pParse,        /* The parser context */
  SrcList *pTabList,    /* A list of all tables to be scanned */
  Expr *pWhere,         /* The WHERE clause */
  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
){
  int i;                     /* Loop counter */
  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
  WhereInfo *pWInfo;         /* Will become the return value of this function */
  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
  Bitmask notReady;          /* Cursors that are not yet positioned */
  WhereMaskSet *pMaskSet;    /* The expression mask set */
  WhereClause *pWC;               /* Decomposition of the WHERE clause */
  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
  WhereLevel *pLevel;             /* A single level in the pWInfo list */
  int iFrom;                      /* First unused FROM clause element */
  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
  sqlite3 *db;               /* Database connection */

  /* The number of tables in the FROM clause is limited by the number of
  ** bits in a Bitmask 
  */
  if( pTabList->nSrc>BMS ){
    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
    return 0;
  }

  /* Allocate and initialize the WhereInfo structure that will become the
  ** return value. A single allocation is used to store the WhereInfo
  ** struct, the contents of WhereInfo.a[], the WhereClause structure
  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  ** some architectures. Hence the ROUND8() below.
  */
  db = pParse->db;
  nByteWInfo = ROUND8(sizeof(WhereInfo)+(pTabList->nSrc-1)*sizeof(WhereLevel));
  pWInfo = sqlite3DbMallocZero(db, 
      nByteWInfo + 
      sizeof(WhereClause) +
      sizeof(WhereMaskSet)
  );
  if( db->mallocFailed ){
    goto whereBeginError;
  }
  pWInfo->nLevel = pTabList->nSrc;
  pWInfo->pParse = pParse;
  pWInfo->pTabList = pTabList;
  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
  pWInfo->wctrlFlags = wctrlFlags;
  pMaskSet = (WhereMaskSet*)&pWC[1];

  /* Split the WHERE clause into separate subexpressions where each
  ** subexpression is separated by an AND operator.
  */
  initMaskSet(pMaskSet);
  whereClauseInit(pWC, pParse, pMaskSet);
  sqlite3ExprCodeConstants(pParse, pWhere);
  whereSplit(pWC, pWhere, TK_AND);
    
  /* Special case: a WHERE clause that is constant.  Evaluate the
  ** expression and either jump over all of the code or fall thru.
  */
  if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
    pWhere = 0;
  }

  /* Assign a bit from the bitmask to every term in the FROM clause.
  **
  ** When assigning bitmask values to FROM clause cursors, it must be
  ** the case that if X is the bitmask for the N-th FROM clause term then
  ** the bitmask for all FROM clause terms to the left of the N-th term
  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
  ** its Expr.iRightJoinTable value to find the bitmask of the right table
  ** of the join.  Subtracting one from the right table bitmask gives a
  ** bitmask for all tables to the left of the join.  Knowing the bitmask
  ** for all tables to the left of a left join is important.  Ticket #3015.
  **
  ** Configure the WhereClause.vmask variable so that bits that correspond
  ** to virtual table cursors are set. This is used to selectively disable 
  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
  ** with virtual tables.
  */
  assert( pWC->vmask==0 && pMaskSet->n==0 );
  for(i=0; i<pTabList->nSrc; i++){
    createMask(pMaskSet, pTabList->a[i].iCursor);
#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
      pWC->vmask |= ((Bitmask)1 << i);
    }
#endif
  }
#ifndef NDEBUG
  {
    Bitmask toTheLeft = 0;
    for(i=0; i<pTabList->nSrc; i++){
      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
      assert( (m-1)==toTheLeft );
      toTheLeft |= m;
    }
  }
#endif

  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
  ** add new virtual terms onto the end of the WHERE clause.  We do not
  ** want to analyze these virtual terms, so start analyzing at the end
  ** and work forward so that the added virtual terms are never processed.
  */
  exprAnalyzeAll(pTabList, pWC);
  if( db->mallocFailed ){
    goto whereBeginError;
  }

  /* Chose the best index to use for each table in the FROM clause.
  **
  ** This loop fills in the following fields:
  **
  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
  **   pWInfo->a[].nEq       The number of == and IN constraints
  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
  **
  ** This loop also figures out the nesting order of tables in the FROM
  ** clause.
  */
  notReady = ~(Bitmask)0;
  pTabItem = pTabList->a;
  pLevel = pWInfo->a;
  andFlags = ~0;
  WHERETRACE(("*** Optimizer Start ***\n"));
  for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
    WhereCost bestPlan;         /* Most efficient plan seen so far */
    Index *pIdx;                /* Index for FROM table at pTabItem */
    int j;                      /* For looping over FROM tables */
    int bestJ = -1;             /* The value of j */
    Bitmask m;                  /* Bitmask value for j or bestJ */
    int isOptimal;              /* Iterator for optimal/non-optimal search */

    memset(&bestPlan, 0, sizeof(bestPlan));
    bestPlan.rCost = SQLITE_BIG_DBL;

    /* Loop through the remaining entries in the FROM clause to find the
    ** next nested loop. The FROM clause entries may be iterated through
    ** either once or twice. 
    **
    ** The first iteration, which is always performed, searches for the
    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
    ** this context an optimal scan is one that uses the same strategy
    ** for the given FROM clause entry as would be selected if the entry
    ** were used as the innermost nested loop.  In other words, a table
    ** is chosen such that the cost of running that table cannot be reduced
    ** by waiting for other tables to run first.
    **
    ** The second iteration is only performed if no optimal scan strategies
    ** were found by the first. This iteration is used to search for the
    ** lowest cost scan overall.
    **
    ** Previous versions of SQLite performed only the second iteration -
    ** the next outermost loop was always that with the lowest overall
    ** cost. However, this meant that SQLite could select the wrong plan
    ** for scripts such as the following:
    **   
    **   CREATE TABLE t1(a, b); 
    **   CREATE TABLE t2(c, d);
    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
    **
    ** The best strategy is to iterate through table t1 first. However it
    ** is not possible to determine this with a simple greedy algorithm.
    ** However, since the cost of a linear scan through table t2 is the same 
    ** as the cost of a linear scan through table t1, a simple greedy 
    ** algorithm may choose to use t2 for the outer loop, which is a much
    ** costlier approach.
    */
    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
      Bitmask mask = (isOptimal ? 0 : notReady);
      assert( (pTabList->nSrc-iFrom)>1 || isOptimal );
      for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
        int doNotReorder;    /* True if this table should not be reordered */
        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
  
        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
        if( j!=iFrom && doNotReorder ) break;
        m = getMask(pMaskSet, pTabItem->iCursor);
        if( (m & notReady)==0 ){
          if( j==iFrom ) iFrom++;
          continue;
        }
        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
  
        assert( pTabItem->pTab );
#ifndef SQLITE_OMIT_VIRTUALTABLE
        if( IsVirtual(pTabItem->pTab) ){
          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
        }else 
#endif
        {
          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
        }
        assert( isOptimal || (sCost.used&notReady)==0 );

        if( (sCost.used&notReady)==0
         && (j==iFrom || sCost.rCost<bestPlan.rCost) 
        ){
          bestPlan = sCost;
          bestJ = j;
        }
        if( doNotReorder ) break;
      }
    }
    assert( bestJ>=0 );
    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
           pLevel-pWInfo->a));
    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
      *ppOrderBy = 0;
    }
    andFlags &= bestPlan.plan.wsFlags;
    pLevel->plan = bestPlan.plan;
    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
      pLevel->iIdxCur = pParse->nTab++;
    }else{
      pLevel->iIdxCur = -1;
    }
    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
    pLevel->iFrom = (u8)bestJ;

    /* Check that if the table scanned by this loop iteration had an
    ** INDEXED BY clause attached to it, that the named index is being
    ** used for the scan. If not, then query compilation has failed.
    ** Return an error.
    */
    pIdx = pTabList->a[bestJ].pIndex;
    if( pIdx ){
      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
        goto whereBeginError;
      }else{
        /* If an INDEXED BY clause is used, the bestIndex() function is
        ** guaranteed to find the index specified in the INDEXED BY clause
        ** if it find an index at all. */
        assert( bestPlan.plan.u.pIdx==pIdx );
      }
    }
  }
  WHERETRACE(("*** Optimizer Finished ***\n"));
  if( pParse->nErr || db->mallocFailed ){
    goto whereBeginError;
  }

  /* If the total query only selects a single row, then the ORDER BY
  ** clause is irrelevant.
  */
  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
    *ppOrderBy = 0;
  }

  /* If the caller is an UPDATE or DELETE statement that is requesting
  ** to use a one-pass algorithm, determine if this is appropriate.
  ** The one-pass algorithm only works if the WHERE clause constraints
  ** the statement to update a single row.
  */
  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
    pWInfo->okOnePass = 1;
    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
  }

  /* Open all tables in the pTabList and any indices selected for
  ** searching those tables.
  */
  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
    Table *pTab;     /* Table to open */
    int iDb;         /* Index of database containing table/index */

#ifndef SQLITE_OMIT_EXPLAIN
    if( pParse->explain==2 ){
      char *zMsg;
      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
      if( pItem->zAlias ){
        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
      }
      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
           zMsg, pLevel->plan.u.pIdx->zName);
      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
      }
#ifndef SQLITE_OMIT_VIRTUALTABLE
      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
                    pVtabIdx->idxNum, pVtabIdx->idxStr);
      }
#endif
      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
      }
      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
    }
#endif /* SQLITE_OMIT_EXPLAIN */
    pTabItem = &pTabList->a[pLevel->iFrom];
    pTab = pTabItem->pTab;
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
#ifndef SQLITE_OMIT_VIRTUALTABLE
    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
      int iCur = pTabItem->iCursor;
      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
    }else
#endif
    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
        Bitmask b = pTabItem->colUsed;
        int n = 0;
        for(; b; b=b>>1, n++){}
        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, SQLITE_INT_TO_PTR(n), P4_INT32);
        assert( n<=pTab->nCol );
      }
    }else{
      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
    }
    pLevel->iTabCur = pTabItem->iCursor;
    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
      Index *pIx = pLevel->plan.u.pIdx;
      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
      int iIdxCur = pLevel->iIdxCur;
      assert( pIx->pSchema==pTab->pSchema );
      assert( iIdxCur>=0 );
      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
                        (char*)pKey, P4_KEYINFO_HANDOFF);
      VdbeComment((v, "%s", pIx->zName));
    }
    sqlite3CodeVerifySchema(pParse, iDb);
  }
  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);

  /* Generate the code to do the search.  Each iteration of the for
  ** loop below generates code for a single nested loop of the VM
  ** program.
  */
  notReady = ~(Bitmask)0;
  for(i=0; i<pTabList->nSrc; i++){
    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
    pWInfo->iContinue = pWInfo->a[i].addrCont;
  }

#ifdef SQLITE_TEST  /* For testing and debugging use only */
  /* Record in the query plan information about the current table
  ** and the index used to access it (if any).  If the table itself
  ** is not used, its name is just '{}'.  If no index is used
  ** the index is listed as "{}".  If the primary key is used the
  ** index name is '*'.
  */
  for(i=0; i<pTabList->nSrc; i++){
    char *z;
    int n;
    pLevel = &pWInfo->a[i];
    pTabItem = &pTabList->a[pLevel->iFrom];
    z = pTabItem->zAlias;
    if( z==0 ) z = pTabItem->pTab->zName;
    n = sqlite3Strlen30(z);
    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
        nQPlan += 2;
      }else{
        memcpy(&sqlite3_query_plan[nQPlan], z, n);
        nQPlan += n;
      }
      sqlite3_query_plan[nQPlan++] = ' ';
    }
    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
      nQPlan += 2;
    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
        nQPlan += n;
        sqlite3_query_plan[nQPlan++] = ' ';
      }
    }else{
      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
      nQPlan += 3;
    }
  }
  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
    sqlite3_query_plan[--nQPlan] = 0;
  }
  sqlite3_query_plan[nQPlan] = 0;
  nQPlan = 0;
#endif /* SQLITE_TEST // Testing and debugging use only */

  /* Record the continuation address in the WhereInfo structure.  Then
  ** clean up and return.
  */
  return pWInfo;

  /* Jump here if malloc fails */
whereBeginError:
  whereInfoFree(db, pWInfo);
  return 0;
}

/*
** Generate the end of the WHERE loop.  See comments on 
** sqlite3WhereBegin() for additional information.
*/
void sqlite3WhereEnd(WhereInfo *pWInfo){
  Parse *pParse = pWInfo->pParse;
  Vdbe *v = pParse->pVdbe;
  int i;
  WhereLevel *pLevel;
  SrcList *pTabList = pWInfo->pTabList;
  sqlite3 *db = pParse->db;

  /* Generate loop termination code.
  */
  sqlite3ExprCacheClear(pParse);
  for(i=pTabList->nSrc-1; i>=0; i--){
    pLevel = &pWInfo->a[i];
    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
    if( pLevel->op!=OP_Noop ){
      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
      sqlite3VdbeChangeP5(v, pLevel->p5);
    }
    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
      struct InLoop *pIn;
      int j;
      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
      }
      sqlite3DbFree(db, pLevel->u.in.aInLoop);
    }
    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
    if( pLevel->iLeftJoin ){
      int addr;
      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
      sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
      if( pLevel->iIdxCur>=0 ){
        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
      }
      if( pLevel->op==OP_Return ){
        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
      }else{
        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
      }
      sqlite3VdbeJumpHere(v, addr);
    }
  }

  /* The "break" point is here, just past the end of the outer loop.
  ** Set it.
  */
  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);

  /* Close all of the cursors that were opened by sqlite3WhereBegin.
  */
  for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
    Table *pTab = pTabItem->pTab;
    assert( pTab!=0 );
    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
    if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
      if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
      }
      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
      }
    }

    /* If this scan uses an index, make code substitutions to read data
    ** from the index in preference to the table. Sometimes, this means
    ** the table need never be read from. This is a performance boost,
    ** as the vdbe level waits until the table is read before actually
    ** seeking the table cursor to the record corresponding to the current
    ** position in the index.
    ** 
    ** Calls to the code generator in between sqlite3WhereBegin and
    ** sqlite3WhereEnd will have created code that references the table
    ** directly.  This loop scans all that code looking for opcodes
    ** that reference the table and converts them into opcodes that
    ** reference the index.
    */
    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
      int k, j, last;
      VdbeOp *pOp;
      Index *pIdx = pLevel->plan.u.pIdx;
      int useIndexOnly = pLevel->plan.wsFlags & WHERE_IDX_ONLY;

      assert( pIdx!=0 );
      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
      last = sqlite3VdbeCurrentAddr(v);
      for(k=pWInfo->iTop; k<last; k++, pOp++){
        if( pOp->p1!=pLevel->iTabCur ) continue;
        if( pOp->opcode==OP_Column ){
          for(j=0; j<pIdx->nColumn; j++){
            if( pOp->p2==pIdx->aiColumn[j] ){
              pOp->p2 = j;
              pOp->p1 = pLevel->iIdxCur;
              break;
            }
          }
          assert(!useIndexOnly || j<pIdx->nColumn);
        }else if( pOp->opcode==OP_Rowid ){
          pOp->p1 = pLevel->iIdxCur;
          pOp->opcode = OP_IdxRowid;
        }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
          pOp->opcode = OP_Noop;
        }
      }
    }
  }

  /* Final cleanup
  */
  whereInfoFree(db, pWInfo);
  return;
}

Added test/aggerror.test.





























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 2006 January 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for calling sqlite3_result_error()
# from within an aggregate function implementation.
#
# $Id: aggerror.test,v 1.3 2006/05/03 23:34:06 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Add the x_count aggregate function to the database handle.
# x_count will error out if its input is 40 or 41 or if its
# final results is 42.  Make sure that such errors are handled
# appropriately.
#
do_test aggerror-1.1 {
  set DB [sqlite3_connection_pointer db]
  sqlite3_create_aggregate $DB
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 SELECT a+2 FROM t1;
    INSERT INTO t1 SELECT a+4 FROM t1;
    INSERT INTO t1 SELECT a+8 FROM t1;
    INSERT INTO t1 SELECT a+16 FROM t1;
    INSERT INTO t1 SELECT a+32 FROM t1 ORDER BY a LIMIT 7;
    SELECT x_count(*) FROM t1;
  }
} {39}
do_test aggerror-1.2 {
  execsql {
    INSERT INTO t1 VALUES(40);
    SELECT x_count(*) FROM t1;
  }
} {40}
do_test aggerror-1.3 {
  catchsql {
    SELECT x_count(a) FROM t1;
  }
} {1 {value of 40 handed to x_count}}
ifcapable utf16 {
  do_test aggerror-1.4 {
    execsql {
      UPDATE t1 SET a=41 WHERE a=40
    }
    catchsql {
      SELECT x_count(a) FROM t1;
    }
  } {1 abc}
}
do_test aggerror-1.5 {
  execsql {
    SELECT x_count(*) FROM t1
  }
} 40
do_test aggerror-1.6 {
  execsql {
    INSERT INTO t1 VALUES(40);
    INSERT INTO t1 VALUES(42);
  }
  catchsql {
    SELECT x_count(*) FROM t1;
  }
} {1 {x_count totals to 42}}

finish_test

Added test/alias.test.

























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# 2008 August 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this script is correct code generation of aliased result-set
# values.  See ticket #3343.
#
# $Id: alias.test,v 1.3 2009/04/23 13:22:44 drh Exp $
#
set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Aliases are currently evaluated twice.  We might try to change this
# in the future.  But not now.
return

# A procedure to return a sequence of increasing integers.
#
namespace eval ::seq {
  variable counter 0
  proc value {args} {
    variable counter
    incr counter
    return $counter
  }
  proc reset {} {
    variable counter
    set counter 0
  }
}


do_test alias-1.1 {
  db function sequence ::seq::value
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(9);
    INSERT INTO t1 VALUES(8);
    INSERT INTO t1 VALUES(7);
    SELECT x, sequence() FROM t1;
  }
} {9 1 8 2 7 3}
do_test alias-1.2 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1 WHERE y>0
  }
} {9 1 8 2 7 3}
do_test alias-1.3 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1 WHERE y>0 AND y<99
  }
} {9 1 8 2 7 3}
do_test alias-1.4 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1 WHERE y>0 AND y<99 AND y!=55
  }
} {9 1 8 2 7 3}
do_test alias-1.5 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1
     WHERE y>0 AND y<99 AND y!=55 AND y NOT IN (56,57,58)
       AND y NOT LIKE 'abc%' AND y%10==2
  }
} {8 2}
do_test alias-1.6 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1 WHERE y BETWEEN 0 AND 99
  }
} {9 1 8 2 7 3}
#do_test alias-1.7 {
#  ::seq::reset
#  db eval {
#    SELECT x, sequence() AS y FROM t1 WHERE y IN (55,66,3)
#  }
#} {7 3}
do_test alias-1.8 {
  ::seq::reset
  db eval {
    SELECT x, 1-sequence() AS y FROM t1 ORDER BY y
  }
} {7 -2 8 -1 9 0}
do_test alias-1.9 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1 ORDER BY -y
  }
} {7 3 8 2 9 1}
do_test alias-1.10 {
  ::seq::reset
  db eval {
    SELECT x, sequence() AS y FROM t1 ORDER BY x%2, y
  }
} {8 2 9 1 7 3}

unset -nocomplain random_int_list
set random_int_list [db eval {
   SELECT random()&2147483647 AS r FROM t1, t1, t1, t1 ORDER BY r
}]
do_test alias-1.11 {
  lsort -integer $::random_int_list
} $random_int_list


do_test alias-2.1 {
  db eval {
    SELECT 4 UNION SELECT 1 ORDER BY 1
  }
} {1 4}
do_test alias-2.2 {
  db eval {
    SELECT 4 UNION SELECT 1 UNION SELECT 9 ORDER BY 1
  }
} {1 4 9}

if 0 {
  # Aliases in the GROUP BY clause cause the expression to be evaluated
  # twice in the current implementation.  This might change in the future.
  #
  do_test alias-3.1 {
    ::seq::reset
    db eval {
      SELECT sequence(*) AS y, count(*) AS z FROM t1 GROUP BY y ORDER BY z, y
    }
  } {1 1 2 1 3 1}
}

finish_test

Added test/all.test.

































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all tests.
#
# $Id: all.test,v 1.62 2009/01/06 18:43:51 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
rename finish_test really_finish_test
proc finish_test {} {
  catch {db close}
  show_memstats
}

if {[file exists ./sqlite_test_count]} {
  set COUNT [exec cat ./sqlite_test_count]
} else {
  set COUNT 1
}

if {[llength $argv]>0} {
  foreach {name value} $argv {
    switch -- $name {
      -count {
         set COUNT $value
      }
      -quick {
         set ISQUICK $value
      }
      -soak {
         set SOAKTEST $value
      }
      default {
         puts stderr "Unknown option: $name"
         exit
      }
    }
  }
}
set argv {}

# LeakList will hold a list of the number of unfreed mallocs after
# each round of the test.  This number should be constant.  If it
# grows, it may mean there is a memory leak in the library.
#
set LeakList {}

set EXCLUDE {}
lappend EXCLUDE all.test               ;# This file
lappend EXCLUDE async.test
lappend EXCLUDE crash.test             ;# Run seperately later.
lappend EXCLUDE crash2.test            ;# Run seperately later.
lappend EXCLUDE quick.test             ;# Alternate test driver script
lappend EXCLUDE veryquick.test         ;# Alternate test driver script
lappend EXCLUDE malloc.test            ;# Run seperately later.
lappend EXCLUDE misuse.test            ;# Run seperately later.
lappend EXCLUDE memleak.test           ;# Alternate test driver script
lappend EXCLUDE permutations.test      ;# Run seperately later.
lappend EXCLUDE soak.test              ;# Takes a very long time (default 1 hr)
lappend EXCLUDE fts3.test              ;# Wrapper for muliple fts3*.tests
lappend EXCLUDE mallocAll.test         ;# Wrapper for running all malloc tests

# Files to include in the test.  If this list is empty then everything
# that is not in the EXCLUDE list is run.
#
set INCLUDE {
}

for {set Counter 0} {$Counter<$COUNT && $nErr==0} {incr Counter} {
  foreach testfile [lsort -dictionary [glob $testdir/*.test]] {
    set tail [file tail $testfile]
    if {[lsearch -exact $EXCLUDE $tail]>=0} continue
    if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue
    reset_prng_state
    source $testfile
    catch {db close}
    if {$sqlite_open_file_count>0} {
      puts "$tail did not close all files: $sqlite_open_file_count"
      incr nErr
      lappend ::failList $tail
      set sqlite_open_file_count 0
    }
  }
  if {[info exists Leak]} {
    lappend LeakList $Leak
  }
}
set argv all
source $testdir/permutations.test
set argv ""

# Do one last test to look for a memory leak in the library.  This will
# only work if SQLite is compiled with the -DSQLITE_DEBUG=1 flag.
#
if {$LeakList!=""} {
  puts -nonewline memory-leak-test...
  incr ::nTest
  foreach x $LeakList {
    if {$x!=[lindex $LeakList 0]} {
       puts " failed!"
       puts "Expected: all values to be the same"
       puts "     Got: $LeakList"
       incr ::nErr
       lappend ::failList memory-leak-test
       break
    }
  }
  puts " Ok"
}

# Run the crashtest only on unix and only once. If the library does not
# always create auto-vacuum databases, also run autovacuum_crash.test.
#
if {$::tcl_platform(platform)=="unix"} {
  source $testdir/crash.test
  source $testdir/crash2.test
  ifcapable !default_autovacuum {
    set argv autovacuum_crash
    source $testdir/permutations.test
    set argv ""
  }
}

# Run the malloc tests and the misuse test after memory leak detection.
# Both tests leak memory. Currently, misuse.test also leaks a handful of
# file descriptors. This is not considered a problem, but can cause tests
# in malloc.test to fail. So set the open-file count to zero before running
# malloc.test to get around this.
#
catch {source $testdir/misuse.test}
set sqlite_open_file_count 0
catch {source $testdir/malloc.test}

catch {db close}
set sqlite_open_file_count 0
really_finish_test

Added test/alter.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
# 2004 November 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the ALTER TABLE statement.
#
# $Id: alter.test,v 1.32 2009/03/24 15:08:10 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_OMIT_ALTERTABLE is defined, omit this file.
ifcapable !altertable {
  finish_test
  return
}

#----------------------------------------------------------------------
# Test organization:
#
# alter-1.1.* - alter-1.7.*: Basic tests of ALTER TABLE, including tables
#     with implicit and explicit indices. These tests came from an earlier
#     fork of SQLite that also supported ALTER TABLE.
# alter-1.8.*: Tests for ALTER TABLE when the table resides in an 
#     attached database.
# alter-1.9.*: Tests for ALTER TABLE when their is whitespace between the
#     table name and left parenthesis token. i.e: 
#     "CREATE TABLE abc       (a, b, c);"
# alter-2.*: Test error conditions and messages.
# alter-3.*: Test ALTER TABLE on tables that have TRIGGERs attached to them.
# alter-4.*: Test ALTER TABLE on tables that have AUTOINCREMENT fields.
# ...
# alter-12.*: Test ALTER TABLE on views.
#

# Create some tables to rename.  Be sure to include some TEMP tables
# and some tables with odd names.
#
do_test alter-1.1 {
  ifcapable tempdb {
    set ::temp TEMP
  } else {
    set ::temp {}
  }
  execsql [subst -nocommands {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    CREATE TABLE [t1'x1](c UNIQUE, b PRIMARY KEY);
    INSERT INTO [t1'x1] VALUES(3,4);
    CREATE INDEX t1i1 ON T1(B);
    CREATE INDEX t1i2 ON t1(a,b);
    CREATE INDEX i3 ON [t1'x1](b,c);
    CREATE $::temp TABLE "temp table"(e,f,g UNIQUE);
    CREATE INDEX i2 ON [temp table](f);
    INSERT INTO [temp table] VALUES(5,6,7);
  }]
  execsql {
    SELECT 't1', * FROM t1;
    SELECT 't1''x1', * FROM "t1'x1";
    SELECT * FROM [temp table];
  }
} {t1 1 2 t1'x1 3 4 5 6 7}
do_test alter-1.2 {
  execsql [subst {
    CREATE $::temp TABLE objlist(type, name, tbl_name);
    INSERT INTO objlist SELECT type, name, tbl_name 
        FROM sqlite_master WHERE NAME!='objlist';
  }]
  ifcapable tempdb {
    execsql {
      INSERT INTO objlist SELECT type, name, tbl_name 
          FROM sqlite_temp_master WHERE NAME!='objlist';
    }
  }

  execsql {
    SELECT type, name, tbl_name FROM objlist ORDER BY tbl_name, type desc, name;
  }
} [list \
     table t1                              t1             \
     index t1i1                            t1             \
     index t1i2                            t1             \
     table t1'x1                           t1'x1          \
     index i3                              t1'x1          \
     index {sqlite_autoindex_t1'x1_1}      t1'x1          \
     index {sqlite_autoindex_t1'x1_2}      t1'x1          \
     table {temp table}                    {temp table}   \
     index i2                              {temp table}   \
     index {sqlite_autoindex_temp table_1} {temp table}   \
  ]

# Make some changes
#
integrity_check alter-1.3.0
do_test alter-1.3 {
  execsql {
    ALTER TABLE [T1] RENAME to [-t1-];
    ALTER TABLE "t1'x1" RENAME TO T2;
    ALTER TABLE [temp table] RENAME to TempTab;
  }
} {}
integrity_check alter-1.3.1
do_test alter-1.4 {
  execsql {
    SELECT 't1', * FROM [-t1-];
    SELECT 't2', * FROM t2;
    SELECT * FROM temptab;
  }
} {t1 1 2 t2 3 4 5 6 7}
do_test alter-1.5 {
  execsql {
    DELETE FROM objlist;
    INSERT INTO objlist SELECT type, name, tbl_name
        FROM sqlite_master WHERE NAME!='objlist';
  }
  catchsql {
    INSERT INTO objlist SELECT type, name, tbl_name 
        FROM sqlite_temp_master WHERE NAME!='objlist';
  }
  execsql {
    SELECT type, name, tbl_name FROM objlist ORDER BY tbl_name, type desc, name;
  }
} [list \
     table -t1-                         -t1-        \
     index t1i1                         -t1-        \
     index t1i2                         -t1-        \
     table T2                           T2          \
     index i3                           T2          \
     index {sqlite_autoindex_T2_1}      T2          \
     index {sqlite_autoindex_T2_2}      T2          \
     table {TempTab}                    {TempTab}   \
     index i2                           {TempTab}   \
     index {sqlite_autoindex_TempTab_1} {TempTab}   \
  ]

# Make sure the changes persist after restarting the database.
# (The TEMP table will not persist, of course.)
#
ifcapable tempdb {
  do_test alter-1.6 {
    db close
    sqlite3 db test.db
    set DB [sqlite3_connection_pointer db]
    execsql {
      CREATE TEMP TABLE objlist(type, name, tbl_name);
      INSERT INTO objlist SELECT type, name, tbl_name FROM sqlite_master;
      INSERT INTO objlist 
          SELECT type, name, tbl_name FROM sqlite_temp_master 
          WHERE NAME!='objlist';
      SELECT type, name, tbl_name FROM objlist 
          ORDER BY tbl_name, type desc, name;
    }
  } [list \
       table -t1-                         -t1-           \
       index t1i1                         -t1-           \
       index t1i2                         -t1-           \
       table T2                           T2          \
       index i3                           T2          \
       index {sqlite_autoindex_T2_1}      T2          \
       index {sqlite_autoindex_T2_2}      T2          \
    ]
} else {
  execsql {
    DROP TABLE TempTab;
  }
}

# Make sure the ALTER TABLE statements work with the
# non-callback API
#
do_test alter-1.7 {
  stepsql $DB {
    ALTER TABLE [-t1-] RENAME to [*t1*];
    ALTER TABLE T2 RENAME TO [<t2>];
  }
  execsql {
    DELETE FROM objlist;
    INSERT INTO objlist SELECT type, name, tbl_name
        FROM sqlite_master WHERE NAME!='objlist';
  }
  catchsql {
    INSERT INTO objlist SELECT type, name, tbl_name 
        FROM sqlite_temp_master WHERE NAME!='objlist';
  }
  execsql {
    SELECT type, name, tbl_name FROM objlist ORDER BY tbl_name, type desc, name;
  }
} [list \
     table *t1*                         *t1*           \
     index t1i1                         *t1*           \
     index t1i2                         *t1*           \
     table <t2>                         <t2>          \
     index i3                           <t2>          \
     index {sqlite_autoindex_<t2>_1}    <t2>          \
     index {sqlite_autoindex_<t2>_2}    <t2>          \
  ]

# Check that ALTER TABLE works on attached databases.
#
ifcapable attach {
  do_test alter-1.8.1 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      ATTACH 'test2.db' AS aux;
    }
  } {}
  do_test alter-1.8.2 {
    execsql {
      CREATE TABLE t4(a PRIMARY KEY, b, c);
      CREATE TABLE aux.t4(a PRIMARY KEY, b, c);
      CREATE INDEX i4 ON t4(b);
      CREATE INDEX aux.i4 ON t4(b);
    }
  } {}
  do_test alter-1.8.3 {
    execsql {
      INSERT INTO t4 VALUES('main', 'main', 'main');
      INSERT INTO aux.t4 VALUES('aux', 'aux', 'aux');
      SELECT * FROM t4 WHERE a = 'main';
    }
  } {main main main}
  do_test alter-1.8.4 {
    execsql {
      ALTER TABLE t4 RENAME TO t5;
      SELECT * FROM t4 WHERE a = 'aux';
    }
  } {aux aux aux}
  do_test alter-1.8.5 {
    execsql {
      SELECT * FROM t5;
    }
  } {main main main}
  do_test alter-1.8.6 {
    execsql {
      SELECT * FROM t5 WHERE b = 'main';
    }
  } {main main main}
  do_test alter-1.8.7 {
    execsql {
      ALTER TABLE aux.t4 RENAME TO t5;
      SELECT * FROM aux.t5 WHERE b = 'aux';
    }
  } {aux aux aux}
}

do_test alter-1.9.1 {
  execsql {
    CREATE TABLE tbl1   (a, b, c);
    INSERT INTO tbl1 VALUES(1, 2, 3);
  }
} {}
do_test alter-1.9.2 {
  execsql {
    SELECT * FROM tbl1;
  }
} {1 2 3}
do_test alter-1.9.3 {
  execsql {
    ALTER TABLE tbl1 RENAME TO tbl2;
    SELECT * FROM tbl2;
  }
} {1 2 3}
do_test alter-1.9.4 {
  execsql {
    DROP TABLE tbl2;
  }
} {}

# Test error messages
#
do_test alter-2.1 {
  catchsql {
    ALTER TABLE none RENAME TO hi;
  }
} {1 {no such table: none}}
do_test alter-2.2 {
  execsql {
    CREATE TABLE t3(p,q,r);
  }
  catchsql {
    ALTER TABLE [<t2>] RENAME TO t3;
  }
} {1 {there is already another table or index with this name: t3}}
do_test alter-2.3 {
  catchsql {
    ALTER TABLE [<t2>] RENAME TO i3;
  }
} {1 {there is already another table or index with this name: i3}}
do_test alter-2.4 {
  catchsql {
    ALTER TABLE SqLiTe_master RENAME TO master;
  }
} {1 {table sqlite_master may not be altered}}
do_test alter-2.5 {
  catchsql {
    ALTER TABLE t3 RENAME TO sqlite_t3;
  }
} {1 {object name reserved for internal use: sqlite_t3}}
do_test alter-2.6 {
  catchsql {
    ALTER TABLE t3 ADD COLUMN (ALTER TABLE t3 ADD COLUMN);
  }
} {1 {near "(": syntax error}}

# If this compilation does not include triggers, omit the alter-3.* tests.
ifcapable trigger {

#-----------------------------------------------------------------------
# Tests alter-3.* test ALTER TABLE on tables that have triggers.
#
# alter-3.1.*: ALTER TABLE with triggers.
# alter-3.2.*: Test that the ON keyword cannot be used as a database,
#     table or column name unquoted. This is done because part of the
#     ALTER TABLE code (specifically the implementation of SQL function
#     "sqlite_alter_trigger") will break in this case.
# alter-3.3.*: ALTER TABLE with TEMP triggers (todo).
#

# An SQL user-function for triggers to fire, so that we know they
# are working.
proc trigfunc {args} {
  set ::TRIGGER $args
}
db func trigfunc trigfunc

do_test alter-3.1.0 {
  execsql {
    CREATE TABLE t6(a, b, c);
    CREATE TRIGGER trig1 AFTER INSERT ON t6 BEGIN
      SELECT trigfunc('trig1', new.a, new.b, new.c);
    END;
  }
} {}
do_test alter-3.1.1 {
  execsql {
    INSERT INTO t6 VALUES(1, 2, 3);
  }
  set ::TRIGGER
} {trig1 1 2 3}
do_test alter-3.1.2 {
  execsql {
    ALTER TABLE t6 RENAME TO t7;
    INSERT INTO t7 VALUES(4, 5, 6);
  }
  set ::TRIGGER
} {trig1 4 5 6}
do_test alter-3.1.3 {
  execsql {
    DROP TRIGGER trig1;
  }
} {}
do_test alter-3.1.4 {
  execsql {
    CREATE TRIGGER trig2 AFTER INSERT ON main.t7 BEGIN
      SELECT trigfunc('trig2', new.a, new.b, new.c);
    END;
    INSERT INTO t7 VALUES(1, 2, 3);
  }
  set ::TRIGGER
} {trig2 1 2 3}
do_test alter-3.1.5 {
  execsql {
    ALTER TABLE t7 RENAME TO t8;
    INSERT INTO t8 VALUES(4, 5, 6);
  }
  set ::TRIGGER
} {trig2 4 5 6}
do_test alter-3.1.6 {
  execsql {
    DROP TRIGGER trig2;
  }
} {}
do_test alter-3.1.7 {
  execsql {
    CREATE TRIGGER trig3 AFTER INSERT ON main.'t8'BEGIN
      SELECT trigfunc('trig3', new.a, new.b, new.c);
    END;
    INSERT INTO t8 VALUES(1, 2, 3);
  }
  set ::TRIGGER
} {trig3 1 2 3}
do_test alter-3.1.8 {
  execsql {
    ALTER TABLE t8 RENAME TO t9;
    INSERT INTO t9 VALUES(4, 5, 6);
  }
  set ::TRIGGER
} {trig3 4 5 6}

# Make sure "ON" cannot be used as a database, table or column name without
# quoting. Otherwise the sqlite_alter_trigger() function might not work.
file delete -force test3.db
file delete -force test3.db-journal
ifcapable attach {
  do_test alter-3.2.1 {
    catchsql {
      ATTACH 'test3.db' AS ON;
    }
  } {1 {near "ON": syntax error}}
  do_test alter-3.2.2 {
    catchsql {
      ATTACH 'test3.db' AS 'ON';
    }
  } {0 {}}
  do_test alter-3.2.3 {
    catchsql {
      CREATE TABLE ON.t1(a, b, c); 
    }
  } {1 {near "ON": syntax error}}
  do_test alter-3.2.4 {
    catchsql {
      CREATE TABLE 'ON'.t1(a, b, c); 
    }
  } {0 {}}
  do_test alter-3.2.4 {
    catchsql {
      CREATE TABLE 'ON'.ON(a, b, c); 
    }
  } {1 {near "ON": syntax error}}
  do_test alter-3.2.5 {
    catchsql {
      CREATE TABLE 'ON'.'ON'(a, b, c); 
    }
  } {0 {}}
}
do_test alter-3.2.6 {
  catchsql {
    CREATE TABLE t10(a, ON, c);
  }
} {1 {near "ON": syntax error}}
do_test alter-3.2.7 {
  catchsql {
    CREATE TABLE t10(a, 'ON', c);
  }
} {0 {}}
do_test alter-3.2.8 {
  catchsql {
    CREATE TRIGGER trig4 AFTER INSERT ON ON BEGIN SELECT 1; END;
  }
} {1 {near "ON": syntax error}}
ifcapable attach {
  do_test alter-3.2.9 {
    catchsql {
      CREATE TRIGGER 'on'.trig4 AFTER INSERT ON 'ON' BEGIN SELECT 1; END;
    }
  } {0 {}}
}
do_test alter-3.2.10 {
  execsql {
    DROP TABLE t10;
  }
} {}

do_test alter-3.3.1 {
  execsql [subst {
    CREATE TABLE tbl1(a, b, c);
    CREATE $::temp TRIGGER trig1 AFTER INSERT ON tbl1 BEGIN
      SELECT trigfunc('trig1', new.a, new.b, new.c);
    END;
  }]
} {}
do_test alter-3.3.2 {
  execsql {
    INSERT INTO tbl1 VALUES('a', 'b', 'c');
  }
  set ::TRIGGER
} {trig1 a b c}
do_test alter-3.3.3 {
  execsql {
    ALTER TABLE tbl1 RENAME TO tbl2;
    INSERT INTO tbl2 VALUES('d', 'e', 'f');
  } 
  set ::TRIGGER
} {trig1 d e f}
do_test alter-3.3.4 {
  execsql [subst {
    CREATE $::temp TRIGGER trig2 AFTER UPDATE ON tbl2 BEGIN
      SELECT trigfunc('trig2', new.a, new.b, new.c);
    END;
  }] 
} {}
do_test alter-3.3.5 {
  execsql {
    ALTER TABLE tbl2 RENAME TO tbl3;
    INSERT INTO tbl3 VALUES('g', 'h', 'i');
  } 
  set ::TRIGGER
} {trig1 g h i}
do_test alter-3.3.6 {
  execsql {
    UPDATE tbl3 SET a = 'G' where a = 'g';
  } 
  set ::TRIGGER
} {trig2 G h i}
do_test alter-3.3.7 {
  execsql {
    DROP TABLE tbl3;
  }
} {}
ifcapable tempdb {
  do_test alter-3.3.8 {
    execsql {
      SELECT * FROM sqlite_temp_master WHERE type = 'trigger';
    }
  } {}
}

} ;# ifcapable trigger

# If the build does not include AUTOINCREMENT fields, omit alter-4.*.
ifcapable autoinc {

do_test alter-4.1 {
  execsql {
    CREATE TABLE tbl1(a INTEGER PRIMARY KEY AUTOINCREMENT);
    INSERT INTO tbl1 VALUES(10);
  }
} {}
do_test alter-4.2 {
  execsql {
    INSERT INTO tbl1 VALUES(NULL);
    SELECT a FROM tbl1;
  }
} {10 11}
do_test alter-4.3 {
  execsql {
    ALTER TABLE tbl1 RENAME TO tbl2;
    DELETE FROM tbl2;
    INSERT INTO tbl2 VALUES(NULL);
    SELECT a FROM tbl2;
  }
} {12}
do_test alter-4.4 {
  execsql {
    DROP TABLE tbl2;
  }
} {}

} ;# ifcapable autoinc

# Test that it is Ok to execute an ALTER TABLE immediately after
# opening a database.
do_test alter-5.1 {
  execsql {
    CREATE TABLE tbl1(a, b, c);
    INSERT INTO tbl1 VALUES('x', 'y', 'z');
  }
} {}
do_test alter-5.2 {
  sqlite3 db2 test.db
  execsql {
    ALTER TABLE tbl1 RENAME TO tbl2;
    SELECT * FROM tbl2;
  } db2
} {x y z}
do_test alter-5.3 {
  db2 close
} {}

foreach tblname [execsql {
  SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite%'
}] {
  execsql "DROP TABLE \"$tblname\""
}

set ::tbl_name "abc\uABCDdef"
do_test alter-6.1 {
  string length $::tbl_name
} {7}
do_test alter-6.2 {
  execsql "
    CREATE TABLE ${tbl_name}(a, b, c);
  "
  set ::oid [execsql {SELECT max(oid) FROM sqlite_master}]
  execsql "
    SELECT sql FROM sqlite_master WHERE oid = $::oid;
  "
} "{CREATE TABLE ${::tbl_name}(a, b, c)}"
execsql "
  SELECT * FROM ${::tbl_name}
"
set ::tbl_name2 "abcXdef"
do_test alter-6.3 {
  execsql "
    ALTER TABLE $::tbl_name RENAME TO $::tbl_name2 
  "
  execsql "
    SELECT sql FROM sqlite_master WHERE oid = $::oid
  "
} "{CREATE TABLE \"${::tbl_name2}\"(a, b, c)}"
do_test alter-6.4 {
  execsql "
    ALTER TABLE $::tbl_name2 RENAME TO $::tbl_name
  "
  execsql "
    SELECT sql FROM sqlite_master WHERE oid = $::oid
  "
} "{CREATE TABLE \"${::tbl_name}\"(a, b, c)}"
set ::col_name ghi\1234\jkl
do_test alter-6.5 {
  execsql "
    ALTER TABLE $::tbl_name ADD COLUMN $::col_name VARCHAR
  "
  execsql "
    SELECT sql FROM sqlite_master WHERE oid = $::oid
  "
} "{CREATE TABLE \"${::tbl_name}\"(a, b, c, $::col_name VARCHAR)}"
set ::col_name2 B\3421\A
do_test alter-6.6 {
  db close
  sqlite3 db test.db
  execsql "
    ALTER TABLE $::tbl_name ADD COLUMN $::col_name2
  "
  execsql "
    SELECT sql FROM sqlite_master WHERE oid = $::oid
  "
} "{CREATE TABLE \"${::tbl_name}\"(a, b, c, $::col_name VARCHAR, $::col_name2)}"
do_test alter-6.7 {
  execsql "
    INSERT INTO ${::tbl_name} VALUES(1, 2, 3, 4, 5);
    SELECT $::col_name, $::col_name2 FROM $::tbl_name;
  "
} {4 5}

# Ticket #1665:  Make sure ALTER TABLE ADD COLUMN works on a table
# that includes a COLLATE clause.
#
do_test alter-7.1 {
  execsql {
    CREATE TABLE t1(a TEXT COLLATE BINARY);
    ALTER TABLE t1 ADD COLUMN b INTEGER COLLATE NOCASE;
    INSERT INTO t1 VALUES(1,'-2');
    INSERT INTO t1 VALUES(5.4e-08,'5.4e-08');
    SELECT typeof(a), a, typeof(b), b FROM t1;
  }
} {text 1 integer -2 text 5.4e-08 real 5.4e-08}

# Make sure that when a column is added by ALTER TABLE ADD COLUMN and has
# a default value that the default value is used by aggregate functions.
#
do_test alter-8.1 {
  execsql {
    CREATE TABLE t2(a INTEGER);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    ALTER TABLE t2 ADD COLUMN b INTEGER DEFAULT 9;
    SELECT sum(b) FROM t2;
  }
} {27}
do_test alter-8.2 {
  execsql {
    SELECT a, sum(b) FROM t2 GROUP BY a;
  }
} {1 18 2 9}

#--------------------------------------------------------------------------
# alter-9.X - Special test: Make sure the sqlite_rename_trigger() and
# rename_table() functions do not crash when handed bad input.
#
ifcapable trigger {
  do_test alter-9.1 {
    execsql {SELECT SQLITE_RENAME_TRIGGER(0,0)}
  } {{}}
}
do_test alter-9.2 {
  execsql {
    SELECT SQLITE_RENAME_TABLE(0,0);
    SELECT SQLITE_RENAME_TABLE(10,20);
    SELECT SQLITE_RENAME_TABLE('foo', 'foo');
  }
} {{} {} {}}

#------------------------------------------------------------------------
# alter-10.X - Make sure ALTER TABLE works with multi-byte UTF-8 characters 
# in the names.
#
do_test alter-10.1 {
  execsql "CREATE TABLE xyz(x UNIQUE)"
  execsql "ALTER TABLE xyz RENAME TO xyz\u1234abc"
  execsql {SELECT name FROM sqlite_master WHERE name LIKE 'xyz%'}
} [list xyz\u1234abc]
do_test alter-10.2 {
  execsql {SELECT name FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
} [list sqlite_autoindex_xyz\u1234abc_1]
do_test alter-10.3 {
  execsql "ALTER TABLE xyz\u1234abc RENAME TO xyzabc"
  execsql {SELECT name FROM sqlite_master WHERE name LIKE 'xyz%'}
} [list xyzabc]
do_test alter-10.4 {
  execsql {SELECT name FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
} [list sqlite_autoindex_xyzabc_1]

do_test alter-11.1 {
  sqlite3_exec db {CREATE TABLE t11(%c6%c6)}
  execsql {
    ALTER TABLE t11 ADD COLUMN abc;
  }
  catchsql {
    ALTER TABLE t11 ADD COLUMN abc;
  }
} {1 {duplicate column name: abc}}
set isutf16 [regexp 16 [db one {PRAGMA encoding}]]
if {!$isutf16} {
  do_test alter-11.2 {
    execsql {INSERT INTO t11 VALUES(1,2)}
    sqlite3_exec db {SELECT %c6%c6 AS xyz, abc FROM t11}
  } {0 {xyz abc 1 2}}
}
do_test alter-11.3 {
  sqlite3_exec db {CREATE TABLE t11b("%81%82%83" text)}
  execsql {
    ALTER TABLE t11b ADD COLUMN abc;
  }
  catchsql {
    ALTER TABLE t11b ADD COLUMN abc;
  }
} {1 {duplicate column name: abc}}
if {!$isutf16} {
  do_test alter-11.4 {
    execsql {INSERT INTO t11b VALUES(3,4)}
    sqlite3_exec db {SELECT %81%82%83 AS xyz, abc FROM t11b}
  } {0 {xyz abc 3 4}}
  do_test alter-11.5 {
    sqlite3_exec db {SELECT [%81%82%83] AS xyz, abc FROM t11b}
  } {0 {xyz abc 3 4}}
  do_test alter-11.6 {
    sqlite3_exec db {SELECT "%81%82%83" AS xyz, abc FROM t11b}
  } {0 {xyz abc 3 4}}
}
do_test alter-11.7 {
  sqlite3_exec db {CREATE TABLE t11c(%81%82%83 text)}
  execsql {
    ALTER TABLE t11c ADD COLUMN abc;
  }
  catchsql {
    ALTER TABLE t11c ADD COLUMN abc;
  }
} {1 {duplicate column name: abc}}
if {!$isutf16} {
  do_test alter-11.8 {
    execsql {INSERT INTO t11c VALUES(5,6)}
    sqlite3_exec db {SELECT %81%82%83 AS xyz, abc FROM t11c}
  } {0 {xyz abc 5 6}}
  do_test alter-11.9 {
    sqlite3_exec db {SELECT [%81%82%83] AS xyz, abc FROM t11c}
  } {0 {xyz abc 5 6}}
  do_test alter-11.10 {
    sqlite3_exec db {SELECT "%81%82%83" AS xyz, abc FROM t11c}
  } {0 {xyz abc 5 6}}
}

do_test alter-12.1 {
  execsql {
    CREATE TABLE t12(a, b, c);
    CREATE VIEW v1 AS SELECT * FROM t12;
  }
} {}
do_test alter-12.2 {
  catchsql {
    ALTER TABLE v1 RENAME TO v2;
  }
} {1 {view v1 may not be altered}}
do_test alter-12.3 {
  execsql { SELECT * FROM v1; }
} {}
do_test alter-12.4 {
  db close
  sqlite3 db test.db
  execsql { SELECT * FROM v1; }
} {}
do_test alter-12.5 {
  catchsql { 
    ALTER TABLE v1 ADD COLUMN new_column;
  }
} {1 {Cannot add a column to a view}}

# Ticket #3102:
# Verify that comments do not interfere with the table rename
# algorithm.
#
do_test alter-13.1 {
  execsql {
    CREATE TABLE /* hi */ t3102a(x);
    CREATE TABLE t3102b -- comment
    (y);
    CREATE INDEX t3102c ON t3102a(x);
    SELECT name FROM sqlite_master WHERE name LIKE 't3102%' ORDER BY 1;
  }
} {t3102a t3102b t3102c}
do_test alter-13.2 {
  execsql {
    ALTER TABLE t3102a RENAME TO t3102a_rename;
    SELECT name FROM sqlite_master WHERE name LIKE 't3102%' ORDER BY 1;
  }
} {t3102a_rename t3102b t3102c}
do_test alter-13.3 {
  execsql {
    ALTER TABLE t3102b RENAME TO t3102b_rename;
    SELECT name FROM sqlite_master WHERE name LIKE 't3102%' ORDER BY 1;
  }
} {t3102a_rename t3102b_rename t3102c}

# Ticket #3651
do_test alter-14.1 {
  catchsql {
    CREATE TABLE t3651(a UNIQUE);
    ALTER TABLE t3651 ADD COLUMN b UNIQUE;
  }
} {1 {Cannot add a UNIQUE column}}
do_test alter-14.2 {
  catchsql {
    ALTER TABLE t3651 ADD COLUMN b PRIMARY KEY;
  }
} {1 {Cannot add a PRIMARY KEY column}}


finish_test

Added test/alter2.test.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# 2005 February 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing that SQLite can handle a subtle 
# file format change that may be used in the future to implement
# "ALTER TABLE ... ADD COLUMN".
#
# $Id: alter2.test,v 1.14 2009/04/07 14:14:22 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We have to have pragmas in order to do this test
ifcapable {!pragma} return

# These tests do not work if there is a codec. 
#
#if {[catch {sqlite3 -has_codec} r] || $r} return

# The file format change affects the way row-records stored in tables (but 
# not indices) are interpreted. Before version 3.1.3, a row-record for a 
# table with N columns was guaranteed to contain exactly N fields. As
# of version 3.1.3, the record may contain up to N fields. In this case
# the M fields that are present are the values for the left-most M 
# columns. The (N-M) rightmost columns contain NULL.
#
# If any records in the database contain less fields than their table
# has columns, then the file-format meta value should be set to (at least) 2. 
#

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}

# This procedure sets the SQL statement stored for table $tbl in the
# sqlite_master table of file 'test.db' to $sql. Also set the file format
# to the supplied value. This is 2 if the added column has a default that is
# NULL, or 3 otherwise. 
#
proc alter_table {tbl sql {file_format 2}} {
  sqlite3 dbat test.db
  set s [string map {' ''} $sql]
  set t [string map {' ''} $tbl]
  dbat eval [subst {
    PRAGMA writable_schema = 1;
    UPDATE sqlite_master SET sql = '$s' WHERE name = '$t' AND type = 'table';
    PRAGMA writable_schema = 0;
  }]
  dbat close
  set_file_format 2
}

#-----------------------------------------------------------------------
# Some basic tests to make sure short rows are handled.
#
do_test alter2-1.1 {
  execsql {
    CREATE TABLE abc(a, b);
    INSERT INTO abc VALUES(1, 2);
    INSERT INTO abc VALUES(3, 4);
    INSERT INTO abc VALUES(5, 6);
  }
} {}
do_test alter2-1.2 {
  # ALTER TABLE abc ADD COLUMN c;
  alter_table abc {CREATE TABLE abc(a, b, c);}
} {}
do_test alter2-1.3 {
  execsql {
    SELECT * FROM abc;
  }
} {1 2 {} 3 4 {} 5 6 {}}
do_test alter2-1.4 {
  execsql {
    UPDATE abc SET c = 10 WHERE a = 1;
    SELECT * FROM abc;
  }
} {1 2 10 3 4 {} 5 6 {}}
do_test alter2-1.5 {
  execsql {
    CREATE INDEX abc_i ON abc(c);
  }
} {}
do_test alter2-1.6 {
  execsql {
    SELECT c FROM abc ORDER BY c;
  }
} {{} {} 10}
do_test alter2-1.7 {
  execsql {
    SELECT * FROM abc WHERE c = 10;
  }
} {1 2 10}
do_test alter2-1.8 {
  execsql {
    SELECT sum(a), c FROM abc GROUP BY c;
  }
} {8 {} 1 10}
do_test alter2-1.9 {
  # ALTER TABLE abc ADD COLUMN d;
  alter_table abc {CREATE TABLE abc(a, b, c, d);}
  execsql { SELECT * FROM abc; }
  execsql {
    UPDATE abc SET d = 11 WHERE c IS NULL AND a<4;
    SELECT * FROM abc;
  }
} {1 2 10 {} 3 4 {} 11 5 6 {} {}}
do_test alter2-1.10 {
  execsql {
    SELECT typeof(d) FROM abc;
  }
} {null integer null}
do_test alter2-1.99 {
  execsql {
    DROP TABLE abc;
  }
} {}

#-----------------------------------------------------------------------
# Test that views work when the underlying table structure is changed.
#
ifcapable view {
  do_test alter2-2.1 {
    execsql {
      CREATE TABLE abc2(a, b, c);
      INSERT INTO abc2 VALUES(1, 2, 10);
      INSERT INTO abc2 VALUES(3, 4, NULL);
      INSERT INTO abc2 VALUES(5, 6, NULL);
      CREATE VIEW abc2_v AS SELECT * FROM abc2;
      SELECT * FROM abc2_v;
    }
  } {1 2 10 3 4 {} 5 6 {}}
  do_test alter2-2.2 {
    # ALTER TABLE abc ADD COLUMN d;
    alter_table abc2 {CREATE TABLE abc2(a, b, c, d);}
    execsql {
      SELECT * FROM abc2_v;
    }
  } {1 2 10 {} 3 4 {} {} 5 6 {} {}}
  do_test alter2-2.3 {
    execsql {
      DROP TABLE abc2;
      DROP VIEW abc2_v;
    }
  } {}
}

#-----------------------------------------------------------------------
# Test that triggers work when a short row is copied to the old.*
# trigger pseudo-table.
#
ifcapable trigger {
  do_test alter2-3.1 {
    execsql {
      CREATE TABLE abc3(a, b);
      CREATE TABLE blog(o, n);
      CREATE TRIGGER abc3_t AFTER UPDATE OF b ON abc3 BEGIN
        INSERT INTO blog VALUES(old.b, new.b);
      END;
    }
  } {}
  do_test alter2-3.2 {
    execsql {
      INSERT INTO abc3 VALUES(1, 4);
      UPDATE abc3 SET b = 2 WHERE b = 4;
      SELECT * FROM blog;
    }
  } {4 2}
  do_test alter2-3.3 {
    execsql {
      INSERT INTO abc3 VALUES(3, 4);
      INSERT INTO abc3 VALUES(5, 6);
    }
    alter_table abc3 {CREATE TABLE abc3(a, b, c);}
    execsql {
      SELECT * FROM abc3;
    }
  } {1 2 {} 3 4 {} 5 6 {}}
  do_test alter2-3.4 {
    execsql {
      UPDATE abc3 SET b = b*2 WHERE a<4;
      SELECT * FROM abc3;
    }
  } {1 4 {} 3 8 {} 5 6 {}}
  do_test alter2-3.5 {
    execsql {
      SELECT * FROM blog;
    }
  } {4 2 2 4 4 8}

  do_test alter2-3.6 {
    execsql {
      CREATE TABLE clog(o, n);
      CREATE TRIGGER abc3_t2 AFTER UPDATE OF c ON abc3 BEGIN
        INSERT INTO clog VALUES(old.c, new.c);
      END;
      UPDATE abc3 SET c = a*2;
      SELECT * FROM clog;
    }
  } {{} 2 {} 6 {} 10}
} else {
  execsql { CREATE TABLE abc3(a, b); }
}

#---------------------------------------------------------------------
# Check that an error occurs if the database is upgraded to a file
# format that SQLite does not support (in this case 5). Note: The 
# file format is checked each time the schema is read, so changing the
# file format requires incrementing the schema cookie.
#
do_test alter2-4.1 {
  db close
  set_file_format 5
  sqlite3 db test.db
} {}
do_test alter2-4.2 {
  # We have to run two queries here because the Tcl interface uses
  # sqlite3_prepare_v2(). In this case, the first query encounters an 
  # SQLITE_SCHEMA error. Then, when trying to recompile the statement, the
  # "unsupported file format" error is encountered. So the error code
  # returned is SQLITE_SCHEMA, not SQLITE_ERROR as required by the following
  # test case.
  #
  # When the query is attempted a second time, the same error message is
  # returned but the error code is SQLITE_ERROR, because the unsupported
  # file format was detected during a call to sqlite3_prepare(), not
  # sqlite3_step().
  #
  catchsql { SELECT * FROM sqlite_master; }
  catchsql { SELECT * FROM sqlite_master; }
} {1 {unsupported file format}}
do_test alter2-4.3 {
  sqlite3_errcode db
} {SQLITE_ERROR}
do_test alter2-4.4 {
  set ::DB [sqlite3_connection_pointer db]
  catchsql {
    SELECT * FROM sqlite_master;
  }
} {1 {unsupported file format}}
do_test alter2-4.5 {
  sqlite3_errcode db
} {SQLITE_ERROR}

#---------------------------------------------------------------------
# Check that executing VACUUM on a file with file-format version 2
# resets the file format to 1.
#
set default_file_format [expr $SQLITE_DEFAULT_FILE_FORMAT==4 ? 4 : 1]
ifcapable vacuum {
  do_test alter2-5.1 {
    set_file_format 2
    db close
    sqlite3 db test.db
    execsql {SELECT 1 FROM sqlite_master LIMIT 1;}
    get_file_format
  } {2}
  do_test alter2-5.2 {
    execsql { VACUUM }
  } {}
  do_test alter2-5.3 {
    get_file_format
  } $default_file_format
}
 
#---------------------------------------------------------------------
# Test that when a database with file-format 2 is opened, new 
# databases are still created with file-format 1.
#
do_test alter2-6.1 {
  db close
  set_file_format 2
  sqlite3 db test.db
  get_file_format
} {2}
ifcapable attach {
  do_test alter2-6.2 {
    file delete -force test2.db-journal
    file delete -force test2.db
    execsql {
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.t1(a, b);
    }
    get_file_format test2.db
  } $default_file_format
}
do_test alter2-6.3 {
  execsql {
    CREATE TABLE t1(a, b);
  }
  get_file_format 
} {2}

#---------------------------------------------------------------------
# Test that types and values for columns added with default values 
# other than NULL work with SELECT statements.
#
do_test alter2-7.1 {
  execsql {
    DROP TABLE t1;
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES(3);
    INSERT INTO t1 VALUES(4);
    SELECT * FROM t1;
  }
} {1 2 3 4}
do_test alter2-7.2 {
  set sql {CREATE TABLE t1(a, b DEFAULT '123', c INTEGER DEFAULT '123')}
  alter_table t1 $sql 3
  execsql {
    SELECT * FROM t1 LIMIT 1;
  }
} {1 123 123}
do_test alter2-7.3 {
  execsql {
    SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1;
  }
} {1 integer 123 text 123 integer}
do_test alter2-7.4 {
  execsql {
    SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1;
  }
} {1 integer 123 text 123 integer}
do_test alter2-7.5 {
  set sql {CREATE TABLE t1(a, b DEFAULT -123.0, c VARCHAR(10) default 5)}
  alter_table t1 $sql 3
  execsql {
    SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1;
  }
} {1 integer -123 integer 5 text}

#-----------------------------------------------------------------------
# Test that UPDATE trigger tables work with default values, and that when
# a row is updated the default values are correctly transfered to the 
# new row.
# 
ifcapable trigger {
db function set_val {set ::val}
  do_test alter2-8.1 {
    execsql {
      CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN
      SELECT set_val(
          old.b||' '||typeof(old.b)||' '||old.c||' '||typeof(old.c)||' '||
          new.b||' '||typeof(new.b)||' '||new.c||' '||typeof(new.c) 
      );
      END;
    }
    list
  } {}
}
do_test alter2-8.2 {
  execsql {
    UPDATE t1 SET c = 10 WHERE a = 1;
    SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1;
  }
} {1 integer -123 integer 10 text}
ifcapable trigger {
  do_test alter2-8.3 {
    set ::val
  } {-123 integer 5 text -123 integer 10 text}
}

#-----------------------------------------------------------------------
# Test that DELETE trigger tables work with default values, and that when
# a row is updated the default values are correctly transfered to the 
# new row.
# 
ifcapable trigger {
  do_test alter2-9.1 {
    execsql {
      CREATE TRIGGER trig2 BEFORE DELETE ON t1 BEGIN
      SELECT set_val(
          old.b||' '||typeof(old.b)||' '||old.c||' '||typeof(old.c)
      );
      END;
    }
    list
  } {}
  do_test alter2-9.2 {
    execsql {
      DELETE FROM t1 WHERE a = 2;
    }
    set ::val
  } {-123 integer 5 text}
}

#-----------------------------------------------------------------------
# Test creating an index on a column added with a default value. 
#
ifcapable bloblit {
  do_test alter2-10.1 {
    execsql {
      CREATE TABLE t2(a);
      INSERT INTO t2 VALUES('a');
      INSERT INTO t2 VALUES('b');
      INSERT INTO t2 VALUES('c');
      INSERT INTO t2 VALUES('d');
    }
    alter_table t2 {CREATE TABLE t2(a, b DEFAULT X'ABCD', c DEFAULT NULL);} 3
    catchsql {
      SELECT * FROM sqlite_master;
    }
    execsql {
      SELECT quote(a), quote(b), quote(c) FROM t2 LIMIT 1;
    }
  } {'a' X'ABCD' NULL}
  do_test alter2-10.2 {
    execsql {
      CREATE INDEX i1 ON t2(b);
      SELECT a FROM t2 WHERE b = X'ABCD';
    }
  } {a b c d}
  do_test alter2-10.3 {
    execsql {
      DELETE FROM t2 WHERE a = 'c';
      SELECT a FROM t2 WHERE b = X'ABCD';
    }
  } {a b d}
  do_test alter2-10.4 {
    execsql {
      SELECT count(b) FROM t2 WHERE b = X'ABCD';
    }
  } {3}
}

finish_test

Added test/alter3.test.























































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# 2005 February 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing that SQLite can handle a subtle 
# file format change that may be used in the future to implement
# "ALTER TABLE ... ADD COLUMN".
#
# $Id: alter3.test,v 1.11 2008/03/19 00:21:31 drh Exp $
#

set testdir [file dirname $argv0]

source $testdir/tester.tcl

# If SQLITE_OMIT_ALTERTABLE is defined, omit this file.
ifcapable !altertable {
  finish_test
  return
}

# Determine if there is a codec available on this test.
#
if {[catch {sqlite3 -has_codec} r] || $r} {
  set has_codec 1
} else {
  set has_codec 0
}


# Test Organisation:
# ------------------
#
# alter3-1.*: Test that ALTER TABLE correctly modifies the CREATE TABLE sql.
# alter3-2.*: Test error messages.
# alter3-3.*: Test adding columns with default value NULL.
# alter3-4.*: Test adding columns with default values other than NULL.
# alter3-5.*: Test adding columns to tables in ATTACHed databases.
# alter3-6.*: Test that temp triggers are not accidentally dropped.
# alter3-7.*: Test that VACUUM resets the file-format.
#

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}

do_test alter3-1.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    SELECT sql FROM sqlite_master;
  }
} {{CREATE TABLE abc(a, b, c)}}
do_test alter3-1.2 {
  execsql {ALTER TABLE abc ADD d INTEGER;}
  execsql {
    SELECT sql FROM sqlite_master;
  }
} {{CREATE TABLE abc(a, b, c, d INTEGER)}}
do_test alter3-1.3 {
  execsql {ALTER TABLE abc ADD e}
  execsql {
    SELECT sql FROM sqlite_master;
  }
} {{CREATE TABLE abc(a, b, c, d INTEGER, e)}}
do_test alter3-1.4 {
  execsql {
    CREATE TABLE main.t1(a, b);
    ALTER TABLE t1 ADD c;
    SELECT sql FROM sqlite_master WHERE tbl_name = 't1';
  }
} {{CREATE TABLE t1(a, b, c)}}
do_test alter3-1.5 {
  execsql {
    ALTER TABLE t1 ADD d CHECK (a>d);
    SELECT sql FROM sqlite_master WHERE tbl_name = 't1';
  }
} {{CREATE TABLE t1(a, b, c, d CHECK (a>d))}}
ifcapable foreignkey {
  do_test alter3-1.6 {
    execsql {
      CREATE TABLE t2(a, b, UNIQUE(a, b));
      ALTER TABLE t2 ADD c REFERENCES t1(c)  ;
      SELECT sql FROM sqlite_master WHERE tbl_name = 't2' AND type = 'table';
    }
  } {{CREATE TABLE t2(a, b, c REFERENCES t1(c), UNIQUE(a, b))}}
}
do_test alter3-1.7 {
  execsql {
    CREATE TABLE t3(a, b, UNIQUE(a, b));
    ALTER TABLE t3 ADD COLUMN c VARCHAR(10, 20);
    SELECT sql FROM sqlite_master WHERE tbl_name = 't3' AND type = 'table';
  }
} {{CREATE TABLE t3(a, b, c VARCHAR(10, 20), UNIQUE(a, b))}}
do_test alter3-1.99 {
  catchsql {
    # May not exist if foriegn-keys are omitted at compile time.
    DROP TABLE t2; 
  }
  execsql {
    DROP TABLE abc; 
    DROP TABLE t1; 
    DROP TABLE t3; 
  }
} {}

do_test alter3-2.1 {
  execsql {
    CREATE TABLE t1(a, b);
  }
  catchsql {
    ALTER TABLE t1 ADD c PRIMARY KEY;
  }
} {1 {Cannot add a PRIMARY KEY column}}
do_test alter3-2.2 {
  catchsql {
    ALTER TABLE t1 ADD c UNIQUE
  }
} {1 {Cannot add a UNIQUE column}}
do_test alter3-2.3 {
  catchsql {
    ALTER TABLE t1 ADD b VARCHAR(10)
  }
} {1 {duplicate column name: b}}
do_test alter3-2.3 {
  catchsql {
    ALTER TABLE t1 ADD c NOT NULL;
  }
} {1 {Cannot add a NOT NULL column with default value NULL}}
do_test alter3-2.4 {
  catchsql {
    ALTER TABLE t1 ADD c NOT NULL DEFAULT 10;
  }
} {0 {}}
ifcapable view {
  do_test alter3-2.5 {
    execsql {
      CREATE VIEW v1 AS SELECT * FROM t1;
    }
    catchsql {
      alter table v1 add column d;
    }
  } {1 {Cannot add a column to a view}}
}
do_test alter3-2.6 {
  catchsql {
    alter table t1 add column d DEFAULT CURRENT_TIME;
  }
} {1 {Cannot add a column with non-constant default}}
do_test alter3-2.99 {
  execsql {
    DROP TABLE t1;
  }
} {}

do_test alter3-3.1 {
  execsql {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 100);
    INSERT INTO t1 VALUES(2, 300);
    SELECT * FROM t1;
  }
} {1 100 2 300}
do_test alter3-3.1 {
  execsql {
    PRAGMA schema_version = 10;
  }
} {}
do_test alter3-3.2 {
  execsql {
    ALTER TABLE t1 ADD c;
    SELECT * FROM t1;
  }
} {1 100 {} 2 300 {}}
if {!$has_codec} {
  do_test alter3-3.3 {
    get_file_format
  } {3}
}
ifcapable schema_version {
  do_test alter3-3.4 {
    execsql {
      PRAGMA schema_version;
    }
  } {11}
}

do_test alter3-4.1 {
  db close
  file delete -force test.db
  set ::DB [sqlite3 db test.db]
  execsql {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 100);
    INSERT INTO t1 VALUES(2, 300);
    SELECT * FROM t1;
  }
} {1 100 2 300}
do_test alter3-4.1 {
  execsql {
    PRAGMA schema_version = 20;
  }
} {}
do_test alter3-4.2 {
  execsql {
    ALTER TABLE t1 ADD c DEFAULT 'hello world';
    SELECT * FROM t1;
  }
} {1 100 {hello world} 2 300 {hello world}}
if {!$has_codec} {
  do_test alter3-4.3 {
    get_file_format
  } {3}
}
ifcapable schema_version {
  do_test alter3-4.4 {
    execsql {
      PRAGMA schema_version;
    }
  } {21}
}
do_test alter3-4.99 {
  execsql {
    DROP TABLE t1;
  }
} {}

ifcapable attach {
  do_test alter3-5.1 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      CREATE TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, 'one');
      INSERT INTO t1 VALUES(2, 'two');
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.t1 AS SELECT * FROM t1;
      PRAGMA aux.schema_version = 30;
      SELECT sql FROM aux.sqlite_master;
    } 
  } {{CREATE TABLE t1(a,b)}}
  do_test alter3-5.2 {
    execsql {
      ALTER TABLE aux.t1 ADD COLUMN c VARCHAR(128);
      SELECT sql FROM aux.sqlite_master;
    }
  } {{CREATE TABLE t1(a,b, c VARCHAR(128))}}
  do_test alter3-5.3 {
    execsql {
      SELECT * FROM aux.t1;
    }
  } {1 one {} 2 two {}}
  ifcapable schema_version {
    do_test alter3-5.4 {
      execsql {
        PRAGMA aux.schema_version;
      }
    } {31}
  }
  if {!$has_codec} {
    do_test alter3-5.5 {
      list [get_file_format test2.db] [get_file_format]
    } {2 3}
  }
  do_test alter3-5.6 {
    execsql {
      ALTER TABLE aux.t1 ADD COLUMN d DEFAULT 1000;
      SELECT sql FROM aux.sqlite_master;
    }
  } {{CREATE TABLE t1(a,b, c VARCHAR(128), d DEFAULT 1000)}}
  do_test alter3-5.7 {
    execsql {
      SELECT * FROM aux.t1;
    }
  } {1 one {} 1000 2 two {} 1000}
  ifcapable schema_version {
    do_test alter3-5.8 {
      execsql {
        PRAGMA aux.schema_version;
      }
    } {32}
  }
  do_test alter3-5.9 {
    execsql {
      SELECT * FROM t1;
    }
  } {1 one 2 two}
  do_test alter3-5.99 {
    execsql {
      DROP TABLE aux.t1;
      DROP TABLE t1;
    }
  } {}
}

#----------------------------------------------------------------
# Test that the table schema is correctly reloaded when a column
# is added to a table.
#
ifcapable trigger&&tempdb {
  do_test alter3-6.1 {
    execsql {
      CREATE TABLE t1(a, b);
      CREATE TABLE log(trig, a, b);

      CREATE TRIGGER t1_a AFTER INSERT ON t1 BEGIN
        INSERT INTO log VALUES('a', new.a, new.b);
      END;
      CREATE TEMP TRIGGER t1_b AFTER INSERT ON t1 BEGIN
        INSERT INTO log VALUES('b', new.a, new.b);
      END;
  
      INSERT INTO t1 VALUES(1, 2);
      SELECT * FROM log;
    }
  } {b 1 2 a 1 2}
  do_test alter3-6.2 {
    execsql {
      ALTER TABLE t1 ADD COLUMN c DEFAULT 'c';
      INSERT INTO t1(a, b) VALUES(3, 4);
      SELECT * FROM log;
    }
  } {b 1 2 a 1 2 b 3 4 a 3 4}
}

if {!$has_codec} {
  ifcapable vacuum {
    do_test alter3-7.1 {
      execsql {
        VACUUM;
      }
      get_file_format
    } {1}
    do_test alter3-7.2 {
      execsql {
        CREATE TABLE abc(a, b, c);
        ALTER TABLE abc ADD d DEFAULT NULL;
      }
      get_file_format
    } {2}
    do_test alter3-7.3 {
      execsql {
        ALTER TABLE abc ADD e DEFAULT 10;
      }
      get_file_format
    } {3}
    do_test alter3-7.4 {
      execsql {
        ALTER TABLE abc ADD f DEFAULT NULL;
      }
      get_file_format
    } {3}
    do_test alter3-7.5 {
      execsql {
        VACUUM;
      }
      get_file_format
    } {1}
  }
}

# Ticket #1183 - Make sure adding columns to large tables does not cause
# memory corruption (as was the case before this bug was fixed).
do_test alter3-8.1 {
  execsql {
    CREATE TABLE t4(c1);
  }
} {}
set ::sql ""
do_test alter3-8.2 {
  set cols c1
  for {set i 2} {$i < 100} {incr i} {
    execsql "
      ALTER TABLE t4 ADD c$i
    "
    lappend cols c$i
  }
  set ::sql "CREATE TABLE t4([join $cols {, }])"
  list 
} {}
do_test alter3-8.2 {
  execsql {
    SELECT sql FROM sqlite_master WHERE name = 't4';
  }
} [list $::sql]

finish_test

Added test/alter4.test.



























































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# 2009 February 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing that SQLite can handle a subtle 
# file format change that may be used in the future to implement
# "ALTER TABLE ... ADD COLUMN".
#
# $Id: alter4.test,v 1.1 2009/02/02 18:03:22 drh Exp $
#

set testdir [file dirname $argv0]

source $testdir/tester.tcl

# If SQLITE_OMIT_ALTERTABLE is defined, omit this file.
ifcapable !altertable {
  finish_test
  return
}

# Determine if there is a codec available on this test.
#
if {[catch {sqlite3 -has_codec} r] || $r} {
  set has_codec 1
} else {
  set has_codec 0
}


# Test Organisation:
# ------------------
#
# alter4-1.*: Test that ALTER TABLE correctly modifies the CREATE TABLE sql.
# alter4-2.*: Test error messages.
# alter4-3.*: Test adding columns with default value NULL.
# alter4-4.*: Test adding columns with default values other than NULL.
# alter4-5.*: Test adding columns to tables in ATTACHed databases.
# alter4-6.*: Test that temp triggers are not accidentally dropped.
# alter4-7.*: Test that VACUUM resets the file-format.
#

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}

do_test alter4-1.1 {
  execsql {
    CREATE TEMP TABLE abc(a, b, c);
    SELECT sql FROM sqlite_temp_master;
  }
} {{CREATE TABLE abc(a, b, c)}}
do_test alter4-1.2 {
  execsql {ALTER TABLE abc ADD d INTEGER;}
  execsql {
    SELECT sql FROM sqlite_temp_master;
  }
} {{CREATE TABLE abc(a, b, c, d INTEGER)}}
do_test alter4-1.3 {
  execsql {ALTER TABLE abc ADD e}
  execsql {
    SELECT sql FROM sqlite_temp_master;
  }
} {{CREATE TABLE abc(a, b, c, d INTEGER, e)}}
do_test alter4-1.4 {
  execsql {
    CREATE TABLE temp.t1(a, b);
    ALTER TABLE t1 ADD c;
    SELECT sql FROM sqlite_temp_master WHERE tbl_name = 't1';
  }
} {{CREATE TABLE t1(a, b, c)}}
do_test alter4-1.5 {
  execsql {
    ALTER TABLE t1 ADD d CHECK (a>d);
    SELECT sql FROM sqlite_temp_master WHERE tbl_name = 't1';
  }
} {{CREATE TABLE t1(a, b, c, d CHECK (a>d))}}
ifcapable foreignkey {
  do_test alter4-1.6 {
    execsql {
      CREATE TEMP TABLE t2(a, b, UNIQUE(a, b));
      ALTER TABLE t2 ADD c REFERENCES t1(c)  ;
      SELECT sql FROM sqlite_temp_master
       WHERE tbl_name = 't2' AND type = 'table';
    }
  } {{CREATE TABLE t2(a, b, c REFERENCES t1(c), UNIQUE(a, b))}}
}
do_test alter4-1.7 {
  execsql {
    CREATE TEMPORARY TABLE t3(a, b, UNIQUE(a, b));
    ALTER TABLE t3 ADD COLUMN c VARCHAR(10, 20);
    SELECT sql FROM sqlite_temp_master
     WHERE tbl_name = 't3' AND type = 'table';
  }
} {{CREATE TABLE t3(a, b, c VARCHAR(10, 20), UNIQUE(a, b))}}
do_test alter4-1.99 {
  catchsql {
    # May not exist if foriegn-keys are omitted at compile time.
    DROP TABLE t2; 
  }
  execsql {
    DROP TABLE abc; 
    DROP TABLE t1; 
    DROP TABLE t3; 
  }
} {}

do_test alter4-2.1 {
  execsql {
    CREATE TABLE temp.t1(a, b);
  }
  catchsql {
    ALTER TABLE t1 ADD c PRIMARY KEY;
  }
} {1 {Cannot add a PRIMARY KEY column}}
do_test alter4-2.2 {
  catchsql {
    ALTER TABLE t1 ADD c UNIQUE
  }
} {1 {Cannot add a UNIQUE column}}
do_test alter4-2.3 {
  catchsql {
    ALTER TABLE t1 ADD b VARCHAR(10)
  }
} {1 {duplicate column name: b}}
do_test alter4-2.3 {
  catchsql {
    ALTER TABLE t1 ADD c NOT NULL;
  }
} {1 {Cannot add a NOT NULL column with default value NULL}}
do_test alter4-2.4 {
  catchsql {
    ALTER TABLE t1 ADD c NOT NULL DEFAULT 10;
  }
} {0 {}}
ifcapable view {
  do_test alter4-2.5 {
    execsql {
      CREATE TEMPORARY VIEW v1 AS SELECT * FROM t1;
    }
    catchsql {
      alter table v1 add column d;
    }
  } {1 {Cannot add a column to a view}}
}
do_test alter4-2.6 {
  catchsql {
    alter table t1 add column d DEFAULT CURRENT_TIME;
  }
} {1 {Cannot add a column with non-constant default}}
do_test alter4-2.99 {
  execsql {
    DROP TABLE t1;
  }
} {}

do_test alter4-3.1 {
  execsql {
    CREATE TEMP TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 100);
    INSERT INTO t1 VALUES(2, 300);
    SELECT * FROM t1;
  }
} {1 100 2 300}
do_test alter4-3.1 {
  execsql {
    PRAGMA schema_version = 10;
  }
} {}
do_test alter4-3.2 {
  execsql {
    ALTER TABLE t1 ADD c;
    SELECT * FROM t1;
  }
} {1 100 {} 2 300 {}}
if {!$has_codec} {
  do_test alter4-3.3 {
    get_file_format
  } {3}
}
ifcapable schema_version {
  do_test alter4-3.4 {
    execsql {
      PRAGMA schema_version;
    }
  } {10}
}

do_test alter4-4.1 {
  db close
  file delete -force test.db
  set ::DB [sqlite3 db test.db]
  execsql {
    CREATE TEMP TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 100);
    INSERT INTO t1 VALUES(2, 300);
    SELECT * FROM t1;
  }
} {1 100 2 300}
do_test alter4-4.1 {
  execsql {
    PRAGMA schema_version = 20;
  }
} {}
do_test alter4-4.2 {
  execsql {
    ALTER TABLE t1 ADD c DEFAULT 'hello world';
    SELECT * FROM t1;
  }
} {1 100 {hello world} 2 300 {hello world}}
if {!$has_codec} {
  do_test alter4-4.3 {
    get_file_format
  } {3}
}
ifcapable schema_version {
  do_test alter4-4.4 {
    execsql {
      PRAGMA schema_version;
    }
  } {20}
}
do_test alter4-4.99 {
  execsql {
    DROP TABLE t1;
  }
} {}

ifcapable attach {
  do_test alter4-5.1 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      CREATE TEMP TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, 'one');
      INSERT INTO t1 VALUES(2, 'two');
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.t1 AS SELECT * FROM t1;
      PRAGMA aux.schema_version = 30;
      SELECT sql FROM aux.sqlite_master;
    } 
  } {{CREATE TABLE t1(a,b)}}
  do_test alter4-5.2 {
    execsql {
      ALTER TABLE aux.t1 ADD COLUMN c VARCHAR(128);
      SELECT sql FROM aux.sqlite_master;
    }
  } {{CREATE TABLE t1(a,b, c VARCHAR(128))}}
  do_test alter4-5.3 {
    execsql {
      SELECT * FROM aux.t1;
    }
  } {1 one {} 2 two {}}
  ifcapable schema_version {
    do_test alter4-5.4 {
      execsql {
        PRAGMA aux.schema_version;
      }
    } {31}
  }
  if {!$has_codec} {
    do_test alter4-5.5 {
      list [get_file_format test2.db] [get_file_format]
    } {2 3}
  }
  do_test alter4-5.6 {
    execsql {
      ALTER TABLE aux.t1 ADD COLUMN d DEFAULT 1000;
      SELECT sql FROM aux.sqlite_master;
    }
  } {{CREATE TABLE t1(a,b, c VARCHAR(128), d DEFAULT 1000)}}
  do_test alter4-5.7 {
    execsql {
      SELECT * FROM aux.t1;
    }
  } {1 one {} 1000 2 two {} 1000}
  ifcapable schema_version {
    do_test alter4-5.8 {
      execsql {
        PRAGMA aux.schema_version;
      }
    } {32}
  }
  do_test alter4-5.9 {
    execsql {
      SELECT * FROM t1;
    }
  } {1 one 2 two}
  do_test alter4-5.99 {
    execsql {
      DROP TABLE aux.t1;
      DROP TABLE t1;
    }
  } {}
}

#----------------------------------------------------------------
# Test that the table schema is correctly reloaded when a column
# is added to a table.
#
ifcapable trigger&&tempdb {
  do_test alter4-6.1 {
    execsql {
      CREATE TEMP TABLE t1(a, b);
      CREATE TEMP TABLE log(trig, a, b);

      CREATE TRIGGER t1_a AFTER INSERT ON t1 BEGIN
        INSERT INTO log VALUES('a', new.a, new.b);
      END;
      CREATE TEMP TRIGGER t1_b AFTER INSERT ON t1 BEGIN
        INSERT INTO log VALUES('b', new.a, new.b);
      END;
  
      INSERT INTO t1 VALUES(1, 2);
      SELECT * FROM log;
    }
  } {b 1 2 a 1 2}
  do_test alter4-6.2 {
    execsql {
      ALTER TABLE t1 ADD COLUMN c DEFAULT 'c';
      INSERT INTO t1(a, b) VALUES(3, 4);
      SELECT * FROM log;
    }
  } {b 1 2 a 1 2 b 3 4 a 3 4}
}

if {!$has_codec} {
  ifcapable vacuum {
    do_test alter4-7.1 {
      execsql {
        VACUUM;
      }
      get_file_format
    } {1}
    do_test alter4-7.2 {
      execsql {
        CREATE TEMP TABLE abc(a, b, c);
        ALTER TABLE abc ADD d DEFAULT NULL;
      }
      get_file_format
    } {2}
    do_test alter4-7.3 {
      execsql {
        ALTER TABLE abc ADD e DEFAULT 10;
      }
      get_file_format
    } {3}
    do_test alter4-7.4 {
      execsql {
        ALTER TABLE abc ADD f DEFAULT NULL;
      }
      get_file_format
    } {3}
    do_test alter4-7.5 {
      execsql {
        VACUUM;
      }
      get_file_format
    } {1}
  }
}

# Ticket #1183 - Make sure adding columns to large tables does not cause
# memory corruption (as was the case before this bug was fixed).
do_test alter4-8.1 {
  execsql {
    CREATE TEMP TABLE t4(c1);
  }
} {}
set ::sql ""
do_test alter4-8.2 {
  set cols c1
  for {set i 2} {$i < 100} {incr i} {
    execsql "
      ALTER TABLE t4 ADD c$i
    "
    lappend cols c$i
  }
  set ::sql "CREATE TABLE t4([join $cols {, }])"
  list 
} {}
do_test alter4-8.2 {
  execsql {
    SELECT sql FROM sqlite_temp_master WHERE name = 't4';
  }
} [list $::sql]

finish_test

Added test/altermalloc.test.















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the ALTER TABLE statement and
# specifically out-of-memory conditions within that command.
#
# $Id: altermalloc.test,v 1.10 2008/10/30 17:21:13 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_OMIT_ALTERTABLE is defined, omit this file.
ifcapable !altertable||!memdebug {
  finish_test
  return
}

source $testdir/malloc_common.tcl

do_malloc_test altermalloc-1 -tclprep {
  db close
} -tclbody {
  if {[catch {sqlite3 db test.db}]} {
    error "out of memory"
  }
  sqlite3_db_config_lookaside db 0 0 0
  sqlite3_extended_result_codes db 1
} -sqlbody {
  CREATE TABLE t1(a int);
  ALTER TABLE t1 ADD COLUMN b INTEGER DEFAULT NULL;
  ALTER TABLE t1 ADD COLUMN c TEXT DEFAULT 'default-text';
  ALTER TABLE t1 RENAME TO t2;
  ALTER TABLE t2 ADD COLUMN d BLOB DEFAULT X'ABCD';
}

# Test malloc() failure on an ALTER TABLE on a virtual table.
#
ifcapable vtab {
  do_malloc_test altermalloc-vtab -tclprep {
    sqlite3 db2 test.db 
    sqlite3_db_config_lookaside db2 0 0 0
    sqlite3_extended_result_codes db2 1
    register_echo_module [sqlite3_connection_pointer db2]
    db2 eval {
      CREATE TABLE t1(a, b VARCHAR, c INTEGER);
      CREATE VIRTUAL TABLE t1echo USING echo(t1);
    }
    db2 close

    register_echo_module [sqlite3_connection_pointer db]
  } -tclbody {
    set rc [catch {db eval { ALTER TABLE t1echo RENAME TO t1_echo }} msg]
    if {$msg eq "vtable constructor failed: t1echo"} {
      set msg "out of memory"
    }
    if {$rc} {
      error $msg
    }
  }
}

finish_test

Added test/analyze.test.





































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# 2005 July 22
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
# This file implements tests for the ANALYZE command.
#
# $Id: analyze.test,v 1.9 2008/08/11 18:44:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# There is nothing to test if ANALYZE is disable for this build.
#
ifcapable {!analyze} {
  finish_test
  return
}

# Basic sanity checks.
#
do_test analyze-1.1 {
  catchsql {
    ANALYZE no_such_table
  }
} {1 {no such table: no_such_table}}
do_test analyze-1.2 {
  execsql {
    SELECT count(*) FROM sqlite_master WHERE name='sqlite_stat1'
  }
} {0}
do_test analyze-1.3 {
  catchsql {
    ANALYZE no_such_db.no_such_table
  }
} {1 {unknown database no_such_db}}
do_test analyze-1.4 {
  execsql {
    SELECT count(*) FROM sqlite_master WHERE name='sqlite_stat1'
  }
} {0}
do_test analyze-1.5.1 {
  catchsql {
    ANALYZE
  }
} {0 {}}
do_test analyze-1.5.2 {
  catchsql {
    PRAGMA empty_result_callbacks=1;
    ANALYZE
  }
} {0 {}}
do_test analyze-1.6 {
  execsql {
    SELECT count(*) FROM sqlite_master WHERE name='sqlite_stat1'
  }
} {1}
do_test analyze-1.6.2 {
  catchsql {
    CREATE INDEX stat1idx ON sqlite_stat1(idx);
  }
} {1 {table sqlite_stat1 may not be indexed}}
do_test analyze-1.6.3 {
  catchsql {
    CREATE INDEX main.stat1idx ON SQLite_stat1(idx);
  }
} {1 {table sqlite_stat1 may not be indexed}}
do_test analyze-1.7 {
  execsql {
    SELECT * FROM sqlite_stat1
  }
} {}
do_test analyze-1.8 {
  catchsql {
    ANALYZE main
  }
} {0 {}}
do_test analyze-1.9 {
  execsql {
    SELECT * FROM sqlite_stat1
  }
} {}
do_test analyze-1.10 {
  catchsql {
    CREATE TABLE t1(a,b);
    ANALYZE main.t1;
  }
} {0 {}}
do_test analyze-1.11 {
  execsql {
    SELECT * FROM sqlite_stat1
  }
} {}
do_test analyze-1.12 {
  catchsql {
    ANALYZE t1;
  }
} {0 {}}
do_test analyze-1.13 {
  execsql {
    SELECT * FROM sqlite_stat1
  }
} {}

# Create some indices that can be analyzed.  But do not yet add
# data.  Without data in the tables, no analysis is done.
#
do_test analyze-2.1 {
  execsql {
    CREATE INDEX t1i1 ON t1(a);
    ANALYZE main.t1;
    SELECT * FROM sqlite_stat1 ORDER BY idx;
  }
} {}
do_test analyze-2.2 {
  execsql {
    CREATE INDEX t1i2 ON t1(b);
    ANALYZE t1;
    SELECT * FROM sqlite_stat1 ORDER BY idx;
  }
} {}
do_test analyze-2.3 {
  execsql {
    CREATE INDEX t1i3 ON t1(a,b);
    ANALYZE main;
    SELECT * FROM sqlite_stat1 ORDER BY idx;
  }
} {}

# Start adding data to the table.  Verify that the analysis
# is done correctly.
#
do_test analyze-3.1 {
  execsql {
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(1,3);
    ANALYZE main.t1;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {2 2} t1i2 {2 1} t1i3 {2 2 1}}
do_test analyze-3.2 {
  execsql {
    INSERT INTO t1 VALUES(1,4);
    INSERT INTO t1 VALUES(1,5);
    ANALYZE t1;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {4 4} t1i2 {4 1} t1i3 {4 4 1}}
do_test analyze-3.3 {
  execsql {
    INSERT INTO t1 VALUES(2,5);
    ANALYZE main;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1}}
do_test analyze-3.4 {
  execsql {
    CREATE TABLE t2 AS SELECT * FROM t1;
    CREATE INDEX t2i1 ON t2(a);
    CREATE INDEX t2i2 ON t2(b);
    CREATE INDEX t2i3 ON t2(a,b);
    ANALYZE;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3} t2i2 {5 2} t2i3 {5 3 1}}
do_test analyze-3.5 {
  execsql {
    DROP INDEX t2i3;
    ANALYZE t1;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3} t2i2 {5 2}}
do_test analyze-3.6 {
  execsql {
    ANALYZE t2;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3} t2i2 {5 2}}
do_test analyze-3.7 {
  execsql {
    DROP INDEX t2i2;
    ANALYZE t2;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3}}
do_test analyze-3.8 {
  execsql {
    CREATE TABLE t3 AS SELECT a, b, rowid AS c, 'hi' AS d FROM t1;
    CREATE INDEX t3i1 ON t3(a);
    CREATE INDEX t3i2 ON t3(a,b,c,d);
    CREATE INDEX t3i3 ON t3(d,b,c,a);
    DROP TABLE t1;
    DROP TABLE t2;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {}
do_test analyze-3.9 {
  execsql {
    ANALYZE;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}}

do_test analyze-3.10 {
  execsql {
    CREATE TABLE [silly " name](a, b, c);
    CREATE INDEX 'foolish '' name' ON [silly " name](a, b);
    CREATE INDEX 'another foolish '' name' ON [silly " name](c);
    INSERT INTO [silly " name] VALUES(1, 2, 3);
    INSERT INTO [silly " name] VALUES(4, 5, 6);
    ANALYZE;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {{another foolish ' name} {2 1} {foolish ' name} {2 1 1} t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}}
do_test analyze-3.11 {
  execsql {
    DROP INDEX "foolish ' name";
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {{another foolish ' name} {2 1} t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}}
do_test analyze-3.11 {
  execsql {
    DROP TABLE "silly "" name";
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}}

# Try corrupting the sqlite_stat1 table and make sure the
# database is still able to function.
#
do_test analyze-4.0 {
  sqlite3 db2 test.db
  db2 eval {
    CREATE TABLE t4(x,y,z);
    CREATE INDEX t4i1 ON t4(x);
    CREATE INDEX t4i2 ON t4(y);
    INSERT INTO t4 SELECT a,b,c FROM t3;
  }
  db2 close
  db close
  sqlite3 db test.db
  execsql {
    ANALYZE;
    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
  }
} {t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1} t4i1 {5 3} t4i2 {5 2}}
do_test analyze-4.1 {
  execsql {
    PRAGMA writable_schema=on;
    INSERT INTO sqlite_stat1 VALUES(null,null,null);
    PRAGMA writable_schema=off;
  }
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM t4 WHERE x=1234;
  }
} {}
do_test analyze-4.2 {
  execsql {
    PRAGMA writable_schema=on;
    DELETE FROM sqlite_stat1;
    INSERT INTO sqlite_stat1 VALUES('t4','t4i1','nonsense');
    INSERT INTO sqlite_stat1 VALUES('t4','t4i2','120897349817238741092873198273409187234918720394817209384710928374109827172901827349871928741910');
    PRAGMA writable_schema=off;
  }
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM t4 WHERE x=1234;
  }
} {}
do_test analyze-4.3 {
  execsql {
    INSERT INTO sqlite_stat1 VALUES('t4','xyzzy','0 1 2 3');
  }
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM t4 WHERE x=1234;
  }
} {}

# This test corrupts the database file so it must be the last test
# in the series.
#
do_test analyze-99.1 {
  execsql {
    PRAGMA writable_schema=on;
    UPDATE sqlite_master SET sql='nonsense' WHERE name='sqlite_stat1';
  }
  db close
  sqlite3 db test.db
  catchsql {
    ANALYZE
  }
} {1 {malformed database schema (sqlite_stat1) - near "nonsense": syntax error}}


finish_test

Added test/analyze2.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# 2009 August 06
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library. This file 
# implements tests for the extra functionality provided by the ANALYZE 
# command when the library is compiled with SQLITE_ENABLE_STAT2 defined.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !stat2 {
  finish_test
  return
}

#--------------------------------------------------------------------
# Test organization:
#
# analyze2-1.*: Tests to verify that ANALYZE creates and populates the
#               sqlite_stat2 table as expected.
#
# analyze2-2.*: Test that when a table has two indexes on it and either
#               index may be used for the scan, the index suggested by
#               the contents of sqlite_stat2 table is prefered.
# 
# analyze2-3.*: Similar to the previous block of tests, but using tables
#               that contain a mixture of NULL, numeric, text and blob
#               values.
#
# analyze2-4.*: Check that when an indexed column uses a collation other
#               than BINARY, the collation is taken into account when
#               using the contents of sqlite_stat2 to estimate the cost
#               of a range scan.
#
# analyze2-5.*: Check that collation sequences are used as described above
#               even when the only available version of the collation 
#               function require UTF-16 encoded arguments.
#
# analyze2-6.*: Check that the library behaves correctly when one of the
#               sqlite_stat2 or sqlite_stat1 tables are missing.
#
# analyze2-7.*: Check that in a shared-schema situation, nothing goes
#               wrong if sqlite_stat2 data is read by one connection,
#               and freed by another.
# 

proc eqp {sql {db db}} {
  uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db
}

do_test analyze2-1.1 {
  execsql { CREATE TABLE t1(x PRIMARY KEY) }
  for {set i 0} {$i < 1000} {incr i} {
    execsql { INSERT INTO t1 VALUES($i) }
  }
  execsql { 
    ANALYZE;
    SELECT * FROM sqlite_stat2;
  }
} [list t1 sqlite_autoindex_t1_1 0 50  \
        t1 sqlite_autoindex_t1_1 1 149 \
        t1 sqlite_autoindex_t1_1 2 249 \
        t1 sqlite_autoindex_t1_1 3 349 \
        t1 sqlite_autoindex_t1_1 4 449 \
        t1 sqlite_autoindex_t1_1 5 549 \
        t1 sqlite_autoindex_t1_1 6 649 \
        t1 sqlite_autoindex_t1_1 7 749 \
        t1 sqlite_autoindex_t1_1 8 849 \
        t1 sqlite_autoindex_t1_1 9 949 \
]

do_test analyze2-1.2 {
  execsql {
    DELETE FROM t1 WHERe x>9;
    ANALYZE;
    SELECT tbl, idx, group_concat(sample, ' ') FROM sqlite_stat2;
  }
} {t1 sqlite_autoindex_t1_1 {0 1 2 3 4 5 6 7 8 9}}
do_test analyze2-1.3 {
  execsql {
    DELETE FROM t1 WHERE x>8;
    ANALYZE;
    SELECT * FROM sqlite_stat2;
  }
} {}
do_test analyze2-1.4 {
  execsql {
    DELETE FROM t1;
    ANALYZE;
    SELECT * FROM sqlite_stat2;
  }
} {}

do_test analyze2-2.1 {
  execsql { 
    BEGIN;
    DROP TABLE t1;
    CREATE TABLE t1(x, y);
    CREATE INDEX t1_x ON t1(x);
    CREATE INDEX t1_y ON t1(y);
  }
  for {set i 0} {$i < 1000} {incr i} {
    execsql { INSERT INTO t1 VALUES($i, $i) }
  }
  execsql COMMIT
  execsql ANALYZE
} {}
do_test analyze2-2.2 {
  eqp "SELECT * FROM t1 WHERE x>500 AND y>700"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-2.3 {
  eqp "SELECT * FROM t1 WHERE x>700 AND y>500"
} {0 0 {TABLE t1 WITH INDEX t1_x}}
do_test analyze2-2.3 {
  eqp "SELECT * FROM t1 WHERE y>700 AND x>500"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-2.4 {
  eqp "SELECT * FROM t1 WHERE y>500 AND x>700"
} {0 0 {TABLE t1 WITH INDEX t1_x}}
do_test analyze2-2.5 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 100 AND 200 AND y BETWEEN 400 AND 700"
} {0 0 {TABLE t1 WITH INDEX t1_x}}
do_test analyze2-2.6 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 100 AND 500 AND y BETWEEN 400 AND 700"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-2.7 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN -400 AND -300 AND y BETWEEN 100 AND 300"
} {0 0 {TABLE t1 WITH INDEX t1_x}}
do_test analyze2-2.8 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 100 AND 300 AND y BETWEEN -400 AND -300"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-2.9 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 500 AND 100 AND y BETWEEN 100 AND 300"
} {0 0 {TABLE t1 WITH INDEX t1_x}}
do_test analyze2-2.10 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 100 AND 300 AND y BETWEEN 500 AND 100"
} {0 0 {TABLE t1 WITH INDEX t1_y}}

do_test analyze2-3.1 {
  set alphabet [list a b c d e f g h i j]
  execsql BEGIN
  for {set i 0} {$i < 1000} {incr i} {
    set str    [lindex $alphabet [expr ($i/100)%10]] 
    append str [lindex $alphabet [expr ($i/ 10)%10]]
    append str [lindex $alphabet [expr ($i/  1)%10]]
    execsql { INSERT INTO t1 VALUES($str, $str) }
  }
  execsql COMMIT
  execsql ANALYZE
  execsql { 
    SELECT tbl,idx,group_concat(sample,' ') 
    FROM sqlite_stat2 
    WHERE idx = 't1_x' 
    GROUP BY tbl,idx
  }
} {t1 t1_x {100 299 499 699 899 ajj cjj ejj gjj ijj}}
do_test analyze2-3.2 {
  execsql { 
    SELECT tbl,idx,group_concat(sample,' ') 
    FROM sqlite_stat2 
    WHERE idx = 't1_y' 
    GROUP BY tbl,idx
  }
} {t1 t1_y {100 299 499 699 899 ajj cjj ejj gjj ijj}}

do_test analyze2-3.3 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 100 AND 500 AND y BETWEEN 'a' AND 'b'"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-3.4 {
  eqp "SELECT * FROM t1 WHERE x BETWEEN 100 AND 400 AND y BETWEEN 'a' AND 'h'"
} {0 0 {TABLE t1 WITH INDEX t1_x}}
do_test analyze2-3.5 {
  eqp "SELECT * FROM t1 WHERE x<'a' AND y>'h'"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-3.6 {
  eqp "SELECT * FROM t1 WHERE x<444 AND y>'h'"
} {0 0 {TABLE t1 WITH INDEX t1_y}}
do_test analyze2-3.7 {
  eqp "SELECT * FROM t1 WHERE x<221 AND y>'g'"
} {0 0 {TABLE t1 WITH INDEX t1_x}}

do_test analyze2-4.1 {
  execsql { CREATE TABLE t3(a COLLATE nocase, b) }
  execsql { CREATE INDEX t3a ON t3(a) }
  execsql { CREATE INDEX t3b ON t3(b) }
  set alphabet [list A b C d E f G h I j]
  execsql BEGIN
  for {set i 0} {$i < 1000} {incr i} {
    set str    [lindex $alphabet [expr ($i/100)%10]] 
    append str [lindex $alphabet [expr ($i/ 10)%10]]
    append str [lindex $alphabet [expr ($i/  1)%10]]
    execsql { INSERT INTO t3 VALUES($str, $str) }
  }
  execsql COMMIT
  execsql ANALYZE
} {}
do_test analyze2-4.2 {
  execsql { 
    SELECT tbl,idx,group_concat(sample,' ') 
    FROM sqlite_stat2 
    WHERE idx = 't3a' 
    GROUP BY tbl,idx
  }
} {t3 t3a {AfA bEj CEj dEj EEj fEj GEj hEj IEj jEj}}
do_test analyze2-4.3 {
  execsql { 
    SELECT tbl,idx,group_concat(sample,' ') 
    FROM sqlite_stat2 
    WHERE idx = 't3b' 
    GROUP BY tbl,idx
  }
} {t3 t3b {AbA CIj EIj GIj IIj bIj dIj fIj hIj jIj}}

do_test analyze2-4.4 {
  eqp "SELECT * FROM t3 WHERE a > 'A' AND a < 'C' AND b > 'A' AND b < 'C'"
} {0 0 {TABLE t3 WITH INDEX t3b}}
do_test analyze2-4.5 {
  eqp "SELECT * FROM t3 WHERE a > 'A' AND a < 'c' AND b > 'A' AND b < 'c'"
} {0 0 {TABLE t3 WITH INDEX t3a}}

ifcapable utf16 {
  proc test_collate {enc lhs rhs} {
    # puts $enc
    return [string compare $lhs $rhs]
  }
  do_test analyze2-5.1 {
    add_test_collate db 0 0 1
    execsql { CREATE TABLE t4(x COLLATE test_collate) }
    execsql { CREATE INDEX t4x ON t4(x) }
    set alphabet [list a b c d e f g h i j]
    execsql BEGIN
    for {set i 0} {$i < 1000} {incr i} {
      set str    [lindex $alphabet [expr ($i/100)%10]] 
      append str [lindex $alphabet [expr ($i/ 10)%10]]
      append str [lindex $alphabet [expr ($i/  1)%10]]
      execsql { INSERT INTO t4 VALUES($str) }
    }
    execsql COMMIT
    execsql ANALYZE
  } {}
  do_test analyze2-5.2 {
    execsql { 
      SELECT tbl,idx,group_concat(sample,' ') 
      FROM sqlite_stat2 
      WHERE tbl = 't4' 
      GROUP BY tbl,idx
    }
  } {t4 t4x {afa bej cej dej eej fej gej hej iej jej}}
  do_test analyze2-5.3 {
    eqp "SELECT * FROM t4 WHERE x>'ccc'"
  } {0 0 {TABLE t4 WITH INDEX t4x}}
  do_test analyze2-5.4 {
    eqp "SELECT * FROM t4 AS t41, t4 AS t42 WHERE t41.x>'ccc' AND t42.x>'ggg'"
  } {0 1 {TABLE t4 AS t42 WITH INDEX t4x} 1 0 {TABLE t4 AS t41 WITH INDEX t4x}}
  do_test analyze2-5.5 {
    eqp "SELECT * FROM t4 AS t41, t4 AS t42 WHERE t41.x>'ddd' AND t42.x>'ccc'"
  } {0 0 {TABLE t4 AS t41 WITH INDEX t4x} 1 1 {TABLE t4 AS t42 WITH INDEX t4x}}
}

#--------------------------------------------------------------------
# These tests, analyze2-6.*, verify that the library behaves correctly
# when one of the sqlite_stat1 and sqlite_stat2 tables is missing.
#
# If the sqlite_stat1 table is not present, then the sqlite_stat2
# table is not read. However, if it is the sqlite_stat2 table that
# is missing, the data in the sqlite_stat1 table is still used.
#
# Tests analyze2-6.1.* test the libary when the sqlite_stat2 table
# is missing. Tests analyze2-6.2.* test the library when sqlite_stat1
# is not present.
#
do_test analyze2-6.0 {
  execsql {
    DROP TABLE IF EXISTS t4;
    CREATE TABLE t5(a, b); CREATE INDEX t5i ON t5(a, b);
    CREATE TABLE t6(a, b); CREATE INDEX t6i ON t6(a, b);
  }
  for {set ii 0} {$ii < 20} {incr ii} {
    execsql {
      INSERT INTO t5 VALUES($ii, $ii);
      INSERT INTO t6 VALUES($ii/10, $ii/10);
    }
  }
  execsql { 
    CREATE TABLE master AS 
    SELECT * FROM sqlite_master WHERE name LIKE 'sqlite_stat%' 
  }
} {}

do_test analyze2-6.1.1 {
  eqp {SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
       t5.a = 1 AND
       t6.a = 1 AND t6.b = 1
  }
} {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
do_test analyze2-6.1.2 {
  db cache flush
  execsql ANALYZE
  eqp {SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
       t5.a = 1 AND
       t6.a = 1 AND t6.b = 1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}
do_test analyze2-6.1.3 {
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
       t5.a = 1 AND
       t6.a = 1 AND t6.b = 1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}
do_test analyze2-6.1.4 {
  execsql { 
    PRAGMA writable_schema = 1;
    DELETE FROM sqlite_master WHERE tbl_name = 'sqlite_stat2';
  }
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
       t5.a = 1 AND
       t6.a = 1 AND t6.b = 1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}
do_test analyze2-6.1.5 {
  execsql { 
    PRAGMA writable_schema = 1;
    DELETE FROM sqlite_master WHERE tbl_name = 'sqlite_stat1';
  }
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
       t5.a = 1 AND
       t6.a = 1 AND t6.b = 1
  }
} {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
do_test analyze2-6.1.6 {
  execsql { 
    PRAGMA writable_schema = 1;
    INSERT INTO sqlite_master SELECT * FROM master;
  }
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
       t5.a = 1 AND
       t6.a = 1 AND t6.b = 1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}

do_test analyze2-6.2.1 {
  execsql { 
    DELETE FROM sqlite_stat1;
    DELETE FROM sqlite_stat2;
  }
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
        t5.a>1 AND t5.a<15 AND
        t6.a>1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}
do_test analyze2-6.2.2 {
  db cache flush
  execsql ANALYZE
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
        t5.a>1 AND t5.a<15 AND
        t6.a>1
  }
} {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
do_test analyze2-6.2.3 {
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
        t5.a>1 AND t5.a<15 AND
        t6.a>1
  }
} {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
do_test analyze2-6.2.4 {
  execsql { 
    PRAGMA writable_schema = 1;
    DELETE FROM sqlite_master WHERE tbl_name = 'sqlite_stat1';
  }
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
        t5.a>1 AND t5.a<15 AND
        t6.a>1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}
do_test analyze2-6.2.5 {
  execsql { 
    PRAGMA writable_schema = 1;
    DELETE FROM sqlite_master WHERE tbl_name = 'sqlite_stat2';
  }
  sqlite3 db test.db
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
        t5.a>1 AND t5.a<15 AND
        t6.a>1
  }
} {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}
do_test analyze2-6.2.6 {
  execsql { 
    PRAGMA writable_schema = 1;
    INSERT INTO sqlite_master SELECT * FROM master;
  }
  sqlite3 db test.db
  execsql ANALYZE
  eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
        t5.a>1 AND t5.a<15 AND
        t6.a>1
  }
} {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}

#--------------------------------------------------------------------
# These tests, analyze2-7.*, test that the sqlite_stat2 functionality
# works in shared-cache mode. Note that these tests reuse the database
# created for the analyze2-6.* tests.
#
ifcapable shared_cache {
  db close
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

  proc incr_schema_cookie {zDb} {
    foreach iOffset {24 40} {
      set cookie [hexio_get_int [hexio_read $zDb $iOffset 4]]
      incr cookie
      hexio_write $zDb $iOffset [hexio_render_int32 $cookie]
    }
  }

  do_test analyze2-7.1 {
    sqlite3 db1 test.db
    sqlite3 db2 test.db
    db1 cache size 0
    db2 cache size 0
    execsql { SELECT count(*) FROM t5 } db1
  } {20}
  do_test analyze2-7.2 {
    incr_schema_cookie test.db
    execsql { SELECT count(*) FROM t5 } db2
  } {20}
  do_test analyze2-7.3 {
    incr_schema_cookie test.db
    execsql { SELECT count(*) FROM t5 } db1
  } {20}
  do_test analyze2-7.4 {
    incr_schema_cookie test.db
    execsql { SELECT count(*) FROM t5 } db2
  } {20}

  do_test analyze2-7.5 {
    eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
          t5.a>1 AND t5.a<15 AND
          t6.a>1
    } db1
  } {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
  do_test analyze2-7.6 {
    incr_schema_cookie test.db
    execsql { SELECT * FROM sqlite_master } db2
    eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
          t5.a>1 AND t5.a<15 AND
          t6.a>1
    } db2
  } {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
  do_test analyze2-7.7 {
    incr_schema_cookie test.db
    execsql { SELECT * FROM sqlite_master } db1
    eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
          t5.a>1 AND t5.a<15 AND
          t6.a>1
    } db1
  } {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}

  do_test analyze2-7.8 {
    execsql { DELETE FROM sqlite_stat2 } db2
    execsql { SELECT * FROM sqlite_master } db1
    eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
          t5.a>1 AND t5.a<15 AND
          t6.a>1
    } db1
  } {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}
  do_test analyze2-7.9 {
    execsql { SELECT * FROM sqlite_master } db2
    eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
          t5.a>1 AND t5.a<15 AND
          t6.a>1
    } db2
  } {0 1 {TABLE t6 WITH INDEX t6i} 1 0 {TABLE t5 USING PRIMARY KEY}}

  do_test analyze2-7.10 {
    incr_schema_cookie test.db
    execsql { SELECT * FROM sqlite_master } db1
    eqp { SELECT * FROM t5,t6 WHERE t5.rowid=t6.rowid AND 
          t5.a>1 AND t5.a<15 AND
          t6.a>1
    } db1
  } {0 0 {TABLE t5 WITH INDEX t5i} 1 1 {TABLE t6 USING PRIMARY KEY}}

  db1 close
  db2 close
  sqlite3_enable_shared_cache $::enable_shared_cache
}

finish_test

Added test/analyze3.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# 2009 August 06
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library. This file 
# implements tests for range and LIKE constraints that use bound variables
# instead of literal constant arguments.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !stat2 {
  finish_test
  return
}

#----------------------------------------------------------------------
# Test Organization:
#
# analyze3-1.*: Test that the values of bound parameters are considered 
#               in the same way as constants when planning queries that
#               use range constraints.
#
# analyze3-2.*: Test that the values of bound parameters are considered 
#               in the same way as constants when planning queries that
#               use LIKE expressions in the WHERE clause.
#
# analyze3-3.*: Test that binding to a variable does not invalidate the 
#               query plan when there is no way in which replanning the
#               query may produce a superior outcome.
#
# analyze3-4.*: Test that SQL or authorization callback errors occuring
#               within sqlite3Reprepare() are handled correctly.
#
# analyze3-5.*: Check that the query plans of applicable statements are
#               invalidated if the values of SQL parameter are modified
#               using the clear_bindings() or transfer_bindings() APIs.
#

proc getvar {varname} { uplevel #0 set $varname }
db function var getvar

proc eqp {sql {db db}} {
  uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db
}

proc sf_execsql {sql {db db}} {
  set ::sqlite_search_count 0
  set r [uplevel [list execsql $sql $db]]

  concat $::sqlite_search_count [$db status step] $r
}

#-------------------------------------------------------------------------
#
# analyze3-1.1.1: 
#   Create a table with two columns. Populate the first column (affinity 
#   INTEGER) with integer values from 100 to 1100. Create an index on this 
#   column. ANALYZE the table.
#
# analyze3-1.1.2 - 3.1.3
#   Show that there are two possible plans for querying the table with
#   a range constraint on the indexed column - "full table scan" or "use 
#   the index". When the range is specified using literal values, SQLite
#   is able to pick the best plan based on the samples in sqlite_stat2.
#
# analyze3-1.1.4 - 3.1.9
#   Show that using SQL variables produces the same results as using
#   literal values to constrain the range scan.
#
#   These tests also check that the compiler code considers column 
#   affinities when estimating the number of rows scanned by the "use 
#   index strategy".
#
do_test analyze3-1.1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(x INTEGER, y);
    CREATE INDEX i1 ON t1(x);
  }
  for {set i 0} {$i < 1000} {incr i} {
    execsql { INSERT INTO t1 VALUES($i+100, $i) }
  }
  execsql {
    COMMIT;
    ANALYZE;
  }
} {}

do_test analyze3-1.1.2 {
  eqp { SELECT sum(y) FROM t1 WHERE x>200 AND x<300 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test analyze3-1.1.3 {
  eqp { SELECT sum(y) FROM t1 WHERE x>0 AND x<1100 }
} {0 0 {TABLE t1}}

do_test analyze3-1.1.4 {
  sf_execsql { SELECT sum(y) FROM t1 WHERE x>200 AND x<300 }
} {199 0 14850}
do_test analyze3-1.1.5 {
  set l [string range "200" 0 end]
  set u [string range "300" 0 end]
  sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u }
} {199 0 14850}
do_test analyze3-1.1.6 {
  set l [expr int(200)]
  set u [expr int(300)]
  sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u }
} {199 0 14850}
do_test analyze3-1.1.7 {
  sf_execsql { SELECT sum(y) FROM t1 WHERE x>0 AND x<1100 }
} {999 999 499500}
do_test analyze3-1.1.8 {
  set l [string range "0" 0 end]
  set u [string range "1100" 0 end]
  sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u }
} {999 999 499500}
do_test analyze3-1.1.9 {
  set l [expr int(0)]
  set u [expr int(1100)]
  sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u }
} {999 999 499500}


# The following tests are similar to the block above. The difference is
# that the indexed column has TEXT affinity in this case. In the tests
# above the affinity is INTEGER.
#
do_test analyze3-1.2.1 {
  execsql {
    BEGIN;
      CREATE TABLE t2(x TEXT, y);
      INSERT INTO t2 SELECT * FROM t1;
      CREATE INDEX i2 ON t2(x);
    COMMIT;
    ANALYZE;
  }
} {}
do_test analyze3-1.2.2 {
  eqp { SELECT sum(y) FROM t2 WHERE x>1 AND x<2 }
} {0 0 {TABLE t2 WITH INDEX i2}}
do_test analyze3-1.2.3 {
  eqp { SELECT sum(y) FROM t2 WHERE x>0 AND x<99 }
} {0 0 {TABLE t2}}
do_test analyze3-1.2.4 {
  sf_execsql { SELECT sum(y) FROM t2 WHERE x>12 AND x<20 }
} {161 0 4760}
do_test analyze3-1.2.5 {
  set l [string range "12" 0 end]
  set u [string range "20" 0 end]
  sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u}
} {161 0 text text 4760}
do_test analyze3-1.2.6 {
  set l [expr int(12)]
  set u [expr int(20)]
  sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u}
} {161 0 integer integer 4760}
do_test analyze3-1.2.7 {
  sf_execsql { SELECT sum(y) FROM t2 WHERE x>0 AND x<99 }
} {999 999 490555}
do_test analyze3-1.2.8 {
  set l [string range "0" 0 end]
  set u [string range "99" 0 end]
  sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u}
} {999 999 text text 490555}
do_test analyze3-1.2.9 {
  set l [expr int(0)]
  set u [expr int(99)]
  sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u}
} {999 999 integer integer 490555}

# Same tests a third time. This time, column x has INTEGER affinity and
# is not the leftmost column of the table. This triggered a bug causing
# SQLite to use sub-optimal query plans in 3.6.18 and earlier.
#
do_test analyze3-1.3.1 {
  execsql {
    BEGIN;
      CREATE TABLE t3(y TEXT, x INTEGER);
      INSERT INTO t3 SELECT y, x FROM t1;
      CREATE INDEX i3 ON t3(x);
    COMMIT;
    ANALYZE;
  }
} {}
do_test analyze3-1.3.2 {
  eqp { SELECT sum(y) FROM t3 WHERE x>200 AND x<300 }
} {0 0 {TABLE t3 WITH INDEX i3}}
do_test analyze3-1.3.3 {
  eqp { SELECT sum(y) FROM t3 WHERE x>0 AND x<1100 }
} {0 0 {TABLE t3}}

do_test analyze3-1.3.4 {
  sf_execsql { SELECT sum(y) FROM t3 WHERE x>200 AND x<300 }
} {199 0 14850}
do_test analyze3-1.3.5 {
  set l [string range "200" 0 end]
  set u [string range "300" 0 end]
  sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u }
} {199 0 14850}
do_test analyze3-1.3.6 {
  set l [expr int(200)]
  set u [expr int(300)]
  sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u }
} {199 0 14850}
do_test analyze3-1.3.7 {
  sf_execsql { SELECT sum(y) FROM t3 WHERE x>0 AND x<1100 }
} {999 999 499500}
do_test analyze3-1.3.8 {
  set l [string range "0" 0 end]
  set u [string range "1100" 0 end]
  sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u }
} {999 999 499500}
do_test analyze3-1.3.9 {
  set l [expr int(0)]
  set u [expr int(1100)]
  sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u }
} {999 999 499500}

#-------------------------------------------------------------------------
# Test that the values of bound SQL variables may be used for the LIKE
# optimization.
#
drop_all_tables
do_test analyze3-2.1 {
  execsql {
    PRAGMA case_sensitive_like=off;
    BEGIN;
    CREATE TABLE t1(a, b TEXT COLLATE nocase);
    CREATE INDEX i1 ON t1(b);
  }
  for {set i 0} {$i < 1000} {incr i} {
    set t ""
    append t [lindex {a b c d e f g h i j} [expr $i/100]]
    append t [lindex {a b c d e f g h i j} [expr ($i/10)%10]]
    append t [lindex {a b c d e f g h i j} [expr ($i%10)]]
    execsql { INSERT INTO t1 VALUES($i, $t) }
  }
  execsql COMMIT
} {}
do_test analyze3-2.2 {
  eqp { SELECT count(a) FROM t1 WHERE b LIKE 'a%' }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test analyze3-2.3 {
  eqp { SELECT count(a) FROM t1 WHERE b LIKE '%a' }
} {0 0 {TABLE t1}}

do_test analyze3-2.4 {
  sf_execsql { SELECT count(*) FROM t1 WHERE b LIKE 'a%' }
} {101 0 100}
do_test analyze3-2.5 {
  sf_execsql { SELECT count(*) FROM t1 WHERE b LIKE '%a' }
} {999 999 100}

do_test analyze3-2.4 {
  set like "a%"
  sf_execsql { SELECT count(*) FROM t1 WHERE b LIKE $like }
} {101 0 100}
do_test analyze3-2.5 {
  set like "%a"
  sf_execsql { SELECT count(*) FROM t1 WHERE b LIKE $like }
} {999 999 100}


#-------------------------------------------------------------------------
# This block of tests checks that statements are correctly marked as
# expired when the values bound to any parameters that may affect the 
# query plan are modified.
#
drop_all_tables
db auth auth
proc auth {args} {
  set ::auth 1
  return SQLITE_OK
}

do_test analyze3-3.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b, c);
    CREATE INDEX i1 ON t1(b);
  }
  for {set i 0} {$i < 100} {incr i} {
    execsql { INSERT INTO t1 VALUES($i, $i, $i) }
  }
  execsql COMMIT
  execsql ANALYZE
} {}

do_test analyze3-3.2.1 {
  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE b>?" -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.2.2 {
  sqlite3_bind_text $S 1 "abc" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.2.4 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-3.2.5 {
  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE b=?" -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.2.6 {
  sqlite3_bind_text $S 1 "abc" 3
  sqlite3_expired $S
} {0}
do_test analyze3-3.2.7 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-3.4.1 {
  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.4.2 {
  sqlite3_bind_text $S 1 "abc" 3
  sqlite3_expired $S
} {0}
do_test analyze3-3.4.3 {
  sqlite3_bind_text $S 2 "def" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.4.4 {
  sqlite3_bind_text $S 2 "ghi" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.4.5 {
  sqlite3_expired $S
} {1}
do_test analyze3-3.4.6 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-3.5.1 {
  set S [sqlite3_prepare_v2 db {
    SELECT * FROM t1 WHERE a IN (
      ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10,
      ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20,
      ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31
    ) AND b>?32;
  } -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.5.2 {
  sqlite3_bind_text $S 31 "abc" 3
  sqlite3_expired $S
} {0}
do_test analyze3-3.5.3 {
  sqlite3_bind_text $S 32 "def" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.5.5 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-3.6.1 {
  set S [sqlite3_prepare_v2 db {
    SELECT * FROM t1 WHERE a IN (
      ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10,
      ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20,
      ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32
    ) AND b>?33;
  } -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.6.2 {
  sqlite3_bind_text $S 32 "abc" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.6.3 {
  sqlite3_bind_text $S 33 "def" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.6.5 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-3.7.1 {
breakpoint
  set S [sqlite3_prepare_v2 db {
    SELECT * FROM t1 WHERE a IN (
      ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?33,
      ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20,
      ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32
    ) AND b>?10;
  } -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.7.2 {
  sqlite3_bind_text $S 32 "abc" 3
  sqlite3_expired $S
} {0}
do_test analyze3-3.7.3 {
  sqlite3_bind_text $S 33 "def" 3
  sqlite3_expired $S
} {0}
do_test analyze3-3.7.4 {
  sqlite3_bind_text $S 10 "def" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.7.6 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-3.8.1 {
  execsql {
    CREATE TABLE t4(x, y TEXT COLLATE NOCASE);
    CREATE INDEX i4 ON t4(y);
  }
} {}
do_test analyze3-3.8.2 {
  set S [sqlite3_prepare_v2 db {
    SELECT * FROM t4 WHERE x != ? AND y LIKE ?
  } -1 dummy]
  sqlite3_expired $S
} {0}
do_test analyze3-3.8.3 {
  sqlite3_bind_text $S 1 "abc" 3
  sqlite3_expired $S
} {0}
do_test analyze3-3.8.4 {
  sqlite3_bind_text $S 2 "def" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.7 {
  sqlite3_bind_text $S 2 "ghi%" 4
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.8 {
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.9 {
  sqlite3_bind_text $S 2 "ghi%def" 7
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.10 {
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.11 {
  sqlite3_bind_text $S 2 "%ab" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.12 {
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.12 {
  sqlite3_bind_text $S 2 "%de" 3
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.13 {
  sqlite3_expired $S
} {1}
do_test analyze3-3.8.14 {
  sqlite3_finalize $S
} {SQLITE_OK}

#-------------------------------------------------------------------------
# These tests check that errors encountered while repreparing an SQL
# statement within sqlite3Reprepare() are handled correctly.
#

# Check a schema error.
#
do_test analyze3-4.1.1 {
  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy]
  sqlite3_step $S
} {SQLITE_DONE}
do_test analyze3-4.1.2 {
  sqlite3_reset $S
  sqlite3_bind_text $S 2 "abc" 3
  execsql { DROP TABLE t1 }
  sqlite3_step $S
} {SQLITE_SCHEMA}
do_test analyze3-4.1.3 {
  sqlite3_finalize $S
} {SQLITE_SCHEMA}

# Check an authorization error.
#
do_test analyze3-4.2.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b, c);
    CREATE INDEX i1 ON t1(b);
  }
  for {set i 0} {$i < 100} {incr i} {
    execsql { INSERT INTO t1 VALUES($i, $i, $i) }
  }
  execsql COMMIT
  execsql ANALYZE
  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy]
  sqlite3_step $S
} {SQLITE_DONE}
db auth auth
proc auth {args} {
  if {[lindex $args 0] == "SQLITE_READ"} {return SQLITE_DENY}
  return SQLITE_OK
}
do_test analyze3-4.2.2 {
  sqlite3_reset $S
  sqlite3_bind_text $S 2 "abc" 3
  sqlite3_step $S
} {SQLITE_SCHEMA}
do_test analyze3-4.2.4 {
  sqlite3_finalize $S
} {SQLITE_SCHEMA}

# Check the effect of an authorization error that occurs in a re-prepare
# performed by sqlite3_step() is the same as one that occurs within
# sqlite3Reprepare().
#
do_test analyze3-4.3.1 {
  db auth {}
  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy]
  execsql { CREATE TABLE t2(d, e, f) }
  db auth auth
  sqlite3_step $S
} {SQLITE_SCHEMA}
do_test analyze3-4.3.2 {
  sqlite3_finalize $S
} {SQLITE_SCHEMA}
db auth {}

#-------------------------------------------------------------------------
# Test that modifying bound variables using the clear_bindings() or
# transfer_bindings() APIs works.
#
#   analyze3-5.1.*: sqlite3_clear_bindings()
#   analyze3-5.2.*: sqlite3_transfer_bindings()
#
do_test analyze3-5.1.1 {
  drop_all_tables
  execsql {
    CREATE TABLE t1(x TEXT COLLATE NOCASE);
    CREATE INDEX i1 ON t1(x);
    INSERT INTO t1 VALUES('aaa');
    INSERT INTO t1 VALUES('abb');
    INSERT INTO t1 VALUES('acc');
    INSERT INTO t1 VALUES('baa');
    INSERT INTO t1 VALUES('bbb');
    INSERT INTO t1 VALUES('bcc');
  }

  set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE x LIKE ?" -1 dummy]
  sqlite3_bind_text $S 1 "a%" 2
  set R [list]
  while { "SQLITE_ROW" == [sqlite3_step $S] } {
    lappend R [sqlite3_column_text $S 0]
  }
  concat [sqlite3_reset $S] $R
} {SQLITE_OK aaa abb acc}
do_test analyze3-5.1.2 {
  sqlite3_clear_bindings $S
  set R [list]
  while { "SQLITE_ROW" == [sqlite3_step $S] } {
    lappend R [sqlite3_column_text $S 0]
  }
  concat [sqlite3_reset $S] $R
} {SQLITE_OK}
do_test analyze3-5.1.3 {
  sqlite3_finalize $S
} {SQLITE_OK}

do_test analyze3-5.1.1 {
  set S1 [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE x LIKE ?" -1 dummy]
  sqlite3_bind_text $S1 1 "b%" 2
  set R [list]
  while { "SQLITE_ROW" == [sqlite3_step $S1] } {
    lappend R [sqlite3_column_text $S1 0]
  }
  concat [sqlite3_reset $S1] $R
} {SQLITE_OK baa bbb bcc}

do_test analyze3-5.1.2 {
  set S2 [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE x = ?" -1 dummy]
  sqlite3_bind_text $S2 1 "a%" 2
  sqlite3_transfer_bindings $S2 $S1
  set R [list]
  while { "SQLITE_ROW" == [sqlite3_step $S1] } {
    lappend R [sqlite3_column_text $S1 0]
  }
  concat [sqlite3_reset $S1] $R
} {SQLITE_OK aaa abb acc}
do_test analyze3-5.1.3 {
  sqlite3_finalize $S2
  sqlite3_finalize $S1
} {SQLITE_OK}

finish_test

Added test/async.test.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all tests.
#
# $Id: async.test,v 1.21 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {[info commands sqlite3async_initialize] eq ""} {
  # The async logic is not built into this system
  finish_test
  return
}

rename finish_test async_really_finish_test
proc finish_test {} {
  catch {db close}
  catch {db2 close}
  catch {db3 close}
}
if {[info exists ISQUICK]} { set ASYNC_SAVE_ISQUICK $ISQUICK }
set ISQUICK 1

set ASYNC_INCLUDE {
  insert.test
  insert2.test
  insert3.test
  lock.test
  lock2.test
  lock3.test
  select1.test
  select2.test
  select3.test
  select4.test
  trans.test
}

# Enable asynchronous IO.
sqlite3async_initialize "" 1

rename do_test async_really_do_test
proc do_test {name args} {
  uplevel async_really_do_test async_io-$name $args
  sqlite3async_start
  sqlite3async_control halt idle
  sqlite3async_wait
  sqlite3async_control halt never
}

foreach testfile [lsort -dictionary [glob $testdir/*.test]] {
  set tail [file tail $testfile]
  if {[lsearch -exact $ASYNC_INCLUDE $tail]<0} continue
  source $testfile

  # Make sure everything is flushed through. This is because [source]ing 
  # the next test file will delete the database file on disk (using
  # [file delete]). If the asynchronous backend still has the file
  # open, it will become confused.
  #
  sqlite3async_control halt idle
  sqlite3async_start
  sqlite3async_wait
  sqlite3async_control halt never
}

# Flush the write-queue and disable asynchronous IO. This should ensure
# all allocated memory is cleaned up.
set sqlite3async_trace 1
sqlite3async_control halt idle
sqlite3async_start
sqlite3async_wait
sqlite3async_control halt never
sqlite3async_shutdown
set sqlite3async_trace 0

rename do_test {}
rename async_really_do_test do_test
rename finish_test {}
rename async_really_finish_test finish_test

if {[info exists ASYNC_SAVE_ISQUICK]} { set ISQUICK $ASYNC_SAVE_ISQUICK }
finish_test

Added test/async2.test.





























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: async2.test,v 1.12 2009/04/25 08:39:15 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {
  [info commands sqlite3async_initialize]=="" ||
  [info command sqlite3_memdebug_fail]==""
} {
  # The async logic is not built into this system
  puts "Skipping async2 tests: not compiled with required features"
  finish_test
  return
}

# Enable asynchronous IO.

set setup_script {
  CREATE TABLE counter(c);
  INSERT INTO counter(c) VALUES (1);
} 

set sql_script {
  BEGIN;
    UPDATE counter SET c = 2;
    CREATE TABLE t1(a PRIMARY KEY, b, c);
    CREATE TABLE t2(a PRIMARY KEY, b, c);
  COMMIT;

  BEGIN;
    UPDATE counter SET c = 3;
    INSERT INTO t1 VALUES('abcdefghij', 'four', 'score');
    INSERT INTO t2 VALUES('klmnopqrst', 'and', 'seven');
  COMMIT;

  UPDATE counter SET c = 'FIN';
}

db close

foreach err [list ioerr malloc-transient malloc-persistent] {
  set ::go 10
  for {set n 1} {$::go} {incr n} {
    set ::sqlite_io_error_pending 0
    sqlite3_memdebug_fail -1
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql $::setup_script
    db close
  
    sqlite3async_initialize "" 1
    sqlite3 db test.db
    sqlite3_db_config_lookaside db 0 0 0
  
    switch -- $err {
      ioerr             { set ::sqlite_io_error_pending $n }
      malloc-persistent { sqlite3_memdebug_fail $n -repeat 1 }
      malloc-transient  { sqlite3_memdebug_fail $n -repeat 0 }
    }

    catchsql $::sql_script
    db close

    sqlite3async_control halt idle
    sqlite3async_start
    sqlite3async_wait
    sqlite3async_control halt never
    sqlite3async_shutdown

    set ::sqlite_io_error_pending 0
    sqlite3_memdebug_fail -1

    sqlite3 db test.db
    set c [db one {SELECT c FROM counter LIMIT 1}]
    switch -- $c {
      1 {
        do_test async-$err-1.1.$n {
          execsql {
            SELECT name FROM sqlite_master;
          }
        } {counter}
      }
      2 {
        do_test async-$err-1.2.$n.1 {
          execsql {
            SELECT * FROM t1;
          }
        } {}
        do_test async-$err-1.2.$n.2 {
          execsql {
            SELECT * FROM t2;
          }
        } {}
      }
      3 {
        do_test async-$err-1.3.$n.1 {
          execsql {
            SELECT * FROM t1;
          }
        } {abcdefghij four score}
        do_test async-$err-1.3.$n.2 {
          execsql {
            SELECT * FROM t2;
          }
        } {klmnopqrst and seven}
      }
      FIN {
        incr ::go -1
      }
    }
  
    db close
  }
}

catch {db close}

finish_test

Added test/async3.test.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 2007 September 5
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing the code in test_async.c.
# Specifically, it tests that the xFullPathname() method of
# of the asynchronous vfs works correctly.
#
# $Id: async3.test,v 1.5 2009/04/25 08:39:15 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if { [info commands sqlite3async_initialize]==""  } {
  # The async logic is not built into this system
  puts "Skipping async3 tests: not compiled with required features"
  finish_test
  return
}

db close
sqlite3async_initialize "" 1
#set sqlite3async_trace 1
sqlite3async_start

set paths {
  chocolate/banana/vanilla/file.db
  chocolate//banana/vanilla/file.db
  chocolate/./banana//vanilla/file.db
  chocolate/banana/./vanilla/file.db
  chocolate/banana/../banana/vanilla/file.db
  chocolate/banana/./vanilla/extra_bit/../file.db
}

do_test async3-1.0 {
  file mkdir [file join chocolate banana vanilla]
  file delete -force chocolate/banana/vanilla/file.db
  file delete -force chocolate/banana/vanilla/file.db-journal
} {}

do_test async3-1.1 {
  sqlite3 db chocolate/banana/vanilla/file.db
  execsql {
    CREATE TABLE abc(a, b, c);
    BEGIN;
    INSERT INTO abc VALUES(1, 2, 3);
  }
} {}

set N 2
foreach p $paths {
  sqlite3 db2 $p
  do_test async3-1.$N.1 {
    execsql {SELECT * FROM abc} db2
  } {}
  do_test async3-1.$N.2 {
    catchsql {INSERT INTO abc VALUES(4, 5, 6)} db2
  } {1 {database is locked}}
  db2 close
  incr N
}

db close

sqlite3async_control halt idle
sqlite3async_wait
sqlite3async_control halt never
sqlite3async_shutdown
finish_test

Added test/async4.test.





































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# 2009 April 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: async4.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# These tests only work for Tcl version 8.5 and later on Windows (for now)
#
if {$tcl_platform(platform)=="windows"} {
  scan $::tcl_version %f vx
  if {$vx<8.5} {
    finish_test
    return
  }
}

if {[info commands sqlite3async_initialize] eq ""} {
  # The async logic is not built into this system
  finish_test
  return
}
db close

# Test layout:
#
#   async4.1.*: Test the lockfiles parameter.
#   async4.2.*: Test the delay parameter.

do_test async4.1.1 {
  sqlite3async_initialize {} 0
  sqlite3async_control lockfiles
} {1}
do_test async4.1.2 {
  sqlite3async_control lockfiles false
} {0}
do_test async4.1.3 {
  sqlite3async_control lockfiles
} {0}
do_test async4.1.4 {
  sqlite3async_control lockfiles true
} {1}

do_test async4.1.5 {
  sqlite3 db test.db -vfs sqlite3async
  execsql { CREATE TABLE t1(a, b, c) }
} {}
do_test async4.1.6 {
  list [file exists test.db] [file size test.db]
} {1 0}
do_test async4.1.7 {
  sqlite3 db2 test.db
  catchsql { CREATE TABLE t2(a, b, c) } db2
} {1 {database is locked}}
do_test async4.1.8 {
  sqlite3async_control halt idle
  sqlite3async_start
  sqlite3async_wait
} {}
do_test async4.1.9 {
  catchsql { CREATE TABLE t2(a, b, c) } db2
} {0 {}}
do_test async4.1.10 {
  list [catch {sqlite3async_control lockfiles false} msg] $msg
} {1 SQLITE_MISUSE}
do_test async4.1.11 {
  db close
  list [catch {sqlite3async_control lockfiles false} msg] $msg
} {1 SQLITE_MISUSE}
do_test async4.1.12 {
  sqlite3async_start
  sqlite3async_wait
  sqlite3async_control lockfiles false
} {0}
do_test async4.1.13 {
  sqlite3 db test.db -vfs sqlite3async
  execsql { CREATE TABLE t3(a, b, c) } db
} {}
do_test async4.1.14 {
  execsql { 
    CREATE INDEX i1 ON t2(a);
    CREATE INDEX i2 ON t1(a);
  } db2
} {}
do_test async4.1.15 {
  sqlite3async_start
  sqlite3async_wait
  execsql { pragma integrity_check } db2
} {{*** in database main ***
Page 5 is never used}}
do_test async4.1.16 {
  db close
  db2 close
  sqlite3async_start
  sqlite3async_wait
} {}
do_test async4.1.17 {
  sqlite3async_control lockfiles true
} {1}

do_test async4.2.1 {
  sqlite3async_control delay
} {0}
do_test async4.2.2 {
  sqlite3async_control delay 23
} {23}
do_test async4.2.3 {
  sqlite3async_control delay
} {23}
do_test async4.2.4 {
  sqlite3async_control delay 0
} {0}
do_test async4.2.5 {
  sqlite3 db test.db -vfs sqlite3async

  execsql { CREATE TABLE t4(a, b) }
  set T1 [lindex [time {
    sqlite3async_start
    sqlite3async_wait
  }] 0]

  sqlite3async_control delay 100
  execsql { CREATE TABLE t5(a, b) }
  set T2 [lindex [time {
    sqlite3async_start
    sqlite3async_wait
  }] 0]

  expr {($T1+1000000) < $T2}
} {1}

do_test async4.2.6 {
  sqlite3async_control delay 0
  execsql { CREATE TABLE t6(a, b) }
  set T1 [lindex [time {
    sqlite3async_start
    sqlite3async_wait
  }] 0]

  expr {($T1+1000000) < $T2}
} {1}

do_test async4.2.7 {
  list [catch { sqlite3async_control delay -1 } msg] $msg
} {1 SQLITE_MISUSE}

do_test async4.2.8 {
  db close
  sqlite3async_start
  sqlite3async_wait
} {}

finish_test

Added test/async5.test.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 2009 July 19
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file tests that asynchronous IO is compatible with multi-file
# transactions.
#
# $Id: async5.test,v 1.1 2009/07/18 11:52:04 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {[info commands sqlite3async_initialize] eq ""} {
  # The async logic is not built into this system
  finish_test
  return
}

db close
file delete -force test2.db
sqlite3async_initialize "" 1
sqlite3async_control halt never
sqlite3 db test.db

do_test async5-1.1 {
  execsql {
    ATTACH 'test2.db' AS next;
    CREATE TABLE main.t1(a, b);
    CREATE TABLE next.t2(a, b);
    BEGIN;
      INSERT INTO t1 VALUES(1, 2);
      INSERT INTO t2 VALUES(3, 4);
    COMMIT;
  }
} {}
do_test async5-1.2 {
  execsql { SELECT * FROM t1 }
} {1 2}
do_test async5-1.3 {
  execsql { SELECT * FROM t2 }
} {3 4}
do_test async5-1.4 {
  execsql {
    BEGIN;
      INSERT INTO t1 VALUES('a', 'b');
      INSERT INTO t2 VALUES('c', 'd');
    COMMIT;
  }
} {}
do_test async5-1.5 {
  execsql { SELECT * FROM t1 }
} {1 2 a b}
do_test async5-1.6 {
  execsql { SELECT * FROM t2 }
} {3 4 c d}

db close

sqlite3async_control halt idle
sqlite3async_start
sqlite3async_wait
sqlite3async_control halt never
sqlite3async_shutdown
set sqlite3async_trace 0
finish_test

Added test/attach.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# 2003 April 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the ATTACH and DETACH commands
# and related functionality.
#
# $Id: attach.test,v 1.52 2009/05/29 14:39:08 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !attach {
  finish_test
  return
}

for {set i 2} {$i<=15} {incr i} {
  file delete -force test$i.db
  file delete -force test$i.db-journal
}

do_test attach-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    SELECT * FROM t1;
  }
} {1 2 3 4}
do_test attach-1.2 {
  sqlite3 db2 test2.db
  execsql {
    CREATE TABLE t2(x,y);
    INSERT INTO t2 VALUES(1,'x');
    INSERT INTO t2 VALUES(2,'y');
    SELECT * FROM t2;
  } db2
} {1 x 2 y}
do_test attach-1.3 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    SELECT * FROM two.t2;
  }
} {1 x 2 y}
do_test attach-1.4 {
  execsql {
    SELECT * FROM t2;
  }
} {1 x 2 y}
do_test attach-1.5 {
  execsql {
    DETACH DATABASE two;
    SELECT * FROM t1;
  }
} {1 2 3 4}
do_test attach-1.6 {
  catchsql {
    SELECT * FROM t2;
  }
} {1 {no such table: t2}}
do_test attach-1.7 {
  catchsql {
    SELECT * FROM two.t2;
  }
} {1 {no such table: two.t2}}
do_test attach-1.8 {
  catchsql {
    ATTACH DATABASE 'test3.db' AS three;
  }
} {0 {}}
do_test attach-1.9 {
  catchsql {
    SELECT * FROM three.sqlite_master;
  }
} {0 {}}
do_test attach-1.10 {
  catchsql {
    DETACH DATABASE [three];
  }
} {0 {}}
do_test attach-1.11 {
  execsql {
    ATTACH 'test.db' AS db2;
    ATTACH 'test.db' AS db3;
    ATTACH 'test.db' AS db4;
    ATTACH 'test.db' AS db5;
    ATTACH 'test.db' AS db6;
    ATTACH 'test.db' AS db7;
    ATTACH 'test.db' AS db8;
    ATTACH 'test.db' AS db9;
  }
} {}
proc db_list {db} {
  set list {}
  foreach {idx name file} [execsql {PRAGMA database_list} $db] {
    lappend list $idx $name
  }
  return $list
}
ifcapable schema_pragmas {
do_test attach-1.11b {
  db_list db
} {0 main 2 db2 3 db3 4 db4 5 db5 6 db6 7 db7 8 db8 9 db9}
} ;# ifcapable schema_pragmas 
do_test attach-1.12 {
  catchsql {
    ATTACH 'test.db' as db2;
  }
} {1 {database db2 is already in use}}
do_test attach-1.12.2 {
  db errorcode
} {1}
do_test attach-1.13 {
  catchsql {
    ATTACH 'test.db' as db5;
  }
} {1 {database db5 is already in use}}
do_test attach-1.14 {
  catchsql {
    ATTACH 'test.db' as db9;
  }
} {1 {database db9 is already in use}}
do_test attach-1.15 {
  catchsql {
    ATTACH 'test.db' as main;
  }
} {1 {database main is already in use}}
ifcapable tempdb {
  do_test attach-1.16 {
    catchsql {
      ATTACH 'test.db' as temp;
    }
  } {1 {database temp is already in use}}
}
do_test attach-1.17 {
  catchsql {
    ATTACH 'test.db' as MAIN;
  }
} {1 {database MAIN is already in use}}
do_test attach-1.18 {
  catchsql {
    ATTACH 'test.db' as db10;
    ATTACH 'test.db' as db11;
  }
} {0 {}}
do_test attach-1.19 {
  catchsql {
    ATTACH 'test.db' as db12;
  }
} {1 {too many attached databases - max 10}}
do_test attach-1.19.1 {
  db errorcode
} {1}
do_test attach-1.20.1 {
  execsql {
    DETACH db5;
  }
} {}
ifcapable schema_pragmas {
do_test attach-1.20.2 {
  db_list db
} {0 main 2 db2 3 db3 4 db4 5 db6 6 db7 7 db8 8 db9 9 db10 10 db11}
} ;# ifcapable schema_pragmas
integrity_check attach-1.20.3
ifcapable tempdb {
  execsql {select * from sqlite_temp_master}
}
do_test attach-1.21 {
  catchsql {
    ATTACH 'test.db' as db12;
  }
} {0 {}}
do_test attach-1.22 {
  catchsql {
    ATTACH 'test.db' as db13;
  }
} {1 {too many attached databases - max 10}}
do_test attach-1.22.1 {
  db errorcode
} {1}
do_test attach-1.23 {
  catchsql {
    DETACH "db14";
  }
} {1 {no such database: db14}}
do_test attach-1.24 {
  catchsql {
    DETACH db12;
  }
} {0 {}}
do_test attach-1.25 {
  catchsql {
    DETACH db12;
  }
} {1 {no such database: db12}}
do_test attach-1.26 {
  catchsql {
    DETACH main;
  }
} {1 {cannot detach database main}}

ifcapable tempdb {
  do_test attach-1.27 {
    catchsql {
      DETACH Temp;
    }
  } {1 {cannot detach database Temp}}
} else {
  do_test attach-1.27 {
    catchsql {
      DETACH Temp;
    }
  } {1 {no such database: Temp}}
}

do_test attach-1.28 {
  catchsql {
    DETACH db11;
    DETACH db10;
    DETACH db9;
    DETACH db8;
    DETACH db7;
    DETACH db6;
    DETACH db4;
    DETACH db3;
    DETACH db2;
  }
} {0 {}}
ifcapable schema_pragmas {
  ifcapable tempdb {
    do_test attach-1.29 {
      db_list db
    } {0 main 1 temp}
  } else {
    do_test attach-1.29 {
      db_list db
    } {0 main}
  }
} ;# ifcapable schema_pragmas

ifcapable {trigger} {  # Only do the following tests if triggers are enabled
do_test attach-2.1 {
  execsql {
    CREATE TABLE tx(x1,x2,y1,y2);
    CREATE TRIGGER r1 AFTER UPDATE ON t2 FOR EACH ROW BEGIN
      INSERT INTO tx(x1,x2,y1,y2) VALUES(OLD.x,NEW.x,OLD.y,NEW.y);
    END;
    SELECT * FROM tx;
  } db2;
} {}
do_test attach-2.2 {
  execsql {
    UPDATE t2 SET x=x+10;
    SELECT * FROM tx;
  } db2;
} {1 11 x x 2 12 y y}
do_test attach-2.3 {
  execsql {
    CREATE TABLE tx(x1,x2,y1,y2);
    SELECT * FROM tx;
  }
} {}
do_test attach-2.4 {
  execsql {
    ATTACH 'test2.db' AS db2;
  }
} {}
do_test attach-2.5 {
  execsql {
    UPDATE db2.t2 SET x=x+10;
    SELECT * FROM db2.tx;
  }
} {1 11 x x 2 12 y y 11 21 x x 12 22 y y}
do_test attach-2.6 {
  execsql {
    SELECT * FROM main.tx;
  }
} {}
do_test attach-2.7 {
  execsql {
    SELECT type, name, tbl_name FROM db2.sqlite_master;
  }
} {table t2 t2 table tx tx trigger r1 t2}

ifcapable schema_pragmas&&tempdb {
  do_test attach-2.8 {
    db_list db
  } {0 main 1 temp 2 db2}
} ;# ifcapable schema_pragmas&&tempdb
ifcapable schema_pragmas&&!tempdb {
  do_test attach-2.8 {
    db_list db
  } {0 main 2 db2}
} ;# ifcapable schema_pragmas&&!tempdb

do_test attach-2.9 {
  execsql {
    CREATE INDEX i2 ON t2(x);
    SELECT * FROM t2 WHERE x>5;
  } db2
} {21 x 22 y}
do_test attach-2.10 {
  execsql {
    SELECT type, name, tbl_name FROM sqlite_master;
  } db2
} {table t2 t2 table tx tx trigger r1 t2 index i2 t2}
#do_test attach-2.11 {
#  catchsql { 
#    SELECT * FROM t2 WHERE x>5;
#  }
#} {1 {database schema has changed}}
ifcapable schema_pragmas {
  ifcapable tempdb {
    do_test attach-2.12 {
      db_list db
    } {0 main 1 temp 2 db2}
  } else {
    do_test attach-2.12 {
      db_list db
    } {0 main 2 db2}
  }
} ;# ifcapable schema_pragmas
do_test attach-2.13 {
  catchsql {
    SELECT * FROM t2 WHERE x>5;
  }
} {0 {21 x 22 y}}
do_test attach-2.14 {
  execsql {
    SELECT type, name, tbl_name FROM sqlite_master;
  }
} {table t1 t1 table tx tx}
do_test attach-2.15 {
  execsql {
    SELECT type, name, tbl_name FROM db2.sqlite_master;
  }
} {table t2 t2 table tx tx trigger r1 t2 index i2 t2}
do_test attach-2.16 {
  db close
  sqlite3 db test.db
  execsql {
    ATTACH 'test2.db' AS db2;
    SELECT type, name, tbl_name FROM db2.sqlite_master;
  }
} {table t2 t2 table tx tx trigger r1 t2 index i2 t2}
} ;# End of ifcapable {trigger}

do_test attach-3.1 {
  db close
  db2 close
  sqlite3 db test.db
  sqlite3 db2 test2.db
  execsql {
    SELECT * FROM t1
  }
} {1 2 3 4}

# If we are testing a version of the code that lacks trigger support,
# adjust the database contents so that they are the same if triggers
# had been enabled.
ifcapable {!trigger} {
  db2 eval {
    DELETE FROM t2;
    INSERT INTO t2 VALUES(21, 'x');
    INSERT INTO t2 VALUES(22, 'y');
    CREATE TABLE tx(x1,x2,y1,y2);
    INSERT INTO tx VALUES(1, 11, 'x', 'x');
    INSERT INTO tx VALUES(2, 12, 'y', 'y');
    INSERT INTO tx VALUES(11, 21, 'x', 'x');
    INSERT INTO tx VALUES(12, 22, 'y', 'y');
    CREATE INDEX i2 ON t2(x);
  }
}

do_test attach-3.2 {
  catchsql {
    SELECT * FROM t2
  }
} {1 {no such table: t2}}
do_test attach-3.3 {
  catchsql {
    ATTACH DATABASE 'test2.db' AS db2;
    SELECT * FROM t2
  }
} {0 {21 x 22 y}}

# Even though 'db' has started a transaction, it should not yet have
# a lock on test2.db so 'db2' should be readable.
do_test attach-3.4 {
  execsql BEGIN
  catchsql {
    SELECT * FROM t2;
  } db2;
} {0 {21 x 22 y}}

# Reading from test2.db from db within a transaction should not
# prevent test2.db from being read by db2.
do_test attach-3.5 {
  execsql {SELECT * FROM t2}
  catchsql {
    SELECT * FROM t2;
  } db2;
} {0 {21 x 22 y}}

# Making a change to test2.db through db  causes test2.db to get
# a reserved lock.  It should still be accessible through db2.
do_test attach-3.6 {
  execsql {
    UPDATE t2 SET x=x+1 WHERE x=50;
  }
  catchsql {
    SELECT * FROM t2;
  } db2;
} {0 {21 x 22 y}}

do_test attach-3.7 {
  execsql ROLLBACK
  execsql {SELECT * FROM t2} db2
} {21 x 22 y}

# Start transactions on both db and db2.  Once again, just because
# we make a change to test2.db using db2, only a RESERVED lock is
# obtained, so test2.db should still be readable using db.
#
do_test attach-3.8 {
  execsql BEGIN
  execsql BEGIN db2
  execsql {UPDATE t2 SET x=0 WHERE 0} db2
  catchsql {SELECT * FROM t2}
} {0 {21 x 22 y}}

# It is also still accessible from db2.
do_test attach-3.9 {
  catchsql {SELECT * FROM t2} db2
} {0 {21 x 22 y}}

do_test attach-3.10 {
  execsql {SELECT * FROM t1}
} {1 2 3 4}

do_test attach-3.11 {
  catchsql {UPDATE t1 SET a=a+1}
} {0 {}}
do_test attach-3.12 {
  execsql {SELECT * FROM t1}
} {2 2 4 4}

# db2 has a RESERVED lock on test2.db, so db cannot write to any tables
# in test2.db.
do_test attach-3.13 {
  catchsql {UPDATE t2 SET x=x+1 WHERE x=50}
} {1 {database is locked}}

# Change for version 3. Transaction is no longer rolled back
# for a locked database.
execsql {ROLLBACK}

# db is able to reread its schema because db2 still only holds a
# reserved lock.
do_test attach-3.14 {
  catchsql {SELECT * FROM t1}
} {0 {1 2 3 4}}
do_test attach-3.15 {
  execsql COMMIT db2
  execsql {SELECT * FROM t1}
} {1 2 3 4}

# Ticket #323
do_test attach-4.1 {
  execsql {DETACH db2}
  db2 close
  sqlite3 db2 test2.db
  execsql {
    CREATE TABLE t3(x,y);
    CREATE UNIQUE INDEX t3i1 ON t3(x);
    INSERT INTO t3 VALUES(1,2);
    SELECT * FROM t3;
  } db2;
} {1 2}
do_test attach-4.2 {
  execsql {
    CREATE TABLE t3(a,b);
    CREATE UNIQUE INDEX t3i1b ON t3(a);
    INSERT INTO t3 VALUES(9,10);
    SELECT * FROM t3;
  }
} {9 10}
do_test attach-4.3 {
  execsql {
    ATTACH DATABASE 'test2.db' AS db2;
    SELECT * FROM db2.t3;
  }
} {1 2}
do_test attach-4.4 {
  execsql {
    SELECT * FROM main.t3;
  }
} {9 10}
do_test attach-4.5 {
  execsql {
    INSERT INTO db2.t3 VALUES(9,10);
    SELECT * FROM db2.t3;
  }
} {1 2 9 10}
execsql {
  DETACH db2;
}
ifcapable {trigger} {
  do_test attach-4.6 {
    execsql {
      CREATE TABLE t4(x);
      CREATE TRIGGER t3r3 AFTER INSERT ON t3 BEGIN
        INSERT INTO t4 VALUES('db2.' || NEW.x);
      END;
      INSERT INTO t3 VALUES(6,7);
      SELECT * FROM t4;
    } db2
  } {db2.6}
  do_test attach-4.7 {
    execsql {
      CREATE TABLE t4(y);
      CREATE TRIGGER t3r3 AFTER INSERT ON t3 BEGIN
        INSERT INTO t4 VALUES('main.' || NEW.a);
      END;
      INSERT INTO main.t3 VALUES(11,12);
      SELECT * FROM main.t4;
    }
  } {main.11}
}
ifcapable {!trigger} {
  # When we do not have trigger support, set up the table like they
  # would have been had triggers been there.  The tests that follow need
  # this setup.
  execsql {
    CREATE TABLE t4(x);
    INSERT INTO t3 VALUES(6,7);
    INSERT INTO t4 VALUES('db2.6');
    INSERT INTO t4 VALUES('db2.13');
  } db2
  execsql {
    CREATE TABLE t4(y);
    INSERT INTO main.t3 VALUES(11,12);
    INSERT INTO t4 VALUES('main.11');
  }
}


# This one is tricky.  On the UNION ALL select, we have to make sure
# the schema for both main and db2 is valid before starting to execute
# the first query of the UNION ALL.  If we wait to test the validity of
# the schema for main until after the first query has run, that test will
# fail and the query will abort but we will have already output some
# results.  When the query is retried, the results will be repeated.
#
ifcapable compound {
do_test attach-4.8 {
  execsql {
    ATTACH DATABASE 'test2.db' AS db2;
    INSERT INTO db2.t3 VALUES(13,14);
    SELECT * FROM db2.t4 UNION ALL SELECT * FROM main.t4;
  }
} {db2.6 db2.13 main.11}

do_test attach-4.9 {
  ifcapable {!trigger} {execsql {INSERT INTO main.t4 VALUES('main.15')}}
  execsql {
    INSERT INTO main.t3 VALUES(15,16);
    SELECT * FROM db2.t4 UNION ALL SELECT * FROM main.t4;
  }
} {db2.6 db2.13 main.11 main.15}
} ;# ifcapable compound

ifcapable !compound {
  ifcapable {!trigger} {execsql {INSERT INTO main.t4 VALUES('main.15')}}
  execsql {
    ATTACH DATABASE 'test2.db' AS db2;
    INSERT INTO db2.t3 VALUES(13,14);
    INSERT INTO main.t3 VALUES(15,16);
  } 
} ;# ifcapable !compound

ifcapable view {
do_test attach-4.10 {
  execsql {
    DETACH DATABASE db2;
  }
  execsql {
    CREATE VIEW v3 AS SELECT x*100+y FROM t3;
    SELECT * FROM v3;
  } db2
} {102 910 607 1314}
do_test attach-4.11 {
  execsql {
    CREATE VIEW v3 AS SELECT a*100+b FROM t3;
    SELECT * FROM v3;
  }
} {910 1112 1516}
do_test attach-4.12 {
  execsql {
    ATTACH DATABASE 'test2.db' AS db2;
    SELECT * FROM db2.v3;
  }
} {102 910 607 1314}
do_test attach-4.13 {
  execsql {
    SELECT * FROM main.v3;
  }
} {910 1112 1516}
} ;# ifcapable view

# Tests for the sqliteFix...() routines in attach.c
#
ifcapable {trigger} {
do_test attach-5.1 {
  db close
  sqlite3 db test.db
  db2 close
  file delete -force test2.db
  sqlite3 db2 test2.db
  catchsql {
    ATTACH DATABASE 'test.db' AS orig;
    CREATE TRIGGER r1 AFTER INSERT ON orig.t1 BEGIN
      SELECT 'no-op';
    END;
  } db2
} {1 {trigger r1 cannot reference objects in database orig}}
do_test attach-5.2 {
  catchsql {
    CREATE TABLE t5(x,y);
    CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
      SELECT 'no-op';
    END;
  } db2
} {0 {}}
do_test attach-5.3 {
  catchsql {
    DROP TRIGGER r5;
    CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
      SELECT 'no-op' FROM orig.t1;
    END;
  } db2
} {1 {trigger r5 cannot reference objects in database orig}}
ifcapable tempdb {
  do_test attach-5.4 {
    catchsql {
      CREATE TEMP TABLE t6(p,q,r);
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        SELECT 'no-op' FROM temp.t6;
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
}
ifcapable subquery {
  do_test attach-5.5 {
    catchsql {
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        SELECT 'no-op' || (SELECT * FROM temp.t6);
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
  do_test attach-5.6 {
    catchsql {
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        SELECT 'no-op' FROM t1 WHERE x<(SELECT min(x) FROM temp.t6);
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
  do_test attach-5.7 {
    catchsql {
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        SELECT 'no-op' FROM t1 GROUP BY 1 HAVING x<(SELECT min(x) FROM temp.t6);
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
  do_test attach-5.7 {
    catchsql {
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        SELECT max(1,x,(SELECT min(x) FROM temp.t6)) FROM t1;
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
  do_test attach-5.8 {
    catchsql {
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        INSERT INTO t1 VALUES((SELECT min(x) FROM temp.t6),5);
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
  do_test attach-5.9 {
    catchsql {
      CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN
        DELETE FROM t1 WHERE x<(SELECT min(x) FROM temp.t6);
      END;
    } db2
  } {1 {trigger r5 cannot reference objects in database temp}}
} ;# endif subquery
} ;# endif trigger

# Check to make sure we get a sensible error if unable to open
# the file that we are trying to attach.
#
do_test attach-6.1 {
  catchsql {
    ATTACH DATABASE 'no-such-file' AS nosuch;
  }
} {0 {}}
if {$tcl_platform(platform)=="unix"} {
  do_test attach-6.2 {
    sqlite3 dbx cannot-read
    dbx eval {CREATE TABLE t1(a,b,c)}
    dbx close
    file attributes cannot-read -permission 0000
    if {[file writable cannot-read]} {
      puts "\n**** Tests do not work when run as root ****"
      file delete -force cannot-read
      exit 1
    }
    catchsql {
      ATTACH DATABASE 'cannot-read' AS noread;
    }
  } {1 {unable to open database: cannot-read}}
  do_test attach-6.2.2 {
    db errorcode
  } {14}
  file delete -force cannot-read
}

# Check the error message if we try to access a database that has
# not been attached.
do_test attach-6.3 {
  catchsql {
    CREATE TABLE no_such_db.t1(a, b, c);
  }
} {1 {unknown database no_such_db}}
for {set i 2} {$i<=15} {incr i} {
  catch {db$i close}
}
db close
file delete -force test2.db
file delete -force no-such-file

ifcapable subquery {
  do_test attach-7.1 {
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    catchsql {
      DETACH RAISE ( IGNORE ) IN ( SELECT "AAAAAA" . * ORDER BY 
      REGISTER LIMIT "AAAAAA" . "AAAAAA" OFFSET RAISE ( IGNORE ) NOT NULL )
    }
  } {1 {no such table: AAAAAA}}
}

# Create a malformed file (a file that is not a valid database)
# and try to attach it
#
do_test attach-8.1 {
  set fd [open test2.db w]
  puts $fd "This file is not a valid SQLite database"
  close $fd
  catchsql {
    ATTACH 'test2.db' AS t2;
  }
} {1 {file is encrypted or is not a database}}
do_test attach-8.2 {
  db errorcode
} {26}
file delete -force test2.db
do_test attach-8.3 {
  sqlite3 db2 test2.db
  db2 eval {CREATE TABLE t1(x); BEGIN EXCLUSIVE}
  catchsql {
    ATTACH 'test2.db' AS t2;
  }
} {1 {database is locked}}
do_test attach-8.4 {
  db errorcode
} {5}
db2 close
file delete -force test2.db


finish_test

Added test/attach2.test.





















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# 2003 July 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the ATTACH and DETACH commands
# and related functionality.
#
# $Id: attach2.test,v 1.38 2007/12/13 21:54:11 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !attach {
  finish_test
  return
}

# Ticket #354
#
# Databases test.db and test2.db contain identical schemas.  Make
# sure we can attach test2.db from test.db.
#
do_test attach2-1.1 {
  db eval {
    CREATE TABLE t1(a,b);
    CREATE INDEX x1 ON t1(a);
  }
  file delete -force test2.db
  file delete -force test2.db-journal
  sqlite3 db2 test2.db
  db2 eval {
    CREATE TABLE t1(a,b);
    CREATE INDEX x1 ON t1(a);
  }
  catchsql {
    ATTACH 'test2.db' AS t2;
  }
} {0 {}}

# Ticket #514
#
proc db_list {db} {
  set list {}
  foreach {idx name file} [execsql {PRAGMA database_list} $db] {
    lappend list $idx $name
  }
  return $list
}
db eval {DETACH t2}
do_test attach2-2.1 {
  # lock test2.db then try to attach it.  This is no longer an error because
  # db2 just RESERVES the database.  It does not obtain a write-lock until
  # we COMMIT.
  db2 eval {BEGIN}
  db2 eval {UPDATE t1 SET a = 0 WHERE 0}
  catchsql {
    ATTACH 'test2.db' AS t2;
  }
} {0 {}}
ifcapable schema_pragmas {
do_test attach2-2.2 {
  # make sure test2.db did get attached.
  db_list db
} {0 main 2 t2}
} ;# ifcapable schema_pragmas
db2 eval {COMMIT}

do_test attach2-2.5 {
  # Make sure we can read test2.db from db
  catchsql {
    SELECT name FROM t2.sqlite_master;
  }
} {0 {t1 x1}}
do_test attach2-2.6 {
  # lock test2.db and try to read from it.  This should still work because
  # the lock is only a RESERVED lock which does not prevent reading.
  #
  db2 eval BEGIN
  db2 eval {UPDATE t1 SET a = 0 WHERE 0}
  catchsql {
    SELECT name FROM t2.sqlite_master;
  }
} {0 {t1 x1}}
do_test attach2-2.7 {
  # but we can still read from test1.db even though test2.db is locked.
  catchsql {
    SELECT name FROM main.sqlite_master;
  }
} {0 {t1 x1}}
do_test attach2-2.8 {
  # start a transaction on test.db even though test2.db is locked.
  catchsql {
    BEGIN;
    INSERT INTO t1 VALUES(8,9);
  }
} {0 {}}
do_test attach2-2.9 {
  execsql {
    SELECT * FROM t1
  }
} {8 9}
do_test attach2-2.10 {
  # now try to write to test2.db.  the write should fail
  catchsql {
    INSERT INTO t2.t1 VALUES(1,2);
  }
} {1 {database is locked}}
do_test attach2-2.11 {
  # when the write failed in the previous test, the transaction should
  # have rolled back.
  # 
  # Update for version 3: A transaction is no longer rolled back if a
  #                       database is found to be busy.
  execsql {rollback}
  db2 eval ROLLBACK
  execsql {
    SELECT * FROM t1
  }
} {}
do_test attach2-2.12 {
  catchsql {
    COMMIT
  }
} {1 {cannot commit - no transaction is active}}

# Ticket #574:  Make sure it works using the non-callback API
#
do_test attach2-3.1 {
  set DB [sqlite3_connection_pointer db]
  set rc [catch {sqlite3_prepare $DB "ATTACH 'test2.db' AS t2" -1 TAIL} VM]
  if {$rc} {lappend rc $VM}
  sqlite3_step $VM
  sqlite3_finalize $VM
  set rc
} {0}
do_test attach2-3.2 {
  set rc [catch {sqlite3_prepare $DB "DETACH t2" -1 TAIL} VM]
  if {$rc} {lappend rc $VM}
  sqlite3_step $VM
  sqlite3_finalize $VM
  set rc
} {0}

db close
for {set i 2} {$i<=15} {incr i} {
  catch {db$i close}
}

# A procedure to verify the status of locks on a database.
#
proc lock_status {testnum db expected_result} {
  # If the database was compiled with OMIT_TEMPDB set, then 
  # the lock_status list will not contain an entry for the temp
  # db. But the test code doesn't know this, so its easiest 
  # to filter it out of the $expected_result list here.
  ifcapable !tempdb {
    set expected_result [concat \
        [lrange $expected_result 0 1] \
        [lrange $expected_result 4 end] \
    ]
  }
  do_test attach2-$testnum [subst {
    $db cache flush  ;# The lock_status pragma should not be cached
    execsql {PRAGMA lock_status} $db
  }] $expected_result
}
set sqlite_os_trace 0

# Tests attach2-4.* test that read-locks work correctly with attached
# databases.
do_test attach2-4.1 {
  sqlite3 db test.db
  sqlite3 db2 test.db
  execsql {ATTACH 'test2.db' as file2}
  execsql {ATTACH 'test2.db' as file2} db2
} {}

lock_status 4.1.1 db {main unlocked temp closed file2 unlocked}
lock_status 4.1.2 db2 {main unlocked temp closed file2 unlocked}

do_test attach2-4.2 {
  # Handle 'db' read-locks test.db
  execsql {BEGIN}
  execsql {SELECT * FROM t1}
  # Lock status:
  #    db  - shared(main)
  #    db2 -
} {}

lock_status 4.2.1 db {main shared temp closed file2 unlocked}
lock_status 4.2.2 db2 {main unlocked temp closed file2 unlocked}

do_test attach2-4.3 {
  # The read lock held by db does not prevent db2 from reading test.db
  execsql {SELECT * FROM t1} db2
} {}

lock_status 4.3.1 db {main shared temp closed file2 unlocked}
lock_status 4.3.2 db2 {main unlocked temp closed file2 unlocked}

do_test attach2-4.4 {
  # db is holding a read lock on test.db, so we should not be able
  # to commit a write to test.db from db2
  catchsql {
    INSERT INTO t1 VALUES(1, 2)
  } db2 
} {1 {database is locked}}

lock_status 4.4.1 db {main shared temp closed file2 unlocked}
lock_status 4.4.2 db2 {main unlocked temp closed file2 unlocked}

# We have to make sure that the cache_size and the soft_heap_limit
# are large enough to hold the entire change in memory.  If either
# is set too small, then changes will spill to the database, forcing
# a reserved lock to promote to exclusive.  That will mess up our
# test results. 

set soft_limit [sqlite3_soft_heap_limit 0]


do_test attach2-4.5 {
  # Handle 'db2' reserves file2.
  execsql {BEGIN} db2
  execsql {INSERT INTO file2.t1 VALUES(1, 2)} db2
  # Lock status:
  #    db  - shared(main)
  #    db2 - reserved(file2)
} {}

lock_status 4.5.1 db {main shared temp closed file2 unlocked}
lock_status 4.5.2 db2 {main unlocked temp closed file2 reserved}

do_test attach2-4.6.1 {
  # Reads are allowed against a reserved database.
  catchsql {
    SELECT * FROM file2.t1;
  }
  # Lock status:
  #    db  - shared(main), shared(file2)
  #    db2 - reserved(file2)
} {0 {}}

lock_status 4.6.1.1 db {main shared temp closed file2 shared}
lock_status 4.6.1.2 db2 {main unlocked temp closed file2 reserved}

do_test attach2-4.6.2 {
  # Writes against a reserved database are not allowed.
  catchsql {
    UPDATE file2.t1 SET a=0;
  }
} {1 {database is locked}}

lock_status 4.6.2.1 db {main shared temp closed file2 shared}
lock_status 4.6.2.2 db2 {main unlocked temp closed file2 reserved}

do_test attach2-4.7 {
  # Ensure handle 'db' retains the lock on the main file after
  # failing to obtain a write-lock on file2.
  catchsql {
    INSERT INTO t1 VALUES(1, 2)
  } db2 
} {0 {}}

lock_status 4.7.1 db {main shared temp closed file2 shared}
lock_status 4.7.2 db2 {main reserved temp closed file2 reserved}

do_test attach2-4.8 {
  # We should still be able to read test.db from db2
  execsql {SELECT * FROM t1} db2
} {1 2}

lock_status 4.8.1 db {main shared temp closed file2 shared}
lock_status 4.8.2 db2 {main reserved temp closed file2 reserved}

do_test attach2-4.9 {
  # Try to upgrade the handle 'db' lock.
  catchsql {
    INSERT INTO t1 VALUES(1, 2)
  }
} {1 {database is locked}}

lock_status 4.9.1 db {main shared temp closed file2 shared}
lock_status 4.9.2 db2 {main reserved temp closed file2 reserved}

do_test attach2-4.10 {
  # We cannot commit db2 while db is holding a read-lock
  catchsql {COMMIT} db2
} {1 {database is locked}}

lock_status 4.10.1 db {main shared temp closed file2 shared}
lock_status 4.10.2 db2 {main pending temp closed file2 reserved}

set sqlite_os_trace 0
do_test attach2-4.11 {
  # db is able to commit.
  catchsql {COMMIT}
} {0 {}}

lock_status 4.11.1 db {main unlocked temp closed file2 unlocked}
lock_status 4.11.2 db2 {main pending temp closed file2 reserved}

do_test attach2-4.12 {
  # Now we can commit db2
  catchsql {COMMIT} db2
} {0 {}}

lock_status 4.12.1 db {main unlocked temp closed file2 unlocked}
lock_status 4.12.2 db2 {main unlocked temp closed file2 unlocked}

do_test attach2-4.13 {
  execsql {SELECT * FROM file2.t1}
} {1 2}
do_test attach2-4.14 {
  execsql {INSERT INTO t1 VALUES(1, 2)}
} {}
do_test attach2-4.15 {
  execsql {SELECT * FROM t1} db2
} {1 2 1 2}

db close
db2 close
file delete -force test2.db
sqlite3_soft_heap_limit $soft_limit

# These tests - attach2-5.* - check that the master journal file is deleted
# correctly when a multi-file transaction is committed or rolled back.
#
# Update: It's not actually created if a rollback occurs, so that test
# doesn't really prove too much.
foreach f [glob test.db*] {file delete -force $f}
do_test attach2-5.1 {
  sqlite3 db test.db
  execsql {
    ATTACH 'test.db2' AS aux;
  }
} {}
do_test attach2-5.2 {
  execsql {
    BEGIN;
    CREATE TABLE tbl(a, b, c);
    CREATE TABLE aux.tbl(a, b, c);
    COMMIT;
  }
} {}
do_test attach2-5.3 {
  lsort [glob test.db*]
} {test.db test.db2}
do_test attach2-5.4 {
  execsql {
    BEGIN;
    DROP TABLE aux.tbl;
    DROP TABLE tbl;
    ROLLBACK;
  }
} {}
do_test attach2-5.5 {
  lsort [glob test.db*]
} {test.db test.db2}

# Check that a database cannot be ATTACHed or DETACHed during a transaction.
do_test attach2-6.1 {
  execsql {
    BEGIN;
  }
} {}
do_test attach2-6.2 {
  catchsql {
    ATTACH 'test3.db' as aux2;
  }
} {1 {cannot ATTACH database within transaction}}

do_test attach2-6.3 {
  catchsql {
    DETACH aux;
  }
} {1 {cannot DETACH database within transaction}}
do_test attach2-6.4 {
  execsql {
    COMMIT;
    DETACH aux;
  }
} {}

db close

finish_test

Added test/attach3.test.





































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# 2003 July 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the ATTACH and DETACH commands
# and schema changes to attached databases.
#
# $Id: attach3.test,v 1.18 2007/10/09 08:29:32 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !attach {
  finish_test
  return
}

# The tests in this file were written before SQLite supported recursive
# trigger invocation, and some tests depend on that to pass. So disable
# recursive triggers for this file.
catchsql { pragma recursive_triggers = off } 

# Create tables t1 and t2 in the main database
execsql {
  CREATE TABLE t1(a, b);
  CREATE TABLE t2(c, d);
}

# Create tables t1 and t2 in database file test2.db
file delete -force test2.db
file delete -force test2.db-journal
sqlite3 db2 test2.db
execsql {
  CREATE TABLE t1(a, b);
  CREATE TABLE t2(c, d);
} db2
db2 close

# Create a table in the auxilary database.
do_test attach3-1.1 {
  execsql {
    ATTACH 'test2.db' AS aux;
  }
} {}
do_test attach3-1.2 {
  execsql {
    CREATE TABLE aux.t3(e, f);
  }
} {}
do_test attach3-1.3 {
  execsql {
    SELECT * FROM sqlite_master WHERE name = 't3';
  }
} {}
do_test attach3-1.4 {
  execsql {
    SELECT * FROM aux.sqlite_master WHERE name = 't3';
  }
} "table t3 t3 [expr $AUTOVACUUM?5:4] {CREATE TABLE t3(e, f)}"
do_test attach3-1.5 {
  execsql {
    INSERT INTO t3 VALUES(1, 2);
    SELECT * FROM t3;
  }
} {1 2}

# Create an index on the auxilary database table.
do_test attach3-2.1 {
  execsql {
    CREATE INDEX aux.i1 on t3(e);
  }
} {}
do_test attach3-2.2 {
  execsql {
    SELECT * FROM sqlite_master WHERE name = 'i1';
  }
} {}
do_test attach3-2.3 {
  execsql {
    SELECT * FROM aux.sqlite_master WHERE name = 'i1';
  }
} "index i1 t3 [expr $AUTOVACUUM?6:5] {CREATE INDEX i1 on t3(e)}"

# Drop the index on the aux database table.
do_test attach3-3.1 {
  execsql {
    DROP INDEX aux.i1;
    SELECT * FROM aux.sqlite_master WHERE name = 'i1';
  }
} {}
do_test attach3-3.2 {
  execsql {
    CREATE INDEX aux.i1 on t3(e);
    SELECT * FROM aux.sqlite_master WHERE name = 'i1';
  }
} "index i1 t3 [expr $AUTOVACUUM?6:5] {CREATE INDEX i1 on t3(e)}"
do_test attach3-3.3 {
  execsql {
    DROP INDEX i1;
    SELECT * FROM aux.sqlite_master WHERE name = 'i1';
  }
} {}

# Drop tables t1 and t2 in the auxilary database.
do_test attach3-4.1 {
  execsql {
    DROP TABLE aux.t1;
    SELECT name FROM aux.sqlite_master;
  }
} {t2 t3}
do_test attach3-4.2 {
  # This will drop main.t2
  execsql {
    DROP TABLE t2;
    SELECT name FROM aux.sqlite_master;
  }
} {t2 t3}
do_test attach3-4.3 {
  execsql {
    DROP TABLE t2;
    SELECT name FROM aux.sqlite_master;
  }
} {t3}

# Create a view in the auxilary database.
ifcapable view {
do_test attach3-5.1 {
  execsql {
    CREATE VIEW aux.v1 AS SELECT * FROM t3;
  }
} {}
do_test attach3-5.2 {
  execsql {
    SELECT * FROM aux.sqlite_master WHERE name = 'v1';
  }
} {view v1 v1 0 {CREATE VIEW v1 AS SELECT * FROM t3}}
do_test attach3-5.3 {
  execsql {
    INSERT INTO aux.t3 VALUES('hello', 'world');
    SELECT * FROM v1;
  }
} {1 2 hello world}

# Drop the view 
do_test attach3-6.1 {
  execsql {
    DROP VIEW aux.v1;
  }
} {}
do_test attach3-6.2 {
  execsql {
    SELECT * FROM aux.sqlite_master WHERE name = 'v1';
  }
} {}
} ;# ifcapable view

ifcapable {trigger} {
# Create a trigger in the auxilary database.
do_test attach3-7.1 {
  execsql {
    CREATE TRIGGER aux.tr1 AFTER INSERT ON t3 BEGIN
      INSERT INTO t3 VALUES(new.e*2, new.f*2);
    END;
  }
} {}
do_test attach3-7.2 {
  execsql {
    DELETE FROM t3;
    INSERT INTO t3 VALUES(10, 20);
    SELECT * FROM t3;
  }
} {10 20 20 40}
do_test attach3-5.3 {
  execsql {
    SELECT * FROM aux.sqlite_master WHERE name = 'tr1';
  }
} {trigger tr1 t3 0 {CREATE TRIGGER tr1 AFTER INSERT ON t3 BEGIN
      INSERT INTO t3 VALUES(new.e*2, new.f*2);
    END}}

# Drop the trigger 
do_test attach3-8.1 {
  execsql {
    DROP TRIGGER aux.tr1;
  }
} {}
do_test attach3-8.2 {
  execsql {
    SELECT * FROM aux.sqlite_master WHERE name = 'tr1';
  }
} {}

ifcapable tempdb {
  # Try to trick SQLite into dropping the wrong temp trigger.
  do_test attach3-9.0 {
    execsql {
      CREATE TABLE main.t4(a, b, c);
      CREATE TABLE aux.t4(a, b, c);
      CREATE TEMP TRIGGER tst_trigger BEFORE INSERT ON aux.t4 BEGIN 
        SELECT 'hello world';
      END;
      SELECT count(*) FROM sqlite_temp_master;
    }
  } {1}
  do_test attach3-9.1 {
    execsql {
      DROP TABLE main.t4;
      SELECT count(*) FROM sqlite_temp_master;
    }
  } {1}
  do_test attach3-9.2 {
    execsql {
      DROP TABLE aux.t4;
      SELECT count(*) FROM sqlite_temp_master;
    }
  } {0}
}
} ;# endif trigger

# Make sure the aux.sqlite_master table is read-only
do_test attach3-10.0 {
  catchsql {
    INSERT INTO aux.sqlite_master VALUES(1, 2, 3, 4, 5);
  }
} {1 {table sqlite_master may not be modified}}

# Failure to attach leaves us in a workable state.
# Ticket #811
#
do_test attach3-11.0 {
  catchsql {
    ATTACH DATABASE '/nodir/nofile.x' AS notadb;
  }
} {1 {unable to open database: /nodir/nofile.x}}
do_test attach3-11.1 {
  catchsql {
    ATTACH DATABASE ':memory:' AS notadb;
  }
} {0 {}}
do_test attach3-11.2 {
  catchsql {
    DETACH DATABASE notadb;
  }
} {0 {}}

# Return a list of attached databases
#
proc db_list {} {
  set x [execsql {
    PRAGMA database_list;
  }]
  set y {}
  foreach {n id file} $x {lappend y $id}
  return $y
}

ifcapable schema_pragmas&&tempdb {

ifcapable !trigger {
  execsql {create temp table dummy(dummy)}
}

# Ticket #1825
#
do_test attach3-12.1 {
  db_list
} {main temp aux}
do_test attach3-12.2 {
  execsql {
    ATTACH DATABASE ? AS ?
  }
  db_list
} {main temp aux {}}
do_test attach3-12.3 {
  execsql {
    DETACH aux
  }
  db_list
} {main temp {}}
do_test attach3-12.4 {
  execsql {
    DETACH ?
  }
  db_list
} {main temp}
do_test attach3-12.5 {
  execsql {
    ATTACH DATABASE '' AS ''
  }
  db_list
} {main temp {}}
do_test attach3-12.6 {
  execsql {
    DETACH ''
  }
  db_list
} {main temp}
do_test attach3-12.7 {
  execsql {
    ATTACH DATABASE '' AS ?
  }
  db_list
} {main temp {}}
do_test attach3-12.8 {
  execsql {
    DETACH ''
  }
  db_list
} {main temp}
do_test attach3-12.9 {
  execsql {
    ATTACH DATABASE '' AS NULL
  }
  db_list
} {main temp {}}
do_test attach3-12.10 {
breakpoint
  execsql {
    DETACH ?
  }
  db_list
} {main temp}
do_test attach3-12.11 {
  catchsql {
    DETACH NULL
  }
} {1 {no such database: }}
do_test attach3-12.12 {
  catchsql {
    ATTACH null AS null;
    ATTACH '' AS '';
  }
} {1 {database  is already in use}}
do_test attach3-12.13 {
  db_list
} {main temp {}}
do_test attach3-12.14 {
  execsql {
    DETACH '';
  }
  db_list
} {main temp}

} ;# ifcapable pragma

finish_test

Added test/attachmalloc.test.































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the ATTACH statement and
# specifically out-of-memory conditions within that command.
#
# $Id: attachmalloc.test,v 1.10 2008/10/22 10:45:38 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !memdebug||!attach {
  finish_test
  return
}

source $testdir/malloc_common.tcl

do_malloc_test attachmalloc-1 -tclprep {
  db close
  for {set i 2} {$i<=4} {incr i} {
    file delete -force test$i.db
    file delete -force test$i.db-journal
  }
} -tclbody {
  if {[catch {sqlite3 db test.db}]} {
    error "out of memory"
  }
  sqlite3_db_config_lookaside db 0 0 0
  sqlite3_extended_result_codes db 1
} -sqlbody {
  ATTACH 'test2.db' AS two;
  CREATE TABLE two.t1(x);
  ATTACH 'test3.db' AS three;
  CREATE TABLE three.t1(x);
  ATTACH 'test4.db' AS four;
  CREATE TABLE four.t1(x);
}

do_malloc_test attachmalloc-2 -tclprep {
  file delete -force test2.db
  file delete -force test2.db-journal
  sqlite3 db2 test2.db
  db2 eval {
    CREATE TABLE t1(a, b, c);
    CREATE INDEX i1 ON t1(a, b);
  }
  db2 close
} -sqlbody {
  CREATE TABLE t1(d, e, f);
  ATTACH 'test2.db' AS db1;
}

finish_test

Added test/auth.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
# 2003 April 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the sqlite3_set_authorizer() API
# and related functionality.
#
# $Id: auth.test,v 1.46 2009/07/02 18:40:35 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# disable this test if the SQLITE_OMIT_AUTHORIZATION macro is
# defined during compilation.
if {[catch {db auth {}} msg]} {
  finish_test
  return
}

rename proc proc_real
proc_real proc {name arguments script} {
  proc_real $name $arguments $script
  if {$name=="auth"} {
    db authorizer ::auth
  }
}

do_test auth-1.1.1 {
  db close
  set ::DB [sqlite3 db test.db]
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  db authorizer ::auth
  catchsql {CREATE TABLE t1(a,b,c)}
} {1 {not authorized}}
do_test auth-1.1.2 {
  db errorcode
} {23}
do_test auth-1.1.3 {
  db authorizer
} {::auth}
do_test auth-1.1.4 {
  # Ticket #896.
  catchsql {
    SELECT x;
  }
} {1 {no such column: x}}
do_test auth-1.2 {
  execsql {SELECT name FROM sqlite_master}
} {}
do_test auth-1.3.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {CREATE TABLE t1(a,b,c)}
} {1 {not authorized}}
do_test auth-1.3.2 {
  db errorcode
} {23}
do_test auth-1.3.3 {
  set ::authargs
} {t1 {} main {}}
do_test auth-1.4 {
  execsql {SELECT name FROM sqlite_master}
} {}

ifcapable tempdb {
  do_test auth-1.5 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMP TABLE t1(a,b,c)}
  } {1 {not authorized}}
  do_test auth-1.6 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {}
  do_test auth-1.7.1 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMP TABLE t1(a,b,c)}
  } {1 {not authorized}}
  do_test auth-1.7.2 {
     set ::authargs
  } {t1 {} temp {}}
  do_test auth-1.8 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {}
}

do_test auth-1.9 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {CREATE TABLE t1(a,b,c)}
} {0 {}}
do_test auth-1.10 {
  execsql {SELECT name FROM sqlite_master}
} {}
do_test auth-1.11 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {CREATE TABLE t1(a,b,c)}
} {0 {}}
do_test auth-1.12 {
  execsql {SELECT name FROM sqlite_master}
} {}

ifcapable tempdb {
  do_test auth-1.13 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMP TABLE t1(a,b,c)}
  } {0 {}}
  do_test auth-1.14 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {}
  do_test auth-1.15 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMP TABLE t1(a,b,c)}
  } {0 {}}
  do_test auth-1.16 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {}
  
  do_test auth-1.17 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMP TABLE t1(a,b,c)}
  } {0 {}}
  do_test auth-1.18 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

do_test auth-1.19.1 {
  set ::authargs {}
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TEMP_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {CREATE TABLE t2(a,b,c)}
} {0 {}}
do_test auth-1.19.2 {
  set ::authargs
} {}
do_test auth-1.20 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

do_test auth-1.21.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TABLE t2}
} {1 {not authorized}}
do_test auth-1.21.2 {
  set ::authargs
} {t2 {} main {}}
do_test auth-1.22 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.23.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TABLE t2}
} {0 {}}
do_test auth-1.23.2 {
  set ::authargs
} {t2 {} main {}}
do_test auth-1.24 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

ifcapable tempdb {
  do_test auth-1.25 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {DROP TABLE t1}
  } {1 {not authorized}}
  do_test auth-1.26 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.27 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP TABLE t1}
  } {0 {}}
  do_test auth-1.28 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

do_test auth-1.29 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="t2"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {INSERT INTO t2 VALUES(1,2,3)}
} {1 {not authorized}}
do_test auth-1.30 {
  execsql {SELECT * FROM t2}
} {}
do_test auth-1.31 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="t2"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {INSERT INTO t2 VALUES(1,2,3)}
} {0 {}}
do_test auth-1.32 {
  execsql {SELECT * FROM t2}
} {}
do_test auth-1.33 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="t1"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {INSERT INTO t2 VALUES(1,2,3)}
} {0 {}}
do_test auth-1.34 {
  execsql {SELECT * FROM t2}
} {1 2 3}

do_test auth-1.35.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2}
} {1 {access to t2.b is prohibited}}
ifcapable attach {
  do_test auth-1.35.2 {
    execsql {ATTACH DATABASE 'test.db' AS two}
    catchsql {SELECT * FROM two.t2}
  } {1 {access to two.t2.b is prohibited}}
  execsql {DETACH DATABASE two}
}
do_test auth-1.36 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2}
} {0 {1 {} 3}}
do_test auth-1.37 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2 WHERE b=2}
} {0 {}}
do_test auth-1.38 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="a"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2 WHERE b=2}
} {0 {{} 2 3}}
do_test auth-1.39 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2 WHERE b IS NULL}
} {0 {1 {} 3}}
do_test auth-1.40 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {SELECT a,c FROM t2 WHERE b IS NULL}
} {1 {access to t2.b is prohibited}}
  
do_test auth-1.41 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_UPDATE" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {UPDATE t2 SET a=11}
} {0 {}}
do_test auth-1.42 {
  execsql {SELECT * FROM t2}
} {11 2 3}
do_test auth-1.43 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_UPDATE" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {UPDATE t2 SET b=22, c=33}
} {1 {not authorized}}
do_test auth-1.44 {
  execsql {SELECT * FROM t2}
} {11 2 3}
do_test auth-1.45 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_UPDATE" && $arg1=="t2" && $arg2=="b"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {UPDATE t2 SET b=22, c=33}
} {0 {}}
do_test auth-1.46 {
  execsql {SELECT * FROM t2}
} {11 2 33}

do_test auth-1.47 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="t2"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DELETE FROM t2 WHERE a=11}
} {1 {not authorized}}
do_test auth-1.48 {
  execsql {SELECT * FROM t2}
} {11 2 33}
do_test auth-1.49 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="t2"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DELETE FROM t2 WHERE a=11}
} {0 {}}
do_test auth-1.50 {
  execsql {SELECT * FROM t2}
} {}
do_test auth-1.50.2 {
  execsql {INSERT INTO t2 VALUES(11, 2, 33)}
} {}

do_test auth-1.51 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_SELECT"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2}
} {1 {not authorized}}
do_test auth-1.52 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_SELECT"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2}
} {0 {}}
do_test auth-1.53 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_SELECT"} {
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2}
} {0 {11 2 33}}

# Update for version 3: There used to be a handful of test here that
# tested the authorisation callback with the COPY command. The following
# test makes the same database modifications as they used to.
do_test auth-1.54 {
  execsql {INSERT INTO t2 VALUES(7, 8, 9);}
} {}
do_test auth-1.55 {
  execsql {SELECT * FROM t2}
} {11 2 33 7 8 9}

do_test auth-1.63 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
       return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TABLE t2}
} {1 {not authorized}}
do_test auth-1.64 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.65 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="t2"} {
       return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TABLE t2}
} {1 {not authorized}}
do_test auth-1.66 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

ifcapable tempdb {
  do_test auth-1.67 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
         return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {DROP TABLE t1}
  } {1 {not authorized}}
  do_test auth-1.68 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.69 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="t1"} {
         return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {DROP TABLE t1}
  } {1 {not authorized}}
  do_test auth-1.70 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

do_test auth-1.71 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
       return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TABLE t2}
} {0 {}}
do_test auth-1.72 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.73 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="t2"} {
       return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TABLE t2}
} {0 {}}
do_test auth-1.74 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

ifcapable tempdb {
  do_test auth-1.75 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
         return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP TABLE t1}
  } {0 {}}
  do_test auth-1.76 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.77 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="t1"} {
         return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP TABLE t1}
  } {0 {}}
  do_test auth-1.78 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

# Test cases auth-1.79 to auth-1.124 test creating and dropping views.
# Omit these if the library was compiled with views omitted.
ifcapable view {
do_test auth-1.79 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_VIEW"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4] 
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2}
} {1 {not authorized}}
do_test auth-1.80 {
  set ::authargs
} {v1 {} main {}}
do_test auth-1.81 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.82 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_VIEW"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4] 
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2}
} {0 {}}
do_test auth-1.83 {
  set ::authargs
} {v1 {} main {}}
do_test auth-1.84 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

ifcapable tempdb {
  do_test auth-1.85 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_VIEW"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4] 
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2}
  } {1 {not authorized}}
  do_test auth-1.86 {
    set ::authargs
  } {v1 {} temp {}}
  do_test auth-1.87 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.88 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_VIEW"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4] 
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2}
  } {0 {}}
  do_test auth-1.89 {
    set ::authargs
  } {v1 {} temp {}}
  do_test auth-1.90 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

do_test auth-1.91 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2}
} {1 {not authorized}}
do_test auth-1.92 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.93 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2}
} {0 {}}
do_test auth-1.94 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

ifcapable tempdb {
  do_test auth-1.95 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2}
  } {1 {not authorized}}
  do_test auth-1.96 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.97 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2}
  } {0 {}}
  do_test auth-1.98 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

do_test auth-1.99 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE VIEW v2 AS SELECT a+1,b+1 FROM t2;
    DROP VIEW v2
  }
} {1 {not authorized}}
do_test auth-1.100 {
  execsql {SELECT name FROM sqlite_master}
} {t2 v2}
do_test auth-1.101 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_VIEW"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP VIEW v2}
} {1 {not authorized}}
do_test auth-1.102 {
  set ::authargs
} {v2 {} main {}}
do_test auth-1.103 {
  execsql {SELECT name FROM sqlite_master}
} {t2 v2}
do_test auth-1.104 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP VIEW v2}
} {0 {}}
do_test auth-1.105 {
  execsql {SELECT name FROM sqlite_master}
} {t2 v2}
do_test auth-1.106 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_VIEW"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP VIEW v2}
} {0 {}}
do_test auth-1.107 {
  set ::authargs
} {v2 {} main {}}
do_test auth-1.108 {
  execsql {SELECT name FROM sqlite_master}
} {t2 v2}
do_test auth-1.109 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_VIEW"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {DROP VIEW v2}
} {0 {}}
do_test auth-1.110 {
  set ::authargs
} {v2 {} main {}}
do_test auth-1.111 {
  execsql {SELECT name FROM sqlite_master}
} {t2}


ifcapable tempdb {
  do_test auth-1.112 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {
      CREATE TEMP VIEW v1 AS SELECT a+1,b+1 FROM t1;
      DROP VIEW v1
    }
  } {1 {not authorized}}
  do_test auth-1.113 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 v1}
  do_test auth-1.114 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_VIEW"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {DROP VIEW v1}
  } {1 {not authorized}}
  do_test auth-1.115 {
    set ::authargs
  } {v1 {} temp {}}
  do_test auth-1.116 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 v1}
  do_test auth-1.117 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP VIEW v1}
  } {0 {}}
  do_test auth-1.118 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 v1}
  do_test auth-1.119 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_VIEW"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP VIEW v1}
  } {0 {}}
  do_test auth-1.120 {
    set ::authargs
  } {v1 {} temp {}}
  do_test auth-1.121 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 v1}
  do_test auth-1.122 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_VIEW"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_OK
      }
      return SQLITE_OK
    }
    catchsql {DROP VIEW v1}
  } {0 {}}
  do_test auth-1.123 {
    set ::authargs
  } {v1 {} temp {}}
  do_test auth-1.124 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}
} ;# ifcapable view

# Test cases auth-1.125 to auth-1.176 test creating and dropping triggers.
# Omit these if the library was compiled with triggers omitted.
#
ifcapable trigger&&tempdb {
do_test auth-1.125 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r2 DELETE on t2 BEGIN
        SELECT NULL;
    END;
  }
} {1 {not authorized}}
do_test auth-1.126 {
  set ::authargs
} {r2 t2 main {}}
do_test auth-1.127 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.128 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r2 DELETE on t2 BEGIN
        SELECT NULL;
    END;
  }
} {1 {not authorized}}
do_test auth-1.129 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.130 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r2 DELETE on t2 BEGIN
        SELECT NULL;
    END;
  }
} {0 {}}
do_test auth-1.131 {
  set ::authargs
} {r2 t2 main {}}
do_test auth-1.132 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.133 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r2 DELETE on t2 BEGIN
        SELECT NULL;
    END;
  }
} {0 {}}
do_test auth-1.134 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.135 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TABLE tx(id);
    CREATE TRIGGER r2 AFTER INSERT ON t2 BEGIN
       INSERT INTO tx VALUES(NEW.rowid);
    END;
  }
} {0 {}}
do_test auth-1.136.1 {
  set ::authargs
} {r2 t2 main {}}
do_test auth-1.136.2 {
  execsql {
    SELECT name FROM sqlite_master WHERE type='trigger'
  }
} {r2}
do_test auth-1.136.3 {
  proc auth {code arg1 arg2 arg3 arg4} {
    lappend ::authargs $code $arg1 $arg2 $arg3 $arg4
    return SQLITE_OK
  }
  set ::authargs {}
  execsql {
    INSERT INTO t2 VALUES(1,2,3);
  }
  set ::authargs 
} {SQLITE_INSERT t2 {} main {} SQLITE_INSERT tx {} main r2 SQLITE_READ t2 ROWID main r2}
do_test auth-1.136.4 {
  execsql {
    SELECT * FROM tx;
  }
} {3}
do_test auth-1.137 {
  execsql {SELECT name FROM sqlite_master}
} {t2 tx r2}
do_test auth-1.138 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TEMP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r1 DELETE on t1 BEGIN
        SELECT NULL;
    END;
  }
} {1 {not authorized}}
do_test auth-1.139 {
  set ::authargs
} {r1 t1 temp {}}
do_test auth-1.140 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1}
do_test auth-1.141 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r1 DELETE on t1 BEGIN
        SELECT NULL;
    END;
  }
} {1 {not authorized}}
do_test auth-1.142 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1}
do_test auth-1.143 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TEMP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r1 DELETE on t1 BEGIN
        SELECT NULL;
    END;
  }
} {0 {}}
do_test auth-1.144 {
  set ::authargs
} {r1 t1 temp {}}
do_test auth-1.145 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1}
do_test auth-1.146 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r1 DELETE on t1 BEGIN
        SELECT NULL;
    END;
  }
} {0 {}}
do_test auth-1.147 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1}
do_test auth-1.148 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_TEMP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {
    CREATE TRIGGER r1 DELETE on t1 BEGIN
        SELECT NULL;
    END;
  }
} {0 {}}
do_test auth-1.149 {
  set ::authargs
} {r1 t1 temp {}}
do_test auth-1.150 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1 r1}

do_test auth-1.151 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r2}
} {1 {not authorized}}
do_test auth-1.152 {
  execsql {SELECT name FROM sqlite_master}
} {t2 tx r2}
do_test auth-1.153 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r2}
} {1 {not authorized}}
do_test auth-1.154 {
  set ::authargs
} {r2 t2 main {}}
do_test auth-1.155 {
  execsql {SELECT name FROM sqlite_master}
} {t2 tx r2}
do_test auth-1.156 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r2}
} {0 {}}
do_test auth-1.157 {
  execsql {SELECT name FROM sqlite_master}
} {t2 tx r2}
do_test auth-1.158 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r2}
} {0 {}}
do_test auth-1.159 {
  set ::authargs
} {r2 t2 main {}}
do_test auth-1.160 {
  execsql {SELECT name FROM sqlite_master}
} {t2 tx r2}
do_test auth-1.161 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r2}
} {0 {}}
do_test auth-1.162 {
  set ::authargs
} {r2 t2 main {}}
do_test auth-1.163 {
  execsql {
    DROP TABLE tx;
    DELETE FROM t2 WHERE a=1 AND b=2 AND c=3;
    SELECT name FROM sqlite_master;
  }
} {t2}

do_test auth-1.164 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r1}
} {1 {not authorized}}
do_test auth-1.165 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1 r1}
do_test auth-1.166 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TEMP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r1}
} {1 {not authorized}}
do_test auth-1.167 {
  set ::authargs
} {r1 t1 temp {}}
do_test auth-1.168 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1 r1}
do_test auth-1.169 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r1}
} {0 {}}
do_test auth-1.170 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1 r1}
do_test auth-1.171 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TEMP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r1}
} {0 {}}
do_test auth-1.172 {
  set ::authargs
} {r1 t1 temp {}}
do_test auth-1.173 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1 r1}
do_test auth-1.174 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_TEMP_TRIGGER"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {DROP TRIGGER r1}
} {0 {}}
do_test auth-1.175 {
  set ::authargs
} {r1 t1 temp {}}
do_test auth-1.176 {
  execsql {SELECT name FROM sqlite_temp_master}
} {t1}
} ;# ifcapable trigger

do_test auth-1.177 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_INDEX"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {CREATE INDEX i2 ON t2(a)}
} {1 {not authorized}}
do_test auth-1.178 {
  set ::authargs
} {i2 t2 main {}}
do_test auth-1.179 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.180 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {CREATE INDEX i2 ON t2(a)}
} {1 {not authorized}}
do_test auth-1.181 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.182 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_INDEX"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {CREATE INDEX i2 ON t2(b)}
} {0 {}}
do_test auth-1.183 {
  set ::authargs
} {i2 t2 main {}}
do_test auth-1.184 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.185 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {CREATE INDEX i2 ON t2(b)}
} {0 {}}
do_test auth-1.186 {
  execsql {SELECT name FROM sqlite_master}
} {t2}
do_test auth-1.187 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_CREATE_INDEX"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {CREATE INDEX i2 ON t2(a)}
} {0 {}}
do_test auth-1.188 {
  set ::authargs
} {i2 t2 main {}}
do_test auth-1.189 {
  execsql {SELECT name FROM sqlite_master}
} {t2 i2}

ifcapable tempdb {
  do_test auth-1.190 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_INDEX"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE INDEX i1 ON t1(a)}
  } {1 {not authorized}}
  do_test auth-1.191 {
    set ::authargs
  } {i1 t1 temp {}}
  do_test auth-1.192 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.193 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {CREATE INDEX i1 ON t1(b)}
  } {1 {not authorized}}
  do_test auth-1.194 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.195 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_INDEX"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {CREATE INDEX i1 ON t1(b)}
  } {0 {}}
  do_test auth-1.196 {
    set ::authargs
  } {i1 t1 temp {}}
  do_test auth-1.197 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.198 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} {
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {CREATE INDEX i1 ON t1(c)}
  } {0 {}}
  do_test auth-1.199 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
  do_test auth-1.200 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_CREATE_TEMP_INDEX"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_OK
      }
      return SQLITE_OK
    }
    catchsql {CREATE INDEX i1 ON t1(a)}
  } {0 {}}
  do_test auth-1.201 {
    set ::authargs
  } {i1 t1 temp {}}
  do_test auth-1.202 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 i1}
}

do_test auth-1.203 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP INDEX i2}
} {1 {not authorized}}
do_test auth-1.204 {
  execsql {SELECT name FROM sqlite_master}
} {t2 i2}
do_test auth-1.205 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_INDEX"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {DROP INDEX i2}
} {1 {not authorized}}
do_test auth-1.206 {
  set ::authargs
} {i2 t2 main {}}
do_test auth-1.207 {
  execsql {SELECT name FROM sqlite_master}
} {t2 i2}
do_test auth-1.208 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP INDEX i2}
} {0 {}}
do_test auth-1.209 {
  execsql {SELECT name FROM sqlite_master}
} {t2 i2}
do_test auth-1.210 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_INDEX"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {DROP INDEX i2}
} {0 {}}
do_test auth-1.211 {
  set ::authargs
} {i2 t2 main {}}
do_test auth-1.212 {
  execsql {SELECT name FROM sqlite_master}
} {t2 i2}
do_test auth-1.213 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_DROP_INDEX"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {DROP INDEX i2}
} {0 {}}
do_test auth-1.214 {
  set ::authargs
} {i2 t2 main {}}
do_test auth-1.215 {
  execsql {SELECT name FROM sqlite_master}
} {t2}

ifcapable tempdb {
  do_test auth-1.216 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {DROP INDEX i1}
  } {1 {not authorized}}
  do_test auth-1.217 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 i1}
  do_test auth-1.218 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_INDEX"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {DROP INDEX i1}
  } {1 {not authorized}}
  do_test auth-1.219 {
    set ::authargs
  } {i1 t1 temp {}}
  do_test auth-1.220 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 i1}
  do_test auth-1.221 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} {
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP INDEX i1}
  } {0 {}}
  do_test auth-1.222 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 i1}
  do_test auth-1.223 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_INDEX"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {DROP INDEX i1}
  } {0 {}}
  do_test auth-1.224 {
    set ::authargs
  } {i1 t1 temp {}}
  do_test auth-1.225 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1 i1}
  do_test auth-1.226 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DROP_TEMP_INDEX"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_OK
      }
      return SQLITE_OK
    }
    catchsql {DROP INDEX i1}
  } {0 {}}
  do_test auth-1.227 {
    set ::authargs
  } {i1 t1 temp {}}
  do_test auth-1.228 {
    execsql {SELECT name FROM sqlite_temp_master}
  } {t1}
}

do_test auth-1.229 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_PRAGMA"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {PRAGMA full_column_names=on}
} {1 {not authorized}}
do_test auth-1.230 {
  set ::authargs
} {full_column_names on {} {}}
do_test auth-1.231 {
  execsql2 {SELECT a FROM t2}
} {a 11 a 7}
do_test auth-1.232 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_PRAGMA"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {PRAGMA full_column_names=on}
} {0 {}}
do_test auth-1.233 {
  set ::authargs
} {full_column_names on {} {}}
do_test auth-1.234 {
  execsql2 {SELECT a FROM t2}
} {a 11 a 7}
do_test auth-1.235 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_PRAGMA"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {PRAGMA full_column_names=on}
} {0 {}}
do_test auth-1.236 {
  execsql2 {SELECT a FROM t2}
} {t2.a 11 t2.a 7}
do_test auth-1.237 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_PRAGMA"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {PRAGMA full_column_names=OFF}
} {0 {}}
do_test auth-1.238 {
  set ::authargs
} {full_column_names OFF {} {}}
do_test auth-1.239 {
  execsql2 {SELECT a FROM t2}
} {a 11 a 7}

do_test auth-1.240 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_TRANSACTION"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {BEGIN}
} {1 {not authorized}}
do_test auth-1.241 {
  set ::authargs
} {BEGIN {} {} {}}
do_test auth-1.242 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_TRANSACTION" && $arg1!="BEGIN"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {BEGIN; INSERT INTO t2 VALUES(44,55,66); COMMIT}
} {1 {not authorized}}
do_test auth-1.243 {
  set ::authargs
} {COMMIT {} {} {}}
do_test auth-1.244 {
  execsql {SELECT * FROM t2}
} {11 2 33 7 8 9 44 55 66}
do_test auth-1.245 {
  catchsql {ROLLBACK}
} {1 {not authorized}}
do_test auth-1.246 {
  set ::authargs
} {ROLLBACK {} {} {}}
do_test auth-1.247 {
  catchsql {END TRANSACTION}
} {1 {not authorized}}
do_test auth-1.248 {
  set ::authargs
} {COMMIT {} {} {}}
do_test auth-1.249 {
  db authorizer {}
  catchsql {ROLLBACK}
} {0 {}}
do_test auth-1.250 {
  execsql {SELECT * FROM t2}
} {11 2 33 7 8 9}

# ticket #340 - authorization for ATTACH and DETACH.
#
ifcapable attach {
  do_test auth-1.251 {
    db authorizer ::auth
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_ATTACH"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      }
      return SQLITE_OK
    }
    catchsql {
      ATTACH DATABASE ':memory:' AS test1
    }
  } {0 {}}
  do_test auth-1.252 {
    set ::authargs
  } {:memory: {} {} {}}
  do_test auth-1.253 {
    catchsql {DETACH DATABASE test1}
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_ATTACH"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {
      ATTACH DATABASE ':memory:' AS test1;
    }
  } {1 {not authorized}}
  do_test auth-1.254 {
    lindex [execsql {PRAGMA database_list}] 7
  } {}
  do_test auth-1.255 {
    catchsql {DETACH DATABASE test1}
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_ATTACH"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {
      ATTACH DATABASE ':memory:' AS test1;
    }
  } {0 {}}
  do_test auth-1.256 {
    lindex [execsql {PRAGMA database_list}] 7
  } {}
  do_test auth-1.257 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DETACH"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_OK
      }
      return SQLITE_OK
    }
    execsql {ATTACH DATABASE ':memory:' AS test1}
    catchsql {
      DETACH DATABASE test1;
    }
  } {0 {}}
  do_test auth-1.258 {
    lindex [execsql {PRAGMA database_list}] 7
  } {}
  do_test auth-1.259 {
    execsql {ATTACH DATABASE ':memory:' AS test1}
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_DETACH"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {
      DETACH DATABASE test1;
    }
  } {0 {}}
  ifcapable tempdb {
    ifcapable schema_pragmas {
    do_test auth-1.260 {
      lindex [execsql {PRAGMA database_list}] 7
    } {test1}
    } ;# ifcapable schema_pragmas
    do_test auth-1.261 {
      proc auth {code arg1 arg2 arg3 arg4} {
        if {$code=="SQLITE_DETACH"} {
          set ::authargs [list $arg1 $arg2 $arg3 $arg4]
          return SQLITE_DENY
        }
        return SQLITE_OK
      }
      catchsql {
        DETACH DATABASE test1;
      }
    } {1 {not authorized}}
    ifcapable schema_pragmas {
    do_test auth-1.262 {
      lindex [execsql {PRAGMA database_list}] 7
    } {test1}
    } ;# ifcapable schema_pragmas
    db authorizer {}
    execsql {DETACH DATABASE test1}
    db authorizer ::auth
    
    # Authorization for ALTER TABLE. These tests are omitted if the library
    # was built without ALTER TABLE support.
    ifcapable altertable {
    
      do_test auth-1.263 {
        proc auth {code arg1 arg2 arg3 arg4} {
          if {$code=="SQLITE_ALTER_TABLE"} {
            set ::authargs [list $arg1 $arg2 $arg3 $arg4]
            return SQLITE_OK
          }
          return SQLITE_OK
        }
        catchsql {
          ALTER TABLE t1 RENAME TO t1x
        }
      } {0 {}}
      do_test auth-1.264 {
        execsql {SELECT name FROM sqlite_temp_master WHERE type='table'}
      } {t1x}
      do_test auth-1.265 {
        set authargs
      } {temp t1 {} {}}
      do_test auth-1.266 {
        proc auth {code arg1 arg2 arg3 arg4} {
          if {$code=="SQLITE_ALTER_TABLE"} {
            set ::authargs [list $arg1 $arg2 $arg3 $arg4]
            return SQLITE_IGNORE
          }
          return SQLITE_OK
        }
        catchsql {
          ALTER TABLE t1x RENAME TO t1
        }
      } {0 {}}
      do_test auth-1.267 {
        execsql {SELECT name FROM sqlite_temp_master WHERE type='table'}
      } {t1x}
      do_test auth-1.268 {
        set authargs
      } {temp t1x {} {}}
      do_test auth-1.269 {
        proc auth {code arg1 arg2 arg3 arg4} {
          if {$code=="SQLITE_ALTER_TABLE"} {
            set ::authargs [list $arg1 $arg2 $arg3 $arg4]
            return SQLITE_DENY
          }
          return SQLITE_OK
        }
        catchsql {
          ALTER TABLE t1x RENAME TO t1
        }
      } {1 {not authorized}}
      do_test auth-1.270 {
        execsql {SELECT name FROM sqlite_temp_master WHERE type='table'}
      } {t1x}
  
      do_test auth-1.271 {
        set authargs
      } {temp t1x {} {}}
    } ;# ifcapable altertable
  
  } else {
    db authorizer {}
    db eval {
      DETACH DATABASE test1;
    }
  }
}

ifcapable  altertable {
db authorizer {}
catchsql {ALTER TABLE t1x RENAME TO t1}
db authorizer ::auth
do_test auth-1.272 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_ALTER_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_OK
    }
    return SQLITE_OK
  }
  catchsql {
    ALTER TABLE t2 RENAME TO t2x
  }
} {0 {}}
do_test auth-1.273 {
  execsql {SELECT name FROM sqlite_master WHERE type='table'}
} {t2x}
do_test auth-1.274 {
  set authargs
} {main t2 {} {}}
do_test auth-1.275 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_ALTER_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {
    ALTER TABLE t2x RENAME TO t2
  }
} {0 {}}
do_test auth-1.276 {
  execsql {SELECT name FROM sqlite_master WHERE type='table'}
} {t2x}
do_test auth-1.277 {
  set authargs
} {main t2x {} {}}
do_test auth-1.278 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_ALTER_TABLE"} {
      set ::authargs [list $arg1 $arg2 $arg3 $arg4]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  catchsql {
    ALTER TABLE t2x RENAME TO t2
  }
} {1 {not authorized}}
do_test auth-1.279 {
  execsql {SELECT name FROM sqlite_master WHERE type='table'}
} {t2x}
do_test auth-1.280 {
  set authargs
} {main t2x {} {}}
db authorizer {}
catchsql {ALTER TABLE t2x RENAME TO t2}

} ;# ifcapable altertable

# Test the authorization callbacks for the REINDEX command.
ifcapable reindex {

proc auth {code args} {
  if {$code=="SQLITE_REINDEX"} {
    set ::authargs [concat $::authargs $args]
  }
  return SQLITE_OK
}
db authorizer auth
do_test auth-1.281 {
  execsql {
    CREATE TABLE t3(a PRIMARY KEY, b, c);
    CREATE INDEX t3_idx1 ON t3(c COLLATE BINARY);
    CREATE INDEX t3_idx2 ON t3(b COLLATE NOCASE);
  }
} {}
do_test auth-1.282 {
  set ::authargs {}
  execsql {
    REINDEX t3_idx1;
  }
  set ::authargs
} {t3_idx1 {} main {}}
do_test auth-1.283 {
  set ::authargs {}
  execsql {
    REINDEX BINARY;
  }
  set ::authargs
} {t3_idx1 {} main {} sqlite_autoindex_t3_1 {} main {}}
do_test auth-1.284 {
  set ::authargs {}
  execsql {
    REINDEX NOCASE;
  }
  set ::authargs
} {t3_idx2 {} main {}}
do_test auth-1.285 {
  set ::authargs {}
  execsql {
    REINDEX t3;
  }
  set ::authargs
} {t3_idx2 {} main {} t3_idx1 {} main {} sqlite_autoindex_t3_1 {} main {}}
do_test auth-1.286 {
  execsql {
    DROP TABLE t3;
  }
} {}
ifcapable tempdb {
  do_test auth-1.287 {
    execsql {
      CREATE TEMP TABLE t3(a PRIMARY KEY, b, c);
      CREATE INDEX t3_idx1 ON t3(c COLLATE BINARY);
      CREATE INDEX t3_idx2 ON t3(b COLLATE NOCASE);
    }
  } {}
  do_test auth-1.288 {
    set ::authargs {}
    execsql {
      REINDEX temp.t3_idx1;
    }
    set ::authargs
  } {t3_idx1 {} temp {}}
  do_test auth-1.289 {
    set ::authargs {}
    execsql {
      REINDEX BINARY;
    }
    set ::authargs
  } {t3_idx1 {} temp {} sqlite_autoindex_t3_1 {} temp {}}
  do_test auth-1.290 {
    set ::authargs {}
    execsql {
      REINDEX NOCASE;
    }
    set ::authargs
  } {t3_idx2 {} temp {}}
  do_test auth-1.291 {
    set ::authargs {}
    execsql {
      REINDEX temp.t3;
    }
    set ::authargs
  } {t3_idx2 {} temp {} t3_idx1 {} temp {} sqlite_autoindex_t3_1 {} temp {}}
  proc auth {code args} {
    if {$code=="SQLITE_REINDEX"} {
      set ::authargs [concat $::authargs $args]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  do_test auth-1.292 {
    set ::authargs {}
    catchsql {
      REINDEX temp.t3;
    }
  } {1 {not authorized}}
  do_test auth-1.293 {
    execsql {
      DROP TABLE t3;
    }
  } {}
}

} ;# ifcapable reindex 

ifcapable analyze {
  proc auth {code args} {
    if {$code=="SQLITE_ANALYZE"} {
      set ::authargs [concat $::authargs $args]
    }
    return SQLITE_OK
  }
  do_test auth-1.294 {
    set ::authargs {}
    execsql {
      CREATE TABLE t4(a,b,c);
      CREATE INDEX t4i1 ON t4(a);
      CREATE INDEX t4i2 ON t4(b,a,c);
      INSERT INTO t4 VALUES(1,2,3);
      ANALYZE;
    }
    set ::authargs
  } {t4 {} main {}}
  do_test auth-1.295 {
    execsql {
      SELECT count(*) FROM sqlite_stat1;
    }
  } 2
  proc auth {code args} {
    if {$code=="SQLITE_ANALYZE"} {
      set ::authargs [concat $::authargs $args]
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  do_test auth-1.296 {
    set ::authargs {}
    catchsql {
      ANALYZE;
    }
  } {1 {not authorized}}
  do_test auth-1.297 {
    execsql {
      SELECT count(*) FROM sqlite_stat1;
    }
  } 2
} ;# ifcapable analyze


# Authorization for ALTER TABLE ADD COLUMN.
# These tests are omitted if the library
# was built without ALTER TABLE support.
ifcapable {altertable} {
  do_test auth-1.300 {
    execsql {CREATE TABLE t5(x)}
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_ALTER_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_OK
      }
      return SQLITE_OK
    }
    catchsql {
      ALTER TABLE t5 ADD COLUMN new_col_1;
    }
  } {0 {}}
  do_test auth-1.301 {
    set x [execsql {SELECT sql FROM sqlite_master WHERE name='t5'}]
    regexp new_col_1 $x
  } {1}
  do_test auth-1.302 {
    set authargs
  } {main t5 {} {}}
  do_test auth-1.303 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_ALTER_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    catchsql {
      ALTER TABLE t5 ADD COLUMN new_col_2;
    }
  } {0 {}}
  do_test auth-1.304 {
    set x [execsql {SELECT sql FROM sqlite_master WHERE name='t5'}]
    regexp new_col_2 $x
  } {0}
  do_test auth-1.305 {
    set authargs
  } {main t5 {} {}}
  do_test auth-1.306 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_ALTER_TABLE"} {
        set ::authargs [list $arg1 $arg2 $arg3 $arg4]
        return SQLITE_DENY
      }
      return SQLITE_OK
    }
    catchsql {
      ALTER TABLE t5 ADD COLUMN new_col_3
    }
  } {1 {not authorized}}
  do_test auth-1.307 {
    set x [execsql {SELECT sql FROM sqlite_temp_master WHERE type='t5'}]
    regexp new_col_3 $x
  } {0}

  do_test auth-1.308 {
    set authargs
  } {main t5 {} {}}
  execsql {DROP TABLE t5}
} ;# ifcapable altertable

do_test auth-2.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t3" && $arg2=="x"} {
      return SQLITE_DENY
    }
    return SQLITE_OK
  }
  db authorizer ::auth
  execsql {CREATE TABLE t3(x INTEGER PRIMARY KEY, y, z)}
  catchsql {SELECT * FROM t3}
} {1 {access to t3.x is prohibited}}
do_test auth-2.1 {
  catchsql {SELECT y,z FROM t3}
} {0 {}}
do_test auth-2.2 {
  catchsql {SELECT ROWID,y,z FROM t3}
} {1 {access to t3.x is prohibited}}
do_test auth-2.3 {
  catchsql {SELECT OID,y,z FROM t3}
} {1 {access to t3.x is prohibited}}
do_test auth-2.4 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t3" && $arg2=="x"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  execsql {INSERT INTO t3 VALUES(44,55,66)}
  catchsql {SELECT * FROM t3}
} {0 {{} 55 66}}
do_test auth-2.5 {
  catchsql {SELECT rowid,y,z FROM t3}
} {0 {{} 55 66}}
do_test auth-2.6 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t3" && $arg2=="ROWID"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t3}
} {0 {44 55 66}}
do_test auth-2.7 {
  catchsql {SELECT ROWID,y,z FROM t3}
} {0 {44 55 66}}
do_test auth-2.8 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="ROWID"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT ROWID,b,c FROM t2}
} {0 {{} 2 33 {} 8 9}}
do_test auth-2.9.1 {
  # We have to flush the cache here in case the Tcl interface tries to
  # reuse a statement compiled with sqlite3_prepare_v2(). In this case,
  # the first error encountered is an SQLITE_SCHEMA error. Then, when
  # trying to recompile the statement, the authorization error is encountered.
  # If we do not flush the cache, the correct error message is returned, but
  # the error code is SQLITE_SCHEMA, not SQLITE_ERROR as required by the test
  # case after this one.
  #
  db cache flush

  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="ROWID"} {
      return bogus
    }
    return SQLITE_OK
  }
  catchsql {SELECT ROWID,b,c FROM t2}
} {1 {authorizer malfunction}}
do_test auth-2.9.2 {
  db errorcode
} {1}
do_test auth-2.10 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_SELECT"} {
      return bogus
    }
    return SQLITE_OK
  }
  catchsql {SELECT ROWID,b,c FROM t2}
} {1 {authorizer malfunction}}
do_test auth-2.11.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg2=="a"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2, t3}
} {0 {{} 2 33 44 55 66 {} 8 9 44 55 66}}
do_test auth-2.11.2 {
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_READ" && $arg2=="x"} {
      return SQLITE_IGNORE
    }
    return SQLITE_OK
  }
  catchsql {SELECT * FROM t2, t3}
} {0 {11 2 33 {} 55 66 7 8 9 {} 55 66}}

# Make sure the OLD and NEW pseudo-tables of a trigger get authorized.
#
ifcapable trigger {
  do_test auth-3.1 {
    proc auth {code arg1 arg2 arg3 arg4} {
      return SQLITE_OK
    }
    execsql {
      CREATE TABLE tx(a1,a2,b1,b2,c1,c2);
      CREATE TRIGGER r1 AFTER UPDATE ON t2 FOR EACH ROW BEGIN
        INSERT INTO tx VALUES(OLD.a,NEW.a,OLD.b,NEW.b,OLD.c,NEW.c);
      END;
      UPDATE t2 SET a=a+1;
      SELECT * FROM tx;
    }
  } {11 12 2 2 33 33 7 8 8 8 9 9}
  do_test auth-3.2 {
    proc auth {code arg1 arg2 arg3 arg4} {
      if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="c"} {
        return SQLITE_IGNORE
      }
      return SQLITE_OK
    }
    execsql {
      DELETE FROM tx;
      UPDATE t2 SET a=a+100;
      SELECT * FROM tx;
    }
  } {12 112 2 2 {} {} 8 108 8 8 {} {}}
} ;# ifcapable trigger

# Make sure the names of views and triggers are passed on on arg4.
#
ifcapable trigger {
do_test auth-4.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    lappend ::authargs $code $arg1 $arg2 $arg3 $arg4
    return SQLITE_OK
  }
  set authargs {}
  execsql {
    UPDATE t2 SET a=a+1;
  }
  set authargs
} [list \
  SQLITE_READ   t2 a  main {} \
  SQLITE_UPDATE t2 a  main {} \
  SQLITE_INSERT tx {} main r1 \
  SQLITE_READ   t2 a  main r1 \
  SQLITE_READ   t2 a  main r1 \
  SQLITE_READ   t2 b  main r1 \
  SQLITE_READ   t2 b  main r1 \
  SQLITE_READ   t2 c  main r1 \
  SQLITE_READ   t2 c  main r1]
}

ifcapable {view && trigger} {
do_test auth-4.2 {
  execsql {
    CREATE VIEW v1 AS SELECT a+b AS x FROM t2;
    CREATE TABLE v1chng(x1,x2);
    CREATE TRIGGER r2 INSTEAD OF UPDATE ON v1 BEGIN
      INSERT INTO v1chng VALUES(OLD.x,NEW.x);
    END;
    SELECT * FROM v1;
  }
} {115 117}
do_test auth-4.3 {
  set authargs {}
  execsql {
    UPDATE v1 SET x=1 WHERE x=117
  }
  set authargs
} [list \
  SQLITE_UPDATE v1     x  main {} \
  SQLITE_SELECT {}     {} {}   v1 \
  SQLITE_READ   t2     a  main v1 \
  SQLITE_READ   t2     b  main v1 \
  SQLITE_SELECT {}     {} {}   {} \
  SQLITE_READ   v1     x  main v1 \
  SQLITE_INSERT v1chng {} main r2 \
  SQLITE_READ   v1     x  main r2 \
  SQLITE_READ   v1     x  main r2 \
]

do_test auth-4.4 {
  execsql {
    CREATE TRIGGER r3 INSTEAD OF DELETE ON v1 BEGIN
      INSERT INTO v1chng VALUES(OLD.x,NULL);
    END;
    SELECT * FROM v1;
  }
} {115 117}
do_test auth-4.5 {
  set authargs {}
  execsql {
    DELETE FROM v1 WHERE x=117
  }
  set authargs
} [list \
  SQLITE_DELETE v1     {} main {} \
  SQLITE_SELECT {}     {} {}   v1 \
  SQLITE_READ   t2     a  main v1 \
  SQLITE_READ   t2     b  main v1 \
  SQLITE_SELECT {}     {} {}   {} \
  SQLITE_READ   v1     x  main v1 \
  SQLITE_INSERT v1chng {} main r3 \
  SQLITE_READ   v1     x  main r3 \
]

} ;# ifcapable view && trigger

# Ticket #1338:  Make sure authentication works in the presence of an AS
# clause.
#
do_test auth-5.1 {
  proc auth {code arg1 arg2 arg3 arg4} {
    return SQLITE_OK
  }
  execsql {
    SELECT count(a) AS cnt FROM t4 ORDER BY cnt
  }
} {1}

# Ticket #1607
#
ifcapable compound&&subquery {
  ifcapable trigger {
    execsql {
      DROP TABLE tx;
    }
    ifcapable view {
      execsql {
        DROP TABLE v1chng;
      }
    }
  }
  ifcapable stat2 {
    set stat2 "sqlite_stat2 "
  } else {
    set stat2 ""
  }
  do_test auth-5.2 {
    execsql {
      SELECT name FROM (
        SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master)
      WHERE type='table'
      ORDER BY name
    }
  } "sqlite_stat1 ${stat2}t1 t2 t3 t4"
}

# Ticket #3944
#
ifcapable trigger {
  do_test auth-5.3.1 {
    execsql {
      CREATE TABLE t5 ( x );
      CREATE TRIGGER t5_tr1 AFTER INSERT ON t5 BEGIN 
        UPDATE t5 SET x = 1 WHERE NEW.x = 0;
      END;
    }
  } {}
  set ::authargs [list]
  proc auth {args} {
    eval lappend ::authargs $args
    return SQLITE_OK
  }
  do_test auth-5.3.2 {
    execsql { INSERT INTO t5 (x) values(0) }
    set ::authargs
  } [list SQLITE_INSERT t5 {} main {}    \
          SQLITE_UPDATE t5 x main t5_tr1 \
          SQLITE_READ t5 x main t5_tr1   \
    ]
  do_test auth-5.3.2 {
    execsql { SELECT * FROM t5 }
  } {1}
}


rename proc {}
rename proc_real proc


finish_test

Added test/auth2.test.

















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# 2006 Aug 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the sqlite3_set_authorizer() API
# and related functionality.
#
# $Id: auth2.test,v 1.3 2008/07/02 13:13:53 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# disable this test if the SQLITE_OMIT_AUTHORIZATION macro is
# defined during compilation.
if {[catch {db auth {}} msg]} {
  finish_test
  return
}

do_test auth2-1.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1,2,3);
  }
  set ::flist {}
  proc auth {code arg1 arg2 arg3 arg4} {
    if {$code=="SQLITE_FUNCTION"} {
      lappend ::flist $arg2
      if {$arg2=="max"} {
        return SQLITE_DENY
      } elseif {$arg2=="min"} {
        return SQLITE_IGNORE
      } else {
        return SQLITE_OK
      }
    }
    return SQLITE_OK
  }
  db authorizer ::auth
  catchsql {SELECT max(a,b,c) FROM t1}
} {1 {not authorized to use function: max}}
do_test auth2-1.2 {
  set ::flist
} max
do_test auth2-1.3 {
  set ::flist {}
  catchsql {SELECT min(a,b,c) FROM t1}
} {0 {{}}}
do_test auth2-1.4 {
  set ::flist
} min
do_test auth2-1.5 {
  set ::flist {}
  catchsql {SELECT coalesce(min(a,b,c),999) FROM t1}
} {0 999}
do_test auth2-1.6 {
  set ::flist
} {coalesce min}
do_test auth2-1.7 {
  set ::flist {}
  catchsql {SELECT coalesce(a,b,c) FROM t1}
} {0 1}
do_test auth2-1.8 {
  set ::flist
} coalesce

# Make sure the authorizer is not called when parsing the schema
# and when computing the result set of a view.
#
db close
sqlite3 db test.db
sqlite3 db2 test.db
proc auth {args} {
  global authargs
  append authargs $args\n
  return SQLITE_OK
}
db auth auth
do_test auth2-2.1 {
  set ::authargs {}
  db eval {
    CREATE TABLE t2(x,y,z);
  }
  set ::authargs
} {SQLITE_INSERT sqlite_master {} main {}
SQLITE_CREATE_TABLE t2 {} main {}
SQLITE_UPDATE sqlite_master type main {}
SQLITE_UPDATE sqlite_master name main {}
SQLITE_UPDATE sqlite_master tbl_name main {}
SQLITE_UPDATE sqlite_master rootpage main {}
SQLITE_UPDATE sqlite_master sql main {}
SQLITE_READ sqlite_master ROWID main {}
SQLITE_READ sqlite_master name main {}
SQLITE_READ sqlite_master rootpage main {}
SQLITE_READ sqlite_master sql main {}
SQLITE_READ sqlite_master tbl_name main {}
}
do_test auth2-2.2 {
  set ::authargs {}
  db eval {
    CREATE VIEW v2 AS SELECT x+y AS a, y+z AS b from t2;
  }
  set ::authargs
} {SQLITE_INSERT sqlite_master {} main {}
SQLITE_CREATE_VIEW v2 {} main {}
SQLITE_UPDATE sqlite_master type main {}
SQLITE_UPDATE sqlite_master name main {}
SQLITE_UPDATE sqlite_master tbl_name main {}
SQLITE_UPDATE sqlite_master rootpage main {}
SQLITE_UPDATE sqlite_master sql main {}
SQLITE_READ sqlite_master ROWID main {}
SQLITE_READ sqlite_master name main {}
SQLITE_READ sqlite_master rootpage main {}
SQLITE_READ sqlite_master sql main {}
SQLITE_READ sqlite_master tbl_name main {}
}
do_test auth2-2.3 {
  set ::authargs {}
  db eval {
    SELECT a, b FROM v2;
  }
  set ::authargs
} {SQLITE_SELECT {} {} {} {}
SQLITE_READ v2 a main {}
SQLITE_READ v2 b main {}
SQLITE_READ t2 x main v2
SQLITE_READ t2 y main v2
SQLITE_READ t2 y main v2
SQLITE_READ t2 z main v2
SQLITE_SELECT {} {} {} v2
}
do_test auth2-2.4 {
  db2 eval {
    CREATE TABLE t3(p,q,r);
  }
  set ::authargs {}
  db eval {
    SELECT b, a FROM v2;
  }
  set ::authargs
} {SQLITE_SELECT {} {} {} {}
SQLITE_READ v2 b main {}
SQLITE_READ v2 a main {}
SQLITE_READ t2 x main v2
SQLITE_READ t2 y main v2
SQLITE_READ t2 y main v2
SQLITE_READ t2 z main v2
SQLITE_SELECT {} {} {} v2
SQLITE_SELECT {} {} {} {}
SQLITE_READ v2 b main {}
SQLITE_READ v2 a main {}
SQLITE_READ t2 x main v2
SQLITE_READ t2 y main v2
SQLITE_READ t2 y main v2
SQLITE_READ t2 z main v2
SQLITE_SELECT {} {} {} v2
}
db2 close

finish_test

Added test/auth3.test.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# 2008 October 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test that the truncate optimization is disabled if the SQLITE_DELETE
# authorization callback returns SQLITE_IGNORE.
#
# $Id: auth3.test,v 1.2 2009/05/04 01:58:31 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# disable this test if the SQLITE_OMIT_AUTHORIZATION macro is
# defined during compilation.
if {[catch {db auth {}} msg]} {
  finish_test
  return
}

# Disable the statement cache for these tests.
# 
db cache size 0

db authorizer ::auth
proc auth {code arg1 arg2 arg3 arg4} {
  if {$code=="SQLITE_DELETE"} {
    return $::authcode
  }
  return SQLITE_OK
}

#--------------------------------------------------------------------------
# The following tests - auth3-1.* - test that return values of SQLITE_DENY,
# SQLITE_IGNORE, SQLITE_OK and <invalid> are correctly handled when returned
# by an SQLITE_DELETE authorization callback triggered by a 
# "DELETE FROM <table-name>" statement.
#
do_test auth3-1.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
  }
} {}
do_test auth3.1.2 {
  set ::authcode SQLITE_DENY
  catchsql { DELETE FROM t1 }
} {1 {not authorized}}
do_test auth3.1.3 {
  set ::authcode SQLITE_INVALID
  catchsql { DELETE FROM t1 }
} {1 {authorizer malfunction}}
do_test auth3.1.4 {
  execsql { SELECT * FROM t1 }
} {1 2 3 4 5 6}
do_test auth3-1.5 {
  set ::authcode SQLITE_IGNORE
  execsql { 
    DELETE FROM t1;
    SELECT * FROM t1;
  }
} {}
do_test auth3-1.6 {
  set ::authcode SQLITE_OK
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
    DELETE FROM t1;
    SELECT * FROM t1;
  }
} {}

#--------------------------------------------------------------------------
# These tests - auth3-2.* - test that returning SQLITE_IGNORE really does
# disable the truncate optimization.
#
do_test auth3-2.1 {
  set ::authcode SQLITE_OK
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
  }
  set sqlite_search_count 0
  execsql {
    DELETE FROM t1;
  }
  set sqlite_search_count
} {0}

do_test auth3-2.2 {
  set ::authcode SQLITE_IGNORE
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
  }
  set sqlite_search_count 0
  execsql {
    DELETE FROM t1;
  }
  set sqlite_search_count
} {1}

finish_test

Added test/autoinc.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# 2004 November 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the AUTOINCREMENT features.
#
# $Id: autoinc.test,v 1.14 2009/06/23 20:28:54 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If the library is not compiled with autoincrement support then
# skip all tests in this file.
#
ifcapable {!autoinc} {
  finish_test
  return
}

sqlite3_db_config_lookaside db 0 0 0

# The database is initially empty.
#
do_test autoinc-1.1 {
  execsql {
    SELECT name FROM sqlite_master WHERE type='table';
  }
} {}

# Add a table with the AUTOINCREMENT feature.  Verify that the
# SQLITE_SEQUENCE table gets created.
#
do_test autoinc-1.2 {
  execsql {
    CREATE TABLE t1(x INTEGER PRIMARY KEY AUTOINCREMENT, y);
    SELECT name FROM sqlite_master WHERE type='table';
  }
} {t1 sqlite_sequence}

# The SQLITE_SEQUENCE table is initially empty
#
do_test autoinc-1.3 {
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {}
do_test autoinc-1.3.1 {
  catchsql {
    CREATE INDEX seqidx ON sqlite_sequence(name)
  }
} {1 {table sqlite_sequence may not be indexed}}

# Close and reopen the database.  Verify that everything is still there.
#
do_test autoinc-1.4 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {}

# We are not allowed to drop the sqlite_sequence table.
#
do_test autoinc-1.5 {
  catchsql {DROP TABLE sqlite_sequence}
} {1 {table sqlite_sequence may not be dropped}}
do_test autoinc-1.6 {
  execsql {SELECT name FROM sqlite_master WHERE type='table'}
} {t1 sqlite_sequence}

# Insert an entries into the t1 table and make sure the largest key
# is always recorded in the sqlite_sequence table.
#
do_test autoinc-2.1 {
  execsql {
    SELECT * FROM sqlite_sequence
  }
} {}
do_test autoinc-2.2 {
  execsql {
    INSERT INTO t1 VALUES(12,34);
    SELECT * FROM sqlite_sequence;
  }
} {t1 12}
do_test autoinc-2.3 {
  execsql {
    INSERT INTO t1 VALUES(1,23);
    SELECT * FROM sqlite_sequence;
  }
} {t1 12}
do_test autoinc-2.4 {
  execsql {
    INSERT INTO t1 VALUES(123,456);
    SELECT * FROM sqlite_sequence;
  }
} {t1 123}
do_test autoinc-2.5 {
  execsql {
    INSERT INTO t1 VALUES(NULL,567);
    SELECT * FROM sqlite_sequence;
  }
} {t1 124}
do_test autoinc-2.6 {
  execsql {
    DELETE FROM t1 WHERE y=567;
    SELECT * FROM sqlite_sequence;
  }
} {t1 124}
do_test autoinc-2.7 {
  execsql {
    INSERT INTO t1 VALUES(NULL,567);
    SELECT * FROM sqlite_sequence;
  }
} {t1 125}
do_test autoinc-2.8 {
  execsql {
    DELETE FROM t1;
    SELECT * FROM sqlite_sequence;
  }
} {t1 125}
do_test autoinc-2.9 {
  execsql {
    INSERT INTO t1 VALUES(12,34);
    SELECT * FROM sqlite_sequence;
  }
} {t1 125}
do_test autoinc-2.10 {
  execsql {
    INSERT INTO t1 VALUES(125,456);
    SELECT * FROM sqlite_sequence;
  }
} {t1 125}
do_test autoinc-2.11 {
  execsql {
    INSERT INTO t1 VALUES(-1234567,-1);
    SELECT * FROM sqlite_sequence;
  }
} {t1 125}
do_test autoinc-2.12 {
  execsql {
    INSERT INTO t1 VALUES(234,5678);
    SELECT * FROM sqlite_sequence;
  }
} {t1 234}
do_test autoinc-2.13 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(NULL,1);
    SELECT * FROM sqlite_sequence;
  }
} {t1 235}
do_test autoinc-2.14 {
  execsql {
    SELECT * FROM t1;
  }
} {235 1}

# Manually change the autoincrement values in sqlite_sequence.
#
do_test autoinc-2.20 {
  execsql {
    UPDATE sqlite_sequence SET seq=1234 WHERE name='t1';
    INSERT INTO t1 VALUES(NULL,2);
    SELECT * FROM t1;
  }
} {235 1 1235 2}
do_test autoinc-2.21 {
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {t1 1235}
do_test autoinc-2.22 {
  execsql {
    UPDATE sqlite_sequence SET seq=NULL WHERE name='t1';
    INSERT INTO t1 VALUES(NULL,3);
    SELECT * FROM t1;
  }
} {235 1 1235 2 1236 3}
do_test autoinc-2.23 {
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {t1 1236}
do_test autoinc-2.24 {
  execsql {
    UPDATE sqlite_sequence SET seq='a-string' WHERE name='t1';
    INSERT INTO t1 VALUES(NULL,4);
    SELECT * FROM t1;
  }
} {235 1 1235 2 1236 3 1237 4}
do_test autoinc-2.25 {
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {t1 1237}
do_test autoinc-2.26 {
  execsql {
    DELETE FROM sqlite_sequence WHERE name='t1';
    INSERT INTO t1 VALUES(NULL,5);
    SELECT * FROM t1;
  }
} {235 1 1235 2 1236 3 1237 4 1238 5}
do_test autoinc-2.27 {
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {t1 1238}
do_test autoinc-2.28 {
  execsql {
    UPDATE sqlite_sequence SET seq='12345678901234567890'
      WHERE name='t1';
    INSERT INTO t1 VALUES(NULL,6);
    SELECT * FROM t1;
  }
} {235 1 1235 2 1236 3 1237 4 1238 5 1239 6}
do_test autoinc-2.29 {
  execsql {
    SELECT * FROM sqlite_sequence;
  }
} {t1 1239}

# Test multi-row inserts
#
do_test autoinc-2.50 {
  execsql {
    DELETE FROM t1 WHERE y>=3;
    INSERT INTO t1 SELECT NULL, y+2 FROM t1;
    SELECT * FROM t1;
  }
} {235 1 1235 2 1240 3 1241 4}
do_test autoinc-2.51 {
  execsql {
    SELECT * FROM sqlite_sequence
  }
} {t1 1241}

ifcapable tempdb {
  do_test autoinc-2.52 {
    execsql {
      CREATE TEMP TABLE t2 AS SELECT y FROM t1;
    }
    execsql {
      INSERT INTO t1 SELECT NULL, y+4 FROM t2;
      SELECT * FROM t1;
    }
  } {235 1 1235 2 1240 3 1241 4 1242 5 1243 6 1244 7 1245 8}
  do_test autoinc-2.53 {
    execsql {
      SELECT * FROM sqlite_sequence
    }
  } {t1 1245}
  do_test autoinc-2.54 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 SELECT NULL, y FROM t2;
      SELECT * FROM t1;
    }
  } {1246 1 1247 2 1248 3 1249 4}
  do_test autoinc-2.55 {
    execsql {
      SELECT * FROM sqlite_sequence
    }
  } {t1 1249}
}

# Create multiple AUTOINCREMENT tables.  Make sure all sequences are
# tracked separately and do not interfere with one another.
#
do_test autoinc-2.70 {
  catchsql {
    DROP TABLE t2;
  }
  execsql {
    CREATE TABLE t2(d, e INTEGER PRIMARY KEY AUTOINCREMENT, f);
    INSERT INTO t2(d) VALUES(1);
    SELECT * FROM sqlite_sequence;
  }
} [ifcapable tempdb {list t1 1249 t2 1} else {list t1 1241 t2 1}]
do_test autoinc-2.71 {
  execsql {
    INSERT INTO t2(d) VALUES(2);
    SELECT * FROM sqlite_sequence;
  }
} [ifcapable tempdb {list t1 1249 t2 2} else {list t1 1241 t2 2}]
do_test autoinc-2.72 {
  execsql {
    INSERT INTO t1(x) VALUES(10000);
    SELECT * FROM sqlite_sequence;
  }
} {t1 10000 t2 2}
do_test autoinc-2.73 {
  execsql {
    CREATE TABLE t3(g INTEGER PRIMARY KEY AUTOINCREMENT, h);
    INSERT INTO t3(h) VALUES(1);
    SELECT * FROM sqlite_sequence;
  }
} {t1 10000 t2 2 t3 1}
do_test autoinc-2.74 {
  execsql {
    INSERT INTO t2(d,e) VALUES(3,100);
    SELECT * FROM sqlite_sequence;
  }
} {t1 10000 t2 100 t3 1}


# When a table with an AUTOINCREMENT is deleted, the corresponding entry
# in the SQLITE_SEQUENCE table should also be deleted.  But the SQLITE_SEQUENCE
# table itself should remain behind.
#
do_test autoinc-3.1 {
  execsql {SELECT name FROM sqlite_sequence}
} {t1 t2 t3}
do_test autoinc-3.2 {
  execsql {
    DROP TABLE t1;
    SELECT name FROM sqlite_sequence;
  }
} {t2 t3}
do_test autoinc-3.3 {
  execsql {
    DROP TABLE t3;
    SELECT name FROM sqlite_sequence;
  }
} {t2}
do_test autoinc-3.4 {
  execsql {
    DROP TABLE t2;
    SELECT name FROM sqlite_sequence;
  }
} {}

# AUTOINCREMENT on TEMP tables.
#
ifcapable tempdb {
  do_test autoinc-4.1 {
    execsql {
      SELECT 1, name FROM sqlite_master WHERE type='table';
      SELECT 2, name FROM sqlite_temp_master WHERE type='table';
    }
  } {1 sqlite_sequence}
  do_test autoinc-4.2 {
    execsql {
      CREATE TABLE t1(x INTEGER PRIMARY KEY AUTOINCREMENT, y);
      CREATE TEMP TABLE t3(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
      SELECT 1, name FROM sqlite_master WHERE type='table';
      SELECT 2, name FROM sqlite_temp_master WHERE type='table';
    }
  } {1 sqlite_sequence 1 t1 2 t3 2 sqlite_sequence}
  do_test autoinc-4.3 {
    execsql {
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {}
  do_test autoinc-4.4 {
    execsql {
      INSERT INTO t1 VALUES(10,1);
      INSERT INTO t3 VALUES(20,2);
      INSERT INTO t1 VALUES(NULL,3);
      INSERT INTO t3 VALUES(NULL,4);
    }
  } {}
  
  ifcapable compound {
  do_test autoinc-4.4.1 {
    execsql {
      SELECT * FROM t1 UNION ALL SELECT * FROM t3;
    }
  } {10 1 11 3 20 2 21 4}
  } ;# ifcapable compound
  
  do_test autoinc-4.5 {
    execsql {
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {1 t1 11 2 t3 21}
  do_test autoinc-4.6 {
    execsql {
      INSERT INTO t1 SELECT * FROM t3;
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {1 t1 21 2 t3 21}
  do_test autoinc-4.7 {
    execsql {
      INSERT INTO t3 SELECT x+100, y  FROM t1;
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {1 t1 21 2 t3 121}
  do_test autoinc-4.8 {
    execsql {
      DROP TABLE t3;
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {1 t1 21}
  do_test autoinc-4.9 {
    execsql {
      CREATE TEMP TABLE t2(p INTEGER PRIMARY KEY AUTOINCREMENT, q);
      INSERT INTO t2 SELECT * FROM t1;
      DROP TABLE t1;
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {2 t2 21}
  do_test autoinc-4.10 {
    execsql {
      DROP TABLE t2;
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
    }
  } {}
}

# Make sure AUTOINCREMENT works on ATTACH-ed tables.
#
ifcapable tempdb&&attach {
  do_test autoinc-5.1 {
    file delete -force test2.db
    file delete -force test2.db-journal
    sqlite3 db2 test2.db
    execsql {
      CREATE TABLE t4(m INTEGER PRIMARY KEY AUTOINCREMENT, n);
      CREATE TABLE t5(o, p INTEGER PRIMARY KEY AUTOINCREMENT);
    } db2;
    execsql {
      ATTACH 'test2.db' as aux;
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
      SELECT 3, * FROM aux.sqlite_sequence;
    }
  } {}
  do_test autoinc-5.2 {
    execsql {
      INSERT INTO t4 VALUES(NULL,1);
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
      SELECT 3, * FROM aux.sqlite_sequence;
    }
  } {3 t4 1}
  do_test autoinc-5.3 {
    execsql {
      INSERT INTO t5 VALUES(100,200);
      SELECT * FROM sqlite_sequence
    } db2
  } {t4 1 t5 200}
  do_test autoinc-5.4 {
    execsql {
      SELECT 1, * FROM main.sqlite_sequence;
      SELECT 2, * FROM temp.sqlite_sequence;
      SELECT 3, * FROM aux.sqlite_sequence;
    }
  } {3 t4 1 3 t5 200}
}

# Requirement REQ00310:  Make sure an insert fails if the sequence is
# already at its maximum value.
#
ifcapable {rowid32} {
  do_test autoinc-6.1 {
    execsql {
      CREATE TABLE t6(v INTEGER PRIMARY KEY AUTOINCREMENT, w);
      INSERT INTO t6 VALUES(2147483647,1);
      SELECT seq FROM main.sqlite_sequence WHERE name='t6';
    }
  } 2147483647
}
ifcapable {!rowid32} {
  do_test autoinc-6.1 {
    execsql {
      CREATE TABLE t6(v INTEGER PRIMARY KEY AUTOINCREMENT, w);
      INSERT INTO t6 VALUES(9223372036854775807,1);
      SELECT seq FROM main.sqlite_sequence WHERE name='t6';
    }
  } 9223372036854775807
}
do_test autoinc-6.2 {
  catchsql {
    INSERT INTO t6 VALUES(NULL,1);
  }
} {1 {database or disk is full}}

# Allow the AUTOINCREMENT keyword inside the parentheses
# on a separate PRIMARY KEY designation.
#
do_test autoinc-7.1 {
  execsql {
    CREATE TABLE t7(x INTEGER, y REAL, PRIMARY KEY(x AUTOINCREMENT));
    INSERT INTO t7(y) VALUES(123);
    INSERT INTO t7(y) VALUES(234);
    DELETE FROM t7;
    INSERT INTO t7(y) VALUES(345);
    SELECT * FROM t7;
  }
} {3 345.0}

# Test that if the AUTOINCREMENT is applied to a non integer primary key
# the error message is sensible.
do_test autoinc-7.2 {
  catchsql {
    CREATE TABLE t8(x TEXT PRIMARY KEY AUTOINCREMENT);
  }
} {1 {AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY}}


# Ticket #1283.  Make sure that preparing but never running a statement
# that creates the sqlite_sequence table does not mess up the database.
#
do_test autoinc-8.1 {
  catch {db2 close}
  catch {db close}
  file delete -force test.db
  sqlite3 db test.db
  set DB [sqlite3_connection_pointer db]
  set STMT [sqlite3_prepare $DB {
     CREATE TABLE t1(
       x INTEGER PRIMARY KEY AUTOINCREMENT
     )
  } -1 TAIL]
  sqlite3_finalize $STMT
  set STMT [sqlite3_prepare $DB {
     CREATE TABLE t1(
       x INTEGER PRIMARY KEY AUTOINCREMENT
     )
  } -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {
    INSERT INTO t1 VALUES(NULL);
    SELECT * FROM t1;
  }
} {1}

# Ticket #3148
# Make sure the sqlite_sequence table is not damaged when doing
# an empty insert - an INSERT INTO ... SELECT ... where the SELECT
# clause returns an empty set.
#
do_test autoinc-9.1 {
  db eval {
    CREATE TABLE t2(x INTEGER PRIMARY KEY AUTOINCREMENT, y);
    INSERT INTO t2 VALUES(NULL, 1);
    CREATE TABLE t3(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
    INSERT INTO t3 SELECT * FROM t2 WHERE y>1;

    SELECT * FROM sqlite_sequence WHERE name='t3';
  }
} {t3 0}

ifcapable trigger {
  catchsql { pragma recursive_triggers = off } 
  
  # Ticket #3928.  Make sure that triggers to not make extra slots in
  # the SQLITE_SEQUENCE table.
  #
  do_test autoinc-3928.1 {
    db eval {
      CREATE TABLE t3928(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
      CREATE TRIGGER t3928r1 BEFORE INSERT ON t3928 BEGIN
        INSERT INTO t3928(b) VALUES('before1');
        INSERT INTO t3928(b) VALUES('before2');
      END;
      CREATE TRIGGER t3928r2 AFTER INSERT ON t3928 BEGIN
        INSERT INTO t3928(b) VALUES('after1');
        INSERT INTO t3928(b) VALUES('after2');
      END;
      INSERT INTO t3928(b) VALUES('test');
      SELECT * FROM t3928 ORDER BY a;
    }
  } {1 before1 2 after1 3 after2 4 before2 5 after1 6 after2 7 test 8 before1 9 before2 10 after1 11 before1 12 before2 13 after2}
  do_test autoinc-3928.2 {
    db eval {
      SELECT * FROM sqlite_sequence WHERE name='t3928'
    }
  } {t3928 13}

  do_test autoinc-3928.3 {
    db eval {
      DROP TRIGGER t3928r1;
      DROP TRIGGER t3928r2;
      CREATE TRIGGER t3928r3 BEFORE UPDATE ON t3928 
        WHEN typeof(new.b)=='integer' BEGIN
           INSERT INTO t3928(b) VALUES('before-int-' || new.b);
      END;
      CREATE TRIGGER t3928r4 AFTER UPDATE ON t3928 
        WHEN typeof(new.b)=='integer' BEGIN
           INSERT INTO t3928(b) VALUES('after-int-' || new.b);
      END;
      DELETE FROM t3928 WHERE a!=1;
      UPDATE t3928 SET b=456 WHERE a=1;
      SELECT * FROM t3928 ORDER BY a;
    }
  } {1 456 14 before-int-456 15 after-int-456}
  do_test autoinc-3928.4 {
    db eval {
      SELECT * FROM sqlite_sequence WHERE name='t3928'
    }
  } {t3928 15}
  
  do_test autoinc-3928.5 {
    db eval {
      CREATE TABLE t3928b(x);
      INSERT INTO t3928b VALUES(100);
      INSERT INTO t3928b VALUES(200);
      INSERT INTO t3928b VALUES(300);
      DELETE FROM t3928;
      CREATE TABLE t3928c(y INTEGER PRIMARY KEY AUTOINCREMENT, z);
      CREATE TRIGGER t3928br1 BEFORE DELETE ON t3928b BEGIN
        INSERT INTO t3928(b) VALUES('before-del-'||old.x);
        INSERT INTO t3928c(z) VALUES('before-del-'||old.x);
      END;
      CREATE TRIGGER t3928br2 AFTER DELETE ON t3928b BEGIN
        INSERT INTO t3928(b) VALUES('after-del-'||old.x);
        INSERT INTO t3928c(z) VALUES('after-del-'||old.x);
      END;
      DELETE FROM t3928b;
      SELECT * FROM t3928 ORDER BY a;
    }
  } {16 before-del-100 17 after-del-100 18 before-del-200 19 after-del-200 20 before-del-300 21 after-del-300}
  do_test autoinc-3928.6 {
    db eval {
      SELECT * FROM t3928c ORDER BY y;
    }
  } {1 before-del-100 2 after-del-100 3 before-del-200 4 after-del-200 5 before-del-300 6 after-del-300}
  do_test autoinc-3928.7 {
    db eval {
      SELECT * FROM sqlite_sequence WHERE name LIKE 't3928%' ORDER BY name;
    }
  } {t3928 21 t3928c 6}
  
  # Ticket [a696379c1f0886615541a48b35bd8181a80e88f8]
  do_test autoinc-a69637.1 {
    db eval {
      CREATE TABLE ta69637_1(x INTEGER PRIMARY KEY AUTOINCREMENT, y);
      CREATE TABLE ta69637_2(z);
      CREATE TRIGGER ra69637_1 AFTER INSERT ON ta69637_2 BEGIN
        INSERT INTO ta69637_1(y) VALUES(new.z+1);
      END;
      INSERT INTO ta69637_2 VALUES(123);
      SELECT * FROM ta69637_1;
    }
  } {1 124}
  do_test autoinc-a69637.2 {
    db eval {
      CREATE VIEW va69637_2 AS SELECT * FROM ta69637_2;
      CREATE TRIGGER ra69637_2 INSTEAD OF INSERT ON va69637_2 BEGIN
        INSERT INTO ta69637_1(y) VALUES(new.z+10000);
      END;
      INSERT INTO va69637_2 VALUES(123);
      SELECT * FROM ta69637_1;
    }
  } {1 124 2 10123}
}



finish_test

Added test/autovacuum.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the SELECT statement.
#
# $Id: autovacuum.test,v 1.29 2009/04/06 17:50:03 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If this build of the library does not support auto-vacuum, omit this
# whole file.
ifcapable {!autovacuum || !pragma} {
  finish_test
  return
}

# Return a string $len characters long. The returned string is $char repeated
# over and over. For example, [make_str abc 8] returns "abcabcab".
proc make_str {char len} {
  set str [string repeat $char. $len]
  return [string range $str 0 [expr $len-1]]
}

# Return the number of pages in the file test.db by looking at the file system.
proc file_pages {} {
  return [expr [file size test.db] / 1024]
}

#-------------------------------------------------------------------------
# Test cases autovacuum-1.* work as follows:
#
# 1. A table with a single indexed field is created.
# 2. Approximately 20 rows are inserted into the table. Each row is long 
#    enough such that it uses at least 2 overflow pages for both the table 
#    and index entry.
# 3. The rows are deleted in a psuedo-random order. Sometimes only one row
#    is deleted per transaction, sometimes more than one.
# 4. After each transaction the table data is checked to ensure it is correct
#    and a "PRAGMA integrity_check" is executed.
# 5. Once all the rows are deleted the file is checked to make sure it 
#    consists of exactly 4 pages.
#
# Steps 2-5 are repeated for a few different psuedo-random delete patterns 
# (defined by the $delete_orders list).
set delete_orders [list]
lappend delete_orders {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20}
lappend delete_orders {20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} 
lappend delete_orders {8 18 2 4 14 11 13 3 10 7 9 5 12 17 19 15 20 6 16 1}
lappend delete_orders {10 3 11 17 19 20 7 4 13 6 1 14 16 12 9 18 8 15 5 2}
lappend delete_orders {{1 2 3 4 5 6 7 8 9 10} {11 12 13 14 15 16 17 18 19 20}}
lappend delete_orders {{19 8 17 15} {16 11 9 14} {18 5 3 1} {13 20 7 2} {6 12}}

# The length of each table entry. 
# set ENTRY_LEN 3500
set ENTRY_LEN 3500

do_test autovacuum-1.1 {
  execsql {
    PRAGMA auto_vacuum = 1;
    CREATE TABLE av1(a);
    CREATE INDEX av1_idx ON av1(a);
  }
} {}

set tn 0
foreach delete_order $delete_orders {
  incr tn

  # Set up the table.
  set ::tbl_data [list]
  foreach i [lsort -integer [eval concat $delete_order]] {
    execsql "INSERT INTO av1 (oid, a) VALUES($i, '[make_str $i $ENTRY_LEN]')"
    lappend ::tbl_data [make_str $i $ENTRY_LEN]
  }

  # Make sure the integrity check passes with the initial data.
  ifcapable {integrityck} {
    do_test autovacuum-1.$tn.1 {
      execsql {
        pragma integrity_check
      }
    } {ok}
  }

  foreach delete $delete_order {
    # Delete one set of rows from the table.
    do_test autovacuum-1.$tn.($delete).1 {
      execsql "
        DELETE FROM av1 WHERE oid = [join $delete " OR oid = "]
      "
    } {}

    # Do the integrity check.
    ifcapable {integrityck} {
      do_test autovacuum-1.$tn.($delete).2 {
        execsql {
          pragma integrity_check
        }
      } {ok}
    }
    # Ensure the data remaining in the table is what was expected.
    foreach d $delete {
      set idx [lsearch $::tbl_data [make_str $d $ENTRY_LEN]]
      set ::tbl_data [lreplace $::tbl_data $idx $idx]
    }
    do_test autovacuum-1.$tn.($delete).3 {
      execsql {
        select a from av1
      }
    } $::tbl_data
  }

  # All rows have been deleted. Ensure the file has shrunk to 4 pages.
  do_test autovacuum-1.$tn.3 {
    file_pages
  } {4}
}

#---------------------------------------------------------------------------
# Tests cases autovacuum-2.* test that root pages are allocated 
# and deallocated correctly at the start of the file. Operation is roughly as
# follows:
#
# autovacuum-2.1.*: Drop the tables that currently exist in the database.
# autovacuum-2.2.*: Create some tables. Ensure that data pages can be
#                   moved correctly to make space for new root-pages.
# autovacuum-2.3.*: Drop one of the tables just created (not the last one),
#                   and check that one of the other tables is moved to
#                   the free root-page location.
# autovacuum-2.4.*: Check that a table can be created correctly when the
#                   root-page it requires is on the free-list.
# autovacuum-2.5.*: Check that a table with indices can be dropped. This
#                   is slightly tricky because dropping one of the
#                   indices/table btrees could move the root-page of another.
#                   The code-generation layer of SQLite overcomes this problem
#                   by dropping the btrees in descending order of root-pages.
#                   This test ensures that this actually happens.
#
do_test autovacuum-2.1.1 {
  execsql {
    DROP TABLE av1;
  }
} {}
do_test autovacuum-2.1.2 {
  file_pages
} {1}

# Create a table and put some data in it.
do_test autovacuum-2.2.1 {
  execsql {
    CREATE TABLE av1(x);
    SELECT rootpage FROM sqlite_master ORDER BY rootpage;
  }
} {3}
do_test autovacuum-2.2.2 {
  execsql "
    INSERT INTO av1 VALUES('[make_str abc 3000]');
    INSERT INTO av1 VALUES('[make_str def 3000]');
    INSERT INTO av1 VALUES('[make_str ghi 3000]');
    INSERT INTO av1 VALUES('[make_str jkl 3000]');
  "
  set ::av1_data [db eval {select * from av1}]
  file_pages
} {15}

# Create another table. Check it is located immediately after the first.
# This test case moves the second page in an over-flow chain.
do_test autovacuum-2.2.3 {
  execsql {
    CREATE TABLE av2(x);
    SELECT rootpage FROM sqlite_master ORDER BY rootpage;
  }
} {3 4}
do_test autovacuum-2.2.4 {
  file_pages
} {16}

# Create another table. Check it is located immediately after the second.
# This test case moves the first page in an over-flow chain.
do_test autovacuum-2.2.5 {
  execsql {
    CREATE TABLE av3(x);
    SELECT rootpage FROM sqlite_master ORDER BY rootpage;
  }
} {3 4 5}
do_test autovacuum-2.2.6 {
  file_pages
} {17}

# Create another table. Check it is located immediately after the second.
# This test case moves a btree leaf page.
do_test autovacuum-2.2.7 {
  execsql {
    CREATE TABLE av4(x);
    SELECT rootpage FROM sqlite_master ORDER BY rootpage;
  }
} {3 4 5 6}
do_test autovacuum-2.2.8 {
  file_pages
} {18}
do_test autovacuum-2.2.9 {
  execsql {
    select * from av1
  }
} $av1_data

do_test autovacuum-2.3.1 {
  execsql {
    INSERT INTO av2 SELECT 'av1' || x FROM av1;
    INSERT INTO av3 SELECT 'av2' || x FROM av1;
    INSERT INTO av4 SELECT 'av3' || x FROM av1;
  }
  set ::av2_data [execsql {select x from av2}]
  set ::av3_data [execsql {select x from av3}]
  set ::av4_data [execsql {select x from av4}]
  file_pages
} {54}
do_test autovacuum-2.3.2 {
  execsql {
    DROP TABLE av2;
    SELECT rootpage FROM sqlite_master ORDER BY rootpage;
  }
} {3 4 5}
do_test autovacuum-2.3.3 {
  file_pages
} {41}
do_test autovacuum-2.3.4 {
  execsql {
    SELECT x FROM av3;
  }
} $::av3_data
do_test autovacuum-2.3.5 {
  execsql {
    SELECT x FROM av4;
  }
} $::av4_data

# Drop all the tables in the file. This puts all pages except the first 2
# (the sqlite_master root-page and the first pointer map page) on the 
# free-list.
do_test autovacuum-2.4.1 {
  execsql {
    DROP TABLE av1;
    DROP TABLE av3;
    BEGIN;
    DROP TABLE av4;
  }
  file_pages
} {15}
do_test autovacuum-2.4.2 {
  for {set i 3} {$i<=10} {incr i} {
    execsql "CREATE TABLE av$i (x)"
  }
  file_pages
} {15}
do_test autovacuum-2.4.3 {
  execsql {
    SELECT rootpage FROM sqlite_master ORDER by rootpage
  }
} {3 4 5 6 7 8 9 10}

# Right now there are 5 free pages in the database. Consume and then free
# a 520 pages. Then create 520 tables. This ensures that at least some of the
# desired root-pages reside on the second free-list trunk page, and that the
# trunk itself is required at some point.
do_test autovacuum-2.4.4 {
  execsql "
    INSERT INTO av3 VALUES ('[make_str abcde [expr 1020*520 + 500]]');
    DELETE FROM av3;
  "
} {}
set root_page_list [list]
set pending_byte_page [expr ($::sqlite_pending_byte / 1024) + 1]
for {set i 3} {$i<=532} {incr i} {
  # 207 and 412 are pointer-map pages.
  if { $i!=207 && $i!=412 && $i != $pending_byte_page} {
    lappend root_page_list $i
  }
}
if {$i >= $pending_byte_page} {
  lappend root_page_list $i
}
do_test autovacuum-2.4.5 {
  for {set i 11} {$i<=530} {incr i} {
    execsql "CREATE TABLE av$i (x)"
  }
  execsql {
    SELECT rootpage FROM sqlite_master ORDER by rootpage
  }
} $root_page_list

# Just for fun, delete all those tables and see if the database is 1 page.
do_test autovacuum-2.4.6 {
  execsql COMMIT;
  file_pages
} [expr 561 + (($i >= $pending_byte_page)?1:0)]
integrity_check autovacuum-2.4.6
do_test autovacuum-2.4.7 {
  execsql BEGIN
  for {set i 3} {$i<=530} {incr i} {
    execsql "DROP TABLE av$i"
  }
  execsql COMMIT
  file_pages
} 1

# Create some tables with indices to drop.
do_test autovacuum-2.5.1 {
  execsql {
    CREATE TABLE av1(a PRIMARY KEY, b, c);
    INSERT INTO av1 VALUES('av1 a', 'av1 b', 'av1 c');

    CREATE TABLE av2(a PRIMARY KEY, b, c);
    CREATE INDEX av2_i1 ON av2(b);
    CREATE INDEX av2_i2 ON av2(c);
    INSERT INTO av2 VALUES('av2 a', 'av2 b', 'av2 c');

    CREATE TABLE av3(a PRIMARY KEY, b, c);
    CREATE INDEX av3_i1 ON av3(b);
    INSERT INTO av3 VALUES('av3 a', 'av3 b', 'av3 c');

    CREATE TABLE av4(a, b, c);
    CREATE INDEX av4_i1 ON av4(a);
    CREATE INDEX av4_i2 ON av4(b);
    CREATE INDEX av4_i3 ON av4(c);
    CREATE INDEX av4_i4 ON av4(a, b, c);
    INSERT INTO av4 VALUES('av4 a', 'av4 b', 'av4 c');
  }
} {}

do_test autovacuum-2.5.2 {
  execsql {
    SELECT name, rootpage FROM sqlite_master;
  }
} [list av1 3  sqlite_autoindex_av1_1 4 \
        av2 5  sqlite_autoindex_av2_1 6 av2_i1 7 av2_i2 8 \
        av3 9 sqlite_autoindex_av3_1 10 av3_i1 11 \
        av4 12 av4_i1 13 av4_i2 14 av4_i3 15 av4_i4 16 \
]

# The following 4 tests are SELECT queries that use the indices created.
# If the root-pages in the internal schema are not updated correctly when
# a table or indice is moved, these queries will fail. They are repeated
# after each table is dropped (i.e. as test cases 2.5.*.[1..4]).
do_test autovacuum-2.5.2.1 {
  execsql {
    SELECT * FROM av1 WHERE a = 'av1 a';
  }
} {{av1 a} {av1 b} {av1 c}}
do_test autovacuum-2.5.2.2 {
  execsql {
    SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c'
  }
} {{av2 a} {av2 b} {av2 c}}
do_test autovacuum-2.5.2.3 {
  execsql {
    SELECT * FROM av3 WHERE a = 'av3 a' AND b = 'av3 b';
  }
} {{av3 a} {av3 b} {av3 c}}
do_test autovacuum-2.5.2.4 {
  execsql {
    SELECT * FROM av4 WHERE a = 'av4 a' AND b = 'av4 b' AND c = 'av4 c';
  }
} {{av4 a} {av4 b} {av4 c}}

# Drop table av3. Indices av4_i2, av4_i3 and av4_i4 are moved to fill the two
# root pages vacated. The operation proceeds as:
# Step 1: Delete av3_i1 (root-page 11). Move root-page of av4_i4 to page 11.
# Step 2: Delete av3 (root-page 10). Move root-page of av4_i3 to page 10.
# Step 3: Delete sqlite_autoindex_av1_3 (root-page 9). Move av4_i2 to page 9.
do_test autovacuum-2.5.3 {
  execsql {
    DROP TABLE av3;
    SELECT name, rootpage FROM sqlite_master;
  }
} [list av1 3  sqlite_autoindex_av1_1 4 \
        av2 5  sqlite_autoindex_av2_1 6 av2_i1 7 av2_i2 8 \
        av4 12 av4_i1 13 av4_i2 9 av4_i3 10 av4_i4 11 \
]
do_test autovacuum-2.5.3.1 {
  execsql {
    SELECT * FROM av1 WHERE a = 'av1 a';
  }
} {{av1 a} {av1 b} {av1 c}}
do_test autovacuum-2.5.3.2 {
  execsql {
    SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c'
  }
} {{av2 a} {av2 b} {av2 c}}
do_test autovacuum-2.5.3.3 {
  execsql {
    SELECT * FROM av4 WHERE a = 'av4 a' AND b = 'av4 b' AND c = 'av4 c';
  }
} {{av4 a} {av4 b} {av4 c}}

# Drop table av1:
# Step 1: Delete av1 (root page 4). Root-page of av4_i1 fills the gap.
# Step 2: Delete sqlite_autoindex_av1_1 (root page 3). Move av4 to the gap.
do_test autovacuum-2.5.4 {
  execsql {
    DROP TABLE av1;
    SELECT name, rootpage FROM sqlite_master;
  }
} [list av2 5  sqlite_autoindex_av2_1 6 av2_i1 7 av2_i2 8 \
        av4 3 av4_i1 4 av4_i2 9 av4_i3 10 av4_i4 11 \
]
do_test autovacuum-2.5.4.2 {
  execsql {
    SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c'
  }
} {{av2 a} {av2 b} {av2 c}}
do_test autovacuum-2.5.4.4 {
  execsql {
    SELECT * FROM av4 WHERE a = 'av4 a' AND b = 'av4 b' AND c = 'av4 c';
  }
} {{av4 a} {av4 b} {av4 c}}

# Drop table av4:
# Step 1: Delete av4_i4.
# Step 2: Delete av4_i3.
# Step 3: Delete av4_i2.
# Step 4: Delete av4_i1. av2_i2 replaces it.
# Step 5: Delete av4. av2_i1 replaces it.
do_test autovacuum-2.5.5 {
  execsql {
    DROP TABLE av4;
    SELECT name, rootpage FROM sqlite_master;
  }
} [list av2 5 sqlite_autoindex_av2_1 6 av2_i1 3 av2_i2 4]
do_test autovacuum-2.5.5.2 {
  execsql {
    SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c'
  }
} {{av2 a} {av2 b} {av2 c}}

#--------------------------------------------------------------------------
# Test cases autovacuum-3.* test the operation of the "PRAGMA auto_vacuum"
# command.
#
do_test autovacuum-3.1 {
  execsql {
    PRAGMA auto_vacuum;
  }
} {1}
do_test autovacuum-3.2 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum;
  }
} {1}
do_test autovacuum-3.3 {
  execsql {
    PRAGMA auto_vacuum = 0;
    PRAGMA auto_vacuum;
  }
} {1}

do_test autovacuum-3.4 {
  db close
  file delete -force test.db
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum;
  }
} $AUTOVACUUM
do_test autovacuum-3.5 {
  execsql {
    CREATE TABLE av1(x);
    PRAGMA auto_vacuum;
  }
} $AUTOVACUUM
do_test autovacuum-3.6 {
  execsql {
    PRAGMA auto_vacuum = 1;
    PRAGMA auto_vacuum;
  }
} [expr $AUTOVACUUM ? 1 : 0]
do_test autovacuum-3.7 {
  execsql {
    DROP TABLE av1;
  }
  file_pages
} [expr $AUTOVACUUM?1:2]


#-----------------------------------------------------------------------
# Test that if a statement transaction around a CREATE INDEX statement is
# rolled back no corruption occurs.
#
do_test autovacuum-4.0 {
  # The last round of tests may have left the db in non-autovacuum mode.
  # Reset everything just in case.
  #
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum = 1;
    PRAGMA auto_vacuum;
  }
} {1}
do_test autovacuum-4.1 {
  execsql {
    CREATE TABLE av1(a, b);
    BEGIN;
  }
  for {set i 0} {$i<100} {incr i} {
    execsql "INSERT INTO av1 VALUES($i, '[string repeat X 200]');"
  }
  execsql "INSERT INTO av1 VALUES(99, '[string repeat X 200]');"
  execsql {
    SELECT sum(a) FROM av1;
  }
} {5049}
do_test autovacuum-4.2 {
  catchsql {
    CREATE UNIQUE INDEX av1_i ON av1(a);
  }
} {1 {indexed columns are not unique}}
do_test autovacuum-4.3 {
  execsql {
    SELECT sum(a) FROM av1;
  }
} {5049}
do_test autovacuum-4.4 {
  execsql {
    COMMIT;
  }
} {}

ifcapable integrityck {

# Ticket #1727
do_test autovacuum-5.1 {
  db close
  sqlite3 db :memory:
  db eval {
    PRAGMA auto_vacuum=1;
    CREATE TABLE t1(a);
    CREATE TABLE t2(a);
    DROP TABLE t1;
    PRAGMA integrity_check;
  }
} ok

}

# Ticket #1728.
#
# In autovacuum mode, when tables or indices are deleted, the rootpage
# values in the symbol table have to be updated.  There was a bug in this
# logic so that if an index/table was moved twice, the second move might
# not occur.  This would leave the internal symbol table in an inconsistent
# state causing subsequent statements to fail.
#
# The problem is difficult to reproduce.  The sequence of statements in
# the following test are carefully designed make it occur and thus to
# verify that this very obscure bug has been resolved.
# 
ifcapable integrityck&&memorydb {

do_test autovacuum-6.1 {
  db close
  sqlite3 db :memory:
  db eval {
    PRAGMA auto_vacuum=1;
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a);
    CREATE TABLE t2(a);
    CREATE INDEX i2 ON t2(a);
    CREATE TABLE t3(a);
    CREATE INDEX i3 ON t2(a);
    CREATE INDEX x ON t1(b);
    DROP TABLE t3;
    PRAGMA integrity_check;
    DROP TABLE t2;
    PRAGMA integrity_check;
    DROP TABLE t1;
    PRAGMA integrity_check;
  }
} {ok ok ok}

}

#---------------------------------------------------------------------
# Test cases autovacuum-7.X test the case where a page must be moved
# and the destination location collides with at least one other
# entry in the page hash-table (internal to the pager.c module. 
#
do_test autovacuum-7.1 {
  db close
  file delete -force test.db
  file delete -force test.db-journal
  sqlite3 db test.db

  execsql {
    PRAGMA auto_vacuum=1;
    CREATE TABLE t1(a, b, PRIMARY KEY(a, b));
    INSERT INTO t1 VALUES(randstr(400,400),randstr(400,400));
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 4
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 8
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 16
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 32
  }

  expr {[file size test.db] / 1024}
} {73}

do_test autovacuum-7.2 {
  execsql {
    CREATE TABLE t2(a, b, PRIMARY KEY(a, b));
    INSERT INTO t2 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2
    CREATE TABLE t3(a, b, PRIMARY KEY(a, b));
    INSERT INTO t3 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2
    CREATE TABLE t4(a, b, PRIMARY KEY(a, b));
    INSERT INTO t4 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2
    CREATE TABLE t5(a, b, PRIMARY KEY(a, b));
    INSERT INTO t5 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2
  }
  expr {[file size test.db] / 1024}
} {354}

do_test autovacuum-7.3 {
  db close
  sqlite3 db test.db
  execsql {
    BEGIN;
    DELETE FROM t4;
    COMMIT;
    SELECT count(*) FROM t1;
  }
  expr {[file size test.db] / 1024}
} {286}

#------------------------------------------------------------------------
# Additional tests.
#
# Try to determine the autovacuum setting for a database that is locked.
#
do_test autovacuum-8.1 {
  db close
  sqlite3 db test.db
  sqlite3 db2 test.db
  db eval {PRAGMA auto_vacuum}
} {1}
do_test autovacuum-8.2 {
  db eval {BEGIN EXCLUSIVE}
  catchsql {PRAGMA auto_vacuum} db2
} {1 {database is locked}}
catch {db2 close}
catch {db eval {COMMIT}}

do_test autovacuum-9.1 {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    DROP TABLE t3;
    DROP TABLE t4;
    DROP TABLE t5;
    PRAGMA page_count;
  }
} {1}
do_test autovacuum-9.2 {
  file size test.db
} 1024
do_test autovacuum-9.3 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    INSERT INTO t1 VALUES(NULL, randstr(50,50));
  }
  for {set ii 0} {$ii < 10} {incr ii} {
    db eval { INSERT INTO t1 SELECT NULL, randstr(50,50) FROM t1 }
  }
  file size test.db
} $::sqlite_pending_byte
do_test autovacuum-9.4 {
  execsql { INSERT INTO t1 SELECT NULL, randstr(50,50) FROM t1 }
} {}
do_test autovacuum-9.5 {
  execsql { DELETE FROM t1 WHERE rowid > (SELECT max(a)/2 FROM t1) }
  file size test.db
} $::sqlite_pending_byte
 

finish_test

Added test/autovacuum_ioerr2.test.









































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# 2001 October 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of I/O errors
# such as writes failing because the disk is full.
# 
# The tests in this file use special facilities that are only
# available in the SQLite test fixture.
#
# $Id: autovacuum_ioerr2.test,v 1.7 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If this build of the library does not support auto-vacuum, omit this
# whole file.
ifcapable {!autovacuum} {
  finish_test
  return
}

do_ioerr_test autovacuum-ioerr2-1 -sqlprep {
  PRAGMA auto_vacuum = 1;
  CREATE TABLE abc(a);
  INSERT INTO abc VALUES(randstr(1500,1500));
} -sqlbody {
  CREATE TABLE abc2(a);
  BEGIN;
  DELETE FROM abc;
  INSERT INTO abc VALUES(randstr(1500,1500));
  CREATE TABLE abc3(a);
  COMMIT;
}

do_ioerr_test autovacuum-ioerr2-2 -tclprep {
  execsql {
    PRAGMA auto_vacuum = 1;
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE abc(a);
    INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 4 is overflow
    INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 5 is overflow
  }
  for {set i 0} {$i<150} {incr i} {
    execsql {
      INSERT INTO abc VALUES(randstr(100,100)); 
    }
  }
  execsql COMMIT
} -sqlbody {
  BEGIN;
  DELETE FROM abc WHERE length(a)>100;
  UPDATE abc SET a = randstr(90,90);
  CREATE TABLE abc3(a);
  COMMIT;
}

do_ioerr_test autovacuum-ioerr2-3 -sqlprep {
  PRAGMA auto_vacuum = 1;
  CREATE TABLE abc(a);
  CREATE TABLE abc2(b);
} -sqlbody {
  BEGIN;
  INSERT INTO abc2 VALUES(10);
  DROP TABLE abc;
  COMMIT;
  DROP TABLE abc2;
}

file delete -force backup.db
ifcapable subquery {
  do_ioerr_test autovacuum-ioerr2-4 -tclprep {
    if {![file exists backup.db]} {
      sqlite3 dbb backup.db 
      execsql {
        PRAGMA auto_vacuum = 1;
        BEGIN;
        CREATE TABLE abc(a);
        INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 4 is overflow
        INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 5 is overflow
      } dbb
      for {set i 0} {$i<2500} {incr i} {
        execsql {
          INSERT INTO abc VALUES(randstr(100,100)); 
        } dbb
      }
      execsql {
        COMMIT;
        PRAGMA cache_size = 10;
      } dbb
      dbb close
    }
    db close
    file delete -force test.db
    file delete -force test.db-journal
    copy_file backup.db test.db
    set ::DB [sqlite3 db test.db]
    execsql {
      PRAGMA cache_size = 10;
    }
  } -sqlbody {
    BEGIN;
    DELETE FROM abc WHERE oid < 3;
    UPDATE abc SET a = randstr(100,100) WHERE oid > 2300;
    UPDATE abc SET a = randstr(1100,1100) WHERE oid = 
        (select max(oid) from abc);
    COMMIT;
  }
}

do_ioerr_test autovacuum-ioerr2-1 -sqlprep {
  PRAGMA auto_vacuum = 1;
  CREATE TABLE abc(a);
  INSERT INTO abc VALUES(randstr(1500,1500));
} -sqlbody {
  CREATE TABLE abc2(a);
  BEGIN;
  DELETE FROM abc;
  INSERT INTO abc VALUES(randstr(1500,1500));
  CREATE TABLE abc3(a);
  COMMIT;
}

finish_test

Added test/avtrans.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  This
# file is a copy of "trans.test" modified to run under autovacuum mode.
# the point is to stress the autovacuum logic and try to get it to fail.
#
# $Id: avtrans.test,v 1.6 2007/09/12 17:01:45 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Create several tables to work with.
#
do_test avtrans-1.0 {
  execsql {
    PRAGMA auto_vacuum=ON;
    CREATE TABLE one(a int PRIMARY KEY, b text);
    INSERT INTO one VALUES(1,'one');
    INSERT INTO one VALUES(2,'two');
    INSERT INTO one VALUES(3,'three');
    SELECT b FROM one ORDER BY a;
  }
} {one two three}
do_test avtrans-1.1 {
  execsql {
    CREATE TABLE two(a int PRIMARY KEY, b text);
    INSERT INTO two VALUES(1,'I');
    INSERT INTO two VALUES(5,'V');
    INSERT INTO two VALUES(10,'X');
    SELECT b FROM two ORDER BY a;
  }
} {I V X}
do_test avtrans-1.9 {
  sqlite3 altdb test.db
  execsql {SELECT b FROM one ORDER BY a} altdb
} {one two three}
do_test avtrans-1.10 {
  execsql {SELECT b FROM two ORDER BY a} altdb
} {I V X}
integrity_check avtrans-1.11

# Basic transactions
#
do_test avtrans-2.1 {
  set v [catch {execsql {BEGIN}} msg]
  lappend v $msg
} {0 {}}
do_test avtrans-2.2 {
  set v [catch {execsql {END}} msg]
  lappend v $msg
} {0 {}}
do_test avtrans-2.3 {
  set v [catch {execsql {BEGIN TRANSACTION}} msg]
  lappend v $msg
} {0 {}}
do_test avtrans-2.4 {
  set v [catch {execsql {COMMIT TRANSACTION}} msg]
  lappend v $msg
} {0 {}}
do_test avtrans-2.5 {
  set v [catch {execsql {BEGIN TRANSACTION 'foo'}} msg]
  lappend v $msg
} {0 {}}
do_test avtrans-2.6 {
  set v [catch {execsql {ROLLBACK TRANSACTION 'foo'}} msg]
  lappend v $msg
} {0 {}}
do_test avtrans-2.10 {
  execsql {
    BEGIN;
    SELECT a FROM one ORDER BY a;
    SELECT a FROM two ORDER BY a;
    END;
  }
} {1 2 3 1 5 10}
integrity_check avtrans-2.11

# Check the locking behavior
#
sqlite3_soft_heap_limit 0
do_test avtrans-3.1 {
  execsql {
    BEGIN;
    UPDATE one SET a = 0 WHERE 0;
    SELECT a FROM one ORDER BY a;
  }
} {1 2 3}
do_test avtrans-3.2 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 5 10}}
do_test avtrans-3.3 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3}}
do_test avtrans-3.4 {
  catchsql {
    INSERT INTO one VALUES(4,'four');
  }
} {0 {}}
do_test avtrans-3.5 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 5 10}}
do_test avtrans-3.6 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3}}
do_test avtrans-3.7 {
  catchsql {
    INSERT INTO two VALUES(4,'IV');
  }
} {0 {}}
do_test avtrans-3.8 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 5 10}}
do_test avtrans-3.9 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3}}
do_test avtrans-3.10 {
  execsql {END TRANSACTION}
} {}
do_test avtrans-3.11 {
  set v [catch {execsql {
    SELECT a FROM two ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test avtrans-3.12 {
  set v [catch {execsql {
    SELECT a FROM one ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 2 3 4}}
do_test avtrans-3.13 {
  set v [catch {execsql {
    SELECT a FROM two ORDER BY a;
  } db} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test avtrans-3.14 {
  set v [catch {execsql {
    SELECT a FROM one ORDER BY a;
  } db} msg]
  lappend v $msg
} {0 {1 2 3 4}}
sqlite3_soft_heap_limit $soft_limit
integrity_check avtrans-3.15

do_test avtrans-4.1 {
  set v [catch {execsql {
    COMMIT;
  } db} msg]
  lappend v $msg
} {1 {cannot commit - no transaction is active}}
do_test avtrans-4.2 {
  set v [catch {execsql {
    ROLLBACK;
  } db} msg]
  lappend v $msg
} {1 {cannot rollback - no transaction is active}}
do_test avtrans-4.3 {
  catchsql {
    BEGIN TRANSACTION;
    UPDATE two SET a = 0 WHERE 0;
    SELECT a FROM two ORDER BY a;
  } db
} {0 {1 4 5 10}}
do_test avtrans-4.4 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 4 5 10}}
do_test avtrans-4.5 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3 4}}
do_test avtrans-4.6 {
  catchsql {
    BEGIN TRANSACTION;
    SELECT a FROM one ORDER BY a;
  } db
} {1 {cannot start a transaction within a transaction}}
do_test avtrans-4.7 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 4 5 10}}
do_test avtrans-4.8 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3 4}}
do_test avtrans-4.9 {
  set v [catch {execsql {
    END TRANSACTION;
    SELECT a FROM two ORDER BY a;
  } db} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test avtrans-4.10 {
  set v [catch {execsql {
    SELECT a FROM two ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test avtrans-4.11 {
  set v [catch {execsql {
    SELECT a FROM one ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 2 3 4}}
integrity_check avtrans-4.12
do_test avtrans-4.98 {
  altdb close
  execsql {
    DROP TABLE one;
    DROP TABLE two;
  }
} {}
integrity_check avtrans-4.99

# Check out the commit/rollback behavior of the database
#
do_test avtrans-5.1 {
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test avtrans-5.2 {
  execsql {BEGIN TRANSACTION}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test avtrans-5.3 {
  execsql {CREATE TABLE one(a text, b int)}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {one}
do_test avtrans-5.4 {
  execsql {SELECT a,b FROM one ORDER BY b}
} {}
do_test avtrans-5.5 {
  execsql {INSERT INTO one(a,b) VALUES('hello', 1)}
  execsql {SELECT a,b FROM one ORDER BY b}
} {hello 1}
do_test avtrans-5.6 {
  execsql {ROLLBACK}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test avtrans-5.7 {
  set v [catch {
    execsql {SELECT a,b FROM one ORDER BY b}
  } msg]
  lappend v $msg
} {1 {no such table: one}}

# Test commits and rollbacks of table CREATE TABLEs, CREATE INDEXs
# DROP TABLEs and DROP INDEXs
#
do_test avtrans-5.8 {
  execsql {
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name
  }
} {}
do_test avtrans-5.9 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE t1(a int, b int, c int);
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {t1}
do_test avtrans-5.10 {
  execsql {
    CREATE INDEX i1 ON t1(a);
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test avtrans-5.11 {
  execsql {
    COMMIT;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test avtrans-5.12 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE t2(a int, b int, c int);
    CREATE INDEX i2a ON t2(a);
    CREATE INDEX i2b ON t2(b);
    DROP TABLE t1;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2a i2b t2}
do_test avtrans-5.13 {
  execsql {
    ROLLBACK;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test avtrans-5.14 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {t1}
do_test avtrans-5.15 {
  execsql {
    ROLLBACK;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test avtrans-5.16 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    CREATE TABLE t2(x int, y int, z int);
    CREATE INDEX i2x ON t2(x);
    CREATE INDEX i2y ON t2(y);
    INSERT INTO t2 VALUES(1,2,3);
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2x i2y t1 t2}
do_test avtrans-5.17 {
  execsql {
    COMMIT;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2x i2y t1 t2}
do_test avtrans-5.18 {
  execsql {
    SELECT * FROM t2;
  }
} {1 2 3}
do_test avtrans-5.19 {
  execsql {
    SELECT x FROM t2 WHERE y=2;
  }
} {1}
do_test avtrans-5.20 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    DROP TABLE t2;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {}
do_test avtrans-5.21 {
  set r [catch {execsql {
    SELECT * FROM t2
  }} msg]
  lappend r $msg
} {1 {no such table: t2}}
do_test avtrans-5.22 {
  execsql {
    ROLLBACK;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2x i2y t1 t2}
do_test avtrans-5.23 {
  execsql {
    SELECT * FROM t2;
  }
} {1 2 3}
integrity_check avtrans-5.23


# Try to DROP and CREATE tables and indices with the same name
# within a transaction.  Make sure ROLLBACK works.
#
do_test avtrans-6.1 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p,q,r);
    ROLLBACK;
    SELECT * FROM t1;
  }
} {a 1 b 2 c 3}
do_test avtrans-6.2 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p,q,r);
    COMMIT;
    SELECT * FROM t1;
  }
} {}
do_test avtrans-6.3 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test avtrans-6.4 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test avtrans-6.5 {
  execsql2 {
    ROLLBACK;
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test avtrans-6.6 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test avtrans-6.7 {
  catchsql {
    COMMIT;
    SELECT * FROM t1;
  }
} {1 {no such table: t1}}

# Repeat on a table with an automatically generated index.
#
do_test avtrans-6.10 {
  execsql2 {
    CREATE TABLE t1(a unique,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p unique,q,r);
    ROLLBACK;
    SELECT * FROM t1;
  }
} {a 1 b 2 c 3}
do_test avtrans-6.11 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p unique,q,r);
    COMMIT;
    SELECT * FROM t1;
  }
} {}
do_test avtrans-6.12 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test avtrans-6.13 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a unique,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test avtrans-6.14 {
  execsql2 {
    ROLLBACK;
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test avtrans-6.15 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a unique,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test avtrans-6.16 {
  catchsql {
    COMMIT;
    SELECT * FROM t1;
  }
} {1 {no such table: t1}}

do_test avtrans-6.20 {
  execsql {
    CREATE TABLE t1(a integer primary key,b,c);
    INSERT INTO t1 VALUES(1,-2,-3);
    INSERT INTO t1 VALUES(4,-5,-6);
    SELECT * FROM t1;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.21 {
  execsql {
    CREATE INDEX i1 ON t1(b);
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.22 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    SELECT * FROM t1 WHERE b<1;
    ROLLBACK;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.23 {
  execsql {
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.24 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}

do_test avtrans-6.25 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    CREATE INDEX i1 ON t1(c);
    SELECT * FROM t1 WHERE b<1;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.26 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.27 {
  execsql {
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.28 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {1 -2 -3 4 -5 -6}

# The following repeats steps 6.20 through 6.28, but puts a "unique"
# constraint the first field of the table in order to generate an
# automatic index.
#
do_test avtrans-6.30 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a int unique,b,c);
    COMMIT;
    INSERT INTO t1 VALUES(1,-2,-3);
    INSERT INTO t1 VALUES(4,-5,-6);
    SELECT * FROM t1 ORDER BY a;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.31 {
  execsql {
    CREATE INDEX i1 ON t1(b);
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.32 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    SELECT * FROM t1 WHERE b<1;
    ROLLBACK;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.33 {
  execsql {
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.34 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}

do_test avtrans-6.35 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    CREATE INDEX i1 ON t1(c);
    SELECT * FROM t1 WHERE b<1;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.36 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.37 {
  execsql {
    DROP INDEX i1;
    SELECT * FROM t1 WHERE c<1;
  }
} {1 -2 -3 4 -5 -6}
do_test avtrans-6.38 {
  execsql {
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test avtrans-6.39 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {1 -2 -3 4 -5 -6}
integrity_check avtrans-6.40

ifcapable !floatingpoint {
  finish_test
  return
}

# Test to make sure rollback restores the database back to its original
# state.
#
do_test avtrans-7.1 {
  execsql {BEGIN}
  for {set i 0} {$i<1000} {incr i} {
    set r1 [expr {rand()}]
    set r2 [expr {rand()}]
    set r3 [expr {rand()}]
    execsql "INSERT INTO t2 VALUES($r1,$r2,$r3)"
  }
  execsql {COMMIT}
  set ::checksum [execsql {SELECT md5sum(x,y,z) FROM t2}]
  set ::checksum2 [
    execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
  ]
  execsql {SELECT count(*) FROM t2}
} {1001}
do_test avtrans-7.2 {
  execsql {SELECT md5sum(x,y,z) FROM t2}
} $checksum
do_test avtrans-7.2.1 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
do_test avtrans-7.3 {
  execsql {
    BEGIN;
    DELETE FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test avtrans-7.4 {
  execsql {
    BEGIN;
    INSERT INTO t2 SELECT * FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test avtrans-7.5 {
  execsql {
    BEGIN;
    DELETE FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test avtrans-7.6 {
  execsql {
    BEGIN;
    INSERT INTO t2 SELECT * FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test avtrans-7.7 {
  execsql {
    BEGIN;
    CREATE TABLE t3 AS SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t3;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test avtrans-7.8 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
ifcapable tempdb {
  do_test avtrans-7.9 {
    execsql {
      BEGIN;
      CREATE TEMP TABLE t3 AS SELECT * FROM t2;
      INSERT INTO t2 SELECT * FROM t3;
      ROLLBACK;
      SELECT md5sum(x,y,z) FROM t2;
    }
  } $checksum
}
do_test avtrans-7.10 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
ifcapable tempdb {
  do_test avtrans-7.11 {
    execsql {
      BEGIN;
      CREATE TEMP TABLE t3 AS SELECT * FROM t2;
      INSERT INTO t2 SELECT * FROM t3;
      DROP INDEX i2x;
      DROP INDEX i2y;
      CREATE INDEX i3a ON t3(x);
      ROLLBACK;
      SELECT md5sum(x,y,z) FROM t2;
    }
  } $checksum
}
do_test avtrans-7.12 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
ifcapable tempdb {
  do_test avtrans-7.13 {
    execsql {
      BEGIN;
      DROP TABLE t2;
      ROLLBACK;
      SELECT md5sum(x,y,z) FROM t2;
    }
  } $checksum
}
do_test avtrans-7.14 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
integrity_check avtrans-7.15

# Arrange for another process to begin modifying the database but abort
# and die in the middle of the modification.  Then have this process read
# the database.  This process should detect the journal file and roll it
# back.  Verify that this happens correctly.
#
set fd [open test.tcl w]
puts $fd {
  sqlite3 db test.db
  db eval {
    PRAGMA default_cache_size=20;
    BEGIN;
    CREATE TABLE t3 AS SELECT * FROM t2;
    DELETE FROM t2;
  }
  sqlite_abort
}
close $fd
do_test avtrans-8.1 {
  catch {exec [info nameofexec] test.tcl}
  execsql {SELECT md5sum(x,y,z) FROM t2}
} $checksum
do_test avtrans-8.2 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
integrity_check avtrans-8.3

# In the following sequence of tests, compute the MD5 sum of the content
# of a table, make lots of modifications to that table, then do a rollback.
# Verify that after the rollback, the MD5 checksum is unchanged.
#
do_test avtrans-9.1 {
  execsql {
    PRAGMA default_cache_size=10;
  }
  db close
  sqlite3 db test.db
  execsql {
    BEGIN;
    CREATE TABLE t3(x TEXT);
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    COMMIT;
    SELECT count(*) FROM t3;
  }
} {1024}

# The following procedure computes a "signature" for table "t3".  If
# T3 changes in any way, the signature should change.  
#
# This is used to test ROLLBACK.  We gather a signature for t3, then
# make lots of changes to t3, then rollback and take another signature.
# The two signatures should be the same.
#
proc signature {} {
  return [db eval {SELECT count(*), md5sum(x) FROM t3}]
}

# Repeat the following group of tests 20 times for quick testing and
# 40 times for full testing.  Each iteration of the test makes table
# t3 a little larger, and thus takes a little longer, so doing 40 tests
# is more than 2.0 times slower than doing 20 tests.  Considerably more.
#
if {[info exists ISQUICK]} {
  set limit 20
} else {
  set limit 40
}

# Do rollbacks.  Make sure the signature does not change.
#
for {set i 2} {$i<=$limit} {incr i} {
  set ::sig [signature]
  set cnt [lindex $::sig 0]
  if {$i%2==0} {
    execsql {PRAGMA fullfsync=ON}
  } else {
    execsql {PRAGMA fullfsync=OFF}
  }
  set sqlite_sync_count 0
  set sqlite_fullsync_count 0
  do_test avtrans-9.$i.1-$cnt {
     execsql {
       BEGIN;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       ROLLBACK;
     }
     signature
  } $sig
  do_test avtrans-9.$i.2-$cnt {
     execsql {
       BEGIN;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       ROLLBACK;
     }
     signature
  } $sig
  if {$i<$limit} {
    do_test avtrans-9.$i.3-$cnt {
       execsql {
         INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0;
       }
    } {}
    if {$tcl_platform(platform)=="unix"} {
      do_test avtrans-9.$i.4-$cnt {
         expr {$sqlite_sync_count>0}
      } 1
      ifcapable pager_pragmas {
        do_test avtrans-9.$i.5-$cnt {
           expr {$sqlite_fullsync_count>0}
        } [expr {$i%2==0}]
      } else {
        do_test avtrans-9.$i.5-$cnt {
           expr {$sqlite_fullsync_count==0}
        } {1}
      }
    }
  }
  set ::pager_old_format 0
}
integrity_check avtrans-10.1
   
finish_test

Added test/backup.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
# 2009 January 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the sqlite3_backup_XXX API.
#
# $Id: backup.test,v 1.11 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#---------------------------------------------------------------------
# Test organization:
#
# backup-1.*: Warm-body tests.
#
# backup-2.*: Test backup under various conditions. To and from in-memory
#             databases. To and from empty/populated databases. etc.
#
# backup-3.*: Verify that the locking-page (pending byte page) is handled.
#
# backup-4.*: Test various error conditions.
#
# backup-5.*: Test the source database being modified during a backup.
#
# backup-6.*: Test the backup_remaining() and backup_pagecount() APIs.
#
# backup-7.*: Test SQLITE_BUSY and SQLITE_LOCKED errors.
#
# backup-8.*: Test multiple simultaneous backup operations.
#
# backup-9.*: Test that passing a negative argument to backup_step() is
#             interpreted as "copy the whole file".
#

proc data_checksum {db file} { $db one "SELECT md5sum(a, b) FROM ${file}.t1" }
proc test_contents {name db1 file1 db2 file2} {
  $db2 eval {select * from sqlite_master}
  $db1 eval {select * from sqlite_master}
  set checksum [data_checksum $db2 $file2]
  uplevel [list do_test $name [list data_checksum $db1 $file1] $checksum]
}

do_test backup-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a, b);
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 VALUES(2, randstr(1000,1000));
    INSERT INTO t1 VALUES(3, randstr(1000,1000));
    INSERT INTO t1 VALUES(4, randstr(1000,1000));
    INSERT INTO t1 VALUES(5, randstr(1000,1000));
    COMMIT;
  }
} {}

# Sanity check to verify that the [test_contents] proc works.
#
test_contents backup-1.2 db main db main

# Check that it is possible to create and finish backup operations.
#
do_test backup-1.3.1 {
  file delete test2.db
  sqlite3 db2 test2.db
  sqlite3_backup B db2 main db main
} {B}
do_test backup-1.3.2 {
  B finish
} {SQLITE_OK}
do_test backup-1.3.3 {
  info commands B
} {}

# Simplest backup operation. Backup test.db to test2.db. test2.db is 
# initially empty. test.db uses the default page size.
# 
do_test backup-1.4.1 {
  sqlite3_backup B db2 main db main
} {B}
do_test backup-1.4.2 {
  B step 200
} {SQLITE_DONE}
do_test backup-1.4.3 {
  B finish
} {SQLITE_OK}
do_test backup-1.4.4 {
  info commands B
} {}
test_contents backup-1.4.5 db2 main db main
db close
db2 close
#
# End of backup-1.* tests.
#---------------------------------------------------------------------


#---------------------------------------------------------------------
# The following tests, backup-2.*, are based on the following procedure:
#
#   1) Populate the source database.
#   2) Populate the destination database.
#   3) Run the backup to completion. (backup-2.*.1)
#   4) Integrity check the destination db. (backup-2.*.2)
#   5) Check that the contents of the destination db is the same as that
#      of the source db. (backup-2.*.3)
# 
# The test is run with all possible combinations of the following
# input parameters, except that if the destination is an in-memory
# database, the only page size tested is 1024 bytes (the same as the
# source page-size).
#
#   * Source database is an in-memory database, OR
#   * Source database is a file-backed database.
#
#   * Target database is an in-memory database, OR
#   * Target database is a file-backed database.
#
#   * Destination database is a main file, OR
#   * Destination database is an attached file, OR
#   * Destination database is a temp database.
#
#   * Target database is empty (zero bytes), OR
#   * Target database is larger than the source, OR
#   * Target database is smaller than the source.
#
#   * Target database page-size is the same as the source, OR
#   * Target database page-size is larger than the source, OR
#   * Target database page-size is smaller than the source.
#
#   * Each call to step copies a single page, OR
#   * A single call to step copies the entire source database.
#
set iTest 1
foreach zSrcFile {test.db :memory:} {
foreach zDestFile {test2.db :memory:} {
foreach zOpenScript [list {
  sqlite3 db $zSrcFile
  sqlite3 db2 $zSrcFile
  db2 eval "ATTACH '$zDestFile' AS bak"
  set db_dest db2
  set file_dest bak
} {
  sqlite3 db $zSrcFile
  sqlite3 db2 $zDestFile
  set db_dest db2
  set file_dest main
} {
  sqlite3 db $zSrcFile
  sqlite3 db2 $zDestFile
  set db_dest db2
  set file_dest temp
}] {
foreach rows_dest {0 3 10} {
foreach pgsz_dest {512 1024 2048} {
foreach nPagePerStep {1 200} {

  # Open the databases.
  catch { file delete test.db }
  catch { file delete test2.db }
  eval $zOpenScript

  # Set to true if copying to an in-memory destination. Copying to an 
  # in-memory destination is only possible if the initial destination
  # page size is the same as the source page size (in this case 1024 bytes).
  #
  set isMemDest [expr {
    $zDestFile eq ":memory:" || $file_dest eq "temp" && $TEMP_STORE==3
  }]

  if { $isMemDest==0 || $pgsz_dest == 1024 } {
    if 0 {
      puts -nonewline "Test $iTest: src=$zSrcFile dest=$zDestFile"
      puts -nonewline " (as $db_dest.$file_dest)"
      puts -nonewline " rows_dest=$rows_dest pgsz_dest=$pgsz_dest"
      puts ""
    }

    # Set up the content of the source database.
    execsql {
      PRAGMA page_size = 1024;
      BEGIN;
      CREATE TABLE t1(a, b);
      CREATE INDEX i1 ON t1(a, b);
      INSERT INTO t1 VALUES(1, randstr(1000,1000));
      INSERT INTO t1 VALUES(2, randstr(1000,1000));
      INSERT INTO t1 VALUES(3, randstr(1000,1000));
      INSERT INTO t1 VALUES(4, randstr(1000,1000));
      INSERT INTO t1 VALUES(5, randstr(1000,1000));
      COMMIT;
    }
    
    

    # Set up the content of the target database.
    execsql "PRAGMA ${file_dest}.page_size = ${pgsz_dest}" $db_dest
    if {$rows_dest != 0} {
      execsql "
        BEGIN; 
        CREATE TABLE ${file_dest}.t1(a, b);
        CREATE INDEX ${file_dest}.i1 ON t1(a, b);
      " $db_dest
      for {set ii 0} {$ii < $rows_dest} {incr ii} {
        execsql "
          INSERT INTO ${file_dest}.t1 VALUES(1, randstr(1000,1000))
        " $db_dest
      }
    }
  
    # Backup the source database.
    do_test backup-2.$iTest.1 {
      sqlite3_backup B $db_dest $file_dest db main
      while {[B step $nPagePerStep]=="SQLITE_OK"} {}
      B finish
    } {SQLITE_OK}
    
    # Run integrity check on the backup.
    do_test backup-2.$iTest.2 {
      execsql "PRAGMA ${file_dest}.integrity_check" $db_dest
    } {ok}
  
    test_contents backup-2.$iTest.3 db main $db_dest $file_dest
  
  }

  db close
  catch {db2 close}
  incr iTest

} } } } } }
#
# End of backup-2.* tests.
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# These tests, backup-3.*, ensure that nothing goes wrong if either 
# the source or destination database are large enough to include the
# the locking-page (the page that contains the range of bytes that
# the locks are applied to). These tests assume that the pending
# byte is at offset 0x00010000 (64KB offset), as set by tester.tcl, 
# not at the 1GB offset as it usually is.
#
# The test procedure is as follows (same procedure as used for 
# the backup-2.* tests):
#
#   1) Populate the source database.
#   2) Populate the destination database.
#   3) Run the backup to completion. (backup-3.*.1)
#   4) Integrity check the destination db. (backup-3.*.2)
#   5) Check that the contents of the destination db is the same as that
#      of the source db. (backup-3.*.3)
#
# The test procedure is run with the following parameters varied: 
#
#   * Source database includes pending-byte page.
#   * Source database does not include pending-byte page.
#
#   * Target database includes pending-byte page.
#   * Target database does not include pending-byte page.
#
#   * Target database page-size is the same as the source, OR
#   * Target database page-size is larger than the source, OR
#   * Target database page-size is smaller than the source.
#
set iTest 1
foreach nSrcPg {10 64 65 66 100} {
foreach nDestRow {10 100} {
foreach nDestPgsz {512 1024 2048 4096} {

  catch { file delete test.db }
  catch { file delete test2.db }
  sqlite3 db test.db
  sqlite3 db2 test2.db

  # Set up the content of the two databases.
  #
  execsql { PRAGMA page_size = 1024 }
  execsql "PRAGMA page_size = $nDestPgsz" db2
  foreach db {db db2} {
    execsql {
      BEGIN; 
      CREATE TABLE t1(a, b);
      CREATE INDEX i1 ON t1(a, b);
      COMMIT;
    } $db
  }
  while {[file size test.db]/1024 < $nSrcPg} {
    execsql { INSERT INTO t1 VALUES($ii, randstr(200,200)) }
  }

  for {set ii 0} {$ii < $nDestRow} {incr ii} {
    execsql { INSERT INTO t1 VALUES($ii, randstr(1000,1000)) } db2
  }

  # Backup the source database.
  do_test backup-3.$iTest.1 {
    sqlite3_backup B db main db2 main
    while {[B step 10]=="SQLITE_OK"} {}
    B finish
  } {SQLITE_OK}
    
  # Run integrity check on the backup.
  do_test backup-3.$iTest.2 {
    execsql "PRAGMA integrity_check" db2
  } {ok}
  
  test_contents backup-3.$iTest.3 db main db2 main

  db close
  db2 close
  incr iTest
}
}
}

#--------------------------------------------------------------------
do_test backup-3.$iTest.1 {
  catch { file delete -force test.db }
  catch { file delete -force test2.db }
  sqlite3 db test.db
  set iTab 1

  db eval { PRAGMA page_size = 512 }
  while {[file size test.db] <= $::sqlite_pending_byte} {
    db eval "CREATE TABLE t${iTab}(a, b, c)"
    incr iTab
  }

  sqlite3 db2 test2.db
  db2 eval { PRAGMA page_size = 4096 }
  while {[file size test2.db] < $::sqlite_pending_byte} {
    db2 eval "CREATE TABLE t${iTab}(a, b, c)"
    incr iTab
  }

  sqlite3_backup B db2 main db main
  B step -1
} {SQLITE_DONE}

do_test backup-3.$iTest.2 {
  B finish
} {SQLITE_OK}

#
# End of backup-3.* tests.
#---------------------------------------------------------------------


#---------------------------------------------------------------------
# The following tests, backup-4.*, test various error conditions:
# 
# backup-4.1.*: Test invalid database names.
#
# backup-4.2.*: Test that the source database cannot be detached while 
#               a backup is in progress.
#
# backup-4.3.*: Test that the source database handle cannot be closed
#               while a backup is in progress.
#
# backup-4.4.*: Test an attempt to specify the same handle for the
#               source and destination databases.
#
# backup-4.5.*: Test that an in-memory destination with a different
#               page-size to the source database is an error.
#
sqlite3 db test.db
sqlite3 db2 test2.db

do_test backup-4.1.1 {
  catch { sqlite3_backup B db aux db2 main }
} {1}
do_test backup-4.1.2 {
  sqlite3_errmsg db
} {unknown database aux}
do_test backup-4.1.3 {
  catch { sqlite3_backup B db main db2 aux }
} {1}
do_test backup-4.1.4 {
  sqlite3_errmsg db
} {unknown database aux}

do_test backup-4.2.1 {
  catch { file delete -force test3.db }
  catch { file delete -force test4.db }
  execsql { 
    ATTACH 'test3.db' AS aux1;
    CREATE TABLE aux1.t1(a, b);
  }
  execsql { 
    ATTACH 'test4.db' AS aux2;
    CREATE TABLE aux2.t2(a, b);
  } db2
  sqlite3_backup B db aux1 db2 aux2
} {B}
do_test backup-4.2.2 {
  catchsql { DETACH aux2 } db2
} {1 {database aux2 is locked}}
do_test backup-4.2.3 {
  B step 50
} {SQLITE_DONE}
do_test backup-4.2.4 {
  B finish
} {SQLITE_OK}

do_test backup-4.3.1 {
  sqlite3_backup B db aux1 db2 aux2
} {B}
do_test backup-4.3.2 {
  db2 cache flush
  sqlite3_close db2
} {SQLITE_BUSY}
do_test backup-4.3.3 {
  sqlite3_errmsg db2
} {unable to close due to unfinished backup operation}
do_test backup-4.3.4 {
  B step 50
} {SQLITE_DONE}
do_test backup-4.3.5 {
  B finish
} {SQLITE_OK}

do_test backup-4.4.1 {
  set rc [catch {sqlite3_backup B db main db aux1}]
  list $rc [sqlite3_errcode db] [sqlite3_errmsg db]
} {1 SQLITE_ERROR {source and destination must be distinct}}
db close
db2 close

do_test backup-4.5.1 {
  catch { file delete -force test.db }
  sqlite3 db test.db
  sqlite3 db2 :memory:
  execsql {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 2);
  }
  execsql {
    PRAGMA page_size = 4096;
    CREATE TABLE t2(a, b);
    INSERT INTO t2 VALUES(3, 4);
  } db2
  sqlite3_backup B db2 main db main
} {B}
do_test backup-4.5.2 {
  B step 5000
} {SQLITE_READONLY}
do_test backup-4.5.3 {
  B finish
} {SQLITE_READONLY}

db close
db2 close
#
# End of backup-5.* tests.
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# The following tests, backup-5.*, test that the backup works properly
# when the source database is modified during the backup. Test cases
# are organized as follows:
#
# backup-5.x.1.*: Nothing special. Modify the database mid-backup.
#
# backup-5.x.2.*: Modify the database mid-backup so that one or more
#                 pages are written out due to cache stress. Then 
#                 rollback the transaction.
#
# backup-5.x.3.*: Database is vacuumed.
#
# backup-5.x.4.*: Database is vacuumed and the page-size modified.
#
# backup-5.x.5.*: Database is shrunk via incr-vacuum.
#
# Each test is run three times, in the following configurations:
#
#   1) Backing up file-to-file. The writer writes via an external pager.
#   2) Backing up file-to-file. The writer writes via the same pager as
#      is used by the backup operation.
#   3) Backing up memory-to-file. 
#
set iTest 0
foreach {writer file} {db test.db db3 test.db db :memory:} {
  incr iTest
  catch { file delete bak.db }
  sqlite3 db2 bak.db
  catch { file delete $file }
  sqlite3 db $file
  sqlite3 db3 $file

  do_test backup-5.$iTest.1.1 {
    execsql {
      BEGIN;
      CREATE TABLE t1(a, b);
      CREATE INDEX i1 ON t1(a, b);
      INSERT INTO t1 VALUES(1, randstr(1000,1000));
      INSERT INTO t1 VALUES(2, randstr(1000,1000));
      INSERT INTO t1 VALUES(3, randstr(1000,1000));
      INSERT INTO t1 VALUES(4, randstr(1000,1000));
      INSERT INTO t1 VALUES(5, randstr(1000,1000));
      COMMIT;
    }
    expr {[execsql {PRAGMA page_count}] > 10}
  } {1}
  do_test backup-5.$iTest.1.2 {
    sqlite3_backup B db2 main db main
    B step 5
  } {SQLITE_OK}
  do_test backup-5.$iTest.1.3 {
    execsql { UPDATE t1 SET a = a + 1 } $writer
    B step 50
  } {SQLITE_DONE}
  do_test backup-5.$iTest.1.4 {
    B finish
  } {SQLITE_OK} 
  integrity_check backup-5.$iTest.1.5 db2
  test_contents backup-5.$iTest.1.6 db main db2 main

  do_test backup-5.$iTest.2.1 {
    execsql {
      PRAGMA cache_size = 10;
      BEGIN;
      INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1;
      INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1;
      INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1;
      INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1;
      COMMIT;
    }
  } {}
  do_test backup-5.$iTest.2.2 {
    sqlite3_backup B db2 main db main
    B step 50
  } {SQLITE_OK}
  do_test backup-5.$iTest.2.3 {
    execsql { 
      BEGIN;
      UPDATE t1 SET a = a + 1;
      ROLLBACK;
    } $writer
    B step 5000
  } {SQLITE_DONE}
  do_test backup-5.$iTest.2.4 {
    B finish
  } {SQLITE_OK} 
  integrity_check backup-5.$iTest.2.5 db2
  test_contents backup-5.$iTest.2.6 db main db2 main

  do_test backup-5.$iTest.3.1 {
    execsql { UPDATE t1 SET b = randstr(1000,1000) }
  } {}
  do_test backup-5.$iTest.3.2 {
    sqlite3_backup B db2 main db main
    B step 50
  } {SQLITE_OK}
  do_test backup-5.$iTest.3.3 {
    execsql { VACUUM } $writer
    B step 5000
  } {SQLITE_DONE}
  do_test backup-5.$iTest.3.4 {
    B finish
  } {SQLITE_OK} 
  integrity_check backup-5.$iTest.3.5 db2
  test_contents backup-5.$iTest.3.6 db main db2 main

  do_test backup-5.$iTest.4.1 {
    execsql { UPDATE t1 SET b = randstr(1000,1000) }
  } {}
  do_test backup-5.$iTest.4.2 {
    sqlite3_backup B db2 main db main
    B step 50
  } {SQLITE_OK}
  do_test backup-5.$iTest.4.3 {
    execsql { 
      PRAGMA page_size = 2048;
      VACUUM;
    } $writer
    B step 5000
  } {SQLITE_DONE}
  do_test backup-5.$iTest.4.4 {
    B finish
  } {SQLITE_OK} 
  integrity_check backup-5.$iTest.4.5 db2
  test_contents backup-5.$iTest.4.6 db main db2 main

  catch {db close}
  catch {db2 close}
  catch {db3 close}
  catch { file delete bak.db }
  sqlite3 db2 bak.db
  catch { file delete $file }
  sqlite3 db $file
  sqlite3 db3 $file
  do_test backup-5.$iTest.5.1 {
    execsql {
      PRAGMA auto_vacuum = incremental;
      BEGIN;
      CREATE TABLE t1(a, b);
      CREATE INDEX i1 ON t1(a, b);
      INSERT INTO t1 VALUES(1, randstr(1000,1000));
      INSERT INTO t1 VALUES(2, randstr(1000,1000));
      INSERT INTO t1 VALUES(3, randstr(1000,1000));
      INSERT INTO t1 VALUES(4, randstr(1000,1000));
      INSERT INTO t1 VALUES(5, randstr(1000,1000));
      COMMIT;
    }
  } {}
  do_test backup-5.$iTest.5.2 {
    sqlite3_backup B db2 main db main
    B step 8
  } {SQLITE_OK}
  do_test backup-5.$iTest.5.3 {
    execsql { 
      DELETE FROM t1;
      PRAGMA incremental_vacuum;
    } $writer
    B step 50
  } {SQLITE_DONE}
  do_test backup-5.$iTest.5.4 {
    B finish
  } {SQLITE_OK} 
  integrity_check backup-5.$iTest.5.5 db2
  test_contents backup-5.$iTest.5.6 db main db2 main
  catch {db close}
  catch {db2 close}
  catch {db3 close}
}
#
# End of backup-5.* tests.
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Test the sqlite3_backup_remaining() and backup_pagecount() APIs.
#
do_test backup-6.1 {
  catch { file delete -force test.db }
  catch { file delete -force test2.db }
  sqlite3 db test.db
  sqlite3 db2 test2.db
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a, b);
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 VALUES(2, randstr(1000,1000));
    INSERT INTO t1 VALUES(3, randstr(1000,1000));
    INSERT INTO t1 VALUES(4, randstr(1000,1000));
    INSERT INTO t1 VALUES(5, randstr(1000,1000));
    COMMIT;
  }
} {}
do_test backup-6.2 {
  set nTotal [expr {[file size test.db]/1024}]
  sqlite3_backup B db2 main db main
  B step 1
} {SQLITE_OK}
do_test backup-6.3 {
  B pagecount
} $nTotal
do_test backup-6.4 {
  B remaining
} [expr $nTotal-1]
do_test backup-6.5 {
  B step 5
  list [B remaining] [B pagecount]
} [list [expr $nTotal-6] $nTotal]
do_test backup-6.6 {
  execsql { CREATE TABLE t2(a PRIMARY KEY, b) }
  B step 1
  list [B remaining] [B pagecount]
} [list [expr $nTotal-5] [expr $nTotal+2]]

do_test backup-6.X {
  B finish
} {SQLITE_OK}

catch {db close}
catch {db2 close}

#---------------------------------------------------------------------
# Test cases backup-7.* test that SQLITE_BUSY and SQLITE_LOCKED errors
# are returned correctly:
#
# backup-7.1.*: Source database is externally locked (return SQLITE_BUSY).
#
# backup-7.2.*: Attempt to step the backup process while a 
#               write-transaction is underway on the source pager (return
#               SQLITE_LOCKED).
#
# backup-7.3.*: Destination database is externally locked (return SQLITE_BUSY).
#
do_test backup-7.0 {
  catch { file delete -force test.db }
  catch { file delete -force test2.db }
  sqlite3 db2 test2.db
  sqlite3 db test.db
  execsql {
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a, b);
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 SELECT a+ 1, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 2, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 4, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 8, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+16, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+32, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+64, randstr(1000,1000) FROM t1;
  }
} {}

do_test backup-7.1.1 {
  sqlite3_backup B db2 main db main
  B step 5
} {SQLITE_OK}
do_test backup-7.1.2 {
  sqlite3 db3 test.db
  execsql { BEGIN EXCLUSIVE } db3
  B step 5
} {SQLITE_BUSY}
do_test backup-7.1.3 {
  execsql { ROLLBACK } db3
  B step 5
} {SQLITE_OK}
do_test backup-7.2.1 {
  execsql { 
    BEGIN;
    INSERT INTO t1 VALUES(1, 4);
  }
} {}
do_test backup-7.2.2 {
  B step 5000
} {SQLITE_BUSY}
do_test backup-7.2.3 {
  execsql { ROLLBACK }
  B step 5000
} {SQLITE_DONE}
do_test backup-7.2.4 {
  B finish
} {SQLITE_OK}
test_contents backup-7.2.5 db main db2 main
integrity_check backup-7.3.6 db2

do_test backup-7.3.1 {
  db2 close
  db3 close
  file delete -force test2.db
  sqlite3 db2 test2.db
  sqlite3 db3 test2.db

  sqlite3_backup B db2 main db main
  execsql { BEGIN ; CREATE TABLE t2(a, b); } db3

  B step 5
} {SQLITE_BUSY}
do_test backup-7.3.2 {
  execsql { COMMIT } db3
  B step 5000
} {SQLITE_DONE}
do_test backup-7.3.3 {
  B finish
} {SQLITE_OK}
test_contents backup-7.3.4 db main db2 main
integrity_check backup-7.3.5 db2
catch { db2 close }
catch { db3 close }

#-----------------------------------------------------------------------
# The following tests, backup-8.*, test attaching multiple backup
# processes to the same source database. Also, reading from the source
# database while a read transaction is active.
#
# These tests reuse the database "test.db" left over from backup-7.*.
#
do_test backup-8.1 {
  catch { file delete -force test2.db }
  catch { file delete -force test3.db }
  sqlite3 db2 test2.db
  sqlite3 db3 test3.db

  sqlite3_backup B2 db2 main db main
  sqlite3_backup B3 db3 main db main
  list [B2 finish] [B3 finish]
} {SQLITE_OK SQLITE_OK}
do_test backup-8.2 {
  sqlite3_backup B3 db3 main db main
  sqlite3_backup B2 db2 main db main
  list [B2 finish] [B3 finish]
} {SQLITE_OK SQLITE_OK}
do_test backup-8.3 {
  sqlite3_backup B2 db2 main db main
  sqlite3_backup B3 db3 main db main
  B2 step 5
} {SQLITE_OK}
do_test backup-8.4 {
  execsql {
    BEGIN;
    SELECT * FROM sqlite_master;
  }
  B3 step 5
} {SQLITE_OK}
do_test backup-8.5 {
  list [B3 step 5000] [B3 finish]
} {SQLITE_DONE SQLITE_OK}
do_test backup-8.6 {
  list [B2 step 5000] [B2 finish]
} {SQLITE_DONE SQLITE_OK}
test_contents backup-8.7 db main db2 main
test_contents backup-8.8 db main db3 main
do_test backup-8.9 {
  execsql { PRAGMA lock_status }
} {main shared temp closed}
do_test backup-8.10 {
  execsql COMMIT
} {}
catch { db2 close }
catch { db3 close }

#-----------------------------------------------------------------------
# The following tests, backup-9.*, test that:
# 
#   * Passing 0 as an argument to sqlite3_backup_step() means no pages
#     are backed up (backup-9.1.*), and 
#   * Passing a negative value as an argument to sqlite3_backup_step() means 
#     all pages are backed up (backup-9.2.*).
#
# These tests reuse the database "test.db" left over from backup-7.*.
# 
do_test backup-9.1.1 {
  sqlite3 db2 test2.db
  sqlite3_backup B db2 main db main
  B step 1
} {SQLITE_OK}
do_test backup-9.1.2 {
  set nRemaining [B remaining]
  expr {$nRemaining>100}
} {1}
do_test backup-9.1.3 {
  B step 0
} {SQLITE_OK}
do_test backup-9.1.4 {
  B remaining
} $nRemaining

do_test backup-9.2.1 {
  B step -1
} {SQLITE_DONE}
do_test backup-9.2.2 {
  B remaining
} {0}
do_test backup-9.2.3 {
  B finish
} {SQLITE_OK}
catch {db2 close}

ifcapable memorymanage {
  db close
  file delete -force test.db
  file delete -force bak.db

  sqlite3 db test.db
  sqlite3 db2 test.db
  sqlite3 db3 bak.db

  do_test backup-10.1.1 {
    execsql {
      BEGIN;
      CREATE TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, randstr(1000,1000));
      INSERT INTO t1 VALUES(2, randstr(1000,1000));
      INSERT INTO t1 VALUES(3, randstr(1000,1000));
      INSERT INTO t1 VALUES(4, randstr(1000,1000));
      INSERT INTO t1 VALUES(5, randstr(1000,1000));
      CREATE INDEX i1 ON t1(a, b);
      COMMIT;
    }
  } {}
  do_test backup-10.1.2 {
    sqlite3_backup B db3 main db2 main
    B step 5
  } {SQLITE_OK}
  do_test backup-10.1.3 {
    execsql {
      UPDATE t1 SET b = randstr(500,500);
    }
  } {}
  sqlite3_release_memory [expr 1024*1024]
  do_test backup-10.1.3 {
    B step 50
  } {SQLITE_DONE}
  do_test backup-10.1.4 {
    B finish
  } {SQLITE_OK}
  do_test backup-10.1.5 {
    execsql { PRAGMA integrity_check } db3
  } {ok}

  db2 close
  db3 close
}

finish_test

Added test/backup2.test.























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# 2009 February 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the "backup" and "restore" methods
# of the TCL interface - methods which are based on the
# sqlite3_backup_XXX API.
#
# $Id: backup2.test,v 1.4 2009/04/07 14:14:23 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !trigger||!view { finish_test ; return }

# Fill a database with test data.
#
do_test backup2-1 {
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(randstr(8000,8000));
    INSERT INTO t1 VALUES(randstr(8000,8000));
    INSERT INTO t1 VALUES(randstr(8000,8000));
    INSERT INTO t1 VALUES(randstr(8000,8000));
    INSERT INTO t1 VALUES(randstr(8000,8000));
    CREATE VIEW v1 AS SELECT substr(x,10,10) FROM t1;
    CREATE TABLE t2(a,b);
    INSERT INTO t2 VALUES(1,2);
    INSERT INTO t2 VALUES(2,4);
    INSERT INTO t2 SELECT a+2, (a+2)*2 FROM t2;
    INSERT INTO t2 SELECT a+4, (a+4)*2 FROM t2;
    INSERT INTO t2 SELECT a+8, (a+8)*2 FROM t2;
    INSERT INTO t2 SELECT a+16, (a+16)*2 FROM t2;
    INSERT INTO t2 SELECT a+32, (a+32)*2 FROM t2;
    INSERT INTO t2 SELECT a+64, (a+64)*2 FROM t2;
    INSERT INTO t2 SELECT a+128, (a+128)*2 FROM t2;
    CREATE INDEX t2i1 ON t2(a,b);
    CREATE TRIGGER r1 AFTER INSERT ON t2 BEGIN
      SELECT 'hello';
    END;
    ANALYZE;
    PRAGMA integrity_check;
  }
} {ok}

# Remember a check-sum on the database file.
#
unset -nocomplain cksum
set cksum [dbcksum db main]

# Make a backup of the test data.  Verify that the backup copy
# is identical to the original.
#
do_test backup2-2 {
  file delete -force bu1.db
  db backup bu1.db
  sqlite3 db2 bu1.db
  dbcksum db2 main
} $cksum

# Delete the original.  Restore from backup.  Verify the content is
# unchanged.
#
do_test backup2-3.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  db2 eval {BEGIN EXCLUSIVE}
  set rc [catch {db restore bu1.db} res]
  lappend rc $res
  db2 eval {ROLLBACK}
  set rc
} {1 {restore failed: source database busy}}
do_test backup2-3.2 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  db restore bu1.db
  dbcksum db main
} $cksum

# Use alternative databases - other than "main".
#
do_test backup2-4 {
  db restore temp bu1.db
  dbcksum db temp
} $cksum
do_test backup2-5 {
  db2 close
  file delete -force bu1.db bu2.db
  db backup temp bu2.db
  sqlite3 db2 bu2.db
  dbcksum db2 main
} $cksum

# Try to backup to a readonly file.
#
do_test backup2-6 {
  db2 close
  catch {file attributes bu2.db -permissions r--------}
  catch {file attributes bu2.db -readonly 1}
  set rc [catch {db backup temp bu2.db} res]
  lappend rc $res
} {1 {backup failed: attempt to write a readonly database}}

# Try to backup to something that is not a database file.
#
do_test backup2-7 {
  catch {file attributes bu2.db -readonly 0}
  catch {file attributes bu2.db -permissions rw-------}
  set out [open bu2.db w]
  puts $out "This is not a valid database file"
  close $out
  set rc [catch {db backup temp bu2.db} res]
  lappend rc $res
} {1 {backup failed: file is encrypted or is not a database}}

# Try to backup database that does not exist
#
do_test backup2-8 {
  file delete -force bu1.db
  set rc [catch {db backup aux1 bu1.db} res]
  lappend rc $res
} {1 {backup failed: unknown database aux1}}

# Invalid syntax on the backup method
#
do_test backup2-9 {
  set rc [catch {db backup} res]
  lappend rc $res
} {1 {wrong # args: should be "db backup ?DATABASE? FILENAME"}}

# Try to restore from an unreadable file.
#
if {$tcl_platform(platform)=="windows"} {
  do_test backup2-10 {
    file delete -force bu3.db
    file mkdir bu3.db
    set rc [catch {db restore temp bu3.db} res]
    lappend rc $res
  } {1 {cannot open source database: unable to open database file}}
}
if {$tcl_platform(platform)!="windows"} {
  do_test backup2-10 {
    file delete -force bu3.db
    file mkdir bu3.db
    set rc [catch {db restore temp bu3.db} res]
    lappend rc $res
  } {1 {cannot open source database: disk I/O error}}
}

# Try to restore from something that is not a database file.
#
do_test backup2-11 {
  set rc [catch {db restore temp bu2.db} res]
  lappend rc $res
} {1 {restore failed: file is encrypted or is not a database}}

# Try to restore a database that does not exist
#
do_test backup2-12 {
  set rc [catch {db restore aux1 bu2.db} res]
  lappend rc $res
} {1 {restore failed: unknown database aux1}}
do_test backup2-13 {
  file delete -force bu4.db
  set rc [catch {db restore bu4.db} res]
  lappend rc $res
} {1 {cannot open source database: unable to open database file}}

# Invalid syntax on the restore method
#
do_test backup2-14 {
  set rc [catch {db restore} res]
  lappend rc $res
} {1 {wrong # args: should be "db restore ?DATABASE? FILENAME"}}
 
file delete -force bu1.db bu2.db bu3.db bu4.db

finish_test

Added test/backup_ioerr.test.





























































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# 2009 January 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the handling of IO errors by the
# sqlite3_backup_XXX APIs.
#
# $Id: backup_ioerr.test,v 1.3 2009/04/10 18:41:01 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc data_checksum {db file} { 
  $db one "SELECT md5sum(a, b) FROM ${file}.t1" 
}
proc test_contents {name db1 file1 db2 file2} {
  $db2 eval {select * from sqlite_master}
  $db1 eval {select * from sqlite_master}
  set checksum [data_checksum $db2 $file2]
  uplevel [list do_test $name [list data_checksum $db1 $file1] $checksum]
}

#--------------------------------------------------------------------
# This proc creates a database of approximately 290 pages. Depending
# on whether or not auto-vacuum is configured. Test cases backup_ioerr-1.*
# verify nothing more than this assumption.
#
proc populate_database {db {xtra_large 0}} {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 SELECT a+ 1, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 2, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 4, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 8, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+16, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+32, randstr(1000,1000) FROM t1;
    CREATE INDEX i1 ON t1(b);
    COMMIT;
  } $db
  if {$xtra_large} {
    execsql { INSERT INTO t1 SELECT a+64, randstr(1000,1000) FROM t1 } $db
  }
}
do_test backup_ioerr-1.1 {
  populate_database db
  set nPage [expr {[file size test.db] / 1024}]
  expr {$nPage>130 && $nPage<160}
} {1}
do_test backup_ioerr-1.2 {
  expr {[file size test.db] > $sqlite_pending_byte}
} {1}
do_test backup_ioerr-1.3 {
  db close
  file delete -force test.db
} {}

# Turn off IO error simulation.
#
proc clear_ioerr_simulation {} {
  set ::sqlite_io_error_hit 0
  set ::sqlite_io_error_hardhit 0
  set ::sqlite_io_error_pending 0
  set ::sqlite_io_error_persist 0
}

#--------------------------------------------------------------------
# The following procedure runs with SQLite's IO error simulation 
# enabled.
#
#   1) Start with a reasonably sized database. One that includes the
#      pending-byte (locking) page.
#
#   2) Open a backup process. Set the cache-size for the destination
#      database to 10 pages only.
#
#   3) Step the backup process N times to partially backup the database
#      file. If an IO error is reported, then the backup process is
#      concluded with a call to backup_finish().
#
#      If an IO error occurs, verify that:
#
#      * the call to backup_step() returns an SQLITE_IOERR_XXX error code.
#
#      * after the failed call to backup_step() but before the call to
#        backup_finish() the destination database handle error code and 
#        error message remain unchanged.
#
#      * the call to backup_finish() returns an SQLITE_IOERR_XXX error code.
#
#      * following the call to backup_finish(), the destination database
#        handle has been populated with an error code and error message.
#
#   4) Write to the database via the source database connection. Check 
#      that:
#
#      * If an IO error occurs while writing the source database, the
#        write operation should report an IO error. The backup should 
#        proceed as normal.
#
#      * If an IO error occurs while updating the backup, the write 
#        operation should proceed normally. The error should be reported
#        from the next call to backup_step() (in step 5 of this test
#        procedure).
#
#   5) Step the backup process to finish the backup. If an IO error is 
#      reported, then the backup process is concluded with a call to 
#      backup_finish().
#
#      Test that if an IO error occurs, or if one occured while updating
#      the backup database during step 4, then the conditions listed
#      under step 3 are all true.
#
#   6) Finish the backup process.
#
#   * If the backup succeeds (backup_finish() returns SQLITE_OK), then
#     the contents of the backup database should match that of the
#     source database.
#
#   * If the backup fails (backup_finish() returns other than SQLITE_OK), 
#     then the contents of the backup database should be as they were 
#     before the operation was started.
#
# The following factors are varied:
#
#   * Destination database is initially larger than the source database, OR
#   * Destination database is initially smaller than the source database.
#
#   * IO errors are transient, OR
#   * IO errors are persistent.
#
#   * Destination page-size is smaller than the source.
#   * Destination page-size is the same as the source.
#   * Destination page-size is larger than the source.
#

set iTest 1
foreach bPersist {0 1} {
foreach iDestPagesize {512 1024 4096} {
foreach zSetupBak [list "" {populate_database ddb 1}] {

  incr iTest
  set bStop 0
for {set iError 1} {$bStop == 0} {incr iError} {
  # Disable IO error simulation.
  clear_ioerr_simulation

  catch { ddb close }
  catch { sdb close }
  catch { file delete -force test.db }
  catch { file delete -force bak.db }

  # Open the source and destination databases.
  sqlite3 sdb test.db
  sqlite3 ddb bak.db

  # Step 1: Populate the source and destination databases.
  populate_database sdb
  ddb eval "PRAGMA page_size = $iDestPagesize"
  ddb eval "PRAGMA cache_size = 10"
  eval $zSetupBak

  # Step 2: Open the backup process.
  sqlite3_backup B ddb main sdb main

  # Enable IO error simulation.
  set ::sqlite_io_error_pending $iError
  set ::sqlite_io_error_persist $bPersist

  # Step 3: Partially backup the database. If an IO error occurs, check
  # a few things then skip to the next iteration of the loop.
  #
  set rc [B step 100]
  if {$::sqlite_io_error_hardhit} {

    do_test backup_ioerr-$iTest.$iError.1 {
      string match SQLITE_IOERR* $rc
    } {1}
    do_test backup_ioerr-$iTest.$iError.2 {
      list [sqlite3_errcode ddb] [sqlite3_errmsg ddb]
    } {SQLITE_OK {not an error}}

    set rc [B finish]
    do_test backup_ioerr-$iTest.$iError.3 {
      string match SQLITE_IOERR* $rc
    } {1}

    do_test backup_ioerr-$iTest.$iError.4 {
      sqlite3_errmsg ddb
    } {disk I/O error}

    clear_ioerr_simulation
    sqlite3 ddb bak.db
    integrity_check backup_ioerr-$iTest.$iError.5 ddb

    continue
  }

  # No IO error was encountered during step 3. Check that backup_step()
  # returned SQLITE_OK before proceding.
  do_test backup_ioerr-$iTest.$iError.6 {
    expr {$rc eq "SQLITE_OK"}
  } {1}

  # Step 4: Write to the source database.
  set rc [catchsql { UPDATE t1 SET b = randstr(1000,1000) WHERE a < 50 } sdb]

  if {[lindex $rc 0] && $::sqlite_io_error_persist==0} {
    # The IO error occured while updating the source database. In this
    # case the backup should be able to continue.
    set rc [B step 5000]
    if { $rc != "SQLITE_IOERR_UNLOCK" } {
      do_test backup_ioerr-$iTest.$iError.7 {
        list [B step 5000] [B finish]
      } {SQLITE_DONE SQLITE_OK}

      clear_ioerr_simulation
      test_contents backup_ioerr-$iTest.$iError.8 ddb main sdb main
      integrity_check backup_ioerr-$iTest.$iError.9 ddb
    } else {
      do_test backup_ioerr-$iTest.$iError.10 {
        B finish
      } {SQLITE_IOERR_UNLOCK}
    }

    clear_ioerr_simulation
    sqlite3 ddb bak.db
    integrity_check backup_ioerr-$iTest.$iError.11 ddb

    continue
  }

  # Step 5: Finish the backup operation. If an IO error occurs, check that
  # it is reported correctly and skip to the next iteration of the loop.
  #
  set rc [B step 5000]
  if {$rc != "SQLITE_DONE"} {
    do_test backup_ioerr-$iTest.$iError.12 {
      string match SQLITE_IOERR* $rc
    } {1}
    do_test backup_ioerr-$iTest.$iError.13 {
      list [sqlite3_errcode ddb] [sqlite3_errmsg ddb]
    } {SQLITE_OK {not an error}}

    set rc [B finish]
    do_test backup_ioerr-$iTest.$iError.14 {
      string match SQLITE_IOERR* $rc
    } {1}
    do_test backup_ioerr-$iTest.$iError.15 {
      sqlite3_errmsg ddb
    } {disk I/O error}

    clear_ioerr_simulation
    sqlite3 ddb bak.db
    integrity_check backup_ioerr-$iTest.$iError.16 ddb

    continue
  }

  # The backup was successfully completed.
  #
  do_test backup_ioerr-$iTest.$iError.17 {
    list [set rc] [B finish]
  } {SQLITE_DONE SQLITE_OK}

  clear_ioerr_simulation
  sqlite3 sdb test.db
  sqlite3 ddb bak.db

  test_contents backup_ioerr-$iTest.$iError.18 ddb main sdb main
  integrity_check backup_ioerr-$iTest.$iError.19 ddb

  set bStop [expr $::sqlite_io_error_pending<=0]
}}}}

catch { sdb close }
catch { ddb close }
finish_test

Added test/backup_malloc.test.













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# 2009 January 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the handling of OOM errors by the
# sqlite3_backup_XXX APIs.
#
# $Id: backup_malloc.test,v 1.2 2009/02/04 22:46:47 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

source $testdir/malloc_common.tcl

do_malloc_test backup_malloc-1 -tclprep {
  execsql {
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 SELECT a+ 1, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 2, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 4, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+ 8, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+16, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+32, randstr(1000,1000) FROM t1;
    INSERT INTO t1 SELECT a+64, randstr(1000,1000) FROM t1;
    CREATE INDEX i1 ON t1(b);
    COMMIT;
  }
  sqlite3 db2 test2.db
  execsql { PRAGMA cache_size = 10 } db2
} -tclbody {

  # Create a backup object.
  #
  set rc [catch {sqlite3_backup B db2 main db main}]
  if {$rc && [sqlite3_errcode db2] == "SQLITE_NOMEM"} {
    error "out of memory"
  }

  # Run the backup process some.
  #
  set rc [B step 50]
  if {$rc == "SQLITE_NOMEM" || $rc == "SQLITE_IOERR_NOMEM"} {
    error "out of memory"
  }
  
  # Update the database.
  #
  execsql { UPDATE t1 SET a = a + 1 }
  
  # Finish doing the backup.
  #
  set rc [B step 5000]
  if {$rc == "SQLITE_NOMEM" || $rc == "SQLITE_IOERR_NOMEM"} {
    error "out of memory"
  }
 
  # Finalize the backup.
  B finish
} -cleanup {
  catch { B finish }
}

do_malloc_test backup_malloc-1 -tclprep {
  sqlite3 db2 test2.db
} -tclbody {
  set rc [catch {sqlite3_backup B db2 temp db main}]
  set errcode [sqlite3_errcode db2]
  if {$rc && ($errcode == "SQLITE_NOMEM" || $errcode == "SQLITE_IOERR_NOMEM")} {
    error "out of memory"
  }
} -cleanup {
  catch { B finish }
  db2 close
}

finish_test

Added test/badutf.test.































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# 2007 May 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# This file checks to make sure SQLite is able to gracefully
# handle malformed UTF-8.
#
# $Id: badutf.test,v 1.2 2007/09/12 17:01:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test badutf-1.1 {
  db eval {PRAGMA encoding=UTF8}
  sqlite3_exec db {SELECT hex('%80') AS x}
} {0 {x 80}}
do_test badutf-1.2 {
  sqlite3_exec db {SELECT hex('%81') AS x}
} {0 {x 81}}
do_test badutf-1.3 {
  sqlite3_exec db {SELECT hex('%bf') AS x}
} {0 {x BF}}
do_test badutf-1.4 {
  sqlite3_exec db {SELECT hex('%c0') AS x}
} {0 {x C0}}
do_test badutf-1.5 {
  sqlite3_exec db {SELECT hex('%e0') AS x}
} {0 {x E0}}
do_test badutf-1.6 {
  sqlite3_exec db {SELECT hex('%f0') AS x}
} {0 {x F0}}
do_test badutf-1.7 {
  sqlite3_exec db {SELECT hex('%ff') AS x}
} {0 {x FF}}

sqlite3 db2 {}
ifcapable utf16 {
  do_test badutf-1.10 {
    db2 eval {PRAGMA encoding=UTF16be}
    sqlite3_exec db2 {SELECT hex('%80') AS x}
  } {0 {x 0080}}
  do_test badutf-1.11 {
    sqlite3_exec db2 {SELECT hex('%81') AS x}
  } {0 {x 0081}}
  do_test badutf-1.12 {
    sqlite3_exec db2 {SELECT hex('%bf') AS x}
  } {0 {x 00BF}}
  do_test badutf-1.13 {
    sqlite3_exec db2 {SELECT hex('%c0') AS x}
  } {0 {x FFFD}}
  do_test badutf-1.14 {
    sqlite3_exec db2 {SELECT hex('%c1') AS x}
  } {0 {x FFFD}}
  do_test badutf-1.15 {
    sqlite3_exec db2 {SELECT hex('%c0%bf') AS x}
  } {0 {x FFFD}}
  do_test badutf-1.16 {
    sqlite3_exec db2 {SELECT hex('%c1%bf') AS x}
  } {0 {x FFFD}}
  do_test badutf-1.17 {
    sqlite3_exec db2 {SELECT hex('%c3%bf') AS x}
  } {0 {x 00FF}}
  do_test badutf-1.18 {
    sqlite3_exec db2 {SELECT hex('%e0') AS x}
  } {0 {x FFFD}}
  do_test badutf-1.19 {
    sqlite3_exec db2 {SELECT hex('%f0') AS x}
  } {0 {x FFFD}}
  do_test badutf-1.20 {
    sqlite3_exec db2 {SELECT hex('%ff') AS x}
  } {0 {x FFFD}}
}


ifcapable bloblit {
  do_test badutf-2.1 {
    sqlite3_exec db {SELECT '%80'=CAST(x'80' AS text) AS x}
  } {0 {x 1}}
  do_test badutf-2.2 {
    sqlite3_exec db {SELECT CAST('%80' AS blob)=x'80' AS x}
  } {0 {x 1}}
}

do_test badutf-3.1 {
  sqlite3_exec db {SELECT length('%80') AS x}
} {0 {x 1}}
do_test badutf-3.2 {
  sqlite3_exec db {SELECT length('%61%62%63') AS x}
} {0 {x 3}}
do_test badutf-3.3 {
  sqlite3_exec db {SELECT length('%7f%80%81') AS x}
} {0 {x 3}}
do_test badutf-3.4 {
  sqlite3_exec db {SELECT length('%61%c0') AS x}
} {0 {x 2}}
do_test badutf-3.5 {
  sqlite3_exec db {SELECT length('%61%c0%80%80%80%80%80%80%80%80%80%80') AS x}
} {0 {x 2}}
do_test badutf-3.6 {
  sqlite3_exec db {SELECT length('%c0%80%80%80%80%80%80%80%80%80%80') AS x}
} {0 {x 1}}
do_test badutf-3.7 {
  sqlite3_exec db {SELECT length('%80%80%80%80%80%80%80%80%80%80') AS x}
} {0 {x 10}}
do_test badutf-3.8 {
  sqlite3_exec db {SELECT length('%80%80%80%80%80%f0%80%80%80%80') AS x}
} {0 {x 6}}
do_test badutf-3.9 {
  sqlite3_exec db {SELECT length('%80%80%80%80%80%f0%80%80%80%ff') AS x}
} {0 {x 7}}

do_test badutf-4.1 {
  sqlite3_exec db {SELECT hex(trim('%80%80%80%f0%80%80%80%ff','%80%ff')) AS x}
} {0 {x F0}}
do_test badutf-4.2 {
  sqlite3_exec db {SELECT hex(ltrim('%80%80%80%f0%80%80%80%ff','%80%ff')) AS x}
} {0 {x F0808080FF}}
do_test badutf-4.3 {
  sqlite3_exec db {SELECT hex(rtrim('%80%80%80%f0%80%80%80%ff','%80%ff')) AS x}
} {0 {x 808080F0}}
do_test badutf-4.4 {
  sqlite3_exec db {SELECT hex(trim('%80%80%80%f0%80%80%80%ff','%ff%80')) AS x}
} {0 {x 808080F0808080FF}}
do_test badutf-4.5 {
  sqlite3_exec db {SELECT hex(trim('%ff%80%80%f0%80%80%80%ff','%ff%80')) AS x}
} {0 {x 80F0808080FF}}
do_test badutf-4.6 {
  sqlite3_exec db {SELECT hex(trim('%ff%80%f0%80%80%80%ff','%ff%80')) AS x}
} {0 {x F0808080FF}}
do_test badutf-4.7 {
  sqlite3_exec db {SELECT hex(trim('%ff%80%f0%80%80%80%ff','%ff%80%80')) AS x}
} {0 {x FF80F0808080FF}}

db2 close
finish_test

Added test/between.test.



































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# 2005 July 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the use of indices in WHERE clauses
# when the WHERE clause contains the BETWEEN operator.
#
# $Id: between.test,v 1.2 2006/01/17 09:35:02 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
do_test between-1.0 {
  execsql {
    BEGIN;
    CREATE TABLE t1(w int, x int, y int, z int);
  }
  for {set i 1} {$i<=100} {incr i} {
    set w $i
    set x [expr {int(log($i)/log(2))}]
    set y [expr {$i*$i + 2*$i + 1}]
    set z [expr {$x+$y}]
    ifcapable tclvar {
      # Random unplanned test of the $varname variable syntax.
      execsql {INSERT INTO t1 VALUES($::w,$::x,$::y,$::z)}
    } else {
      # If the $varname syntax is not available, use the regular variable
      # declaration syntax.
      execsql {INSERT INTO t1 VALUES(:w,:x,:y,:z)}
    }
  }
  execsql {
    CREATE UNIQUE INDEX i1w ON t1(w);
    CREATE INDEX i1xy ON t1(x,y);
    CREATE INDEX i1zyx ON t1(z,y,x);
    COMMIT;
  }
} {}

# This procedure executes the SQL.  Then it appends to the result the
# "sort" or "nosort" keyword depending on whether or not any sorting
# is done.  Then it appends the ::sqlite_query_plan variable.
#
proc queryplan {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return [concat $data $::sqlite_query_plan]
}

do_test between-1.1.1 {
  queryplan {
    SELECT * FROM t1 WHERE w BETWEEN 5 AND 6 ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 i1w}
do_test between-1.1.2 {
  queryplan {
    SELECT * FROM t1 WHERE +w BETWEEN 5 AND 6 ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 {}}
do_test between-1.2.1 {
  queryplan {
    SELECT * FROM t1 WHERE w BETWEEN 5 AND 65-y ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 i1w}
do_test between-1.2.2 {
  queryplan {
    SELECT * FROM t1 WHERE +w BETWEEN 5 AND 65-y ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 {}}
do_test between-1.3.1 {
  queryplan {
    SELECT * FROM t1 WHERE w BETWEEN 41-y AND 6 ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 i1w}
do_test between-1.3.2 {
  queryplan {
    SELECT * FROM t1 WHERE +w BETWEEN 41-y AND 6 ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 {}}
do_test between-1.4 {
  queryplan {
    SELECT * FROM t1 WHERE w BETWEEN 41-y AND 65-y ORDER BY +w
  }
} {5 2 36 38 6 2 49 51 sort t1 {}}
do_test between-1.5.1 {
  queryplan {
    SELECT * FROM t1 WHERE 26 BETWEEN y AND z ORDER BY +w
  }
} {4 2 25 27 sort t1 i1zyx}
do_test between-1.5.2 {
  queryplan {
    SELECT * FROM t1 WHERE 26 BETWEEN +y AND z ORDER BY +w
  }
} {4 2 25 27 sort t1 i1zyx}
do_test between-1.5.3 {
  queryplan {
    SELECT * FROM t1 WHERE 26 BETWEEN y AND +z ORDER BY +w
  }
} {4 2 25 27 sort t1 {}}


finish_test

Added test/bigfile.test.

































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# 2002 November 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the ability of SQLite to handle database
# files larger than 4GB.
#
# $Id: bigfile.test,v 1.12 2009/03/05 04:27:08 shane Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_DISABLE_LFS is defined, omit this file.
ifcapable !lfs {
  finish_test
  return
}

# These tests only work for Tcl version 8.4 and later.  Prior to 8.4,
# Tcl was unable to handle large files.
#
scan $::tcl_version %f vx
if {$vx<8.4} return

# Mac OS X does not handle large files efficiently.  So skip this test
# on that platform.
if {$tcl_platform(os)=="Darwin"} return

# This is the md5 checksum of all the data in table t1 as created
# by the first test.  We will use this number to make sure that data
# never changes.
#
set MAGIC_SUM {593f1efcfdbe698c28b4b1b693f7e4cf}

do_test bigfile-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES('abcdefghijklmnopqrstuvwxyz');
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    INSERT INTO t1 SELECT rowid || ' ' || x FROM t1;
    COMMIT;
  }
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM

# Try to create a large file - a file that is larger than 2^32 bytes.
# If this fails, it means that the system being tested does not support
# large files.  So skip all of the remaining tests in this file.
#
db close
if {[catch {fake_big_file 4096 [pwd]/test.db} msg]} {
  puts "**** Unable to create a file larger than 4096 MB. *****"
  finish_test
  return
}

do_test bigfile-1.2 {
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM

# The previous test may fail on some systems because they are unable
# to handle large files.  If that is so, then skip all of the following
# tests.  We will know the above test failed because the "db" command
# does not exist.
#
if {[llength [info command db]]<=0} {
  puts "**** Large file support appears to be broken. *****"
  finish_test
  return
}

do_test bigfile-1.3 {
  execsql {
    CREATE TABLE t2 AS SELECT * FROM t1;
    SELECT md5sum(x) FROM t2;
  }
} $::MAGIC_SUM
do_test bigfile-1.4 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM

db close
if {[catch {fake_big_file 8192 [pwd]/test.db}]} {
  puts "**** Unable to create a file larger than 8192 MB. *****"
  finish_test
  return
}

do_test bigfile-1.5 {
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM
do_test bigfile-1.6 {
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t2;
  }
} $::MAGIC_SUM
do_test bigfile-1.7 {
  execsql {
    CREATE TABLE t3 AS SELECT * FROM t1;
    SELECT md5sum(x) FROM t3;
  }
} $::MAGIC_SUM
do_test bigfile-1.8 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM
do_test bigfile-1.9 {
  execsql {
    SELECT md5sum(x) FROM t2;
  }
} $::MAGIC_SUM

db close
if {[catch {fake_big_file 16384 [pwd]/test.db}]} {
  puts "**** Unable to create a file larger than 16384 MB. *****"
  finish_test
  return
}

do_test bigfile-1.10 {
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM
do_test bigfile-1.11 {
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t2;
  }
} $::MAGIC_SUM
do_test bigfile-1.12 {
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t3;
  }
} $::MAGIC_SUM
do_test bigfile-1.13 {
  execsql {
    CREATE TABLE t4 AS SELECT * FROM t1;
    SELECT md5sum(x) FROM t4;
  }
} $::MAGIC_SUM
do_test bigfile-1.14 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT md5sum(x) FROM t1;
  }
} $::MAGIC_SUM
do_test bigfile-1.15 {
  execsql {
    SELECT md5sum(x) FROM t2;
  }
} $::MAGIC_SUM
do_test bigfile-1.16 {
  execsql {
    SELECT md5sum(x) FROM t3;
  }
} $::MAGIC_SUM

finish_test

Added test/bigrow.test.































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# 2001 September 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is stressing the library by putting large amounts
# of data in a single row of a table.
#
# $Id: bigrow.test,v 1.5 2004/08/07 23:54:48 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Make a big string that we can use for test data
#
do_test bigrow-1.0 {
  set ::bigstr {}
  for {set i 1} {$i<=9999} {incr i} {
    set sep [string index "abcdefghijklmnopqrstuvwxyz" [expr {$i%26}]]
    append ::bigstr "$sep [format %04d $i] "
  }
  string length $::bigstr
} {69993}

# Make a table into which we can insert some but records.
#
do_test bigrow-1.1 {
  execsql {
    CREATE TABLE t1(a text, b text, c text);
    SELECT name FROM sqlite_master
      WHERE type='table' OR type='index'
      ORDER BY name
  }
} {t1}

do_test bigrow-1.2 {
  set ::big1 [string range $::bigstr 0 65519]
  set sql "INSERT INTO t1 VALUES('abc',"
  append sql "'$::big1', 'xyz');"
  execsql $sql
  execsql {SELECT a, c FROM t1}
} {abc xyz}
do_test bigrow-1.3 {
  execsql {SELECT b FROM t1}
} [list $::big1]
do_test bigrow-1.4 {
  set ::big2 [string range $::bigstr 0 65520]
  set sql "INSERT INTO t1 VALUES('abc2',"
  append sql "'$::big2', 'xyz2');"
  set r [catch {execsql $sql} msg]
  lappend r $msg
} {0 {}}
do_test bigrow-1.4.1 {
  execsql {SELECT b FROM t1 ORDER BY c}
} [list $::big1 $::big2]
do_test bigrow-1.4.2 {
  execsql {SELECT c FROM t1 ORDER BY c}
} {xyz xyz2}
do_test bigrow-1.4.3 {
  execsql {DELETE FROM t1 WHERE a='abc2'}
  execsql {SELECT c FROM t1}
} {xyz}

do_test bigrow-1.5 {
  execsql {
    UPDATE t1 SET a=b, b=a;
    SELECT b,c FROM t1
  }
} {abc xyz}
do_test bigrow-1.6 {
  execsql {
    SELECT * FROM t1
  }
} [list $::big1 abc xyz]
do_test bigrow-1.7 {
  execsql {
    INSERT INTO t1 VALUES('1','2','3');
    INSERT INTO t1 VALUES('A','B','C');
    SELECT b FROM t1 WHERE a=='1';
  }
} {2}
do_test bigrow-1.8 {
  execsql "SELECT b FROM t1 WHERE a=='$::big1'"
} {abc}
do_test bigrow-1.9 {
  execsql "SELECT b FROM t1 WHERE a!='$::big1' ORDER BY a"
} {2 B}

# Try doing some indexing on big columns
#
do_test bigrow-2.1 {
  execsql {
    CREATE INDEX i1 ON t1(a)
  }
  execsql "SELECT b FROM t1 WHERE a=='$::big1'"
} {abc}
do_test bigrow-2.2 {
  execsql {
    UPDATE t1 SET a=b, b=a
  }
  execsql "SELECT b FROM t1 WHERE a=='abc'"
} [list $::big1]
do_test bigrow-2.3 {
  execsql {
    UPDATE t1 SET a=b, b=a
  }
  execsql "SELECT b FROM t1 WHERE a=='$::big1'"
} {abc}
catch {unset ::bigstr}
catch {unset ::big1}
catch {unset ::big2}

# Mosts of the tests above were created back when rows were limited in
# size to 64K.  Now rows can be much bigger.  Test that logic.  Also
# make sure things work correctly at the transition boundries between
# row sizes of 256 to 257 bytes and from 65536 to 65537 bytes.
#
# We begin by testing the 256..257 transition.
#
do_test bigrow-3.1 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c) VALUES('one','abcdefghijklmnopqrstuvwxyz0123','hi');
  }
  execsql {SELECT a,length(b),c FROM t1}
} {one 30 hi}
do_test bigrow-3.2 {
  execsql {
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
  }
  execsql {SELECT a,length(b),c FROM t1}
} {one 240 hi}
for {set i 1} {$i<10} {incr i} {
  do_test bigrow-3.3.$i {
    execsql "UPDATE t1 SET b=b||'$i'"
    execsql {SELECT a,length(b),c FROM t1}
  } "one [expr {240+$i}] hi"
}

# Now test the 65536..65537 row-size transition.
#
do_test bigrow-4.1 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c) VALUES('one','abcdefghijklmnopqrstuvwxyz0123','hi');
  }
  execsql {SELECT a,length(b),c FROM t1}
} {one 30 hi}
do_test bigrow-4.2 {
  execsql {
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
    UPDATE t1 SET b=b||b;
  }
  execsql {SELECT a,length(b),c FROM t1}
} {one 122880 hi}
do_test bigrow-4.3 {
  execsql {
    UPDATE t1 SET b=substr(b,1,65515)
  }
  execsql {SELECT a,length(b),c FROM t1}
} {one 65515 hi}
for {set i 1} {$i<10} {incr i} {
  do_test bigrow-4.4.$i {
    execsql "UPDATE t1 SET b=b||'$i'"
    execsql {SELECT a,length(b),c FROM t1}
  } "one [expr {65515+$i}] hi"
}

# Check to make sure the library recovers safely if a row contains
# too much data.
#
do_test bigrow-5.1 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c) VALUES('one','abcdefghijklmnopqrstuvwxyz0123','hi');
  }
  execsql {SELECT a,length(b),c FROM t1}
} {one 30 hi}
set i 1
for {set sz 60} {$sz<1048560} {incr sz $sz} {
  do_test bigrow-5.2.$i {
    execsql {
      UPDATE t1 SET b=b||b;
      SELECT a,length(b),c FROM t1;
    }
  } "one $sz hi"
  incr i
}
do_test bigrow-5.3 {
  catchsql {UPDATE t1 SET b=b||b}
} {0 {}}
do_test bigrow-5.4 {
  execsql {SELECT length(b) FROM t1}
} 1966080
do_test bigrow-5.5 {
  catchsql {UPDATE t1 SET b=b||b}
} {0 {}}
do_test bigrow-5.6 {
  execsql {SELECT length(b) FROM t1}
} 3932160
do_test bigrow-5.99 {
  execsql {DROP TABLE t1}
} {}

finish_test

Added test/bind.test.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# 2003 September 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the sqlite_bind API.
#
# $Id: bind.test,v 1.48 2009/07/22 07:27:57 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc sqlite_step {stmt N VALS COLS} {
  upvar VALS vals
  upvar COLS cols
  set vals [list]
  set cols [list]

  set rc [sqlite3_step $stmt]
  for {set i 0} {$i < [sqlite3_column_count $stmt]} {incr i} {
    lappend cols [sqlite3_column_name $stmt $i]
  }
  for {set i 0} {$i < [sqlite3_data_count $stmt]} {incr i} {
    lappend vals [sqlite3_column_text $stmt $i]
  }

  return $rc
}

do_test bind-1.1 {
  set DB [sqlite3_connection_pointer db]
  execsql {CREATE TABLE t1(a,b,c);}
  set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(:1,?,:abc)} -1 TAIL]
  set TAIL
} {}
do_test bind-1.1.1 {
  sqlite3_bind_parameter_count $VM
} 3
do_test bind-1.1.2 {
  sqlite3_bind_parameter_name $VM 1
} {:1}
do_test bind-1.1.3 {
  sqlite3_bind_parameter_name $VM 2
} {}
do_test bind-1.1.4 {
  sqlite3_bind_parameter_name $VM 3
} {:abc}
do_test bind-1.2 {
  sqlite_step $VM N VALUES COLNAMES
} {SQLITE_DONE}
do_test bind-1.3 {
  execsql {SELECT rowid, * FROM t1}
} {1 {} {} {}}
do_test bind-1.4 {
  sqlite3_reset $VM
  sqlite_bind $VM 1 {test value 1} normal
  sqlite_step $VM N VALUES COLNAMES
} SQLITE_DONE
do_test bind-1.5 {
  execsql {SELECT rowid, * FROM t1}
} {1 {} {} {} 2 {test value 1} {} {}}
do_test bind-1.6 {
  sqlite3_reset $VM
  sqlite_bind $VM 3 {'test value 2'} normal
  sqlite_step $VM N VALUES COLNAMES
} SQLITE_DONE
do_test bind-1.7 {
  execsql {SELECT rowid, * FROM t1}
} {1 {} {} {} 2 {test value 1} {} {} 3 {test value 1} {} {'test value 2'}}
do_test bind-1.8 {
  sqlite3_reset $VM
  set sqlite_static_bind_value 123
  sqlite_bind $VM 1 {} static
  sqlite_bind $VM 2 {abcdefg} normal
  sqlite_bind $VM 3 {} null
  execsql {DELETE FROM t1}
  sqlite_step $VM N VALUES COLNAMES
  execsql {SELECT rowid, * FROM t1}
} {1 123 abcdefg {}}
do_test bind-1.9 {
  sqlite3_reset $VM
  sqlite_bind $VM 1 {456} normal
  sqlite_step $VM N VALUES COLNAMES
  execsql {SELECT rowid, * FROM t1}
} {1 123 abcdefg {} 2 456 abcdefg {}}

do_test bind-1.10 {
   set rc [catch {
     sqlite3_prepare db {INSERT INTO t1 VALUES($abc:123,?,:abc)} -1 TAIL
   } msg]
   lappend rc $msg
} {1 {(1) near ":123": syntax error}}
do_test bind-1.11 {
   set rc [catch {
     sqlite3_prepare db {INSERT INTO t1 VALUES(@abc:xyz,?,:abc)} -1 TAIL
   } msg]
   lappend rc $msg
} {1 {(1) near ":xyz": syntax error}}

do_test bind-1.99 {
  sqlite3_finalize $VM
} SQLITE_OK

# Prepare the statement in different ways depending on whether or not
# the $var processing is compiled into the library.
#
ifcapable {tclvar} {
  do_test bind-2.1 {
    execsql {
      DELETE FROM t1;
    }
    set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES($one,$::two,$x(-z-))}\
            -1 TX]
    set TX
  } {}
  set v1 {$one}
  set v2 {$::two}
  set v3 {$x(-z-)}
}
ifcapable {!tclvar} {
  do_test bind-2.1 {
    execsql {
      DELETE FROM t1;
    }
    set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(:one,:two,:_)} -1 TX]
    set TX
  } {}
  set v1 {:one}
  set v2 {:two}
  set v3 {:_}
}

do_test bind-2.1.1 {
  sqlite3_bind_parameter_count $VM
} 3
do_test bind-2.1.2 {
  sqlite3_bind_parameter_name $VM 1
} $v1
do_test bind-2.1.3 {
  sqlite3_bind_parameter_name $VM 2
} $v2
do_test bind-2.1.4 {
  sqlite3_bind_parameter_name $VM 3
} $v3
do_test bind-2.1.5 {
  sqlite3_bind_parameter_index $VM $v1
} 1
do_test bind-2.1.6 {
  sqlite3_bind_parameter_index $VM $v2
} 2
do_test bind-2.1.7 {
  sqlite3_bind_parameter_index $VM $v3
} 3
do_test bind-2.1.8 {
  sqlite3_bind_parameter_index $VM {:hi}
} 0

# 32 bit Integers
do_test bind-2.2 {
  sqlite3_bind_int $VM 1 123
  sqlite3_bind_int $VM 2 456
  sqlite3_bind_int $VM 3 789
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  execsql {SELECT rowid, * FROM t1}
} {1 123 456 789}
do_test bind-2.3 {
  sqlite3_bind_int $VM 2 -2000000000
  sqlite3_bind_int $VM 3 2000000000
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  execsql {SELECT rowid, * FROM t1}
} {1 123 456 789 2 123 -2000000000 2000000000}
do_test bind-2.4 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {integer integer integer integer integer integer}
do_test bind-2.5 {
  execsql {
    DELETE FROM t1;
  }
} {}

# 64 bit Integers
do_test bind-3.1 {
  sqlite3_bind_int64 $VM 1 32
  sqlite3_bind_int64 $VM 2 -2000000000000
  sqlite3_bind_int64 $VM 3 2000000000000
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  execsql {SELECT rowid, * FROM t1}
} {1 32 -2000000000000 2000000000000}
do_test bind-3.2 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {integer integer integer}
do_test bind-3.3 {
  execsql {
    DELETE FROM t1;
  }
} {}

# Doubles
do_test bind-4.1 {
  sqlite3_bind_double $VM 1 1234.1234
  sqlite3_bind_double $VM 2 0.00001
  sqlite3_bind_double $VM 3 123456789
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  set x [execsql {SELECT rowid, * FROM t1}]
  regsub {1e-005} $x {1e-05} y
  set y
} {1 1234.1234 1e-05 123456789.0}
do_test bind-4.2 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {real real real}
do_test bind-4.3 {
  execsql {
    DELETE FROM t1;
  }
} {}
do_test bind-4.4 {
  sqlite3_bind_double $VM 1 NaN
  sqlite3_bind_double $VM 2 1e300
  sqlite3_bind_double $VM 3 -1e-300
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  set x [execsql {SELECT rowid, * FROM t1}]
  regsub {1e-005} $x {1e-05} y
  set y
} {1 {} 1e+300 -1e-300}
do_test bind-4.5 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {null real real}
do_test bind-4.6 {
  execsql {
    DELETE FROM t1;
  }
} {}

# NULL
do_test bind-5.1 {
  sqlite3_bind_null $VM 1
  sqlite3_bind_null $VM 2
  sqlite3_bind_null $VM 3 
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  execsql {SELECT rowid, * FROM t1}
} {1 {} {} {}}
do_test bind-5.2 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {null null null}
do_test bind-5.3 {
  execsql {
    DELETE FROM t1;
  }
} {}

# UTF-8 text
do_test bind-6.1 {
  sqlite3_bind_text $VM 1 hellothere 5
  sqlite3_bind_text $VM 2 ".." 1
  sqlite3_bind_text $VM 3 world\000 -1
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  execsql {SELECT rowid, * FROM t1}
} {1 hello . world}
do_test bind-6.2 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {text text text}
do_test bind-6.3 {
  execsql {
    DELETE FROM t1;
  }
} {}

# Make sure zeros in a string work.
#
do_test bind-6.4 {
  db eval {DELETE FROM t1}
  sqlite3_bind_text $VM 1 hello\000there\000 12
  sqlite3_bind_text $VM 2 hello\000there\000 11
  sqlite3_bind_text $VM 3 hello\000there\000 -1
  sqlite_step $VM N VALUES COLNAMES
  sqlite3_reset $VM
  execsql {SELECT * FROM t1}
} {hello hello hello}
set enc [db eval {PRAGMA encoding}]
if {$enc=="UTF-8" || $enc==""} {
  do_test bind-6.5 {
    execsql {SELECT  hex(a), hex(b), hex(c) FROM t1}
  } {68656C6C6F00746865726500 68656C6C6F007468657265 68656C6C6F}
} elseif {$enc=="UTF-16le"} {
  do_test bind-6.5 {
    execsql {SELECT  hex(a), hex(b), hex(c) FROM t1}
  } {680065006C006C006F000000740068006500720065000000 680065006C006C006F00000074006800650072006500 680065006C006C006F00}
} elseif {$enc=="UTF-16be"} {
  do_test bind-6.5 {
    execsql {SELECT  hex(a), hex(b), hex(c) FROM t1}
  } {00680065006C006C006F0000007400680065007200650000 00680065006C006C006F000000740068006500720065 00680065006C006C006F}
} else {
  do_test bind-6.5 {
    set "Unknown database encoding: $::enc"
  } {}
}
do_test bind-6.6 {
  execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
} {text text text}
do_test bind-6.7 {
  execsql {
    DELETE FROM t1;
  }
} {}

# UTF-16 text
ifcapable {utf16} {
  do_test bind-7.1 {
    sqlite3_bind_text16 $VM 1 [encoding convertto unicode hellothere] 10
    sqlite3_bind_text16 $VM 2 [encoding convertto unicode ""] 0
    sqlite3_bind_text16 $VM 3 [encoding convertto unicode world] 10
    sqlite_step $VM N VALUES COLNAMES
    sqlite3_reset $VM
    execsql {SELECT rowid, * FROM t1}
  } {1 hello {} world}
  do_test bind-7.2 {
    execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
  } {text text text}
  do_test bind-7.3 {
    db eval {DELETE FROM t1}
    sqlite3_bind_text16 $VM 1 [encoding convertto unicode hi\000yall\000] 16
    sqlite3_bind_text16 $VM 2 [encoding convertto unicode hi\000yall\000] 14
    sqlite3_bind_text16 $VM 3 [encoding convertto unicode hi\000yall\000] -1
    sqlite_step $VM N VALUES COLNAMES
    sqlite3_reset $VM
    execsql {SELECT * FROM t1}
  } {hi hi hi}
  if {$enc=="UTF-8"} {
    do_test bind-7.4 {
      execsql {SELECT hex(a), hex(b), hex(c) FROM t1}
    } {68690079616C6C00 68690079616C6C 6869}
  } elseif {$enc=="UTF-16le"} {
    do_test bind-7.4 {
      execsql {SELECT hex(a), hex(b), hex(c) FROM t1}
    } {680069000000790061006C006C000000 680069000000790061006C006C00 68006900}
  } elseif {$enc=="UTF-16be"} {
    do_test bind-7.4 {
      execsql {SELECT hex(a), hex(b), hex(c) FROM t1}
    } {00680069000000790061006C006C0000 00680069000000790061006C006C 00680069}
  }
  do_test bind-7.5 {
    execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1}
  } {text text text}
}
do_test bind-7.99 {
  execsql {DELETE FROM t1;}
} {}

# Test that the 'out of range' error works.
do_test bind-8.1 {
  catch { sqlite3_bind_null $VM 0 }
} {1}
do_test bind-8.2 {
  sqlite3_errmsg $DB
} {bind or column index out of range}
ifcapable {utf16} {
  do_test bind-8.3 {
    encoding convertfrom unicode [sqlite3_errmsg16 $DB]
  } {bind or column index out of range}
}
do_test bind-8.4 {
  sqlite3_bind_null $VM 1 
  sqlite3_errmsg $DB
} {not an error}
do_test bind-8.5 {
  catch { sqlite3_bind_null $VM 4 }
} {1}
do_test bind-8.6 {
  sqlite3_errmsg $DB
} {bind or column index out of range}
ifcapable {utf16} {
  do_test bind-8.7 {
    encoding convertfrom unicode [sqlite3_errmsg16 $DB]
  } {bind or column index out of range}
}

do_test bind-8.8 {
  catch { sqlite3_bind_blob $VM 0 "abc" 3 }
} {1}
do_test bind-8.9 {
  catch { sqlite3_bind_blob $VM 4 "abc" 3 }
} {1}
do_test bind-8.10 {
  catch { sqlite3_bind_text $VM 0 "abc" 3 }
} {1}
ifcapable {utf16} {
  do_test bind-8.11 {
    catch { sqlite3_bind_text16 $VM 4 "abc" 2 }
  } {1}
}
do_test bind-8.12 {
  catch { sqlite3_bind_int $VM 0 5 }
} {1}
do_test bind-8.13 {
  catch { sqlite3_bind_int $VM 4 5 }
} {1}
do_test bind-8.14 {
  catch { sqlite3_bind_double $VM 0 5.0 }
} {1}
do_test bind-8.15 {
  catch { sqlite3_bind_double $VM 4 6.0 }
} {1}

do_test bind-8.99 {
  sqlite3_finalize $VM
} SQLITE_OK

set iMaxVar $SQLITE_MAX_VARIABLE_NUMBER
set zError "(1) variable number must be between ?1 and ?$iMaxVar"
do_test bind-9.1 {
  execsql {
    CREATE TABLE t2(a,b,c,d,e,f);
  }
  set rc [catch {
    sqlite3_prepare $DB {
      INSERT INTO t2(a) VALUES(?0)
    } -1 TAIL
  } msg]
  lappend rc $msg
} [list 1 $zError]
do_test bind-9.2 {
  set rc [catch {
    sqlite3_prepare $DB "INSERT INTO t2(a) VALUES(?[expr $iMaxVar+1])" -1 TAIL
  } msg]
  lappend rc $msg
} [list 1 $zError]
do_test bind-9.3.1 {
  set VM [
    sqlite3_prepare $DB "
      INSERT INTO t2(a,b) VALUES(?1,?$iMaxVar)
    " -1 TAIL
  ]
  sqlite3_bind_parameter_count $VM
} $iMaxVar
catch {sqlite3_finalize $VM}
do_test bind-9.3.2 {
  set VM [
    sqlite3_prepare $DB "
      INSERT INTO t2(a,b) VALUES(?2,?[expr $iMaxVar - 1])
    " -1 TAIL
  ]
  sqlite3_bind_parameter_count $VM
} [expr {$iMaxVar - 1}]
catch {sqlite3_finalize $VM}
do_test bind-9.4 {
  set VM [
    sqlite3_prepare $DB "
      INSERT INTO t2(a,b,c,d) VALUES(?1,?[expr $iMaxVar - 2],?,?)
    " -1 TAIL
  ]
  sqlite3_bind_parameter_count $VM
} $iMaxVar
do_test bind-9.5 {
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM [expr $iMaxVar - 2] 999
  sqlite3_bind_int $VM [expr $iMaxVar - 1] 1000
  sqlite3_bind_int $VM $iMaxVar 1001
  sqlite3_step $VM
} SQLITE_DONE
do_test bind-9.6 {
  sqlite3_finalize $VM
} SQLITE_OK
do_test bind-9.7 {
  execsql {SELECT * FROM t2}
} {1 999 1000 1001 {} {}}

ifcapable {tclvar} {
  do_test bind-10.1 {
    set VM [
      sqlite3_prepare $DB {
        INSERT INTO t2(a,b,c,d,e,f) VALUES(:abc,$abc,:abc,$ab,$abc,:abc)
      } -1 TAIL
    ]
    sqlite3_bind_parameter_count $VM
  } 3
  set v1 {$abc}
  set v2 {$ab}
}
ifcapable {!tclvar} {
  do_test bind-10.1 {
    set VM [
      sqlite3_prepare $DB {
        INSERT INTO t2(a,b,c,d,e,f) VALUES(:abc,:xyz,:abc,:xy,:xyz,:abc)
      } -1 TAIL
    ]
    sqlite3_bind_parameter_count $VM
  } 3
  set v1 {:xyz}
  set v2 {:xy}
}
do_test bind-10.2 {
  sqlite3_bind_parameter_index $VM :abc
} 1
do_test bind-10.3 {
  sqlite3_bind_parameter_index $VM $v1
} 2
do_test bind-10.4 {
  sqlite3_bind_parameter_index $VM $v2
} 3
do_test bind-10.5 {
  sqlite3_bind_parameter_name $VM 1
} :abc
do_test bind-10.6 {
  sqlite3_bind_parameter_name $VM 2
} $v1
do_test bind-10.7 {
  sqlite3_bind_parameter_name $VM 3
} $v2
do_test bind-10.7.1 {
  sqlite3_bind_parameter_name 0 1   ;# Ignore if VM is NULL
} {}
do_test bind-10.7.2 {
  sqlite3_bind_parameter_name $VM 0 ;# Ignore if index too small
} {}
do_test bind-10.7.3 {
  sqlite3_bind_parameter_name $VM 4 ;# Ignore if index is too big
} {}
do_test bind-10.8 {
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM 2 2
  sqlite3_bind_int $VM 3 3
  sqlite3_step $VM
} SQLITE_DONE
do_test bind-10.8.1 {
  # Binding attempts after program start should fail
  set rc [catch {
    sqlite3_bind_int $VM 1 1
  } msg]
  lappend rc $msg
} {1 {}}
do_test bind-10.9 {
  sqlite3_finalize $VM
} SQLITE_OK
do_test bind-10.10 {
  execsql {SELECT * FROM t2}
} {1 999 1000 1001 {} {} 1 2 1 3 2 1}

# Ticket #918
#
do_test bind-10.11 {
  # catch {sqlite3_finalize $VM}
  set VM [
    sqlite3_prepare $DB {
      INSERT INTO t2(a,b,c,d,e,f) VALUES(:abc,?,?4,:pqr,:abc,?4)
    } -1 TAIL
  ]
  sqlite3_bind_parameter_count $VM
} 5
do_test bind-10.11.1 {
  sqlite3_bind_parameter_index 0 :xyz  ;# ignore NULL VM arguments
} 0
do_test bind-10.12 {
  sqlite3_bind_parameter_index $VM :xyz
} 0
do_test bind-10.13 {
  sqlite3_bind_parameter_index $VM {}
} 0
do_test bind-10.14 {
  sqlite3_bind_parameter_index $VM :pqr
} 5
do_test bind-10.15 {
  sqlite3_bind_parameter_index $VM ?4
} 4
do_test bind-10.16 {
  sqlite3_bind_parameter_name $VM 1
} :abc
do_test bind-10.17 {
  sqlite3_bind_parameter_name $VM 2
} {}
do_test bind-10.18 {
  sqlite3_bind_parameter_name $VM 3
} {}
do_test bind-10.19 {
  sqlite3_bind_parameter_name $VM 4
} {?4}
do_test bind-10.20 {
  sqlite3_bind_parameter_name $VM 5
} :pqr
catch {sqlite3_finalize $VM}

# Make sure we catch an unterminated "(" in a Tcl-style variable name
#
ifcapable tclvar {
  do_test bind-11.1 {
    catchsql {SELECT * FROM sqlite_master WHERE name=$abc(123 and sql NOT NULL;}
  } {1 {unrecognized token: "$abc(123"}}
}

if {[execsql {pragma encoding}]=="UTF-8"} {
  # Test the ability to bind text that contains embedded '\000' characters.
  # Make sure we can recover the entire input string.
  #
  do_test bind-12.1 {
    execsql {
      CREATE TABLE t3(x BLOB);
    }
    set VM [sqlite3_prepare $DB {INSERT INTO t3 VALUES(?)} -1 TAIL]
    sqlite_bind  $VM 1 not-used blob10
    sqlite3_step $VM
    sqlite3_finalize $VM
    execsql {
      SELECT typeof(x), length(x), quote(x),
             length(cast(x AS BLOB)), quote(cast(x AS BLOB)) FROM t3
    }
  } {text 3 'abc' 10 X'6162630078797A007071'}
  do_test bind-12.2 {
    sqlite3_create_function $DB
    execsql {
      SELECT quote(cast(x_coalesce(x) AS blob)) FROM t3
    }
  } {X'6162630078797A007071'}
}

# Test the operation of sqlite3_clear_bindings
#
do_test bind-13.1 {
  set VM [sqlite3_prepare $DB {SELECT ?,?,?} -1 TAIL]
  sqlite3_step $VM
  list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \
               [sqlite3_column_type $VM 2]
} {NULL NULL NULL}
do_test bind-13.2 {
  sqlite3_reset $VM
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM 2 2
  sqlite3_bind_int $VM 3 3
  sqlite3_step $VM
  list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \
               [sqlite3_column_type $VM 2]
} {INTEGER INTEGER INTEGER}
do_test bind-13.3 {
  sqlite3_reset $VM
  sqlite3_step $VM
  list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \
               [sqlite3_column_type $VM 2]
} {INTEGER INTEGER INTEGER}
do_test bind-13.4 {
  sqlite3_reset $VM
  sqlite3_clear_bindings $VM
  sqlite3_step $VM
  list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \
               [sqlite3_column_type $VM 2]
} {NULL NULL NULL}
sqlite3_finalize $VM

#--------------------------------------------------------------------
# These tests attempt to reproduce bug #3463.
#
proc param_names {db zSql} {
  set ret [list]
  set VM [sqlite3_prepare db $zSql -1 TAIL]
  for {set ii 1} {$ii <= [sqlite3_bind_parameter_count $VM]} {incr ii} {
    lappend ret [sqlite3_bind_parameter_name $VM $ii]
  }
  sqlite3_finalize $VM
  set ret
}

do_test bind-14.1 {
  param_names db { SELECT @a, @b }
} {@a @b}
do_test bind-14.2 {
  param_names db { SELECT NULL FROM (SELECT NULL) WHERE @a = @b }
} {@a @b}
do_test bind-14.3 {
  param_names db { SELECT @a FROM (SELECT NULL) WHERE 1 = @b }
} {@a @b}
do_test bind-14.4 {
  param_names db { SELECT @a, @b FROM (SELECT NULL) }
} {@a @b}

#--------------------------------------------------------------------------
# Tests of the OP_Variable opcode where P3>1
#
do_test bind-15.1 {
  db eval {CREATE TABLE t4(a,b,c,d,e,f,g,h);}
  set VM [sqlite3_prepare db {
       INSERT INTO t4(a,b,c,d,f,g,h,e) VALUES(?,?,?,?,?,?,?,?)
  } -1 TAIL]
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM 2 2
  sqlite3_bind_int $VM 3 3
  sqlite3_bind_int $VM 4 4
  sqlite3_bind_int $VM 5 5
  sqlite3_bind_int $VM 6 6
  sqlite3_bind_int $VM 7 7
  sqlite3_bind_int $VM 8 8
  sqlite3_step $VM
  sqlite3_finalize $VM
  db eval {SELECT * FROM t4}
} {1 2 3 4 8 5 6 7}
do_test bind-15.2 {
  db eval {DELETE FROM t4}
  set VM [sqlite3_prepare db {
       INSERT INTO t4(a,b,c,d,e,f,g,h) VALUES(?,?,?,?,?,?,?,?)
  } -1 TAIL]
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM 2 2
  sqlite3_bind_int $VM 3 3
  sqlite3_bind_int $VM 4 4
  sqlite3_bind_int $VM 5 5
  sqlite3_bind_int $VM 6 6
  sqlite3_bind_int $VM 7 7
  sqlite3_bind_int $VM 8 8
  sqlite3_step $VM
  sqlite3_finalize $VM
  db eval {SELECT * FROM t4}
} {1 2 3 4 5 6 7 8}
do_test bind-15.3 {
  db eval {DELETE FROM t4}
  set VM [sqlite3_prepare db {
       INSERT INTO t4(h,g,f,e,d,c,b,a) VALUES(?,?,?,?,?,?,?,?)
  } -1 TAIL]
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM 2 2
  sqlite3_bind_int $VM 3 3
  sqlite3_bind_int $VM 4 4
  sqlite3_bind_int $VM 5 5
  sqlite3_bind_int $VM 6 6
  sqlite3_bind_int $VM 7 7
  sqlite3_bind_int $VM 8 8
  sqlite3_step $VM
  sqlite3_finalize $VM
  db eval {SELECT * FROM t4}
} {8 7 6 5 4 3 2 1}
do_test bind-15.4 {
  db eval {DELETE FROM t4}
  set VM [sqlite3_prepare db {
       INSERT INTO t4(a,b,c,d,e,f,g,h) VALUES(?,?,?,?4,?,?6,?,?)
  } -1 TAIL]
  sqlite3_bind_int $VM 1 1
  sqlite3_bind_int $VM 2 2
  sqlite3_bind_int $VM 3 3
  sqlite3_bind_int $VM 4 4
  sqlite3_bind_int $VM 5 5
  sqlite3_bind_int $VM 6 6
  sqlite3_bind_int $VM 7 7
  sqlite3_bind_int $VM 8 8
  sqlite3_step $VM
  sqlite3_finalize $VM
  db eval {SELECT * FROM t4}
} {1 2 3 4 5 6 7 8}

finish_test

Added test/bindxfer.test.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 2005 April 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the sqlite_transfer_bindings() API.
#
# $Id: bindxfer.test,v 1.9 2009/04/17 11:56:28 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc sqlite_step {stmt VALS COLS} {
  upvar #0 $VALS vals
  upvar #0 $COLS cols
  set vals [list]
  set cols [list]

  set rc [sqlite3_step $stmt]
  for {set i 0} {$i < [sqlite3_column_count $stmt]} {incr i} {
    lappend cols [sqlite3_column_name $stmt $i]
  }
  for {set i 0} {$i < [sqlite3_data_count $stmt]} {incr i} {
    lappend vals [sqlite3_column_text $stmt $i]
  }

  return $rc
}

do_test bindxfer-1.1 {
  set DB [sqlite3_connection_pointer db]
  execsql {CREATE TABLE t1(a,b,c);}
  set VM1 [sqlite3_prepare $DB {SELECT ?, ?, ?} -1 TAIL]
  set TAIL
} {}
do_test bindxfer-1.2 {
  sqlite3_bind_parameter_count $VM1
} 3
do_test bindxfer-1.3 {
  set VM2 [sqlite3_prepare $DB {SELECT ?, ?, ?} -1 TAIL]
  set TAIL
} {}
do_test bindxfer-1.4 {
  sqlite3_bind_parameter_count $VM2
} 3
ifcapable deprecated {
  do_test bindxfer-1.5 {
    sqlite_bind $VM1 1 one normal
    set sqlite_static_bind_value two
    sqlite_bind $VM1 2 {} static
    sqlite_bind $VM1 3 {} null
    sqlite3_transfer_bindings $VM1 $VM2
    sqlite_step $VM1 VALUES COLNAMES
  } SQLITE_ROW
  do_test bindxfer-1.6 {
    set VALUES
  } {{} {} {}}
  do_test bindxfer-1.7 {
    sqlite_step $VM2 VALUES COLNAMES
  } SQLITE_ROW
  do_test bindxfer-1.8 {
    set VALUES
  } {one two {}}
}
catch {sqlite3_finalize $VM1}
catch {sqlite3_finalize $VM2}


finish_test

Added test/bitvec.test.







































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# 2008 February 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Unit testing of the Bitvec object.
#
# $Id: bitvec.test,v 1.4 2009/04/01 23:49:04 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# The built-in test logic must be operational in order for
# this test to work.
ifcapable !builtin_test {
  finish_test
  return
}

# Test that sqlite3BitvecBuiltinTest correctly reports errors
# that are deliberately introduced.
#
do_test bitvec-1.0.1 {
  sqlite3BitvecBuiltinTest 400 {5 1 1 1 0}
} 1
do_test bitvec-1.0.2 {
  sqlite3BitvecBuiltinTest 400 {5 1 234 1 0}
} 234

# Run test cases that set every bit in vectors of various sizes.
# for larger cases, this should cycle the bit vector representation
# from hashing into subbitmaps.  The subbitmaps should start as
# hashes then change to either subbitmaps or linear maps, depending
# on their size.
#
do_test bitvec-1.1 {
  sqlite3BitvecBuiltinTest 400 {1 400 1 1 0}
} 0
do_test bitvec-1.2 {
  sqlite3BitvecBuiltinTest 4000 {1 4000 1 1 0}
} 0
do_test bitvec-1.3 {
  sqlite3BitvecBuiltinTest 40000 {1 40000 1 1 0}
} 0
do_test bitvec-1.4 {
  sqlite3BitvecBuiltinTest 400000 {1 400000 1 1 0}
} 0

# By specifying a larger increments, we spread the load around.
#
do_test bitvec-1.5 {
  sqlite3BitvecBuiltinTest 400 {1 400 1 7 0}
} 0
do_test bitvec-1.6 {
  sqlite3BitvecBuiltinTest 4000 {1 4000 1 7 0}
} 0
do_test bitvec-1.7 {
  sqlite3BitvecBuiltinTest 40000 {1 40000 1 7 0}
} 0
do_test bitvec-1.8 {
  sqlite3BitvecBuiltinTest 400000 {1 400000 1 7 0}
} 0

# First fill up the bitmap with ones,  then go through and
# clear all the bits.  This will stress the clearing mechanism.
#
do_test bitvec-1.9 {
  sqlite3BitvecBuiltinTest 400 {1 400 1 1 2 400 1 1 0}
} 0
do_test bitvec-1.10 {
  sqlite3BitvecBuiltinTest 4000 {1 4000 1 1 2 4000 1 1 0}
} 0
do_test bitvec-1.11 {
  sqlite3BitvecBuiltinTest 40000 {1 40000 1 1 2 40000 1 1 0}
} 0
do_test bitvec-1.12 {
  sqlite3BitvecBuiltinTest 400000 {1 400000 1 1 2 400000 1 1 0}
} 0

do_test bitvec-1.13 {
  sqlite3BitvecBuiltinTest 400 {1 400 1 1 2 400 1 7 0}
} 0
do_test bitvec-1.15 {
  sqlite3BitvecBuiltinTest 4000 {1 4000 1 1 2 4000 1 7 0}
} 0
do_test bitvec-1.16 {
  sqlite3BitvecBuiltinTest 40000 {1 40000 1 1 2 40000 1 77 0}
} 0
do_test bitvec-1.17 {
  sqlite3BitvecBuiltinTest 400000 {1 400000 1 1 2 400000 1 777 0}
} 0

do_test bitvec-1.18 {
  sqlite3BitvecBuiltinTest 400000 {1 5000 100000 1 2 400000 1 37 0}
} 0

# Attempt to induce hash collisions.  
#
unset -nocomplain start
unset -nocomplain incr
foreach start {1 2 3 4 5 6 7 8} {
  foreach incr {124 125} {
    do_test bitvec-1.20.$start.$incr {
      set prog [list 1 60 $::start $::incr 2 5000 1 1 0]
      sqlite3BitvecBuiltinTest 5000 $prog
    } 0
  }
}

do_test bitvec-1.30.big_and_slow {
  sqlite3BitvecBuiltinTest 17000000 {1 17000000 1 1 2 17000000 1 1 0}
} 0


# Test setting and clearing a random subset of bits.
#
do_test bitvec-2.1 {
  sqlite3BitvecBuiltinTest 4000 {3 2000 4 2000 0}
} 0
do_test bitvec-2.2 {
  sqlite3BitvecBuiltinTest 4000 {3 1000 4 1000 3 1000 4 1000 3 1000 4 1000
                                 3 1000 4 1000 3 1000 4 1000 3 1000 4 1000 0}
} 0
do_test bitvec-2.3 {
  sqlite3BitvecBuiltinTest 400000 {3 10 0}
} 0
do_test bitvec-2.4 {
  sqlite3BitvecBuiltinTest 4000 {3 10 2 4000 1 1 0}
} 0
do_test bitvec-2.5 {
  sqlite3BitvecBuiltinTest 5000 {3 20 2 5000 1 1 0}
} 0
do_test bitvec-2.6 {
  sqlite3BitvecBuiltinTest 50000 {3 60 2 50000 1 1 0}
} 0
do_test bitvec-2.7 {
  sqlite3BitvecBuiltinTest 5000 {
          1 25 121 125
          1 50 121 125
          2 25 121 125
          0
  }
} 0

# This procedure runs sqlite3BitvecBuiltinTest with argments "n" and
# "program".  But it also causes a malloc error to occur after the
# "failcnt"-th malloc.  The result should be "0" if no malloc failure
# occurs or "-1" if there is a malloc failure.
#
proc bitvec_malloc_test {label failcnt n program} {
  do_test $label [subst {
    sqlite3_memdebug_fail $failcnt
    set x \[sqlite3BitvecBuiltinTest $n [list $program]\]
    set nFail \[sqlite3_memdebug_fail -1\]
    if {\$nFail==0} {
      set ::go 0
      set x -1
    }
    set x
  }] -1
}

# Make sure malloc failures are handled sanily.
#
unset -nocomplain n
unset -nocomplain go
set go 1
save_prng_state
for {set n 0} {$go} {incr n} {
  restore_prng_state
  bitvec_malloc_test bitvec-3.1.$n $n 5000 {
      3 60 2 5000 1 1 3 60 2 5000 1 1 3 60 2 5000 1 1 0
  }
}
set go 1
for {set n 0} {$go} {incr n} {
  restore_prng_state
  bitvec_malloc_test bitvec-3.2.$n $n 5000 {
      3 600 2 5000 1 1 3 600 2 5000 1 1 3 600 2 5000 1 1 0
  }
}
set go 1
for {set n 1} {$go} {incr n} {
  bitvec_malloc_test bitvec-3.3.$n $n 50000 {1 50000 1 1 0}
}

finish_test
return

Added test/blob.test.







































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# $Id: blob.test,v 1.8 2009/04/28 18:00:27 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!bloblit} {
  finish_test
  return
}

proc bin_to_hex {blob} {
  set bytes {}
  binary scan $blob \c* bytes
  set bytes2 [list]
  foreach b $bytes {lappend bytes2 [format %02X [expr $b & 0xFF]]}
  join $bytes2 {}
}

# Simplest possible case. Specify a blob literal
do_test blob-1.0 {
  set blob [execsql {SELECT X'01020304';}]
  bin_to_hex [lindex $blob 0]
} {01020304}
do_test blob-1.1 {
  set blob [execsql {SELECT x'ABCDEF';}]
  bin_to_hex [lindex $blob 0]
} {ABCDEF}
do_test blob-1.2 {
  set blob [execsql {SELECT x'';}]
  bin_to_hex [lindex $blob 0]
} {}
do_test blob-1.3 {
  set blob [execsql {SELECT x'abcdEF12';}]
  bin_to_hex [lindex $blob 0]
} {ABCDEF12}
do_test blob-1.3.2 {
  set blob [execsql {SELECT x'0123456789abcdefABCDEF';}]
  bin_to_hex [lindex $blob 0]
} {0123456789ABCDEFABCDEF}

# Try some syntax errors in blob literals.
do_test blob-1.4 {
  catchsql {SELECT X'01020k304', 100}
} {1 {unrecognized token: "X'01020k304'"}}
do_test blob-1.5 {
  catchsql {SELECT X'01020, 100}
} {1 {unrecognized token: "X'01020, 100"}}
do_test blob-1.6 {
  catchsql {SELECT X'01020 100'}
} {1 {unrecognized token: "X'01020 100'"}}
do_test blob-1.7 {
  catchsql {SELECT X'01001'}
} {1 {unrecognized token: "X'01001'"}}
do_test blob-1.8 {
  catchsql {SELECT x'012/45'}
} {1 {unrecognized token: "x'012/45'"}}
do_test blob-1.9 {
  catchsql {SELECT x'012:45'}
} {1 {unrecognized token: "x'012:45'"}}
do_test blob-1.10 {
  catchsql {SELECT x'012@45'}
} {1 {unrecognized token: "x'012@45'"}}
do_test blob-1.11 {
  catchsql {SELECT x'012G45'}
} {1 {unrecognized token: "x'012G45'"}}
do_test blob-1.12 {
  catchsql {SELECT x'012`45'}
} {1 {unrecognized token: "x'012`45'"}}
do_test blob-1.13 {
  catchsql {SELECT x'012g45'}
} {1 {unrecognized token: "x'012g45'"}}


# Insert a blob into a table and retrieve it.
do_test blob-2.0 {
  execsql {
    CREATE TABLE t1(a BLOB, b BLOB);
    INSERT INTO t1 VALUES(X'123456', x'7890ab');
    INSERT INTO t1 VALUES(X'CDEF12', x'345678');
  }
  set blobs [execsql {SELECT * FROM t1}]
  set blobs2 [list]
  foreach b $blobs {lappend blobs2 [bin_to_hex $b]}
  set blobs2
} {123456 7890AB CDEF12 345678}

# An index on a blob column
do_test blob-2.1 {
  execsql {
    CREATE INDEX i1 ON t1(a);
  }
  set blobs [execsql {SELECT * FROM t1}]
  set blobs2 [list]
  foreach b $blobs {lappend blobs2 [bin_to_hex $b]}
  set blobs2
} {123456 7890AB CDEF12 345678}
do_test blob-2.2 {
  set blobs [execsql {SELECT * FROM t1 where a = X'123456'}]
  set blobs2 [list]
  foreach b $blobs {lappend blobs2 [bin_to_hex $b]}
  set blobs2
} {123456 7890AB}
do_test blob-2.3 {
  set blobs [execsql {SELECT * FROM t1 where a = X'CDEF12'}]
  set blobs2 [list]
  foreach b $blobs {lappend blobs2 [bin_to_hex $b]}
  set blobs2
} {CDEF12 345678}
do_test blob-2.4 {
  set blobs [execsql {SELECT * FROM t1 where a = X'CD12'}]
  set blobs2 [list]
  foreach b $blobs {lappend blobs2 [bin_to_hex $b]}
  set blobs2
} {}

# Try to bind a blob value to a prepared statement.
do_test blob-3.0 {
  sqlite3 db2 test.db
  set DB [sqlite3_connection_pointer db2]
  set STMT [sqlite3_prepare $DB "DELETE FROM t1 WHERE a = ?" -1 DUMMY]
  sqlite3_bind_blob $STMT 1 "\x12\x34\x56" 3
  sqlite3_step $STMT
} {SQLITE_DONE}
do_test blob-3.1 {
  sqlite3_finalize $STMT
  db2 close
} {}
do_test blob-3.2 {
  set blobs [execsql {SELECT * FROM t1}]
  set blobs2 [list]
  foreach b $blobs {lappend blobs2 [bin_to_hex $b]}
  set blobs2
} {CDEF12 345678}

finish_test

Added test/boundary1.tcl.



































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
puts {# 2008 December 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is automatically generated from a separate TCL script.
# This file seeks to exercise integer boundary values.
#
# $Id: boundary1.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Many of the boundary tests depend on a working 64-bit implementation.
if {![working_64bit_int]} { finish_test; return }
}

expr srand(0)

# Generate interesting boundary numbers
#
foreach x {
  0
  1
  0x7f
  0x7fff
  0x7fffff
  0x7fffffff
  0x7fffffffff
  0x7fffffffffff
  0x7fffffffffffff
  0x7fffffffffffffff
} {
  set x [expr {wide($x)}]
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set boundarynum([expr {-($x+1)}]) 1
  set boundarynum([expr {-($x+2)}]) 1
  set boundarynum([expr {$x+$x+1}]) 1
  set boundarynum([expr {$x+$x+2}]) 1
}
set x [expr {wide(127)}]
for {set i 1} {$i<=9} {incr i} {
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set x [expr {wide($x*128 + 127)}]
}

# Scramble the $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# A simple selection sort.  Not trying to be efficient.
#
proc sort {inlist} {
  set outlist {}
  set mn [lindex $inlist 0]
  foreach x $inlist {
    if {$x<$mn} {set mn $x}
  }
  set outlist $mn
  set mx $mn
  while {1} {
    set valid 0
    foreach x $inlist {
      if {$x>$mx && (!$valid || $mn>$x)} {
        set mn $x
        set valid 1
      }
    }
    if {!$valid} break
    lappend outlist $mn
    set mx $mn
  }
  return $outlist
}

# Reverse the order of a list
#
proc reverse {inlist} {
  set i [llength $inlist]
  set outlist {}
  for {incr i -1} {$i>=0} {incr i -1} {
    lappend outlist [lindex $inlist $i]
  }
  return $outlist
}

set nums1 [scramble [array names boundarynum]]
set nums2 [scramble [array names boundarynum]]

set tname boundary1
puts "do_test $tname-1.1 \173"
puts "  db eval \173"
puts "    CREATE TABLE t1(a,x);"
set a 0
foreach r $nums1 {
  incr a
  set t1ra($r) $a
  set t1ar($a) $r
  set x [format %08x%08x [expr {wide($r)>>32}] $r]
  set t1rx($r) $x
  set t1xr($x) $r
  puts "    INSERT INTO t1(oid,a,x) VALUES($r,$a,'$x');"
}
puts "    CREATE INDEX t1i1 ON t1(a);"
puts "    CREATE INDEX t1i2 ON t1(x);"
puts "  \175"
puts "\175 {}"

puts "do_test $tname-1.2 \173"
puts "  db eval \173"
puts "    SELECT count(*) FROM t1"
puts "  \175"
puts "\175 {64}"

set nums3 $nums2
lappend nums3 9.22337303685477580800e+18
lappend nums3 -9.22337303685477580800e+18

set i 0
foreach r $nums3 {
  incr i

  if {abs($r)<9.22337203685477580800e+18} {
    set x $t1rx($r)
    set a $t1ra($r)
    set r5 $r.5
    set r0 $r.0
    puts "do_test $tname-2.$i.1 \173"
    puts "  db eval \173"
    puts "    SELECT * FROM t1 WHERE rowid=$r"
    puts "  \175"
    puts "\175 {$a $x}"
    puts "do_test $tname-2.$i.2 \173"
    puts "  db eval \173"
    puts "    SELECT rowid, a FROM t1 WHERE x='$x'"
    puts "  \175"
    puts "\175 {$r $a}"
    puts "do_test $tname-2.$i.3 \173"
    puts "  db eval \173"
    puts "    SELECT rowid, x FROM t1 WHERE a=$a"
    puts "  \175"
    puts "\175 {$r $x}"
  }

  foreach op {> >= < <=} subno {gt ge lt le} {

    ################################################################ 2.x.y.1
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r" {
        lappend rset $rx
        lappend aset $t1ra($rx)
      }
    }
    puts "do_test $tname-2.$i.$subno.1 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r ORDER BY a"
    puts "  \175"
    puts "\175 {[sort $aset]}"
  
    ################################################################ 2.x.y.2
    puts "do_test $tname-2.$i.$subno.2 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r ORDER BY a DESC"
    puts "  \175"
    puts "\175 {[reverse [sort $aset]]}"
  
    ################################################################ 2.x.y.3
    set aset {}
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.3 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r ORDER BY rowid"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.4
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.4 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r ORDER BY rowid DESC"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.5
    set aset {}
    set xset {}
    foreach rx $rset {
      lappend xset $t1rx($rx)
    }
    foreach x [sort $xset] {
      set rx $t1xr($x)
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.5 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r ORDER BY x"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.10
    if {abs($r)>9223372036854775808 || [string length $r5]>15} continue
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r0" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.10 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r0 ORDER BY rowid"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.11
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.11 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r0 ORDER BY rowid DESC"
    puts "  \175"
    puts "\175 {$aset}"


    ################################################################ 2.x.y.12
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r5" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.12 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r5 ORDER BY rowid"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.13
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.13 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE rowid $op $r5 ORDER BY rowid DESC"
    puts "  \175"
    puts "\175 {$aset}"
  }
  
}


puts {finish_test}

Added test/boundary1.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
# 2008 December 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is automatically generated from a separate TCL script.
# This file seeks to exercise integer boundary values.
#
# $Id: boundary1.test,v 1.2 2009/01/02 15:45:48 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Many of the boundary tests depend on a working 64-bit implementation.
if {![working_64bit_int]} { finish_test; return }

do_test boundary1-1.1 {
  db eval {
    CREATE TABLE t1(a,x);
    INSERT INTO t1(oid,a,x) VALUES(-8388609,1,'ffffffffff7fffff');
    INSERT INTO t1(oid,a,x) VALUES(-36028797018963969,2,'ff7fffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(9223372036854775807,3,'7fffffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(127,4,'000000000000007f');
    INSERT INTO t1(oid,a,x) VALUES(3,5,'0000000000000003');
    INSERT INTO t1(oid,a,x) VALUES(16777216,6,'0000000001000000');
    INSERT INTO t1(oid,a,x) VALUES(4398046511103,7,'000003ffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(16383,8,'0000000000003fff');
    INSERT INTO t1(oid,a,x) VALUES(16777215,9,'0000000000ffffff');
    INSERT INTO t1(oid,a,x) VALUES(281474976710655,10,'0000ffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-2147483648,11,'ffffffff80000000');
    INSERT INTO t1(oid,a,x) VALUES(268435455,12,'000000000fffffff');
    INSERT INTO t1(oid,a,x) VALUES(562949953421311,13,'0001ffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(4294967295,14,'00000000ffffffff');
    INSERT INTO t1(oid,a,x) VALUES(2097151,15,'00000000001fffff');
    INSERT INTO t1(oid,a,x) VALUES(16384,16,'0000000000004000');
    INSERT INTO t1(oid,a,x) VALUES(72057594037927935,17,'00ffffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(8388607,18,'00000000007fffff');
    INSERT INTO t1(oid,a,x) VALUES(1099511627776,19,'0000010000000000');
    INSERT INTO t1(oid,a,x) VALUES(2147483647,20,'000000007fffffff');
    INSERT INTO t1(oid,a,x) VALUES(-140737488355329,21,'ffff7fffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(34359738368,22,'0000000800000000');
    INSERT INTO t1(oid,a,x) VALUES(32767,23,'0000000000007fff');
    INSERT INTO t1(oid,a,x) VALUES(8388608,24,'0000000000800000');
    INSERT INTO t1(oid,a,x) VALUES(140737488355327,25,'00007fffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(281474976710656,26,'0001000000000000');
    INSERT INTO t1(oid,a,x) VALUES(36028797018963967,27,'007fffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(72057594037927936,28,'0100000000000000');
    INSERT INTO t1(oid,a,x) VALUES(-32769,29,'ffffffffffff7fff');
    INSERT INTO t1(oid,a,x) VALUES(255,30,'00000000000000ff');
    INSERT INTO t1(oid,a,x) VALUES(4,31,'0000000000000004');
    INSERT INTO t1(oid,a,x) VALUES(-32768,32,'ffffffffffff8000');
    INSERT INTO t1(oid,a,x) VALUES(-2,33,'fffffffffffffffe');
    INSERT INTO t1(oid,a,x) VALUES(140737488355328,34,'0000800000000000');
    INSERT INTO t1(oid,a,x) VALUES(549755813888,35,'0000008000000000');
    INSERT INTO t1(oid,a,x) VALUES(4294967296,36,'0000000100000000');
    INSERT INTO t1(oid,a,x) VALUES(-8388608,37,'ffffffffff800000');
    INSERT INTO t1(oid,a,x) VALUES(-1,38,'ffffffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(34359738367,39,'00000007ffffffff');
    INSERT INTO t1(oid,a,x) VALUES(268435456,40,'0000000010000000');
    INSERT INTO t1(oid,a,x) VALUES(2,41,'0000000000000002');
    INSERT INTO t1(oid,a,x) VALUES(2097152,42,'0000000000200000');
    INSERT INTO t1(oid,a,x) VALUES(562949953421312,43,'0002000000000000');
    INSERT INTO t1(oid,a,x) VALUES(-140737488355328,44,'ffff800000000000');
    INSERT INTO t1(oid,a,x) VALUES(36028797018963968,45,'0080000000000000');
    INSERT INTO t1(oid,a,x) VALUES(549755813887,46,'0000007fffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-2147483649,47,'ffffffff7fffffff');
    INSERT INTO t1(oid,a,x) VALUES(65535,48,'000000000000ffff');
    INSERT INTO t1(oid,a,x) VALUES(128,49,'0000000000000080');
    INSERT INTO t1(oid,a,x) VALUES(32768,50,'0000000000008000');
    INSERT INTO t1(oid,a,x) VALUES(2147483648,51,'0000000080000000');
    INSERT INTO t1(oid,a,x) VALUES(-3,52,'fffffffffffffffd');
    INSERT INTO t1(oid,a,x) VALUES(-128,53,'ffffffffffffff80');
    INSERT INTO t1(oid,a,x) VALUES(-129,54,'ffffffffffffff7f');
    INSERT INTO t1(oid,a,x) VALUES(-9223372036854775808,55,'8000000000000000');
    INSERT INTO t1(oid,a,x) VALUES(4398046511104,56,'0000040000000000');
    INSERT INTO t1(oid,a,x) VALUES(1099511627775,57,'000000ffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-549755813889,58,'ffffff7fffffffff');
    INSERT INTO t1(oid,a,x) VALUES(0,59,'0000000000000000');
    INSERT INTO t1(oid,a,x) VALUES(1,60,'0000000000000001');
    INSERT INTO t1(oid,a,x) VALUES(256,61,'0000000000000100');
    INSERT INTO t1(oid,a,x) VALUES(65536,62,'0000000000010000');
    INSERT INTO t1(oid,a,x) VALUES(-549755813888,63,'ffffff8000000000');
    INSERT INTO t1(oid,a,x) VALUES(-36028797018963968,64,'ff80000000000000');
    CREATE INDEX t1i1 ON t1(a);
    CREATE INDEX t1i2 ON t1(x);
  }
} {}
do_test boundary1-1.2 {
  db eval {
    SELECT count(*) FROM t1
  }
} {64}
do_test boundary1-2.1.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=72057594037927935
  }
} {17 00ffffffffffffff}
do_test boundary1-2.1.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00ffffffffffffff'
  }
} {72057594037927935 17}
do_test boundary1-2.1.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=17
  }
} {72057594037927935 00ffffffffffffff}
do_test boundary1-2.1.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY a
  }
} {3 28}
do_test boundary1-2.1.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY a DESC
  }
} {28 3}
do_test boundary1-2.1.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY rowid
  }
} {28 3}
do_test boundary1-2.1.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY rowid DESC
  }
} {3 28}
do_test boundary1-2.1.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY x
  }
} {28 3}
do_test boundary1-2.1.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY a
  }
} {3 17 28}
do_test boundary1-2.1.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY a DESC
  }
} {28 17 3}
do_test boundary1-2.1.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY rowid
  }
} {17 28 3}
do_test boundary1-2.1.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY rowid DESC
  }
} {3 28 17}
do_test boundary1-2.1.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY x
  }
} {17 28 3}
do_test boundary1-2.1.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.1.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.1.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45}
do_test boundary1-2.1.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY rowid DESC
  }
} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.1.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.1.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.1.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.1.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17}
do_test boundary1-2.1.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY rowid DESC
  }
} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.1.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.2.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=16384
  }
} {16 0000000000004000}
do_test boundary1-2.2.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000004000'
  }
} {16384 16}
do_test boundary1-2.2.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=16
  }
} {16384 0000000000004000}
do_test boundary1-2.2.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16384 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.2.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16384 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.2.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16384 ORDER BY rowid
  }
} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.2.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16384 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23}
do_test boundary1-2.2.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16384 ORDER BY x
  }
} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.2.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.2.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.2.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY rowid
  }
} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.2.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16}
do_test boundary1-2.2.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY x
  }
} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.2.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16384 ORDER BY a
  }
} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.2.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16384 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1}
do_test boundary1-2.2.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16384 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8}
do_test boundary1-2.2.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16384 ORDER BY rowid DESC
  }
} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.2.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16384 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.2.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.2.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1}
do_test boundary1-2.2.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16}
do_test boundary1-2.2.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY rowid DESC
  }
} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.2.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.3.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=4294967296
  }
} {36 0000000100000000}
do_test boundary1-2.3.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000100000000'
  }
} {4294967296 36}
do_test boundary1-2.3.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=36
  }
} {4294967296 0000000100000000}
do_test boundary1-2.3.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY a
  }
} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57}
do_test boundary1-2.3.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY a DESC
  }
} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3}
do_test boundary1-2.3.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY rowid
  }
} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.3.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39}
do_test boundary1-2.3.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY x
  }
} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.3.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY a
  }
} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57}
do_test boundary1-2.3.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY a DESC
  }
} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3}
do_test boundary1-2.3.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY rowid
  }
} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.3.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36}
do_test boundary1-2.3.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY x
  }
} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.3.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.3.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.3.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14}
do_test boundary1-2.3.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY rowid DESC
  }
} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.3.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.3.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.3.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.3.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36}
do_test boundary1-2.3.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY rowid DESC
  }
} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.3.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.4.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=16777216
  }
} {6 0000000001000000}
do_test boundary1-2.4.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000001000000'
  }
} {16777216 6}
do_test boundary1-2.4.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=6
  }
} {16777216 0000000001000000}
do_test boundary1-2.4.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY a
  }
} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.4.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3}
do_test boundary1-2.4.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY rowid
  }
} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.4.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12}
do_test boundary1-2.4.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY x
  }
} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.4.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY a
  }
} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.4.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3}
do_test boundary1-2.4.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY rowid
  }
} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.4.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6}
do_test boundary1-2.4.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY x
  }
} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.4.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY a
  }
} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.4.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1}
do_test boundary1-2.4.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9}
do_test boundary1-2.4.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY rowid DESC
  }
} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.4.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.4.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.4.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1}
do_test boundary1-2.4.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6}
do_test boundary1-2.4.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY rowid DESC
  }
} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.4.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.5.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-32769
  }
} {29 ffffffffffff7fff}
do_test boundary1-2.5.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffffff7fff'
  }
} {-32769 29}
do_test boundary1-2.5.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=29
  }
} {-32769 ffffffffffff7fff}
do_test boundary1-2.5.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32769 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.5.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32769 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.5.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32769 ORDER BY rowid
  }
} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.5.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32769 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32}
do_test boundary1-2.5.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32769 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38}
do_test boundary1-2.5.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.5.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.5.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY rowid
  }
} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.5.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29}
do_test boundary1-2.5.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38}
do_test boundary1-2.5.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32769 ORDER BY a
  }
} {1 2 11 21 37 44 47 55 58 63 64}
do_test boundary1-2.5.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32769 ORDER BY a DESC
  }
} {64 63 58 55 47 44 37 21 11 2 1}
do_test boundary1-2.5.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32769 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37}
do_test boundary1-2.5.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32769 ORDER BY rowid DESC
  }
} {37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.5.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32769 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37}
do_test boundary1-2.5.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY a
  }
} {1 2 11 21 29 37 44 47 55 58 63 64}
do_test boundary1-2.5.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY a DESC
  }
} {64 63 58 55 47 44 37 29 21 11 2 1}
do_test boundary1-2.5.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29}
do_test boundary1-2.5.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY rowid DESC
  }
} {29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.5.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29}
do_test boundary1-2.6.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-140737488355329
  }
} {21 ffff7fffffffffff}
do_test boundary1-2.6.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffff7fffffffffff'
  }
} {-140737488355329 21}
do_test boundary1-2.6.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=21
  }
} {-140737488355329 ffff7fffffffffff}
do_test boundary1-2.6.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63}
do_test boundary1-2.6.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY a DESC
  }
} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.6.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY rowid
  }
} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.6.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44}
do_test boundary1-2.6.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.6.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63}
do_test boundary1-2.6.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY a DESC
  }
} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.6.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY rowid
  }
} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.6.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21}
do_test boundary1-2.6.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.6.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY a
  }
} {2 55 64}
do_test boundary1-2.6.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY a DESC
  }
} {64 55 2}
do_test boundary1-2.6.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY rowid
  }
} {55 2 64}
do_test boundary1-2.6.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY rowid DESC
  }
} {64 2 55}
do_test boundary1-2.6.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY x
  }
} {55 2 64}
do_test boundary1-2.6.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY a
  }
} {2 21 55 64}
do_test boundary1-2.6.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY a DESC
  }
} {64 55 21 2}
do_test boundary1-2.6.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY rowid
  }
} {55 2 64 21}
do_test boundary1-2.6.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY rowid DESC
  }
} {21 64 2 55}
do_test boundary1-2.6.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY x
  }
} {55 2 64 21}
do_test boundary1-2.7.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=2
  }
} {41 0000000000000002}
do_test boundary1-2.7.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000002'
  }
} {2 41}
do_test boundary1-2.7.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=41
  }
} {2 0000000000000002}
do_test boundary1-2.7.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.7.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.7.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2 ORDER BY rowid
  }
} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.7.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5}
do_test boundary1-2.7.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2 ORDER BY x
  }
} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.7.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.7.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.7.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2 ORDER BY rowid
  }
} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.7.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41}
do_test boundary1-2.7.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2 ORDER BY x
  }
} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.7.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.7.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.7.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60}
do_test boundary1-2.7.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2 ORDER BY rowid DESC
  }
} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.7.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2 ORDER BY x
  }
} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.7.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.7.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.7.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41}
do_test boundary1-2.7.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2 ORDER BY rowid DESC
  }
} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.7.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2 ORDER BY x
  }
} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.8.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=4
  }
} {31 0000000000000004}
do_test boundary1-2.8.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000004'
  }
} {4 31}
do_test boundary1-2.8.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=31
  }
} {4 0000000000000004}
do_test boundary1-2.8.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4 ORDER BY a
  }
} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.8.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3}
do_test boundary1-2.8.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4 ORDER BY rowid
  }
} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.8.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4}
do_test boundary1-2.8.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4 ORDER BY x
  }
} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.8.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4 ORDER BY a
  }
} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.8.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3}
do_test boundary1-2.8.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4 ORDER BY rowid
  }
} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.8.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31}
do_test boundary1-2.8.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4 ORDER BY x
  }
} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.8.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4 ORDER BY a
  }
} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.8.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1}
do_test boundary1-2.8.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5}
do_test boundary1-2.8.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4 ORDER BY rowid DESC
  }
} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.8.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4 ORDER BY x
  }
} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.8.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4 ORDER BY a
  }
} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.8.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1}
do_test boundary1-2.8.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31}
do_test boundary1-2.8.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4 ORDER BY rowid DESC
  }
} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.8.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4 ORDER BY x
  }
} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.9.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=562949953421311
  }
} {13 0001ffffffffffff}
do_test boundary1-2.9.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0001ffffffffffff'
  }
} {562949953421311 13}
do_test boundary1-2.9.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=13
  }
} {562949953421311 0001ffffffffffff}
do_test boundary1-2.9.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY a
  }
} {3 17 27 28 43 45}
do_test boundary1-2.9.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY a DESC
  }
} {45 43 28 27 17 3}
do_test boundary1-2.9.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY rowid
  }
} {43 27 45 17 28 3}
do_test boundary1-2.9.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43}
do_test boundary1-2.9.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY x
  }
} {43 27 45 17 28 3}
do_test boundary1-2.9.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY a
  }
} {3 13 17 27 28 43 45}
do_test boundary1-2.9.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY a DESC
  }
} {45 43 28 27 17 13 3}
do_test boundary1-2.9.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY rowid
  }
} {13 43 27 45 17 28 3}
do_test boundary1-2.9.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13}
do_test boundary1-2.9.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY x
  }
} {13 43 27 45 17 28 3}
do_test boundary1-2.9.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.9.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.9.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26}
do_test boundary1-2.9.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY rowid DESC
  }
} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.9.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.9.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.9.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.9.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13}
do_test boundary1-2.9.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY rowid DESC
  }
} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.9.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.10.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=256
  }
} {61 0000000000000100}
do_test boundary1-2.10.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000100'
  }
} {256 61}
do_test boundary1-2.10.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=61
  }
} {256 0000000000000100}
do_test boundary1-2.10.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 256 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.10.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 256 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.10.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 256 ORDER BY rowid
  }
} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.10.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 256 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8}
do_test boundary1-2.10.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 256 ORDER BY x
  }
} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.10.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 256 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62}
do_test boundary1-2.10.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 256 ORDER BY a DESC
  }
} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.10.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 256 ORDER BY rowid
  }
} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.10.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 256 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61}
do_test boundary1-2.10.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 256 ORDER BY x
  }
} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.10.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 256 ORDER BY a
  }
} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.10.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 256 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1}
do_test boundary1-2.10.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 256 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30}
do_test boundary1-2.10.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 256 ORDER BY rowid DESC
  }
} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.10.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 256 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.10.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 256 ORDER BY a
  }
} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.10.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 256 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1}
do_test boundary1-2.10.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 256 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61}
do_test boundary1-2.10.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 256 ORDER BY rowid DESC
  }
} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.10.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 256 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.11.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=34359738368
  }
} {22 0000000800000000}
do_test boundary1-2.11.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000800000000'
  }
} {34359738368 22}
do_test boundary1-2.11.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=22
  }
} {34359738368 0000000800000000}
do_test boundary1-2.11.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57}
do_test boundary1-2.11.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY a DESC
  }
} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.11.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY rowid
  }
} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.11.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46}
do_test boundary1-2.11.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY x
  }
} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.11.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY a
  }
} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57}
do_test boundary1-2.11.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY a DESC
  }
} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3}
do_test boundary1-2.11.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY rowid
  }
} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.11.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22}
do_test boundary1-2.11.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY x
  }
} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.11.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.11.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.11.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39}
do_test boundary1-2.11.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY rowid DESC
  }
} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.11.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.11.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.11.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.11.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22}
do_test boundary1-2.11.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY rowid DESC
  }
} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.11.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.12.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=65536
  }
} {62 0000000000010000}
do_test boundary1-2.12.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000010000'
  }
} {65536 62}
do_test boundary1-2.12.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=62
  }
} {65536 0000000000010000}
do_test boundary1-2.12.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65536 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57}
do_test boundary1-2.12.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65536 ORDER BY a DESC
  }
} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.12.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65536 ORDER BY rowid
  }
} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.12.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65536 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15}
do_test boundary1-2.12.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65536 ORDER BY x
  }
} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.12.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62}
do_test boundary1-2.12.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY a DESC
  }
} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.12.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY rowid
  }
} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.12.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62}
do_test boundary1-2.12.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY x
  }
} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.12.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65536 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.12.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65536 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.12.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65536 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48}
do_test boundary1-2.12.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65536 ORDER BY rowid DESC
  }
} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.12.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65536 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.12.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.12.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.12.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62}
do_test boundary1-2.12.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY rowid DESC
  }
} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.12.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.13.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=268435456
  }
} {40 0000000010000000}
do_test boundary1-2.13.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000010000000'
  }
} {268435456 40}
do_test boundary1-2.13.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=40
  }
} {268435456 0000000010000000}
do_test boundary1-2.13.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY a
  }
} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57}
do_test boundary1-2.13.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY a DESC
  }
} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3}
do_test boundary1-2.13.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY rowid
  }
} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.13.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20}
do_test boundary1-2.13.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY x
  }
} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.13.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY a
  }
} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.13.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3}
do_test boundary1-2.13.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY rowid
  }
} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.13.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40}
do_test boundary1-2.13.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY x
  }
} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.13.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.13.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.13.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12}
do_test boundary1-2.13.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY rowid DESC
  }
} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.13.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.13.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.13.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.13.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40}
do_test boundary1-2.13.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY rowid DESC
  }
} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.13.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.14.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-140737488355328
  }
} {44 ffff800000000000}
do_test boundary1-2.14.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffff800000000000'
  }
} {-140737488355328 44}
do_test boundary1-2.14.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=44
  }
} {-140737488355328 ffff800000000000}
do_test boundary1-2.14.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63}
do_test boundary1-2.14.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY a DESC
  }
} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.14.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY rowid
  }
} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.14.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58}
do_test boundary1-2.14.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.14.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63}
do_test boundary1-2.14.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY a DESC
  }
} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.14.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY rowid
  }
} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.14.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44}
do_test boundary1-2.14.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.14.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY a
  }
} {2 21 55 64}
do_test boundary1-2.14.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY a DESC
  }
} {64 55 21 2}
do_test boundary1-2.14.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY rowid
  }
} {55 2 64 21}
do_test boundary1-2.14.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY rowid DESC
  }
} {21 64 2 55}
do_test boundary1-2.14.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY x
  }
} {55 2 64 21}
do_test boundary1-2.14.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY a
  }
} {2 21 44 55 64}
do_test boundary1-2.14.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY a DESC
  }
} {64 55 44 21 2}
do_test boundary1-2.14.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY rowid
  }
} {55 2 64 21 44}
do_test boundary1-2.14.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY rowid DESC
  }
} {44 21 64 2 55}
do_test boundary1-2.14.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY x
  }
} {55 2 64 21 44}
do_test boundary1-2.15.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=1099511627776
  }
} {19 0000010000000000}
do_test boundary1-2.15.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000010000000000'
  }
} {1099511627776 19}
do_test boundary1-2.15.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=19
  }
} {1099511627776 0000010000000000}
do_test boundary1-2.15.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY a
  }
} {3 7 10 13 17 25 26 27 28 34 43 45 56}
do_test boundary1-2.15.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY a DESC
  }
} {56 45 43 34 28 27 26 25 17 13 10 7 3}
do_test boundary1-2.15.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY rowid
  }
} {7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.15.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7}
do_test boundary1-2.15.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY x
  }
} {7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.15.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 43 45 56}
do_test boundary1-2.15.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY a DESC
  }
} {56 45 43 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.15.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY rowid
  }
} {19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.15.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19}
do_test boundary1-2.15.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY x
  }
} {19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.15.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64}
do_test boundary1-2.15.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.15.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57}
do_test boundary1-2.15.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY rowid DESC
  }
} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.15.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.15.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64}
do_test boundary1-2.15.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.15.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19}
do_test boundary1-2.15.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY rowid DESC
  }
} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.15.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.16.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY a
  }
} {}
do_test boundary1-2.16.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY a DESC
  }
} {}
do_test boundary1-2.16.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY rowid
  }
} {}
do_test boundary1-2.16.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY rowid DESC
  }
} {}
do_test boundary1-2.16.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY x
  }
} {}
do_test boundary1-2.16.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY a
  }
} {3}
do_test boundary1-2.16.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY a DESC
  }
} {3}
do_test boundary1-2.16.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY rowid
  }
} {3}
do_test boundary1-2.16.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY rowid DESC
  }
} {3}
do_test boundary1-2.16.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY x
  }
} {3}
do_test boundary1-2.16.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.16.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.16.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28}
do_test boundary1-2.16.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY rowid DESC
  }
} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.16.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.16.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.16.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.16.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.16.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.16.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.17.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=32768
  }
} {50 0000000000008000}
do_test boundary1-2.17.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000008000'
  }
} {32768 50}
do_test boundary1-2.17.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=50
  }
} {32768 0000000000008000}
do_test boundary1-2.17.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32768 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62}
do_test boundary1-2.17.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32768 ORDER BY a DESC
  }
} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.17.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32768 ORDER BY rowid
  }
} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.17.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32768 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48}
do_test boundary1-2.17.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32768 ORDER BY x
  }
} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.17.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.17.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.17.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY rowid
  }
} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.17.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50}
do_test boundary1-2.17.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY x
  }
} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.17.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32768 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.17.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32768 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.17.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32768 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23}
do_test boundary1-2.17.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32768 ORDER BY rowid DESC
  }
} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.17.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32768 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.17.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.17.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.17.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50}
do_test boundary1-2.17.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY rowid DESC
  }
} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.17.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.18.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-36028797018963968
  }
} {64 ff80000000000000}
do_test boundary1-2.18.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ff80000000000000'
  }
} {-36028797018963968 64}
do_test boundary1-2.18.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=64
  }
} {-36028797018963968 ff80000000000000}
do_test boundary1-2.18.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63}
do_test boundary1-2.18.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY a DESC
  }
} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.18.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY rowid
  }
} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.18.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21}
do_test boundary1-2.18.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.18.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.18.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.18.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY rowid
  }
} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.18.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64}
do_test boundary1-2.18.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.18.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY a
  }
} {2 55}
do_test boundary1-2.18.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY a DESC
  }
} {55 2}
do_test boundary1-2.18.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY rowid
  }
} {55 2}
do_test boundary1-2.18.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY rowid DESC
  }
} {2 55}
do_test boundary1-2.18.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY x
  }
} {55 2}
do_test boundary1-2.18.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY a
  }
} {2 55 64}
do_test boundary1-2.18.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY a DESC
  }
} {64 55 2}
do_test boundary1-2.18.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY rowid
  }
} {55 2 64}
do_test boundary1-2.18.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY rowid DESC
  }
} {64 2 55}
do_test boundary1-2.18.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY x
  }
} {55 2 64}
do_test boundary1-2.19.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=65535
  }
} {48 000000000000ffff}
do_test boundary1-2.19.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='000000000000ffff'
  }
} {65535 48}
do_test boundary1-2.19.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=48
  }
} {65535 000000000000ffff}
do_test boundary1-2.19.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65535 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62}
do_test boundary1-2.19.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65535 ORDER BY a DESC
  }
} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.19.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65535 ORDER BY rowid
  }
} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.19.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65535 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62}
do_test boundary1-2.19.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 65535 ORDER BY x
  }
} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.19.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62}
do_test boundary1-2.19.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY a DESC
  }
} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.19.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY rowid
  }
} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.19.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48}
do_test boundary1-2.19.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY x
  }
} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.19.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65535 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.19.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65535 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.19.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65535 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50}
do_test boundary1-2.19.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65535 ORDER BY rowid DESC
  }
} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.19.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 65535 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.19.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.19.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.19.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48}
do_test boundary1-2.19.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY rowid DESC
  }
} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.19.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.20.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=4294967295
  }
} {14 00000000ffffffff}
do_test boundary1-2.20.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00000000ffffffff'
  }
} {4294967295 14}
do_test boundary1-2.20.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=14
  }
} {4294967295 00000000ffffffff}
do_test boundary1-2.20.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY a
  }
} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57}
do_test boundary1-2.20.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY a DESC
  }
} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3}
do_test boundary1-2.20.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY rowid
  }
} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.20.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36}
do_test boundary1-2.20.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY x
  }
} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.20.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY a
  }
} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57}
do_test boundary1-2.20.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY a DESC
  }
} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3}
do_test boundary1-2.20.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY rowid
  }
} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.20.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14}
do_test boundary1-2.20.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY x
  }
} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.20.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.20.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.20.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51}
do_test boundary1-2.20.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY rowid DESC
  }
} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.20.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.20.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.20.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.20.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14}
do_test boundary1-2.20.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY rowid DESC
  }
} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.20.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.21.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=1099511627775
  }
} {57 000000ffffffffff}
do_test boundary1-2.21.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='000000ffffffffff'
  }
} {1099511627775 57}
do_test boundary1-2.21.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=57
  }
} {1099511627775 000000ffffffffff}
do_test boundary1-2.21.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 43 45 56}
do_test boundary1-2.21.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY a DESC
  }
} {56 45 43 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.21.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY rowid
  }
} {19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.21.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19}
do_test boundary1-2.21.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY x
  }
} {19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.21.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57}
do_test boundary1-2.21.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY a DESC
  }
} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.21.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY rowid
  }
} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.21.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57}
do_test boundary1-2.21.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY x
  }
} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.21.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.21.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.21.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35}
do_test boundary1-2.21.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY rowid DESC
  }
} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.21.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.21.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64}
do_test boundary1-2.21.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.21.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57}
do_test boundary1-2.21.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY rowid DESC
  }
} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.21.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.22.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-8388608
  }
} {37 ffffffffff800000}
do_test boundary1-2.22.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffff800000'
  }
} {-8388608 37}
do_test boundary1-2.22.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=37
  }
} {-8388608 ffffffffff800000}
do_test boundary1-2.22.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.22.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.22.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY rowid
  }
} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.22.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29}
do_test boundary1-2.22.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38}
do_test boundary1-2.22.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.22.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.22.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY rowid
  }
} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.22.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37}
do_test boundary1-2.22.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38}
do_test boundary1-2.22.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY a
  }
} {1 2 11 21 44 47 55 58 63 64}
do_test boundary1-2.22.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY a DESC
  }
} {64 63 58 55 47 44 21 11 2 1}
do_test boundary1-2.22.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1}
do_test boundary1-2.22.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY rowid DESC
  }
} {1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.22.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1}
do_test boundary1-2.22.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY a
  }
} {1 2 11 21 37 44 47 55 58 63 64}
do_test boundary1-2.22.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY a DESC
  }
} {64 63 58 55 47 44 37 21 11 2 1}
do_test boundary1-2.22.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37}
do_test boundary1-2.22.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY rowid DESC
  }
} {37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.22.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37}
do_test boundary1-2.23.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=549755813888
  }
} {35 0000008000000000}
do_test boundary1-2.23.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000008000000000'
  }
} {549755813888 35}
do_test boundary1-2.23.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=35
  }
} {549755813888 0000008000000000}
do_test boundary1-2.23.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57}
do_test boundary1-2.23.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY a DESC
  }
} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.23.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY rowid
  }
} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.23.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57}
do_test boundary1-2.23.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY x
  }
} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.23.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57}
do_test boundary1-2.23.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY a DESC
  }
} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.23.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY rowid
  }
} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.23.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35}
do_test boundary1-2.23.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY x
  }
} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.23.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.23.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.23.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46}
do_test boundary1-2.23.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY rowid DESC
  }
} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.23.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.23.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.23.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.23.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35}
do_test boundary1-2.23.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY rowid DESC
  }
} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.23.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.24.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=8388607
  }
} {18 00000000007fffff}
do_test boundary1-2.24.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00000000007fffff'
  }
} {8388607 18}
do_test boundary1-2.24.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=18
  }
} {8388607 00000000007fffff}
do_test boundary1-2.24.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.24.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.24.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY rowid
  }
} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.24.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24}
do_test boundary1-2.24.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY x
  }
} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.24.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.24.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.24.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY rowid
  }
} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.24.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18}
do_test boundary1-2.24.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY x
  }
} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.24.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.24.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1}
do_test boundary1-2.24.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42}
do_test boundary1-2.24.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY rowid DESC
  }
} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.24.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.24.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.24.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1}
do_test boundary1-2.24.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18}
do_test boundary1-2.24.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY rowid DESC
  }
} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.24.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.25.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-3
  }
} {52 fffffffffffffffd}
do_test boundary1-2.25.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='fffffffffffffffd'
  }
} {-3 52}
do_test boundary1-2.25.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=52
  }
} {-3 fffffffffffffffd}
do_test boundary1-2.25.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -3 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62}
do_test boundary1-2.25.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -3 ORDER BY a DESC
  }
} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.25.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -3 ORDER BY rowid
  }
} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.25.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -3 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33}
do_test boundary1-2.25.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -3 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38}
do_test boundary1-2.25.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -3 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62}
do_test boundary1-2.25.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -3 ORDER BY a DESC
  }
} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.25.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -3 ORDER BY rowid
  }
} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.25.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -3 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52}
do_test boundary1-2.25.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -3 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38}
do_test boundary1-2.25.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -3 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64}
do_test boundary1-2.25.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -3 ORDER BY a DESC
  }
} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.25.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -3 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53}
do_test boundary1-2.25.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -3 ORDER BY rowid DESC
  }
} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.25.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -3 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53}
do_test boundary1-2.25.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -3 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64}
do_test boundary1-2.25.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -3 ORDER BY a DESC
  }
} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.25.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -3 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52}
do_test boundary1-2.25.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -3 ORDER BY rowid DESC
  }
} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.25.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -3 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52}
do_test boundary1-2.26.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=0
  }
} {59 0000000000000000}
do_test boundary1-2.26.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000000'
  }
} {0 59}
do_test boundary1-2.26.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=59
  }
} {0 0000000000000000}
do_test boundary1-2.26.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 0 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62}
do_test boundary1-2.26.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 0 ORDER BY a DESC
  }
} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.26.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 0 ORDER BY rowid
  }
} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.26.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 0 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60}
do_test boundary1-2.26.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 0 ORDER BY x
  }
} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.26.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 0 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62}
do_test boundary1-2.26.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 0 ORDER BY a DESC
  }
} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.26.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 0 ORDER BY rowid
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.26.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 0 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59}
do_test boundary1-2.26.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 0 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.26.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 0 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64}
do_test boundary1-2.26.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 0 ORDER BY a DESC
  }
} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.26.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 0 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.26.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 0 ORDER BY rowid DESC
  }
} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.26.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 0 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.26.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 0 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64}
do_test boundary1-2.26.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 0 ORDER BY a DESC
  }
} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.26.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 0 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59}
do_test boundary1-2.26.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 0 ORDER BY rowid DESC
  }
} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.26.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 0 ORDER BY x
  }
} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.27.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-1
  }
} {38 ffffffffffffffff}
do_test boundary1-2.27.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffffffffff'
  }
} {-1 38}
do_test boundary1-2.27.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=38
  }
} {-1 ffffffffffffffff}
do_test boundary1-2.27.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -1 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62}
do_test boundary1-2.27.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -1 ORDER BY a DESC
  }
} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.27.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -1 ORDER BY rowid
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.27.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -1 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59}
do_test boundary1-2.27.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -1 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.27.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -1 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62}
do_test boundary1-2.27.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -1 ORDER BY a DESC
  }
} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.27.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -1 ORDER BY rowid
  }
} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.27.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -1 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38}
do_test boundary1-2.27.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -1 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38}
do_test boundary1-2.27.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -1 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64}
do_test boundary1-2.27.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -1 ORDER BY a DESC
  }
} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1}
do_test boundary1-2.27.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -1 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33}
do_test boundary1-2.27.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -1 ORDER BY rowid DESC
  }
} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.27.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -1 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33}
do_test boundary1-2.27.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -1 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64}
do_test boundary1-2.27.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -1 ORDER BY a DESC
  }
} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.27.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -1 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.27.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -1 ORDER BY rowid DESC
  }
} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.27.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -1 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.28.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-2
  }
} {33 fffffffffffffffe}
do_test boundary1-2.28.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='fffffffffffffffe'
  }
} {-2 33}
do_test boundary1-2.28.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=33
  }
} {-2 fffffffffffffffe}
do_test boundary1-2.28.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62}
do_test boundary1-2.28.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2 ORDER BY a DESC
  }
} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.28.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2 ORDER BY rowid
  }
} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.28.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38}
do_test boundary1-2.28.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38}
do_test boundary1-2.28.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62}
do_test boundary1-2.28.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2 ORDER BY a DESC
  }
} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.28.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2 ORDER BY rowid
  }
} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.28.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33}
do_test boundary1-2.28.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38}
do_test boundary1-2.28.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64}
do_test boundary1-2.28.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2 ORDER BY a DESC
  }
} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.28.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52}
do_test boundary1-2.28.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2 ORDER BY rowid DESC
  }
} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.28.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52}
do_test boundary1-2.28.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64}
do_test boundary1-2.28.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2 ORDER BY a DESC
  }
} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1}
do_test boundary1-2.28.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33}
do_test boundary1-2.28.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2 ORDER BY rowid DESC
  }
} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.28.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33}
do_test boundary1-2.29.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=2097152
  }
} {42 0000000000200000}
do_test boundary1-2.29.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000200000'
  }
} {2097152 42}
do_test boundary1-2.29.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=42
  }
} {2097152 0000000000200000}
do_test boundary1-2.29.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.29.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.29.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY rowid
  }
} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.29.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18}
do_test boundary1-2.29.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY x
  }
} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.29.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57}
do_test boundary1-2.29.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY a DESC
  }
} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.29.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY rowid
  }
} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.29.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42}
do_test boundary1-2.29.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY x
  }
} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.29.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.29.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1}
do_test boundary1-2.29.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15}
do_test boundary1-2.29.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY rowid DESC
  }
} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.29.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.29.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.29.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1}
do_test boundary1-2.29.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42}
do_test boundary1-2.29.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY rowid DESC
  }
} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.29.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.30.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=128
  }
} {49 0000000000000080}
do_test boundary1-2.30.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000080'
  }
} {128 49}
do_test boundary1-2.30.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=49
  }
} {128 0000000000000080}
do_test boundary1-2.30.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 128 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62}
do_test boundary1-2.30.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 128 ORDER BY a DESC
  }
} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.30.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 128 ORDER BY rowid
  }
} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.30.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 128 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30}
do_test boundary1-2.30.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 128 ORDER BY x
  }
} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.30.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 128 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.30.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 128 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.30.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 128 ORDER BY rowid
  }
} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.30.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 128 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49}
do_test boundary1-2.30.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 128 ORDER BY x
  }
} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.30.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 128 ORDER BY a
  }
} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.30.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 128 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1}
do_test boundary1-2.30.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 128 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4}
do_test boundary1-2.30.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 128 ORDER BY rowid DESC
  }
} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.30.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 128 ORDER BY x
  }
} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.30.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 128 ORDER BY a
  }
} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.30.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 128 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1}
do_test boundary1-2.30.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 128 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49}
do_test boundary1-2.30.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 128 ORDER BY rowid DESC
  }
} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.30.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 128 ORDER BY x
  }
} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.31.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=255
  }
} {30 00000000000000ff}
do_test boundary1-2.31.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00000000000000ff'
  }
} {255 30}
do_test boundary1-2.31.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=30
  }
} {255 00000000000000ff}
do_test boundary1-2.31.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 255 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62}
do_test boundary1-2.31.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 255 ORDER BY a DESC
  }
} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.31.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 255 ORDER BY rowid
  }
} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.31.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 255 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61}
do_test boundary1-2.31.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 255 ORDER BY x
  }
} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.31.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 255 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62}
do_test boundary1-2.31.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 255 ORDER BY a DESC
  }
} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.31.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 255 ORDER BY rowid
  }
} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.31.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 255 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30}
do_test boundary1-2.31.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 255 ORDER BY x
  }
} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.31.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 255 ORDER BY a
  }
} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.31.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 255 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1}
do_test boundary1-2.31.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 255 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49}
do_test boundary1-2.31.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 255 ORDER BY rowid DESC
  }
} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.31.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 255 ORDER BY x
  }
} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.31.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 255 ORDER BY a
  }
} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.31.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 255 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1}
do_test boundary1-2.31.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 255 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30}
do_test boundary1-2.31.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 255 ORDER BY rowid DESC
  }
} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.31.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 255 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.32.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-2147483648
  }
} {11 ffffffff80000000}
do_test boundary1-2.32.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffff80000000'
  }
} {-2147483648 11}
do_test boundary1-2.32.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=11
  }
} {-2147483648 ffffffff80000000}
do_test boundary1-2.32.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.32.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.32.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY rowid
  }
} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.32.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1}
do_test boundary1-2.32.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.32.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.32.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.32.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY rowid
  }
} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.32.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11}
do_test boundary1-2.32.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.32.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY a
  }
} {2 21 44 47 55 58 63 64}
do_test boundary1-2.32.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY a DESC
  }
} {64 63 58 55 47 44 21 2}
do_test boundary1-2.32.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47}
do_test boundary1-2.32.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY rowid DESC
  }
} {47 63 58 44 21 64 2 55}
do_test boundary1-2.32.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY x
  }
} {55 2 64 21 44 58 63 47}
do_test boundary1-2.32.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY a
  }
} {2 11 21 44 47 55 58 63 64}
do_test boundary1-2.32.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY a DESC
  }
} {64 63 58 55 47 44 21 11 2}
do_test boundary1-2.32.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11}
do_test boundary1-2.32.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY rowid DESC
  }
} {11 47 63 58 44 21 64 2 55}
do_test boundary1-2.32.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11}
do_test boundary1-2.33.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=34359738367
  }
} {39 00000007ffffffff}
do_test boundary1-2.33.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00000007ffffffff'
  }
} {34359738367 39}
do_test boundary1-2.33.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=39
  }
} {34359738367 00000007ffffffff}
do_test boundary1-2.33.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY a
  }
} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57}
do_test boundary1-2.33.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY a DESC
  }
} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3}
do_test boundary1-2.33.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY rowid
  }
} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.33.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22}
do_test boundary1-2.33.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY x
  }
} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.33.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY a
  }
} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57}
do_test boundary1-2.33.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY a DESC
  }
} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3}
do_test boundary1-2.33.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY rowid
  }
} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.33.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39}
do_test boundary1-2.33.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY x
  }
} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.33.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.33.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.33.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36}
do_test boundary1-2.33.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY rowid DESC
  }
} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.33.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.33.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.33.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.33.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39}
do_test boundary1-2.33.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY rowid DESC
  }
} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.33.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.34.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-549755813889
  }
} {58 ffffff7fffffffff}
do_test boundary1-2.34.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffff7fffffffff'
  }
} {-549755813889 58}
do_test boundary1-2.34.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=58
  }
} {-549755813889 ffffff7fffffffff}
do_test boundary1-2.34.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63}
do_test boundary1-2.34.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY a DESC
  }
} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.34.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY rowid
  }
} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.34.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63}
do_test boundary1-2.34.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.34.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63}
do_test boundary1-2.34.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY a DESC
  }
} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.34.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY rowid
  }
} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.34.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58}
do_test boundary1-2.34.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.34.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY a
  }
} {2 21 44 55 64}
do_test boundary1-2.34.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY a DESC
  }
} {64 55 44 21 2}
do_test boundary1-2.34.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY rowid
  }
} {55 2 64 21 44}
do_test boundary1-2.34.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY rowid DESC
  }
} {44 21 64 2 55}
do_test boundary1-2.34.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY x
  }
} {55 2 64 21 44}
do_test boundary1-2.34.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY a
  }
} {2 21 44 55 58 64}
do_test boundary1-2.34.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY a DESC
  }
} {64 58 55 44 21 2}
do_test boundary1-2.34.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY rowid
  }
} {55 2 64 21 44 58}
do_test boundary1-2.34.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY rowid DESC
  }
} {58 44 21 64 2 55}
do_test boundary1-2.34.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY x
  }
} {55 2 64 21 44 58}
do_test boundary1-2.35.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-32768
  }
} {32 ffffffffffff8000}
do_test boundary1-2.35.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffffff8000'
  }
} {-32768 32}
do_test boundary1-2.35.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=32
  }
} {-32768 ffffffffffff8000}
do_test boundary1-2.35.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32768 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.35.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32768 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.35.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32768 ORDER BY rowid
  }
} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.35.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32768 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54}
do_test boundary1-2.35.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -32768 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38}
do_test boundary1-2.35.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.35.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.35.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY rowid
  }
} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.35.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32}
do_test boundary1-2.35.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38}
do_test boundary1-2.35.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32768 ORDER BY a
  }
} {1 2 11 21 29 37 44 47 55 58 63 64}
do_test boundary1-2.35.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32768 ORDER BY a DESC
  }
} {64 63 58 55 47 44 37 29 21 11 2 1}
do_test boundary1-2.35.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32768 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29}
do_test boundary1-2.35.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32768 ORDER BY rowid DESC
  }
} {29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.35.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -32768 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29}
do_test boundary1-2.35.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 55 58 63 64}
do_test boundary1-2.35.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY a DESC
  }
} {64 63 58 55 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.35.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32}
do_test boundary1-2.35.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY rowid DESC
  }
} {32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.35.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32}
do_test boundary1-2.36.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=2147483647
  }
} {20 000000007fffffff}
do_test boundary1-2.36.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='000000007fffffff'
  }
} {2147483647 20}
do_test boundary1-2.36.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=20
  }
} {2147483647 000000007fffffff}
do_test boundary1-2.36.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY a
  }
} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57}
do_test boundary1-2.36.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY a DESC
  }
} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3}
do_test boundary1-2.36.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY rowid
  }
} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.36.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51}
do_test boundary1-2.36.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY x
  }
} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.36.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY a
  }
} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57}
do_test boundary1-2.36.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY a DESC
  }
} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3}
do_test boundary1-2.36.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY rowid
  }
} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.36.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20}
do_test boundary1-2.36.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY x
  }
} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.36.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.36.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.36.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40}
do_test boundary1-2.36.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY rowid DESC
  }
} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.36.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.36.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.36.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.36.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20}
do_test boundary1-2.36.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY rowid DESC
  }
} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.36.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.37.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-129
  }
} {54 ffffffffffffff7f}
do_test boundary1-2.37.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffffffff7f'
  }
} {-129 54}
do_test boundary1-2.37.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=54
  }
} {-129 ffffffffffffff7f}
do_test boundary1-2.37.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -129 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62}
do_test boundary1-2.37.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -129 ORDER BY a DESC
  }
} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.37.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -129 ORDER BY rowid
  }
} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.37.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -129 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53}
do_test boundary1-2.37.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -129 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38}
do_test boundary1-2.37.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -129 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.37.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -129 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.37.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -129 ORDER BY rowid
  }
} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.37.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -129 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54}
do_test boundary1-2.37.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -129 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38}
do_test boundary1-2.37.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -129 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 55 58 63 64}
do_test boundary1-2.37.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -129 ORDER BY a DESC
  }
} {64 63 58 55 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.37.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -129 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32}
do_test boundary1-2.37.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -129 ORDER BY rowid DESC
  }
} {32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.37.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -129 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32}
do_test boundary1-2.37.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -129 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 54 55 58 63 64}
do_test boundary1-2.37.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -129 ORDER BY a DESC
  }
} {64 63 58 55 54 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.37.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -129 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54}
do_test boundary1-2.37.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -129 ORDER BY rowid DESC
  }
} {54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.37.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -129 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54}
do_test boundary1-2.38.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-128
  }
} {53 ffffffffffffff80}
do_test boundary1-2.38.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffffffff80'
  }
} {-128 53}
do_test boundary1-2.38.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=53
  }
} {-128 ffffffffffffff80}
do_test boundary1-2.38.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -128 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62}
do_test boundary1-2.38.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -128 ORDER BY a DESC
  }
} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.38.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -128 ORDER BY rowid
  }
} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.38.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -128 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52}
do_test boundary1-2.38.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -128 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38}
do_test boundary1-2.38.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -128 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62}
do_test boundary1-2.38.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -128 ORDER BY a DESC
  }
} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.38.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -128 ORDER BY rowid
  }
} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.38.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -128 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53}
do_test boundary1-2.38.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -128 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38}
do_test boundary1-2.38.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -128 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 54 55 58 63 64}
do_test boundary1-2.38.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -128 ORDER BY a DESC
  }
} {64 63 58 55 54 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.38.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -128 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54}
do_test boundary1-2.38.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -128 ORDER BY rowid DESC
  }
} {54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.38.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -128 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54}
do_test boundary1-2.38.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -128 ORDER BY a
  }
} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64}
do_test boundary1-2.38.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -128 ORDER BY a DESC
  }
} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1}
do_test boundary1-2.38.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -128 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53}
do_test boundary1-2.38.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -128 ORDER BY rowid DESC
  }
} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.38.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -128 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53}
do_test boundary1-2.39.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=72057594037927936
  }
} {28 0100000000000000}
do_test boundary1-2.39.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0100000000000000'
  }
} {72057594037927936 28}
do_test boundary1-2.39.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=28
  }
} {72057594037927936 0100000000000000}
do_test boundary1-2.39.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY a
  }
} {3}
do_test boundary1-2.39.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY a DESC
  }
} {3}
do_test boundary1-2.39.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY rowid
  }
} {3}
do_test boundary1-2.39.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY rowid DESC
  }
} {3}
do_test boundary1-2.39.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY x
  }
} {3}
do_test boundary1-2.39.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY a
  }
} {3 28}
do_test boundary1-2.39.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY a DESC
  }
} {28 3}
do_test boundary1-2.39.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY rowid
  }
} {28 3}
do_test boundary1-2.39.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY rowid DESC
  }
} {3 28}
do_test boundary1-2.39.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY x
  }
} {28 3}
do_test boundary1-2.39.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.39.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.39.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17}
do_test boundary1-2.39.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY rowid DESC
  }
} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.39.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.39.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.39.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.39.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28}
do_test boundary1-2.39.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY rowid DESC
  }
} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.39.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.40.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=2147483648
  }
} {51 0000000080000000}
do_test boundary1-2.40.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000080000000'
  }
} {2147483648 51}
do_test boundary1-2.40.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=51
  }
} {2147483648 0000000080000000}
do_test boundary1-2.40.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY a
  }
} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57}
do_test boundary1-2.40.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY a DESC
  }
} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3}
do_test boundary1-2.40.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY rowid
  }
} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.40.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14}
do_test boundary1-2.40.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY x
  }
} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.40.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY a
  }
} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57}
do_test boundary1-2.40.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY a DESC
  }
} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3}
do_test boundary1-2.40.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY rowid
  }
} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.40.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51}
do_test boundary1-2.40.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY x
  }
} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.40.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.40.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.40.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20}
do_test boundary1-2.40.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY rowid DESC
  }
} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.40.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.40.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.40.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.40.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51}
do_test boundary1-2.40.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY rowid DESC
  }
} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.40.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.41.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=549755813887
  }
} {46 0000007fffffffff}
do_test boundary1-2.41.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000007fffffffff'
  }
} {549755813887 46}
do_test boundary1-2.41.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=46
  }
} {549755813887 0000007fffffffff}
do_test boundary1-2.41.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57}
do_test boundary1-2.41.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY a DESC
  }
} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.41.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY rowid
  }
} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.41.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35}
do_test boundary1-2.41.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY x
  }
} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.41.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY a
  }
} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57}
do_test boundary1-2.41.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY a DESC
  }
} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3}
do_test boundary1-2.41.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY rowid
  }
} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.41.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46}
do_test boundary1-2.41.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY x
  }
} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.41.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.41.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.41.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22}
do_test boundary1-2.41.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY rowid DESC
  }
} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.41.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.41.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.41.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.41.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46}
do_test boundary1-2.41.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY rowid DESC
  }
} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.41.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.42.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-549755813888
  }
} {63 ffffff8000000000}
do_test boundary1-2.42.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffff8000000000'
  }
} {-549755813888 63}
do_test boundary1-2.42.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=63
  }
} {-549755813888 ffffff8000000000}
do_test boundary1-2.42.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.42.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.42.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY rowid
  }
} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.42.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47}
do_test boundary1-2.42.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.42.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63}
do_test boundary1-2.42.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY a DESC
  }
} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.42.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY rowid
  }
} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.42.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63}
do_test boundary1-2.42.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.42.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY a
  }
} {2 21 44 55 58 64}
do_test boundary1-2.42.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY a DESC
  }
} {64 58 55 44 21 2}
do_test boundary1-2.42.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY rowid
  }
} {55 2 64 21 44 58}
do_test boundary1-2.42.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY rowid DESC
  }
} {58 44 21 64 2 55}
do_test boundary1-2.42.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY x
  }
} {55 2 64 21 44 58}
do_test boundary1-2.42.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY a
  }
} {2 21 44 55 58 63 64}
do_test boundary1-2.42.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY a DESC
  }
} {64 63 58 55 44 21 2}
do_test boundary1-2.42.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY rowid
  }
} {55 2 64 21 44 58 63}
do_test boundary1-2.42.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY rowid DESC
  }
} {63 58 44 21 64 2 55}
do_test boundary1-2.42.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY x
  }
} {55 2 64 21 44 58 63}
do_test boundary1-2.43.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=281474976710655
  }
} {10 0000ffffffffffff}
do_test boundary1-2.43.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000ffffffffffff'
  }
} {281474976710655 10}
do_test boundary1-2.43.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=10
  }
} {281474976710655 0000ffffffffffff}
do_test boundary1-2.43.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY a
  }
} {3 13 17 26 27 28 43 45}
do_test boundary1-2.43.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY a DESC
  }
} {45 43 28 27 26 17 13 3}
do_test boundary1-2.43.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY rowid
  }
} {26 13 43 27 45 17 28 3}
do_test boundary1-2.43.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26}
do_test boundary1-2.43.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY x
  }
} {26 13 43 27 45 17 28 3}
do_test boundary1-2.43.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY a
  }
} {3 10 13 17 26 27 28 43 45}
do_test boundary1-2.43.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY a DESC
  }
} {45 43 28 27 26 17 13 10 3}
do_test boundary1-2.43.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY rowid
  }
} {10 26 13 43 27 45 17 28 3}
do_test boundary1-2.43.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10}
do_test boundary1-2.43.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY x
  }
} {10 26 13 43 27 45 17 28 3}
do_test boundary1-2.43.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.43.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.43.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34}
do_test boundary1-2.43.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY rowid DESC
  }
} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.43.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.43.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.43.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.43.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10}
do_test boundary1-2.43.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY rowid DESC
  }
} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.43.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.44.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=4398046511103
  }
} {7 000003ffffffffff}
do_test boundary1-2.44.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='000003ffffffffff'
  }
} {4398046511103 7}
do_test boundary1-2.44.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=7
  }
} {4398046511103 000003ffffffffff}
do_test boundary1-2.44.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY a
  }
} {3 10 13 17 25 26 27 28 34 43 45 56}
do_test boundary1-2.44.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY a DESC
  }
} {56 45 43 34 28 27 26 25 17 13 10 3}
do_test boundary1-2.44.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY rowid
  }
} {56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.44.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56}
do_test boundary1-2.44.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY x
  }
} {56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.44.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY a
  }
} {3 7 10 13 17 25 26 27 28 34 43 45 56}
do_test boundary1-2.44.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY a DESC
  }
} {56 45 43 34 28 27 26 25 17 13 10 7 3}
do_test boundary1-2.44.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY rowid
  }
} {7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.44.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7}
do_test boundary1-2.44.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY x
  }
} {7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.44.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64}
do_test boundary1-2.44.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.44.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19}
do_test boundary1-2.44.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY rowid DESC
  }
} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.44.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.44.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64}
do_test boundary1-2.44.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.44.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7}
do_test boundary1-2.44.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY rowid DESC
  }
} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.44.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.45.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=268435455
  }
} {12 000000000fffffff}
do_test boundary1-2.45.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='000000000fffffff'
  }
} {268435455 12}
do_test boundary1-2.45.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=12
  }
} {268435455 000000000fffffff}
do_test boundary1-2.45.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY a
  }
} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.45.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3}
do_test boundary1-2.45.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY rowid
  }
} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.45.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40}
do_test boundary1-2.45.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY x
  }
} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.45.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY a
  }
} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.45.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3}
do_test boundary1-2.45.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY rowid
  }
} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.45.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12}
do_test boundary1-2.45.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY x
  }
} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.45.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.45.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1}
do_test boundary1-2.45.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6}
do_test boundary1-2.45.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY rowid DESC
  }
} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.45.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.45.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY a
  }
} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.45.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1}
do_test boundary1-2.45.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12}
do_test boundary1-2.45.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY rowid DESC
  }
} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.45.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.46.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-9223372036854775808
  }
} {55 8000000000000000}
do_test boundary1-2.46.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='8000000000000000'
  }
} {-9223372036854775808 55}
do_test boundary1-2.46.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=55
  }
} {-9223372036854775808 8000000000000000}
do_test boundary1-2.46.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.46.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.46.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY rowid
  }
} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.46.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2}
do_test boundary1-2.46.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.46.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.46.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.46.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.46.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.46.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.46.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY a
  }
} {}
do_test boundary1-2.46.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY a DESC
  }
} {}
do_test boundary1-2.46.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY rowid
  }
} {}
do_test boundary1-2.46.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY rowid DESC
  }
} {}
do_test boundary1-2.46.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY x
  }
} {}
do_test boundary1-2.46.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY a
  }
} {55}
do_test boundary1-2.46.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY a DESC
  }
} {55}
do_test boundary1-2.46.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY rowid
  }
} {55}
do_test boundary1-2.46.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY rowid DESC
  }
} {55}
do_test boundary1-2.46.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY x
  }
} {55}
do_test boundary1-2.47.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=562949953421312
  }
} {43 0002000000000000}
do_test boundary1-2.47.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0002000000000000'
  }
} {562949953421312 43}
do_test boundary1-2.47.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=43
  }
} {562949953421312 0002000000000000}
do_test boundary1-2.47.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY a
  }
} {3 17 27 28 45}
do_test boundary1-2.47.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY a DESC
  }
} {45 28 27 17 3}
do_test boundary1-2.47.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY rowid
  }
} {27 45 17 28 3}
do_test boundary1-2.47.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY rowid DESC
  }
} {3 28 17 45 27}
do_test boundary1-2.47.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY x
  }
} {27 45 17 28 3}
do_test boundary1-2.47.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY a
  }
} {3 17 27 28 43 45}
do_test boundary1-2.47.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY a DESC
  }
} {45 43 28 27 17 3}
do_test boundary1-2.47.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY rowid
  }
} {43 27 45 17 28 3}
do_test boundary1-2.47.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43}
do_test boundary1-2.47.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY x
  }
} {43 27 45 17 28 3}
do_test boundary1-2.47.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.47.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.47.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13}
do_test boundary1-2.47.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY rowid DESC
  }
} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.47.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.47.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.47.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.47.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43}
do_test boundary1-2.47.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY rowid DESC
  }
} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.47.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.48.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-8388609
  }
} {1 ffffffffff7fffff}
do_test boundary1-2.48.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffffff7fffff'
  }
} {-8388609 1}
do_test boundary1-2.48.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=1
  }
} {-8388609 ffffffffff7fffff}
do_test boundary1-2.48.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.48.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.48.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY rowid
  }
} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.48.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37}
do_test boundary1-2.48.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38}
do_test boundary1-2.48.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.48.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.48.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY rowid
  }
} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.48.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1}
do_test boundary1-2.48.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.48.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY a
  }
} {2 11 21 44 47 55 58 63 64}
do_test boundary1-2.48.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY a DESC
  }
} {64 63 58 55 47 44 21 11 2}
do_test boundary1-2.48.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11}
do_test boundary1-2.48.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY rowid DESC
  }
} {11 47 63 58 44 21 64 2 55}
do_test boundary1-2.48.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11}
do_test boundary1-2.48.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY a
  }
} {1 2 11 21 44 47 55 58 63 64}
do_test boundary1-2.48.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY a DESC
  }
} {64 63 58 55 47 44 21 11 2 1}
do_test boundary1-2.48.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1}
do_test boundary1-2.48.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY rowid DESC
  }
} {1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.48.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY x
  }
} {55 2 64 21 44 58 63 47 11 1}
do_test boundary1-2.49.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=16777215
  }
} {9 0000000000ffffff}
do_test boundary1-2.49.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000ffffff'
  }
} {16777215 9}
do_test boundary1-2.49.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=9
  }
} {16777215 0000000000ffffff}
do_test boundary1-2.49.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY a
  }
} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.49.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3}
do_test boundary1-2.49.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY rowid
  }
} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.49.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6}
do_test boundary1-2.49.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY x
  }
} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.49.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.49.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.49.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY rowid
  }
} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.49.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9}
do_test boundary1-2.49.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY x
  }
} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.49.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.49.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1}
do_test boundary1-2.49.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24}
do_test boundary1-2.49.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY rowid DESC
  }
} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.49.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.49.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY a
  }
} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.49.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1}
do_test boundary1-2.49.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9}
do_test boundary1-2.49.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY rowid DESC
  }
} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.49.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.50.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=8388608
  }
} {24 0000000000800000}
do_test boundary1-2.50.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000800000'
  }
} {8388608 24}
do_test boundary1-2.50.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=24
  }
} {8388608 0000000000800000}
do_test boundary1-2.50.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.50.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.50.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY rowid
  }
} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.50.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9}
do_test boundary1-2.50.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY x
  }
} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.50.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57}
do_test boundary1-2.50.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY a DESC
  }
} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.50.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY rowid
  }
} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.50.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24}
do_test boundary1-2.50.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY x
  }
} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.50.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.50.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1}
do_test boundary1-2.50.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18}
do_test boundary1-2.50.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY rowid DESC
  }
} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.50.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.50.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.50.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1}
do_test boundary1-2.50.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24}
do_test boundary1-2.50.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY rowid DESC
  }
} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.50.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.51.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=16383
  }
} {8 0000000000003fff}
do_test boundary1-2.51.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000003fff'
  }
} {16383 8}
do_test boundary1-2.51.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=8
  }
} {16383 0000000000003fff}
do_test boundary1-2.51.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16383 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.51.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16383 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.51.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16383 ORDER BY rowid
  }
} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.51.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16383 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16}
do_test boundary1-2.51.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 16383 ORDER BY x
  }
} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.51.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.51.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.51.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY rowid
  }
} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.51.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8}
do_test boundary1-2.51.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY x
  }
} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.51.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16383 ORDER BY a
  }
} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.51.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16383 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1}
do_test boundary1-2.51.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16383 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61}
do_test boundary1-2.51.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16383 ORDER BY rowid DESC
  }
} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.51.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 16383 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.51.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY a
  }
} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.51.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1}
do_test boundary1-2.51.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8}
do_test boundary1-2.51.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY rowid DESC
  }
} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.51.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.52.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=140737488355328
  }
} {34 0000800000000000}
do_test boundary1-2.52.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000800000000000'
  }
} {140737488355328 34}
do_test boundary1-2.52.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=34
  }
} {140737488355328 0000800000000000}
do_test boundary1-2.52.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY a
  }
} {3 10 13 17 26 27 28 43 45}
do_test boundary1-2.52.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY a DESC
  }
} {45 43 28 27 26 17 13 10 3}
do_test boundary1-2.52.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY rowid
  }
} {10 26 13 43 27 45 17 28 3}
do_test boundary1-2.52.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10}
do_test boundary1-2.52.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY x
  }
} {10 26 13 43 27 45 17 28 3}
do_test boundary1-2.52.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY a
  }
} {3 10 13 17 26 27 28 34 43 45}
do_test boundary1-2.52.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY a DESC
  }
} {45 43 34 28 27 26 17 13 10 3}
do_test boundary1-2.52.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY rowid
  }
} {34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.52.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34}
do_test boundary1-2.52.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY x
  }
} {34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.52.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.52.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.52.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25}
do_test boundary1-2.52.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY rowid DESC
  }
} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.52.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.52.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.52.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.52.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34}
do_test boundary1-2.52.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY rowid DESC
  }
} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.52.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.53.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=2097151
  }
} {15 00000000001fffff}
do_test boundary1-2.53.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00000000001fffff'
  }
} {2097151 15}
do_test boundary1-2.53.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=15
  }
} {2097151 00000000001fffff}
do_test boundary1-2.53.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57}
do_test boundary1-2.53.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY a DESC
  }
} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3}
do_test boundary1-2.53.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY rowid
  }
} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.53.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42}
do_test boundary1-2.53.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY x
  }
} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.53.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57}
do_test boundary1-2.53.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY a DESC
  }
} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.53.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY rowid
  }
} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.53.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15}
do_test boundary1-2.53.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY x
  }
} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.53.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.53.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.53.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62}
do_test boundary1-2.53.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY rowid DESC
  }
} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.53.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.53.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY a
  }
} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64}
do_test boundary1-2.53.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1}
do_test boundary1-2.53.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15}
do_test boundary1-2.53.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY rowid DESC
  }
} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.53.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.54.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=140737488355327
  }
} {25 00007fffffffffff}
do_test boundary1-2.54.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='00007fffffffffff'
  }
} {140737488355327 25}
do_test boundary1-2.54.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=25
  }
} {140737488355327 00007fffffffffff}
do_test boundary1-2.54.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY a
  }
} {3 10 13 17 26 27 28 34 43 45}
do_test boundary1-2.54.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY a DESC
  }
} {45 43 34 28 27 26 17 13 10 3}
do_test boundary1-2.54.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY rowid
  }
} {34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.54.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34}
do_test boundary1-2.54.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY x
  }
} {34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.54.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY a
  }
} {3 10 13 17 25 26 27 28 34 43 45}
do_test boundary1-2.54.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY a DESC
  }
} {45 43 34 28 27 26 25 17 13 10 3}
do_test boundary1-2.54.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY rowid
  }
} {25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.54.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25}
do_test boundary1-2.54.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY x
  }
} {25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.54.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.54.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.54.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56}
do_test boundary1-2.54.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY rowid DESC
  }
} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.54.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.54.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.54.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.54.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25}
do_test boundary1-2.54.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY rowid DESC
  }
} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.54.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.55.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=281474976710656
  }
} {26 0001000000000000}
do_test boundary1-2.55.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0001000000000000'
  }
} {281474976710656 26}
do_test boundary1-2.55.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=26
  }
} {281474976710656 0001000000000000}
do_test boundary1-2.55.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY a
  }
} {3 13 17 27 28 43 45}
do_test boundary1-2.55.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY a DESC
  }
} {45 43 28 27 17 13 3}
do_test boundary1-2.55.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY rowid
  }
} {13 43 27 45 17 28 3}
do_test boundary1-2.55.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13}
do_test boundary1-2.55.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY x
  }
} {13 43 27 45 17 28 3}
do_test boundary1-2.55.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY a
  }
} {3 13 17 26 27 28 43 45}
do_test boundary1-2.55.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY a DESC
  }
} {45 43 28 27 26 17 13 3}
do_test boundary1-2.55.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY rowid
  }
} {26 13 43 27 45 17 28 3}
do_test boundary1-2.55.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26}
do_test boundary1-2.55.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY x
  }
} {26 13 43 27 45 17 28 3}
do_test boundary1-2.55.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.55.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.55.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10}
do_test boundary1-2.55.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY rowid DESC
  }
} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.55.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.55.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.55.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.55.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26}
do_test boundary1-2.55.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY rowid DESC
  }
} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.55.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.56.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=32767
  }
} {23 0000000000007fff}
do_test boundary1-2.56.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000007fff'
  }
} {32767 23}
do_test boundary1-2.56.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=23
  }
} {32767 0000000000007fff}
do_test boundary1-2.56.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32767 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.56.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32767 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.56.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32767 ORDER BY rowid
  }
} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.56.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32767 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50}
do_test boundary1-2.56.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 32767 ORDER BY x
  }
} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.56.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY a
  }
} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62}
do_test boundary1-2.56.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY a DESC
  }
} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3}
do_test boundary1-2.56.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY rowid
  }
} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.56.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23}
do_test boundary1-2.56.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY x
  }
} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.56.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32767 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.56.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32767 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1}
do_test boundary1-2.56.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32767 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16}
do_test boundary1-2.56.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32767 ORDER BY rowid DESC
  }
} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.56.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 32767 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.56.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY a
  }
} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64}
do_test boundary1-2.56.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY a DESC
  }
} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1}
do_test boundary1-2.56.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23}
do_test boundary1-2.56.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY rowid DESC
  }
} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.56.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.57.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=127
  }
} {4 000000000000007f}
do_test boundary1-2.57.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='000000000000007f'
  }
} {127 4}
do_test boundary1-2.57.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=4
  }
} {127 000000000000007f}
do_test boundary1-2.57.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 127 ORDER BY a
  }
} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.57.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 127 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3}
do_test boundary1-2.57.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 127 ORDER BY rowid
  }
} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.57.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 127 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49}
do_test boundary1-2.57.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 127 ORDER BY x
  }
} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.57.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 127 ORDER BY a
  }
} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.57.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 127 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3}
do_test boundary1-2.57.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 127 ORDER BY rowid
  }
} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.57.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 127 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4}
do_test boundary1-2.57.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 127 ORDER BY x
  }
} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.57.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 127 ORDER BY a
  }
} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.57.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 127 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1}
do_test boundary1-2.57.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 127 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31}
do_test boundary1-2.57.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 127 ORDER BY rowid DESC
  }
} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.57.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 127 ORDER BY x
  }
} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.57.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 127 ORDER BY a
  }
} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.57.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 127 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1}
do_test boundary1-2.57.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 127 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4}
do_test boundary1-2.57.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 127 ORDER BY rowid DESC
  }
} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.57.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 127 ORDER BY x
  }
} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.58.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=36028797018963967
  }
} {27 007fffffffffffff}
do_test boundary1-2.58.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='007fffffffffffff'
  }
} {36028797018963967 27}
do_test boundary1-2.58.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=27
  }
} {36028797018963967 007fffffffffffff}
do_test boundary1-2.58.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY a
  }
} {3 17 28 45}
do_test boundary1-2.58.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY a DESC
  }
} {45 28 17 3}
do_test boundary1-2.58.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY rowid
  }
} {45 17 28 3}
do_test boundary1-2.58.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY rowid DESC
  }
} {3 28 17 45}
do_test boundary1-2.58.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY x
  }
} {45 17 28 3}
do_test boundary1-2.58.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY a
  }
} {3 17 27 28 45}
do_test boundary1-2.58.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY a DESC
  }
} {45 28 27 17 3}
do_test boundary1-2.58.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY rowid
  }
} {27 45 17 28 3}
do_test boundary1-2.58.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY rowid DESC
  }
} {3 28 17 45 27}
do_test boundary1-2.58.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY x
  }
} {27 45 17 28 3}
do_test boundary1-2.58.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.58.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.58.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43}
do_test boundary1-2.58.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY rowid DESC
  }
} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.58.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.58.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.58.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.58.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27}
do_test boundary1-2.58.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY rowid DESC
  }
} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.58.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.59.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=4398046511104
  }
} {56 0000040000000000}
do_test boundary1-2.59.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000040000000000'
  }
} {4398046511104 56}
do_test boundary1-2.59.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=56
  }
} {4398046511104 0000040000000000}
do_test boundary1-2.59.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY a
  }
} {3 10 13 17 25 26 27 28 34 43 45}
do_test boundary1-2.59.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY a DESC
  }
} {45 43 34 28 27 26 25 17 13 10 3}
do_test boundary1-2.59.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY rowid
  }
} {25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.59.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25}
do_test boundary1-2.59.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY x
  }
} {25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.59.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY a
  }
} {3 10 13 17 25 26 27 28 34 43 45 56}
do_test boundary1-2.59.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY a DESC
  }
} {56 45 43 34 28 27 26 25 17 13 10 3}
do_test boundary1-2.59.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY rowid
  }
} {56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.59.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56}
do_test boundary1-2.59.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY x
  }
} {56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.59.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64}
do_test boundary1-2.59.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.59.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7}
do_test boundary1-2.59.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY rowid DESC
  }
} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.59.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.59.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.59.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1}
do_test boundary1-2.59.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56}
do_test boundary1-2.59.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY rowid DESC
  }
} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.59.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.60.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=1
  }
} {60 0000000000000001}
do_test boundary1-2.60.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000001'
  }
} {1 60}
do_test boundary1-2.60.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=60
  }
} {1 0000000000000001}
do_test boundary1-2.60.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.60.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.60.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1 ORDER BY rowid
  }
} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.60.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41}
do_test boundary1-2.60.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 1 ORDER BY x
  }
} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.60.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62}
do_test boundary1-2.60.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1 ORDER BY a DESC
  }
} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.60.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1 ORDER BY rowid
  }
} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.60.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60}
do_test boundary1-2.60.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 1 ORDER BY x
  }
} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.60.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64}
do_test boundary1-2.60.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1 ORDER BY a DESC
  }
} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.60.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59}
do_test boundary1-2.60.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1 ORDER BY rowid DESC
  }
} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.60.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 1 ORDER BY x
  }
} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.60.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.60.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.60.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60}
do_test boundary1-2.60.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1 ORDER BY rowid DESC
  }
} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.60.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 1 ORDER BY x
  }
} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.61.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=36028797018963968
  }
} {45 0080000000000000}
do_test boundary1-2.61.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0080000000000000'
  }
} {36028797018963968 45}
do_test boundary1-2.61.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=45
  }
} {36028797018963968 0080000000000000}
do_test boundary1-2.61.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY a
  }
} {3 17 28}
do_test boundary1-2.61.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY a DESC
  }
} {28 17 3}
do_test boundary1-2.61.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY rowid
  }
} {17 28 3}
do_test boundary1-2.61.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY rowid DESC
  }
} {3 28 17}
do_test boundary1-2.61.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY x
  }
} {17 28 3}
do_test boundary1-2.61.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY a
  }
} {3 17 28 45}
do_test boundary1-2.61.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY a DESC
  }
} {45 28 17 3}
do_test boundary1-2.61.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY rowid
  }
} {45 17 28 3}
do_test boundary1-2.61.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY rowid DESC
  }
} {3 28 17 45}
do_test boundary1-2.61.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY x
  }
} {45 17 28 3}
do_test boundary1-2.61.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.61.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.61.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27}
do_test boundary1-2.61.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY rowid DESC
  }
} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.61.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.61.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY a
  }
} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.61.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1}
do_test boundary1-2.61.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45}
do_test boundary1-2.61.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY rowid DESC
  }
} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.61.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.62.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-2147483649
  }
} {47 ffffffff7fffffff}
do_test boundary1-2.62.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ffffffff7fffffff'
  }
} {-2147483649 47}
do_test boundary1-2.62.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=47
  }
} {-2147483649 ffffffff7fffffff}
do_test boundary1-2.62.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.62.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.62.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY rowid
  }
} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.62.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11}
do_test boundary1-2.62.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.62.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62}
do_test boundary1-2.62.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY a DESC
  }
} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.62.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY rowid
  }
} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.62.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47}
do_test boundary1-2.62.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.62.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY a
  }
} {2 21 44 55 58 63 64}
do_test boundary1-2.62.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY a DESC
  }
} {64 63 58 55 44 21 2}
do_test boundary1-2.62.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY rowid
  }
} {55 2 64 21 44 58 63}
do_test boundary1-2.62.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY rowid DESC
  }
} {63 58 44 21 64 2 55}
do_test boundary1-2.62.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY x
  }
} {55 2 64 21 44 58 63}
do_test boundary1-2.62.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY a
  }
} {2 21 44 47 55 58 63 64}
do_test boundary1-2.62.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY a DESC
  }
} {64 63 58 55 47 44 21 2}
do_test boundary1-2.62.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47}
do_test boundary1-2.62.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY rowid DESC
  }
} {47 63 58 44 21 64 2 55}
do_test boundary1-2.62.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY x
  }
} {55 2 64 21 44 58 63 47}
do_test boundary1-2.63.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=-36028797018963969
  }
} {2 ff7fffffffffffff}
do_test boundary1-2.63.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='ff7fffffffffffff'
  }
} {-36028797018963969 2}
do_test boundary1-2.63.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=2
  }
} {-36028797018963969 ff7fffffffffffff}
do_test boundary1-2.63.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY a
  }
} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.63.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1}
do_test boundary1-2.63.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY rowid
  }
} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.63.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64}
do_test boundary1-2.63.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.63.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.63.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.63.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY rowid
  }
} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.63.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2}
do_test boundary1-2.63.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.63.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY a
  }
} {55}
do_test boundary1-2.63.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY a DESC
  }
} {55}
do_test boundary1-2.63.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY rowid
  }
} {55}
do_test boundary1-2.63.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY rowid DESC
  }
} {55}
do_test boundary1-2.63.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY x
  }
} {55}
do_test boundary1-2.63.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY a
  }
} {2 55}
do_test boundary1-2.63.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY a DESC
  }
} {55 2}
do_test boundary1-2.63.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY rowid
  }
} {55 2}
do_test boundary1-2.63.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY rowid DESC
  }
} {2 55}
do_test boundary1-2.63.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY x
  }
} {55 2}
do_test boundary1-2.64.1 {
  db eval {
    SELECT * FROM t1 WHERE rowid=3
  }
} {5 0000000000000003}
do_test boundary1-2.64.2 {
  db eval {
    SELECT rowid, a FROM t1 WHERE x='0000000000000003'
  }
} {3 5}
do_test boundary1-2.64.3 {
  db eval {
    SELECT rowid, x FROM t1 WHERE a=5
  }
} {3 0000000000000003}
do_test boundary1-2.64.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 3 ORDER BY a
  }
} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.64.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 3 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3}
do_test boundary1-2.64.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 3 ORDER BY rowid
  }
} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.64.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 3 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31}
do_test boundary1-2.64.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 3 ORDER BY x
  }
} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.64.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 3 ORDER BY a
  }
} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62}
do_test boundary1-2.64.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 3 ORDER BY a DESC
  }
} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3}
do_test boundary1-2.64.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 3 ORDER BY rowid
  }
} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.64.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 3 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5}
do_test boundary1-2.64.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 3 ORDER BY x
  }
} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.64.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 3 ORDER BY a
  }
} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.64.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 3 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1}
do_test boundary1-2.64.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 3 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41}
do_test boundary1-2.64.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 3 ORDER BY rowid DESC
  }
} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.64.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 3 ORDER BY x
  }
} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.64.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 3 ORDER BY a
  }
} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64}
do_test boundary1-2.64.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 3 ORDER BY a DESC
  }
} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1}
do_test boundary1-2.64.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 3 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5}
do_test boundary1-2.64.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 3 ORDER BY rowid DESC
  }
} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.64.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 3 ORDER BY x
  }
} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.65.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY a
  }
} {}
do_test boundary1-2.65.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY a DESC
  }
} {}
do_test boundary1-2.65.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY rowid
  }
} {}
do_test boundary1-2.65.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {}
do_test boundary1-2.65.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY x
  }
} {}
do_test boundary1-2.65.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY a
  }
} {}
do_test boundary1-2.65.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY a DESC
  }
} {}
do_test boundary1-2.65.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY rowid
  }
} {}
do_test boundary1-2.65.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {}
do_test boundary1-2.65.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY x
  }
} {}
do_test boundary1-2.65.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.65.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.65.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.65.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.65.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.65.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.65.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.65.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.65.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.65.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.66.gt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.66.gt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.66.gt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.66.gt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.66.gt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.66.ge.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY a
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64}
do_test boundary1-2.66.ge.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY a DESC
  }
} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1}
do_test boundary1-2.66.ge.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY rowid
  }
} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3}
do_test boundary1-2.66.ge.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55}
do_test boundary1-2.66.ge.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY x
  }
} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38}
do_test boundary1-2.66.lt.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY a
  }
} {}
do_test boundary1-2.66.lt.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY a DESC
  }
} {}
do_test boundary1-2.66.lt.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY rowid
  }
} {}
do_test boundary1-2.66.lt.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {}
do_test boundary1-2.66.lt.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY x
  }
} {}
do_test boundary1-2.66.le.1 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY a
  }
} {}
do_test boundary1-2.66.le.2 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY a DESC
  }
} {}
do_test boundary1-2.66.le.3 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY rowid
  }
} {}
do_test boundary1-2.66.le.4 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY rowid DESC
  }
} {}
do_test boundary1-2.66.le.5 {
  db eval {
    SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY x
  }
} {}
finish_test

Added test/boundary2.tcl.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
puts {# 2008 December 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is automatically generated from a separate TCL script.
# This file seeks to exercise integer boundary values.
#
# $Id: boundary2.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Many of the boundary tests depend on a working 64-bit implementation.
if {![working_64bit_int]} { finish_test; return }
}

expr srand(0)

# Generate interesting boundary numbers
#
foreach x {
  0
  1
  0x7f
  0x7fff
  0x7fffff
  0x7fffffff
  0x7fffffffff
  0x7fffffffffff
  0x7fffffffffffff
  0x7fffffffffffffff
} {
  set x [expr {wide($x)}]
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set boundarynum([expr {-($x+1)}]) 1
  set boundarynum([expr {-($x+2)}]) 1
  set boundarynum([expr {$x+$x+1}]) 1
  set boundarynum([expr {$x+$x+2}]) 1
}
set x [expr {wide(127)}]
for {set i 1} {$i<=9} {incr i} {
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set x [expr {wide($x*128 + 127)}]
}

# Scramble the $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# A simple selection sort.  Not trying to be efficient.
#
proc sort {inlist} {
  set outlist {}
  set mn [lindex $inlist 0]
  foreach x $inlist {
    if {$x<$mn} {set mn $x}
  }
  set outlist $mn
  set mx $mn
  while {1} {
    set valid 0
    foreach x $inlist {
      if {$x>$mx && (!$valid || $mn>$x)} {
        set mn $x
        set valid 1
      }
    }
    if {!$valid} break
    lappend outlist $mn
    set mx $mn
  }
  return $outlist
}

# Reverse the order of a list
#
proc reverse {inlist} {
  set i [llength $inlist]
  set outlist {}
  for {incr i -1} {$i>=0} {incr i -1} {
    lappend outlist [lindex $inlist $i]
  }
  return $outlist
}

set nums1 [scramble [array names boundarynum]]
set nums2 [scramble [array names boundarynum]]

set tname boundary2
puts "do_test $tname-1.1 \173"
puts "  db eval \173"
puts "    CREATE TABLE t1(r INTEGER, a INTEGER, x TEXT);"
set a 0
foreach r $nums1 {
  incr a
  set t1ra($r) $a
  set t1ar($a) $r
  set x [format %08x%08x [expr {wide($r)>>32}] $r]
  set t1rx($r) $x
  set t1xr($x) $r
  puts "    INSERT INTO t1 VALUES($r,$a,'$x');"
}
puts "    CREATE INDEX t1i1 ON t1(r);"
puts "    CREATE INDEX t1i2 ON t1(a);"
puts "    CREATE INDEX t1i3 ON t1(x);"
puts "  \175"
puts "\175 {}"

puts "do_test $tname-1.2 \173"
puts "  db eval \173"
puts "    SELECT count(*) FROM t1"
puts "  \175"
puts "\175 {64}"

set nums3 $nums2
lappend nums3 9.22337303685477580800e+18
lappend nums3 -9.22337303685477580800e+18

set i 0
foreach r $nums3 {
  incr i

  if {abs($r)<9.22337203685477580800e+18} {
    set x $t1rx($r)
    set a $t1ra($r)
    set r5 $r.5
    set r0 $r.0
    puts "do_test $tname-2.$i.1 \173"
    puts "  db eval \173"
    puts "    SELECT * FROM t1 WHERE r=$r"
    puts "  \175"
    puts "\175 {$r $a $x}"
    puts "do_test $tname-2.$i.2 \173"
    puts "  db eval \173"
    puts "    SELECT r, a FROM t1 WHERE x='$x'"
    puts "  \175"
    puts "\175 {$r $a}"
    puts "do_test $tname-2.$i.3 \173"
    puts "  db eval \173"
    puts "    SELECT r, x FROM t1 WHERE a=$a"
    puts "  \175"
    puts "\175 {$r $x}"
  }

  foreach op {> >= < <=} subno {gt ge lt le} {

    ################################################################ 2.x.y.1
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r" {
        lappend rset $rx
        lappend aset $t1ra($rx)
      }
    }
    puts "do_test $tname-2.$i.$subno.1 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY a"
    puts "  \175"
    puts "\175 {[sort $aset]}"
  
    ################################################################ 2.x.y.2
    puts "do_test $tname-2.$i.$subno.2 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY a DESC"
    puts "  \175"
    puts "\175 {[reverse [sort $aset]]}"
  
    ################################################################ 2.x.y.3
    set aset {}
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.3 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY r"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.4
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.4 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY r DESC"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.5
    set aset {}
    set xset {}
    foreach rx $rset {
      lappend xset $t1rx($rx)
    }
    foreach x [sort $xset] {
      set rx $t1xr($x)
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.5 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY x"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.10
    if {abs($r)>9223372036854775808 || [string length $r5]>15} continue
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r0" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.10 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r0 ORDER BY r"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.11
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.11 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r0 ORDER BY r DESC"
    puts "  \175"
    puts "\175 {$aset}"


    ################################################################ 2.x.y.12
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r5" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.12 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r5 ORDER BY r"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.13
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.13 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r5 ORDER BY r DESC"
    puts "  \175"
    puts "\175 {$aset}"
  }
}

puts "do_test $tname-3.1 \173"
puts "  db eval \173"
puts "    DROP INDEX t1i1;"
puts "    DROP INDEX t1i2;"
puts "    DROP INDEX t1i3;"
puts "  \175"
puts "\175 {}"

set i 0
foreach r $nums3 {
  incr i

  if {abs($r)<9.22337203685477580800e+18} {
    set x $t1rx($r)
    set a $t1ra($r)
    set r5 $r.5
    set r0 $r.0
    puts "do_test $tname-4.$i.1 \173"
    puts "  db eval \173"
    puts "    SELECT * FROM t1 WHERE r=$r"
    puts "  \175"
    puts "\175 {$r $a $x}"
    puts "do_test $tname-4.$i.2 \173"
    puts "  db eval \173"
    puts "    SELECT r, a FROM t1 WHERE x='$x'"
    puts "  \175"
    puts "\175 {$r $a}"
    puts "do_test $tname-4.$i.3 \173"
    puts "  db eval \173"
    puts "    SELECT r, x FROM t1 WHERE a=$a"
    puts "  \175"
    puts "\175 {$r $x}"
  }

  foreach op {> >= < <=} subno {gt ge lt le} {

    ################################################################ 2.x.y.1
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r" {
        lappend rset $rx
        lappend aset $t1ra($rx)
      }
    }
    puts "do_test $tname-4.$i.$subno.1 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY a"
    puts "  \175"
    puts "\175 {[sort $aset]}"
  
    ################################################################ 2.x.y.2
    puts "do_test $tname-4.$i.$subno.2 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY a DESC"
    puts "  \175"
    puts "\175 {[reverse [sort $aset]]}"
  
    ################################################################ 2.x.y.3
    set aset {}
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.3 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY r"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.4
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.4 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY r DESC"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.5
    set aset {}
    set xset {}
    foreach rx $rset {
      lappend xset $t1rx($rx)
    }
    foreach x [sort $xset] {
      set rx $t1xr($x)
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.5 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r ORDER BY x"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.10
    if {abs($r)>9223372036854775808 || [string length $r5]>15} continue
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r0" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.10 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r0 ORDER BY r"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.11
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.11 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r0 ORDER BY r DESC"
    puts "  \175"
    puts "\175 {$aset}"


    ################################################################ 2.x.y.12
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r5" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.12 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r5 ORDER BY r"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.13
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-4.$i.$subno.13 \173"
    puts "  db eval \173"
    puts "    SELECT a FROM t1 WHERE r $op $r5 ORDER BY r DESC"
    puts "  \175"
    puts "\175 {$aset}"
  }
}


puts {finish_test}

Added test/boundary2.test.

more than 10,000 changes

Added test/boundary3.tcl.





































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
puts {# 2008 December 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is automatically generated from a separate TCL script.
# This file seeks to exercise integer boundary values.
#
# $Id: boundary3.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Many of the boundary tests depend on a working 64-bit implementation.
if {![working_64bit_int]} { finish_test; return }
}

expr srand(0)

# Generate interesting boundary numbers
#
foreach x {
  0
  1
  0x7f
  0x7fff
  0x7fffff
  0x7fffffff
  0x7fffffffff
  0x7fffffffffff
  0x7fffffffffffff
  0x7fffffffffffffff
} {
  set x [expr {wide($x)}]
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set boundarynum([expr {-($x+1)}]) 1
  set boundarynum([expr {-($x+2)}]) 1
  set boundarynum([expr {$x+$x+1}]) 1
  set boundarynum([expr {$x+$x+2}]) 1
}
set x [expr {wide(127)}]
for {set i 1} {$i<=9} {incr i} {
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set x [expr {wide($x*128 + 127)}]
}

# Scramble the $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# A simple selection sort.  Not trying to be efficient.
#
proc sort {inlist} {
  set outlist {}
  set mn [lindex $inlist 0]
  foreach x $inlist {
    if {$x<$mn} {set mn $x}
  }
  set outlist $mn
  set mx $mn
  while {1} {
    set valid 0
    foreach x $inlist {
      if {$x>$mx && (!$valid || $mn>$x)} {
        set mn $x
        set valid 1
      }
    }
    if {!$valid} break
    lappend outlist $mn
    set mx $mn
  }
  return $outlist
}

# Reverse the order of a list
#
proc reverse {inlist} {
  set i [llength $inlist]
  set outlist {}
  for {incr i -1} {$i>=0} {incr i -1} {
    lappend outlist [lindex $inlist $i]
  }
  return $outlist
}

set nums1 [scramble [array names boundarynum]]
set nums2 [scramble [array names boundarynum]]

set tname boundary3
puts "do_test $tname-1.1 \173"
puts "  db eval \173"
puts "    CREATE TABLE t1(a,x);"
set a 0
foreach r $nums1 {
  incr a
  set t1ra($r) $a
  set t1ar($a) $r
  set x [format %08x%08x [expr {wide($r)>>32}] $r]
  set t1rx($r) $x
  set t1xr($x) $r
  puts "    INSERT INTO t1(oid,a,x) VALUES($r,$a,'$x');"
}
puts "    CREATE INDEX t1i1 ON t1(a);"
puts "    CREATE INDEX t1i2 ON t1(x);"
puts "  \175"
puts "\175 {}"

puts "do_test $tname-1.2 \173"
puts "  db eval \173"
puts "    SELECT count(*) FROM t1"
puts "  \175"
puts "\175 {64}"

puts "do_test $tname-1.3 \173"
puts "  db eval \173"
puts "    CREATE TABLE t2(r,a);"
puts "    INSERT INTO t2 SELECT rowid, a FROM t1;"
puts "    CREATE INDEX t2i1 ON t2(r);"
puts "    CREATE INDEX t2i2 ON t2(a);"
puts "    INSERT INTO t2 VALUES(9.22337303685477580800e+18,65);"
set t1ra(9.22337303685477580800e+18) 65
set t1ar(65) 9.22337303685477580800e+18)
puts "    INSERT INTO t2 VALUES(-9.22337303685477580800e+18,66);"
set t1ra(-9.22337303685477580800e+18) 66
set t1ar(66) -9.22337303685477580800e+18)
puts "    SELECT count(*) FROM t2;"
puts "  \175"
puts "\175 {66}"

set nums3 $nums2
lappend nums3 9.22337303685477580800e+18
lappend nums3 -9.22337303685477580800e+18

set i 0
foreach r $nums3 {
  incr i

  set r5 $r.5
  set r0 $r.0
  if {abs($r)<9.22337203685477580800e+18} {
    set x $t1rx($r)
    set a $t1ra($r)
    puts "do_test $tname-2.$i.1 \173"
    puts "  db eval \173"
    puts "    SELECT t1.* FROM t1, t2 WHERE t1.rowid=$r AND t2.a=t1.a"
    puts "  \175"
    puts "\175 {$a $x}"
    puts "do_test $tname-2.$i.2 \173"
    puts "  db eval \173"
    puts "    SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='$x'"
    puts "  \175"
    puts "\175 {$r $a}"
    puts "do_test $tname-2.$i.3 \173"
    puts "  db eval \173"
    puts "    SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=$a"
    puts "  \175"
    puts "\175 {$r $x}"
  }

  foreach op {> >= < <=} subno {gt ge lt le} {

    ################################################################ 2.x.y.1
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r" {
        lappend rset $rx
        lappend aset $t1ra($rx)
      }
    }
    puts "do_test $tname-2.$i.$subno.1 \173"
    puts "  db eval \173"
    puts "    SELECT t2.a FROM t1 JOIN t2 USING(a)"
    puts "     WHERE t1.rowid $op $r ORDER BY t2.a"
    puts "  \175"
    puts "\175 {[sort $aset]}"
  
    ################################################################ 2.x.y.2
    puts "do_test $tname-2.$i.$subno.2 \173"
    puts "  db eval \173"
    puts "    SELECT t2.a FROM t2 NATURAL JOIN t1"
    puts "     WHERE t1.rowid $op $r ORDER BY t1.a DESC"
    puts "  \175"
    puts "\175 {[reverse [sort $aset]]}"


    ################################################################ 2.x.y.3
    set ax $t1ra($r)
    set aset {}
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.3 \173"
    puts "  db eval \173"
    puts "    SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op t2.r"
    puts "     WHERE t2.a=$ax"
    puts "     ORDER BY t1.rowid"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.4
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.4 \173"
    puts "  db eval \173"
    puts "    SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op t2.r"
    puts "     WHERE t2.a=$ax"
    puts "     ORDER BY t1.rowid DESC"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.5
    set aset {}
    set xset {}
    foreach rx $rset {
      lappend xset $t1rx($rx)
    }
    foreach x [sort $xset] {
      set rx $t1xr($x)
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.5 \173"
    puts "  db eval \173"
    puts "    SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op t2.r"
    puts "     WHERE t2.a=$ax"
    puts "     ORDER BY x"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.10
    if {[string length $r5]>15} continue
    set rset {}
    set aset {}
    foreach rx $nums2 {
      if "\$rx $op \$r0" {
        lappend rset $rx
      }
    }
    foreach rx [sort $rset] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.10 \173"
    puts "  db eval \173"
    puts "    SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op CAST(t2.r AS real)"
    puts "     WHERE t2.a=$ax"
    puts "     ORDER BY t1.rowid"
    puts "  \175"
    puts "\175 {$aset}"
  
    ################################################################ 2.x.y.11
    set aset {}
    foreach rx [reverse [sort $rset]] {
      lappend aset $t1ra($rx)
    }
    puts "do_test $tname-2.$i.$subno.11 \173"
    puts "  db eval \173"
    puts "    SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op CAST(t2.r AS real)"
    puts "     WHERE t2.a=$ax"
    puts "     ORDER BY t1.rowid DESC"
    puts "  \175"
    puts "\175 {$aset}"
  }
  
}


puts {finish_test}

Added test/boundary3.test.

more than 10,000 changes

Added test/boundary4.tcl.









































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
puts {# 2008 December 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is automatically generated from a separate TCL script.
# This file seeks to exercise integer boundary values.
#
# $Id: boundary4.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Many of the boundary tests depend on a working 64-bit implementation.
if {![working_64bit_int]} { finish_test; return }
ifcapable !altertable     { finish_test; return }
}

expr srand(0)

# Generate interesting boundary numbers
#
foreach x {
  0x7f
  0x7fff
  0x7fffff
  0x7fffffff
  0x7fffffffff
  0x7fffffffffff
  0x7fffffffffffff
  0x7fffffffffffffff
} {
  set x [expr {wide($x)}]
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set boundarynum([expr {-($x+1)}]) 1
  set boundarynum([expr {-($x+2)}]) 1
  set boundarynum([expr {$x+$x+1}]) 1
  set boundarynum([expr {$x+$x+2}]) 1
}
set x [expr {wide(127)}]
for {set i 127} {$i<=9} {incr i} {
  set boundarynum($x) 1
  set boundarynum([expr {$x+1}]) 1
  set x [expr {wide($x*128 + 127)}]
}

# Scramble the $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# A simple selection sort.  Not trying to be efficient.
#
proc sort {inlist} {
  set outlist {}
  set mn [lindex $inlist 0]
  foreach x $inlist {
    if {$x<$mn} {set mn $x}
  }
  set outlist $mn
  set mx $mn
  while {1} {
    set valid 0
    foreach x $inlist {
      if {$x>$mx && (!$valid || $mn>$x)} {
        set mn $x
        set valid 1
      }
    }
    if {!$valid} break
    lappend outlist $mn
    set mx $mn
  }
  return $outlist
}

# Reverse the order of a list
#
proc reverse {inlist} {
  set i [llength $inlist]
  set outlist {}
  for {incr i -1} {$i>=0} {incr i -1} {
    lappend outlist [lindex $inlist $i]
  }
  return $outlist
}

set nums1 [scramble [array names boundarynum]]
set nums2 [scramble [array names boundarynum]]

set tname boundary4
puts "do_test $tname-1.1 \173"
puts "  db eval \173"
puts "    CREATE TABLE t1(a,x);"
set a 0
set all_rowid {}
set all_a {}
set all_x {}
foreach r $nums1 {
  incr a
  set t1ra($r) $a
  set t1ar($a) $r
  set x [format %08x%08x [expr {wide($r)>>32}] $r]
  set t1rx($r) $x
  set t1xr($x) $r
  puts "    INSERT INTO t1(oid,a,x) VALUES($r,$a,'$x');"
  lappend all_rowid $r
  lappend all_a $a
  lappend all_x $x
}
puts "    CREATE INDEX t1i1 ON t1(a);"
puts "    CREATE INDEX t1i2 ON t1(x);"
puts "  \175"
puts "\175 {}"

puts "do_test $tname-1.2 \173"
puts "  db eval \173"
puts "    SELECT count(*) FROM t1"
puts "  \175"
puts "\175 {[llength $nums1]}"

proc maketest {tnum sql answer} {
  puts "do_test $::tname-$tnum \173"
  puts "  db eval \173"
  puts "    $sql"
  puts "  \175"
  puts "\175 {$answer}"
}

set ans {}
foreach r [sort $all_rowid] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 1.3 {SELECT rowid, a, x FROM t1 ORDER BY +rowid} $ans
maketest 1.4 {SELECT rowid, a, x FROM t1 ORDER BY rowid} $ans

set ans {}
foreach r [reverse [sort $all_rowid]] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 1.5 {SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC} $ans
maketest 1.6 {SELECT rowid, a, x FROM t1 ORDER BY rowid DESC} $ans

set ans {}
foreach a [sort $all_a] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 1.7 {SELECT rowid, a, x FROM t1 ORDER BY +a} $ans
maketest 1.8 {SELECT rowid, a, x FROM t1 ORDER BY a} $ans

set ans {}
foreach a [reverse [sort $all_a]] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 1.9 {SELECT rowid, a, x FROM t1 ORDER BY +a DESC} $ans
maketest 1.10 {SELECT rowid, a, x FROM t1 ORDER BY a DESC} $ans

set ans {}
foreach x [sort $all_x] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 1.11 {SELECT rowid, a, x FROM t1 ORDER BY +x} $ans
maketest 1.12 {SELECT rowid, a, x FROM t1 ORDER BY x} $ans

set ans {}
foreach x [reverse [sort $all_x]] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 1.13 {SELECT rowid, a, x FROM t1 ORDER BY +x DESC} $ans
maketest 1.14 {SELECT rowid, a, x FROM t1 ORDER BY x DESC} $ans

maketest 2.1 {UPDATE t1 SET rowid=a, a=rowid} {}

set ans {}
foreach r [sort $all_rowid] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 2.3 {SELECT a, rowid, x FROM t1 ORDER BY +a} $ans
maketest 2.4 {SELECT a, rowid, x FROM t1 ORDER BY a} $ans

set ans {}
foreach r [reverse [sort $all_rowid]] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 2.5 {SELECT a, rowid, x FROM t1 ORDER BY +a DESC} $ans
maketest 2.6 {SELECT a, rowid, x FROM t1 ORDER BY a DESC} $ans

set ans {}
foreach a [sort $all_a] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 2.7 {SELECT a, rowid, x FROM t1 ORDER BY +rowid} $ans
maketest 2.8 {SELECT a, rowid, x FROM t1 ORDER BY rowid} $ans

set ans {}
foreach a [reverse [sort $all_a]] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 2.9 {SELECT a, rowid, x FROM t1 ORDER BY +rowid DESC} $ans
maketest 2.10 {SELECT a, rowid, x FROM t1 ORDER BY rowid DESC} $ans

set ans {}
foreach x [sort $all_x] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 2.11 {SELECT a, rowid, x FROM t1 ORDER BY +x} $ans
maketest 2.12 {SELECT a, rowid, x FROM t1 ORDER BY x} $ans

set ans {}
foreach x [reverse [sort $all_x]] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 2.13 {SELECT a, rowid, x FROM t1 ORDER BY +x DESC} $ans
maketest 2.14 {SELECT a, rowid, x FROM t1 ORDER BY x DESC} $ans

maketest 3.1 {UPDATE t1 SET rowid=a, a=rowid} {}
maketest 3.2 {ALTER TABLE t1 ADD COLUMN z; UPDATE t1 SET z=zeroblob(600)} {}

set ans {}
foreach r [sort $all_rowid] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 3.3 {SELECT rowid, a, x FROM t1 ORDER BY +rowid} $ans
maketest 3.4 {SELECT rowid, a, x FROM t1 ORDER BY rowid} $ans

set ans {}
foreach r [reverse [sort $all_rowid]] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 3.5 {SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC} $ans
maketest 3.6 {SELECT rowid, a, x FROM t1 ORDER BY rowid DESC} $ans

set ans {}
foreach a [sort $all_a] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 3.7 {SELECT rowid, a, x FROM t1 ORDER BY +a} $ans
maketest 3.8 {SELECT rowid, a, x FROM t1 ORDER BY a} $ans

set ans {}
foreach a [reverse [sort $all_a]] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 3.9 {SELECT rowid, a, x FROM t1 ORDER BY +a DESC} $ans
maketest 3.10 {SELECT rowid, a, x FROM t1 ORDER BY a DESC} $ans

set ans {}
foreach x [sort $all_x] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 3.11 {SELECT rowid, a, x FROM t1 ORDER BY +x} $ans
maketest 3.12 {SELECT rowid, a, x FROM t1 ORDER BY x} $ans

set ans {}
foreach x [reverse [sort $all_x]] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 3.13 {SELECT rowid, a, x FROM t1 ORDER BY +x DESC} $ans
maketest 3.14 {SELECT rowid, a, x FROM t1 ORDER BY x DESC} $ans


maketest 4.1 {UPDATE t1 SET rowid=a, a=rowid, x=z, z=x} {}

set ans {}
foreach r [sort $all_rowid] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 4.3 {SELECT a, rowid, z FROM t1 ORDER BY +a} $ans
maketest 4.4 {SELECT a, rowid, z FROM t1 ORDER BY a} $ans

set ans {}
foreach r [reverse [sort $all_rowid]] {
  lappend ans $r $t1ra($r) $t1rx($r)
}
maketest 4.5 {SELECT a, rowid, z FROM t1 ORDER BY +a DESC} $ans
maketest 4.6 {SELECT a, rowid, z FROM t1 ORDER BY a DESC} $ans

set ans {}
foreach a [sort $all_a] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 4.7 {SELECT a, rowid, z FROM t1 ORDER BY +rowid} $ans
maketest 4.8 {SELECT a, rowid, z FROM t1 ORDER BY rowid} $ans

set ans {}
foreach a [reverse [sort $all_a]] {
  set r $t1ar($a)
  lappend ans $r $a $t1rx($r)
}
maketest 4.9 {SELECT a, rowid, z FROM t1 ORDER BY +rowid DESC} $ans
maketest 4.10 {SELECT a, rowid, z FROM t1 ORDER BY rowid DESC} $ans

set ans {}
foreach x [sort $all_x] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 4.11 {SELECT a, rowid, z FROM t1 ORDER BY +z} $ans
maketest 4.12 {SELECT a, rowid, z FROM t1 ORDER BY z} $ans

set ans {}
foreach x [reverse [sort $all_x]] {
  set r $t1xr($x)
  lappend ans $r $t1ra($r) $x
}
maketest 4.13 {SELECT a, rowid, z FROM t1 ORDER BY +z DESC} $ans
maketest 4.14 {SELECT a, rowid, z FROM t1 ORDER BY z DESC} $ans

puts {finish_test}

Added test/boundary4.test.















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# 2008 December 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is automatically generated from a separate TCL script.
# This file seeks to exercise integer boundary values.
#
# $Id: boundary4.test,v 1.2 2009/01/02 15:45:48 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Many of the boundary tests depend on a working 64-bit implementation.
if {![working_64bit_int]} { finish_test; return }
ifcapable !altertable     { finish_test; return }

do_test boundary4-1.1 {
  db eval {
    CREATE TABLE t1(a,x);
    INSERT INTO t1(oid,a,x) VALUES(549755813887,1,'0000007fffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-8388608,2,'ffffffffff800000');
    INSERT INTO t1(oid,a,x) VALUES(0,3,'0000000000000000');
    INSERT INTO t1(oid,a,x) VALUES(-129,4,'ffffffffffffff7f');
    INSERT INTO t1(oid,a,x) VALUES(8388608,5,'0000000000800000');
    INSERT INTO t1(oid,a,x) VALUES(65535,6,'000000000000ffff');
    INSERT INTO t1(oid,a,x) VALUES(8388607,7,'00000000007fffff');
    INSERT INTO t1(oid,a,x) VALUES(1099511627776,8,'0000010000000000');
    INSERT INTO t1(oid,a,x) VALUES(16777215,9,'0000000000ffffff');
    INSERT INTO t1(oid,a,x) VALUES(32767,10,'0000000000007fff');
    INSERT INTO t1(oid,a,x) VALUES(4294967296,11,'0000000100000000');
    INSERT INTO t1(oid,a,x) VALUES(-549755813888,12,'ffffff8000000000');
    INSERT INTO t1(oid,a,x) VALUES(-140737488355328,13,'ffff800000000000');
    INSERT INTO t1(oid,a,x) VALUES(256,14,'0000000000000100');
    INSERT INTO t1(oid,a,x) VALUES(16777216,15,'0000000001000000');
    INSERT INTO t1(oid,a,x) VALUES(72057594037927936,16,'0100000000000000');
    INSERT INTO t1(oid,a,x) VALUES(-1,17,'ffffffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(9223372036854775807,18,'7fffffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(281474976710655,19,'0000ffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(1099511627775,20,'000000ffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-8388609,21,'ffffffffff7fffff');
    INSERT INTO t1(oid,a,x) VALUES(32768,22,'0000000000008000');
    INSERT INTO t1(oid,a,x) VALUES(36028797018963968,23,'0080000000000000');
    INSERT INTO t1(oid,a,x) VALUES(-32769,24,'ffffffffffff7fff');
    INSERT INTO t1(oid,a,x) VALUES(127,25,'000000000000007f');
    INSERT INTO t1(oid,a,x) VALUES(-9223372036854775808,26,'8000000000000000');
    INSERT INTO t1(oid,a,x) VALUES(72057594037927935,27,'00ffffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-549755813889,28,'ffffff7fffffffff');
    INSERT INTO t1(oid,a,x) VALUES(255,29,'00000000000000ff');
    INSERT INTO t1(oid,a,x) VALUES(-36028797018963969,30,'ff7fffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-2147483648,31,'ffffffff80000000');
    INSERT INTO t1(oid,a,x) VALUES(281474976710656,32,'0001000000000000');
    INSERT INTO t1(oid,a,x) VALUES(65536,33,'0000000000010000');
    INSERT INTO t1(oid,a,x) VALUES(140737488355328,34,'0000800000000000');
    INSERT INTO t1(oid,a,x) VALUES(549755813888,35,'0000008000000000');
    INSERT INTO t1(oid,a,x) VALUES(2147483648,36,'0000000080000000');
    INSERT INTO t1(oid,a,x) VALUES(4294967295,37,'00000000ffffffff');
    INSERT INTO t1(oid,a,x) VALUES(140737488355327,38,'00007fffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-2147483649,39,'ffffffff7fffffff');
    INSERT INTO t1(oid,a,x) VALUES(36028797018963967,40,'007fffffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(128,41,'0000000000000080');
    INSERT INTO t1(oid,a,x) VALUES(-32768,42,'ffffffffffff8000');
    INSERT INTO t1(oid,a,x) VALUES(-36028797018963968,43,'ff80000000000000');
    INSERT INTO t1(oid,a,x) VALUES(-140737488355329,44,'ffff7fffffffffff');
    INSERT INTO t1(oid,a,x) VALUES(-128,45,'ffffffffffffff80');
    INSERT INTO t1(oid,a,x) VALUES(2147483647,46,'000000007fffffff');
    CREATE INDEX t1i1 ON t1(a);
    CREATE INDEX t1i2 ON t1(x);
  }
} {}
do_test boundary4-1.2 {
  db eval {
    SELECT count(*) FROM t1
  }
} {46}
do_test boundary4-1.3 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +rowid
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-1.4 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY rowid
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-1.5 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-1.6 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY rowid DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-1.7 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +a
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-1.8 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY a
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-1.9 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +a DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-1.10 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY a DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-1.11 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +x
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-1.12 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY x
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-1.13 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +x DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-1.14 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY x DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-2.1 {
  db eval {
    UPDATE t1 SET rowid=a, a=rowid
  }
} {}
do_test boundary4-2.3 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY +a
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-2.4 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY a
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-2.5 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY +a DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-2.6 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY a DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-2.7 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY +rowid
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-2.8 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY rowid
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-2.9 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY +rowid DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-2.10 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY rowid DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-2.11 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY +x
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-2.12 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY x
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-2.13 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY +x DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-2.14 {
  db eval {
    SELECT a, rowid, x FROM t1 ORDER BY x DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-3.1 {
  db eval {
    UPDATE t1 SET rowid=a, a=rowid
  }
} {}
do_test boundary4-3.2 {
  db eval {
    ALTER TABLE t1 ADD COLUMN z; UPDATE t1 SET z=zeroblob(600)
  }
} {}
do_test boundary4-3.3 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +rowid
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-3.4 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY rowid
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-3.5 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-3.6 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY rowid DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-3.7 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +a
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-3.8 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY a
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-3.9 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +a DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-3.10 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY a DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-3.11 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +x
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-3.12 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY x
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-3.13 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY +x DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-3.14 {
  db eval {
    SELECT rowid, a, x FROM t1 ORDER BY x DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-4.1 {
  db eval {
    UPDATE t1 SET rowid=a, a=rowid, x=z, z=x
  }
} {}
do_test boundary4-4.3 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY +a
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-4.4 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY a
  }
} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff}
do_test boundary4-4.5 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY +a DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-4.6 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY a DESC
  }
} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000}
do_test boundary4-4.7 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY +rowid
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-4.8 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY rowid
  }
} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff}
do_test boundary4-4.9 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY +rowid DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-4.10 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY rowid DESC
  }
} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff}
do_test boundary4-4.11 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY +z
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-4.12 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY z
  }
} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff}
do_test boundary4-4.13 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY +z DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
do_test boundary4-4.14 {
  db eval {
    SELECT a, rowid, z FROM t1 ORDER BY z DESC
  }
} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000}
finish_test

Added test/busy.test.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 2005 july 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file test the busy handler
#
# $Id: busy.test,v 1.3 2008/03/15 02:09:22 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test busy-1.1 {
  sqlite3 db2 test.db
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT * FROM t1
  }
} 1
proc busy x {
  lappend ::busyargs $x
  if {$x>2} {return 1}
  return 0
}
set busyargs {}
do_test busy-1.2 {
  db busy busy
  db2 eval {BEGIN EXCLUSIVE}
  catchsql {BEGIN IMMEDIATE}
} {1 {database is locked}}
do_test busy-1.3 {
  set busyargs
} {0 1 2 3}
do_test busy-1.4 {
  set busyargs {}
  catchsql {BEGIN IMMEDIATE}
  set busyargs
} {0 1 2 3}

do_test busy-2.1 {
  db2 eval {COMMIT}
  db eval {BEGIN; INSERT INTO t1 VALUES(5)}
  db2 eval {BEGIN; SELECT * FROM t1}
  set busyargs {}
  catchsql COMMIT
} {1 {database is locked}}
do_test busy-2.2 {
  set busyargs
} {0 1 2 3}


db2 close

finish_test

Added test/cache.test.































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 2007 March 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: cache.test,v 1.4 2007/08/22 02:56:44 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas} {
  finish_test
  return
}
sqlite3_soft_heap_limit 0

proc pager_cache_size {db} {
  set bt [btree_from_db $db]
  db_enter $db
  array set stats [btree_pager_stats $bt]
  db_leave $db
  return $stats(page)
}

do_test cache-1.1 {
  pager_cache_size db
} {0}

do_test cache-1.2 {
  execsql {
    PRAGMA auto_vacuum=OFF;
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
  }
  pager_cache_size db
} {2}

# At one point, repeatedly locking and unlocking the cache was causing
# a resource leak of one page per repetition. The page wasn't actually
# leaked, but would not be reused until the pager-cache was full (i.e. 
# 2000 pages by default).
#
# This tests that once the pager-cache is initialised, it can be locked
# and unlocked repeatedly without internally allocating any new pages.
#
set cache_size [pager_cache_size db]
for {set ii 0} {$ii < 10} {incr ii} {

  do_test cache-1.3.$ii {
    execsql {SELECT * FROM abc}
    pager_cache_size db
  } $::cache_size

}
sqlite3_soft_heap_limit $soft_limit

finish_test

Added test/capi2.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# 2003 January 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the callback-free C/C++ API.
#
# $Id: capi2.test,v 1.37 2008/12/30 17:55:00 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Return the text values from the current row pointed at by STMT as a list.
proc get_row_values {STMT} {
  set VALUES [list]
  for {set i 0} {$i < [sqlite3_data_count $STMT]} {incr i} {
    lappend VALUES [sqlite3_column_text $STMT $i]
  }
  return $VALUES
}

# Return the column names followed by declaration types for the result set
# of the SQL statement STMT.
#
# i.e. for:
# CREATE TABLE abc(a text, b integer); 
# SELECT * FROM abc;
#
# The result is {a b text integer}
proc get_column_names {STMT} {
  set VALUES [list]
  for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} {
    lappend VALUES [sqlite3_column_name $STMT $i]
  }
  for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} {
    lappend VALUES [sqlite3_column_decltype $STMT $i]
  }
  return $VALUES
}

# Check basic functionality
#
do_test capi2-1.1 {
  set DB [sqlite3_connection_pointer db]
  execsql {CREATE TABLE t1(a,b,c)}
  set VM [sqlite3_prepare $DB {SELECT name, rowid FROM sqlite_master} -1 TAIL]
  set TAIL
} {}
do_test capi2-1.2 {
  sqlite3_step $VM
} {SQLITE_ROW}
do_test capi2-1.3 {
  sqlite3_data_count $VM
} {2}
do_test capi2-1.4 {
  get_row_values $VM
} {t1 1}
do_test capi2-1.5 {
  get_column_names $VM
} {name rowid text INTEGER}
do_test capi2-1.6 {
  sqlite3_step $VM 
} {SQLITE_DONE}
do_test capi2-1.7 {
  list [sqlite3_column_count $VM] [get_row_values $VM] [get_column_names $VM]
} {2 {} {name rowid text INTEGER}}
do_test capi2-1.8-misuse {
  sqlite3_step $VM
} {SQLITE_MISUSE}

# Update: In v2, once SQLITE_MISUSE is returned the statement handle cannot
# be interrogated for more information. However in v3, since the column
# count, names and types are determined at compile time, these are still
# accessible after an SQLITE_MISUSE error.
do_test capi2-1.9 {
  list [sqlite3_column_count $VM] [get_row_values $VM] [get_column_names $VM]
} {2 {} {name rowid text INTEGER}}
do_test capi2-1.10 {
  sqlite3_data_count $VM
} {0}

do_test capi2-1.11 {
  sqlite3_finalize $VM
} {SQLITE_OK}

# Check to make sure that the "tail" of a multi-statement SQL script
# is returned by sqlite3_prepare.
#
do_test capi2-2.1 {
  set SQL {
    SELECT name, rowid FROM sqlite_master;
    SELECT name, rowid FROM sqlite_master WHERE 0;
    -- A comment at the end
  }
  set VM [sqlite3_prepare $DB $SQL -1 SQL]
  set SQL
} {
    SELECT name, rowid FROM sqlite_master WHERE 0;
    -- A comment at the end
  }
do_test capi2-2.2 {
  set r [sqlite3_step $VM]
  lappend r [sqlite3_column_count $VM] \
            [get_row_values $VM] \
            [get_column_names $VM]
} {SQLITE_ROW 2 {t1 1} {name rowid text INTEGER}}
do_test capi2-2.3 {
  set r [sqlite3_step $VM]
  lappend r [sqlite3_column_count $VM] \
            [get_row_values $VM] \
            [get_column_names $VM]
} {SQLITE_DONE 2 {} {name rowid text INTEGER}}
do_test capi2-2.4 {
  sqlite3_finalize $VM
} {SQLITE_OK}
do_test capi2-2.5 {
  set VM [sqlite3_prepare $DB $SQL -1 SQL]
  set SQL
} {
    -- A comment at the end
  }
do_test capi2-2.6 {
  set r [sqlite3_step $VM]
  lappend r [sqlite3_column_count $VM] \
            [get_row_values $VM] \
            [get_column_names $VM]
} {SQLITE_DONE 2 {} {name rowid text INTEGER}}
do_test capi2-2.7 {
  sqlite3_finalize $VM
} {SQLITE_OK}
do_test capi2-2.8 {
  set VM [sqlite3_prepare $DB $SQL -1 SQL]
  list $SQL $VM
} {{} {}}

# Check the error handling.
#
do_test capi2-3.1 {
  set rc [catch {
      sqlite3_prepare $DB {select bogus from sqlite_master} -1 TAIL
  } msg]
  lappend rc $msg $TAIL
} {1 {(1) no such column: bogus} {}}
do_test capi2-3.2 {
  set rc [catch {
      sqlite3_prepare $DB {select bogus from } -1 TAIL
  } msg]
  lappend rc $msg $TAIL
} {1 {(1) near " ": syntax error} {}}
do_test capi2-3.3 {
  set rc [catch {
      sqlite3_prepare $DB {;;;;select bogus from sqlite_master} -1 TAIL
  } msg]
  lappend rc $msg $TAIL
} {1 {(1) no such column: bogus} {}}
do_test capi2-3.4 {
  set rc [catch {
      sqlite3_prepare $DB {select bogus from sqlite_master;x;} -1 TAIL
  } msg]
  lappend rc $msg $TAIL
} {1 {(1) no such column: bogus} {x;}}
do_test capi2-3.5 {
  set rc [catch {
      sqlite3_prepare $DB {select bogus from sqlite_master;;;x;} -1 TAIL
  } msg]
  lappend rc $msg $TAIL
} {1 {(1) no such column: bogus} {;;x;}}
do_test capi2-3.6 {
  set rc [catch {
      sqlite3_prepare $DB {select 5/0} -1 TAIL
  } VM]
  lappend rc $TAIL
} {0 {}}
do_test capi2-3.7 {
  list [sqlite3_step $VM] \
       [sqlite3_column_count $VM] \
       [get_row_values $VM] \
       [get_column_names $VM]
} {SQLITE_ROW 1 {{}} {5/0 {}}}
do_test capi2-3.8 {
  sqlite3_finalize $VM
} {SQLITE_OK}
do_test capi2-3.9 {
  execsql {CREATE UNIQUE INDEX i1 ON t1(a)}
  set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(1,2,3)} -1 TAIL]
  set TAIL
} {}
do_test capi2-3.9b {db changes} {0}
do_test capi2-3.10 {
  list [sqlite3_step $VM] \
       [sqlite3_column_count $VM] \
       [get_row_values $VM] \
       [get_column_names $VM]
} {SQLITE_DONE 0 {} {}}

# Update for v3 - the change has not actually happened until the query is
# finalized. Is this going to cause trouble for anyone? Lee Nelson maybe?
# (Later:) The change now happens just before SQLITE_DONE is returned.
do_test capi2-3.10b {db changes} {1}
do_test capi2-3.11 {
  sqlite3_finalize $VM
} {SQLITE_OK}
do_test capi2-3.11b {db changes} {1}
#do_test capi2-3.12-misuse {
#  sqlite3_finalize $VM
#} {SQLITE_MISUSE}
do_test capi2-3.13 {
  set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(1,3,4)} -1 TAIL]
  list [sqlite3_step $VM] \
       [sqlite3_column_count $VM] \
       [get_row_values $VM] \
       [get_column_names $VM]
} {SQLITE_ERROR 0 {} {}}

# Update for v3: Preparing a statement does not affect the change counter.
# (Test result changes from 0 to 1).  (Later:) change counter updates occur
# when sqlite3_step returns, not at finalize time.
do_test capi2-3.13b {db changes} {0}

do_test capi2-3.14 {
  list [sqlite3_finalize $VM] [sqlite3_errmsg $DB]
} {SQLITE_CONSTRAINT {column a is not unique}}
do_test capi2-3.15 {
  set VM [sqlite3_prepare $DB {CREATE TABLE t2(a NOT NULL, b)} -1 TAIL]
  set TAIL
} {}
do_test capi2-3.16 {
  list [sqlite3_step $VM] \
       [sqlite3_column_count $VM] \
       [get_row_values $VM] \
       [get_column_names $VM]
} {SQLITE_DONE 0 {} {}}
do_test capi2-3.17 {
  list [sqlite3_finalize $VM] [sqlite3_errmsg $DB]
} {SQLITE_OK {not an error}}
do_test capi2-3.18 {
  set VM [sqlite3_prepare $DB {INSERT INTO t2 VALUES(NULL,2)} -1 TAIL]
  list [sqlite3_step $VM] \
       [sqlite3_column_count $VM] \
       [get_row_values $VM] \
       [get_column_names $VM]
} {SQLITE_ERROR 0 {} {}}
do_test capi2-3.19 {
  list [sqlite3_finalize $VM] [sqlite3_errmsg $DB]
} {SQLITE_CONSTRAINT {t2.a may not be NULL}}

do_test capi2-3.20 {
  execsql {
    CREATE TABLE a1(message_id, name , UNIQUE(message_id, name) );
    INSERT INTO a1 VALUES(1, 1);
  }
} {}
do_test capi2-3.21 {
  set VM [sqlite3_prepare $DB {INSERT INTO a1 VALUES(1, 1)} -1 TAIL]
  sqlite3_step $VM
} {SQLITE_ERROR}
do_test capi2-3.22 {
  sqlite3_errcode $DB
} {SQLITE_ERROR}
do_test capi2-3.23 {
  sqlite3_finalize $VM
} {SQLITE_CONSTRAINT}
do_test capi2-3.24 {
  sqlite3_errcode $DB
} {SQLITE_CONSTRAINT}

# Two or more virtual machines exists at the same time.
#
do_test capi2-4.1 {
  set VM1 [sqlite3_prepare $DB {INSERT INTO t2 VALUES(1,2)} -1 TAIL]
  set TAIL
} {}
do_test capi2-4.2 {
  set VM2 [sqlite3_prepare $DB {INSERT INTO t2 VALUES(2,3)} -1 TAIL]
  set TAIL
} {}
do_test capi2-4.3 {
  set VM3 [sqlite3_prepare $DB {INSERT INTO t2 VALUES(3,4)} -1 TAIL]
  set TAIL
} {}
do_test capi2-4.4 {
  list [sqlite3_step $VM2] \
       [sqlite3_column_count $VM2] \
       [get_row_values $VM2] \
       [get_column_names $VM2]
} {SQLITE_DONE 0 {} {}}
do_test capi2-4.5 {
  execsql {SELECT * FROM t2 ORDER BY a}
} {2 3}
do_test capi2-4.6 {
  sqlite3_finalize $VM2
} {SQLITE_OK}
do_test capi2-4.7 {
  list [sqlite3_step $VM3] \
       [sqlite3_column_count $VM3] \
       [get_row_values $VM3] \
       [get_column_names $VM3]
} {SQLITE_DONE 0 {} {}}
do_test capi2-4.8 {
  execsql {SELECT * FROM t2 ORDER BY a}
} {2 3 3 4}
do_test capi2-4.9 {
  sqlite3_finalize $VM3
} {SQLITE_OK}
do_test capi2-4.10 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_DONE 0 {} {}}
do_test capi2-4.11 {
  execsql {SELECT * FROM t2 ORDER BY a}
} {1 2 2 3 3 4}
do_test capi2-4.12 {
  sqlite3_finalize $VM1
} {SQLITE_OK}

# Interleaved SELECTs
#
do_test capi2-5.1 {
  set VM1 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL]
  set VM2 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL]
  set VM3 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL]
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 2 {2 3} {a b {} {}}}
do_test capi2-5.2 {
  list [sqlite3_step $VM2] \
       [sqlite3_column_count $VM2] \
       [get_row_values $VM2] \
       [get_column_names $VM2]
} {SQLITE_ROW 2 {2 3} {a b {} {}}}
do_test capi2-5.3 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 2 {3 4} {a b {} {}}}
do_test capi2-5.4 {
  list [sqlite3_step $VM3] \
       [sqlite3_column_count $VM3] \
       [get_row_values $VM3] \
       [get_column_names $VM3]
} {SQLITE_ROW 2 {2 3} {a b {} {}}}
do_test capi2-5.5 {
  list [sqlite3_step $VM3] \
       [sqlite3_column_count $VM3] \
       [get_row_values $VM3] \
       [get_column_names $VM3]
} {SQLITE_ROW 2 {3 4} {a b {} {}}}
do_test capi2-5.6 {
  list [sqlite3_step $VM3] \
       [sqlite3_column_count $VM3] \
       [get_row_values $VM3] \
       [get_column_names $VM3]
} {SQLITE_ROW 2 {1 2} {a b {} {}}}
do_test capi2-5.7 {
  list [sqlite3_step $VM3] \
       [sqlite3_column_count $VM3] \
       [get_row_values $VM3] \
       [get_column_names $VM3]
} {SQLITE_DONE 2 {} {a b {} {}}}
do_test capi2-5.8 {
  sqlite3_finalize $VM3
} {SQLITE_OK}
do_test capi2-5.9 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 2 {1 2} {a b {} {}}}
do_test capi2-5.10 {
  sqlite3_finalize $VM1
} {SQLITE_OK}
do_test capi2-5.11 {
  list [sqlite3_step $VM2] \
       [sqlite3_column_count $VM2] \
       [get_row_values $VM2] \
       [get_column_names $VM2]
} {SQLITE_ROW 2 {3 4} {a b {} {}}}
do_test capi2-5.12 {
  list [sqlite3_step $VM2] \
       [sqlite3_column_count $VM2] \
       [get_row_values $VM2] \
       [get_column_names $VM2]
} {SQLITE_ROW 2 {1 2} {a b {} {}}}
do_test capi2-5.11 {
  sqlite3_finalize $VM2
} {SQLITE_OK}

# Check for proper SQLITE_BUSY returns.
#
do_test capi2-6.1 {
  execsql {
    BEGIN;
    CREATE TABLE t3(x counter);
    INSERT INTO t3 VALUES(1);
    INSERT INTO t3 VALUES(2);
    INSERT INTO t3 SELECT x+2 FROM t3;
    INSERT INTO t3 SELECT x+4 FROM t3;
    INSERT INTO t3 SELECT x+8 FROM t3;
    COMMIT;
  }
  set VM1 [sqlite3_prepare $DB {SELECT * FROM t3} -1 TAIL]
  sqlite3 db2 test.db
  execsql {BEGIN} db2
} {}
# Update for v3: BEGIN doesn't write-lock the database. It is quite
# difficult to get v3 to write-lock the database, which causes a few
# problems for test scripts.
#
# do_test capi2-6.2 {
#   list [sqlite3_step $VM1] \
#        [sqlite3_column_count $VM1] \
#        [get_row_values $VM1] \
#        [get_column_names $VM1]
# } {SQLITE_BUSY 0 {} {}}
do_test capi2-6.3 {
  execsql {COMMIT} db2
} {}
do_test capi2-6.4 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 1 {x counter}}
do_test capi2-6.5 {
  catchsql {INSERT INTO t3 VALUES(10);} db2
} {1 {database is locked}}
do_test capi2-6.6 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 2 {x counter}}
do_test capi2-6.7 {
  execsql {SELECT * FROM t2} db2
} {2 3 3 4 1 2}
do_test capi2-6.8 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 3 {x counter}}
do_test capi2-6.9 {
  execsql {SELECT * FROM t2} 
} {2 3 3 4 1 2}
do_test capi2-6.10 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 4 {x counter}}
do_test capi2-6.11 {
  execsql {BEGIN}
} {}
do_test capi2-6.12 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 5 {x counter}}

# A read no longer blocks a write in the same connection.
#do_test capi2-6.13 {
#  catchsql {UPDATE t3 SET x=x+1}
#} {1 {database table is locked}}

do_test capi2-6.14 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 6 {x counter}}
do_test capi2-6.15 {
  execsql {SELECT * FROM t1}
} {1 2 3}
do_test capi2-6.16 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 7 {x counter}}
do_test capi2-6.17 {
  catchsql {UPDATE t1 SET b=b+1}
} {0 {}}
do_test capi2-6.18 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 8 {x counter}}
do_test capi2-6.19 {
  execsql {SELECT * FROM t1}
} {1 3 3}
do_test capi2-6.20 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 9 {x counter}}
#do_test capi2-6.21 {
#  execsql {ROLLBACK; SELECT * FROM t1}
#} {1 2 3}
do_test capi2-6.22 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 10 {x counter}}
#do_test capi2-6.23 {
#  execsql {BEGIN TRANSACTION;}
#} {}
do_test capi2-6.24 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 11 {x counter}}
do_test capi2-6.25 {
  execsql {
    INSERT INTO t1 VALUES(2,3,4);
    SELECT * FROM t1;
  }
} {1 3 3 2 3 4}
do_test capi2-6.26 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 12 {x counter}}
do_test capi2-6.27 {
  catchsql {
    INSERT INTO t1 VALUES(2,4,5);
    SELECT * FROM t1;
  }
} {1 {column a is not unique}}
do_test capi2-6.28 {
  list [sqlite3_step $VM1] \
       [sqlite3_column_count $VM1] \
       [get_row_values $VM1] \
       [get_column_names $VM1]
} {SQLITE_ROW 1 13 {x counter}}
do_test capi2-6.99 {
  sqlite3_finalize $VM1
} {SQLITE_OK}
catchsql {ROLLBACK}

do_test capi2-7.1 {
  stepsql $DB {
    SELECT * FROM t1
  }
} {0 1 2 3}
do_test capi2-7.2 {
  stepsql $DB {
    PRAGMA count_changes=on
  }
} {0}
do_test capi2-7.3 {
  stepsql $DB {
    UPDATE t1 SET a=a+10;
  }
} {0 1}
do_test capi2-7.4 {
  stepsql $DB {
    INSERT INTO t1 SELECT a+1,b+1,c+1 FROM t1;
  }
} {0 1}
do_test capi2-7.4b {sqlite3_changes $DB} {1}
do_test capi2-7.5 {
  stepsql $DB {
    UPDATE t1 SET a=a+10;
  }
} {0 2}
do_test capi2-7.5b {sqlite3_changes $DB} {2}
do_test capi2-7.6 {
  stepsql $DB {
    SELECT * FROM t1;
  }
} {0 21 2 3 22 3 4}
do_test capi2-7.7 {
  stepsql $DB {
    INSERT INTO t1 SELECT a+2,b+2,c+2 FROM t1;
  }
} {0 2}
do_test capi2-7.8 {
  sqlite3_changes $DB
} {2}
do_test capi2-7.9 {
  stepsql $DB {
    SELECT * FROM t1;
  }
} {0 21 2 3 22 3 4 23 4 5 24 5 6}
do_test capi2-7.10 {
  stepsql $DB {
    UPDATE t1 SET a=a-20;
    SELECT * FROM t1;
  }
} {0 4 1 2 3 2 3 4 3 4 5 4 5 6}

# Update for version 3: A SELECT statement no longer resets the change
# counter (Test result changes from 0 to 4).
do_test capi2-7.11 {
  sqlite3_changes $DB
} {4}
do_test capi2-7.11a {
  execsql {SELECT count(*) FROM t1}
} {4}

ifcapable {explain} {
  do_test capi2-7.12 {
    set x [stepsql $DB {EXPLAIN SELECT * FROM t1}]
    lindex $x 0
  } {0}
}

# Ticket #261 - make sure we can finalize before the end of a query.
#
do_test capi2-8.1 {
  set VM1 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL]
  sqlite3_finalize $VM1
} {SQLITE_OK}
  
# Tickets #384 and #385 - make sure the TAIL argument to sqlite3_prepare
# and all of the return pointers in sqlite_step can be null.
#
do_test capi2-9.1 {
  set VM1 [sqlite3_prepare $DB {SELECT * FROM t2} -1 DUMMY]
  sqlite3_step $VM1
  sqlite3_finalize $VM1
} {SQLITE_OK}

# Test that passing a NULL pointer to sqlite3_finalize() or sqlite3_reset
# does not cause an error.
do_test capi2-10.1 {
  sqlite3_finalize 0
} {SQLITE_OK}
do_test capi2-10.2 {
  sqlite3_reset 0
} {SQLITE_OK}

#---------------------------------------------------------------------------
# The following tests - capi2-11.* - test the "column origin" APIs.
#
#   sqlite3_column_origin_name()
#   sqlite3_column_database_name()
#   sqlite3_column_table_name()
#

ifcapable columnmetadata {

# This proc uses the database handle $::DB to compile the SQL statement passed
# as a parameter. The return value of this procedure is a list with one
# element for each column returned by the compiled statement. Each element of
# this list is itself a list of length three, consisting of the origin
# database, table and column for the corresponding returned column.
proc check_origins {sql} {
  set ret [list]
  set ::STMT [sqlite3_prepare $::DB $sql -1 dummy]
  for {set i 0} {$i < [sqlite3_column_count $::STMT]} {incr i} {
    lappend ret [list                           \
      [sqlite3_column_database_name $::STMT $i] \
      [sqlite3_column_table_name $::STMT $i]    \
      [sqlite3_column_origin_name $::STMT $i]   \
    ]
  }
  sqlite3_finalize $::STMT
  return $ret
}
do_test capi2-11.1 {
  execsql {
    CREATE TABLE tab1(col1, col2);
  }
} {}
do_test capi2-11.2 {
  check_origins {SELECT col2, col1 FROM tab1}
} [list {main tab1 col2} {main tab1 col1}]
do_test capi2-11.3 {
  check_origins {SELECT col2 AS hello, col1 AS world FROM tab1}
} [list {main tab1 col2} {main tab1 col1}]

ifcapable subquery {
  do_test capi2-11.4 {
    check_origins {SELECT b, a FROM (SELECT col1 AS a, col2 AS b FROM tab1)}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-11.5 {
    check_origins {SELECT (SELECT col2 FROM tab1), (SELECT col1 FROM tab1)}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-11.6 {
    check_origins {SELECT (SELECT col2), (SELECT col1) FROM tab1}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-11.7 {
    check_origins {SELECT * FROM tab1}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-11.8 {
    check_origins {SELECT * FROM (SELECT * FROM tab1)}
  } [list {main tab1 col1} {main tab1 col2}]
}

ifcapable view&&subquery {
  do_test capi2-12.1 {
    execsql {
      CREATE VIEW view1 AS SELECT * FROM  tab1;
    }
  } {}
  do_test capi2-12.2 {
    check_origins {SELECT col2, col1 FROM view1}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-12.3 {
    check_origins {SELECT col2 AS hello, col1 AS world FROM view1}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-12.4 {
    check_origins {SELECT b, a FROM (SELECT col1 AS a, col2 AS b FROM view1)}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-12.5 {
    check_origins {SELECT (SELECT col2 FROM view1), (SELECT col1 FROM view1)}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-12.6 {
    check_origins {SELECT (SELECT col2), (SELECT col1) FROM view1}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-12.7 {
    check_origins {SELECT * FROM view1}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-12.8 {
    check_origins {select * from (select * from view1)}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-12.9 {
    check_origins {select * from (select * from (select * from view1))}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-12.10 {
    db close
    sqlite3 db test.db
    set ::DB [sqlite3_connection_pointer db]
    check_origins {select * from (select * from (select * from view1))}
  } [list {main tab1 col1} {main tab1 col2}]
  
  # This view will thwart the flattening optimization.
  do_test capi2-13.1 {
    execsql {
      CREATE VIEW view2 AS SELECT * FROM tab1 limit 10 offset 10;
    }
  } {}
  do_test capi2-13.2 {
    check_origins {SELECT col2, col1 FROM view2}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-13.3 {
    check_origins {SELECT col2 AS hello, col1 AS world FROM view2}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-13.4 {
    check_origins {SELECT b, a FROM (SELECT col1 AS a, col2 AS b FROM view2)}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-13.5 {
    check_origins {SELECT (SELECT col2 FROM view2), (SELECT col1 FROM view2)}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-13.6 {
    check_origins {SELECT (SELECT col2), (SELECT col1) FROM view2}
  } [list {main tab1 col2} {main tab1 col1}]
  do_test capi2-13.7 {
    check_origins {SELECT * FROM view2}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-13.8 {
    check_origins {select * from (select * from view2)}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-13.9 {
    check_origins {select * from (select * from (select * from view2))}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-13.10 {
    db close
    sqlite3 db test.db
    set ::DB [sqlite3_connection_pointer db]
    check_origins {select * from (select * from (select * from view2))}
  } [list {main tab1 col1} {main tab1 col2}]
  do_test capi2-13.11 {
    check_origins {select * from (select * from tab1 limit 10 offset 10)}
  } [list {main tab1 col1} {main tab1 col2}]
}


} ;# ifcapable columnmetadata

db2 close
finish_test

Added test/capi3.test.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# 2003 January 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the callback-free C/C++ API.
#
# $Id: capi3.test,v 1.70 2009/01/09 02:49:32 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Return the UTF-16 representation of the supplied UTF-8 string $str.
# If $nt is true, append two 0x00 bytes as a nul terminator.
proc utf16 {str {nt 1}} {
  set r [encoding convertto unicode $str]
  if {$nt} {
    append r "\x00\x00"
  }
  return $r
}

# Return the UTF-8 representation of the supplied UTF-16 string $str. 
proc utf8 {str} {
  # If $str ends in two 0x00 0x00 bytes, knock these off before
  # converting to UTF-8 using TCL.
  binary scan $str \c* vals
  if {[lindex $vals end]==0 && [lindex $vals end-1]==0} {
    set str [binary format \c* [lrange $vals 0 end-2]]
  }

  set r [encoding convertfrom unicode $str]
  return $r
}

# These tests complement those in capi2.test. They are organized
# as follows:
#
# capi3-1.*: Test sqlite3_prepare 
# capi3-2.*: Test sqlite3_prepare16
# capi3-3.*: Test sqlite3_open
# capi3-4.*: Test sqlite3_open16
# capi3-5.*: Test the various sqlite3_result_* APIs
# capi3-6.*: Test that sqlite3_close fails if there are outstanding VMs.
#

set DB [sqlite3_connection_pointer db]

do_test capi3-1.0 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3-1.1 {
  set STMT [sqlite3_prepare $DB {SELECT name FROM sqlite_master} -1 TAIL]
  sqlite3_finalize $STMT
  set TAIL
} {}
do_test capi3-1.2.1 {
  sqlite3_errcode $DB
} {SQLITE_OK}
do_test capi3-1.2.2 {
  sqlite3_extended_errcode $DB
} {SQLITE_OK}
do_test capi3-1.3 {
  sqlite3_errmsg $DB
} {not an error}
do_test capi3-1.4 {
  set sql {SELECT name FROM sqlite_master;SELECT 10}
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_finalize $STMT
  set TAIL
} {SELECT 10}
do_test capi3-1.5 {
  set sql {SELECT name FROM sqlite_master;SELECT 10}
  set STMT [sqlite3_prepare $DB $sql [string length $sql] TAIL]
  sqlite3_finalize $STMT
  set TAIL
} {SELECT 10}
do_test capi3-1.6 {
  set sql {SELECT name FROM sqlite_master;SELECT 10}
  set STMT [sqlite3_prepare $DB $sql [expr [string length $sql]+1] TAIL]
  sqlite3_finalize $STMT
  set TAIL
} {SELECT 10}

do_test capi3-1.7 {
  set sql {SELECT namex FROM sqlite_master}
  catch {
    set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  }
} {1}
do_test capi3-1.8.1 {
  sqlite3_errcode $DB
} {SQLITE_ERROR}
do_test capi3-1.8.2 {
  sqlite3_extended_errcode $DB
} {SQLITE_ERROR}
do_test capi3-1.9 {
  sqlite3_errmsg $DB
} {no such column: namex}

ifcapable {utf16} {
  do_test capi3-2.1 {
    set sql16 [utf16 {SELECT name FROM sqlite_master}]
    set STMT [sqlite3_prepare16 $DB $sql16 -1 ::TAIL]
    sqlite3_finalize $STMT
    utf8 $::TAIL
  } {}
  do_test capi3-2.2 {
    set sql [utf16 {SELECT name FROM sqlite_master;SELECT 10}]
    set STMT [sqlite3_prepare16 $DB $sql -1 TAIL]
    sqlite3_finalize $STMT
    utf8 $TAIL
  } {SELECT 10}
  do_test capi3-2.3 {
    set sql [utf16 {SELECT namex FROM sqlite_master}]
    catch {
      set STMT [sqlite3_prepare16 $DB $sql -1]
    }
  } {1}
  do_test capi3-2.4.1 {
    sqlite3_errcode $DB
  } {SQLITE_ERROR}
  do_test capi3-2.4.2 {
    sqlite3_extended_errcode $DB
  } {SQLITE_ERROR}
  do_test capi3-2.5 {
    sqlite3_errmsg $DB
  } {no such column: namex}

  ifcapable schema_pragmas {
    do_test capi3-2.6 {
      execsql {CREATE TABLE tablename(x)}
      set sql16 [utf16 {PRAGMA table_info("TableName"); --excess text}]
      set STMT [sqlite3_prepare16 $DB $sql16 -1]
      sqlite3_step $STMT
    } SQLITE_ROW
    do_test capi3-2.7 {
      sqlite3_step $STMT
    } SQLITE_DONE
    do_test capi3-2.8 {
      sqlite3_finalize $STMT
    } SQLITE_OK
  }

} ;# endif utf16

# rename sqlite3_open sqlite3_open_old
# proc sqlite3_open {fname options} {sqlite3_open_new $fname $options}

do_test capi3-3.1 {
  set db2 [sqlite3_open test.db {}]
  sqlite3_errcode $db2
} {SQLITE_OK}
# FIX ME: Should test the db handle works.
do_test capi3-3.2 {
  sqlite3_close $db2
} {SQLITE_OK}
do_test capi3-3.3 {
  catch {
    set db2 [sqlite3_open /bogus/path/test.db {}]
  }
  sqlite3_extended_errcode $db2
} {SQLITE_CANTOPEN}
do_test capi3-3.4 {
  sqlite3_errmsg $db2
} {unable to open database file}
do_test capi3-3.5 {
  sqlite3_close $db2
} {SQLITE_OK}
do_test capi3-3.6.1-misuse {
  sqlite3_close $db2
} {SQLITE_MISUSE}
do_test capi3-3.6.2-misuse {
  sqlite3_errmsg $db2
} {library routine called out of sequence}
ifcapable {utf16} {
  do_test capi3-3.6.3-misuse {
    utf8 [sqlite3_errmsg16 $db2]
  } {library routine called out of sequence}
}

do_test capi3-3.7 {
  set db2 [sqlite3_open]
  sqlite3_errcode $db2
} {SQLITE_OK}
do_test capi3-3.8 {
  sqlite3_close $db2
} {SQLITE_OK}

# rename sqlite3_open ""
# rename sqlite3_open_old sqlite3_open

ifcapable {utf16} {
do_test capi3-4.1 {
  set db2 [sqlite3_open16 [utf16 test.db] {}]
  sqlite3_errcode $db2
} {SQLITE_OK}
# FIX ME: Should test the db handle works.
do_test capi3-4.2 {
  sqlite3_close $db2
} {SQLITE_OK}
do_test capi3-4.3 {
  catch {
    set db2 [sqlite3_open16 [utf16 /bogus/path/test.db] {}]
  }
  sqlite3_errcode $db2
} {SQLITE_CANTOPEN}
do_test capi3-4.4 {
  utf8 [sqlite3_errmsg16 $db2]
} {unable to open database file}
do_test capi3-4.5 {
  sqlite3_close $db2
} {SQLITE_OK}
} ;# utf16

# This proc is used to test the following API calls:
#
# sqlite3_column_count
# sqlite3_column_name
# sqlite3_column_name16
# sqlite3_column_decltype
# sqlite3_column_decltype16
#
# $STMT is a compiled SQL statement. $test is a prefix
# to use for test names within this proc. $names is a list
# of the column names that should be returned by $STMT.
# $decltypes is a list of column declaration types for $STMT.
#
# Example:
#
# set STMT [sqlite3_prepare "SELECT 1, 2, 2;" -1 DUMMY]
# check_header test1.1 {1 2 3} {"" "" ""}
#
proc check_header {STMT test names decltypes} {

  # Use the return value of sqlite3_column_count() to build
  # a list of column indexes. i.e. If sqlite3_column_count
  # is 3, build the list {0 1 2}.
  set ::idxlist [list]
  set ::numcols [sqlite3_column_count $STMT]
  for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i}

  # Column names in UTF-8
  do_test $test.1 {
    set cnamelist [list]
    foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} 
    set cnamelist
  } $names

  # Column names in UTF-16
  ifcapable {utf16} {
    do_test $test.2 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]]
      }
      set cnamelist
    } $names
  }

  # Column names in UTF-8
  do_test $test.3 {
    set cnamelist [list]
    foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} 
    set cnamelist
  } $names

  # Column names in UTF-16
  ifcapable {utf16} {
    do_test $test.4 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]]
      }
      set cnamelist
    } $names
  }

  # Column names in UTF-8
  do_test $test.5 {
    set cnamelist [list]
    foreach i $idxlist {lappend cnamelist [sqlite3_column_decltype $STMT $i]} 
    set cnamelist
  } $decltypes

  # Column declaration types in UTF-16
  ifcapable {utf16} {
    do_test $test.6 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [utf8 [sqlite3_column_decltype16 $STMT $i]]
      }
      set cnamelist
    } $decltypes
  }


  # Test some out of range conditions:
  ifcapable {utf16} {
    do_test $test.7 {
      list \
        [sqlite3_column_name $STMT -1] \
        [sqlite3_column_name16 $STMT -1] \
        [sqlite3_column_decltype $STMT -1] \
        [sqlite3_column_decltype16 $STMT -1] \
        [sqlite3_column_name $STMT $numcols] \
        [sqlite3_column_name16 $STMT $numcols] \
        [sqlite3_column_decltype $STMT $numcols] \
        [sqlite3_column_decltype16 $STMT $numcols]
    } {{} {} {} {} {} {} {} {}}
  }
} 

# This proc is used to test the following API calls:
#
# sqlite3_column_origin_name
# sqlite3_column_origin_name16
# sqlite3_column_table_name
# sqlite3_column_table_name16
# sqlite3_column_database_name
# sqlite3_column_database_name16
#
# $STMT is a compiled SQL statement. $test is a prefix
# to use for test names within this proc. $names is a list
# of the column names that should be returned by $STMT.
# $decltypes is a list of column declaration types for $STMT.
#
# Example:
#
# set STMT [sqlite3_prepare "SELECT 1, 2, 2;" -1 DUMMY]
# check_header test1.1 {1 2 3} {"" "" ""}
#
proc check_origin_header {STMT test dbs tables cols} {
  # If sqlite3_column_origin_name() and friends are not compiled into
  # this build, this proc is a no-op.
  ifcapable columnmetadata {
    # Use the return value of sqlite3_column_count() to build
    # a list of column indexes. i.e. If sqlite3_column_count
    # is 3, build the list {0 1 2}.
    set ::idxlist [list]
    set ::numcols [sqlite3_column_count $STMT]
    for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i}
  
    # Database names in UTF-8
    do_test $test.8 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [sqlite3_column_database_name $STMT $i]
      } 
      set cnamelist
    } $dbs
  
    # Database names in UTF-16
    ifcapable {utf16} {
      do_test $test.9 {
        set cnamelist [list]
        foreach i $idxlist {
          lappend cnamelist [utf8 [sqlite3_column_database_name16 $STMT $i]]
        }
        set cnamelist
      } $dbs
    }
  
    # Table names in UTF-8
    do_test $test.10 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [sqlite3_column_table_name $STMT $i]
      } 
      set cnamelist
    } $tables
  
    # Table names in UTF-16
    ifcapable {utf16} {
      do_test $test.11 {
        set cnamelist [list]
        foreach i $idxlist {
          lappend cnamelist [utf8 [sqlite3_column_table_name16 $STMT $i]]
        }
        set cnamelist
      } $tables
    }
  
    # Origin names in UTF-8
    do_test $test.12 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [sqlite3_column_origin_name $STMT $i]
      } 
      set cnamelist
    } $cols
  
    # Origin declaration types in UTF-16
    ifcapable {utf16} {
      do_test $test.13 {
        set cnamelist [list]
        foreach i $idxlist {
          lappend cnamelist [utf8 [sqlite3_column_origin_name16 $STMT $i]]
        }
        set cnamelist
      } $cols
    }
  }
}

# This proc is used to test the following APIs:
#
# sqlite3_data_count
# sqlite3_column_type
# sqlite3_column_int
# sqlite3_column_text
# sqlite3_column_text16
# sqlite3_column_double
#
# $STMT is a compiled SQL statement for which the previous call 
# to sqlite3_step returned SQLITE_ROW. $test is a prefix to use 
# for test names within this proc. $types is a list of the 
# manifest types for the current row. $ints, $doubles and $strings
# are lists of the integer, real and string representations of
# the values in the current row.
#
# Example:
#
# set STMT [sqlite3_prepare "SELECT 'hello', 1.1, NULL" -1 DUMMY]
# sqlite3_step $STMT
# check_data test1.2 {TEXT REAL NULL} {0 1 0} {0 1.1 0} {hello 1.1 {}}
#
proc check_data {STMT test types ints doubles strings} {

  # Use the return value of sqlite3_column_count() to build
  # a list of column indexes. i.e. If sqlite3_column_count
  # is 3, build the list {0 1 2}.
  set ::idxlist [list]
  set numcols [sqlite3_data_count $STMT]
  for {set i 0} {$i < $numcols} {incr i} {lappend ::idxlist $i}

# types
do_test $test.1 {
  set types [list]
  foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]}
  set types
} $types

# Integers
do_test $test.2 {
  set ints [list]
  foreach i $idxlist {lappend ints [sqlite3_column_int64 $STMT $i]}
  set ints
} $ints

# bytes
set lens [list]
foreach i $::idxlist {
  lappend lens [string length [lindex $strings $i]]
}
do_test $test.3 {
  set bytes [list]
  set lens [list]
  foreach i $idxlist {
    lappend bytes [sqlite3_column_bytes $STMT $i]
  }
  set bytes
} $lens

# bytes16
ifcapable {utf16} {
  set lens [list]
  foreach i $::idxlist {
    lappend lens [expr 2 * [string length [lindex $strings $i]]]
  }
  do_test $test.4 {
    set bytes [list]
    set lens [list]
    foreach i $idxlist {
      lappend bytes [sqlite3_column_bytes16 $STMT $i]
    }
    set bytes
  } $lens
}

# Blob
do_test $test.5 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_blob $STMT $i]}
  set utf8
} $strings

# UTF-8
do_test $test.6 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]}
  set utf8
} $strings

# Floats
do_test $test.7 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]}
  set utf8
} $doubles

# UTF-16
ifcapable {utf16} {
  do_test $test.8 {
    set utf8 [list]
    foreach i $idxlist {lappend utf8 [utf8 [sqlite3_column_text16 $STMT $i]]}
    set utf8
  } $strings
}

# Integers
do_test $test.9 {
  set ints [list]
  foreach i $idxlist {lappend ints [sqlite3_column_int $STMT $i]}
  set ints
} $ints

# Floats
do_test $test.10 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]}
  set utf8
} $doubles

# UTF-8
do_test $test.11 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]}
  set utf8
} $strings

# Types
do_test $test.12 {
  set types [list]
  foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]}
  set types
} $types

# Test that an out of range request returns the equivalent of NULL
do_test $test.13 {
  sqlite3_column_int $STMT -1
} {0}
do_test $test.13 {
  sqlite3_column_text $STMT -1
} {}

}

ifcapable !floatingpoint {
  finish_test
  return
}

do_test capi3-5.0 {
  execsql {
    CREATE TABLE t1(a VARINT, b BLOB, c VARCHAR(16));
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES('one', 'two', NULL);
    INSERT INTO t1 VALUES(1.2, 1.3, 1.4);
  }
  set sql "SELECT * FROM t1"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_column_count $STMT
} 3

check_header $STMT capi3-5.1 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3-5.1 {main main main} {t1 t1 t1} {a b c}
do_test capi3-5.2 {
  sqlite3_step $STMT
} SQLITE_ROW

check_header $STMT capi3-5.3 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3-5.3 {main main main} {t1 t1 t1} {a b c}
check_data $STMT capi3-5.4 {INTEGER INTEGER TEXT} {1 2 3} {1.0 2.0 3.0} {1 2 3}

do_test capi3-5.5 {
  sqlite3_step $STMT
} SQLITE_ROW

check_header $STMT capi3-5.6 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3-5.6 {main main main} {t1 t1 t1} {a b c}
check_data $STMT capi3-5.7 {TEXT TEXT NULL} {0 0 0} {0.0 0.0 0.0} {one two {}}

do_test capi3-5.8 {
  sqlite3_step $STMT
} SQLITE_ROW

check_header $STMT capi3-5.9 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3-5.9 {main main main} {t1 t1 t1} {a b c}
check_data $STMT capi3-5.10 {FLOAT FLOAT TEXT} {1 1 1} {1.2 1.3 1.4} {1.2 1.3 1.4}

do_test capi3-5.11 {
  sqlite3_step $STMT
} SQLITE_DONE

do_test capi3-5.12 {
  sqlite3_finalize $STMT
} SQLITE_OK

do_test capi3-5.20 {
  set sql "SELECT a, sum(b), max(c) FROM t1 GROUP BY a"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_column_count $STMT
} 3

check_header $STMT capi3-5.21 {a sum(b) max(c)} {VARINT {} {}}
check_origin_header $STMT capi3-5.22 {main {} {}} {t1 {} {}} {a {} {}}
do_test capi3-5.23 {
  sqlite3_finalize $STMT
} SQLITE_OK

do_test capi3-5.30 {
  set sql "SELECT a AS x, sum(b) AS y, max(c) AS z FROM t1 AS m GROUP BY x"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_column_count $STMT
} 3

check_header $STMT capi3-5.31 {x y z} {VARINT {} {}}
check_origin_header $STMT capi3-5.32 {main {} {}} {t1 {} {}} {a {} {}}
do_test capi3-5.33 {
  sqlite3_finalize $STMT
} SQLITE_OK


set ::ENC [execsql {pragma encoding}]
db close

do_test capi3-6.0 {
  sqlite3 db test.db
  set DB [sqlite3_connection_pointer db]
  sqlite3_key $DB xyzzy
  set sql {SELECT a FROM t1 order by rowid}
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  expr 0
} {0}
do_test capi3-6.1 {
  db cache flush
  sqlite3_close $DB
} {SQLITE_BUSY}
do_test capi3-6.2 {
  sqlite3_step $STMT
} {SQLITE_ROW}
check_data $STMT capi3-6.3 {INTEGER} {1} {1.0} {1}
do_test capi3-6.3 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3-6.4-misuse {
  db cache flush
  sqlite3_close $DB
} {SQLITE_OK}
db close

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}

if {![sqlite3 -has-codec]} {
  # Test what happens when the library encounters a newer file format.
  do_test capi3-7.1 {
    set_file_format 5
  } {}
  do_test capi3-7.2 {
    sqlite3 db test.db
    catchsql {
      SELECT * FROM sqlite_master;
    }
  } {1 {unsupported file format}}
  db close
}

if {![sqlite3 -has-codec]} {
  # Now test that the library correctly handles bogus entries in the
  # sqlite_master table (schema corruption).
  do_test capi3-8.1 {
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql {
      CREATE TABLE t1(a);
    }
    db close
  } {}
  do_test capi3-8.2 {
    sqlite3 db test.db
    execsql {
      PRAGMA writable_schema=ON;
      INSERT INTO sqlite_master VALUES(NULL,NULL,NULL,NULL,NULL);
    }
    db close
  } {}
  do_test capi3-8.3 {
    sqlite3 db test.db
    catchsql {
      SELECT * FROM sqlite_master;
    }
  } {1 {malformed database schema (?)}}
  do_test capi3-8.4 {
    # Build a 5-field row record. The first field is a string 'table', and
    # subsequent fields are all NULL.
    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql {
      CREATE TABLE t1(a);
      PRAGMA writable_schema=ON;
      INSERT INTO sqlite_master VALUES('table',NULL,NULL,NULL,NULL);
    }
    db close
  } {};
  do_test capi3-8.5 {
    sqlite3 db test.db
    catchsql {
      SELECT * FROM sqlite_master;
    }
  } {1 {malformed database schema (?)}}
  db close
}
file delete -force test.db
file delete -force test.db-journal


# Test the english language string equivalents for sqlite error codes
set code2english [list \
SQLITE_OK         {not an error} \
SQLITE_ERROR      {SQL logic error or missing database} \
SQLITE_PERM       {access permission denied} \
SQLITE_ABORT      {callback requested query abort} \
SQLITE_BUSY       {database is locked} \
SQLITE_LOCKED     {database table is locked} \
SQLITE_NOMEM      {out of memory} \
SQLITE_READONLY   {attempt to write a readonly database} \
SQLITE_INTERRUPT  {interrupted} \
SQLITE_IOERR      {disk I/O error} \
SQLITE_CORRUPT    {database disk image is malformed} \
SQLITE_FULL       {database or disk is full} \
SQLITE_CANTOPEN   {unable to open database file} \
SQLITE_EMPTY      {table contains no data} \
SQLITE_SCHEMA     {database schema has changed} \
SQLITE_CONSTRAINT {constraint failed} \
SQLITE_MISMATCH   {datatype mismatch} \
SQLITE_MISUSE     {library routine called out of sequence} \
SQLITE_NOLFS      {large file support is disabled} \
SQLITE_AUTH       {authorization denied} \
SQLITE_FORMAT     {auxiliary database format error} \
SQLITE_RANGE      {bind or column index out of range} \
SQLITE_NOTADB     {file is encrypted or is not a database} \
unknownerror      {unknown error} \
]

set test_number 1
foreach {code english} $code2english {
  do_test capi3-9.$test_number "sqlite3_test_errstr $code" $english
  incr test_number
}

# Test the error message when a "real" out of memory occurs.
ifcapable memdebug {
  do_test capi3-10-1 {
    sqlite3 db test.db
    set DB [sqlite3_connection_pointer db]
    sqlite3_memdebug_fail 1
    catchsql {
      select * from sqlite_master;
    }
  } {1 {out of memory}}
  do_test capi3-10-2 {
    sqlite3_errmsg $::DB
  } {out of memory}
  ifcapable {utf16} {
    do_test capi3-10-3 {
      utf8 [sqlite3_errmsg16 $::DB]
    } {out of memory}
  }
  db close
  sqlite3_memdebug_fail -1
  do_test capi3-10-4 {
    sqlite3 db test.db
    set DB [sqlite3_connection_pointer db]
    sqlite3_memdebug_fail 1
    catchsql {
      select * from sqlite_master where rowid>5;
    }
  } {1 {out of memory}}
  do_test capi3-10-5 {
    sqlite3_errmsg $::DB
  } {out of memory}
  ifcapable {utf16} {
    do_test capi3-10-6 {
      utf8 [sqlite3_errmsg16 $::DB]
    } {out of memory}
  }
  db close
  sqlite3_memdebug_fail -1
}

# The following tests - capi3-11.* - test that a COMMIT or ROLLBACK
# statement issued while there are still outstanding VMs that are part of
# the transaction fails.
sqlite3 db test.db
set DB [sqlite3_connection_pointer db]
sqlite_register_test_function $DB func
do_test capi3-11.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 'int');
    INSERT INTO t1 VALUES(2, 'notatype');
  }
} {}
do_test capi3-11.1.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3-11.2 {
  set STMT [sqlite3_prepare $DB "SELECT func(b, a) FROM t1" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}

# As of 3.6.5 a COMMIT is OK during while a query is still running -
# as long as it is a read-only query and not an incremental BLOB write.
#
do_test capi3-11.3.1 {
  catchsql {
    COMMIT;
  }
} {0 {}}
do_test capi3-11.3.2 {
  sqlite3_extended_errcode $DB
} {SQLITE_OK}
do_test capi3-11.3.3 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3-11.3.4 {
  db eval {PRAGMA lock_status}
} {main shared temp closed}

do_test capi3-11.4 {
  sqlite3_step $STMT
} {SQLITE_ERROR}
do_test capi3-11.5 {
  sqlite3_finalize $STMT
} {SQLITE_ERROR}
do_test capi3-11.6 {
  catchsql {
    SELECT * FROM t1;
  }
} {0 {1 int 2 notatype}}
do_test capi3-11.7 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3-11.8 {
  execsql {
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    BEGIN;
    INSERT INTO t2 VALUES(3);
  }
} {}
do_test capi3-11.8.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3-11.9 {
  set STMT [sqlite3_prepare $DB "SELECT a FROM t2" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-11.9.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3-11.9.2 {
  catchsql {
    ROLLBACK;
  }
} {1 {cannot rollback transaction - SQL statements in progress}}
do_test capi3-11.9.3 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3-11.10 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-11.11 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-11.12 {
  sqlite3_step $STMT
} {SQLITE_DONE}
do_test capi3-11.13 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3-11.14 {
  execsql {
    SELECT a FROM t2;
  }
} {1 2 3}
do_test capi3-11.14.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3-11.15 {
  catchsql {
    ROLLBACK;
  }
} {0 {}}
do_test capi3-11.15.1 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3-11.16 {
  execsql {
    SELECT a FROM t2;
  }
} {1 2}

# Sanity check on the definition of 'outstanding VM'. This means any VM
# that has had sqlite3_step() called more recently than sqlite3_finalize() or
# sqlite3_reset(). So a VM that has just been prepared or reset does not
# count as an active VM.
do_test capi3-11.17 {
  execsql {
    BEGIN;
  }
} {}
do_test capi3-11.18 {
  set STMT [sqlite3_prepare $DB "SELECT a FROM t1" -1 TAIL]
  catchsql {
    COMMIT;
  }
} {0 {}}
do_test capi3-11.19 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-11.20 {
  catchsql {
    BEGIN;
    COMMIT;
  }
} {0 {}}
do_test capi3-11.20 {
  sqlite3_reset $STMT
  catchsql {
    COMMIT;
  }
} {1 {cannot commit - no transaction is active}}
do_test capi3-11.21 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

# The following tests - capi3-12.* - check that its Ok to start a
# transaction while other VMs are active, and that its Ok to execute
# atomic updates in the same situation 
#
do_test capi3-12.1 {
  set STMT [sqlite3_prepare $DB "SELECT a FROM t2" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-12.2 {
  catchsql {
    INSERT INTO t1 VALUES(3, NULL);
  }
} {0 {}}
do_test capi3-12.3 {
  catchsql {
    INSERT INTO t2 VALUES(4);
  }
} {0 {}}
do_test capi3-12.4 {
  catchsql {
    BEGIN;
    INSERT INTO t1 VALUES(4, NULL);
  }
} {0 {}}
do_test capi3-12.5 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-12.5.1 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3-12.6 {
  sqlite3_step $STMT
} {SQLITE_DONE}
do_test capi3-12.7 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3-12.8 {
  execsql {
    COMMIT;
    SELECT a FROM t1;
  }
} {1 2 3 4}

# Test cases capi3-13.* test the sqlite3_clear_bindings() and 
# sqlite3_sleep APIs.
#
if {[llength [info commands sqlite3_clear_bindings]]>0} {
  do_test capi3-13.1 {
    execsql {
      DELETE FROM t1;
    }
    set STMT [sqlite3_prepare $DB "INSERT INTO t1 VALUES(?, ?)" -1 TAIL]
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test capi3-13.2 {
    sqlite3_reset $STMT
    sqlite3_bind_text $STMT 1 hello 5
    sqlite3_bind_text $STMT 2 world 5
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test capi3-13.3 {
    sqlite3_reset $STMT
    sqlite3_clear_bindings $STMT
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test capi3-13-4 {
    sqlite3_finalize $STMT
    execsql {
      SELECT * FROM t1;
    }
  } {{} {} hello world {} {}}
}
if {[llength [info commands sqlite3_sleep]]>0} {
  do_test capi3-13-5 {
    set ms [sqlite3_sleep 80]
    expr {$ms==80 || $ms==1000}
  } {1}
}

# Ticket #1219:  Make sure binding APIs can handle a NULL pointer.
#
do_test capi3-14.1-misuse {
  set rc [catch {sqlite3_bind_text 0 1 hello 5} msg]
  lappend rc $msg
} {1 SQLITE_MISUSE}

# Ticket #1650:  Honor the nBytes parameter to sqlite3_prepare.
#
do_test capi3-15.1 {
  set sql {SELECT * FROM t2}
  set nbytes [string length $sql]
  append sql { WHERE a==1}
  set STMT [sqlite3_prepare $DB $sql $nbytes TAIL]
  sqlite3_step $STMT
  sqlite3_column_int $STMT 0
} {1}
do_test capi3-15.2 {
  sqlite3_step $STMT
  sqlite3_column_int $STMT 0
} {2}
do_test capi3-15.3 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3-15.4 {
  #        123456789 1234567
  set sql {SELECT 1234567890}
  set STMT [sqlite3_prepare $DB $sql 8 TAIL]
  sqlite3_step $STMT
  set v1 [sqlite3_column_int $STMT 0]
  sqlite3_finalize $STMT
  set v1
} {1}
do_test capi3-15.5 {
  #        123456789 1234567
  set sql {SELECT 1234567890}
  set STMT [sqlite3_prepare $DB $sql 9 TAIL]
  sqlite3_step $STMT
  set v1 [sqlite3_column_int $STMT 0]
  sqlite3_finalize $STMT
  set v1
} {12}
do_test capi3-15.6 {
  #        123456789 1234567
  set sql {SELECT 1234567890}
  set STMT [sqlite3_prepare $DB $sql 12 TAIL]
  sqlite3_step $STMT
  set v1 [sqlite3_column_int $STMT 0]
  sqlite3_finalize $STMT
  set v1
} {12345}
do_test capi3-15.7 {
  #        123456789 1234567
  set sql {SELECT 12.34567890}
  set STMT [sqlite3_prepare $DB $sql 12 TAIL]
  sqlite3_step $STMT
  set v1 [sqlite3_column_double $STMT 0]
  sqlite3_finalize $STMT
  set v1
} {12.34}
do_test capi3-15.8 {
  #        123456789 1234567
  set sql {SELECT 12.34567890}
  set STMT [sqlite3_prepare $DB $sql 14 TAIL]
  sqlite3_step $STMT
  set v1 [sqlite3_column_double $STMT 0]
  sqlite3_finalize $STMT
  set v1
} {12.3456}

# Make sure code is always generated even if an IF EXISTS or 
# IF NOT EXISTS clause is present that the table does not or
# does exists.  That way we will always have a prepared statement
# to expire when the schema changes.
#
do_test capi3-16.1 {
  set sql {DROP TABLE IF EXISTS t3}
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT!=""}
} {1}
do_test capi3-16.2 {
  set sql {CREATE TABLE IF NOT EXISTS t1(x,y)}
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT!=""}
} {1}

# But still we do not generate code if there is no SQL
#
do_test capi3-16.3 {
  set STMT [sqlite3_prepare $DB {} -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT==""}
} {1}
do_test capi3-16.4 {
  set STMT [sqlite3_prepare $DB {;} -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT==""}
} {1}

# Ticket #2426:  Misuse of sqlite3_column_* by calling it after
# a sqlite3_reset should be harmless.
#
do_test capi3-17.1 {
  set STMT [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL]
  sqlite3_step $STMT
  sqlite3_column_int $STMT 0
} {1}
do_test capi3-17.2 {
  sqlite3_reset $STMT
  sqlite3_column_int $STMT 0
} {0}
do_test capi3-17.3 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

# Verify that sqlite3_step() fails with an SQLITE_SCHEMA error
# when the statement is prepared with sqlite3_prepare() (not
# sqlite3_prepare_v2()) and the schema has changed.
#
do_test capi3-18.1 {
  set STMT [sqlite3_prepare db {SELECT * FROM t2} -1 TAIL]
  sqlite3 db2 test.db
  db2 eval {CREATE TABLE t3(x)}
  db2 close
  sqlite3_step $STMT
} {SQLITE_ERROR}
do_test capi3-18.2 {
  sqlite3_reset $STMT
  sqlite3_errcode db
} {SQLITE_SCHEMA}
do_test capi3-18.3 {
  sqlite3_errmsg db
} {database schema has changed}
# The error persist on retry when sqlite3_prepare() has been used.
do_test capi3-18.4 {
  sqlite3_step $STMT
} {SQLITE_ERROR}
do_test capi3-18.5 {
  sqlite3_reset $STMT
  sqlite3_errcode db
} {SQLITE_SCHEMA}
do_test capi3-18.6 {
  sqlite3_errmsg db
} {database schema has changed}
sqlite3_finalize $STMT

# Ticket #3134.  Prepare a statement with an nBytes parameter of 0.
# Make sure this works correctly and does not reference memory out of
# range.
#
do_test capi3-19.1 {
  sqlite3_prepare_tkt3134 db
} {}

# Tests of the interface when no VFS is registered.
#
if {![info exists tester_do_binarylog]} {
  db close
  vfs_unregister_all
  do_test capi3-20.1 {
    sqlite3_sleep 100
  } {0}
  vfs_reregister_all
}

finish_test

Added test/capi3b.test.



































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# 2004 September 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the callback-free C/C++ API and in
# particular the behavior of sqlite3_step() when trying to commit
# with lock contention.
#
# $Id: capi3b.test,v 1.4 2007/08/10 19:46:14 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# These tests depend on the pager holding changes in cache
# until it is time to commit.  But that won't happen if the
# soft-heap-limit is set too low.  So disable the soft heap limit
# for the duration of this test.
#
sqlite3_soft_heap_limit 0


set DB [sqlite3_connection_pointer db]
sqlite3 db2 test.db
set DB2 [sqlite3_connection_pointer db2]

# Create some data in the database
#
do_test capi3b-1.1 {
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    SELECT * FROM t1
  }
} {1 2}

# Make sure the second database connection can see the data
#
do_test capi3b-1.2 {
  execsql {
    SELECT * FROM t1
  } db2
} {1 2}

# First database connection acquires a shared lock
#
do_test capi3b-1.3 {
  execsql {
    BEGIN;
    SELECT * FROM t1;
  }
} {1 2}

# Second database connection tries to write.  The sqlite3_step()
# function returns SQLITE_BUSY because it cannot commit.
#
do_test capi3b-1.4 {
  set VM [sqlite3_prepare $DB2 {INSERT INTO t1 VALUES(3)} -1 TAIL]
  sqlite3_step $VM
} SQLITE_BUSY

# The sqlite3_step call can be repeated multiple times.
#
do_test capi3b-1.5.1 {
  sqlite3_step $VM
} SQLITE_BUSY
do_test capi3b-1.5.2 {
  sqlite3_step $VM
} SQLITE_BUSY

# The first connection closes its transaction.  This allows the second
# connections sqlite3_step to succeed.
#
do_test capi3b-1.6 {
  execsql COMMIT
  sqlite3_step $VM
} SQLITE_DONE
do_test capi3b-1.7 {
  sqlite3_finalize $VM
} SQLITE_OK
do_test capi3b-1.8 {
  execsql {SELECT * FROM t1} db2
} {1 2 3}
do_test capi3b-1.9 {
  execsql {SELECT * FROM t1}
} {1 2 3}

# Start doing a SELECT with one connection.  This gets a SHARED lock.
# Then do an INSERT with the other connection.  The INSERT should
# not be able to complete until the SELECT finishes.
#
do_test capi3b-2.1 {
  set VM1 [sqlite3_prepare $DB {SELECT * FROM t1} -1 TAIL]
  sqlite3_step $VM1
} SQLITE_ROW
do_test capi3b-2.2 {
  sqlite3_column_text $VM1 0
} 1
do_test capi3b-2.3 {
  set VM2 [sqlite3_prepare $DB2 {INSERT INTO t1 VALUES(4)} -1 TAIL]
  sqlite3_step $VM2
} SQLITE_BUSY
do_test capi3b-2.4 {
  sqlite3_step $VM1
} SQLITE_ROW
do_test capi3b-2.5 {
  sqlite3_column_text $VM1 0
} 2
do_test capi3b-2.6 {
  sqlite3_step $VM2
} SQLITE_BUSY
do_test capi3b-2.7 {
  sqlite3_step $VM1
} SQLITE_ROW
do_test capi3b-2.8 {
  sqlite3_column_text $VM1 0
} 3
do_test capi3b-2.9 {
  sqlite3_step $VM2
} SQLITE_BUSY
do_test capi3b-2.10 {
  sqlite3_step $VM1
} SQLITE_DONE
do_test capi3b-2.11 {
  sqlite3_step $VM2
} SQLITE_DONE
do_test capi3b-2.12 {
  sqlite3_finalize $VM1
  sqlite3_finalize $VM2
  execsql {SELECT * FROM t1}
} {1 2 3 4}

catch {db2 close}

sqlite3_soft_heap_limit $soft_limit
finish_test

Added test/capi3c.test.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
# 2006 November 08
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  
#
# This is a copy of the capi3.test file that has been adapted to
# test the new sqlite3_prepare_v2 interface.
#
# $Id: capi3c.test,v 1.23 2009/07/22 07:27:57 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Return the UTF-16 representation of the supplied UTF-8 string $str.
# If $nt is true, append two 0x00 bytes as a nul terminator.
proc utf16 {str {nt 1}} {
  set r [encoding convertto unicode $str]
  if {$nt} {
    append r "\x00\x00"
  }
  return $r
}

# Return the UTF-8 representation of the supplied UTF-16 string $str. 
proc utf8 {str} {
  # If $str ends in two 0x00 0x00 bytes, knock these off before
  # converting to UTF-8 using TCL.
  binary scan $str \c* vals
  if {[lindex $vals end]==0 && [lindex $vals end-1]==0} {
    set str [binary format \c* [lrange $vals 0 end-2]]
  }

  set r [encoding convertfrom unicode $str]
  return $r
}

# These tests complement those in capi2.test. They are organized
# as follows:
#
# capi3c-1.*: Test sqlite3_prepare_v2 
# capi3c-2.*: Test sqlite3_prepare16_v2 
# capi3c-3.*: Test sqlite3_open
# capi3c-4.*: Test sqlite3_open16
# capi3c-5.*: Test the various sqlite3_result_* APIs
# capi3c-6.*: Test that sqlite3_close fails if there are outstanding VMs.
#

set DB [sqlite3_connection_pointer db]

do_test capi3c-1.0 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3c-1.1 {
  set STMT [sqlite3_prepare_v2 $DB {SELECT name FROM sqlite_master} -1 TAIL]
  sqlite3_finalize $STMT
  set TAIL
} {}
do_test capi3c-1.2.1 {
  sqlite3_errcode $DB
} {SQLITE_OK}
do_test capi3c-1.2.2 {
  sqlite3_extended_errcode $DB
} {SQLITE_OK}
do_test capi3c-1.3 {
  sqlite3_errmsg $DB
} {not an error}
do_test capi3c-1.4 {
  set sql {SELECT name FROM sqlite_master;SELECT 10}
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  sqlite3_finalize $STMT
  set TAIL
} {SELECT 10}
do_test capi3c-1.5 {
  set sql {SELECT namex FROM sqlite_master}
  catch {
    set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  }
} {1}
do_test capi3c-1.6.1 {
  sqlite3_errcode $DB
} {SQLITE_ERROR}
do_test capi3c-1.6.2 {
  sqlite3_extended_errcode $DB
} {SQLITE_ERROR}
do_test capi3c-1.7 {
  sqlite3_errmsg $DB
} {no such column: namex}


ifcapable {utf16} {
  do_test capi3c-2.1 {
    set sql16 [utf16 {SELECT name FROM sqlite_master}]
    set STMT [sqlite3_prepare16_v2  $DB $sql16 -1 ::TAIL]
    sqlite3_finalize $STMT
    utf8 $::TAIL
  } {}
  do_test capi3c-2.2 {
    set sql [utf16 {SELECT name FROM sqlite_master;SELECT 10}]
    set STMT [sqlite3_prepare16_v2  $DB $sql -1 TAIL]
    sqlite3_finalize $STMT
    utf8 $TAIL
  } {SELECT 10}
  do_test capi3c-2.3 {
    set sql [utf16 {SELECT namex FROM sqlite_master}]
    catch {
      set STMT [sqlite3_prepare16_v2  $DB $sql -1 TAIL]
    }
  } {1}
  do_test capi3c-2.4.1 {
    sqlite3_errcode $DB
  } {SQLITE_ERROR}
  do_test capi3c-2.4.2 {
    sqlite3_extended_errcode $DB
  } {SQLITE_ERROR}
  do_test capi3c-2.5 {
    sqlite3_errmsg $DB
  } {no such column: namex}

  ifcapable schema_pragmas {
    do_test capi3c-2.6 {
      execsql {CREATE TABLE tablename(x)}
      set sql16 [utf16 {PRAGMA table_info("TableName")}]
      set STMT [sqlite3_prepare16_v2  $DB $sql16 -1 TAIL]
      sqlite3_step $STMT
    } SQLITE_ROW
    do_test capi3c-2.7 {
      sqlite3_step $STMT
    } SQLITE_DONE
    do_test capi3c-2.8 {
      sqlite3_finalize $STMT
    } SQLITE_OK
  }

} ;# endif utf16

# rename sqlite3_open sqlite3_open_old
# proc sqlite3_open {fname options} {sqlite3_open_new $fname $options}

do_test capi3c-3.1 {
  set db2 [sqlite3_open test.db {}]
  sqlite3_errcode $db2
} {SQLITE_OK}
# FIX ME: Should test the db handle works.
do_test capi3c-3.2 {
  sqlite3_close $db2
} {SQLITE_OK}
do_test capi3c-3.3 {
  catch {
    set db2 [sqlite3_open /bogus/path/test.db {}]
  }
  sqlite3_errcode $db2
} {SQLITE_CANTOPEN}
do_test capi3c-3.4 {
  sqlite3_errmsg $db2
} {unable to open database file}
do_test capi3c-3.5 {
  sqlite3_close $db2
} {SQLITE_OK}
do_test capi3c-3.6.1-misuse {
  sqlite3_close $db2
} {SQLITE_MISUSE}
do_test capi3c-3.6.2-misuse {
  sqlite3_errmsg $db2
} {library routine called out of sequence}
ifcapable {utf16} {
  do_test capi3c-3.6.3-misuse {
    utf8 [sqlite3_errmsg16 $db2]
  } {library routine called out of sequence}
}

# rename sqlite3_open ""
# rename sqlite3_open_old sqlite3_open

ifcapable {utf16} {
do_test capi3c-4.1 {
  set db2 [sqlite3_open16 [utf16 test.db] {}]
  sqlite3_errcode $db2
} {SQLITE_OK}
# FIX ME: Should test the db handle works.
do_test capi3c-4.2 {
  sqlite3_close $db2
} {SQLITE_OK}
do_test capi3c-4.3 {
  catch {
    set db2 [sqlite3_open16 [utf16 /bogus/path/test.db] {}]
  }
  sqlite3_errcode $db2
} {SQLITE_CANTOPEN}
do_test capi3c-4.4 {
  utf8 [sqlite3_errmsg16 $db2]
} {unable to open database file}
do_test capi3c-4.5 {
  sqlite3_close $db2
} {SQLITE_OK}
} ;# utf16

# This proc is used to test the following API calls:
#
# sqlite3_column_count
# sqlite3_column_name
# sqlite3_column_name16
# sqlite3_column_decltype
# sqlite3_column_decltype16
#
# $STMT is a compiled SQL statement. $test is a prefix
# to use for test names within this proc. $names is a list
# of the column names that should be returned by $STMT.
# $decltypes is a list of column declaration types for $STMT.
#
# Example:
#
# set STMT [sqlite3_prepare_v2 "SELECT 1, 2, 2;" -1 DUMMY]
# check_header test1.1 {1 2 3} {"" "" ""}
#
proc check_header {STMT test names decltypes} {

  # Use the return value of sqlite3_column_count() to build
  # a list of column indexes. i.e. If sqlite3_column_count
  # is 3, build the list {0 1 2}.
  set ::idxlist [list]
  set ::numcols [sqlite3_column_count $STMT]
  for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i}

  # Column names in UTF-8
  do_test $test.1 {
    set cnamelist [list]
    foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} 
    set cnamelist
  } $names

  # Column names in UTF-16
  ifcapable {utf16} {
    do_test $test.2 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]]
      }
      set cnamelist
    } $names
  }

  # Column names in UTF-8
  do_test $test.3 {
    set cnamelist [list]
    foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} 
    set cnamelist
  } $names

  # Column names in UTF-16
  ifcapable {utf16} {
    do_test $test.4 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]]
      }
      set cnamelist
    } $names
  }

  # Column names in UTF-8
  do_test $test.5 {
    set cnamelist [list]
    foreach i $idxlist {lappend cnamelist [sqlite3_column_decltype $STMT $i]} 
    set cnamelist
  } $decltypes

  # Column declaration types in UTF-16
  ifcapable {utf16} {
    do_test $test.6 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [utf8 [sqlite3_column_decltype16 $STMT $i]]
      }
      set cnamelist
    } $decltypes
  }


  # Test some out of range conditions:
  ifcapable {utf16} {
    do_test $test.7 {
      list \
        [sqlite3_column_name $STMT -1] \
        [sqlite3_column_name16 $STMT -1] \
        [sqlite3_column_decltype $STMT -1] \
        [sqlite3_column_decltype16 $STMT -1] \
        [sqlite3_column_name $STMT $numcols] \
        [sqlite3_column_name16 $STMT $numcols] \
        [sqlite3_column_decltype $STMT $numcols] \
        [sqlite3_column_decltype16 $STMT $numcols]
    } {{} {} {} {} {} {} {} {}}
  }
} 

# This proc is used to test the following API calls:
#
# sqlite3_column_origin_name
# sqlite3_column_origin_name16
# sqlite3_column_table_name
# sqlite3_column_table_name16
# sqlite3_column_database_name
# sqlite3_column_database_name16
#
# $STMT is a compiled SQL statement. $test is a prefix
# to use for test names within this proc. $names is a list
# of the column names that should be returned by $STMT.
# $decltypes is a list of column declaration types for $STMT.
#
# Example:
#
# set STMT [sqlite3_prepare_v2 "SELECT 1, 2, 2;" -1 DUMMY]
# check_header test1.1 {1 2 3} {"" "" ""}
#
proc check_origin_header {STMT test dbs tables cols} {
  # If sqlite3_column_origin_name() and friends are not compiled into
  # this build, this proc is a no-op.
ifcapable columnmetadata {

    # Use the return value of sqlite3_column_count() to build
    # a list of column indexes. i.e. If sqlite3_column_count
    # is 3, build the list {0 1 2}.
    set ::idxlist [list]
    set ::numcols [sqlite3_column_count $STMT]
    for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i}
  
    # Database names in UTF-8
    do_test $test.8 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [sqlite3_column_database_name $STMT $i]
      } 
      set cnamelist
    } $dbs
  
    # Database names in UTF-16
    ifcapable {utf16} {
      do_test $test.9 {
        set cnamelist [list]
        foreach i $idxlist {
          lappend cnamelist [utf8 [sqlite3_column_database_name16 $STMT $i]]
        }
        set cnamelist
      } $dbs
    }
  
    # Table names in UTF-8
    do_test $test.10 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [sqlite3_column_table_name $STMT $i]
      } 
      set cnamelist
    } $tables
  
    # Table names in UTF-16
    ifcapable {utf16} {
      do_test $test.11 {
        set cnamelist [list]
        foreach i $idxlist {
          lappend cnamelist [utf8 [sqlite3_column_table_name16 $STMT $i]]
        }
        set cnamelist
      } $tables
    }
  
    # Origin names in UTF-8
    do_test $test.12 {
      set cnamelist [list]
      foreach i $idxlist {
        lappend cnamelist [sqlite3_column_origin_name $STMT $i]
      } 
      set cnamelist
    } $cols
  
    # Origin declaration types in UTF-16
    ifcapable {utf16} {
      do_test $test.13 {
        set cnamelist [list]
        foreach i $idxlist {
          lappend cnamelist [utf8 [sqlite3_column_origin_name16 $STMT $i]]
        }
        set cnamelist
      } $cols
    }
  }
}

# This proc is used to test the following APIs:
#
# sqlite3_data_count
# sqlite3_column_type
# sqlite3_column_int
# sqlite3_column_text
# sqlite3_column_text16
# sqlite3_column_double
#
# $STMT is a compiled SQL statement for which the previous call 
# to sqlite3_step returned SQLITE_ROW. $test is a prefix to use 
# for test names within this proc. $types is a list of the 
# manifest types for the current row. $ints, $doubles and $strings
# are lists of the integer, real and string representations of
# the values in the current row.
#
# Example:
#
# set STMT [sqlite3_prepare_v2 "SELECT 'hello', 1.1, NULL" -1 DUMMY]
# sqlite3_step $STMT
# check_data test1.2 {TEXT REAL NULL} {0 1 0} {0 1.1 0} {hello 1.1 {}}
#
proc check_data {STMT test types ints doubles strings} {

  # Use the return value of sqlite3_column_count() to build
  # a list of column indexes. i.e. If sqlite3_column_count
  # is 3, build the list {0 1 2}.
  set ::idxlist [list]
  set numcols [sqlite3_data_count $STMT]
  for {set i 0} {$i < $numcols} {incr i} {lappend ::idxlist $i}

# types
do_test $test.1 {
  set types [list]
  foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]}
  set types
} $types

# Integers
do_test $test.2 {
  set ints [list]
  foreach i $idxlist {lappend ints [sqlite3_column_int64 $STMT $i]}
  set ints
} $ints

# bytes
set lens [list]
foreach i $::idxlist {
  lappend lens [string length [lindex $strings $i]]
}
do_test $test.3 {
  set bytes [list]
  set lens [list]
  foreach i $idxlist {
    lappend bytes [sqlite3_column_bytes $STMT $i]
  }
  set bytes
} $lens

# bytes16
ifcapable {utf16} {
  set lens [list]
  foreach i $::idxlist {
    lappend lens [expr 2 * [string length [lindex $strings $i]]]
  }
  do_test $test.4 {
    set bytes [list]
    set lens [list]
    foreach i $idxlist {
      lappend bytes [sqlite3_column_bytes16 $STMT $i]
    }
    set bytes
  } $lens
}

# Blob
do_test $test.5 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_blob $STMT $i]}
  set utf8
} $strings

# UTF-8
do_test $test.6 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]}
  set utf8
} $strings

# Floats
do_test $test.7 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]}
  set utf8
} $doubles

# UTF-16
ifcapable {utf16} {
  do_test $test.8 {
    set utf8 [list]
    foreach i $idxlist {lappend utf8 [utf8 [sqlite3_column_text16 $STMT $i]]}
    set utf8
  } $strings
}

# Integers
do_test $test.9 {
  set ints [list]
  foreach i $idxlist {lappend ints [sqlite3_column_int $STMT $i]}
  set ints
} $ints

# Floats
do_test $test.10 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]}
  set utf8
} $doubles

# UTF-8
do_test $test.11 {
  set utf8 [list]
  foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]}
  set utf8
} $strings

# Types
do_test $test.12 {
  set types [list]
  foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]}
  set types
} $types

# Test that an out of range request returns the equivalent of NULL
do_test $test.13 {
  sqlite3_column_int $STMT -1
} {0}
do_test $test.13 {
  sqlite3_column_text $STMT -1
} {}

}

ifcapable !floatingpoint {
  finish_test
  return
}

do_test capi3c-5.0 {
  execsql {
    CREATE TABLE t1(a VARINT, b BLOB, c VARCHAR(16));
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES('one', 'two', NULL);
    INSERT INTO t1 VALUES(1.2, 1.3, 1.4);
  }
  set sql "SELECT * FROM t1"
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  sqlite3_column_count $STMT
} 3

check_header $STMT capi3c-5.1 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3c-5.1 {main main main} {t1 t1 t1} {a b c}
do_test capi3c-5.2 {
  sqlite3_step $STMT
} SQLITE_ROW

check_header $STMT capi3c-5.3 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3c-5.3 {main main main} {t1 t1 t1} {a b c}
check_data $STMT capi3c-5.4 {INTEGER INTEGER TEXT} {1 2 3} {1.0 2.0 3.0} {1 2 3}

do_test capi3c-5.5 {
  sqlite3_step $STMT
} SQLITE_ROW

check_header $STMT capi3c-5.6 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3c-5.6 {main main main} {t1 t1 t1} {a b c}
check_data $STMT capi3c-5.7 {TEXT TEXT NULL} {0 0 0} {0.0 0.0 0.0} {one two {}}

do_test capi3c-5.8 {
  sqlite3_step $STMT
} SQLITE_ROW

check_header $STMT capi3c-5.9 {a b c} {VARINT BLOB VARCHAR(16)}
check_origin_header $STMT capi3c-5.9 {main main main} {t1 t1 t1} {a b c}
check_data $STMT capi3c-5.10 {FLOAT FLOAT TEXT} {1 1 1} {1.2 1.3 1.4} {1.2 1.3 1.4}

do_test capi3c-5.11 {
  sqlite3_step $STMT
} SQLITE_DONE

do_test capi3c-5.12 {
  sqlite3_finalize $STMT
} SQLITE_OK

do_test capi3c-5.20 {
  set sql "SELECT a, sum(b), max(c) FROM t1 GROUP BY a"
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  sqlite3_column_count $STMT
} 3

check_header $STMT capi3c-5.21 {a sum(b) max(c)} {VARINT {} {}}
check_origin_header $STMT capi3c-5.22 {main {} {}} {t1 {} {}} {a {} {}}
do_test capi3c-5.23 {
  sqlite3_finalize $STMT
} SQLITE_OK


set ::ENC [execsql {pragma encoding}]
db close

do_test capi3c-6.0 {
  sqlite3 db test.db
  set DB [sqlite3_connection_pointer db]
  sqlite3_key $DB xyzzy
  set sql {SELECT a FROM t1 order by rowid}
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  expr 0
} {0}
do_test capi3c-6.1 {
  db cache flush
  sqlite3_close $DB
} {SQLITE_BUSY}
do_test capi3c-6.2 {
  sqlite3_step $STMT
} {SQLITE_ROW}
check_data $STMT capi3c-6.3 {INTEGER} {1} {1.0} {1}
do_test capi3c-6.3 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3c-6.4 {
  db cache flush
  sqlite3_close $DB
} {SQLITE_OK}
do_test capi3c-6.99-misuse {
  db close
} {}

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}

if {![sqlite3 -has-codec]} {
  # Test what happens when the library encounters a newer file format.
  do_test capi3c-7.1 {
    set_file_format 5
  } {}
  do_test capi3c-7.2 {
    sqlite3 db test.db
    catchsql {
      SELECT * FROM sqlite_master;
    }
  } {1 {unsupported file format}}
  db close
}

if {![sqlite3 -has-codec]} {
  # Now test that the library correctly handles bogus entries in the
  # sqlite_master table (schema corruption).
  do_test capi3c-8.1 {
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql {
      CREATE TABLE t1(a);
    }
    db close
  } {}
  do_test capi3c-8.2 {
    sqlite3 db test.db
    execsql {
      PRAGMA writable_schema=ON;
      INSERT INTO sqlite_master VALUES(NULL,NULL,NULL,NULL,NULL);
    }
    db close
  } {}
  do_test capi3c-8.3 {
    sqlite3 db test.db
    catchsql {
      SELECT * FROM sqlite_master;
    }
  } {1 {malformed database schema (?)}}
  do_test capi3c-8.4 {
    # Build a 5-field row record. The first field is a string 'table', and
    # subsequent fields are all NULL.
    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql {
      CREATE TABLE t1(a);
      PRAGMA writable_schema=ON;
      INSERT INTO sqlite_master VALUES('table',NULL,NULL,NULL,NULL);
    }
    db close
  } {};
  do_test capi3c-8.5 {
    sqlite3 db test.db
    catchsql {
      SELECT * FROM sqlite_master;
    }
  } {1 {malformed database schema (?)}}
  db close
}
file delete -force test.db
file delete -force test.db-journal


# Test the english language string equivalents for sqlite error codes
set code2english [list \
SQLITE_OK         {not an error} \
SQLITE_ERROR      {SQL logic error or missing database} \
SQLITE_PERM       {access permission denied} \
SQLITE_ABORT      {callback requested query abort} \
SQLITE_BUSY       {database is locked} \
SQLITE_LOCKED     {database table is locked} \
SQLITE_NOMEM      {out of memory} \
SQLITE_READONLY   {attempt to write a readonly database} \
SQLITE_INTERRUPT  {interrupted} \
SQLITE_IOERR      {disk I/O error} \
SQLITE_CORRUPT    {database disk image is malformed} \
SQLITE_FULL       {database or disk is full} \
SQLITE_CANTOPEN   {unable to open database file} \
SQLITE_EMPTY      {table contains no data} \
SQLITE_SCHEMA     {database schema has changed} \
SQLITE_CONSTRAINT {constraint failed} \
SQLITE_MISMATCH   {datatype mismatch} \
SQLITE_MISUSE     {library routine called out of sequence} \
SQLITE_NOLFS      {large file support is disabled} \
SQLITE_AUTH       {authorization denied} \
SQLITE_FORMAT     {auxiliary database format error} \
SQLITE_RANGE      {bind or column index out of range} \
SQLITE_NOTADB     {file is encrypted or is not a database} \
unknownerror      {unknown error} \
]

set test_number 1
foreach {code english} $code2english {
  do_test capi3c-9.$test_number "sqlite3_test_errstr $code" $english
  incr test_number
}

# Test the error message when a "real" out of memory occurs.
ifcapable memdebug {
  do_test capi3c-10-1 {
    sqlite3 db test.db
    set DB [sqlite3_connection_pointer db]
    sqlite3_memdebug_fail 0
    catchsql {
      select * from sqlite_master;
    }
  } {1 {out of memory}}
  do_test capi3c-10-2 {
    sqlite3_errmsg $::DB
  } {out of memory}
  ifcapable {utf16} {
    do_test capi3c-10-3 {
      utf8 [sqlite3_errmsg16 $::DB]
    } {out of memory}
  }
  db close
  sqlite3_memdebug_fail -1
}

# The following tests - capi3c-11.* - test that a COMMIT or ROLLBACK
# statement issued while there are still outstanding VMs that are part of
# the transaction fails.
sqlite3 db test.db
set DB [sqlite3_connection_pointer db]
sqlite_register_test_function $DB func
do_test capi3c-11.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 'int');
    INSERT INTO t1 VALUES(2, 'notatype');
  }
} {}
do_test capi3c-11.1.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3c-11.2 {
  set STMT [sqlite3_prepare_v2 $DB "SELECT func(b, a) FROM t1" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}

# As of 3.6.5 a COMMIT is OK during while a query is still running -
# as long as it is a read-only query and not an incremental BLOB write.
#
do_test capi3-11.3.1 {
  catchsql {
    COMMIT;
  }
} {0 {}}
do_test capi3-11.3.2 {
  sqlite3_extended_errcode $DB
} {SQLITE_OK}
do_test capi3-11.3.3 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3-11.3.4 {
  db eval {PRAGMA lock_status}
} {main shared temp closed}

do_test capi3c-11.4 {
  sqlite3_step $STMT
} {SQLITE_ERROR}
do_test capi3c-11.5 {
  sqlite3_finalize $STMT
} {SQLITE_ERROR}
do_test capi3c-11.6 {
  catchsql {
    SELECT * FROM t1;
  }
} {0 {1 int 2 notatype}}
do_test capi3c-11.7 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3c-11.8 {
  execsql {
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    BEGIN;
    INSERT INTO t2 VALUES(3);
  }
} {}
do_test capi3c-11.8.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3c-11.9 {
  set STMT [sqlite3_prepare_v2 $DB "SELECT a FROM t2" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-11.9.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3c-11.9.2 {
  catchsql {
    ROLLBACK;
  }
} {1 {cannot rollback transaction - SQL statements in progress}}
do_test capi3c-11.9.3 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3c-11.10 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-11.11 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-11.12 {
  sqlite3_step $STMT
} {SQLITE_DONE}
do_test capi3c-11.13 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3c-11.14 {
  execsql {
    SELECT a FROM t2;
  }
} {1 2 3}
do_test capi3c-11.14.1 {
  sqlite3_get_autocommit $DB
} 0
do_test capi3c-11.15 {
  catchsql {
    ROLLBACK;
  }
} {0 {}}
do_test capi3c-11.15.1 {
  sqlite3_get_autocommit $DB
} 1
do_test capi3c-11.16 {
  execsql {
    SELECT a FROM t2;
  }
} {1 2}

# Sanity check on the definition of 'outstanding VM'. This means any VM
# that has had sqlite3_step() called more recently than sqlite3_finalize() or
# sqlite3_reset(). So a VM that has just been prepared or reset does not
# count as an active VM.
do_test capi3c-11.17 {
  execsql {
    BEGIN;
  }
} {}
do_test capi3c-11.18 {
  set STMT [sqlite3_prepare_v2 $DB "SELECT a FROM t1" -1 TAIL]
  catchsql {
    COMMIT;
  }
} {0 {}}
do_test capi3c-11.19 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-11.20 {
  catchsql {
    BEGIN;
    COMMIT;
  }
} {0 {}}
do_test capi3c-11.20 {
  sqlite3_reset $STMT
  catchsql {
    COMMIT;
  }
} {1 {cannot commit - no transaction is active}}
do_test capi3c-11.21 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

# The following tests - capi3c-12.* - check that its Ok to start a
# transaction while other VMs are active, and that its Ok to execute
# atomic updates in the same situation 
#
do_test capi3c-12.1 {
  set STMT [sqlite3_prepare_v2 $DB "SELECT a FROM t2" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-12.2 {
  catchsql {
    INSERT INTO t1 VALUES(3, NULL);
  }
} {0 {}}
do_test capi3c-12.3 {
  catchsql {
    INSERT INTO t2 VALUES(4);
  }
} {0 {}}
do_test capi3c-12.4 {
  catchsql {
    BEGIN;
    INSERT INTO t1 VALUES(4, NULL);
  }
} {0 {}}
do_test capi3c-12.5 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-12.5.1 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test capi3c-12.6 {
  sqlite3_step $STMT
} {SQLITE_DONE}
do_test capi3c-12.7 {
  sqlite3_finalize $STMT
} {SQLITE_OK}
do_test capi3c-12.8 {
  execsql {
    COMMIT;
    SELECT a FROM t1;
  }
} {1 2 3 4}

# Test cases capi3c-13.* test the sqlite3_clear_bindings() and 
# sqlite3_sleep APIs.
#
if {[llength [info commands sqlite3_clear_bindings]]>0} {
  do_test capi3c-13.1 {
    execsql {
      DELETE FROM t1;
    }
    set STMT [sqlite3_prepare_v2 $DB "INSERT INTO t1 VALUES(?, ?)" -1 TAIL]
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test capi3c-13.2 {
    sqlite3_reset $STMT
    sqlite3_bind_text $STMT 1 hello 5
    sqlite3_bind_text $STMT 2 world 5
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test capi3c-13.3 {
    sqlite3_reset $STMT
    sqlite3_clear_bindings $STMT
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test capi3c-13-4 {
    sqlite3_finalize $STMT
    execsql {
      SELECT * FROM t1;
    }
  } {{} {} hello world {} {}}
}
if {[llength [info commands sqlite3_sleep]]>0} {
  do_test capi3c-13-5 {
    set ms [sqlite3_sleep 80]
    expr {$ms==80 || $ms==1000}
  } {1}
}

# Ticket #1219:  Make sure binding APIs can handle a NULL pointer.
#
do_test capi3c-14.1 {
  set rc [catch {sqlite3_bind_text 0 1 hello 5} msg]
  lappend rc $msg
} {1 SQLITE_MISUSE}

# Ticket #1650:  Honor the nBytes parameter to sqlite3_prepare.
#
do_test capi3c-15.1 {
  set sql {SELECT * FROM t2}
  set nbytes [string length $sql]
  append sql { WHERE a==1}
  set STMT [sqlite3_prepare_v2 $DB $sql $nbytes TAIL]
  sqlite3_step $STMT
  sqlite3_column_int $STMT 0
} {1}
do_test capi3c-15.2 {
  sqlite3_step $STMT
  sqlite3_column_int $STMT 0
} {2}
do_test capi3c-15.3 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

# Make sure code is always generated even if an IF EXISTS or 
# IF NOT EXISTS clause is present that the table does not or
# does exists.  That way we will always have a prepared statement
# to expire when the schema changes.
#
do_test capi3c-16.1 {
  set sql {DROP TABLE IF EXISTS t3}
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT!=""}
} {1}
do_test capi3c-16.2 {
  set sql {CREATE TABLE IF NOT EXISTS t1(x,y)}
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT!=""}
} {1}

# But still we do not generate code if there is no SQL
#
do_test capi3c-16.3 {
  set STMT [sqlite3_prepare_v2 $DB {} -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT==""}
} {1}
do_test capi3c-16.4 {
  set STMT [sqlite3_prepare_v2 $DB {;} -1 TAIL]
  sqlite3_finalize $STMT
  expr {$STMT==""}
} {1}

# Ticket #2154.
#
do_test capi3c-17.1 {
  set STMT [sqlite3_prepare_v2 $DB {SELECT max(a) FROM t2} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-17.2 {
  sqlite3_column_int $STMT 0
} 4
do_test capi3c-17.3 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-17.4 {
  sqlite3_reset $STMT
  db eval {CREATE INDEX i2 ON t2(a)}
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-17.5 {
  sqlite3_column_int $STMT 0
} 4
do_test capi3c-17.6 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-17.7 {
  sqlite3_reset $STMT
  db eval {DROP INDEX i2}
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-17.8 {
  sqlite3_column_int $STMT 0
} 4
do_test capi3c-17.9 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-17.10 {
  sqlite3_finalize $STMT
  set STMT [sqlite3_prepare_v2 $DB {SELECT b FROM t1 WHERE a=?} -1 TAIL]
  sqlite3_bind_int $STMT 1 2
  db eval {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,'one');
    INSERT INTO t1 VALUES(2,'two');
    INSERT INTO t1 VALUES(3,'three');
    INSERT INTO t1 VALUES(4,'four');
  }
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-17.11 {
  sqlite3_column_text $STMT 0
} two
do_test capi3c-17.12 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-17.13 {
  sqlite3_reset $STMT
  db eval {CREATE INDEX i1 ON t1(a)}
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-17.14 {
  sqlite3_column_text $STMT 0
} two
do_test capi3c-17.15 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-17.16 {
  sqlite3_reset $STMT
  db eval {DROP INDEX i1}
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-17.17 {
  sqlite3_column_text $STMT 0
} two
do_test capi3c-17.18 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-17.99 {
  sqlite3_finalize $STMT
} SQLITE_OK

# On the mailing list it has been reported that finalizing after
# an SQLITE_BUSY return leads to a segfault.  Here we test that case.
#
do_test capi3c-18.1 {
  sqlite3 db2 test.db
  set STMT [sqlite3_prepare_v2 $DB {SELECT max(a) FROM t1} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-18.2 {
  sqlite3_column_int $STMT 0
} 4
do_test capi3c-18.3 {
  sqlite3_reset $STMT
  db2 eval {BEGIN EXCLUSIVE}
  sqlite3_step $STMT
} SQLITE_BUSY
do_test capi3c-18.4 {
  sqlite3_finalize $STMT
} SQLITE_BUSY
do_test capi3c-18.5 {
  db2 eval {COMMIT}
  db2 close
} {}

# Ticket #2158.  The sqlite3_step() will still return SQLITE_SCHEMA
# if the database schema changes in a way that makes the statement
# no longer valid.
#
do_test capi3c-19.1 {
  db eval {
     CREATE TABLE t3(x,y);
     INSERT INTO t3 VALUES(1,2);
  }
  set STMT [sqlite3_prepare_v2 $DB {SELECT * FROM t3} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-19.2 {
  sqlite3_column_int $STMT 0
} 1
do_test capi3c-19.3 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-19.4 {
  sqlite3_reset $STMT
  db eval {DROP TABLE t3}
  sqlite3_step $STMT
} SQLITE_SCHEMA
do_test capi3c-19.4.1 {
  sqlite3_errmsg $DB
} {no such table: t3}
ifcapable deprecated {
  do_test capi3c-19.4.2 {
    sqlite3_expired $STMT
  } 1
}
do_test capi3c-19.4.3 {
  sqlite3_errmsg $DB
} {no such table: t3}
ifcapable deprecated {
  do_test capi3c-19.4.4 {
    sqlite3_expired 0
  } 1
}
do_test capi3c-19.5 {
  sqlite3_reset $STMT
  db eval {
     CREATE TABLE t3(x,y);
     INSERT INTO t3 VALUES(1,2);
  }
  sqlite3_step $STMT
} SQLITE_ROW
ifcapable deprecated {
  do_test capi3c-19.5.2 {
    sqlite3_expired $STMT
  } 0
}
do_test capi3c-19.6 {
  sqlite3_column_int $STMT 1
} 2
do_test capi3c-19.99 {
  sqlite3_finalize $STMT
} SQLITE_OK

# Make sure a change in a separate database connection does not
# cause an SQLITE_SCHEMA return.
#
do_test capi3c-20.1 {
  set STMT [sqlite3_prepare_v2 $DB {SELECT * FROM t3} -1 TAIL]
  sqlite3 db2 test.db
  db2 eval {CREATE TABLE t4(x)}
  sqlite3_step $STMT
} SQLITE_ROW
do_test capi3c-20.2 {
  sqlite3_column_int $STMT 1
} 2
do_test capi3c-20.3 {
  sqlite3_step $STMT
} SQLITE_DONE
do_test capi3c-20.4 {
  db2 close
  sqlite3_finalize $STMT
} SQLITE_OK

# Test that sqlite3_step() sets the database error code correctly.
# See ticket #2497.
#
ifcapable progress {
  do_test capi3c-21.1 {
    set STMT [sqlite3_prepare_v2 $DB {SELECT * FROM t3} -1 TAIL]
    db progress 5 "expr 1"
    sqlite3_step $STMT
  } {SQLITE_INTERRUPT}
  do_test capi3c-21.2 {
    sqlite3_extended_errcode $DB
  } {SQLITE_INTERRUPT}
  do_test capi3c-21.3 {
    sqlite3_finalize $STMT
  } {SQLITE_INTERRUPT}
  do_test capi3c-21.4 {
    set STMT [sqlite3_prepare $DB {SELECT * FROM t3} -1 TAIL]
    db progress 5 "expr 1"
    sqlite3_step $STMT
  } {SQLITE_ERROR}
  do_test capi3c-21.5 {
    sqlite3_errcode $DB
  } {SQLITE_ERROR}
  do_test capi3c-21.6 {
    sqlite3_finalize $STMT
  } {SQLITE_INTERRUPT}
  do_test capi3c-21.7 {
    sqlite3_errcode $DB
  } {SQLITE_INTERRUPT}
  do_test capi3c-21.8 {
    sqlite3_extended_errcode $DB
  } {SQLITE_INTERRUPT}
}

# Make sure sqlite3_result_error_code() returns the correct error code.
# See ticket #2940
#
do_test capi3c-22.1 {
  db progress 0 {}
  set STMT [sqlite3_prepare_v2 db {SELECT test_error('the message',3)} -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_PERM}
sqlite3_finalize $STMT
do_test capi3c-22.2 {
  set STMT [sqlite3_prepare_v2 db {SELECT test_error('the message',4)} -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ABORT}
sqlite3_finalize $STMT
do_test capi3c-22.3 {
  set STMT [sqlite3_prepare_v2 db {SELECT test_error('the message',16)} -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_EMPTY}
sqlite3_finalize $STMT

# For a multi-column result set where the same table column is repeated
# in multiple columns of the output, verify that doing a UTF-8 to UTF-16
# conversion (or vice versa) on one column does not change the value of
# the second.
#
ifcapable utf16 {
  do_test capi3c-23.1 {
    set STMT [sqlite3_prepare_v2 db {SELECT b,b,b,b FROM t1} -1 TAIL]
    sqlite3_step $STMT
  } {SQLITE_ROW}
  do_test capi3c-23.2 {
    sqlite3_column_text16 $STMT 0
    sqlite3_column_text $STMT 1
  } {one}
  do_test capi3c-23.3 {
    sqlite3_column_text16 $STMT 2
    sqlite3_column_text $STMT 3
  } {one}
  sqlite3_finalize $STMT
  do_test capi3c-23.4 {
    set STMT [sqlite3_prepare_v2 db {SELECT b||'x',b,b,b FROM t1} -1 TAIL]
    sqlite3_step $STMT
  } {SQLITE_ROW}
  do_test capi3c-23.5 {
    sqlite3_column_text16 $STMT 0
    sqlite3_column_text $STMT 1
  } {one}
  do_test capi3c-23.6 {
    sqlite3_column_text16 $STMT 2
    sqlite3_column_text $STMT 3
  } {one}
  sqlite3_finalize $STMT
}

# Test decltype on some SELECT statements that contain sub-selects.
#
proc decltype {zSql} {
  set ret [list]
  set STMT [sqlite3_prepare_v2 db $zSql -1 TAIL]
  for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} {
    lappend ret [sqlite3_column_decltype $STMT $i]
  }
  sqlite3_finalize $STMT
  return $ret
}
do_test capi3c-24.1 {
  execsql { CREATE TABLE t5(a INTEGER, b STRING, c DATETIME) }
  decltype {SELECT * FROM t5}
} {INTEGER STRING DATETIME}
do_test capi3c-24.2 {
  decltype {SELECT (SELECT c) FROM t5}
} {DATETIME}
do_test capi3c-24.3 {
  decltype {SELECT (SELECT * FROM (SELECT c)) FROM t5}
} {DATETIME}
do_test capi3c-24.4 {
  decltype {SELECT * FROM (SELECT * FROM t5 ORDER BY c LIMIT 1) ORDER BY b}
} {INTEGER STRING DATETIME}
do_test capi3c-24.5 {
  decltype {
    SELECT (SELECT x FROM (SELECT c AS x)) 
    FROM (SELECT * FROM t5 ORDER BY c LIMIT 1) ORDER BY b
  }
} {DATETIME}
do_test capi3c-24.3 {
  decltype {SELECT (SELECT x FROM (SELECT t5.a AS x)) FROM t5}
} {INTEGER}

finish_test

Added test/capi3d.test.



























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 2008 June 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  
#
# This file is devoted to testing the sqlite3_next_stmt interface.
#
# $Id: capi3d.test,v 1.2 2008/07/14 15:11:20 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create N prepared statements against database connection db
# and return a list of all the generated prepared statements.
#
proc make_prepared_statements {N} {
  set plist {}
  for {set i 0} {$i<$N} {incr i} {
    set sql "SELECT $i FROM sqlite_master WHERE name LIKE '%$i%'"
    if {rand()<0.33} {    
      set s [sqlite3_prepare_v2 db $sql -1 notused]
    } else {
      ifcapable utf16 {
        if {rand()<0.5} {
          set sql [encoding convertto unicode $sql]\x00\x00
          set s [sqlite3_prepare16 db $sql -1 notused]
        } else {
          set s [sqlite3_prepare db $sql -1 notused]
        }
      }
      ifcapable !utf16 {
        set s [sqlite3_prepare db $sql -1 notused]
      }
    }
    lappend plist $s
  }
  return $plist
}


# Scramble the $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# Database initially has no prepared statements.
#
do_test capi3d-1.1 {
  db cache flush
  sqlite3_next_stmt db 0
} {}

# Run the following tests for between 1 and 100 prepared statements.
#
for {set i 1} {$i<=100} {incr i} {
  set stmtlist [make_prepared_statements $i]
  do_test capi3d-1.2.$i.1 {
    set p [sqlite3_next_stmt db 0]
    set x {}
    while {$p!=""} {
      lappend x $p
      set p [sqlite3_next_stmt db $p]
    }
    lsort $x
  } [lsort $stmtlist]
  do_test capi3-1.2.$i.2 {
    foreach p [scramble $::stmtlist] {
      sqlite3_finalize $p
    }
    sqlite3_next_stmt db 0
  } {}
}
      

finish_test

Added test/cast.test.





















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# 2005 June 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CAST operator.
#
# $Id: cast.test,v 1.10 2008/11/06 15:33:04 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only run these tests if the build includes the CAST operator
ifcapable !cast {
  finish_test
  return
}

# Tests for the CAST( AS blob), CAST( AS text) and CAST( AS numeric) built-ins
#
ifcapable bloblit {
  do_test cast-1.1 {
    execsql {SELECT x'616263'}
  } abc
  do_test cast-1.2 {
    execsql {SELECT typeof(x'616263')}
  } blob
  do_test cast-1.3 {
    execsql {SELECT CAST(x'616263' AS text)}
  } abc
  do_test cast-1.4 {
    execsql {SELECT typeof(CAST(x'616263' AS text))}
  } text
  do_test cast-1.5 {
    execsql {SELECT CAST(x'616263' AS numeric)}
  } 0
  do_test cast-1.6 {
    execsql {SELECT typeof(CAST(x'616263' AS numeric))}
  } integer
  do_test cast-1.7 {
    execsql {SELECT CAST(x'616263' AS blob)}
  } abc
  do_test cast-1.8 {
    execsql {SELECT typeof(CAST(x'616263' AS blob))}
  } blob
  do_test cast-1.9 {
    execsql {SELECT CAST(x'616263' AS integer)}
  } 0
  do_test cast-1.10 {
    execsql {SELECT typeof(CAST(x'616263' AS integer))}
  } integer
}
do_test cast-1.11 {
  execsql {SELECT null}
} {{}}
do_test cast-1.12 {
  execsql {SELECT typeof(NULL)}
} null
do_test cast-1.13 {
  execsql {SELECT CAST(NULL AS text)}
} {{}}
do_test cast-1.14 {
  execsql {SELECT typeof(CAST(NULL AS text))}
} null
do_test cast-1.15 {
  execsql {SELECT CAST(NULL AS numeric)}
} {{}}
do_test cast-1.16 {
  execsql {SELECT typeof(CAST(NULL AS numeric))}
} null
do_test cast-1.17 {
  execsql {SELECT CAST(NULL AS blob)}
} {{}}
do_test cast-1.18 {
  execsql {SELECT typeof(CAST(NULL AS blob))}
} null
do_test cast-1.19 {
  execsql {SELECT CAST(NULL AS integer)}
} {{}}
do_test cast-1.20 {
  execsql {SELECT typeof(CAST(NULL AS integer))}
} null
do_test cast-1.21 {
  execsql {SELECT 123}
} {123}
do_test cast-1.22 {
  execsql {SELECT typeof(123)}
} integer
do_test cast-1.23 {
  execsql {SELECT CAST(123 AS text)}
} {123}
do_test cast-1.24 {
  execsql {SELECT typeof(CAST(123 AS text))}
} text
do_test cast-1.25 {
  execsql {SELECT CAST(123 AS numeric)}
} 123
do_test cast-1.26 {
  execsql {SELECT typeof(CAST(123 AS numeric))}
} integer
do_test cast-1.27 {
  execsql {SELECT CAST(123 AS blob)}
} {123}
do_test cast-1.28 {
  execsql {SELECT typeof(CAST(123 AS blob))}
} blob
do_test cast-1.29 {
  execsql {SELECT CAST(123 AS integer)}
} {123}
do_test cast-1.30 {
  execsql {SELECT typeof(CAST(123 AS integer))}
} integer
do_test cast-1.31 {
  execsql {SELECT 123.456}
} {123.456}
do_test cast-1.32 {
  execsql {SELECT typeof(123.456)}
} real
do_test cast-1.33 {
  execsql {SELECT CAST(123.456 AS text)}
} {123.456}
do_test cast-1.34 {
  execsql {SELECT typeof(CAST(123.456 AS text))}
} text
do_test cast-1.35 {
  execsql {SELECT CAST(123.456 AS numeric)}
} 123.456
do_test cast-1.36 {
  execsql {SELECT typeof(CAST(123.456 AS numeric))}
} real
do_test cast-1.37 {
  execsql {SELECT CAST(123.456 AS blob)}
} {123.456}
do_test cast-1.38 {
  execsql {SELECT typeof(CAST(123.456 AS blob))}
} blob
do_test cast-1.39 {
  execsql {SELECT CAST(123.456 AS integer)}
} {123}
do_test cast-1.38 {
  execsql {SELECT typeof(CAST(123.456 AS integer))}
} integer
do_test cast-1.41 {
  execsql {SELECT '123abc'}
} {123abc}
do_test cast-1.42 {
  execsql {SELECT typeof('123abc')}
} text
do_test cast-1.43 {
  execsql {SELECT CAST('123abc' AS text)}
} {123abc}
do_test cast-1.44 {
  execsql {SELECT typeof(CAST('123abc' AS text))}
} text
do_test cast-1.45 {
  execsql {SELECT CAST('123abc' AS numeric)}
} 123
do_test cast-1.46 {
  execsql {SELECT typeof(CAST('123abc' AS numeric))}
} integer
do_test cast-1.47 {
  execsql {SELECT CAST('123abc' AS blob)}
} {123abc}
do_test cast-1.48 {
  execsql {SELECT typeof(CAST('123abc' AS blob))}
} blob
do_test cast-1.49 {
  execsql {SELECT CAST('123abc' AS integer)}
} 123
do_test cast-1.50 {
  execsql {SELECT typeof(CAST('123abc' AS integer))}
} integer
do_test cast-1.51 {
  execsql {SELECT CAST('123.5abc' AS numeric)}
} 123.5
do_test cast-1.53 {
  execsql {SELECT CAST('123.5abc' AS integer)}
} 123

do_test case-1.60 {
  execsql {SELECT CAST(null AS REAL)}
} {{}}
do_test case-1.61 {
  execsql {SELECT typeof(CAST(null AS REAL))}
} {null}
do_test case-1.62 {
  execsql {SELECT CAST(1 AS REAL)}
} {1.0}
do_test case-1.63 {
  execsql {SELECT typeof(CAST(1 AS REAL))}
} {real}
do_test case-1.64 {
  execsql {SELECT CAST('1' AS REAL)}
} {1.0}
do_test case-1.65 {
  execsql {SELECT typeof(CAST('1' AS REAL))}
} {real}
do_test case-1.66 {
  execsql {SELECT CAST('abc' AS REAL)}
} {0.0}
do_test case-1.67 {
  execsql {SELECT typeof(CAST('abc' AS REAL))}
} {real}
do_test case-1.68 {
  execsql {SELECT CAST(x'31' AS REAL)}
} {1.0}
do_test case-1.69 {
  execsql {SELECT typeof(CAST(x'31' AS REAL))}
} {real}


# Ticket #1662.  Ignore leading spaces in numbers when casting.
#
do_test cast-2.1 {
  execsql {SELECT CAST('   123' AS integer)}
} 123
do_test cast-2.2 {
  execsql {SELECT CAST('   -123.456' AS real)}
} -123.456

# ticket #2364.  Use full percision integers if possible when casting
# to numeric.  Do not fallback to real (and the corresponding 48-bit
# mantissa) unless absolutely necessary.
#
do_test cast-3.1 {
  execsql {SELECT CAST(9223372036854774800 AS integer)}
} 9223372036854774800
do_test cast-3.2 {
  execsql {SELECT CAST(9223372036854774800 AS numeric)}
} 9223372036854774800
do_test cast-3.3 {
  execsql {SELECT CAST(9223372036854774800 AS real)}
} 9.22337203685477e+18
do_test cast-3.4 {
  execsql {SELECT CAST(CAST(9223372036854774800 AS real) AS integer)}
} 9223372036854774784
do_test cast-3.5 {
  execsql {SELECT CAST(-9223372036854774800 AS integer)}
} -9223372036854774800
do_test cast-3.6 {
  execsql {SELECT CAST(-9223372036854774800 AS numeric)}
} -9223372036854774800
do_test cast-3.7 {
  execsql {SELECT CAST(-9223372036854774800 AS real)}
} -9.22337203685477e+18
do_test cast-3.8 {
  execsql {SELECT CAST(CAST(-9223372036854774800 AS real) AS integer)}
} -9223372036854774784
do_test cast-3.11 {
  execsql {SELECT CAST('9223372036854774800' AS integer)}
} 9223372036854774800
do_test cast-3.12 {
  execsql {SELECT CAST('9223372036854774800' AS numeric)}
} 9223372036854774800
do_test cast-3.13 {
  execsql {SELECT CAST('9223372036854774800' AS real)}
} 9.22337203685477e+18
ifcapable long_double {
  do_test cast-3.14 {
    execsql {SELECT CAST(CAST('9223372036854774800' AS real) AS integer)}
  } 9223372036854774784
}
do_test cast-3.15 {
  execsql {SELECT CAST('-9223372036854774800' AS integer)}
} -9223372036854774800
do_test cast-3.16 {
  execsql {SELECT CAST('-9223372036854774800' AS numeric)}
} -9223372036854774800
do_test cast-3.17 {
  execsql {SELECT CAST('-9223372036854774800' AS real)}
} -9.22337203685477e+18
ifcapable long_double {
  do_test cast-3.18 {
    execsql {SELECT CAST(CAST('-9223372036854774800' AS real) AS integer)}
  } -9223372036854774784
}
if {[db eval {PRAGMA encoding}]=="UTF-8"} {
  do_test cast-3.21 {
    execsql {SELECT CAST(x'39323233333732303336383534373734383030' AS integer)}
  } 9223372036854774800
  do_test cast-3.22 {
    execsql {SELECT CAST(x'39323233333732303336383534373734383030' AS numeric)}
  } 9223372036854774800
  do_test cast-3.23 {
    execsql {SELECT CAST(x'39323233333732303336383534373734383030' AS real)}
  } 9.22337203685477e+18
  ifcapable long_double {
    do_test cast-3.24 {
      execsql {
        SELECT CAST(CAST(x'39323233333732303336383534373734383030' AS real)
                    AS integer)
      }
    } 9223372036854774784
  }
}
do_test case-3.31 {
  execsql {SELECT CAST(NULL AS numeric)}
} {{}}

# Test to see if it is possible to trick SQLite into reading past 
# the end of a blob when converting it to a number.
do_test cast-3.32.1 {
  set blob "1234567890"
  set DB [sqlite3_connection_pointer db]
  set ::STMT [sqlite3_prepare $DB {SELECT CAST(? AS real)} -1 TAIL]
  sqlite3_bind_blob -static $::STMT 1 $blob 5
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test cast-3.32.2 {
  sqlite3_column_int $::STMT 0
} {12345}
do_test cast-3.32.3 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}


do_test cast-4.1 {
  db eval {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES('abc');
    SELECT a, CAST(a AS integer) FROM t1;
  }
} {abc 0}
do_test cast-4.2 {
  db eval {
    SELECT CAST(a AS integer), a FROM t1;
  }
} {0 abc}
do_test cast-4.3 {
  db eval {
    SELECT a, CAST(a AS integer), a FROM t1;
  }
} {abc 0 abc}
do_test cast-4.4 {
  db eval {
    SELECT CAST(a AS integer), a, CAST(a AS real), a FROM t1;
  }
} {0 abc 0.0 abc}

finish_test

Added test/check.test.













































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# 2005 November 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing CHECK constraints
#
# $Id: check.test,v 1.13 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only run these tests if the build includes support for CHECK constraints
ifcapable !check {
  finish_test
  return
}

do_test check-1.1 {
  execsql {
    CREATE TABLE t1(
      x INTEGER CHECK( x<5 ),
      y REAL CHECK( y>x )
    );
  }
} {}
do_test check-1.2 {
  execsql {
    INSERT INTO t1 VALUES(3,4);
    SELECT * FROM t1;
  }  
} {3 4.0}
do_test check-1.3 {
  catchsql {
    INSERT INTO t1 VALUES(6,7);
  }
} {1 {constraint failed}}
do_test check-1.4 {
  execsql {
    SELECT * FROM t1;
  }  
} {3 4.0}
do_test check-1.5 {
  catchsql {
    INSERT INTO t1 VALUES(4,3);
  }
} {1 {constraint failed}}
do_test check-1.6 {
  execsql {
    SELECT * FROM t1;
  }  
} {3 4.0}
do_test check-1.7 {
  catchsql {
    INSERT INTO t1 VALUES(NULL,6);
  }
} {0 {}}
do_test check-1.8 {
  execsql {
    SELECT * FROM t1;
  }  
} {3 4.0 {} 6.0}
do_test check-1.9 {
  catchsql {
    INSERT INTO t1 VALUES(2,NULL);
  }
} {0 {}}
do_test check-1.10 {
  execsql {
    SELECT * FROM t1;
  }  
} {3 4.0 {} 6.0 2 {}}
do_test check-1.11 {
  execsql {
    DELETE FROM t1 WHERE x IS NULL OR x!=3;
    UPDATE t1 SET x=2 WHERE x==3;
    SELECT * FROM t1;
  }
} {2 4.0}
do_test check-1.12 {
  catchsql {
    UPDATE t1 SET x=7 WHERE x==2
  }
} {1 {constraint failed}}
do_test check-1.13 {
  execsql {
    SELECT * FROM t1;
  }
} {2 4.0}
do_test check-1.14 {
  catchsql {
    UPDATE t1 SET x=5 WHERE x==2
  }
} {1 {constraint failed}}
do_test check-1.15 {
  execsql {
    SELECT * FROM t1;
  }
} {2 4.0}
do_test check-1.16 {
  catchsql {
    UPDATE t1 SET x=4, y=11 WHERE x==2
  }
} {0 {}}
do_test check-1.17 {
  execsql {
    SELECT * FROM t1;
  }
} {4 11.0}

do_test check-2.1 {
  execsql {
    CREATE TABLE t2(
      x INTEGER CHECK( typeof(coalesce(x,0))=="integer" ),
      y REAL CHECK( typeof(coalesce(y,0.1))=='real' ),
      z TEXT CHECK( typeof(coalesce(z,''))=='text' )
    );
  }
} {}
do_test check-2.2 {
  execsql {
    INSERT INTO t2 VALUES(1,2.2,'three');
    SELECT * FROM t2;
  }
} {1 2.2 three}
db close
sqlite3 db test.db
do_test check-2.3 {
  execsql {
    INSERT INTO t2 VALUES(NULL, NULL, NULL);
    SELECT * FROM t2;
  }
} {1 2.2 three {} {} {}}
do_test check-2.4 {
  catchsql {
    INSERT INTO t2 VALUES(1.1, NULL, NULL);
  }
} {1 {constraint failed}}
do_test check-2.5 {
  catchsql {
    INSERT INTO t2 VALUES(NULL, 5, NULL);
  }
} {1 {constraint failed}}
do_test check-2.6 {
  catchsql {
    INSERT INTO t2 VALUES(NULL, NULL, 3.14159);
  }
} {1 {constraint failed}}

ifcapable subquery {
  do_test check-3.1 {
    catchsql {
      CREATE TABLE t3(
        x, y, z,
        CHECK( x<(SELECT min(x) FROM t1) )
      );
    }
  } {1 {subqueries prohibited in CHECK constraints}}
}

do_test check-3.2 {
  execsql {
    SELECT name FROM sqlite_master ORDER BY name
  }
} {t1 t2}
do_test check-3.3 {
  catchsql {
    CREATE TABLE t3(
      x, y, z,
      CHECK( q<x )
    );
  }
} {1 {no such column: q}}
do_test check-3.4 {
  execsql {
    SELECT name FROM sqlite_master ORDER BY name
  }
} {t1 t2}
do_test check-3.5 {
  catchsql {
    CREATE TABLE t3(
      x, y, z,
      CHECK( t2.x<x )
    );
  }
} {1 {no such column: t2.x}}
do_test check-3.6 {
  execsql {
    SELECT name FROM sqlite_master ORDER BY name
  }
} {t1 t2}
do_test check-3.7 {
  catchsql {
    CREATE TABLE t3(
      x, y, z,
      CHECK( t3.x<25 )
    );
  }
} {0 {}}
do_test check-3.8 {
  execsql {
    INSERT INTO t3 VALUES(1,2,3);
    SELECT * FROM t3;
  }
} {1 2 3}
do_test check-3.9 {
  catchsql {
    INSERT INTO t3 VALUES(111,222,333);
  }
} {1 {constraint failed}}

do_test check-4.1 {
  execsql {
    CREATE TABLE t4(x, y,
      CHECK (
           x+y==11
        OR x*y==12
        OR x/y BETWEEN 5 AND 8
        OR -x==y+10
      )
    );
  }
} {}
do_test check-4.2 {
  execsql {
    INSERT INTO t4 VALUES(1,10);
    SELECT * FROM t4
  }
} {1 10}
do_test check-4.3 {
  execsql {
    UPDATE t4 SET x=4, y=3;
    SELECT * FROM t4
  }
} {4 3}
do_test check-4.3 {
  execsql {
    UPDATE t4 SET x=12, y=2;
    SELECT * FROM t4
  }
} {12 2}
do_test check-4.4 {
  execsql {
    UPDATE t4 SET x=12, y=-22;
    SELECT * FROM t4
  }
} {12 -22}
do_test check-4.5 {
  catchsql {
    UPDATE t4 SET x=0, y=1;
  }
} {1 {constraint failed}}
do_test check-4.6 {
  execsql {
    SELECT * FROM t4;
  }
} {12 -22}
do_test check-4.7 {
  execsql {
    PRAGMA ignore_check_constraints=ON;
    UPDATE t4 SET x=0, y=1;
    SELECT * FROM t4;
  }
} {0 1}
do_test check-4.8 {
  catchsql {
    PRAGMA ignore_check_constraints=OFF;
    UPDATE t4 SET x=0, y=2;
  }
} {1 {constraint failed}}
ifcapable vacuum {
  do_test check_4.9 {
    catchsql {
      VACUUM
    }
  } {0 {}}
}

do_test check-5.1 {
  catchsql {
    CREATE TABLE t5(x, y,
      CHECK( x*y<:abc )
    );
  }
} {1 {parameters prohibited in CHECK constraints}}
do_test check-5.2 {
  catchsql {
    CREATE TABLE t5(x, y,
      CHECK( x*y<? )
    );
  }
} {1 {parameters prohibited in CHECK constraints}}

ifcapable conflict {

do_test check-6.1 {
  execsql {SELECT * FROM t1}
} {4 11.0}
do_test check-6.2 {
  execsql {
    UPDATE OR IGNORE t1 SET x=5;
    SELECT * FROM t1;
  }
} {4 11.0}
do_test check-6.3 {
  execsql {
    INSERT OR IGNORE INTO t1 VALUES(5,4.0);
    SELECT * FROM t1;
  }
} {4 11.0}
do_test check-6.4 {
  execsql {
    INSERT OR IGNORE INTO t1 VALUES(2,20.0);
    SELECT * FROM t1;
  }
} {4 11.0 2 20.0}
do_test check-6.5 {
  catchsql {
    UPDATE OR FAIL t1 SET x=7-x, y=y+1;
  }
} {1 {constraint failed}}
do_test check-6.6 {
  execsql {
    SELECT * FROM t1;
  }
} {3 12.0 2 20.0}
do_test check-6.7 {
  catchsql {
    BEGIN;
    INSERT INTO t1 VALUES(1,30.0);
    INSERT OR ROLLBACK INTO t1 VALUES(8,40.0);
  }
} {1 {constraint failed}}
do_test check-6.8 {
  catchsql {
    COMMIT;
  }
} {1 {cannot commit - no transaction is active}}
do_test check-6.9 {
  execsql {
    SELECT * FROM t1
  }
} {3 12.0 2 20.0}

do_test check-6.11 {
  execsql {SELECT * FROM t1}
} {3 12.0 2 20.0}
do_test check-6.12 {
  catchsql {
    REPLACE INTO t1 VALUES(6,7);
  }
} {1 {constraint failed}}
do_test check-6.13 {
  execsql {SELECT * FROM t1}
} {3 12.0 2 20.0}
do_test check-6.14 {
  catchsql {
    INSERT OR IGNORE INTO t1 VALUES(6,7);
  }
} {0 {}}
do_test check-6.15 {
  execsql {SELECT * FROM t1}
} {3 12.0 2 20.0}


}

finish_test

Added test/collate1.test.







































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is page cache subsystem.
#
# $Id: collate1.test,v 1.5 2007/02/01 23:02:46 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#
# Tests are roughly organised as follows:
#
# collate1-1.* - Single-field ORDER BY with an explicit COLLATE clause.
# collate1-2.* - Multi-field ORDER BY with an explicit COLLATE clause.
# collate1-3.* - ORDER BY using a default collation type. Also that an 
#                explict collate type overrides a default collate type.
# collate1-4.* - ORDER BY using a data type.
#

#
# Collation type 'HEX'. If an argument can be interpreted as a hexadecimal
# number, then it is converted to one before the comparison is performed. 
# Numbers are less than other strings. If neither argument is a number, 
# [string compare] is used.
#
db collate HEX hex_collate
proc hex_collate {lhs rhs} {
  set lhs_ishex [regexp {^(0x|)[1234567890abcdefABCDEF]+$} $lhs]
  set rhs_ishex [regexp {^(0x|)[1234567890abcdefABCDEF]+$} $rhs]
  if {$lhs_ishex && $rhs_ishex} { 
    set lhsx [scan $lhs %x]
    set rhsx [scan $rhs %x]
    if {$lhs < $rhs} {return -1}
    if {$lhs == $rhs} {return 0}
    if {$lhs > $rhs} {return 1}
  }
  if {$lhs_ishex} {
    return -1;
  }
  if {$rhs_ishex} {
    return 1;
  }
  return [string compare $lhs $rhs]
}
db function hex {format 0x%X}

# Mimic the SQLite 2 collation type NUMERIC.
db collate numeric numeric_collate
proc numeric_collate {lhs rhs} {
  if {$lhs == $rhs} {return 0} 
  return [expr ($lhs>$rhs)?1:-1]
}

do_test collate1-1.0 {
  execsql {
    CREATE TABLE collate1t1(c1, c2);
    INSERT INTO collate1t1 VALUES(45, hex(45));
    INSERT INTO collate1t1 VALUES(NULL, NULL);
    INSERT INTO collate1t1 VALUES(281, hex(281));
  }
} {}
do_test collate1-1.1 {
  execsql {
    SELECT c2 FROM collate1t1 ORDER BY 1;
  }
} {{} 0x119 0x2D}
do_test collate1-1.2 {
  execsql {
    SELECT c2 FROM collate1t1 ORDER BY 1 COLLATE hex;
  }
} {{} 0x2D 0x119}
do_test collate1-1.3 {
  execsql {
    SELECT c2 FROM collate1t1 ORDER BY 1 COLLATE hex DESC;
  }
} {0x119 0x2D {}}
do_test collate1-1.4 {
  execsql {
   SELECT c2 FROM collate1t1 ORDER BY 1 COLLATE hex ASC;
  }
} {{} 0x2D 0x119}
do_test collate1-1.5 {
  execsql {
    SELECT c2 COLLATE hex FROM collate1t1 ORDER BY 1
  }
} {{} 0x2D 0x119}
do_test collate1-1.6 {
  execsql {
    SELECT c2 COLLATE hex FROM collate1t1 ORDER BY 1 ASC
  }
} {{} 0x2D 0x119}
do_test collate1-1.7 {
  execsql {
    SELECT c2 COLLATE hex FROM collate1t1 ORDER BY 1 DESC
  }
} {0x119 0x2D {}}
do_test collate1-1.99 {
  execsql {
    DROP TABLE collate1t1;
  }
} {}

do_test collate1-2.0 {
  execsql {
    CREATE TABLE collate1t1(c1, c2);
    INSERT INTO collate1t1 VALUES('5', '0x11');
    INSERT INTO collate1t1 VALUES('5', '0xA');
    INSERT INTO collate1t1 VALUES(NULL, NULL);
    INSERT INTO collate1t1 VALUES('7', '0xA');
    INSERT INTO collate1t1 VALUES('11', '0x11');
    INSERT INTO collate1t1 VALUES('11', '0x101');
  }
} {}
do_test collate1-2.2 {
  execsql {
    SELECT c1, c2 FROM collate1t1 ORDER BY 1 COLLATE numeric, 2 COLLATE hex;
  }
} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101}
do_test collate1-2.3 {
  execsql {
    SELECT c1, c2 FROM collate1t1 ORDER BY 1 COLLATE binary, 2 COLLATE hex;
  }
} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA}
do_test collate1-2.4 {
  execsql {
    SELECT c1, c2 FROM collate1t1 ORDER BY 1 COLLATE binary DESC, 2 COLLATE hex;
  }
} {7 0xA 5 0xA 5 0x11 11 0x11 11 0x101 {} {}}
do_test collate1-2.5 {
  execsql {
    SELECT c1, c2 FROM collate1t1 
        ORDER BY 1 COLLATE binary DESC, 2 COLLATE hex DESC;
  }
} {7 0xA 5 0x11 5 0xA 11 0x101 11 0x11 {} {}}
do_test collate1-2.6 {
  execsql {
    SELECT c1, c2 FROM collate1t1 
        ORDER BY 1 COLLATE binary ASC, 2 COLLATE hex ASC;
  }
} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA}
do_test collate1-2.12.1 {
  execsql {
    SELECT c1 COLLATE numeric, c2 FROM collate1t1 
     ORDER BY 1, 2 COLLATE hex;
  }
} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101}
do_test collate1-2.12.2 {
  execsql {
    SELECT c1 COLLATE hex, c2 FROM collate1t1 
     ORDER BY 1 COLLATE numeric, 2 COLLATE hex;
  }
} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101}
do_test collate1-2.12.3 {
  execsql {
    SELECT c1, c2 COLLATE hex FROM collate1t1 
     ORDER BY 1 COLLATE numeric, 2;
  }
} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101}
do_test collate1-2.12.4 {
  execsql {
    SELECT c1 COLLATE numeric, c2 COLLATE hex
      FROM collate1t1 
     ORDER BY 1, 2;
  }
} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101}
do_test collate1-2.13 {
  execsql {
    SELECT c1 COLLATE binary, c2 COLLATE hex
      FROM collate1t1
     ORDER BY 1, 2;
  }
} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA}
do_test collate1-2.14 {
  execsql {
    SELECT c1, c2
      FROM collate1t1 ORDER BY 1 COLLATE binary DESC, 2 COLLATE hex;
  }
} {7 0xA 5 0xA 5 0x11 11 0x11 11 0x101 {} {}}
do_test collate1-2.15 {
  execsql {
    SELECT c1 COLLATE binary, c2 COLLATE hex
      FROM collate1t1 
     ORDER BY 1 DESC, 2 DESC;
  }
} {7 0xA 5 0x11 5 0xA 11 0x101 11 0x11 {} {}}
do_test collate1-2.16 {
  execsql {
    SELECT c1 COLLATE hex, c2 COLLATE binary
      FROM collate1t1 
     ORDER BY 1 COLLATE binary ASC, 2 COLLATE hex ASC;
  }
} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA}
do_test collate1-2.99 {
  execsql {
    DROP TABLE collate1t1;
  }
} {}

#
# These tests ensure that the default collation type for a column is used 
# by an ORDER BY clause correctly. The focus is all the different ways
# the column can be referenced. i.e. a, collate2t1.a, main.collate2t1.a etc.
#
do_test collate1-3.0 {
  execsql {
    CREATE TABLE collate1t1(a COLLATE hex, b);
    INSERT INTO collate1t1 VALUES( '0x5', 5 );
    INSERT INTO collate1t1 VALUES( '1', 1 );
    INSERT INTO collate1t1 VALUES( '0x45', 69 );
    INSERT INTO collate1t1 VALUES( NULL, NULL );
    SELECT * FROM collate1t1 ORDER BY a;
  }
} {{} {} 1 1 0x5 5 0x45 69}

do_test collate1-3.1 {
  execsql {
    SELECT * FROM collate1t1 ORDER BY 1;
  }
} {{} {} 1 1 0x5 5 0x45 69}
do_test collate1-3.2 {
  execsql {
    SELECT * FROM collate1t1 ORDER BY collate1t1.a;
  }
} {{} {} 1 1 0x5 5 0x45 69}
do_test collate1-3.3 {
  execsql {
    SELECT * FROM collate1t1 ORDER BY main.collate1t1.a;
  }
} {{} {} 1 1 0x5 5 0x45 69}
do_test collate1-3.4 {
  execsql {
    SELECT a as c1, b as c2 FROM collate1t1 ORDER BY c1;
  }
} {{} {} 1 1 0x5 5 0x45 69}
do_test collate1-3.5 {
  execsql {
    SELECT a as c1, b as c2 FROM collate1t1 ORDER BY c1 COLLATE binary;
  }
} {{} {} 0x45 69 0x5 5 1 1}
do_test collate1-3.5.1 {
  execsql {
    SELECT a COLLATE binary as c1, b as c2
      FROM collate1t1 ORDER BY c1;
  }
} {{} {} 0x45 69 0x5 5 1 1}
do_test collate1-3.6 {
  execsql {
    DROP TABLE collate1t1;
  }
} {}

# Update for SQLite version 3. The collate1-4.* test cases were written
# before manifest types were introduced. The following test cases still
# work, due to the 'affinity' mechanism, but they don't prove anything
# about collation sequences.
#
do_test collate1-4.0 {
  execsql {
    CREATE TABLE collate1t1(c1 numeric, c2 text);
    INSERT INTO collate1t1 VALUES(1, 1);
    INSERT INTO collate1t1 VALUES(12, 12);
    INSERT INTO collate1t1 VALUES(NULL, NULL);
    INSERT INTO collate1t1 VALUES(101, 101);
  }
} {}
do_test collate1-4.1 {
  execsql {
    SELECT c1 FROM collate1t1 ORDER BY 1;
  }
} {{} 1 12 101}
do_test collate1-4.2 {
  execsql {
    SELECT c2 FROM collate1t1 ORDER BY 1;
  }
} {{} 1 101 12}
do_test collate1-4.3 {
  execsql {
    SELECT c2+0 FROM collate1t1 ORDER BY 1;
  }
} {{} 1 12 101}
do_test collate1-4.4 {
  execsql {
    SELECT c1||'' FROM collate1t1 ORDER BY 1;
  }
} {{} 1 101 12}
do_test collate1-4.4.1 {
  execsql {
    SELECT (c1||'') COLLATE numeric FROM collate1t1 ORDER BY 1;
  }
} {{} 1 12 101}
do_test collate1-4.5 {
  execsql {
    DROP TABLE collate1t1;
  }
} {}

finish_test

Added test/collate2.test.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is page cache subsystem.
#
# $Id: collate2.test,v 1.6 2008/08/20 16:35:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#
# Tests are organised as follows:
#
# collate2-1.* WHERE <expr> expressions (sqliteExprIfTrue).
# collate2-2.* WHERE NOT <expr> expressions (sqliteExprIfFalse).
# collate2-3.* SELECT <expr> expressions (sqliteExprCode).
# collate2-4.* Precedence of collation/data types in binary comparisons
# collate2-5.* JOIN syntax.
#

# Create a collation type BACKWARDS for use in testing. This collation type
# is similar to the built-in TEXT collation type except the order of
# characters in each string is reversed before the comparison is performed.
db collate BACKWARDS backwards_collate
proc backwards_collate {a b} {
  set ra {};
  set rb {}
  foreach c [split $a {}] { set ra $c$ra }
  foreach c [split $b {}] { set rb $c$rb }
  return [string compare $ra $rb]
}

# The following values are used in these tests:
# NULL   aa ab ba bb   aA aB bA bB   Aa Ab Ba Bb   AA AB BA BB 
#
# The collation orders for each of the tested collation types are:
#
# BINARY:    NULL  AA AB Aa Ab  BA BB Ba Bb  aA aB aa ab  bA bB ba bb 
# NOCASE:    NULL  aa aA Aa AA  ab aB Ab AB  ba bA Ba BA  bb bB Bb BB 
# BACKWARDS: NULL  AA BA aA bA  AB BB aB bB  Aa Ba aa ba  Ab Bb ab bb 
#
# These tests verify that the default collation type for a column is used
# for comparison operators (<, >, <=, >=, =) involving that column and 
# an expression that is not a column with a default collation type.
# 
# The collation sequences BINARY and NOCASE are built-in, the BACKWARDS
# collation sequence is implemented by the TCL proc backwards_collate
# above.
#
do_test collate2-1.0 {
  execsql {
    CREATE TABLE collate2t1(
      a COLLATE BINARY, 
      b COLLATE NOCASE, 
      c COLLATE BACKWARDS
    );
    INSERT INTO collate2t1 VALUES( NULL, NULL, NULL );

    INSERT INTO collate2t1 VALUES( 'aa', 'aa', 'aa' );
    INSERT INTO collate2t1 VALUES( 'ab', 'ab', 'ab' );
    INSERT INTO collate2t1 VALUES( 'ba', 'ba', 'ba' );
    INSERT INTO collate2t1 VALUES( 'bb', 'bb', 'bb' );

    INSERT INTO collate2t1 VALUES( 'aA', 'aA', 'aA' );
    INSERT INTO collate2t1 VALUES( 'aB', 'aB', 'aB' );
    INSERT INTO collate2t1 VALUES( 'bA', 'bA', 'bA' );
    INSERT INTO collate2t1 VALUES( 'bB', 'bB', 'bB' );

    INSERT INTO collate2t1 VALUES( 'Aa', 'Aa', 'Aa' );
    INSERT INTO collate2t1 VALUES( 'Ab', 'Ab', 'Ab' );
    INSERT INTO collate2t1 VALUES( 'Ba', 'Ba', 'Ba' );
    INSERT INTO collate2t1 VALUES( 'Bb', 'Bb', 'Bb' );

    INSERT INTO collate2t1 VALUES( 'AA', 'AA', 'AA' );
    INSERT INTO collate2t1 VALUES( 'AB', 'AB', 'AB' );
    INSERT INTO collate2t1 VALUES( 'BA', 'BA', 'BA' );
    INSERT INTO collate2t1 VALUES( 'BB', 'BB', 'BB' );
  }
  if {[info exists collate_test_use_index]} { 
    execsql {
      CREATE INDEX collate2t1_i1 ON collate2t1(a);
      CREATE INDEX collate2t1_i2 ON collate2t1(b);
      CREATE INDEX collate2t1_i3 ON collate2t1(c);
    }
  }
} {}
do_test collate2-1.1 {
  execsql {
    SELECT a FROM collate2t1 WHERE a > 'aa' ORDER BY 1;
  }
} {ab bA bB ba bb}
do_test collate2-1.1.1 {
  execsql {
    SELECT a FROM collate2t1 WHERE a COLLATE binary > 'aa' ORDER BY 1;
  }
} {ab bA bB ba bb}
do_test collate2-1.1.2 {
  execsql {
    SELECT a FROM collate2t1 WHERE b COLLATE binary > 'aa' ORDER BY 1;
  }
} {ab bA bB ba bb}
do_test collate2-1.1.3 {
  execsql {
    SELECT a FROM collate2t1 WHERE c COLLATE binary > 'aa' ORDER BY 1;
  }
} {ab bA bB ba bb}
do_test collate2-1.2 {
  execsql {
    SELECT b FROM collate2t1 WHERE b > 'aa' ORDER BY 1, oid;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.1 {
  execsql {
    SELECT b FROM collate2t1 WHERE a COLLATE nocase > 'aa'
     ORDER BY 1, oid;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.2 {
  execsql {
    SELECT b FROM collate2t1 WHERE b COLLATE nocase > 'aa'
     ORDER BY 1, oid;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.3 {
  execsql {
    SELECT b FROM collate2t1 WHERE c COLLATE nocase > 'aa'
     ORDER BY 1, oid;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.4 {
  execsql {
    SELECT b FROM collate2t1 WHERE b > 'aa' ORDER BY +b;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.5 {
  execsql {
    SELECT b FROM collate2t1 WHERE a COLLATE nocase > 'aa' ORDER BY +b;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.6 {
  execsql {
    SELECT b FROM collate2t1 WHERE b COLLATE nocase > 'aa' ORDER BY +b;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.2.7 {
  execsql {
    SELECT b FROM collate2t1 WHERE c COLLATE nocase > 'aa' ORDER BY +b;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.3 {
  execsql {
    SELECT c FROM collate2t1 WHERE c > 'aa' ORDER BY 1;
  }
} {ba Ab Bb ab bb}
do_test collate2-1.3.1 {
  execsql {
    SELECT c FROM collate2t1 WHERE a COLLATE backwards > 'aa'
    ORDER BY 1;
  }
} {ba Ab Bb ab bb}
do_test collate2-1.3.2 {
  execsql {
    SELECT c FROM collate2t1 WHERE b COLLATE backwards > 'aa'
    ORDER BY 1;
  }
} {ba Ab Bb ab bb}
do_test collate2-1.3.3 {
  execsql {
    SELECT c FROM collate2t1 WHERE c COLLATE backwards > 'aa'
    ORDER BY 1;
  }
} {ba Ab Bb ab bb}
do_test collate2-1.4 {
  execsql {
    SELECT a FROM collate2t1 WHERE a < 'aa' ORDER BY 1;
  }
} {AA AB Aa Ab BA BB Ba Bb aA aB}
do_test collate2-1.5 {
  execsql {
    SELECT b FROM collate2t1 WHERE b < 'aa' ORDER BY 1, oid;
  }
} {}
do_test collate2-1.5.1 {
  execsql {
    SELECT b FROM collate2t1 WHERE b < 'aa' ORDER BY +b;
  }
} {}
do_test collate2-1.6 {
  execsql {
    SELECT c FROM collate2t1 WHERE c < 'aa' ORDER BY 1;
  }
} {AA BA aA bA AB BB aB bB Aa Ba}
do_test collate2-1.7 {
  execsql {
    SELECT a FROM collate2t1 WHERE a = 'aa';
  }
} {aa}
do_test collate2-1.8 {
  execsql {
    SELECT b FROM collate2t1 WHERE b = 'aa' ORDER BY oid;
  }
} {aa aA Aa AA}
do_test collate2-1.9 {
  execsql {
    SELECT c FROM collate2t1 WHERE c = 'aa';
  }
} {aa}
do_test collate2-1.10 {
  execsql {
    SELECT a FROM collate2t1 WHERE a >= 'aa' ORDER BY 1;
  }
} {aa ab bA bB ba bb}
do_test collate2-1.11 {
  execsql {
    SELECT b FROM collate2t1 WHERE b >= 'aa' ORDER BY 1, oid;
  }
} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.12 {
  execsql {
    SELECT c FROM collate2t1 WHERE c >= 'aa' ORDER BY 1;
  }
} {aa ba Ab Bb ab bb}
do_test collate2-1.13 {
  execsql {
    SELECT a FROM collate2t1 WHERE a <= 'aa' ORDER BY 1;
  }
} {AA AB Aa Ab BA BB Ba Bb aA aB aa}
do_test collate2-1.14 {
  execsql {
    SELECT b FROM collate2t1 WHERE b <= 'aa' ORDER BY 1, oid;
  }
} {aa aA Aa AA}
do_test collate2-1.15 {
  execsql {
    SELECT c FROM collate2t1 WHERE c <= 'aa' ORDER BY 1;
  }
} {AA BA aA bA AB BB aB bB Aa Ba aa}
do_test collate2-1.16 {
  execsql {
    SELECT a FROM collate2t1 WHERE a BETWEEN 'Aa' AND 'Bb' ORDER BY 1;
  }
} {Aa Ab BA BB Ba Bb}
do_test collate2-1.17 {
  execsql {
    SELECT b FROM collate2t1 WHERE b BETWEEN 'Aa' AND 'Bb' ORDER BY 1, oid;
  }
} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.17.1 {
  execsql {
    SELECT b FROM collate2t1 WHERE b BETWEEN 'Aa' AND 'Bb' ORDER BY +b;
  }
} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-1.18 {
  execsql {
    SELECT c FROM collate2t1 WHERE c BETWEEN 'Aa' AND 'Bb' ORDER BY 1;
  }
} {Aa Ba aa ba Ab Bb}
do_test collate2-1.19 {
  execsql {
    SELECT a FROM collate2t1 WHERE 
      CASE a WHEN 'aa' THEN 1 ELSE 0 END
        ORDER BY 1, oid;
  }
} {aa}
do_test collate2-1.20 {
  execsql {
    SELECT b FROM collate2t1 WHERE 
      CASE b WHEN 'aa' THEN 1 ELSE 0 END
        ORDER BY 1, oid;
  }
} {aa aA Aa AA}
do_test collate2-1.21 {
  execsql {
    SELECT c FROM collate2t1 WHERE 
      CASE c WHEN 'aa' THEN 1 ELSE 0 END
        ORDER BY 1, oid;
  }
} {aa}

ifcapable subquery {
  do_test collate2-1.22 {
    execsql {
      SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb') ORDER BY 1, oid;
    }
  } {aa bb}
  do_test collate2-1.23 {
    execsql {
      SELECT b FROM collate2t1 WHERE b IN ('aa', 'bb') ORDER BY 1, oid;
    }
  } {aa aA Aa AA bb bB Bb BB}
  do_test collate2-1.24 {
    execsql {
      SELECT c FROM collate2t1 WHERE c IN ('aa', 'bb') ORDER BY 1, oid;
    }
  } {aa bb}
  do_test collate2-1.25 {
    execsql {
      SELECT a FROM collate2t1 
        WHERE a IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb'));
    }
  } {aa bb}
  do_test collate2-1.26 {
    execsql {
      SELECT b FROM collate2t1 
        WHERE b IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb'));
    }
  } {aa bb aA bB Aa Bb AA BB}
  do_test collate2-1.27 {
    execsql {
      SELECT c FROM collate2t1 
        WHERE c IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb'));
    }
  } {aa bb}
} ;# ifcapable subquery

do_test collate2-2.1 {
  execsql {
    SELECT a FROM collate2t1 WHERE NOT a > 'aa' ORDER BY 1;
  }
} {AA AB Aa Ab BA BB Ba Bb aA aB aa}
do_test collate2-2.2 {
  execsql {
    SELECT b FROM collate2t1 WHERE NOT b > 'aa' ORDER BY 1, oid;
  }
} {aa aA Aa AA}
do_test collate2-2.3 {
  execsql {
    SELECT c FROM collate2t1 WHERE NOT c > 'aa' ORDER BY 1;
  }
} {AA BA aA bA AB BB aB bB Aa Ba aa}
do_test collate2-2.4 {
  execsql {
    SELECT a FROM collate2t1 WHERE NOT a < 'aa' ORDER BY 1;
  }
} {aa ab bA bB ba bb}
do_test collate2-2.5 {
  execsql {
    SELECT b FROM collate2t1 WHERE NOT b < 'aa' ORDER BY 1, oid;
  }
} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-2.6 {
  execsql {
    SELECT c FROM collate2t1 WHERE NOT c < 'aa' ORDER BY 1;
  }
} {aa ba Ab Bb ab bb}
do_test collate2-2.7 {
  execsql {
    SELECT a FROM collate2t1 WHERE NOT a = 'aa';
  }
} {ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
do_test collate2-2.8 {
  execsql {
    SELECT b FROM collate2t1 WHERE NOT b = 'aa';
  }
} {ab ba bb aB bA bB Ab Ba Bb AB BA BB}
do_test collate2-2.9 {
  execsql {
    SELECT c FROM collate2t1 WHERE NOT c = 'aa';
  }
} {ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
do_test collate2-2.10 {
  execsql {
    SELECT a FROM collate2t1 WHERE NOT a >= 'aa' ORDER BY 1;
  }
} {AA AB Aa Ab BA BB Ba Bb aA aB}
do_test collate2-2.11 {
  execsql {
    SELECT b FROM collate2t1 WHERE NOT b >= 'aa' ORDER BY 1, oid;
  }
} {}
do_test collate2-2.12 {
  execsql {
    SELECT c FROM collate2t1 WHERE NOT c >= 'aa' ORDER BY 1;
  }
} {AA BA aA bA AB BB aB bB Aa Ba}
do_test collate2-2.13 {
  execsql {
    SELECT a FROM collate2t1 WHERE NOT a <= 'aa' ORDER BY 1;
  }
} {ab bA bB ba bb}
do_test collate2-2.14 {
  execsql {
    SELECT b FROM collate2t1 WHERE NOT b <= 'aa' ORDER BY 1, oid;
  }
} {ab aB Ab AB ba bA Ba BA bb bB Bb BB}
do_test collate2-2.15 {
  execsql {
    SELECT c FROM collate2t1 WHERE NOT c <= 'aa' ORDER BY 1;
  }
} {ba Ab Bb ab bb}
do_test collate2-2.16 {
  execsql {
    SELECT a FROM collate2t1 WHERE a NOT BETWEEN 'Aa' AND 'Bb' ORDER BY 1;
  }
} {AA AB aA aB aa ab bA bB ba bb}
do_test collate2-2.17 {
  execsql {
    SELECT b FROM collate2t1 WHERE b NOT BETWEEN 'Aa' AND 'Bb' ORDER BY 1, oid;
  }
} {}
do_test collate2-2.18 {
  execsql {
    SELECT c FROM collate2t1 WHERE c NOT BETWEEN 'Aa' AND 'Bb' ORDER BY 1;
  }
} {AA BA aA bA AB BB aB bB ab bb}
do_test collate2-2.19 {
  execsql {
    SELECT a FROM collate2t1 WHERE NOT CASE a WHEN 'aa' THEN 1 ELSE 0 END;
  }
} {{} ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
do_test collate2-2.20 {
  execsql {
    SELECT b FROM collate2t1 WHERE NOT CASE b WHEN 'aa' THEN 1 ELSE 0 END;
  }
} {{} ab ba bb aB bA bB Ab Ba Bb AB BA BB}
do_test collate2-2.21 {
  execsql {
    SELECT c FROM collate2t1 WHERE NOT CASE c WHEN 'aa' THEN 1 ELSE 0 END;
  }
} {{} ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB}

ifcapable subquery {
  do_test collate2-2.22 {
    execsql {
      SELECT a FROM collate2t1 WHERE NOT a IN ('aa', 'bb');
    }
  } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
  do_test collate2-2.23 {
    execsql {
      SELECT b FROM collate2t1 WHERE NOT b IN ('aa', 'bb');
    }
  } {ab ba aB bA Ab Ba AB BA}
  do_test collate2-2.24 {
    execsql {
      SELECT c FROM collate2t1 WHERE NOT c IN ('aa', 'bb');
    }
  } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
  do_test collate2-2.25 {
    execsql {
      SELECT a FROM collate2t1 
        WHERE NOT a IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb'));
    }
  } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
  do_test collate2-2.26 {
    execsql {
      SELECT b FROM collate2t1 
        WHERE NOT b IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb'));
    }
  } {ab ba aB bA Ab Ba AB BA}
  do_test collate2-2.27 {
    execsql {
      SELECT c FROM collate2t1 
        WHERE NOT c IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb'));
    }
  } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB}
}

do_test collate2-3.1 {
  execsql {
    SELECT a > 'aa' FROM collate2t1;
  }
} {{} 0 1 1 1 0 0 1 1 0 0 0 0 0 0 0 0}
do_test collate2-3.2 {
  execsql {
    SELECT b > 'aa' FROM collate2t1;
  }
} {{} 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1}
do_test collate2-3.3 {
  execsql {
    SELECT c > 'aa' FROM collate2t1;
  }
} {{} 0 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0}
do_test collate2-3.4 {
  execsql {
    SELECT a < 'aa' FROM collate2t1;
  }
} {{} 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1}
do_test collate2-3.5 {
  execsql {
    SELECT b < 'aa' FROM collate2t1;
  }
} {{} 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0}
do_test collate2-3.6 {
  execsql {
    SELECT c < 'aa' FROM collate2t1;
  }
} {{} 0 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1}
do_test collate2-3.7 {
  execsql {
    SELECT a = 'aa' FROM collate2t1;
  }
} {{} 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0}
do_test collate2-3.8 {
  execsql {
    SELECT b = 'aa' FROM collate2t1;
  }
} {{} 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0}
do_test collate2-3.9 {
  execsql {
    SELECT c = 'aa' FROM collate2t1;
  }
} {{} 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0}
do_test collate2-3.10 {
  execsql {
    SELECT a <= 'aa' FROM collate2t1;
  }
} {{} 1 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1}
do_test collate2-3.11 {
  execsql {
    SELECT b <= 'aa' FROM collate2t1;
  }
} {{} 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0}
do_test collate2-3.12 {
  execsql {
    SELECT c <= 'aa' FROM collate2t1;
  }
} {{} 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1}
do_test collate2-3.13 {
  execsql {
    SELECT a >= 'aa' FROM collate2t1;
  }
} {{} 1 1 1 1 0 0 1 1 0 0 0 0 0 0 0 0}
do_test collate2-3.14 {
  execsql {
    SELECT b >= 'aa' FROM collate2t1;
  }
} {{} 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1}
do_test collate2-3.15 {
  execsql {
    SELECT c >= 'aa' FROM collate2t1;
  }
} {{} 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0}
do_test collate2-3.16 {
  execsql {
    SELECT a BETWEEN 'Aa' AND 'Bb' FROM collate2t1;
  }
} {{} 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 1}
do_test collate2-3.17 {
  execsql {
    SELECT b BETWEEN 'Aa' AND 'Bb' FROM collate2t1;
  }
} {{} 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1}
do_test collate2-3.18 {
  execsql {
    SELECT c BETWEEN 'Aa' AND 'Bb' FROM collate2t1;
  }
} {{} 1 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0}
do_test collate2-3.19 {
  execsql {
    SELECT CASE a WHEN 'aa' THEN 1 ELSE 0 END FROM collate2t1;
  }
} {0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0}
do_test collate2-3.20 {
  execsql {
    SELECT CASE b WHEN 'aa' THEN 1 ELSE 0 END FROM collate2t1;
  }
} {0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0}
do_test collate2-3.21 {
  execsql {
    SELECT CASE c WHEN 'aa' THEN 1 ELSE 0 END FROM collate2t1;
  }
} {0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0}

ifcapable subquery {
  do_test collate2-3.22 {
    execsql {
      SELECT a IN ('aa', 'bb') FROM collate2t1;
    }
  } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0}
  do_test collate2-3.23 {
    execsql {
      SELECT b IN ('aa', 'bb') FROM collate2t1;
    }
  } {{} 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1}
  do_test collate2-3.24 {
    execsql {
      SELECT c IN ('aa', 'bb') FROM collate2t1;
    }
  } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0}
  do_test collate2-3.25 {
    execsql {
      SELECT a IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')) 
        FROM collate2t1;
    }
  } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0}
  do_test collate2-3.26 {
    execsql {
      SELECT b IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')) 
        FROM collate2t1;
    }
  } {{} 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1}
  do_test collate2-3.27 {
    execsql {
      SELECT c IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')) 
        FROM collate2t1;
    }
  } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0}
}

do_test collate2-4.0 {
  execsql {
    CREATE TABLE collate2t2(b COLLATE binary);
    CREATE TABLE collate2t3(b text);
    INSERT INTO collate2t2 VALUES('aa');
    INSERT INTO collate2t3 VALUES('aa');
  }
} {}

# Test that when both sides of a binary comparison operator have
# default collation types, the collate type for the leftmost term
# is used.
do_test collate2-4.1 {
  execsql {
    SELECT collate2t1.a FROM collate2t1, collate2t2 
      WHERE collate2t1.b = collate2t2.b;
  }
} {aa aA Aa AA}
do_test collate2-4.2 {
  execsql {
    SELECT collate2t1.a FROM collate2t1, collate2t2 
      WHERE collate2t2.b = collate2t1.b;
  }
} {aa}

# Test that when one side has a default collation type and the other
# does not, the collation type is used.
do_test collate2-4.3 {
  execsql {
    SELECT collate2t1.a FROM collate2t1, collate2t3 
      WHERE collate2t1.b = collate2t3.b||'';
  }
} {aa aA Aa AA}
do_test collate2-4.4 {
  execsql {
    SELECT collate2t1.a FROM collate2t1, collate2t3 
      WHERE collate2t3.b||'' = collate2t1.b;
  }
} {aa aA Aa AA}

do_test collate2-4.5 {
  execsql {
    DROP TABLE collate2t3;
  }
} {}

#
# Test that the default collation types are used when the JOIN syntax
# is used in place of a WHERE clause.
#
# SQLite transforms the JOIN syntax into a WHERE clause internally, so
# the focus of these tests is to ensure that the table on the left-hand-side
# of the join determines the collation type used. 
#
do_test collate2-5.0 {
  execsql {
    SELECT collate2t1.b FROM collate2t1 JOIN collate2t2 USING (b);
  }
} {aa aA Aa AA}
do_test collate2-5.1 {
  execsql {
    SELECT collate2t1.b FROM collate2t2 JOIN collate2t1 USING (b);
  }
} {aa}
do_test collate2-5.2 {
  execsql {
    SELECT collate2t1.b FROM collate2t1 NATURAL JOIN collate2t2;
  }
} {aa aA Aa AA}
do_test collate2-5.3 {
  execsql {
    SELECT collate2t1.b FROM collate2t2 NATURAL JOIN collate2t1;
  }
} {aa}
do_test collate2-5.4 {
  execsql {
    SELECT collate2t2.b FROM collate2t1 LEFT OUTER JOIN collate2t2 USING (b) order by collate2t1.oid;
  }
} {{} aa {} {} {} aa {} {} {} aa {} {} {} aa {} {} {}}
do_test collate2-5.5 {
  execsql {
    SELECT collate2t1.b, collate2t2.b FROM collate2t2 LEFT OUTER JOIN collate2t1 USING (b);
  }
} {aa aa}

finish_test

Added test/collate3.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is page cache subsystem.
#
# $Id: collate3.test,v 1.13 2008/08/20 16:35:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#
# Tests are organised as follows:
#
# collate3.1.* - Errors related to unknown collation sequences.
# collate3.2.* - Errors related to undefined collation sequences.
# collate3.3.* - Writing to a table that has an index with an undefined c.s.
# collate3.4.* - Misc errors.
# collate3.5.* - Collation factory.
#

#
# These tests ensure that when a user executes a statement with an 
# unknown collation sequence an error is returned.
#
do_test collate3-1.0 {
  execsql {
    CREATE TABLE collate3t1(c1);
  }
} {}
do_test collate3-1.1 {
  catchsql {
    SELECT * FROM collate3t1 ORDER BY 1 collate garbage;
  }
} {1 {no such collation sequence: garbage}}
do_test collate3-1.2 {
  catchsql {
    CREATE TABLE collate3t2(c1 collate garbage);
  }
} {1 {no such collation sequence: garbage}}
do_test collate3-1.3 {
  catchsql {
    CREATE INDEX collate3i1 ON collate3t1(c1 COLLATE garbage);
  }
} {1 {no such collation sequence: garbage}}

execsql {
  DROP TABLE collate3t1;
}

#
# Create a table with a default collation sequence, then close
# and re-open the database without re-registering the collation
# sequence. Then make sure the library stops us from using
# the collation sequence in:
# * an explicitly collated ORDER BY
# * an ORDER BY that uses the default collation sequence
# * an expression (=)
# * a CREATE TABLE statement
# * a CREATE INDEX statement that uses a default collation sequence
# * a GROUP BY that uses the default collation sequence
# * a SELECT DISTINCT that uses the default collation sequence
# * Compound SELECTs that uses the default collation sequence
# * An ORDER BY on a compound SELECT with an explicit ORDER BY.
#
do_test collate3-2.0 {
  db collate string_compare {string compare}
  execsql {
    CREATE TABLE collate3t1(c1 COLLATE string_compare, c2);
  }
  db close
  sqlite3 db test.db
  expr 0
} 0
do_test collate3-2.1 {
  catchsql {
    SELECT * FROM collate3t1 ORDER BY 1 COLLATE string_compare;
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-2.2 {
  catchsql {
    SELECT * FROM collate3t1 ORDER BY c1;
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-2.3 {
  catchsql {
    SELECT * FROM collate3t1 WHERE c1 = 'xxx';
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-2.4 {
  catchsql {
    CREATE TABLE collate3t2(c1 COLLATE string_compare);
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-2.5 {
  catchsql {
    CREATE INDEX collate3t1_i1 ON collate3t1(c1);
  }
} {1 {no such collation sequence: string_compare}}
do_test collate3-2.6 {
  catchsql {
    SELECT * FROM collate3t1;
  }
} {0 {}}
do_test collate3-2.7.1 {
  catchsql {
    SELECT count(*) FROM collate3t1 GROUP BY c1;
  }
} {1 {no such collation sequence: string_compare}} 
# do_test collate3-2.7.2 {
#   catchsql {
#     SELECT * FROM collate3t1 GROUP BY c1;
#   }
# } {1 {GROUP BY may only be used on aggregate queries}}
do_test collate3-2.7.2 {
  catchsql {
    SELECT * FROM collate3t1 GROUP BY c1;
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-2.8 {
  catchsql {
    SELECT DISTINCT c1 FROM collate3t1;
  }
} {1 {no such collation sequence: string_compare}} 

ifcapable compound {
  do_test collate3-2.9 {
    catchsql {
      SELECT c1 FROM collate3t1 UNION SELECT c1 FROM collate3t1;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.10 {
    catchsql {
      SELECT c1 FROM collate3t1 EXCEPT SELECT c1 FROM collate3t1;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.11 {
    catchsql {
      SELECT c1 FROM collate3t1 INTERSECT SELECT c1 FROM collate3t1;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.12 {
    catchsql {
      SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1;
    }
  } {0 {}}
  do_test collate3-2.13 {
    catchsql {
      SELECT 10 UNION ALL SELECT 20 ORDER BY 1 COLLATE string_compare;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.14 {
    catchsql {
      SELECT 10 INTERSECT SELECT 20 ORDER BY 1 COLLATE string_compare;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.15 {
    catchsql {
      SELECT 10 EXCEPT SELECT 20 ORDER BY 1 COLLATE string_compare;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.16 {
    catchsql {
      SELECT 10 UNION SELECT 20 ORDER BY 1 COLLATE string_compare;
    }
  } {1 {no such collation sequence: string_compare}} 
  do_test collate3-2.17 {
    catchsql {
      SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1 ORDER BY 1;
    }
  } {1 {no such collation sequence: string_compare}} 
} ;# ifcapable compound

#
# Create an index that uses a collation sequence then close and
# re-open the database without re-registering the collation
# sequence. Then check that for the table with the index 
# * An INSERT fails,
# * An UPDATE on the column with the index fails,
# * An UPDATE on a different column succeeds.
# * A DELETE with a WHERE clause fails
# * A DELETE without a WHERE clause succeeds
#
# Also, ensure that the restrictions tested by collate3-2.* still
# apply after the index has been created.
#
do_test collate3-3.0 {
  db collate string_compare {string compare}
  execsql {
    CREATE INDEX collate3t1_i1 ON collate3t1(c1);
    INSERT INTO collate3t1 VALUES('xxx', 'yyy');
  }
  db close
  sqlite3 db test.db
  expr 0
} 0
db eval {select * from collate3t1}
do_test collate3-3.1 {
  catchsql {
    INSERT INTO collate3t1 VALUES('xxx', 0);
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.2 {
  catchsql {
    UPDATE collate3t1 SET c1 = 'xxx';
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.3 {
  catchsql {
    UPDATE collate3t1 SET c2 = 'xxx';
  }
} {0 {}}
do_test collate3-3.4 {
  catchsql {
    DELETE FROM collate3t1 WHERE 1;
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.5 {
  catchsql {
    SELECT * FROM collate3t1;
  }
} {0 {xxx xxx}}
do_test collate3-3.6 {
  catchsql {
    DELETE FROM collate3t1;
  }
} {0 {}}
ifcapable {integrityck} {
  do_test collate3-3.8 {
    catchsql {
      PRAGMA integrity_check
    }
  } {1 {no such collation sequence: string_compare}}
}
do_test collate3-3.9 {
  catchsql {
    SELECT * FROM collate3t1;
  }
} {0 {}}
do_test collate3-3.10 {
  catchsql {
    SELECT * FROM collate3t1 ORDER BY 1 COLLATE string_compare;
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.11 {
  catchsql {
    SELECT * FROM collate3t1 ORDER BY c1;
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.12 {
  catchsql {
    SELECT * FROM collate3t1 WHERE c1 = 'xxx';
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.13 {
  catchsql {
    CREATE TABLE collate3t2(c1 COLLATE string_compare);
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.14 {
  catchsql {
    CREATE INDEX collate3t1_i2 ON collate3t1(c1);
  }
} {1 {no such collation sequence: string_compare}} 
do_test collate3-3.15 {
  execsql {
    DROP TABLE collate3t1;
  }
} {}

# Check we can create an index that uses an explicit collation 
# sequence and then close and re-open the database.
do_test collate3-4.6 {
  db collate user_defined "string compare"
  execsql {
    CREATE TABLE collate3t1(a, b);
    INSERT INTO collate3t1 VALUES('hello', NULL);
    CREATE INDEX collate3i1 ON collate3t1(a COLLATE user_defined);
  }
} {}
do_test collate3-4.7 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM collate3t1 ORDER BY a COLLATE user_defined;
  }
} {1 {no such collation sequence: user_defined}}
do_test collate3-4.8.1 {
  db collate user_defined "string compare"
  catchsql {
    SELECT * FROM collate3t1 ORDER BY a COLLATE user_defined;
  }
} {0 {hello {}}}
do_test collate3-4.8.2 {
  db close
  lindex [catch {
    sqlite3 db test.db
  }] 0
} {0}
do_test collate3-4.8.3 {
  execsql {
    DROP TABLE collate3t1;
  }
} {}

# Compare strings as numbers.
proc numeric_compare {lhs rhs} {
  if {$rhs > $lhs} {
    set res -1
  } else {
    set res [expr ($lhs > $rhs)?1:0]
  }
  return $res
}

# Check we can create a view that uses an explicit collation 
# sequence and then close and re-open the database.
ifcapable view {
do_test collate3-4.9 {
  db collate user_defined numeric_compare
  execsql {
    CREATE TABLE collate3t1(a, b);
    INSERT INTO collate3t1 VALUES('2', NULL);
    INSERT INTO collate3t1 VALUES('101', NULL);
    INSERT INTO collate3t1 VALUES('12', NULL);
    CREATE VIEW collate3v1 AS SELECT * FROM collate3t1 
        ORDER BY 1 COLLATE user_defined;
    SELECT * FROM collate3v1;
  }
} {2 {} 12 {} 101 {}}
do_test collate3-4.10 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM collate3v1;
  }
} {1 {no such collation sequence: user_defined}}
do_test collate3-4.11 {
  db collate user_defined numeric_compare
  catchsql {
    SELECT * FROM collate3v1;
  }
} {0 {2 {} 12 {} 101 {}}}
do_test collate3-4.12 {
  execsql {
    DROP TABLE collate3t1;
  }
} {}
} ;# ifcapable view

#
# Test the collation factory. In the code, the "no such collation sequence"
# message is only generated in two places. So these tests just test that
# the collation factory can be called once from each of those points.
#
do_test collate3-5.0 {
  catchsql {
    CREATE TABLE collate3t1(a);
    INSERT INTO collate3t1 VALUES(10);
    SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk;
  }
} {1 {no such collation sequence: unk}}
do_test collate3-5.1 {
  set ::cfact_cnt 0
  proc cfact {nm} {
    db collate $nm {string compare}
    incr ::cfact_cnt
  }
  db collation_needed cfact
} {}
do_test collate3-5.2 {
  catchsql {
    SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk;
  }
} {0 10}
do_test collate3-5.3 {
  set ::cfact_cnt
} {1}
do_test collate3-5.4 {
  catchsql {
    SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk;
  }
} {0 10}
do_test collate3-5.5 {
  set ::cfact_cnt
} {1}
do_test collate3-5.6 {
  catchsql {
    SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk;
  }
} {0 10}
do_test collate3-5.7 {
  execsql {
    DROP TABLE collate3t1;
    CREATE TABLE collate3t1(a COLLATE unk);
  }
  db close
  sqlite3 db test.db
  catchsql {
    SELECT a FROM collate3t1 ORDER BY 1;
  }
} {1 {no such collation sequence: unk}}
do_test collate3-5.8 {
  set ::cfact_cnt 0
  proc cfact {nm} {
    db collate $nm {string compare}
    incr ::cfact_cnt
  }
  db collation_needed cfact
  catchsql {
    SELECT a FROM collate3t1 ORDER BY 1;
  }
} {0 {}}

do_test collate3-5.9 {
  execsql {
    DROP TABLE collate3t1;
  }
} {}

finish_test

Added test/collate4.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is page cache subsystem.
#
# $Id: collate4.test,v 1.9 2008/01/05 17:39:30 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db collate TEXT text_collate
proc text_collate {a b} {
  return [string compare $a $b]
}

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  return [concat [execsql $sql] $::sqlite_search_count]
}

# This procedure executes the SQL.  Then it checks the generated program
# for the SQL and appends a "nosort" to the result if the program contains the
# SortCallback opcode.  If the program does not contain the SortCallback
# opcode it appends "sort"
#
proc cksort {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

# 
# Test cases are organized roughly as follows:
#
# collate4-1.*      ORDER BY.
# collate4-2.*      WHERE clauses.
# collate4-3.*      constraints (primary key, unique).
# collate4-4.*      simple min() or max() queries.
# collate4-5.*      REINDEX command
# collate4-6.*      INTEGER PRIMARY KEY indices.
#

#
# These tests - collate4-1.* - check that indices are correctly
# selected or not selected to implement ORDER BY clauses when 
# user defined collation sequences are involved. 
#
# Because these tests also exercise all the different ways indices 
# can be created, they also serve to verify that indices are correctly 
# initialised with user-defined collation sequences when they are
# created.
#
# Tests named collate4-1.1.* use indices with a single column. Tests
# collate4-1.2.* use indices with two columns.
#
do_test collate4-1.1.0 {
  execsql {
    CREATE TABLE collate4t1(a COLLATE NOCASE, b COLLATE TEXT);
    INSERT INTO collate4t1 VALUES( 'a', 'a' );
    INSERT INTO collate4t1 VALUES( 'b', 'b' );
    INSERT INTO collate4t1 VALUES( NULL, NULL );
    INSERT INTO collate4t1 VALUES( 'B', 'B' );
    INSERT INTO collate4t1 VALUES( 'A', 'A' );
    CREATE INDEX collate4i1 ON collate4t1(a);
    CREATE INDEX collate4i2 ON collate4t1(b);
  }
} {}
do_test collate4-1.1.1 {
  cksort {SELECT a FROM collate4t1 ORDER BY a}
} {{} a A b B nosort}
do_test collate4-1.1.2 {
  cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE NOCASE}
} {{} a A b B nosort}
do_test collate4-1.1.3 {
  cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE TEXT}
} {{} A B a b sort}
do_test collate4-1.1.4 {
  cksort {SELECT b FROM collate4t1 ORDER BY b}
} {{} A B a b nosort}
do_test collate4-1.1.5 {
  cksort {SELECT b FROM collate4t1 ORDER BY b COLLATE TEXT}
} {{} A B a b nosort}
do_test collate4-1.1.6 {
  cksort {SELECT b FROM collate4t1 ORDER BY b COLLATE NOCASE}
} {{} a A b B sort}

do_test collate4-1.1.7 {
  execsql {
    CREATE TABLE collate4t2(
      a PRIMARY KEY COLLATE NOCASE, 
      b UNIQUE COLLATE TEXT
    );
    INSERT INTO collate4t2 VALUES( 'a', 'a' );
    INSERT INTO collate4t2 VALUES( NULL, NULL );
    INSERT INTO collate4t2 VALUES( 'B', 'B' );
  }
} {}
do_test collate4-1.1.8 {
  cksort {SELECT a FROM collate4t2 ORDER BY a}
} {{} a B nosort}
do_test collate4-1.1.9 {
  cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE NOCASE}
} {{} a B nosort}
do_test collate4-1.1.10 {
  cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE TEXT}
} {{} B a sort}
do_test collate4-1.1.11 {
  cksort {SELECT b FROM collate4t2 ORDER BY b}
} {{} B a nosort}
do_test collate4-1.1.12 {
  cksort {SELECT b FROM collate4t2 ORDER BY b COLLATE TEXT}
} {{} B a nosort}
do_test collate4-1.1.13 {
  cksort {SELECT b FROM collate4t2 ORDER BY b COLLATE NOCASE}
} {{} a B sort}

do_test collate4-1.1.14 {
  execsql {
    CREATE TABLE collate4t3(
      b COLLATE TEXT,  
      a COLLATE NOCASE, 
      UNIQUE(a), PRIMARY KEY(b)
    );
    INSERT INTO collate4t3 VALUES( 'a', 'a' );
    INSERT INTO collate4t3 VALUES( NULL, NULL );
    INSERT INTO collate4t3 VALUES( 'B', 'B' );
  }
} {}
do_test collate4-1.1.15 {
  cksort {SELECT a FROM collate4t3 ORDER BY a}
} {{} a B nosort}
do_test collate4-1.1.16 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE NOCASE}
} {{} a B nosort}
do_test collate4-1.1.17 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE TEXT}
} {{} B a sort}
do_test collate4-1.1.18 {
  cksort {SELECT b FROM collate4t3 ORDER BY b}
} {{} B a nosort}
do_test collate4-1.1.19 {
  cksort {SELECT b FROM collate4t3 ORDER BY b COLLATE TEXT}
} {{} B a nosort}
do_test collate4-1.1.20 {
  cksort {SELECT b FROM collate4t3 ORDER BY b COLLATE NOCASE}
} {{} a B sort}

do_test collate4-1.1.21 {
  execsql {
    CREATE TABLE collate4t4(a COLLATE NOCASE, b COLLATE TEXT);
    INSERT INTO collate4t4 VALUES( 'a', 'a' );
    INSERT INTO collate4t4 VALUES( 'b', 'b' );
    INSERT INTO collate4t4 VALUES( NULL, NULL );
    INSERT INTO collate4t4 VALUES( 'B', 'B' );
    INSERT INTO collate4t4 VALUES( 'A', 'A' );
    CREATE INDEX collate4i3 ON collate4t4(a COLLATE TEXT);
    CREATE INDEX collate4i4 ON collate4t4(b COLLATE NOCASE);
  }
} {}
do_test collate4-1.1.22 {
  cksort {SELECT a FROM collate4t4 ORDER BY a}
} {{} a A b B sort}
do_test collate4-1.1.23 {
  cksort {SELECT a FROM collate4t4 ORDER BY a COLLATE NOCASE}
} {{} a A b B sort}
do_test collate4-1.1.24 {
  cksort {SELECT a FROM collate4t4 ORDER BY a COLLATE TEXT}
} {{} A B a b nosort}
do_test collate4-1.1.25 {
  cksort {SELECT b FROM collate4t4 ORDER BY b}
} {{} A B a b sort}
do_test collate4-1.1.26 {
  cksort {SELECT b FROM collate4t4 ORDER BY b COLLATE TEXT}
} {{} A B a b sort}
do_test collate4-1.1.27 {
  cksort {SELECT b FROM collate4t4 ORDER BY b COLLATE NOCASE}
} {{} a A b B nosort}

do_test collate4-1.1.30 {
  execsql {
    DROP TABLE collate4t1;
    DROP TABLE collate4t2;
    DROP TABLE collate4t3;
    DROP TABLE collate4t4;
  }
} {}

do_test collate4-1.2.0 {
  execsql {
    CREATE TABLE collate4t1(a COLLATE NOCASE, b COLLATE TEXT);
    INSERT INTO collate4t1 VALUES( 'a', 'a' );
    INSERT INTO collate4t1 VALUES( 'b', 'b' );
    INSERT INTO collate4t1 VALUES( NULL, NULL );
    INSERT INTO collate4t1 VALUES( 'B', 'B' );
    INSERT INTO collate4t1 VALUES( 'A', 'A' );
    CREATE INDEX collate4i1 ON collate4t1(a, b);
  }
} {}
do_test collate4-1.2.1 {
  cksort {SELECT a FROM collate4t1 ORDER BY a}
} {{} A a B b nosort}
do_test collate4-1.2.2 {
  cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE nocase}
} {{} A a B b nosort}
do_test collate4-1.2.3 {
  cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE text}
} {{} A B a b sort}
do_test collate4-1.2.4 {
  cksort {SELECT a FROM collate4t1 ORDER BY a, b}
} {{} A a B b nosort}
do_test collate4-1.2.5 {
  cksort {SELECT a FROM collate4t1 ORDER BY a, b COLLATE nocase}
} {{} a A b B sort}
do_test collate4-1.2.6 {
  cksort {SELECT a FROM collate4t1 ORDER BY a, b COLLATE text}
} {{} A a B b nosort}

do_test collate4-1.2.7 {
  execsql {
    CREATE TABLE collate4t2(
      a COLLATE NOCASE, 
      b COLLATE TEXT, 
      PRIMARY KEY(a, b)
    );
    INSERT INTO collate4t2 VALUES( 'a', 'a' );
    INSERT INTO collate4t2 VALUES( NULL, NULL );
    INSERT INTO collate4t2 VALUES( 'B', 'B' );
  }
} {}
do_test collate4-1.2.8 {
  cksort {SELECT a FROM collate4t2 ORDER BY a}
} {{} a B nosort}
do_test collate4-1.2.9 {
  cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE nocase}
} {{} a B nosort}
do_test collate4-1.2.10 {
  cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE text}
} {{} B a sort}
do_test collate4-1.2.11 {
  cksort {SELECT a FROM collate4t2 ORDER BY a, b}
} {{} a B nosort}
do_test collate4-1.2.12 {
  cksort {SELECT a FROM collate4t2 ORDER BY a, b COLLATE nocase}
} {{} a B sort}
do_test collate4-1.2.13 {
  cksort {SELECT a FROM collate4t2 ORDER BY a, b COLLATE text}
} {{} a B nosort}

do_test collate4-1.2.14 {
  execsql {
    CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT);
    INSERT INTO collate4t3 VALUES( 'a', 'a' );
    INSERT INTO collate4t3 VALUES( 'b', 'b' );
    INSERT INTO collate4t3 VALUES( NULL, NULL );
    INSERT INTO collate4t3 VALUES( 'B', 'B' );
    INSERT INTO collate4t3 VALUES( 'A', 'A' );
    CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE);
  }
} {}
do_test collate4-1.2.15 {
  cksort {SELECT a FROM collate4t3 ORDER BY a}
} {{} a A b B sort}
do_test collate4-1.2.16 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE nocase}
} {{} a A b B sort}
do_test collate4-1.2.17 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text}
} {{} A B a b nosort}
do_test collate4-1.2.18 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text, b}
} {{} A B a b sort}
do_test collate4-1.2.19 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text, b COLLATE nocase}
} {{} A B a b nosort}
do_test collate4-1.2.20 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text, b COLLATE text}
} {{} A B a b sort}
do_test collate4-1.2.21 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text DESC}
} {b a B A {} nosort}
do_test collate4-1.2.22 {
  cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text DESC, b}
} {b a B A {} sort}
do_test collate4-1.2.23 {
  cksort {SELECT a FROM collate4t3 
            ORDER BY a COLLATE text DESC, b COLLATE nocase}
} {b a B A {} sort}
do_test collate4-1.2.24 {
  cksort {SELECT a FROM collate4t3 
            ORDER BY a COLLATE text DESC, b COLLATE nocase DESC}
} {b a B A {} nosort}

do_test collate4-1.2.25 {
  execsql {
    DROP TABLE collate4t1;
    DROP TABLE collate4t2;
    DROP TABLE collate4t3;
  }
} {}

#
# These tests - collate4-2.* - check that indices are correctly
# selected or not selected to implement WHERE clauses when user 
# defined collation sequences are involved. 
#
# Indices may optimise WHERE clauses using <, >, <=, >=, = or IN
# operators.
#
do_test collate4-2.1.0 {
  execsql {
    CREATE TABLE collate4t1(a COLLATE NOCASE);
    CREATE TABLE collate4t2(b COLLATE TEXT);

    INSERT INTO collate4t1 VALUES('a');
    INSERT INTO collate4t1 VALUES('A');
    INSERT INTO collate4t1 VALUES('b');
    INSERT INTO collate4t1 VALUES('B');
    INSERT INTO collate4t1 VALUES('c');
    INSERT INTO collate4t1 VALUES('C');
    INSERT INTO collate4t1 VALUES('d');
    INSERT INTO collate4t1 VALUES('D');
    INSERT INTO collate4t1 VALUES('e');
    INSERT INTO collate4t1 VALUES('D');

    INSERT INTO collate4t2 VALUES('A');
    INSERT INTO collate4t2 VALUES('Z');
  }
} {}
do_test collate4-2.1.1 {
  count {
    SELECT * FROM collate4t2, collate4t1 WHERE a = b;
  }
} {A a A A 19}
do_test collate4-2.1.2 {
  execsql {
    CREATE INDEX collate4i1 ON collate4t1(a);
  }
  count {
    SELECT * FROM collate4t2, collate4t1 WHERE a = b;
  }
} {A a A A 5}
do_test collate4-2.1.3 {
  count {
    SELECT * FROM collate4t2, collate4t1 WHERE b = a;
  }
} {A A 19}
do_test collate4-2.1.4 {
  execsql {
    DROP INDEX collate4i1;
    CREATE INDEX collate4i1 ON collate4t1(a COLLATE TEXT);
  }
  count {
    SELECT * FROM collate4t2, collate4t1 WHERE a = b;
  }
} {A a A A 19}
do_test collate4-2.1.5 {
  count {
    SELECT * FROM collate4t2, collate4t1 WHERE b = a;
  }
} {A A 4}
ifcapable subquery {
  do_test collate4-2.1.6 {
    count {
      SELECT a FROM collate4t1 WHERE a IN (SELECT * FROM collate4t2);
    }
  } {a A 10}
  do_test collate4-2.1.7 {
    execsql {
      DROP INDEX collate4i1;
      CREATE INDEX collate4i1 ON collate4t1(a);
    }
    count {
      SELECT a FROM collate4t1 WHERE a IN (SELECT * FROM collate4t2);
    }
  } {a A 6}
  do_test collate4-2.1.8 {
    count {
      SELECT a FROM collate4t1 WHERE a IN ('z', 'a');
    }
  } {a A 5}
  do_test collate4-2.1.9 {
    execsql {
      DROP INDEX collate4i1;
      CREATE INDEX collate4i1 ON collate4t1(a COLLATE TEXT);
    }
    count {
      SELECT a FROM collate4t1 WHERE a IN ('z', 'a');
    }
  } {a A 9}
}
do_test collate4-2.1.10 {
  execsql {
    DROP TABLE collate4t1;
    DROP TABLE collate4t2;
  }
} {}

do_test collate4-2.2.0 {
  execsql {
    CREATE TABLE collate4t1(a COLLATE nocase, b COLLATE text, c);
    CREATE TABLE collate4t2(a COLLATE nocase, b COLLATE text, c COLLATE TEXT);

    INSERT INTO collate4t1 VALUES('0', '0', '0');
    INSERT INTO collate4t1 VALUES('0', '0', '1');
    INSERT INTO collate4t1 VALUES('0', '1', '0');
    INSERT INTO collate4t1 VALUES('0', '1', '1');
    INSERT INTO collate4t1 VALUES('1', '0', '0');
    INSERT INTO collate4t1 VALUES('1', '0', '1');
    INSERT INTO collate4t1 VALUES('1', '1', '0');
    INSERT INTO collate4t1 VALUES('1', '1', '1');
    insert into collate4t2 SELECT * FROM collate4t1;
  }
} {}
do_test collate4-2.2.1 {
  count {
    SELECT * FROM collate4t2 NATURAL JOIN collate4t1;
  }
} {0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 63}
do_test collate4-2.2.1b {
  execsql {
    CREATE INDEX collate4i1 ON collate4t1(a, b, c);
  }
  count {
    SELECT * FROM collate4t2 NATURAL JOIN collate4t1;
  }
} {0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 29}
do_test collate4-2.2.2 {
  execsql {
    DROP INDEX collate4i1;
    CREATE INDEX collate4i1 ON collate4t1(a, b, c COLLATE text);
  }
  count {
    SELECT * FROM collate4t2 NATURAL JOIN collate4t1;
  }
} {0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 22}

do_test collate4-2.2.10 {
  execsql {
    DROP TABLE collate4t1;
    DROP TABLE collate4t2;
  }
} {}

#
# These tests - collate4-3.* verify that indices that implement
# UNIQUE and PRIMARY KEY constraints operate correctly with user
# defined collation sequences.
#
do_test collate4-3.0 {
  execsql {
    CREATE TABLE collate4t1(a PRIMARY KEY COLLATE NOCASE);
  }
} {}
do_test collate4-3.1 {
  catchsql {
    INSERT INTO collate4t1 VALUES('abc');
    INSERT INTO collate4t1 VALUES('ABC');
  }
} {1 {column a is not unique}}
do_test collate4-3.2 {
  execsql {
    SELECT * FROM collate4t1;
  }
} {abc}
do_test collate4-3.3 {
  catchsql {
    INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1;
  }
} {1 {column a is not unique}}
do_test collate4-3.4 {
  catchsql {
    INSERT INTO collate4t1 VALUES(1);
    UPDATE collate4t1 SET a = 'abc';
  }
} {1 {column a is not unique}}
do_test collate4-3.5 {
  execsql {
    DROP TABLE collate4t1;
    CREATE TABLE collate4t1(a COLLATE NOCASE UNIQUE);
  }
} {}
do_test collate4-3.6 {
  catchsql {
    INSERT INTO collate4t1 VALUES('abc');
    INSERT INTO collate4t1 VALUES('ABC');
  }
} {1 {column a is not unique}}
do_test collate4-3.7 {
  execsql {
    SELECT * FROM collate4t1;
  }
} {abc}
do_test collate4-3.8 {
  catchsql {
    INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1;
  }
} {1 {column a is not unique}}
do_test collate4-3.9 {
  catchsql {
    INSERT INTO collate4t1 VALUES(1);
    UPDATE collate4t1 SET a = 'abc';
  }
} {1 {column a is not unique}}
do_test collate4-3.10 {
  execsql {
    DROP TABLE collate4t1;
    CREATE TABLE collate4t1(a);
    CREATE UNIQUE INDEX collate4i1 ON collate4t1(a COLLATE NOCASE);
  }
} {}
do_test collate4-3.11 {
  catchsql {
    INSERT INTO collate4t1 VALUES('abc');
    INSERT INTO collate4t1 VALUES('ABC');
  }
} {1 {column a is not unique}}
do_test collate4-3.12 {
  execsql {
    SELECT * FROM collate4t1;
  }
} {abc}
do_test collate4-3.13 {
  catchsql {
    INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1;
  }
} {1 {column a is not unique}}
do_test collate4-3.14 {
  catchsql {
    INSERT INTO collate4t1 VALUES(1);
    UPDATE collate4t1 SET a = 'abc';
  }
} {1 {column a is not unique}}

do_test collate4-3.15 {
  execsql {
    DROP TABLE collate4t1;
  }
} {}

# Mimic the SQLite 2 collation type NUMERIC.
db collate numeric numeric_collate
proc numeric_collate {lhs rhs} {
  if {$lhs == $rhs} {return 0} 
  return [expr ($lhs>$rhs)?1:-1]
}

#
# These tests - collate4-4.* check that min() and max() only ever 
# use indices constructed with built-in collation type numeric.
#
# CHANGED:  min() and max() now use the collation type. If there
# is an indice that can be used, it is used.
#
do_test collate4-4.0 {
  execsql {
    CREATE TABLE collate4t1(a COLLATE TEXT);
    INSERT INTO collate4t1 VALUES('2');
    INSERT INTO collate4t1 VALUES('10');
    INSERT INTO collate4t1 VALUES('20');
    INSERT INTO collate4t1 VALUES('104');
  }
} {}
do_test collate4-4.1 {
  count {
    SELECT max(a) FROM collate4t1
  }
} {20 3}
do_test collate4-4.2 {
  count {
    SELECT min(a) FROM collate4t1
  }
} {10 3}
do_test collate4-4.3 {
  # Test that the index with collation type TEXT is used.
  execsql {
    CREATE INDEX collate4i1 ON collate4t1(a);
  }
  count {
    SELECT min(a) FROM collate4t1;
  }
} {10 1}
do_test collate4-4.4 {
  count {
    SELECT max(a) FROM collate4t1;
  }
} {20 0}
do_test collate4-4.5 {
  # Test that the index with collation type NUMERIC is not used.
  execsql {
    DROP INDEX collate4i1;
    CREATE INDEX collate4i1 ON collate4t1(a COLLATE NUMERIC);
  }
  count {
    SELECT min(a) FROM collate4t1;
  }
} {10 3}
do_test collate4-4.6 {
  count {
    SELECT max(a) FROM collate4t1;
  }
} {20 3}
do_test collate4-4.7 {
  execsql {
    DROP TABLE collate4t1;
  }
} {}

# Also test the scalar min() and max() functions.
#
do_test collate4-4.8 {
  execsql {
    CREATE TABLE collate4t1(a COLLATE TEXT, b COLLATE NUMERIC);
    INSERT INTO collate4t1 VALUES('11', '101');
    INSERT INTO collate4t1 VALUES('101', '11')
  }
} {}
do_test collate4-4.9 {
  execsql {
    SELECT max(a, b) FROM collate4t1;
  }
} {11 11}
do_test collate4-4.10 {
  execsql {
    SELECT max(b, a) FROM collate4t1;
  }
} {101 101}
do_test collate4-4.11 {
  execsql {
    SELECT max(a, '101') FROM collate4t1;
  }
} {11 101}
do_test collate4-4.12 {
  execsql {
    SELECT max('101', a) FROM collate4t1;
  }
} {11 101}
do_test collate4-4.13 {
  execsql {
    SELECT max(b, '101') FROM collate4t1;
  }
} {101 101}
do_test collate4-4.14 {
  execsql {
    SELECT max('101', b) FROM collate4t1;
  }
} {101 101}

do_test collate4-4.15 {
  execsql {
    DROP TABLE collate4t1;
  }
} {}

#
# These tests - collate4.6.* - ensure that implict INTEGER PRIMARY KEY 
# indices do not confuse collation sequences. 
#
# These indices are never used for sorting in SQLite. And you can't
# create another index on an INTEGER PRIMARY KEY column, so we don't have 
# to test that.
# (Revised 2004-Nov-22):  The ROWID can be used for sorting now.
#
do_test collate4-6.0 {
  execsql {
    CREATE TABLE collate4t1(a INTEGER PRIMARY KEY);
    INSERT INTO collate4t1 VALUES(101);
    INSERT INTO collate4t1 VALUES(10);
    INSERT INTO collate4t1 VALUES(15);
  }
} {}
do_test collate4-6.1 {
  cksort {
    SELECT * FROM collate4t1 ORDER BY 1;
  }
} {10 15 101 nosort}
do_test collate4-6.2 {
  cksort {
    SELECT * FROM collate4t1 ORDER BY oid;
  }
} {10 15 101 nosort}
do_test collate4-6.3 {
  cksort {
    SELECT * FROM collate4t1 ORDER BY oid||'' COLLATE TEXT;
  }
} {10 101 15 sort}

finish_test

Added test/collate5.test.









































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing DISTINCT, UNION, INTERSECT and EXCEPT
# SELECT statements that use user-defined collation sequences. Also
# GROUP BY clauses that use user-defined collation sequences.
#
# $Id: collate5.test,v 1.7 2008/09/16 11:58:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


#
# Tests are organised as follows:
# collate5-1.* - DISTINCT
# collate5-2.* - Compound SELECT
# collate5-3.* - ORDER BY on compound SELECT
# collate5-4.* - GROUP BY

# Create the collation sequence 'TEXT', purely for asthetic reasons. The
# test cases in this script could just as easily use BINARY.
db collate TEXT [list string compare]

# Mimic the SQLite 2 collation type NUMERIC.
db collate numeric numeric_collate
proc numeric_collate {lhs rhs} {
  if {$lhs == $rhs} {return 0} 
  return [expr ($lhs>$rhs)?1:-1]
}

#
# These tests - collate5-1.* - focus on the DISTINCT keyword.
#
do_test collate5-1.0 {
  execsql {
    CREATE TABLE collate5t1(a COLLATE nocase, b COLLATE text);

    INSERT INTO collate5t1 VALUES('a', 'apple');
    INSERT INTO collate5t1 VALUES('A', 'Apple');
    INSERT INTO collate5t1 VALUES('b', 'banana');
    INSERT INTO collate5t1 VALUES('B', 'banana');
    INSERT INTO collate5t1 VALUES('n', NULL);
    INSERT INTO collate5t1 VALUES('N', NULL);
  } 
} {}
do_test collate5-1.1 {
  execsql {
    SELECT DISTINCT a FROM collate5t1;
  }
} {A B N}
do_test collate5-1.2 {
  execsql {
    SELECT DISTINCT b FROM collate5t1;
  }
} {{} Apple apple banana}
do_test collate5-1.3 {
  execsql {
    SELECT DISTINCT a, b FROM collate5t1;
  }
} {A Apple a apple B banana N {}}

# Ticket #3376
#
do_test collate5-1.11 {
  execsql {
    CREATE TABLE tkt3376(a COLLATE nocase PRIMARY KEY);
    INSERT INTO tkt3376 VALUES('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz');
    INSERT INTO tkt3376 VALUES('ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789');
    SELECT DISTINCT a FROM tkt3376;
  }
} {abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789}
do_test collate5-1.12 {
  sqlite3 db2 :memory:
  db2 eval {
    PRAGMA encoding=UTF16le;
    CREATE TABLE tkt3376(a COLLATE nocase PRIMARY KEY);
    INSERT INTO tkt3376 VALUES('abc');
    INSERT INTO tkt3376 VALUES('ABX');
    SELECT DISTINCT a FROM tkt3376;
  }
} {abc ABX}
catch {db2 close}

# The remainder of this file tests compound SELECT statements.
# Omit it if the library is compiled such that they are omitted.
#
ifcapable !compound {
  finish_test
  return
}

#
# Tests named collate5-2.* focus on UNION, EXCEPT and INTERSECT
# queries that use user-defined collation sequences.
#
# collate5-2.1.* - UNION
# collate5-2.2.* - INTERSECT
# collate5-2.3.* - EXCEPT
#
do_test collate5-2.0 {
  execsql {
    CREATE TABLE collate5t2(a COLLATE text, b COLLATE nocase);

    INSERT INTO collate5t2 VALUES('a', 'apple');
    INSERT INTO collate5t2 VALUES('A', 'apple');
    INSERT INTO collate5t2 VALUES('b', 'banana');
    INSERT INTO collate5t2 VALUES('B', 'Banana');
  } 
} {}

do_test collate5-2.1.1 {
  execsql {
    SELECT a FROM collate5t1 UNION select a FROM collate5t2;
  }
} {A B N}
do_test collate5-2.1.2 {
  execsql {
    SELECT a FROM collate5t2 UNION select a FROM collate5t1;
  }
} {A B N a b n}
do_test collate5-2.1.3 {
  execsql {
    SELECT a, b FROM collate5t1 UNION select a, b FROM collate5t2;
  }
} {A Apple A apple B Banana b banana N {}}
do_test collate5-2.1.4 {
  execsql {
    SELECT a, b FROM collate5t2 UNION select a, b FROM collate5t1;
  }
} {A Apple B banana N {} a apple b banana n {}}

do_test collate5-2.2.1 {
  execsql {
    SELECT a FROM collate5t1 EXCEPT select a FROM collate5t2;
  }
} {N}
do_test collate5-2.2.2 {
  execsql {
    SELECT a FROM collate5t2 EXCEPT select a FROM collate5t1 WHERE a != 'a';
  }
} {A a}
do_test collate5-2.2.3 {
  execsql {
    SELECT a, b FROM collate5t1 EXCEPT select a, b FROM collate5t2;
  }
} {A Apple N {}}
do_test collate5-2.2.4 {
  execsql {
    SELECT a, b FROM collate5t2 EXCEPT select a, b FROM collate5t1 
      where a != 'a';
  }
} {A apple a apple}

do_test collate5-2.3.1 {
  execsql {
    SELECT a FROM collate5t1 INTERSECT select a FROM collate5t2;
  }
} {A B}
do_test collate5-2.3.2 {
  execsql {
    SELECT a FROM collate5t2 INTERSECT select a FROM collate5t1 WHERE a != 'a';
  }
} {B b}
do_test collate5-2.3.3 {
  execsql {
    SELECT a, b FROM collate5t1 INTERSECT select a, b FROM collate5t2;
  }
} {a apple B banana}
do_test collate5-2.3.4 {
  execsql {
    SELECT a, b FROM collate5t2 INTERSECT select a, b FROM collate5t1;
  }
} {A apple B Banana a apple b banana}

#
# This test ensures performs a UNION operation with a bunch of different
# length records. The goal is to test that the logic that compares records
# for the compound SELECT operators works with record lengths that lie
# either side of the troublesome 256 and 65536 byte marks.
#
set ::lens [list \
  0 1 2 3 4 5 6 7 8 9 \
  240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 \
  257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 \
  65520 65521 65522 65523 65524 65525 65526 65527 65528 65529 65530 \
  65531 65532 65533 65534 65535 65536 65537 65538 65539 65540 65541 \
  65542 65543 65544 65545 65546 65547 65548 65549 65550 65551 ]
do_test collate5-2.4.0 {
  execsql {
    BEGIN;
    CREATE TABLE collate5t3(a, b);
  }
  foreach ii $::lens { 
    execsql "INSERT INTO collate5t3 VALUES($ii, '[string repeat a $ii]');"
  }
  expr [llength [execsql {
    COMMIT;
    SELECT * FROM collate5t3 UNION SELECT * FROM collate5t3;
  }]] / 2
} [llength $::lens]
do_test collate5-2.4.1 {
  execsql {DROP TABLE collate5t3;}
} {}
unset ::lens

#
# These tests - collate5-3.* - focus on compound SELECT queries that 
# feature ORDER BY clauses.
#
do_test collate5-3.0 {
  execsql {
    SELECT a FROM collate5t1 UNION ALL SELECT a FROM collate5t2 ORDER BY 1;
  }
} {a A a A b B b B n N}
do_test collate5-3.1 {
  execsql {
    SELECT a FROM collate5t2 UNION ALL SELECT a FROM collate5t1 ORDER BY 1;
  }
} {A A B B N a a b b n}
do_test collate5-3.2 {
  execsql {
    SELECT a FROM collate5t1 UNION ALL SELECT a FROM collate5t2 
      ORDER BY 1 COLLATE TEXT;
  }
} {A A B B N a a b b n}

do_test collate5-3.3 {
  execsql {
    CREATE TABLE collate5t_cn(a COLLATE NUMERIC);
    CREATE TABLE collate5t_ct(a COLLATE TEXT);
    INSERT INTO collate5t_cn VALUES('1');
    INSERT INTO collate5t_cn VALUES('11');
    INSERT INTO collate5t_cn VALUES('101');
    INSERT INTO collate5t_ct SELECT * FROM collate5t_cn;
  }
} {}
do_test collate5-3.4 {
  execsql {
    SELECT a FROM collate5t_cn INTERSECT SELECT a FROM collate5t_ct ORDER BY 1;
  }
} {1 11 101}
do_test collate5-3.5 {
  execsql {
    SELECT a FROM collate5t_ct INTERSECT SELECT a FROM collate5t_cn ORDER BY 1;
  }
} {1 101 11}

do_test collate5-3.20 {
  execsql {
    DROP TABLE collate5t_cn;
    DROP TABLE collate5t_ct;
    DROP TABLE collate5t1;
    DROP TABLE collate5t2;
  }
} {}

do_test collate5-4.0 {
  execsql {
    CREATE TABLE collate5t1(a COLLATE NOCASE, b COLLATE NUMERIC); 
    INSERT INTO collate5t1 VALUES('a', '1');
    INSERT INTO collate5t1 VALUES('A', '1.0');
    INSERT INTO collate5t1 VALUES('b', '2');
    INSERT INTO collate5t1 VALUES('B', '3');
  }
} {}
do_test collate5-4.1 {
  string tolower [execsql {
    SELECT a, count(*) FROM collate5t1 GROUP BY a;
  }]
} {a 2 b 2}
do_test collate5-4.2 {
  execsql {
    SELECT a, b, count(*) FROM collate5t1 GROUP BY a, b ORDER BY a, b;
  }
} {A 1.0 2 b 2 1 B 3 1}
do_test collate5-4.3 {
  execsql {
    DROP TABLE collate5t1;
  }
} {}

finish_test

Added test/collate6.test.



















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is collation sequences in concert with triggers.
#
# $Id: collate6.test,v 1.4 2007/07/30 14:40:48 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# There are no tests in this file that will work without
# trigger support.
#
ifcapable {!trigger} {
  finish_test
  return
}

# Create a case-insensitive collation type NOCASE for use in testing. 
# Normally, capital letters are less than their lower-case counterparts.
db collate NOCASE nocase_collate
proc nocase_collate {a b} {
  return [string compare -nocase $a $b]
}

#
# Tests are organized as follows:
# collate6-1.* - triggers.
#

do_test collate6-1.0 {
  execsql {
    CREATE TABLE collate6log(a, b);
    CREATE TABLE collate6tab(a COLLATE NOCASE, b COLLATE BINARY);
  }
} {}

# Test that the default collation sequence applies to new.* references 
# in WHEN clauses.
do_test collate6-1.1 {
  execsql {
    CREATE TRIGGER collate6trig BEFORE INSERT ON collate6tab 
      WHEN new.a = 'a' BEGIN
        INSERT INTO collate6log VALUES(new.a, new.b);
    END;
  }
} {}
do_test collate6-1.2 {
  execsql {
    INSERT INTO collate6tab VALUES('a', 'b');
    SELECT * FROM collate6log;
  }
} {a b}
do_test collate6-1.3 {
  execsql {
    INSERT INTO collate6tab VALUES('A', 'B');
    SELECT * FROM collate6log;
  }
} {a b A B}
do_test collate6-1.4 {
  execsql {
    DROP TRIGGER collate6trig;
    DELETE FROM collate6log;
  } 
} {}

# Test that the default collation sequence applies to new.* references 
# in the body of triggers.
do_test collate6-1.5 {
  execsql {
    CREATE TRIGGER collate6trig BEFORE INSERT ON collate6tab BEGIN
      INSERT INTO collate6log VALUES(new.a='a', new.b='b');
    END;
  }
} {}
do_test collate6-1.6 {
  execsql {
    INSERT INTO collate6tab VALUES('a', 'b');
    SELECT * FROM collate6log;
  }
} {1 1}
do_test collate6-1.7 {
  execsql {
    INSERT INTO collate6tab VALUES('A', 'B');
    SELECT * FROM collate6log;
  }
} {1 1 1 0}
do_test collate6-1.8 {
  execsql {
    DROP TRIGGER collate6trig;
    DELETE FROM collate6log;
  } 
} {}

do_test collate6-1.9 {
  execsql {
    DROP TABLE collate6tab;
  }
} {}

# Test that an explicit collation sequence overrides an implicit 
# one attached to a 'new' reference.
#
do_test collate6-2.1 {
  execsql {
    CREATE TABLE abc(a COLLATE binary, b, c);
    CREATE TABLE def(a, b, c);
    CREATE TRIGGER abc_t1 AFTER INSERT ON abc BEGIN
      INSERT INTO def SELECT * FROM abc WHERE a < new.a COLLATE nocase;
    END
  }
} {}
do_test collate6-2.2 {
  execsql {
    INSERT INTO abc VALUES('One', 'Two', 'Three');
    INSERT INTO abc VALUES('one', 'two', 'three');
    SELECT * FROM def;
  }
} {}
do_test collate6-2.3 {
  execsql {
    UPDATE abc SET a = 'four' WHERE a = 'one';
    CREATE TRIGGER abc_t2 AFTER UPDATE ON abc BEGIN
      INSERT INTO def SELECT * FROM abc WHERE a < new.a COLLATE nocase;
    END;
    SELECT * FROM def;
  }
} {}

# At one point the 6-3.2 (but not 6-3.1) was causing an assert() to fail.
#
do_test collate6-3.1 {
  execsql {
    SELECT 1 FROM sqlite_master WHERE name COLLATE nocase = 'hello';
  }
} {}
do_test collate6-3.2 {
  execsql {
    SELECT 1 FROM sqlite_master WHERE 'hello' = name COLLATE nocase;
  }
} {}


finish_test

Added test/collate7.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#
# 2007 May 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is the experimental sqlite3_create_collation_v2()
# API.
#
# $Id: collate7.test,v 1.2 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

set ::caseless_del 0
proc caseless_cmp {zLeft zRight} {
  string compare -nocase $zLeft $zRight
}

do_test collate7-1.1 {
  set cmd [list incr ::caseless_del]
  sqlite3_create_collation_v2 db CASELESS caseless_cmp $cmd
  set ::caseless_del
} {0}
do_test collate7-1.2 {
  sqlite_delete_collation db CASELESS
  set ::caseless_del
} {1}
do_test collate7-1.3 {
  catchsql {
    CREATE TABLE abc(a COLLATE CASELESS, b, c);
  }
} {1 {no such collation sequence: CASELESS}}
do_test collate7-1.4 {
  sqlite3_create_collation_v2 db CASELESS caseless_cmp {incr ::caseless_del}
  db close
  set ::caseless_del
} {2}

do_test collate7-2.1 {
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  sqlite3_create_collation_v2 db CASELESS caseless_cmp {incr ::caseless_del}
  execsql {
    PRAGMA encoding='utf-16';
    CREATE TABLE abc16(a COLLATE CASELESS, b, c);
  } db
  set ::caseless_del
} {2}
do_test collate7-2.2 {
  execsql {
    SELECT * FROM abc16 WHERE a < 'abc';
  }
  set ::caseless_del
} {2}
do_test collate7-2.3 {
  sqlite_delete_collation db CASELESS
  set ::caseless_del
} {3}
do_test collate7-2.4 {
  catchsql {
    SELECT * FROM abc16 WHERE a < 'abc';
  }
} {1 {no such collation sequence: CASELESS}}

finish_test

Added test/collate8.test.



























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#
# 2007 June 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is making sure collations pass through the
# unary + operator.
#
# $Id: collate8.test,v 1.2 2008/08/25 12:14:09 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test collate8-1.1 {
  execsql {
    CREATE TABLE t1(a TEXT COLLATE nocase);
    INSERT INTO t1 VALUES('aaa');
    INSERT INTO t1 VALUES('BBB');
    INSERT INTO t1 VALUES('ccc');
    INSERT INTO t1 VALUES('DDD');
    SELECT a FROM t1 ORDER BY a;
  }
} {aaa BBB ccc DDD}
do_test collate8-1.2 {
  execsql {
    SELECT rowid FROM t1 WHERE a<'ccc' ORDER BY 1
  }
} {1 2}
do_test collate8-1.3 {
  execsql {
    SELECT rowid FROM t1 WHERE a<'ccc' COLLATE binary ORDER BY 1
  }
} {1 2 4}
do_test collate8-1.4 {
  execsql {
    SELECT rowid FROM t1 WHERE +a<'ccc' ORDER BY 1
  }
} {1 2}
do_test collate8-1.5 {
  execsql {
    SELECT a FROM t1 ORDER BY +a
  }
} {aaa BBB ccc DDD}
do_test collate8-1.11 {
  execsql {
    SELECT a AS x FROM t1 ORDER BY "x";
  }
} {aaa BBB ccc DDD}
do_test collate8-1.12 {
  execsql {
    SELECT a AS x FROM t1 WHERE x<'ccc' ORDER BY 1
  }
} {aaa BBB}
do_test collate8-1.13 {
  execsql {
    SELECT a AS x FROM t1 WHERE x<'ccc' COLLATE binary ORDER BY [x]
  }
} {aaa BBB DDD}
do_test collate8-1.14 {
  execsql {
    SELECT a AS x FROM t1 WHERE +x<'ccc' ORDER BY 1
  }
} {aaa BBB}
do_test collate8-1.15 {
  execsql {
    SELECT a AS x FROM t1 ORDER BY +x
  }
} {aaa BBB ccc DDD}


# When a result-set column is aliased into a WHERE clause, make sure the
# collating sequence logic works correctly.
#
do_test collate8-2.1 {
  execsql {
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES('abc');
    INSERT INTO t2 VALUES('ABC');
    SELECT a AS x FROM t2 WHERE x='abc';
  }
} {abc}
do_test collate8-2.2 {
  execsql {
    SELECT a AS x FROM t2 WHERE x='abc' COLLATE nocase;
  }
} {abc ABC}
do_test collate8-2.3 {
  execsql {
    SELECT a AS x FROM t2 WHERE (x COLLATE nocase)='abc';
  }
} {abc ABC}
do_test collate8-2.4 {
  execsql {
    SELECT a COLLATE nocase AS x FROM t2 WHERE x='abc';
  }
} {abc ABC}
do_test collate8-2.5 {
  execsql {
    SELECT a COLLATE nocase AS x FROM t2 WHERE (x COLLATE binary)='abc';
  }
} {abc}
do_test collate8-2.6 {
  execsql {
    SELECT a COLLATE nocase AS x FROM t2 WHERE x='abc' COLLATE binary;
  }
} {abc ABC}
do_test collate8-2.7 {
  execsql {
    SELECT * FROM t2 WHERE (a COLLATE nocase)='abc' COLLATE binary;
  }
} {abc ABC}
do_test collate8-2.8 {
  execsql {
    SELECT a COLLATE nocase AS x FROM t2 WHERE 'abc'=x COLLATE binary;
  }
} {abc}

finish_test

Added test/collate9.test.





































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#
# 2007 November 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is making sure that the names of collation
# sequences may be quoted using double quotes in SQL statements.
#
# $Id: collate9.test,v 1.2 2008/07/10 00:32:42 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc reverse_sort {lhs rhs} {
  return [string compare $rhs $lhs]
}
db collate "reverse sort" reverse_sort

# This procedure executes the SQL.  Then it checks to see if the OP_Sort
# opcode was executed.  If an OP_Sort did occur, then "sort" is appended
# to the result.  If no OP_Sort happened, then "nosort" is appended.
#
# This procedure is used to check to make sure sorting is or is not
# occurring as expected.
#
proc cksort {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

# Test plan:
#
#     collate9-1.* - Test collation sequences attached to table columns
#     collate9-2.* - Test collation sequences attached to expressions
#     collate9-3.* - Test collation sequences attached to an index
#     collate9-4.* - Test collation sequences as an argument to REINDEX
#

do_test collate9-1.1 {
  execsql {
    CREATE TABLE xy(x COLLATE "reverse sort", y COLLATE binary);
    INSERT INTO xy VALUES('one', 'one');
    INSERT INTO xy VALUES('two', 'two');
    INSERT INTO xy VALUES('three', 'three');
  }
} {}
do_test collate9-1.2 {
  execsql { 
    SELECT x FROM xy ORDER BY x
  }
} {two three one}
do_test collate9-1.3 {
  execsql { 
    SELECT y FROM xy ORDER BY y
  }
} {one three two}
do_test collate9-1.4 {
  cksort { 
    SELECT x FROM xy ORDER BY x
  }
} {two three one sort}
do_test collate9-1.5 {
  execsql { 
    CREATE INDEX xy_i ON xy(x)
  }
} {}
do_test collate9-1.6 {
  cksort { 
    SELECT x FROM xy ORDER BY x
  }
} {two three one nosort}

do_test collate9-2.1 {
  execsql { 
    SELECT x, x < 'seven' FROM xy ORDER BY x
  }
} {two 1 three 1 one 0}
do_test collate9-2.2 {
  execsql { 
    SELECT y, y < 'seven' FROM xy ORDER BY x
  }
} {two 0 three 0 one 1}
do_test collate9-2.3 {
  execsql { 
    SELECT y, y COLLATE "reverse sort" < 'seven' FROM xy ORDER BY x
  }
} {two 1 three 1 one 0}
do_test collate9-2.4 {
  execsql {
    SELECT y FROM xy ORDER BY y
  }
} {one three two}
do_test collate9-2.5 {
  execsql {
    SELECT y FROM xy ORDER BY y COLLATE "reverse sort"
  }
} {two three one}
do_test collate9-2.6 {
  execsql {
    SELECT y COLLATE "reverse sort" AS aaa FROM xy ORDER BY aaa
  }
} {two three one}

do_test collate9-3.1 {
  execsql {
    CREATE INDEX xy_i2 ON xy(y COLLATE "reverse sort");
  }
} {}
do_test collate9-3.2 {
  cksort { 
    SELECT y FROM xy ORDER BY y 
  }
} {one three two sort}
do_test collate9-3.3 {
  cksort { 
    SELECT y FROM xy ORDER BY y COLLATE "reverse sort"
  }
} {two three one nosort}
do_test collate9-3.4 {
  cksort { 
    SELECT y AS aaa FROM xy ORDER BY aaa
  }
} {one three two sort}
do_test collate9-3.5 {
  cksort { 
    SELECT y COLLATE "reverse sort" AS aaa FROM xy ORDER BY aaa
  }
} {two three one nosort}

ifcapable reindex {
  do_test collate9-4.1 {
    execsql {
      REINDEX "reverse sort"
    }
  } {}

  # Modify the "reverse sort" collation so that it now sorts in the same
  # order as binary.
  proc reverse_sort {lhs rhs} {
    return [string compare $lhs $rhs]
  }

  # The integrity check should now fail because the indexes created using
  # "reverse sort" are no longer in sync with the collation sequence
  # implementation.
  do_test collate9-4.2 {
    expr {"ok" eq [execsql { PRAGMA integrity_check }]}
  } {0}

  do_test collate9-4.3 {
    execsql {
      REINDEX "reverse sort"
    }
  } {}

  # Integrity check should now pass.
  do_test collate9-4.4 {
    expr {"ok" eq [execsql { PRAGMA integrity_check }]}
  } {1}

  do_test collate9-4.5 {
    cksort {
      SELECT x FROM xy ORDER BY x COLLATE "reverse sort"
    }
  } {one three two nosort}
}

finish_test

Added test/collateA.test.



















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#
# 2008 January 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is the built-in RTRIM collating
# API.
#
# $Id: collateA.test,v 1.3 2008/04/15 04:02:41 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test collateA-1.1 {
  execsql {
    CREATE TABLE t1(
      a INTEGER PRIMARY KEY,
      b TEXT COLLATE BINARY,
      c TEXT COLLATE RTRIM
    );
    INSERT INTO t1 VALUES(1, 'abcde','abcde');
    INSERT INTO t1 VALUES(2, 'xyzzy ','xyzzy ');
    INSERT INTO t1 VALUES(3, 'xyzzy  ','xyzzy  ');
    INSERT INTO t1 VALUES(4, 'xyzzy   ','xyzzy   ');
    INSERT INTO t1 VALUES(5, '   ', '   ');
    INSERT INTO t1 VALUES(6, '', '');
    SELECT count(*) FROM t1;
  }
} {6}
do_test collateA-1.2 {
  execsql {SELECT a FROM t1 WHERE b='abcde     '}
} {}
do_test collateA-1.3 {
  execsql {SELECT a FROM t1 WHERE c='abcde     '}
} {1}
do_test collateA-1.4 {
  execsql {SELECT a FROM t1 WHERE b='xyzzy'}
} {}
do_test collateA-1.5 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy'}
} {2 3 4}
do_test collateA-1.6 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy '}
} {2 3 4}
do_test collateA-1.7 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy  '}
} {2 3 4}
do_test collateA-1.8 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy   '}
} {2 3 4}
do_test collateA-1.9 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy    '}
} {2 3 4}
do_test collateA-1.10 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy                                  '}
} {2 3 4}
do_test collateA-1.11 {
  execsql {SELECT 'abc123'='abc123                         ' COLLATE RTRIM;}
} {1}
do_test collateA-1.12 {
  execsql {SELECT 'abc123                         '='abc123' COLLATE RTRIM;}
} {1}
do_test collateA-1.13 {
  execsql {SELECT '  '='' COLLATE RTRIM, '  '='' COLLATE BINARY, '  '=''}
} {1 0 0}
do_test collateA-1.14 {
  execsql {SELECT ''='  ' COLLATE RTRIM, ''='  ' COLLATE BINARY, ''='  '}
} {1 0 0}
do_test collateA-1.15 {
  execsql {SELECT '  '='      ' COLLATE RTRIM, '  '='        '}
} {1 0}
do_test collateA-1.16 {
  execsql {SELECT ''<>'  ' COLLATE RTRIM, ''<>'  ' COLLATE BINARY, ''<>'  '}
} {0 1 1}
do_test collateA-1.17 {
  execsql {SELECT a FROM t1 WHERE c='xyzz'}
} {}
do_test collateA-1.18 {
  execsql {SELECT a FROM t1 WHERE c='xyzzyy   '}
} {}
do_test collateA-1.19 {
  execsql {SELECT a FROM t1 WHERE c='xyzz   '}
} {}
do_test collateA-1.20 {
  execsql {SELECT a FROM t1 WHERE c='abcd   '}
} {}
do_test collateA-1.21 {
  execsql {SELECT a FROM t1 WHERE c='abcd'}
} {}
do_test collateA-1.22 {
  execsql {SELECT a FROM t1 WHERE c='abc'}
} {}
do_test collateA-1.23 {
  execsql {SELECT a FROM t1 WHERE c='abcdef    '}
} {}
do_test collateA-1.24 {
  execsql {SELECT a FROM t1 WHERE c=''}
} {5 6}
do_test collateA-1.25 {
  execsql {SELECT a FROM t1 WHERE c=' '}
} {5 6}
do_test collateA-1.26 {
  execsql {SELECT a FROM t1 WHERE c='                    '}
} {5 6}


do_test collateA-2.1 {
  execsql {
    CREATE INDEX i1b ON t1(b);
    CREATE INDEX i1c ON t1(c);
    PRAGMA integrity_check;
  }
} {ok}
do_test collateA-2.2 {
  execsql {SELECT a FROM t1 WHERE b='abcde     '}
} {}
do_test collateA-2.3 {
  execsql {SELECT a FROM t1 WHERE c='abcde     '}
} {1}
do_test collateA-2.4 {
  execsql {SELECT a FROM t1 WHERE b='xyzzy'}
} {}
do_test collateA-2.5 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy'}
} {2 3 4}
do_test collateA-2.6 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy '}
} {2 3 4}
do_test collateA-2.7 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy  '}
} {2 3 4}
do_test collateA-2.8 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy   '}
} {2 3 4}
do_test collateA-2.9 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy    '}
} {2 3 4}
do_test collateA-2.10 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy                                  '}
} {2 3 4}
do_test collateA-2.17 {
  execsql {SELECT a FROM t1 WHERE c='xyzz'}
} {}
do_test collateA-2.18 {
  execsql {SELECT a FROM t1 WHERE c='xyzzyy   '}
} {}
do_test collateA-2.19 {
  execsql {SELECT a FROM t1 WHERE c='xyzz   '}
} {}
do_test collateA-2.20 {
  execsql {SELECT a FROM t1 WHERE c='abcd   '}
} {}
do_test collateA-2.21 {
  execsql {SELECT a FROM t1 WHERE c='abcd'}
} {}
do_test collateA-2.22 {
  execsql {SELECT a FROM t1 WHERE c='abc'}
} {}
do_test collateA-2.23 {
  execsql {SELECT a FROM t1 WHERE c='abcdef    '}
} {}
do_test collateA-2.24 {
  execsql {SELECT a FROM t1 WHERE c=''}
} {5 6}
do_test collateA-2.25 {
  execsql {SELECT a FROM t1 WHERE c=' '}
} {5 6}
do_test collateA-2.26 {
  execsql {SELECT a FROM t1 WHERE c='                    '}
} {5 6}


do_test collateA-3.1 {
  db close
  sqlite3 db test.db
  execsql {
    REINDEX;
    PRAGMA integrity_check;
  }
} {ok}
do_test collateA-3.2 {
  execsql {SELECT a FROM t1 WHERE b='abcde     '}
} {}
do_test collateA-3.3 {
  execsql {SELECT a FROM t1 WHERE c='abcde     '}
} {1}
do_test collateA-3.4 {
  execsql {SELECT a FROM t1 WHERE b='xyzzy'}
} {}
do_test collateA-3.5 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy'}
} {2 3 4}
do_test collateA-3.6 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy '}
} {2 3 4}
do_test collateA-3.7 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy  '}
} {2 3 4}
do_test collateA-3.8 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy   '}
} {2 3 4}
do_test collateA-3.9 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy    '}
} {2 3 4}
do_test collateA-3.10 {
  execsql {SELECT a FROM t1 WHERE c='xyzzy                                  '}
} {2 3 4}


finish_test

Added test/colmeta.test.





























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#
# 2006 February 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is the sqlite3_table_column_metadata() API.
#
# $Id: colmeta.test,v 1.4 2008/01/23 12:52:41 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !columnmetadata {
  finish_test
  return
}

# Set up a schema in the main and temp test databases.
do_test colmeta-0 {
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE TABLE abc2(a PRIMARY KEY COLLATE NOCASE, b VARCHAR(32), c);
    CREATE TABLE abc3(a NOT NULL, b INTEGER PRIMARY KEY, c);
  }
  ifcapable autoinc {
    execsql {
      CREATE TABLE abc4(a, b INTEGER PRIMARY KEY AUTOINCREMENT, c);
    }
  }
  ifcapable view {
    execsql {
      CREATE VIEW v1 AS SELECT * FROM abc2;
    }
  }
} {}


# Return values are of the form:
#
#   {<decl-type> <collation> <not null> <primary key> <auto increment>}
#
set tests {
  1  {main abc a}                {0 {{} BINARY 0 0 0}}
  2  {{} abc a}                  {0 {{} BINARY 0 0 0}}
  3  {{} abc2 b}                 {0 {VARCHAR(32) BINARY 0 0 0}}
  4  {main abc2 b}               {0 {VARCHAR(32) BINARY 0 0 0}}
  5  {{} abc2 a}                 {0 {{} NOCASE 0 1 0}}
  6  {{} abc3 a}                 {0 {{} BINARY 1 0 0}}
  7  {{} abc3 b}                 {0 {INTEGER BINARY 0 1 0}}
  13 {main abc rowid}            {0 {INTEGER BINARY 0 1 0}}
  14 {main abc3 rowid}           {0 {INTEGER BINARY 0 1 0}}
  16 {main abc d}                {1 {no such table column: abc.d}}
}
ifcapable view {
  set tests [concat $tests {
    8  {{} abc4 b}                 {0 {INTEGER BINARY 0 1 1}}
    15 {main abc4 rowid}           {0 {INTEGER BINARY 0 1 1}}
  }]
}
ifcapable view {
  set tests [concat $tests {
    9  {{} v1 a}                   {1 {no such table column: v1.a}}
    10 {main v1 b}                 {1 {no such table column: v1.b}}
    11 {main v1 badname}           {1 {no such table column: v1.badname}}
    12 {main v1 rowid}             {1 {no such table column: v1.rowid}}
  }]
}

foreach {tn params results} $tests {
  set ::DB [sqlite3_connection_pointer db]

  set tstbody [concat sqlite3_table_column_metadata $::DB $params] 
  do_test colmeta-$tn.1 {
    list [catch $tstbody msg] [set msg]
  } $results

  db close
  sqlite3 db test.db

  set ::DB [sqlite3_connection_pointer db]
  set tstbody [concat sqlite3_table_column_metadata $::DB $params] 
  do_test colmeta-$tn.2 {
    list [catch $tstbody msg] [set msg]
  } $results
}

finish_test

Added test/colname.test.



















































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# 2008 July 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# The focus of this file is testing how SQLite generates the names
# of columns in a result set.
#
# $Id: colname.test,v 1.7 2009/06/02 15:47:38 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Rules (applied in order):
#
# (1) If there is an AS clause, use it.
#
# (2) A non-trival expression (not a table column name) then the name is
#     a copy of the expression text.
#
# (3) If short_column_names=ON, then just the abbreviated column name without
#     the table name.
#
# (4) When short_column_names=OFF and full_column_names=OFF then
#     use case (2) for simple queries and case (5) for joins.
#
# (5) When short_column_names=OFF and full_column_names=ON then
#     use the form: TABLE.COLUMN
#


# Verify the default settings for short_column_name and full_column_name
#
do_test colname-1.1 {
  db eval {PRAGMA short_column_names}
} {1}
do_test colname-1.2 {
  db eval {PRAGMA full_column_names}
} {0}

# Tests for then short=ON and full=any
#
do_test colname-2.1 {
  db eval {
    CREATE TABLE tabc(a,b,c);
    INSERT INTO tabc VALUES(1,2,3);
    CREATE TABLE txyz(x,y,z);
    INSERT INTO txyz VALUES(4,5,6);
    CREATE TABLE tboth(a,b,c,x,y,z);
    INSERT INTO tboth VALUES(11,12,13,14,15,16);
    CREATE VIEW v1 AS SELECT tabC.a, txyZ.x, * 
      FROM tabc, txyz ORDER BY 1 LIMIT 1;
    CREATE VIEW v2 AS SELECT tabC.a, txyZ.x, tboTh.a, tbotH.x, *
      FROM tabc, txyz, tboth ORDER BY 1 LIMIT 1;
  }
  execsql2 {
    SELECT * FROM tabc;
  }
} {a 1 b 2 c 3}
do_test colname-2.2 {
  execsql2 {
    SELECT Tabc.a, tAbc.b, taBc.c, * FROM tabc
  }
} {a 1 b 2 c 3 a 1 b 2 c 3}
do_test colname-2.3 {
  execsql2 {
    SELECT +tabc.a, -tabc.b, tabc.c, * FROM tabc
  }
} {+tabc.a 1 -tabc.b -2 c 3 a 1 b 2 c 3}
do_test colname-2.4 {
  execsql2 {
    SELECT +tabc.a AS AAA, -tabc.b AS BBB, tabc.c CCC, * FROM tabc
  }
} {AAA 1 BBB -2 CCC 3 a 1 b 2 c 3}
do_test colname-2.5 {
  execsql2 {
    SELECT tabc.a, txyz.x, * FROM tabc, txyz;
  }
} {a 1 x 4 a 1 b 2 c 3 x 4 y 5 z 6}
do_test colname-2.6 {
  execsql2 {
    SELECT tabc.a, txyz.x, tabc.*, txyz.* FROM tabc, txyz;
  }
} {a 1 x 4 a 1 b 2 c 3 x 4 y 5 z 6}
do_test colname-2.7 {
  execsql2 {
    SELECT tabc.a, txyz.x, tboth.a, tboth.x, * FROM tabc, txyz, tboth;
  }
} {a 11 x 14 a 11 x 14 a 11 b 12 c 13 x 14 y 15 z 16 a 11 b 12 c 13 x 14 y 15 z 16}
do_test colname-2.8 {
  execsql2 {
    SELECT * FROM v1 ORDER BY 2;
  }
} {a 1 x 4 a:1 1 b 2 c 3 x:1 4 y 5 z 6}
do_test colname-2.9 {
  execsql2 {
    SELECT * FROM v2 ORDER BY 2;
  }
} {a 1 x 4 a:1 11 x:1 14 a:2 1 b 2 c 3 x:2 4 y 5 z 6 a:3 11 b:1 12 c:1 13 x:3 14 y:1 15 z:1 16}


# Tests for short=OFF and full=OFF
#
do_test colname-3.1 {
  db eval {
    PRAGMA short_column_names=OFF;
    PRAGMA full_column_names=OFF;
    CREATE VIEW v3 AS SELECT tabC.a, txyZ.x, *
      FROM tabc, txyz ORDER BY 1 LIMIT 1;
    CREATE VIEW v4 AS SELECT tabC.a, txyZ.x, tboTh.a, tbotH.x, * 
      FROM tabc, txyz, tboth ORDER BY 1 LIMIT 1;
  }
  execsql2 {
    SELECT * FROM tabc;
  }
} {a 1 b 2 c 3}
do_test colname-3.2 {
  execsql2 {
    SELECT Tabc.a, tAbc.b, taBc.c FROM tabc
  }
} {Tabc.a 1 tAbc.b 2 taBc.c 3}
do_test colname-3.3 {
  execsql2 {
    SELECT +tabc.a, -tabc.b, tabc.c FROM tabc
  }
} {+tabc.a 1 -tabc.b -2 tabc.c 3}
do_test colname-3.4 {
  execsql2 {
    SELECT +tabc.a AS AAA, -tabc.b AS BBB, tabc.c CCC FROM tabc
  }
} {AAA 1 BBB -2 CCC 3}
do_test colname-3.5 {
  execsql2 {
    SELECT Tabc.a, Txyz.x, * FROM tabc, txyz;
  }
} {Tabc.a 1 Txyz.x 4 a 1 b 2 c 3 x 4 y 5 z 6}
do_test colname-3.6 {
  execsql2 {
    SELECT tabc.*, txyz.* FROM tabc, txyz;
  }
} {a 1 b 2 c 3 x 4 y 5 z 6}
do_test colname-3.7 {
  execsql2 {
    SELECT * FROM tabc, txyz, tboth;
  }
} {a 11 b 12 c 13 x 14 y 15 z 16 a 11 b 12 c 13 x 14 y 15 z 16}
do_test colname-3.8 {
  execsql2 {
    SELECT v1.a, * FROM v1 ORDER BY 2;
  }
} {v1.a 1 a 1 x 4 a:1 1 b 2 c 3 x:1 4 y 5 z 6}
do_test colname-3.9 {
  execsql2 {
    SELECT * FROM v2 ORDER BY 2;
  }
} {a 1 x 4 a:1 11 x:1 14 a:2 1 b 2 c 3 x:2 4 y 5 z 6 a:3 11 b:1 12 c:1 13 x:3 14 y:1 15 z:1 16}
do_test colname-3.10 {
  execsql2 {
    SELECT * FROM v3 ORDER BY 2;
  }
} {a 1 x 4 a:1 1 b 2 c 3 x:1 4 y 5 z 6}
do_test colname-3.11 {
  execsql2 {
    SELECT * FROM v4 ORDER BY 2;
  }
} {a 1 x 4 a:1 11 x:1 14 a:2 1 b 2 c 3 x:2 4 y 5 z 6 a:3 11 b:1 12 c:1 13 x:3 14 y:1 15 z:1 16}

# Test for short=OFF and full=ON
#
do_test colname-4.1 {
  db eval {
    PRAGMA short_column_names=OFF;
    PRAGMA full_column_names=ON;
    CREATE VIEW v5 AS SELECT tabC.a, txyZ.x, *
      FROM tabc, txyz ORDER BY 1 LIMIT 1;
    CREATE VIEW v6 AS SELECT tabC.a, txyZ.x, tboTh.a, tbotH.x, * 
      FROM tabc, txyz, tboth ORDER BY 1 LIMIT 1;
  }
  execsql2 {
    SELECT * FROM tabc;
  }
} {tabc.a 1 tabc.b 2 tabc.c 3}
do_test colname-4.2 {
  execsql2 {
    SELECT Tabc.a, tAbc.b, taBc.c FROM tabc
  }
} {tabc.a 1 tabc.b 2 tabc.c 3}
do_test colname-4.3 {
  execsql2 {
    SELECT +tabc.a, -tabc.b, tabc.c FROM tabc
  }
} {+tabc.a 1 -tabc.b -2 tabc.c 3}
do_test colname-4.4 {
  execsql2 {
    SELECT +tabc.a AS AAA, -tabc.b AS BBB, tabc.c CCC FROM tabc
  }
} {AAA 1 BBB -2 CCC 3}
do_test colname-4.5 {
  execsql2 {
    SELECT Tabc.a, Txyz.x, * FROM tabc, txyz;
  }
} {tabc.a 1 txyz.x 4 tabc.a 1 tabc.b 2 tabc.c 3 txyz.x 4 txyz.y 5 txyz.z 6}
do_test colname-4.6 {
  execsql2 {
    SELECT tabc.*, txyz.* FROM tabc, txyz;
  }
} {tabc.a 1 tabc.b 2 tabc.c 3 txyz.x 4 txyz.y 5 txyz.z 6}
do_test colname-4.7 {
  execsql2 {
    SELECT * FROM tabc, txyz, tboth;
  }
} {tabc.a 1 tabc.b 2 tabc.c 3 txyz.x 4 txyz.y 5 txyz.z 6 tboth.a 11 tboth.b 12 tboth.c 13 tboth.x 14 tboth.y 15 tboth.z 16}
do_test colname-4.8 {
  execsql2 {
    SELECT * FROM v1 ORDER BY 2;
  }
} {v1.a 1 v1.x 4 v1.a:1 1 v1.b 2 v1.c 3 v1.x:1 4 v1.y 5 v1.z 6}
do_test colname-4.9 {
  execsql2 {
    SELECT * FROM v2 ORDER BY 2;
  }
} {v2.a 1 v2.x 4 v2.a:1 11 v2.x:1 14 v2.a:2 1 v2.b 2 v2.c 3 v2.x:2 4 v2.y 5 v2.z 6 v2.a:3 11 v2.b:1 12 v2.c:1 13 v2.x:3 14 v2.y:1 15 v2.z:1 16}
do_test colname-4.10 {
  execsql2 {
    SELECT * FROM v3 ORDER BY 2;
  }
} {v3.a 1 v3.x 4 v3.a:1 1 v3.b 2 v3.c 3 v3.x:1 4 v3.y 5 v3.z 6}
do_test colname-4.11 {
  execsql2 {
    SELECT * FROM v4 ORDER BY 2;
  }
} {v4.a 1 v4.x 4 v4.a:1 11 v4.x:1 14 v4.a:2 1 v4.b 2 v4.c 3 v4.x:2 4 v4.y 5 v4.z 6 v4.a:3 11 v4.b:1 12 v4.c:1 13 v4.x:3 14 v4.y:1 15 v4.z:1 16}
do_test colname-4.12 {
  execsql2 {
    SELECT * FROM v5 ORDER BY 2;
  }
} {v5.a 1 v5.x 4 v5.a:1 1 v5.b 2 v5.c 3 v5.x:1 4 v5.y 5 v5.z 6}
do_test colname-4.13 {
  execsql2 {
    SELECT * FROM v6 ORDER BY 2;
  }
} {v6.a 1 v6.x 4 v6.a:1 11 v6.x:1 14 v6.a:2 1 v6.b 2 v6.c 3 v6.x:2 4 v6.y 5 v6.z 6 v6.a:3 11 v6.b:1 12 v6.c:1 13 v6.x:3 14 v6.y:1 15 v6.z:1 16}

# ticket #3229
do_test colname-5.1 {
  lreplace [db eval {
    SELECT x.* FROM sqlite_master X LIMIT 1;
  }] 3 3 x
} {table tabc tabc x {CREATE TABLE tabc(a,b,c)}}

# ticket #3370, #3371, #3372
#
do_test colname-6.1 {
  db close
  sqlite3 db test.db
  db eval {
    CREATE TABLE t6(a, ['a'], ["a"], "[a]", [`a`]);
    INSERT INTO t6 VALUES(1,2,3,4,5);
  }
  execsql2 {SELECT * FROM t6}
} {a 1 'a' 2 {"a"} 3 {[a]} 4 `a` 5}
do_test colname-6.2 {
  execsql2 {SELECT ['a'], [`a`], "[a]", [a], ["a"] FROM t6}
} {'a' 2 `a` 5 {[a]} 4 a 1 {"a"} 3}
do_test colname-6.3 {
  execsql2 {SELECT "'a'", "`a`", "[a]", "a", """a""" FROM t6}
} {'a' 2 `a` 5 {[a]} 4 a 1 {"a"} 3}
do_test colname-6.4 {
  execsql2 {SELECT `'a'`, ```a```, `[a]`, `a`, `"a"` FROM t6}
} {'a' 2 `a` 5 {[a]} 4 a 1 {"a"} 3}
do_test colname-6.11 {
  execsql2 {SELECT a, max(a) AS m FROM t6}
} {a 1 m 1}
do_test colname-6.12 {
  execsql2 {SELECT `a`, max(a) AS m FROM t6}
} {a 1 m 1}
do_test colname-6.13 {
  execsql2 {SELECT "a", max(a) AS m FROM t6}
} {a 1 m 1}
do_test colname-6.14 {
  execsql2 {SELECT [a], max(a) AS m FROM t6}
} {a 1 m 1}
do_test colname-6.15 {
  execsql2 {SELECT t6.a, max(a) AS m FROM t6}
} {a 1 m 1}
do_test colname-6.16 {
  execsql2 {SELECT ['a'], max(['a']) AS m FROM t6}
} {'a' 2 m 2}
do_test colname-6.17 {
  execsql2 {SELECT ["a"], max(["a"]) AS m FROM t6}
} {{"a"} 3 m 3}
do_test colname-6.18 {
  execsql2 {SELECT "[a]", max("[a]") AS m FROM t6}
} {{[a]} 4 m 4}
do_test colname-6.19 {
  execsql2 {SELECT "`a`", max([`a`]) AS m FROM t6}
} {`a` 5 m 5}


# Ticket #3429
# We cannot find anything wrong, but it never hurts to add another
# test case.
#
do_test colname-7.1 {
  db eval {
    CREATE TABLE t7(x INTEGER PRIMARY KEY, y);
    INSERT INTO t7 VALUES(1,2);
  }
  execsql2 {SELECT rowid, * FROM t7}
} {x 1 x 1 y 2}

# Tickets #3893 and #3984.  (Same problem; independently reported)
#
do_test colname-8.1 {
  db eval {
    CREATE TABLE "t3893"("x");
    INSERT INTO t3893 VALUES(123);
    SELECT "y"."x" FROM (SELECT "x" FROM "t3893") AS "y";
  }
} {123}

finish_test

Added test/conflict.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# 2002 January 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the conflict resolution extension
# to SQLite.
#
# $Id: conflict.test,v 1.32 2009/04/30 09:10:38 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !conflict {
  finish_test
  return
}

# Create tables for the first group of tests.
#
do_test conflict-1.0 {
  execsql {
    CREATE TABLE t1(a, b, c, UNIQUE(a,b));
    CREATE TABLE t2(x);
    SELECT c FROM t1 ORDER BY c;
  }
} {}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   cmd    An INSERT or REPLACE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "c" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t2
#   t3     Number of temporary files created by this test
#
foreach {i cmd t0 t1 t2 t3} {
  1 INSERT                  1 {}  1  0
  2 {INSERT OR IGNORE}      0 3   1  0
  3 {INSERT OR REPLACE}     0 4   1  0
  4 REPLACE                 0 4   1  0
  5 {INSERT OR FAIL}        1 {}  1  0
  6 {INSERT OR ABORT}       1 {}  1  0
  7 {INSERT OR ROLLBACK}    1 {}  {} 0
} {
  do_test conflict-1.$i {
    set ::sqlite_opentemp_count 0
    set r0 [catch {execsql [subst {
      DELETE FROM t1;
      DELETE FROM t2;
      INSERT INTO t1 VALUES(1,2,3);
      BEGIN;
      INSERT INTO t2 VALUES(1); 
      $cmd INTO t1 VALUES(1,2,4);
    }]} r1]
    catch {execsql {COMMIT}}
    if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]}
    set r2 [execsql {SELECT x FROM t2}]
    set r3 $::sqlite_opentemp_count
    list $r0 $r1 $r2 $r3
  } [list $t0 $t1 $t2 $t3]
}

# Create tables for the first group of tests.
#
do_test conflict-2.0 {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(a,b));
    CREATE TABLE t2(x);
    SELECT c FROM t1 ORDER BY c;
  }
} {}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   cmd    An INSERT or REPLACE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "c" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t2
#
foreach {i cmd t0 t1 t2} {
  1 INSERT                  1 {}  1
  2 {INSERT OR IGNORE}      0 3   1
  3 {INSERT OR REPLACE}     0 4   1
  4 REPLACE                 0 4   1
  5 {INSERT OR FAIL}        1 {}  1
  6 {INSERT OR ABORT}       1 {}  1
  7 {INSERT OR ROLLBACK}    1 {}  {}
} {
  do_test conflict-2.$i {
    set r0 [catch {execsql [subst {
      DELETE FROM t1;
      DELETE FROM t2;
      INSERT INTO t1 VALUES(1,2,3);
      BEGIN;
      INSERT INTO t2 VALUES(1); 
      $cmd INTO t1 VALUES(1,2,4);
    }]} r1]
    catch {execsql {COMMIT}}
    if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]}
    set r2 [execsql {SELECT x FROM t2}]
    list $r0 $r1 $r2
  } [list $t0 $t1 $t2]
}

# Create tables for the first group of tests.
#
do_test conflict-3.0 {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    CREATE TABLE t1(a, b, c INTEGER, PRIMARY KEY(c), UNIQUE(a,b));
    CREATE TABLE t2(x);
    SELECT c FROM t1 ORDER BY c;
  }
} {}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   cmd    An INSERT or REPLACE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "c" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t2
#
foreach {i cmd t0 t1 t2} {
  1 INSERT                  1 {}  1
  2 {INSERT OR IGNORE}      0 3   1
  3 {INSERT OR REPLACE}     0 4   1
  4 REPLACE                 0 4   1
  5 {INSERT OR FAIL}        1 {}  1
  6 {INSERT OR ABORT}       1 {}  1
  7 {INSERT OR ROLLBACK}    1 {}  {}
} {
  do_test conflict-3.$i {
    set r0 [catch {execsql [subst {
      DELETE FROM t1;
      DELETE FROM t2;
      INSERT INTO t1 VALUES(1,2,3);
      BEGIN;
      INSERT INTO t2 VALUES(1); 
      $cmd INTO t1 VALUES(1,2,4);
    }]} r1]
    catch {execsql {COMMIT}}
    if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]}
    set r2 [execsql {SELECT x FROM t2}]
    list $r0 $r1 $r2
  } [list $t0 $t1 $t2]
}

do_test conflict-4.0 {
  execsql {
    DROP TABLE t2;
    CREATE TABLE t2(x);
    SELECT x FROM t2;
  }
} {}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   conf1  The conflict resolution algorithm on the UNIQUE constraint
#   cmd    An INSERT or REPLACE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "c" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t2
#
foreach {i conf1 cmd t0 t1 t2} {
  1 {}       INSERT                  1 {}  1
  2 REPLACE  INSERT                  0 4   1
  3 IGNORE   INSERT                  0 3   1
  4 FAIL     INSERT                  1 {}  1
  5 ABORT    INSERT                  1 {}  1
  6 ROLLBACK INSERT                  1 {}  {}
  7 REPLACE  {INSERT OR IGNORE}      0 3   1
  8 IGNORE   {INSERT OR REPLACE}     0 4   1
  9 FAIL     {INSERT OR IGNORE}      0 3   1
 10 ABORT    {INSERT OR REPLACE}     0 4   1
 11 ROLLBACK {INSERT OR IGNORE }     0 3   1
} {
  do_test conflict-4.$i {
    if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"}
    set r0 [catch {execsql [subst {
      DROP TABLE t1;
      CREATE TABLE t1(a,b,c,UNIQUE(a,b) $conf1);
      DELETE FROM t2;
      INSERT INTO t1 VALUES(1,2,3);
      BEGIN;
      INSERT INTO t2 VALUES(1); 
      $cmd INTO t1 VALUES(1,2,4);
    }]} r1]
    catch {execsql {COMMIT}}
    if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]}
    set r2 [execsql {SELECT x FROM t2}]
    list $r0 $r1 $r2
  } [list $t0 $t1 $t2]
}

do_test conflict-5.0 {
  execsql {
    DROP TABLE t2;
    CREATE TABLE t2(x);
    SELECT x FROM t2;
  }
} {}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   conf1  The conflict resolution algorithm on the NOT NULL constraint
#   cmd    An INSERT or REPLACE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "c" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t2
#
foreach {i conf1 cmd t0 t1 t2} {
  1 {}       INSERT                  1 {}  1
  2 REPLACE  INSERT                  0 5   1
  3 IGNORE   INSERT                  0 {}  1
  4 FAIL     INSERT                  1 {}  1
  5 ABORT    INSERT                  1 {}  1
  6 ROLLBACK INSERT                  1 {}  {}
  7 REPLACE  {INSERT OR IGNORE}      0 {}  1
  8 IGNORE   {INSERT OR REPLACE}     0 5   1
  9 FAIL     {INSERT OR IGNORE}      0 {}  1
 10 ABORT    {INSERT OR REPLACE}     0 5   1
 11 ROLLBACK {INSERT OR IGNORE}      0 {}  1
 12 {}       {INSERT OR IGNORE}      0 {}  1
 13 {}       {INSERT OR REPLACE}     0 5   1
 14 {}       {INSERT OR FAIL}        1 {}  1
 15 {}       {INSERT OR ABORT}       1 {}  1
 16 {}       {INSERT OR ROLLBACK}    1 {}  {}
} {
  if {$t0} {set t1 {t1.c may not be NULL}}
  do_test conflict-5.$i {
    if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"}
    set r0 [catch {execsql [subst {
      DROP TABLE t1;
      CREATE TABLE t1(a,b,c NOT NULL $conf1 DEFAULT 5);
      DELETE FROM t2;
      BEGIN;
      INSERT INTO t2 VALUES(1); 
      $cmd INTO t1 VALUES(1,2,NULL);
    }]} r1]
    catch {execsql {COMMIT}}
    if {!$r0} {set r1 [execsql {SELECT c FROM t1}]}
    set r2 [execsql {SELECT x FROM t2}]
    list $r0 $r1 $r2
  } [list $t0 $t1 $t2]
}

do_test conflict-6.0 {
  execsql {
    DROP TABLE t2;
    CREATE TABLE t2(a,b,c);
    INSERT INTO t2 VALUES(1,2,1);
    INSERT INTO t2 VALUES(2,3,2);
    INSERT INTO t2 VALUES(3,4,1);
    INSERT INTO t2 VALUES(4,5,4);
    SELECT c FROM t2 ORDER BY b;
    CREATE TABLE t3(x);
    INSERT INTO t3 VALUES(1);
  }
} {1 2 1 4}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   conf1  The conflict resolution algorithm on the UNIQUE constraint
#   cmd    An UPDATE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "b" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t3
#   t3     Number of temporary files for tables
#   t4     Number of temporary files for statement journals
#
# Update: Since temporary table files are now opened lazily, and none
# of the following tests use large quantities of data, t3 is always 0.
#
foreach {i conf1 cmd t0 t1 t2 t3 t4} {
  1 {}       UPDATE                  1 {6 7 8 9}  1 0 1
  2 REPLACE  UPDATE                  0 {7 6 9}    1 0 0
  3 IGNORE   UPDATE                  0 {6 7 3 9}  1 0 0
  4 FAIL     UPDATE                  1 {6 7 3 4}  1 0 0
  5 ABORT    UPDATE                  1 {1 2 3 4}  1 0 1
  6 ROLLBACK UPDATE                  1 {1 2 3 4}  0 0 0
  7 REPLACE  {UPDATE OR IGNORE}      0 {6 7 3 9}  1 0 0
  8 IGNORE   {UPDATE OR REPLACE}     0 {7 6 9}    1 0 0
  9 FAIL     {UPDATE OR IGNORE}      0 {6 7 3 9}  1 0 0
 10 ABORT    {UPDATE OR REPLACE}     0 {7 6 9}    1 0 0
 11 ROLLBACK {UPDATE OR IGNORE}      0 {6 7 3 9}  1 0 0
 12 {}       {UPDATE OR IGNORE}      0 {6 7 3 9}  1 0 0
 13 {}       {UPDATE OR REPLACE}     0 {7 6 9}    1 0 0
 14 {}       {UPDATE OR FAIL}        1 {6 7 3 4}  1 0 0
 15 {}       {UPDATE OR ABORT}       1 {1 2 3 4}  1 0 1
 16 {}       {UPDATE OR ROLLBACK}    1 {1 2 3 4}  0 0 0
} {
  if {$t0} {set t1 {column a is not unique}}
  if {[info exists TEMP_STORE] && $TEMP_STORE>=2} {
    set t3 0
  } else {
    set t3 [expr {$t3+$t4}]
  }
  do_test conflict-6.$i {
    db close
    sqlite3 db test.db 
    if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"}
    execsql {pragma temp_store=file}
    set ::sqlite_opentemp_count 0
    set r0 [catch {execsql [subst {
      DROP TABLE t1;
      CREATE TABLE t1(a,b,c, UNIQUE(a) $conf1);
      INSERT INTO t1 SELECT * FROM t2;
      UPDATE t3 SET x=0;
      BEGIN;
      $cmd t3 SET x=1;
      $cmd t1 SET b=b*2;
      $cmd t1 SET a=c+5;
    }]} r1]
    catch {execsql {COMMIT}}
    if {!$r0} {set r1 [execsql {SELECT a FROM t1 ORDER BY b}]}
    set r2 [execsql {SELECT x FROM t3}]
    list $r0 $r1 $r2 $::sqlite_opentemp_count
  } [list $t0 $t1 $t2 $t3]
}

# Test to make sure a lot of IGNOREs don't cause a stack overflow
#
do_test conflict-7.1 {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    DROP TABLE t3;
    CREATE TABLE t1(a unique, b);
  }
  for {set i 1} {$i<=50} {incr i} {
    execsql "INSERT into t1 values($i,[expr {$i+1}]);"
  }
  execsql {
    SELECT count(*), min(a), max(b) FROM t1;
  }
} {50 1 51}
do_test conflict-7.2 {
  execsql {
    PRAGMA count_changes=on;
    UPDATE OR IGNORE t1 SET a=1000;
  }
} {1}
do_test conflict-7.2.1 {
  db changes
} {1}
do_test conflict-7.3 {
  execsql {
    SELECT b FROM t1 WHERE a=1000;
  }
} {2}
do_test conflict-7.4 {
  execsql {
    SELECT count(*) FROM t1;
  }
} {50}
do_test conflict-7.5 {
  execsql {
    PRAGMA count_changes=on;
    UPDATE OR REPLACE t1 SET a=1001;
  }
} {50}
do_test conflict-7.5.1 {
  db changes
} {50}
do_test conflict-7.6 {
  execsql {
    SELECT b FROM t1 WHERE a=1001;
  }
} {51}
do_test conflict-7.7 {
  execsql {
    SELECT count(*) FROM t1;
  }
} {1}

# Update for version 3: A SELECT statement no longer resets the change
# counter (Test result changes from 0 to 50).
do_test conflict-7.7.1 {
  db changes
} {50}

# Make sure the row count is right for rows that are ignored on
# an insert.
#
do_test conflict-8.1 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2);
  }
  execsql {
    INSERT OR IGNORE INTO t1 VALUES(2,3);
  }
} {1}
do_test conflict-8.1.1 {
  db changes
} {1}
do_test conflict-8.2 {
  execsql {
    INSERT OR IGNORE INTO t1 VALUES(2,4);
  }
} {0}
do_test conflict-8.2.1 {
  db changes
} {0}
do_test conflict-8.3 {
  execsql {
    INSERT OR REPLACE INTO t1 VALUES(2,4);
  }
} {1}
do_test conflict-8.3.1 {
  db changes
} {1}
do_test conflict-8.4 {
  execsql {
    INSERT OR IGNORE INTO t1 SELECT * FROM t1;
  }
} {0}
do_test conflict-8.4.1 {
  db changes
} {0}
do_test conflict-8.5 {
  execsql {
    INSERT OR IGNORE INTO t1 SELECT a+2,b+2 FROM t1;
  }
} {2}
do_test conflict-8.5.1 {
  db changes
} {2}
do_test conflict-8.6 {
  execsql {
    INSERT OR IGNORE INTO t1 SELECT a+3,b+3 FROM t1;
  }
} {3}
do_test conflict-8.6.1 {
  db changes
} {3}

integrity_check conflict-8.99

do_test conflict-9.1 {
  execsql {
    PRAGMA count_changes=0;
    CREATE TABLE t2(
      a INTEGER UNIQUE ON CONFLICT IGNORE,
      b INTEGER UNIQUE ON CONFLICT FAIL,
      c INTEGER UNIQUE ON CONFLICT REPLACE,
      d INTEGER UNIQUE ON CONFLICT ABORT,
      e INTEGER UNIQUE ON CONFLICT ROLLBACK
    );
    CREATE TABLE t3(x);
    INSERT INTO t3 VALUES(1);
    SELECT * FROM t3;
  }
} {1}
do_test conflict-9.2 {
  catchsql {
    INSERT INTO t2 VALUES(1,1,1,1,1);
    INSERT INTO t2 VALUES(2,2,2,2,2);
    SELECT * FROM t2;
  }
} {0 {1 1 1 1 1 2 2 2 2 2}}
do_test conflict-9.3 {
  catchsql {
    INSERT INTO t2 VALUES(1,3,3,3,3);
    SELECT * FROM t2;
  }
} {0 {1 1 1 1 1 2 2 2 2 2}}
do_test conflict-9.4 {
  catchsql {
    UPDATE t2 SET a=a+1 WHERE a=1;
    SELECT * FROM t2;
  }
} {0 {1 1 1 1 1 2 2 2 2 2}}
do_test conflict-9.5 {
  catchsql {
    INSERT INTO t2 VALUES(3,1,3,3,3);
    SELECT * FROM t2;
  }
} {1 {column b is not unique}}
do_test conflict-9.6 {
  catchsql {
    UPDATE t2 SET b=b+1 WHERE b=1;
    SELECT * FROM t2;
  }
} {1 {column b is not unique}}
do_test conflict-9.7 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    INSERT INTO t2 VALUES(3,1,3,3,3);
    SELECT * FROM t2;
  }
} {1 {column b is not unique}}
do_test conflict-9.8 {
  execsql {COMMIT}
  execsql {SELECT * FROM t3}
} {2}
do_test conflict-9.9 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    UPDATE t2 SET b=b+1 WHERE b=1;
    SELECT * FROM t2;
  }
} {1 {column b is not unique}}
do_test conflict-9.10 {
  execsql {COMMIT}
  execsql {SELECT * FROM t3}
} {3}
do_test conflict-9.11 {
  catchsql {
    INSERT INTO t2 VALUES(3,3,3,1,3);
    SELECT * FROM t2;
  }
} {1 {column d is not unique}}
do_test conflict-9.12 {
  catchsql {
    UPDATE t2 SET d=d+1 WHERE d=1;
    SELECT * FROM t2;
  }
} {1 {column d is not unique}}
do_test conflict-9.13 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    INSERT INTO t2 VALUES(3,3,3,1,3);
    SELECT * FROM t2;
  }
} {1 {column d is not unique}}
do_test conflict-9.14 {
  execsql {COMMIT}
  execsql {SELECT * FROM t3}
} {4}
do_test conflict-9.15 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    UPDATE t2 SET d=d+1 WHERE d=1;
    SELECT * FROM t2;
  }
} {1 {column d is not unique}}
do_test conflict-9.16 {
  execsql {COMMIT}
  execsql {SELECT * FROM t3}
} {5}
do_test conflict-9.17 {
  catchsql {
    INSERT INTO t2 VALUES(3,3,3,3,1);
    SELECT * FROM t2;
  }
} {1 {column e is not unique}}
do_test conflict-9.18 {
  catchsql {
    UPDATE t2 SET e=e+1 WHERE e=1;
    SELECT * FROM t2;
  }
} {1 {column e is not unique}}
do_test conflict-9.19 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    INSERT INTO t2 VALUES(3,3,3,3,1);
    SELECT * FROM t2;
  }
} {1 {column e is not unique}}
do_test conflict-9.20 {
  catch {execsql {COMMIT}}
  execsql {SELECT * FROM t3}
} {5}
do_test conflict-9.21 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    UPDATE t2 SET e=e+1 WHERE e=1;
    SELECT * FROM t2;
  }
} {1 {column e is not unique}}
do_test conflict-9.22 {
  catch {execsql {COMMIT}}
  execsql {SELECT * FROM t3}
} {5}
do_test conflict-9.23 {
  catchsql {
    INSERT INTO t2 VALUES(3,3,1,3,3);
    SELECT * FROM t2;
  }
} {0 {2 2 2 2 2 3 3 1 3 3}}
do_test conflict-9.24 {
  catchsql {
    UPDATE t2 SET c=c-1 WHERE c=2;
    SELECT * FROM t2;
  }
} {0 {2 2 1 2 2}}
do_test conflict-9.25 {
  catchsql {
    BEGIN;
    UPDATE t3 SET x=x+1;
    INSERT INTO t2 VALUES(3,3,1,3,3);
    SELECT * FROM t2;
  }
} {0 {3 3 1 3 3}}
do_test conflict-9.26 {
  catch {execsql {COMMIT}}
  execsql {SELECT * FROM t3}
} {6}

do_test conflict-10.1 {
  catchsql {
    DELETE FROM t1;
    BEGIN;
    INSERT OR ROLLBACK INTO t1 VALUES(1,2);
    INSERT OR ROLLBACK INTO t1 VALUES(1,3);
    COMMIT;
  }
  execsql {SELECT * FROM t1}
} {}
do_test conflict-10.2 {
  catchsql {
    CREATE TABLE t4(x);
    CREATE UNIQUE INDEX t4x ON t4(x);
    BEGIN;
    INSERT OR ROLLBACK INTO t4 VALUES(1);
    INSERT OR ROLLBACK INTO t4 VALUES(1);
    COMMIT;
  }
  execsql {SELECT * FROM t4}
} {}

# Ticket #1171.  Make sure statement rollbacks do not
# damage the database.
#
do_test conflict-11.1 {
  execsql {
    -- Create a database object (pages 2, 3 of the file)
    BEGIN;
      CREATE TABLE abc(a UNIQUE, b, c);
      INSERT INTO abc VALUES(1, 2, 3);
      INSERT INTO abc VALUES(4, 5, 6);
      INSERT INTO abc VALUES(7, 8, 9);
    COMMIT;
  }

  
  # Set a small cache size so that changes will spill into
  # the database file.  
  execsql {
    PRAGMA cache_size = 10;
  }
  
  # Make lots of changes.  Because of the small cache, some
  # (most?) of these changes will spill into the disk file.
  # In other words, some of the changes will not be held in
  # cache.
  #
  execsql {
    BEGIN;
      -- Make sure the pager is in EXCLUSIVE state.
      CREATE TABLE def(d, e, f);
      INSERT INTO def VALUES
          ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz');
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      DELETE FROM abc WHERE a = 4;
  }

  # Execute a statement that does a statement rollback due to
  # a constraint failure.
  #
  catchsql {
    INSERT INTO abc SELECT 10, 20, 30 FROM def;
  }

  # Rollback the database.  Verify that the state of the ABC table
  # is unchanged from the beginning of the transaction.  In other words,
  # make sure the DELETE on table ABC that occurred within the transaction
  # had no effect.
  #
  execsql {
    ROLLBACK;
    SELECT * FROM abc;
  }
} {1 2 3 4 5 6 7 8 9}
integrity_check conflict-11.2

# Repeat test conflict-11.1 but this time commit.
#
do_test conflict-11.3 {
  execsql {
    BEGIN;
      -- Make sure the pager is in EXCLUSIVE state.
      UPDATE abc SET a=a+1;
      CREATE TABLE def(d, e, f);
      INSERT INTO def VALUES
          ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz');
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      DELETE FROM abc WHERE a = 4;
  }
  catchsql {
    INSERT INTO abc SELECT 10, 20, 30 FROM def;
  }
  execsql {
    ROLLBACK;
    SELECT * FROM abc;
  }
} {1 2 3 4 5 6 7 8 9}
# Repeat test conflict-11.1 but this time commit.
#
do_test conflict-11.5 {
  execsql {
    BEGIN;
      -- Make sure the pager is in EXCLUSIVE state.
      CREATE TABLE def(d, e, f);
      INSERT INTO def VALUES
          ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz');
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      INSERT INTO def SELECT * FROM def;
      DELETE FROM abc WHERE a = 4;
  }
  catchsql {
    INSERT INTO abc SELECT 10, 20, 30 FROM def;
  }
  execsql {
    COMMIT;
    SELECT * FROM abc;
  }
} {1 2 3 7 8 9}
integrity_check conflict-11.6

# Make sure UPDATE OR REPLACE works on tables that have only
# an INTEGER PRIMARY KEY.
#
do_test conflict-12.1 {
  execsql {
    CREATE TABLE t5(a INTEGER PRIMARY KEY, b text);
    INSERT INTO t5 VALUES(1,'one');
    INSERT INTO t5 VALUES(2,'two');
    SELECT * FROM t5
  }
} {1 one 2 two}
do_test conflict-12.2 {
  execsql {
    UPDATE OR IGNORE t5 SET a=a+1 WHERE a=1;
    SELECT * FROM t5;
  }
} {1 one 2 two}
do_test conflict-12.3 {
  catchsql {
    UPDATE t5 SET a=a+1 WHERE a=1;
  }
} {1 {PRIMARY KEY must be unique}}
do_test conflict-12.4 {
  execsql {
    UPDATE OR REPLACE t5 SET a=a+1 WHERE a=1;
    SELECT * FROM t5;
  }
} {2 one}


finish_test

Added test/corrupt.test.









































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# 2004 August 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.
#
# $Id: corrupt.test,v 1.12 2009/07/13 09:41:45 danielk1977 Exp $

catch {file delete -force test.db test.db-journal test.bu}

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Construct a large database for testing.
#
do_test corrupt-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(randstr(100,100));
    INSERT INTO t1 VALUES(randstr(90,90));
    INSERT INTO t1 VALUES(randstr(80,80));
    INSERT INTO t1 SELECT x || randstr(5,5) FROM t1;
    INSERT INTO t1 SELECT x || randstr(6,6) FROM t1;
    INSERT INTO t1 SELECT x || randstr(7,7) FROM t1;
    INSERT INTO t1 SELECT x || randstr(8,8) FROM t1;
    INSERT INTO t1 VALUES(randstr(3000,3000));
    INSERT INTO t1 SELECT x || randstr(9,9) FROM t1;
    INSERT INTO t1 SELECT x || randstr(10,10) FROM t1;
    INSERT INTO t1 SELECT x || randstr(11,11) FROM t1;
    INSERT INTO t1 SELECT x || randstr(12,12) FROM t1;
    CREATE INDEX t1i1 ON t1(x);
    CREATE TABLE t2 AS SELECT * FROM t1;
    DELETE FROM t2 WHERE rowid%5!=0;
    COMMIT;
  }
} {}
integrity_check corrupt-1.2

# Copy file $from into $to
#
proc copy_file {from to} {
  set f [open $from]
  fconfigure $f -translation binary
  set t [open $to w]
  fconfigure $t -translation binary
  puts -nonewline $t [read $f [file size $from]]
  close $t
  close $f
}

# Setup for the tests.  Make a backup copy of the good database in test.bu.
# Create a string of garbage data that is 256 bytes long.
#
copy_file test.db test.bu
set fsize [file size test.db]
set junk "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while {[string length $junk]<256} {append junk $junk}
set junk [string range $junk 0 255]

# Go through the database and write garbage data into each 256 segment
# of the file.  Then do various operations on the file to make sure that
# the database engine can recover gracefully from the corruption.
#
for {set i [expr {1*256}]} {$i<$fsize-256} {incr i 256} {
  set tn [expr {$i/256}]
  db close
  copy_file test.bu test.db
  set fd [open test.db r+]
  fconfigure $fd -translation binary
  seek $fd $i
  puts -nonewline $fd $junk
  close $fd
  do_test corrupt-2.$tn.1 {
    sqlite3 db test.db
    catchsql {SELECT count(*) FROM sqlite_master}
    set x {}
  } {}
  do_test corrupt-2.$tn.2 {
    catchsql {SELECT count(*) FROM t1}
    set x {}
  } {}
  do_test corrupt-2.$tn.3 {
    catchsql {SELECT count(*) FROM t1 WHERE x>'abcdef'}
    set x {}
  } {}
  do_test corrupt-2.$tn.4 {
    catchsql {SELECT count(*) FROM t2}
    set x {}
  } {}
  do_test corrupt-2.$tn.5 {
    catchsql {CREATE TABLE t3 AS SELECT * FROM t1}
    set x {}
  } {}
  do_test corrupt-2.$tn.6 {
    catchsql {DROP TABLE t1}
    set x {}
  } {}
  do_test corrupt-2.$tn.7 {
    catchsql {PRAGMA integrity_check}
    set x {}
  } {}

  # Check that no page references were leaked.
  do_test corrupt-2.$tn.8 {
    set bt [btree_from_db db]
    db_enter db
    array set stats [btree_pager_stats $bt]
    db_leave db
    set stats(ref)
  } {0}
}  

#------------------------------------------------------------------------
# For these tests, swap the rootpage entries of t1 (a table) and t1i1 (an
# index on t1) in sqlite_master. Then perform a few different queries
# and make sure this is detected as corruption.
#
do_test corrupt-3.1 {
  db close
  copy_file test.bu test.db
  sqlite3 db test.db
  list
} {}
do_test corrupt-3.2 {
  set t1_r [execsql {SELECT rootpage FROM sqlite_master WHERE name = 't1i1'}]
  set t1i1_r [execsql {SELECT rootpage FROM sqlite_master WHERE name = 't1'}]
  set cookie [expr [execsql {PRAGMA schema_version}] + 1]
  execsql "
    PRAGMA writable_schema = 1;
    UPDATE sqlite_master SET rootpage = $t1_r WHERE name = 't1';
    UPDATE sqlite_master SET rootpage = $t1i1_r WHERE name = 't1i1';
    PRAGMA writable_schema = 0;
    PRAGMA schema_version = $cookie;
  "
} {}

# This one tests the case caught by code in checkin [2313].
do_test corrupt-3.3 {
  db close
  sqlite3 db test.db
  catchsql {
    INSERT INTO t1 VALUES('abc');
  }
} {1 {database disk image is malformed}}
do_test corrupt-3.4 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM t1;
  }
} {1 {database disk image is malformed}}
do_test corrupt-3.5 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM t1 WHERE oid = 10;
  }
} {1 {database disk image is malformed}}
do_test corrupt-3.6 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM t1 WHERE x = 'abcde';
  }
} {1 {database disk image is malformed}}

do_test corrupt-4.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql {
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT);
  }
  for {set i 0} {$i < 10} {incr i} {
    set text [string repeat $i 220]
    execsql { INSERT INTO t1 VALUES($i, $text) }
  }
  execsql { CREATE INDEX i1 ON t1(b) }
} {}
do_test corrupt-4.2 {
  set iRoot [db one {SELECT rootpage FROM sqlite_master WHERE name = 'i1'}]
  set iOffset [hexio_get_int [hexio_read test.db [expr 12+($iRoot-1)*1024] 2]]
  set data [hexio_render_int32 [expr $iRoot - 1]]
  hexio_write test.db [expr ($iRoot-1)*1024 + $iOffset] $data
  db close
  sqlite3 db test.db

  # The following DELETE statement attempts to delete a cell stored on the
  # root page of index i1. After this cell is deleted it must be replaced
  # by a cell retrieved from the child page (a leaf) of the deleted cell.
  # This will fail, as the block modified the database image so that the
  # child page of the deleted cell is from a table (intkey) b-tree, not an
  # index b-tree as expected. At one point this was causing an assert()
  # to fail.
  catchsql { DELETE FROM t1 WHERE rowid = 3 }
} {1 {database disk image is malformed}}

do_test corrupt-5.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db

  execsql { PRAGMA page_size = 1024 }
  set ct "CREATE TABLE t1(c0 "
  set i 0
  while {[string length $ct] < 950} { append ct ", c[incr i]" }
  append ct ")"
  execsql $ct
} {}

do_test corrupt-5.2 {
  db close
  hexio_write test.db 108 00000000 
  sqlite3 db test.db
  catchsql { SELECT * FROM sqlite_master }
} {1 {database disk image is malformed}}

# At one point, the specific corruption caused by this test case was
# causing a buffer overwrite. Although a crash was never demonstrated,
# running this testcase under valgrind revealed the problem.
do_test corrupt-6.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql { 
    PRAGMA page_size = 1024; CREATE TABLE t1(x);
  }

  # The root page of t1 is 1024 bytes in size. The header is 8 bytes, and
  # each of the cells inserted by the following INSERT statements consume
  # 16 bytes (including the 2 byte cell-offset array entry). So the page
  # can contain up to 63 cells.
  for {set i 0} {$i < 63} {incr i} {
    execsql { INSERT INTO t1 VALUES( randomblob(10) ) }
  }

  # Free the cell stored right at the end of the page (at offset pgsz-14).
  execsql { DELETE FROM t1 WHERE rowid=1 }
  set rootpage [db one {SELECT rootpage FROM sqlite_master WHERE name = 't1'}]
  db close

  set offset [expr ($rootpage * 1024)-14+2]
  hexio_write test.db $offset 00FF
  sqlite3 db test.db 

  catchsql { INSERT INTO t1 VALUES( randomblob(10) ) }
} {1 {database disk image is malformed}}

finish_test

Added test/corrupt2.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# 2004 August 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.
#
# $Id: corrupt2.test,v 1.20 2009/04/06 17:50:03 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# The following tests - corrupt2-1.* - create some databases corrupted in
# specific ways and ensure that SQLite detects them as corrupt.
#
do_test corrupt2-1.1 {
  execsql {
    PRAGMA auto_vacuum=0;
    PRAGMA page_size=1024;
    CREATE TABLE abc(a, b, c);
  }
} {}

do_test corrupt2-1.2 {

  # Corrupt the 16 byte magic string at the start of the file
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db RDWR]
  seek $f 8 start
  puts $f blah
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {file is encrypted or is not a database}}

do_test corrupt2-1.3 {
  db2 close

  # Corrupt the page-size (bytes 16 and 17 of page 1).
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db RDWR]
  fconfigure $f -encoding binary
  seek $f 16 start
  puts -nonewline $f "\x00\xFF"
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {file is encrypted or is not a database}}

do_test corrupt2-1.4 {
  db2 close

  # Corrupt the free-block list on page 1.
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db RDWR]
  fconfigure $f -encoding binary
  seek $f 101 start
  puts -nonewline $f "\xFF\xFF"
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {database disk image is malformed}}

do_test corrupt2-1.5 {
  db2 close

  # Corrupt the free-block list on page 1.
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db RDWR]
  fconfigure $f -encoding binary
  seek $f 101 start
  puts -nonewline $f "\x00\xC8"
  seek $f 200 start
  puts -nonewline $f "\x00\x00"
  puts -nonewline $f "\x10\x00"
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {database disk image is malformed}}
db2 close

# Corrupt a database by having 2 indices of the same name:
do_test corrupt2-2.1 {

  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db

  sqlite3 db2 corrupt.db 
  execsql {
    CREATE INDEX a1 ON abc(a);
    CREATE INDEX a2 ON abc(b);
    PRAGMA writable_schema = 1;
    UPDATE sqlite_master 
      SET name = 'a3', sql = 'CREATE INDEX a3' || substr(sql, 16, 10000)
      WHERE type = 'index';
    PRAGMA writable_schema = 0;
  } db2

  db2 close
  sqlite3 db2 corrupt.db 
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {malformed database schema (a3) - index a3 already exists}}

db2 close

do_test corrupt2-3.1 {
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  sqlite3 db2 corrupt.db 

  execsql {
    PRAGMA auto_vacuum = 1;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(a, b, c);
    INSERT INTO t2 VALUES(randomblob(100), randomblob(100), randomblob(100));
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t2;
  } db2

  db2 close

  # On the root page of table t2 (page 4), set one of the child page-numbers
  # to 0. This corruption will be detected when SQLite attempts to update
  # the pointer-map after moving the content of page 4 to page 3 as part
  # of the DROP TABLE operation below.
  #
  set fd [open corrupt.db r+]
  fconfigure $fd -encoding binary -translation binary
  seek $fd [expr 1024*3 + 12]
  set zCelloffset [read $fd 2]
  binary scan $zCelloffset S iCelloffset
  seek $fd [expr 1024*3 + $iCelloffset]
  puts -nonewline $fd "\00\00\00\00" 
  close $fd

  sqlite3 db2 corrupt.db 
  catchsql {
    DROP TABLE t1;
  } db2
} {1 {database disk image is malformed}}

do_test corrupt2-4.1 {
  catchsql {
    SELECT * FROM t2;
  } db2
} {1 {database disk image is malformed}}

db2 close

unset -nocomplain result
do_test corrupt2-5.1 {
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  sqlite3 db2 corrupt.db 

  execsql {
    PRAGMA auto_vacuum = 0;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(a, b, c);
    INSERT INTO t2 VALUES(randomblob(100), randomblob(100), randomblob(100));
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t2;
    INSERT INTO t1 SELECT * FROM t2;
  } db2

  db2 close

  # This block links a page from table t2 into the t1 table structure.
  #
  set fd [open corrupt.db r+]
  fconfigure $fd -encoding binary -translation binary
  seek $fd [expr 1024 + 12]
  set zCelloffset [read $fd 2]
  binary scan $zCelloffset S iCelloffset
  seek $fd [expr 1024 + $iCelloffset]
  set zChildPage [read $fd 4]
  seek $fd [expr 2*1024 + 12]
  set zCelloffset [read $fd 2]
  binary scan $zCelloffset S iCelloffset
  seek $fd [expr 2*1024 + $iCelloffset]
  puts -nonewline $fd $zChildPage
  close $fd

  sqlite3 db2 corrupt.db 
  db2 eval {SELECT rowid FROM t1} {
    set result [db2 eval {pragma integrity_check}]
    break
  }
  set result
} {{*** in database main ***
On tree page 2 cell 0: 2nd reference to page 10
On tree page 2 cell 1: Child page depth differs
Page 4 is never used}}

db2 close

proc corruption_test {args} {
  set A(-corrupt) {}
  set A(-sqlprep) {}
  set A(-tclprep) {}
  array set A $args

  catch {db close}
  file delete -force corrupt.db
  file delete -force corrupt.db-journal

  sqlite3 db corrupt.db 
  eval $A(-tclprep)
  db eval $A(-sqlprep)
  db close

  eval $A(-corrupt)

  sqlite3 db corrupt.db
  eval $A(-test)
}

ifcapable autovacuum {
  # The tests within this block - corrupt2-6.* - aim to test corruption
  # detection within an incremental-vacuum. When an incremental-vacuum
  # step is executed, the last non-free page of the database file is 
  # moved into a free space in the body of the file. After doing so,
  # the page reference in the parent page must be updated to refer
  # to the new location. These tests test the outcome of corrupting
  # that page reference before performing the incremental vacuum.
  #

  # The last page in the database page is the second page 
  # in an overflow chain.
  #
  corruption_test -sqlprep {
    PRAGMA auto_vacuum = incremental;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, randomblob(2500));
    INSERT INTO t1 VALUES(2, randomblob(2500));
    DELETE FROM t1 WHERE a = 1;
  } -corrupt {
    hexio_write corrupt.db [expr 1024*5] 00000008
  } -test {
    do_test corrupt2-6.1 {
      catchsql { pragma incremental_vacuum = 1 }
    } {1 {database disk image is malformed}}
  }

  # The last page in the database page is a non-root b-tree page.
  #
  corruption_test -sqlprep {
    PRAGMA auto_vacuum = incremental;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, randomblob(2500));
    INSERT INTO t1 VALUES(2, randomblob(50));
    INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
    INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
    INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
    INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
    DELETE FROM t1 WHERE a = 1;
  } -corrupt {
    hexio_write corrupt.db [expr 1024*2 + 8] 00000009
  } -test {
    do_test corrupt2-6.2 {
      catchsql { pragma incremental_vacuum = 1 }
    } {1 {database disk image is malformed}}
  }

  # Set up a pointer-map entry so that the last page of the database
  # file appears to be a b-tree root page. This should be detected
  # as corruption.
  #
  corruption_test -sqlprep {
    PRAGMA auto_vacuum = incremental;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, randomblob(2500));
    INSERT INTO t1 VALUES(2, randomblob(2500));
    INSERT INTO t1 VALUES(3, randomblob(2500));
    DELETE FROM t1 WHERE a = 1;
  } -corrupt {
    set nPage [expr [file size corrupt.db] / 1024]
    hexio_write corrupt.db [expr 1024 + ($nPage-3)*5] 010000000
  } -test {
    do_test corrupt2-6.3 {
      catchsql { pragma incremental_vacuum = 1 }
    } {1 {database disk image is malformed}}
  }

  corruption_test -sqlprep {
    PRAGMA auto_vacuum = 1;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, randomblob(2500));
    DELETE FROM t1 WHERE a = 1;
  } -corrupt {
    set nAppend [expr 1024*207 - [file size corrupt.db]]
    set fd [open corrupt.db r+]
    seek $fd 0 end
    puts -nonewline $fd [string repeat x $nAppend]
    close $fd
  } -test {
    do_test corrupt2-6.4 {
      catchsql { 
        BEGIN EXCLUSIVE;
        COMMIT;
      }
    } {1 {database disk image is malformed}}
  }
}


set sqlprep {
  PRAGMA auto_vacuum = 0;
  PRAGMA page_size = 1024;
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
  CREATE INDEX i1 ON t1(b);
  INSERT INTO t1 VALUES(1, randomblob(50));
  INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
  INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
  INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
  INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
  INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
  INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1;
}

corruption_test -sqlprep $sqlprep -corrupt {
  # Set the page-flags of one of the leaf pages of the index B-Tree to
  # 0x0D (interpreted by SQLite as "leaf page of a table B-Tree").
  #
  set fd [open corrupt.db r+]
  fconfigure $fd -translation binary -encoding binary
  seek $fd [expr 1024*2 + 8] 
  set zRightChild [read $fd 4]
  binary scan $zRightChild I iRightChild
  seek $fd [expr 1024*($iRightChild-1)]
  puts -nonewline $fd "\x0D"
  close $fd
} -test {
  do_test corrupt2-7.1 {
    catchsql { SELECT b FROM t1 ORDER BY b ASC }
  } {1 {database disk image is malformed}}
}

corruption_test -sqlprep $sqlprep -corrupt {
  # Mess up the page-header of one of the leaf pages of the index B-Tree.
  # The corruption is detected as part of an OP_Prev opcode.
  #
  set fd [open corrupt.db r+]
  fconfigure $fd -translation binary -encoding binary
  seek $fd [expr 1024*2 + 12] 
  set zCellOffset [read $fd 2]
  binary scan $zCellOffset S iCellOffset
  seek $fd [expr 1024*2 + $iCellOffset]
  set zChild [read $fd 4]
  binary scan $zChild I iChild
  seek $fd [expr 1024*($iChild-1)+3]
  puts -nonewline $fd "\xFFFF"
  close $fd
} -test {
  do_test corrupt2-7.1 {
    catchsql { SELECT b FROM t1 ORDER BY b DESC }
  } {1 {database disk image is malformed}}
}

corruption_test -sqlprep $sqlprep -corrupt {
  # Set the page-flags of one of the leaf pages of the table B-Tree to
  # 0x0A (interpreted by SQLite as "leaf page of an index B-Tree").
  #
  set fd [open corrupt.db r+]
  fconfigure $fd -translation binary -encoding binary
  seek $fd [expr 1024*1 + 8] 
  set zRightChild [read $fd 4]
  binary scan $zRightChild I iRightChild
  seek $fd [expr 1024*($iRightChild-1)]
  puts -nonewline $fd "\x0A"
  close $fd
} -test {
  do_test corrupt2-8.1 {
    catchsql { SELECT * FROM t1 WHERE rowid=1000 }
  } {1 {database disk image is malformed}}
}

corruption_test -sqlprep {
  CREATE TABLE t1(a, b, c); CREATE TABLE t8(a, b, c); CREATE TABLE tE(a, b, c);
  CREATE TABLE t2(a, b, c); CREATE TABLE t9(a, b, c); CREATE TABLE tF(a, b, c);
  CREATE TABLE t3(a, b, c); CREATE TABLE tA(a, b, c); CREATE TABLE tG(a, b, c);
  CREATE TABLE t4(a, b, c); CREATE TABLE tB(a, b, c); CREATE TABLE tH(a, b, c);
  CREATE TABLE t5(a, b, c); CREATE TABLE tC(a, b, c); CREATE TABLE tI(a, b, c);
  CREATE TABLE t6(a, b, c); CREATE TABLE tD(a, b, c); CREATE TABLE tJ(a, b, c);
  CREATE TABLE x1(a, b, c); CREATE TABLE x8(a, b, c); CREATE TABLE xE(a, b, c);
  CREATE TABLE x2(a, b, c); CREATE TABLE x9(a, b, c); CREATE TABLE xF(a, b, c);
  CREATE TABLE x3(a, b, c); CREATE TABLE xA(a, b, c); CREATE TABLE xG(a, b, c);
  CREATE TABLE x4(a, b, c); CREATE TABLE xB(a, b, c); CREATE TABLE xH(a, b, c);
  CREATE TABLE x5(a, b, c); CREATE TABLE xC(a, b, c); CREATE TABLE xI(a, b, c);
  CREATE TABLE x6(a, b, c); CREATE TABLE xD(a, b, c); CREATE TABLE xJ(a, b, c);
} -corrupt {
  set fd [open corrupt.db r+]
  fconfigure $fd -translation binary -encoding binary
  seek $fd 108
  set zRightChild [read $fd 4]
  binary scan $zRightChild I iRightChild
  seek $fd [expr 1024*($iRightChild-1)+3]
  puts -nonewline $fd "\x00\x00"
  close $fd
} -test {
  do_test corrupt2-9.1 {
    catchsql { SELECT sql FROM sqlite_master }
  } {1 {database disk image is malformed}}
}

corruption_test -sqlprep {
  CREATE TABLE t1(a, b, c);
  CREATE TABLE t2(a, b, c);
  PRAGMA writable_schema = 1;
  UPDATE sqlite_master SET rootpage = NULL WHERE name = 't2';
} -test {
  do_test corrupt2-10.1 {
    catchsql { SELECT * FROM t2 }
  } {1 {malformed database schema (t2)}}
  do_test corrupt2-10.2 {
    sqlite3_errcode db
  } {SQLITE_CORRUPT}
}

corruption_test -sqlprep {
  PRAGMA auto_vacuum = incremental;
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
  CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
  INSERT INTO t1 VALUES(1, randstr(100,100));
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t2 SELECT * FROM t1;
  DELETE FROM t1;
} -corrupt {
  set offset [expr [file size corrupt.db] - 1024]
  hexio_write corrupt.db $offset FF 
  hexio_write corrupt.db 24   12345678
} -test {
  do_test corrupt2-11.1 {
    catchsql { PRAGMA incremental_vacuum }
  } {1 {database disk image is malformed}}
}
corruption_test -sqlprep {
  PRAGMA auto_vacuum = incremental;
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
  CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
  INSERT INTO t1 VALUES(1, randstr(100,100));
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1;
  INSERT INTO t2 SELECT * FROM t1;
  DELETE FROM t1;
} -corrupt {
  set pgno [expr [file size corrupt.db] / 1024]
  hexio_write corrupt.db [expr 1024+5*($pgno-3)] 03 
  hexio_write corrupt.db 24   12345678
} -test {
  do_test corrupt2-12.1 {
    catchsql { PRAGMA incremental_vacuum }
  } {1 {database disk image is malformed}}
}

ifcapable autovacuum {
  # It is not possible for the last page in a database file to be the
  # pending-byte page (AKA the locking page). This test verifies that if
  # an attempt is made to commit a transaction to such an auto-vacuum 
  # database SQLITE_CORRUPT is returned.
  #
  corruption_test -tclprep {
    db eval { 
      PRAGMA auto_vacuum = full;
      PRAGMA page_size = 1024;
      CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
      INSERT INTO t1 VALUES(NULL, randstr(50,50));
    }
    for {set ii 0} {$ii < 10} {incr ii} {
      db eval { INSERT INTO t1 SELECT NULL, randstr(50,50) FROM t1 }
    }
  } -corrupt {
    do_test corrupt2-13.1 {
      file size corrupt.db
    } $::sqlite_pending_byte
    hexio_write corrupt.db [expr $::sqlite_pending_byte+1023] 00
  } -test {
    do_test corrupt2-13.2 {
      file size corrupt.db
    } [expr $::sqlite_pending_byte + 1024]
    do_test corrupt2-13.3 {
      catchsql { DELETE FROM t1 WHERE rowid < 30; }
    } {1 {database disk image is malformed}}
  }
}

finish_test

Added test/corrupt3.test.



























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# 2007 April 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.
#
# $Id: corrupt3.test,v 1.2 2007/04/06 21:42:22 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas {
  finish_test
  return
}

# Create a database with an overflow page.
#
do_test corrupt3-1.1 {
  set bigstring [string repeat 0123456789 200]
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES($bigstring);
  }
  file size test.db
} [expr {1024*3}]

# Verify that the file format is as we expect.  The page size
# should be 1024 bytes.  The only record should have a single
# overflow page.  The overflow page is page 3.  The pointer to
# the overflow page is on the last 4 bytes of page 2.
#
do_test corrupt3-1.2 {
  hexio_get_int [hexio_read test.db 16 2]
} 1024   ;# The page size is 1024
do_test corrupt3-1.3 {
  hexio_get_int [hexio_read test.db 20 1]
} 0      ;# Unused bytes per page is 0
do_test corrupt3-1.4 {
  hexio_get_int [hexio_read test.db 2044 4]
} 3      ;# Overflow page is 3
do_test corrupt3-1.5 {
  hexio_get_int [hexio_read test.db 2048 4]
} 0      ;# First chained overflow is 0

integrity_check corrupt3-1.6

# Make the overflow chain loop back on itself.   See if the
# corruption is detected.   (Actually, the last pointer in
# an overflow chain is ignored, so this is not an error.)
#
do_test corrupt3-1.7 {
  db close
  hexio_write test.db 2048 [hexio_render_int32 3]
  sqlite3 db test.db
  catchsql {
    SELECT x FROM t1
  }
} [list 0 $bigstring]
integrity_check corrupt3-1.8

# Change the pointer for the first page of the overflow
# change to be a non-existant page.
#
do_test corrupt3-1.9 {
  db close
  hexio_write test.db 2044 [hexio_render_int32 4]
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,10) FROM t1
  }
} [list 0 0123456789]
do_test corrupt3-1.10 {
  catchsql {
    PRAGMA integrity_check
  }
} {0 {{*** in database main ***
On tree page 2 cell 0: invalid page number 4
Page 3 is never used}}}
do_test corrupt3-1.11 {
  db close
  hexio_write test.db 2044 [hexio_render_int32 0]
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,10) FROM t1
  }
} [list 1 {database disk image is malformed}]
do_test corrupt3-1.12 {
  catchsql {
    PRAGMA integrity_check
  }
} {0 {{*** in database main ***
On tree page 2 cell 0: 1 of 1 pages missing from overflow list starting at 0
Page 3 is never used}}}

finish_test

Added test/corrupt4.test.





















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 2007 Sept 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.
#
# $Id: corrupt4.test,v 1.1 2007/09/07 14:32:07 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas {
  finish_test
  return
}

# Create a database with a freelist containing at least two pages.
#
do_test corrupt4-1.1 {
  set bigstring [string repeat 0123456789 200]
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES($bigstring);
    CREATE TABLE t2(y);
    INSERT INTO t2 VALUES(1);
    DROP TABLE t1;
  }
  file size test.db
} [expr {1024*4}]

# Verify that there are two pages on the freelist.
#
do_test corrupt4-1.2 {
  execsql {PRAGMA freelist_count}
} {2}

# Get the page number for the trunk of the freelist.
#
set trunkpgno [hexio_get_int [hexio_read test.db 32 4]]
set baseaddr [expr {($trunkpgno-1)*1024}]

# Verify that the trunk of the freelist has exactly one
# leaf.
#
do_test corrupt4-1.3 {
  hexio_get_int [hexio_read test.db [expr {$::baseaddr+4}] 4]
} {1}

# Insert a negative number as the number of leaves on the trunk.
# Then try to add a new element to the freelist.
#
do_test corrupt4-1.4 {
  hexio_write test.db [expr {$::baseaddr+4}] [hexio_render_int32 -100000000]
  db close
  sqlite3 db test.db
  catchsql {
    DROP TABLE t2
  }
} {1 {database disk image is malformed}}

finish_test

Added test/corrupt5.test.



























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 2008 Jan 22
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  Checks for 
# malformed schema.
#
# $Id: corrupt5.test,v 1.3 2009/06/04 02:47:04 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas {
  finish_test
  return
}

# Create a database with a freelist containing at least two pages.
#
do_test corrupt5-1.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    CREATE INDEX i1 ON t1(a,b);
    PRAGMA writable_schema=ON;
    UPDATE sqlite_master SET name=NULL, sql=NULL WHERE name='i1';
  }
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM t1
  }
} {1 {malformed database schema (?)}}

finish_test

Added test/corrupt6.test.























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# 2008 May 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It specifically focuses
# on corrupt SerialTypeLen values.
#
# $Id: corrupt6.test,v 1.2 2008/05/19 15:37:10 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas {
  finish_test
  return
}

# Create a simple, small database.
#
do_test corrupt6-1.1 {
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x);
    INSERT INTO t1(x) VALUES('varint32-01234567890123456789012345678901234567890123456789');
    INSERT INTO t1(x) VALUES('varint32-01234567890123456789012345678901234567890123456789');
  }
  file size test.db
} [expr {1024*2}]

# Verify that the file format is as we expect.  The page size
# should be 1024 bytes.
#
do_test corrupt6-1.2 {
  hexio_get_int [hexio_read test.db 16 2]
} 1024   ;# The page size is 1024
do_test corrupt6-1.3 {
  hexio_get_int [hexio_read test.db 20 1]
} 0      ;# Unused bytes per page is 0

integrity_check corrupt6-1.4

# Verify SerialTypeLen for first field of two records as we expect.
# SerialTypeLen = (len*2+12) = 60*2+12 = 132
do_test corrupt6-1.5.1 {
  hexio_read test.db 1923 2
} 8103      ;# First text field size is 81 03 == 131
do_test corrupt6-1.5.2 {
  hexio_read test.db 1987 2
} 8103      ;# Second text field size is 81 03 == 131

# Verify simple query results as expected.
do_test corrupt6-1.6 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 0 {varint32 varint32} ]
integrity_check corrupt6-1.7

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Increase SerialTypeLen by 2.
do_test corrupt6-1.8.1 {
  db close
  hexio_write test.db 1923 8105
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Decrease SerialTypeLen by 2.
do_test corrupt6-1.8.2 {
  db close
  hexio_write test.db 1923 8101
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Put value of record 1 / field 1 SerialTypeLen back.
do_test corrupt6-1.8.3 {
  db close
  hexio_write test.db 1923 8103
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 0 {varint32 varint32} ]
integrity_check corrupt6-1.8.4

# Adjust value of record 2 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Increase SerialTypeLen by 2.
do_test corrupt6-1.9.1 {
  db close
  hexio_write test.db 1987 8105
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 2 / field 2 SerialTypeLen and see if the
# corruption is detected.
# Decrease SerialTypeLen by 2.
do_test corrupt6-1.9.2 {
  db close
  hexio_write test.db 1987 8101
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Put value of record 1 / field 2 SerialTypeLen back.
do_test corrupt6-1.9.3 {
  db close
  hexio_write test.db 1987 8103
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 0 {varint32 varint32} ]
integrity_check corrupt6-1.9.4

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF 7F (2 bytes)
do_test corrupt6-1.10.1 {
  db close
  hexio_write test.db 1923 FF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF 7F (3 bytes)
do_test corrupt6-1.10.2 {
  db close
  hexio_write test.db 1923 FFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF FF 7F (4 bytes)
do_test corrupt6-1.10.3 {
  db close
  hexio_write test.db 1923 FFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF FF FF 7F (5 bytes)
do_test corrupt6-1.10.4 {
  db close
  hexio_write test.db 1923 FFFFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF FF FF FF 7F (6 bytes, and overflows).
do_test corrupt6-1.10.5 {
  db close
  hexio_write test.db 1923 FFFFFFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF FF FF FF FF 7F (7 bytes, and overflows).
do_test corrupt6-1.10.6 {
  db close
  hexio_write test.db 1923 FFFFFFFFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF FF FF FF FF FF 7F (8 bytes, and overflows).
do_test corrupt6-1.10.7 {
  db close
  hexio_write test.db 1923 FFFFFFFFFFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FF FF FF FF FF FF FF FF 7F (9 bytes, and overflows).
do_test corrupt6-1.10.8 {
  db close
  hexio_write test.db 1923 FFFFFFFFFFFFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

# Adjust value of record 1 / field 1 SerialTypeLen and see if the
# corruption is detected.
# Set SerialTypeLen to FFFF FF FF FF FF FF FF FF 7F (10 bytes, and overflows).
do_test corrupt6-1.10.9 {
  db close
  hexio_write test.db 1923 FFFFFFFFFFFFFFFFFF7F
  sqlite3 db test.db
  catchsql {
    SELECT substr(x,1,8) FROM t1
  }
} [list 1 {database disk image is malformed}]

finish_test

Added test/corrupt7.test.



























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# 2008 June 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It specifically focuses
# on corrupt cell offsets in a btree page.
#
# $Id: corrupt7.test,v 1.8 2009/08/10 10:18:08 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas {
  finish_test
  return
}

# Create a simple, small database.
#
do_test corrupt7-1.1 {
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x);
    INSERT INTO t1(x) VALUES(1);
    INSERT INTO t1(x) VALUES(2);
    INSERT INTO t1(x) SELECT x+2 FROM t1;
    INSERT INTO t1(x) SELECT x+4 FROM t1;
    INSERT INTO t1(x) SELECT x+8 FROM t1;
  }
  file size test.db
} [expr {1024*2}]

# Verify that the file format is as we expect.  The page size
# should be 1024 bytes.
#
do_test corrupt7-1.2 {
  hexio_get_int [hexio_read test.db 16 2]
} 1024   ;# The page size is 1024
do_test corrupt7-1.3 {
  hexio_get_int [hexio_read test.db 20 1]
} 0      ;# Unused bytes per page is 0

integrity_check corrupt7-1.4

# Deliberately corrupt some of the cell offsets in the btree page
# on page 2 of the database.
#
# The error message is different depending on whether or not the
# SQLITE_ENABLE_OVERSIZE_CELL_CHECK compile-time option is engaged.
#
ifcapable oversize_cell_check {
  do_test corrupt7-2.1 {
    db close
    hexio_write test.db 1062 FF
    sqlite3 db test.db
    db eval {PRAGMA integrity_check(1)}
  } {{*** in database main ***
Page 2: btreeInitPage() returns error code 11}}
  do_test corrupt7-2.2 {
    db close
    hexio_write test.db 1062 04
    sqlite3 db test.db
    db eval {PRAGMA integrity_check(1)}
  } {{*** in database main ***
Page 2: btreeInitPage() returns error code 11}}
} else {
  do_test corrupt7-2.1 {
    db close
    hexio_write test.db 1062 FF
    sqlite3 db test.db
    db eval {PRAGMA integrity_check(1)}
  } {{*** in database main ***
Corruption detected in cell 15 on page 2}}
  do_test corrupt7-2.2 {
    db close
    hexio_write test.db 1062 04
    sqlite3 db test.db
    db eval {PRAGMA integrity_check(1)}
  } {{*** in database main ***
Corruption detected in cell 15 on page 2}}
}
  
# The code path that was causing the buffer overrun that this test
# case was checking for was removed.
#
#do_test corrupt7-3.1 {
#  execsql {
#    DROP TABLE t1;
#    CREATE TABLE t1(a, b);
#    INSERT INTO t1 VALUES(1, 'one');
#    INSERT INTO t1 VALUES(100, 'one hundred');
#    INSERT INTO t1 VALUES(100000, 'one hundred thousand');
#    CREATE INDEX i1 ON t1(b);
#  }
#  db close
#
#  # Locate the 3rd cell in the index.
#  set cell_offset [hexio_get_int [hexio_read test.db [expr 1024*2 + 12] 2]]
#  incr cell_offset [expr 1024*2]
#  incr cell_offset 1
#
#  # This write corrupts the "header-size" field of the database record
#  # stored in the index cell. At one point this was causing sqlite to 
#  # reference invalid memory.
#  hexio_write test.db $cell_offset FFFF7F
#  
#  sqlite3 db test.db
#  catchsql {
#    SELECT b FROM t1 WHERE b > 'o' AND b < 'p';
#  }
#} {1 {database disk image is malformed}}

finish_test

Added test/corrupt8.test.







































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 2008 July 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It specifically focuses
# on corrupt pointer map pages.
#
# $Id: corrupt8.test,v 1.2 2008/07/11 03:34:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas||!autovacuum {
  finish_test
  return
}

# Create a database to work with.
#
do_test corrupt8-1.1 {
  execsql {
    PRAGMA auto_vacuum=1;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x);
    INSERT INTO t1(x) VALUES(1);
    INSERT INTO t1(x) VALUES(2);
    INSERT INTO t1(x) SELECT x+2 FROM t1;
    INSERT INTO t1(x) SELECT x+4 FROM t1;
    INSERT INTO t1(x) SELECT x+8 FROM t1;
    INSERT INTO t1(x) SELECT x+16 FROM t1;
    INSERT INTO t1(x) SELECT x+32 FROM t1;
    INSERT INTO t1(x) SELECT x+64 FROM t1;
    INSERT INTO t1(x) SELECT x+128 FROM t1;
    INSERT INTO t1(x) SELECT x+256 FROM t1;
    CREATE TABLE t2(a,b);
    INSERT INTO t2 SELECT x, x*x FROM t1;
  }
  expr {[file size test.db]>1024*12}
} {1}
integrity_check corrupt8-1.2

# Loop through each ptrmap entry.  Corrupt the entry and make sure the
# corruption is detected by the integrity_check.
#
for {set i 1024} {$i<2048} {incr i 5} {
  set oldval [hexio_read test.db $i 1]
  if {$oldval==0} break
  hexio_write test.db $i 00
  do_test corrupt8-2.$i.0 {
    db close
    sqlite3 db test.db
    set x [db eval {PRAGMA integrity_check}]
    expr {$x!="ok"}
  } {1}
  for {set k 1} {$k<=5} {incr k} {
    if {$k==$oldval} continue
    hexio_write test.db $i 0$k
    do_test corrupt8-2.$i.$k {
      db close
      sqlite3 db test.db
      set x [db eval {PRAGMA integrity_check}]
      expr {$x!="ok"}
    } {1}
  }
  hexio_write test.db $i 06
  do_test corrupt8-2.$i.6 {
    db close
    sqlite3 db test.db
    set x [db eval {PRAGMA integrity_check}]
    expr {$x!="ok"}
  } {1}
  hexio_write test.db $i $oldval
  if {$oldval>2} {
    set i2 [expr {$i+1+$i%4}]
    set oldval [hexio_read test.db $i2 1]
    hexio_write test.db $i2 [format %02x [expr {($oldval+1)&0xff}]]
    do_test corrupt8-2.$i.7 {
      db close
      sqlite3 db test.db
      set x [db eval {PRAGMA integrity_check}]
      expr {$x!="ok"}
    } {1}
    hexio_write test.db $i2 $oldval
  }
}


finish_test

Added test/corrupt9.test.







































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# 2008 July 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It specifically focuses
# on corruption in the form of duplicate entries on the freelist.
#
# $Id: corrupt9.test,v 1.3 2009/06/04 02:47:04 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# We must have the page_size pragma for these tests to work.
#
ifcapable !pager_pragmas {
  finish_test
  return
}

# Return the offset to the first (trunk) page of the freelist.  Return
# zero of the freelist is empty.
#
proc freelist_trunk_offset {filename} {
  if {[hexio_read $filename 36 4]==0} {return 0}
  set pgno [hexio_get_int [hexio_read $filename 32 4]]
  return [expr {($pgno-1)*[hexio_get_int [hexio_read $filename 16 2]]}]
}

# This procedure looks at the first trunk page of the freelist and
# corrupts that page by overwriting up to N entries with duplicates
# of the first entry.
#
proc corrupt_freelist {filename N} {
  set offset [freelist_trunk_offset $filename]
  if {$offset==0} {error "Freelist is empty"}
  set cnt [hexio_get_int [hexio_read $filename [expr {$offset+4}] 4]]
  set pgno [hexio_read $filename [expr {$offset+8}] 4]
  for {set i 12} {$N>0 && $i<8+4*$cnt} {incr i 4; incr N -1} {
    hexio_write $filename [expr {$offset+$i}] $pgno
  }
}

# Create a database to work with.  Make sure there are plenty of
# entries on the freelist.
#
do_test corrupt9-1.1 {
  execsql {
    PRAGMA auto_vacuum=NONE;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x);
    INSERT INTO t1(x) VALUES(1);
    INSERT INTO t1(x) VALUES(2);
    INSERT INTO t1(x) SELECT x+2 FROM t1;
    INSERT INTO t1(x) SELECT x+4 FROM t1;
    INSERT INTO t1(x) SELECT x+8 FROM t1;
    INSERT INTO t1(x) SELECT x+16 FROM t1;
    INSERT INTO t1(x) SELECT x+32 FROM t1;
    INSERT INTO t1(x) SELECT x+64 FROM t1;
    INSERT INTO t1(x) SELECT x+128 FROM t1;
    INSERT INTO t1(x) SELECT x+256 FROM t1;
    CREATE TABLE t2(a,b);
    INSERT INTO t2 SELECT x, x*x FROM t1;
    CREATE INDEX i1 ON t1(x);
    CREATE INDEX i2 ON t2(b,a);
    DROP INDEX i2;
  }
  expr {[file size test.db]>1024*24}
} {1}
integrity_check corrupt9-1.2

# Corrupt the freelist by adding duplicate entries to the freelist.
# Make sure the corruption is detected.
#
db close
file copy -force test.db test.db-template

corrupt_freelist test.db 1
sqlite3 db test.db
do_test corrupt9-2.1 {
  set x [db eval {PRAGMA integrity_check}]
  expr {$x!="ok"}
} {1}
do_test corrupt9-2.2 {
  catchsql {
    CREATE INDEX i2 ON t2(b,a);
    REINDEX;
  }
} {1 {database disk image is malformed}}


db close
file copy -force test.db-template test.db
corrupt_freelist test.db 2
sqlite3 db test.db
do_test corrupt9-3.1 {
  set x [db eval {PRAGMA integrity_check}]
  expr {$x!="ok"}
} {1}
do_test corrupt9-3.2 {
  catchsql {
    CREATE INDEX i2 ON t2(b,a);
    REINDEX;
  }
} {1 {database disk image is malformed}}

db close
file copy -force test.db-template test.db
corrupt_freelist test.db 3
sqlite3 db test.db
do_test corrupt9-4.1 {
  set x [db eval {PRAGMA integrity_check}]
  expr {$x!="ok"}
} {1}
do_test corrupt9-4.2 {
  catchsql {
    CREATE INDEX i2 ON t2(b,a);
    REINDEX;
  }
} {1 {database disk image is malformed}}
 

finish_test

Added test/corruptA.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2008 July 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It specifically focuses
# on corrupt database headers.
#
# $Id: corruptA.test,v 1.1 2008/07/11 16:39:23 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Create a database to work with.
#
do_test corruptA-1.1 {
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1(x) VALUES(1);
  }
  expr {[file size test.db]>=1024}
} {1}
integrity_check corruptA-1.2

# Corrupt the file header in various ways and make sure the corruption
# is detected when opening the database file.
#
db close
file copy -force test.db test.db-template

do_test corruptA-2.1 {
  file copy -force test.db-template test.db
  hexio_write test.db 19 02   ;# the read format number
  sqlite3 db test.db
  catchsql {SELECT * FROM t1}  
} {1 {file is encrypted or is not a database}}
 
do_test corruptA-2.2 {
  db close
  file copy -force test.db-template test.db
  hexio_write test.db 21 41   ;# max embedded payload fraction
  sqlite3 db test.db
  catchsql {SELECT * FROM t1}  
} {1 {file is encrypted or is not a database}}
 
do_test corruptA-2.3 {
  db close
  file copy -force test.db-template test.db
  hexio_write test.db 22 1f   ;# min embedded payload fraction
  sqlite3 db test.db
  catchsql {SELECT * FROM t1}  
} {1 {file is encrypted or is not a database}}
 
do_test corruptA-2.4 {
  db close
  file copy -force test.db-template test.db
  hexio_write test.db 23 21   ;# min leaf payload fraction
  sqlite3 db test.db
  catchsql {SELECT * FROM t1}  
} {1 {file is encrypted or is not a database}}
 

finish_test

Added test/corruptB.test.

















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# 2008 Sep 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It specifically focuses
# on loops in the B-Tree structure. A loop is formed in a B-Tree structure
# when there exists a page that is both an a descendent or ancestor of
# itself.
#
# Also test that an SQLITE_CORRUPT error is returned if a B-Tree page
# contains a (corrupt) reference to a page greater than the configured
# maximum page number.
#
# $Id: corruptB.test,v 1.4 2009/07/21 19:25:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


do_test corruptB-1.1 {
  execsql {
    PRAGMA auto_vacuum = 1;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(randomblob(200));
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
  }
  expr {[file size test.db] > (1024*9)}
} {1}
integrity_check corruptB-1.2

file copy -force test.db bak.db

# Set the right-child of a B-Tree rootpage to refer to the root-page itself.
#
do_test corruptB-1.3.1 {
  set ::root [execsql {SELECT rootpage FROM sqlite_master}]
  set ::offset [expr {($::root-1)*1024}]
  hexio_write test.db [expr $offset+8] [hexio_render_int32 $::root]
} {4}
do_test corruptB-1.3.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

# Set the left-child of a cell in a B-Tree rootpage to refer to the 
# root-page itself.
#
do_test corruptB-1.4.1 {
  db close
  file copy -force bak.db test.db
  set cell_offset [hexio_get_int [hexio_read test.db [expr $offset+12] 2]]
  hexio_write test.db [expr $offset+$cell_offset] [hexio_render_int32 $::root]
} {4}
do_test corruptB-1.4.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

# Now grow the table B-Tree so that it is more than 2 levels high.
#
do_test corruptB-1.5.1 {
  db close
  file copy -force bak.db test.db
  sqlite3 db test.db
  execsql {
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
    INSERT INTO t1 SELECT randomblob(200) FROM t1;
  }
} {}

file copy -force test.db bak.db

# Set the right-child pointer of the right-child of the root page to point
# back to the root page.
#
do_test corruptB-1.6.1 {
  db close
  set iRightChild [hexio_get_int [hexio_read test.db [expr $offset+8] 4]]
  set c_offset [expr ($iRightChild-1)*1024]
  hexio_write test.db [expr $c_offset+8] [hexio_render_int32 $::root]
} {4}
do_test corruptB-1.6.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

# Set the left-child pointer of a cell of the right-child of the root page to
# point back to the root page.
#
do_test corruptB-1.7.1 {
  db close
  file copy -force bak.db test.db
  set cell_offset [hexio_get_int [hexio_read test.db [expr $c_offset+12] 2]]
  hexio_write test.db [expr $c_offset+$cell_offset] [hexio_render_int32 $::root]
} {4}
do_test corruptB-1.7.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

do_test corruptB-1.8.1 {
  db close
  set cell_offset [hexio_get_int [hexio_read test.db [expr $offset+12] 2]]
  set iLeftChild [
      hexio_get_int [hexio_read test.db [expr $offset+$cell_offset] 4]
  ]
  set c_offset [expr ($iLeftChild-1)*1024]
  hexio_write test.db [expr $c_offset+8] [hexio_render_int32 $::root]
} {4}
do_test corruptB-1.8.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

# Set the left-child pointer of a cell of the right-child of the root page to
# point back to the root page.
#
do_test corruptB-1.9.1 {
  db close
  file copy -force bak.db test.db
  set cell_offset [hexio_get_int [hexio_read test.db [expr $c_offset+12] 2]]
  hexio_write test.db [expr $c_offset+$cell_offset] [hexio_render_int32 $::root]
} {4}
do_test corruptB-1.9.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

#---------------------------------------------------------------------------

do_test corruptB-2.1.1 {
  db close
  file copy -force bak.db test.db
  hexio_write test.db [expr $offset+8] [hexio_render_int32 0x6FFFFFFF]
} {4}
do_test corruptB-2.1.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t1 }
} {1 {database or disk is full}}

#---------------------------------------------------------------------------

# Corrupt the header-size field of a database record.
#
do_test corruptB-3.1.1 {
  db close
  file copy -force bak.db test.db
  sqlite3 db test.db
  set v [string repeat abcdefghij 200]
  execsql {
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES($v);
  }
  set t2_root [execsql {SELECT rootpage FROM sqlite_master WHERE name = 't2'}]
  set iPage [expr ($t2_root-1)*1024]
  set iCellarray [expr $iPage + 8]
  set iRecord [hexio_get_int [hexio_read test.db $iCellarray 2]]
  db close
  hexio_write test.db [expr $iPage+$iRecord+3] FF00
} {2}
do_test corruptB-3.1.2 {
  sqlite3 db test.db
  catchsql { SELECT * FROM t2 }
} {1 {database disk image is malformed}}

finish_test

Added test/corruptC.test.



























































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# 2004 August 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.  It creates a base
# data base file, then tests that single byte corruptions in 
# increasingly larger quantities are handled gracefully.
#
# $Id: corruptC.test,v 1.14 2009/07/11 06:55:34 danielk1977 Exp $

catch {file delete -force test.db test.db-journal test.bu}

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Construct a compact, dense database for testing.
#
do_test corruptC-1.1 {
  execsql {
    PRAGMA auto_vacuum = 0;
    PRAGMA legacy_file_format=1;
    BEGIN;
    CREATE TABLE t1(x,y);
    INSERT INTO t1 VALUES(1,1);
    INSERT OR IGNORE INTO t1 SELECT x*2,y FROM t1;
    INSERT OR IGNORE INTO t1 SELECT x*3,y FROM t1;
    INSERT OR IGNORE INTO t1 SELECT x*5,y FROM t1;
    INSERT OR IGNORE INTO t1 SELECT x*7,y FROM t1;
    INSERT OR IGNORE INTO t1 SELECT x*11,y FROM t1;
    INSERT OR IGNORE INTO t1 SELECT x*13,y FROM t1;
    CREATE INDEX t1i1 ON t1(x);
    CREATE TABLE t2 AS SELECT x,2 as y FROM t1 WHERE rowid%5!=0;
    COMMIT;
  }
} {}

ifcapable {integrityck} {
  integrity_check corruptC-1.2
}

# Generate random integer
#
proc random {range} {
  return [expr {round(rand()*$range)}]
}

# Copy file $from into $to
#
proc copy_file {from to} {
  file copy -force $from $to
}

# Setup for the tests.  Make a backup copy of the good database in test.bu.
#
db close
copy_file test.db test.bu
sqlite3 db test.db
set fsize [file size test.db]

# Set a quasi-random random seed. 
if {[info exists SOAKTEST]} {
  # If we are doing SOAK tests, we want a different
  # random seed for each run.  Ideally we would like 
  # to use [clock clicks] or something like that here.
  set qseed [file mtime test.db]
} else {
  # If we are not doing soak tests,
  # make it repeatable.
  set qseed 0
}
expr srand($qseed)

#
# First test some specific corruption tests found from earlier runs
# with specific seeds.
#

# test that a corrupt content offset size is handled (seed 5577)
do_test corruptC-2.1 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 2053 [format %02x 0x04]

  sqlite3 db test.db
  catchsql {PRAGMA integrity_check}
} {1 {database disk image is malformed}}

# test that a corrupt content offset size is handled (seed 5649)
do_test corruptC-2.2 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 27   [format %02x 0x08]
  hexio_write test.db 233  [format %02x 0x6a]
  hexio_write test.db 328  [format %02x 0x67]
  hexio_write test.db 750  [format %02x 0x1f]
  hexio_write test.db 1132 [format %02x 0x52]
  hexio_write test.db 1133 [format %02x 0x84]
  hexio_write test.db 1220 [format %02x 0x01]
  hexio_write test.db 3688 [format %02x 0xc1]
  hexio_write test.db 3714 [format %02x 0x58]
  hexio_write test.db 3746 [format %02x 0x9a]

  sqlite3 db test.db
  catchsql {UPDATE t1 SET y=1}
} {1 {database disk image is malformed}}

# test that a corrupt free cell size is handled (seed 13329)
do_test corruptC-2.3 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 1094 [format %02x 0x76]

  sqlite3 db test.db
  catchsql {UPDATE t1 SET y=1}
} {1 {database disk image is malformed}}

# test that a corrupt free cell size is handled (seed 169571)
do_test corruptC-2.4 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 3119 [format %02x 0xdf]

  sqlite3 db test.db
  catchsql {UPDATE t2 SET y='abcdef-uvwxyz'}
} {1 {database disk image is malformed}}

# test that a corrupt free cell size is handled (seed 169571)
do_test corruptC-2.5 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 3119 [format %02x 0xdf]
  hexio_write test.db 4073 [format %02x 0xbf]

  sqlite3 db test.db
  catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;}
  catchsql {PRAGMA integrity_check}
} {0 {{*** in database main ***
Page 4: btreeInitPage() returns error code 11}}}

# {0 {{*** in database main ***
# Corruption detected in cell 710 on page 4
# Multiple uses for byte 661 of page 4
# Fragmented space is 249 byte reported as 21 on page 4}}}

# test that a corrupt free cell size is handled (seed 169595)
do_test corruptC-2.6 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 619 [format %02x 0xe2]
  hexio_write test.db 3150 [format %02x 0xa8]

  sqlite3 db test.db
  catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;}
} {1 {database disk image is malformed}}

# corruption (seed 178692)
do_test corruptC-2.7 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 3074 [format %02x 0xa0]

  sqlite3 db test.db
  catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;}
} {1 {database disk image is malformed}}

# corruption (seed 179069)
do_test corruptC-2.8 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 1393 [format %02x 0x7d]
  hexio_write test.db 84 [format %02x 0x19]
  hexio_write test.db 3287 [format %02x 0x3b]
  hexio_write test.db 2564 [format %02x 0xed]
  hexio_write test.db 2139 [format %02x 0x55]

  sqlite3 db test.db
  catchsql {BEGIN; DELETE FROM t1 WHERE x>13; ROLLBACK;}
} {1 {database disk image is malformed}}

# corruption (seed 170434)
do_test corruptC-2.9 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 2095 [format %02x 0xd6]

  sqlite3 db test.db
  catchsql {BEGIN; DELETE FROM t1 WHERE x>13; ROLLBACK;}
} {1 {database disk image is malformed}}

# corruption (seed 186504)
do_test corruptC-2.10 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 3130 [format %02x 0x02]
  
  sqlite3 db test.db
  catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;}
} {1 {database disk image is malformed}}

# corruption (seed 1589)
do_test corruptC-2.11 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 55 [format %02x 0xa7]
  
  sqlite3 db test.db
  catchsql {BEGIN; CREATE TABLE t3 AS SELECT x,3 as y FROM t2 WHERE rowid%5!=0; ROLLBACK;}
} {1 {database disk image is malformed}}

# corruption (seed 14166)
do_test corruptC-2.12 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 974 [format %02x 0x2e]
  
  sqlite3 db test.db
  catchsql {SELECT count(*) FROM sqlite_master;}
} {1 {malformed database schema (t1i1) - corrupt database}}

# corruption (seed 218803)
do_test corruptC-2.13 {
  db close
  copy_file test.bu test.db

  # insert corrupt byte(s)
  hexio_write test.db 102 [format %02x 0x12]
  
  sqlite3 db test.db
  catchsql {BEGIN; CREATE TABLE t3 AS SELECT x,3 as y FROM t2 WHERE rowid%5!=0; ROLLBACK;}
} {1 {database disk image is malformed}}

do_test corruptC-2.14 {
  db close
  copy_file test.bu test.db

  sqlite3 db test.db
  set blob [string repeat abcdefghij 10000]
  execsql { INSERT INTO t1 VALUES (1, $blob) }

  sqlite3 db test.db
  set filesize [file size test.db]
  hexio_write test.db [expr $filesize-2048] 00000001
  catchsql {DELETE FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)}
} {1 {database disk image is malformed}}

#
# Now test for a series of quasi-random seeds.
# We loop over the entire file size and touch
# each byte at least once.
for {set tn 0} {$tn<$fsize} {incr tn 1} {

  # setup for test
  db close
  copy_file test.bu test.db
  sqlite3 db test.db

  # Seek to a random location in the file, and write a random single byte
  # value.  Then do various operations on the file to make sure that
  # the database engine can handle the corruption gracefully.
  #
  set last 0
  for {set i 1} {$i<=512 && !$last} {incr i 1} {

    db close
    if {$i==1} {
      # on the first corrupt value, use location $tn
      # this ensures that we touch each location in the 
      # file at least once.
      set roffset $tn
    } else { 
      # insert random byte at random location
      set roffset [random $fsize]
    }
    set rbyte [format %02x [random 255]]

    # You can uncomment the following to have it trace
    # exactly how it's corrupting the file.  This is 
    # useful for generating the "seed specific" tests
    # above.
    # set rline "$roffset $rbyte"
    # puts stdout $rline

    hexio_write test.db $roffset $rbyte
    sqlite3 db test.db

    # do a few random operations to make sure that if 
    # they error, they error gracefully instead of crashing.
    do_test corruptC-3.$tn.($qseed).$i.1 {
      catchsql {SELECT count(*) FROM sqlite_master}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.2 {
      catchsql {SELECT count(*) FROM t1}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.3 {
      catchsql {SELECT count(*) FROM t1 WHERE x>13}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.4 {
      catchsql {SELECT count(*) FROM t2}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.5 {
      catchsql {SELECT count(*) FROM t2 WHERE x<13}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.6 {
      catchsql {BEGIN; UPDATE t1 SET y=1; ROLLBACK;}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.7 {
      catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.8 {
      catchsql {BEGIN; DELETE FROM t1 WHERE x>13; ROLLBACK;}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.9 {
      catchsql {BEGIN; DELETE FROM t2 WHERE x<13; ROLLBACK;}
      set x {}
    } {}
    do_test corruptC-3.$tn.($qseed).$i.10 {
      catchsql {BEGIN; CREATE TABLE t3 AS SELECT x,3 as y FROM t2 WHERE rowid%5!=0; ROLLBACK;}
      set x {}
    } {}

    # check the integrity of the database.
    # once the corruption is detected, we can stop.
    ifcapable {integrityck} {
      set res [ catchsql {PRAGMA integrity_check} ]
      set ans [lindex $res 1]
      if { [ string compare $ans "ok" ] != 0 } {
        set last -1
      }
    }
    # if we are not capable of doing an integrity check,
    # stop after corrupting 5 bytes.
    ifcapable {!integrityck} {
      if { $i > 5 } {
        set last -1
      }
    }

    # Check that no page references were leaked.
    # TBD:  need to figure out why this doesn't work
    # work with ROLLBACKs...
    if {0} {
      do_test corruptC-3.$tn.($qseed).$i.11 {
        set bt [btree_from_db db]
        db_enter db
        array set stats [btree_pager_stats $bt]
        db_leave db
        set stats(ref)
      } {0}
    }
  }
  # end for i

}
# end for tn

finish_test

Added test/corruptD.test.















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# 2009 June 3
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: corruptD.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#--------------------------------------------------------------------------
# OVERVIEW
#
#   This test file attempts to verify that SQLite does not read past the 
#   end of any in-memory buffers as a result of corrupted database page 
#   images. Usually this happens because a field within a database page
#   that contains an offset to some other structure within the same page
#   is set to too large a value. A database page contains the following
#   such fields:
#
#     1. The page header field that contains the offset to the first 
#        free block of space.
#
#     2. The first two bytes of all but the last free block on the free-block
#        list (the offset to the next free block).
#
#     3. The page header field containing the number of cells on the page
#        (implicitly defines the offset to the final element in the cell offset
#        array, which could potentially be off the end of the page).
#
#     4. The page header field containing the offset to the start of the cell
#        content area.
#
#     5. The contents of the cell offset array.
#
#     6. The first few bytes of each cell determine the size of the cell
#        stored within the page, and hence the offset to the final byte of
#        the cell.
#
#   If any of the above fields are set to too large a value, then a buffer
#   overread may occur. This test script creates and operates on various
#   strategically corrupted database files to attempt to provoke such buffer
#   overreads.
#
#   Very often, a buffer overread passes unnoticed, particularly in workstation
#   environments. For this reason, this test script should be run using valgrind
#   (or similar) in order to verify that no overreads occur.
#
# TEST PLAN
# 
#   Test cases corruptD-1.* are white-box tests. They attempt to corrupt
#   one of the above fields, then exercise each part of the code in btree.c
#   that uses said field.
#   
#   Offset variables 1, 2, 3 and 4 are all checked to make sure they
#   will not result in buffer overruns as part of page initialization in
#   sqlite3BtreeInitPage(). Offsets 5 and 6 cannot be tested as part of
#   page initialization, as trying to do so causes a performance hit.
#

do_test corruptD-1.0 {
  execsql { 
    PRAGMA auto_vacuum = 0;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a, b);
  }
  for {set ii 1} {$ii < 50} {incr ii} {
    execsql { INSERT INTO t1 VALUES($ii, $ii * $ii) }
  }
  execsql {
    DELETE FROM t1 WHERE a = 10;
    DELETE FROM t1 WHERE a = 20;
    DELETE FROM t1 WHERE a = 30;
    DELETE FROM t1 WHERE a = 40;
  }
  copy_file test.db test.bu
} {}

proc incr_change_counter {} {
  hexio_write test.db 24 [
    hexio_render_int32 [expr [hexio_get_int [hexio_read test.db 24 4]] + 1]
  ]
}

proc restore_file {} {
  db close
  copy_file test.bu test.db
  sqlite3 db test.db
}

#-------------------------------------------------------------------------
# The following tests, corruptD-1.1.*, focus on the page header field
# containing the offset of the first free block in a page. 
#
do_test corruptD-1.1.1 {
  incr_change_counter
  hexio_write test.db [expr 1024+1] FFFF
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}
do_test corruptD-1.1.2 {
  incr_change_counter
  hexio_write test.db [expr 1024+1] [hexio_render_int32 1021]
  catchsql { SELECT * FROM t1 }
} {1 {database disk image is malformed}}

#-------------------------------------------------------------------------
# The following tests, corruptD-1.2.*, focus on the offsets contained
# in the first 2 byte of each free-block on the free-list.
#
do_test corruptD-1.2.1 {
  restore_file
} {}
do_test corruptD-1.2.2 {
} {}

#-------------------------------------------------------------------------
# The following tests, corruptD-1.4.*, ...
#


#-------------------------------------------------------------------------
# The following tests, corruptD-1.5.*, focus on the offsets contained
# in the cell offset array.
# 
#   defragmentPage
#

finish_test

Added test/count.test.

































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# 2009 February 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing "SELECT count(*)" statements.
#
# $Id: count.test,v 1.6 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Test plan:
#
#  count-0.*: Make sure count(*) works on an empty database.  (Ticket #3774)
#
#  count-1.*: Test that the OP_Count instruction appears to work on both
#             tables and indexes. Test both when they contain 0 entries,
#             when all entries are on the root page, and when the b-tree
#             forms a structure 2 and 3 levels deep.
#            
#  count-2.*: Test that 
#
#

do_test count-0.1 {
  db eval {
     SELECT count(*) FROM sqlite_master;
  }
} {0}

set iTest 0
foreach zIndex [list {
  /* no-op */
} {
  CREATE INDEX i1 ON t1(a);
}] { 
  incr iTest
  do_test count-1.$iTest.1 {
    execsql {
      DROP TABLE IF EXISTS t1;
      CREATE TABLE t1(a, b);
    }
    execsql $zIndex
    execsql { SELECT count(*) FROM t1 }
  } {0}
  
  do_test count-1.$iTest.2 {
    execsql {
      INSERT INTO t1 VALUES(1, 2);
      INSERT INTO t1 VALUES(3, 4);
      SELECT count(*) FROM t1;
    }
  } {2}

  do_test count-1.$iTest.3 {
    execsql {
      INSERT INTO t1 SELECT * FROM t1;          --   4
      INSERT INTO t1 SELECT * FROM t1;          --   8
      INSERT INTO t1 SELECT * FROM t1;          --  16
      INSERT INTO t1 SELECT * FROM t1;          --  32
      INSERT INTO t1 SELECT * FROM t1;          --  64
      INSERT INTO t1 SELECT * FROM t1;          -- 128
      INSERT INTO t1 SELECT * FROM t1;          -- 256
      SELECT count(*) FROM t1;
    }
  } {256}
  
  do_test count-1.$iTest.4 {
    execsql {
      INSERT INTO t1 SELECT * FROM t1;          --  512
      INSERT INTO t1 SELECT * FROM t1;          -- 1024
      INSERT INTO t1 SELECT * FROM t1;          -- 2048
      INSERT INTO t1 SELECT * FROM t1;          -- 4096
      SELECT count(*) FROM t1;
    }
  } {4096}
  
  do_test count-1.$iTest.5 {
    execsql {
      BEGIN;
      INSERT INTO t1 SELECT * FROM t1;          --  8192
      INSERT INTO t1 SELECT * FROM t1;          -- 16384
      INSERT INTO t1 SELECT * FROM t1;          -- 32768
      INSERT INTO t1 SELECT * FROM t1;          -- 65536
      COMMIT;
      SELECT count(*) FROM t1;
    }
  } {65536}
}

proc uses_op_count {sql} {
  if {[lsearch [execsql "EXPLAIN $sql"] Count]>=0} {
    return 1;
  }
  return 0
}

do_test count-2.1 {
  execsql {
    CREATE TABLE t2(a, b);
  }
  uses_op_count {SELECT count(*) FROM t2}
} {1}
do_test count-2.2 {
  catchsql {SELECT count(DISTINCT *) FROM t2}
} {1 {near "*": syntax error}}
do_test count-2.3 {
  uses_op_count {SELECT count(DISTINCT a) FROM t2}
} {0}
do_test count-2.4 {
  uses_op_count {SELECT count(a) FROM t2}
} {0}
do_test count-2.5 {
  uses_op_count {SELECT count() FROM t2}
} {1}
do_test count-2.6 {
  catchsql {SELECT count(DISTINCT) FROM t2}
} {1 {DISTINCT aggregates must have exactly one argument}}
do_test count-2.7 {
  uses_op_count {SELECT count(*)+1 FROM t2}
} {0}
do_test count-2.8 {
  uses_op_count {SELECT count(*) FROM t2 WHERE a IS NOT NULL}
} {0}
do_test count-2.9 {
  catchsql {SELECT count(*) FROM t2 HAVING count(*)>1}
} {1 {a GROUP BY clause is required before HAVING}}
do_test count-2.10 {
  uses_op_count {SELECT count(*) FROM (SELECT 1)}
} {0}
do_test count-2.11 {
  execsql { CREATE VIEW v1 AS SELECT 1 AS a }
  uses_op_count {SELECT count(*) FROM v1}
} {0}
do_test count-2.12 {
  uses_op_count {SELECT count(*), max(a) FROM t2}
} {0}
do_test count-2.13 {
  uses_op_count {SELECT count(*) FROM t1, t2}
} {0}

ifcapable vtab {
  register_echo_module [sqlite3_connection_pointer db]
  do_test count-2.14 {
    execsql { CREATE VIRTUAL TABLE techo USING echo(t1); }
    uses_op_count {SELECT count(*) FROM techo}
  } {0}
}

do_test count-3.1 {
  execsql {
    CREATE TABLE t3(a, b);
    SELECT a FROM (SELECT count(*) AS a FROM t3) WHERE a==0;
  }
} {0}
do_test count-3.2 {
  execsql {
    SELECT a FROM (SELECT count(*) AS a FROM t3) WHERE a==1;
  }
} {}

do_test count-4.1 {
  execsql {
    CREATE TABLE t4(a, b);
    INSERT INTO t4 VALUES('a', 'b');
    CREATE INDEX t4i1 ON t4(b, a);
    SELECT count(*) FROM t4;
  }
} {1}
do_test count-4.2 {
  execsql {
    CREATE INDEX t4i2 ON t4(b);
    SELECT count(*) FROM t4;
  }
} {1}
do_test count-4.3 {
  execsql {
    DROP INDEX t4i1;
    CREATE INDEX t4i1 ON t4(b, a);
    SELECT count(*) FROM t4;
  }
} {1}


finish_test

Added test/crash.test.























































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# The focus of this file is testing the ability of the database to
# uses its rollback journal to recover intact (no database corruption)
# from a power failure during the middle of a COMMIT.  The OS interface
# modules are overloaded using the modified I/O routines found in test6.c.  
# These routines allow us to simulate the kind of file damage that 
# occurs after a power failure.
#
# $Id: crash.test,v 1.27 2008/01/08 15:18:52 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

set repeats 100
#set repeats 10

# The following procedure computes a "signature" for table "abc".  If
# abc changes in any way, the signature should change.  
proc signature {} {
  return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}]
}
proc signature2 {} {
  return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc2}]
}

#--------------------------------------------------------------------------
# Simple crash test:
#
# crash-1.1: Create a database with a table with two rows.
# crash-1.2: Run a 'DELETE FROM abc WHERE a = 1' that crashes during
#            the first journal-sync.
# crash-1.3: Ensure the database is in the same state as after crash-1.1.
# crash-1.4: Run a 'DELETE FROM abc WHERE a = 1' that crashes during
#            the first database-sync.
# crash-1.5: Ensure the database is in the same state as after crash-1.1.
# crash-1.6: Run a 'DELETE FROM abc WHERE a = 1' that crashes during
#            the second journal-sync.
# crash-1.7: Ensure the database is in the same state as after crash-1.1.
#
# Tests 1.8 through 1.11 test for crashes on the third journal sync and
# second database sync.  Neither of these is required in such a small test
# case, so these tests are just to verify that the test infrastructure
# operates as expected.
#
do_test crash-1.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc VALUES(4, 5, 6);
  }
  set ::sig [signature]
  expr 0
} {0}
for {set i 0} {$i<10} {incr i} {
  set seed [expr {int(abs(rand()*10000))}]
  do_test crash-1.2.$i {
    crashsql -delay 1 -file test.db-journal -seed $seed {
      DELETE FROM abc WHERE a = 1;
    }
  } {1 {child process exited abnormally}}
  do_test crash-1.3.$i {
    signature
  } $::sig
}
do_test crash-1.4 {
  crashsql -delay 1 -file test.db {
    DELETE FROM abc WHERE a = 1;
  }
} {1 {child process exited abnormally}}
do_test crash-1.5 {
  signature
} $::sig
do_test crash-1.6 {
  crashsql -delay 2 -file test.db-journal {
    DELETE FROM abc WHERE a = 1;
  }
} {1 {child process exited abnormally}}
do_test crash-1.7 {
  catchsql {
    SELECT * FROM abc;
  }
} {0 {1 2 3 4 5 6}}

do_test crash-1.8 {
  crashsql -delay 3 -file test.db-journal {
    DELETE FROM abc WHERE a = 1;
  }
} {0 {}}
do_test crash-1.9 {
  catchsql {
    SELECT * FROM abc;
  }
} {0 {4 5 6}}
do_test crash-1.10 {
  crashsql -delay 2 -file test.db {
    DELETE FROM abc WHERE a = 4;
  }
} {0 {}}
do_test crash-1.11 {
  catchsql {
    SELECT * FROM abc;
  }
} {0 {}}

#--------------------------------------------------------------------------
# The following tests test recovery when both the database file and the the
# journal file contain corrupt data. This can happen after pages are
# written to the database file before a transaction is committed due to
# cache-pressure.
#
# crash-2.1: Insert 18 pages of data into the database.
# crash-2.2: Check the database file size looks ok.
# crash-2.3: Delete 15 or so pages (with a 10 page page-cache), then crash.
# crash-2.4: Ensure the database is in the same state as after crash-2.1.
#
# Test cases crash-2.5 and crash-2.6 check that the database is OK if the 
# crash occurs during the main database file sync. But this isn't really
# different from the crash-1.* cases.
#
do_test crash-2.1 {
  execsql { BEGIN }
  for {set n 0} {$n < 1000} {incr n} {
    execsql "INSERT INTO abc VALUES($n, [expr 2*$n], [expr 3*$n])"
  }
  execsql { COMMIT }
  set ::sig [signature]
  execsql { SELECT sum(a), sum(b), sum(c) from abc }
} {499500 999000 1498500}
do_test crash-2.2 {
  expr ([file size test.db] / 1024)>16
} {1}
do_test crash-2.3 {
  crashsql -delay 2 -file test.db-journal {
    DELETE FROM abc WHERE a < 800;
  }
} {1 {child process exited abnormally}}
do_test crash-2.4 {
  signature
} $sig
do_test crash-2.5 {
  crashsql -delay 1 -file test.db {
    DELETE FROM abc WHERE a<800;
  }
} {1 {child process exited abnormally}}
do_test crash-2.6 {
  signature
} $sig

#--------------------------------------------------------------------------
# The crash-3.* test cases are essentially the same test as test case
# crash-2.*, but with a more complicated data set. 
#
# The test is repeated a few times with different seeds for the random
# number generator in the crashing executable. Because there is no way to
# seed the random number generator directly, some SQL is added to the test
# case to 'use up' a different quantity random numbers before the test SQL
# is executed.
#

# Make sure the file is much bigger than the pager-cache (10 pages). This
# ensures that cache-spills happen regularly.
do_test crash-3.0 {
  execsql {
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
  }
  expr ([file size test.db] / 1024) > 450
} {1}
for {set i 1} {$i < $repeats} {incr i} {
  set sig [signature]
  do_test crash-3.$i.1 {
     set seed [expr {int(abs(rand()*10000))}]
     crashsql -delay [expr $i%5 + 1] -file test.db-journal -seed $seed "
       BEGIN;
       SELECT random() FROM abc LIMIT $i;
       INSERT INTO abc VALUES(randstr(10,10), 0, 0);
       DELETE FROM abc WHERE random()%10!=0;
       COMMIT;
     "
  } {1 {child process exited abnormally}}
  do_test crash-3.$i.2 {
    signature
  } $sig
} 

#--------------------------------------------------------------------------
# The following test cases - crash-4.* - test the correct recovery of the
# database when a crash occurs during a multi-file transaction.
#
# crash-4.1.*: Test recovery when crash occurs during sync() of the 
#              main database journal file.
# crash-4.2.*: Test recovery when crash occurs during sync() of an 
#              attached database journal file.
# crash-4.3.*: Test recovery when crash occurs during sync() of the master
#              journal file. 
#
ifcapable attach {
  do_test crash-4.0 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      ATTACH 'test2.db' AS aux;
      PRAGMA aux.default_cache_size = 10;
      CREATE TABLE aux.abc2 AS SELECT 2*a as a, 2*b as b, 2*c as c FROM abc;
    }
    expr ([file size test2.db] / 1024) > 450
  } {1}
  
  set fin 0
  for {set i 1} {$i<$repeats} {incr i} {
    set seed [expr {int(abs(rand()*10000))}]
    set sig [signature]
    set sig2 [signature2]
    do_test crash-4.1.$i.1 {
       set c [crashsql -delay $i -file test.db-journal -seed $::seed "
         ATTACH 'test2.db' AS aux;
         BEGIN;
         SELECT randstr($i,$i) FROM abc LIMIT $i;
         INSERT INTO abc VALUES(randstr(10,10), 0, 0);
         DELETE FROM abc WHERE random()%10!=0;
         INSERT INTO abc2 VALUES(randstr(10,10), 0, 0);
         DELETE FROM abc2 WHERE random()%10!=0;
         COMMIT;
       "]
       if { $c == {0 {}} } {
         set ::fin 1
         set c {1 {child process exited abnormally}}
       }
       set c
    } {1 {child process exited abnormally}}
    if {$::fin} break
    do_test crash-4.1.$i.2 {
      signature
    } $sig
    do_test crash-4.1.$i.3 {
      signature2
    } $sig2
  } 
  set i 0
  set fin 0
  while {[incr i]} {
    set seed [expr {int(abs(rand()*10000))}]
    set sig [signature]
    set sig2 [signature2]
    set ::fin 0
    do_test crash-4.2.$i.1 {
       set c [crashsql -delay $i -file test2.db-journal -seed $::seed "
         ATTACH 'test2.db' AS aux;
         BEGIN;
         SELECT randstr($i,$i) FROM abc LIMIT $i;
         INSERT INTO abc VALUES(randstr(10,10), 0, 0);
         DELETE FROM abc WHERE random()%10!=0;
         INSERT INTO abc2 VALUES(randstr(10,10), 0, 0);
         DELETE FROM abc2 WHERE random()%10!=0;
         COMMIT;
       "]
       if { $c == {0 {}} } {
         set ::fin 1
         set c {1 {child process exited abnormally}}
       }
       set c
    } {1 {child process exited abnormally}}
    if { $::fin } break
    do_test crash-4.2.$i.2 {
      signature
    } $sig
    do_test crash-4.2.$i.3 {
      signature2
    } $sig2
  } 
  for {set i 1} {$i < 5} {incr i} {
    set sig [signature]
    set sig2 [signature2]
    do_test crash-4.3.$i.1 {
       crashsql -delay 1 -file test.db-mj* "
         ATTACH 'test2.db' AS aux;
         BEGIN;
         SELECT random() FROM abc LIMIT $i;
         INSERT INTO abc VALUES(randstr(10,10), 0, 0);
         DELETE FROM abc WHERE random()%10!=0;
         INSERT INTO abc2 VALUES(randstr(10,10), 0, 0);
         DELETE FROM abc2 WHERE random()%10!=0;
         COMMIT;
       "
    } {1 {child process exited abnormally}}
    do_test crash-4.3.$i.2 {
      signature
    } $sig
    do_test crash-4.3.$i.3 {
      signature2
    } $sig2
  }
}

#--------------------------------------------------------------------------
# The following test cases - crash-5.* - exposes a bug that existed in the
# sqlite3pager_movepage() API used by auto-vacuum databases.
# database when a crash occurs during a multi-file transaction. See comments
# in test crash-5.3 for details.
#
db close
file delete -force test.db
sqlite3 db test.db
do_test crash-5.1 {
  execsql {
    CREATE TABLE abc(a, b, c);                          -- Root page 3
    INSERT INTO abc VALUES(randstr(1500,1500), 0, 0);   -- Overflow page 4
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
  }
} {}
do_test crash-5.2 {
  expr [file size test.db] / 1024
} [expr [string match [execsql {pragma auto_vacuum}] 1] ? 11 : 10]
set sig [signature]
do_test crash-5.3 {
# The SQL below is used to expose a bug that existed in
# sqlite3pager_movepage() during development of the auto-vacuum feature. It
# functions as follows:
# 
# 1: Begin a transaction.
# 2: Put page 4 on the free-list (was the overflow page for the row deleted).
# 3: Write data to page 4 (it becomes the overflow page for the row inserted).
#    The old page 4 data has been written to the journal file, but the
#    journal file has not been sync()hronized.
# 4: Create a table, which calls sqlite3pager_movepage() to move page 4
#    to the end of the database (page 12) to make room for the new root-page.
# 5: Put pressure on the pager-cache. This results in page 4 being written
#    to the database file to make space in the cache to load a new page. The
#    bug was that page 4 was written to the database file before the journal
#    is sync()hronized.
# 6: Commit. A crash occurs during the sync of the journal file.
#
# End result: Before the bug was fixed, data has been written to page 4 of the
# database file and the journal file does not contain trustworthy rollback
# data for this page.
#
  crashsql -delay 1 -file test.db-journal {
    BEGIN;                                             -- 1
    DELETE FROM abc WHERE oid = 1;                     -- 2
    INSERT INTO abc VALUES(randstr(1500,1500), 0, 0);  -- 3
    CREATE TABLE abc2(a, b, c);                        -- 4
    SELECT * FROM abc;                                 -- 5
    COMMIT;                                            -- 6
  }
} {1 {child process exited abnormally}}
integrity_check crash-5.4
do_test crash-5.5 {
  signature
} $sig

#--------------------------------------------------------------------------
# The following test cases - crash-6.* - test that a DROP TABLE operation
# is correctly rolled back in the event of a crash while the database file
# is being written. This is mainly to test that all pages are written to the
# journal file before truncation in an auto-vacuum database.
#
do_test crash-6.1 {
  crashsql -delay 1 -file test.db {
    DROP TABLE abc;
  }
} {1 {child process exited abnormally}}
do_test crash-6.2 {
  signature
} $sig

#--------------------------------------------------------------------------
# These test cases test the case where the master journal file name is 
# corrupted slightly so that the corruption has to be detected by the
# checksum.
do_test crash-7.1 {
  crashsql -delay 1 -file test.db {
    ATTACH 'test2.db' AS aux;
    BEGIN;
    INSERT INTO abc VALUES(randstr(1500,1500), 0, 0);
    INSERT INTO abc2 VALUES(randstr(1500,1500), 0, 0);
    COMMIT;
  }

  # Change the checksum value for the master journal name.
  set f [open test.db-journal a]
  fconfigure $f -encoding binary
  seek $f [expr [file size test.db-journal] - 12]
  puts -nonewline $f "\00\00\00\00"
  close $f
} {}
do_test crash-7.2 {
  signature
} $sig

finish_test

Added test/crash2.test.











































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# The focus of this file is testing the ability of the database to
# uses its rollback journal to recover intact (no database corruption)
# from a power failure during the middle of a COMMIT. Even more
# specifically, the tests in this file verify this functionality
# for storage mediums with various sector sizes.
#
# $Id: crash2.test,v 1.6 2008/08/25 07:12:29 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

db close

# This test is designed to check that the crash-test infrastructure
# can create files that do not consist of an integer number of
# simulated disk blocks (i.e. 3KB file using 2KB disk blocks).
#
do_test crash2-1.1 {
  crashsql -delay 500 -file test.db -blocksize 2048 {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    BEGIN;
    CREATE TABLE abc AS SELECT 1 AS a, 2 AS b, 3 AS c;
    CREATE TABLE def AS SELECT 1 AS d, 2 AS e, 3 AS f;
    COMMIT;
  }
  file size test.db
} {3072}

for {set ii 0} {$ii < 5} {incr ii} {

  # Simple test using the database created above: Create a new
  # table so that page 1 and page 4 are modified. Using a
  # block-size of 2048 and page-size of 1024, this means
  # pages 2 and 3 must also be saved in the journal to avoid
  # risking corruption.
  #
  # The loop is so that this test can be run with a couple
  # of different seeds for the random number generator.
  #
  do_test crash2-1.2.$ii {
    crashsql -file test.db -blocksize 2048 [subst {
      [string repeat {SELECT random();} $ii]
      CREATE TABLE hij(h, i, j);
    }]
    sqlite3 db test.db
    db eval {PRAGMA integrity_check}
  } {ok}
}

proc signature {} {
  return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}]
}

# Test case for crashing during journal sync with simulated
# sector-size values from 1024 to 8192.
#
do_test crash2-2.0 {
  execsql BEGIN
  for {set n 0} {$n < 1000} {incr n} {
    execsql "INSERT INTO abc VALUES($n, [expr 2*$n], [expr 3*$n])"
  }
  execsql {
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
  }
  execsql COMMIT
  expr ([file size test.db] / 1024) > 450
} {1}
for {set i 1} {$i < 30} {incr i} {
  set sig [signature]
  set sector [expr 1024 * 1<<($i%4)]
  db close
  do_test crash2-2.$i.1 {
     crashsql -blocksize $sector -delay [expr $i%5 + 1] -file test.db-journal "
       PRAGMA temp_store = memory;
       BEGIN;
       SELECT random() FROM abc LIMIT $i;
       INSERT INTO abc SELECT randstr(10,10), 0, 0 FROM abc WHERE random()%2==0;
       DELETE FROM abc WHERE random()%2!=0;
       COMMIT;
     "
  } {1 {child process exited abnormally}}
  do_test crash2-2.$i.2 {
    sqlite3 db test.db
    signature
  } $sig
} 


# Test case for crashing during database sync with simulated
# sector-size values from 1024 to 8192.
#
for {set i 1} {$i < 10} {incr i} {
  set sig [signature]
  set sector [expr 1024 * 1<<($i%4)]
  db close
  do_test crash2-3.$i.1 {
     crashsql -blocksize $sector -file test.db "
       BEGIN;
       SELECT random() FROM abc LIMIT $i;
       INSERT INTO abc SELECT randstr(10,10), 0, 0 FROM abc WHERE random()%2==0;
       DELETE FROM abc WHERE random()%2!=0;
       COMMIT;
     "
  } {1 {child process exited abnormally}}
  do_test crash2-3.$i.2 {
    sqlite3 db test.db
    signature
  } $sig
} 

finish_test

Added test/crash3.test.





























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# 2007 August 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains tests that verify that SQLite can correctly rollback
# databases after crashes when using the special IO modes triggered 
# by device IOCAP flags.
#
# $Id: crash3.test,v 1.4 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

proc do_test2 {name tcl res1 res2} {
  set script [subst -nocommands {
    do_test $name {
      set res1 {$res1}
      set res2 {$res2}
      set res [eval {$tcl}]
      if {[set res] eq [set res1] || [set res] eq [set res2]} {
        set res "{[set res1]} or {[set res2]}"
      }
      set res
    } {{$res1} or {$res2}}
  }]
  uplevel $script
}

# This block tests crash-recovery when the IOCAP_ATOMIC flags is set.
#
# Each iteration of the following loop sets up the database to contain
# the following schema and data:
#
#    CREATE TABLE abc(a, b, c);
#    INSERT INTO abc VALUES(1, 2, 3);
#
# Then execute the SQL statement, scheduling a crash for part-way through
# the first sync() of either the database file or the journal file (often
# the journal file is not required - meaning no crash occurs).
#
# After the crash (or absence of a crash), open the database and 
# verify that:
#
#   * The integrity check passes, and
#   * The contents of table abc is either {1 2 3} or the value specified
#     to the right of the SQL statement below.
#
# The procedure is repeated 10 times for each SQL statement. Five times
# with the crash scheduled for midway through the first journal sync (if 
# any), and five times with the crash midway through the database sync.
#
set tn 1
foreach {sql res2} [list \
  {INSERT INTO abc VALUES(4, 5, 6)}                    {1 2 3 4 5 6} \
  {DELETE FROM abc}                                    {}    \
  {INSERT INTO abc SELECT * FROM abc}                  {1 2 3 1 2 3} \
  {UPDATE abc SET a = 2}                               {2 2 3}       \
  {INSERT INTO abc VALUES(4, 5, randstr(1000,1000))}   {n/a} \
  {CREATE TABLE def(d, e, f)}                          {n/a} \
] {
  for {set ii 0} {$ii < 10} {incr ii} {

    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    do_test crash3-1.$tn.1 {
      execsql {
        PRAGMA page_size = 1024;
        BEGIN;
        CREATE TABLE abc(a, b, c);
        INSERT INTO abc VALUES(1, 2, 3);
        COMMIT;
      }
    } {}
    db close
  
    set crashfile test.db
    if {($ii%2)==0} { append crashfile -journal }
    set rand "SELECT randstr($tn,$tn);"
    do_test crash3-1.$tn.2 [subst {
      crashsql -file $crashfile -char atomic {$rand $sql}
      sqlite3 db test.db
      execsql { PRAGMA integrity_check; }
    }] {ok}
  
    do_test2 crash3-1.$tn.3 {
      execsql { SELECT * FROM abc }
    } {1 2 3} $res2

    incr tn
  }
}

# This block tests both the IOCAP_SEQUENTIAL and IOCAP_SAFE_APPEND flags.
#
db close
file delete -force test.db test.db-journal
sqlite3 db test.db
do_test crash3-2.0 {
  execsql {
    BEGIN;
    CREATE TABLE abc(a PRIMARY KEY, b, c);
    CREATE TABLE def(d PRIMARY KEY, e, f);
    PRAGMA default_cache_size = 10;
    INSERT INTO abc VALUES(randstr(10,1000),randstr(10,1000),randstr(10,1000));
    INSERT INTO abc 
      SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc;
    INSERT INTO abc 
      SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc;
    INSERT INTO abc 
      SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc;
    INSERT INTO abc 
      SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc;
    INSERT INTO abc 
      SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc;
    INSERT INTO abc 
      SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc;
    COMMIT;
  }
} {}

set tn 1
foreach {::crashfile ::delay ::char} {
  test.db         1 sequential
  test.db         1 safe_append
  test.db-journal 1 sequential
  test.db-journal 1 safe_append
  test.db-journal 2 safe_append
  test.db-journal 2 sequential
  test.db-journal 3 sequential
  test.db-journal 3 safe_append
} {
  for {set ii 0} {$ii < 100} {incr ii} {
    set ::SQL [subst {
      SELECT randstr($ii,$ii+10);
      BEGIN;
      DELETE FROM abc WHERE random()%5;
      INSERT INTO abc 
        SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) 
        FROM abc
        WHERE (random()%5)==0;
      DELETE FROM def WHERE random()%5;
      INSERT INTO def 
        SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) 
        FROM def
        WHERE (random()%5)==0;
      COMMIT;
    }]

    do_test crash3-2.$tn.$ii {
      crashsql -file $::crashfile -delay $::delay -char $::char $::SQL
      db close
      sqlite3 db test.db
      execsql {PRAGMA integrity_check}
    } {ok}
  }
  incr tn
}

# The following block tests an interaction between IOCAP_ATOMIC and
# IOCAP_SEQUENTIAL. At one point, if both flags were set, small
# journal files that contained only a single page, but were required 
# for some other reason (i.e. nTrunk) were not being written to
# disk.
#
for {set ii 0} {$ii < 10} {incr ii} {
  db close
  file delete -force test.db test.db-journal
  crashsql -file test.db -char {sequential atomic} {
    CREATE TABLE abc(a, b, c);
  }
  sqlite3 db test.db
  do_test crash3-3.$ii {
    execsql {PRAGMA integrity_check}
  } {ok}
}

finish_test

Added test/crash4.test.













































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# 2008 January 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains additional tests to verify that SQLite database
# file survive a power loss or OS crash.
#
# $Id: crash4.test,v 1.3 2008/01/16 17:46:38 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}


# A sequence of SQL commands:
#
set sql_cmd_list {
  {CREATE TABLE a(id INTEGER, name CHAR(50))}
  {INSERT INTO a(id,name) VALUES(1,'one')}
  {INSERT INTO a(id,name) VALUES(2,'two')}
  {INSERT INTO a(id,name) VALUES(3,'three')}
  {INSERT INTO a(id,name) VALUES(4,'four')}
  {INSERT INTO a(id,name) VALUES(5,'five')}
  {INSERT INTO a(id,name) VALUES(6,'six')}
  {INSERT INTO a(id,name) VALUES(7,'seven')}
  {INSERT INTO a(id,name) VALUES(8,'eight')}
  {INSERT INTO a(id,name) VALUES(9,'nine')}
  {INSERT INTO a(id,name) VALUES(10,'ten')}
  {UPDATE A SET name='new text for row 3' WHERE id=3}
}

# Assume that a database is created by evaluating the SQL statements
# in $sql_cmd_list.  Compute a set of checksums that capture the state
# of the database after each statement.  Also include a checksum for
# the state of the database prior to any of these statements.
#
set crash4_cksum_set {}
lappend crash4_cksum_set [allcksum db]
foreach cmd $sql_cmd_list {
  db eval $cmd
  lappend crash4_cksum_set [allcksum db]
}

# Run the sequence of SQL statements shown above repeatedly.
# Close and reopen the database right before the UPDATE statement.
# On each repetition, introduce database corruption typical of
# what might be seen in a power loss or OS crash.  
#
# Slowly increase the delay before the crash, repeating the test
# over and over.  Stop testing when the entire sequence of SQL
# statements runs to completing without hitting the crash.
#
for {set cnt 1; set fin 0} {!$fin} {incr cnt} {
  db close
  file delete -force test.db test.db-journal
  do_test crash4-1.$cnt.1 {
    set seed [expr {int(abs(rand()*10000))}]
    set delay [expr {int($cnt/50)+1}]
    set file [expr {($cnt&1)?"test.db":"test.db-journal"}]
    set c [crashsql -delay $delay -file $file -seed $seed -tclbody {
      db eval {CREATE TABLE a(id INTEGER, name CHAR(50))}
      db eval {INSERT INTO a(id,name) VALUES(1,'one')}
      db eval {INSERT INTO a(id,name) VALUES(2,'two')}
      db eval {INSERT INTO a(id,name) VALUES(3,'three')}
      db eval {INSERT INTO a(id,name) VALUES(4,'four')}
      db eval {INSERT INTO a(id,name) VALUES(5,'five')}
      db eval {INSERT INTO a(id,name) VALUES(6,'six')}
      db eval {INSERT INTO a(id,name) VALUES(7,'seven')}
      db eval {INSERT INTO a(id,name) VALUES(8,'eight')}
      db eval {INSERT INTO a(id,name) VALUES(9,'nine')}
      db eval {INSERT INTO a(id,name) VALUES(10,'ten')}
      db close
      sqlite3 db test.db
      db eval {UPDATE A SET name='new text for row 3' WHERE id=3}
      db close
    } {}]
    if {$c==[list 0 {}]} {
      set ::fin 1
      set c [list 1 {child process exited abnormally}]
    }
    set c
  } {1 {child process exited abnormally}}
  sqlite3 db test.db
  integrity_check crash4-1.$cnt.2
  do_test crash4-1.$cnt.3 {
    set x [lsearch $::crash4_cksum_set [allcksum db]]
    expr {$x>=0}
  } {1}
}

finish_test

Added test/crash5.test.





























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

# 2007 Aug 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# 
# This file tests aspects of recovery from a malloc() failure
# in a CREATE INDEX statement.
#
# $Id: crash5.test,v 1.3 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only run these tests if memory debugging is turned on.
#
ifcapable !memdebug||!crashtest||!memorymanage {
   puts "Skipping crash5 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

db close

for {set ii 0} {$ii < 10} {incr ii} {
  for {set jj 50} {$jj < 100} {incr jj} {

    # Set up the database so that it is an auto-vacuum database 
    # containing a single table (root page 3) with a single row. 
    # The row has an overflow page (page 4).
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    set c [string repeat 3 1500]
    db eval {
      pragma auto_vacuum = 1;
      CREATE TABLE t1(a, b, c);
      INSERT INTO t1 VALUES('1111111111', '2222222222', $c);
    }
    db close

    do_test crash5-$ii.$jj.1 {
      crashsql -delay 1 -file test.db-journal -seed $ii -tclbody [join [list \
        [list set iFail $jj] {
        sqlite3_crashparams 0 [file join [pwd] test.db-journal]
      
        # Begin a transaction and evaluate a "CREATE INDEX" statement
        # with the iFail'th malloc() set to fail. This operation will
        # have to move the current contents of page 4 (the overflow
        # page) to make room for the new root page. The bug is that
        # if malloc() fails at a particular point in sqlite3PagerMovepage(),
        # sqlite mistakenly thinks that the page being moved (page 4) has 
        # been safely synced into the journal. If the page is written
        # to later in the transaction, it may be written out to the database
        # before the relevant part of the journal has been synced.
        #
        db eval BEGIN
        sqlite3_memdebug_fail $iFail -repeat 0
        catch {db eval { CREATE UNIQUE INDEX i1 ON t1(a); }} msg
        # puts "$n $msg ac=[sqlite3_get_autocommit db]"
      
        # If the transaction is still active (it may not be if the malloc()
        # failure occured in the OS layer), write to the database. Make sure
        # page 4 is among those written.
        #
        if {![sqlite3_get_autocommit db]} {
          db eval {
            DELETE FROM t1;  -- This will put page 4 on the free list.
            INSERT INTO t1 VALUES('111111111', '2222222222', '33333333');
            INSERT INTO t1 SELECT * FROM t1;                     -- 2
            INSERT INTO t1 SELECT * FROM t1;                     -- 4
            INSERT INTO t1 SELECT * FROM t1;                     -- 8
            INSERT INTO t1 SELECT * FROM t1;                     -- 16
            INSERT INTO t1 SELECT * FROM t1;                     -- 32
            INSERT INTO t1 SELECT * FROM t1 WHERE rowid%2;       -- 48
          }
        }
        
        # If the right malloc() failed during the 'CREATE INDEX' above and
        # the transaction was not rolled back, then the sqlite cache now 
        # has a dirty page 4 that it incorrectly believes is already safely
        # in the synced part of the journal file. When 
        # sqlite3_release_memory() is called sqlite tries to free memory
        # by writing page 4 out to the db file. If it crashes later on,
        # before syncing the journal... Corruption!
        #
        sqlite3_crashparams 1 [file join [pwd] test.db-journal]
        sqlite3_release_memory 8092
      }]] {}
      expr 1
    } {1}
  
    sqlite3 db test.db
    do_test crash5-$ii.$jj.2 {
      db eval {pragma integrity_check}
    } {ok}
    do_test crash5-$ii.$jj.3 {
      db eval {SELECT * FROM t1}
    } [list 1111111111 2222222222 $::c]
    db close
  }
}


finish_test

Added test/crash6.test.













































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file tests that rollback journals for databases that use a 
# page-size other than the default page-size can be rolled back Ok.
#
# $Id: crash6.test,v 1.2 2008/04/14 15:27:19 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

for {set ii 0} {$ii < 10} {incr ii} {
  catch {db close}
  file delete -force test.db test.db-journal
  crashsql -delay 2 -file test.db {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=4096;
    BEGIN;
    CREATE TABLE abc AS SELECT 1 AS a, 2 AS b, 3 AS c;
    COMMIT;
    BEGIN;
    CREATE TABLE def AS SELECT 1 AS d, 2 AS e, 3 AS f;
    COMMIT;
  }
  sqlite3 db test.db
  integrity_check crash6-1.$ii
}

for {set ii 0} {$ii < 10} {incr ii} {
  catch {db close}
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=2048;
    BEGIN;
    CREATE TABLE abc AS SELECT 1 AS a, 2 AS b, 3 AS c;
    COMMIT;
  }
  db close
  crashsql -delay 1 -file test.db {
    INSERT INTO abc VALUES(5, 6, 7);
  }
  sqlite3 db test.db
  integrity_check crash6-2.$ii
}

proc signature {} {
  return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}]
}

# Test case for crashing during database sync with page-size values 
# from 1024 to 8192.
#
for {set ii 0} {$ii < 30} {incr ii} {
  db close
  file delete -force test.db
  sqlite3 db test.db

  set pagesize [expr 1024 << ($ii % 4)]
  if {$pagesize>$::SQLITE_MAX_PAGE_SIZE} {
    set pagesize $::SQLITE_MAX_PAGE_SIZE
  }
  do_test crash6-3.$ii.0 {
    execsql "pragma page_size = $pagesize"
    execsql "pragma page_size"
  } $pagesize

  do_test crash6-3.$ii.1 {
  
    execsql BEGIN
    execsql {CREATE TABLE abc(a, b, c)}
    for {set n 0} {$n < 1000} {incr n} {
      execsql "INSERT INTO abc VALUES($n, [expr 2*$n], [expr 3*$n])"
    }
    execsql {
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
    }
    execsql COMMIT
    expr ([file size test.db] / 1024) > 450
  } {1}

  set sig [signature]
  db close

  do_test crash6-3.$ii.2 {
     crashsql -file test.db "
       BEGIN;
       SELECT random() FROM abc LIMIT $ii;
       INSERT INTO abc SELECT randstr(10,10), 0, 0 FROM abc WHERE random()%2==0;
       DELETE FROM abc WHERE random()%2!=0;
       COMMIT;
     "
  } {1 {child process exited abnormally}}

  do_test crash6-3.$ii.3 {
    sqlite3 db test.db
    signature
  } $sig
} 

finish_test

Added test/crash7.test.





































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# 2008 March 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: crash7.test,v 1.1 2008/04/03 14:36:26 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

proc signature {} {
  return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}]
}

foreach f [list test.db test.db-journal] {
  for {set ii 1} {$ii < 64} {incr ii} {
    db close
    file delete test.db
    sqlite3 db test.db
  
    set from_size [expr 1024 << ($ii&3)]
    set to_size   [expr 1024 << (($ii>>2)&3)]
  
    execsql "
      PRAGMA page_size = $from_size;
      BEGIN;
      CREATE TABLE abc(a PRIMARY KEY, b, c);
      INSERT INTO abc VALUES(randomblob(100), randomblob(200), randomblob(1000));
      INSERT INTO abc 
          SELECT randomblob(1000), randomblob(200), randomblob(100)
          FROM abc;
      INSERT INTO abc 
          SELECT randomblob(100), randomblob(200), randomblob(1000)
          FROM abc;
      INSERT INTO abc 
          SELECT randomblob(100), randomblob(200), randomblob(1000)
          FROM abc;
      INSERT INTO abc 
          SELECT randomblob(100), randomblob(200), randomblob(1000)
          FROM abc;
      INSERT INTO abc 
          SELECT randomblob(100), randomblob(200), randomblob(1000)
          FROM abc WHERE [expr $ii&16];
      INSERT INTO abc 
          SELECT randomblob(25), randomblob(45), randomblob(9456)
          FROM abc WHERE [expr $ii&32];
      INSERT INTO abc 
          SELECT randomblob(100), randomblob(200), randomblob(1000)
          FROM abc WHERE [expr $ii&8];
      INSERT INTO abc 
          SELECT randomblob(25), randomblob(45), randomblob(9456)
          FROM abc WHERE [expr $ii&4];
      COMMIT;
    "
  
    set sig [signature]
    db close
  
    do_test crash7-1.$ii.crash {
       crashsql -file $f "
         PRAGMA page_size = $to_size;
         VACUUM;
       "
    } {1 {child process exited abnormally}}
  
    sqlite3 db test.db
    integrity_check crash7-1.$ii.integrity
  } 
}

finish_test

Added test/crash8.test.















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# 2009 January 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test verifies a couple of specific potential data corruption 
# scenarios involving crashes or power failures.
#
# Later: Also, some other specific scenarios required for coverage
# testing that do not lead to corruption.
#
# $Id: crash8.test,v 1.4 2009/01/11 00:44:48 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

do_test crash8-1.1 {
  execsql {
    PRAGMA auto_vacuum=OFF;
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a, b);
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 VALUES(2, randstr(1000,1000));
    INSERT INTO t1 VALUES(3, randstr(1000,1000));
    INSERT INTO t1 VALUES(4, randstr(1000,1000));
    INSERT INTO t1 VALUES(5, randstr(1000,1000));
    INSERT INTO t1 VALUES(6, randstr(1000,1000));
    CREATE TABLE t2(a, b);
    CREATE TABLE t3(a, b);
    CREATE TABLE t4(a, b);
    CREATE TABLE t5(a, b);
    CREATE TABLE t6(a, b);
    CREATE TABLE t7(a, b);
    CREATE TABLE t8(a, b);
    CREATE TABLE t9(a, b);
    CREATE TABLE t10(a, b);
    PRAGMA integrity_check
  }
} {ok}


# Potential corruption scenario 1. A second process opens the database 
# and modifies a large portion of it. It then opens a second transaction
# and modifies a small part of the database, but crashes before it commits
# the transaction. 
#
# When the first process accessed the database again, it was rolling back
# the aborted transaction, but was not purging its in-memory cache (which
# was loaded before the second process made its first, successful, 
# modification). Producing an inconsistent cache.
#
do_test crash8-1.2 {
  crashsql -delay 2 -file test.db {
    PRAGMA cache_size = 10;
    UPDATE t1 SET b = randstr(1000,1000);
    INSERT INTO t9 VALUES(1, 2);
  }
} {1 {child process exited abnormally}}
do_test crash8-1.3 {
  execsql {PRAGMA integrity_check}
} {ok}

# Potential corruption scenario 2. The second process, operating in
# persistent-journal mode, makes a large change to the database file
# with a small in-memory cache. Such that more than one journal-header
# was written to the file. It then opens a second transaction and makes
# a smaller change that requires only a single journal-header to be
# written to the journal file. The second change is such that the 
# journal content written to the persistent journal file exactly overwrites
# the first journal-header and set of subsequent records written by the
# first, successful, change. The second process crashes before it can
# commit its second change.
#
# When the first process accessed the database again, it was rolling back
# the second aborted transaction, then continuing to rollback the second
# and subsequent journal-headers written by the first, successful, change.
# Database corruption.
#
do_test crash8.2.1 {
  crashsql -delay 2 -file test.db {
    PRAGMA journal_mode = persist;
    PRAGMA cache_size = 10;
    UPDATE t1 SET b = randstr(1000,1000);
    PRAGMA cache_size = 100;
    BEGIN;
      INSERT INTO t2 VALUES('a', 'b');
      INSERT INTO t3 VALUES('a', 'b');
      INSERT INTO t4 VALUES('a', 'b');
      INSERT INTO t5 VALUES('a', 'b');
      INSERT INTO t6 VALUES('a', 'b');
      INSERT INTO t7 VALUES('a', 'b');
      INSERT INTO t8 VALUES('a', 'b');
      INSERT INTO t9 VALUES('a', 'b');
      INSERT INTO t10 VALUES('a', 'b');
    COMMIT;
  }
} {1 {child process exited abnormally}}

do_test crash8-2.3 {
  execsql {PRAGMA integrity_check}
} {ok}

proc read_file {zFile} {
  set fd [open $zFile]
  fconfigure $fd -translation binary 
  set zData [read $fd]
  close $fd
  return $zData
}
proc write_file {zFile zData} {
  set fd [open $zFile w]
  fconfigure $fd -translation binary 
  puts -nonewline $fd $zData
  close $fd
}

# The following tests check that SQLite will not roll back a hot-journal
# file if the sector-size field in the first journal file header is
# suspect. Definition of suspect:
# 
#    a) Not a power of 2, or                (crash8-3.5)
#    b) Greater than 0x01000000 (16MB), or  (crash8-3.6)
#    c) Less than 512.                      (crash8-3.7)
#
# Also test that SQLite will not rollback a hot-journal file with a
# suspect page-size. In this case "suspect" means:
# 
#    a) Not a power of 2, or
#    b) Less than 512, or
#    c) Greater than SQLITE_MAX_PAGE_SIZE
#
do_test crash8-3.1 {
  list [file exists test.db-joural] [file exists test.db]
} {0 1}
do_test crash8-3.2 {
  execsql {
    PRAGMA synchronous = off;
    BEGIN;
    DELETE FROM t1;
    SELECT count(*) FROM t1;
  }
} {0}
do_test crash8-3.3 {
  set zJournal [read_file test.db-journal]
  execsql { 
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {0}
do_test crash8-3.4 {
  binary scan [string range $zJournal 20 23] I nSector
  set nSector
} {512}

do_test crash8-3.5 {
  set zJournal2 [string replace $zJournal 20 23 [binary format I 513]]
  write_file test.db-journal $zJournal2

  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {0 ok}
do_test crash8-3.6 {
  set zJournal2 [string replace $zJournal 20 23 [binary format I 0x2000000]]
  write_file test.db-journal $zJournal2
  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {0 ok}
do_test crash8-3.7 {
  set zJournal2 [string replace $zJournal 20 23 [binary format I 256]]
  write_file test.db-journal $zJournal2
  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {0 ok}

do_test crash8-3.8 {
  set zJournal2 [string replace $zJournal 24 27 [binary format I 513]]
  write_file test.db-journal $zJournal2

  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {0 ok}
do_test crash8-3.9 {
  set big [expr $SQLITE_MAX_PAGE_SIZE * 2]
  set zJournal2 [string replace $zJournal 24 27 [binary format I $big]]
  write_file test.db-journal $zJournal2
  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {0 ok}
do_test crash8-3.10 {
  set zJournal2 [string replace $zJournal 24 27 [binary format I 256]]
  write_file test.db-journal $zJournal2
  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {0 ok}

do_test crash8-3.11 {
  set fd [open test.db-journal w]
  fconfigure $fd -translation binary 
  puts -nonewline $fd $zJournal
  close $fd
  execsql { 
    SELECT count(*) FROM t1;
    PRAGMA integrity_check
  }
} {6 ok}


# If a connection running in persistent-journal mode is part of a 
# multi-file transaction, it must ensure that the master-journal name
# appended to the journal file contents during the commit is located
# at the end of the physical journal file. If there was already a
# large journal file allocated at the start of the transaction, this
# may mean truncating the file so that the master journal name really
# is at the physical end of the file.
#
# This block of tests test that SQLite correctly truncates such
# journal files, and that the results behave correctly if a hot-journal
# rollback occurs.
#
ifcapable pragma {
  reset_db
  file delete -force test2.db

  do_test crash8-4.1 {
    execsql {
      PRAGMA journal_mode = persist;
      CREATE TABLE ab(a, b);
      INSERT INTO ab VALUES(0, 'abc');
      INSERT INTO ab VALUES(1, NULL);
      INSERT INTO ab VALUES(2, NULL);
      INSERT INTO ab VALUES(3, NULL);
      INSERT INTO ab VALUES(4, NULL);
      INSERT INTO ab VALUES(5, NULL);
      INSERT INTO ab VALUES(6, NULL);
      UPDATE ab SET b = randstr(1000,1000);
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.ab(a, b);
      INSERT INTO aux.ab SELECT * FROM main.ab;

      UPDATE aux.ab SET b = randstr(1000,1000) WHERE a>=1;
      UPDATE ab SET b = randstr(1000,1000) WHERE a>=1;
    }
    list [file exists test.db-journal] [file exists test2.db-journal]
  } {1 1}

  do_test crash8-4.2 {
    execsql {
      BEGIN;
        UPDATE aux.ab SET b = 'def' WHERE a = 0;
        UPDATE main.ab SET b = 'def' WHERE a = 0;
      COMMIT;
    }
  } {}

  do_test crash8-4.3 {
    execsql {
      UPDATE aux.ab SET b = randstr(1000,1000) WHERE a>=1;
      UPDATE ab SET b = randstr(1000,1000) WHERE a>=1;
    }
  } {}

  set contents_main [db eval {SELECT b FROM main.ab WHERE a = 1}]
  set contents_aux  [db eval {SELECT b FROM  aux.ab WHERE a = 1}]

  do_test crash8-4.4 {
    crashsql -file test2.db -delay 1 {
      ATTACH 'test2.db' AS aux;
      BEGIN;
        UPDATE aux.ab SET b = 'ghi' WHERE a = 0;
        UPDATE main.ab SET b = 'ghi' WHERE a = 0;
      COMMIT;
    }
  } {1 {child process exited abnormally}}

  do_test crash8-4.5 {
    list [file exists test.db-journal] [file exists test2.db-journal]
  } {1 1}

  do_test crash8-4.6 {
    execsql {
      SELECT b FROM main.ab WHERE a = 0;
      SELECT b FROM aux.ab WHERE a = 0;
    }
  } {def def}

  do_test crash8-4.7 {
    crashsql -file test2.db -delay 1 {
      ATTACH 'test2.db' AS aux;
      BEGIN;
        UPDATE aux.ab SET b = 'jkl' WHERE a = 0;
        UPDATE main.ab SET b = 'jkl' WHERE a = 0;
      COMMIT;
    }
  } {1 {child process exited abnormally}}

  do_test crash8-4.8 {
    set fd [open test.db-journal]
    fconfigure $fd -translation binary
    seek $fd -16 end
    binary scan [read $fd 4] I len

    seek $fd [expr {-1 * ($len + 16)}] end
    set zMasterJournal [read $fd $len]
    close $fd

    file exists $zMasterJournal
  } {1}

  do_test crash8-4.9 {
    execsql { SELECT b FROM aux.ab WHERE a = 0 }
  } {def}

  do_test crash8-4.10 {
    file delete $zMasterJournal
    execsql { SELECT b FROM main.ab WHERE a = 0 }
  } {jkl}
}

finish_test

Added test/crashtest1.c.

































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
** This program tests the ability of SQLite database to recover from a crash.
** This program runs under Unix only, but the results are applicable to all
** systems.
**
** The main process first constructs a test database, then starts creating
** subprocesses that write to that database.  Each subprocess is killed off,
** without a chance to clean up its database connection, after a random
** delay.  This killing of the subprocesses simulates a crash or power
** failure.  The next subprocess to open the database should rollback
** whatever operation was in process at the time of the simulated crash.
**
** If any problems are encountered, an error is reported and the test stops.
** If no problems are seen after a large number of tests, we assume that
** the rollback mechanism is working.
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include "sqlite.h"

static void do_some_sql(int parent){
  char *zErr;
  int rc = SQLITE_OK;
  sqlite *db;
  int cnt = 0;
  static char zBig[] = 
    "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  if( access("./test.db-journal",0)==0 ){
    /*printf("pid %d: journal exists.  rollback will be required\n",getpid());*/    unlink("test.db-saved");
    system("cp test.db test.db-saved");
    unlink("test.db-journal-saved");
    system("cp test.db-journal test.db-journal-saved");
  }
  db = sqlite_open("./test.db", 0, &zErr);
  if( db==0 ){
    printf("ERROR: %s\n", zErr);
    if( strcmp(zErr,"database disk image is malformed")==0 ){
      kill(parent, SIGKILL);
    }
    exit(1);
  }
  srand(getpid());
  while( rc==SQLITE_OK ){
    cnt++;
    rc = sqlite_exec_printf(db, 
       "INSERT INTO t1 VALUES(%d,'%d%s')", 0, 0, &zErr,
       rand(), rand(), zBig);
  }
  if( rc!=SQLITE_OK ){
    printf("ERROR #%d: %s\n", rc, zErr);
    if( rc==SQLITE_CORRUPT ){
      kill(parent, SIGKILL);
    }
  }
  printf("pid %d: cnt=%d\n", getpid(), cnt);
}


int main(int argc, char **argv){
  int i;
  sqlite *db;
  char *zErr;
  int status;
  int parent = getpid();

  unlink("test.db");
  unlink("test.db-journal");
  db = sqlite_open("test.db", 0, &zErr);
  if( db==0 ){
    printf("Cannot initialize: %s\n", zErr);
    return 1;
  }
  sqlite_exec(db, "CREATE TABLE t1(a,b)", 0, 0, 0);
  sqlite_close(db);
  for(i=0; i<10000; i++){
    int pid = fork();
    if( pid==0 ){
      sched_yield();
      do_some_sql(parent);
      return 0;
    }
    printf("test %d, pid=%d\n", i, pid);
    usleep(rand()%10000 + 1000);
    kill(pid, SIGKILL);
    waitpid(pid, &status, 0);
  }
  return 0;
}

Added test/createtab.test.





































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# 2007 May 02
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing that it is OK to create new tables
# and indices while creating existing tables and indices.
#
# $Id: createtab.test,v 1.3 2007/09/12 17:01:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable autovacuum {
  set upperBound 2
} else {
  set upperBound 0
}

# Run these tests for all possible values of autovacuum.
#
for {set av 0} {$av<=$upperBound} {incr av} {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db

  # Create a table that spans multiple pages.  It is important
  # that part of the database be in pages beyond the root page.
  #
  do_test createtab-$av.1 {
    execsql "PRAGMA auto_vacuum=$av"
    execsql {
      PRAGMA page_size=1024;
      CREATE TABLE t1(x INTEGER PRIMARY KEY, y);
      INSERT INTO t1 VALUES(1, hex(randomblob(200)));
      INSERT INTO t1 VALUES(2, hex(randomblob(200)));
      INSERT INTO t1 VALUES(3, hex(randomblob(200)));
      INSERT INTO t1 VALUES(4, hex(randomblob(200)));
      SELECT count(*) FROM t1;
    }
  } {4}

  set isUtf16 0
  ifcapable utf16 { 
    set isUtf16 [expr {[execsql {PRAGMA encoding}] != "UTF-8"}]
  }

  do_test createtab-$av.2 {
    file size test.db
  } [expr {1024*(4+($av!=0)+(${isUtf16}*2))}]
  
  # Start reading the table
  #
  do_test createtab-$av.3 {
    set STMT [sqlite3_prepare db {SELECT x FROM t1} -1 TAIL]
    sqlite3_step $STMT
  } {SQLITE_ROW}
  do_test createtab-$av.4 {
    sqlite3_column_int $STMT 0
  } {1}
  
  # While still reading the table, create a new table.
  #
  do_test createtab-$av.5 {
    execsql {
      CREATE TABLE t2(a,b);
      INSERT INTO t2 VALUES(1,2);
      SELECT * FROM t2;
    }
  } {1 2}
  
  # Continue reading the original table.
  #
  do_test createtab-$av.6 {
    sqlite3_column_int $STMT 0
  } {1}
  do_test createtab-$av.7 {
    sqlite3_step $STMT
  } {SQLITE_ROW}
  do_test createtab-$av.8 {
    sqlite3_column_int $STMT 0
  } {2}
  
  # Do another cycle of creating a new database table while contining
  # to read the original table.
  #
  do_test createtab-$av.11 {
    execsql {
      CREATE TABLE t3(a,b);
      INSERT INTO t3 VALUES(4,5);
      SELECT * FROM t3;
    }
  } {4 5}
  do_test createtab-$av.12 {
    sqlite3_column_int $STMT 0
  } {2}
  do_test createtab-$av.13 {
    sqlite3_step $STMT
  } {SQLITE_ROW}
  do_test createtab-$av.14 {
    sqlite3_column_int $STMT 0
  } {3}
  
  # One more cycle.
  #
  do_test createtab-$av.21 {
    execsql {
      CREATE TABLE t4(a,b);
      INSERT INTO t4 VALUES('abc','xyz');
      SELECT * FROM t4;
    }
  } {abc xyz}
  do_test createtab-$av.22 {
    sqlite3_column_int $STMT 0
  } {3}
  do_test createtab-$av.23 {
    sqlite3_step $STMT
  } {SQLITE_ROW}
  do_test createtab-$av.24 {
    sqlite3_column_int $STMT 0
  } {4}
  
  # Finish reading.  Do an integrity check on the database.
  #
  do_test createtab-$av.30 {
    sqlite3_step $STMT
  } {SQLITE_DONE}
  do_test createtab-$av.31 {
    sqlite3_finalize $STMT
  } {SQLITE_OK}
  do_test createtab-$av.32 {
    execsql {
      SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1
    }
  } {t1 t2 t3 t4}
  integrity_check createtab-$av.40

}
  
finish_test

Added test/cse.test.

































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# 2008 April 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test cases designed to exercise and verify the logic for
# factoring constant expressions out of loops and for
# common subexpression eliminations.
#
# $Id: cse.test,v 1.6 2008/08/04 03:51:24 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test cse-1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, d, e, f);
    INSERT INTO t1 VALUES(1,11,12,13,14,15);
    INSERT INTO t1 VALUES(2,21,22,23,24,25);
  }
  execsql {
    SELECT b, -b, ~b, NOT b, NOT NOT b, b-b, b+b, b*b, b/b, b FROM t1
  }
} {11 -11 -12 0 1 0 22 121 1 11 21 -21 -22 0 1 0 42 441 1 21}
do_test cse-1.2 {
  execsql {
    SELECT b, b%b, b==b, b!=b, b<b, b<=b, b IS NULL, b NOT NULL, b FROM t1
  }
} {11 0 1 0 0 1 0 1 11 21 0 1 0 0 1 0 1 21}
do_test cse-1.3 {
  execsql {
    SELECT b, abs(b), coalesce(b,-b,NOT b,c,NOT c), c, -c FROM t1;
  }
} {11 11 11 12 -12 21 21 21 22 -22}
do_test cse-1.4 {
  execsql {
    SELECT CASE WHEN a==1 THEN b ELSE c END, b, c FROM t1
  }
} {11 11 12 22 21 22}
do_test cse-1.5 {
  execsql {
    SELECT CASE a WHEN 1 THEN b WHEN 2 THEN c ELSE d END, b, c, d FROM t1
  }
} {11 11 12 13 22 21 22 23}
do_test cse-1.6.1 {
  execsql {
    SELECT CASE b WHEN 11 THEN -b WHEN 21 THEN -c ELSE -d END, b, c, d FROM t1
  }
} {-11 11 12 13 -22 21 22 23}
do_test cse-1.6.2 {
  execsql {
    SELECT CASE b+1 WHEN c THEN d WHEN e THEN f ELSE 999 END, b, c, d FROM t1
  }
} {13 11 12 13 23 21 22 23}
do_test cse-1.6.3 {
  execsql {
    SELECT CASE WHEN b THEN d WHEN e THEN f ELSE 999 END, b, c, d FROM t1
  }
} {13 11 12 13 23 21 22 23}
do_test cse-1.6.4 {
  execsql {
    SELECT b, c, d, CASE WHEN b THEN d WHEN e THEN f ELSE 999 END FROM t1
  }
} {11 12 13 13 21 22 23 23}
do_test cse-1.6.5 {
  execsql {
    SELECT b, c, d, CASE WHEN 0 THEN d WHEN e THEN f ELSE 999 END FROM t1
  }
} {11 12 13 15 21 22 23 25}
do_test cse-1.7 {
  execsql {
    SELECT a, -a, ~a, NOT a, NOT NOT a, a-a, a+a, a*a, a/a, a FROM t1
  }
} {1 -1 -2 0 1 0 2 1 1 1 2 -2 -3 0 1 0 4 4 1 2}
do_test cse-1.8 {
  execsql {
    SELECT a, a%a, a==a, a!=a, a<a, a<=a, a IS NULL, a NOT NULL, a FROM t1
  }
} {1 0 1 0 0 1 0 1 1 2 0 1 0 0 1 0 1 2}
do_test cse-1.9 {
  execsql {
    SELECT NOT b, ~b, NOT NOT b, b FROM t1
  }
} {0 -12 1 11 0 -22 1 21}
do_test cse-1.10 {
  execsql {
    SELECT CAST(b AS integer), typeof(b), CAST(b AS text), typeof(b) FROM t1
  }
} {11 integer 11 integer 21 integer 21 integer}
ifcapable compound {
  do_test cse-1.11 { 
    execsql {
      SELECT *,* FROM t1 WHERE a=2
      UNION ALL
      SELECT *,* FROM t1 WHERE a=1
    }
  } {2 21 22 23 24 25 2 21 22 23 24 25 1 11 12 13 14 15 1 11 12 13 14 15}
  do_test cse-1.12 { 
    execsql {
      SELECT coalesce(b,c,d,e), a, b, c, d, e FROM t1 WHERE a=2
      UNION ALL
      SELECT coalesce(e,d,c,b), e, d, c, b, a FROM t1 WHERE a=1
    }
  } {21 2 21 22 23 24 14 14 13 12 11 1}
}
do_test cse-1.13 {
  execsql {
     SELECT upper(b), typeof(b), b FROM t1
  }
} {11 integer 11 21 integer 21}
do_test cse-1.14 {
  execsql {
     SELECT b, typeof(b), upper(b), typeof(b), b FROM t1
  }
} {11 integer 11 integer 11 21 integer 21 integer 21}

# Overflow the column cache.  Create queries involving more and more
# columns until the cache overflows.  Verify correct operation throughout.
#
do_test cse-2.1 {
  execsql {
    CREATE TABLE t2(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,
                    a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,
                    a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,
                    a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,
                    a40,a41,a42,a43,a44,a45,a46,a47,a48,a49);
    INSERT INTO t2 VALUES(0,1,2,3,4,5,6,7,8,9,
                    10,11,12,13,14,15,16,17,18,19,
                    20,21,22,23,24,25,26,27,28,29,
                    30,31,32,33,34,35,36,37,38,39,
                    40,41,42,43,44,45,46,47,48,49);
    SELECT * FROM t2;
  }
} {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49}

for {set i 1} {$i<100} {incr i} {
  set n [expr {int(rand()*44)+5}]
  set colset {}
  set answer {}
  for {set j 0} {$j<$n} {incr j} {
    set r [expr {$j+int(rand()*5)}]
    if {$r>49} {set r [expr {99-$r}]}
    lappend colset a$j a$r 
    lappend answer $j $r
  }
  set sql "SELECT [join $colset ,] FROM t2"
  do_test cse-2.2.$i {
    # explain $::sql
    execsql $::sql
  } $answer
}

finish_test

Added test/date.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# 2003 October 31
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing date and time functions.
#
# $Id: date.test,v 1.34 2009/04/16 12:58:03 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Skip this whole file if date and time functions are omitted
# at compile-time
#
ifcapable {!datetime} {
  finish_test
  return
}

proc datetest {tnum expr result} {
  do_test date-$tnum [subst {
    execsql "SELECT coalesce($expr,'NULL')"
  }] [list $result]
}
set tcl_precision 15
datetest 1.1 julianday('2000-01-01') 2451544.5
datetest 1.2 julianday('1970-01-01') 2440587.5
datetest 1.3 julianday('1910-04-20') 2418781.5
datetest 1.4 julianday('1986-02-09') 2446470.5
datetest 1.5 julianday('12:00:00') 2451545.0
datetest 1.6 {julianday('2000-01-01 12:00:00')} 2451545.0
datetest 1.7 {julianday('2000-01-01 12:00')} 2451545.0
datetest 1.8 julianday('bogus') NULL
datetest 1.9 julianday('1999-12-31') 2451543.5
datetest 1.10 julianday('1999-12-32') NULL
datetest 1.11 julianday('1999-13-01') NULL
datetest 1.12 julianday('2003-02-31') 2452701.5
datetest 1.13 julianday('2003-03-03') 2452701.5
datetest 1.14 julianday('+2000-01-01') NULL
datetest 1.15 julianday('200-01-01') NULL
datetest 1.16 julianday('2000-1-01') NULL
datetest 1.17 julianday('2000-01-1') NULL
datetest 1.18.1 {julianday('2000-01-01     12:00:00')} 2451545.0
datetest 1.18.2 {julianday('2000-01-01T12:00:00')} 2451545.0
datetest 1.18.3 {julianday('2000-01-01 T12:00:00')} 2451545.0
datetest 1.18.4 {julianday('2000-01-01T 12:00:00')} 2451545.0
datetest 1.18.4 {julianday('2000-01-01 T 12:00:00')} 2451545.0
datetest 1.19 {julianday('2000-01-01 12:00:00.1')}   2451545.00000116
datetest 1.20 {julianday('2000-01-01 12:00:00.01')}  2451545.00000012
datetest 1.21 {julianday('2000-01-01 12:00:00.001')} 2451545.00000001
datetest 1.22 {julianday('2000-01-01 12:00:00.')} NULL
datetest 1.23 julianday(12345.6) 12345.6
datetest 1.23b julianday('12345.6') 12345.6
datetest 1.24 {julianday('2001-01-01 12:00:00 bogus')} NULL
datetest 1.25 {julianday('2001-01-01 bogus')} NULL
datetest 1.26 {julianday('2001-01-01 12:60:00')} NULL
datetest 1.27 {julianday('2001-01-01 12:59:60')} NULL
datetest 1.28 {julianday('2001-00-01')} NULL
datetest 1.29 {julianday('2001-01-00')} NULL

datetest 2.1 datetime(0,'unixepoch') {1970-01-01 00:00:00}
datetest 2.1b datetime(0,'unixepoc') NULL
datetest 2.1c datetime(0,'unixepochx') NULL
datetest 2.1d datetime('2003-10-22','unixepoch') NULL
datetest 2.2 datetime(946684800,'unixepoch') {2000-01-01 00:00:00}
datetest 2.2b datetime('946684800','unixepoch') {2000-01-01 00:00:00}
for {set i 0} {$i<1000} {incr i} {
  set sql [format {strftime('%%H:%%M:%%f',1237962480.%03d,'unixepoch')} $i]
  set res [format {06:28:00.%03d} $i]
  datetest 2.2c-$i $sql $res
}
datetest 2.3 {date('2003-10-22','weekday 0')} 2003-10-26
datetest 2.4 {date('2003-10-22','weekday 1')} 2003-10-27
datetest 2.4a {date('2003-10-22','weekday  1')} 2003-10-27
datetest 2.4b {date('2003-10-22','weekday  1x')} 2003-10-27
datetest 2.4c {date('2003-10-22','weekday  -1')} NULL
datetest 2.4d {date('2003-10-22','weakday  1x')} NULL
datetest 2.4e {date('2003-10-22','weekday ')} NULL
datetest 2.5 {date('2003-10-22','weekday 2')} 2003-10-28
datetest 2.6 {date('2003-10-22','weekday 3')} 2003-10-22
datetest 2.7 {date('2003-10-22','weekday 4')} 2003-10-23
datetest 2.8 {date('2003-10-22','weekday 5')} 2003-10-24
datetest 2.9 {date('2003-10-22','weekday 6')} 2003-10-25
datetest 2.10 {date('2003-10-22','weekday 7')} NULL
datetest 2.11 {date('2003-10-22','weekday 5.5')} NULL
datetest 2.12 {datetime('2003-10-22 12:34','weekday 0')} {2003-10-26 12:34:00}
datetest 2.13 {datetime('2003-10-22 12:34','start of month')} \
   {2003-10-01 00:00:00}
datetest 2.14 {datetime('2003-10-22 12:34','start of year')} \
   {2003-01-01 00:00:00}
datetest 2.15 {datetime('2003-10-22 12:34','start of day')} \
   {2003-10-22 00:00:00}
datetest 2.15a {datetime('2003-10-22 12:34','start of')} NULL
datetest 2.15b {datetime('2003-10-22 12:34','start of bogus')} NULL
datetest 2.16 time('12:34:56.43') 12:34:56
datetest 2.17 {datetime('2003-10-22 12:34','1 day')} {2003-10-23 12:34:00}
datetest 2.18 {datetime('2003-10-22 12:34','+1 day')} {2003-10-23 12:34:00}
datetest 2.19 {datetime('2003-10-22 12:34','+1.25 day')} {2003-10-23 18:34:00}
datetest 2.20 {datetime('2003-10-22 12:34','-1.0 day')} {2003-10-21 12:34:00}
datetest 2.21 {datetime('2003-10-22 12:34','1 month')} {2003-11-22 12:34:00}
datetest 2.22 {datetime('2003-10-22 12:34','11 month')} {2004-09-22 12:34:00}
datetest 2.23 {datetime('2003-10-22 12:34','-13 month')} {2002-09-22 12:34:00}
datetest 2.24 {datetime('2003-10-22 12:34','1.5 months')} {2003-12-07 12:34:00}
datetest 2.25 {datetime('2003-10-22 12:34','-5 years')} {1998-10-22 12:34:00}
datetest 2.26 {datetime('2003-10-22 12:34','+10.5 minutes')} \
  {2003-10-22 12:44:30}
datetest 2.27 {datetime('2003-10-22 12:34','-1.25 hours')} \
  {2003-10-22 11:19:00}
datetest 2.28 {datetime('2003-10-22 12:34','11.25 seconds')} \
  {2003-10-22 12:34:11}
datetest 2.29 {datetime('2003-10-22 12:24','+5 bogus')} NULL
datetest 2.30 {datetime('2003-10-22 12:24','+++')} NULL
datetest 2.31 {datetime('2003-10-22 12:24','+12.3e4 femtoseconds')} NULL
datetest 2.32 {datetime('2003-10-22 12:24','+12.3e4 uS')} NULL
datetest 2.33 {datetime('2003-10-22 12:24','+1 abc')} NULL
datetest 2.34 {datetime('2003-10-22 12:24','+1 abcd')} NULL
datetest 2.35 {datetime('2003-10-22 12:24','+1 abcde')} NULL
datetest 2.36 {datetime('2003-10-22 12:24','+1 abcdef')} NULL
datetest 2.37 {datetime('2003-10-22 12:24','+1 abcdefg')} NULL
datetest 2.38 {datetime('2003-10-22 12:24','+1 abcdefgh')} NULL
datetest 2.39 {datetime('2003-10-22 12:24','+1 abcdefghi')} NULL
set sqlite_current_time 1199243045
datetest 2.40 {datetime()} {2008-01-02 03:04:05}
set sqlite_current_time 0
datetest 2.41 {datetime('2003-10-22 12:24','23 seconds')} {2003-10-22 12:24:23}
datetest 2.42 {datetime('2003-10-22 12:24','345 second')} {2003-10-22 12:29:45}
datetest 2.43 {datetime('2003-10-22 12:24','4 second')} {2003-10-22 12:24:04}
datetest 2.44 {datetime('2003-10-22 12:24','56 second')} {2003-10-22 12:24:56}
datetest 2.45 {datetime('2003-10-22 12:24','60 second')} {2003-10-22 12:25:00}
datetest 2.46 {datetime('2003-10-22 12:24','70 second')} {2003-10-22 12:25:10}
datetest 2.47 {datetime('2003-10-22 12:24','8.6 seconds')} {2003-10-22 12:24:08}
datetest 2.48 {datetime('2003-10-22 12:24','9.4 second')} {2003-10-22 12:24:09}
datetest 2.49 {datetime('2003-10-22 12:24','0000 second')} {2003-10-22 12:24:00}
datetest 2.50 {datetime('2003-10-22 12:24','0001 second')} {2003-10-22 12:24:01}
datetest 2.51 {datetime('2003-10-22 12:24','nonsense')} NULL

datetest 3.1 {strftime('%d','2003-10-31 12:34:56.432')} 31
datetest 3.2.1 {strftime('pre%fpost','2003-10-31 12:34:56.432')} pre56.432post
datetest 3.2.2 {strftime('%f','2003-10-31 12:34:59.9999999')} 59.999
datetest 3.3 {strftime('%H','2003-10-31 12:34:56.432')} 12
datetest 3.4 {strftime('%j','2003-10-31 12:34:56.432')} 304
datetest 3.5 {strftime('%J','2003-10-31 12:34:56.432')} 2452944.02426426
datetest 3.6 {strftime('%m','2003-10-31 12:34:56.432')} 10
datetest 3.7 {strftime('%M','2003-10-31 12:34:56.432')} 34
datetest 3.8.1 {strftime('%s','2003-10-31 12:34:56.432')} 1067603696
datetest 3.8.2 {strftime('%s','2038-01-19 03:14:07')} 2147483647
datetest 3.8.3 {strftime('%s','2038-01-19 03:14:08')} 2147483648
datetest 3.8.4 {strftime('%s','2201-04-09 12:00:00')} 7298164800
datetest 3.8.5 {strftime('%s','9999-12-31 23:59:59')} 253402300799
datetest 3.8.6 {strftime('%s','1969-12-31 23:59:59')} -1
datetest 3.8.7 {strftime('%s','1901-12-13 20:45:52')} -2147483648
datetest 3.8.8 {strftime('%s','1901-12-13 20:45:51')} -2147483649
datetest 3.8.9 {strftime('%s','1776-07-04 00:00:00')} -6106060800
datetest 3.9 {strftime('%S','2003-10-31 12:34:56.432')} 56
datetest 3.10 {strftime('%w','2003-10-31 12:34:56.432')} 5
datetest 3.11.1 {strftime('%W','2003-10-31 12:34:56.432')} 43
datetest 3.11.2 {strftime('%W','2004-01-01')} 00
datetest 3.11.3 {strftime('%W','2004-01-02')} 00
datetest 3.11.4 {strftime('%W','2004-01-03')} 00
datetest 3.11.5 {strftime('abc%Wxyz','2004-01-04')} abc00xyz
datetest 3.11.6 {strftime('%W','2004-01-05')} 01
datetest 3.11.7 {strftime('%W','2004-01-06')} 01
datetest 3.11.8 {strftime('%W','2004-01-07')} 01
datetest 3.11.9 {strftime('%W','2004-01-08')} 01
datetest 3.11.10 {strftime('%W','2004-01-09')} 01
datetest 3.11.11 {strftime('%W','2004-07-18')} 28
datetest 3.11.12 {strftime('%W','2004-12-31')} 52
datetest 3.11.13 {strftime('%W','2007-12-31')} 53
datetest 3.11.14 {strftime('%W','2007-01-01')} 01
datetest 3.11.15 {strftime('%W %j',2454109.04140970)} {02 008}
datetest 3.11.16 {strftime('%W %j',2454109.04140971)} {02 008}
datetest 3.11.17 {strftime('%W %j',2454109.04140972)} {02 008}
datetest 3.11.18 {strftime('%W %j',2454109.04140973)} {02 008}
datetest 3.11.19 {strftime('%W %j',2454109.04140974)} {02 008}
datetest 3.11.20 {strftime('%W %j',2454109.04140975)} {02 008}
datetest 3.11.21 {strftime('%W %j',2454109.04140976)} {02 008}
datetest 3.11.22 {strftime('%W %j',2454109.04140977)} {02 008}
datetest 3.11.23 {strftime('%W %j',2454109.04140978)} {02 008}
datetest 3.11.24 {strftime('%W %j',2454109.04140979)} {02 008}
datetest 3.11.25 {strftime('%W %j',2454109.04140980)} {02 008}
datetest 3.11.99 {strftime('%W %j','2454109.04140970')} {02 008}
datetest 3.12 {strftime('%Y','2003-10-31 12:34:56.432')} 2003
datetest 3.13 {strftime('%%','2003-10-31 12:34:56.432')} %
datetest 3.14 {strftime('%_','2003-10-31 12:34:56.432')} NULL
datetest 3.15 {strftime('%Y-%m-%d','2003-10-31')} 2003-10-31
proc repeat {n txt} {
  set x {} 
  while {$n>0} {
    append x $txt
    incr n -1
  }
  return $x
}
datetest 3.16 "strftime('[repeat 200 %Y]','2003-10-31')" [repeat 200 2003]
datetest 3.17 "strftime('[repeat 200 abc%m123]','2003-10-31')" \
    [repeat 200 abc10123]

foreach c {a b c e g h i k l n o p q r t v x y z
           A B C D E F G I K L N O P Q R T U V Z
           0 1 2 3 4 5 6 6 7 9 _} {
  datetest 3.18.$c "strftime('%$c','2003-10-31')" NULL
}

# Ticket #2276.  Make sure leading zeros are inserted where appropriate.
#
datetest 3.20 \
   {strftime('%d/%f/%H/%W/%j/%m/%M/%S/%Y','0421-01-02 03:04:05.006')} \
   02/05.006/03/00/002/01/04/05/0421

set sqlite_current_time 1157124367
datetest 4.1 {date('now')} {2006-09-01}
set sqlite_current_time 0

datetest 5.1 {datetime('1994-04-16 14:00:00 +05:00')} {1994-04-16 09:00:00}
datetest 5.2 {datetime('1994-04-16 14:00:00 -05:15')} {1994-04-16 19:15:00}
datetest 5.3 {datetime('1994-04-16 05:00:00 +08:30')} {1994-04-15 20:30:00}
datetest 5.4 {datetime('1994-04-16 14:00:00 -11:55')} {1994-04-17 01:55:00}
datetest 5.5 {datetime('1994-04-16 14:00:00 -11:60')} NULL
datetest 5.6 {datetime('1994-04-16 14:00:00 -11:55  ')} {1994-04-17 01:55:00}
datetest 5.7 {datetime('1994-04-16 14:00:00 -11:55 x')} NULL
datetest 5.8 {datetime('1994-04-16T14:00:00Z')} {1994-04-16 14:00:00}
datetest 5.9 {datetime('1994-04-16 14:00:00z')} {1994-04-16 14:00:00}
datetest 5.10 {datetime('1994-04-16 14:00:00 Z')} {1994-04-16 14:00:00}
datetest 5.11 {datetime('1994-04-16 14:00:00z    ')} {1994-04-16 14:00:00}
datetest 5.12 {datetime('1994-04-16 14:00:00     z    ')} {1994-04-16 14:00:00}
datetest 5.13 {datetime('1994-04-16 14:00:00Zulu')} NULL
datetest 5.14 {datetime('1994-04-16 14:00:00Z +05:00')} NULL
datetest 5.15 {datetime('1994-04-16 14:00:00 +05:00 Z')} NULL

# localtime->utc and utc->localtime conversions.  These tests only work
# if the localtime is in the US Eastern Time (the time in Charlotte, NC
# and in New York.)
#
# On non-Vista Windows platform, '2006-03-31' is treated incorrectly as being
# in DST giving a 4 hour offset instead of 5.  In 2007, DST was extended to 
# start three weeks earlier (second Sunday in March) and end one week
# later (first Sunday in November).  Older Windows systems apply this
# new rule incorrectly to dates prior to 2007.
#
# It might be argued that this is masking a problem on non-Vista Windows
# platform.  A ticket has already been opened for this issue 
# (http://www.sqlite.org/cvstrac/tktview?tn=2322).  This is just to prevent
# more confusion/reports of the issue.
#

# $tzoffset_old should be 5 if DST is working correctly.
set tzoffset_old [db one {
  SELECT CAST(24*(julianday('2006-03-31') -
                  julianday('2006-03-31','localtime'))+0.5
              AS INT)
}]

# $tzoffset_new should be 4 if DST is working correctly.
set tzoffset_new [db one {
  SELECT CAST(24*(julianday('2007-03-31') -
                  julianday('2007-03-31','localtime'))+0.5
              AS INT)
}]

# Warn about possibly broken Windows DST implementations.
if {$::tcl_platform(platform)=="windows" && $tzoffset_new==4 && $tzoffset_old==4} {
  puts "******************************************************************"
  puts "N.B.:  The DST support provided by your current O/S seems to be"
  puts "suspect in that it is reporting incorrect DST values for dates"
  puts "prior to 2007.  This is the known case for most (all?) non-Vista"
  puts "Windows versions.  Please see ticket #2322 for more information."
  puts "******************************************************************"
}

if {$tzoffset_new==4} {
  datetest 6.1 {datetime('2000-10-29 05:59:00','localtime')}\
      {2000-10-29 01:59:00}
  datetest 6.1.1 {datetime('2006-10-29 05:59:00','localtime')}\
      {2006-10-29 01:59:00}
  datetest 6.1.2 {datetime('2007-11-04 05:59:00','localtime')}\
      {2007-11-04 01:59:00}

  # If the new and old DST rules seem to be working correctly...
  if {$tzoffset_new==4 && $tzoffset_old==5} {
    datetest 6.2 {datetime('2000-10-29 06:00:00','localtime')}\
        {2000-10-29 01:00:00}
    datetest 6.2.1 {datetime('2006-10-29 06:00:00','localtime')}\
        {2006-10-29 01:00:00}
  }
  datetest 6.2.2 {datetime('2007-11-04 06:00:00','localtime')}\
      {2007-11-04 01:00:00}

  # If the new and old DST rules seem to be working correctly...
  if {$tzoffset_new==4 && $tzoffset_old==5} {
    datetest 6.3 {datetime('2000-04-02 06:59:00','localtime')}\
        {2000-04-02 01:59:00}
    datetest 6.3.1 {datetime('2006-04-02 06:59:00','localtime')}\
        {2006-04-02 01:59:00}
  }
  datetest 6.3.2 {datetime('2007-03-11 07:00:00','localtime')}\
      {2007-03-11 03:00:00}

  datetest 6.4 {datetime('2000-04-02 07:00:00','localtime')}\
      {2000-04-02 03:00:00}
  datetest 6.4.1 {datetime('2006-04-02 07:00:00','localtime')}\
      {2006-04-02 03:00:00}
  datetest 6.4.2 {datetime('2007-03-11 07:00:00','localtime')}\
      {2007-03-11 03:00:00}
      
  datetest 6.5 {datetime('2000-10-29 01:59:00','utc')} {2000-10-29 05:59:00}
  datetest 6.5.1 {datetime('2006-10-29 01:59:00','utc')} {2006-10-29 05:59:00}
  datetest 6.5.2 {datetime('2007-11-04 01:59:00','utc')} {2007-11-04 05:59:00}

  # If the new and old DST rules seem to be working correctly...
  if {$tzoffset_new==4 && $tzoffset_old==5} {
    datetest 6.6 {datetime('2000-10-29 02:00:00','utc')} {2000-10-29 07:00:00}
    datetest 6.6.1 {datetime('2006-10-29 02:00:00','utc')} {2006-10-29 07:00:00}
  }
  datetest 6.6.2 {datetime('2007-11-04 02:00:00','utc')} {2007-11-04 07:00:00}

  # If the new and old DST rules seem to be working correctly...
  if {$tzoffset_new==4 && $tzoffset_old==5} {
    datetest 6.7 {datetime('2000-04-02 01:59:00','utc')} {2000-04-02 06:59:00}
    datetest 6.7.1 {datetime('2006-04-02 01:59:00','utc')} {2006-04-02 06:59:00}
  }
  datetest 6.7.2 {datetime('2007-03-11 01:59:00','utc')} {2007-03-11 06:59:00}

  datetest 6.8 {datetime('2000-04-02 02:00:00','utc')} {2000-04-02 06:00:00}
  datetest 6.8.1 {datetime('2006-04-02 02:00:00','utc')} {2006-04-02 06:00:00}
  datetest 6.8.2 {datetime('2007-03-11 02:00:00','utc')} {2007-03-11 06:00:00}

  datetest 6.10 {datetime('2000-01-01 12:00:00','localtime')} \
      {2000-01-01 07:00:00}
  datetest 6.11 {datetime('1969-01-01 12:00:00','localtime')} \
      {1969-01-01 07:00:00}
  datetest 6.12 {datetime('2039-01-01 12:00:00','localtime')} \
      {2039-01-01 07:00:00}
  datetest 6.13 {datetime('2000-07-01 12:00:00','localtime')} \
      {2000-07-01 08:00:00}
  datetest 6.14 {datetime('1969-07-01 12:00:00','localtime')} \
      {1969-07-01 07:00:00}
  datetest 6.15 {datetime('2039-07-01 12:00:00','localtime')} \
      {2039-07-01 07:00:00}
  set sqlite_current_time \
     [db eval {SELECT strftime('%s','2000-07-01 12:34:56')}]
  datetest 6.16 {datetime('now','localtime')} {2000-07-01 08:34:56}
  datetest 6.17 {datetime('now','localtimex')} NULL
  datetest 6.18 {datetime('now','localtim')} NULL
  set sqlite_current_time 0
}

# These two are a bit of a scam. They are added to ensure that 100% of
# the date.c file is covered by testing, even when the time-zone
# is not -0400 (the condition for running of the block of tests above).
#
datetest 6.19 {datetime('2039-07-01 12:00:00','localtime',null)} NULL
datetest 6.20 {datetime('2039-07-01 12:00:00','utc',null)} NULL

# Date-time functions that contain NULL arguments return a NULL
# result.
#
datetest 7.1 {datetime(null)} NULL
datetest 7.2 {datetime('now',null)} NULL
datetest 7.3 {datetime('now','localtime',null)} NULL
datetest 7.4 {time(null)} NULL
datetest 7.5 {time('now',null)} NULL
datetest 7.6 {time('now','localtime',null)} NULL
datetest 7.7 {date(null)} NULL
datetest 7.8 {date('now',null)} NULL
datetest 7.9 {date('now','localtime',null)} NULL
datetest 7.10 {julianday(null)} NULL
datetest 7.11 {julianday('now',null)} NULL
datetest 7.12 {julianday('now','localtime',null)} NULL
datetest 7.13 {strftime(null,'now')} NULL
datetest 7.14 {strftime('%s',null)} NULL
datetest 7.15 {strftime('%s','now',null)} NULL
datetest 7.16 {strftime('%s','now','localtime',null)} NULL

# Test modifiers when the date begins as a julian day number - to
# make sure the HH:MM:SS is preserved.  Ticket #551.
#
set sqlite_current_time [db eval {SELECT strftime('%s','2003-10-22 12:34:00')}]
datetest 8.1 {datetime('now','weekday 0')} {2003-10-26 12:34:00}
datetest 8.2 {datetime('now','weekday 1')} {2003-10-27 12:34:00}
datetest 8.3 {datetime('now','weekday 2')} {2003-10-28 12:34:00}
datetest 8.4 {datetime('now','weekday 3')} {2003-10-22 12:34:00}
datetest 8.5 {datetime('now','start of month')} {2003-10-01 00:00:00}
datetest 8.6 {datetime('now','start of year')} {2003-01-01 00:00:00}
datetest 8.7 {datetime('now','start of day')} {2003-10-22 00:00:00}
datetest 8.8 {datetime('now','1 day')} {2003-10-23 12:34:00}
datetest 8.9 {datetime('now','+1 day')} {2003-10-23 12:34:00}
datetest 8.10 {datetime('now','+1.25 day')} {2003-10-23 18:34:00}
datetest 8.11 {datetime('now','-1.0 day')} {2003-10-21 12:34:00}
datetest 8.12 {datetime('now','1 month')} {2003-11-22 12:34:00}
datetest 8.13 {datetime('now','11 month')} {2004-09-22 12:34:00}
datetest 8.14 {datetime('now','-13 month')} {2002-09-22 12:34:00}
datetest 8.15 {datetime('now','1.5 months')} {2003-12-07 12:34:00}
datetest 8.16 {datetime('now','-5 years')} {1998-10-22 12:34:00}
datetest 8.17 {datetime('now','+10.5 minutes')} {2003-10-22 12:44:30}
datetest 8.18 {datetime('now','-1.25 hours')} {2003-10-22 11:19:00}
datetest 8.19 {datetime('now','11.25 seconds')} {2003-10-22 12:34:11}
datetest 8.90 {datetime('now','abcdefghijklmnopqrstuvwyxzABCDEFGHIJLMNOP')} NULL
set sqlite_current_time 0

# Negative years work.  Example:  '-4713-11-26' is JD 1.5.
#
datetest 9.1 {julianday('-4713-11-24 12:00:00')} {0.0}
datetest 9.2 {julianday(datetime(5))} {5.0}
datetest 9.3 {julianday(datetime(10))} {10.0}
datetest 9.4 {julianday(datetime(100))} {100.0}
datetest 9.5 {julianday(datetime(1000))} {1000.0}
datetest 9.6 {julianday(datetime(10000))} {10000.0}
datetest 9.7 {julianday(datetime(100000))} {100000.0}

# datetime() with just an HH:MM:SS correctly inserts the date 2000-01-01.
#
datetest 10.1 {datetime('01:02:03')}  {2000-01-01 01:02:03}
datetest 10.2 {date('01:02:03')}  {2000-01-01}
datetest 10.3 {strftime('%Y-%m-%d %H:%M','01:02:03')} {2000-01-01 01:02}

# Test the new HH:MM:SS modifier
#
datetest 11.1 {datetime('2004-02-28 20:00:00', '-01:20:30')} \
   {2004-02-28 18:39:30}
datetest 11.2 {datetime('2004-02-28 20:00:00', '+12:30:00')} \
   {2004-02-29 08:30:00}
datetest 11.3 {datetime('2004-02-28 20:00:00', '+12:30')} \
   {2004-02-29 08:30:00}
datetest 11.4 {datetime('2004-02-28 20:00:00', '12:30')} \
   {2004-02-29 08:30:00}
datetest 11.5 {datetime('2004-02-28 20:00:00', '-12:00')} \
   {2004-02-28 08:00:00}
datetest 11.6 {datetime('2004-02-28 20:00:00', '-12:01')} \
   {2004-02-28 07:59:00}
datetest 11.7 {datetime('2004-02-28 20:00:00', '-11:59')} \
   {2004-02-28 08:01:00}
datetest 11.8 {datetime('2004-02-28 20:00:00', '11:59')} \
   {2004-02-29 07:59:00}
datetest 11.9 {datetime('2004-02-28 20:00:00', '12:01')} \
   {2004-02-29 08:01:00}
datetest 11.10 {datetime('2004-02-28 20:00:00', '12:60')} NULL

# Ticket #1964
datetest 12.1 {datetime('2005-09-01')} {2005-09-01 00:00:00}
datetest 12.2 {datetime('2005-09-01','+0 hours')} {2005-09-01 00:00:00}

# Ticket #1991
do_test date-13.1 {
  execsql {
    SELECT strftime('%Y-%m-%d %H:%M:%f', julianday('2006-09-24T10:50:26.047'))
  }
} {{2006-09-24 10:50:26.047}}

# Ticket #2153
datetest 13.2 {strftime('%Y-%m-%d %H:%M:%S', '2007-01-01 12:34:59.6')} \
  {2007-01-01 12:34:59}
datetest 13.3 {strftime('%Y-%m-%d %H:%M:%f', '2007-01-01 12:34:59.6')} \
  {2007-01-01 12:34:59.600}
datetest 13.4 {strftime('%Y-%m-%d %H:%M:%S', '2007-01-01 12:59:59.6')} \
  {2007-01-01 12:59:59}
datetest 13.5 {strftime('%Y-%m-%d %H:%M:%f', '2007-01-01 12:59:59.6')} \
  {2007-01-01 12:59:59.600}
datetest 13.6 {strftime('%Y-%m-%d %H:%M:%S', '2007-01-01 23:59:59.6')} \
  {2007-01-01 23:59:59}
datetest 13.7 {strftime('%Y-%m-%d %H:%M:%f', '2007-01-01 23:59:59.6')} \
  {2007-01-01 23:59:59.600}

# Ticket #3618
datetest 13.11 {julianday(2454832.5,'-1 day')} {2454831.5}
datetest 13.12 {julianday(2454832.5,'+1 day')} {2454833.5}
datetest 13.13 {julianday(2454832.5,'-1.5 day')} {2454831.0}
datetest 13.14 {julianday(2454832.5,'+1.5 day')} {2454834.0}
datetest 13.15 {julianday(2454832.5,'-3 hours')} {2454832.375}
datetest 13.16 {julianday(2454832.5,'+3 hours')} {2454832.625}
datetest 13.17 {julianday(2454832.5,'-45 minutes')} {2454832.46875}
datetest 13.18 {julianday(2454832.5,'+45 minutes')} {2454832.53125}
datetest 13.19 {julianday(2454832.5,'-675 seconds')} {2454832.4921875}
datetest 13.20 {julianday(2454832.5,'+675 seconds')} {2454832.5078125}
datetest 13.21 {julianday(2454832.5,'-1.5 months')} {2454786.5}
datetest 13.22 {julianday(2454832.5,'+1.5 months')} {2454878.5}
datetest 13.23 {julianday(2454832.5,'-1.5 years')} {2454284.0}
datetest 13.24 {julianday(2454832.5,'+1.5 years')} {2455380.0}

datetest 13.30 {date('2000-01-01','+1.5 years')} {2001-07-02}
datetest 13.31 {date('2001-01-01','+1.5 years')} {2002-07-02}
datetest 13.32 {date('2002-01-01','+1.5 years')} {2003-07-02}
datetest 13.33 {date('2002-01-01','-1.5 years')} {2000-07-02}
datetest 13.34 {date('2001-01-01','-1.5 years')} {1999-07-02}

# Test for issues reported by BareFeet (list.sql at tandb.com.au)
# on mailing list on 2008-06-12.
#
# Put a floating point number in the database so that we can manipulate
# raw bits using the hexio interface.
#
do_test date-14.1 {
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1.1);
  }
  db close
  hexio_write test.db 2040 4142ba32bffffff9
  sqlite3 db test.db
  db eval {SELECT * FROM t1}
} {2454629.5}

# Changing the least significant byte of the floating point value between
# 00 and FF should always generate a time of either 23:59:59 or 00:00:00,
# never 24:00:00
#
for {set i 0} {$i<=255} {incr i} {
  db close
  hexio_write test.db 2047 [format %02x $i]
  sqlite3 db test.db
  do_test date-14.2.$i {
    set date [db one {SELECT datetime(x) FROM t1}]
    expr {$date eq "2008-06-12 00:00:00" || $date eq "2008-06-11 23:59:59"}
  } {1}
}
finish_test

Added test/default.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2005 August 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing corner cases of the DEFAULT syntax
# on table definitions.
#
# $Id: default.test,v 1.3 2009/02/19 14:39:25 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable bloblit {
  do_test default-1.1 {
    execsql {
      CREATE TABLE t1(
        a INTEGER,
        b BLOB DEFAULT x'6869'
      );
      INSERT INTO t1(a) VALUES(1);
      SELECT * from t1;
    }
  } {1 hi}
}
do_test default-1.2 {
  execsql {
    CREATE TABLE t2(
      x INTEGER,
      y INTEGER DEFAULT NULL
    );
    INSERT INTO t2(x) VALUES(1);
    SELECT * FROM t2;
  }
} {1 {}}
do_test default-1.3 {
  catchsql {
    CREATE TABLE t3(
      x INTEGER,
      y INTEGER DEFAULT (max(x,5))
    )
  }
} {1 {default value of column [y] is not constant}}

ifcapable pragma {
  do_test default-2.1 {
    execsql {
      CREATE TABLE t4(c DEFAULT 'abc');
      PRAGMA table_info(t4);
    }
  } {0 c {} 0 'abc' 0}
  do_test default-2.2 {
    execsql {
      INSERT INTO t4 DEFAULT VALUES;
      PRAGMA table_info(t4);
    }
  } {0 c {} 0 'abc' 0}
}

finish_test

Added test/delete.test.





















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the DELETE FROM statement.
#
# $Id: delete.test,v 1.26 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Try to delete from a non-existant table.
#
do_test delete-1.1 {
  set v [catch {execsql {DELETE FROM test1}} msg]
  lappend v $msg
} {1 {no such table: test1}}

# Try to delete from sqlite_master
#
do_test delete-2.1 {
  set v [catch {execsql {DELETE FROM sqlite_master}} msg]
  lappend v $msg
} {1 {table sqlite_master may not be modified}}

# Delete selected entries from a table with and without an index.
#
do_test delete-3.1.1 {
  execsql {CREATE TABLE table1(f1 int, f2 int)}
  execsql {INSERT INTO table1 VALUES(1,2)}
  execsql {INSERT INTO table1 VALUES(2,4)}
  execsql {INSERT INTO table1 VALUES(3,8)}
  execsql {INSERT INTO table1 VALUES(4,16)}
  execsql {SELECT * FROM table1 ORDER BY f1}
} {1 2 2 4 3 8 4 16}
do_test delete-3.1.2 {
  execsql {DELETE FROM table1 WHERE f1=3}
} {}
do_test delete-3.1.3 {
  execsql {SELECT * FROM table1 ORDER BY f1}
} {1 2 2 4 4 16}
do_test delete-3.1.4 {
  execsql {CREATE INDEX index1 ON table1(f1)}
  execsql {PRAGMA count_changes=on}
  ifcapable explain {
    execsql {EXPLAIN DELETE FROM table1 WHERE f1=3}
  }
  execsql {DELETE FROM 'table1' WHERE f1=3}
} {0}
do_test delete-3.1.5 {
  execsql {SELECT * FROM table1 ORDER BY f1}
} {1 2 2 4 4 16}
do_test delete-3.1.6.1 {
  execsql {DELETE FROM table1 WHERE f1=2}
} {1}
do_test delete-3.1.6.2 {
  db changes
} 1
do_test delete-3.1.7 {
  execsql {SELECT * FROM table1 ORDER BY f1}
} {1 2 4 16}
integrity_check delete-3.2


# Semantic errors in the WHERE clause
#
do_test delete-4.1 {
  execsql {CREATE TABLE table2(f1 int, f2 int)}
  set v [catch {execsql {DELETE FROM table2 WHERE f3=5}} msg]
  lappend v $msg
} {1 {no such column: f3}}

do_test delete-4.2 {
  set v [catch {execsql {DELETE FROM table2 WHERE xyzzy(f1+4)}} msg]
  lappend v $msg
} {1 {no such function: xyzzy}}
integrity_check delete-4.3

# Lots of deletes
#
do_test delete-5.1.1 {
  execsql {DELETE FROM table1}
} {2}
do_test delete-5.1.2 {
  execsql {SELECT count(*) FROM table1}
} {0}
do_test delete-5.2.1 {
  execsql {BEGIN TRANSACTION}
  for {set i 1} {$i<=200} {incr i} {
     execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])"
  }
  execsql {COMMIT}
  execsql {SELECT count(*) FROM table1}
} {200}
do_test delete-5.2.2 {
  execsql {DELETE FROM table1}
} {200}
do_test delete-5.2.3 {
  execsql {BEGIN TRANSACTION}
  for {set i 1} {$i<=200} {incr i} {
     execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])"
  }
  execsql {COMMIT}
  execsql {SELECT count(*) FROM table1}
} {200}
do_test delete-5.2.4 {
  execsql {PRAGMA count_changes=off}
  execsql {DELETE FROM table1}
} {}
do_test delete-5.2.5 {
  execsql {SELECT count(*) FROM table1}
} {0}
do_test delete-5.2.6 {
  execsql {BEGIN TRANSACTION}
  for {set i 1} {$i<=200} {incr i} {
     execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])"
  }
  execsql {COMMIT}
  execsql {SELECT count(*) FROM table1}
} {200}
do_test delete-5.3 {
  for {set i 1} {$i<=200} {incr i 4} {
     execsql "DELETE FROM table1 WHERE f1==$i"
  }
  execsql {SELECT count(*) FROM table1}
} {150}
do_test delete-5.4.1 {
  execsql "DELETE FROM table1 WHERE f1>50"
  db changes
} [db one {SELECT count(*) FROM table1 WHERE f1>50}]
do_test delete-5.4.2 {
  execsql {SELECT count(*) FROM table1}
} {37}
do_test delete-5.5 {
  for {set i 1} {$i<=70} {incr i 3} {
     execsql "DELETE FROM table1 WHERE f1==$i"
  }
  execsql {SELECT f1 FROM table1 ORDER BY f1}
} {2 3 6 8 11 12 14 15 18 20 23 24 26 27 30 32 35 36 38 39 42 44 47 48 50}
do_test delete-5.6 {
  for {set i 1} {$i<40} {incr i} {
     execsql "DELETE FROM table1 WHERE f1==$i"
  }
  execsql {SELECT f1 FROM table1 ORDER BY f1}
} {42 44 47 48 50}
do_test delete-5.7 {
  execsql "DELETE FROM table1 WHERE f1!=48"
  execsql {SELECT f1 FROM table1 ORDER BY f1}
} {48}
integrity_check delete-5.8


# Delete large quantities of data.  We want to test the List overflow
# mechanism in the vdbe.
#
do_test delete-6.1 {
  execsql {BEGIN; DELETE FROM table1}
  for {set i 1} {$i<=3000} {incr i} {
    execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])"
  }
  execsql {DELETE FROM table2}
  for {set i 1} {$i<=3000} {incr i} {
    execsql "INSERT INTO table2 VALUES($i,[expr {$i*$i}])"
  }
  execsql {COMMIT}
  execsql {SELECT count(*) FROM table1}
} {3000}
do_test delete-6.2 {
  execsql {SELECT count(*) FROM table2}
} {3000}
do_test delete-6.3 {
  execsql {SELECT f1 FROM table1 WHERE f1<10 ORDER BY f1}
} {1 2 3 4 5 6 7 8 9}
do_test delete-6.4 {
  execsql {SELECT f1 FROM table2 WHERE f1<10 ORDER BY f1}
} {1 2 3 4 5 6 7 8 9}
do_test delete-6.5.1 {
  execsql {DELETE FROM table1 WHERE f1>7}
  db changes
} {2993}
do_test delete-6.5.2 {
  execsql {SELECT f1 FROM table1 ORDER BY f1}
} {1 2 3 4 5 6 7}
do_test delete-6.6 {
  execsql {DELETE FROM table2 WHERE f1>7}
  execsql {SELECT f1 FROM table2 ORDER BY f1}
} {1 2 3 4 5 6 7}
do_test delete-6.7 {
  execsql {DELETE FROM table1}
  execsql {SELECT f1 FROM table1}
} {}
do_test delete-6.8 {
  execsql {INSERT INTO table1 VALUES(2,3)}
  execsql {SELECT f1 FROM table1}
} {2}
do_test delete-6.9 {
  execsql {DELETE FROM table2}
  execsql {SELECT f1 FROM table2}
} {}
do_test delete-6.10 {
  execsql {INSERT INTO table2 VALUES(2,3)}
  execsql {SELECT f1 FROM table2}
} {2}
integrity_check delete-6.11

do_test delete-7.1 {
  execsql {
    CREATE TABLE t3(a);
    INSERT INTO t3 VALUES(1);
    INSERT INTO t3 SELECT a+1 FROM t3;
    INSERT INTO t3 SELECT a+2 FROM t3;
    SELECT * FROM t3;
  }
} {1 2 3 4}
ifcapable {trigger} {
  do_test delete-7.2 {
    execsql {
      CREATE TABLE cnt(del);
      INSERT INTO cnt VALUES(0);
      CREATE TRIGGER r1 AFTER DELETE ON t3 FOR EACH ROW BEGIN
        UPDATE cnt SET del=del+1;
      END;
      DELETE FROM t3 WHERE a<2;
      SELECT * FROM t3;
    }
  } {2 3 4}
  do_test delete-7.3 {
    execsql {
      SELECT * FROM cnt;
    }
  } {1}
  do_test delete-7.4 {
    execsql {
      DELETE FROM t3;
      SELECT * FROM t3;
    }
  } {}
  do_test delete-7.5 {
    execsql {
      SELECT * FROM cnt;
    }
  } {4}
  do_test delete-7.6 {
    execsql {
      INSERT INTO t3 VALUES(1);
      INSERT INTO t3 SELECT a+1 FROM t3;
      INSERT INTO t3 SELECT a+2 FROM t3;
      CREATE TABLE t4 AS SELECT * FROM t3;
      PRAGMA count_changes=ON;
      DELETE FROM t3;
      DELETE FROM t4;
    }
  } {4 4}
} ;# endif trigger
ifcapable {!trigger} {
  execsql {DELETE FROM t3}
}
integrity_check delete-7.7

# Make sure error messages are consistent when attempting to delete
# from a read-only database.  Ticket #304.
#
do_test delete-8.0 {
  execsql {
    PRAGMA count_changes=OFF;
    INSERT INTO t3 VALUES(123);
    SELECT * FROM t3;
  }
} {123}
db close
catch {file delete -force test.db-journal}
catch {file attributes test.db -permissions 0444}
catch {file attributes test.db -readonly 1}
sqlite3 db test.db
set ::DB [sqlite3_connection_pointer db]
do_test delete-8.1 {
  catchsql {
    DELETE FROM t3;
  }
} {1 {attempt to write a readonly database}}
do_test delete-8.2 {
  execsql {SELECT * FROM t3} 
} {123}
do_test delete-8.3 {
  catchsql {
    DELETE FROM t3 WHERE 1;
  }
} {1 {attempt to write a readonly database}}
do_test delete-8.4 {
  execsql {SELECT * FROM t3} 
} {123}

# Update for v3: In v2 the DELETE statement would succeed because no
# database writes actually occur. Version 3 refuses to open a transaction
# on a read-only file, so the statement fails.
do_test delete-8.5 {
  catchsql {
    DELETE FROM t3 WHERE a<100;
  }
# v2 result: {0 {}}
} {1 {attempt to write a readonly database}}
do_test delete-8.6 {
  execsql {SELECT * FROM t3}
} {123}
integrity_check delete-8.7

# Need to do the following for tcl 8.5 on mac. On that configuration, the
# -readonly flag is taken so seriously that a subsequent [file delete -force]
# (required before the next test file can be executed) will fail.
#
catch {file attributes test.db -readonly 0}
db close
file delete -force test.db test.db-journal

# The following tests verify that SQLite correctly handles the case
# where an index B-Tree is being scanned, the rowid column being read
# from each index entry and another statement deletes some rows from
# the index B-Tree. At one point this (obscure) scenario was causing 
# SQLite to return spurious SQLITE_CORRUPT errors and arguably incorrect
# query results. 
#
do_test delete-9.1 {
  sqlite3 db test.db
  execsql {
    CREATE TABLE t5(a, b);
    CREATE TABLE t6(c, d);
    INSERT INTO t5 VALUES(1, 2);
    INSERT INTO t5 VALUES(3, 4);
    INSERT INTO t5 VALUES(5, 6);
    INSERT INTO t6 VALUES('a', 'b');
    INSERT INTO t6 VALUES('c', 'd');
    CREATE INDEX i5 ON t5(a);
    CREATE INDEX i6 ON t6(c);
  }
} {}
do_test delete-9.2 {
  set res [list]
  db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } {
    if {$r==2} { db eval { DELETE FROM t5 } }
    lappend res $r $c $d
  }
  set res
} {1 a b 1 c d 2 a b {} c d}
do_test delete-9.3 {
  execsql {
    INSERT INTO t5 VALUES(1, 2);
    INSERT INTO t5 VALUES(3, 4);
    INSERT INTO t5 VALUES(5, 6);
  }
  set res [list]
  db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } {
    if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 2 } }
    lappend res $r $c $d
  }
  set res
} {1 a b 1 c d 2 a b {} c d 3 a b 3 c d}
do_test delete-9.4 {
  execsql {
    DELETE FROM t5;
    INSERT INTO t5 VALUES(1, 2);
    INSERT INTO t5 VALUES(3, 4);
    INSERT INTO t5 VALUES(5, 6);
  }
  set res [list]
  db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } {
    if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 1 } }
    lappend res $r $c $d
  }
  set res
} {1 a b 1 c d 2 a b 2 c d 3 a b 3 c d}
do_test delete-9.5 {
  execsql {
    DELETE FROM t5;
    INSERT INTO t5 VALUES(1, 2);
    INSERT INTO t5 VALUES(3, 4);
    INSERT INTO t5 VALUES(5, 6);
  }
  set res [list]
  db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } {
    if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 3 } }
    lappend res $r $c $d
  }
  set res
} {1 a b 1 c d 2 a b 2 c d}


finish_test

Added test/delete2.test.















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# 2003 September 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is a test to replicate the bug reported by
# ticket #842.
#
# Ticket #842 was a database corruption problem caused by a DELETE that
# removed an index entry by not the main table entry.  To recreate the
# problem do this:
#
#   (1) Create a table with an index.  Insert some data into that table.
#   (2) Start a query on the table but do not complete the query.
#   (3) Try to delete a single entry from the table.
#
# Step 3 will fail because there is still a read cursor on the table.
# But the database is corrupted by the DELETE.  It turns out that the
# index entry was deleted first, before the table entry.  And the index
# delete worked.  Thus an entry was deleted from the index but not from
# the table.
#
# The solution to the problem was to detect that the table is locked
# before the index entry is deleted.
#
# $Id: delete2.test,v 1.8 2008/07/08 15:59:52 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table that has an index.
#
do_test delete2-1.1 {
  set DB [sqlite3_connection_pointer db]
  execsql {
    CREATE TABLE q(s string, id string, constraint pk_q primary key(id));
    BEGIN;
    INSERT INTO q(s,id) VALUES('hello','id.1');
    INSERT INTO q(s,id) VALUES('goodbye','id.2');
    INSERT INTO q(s,id) VALUES('again','id.3');
    END;
    SELECT * FROM q;
  }
} {hello id.1 goodbye id.2 again id.3}
do_test delete2-1.2 {
  execsql {
    SELECT * FROM q WHERE id='id.1';
  }
} {hello id.1}
integrity_check delete2-1.3

# Start a query on the table.  The query should not use the index.
# Do not complete the query, thus leaving the table locked.
#
do_test delete2-1.4 {
  set STMT [sqlite3_prepare $DB {SELECT * FROM q} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
integrity_check delete2-1.5

# Try to delete a row from the table while a read is in process.
# As of 2006-08-16, this is allowed.  (It used to fail with SQLITE_LOCKED.)
#
do_test delete2-1.6 {
  catchsql {
    DELETE FROM q WHERE rowid=1
  }
} {0 {}}
integrity_check delete2-1.7
do_test delete2-1.8 {
  execsql {
    SELECT * FROM q;
  }
} {goodbye id.2 again id.3}

# Finalize the query, thus clearing the lock on the table.  Then
# retry the delete.  The delete should work this time.
#
do_test delete2-1.9 {
  sqlite3_finalize $STMT
  catchsql {
    DELETE FROM q WHERE rowid=1
  }
} {0 {}}
integrity_check delete2-1.10
do_test delete2-1.11 {
  execsql {
    SELECT * FROM q;
  }
} {goodbye id.2 again id.3}

do_test delete2-2.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(c, d);
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t2 VALUES(3, 4);
    INSERT INTO t2 VALUES(5, 6);
  }
} {}
do_test delete2-2.2 {
  set res [list]
  db eval {
    SELECT CASE WHEN c = 5 THEN b ELSE NULL END AS b, c, d FROM t1, t2
  } {
    db eval {DELETE FROM t1}
    lappend res $b $c $d
  }
  set res
} {{} 3 4 {} 5 6}

finish_test

Added test/delete3.test.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 2005 August 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is a test of the DELETE command where a
# large number of rows are deleted.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table that contains a large number of rows.
#
do_test delete3-1.1 {
  execsql {
    CREATE TABLE t1(x integer primary key);
    BEGIN;
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 SELECT x+2 FROM t1;
    INSERT INTO t1 SELECT x+4 FROM t1;
    INSERT INTO t1 SELECT x+8 FROM t1;
    INSERT INTO t1 SELECT x+16 FROM t1;
    INSERT INTO t1 SELECT x+32 FROM t1;
    INSERT INTO t1 SELECT x+64 FROM t1;
    INSERT INTO t1 SELECT x+128 FROM t1;
    INSERT INTO t1 SELECT x+256 FROM t1;
    INSERT INTO t1 SELECT x+512 FROM t1;
    INSERT INTO t1 SELECT x+1024 FROM t1;
    INSERT INTO t1 SELECT x+2048 FROM t1;
    INSERT INTO t1 SELECT x+4096 FROM t1;
    INSERT INTO t1 SELECT x+8192 FROM t1;
    INSERT INTO t1 SELECT x+16384 FROM t1;
    INSERT INTO t1 SELECT x+32768 FROM t1;
    INSERT INTO t1 SELECT x+65536 FROM t1;
    INSERT INTO t1 SELECT x+131072 FROM t1;
    INSERT INTO t1 SELECT x+262144 FROM t1;
    COMMIT;
    SELECT count(*) FROM t1;	
  }
} {524288}
do_test delete3-1.2 {
  execsql {
    DELETE FROM t1 WHERE x%2==0;
    SELECT count(*) FROM t1;
  }
} {262144}
integrity_check delete3-1.3

finish_test

Added test/descidx1.test.















































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# 2005 December 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is descending indices.
#
# $Id: descidx1.test,v 1.10 2008/03/19 00:21:31 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db eval {PRAGMA legacy_file_format=OFF}

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}


# Verify that the file format starts as 4.
#
do_test descidx1-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    CREATE INDEX i1 ON t1(b ASC);
  }
  get_file_format
} {4}
do_test descidx1-1.2 {
  execsql {
    CREATE INDEX i2 ON t1(a DESC);
  }
  get_file_format
} {4}

# Put some information in the table and verify that the descending
# index actually works.
#
do_test descidx1-2.1 {
  execsql {
    INSERT INTO t1 VALUES(1,1);
    INSERT INTO t1 VALUES(2,2);
    INSERT INTO t1 SELECT a+2, a+2 FROM t1;
    INSERT INTO t1 SELECT a+4, a+4 FROM t1;
    SELECT b FROM t1 WHERE a>3 AND a<7;
  }
} {6 5 4}
do_test descidx1-2.2 {
  execsql {
    SELECT a FROM t1 WHERE b>3 AND b<7;
  }
} {4 5 6}
do_test descidx1-2.3 {
  execsql {
    SELECT b FROM t1 WHERE a>=3 AND a<7;
  }
} {6 5 4 3}
do_test descidx1-2.4 {
  execsql {
    SELECT b FROM t1 WHERE a>3 AND a<=7;
  }
} {7 6 5 4}
do_test descidx1-2.5 {
  execsql {
    SELECT b FROM t1 WHERE a>=3 AND a<=7;
  }
} {7 6 5 4 3}
do_test descidx1-2.6 {
  execsql {
    SELECT a FROM t1 WHERE b>=3 AND b<=7;
  }
} {3 4 5 6 7}

# This procedure executes the SQL.  Then it checks to see if the OP_Sort
# opcode was executed.  If an OP_Sort did occur, then "sort" is appended
# to the result.  If no OP_Sort happened, then "nosort" is appended.
#
# This procedure is used to check to make sure sorting is or is not
# occurring as expected.
#
proc cksort {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

# Test sorting using a descending index.
#
do_test descidx1-3.1 {
  cksort {SELECT a FROM t1 ORDER BY a}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.2 {
  cksort {SELECT a FROM t1 ORDER BY a ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.3 {
  cksort {SELECT a FROM t1 ORDER BY a DESC}
} {8 7 6 5 4 3 2 1 nosort}
do_test descidx1-3.4 {
  cksort {SELECT b FROM t1 ORDER BY a}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.5 {
  cksort {SELECT b FROM t1 ORDER BY a ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.6 {
  cksort {SELECT b FROM t1 ORDER BY a DESC}
} {8 7 6 5 4 3 2 1 nosort}
do_test descidx1-3.7 {
  cksort {SELECT a FROM t1 ORDER BY b}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.8 {
  cksort {SELECT a FROM t1 ORDER BY b ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.9 {
  cksort {SELECT a FROM t1 ORDER BY b DESC}
} {8 7 6 5 4 3 2 1 nosort}
do_test descidx1-3.10 {
  cksort {SELECT b FROM t1 ORDER BY b}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.11 {
  cksort {SELECT b FROM t1 ORDER BY b ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx1-3.12 {
  cksort {SELECT b FROM t1 ORDER BY b DESC}
} {8 7 6 5 4 3 2 1 nosort}

do_test descidx1-3.21 {
  cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a}
} {4 5 6 7 nosort}
do_test descidx1-3.22 {
  cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC}
} {4 5 6 7 nosort}
do_test descidx1-3.23 {
  cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC}
} {7 6 5 4 nosort}
do_test descidx1-3.24 {
  cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a}
} {4 5 6 7 nosort}
do_test descidx1-3.25 {
  cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC}
} {4 5 6 7 nosort}
do_test descidx1-3.26 {
  cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC}
} {7 6 5 4 nosort}

# Create a table with indices that are descending on some terms and
# ascending on others.
#
ifcapable bloblit {
  do_test descidx1-4.1 {
    execsql {
      CREATE TABLE t2(a INT, b TEXT, c BLOB, d REAL);
      CREATE INDEX i3 ON t2(a ASC, b DESC, c ASC);
      CREATE INDEX i4 ON t2(b DESC, a ASC, d DESC);
      INSERT INTO t2 VALUES(1,'one',x'31',1.0);
      INSERT INTO t2 VALUES(2,'two',x'3232',2.0);
      INSERT INTO t2 VALUES(3,'three',x'333333',3.0);
      INSERT INTO t2 VALUES(4,'four',x'34343434',4.0);
      INSERT INTO t2 VALUES(5,'five',x'3535353535',5.0);
      INSERT INTO t2 VALUES(6,'six',x'363636363636',6.0);
      INSERT INTO t2 VALUES(2,'two',x'323232',2.1);
      INSERT INTO t2 VALUES(2,'zwei',x'3232',2.2);
      INSERT INTO t2 VALUES(2,NULL,NULL,2.3);
      SELECT count(*) FROM t2;
    }
  } {9}
  do_test descidx1-4.2 {
    execsql {
      SELECT d FROM t2 ORDER BY a;
    }
  } {1.0 2.2 2.0 2.1 2.3 3.0 4.0 5.0 6.0}
  do_test descidx1-4.3 {
    execsql {
      SELECT d FROM t2 WHERE a>=2;
    }
  } {2.2 2.0 2.1 2.3 3.0 4.0 5.0 6.0}
  do_test descidx1-4.4 {
    execsql {
      SELECT d FROM t2 WHERE a>2;
    }
  } {3.0 4.0 5.0 6.0}
  do_test descidx1-4.5 {
    execsql {
      SELECT d FROM t2 WHERE a=2 AND b>'two';
    }
  } {2.2}
  do_test descidx1-4.6 {
    execsql {
      SELECT d FROM t2 WHERE a=2 AND b>='two';
    }
  } {2.2 2.0 2.1}
  do_test descidx1-4.7 {
    execsql {
      SELECT d FROM t2 WHERE a=2 AND b<'two';
    }
  } {}
  do_test descidx1-4.8 {
    execsql {
      SELECT d FROM t2 WHERE a=2 AND b<='two';
    }
  } {2.0 2.1}
}

do_test descidx1-5.1 {
  execsql {
    CREATE TABLE t3(a,b,c,d);
    CREATE INDEX t3i1 ON t3(a DESC, b ASC, c DESC, d ASC);
    INSERT INTO t3 VALUES(0,0,0,0);
    INSERT INTO t3 VALUES(0,0,0,1);
    INSERT INTO t3 VALUES(0,0,1,0);
    INSERT INTO t3 VALUES(0,0,1,1);
    INSERT INTO t3 VALUES(0,1,0,0);
    INSERT INTO t3 VALUES(0,1,0,1);
    INSERT INTO t3 VALUES(0,1,1,0);
    INSERT INTO t3 VALUES(0,1,1,1);
    INSERT INTO t3 VALUES(1,0,0,0);
    INSERT INTO t3 VALUES(1,0,0,1);
    INSERT INTO t3 VALUES(1,0,1,0);
    INSERT INTO t3 VALUES(1,0,1,1);
    INSERT INTO t3 VALUES(1,1,0,0);
    INSERT INTO t3 VALUES(1,1,0,1);
    INSERT INTO t3 VALUES(1,1,1,0);
    INSERT INTO t3 VALUES(1,1,1,1);
    SELECT count(*) FROM t3;
  }
} {16}
do_test descidx1-5.2 {
  cksort {
    SELECT a||b||c||d FROM t3 ORDER BY a,b,c,d;
  }
} {0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 sort}
do_test descidx1-5.3 {
  cksort {
    SELECT a||b||c||d FROM t3 ORDER BY a DESC, b ASC, c DESC, d ASC;
  }
} {1010 1011 1000 1001 1110 1111 1100 1101 0010 0011 0000 0001 0110 0111 0100 0101 nosort}
do_test descidx1-5.4 {
  cksort {
    SELECT a||b||c||d FROM t3 ORDER BY a ASC, b DESC, c ASC, d DESC;
  }
} {0101 0100 0111 0110 0001 0000 0011 0010 1101 1100 1111 1110 1001 1000 1011 1010 nosort}
do_test descidx1-5.5 {
  cksort {
    SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a DESC, b ASC, c DESC
  }
} {101 100 111 110 001 000 011 010 nosort}
do_test descidx1-5.6 {
  cksort {
    SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a ASC, b DESC, c ASC
  }
} {010 011 000 001 110 111 100 101 nosort}
do_test descidx1-5.7 {
  cksort {
    SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a ASC, b DESC, c DESC
  }
} {011 010 001 000 111 110 101 100 sort}
do_test descidx1-5.8 {
  cksort {
    SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a ASC, b ASC, c ASC
  }
} {000 001 010 011 100 101 110 111 sort}
do_test descidx1-5.9 {
  cksort {
    SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a DESC, b DESC, c ASC
  }
} {110 111 100 101 010 011 000 001 sort}

# Test the legacy_file_format pragma here because we have access to
# the get_file_format command.
#
ifcapable legacyformat {
  do_test descidx1-6.1 {
    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql {PRAGMA legacy_file_format}
  } {1}
} else {
  do_test descidx1-6.1 {
    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    execsql {PRAGMA legacy_file_format}
  } {0}
}
do_test descidx1-6.2 {
  execsql {PRAGMA legacy_file_format=YES}
  execsql {PRAGMA legacy_file_format}
} {1}
do_test descidx1-6.3 {
  execsql {
    CREATE TABLE t1(a,b,c);
  }
  get_file_format
} {1}
ifcapable vacuum {
  # Verify that the file format is preserved across a vacuum.
  do_test descidx1-6.3.1 {
    execsql {VACUUM}
    get_file_format
  } {1}
}
do_test descidx1-6.4 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql {PRAGMA legacy_file_format=NO}
  execsql {PRAGMA legacy_file_format}
} {0}
do_test descidx1-6.5 {
  execsql {
    CREATE TABLE t1(a,b,c);
    CREATE INDEX i1 ON t1(a ASC, b DESC, c ASC);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(1,1,0);
    INSERT INTO t1 VALUES(1,2,1);
    INSERT INTO t1 VALUES(1,3,4);
  }
  get_file_format
} {4}
ifcapable vacuum {
  # Verify that the file format is preserved across a vacuum.
  do_test descidx1-6.6 {
    execsql {VACUUM}
    get_file_format
  } {4}
  do_test descidx1-6.7 {
    execsql {
      PRAGMA legacy_file_format=ON;
      VACUUM;
    }
    get_file_format
  } {4}
} 



finish_test

Added test/descidx2.test.







































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# 2005 December 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is descending indices.
#
# $Id: descidx2.test,v 1.5 2008/03/19 00:21:31 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db eval {PRAGMA legacy_file_format=OFF}

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}


# Verify that the file format starts as 4
#
do_test descidx2-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    CREATE INDEX i1 ON t1(b ASC);
  }
  get_file_format
} {4}
do_test descidx2-1.2 {
  execsql {
    CREATE INDEX i2 ON t1(a DESC);
  }
  get_file_format
} {4}

# Before adding any information to the database, set the file format
# back to three.  Then close and reopen the database.  With the file
# format set to three, SQLite should ignore the DESC argument on the
# index.
#
do_test descidx2-2.0 {
  set_file_format 3
  db close
  sqlite3 db test.db
  get_file_format
} {3}

# Put some information in the table and verify that the DESC
# on the index is ignored.
#
do_test descidx2-2.1 {
  execsql {
    INSERT INTO t1 VALUES(1,1);
    INSERT INTO t1 VALUES(2,2);
    INSERT INTO t1 SELECT a+2, a+2 FROM t1;
    INSERT INTO t1 SELECT a+4, a+4 FROM t1;
    SELECT b FROM t1 WHERE a>3 AND a<7;
  }
} {4 5 6}
do_test descidx2-2.2 {
  execsql {
    SELECT a FROM t1 WHERE b>3 AND b<7;
  }
} {4 5 6}
do_test descidx2-2.3 {
  execsql {
    SELECT b FROM t1 WHERE a>=3 AND a<7;
  }
} {3 4 5 6}
do_test descidx2-2.4 {
  execsql {
    SELECT b FROM t1 WHERE a>3 AND a<=7;
  }
} {4 5 6 7}
do_test descidx2-2.5 {
  execsql {
    SELECT b FROM t1 WHERE a>=3 AND a<=7;
  }
} {3 4 5 6 7}
do_test descidx2-2.6 {
  execsql {
    SELECT a FROM t1 WHERE b>=3 AND b<=7;
  }
} {3 4 5 6 7}

# This procedure executes the SQL.  Then it checks to see if the OP_Sort
# opcode was executed.  If an OP_Sort did occur, then "sort" is appended
# to the result.  If no OP_Sort happened, then "nosort" is appended.
#
# This procedure is used to check to make sure sorting is or is not
# occurring as expected.
#
proc cksort {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

# Test sorting using a descending index.
#
do_test descidx2-3.1 {
  cksort {SELECT a FROM t1 ORDER BY a}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.2 {
  cksort {SELECT a FROM t1 ORDER BY a ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.3 {
  cksort {SELECT a FROM t1 ORDER BY a DESC}
} {8 7 6 5 4 3 2 1 nosort}
do_test descidx2-3.4 {
  cksort {SELECT b FROM t1 ORDER BY a}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.5 {
  cksort {SELECT b FROM t1 ORDER BY a ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.6 {
  cksort {SELECT b FROM t1 ORDER BY a DESC}
} {8 7 6 5 4 3 2 1 nosort}
do_test descidx2-3.7 {
  cksort {SELECT a FROM t1 ORDER BY b}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.8 {
  cksort {SELECT a FROM t1 ORDER BY b ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.9 {
  cksort {SELECT a FROM t1 ORDER BY b DESC}
} {8 7 6 5 4 3 2 1 nosort}
do_test descidx2-3.10 {
  cksort {SELECT b FROM t1 ORDER BY b}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.11 {
  cksort {SELECT b FROM t1 ORDER BY b ASC}
} {1 2 3 4 5 6 7 8 nosort}
do_test descidx2-3.12 {
  cksort {SELECT b FROM t1 ORDER BY b DESC}
} {8 7 6 5 4 3 2 1 nosort}

do_test descidx2-3.21 {
  cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a}
} {4 5 6 7 nosort}
do_test descidx2-3.22 {
  cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC}
} {4 5 6 7 nosort}
do_test descidx2-3.23 {
  cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC}
} {7 6 5 4 nosort}
do_test descidx2-3.24 {
  cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a}
} {4 5 6 7 nosort}
do_test descidx2-3.25 {
  cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC}
} {4 5 6 7 nosort}
do_test descidx2-3.26 {
  cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC}
} {7 6 5 4 nosort}

finish_test

Added test/descidx3.test.











































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# 2006 January 02
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is descending indices.
#
# $Id: descidx3.test,v 1.6 2008/03/19 00:21:31 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !bloblit {
  finish_test
  return
}
db eval {PRAGMA legacy_file_format=OFF}

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

# This procedure returns the value of the file-format in file 'test.db'.
# 
proc get_file_format {{fname test.db}} {
  return [hexio_get_int [hexio_read $fname 44 4]]
}

# Verify that the file format starts as 4.
#
do_test descidx3-1.1 {
  execsql {
    CREATE TABLE t1(i INTEGER PRIMARY KEY,a,b,c,d);
    CREATE INDEX t1i1 ON t1(a DESC, b ASC, c DESC);
    CREATE INDEX t1i2 ON t1(b DESC, c ASC, d DESC);
  }
  get_file_format
} {4}

# Put some information in the table and verify that the descending
# index actually works.
#
do_test descidx3-2.1 {
  execsql {
    INSERT INTO t1 VALUES(1, NULL, NULL, NULL, NULL);
    INSERT INTO t1 VALUES(2, 2, 2, 2, 2);
    INSERT INTO t1 VALUES(3, 3, 3, 3, 3);
    INSERT INTO t1 VALUES(4, 2.5, 2.5, 2.5, 2.5);
    INSERT INTO t1 VALUES(5, -5, -5, -5, -5);
    INSERT INTO t1 VALUES(6, 'six', 'six', 'six', 'six');
    INSERT INTO t1 VALUES(7, x'77', x'77', x'77', x'77');
    INSERT INTO t1 VALUES(8, 'eight', 'eight', 'eight', 'eight');
    INSERT INTO t1 VALUES(9, x'7979', x'7979', x'7979', x'7979');
    SELECT count(*) FROM t1;
  }
} 9
do_test descidx3-2.2 {
  execsql {
    SELECT i FROM t1 ORDER BY a;
  }
} {1 5 2 4 3 8 6 7 9}
do_test descidx3-2.3 {
  execsql {
    SELECT i FROM t1 ORDER BY a DESC;
  }
} {9 7 6 8 3 4 2 5 1}

# The "natural" order for the index is decreasing
do_test descidx3-2.4 {
  execsql {
    SELECT i FROM t1 WHERE a<=x'7979';
  }
} {9 7 6 8 3 4 2 5}
do_test descidx3-2.5 {
  execsql {
    SELECT i FROM t1 WHERE a>-99;
  }
} {9 7 6 8 3 4 2 5}

# Even when all values of t1.a are the same, sorting by A returns
# the rows in reverse order because this the natural order of the
# index.
#
do_test descidx3-3.1 {
  execsql {
    UPDATE t1 SET a=1;
    SELECT i FROM t1 ORDER BY a;
  }
} {9 7 6 8 3 4 2 5 1}
do_test descidx3-3.2 {
  execsql {
    SELECT i FROM t1 WHERE a=1 AND b>0 AND b<'zzz'
  }
} {2 4 3 8 6}
do_test descidx3-3.3 {
  execsql {
    SELECT i FROM t1 WHERE b>0 AND b<'zzz'
  }
} {6 8 3 4 2}
do_test descidx3-3.4 {
  execsql {
    SELECT i FROM t1 WHERE a=1 AND b>-9999 AND b<x'ffffffff'
  }
} {5 2 4 3 8 6 7 9}
do_test descidx3-3.5 {
  execsql {
    SELECT i FROM t1 WHERE b>-9999 AND b<x'ffffffff'
  }
} {9 7 6 8 3 4 2 5}

ifcapable subquery {
  # If the subquery capability is not compiled in to the binary, then
  # the IN(...) operator is not available. Hence these tests cannot be 
  # run.
  do_test descidx3-4.1 {
    execsql {
      UPDATE t1 SET a=2 WHERE i<6;
      SELECT i FROM t1 WHERE a IN (1,2) AND b>0 AND b<'zzz';
    }
  } {8 6 2 4 3}
  do_test descidx3-4.2 {
    execsql {
      UPDATE t1 SET a=1;
      SELECT i FROM t1 WHERE a IN (1,2) AND b>0 AND b<'zzz';
    }
  } {2 4 3 8 6}
  do_test descidx3-4.3 {
    execsql {
      UPDATE t1 SET b=2;
      SELECT i FROM t1 WHERE a IN (1,2) AND b>0 AND b<'zzz';
    }
  } {9 7 6 8 3 4 2 5 1}
}

finish_test

Added test/diskfull.test.







































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# 2001 October 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of disk full
# errors.
# 
# $Id: diskfull.test,v 1.8 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

set sqlite_io_error_persist 0
set sqlite_io_error_hit 0
set sqlite_io_error_pending 0
do_test diskfull-1.1 {
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(randstr(1000,1000));
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    CREATE INDEX t1i1 ON t1(x);
    CREATE TABLE t2 AS SELECT x AS a, x AS b FROM t1;
    CREATE INDEX t2i1 ON t2(b);
  }
} {}
set sqlite_diskfull_pending 0
integrity_check diskfull-1.2
do_test diskfull-1.3 {
  set sqlite_diskfull_pending 1
  catchsql {
    INSERT INTO t1 SELECT * FROM t1;
  }
} {1 {database or disk is full}}
set sqlite_diskfull_pending 0
integrity_check diskfull-1.4
do_test diskfull-1.5 {
  set sqlite_diskfull_pending 1
  catchsql {
    DELETE FROM t1;
  }
} {1 {database or disk is full}}
set sqlite_diskfull_pending 0
set sqlite_io_error_hit 0
integrity_check diskfull-1.6

proc do_diskfull_test {prefix sql} {
  set ::go 1
  set ::sql $sql
  set ::i 1
  while {$::go} {
    incr ::i
    do_test ${prefix}.$::i.1 {
      set ::sqlite_diskfull_pending $::i
      set ::sqlite_diskfull 0
      set r [catchsql $::sql]
      if {!$::sqlite_diskfull} {
        set r {1 {database or disk is full}}
        set ::go 0
      }
      if {$r=="1 {disk I/O error}"} {
        set r {1 {database or disk is full}}
      }
      set r
    } {1 {database or disk is full}}
    set ::sqlite_diskfull_pending 0
    db close
    sqlite3 db test.db
    integrity_check ${prefix}.$::i.2
  }
}

do_diskfull_test diskfull-2 VACUUM

# db close
# file delete -force test.db
# file delete -force test.db-journal
# sqlite3 db test.db
# 
# do_test diskfull-3.1 {
#   execsql {
#     PRAGMA default_cache_size = 10;
#     CREATE TABLE t3(a, b, UNIQUE(a, b));
#     INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) );
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
#     UPDATE t3 
#     SET b = (SELECT a FROM t3 WHERE rowid = (SELECT max(rowid)-1 FROM t3))
#     WHERE rowid = (SELECT max(rowid) FROM t3);
#     PRAGMA cache_size;
#   }
# } {10}
# 
# do_diskfull_test diskfull-3.2 {
#   BEGIN;
#     INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) );
#     UPDATE t3 SET a = b;
#   COMMIT;
# }

finish_test

Added test/distinctagg.test.





























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 2005 September 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is the DISTINCT modifier on aggregate functions.
#
# $Id: distinctagg.test,v 1.3 2009/02/09 13:19:28 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test distinctagg-1.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(1,3,4);
    INSERT INTO t1 VALUES(1,3,5);
    SELECT count(distinct a),
           count(distinct b),
           count(distinct c),
           count(all a) FROM t1;
  }
} {1 2 3 3}
do_test distinctagg-1.2 {
  execsql {
    SELECT b, count(distinct c) FROM t1 GROUP BY b ORDER BY b
  }
} {2 1 3 2}
do_test distinctagg-1.3 {
  execsql {
    INSERT INTO t1 SELECT a+1, b+3, c+5 FROM t1;
    INSERT INTO t1 SELECT a+2, b+6, c+10 FROM t1;
    INSERT INTO t1 SELECT a+4, b+12, c+20 FROM t1;
    SELECT count(*), count(distinct a), count(distinct b) FROM t1
  }
} {24 8 16}
do_test distinctagg-1.4 {
  execsql {
    SELECT a, count(distinct c) FROM t1 GROUP BY a ORDER BY a
  }
} {1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3}

do_test distinctagg-2.1 {
  catchsql {
    SELECT count(distinct) FROM t1;
  }
} {1 {DISTINCT aggregates must have exactly one argument}}
do_test distinctagg-2.2 {
  catchsql {
    SELECT group_concat(distinct a,b) FROM t1;
  }
} {1 {DISTINCT aggregates must have exactly one argument}}

finish_test

Added test/e_fkey.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
# 2009 October 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements tests to verify the "testable statements" in the
# foreignkeys.in document.
#
# The tests in this file are arranged to mirror the structure of 
# foreignkey.in, with one exception: The statements in section 2, which 
# deals with enabling/disabling foreign key support, is tested first,
# before section 1. This is because some statements in section 2 deal
# with builds that do not include complete foreign key support (because
# either SQLITE_OMIT_TRIGGER or SQLITE_OMIT_FOREIGN_KEY was defined
# at build time).
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc eqp {sql {db db}} { uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db }

###########################################################################
### SECTION 2: Enabling Foreign Key Support
###########################################################################

#-------------------------------------------------------------------------
# /* EV: R-33710-56344 */
#
# Test builds neither OMIT_FOREIGN_KEY or OMIT_TRIGGER defined have 
# foreign key functionality.
#
ifcapable trigger&&foreignkey {
  do_test e_fkey-49 {
    execsql {
      PRAGMA foreign_keys = ON;
      CREATE TABLE p(i PRIMARY KEY);
      CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE);
      INSERT INTO p VALUES('hello');
      INSERT INTO c VALUES('hello');
      UPDATE p SET i = 'world';
      SELECT * FROM c;
    }
  } {world}
}

#-------------------------------------------------------------------------
# /* EV: R-44697-61543 */
#
# Test the effects of defining OMIT_TRIGGER but not OMIT_FOREIGN_KEY.
#
# /* EV: R-22567-44039 */
# /* EV: R-41784-13339 */
#
# Specifically, test that "PRAGMA foreign_keys" is a no-op in this case.
# When using the pragma to query the current setting, 0 rows are returned.
#
reset_db
ifcapable !trigger&&foreignkey {
  do_test e_fkey-51.1 {
    execsql {
      PRAGMA foreign_keys = ON;
      CREATE TABLE p(i PRIMARY KEY);
      CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE);
      INSERT INTO p VALUES('hello');
      INSERT INTO c VALUES('hello');
      UPDATE p SET i = 'world';
      SELECT * FROM c;
    }
  } {hello}
  do_test e_fkey-51.2 {
    execsql { PRAGMA foreign_key_list(c) }
  } {0 0 p j {} CASCADE {NO ACTION} NONE}
  do_test e_fkey-51.3 {
    execsql { PRAGMA foreign_keys }
  } {}
}


#-------------------------------------------------------------------------
# /* EV: R-58428-36660 */
#
# Test the effects of defining OMIT_FOREIGN_KEY.
#
# /* EV: R-58428-36660 */
#
# Specifically, test that foreign key constraints cannot even be parsed 
# in such a build.
#
reset_db
ifcapable !foreignkey {
  do_test e_fkey-52.1 {
    execsql { CREATE TABLE p(i PRIMARY KEY) }
    catchsql { CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE) }
  } {1 {near "ON": syntax error}}
  do_test e_fkey-52.2 {
    # This is allowed, as in this build, "REFERENCES" is not a keyword.
    # The declared datatype of column j is "REFERENCES p".
    execsql { CREATE TABLE c(j REFERENCES p) }
  } {}
  do_test e_fkey-52.3 {
    execsql { PRAGMA table_info(c) }
  } {0 j {REFERENCES p} 0 {} 0}
  do_test e_fkey-52.4 {
    execsql { PRAGMA foreign_key_list(c) }
  } {}
  do_test e_fkey-52.5 {
    execsql { PRAGMA foreign_keys }
  } {}
}

ifcapable !foreignkey||!trigger { finish_test ; return }
reset_db


#-------------------------------------------------------------------------
# /* EV: R-07280-60510 */
#
# Test that even if foreign keys are supported by the build, they must
# be enabled using "PRAGMA foreign_keys = ON" (or similar).
#
# /* EV: R-59578-04990 */
#
# This also tests that foreign key constraints are disabled by default.
#
drop_all_tables
do_test e_fkey-53.1 {
  execsql {
    CREATE TABLE p(i PRIMARY KEY);
    CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE);
    INSERT INTO p VALUES('hello');
    INSERT INTO c VALUES('hello');
    UPDATE p SET i = 'world';
    SELECT * FROM c;
  } 
} {hello}
do_test e_fkey-53.2 {
  execsql {
    DELETE FROM c;
    DELETE FROM p;
    PRAGMA foreign_keys = ON;
    INSERT INTO p VALUES('hello');
    INSERT INTO c VALUES('hello');
    UPDATE p SET i = 'world';
    SELECT * FROM c;
  } 
} {world}

#-------------------------------------------------------------------------
# /* EV: R-15278-54456 */
# /* EV: R-11255-19907 */
#
# Test that the application can use "PRAGMA foreign_keys" to query for
# whether or not foreign keys are currently enabled. This also tests
# the example code in section 2 of foreignkeys.in.
#
reset_db
do_test e_fkey-54.1 {
  execsql { PRAGMA foreign_keys }
} {0}
do_test e_fkey-54.2 {
  execsql { 
    PRAGMA foreign_keys = ON;
    PRAGMA foreign_keys;
  }
} {1}
do_test e_fkey-54.3 {
  execsql { 
    PRAGMA foreign_keys = OFF;
    PRAGMA foreign_keys;
  }
} {0}

#-------------------------------------------------------------------------
# /* EV: R-46649-58537 */
#
# Test that it is not possible to enable or disable foreign key support
# while not in auto-commit mode.
#
reset_db
do_test e_fkey-55.1 {
  execsql {
    PRAGMA foreign_keys = ON;
    CREATE TABLE t1(a UNIQUE, b);
    CREATE TABLE t2(c, d REFERENCES t1(a));
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t2 VALUES(2, 1);
    BEGIN;
      PRAGMA foreign_keys = OFF;
  }
  catchsql {
      DELETE FROM t1
  }
} {1 {foreign key constraint failed}}
do_test e_fkey-55.2 {
  execsql { PRAGMA foreign_keys }
} {1}
do_test e_fkey-55.3 {
  execsql {
    COMMIT;
    PRAGMA foreign_keys = OFF;
    BEGIN;
      PRAGMA foreign_keys = ON;
      DELETE FROM t1;
      PRAGMA foreign_keys;
  }
} {0}
do_test e_fkey-55.4 {
  execsql COMMIT
} {}

###########################################################################
### SECTION 1: Introduction to Foreign Key Constraints
###########################################################################
execsql "PRAGMA foreign_keys = ON"

#-------------------------------------------------------------------------
# /* EV: R-04042-24825 */
#
# Verify that the syntax in the first example in section 1 is valid.
#
do_test e_fkey-38.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER, 
      trackname   TEXT, 
      trackartist INTEGER,
      FOREIGN KEY(trackartist) REFERENCES artist(artistid)
    );
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-61362-32087 */
#
# Attempting to insert a row into the 'track' table that corresponds
# to no row in the 'artist' table fails.
#
do_test e_fkey-39.1 {
  catchsql { INSERT INTO track VALUES(1, 'track 1', 1) }
} {1 {foreign key constraint failed}}
do_test e_fkey-39.2 {
  execsql { INSERT INTO artist VALUES(2, 'artist 1') }
  catchsql { INSERT INTO track VALUES(1, 'track 1', 1) }
} {1 {foreign key constraint failed}}
do_test e_fkey-39.2 {
  execsql { INSERT INTO track VALUES(1, 'track 1', 2) }
} {}

#-------------------------------------------------------------------------
# /* EV: R-24401-52400 */
#
# Attempting to delete a row from the 'artist' table while there are 
# dependent rows in the track table also fails.
#
do_test e_fkey-40.1 {
  catchsql { DELETE FROM artist WHERE artistid = 2 }
} {1 {foreign key constraint failed}}
do_test e_fkey-40.2 {
  execsql { 
    DELETE FROM track WHERE trackartist = 2;
    DELETE FROM artist WHERE artistid = 2;
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-23980-48859 */
#
# If the foreign key column (trackartist) in table 'track' is set to NULL,
# there is no requirement for a matching row in the 'artist' table.
#
do_test e_fkey-41.1 {
  execsql {
    INSERT INTO track VALUES(1, 'track 1', NULL);
    INSERT INTO track VALUES(2, 'track 2', NULL);
  }
} {}
do_test e_fkey-41.2 {
  execsql { SELECT * FROM artist }
} {}
do_test e_fkey-41.3 {
  # Setting the trackid to a non-NULL value fails, of course.
  catchsql { UPDATE track SET trackartist = 5 WHERE trackid = 1 }
} {1 {foreign key constraint failed}}
do_test e_fkey-41.4 {
  execsql {
    INSERT INTO artist VALUES(5, 'artist 5');
    UPDATE track SET trackartist = 5 WHERE trackid = 1;
  }
  catchsql { DELETE FROM artist WHERE artistid = 5}
} {1 {foreign key constraint failed}}
do_test e_fkey-41.5 {
  execsql { 
    UPDATE track SET trackartist = NULL WHERE trackid = 1;
    DELETE FROM artist WHERE artistid = 5;
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-52486-21352 */
#
# Test that the following is true fo all rows in the track table:
#
#   trackartist IS NULL OR 
#   EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist)
#

# This procedure executes a test case to check that statement 
# R-52486-21352 is true after executing the SQL statement passed.
# as the second argument.
proc test_r52486_21352 {tn sql} {
  set res [catchsql $sql]
  set results {
    {0 {}} 
    {1 {PRIMARY KEY must be unique}} 
    {1 {foreign key constraint failed}}
  }
  if {[lsearch $results $res]<0} {
    error $res
  }

  do_test e_fkey-42.$tn {
    execsql {
      SELECT count(*) FROM track WHERE NOT (
        trackartist IS NULL OR 
        EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist)
      )
    }
  } {0}
}

# Execute a series of random INSERT, UPDATE and DELETE operations
# (some of which may fail due to FK or PK constraint violations) on 
# the two tables in the example schema. Test that R-52486-21352
# is true after executing each operation.
#
set Template {
  {INSERT INTO track VALUES($t, 'track $t', $a)}
  {DELETE FROM track WHERE trackid = $t}
  {UPDATE track SET trackartist = $a WHERE trackid = $t}
  {INSERT INTO artist VALUES($a, 'artist $a')}
  {DELETE FROM artist WHERE artistid = $a}
  {UPDATE artist SET artistid = $a2 WHERE artistid = $a}
}
for {set i 0} {$i < 500} {incr i} {
  set a   [expr int(rand()*10)]
  set a2  [expr int(rand()*10)]
  set t   [expr int(rand()*50)]
  set sql [subst [lindex $Template [expr int(rand()*6)]]]

  test_r52486_21352 $i $sql
}

#-------------------------------------------------------------------------
# /* EV: R-42412-59321 */
#
# Check that a NOT NULL constraint can be added to the example schema
# to prohibit NULL child keys from being inserted.
#
drop_all_tables
do_test e_fkey-48.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER, 
      trackname   TEXT, 
      trackartist INTEGER NOT NULL,
      FOREIGN KEY(trackartist) REFERENCES artist(artistid)
    );
  }
} {}
do_test e_fkey-48.2 {
  catchsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL) }
} {1 {track.trackartist may not be NULL}}

#-------------------------------------------------------------------------
# /* EV: R-17902-59250 */
#
# Test an example from foreignkeys.html.
#
drop_all_tables
do_test e_fkey-43.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER, 
      trackname   TEXT, 
      trackartist INTEGER,
      FOREIGN KEY(trackartist) REFERENCES artist(artistid)
    );
    INSERT INTO artist VALUES(1, 'Dean Martin');
    INSERT INTO artist VALUES(2, 'Frank Sinatra');
    INSERT INTO track VALUES(11, 'That''s Amore', 1);
    INSERT INTO track VALUES(12, 'Christmas Blues', 1);
    INSERT INTO track VALUES(13, 'My Way', 2);
  }
} {}
do_test e_fkey-43.2 {
  catchsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', 3) }
} {1 {foreign key constraint failed}}
do_test e_fkey-43.3 {
  execsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL) }
} {}
do_test e_fkey-43.4 {
  catchsql { 
    UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
  }
} {1 {foreign key constraint failed}}
do_test e_fkey-43.5 {
  execsql {
    INSERT INTO artist VALUES(3, 'Sammy Davis Jr.');
    UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
    INSERT INTO track VALUES(15, 'Boogie Woogie', 3);
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-15034-64331 */
#
# Test the second example from the first section of foreignkeys.html.
#
do_test e_fkey-44.1 {
  catchsql {
    DELETE FROM artist WHERE artistname = 'Frank Sinatra';
  }
} {1 {foreign key constraint failed}}
do_test e_fkey-44.2 {
  execsql {
    DELETE FROM track WHERE trackname = 'My Way';
    DELETE FROM artist WHERE artistname = 'Frank Sinatra';
  }
} {}
do_test e_fkey-44.3 {
  catchsql {
    UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
  }
} {1 {foreign key constraint failed}}
do_test e_fkey-44.4 {
  execsql {
    DELETE FROM track WHERE trackname IN('That''s Amore', 'Christmas Blues');
    UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
  }
} {}


#-------------------------------------------------------------------------
# /* EV: R-56032-24923 */
#
# Test that a foreign key constraint is satisifed if "for each row in the child
# table either one or more of the child key columns are NULL, or there exists a
# row in the parent table for which each parent key column contains a value
# equal to the value in its associated child key column".
#
# /* EV: R-57765-12380 */
#
# Test also that the comparison rules are used when testing if there 
# is a matching row in the parent table of a foreign key constraint.
#
drop_all_tables
do_test e_fkey-45.1 {
  execsql {
    CREATE TABLE par(p PRIMARY KEY);
    CREATE TABLE chi(c REFERENCES par);

    INSERT INTO par VALUES(1);
    INSERT INTO par VALUES('1');
    INSERT INTO par VALUES(X'31');
    SELECT typeof(p) FROM par;
  }
} {integer text blob}

proc test_efkey_45 {tn isError sql} {
  do_test e_fkey-45.$tn.1 "
    catchsql {$sql}
  " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError]

  do_test e_fkey-45.$tn.2 {
    execsql {
      SELECT * FROM chi WHERE c IS NOT NULL AND c NOT IN (SELECT p FROM par)
    }
  } {}
}

test_efkey_45 1 0 "INSERT INTO chi VALUES(1)"
test_efkey_45 2 1 "INSERT INTO chi VALUES('1.0')"
test_efkey_45 3 0 "INSERT INTO chi VALUES('1')"
test_efkey_45 4 1 "DELETE FROM par WHERE p = '1'"
test_efkey_45 5 0 "DELETE FROM chi WHERE c = '1'"
test_efkey_45 6 0 "DELETE FROM par WHERE p = '1'"
test_efkey_45 7 1 "INSERT INTO chi VALUES('1')"
test_efkey_45 8 0 "INSERT INTO chi VALUES(X'31')"
test_efkey_45 9 1 "INSERT INTO chi VALUES(X'32')"

#-------------------------------------------------------------------------
# /* EV: R-15796-47513 */
#
# Specifically, test that when comparing child and parent key values the
# default collation sequence of the parent key column is used.
#
drop_all_tables
do_test e_fkey-46.1 {
  execsql {
    CREATE TABLE t1(a COLLATE nocase PRIMARY KEY);
    CREATE TABLE t2(b REFERENCES t1);
  }
} {}
do_test e_fkey-46.2 {
  execsql {
    INSERT INTO t1 VALUES('oNe');
    INSERT INTO t2 VALUES('one');
    INSERT INTO t2 VALUES('ONE');
    UPDATE t2 SET b = 'OnE';
    UPDATE t1 SET a = 'ONE';
  }
} {}
do_test e_fkey-46.3 {
  catchsql { UPDATE t2 SET b = 'two' WHERE rowid = 1 }
} {1 {foreign key constraint failed}}
do_test e_fkey-46.4 {
  catchsql { DELETE FROM t1 WHERE rowid = 1 }
} {1 {foreign key constraint failed}}

#-------------------------------------------------------------------------
# /* EV: R-04240-13860 */
#
# Specifically, test that when comparing child and parent key values the
# affinity of the parent key column is applied to the child key value
# before the comparison takes place.
#
drop_all_tables
do_test e_fkey-47.1 {
  execsql {
    CREATE TABLE t1(a NUMERIC PRIMARY KEY);
    CREATE TABLE t2(b TEXT REFERENCES t1);
  }
} {}
do_test e_fkey-47.2 {
  execsql {
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES('three');
    INSERT INTO t2 VALUES('2.0');
    SELECT b, typeof(b) FROM t2;
  }
} {2.0 text}
do_test e_fkey-47.3 {
  execsql { SELECT typeof(a) FROM t1 }
} {integer integer text}
do_test e_fkey-47.4 {
  catchsql { DELETE FROM t1 WHERE rowid = 2 }
} {1 {foreign key constraint failed}}

###########################################################################
### SECTION 3: Required and Suggested Database Indexes
###########################################################################

#-------------------------------------------------------------------------
# /* EV: R-13435-26311 */
#
# A parent key must be either a PRIMARY KEY, subject to a UNIQUE 
# constraint, or have a UNIQUE index created on it.
# 
# /* EV: R-00376-39212 */
#
# Also test that if a parent key is not subject to a PRIMARY KEY or UNIQUE
# constraint, but does have a UNIQUE index created on it, then the UNIQUE index
# must use the default collation sequences associated with the parent key
# columns.
#
drop_all_tables
do_test e_fkey-57.1 {
  execsql {
    CREATE TABLE t2(a REFERENCES t1(x));
  }
} {}
proc test_efkey_57 {tn isError sql} {
  catchsql { DROP TABLE t1 }
  execsql $sql
  do_test e_fkey-57.$tn {
    catchsql { INSERT INTO t2 VALUES(NULL) }
  } [lindex {{0 {}} {1 {foreign key mismatch}}} $isError]
}
test_efkey_57 2 0 { CREATE TABLE t1(x PRIMARY KEY) }
test_efkey_57 3 0 { CREATE TABLE t1(x UNIQUE) }
test_efkey_57 4 0 { CREATE TABLE t1(x); CREATE UNIQUE INDEX t1i ON t1(x) }
test_efkey_57 5 1 { 
  CREATE TABLE t1(x); 
  CREATE UNIQUE INDEX t1i ON t1(x COLLATE nocase);
}
test_efkey_57 6 1 { CREATE TABLE t1(x) }
test_efkey_57 7 1 { CREATE TABLE t1(x, y, PRIMARY KEY(x, y)) }
test_efkey_57 8 1 { CREATE TABLE t1(x, y, UNIQUE(x, y)) }
test_efkey_57 9 1 { 
  CREATE TABLE t1(x, y); 
  CREATE UNIQUE INDEX t1i ON t1(x, y);
}


#-------------------------------------------------------------------------
# This block tests an example in foreignkeys.html. Several testable
# statements refer to this example, as follows
#
# /* EV: R-27484-01467 */
#
# FK Constraints on child1, child2 and child3 are Ok.
#
# /* EV: R-51039-44840 */
#
# Problem with FK on child4.
#
# /* EV: R-01060-48788 */
#
# Problem with FK on child5.
#
# /* EV: R-63088-37469 */
#
# Problem with FK on child6 and child7.
#
drop_all_tables
do_test e_fkey-56.1 {
  execsql {
    CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f);
    CREATE UNIQUE INDEX i1 ON parent(c, d);
    CREATE INDEX i2 ON parent(e);
    CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase);

    CREATE TABLE child1(f, g REFERENCES parent(a));                       -- Ok
    CREATE TABLE child2(h, i REFERENCES parent(b));                       -- Ok
    CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d)); -- Ok
    CREATE TABLE child4(l, m REFERENCES parent(e));                       -- Err
    CREATE TABLE child5(n, o REFERENCES parent(f));                       -- Err
    CREATE TABLE child6(p, q, FOREIGN KEY(p,q) REFERENCES parent(b, c));  -- Err
    CREATE TABLE child7(r REFERENCES parent(c));                          -- Err
  }
} {}
do_test e_fkey-56.2 {
  execsql {
    INSERT INTO parent VALUES(1, 2, 3, 4, 5, 6);
    INSERT INTO child1 VALUES('xxx', 1);
    INSERT INTO child2 VALUES('xxx', 2);
    INSERT INTO child3 VALUES(3, 4);
  }
} {}
do_test e_fkey-56.2 {
  catchsql { INSERT INTO child4 VALUES('xxx', 5) }
} {1 {foreign key mismatch}}
do_test e_fkey-56.3 {
  catchsql { INSERT INTO child5 VALUES('xxx', 6) }
} {1 {foreign key mismatch}}
do_test e_fkey-56.4 {
  catchsql { INSERT INTO child6 VALUES(2, 3) }
} {1 {foreign key mismatch}}
do_test e_fkey-56.5 {
  catchsql { INSERT INTO child7 VALUES(3) }
} {1 {foreign key mismatch}}

#-------------------------------------------------------------------------
# /* EV: R-45488-08504 */
# /* EV: R-48391-38472 */
# /* EV: R-03108-63659 */
# /* EV: R-60781-26576 */
#
# Test errors in the database schema that are detected while preparing
# DML statements. The error text for these messages always matches 
# either "foreign key mismatch" or "no such table*" (using [string match]).
#
do_test e_fkey-66.1 {
  execsql {
    CREATE TABLE c1(c REFERENCES nosuchtable, d);

    CREATE TABLE p2(a, b, UNIQUE(a, b));
    CREATE TABLE c2(c, d, FOREIGN KEY(c, d) REFERENCES p2(a, x));

    CREATE TABLE p3(a PRIMARY KEY, b);
    CREATE TABLE c3(c REFERENCES p3(b), d);

    CREATE TABLE p4(a PRIMARY KEY, b);
    CREATE UNIQUE INDEX p4i ON p4(b COLLATE nocase);
    CREATE TABLE c4(c REFERENCES p4(b), d);

    CREATE TABLE p5(a PRIMARY KEY, b COLLATE nocase);
    CREATE UNIQUE INDEX p5i ON p5(b COLLATE binary);
    CREATE TABLE c5(c REFERENCES p5(b), d);

    CREATE TABLE p6(a PRIMARY KEY, b);
    CREATE TABLE c6(c, d, FOREIGN KEY(c, d) REFERENCES p6);

    CREATE TABLE p7(a, b, PRIMARY KEY(a, b));
    CREATE TABLE c7(c, d REFERENCES p7);
  }
} {}

foreach {tn tbl ptbl err} {
  2 c1 {} "no such table: main.nosuchtable"
  3 c2 p2 "foreign key mismatch"
  4 c3 p3 "foreign key mismatch"
  5 c4 p4 "foreign key mismatch"
  6 c5 p5 "foreign key mismatch"
  7 c6 p6 "foreign key mismatch"
  8 c7 p7 "foreign key mismatch"
} {
  do_test e_fkey-66.$tn.1 {
    catchsql "INSERT INTO $tbl VALUES('a', 'b')"
  } [list 1 $err]
  do_test e_fkey-66.$tn.2 {
    catchsql "UPDATE $tbl SET c = ?, d = ?"
  } [list 1 $err]
  do_test e_fkey-66.$tn.3 {
    catchsql "INSERT INTO $tbl SELECT ?, ?"
  } [list 1 $err]

  if {$ptbl ne ""} {
    do_test e_fkey-66.$tn.4 {
      catchsql "DELETE FROM $ptbl"
    } [list 1 $err]
    do_test e_fkey-66.$tn.5 {
      catchsql "UPDATE $ptbl SET a = ?, b = ?"
    } [list 1 $err]
    do_test e_fkey-66.$tn.6 {
      catchsql "INSERT INTO $ptbl SELECT ?, ?"
    } [list 1 $err]
  }
}

#-------------------------------------------------------------------------
# /* EV: R-19353-43643 */
#
# Test the example of foreign key mismatch errors caused by implicitly
# mapping a child key to the primary key of the parent table when the
# child key consists of a different number of columns to that primary key.
# 
drop_all_tables
do_test e_fkey-58.1 {
  execsql {
    CREATE TABLE parent2(a, b, PRIMARY KEY(a,b));

    CREATE TABLE child8(x, y, FOREIGN KEY(x,y) REFERENCES parent2);     -- Ok
    CREATE TABLE child9(x REFERENCES parent2);                          -- Err
    CREATE TABLE child10(x,y,z, FOREIGN KEY(x,y,z) REFERENCES parent2); -- Err
  }
} {}
do_test e_fkey-58.2 {
  execsql {
    INSERT INTO parent2 VALUES('I', 'II');
    INSERT INTO child8 VALUES('I', 'II');
  }
} {}
do_test e_fkey-58.3 {
  catchsql { INSERT INTO child9 VALUES('I') }
} {1 {foreign key mismatch}}
do_test e_fkey-58.4 {
  catchsql { INSERT INTO child9 VALUES('II') }
} {1 {foreign key mismatch}}
do_test e_fkey-58.5 {
  catchsql { INSERT INTO child9 VALUES(NULL) }
} {1 {foreign key mismatch}}
do_test e_fkey-58.6 {
  catchsql { INSERT INTO child10 VALUES('I', 'II', 'III') }
} {1 {foreign key mismatch}}
do_test e_fkey-58.7 {
  catchsql { INSERT INTO child10 VALUES(1, 2, 3) }
} {1 {foreign key mismatch}}
do_test e_fkey-58.8 {
  catchsql { INSERT INTO child10 VALUES(NULL, NULL, NULL) }
} {1 {foreign key mismatch}}

#-------------------------------------------------------------------------
# /* EV: R-23682-59820 */
#
# Test errors that are reported when creating the child table. 
# Specifically:
#
#   * different number of child and parent key columns, and
#   * child columns that do not exist.
#
# /* EV: R-33883-28833 */
#
# These errors are reported whether or not FK support is enabled.
#
drop_all_tables
foreach fk [list OFF ON] {
  execsql "PRAGMA foreign_keys = $fk"
  set i 0
  foreach {sql error} {
    "CREATE TABLE child1(a, b, FOREIGN KEY(a, b) REFERENCES p(c))"
      {number of columns in foreign key does not match the number of columns in the referenced table}
    "CREATE TABLE child2(a, b, FOREIGN KEY(a, b) REFERENCES p(c, d, e))"
      {number of columns in foreign key does not match the number of columns in the referenced table}
    "CREATE TABLE child2(a, b, FOREIGN KEY(a, c) REFERENCES p(c, d))"
      {unknown column "c" in foreign key definition}
    "CREATE TABLE child2(a, b, FOREIGN KEY(c, b) REFERENCES p(c, d))"
      {unknown column "c" in foreign key definition}
  } {
    do_test e_fkey-59.$fk.[incr i] {
      catchsql $sql
    } [list 1 $error]
  }
}

#-------------------------------------------------------------------------
# /* EV: R-47109-40581 */
#
# Test that a REFERENCING clause that does not specify parent key columns
# implicitly maps to the primary key of the parent table.
# 
do_test e_fkey-60.1 {
  execsql {
    CREATE TABLE p1(a, b, PRIMARY KEY(a, b));
    CREATE TABLE p2(a, b PRIMARY KEY);
    CREATE TABLE c1(c, d, FOREIGN KEY(c, d) REFERENCES p1);
    CREATE TABLE c2(a, b REFERENCES p2);
  }
} {}
proc test_efkey_60 {tn isError sql} {
  do_test e_fkey-60.$tn "
    catchsql {$sql}
  " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError]
}

test_efkey_60 2 1 "INSERT INTO c1 VALUES(239, 231)"
test_efkey_60 3 0 "INSERT INTO p1 VALUES(239, 231)"
test_efkey_60 4 0 "INSERT INTO c1 VALUES(239, 231)"
test_efkey_60 5 1 "INSERT INTO c2 VALUES(239, 231)"
test_efkey_60 6 0 "INSERT INTO p2 VALUES(239, 231)"
test_efkey_60 7 0 "INSERT INTO c2 VALUES(239, 231)"

#-------------------------------------------------------------------------
# /* EV: R-15417-28014 */
#
# Test that an index on on the child key columns of an FK constraint
# is optional.
#
# /* EV: R-15741-50893 */
#
# Also test that if an index is created on the child key columns, it does
# not make a difference whether or not it is a UNIQUE index.
#
drop_all_tables
do_test e_fkey-61.1 {
  execsql {
    CREATE TABLE parent(x, y, UNIQUE(y, x));
    CREATE TABLE c1(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y));
    CREATE TABLE c2(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y));
    CREATE TABLE c3(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y));
    CREATE INDEX c2i ON c2(a, b);
    CREATE UNIQUE INDEX c3i ON c2(b, a);
  }
} {}
proc test_efkey_61 {tn isError sql} {
  do_test e_fkey-61.$tn "
    catchsql {$sql}
  " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError]
}
foreach {tn c} [list 2 c1 3 c2 4 c3] {
  test_efkey_61 $tn.1 1 "INSERT INTO $c VALUES(1, 2)"
  test_efkey_61 $tn.2 0 "INSERT INTO parent VALUES(1, 2)"
  test_efkey_61 $tn.3 0 "INSERT INTO $c VALUES(1, 2)"

  execsql "DELETE FROM $c ; DELETE FROM parent"
}

#-------------------------------------------------------------------------
# /* EV: R-00279-52283 */
#
# Test an example showing that when a row is deleted from the parent 
# table, the child table is queried for orphaned rows as follows:
#
#   SELECT rowid FROM track WHERE trackartist = ?
#
# /* EV: R-23302-30956 */
#
# Also test that if the SELECT above would return any rows, a foreign
# key constraint is violated.
#
do_test e_fkey-62.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER, 
      trackname   TEXT, 
      trackartist INTEGER,
      FOREIGN KEY(trackartist) REFERENCES artist(artistid)
    );
  }
} {}
do_test e_fkey-62.2 {
  execsql {
    PRAGMA foreign_keys = OFF;
    EXPLAIN QUERY PLAN DELETE FROM artist WHERE 1;
    EXPLAIN QUERY PLAN SELECT rowid FROM track WHERE trackartist = ?;
  }
} {0 0 {TABLE artist} 0 0 {TABLE track}}
do_test e_fkey-62.3 {
  execsql { 
    PRAGMA foreign_keys = ON;
    EXPLAIN QUERY PLAN DELETE FROM artist WHERE 1;
  }
} {0 0 {TABLE artist} 0 0 {TABLE track}}
do_test e_fkey-62.4 {
  execsql {
    INSERT INTO artist VALUES(5, 'artist 5');
    INSERT INTO artist VALUES(6, 'artist 6');
    INSERT INTO artist VALUES(7, 'artist 7');
    INSERT INTO track VALUES(1, 'track 1', 5);
    INSERT INTO track VALUES(2, 'track 2', 6);
  }
} {}

do_test e_fkey-62.5 {
  concat \
    [execsql { SELECT rowid FROM track WHERE trackartist = 5 }]   \
    [catchsql { DELETE FROM artist WHERE artistid = 5 }]
} {1 1 {foreign key constraint failed}}

do_test e_fkey-62.6 {
  concat \
    [execsql { SELECT rowid FROM track WHERE trackartist = 7 }]   \
    [catchsql { DELETE FROM artist WHERE artistid = 7 }]
} {0 {}}

do_test e_fkey-62.7 {
  concat \
    [execsql { SELECT rowid FROM track WHERE trackartist = 6 }]   \
    [catchsql { DELETE FROM artist WHERE artistid = 6 }]
} {2 1 {foreign key constraint failed}}

#-------------------------------------------------------------------------
# /* EV: R-54172-55848 */
#
# Test that when a row is deleted from the parent table of an FK 
# constraint, the child table is queried for orphaned rows. The
# query is equivalent to:
#
#   SELECT rowid FROM <child-table> WHERE <child-key> = :parent_key_value
#
# /* EV: R-61616-46700 */
#
# Also test that when a row is inserted into the parent table, or when the 
# parent key values of an existing row are modified, a query equivalent
# to the following is planned. In some cases it is not executed, but it
# is always planned.
#
#   SELECT rowid FROM <child-table> WHERE <child-key> = :parent_key_value
#
#
drop_all_tables
do_test e_fkey-64.1 {
  execsql { CREATE TABLE parent(x, y, UNIQUE(y, x)) }
} {}
foreach {tn sql} {
  2 { 
    CREATE TABLE child(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y))
  }
  3 { 
    CREATE TABLE child(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y));
    CREATE INDEX childi ON child(a, b);
  }
  4 { 
    CREATE TABLE child(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y));
    CREATE UNIQUE INDEX childi ON child(b, a);
  }
} {
  execsql $sql

  execsql {PRAGMA foreign_keys = OFF}
  set delete [concat \
      [eqp "DELETE FROM parent WHERE 1"] \
      [eqp "SELECT rowid FROM child WHERE a = ? AND b = ?"]
  ]
  set update [concat \
      [eqp "UPDATE parent SET x=?, y=?"] \
      [eqp "SELECT rowid FROM child WHERE a = ? AND b = ?"] \
      [eqp "SELECT rowid FROM child WHERE a = ? AND b = ?"]
  ]
  execsql {PRAGMA foreign_keys = ON}

  do_test e_fkey-64.$tn.1 { eqp "DELETE FROM parent WHERE 1" } $delete
  do_test e_fkey-64.$tn.2 { eqp "UPDATE parent set x=?, y=?" } $update

  execsql {DROP TABLE child}
}

#-------------------------------------------------------------------------
# /* EV: R-14553-34013 */
#
# Test the example schema at the end of section 3. Also test that is
# is "efficient". In this case "efficient" means that foreign key
# related operations on the parent table do not provoke linear scans.
#
drop_all_tables
do_test e_fkey-63.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER,
      trackname   TEXT, 
      trackartist INTEGER REFERENCES artist
    );
    CREATE INDEX trackindex ON track(trackartist);
  }
} {}
do_test e_fkey-63.2 {
  eqp { INSERT INTO artist VALUES(?, ?) }
} {}
do_test e_fkey-63.3 {
  eqp { UPDATE artist SET artistid = ?, artistname = ? }
} [list \
  0 0 {TABLE artist} \
  0 0 {TABLE track WITH INDEX trackindex} \
  0 0 {TABLE track WITH INDEX trackindex}
]
do_test e_fkey-63.4 {
  eqp { DELETE FROM artist }
} [list \
  0 0 {TABLE artist} \
  0 0 {TABLE track WITH INDEX trackindex}
]


###########################################################################
### SECTION 4.1: Composite Foreign Key Constraints
###########################################################################

#-------------------------------------------------------------------------
# /* EV: R-41062-34431 */
#
# Check that parent and child keys must have the same number of columns.
#
foreach {tn sql err} {
  1 "CREATE TABLE c(jj REFERENCES p(x, y))" 
    {foreign key on jj should reference only one column of table p}

  2 "CREATE TABLE c(jj REFERENCES p())" {near ")": syntax error}

  3 "CREATE TABLE c(jj, FOREIGN KEY(jj) REFERENCES p(x, y))" 
    {number of columns in foreign key does not match the number of columns in the referenced table}

  4 "CREATE TABLE c(jj, FOREIGN KEY(jj) REFERENCES p())" 
    {near ")": syntax error}

  5 "CREATE TABLE c(ii, jj, FOREIGN KEY(jj, ii) REFERENCES p())" 
    {near ")": syntax error}

  6 "CREATE TABLE c(ii, jj, FOREIGN KEY(jj, ii) REFERENCES p(x))" 
    {number of columns in foreign key does not match the number of columns in the referenced table}

  7 "CREATE TABLE c(ii, jj, FOREIGN KEY(jj, ii) REFERENCES p(x,y,z))" 
    {number of columns in foreign key does not match the number of columns in the referenced table}
} {
  drop_all_tables
  do_test e_fkey-65.$tn [list catchsql $sql] [list 1 $err]
}
do_test e_fkey-65.8 {
  drop_all_tables
  execsql {
    CREATE TABLE p(x PRIMARY KEY);
    CREATE TABLE c(a, b, FOREIGN KEY(a,b) REFERENCES p);
  }
  catchsql {DELETE FROM p}
} {1 {foreign key mismatch}}
do_test e_fkey-65.9 {
  drop_all_tables
  execsql {
    CREATE TABLE p(x, y, PRIMARY KEY(x,y));
    CREATE TABLE c(a REFERENCES p);
  }
  catchsql {DELETE FROM p}
} {1 {foreign key mismatch}}


#-------------------------------------------------------------------------
# /* EV: R-24676-09859 */
#
# Test the example schema in the "Composite Foreign Key Constraints" 
# section.
#
do_test e_fkey-36.1 {
  execsql {
    CREATE TABLE album(
      albumartist TEXT,
      albumname TEXT,
      albumcover BINARY,
      PRIMARY KEY(albumartist, albumname)
    );
    CREATE TABLE song(
      songid INTEGER,
      songartist TEXT,
      songalbum TEXT,
      songname TEXT,
      FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist,albumname)
    );
  }
} {}

do_test e_fkey-36.2 {
  execsql {
    INSERT INTO album VALUES('Elvis Presley', 'Elvis'' Christmas Album', NULL);
    INSERT INTO song VALUES(
      1, 'Elvis Presley', 'Elvis'' Christmas Album', 'Here Comes Santa Clause'
    );
  }
} {}
do_test e_fkey-36.3 {
  catchsql {
    INSERT INTO song VALUES(2, 'Elvis Presley', 'Elvis Is Back!', 'Fever');
  }
} {1 {foreign key constraint failed}}


#-------------------------------------------------------------------------
# /* EV: R-33626-48418 */
#
# Check that if any of the child key columns in the above schema are NULL,
# there is no requirement for a corresponding parent key.
#
do_test e_fkey-37.1 {
  execsql {
    INSERT INTO song VALUES(2, 'Elvis Presley', NULL, 'Fever');
    INSERT INTO song VALUES(3, NULL, 'Elvis Is Back', 'Soldier Boy');
  }
} {}

###########################################################################
### SECTION 4.2: Deferred Foreign Key Constraints
###########################################################################

#-------------------------------------------------------------------------
# Note: R-35290-16460 is tested below.
#
# TODO: R-30323-21917

#-------------------------------------------------------------------------
# /* EV: R-09323-30470 */
#
# Test that if a statement violates an immediate FK constraint, and the
# database does not satisfy the FK constraint once all effects of the
# statement have been applied, an error is reported and the effects of
# the statement rolled back.
#
drop_all_tables
do_test e_fkey-33.1 {
  execsql {
    CREATE TABLE king(a, b, PRIMARY KEY(a));
    CREATE TABLE prince(c REFERENCES king, d);
  }
} {}

do_test e_fkey-33.2 {
  # Execute a statement that violates the immediate FK constraint.
  catchsql { INSERT INTO prince VALUES(1, 2) }
} {1 {foreign key constraint failed}}

do_test e_fkey-33.3 {
  # This time, use a trigger to fix the constraint violation before the
  # statement has finished executing. Then execute the same statement as
  # in the previous test case. This time, no error.
  execsql {
    CREATE TRIGGER kt AFTER INSERT ON prince WHEN
      NOT EXISTS (SELECT a FROM king WHERE a = new.c)
    BEGIN
      INSERT INTO king VALUES(new.c, NULL);
    END
  }
  execsql { INSERT INTO prince VALUES(1, 2) }
} {}

# Test that operating inside a transaction makes no difference to 
# immediate constraint violation handling.
do_test e_fkey-33.4 {
  execsql {
    BEGIN;
    INSERT INTO prince VALUES(2, 3);
    DROP TRIGGER kt;
  }
  catchsql { INSERT INTO prince VALUES(3, 4) }
} {1 {foreign key constraint failed}}
do_test e_fkey-33.5 {
  execsql {
    COMMIT;
    SELECT * FROM king;
  }
} {1 {} 2 {}}

#-------------------------------------------------------------------------
# /* EV: R-49178-21358 */
# /* EV: R-39692-12488 */
# /* EV: R-55147-47664 */
# /* EV: R-29604-30395 */
#
# Test that if a deferred constraint is violated within a transaction,
# nothing happens immediately and the database is allowed to persist
# in a state that does not satisfy the FK constraint. However attempts
# to COMMIT the transaction fail until the FK constraint is satisfied.
#
proc test_efkey_34 {tn isError sql} {
  do_test e_fkey-34.$tn "
    catchsql {$sql}
  " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError]
}
drop_all_tables

test_efkey_34  1 0 {
  CREATE TABLE ll(k PRIMARY KEY);
  CREATE TABLE kk(c REFERENCES ll DEFERRABLE INITIALLY DEFERRED);
}
test_efkey_34  2 0 "BEGIN"
test_efkey_34  3 0   "INSERT INTO kk VALUES(5)"
test_efkey_34  4 0   "INSERT INTO kk VALUES(10)"
test_efkey_34  5 1 "COMMIT"
test_efkey_34  6 0   "INSERT INTO ll VALUES(10)"
test_efkey_34  7 1 "COMMIT"
test_efkey_34  8 0   "INSERT INTO ll VALUES(5)"
test_efkey_34  9 0 "COMMIT"

#-------------------------------------------------------------------------
# /* EV: R-56844-61705 */
#
# When not running inside a transaction, a deferred constraint is similar
# to an immediate constraint (violations are reported immediately).
#
drop_all_tables
proc test_efkey_35 {tn isError sql} {
  do_test e_fkey-35.$tn "
    catchsql {$sql}
  " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError]
}
do_test e_fkey-35.1 {
  execsql {
    CREATE TABLE parent(x, y);
    CREATE UNIQUE INDEX pi ON parent(x, y);
    CREATE TABLE child(a, b,
      FOREIGN KEY(a, b) REFERENCES parent(x, y) DEFERRABLE INITIALLY DEFERRED
    );
  }
} {}
test_efkey_35 2 1 "INSERT INTO child  VALUES('x', 'y')"
test_efkey_35 3 0 "INSERT INTO parent VALUES('x', 'y')"
test_efkey_35 4 0 "INSERT INTO child  VALUES('x', 'y')"


#-------------------------------------------------------------------------
# /* EV: R-12782-61841 */
#
# Test that an FK constraint is made deferred by adding the following
# to the definition:
#
#   DEFERRABLE INITIALLY DEFERRED
#
# /* EV: R-09005-28791 */
#
# Also test that adding any of the following to a foreign key definition 
# makes the constraint IMMEDIATE:
#
#   NOT DEFERRABLE INITIALLY DEFERRED
#   NOT DEFERRABLE INITIALLY IMMEDIATE
#   NOT DEFERRABLE
#   DEFERRABLE INITIALLY IMMEDIATE
#   DEFERRABLE
#
# /* EV: R-35290-16460 */
#
# Foreign keys are IMMEDIATE by default (if there is no DEFERRABLE or NOT
# DEFERRABLE clause).
#
# /* EV: R-30323-21917 */  FKs are either IMMEDIATE or DEFERRED.
#
drop_all_tables
do_test e_fkey-29.1 {
  execsql {
    CREATE TABLE parent(x, y, z, PRIMARY KEY(x,y,z));
    CREATE TABLE c1(a, b, c,
      FOREIGN KEY(a, b, c) REFERENCES parent NOT DEFERRABLE INITIALLY DEFERRED
    );
    CREATE TABLE c2(a, b, c,
      FOREIGN KEY(a, b, c) REFERENCES parent NOT DEFERRABLE INITIALLY IMMEDIATE
    );
    CREATE TABLE c3(a, b, c,
      FOREIGN KEY(a, b, c) REFERENCES parent NOT DEFERRABLE
    );
    CREATE TABLE c4(a, b, c,
      FOREIGN KEY(a, b, c) REFERENCES parent DEFERRABLE INITIALLY IMMEDIATE
    );
    CREATE TABLE c5(a, b, c,
      FOREIGN KEY(a, b, c) REFERENCES parent DEFERRABLE
    );
    CREATE TABLE c6(a, b, c, FOREIGN KEY(a, b, c) REFERENCES parent);

    -- This FK constraint is the only deferrable one.
    CREATE TABLE c7(a, b, c,
      FOREIGN KEY(a, b, c) REFERENCES parent DEFERRABLE INITIALLY DEFERRED
    );

    INSERT INTO parent VALUES('a', 'b', 'c');
    INSERT INTO parent VALUES('d', 'e', 'f');
    INSERT INTO parent VALUES('g', 'h', 'i');
    INSERT INTO parent VALUES('j', 'k', 'l');
    INSERT INTO parent VALUES('m', 'n', 'o');
    INSERT INTO parent VALUES('p', 'q', 'r');
    INSERT INTO parent VALUES('s', 't', 'u');

    INSERT INTO c1 VALUES('a', 'b', 'c');
    INSERT INTO c2 VALUES('d', 'e', 'f');
    INSERT INTO c3 VALUES('g', 'h', 'i');
    INSERT INTO c4 VALUES('j', 'k', 'l');
    INSERT INTO c5 VALUES('m', 'n', 'o');
    INSERT INTO c6 VALUES('p', 'q', 'r');
    INSERT INTO c7 VALUES('s', 't', 'u');
  }
} {}

proc test_efkey_29 {tn sql isError} {
  do_test e_fkey-29.$tn "catchsql {$sql}" [
    lindex {{0 {}} {1 {foreign key constraint failed}}} $isError
  ]
}
test_efkey_29  2 "BEGIN"                                   0
test_efkey_29  3 "DELETE FROM parent WHERE x = 'a'"        1
test_efkey_29  4 "DELETE FROM parent WHERE x = 'd'"        1
test_efkey_29  5 "DELETE FROM parent WHERE x = 'g'"        1
test_efkey_29  6 "DELETE FROM parent WHERE x = 'j'"        1
test_efkey_29  7 "DELETE FROM parent WHERE x = 'm'"        1
test_efkey_29  8 "DELETE FROM parent WHERE x = 'p'"        1
test_efkey_29  9 "DELETE FROM parent WHERE x = 's'"        0
test_efkey_29 10 "COMMIT"                                  1
test_efkey_29 11 "ROLLBACK"                                0

test_efkey_29  9 "BEGIN"                                   0
test_efkey_29 10 "UPDATE parent SET z = 'z' WHERE z = 'c'" 1
test_efkey_29 11 "UPDATE parent SET z = 'z' WHERE z = 'f'" 1
test_efkey_29 12 "UPDATE parent SET z = 'z' WHERE z = 'i'" 1
test_efkey_29 13 "UPDATE parent SET z = 'z' WHERE z = 'l'" 1
test_efkey_29 14 "UPDATE parent SET z = 'z' WHERE z = 'o'" 1
test_efkey_29 15 "UPDATE parent SET z = 'z' WHERE z = 'r'" 1
test_efkey_29 16 "UPDATE parent SET z = 'z' WHERE z = 'u'" 0
test_efkey_29 17 "COMMIT"                                  1
test_efkey_29 18 "ROLLBACK"                                0

test_efkey_29 17 "BEGIN"                                   0
test_efkey_29 18 "INSERT INTO c1 VALUES(1, 2, 3)"          1
test_efkey_29 19 "INSERT INTO c2 VALUES(1, 2, 3)"          1
test_efkey_29 20 "INSERT INTO c3 VALUES(1, 2, 3)"          1
test_efkey_29 21 "INSERT INTO c4 VALUES(1, 2, 3)"          1
test_efkey_29 22 "INSERT INTO c5 VALUES(1, 2, 3)"          1
test_efkey_29 22 "INSERT INTO c6 VALUES(1, 2, 3)"          1
test_efkey_29 22 "INSERT INTO c7 VALUES(1, 2, 3)"          0
test_efkey_29 23 "COMMIT"                                  1
test_efkey_29 24 "INSERT INTO parent VALUES(1, 2, 3)"      0
test_efkey_29 25 "COMMIT"                                  0

test_efkey_29 26 "BEGIN"                                   0
test_efkey_29 27 "UPDATE c1 SET a = 10"                    1
test_efkey_29 28 "UPDATE c2 SET a = 10"                    1
test_efkey_29 29 "UPDATE c3 SET a = 10"                    1
test_efkey_29 30 "UPDATE c4 SET a = 10"                    1
test_efkey_29 31 "UPDATE c5 SET a = 10"                    1
test_efkey_29 31 "UPDATE c6 SET a = 10"                    1
test_efkey_29 31 "UPDATE c7 SET a = 10"                    0
test_efkey_29 32 "COMMIT"                                  1
test_efkey_29 33 "ROLLBACK"                                0

#-------------------------------------------------------------------------
# /* EV: R-35043-01546 */
#
# Test an example from foreignkeys.html dealing with a deferred foreign 
# key constraint.
#
do_test e_fkey-28.1 {
  drop_all_tables
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER,
      trackname   TEXT, 
      trackartist INTEGER REFERENCES artist(artistid) DEFERRABLE INITIALLY DEFERRED
    );
  }
} {}
do_test e_fkey-28.2 {
  execsql {
    BEGIN;
      INSERT INTO track VALUES(1, 'White Christmas', 5);
  }
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-28.3 {
  execsql {
    INSERT INTO artist VALUES(5, 'Bing Crosby');
    COMMIT;
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-07223-48323 */
#
# Verify that a nested savepoint may be released without satisfying 
# deferred foreign key constraints.
#
drop_all_tables
do_test e_fkey-30.1 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY,
      b REFERENCES t1 DEFERRABLE INITIALLY DEFERRED
    );
    INSERT INTO t1 VALUES(1, 1);
    INSERT INTO t1 VALUES(2, 2);
    INSERT INTO t1 VALUES(3, 3);
  }
} {}
do_test e_fkey-30.2 {
  execsql {
    BEGIN;
      SAVEPOINT one;
        INSERT INTO t1 VALUES(4, 5);
      RELEASE one;
  }
} {}
do_test e_fkey-30.3 {
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-30.4 {
  execsql {
    UPDATE t1 SET a = 5 WHERE a = 4;
    COMMIT;
  }
} {}


#-------------------------------------------------------------------------
# /* EV: R-44295-13823 */
#
# Check that a transaction savepoint (an outermost savepoint opened when
# the database was in auto-commit mode) cannot be released without
# satisfying deferred foreign key constraints. It may be rolled back.
#
do_test e_fkey-31.1 {
  execsql {
    SAVEPOINT one;
      SAVEPOINT two;
        INSERT INTO t1 VALUES(6, 7);
      RELEASE two;
  }
} {}
do_test e_fkey-31.2 {
  catchsql {RELEASE one}
} {1 {foreign key constraint failed}}
do_test e_fkey-31.3 {
  execsql {
      UPDATE t1 SET a = 7 WHERE a = 6;
    RELEASE one;
  }
} {}
do_test e_fkey-31.4 {
  execsql {
    SAVEPOINT one;
      SAVEPOINT two;
        INSERT INTO t1 VALUES(9, 10);
      RELEASE two;
  }
} {}
do_test e_fkey-31.5 {
  catchsql {RELEASE one}
} {1 {foreign key constraint failed}}
do_test e_fkey-31.6 {
  execsql {ROLLBACK TO one ; RELEASE one}
} {}

#-------------------------------------------------------------------------
# /* EV: R-37736-42616 */
#
# Test that if a COMMIT operation fails due to deferred foreign key 
# constraints, any nested savepoints remain open.
#
do_test e_fkey-32.1 {
  execsql {
    DELETE FROM t1 WHERE a>3;
    SELECT * FROM t1;
  }
} {1 1 2 2 3 3}
do_test e_fkey-32.2 {
  execsql {
    BEGIN;
      INSERT INTO t1 VALUES(4, 4);
      SAVEPOINT one;
        INSERT INTO t1 VALUES(5, 6);
        SELECT * FROM t1;
  }
} {1 1 2 2 3 3 4 4 5 6}
do_test e_fkey-32.3 {
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-32.4 {
  execsql {
    ROLLBACK TO one;
    COMMIT;
    SELECT * FROM t1;
  }
} {1 1 2 2 3 3 4 4}

do_test e_fkey-32.5 {
  execsql {
    SAVEPOINT a;
      INSERT INTO t1 VALUES(5, 5);
      SAVEPOINT b;
        INSERT INTO t1 VALUES(6, 7);
        SAVEPOINT c;
          INSERT INTO t1 VALUES(7, 8);
  }
} {}
do_test e_fkey-32.6 {
  catchsql {RELEASE a}
} {1 {foreign key constraint failed}}
do_test e_fkey-32.7 {
  execsql  {ROLLBACK TO c}
  catchsql {RELEASE a}
} {1 {foreign key constraint failed}}
do_test e_fkey-32.8 {
  execsql  {
    ROLLBACK TO b;
    RELEASE a;
    SELECT * FROM t1;
  }
} {1 1 2 2 3 3 4 4 5 5}

###########################################################################
### SECTION 4.3: ON DELETE and ON UPDATE Actions
###########################################################################

#-------------------------------------------------------------------------
# /* EV: R-48270-44282 */
#
# Test that configured ON DELETE and ON UPDATE actions take place when
# deleting or modifying rows of the parent table, respectively.
#
# /* EV: R-48124-63225 */
#
# Test that a single FK constraint may have different actions configured
# for ON DELETE and ON UPDATE.
#
do_test e_fkey-16.1 {
  execsql {
    CREATE TABLE p(a, b PRIMARY KEY, c);
    CREATE TABLE c1(d, e, f DEFAULT 'k0' REFERENCES p 
      ON UPDATE SET DEFAULT
      ON DELETE SET NULL
    );

    INSERT INTO p VALUES(0, 'k0', '');
    INSERT INTO p VALUES(1, 'k1', 'I');
    INSERT INTO p VALUES(2, 'k2', 'II');
    INSERT INTO p VALUES(3, 'k3', 'III');

    INSERT INTO c1 VALUES(1, 'xx', 'k1');
    INSERT INTO c1 VALUES(2, 'xx', 'k2');
    INSERT INTO c1 VALUES(3, 'xx', 'k3');
  }
} {}
do_test e_fkey-16.2 {
  execsql {
    UPDATE p SET b = 'k4' WHERE a = 1;
    SELECT * FROM c1;
  }
} {1 xx k0 2 xx k2 3 xx k3}
do_test e_fkey-16.3 {
  execsql {
    DELETE FROM p WHERE a = 2;
    SELECT * FROM c1;
  }
} {1 xx k0 2 xx {} 3 xx k3}
do_test e_fkey-16.4 {
  execsql {
    CREATE UNIQUE INDEX pi ON p(c);
    REPLACE INTO p VALUES(5, 'k5', 'III');
    SELECT * FROM c1;
  }
} {1 xx k0 2 xx {} 3 xx {}}

#-------------------------------------------------------------------------
# /* EV: R-33326-45252 */
#
# Each foreign key in the system has an ON UPDATE and ON DELETE action,
# either "NO ACTION", "RESTRICT", "SET NULL", "SET DEFAULT" or "CASCADE".
#
# /* EV: R-19803-45884 */
#
# If none is specified explicitly, "NO ACTION" is the default.
# 
drop_all_tables
do_test e_fkey-17.1 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY, y);
    CREATE TABLE child1(a, 
      b REFERENCES parent ON UPDATE NO ACTION ON DELETE RESTRICT
    );
    CREATE TABLE child2(a, 
      b REFERENCES parent ON UPDATE RESTRICT ON DELETE SET NULL
    );
    CREATE TABLE child3(a, 
      b REFERENCES parent ON UPDATE SET NULL ON DELETE SET DEFAULT
    );
    CREATE TABLE child4(a, 
      b REFERENCES parent ON UPDATE SET DEFAULT ON DELETE CASCADE
    );

    -- Create some foreign keys that use the default action - "NO ACTION"
    CREATE TABLE child5(a, b REFERENCES parent ON UPDATE CASCADE);
    CREATE TABLE child6(a, b REFERENCES parent ON DELETE RESTRICT);
    CREATE TABLE child7(a, b REFERENCES parent ON DELETE NO ACTION);
    CREATE TABLE child8(a, b REFERENCES parent ON UPDATE NO ACTION);
  }
} {}

foreach {tn zTab lRes} {
  2 child1 {0 0 parent b {} {NO ACTION} RESTRICT NONE}
  3 child2 {0 0 parent b {} RESTRICT {SET NULL} NONE}
  4 child3 {0 0 parent b {} {SET NULL} {SET DEFAULT} NONE}
  5 child4 {0 0 parent b {} {SET DEFAULT} CASCADE NONE}
  6 child5 {0 0 parent b {} CASCADE {NO ACTION} NONE}
  7 child6 {0 0 parent b {} {NO ACTION} RESTRICT NONE}
  8 child7 {0 0 parent b {} {NO ACTION} {NO ACTION} NONE}
  9 child8 {0 0 parent b {} {NO ACTION} {NO ACTION} NONE}
} {
  do_test e_fkey-17.$tn { execsql "PRAGMA foreign_key_list($zTab)" } $lRes
}

#-------------------------------------------------------------------------
# /* EV: R-19971-54976 */
#
# Test that "NO ACTION" means that nothing happens to a child row when
# it's parent row is updated or deleted.
#
drop_all_tables
do_test e_fkey-18.1 {
  execsql {
    CREATE TABLE parent(p1, p2, PRIMARY KEY(p1, p2));
    CREATE TABLE child(c1, c2, 
      FOREIGN KEY(c1, c2) REFERENCES parent
      ON UPDATE NO ACTION
      ON DELETE NO ACTION
      DEFERRABLE INITIALLY DEFERRED
    );
    INSERT INTO parent VALUES('j', 'k');
    INSERT INTO parent VALUES('l', 'm');
    INSERT INTO child VALUES('j', 'k');
    INSERT INTO child VALUES('l', 'm');
  }
} {}
do_test e_fkey-18.2 {
  execsql {
    BEGIN;
      UPDATE parent SET p1='k' WHERE p1='j';
      DELETE FROM parent WHERE p1='l';
      SELECT * FROM child;
  }
} {j k l m}
do_test e_fkey-18.3 {
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-18.4 {
  execsql ROLLBACK
} {}

#-------------------------------------------------------------------------
# /* EV: R-04272-38653 */
#
# Test that "RESTRICT" means the application is prohibited from deleting
# or updating a parent table row when there exists one or more child keys
# mapped to it.
#
drop_all_tables
do_test e_fkey-18.1 {
  execsql {
    CREATE TABLE parent(p1, p2);
    CREATE UNIQUE INDEX parent_i ON parent(p1, p2);
    CREATE TABLE child1(c1, c2, 
      FOREIGN KEY(c2, c1) REFERENCES parent(p1, p2) ON DELETE RESTRICT
    );
    CREATE TABLE child2(c1, c2, 
      FOREIGN KEY(c2, c1) REFERENCES parent(p1, p2) ON UPDATE RESTRICT
    );
  }
} {}
do_test e_fkey-18.2 {
  execsql {
    INSERT INTO parent VALUES('a', 'b');
    INSERT INTO parent VALUES('c', 'd');
    INSERT INTO child1 VALUES('b', 'a');
    INSERT INTO child2 VALUES('d', 'c');
  }
} {}
do_test e_fkey-18.3 {
  catchsql { DELETE FROM parent WHERE p1 = 'a' }
} {1 {foreign key constraint failed}}
do_test e_fkey-18.4 {
  catchsql { UPDATE parent SET p2 = 'e' WHERE p1 = 'c' }
} {1 {foreign key constraint failed}}

#-------------------------------------------------------------------------
# /* EV: R-37997-42187 */
# 
# Test that RESTRICT is slightly different from NO ACTION for IMMEDIATE
# constraints, in that it is enforced immediately, not at the end of the 
# statement.
#
drop_all_tables
do_test e_fkey-19.1 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY);
    CREATE TABLE child1(c REFERENCES parent ON UPDATE RESTRICT);
    CREATE TABLE child2(c REFERENCES parent ON UPDATE NO ACTION);

    INSERT INTO parent VALUES('key1');
    INSERT INTO parent VALUES('key2');
    INSERT INTO child1 VALUES('key1');
    INSERT INTO child2 VALUES('key2');

    CREATE TRIGGER parent_t AFTER UPDATE ON parent BEGIN
      UPDATE child1 set c = new.x WHERE c = old.x;
      UPDATE child2 set c = new.x WHERE c = old.x;
    END;
  }
} {}
do_test e_fkey-19.2 {
  catchsql { UPDATE parent SET x = 'key one' WHERE x = 'key1' }
} {1 {foreign key constraint failed}}
do_test e_fkey-19.3 {
  execsql { 
    UPDATE parent SET x = 'key two' WHERE x = 'key2';
    SELECT * FROM child2;
  }
} {{key two}}

drop_all_tables
do_test e_fkey-19.4 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY);
    CREATE TABLE child1(c REFERENCES parent ON DELETE RESTRICT);
    CREATE TABLE child2(c REFERENCES parent ON DELETE NO ACTION);

    INSERT INTO parent VALUES('key1');
    INSERT INTO parent VALUES('key2');
    INSERT INTO child1 VALUES('key1');
    INSERT INTO child2 VALUES('key2');

    CREATE TRIGGER parent_t AFTER DELETE ON parent BEGIN
      UPDATE child1 SET c = NULL WHERE c = old.x;
      UPDATE child2 SET c = NULL WHERE c = old.x;
    END;
  }
} {}
do_test e_fkey-19.5 {
  catchsql { DELETE FROM parent WHERE x = 'key1' }
} {1 {foreign key constraint failed}}
do_test e_fkey-19.6 {
  execsql { 
    DELETE FROM parent WHERE x = 'key2';
    SELECT * FROM child2;
  }
} {{}}

drop_all_tables
do_test e_fkey-19.7 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY);
    CREATE TABLE child1(c REFERENCES parent ON DELETE RESTRICT);
    CREATE TABLE child2(c REFERENCES parent ON DELETE NO ACTION);

    INSERT INTO parent VALUES('key1');
    INSERT INTO parent VALUES('key2');
    INSERT INTO child1 VALUES('key1');
    INSERT INTO child2 VALUES('key2');
  }
} {}
do_test e_fkey-19.8 {
  catchsql { REPLACE INTO parent VALUES('key1') }
} {1 {foreign key constraint failed}}
do_test e_fkey-19.9 {
  execsql { 
    REPLACE INTO parent VALUES('key2');
    SELECT * FROM child2;
  }
} {key2}

#-------------------------------------------------------------------------
# /* EV: R-24179-60523 */
# 
# Test that RESTRICT is enforced immediately, even for a DEFERRED constraint.
#
drop_all_tables
do_test e_fkey-20.1 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY);
    CREATE TABLE child1(c REFERENCES parent ON UPDATE RESTRICT
      DEFERRABLE INITIALLY DEFERRED
    );
    CREATE TABLE child2(c REFERENCES parent ON UPDATE NO ACTION
      DEFERRABLE INITIALLY DEFERRED
    );

    INSERT INTO parent VALUES('key1');
    INSERT INTO parent VALUES('key2');
    INSERT INTO child1 VALUES('key1');
    INSERT INTO child2 VALUES('key2');
    BEGIN;
  }
} {}
do_test e_fkey-20.2 {
  catchsql { UPDATE parent SET x = 'key one' WHERE x = 'key1' }
} {1 {foreign key constraint failed}}
do_test e_fkey-20.3 {
  execsql { UPDATE parent SET x = 'key two' WHERE x = 'key2' }
} {}
do_test e_fkey-20.4 {
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-20.5 {
  execsql {
    UPDATE child2 SET c = 'key two';
    COMMIT;
  }
} {}

drop_all_tables
do_test e_fkey-20.6 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY);
    CREATE TABLE child1(c REFERENCES parent ON DELETE RESTRICT
      DEFERRABLE INITIALLY DEFERRED
    );
    CREATE TABLE child2(c REFERENCES parent ON DELETE NO ACTION
      DEFERRABLE INITIALLY DEFERRED
    );

    INSERT INTO parent VALUES('key1');
    INSERT INTO parent VALUES('key2');
    INSERT INTO child1 VALUES('key1');
    INSERT INTO child2 VALUES('key2');
    BEGIN;
  }
} {}
do_test e_fkey-20.7 {
  catchsql { DELETE FROM parent WHERE x = 'key1' }
} {1 {foreign key constraint failed}}
do_test e_fkey-20.8 {
  execsql { DELETE FROM parent WHERE x = 'key2' }
} {}
do_test e_fkey-20.9 {
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-20.10 {
  execsql {
    UPDATE child2 SET c = NULL;
    COMMIT;
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-03353-05327 */
#
# Test SET NULL actions.
#
drop_all_tables
do_test e_fkey-21.1 {
  execsql {
    CREATE TABLE pA(x PRIMARY KEY);
    CREATE TABLE cA(c REFERENCES pA ON DELETE SET NULL);
    CREATE TABLE cB(c REFERENCES pA ON UPDATE SET NULL);

    INSERT INTO pA VALUES(X'ABCD');
    INSERT INTO pA VALUES(X'1234');
    INSERT INTO cA VALUES(X'ABCD');
    INSERT INTO cB VALUES(X'1234');
  }
} {}
do_test e_fkey-21.2 {
  execsql {
    DELETE FROM pA WHERE rowid = 1;
    SELECT quote(x) FROM pA;
  }
} {X'1234'}
do_test e_fkey-21.3 {
  execsql {
    SELECT quote(c) FROM cA;
  }
} {NULL}
do_test e_fkey-21.4 {
  execsql {
    UPDATE pA SET x = X'8765' WHERE rowid = 2;
    SELECT quote(x) FROM pA;
  }
} {X'8765'}
do_test e_fkey-21.5 {
  execsql { SELECT quote(c) FROM cB }
} {NULL}

#-------------------------------------------------------------------------
# /* EV: R-43054-54832 */
#
# Test SET DEFAULT actions.
#
drop_all_tables
do_test e_fkey-22.1 {
  execsql {
    CREATE TABLE pA(x PRIMARY KEY);
    CREATE TABLE cA(c DEFAULT X'0000' REFERENCES pA ON DELETE SET DEFAULT);
    CREATE TABLE cB(c DEFAULT X'9999' REFERENCES pA ON UPDATE SET DEFAULT);

    INSERT INTO pA(rowid, x) VALUES(1, X'0000');
    INSERT INTO pA(rowid, x) VALUES(2, X'9999');
    INSERT INTO pA(rowid, x) VALUES(3, X'ABCD');
    INSERT INTO pA(rowid, x) VALUES(4, X'1234');

    INSERT INTO cA VALUES(X'ABCD');
    INSERT INTO cB VALUES(X'1234');
  }
} {}
do_test e_fkey-22.2 {
  execsql {
    DELETE FROM pA WHERE rowid = 3;
    SELECT quote(x) FROM pA;
  }
} {X'0000' X'9999' X'1234'}
do_test e_fkey-22.3 {
  execsql { SELECT quote(c) FROM cA }
} {X'0000'}
do_test e_fkey-22.4 {
  execsql {
    UPDATE pA SET x = X'8765' WHERE rowid = 4;
    SELECT quote(x) FROM pA;
  }
} {X'0000' X'9999' X'8765'}
do_test e_fkey-22.5 {
  execsql { SELECT quote(c) FROM cB }
} {X'9999'}

#-------------------------------------------------------------------------
# /* EV: R-61376-57267 */
# /* EV: R-61809-62207 */
#
# Test ON DELETE CASCADE actions.
#
drop_all_tables
do_test e_fkey-23.1 {
  execsql {
    CREATE TABLE p1(a, b UNIQUE);
    CREATE TABLE c1(c REFERENCES p1(b) ON DELETE CASCADE, d);
    INSERT INTO p1 VALUES(NULL, NULL);
    INSERT INTO p1 VALUES(4, 4);
    INSERT INTO p1 VALUES(5, 5);
    INSERT INTO c1 VALUES(NULL, NULL);
    INSERT INTO c1 VALUES(4, 4);
    INSERT INTO c1 VALUES(5, 5);
    SELECT count(*) FROM c1;
  }
} {3}
do_test e_fkey-23.2 {
  execsql {
    DELETE FROM p1 WHERE a = 4;
    SELECT d, c FROM c1;
  }
} {{} {} 5 5}
do_test e_fkey-23.3 {
  execsql {
    DELETE FROM p1;
    SELECT d, c FROM c1;
  }
} {{} {}}
do_test e_fkey-23.4 {
  execsql { SELECT * FROM p1 }
} {}


#-------------------------------------------------------------------------
# /* EV: R-61376-57267 */
# /* EV: R-13877-64542 */
#
# Test ON UPDATE CASCADE actions.
#
drop_all_tables
do_test e_fkey-24.1 {
  execsql {
    CREATE TABLE p1(a, b UNIQUE);
    CREATE TABLE c1(c REFERENCES p1(b) ON UPDATE CASCADE, d);
    INSERT INTO p1 VALUES(NULL, NULL);
    INSERT INTO p1 VALUES(4, 4);
    INSERT INTO p1 VALUES(5, 5);
    INSERT INTO c1 VALUES(NULL, NULL);
    INSERT INTO c1 VALUES(4, 4);
    INSERT INTO c1 VALUES(5, 5);
    SELECT count(*) FROM c1;
  }
} {3}
do_test e_fkey-24.2 {
  execsql {
    UPDATE p1 SET b = 10 WHERE b = 5;
    SELECT d, c FROM c1;
  }
} {{} {} 4 4 5 10}
do_test e_fkey-24.3 {
  execsql {
    UPDATE p1 SET b = 11 WHERE b = 4;
    SELECT d, c FROM c1;
  }
} {{} {} 4 11 5 10}
do_test e_fkey-24.4 {
  execsql { 
    UPDATE p1 SET b = 6 WHERE b IS NULL;
    SELECT d, c FROM c1;
  }
} {{} {} 4 11 5 10}
do_test e_fkey-23.5 {
  execsql { SELECT * FROM p1 }
} {{} 6 4 11 5 10}

#-------------------------------------------------------------------------
# /* EV: R-51329-33438 */
#
# Test an example from the "ON DELETE and ON UPDATE Actions" section 
# of foreignkeys.html.
#
drop_all_tables
do_test e_fkey-15.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER,
      trackname   TEXT, 
      trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE
    );

    INSERT INTO artist VALUES(1, 'Dean Martin');
    INSERT INTO artist VALUES(2, 'Frank Sinatra');
    INSERT INTO track VALUES(11, 'That''s Amore', 1);
    INSERT INTO track VALUES(12, 'Christmas Blues', 1);
    INSERT INTO track VALUES(13, 'My Way', 2);
  }
} {}
do_test e_fkey-15.2 {
  execsql {
    UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin';
  }
} {}
do_test e_fkey-15.3 {
  execsql { SELECT * FROM artist }
} {2 {Frank Sinatra} 100 {Dean Martin}}
do_test e_fkey-15.4 {
  execsql { SELECT * FROM track }
} {11 {That's Amore} 100 12 {Christmas Blues} 100 13 {My Way} 2}


#-------------------------------------------------------------------------
# /* EV: R-53968-51642 */
#
# Verify that adding an FK action does not absolve the user of the 
# requirement not to violate the foreign key constraint.
#
drop_all_tables
do_test e_fkey-25.1 {
  execsql {
    CREATE TABLE parent(a COLLATE nocase, b, c, PRIMARY KEY(c, a));
    CREATE TABLE child(d DEFAULT 'a', e, f DEFAULT 'c',
      FOREIGN KEY(f, d) REFERENCES parent ON UPDATE SET DEFAULT
    );

    INSERT INTO parent VALUES('A', 'b', 'c');
    INSERT INTO parent VALUES('ONE', 'two', 'three');
    INSERT INTO child VALUES('one', 'two', 'three');
  }
} {}
do_test e_fkey-25.2 {
  execsql {
    BEGIN;
      UPDATE parent SET a = '' WHERE a = 'oNe';
      SELECT * FROM child;
  }
} {a two c}
do_test e_fkey-25.3 {
  execsql {
    ROLLBACK;
    DELETE FROM parent WHERE a = 'A';
    SELECT * FROM parent;
  }
} {ONE two three}
do_test e_fkey-25.4 {
  catchsql { UPDATE parent SET a = '' WHERE a = 'oNe' }
} {1 {foreign key constraint failed}}


#-------------------------------------------------------------------------
# /* EV: R-07065-59588 */
# /* EV: R-28220-46694 */
#
# Test an example from the "ON DELETE and ON UPDATE Actions" section 
# of foreignkeys.html. This example shows that adding an "ON DELETE DEFAULT"
# clause does not abrogate the need to satisfy the foreign key constraint
# (R-28220-46694).
#
drop_all_tables
do_test e_fkey-14.1 {
  execsql {
    CREATE TABLE artist(
      artistid    INTEGER PRIMARY KEY, 
      artistname  TEXT
    );
    CREATE TABLE track(
      trackid     INTEGER,
      trackname   TEXT, 
      trackartist INTEGER DEFAULT 0 REFERENCES artist(artistid) ON DELETE SET DEFAULT
    );
    INSERT INTO artist VALUES(3, 'Sammy Davis Jr.');
    INSERT INTO track VALUES(14, 'Mr. Bojangles', 3);
  }
} {}
do_test e_fkey-14.2 {
  catchsql { DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.' }
} {1 {foreign key constraint failed}}
do_test e_fkey-14.3 {
  execsql {
    INSERT INTO artist VALUES(0, 'Unknown Artist');
    DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';
  }
} {}
do_test e_fkey-14.4 {
  execsql { SELECT * FROM artist }
} {0 {Unknown Artist}}
do_test e_fkey-14.5 {
  execsql { SELECT * FROM track }
} {14 {Mr. Bojangles} 0}

#-------------------------------------------------------------------------
# /* EV: R-09564-22170 */
#
# Check that the order of steps in an UPDATE or DELETE on a parent 
# table is as follows:
#
#   1. Execute applicable BEFORE trigger programs,
#   2. Check local (non foreign key) constraints,
#   3. Update or delete the row in the parent table,
#   4. Perform any required foreign key actions,
#   5. Execute applicable AFTER trigger programs. 
#
drop_all_tables
do_test e_fkey-27.1 {
  proc maxparent {args} { db one {SELECT max(x) FROM parent} }
  db func maxparent maxparent

  execsql {
    CREATE TABLE parent(x PRIMARY KEY);

    CREATE TRIGGER bu BEFORE UPDATE ON parent BEGIN
      INSERT INTO parent VALUES(new.x-old.x);
    END;
    CREATE TABLE child(
      a DEFAULT (maxparent()) REFERENCES parent ON UPDATE SET DEFAULT
    );
    CREATE TRIGGER au AFTER UPDATE ON parent BEGIN
      INSERT INTO parent VALUES(new.x+old.x);
    END;

    INSERT INTO parent VALUES(1);
    INSERT INTO child VALUES(1);
  }
} {}
do_test e_fkey-27.2 {
  execsql {
    UPDATE parent SET x = 22;
    SELECT * FROM parent UNION ALL SELECT 'xxx' UNION ALL SELECT a FROM child;
  }
} {22 21 23 xxx 22}
do_test e_fkey-27.3 {
  execsql {
    DELETE FROM child;
    DELETE FROM parent;
    INSERT INTO parent VALUES(-1);
    INSERT INTO child VALUES(-1);
    UPDATE parent SET x = 22;
    SELECT * FROM parent UNION ALL SELECT 'xxx' UNION ALL SELECT a FROM child;
  }
} {22 23 21 xxx 23}


#-------------------------------------------------------------------------
# /* EV: R-27383-10246 */
#
# Verify that ON UPDATE actions only actually take place if the parent key
# is set to a new value that is distinct from the old value. The default
# collation sequence and affinity are used to determine if the new value
# is 'distinct' from the old or not.
#
drop_all_tables
do_test e_fkey-26.1 {
  execsql {
    CREATE TABLE zeus(a INTEGER COLLATE NOCASE, b, PRIMARY KEY(a, b));
    CREATE TABLE apollo(c, d, 
      FOREIGN KEY(c, d) REFERENCES zeus ON UPDATE CASCADE
    );
    INSERT INTO zeus VALUES('abc', 'xyz');
    INSERT INTO apollo VALUES('ABC', 'xyz');
  }
  execsql {
    UPDATE zeus SET a = 'aBc';
    SELECT * FROM apollo;
  }
} {ABC xyz}
do_test e_fkey-26.2 {
  execsql {
    UPDATE zeus SET a = 1, b = 1;
    SELECT * FROM apollo;
  }
} {1 1}
do_test e_fkey-26.3 {
  execsql {
    UPDATE zeus SET a = 1, b = 1;
    SELECT typeof(c), c, typeof(d), d FROM apollo;
  }
} {integer 1 integer 1}
do_test e_fkey-26.4 {
  execsql {
    UPDATE zeus SET a = '1';
    SELECT typeof(c), c, typeof(d), d FROM apollo;
  }
} {integer 1 integer 1}
do_test e_fkey-26.5 {
  execsql {
    UPDATE zeus SET b = '1';
    SELECT typeof(c), c, typeof(d), d FROM apollo;
  }
} {integer 1 text 1}
do_test e_fkey-26.6 {
  execsql {
    UPDATE zeus SET b = NULL;
    SELECT typeof(c), c, typeof(d), d FROM apollo;
  }
} {integer 1 null {}}

#-------------------------------------------------------------------------
# /* EV: R-58589-50781 */
#
# Test an example from the "ON DELETE and ON UPDATE Actions" section 
# of foreignkeys.html. This example demonstrates that ON UPDATE actions
# only take place if at least one parent key column is set to a value 
# that is distinct from its previous value.
#
drop_all_tables
do_test e_fkey-13.1 {
  execsql {
    CREATE TABLE parent(x PRIMARY KEY);
    CREATE TABLE child(y REFERENCES parent ON UPDATE SET NULL);
    INSERT INTO parent VALUES('key');
    INSERT INTO child VALUES('key');
  }
} {}
do_test e_fkey-13.2 {
  execsql {
    UPDATE parent SET x = 'key';
    SELECT IFNULL(y, 'null') FROM child;
  }
} {key}
do_test e_fkey-13.3 {
  execsql {
    UPDATE parent SET x = 'key2';
    SELECT IFNULL(y, 'null') FROM child;
  }
} {null}

###########################################################################
### SECTION 5: CREATE, ALTER and DROP TABLE commands
###########################################################################

#-------------------------------------------------------------------------
# /* EV: R-36018-21755 */
# /* EV: R-25384-39337 */
# 
# Test that parent keys are not checked when tables are created.
#
# Child keys are checked to ensure all component columns exist. If parent
# key columns are explicitly specified, SQLite checks to make sure there
# are the same number of columns in the child and parent keys. (TODO: This
# is tested but does not correspond to any testable statement.)
#
# /* EV: R-08908-23439 */
#
# Also test that the above statements are true regardless of whether or not
# foreign keys are enabled:  "A CREATE TABLE command operates the same whether
# or not foreign key constraints are enabled."
# 
foreach {tn zCreateTbl lRes} {
  1 "CREATE TABLE t1(a, b REFERENCES t1)"                            {0 {}}
  2 "CREATE TABLE t1(a, b REFERENCES t2)"                            {0 {}}
  3 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t1)"          {0 {}}
  4 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t2)"          {0 {}}
  5 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t2)"          {0 {}}
  6 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t2(n,d))"     {0 {}}
  7 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t1(a,b))"     {0 {}}

  A "CREATE TABLE t1(a, b, FOREIGN KEY(c,b) REFERENCES t2)"          
     {1 {unknown column "c" in foreign key definition}}
  B "CREATE TABLE t1(a, b, FOREIGN KEY(c,b) REFERENCES t2(d))"          
     {1 {number of columns in foreign key does not match the number of columns in the referenced table}}
} {
  do_test e_fkey-5.$tn.off {
    drop_all_tables
    execsql {PRAGMA foreign_keys = OFF}
    catchsql $zCreateTbl
  } $lRes
  do_test e_fkey-5.$tn.on {
    drop_all_tables
    execsql {PRAGMA foreign_keys = ON}
    catchsql $zCreateTbl
  } $lRes
}

#-------------------------------------------------------------------------
# /* EV: R-47952-62498 */
#
proc test_efkey_6 {tn zAlter isError} {
  drop_all_tables 

  do_test e_fkey-6.$tn.1 "
    execsql { CREATE TABLE tbl(a, b) }
    [list catchsql $zAlter]
  " [lindex {{0 {}} {1 {Cannot add a REFERENCES column with non-NULL default value}}} $isError]

}

test_efkey_6 1 "ALTER TABLE tbl ADD COLUMN c REFERENCES xx" 0
test_efkey_6 2 "ALTER TABLE tbl ADD COLUMN c DEFAULT NULL REFERENCES xx" 0
test_efkey_6 3 "ALTER TABLE tbl ADD COLUMN c DEFAULT 0 REFERENCES xx" 1

#-------------------------------------------------------------------------
# /* EV: R-47080-02069 */
#
# Test that ALTER TABLE adjusts REFERENCES clauses when the parent table
# is RENAMED.
#
# /* EV: R-63827-54774 */
#
# Test that these adjustments are visible in the sqlite_master table.
#
do_test e_fkey-7.1 {
  drop_all_tables
  execsql {
    CREATE TABLE 'p 1 "parent one"'(a REFERENCES 'p 1 "parent one"', b, PRIMARY KEY(b));

    CREATE TABLE c1(c, d REFERENCES 'p 1 "parent one"' ON UPDATE CASCADE);
    CREATE TABLE c2(e, f, FOREIGN KEY(f) REFERENCES 'p 1 "parent one"' ON UPDATE CASCADE);
    CREATE TABLE c3(e, 'f col 2', FOREIGN KEY('f col 2') REFERENCES 'p 1 "parent one"' ON UPDATE CASCADE);

    INSERT INTO 'p 1 "parent one"' VALUES(1, 1);
    INSERT INTO c1 VALUES(1, 1);
    INSERT INTO c2 VALUES(1, 1);
    INSERT INTO c3 VALUES(1, 1);

    -- CREATE TABLE q(a, b, PRIMARY KEY(b));
  }
} {}
do_test e_fkey-7.2 {
  execsql { ALTER TABLE 'p 1 "parent one"' RENAME TO p }
} {}
do_test e_fkey-7.3 {
  execsql {
    UPDATE p SET a = 'xxx', b = 'xxx';
    SELECT * FROM p;
    SELECT * FROM c1;
    SELECT * FROM c2;
    SELECT * FROM c3;
  }
} {xxx xxx 1 xxx 1 xxx 1 xxx}
do_test e_fkey-7.4 {
  execsql { SELECT sql FROM sqlite_master WHERE type = 'table'}
} [list                                                                     \
  {CREATE TABLE "p"(a REFERENCES "p", b, PRIMARY KEY(b))}                   \
  {CREATE TABLE c1(c, d REFERENCES "p" ON UPDATE CASCADE)}                  \
  {CREATE TABLE c2(e, f, FOREIGN KEY(f) REFERENCES "p" ON UPDATE CASCADE)}  \
  {CREATE TABLE c3(e, 'f col 2', FOREIGN KEY('f col 2') REFERENCES "p" ON UPDATE CASCADE)} \
]

#-------------------------------------------------------------------------
# /* EV: R-14208-23986 */
# /* EV: R-11078-03945 */
#
# Check that a DROP TABLE does an implicit DELETE FROM. Which does not
# cause any triggers to fire, but does fire foreign key actions.
#
do_test e_fkey-8.1 {
  drop_all_tables
  execsql {
    CREATE TABLE p(a, b, PRIMARY KEY(a, b));

    CREATE TABLE c1(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE SET NULL);
    CREATE TABLE c2(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE SET DEFAULT);
    CREATE TABLE c3(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE CASCADE);
    CREATE TABLE c4(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE RESTRICT);
    CREATE TABLE c5(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE NO ACTION);

    CREATE TABLE c6(c, d, 
      FOREIGN KEY(c, d) REFERENCES p ON DELETE RESTRICT 
      DEFERRABLE INITIALLY DEFERRED
    );
    CREATE TABLE c7(c, d, 
      FOREIGN KEY(c, d) REFERENCES p ON DELETE NO ACTION
      DEFERRABLE INITIALLY DEFERRED
    );

    CREATE TABLE log(msg);
    CREATE TRIGGER tt AFTER DELETE ON p BEGIN
      INSERT INTO log VALUES('delete ' || old.rowid);
    END;
  }
} {}

do_test e_fkey-8.2 {
  execsql {
    INSERT INTO p VALUES('a', 'b');
    INSERT INTO c1 VALUES('a', 'b');
    INSERT INTO c2 VALUES('a', 'b');
    INSERT INTO c3 VALUES('a', 'b');
    BEGIN;
      DROP TABLE p;
      SELECT * FROM c1;
  }
} {{} {}}
do_test e_fkey-8.3 {
  execsql { SELECT * FROM c2 }
} {{} {}}
do_test e_fkey-8.4 {
  execsql { SELECT * FROM c3 }
} {}
do_test e_fkey-8.5 {
  execsql { SELECT * FROM log }
} {}
do_test e_fkey-8.6 {
  execsql ROLLBACK
} {}
do_test e_fkey-8.7 {
  execsql {
    BEGIN;
      DELETE FROM p;
      SELECT * FROM log;
    ROLLBACK;
  }
} {{delete 1}}

#-------------------------------------------------------------------------
# /* EV: R-32768-47925 */
#
# If an IMMEDIATE foreign key fails as a result of a DROP TABLE, the
# DROP TABLE command fails.
#
do_test e_fkey-9.1 {
  execsql { 
    DELETE FROM c1;
    DELETE FROM c2;
    DELETE FROM c3;
  }
  execsql { INSERT INTO c5 VALUES('a', 'b') }
  catchsql { DROP TABLE p }
} {1 {foreign key constraint failed}}
do_test e_fkey-9.2 {
  execsql { SELECT * FROM p }
} {a b}
do_test e_fkey-9.3 {
  catchsql {
    BEGIN;
      DROP TABLE p;
  }
} {1 {foreign key constraint failed}}
do_test e_fkey-9.4 {
  execsql {
    SELECT * FROM p;
    SELECT * FROM c5;
    ROLLBACK;
  }
} {a b a b}

#-------------------------------------------------------------------------
# /* EV: R-05903-08460 */
#
# If a DEFERRED foreign key fails as a result of a DROP TABLE, attempting
# to commit the transaction fails unless the violation is fixed.
#
do_test e_fkey-10.1 {
  execsql { 
    DELETE FROM c1 ; DELETE FROM c2 ; DELETE FROM c3 ;
    DELETE FROM c4 ; DELETE FROM c5 ; DELETE FROM c6 ;
    DELETE FROM c7 
  }
} {}
do_test e_fkey-10.2 {
  execsql { INSERT INTO c7 VALUES('a', 'b') }
  execsql {
    BEGIN;
      DROP TABLE p;
  }
} {}
do_test e_fkey-10.3 {
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-10.4 {
  execsql { CREATE TABLE p(a, b, PRIMARY KEY(a, b)) }
  catchsql COMMIT
} {1 {foreign key constraint failed}}
do_test e_fkey-10.5 {
  execsql { INSERT INTO p VALUES('a', 'b') }
  execsql COMMIT
} {}

#-------------------------------------------------------------------------
# /* EV: R-57242-37005 */
#
# Any "foreign key mismatch" errors encountered while running an implicit
# "DELETE FROM tbl" are ignored.
#
drop_all_tables
do_test e_fkey-11.1 {
  execsql {
    PRAGMA foreign_keys = OFF;

    CREATE TABLE p(a PRIMARY KEY, b REFERENCES nosuchtable);
    CREATE TABLE c1(c, d, FOREIGN KEY(c, d) REFERENCES a);
    CREATE TABLE c2(c REFERENCES p(b), d);
    CREATE TABLE c3(c REFERENCES p ON DELETE SET NULL, d);

    INSERT INTO p VALUES(1, 2);
    INSERT INTO c1 VALUES(1, 2);
    INSERT INTO c2 VALUES(1, 2);
    INSERT INTO c3 VALUES(1, 2);
  }
} {}
do_test e_fkey-11.2 {
  execsql { PRAGMA foreign_keys = ON }
  catchsql { DELETE FROM p }
} {1 {no such table: main.nosuchtable}}
do_test e_fkey-11.3 {
  execsql {
    BEGIN;
      DROP TABLE p;
      SELECT * FROM c3;
    ROLLBACK;
  }
} {{} 2}
do_test e_fkey-11.4 {
  execsql { CREATE TABLE nosuchtable(x PRIMARY KEY) }
  catchsql { DELETE FROM p }
} {1 {foreign key mismatch}}
do_test e_fkey-11.5 {
  execsql { DROP TABLE c1 }
  catchsql { DELETE FROM p }
} {1 {foreign key mismatch}}
do_test e_fkey-11.6 {
  execsql { DROP TABLE c2 }
  execsql { DELETE FROM p }
} {}

#-------------------------------------------------------------------------
# /* EV: R-54142-41346 */
#
# Test that the special behaviours of ALTER and DROP TABLE are only
# activated when foreign keys are enabled. Special behaviours are:
#
#   1. ADD COLUMN not allowing a REFERENCES clause with a non-NULL 
#      default value.
#   2. Modifying foreign key definitions when a parent table is RENAMEd.
#   3. Running an implicit DELETE FROM command as part of DROP TABLE.
#
do_test e_fkey-12.1.1 {
  drop_all_tables
  execsql { CREATE TABLE t1(a, b) }
  catchsql { ALTER TABLE t1 ADD COLUMN c DEFAULT 'xxx' REFERENCES t2 }
} {1 {Cannot add a REFERENCES column with non-NULL default value}}
do_test e_fkey-12.1.2 {
  execsql { PRAGMA foreign_keys = OFF }
  execsql { ALTER TABLE t1 ADD COLUMN c DEFAULT 'xxx' REFERENCES t2 }
  execsql { SELECT sql FROM sqlite_master WHERE name = 't1' }
} {{CREATE TABLE t1(a, b, c DEFAULT 'xxx' REFERENCES t2)}}
do_test e_fkey-12.1.3 {
  execsql { PRAGMA foreign_keys = ON }
} {}

do_test e_fkey-12.2.1 {
  drop_all_tables
  execsql {
    CREATE TABLE p(a UNIQUE);
    CREATE TABLE c(b REFERENCES p(a));
    BEGIN;
      ALTER TABLE p RENAME TO parent;
      SELECT sql FROM sqlite_master WHERE name = 'c';
    ROLLBACK;
  }
} {{CREATE TABLE c(b REFERENCES "parent"(a))}}
do_test e_fkey-12.2.2 {
  execsql {
    PRAGMA foreign_keys = OFF;
    ALTER TABLE p RENAME TO parent;
    SELECT sql FROM sqlite_master WHERE name = 'c';
  }
} {{CREATE TABLE c(b REFERENCES p(a))}}
do_test e_fkey-12.2.3 {
  execsql { PRAGMA foreign_keys = ON }
} {}

do_test e_fkey-12.3.1 {
  drop_all_tables
  execsql {
    CREATE TABLE p(a UNIQUE);
    CREATE TABLE c(b REFERENCES p(a) ON DELETE SET NULL);
    INSERT INTO p VALUES('x');
    INSERT INTO c VALUES('x');
    BEGIN;
      DROP TABLE p;
      SELECT * FROM c;
    ROLLBACK;
  }
} {{}}
do_test e_fkey-12.3.2 {
  execsql {
    PRAGMA foreign_keys = OFF;
    DROP TABLE p;
    SELECT * FROM c;
  }
} {x}
do_test e_fkey-12.3.3 {
  execsql { PRAGMA foreign_keys = ON }
} {}

###########################################################################
### SECTION 6: Limits and Unsupported Features
###########################################################################

#-------------------------------------------------------------------------
# /* EV: R-24728-13230 */
# /* EV: R-24450-46174 */
#
# Test that MATCH clauses are parsed, but SQLite treats every foreign key
# constraint as if it were "MATCH SIMPLE".
#
foreach zMatch [list SIMPLE PARTIAL FULL Simple parTIAL FuLL ] {
  drop_all_tables
  do_test e_fkey-1.$zMatch.1 {
    execsql "
      CREATE TABLE p(a, b, c, PRIMARY KEY(b, c));
      CREATE TABLE c(d, e, f, FOREIGN KEY(e, f) REFERENCES p MATCH $zMatch);
    "
  } {}
  do_test e_fkey-1.$zMatch.2 {
    execsql { INSERT INTO p VALUES(1, 2, 3)         }

    # MATCH SIMPLE behaviour: Allow any child key that contains one or more
    # NULL value to be inserted. Non-NULL values do not have to map to any
    # parent key values, so long as at least one field of the child key is
    # NULL.
    execsql { INSERT INTO c VALUES('w', 2, 3)       }
    execsql { INSERT INTO c VALUES('x', 'x', NULL)  }
    execsql { INSERT INTO c VALUES('y', NULL, 'x')  }
    execsql { INSERT INTO c VALUES('z', NULL, NULL) }

    # Check that the FK is enforced properly if there are no NULL values 
    # in the child key columns.
    catchsql { INSERT INTO c VALUES('a', 2, 4) }
  } {1 {foreign key constraint failed}}
}

#-------------------------------------------------------------------------
# /* EV: R-21599-16038 */
#
# Test that SQLite does not support the SET CONSTRAINT statement. And
# that it is possible to create both immediate and deferred constraints.
#
drop_all_tables
do_test e_fkey-2.1 {
  catchsql { SET CONSTRAINTS ALL IMMEDIATE }
} {1 {near "SET": syntax error}}
do_test e_fkey-2.2 {
  catchsql { SET CONSTRAINTS ALL DEFERRED }
} {1 {near "SET": syntax error}}

do_test e_fkey-2.3 {
  execsql {
    CREATE TABLE p(a, b, PRIMARY KEY(a, b));
    CREATE TABLE cd(c, d, 
      FOREIGN KEY(c, d) REFERENCES p DEFERRABLE INITIALLY DEFERRED);
    CREATE TABLE ci(c, d, 
      FOREIGN KEY(c, d) REFERENCES p DEFERRABLE INITIALLY IMMEDIATE);
    BEGIN;
  }
} {}
do_test e_fkey-2.4 {
  catchsql { INSERT INTO ci VALUES('x', 'y') }
} {1 {foreign key constraint failed}}
do_test e_fkey-2.5 {
  catchsql { INSERT INTO cd VALUES('x', 'y') }
} {0 {}}
do_test e_fkey-2.6 {
  catchsql { COMMIT }
} {1 {foreign key constraint failed}}
do_test e_fkey-2.7 {
  execsql { 
    DELETE FROM cd;
    COMMIT;
  }
} {}

#-------------------------------------------------------------------------
# /* EV: R-42264-30503 */
#
# Test that the maximum recursion depth of foreign key action programs is
# governed by the SQLITE_MAX_TRIGGER_DEPTH and SQLITE_LIMIT_TRIGGER_DEPTH
# settings.
#
proc test_on_delete_recursion {limit} {
  drop_all_tables
  execsql { 
    BEGIN;
    CREATE TABLE t0(a PRIMARY KEY, b);
    INSERT INTO t0 VALUES('x0', NULL);
  }
  for {set i 1} {$i <= $limit} {incr i} {
    execsql "
      CREATE TABLE t$i (
        a PRIMARY KEY, b REFERENCES t[expr $i-1] ON DELETE CASCADE
      );
      INSERT INTO t$i VALUES('x$i', 'x[expr $i-1]');
    "
  }
  execsql COMMIT
  catchsql "
    DELETE FROM t0;
    SELECT count(*) FROM t$limit;
  "
}
proc test_on_update_recursion {limit} {
  drop_all_tables
  execsql { 
    BEGIN;
    CREATE TABLE t0(a PRIMARY KEY);
    INSERT INTO t0 VALUES('xxx');
  }
  for {set i 1} {$i <= $limit} {incr i} {
    set j [expr $i-1]

    execsql "
      CREATE TABLE t$i (a PRIMARY KEY REFERENCES t$j ON UPDATE CASCADE);
      INSERT INTO t$i VALUES('xxx');
    "
  }
  execsql COMMIT
  catchsql "
    UPDATE t0 SET a = 'yyy';
    SELECT NOT (a='yyy') FROM t$limit;
  "
}

do_test e_fkey-3.1.1 {
  test_on_delete_recursion $SQLITE_MAX_TRIGGER_DEPTH
} {0 0}
do_test e_fkey-3.1.2 {
  test_on_delete_recursion [expr $SQLITE_MAX_TRIGGER_DEPTH+1]
} {1 {too many levels of trigger recursion}}
do_test e_fkey-3.1.3 {
  sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 5
  test_on_delete_recursion 5
} {0 0}
do_test e_fkey-3.1.4 {
  test_on_delete_recursion 6
} {1 {too many levels of trigger recursion}}
do_test e_fkey-3.1.5 {
  sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1000000
} {5}
do_test e_fkey-3.2.1 {
  test_on_update_recursion $SQLITE_MAX_TRIGGER_DEPTH
} {0 0}
do_test e_fkey-3.2.2 {
  test_on_update_recursion [expr $SQLITE_MAX_TRIGGER_DEPTH+1]
} {1 {too many levels of trigger recursion}}
do_test e_fkey-3.2.3 {
  sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 5
  test_on_update_recursion 5
} {0 0}
do_test e_fkey-3.2.4 {
  test_on_update_recursion 6
} {1 {too many levels of trigger recursion}}
do_test e_fkey-3.2.5 {
  sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1000000
} {5}

#-------------------------------------------------------------------------
# /* EV: R-51769-32730 */
#
# The setting of the recursive_triggers pragma does not affect foreign
# key actions.
#
foreach recursive_triggers_setting [list 0 1 ON OFF] {
  drop_all_tables
  execsql "PRAGMA recursive_triggers = $recursive_triggers_setting"

  do_test e_fkey-4.$recursive_triggers_setting.1 {
    execsql {
      CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1 ON DELETE CASCADE);
      INSERT INTO t1 VALUES(1, NULL);
      INSERT INTO t1 VALUES(2, 1);
      INSERT INTO t1 VALUES(3, 2);
      INSERT INTO t1 VALUES(4, 3);
      INSERT INTO t1 VALUES(5, 4);
      SELECT count(*) FROM t1;
    }
  } {5}
  do_test e_fkey-4.$recursive_triggers_setting.2 {
    execsql { SELECT count(*) FROM t1 WHERE a = 1 }
  } {1}
  do_test e_fkey-4.$recursive_triggers_setting.3 {
    execsql { 
      DELETE FROM t1 WHERE a = 1;
      SELECT count(*) FROM t1;
    }
  } {0}
}

finish_test

Added test/enc.test.

























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The focus of
# this file is testing the SQLite routines used for converting between the
# various suported unicode encodings (UTF-8, UTF-16, UTF-16le and
# UTF-16be).
#
# $Id: enc.test,v 1.7 2007/05/23 16:23:09 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Skip this test if the build does not support multiple encodings.
#
ifcapable {!utf16} {
  finish_test
  return
}

proc do_bincmp_test {testname got expect} {
  binary scan $expect \c* expectvals
  binary scan $got \c* gotvals
  do_test $testname [list set dummy $gotvals] $expectvals
}

# $utf16 is a UTF-16 encoded string. Swap each pair of bytes around
# to change the byte-order of the string.
proc swap_byte_order {utf16} {
  binary scan $utf16 \c* ints

  foreach {a b} $ints {
    lappend ints2 $b
    lappend ints2 $a
  }

  return [binary format \c* $ints2]
}

#
# Test that the SQLite routines for converting between UTF encodings
# produce the same results as their TCL counterparts.
#
# $testname is the prefix to be used for the test names.
# $str is a string to use for testing (encoded in UTF-8, as normal for TCL).
#
# The test procedure is:
# 1. Convert the string from UTF-8 to UTF-16le and check that the TCL and
#    SQLite routines produce the same results.
#
# 2. Convert the string from UTF-8 to UTF-16be and check that the TCL and
#    SQLite routines produce the same results.
#
# 3. Use the SQLite routines to convert the native machine order UTF-16
#    representation back to the original UTF-8. Check that the result
#    matches the original representation.
#
# 4. Add a byte-order mark to each of the UTF-16 representations and
#    check that the SQLite routines can convert them back to UTF-8.  For
#    byte-order mark info, refer to section 3.10 of the unicode standard.
#
# 5. Take the byte-order marked UTF-16 strings from step 4 and ensure
#    that SQLite can convert them both to native byte order UTF-16 
#    strings, sans BOM.
#
# Coverage:
#
# sqlite_utf8to16be (step 2)
# sqlite_utf8to16le (step 1)
# sqlite_utf16to8 (steps 3, 4)
# sqlite_utf16to16le (step 5)
# sqlite_utf16to16be (step 5)
#
proc test_conversion {testname str} {
 
  # Step 1.
  set utf16le_sqlite3 [test_translate $str UTF8 UTF16LE]
  set utf16le_tcl [encoding convertto unicode $str]
  append utf16le_tcl "\x00\x00"
  if { $::tcl_platform(byteOrder)!="littleEndian" } {
    set utf16le_tcl [swap_byte_order $utf16le_tcl]
  }
  do_bincmp_test $testname.1 $utf16le_sqlite3 $utf16le_tcl
  set utf16le $utf16le_tcl

  # Step 2.
  set utf16be_sqlite3 [test_translate $str UTF8 UTF16BE]
  set utf16be_tcl [encoding convertto unicode $str]
  append utf16be_tcl "\x00\x00"
  if { $::tcl_platform(byteOrder)=="littleEndian" } {
    set utf16be_tcl [swap_byte_order $utf16be_tcl]
  }
  do_bincmp_test $testname.2 $utf16be_sqlite3 $utf16be_tcl
  set utf16be $utf16be_tcl
 
  # Step 3.
  if { $::tcl_platform(byteOrder)=="littleEndian" } {
    set utf16 $utf16le
  } else {
    set utf16 $utf16be
  }
  set utf8_sqlite3 [test_translate $utf16 UTF16 UTF8]
  do_bincmp_test $testname.3 $utf8_sqlite3 [binarize $str]

  # Step 4 (little endian).
  append utf16le_bom "\xFF\xFE" $utf16le
  set utf8_sqlite3 [test_translate $utf16le_bom UTF16 UTF8 1]
  do_bincmp_test $testname.4.le $utf8_sqlite3 [binarize $str]

  # Step 4 (big endian).
  append utf16be_bom "\xFE\xFF" $utf16be
  set utf8_sqlite3 [test_translate $utf16be_bom UTF16 UTF8]
  do_bincmp_test $testname.4.be $utf8_sqlite3 [binarize $str]

  # Step 5 (little endian to little endian).
  set utf16_sqlite3 [test_translate $utf16le_bom UTF16LE UTF16LE]
  do_bincmp_test $testname.5.le.le $utf16_sqlite3 $utf16le

  # Step 5 (big endian to big endian).
  set utf16_sqlite3 [test_translate $utf16be_bom UTF16 UTF16BE]
  do_bincmp_test $testname.5.be.be $utf16_sqlite3 $utf16be

  # Step 5 (big endian to little endian).
  set utf16_sqlite3 [test_translate $utf16be_bom UTF16 UTF16LE]
  do_bincmp_test $testname.5.be.le $utf16_sqlite3 $utf16le

  # Step 5 (little endian to big endian).
  set utf16_sqlite3 [test_translate $utf16le_bom UTF16 UTF16BE]
  do_bincmp_test $testname.5.le.be $utf16_sqlite3 $utf16be
}

translate_selftest

test_conversion enc-1 "hello world"
test_conversion enc-2 "sqlite"
test_conversion enc-3 ""
test_conversion enc-X "\u0100"
test_conversion enc-4 "\u1234"
test_conversion enc-5 "\u4321abc"
test_conversion enc-6 "\u4321\u1234"
test_conversion enc-7 [string repeat "abcde\u00EF\u00EE\uFFFCabc" 100]
test_conversion enc-8 [string repeat "\u007E\u007F\u0080\u0081" 100]
test_conversion enc-9 [string repeat "\u07FE\u07FF\u0800\u0801\uFFF0" 100]
test_conversion enc-10 [string repeat "\uE000" 100]

proc test_collate {enc zLeft zRight} {
  return [string compare $zLeft $zRight]
}
add_test_collate $::DB 0 0 1
do_test enc-11.1 {
  execsql {
    CREATE TABLE ab(a COLLATE test_collate, b);
    INSERT INTO ab VALUES(CAST (X'C388' AS TEXT), X'888800');
    INSERT INTO ab VALUES(CAST (X'C0808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808388' AS TEXT), X'888800');
    CREATE INDEX ab_i ON ab(a, b);
  }
} {}
do_test enc-11.2 {
  set cp200 "\u00C8"
  execsql {
    SELECT count(*) FROM ab WHERE a = $::cp200;
  }
} {2}

finish_test

Added test/enc2.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The focus of
# this file is testing the SQLite routines used for converting between the
# various suported unicode encodings (UTF-8, UTF-16, UTF-16le and
# UTF-16be).
#
# $Id: enc2.test,v 1.29 2007/10/09 08:29:32 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If UTF16 support is disabled, ignore the tests in this file
#
ifcapable {!utf16} {
  finish_test
  return
}

# The rough organisation of tests in this file is:
#
# enc2.1.*: Simple tests with a UTF-8 db.
# enc2.2.*: Simple tests with a UTF-16LE db.
# enc2.3.*: Simple tests with a UTF-16BE db.
# enc2.4.*: Test that attached databases must have the same text encoding
#           as the main database.
# enc2.5.*: Test the behaviour of the library when a collation sequence is
#           not available for the most desirable text encoding.
# enc2.6.*: Similar test for user functions.
# enc2.7.*: Test that the VerifyCookie opcode protects against assuming the
#           wrong text encoding for the database.
# enc2.8.*: Test sqlite3_complete16()
#

db close

# Return the UTF-8 representation of the supplied UTF-16 string $str. 
proc utf8 {str} {
  # If $str ends in two 0x00 0x00 bytes, knock these off before
  # converting to UTF-8 using TCL.
  binary scan $str \c* vals
  if {[lindex $vals end]==0 && [lindex $vals end-1]==0} {
    set str [binary format \c* [lrange $vals 0 end-2]]
  }

  set r [encoding convertfrom unicode $str]
  return $r
}

#
# This proc contains all the tests in this file. It is run
# three times. Each time the file 'test.db' contains a database
# with the following contents:
set dbcontents {
  CREATE TABLE t1(a PRIMARY KEY, b, c);
  INSERT INTO t1 VALUES('one', 'I', 1);
}
# This proc tests that we can open and manipulate the test.db 
# database, and that it is possible to retreive values in
# various text encodings.
#
proc run_test_script {t enc} {

# Open the database and pull out a (the) row.
do_test $t.1 {
  sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
  execsql {SELECT * FROM t1}
} {one I 1}

# Insert some data
do_test $t.2 {
  execsql {INSERT INTO t1 VALUES('two', 'II', 2);}
  execsql {SELECT * FROM t1}
} {one I 1 two II 2}

# Insert some data 
do_test $t.3 {
  execsql {
    INSERT INTO t1 VALUES('three','III',3);
    INSERT INTO t1 VALUES('four','IV',4);
    INSERT INTO t1 VALUES('five','V',5);
  }
  execsql {SELECT * FROM t1}
} {one I 1 two II 2 three III 3 four IV 4 five V 5}

# Use the index
do_test $t.4 {
  execsql {
    SELECT * FROM t1 WHERE a = 'one';
  }
} {one I 1}
do_test $t.5 {
  execsql {
    SELECT * FROM t1 WHERE a = 'four';
  }
} {four IV 4}
ifcapable subquery {
  do_test $t.6 {
    execsql {
      SELECT * FROM t1 WHERE a IN ('one', 'two');
    }
  } {one I 1 two II 2}
}

# Now check that we can retrieve data in both UTF-16 and UTF-8
do_test $t.7 {
  set STMT [sqlite3_prepare $DB "SELECT a FROM t1 WHERE c>3;" -1 TAIL]
  sqlite3_step $STMT
  sqlite3_column_text $STMT 0
} {four}

do_test $t.8 {
  sqlite3_step $STMT
  utf8 [sqlite3_column_text16 $STMT 0]
} {five}

do_test $t.9 {
  sqlite3_finalize $STMT
} SQLITE_OK

ifcapable vacuum {
  execsql VACUUM
}

do_test $t.10 {
  db eval {PRAGMA encoding}
} $enc

}

# The three unicode encodings understood by SQLite.
set encodings [list UTF-8 UTF-16le UTF-16be]

set sqlite_os_trace 0
set i 1
foreach enc $encodings {
  file delete -force test.db
  sqlite3 db test.db
  db eval "PRAGMA encoding = \"$enc\""
  execsql $dbcontents
  do_test enc2-$i.0.1 {
    db eval {PRAGMA encoding}
  } $enc
  do_test enc2-$i.0.2 {
    db eval {PRAGMA encoding=UTF8}
    db eval {PRAGMA encoding}
  } $enc
  do_test enc2-$i.0.3 {
    db eval {PRAGMA encoding=UTF16le}
    db eval {PRAGMA encoding}
  } $enc
  do_test enc2-$i.0.4 {
    db eval {PRAGMA encoding=UTF16be}
    db eval {PRAGMA encoding}
  } $enc

  db close
  run_test_script enc2-$i $enc
  db close
  incr i
}

# Test that it is an error to try to attach a database with a different
# encoding to the main database.
ifcapable attach {
  do_test enc2-4.1 {
    file delete -force test.db
    sqlite3 db test.db
    db eval "PRAGMA encoding = 'UTF-8'"
    db eval "CREATE TABLE abc(a, b, c);"
  } {}
  do_test enc2-4.2 {
    file delete -force test2.db
    sqlite3 db2 test2.db
    db2 eval "PRAGMA encoding = 'UTF-16'"
    db2 eval "CREATE TABLE abc(a, b, c);"
  } {}
  do_test enc2-4.3 {
    catchsql {
      ATTACH 'test2.db' as aux;
    }
  } {1 {attached databases must use the same text encoding as main database}}
  db2 close
  db close
}

# The following tests - enc2-5.* - test that SQLite selects the correct
# collation sequence when more than one is available.

set ::values [list one two three four five]
set ::test_collate_enc INVALID
proc test_collate {enc lhs rhs} {
  set ::test_collate_enc $enc
  set l [lsearch -exact $::values $lhs]
  set r [lsearch -exact $::values $rhs]
  set res [expr $l - $r]
  # puts "enc=$enc lhs=$lhs/$l rhs=$rhs/$r res=$res"
  return $res
}

file delete -force test.db
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-5.0 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES('one');
    INSERT INTO t5 VALUES('two');
    INSERT INTO t5 VALUES('five');
    INSERT INTO t5 VALUES('three');
    INSERT INTO t5 VALUES('four');
  }
} {}
do_test enc2-5.1 {
  add_test_collate $DB 1 1 1
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate;}]
  lappend res $::test_collate_enc
} {one two three four five UTF-8}
do_test enc2-5.2 {
  add_test_collate $DB 0 1 0
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-16LE}
do_test enc2-5.3 {
  add_test_collate $DB 0 0 1
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-16BE}

db close
file delete -force test.db
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
execsql {pragma encoding = 'UTF-16LE'}
do_test enc2-5.4 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES('one');
    INSERT INTO t5 VALUES('two');
    INSERT INTO t5 VALUES('five');
    INSERT INTO t5 VALUES('three');
    INSERT INTO t5 VALUES('four');
  }
} {}
do_test enc2-5.5 {
  add_test_collate $DB 1 1 1
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-16LE}
do_test enc2-5.6 {
  add_test_collate $DB 1 0 1
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-16BE}
do_test enc2-5.7 {
  add_test_collate $DB 1 0 0
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-8}

db close
file delete -force test.db
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
execsql {pragma encoding = 'UTF-16BE'}
do_test enc2-5.8 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES('one');
    INSERT INTO t5 VALUES('two');
    INSERT INTO t5 VALUES('five');
    INSERT INTO t5 VALUES('three');
    INSERT INTO t5 VALUES('four');
  }
} {}
do_test enc2-5.9 {
  add_test_collate $DB 1 1 1
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-16BE}
do_test enc2-5.10 {
  add_test_collate $DB 1 1 0
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-16LE}
do_test enc2-5.11 {
  add_test_collate $DB 1 0 0
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}]
  lappend res $::test_collate_enc
} {one two three four five UTF-8}

# Also test that a UTF-16 collation factory works.
do_test enc2-5-12 {
  add_test_collate $DB 0 0 0
  catchsql {
    SELECT * FROM t5 ORDER BY 1 COLLATE test_collate
  }
} {1 {no such collation sequence: test_collate}}
do_test enc2-5.13 {
  add_test_collate_needed $DB 
  set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate; }]
  lappend res $::test_collate_enc
} {one two three four five UTF-16BE}
do_test enc2-5.14 {
  set ::sqlite_last_needed_collation
} test_collate

db close
file delete -force test.db

do_test enc2-5.15 {
  sqlite3 db test.db; set ::DB [sqlite3_connection_pointer db]
  add_test_collate_needed $::DB
  set ::sqlite_last_needed_collation
} {}
do_test enc2-5.16 {
  execsql {CREATE TABLE t1(a varchar collate test_collate);}
} {}
do_test enc2-5.17 {
  set ::sqlite_last_needed_collation
} {test_collate}

# The following tests - enc2-6.* - test that SQLite selects the correct
# user function when more than one is available.

proc test_function {enc arg} {
  return "$enc $arg"
}

db close
file delete -force test.db
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
execsql {pragma encoding = 'UTF-8'}
do_test enc2-6.0 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES('one');
  }
} {}
do_test enc2-6.1 {
  add_test_function $DB 1 1 1
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-8 sqlite}}
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-6.2 {
  add_test_function $DB 0 1 0
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16LE sqlite}}
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-6.3 {
  add_test_function $DB 0 0 1
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16BE sqlite}}

db close
file delete -force test.db
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
execsql {pragma encoding = 'UTF-16LE'}
do_test enc2-6.3 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES('sqlite');
  }
} {}
do_test enc2-6.4 {
  add_test_function $DB 1 1 1
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16LE sqlite}}
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-6.5 {
  add_test_function $DB 0 1 0
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16LE sqlite}}
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-6.6 {
  add_test_function $DB 0 0 1
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16BE sqlite}}

db close
file delete -force test.db
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
execsql {pragma encoding = 'UTF-16BE'}
do_test enc2-6.7 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES('sqlite');
  }
} {}
do_test enc2-6.8 {
  add_test_function $DB 1 1 1
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16BE sqlite}}
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-6.9 {
  add_test_function $DB 0 1 0
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16LE sqlite}}
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test enc2-6.10 {
  add_test_function $DB 0 0 1
  execsql {
    SELECT test_function('sqlite')
  }
} {{UTF-16BE sqlite}}


db close
file delete -force test.db

# The following tests - enc2-7.* - function as follows:
#
# 1: Open an empty database file assuming UTF-16 encoding.
# 2: Open the same database with a different handle assuming UTF-8. Create
#    a table using this handle.
# 3: Read the sqlite_master table from the first handle. 
# 4: Ensure the first handle recognises the database encoding is UTF-8.
#
do_test enc2-7.1 {
  sqlite3 db test.db
  execsql {
    PRAGMA encoding = 'UTF-16';
    SELECT * FROM sqlite_master;
  }
} {}
do_test enc2-7.2 {
  set enc [execsql {
    PRAGMA encoding;
  }]
  string range $enc 0 end-2 ;# Chop off the "le" or "be"
} {UTF-16}
do_test enc2-7.3 {
  sqlite3 db2 test.db
  execsql {
    PRAGMA encoding = 'UTF-8';
    CREATE TABLE abc(a, b, c);
  } db2
} {}
do_test enc2-7.4 {
  execsql {
    SELECT * FROM sqlite_master;
  }
} "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}"
do_test enc2-7.5 {
  execsql {
    PRAGMA encoding;
  }
} {UTF-8}

db close
db2 close

proc utf16 {utf8} {
  set utf16 [encoding convertto unicode $utf8]
  append utf16 "\x00\x00"
  return $utf16
}
ifcapable {complete} {
  do_test enc2-8.1 {
    sqlite3_complete16 [utf16 "SELECT * FROM t1;"]
  } {1}
  do_test enc2-8.2 {
    sqlite3_complete16 [utf16 "SELECT * FROM"]
  } {0}
}

# Test that the encoding of an empty database may still be set after the
# (empty) schema has been initialized.
file delete -force test.db
do_test enc2-9.1 {
  sqlite3 db test.db
  execsql {
    PRAGMA encoding = 'UTF-8';
    PRAGMA encoding;
  }
} {UTF-8}
do_test enc2-9.2 {
  sqlite3 db test.db
  execsql {
    PRAGMA encoding = 'UTF-16le';
    PRAGMA encoding;
  }
} {UTF-16le}
do_test enc2-9.3 {
  sqlite3 db test.db
  execsql {
    SELECT * FROM sqlite_master;
    PRAGMA encoding = 'UTF-8';
    PRAGMA encoding;
  }
} {UTF-8}
do_test enc2-9.4 {
  sqlite3 db test.db
  execsql {
    PRAGMA encoding = 'UTF-16le';
    CREATE TABLE abc(a, b, c);
    PRAGMA encoding;
  }
} {UTF-16le}
do_test enc2-9.5 {
  sqlite3 db test.db
  execsql {
    PRAGMA encoding = 'UTF-8';
    PRAGMA encoding;
  }
} {UTF-16le}

# Ticket #1987.
# Disallow encoding changes once the encoding has been set.
#
do_test enc2-10.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  db eval {
    PRAGMA encoding=UTF16;
    CREATE TABLE t1(a);
    PRAGMA encoding=UTF8;
    CREATE TABLE t2(b);
  }
  db close
  sqlite3 db test.db
  db eval {
    SELECT name FROM sqlite_master
  }
} {t1 t2}

finish_test

Added test/enc3.test.























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# The focus of this file is testing of the proper handling of conversions
# to the native text representation.
#
# $Id: enc3.test,v 1.8 2008/01/22 01:48:09 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {utf16} {
  do_test enc3-1.1 {
    execsql {
      PRAGMA encoding=utf16le;
      PRAGMA encoding;
    }
  } {UTF-16le}
}
do_test enc3-1.2 {
  execsql {
    CREATE TABLE t1(x,y);
    INSERT INTO t1 VALUES('abc''123',5);
    SELECT * FROM t1
  }
} {abc'123 5}
do_test enc3-1.3 {
  execsql {
    SELECT quote(x) || ' ' || quote(y) FROM t1
  }
} {{'abc''123' 5}}
ifcapable {bloblit} {
  do_test enc3-1.4 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(x'616263646566',NULL);
      SELECT * FROM t1
    }
  } {abcdef {}}
  do_test enc3-1.5 {
    execsql {
      SELECT quote(x) || ' ' || quote(y) FROM t1
    }
  } {{X'616263646566' NULL}}
}
ifcapable {bloblit && utf16} {
  do_test enc3-2.1 {
    execsql {
      PRAGMA encoding
    }
  } {UTF-16le}
  do_test enc3-2.2 {
    execsql {
      CREATE TABLE t2(a);
      INSERT INTO t2 VALUES(x'61006200630064006500');
      SELECT CAST(a AS text) FROM t2 WHERE a LIKE 'abc%';
    }
  } {abcde}
  do_test enc3-2.3 {
    execsql {
      SELECT CAST(x'61006200630064006500' AS text);
    }
  } {abcde}
  do_test enc3-2.4 {
    execsql {
      SELECT rowid FROM t2 WHERE a LIKE x'610062002500';
    }
  } {1}
}

# Try to attach a database with a different encoding.
#
ifcapable {utf16 && shared_cache} {
  db close
  file delete -force test8.db test8.db-journal
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
  sqlite3 dbaux test8.db
  sqlite3 db test.db
  db eval {SELECT 1 FROM sqlite_master LIMIT 1}
  do_test enc3-3.1 {
    dbaux eval {
      PRAGMA encoding='utf8';
      CREATE TABLE t1(x);
      PRAGMA encoding
    }
  } {UTF-8}
  do_test enc3-3.2 {
    catchsql {
      ATTACH 'test.db' AS utf16;
      SELECT 1 FROM utf16.sqlite_master LIMIT 1;
    } dbaux
  } {1 {attached databases must use the same text encoding as main database}}
  dbaux close
  file delete -force test8.db test8.db-journal
  sqlite3_enable_shared_cache $::enable_shared_cache
}

finish_test

Added test/eval.test.























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# 2008 July 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file experiments with recursion using the "test_eval()" SQL function
# in order to make sure that SQLite is reentrant.
#
# $Id: eval.test,v 1.2 2008/10/13 10:37:50 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table to work with.
#
do_test eval-1.1 {
  execsql {
    CREATE TABLE t1(x INTEGER PRIMARY KEY); 
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 SELECT x+2 FROM t1;
    INSERT INTO t1 SELECT x+4 FROM t1;
    INSERT INTO t1 SELECT x+8 FROM t1;
    INSERT INTO t1 SELECT x+16 FROM t1;
    INSERT INTO t1 SELECT x+32 FROM t1;
    INSERT INTO t1 SELECT x+64 FROM t1;
    INSERT INTO t1 SELECT x+128 FROM t1;
    INSERT INTO t1 SELECT x+256 FROM t1;
    SELECT count(*), max(x) FROM t1;
  }
} {512 512}
do_test eval-1.2 {
  execsql {
    SELECT x, test_eval('SELECT max(x) FROM t1 WHERE x<' || x) FROM t1 LIMIT 5
  }
} {1 {} 2 1 3 2 4 3 5 4}

# Delete a row out from under a read cursor in the middle of
# collecting the arguments for a single row in a result set.
# Verify that subsequent rows come out as NULL.
#
do_test eval-2.1 {
  execsql {
    CREATE TABLE t2(x,y);
    INSERT INTO t2 SELECT x, x+1 FROM t1 WHERE x<5;
    SELECT x, test_eval('DELETE FROM t2 WHERE x='||x), y FROM t2;
  }
} {1 {} {} 2 {} {} 3 {} {} 4 {} {}}
do_test eval-2.2 {
  execsql {
    SELECT * FROM t2
  }
} {}

# Modify a row while it is being read.
#
do_test eval-3.1 {
  execsql {
    INSERT INTO t2 SELECT x, x+1 FROM t1 WHERE x<5;
    SELECT x, test_eval('UPDATE t2 SET y=y+100 WHERE x='||x), y FROM t2;
  }
} {1 {} 102 2 {} 103 3 {} 104 4 {} 105}

do_test eval-4.1 {
  execsql { SELECT test_eval('SELECT "abcdefghij"') }
} {abcdefghij}

finish_test

Added test/exclusive.test.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# 2007 March 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# of these tests is exclusive access mode (i.e. the thing activated by 
# "PRAGMA locking_mode = EXCLUSIVE").
#
# $Id: exclusive.test,v 1.15 2009/06/26 12:30:40 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas} {
  finish_test
  return
}

file delete -force test2.db-journal
file delete -force test2.db
file delete -force test3.db-journal
file delete -force test3.db
file delete -force test4.db-journal
file delete -force test4.db

#----------------------------------------------------------------------
# Test cases exclusive-1.X test the PRAGMA logic.
#
do_test exclusive-1.0 {
  execsql {
    pragma locking_mode;
    pragma main.locking_mode;
    pragma temp.locking_mode;
  } 
} [list normal normal exclusive]
do_test exclusive-1.1 {
  execsql {
    pragma locking_mode = exclusive;
  } 
} {exclusive}
do_test exclusive-1.2 {
  execsql {
    pragma locking_mode;
    pragma main.locking_mode;
    pragma temp.locking_mode;
  } 
} [list exclusive exclusive exclusive]
do_test exclusive-1.3 {
  execsql {
    pragma locking_mode = normal;
  } 
} {normal}
do_test exclusive-1.4 {
  execsql {
    pragma locking_mode;
    pragma main.locking_mode;
    pragma temp.locking_mode;
  } 
} [list normal normal exclusive]
do_test exclusive-1.5 {
  execsql {
    pragma locking_mode = invalid;
  } 
} {normal}
do_test exclusive-1.6 {
  execsql {
    pragma locking_mode;
    pragma main.locking_mode;
    pragma temp.locking_mode;
  } 
} [list normal normal exclusive]
ifcapable attach {
  do_test exclusive-1.7 {
    execsql {
      pragma locking_mode = exclusive;
      ATTACH 'test2.db' as aux;
    }
    execsql {
      pragma main.locking_mode;
      pragma aux.locking_mode;
    }
  } {exclusive exclusive}
  do_test exclusive-1.8 {
    execsql {
      pragma main.locking_mode = normal;
    }
    execsql {
      pragma main.locking_mode;
      pragma temp.locking_mode;
      pragma aux.locking_mode;
    }
  } [list normal exclusive exclusive]
  do_test exclusive-1.9 {
    execsql {
      pragma locking_mode;
    }
  } {exclusive}
  do_test exclusive-1.10 {
    execsql {
      ATTACH 'test3.db' as aux2;
    }
    execsql {
      pragma main.locking_mode;
      pragma aux.locking_mode;
      pragma aux2.locking_mode;
    }
  } {normal exclusive exclusive}
  do_test exclusive-1.11 {
    execsql {
      pragma aux.locking_mode = normal;
    }
    execsql {
      pragma main.locking_mode;
      pragma aux.locking_mode;
      pragma aux2.locking_mode;
    }
  } {normal normal exclusive}
  do_test exclusive-1.12 {
    execsql {
      pragma locking_mode = normal;
    }
    execsql {
      pragma main.locking_mode;
      pragma temp.locking_mode;
      pragma aux.locking_mode;
      pragma aux2.locking_mode;
    }
  } [list normal exclusive normal normal]
  do_test exclusive-1.13 {
    execsql {
      ATTACH 'test4.db' as aux3;
    }
    execsql {
      pragma main.locking_mode;
      pragma temp.locking_mode;
      pragma aux.locking_mode;
      pragma aux2.locking_mode;
      pragma aux3.locking_mode;
    }
  } [list normal exclusive normal normal normal]
  
  do_test exclusive-1.99 {
    execsql {
      DETACH aux;
      DETACH aux2;
      DETACH aux3;
    }
  } {}
}

#----------------------------------------------------------------------
# Test cases exclusive-2.X verify that connections in exclusive 
# locking_mode do not relinquish locks.
#
do_test exclusive-2.0 {
  execsql {
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
    PRAGMA locking_mode = exclusive;
  }
} {exclusive}
do_test exclusive-2.1 {
  sqlite3 db2 test.db
  execsql {
    INSERT INTO abc VALUES(4, 5, 6);
    SELECT * FROM abc;
  } db2
} {1 2 3 4 5 6}
do_test exclusive-2.2 {
  # This causes connection 'db' (in exclusive mode) to establish 
  # a shared-lock on the db. The other connection should now be
  # locked out as a writer.
  execsql {
    SELECT * FROM abc;
  } db
} {1 2 3 4 5 6}
do_test exclusive-2.4 {
  execsql {
    SELECT * FROM abc;
  } db2
} {1 2 3 4 5 6}
do_test exclusive-2.5 {
  catchsql {
    INSERT INTO abc VALUES(7, 8, 9);
  } db2
} {1 {database is locked}}
sqlite3_soft_heap_limit 0
do_test exclusive-2.6 {
  # Because connection 'db' only has a shared-lock, the other connection
  # will be able to get a RESERVED, but will fail to upgrade to EXCLUSIVE.
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(7, 8, 9);
  } db2
  catchsql {
    COMMIT
  } db2
} {1 {database is locked}}
do_test exclusive-2.7 {
  catchsql {
    COMMIT
  } db2
} {1 {database is locked}}
do_test exclusive-2.8 {
  execsql {
    ROLLBACK;
  } db2
} {}
sqlite3_soft_heap_limit $soft_limit

do_test exclusive-2.9 {
  # Write the database to establish the exclusive lock with connection 'db.
  execsql {
    INSERT INTO abc VALUES(7, 8, 9);
  } db
  catchsql {
    SELECT * FROM abc;
  } db2
} {1 {database is locked}}
do_test exclusive-2.10 {
  # Changing the locking-mode does not release any locks.
  execsql {
    PRAGMA locking_mode = normal;
  } db
  catchsql {
    SELECT * FROM abc;
  } db2
} {1 {database is locked}}
do_test exclusive-2.11 {
  # After changing the locking mode, accessing the db releases locks.
  execsql {
    SELECT * FROM abc;
  } db
  execsql {
    SELECT * FROM abc;
  } db2
} {1 2 3 4 5 6 7 8 9}
db2 close

#----------------------------------------------------------------------
# Tests exclusive-3.X - test that a connection in exclusive mode 
# truncates instead of deletes the journal file when committing 
# a transaction.
#
# These tests are not run on windows because the windows backend
# opens the journal file for exclusive access, preventing its contents 
# from being inspected externally.
#
if {$tcl_platform(platform) != "windows"} {
  proc filestate {fname} {
    set exists 0
    set content 0
    if {[file exists $fname]} {
      set exists 1
      set hdr [hexio_read $fname 0 28]
      set content [expr {0==[string match $hdr [string repeat 0 56]]}]
    }
    list $exists $content
  }
  do_test exclusive-3.0 {
    filestate test.db-journal
  } {0 0}
  do_test exclusive-3.1 {
    execsql {
      PRAGMA locking_mode = exclusive;
      BEGIN;
      DELETE FROM abc;
    }
    filestate test.db-journal
  } {1 1}
  do_test exclusive-3.2 {
    execsql {
      COMMIT;
    }
    filestate test.db-journal
  } {1 0}
  do_test exclusive-3.3 {
    execsql {
      INSERT INTO abc VALUES('A', 'B', 'C');
      SELECT * FROM abc;
    }
  } {A B C}
  do_test exclusive-3.4 {
    execsql {
      BEGIN;
      UPDATE abc SET a = 1, b = 2, c = 3;
      ROLLBACK;
      SELECT * FROM abc;
    }
  } {A B C}
  do_test exclusive-3.5 {
    filestate test.db-journal
  } {1 0}
  do_test exclusive-3.6 {
    execsql {
      PRAGMA locking_mode = normal;
      SELECT * FROM abc;
    }
    filestate test.db-journal
  } {0 0}
}

#----------------------------------------------------------------------
# Tests exclusive-4.X - test that rollback works correctly when
# in exclusive-access mode.
#

# The following procedure computes a "signature" for table "t3".  If
# T3 changes in any way, the signature should change.  
#
# This is used to test ROLLBACK.  We gather a signature for t3, then
# make lots of changes to t3, then rollback and take another signature.
# The two signatures should be the same.
#
proc signature {} {
  return [db eval {SELECT count(*), md5sum(x) FROM t3}]
}

do_test exclusive-4.0 {
  execsql { PRAGMA locking_mode = exclusive; }
  execsql { PRAGMA default_cache_size = 10; }
  execsql {
    BEGIN;
    CREATE TABLE t3(x TEXT);
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    COMMIT;
  }
  execsql {SELECT count(*) FROM t3;}
} {32}

set ::X [signature]
do_test exclusive-4.1 {
  execsql {
    BEGIN;
    DELETE FROM t3 WHERE random()%10!=0;
    INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
    INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
    SELECT count(*) FROM t3;
    ROLLBACK;
  }
  signature
} $::X

do_test exclusive-4.2 {
  execsql {
    BEGIN;
    DELETE FROM t3 WHERE random()%10!=0;
    INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
    DELETE FROM t3 WHERE random()%10!=0;
    INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
    ROLLBACK;
  }
  signature
} $::X

do_test exclusive-4.3 {
  execsql {
    INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0;
  }
} {}

do_test exclusive-4.4 {
  catch {set ::X [signature]}
} {0}
do_test exclusive-4.5 {
  execsql {
    PRAGMA locking_mode = NORMAL;
    DROP TABLE t3;
    DROP TABLE abc;
  }
} {normal}

#----------------------------------------------------------------------
# Tests exclusive-5.X - test that statement journals are truncated
# instead of deleted when in exclusive access mode.
#

# Close and reopen the database so that the temp database is no
# longer active.
#
db close
sqlite db test.db

# if we're using proxy locks, we use 3 filedescriptors for a db
# that is open but NOT writing changes, normally
# sqlite uses 1 (proxy locking adds the conch and the local lock)
set using_proxy 0
foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] {
  set using_proxy $value
}
set extrafds 0
if {$using_proxy!=0} {
  set extrafds 2
} 

do_test exclusive-5.0 {
  execsql {
    CREATE TABLE abc(a UNIQUE, b UNIQUE, c UNIQUE);
    BEGIN;
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc SELECT a+1, b+1, c+1 FROM abc;
  }
} {}
do_test exclusive-5.1 {
  # Three files are open: The db, journal and statement-journal.
  set sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds
} [expr 3 - ($TEMP_STORE>=2)]
do_test exclusive-5.2 {
  execsql {
    COMMIT;
  }
  # One file open: the db.
  set sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds
} {1}
do_test exclusive-5.3 {
  execsql {
    PRAGMA locking_mode = exclusive;
    BEGIN;
    INSERT INTO abc VALUES(5, 6, 7);
  }
  # Two files open: the db and journal.
  set sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds
} {2}
do_test exclusive-5.4 {
  execsql {
    INSERT INTO abc SELECT a+10, b+10, c+10 FROM abc;
  }
  # Three files are open: The db, journal and statement-journal.
  set sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds
} [expr 3 - ($TEMP_STORE>=2)]
do_test exclusive-5.5 {
  execsql {
    COMMIT;
  }
  # Three files are still open: The db, journal and statement-journal.
  set sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds
} [expr 3 - ($TEMP_STORE>=2)]
do_test exclusive-5.6 {
  execsql {
    PRAGMA locking_mode = normal;
    SELECT * FROM abc;
  }
} {normal 1 2 3 2 3 4 5 6 7 11 12 13 12 13 14 15 16 17}
do_test exclusive-5.7 {
  # Just the db open.
  set sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds
} {1}

finish_test

Added test/exclusive2.test.

































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# 2007 March 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# $Id: exclusive2.test,v 1.10 2008/11/27 02:22:11 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas} {
  finish_test
  return
}

# This module does not work right if the cache spills at unexpected
# moments.  So disable the soft-heap-limit.
#
sqlite3_soft_heap_limit 0

proc pagerChangeCounter {filename new {fd ""}} {
  if {$fd==""} {
    set fd [open $filename RDWR]
    fconfigure $fd -translation binary -encoding binary
    set needClose 1
  } else {
    set needClose 0
  }
  if {$new ne ""} {
    seek $fd 24
    set a [expr {($new&0xFF000000)>>24}]
    set b [expr {($new&0x00FF0000)>>16}]
    set c [expr {($new&0x0000FF00)>>8}]
    set d [expr {($new&0x000000FF)}]
    puts -nonewline $fd [binary format cccc $a $b $c $d]
    flush $fd
  }

  seek $fd 24
  foreach {a b c d} [list 0 0 0 0] {}
  binary scan [read $fd 4] cccc a b c d
  set  ret [expr ($a&0x000000FF)<<24]
  incr ret [expr ($b&0x000000FF)<<16]
  incr ret [expr ($c&0x000000FF)<<8]
  incr ret [expr ($d&0x000000FF)<<0]

  if {$needClose} {close $fd}
  return $ret
}

proc readPagerChangeCounter {filename} {
  set fd [open $filename RDONLY]
  fconfigure $fd -translation binary -encoding binary

  seek $fd 24
  foreach {a b c d} [list 0 0 0 0] {}
  binary scan [read $fd 4] cccc a b c d
  set  ret [expr ($a&0x000000FF)<<24]
  incr ret [expr ($b&0x000000FF)<<16]
  incr ret [expr ($c&0x000000FF)<<8]
  incr ret [expr ($d&0x000000FF)<<0]

  close $fd
  return $ret
}


proc t1sig {{db db}} {
  execsql {SELECT count(*), md5sum(a) FROM t1} $db
}
do_test exclusive2-1.0 {
  readPagerChangeCounter test.db
} {0}

#-----------------------------------------------------------------------
# The following tests - exclusive2-1.X - check that:
#
# 1-3:   Build a database with connection 1, calculate a signature.
# 4-9:   Modify the database using a second connection in a way that
#        does not modify the freelist, then reset the pager change-counter
#        to the value it had before the modifications.
# 8:     Check that using the first connection, the database signature
#        is still the same. This is because it uses the in-memory cache.
#        It can't tell the db has changed because we reset the change-counter.
# 9:     Increment the change-counter.
# 10:    Ensure that the first connection now sees the updated database. It
#        sees the change-counter has been incremented and discards the 
#        invalid in-memory cache.
#
# This will only work if the database cache is large enough to hold 
# the entire database. In the case of 1024 byte pages, this means
# the cache size must be at least 17. Otherwise, some pages will be
# loaded from the database file in step 8.
#
do_test exclusive2-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    INSERT INTO t1(a) VALUES(randstr(10, 400));
    INSERT INTO t1(a) VALUES(randstr(10, 400));
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {64}
do_test exclusive2-1.2.1 {
  # Make sure the pager cache is large enough to store the 
  # entire database.
  set nPage [expr [file size test.db]/1024]
  if {$::SQLITE_DEFAULT_CACHE_SIZE < $nPage} {
    execsql "PRAGMA cache_size = $nPage"
  }
  expr {[execsql {PRAGMA cache_size}] >= $nPage}
} {1}
do_test exclusive2-1.2 {
  set ::sig [t1sig]
  readPagerChangeCounter test.db
} {1}
do_test exclusive2-1.3 {
  t1sig
} $::sig
do_test exclusive2-1.4 {
  sqlite3 db2 test.db
  t1sig db2
} $::sig
do_test exclusive2-1.5 {
  execsql {
    UPDATE t1 SET b=a, a=NULL;
  } db2
  expr {[t1sig db2] eq $::sig}
} 0
do_test exclusive2-1.6 {
  readPagerChangeCounter test.db
} {2}
do_test exclusive2-1.7 {
  pagerChangeCounter test.db 1
} {1}
do_test exclusive2-1.9 {
  t1sig
  expr {[t1sig] eq $::sig}
} {1}
do_test exclusive2-1.10 {
  pagerChangeCounter test.db 2
} {2}
do_test exclusive2-1.11 {
  expr {[t1sig] eq $::sig}
} {0}

#--------------------------------------------------------------------
# These tests - exclusive2-2.X - are similar to exclusive2-1.X, 
# except that they are run with locking_mode=EXCLUSIVE.
#
# 1-3:   Build a database with exclusive-access connection 1, 
#        calculate a signature.
# 4:     Corrupt the database by writing 10000 bytes of garbage
#        starting at the beginning of page 2. Check that connection 1
#        still works. It should be accessing the in-memory cache.
# 5-6:   Modify the dataase change-counter. Connection 1 still works
#        entirely from in-memory cache, because it doesn't check the
#        change-counter.
# 7-8    Set the locking-mode back to normal. After the db is unlocked,
#        SQLite detects the modified change-counter and discards the
#        in-memory cache. Then it finds the corruption caused in step 4....
#
# As above, this test is only applicable if the pager cache is
# large enough to hold the entire database. With 1024 byte pages,
# this means 19 pages.  We also need to disable the soft-heap-limit
# to prevent memory-induced cache spills.
#
do_test exclusive2-2.1 {
  execsql {PRAGMA cache_size=1000;}
  execsql {PRAGMA locking_mode = exclusive;}
  execsql {
    BEGIN;
    DELETE FROM t1;
    INSERT INTO t1(a) VALUES(randstr(10, 400));
    INSERT INTO t1(a) VALUES(randstr(10, 400));
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1;
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {64}
do_test exclusive2-2.2.1 {
  # Make sure the pager cache is large enough to store the 
  # entire database.
  set nPage [expr [file size test.db]/1024]
  if {$::SQLITE_DEFAULT_CACHE_SIZE < $nPage} {
    execsql "PRAGMA cache_size = $nPage"
  }
  expr {[execsql {PRAGMA cache_size}] >= $nPage}
} {1}
do_test exclusive2-2.2 {
  set ::sig [t1sig]
  readPagerChangeCounter test.db
} {3}
do_test exclusive2-2.3 {
  t1sig
} $::sig

do_test exclusive2-2.4 {
  set ::fd [open test.db RDWR]
  fconfigure $::fd -translation binary
  seek $::fd 1024
  puts -nonewline $::fd [string repeat [binary format c 0] 10000]
  flush $::fd
  t1sig
} $::sig

do_test exclusive2-2.5 {
  pagerChangeCounter test.db 5 $::fd
} {5}
do_test exclusive2-2.6 {
  t1sig
} $::sig
do_test exclusive2-2.7 {
  execsql {PRAGMA locking_mode = normal}
  t1sig
} $::sig

do_test exclusive2-2.8 {
  set rc [catch {t1sig} msg]
  list $rc $msg
} {1 {database disk image is malformed}}

#--------------------------------------------------------------------
# These tests - exclusive2-3.X - verify that the pager change-counter
# is only incremented by the first change when in exclusive access
# mode. In normal mode, the change-counter is incremented once
# per write-transaction.
#

db close
db2 close
catch {close $::fd}
file delete -force test.db
file delete -force test.db-journal

do_test exclusive2-3.0 {
  sqlite3 db test.db
  execsql {
    BEGIN;
    CREATE TABLE t1(a UNIQUE);
    INSERT INTO t1 VALUES(randstr(10, 400));
    INSERT INTO t1 VALUES(randstr(10, 400));
    COMMIT;
  }
  readPagerChangeCounter test.db
} {1}
do_test exclusive2-3.1 {
  execsql {
    INSERT INTO t1 VALUES(randstr(10, 400));
  }
  readPagerChangeCounter test.db
} {2}
do_test exclusive2-3.2 {
  execsql {
    INSERT INTO t1 VALUES(randstr(10, 400));
  }
  readPagerChangeCounter test.db
} {3}
do_test exclusive2-3.3 {
  execsql {
    PRAGMA locking_mode = exclusive;
    INSERT INTO t1 VALUES(randstr(10, 400));
  }
  readPagerChangeCounter test.db
} {4}
do_test exclusive2-3.4 {
  execsql {
    INSERT INTO t1 VALUES(randstr(10, 400));
  }
  readPagerChangeCounter test.db
} {4}
do_test exclusive2-3.5 {
  execsql {
    PRAGMA locking_mode = normal;
    INSERT INTO t1 VALUES(randstr(10, 400));
  }
  readPagerChangeCounter test.db
} {4}
do_test exclusive2-3.6 {
  execsql {
    INSERT INTO t1 VALUES(randstr(10, 400));
  }
  readPagerChangeCounter test.db
} {5}
sqlite3_soft_heap_limit $soft_limit

finish_test

Added test/exec.test.











































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 2008 Jan 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the sqlite3_exec interface
#
# $Id: exec.test,v 1.1 2008/01/21 16:22:46 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test exec-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    SELECT * FROM t1;
  }
} {1 2}
do_test exec-1.2 {
  sqlite3_exec db {/* comment */;;; SELECT * FROM t1; /* comment */}
} {0 {a b 1 2}}
do_test exec-1.3 {
  sqlite3 db2 test.db
  db2 eval {CREATE TABLE t2(x, y);}
  db2 close
  sqlite3_exec db {SELECT * FROM t1}
} {0 {a b 1 2}}

finish_test

Added test/expr.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing expressions.
#
# $Id: expr.test,v 1.67 2009/02/04 03:59:25 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table to work with.
#
ifcapable floatingpoint {
  execsql {CREATE TABLE test1(i1 int, i2 int, r1 real, r2 real, t1 text, t2 text)}
  execsql {INSERT INTO test1 VALUES(1,2,1.1,2.2,'hello','world')}
}
ifcapable !floatingpoint {
  execsql {CREATE TABLE test1(i1 int, i2 int, t1 text, t2 text)}
  execsql {INSERT INTO test1 VALUES(1,2,'hello','world')}
}

proc test_expr {name settings expr result} {
  do_test $name [format {
    execsql {BEGIN; UPDATE test1 SET %s; SELECT %s FROM test1; ROLLBACK;}
  } $settings $expr] $result
}

test_expr expr-1.1 {i1=10, i2=20} {i1+i2} 30
test_expr expr-1.2 {i1=10, i2=20} {i1-i2} -10
test_expr expr-1.3 {i1=10, i2=20} {i1*i2} 200
test_expr expr-1.4 {i1=10, i2=20} {i1/i2} 0
test_expr expr-1.5 {i1=10, i2=20} {i2/i1} 2
test_expr expr-1.6 {i1=10, i2=20} {i2<i1} 0
test_expr expr-1.7 {i1=10, i2=20} {i2<=i1} 0
test_expr expr-1.8 {i1=10, i2=20} {i2>i1} 1
test_expr expr-1.9 {i1=10, i2=20} {i2>=i1} 1
test_expr expr-1.10 {i1=10, i2=20} {i2!=i1} 1
test_expr expr-1.11 {i1=10, i2=20} {i2=i1} 0
test_expr expr-1.12 {i1=10, i2=20} {i2<>i1} 1
test_expr expr-1.13 {i1=10, i2=20} {i2==i1} 0
test_expr expr-1.14 {i1=20, i2=20} {i2<i1} 0
test_expr expr-1.15 {i1=20, i2=20} {i2<=i1} 1
test_expr expr-1.16 {i1=20, i2=20} {i2>i1} 0
test_expr expr-1.17 {i1=20, i2=20} {i2>=i1} 1
test_expr expr-1.18 {i1=20, i2=20} {i2!=i1} 0
test_expr expr-1.19 {i1=20, i2=20} {i2=i1} 1
test_expr expr-1.20 {i1=20, i2=20} {i2<>i1} 0
test_expr expr-1.21 {i1=20, i2=20} {i2==i1} 1
ifcapable floatingpoint {
  test_expr expr-1.22 {i1=1, i2=2, r1=3.0} {i1+i2*r1} {7.0}
  test_expr expr-1.23 {i1=1, i2=2, r1=3.0} {(i1+i2)*r1} {9.0}
}
test_expr expr-1.24 {i1=1, i2=2} {min(i1,i2,i1+i2,i1-i2)} {-1}
test_expr expr-1.25 {i1=1, i2=2} {max(i1,i2,i1+i2,i1-i2)} {3}
test_expr expr-1.26 {i1=1, i2=2} {max(i1,i2,i1+i2,i1-i2)} {3}
test_expr expr-1.27 {i1=1, i2=2} {i1==1 AND i2=2} {1}
test_expr expr-1.28 {i1=1, i2=2} {i1=2 AND i2=1} {0}
test_expr expr-1.29 {i1=1, i2=2} {i1=1 AND i2=1} {0}
test_expr expr-1.30 {i1=1, i2=2} {i1=2 AND i2=2} {0}
test_expr expr-1.31 {i1=1, i2=2} {i1==1 OR i2=2} {1}
test_expr expr-1.32 {i1=1, i2=2} {i1=2 OR i2=1} {0}
test_expr expr-1.33 {i1=1, i2=2} {i1=1 OR i2=1} {1}
test_expr expr-1.34 {i1=1, i2=2} {i1=2 OR i2=2} {1}
test_expr expr-1.35 {i1=1, i2=2} {i1-i2=-1} {1}
test_expr expr-1.36 {i1=1, i2=0} {not i1} {0}
test_expr expr-1.37 {i1=1, i2=0} {not i2} {1}
test_expr expr-1.38 {i1=1} {-i1} {-1}
test_expr expr-1.39 {i1=1} {+i1} {1}
test_expr expr-1.40 {i1=1, i2=2} {+(i2+i1)} {3}
test_expr expr-1.41 {i1=1, i2=2} {-(i2+i1)} {-3}
test_expr expr-1.42 {i1=1, i2=2} {i1|i2} {3}
test_expr expr-1.42b {i1=1, i2=2} {4|2} {6}
test_expr expr-1.43 {i1=1, i2=2} {i1&i2} {0}
test_expr expr-1.43b {i1=1, i2=2} {4&5} {4}
test_expr expr-1.44 {i1=1} {~i1} {-2}
test_expr expr-1.44b {i1=NULL} {~i1} {{}}
test_expr expr-1.45 {i1=1, i2=3} {i1<<i2} {8}
test_expr expr-1.46 {i1=32, i2=3} {i1>>i2} {4}
test_expr expr-1.47 {i1=9999999999, i2=8888888888} {i1<i2} 0
test_expr expr-1.48 {i1=9999999999, i2=8888888888} {i1=i2} 0
test_expr expr-1.49 {i1=9999999999, i2=8888888888} {i1>i2} 1
test_expr expr-1.50 {i1=99999999999, i2=99999999998} {i1<i2} 0
test_expr expr-1.51 {i1=99999999999, i2=99999999998} {i1=i2} 0
test_expr expr-1.52 {i1=99999999999, i2=99999999998} {i1>i2} 1
test_expr expr-1.53 {i1=099999999999, i2=99999999999} {i1<i2} 0
test_expr expr-1.54 {i1=099999999999, i2=99999999999} {i1=i2} 1
test_expr expr-1.55 {i1=099999999999, i2=99999999999} {i1>i2} 0
test_expr expr-1.56 {i1=25, i2=11} {i1%i2} 3
test_expr expr-1.58 {i1=NULL, i2=1} {coalesce(i1+i2,99)} 99
test_expr expr-1.59 {i1=1, i2=NULL} {coalesce(i1+i2,99)} 99
test_expr expr-1.60 {i1=NULL, i2=NULL} {coalesce(i1+i2,99)} 99
test_expr expr-1.61 {i1=NULL, i2=1} {coalesce(i1-i2,99)} 99
test_expr expr-1.62 {i1=1, i2=NULL} {coalesce(i1-i2,99)} 99
test_expr expr-1.63 {i1=NULL, i2=NULL} {coalesce(i1-i2,99)} 99
test_expr expr-1.64 {i1=NULL, i2=1} {coalesce(i1*i2,99)} 99
test_expr expr-1.65 {i1=1, i2=NULL} {coalesce(i1*i2,99)} 99
test_expr expr-1.66 {i1=NULL, i2=NULL} {coalesce(i1*i2,99)} 99
test_expr expr-1.67 {i1=NULL, i2=1} {coalesce(i1/i2,99)} 99
test_expr expr-1.68 {i1=1, i2=NULL} {coalesce(i1/i2,99)} 99
test_expr expr-1.69 {i1=NULL, i2=NULL} {coalesce(i1/i2,99)} 99
test_expr expr-1.70 {i1=NULL, i2=1} {coalesce(i1<i2,99)} 99
test_expr expr-1.71 {i1=1, i2=NULL} {coalesce(i1>i2,99)} 99
test_expr expr-1.72 {i1=NULL, i2=NULL} {coalesce(i1<=i2,99)} 99
test_expr expr-1.73 {i1=NULL, i2=1} {coalesce(i1>=i2,99)} 99
test_expr expr-1.74 {i1=1, i2=NULL} {coalesce(i1!=i2,99)} 99
test_expr expr-1.75 {i1=NULL, i2=NULL} {coalesce(i1==i2,99)} 99
test_expr expr-1.76 {i1=NULL, i2=NULL} {coalesce(not i1,99)} 99
test_expr expr-1.77 {i1=NULL, i2=NULL} {coalesce(-i1,99)} 99
test_expr expr-1.78 {i1=NULL, i2=NULL} {coalesce(i1 IS NULL AND i2=5,99)} 99
test_expr expr-1.79 {i1=NULL, i2=NULL} {coalesce(i1 IS NULL OR i2=5,99)} 1
test_expr expr-1.80 {i1=NULL, i2=NULL} {coalesce(i1=5 AND i2 IS NULL,99)} 99
test_expr expr-1.81 {i1=NULL, i2=NULL} {coalesce(i1=5 OR i2 IS NULL,99)} 1
test_expr expr-1.82 {i1=NULL, i2=3} {coalesce(min(i1,i2,1),99)} 99
test_expr expr-1.83 {i1=NULL, i2=3} {coalesce(max(i1,i2,1),99)} 99
test_expr expr-1.84 {i1=3, i2=NULL} {coalesce(min(i1,i2,1),99)} 99
test_expr expr-1.85 {i1=3, i2=NULL} {coalesce(max(i1,i2,1),99)} 99
test_expr expr-1.86 {i1=3, i2=8} {5 between i1 and i2} 1
test_expr expr-1.87 {i1=3, i2=8} {5 not between i1 and i2} 0
test_expr expr-1.88 {i1=3, i2=8} {55 between i1 and i2} 0
test_expr expr-1.89 {i1=3, i2=8} {55 not between i1 and i2} 1
test_expr expr-1.90 {i1=3, i2=NULL} {5 between i1 and i2} {{}}
test_expr expr-1.91 {i1=3, i2=NULL} {5 not between i1 and i2} {{}}
test_expr expr-1.92 {i1=3, i2=NULL} {2 between i1 and i2} 0
test_expr expr-1.93 {i1=3, i2=NULL} {2 not between i1 and i2} 1
test_expr expr-1.94 {i1=NULL, i2=8} {2 between i1 and i2} {{}}
test_expr expr-1.95 {i1=NULL, i2=8} {2 not between i1 and i2} {{}}
test_expr expr-1.94 {i1=NULL, i2=8} {55 between i1 and i2} 0
test_expr expr-1.95 {i1=NULL, i2=8} {55 not between i1 and i2} 1
test_expr expr-1.96 {i1=NULL, i2=3} {coalesce(i1<<i2,99)} 99
test_expr expr-1.97 {i1=32, i2=NULL} {coalesce(i1>>i2,99)} 99
test_expr expr-1.98 {i1=NULL, i2=NULL} {coalesce(i1|i2,99)} 99
test_expr expr-1.99 {i1=32, i2=NULL} {coalesce(i1&i2,99)} 99
test_expr expr-1.100 {i1=1, i2=''} {i1=i2} 0
test_expr expr-1.101 {i1=0, i2=''} {i1=i2} 0

# Check for proper handling of 64-bit integer values.
#
if {[working_64bit_int]} {
  test_expr expr-1.102 {i1=40, i2=1} {i2<<i1} 1099511627776
}

ifcapable floatingpoint {
  test_expr expr-1.103 {i1=0} {(-2147483648.0 % -1)} 0.0
  test_expr expr-1.104 {i1=0} {(-9223372036854775808.0 % -1)} 0.0
  test_expr expr-1.105 {i1=0} {(-9223372036854775808.0 / -1)>1} 1
}

if {[working_64bit_int]} {
  test_expr expr-1.106 {i1=0} {(1<<63)/-1} -9223372036854775808
}

test_expr expr-1.107 {i1=0} {(1<<63)%-1} 0
test_expr expr-1.108 {i1=0} {1%0} {{}}
test_expr expr-1.109 {i1=0} {1/0} {{}}

if {[working_64bit_int]} {
  test_expr expr-1.110 {i1=0} {-9223372036854775807/-1} 9223372036854775807
}

test_expr expr-1.111 {i1=NULL, i2=8} {i1 IS i2} 0
test_expr expr-1.112 {i1=NULL, i2=NULL} {i1 IS i2} 1
test_expr expr-1.113 {i1=6, i2=NULL} {i1 IS i2} 0
test_expr expr-1.114 {i1=6, i2=6} {i1 IS i2} 1
test_expr expr-1.115 {i1=NULL, i2=8} \
  {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} no
test_expr expr-1.116 {i1=NULL, i2=NULL} \
  {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} yes
test_expr expr-1.117 {i1=6, i2=NULL} \
  {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} no
test_expr expr-1.118 {i1=8, i2=8} \
  {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} yes
test_expr expr-1.119 {i1=NULL, i2=8} {i1 IS NOT i2} 1
test_expr expr-1.120 {i1=NULL, i2=NULL} {i1 IS NOT i2} 0
test_expr expr-1.121 {i1=6, i2=NULL} {i1 IS NOT i2} 1
test_expr expr-1.122 {i1=6, i2=6} {i1 IS NOT i2} 0
test_expr expr-1.123 {i1=NULL, i2=8} \
  {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} yes
test_expr expr-1.124 {i1=NULL, i2=NULL} \
  {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} no
test_expr expr-1.125 {i1=6, i2=NULL} \
  {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} yes
test_expr expr-1.126 {i1=8, i2=8} \
  {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} no

ifcapable floatingpoint {
  test_expr expr-2.1 {r1=1.23, r2=2.34} {r1+r2} 3.57
  test_expr expr-2.2 {r1=1.23, r2=2.34} {r1-r2} -1.11
  test_expr expr-2.3 {r1=1.23, r2=2.34} {r1*r2} 2.8782
}
set tcl_precision 15
ifcapable floatingpoint {
  test_expr expr-2.4 {r1=1.23, r2=2.34} {r1/r2} 0.525641025641026
  test_expr expr-2.5 {r1=1.23, r2=2.34} {r2/r1} 1.90243902439024
  test_expr expr-2.6 {r1=1.23, r2=2.34} {r2<r1} 0
  test_expr expr-2.7 {r1=1.23, r2=2.34} {r2<=r1} 0
  test_expr expr-2.8 {r1=1.23, r2=2.34} {r2>r1} 1
  test_expr expr-2.9 {r1=1.23, r2=2.34} {r2>=r1} 1
  test_expr expr-2.10 {r1=1.23, r2=2.34} {r2!=r1} 1
  test_expr expr-2.11 {r1=1.23, r2=2.34} {r2=r1} 0
  test_expr expr-2.12 {r1=1.23, r2=2.34} {r2<>r1} 1
  test_expr expr-2.13 {r1=1.23, r2=2.34} {r2==r1} 0
  test_expr expr-2.14 {r1=2.34, r2=2.34} {r2<r1} 0
  test_expr expr-2.15 {r1=2.34, r2=2.34} {r2<=r1} 1
  test_expr expr-2.16 {r1=2.34, r2=2.34} {r2>r1} 0
  test_expr expr-2.17 {r1=2.34, r2=2.34} {r2>=r1} 1
  test_expr expr-2.18 {r1=2.34, r2=2.34} {r2!=r1} 0
  test_expr expr-2.19 {r1=2.34, r2=2.34} {r2=r1} 1
  test_expr expr-2.20 {r1=2.34, r2=2.34} {r2<>r1} 0
  test_expr expr-2.21 {r1=2.34, r2=2.34} {r2==r1} 1
  test_expr expr-2.22 {r1=1.23, r2=2.34} {min(r1,r2,r1+r2,r1-r2)} {-1.11}
  test_expr expr-2.23 {r1=1.23, r2=2.34} {max(r1,r2,r1+r2,r1-r2)} {3.57}
  test_expr expr-2.24 {r1=25.0, r2=11.0} {r1%r2} 3.0
  test_expr expr-2.25 {r1=1.23, r2=NULL} {coalesce(r1+r2,99.0)} 99.0
  test_expr expr-2.26 {r1=1e300, r2=1e300} {coalesce((r1*r2)*0.0,99.0)} 99.0
  test_expr expr-2.26b {r1=1e300, r2=-1e300} {coalesce((r1*r2)*0.0,99.0)} 99.0
  test_expr expr-2.27 {r1=1.1, r2=0.0} {r1/r2} {{}}
  test_expr expr-2.28 {r1=1.1, r2=0.0} {r1%r2} {{}}
}

test_expr expr-3.1 {t1='abc', t2='xyz'} {t1<t2} 1
test_expr expr-3.2 {t1='xyz', t2='abc'} {t1<t2} 0
test_expr expr-3.3 {t1='abc', t2='abc'} {t1<t2} 0
test_expr expr-3.4 {t1='abc', t2='xyz'} {t1<=t2} 1
test_expr expr-3.5 {t1='xyz', t2='abc'} {t1<=t2} 0
test_expr expr-3.6 {t1='abc', t2='abc'} {t1<=t2} 1
test_expr expr-3.7 {t1='abc', t2='xyz'} {t1>t2} 0
test_expr expr-3.8 {t1='xyz', t2='abc'} {t1>t2} 1
test_expr expr-3.9 {t1='abc', t2='abc'} {t1>t2} 0
test_expr expr-3.10 {t1='abc', t2='xyz'} {t1>=t2} 0
test_expr expr-3.11 {t1='xyz', t2='abc'} {t1>=t2} 1
test_expr expr-3.12 {t1='abc', t2='abc'} {t1>=t2} 1
test_expr expr-3.13 {t1='abc', t2='xyz'} {t1=t2} 0
test_expr expr-3.14 {t1='xyz', t2='abc'} {t1=t2} 0
test_expr expr-3.15 {t1='abc', t2='abc'} {t1=t2} 1
test_expr expr-3.16 {t1='abc', t2='xyz'} {t1==t2} 0
test_expr expr-3.17 {t1='xyz', t2='abc'} {t1==t2} 0
test_expr expr-3.18 {t1='abc', t2='abc'} {t1==t2} 1
test_expr expr-3.19 {t1='abc', t2='xyz'} {t1<>t2} 1
test_expr expr-3.20 {t1='xyz', t2='abc'} {t1<>t2} 1
test_expr expr-3.21 {t1='abc', t2='abc'} {t1<>t2} 0
test_expr expr-3.22 {t1='abc', t2='xyz'} {t1!=t2} 1
test_expr expr-3.23 {t1='xyz', t2='abc'} {t1!=t2} 1
test_expr expr-3.24 {t1='abc', t2='abc'} {t1!=t2} 0
test_expr expr-3.25 {t1=NULL, t2='hi'} {t1 isnull} 1
test_expr expr-3.25b {t1=NULL, t2='hi'} {t1 is null} 1
test_expr expr-3.26 {t1=NULL, t2='hi'} {t2 isnull} 0
test_expr expr-3.27 {t1=NULL, t2='hi'} {t1 notnull} 0
test_expr expr-3.28 {t1=NULL, t2='hi'} {t2 notnull} 1
test_expr expr-3.28b {t1=NULL, t2='hi'} {t2 is not null} 1
test_expr expr-3.29 {t1='xyz', t2='abc'} {t1||t2} {xyzabc}
test_expr expr-3.30 {t1=NULL, t2='abc'} {t1||t2} {{}}
test_expr expr-3.31 {t1='xyz', t2=NULL} {t1||t2} {{}}
test_expr expr-3.32 {t1='xyz', t2='abc'} {t1||' hi '||t2} {{xyz hi abc}}
test_expr epxr-3.33 {t1='abc', t2=NULL} {coalesce(t1<t2,99)} 99
test_expr epxr-3.34 {t1='abc', t2=NULL} {coalesce(t2<t1,99)} 99
test_expr epxr-3.35 {t1='abc', t2=NULL} {coalesce(t1>t2,99)} 99
test_expr epxr-3.36 {t1='abc', t2=NULL} {coalesce(t2>t1,99)} 99
test_expr epxr-3.37 {t1='abc', t2=NULL} {coalesce(t1<=t2,99)} 99
test_expr epxr-3.38 {t1='abc', t2=NULL} {coalesce(t2<=t1,99)} 99
test_expr epxr-3.39 {t1='abc', t2=NULL} {coalesce(t1>=t2,99)} 99
test_expr epxr-3.40 {t1='abc', t2=NULL} {coalesce(t2>=t1,99)} 99
test_expr epxr-3.41 {t1='abc', t2=NULL} {coalesce(t1==t2,99)} 99
test_expr epxr-3.42 {t1='abc', t2=NULL} {coalesce(t2==t1,99)} 99
test_expr epxr-3.43 {t1='abc', t2=NULL} {coalesce(t1!=t2,99)} 99
test_expr epxr-3.44 {t1='abc', t2=NULL} {coalesce(t2!=t1,99)} 99

test_expr expr-4.1 {t1='abc', t2='Abc'} {t1<t2} 0
test_expr expr-4.2 {t1='abc', t2='Abc'} {t1>t2} 1
test_expr expr-4.3 {t1='abc', t2='Bbc'} {t1<t2} 0
test_expr expr-4.4 {t1='abc', t2='Bbc'} {t1>t2} 1
test_expr expr-4.5 {t1='0', t2='0.0'} {t1==t2} 0
test_expr expr-4.6 {t1='0.000', t2='0.0'} {t1==t2} 0
test_expr expr-4.7 {t1=' 0.000', t2=' 0.0'} {t1==t2} 0
test_expr expr-4.8 {t1='0.0', t2='abc'} {t1<t2} 1
test_expr expr-4.9 {t1='0.0', t2='abc'} {t1==t2} 0

ifcapable floatingpoint {
  test_expr expr-4.10 {r1='0.0', r2='abc'} {r1>r2} 0
  test_expr expr-4.11 {r1='abc', r2='Abc'} {r1<r2} 0
  test_expr expr-4.12 {r1='abc', r2='Abc'} {r1>r2} 1
  test_expr expr-4.13 {r1='abc', r2='Bbc'} {r1<r2} 0
  test_expr expr-4.14 {r1='abc', r2='Bbc'} {r1>r2} 1
  test_expr expr-4.15 {r1='0', r2='0.0'} {r1==r2} 1
  test_expr expr-4.16 {r1='0.000', r2='0.0'} {r1==r2} 1
  test_expr expr-4.17 {r1=' 0.000', r2=' 0.0'} {r1==r2} 0
  test_expr expr-4.18 {r1='0.0', r2='abc'} {r1<r2} 1
  test_expr expr-4.19 {r1='0.0', r2='abc'} {r1==r2} 0
  test_expr expr-4.20 {r1='0.0', r2='abc'} {r1>r2} 0
}

# CSL is true if LIKE is case sensitive and false if not.
# NCSL is the opposite.  Use these variables as the result
# on operations where case makes a difference.
set CSL $sqlite_options(casesensitivelike)
set NCSL [expr {!$CSL}]

test_expr expr-5.1 {t1='abc', t2='xyz'} {t1 LIKE t2} 0
test_expr expr-5.2a {t1='abc', t2='abc'} {t1 LIKE t2} 1
test_expr expr-5.2b {t1='abc', t2='ABC'} {t1 LIKE t2} $NCSL
test_expr expr-5.3a {t1='abc', t2='a_c'} {t1 LIKE t2} 1
test_expr expr-5.3b {t1='abc', t2='A_C'} {t1 LIKE t2} $NCSL
test_expr expr-5.4 {t1='abc', t2='abc_'} {t1 LIKE t2} 0
test_expr expr-5.5a {t1='abc', t2='a%c'} {t1 LIKE t2} 1
test_expr expr-5.5b {t1='abc', t2='A%C'} {t1 LIKE t2} $NCSL
test_expr expr-5.5c {t1='abdc', t2='a%c'} {t1 LIKE t2} 1
test_expr expr-5.5d {t1='ac', t2='a%c'} {t1 LIKE t2} 1
test_expr expr-5.5e {t1='ac', t2='A%C'} {t1 LIKE t2} $NCSL
test_expr expr-5.6a {t1='abxyzzyc', t2='a%c'} {t1 LIKE t2} 1
test_expr expr-5.6b {t1='abxyzzyc', t2='A%C'} {t1 LIKE t2} $NCSL
test_expr expr-5.7a {t1='abxyzzy', t2='a%c'} {t1 LIKE t2} 0
test_expr expr-5.7b {t1='abxyzzy', t2='A%C'} {t1 LIKE t2} 0
test_expr expr-5.8a {t1='abxyzzycx', t2='a%c'} {t1 LIKE t2} 0
test_expr expr-5.8b {t1='abxyzzycy', t2='a%cx'} {t1 LIKE t2} 0
test_expr expr-5.8c {t1='abxyzzycx', t2='A%C'} {t1 LIKE t2} 0
test_expr expr-5.8d {t1='abxyzzycy', t2='A%CX'} {t1 LIKE t2} 0
test_expr expr-5.9a {t1='abc', t2='a%_c'} {t1 LIKE t2} 1
test_expr expr-5.9b {t1='ac', t2='a%_c'} {t1 LIKE t2} 0
test_expr expr-5.9c {t1='abc', t2='A%_C'} {t1 LIKE t2} $NCSL
test_expr expr-5.9d {t1='ac', t2='A%_C'} {t1 LIKE t2} 0
test_expr expr-5.10a {t1='abxyzzyc', t2='a%_c'} {t1 LIKE t2} 1
test_expr expr-5.10b {t1='abxyzzyc', t2='A%_C'} {t1 LIKE t2} $NCSL
test_expr expr-5.11 {t1='abc', t2='xyz'} {t1 NOT LIKE t2} 1
test_expr expr-5.12a {t1='abc', t2='abc'} {t1 NOT LIKE t2} 0
test_expr expr-5.12b {t1='abc', t2='ABC'} {t1 NOT LIKE t2} $CSL
test_expr expr-5.13  {t1='A'}  {t1 LIKE 'A%_'} 0
test_expr expr-5.14  {t1='AB'} {t1 LIKE 'A%b' ESCAPE 'b'} 0

# The following tests only work on versions of TCL that support Unicode
#
if {"\u1234"!="u1234"} {
  test_expr expr-5.13a "t1='a\u0080c', t2='a_c'" {t1 LIKE t2} 1
  test_expr expr-5.13b "t1='a\u0080c', t2='A_C'" {t1 LIKE t2} $NCSL
  test_expr expr-5.14a "t1='a\u07FFc', t2='a_c'" {t1 LIKE t2} 1
  test_expr expr-5.14b "t1='a\u07FFc', t2='A_C'" {t1 LIKE t2} $NCSL
  test_expr expr-5.15a "t1='a\u0800c', t2='a_c'" {t1 LIKE t2} 1
  test_expr expr-5.15b "t1='a\u0800c', t2='A_C'" {t1 LIKE t2} $NCSL
  test_expr expr-5.16a "t1='a\uFFFFc', t2='a_c'" {t1 LIKE t2} 1
  test_expr expr-5.16b "t1='a\uFFFFc', t2='A_C'" {t1 LIKE t2} $NCSL
  test_expr expr-5.17 "t1='a\u0080', t2='A__'" {t1 LIKE t2} 0
  test_expr expr-5.18 "t1='a\u07FF', t2='A__'" {t1 LIKE t2} 0
  test_expr expr-5.19 "t1='a\u0800', t2='A__'" {t1 LIKE t2} 0
  test_expr expr-5.20 "t1='a\uFFFF', t2='A__'" {t1 LIKE t2} 0
  test_expr expr-5.21a "t1='ax\uABCD', t2='a_\uABCD'" {t1 LIKE t2} 1
  test_expr expr-5.21b "t1='ax\uABCD', t2='A_\uABCD'" {t1 LIKE t2} $NCSL
  test_expr expr-5.22a "t1='ax\u1234', t2='a%\u1234'" {t1 LIKE t2} 1
  test_expr expr-5.22b "t1='ax\u1234', t2='A%\u1234'" {t1 LIKE t2} $NCSL
  test_expr expr-5.23a "t1='ax\uFEDC', t2='a_%'" {t1 LIKE t2} 1
  test_expr expr-5.23b "t1='ax\uFEDC', t2='A_%'" {t1 LIKE t2} $NCSL
  test_expr expr-5.24a "t1='ax\uFEDCy\uFEDC', t2='a%\uFEDC'" {t1 LIKE t2} 1
  test_expr expr-5.24b "t1='ax\uFEDCy\uFEDC', t2='A%\uFEDC'" {t1 LIKE t2} $NCSL
}

test_expr expr-5.54 {t1='abc', t2=NULL} {t1 LIKE t2} {{}}
test_expr expr-5.55 {t1='abc', t2=NULL} {t1 NOT LIKE t2} {{}}
test_expr expr-5.56 {t1='abc', t2=NULL} {t2 LIKE t1} {{}}
test_expr expr-5.57 {t1='abc', t2=NULL} {t2 NOT LIKE t1} {{}}

# LIKE expressions that use ESCAPE characters.
test_expr expr-5.58a {t1='abc', t2='a_c'}   {t1 LIKE t2 ESCAPE '7'} 1
test_expr expr-5.58b {t1='abc', t2='A_C'}   {t1 LIKE t2 ESCAPE '7'} $NCSL
test_expr expr-5.59a {t1='a_c', t2='a7_c'}  {t1 LIKE t2 ESCAPE '7'} 1
test_expr expr-5.59b {t1='a_c', t2='A7_C'}  {t1 LIKE t2 ESCAPE '7'} $NCSL
test_expr expr-5.60a {t1='abc', t2='a7_c'}  {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.60b {t1='abc', t2='A7_C'}  {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.61a {t1='a7Xc', t2='a7_c'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.61b {t1='a7Xc', t2='A7_C'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.62a {t1='abcde', t2='a%e'} {t1 LIKE t2 ESCAPE '7'} 1
test_expr expr-5.62b {t1='abcde', t2='A%E'} {t1 LIKE t2 ESCAPE '7'} $NCSL
test_expr expr-5.63a {t1='abcde', t2='a7%e'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.63b {t1='abcde', t2='A7%E'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.64a {t1='a7cde', t2='a7%e'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.64b {t1='a7cde', t2='A7%E'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.65a {t1='a7cde', t2='a77%e'} {t1 LIKE t2 ESCAPE '7'} 1
test_expr expr-5.65b {t1='a7cde', t2='A77%E'} {t1 LIKE t2 ESCAPE '7'} $NCSL
test_expr expr-5.66a {t1='abc7', t2='a%77'} {t1 LIKE t2 ESCAPE '7'} 1
test_expr expr-5.66b {t1='abc7', t2='A%77'} {t1 LIKE t2 ESCAPE '7'} $NCSL
test_expr expr-5.67a {t1='abc_', t2='a%7_'} {t1 LIKE t2 ESCAPE '7'} 1
test_expr expr-5.67b {t1='abc_', t2='A%7_'} {t1 LIKE t2 ESCAPE '7'} $NCSL
test_expr expr-5.68a {t1='abc7', t2='a%7_'} {t1 LIKE t2 ESCAPE '7'} 0
test_expr expr-5.68b {t1='abc7', t2='A%7_'} {t1 LIKE t2 ESCAPE '7'} 0

# These are the same test as the block above, but using a multi-byte 
# character as the escape character.
if {"\u1234"!="u1234"} {
  test_expr expr-5.69a "t1='abc', t2='a_c'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 1
  test_expr expr-5.69b "t1='abc', t2='A_C'" \
      "t1 LIKE t2 ESCAPE '\u1234'" $NCSL
  test_expr expr-5.70a "t1='a_c', t2='a\u1234_c'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 1
  test_expr expr-5.70b "t1='a_c', t2='A\u1234_C'" \
      "t1 LIKE t2 ESCAPE '\u1234'" $NCSL
  test_expr expr-5.71a "t1='abc', t2='a\u1234_c'" \
       "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.71b "t1='abc', t2='A\u1234_C'" \
       "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.72a "t1='a\u1234Xc', t2='a\u1234_c'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.72b "t1='a\u1234Xc', t2='A\u1234_C'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.73a "t1='abcde', t2='a%e'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 1
  test_expr expr-5.73b "t1='abcde', t2='A%E'" \
      "t1 LIKE t2 ESCAPE '\u1234'" $NCSL
  test_expr expr-5.74a "t1='abcde', t2='a\u1234%e'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.74b "t1='abcde', t2='A\u1234%E'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.75a "t1='a\u1234cde', t2='a\u1234%e'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.75b "t1='a\u1234cde', t2='A\u1234%E'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.76a "t1='a\u1234cde', t2='a\u1234\u1234%e'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 1
  test_expr expr-5.76b "t1='a\u1234cde', t2='A\u1234\u1234%E'" \
      "t1 LIKE t2 ESCAPE '\u1234'" $NCSL
  test_expr expr-5.77a "t1='abc\u1234', t2='a%\u1234\u1234'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 1
  test_expr expr-5.77b "t1='abc\u1234', t2='A%\u1234\u1234'" \
      "t1 LIKE t2 ESCAPE '\u1234'" $NCSL
  test_expr expr-5.78a "t1='abc_', t2='a%\u1234_'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 1
  test_expr expr-5.78b "t1='abc_', t2='A%\u1234_'" \
      "t1 LIKE t2 ESCAPE '\u1234'" $NCSL
  test_expr expr-5.79a "t1='abc\u1234', t2='a%\u1234_'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
  test_expr expr-5.79b "t1='abc\u1234', t2='A%\u1234_'" \
      "t1 LIKE t2 ESCAPE '\u1234'" 0
}

test_expr expr-6.1 {t1='abc', t2='xyz'} {t1 GLOB t2} 0
test_expr expr-6.2 {t1='abc', t2='ABC'} {t1 GLOB t2} 0
test_expr expr-6.3 {t1='abc', t2='A?C'} {t1 GLOB t2} 0
test_expr expr-6.4 {t1='abc', t2='a?c'} {t1 GLOB t2} 1
test_expr expr-6.5 {t1='abc', t2='abc?'} {t1 GLOB t2} 0
test_expr expr-6.6 {t1='abc', t2='A*C'} {t1 GLOB t2} 0
test_expr expr-6.7 {t1='abc', t2='a*c'} {t1 GLOB t2} 1
test_expr expr-6.8 {t1='abxyzzyc', t2='a*c'} {t1 GLOB t2} 1
test_expr expr-6.9 {t1='abxyzzy', t2='a*c'} {t1 GLOB t2} 0
test_expr expr-6.10 {t1='abxyzzycx', t2='a*c'} {t1 GLOB t2} 0
test_expr expr-6.11 {t1='abc', t2='xyz'} {t1 NOT GLOB t2} 1
test_expr expr-6.12 {t1='abc', t2='abc'} {t1 NOT GLOB t2} 0
test_expr expr-6.13 {t1='abc', t2='a[bx]c'} {t1 GLOB t2} 1
test_expr expr-6.14 {t1='abc', t2='a[cx]c'} {t1 GLOB t2} 0
test_expr expr-6.15 {t1='abc', t2='a[a-d]c'} {t1 GLOB t2} 1
test_expr expr-6.16 {t1='abc', t2='a[^a-d]c'} {t1 GLOB t2} 0
test_expr expr-6.17 {t1='abc', t2='a[A-Dc]c'} {t1 GLOB t2} 0
test_expr expr-6.18 {t1='abc', t2='a[^A-Dc]c'} {t1 GLOB t2} 1
test_expr expr-6.19 {t1='abc', t2='a[]b]c'} {t1 GLOB t2} 1
test_expr expr-6.20 {t1='abc', t2='a[^]b]c'} {t1 GLOB t2} 0
test_expr expr-6.21a {t1='abcdefg', t2='a*[de]g'} {t1 GLOB t2} 0
test_expr expr-6.21b {t1='abcdefg', t2='a*[df]g'} {t1 GLOB t2} 1
test_expr expr-6.21c {t1='abcdefg', t2='a*[d-h]g'} {t1 GLOB t2} 1
test_expr expr-6.21d {t1='abcdefg', t2='a*[b-e]g'} {t1 GLOB t2} 0
test_expr expr-6.22a {t1='abcdefg', t2='a*[^de]g'} {t1 GLOB t2} 1
test_expr expr-6.22b {t1='abcdefg', t2='a*[^def]g'} {t1 GLOB t2} 0
test_expr expr-6.23 {t1='abcdefg', t2='a*?g'} {t1 GLOB t2} 1
test_expr expr-6.24 {t1='ac', t2='a*c'} {t1 GLOB t2} 1
test_expr expr-6.25 {t1='ac', t2='a*?c'} {t1 GLOB t2} 0
test_expr expr-6.26 {t1='a*c', t2='a[*]c'} {t1 GLOB t2} 1
test_expr expr-6.27 {t1='a?c', t2='a[?]c'} {t1 GLOB t2} 1
test_expr expr-6.28 {t1='a[c', t2='a[[]c'} {t1 GLOB t2} 1


# These tests only work on versions of TCL that support Unicode
#
if {"\u1234"!="u1234"} {
  test_expr expr-6.26 "t1='a\u0080c', t2='a?c'" {t1 GLOB t2} 1
  test_expr expr-6.27 "t1='a\u07ffc', t2='a?c'" {t1 GLOB t2} 1
  test_expr expr-6.28 "t1='a\u0800c', t2='a?c'" {t1 GLOB t2} 1
  test_expr expr-6.29 "t1='a\uffffc', t2='a?c'" {t1 GLOB t2} 1
  test_expr expr-6.30 "t1='a\u1234', t2='a?'" {t1 GLOB t2} 1
  test_expr expr-6.31 "t1='a\u1234', t2='a??'" {t1 GLOB t2} 0
  test_expr expr-6.32 "t1='ax\u1234', t2='a?\u1234'" {t1 GLOB t2} 1
  test_expr expr-6.33 "t1='ax\u1234', t2='a*\u1234'" {t1 GLOB t2} 1
  test_expr expr-6.34 "t1='ax\u1234y\u1234', t2='a*\u1234'" {t1 GLOB t2} 1
  test_expr expr-6.35 "t1='a\u1234b', t2='a\[x\u1234y\]b'" {t1 GLOB t2} 1
  test_expr expr-6.36 "t1='a\u1234b', t2='a\[\u1233-\u1235\]b'" {t1 GLOB t2} 1
  test_expr expr-6.37 "t1='a\u1234b', t2='a\[\u1234-\u124f\]b'" {t1 GLOB t2} 1
  test_expr expr-6.38 "t1='a\u1234b', t2='a\[\u1235-\u124f\]b'" {t1 GLOB t2} 0
  test_expr expr-6.39 "t1='a\u1234b', t2='a\[a-\u1235\]b'" {t1 GLOB t2} 1
  test_expr expr-6.40 "t1='a\u1234b', t2='a\[a-\u1234\]b'" {t1 GLOB t2} 1
  test_expr expr-6.41 "t1='a\u1234b', t2='a\[a-\u1233\]b'" {t1 GLOB t2} 0
}

test_expr expr-6.51 {t1='ABC', t2='xyz'} {t1 GLOB t2} 0
test_expr expr-6.52 {t1='ABC', t2='abc'} {t1 GLOB t2} 0
test_expr expr-6.53 {t1='ABC', t2='a?c'} {t1 GLOB t2} 0
test_expr expr-6.54 {t1='ABC', t2='A?C'} {t1 GLOB t2} 1
test_expr expr-6.55 {t1='ABC', t2='abc?'} {t1 GLOB t2} 0
test_expr expr-6.56 {t1='ABC', t2='a*c'} {t1 GLOB t2} 0
test_expr expr-6.57 {t1='ABC', t2='A*C'} {t1 GLOB t2} 1
test_expr expr-6.58 {t1='ABxyzzyC', t2='A*C'} {t1 GLOB t2} 1
test_expr expr-6.59 {t1='ABxyzzy', t2='A*C'} {t1 GLOB t2} 0
test_expr expr-6.60 {t1='ABxyzzyCx', t2='A*C'} {t1 GLOB t2} 0
test_expr expr-6.61 {t1='ABC', t2='xyz'} {t1 NOT GLOB t2} 1
test_expr expr-6.62 {t1='ABC', t2='ABC'} {t1 NOT GLOB t2} 0
test_expr expr-6.63 {t1='ABC', t2='A[Bx]C'} {t1 GLOB t2} 1
test_expr expr-6.64 {t1='ABC', t2='A[Cx]C'} {t1 GLOB t2} 0
test_expr expr-6.65 {t1='ABC', t2='A[A-D]C'} {t1 GLOB t2} 1
test_expr expr-6.66 {t1='ABC', t2='A[^A-D]C'} {t1 GLOB t2} 0
test_expr expr-6.67 {t1='ABC', t2='A[a-dC]C'} {t1 GLOB t2} 0
test_expr expr-6.68 {t1='ABC', t2='A[^a-dC]C'} {t1 GLOB t2} 1
test_expr expr-6.69a {t1='ABC', t2='A[]B]C'} {t1 GLOB t2} 1
test_expr expr-6.69b {t1='A]C', t2='A[]B]C'} {t1 GLOB t2} 1
test_expr expr-6.70a {t1='ABC', t2='A[^]B]C'} {t1 GLOB t2} 0
test_expr expr-6.70b {t1='AxC', t2='A[^]B]C'} {t1 GLOB t2} 1
test_expr expr-6.70c {t1='A]C', t2='A[^]B]C'} {t1 GLOB t2} 0
test_expr expr-6.71 {t1='ABCDEFG', t2='A*[DE]G'} {t1 GLOB t2} 0
test_expr expr-6.72 {t1='ABCDEFG', t2='A*[^DE]G'} {t1 GLOB t2} 1
test_expr expr-6.73 {t1='ABCDEFG', t2='A*?G'} {t1 GLOB t2} 1
test_expr expr-6.74 {t1='AC', t2='A*C'} {t1 GLOB t2} 1
test_expr expr-6.75 {t1='AC', t2='A*?C'} {t1 GLOB t2} 0

test_expr expr-6.63 {t1=NULL, t2='a*?c'} {t1 GLOB t2} {{}}
test_expr expr-6.64 {t1='ac', t2=NULL} {t1 GLOB t2} {{}}
test_expr expr-6.65 {t1=NULL, t2='a*?c'} {t1 NOT GLOB t2} {{}}
test_expr expr-6.66 {t1='ac', t2=NULL} {t1 NOT GLOB t2} {{}}

# Check that the affinity of a CAST expression is calculated correctly.
ifcapable cast {
  test_expr expr-6.67 {t1='01', t2=1} {t1 = t2} 0
  test_expr expr-6.68 {t1='1', t2=1} {t1 = t2} 1
  test_expr expr-6.69 {t1='01', t2=1} {CAST(t1 AS INTEGER) = t2} 1
}

test_expr expr-case.1 {i1=1, i2=2} \
	{CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} ne
test_expr expr-case.2 {i1=2, i2=2} \
	{CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} eq
test_expr expr-case.3 {i1=NULL, i2=2} \
	{CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} ne
test_expr expr-case.4 {i1=2, i2=NULL} \
	{CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} ne
test_expr expr-case.5 {i1=2} \
	{CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'error' END} two
test_expr expr-case.6 {i1=1} \
	{CASE i1 WHEN 1 THEN 'one' WHEN NULL THEN 'two' ELSE 'error' END} one
test_expr expr-case.7 {i1=2} \
	{CASE i1 WHEN 1 THEN 'one' WHEN NULL THEN 'two' ELSE 'error' END} error
test_expr expr-case.8 {i1=3} \
	{CASE i1 WHEN 1 THEN 'one' WHEN NULL THEN 'two' ELSE 'error' END} error
test_expr expr-case.9 {i1=3} \
	{CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'error' END} error
test_expr expr-case.10 {i1=3} \
	{CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' END} {{}}
test_expr expr-case.11 {i1=null} \
	{CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 3 END} 3
test_expr expr-case.12 {i1=1} \
	{CASE i1 WHEN 1 THEN null WHEN 2 THEN 'two' ELSE 3 END} {{}}
test_expr expr-case.13 {i1=7} \
	{ CASE WHEN i1 < 5 THEN 'low' 
	       WHEN i1 < 10 THEN 'medium' 
               WHEN i1 < 15 THEN 'high' ELSE 'error' END} medium


# The sqliteExprIfFalse and sqliteExprIfTrue routines are only
# executed as part of a WHERE clause.  Create a table suitable
# for testing these functions.
#
execsql {DROP TABLE test1}
execsql {CREATE TABLE test1(a int, b int);}
for {set i 1} {$i<=20} {incr i} {
  execsql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])"
}
execsql "INSERT INTO test1 VALUES(NULL,0)"
do_test expr-7.1 {
  execsql {SELECT * FROM test1 ORDER BY a}
} {{} 0 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024 11 2048 12 4096 13 8192 14 16384 15 32768 16 65536 17 131072 18 262144 19 524288 20 1048576}

proc test_expr2 {name expr result} {
  do_test $name [format {
    execsql {SELECT a FROM test1 WHERE %s ORDER BY a}
  } $expr] $result
}

test_expr2 expr-7.2  {a<10 AND a>8}                  {9}
test_expr2 expr-7.3  {a<=10 AND a>=8}                {8 9 10}
test_expr2 expr-7.4  {a>=8 AND a<=10}                {8 9 10}
test_expr2 expr-7.5  {a>=20 OR a<=1}                 {1 20}
test_expr2 expr-7.6  {b!=4 AND a<=3}                 {1 3}
test_expr2 expr-7.7  {b==8 OR b==16 OR b==32}        {3 4 5}
test_expr2 expr-7.8  {NOT b<>8 OR b==1024}           {3 10}
test_expr2 expr-7.9  {b LIKE '10%'}                  {10 20}
test_expr2 expr-7.10 {b LIKE '_4'}                   {6}
test_expr2 expr-7.11 {a GLOB '1?'}            {10 11 12 13 14 15 16 17 18 19}
test_expr2 expr-7.12 {b GLOB '1*4'}                  {10 14}
test_expr2 expr-7.13 {b GLOB '*1[456]'}              {4}
test_expr2 expr-7.14 {a ISNULL}                      {{}}
test_expr2 expr-7.15 {a NOTNULL AND a<3}             {1 2}
test_expr2 expr-7.16 {a AND a<3}                     {1 2}
test_expr2 expr-7.17 {NOT a}                         {}
test_expr2 expr-7.18 {a==11 OR (b>1000 AND b<2000)}  {10 11}
test_expr2 expr-7.19 {a<=1 OR a>=20}                 {1 20}
test_expr2 expr-7.20 {a<1 OR a>20}                   {}
test_expr2 expr-7.21 {a>19 OR a<1}                   {20}
test_expr2 expr-7.22 {a!=1 OR a=100} \
                         {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20}
test_expr2 expr-7.23 {(a notnull AND a<4) OR a==8}   {1 2 3 8}
test_expr2 expr-7.24 {a LIKE '2_' OR a==8}           {8 20}
test_expr2 expr-7.25 {a GLOB '2?' OR a==8}           {8 20}
test_expr2 expr-7.26 {a isnull OR a=8}               {{} 8}
test_expr2 expr-7.27 {a notnull OR a=8} \
                          {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20}
test_expr2 expr-7.28 {a<0 OR b=0} {{}}
test_expr2 expr-7.29 {b=0 OR a<0} {{}}
test_expr2 expr-7.30 {a<0 AND b=0} {}
test_expr2 expr-7.31 {b=0 AND a<0} {}
test_expr2 expr-7.32 {a IS NULL AND (a<0 OR b=0)} {{}}
test_expr2 expr-7.33 {a IS NULL AND (b=0 OR a<0)} {{}}
test_expr2 expr-7.34 {a IS NULL AND (a<0 AND b=0)} {}
test_expr2 expr-7.35 {a IS NULL AND (b=0 AND a<0)} {}
test_expr2 expr-7.32 {(a<0 OR b=0) AND a IS NULL} {{}}
test_expr2 expr-7.33 {(b=0 OR a<0) AND a IS NULL} {{}}
test_expr2 expr-7.34 {(a<0 AND b=0) AND a IS NULL} {}
test_expr2 expr-7.35 {(b=0 AND a<0) AND a IS NULL} {}
test_expr2 expr-7.36 {a<2 OR (a<0 OR b=0)} {{} 1}
test_expr2 expr-7.37 {a<2 OR (b=0 OR a<0)} {{} 1}
test_expr2 expr-7.38 {a<2 OR (a<0 AND b=0)} {1}
test_expr2 expr-7.39 {a<2 OR (b=0 AND a<0)} {1}
ifcapable floatingpoint {
  test_expr2 expr-7.40 {((a<2 OR a IS NULL) AND b<3) OR b>1e10} {{} 1}
}
test_expr2 expr-7.41 {a BETWEEN -1 AND 1} {1}
test_expr2 expr-7.42 {a NOT BETWEEN 2 AND 100} {1}
test_expr2 expr-7.43 {(b+1234)||'this is a string that is at least 32 characters long' BETWEEN 1 AND 2} {}
test_expr2 expr-7.44 {123||'xabcdefghijklmnopqrstuvwyxz01234567890'||a BETWEEN '123a' AND '123b'} {}
test_expr2 expr-7.45 {((123||'xabcdefghijklmnopqrstuvwyxz01234567890'||a) BETWEEN '123a' AND '123b')<0} {}
test_expr2 expr-7.46 {((123||'xabcdefghijklmnopqrstuvwyxz01234567890'||a) BETWEEN '123a' AND '123z')>0} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20}

test_expr2 expr-7.50 {((a between 1 and 2 OR 0) AND 1) OR 0} {1 2}
test_expr2 expr-7.51 {((a not between 3 and 100 OR 0) AND 1) OR 0} {1 2}

ifcapable subquery {
  test_expr2 expr-7.52 {((a in (1,2) OR 0) AND 1) OR 0} {1 2}
  test_expr2 expr-7.53 \
      {((a not in (3,4,5,6,7,8,9,10) OR 0) AND a<11) OR 0} {1 2}
}
test_expr2 expr-7.54 {((a>0 OR 0) AND a<3) OR 0} {1 2}
ifcapable subquery {
  test_expr2 expr-7.55 {((a in (1,2) OR 0) IS NULL AND 1) OR 0} {{}}
  test_expr2 expr-7.56 \
      {((a not in (3,4,5,6,7,8,9,10) IS NULL OR 0) AND 1) OR 0} {{}}
}
test_expr2 expr-7.57 {((a>0 IS NULL OR 0) AND 1) OR 0} {{}}

test_expr2 expr-7.58  {(a||'')<='1'}                  {1}

test_expr2 expr-7.59 {LIKE('10%',b)}                  {10 20}
test_expr2 expr-7.60 {LIKE('_4',b)}                   {6}
test_expr2 expr-7.61 {GLOB('1?',a)}            {10 11 12 13 14 15 16 17 18 19}
test_expr2 expr-7.62 {GLOB('1*4',b)}                  {10 14}
test_expr2 expr-7.63 {GLOB('*1[456]',b)}              {4}
test_expr2 expr-7.64 {b = abs(-2)}                    {1}
test_expr2 expr-7.65 {b = abs(+-2)}                   {1}
test_expr2 expr-7.66 {b = abs(++-2)}                  {1}
test_expr2 expr-7.67 {b = abs(+-+-2)}                 {1}
test_expr2 expr-7.68 {b = abs(+-++-2)}                {1}
test_expr2 expr-7.69 {b = abs(++++-2)}                {1}
test_expr2 expr-7.70 {b = 5 - abs(+3)}                {1}
test_expr2 expr-7.71 {b = 5 - abs(-3)}                {1}
ifcapable floatingpoint {
  test_expr2 expr-7.72 {b = abs(-2.0)}                  {1}
}
test_expr2 expr-7.73 {b = 6 - abs(-a)}                {2}
ifcapable floatingpoint {
  test_expr2 expr-7.74 {b = abs(8.0)}                   {3}
}

# Test the CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP expressions.
#
ifcapable {floatingpoint} {
  set sqlite_current_time 1157124849
  do_test expr-8.1 {
    execsql {SELECT CURRENT_TIME}
  } {15:34:09}
  do_test expr-8.2 {
    execsql {SELECT CURRENT_DATE}
  } {2006-09-01}
  do_test expr-8.3 {
    execsql {SELECT CURRENT_TIMESTAMP}
  } {{2006-09-01 15:34:09}}
}
ifcapable datetime {
  do_test expr-8.4 {
    execsql {SELECT CURRENT_TIME==time('now');}
  } 1
  do_test expr-8.5 {
    execsql {SELECT CURRENT_DATE==date('now');}
  } 1
  do_test expr-8.6 {
    execsql {SELECT CURRENT_TIMESTAMP==datetime('now');}
  } 1
}
set sqlite_current_time 0

ifcapable floatingpoint {
  do_test expr-9.1 {
    execsql {SELECT round(-('-'||'123'))}
  } 123.0
}

# Test an error message that can be generated by the LIKE expression
do_test expr-10.1 {
  catchsql {SELECT 'abc' LIKE 'abc' ESCAPE ''}
} {1 {ESCAPE expression must be a single character}}
do_test expr-10.2 {
  catchsql {SELECT 'abc' LIKE 'abc' ESCAPE 'ab'}
} {1 {ESCAPE expression must be a single character}}

# If we specify an integer constant that is bigger than the largest
# possible integer, code the integer as a real number.
#
do_test expr-11.1 {
  execsql {SELECT typeof(9223372036854775807)}
} {integer}
do_test expr-11.2 {
  execsql {SELECT typeof(00000009223372036854775807)}
} {integer}
do_test expr-11.3 {
  execsql {SELECT typeof(+9223372036854775807)}
} {integer}
do_test expr-11.4 {
  execsql {SELECT typeof(+000000009223372036854775807)}
} {integer}
do_test expr-11.5 {
  execsql {SELECT typeof(9223372036854775808)}
} {real}
do_test expr-11.6 {
  execsql {SELECT typeof(00000009223372036854775808)}
} {real}
do_test expr-11.7 {
  execsql {SELECT typeof(+9223372036854775808)}
} {real}
do_test expr-11.8 {
  execsql {SELECT typeof(+0000009223372036854775808)}
} {real}
do_test expr-11.11 {
  execsql {SELECT typeof(-9223372036854775808)}
} {integer}
do_test expr-11.12 {
  execsql {SELECT typeof(-00000009223372036854775808)}
} {integer}
ifcapable floatingpoint {
  do_test expr-11.13 {
    execsql {SELECT typeof(-9223372036854775809)}
  } {real}
  do_test expr-11.14 {
    execsql {SELECT typeof(-00000009223372036854775809)}
  } {real}
}

# These two statements used to leak memory (because of missing %destructor
# directives in parse.y).
do_test expr-12.1 {
  catchsql {
    SELECT (CASE a>4 THEN 1 ELSE 0 END) FROM test1;
  }
} {1 {near "THEN": syntax error}}
do_test expr-12.2 {
  catchsql {
    SELECT (CASE WHEN a>4 THEN 1 ELSE 0) FROM test1;
  }
} {1 {near ")": syntax error}}

ifcapable floatingpoint {
  do_test expr-13.1 {
    execsql {
      SELECT 12345678901234567890;
    }
  } {1.23456789012346e+19}
}

# Implicit String->Integer conversion is used when possible.
#
if {[working_64bit_int]} {
  do_test expr-13.2 {
    execsql {
      SELECT 0+'9223372036854775807'
    }
  } {9223372036854775807}
  do_test expr-13.3 {
    execsql {
      SELECT '9223372036854775807'+0
    }
  } {9223372036854775807}
}

# If the value is too large, use String->Float conversion.
#
ifcapable floatingpoint {
  do_test expr-13.4 {
    execsql {
      SELECT 0+'9223372036854775808'
    }
  } {9.22337203685478e+18}
  do_test expr-13.5 {
    execsql {
      SELECT '9223372036854775808'+0
    }
  } {9.22337203685478e+18}
}

# Use String->float conversion if the value is explicitly a floating
# point value.
#
do_test expr-13.6 {
  execsql {
    SELECT 0+'9223372036854775807.0'
  }
} {9.22337203685478e+18}
do_test expr-13.7 {
  execsql {
    SELECT '9223372036854775807.0'+0
  }
} {9.22337203685478e+18}


finish_test

Added test/filectrl.test.



















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 2008 Jan 22
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: filectrl.test,v 1.2 2008/11/21 00:10:35 aswift Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


do_test filectrl-1.1 {
  file_control_test db
} {}
do_test filectrl-1.2 {
  db eval {CREATE TEMP TABLE x(y);}
  file_control_test db
} {}
do_test filectrl-1.3 {
  db close
  sqlite3 db :memory:
  file_control_test db
} {}
do_test filectrl-1.4 {
  sqlite3 db test.db
  file_control_lasterrno_test db
} {}
do_test filectrl-1.5 {
  db close
  sqlite3 db test_control_lockproxy.db
  file_control_lockproxy_test db
} {}
db close
file delete -force .test_control_lockproxy.db-conch test.proxy
finish_test

Added test/filefmt.test.







































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# 2007 April 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify database file format.
#
# $Id: filefmt.test,v 1.3 2009/06/18 11:34:43 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close
file delete -force test.db test.db-journal

# Database begins with valid 16-byte header string.
#
do_test filefmt-1.1 {
  sqlite3 db test.db
  db eval {CREATE TABLE t1(x)}
  db close
  hexio_read test.db 0 16
} {53514C69746520666F726D6174203300}

# If the 16-byte header is changed, the file will not open
#
do_test filefmt-1.2 {
  hexio_write test.db 0 54
  set x [catch {sqlite3 db test.db} err]
  lappend x $err
} {0 {}}
do_test filefmt-1.3 {
  catchsql {
    SELECT count(*) FROM sqlite_master
  }
} {1 {file is encrypted or is not a database}}
do_test filefmt-1.4 {
  db close
  hexio_write test.db 0 53
  sqlite3 db test.db
  catchsql {
    SELECT count(*) FROM sqlite_master
  }
} {0 1}

# The page-size is stored at offset 16
#
ifcapable pager_pragmas {
  foreach pagesize {512 1024 2048 4096 8192 16384 32768} {
     if {[info exists SQLITE_MAX_PAGE_SIZE]
          && $pagesize>$SQLITE_MAX_PAGE_SIZE} continue
     do_test filefmt-1.5.$pagesize.1 {
       db close
       file delete -force test.db
       sqlite3 db test.db
       db eval "PRAGMA auto_vacuum=OFF"
       db eval "PRAGMA page_size=$pagesize"
       db eval {CREATE TABLE t1(x)}
       file size test.db
     } [expr $pagesize*2]
     do_test filefmt-1.5.$pagesize.2 {
       hexio_get_int [hexio_read test.db 16 2]
     } $pagesize
  }
}

# The page-size must be a power of 2
#
do_test filefmt-1.6 {
  db close
  hexio_write test.db 16 [hexio_render_int16 1025]
  sqlite3 db test.db
  catchsql {
     SELECT count(*) FROM sqlite_master
  }
} {1 {file is encrypted or is not a database}}


# The page-size must be at least 512 bytes
#
do_test filefmt-1.7 {
  db close
  hexio_write test.db 16 [hexio_render_int16 256]
  sqlite3 db test.db
  catchsql {
     SELECT count(*) FROM sqlite_master
  }
} {1 {file is encrypted or is not a database}}

# Usable space per page (page-size minus unused space per page)
# must be at least 480 bytes
#
ifcapable pager_pragmas {
  do_test filefmt-1.8 {
    db close
    file delete -force test.db
    sqlite3 db test.db
    db eval {PRAGMA page_size=512; CREATE TABLE t1(x)}
    db close
    hexio_write test.db 20 21
    sqlite3 db test.db
    catchsql {
       SELECT count(*) FROM sqlite_master
    }
  } {1 {file is encrypted or is not a database}}
}


finish_test

Added test/fkey1.test.



















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for foreign keys.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!foreignkey} {
  finish_test
  return
}

# Create a table and some data to work with.
#
do_test fkey1-1.0 {
  execsql {
    CREATE TABLE t1(
      a INTEGER PRIMARY KEY,
      b INTEGER
           REFERENCES t1 ON DELETE CASCADE
           REFERENCES t2,
      c TEXT,
      FOREIGN KEY (b,c) REFERENCES t2(x,y) ON UPDATE CASCADE
    );
  }
} {}
do_test fkey1-1.1 {
  execsql {
    CREATE TABLE t2(
      x INTEGER PRIMARY KEY,
      y TEXT
    );
  }
} {}
do_test fkey1-1.2 {
  execsql {
    CREATE TABLE t3(
      a INTEGER REFERENCES t2,
      b INTEGER REFERENCES t1,
      FOREIGN KEY (a,b) REFERENCES t2(x,y)
    );
  }
} {}

do_test fkey1-2.1 {
  execsql {
    CREATE TABLE t4(a integer primary key);
    CREATE TABLE t5(x references t4);
    CREATE TABLE t6(x references t4);
    CREATE TABLE t7(x references t4);
    CREATE TABLE t8(x references t4);
    CREATE TABLE t9(x references t4);
    CREATE TABLE t10(x references t4);
    DROP TABLE t7;
    DROP TABLE t9;
    DROP TABLE t5;
    DROP TABLE t8;
    DROP TABLE t6;
    DROP TABLE t10;
  }
} {}

do_test fkey1-3.1 {
  execsql {
    CREATE TABLE t5(a PRIMARY KEY, b, c);
    CREATE TABLE t6(
      d REFERENCES t5,
      e REFERENCES t5(c)
    );
    PRAGMA foreign_key_list(t6);
  }
} [concat                                         \
  {0 0 t5 e c {NO ACTION} {NO ACTION} NONE}       \
  {1 0 t5 d {} {NO ACTION} {NO ACTION} NONE}      \
]
do_test fkey1-3.2 {
  execsql {
    CREATE TABLE t7(d, e, f,
      FOREIGN KEY (d, e) REFERENCES t5(a, b)
    );
    PRAGMA foreign_key_list(t7);
  }
} [concat                                   \
  {0 0 t5 d a {NO ACTION} {NO ACTION} NONE} \
  {0 1 t5 e b {NO ACTION} {NO ACTION} NONE} \
]
do_test fkey1-3.3 {
  execsql {
    CREATE TABLE t8(d, e, f,
      FOREIGN KEY (d, e) REFERENCES t5 ON DELETE CASCADE ON UPDATE SET NULL
    );
    PRAGMA foreign_key_list(t8);
  }
} [concat                        \
  {0 0 t5 d {} {SET NULL} CASCADE NONE} \
  {0 1 t5 e {} {SET NULL} CASCADE NONE} \
]
do_test fkey1-3.4 {
  execsql {
    CREATE TABLE t9(d, e, f,
      FOREIGN KEY (d, e) REFERENCES t5 ON DELETE CASCADE ON UPDATE SET DEFAULT
    );
    PRAGMA foreign_key_list(t9);
  }
} [concat                        \
  {0 0 t5 d {} {SET DEFAULT} CASCADE NONE} \
  {0 1 t5 e {} {SET DEFAULT} CASCADE NONE} \
]

finish_test

Added test/fkey2.test.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
# 2009 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for foreign keys.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!foreignkey||!trigger} {
  finish_test
  return
}

#-------------------------------------------------------------------------
# Test structure:
#
# fkey2-1.*: Simple tests to check that immediate and deferred foreign key 
#            constraints work when not inside a transaction.
#            
# fkey2-2.*: Tests to verify that deferred foreign keys work inside
#            explicit transactions (i.e that processing really is deferred).
#
# fkey2-3.*: Tests that a statement transaction is rolled back if an
#            immediate foreign key constraint is violated.
#
# fkey2-4.*: Test that FK actions may recurse even when recursive triggers
#            are disabled.
#
# fkey2-5.*: Check that if foreign-keys are enabled, it is not possible
#            to write to an FK column using the incremental blob API.
#
# fkey2-6.*: Test that FK processing is automatically disabled when 
#            running VACUUM.
#
# fkey2-7.*: Test using an IPK as the key in the child (referencing) table.
#
# fkey2-8.*: Test that enabling/disabling foreign key support while a 
#            transaction is active is not possible.
#
# fkey2-9.*: Test SET DEFAULT actions.
#
# fkey2-10.*: Test errors.
#
# fkey2-11.*: Test CASCADE actions.
#
# fkey2-12.*: Test RESTRICT actions.
#
# fkey2-13.*: Test that FK processing is performed when a row is REPLACED by
#             an UPDATE or INSERT statement.
#
# fkey2-14.*: Test the ALTER TABLE and DROP TABLE commands.
#
# fkey2-15.*: Test that if there are no (known) outstanding foreign key 
#             constraint violations in the database, inserting into a parent
#             table or deleting from a child table does not cause SQLite
#             to check if this has repaired an outstanding violation.
#
# fkey2-16.*: Test that rows that refer to themselves may be inserted, 
#             updated and deleted.
#
# fkey2-17.*: Test that the "count_changes" pragma does not interfere with
#             FK constraint processing.
# 
# fkey2-18.*: Test that the authorization callback is invoked when processing
#             FK constraints.
#
# fkey2-genfkey.*: Tests that were used with the shell tool .genfkey
#            command. Recycled to test the built-in implementation.
#


execsql { PRAGMA foreign_keys = on }

set FkeySimpleSchema {
  PRAGMA foreign_keys = on;
  CREATE TABLE t1(a PRIMARY KEY, b);
  CREATE TABLE t2(c REFERENCES t1(a) /D/ , d);

  CREATE TABLE t3(a PRIMARY KEY, b);
  CREATE TABLE t4(c REFERENCES t3 /D/, d);

  CREATE TABLE t7(a, b INTEGER PRIMARY KEY);
  CREATE TABLE t8(c REFERENCES t7 /D/, d);

  CREATE TABLE t9(a REFERENCES nosuchtable, b);
  CREATE TABLE t10(a REFERENCES t9(c) /D/, b);
}


set FkeySimpleTests {
  1.1  "INSERT INTO t2 VALUES(1, 3)"      {1 {foreign key constraint failed}}
  1.2  "INSERT INTO t1 VALUES(1, 2)"      {0 {}}
  1.3  "INSERT INTO t2 VALUES(1, 3)"      {0 {}}
  1.4  "INSERT INTO t2 VALUES(2, 4)"      {1 {foreign key constraint failed}}
  1.5  "INSERT INTO t2 VALUES(NULL, 4)"   {0 {}}
  1.6  "UPDATE t2 SET c=2 WHERE d=4"      {1 {foreign key constraint failed}}
  1.7  "UPDATE t2 SET c=1 WHERE d=4"      {0 {}}
  1.9  "UPDATE t2 SET c=1 WHERE d=4"      {0 {}}
  1.10 "UPDATE t2 SET c=NULL WHERE d=4"   {0 {}}
  1.11 "DELETE FROM t1 WHERE a=1"         {1 {foreign key constraint failed}}
  1.12 "UPDATE t1 SET a = 2"              {1 {foreign key constraint failed}}
  1.13 "UPDATE t1 SET a = 1"              {0 {}}

  2.1  "INSERT INTO t4 VALUES(1, 3)"      {1 {foreign key constraint failed}}
  2.2  "INSERT INTO t3 VALUES(1, 2)"      {0 {}}
  2.3  "INSERT INTO t4 VALUES(1, 3)"      {0 {}}

  4.1  "INSERT INTO t8 VALUES(1, 3)"      {1 {foreign key constraint failed}}
  4.2  "INSERT INTO t7 VALUES(2, 1)"      {0 {}}
  4.3  "INSERT INTO t8 VALUES(1, 3)"      {0 {}}
  4.4  "INSERT INTO t8 VALUES(2, 4)"      {1 {foreign key constraint failed}}
  4.5  "INSERT INTO t8 VALUES(NULL, 4)"   {0 {}}
  4.6  "UPDATE t8 SET c=2 WHERE d=4"      {1 {foreign key constraint failed}}
  4.7  "UPDATE t8 SET c=1 WHERE d=4"      {0 {}}
  4.9  "UPDATE t8 SET c=1 WHERE d=4"      {0 {}}
  4.10 "UPDATE t8 SET c=NULL WHERE d=4"   {0 {}}
  4.11 "DELETE FROM t7 WHERE b=1"         {1 {foreign key constraint failed}}
  4.12 "UPDATE t7 SET b = 2"              {1 {foreign key constraint failed}}
  4.13 "UPDATE t7 SET b = 1"              {0 {}}
  4.14 "INSERT INTO t8 VALUES('a', 'b')"  {1 {foreign key constraint failed}}
  4.15 "UPDATE t7 SET b = 5"              {1 {foreign key constraint failed}}
  4.16 "UPDATE t7 SET rowid = 5"          {1 {foreign key constraint failed}}
  4.17 "UPDATE t7 SET a = 10"             {0 {}}

  5.1  "INSERT INTO t9 VALUES(1, 3)"      {1 {no such table: main.nosuchtable}}
  5.2  "INSERT INTO t10 VALUES(1, 3)"     {1 {foreign key mismatch}}
}

do_test fkey2-1.1.0 {
  execsql [string map {/D/ {}} $FkeySimpleSchema]
} {}
foreach {tn zSql res} $FkeySimpleTests {
  do_test fkey2-1.1.$tn { catchsql $zSql } $res
}
drop_all_tables

do_test fkey2-1.2.0 {
  execsql [string map {/D/ {DEFERRABLE INITIALLY DEFERRED}} $FkeySimpleSchema]
} {}
foreach {tn zSql res} $FkeySimpleTests {
  do_test fkey2-1.2.$tn { catchsql $zSql } $res
}
drop_all_tables

do_test fkey2-1.3.0 {
  execsql [string map {/D/ {}} $FkeySimpleSchema]
  execsql { PRAGMA count_changes = 1 }
} {}
foreach {tn zSql res} $FkeySimpleTests {
  if {$res == "0 {}"} { set res {0 1} }
  do_test fkey2-1.3.$tn { catchsql $zSql } $res
}
execsql { PRAGMA count_changes = 0 }
drop_all_tables

do_test fkey2-1.4.0 {
  execsql [string map {/D/ {}} $FkeySimpleSchema]
  execsql { PRAGMA count_changes = 1 }
} {}
foreach {tn zSql res} $FkeySimpleTests {
  if {$res == "0 {}"} { set res {0 1} }
  execsql BEGIN
  do_test fkey2-1.4.$tn { catchsql $zSql } $res
  execsql COMMIT
}
execsql { PRAGMA count_changes = 0 }
drop_all_tables

# Special test: When the parent key is an IPK, make sure the affinity of
# the IPK is not applied to the child key value before it is inserted
# into the child table.
do_test fkey2-1.5.1 {
  execsql {
    CREATE TABLE i(i INTEGER PRIMARY KEY);
    CREATE TABLE j(j REFERENCES i);
    INSERT INTO i VALUES(35);
    INSERT INTO j VALUES('35.0');
    SELECT j, typeof(j) FROM j;
  }
} {35.0 text}
do_test fkey2-1.5.2 {
  catchsql { DELETE FROM i }
} {1 {foreign key constraint failed}}

# Same test using a regular primary key with integer affinity.
drop_all_tables
do_test fkey2-1.6.1 {
  execsql {
    CREATE TABLE i(i INT UNIQUE);
    CREATE TABLE j(j REFERENCES i(i));
    INSERT INTO i VALUES('35.0');
    INSERT INTO j VALUES('35.0');
    SELECT j, typeof(j) FROM j;
    SELECT i, typeof(i) FROM i;
  }
} {35.0 text 35 integer}
do_test fkey2-1.6.2 {
  catchsql { DELETE FROM i }
} {1 {foreign key constraint failed}}

# Use a collation sequence on the parent key.
drop_all_tables
do_test fkey2-1.7.1 {
  execsql {
    CREATE TABLE i(i TEXT COLLATE nocase PRIMARY KEY);
    CREATE TABLE j(j TEXT COLLATE binary REFERENCES i(i));
    INSERT INTO i VALUES('SQLite');
    INSERT INTO j VALUES('sqlite');
  }
  catchsql { DELETE FROM i }
} {1 {foreign key constraint failed}}

# Use the parent key collation even if it is default and the child key
# has an explicit value.
drop_all_tables
do_test fkey2-1.7.2 {
  execsql {
    CREATE TABLE i(i TEXT PRIMARY KEY);        -- Colseq is "BINARY"
    CREATE TABLE j(j TEXT COLLATE nocase REFERENCES i(i));
    INSERT INTO i VALUES('SQLite');
  }
  catchsql { INSERT INTO j VALUES('sqlite') }
} {1 {foreign key constraint failed}}
do_test fkey2-1.7.3 {
  execsql {
    INSERT INTO i VALUES('sqlite');
    INSERT INTO j VALUES('sqlite');
    DELETE FROM i WHERE i = 'SQLite';
  }
  catchsql { DELETE FROM i WHERE i = 'sqlite' }
} {1 {foreign key constraint failed}}

#-------------------------------------------------------------------------
# This section (test cases fkey2-2.*) contains tests to check that the
# deferred foreign key constraint logic works.
#
proc fkey2-2-test {tn nocommit sql {res {}}} {
  if {$res eq "FKV"} {
    set expected {1 {foreign key constraint failed}}
  } else {
    set expected [list 0 $res]
  }
  do_test fkey2-2.$tn [list catchsql $sql] $expected
  if {$nocommit} {
    do_test fkey2-2.${tn}c {
      catchsql COMMIT
    } {1 {foreign key constraint failed}}
  }
}

fkey2-2-test 1 0 {
  CREATE TABLE node(
    nodeid PRIMARY KEY,
    parent REFERENCES node DEFERRABLE INITIALLY DEFERRED
  );
  CREATE TABLE leaf(
    cellid PRIMARY KEY,
    parent REFERENCES node DEFERRABLE INITIALLY DEFERRED
  );
}

fkey2-2-test 1  0 "INSERT INTO node VALUES(1, 0)"       FKV
fkey2-2-test 2  0 "BEGIN"
fkey2-2-test 3  1   "INSERT INTO node VALUES(1, 0)"
fkey2-2-test 4  0   "UPDATE node SET parent = NULL"
fkey2-2-test 5  0 "COMMIT"
fkey2-2-test 6  0 "SELECT * FROM node" {1 {}}

fkey2-2-test 7  0 "BEGIN"
fkey2-2-test 8  1   "INSERT INTO leaf VALUES('a', 2)"
fkey2-2-test 9  1   "INSERT INTO node VALUES(2, 0)"
fkey2-2-test 10 0   "UPDATE node SET parent = 1 WHERE nodeid = 2"
fkey2-2-test 11 0 "COMMIT"
fkey2-2-test 12 0 "SELECT * FROM node" {1 {} 2 1}
fkey2-2-test 13 0 "SELECT * FROM leaf" {a 2}

fkey2-2-test 14 0 "BEGIN"
fkey2-2-test 15 1   "DELETE FROM node WHERE nodeid = 2"
fkey2-2-test 16 0   "INSERT INTO node VALUES(2, NULL)"
fkey2-2-test 17 0 "COMMIT"
fkey2-2-test 18 0 "SELECT * FROM node" {1 {} 2 {}}
fkey2-2-test 19 0 "SELECT * FROM leaf" {a 2}

fkey2-2-test 20 0 "BEGIN"
fkey2-2-test 21 0   "INSERT INTO leaf VALUES('b', 1)"
fkey2-2-test 22 0   "SAVEPOINT save"
fkey2-2-test 23 0     "DELETE FROM node WHERE nodeid = 1"
fkey2-2-test 24 0   "ROLLBACK TO save"
fkey2-2-test 25 0 "COMMIT"
fkey2-2-test 26 0 "SELECT * FROM node" {1 {} 2 {}}
fkey2-2-test 27 0 "SELECT * FROM leaf" {a 2 b 1}

fkey2-2-test 28 0 "BEGIN"
fkey2-2-test 29 0   "INSERT INTO leaf VALUES('c', 1)"
fkey2-2-test 30 0   "SAVEPOINT save"
fkey2-2-test 31 0     "DELETE FROM node WHERE nodeid = 1"
fkey2-2-test 32 1   "RELEASE save"
fkey2-2-test 33 1   "DELETE FROM leaf WHERE cellid = 'b'"
fkey2-2-test 34 0   "DELETE FROM leaf WHERE cellid = 'c'"
fkey2-2-test 35 0 "COMMIT"
fkey2-2-test 36 0 "SELECT * FROM node" {2 {}} 
fkey2-2-test 37 0 "SELECT * FROM leaf" {a 2}

fkey2-2-test 38 0 "SAVEPOINT outer"
fkey2-2-test 39 1   "INSERT INTO leaf VALUES('d', 3)"
fkey2-2-test 40 1 "RELEASE outer"    FKV
fkey2-2-test 41 1   "INSERT INTO leaf VALUES('e', 3)"
fkey2-2-test 42 0   "INSERT INTO node VALUES(3, 2)"
fkey2-2-test 43 0 "RELEASE outer"

fkey2-2-test 44 0 "SAVEPOINT outer"
fkey2-2-test 45 1   "DELETE FROM node WHERE nodeid=3"
fkey2-2-test 47 0   "INSERT INTO node VALUES(3, 2)"
fkey2-2-test 48 0 "ROLLBACK TO outer"
fkey2-2-test 49 0 "RELEASE outer"

fkey2-2-test 50 0 "SAVEPOINT outer"
fkey2-2-test 51 1   "INSERT INTO leaf VALUES('f', 4)"
fkey2-2-test 52 1   "SAVEPOINT inner"
fkey2-2-test 53 1     "INSERT INTO leaf VALUES('g', 4)"
fkey2-2-test 54 1  "RELEASE outer"   FKV
fkey2-2-test 55 1   "ROLLBACK TO inner"
fkey2-2-test 56 0  "COMMIT"          FKV
fkey2-2-test 57 0   "INSERT INTO node VALUES(4, NULL)"
fkey2-2-test 58 0 "RELEASE outer"
fkey2-2-test 59 0 "SELECT * FROM node" {2 {} 3 2 4 {}}
fkey2-2-test 60 0 "SELECT * FROM leaf" {a 2 d 3 e 3 f 4}

# The following set of tests check that if a statement that affects 
# multiple rows violates some foreign key constraints, then strikes a 
# constraint that causes the statement-transaction to be rolled back, 
# the deferred constraint counter is correctly reset to the value it 
# had before the statement-transaction was opened.
#
fkey2-2-test 61 0 "BEGIN"
fkey2-2-test 62 0   "DELETE FROM leaf"
fkey2-2-test 63 0   "DELETE FROM node"
fkey2-2-test 64 1   "INSERT INTO leaf VALUES('a', 1)"
fkey2-2-test 65 1   "INSERT INTO leaf VALUES('b', 2)"
fkey2-2-test 66 1   "INSERT INTO leaf VALUES('c', 1)"
do_test fkey2-2-test-67 {
  catchsql          "INSERT INTO node SELECT parent, 3 FROM leaf"
} {1 {column nodeid is not unique}}
fkey2-2-test 68 0 "COMMIT"           FKV
fkey2-2-test 69 1   "INSERT INTO node VALUES(1, NULL)"
fkey2-2-test 70 0   "INSERT INTO node VALUES(2, NULL)"
fkey2-2-test 71 0 "COMMIT"

fkey2-2-test 72 0 "BEGIN"
fkey2-2-test 73 1   "DELETE FROM node"
fkey2-2-test 74 0   "INSERT INTO node(nodeid) SELECT DISTINCT parent FROM leaf"
fkey2-2-test 75 0 "COMMIT"

#-------------------------------------------------------------------------
# Test cases fkey2-3.* test that a program that executes foreign key
# actions (CASCADE, SET DEFAULT, SET NULL etc.) or tests FK constraints
# opens a statement transaction if required.
#
# fkey2-3.1.*: Test UPDATE statements.
# fkey2-3.2.*: Test DELETE statements.
#
drop_all_tables
do_test fkey2-3.1.1 {
  execsql {
    CREATE TABLE ab(a PRIMARY KEY, b);
    CREATE TABLE cd(
      c PRIMARY KEY REFERENCES ab ON UPDATE CASCADE ON DELETE CASCADE, 
      d
    );
    CREATE TABLE ef(
      e REFERENCES cd ON UPDATE CASCADE, 
      f, CHECK (e!=5)
    );
  }
} {}
do_test fkey2-3.1.2 {
  execsql {
    INSERT INTO ab VALUES(1, 'b');
    INSERT INTO cd VALUES(1, 'd');
    INSERT INTO ef VALUES(1, 'e');
  }
} {}
do_test fkey2-3.1.3 {
  catchsql { UPDATE ab SET a = 5 }
} {1 {constraint failed}}
do_test fkey2-3.1.4 {
  execsql { SELECT * FROM ab }
} {1 b}
do_test fkey2-3.1.4 {
  execsql BEGIN;
  catchsql { UPDATE ab SET a = 5 }
} {1 {constraint failed}}
do_test fkey2-3.1.5 {
  execsql COMMIT;
  execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef }
} {1 b 1 d 1 e}

do_test fkey2-3.2.1 {
  execsql BEGIN;
  catchsql { DELETE FROM ab }
} {1 {foreign key constraint failed}}
do_test fkey2-3.2.2 {
  execsql COMMIT
  execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef }
} {1 b 1 d 1 e}

#-------------------------------------------------------------------------
# Test cases fkey2-4.* test that recursive foreign key actions 
# (i.e. CASCADE) are allowed even if recursive triggers are disabled.
#
drop_all_tables
do_test fkey2-4.1 {
  execsql {
    CREATE TABLE t1(
      node PRIMARY KEY, 
      parent REFERENCES t1 ON DELETE CASCADE
    );
    CREATE TABLE t2(node PRIMARY KEY, parent);
    CREATE TRIGGER t2t AFTER DELETE ON t2 BEGIN
      DELETE FROM t2 WHERE parent = old.node;
    END;
    INSERT INTO t1 VALUES(1, NULL);
    INSERT INTO t1 VALUES(2, 1);
    INSERT INTO t1 VALUES(3, 1);
    INSERT INTO t1 VALUES(4, 2);
    INSERT INTO t1 VALUES(5, 2);
    INSERT INTO t1 VALUES(6, 3);
    INSERT INTO t1 VALUES(7, 3);
    INSERT INTO t2 SELECT * FROM t1;
  }
} {}
do_test fkey2-4.2 {
  execsql { PRAGMA recursive_triggers = off }
  execsql { 
    BEGIN;
      DELETE FROM t1 WHERE node = 1;
      SELECT node FROM t1;
  }
} {}
do_test fkey2-4.3 {
  execsql { 
      DELETE FROM t2 WHERE node = 1;
      SELECT node FROM t2;
    ROLLBACK;
  }
} {4 5 6 7}
do_test fkey2-4.4 {
  execsql { PRAGMA recursive_triggers = on }
  execsql { 
    BEGIN;
      DELETE FROM t1 WHERE node = 1;
      SELECT node FROM t1;
  }
} {}
do_test fkey2-4.3 {
  execsql { 
      DELETE FROM t2 WHERE node = 1;
      SELECT node FROM t2;
    ROLLBACK;
  }
} {}

#-------------------------------------------------------------------------
# Test cases fkey2-5.* verify that the incremental blob API may not
# write to a foreign key column while foreign-keys are enabled.
#
drop_all_tables
ifcapable incrblob {
  do_test fkey2-5.1 {
    execsql {
      CREATE TABLE t1(a PRIMARY KEY, b);
      CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1(a));
      INSERT INTO t1 VALUES('hello', 'world');
      INSERT INTO t2 VALUES('key', 'hello');
    }
  } {}
  do_test fkey2-5.2 {
    set rc [catch { set fd [db incrblob t2 b 1] } msg]
    list $rc $msg
  } {1 {cannot open foreign key column for writing}}
  do_test fkey2-5.3 {
    set rc [catch { set fd [db incrblob -readonly t2 b 1] } msg]
    close $fd
    set rc
  } {0}
  do_test fkey2-5.4 {
    execsql { PRAGMA foreign_keys = off }
    set rc [catch { set fd [db incrblob t2 b 1] } msg]
    close $fd
    set rc
  } {0}
  do_test fkey2-5.5 {
    execsql { PRAGMA foreign_keys = on }
  } {}
}

drop_all_tables
ifcapable vacuum {
  do_test fkey2-6.1 {
    execsql {
      CREATE TABLE t1(a REFERENCES t2(c), b);
      CREATE TABLE t2(c UNIQUE, b);
      INSERT INTO t2 VALUES(1, 2);
      INSERT INTO t1 VALUES(1, 2);
      VACUUM;
    }
  } {}
}

#-------------------------------------------------------------------------
# Test that it is possible to use an INTEGER PRIMARY KEY as the child key
# of a foreign constraint.
# 
drop_all_tables
do_test fkey2-7.1 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    CREATE TABLE t2(c INTEGER PRIMARY KEY REFERENCES t1, b);
  }
} {}
do_test fkey2-7.2 {
  catchsql { INSERT INTO t2 VALUES(1, 'A'); }
} {1 {foreign key constraint failed}}
do_test fkey2-7.3 {
  execsql { 
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t1 VALUES(2, 3);
    INSERT INTO t2 VALUES(1, 'A');
  }
} {}
do_test fkey2-7.4 {
  execsql { UPDATE t2 SET c = 2 }
} {}
do_test fkey2-7.5 {
  catchsql { UPDATE t2 SET c = 3 }
} {1 {foreign key constraint failed}}
do_test fkey2-7.6 {
  catchsql { DELETE FROM t1 WHERE a = 2 }
} {1 {foreign key constraint failed}}
do_test fkey2-7.7 {
  execsql { DELETE FROM t1 WHERE a = 1 }
} {}
do_test fkey2-7.8 {
  catchsql { UPDATE t1 SET a = 3 }
} {1 {foreign key constraint failed}}
do_test fkey2-7.9 {
  catchsql { UPDATE t2 SET rowid = 3 }
} {1 {foreign key constraint failed}}

#-------------------------------------------------------------------------
# Test that it is not possible to enable/disable FK support while a
# transaction is open.
# 
drop_all_tables
proc fkey2-8-test {tn zSql value} {
  do_test fkey-2.8.$tn.1 [list execsql $zSql] {}
  do_test fkey-2.8.$tn.2 { execsql "PRAGMA foreign_keys" } $value
}
fkey2-8-test  1 { PRAGMA foreign_keys = 0     } 0
fkey2-8-test  2 { PRAGMA foreign_keys = 1     } 1
fkey2-8-test  3 { BEGIN                       } 1
fkey2-8-test  4 { PRAGMA foreign_keys = 0     } 1
fkey2-8-test  5 { COMMIT                      } 1
fkey2-8-test  6 { PRAGMA foreign_keys = 0     } 0
fkey2-8-test  7 { BEGIN                       } 0
fkey2-8-test  8 { PRAGMA foreign_keys = 1     } 0
fkey2-8-test  9 { COMMIT                      } 0
fkey2-8-test 10 { PRAGMA foreign_keys = 1     } 1
fkey2-8-test 11 { PRAGMA foreign_keys = off   } 0
fkey2-8-test 12 { PRAGMA foreign_keys = on    } 1
fkey2-8-test 13 { PRAGMA foreign_keys = no    } 0
fkey2-8-test 14 { PRAGMA foreign_keys = yes   } 1
fkey2-8-test 15 { PRAGMA foreign_keys = false } 0
fkey2-8-test 16 { PRAGMA foreign_keys = true  } 1

#-------------------------------------------------------------------------
# The following tests, fkey2-9.*, test SET DEFAULT actions.
#
drop_all_tables
do_test fkey2-9.1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    CREATE TABLE t2(
      c INTEGER PRIMARY KEY,
      d INTEGER DEFAULT 1 REFERENCES t1 ON DELETE SET DEFAULT
    );
    DELETE FROM t1;
  }
} {}
do_test fkey2-9.1.2 {
  execsql {
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
    INSERT INTO t2 VALUES(1, 2);
    SELECT * FROM t2;
    DELETE FROM t1 WHERE a = 2;
    SELECT * FROM t2;
  }
} {1 2 1 1}
do_test fkey2-9.1.3 {
  execsql {
    INSERT INTO t1 VALUES(2, 'two');
    UPDATE t2 SET d = 2;
    DELETE FROM t1 WHERE a = 1;
    SELECT * FROM t2;
  }
} {1 2}
do_test fkey2-9.1.4 {
  execsql { SELECT * FROM t1 }
} {2 two}
do_test fkey2-9.1.5 {
  catchsql { DELETE FROM t1 }
} {1 {foreign key constraint failed}}

do_test fkey2-9.2.1 {
  execsql {
    CREATE TABLE pp(a, b, c, PRIMARY KEY(b, c));
    CREATE TABLE cc(d DEFAULT 3, e DEFAULT 1, f DEFAULT 2,
        FOREIGN KEY(f, d) REFERENCES pp 
        ON UPDATE SET DEFAULT 
        ON DELETE SET NULL
    );
    INSERT INTO pp VALUES(1, 2, 3);
    INSERT INTO pp VALUES(4, 5, 6);
    INSERT INTO pp VALUES(7, 8, 9);
  }
} {}
do_test fkey2-9.2.2 {
  execsql {
    INSERT INTO cc VALUES(6, 'A', 5);
    INSERT INTO cc VALUES(6, 'B', 5);
    INSERT INTO cc VALUES(9, 'A', 8);
    INSERT INTO cc VALUES(9, 'B', 8);
    UPDATE pp SET b = 1 WHERE a = 7;
    SELECT * FROM cc;
  }
} {6 A 5 6 B 5 3 A 2 3 B 2}
do_test fkey2-9.2.3 {
  execsql {
    DELETE FROM pp WHERE a = 4;
    SELECT * FROM cc;
  }
} {{} A {} {} B {} 3 A 2 3 B 2}

#-------------------------------------------------------------------------
# The following tests, fkey2-10.*, test "foreign key mismatch" and 
# other errors.
#
set tn 0
foreach zSql [list {
  CREATE TABLE p(a PRIMARY KEY, b);
  CREATE TABLE c(x REFERENCES p(c));
} {
  CREATE TABLE c(x REFERENCES v(y));
  CREATE VIEW v AS SELECT x AS y FROM c;
} {
  CREATE TABLE p(a, b, PRIMARY KEY(a, b));
  CREATE TABLE c(x REFERENCES p);
} {
  CREATE TABLE p(a COLLATE binary, b);
  CREATE UNIQUE INDEX i ON p(a COLLATE nocase);
  CREATE TABLE c(x REFERENCES p(a));
}] {
  drop_all_tables
  do_test fkey2-10.1.[incr tn] {
    execsql $zSql
    catchsql { INSERT INTO c DEFAULT VALUES }
  } {1 {foreign key mismatch}}
}

# "rowid" cannot be used as part of a child or parent key definition 
# unless it happens to be the name of an explicitly declared column.
#
do_test fkey2-10.2.1 {
  drop_all_tables
  catchsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    CREATE TABLE t2(c, d, FOREIGN KEY(rowid) REFERENCES t1(a));
  }
} {1 {unknown column "rowid" in foreign key definition}}
do_test fkey2-10.2.2 {
  drop_all_tables
  catchsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    CREATE TABLE t2(rowid, d, FOREIGN KEY(rowid) REFERENCES t1(a));
  }
} {0 {}}
do_test fkey2-10.2.1 {
  drop_all_tables
  catchsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(rowid));
    INSERT INTO t1(rowid, a, b) VALUES(1, 1, 1);
    INSERT INTO t2 VALUES(1, 1);
  }
} {1 {foreign key mismatch}}
do_test fkey2-10.2.2 {
  drop_all_tables
  catchsql {
    CREATE TABLE t1(rowid PRIMARY KEY, b);
    CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(rowid));
    INSERT INTO t1(rowid, b) VALUES(1, 1);
    INSERT INTO t2 VALUES(1, 1);
  }
} {0 {}}


#-------------------------------------------------------------------------
# The following tests, fkey2-11.*, test CASCADE actions.
#
drop_all_tables
do_test fkey2-11.1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(a) ON UPDATE CASCADE);

    INSERT INTO t1 VALUES(10, 100);
    INSERT INTO t2 VALUES(10, 100);
    UPDATE t1 SET a = 15;
    SELECT * FROM t2;
  }
} {15 100}

#-------------------------------------------------------------------------
# The following tests, fkey2-12.*, test RESTRICT actions.
#
drop_all_tables
do_test fkey2-12.1.1 {
  execsql {
    CREATE TABLE t1(a, b PRIMARY KEY);
    CREATE TABLE t2(
      x REFERENCES t1 ON UPDATE RESTRICT DEFERRABLE INITIALLY DEFERRED 
    );
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
    INSERT INTO t1 VALUES(3, 'three');
  }
} {}
do_test fkey2-12.1.2 { 
  execsql "BEGIN"
  execsql "INSERT INTO t2 VALUES('two')"
} {}
do_test fkey2-12.1.3 { 
  execsql "UPDATE t1 SET b = 'four' WHERE b = 'one'"
} {}
do_test fkey2-12.1.4 { 
  catchsql "UPDATE t1 SET b = 'five' WHERE b = 'two'"
} {1 {foreign key constraint failed}}
do_test fkey2-12.1.5 { 
  execsql "DELETE FROM t1 WHERE b = 'two'"
} {}
do_test fkey2-12.1.6 { 
  catchsql "COMMIT"
} {1 {foreign key constraint failed}}
do_test fkey2-12.1.7 { 
  execsql {
    INSERT INTO t1 VALUES(2, 'two');
    COMMIT;
  }
} {}

drop_all_tables
do_test fkey2-12.2.1 {
  execsql {
    CREATE TABLE t1(x COLLATE NOCASE PRIMARY KEY);
    CREATE TRIGGER tt1 AFTER DELETE ON t1 
      WHEN EXISTS ( SELECT 1 FROM t2 WHERE old.x = y )
    BEGIN
      INSERT INTO t1 VALUES(old.x);
    END;
    CREATE TABLE t2(y REFERENCES t1);
    INSERT INTO t1 VALUES('A');
    INSERT INTO t1 VALUES('B');
    INSERT INTO t2 VALUES('a');
    INSERT INTO t2 VALUES('b');

    SELECT * FROM t1;
    SELECT * FROM t2;
  }
} {A B a b}
do_test fkey2-12.2.2 {
  execsql { DELETE FROM t1 }
  execsql {
    SELECT * FROM t1;
    SELECT * FROM t2;
  }
} {A B a b}
do_test fkey2-12.2.3 {
  execsql {
    DROP TABLE t2;
    CREATE TABLE t2(y REFERENCES t1 ON DELETE RESTRICT);
    INSERT INTO t2 VALUES('a');
    INSERT INTO t2 VALUES('b');
  }
  catchsql { DELETE FROM t1 }
} {1 {foreign key constraint failed}}
do_test fkey2-12.2.4 {
  execsql {
    SELECT * FROM t1;
    SELECT * FROM t2;
  }
} {A B a b}

drop_all_tables
do_test fkey2-12.3.1 {
  execsql {
    CREATE TABLE up(
      c00, c01, c02, c03, c04, c05, c06, c07, c08, c09,
      c10, c11, c12, c13, c14, c15, c16, c17, c18, c19,
      c20, c21, c22, c23, c24, c25, c26, c27, c28, c29,
      c30, c31, c32, c33, c34, c35, c36, c37, c38, c39,
      PRIMARY KEY(c34, c35)
    );
    CREATE TABLE down(
      c00, c01, c02, c03, c04, c05, c06, c07, c08, c09,
      c10, c11, c12, c13, c14, c15, c16, c17, c18, c19,
      c20, c21, c22, c23, c24, c25, c26, c27, c28, c29,
      c30, c31, c32, c33, c34, c35, c36, c37, c38, c39,
      FOREIGN KEY(c39, c38) REFERENCES up ON UPDATE CASCADE
    );
  }
} {}
do_test fkey2-12.3.2 {
  execsql {
    INSERT INTO up(c34, c35) VALUES('yes', 'no');
    INSERT INTO down(c39, c38) VALUES('yes', 'no');
    UPDATE up SET c34 = 'possibly';
    SELECT c38, c39 FROM down;
    DELETE FROM down;
  }
} {no possibly}
do_test fkey2-12.3.3 {
  catchsql { INSERT INTO down(c39, c38) VALUES('yes', 'no') }
} {1 {foreign key constraint failed}}
do_test fkey2-12.3.4 {
  execsql { 
    INSERT INTO up(c34, c35) VALUES('yes', 'no');
    INSERT INTO down(c39, c38) VALUES('yes', 'no');
  }
  catchsql { DELETE FROM up WHERE c34 = 'yes' }
} {1 {foreign key constraint failed}}
do_test fkey2-12.3.5 {
  execsql { 
    DELETE FROM up WHERE c34 = 'possibly';
    SELECT c34, c35 FROM up;
    SELECT c39, c38 FROM down;
  }
} {yes no yes no}

#-------------------------------------------------------------------------
# The following tests, fkey2-13.*, test that FK processing is performed
# when rows are REPLACEd.
#
drop_all_tables
do_test fkey2-13.1.1 {
  execsql {
    CREATE TABLE pp(a UNIQUE, b, c, PRIMARY KEY(b, c));
    CREATE TABLE cc(d, e, f UNIQUE, FOREIGN KEY(d, e) REFERENCES pp);
    INSERT INTO pp VALUES(1, 2, 3);
    INSERT INTO cc VALUES(2, 3, 1);
  }
} {}
foreach {tn stmt} {
  1   "REPLACE INTO pp VALUES(1, 4, 5)"
  2   "REPLACE INTO pp(rowid, a, b, c) VALUES(1, 2, 3, 4)"
} {
  do_test fkey2-13.1.$tn.1 {
    catchsql $stmt
  } {1 {foreign key constraint failed}}
  do_test fkey2-13.1.$tn.2 {
    execsql {
      SELECT * FROM pp;
      SELECT * FROM cc;
    }
  } {1 2 3 2 3 1}
  do_test fkey2-13.1.$tn.3 {
    execsql BEGIN;
    catchsql $stmt
  } {1 {foreign key constraint failed}}
  do_test fkey2-13.1.$tn.4 {
    execsql {
      COMMIT;
      SELECT * FROM pp;
      SELECT * FROM cc;
    }
  } {1 2 3 2 3 1}
}
do_test fkey2-13.1.3 {
  execsql { 
    REPLACE INTO pp(rowid, a, b, c) VALUES(1, 2, 2, 3);
    SELECT rowid, * FROM pp;
    SELECT * FROM cc;
  }
} {1 2 2 3 2 3 1}
do_test fkey2-13.1.4 {
  execsql { 
    REPLACE INTO pp(rowid, a, b, c) VALUES(2, 2, 2, 3);
    SELECT rowid, * FROM pp;
    SELECT * FROM cc;
  }
} {2 2 2 3 2 3 1}

#-------------------------------------------------------------------------
# The following tests, fkey2-14.*, test that the "DROP TABLE" and "ALTER
# TABLE" commands work as expected wrt foreign key constraints.
#
# fkey2-14.1*: ALTER TABLE ADD COLUMN
# fkey2-14.2*: ALTER TABLE RENAME TABLE
# fkey2-14.3*: DROP TABLE
#
drop_all_tables
ifcapable altertable {
  do_test fkey2-14.1.1 {
    # Adding a column with a REFERENCES clause is not supported.
    execsql { 
      CREATE TABLE t1(a PRIMARY KEY);
      CREATE TABLE t2(a, b);
    }
    catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 }
  } {0 {}}
  do_test fkey2-14.1.2 {
    catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 }
  } {0 {}}
  do_test fkey2-14.1.3 {
    catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL}
  } {0 {}}
  do_test fkey2-14.1.4 {
    catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'}
  } {1 {Cannot add a REFERENCES column with non-NULL default value}}
  do_test fkey2-14.1.5 {
    catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 }
  } {1 {Cannot add a REFERENCES column with non-NULL default value}}
  do_test fkey2-14.1.6 {
    execsql { 
      PRAGMA foreign_keys = off;
      ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1;
      PRAGMA foreign_keys = on;
      SELECT sql FROM sqlite_master WHERE name='t2';
    }
  } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}}
  
  
  # Test the sqlite_rename_parent() function directly.
  #
  proc test_rename_parent {zCreate zOld zNew} {
    db eval {SELECT sqlite_rename_parent($zCreate, $zOld, $zNew)}
  }
  do_test fkey2-14.2.1.1 {
    test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3
  } {{CREATE TABLE t1(a REFERENCES "t3")}}
  do_test fkey2-14.2.1.2 {
    test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3
  } {{CREATE TABLE t1(a REFERENCES t2)}}
  do_test fkey2-14.2.1.3 {
    test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3
  } {{CREATE TABLE t1(a REFERENCES "t3")}}
  
  # Test ALTER TABLE RENAME TABLE a bit.
  #
  do_test fkey2-14.2.2.1 {
    drop_all_tables
    execsql {
      CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1);
      CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2);
      CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1);
    }
    execsql { SELECT sql FROM sqlite_master WHERE type = 'table'}
  } [list \
    {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1)}                     \
    {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2)}    \
    {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)}  \
  ]
  do_test fkey2-14.2.2.2 {
    execsql { ALTER TABLE t1 RENAME TO t4 }
    execsql { SELECT sql FROM sqlite_master WHERE type = 'table'}
  } [list \
    {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4")}                    \
    {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2)}     \
    {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \
  ]
  do_test fkey2-14.2.2.3 {
    catchsql { INSERT INTO t3 VALUES(1, 2, 3) }
  } {1 {foreign key constraint failed}}
  do_test fkey2-14.2.2.4 {
    execsql { INSERT INTO t4 VALUES(1, NULL) }
  } {}
  do_test fkey2-14.2.2.5 {
    catchsql { UPDATE t4 SET b = 5 }
  } {1 {foreign key constraint failed}}
  do_test fkey2-14.2.2.6 {
    catchsql { UPDATE t4 SET b = 1 }
  } {0 {}}
  do_test fkey2-14.2.2.7 {
    execsql { INSERT INTO t3 VALUES(1, NULL, 1) }
  } {}
}

do_test fkey-2.14.3.1 {
  drop_all_tables
  execsql {
    CREATE TABLE t1(a, b REFERENCES nosuchtable);
    DROP TABLE t1;
  }
} {}
do_test fkey-2.14.3.2 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES('a', 1);
    CREATE TABLE t2(x REFERENCES t1);
    INSERT INTO t2 VALUES('a');
  }
} {}
do_test fkey-2.14.3.3 {
  catchsql { DROP TABLE t1 }
} {1 {foreign key constraint failed}}
do_test fkey-2.14.3.4 {
  execsql {
    DELETE FROM t2;
    DROP TABLE t1;
  }
} {}
do_test fkey-2.14.3.4 {
  catchsql { INSERT INTO t2 VALUES('x') }
} {1 {no such table: main.t1}}
do_test fkey-2.14.3.5 {
  execsql {
    CREATE TABLE t1(x PRIMARY KEY);
    INSERT INTO t1 VALUES('x');
  }
  execsql { INSERT INTO t2 VALUES('x') }
} {}
do_test fkey-2.14.3.6 {
  catchsql { DROP TABLE t1 }
} {1 {foreign key constraint failed}}
do_test fkey-2.14.3.7 {
  execsql {
    DROP TABLE t2;
    DROP TABLE t1;
  }
} {}
do_test fkey-2.14.3.8 {
  execsql {
    CREATE TABLE pp(x, y, PRIMARY KEY(x, y));
    CREATE TABLE cc(a, b, FOREIGN KEY(a, b) REFERENCES pp(x, z));
  }
  catchsql { INSERT INTO cc VALUES(1, 2) }
} {1 {foreign key mismatch}}
do_test fkey-2.14.3.9 {
  execsql { DROP TABLE cc }
} {}
do_test fkey-2.14.3.10 {
  execsql {
    CREATE TABLE cc(a, b, 
      FOREIGN KEY(a, b) REFERENCES pp DEFERRABLE INITIALLY DEFERRED
    );
  }
  execsql {
    INSERT INTO pp VALUES('a', 'b');
    INSERT INTO cc VALUES('a', 'b');
    BEGIN;
      DROP TABLE pp;
      CREATE TABLE pp(a, b, c, PRIMARY KEY(b, c));
      INSERT INTO pp VALUES(1, 'a', 'b');
    COMMIT;
  }
} {}
do_test fkey-2.14.3.11 {
  execsql { 
    BEGIN;
      DROP TABLE cc;
      DROP TABLE pp;
    COMMIT;
  }
} {}
do_test fkey-2.14.3.12 {
  execsql {
    CREATE TABLE b1(a, b);
    CREATE TABLE b2(a, b REFERENCES b1);
    DROP TABLE b1;
  }
} {}
do_test fkey-2.14.3.13 {
  execsql {
    CREATE TABLE b3(a, b REFERENCES b2 DEFERRABLE INITIALLY DEFERRED);
    DROP TABLE b2;
  }
} {}

# Test that nothing goes wrong when dropping a table that refers to a view.
# Or dropping a view that an existing FK (incorrectly) refers to. Or either
# of the above scenarios with a virtual table.
drop_all_tables
do_test fkey-2.14.4.1 {
  execsql {
    CREATE TABLE t1(x REFERENCES v); 
    CREATE VIEW v AS SELECT * FROM t1;
  }
} {}
do_test fkey-2.14.4.2 {
  execsql {
    DROP VIEW v;
  }
} {}
ifcapable vtab {
  register_echo_module db
  do_test fkey-2.14.4.3 {
    execsql { CREATE VIRTUAL TABLE v USING echo(t1) }
  } {}
  do_test fkey-2.14.4.2 {
    execsql {
      DROP TABLE v;
    }
  } {}
}

#-------------------------------------------------------------------------
# The following tests, fkey2-15.*, test that unnecessary FK related scans 
# and lookups are avoided when the constraint counters are zero.
#
drop_all_tables
proc execsqlS {zSql} {
  set ::sqlite_search_count 0
  set ::sqlite_found_count 0
  set res [uplevel [list execsql $zSql]]
  concat [expr $::sqlite_found_count + $::sqlite_search_count] $res
}
do_test fkey2-15.1.1 {
  execsql {
    CREATE TABLE pp(a PRIMARY KEY, b);
    CREATE TABLE cc(x, y REFERENCES pp DEFERRABLE INITIALLY DEFERRED);
    INSERT INTO pp VALUES(1, 'one');
    INSERT INTO pp VALUES(2, 'two');
    INSERT INTO cc VALUES('neung', 1);
    INSERT INTO cc VALUES('song', 2);
  }
} {}
do_test fkey2-15.1.2 {
  execsqlS { INSERT INTO pp VALUES(3, 'three') }
} {0}
do_test fkey2-15.1.3 {
  execsql {
    BEGIN;
      INSERT INTO cc VALUES('see', 4);    -- Violates deferred constraint
  }
  execsqlS { INSERT INTO pp VALUES(5, 'five') }
} {2}
do_test fkey2-15.1.4 {
  execsql { DELETE FROM cc WHERE x = 'see' }
  execsqlS { INSERT INTO pp VALUES(6, 'six') }
} {0}
do_test fkey2-15.1.5 {
  execsql COMMIT
} {}
do_test fkey2-15.1.6 {
  execsql BEGIN
  execsqlS {
    DELETE FROM cc WHERE x = 'neung';
    ROLLBACK;
  }
} {1}
do_test fkey2-15.1.7 {
  execsql { 
    BEGIN;
    DELETE FROM pp WHERE a = 2;
  }
  execsqlS {
    DELETE FROM cc WHERE x = 'neung';
    ROLLBACK;
  }
} {2}

#-------------------------------------------------------------------------
# This next block of tests, fkey2-16.*, test that rows that refer to
# themselves may be inserted and deleted.
#
foreach {tn zSchema} {
  1 { CREATE TABLE self(a INTEGER PRIMARY KEY, b REFERENCES self(a)) }
  2 { CREATE TABLE self(a PRIMARY KEY, b REFERENCES self(a)) }
  3 { CREATE TABLE self(a UNIQUE, b INTEGER PRIMARY KEY REFERENCES self(a)) }
} {
  drop_all_tables
  do_test fkey2-16.1.$tn.1 {
    execsql $zSchema
    execsql { INSERT INTO self VALUES(13, 13) }
  } {}
  do_test fkey2-16.1.$tn.2 {
    execsql { UPDATE self SET a = 14, b = 14 }
  } {}

  do_test fkey2-16.1.$tn.3 {
    catchsql { UPDATE self SET b = 15 }
  } {1 {foreign key constraint failed}}

  do_test fkey2-16.1.$tn.4 {
    catchsql { UPDATE self SET a = 15 }
  } {1 {foreign key constraint failed}}

  do_test fkey2-16.1.$tn.5 {
    catchsql { UPDATE self SET a = 15, b = 16 }
  } {1 {foreign key constraint failed}}

  do_test fkey2-16.1.$tn.6 {
    catchsql { UPDATE self SET a = 17, b = 17 }
  } {0 {}}

  do_test fkey2-16.1.$tn.7 {
    execsql { DELETE FROM self }
  } {}
  do_test fkey2-16.1.$tn.8 {
    catchsql { INSERT INTO self VALUES(20, 21) }
  } {1 {foreign key constraint failed}}
}

#-------------------------------------------------------------------------
# This next block of tests, fkey2-17.*, tests that if "PRAGMA count_changes"
# is turned on statements that violate immediate FK constraints return
# SQLITE_CONSTRAINT immediately, not after returning a number of rows.
# Whereas statements that violate deferred FK constraints return the number
# of rows before failing.
#
# Also test that rows modified by FK actions are not counted in either the
# returned row count or the values returned by sqlite3_changes(). Like
# trigger related changes, they are included in sqlite3_total_changes() though.
#
drop_all_tables
do_test fkey2-17.1.1 {
  execsql { PRAGMA count_changes = 1 }
  execsql { 
    CREATE TABLE one(a, b, c, UNIQUE(b, c));
    CREATE TABLE two(d, e, f, FOREIGN KEY(e, f) REFERENCES one(b, c));
    INSERT INTO one VALUES(1, 2, 3);
  }
} {1}
do_test fkey2-17.1.2 {
  set STMT [sqlite3_prepare_v2 db "INSERT INTO two VALUES(4, 5, 6)" -1 dummy]
  sqlite3_step $STMT
} {SQLITE_CONSTRAINT}
do_test fkey2-17.1.3 {
  sqlite3_step $STMT
} {SQLITE_MISUSE}
do_test fkey2-17.1.4 {
  sqlite3_finalize $STMT
} {SQLITE_CONSTRAINT}
do_test fkey2-17.1.5 {
  execsql {
    INSERT INTO one VALUES(2, 3, 4);
    INSERT INTO one VALUES(3, 4, 5);
    INSERT INTO two VALUES(1, 2, 3);
    INSERT INTO two VALUES(2, 3, 4);
    INSERT INTO two VALUES(3, 4, 5);
  }
} {1 1 1 1 1}
do_test fkey2-17.1.6 {
  catchsql {
    BEGIN;
      INSERT INTO one VALUES(0, 0, 0);
      UPDATE two SET e=e+1, f=f+1;
  }
} {1 {foreign key constraint failed}}
do_test fkey2-17.1.7 {
  execsql { SELECT * FROM one }
} {1 2 3 2 3 4 3 4 5 0 0 0}
do_test fkey2-17.1.8 {
  execsql { SELECT * FROM two }
} {1 2 3 2 3 4 3 4 5}
do_test fkey2-17.1.9 {
  execsql COMMIT
} {}
do_test fkey2-17.1.10 {
  execsql {
    CREATE TABLE three(
      g, h, i, 
      FOREIGN KEY(h, i) REFERENCES one(b, c) DEFERRABLE INITIALLY DEFERRED
    );
  }
} {}
do_test fkey2-17.1.11 {
  set STMT [sqlite3_prepare_v2 db "INSERT INTO three VALUES(7, 8, 9)" -1 dummy]
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test fkey2-17.1.12 {
  sqlite3_column_text $STMT 0
} {1}
do_test fkey2-17.1.13 {
  sqlite3_step $STMT
} {SQLITE_CONSTRAINT}
do_test fkey2-17.1.14 {
  sqlite3_finalize $STMT
} {SQLITE_CONSTRAINT}

drop_all_tables
do_test fkey2-17.2.1 {
  execsql {
    CREATE TABLE high("a'b!" PRIMARY KEY, b);
    CREATE TABLE low(
      c, 
      "d&6" REFERENCES high ON UPDATE CASCADE ON DELETE CASCADE
    );
  }
} {}
do_test fkey2-17.2.2 {
  execsql {
    INSERT INTO high VALUES('a', 'b');
    INSERT INTO low VALUES('b', 'a');
  }
  db changes
} {1}
set nTotal [db total_changes]
do_test fkey2-17.2.3 {
  execsql { UPDATE high SET "a'b!" = 'c' }
} {1}
do_test fkey2-17.2.4 {
  db changes
} {1}
do_test fkey2-17.2.5 {
  expr [db total_changes] - $nTotal
} {2}
do_test fkey2-17.2.6 {
  execsql { SELECT * FROM high ; SELECT * FROM low }
} {c b b c}
do_test fkey2-17.2.7 {
  execsql { DELETE FROM high }
} {1}
do_test fkey2-17.2.8 {
  db changes
} {1}
do_test fkey2-17.2.9 {
  expr [db total_changes] - $nTotal
} {4}
do_test fkey2-17.2.10 {
  execsql { SELECT * FROM high ; SELECT * FROM low }
} {}
execsql { PRAGMA count_changes = 0 }

#-------------------------------------------------------------------------
# Test that the authorization callback works.
#

ifcapable auth {
  do_test fkey2-18.1 {
    execsql {
      CREATE TABLE long(a, b PRIMARY KEY, c);
      CREATE TABLE short(d, e, f REFERENCES long);
      CREATE TABLE mid(g, h, i REFERENCES long DEFERRABLE INITIALLY DEFERRED);
    }
  } {}

  proc auth {args} {eval lappend ::authargs $args ; return SQLITE_OK}
  db auth auth

  # An insert on the parent table must read the child key of any deferred
  # foreign key constraints. But not the child key of immediate constraints.
  set authargs {}
  do_test fkey2-18.2 {
    execsql { INSERT INTO long VALUES(1, 2, 3) }
    set authargs
  } {SQLITE_INSERT long {} main {} SQLITE_READ mid i main {}}

  # An insert on the child table of an immediate constraint must read the
  # parent key columns (to see if it is a violation or not).
  set authargs {}
  do_test fkey2-18.3 {
    execsql { INSERT INTO short VALUES(1, 3, 2) }
    set authargs
  } {SQLITE_INSERT short {} main {} SQLITE_READ long b main {}}
  
  # As must an insert on the child table of a deferred constraint.
  set authargs {}
  do_test fkey2-18.4 {
    execsql { INSERT INTO mid VALUES(1, 3, 2) }
    set authargs
  } {SQLITE_INSERT mid {} main {} SQLITE_READ long b main {}}

  do_test fkey2-18.5 {
    execsql {
      CREATE TABLE nought(a, b PRIMARY KEY, c);
      CREATE TABLE cross(d, e, f,
        FOREIGN KEY(e) REFERENCES nought(b) ON UPDATE CASCADE
      );
    }
    execsql { INSERT INTO nought VALUES(2, 1, 2) }
    execsql { INSERT INTO cross VALUES(0, 1, 0) }
    set authargs [list]
    execsql { UPDATE nought SET b = 5 }
    set authargs
  } {SQLITE_UPDATE nought b main {} SQLITE_READ cross e main {} SQLITE_READ cross e main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {} SQLITE_UPDATE cross e main {} SQLITE_READ nought b main {} SQLITE_READ cross e main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {}}

  do_test fkey2-18.6 {
    execsql {SELECT * FROM cross}
  } {0 5 0}

  do_test fkey2-18.7 {
    execsql {
      CREATE TABLE one(a INTEGER PRIMARY KEY, b);
      CREATE TABLE two(b, c REFERENCES one);
      INSERT INTO one VALUES(101, 102);
    }
    set authargs [list]
    execsql { INSERT INTO two VALUES(100, 101); }
    set authargs
  } {SQLITE_INSERT two {} main {} SQLITE_READ one a main {}}

  # Return SQLITE_IGNORE to requests to read from the parent table. This
  # causes inserts of non-NULL keys into the child table to fail.
  #
  rename auth {}
  proc auth {args} {
    if {[lindex $args 1] == "long"} {return SQLITE_IGNORE}
    return SQLITE_OK
  }
  do_test fkey2-18.8 {
    catchsql { INSERT INTO short VALUES(1, 3, 2) }
  } {1 {foreign key constraint failed}}
  do_test fkey2-18.9 {
    execsql { INSERT INTO short VALUES(1, 3, NULL) }
  } {}
  do_test fkey2-18.10 {
    execsql { SELECT * FROM short }
  } {1 3 2 1 3 {}}
  do_test fkey2-18.11 {
    catchsql { UPDATE short SET f = 2 WHERE f IS NULL }
  } {1 {foreign key constraint failed}}

  db auth {}
  unset authargs
}

#-------------------------------------------------------------------------
# The following block of tests, those prefixed with "fkey2-genfkey.", are 
# the same tests that were used to test the ".genfkey" command provided 
# by the shell tool. So these tests show that the built-in foreign key 
# implementation is more or less compatible with the triggers generated 
# by genfkey.
#
drop_all_tables
do_test fkey2-genfkey.1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c));
    CREATE TABLE t2(e REFERENCES t1, f);
    CREATE TABLE t3(g, h, i, FOREIGN KEY (h, i) REFERENCES t1(b, c));
  }
} {}
do_test fkey2-genfkey.1.2 {
  catchsql { INSERT INTO t2 VALUES(1, 2) }
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.3 {
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t2 VALUES(1, 2);
  }
} {}
do_test fkey2-genfkey.1.4 {
  execsql { INSERT INTO t2 VALUES(NULL, 3) }
} {}
do_test fkey2-genfkey.1.5 {
  catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL }
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.6 {
  execsql { UPDATE t2 SET e = 1 WHERE e IS NULL }
} {}
do_test fkey2-genfkey.1.7 {
  execsql { UPDATE t2 SET e = NULL WHERE f = 3 }
} {}
do_test fkey2-genfkey.1.8 {
  catchsql { UPDATE t1 SET a = 10 }
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.9 {
  catchsql { UPDATE t1 SET a = NULL }
} {1 {datatype mismatch}}
do_test fkey2-genfkey.1.10 {
  catchsql { DELETE FROM t1 }
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.11 {
  execsql { UPDATE t2 SET e = NULL }
} {}
do_test fkey2-genfkey.1.12 {
  execsql { 
    UPDATE t1 SET a = 10;
    DELETE FROM t1;
    DELETE FROM t2;
  }
} {}
do_test fkey2-genfkey.1.13 {
  execsql {
    INSERT INTO t3 VALUES(1, NULL, NULL);
    INSERT INTO t3 VALUES(1, 2, NULL);
    INSERT INTO t3 VALUES(1, NULL, 3);
  }
} {}
do_test fkey2-genfkey.1.14 {
  catchsql { INSERT INTO t3 VALUES(3, 1, 4) }
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.15 {
  execsql { 
    INSERT INTO t1 VALUES(1, 1, 4);
    INSERT INTO t3 VALUES(3, 1, 4);
  }
} {}
do_test fkey2-genfkey.1.16 {
  catchsql { DELETE FROM t1 }
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.17 {
  catchsql { UPDATE t1 SET b = 10}
} {1 {foreign key constraint failed}}
do_test fkey2-genfkey.1.18 {
  execsql { UPDATE t1 SET a = 10}
} {}
do_test fkey2-genfkey.1.19 {
  catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3}
} {1 {foreign key constraint failed}}

drop_all_tables
do_test fkey2-genfkey.2.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c));
    CREATE TABLE t2(e REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE, f);
    CREATE TABLE t3(g, h, i, 
        FOREIGN KEY (h, i) 
        REFERENCES t1(b, c) ON UPDATE CASCADE ON DELETE CASCADE
    );
  }
} {}
do_test fkey2-genfkey.2.2 {
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(4, 'four');
  }
} {}
do_test fkey2-genfkey.2.3 {
  execsql {
    UPDATE t1 SET a = 2 WHERE a = 1;
    SELECT * FROM t2;
  }
} {2 one 4 four}
do_test fkey2-genfkey.2.4 {
  execsql {
    DELETE FROM t1 WHERE a = 4;
    SELECT * FROM t2;
  }
} {2 one}

do_test fkey2-genfkey.2.5 {
  execsql {
    INSERT INTO t3 VALUES('hello', 2, 3);
    UPDATE t1 SET c = 2;
    SELECT * FROM t3;
  }
} {hello 2 2}
do_test fkey2-genfkey.2.6 {
  execsql {
    DELETE FROM t1;
    SELECT * FROM t3;
  }
} {}

drop_all_tables
do_test fkey2-genfkey.3.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(c, b));
    CREATE TABLE t2(e REFERENCES t1 ON UPDATE SET NULL ON DELETE SET NULL, f);
    CREATE TABLE t3(g, h, i, 
        FOREIGN KEY (h, i) 
        REFERENCES t1(b, c) ON UPDATE SET NULL ON DELETE SET NULL
    );
  }
} {}
do_test fkey2-genfkey.3.2 {
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(4, 'four');
  }
} {}
do_test fkey2-genfkey.3.3 {
  execsql {
    UPDATE t1 SET a = 2 WHERE a = 1;
    SELECT * FROM t2;
  }
} {{} one 4 four}
do_test fkey2-genfkey.3.4 {
  execsql {
    DELETE FROM t1 WHERE a = 4;
    SELECT * FROM t2;
  }
} {{} one {} four}
do_test fkey2-genfkey.3.5 {
  execsql {
    INSERT INTO t3 VALUES('hello', 2, 3);
    UPDATE t1 SET c = 2;
    SELECT * FROM t3;
  }
} {hello {} {}}
do_test fkey2-genfkey.3.6 {
  execsql {
    UPDATE t3 SET h = 2, i = 2;
    DELETE FROM t1;
    SELECT * FROM t3;
  }
} {hello {} {}}

finish_test

Added test/fkey3.test.

































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 2009 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for foreign keys.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!foreignkey||!trigger} {
  finish_test
  return
}

# Create a table and some data to work with.
#
do_test fkey3-1.1 {
  execsql {
    PRAGMA foreign_keys=ON;
    CREATE TABLE t1(x INTEGER PRIMARY KEY);
    INSERT INTO t1 VALUES(100);
    INSERT INTO t1 VALUES(101);
    CREATE TABLE t2(y INTEGER REFERENCES t1 (x));
    INSERT INTO t2 VALUES(100);
    INSERT INTO t2 VALUES(101);
    SELECT 1, x FROM t1;
    SELECT 2, y FROM t2;
  }
} {1 100 1 101 2 100 2 101}

do_test fkey3-1.2 {
  catchsql {
    DELETE FROM t1 WHERE x=100;
  }
} {1 {foreign key constraint failed}}

do_test fkey3-1.3 {
  catchsql {
    DROP TABLE t1;
  }
} {1 {foreign key constraint failed}}

do_test fkey3-1.4 {
  execsql {
    DROP TABLE t2;
  }
} {}

do_test fkey3-1.5 {
  execsql {
    DROP TABLE t1;
  }
} {}

do_test fkey3-2.1 {
  execsql {
    PRAGMA foreign_keys=ON;
    CREATE TABLE t1(x INTEGER PRIMARY KEY);
    INSERT INTO t1 VALUES(100);
    INSERT INTO t1 VALUES(101);
    CREATE TABLE t2(y INTEGER PRIMARY KEY REFERENCES t1 (x) ON UPDATE SET NULL);
  }
  execsql {
    INSERT INTO t2 VALUES(100);
    INSERT INTO t2 VALUES(101);
    SELECT 1, x FROM t1;
    SELECT 2, y FROM t2;
  }
} {1 100 1 101 2 100 2 101}

finish_test

Added test/fkey_malloc.test.









































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# 2009 September 22
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !foreignkey||!trigger {
  finish_test
  return
}
source $testdir/malloc_common.tcl

do_malloc_test fkey_malloc-1 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE t1(a PRIMARY KEY, b UNIQUE);
  CREATE TABLE t2(x REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE);
} -sqlbody {
  INSERT INTO t1 VALUES('aaa', 1);
  INSERT INTO t2 VALUES('aaa');
  UPDATE t1 SET a = 'bbb';
  DELETE FROM t1;
}

do_malloc_test fkey_malloc-2 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE t1(a, b, UNIQUE(a, b));
} -sqlbody {
  CREATE TABLE t2(x, y, 
    FOREIGN KEY(x, y) REFERENCES t1(a, b) DEFERRABLE INITIALLY DEFERRED
  );
  BEGIN;
    INSERT INTO t2 VALUES('a', 'b');
    INSERT INTO t1 VALUES('a', 'b');
    UPDATE t1 SET a = 'c';
    DELETE FROM t2;
    INSERT INTO t2 VALUES('d', 'b');
    UPDATE t2 SET x = 'c';
  COMMIT;
}

do_malloc_test fkey_malloc-3 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE t1(x INTEGER PRIMARY KEY);
  CREATE TABLE t2(y DEFAULT 14 REFERENCES t1(x) ON UPDATE SET DEFAULT);
  CREATE TABLE t3(y REFERENCES t1 ON UPDATE SET NULL);
  INSERT INTO t1 VALUES(13);
  INSERT INTO t2 VALUES(13);
  INSERT INTO t3 VALUES(13);
} -sqlbody {
  UPDATE t1 SET x = 14;
}

proc catch_fk_error {zSql} {
  set rc [catch {db eval $zSql} msg]
  if {$rc==0} {
    return $msg
  }
  if {[string match {*foreign key*} $msg]} {
    return ""
  }
  if {$msg eq "out of memory"} {
    error 1
  }
  error $msg
}

do_malloc_test fkey_malloc-4 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE);
  CREATE TABLE t2(z REFERENCES t1(x), a REFERENCES t1(y));
  CREATE TABLE t3(x);
  CREATE TABLE t4(z REFERENCES t3);
  CREATE TABLE t5(x, y);
  CREATE TABLE t6(z REFERENCES t5(x));
  CREATE INDEX i51 ON t5(x);
  CREATE INDEX i52 ON t5(y, x);
  INSERT INTO t1 VALUES(1, 2);
} -tclbody {
  catch_fk_error {INSERT INTO t2 VALUES(1, 3)}
  catch_fk_error {INSERT INTO t4 VALUES(2)}
  catch_fk_error {INSERT INTO t6 VALUES(2)}
}

do_malloc_test fkey_malloc-5 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE t1(x, y, PRIMARY KEY(x, y));
  CREATE TABLE t2(a, b, FOREIGN KEY(a, b) REFERENCES t1 ON UPDATE CASCADE);
  INSERT INTO t1 VALUES(1, 2);
  INSERT INTO t2 VALUES(1, 2);
} -sqlbody {
  UPDATE t1 SET x = 5;
}

do_malloc_test fkey_malloc-6 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE t1(
    x PRIMARY KEY, 
    y REFERENCES t1 ON DELETE RESTRICT ON UPDATE SET DEFAULT
  );
  INSERT INTO t1 VALUES('abc', 'abc');
  INSERT INTO t1 VALUES('def', 'def');
} -sqlbody {
  INSERT INTO t1 VALUES('ghi', 'ghi');
  DELETE FROM t1 WHERE rowid>1;
  UPDATE t1 SET x='jkl', y='jkl';
}

do_malloc_test fkey_malloc-7 -sqlprep {
  PRAGMA foreign_keys = 1;
  CREATE TABLE x(a, b, PRIMARY KEY(a, b));
  CREATE TABLE y(c, d,
    FOREIGN KEY(d, c) REFERENCES x DEFERRABLE INITIALLY DEFERRED
  );
  CREATE TABLE z(e, f, FOREIGN KEY(e, f) REFERENCES x);
} -sqlbody {
  DROP TABLE y;
  DROP TABLE x;
}

finish_test


Added test/format4.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2005 December 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that the new serial_type
# values of 8 (integer 0) and 9 (integer 1) work correctly.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db eval {PRAGMA legacy_file_format=OFF}

# The size of the database depends on whether or not autovacuum
# is enabled.
#
ifcapable autovacuum {
  if {[db one {PRAGMA auto_vacuum}]} {
    set small 3072
    set large 5120
  } else {
    set small 2048
    set large 4096
  }
} else {
  set small 2048
  set large 4096
}

do_test format4-1.1 {
  execsql {
    CREATE TABLE t1(x0,x1,x2,x3,x4,x5,x6,x7,x8,x9);
    INSERT INTO t1 VALUES(0,0,0,0,0,0,0,0,0,0);
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
  }
  file size test.db
} $small
do_test format4-1.2 {
  execsql {
    UPDATE t1 SET x0=1, x1=1, x2=1, x3=1, x4=1, x5=1, x6=1, x7=1, x8=1, x9=1
  }
  file size test.db
} $small
do_test format4-1.3 {
  execsql {
    UPDATE t1 SET x0=2, x1=2, x2=2, x3=2, x4=2, x5=2, x6=2, x7=2, x8=2, x9=2
  }
  file size test.db
} $large


finish_test

Added test/fts1a.test.





















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# 2006 September 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS1 module.
#
# $Id: fts1a.test,v 1.4 2006/09/28 19:43:32 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Construct a full-text search table containing five keywords:
# one, two, three, four, and five, in various combinations.  The
# rowid for each will be a bitmask for the elements it contains.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(content);
  INSERT INTO t1(content) VALUES('one');
  INSERT INTO t1(content) VALUES('two');
  INSERT INTO t1(content) VALUES('one two');
  INSERT INTO t1(content) VALUES('three');
  INSERT INTO t1(content) VALUES('one three');
  INSERT INTO t1(content) VALUES('two three');
  INSERT INTO t1(content) VALUES('one two three');
  INSERT INTO t1(content) VALUES('four');
  INSERT INTO t1(content) VALUES('one four');
  INSERT INTO t1(content) VALUES('two four');
  INSERT INTO t1(content) VALUES('one two four');
  INSERT INTO t1(content) VALUES('three four');
  INSERT INTO t1(content) VALUES('one three four');
  INSERT INTO t1(content) VALUES('two three four');
  INSERT INTO t1(content) VALUES('one two three four');
  INSERT INTO t1(content) VALUES('five');
  INSERT INTO t1(content) VALUES('one five');
  INSERT INTO t1(content) VALUES('two five');
  INSERT INTO t1(content) VALUES('one two five');
  INSERT INTO t1(content) VALUES('three five');
  INSERT INTO t1(content) VALUES('one three five');
  INSERT INTO t1(content) VALUES('two three five');
  INSERT INTO t1(content) VALUES('one two three five');
  INSERT INTO t1(content) VALUES('four five');
  INSERT INTO t1(content) VALUES('one four five');
  INSERT INTO t1(content) VALUES('two four five');
  INSERT INTO t1(content) VALUES('one two four five');
  INSERT INTO t1(content) VALUES('three four five');
  INSERT INTO t1(content) VALUES('one three four five');
  INSERT INTO t1(content) VALUES('two three four five');
  INSERT INTO t1(content) VALUES('one two three four five');
}

do_test fts1a-1.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts1a-1.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two'}
} {3 7 11 15 19 23 27 31}
do_test fts1a-1.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one'}
} {3 7 11 15 19 23 27 31}
do_test fts1a-1.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two three'}
} {7 15 23 31}
do_test fts1a-1.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one three two'}
} {7 15 23 31}
do_test fts1a-1.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two three one'}
} {7 15 23 31}
do_test fts1a-1.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one three'}
} {7 15 23 31}
do_test fts1a-1.8 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three one two'}
} {7 15 23 31}
do_test fts1a-1.9 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three two one'}
} {7 15 23 31}
do_test fts1a-1.10 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two THREE'}
} {7 15 23 31}
do_test fts1a-1.11 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '  ONE    Two   three  '}
} {7 15 23 31}

do_test fts1a-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one"'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts1a-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two"'}
} {3 7 11 15 19 23 27 31}
do_test fts1a-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"two one"'}
} {}
do_test fts1a-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three"'}
} {7 15 23 31}
do_test fts1a-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two"'}
} {}
do_test fts1a-2.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three four"'}
} {15 31}
do_test fts1a-2.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two four"'}
} {}
do_test fts1a-2.8 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three five"'}
} {21}
do_test fts1a-2.9 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" five'}
} {21 29}
do_test fts1a-2.10 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three"'}
} {21 29}
do_test fts1a-2.11 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three" four'}
} {29}
do_test fts1a-2.12 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five four "one three"'}
} {29}
do_test fts1a-2.13 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" four five'}
} {29}

do_test fts1a-3.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts1a-3.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one -two'}
} {1 5 9 13 17 21 25 29}
do_test fts1a-3.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '-two one'}
} {1 5 9 13 17 21 25 29}

do_test fts1a-4.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one OR two'}
} {1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21 22 23 25 26 27 29 30 31}
do_test fts1a-4.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two" OR three'}
} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31}
do_test fts1a-4.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR "one two"'}
} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31}
do_test fts1a-4.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three'}
} {3 5 7 11 13 15 19 21 23 27 29 31}
do_test fts1a-4.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR two one'}
} {3 5 7 11 13 15 19 21 23 27 29 31}
do_test fts1a-4.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three OR four'}
} {3 5 7 9 11 13 15 19 21 23 25 27 29 31}
do_test fts1a-4.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two OR three OR four one'}
} {3 5 7 9 11 13 15 19 21 23 25 27 29 31}

# Test the ability to handle NULL content
#
do_test fts1a-5.1 {
  execsql {INSERT INTO t1(content) VALUES(NULL)}
} {}
do_test fts1a-5.2 {
  set rowid [db last_insert_rowid]
  execsql {SELECT content FROM t1 WHERE rowid=$rowid}
} {{}}
do_test fts1a-5.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH NULL}
} {}



finish_test

Added test/fts1b.test.







































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# 2006 September 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS1 module.
#
# $Id: fts1b.test,v 1.4 2006/09/18 02:12:48 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Fill the full-text index "t1" with phrases in english, spanish,
# and german.  For the i-th row, fill in the names for the bits
# that are set in the value of i.  The least significant bit is
# 1.  For example,  the value 5 is 101 in binary which will be
# converted to "one three" in english.
#
proc fill_multilanguage_fulltext_t1 {} {
  set english {one two three four five}
  set spanish {un dos tres cuatro cinco}
  set german {eine zwei drei vier funf}
  
  for {set i 1} {$i<=31} {incr i} {
    set cmd "INSERT INTO t1 VALUES"
    set vset {}
    foreach lang {english spanish german} {
      set words {}
      for {set j 0; set k 1} {$j<5} {incr j; incr k $k} {
        if {$k&$i} {lappend words [lindex [set $lang] $j]}
      }
      lappend vset "'$words'"
    }
    set sql "INSERT INTO t1(english,spanish,german) VALUES([join $vset ,])"
    # puts $sql
    db eval $sql
  }
}

# Construct a full-text search table containing five keywords:
# one, two, three, four, and five, in various combinations.  The
# rowid for each will be a bitmask for the elements it contains.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(english,spanish,german);
}
fill_multilanguage_fulltext_t1

do_test fts1b-1.1 {
  execsql {SELECT rowid FROM t1 WHERE english MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts1b-1.2 {
  execsql {SELECT rowid FROM t1 WHERE spanish MATCH 'one'}
} {}
do_test fts1b-1.3 {
  execsql {SELECT rowid FROM t1 WHERE german MATCH 'one'}
} {}
do_test fts1b-1.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts1b-1.5 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one dos drei'}
} {7 15 23 31}
do_test fts1b-1.6 {
  execsql {SELECT english, spanish, german FROM t1 WHERE rowid=1}
} {one un eine}
do_test fts1b-1.7 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"one un"'}
} {}

do_test fts1b-2.1 {
  execsql {
    CREATE VIRTUAL TABLE t2 USING fts1(from,to);
    INSERT INTO t2([from],[to]) VALUES ('one two three', 'four five six');
    SELECT [from], [to] FROM t2
  }
} {{one two three} {four five six}}


# Compute an SQL string that contains the words one, two, three,... to
# describe bits set in the value $i.  Only the lower 5 bits are examined.
#
proc wordset {i} {
  set x {}
  for {set j 0; set k 1} {$j<5} {incr j; incr k $k} {
    if {$k&$i} {lappend x [lindex {one two three four five} $j]}
  }
  return '$x'
}

# Create a new FTS table with three columns:
#
#    norm:      words for the bits of rowid
#    plusone:   words for the bits of rowid+1
#    invert:    words for the bits of ~rowid
#
db eval {
   CREATE VIRTUAL TABLE t4 USING fts1([norm],'plusone',"invert");
}
for {set i 1} {$i<=15} {incr i} {
  set vset [list [wordset $i] [wordset [expr {$i+1}]] [wordset [expr {~$i}]]]
  db eval "INSERT INTO t4(norm,plusone,invert) VALUES([join $vset ,]);"
}

do_test fts1b-4.1 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one'}
} {1 3 5 7 9 11 13 15}
do_test fts1b-4.2 {
  execsql {SELECT rowid FROM t4 WHERE norm MATCH 'one'}
} {1 3 5 7 9 11 13 15}
do_test fts1b-4.3 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'one'}
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}
do_test fts1b-4.4 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:one'}
} {2 4 6 8 10 12 14}
do_test fts1b-4.5 {
  execsql {SELECT rowid FROM t4 WHERE plusone MATCH 'one'}
} {2 4 6 8 10 12 14}
do_test fts1b-4.6 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one plusone:two'}
} {1 5 9 13}
do_test fts1b-4.7 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one two'}
} {1 3 5 7 9 11 13 15}
do_test fts1b-4.8 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:two norm:one'}
} {1 5 9 13}
do_test fts1b-4.9 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'two norm:one'}
} {1 3 5 7 9 11 13 15}


finish_test

Added test/fts1c.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# 2006 September 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS1 module.
#
# $Id: fts1c.test,v 1.11 2006/10/04 17:35:28 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Create a table of sample email data.   The data comes from email
# archives of Enron executives that was published as part of the
# litigation against that company.
#
do_test fts1c-1.1 {
  db eval {
    CREATE VIRTUAL TABLE email USING fts1([from],[to],subject,body);
    BEGIN TRANSACTION;
INSERT INTO email([from],[to],subject,body) VALUES('savita.puthigai@enron.com', 'traders.eol@enron.com, traders.eol@enron.com', 'EnronOnline- Change to Autohedge', 'Effective Monday, October 22, 2001 the following changes will be made to the Autohedge functionality on EnronOnline.

The volume on the hedge will now respect the minimum volume and volume increment settings on the parent product. See rules below: 

?	If the transaction volume on the child is less than half of the parent''s minimum volume no hedge will occur.
?	If the transaction volume on the child is more than half the parent''s minimum volume but less than half the volume increment on the parent, the hedge will volume will be the parent''s minimum volume.
?	For all other volumes, the same rounding rules will apply based on the volume increment on the parent product.

Please see example below:

Parent''s Settings:
Minimum: 	5000
Increment:  1000

Volume on Autohedge transaction			Volume Hedged
1      - 2499							0
2500 - 5499							5000
5500 - 6499							6000');
INSERT INTO email([from],[to],subject,body) VALUES('dana.davis@enron.com', 'laynie.east@enron.com, lisa.king@enron.com, lisa.best@enron.com,', 'Leaving Early', 'FYI:  
If it''s ok with everyone''s needs, I would like to leave @4pm. If you think 
you will need my assistance past the 4 o''clock hour just let me know;  I''ll 
be more than willing to stay.');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'louise.kitchen@enron.com', '<<Concur Expense Document>> - CC02.06.02', 'The following expense report is ready for approval:

Employee Name: Christopher F. Calger
Status last changed by: Mollie E. Gustafson Ms
Expense Report Name: CC02.06.02
Report Total: $3,972.93
Amount Due Employee: $3,972.93


To approve this expense report, click on the following link for Concur Expense.
http://expensexms.enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('jeff.duff@enron.com', 'julie.johnson@enron.com', 'Work request', 'Julie,

Could you print off the current work request report by 1:30 today?

Gentlemen,

I''d like to review this today at 1:30 in our office.  Also, could you provide 
me with your activity reports so I can have Julie enter this information.

JD');
INSERT INTO email([from],[to],subject,body) VALUES('v.weldon@enron.com', 'gary.l.carrier@usa.dupont.com, scott.joyce@bankofamerica.com', 'Enron News', 'This could turn into something big.... 
http://biz.yahoo.com/rf/010129/n29305829.html');
INSERT INTO email([from],[to],subject,body) VALUES('mark.haedicke@enron.com', 'paul.simons@enron.com', 'Re: First Polish Deal!', 'Congrats!  Things seem to be building rapidly now on the Continent.  Mark');
INSERT INTO email([from],[to],subject,body) VALUES('e..carter@enron.com', 't..robinson@enron.com', 'FW: Producers Newsletter 9-24-2001', '
The producer lumber pricing sheet.
 -----Original Message-----
From: 	Johnson, Jay  
Sent:	Tuesday, October 16, 2001 3:42 PM
To:	Carter, Karen E.
Subject:	FW: Producers Newsletter 9-24-2001



 -----Original Message-----
From: 	Daigre, Sergai  
Sent:	Friday, September 21, 2001 8:33 PM
Subject:	Producers Newsletter 9-24-2001

 ');
INSERT INTO email([from],[to],subject,body) VALUES('david.delainey@enron.com', 'kenneth.lay@enron.com', 'Greater Houston Partnership', 'Ken, in response to the letter from Mr Miguel San Juan, my suggestion would 
be to offer up the Falcon for their use; however, given the tight time frame 
and your recent visit with Mr. Fox that it would be difficult for either you 
or me to participate.

I spoke to Max and he agrees with this approach.

I hope this meets with your approval.

Regards
Delainey');
INSERT INTO email([from],[to],subject,body) VALUES('lachandra.fenceroy@enron.com', 'lindy.donoho@enron.com', 'FW: Bus Applications Meeting Follow Up', 'Lindy,

Here is the original memo we discussed earlier.  Please provide any information that you may have.

Your cooperation is greatly appreciated.

Thanks,

lachandra.fenceroy@enron.com
713.853.3884
877.498.3401 Pager

 -----Original Message-----
From: 	Bisbee, Joanne  
Sent:	Wednesday, September 26, 2001 7:50 AM
To:	Fenceroy, LaChandra
Subject:	FW: Bus Applications Meeting Follow Up

Lachandra, Please get with David Duff today and see what this is about.  Who are our TW accounting business users?

 -----Original Message-----
From: 	Koh, Wendy  
Sent:	Tuesday, September 25, 2001 2:41 PM
To:	Bisbee, Joanne
Subject:	Bus Applications Meeting Follow Up

Lisa brought up a TW change effective Nov 1.  It involves eliminating a turnback surcharge.  I have no other information, but you might check with the business folks for any system changes required.

Wendy');
INSERT INTO email([from],[to],subject,body) VALUES('danny.mccarty@enron.com', 'fran.fagan@enron.com', 'RE: worksheets', 'Fran,
    If Julie''s merit needs to be lump sum, just move it over to that column.  Also, send me Eric Gadd''s sheets as well.  Thanks.
Dan

 -----Original Message-----
From: 	Fagan, Fran  
Sent:	Thursday, December 20, 2001 11:10 AM
To:	McCarty, Danny
Subject:	worksheets

As discussed, attached are your sheets for bonus and merit.

Thanks,

Fran Fagan
Sr. HR Rep
713.853.5219


 << File: McCartyMerit.xls >>  << File: mccartyBonusCommercial_UnP.xls >> 

');
INSERT INTO email([from],[to],subject,body) VALUES('bert.meyers@enron.com', 'shift.dl-portland@enron.com', 'OCTOBER SCHEDULE', 'TEAM,

PLEASE SEND ME ANY REQUESTS THAT YOU HAVE FOR OCTOBER.  SO FAR I HAVE THEM FOR LEAF.  I WOULD LIKE TO HAVE IT DONE BY THE 15TH OF THE MONTH.  ANY QUESTIONS PLEASE GIVE ME A CALL.

BERT');
INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'john.arnold@enron.com, bilal.bajwa@enron.com, john.griffith@enron.com,', 'TRV Notification:  (NG - PROPT P/L - 09/27/2001)', 'The report named: NG - PROPT P/L <http://trv.corp.enron.com/linkFromExcel.asp?report_cd=11&report_name=NG+-+PROPT+P/L&category_cd=5&category_name=FINANCIAL&toc_hide=1&sTV1=5&TV1Exp=Y&current_efct_date=09/27/2001>, published as of 09/27/2001 is now available for viewing on the website.');
INSERT INTO email([from],[to],subject,body) VALUES('patrice.mims@enron.com', 'calvin.eakins@enron.com', 'Re: Small business supply assistance', 'Hi Calvin


I spoke with Rickey (boy, is he long-winded!!).  Gave him the name of our 
credit guy, Russell Diamond.

Thank for your help!');
INSERT INTO email([from],[to],subject,body) VALUES('legal <.hall@enron.com>', 'stephanie.panus@enron.com', 'Termination update', 'City of Vernon and Salt River Project terminated their contracts.  I will fax these notices to you.');
INSERT INTO email([from],[to],subject,body) VALUES('d..steffes@enron.com', 'richard.shapiro@enron.com', 'EES / ENA Government Affairs Staffing & Outside Services', 'Rick --

Here is the information on staffing and outside services.  Call if you need anything else.

Jim

 ');
INSERT INTO email([from],[to],subject,body) VALUES('gelliott@industrialinfo.com', 'pcopello@industrialinfo.com', 'ECAAR (Gavin), WSCC (Diablo Canyon), & NPCC (Seabrook)', 'Dear Power Outage Database Customer, 
Attached you will find an excel document. The outages contained within are forced or rescheduled outages. Your daily delivery will still contain these outages. 
In addition to the two excel documents, there is a dbf file that is formatted like your daily deliveries you receive nightly. This will enable you to load the data into your regular database. Any questions please let me know. Thanks. 
Greg Elliott 
IIR, Inc. 
713-783-5147 x 3481 
outages@industrialinfo.com 
THE INFORMATION CONTAINED IN THIS E-MAIL IS LEGALLY PRIVILEGED AND CONFIDENTIAL INFORMATION INTENDED ONLY FOR THE USE OF THE INDIVIDUAL OR ENTITY NAMED ABOVE.  YOU ARE HEREBY NOTIFIED THAT ANY DISSEMINATION, DISTRIBUTION, OR COPY OF THIS E-MAIL TO UNAUTHORIZED ENTITIES IS STRICTLY PROHIBITED. IF YOU HAVE RECEIVED THIS 
E-MAIL IN ERROR, PLEASE DELETE IT.
 - OUTAGE.dbf 
 - 111201R.xls 
 - 111201.xls ');
INSERT INTO email([from],[to],subject,body) VALUES('enron.announcements@enron.com', 'all_ena_egm_eim@enron.com', 'EWS Brown Bag', 'MARK YOUR LUNCH CALENDARS NOW !

You are invited to attend the EWS Brown Bag Lunch Series

Featuring:   RAY BOWEN, COO

Topic:  Enron Industrial Markets

Thursday, March 15, 2001
11:30 am - 12:30 pm
EB 5 C2


You bring your lunch,           Limited Seating
We provide drinks and dessert.          RSVP  x 3-9610');
INSERT INTO email([from],[to],subject,body) VALUES('chris.germany@enron.com', 'ingrid.immer@williams.com', 'Re: About St Pauls', 'Sounds good to me.  I bet this is next to the Warick?? Hotel.




"Immer, Ingrid" <Ingrid.Immer@Williams.com> on 12/21/2000 11:48:47 AM
To: "''chris.germany@enron.com''" <chris.germany@enron.com>
cc:  
Subject: About St Pauls




 <<About St Pauls.url>>  
? 
?http://www.stpaulshouston.org/about.html 

Chris, 

I like the looks of this place.? What do you think about going here Christmas 
eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., 
among others.

Let me know.?? ii 

 - About St Pauls.url

');
INSERT INTO email([from],[to],subject,body) VALUES('nas@cpuc.ca.gov', 'skatz@sempratrading.com, kmccrea@sablaw.com, thompson@wrightlaw.com,', 'Reply Brief filed July 31, 2000', ' - CPUC01-#76371-v1-Revised_Reply_Brief__Due_today_7_31_.doc');
INSERT INTO email([from],[to],subject,body) VALUES('gascontrol@aglresources.com', 'dscott4@enron.com, lcampbel@enron.com', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder
As discussed in the Winter Operations Meeting on Sept.29,2000, 
E-Gas(Emergency Gas) will not be offered this winter as a service from AGLC.  
Marketers and Poolers can receive gas via Peaking and IBSS nominations(daisy 
chain) from other marketers up to the 6 p.m. Same Day 2 nomination cycle.
');
INSERT INTO email([from],[to],subject,body) VALUES('dutch.quigley@enron.com', 'rwolkwitz@powermerchants.com', '', ' 

Here is a goody for you');
INSERT INTO email([from],[to],subject,body) VALUES('ryan.o''rourke@enron.com', 'k..allen@enron.com, randy.bhatia@enron.com, frank.ermis@enron.com,', 'TRV Notification:  (West VaR - 11/07/2001)', 'The report named: West VaR <http://trv.corp.enron.com/linkFromExcel.asp?report_cd=36&report_name=West+VaR&category_cd=2&category_name=WEST&toc_hide=1&sTV1=2&TV1Exp=Y&current_efct_date=11/07/2001>, published as of 11/07/2001 is now available for viewing on the website.');
INSERT INTO email([from],[to],subject,body) VALUES('mjones7@txu.com', 'cstone1@txu.com, ggreen2@txu.com, timpowell@txu.com,', 'Enron / HPL Actuals for July 10, 2000', 'Teco Tap       10.000 / Enron ; 110.000 / HPL IFERC

LS HPL LSK IC       30.000 / Enron
');
INSERT INTO email([from],[to],subject,body) VALUES('susan.pereira@enron.com', 'kkw816@aol.com', 'soccer practice', 'Kathy-

Is it safe to assume that practice is cancelled for tonight??

Susan Pereira');
INSERT INTO email([from],[to],subject,body) VALUES('mark.whitt@enron.com', 'barry.tycholiz@enron.com', 'Huber Internal Memo', 'Please look at this.  I didn''t know how deep to go with the desk.  Do you think this works.

 ');
INSERT INTO email([from],[to],subject,body) VALUES('m..forney@enron.com', 'george.phillips@enron.com', '', 'George,
Give me a call and we will further discuss opportunities on the 13st floor.

Thanks,
JMForney
3-7160');
INSERT INTO email([from],[to],subject,body) VALUES('brad.mckay@enron.com', 'angusmcka@aol.com', 'Re: (no subject)', 'not yet');
INSERT INTO email([from],[to],subject,body) VALUES('adam.bayer@enron.com', 'jonathan.mckay@enron.com', 'FW: Curve Fetch File', 'Here is the curve fetch file sent to me.  It has plenty of points in it.  If you give me a list of which ones you need we may be able to construct a secondary worksheet to vlookup the values.

adam
35227


 -----Original Message-----
From: 	Royed, Jeff  
Sent:	Tuesday, September 25, 2001 11:37 AM
To:	Bayer, Adam
Subject:	Curve Fetch File

Let me know if it works.   It may be required to have a certain version of Oracle for it to work properly.

 

Jeff Royed
Enron 
Energy Operations
Phone: 713-853-5295');
INSERT INTO email([from],[to],subject,body) VALUES('matt.smith@enron.com', 'yan.wang@enron.com', 'Report Formats', 'Yan,

The merged reports look great.  I believe the only orientation changes are to 
"unmerge" the following six reports:  

31 Keystone Receipts
15 Questar Pipeline
40 Rockies Production
22 West_2
23 West_3
25 CIG_WIC

The orientation of the individual reports should be correct.  Thanks.

Mat

PS.  Just a reminder to add the "*" by the title of calculated points.');
INSERT INTO email([from],[to],subject,body) VALUES('michelle.lokay@enron.com', 'jimboman@bigfoot.com', 'Egyptian Festival', '---------------------- Forwarded by Michelle Lokay/ET&S/Enron on 09/07/2000 
10:08 AM ---------------------------


"Karkour, Randa" <Randa.Karkour@COMPAQ.com> on 09/07/2000 09:01:04 AM
To: "''Agheb (E-mail)" <Agheb@aol.com>, "Leila Mankarious (E-mail)" 
<Leila_Mankarious@mhhs.org>, "''Marymankarious (E-mail)" 
<marymankarious@aol.com>, "Michelle lokay (E-mail)" <mlokay@enron.com>, "Ramy 
Mankarious (E-mail)" <Mankarious@aol.com>
cc:  

Subject: Egyptian Festival


 <<Egyptian Festival.url>>

 http://www.egyptianfestival.com/

 - Egyptian Festival.url
');
INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'sherry.dawson@enron.com', 'Urgent!!! --- New EAST books', 'This has to be done..................................

Thanks
---------------------- Forwarded by Errol McLaughlin/Corp/Enron on 12/20/2000 
08:39 AM ---------------------------
   
	
	
	From:  William Kelly @ ECT                           12/20/2000 08:31 AM
	

To: Kam Keiser/HOU/ECT@ECT, Darron C Giron/HOU/ECT@ECT, David 
Baumbach/HOU/ECT@ECT, Errol McLaughlin/Corp/Enron@ENRON
cc: Kimat Singla/HOU/ECT@ECT, Kulvinder Fowler/NA/Enron@ENRON, Kyle R 
Lilly/HOU/ECT@ECT, Jeff Royed/Corp/Enron@ENRON, Alejandra 
Chavez/NA/Enron@ENRON, Crystal Hyde/HOU/ECT@ECT 

Subject: New EAST books

We have new book names in TAGG for our intramonth portfolios and it is 
extremely important that any deal booked to the East is communicated quickly 
to someone on my team.  I know it will take some time for the new names to 
sink in and I do not want us to miss any positions or P&L.  

Thanks for your help on this.

New:
Scott Neal :         East Northeast
Dick Jenkins:     East Marketeast

WK 
');
INSERT INTO email([from],[to],subject,body) VALUES('david.forster@enron.com', 'eol.wide@enron.com', 'Change to Stack Manager', 'Effective immediately, there is a change to the Stack Manager which will 
affect any Inactive Child.

An inactive Child with links to Parent products will not have their 
calculated prices updated until the Child product is Activated.

When the Child Product is activated, the price will be recalculated and 
updated BEFORE it is displayed on the web.

This means that if you are inputting a basis price on a Child product, you 
will not see the final, calculated price until you Activate the product, at 
which time the customer will also see it.

If you have any questions, please contact the Help Desk on:

Americas: 713 853 4357
Europe: + 44 (0) 20 7783 7783
Asia/Australia: +61 2 9229 2300

Dave');
INSERT INTO email([from],[to],subject,body) VALUES('vince.kaminski@enron.com', 'jhh1@email.msn.com', 'Re: Light reading - see pieces beginning on page 7', 'John,

I saw it. Very interesting.

Vince





"John H Herbert" <jhh1@email.msn.com> on 07/28/2000 08:38:08 AM
To: "Vince J Kaminski" <Vince_J_Kaminski@enron.com>
cc:  
Subject: Light reading - see pieces beginning on page 7


Cheers and have a nice weekend,


JHHerbert




 - gd000728.pdf



');
INSERT INTO email([from],[to],subject,body) VALUES('matthew.lenhart@enron.com', 'mmmarcantel@equiva.com', 'RE:', 'i will try to line up a pig for you ');
INSERT INTO email([from],[to],subject,body) VALUES('jae.black@enron.com', 'claudette.harvey@enron.com, chaun.roberts@enron.com, judy.martinez@enron.com,', 'Disaster Recovery Equipment', 'As a reminder...there are several pieces of equipment that are set up on the 30th Floor, as well as on our floor, for the Disaster Recovery Team.  PLEASE DO NOT TAKE, BORROW OR USE this equipment.  Should you need to use another computer system, other than yours, or make conference calls please work with your Assistant to help find or set up equipment for you to use.

Thanks for your understanding in this matter.

T.Jae Black
East Power Trading
Assistant to Kevin Presto
off. 713-853-5800
fax 713-646-8272
cell 713-539-4760');
INSERT INTO email([from],[to],subject,body) VALUES('eric.bass@enron.com', 'dale.neuner@enron.com', '5 X 24', 'Dale,

Have you heard anything more on the 5 X 24s?  We would like to get this 
product out ASAP.


Thanks,

Eric');
INSERT INTO email([from],[to],subject,body) VALUES('messenger@smartreminders.com', 'm..tholt@enron.com', '10% Coupon - PrintPal Printer Cartridges - 100% Guaranteed', '[IMAGE]
[IMAGE][IMAGE][IMAGE] 
Dear  SmartReminders Member,
       [IMAGE]         [IMAGE]        [IMAGE]     [IMAGE]    [IMAGE]    [IMAGE]        [IMAGE]      [IMAGE]     	


  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

We respect  your privacy and are a Certified Participant of the BBBOnLine
 Privacy Program.  To be removed from future offers,click  here. 
SmartReminders.com  is a permission based service. To unsubscribe click  here .  ');
INSERT INTO email([from],[to],subject,body) VALUES('benjamin.rogers@enron.com', 'mark.bernstein@enron.com', '', 'The guy you are talking about left CIN under a "cloud of suspicion" sort of 
speak.  He was the one who got into several bad deals and PPA''s in California 
for CIN, thus he left on a bad note.  Let me know if you need more detail 
than that, I felt this was the type of info you were looking for.  Thanks!
Ben');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'michelle.cash@enron.com', 'Expense Report Receipts Not Received', 'Employee Name: Michelle Cash
Report Name:   Houston Cellular 8-11-01
Report Date:   12/13/01
Report ID:     594D37C9ED2111D5B452
Submitted On:  12/13/01

You are only allowed 2 reports with receipts outstanding.  Your expense reports will not be paid until you meet this requirement.');
INSERT INTO email([from],[to],subject,body) VALUES('susan.mara@enron.com', 'ray.alvarez@enron.com, mark.palmer@enron.com, karen.denne@enron.com,', 'CAISO Emergency Motion -- to discontinue market-based rates for', 'FYI.  the latest broadside against the generators.

Sue Mara
Enron Corp.
Tel: (415) 782-7802
Fax:(415) 782-7854
----- Forwarded by Susan J Mara/NA/Enron on 06/08/2001 12:24 PM -----


	"Milner, Marcie" <MMilner@coral-energy.com> 06/08/2001 11:13 AM 	   To: "''smara@enron.com''" <smara@enron.com>  cc:   Subject: CAISO Emergency Motion	


Sue, did you see this emergency motion the CAISO filed today?  Apparently
they are requesting that FERC discontinue market-based rates immediately and
grant refunds plus interest on the difference between cost-based rates and
market revenues received back to May 2000.  They are requesting the
commission act within 14 days.  Have you heard anything about what they are
doing?

Marcie

http://www.caiso.com/docs/2001/06/08/200106081005526469.pdf 
');
INSERT INTO email([from],[to],subject,body) VALUES('fletcher.sturm@enron.com', 'eloy.escobar@enron.com', 'Re: General Brinks Position Meeting', 'Eloy,

Who is General Brinks?

Fletch');
INSERT INTO email([from],[to],subject,body) VALUES('nailia.dindarova@enron.com', 'richard.shapiro@enron.com', 'Documents for Mark Frevert (on EU developments and lessons from', 'Rick,

Here are the documents that Peter has prepared for Mark Frevert. 

Nailia
---------------------- Forwarded by Nailia Dindarova/LON/ECT on 25/06/2001 
16:36 ---------------------------


Nailia Dindarova
25/06/2001 15:36
To: Michael Brown/Enron@EUEnronXGate
cc: Ross Sankey/Enron@EUEnronXGate, Eric Shaw/ENRON@EUEnronXGate, Peter 
Styles/LON/ECT@ECT 

Subject: Documents for Mark Frevert (on EU developments and lessons from 
California)

Michael,


These are the documents that Peter promised to give to you for Mark Frevert. 
He has now handed them to him in person but asked me to transmit them 
electronically to you, as well as Eric and Ross.

Nailia





');
INSERT INTO email([from],[to],subject,body) VALUES('peggy.a.kostial@accenture.com', 'dave.samuels@enron.com', 'EOL-Accenture Deal Sheet', 'Dave -

Attached are our comments and suggested changes. Please call to review.

On the time line for completion, we have four critical steps to complete:
     Finalize market analysis to refine business case, specifically
     projected revenue stream
     Complete counterparty surveying, including targeting 3 CPs for letters
     of intent
     Review Enron asset base for potential reuse/ licensing
     Contract negotiations

Joe will come back to us with an updated time line, but it is my
expectation that we are still on the same schedule (we just begun week
three) with possibly a week or so slippage.....contract negotiations will
probably be the critical path.

We will send our cut at the actual time line here shortly. Thanks,

Peggy

(See attached file: accenture-dealpoints v2.doc)
 - accenture-dealpoints v2.doc ');
INSERT INTO email([from],[to],subject,body) VALUES('thomas.martin@enron.com', 'thomas.martin@enron.com', 'Re: Guadalupe Power Partners LP', '---------------------- Forwarded by Thomas A Martin/HOU/ECT on 03/20/2001 
03:49 PM ---------------------------


Thomas A Martin
10/11/2000 03:55 PM
To: Patrick Wade/HOU/ECT@ECT
cc:  
Subject: Re: Guadalupe Power Partners LP  

The deal is physically served at Oasis Waha or Oasis Katy and is priced at 
either HSC, Waha or Katytailgate GD at buyers option three days prior to 
NYMEX  close.

');
INSERT INTO email([from],[to],subject,body) VALUES('judy.townsend@enron.com', 'dan.junek@enron.com, chris.germany@enron.com', 'Columbia Distribution''s Capacity Available for Release - Sum', '---------------------- Forwarded by Judy Townsend/HOU/ECT on 03/09/2001 11:04 
AM ---------------------------


agoddard@nisource.com on 03/08/2001 09:16:57 AM
To: "        -         *Koch, Kent" <kkoch@nisource.com>, "        -         
*Millar, Debra" <dmillar@nisource.com>, "        -         *Burke, Lynn" 
<lburke@nisource.com>
cc: "        -         *Heckathorn, Tom" <theckathorn@nisource.com> 
Subject: Columbia Distribution''s Capacity Available for Release - Sum


Attached is Columbia Distribution''s notice of capacity available for release
for
the summer of 2001 (Apr. 2001 through Oct. 2001).

Please note that the deadline for bids is 3:00pm EST on March 20, 2001.

If you have any questions, feel free to contact any of the representatives
listed
at the bottom of the attachment.

Aaron Goddard




 - 2001Summer.doc
');
INSERT INTO email([from],[to],subject,body) VALUES('rhonda.denton@enron.com', 'tim.belden@enron.com, dana.davis@enron.com, genia.fitzgerald@enron.com,', 'Split Rock Energy LLC', 'We have received the executed EEI contract from this CP dated 12/12/2000.  
Copies will be distributed to Legal and Credit.');
INSERT INTO email([from],[to],subject,body) VALUES('kerrymcelroy@dwt.com', 'jack.speer@alcoa.com, crow@millernash.com, michaelearly@earthlink.net,', 'Oral Argument Request', ' - Oral Argument Request.doc');
INSERT INTO email([from],[to],subject,body) VALUES('mike.carson@enron.com', 'rlmichaelis@hormel.com', '', 'Did you come in town this wk end..... My new number at our house is : 
713-668-3712...... my cell # is 281-381-7332

the kid');
INSERT INTO email([from],[to],subject,body) VALUES('cooper.richey@enron.com', 'trycooper@hotmail.com', 'FW: Contact Info', '

-----Original Message-----
From: Punja, Karim 
Sent: Thursday, December 13, 2001 2:35 PM
To: Richey, Cooper
Subject: Contact Info


Cooper,

Its been a real pleasure working with you (even though it was for only a small amount of time)
I hope we can stay in touch.

Home# 234-0249
email: kpunja@hotmail.com

Take Care, 

Karim.
  ');
INSERT INTO email([from],[to],subject,body) VALUES('bjm30@earthlink.net', 'mcguinn.k@enron.com, mcguinn.ian@enron.com, mcguinn.stephen@enron.com,', 'email address change', 'Hello all.

I haven''t talked to many of you via email recently but I do want to give you
my new address for your email file:

    bjm30@earthlink.net

I hope all is well.

Brian McGuinn');
INSERT INTO email([from],[to],subject,body) VALUES('shelley.corman@enron.com', 'steve.hotte@enron.com', 'Flat Panels', 'Can you please advise what is going on with the flat panels that we had planned to distribute to our gas logistics team.  It was in the budget and we had the okay, but now I''m hearing there is some hold-up & the units are stored on 44.

Shelley');
INSERT INTO email([from],[to],subject,body) VALUES('sara.davidson@enron.com', 'john.schwartzenburg@enron.com, scott.dieball@enron.com, recipients@enron.com,', '2001 Enron Law Conference (Distribution List 2)', '    Enron Law Conference

San Antonio, Texas    May 2-4, 2001    Westin Riverwalk

                   See attached memo for more details!!


? Registration for the law conference this year will be handled through an 
Online RSVP Form on the Enron Law Conference Website at 
http://lawconference.corp.enron.com.  The website is still under construction 
and will not be available until Thursday, March 15, 2001.  

? We will send you another e-mail to confirm when the Law Conference Website 
is operational. 

? Please complete the Online RSVP Form as soon as it is available  and submit 
it no later than Friday, March 30th.  




');
INSERT INTO email([from],[to],subject,body) VALUES('tori.kuykendall@enron.com', 'heath.b.taylor@accenture.com', 'Re:', 'hey - thats funny about john - he definitely remembers him - i''ll call pat 
and let him know - we are coming on saturday - i just havent had a chance to 
call you guys back --  looking forward to it -- i probably need the 
directions again though');
INSERT INTO email([from],[to],subject,body) VALUES('darron.giron@enron.com', 'bryce.baxter@enron.com', 'Re: Feedback for Audrey Cook', 'Bryce,

I''ll get it done today.  

DG    3-9573


   
	
	
	From:  Bryce Baxter                           06/12/2000 07:15 PM
	

To: Darron C Giron/HOU/ECT@ECT
cc:  
Subject: Feedback for Audrey Cook

You were identified as a reviewer for Audrey Cook.  If possible, could you 
complete her feedback by end of business Wednesday?  It will really help me 
in the PRC process to have your input.  Thanks.

');
INSERT INTO email([from],[to],subject,body) VALUES('casey.evans@enron.com', 'stephanie.sever@enron.com', 'Gas EOL ID', 'Stephanie,

In conjunction with the recent movement of several power traders, they are changing the names of their gas books as well.  The names of the new gas books and traders are as follows:

PWR-NG-LT-SPP:  Mike Carson
PWR-NG-LT-SERC:  Jeff King

If you need to know their power desk to map their ID to their gas books, those desks are as follows:

EPMI-LT-SPP:  Mike Carson
EPMI-LT-SERC:  Jeff King

I will be in training this afternoon, but will be back when class is over.  Let me know if you have any questions.

Thanks for your help!
Casey');
INSERT INTO email([from],[to],subject,body) VALUES('darrell.schoolcraft@enron.com', 'david.roensch@enron.com, kimberly.watson@enron.com, michelle.lokay@enron.com,', 'Postings', 'Please see the attached.


ds


  

 ');
INSERT INTO email([from],[to],subject,body) VALUES('mcominsky@aol.com', 'cpatman@bracepatt.com, james_derrick@enron.com', 'Jurisprudence Luncheon', 'Carrin & Jim --

It was an honor and a pleasure to meet both of you yesterday.  I know we will
have fun working together on this very special event.

Jeff left the jurisprudence luncheon lists for me before he left on vacation.
 I wasn''t sure whether he transmitted them to you as well.  Would you please
advise me if you would like them sent to you?  I can email the MS Excel files
or I can fax the hard copies to you.   Please advise what is most convenient.

I plan to be in town through the holidays and can be reached by phone, email,
or cell phone at any time.  My cell phone number is 713/705-4829.

Thanks again for your interest in the ADL''s work.  Martin.

Martin B. Cominsky
Director, Southwest Region
Anti-Defamation League
713/627-3490, ext. 122
713/627-2011 (fax)
MCominsky@aol.com');
INSERT INTO email([from],[to],subject,body) VALUES('phillip.love@enron.com', 'todagost@utmb.edu, gbsonnta@utmb.edu', 'New President', 'I had a little bird put a word in my ear.  Is there any possibility for Ben 
Raimer to be Bush''s secretary of HHS?  Just curious about that infamous UTMB 
rumor mill.  Hope things are well, happy holidays.
PL');
INSERT INTO email([from],[to],subject,body) VALUES('marie.heard@enron.com', 'ehamilton@fna.com', 'ISDA Master Agreement', 'Erin:

Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together with Paragraph 13 to the ISDA Credit Support Annex.  Please let me know if you need anything else.  We look forward to hearing your comments.

Marie

Marie Heard
Senior Legal Specialist
Enron North America Corp.
Phone:  (713) 853-3907
Fax:  (713) 646-3490
marie.heard@enron.com

				 ');
INSERT INTO email([from],[to],subject,body) VALUES('andrea.ring@enron.com', 'beverly.beaty@enron.com', 'Re: Tennessee Buy - Louis Dreyfus', 'Beverly -  once again thanks so much for your help on this.

           

                                                                     ');
INSERT INTO email([from],[to],subject,body) VALUES('karolyn.criado@enron.com', 'j..bonin@enron.com, felicia.case@enron.com, b..clapp@enron.com,', 'Price List week of Oct. 8-9, 2001', '
Please contact me if you have any questions regarding last weeks prices.

Thank you,
Karolyn Criado
3-9441


 

');
INSERT INTO email([from],[to],subject,body) VALUES('kevin.presto@enron.com', 'edward.baughman@enron.com, billy.braddock@enron.com', 'Associated', 'Please begin working on filling our Associated short position in 02.   I would like to take this risk off the books.

In addition, please find out what a buy-out of VEPCO would cost us.   With Rogers transitioning to run our retail risk management, I would like to clean up our customer positions.

We also need to continue to explore a JEA buy-out.

Thanks.');
INSERT INTO email([from],[to],subject,body) VALUES('stacy.dickson@enron.com', 'gregg.penman@enron.com', 'RE: Constellation TC 5-7-01', 'Gregg, 

I am at home with a sick baby.  (Lots of fun!)  I will call you about this 
tomorrow.

Stacy');
INSERT INTO email([from],[to],subject,body) VALUES('joe.quenet@enron.com', 'dfincher@utilicorp.com', '', 'hey big guy.....check this out.....

 w ww.gorelieberman-2000.com/');
INSERT INTO email([from],[to],subject,body) VALUES('k..allen@enron.com', 'jacqestc@aol.com', '', 'Jacques,

I sent you a fax of Kevin Kolb''s comments on the release.  The payoff on the note would be $36,248 ($36090(principal) + $158 (accrued interest)).
This is assuming we wrap this up on Tuesday.  

Please email to confirm that their changes are ok so I can set up a meeting on Tuesday to reach closure.

Phillip');
INSERT INTO email([from],[to],subject,body) VALUES('kourtney.nelson@enron.com', 'mike.swerzbin@enron.com', 'Adjusted L/R Balance', 'Mike,

I placed the adjusted L/R Balance on the Enronwest site.  It is under the "Staff/Kourtney Nelson".  There are two links:  

1)  "Adj L_R" is the same data/format from the weekly strategy meeting. 
2)  "New Gen 2001_2002" link has all of the supply side info that is used to calculate the L/R balance
	-Please note the Data Flag column, a value of "3" indicates the project was cancelled, on hold, etc and is not included in the calc.  

Both of these sheets are interactive Excel spreadsheets and thus you can play around with the data as you please.  Also, James Bruce is working to get his gen report on the web.  That will help with your access to information on new gen.

Please let me know if you have any questions or feedback,

Kourtney



Kourtney Nelson
Fundamental Analysis 
Enron North America
(503) 464-8280
kourtney.nelson@enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('d..thomas@enron.com', 'naveed.ahmed@enron.com', 'FW: Current Enron TCC Portfolio', '

-----Original Message-----
From: Grace, Rebecca M. 
Sent: Monday, December 17, 2001 9:44 AM
To: Thomas, Paul D.
Cc: Cashion, Jim; Allen, Thresa A.; May, Tom
Subject: RE: Current Enron TCC Portfolio


Paul,

I reviewed NY''s list.  I agree with all of their contracts numbers and mw amounts.

Call if you have any more questions.

Rebecca



 -----Original Message-----
From: 	Thomas, Paul D.  
Sent:	Monday, December 17, 2001 9:08 AM
To:	Grace, Rebecca M.
Subject:	FW: Current Enron TCC Portfolio

 << File: enrontccs.xls >> 
Rebecca,
Let me know if you see any differences.

Paul
X 3-0403
-----Original Message-----
From: Thomas, Paul D. 
Sent: Monday, December 17, 2001 9:04 AM
To: Ahmed, Naveed
Subject: FW: Current Enron TCC Portfolio




-----Original Message-----
From: Thomas, Paul D. 
Sent: Thursday, December 13, 2001 10:01 AM
To: Baughman, Edward D.
Subject: Current Enron TCC Portfolio


');
INSERT INTO email([from],[to],subject,body) VALUES('stephanie.panus@enron.com', 'william.bradford@enron.com, debbie.brackett@enron.com,', 'Coastal Merchant Energy/El Paso Merchant Energy', 'Coastal Merchant Energy, L.P. merged with and into El Paso Merchant Energy, 
L.P., effective February 1, 2001, with the surviving entity being El Paso 
Merchant Energy, L.P.  We currently have ISDA Master Agreements with both 
counterparties.  Please see the attached memo regarding the existing Masters 
and let us know which agreement should be terminated.

Thanks,
Stephanie
');
INSERT INTO email([from],[to],subject,body) VALUES('kam.keiser@enron.com', 'c..kenne@enron.com', 'RE: What about this too???', ' 

 -----Original Message-----
From: 	Kenne, Dawn C.  
Sent:	Wednesday, February 06, 2002 11:50 AM
To:	Keiser, Kam
Subject:	What about this too???


 << File: Netco Trader Matrix.xls >> 
 ');
INSERT INTO email([from],[to],subject,body) VALUES('chris.meyer@enron.com', 'joe.parks@enron.com', 'Centana', 'Talked to Chip.  We do need Cash Committe approval given the netting feature of your deal, which means Batch Funding Request.  Please update per my previous e-mail and forward.

Thanks

chris
x31666');
INSERT INTO email([from],[to],subject,body) VALUES('debra.perlingiere@enron.com', 'jworman@academyofhealth.com', '', 'Have a great weekend!   Happy Fathers Day!


Debra Perlingiere
Enron North America Corp.
1400 Smith Street, EB 3885
Houston, Texas 77002
dperlin@enron.com
Phone 713-853-7658
Fax  713-646-3490');
INSERT INTO email([from],[to],subject,body) VALUES('outlook.team@enron.com', '', 'Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia  &', 'CALENDAR ENTRY:	APPOINTMENT

Description:
	Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia  & Dir Rpts. - 4102

Date:		1/5/2001
Time:		9:00 AM - 10:00 AM (Central Standard Time)

Chairperson:	Outlook Migration Team

Detailed Description:');
INSERT INTO email([from],[to],subject,body) VALUES('diana.seifert@enron.com', 'mark.taylor@enron.com', 'Guest access Chile', 'Hello Mark,

Justin Boyd told me that your can help me with questions regarding Chile.
We got a request for guest access through MG.
The company is called Escondida and is a subsidiary of BHP Australia.

Please advise if I can set up a guest account or not.
F.Y.I.: MG is planning to put a "in w/h Chile" contract for Copper on-line as 
soon as Enron has done the due diligence for this country.
Thanks !


Best regards

Diana Seifert
EOL PCG');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'mark.whitt@enron.com', '<<Concur Expense Document>> - 121001', 'The Approval status has changed on the following report:

Status last changed by: Barry L. Tycholiz
Expense Report Name: 121001
Report Total: $198.98
Amount Due Employee: $198.98
Amount Approved: $198.98
Amount Paid: $0.00
Approval Status: Approved
Payment Status: Pending


To review this expense report, click on the following link for Concur Expense.
http://expensexms.enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('kevin.hyatt@enron.com', '', 'Technical Support', 'Outside the U.S., please refer to the list below:

Australia:
1800 678-515
support@palm-au.com

Canada:
1905 305-6530
support@palm.com

New Zealand:
0800 446-398
support@palm-nz.com

U.K.:
0171 867 0108
eurosupport@palm.3com.com

Please refer to the Worldwide Customer Support card for a complete technical support contact list.');
INSERT INTO email([from],[to],subject,body) VALUES('geoff.storey@enron.com', 'dutch.quigley@enron.com', 'RE:', 'duke contact?

 -----Original Message-----
From: 	Quigley, Dutch  
Sent:	Wednesday, October 31, 2001 10:14 AM
To:	Storey, Geoff
Subject:	RE: 

bp corp	Albert LaMore	281-366-4962

running the reports now


 -----Original Message-----
From: 	Storey, Geoff  
Sent:	Wednesday, October 31, 2001 10:10 AM
To:	Quigley, Dutch
Subject:	RE: 

give me a contact over there too
BP


 -----Original Message-----
From: 	Quigley, Dutch  
Sent:	Wednesday, October 31, 2001 9:42 AM
To:	Storey, Geoff
Subject:	

Coral	Jeff Whitnah	713-767-5374
Relaint	Steve McGinn	713-207-4000');
INSERT INTO email([from],[to],subject,body) VALUES('pete.davis@enron.com', 'pete.davis@enron.com', 'Start Date: 4/22/01; HourAhead hour: 3;  <CODESITE>', 'Start Date: 4/22/01; HourAhead hour: 3;  No ancillary schedules awarded.  
Variances detected.
Variances detected in Load schedule.

    LOG MESSAGES:

PARSING FILE -->> O:\Portland\WestDesk\California Scheduling\ISO Final 
Schedules\2001042203.txt

---- Load Schedule ----
$$$ Variance found in table tblLoads.
     Details: (Hour: 3 / Preferred:   1.92 / Final:   1.89)
  TRANS_TYPE: FINAL
  LOAD_ID: PGE4
  MKT_TYPE: 2
  TRANS_DATE: 4/22/01
  SC_ID: EPMI

');
INSERT INTO email([from],[to],subject,body) VALUES('john.postlethwaite@enron.com', 'john.zufferli@enron.com', 'Reference', 'John, hope things are going well up there for you. The big day is almost here for you and Jessica. I was wondering if I could use your name as a job reference if need be. I am just trying to get everything in order just in case something happens. 

John');
INSERT INTO email([from],[to],subject,body) VALUES('jeffrey.shankman@enron.com', 'lschiffm@jonesday.com', 'Re:', 'I saw you called on the cell this a.m.  Sorry I missed you.  (I was in the 
shower).  I have had a shitty week--I suspect my silence (not only to you, 
but others) after our phone call is a result of the week.  I''m seeing Glen at 
11:15....talk to you');
INSERT INTO email([from],[to],subject,body) VALUES('litebytz@enron.com', '', 'Lite Bytz RSVP', '
This week''s Lite Bytz presentation will feature the following TOOLZ speaker:

Richard McDougall
Solaris 8
Thursday, June 7, 2001

If you have not already signed up, please RSVP via email to litebytz@enron.com by the end of the day Tuesday, June 5, 2001.

*Remember: this is now a Brown Bag Event--so bring your lunch and we will provide cookies and drinks.

Click below for more details.

http://home.enron.com:84/messaging/litebytztoolzprint.jpg');
    COMMIT;
  }
} {}

###############################################################################
# Everything above just builds an interesting test database.  The actual
# tests come after this comment.
###############################################################################

do_test fts1c-1.2 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark'
  }
} {6 17 25 38 40 42 73 74}
do_test fts1c-1.3 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'susan'
  }
} {24 40}
do_test fts1c-1.4 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark susan'
  }
} {40}
do_test fts1c-1.5 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'susan mark'
  }
} {40}
do_test fts1c-1.6 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH '"mark susan"'
  }
} {}
do_test fts1c-1.7 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark -susan'
  }
} {6 17 25 38 42 73 74}
do_test fts1c-1.8 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH '-mark susan'
  }
} {24}
do_test fts1c-1.9 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark OR susan'
  }
} {6 17 24 25 38 40 42 73 74}

# Some simple tests of the automatic "offsets(email)" column.  In the sample
# data set above, only one message, number 20, contains the words
# "gas" and "reminder" in both body and subject.
#
do_test fts1c-2.1 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}
do_test fts1c-2.2 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'subject:gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8 3 1 54 8}}
do_test fts1c-2.3 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'body:gas reminder'
  }
} {20 {2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}
do_test fts1c-2.4 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE subject MATCH 'gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8}}
do_test fts1c-2.5 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH 'gas reminder'
  }
} {20 {3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}

# Document 32 contains 5 instances of the world "child".  But only
# 3 of them are paired with "product".  Make sure only those instances
# that match the phrase appear in the offsets(email) list.
#
do_test fts1c-3.1 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH 'child product' AND +rowid=32
  }
} {32 {3 0 94 5 3 0 114 5 3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7 3 1 493 7}}
do_test fts1c-3.2 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH '"child product"'
  }
} {32 {3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7}}

# Snippet generator tests
#
do_test fts1c-4.1 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'subject:gas reminder'
  }
} {{Alert Posted 10:00 AM November 20,2000: E-<b>GAS</b> Request <b>Reminder</b>}}
do_test fts1c-4.2 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'christmas candlelight'
  }
} {{<b>...</b> place.? What do you think about going here <b>Christmas</b> 
eve?? They have an 11:00 a.m. service and a <b>candlelight</b> service at 5:00 p.m., 
among others. <b>...</b>}}

do_test fts1c-4.3 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'deal sheet potential reuse'
  }
} {{EOL-Accenture <b>Deal</b> <b>Sheet</b> <b>...</b> intent
     Review Enron asset base for <b>potential</b> <b>reuse</b>/ licensing
     Contract negotiations <b>...</b>}}
do_test fts1c-4.4 {
  execsql {
    SELECT snippet(email,'<<<','>>>',' ') FROM email
     WHERE email MATCH 'deal sheet potential reuse'
  }
} {{EOL-Accenture <<<Deal>>> <<<Sheet>>>  intent
     Review Enron asset base for <<<potential>>> <<<reuse>>>/ licensing
     Contract negotiations  }}
do_test fts1c-4.5 {
  execsql {
    SELECT snippet(email,'<<<','>>>',' ') FROM email
     WHERE email MATCH 'first things'
  }
} {{Re: <<<First>>> Polish Deal!  Congrats!  <<<Things>>> seem to be building rapidly now on the  }}
do_test fts1c-4.6 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'chris is here'
  }
} {{<b>chris</b>.germany@enron.com <b>...</b> Sounds good to me.  I bet this <b>is</b> next to the Warick?? Hotel. <b>...</b> place.? What do you think about going <b>here</b> Christmas 
eve?? They have an 11:00 a.m. <b>...</b>}}
do_test fts1c-4.7 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH '"pursuant to"'
  }
} {{Erin:

<b>Pursuant</b> <b>to</b> your request, attached are the Schedule to <b>...</b>}}
do_test fts1c-4.8 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'ancillary load davis'
  }
} {{pete.<b>davis</b>@enron.com <b>...</b> Start Date: 4/22/01; HourAhead hour: 3;  No <b>ancillary</b> schedules awarded.  
Variances detected.
Variances detected in <b>Load</b> schedule.

    LOG MESSAGES:

PARSING <b>...</b>}}

# Combinations of AND and OR operators:
#
do_test fts1c-5.1 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'questar enron OR com'
  }
} {{matt.smith@<b>enron</b>.<b>com</b> <b>...</b> six reports:  

31 Keystone Receipts
15 <b>Questar</b> Pipeline
40 Rockies Production
22 West_2 <b>...</b>}}
do_test fts1c-5.2 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'enron OR com questar'
  }
} {{matt.smith@<b>enron</b>.<b>com</b> <b>...</b> six reports:  

31 Keystone Receipts
15 <b>Questar</b> Pipeline
40 Rockies Production
22 West_2 <b>...</b>}}

finish_test

Added test/fts1d.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2006 October 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS1 module, and in particular
# the Porter stemmer.
#
# $Id: fts1d.test,v 1.1 2006/10/01 18:41:21 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

do_test fts1d-1.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts1(content, tokenize porter);
    INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping');
    SELECT rowid FROM t1 WHERE content MATCH 'run jump';
  }
} {1}
do_test fts1d-1.2 {
  execsql {
    SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'run jump';
  }
} {{<b>running</b> and <b>jumping</b>}}
do_test fts1d-1.3 {
  execsql {
    INSERT INTO t1(rowid, content) 
          VALUES(2, 'abcdefghijklmnopqrstuvwyxz');
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz'
  }
} {2 <b>abcdefghijklmnopqrstuvwyxz</b>}
do_test fts1d-1.4 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijXXXXqrstuvwyxz'
  }
} {2 <b>abcdefghijklmnopqrstuvwyxz</b>}
do_test fts1d-1.5 {
  execsql {
    INSERT INTO t1(rowid, content) 
          VALUES(3, 'The value is 123456789');
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123789'
  }
} {3 {The value is <b>123456789</b>}}
do_test fts1d-1.6 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123000000789'
  }
} {3 {The value is <b>123456789</b>}}


finish_test

Added test/fts1e.test.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing deletions in the FTS1 module.
#
# $Id: fts1e.test,v 1.1 2006/10/19 23:28:35 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Construct a full-text search table containing keywords which are the
# ordinal numbers of the bit positions set for a sequence of integers,
# which are used for the rowid.  There are a total of 30 INSERT and
# DELETE statements, so that we'll test both the segmentMerge() merge
# (over the first 16) and the termSelect() merge (over the level-1
# segment and 14 level-0 segments).
db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'one');
  INSERT INTO t1 (rowid, content) VALUES(2, 'two');
  INSERT INTO t1 (rowid, content) VALUES(3, 'one two');
  INSERT INTO t1 (rowid, content) VALUES(4, 'three');
  DELETE FROM t1 WHERE rowid = 1;
  INSERT INTO t1 (rowid, content) VALUES(5, 'one three');
  INSERT INTO t1 (rowid, content) VALUES(6, 'two three');
  INSERT INTO t1 (rowid, content) VALUES(7, 'one two three');
  DELETE FROM t1 WHERE rowid = 4;
  INSERT INTO t1 (rowid, content) VALUES(8, 'four');
  INSERT INTO t1 (rowid, content) VALUES(9, 'one four');
  INSERT INTO t1 (rowid, content) VALUES(10, 'two four');
  DELETE FROM t1 WHERE rowid = 7;
  INSERT INTO t1 (rowid, content) VALUES(11, 'one two four');
  INSERT INTO t1 (rowid, content) VALUES(12, 'three four');
  INSERT INTO t1 (rowid, content) VALUES(13, 'one three four');
  DELETE FROM t1 WHERE rowid = 10;
  INSERT INTO t1 (rowid, content) VALUES(14, 'two three four');
  INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four');
  INSERT INTO t1 (rowid, content) VALUES(16, 'five');
  DELETE FROM t1 WHERE rowid = 13;
  INSERT INTO t1 (rowid, content) VALUES(17, 'one five');
  INSERT INTO t1 (rowid, content) VALUES(18, 'two five');
  INSERT INTO t1 (rowid, content) VALUES(19, 'one two five');
  DELETE FROM t1 WHERE rowid = 16;
  INSERT INTO t1 (rowid, content) VALUES(20, 'three five');
  INSERT INTO t1 (rowid, content) VALUES(21, 'one three five');
  INSERT INTO t1 (rowid, content) VALUES(22, 'two three five');
  DELETE FROM t1 WHERE rowid = 19;
  DELETE FROM t1 WHERE rowid = 22;
}

do_test fts1f-1.1 {
  execsql {SELECT COUNT(*) FROM t1}
} {14}

do_test fts1e-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {3 5 9 11 15 17 21}

do_test fts1e-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'}
} {2 3 6 11 14 15 18}

do_test fts1e-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'}
} {5 6 12 14 15 20 21}

do_test fts1e-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'}
} {8 9 11 12 14 15}

do_test fts1e-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'}
} {17 18 20 21}

finish_test

Added test/fts1f.test.





















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing updates in the FTS1 module.
#
# $Id: fts1f.test,v 1.2 2007/02/23 00:14:06 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Construct a full-text search table containing keywords which are the
# ordinal numbers of the bit positions set for a sequence of integers,
# which are used for the rowid.  There are a total of 31 INSERT,
# UPDATE, and DELETE statements, so that we'll test both the
# segmentMerge() merge (over the first 16) and the termSelect() merge
# (over the level-1 segment and 15 level-0 segments).
db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'one');
  INSERT INTO t1 (rowid, content) VALUES(2, 'two');
  INSERT INTO t1 (rowid, content) VALUES(3, 'one two');
  INSERT INTO t1 (rowid, content) VALUES(4, 'three');
  INSERT INTO t1 (rowid, content) VALUES(5, 'one three');
  INSERT INTO t1 (rowid, content) VALUES(6, 'two three');
  INSERT INTO t1 (rowid, content) VALUES(7, 'one two three');
  DELETE FROM t1 WHERE rowid = 4;
  INSERT INTO t1 (rowid, content) VALUES(8, 'four');
  UPDATE t1 SET content = 'update one three' WHERE rowid = 1;
  INSERT INTO t1 (rowid, content) VALUES(9, 'one four');
  INSERT INTO t1 (rowid, content) VALUES(10, 'two four');
  DELETE FROM t1 WHERE rowid = 7;
  INSERT INTO t1 (rowid, content) VALUES(11, 'one two four');
  INSERT INTO t1 (rowid, content) VALUES(12, 'three four');
  INSERT INTO t1 (rowid, content) VALUES(13, 'one three four');
  DELETE FROM t1 WHERE rowid = 10;
  INSERT INTO t1 (rowid, content) VALUES(14, 'two three four');
  INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four');
  UPDATE t1 SET content = 'update two five' WHERE rowid = 8;
  INSERT INTO t1 (rowid, content) VALUES(16, 'five');
  DELETE FROM t1 WHERE rowid = 13;
  INSERT INTO t1 (rowid, content) VALUES(17, 'one five');
  INSERT INTO t1 (rowid, content) VALUES(18, 'two five');
  INSERT INTO t1 (rowid, content) VALUES(19, 'one two five');
  DELETE FROM t1 WHERE rowid = 16;
  INSERT INTO t1 (rowid, content) VALUES(20, 'three five');
  INSERT INTO t1 (rowid, content) VALUES(21, 'one three five');
  INSERT INTO t1 (rowid, content) VALUES(22, 'two three five');
  DELETE FROM t1 WHERE rowid = 19;
  UPDATE t1 SET content = 'update' WHERE rowid = 15;
}

do_test fts1f-1.1 {
  execsql {SELECT COUNT(*) FROM t1}
} {16}

do_test fts1f-2.0 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'update'}
} {1 8 15}

do_test fts1f-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 9 11 17 21}

do_test fts1f-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'}
} {2 3 6 8 11 14 18 22}

do_test fts1f-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'}
} {1 5 6 12 14 20 21 22}

do_test fts1f-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'}
} {9 11 12 14}

do_test fts1f-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'}
} {8 17 18 20 21 22}

finish_test

Added test/fts1i.test.

















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# 2007 January 17
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite fts1 library.  The
# focus here is testing handling of UPDATE when using UTF-16-encoded
# databases.
#
# $Id: fts1i.test,v 1.2 2007/01/24 03:43:20 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}


# Return the UTF-16 representation of the supplied UTF-8 string $str.
# If $nt is true, append two 0x00 bytes as a nul terminator.
# NOTE(shess) Copied from capi3.test.
proc utf16 {str {nt 1}} {
  set r [encoding convertto unicode $str]
  if {$nt} {
    append r "\x00\x00"
  }
  return $r
}

db eval {
  PRAGMA encoding = "UTF-16le";
  CREATE VIRTUAL TABLE t1 USING fts1(content);
}

do_test fts1i-1.0 {
  execsql {PRAGMA encoding}
} {UTF-16le}

do_test fts1i-1.1 {
  execsql {INSERT INTO t1 (rowid, content) VALUES(1, 'one')}
  execsql {SELECT content FROM t1 WHERE rowid = 1}
} {one}

do_test fts1i-1.2 {
  set sql "INSERT INTO t1 (rowid, content) VALUES(2, 'two')"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 2}
} {two}

do_test fts1i-1.3 {
  set sql "INSERT INTO t1 (rowid, content) VALUES(3, 'three')"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  set sql "UPDATE t1 SET content = 'trois' WHERE rowid = 3"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 3}
} {trois}

do_test fts1i-1.4 {
  set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(4, 'four')}]
  set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 4}
} {four}

do_test fts1i-1.5 {
  set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(5, 'five')}]
  set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  set sql "UPDATE t1 SET content = 'cinq' WHERE rowid = 5"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 5}
} {cinq}

finish_test

Added test/fts1j.test.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 2007 February 6
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  This
# tests creating fts1 tables in an attached database.
#
# $Id: fts1j.test,v 1.1 2007/02/07 01:01:18 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Clean up anything left over from a previous pass.
file delete -force test2.db
file delete -force test2.db-journal
sqlite3 db2 test2.db

db eval {
  CREATE VIRTUAL TABLE t3 USING fts1(content);
  INSERT INTO t3 (rowid, content) VALUES(1, "hello world");
}

db2 eval {
  CREATE VIRTUAL TABLE t1 USING fts1(content);
  INSERT INTO t1 (rowid, content) VALUES(1, "hello world");
  INSERT INTO t1 (rowid, content) VALUES(2, "hello there");
  INSERT INTO t1 (rowid, content) VALUES(3, "cruel world");
}

# This has always worked because the t1_* tables used by fts1 will be
# the defaults.
do_test fts1j-1.1 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    SELECT rowid FROM t1 WHERE t1 MATCH 'hello';
    DETACH DATABASE two;
  }
} {1 2}
# Make certain we're detached if there was an error.
catch {db eval {DETACH DATABASE two}}

# In older code, this appears to work fine, but the t2_* tables used
# by fts1 will be created in database 'main' instead of database
# 'two'.  It appears to work fine because the tables end up being the
# defaults, but obviously is badly broken if you hope to use things
# other than in the exact same ATTACH setup.
do_test fts1j-1.2 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    CREATE VIRTUAL TABLE two.t2 USING fts1(content);
    INSERT INTO t2 (rowid, content) VALUES(1, "hello world");
    INSERT INTO t2 (rowid, content) VALUES(2, "hello there");
    INSERT INTO t2 (rowid, content) VALUES(3, "cruel world");
    SELECT rowid FROM t2 WHERE t2 MATCH 'hello';
    DETACH DATABASE two;
  }
} {1 2}
catch {db eval {DETACH DATABASE two}}

# In older code, this broke because the fts1 code attempted to create
# t3_* tables in database 'main', but they already existed.  Normally
# this wouldn't happen without t3 itself existing, in which case the
# fts1 code would never be called in the first place.
do_test fts1j-1.3 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;

    CREATE VIRTUAL TABLE two.t3 USING fts1(content);
    INSERT INTO two.t3 (rowid, content) VALUES(2, "hello there");
    INSERT INTO two.t3 (rowid, content) VALUES(3, "cruel world");
    SELECT rowid FROM two.t3 WHERE t3 MATCH 'hello';

    DETACH DATABASE two;
  } db2
} {2}
catch {db eval {DETACH DATABASE two}}

catch {db2 close}
file delete -force test2.db

finish_test

Added test/fts1k.test.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 2007 March 28
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing isspace/isalnum/tolower problems with the
# FTS1 module.  Unfortunately, this code isn't a really principled set
# of tests, because it is impossible to know where new uses of these
# functions might appear.
#
# $Id: fts1k.test,v 1.2 2007/12/13 21:54:11 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

# Tests that startsWith() (calls isspace, tolower, isalnum) can handle
# hi-bit chars.  parseSpec() also calls isalnum here.
do_test fts1k-1.1 {
  execsql "CREATE VIRTUAL TABLE t1 USING fts1(content, \x80)"
} {}

# Additionally tests isspace() call in getToken(), and isalnum() call
# in tokenListToIdList().
do_test fts1k-1.2 {
  catch {
    execsql "CREATE VIRTUAL TABLE t2 USING fts1(content, tokenize \x80)"
  }
  sqlite3_errmsg $DB
} "unknown tokenizer: \x80"

# Additionally test final isalnum() in startsWith().
do_test fts1k-1.3 {
  execsql "CREATE VIRTUAL TABLE t3 USING fts1(content, tokenize\x80)"
} {}

# The snippet-generation code has calls to isspace() which are sort of
# hard to get to.  It finds convenient breakpoints by starting ~40
# chars before and after the matched term, and scanning ~10 chars
# around that position for isspace() characters.  The long word with
# embedded hi-bit chars causes one of these isspace() calls to be
# exercised.  The version with a couple extra spaces should cause the
# other isspace() call to be exercised.  [Both cases have been tested
# in the debugger, but I'm hoping to continue to catch it if simple
# constant changes change things slightly.
#
# The trailing and leading hi-bit chars help with code which tests for
# isspace() to coalesce multiple spaces.

set word "\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80"
set phrase1 "$word $word $word target $word $word $word"
set phrase2 "$word $word $word    target    $word $word $word"

db eval {CREATE VIRTUAL TABLE t4 USING fts1(content)}
db eval "INSERT INTO t4 (content) VALUES ('$phrase1')"
db eval "INSERT INTO t4 (content) VALUES ('$phrase2')"

do_test fts1k-1.4 {
  execsql {SELECT rowid, length(snippet(t4)) FROM t4 WHERE t4 MATCH 'target'}
} {1 111 2 117}

finish_test

Added test/fts1l.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2007 April 9
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  fts1
# DELETE handling assumed all fields were non-null.  This was not
# the intention at all.
#
# $Id: fts1l.test,v 1.1 2007/04/09 20:45:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(col_a, col_b);

  INSERT INTO t1(rowid, col_a, col_b) VALUES(1, 'testing', 'testing');
  INSERT INTO t1(rowid, col_a, col_b) VALUES(2, 'only a', null);
  INSERT INTO t1(rowid, col_a, col_b) VALUES(3, null, 'only b');
  INSERT INTO t1(rowid, col_a, col_b) VALUES(4, null, null);
}

do_test fts1m-1.0 {
  execsql {
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {2 2 4}

do_test fts1m-1.1 {
  execsql {
    DELETE FROM t1 WHERE rowid = 1;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {1 1 3}

do_test fts1m-1.2 {
  execsql {
    DELETE FROM t1 WHERE rowid = 2;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 1 2}

do_test fts1m-1.3 {
  execsql {
    DELETE FROM t1 WHERE rowid = 3;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 0 1}

do_test fts1m-1.4 {
  execsql {
    DELETE FROM t1 WHERE rowid = 4;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 0 0}

finish_test

Added test/fts1m.test.





































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 2007 July 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing the FTS1 module, specifically snippet
# generation.  Extracted from fts2o.test.
#
# $Id: fts1m.test,v 1.1 2007/07/25 00:25:20 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is not defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

#---------------------------------------------------------------------
# These tests, fts1m-1.*, test that ticket #2429 is fixed.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(a, b, c);
  INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two');
}
do_test fts1m-1.1 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE c MATCH 'four';
  }
} {1 {one <b>four</b> two}}
do_test fts1m-1.2 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE b MATCH 'four';
  }
} {1 {one <b>four</b>}}
do_test fts1m-1.3 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE a MATCH 'four';
  }
} {1 {one three <b>four</b>}}

finish_test

Added test/fts1n.test.



























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 2007 July 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing the FTS1 module for errors in the handling
# of SQLITE_SCHEMA.
#
# $Id: fts1n.test,v 1.1 2007/07/25 00:38:06 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is not defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

do_test fts1m-1.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts1(a, b, c);
    INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one two');
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
  }
} {{one three four} {one four} {one two}}

# This test was crashing at one point.
#
do_test fts1m-1.2 {
  execsql {
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
    CREATE TABLE t3(a, b, c);
    SELECT a, b, c FROM t1 WHERE  c  MATCH 'two';
  }
} {{one three four} {one four} {one two} {one three four} {one four} {one two}}

finish_test

Added test/fts1o.test.





















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# 2007 July 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing the FTS1 module rename functionality.  Mostly
# copied from fts2o.test.
#
# $Id: fts1o.test,v 1.2 2007/08/30 20:01:33 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS1 is not defined, omit this file.
ifcapable !fts1 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts1(a, b, c);
  INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two');
}

#---------------------------------------------------------------------
# Test that it is possible to rename an fts1 table.
#
do_test fts1o-1.1 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {t1 t1_content t1_term}
do_test fts1o-1.2 {
  execsql { ALTER TABLE t1 RENAME to fts_t1; }
} {}
do_test fts1o-1.3 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts1o-1.4 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_term}

# See what happens when renaming the fts1 table fails.
#
do_test fts1o-2.1 {
  catchsql {
    CREATE TABLE t1_term(a, b, c);
    ALTER TABLE fts_t1 RENAME to t1;
  }
} {1 {SQL logic error or missing database}}
do_test fts1o-2.2 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts1o-2.3 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_term t1_term}

# See what happens when renaming the fts1 table fails inside a transaction.
#
do_test fts1o-3.1 {
  execsql {
    BEGIN;
    INSERT INTO fts_t1(a, b, c) VALUES('one two three', 'one four', 'one two');
  }
} {}
do_test fts1o-3.2 {
  catchsql {
    ALTER TABLE fts_t1 RENAME to t1;
  }
} {1 {SQL logic error or missing database}}
# NOTE(shess) rowid AS rowid to defeat caching.  Otherwise, this
# seg-faults, I suspect that there's something up with a stale
# virtual-table reference, but I'm not quite sure how it happens here
# but not for fts2o.test.
do_test fts1o-3.3 {
  execsql { SELECT rowid AS rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts1o-3.4 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_term t1_term}
do_test fts1o-3.5 {
  execsql COMMIT
  execsql {SELECT a FROM fts_t1}
} {{one three four} {one two three}}
do_test fts1o-3.6 {
  execsql { SELECT a, b, c FROM fts_t1 WHERE c MATCH 'four'; }
} {{one three four} {one four} {one four two}}

#---------------------------------------------------------------------
# Test that it is possible to rename an fts1 table in an attached 
# database.
#
file delete -force test2.db test2.db-journal

do_test fts1o-4.1 {
  execsql {
    DROP TABLE t1_term;
    ALTER TABLE fts_t1 RENAME to t1;
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
  }
} {{one three four} {one four} {one four two} {one two three} {one four} {one two}}

do_test fts1o-4.2 {
  execsql {
    ATTACH 'test2.db' AS aux;
    CREATE VIRTUAL TABLE aux.t1 USING fts1(a, b, c);
    INSERT INTO aux.t1(a, b, c) VALUES(
      'neung song sahm', 'neung see', 'neung see song'
    );
  }
} {}

do_test fts1o-4.3 {
  execsql { SELECT a, b, c FROM aux.t1 WHERE a MATCH 'song'; }
} {{neung song sahm} {neung see} {neung see song}}

do_test fts1o-4.4 {
  execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; }
} {{one three four} {one four} {one four two} {one two three} {one four} {one two}}

do_test fts1o-4.5 {
  execsql { ALTER TABLE aux.t1 RENAME TO t2 }
} {}

do_test fts1o-4.6 {
  execsql { SELECT a, b, c FROM t2 WHERE a MATCH 'song'; }
} {{neung song sahm} {neung see} {neung see song}}

do_test fts1o-4.7 {
  execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; }
} {{one three four} {one four} {one four two} {one two three} {one four} {one two}}

finish_test

Added test/fts1porter.test.

more than 10,000 changes

Added test/fts2.test.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 2008 July 22
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all tests.
#
# $Id: fts2.test,v 1.2 2008/07/23 18:17:32 drh Exp $

proc lshift {lvar} {
  upvar $lvar l
  set ret [lindex $l 0]
  set l [lrange $l 1 end]
  return $ret
}
while {[set arg [lshift argv]] != ""} {
  switch -- $arg {
    -sharedpagercache {
      sqlite3_enable_shared_cache 1
    }
    -soak {
       set SOAKTEST 1
    }
    default {
      set argv [linsert $argv 0 $arg]
      break
    }
  }
}

set testdir [file dirname $argv0]
source $testdir/tester.tcl
# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  return
}
rename finish_test really_finish_test
proc finish_test {} {}
set ISQUICK 1

set EXCLUDE {
  fts2.test
}

# Files to include in the test.  If this list is empty then everything
# that is not in the EXCLUDE list is run.
#
set INCLUDE {
}

foreach testfile [lsort -dictionary [glob $testdir/fts2*.test]] {
  set tail [file tail $testfile]
  if {[lsearch -exact $EXCLUDE $tail]>=0} continue
  if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue
  source $testfile
  catch {db close}
  if {$sqlite_open_file_count>0} {
    puts "$tail did not close all files: $sqlite_open_file_count"
    incr nErr
    lappend ::failList $tail
    set sqlite_open_file_count 0
  }
}

set sqlite_open_file_count 0
really_finish_test

Added test/fts2a.test.





















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# 2006 September 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS2 module.
#
# $Id: fts2a.test,v 1.2 2007/05/21 21:59:18 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Construct a full-text search table containing five keywords:
# one, two, three, four, and five, in various combinations.  The
# rowid for each will be a bitmask for the elements it contains.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1(content) VALUES('one');
  INSERT INTO t1(content) VALUES('two');
  INSERT INTO t1(content) VALUES('one two');
  INSERT INTO t1(content) VALUES('three');
  INSERT INTO t1(content) VALUES('one three');
  INSERT INTO t1(content) VALUES('two three');
  INSERT INTO t1(content) VALUES('one two three');
  INSERT INTO t1(content) VALUES('four');
  INSERT INTO t1(content) VALUES('one four');
  INSERT INTO t1(content) VALUES('two four');
  INSERT INTO t1(content) VALUES('one two four');
  INSERT INTO t1(content) VALUES('three four');
  INSERT INTO t1(content) VALUES('one three four');
  INSERT INTO t1(content) VALUES('two three four');
  INSERT INTO t1(content) VALUES('one two three four');
  INSERT INTO t1(content) VALUES('five');
  INSERT INTO t1(content) VALUES('one five');
  INSERT INTO t1(content) VALUES('two five');
  INSERT INTO t1(content) VALUES('one two five');
  INSERT INTO t1(content) VALUES('three five');
  INSERT INTO t1(content) VALUES('one three five');
  INSERT INTO t1(content) VALUES('two three five');
  INSERT INTO t1(content) VALUES('one two three five');
  INSERT INTO t1(content) VALUES('four five');
  INSERT INTO t1(content) VALUES('one four five');
  INSERT INTO t1(content) VALUES('two four five');
  INSERT INTO t1(content) VALUES('one two four five');
  INSERT INTO t1(content) VALUES('three four five');
  INSERT INTO t1(content) VALUES('one three four five');
  INSERT INTO t1(content) VALUES('two three four five');
  INSERT INTO t1(content) VALUES('one two three four five');
}

do_test fts2a-1.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts2a-1.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two'}
} {3 7 11 15 19 23 27 31}
do_test fts2a-1.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one'}
} {3 7 11 15 19 23 27 31}
do_test fts2a-1.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two three'}
} {7 15 23 31}
do_test fts2a-1.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one three two'}
} {7 15 23 31}
do_test fts2a-1.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two three one'}
} {7 15 23 31}
do_test fts2a-1.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one three'}
} {7 15 23 31}
do_test fts2a-1.8 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three one two'}
} {7 15 23 31}
do_test fts2a-1.9 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three two one'}
} {7 15 23 31}
do_test fts2a-1.10 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two THREE'}
} {7 15 23 31}
do_test fts2a-1.11 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '  ONE    Two   three  '}
} {7 15 23 31}

do_test fts2a-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one"'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts2a-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two"'}
} {3 7 11 15 19 23 27 31}
do_test fts2a-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"two one"'}
} {}
do_test fts2a-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three"'}
} {7 15 23 31}
do_test fts2a-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two"'}
} {}
do_test fts2a-2.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three four"'}
} {15 31}
do_test fts2a-2.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two four"'}
} {}
do_test fts2a-2.8 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three five"'}
} {21}
do_test fts2a-2.9 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" five'}
} {21 29}
do_test fts2a-2.10 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three"'}
} {21 29}
do_test fts2a-2.11 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three" four'}
} {29}
do_test fts2a-2.12 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five four "one three"'}
} {29}
do_test fts2a-2.13 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" four five'}
} {29}

do_test fts2a-3.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts2a-3.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one -two'}
} {1 5 9 13 17 21 25 29}
do_test fts2a-3.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '-two one'}
} {1 5 9 13 17 21 25 29}

do_test fts2a-4.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one OR two'}
} {1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21 22 23 25 26 27 29 30 31}
do_test fts2a-4.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two" OR three'}
} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31}
do_test fts2a-4.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR "one two"'}
} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31}
do_test fts2a-4.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three'}
} {3 5 7 11 13 15 19 21 23 27 29 31}
do_test fts2a-4.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR two one'}
} {3 5 7 11 13 15 19 21 23 27 29 31}
do_test fts2a-4.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three OR four'}
} {3 5 7 9 11 13 15 19 21 23 25 27 29 31}
do_test fts2a-4.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two OR three OR four one'}
} {3 5 7 9 11 13 15 19 21 23 25 27 29 31}

# Test the ability to handle NULL content
#
do_test fts2a-5.1 {
  execsql {INSERT INTO t1(content) VALUES(NULL)}
} {}
do_test fts2a-5.2 {
  set rowid [db last_insert_rowid]
  execsql {SELECT content FROM t1 WHERE rowid=$rowid}
} {{}}
do_test fts2a-5.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH NULL}
} {}

# Test the ability to handle non-positive rowids
#
do_test fts2a-6.0 {
  execsql {INSERT INTO t1(rowid, content) VALUES(0, 'four five')}
} {}
do_test fts2a-6.1 {
  execsql {SELECT content FROM t1 WHERE rowid = 0}
} {{four five}}
do_test fts2a-6.2 {
  execsql {INSERT INTO t1(rowid, content) VALUES(-1, 'three four')}
} {}
do_test fts2a-6.3 {
  execsql {SELECT content FROM t1 WHERE rowid = -1}
} {{three four}}
do_test fts2a-6.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'four'}
} {-1 0 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31}

finish_test

Added test/fts2b.test.







































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# 2006 September 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS2 module.
#
# $Id: fts2b.test,v 1.1 2006/10/19 23:36:26 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Fill the full-text index "t1" with phrases in english, spanish,
# and german.  For the i-th row, fill in the names for the bits
# that are set in the value of i.  The least significant bit is
# 1.  For example,  the value 5 is 101 in binary which will be
# converted to "one three" in english.
#
proc fill_multilanguage_fulltext_t1 {} {
  set english {one two three four five}
  set spanish {un dos tres cuatro cinco}
  set german {eine zwei drei vier funf}
  
  for {set i 1} {$i<=31} {incr i} {
    set cmd "INSERT INTO t1 VALUES"
    set vset {}
    foreach lang {english spanish german} {
      set words {}
      for {set j 0; set k 1} {$j<5} {incr j; incr k $k} {
        if {$k&$i} {lappend words [lindex [set $lang] $j]}
      }
      lappend vset "'$words'"
    }
    set sql "INSERT INTO t1(english,spanish,german) VALUES([join $vset ,])"
    # puts $sql
    db eval $sql
  }
}

# Construct a full-text search table containing five keywords:
# one, two, three, four, and five, in various combinations.  The
# rowid for each will be a bitmask for the elements it contains.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(english,spanish,german);
}
fill_multilanguage_fulltext_t1

do_test fts2b-1.1 {
  execsql {SELECT rowid FROM t1 WHERE english MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts2b-1.2 {
  execsql {SELECT rowid FROM t1 WHERE spanish MATCH 'one'}
} {}
do_test fts2b-1.3 {
  execsql {SELECT rowid FROM t1 WHERE german MATCH 'one'}
} {}
do_test fts2b-1.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts2b-1.5 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one dos drei'}
} {7 15 23 31}
do_test fts2b-1.6 {
  execsql {SELECT english, spanish, german FROM t1 WHERE rowid=1}
} {one un eine}
do_test fts2b-1.7 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"one un"'}
} {}

do_test fts2b-2.1 {
  execsql {
    CREATE VIRTUAL TABLE t2 USING fts2(from,to);
    INSERT INTO t2([from],[to]) VALUES ('one two three', 'four five six');
    SELECT [from], [to] FROM t2
  }
} {{one two three} {four five six}}


# Compute an SQL string that contains the words one, two, three,... to
# describe bits set in the value $i.  Only the lower 5 bits are examined.
#
proc wordset {i} {
  set x {}
  for {set j 0; set k 1} {$j<5} {incr j; incr k $k} {
    if {$k&$i} {lappend x [lindex {one two three four five} $j]}
  }
  return '$x'
}

# Create a new FTS table with three columns:
#
#    norm:      words for the bits of rowid
#    plusone:   words for the bits of rowid+1
#    invert:    words for the bits of ~rowid
#
db eval {
   CREATE VIRTUAL TABLE t4 USING fts2([norm],'plusone',"invert");
}
for {set i 1} {$i<=15} {incr i} {
  set vset [list [wordset $i] [wordset [expr {$i+1}]] [wordset [expr {~$i}]]]
  db eval "INSERT INTO t4(norm,plusone,invert) VALUES([join $vset ,]);"
}

do_test fts2b-4.1 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one'}
} {1 3 5 7 9 11 13 15}
do_test fts2b-4.2 {
  execsql {SELECT rowid FROM t4 WHERE norm MATCH 'one'}
} {1 3 5 7 9 11 13 15}
do_test fts2b-4.3 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'one'}
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}
do_test fts2b-4.4 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:one'}
} {2 4 6 8 10 12 14}
do_test fts2b-4.5 {
  execsql {SELECT rowid FROM t4 WHERE plusone MATCH 'one'}
} {2 4 6 8 10 12 14}
do_test fts2b-4.6 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one plusone:two'}
} {1 5 9 13}
do_test fts2b-4.7 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one two'}
} {1 3 5 7 9 11 13 15}
do_test fts2b-4.8 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:two norm:one'}
} {1 5 9 13}
do_test fts2b-4.9 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'two norm:one'}
} {1 3 5 7 9 11 13 15}


finish_test

Added test/fts2c.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# 2006 September 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS2 module.
#
# $Id: fts2c.test,v 1.1 2006/10/19 23:36:26 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Create a table of sample email data.   The data comes from email
# archives of Enron executives that was published as part of the
# litigation against that company.
#
do_test fts2c-1.1 {
  db eval {
    CREATE VIRTUAL TABLE email USING fts2([from],[to],subject,body);
    BEGIN TRANSACTION;
INSERT INTO email([from],[to],subject,body) VALUES('savita.puthigai@enron.com', 'traders.eol@enron.com, traders.eol@enron.com', 'EnronOnline- Change to Autohedge', 'Effective Monday, October 22, 2001 the following changes will be made to the Autohedge functionality on EnronOnline.

The volume on the hedge will now respect the minimum volume and volume increment settings on the parent product. See rules below: 

?	If the transaction volume on the child is less than half of the parent''s minimum volume no hedge will occur.
?	If the transaction volume on the child is more than half the parent''s minimum volume but less than half the volume increment on the parent, the hedge will volume will be the parent''s minimum volume.
?	For all other volumes, the same rounding rules will apply based on the volume increment on the parent product.

Please see example below:

Parent''s Settings:
Minimum: 	5000
Increment:  1000

Volume on Autohedge transaction			Volume Hedged
1      - 2499							0
2500 - 5499							5000
5500 - 6499							6000');
INSERT INTO email([from],[to],subject,body) VALUES('dana.davis@enron.com', 'laynie.east@enron.com, lisa.king@enron.com, lisa.best@enron.com,', 'Leaving Early', 'FYI:  
If it''s ok with everyone''s needs, I would like to leave @4pm. If you think 
you will need my assistance past the 4 o''clock hour just let me know;  I''ll 
be more than willing to stay.');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'louise.kitchen@enron.com', '<<Concur Expense Document>> - CC02.06.02', 'The following expense report is ready for approval:

Employee Name: Christopher F. Calger
Status last changed by: Mollie E. Gustafson Ms
Expense Report Name: CC02.06.02
Report Total: $3,972.93
Amount Due Employee: $3,972.93


To approve this expense report, click on the following link for Concur Expense.
http://expensexms.enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('jeff.duff@enron.com', 'julie.johnson@enron.com', 'Work request', 'Julie,

Could you print off the current work request report by 1:30 today?

Gentlemen,

I''d like to review this today at 1:30 in our office.  Also, could you provide 
me with your activity reports so I can have Julie enter this information.

JD');
INSERT INTO email([from],[to],subject,body) VALUES('v.weldon@enron.com', 'gary.l.carrier@usa.dupont.com, scott.joyce@bankofamerica.com', 'Enron News', 'This could turn into something big.... 
http://biz.yahoo.com/rf/010129/n29305829.html');
INSERT INTO email([from],[to],subject,body) VALUES('mark.haedicke@enron.com', 'paul.simons@enron.com', 'Re: First Polish Deal!', 'Congrats!  Things seem to be building rapidly now on the Continent.  Mark');
INSERT INTO email([from],[to],subject,body) VALUES('e..carter@enron.com', 't..robinson@enron.com', 'FW: Producers Newsletter 9-24-2001', '
The producer lumber pricing sheet.
 -----Original Message-----
From: 	Johnson, Jay  
Sent:	Tuesday, October 16, 2001 3:42 PM
To:	Carter, Karen E.
Subject:	FW: Producers Newsletter 9-24-2001



 -----Original Message-----
From: 	Daigre, Sergai  
Sent:	Friday, September 21, 2001 8:33 PM
Subject:	Producers Newsletter 9-24-2001

 ');
INSERT INTO email([from],[to],subject,body) VALUES('david.delainey@enron.com', 'kenneth.lay@enron.com', 'Greater Houston Partnership', 'Ken, in response to the letter from Mr Miguel San Juan, my suggestion would 
be to offer up the Falcon for their use; however, given the tight time frame 
and your recent visit with Mr. Fox that it would be difficult for either you 
or me to participate.

I spoke to Max and he agrees with this approach.

I hope this meets with your approval.

Regards
Delainey');
INSERT INTO email([from],[to],subject,body) VALUES('lachandra.fenceroy@enron.com', 'lindy.donoho@enron.com', 'FW: Bus Applications Meeting Follow Up', 'Lindy,

Here is the original memo we discussed earlier.  Please provide any information that you may have.

Your cooperation is greatly appreciated.

Thanks,

lachandra.fenceroy@enron.com
713.853.3884
877.498.3401 Pager

 -----Original Message-----
From: 	Bisbee, Joanne  
Sent:	Wednesday, September 26, 2001 7:50 AM
To:	Fenceroy, LaChandra
Subject:	FW: Bus Applications Meeting Follow Up

Lachandra, Please get with David Duff today and see what this is about.  Who are our TW accounting business users?

 -----Original Message-----
From: 	Koh, Wendy  
Sent:	Tuesday, September 25, 2001 2:41 PM
To:	Bisbee, Joanne
Subject:	Bus Applications Meeting Follow Up

Lisa brought up a TW change effective Nov 1.  It involves eliminating a turnback surcharge.  I have no other information, but you might check with the business folks for any system changes required.

Wendy');
INSERT INTO email([from],[to],subject,body) VALUES('danny.mccarty@enron.com', 'fran.fagan@enron.com', 'RE: worksheets', 'Fran,
    If Julie''s merit needs to be lump sum, just move it over to that column.  Also, send me Eric Gadd''s sheets as well.  Thanks.
Dan

 -----Original Message-----
From: 	Fagan, Fran  
Sent:	Thursday, December 20, 2001 11:10 AM
To:	McCarty, Danny
Subject:	worksheets

As discussed, attached are your sheets for bonus and merit.

Thanks,

Fran Fagan
Sr. HR Rep
713.853.5219


 << File: McCartyMerit.xls >>  << File: mccartyBonusCommercial_UnP.xls >> 

');
INSERT INTO email([from],[to],subject,body) VALUES('bert.meyers@enron.com', 'shift.dl-portland@enron.com', 'OCTOBER SCHEDULE', 'TEAM,

PLEASE SEND ME ANY REQUESTS THAT YOU HAVE FOR OCTOBER.  SO FAR I HAVE THEM FOR LEAF.  I WOULD LIKE TO HAVE IT DONE BY THE 15TH OF THE MONTH.  ANY QUESTIONS PLEASE GIVE ME A CALL.

BERT');
INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'john.arnold@enron.com, bilal.bajwa@enron.com, john.griffith@enron.com,', 'TRV Notification:  (NG - PROPT P/L - 09/27/2001)', 'The report named: NG - PROPT P/L <http://trv.corp.enron.com/linkFromExcel.asp?report_cd=11&report_name=NG+-+PROPT+P/L&category_cd=5&category_name=FINANCIAL&toc_hide=1&sTV1=5&TV1Exp=Y&current_efct_date=09/27/2001>, published as of 09/27/2001 is now available for viewing on the website.');
INSERT INTO email([from],[to],subject,body) VALUES('patrice.mims@enron.com', 'calvin.eakins@enron.com', 'Re: Small business supply assistance', 'Hi Calvin


I spoke with Rickey (boy, is he long-winded!!).  Gave him the name of our 
credit guy, Russell Diamond.

Thank for your help!');
INSERT INTO email([from],[to],subject,body) VALUES('legal <.hall@enron.com>', 'stephanie.panus@enron.com', 'Termination update', 'City of Vernon and Salt River Project terminated their contracts.  I will fax these notices to you.');
INSERT INTO email([from],[to],subject,body) VALUES('d..steffes@enron.com', 'richard.shapiro@enron.com', 'EES / ENA Government Affairs Staffing & Outside Services', 'Rick --

Here is the information on staffing and outside services.  Call if you need anything else.

Jim

 ');
INSERT INTO email([from],[to],subject,body) VALUES('gelliott@industrialinfo.com', 'pcopello@industrialinfo.com', 'ECAAR (Gavin), WSCC (Diablo Canyon), & NPCC (Seabrook)', 'Dear Power Outage Database Customer, 
Attached you will find an excel document. The outages contained within are forced or rescheduled outages. Your daily delivery will still contain these outages. 
In addition to the two excel documents, there is a dbf file that is formatted like your daily deliveries you receive nightly. This will enable you to load the data into your regular database. Any questions please let me know. Thanks. 
Greg Elliott 
IIR, Inc. 
713-783-5147 x 3481 
outages@industrialinfo.com 
THE INFORMATION CONTAINED IN THIS E-MAIL IS LEGALLY PRIVILEGED AND CONFIDENTIAL INFORMATION INTENDED ONLY FOR THE USE OF THE INDIVIDUAL OR ENTITY NAMED ABOVE.  YOU ARE HEREBY NOTIFIED THAT ANY DISSEMINATION, DISTRIBUTION, OR COPY OF THIS E-MAIL TO UNAUTHORIZED ENTITIES IS STRICTLY PROHIBITED. IF YOU HAVE RECEIVED THIS 
E-MAIL IN ERROR, PLEASE DELETE IT.
 - OUTAGE.dbf 
 - 111201R.xls 
 - 111201.xls ');
INSERT INTO email([from],[to],subject,body) VALUES('enron.announcements@enron.com', 'all_ena_egm_eim@enron.com', 'EWS Brown Bag', 'MARK YOUR LUNCH CALENDARS NOW !

You are invited to attend the EWS Brown Bag Lunch Series

Featuring:   RAY BOWEN, COO

Topic:  Enron Industrial Markets

Thursday, March 15, 2001
11:30 am - 12:30 pm
EB 5 C2


You bring your lunch,           Limited Seating
We provide drinks and dessert.          RSVP  x 3-9610');
INSERT INTO email([from],[to],subject,body) VALUES('chris.germany@enron.com', 'ingrid.immer@williams.com', 'Re: About St Pauls', 'Sounds good to me.  I bet this is next to the Warick?? Hotel.




"Immer, Ingrid" <Ingrid.Immer@Williams.com> on 12/21/2000 11:48:47 AM
To: "''chris.germany@enron.com''" <chris.germany@enron.com>
cc:  
Subject: About St Pauls




 <<About St Pauls.url>>  
? 
?http://www.stpaulshouston.org/about.html 

Chris, 

I like the looks of this place.? What do you think about going here Christmas 
eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., 
among others.

Let me know.?? ii 

 - About St Pauls.url

');
INSERT INTO email([from],[to],subject,body) VALUES('nas@cpuc.ca.gov', 'skatz@sempratrading.com, kmccrea@sablaw.com, thompson@wrightlaw.com,', 'Reply Brief filed July 31, 2000', ' - CPUC01-#76371-v1-Revised_Reply_Brief__Due_today_7_31_.doc');
INSERT INTO email([from],[to],subject,body) VALUES('gascontrol@aglresources.com', 'dscott4@enron.com, lcampbel@enron.com', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder
As discussed in the Winter Operations Meeting on Sept.29,2000, 
E-Gas(Emergency Gas) will not be offered this winter as a service from AGLC.  
Marketers and Poolers can receive gas via Peaking and IBSS nominations(daisy 
chain) from other marketers up to the 6 p.m. Same Day 2 nomination cycle.
');
INSERT INTO email([from],[to],subject,body) VALUES('dutch.quigley@enron.com', 'rwolkwitz@powermerchants.com', '', ' 

Here is a goody for you');
INSERT INTO email([from],[to],subject,body) VALUES('ryan.o''rourke@enron.com', 'k..allen@enron.com, randy.bhatia@enron.com, frank.ermis@enron.com,', 'TRV Notification:  (West VaR - 11/07/2001)', 'The report named: West VaR <http://trv.corp.enron.com/linkFromExcel.asp?report_cd=36&report_name=West+VaR&category_cd=2&category_name=WEST&toc_hide=1&sTV1=2&TV1Exp=Y&current_efct_date=11/07/2001>, published as of 11/07/2001 is now available for viewing on the website.');
INSERT INTO email([from],[to],subject,body) VALUES('mjones7@txu.com', 'cstone1@txu.com, ggreen2@txu.com, timpowell@txu.com,', 'Enron / HPL Actuals for July 10, 2000', 'Teco Tap       10.000 / Enron ; 110.000 / HPL IFERC

LS HPL LSK IC       30.000 / Enron
');
INSERT INTO email([from],[to],subject,body) VALUES('susan.pereira@enron.com', 'kkw816@aol.com', 'soccer practice', 'Kathy-

Is it safe to assume that practice is cancelled for tonight??

Susan Pereira');
INSERT INTO email([from],[to],subject,body) VALUES('mark.whitt@enron.com', 'barry.tycholiz@enron.com', 'Huber Internal Memo', 'Please look at this.  I didn''t know how deep to go with the desk.  Do you think this works.

 ');
INSERT INTO email([from],[to],subject,body) VALUES('m..forney@enron.com', 'george.phillips@enron.com', '', 'George,
Give me a call and we will further discuss opportunities on the 13st floor.

Thanks,
JMForney
3-7160');
INSERT INTO email([from],[to],subject,body) VALUES('brad.mckay@enron.com', 'angusmcka@aol.com', 'Re: (no subject)', 'not yet');
INSERT INTO email([from],[to],subject,body) VALUES('adam.bayer@enron.com', 'jonathan.mckay@enron.com', 'FW: Curve Fetch File', 'Here is the curve fetch file sent to me.  It has plenty of points in it.  If you give me a list of which ones you need we may be able to construct a secondary worksheet to vlookup the values.

adam
35227


 -----Original Message-----
From: 	Royed, Jeff  
Sent:	Tuesday, September 25, 2001 11:37 AM
To:	Bayer, Adam
Subject:	Curve Fetch File

Let me know if it works.   It may be required to have a certain version of Oracle for it to work properly.

 

Jeff Royed
Enron 
Energy Operations
Phone: 713-853-5295');
INSERT INTO email([from],[to],subject,body) VALUES('matt.smith@enron.com', 'yan.wang@enron.com', 'Report Formats', 'Yan,

The merged reports look great.  I believe the only orientation changes are to 
"unmerge" the following six reports:  

31 Keystone Receipts
15 Questar Pipeline
40 Rockies Production
22 West_2
23 West_3
25 CIG_WIC

The orientation of the individual reports should be correct.  Thanks.

Mat

PS.  Just a reminder to add the "*" by the title of calculated points.');
INSERT INTO email([from],[to],subject,body) VALUES('michelle.lokay@enron.com', 'jimboman@bigfoot.com', 'Egyptian Festival', '---------------------- Forwarded by Michelle Lokay/ET&S/Enron on 09/07/2000 
10:08 AM ---------------------------


"Karkour, Randa" <Randa.Karkour@COMPAQ.com> on 09/07/2000 09:01:04 AM
To: "''Agheb (E-mail)" <Agheb@aol.com>, "Leila Mankarious (E-mail)" 
<Leila_Mankarious@mhhs.org>, "''Marymankarious (E-mail)" 
<marymankarious@aol.com>, "Michelle lokay (E-mail)" <mlokay@enron.com>, "Ramy 
Mankarious (E-mail)" <Mankarious@aol.com>
cc:  

Subject: Egyptian Festival


 <<Egyptian Festival.url>>

 http://www.egyptianfestival.com/

 - Egyptian Festival.url
');
INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'sherry.dawson@enron.com', 'Urgent!!! --- New EAST books', 'This has to be done..................................

Thanks
---------------------- Forwarded by Errol McLaughlin/Corp/Enron on 12/20/2000 
08:39 AM ---------------------------
   
	
	
	From:  William Kelly @ ECT                           12/20/2000 08:31 AM
	

To: Kam Keiser/HOU/ECT@ECT, Darron C Giron/HOU/ECT@ECT, David 
Baumbach/HOU/ECT@ECT, Errol McLaughlin/Corp/Enron@ENRON
cc: Kimat Singla/HOU/ECT@ECT, Kulvinder Fowler/NA/Enron@ENRON, Kyle R 
Lilly/HOU/ECT@ECT, Jeff Royed/Corp/Enron@ENRON, Alejandra 
Chavez/NA/Enron@ENRON, Crystal Hyde/HOU/ECT@ECT 

Subject: New EAST books

We have new book names in TAGG for our intramonth portfolios and it is 
extremely important that any deal booked to the East is communicated quickly 
to someone on my team.  I know it will take some time for the new names to 
sink in and I do not want us to miss any positions or P&L.  

Thanks for your help on this.

New:
Scott Neal :         East Northeast
Dick Jenkins:     East Marketeast

WK 
');
INSERT INTO email([from],[to],subject,body) VALUES('david.forster@enron.com', 'eol.wide@enron.com', 'Change to Stack Manager', 'Effective immediately, there is a change to the Stack Manager which will 
affect any Inactive Child.

An inactive Child with links to Parent products will not have their 
calculated prices updated until the Child product is Activated.

When the Child Product is activated, the price will be recalculated and 
updated BEFORE it is displayed on the web.

This means that if you are inputting a basis price on a Child product, you 
will not see the final, calculated price until you Activate the product, at 
which time the customer will also see it.

If you have any questions, please contact the Help Desk on:

Americas: 713 853 4357
Europe: + 44 (0) 20 7783 7783
Asia/Australia: +61 2 9229 2300

Dave');
INSERT INTO email([from],[to],subject,body) VALUES('vince.kaminski@enron.com', 'jhh1@email.msn.com', 'Re: Light reading - see pieces beginning on page 7', 'John,

I saw it. Very interesting.

Vince





"John H Herbert" <jhh1@email.msn.com> on 07/28/2000 08:38:08 AM
To: "Vince J Kaminski" <Vince_J_Kaminski@enron.com>
cc:  
Subject: Light reading - see pieces beginning on page 7


Cheers and have a nice weekend,


JHHerbert




 - gd000728.pdf



');
INSERT INTO email([from],[to],subject,body) VALUES('matthew.lenhart@enron.com', 'mmmarcantel@equiva.com', 'RE:', 'i will try to line up a pig for you ');
INSERT INTO email([from],[to],subject,body) VALUES('jae.black@enron.com', 'claudette.harvey@enron.com, chaun.roberts@enron.com, judy.martinez@enron.com,', 'Disaster Recovery Equipment', 'As a reminder...there are several pieces of equipment that are set up on the 30th Floor, as well as on our floor, for the Disaster Recovery Team.  PLEASE DO NOT TAKE, BORROW OR USE this equipment.  Should you need to use another computer system, other than yours, or make conference calls please work with your Assistant to help find or set up equipment for you to use.

Thanks for your understanding in this matter.

T.Jae Black
East Power Trading
Assistant to Kevin Presto
off. 713-853-5800
fax 713-646-8272
cell 713-539-4760');
INSERT INTO email([from],[to],subject,body) VALUES('eric.bass@enron.com', 'dale.neuner@enron.com', '5 X 24', 'Dale,

Have you heard anything more on the 5 X 24s?  We would like to get this 
product out ASAP.


Thanks,

Eric');
INSERT INTO email([from],[to],subject,body) VALUES('messenger@smartreminders.com', 'm..tholt@enron.com', '10% Coupon - PrintPal Printer Cartridges - 100% Guaranteed', '[IMAGE]
[IMAGE][IMAGE][IMAGE] 
Dear  SmartReminders Member,
       [IMAGE]         [IMAGE]        [IMAGE]     [IMAGE]    [IMAGE]    [IMAGE]        [IMAGE]      [IMAGE]     	


  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

We respect  your privacy and are a Certified Participant of the BBBOnLine
 Privacy Program.  To be removed from future offers,click  here. 
SmartReminders.com  is a permission based service. To unsubscribe click  here .  ');
INSERT INTO email([from],[to],subject,body) VALUES('benjamin.rogers@enron.com', 'mark.bernstein@enron.com', '', 'The guy you are talking about left CIN under a "cloud of suspicion" sort of 
speak.  He was the one who got into several bad deals and PPA''s in California 
for CIN, thus he left on a bad note.  Let me know if you need more detail 
than that, I felt this was the type of info you were looking for.  Thanks!
Ben');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'michelle.cash@enron.com', 'Expense Report Receipts Not Received', 'Employee Name: Michelle Cash
Report Name:   Houston Cellular 8-11-01
Report Date:   12/13/01
Report ID:     594D37C9ED2111D5B452
Submitted On:  12/13/01

You are only allowed 2 reports with receipts outstanding.  Your expense reports will not be paid until you meet this requirement.');
INSERT INTO email([from],[to],subject,body) VALUES('susan.mara@enron.com', 'ray.alvarez@enron.com, mark.palmer@enron.com, karen.denne@enron.com,', 'CAISO Emergency Motion -- to discontinue market-based rates for', 'FYI.  the latest broadside against the generators.

Sue Mara
Enron Corp.
Tel: (415) 782-7802
Fax:(415) 782-7854
----- Forwarded by Susan J Mara/NA/Enron on 06/08/2001 12:24 PM -----


	"Milner, Marcie" <MMilner@coral-energy.com> 06/08/2001 11:13 AM 	   To: "''smara@enron.com''" <smara@enron.com>  cc:   Subject: CAISO Emergency Motion	


Sue, did you see this emergency motion the CAISO filed today?  Apparently
they are requesting that FERC discontinue market-based rates immediately and
grant refunds plus interest on the difference between cost-based rates and
market revenues received back to May 2000.  They are requesting the
commission act within 14 days.  Have you heard anything about what they are
doing?

Marcie

http://www.caiso.com/docs/2001/06/08/200106081005526469.pdf 
');
INSERT INTO email([from],[to],subject,body) VALUES('fletcher.sturm@enron.com', 'eloy.escobar@enron.com', 'Re: General Brinks Position Meeting', 'Eloy,

Who is General Brinks?

Fletch');
INSERT INTO email([from],[to],subject,body) VALUES('nailia.dindarova@enron.com', 'richard.shapiro@enron.com', 'Documents for Mark Frevert (on EU developments and lessons from', 'Rick,

Here are the documents that Peter has prepared for Mark Frevert. 

Nailia
---------------------- Forwarded by Nailia Dindarova/LON/ECT on 25/06/2001 
16:36 ---------------------------


Nailia Dindarova
25/06/2001 15:36
To: Michael Brown/Enron@EUEnronXGate
cc: Ross Sankey/Enron@EUEnronXGate, Eric Shaw/ENRON@EUEnronXGate, Peter 
Styles/LON/ECT@ECT 

Subject: Documents for Mark Frevert (on EU developments and lessons from 
California)

Michael,


These are the documents that Peter promised to give to you for Mark Frevert. 
He has now handed them to him in person but asked me to transmit them 
electronically to you, as well as Eric and Ross.

Nailia





');
INSERT INTO email([from],[to],subject,body) VALUES('peggy.a.kostial@accenture.com', 'dave.samuels@enron.com', 'EOL-Accenture Deal Sheet', 'Dave -

Attached are our comments and suggested changes. Please call to review.

On the time line for completion, we have four critical steps to complete:
     Finalize market analysis to refine business case, specifically
     projected revenue stream
     Complete counterparty surveying, including targeting 3 CPs for letters
     of intent
     Review Enron asset base for potential reuse/ licensing
     Contract negotiations

Joe will come back to us with an updated time line, but it is my
expectation that we are still on the same schedule (we just begun week
three) with possibly a week or so slippage.....contract negotiations will
probably be the critical path.

We will send our cut at the actual time line here shortly. Thanks,

Peggy

(See attached file: accenture-dealpoints v2.doc)
 - accenture-dealpoints v2.doc ');
INSERT INTO email([from],[to],subject,body) VALUES('thomas.martin@enron.com', 'thomas.martin@enron.com', 'Re: Guadalupe Power Partners LP', '---------------------- Forwarded by Thomas A Martin/HOU/ECT on 03/20/2001 
03:49 PM ---------------------------


Thomas A Martin
10/11/2000 03:55 PM
To: Patrick Wade/HOU/ECT@ECT
cc:  
Subject: Re: Guadalupe Power Partners LP  

The deal is physically served at Oasis Waha or Oasis Katy and is priced at 
either HSC, Waha or Katytailgate GD at buyers option three days prior to 
NYMEX  close.

');
INSERT INTO email([from],[to],subject,body) VALUES('judy.townsend@enron.com', 'dan.junek@enron.com, chris.germany@enron.com', 'Columbia Distribution''s Capacity Available for Release - Sum', '---------------------- Forwarded by Judy Townsend/HOU/ECT on 03/09/2001 11:04 
AM ---------------------------


agoddard@nisource.com on 03/08/2001 09:16:57 AM
To: "        -         *Koch, Kent" <kkoch@nisource.com>, "        -         
*Millar, Debra" <dmillar@nisource.com>, "        -         *Burke, Lynn" 
<lburke@nisource.com>
cc: "        -         *Heckathorn, Tom" <theckathorn@nisource.com> 
Subject: Columbia Distribution''s Capacity Available for Release - Sum


Attached is Columbia Distribution''s notice of capacity available for release
for
the summer of 2001 (Apr. 2001 through Oct. 2001).

Please note that the deadline for bids is 3:00pm EST on March 20, 2001.

If you have any questions, feel free to contact any of the representatives
listed
at the bottom of the attachment.

Aaron Goddard




 - 2001Summer.doc
');
INSERT INTO email([from],[to],subject,body) VALUES('rhonda.denton@enron.com', 'tim.belden@enron.com, dana.davis@enron.com, genia.fitzgerald@enron.com,', 'Split Rock Energy LLC', 'We have received the executed EEI contract from this CP dated 12/12/2000.  
Copies will be distributed to Legal and Credit.');
INSERT INTO email([from],[to],subject,body) VALUES('kerrymcelroy@dwt.com', 'jack.speer@alcoa.com, crow@millernash.com, michaelearly@earthlink.net,', 'Oral Argument Request', ' - Oral Argument Request.doc');
INSERT INTO email([from],[to],subject,body) VALUES('mike.carson@enron.com', 'rlmichaelis@hormel.com', '', 'Did you come in town this wk end..... My new number at our house is : 
713-668-3712...... my cell # is 281-381-7332

the kid');
INSERT INTO email([from],[to],subject,body) VALUES('cooper.richey@enron.com', 'trycooper@hotmail.com', 'FW: Contact Info', '

-----Original Message-----
From: Punja, Karim 
Sent: Thursday, December 13, 2001 2:35 PM
To: Richey, Cooper
Subject: Contact Info


Cooper,

Its been a real pleasure working with you (even though it was for only a small amount of time)
I hope we can stay in touch.

Home# 234-0249
email: kpunja@hotmail.com

Take Care, 

Karim.
  ');
INSERT INTO email([from],[to],subject,body) VALUES('bjm30@earthlink.net', 'mcguinn.k@enron.com, mcguinn.ian@enron.com, mcguinn.stephen@enron.com,', 'email address change', 'Hello all.

I haven''t talked to many of you via email recently but I do want to give you
my new address for your email file:

    bjm30@earthlink.net

I hope all is well.

Brian McGuinn');
INSERT INTO email([from],[to],subject,body) VALUES('shelley.corman@enron.com', 'steve.hotte@enron.com', 'Flat Panels', 'Can you please advise what is going on with the flat panels that we had planned to distribute to our gas logistics team.  It was in the budget and we had the okay, but now I''m hearing there is some hold-up & the units are stored on 44.

Shelley');
INSERT INTO email([from],[to],subject,body) VALUES('sara.davidson@enron.com', 'john.schwartzenburg@enron.com, scott.dieball@enron.com, recipients@enron.com,', '2001 Enron Law Conference (Distribution List 2)', '    Enron Law Conference

San Antonio, Texas    May 2-4, 2001    Westin Riverwalk

                   See attached memo for more details!!


? Registration for the law conference this year will be handled through an 
Online RSVP Form on the Enron Law Conference Website at 
http://lawconference.corp.enron.com.  The website is still under construction 
and will not be available until Thursday, March 15, 2001.  

? We will send you another e-mail to confirm when the Law Conference Website 
is operational. 

? Please complete the Online RSVP Form as soon as it is available  and submit 
it no later than Friday, March 30th.  




');
INSERT INTO email([from],[to],subject,body) VALUES('tori.kuykendall@enron.com', 'heath.b.taylor@accenture.com', 'Re:', 'hey - thats funny about john - he definitely remembers him - i''ll call pat 
and let him know - we are coming on saturday - i just havent had a chance to 
call you guys back --  looking forward to it -- i probably need the 
directions again though');
INSERT INTO email([from],[to],subject,body) VALUES('darron.giron@enron.com', 'bryce.baxter@enron.com', 'Re: Feedback for Audrey Cook', 'Bryce,

I''ll get it done today.  

DG    3-9573


   
	
	
	From:  Bryce Baxter                           06/12/2000 07:15 PM
	

To: Darron C Giron/HOU/ECT@ECT
cc:  
Subject: Feedback for Audrey Cook

You were identified as a reviewer for Audrey Cook.  If possible, could you 
complete her feedback by end of business Wednesday?  It will really help me 
in the PRC process to have your input.  Thanks.

');
INSERT INTO email([from],[to],subject,body) VALUES('casey.evans@enron.com', 'stephanie.sever@enron.com', 'Gas EOL ID', 'Stephanie,

In conjunction with the recent movement of several power traders, they are changing the names of their gas books as well.  The names of the new gas books and traders are as follows:

PWR-NG-LT-SPP:  Mike Carson
PWR-NG-LT-SERC:  Jeff King

If you need to know their power desk to map their ID to their gas books, those desks are as follows:

EPMI-LT-SPP:  Mike Carson
EPMI-LT-SERC:  Jeff King

I will be in training this afternoon, but will be back when class is over.  Let me know if you have any questions.

Thanks for your help!
Casey');
INSERT INTO email([from],[to],subject,body) VALUES('darrell.schoolcraft@enron.com', 'david.roensch@enron.com, kimberly.watson@enron.com, michelle.lokay@enron.com,', 'Postings', 'Please see the attached.


ds


  

 ');
INSERT INTO email([from],[to],subject,body) VALUES('mcominsky@aol.com', 'cpatman@bracepatt.com, james_derrick@enron.com', 'Jurisprudence Luncheon', 'Carrin & Jim --

It was an honor and a pleasure to meet both of you yesterday.  I know we will
have fun working together on this very special event.

Jeff left the jurisprudence luncheon lists for me before he left on vacation.
 I wasn''t sure whether he transmitted them to you as well.  Would you please
advise me if you would like them sent to you?  I can email the MS Excel files
or I can fax the hard copies to you.   Please advise what is most convenient.

I plan to be in town through the holidays and can be reached by phone, email,
or cell phone at any time.  My cell phone number is 713/705-4829.

Thanks again for your interest in the ADL''s work.  Martin.

Martin B. Cominsky
Director, Southwest Region
Anti-Defamation League
713/627-3490, ext. 122
713/627-2011 (fax)
MCominsky@aol.com');
INSERT INTO email([from],[to],subject,body) VALUES('phillip.love@enron.com', 'todagost@utmb.edu, gbsonnta@utmb.edu', 'New President', 'I had a little bird put a word in my ear.  Is there any possibility for Ben 
Raimer to be Bush''s secretary of HHS?  Just curious about that infamous UTMB 
rumor mill.  Hope things are well, happy holidays.
PL');
INSERT INTO email([from],[to],subject,body) VALUES('marie.heard@enron.com', 'ehamilton@fna.com', 'ISDA Master Agreement', 'Erin:

Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together with Paragraph 13 to the ISDA Credit Support Annex.  Please let me know if you need anything else.  We look forward to hearing your comments.

Marie

Marie Heard
Senior Legal Specialist
Enron North America Corp.
Phone:  (713) 853-3907
Fax:  (713) 646-3490
marie.heard@enron.com

				 ');
INSERT INTO email([from],[to],subject,body) VALUES('andrea.ring@enron.com', 'beverly.beaty@enron.com', 'Re: Tennessee Buy - Louis Dreyfus', 'Beverly -  once again thanks so much for your help on this.

           

                                                                     ');
INSERT INTO email([from],[to],subject,body) VALUES('karolyn.criado@enron.com', 'j..bonin@enron.com, felicia.case@enron.com, b..clapp@enron.com,', 'Price List week of Oct. 8-9, 2001', '
Please contact me if you have any questions regarding last weeks prices.

Thank you,
Karolyn Criado
3-9441


 

');
INSERT INTO email([from],[to],subject,body) VALUES('kevin.presto@enron.com', 'edward.baughman@enron.com, billy.braddock@enron.com', 'Associated', 'Please begin working on filling our Associated short position in 02.   I would like to take this risk off the books.

In addition, please find out what a buy-out of VEPCO would cost us.   With Rogers transitioning to run our retail risk management, I would like to clean up our customer positions.

We also need to continue to explore a JEA buy-out.

Thanks.');
INSERT INTO email([from],[to],subject,body) VALUES('stacy.dickson@enron.com', 'gregg.penman@enron.com', 'RE: Constellation TC 5-7-01', 'Gregg, 

I am at home with a sick baby.  (Lots of fun!)  I will call you about this 
tomorrow.

Stacy');
INSERT INTO email([from],[to],subject,body) VALUES('joe.quenet@enron.com', 'dfincher@utilicorp.com', '', 'hey big guy.....check this out.....

 w ww.gorelieberman-2000.com/');
INSERT INTO email([from],[to],subject,body) VALUES('k..allen@enron.com', 'jacqestc@aol.com', '', 'Jacques,

I sent you a fax of Kevin Kolb''s comments on the release.  The payoff on the note would be $36,248 ($36090(principal) + $158 (accrued interest)).
This is assuming we wrap this up on Tuesday.  

Please email to confirm that their changes are ok so I can set up a meeting on Tuesday to reach closure.

Phillip');
INSERT INTO email([from],[to],subject,body) VALUES('kourtney.nelson@enron.com', 'mike.swerzbin@enron.com', 'Adjusted L/R Balance', 'Mike,

I placed the adjusted L/R Balance on the Enronwest site.  It is under the "Staff/Kourtney Nelson".  There are two links:  

1)  "Adj L_R" is the same data/format from the weekly strategy meeting. 
2)  "New Gen 2001_2002" link has all of the supply side info that is used to calculate the L/R balance
	-Please note the Data Flag column, a value of "3" indicates the project was cancelled, on hold, etc and is not included in the calc.  

Both of these sheets are interactive Excel spreadsheets and thus you can play around with the data as you please.  Also, James Bruce is working to get his gen report on the web.  That will help with your access to information on new gen.

Please let me know if you have any questions or feedback,

Kourtney



Kourtney Nelson
Fundamental Analysis 
Enron North America
(503) 464-8280
kourtney.nelson@enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('d..thomas@enron.com', 'naveed.ahmed@enron.com', 'FW: Current Enron TCC Portfolio', '

-----Original Message-----
From: Grace, Rebecca M. 
Sent: Monday, December 17, 2001 9:44 AM
To: Thomas, Paul D.
Cc: Cashion, Jim; Allen, Thresa A.; May, Tom
Subject: RE: Current Enron TCC Portfolio


Paul,

I reviewed NY''s list.  I agree with all of their contracts numbers and mw amounts.

Call if you have any more questions.

Rebecca



 -----Original Message-----
From: 	Thomas, Paul D.  
Sent:	Monday, December 17, 2001 9:08 AM
To:	Grace, Rebecca M.
Subject:	FW: Current Enron TCC Portfolio

 << File: enrontccs.xls >> 
Rebecca,
Let me know if you see any differences.

Paul
X 3-0403
-----Original Message-----
From: Thomas, Paul D. 
Sent: Monday, December 17, 2001 9:04 AM
To: Ahmed, Naveed
Subject: FW: Current Enron TCC Portfolio




-----Original Message-----
From: Thomas, Paul D. 
Sent: Thursday, December 13, 2001 10:01 AM
To: Baughman, Edward D.
Subject: Current Enron TCC Portfolio


');
INSERT INTO email([from],[to],subject,body) VALUES('stephanie.panus@enron.com', 'william.bradford@enron.com, debbie.brackett@enron.com,', 'Coastal Merchant Energy/El Paso Merchant Energy', 'Coastal Merchant Energy, L.P. merged with and into El Paso Merchant Energy, 
L.P., effective February 1, 2001, with the surviving entity being El Paso 
Merchant Energy, L.P.  We currently have ISDA Master Agreements with both 
counterparties.  Please see the attached memo regarding the existing Masters 
and let us know which agreement should be terminated.

Thanks,
Stephanie
');
INSERT INTO email([from],[to],subject,body) VALUES('kam.keiser@enron.com', 'c..kenne@enron.com', 'RE: What about this too???', ' 

 -----Original Message-----
From: 	Kenne, Dawn C.  
Sent:	Wednesday, February 06, 2002 11:50 AM
To:	Keiser, Kam
Subject:	What about this too???


 << File: Netco Trader Matrix.xls >> 
 ');
INSERT INTO email([from],[to],subject,body) VALUES('chris.meyer@enron.com', 'joe.parks@enron.com', 'Centana', 'Talked to Chip.  We do need Cash Committe approval given the netting feature of your deal, which means Batch Funding Request.  Please update per my previous e-mail and forward.

Thanks

chris
x31666');
INSERT INTO email([from],[to],subject,body) VALUES('debra.perlingiere@enron.com', 'jworman@academyofhealth.com', '', 'Have a great weekend!   Happy Fathers Day!


Debra Perlingiere
Enron North America Corp.
1400 Smith Street, EB 3885
Houston, Texas 77002
dperlin@enron.com
Phone 713-853-7658
Fax  713-646-3490');
INSERT INTO email([from],[to],subject,body) VALUES('outlook.team@enron.com', '', 'Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia  &', 'CALENDAR ENTRY:	APPOINTMENT

Description:
	Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia  & Dir Rpts. - 4102

Date:		1/5/2001
Time:		9:00 AM - 10:00 AM (Central Standard Time)

Chairperson:	Outlook Migration Team

Detailed Description:');
INSERT INTO email([from],[to],subject,body) VALUES('diana.seifert@enron.com', 'mark.taylor@enron.com', 'Guest access Chile', 'Hello Mark,

Justin Boyd told me that your can help me with questions regarding Chile.
We got a request for guest access through MG.
The company is called Escondida and is a subsidiary of BHP Australia.

Please advise if I can set up a guest account or not.
F.Y.I.: MG is planning to put a "in w/h Chile" contract for Copper on-line as 
soon as Enron has done the due diligence for this country.
Thanks !


Best regards

Diana Seifert
EOL PCG');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'mark.whitt@enron.com', '<<Concur Expense Document>> - 121001', 'The Approval status has changed on the following report:

Status last changed by: Barry L. Tycholiz
Expense Report Name: 121001
Report Total: $198.98
Amount Due Employee: $198.98
Amount Approved: $198.98
Amount Paid: $0.00
Approval Status: Approved
Payment Status: Pending


To review this expense report, click on the following link for Concur Expense.
http://expensexms.enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('kevin.hyatt@enron.com', '', 'Technical Support', 'Outside the U.S., please refer to the list below:

Australia:
1800 678-515
support@palm-au.com

Canada:
1905 305-6530
support@palm.com

New Zealand:
0800 446-398
support@palm-nz.com

U.K.:
0171 867 0108
eurosupport@palm.3com.com

Please refer to the Worldwide Customer Support card for a complete technical support contact list.');
INSERT INTO email([from],[to],subject,body) VALUES('geoff.storey@enron.com', 'dutch.quigley@enron.com', 'RE:', 'duke contact?

 -----Original Message-----
From: 	Quigley, Dutch  
Sent:	Wednesday, October 31, 2001 10:14 AM
To:	Storey, Geoff
Subject:	RE: 

bp corp	Albert LaMore	281-366-4962

running the reports now


 -----Original Message-----
From: 	Storey, Geoff  
Sent:	Wednesday, October 31, 2001 10:10 AM
To:	Quigley, Dutch
Subject:	RE: 

give me a contact over there too
BP


 -----Original Message-----
From: 	Quigley, Dutch  
Sent:	Wednesday, October 31, 2001 9:42 AM
To:	Storey, Geoff
Subject:	

Coral	Jeff Whitnah	713-767-5374
Relaint	Steve McGinn	713-207-4000');
INSERT INTO email([from],[to],subject,body) VALUES('pete.davis@enron.com', 'pete.davis@enron.com', 'Start Date: 4/22/01; HourAhead hour: 3;  <CODESITE>', 'Start Date: 4/22/01; HourAhead hour: 3;  No ancillary schedules awarded.  
Variances detected.
Variances detected in Load schedule.

    LOG MESSAGES:

PARSING FILE -->> O:\Portland\WestDesk\California Scheduling\ISO Final 
Schedules\2001042203.txt

---- Load Schedule ----
$$$ Variance found in table tblLoads.
     Details: (Hour: 3 / Preferred:   1.92 / Final:   1.89)
  TRANS_TYPE: FINAL
  LOAD_ID: PGE4
  MKT_TYPE: 2
  TRANS_DATE: 4/22/01
  SC_ID: EPMI

');
INSERT INTO email([from],[to],subject,body) VALUES('john.postlethwaite@enron.com', 'john.zufferli@enron.com', 'Reference', 'John, hope things are going well up there for you. The big day is almost here for you and Jessica. I was wondering if I could use your name as a job reference if need be. I am just trying to get everything in order just in case something happens. 

John');
INSERT INTO email([from],[to],subject,body) VALUES('jeffrey.shankman@enron.com', 'lschiffm@jonesday.com', 'Re:', 'I saw you called on the cell this a.m.  Sorry I missed you.  (I was in the 
shower).  I have had a shitty week--I suspect my silence (not only to you, 
but others) after our phone call is a result of the week.  I''m seeing Glen at 
11:15....talk to you');
INSERT INTO email([from],[to],subject,body) VALUES('litebytz@enron.com', '', 'Lite Bytz RSVP', '
This week''s Lite Bytz presentation will feature the following TOOLZ speaker:

Richard McDougall
Solaris 8
Thursday, June 7, 2001

If you have not already signed up, please RSVP via email to litebytz@enron.com by the end of the day Tuesday, June 5, 2001.

*Remember: this is now a Brown Bag Event--so bring your lunch and we will provide cookies and drinks.

Click below for more details.

http://home.enron.com:84/messaging/litebytztoolzprint.jpg');
    COMMIT;
  }
} {}

###############################################################################
# Everything above just builds an interesting test database.  The actual
# tests come after this comment.
###############################################################################

do_test fts2c-1.2 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark'
  }
} {6 17 25 38 40 42 73 74}
do_test fts2c-1.3 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'susan'
  }
} {24 40}
do_test fts2c-1.4 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark susan'
  }
} {40}
do_test fts2c-1.5 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'susan mark'
  }
} {40}
do_test fts2c-1.6 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH '"mark susan"'
  }
} {}
do_test fts2c-1.7 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark -susan'
  }
} {6 17 25 38 42 73 74}
do_test fts2c-1.8 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH '-mark susan'
  }
} {24}
do_test fts2c-1.9 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark OR susan'
  }
} {6 17 24 25 38 40 42 73 74}

# Some simple tests of the automatic "offsets(email)" column.  In the sample
# data set above, only one message, number 20, contains the words
# "gas" and "reminder" in both body and subject.
#
do_test fts2c-2.1 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}
do_test fts2c-2.2 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'subject:gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8 3 1 54 8}}
do_test fts2c-2.3 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'body:gas reminder'
  }
} {20 {2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}
do_test fts2c-2.4 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE subject MATCH 'gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8}}
do_test fts2c-2.5 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH 'gas reminder'
  }
} {20 {3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}

# Document 32 contains 5 instances of the world "child".  But only
# 3 of them are paired with "product".  Make sure only those instances
# that match the phrase appear in the offsets(email) list.
#
do_test fts2c-3.1 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH 'child product' AND +rowid=32
  }
} {32 {3 0 94 5 3 0 114 5 3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7 3 1 493 7}}
do_test fts2c-3.2 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH '"child product"'
  }
} {32 {3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7}}

# Snippet generator tests
#
do_test fts2c-4.1 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'subject:gas reminder'
  }
} {{Alert Posted 10:00 AM November 20,2000: E-<b>GAS</b> Request <b>Reminder</b>}}
do_test fts2c-4.2 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'christmas candlelight'
  }
} {{<b>...</b> place.? What do you think about going here <b>Christmas</b> 
eve?? They have an 11:00 a.m. service and a <b>candlelight</b> service at 5:00 p.m., 
among others. <b>...</b>}}

do_test fts2c-4.3 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'deal sheet potential reuse'
  }
} {{EOL-Accenture <b>Deal</b> <b>Sheet</b> <b>...</b> intent
     Review Enron asset base for <b>potential</b> <b>reuse</b>/ licensing
     Contract negotiations <b>...</b>}}
do_test fts2c-4.4 {
  execsql {
    SELECT snippet(email,'<<<','>>>',' ') FROM email
     WHERE email MATCH 'deal sheet potential reuse'
  }
} {{EOL-Accenture <<<Deal>>> <<<Sheet>>>  intent
     Review Enron asset base for <<<potential>>> <<<reuse>>>/ licensing
     Contract negotiations  }}
do_test fts2c-4.5 {
  execsql {
    SELECT snippet(email,'<<<','>>>',' ') FROM email
     WHERE email MATCH 'first things'
  }
} {{Re: <<<First>>> Polish Deal!  Congrats!  <<<Things>>> seem to be building rapidly now on the  }}
do_test fts2c-4.6 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'chris is here'
  }
} {{<b>chris</b>.germany@enron.com <b>...</b> Sounds good to me.  I bet this <b>is</b> next to the Warick?? Hotel. <b>...</b> place.? What do you think about going <b>here</b> Christmas 
eve?? They have an 11:00 a.m. <b>...</b>}}
do_test fts2c-4.7 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH '"pursuant to"'
  }
} {{Erin:

<b>Pursuant</b> <b>to</b> your request, attached are the Schedule to <b>...</b>}}
do_test fts2c-4.8 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'ancillary load davis'
  }
} {{pete.<b>davis</b>@enron.com <b>...</b> Start Date: 4/22/01; HourAhead hour: 3;  No <b>ancillary</b> schedules awarded.  
Variances detected.
Variances detected in <b>Load</b> schedule.

    LOG MESSAGES:

PARSING <b>...</b>}}

# Combinations of AND and OR operators:
#
do_test fts2c-5.1 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'questar enron OR com'
  }
} {{matt.smith@<b>enron</b>.<b>com</b> <b>...</b> six reports:  

31 Keystone Receipts
15 <b>Questar</b> Pipeline
40 Rockies Production
22 West_2 <b>...</b>}}
do_test fts2c-5.2 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'enron OR com questar'
  }
} {{matt.smith@<b>enron</b>.<b>com</b> <b>...</b> six reports:  

31 Keystone Receipts
15 <b>Questar</b> Pipeline
40 Rockies Production
22 West_2 <b>...</b>}}

finish_test

Added test/fts2d.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2006 October 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS2 module, and in particular
# the Porter stemmer.
#
# $Id: fts2d.test,v 1.1 2006/10/19 23:36:26 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

do_test fts2d-1.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts2(content, tokenize porter);
    INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping');
    SELECT rowid FROM t1 WHERE content MATCH 'run jump';
  }
} {1}
do_test fts2d-1.2 {
  execsql {
    SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'run jump';
  }
} {{<b>running</b> and <b>jumping</b>}}
do_test fts2d-1.3 {
  execsql {
    INSERT INTO t1(rowid, content) 
          VALUES(2, 'abcdefghijklmnopqrstuvwyxz');
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz'
  }
} {2 <b>abcdefghijklmnopqrstuvwyxz</b>}
do_test fts2d-1.4 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijXXXXqrstuvwyxz'
  }
} {2 <b>abcdefghijklmnopqrstuvwyxz</b>}
do_test fts2d-1.5 {
  execsql {
    INSERT INTO t1(rowid, content) 
          VALUES(3, 'The value is 123456789');
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123789'
  }
} {3 {The value is <b>123456789</b>}}
do_test fts2d-1.6 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123000000789'
  }
} {3 {The value is <b>123456789</b>}}


finish_test

Added test/fts2e.test.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing deletions in the FTS2 module.
#
# $Id: fts2e.test,v 1.1 2006/10/19 23:36:26 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Construct a full-text search table containing keywords which are the
# ordinal numbers of the bit positions set for a sequence of integers,
# which are used for the rowid.  There are a total of 30 INSERT and
# DELETE statements, so that we'll test both the segmentMerge() merge
# (over the first 16) and the termSelect() merge (over the level-1
# segment and 14 level-0 segments).
db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'one');
  INSERT INTO t1 (rowid, content) VALUES(2, 'two');
  INSERT INTO t1 (rowid, content) VALUES(3, 'one two');
  INSERT INTO t1 (rowid, content) VALUES(4, 'three');
  DELETE FROM t1 WHERE rowid = 1;
  INSERT INTO t1 (rowid, content) VALUES(5, 'one three');
  INSERT INTO t1 (rowid, content) VALUES(6, 'two three');
  INSERT INTO t1 (rowid, content) VALUES(7, 'one two three');
  DELETE FROM t1 WHERE rowid = 4;
  INSERT INTO t1 (rowid, content) VALUES(8, 'four');
  INSERT INTO t1 (rowid, content) VALUES(9, 'one four');
  INSERT INTO t1 (rowid, content) VALUES(10, 'two four');
  DELETE FROM t1 WHERE rowid = 7;
  INSERT INTO t1 (rowid, content) VALUES(11, 'one two four');
  INSERT INTO t1 (rowid, content) VALUES(12, 'three four');
  INSERT INTO t1 (rowid, content) VALUES(13, 'one three four');
  DELETE FROM t1 WHERE rowid = 10;
  INSERT INTO t1 (rowid, content) VALUES(14, 'two three four');
  INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four');
  INSERT INTO t1 (rowid, content) VALUES(16, 'five');
  DELETE FROM t1 WHERE rowid = 13;
  INSERT INTO t1 (rowid, content) VALUES(17, 'one five');
  INSERT INTO t1 (rowid, content) VALUES(18, 'two five');
  INSERT INTO t1 (rowid, content) VALUES(19, 'one two five');
  DELETE FROM t1 WHERE rowid = 16;
  INSERT INTO t1 (rowid, content) VALUES(20, 'three five');
  INSERT INTO t1 (rowid, content) VALUES(21, 'one three five');
  INSERT INTO t1 (rowid, content) VALUES(22, 'two three five');
  DELETE FROM t1 WHERE rowid = 19;
  DELETE FROM t1 WHERE rowid = 22;
}

do_test fts2f-1.1 {
  execsql {SELECT COUNT(*) FROM t1}
} {14}

do_test fts2e-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {3 5 9 11 15 17 21}

do_test fts2e-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'}
} {2 3 6 11 14 15 18}

do_test fts2e-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'}
} {5 6 12 14 15 20 21}

do_test fts2e-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'}
} {8 9 11 12 14 15}

do_test fts2e-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'}
} {17 18 20 21}

finish_test

Added test/fts2f.test.





















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing updates in the FTS2 module.
#
# $Id: fts2f.test,v 1.2 2007/02/23 00:14:06 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Construct a full-text search table containing keywords which are the
# ordinal numbers of the bit positions set for a sequence of integers,
# which are used for the rowid.  There are a total of 31 INSERT,
# UPDATE, and DELETE statements, so that we'll test both the
# segmentMerge() merge (over the first 16) and the termSelect() merge
# (over the level-1 segment and 15 level-0 segments).
db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'one');
  INSERT INTO t1 (rowid, content) VALUES(2, 'two');
  INSERT INTO t1 (rowid, content) VALUES(3, 'one two');
  INSERT INTO t1 (rowid, content) VALUES(4, 'three');
  INSERT INTO t1 (rowid, content) VALUES(5, 'one three');
  INSERT INTO t1 (rowid, content) VALUES(6, 'two three');
  INSERT INTO t1 (rowid, content) VALUES(7, 'one two three');
  DELETE FROM t1 WHERE rowid = 4;
  INSERT INTO t1 (rowid, content) VALUES(8, 'four');
  UPDATE t1 SET content = 'update one three' WHERE rowid = 1;
  INSERT INTO t1 (rowid, content) VALUES(9, 'one four');
  INSERT INTO t1 (rowid, content) VALUES(10, 'two four');
  DELETE FROM t1 WHERE rowid = 7;
  INSERT INTO t1 (rowid, content) VALUES(11, 'one two four');
  INSERT INTO t1 (rowid, content) VALUES(12, 'three four');
  INSERT INTO t1 (rowid, content) VALUES(13, 'one three four');
  DELETE FROM t1 WHERE rowid = 10;
  INSERT INTO t1 (rowid, content) VALUES(14, 'two three four');
  INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four');
  UPDATE t1 SET content = 'update two five' WHERE rowid = 8;
  INSERT INTO t1 (rowid, content) VALUES(16, 'five');
  DELETE FROM t1 WHERE rowid = 13;
  INSERT INTO t1 (rowid, content) VALUES(17, 'one five');
  INSERT INTO t1 (rowid, content) VALUES(18, 'two five');
  INSERT INTO t1 (rowid, content) VALUES(19, 'one two five');
  DELETE FROM t1 WHERE rowid = 16;
  INSERT INTO t1 (rowid, content) VALUES(20, 'three five');
  INSERT INTO t1 (rowid, content) VALUES(21, 'one three five');
  INSERT INTO t1 (rowid, content) VALUES(22, 'two three five');
  DELETE FROM t1 WHERE rowid = 19;
  UPDATE t1 SET content = 'update' WHERE rowid = 15;
}

do_test fts2f-1.1 {
  execsql {SELECT COUNT(*) FROM t1}
} {16}

do_test fts2f-2.0 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'update'}
} {1 8 15}

do_test fts2f-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 9 11 17 21}

do_test fts2f-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'}
} {2 3 6 8 11 14 18 22}

do_test fts2f-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'}
} {1 5 6 12 14 20 21 22}

do_test fts2f-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'}
} {9 11 12 14}

do_test fts2f-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'}
} {8 17 18 20 21 22}

finish_test

Added test/fts2g.test.



























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing handling of edge cases for various doclist
# merging functions in the FTS2 module query logic.
#
# $Id: fts2g.test,v 1.3 2007/11/16 00:23:08 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'this is a test');
  INSERT INTO t1 (rowid, content) VALUES(2, 'also a test');
}

# No hits at all.  Returns empty doclists from termSelect().
do_test fts2g-1.1 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'}
} {}

# Empty left in docListExceptMerge().
do_test fts2g-1.2 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this something'}
} {}

# Empty right in docListExceptMerge().
do_test fts2g-1.3 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this -something'}
} {1}

# Empty left in docListPhraseMerge().
do_test fts2g-1.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"this something"'}
} {}

# Empty right in docListPhraseMerge().
do_test fts2g-1.5 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"something is"'}
} {}

# Empty left in docListOrMerge().
do_test fts2g-1.6 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR this'}
} {1}

# Empty right in docListOrMerge().
do_test fts2g-1.7 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR something'}
} {1}

# Empty left in docListAndMerge().
do_test fts2g-1.8 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something this'}
} {}

# Empty right in docListAndMerge().
do_test fts2g-1.9 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this something'}
} {}

# No support for all-except queries.
do_test fts2g-1.10 {
  catchsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this -something'}
} {1 {SQL logic error or missing database}}

# Test that docListOrMerge() correctly handles reaching the end of one
# doclist before it reaches the end of the other.
do_test fts2g-1.11 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR also'}
} {1 2}
do_test fts2g-1.12 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'also OR this'}
} {1 2}

# Empty left and right in docListOrMerge().  Each term matches neither
# row, and when combined there was an assertion failure.
do_test fts2g-1.13 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR nothing'}
} {}

finish_test

Added test/fts2h.test.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 2006 October 31 (scaaarey)
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# here is testing correct handling of excessively long terms.
#
# $Id: fts2h.test,v 1.1 2006/11/29 21:03:01 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Generate a term of len copies of char.
proc bigterm {char len} {
  for {set term ""} {$len>0} {incr len -1} {
    append term $char
  }
  return $term
}

# Generate a document of bigterms based on characters from the list
# chars.
proc bigtermdoc {chars len} {
  set doc ""
  foreach char $chars {
    append doc " " [bigterm $char $len]
  }
  return $doc
}

set len 5000
set doc1 [bigtermdoc {a b c d} $len]
set doc2 [bigtermdoc {b d e f} $len]
set doc3 [bigtermdoc {a c e} $len]

set aterm [bigterm a $len]
set bterm [bigterm b $len]
set xterm [bigterm x $len]

db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1 (rowid, content) VALUES(1, $doc1);
  INSERT INTO t1 (rowid, content) VALUES(2, $doc2);
  INSERT INTO t1 (rowid, content) VALUES(3, $doc3);
}

# No hits at all.  Returns empty doclists from termSelect().
do_test fts2h-1.1 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'}
} {}

do_test fts2h-1.2 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH $aterm}
} {1 3}

do_test fts2h-1.2 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH $xterm}
} {}

do_test fts2h-1.3 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '$aterm -$xterm'"
} {1 3}

do_test fts2h-1.4 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"$aterm $bterm\"'"
} {1}

finish_test

Added test/fts2i.test.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 2007 January 17
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite fts2 library.  The
# focus here is testing handling of UPDATE when using UTF-16-encoded
# databases.
#
# $Id: fts2i.test,v 1.2 2007/01/24 03:46:35 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Return the UTF-16 representation of the supplied UTF-8 string $str.
# If $nt is true, append two 0x00 bytes as a nul terminator.
# NOTE(shess) Copied from capi3.test.
proc utf16 {str {nt 1}} {
  set r [encoding convertto unicode $str]
  if {$nt} {
    append r "\x00\x00"
  }
  return $r
}

db eval {
  PRAGMA encoding = "UTF-16le";
  CREATE VIRTUAL TABLE t1 USING fts2(content);
}

do_test fts2i-1.0 {
  execsql {PRAGMA encoding}
} {UTF-16le}

do_test fts2i-1.1 {
  execsql {INSERT INTO t1 (rowid, content) VALUES(1, 'one')}
  execsql {SELECT content FROM t1 WHERE rowid = 1}
} {one}

do_test fts2i-1.2 {
  set sql "INSERT INTO t1 (rowid, content) VALUES(2, 'two')"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 2}
} {two}

do_test fts2i-1.3 {
  set sql "INSERT INTO t1 (rowid, content) VALUES(3, 'three')"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  set sql "UPDATE t1 SET content = 'trois' WHERE rowid = 3"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 3}
} {trois}

do_test fts2i-1.4 {
  set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(4, 'four')}]
  set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 4}
} {four}

do_test fts2i-1.5 {
  set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(5, 'five')}]
  set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  set sql "UPDATE t1 SET content = 'cinq' WHERE rowid = 5"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 5}
} {cinq}

finish_test

Added test/fts2j.test.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 2007 February 6
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  This
# tests creating fts2 tables in an attached database.
#
# $Id: fts2j.test,v 1.1 2007/02/07 01:01:18 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Clean up anything left over from a previous pass.
file delete -force test2.db
file delete -force test2.db-journal
sqlite3 db2 test2.db

db eval {
  CREATE VIRTUAL TABLE t3 USING fts2(content);
  INSERT INTO t3 (rowid, content) VALUES(1, "hello world");
}

db2 eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1 (rowid, content) VALUES(1, "hello world");
  INSERT INTO t1 (rowid, content) VALUES(2, "hello there");
  INSERT INTO t1 (rowid, content) VALUES(3, "cruel world");
}

# This has always worked because the t1_* tables used by fts2 will be
# the defaults.
do_test fts2j-1.1 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    SELECT rowid FROM t1 WHERE t1 MATCH 'hello';
    DETACH DATABASE two;
  }
} {1 2}
# Make certain we're detached if there was an error.
catch {db eval {DETACH DATABASE two}}

# In older code, this appears to work fine, but the t2_* tables used
# by fts2 will be created in database 'main' instead of database
# 'two'.  It appears to work fine because the tables end up being the
# defaults, but obviously is badly broken if you hope to use things
# other than in the exact same ATTACH setup.
do_test fts2j-1.2 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    CREATE VIRTUAL TABLE two.t2 USING fts2(content);
    INSERT INTO t2 (rowid, content) VALUES(1, "hello world");
    INSERT INTO t2 (rowid, content) VALUES(2, "hello there");
    INSERT INTO t2 (rowid, content) VALUES(3, "cruel world");
    SELECT rowid FROM t2 WHERE t2 MATCH 'hello';
    DETACH DATABASE two;
  }
} {1 2}
catch {db eval {DETACH DATABASE two}}

# In older code, this broke because the fts2 code attempted to create
# t3_* tables in database 'main', but they already existed.  Normally
# this wouldn't happen without t3 itself existing, in which case the
# fts2 code would never be called in the first place.
do_test fts2j-1.3 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;

    CREATE VIRTUAL TABLE two.t3 USING fts2(content);
    INSERT INTO two.t3 (rowid, content) VALUES(2, "hello there");
    INSERT INTO two.t3 (rowid, content) VALUES(3, "cruel world");
    SELECT rowid FROM two.t3 WHERE t3 MATCH 'hello';

    DETACH DATABASE two;
  } db2
} {2}
catch {db eval {DETACH DATABASE two}}

catch {db2 close}
file delete -force test2.db

finish_test

Added test/fts2k.test.



















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 2007 March 9
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  These
# make sure that fts2 insertion buffering is fully transparent when
# using transactions.
#
# $Id: fts2k.test,v 1.2 2007/08/10 23:47:04 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(content);
  INSERT INTO t1 (rowid, content) VALUES(1, "hello world");
  INSERT INTO t1 (rowid, content) VALUES(2, "hello there");
  INSERT INTO t1 (rowid, content) VALUES(3, "cruel world");
}

# Test that possibly-buffered inserts went through after commit.
do_test fts2k-1.1 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(4, "false world");
    INSERT INTO t1 (rowid, content) VALUES(5, "false door");
    COMMIT TRANSACTION;
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
  }
} {1 3 4}

# Test that buffered inserts are seen by selects in the same
# transaction.
do_test fts2k-1.2 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(6, "another world");
    INSERT INTO t1 (rowid, content) VALUES(7, "another test");
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
    COMMIT TRANSACTION;
  }
} {1 3 4 6}

# Test that buffered inserts are seen within a transaction.  This is
# really the same test as 1.2.
do_test fts2k-1.3 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(8, "second world");
    INSERT INTO t1 (rowid, content) VALUES(9, "second sight");
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
    ROLLBACK TRANSACTION;
  }
} {1 3 4 6 8}

# Double-check that the previous result doesn't persist past the
# rollback!
do_test fts2k-1.4 {
  execsql {
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
  }
} {1 3 4 6}

# Test it all together.
do_test fts2k-1.5 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(10, "second world");
    INSERT INTO t1 (rowid, content) VALUES(11, "second sight");
    ROLLBACK TRANSACTION;
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
  }
} {1 3 4 6}

# Test that the obvious case works.
do_test fts2k-1.6 {
  execsql {
    BEGIN;
    INSERT INTO t1 (rowid, content) VALUES(12, "third world");
    COMMIT;
    SELECT rowid FROM t1 WHERE t1 MATCH 'third';
  }
} {12}

# This is exactly the same as the previous test, except that older
# code loses the INSERT due to an SQLITE_SCHEMA error.
do_test fts2k-1.7 {
  execsql {
    BEGIN;
    INSERT INTO t1 (rowid, content) VALUES(13, "third dimension");
    CREATE TABLE x (c);
    COMMIT;
    SELECT rowid FROM t1 WHERE t1 MATCH 'dimension';
  }
} {13}

finish_test

Added test/fts2l.test.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 2007 March 28
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing isspace/isalnum/tolower problems with the
# FTS2 module.  Unfortunately, this code isn't a really principled set
# of tests, because it is impossible to know where new uses of these
# functions might appear.
#
# $Id: fts2l.test,v 1.2 2007/12/13 21:54:11 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# Tests that startsWith() (calls isspace, tolower, isalnum) can handle
# hi-bit chars.  parseSpec() also calls isalnum here.
do_test fts2l-1.1 {
  execsql "CREATE VIRTUAL TABLE t1 USING fts2(content, \x80)"
} {}

# Additionally tests isspace() call in getToken(), and isalnum() call
# in tokenListToIdList().
do_test fts2l-1.2 {
  catch {
    execsql "CREATE VIRTUAL TABLE t2 USING fts2(content, tokenize \x80)"
  }
  sqlite3_errmsg $DB
} "unknown tokenizer: \x80"

# Additionally test final isalnum() in startsWith().
do_test fts2l-1.3 {
  execsql "CREATE VIRTUAL TABLE t3 USING fts2(content, tokenize\x80)"
} {}

# The snippet-generation code has calls to isspace() which are sort of
# hard to get to.  It finds convenient breakpoints by starting ~40
# chars before and after the matched term, and scanning ~10 chars
# around that position for isspace() characters.  The long word with
# embedded hi-bit chars causes one of these isspace() calls to be
# exercised.  The version with a couple extra spaces should cause the
# other isspace() call to be exercised.  [Both cases have been tested
# in the debugger, but I'm hoping to continue to catch it if simple
# constant changes change things slightly.
#
# The trailing and leading hi-bit chars help with code which tests for
# isspace() to coalesce multiple spaces.

set word "\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80"
set phrase1 "$word $word $word target $word $word $word"
set phrase2 "$word $word $word    target    $word $word $word"

db eval {CREATE VIRTUAL TABLE t4 USING fts2(content)}
db eval "INSERT INTO t4 (content) VALUES ('$phrase1')"
db eval "INSERT INTO t4 (content) VALUES ('$phrase2')"

do_test fts2l-1.4 {
  execsql {SELECT rowid, length(snippet(t4)) FROM t4 WHERE t4 MATCH 'target'}
} {1 111 2 117}

finish_test

Added test/fts2m.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2007 April 9
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  fts2
# DELETE handling assumed all fields were non-null.  This was not
# the intention at all.
#
# $Id: fts2m.test,v 1.1 2007/04/09 20:45:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(col_a, col_b);

  INSERT INTO t1(rowid, col_a, col_b) VALUES(1, 'testing', 'testing');
  INSERT INTO t1(rowid, col_a, col_b) VALUES(2, 'only a', null);
  INSERT INTO t1(rowid, col_a, col_b) VALUES(3, null, 'only b');
  INSERT INTO t1(rowid, col_a, col_b) VALUES(4, null, null);
}

do_test fts2m-1.0 {
  execsql {
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {2 2 4}

do_test fts2m-1.1 {
  execsql {
    DELETE FROM t1 WHERE rowid = 1;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {1 1 3}

do_test fts2m-1.2 {
  execsql {
    DELETE FROM t1 WHERE rowid = 2;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 1 2}

do_test fts2m-1.3 {
  execsql {
    DELETE FROM t1 WHERE rowid = 3;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 0 1}

do_test fts2m-1.4 {
  execsql {
    DELETE FROM t1 WHERE rowid = 4;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 0 0}

finish_test

Added test/fts2n.test.









































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# 2007 April 26
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements tests for prefix-searching in the fts2
# component of the SQLite library.
#
# $Id: fts2n.test,v 1.2 2007/12/13 21:54:11 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

# A large string to prime the pump with.
set text {
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
  iaculis mollis ipsum. Praesent rhoncus placerat justo. Duis non quam
  sed turpis posuere placerat. Curabitur et lorem in lorem porttitor
  aliquet. Pellentesque bibendum tincidunt diam. Vestibulum blandit
  ante nec elit. In sapien diam, facilisis eget, dictum sed, viverra
  at, felis. Vestibulum magna. Sed magna dolor, vestibulum rhoncus,
  ornare vel, vulputate sit amet, felis. Integer malesuada, tellus at
  luctus gravida, diam nunc porta nibh, nec imperdiet massa metus eu
  lectus. Aliquam nisi. Nunc fringilla nulla at lectus. Suspendisse
  potenti. Cum sociis natoque penatibus et magnis dis parturient
  montes, nascetur ridiculus mus. Pellentesque odio nulla, feugiat eu,
  suscipit nec, consequat quis, risus.
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(c);

  INSERT INTO t1(rowid, c) VALUES(1, $text);
  INSERT INTO t1(rowid, c) VALUES(2, 'Another lovely row');
}

# Exact match
do_test fts2n-1.1 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem'"
} {1}

# And a prefix
do_test fts2n-1.2 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore*'"
} {1}

# Prefix includes exact match
do_test fts2n-1.3 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem*'"
} {1}

# Make certain everything isn't considered a prefix!
do_test fts2n-1.4 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore'"
} {}

# Prefix across multiple rows.
do_test fts2n-1.5 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo*'"
} {1 2}

# Likewise, with multiple hits in one document.
do_test fts2n-1.6 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'l*'"
} {1 2}

# Prefix which should only hit one document.
do_test fts2n-1.7 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lov*'"
} {2}

# * not at end is dropped.
do_test fts2n-1.8 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo *'"
} {}

# Stand-alone * is dropped.
do_test fts2n-1.9 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '*'"
} {}

# Phrase-query prefix.
do_test fts2n-1.10 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r*\"'"
} {2}
do_test fts2n-1.11 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r\"'"
} {}

# Phrase query with multiple prefix matches.
do_test fts2n-1.12 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l*\"'"
} {1 2}

# Phrase query with multiple prefix matches.
do_test fts2n-1.13 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l* row\"'"
} {2}




# Test across updates (and, by implication, deletes).

# Version of text without "lorem".
regsub -all {[Ll]orem} $text '' ntext

db eval {
  CREATE VIRTUAL TABLE t2 USING fts2(c);

  INSERT INTO t2(rowid, c) VALUES(1, $text);
  INSERT INTO t2(rowid, c) VALUES(2, 'Another lovely row');
  UPDATE t2 SET c = $ntext WHERE rowid = 1;
}

# Can't see lorem as an exact match.
do_test fts2n-2.1 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lorem'"
} {}

# Can't see a prefix of lorem, either.
do_test fts2n-2.2 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lore*'"
} {}

# Can see lovely in the other document.
do_test fts2n-2.3 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lo*'"
} {2}

# Can still see other hits.
do_test fts2n-2.4 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'l*'"
} {1 2}

# Prefix which should only hit one document.
do_test fts2n-2.5 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lov*'"
} {2}



# Test with a segment which will have multiple levels in the tree.

# Build a big document with lots of unique terms.
set bigtext $text
foreach c {a b c d e} {
  regsub -all {[A-Za-z]+} $bigtext "&$c" t
  append bigtext $t
}

# Populate a table with many copies of the big document, so that we
# can test the number of hits found.  Populate $ret with the expected
# hit counts for each row.  offsets() returns 4 elements for every
# hit.  We'll have 6 hits for row 1, 1 for row 2, and 6*(2^5)==192 for
# $bigtext.
set ret {6 1}
db eval {
  BEGIN;
  CREATE VIRTUAL TABLE t3 USING fts2(c);

  INSERT INTO t3(rowid, c) VALUES(1, $text);
  INSERT INTO t3(rowid, c) VALUES(2, 'Another lovely row');
}
for {set i 0} {$i<100} {incr i} {
  db eval {INSERT INTO t3(rowid, c) VALUES(3+$i, $bigtext)}
  lappend ret 192
}
db eval {COMMIT;}

# Test that we get the expected number of hits.
do_test fts2n-3.1 {
  set t {}
  db eval {SELECT offsets(t3) as o FROM t3 WHERE t3 MATCH 'l*'} {
    set l [llength $o]
    lappend t [expr {$l/4}]
  }
  set t
} $ret

# TODO(shess) It would be useful to test a couple edge cases, but I
# don't know if we have the precision to manage it from here at this
# time.  Prefix hits can cross leaves, which the code above _should_
# hit by virtue of size.  There are two variations on this.  If the
# tree is 2 levels high, the code will find the leaf-node extent
# directly, but if its higher, the code will have to follow two
# separate interior branches down the tree.  Both should be tested.

finish_test

Added test/fts2o.test.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# 2007 June 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS2 module.
#
# $Id: fts2o.test,v 1.4 2007/07/02 10:16:50 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is not defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

#---------------------------------------------------------------------
# These tests, fts2o-1.*, test that ticket #2429 is fixed.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts2(a, b, c);
  INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two');
}
do_test fts2o-1.1 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE c MATCH 'four';
  }
} {1 {one <b>four</b> two}}
do_test fts2o-1.2 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE b MATCH 'four';
  }
} {1 {one <b>four</b>}}
do_test fts2o-1.3 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE a MATCH 'four';
  }
} {1 {one three <b>four</b>}}

#---------------------------------------------------------------------
# Test that it is possible to rename an fts2 table.
#
do_test fts2o-2.1 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {t1 t1_content t1_segments t1_segdir}
do_test fts2o-2.2 {
  execsql { ALTER TABLE t1 RENAME to fts_t1; }
} {}
do_test fts2o-2.3 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts2o-2.4 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir}

# See what happens when renaming the fts2 table fails.
#
do_test fts2o-2.5 {
  catchsql {
    CREATE TABLE t1_segdir(a, b, c);
    ALTER TABLE fts_t1 RENAME to t1;
  }
} {1 {SQL logic error or missing database}}
do_test fts2o-2.6 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts2o-2.7 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir}

# See what happens when renaming the fts2 table fails inside a transaction.
#
do_test fts2o-2.8 {
  execsql {
    BEGIN;
    INSERT INTO fts_t1(a, b, c) VALUES('one two three', 'one four', 'one two');
  }
} {}
do_test fts2o-2.9 {
  catchsql {
    ALTER TABLE fts_t1 RENAME to t1;
  }
} {1 {SQL logic error or missing database}}
do_test fts2o-2.10 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts2o-2.11 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir}
do_test fts2o-2.12 {
  execsql COMMIT
  execsql {SELECT a FROM fts_t1}
} {{one three four} {one two three}}
do_test fts2o-2.12 {
  execsql { SELECT a, b, c FROM fts_t1 WHERE c MATCH 'four'; }
} {{one three four} {one four} {one four two}}

#-------------------------------------------------------------------
# Close, delete and reopen the database. The following test should 
# be run on an initially empty db.
#
db close
file delete -force test.db test.db-journal
sqlite3 db test.db

do_test fts2o-3.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts2(a, b, c);
    INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one two');
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
  }
} {{one three four} {one four} {one two}}

# This test was crashing at one point.
#
do_test fts2o-3.2 {
  execsql {
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
    CREATE TABLE t3(a, b, c);
    SELECT a, b, c FROM t1 WHERE  c  MATCH 'two';
  }
} {{one three four} {one four} {one two} {one three four} {one four} {one two}}

#---------------------------------------------------------------------
# Test that it is possible to rename an fts2 table in an attached 
# database.
#
file delete -force test2.db test2.db-journal

do_test fts2o-3.1 {
  execsql {
    ATTACH 'test2.db' AS aux;
    CREATE VIRTUAL TABLE aux.t1 USING fts2(a, b, c);
    INSERT INTO aux.t1(a, b, c) VALUES(
      'neung song sahm', 'neung see', 'neung see song'
    );
  }
} {}

do_test fts2o-3.2 {
  execsql { SELECT a, b, c FROM aux.t1 WHERE a MATCH 'song'; }
} {{neung song sahm} {neung see} {neung see song}}

do_test fts2o-3.3 {
  execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; }
} {{one three four} {one four} {one two}}

do_test fts2o-3.4 {
  execsql { ALTER TABLE aux.t1 RENAME TO t2 }
} {}

do_test fts2o-3.2 {
  execsql { SELECT a, b, c FROM t2 WHERE a MATCH 'song'; }
} {{neung song sahm} {neung see} {neung see song}}

do_test fts2o-3.3 {
  execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; }
} {{one three four} {one four} {one two}}

finish_test

Added test/fts2p.test.











































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# 2008 June 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file exercises some new testing functions in the FTS2 module,
# and then uses them to do some basic tests that FTS2 is internally
# working as expected.
#
# $Id: fts2p.test,v 1.1 2008/07/22 23:32:28 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is not defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

#*************************************************************************
# Probe to see if support for these functions is compiled in.
# TODO(shess): Change main.mk to do the right thing and remove this test.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'x');
}

set s {SELECT dump_terms(t1, 1) FROM t1 LIMIT 1}
set r {1 {unable to use function dump_terms in the requested context}}
if {[catchsql $s]==$r} {
  finish_test
  return
}

#*************************************************************************
# Test that the new functions give appropriate errors.
do_test fts2p-0.0 {
  catchsql {
    SELECT dump_terms(t1, 1) FROM t1 LIMIT 1;
  }
} {1 {dump_terms: incorrect arguments}}

do_test fts2p-0.1 {
  catchsql {
    SELECT dump_terms(t1, 0, 0, 0) FROM t1 LIMIT 1;
  }
} {1 {dump_terms: incorrect arguments}}

do_test fts2p-0.2 {
  catchsql {
    SELECT dump_terms(1, t1) FROM t1 LIMIT 1;
  }
} {1 {unable to use function dump_terms in the requested context}}

do_test fts2p-0.3 {
  catchsql {
    SELECT dump_terms(t1, 16, 16) FROM t1 LIMIT 1;
  }
} {1 {dump_terms: segment not found}}

do_test fts2p-0.4 {
  catchsql {
    SELECT dump_doclist(t1) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: incorrect arguments}}

do_test fts2p-0.5 {
  catchsql {
    SELECT dump_doclist(t1, NULL) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: empty second argument}}

do_test fts2p-0.6 {
  catchsql {
    SELECT dump_doclist(t1, '') FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: empty second argument}}

do_test fts2p-0.7 {
  catchsql {
    SELECT dump_doclist(t1, 'a', 0) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: incorrect arguments}}

do_test fts2p-0.8 {
  catchsql {
    SELECT dump_doclist(t1, 'a', 0, 0, 0) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: incorrect arguments}}

do_test fts2p-0.9 {
  catchsql {
    SELECT dump_doclist(t1, 'a', 16, 16) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: segment not found}}

#*************************************************************************
# Utility function to check for the expected terms in the segment
# level/index.  _all version does same but for entire index.
proc check_terms {test level index terms} {
  # TODO(shess): Figure out why uplevel in do_test can't catch
  # $level and $index directly.
  set ::level $level
  set ::index $index
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $terms]
}
proc check_terms_all {test terms} {
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1) FROM t1 LIMIT 1;
    }
  } [list $terms]
}

# Utility function to check for the expected doclist for the term in
# segment level/index.  _all version does same for entire index.
proc check_doclist {test level index term doclist} {
  # TODO(shess): Again, why can't the non-:: versions work?
  set ::term $term
  set ::level $level
  set ::index $index
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}
proc check_doclist_all {test term doclist} {
  set ::term $term
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}

#*************************************************************************
# Test the segments resulting from straight-forward inserts.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
}

# Check for expected segments and expected matches.
do_test fts2p-1.0.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 0 2}
do_test fts2p-1.0.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \
        {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \
        {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}]

# Check the specifics of the segments constructed.
# Logical view of entire index.
check_terms_all   fts2p-1.0.1   {a is test that this was}
check_doclist_all fts2p-1.0.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist_all fts2p-1.0.1.2 is {[1 0[1]] [3 0[1]]}
check_doclist_all fts2p-1.0.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist_all fts2p-1.0.1.4 that {[2 0[0]]}
check_doclist_all fts2p-1.0.1.5 this {[1 0[0]] [3 0[0]]}
check_doclist_all fts2p-1.0.1.6 was {[2 0[1]]}

# Segment 0,0
check_terms   fts2p-1.0.2   0 0 {a is test this}
check_doclist fts2p-1.0.2.1 0 0 a {[1 0[2]]}
check_doclist fts2p-1.0.2.2 0 0 is {[1 0[1]]}
check_doclist fts2p-1.0.2.3 0 0 test {[1 0[3]]}
check_doclist fts2p-1.0.2.4 0 0 this {[1 0[0]]}

# Segment 0,1
check_terms   fts2p-1.0.3   0 1 {a test that was}
check_doclist fts2p-1.0.3.1 0 1 a {[2 0[2]]}
check_doclist fts2p-1.0.3.2 0 1 test {[2 0[3]]}
check_doclist fts2p-1.0.3.3 0 1 that {[2 0[0]]}
check_doclist fts2p-1.0.3.4 0 1 was {[2 0[1]]}

# Segment 0,2
check_terms   fts2p-1.0.4   0 2 {a is test this}
check_doclist fts2p-1.0.4.1 0 2 a {[3 0[2]]}
check_doclist fts2p-1.0.4.2 0 2 is {[3 0[1]]}
check_doclist fts2p-1.0.4.3 0 2 test {[3 0[3]]}
check_doclist fts2p-1.0.4.4 0 2 this {[3 0[0]]}

#*************************************************************************
# Test the segments resulting from inserts followed by a delete.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE rowid = 1;
}

do_test fts2p-1.1.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 0 2 0 3}
do_test fts2p-1.1.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}}

check_terms_all fts2p-1.1.1 {a is test that this was}
check_doclist_all fts2p-1.1.1.1 a {[2 0[2]] [3 0[2]]}
check_doclist_all fts2p-1.1.1.2 is {[3 0[1]]}
check_doclist_all fts2p-1.1.1.3 test {[2 0[3]] [3 0[3]]}
check_doclist_all fts2p-1.1.1.4 that {[2 0[0]]}
check_doclist_all fts2p-1.1.1.5 this {[3 0[0]]}
check_doclist_all fts2p-1.1.1.6 was {[2 0[1]]}

check_terms fts2p-1.1.2 0 0 {a is test this}
check_doclist fts2p-1.1.2.1 0 0 a {[1 0[2]]}
check_doclist fts2p-1.1.2.2 0 0 is {[1 0[1]]}
check_doclist fts2p-1.1.2.3 0 0 test {[1 0[3]]}
check_doclist fts2p-1.1.2.4 0 0 this {[1 0[0]]}

check_terms fts2p-1.1.3 0 1 {a test that was}
check_doclist fts2p-1.1.3.1 0 1 a {[2 0[2]]}
check_doclist fts2p-1.1.3.2 0 1 test {[2 0[3]]}
check_doclist fts2p-1.1.3.3 0 1 that {[2 0[0]]}
check_doclist fts2p-1.1.3.4 0 1 was {[2 0[1]]}

check_terms fts2p-1.1.4 0 2 {a is test this}
check_doclist fts2p-1.1.4.1 0 2 a {[3 0[2]]}
check_doclist fts2p-1.1.4.2 0 2 is {[3 0[1]]}
check_doclist fts2p-1.1.4.3 0 2 test {[3 0[3]]}
check_doclist fts2p-1.1.4.4 0 2 this {[3 0[0]]}

check_terms fts2p-1.1.5 0 3 {a is test this}
check_doclist fts2p-1.1.5.1 0 3 a {[1]}
check_doclist fts2p-1.1.5.2 0 3 is {[1]}
check_doclist fts2p-1.1.5.3 0 3 test {[1]}
check_doclist fts2p-1.1.5.4 0 3 this {[1]}

#*************************************************************************
# Test results when all references to certain tokens are deleted.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE rowid IN (1,3);
}

# Still 4 segments because 0,3 will contain deletes for rowid 1 and 3.
do_test fts2p-1.2.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 0 2 0 3}
do_test fts2p-1.2.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts2p-1.2.1 {a is test that this was}
check_doclist_all fts2p-1.2.1.1 a {[2 0[2]]}
check_doclist_all fts2p-1.2.1.2 is {}
check_doclist_all fts2p-1.2.1.3 test {[2 0[3]]}
check_doclist_all fts2p-1.2.1.4 that {[2 0[0]]}
check_doclist_all fts2p-1.2.1.5 this {}
check_doclist_all fts2p-1.2.1.6 was {[2 0[1]]}

check_terms fts2p-1.2.2 0 0 {a is test this}
check_doclist fts2p-1.2.2.1 0 0 a {[1 0[2]]}
check_doclist fts2p-1.2.2.2 0 0 is {[1 0[1]]}
check_doclist fts2p-1.2.2.3 0 0 test {[1 0[3]]}
check_doclist fts2p-1.2.2.4 0 0 this {[1 0[0]]}

check_terms fts2p-1.2.3 0 1 {a test that was}
check_doclist fts2p-1.2.3.1 0 1 a {[2 0[2]]}
check_doclist fts2p-1.2.3.2 0 1 test {[2 0[3]]}
check_doclist fts2p-1.2.3.3 0 1 that {[2 0[0]]}
check_doclist fts2p-1.2.3.4 0 1 was {[2 0[1]]}

check_terms fts2p-1.2.4 0 2 {a is test this}
check_doclist fts2p-1.2.4.1 0 2 a {[3 0[2]]}
check_doclist fts2p-1.2.4.2 0 2 is {[3 0[1]]}
check_doclist fts2p-1.2.4.3 0 2 test {[3 0[3]]}
check_doclist fts2p-1.2.4.4 0 2 this {[3 0[0]]}

check_terms fts2p-1.2.5 0 3 {a is test this}
check_doclist fts2p-1.2.5.1 0 3 a {[1] [3]}
check_doclist fts2p-1.2.5.2 0 3 is {[1] [3]}
check_doclist fts2p-1.2.5.3 0 3 test {[1] [3]}
check_doclist fts2p-1.2.5.4 0 3 this {[1] [3]}

#*************************************************************************
# Test results when everything is optimized manually.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE rowid IN (1,3);
  DROP TABLE IF EXISTS t1old;
  ALTER TABLE t1 RENAME TO t1old;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) SELECT rowid, c FROM t1old;
  DROP TABLE t1old;
}

# Should be a single optimal segment with the same logical results.
do_test fts2p-1.3.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts2p-1.3.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts2p-1.3.1 {a test that was}
check_doclist_all fts2p-1.3.1.1 a {[2 0[2]]}
check_doclist_all fts2p-1.3.1.2 test {[2 0[3]]}
check_doclist_all fts2p-1.3.1.3 that {[2 0[0]]}
check_doclist_all fts2p-1.3.1.4 was {[2 0[1]]}

check_terms fts2p-1.3.2 0 0 {a test that was}
check_doclist fts2p-1.3.2.1 0 0 a {[2 0[2]]}
check_doclist fts2p-1.3.2.2 0 0 test {[2 0[3]]}
check_doclist fts2p-1.3.2.3 0 0 that {[2 0[0]]}
check_doclist fts2p-1.3.2.4 0 0 was {[2 0[1]]}

finish_test

Added test/fts2q.test.





















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# 2008 June 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing the FTS2 module's optimize() function.
#
# $Id: fts2q.test,v 1.2 2008/07/22 23:49:44 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is not defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

#*************************************************************************
# Probe to see if support for the FTS2 dump_* functions is compiled in.
# TODO(shess): Change main.mk to do the right thing and remove this test.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'x');
}

set s {SELECT dump_terms(t1, 1) FROM t1 LIMIT 1}
set r {1 {unable to use function dump_terms in the requested context}}
if {[catchsql $s]==$r} {
  finish_test
  return
}

#*************************************************************************
# Utility function to check for the expected terms in the segment
# level/index.  _all version does same but for entire index.
proc check_terms {test level index terms} {
  # TODO(shess): Figure out why uplevel in do_test can't catch
  # $level and $index directly.
  set ::level $level
  set ::index $index
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $terms]
}
proc check_terms_all {test terms} {
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1) FROM t1 LIMIT 1;
    }
  } [list $terms]
}

# Utility function to check for the expected doclist for the term in
# segment level/index.  _all version does same for entire index.
proc check_doclist {test level index term doclist} {
  # TODO(shess): Again, why can't the non-:: versions work?
  set ::term $term
  set ::level $level
  set ::index $index
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}
proc check_doclist_all {test term doclist} {
  set ::term $term
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}

#*************************************************************************
# Test results when all rows are deleted and one is added back.
# Previously older segments would continue to exist, but now the index
# should be dropped when the table is empty.  The results should look
# exactly like we never added the earlier rows in the first place.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE 1=1; -- Delete each row rather than dropping table.
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
}

# Should be a single initial segment.
do_test fts2q-1.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts2q-1.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} {{0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}}

check_terms_all fts2q-1.1 {a is test this}
check_doclist_all fts2q-1.1.1 a {[1 0[2]]}
check_doclist_all fts2q-1.1.2 is {[1 0[1]]}
check_doclist_all fts2q-1.1.3 test {[1 0[3]]}
check_doclist_all fts2q-1.1.4 this {[1 0[0]]}

check_terms   fts2q-1.2   0 0 {a is test this}
check_doclist fts2q-1.2.1 0 0 a {[1 0[2]]}
check_doclist fts2q-1.2.2 0 0 is {[1 0[1]]}
check_doclist fts2q-1.2.3 0 0 test {[1 0[3]]}
check_doclist fts2q-1.2.4 0 0 this {[1 0[0]]}

#*************************************************************************
# Test results when everything is optimized manually.
# NOTE(shess): This is a copy of fts2c-1.3.  I've pulled a copy here
# because fts2q-2 and fts2q-3 should have identical results.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE rowid IN (1,3);
  DROP TABLE IF EXISTS t1old;
  ALTER TABLE t1 RENAME TO t1old;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) SELECT rowid, c FROM t1old;
  DROP TABLE t1old;
}

# Should be a single optimal segment with the same logical results.
do_test fts2q-2.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts2q-2.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts2q-2.1 {a test that was}
check_doclist_all fts2q-2.1.1 a {[2 0[2]]}
check_doclist_all fts2q-2.1.2 test {[2 0[3]]}
check_doclist_all fts2q-2.1.3 that {[2 0[0]]}
check_doclist_all fts2q-2.1.4 was {[2 0[1]]}

check_terms fts2q-2.2 0 0 {a test that was}
check_doclist fts2q-2.2.1 0 0 a {[2 0[2]]}
check_doclist fts2q-2.2.2 0 0 test {[2 0[3]]}
check_doclist fts2q-2.2.3 0 0 that {[2 0[0]]}
check_doclist fts2q-2.2.4 0 0 was {[2 0[1]]}

#*************************************************************************
# Test results when everything is optimized via optimize().
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE rowid IN (1,3);
  SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
}

# Should be a single optimal segment with the same logical results.
do_test fts2q-3.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts2q-3.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts2q-3.1 {a test that was}
check_doclist_all fts2q-3.1.1 a {[2 0[2]]}
check_doclist_all fts2q-3.1.2 test {[2 0[3]]}
check_doclist_all fts2q-3.1.3 that {[2 0[0]]}
check_doclist_all fts2q-3.1.4 was {[2 0[1]]}

check_terms fts2q-3.2 0 0 {a test that was}
check_doclist fts2q-3.2.1 0 0 a {[2 0[2]]}
check_doclist fts2q-3.2.2 0 0 test {[2 0[3]]}
check_doclist fts2q-3.2.3 0 0 that {[2 0[0]]}
check_doclist fts2q-3.2.4 0 0 was {[2 0[1]]}

#*************************************************************************
# Test optimize() against a table involving segment merges.
# NOTE(shess): Since there's no transaction, each of the INSERT/UPDATE
# statements generates a segment.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);

  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');

  UPDATE t1 SET c = 'This is a test one' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test one' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test one' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test two' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test two' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test two' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test three' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test three' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test three' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test four' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test four' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test four' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test' WHERE rowid = 3;
}

# 2 segments in level 0, 1 in level 1 (18 segments created, 16
# merged).
do_test fts2q-4.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 1 0}

do_test fts2q-4.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \
        {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \
        {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}]

check_terms_all fts2q-4.1      {a four is one test that this three two was}
check_doclist_all fts2q-4.1.1  a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist_all fts2q-4.1.2  four {}
check_doclist_all fts2q-4.1.3  is {[1 0[1]] [3 0[1]]}
check_doclist_all fts2q-4.1.4  one {}
check_doclist_all fts2q-4.1.5  test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist_all fts2q-4.1.6  that {[2 0[0]]}
check_doclist_all fts2q-4.1.7  this {[1 0[0]] [3 0[0]]}
check_doclist_all fts2q-4.1.8  three {}
check_doclist_all fts2q-4.1.9  two {}
check_doclist_all fts2q-4.1.10 was {[2 0[1]]}

check_terms fts2q-4.2     0 0 {a four test that was}
check_doclist fts2q-4.2.1 0 0 a {[2 0[2]]}
check_doclist fts2q-4.2.2 0 0 four {[2]}
check_doclist fts2q-4.2.3 0 0 test {[2 0[3]]}
check_doclist fts2q-4.2.4 0 0 that {[2 0[0]]}
check_doclist fts2q-4.2.5 0 0 was {[2 0[1]]}

check_terms fts2q-4.3     0 1 {a four is test this}
check_doclist fts2q-4.3.1 0 1 a {[3 0[2]]}
check_doclist fts2q-4.3.2 0 1 four {[3]}
check_doclist fts2q-4.3.3 0 1 is {[3 0[1]]}
check_doclist fts2q-4.3.4 0 1 test {[3 0[3]]}
check_doclist fts2q-4.3.5 0 1 this {[3 0[0]]}

check_terms fts2q-4.4      1 0 {a four is one test that this three two was}
check_doclist fts2q-4.4.1  1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist fts2q-4.4.2  1 0 four {[1] [2 0[4]] [3 0[4]]}
check_doclist fts2q-4.4.3  1 0 is {[1 0[1]] [3 0[1]]}
check_doclist fts2q-4.4.4  1 0 one {[1] [2] [3]}
check_doclist fts2q-4.4.5  1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist fts2q-4.4.6  1 0 that {[2 0[0]]}
check_doclist fts2q-4.4.7  1 0 this {[1 0[0]] [3 0[0]]}
check_doclist fts2q-4.4.8  1 0 three {[1] [2] [3]}
check_doclist fts2q-4.4.9  1 0 two {[1] [2] [3]}
check_doclist fts2q-4.4.10 1 0 was {[2 0[1]]}

# Optimize should leave the result in the level of the highest-level
# prior segment.
do_test fts2q-4.5 {
  execsql {
    SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {{Index optimized} 1 0}

# Identical to fts2q-4.matches.
do_test fts2q-4.5.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid;
  }
} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \
        {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \
        {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}]

check_terms_all fts2q-4.5.1     {a is test that this was}
check_doclist_all fts2q-4.5.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist_all fts2q-4.5.1.2 is {[1 0[1]] [3 0[1]]}
check_doclist_all fts2q-4.5.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist_all fts2q-4.5.1.4 that {[2 0[0]]}
check_doclist_all fts2q-4.5.1.5 this {[1 0[0]] [3 0[0]]}
check_doclist_all fts2q-4.5.1.6 was {[2 0[1]]}

check_terms fts2q-4.5.2     1 0 {a is test that this was}
check_doclist fts2q-4.5.2.1 1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist fts2q-4.5.2.2 1 0 is {[1 0[1]] [3 0[1]]}
check_doclist fts2q-4.5.2.3 1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist fts2q-4.5.2.4 1 0 that {[2 0[0]]}
check_doclist fts2q-4.5.2.5 1 0 this {[1 0[0]] [3 0[0]]}
check_doclist fts2q-4.5.2.6 1 0 was {[2 0[1]]}

# Re-optimizing does nothing.
do_test fts2q-5.0 {
  execsql {
    SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {{Index already optimal} 1 0}

# Even if we move things around, still does nothing.
do_test fts2q-5.1 {
  execsql {
    UPDATE t1_segdir SET level = 2 WHERE level = 1 AND idx = 0;
    SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {{Index already optimal} 2 0}

finish_test

Added test/fts2r.test.



















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# 2008 July 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# These tests exercise the various types of fts2 cursors.
#
# $Id: fts2r.test,v 1.1 2008/07/29 20:38:18 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is not defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

#*************************************************************************
# Test table scan (QUERY_GENERIC).  This kind of query happens for
# queries with no WHERE clause, or for WHERE clauses which cannot be
# satisfied by an index.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');
}

do_test fts2e-1.1 {
  execsql {
    SELECT rowid FROM t1 ORDER BY rowid;
  }
} {1 2 3}

do_test fts2e-1.2 {
  execsql {
    SELECT rowid FROM t1 WHERE c LIKE '%test' ORDER BY rowid;
  }
} {1 2 3}

do_test fts2e-1.3 {
  execsql {
    SELECT rowid FROM t1 WHERE c LIKE 'That%' ORDER BY rowid;
  }
} {2}

#*************************************************************************
# Test lookup by rowid (QUERY_ROWID).  This kind of query happens for
# queries which select by the rowid implicit index.
db eval {
  DROP TABLE IF EXISTS t1;
  DROP TABLE IF EXISTS t2;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE);
  INSERT INTO t2 VALUES (null, 10);
  INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test');
  INSERT INTO t2 VALUES (null, 5);
  INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'That was a test');
  INSERT INTO t2 VALUES (null, 20);
  INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test');
}

# TODO(shess): This actually is doing QUERY_GENERIC?  I'd have
# expected QUERY_ROWID in this case, as for a very large table the
# full scan is less efficient.
do_test fts2e-2.1 {
  execsql {
    SELECT rowid FROM t1 WHERE rowid in (1, 2, 10);
  }
} {1 2}

do_test fts2e-2.2 {
  execsql {
    SELECT t1.rowid, weight FROM t1, t2 WHERE t2.id = t1.rowid ORDER BY weight;
  }
} {2 5 1 10 3 20}

do_test fts2e-2.3 {
  execsql {
    SELECT t1.rowid, weight FROM t1, t2
           WHERE t2.weight>5 AND t2.id = t1.rowid ORDER BY weight;
  }
} {1 10 3 20}

#*************************************************************************
# Test lookup by MATCH (QUERY_FULLTEXT).  This is the fulltext index.
db eval {
  DROP TABLE IF EXISTS t1;
  DROP TABLE IF EXISTS t2;
  CREATE VIRTUAL TABLE t1 USING fts2(c);
  CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE);
  INSERT INTO t2 VALUES (null, 10);
  INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test');
  INSERT INTO t2 VALUES (null, 5);
  INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'That was a test');
  INSERT INTO t2 VALUES (null, 20);
  INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test');
}

do_test fts2e-3.1 {
  execsql {
    SELECT rowid FROM t1 WHERE t1 MATCH 'this' ORDER BY rowid;
  }
} {1 3}

do_test fts2e-3.2 {
  execsql {
    SELECT t1.rowid, weight FROM t1, t2
     WHERE t1 MATCH 'this' AND t1.rowid = t2.id ORDER BY weight;
  }
} {1 10 3 20}

finish_test

Added test/fts2token.test.





























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# 2007 June 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library. The focus 
# of this script is testing the pluggable tokeniser feature of the 
# FTS2 module.
#
# $Id: fts2token.test,v 1.3 2007/06/25 12:05:40 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS2 is defined, omit this file.
ifcapable !fts2 {
  finish_test
  return
}

proc escape_string {str} {
  set out ""
  foreach char [split $str ""] {
    scan $char %c i
    if {$i<=127} {
      append out $char
    } else {
      append out [format {\x%.4x} $i]
    }
  }
  set out
}

#--------------------------------------------------------------------------
# Test cases fts2token-1.* are the warm-body test for the SQL scalar
# function fts2_tokenizer(). The procedure is as follows:
#
#   1: Verify that there is no such fts2 tokenizer as 'blah'.
#
#   2: Query for the built-in tokenizer 'simple'. Insert a copy of the
#      retrieved value as tokenizer 'blah'.
#
#   3: Test that the value returned for tokenizer 'blah' is now the
#      same as that retrieved for 'simple'.
#
#   4: Test that it is now possible to create an fts2 table using 
#      tokenizer 'blah' (it was not possible in step 1).
#
#   5: Test that the table created to use tokenizer 'blah' is usable.
#
do_test fts2token-1.1 {
  catchsql {
    CREATE VIRTUAL TABLE t1 USING fts2(content, tokenize blah);
  }
} {1 {unknown tokenizer: blah}}
do_test fts2token-1.2 {
  execsql {
    SELECT fts2_tokenizer('blah', fts2_tokenizer('simple')) IS NULL;
  }
} {0}
do_test fts2token-1.3 {
  execsql {
    SELECT fts2_tokenizer('blah') == fts2_tokenizer('simple');
  }
} {1}
do_test fts2token-1.4 {
  catchsql {
    CREATE VIRTUAL TABLE t1 USING fts2(content, tokenize blah);
  }
} {0 {}}
do_test fts2token-1.5 {
  execsql {
    INSERT INTO t1(content) VALUES('There was movement at the station');
    INSERT INTO t1(content) VALUES('For the word has passed around');
    INSERT INTO t1(content) VALUES('That the colt from ol regret had got away');
    SELECT content FROM t1 WHERE content MATCH 'movement'
  }
} {{There was movement at the station}}

#--------------------------------------------------------------------------
# Test cases fts2token-2.* test error cases in the scalar function based
# API for getting and setting tokenizers.
#
do_test fts2token-2.1 {
  catchsql {
    SELECT fts2_tokenizer('nosuchtokenizer');
  }
} {1 {unknown tokenizer: nosuchtokenizer}}

#--------------------------------------------------------------------------
# Test cases fts2token-3.* test the three built-in tokenizers with a
# simple input string via the built-in test function. This is as much
# to test the test function as the tokenizer implementations.
#
do_test fts2token-3.1 {
  execsql {
    SELECT fts2_tokenizer_test('simple', 'I don''t see how');
  }
} {{0 i I 1 don don 2 t t 3 see see 4 how how}}
do_test fts2token-3.2 {
  execsql {
    SELECT fts2_tokenizer_test('porter', 'I don''t see how');
  }
} {{0 i I 1 don don 2 t t 3 see see 4 how how}}
ifcapable icu {
  do_test fts2token-3.3 {
    execsql {
      SELECT fts2_tokenizer_test('icu', 'I don''t see how');
    }
  } {{0 i I 1 don't don't 2 see see 3 how how}}
}

#--------------------------------------------------------------------------
# Test cases fts2token-4.* test the ICU tokenizer. In practice, this
# tokenizer only has two modes - "thai" and "everybody else". Some other
# Asian languages (Lao, Khmer etc.) require the same special treatment as 
# Thai, but ICU doesn't support them yet.
#
ifcapable icu {

  proc do_icu_test {name locale input output} {
    set ::out [db eval { SELECT fts2_tokenizer_test('icu', $locale, $input) }]
    do_test $name {
      lindex $::out 0
    } $output
  }
  
  do_icu_test fts2token-4.1 en_US  {}   {}
  do_icu_test fts2token-4.2 en_US {Test cases fts2} [list \
    0 test Test 1 cases cases 2 fts2 fts2
  ]

  # The following test shows that ICU is smart enough to recognise
  # Thai chararacters, even when the locale is set to English/United 
  # States.
  #
  set input "\u0e2d\u0e30\u0e44\u0e23\u0e19\u0e30\u0e04\u0e23\u0e31\u0e1a"
  set output    "0 \u0e2d\u0e30\u0e44\u0e23 \u0e2d\u0e30\u0e44\u0e23 "
  append output "1 \u0e19\u0e30 \u0e19\u0e30 "
  append output "2 \u0e04\u0e23\u0e31\u0e1a \u0e04\u0e23\u0e31\u0e1a"

  do_icu_test fts2token-4.3 th_TH  $input $output
  do_icu_test fts2token-4.4 en_US  $input $output

  # ICU handles an unknown locale by falling back to the default.
  # So this is not an error.
  do_icu_test fts2token-4.5 MiddleOfTheOcean  $input $output

  set    longtoken "AReallyReallyLongTokenOneThatWillSurelyRequire"
  append longtoken "AReallocInTheIcuTokenizerCode"

  set    input "short tokens then "
  append input $longtoken
  set    output "0 short short "
  append output "1 tokens tokens "
  append output "2 then then "
  append output "3 [string tolower $longtoken] $longtoken"

  do_icu_test fts2token-4.6 MiddleOfTheOcean  $input $output
  do_icu_test fts2token-4.7 th_TH  $input $output
  do_icu_test fts2token-4.8 en_US  $input $output
}

do_test fts2token-internal {
  execsql { SELECT fts2_tokenizer_internal_test() }
} {ok}

finish_test

Added test/fts3.test.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 2007 November 23
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all tests.
#
# $Id: fts3.test,v 1.2 2008/07/23 18:17:32 drh Exp $

proc lshift {lvar} {
  upvar $lvar l
  set ret [lindex $l 0]
  set l [lrange $l 1 end]
  return $ret
}
while {[set arg [lshift argv]] != ""} {
  switch -- $arg {
    -sharedpagercache {
      sqlite3_enable_shared_cache 1
    }
    -soak {
       set SOAKTEST 1
    }
    default {
      set argv [linsert $argv 0 $arg]
      break
    }
  }
}

set testdir [file dirname $argv0]
source $testdir/tester.tcl
# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  return
}
rename finish_test really_finish_test
proc finish_test {} {}
set ISQUICK 1

set EXCLUDE {
  fts3.test
}

# Files to include in the test.  If this list is empty then everything
# that is not in the EXCLUDE list is run.
#
set INCLUDE {
}

foreach testfile [lsort -dictionary [glob $testdir/fts3*.test]] {
  set tail [file tail $testfile]
  if {[lsearch -exact $EXCLUDE $tail]>=0} continue
  if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue
  source $testfile
  catch {db close}
  if {$sqlite_open_file_count>0} {
    puts "$tail did not close all files: $sqlite_open_file_count"
    incr nErr
    lappend ::failList $tail
    set sqlite_open_file_count 0
  }
}

set sqlite_open_file_count 0
really_finish_test

Added test/fts3aa.test.





















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# 2006 September 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module.
#
# $Id: fts3aa.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Construct a full-text search table containing five keywords:
# one, two, three, four, and five, in various combinations.  The
# rowid for each will be a bitmask for the elements it contains.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1(content) VALUES('one');
  INSERT INTO t1(content) VALUES('two');
  INSERT INTO t1(content) VALUES('one two');
  INSERT INTO t1(content) VALUES('three');
  INSERT INTO t1(content) VALUES('one three');
  INSERT INTO t1(content) VALUES('two three');
  INSERT INTO t1(content) VALUES('one two three');
  INSERT INTO t1(content) VALUES('four');
  INSERT INTO t1(content) VALUES('one four');
  INSERT INTO t1(content) VALUES('two four');
  INSERT INTO t1(content) VALUES('one two four');
  INSERT INTO t1(content) VALUES('three four');
  INSERT INTO t1(content) VALUES('one three four');
  INSERT INTO t1(content) VALUES('two three four');
  INSERT INTO t1(content) VALUES('one two three four');
  INSERT INTO t1(content) VALUES('five');
  INSERT INTO t1(content) VALUES('one five');
  INSERT INTO t1(content) VALUES('two five');
  INSERT INTO t1(content) VALUES('one two five');
  INSERT INTO t1(content) VALUES('three five');
  INSERT INTO t1(content) VALUES('one three five');
  INSERT INTO t1(content) VALUES('two three five');
  INSERT INTO t1(content) VALUES('one two three five');
  INSERT INTO t1(content) VALUES('four five');
  INSERT INTO t1(content) VALUES('one four five');
  INSERT INTO t1(content) VALUES('two four five');
  INSERT INTO t1(content) VALUES('one two four five');
  INSERT INTO t1(content) VALUES('three four five');
  INSERT INTO t1(content) VALUES('one three four five');
  INSERT INTO t1(content) VALUES('two three four five');
  INSERT INTO t1(content) VALUES('one two three four five');
}

do_test fts3aa-1.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts3aa-1.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two'}
} {3 7 11 15 19 23 27 31}
do_test fts3aa-1.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one'}
} {3 7 11 15 19 23 27 31}
do_test fts3aa-1.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two three'}
} {7 15 23 31}
do_test fts3aa-1.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one three two'}
} {7 15 23 31}
do_test fts3aa-1.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two three one'}
} {7 15 23 31}
do_test fts3aa-1.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one three'}
} {7 15 23 31}
do_test fts3aa-1.8 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three one two'}
} {7 15 23 31}
do_test fts3aa-1.9 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three two one'}
} {7 15 23 31}
do_test fts3aa-1.10 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two THREE'}
} {7 15 23 31}
do_test fts3aa-1.11 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '  ONE    Two   three  '}
} {7 15 23 31}

do_test fts3aa-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one"'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts3aa-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two"'}
} {3 7 11 15 19 23 27 31}
do_test fts3aa-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"two one"'}
} {}
do_test fts3aa-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three"'}
} {7 15 23 31}
do_test fts3aa-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two"'}
} {}
do_test fts3aa-2.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three four"'}
} {15 31}
do_test fts3aa-2.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two four"'}
} {}
do_test fts3aa-2.8 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three five"'}
} {21}
do_test fts3aa-2.9 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" five'}
} {21 29}
do_test fts3aa-2.10 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three"'}
} {21 29}
do_test fts3aa-2.11 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three" four'}
} {29}
do_test fts3aa-2.12 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five four "one three"'}
} {29}
do_test fts3aa-2.13 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" four five'}
} {29}

do_test fts3aa-3.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts3aa-3.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one -two'}
} {1 5 9 13 17 21 25 29}
do_test fts3aa-3.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '-two one'}
} {1 5 9 13 17 21 25 29}

do_test fts3aa-4.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one OR two'}
} {1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21 22 23 25 26 27 29 30 31}
do_test fts3aa-4.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two" OR three'}
} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31}
do_test fts3aa-4.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR "one two"'}
} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31}
do_test fts3aa-4.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three'}
} {3 5 7 11 13 15 19 21 23 27 29 31}
do_test fts3aa-4.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR two one'}
} {3 5 7 11 13 15 19 21 23 27 29 31}
do_test fts3aa-4.6 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three OR four'}
} {3 5 7 9 11 13 15 19 21 23 25 27 29 31}
do_test fts3aa-4.7 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two OR three OR four one'}
} {3 5 7 9 11 13 15 19 21 23 25 27 29 31}

# Test the ability to handle NULL content
#
do_test fts3aa-5.1 {
  execsql {INSERT INTO t1(content) VALUES(NULL)}
} {}
do_test fts3aa-5.2 {
  set rowid [db last_insert_rowid]
  execsql {SELECT content FROM t1 WHERE rowid=$rowid}
} {{}}
do_test fts3aa-5.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH NULL}
} {}

# Test the ability to handle non-positive rowids
#
do_test fts3aa-6.0 {
  execsql {INSERT INTO t1(rowid, content) VALUES(0, 'four five')}
} {}
do_test fts3aa-6.1 {
  execsql {SELECT content FROM t1 WHERE rowid = 0}
} {{four five}}
do_test fts3aa-6.2 {
  execsql {INSERT INTO t1(rowid, content) VALUES(-1, 'three four')}
} {}
do_test fts3aa-6.3 {
  execsql {SELECT content FROM t1 WHERE rowid = -1}
} {{three four}}
do_test fts3aa-6.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'four'}
} {-1 0 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31}

finish_test

Added test/fts3ab.test.







































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# 2006 September 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module.
#
# $Id: fts3ab.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Fill the full-text index "t1" with phrases in english, spanish,
# and german.  For the i-th row, fill in the names for the bits
# that are set in the value of i.  The least significant bit is
# 1.  For example,  the value 5 is 101 in binary which will be
# converted to "one three" in english.
#
proc fill_multilanguage_fulltext_t1 {} {
  set english {one two three four five}
  set spanish {un dos tres cuatro cinco}
  set german {eine zwei drei vier funf}
  
  for {set i 1} {$i<=31} {incr i} {
    set cmd "INSERT INTO t1 VALUES"
    set vset {}
    foreach lang {english spanish german} {
      set words {}
      for {set j 0; set k 1} {$j<5} {incr j; incr k $k} {
        if {$k&$i} {lappend words [lindex [set $lang] $j]}
      }
      lappend vset "'$words'"
    }
    set sql "INSERT INTO t1(english,spanish,german) VALUES([join $vset ,])"
    # puts $sql
    db eval $sql
  }
}

# Construct a full-text search table containing five keywords:
# one, two, three, four, and five, in various combinations.  The
# rowid for each will be a bitmask for the elements it contains.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(english,spanish,german);
}
fill_multilanguage_fulltext_t1

do_test fts3ab-1.1 {
  execsql {SELECT rowid FROM t1 WHERE english MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts3ab-1.2 {
  execsql {SELECT rowid FROM t1 WHERE spanish MATCH 'one'}
} {}
do_test fts3ab-1.3 {
  execsql {SELECT rowid FROM t1 WHERE german MATCH 'one'}
} {}
do_test fts3ab-1.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one'}
} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31}
do_test fts3ab-1.5 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one dos drei'}
} {7 15 23 31}
do_test fts3ab-1.6 {
  execsql {SELECT english, spanish, german FROM t1 WHERE rowid=1}
} {one un eine}
do_test fts3ab-1.7 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"one un"'}
} {}

do_test fts3ab-2.1 {
  execsql {
    CREATE VIRTUAL TABLE t2 USING fts3(from,to);
    INSERT INTO t2([from],[to]) VALUES ('one two three', 'four five six');
    SELECT [from], [to] FROM t2
  }
} {{one two three} {four five six}}


# Compute an SQL string that contains the words one, two, three,... to
# describe bits set in the value $i.  Only the lower 5 bits are examined.
#
proc wordset {i} {
  set x {}
  for {set j 0; set k 1} {$j<5} {incr j; incr k $k} {
    if {$k&$i} {lappend x [lindex {one two three four five} $j]}
  }
  return '$x'
}

# Create a new FTS table with three columns:
#
#    norm:      words for the bits of rowid
#    plusone:   words for the bits of rowid+1
#    invert:    words for the bits of ~rowid
#
db eval {
   CREATE VIRTUAL TABLE t4 USING fts3([norm],'plusone',"invert");
}
for {set i 1} {$i<=15} {incr i} {
  set vset [list [wordset $i] [wordset [expr {$i+1}]] [wordset [expr {~$i}]]]
  db eval "INSERT INTO t4(norm,plusone,invert) VALUES([join $vset ,]);"
}

do_test fts3ab-4.1 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one'}
} {1 3 5 7 9 11 13 15}
do_test fts3ab-4.2 {
  execsql {SELECT rowid FROM t4 WHERE norm MATCH 'one'}
} {1 3 5 7 9 11 13 15}
do_test fts3ab-4.3 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'one'}
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}
do_test fts3ab-4.4 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:one'}
} {2 4 6 8 10 12 14}
do_test fts3ab-4.5 {
  execsql {SELECT rowid FROM t4 WHERE plusone MATCH 'one'}
} {2 4 6 8 10 12 14}
do_test fts3ab-4.6 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one plusone:two'}
} {1 5 9 13}
do_test fts3ab-4.7 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one two'}
} {1 3 5 7 9 11 13 15}
do_test fts3ab-4.8 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:two norm:one'}
} {1 5 9 13}
do_test fts3ab-4.9 {
  execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'two norm:one'}
} {1 3 5 7 9 11 13 15}


finish_test

Added test/fts3ac.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# 2006 September 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module.
#
# $Id: fts3ac.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Create a table of sample email data.   The data comes from email
# archives of Enron executives that was published as part of the
# litigation against that company.
#
do_test fts3ac-1.1 {
  db eval {
    CREATE VIRTUAL TABLE email USING fts3([from],[to],subject,body);
    BEGIN TRANSACTION;
INSERT INTO email([from],[to],subject,body) VALUES('savita.puthigai@enron.com', 'traders.eol@enron.com, traders.eol@enron.com', 'EnronOnline- Change to Autohedge', 'Effective Monday, October 22, 2001 the following changes will be made to the Autohedge functionality on EnronOnline.

The volume on the hedge will now respect the minimum volume and volume increment settings on the parent product. See rules below: 

?	If the transaction volume on the child is less than half of the parent''s minimum volume no hedge will occur.
?	If the transaction volume on the child is more than half the parent''s minimum volume but less than half the volume increment on the parent, the hedge will volume will be the parent''s minimum volume.
?	For all other volumes, the same rounding rules will apply based on the volume increment on the parent product.

Please see example below:

Parent''s Settings:
Minimum: 	5000
Increment:  1000

Volume on Autohedge transaction			Volume Hedged
1      - 2499							0
2500 - 5499							5000
5500 - 6499							6000');
INSERT INTO email([from],[to],subject,body) VALUES('dana.davis@enron.com', 'laynie.east@enron.com, lisa.king@enron.com, lisa.best@enron.com,', 'Leaving Early', 'FYI:  
If it''s ok with everyone''s needs, I would like to leave @4pm. If you think 
you will need my assistance past the 4 o''clock hour just let me know;  I''ll 
be more than willing to stay.');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'louise.kitchen@enron.com', '<<Concur Expense Document>> - CC02.06.02', 'The following expense report is ready for approval:

Employee Name: Christopher F. Calger
Status last changed by: Mollie E. Gustafson Ms
Expense Report Name: CC02.06.02
Report Total: $3,972.93
Amount Due Employee: $3,972.93


To approve this expense report, click on the following link for Concur Expense.
http://expensexms.enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('jeff.duff@enron.com', 'julie.johnson@enron.com', 'Work request', 'Julie,

Could you print off the current work request report by 1:30 today?

Gentlemen,

I''d like to review this today at 1:30 in our office.  Also, could you provide 
me with your activity reports so I can have Julie enter this information.

JD');
INSERT INTO email([from],[to],subject,body) VALUES('v.weldon@enron.com', 'gary.l.carrier@usa.dupont.com, scott.joyce@bankofamerica.com', 'Enron News', 'This could turn into something big.... 
http://biz.yahoo.com/rf/010129/n29305829.html');
INSERT INTO email([from],[to],subject,body) VALUES('mark.haedicke@enron.com', 'paul.simons@enron.com', 'Re: First Polish Deal!', 'Congrats!  Things seem to be building rapidly now on the Continent.  Mark');
INSERT INTO email([from],[to],subject,body) VALUES('e..carter@enron.com', 't..robinson@enron.com', 'FW: Producers Newsletter 9-24-2001', '
The producer lumber pricing sheet.
 -----Original Message-----
From: 	Johnson, Jay  
Sent:	Tuesday, October 16, 2001 3:42 PM
To:	Carter, Karen E.
Subject:	FW: Producers Newsletter 9-24-2001



 -----Original Message-----
From: 	Daigre, Sergai  
Sent:	Friday, September 21, 2001 8:33 PM
Subject:	Producers Newsletter 9-24-2001

 ');
INSERT INTO email([from],[to],subject,body) VALUES('david.delainey@enron.com', 'kenneth.lay@enron.com', 'Greater Houston Partnership', 'Ken, in response to the letter from Mr Miguel San Juan, my suggestion would 
be to offer up the Falcon for their use; however, given the tight time frame 
and your recent visit with Mr. Fox that it would be difficult for either you 
or me to participate.

I spoke to Max and he agrees with this approach.

I hope this meets with your approval.

Regards
Delainey');
INSERT INTO email([from],[to],subject,body) VALUES('lachandra.fenceroy@enron.com', 'lindy.donoho@enron.com', 'FW: Bus Applications Meeting Follow Up', 'Lindy,

Here is the original memo we discussed earlier.  Please provide any information that you may have.

Your cooperation is greatly appreciated.

Thanks,

lachandra.fenceroy@enron.com
713.853.3884
877.498.3401 Pager

 -----Original Message-----
From: 	Bisbee, Joanne  
Sent:	Wednesday, September 26, 2001 7:50 AM
To:	Fenceroy, LaChandra
Subject:	FW: Bus Applications Meeting Follow Up

Lachandra, Please get with David Duff today and see what this is about.  Who are our TW accounting business users?

 -----Original Message-----
From: 	Koh, Wendy  
Sent:	Tuesday, September 25, 2001 2:41 PM
To:	Bisbee, Joanne
Subject:	Bus Applications Meeting Follow Up

Lisa brought up a TW change effective Nov 1.  It involves eliminating a turnback surcharge.  I have no other information, but you might check with the business folks for any system changes required.

Wendy');
INSERT INTO email([from],[to],subject,body) VALUES('danny.mccarty@enron.com', 'fran.fagan@enron.com', 'RE: worksheets', 'Fran,
    If Julie''s merit needs to be lump sum, just move it over to that column.  Also, send me Eric Gadd''s sheets as well.  Thanks.
Dan

 -----Original Message-----
From: 	Fagan, Fran  
Sent:	Thursday, December 20, 2001 11:10 AM
To:	McCarty, Danny
Subject:	worksheets

As discussed, attached are your sheets for bonus and merit.

Thanks,

Fran Fagan
Sr. HR Rep
713.853.5219


 << File: McCartyMerit.xls >>  << File: mccartyBonusCommercial_UnP.xls >> 

');
INSERT INTO email([from],[to],subject,body) VALUES('bert.meyers@enron.com', 'shift.dl-portland@enron.com', 'OCTOBER SCHEDULE', 'TEAM,

PLEASE SEND ME ANY REQUESTS THAT YOU HAVE FOR OCTOBER.  SO FAR I HAVE THEM FOR LEAF.  I WOULD LIKE TO HAVE IT DONE BY THE 15TH OF THE MONTH.  ANY QUESTIONS PLEASE GIVE ME A CALL.

BERT');
INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'john.arnold@enron.com, bilal.bajwa@enron.com, john.griffith@enron.com,', 'TRV Notification:  (NG - PROPT P/L - 09/27/2001)', 'The report named: NG - PROPT P/L <http://trv.corp.enron.com/linkFromExcel.asp?report_cd=11&report_name=NG+-+PROPT+P/L&category_cd=5&category_name=FINANCIAL&toc_hide=1&sTV1=5&TV1Exp=Y&current_efct_date=09/27/2001>, published as of 09/27/2001 is now available for viewing on the website.');
INSERT INTO email([from],[to],subject,body) VALUES('patrice.mims@enron.com', 'calvin.eakins@enron.com', 'Re: Small business supply assistance', 'Hi Calvin


I spoke with Rickey (boy, is he long-winded!!).  Gave him the name of our 
credit guy, Russell Diamond.

Thank for your help!');
INSERT INTO email([from],[to],subject,body) VALUES('legal <.hall@enron.com>', 'stephanie.panus@enron.com', 'Termination update', 'City of Vernon and Salt River Project terminated their contracts.  I will fax these notices to you.');
INSERT INTO email([from],[to],subject,body) VALUES('d..steffes@enron.com', 'richard.shapiro@enron.com', 'EES / ENA Government Affairs Staffing & Outside Services', 'Rick --

Here is the information on staffing and outside services.  Call if you need anything else.

Jim

 ');
INSERT INTO email([from],[to],subject,body) VALUES('gelliott@industrialinfo.com', 'pcopello@industrialinfo.com', 'ECAAR (Gavin), WSCC (Diablo Canyon), & NPCC (Seabrook)', 'Dear Power Outage Database Customer, 
Attached you will find an excel document. The outages contained within are forced or rescheduled outages. Your daily delivery will still contain these outages. 
In addition to the two excel documents, there is a dbf file that is formatted like your daily deliveries you receive nightly. This will enable you to load the data into your regular database. Any questions please let me know. Thanks. 
Greg Elliott 
IIR, Inc. 
713-783-5147 x 3481 
outages@industrialinfo.com 
THE INFORMATION CONTAINED IN THIS E-MAIL IS LEGALLY PRIVILEGED AND CONFIDENTIAL INFORMATION INTENDED ONLY FOR THE USE OF THE INDIVIDUAL OR ENTITY NAMED ABOVE.  YOU ARE HEREBY NOTIFIED THAT ANY DISSEMINATION, DISTRIBUTION, OR COPY OF THIS E-MAIL TO UNAUTHORIZED ENTITIES IS STRICTLY PROHIBITED. IF YOU HAVE RECEIVED THIS 
E-MAIL IN ERROR, PLEASE DELETE IT.
 - OUTAGE.dbf 
 - 111201R.xls 
 - 111201.xls ');
INSERT INTO email([from],[to],subject,body) VALUES('enron.announcements@enron.com', 'all_ena_egm_eim@enron.com', 'EWS Brown Bag', 'MARK YOUR LUNCH CALENDARS NOW !

You are invited to attend the EWS Brown Bag Lunch Series

Featuring:   RAY BOWEN, COO

Topic:  Enron Industrial Markets

Thursday, March 15, 2001
11:30 am - 12:30 pm
EB 5 C2


You bring your lunch,           Limited Seating
We provide drinks and dessert.          RSVP  x 3-9610');
INSERT INTO email([from],[to],subject,body) VALUES('chris.germany@enron.com', 'ingrid.immer@williams.com', 'Re: About St Pauls', 'Sounds good to me.  I bet this is next to the Warick?? Hotel.




"Immer, Ingrid" <Ingrid.Immer@Williams.com> on 12/21/2000 11:48:47 AM
To: "''chris.germany@enron.com''" <chris.germany@enron.com>
cc:  
Subject: About St Pauls




 <<About St Pauls.url>>  
? 
?http://www.stpaulshouston.org/about.html 

Chris, 

I like the looks of this place.? What do you think about going here Christmas 
eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., 
among others.

Let me know.?? ii 

 - About St Pauls.url

');
INSERT INTO email([from],[to],subject,body) VALUES('nas@cpuc.ca.gov', 'skatz@sempratrading.com, kmccrea@sablaw.com, thompson@wrightlaw.com,', 'Reply Brief filed July 31, 2000', ' - CPUC01-#76371-v1-Revised_Reply_Brief__Due_today_7_31_.doc');
INSERT INTO email([from],[to],subject,body) VALUES('gascontrol@aglresources.com', 'dscott4@enron.com, lcampbel@enron.com', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder
As discussed in the Winter Operations Meeting on Sept.29,2000, 
E-Gas(Emergency Gas) will not be offered this winter as a service from AGLC.  
Marketers and Poolers can receive gas via Peaking and IBSS nominations(daisy 
chain) from other marketers up to the 6 p.m. Same Day 2 nomination cycle.
');
INSERT INTO email([from],[to],subject,body) VALUES('dutch.quigley@enron.com', 'rwolkwitz@powermerchants.com', '', ' 

Here is a goody for you');
INSERT INTO email([from],[to],subject,body) VALUES('ryan.o''rourke@enron.com', 'k..allen@enron.com, randy.bhatia@enron.com, frank.ermis@enron.com,', 'TRV Notification:  (West VaR - 11/07/2001)', 'The report named: West VaR <http://trv.corp.enron.com/linkFromExcel.asp?report_cd=36&report_name=West+VaR&category_cd=2&category_name=WEST&toc_hide=1&sTV1=2&TV1Exp=Y&current_efct_date=11/07/2001>, published as of 11/07/2001 is now available for viewing on the website.');
INSERT INTO email([from],[to],subject,body) VALUES('mjones7@txu.com', 'cstone1@txu.com, ggreen2@txu.com, timpowell@txu.com,', 'Enron / HPL Actuals for July 10, 2000', 'Teco Tap       10.000 / Enron ; 110.000 / HPL IFERC

LS HPL LSK IC       30.000 / Enron
');
INSERT INTO email([from],[to],subject,body) VALUES('susan.pereira@enron.com', 'kkw816@aol.com', 'soccer practice', 'Kathy-

Is it safe to assume that practice is cancelled for tonight??

Susan Pereira');
INSERT INTO email([from],[to],subject,body) VALUES('mark.whitt@enron.com', 'barry.tycholiz@enron.com', 'Huber Internal Memo', 'Please look at this.  I didn''t know how deep to go with the desk.  Do you think this works.

 ');
INSERT INTO email([from],[to],subject,body) VALUES('m..forney@enron.com', 'george.phillips@enron.com', '', 'George,
Give me a call and we will further discuss opportunities on the 13st floor.

Thanks,
JMForney
3-7160');
INSERT INTO email([from],[to],subject,body) VALUES('brad.mckay@enron.com', 'angusmcka@aol.com', 'Re: (no subject)', 'not yet');
INSERT INTO email([from],[to],subject,body) VALUES('adam.bayer@enron.com', 'jonathan.mckay@enron.com', 'FW: Curve Fetch File', 'Here is the curve fetch file sent to me.  It has plenty of points in it.  If you give me a list of which ones you need we may be able to construct a secondary worksheet to vlookup the values.

adam
35227


 -----Original Message-----
From: 	Royed, Jeff  
Sent:	Tuesday, September 25, 2001 11:37 AM
To:	Bayer, Adam
Subject:	Curve Fetch File

Let me know if it works.   It may be required to have a certain version of Oracle for it to work properly.

 

Jeff Royed
Enron 
Energy Operations
Phone: 713-853-5295');
INSERT INTO email([from],[to],subject,body) VALUES('matt.smith@enron.com', 'yan.wang@enron.com', 'Report Formats', 'Yan,

The merged reports look great.  I believe the only orientation changes are to 
"unmerge" the following six reports:  

31 Keystone Receipts
15 Questar Pipeline
40 Rockies Production
22 West_2
23 West_3
25 CIG_WIC

The orientation of the individual reports should be correct.  Thanks.

Mat

PS.  Just a reminder to add the "*" by the title of calculated points.');
INSERT INTO email([from],[to],subject,body) VALUES('michelle.lokay@enron.com', 'jimboman@bigfoot.com', 'Egyptian Festival', '---------------------- Forwarded by Michelle Lokay/ET&S/Enron on 09/07/2000 
10:08 AM ---------------------------


"Karkour, Randa" <Randa.Karkour@COMPAQ.com> on 09/07/2000 09:01:04 AM
To: "''Agheb (E-mail)" <Agheb@aol.com>, "Leila Mankarious (E-mail)" 
<Leila_Mankarious@mhhs.org>, "''Marymankarious (E-mail)" 
<marymankarious@aol.com>, "Michelle lokay (E-mail)" <mlokay@enron.com>, "Ramy 
Mankarious (E-mail)" <Mankarious@aol.com>
cc:  

Subject: Egyptian Festival


 <<Egyptian Festival.url>>

 http://www.egyptianfestival.com/

 - Egyptian Festival.url
');
INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'sherry.dawson@enron.com', 'Urgent!!! --- New EAST books', 'This has to be done..................................

Thanks
---------------------- Forwarded by Errol McLaughlin/Corp/Enron on 12/20/2000 
08:39 AM ---------------------------
   
	
	
	From:  William Kelly @ ECT                           12/20/2000 08:31 AM
	

To: Kam Keiser/HOU/ECT@ECT, Darron C Giron/HOU/ECT@ECT, David 
Baumbach/HOU/ECT@ECT, Errol McLaughlin/Corp/Enron@ENRON
cc: Kimat Singla/HOU/ECT@ECT, Kulvinder Fowler/NA/Enron@ENRON, Kyle R 
Lilly/HOU/ECT@ECT, Jeff Royed/Corp/Enron@ENRON, Alejandra 
Chavez/NA/Enron@ENRON, Crystal Hyde/HOU/ECT@ECT 

Subject: New EAST books

We have new book names in TAGG for our intramonth portfolios and it is 
extremely important that any deal booked to the East is communicated quickly 
to someone on my team.  I know it will take some time for the new names to 
sink in and I do not want us to miss any positions or P&L.  

Thanks for your help on this.

New:
Scott Neal :         East Northeast
Dick Jenkins:     East Marketeast

WK 
');
INSERT INTO email([from],[to],subject,body) VALUES('david.forster@enron.com', 'eol.wide@enron.com', 'Change to Stack Manager', 'Effective immediately, there is a change to the Stack Manager which will 
affect any Inactive Child.

An inactive Child with links to Parent products will not have their 
calculated prices updated until the Child product is Activated.

When the Child Product is activated, the price will be recalculated and 
updated BEFORE it is displayed on the web.

This means that if you are inputting a basis price on a Child product, you 
will not see the final, calculated price until you Activate the product, at 
which time the customer will also see it.

If you have any questions, please contact the Help Desk on:

Americas: 713 853 4357
Europe: + 44 (0) 20 7783 7783
Asia/Australia: +61 2 9229 2300

Dave');
INSERT INTO email([from],[to],subject,body) VALUES('vince.kaminski@enron.com', 'jhh1@email.msn.com', 'Re: Light reading - see pieces beginning on page 7', 'John,

I saw it. Very interesting.

Vince





"John H Herbert" <jhh1@email.msn.com> on 07/28/2000 08:38:08 AM
To: "Vince J Kaminski" <Vince_J_Kaminski@enron.com>
cc:  
Subject: Light reading - see pieces beginning on page 7


Cheers and have a nice weekend,


JHHerbert




 - gd000728.pdf



');
INSERT INTO email([from],[to],subject,body) VALUES('matthew.lenhart@enron.com', 'mmmarcantel@equiva.com', 'RE:', 'i will try to line up a pig for you ');
INSERT INTO email([from],[to],subject,body) VALUES('jae.black@enron.com', 'claudette.harvey@enron.com, chaun.roberts@enron.com, judy.martinez@enron.com,', 'Disaster Recovery Equipment', 'As a reminder...there are several pieces of equipment that are set up on the 30th Floor, as well as on our floor, for the Disaster Recovery Team.  PLEASE DO NOT TAKE, BORROW OR USE this equipment.  Should you need to use another computer system, other than yours, or make conference calls please work with your Assistant to help find or set up equipment for you to use.

Thanks for your understanding in this matter.

T.Jae Black
East Power Trading
Assistant to Kevin Presto
off. 713-853-5800
fax 713-646-8272
cell 713-539-4760');
INSERT INTO email([from],[to],subject,body) VALUES('eric.bass@enron.com', 'dale.neuner@enron.com', '5 X 24', 'Dale,

Have you heard anything more on the 5 X 24s?  We would like to get this 
product out ASAP.


Thanks,

Eric');
INSERT INTO email([from],[to],subject,body) VALUES('messenger@smartreminders.com', 'm..tholt@enron.com', '10% Coupon - PrintPal Printer Cartridges - 100% Guaranteed', '[IMAGE]
[IMAGE][IMAGE][IMAGE] 
Dear  SmartReminders Member,
       [IMAGE]         [IMAGE]        [IMAGE]     [IMAGE]    [IMAGE]    [IMAGE]        [IMAGE]      [IMAGE]     	


  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

We respect  your privacy and are a Certified Participant of the BBBOnLine
 Privacy Program.  To be removed from future offers,click  here. 
SmartReminders.com  is a permission based service. To unsubscribe click  here .  ');
INSERT INTO email([from],[to],subject,body) VALUES('benjamin.rogers@enron.com', 'mark.bernstein@enron.com', '', 'The guy you are talking about left CIN under a "cloud of suspicion" sort of 
speak.  He was the one who got into several bad deals and PPA''s in California 
for CIN, thus he left on a bad note.  Let me know if you need more detail 
than that, I felt this was the type of info you were looking for.  Thanks!
Ben');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'michelle.cash@enron.com', 'Expense Report Receipts Not Received', 'Employee Name: Michelle Cash
Report Name:   Houston Cellular 8-11-01
Report Date:   12/13/01
Report ID:     594D37C9ED2111D5B452
Submitted On:  12/13/01

You are only allowed 2 reports with receipts outstanding.  Your expense reports will not be paid until you meet this requirement.');
INSERT INTO email([from],[to],subject,body) VALUES('susan.mara@enron.com', 'ray.alvarez@enron.com, mark.palmer@enron.com, karen.denne@enron.com,', 'CAISO Emergency Motion -- to discontinue market-based rates for', 'FYI.  the latest broadside against the generators.

Sue Mara
Enron Corp.
Tel: (415) 782-7802
Fax:(415) 782-7854
----- Forwarded by Susan J Mara/NA/Enron on 06/08/2001 12:24 PM -----


	"Milner, Marcie" <MMilner@coral-energy.com> 06/08/2001 11:13 AM 	   To: "''smara@enron.com''" <smara@enron.com>  cc:   Subject: CAISO Emergency Motion	


Sue, did you see this emergency motion the CAISO filed today?  Apparently
they are requesting that FERC discontinue market-based rates immediately and
grant refunds plus interest on the difference between cost-based rates and
market revenues received back to May 2000.  They are requesting the
commission act within 14 days.  Have you heard anything about what they are
doing?

Marcie

http://www.caiso.com/docs/2001/06/08/200106081005526469.pdf 
');
INSERT INTO email([from],[to],subject,body) VALUES('fletcher.sturm@enron.com', 'eloy.escobar@enron.com', 'Re: General Brinks Position Meeting', 'Eloy,

Who is General Brinks?

Fletch');
INSERT INTO email([from],[to],subject,body) VALUES('nailia.dindarova@enron.com', 'richard.shapiro@enron.com', 'Documents for Mark Frevert (on EU developments and lessons from', 'Rick,

Here are the documents that Peter has prepared for Mark Frevert. 

Nailia
---------------------- Forwarded by Nailia Dindarova/LON/ECT on 25/06/2001 
16:36 ---------------------------


Nailia Dindarova
25/06/2001 15:36
To: Michael Brown/Enron@EUEnronXGate
cc: Ross Sankey/Enron@EUEnronXGate, Eric Shaw/ENRON@EUEnronXGate, Peter 
Styles/LON/ECT@ECT 

Subject: Documents for Mark Frevert (on EU developments and lessons from 
California)

Michael,


These are the documents that Peter promised to give to you for Mark Frevert. 
He has now handed them to him in person but asked me to transmit them 
electronically to you, as well as Eric and Ross.

Nailia





');
INSERT INTO email([from],[to],subject,body) VALUES('peggy.a.kostial@accenture.com', 'dave.samuels@enron.com', 'EOL-Accenture Deal Sheet', 'Dave -

Attached are our comments and suggested changes. Please call to review.

On the time line for completion, we have four critical steps to complete:
     Finalize market analysis to refine business case, specifically
     projected revenue stream
     Complete counterparty surveying, including targeting 3 CPs for letters
     of intent
     Review Enron asset base for potential reuse/ licensing
     Contract negotiations

Joe will come back to us with an updated time line, but it is my
expectation that we are still on the same schedule (we just begun week
three) with possibly a week or so slippage.....contract negotiations will
probably be the critical path.

We will send our cut at the actual time line here shortly. Thanks,

Peggy

(See attached file: accenture-dealpoints v2.doc)
 - accenture-dealpoints v2.doc ');
INSERT INTO email([from],[to],subject,body) VALUES('thomas.martin@enron.com', 'thomas.martin@enron.com', 'Re: Guadalupe Power Partners LP', '---------------------- Forwarded by Thomas A Martin/HOU/ECT on 03/20/2001 
03:49 PM ---------------------------


Thomas A Martin
10/11/2000 03:55 PM
To: Patrick Wade/HOU/ECT@ECT
cc:  
Subject: Re: Guadalupe Power Partners LP  

The deal is physically served at Oasis Waha or Oasis Katy and is priced at 
either HSC, Waha or Katytailgate GD at buyers option three days prior to 
NYMEX  close.

');
INSERT INTO email([from],[to],subject,body) VALUES('judy.townsend@enron.com', 'dan.junek@enron.com, chris.germany@enron.com', 'Columbia Distribution''s Capacity Available for Release - Sum', '---------------------- Forwarded by Judy Townsend/HOU/ECT on 03/09/2001 11:04 
AM ---------------------------


agoddard@nisource.com on 03/08/2001 09:16:57 AM
To: "        -         *Koch, Kent" <kkoch@nisource.com>, "        -         
*Millar, Debra" <dmillar@nisource.com>, "        -         *Burke, Lynn" 
<lburke@nisource.com>
cc: "        -         *Heckathorn, Tom" <theckathorn@nisource.com> 
Subject: Columbia Distribution''s Capacity Available for Release - Sum


Attached is Columbia Distribution''s notice of capacity available for release
for
the summer of 2001 (Apr. 2001 through Oct. 2001).

Please note that the deadline for bids is 3:00pm EST on March 20, 2001.

If you have any questions, feel free to contact any of the representatives
listed
at the bottom of the attachment.

Aaron Goddard




 - 2001Summer.doc
');
INSERT INTO email([from],[to],subject,body) VALUES('rhonda.denton@enron.com', 'tim.belden@enron.com, dana.davis@enron.com, genia.fitzgerald@enron.com,', 'Split Rock Energy LLC', 'We have received the executed EEI contract from this CP dated 12/12/2000.  
Copies will be distributed to Legal and Credit.');
INSERT INTO email([from],[to],subject,body) VALUES('kerrymcelroy@dwt.com', 'jack.speer@alcoa.com, crow@millernash.com, michaelearly@earthlink.net,', 'Oral Argument Request', ' - Oral Argument Request.doc');
INSERT INTO email([from],[to],subject,body) VALUES('mike.carson@enron.com', 'rlmichaelis@hormel.com', '', 'Did you come in town this wk end..... My new number at our house is : 
713-668-3712...... my cell # is 281-381-7332

the kid');
INSERT INTO email([from],[to],subject,body) VALUES('cooper.richey@enron.com', 'trycooper@hotmail.com', 'FW: Contact Info', '

-----Original Message-----
From: Punja, Karim 
Sent: Thursday, December 13, 2001 2:35 PM
To: Richey, Cooper
Subject: Contact Info


Cooper,

Its been a real pleasure working with you (even though it was for only a small amount of time)
I hope we can stay in touch.

Home# 234-0249
email: kpunja@hotmail.com

Take Care, 

Karim.
  ');
INSERT INTO email([from],[to],subject,body) VALUES('bjm30@earthlink.net', 'mcguinn.k@enron.com, mcguinn.ian@enron.com, mcguinn.stephen@enron.com,', 'email address change', 'Hello all.

I haven''t talked to many of you via email recently but I do want to give you
my new address for your email file:

    bjm30@earthlink.net

I hope all is well.

Brian McGuinn');
INSERT INTO email([from],[to],subject,body) VALUES('shelley.corman@enron.com', 'steve.hotte@enron.com', 'Flat Panels', 'Can you please advise what is going on with the flat panels that we had planned to distribute to our gas logistics team.  It was in the budget and we had the okay, but now I''m hearing there is some hold-up & the units are stored on 44.

Shelley');
INSERT INTO email([from],[to],subject,body) VALUES('sara.davidson@enron.com', 'john.schwartzenburg@enron.com, scott.dieball@enron.com, recipients@enron.com,', '2001 Enron Law Conference (Distribution List 2)', '    Enron Law Conference

San Antonio, Texas    May 2-4, 2001    Westin Riverwalk

                   See attached memo for more details!!


? Registration for the law conference this year will be handled through an 
Online RSVP Form on the Enron Law Conference Website at 
http://lawconference.corp.enron.com.  The website is still under construction 
and will not be available until Thursday, March 15, 2001.  

? We will send you another e-mail to confirm when the Law Conference Website 
is operational. 

? Please complete the Online RSVP Form as soon as it is available  and submit 
it no later than Friday, March 30th.  




');
INSERT INTO email([from],[to],subject,body) VALUES('tori.kuykendall@enron.com', 'heath.b.taylor@accenture.com', 'Re:', 'hey - thats funny about john - he definitely remembers him - i''ll call pat 
and let him know - we are coming on saturday - i just havent had a chance to 
call you guys back --  looking forward to it -- i probably need the 
directions again though');
INSERT INTO email([from],[to],subject,body) VALUES('darron.giron@enron.com', 'bryce.baxter@enron.com', 'Re: Feedback for Audrey Cook', 'Bryce,

I''ll get it done today.  

DG    3-9573


   
	
	
	From:  Bryce Baxter                           06/12/2000 07:15 PM
	

To: Darron C Giron/HOU/ECT@ECT
cc:  
Subject: Feedback for Audrey Cook

You were identified as a reviewer for Audrey Cook.  If possible, could you 
complete her feedback by end of business Wednesday?  It will really help me 
in the PRC process to have your input.  Thanks.

');
INSERT INTO email([from],[to],subject,body) VALUES('casey.evans@enron.com', 'stephanie.sever@enron.com', 'Gas EOL ID', 'Stephanie,

In conjunction with the recent movement of several power traders, they are changing the names of their gas books as well.  The names of the new gas books and traders are as follows:

PWR-NG-LT-SPP:  Mike Carson
PWR-NG-LT-SERC:  Jeff King

If you need to know their power desk to map their ID to their gas books, those desks are as follows:

EPMI-LT-SPP:  Mike Carson
EPMI-LT-SERC:  Jeff King

I will be in training this afternoon, but will be back when class is over.  Let me know if you have any questions.

Thanks for your help!
Casey');
INSERT INTO email([from],[to],subject,body) VALUES('darrell.schoolcraft@enron.com', 'david.roensch@enron.com, kimberly.watson@enron.com, michelle.lokay@enron.com,', 'Postings', 'Please see the attached.


ds


  

 ');
INSERT INTO email([from],[to],subject,body) VALUES('mcominsky@aol.com', 'cpatman@bracepatt.com, james_derrick@enron.com', 'Jurisprudence Luncheon', 'Carrin & Jim --

It was an honor and a pleasure to meet both of you yesterday.  I know we will
have fun working together on this very special event.

Jeff left the jurisprudence luncheon lists for me before he left on vacation.
 I wasn''t sure whether he transmitted them to you as well.  Would you please
advise me if you would like them sent to you?  I can email the MS Excel files
or I can fax the hard copies to you.   Please advise what is most convenient.

I plan to be in town through the holidays and can be reached by phone, email,
or cell phone at any time.  My cell phone number is 713/705-4829.

Thanks again for your interest in the ADL''s work.  Martin.

Martin B. Cominsky
Director, Southwest Region
Anti-Defamation League
713/627-3490, ext. 122
713/627-2011 (fax)
MCominsky@aol.com');
INSERT INTO email([from],[to],subject,body) VALUES('phillip.love@enron.com', 'todagost@utmb.edu, gbsonnta@utmb.edu', 'New President', 'I had a little bird put a word in my ear.  Is there any possibility for Ben 
Raimer to be Bush''s secretary of HHS?  Just curious about that infamous UTMB 
rumor mill.  Hope things are well, happy holidays.
PL');
INSERT INTO email([from],[to],subject,body) VALUES('marie.heard@enron.com', 'ehamilton@fna.com', 'ISDA Master Agreement', 'Erin:

Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together with Paragraph 13 to the ISDA Credit Support Annex.  Please let me know if you need anything else.  We look forward to hearing your comments.

Marie

Marie Heard
Senior Legal Specialist
Enron North America Corp.
Phone:  (713) 853-3907
Fax:  (713) 646-3490
marie.heard@enron.com

				 ');
INSERT INTO email([from],[to],subject,body) VALUES('andrea.ring@enron.com', 'beverly.beaty@enron.com', 'Re: Tennessee Buy - Louis Dreyfus', 'Beverly -  once again thanks so much for your help on this.

           

                                                                     ');
INSERT INTO email([from],[to],subject,body) VALUES('karolyn.criado@enron.com', 'j..bonin@enron.com, felicia.case@enron.com, b..clapp@enron.com,', 'Price List week of Oct. 8-9, 2001', '
Please contact me if you have any questions regarding last weeks prices.

Thank you,
Karolyn Criado
3-9441


 

');
INSERT INTO email([from],[to],subject,body) VALUES('kevin.presto@enron.com', 'edward.baughman@enron.com, billy.braddock@enron.com', 'Associated', 'Please begin working on filling our Associated short position in 02.   I would like to take this risk off the books.

In addition, please find out what a buy-out of VEPCO would cost us.   With Rogers transitioning to run our retail risk management, I would like to clean up our customer positions.

We also need to continue to explore a JEA buy-out.

Thanks.');
INSERT INTO email([from],[to],subject,body) VALUES('stacy.dickson@enron.com', 'gregg.penman@enron.com', 'RE: Constellation TC 5-7-01', 'Gregg, 

I am at home with a sick baby.  (Lots of fun!)  I will call you about this 
tomorrow.

Stacy');
INSERT INTO email([from],[to],subject,body) VALUES('joe.quenet@enron.com', 'dfincher@utilicorp.com', '', 'hey big guy.....check this out.....

 w ww.gorelieberman-2000.com/');
INSERT INTO email([from],[to],subject,body) VALUES('k..allen@enron.com', 'jacqestc@aol.com', '', 'Jacques,

I sent you a fax of Kevin Kolb''s comments on the release.  The payoff on the note would be $36,248 ($36090(principal) + $158 (accrued interest)).
This is assuming we wrap this up on Tuesday.  

Please email to confirm that their changes are ok so I can set up a meeting on Tuesday to reach closure.

Phillip');
INSERT INTO email([from],[to],subject,body) VALUES('kourtney.nelson@enron.com', 'mike.swerzbin@enron.com', 'Adjusted L/R Balance', 'Mike,

I placed the adjusted L/R Balance on the Enronwest site.  It is under the "Staff/Kourtney Nelson".  There are two links:  

1)  "Adj L_R" is the same data/format from the weekly strategy meeting. 
2)  "New Gen 2001_2002" link has all of the supply side info that is used to calculate the L/R balance
	-Please note the Data Flag column, a value of "3" indicates the project was cancelled, on hold, etc and is not included in the calc.  

Both of these sheets are interactive Excel spreadsheets and thus you can play around with the data as you please.  Also, James Bruce is working to get his gen report on the web.  That will help with your access to information on new gen.

Please let me know if you have any questions or feedback,

Kourtney



Kourtney Nelson
Fundamental Analysis 
Enron North America
(503) 464-8280
kourtney.nelson@enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('d..thomas@enron.com', 'naveed.ahmed@enron.com', 'FW: Current Enron TCC Portfolio', '

-----Original Message-----
From: Grace, Rebecca M. 
Sent: Monday, December 17, 2001 9:44 AM
To: Thomas, Paul D.
Cc: Cashion, Jim; Allen, Thresa A.; May, Tom
Subject: RE: Current Enron TCC Portfolio


Paul,

I reviewed NY''s list.  I agree with all of their contracts numbers and mw amounts.

Call if you have any more questions.

Rebecca



 -----Original Message-----
From: 	Thomas, Paul D.  
Sent:	Monday, December 17, 2001 9:08 AM
To:	Grace, Rebecca M.
Subject:	FW: Current Enron TCC Portfolio

 << File: enrontccs.xls >> 
Rebecca,
Let me know if you see any differences.

Paul
X 3-0403
-----Original Message-----
From: Thomas, Paul D. 
Sent: Monday, December 17, 2001 9:04 AM
To: Ahmed, Naveed
Subject: FW: Current Enron TCC Portfolio




-----Original Message-----
From: Thomas, Paul D. 
Sent: Thursday, December 13, 2001 10:01 AM
To: Baughman, Edward D.
Subject: Current Enron TCC Portfolio


');
INSERT INTO email([from],[to],subject,body) VALUES('stephanie.panus@enron.com', 'william.bradford@enron.com, debbie.brackett@enron.com,', 'Coastal Merchant Energy/El Paso Merchant Energy', 'Coastal Merchant Energy, L.P. merged with and into El Paso Merchant Energy, 
L.P., effective February 1, 2001, with the surviving entity being El Paso 
Merchant Energy, L.P.  We currently have ISDA Master Agreements with both 
counterparties.  Please see the attached memo regarding the existing Masters 
and let us know which agreement should be terminated.

Thanks,
Stephanie
');
INSERT INTO email([from],[to],subject,body) VALUES('kam.keiser@enron.com', 'c..kenne@enron.com', 'RE: What about this too???', ' 

 -----Original Message-----
From: 	Kenne, Dawn C.  
Sent:	Wednesday, February 06, 2002 11:50 AM
To:	Keiser, Kam
Subject:	What about this too???


 << File: Netco Trader Matrix.xls >> 
 ');
INSERT INTO email([from],[to],subject,body) VALUES('chris.meyer@enron.com', 'joe.parks@enron.com', 'Centana', 'Talked to Chip.  We do need Cash Committe approval given the netting feature of your deal, which means Batch Funding Request.  Please update per my previous e-mail and forward.

Thanks

chris
x31666');
INSERT INTO email([from],[to],subject,body) VALUES('debra.perlingiere@enron.com', 'jworman@academyofhealth.com', '', 'Have a great weekend!   Happy Fathers Day!


Debra Perlingiere
Enron North America Corp.
1400 Smith Street, EB 3885
Houston, Texas 77002
dperlin@enron.com
Phone 713-853-7658
Fax  713-646-3490');
INSERT INTO email([from],[to],subject,body) VALUES('outlook.team@enron.com', '', 'Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia  &', 'CALENDAR ENTRY:	APPOINTMENT

Description:
	Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia  & Dir Rpts. - 4102

Date:		1/5/2001
Time:		9:00 AM - 10:00 AM (Central Standard Time)

Chairperson:	Outlook Migration Team

Detailed Description:');
INSERT INTO email([from],[to],subject,body) VALUES('diana.seifert@enron.com', 'mark.taylor@enron.com', 'Guest access Chile', 'Hello Mark,

Justin Boyd told me that your can help me with questions regarding Chile.
We got a request for guest access through MG.
The company is called Escondida and is a subsidiary of BHP Australia.

Please advise if I can set up a guest account or not.
F.Y.I.: MG is planning to put a "in w/h Chile" contract for Copper on-line as 
soon as Enron has done the due diligence for this country.
Thanks !


Best regards

Diana Seifert
EOL PCG');
INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'mark.whitt@enron.com', '<<Concur Expense Document>> - 121001', 'The Approval status has changed on the following report:

Status last changed by: Barry L. Tycholiz
Expense Report Name: 121001
Report Total: $198.98
Amount Due Employee: $198.98
Amount Approved: $198.98
Amount Paid: $0.00
Approval Status: Approved
Payment Status: Pending


To review this expense report, click on the following link for Concur Expense.
http://expensexms.enron.com');
INSERT INTO email([from],[to],subject,body) VALUES('kevin.hyatt@enron.com', '', 'Technical Support', 'Outside the U.S., please refer to the list below:

Australia:
1800 678-515
support@palm-au.com

Canada:
1905 305-6530
support@palm.com

New Zealand:
0800 446-398
support@palm-nz.com

U.K.:
0171 867 0108
eurosupport@palm.3com.com

Please refer to the Worldwide Customer Support card for a complete technical support contact list.');
INSERT INTO email([from],[to],subject,body) VALUES('geoff.storey@enron.com', 'dutch.quigley@enron.com', 'RE:', 'duke contact?

 -----Original Message-----
From: 	Quigley, Dutch  
Sent:	Wednesday, October 31, 2001 10:14 AM
To:	Storey, Geoff
Subject:	RE: 

bp corp	Albert LaMore	281-366-4962

running the reports now


 -----Original Message-----
From: 	Storey, Geoff  
Sent:	Wednesday, October 31, 2001 10:10 AM
To:	Quigley, Dutch
Subject:	RE: 

give me a contact over there too
BP


 -----Original Message-----
From: 	Quigley, Dutch  
Sent:	Wednesday, October 31, 2001 9:42 AM
To:	Storey, Geoff
Subject:	

Coral	Jeff Whitnah	713-767-5374
Relaint	Steve McGinn	713-207-4000');
INSERT INTO email([from],[to],subject,body) VALUES('pete.davis@enron.com', 'pete.davis@enron.com', 'Start Date: 4/22/01; HourAhead hour: 3;  <CODESITE>', 'Start Date: 4/22/01; HourAhead hour: 3;  No ancillary schedules awarded.  
Variances detected.
Variances detected in Load schedule.

    LOG MESSAGES:

PARSING FILE -->> O:\Portland\WestDesk\California Scheduling\ISO Final 
Schedules\2001042203.txt

---- Load Schedule ----
$$$ Variance found in table tblLoads.
     Details: (Hour: 3 / Preferred:   1.92 / Final:   1.89)
  TRANS_TYPE: FINAL
  LOAD_ID: PGE4
  MKT_TYPE: 2
  TRANS_DATE: 4/22/01
  SC_ID: EPMI

');
INSERT INTO email([from],[to],subject,body) VALUES('john.postlethwaite@enron.com', 'john.zufferli@enron.com', 'Reference', 'John, hope things are going well up there for you. The big day is almost here for you and Jessica. I was wondering if I could use your name as a job reference if need be. I am just trying to get everything in order just in case something happens. 

John');
INSERT INTO email([from],[to],subject,body) VALUES('jeffrey.shankman@enron.com', 'lschiffm@jonesday.com', 'Re:', 'I saw you called on the cell this a.m.  Sorry I missed you.  (I was in the 
shower).  I have had a shitty week--I suspect my silence (not only to you, 
but others) after our phone call is a result of the week.  I''m seeing Glen at 
11:15....talk to you');
INSERT INTO email([from],[to],subject,body) VALUES('litebytz@enron.com', '', 'Lite Bytz RSVP', '
This week''s Lite Bytz presentation will feature the following TOOLZ speaker:

Richard McDougall
Solaris 8
Thursday, June 7, 2001

If you have not already signed up, please RSVP via email to litebytz@enron.com by the end of the day Tuesday, June 5, 2001.

*Remember: this is now a Brown Bag Event--so bring your lunch and we will provide cookies and drinks.

Click below for more details.

http://home.enron.com:84/messaging/litebytztoolzprint.jpg');
    COMMIT;
  }
} {}

###############################################################################
# Everything above just builds an interesting test database.  The actual
# tests come after this comment.
###############################################################################

do_test fts3ac-1.2 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark'
  }
} {6 17 25 38 40 42 73 74}
do_test fts3ac-1.3 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'susan'
  }
} {24 40}
do_test fts3ac-1.4 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark susan'
  }
} {40}
do_test fts3ac-1.5 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'susan mark'
  }
} {40}
do_test fts3ac-1.6 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH '"mark susan"'
  }
} {}
do_test fts3ac-1.7 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark -susan'
  }
} {6 17 25 38 42 73 74}
do_test fts3ac-1.8 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH '-mark susan'
  }
} {24}
do_test fts3ac-1.9 {
  execsql {
    SELECT rowid FROM email WHERE email MATCH 'mark OR susan'
  }
} {6 17 24 25 38 40 42 73 74}

# Some simple tests of the automatic "offsets(email)" column.  In the sample
# data set above, only one message, number 20, contains the words
# "gas" and "reminder" in both body and subject.
#
do_test fts3ac-2.1 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}
do_test fts3ac-2.2 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'subject:gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8 3 1 54 8}}
do_test fts3ac-2.3 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE email MATCH 'body:gas reminder'
  }
} {20 {2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}
do_test fts3ac-2.4 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE subject MATCH 'gas reminder'
  }
} {20 {2 0 42 3 2 1 54 8}}
do_test fts3ac-2.5 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH 'gas reminder'
  }
} {20 {3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}}

# Document 32 contains 5 instances of the world "child".  But only
# 3 of them are paired with "product".  Make sure only those instances
# that match the phrase appear in the offsets(email) list.
#
do_test fts3ac-3.1 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH 'child product' AND +rowid=32
  }
} {32 {3 0 94 5 3 0 114 5 3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7 3 1 493 7}}
do_test fts3ac-3.2 {
  execsql {
    SELECT rowid, offsets(email) FROM email
     WHERE body MATCH '"child product"'
  }
} {32 {3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7}}

# Snippet generator tests
#
do_test fts3ac-4.1 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'subject:gas reminder'
  }
} {{Alert Posted 10:00 AM November 20,2000: E-<b>GAS</b> Request <b>Reminder</b>}}
do_test fts3ac-4.2 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'christmas candlelight'
  }
} {{<b>...</b> place.? What do you think about going here <b>Christmas</b> 
eve?? They have an 11:00 a.m. service and a <b>candlelight</b> service at 5:00 p.m., 
among others. <b>...</b>}}

do_test fts3ac-4.3 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'deal sheet potential reuse'
  }
} {{EOL-Accenture <b>Deal</b> <b>Sheet</b> <b>...</b> intent
     Review Enron asset base for <b>potential</b> <b>reuse</b>/ licensing
     Contract negotiations <b>...</b>}}
do_test fts3ac-4.4 {
  execsql {
    SELECT snippet(email,'<<<','>>>',' ') FROM email
     WHERE email MATCH 'deal sheet potential reuse'
  }
} {{EOL-Accenture <<<Deal>>> <<<Sheet>>>  intent
     Review Enron asset base for <<<potential>>> <<<reuse>>>/ licensing
     Contract negotiations  }}
do_test fts3ac-4.5 {
  execsql {
    SELECT snippet(email,'<<<','>>>',' ') FROM email
     WHERE email MATCH 'first things'
  }
} {{Re: <<<First>>> Polish Deal!  Congrats!  <<<Things>>> seem to be building rapidly now on the  }}
do_test fts3ac-4.6 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'chris is here'
  }
} {{<b>chris</b>.germany@enron.com <b>...</b> Sounds good to me.  I bet this <b>is</b> next to the Warick?? Hotel. <b>...</b> place.? What do you think about going <b>here</b> Christmas 
eve?? They have an 11:00 a.m. <b>...</b>}}
do_test fts3ac-4.7 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH '"pursuant to"'
  }
} {{Erin:

<b>Pursuant</b> <b>to</b> your request, attached are the Schedule to <b>...</b>}}
do_test fts3ac-4.8 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'ancillary load davis'
  }
} {{pete.<b>davis</b>@enron.com <b>...</b> Start Date: 4/22/01; HourAhead hour: 3;  No <b>ancillary</b> schedules awarded.  
Variances detected.
Variances detected in <b>Load</b> schedule.

    LOG MESSAGES:

PARSING <b>...</b>}}

# Combinations of AND and OR operators:
#
do_test fts3ac-5.1 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'questar enron OR com'
  }
} {{matt.smith@<b>enron</b>.<b>com</b> <b>...</b> six reports:  

31 Keystone Receipts
15 <b>Questar</b> Pipeline
40 Rockies Production
22 West_2 <b>...</b>}}
do_test fts3ac-5.2 {
  execsql {
    SELECT snippet(email) FROM email
     WHERE email MATCH 'enron OR com questar'
  }
} {{matt.smith@<b>enron</b>.<b>com</b> <b>...</b> six reports:  

31 Keystone Receipts
15 <b>Questar</b> Pipeline
40 Rockies Production
22 West_2 <b>...</b>}}

finish_test

Added test/fts3ad.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2006 October 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module, and in particular
# the Porter stemmer.
#
# $Id: fts3ad.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

do_test fts3ad-1.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize porter);
    INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping');
    SELECT rowid FROM t1 WHERE content MATCH 'run jump';
  }
} {1}
do_test fts3ad-1.2 {
  execsql {
    SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'run jump';
  }
} {{<b>running</b> and <b>jumping</b>}}
do_test fts3ad-1.3 {
  execsql {
    INSERT INTO t1(rowid, content) 
          VALUES(2, 'abcdefghijklmnopqrstuvwyxz');
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz'
  }
} {2 <b>abcdefghijklmnopqrstuvwyxz</b>}
do_test fts3ad-1.4 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijXXXXqrstuvwyxz'
  }
} {2 <b>abcdefghijklmnopqrstuvwyxz</b>}
do_test fts3ad-1.5 {
  execsql {
    INSERT INTO t1(rowid, content) 
          VALUES(3, 'The value is 123456789');
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123789'
  }
} {3 {The value is <b>123456789</b>}}
do_test fts3ad-1.6 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123000000789'
  }
} {3 {The value is <b>123456789</b>}}


finish_test

Added test/fts3ae.test.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing deletions in the FTS3 module.
#
# $Id: fts3ae.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Construct a full-text search table containing keywords which are the
# ordinal numbers of the bit positions set for a sequence of integers,
# which are used for the rowid.  There are a total of 30 INSERT and
# DELETE statements, so that we'll test both the segmentMerge() merge
# (over the first 16) and the termSelect() merge (over the level-1
# segment and 14 level-0 segments).
db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'one');
  INSERT INTO t1 (rowid, content) VALUES(2, 'two');
  INSERT INTO t1 (rowid, content) VALUES(3, 'one two');
  INSERT INTO t1 (rowid, content) VALUES(4, 'three');
  DELETE FROM t1 WHERE rowid = 1;
  INSERT INTO t1 (rowid, content) VALUES(5, 'one three');
  INSERT INTO t1 (rowid, content) VALUES(6, 'two three');
  INSERT INTO t1 (rowid, content) VALUES(7, 'one two three');
  DELETE FROM t1 WHERE rowid = 4;
  INSERT INTO t1 (rowid, content) VALUES(8, 'four');
  INSERT INTO t1 (rowid, content) VALUES(9, 'one four');
  INSERT INTO t1 (rowid, content) VALUES(10, 'two four');
  DELETE FROM t1 WHERE rowid = 7;
  INSERT INTO t1 (rowid, content) VALUES(11, 'one two four');
  INSERT INTO t1 (rowid, content) VALUES(12, 'three four');
  INSERT INTO t1 (rowid, content) VALUES(13, 'one three four');
  DELETE FROM t1 WHERE rowid = 10;
  INSERT INTO t1 (rowid, content) VALUES(14, 'two three four');
  INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four');
  INSERT INTO t1 (rowid, content) VALUES(16, 'five');
  DELETE FROM t1 WHERE rowid = 13;
  INSERT INTO t1 (rowid, content) VALUES(17, 'one five');
  INSERT INTO t1 (rowid, content) VALUES(18, 'two five');
  INSERT INTO t1 (rowid, content) VALUES(19, 'one two five');
  DELETE FROM t1 WHERE rowid = 16;
  INSERT INTO t1 (rowid, content) VALUES(20, 'three five');
  INSERT INTO t1 (rowid, content) VALUES(21, 'one three five');
  INSERT INTO t1 (rowid, content) VALUES(22, 'two three five');
  DELETE FROM t1 WHERE rowid = 19;
  DELETE FROM t1 WHERE rowid = 22;
}

do_test fts3af-1.1 {
  execsql {SELECT COUNT(*) FROM t1}
} {14}

do_test fts3ae-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {3 5 9 11 15 17 21}

do_test fts3ae-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'}
} {2 3 6 11 14 15 18}

do_test fts3ae-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'}
} {5 6 12 14 15 20 21}

do_test fts3ae-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'}
} {8 9 11 12 14 15}

do_test fts3ae-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'}
} {17 18 20 21}

finish_test

Added test/fts3af.test.





















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing updates in the FTS3 module.
#
# $Id: fts3af.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Construct a full-text search table containing keywords which are the
# ordinal numbers of the bit positions set for a sequence of integers,
# which are used for the rowid.  There are a total of 31 INSERT,
# UPDATE, and DELETE statements, so that we'll test both the
# segmentMerge() merge (over the first 16) and the termSelect() merge
# (over the level-1 segment and 15 level-0 segments).
db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'one');
  INSERT INTO t1 (rowid, content) VALUES(2, 'two');
  INSERT INTO t1 (rowid, content) VALUES(3, 'one two');
  INSERT INTO t1 (rowid, content) VALUES(4, 'three');
  INSERT INTO t1 (rowid, content) VALUES(5, 'one three');
  INSERT INTO t1 (rowid, content) VALUES(6, 'two three');
  INSERT INTO t1 (rowid, content) VALUES(7, 'one two three');
  DELETE FROM t1 WHERE rowid = 4;
  INSERT INTO t1 (rowid, content) VALUES(8, 'four');
  UPDATE t1 SET content = 'update one three' WHERE rowid = 1;
  INSERT INTO t1 (rowid, content) VALUES(9, 'one four');
  INSERT INTO t1 (rowid, content) VALUES(10, 'two four');
  DELETE FROM t1 WHERE rowid = 7;
  INSERT INTO t1 (rowid, content) VALUES(11, 'one two four');
  INSERT INTO t1 (rowid, content) VALUES(12, 'three four');
  INSERT INTO t1 (rowid, content) VALUES(13, 'one three four');
  DELETE FROM t1 WHERE rowid = 10;
  INSERT INTO t1 (rowid, content) VALUES(14, 'two three four');
  INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four');
  UPDATE t1 SET content = 'update two five' WHERE rowid = 8;
  INSERT INTO t1 (rowid, content) VALUES(16, 'five');
  DELETE FROM t1 WHERE rowid = 13;
  INSERT INTO t1 (rowid, content) VALUES(17, 'one five');
  INSERT INTO t1 (rowid, content) VALUES(18, 'two five');
  INSERT INTO t1 (rowid, content) VALUES(19, 'one two five');
  DELETE FROM t1 WHERE rowid = 16;
  INSERT INTO t1 (rowid, content) VALUES(20, 'three five');
  INSERT INTO t1 (rowid, content) VALUES(21, 'one three five');
  INSERT INTO t1 (rowid, content) VALUES(22, 'two three five');
  DELETE FROM t1 WHERE rowid = 19;
  UPDATE t1 SET content = 'update' WHERE rowid = 15;
}

do_test fts3af-1.1 {
  execsql {SELECT COUNT(*) FROM t1}
} {16}

do_test fts3af-2.0 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'update'}
} {1 8 15}

do_test fts3af-2.1 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'}
} {1 3 5 9 11 17 21}

do_test fts3af-2.2 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'}
} {2 3 6 8 11 14 18 22}

do_test fts3af-2.3 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'}
} {1 5 6 12 14 20 21 22}

do_test fts3af-2.4 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'}
} {9 11 12 14}

do_test fts3af-2.5 {
  execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'}
} {8 17 18 20 21 22}

finish_test

Added test/fts3ag.test.



























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 2006 October 19
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing handling of edge cases for various doclist
# merging functions in the FTS3 module query logic.
#
# $Id: fts3ag.test,v 1.2 2007/11/16 00:23:08 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1 (rowid, content) VALUES(1, 'this is a test');
  INSERT INTO t1 (rowid, content) VALUES(2, 'also a test');
}

# No hits at all.  Returns empty doclists from termSelect().
do_test fts3ag-1.1 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'}
} {}

# Empty left in docListExceptMerge().
do_test fts3ag-1.2 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this something'}
} {}

# Empty right in docListExceptMerge().
do_test fts3ag-1.3 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this -something'}
} {1}

# Empty left in docListPhraseMerge().
do_test fts3ag-1.4 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"this something"'}
} {}

# Empty right in docListPhraseMerge().
do_test fts3ag-1.5 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"something is"'}
} {}

# Empty left in docListOrMerge().
do_test fts3ag-1.6 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR this'}
} {1}

# Empty right in docListOrMerge().
do_test fts3ag-1.7 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR something'}
} {1}

# Empty left in docListAndMerge().
do_test fts3ag-1.8 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something this'}
} {}

# Empty right in docListAndMerge().
do_test fts3ag-1.9 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this something'}
} {}

# No support for all-except queries.
do_test fts3ag-1.10 {
  catchsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this -something'}
} {1 {SQL logic error or missing database}}

# Test that docListOrMerge() correctly handles reaching the end of one
# doclist before it reaches the end of the other.
do_test fts3ag-1.11 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR also'}
} {1 2}
do_test fts3ag-1.12 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'also OR this'}
} {1 2}

# Empty left and right in docListOrMerge().  Each term matches neither
# row, and when combined there was an assertion failure.
do_test fts3ag-1.13 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR nothing'}
} {}

finish_test

Added test/fts3ah.test.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 2006 October 31 (scaaarey)
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# here is testing correct handling of excessively long terms.
#
# $Id: fts3ah.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Generate a term of len copies of char.
proc bigterm {char len} {
  for {set term ""} {$len>0} {incr len -1} {
    append term $char
  }
  return $term
}

# Generate a document of bigterms based on characters from the list
# chars.
proc bigtermdoc {chars len} {
  set doc ""
  foreach char $chars {
    append doc " " [bigterm $char $len]
  }
  return $doc
}

set len 5000
set doc1 [bigtermdoc {a b c d} $len]
set doc2 [bigtermdoc {b d e f} $len]
set doc3 [bigtermdoc {a c e} $len]

set aterm [bigterm a $len]
set bterm [bigterm b $len]
set xterm [bigterm x $len]

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1 (rowid, content) VALUES(1, $doc1);
  INSERT INTO t1 (rowid, content) VALUES(2, $doc2);
  INSERT INTO t1 (rowid, content) VALUES(3, $doc3);
}

# No hits at all.  Returns empty doclists from termSelect().
do_test fts3ah-1.1 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'}
} {}

do_test fts3ah-1.2 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH $aterm}
} {1 3}

do_test fts3ah-1.2 {
  execsql {SELECT rowid FROM t1 WHERE t1 MATCH $xterm}
} {}

do_test fts3ah-1.3 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '$aterm -$xterm'"
} {1 3}

do_test fts3ah-1.4 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"$aterm $bterm\"'"
} {1}

finish_test

Added test/fts3ai.test.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 2007 January 17
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite fts3 library.  The
# focus here is testing handling of UPDATE when using UTF-16-encoded
# databases.
#
# $Id: fts3ai.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Return the UTF-16 representation of the supplied UTF-8 string $str.
# If $nt is true, append two 0x00 bytes as a nul terminator.
# NOTE(shess) Copied from capi3.test.
proc utf16 {str {nt 1}} {
  set r [encoding convertto unicode $str]
  if {$nt} {
    append r "\x00\x00"
  }
  return $r
}

db eval {
  PRAGMA encoding = "UTF-16le";
  CREATE VIRTUAL TABLE t1 USING fts3(content);
}

do_test fts3ai-1.0 {
  execsql {PRAGMA encoding}
} {UTF-16le}

do_test fts3ai-1.1 {
  execsql {INSERT INTO t1 (rowid, content) VALUES(1, 'one')}
  execsql {SELECT content FROM t1 WHERE rowid = 1}
} {one}

do_test fts3ai-1.2 {
  set sql "INSERT INTO t1 (rowid, content) VALUES(2, 'two')"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 2}
} {two}

do_test fts3ai-1.3 {
  set sql "INSERT INTO t1 (rowid, content) VALUES(3, 'three')"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  set sql "UPDATE t1 SET content = 'trois' WHERE rowid = 3"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 3}
} {trois}

do_test fts3ai-1.4 {
  set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(4, 'four')}]
  set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 4}
} {four}

do_test fts3ai-1.5 {
  set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(5, 'five')}]
  set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  set sql "UPDATE t1 SET content = 'cinq' WHERE rowid = 5"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_step $STMT
  sqlite3_finalize $STMT
  execsql {SELECT content FROM t1 WHERE rowid = 5}
} {cinq}

finish_test

Added test/fts3aj.test.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 2007 February 6
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  This
# tests creating fts3 tables in an attached database.
#
# $Id: fts3aj.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Clean up anything left over from a previous pass.
file delete -force test2.db
file delete -force test2.db-journal
sqlite3 db2 test2.db

db eval {
  CREATE VIRTUAL TABLE t3 USING fts3(content);
  INSERT INTO t3 (rowid, content) VALUES(1, "hello world");
}

db2 eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1 (rowid, content) VALUES(1, "hello world");
  INSERT INTO t1 (rowid, content) VALUES(2, "hello there");
  INSERT INTO t1 (rowid, content) VALUES(3, "cruel world");
}

# This has always worked because the t1_* tables used by fts3 will be
# the defaults.
do_test fts3aj-1.1 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    SELECT rowid FROM t1 WHERE t1 MATCH 'hello';
    DETACH DATABASE two;
  }
} {1 2}
# Make certain we're detached if there was an error.
catch {db eval {DETACH DATABASE two}}

# In older code, this appears to work fine, but the t2_* tables used
# by fts3 will be created in database 'main' instead of database
# 'two'.  It appears to work fine because the tables end up being the
# defaults, but obviously is badly broken if you hope to use things
# other than in the exact same ATTACH setup.
do_test fts3aj-1.2 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;
    CREATE VIRTUAL TABLE two.t2 USING fts3(content);
    INSERT INTO t2 (rowid, content) VALUES(1, "hello world");
    INSERT INTO t2 (rowid, content) VALUES(2, "hello there");
    INSERT INTO t2 (rowid, content) VALUES(3, "cruel world");
    SELECT rowid FROM t2 WHERE t2 MATCH 'hello';
    DETACH DATABASE two;
  }
} {1 2}
catch {db eval {DETACH DATABASE two}}

# In older code, this broke because the fts3 code attempted to create
# t3_* tables in database 'main', but they already existed.  Normally
# this wouldn't happen without t3 itself existing, in which case the
# fts3 code would never be called in the first place.
do_test fts3aj-1.3 {
  execsql {
    ATTACH DATABASE 'test2.db' AS two;

    CREATE VIRTUAL TABLE two.t3 USING fts3(content);
    INSERT INTO two.t3 (rowid, content) VALUES(2, "hello there");
    INSERT INTO two.t3 (rowid, content) VALUES(3, "cruel world");
    SELECT rowid FROM two.t3 WHERE t3 MATCH 'hello';

    DETACH DATABASE two;
  } db2
} {2}
catch {db eval {DETACH DATABASE two}}

catch {db2 close}
file delete -force test2.db

finish_test

Added test/fts3ak.test.



















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 2007 March 9
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  These
# make sure that fts3 insertion buffering is fully transparent when
# using transactions.
#
# $Id: fts3ak.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1 (rowid, content) VALUES(1, "hello world");
  INSERT INTO t1 (rowid, content) VALUES(2, "hello there");
  INSERT INTO t1 (rowid, content) VALUES(3, "cruel world");
}

# Test that possibly-buffered inserts went through after commit.
do_test fts3ak-1.1 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(4, "false world");
    INSERT INTO t1 (rowid, content) VALUES(5, "false door");
    COMMIT TRANSACTION;
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
  }
} {1 3 4}

# Test that buffered inserts are seen by selects in the same
# transaction.
do_test fts3ak-1.2 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(6, "another world");
    INSERT INTO t1 (rowid, content) VALUES(7, "another test");
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
    COMMIT TRANSACTION;
  }
} {1 3 4 6}

# Test that buffered inserts are seen within a transaction.  This is
# really the same test as 1.2.
do_test fts3ak-1.3 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(8, "second world");
    INSERT INTO t1 (rowid, content) VALUES(9, "second sight");
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
    ROLLBACK TRANSACTION;
  }
} {1 3 4 6 8}

# Double-check that the previous result doesn't persist past the
# rollback!
do_test fts3ak-1.4 {
  execsql {
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
  }
} {1 3 4 6}

# Test it all together.
do_test fts3ak-1.5 {
  execsql {
    BEGIN TRANSACTION;
    INSERT INTO t1 (rowid, content) VALUES(10, "second world");
    INSERT INTO t1 (rowid, content) VALUES(11, "second sight");
    ROLLBACK TRANSACTION;
    SELECT rowid FROM t1 WHERE t1 MATCH 'world';
  }
} {1 3 4 6}

# Test that the obvious case works.
do_test fts3ak-1.6 {
  execsql {
    BEGIN;
    INSERT INTO t1 (rowid, content) VALUES(12, "third world");
    COMMIT;
    SELECT rowid FROM t1 WHERE t1 MATCH 'third';
  }
} {12}

# This is exactly the same as the previous test, except that older
# code loses the INSERT due to an SQLITE_SCHEMA error.
do_test fts3ak-1.7 {
  execsql {
    BEGIN;
    INSERT INTO t1 (rowid, content) VALUES(13, "third dimension");
    CREATE TABLE x (c);
    COMMIT;
    SELECT rowid FROM t1 WHERE t1 MATCH 'dimension';
  }
} {13}

finish_test

Added test/fts3al.test.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 2007 March 28
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing isspace/isalnum/tolower problems with the
# FTS3 module.  Unfortunately, this code isn't a really principled set
# of tests, because it is impossible to know where new uses of these
# functions might appear.
#
# $Id: fts3al.test,v 1.2 2007/12/13 21:54:11 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Tests that startsWith() (calls isspace, tolower, isalnum) can handle
# hi-bit chars.  parseSpec() also calls isalnum here.
do_test fts3al-1.1 {
  execsql "CREATE VIRTUAL TABLE t1 USING fts3(content, \x80)"
} {}

# Additionally tests isspace() call in getToken(), and isalnum() call
# in tokenListToIdList().
do_test fts3al-1.2 {
  catch {
    execsql "CREATE VIRTUAL TABLE t2 USING fts3(content, tokenize \x80)"
  }
  sqlite3_errmsg $DB
} "unknown tokenizer: \x80"

# Additionally test final isalnum() in startsWith().
do_test fts3al-1.3 {
  execsql "CREATE VIRTUAL TABLE t3 USING fts3(content, tokenize\x80)"
} {}

# The snippet-generation code has calls to isspace() which are sort of
# hard to get to.  It finds convenient breakpoints by starting ~40
# chars before and after the matched term, and scanning ~10 chars
# around that position for isspace() characters.  The long word with
# embedded hi-bit chars causes one of these isspace() calls to be
# exercised.  The version with a couple extra spaces should cause the
# other isspace() call to be exercised.  [Both cases have been tested
# in the debugger, but I'm hoping to continue to catch it if simple
# constant changes change things slightly.
#
# The trailing and leading hi-bit chars help with code which tests for
# isspace() to coalesce multiple spaces.

set word "\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80"
set phrase1 "$word $word $word target $word $word $word"
set phrase2 "$word $word $word    target    $word $word $word"

db eval {CREATE VIRTUAL TABLE t4 USING fts3(content)}
db eval "INSERT INTO t4 (content) VALUES ('$phrase1')"
db eval "INSERT INTO t4 (content) VALUES ('$phrase2')"

do_test fts3al-1.4 {
  execsql {SELECT rowid, length(snippet(t4)) FROM t4 WHERE t4 MATCH 'target'}
} {1 111 2 117}

finish_test

Added test/fts3am.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2007 April 9
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  fts3
# DELETE handling assumed all fields were non-null.  This was not
# the intention at all.
#
# $Id: fts3am.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(col_a, col_b);

  INSERT INTO t1(rowid, col_a, col_b) VALUES(1, 'testing', 'testing');
  INSERT INTO t1(rowid, col_a, col_b) VALUES(2, 'only a', null);
  INSERT INTO t1(rowid, col_a, col_b) VALUES(3, null, 'only b');
  INSERT INTO t1(rowid, col_a, col_b) VALUES(4, null, null);
}

do_test fts3am-1.0 {
  execsql {
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {2 2 4}

do_test fts3am-1.1 {
  execsql {
    DELETE FROM t1 WHERE rowid = 1;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {1 1 3}

do_test fts3am-1.2 {
  execsql {
    DELETE FROM t1 WHERE rowid = 2;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 1 2}

do_test fts3am-1.3 {
  execsql {
    DELETE FROM t1 WHERE rowid = 3;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 0 1}

do_test fts3am-1.4 {
  execsql {
    DELETE FROM t1 WHERE rowid = 4;
    SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1;
  }
} {0 0 0}

finish_test

Added test/fts3an.test.









































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# 2007 April 26
#
# The author disclaims copyright to this source code.
#
#*************************************************************************
# This file implements tests for prefix-searching in the fts3
# component of the SQLite library.
#
# $Id: fts3an.test,v 1.2 2007/12/13 21:54:11 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# A large string to prime the pump with.
set text {
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
  iaculis mollis ipsum. Praesent rhoncus placerat justo. Duis non quam
  sed turpis posuere placerat. Curabitur et lorem in lorem porttitor
  aliquet. Pellentesque bibendum tincidunt diam. Vestibulum blandit
  ante nec elit. In sapien diam, facilisis eget, dictum sed, viverra
  at, felis. Vestibulum magna. Sed magna dolor, vestibulum rhoncus,
  ornare vel, vulputate sit amet, felis. Integer malesuada, tellus at
  luctus gravida, diam nunc porta nibh, nec imperdiet massa metus eu
  lectus. Aliquam nisi. Nunc fringilla nulla at lectus. Suspendisse
  potenti. Cum sociis natoque penatibus et magnis dis parturient
  montes, nascetur ridiculus mus. Pellentesque odio nulla, feugiat eu,
  suscipit nec, consequat quis, risus.
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(c);

  INSERT INTO t1(rowid, c) VALUES(1, $text);
  INSERT INTO t1(rowid, c) VALUES(2, 'Another lovely row');
}

# Exact match
do_test fts3an-1.1 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem'"
} {1}

# And a prefix
do_test fts3an-1.2 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore*'"
} {1}

# Prefix includes exact match
do_test fts3an-1.3 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem*'"
} {1}

# Make certain everything isn't considered a prefix!
do_test fts3an-1.4 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore'"
} {}

# Prefix across multiple rows.
do_test fts3an-1.5 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo*'"
} {1 2}

# Likewise, with multiple hits in one document.
do_test fts3an-1.6 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'l*'"
} {1 2}

# Prefix which should only hit one document.
do_test fts3an-1.7 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lov*'"
} {2}

# * not at end is dropped.
do_test fts3an-1.8 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo *'"
} {}

# Stand-alone * is dropped.
do_test fts3an-1.9 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '*'"
} {}

# Phrase-query prefix.
do_test fts3an-1.10 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r*\"'"
} {2}
do_test fts3an-1.11 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r\"'"
} {}

# Phrase query with multiple prefix matches.
do_test fts3an-1.12 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l*\"'"
} {1 2}

# Phrase query with multiple prefix matches.
do_test fts3an-1.13 {
  execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l* row\"'"
} {2}




# Test across updates (and, by implication, deletes).

# Version of text without "lorem".
regsub -all {[Ll]orem} $text '' ntext

db eval {
  CREATE VIRTUAL TABLE t2 USING fts3(c);

  INSERT INTO t2(rowid, c) VALUES(1, $text);
  INSERT INTO t2(rowid, c) VALUES(2, 'Another lovely row');
  UPDATE t2 SET c = $ntext WHERE rowid = 1;
}

# Can't see lorem as an exact match.
do_test fts3an-2.1 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lorem'"
} {}

# Can't see a prefix of lorem, either.
do_test fts3an-2.2 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lore*'"
} {}

# Can see lovely in the other document.
do_test fts3an-2.3 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lo*'"
} {2}

# Can still see other hits.
do_test fts3an-2.4 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'l*'"
} {1 2}

# Prefix which should only hit one document.
do_test fts3an-2.5 {
  execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lov*'"
} {2}



# Test with a segment which will have multiple levels in the tree.

# Build a big document with lots of unique terms.
set bigtext $text
foreach c {a b c d e} {
  regsub -all {[A-Za-z]+} $bigtext "&$c" t
  append bigtext $t
}

# Populate a table with many copies of the big document, so that we
# can test the number of hits found.  Populate $ret with the expected
# hit counts for each row.  offsets() returns 4 elements for every
# hit.  We'll have 6 hits for row 1, 1 for row 2, and 6*(2^5)==192 for
# $bigtext.
set ret {6 1}
db eval {
  BEGIN;
  CREATE VIRTUAL TABLE t3 USING fts3(c);

  INSERT INTO t3(rowid, c) VALUES(1, $text);
  INSERT INTO t3(rowid, c) VALUES(2, 'Another lovely row');
}
for {set i 0} {$i<100} {incr i} {
  db eval {INSERT INTO t3(rowid, c) VALUES(3+$i, $bigtext)}
  lappend ret 192
}
db eval {COMMIT;}

# Test that we get the expected number of hits.
do_test fts3an-3.1 {
  set t {}
  db eval {SELECT offsets(t3) as o FROM t3 WHERE t3 MATCH 'l*'} {
    set l [llength $o]
    lappend t [expr {$l/4}]
  }
  set t
} $ret

# TODO(shess) It would be useful to test a couple edge cases, but I
# don't know if we have the precision to manage it from here at this
# time.  Prefix hits can cross leaves, which the code above _should_
# hit by virtue of size.  There are two variations on this.  If the
# tree is 2 levels high, the code will find the leaf-node extent
# directly, but if it is higher, the code will have to follow two
# separate interior branches down the tree.  Both should be tested.

finish_test

Added test/fts3ao.test.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# 2007 June 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module.
#
# $Id: fts3ao.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is not defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

#---------------------------------------------------------------------
# These tests, fts3ao-1.*, test that ticket #2429 is fixed.
#
db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(a, b, c);
  INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two');
}
do_test fts3ao-1.1 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE c MATCH 'four';
  }
} {1 {one <b>four</b> two}}
do_test fts3ao-1.2 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE b MATCH 'four';
  }
} {1 {one <b>four</b>}}
do_test fts3ao-1.3 {
  execsql {
    SELECT rowid, snippet(t1) FROM t1 WHERE a MATCH 'four';
  }
} {1 {one three <b>four</b>}}

#---------------------------------------------------------------------
# Test that it is possible to rename an fts3 table.
#
do_test fts3ao-2.1 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {t1 t1_content t1_segments t1_segdir}
do_test fts3ao-2.2 {
  execsql { ALTER TABLE t1 RENAME to fts_t1; }
} {}
do_test fts3ao-2.3 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts3ao-2.4 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir}

# See what happens when renaming the fts3 table fails.
#
do_test fts3ao-2.5 {
  catchsql {
    CREATE TABLE t1_segdir(a, b, c);
    ALTER TABLE fts_t1 RENAME to t1;
  }
} {1 {SQL logic error or missing database}}
do_test fts3ao-2.6 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts3ao-2.7 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir}

# See what happens when renaming the fts3 table fails inside a transaction.
#
do_test fts3ao-2.8 {
  execsql {
    BEGIN;
    INSERT INTO fts_t1(a, b, c) VALUES('one two three', 'one four', 'one two');
  }
} {}
do_test fts3ao-2.9 {
  catchsql {
    ALTER TABLE fts_t1 RENAME to t1;
  }
} {1 {SQL logic error or missing database}}
do_test fts3ao-2.10 {
  execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; }
} {1 {one three <b>four</b>}}
do_test fts3ao-2.11 {
  execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'}
} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir}
do_test fts3ao-2.12 {
  execsql COMMIT
  execsql {SELECT a FROM fts_t1}
} {{one three four} {one two three}}
do_test fts3ao-2.12 {
  execsql { SELECT a, b, c FROM fts_t1 WHERE c MATCH 'four'; }
} {{one three four} {one four} {one four two}}

#-------------------------------------------------------------------
# Close, delete and reopen the database. The following test should 
# be run on an initially empty db.
#
db close
file delete -force test.db test.db-journal
sqlite3 db test.db

do_test fts3ao-3.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts3(a, b, c);
    INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one two');
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
  }
} {{one three four} {one four} {one two}}

# This test was crashing at one point.
#
do_test fts3ao-3.2 {
  execsql {
    SELECT a, b, c FROM t1 WHERE c MATCH 'two';
    CREATE TABLE t3(a, b, c);
    SELECT a, b, c FROM t1 WHERE  c  MATCH 'two';
  }
} {{one three four} {one four} {one two} {one three four} {one four} {one two}}

#---------------------------------------------------------------------
# Test that it is possible to rename an fts3 table in an attached 
# database.
#
file delete -force test2.db test2.db-journal

do_test fts3ao-3.1 {
  execsql {
    ATTACH 'test2.db' AS aux;
    CREATE VIRTUAL TABLE aux.t1 USING fts3(a, b, c);
    INSERT INTO aux.t1(a, b, c) VALUES(
      'neung song sahm', 'neung see', 'neung see song'
    );
  }
} {}

do_test fts3ao-3.2 {
  execsql { SELECT a, b, c FROM aux.t1 WHERE a MATCH 'song'; }
} {{neung song sahm} {neung see} {neung see song}}

do_test fts3ao-3.3 {
  execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; }
} {{one three four} {one four} {one two}}

do_test fts3ao-3.4 {
  execsql { ALTER TABLE aux.t1 RENAME TO t2 }
} {}

do_test fts3ao-3.2 {
  execsql { SELECT a, b, c FROM t2 WHERE a MATCH 'song'; }
} {{neung song sahm} {neung see} {neung see song}}

do_test fts3ao-3.3 {
  execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; }
} {{one three four} {one four} {one two}}

finish_test

Added test/fts3atoken.test.





























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# 2007 June 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library. The focus 
# of this script is testing the pluggable tokeniser feature of the 
# FTS3 module.
#
# $Id: fts3atoken.test,v 1.1 2007/08/20 17:38:42 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

proc escape_string {str} {
  set out ""
  foreach char [split $str ""] {
    scan $char %c i
    if {$i<=127} {
      append out $char
    } else {
      append out [format {\x%.4x} $i]
    }
  }
  set out
}

#--------------------------------------------------------------------------
# Test cases fts3token-1.* are the warm-body test for the SQL scalar
# function fts3_tokenizer(). The procedure is as follows:
#
#   1: Verify that there is no such fts3 tokenizer as 'blah'.
#
#   2: Query for the built-in tokenizer 'simple'. Insert a copy of the
#      retrieved value as tokenizer 'blah'.
#
#   3: Test that the value returned for tokenizer 'blah' is now the
#      same as that retrieved for 'simple'.
#
#   4: Test that it is now possible to create an fts3 table using 
#      tokenizer 'blah' (it was not possible in step 1).
#
#   5: Test that the table created to use tokenizer 'blah' is usable.
#
do_test fts3token-1.1 {
  catchsql {
    CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize blah);
  }
} {1 {unknown tokenizer: blah}}
do_test fts3token-1.2 {
  execsql {
    SELECT fts3_tokenizer('blah', fts3_tokenizer('simple')) IS NULL;
  }
} {0}
do_test fts3token-1.3 {
  execsql {
    SELECT fts3_tokenizer('blah') == fts3_tokenizer('simple');
  }
} {1}
do_test fts3token-1.4 {
  catchsql {
    CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize blah);
  }
} {0 {}}
do_test fts3token-1.5 {
  execsql {
    INSERT INTO t1(content) VALUES('There was movement at the station');
    INSERT INTO t1(content) VALUES('For the word has passed around');
    INSERT INTO t1(content) VALUES('That the colt from ol regret had got away');
    SELECT content FROM t1 WHERE content MATCH 'movement'
  }
} {{There was movement at the station}}

#--------------------------------------------------------------------------
# Test cases fts3token-2.* test error cases in the scalar function based
# API for getting and setting tokenizers.
#
do_test fts3token-2.1 {
  catchsql {
    SELECT fts3_tokenizer('nosuchtokenizer');
  }
} {1 {unknown tokenizer: nosuchtokenizer}}

#--------------------------------------------------------------------------
# Test cases fts3token-3.* test the three built-in tokenizers with a
# simple input string via the built-in test function. This is as much
# to test the test function as the tokenizer implementations.
#
do_test fts3token-3.1 {
  execsql {
    SELECT fts3_tokenizer_test('simple', 'I don''t see how');
  }
} {{0 i I 1 don don 2 t t 3 see see 4 how how}}
do_test fts3token-3.2 {
  execsql {
    SELECT fts3_tokenizer_test('porter', 'I don''t see how');
  }
} {{0 i I 1 don don 2 t t 3 see see 4 how how}}
ifcapable icu {
  do_test fts3token-3.3 {
    execsql {
      SELECT fts3_tokenizer_test('icu', 'I don''t see how');
    }
  } {{0 i I 1 don't don't 2 see see 3 how how}}
}

#--------------------------------------------------------------------------
# Test cases fts3token-4.* test the ICU tokenizer. In practice, this
# tokenizer only has two modes - "thai" and "everybody else". Some other
# Asian languages (Lao, Khmer etc.) require the same special treatment as 
# Thai, but ICU doesn't support them yet.
#
ifcapable icu {

  proc do_icu_test {name locale input output} {
    set ::out [db eval { SELECT fts3_tokenizer_test('icu', $locale, $input) }]
    do_test $name {
      lindex $::out 0
    } $output
  }
  
  do_icu_test fts3token-4.1 en_US  {}   {}
  do_icu_test fts3token-4.2 en_US {Test cases fts3} [list \
    0 test Test 1 cases cases 2 fts3 fts3
  ]

  # The following test shows that ICU is smart enough to recognise
  # Thai chararacters, even when the locale is set to English/United 
  # States.
  #
  set input "\u0e2d\u0e30\u0e44\u0e23\u0e19\u0e30\u0e04\u0e23\u0e31\u0e1a"
  set output    "0 \u0e2d\u0e30\u0e44\u0e23 \u0e2d\u0e30\u0e44\u0e23 "
  append output "1 \u0e19\u0e30 \u0e19\u0e30 "
  append output "2 \u0e04\u0e23\u0e31\u0e1a \u0e04\u0e23\u0e31\u0e1a"

  do_icu_test fts3token-4.3 th_TH  $input $output
  do_icu_test fts3token-4.4 en_US  $input $output

  # ICU handles an unknown locale by falling back to the default.
  # So this is not an error.
  do_icu_test fts3token-4.5 MiddleOfTheOcean  $input $output

  set    longtoken "AReallyReallyLongTokenOneThatWillSurelyRequire"
  append longtoken "AReallocInTheIcuTokenizerCode"

  set    input "short tokens then "
  append input $longtoken
  set    output "0 short short "
  append output "1 tokens tokens "
  append output "2 then then "
  append output "3 [string tolower $longtoken] $longtoken"

  do_icu_test fts3token-4.6 MiddleOfTheOcean  $input $output
  do_icu_test fts3token-4.7 th_TH  $input $output
  do_icu_test fts3token-4.8 en_US  $input $output
}

do_test fts3token-internal {
  execsql { SELECT fts3_tokenizer_internal_test() }
} {ok}

finish_test

Added test/fts3b.test.





















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# 2007 August 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  This
# script tests for the fts2 rowid-versus-vacuum problem (ticket #2566).
#
# $Id: fts3b.test,v 1.3 2007/09/13 18:14:49 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is not defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (c) VALUES('this is a test');
  INSERT INTO t1 (c) VALUES('that was a test');
  INSERT INTO t1 (c) VALUES('this is fun');
  DELETE FROM t1 WHERE c = 'that was a test';
}

# Baseline test.
do_test fts3b-1.1 {
  execsql {
    SELECT rowid FROM t1 WHERE c MATCH 'this';
  }
} {1 3}

db eval {VACUUM}

# The VACUUM renumbered the t1_content table in fts2, which breaks
# this.
do_test fts3b-1.2 {
  execsql {
    SELECT rowid FROM t1 WHERE c MATCH 'this';
  }
} {1 3}

# The t2 table is unfortunately pretty contrived.  We need documents
# that are bigger than ROOT_MAX (1024) to force segments out of the
# segdir and into %_segments.  We also need to force segment merging
# to generate a hole in the %_segments table, which needs more than 16
# docs.  Beyond that, to test correct operation of BLOCK_SELECT_STMT,
# we need to merge a mult-level tree, which is where the 10,000 comes
# from.  Which is slow, thus the set of transactions, with the 500
# being a number such that 10,000/500 > 16.
set text {
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
  iaculis mollis ipsum. Praesent rhoncus placerat justo. Duis non quam
  sed turpis posuere placerat. Curabitur et lorem in lorem porttitor
  aliquet. Pellentesque bibendum tincidunt diam. Vestibulum blandit
  ante nec elit. In sapien diam, facilisis eget, dictum sed, viverra
  at, felis. Vestibulum magna. Sed magna dolor, vestibulum rhoncus,
  ornare vel, vulputate sit amet, felis. Integer malesuada, tellus at
  luctus gravida, diam nunc porta nibh, nec imperdiet massa metus eu
  lectus. Aliquam nisi. Nunc fringilla nulla at lectus. Suspendisse
  potenti. Cum sociis natoque penatibus et magnis dis parturient
  montes, nascetur ridiculus mus. Pellentesque odio nulla, feugiat eu,
  suscipit nec, consequat quis, risus.
}
append text $text

db eval {CREATE VIRTUAL TABLE t2 USING fts3(c)}
set res {}
db eval {BEGIN}
for {set ii 0} {$ii<10000} {incr ii} {
  db eval {INSERT INTO t2 (c) VALUES ($text)}
  lappend res [expr {$ii+1}]
  if {($ii%500)==0} {
    db eval {
      COMMIT;
      BEGIN;
    }
  }
}
db eval {COMMIT}

do_test fts3b-2.1 {
  execsql {
    SELECT rowid FROM t2 WHERE c MATCH 'lorem';
  }
} $res

db eval {VACUUM}

# The VACUUM renumbered the t2_segment table in fts2, which would
# break the following.
do_test fts3b-2.2 {
  execsql {
    SELECT rowid FROM t2 WHERE c MATCH 'lorem';
  }
} $res

# Since fts3 is already an API break, I've marked the table-named
# column HIDDEN.

db eval {
  CREATE VIRTUAL TABLE t3 USING fts3(c);
  INSERT INTO t3 (c) VALUES('this is a test');
  INSERT INTO t3 (c) VALUES('that was a test');
  INSERT INTO t3 (c) VALUES('this is fun');
  DELETE FROM t3 WHERE c = 'that was a test';
}

# Test that the table-named column still works.
do_test fts3b-3.1 {
  execsql {
    SELECT snippet(t3) FROM t3 WHERE t3 MATCH 'test';
  }
} {{this is a <b>test</b>}}

# Test that the column doesn't appear when selecting all columns.
do_test fts3b-3.2 {
  execsql {
    SELECT * FROM t3 WHERE rowid = 1;
  }
} {{this is a test}}

# Test that the column doesn't conflict with inserts that don't name
# columns.
do_test fts3b-3.3 {
  execsql {
    INSERT INTO t3 VALUES ('another test');
  }
} {}

# fts3 adds a new implicit column, docid, which acts as an alias for
# rowid.

db eval {
  CREATE VIRTUAL TABLE t4 USING fts3(c);
  INSERT INTO t4 (c) VALUES('this is a test');
  INSERT INTO t4 (c) VALUES('that was a test');
  INSERT INTO t4 (c) VALUES('this is fun');
  DELETE FROM t4 WHERE c = 'that was a test';
}

# Test that docid is present and identical to rowid.
do_test fts3b-4.1 {
  execsql {
    SELECT rowid FROM t4 WHERE rowid <> docid;
  }
} {}

# Test that docid is hidden.
do_test fts3b-4.2 {
  execsql {
    SELECT * FROM t4 WHERE rowid = 1;
  }
} {{this is a test}}

# Test that docid can be selected.
do_test fts3b-4.3 {
  execsql {
    SELECT docid, * FROM t4 WHERE rowid = 1;
  }
} {1 {this is a test}}

# Test that docid can be used in WHERE.
do_test fts3b-4.4 {
  execsql {
    SELECT docid, * FROM t4 WHERE docid = 1;
  }
} {1 {this is a test}}

# Test that the column doesn't conflict with inserts that don't name
# columns.  [Yes, this is the same as fts3b-3.3, here just in case the
# goals of that test change.]
do_test fts3b-4.5 {
  execsql {
    INSERT INTO t4 VALUES ('another test');
  }
} {}

# Test that the docid can be forced on insert.
do_test fts3b-4.6 {
  execsql {
    INSERT INTO t4 (docid, c) VALUES (10, 'yet another test');
    SELECT * FROM t4 WHERE docid = 10;
  }
} {{yet another test}}

# Test that rowid can also be forced.
do_test fts3b-4.7 {
  execsql {
    INSERT INTO t4 (docid, c) VALUES (12, 'still testing');
    SELECT * FROM t4 WHERE docid = 12;
  }
} {{still testing}}

# If an insert tries to set both docid and rowid, require an error.
do_test fts3b-4.8 {
  catchsql {
    INSERT INTO t4 (rowid, docid, c) VALUES (14, 15, 'bad test');
    SELECT * FROM t4 WHERE docid = 14;
  }
} {1 {SQL logic error or missing database}}

# Don't allow update of docid, to match rowid behaviour.
do_test fts3b-4.9 {
  catchsql {
    UPDATE t4 SET docid = 14 WHERE docid = 12;
  }
} {1 {SQL logic error or missing database}}

finish_test

Added test/fts3c.test.











































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# 2008 June 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file exercises some new testing functions in the FTS3 module,
# and then uses them to do some basic tests that FTS3 is internally
# working as expected.
#
# $Id: fts3c.test,v 1.1 2008/07/03 19:53:22 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is not defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

#*************************************************************************
# Probe to see if support for these functions is compiled in.
# TODO(shess): Change main.mk to do the right thing and remove this test.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'x');
}

set s {SELECT dump_terms(t1, 1) FROM t1 LIMIT 1}
set r {1 {unable to use function dump_terms in the requested context}}
if {[catchsql $s]==$r} {
  finish_test
  return
}

#*************************************************************************
# Test that the new functions give appropriate errors.
do_test fts3c-0.0 {
  catchsql {
    SELECT dump_terms(t1, 1) FROM t1 LIMIT 1;
  }
} {1 {dump_terms: incorrect arguments}}

do_test fts3c-0.1 {
  catchsql {
    SELECT dump_terms(t1, 0, 0, 0) FROM t1 LIMIT 1;
  }
} {1 {dump_terms: incorrect arguments}}

do_test fts3c-0.2 {
  catchsql {
    SELECT dump_terms(1, t1) FROM t1 LIMIT 1;
  }
} {1 {unable to use function dump_terms in the requested context}}

do_test fts3c-0.3 {
  catchsql {
    SELECT dump_terms(t1, 16, 16) FROM t1 LIMIT 1;
  }
} {1 {dump_terms: segment not found}}

do_test fts3c-0.4 {
  catchsql {
    SELECT dump_doclist(t1) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: incorrect arguments}}

do_test fts3c-0.5 {
  catchsql {
    SELECT dump_doclist(t1, NULL) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: empty second argument}}

do_test fts3c-0.6 {
  catchsql {
    SELECT dump_doclist(t1, '') FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: empty second argument}}

do_test fts3c-0.7 {
  catchsql {
    SELECT dump_doclist(t1, 'a', 0) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: incorrect arguments}}

do_test fts3c-0.8 {
  catchsql {
    SELECT dump_doclist(t1, 'a', 0, 0, 0) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: incorrect arguments}}

do_test fts3c-0.9 {
  catchsql {
    SELECT dump_doclist(t1, 'a', 16, 16) FROM t1 LIMIT 1;
  }
} {1 {dump_doclist: segment not found}}

#*************************************************************************
# Utility function to check for the expected terms in the segment
# level/index.  _all version does same but for entire index.
proc check_terms {test level index terms} {
  # TODO(shess): Figure out why uplevel in do_test can't catch
  # $level and $index directly.
  set ::level $level
  set ::index $index
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $terms]
}
proc check_terms_all {test terms} {
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1) FROM t1 LIMIT 1;
    }
  } [list $terms]
}

# Utility function to check for the expected doclist for the term in
# segment level/index.  _all version does same for entire index.
proc check_doclist {test level index term doclist} {
  # TODO(shess): Again, why can't the non-:: versions work?
  set ::term $term
  set ::level $level
  set ::index $index
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}
proc check_doclist_all {test term doclist} {
  set ::term $term
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}

#*************************************************************************
# Test the segments resulting from straight-forward inserts.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
}

# Check for expected segments and expected matches.
do_test fts3c-1.0.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 0 2}
do_test fts3c-1.0.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \
        {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \
        {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}]

# Check the specifics of the segments constructed.
# Logical view of entire index.
check_terms_all   fts3c-1.0.1   {a is test that this was}
check_doclist_all fts3c-1.0.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist_all fts3c-1.0.1.2 is {[1 0[1]] [3 0[1]]}
check_doclist_all fts3c-1.0.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist_all fts3c-1.0.1.4 that {[2 0[0]]}
check_doclist_all fts3c-1.0.1.5 this {[1 0[0]] [3 0[0]]}
check_doclist_all fts3c-1.0.1.6 was {[2 0[1]]}

# Segment 0,0
check_terms   fts3c-1.0.2   0 0 {a is test this}
check_doclist fts3c-1.0.2.1 0 0 a {[1 0[2]]}
check_doclist fts3c-1.0.2.2 0 0 is {[1 0[1]]}
check_doclist fts3c-1.0.2.3 0 0 test {[1 0[3]]}
check_doclist fts3c-1.0.2.4 0 0 this {[1 0[0]]}

# Segment 0,1
check_terms   fts3c-1.0.3   0 1 {a test that was}
check_doclist fts3c-1.0.3.1 0 1 a {[2 0[2]]}
check_doclist fts3c-1.0.3.2 0 1 test {[2 0[3]]}
check_doclist fts3c-1.0.3.3 0 1 that {[2 0[0]]}
check_doclist fts3c-1.0.3.4 0 1 was {[2 0[1]]}

# Segment 0,2
check_terms   fts3c-1.0.4   0 2 {a is test this}
check_doclist fts3c-1.0.4.1 0 2 a {[3 0[2]]}
check_doclist fts3c-1.0.4.2 0 2 is {[3 0[1]]}
check_doclist fts3c-1.0.4.3 0 2 test {[3 0[3]]}
check_doclist fts3c-1.0.4.4 0 2 this {[3 0[0]]}

#*************************************************************************
# Test the segments resulting from inserts followed by a delete.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE docid = 1;
}

do_test fts3c-1.1.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 0 2 0 3}
do_test fts3c-1.1.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}}

check_terms_all fts3c-1.1.1 {a is test that this was}
check_doclist_all fts3c-1.1.1.1 a {[2 0[2]] [3 0[2]]}
check_doclist_all fts3c-1.1.1.2 is {[3 0[1]]}
check_doclist_all fts3c-1.1.1.3 test {[2 0[3]] [3 0[3]]}
check_doclist_all fts3c-1.1.1.4 that {[2 0[0]]}
check_doclist_all fts3c-1.1.1.5 this {[3 0[0]]}
check_doclist_all fts3c-1.1.1.6 was {[2 0[1]]}

check_terms fts3c-1.1.2 0 0 {a is test this}
check_doclist fts3c-1.1.2.1 0 0 a {[1 0[2]]}
check_doclist fts3c-1.1.2.2 0 0 is {[1 0[1]]}
check_doclist fts3c-1.1.2.3 0 0 test {[1 0[3]]}
check_doclist fts3c-1.1.2.4 0 0 this {[1 0[0]]}

check_terms fts3c-1.1.3 0 1 {a test that was}
check_doclist fts3c-1.1.3.1 0 1 a {[2 0[2]]}
check_doclist fts3c-1.1.3.2 0 1 test {[2 0[3]]}
check_doclist fts3c-1.1.3.3 0 1 that {[2 0[0]]}
check_doclist fts3c-1.1.3.4 0 1 was {[2 0[1]]}

check_terms fts3c-1.1.4 0 2 {a is test this}
check_doclist fts3c-1.1.4.1 0 2 a {[3 0[2]]}
check_doclist fts3c-1.1.4.2 0 2 is {[3 0[1]]}
check_doclist fts3c-1.1.4.3 0 2 test {[3 0[3]]}
check_doclist fts3c-1.1.4.4 0 2 this {[3 0[0]]}

check_terms fts3c-1.1.5 0 3 {a is test this}
check_doclist fts3c-1.1.5.1 0 3 a {[1]}
check_doclist fts3c-1.1.5.2 0 3 is {[1]}
check_doclist fts3c-1.1.5.3 0 3 test {[1]}
check_doclist fts3c-1.1.5.4 0 3 this {[1]}

#*************************************************************************
# Test results when all references to certain tokens are deleted.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE docid IN (1,3);
}

# Still 4 segments because 0,3 will contain deletes for docid 1 and 3.
do_test fts3c-1.2.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 0 2 0 3}
do_test fts3c-1.2.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts3c-1.2.1 {a is test that this was}
check_doclist_all fts3c-1.2.1.1 a {[2 0[2]]}
check_doclist_all fts3c-1.2.1.2 is {}
check_doclist_all fts3c-1.2.1.3 test {[2 0[3]]}
check_doclist_all fts3c-1.2.1.4 that {[2 0[0]]}
check_doclist_all fts3c-1.2.1.5 this {}
check_doclist_all fts3c-1.2.1.6 was {[2 0[1]]}

check_terms fts3c-1.2.2 0 0 {a is test this}
check_doclist fts3c-1.2.2.1 0 0 a {[1 0[2]]}
check_doclist fts3c-1.2.2.2 0 0 is {[1 0[1]]}
check_doclist fts3c-1.2.2.3 0 0 test {[1 0[3]]}
check_doclist fts3c-1.2.2.4 0 0 this {[1 0[0]]}

check_terms fts3c-1.2.3 0 1 {a test that was}
check_doclist fts3c-1.2.3.1 0 1 a {[2 0[2]]}
check_doclist fts3c-1.2.3.2 0 1 test {[2 0[3]]}
check_doclist fts3c-1.2.3.3 0 1 that {[2 0[0]]}
check_doclist fts3c-1.2.3.4 0 1 was {[2 0[1]]}

check_terms fts3c-1.2.4 0 2 {a is test this}
check_doclist fts3c-1.2.4.1 0 2 a {[3 0[2]]}
check_doclist fts3c-1.2.4.2 0 2 is {[3 0[1]]}
check_doclist fts3c-1.2.4.3 0 2 test {[3 0[3]]}
check_doclist fts3c-1.2.4.4 0 2 this {[3 0[0]]}

check_terms fts3c-1.2.5 0 3 {a is test this}
check_doclist fts3c-1.2.5.1 0 3 a {[1] [3]}
check_doclist fts3c-1.2.5.2 0 3 is {[1] [3]}
check_doclist fts3c-1.2.5.3 0 3 test {[1] [3]}
check_doclist fts3c-1.2.5.4 0 3 this {[1] [3]}

#*************************************************************************
# Test results when everything is optimized manually.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE docid IN (1,3);
  DROP TABLE IF EXISTS t1old;
  ALTER TABLE t1 RENAME TO t1old;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) SELECT docid, c FROM t1old;
  DROP TABLE t1old;
}

# Should be a single optimal segment with the same logical results.
do_test fts3c-1.3.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts3c-1.3.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts3c-1.3.1 {a test that was}
check_doclist_all fts3c-1.3.1.1 a {[2 0[2]]}
check_doclist_all fts3c-1.3.1.2 test {[2 0[3]]}
check_doclist_all fts3c-1.3.1.3 that {[2 0[0]]}
check_doclist_all fts3c-1.3.1.4 was {[2 0[1]]}

check_terms fts3c-1.3.2 0 0 {a test that was}
check_doclist fts3c-1.3.2.1 0 0 a {[2 0[2]]}
check_doclist fts3c-1.3.2.2 0 0 test {[2 0[3]]}
check_doclist fts3c-1.3.2.3 0 0 that {[2 0[0]]}
check_doclist fts3c-1.3.2.4 0 0 was {[2 0[1]]}

finish_test

Added test/fts3d.test.





















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# 2008 June 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this script is testing the FTS3 module's optimize() function.
#
# $Id: fts3d.test,v 1.2 2008/07/15 21:32:07 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is not defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

#*************************************************************************
# Probe to see if support for the FTS3 dump_* functions is compiled in.
# TODO(shess): Change main.mk to do the right thing and remove this test.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'x');
}

set s {SELECT dump_terms(t1, 1) FROM t1 LIMIT 1}
set r {1 {unable to use function dump_terms in the requested context}}
if {[catchsql $s]==$r} {
  finish_test
  return
}

#*************************************************************************
# Utility function to check for the expected terms in the segment
# level/index.  _all version does same but for entire index.
proc check_terms {test level index terms} {
  # TODO(shess): Figure out why uplevel in do_test can't catch
  # $level and $index directly.
  set ::level $level
  set ::index $index
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $terms]
}
proc check_terms_all {test terms} {
  do_test $test.terms {
    execsql {
      SELECT dump_terms(t1) FROM t1 LIMIT 1;
    }
  } [list $terms]
}

# Utility function to check for the expected doclist for the term in
# segment level/index.  _all version does same for entire index.
proc check_doclist {test level index term doclist} {
  # TODO(shess): Again, why can't the non-:: versions work?
  set ::term $term
  set ::level $level
  set ::index $index
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term, $::level, $::index) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}
proc check_doclist_all {test term doclist} {
  set ::term $term
  do_test $test {
    execsql {
      SELECT dump_doclist(t1, $::term) FROM t1 LIMIT 1;
    }
  } [list $doclist]
}

#*************************************************************************
# Test results when all rows are deleted and one is added back.
# Previously older segments would continue to exist, but now the index
# should be dropped when the table is empty.  The results should look
# exactly like we never added the earlier rows in the first place.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE 1=1; -- Delete each row rather than dropping table.
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
}

# Should be a single initial segment.
do_test fts3d-1.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts3d-1.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} {{0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}}

check_terms_all fts3d-1.1 {a is test this}
check_doclist_all fts3d-1.1.1 a {[1 0[2]]}
check_doclist_all fts3d-1.1.2 is {[1 0[1]]}
check_doclist_all fts3d-1.1.3 test {[1 0[3]]}
check_doclist_all fts3d-1.1.4 this {[1 0[0]]}

check_terms   fts3d-1.2   0 0 {a is test this}
check_doclist fts3d-1.2.1 0 0 a {[1 0[2]]}
check_doclist fts3d-1.2.2 0 0 is {[1 0[1]]}
check_doclist fts3d-1.2.3 0 0 test {[1 0[3]]}
check_doclist fts3d-1.2.4 0 0 this {[1 0[0]]}

#*************************************************************************
# Test results when everything is optimized manually.
# NOTE(shess): This is a copy of fts3c-1.3.  I've pulled a copy here
# because fts3d-2 and fts3d-3 should have identical results.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE docid IN (1,3);
  DROP TABLE IF EXISTS t1old;
  ALTER TABLE t1 RENAME TO t1old;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) SELECT docid, c FROM t1old;
  DROP TABLE t1old;
}

# Should be a single optimal segment with the same logical results.
do_test fts3d-2.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts3d-2.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts3d-2.1 {a test that was}
check_doclist_all fts3d-2.1.1 a {[2 0[2]]}
check_doclist_all fts3d-2.1.2 test {[2 0[3]]}
check_doclist_all fts3d-2.1.3 that {[2 0[0]]}
check_doclist_all fts3d-2.1.4 was {[2 0[1]]}

check_terms fts3d-2.2 0 0 {a test that was}
check_doclist fts3d-2.2.1 0 0 a {[2 0[2]]}
check_doclist fts3d-2.2.2 0 0 test {[2 0[3]]}
check_doclist fts3d-2.2.3 0 0 that {[2 0[0]]}
check_doclist fts3d-2.2.4 0 0 was {[2 0[1]]}

#*************************************************************************
# Test results when everything is optimized via optimize().
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
  DELETE FROM t1 WHERE docid IN (1,3);
  SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
}

# Should be a single optimal segment with the same logical results.
do_test fts3d-3.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0}
do_test fts3d-3.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}}

check_terms_all fts3d-3.1 {a test that was}
check_doclist_all fts3d-3.1.1 a {[2 0[2]]}
check_doclist_all fts3d-3.1.2 test {[2 0[3]]}
check_doclist_all fts3d-3.1.3 that {[2 0[0]]}
check_doclist_all fts3d-3.1.4 was {[2 0[1]]}

check_terms fts3d-3.2 0 0 {a test that was}
check_doclist fts3d-3.2.1 0 0 a {[2 0[2]]}
check_doclist fts3d-3.2.2 0 0 test {[2 0[3]]}
check_doclist fts3d-3.2.3 0 0 that {[2 0[0]]}
check_doclist fts3d-3.2.4 0 0 was {[2 0[1]]}

#*************************************************************************
# Test optimize() against a table involving segment merges.
# NOTE(shess): Since there's no transaction, each of the INSERT/UPDATE
# statements generates a segment.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);

  INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test');

  UPDATE t1 SET c = 'This is a test one' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test one' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test one' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test two' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test two' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test two' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test three' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test three' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test three' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test four' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test four' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test four' WHERE rowid = 3;

  UPDATE t1 SET c = 'This is a test' WHERE rowid = 1;
  UPDATE t1 SET c = 'That was a test' WHERE rowid = 2;
  UPDATE t1 SET c = 'This is a test' WHERE rowid = 3;
}

# 2 segments in level 0, 1 in level 1 (18 segments created, 16
# merged).
do_test fts3d-4.segments {
  execsql {
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {0 0 0 1 1 0}

do_test fts3d-4.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \
        {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \
        {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}]

check_terms_all fts3d-4.1      {a four is one test that this three two was}
check_doclist_all fts3d-4.1.1  a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist_all fts3d-4.1.2  four {}
check_doclist_all fts3d-4.1.3  is {[1 0[1]] [3 0[1]]}
check_doclist_all fts3d-4.1.4  one {}
check_doclist_all fts3d-4.1.5  test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist_all fts3d-4.1.6  that {[2 0[0]]}
check_doclist_all fts3d-4.1.7  this {[1 0[0]] [3 0[0]]}
check_doclist_all fts3d-4.1.8  three {}
check_doclist_all fts3d-4.1.9  two {}
check_doclist_all fts3d-4.1.10 was {[2 0[1]]}

check_terms fts3d-4.2     0 0 {a four test that was}
check_doclist fts3d-4.2.1 0 0 a {[2 0[2]]}
check_doclist fts3d-4.2.2 0 0 four {[2]}
check_doclist fts3d-4.2.3 0 0 test {[2 0[3]]}
check_doclist fts3d-4.2.4 0 0 that {[2 0[0]]}
check_doclist fts3d-4.2.5 0 0 was {[2 0[1]]}

check_terms fts3d-4.3     0 1 {a four is test this}
check_doclist fts3d-4.3.1 0 1 a {[3 0[2]]}
check_doclist fts3d-4.3.2 0 1 four {[3]}
check_doclist fts3d-4.3.3 0 1 is {[3 0[1]]}
check_doclist fts3d-4.3.4 0 1 test {[3 0[3]]}
check_doclist fts3d-4.3.5 0 1 this {[3 0[0]]}

check_terms fts3d-4.4      1 0 {a four is one test that this three two was}
check_doclist fts3d-4.4.1  1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist fts3d-4.4.2  1 0 four {[1] [2 0[4]] [3 0[4]]}
check_doclist fts3d-4.4.3  1 0 is {[1 0[1]] [3 0[1]]}
check_doclist fts3d-4.4.4  1 0 one {[1] [2] [3]}
check_doclist fts3d-4.4.5  1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist fts3d-4.4.6  1 0 that {[2 0[0]]}
check_doclist fts3d-4.4.7  1 0 this {[1 0[0]] [3 0[0]]}
check_doclist fts3d-4.4.8  1 0 three {[1] [2] [3]}
check_doclist fts3d-4.4.9  1 0 two {[1] [2] [3]}
check_doclist fts3d-4.4.10 1 0 was {[2 0[1]]}

# Optimize should leave the result in the level of the highest-level
# prior segment.
do_test fts3d-4.5 {
  execsql {
    SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {{Index optimized} 1 0}

# Identical to fts3d-4.matches.
do_test fts3d-4.5.matches {
  execsql {
    SELECT OFFSETS(t1) FROM t1
     WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid;
  }
} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \
        {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \
        {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}]

check_terms_all fts3d-4.5.1     {a is test that this was}
check_doclist_all fts3d-4.5.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist_all fts3d-4.5.1.2 is {[1 0[1]] [3 0[1]]}
check_doclist_all fts3d-4.5.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist_all fts3d-4.5.1.4 that {[2 0[0]]}
check_doclist_all fts3d-4.5.1.5 this {[1 0[0]] [3 0[0]]}
check_doclist_all fts3d-4.5.1.6 was {[2 0[1]]}

check_terms fts3d-4.5.2     1 0 {a is test that this was}
check_doclist fts3d-4.5.2.1 1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]}
check_doclist fts3d-4.5.2.2 1 0 is {[1 0[1]] [3 0[1]]}
check_doclist fts3d-4.5.2.3 1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]}
check_doclist fts3d-4.5.2.4 1 0 that {[2 0[0]]}
check_doclist fts3d-4.5.2.5 1 0 this {[1 0[0]] [3 0[0]]}
check_doclist fts3d-4.5.2.6 1 0 was {[2 0[1]]}

# Re-optimizing does nothing.
do_test fts3d-5.0 {
  execsql {
    SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {{Index already optimal} 1 0}

# Even if we move things around, still does nothing.
do_test fts3d-5.1 {
  execsql {
    UPDATE t1_segdir SET level = 2 WHERE level = 1 AND idx = 0;
    SELECT OPTIMIZE(t1) FROM t1 LIMIT 1;
    SELECT level, idx FROM t1_segdir ORDER BY level, idx;
  }
} {{Index already optimal} 2 0}

finish_test

Added test/fts3e.test.



























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# 2008 July 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# These tests exercise the various types of fts3 cursors.
#
# $Id: fts3e.test,v 1.1 2008/07/29 20:24:46 shess Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is not defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

#*************************************************************************
# Test table scan (QUERY_GENERIC).  This kind of query happens for
# queries with no WHERE clause, or for WHERE clauses which cannot be
# satisfied by an index.
db eval {
  DROP TABLE IF EXISTS t1;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  INSERT INTO t1 (docid, c) VALUES (1, 'This is a test');
  INSERT INTO t1 (docid, c) VALUES (2, 'That was a test');
  INSERT INTO t1 (docid, c) VALUES (3, 'This is a test');
}

do_test fts3e-1.1 {
  execsql {
    SELECT docid FROM t1 ORDER BY docid;
  }
} {1 2 3}

do_test fts3e-1.2 {
  execsql {
    SELECT docid FROM t1 WHERE c LIKE '%test' ORDER BY docid;
  }
} {1 2 3}

do_test fts3e-1.3 {
  execsql {
    SELECT docid FROM t1 WHERE c LIKE 'That%' ORDER BY docid;
  }
} {2}

#*************************************************************************
# Test lookup by docid (QUERY_DOCID).  This kind of query happens for
# queries which select by the docid/rowid implicit index.
db eval {
  DROP TABLE IF EXISTS t1;
  DROP TABLE IF EXISTS t2;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE);
  INSERT INTO t2 VALUES (null, 10);
  INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test');
  INSERT INTO t2 VALUES (null, 5);
  INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'That was a test');
  INSERT INTO t2 VALUES (null, 20);
  INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test');
}

# TODO(shess): This actually is doing QUERY_GENERIC?  I'd have
# expected QUERY_DOCID in this case, as for a very large table the
# full scan is less efficient.
do_test fts3e-2.1 {
  execsql {
    SELECT docid FROM t1 WHERE docid in (1, 2, 10);
    SELECT rowid FROM t1 WHERE rowid in (1, 2, 10);
  }
} {1 2 1 2}

do_test fts3e-2.2 {
  execsql {
    SELECT docid, weight FROM t1, t2 WHERE t2.id = t1.docid ORDER BY weight;
    SELECT t1.rowid, weight FROM t1, t2 WHERE t2.id = t1.rowid ORDER BY weight;
  }
} {2 5 1 10 3 20 2 5 1 10 3 20}

do_test fts3e-2.3 {
  execsql {
    SELECT docid, weight FROM t1, t2
           WHERE t2.weight>5 AND t2.id = t1.docid ORDER BY weight;
    SELECT t1.rowid, weight FROM t1, t2
           WHERE t2.weight>5 AND t2.id = t1.rowid ORDER BY weight;
  }
} {1 10 3 20 1 10 3 20}

#*************************************************************************
# Test lookup by MATCH (QUERY_FULLTEXT).  This is the fulltext index.
db eval {
  DROP TABLE IF EXISTS t1;
  DROP TABLE IF EXISTS t2;
  CREATE VIRTUAL TABLE t1 USING fts3(c);
  CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE);
  INSERT INTO t2 VALUES (null, 10);
  INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test');
  INSERT INTO t2 VALUES (null, 5);
  INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'That was a test');
  INSERT INTO t2 VALUES (null, 20);
  INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test');
}

do_test fts3e-3.1 {
  execsql {
    SELECT docid FROM t1 WHERE t1 MATCH 'this' ORDER BY docid;
  }
} {1 3}

do_test fts3e-3.2 {
  execsql {
    SELECT docid, weight FROM t1, t2
     WHERE t1 MATCH 'this' AND t1.docid = t2.id ORDER BY weight;
  }
} {1 10 3 20}

finish_test

Added test/fts3expr.test.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# 2006 September 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module.
#
# $Id: fts3expr.test,v 1.9 2009/07/28 16:44:26 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

set sqlite_fts3_enable_parentheses 1

proc test_fts3expr {expr} {
  db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')}
}
do_test fts3expr-1.0 {
  test_fts3expr "abcd"
} {PHRASE 3 0 abcd}
do_test fts3expr-1.1 {
  test_fts3expr " tag "
} {PHRASE 3 0 tag}

do_test fts3expr-1.2 {
  test_fts3expr "ab AND cd"
} {AND {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.2.1 {
  test_fts3expr "ab cd"
} {AND {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.3 {
  test_fts3expr "ab OR cd"
} {OR {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.4 {
  test_fts3expr "ab NOT cd"
} {NOT {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.5 {
  test_fts3expr "ab NEAR cd"
} {NEAR/10 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.1 {
  test_fts3expr "ab NEAR/5 cd"
} {NEAR/5 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.2 {
  test_fts3expr "ab NEAR/87654321 cd"
} {NEAR/87654321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.3 {
  test_fts3expr "ab NEAR/7654321 cd"
} {NEAR/7654321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.4 {
  test_fts3expr "ab NEAR/654321 cd"
} {NEAR/654321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.5 {
  test_fts3expr "ab NEAR/54321 cd"
} {NEAR/54321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.6 {
  test_fts3expr "ab NEAR/4321 cd"
} {NEAR/4321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.7 {
  test_fts3expr "ab NEAR/321 cd"
} {NEAR/321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}
do_test fts3expr-1.6.8 {
  test_fts3expr "ab NEAR/21 cd"
} {NEAR/21 {PHRASE 3 0 ab} {PHRASE 3 0 cd}}

do_test fts3expr-1.7 {
  test_fts3expr {"one two three"}
} {PHRASE 3 0 one two three}
do_test fts3expr-1.8.1 {
  test_fts3expr {zero "one two three" four}
} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}}
do_test fts3expr-1.8.2 {
  test_fts3expr {zero AND "one two three" four}
} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}}
do_test fts3expr-1.8.3 {
  test_fts3expr {zero "one two three" AND four}
} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}}
do_test fts3expr-1.8.4 {
  test_fts3expr {zero AND "one two three" AND four}
} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}}
do_test fts3expr-1.9.1 {
  test_fts3expr {"one* two three"}
} {PHRASE 3 0 one+ two three}
do_test fts3expr-1.9.2 {
  test_fts3expr {"one two* three"}
} {PHRASE 3 0 one two+ three}
do_test fts3expr-1.9.3 {
  test_fts3expr {"one* two* three"}
} {PHRASE 3 0 one+ two+ three}
do_test fts3expr-1.9.4 {
  test_fts3expr {"one two three*"}
} {PHRASE 3 0 one two three+}
do_test fts3expr-1.9.5 {
  test_fts3expr {"one* two three*"}
} {PHRASE 3 0 one+ two three+}
do_test fts3expr-1.9.6 {
  test_fts3expr {"one two* three*"}
} {PHRASE 3 0 one two+ three+}
do_test fts3expr-1.9.7 {
  test_fts3expr {"one* two* three*"}
} {PHRASE 3 0 one+ two+ three+}

do_test fts3expr-1.10 {
  test_fts3expr {one* two}
} {AND {PHRASE 3 0 one+} {PHRASE 3 0 two}}
do_test fts3expr-1.11 {
  test_fts3expr {one two*}
} {AND {PHRASE 3 0 one} {PHRASE 3 0 two+}}

do_test fts3expr-1.14 {
  test_fts3expr {a:one two}
} {AND {PHRASE 0 0 one} {PHRASE 3 0 two}}
do_test fts3expr-1.15.1 {
  test_fts3expr {one b:two}
} {AND {PHRASE 3 0 one} {PHRASE 1 0 two}}
do_test fts3expr-1.15.2 {
  test_fts3expr {one B:two}
} {AND {PHRASE 3 0 one} {PHRASE 1 0 two}}

do_test fts3expr-1.16 {
  test_fts3expr {one AND two AND three AND four AND five}
} [list AND \
        [list AND \
              [list AND \
                    [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \
                    {PHRASE 3 0 three} \
              ] \
              {PHRASE 3 0 four} \
        ] \
        {PHRASE 3 0 five} \
  ]
do_test fts3expr-1.17 {
  test_fts3expr {(one AND two) AND ((three AND four) AND five)}
} [list AND \
        [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list AND {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.18 {
  test_fts3expr {(one AND two) OR ((three AND four) AND five)}
} [list OR \
        [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list AND {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.19 {
  test_fts3expr {(one AND two) AND ((three AND four) OR five)}
} [list AND \
        [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list OR \
              [list AND {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.20 {
  test_fts3expr {(one OR two) AND ((three OR four) AND five)}
} [list AND \
        [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.21 {
  test_fts3expr {(one OR two) AND ((three NOT four) AND five)}
} [list AND \
        [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list NOT {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.22 {
  test_fts3expr {(one OR two) NOT ((three OR four) AND five)}
} [list NOT \
        [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.23 {
  test_fts3expr {(((((one OR two))))) NOT (((((three OR four))) AND five))}
} [list NOT \
        [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.24 {
  test_fts3expr {one NEAR two}
} [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}]
do_test fts3expr-1.25 {
  test_fts3expr {(one NEAR two)}
} [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}]
do_test fts3expr-1.26 {
  test_fts3expr {((((((one NEAR two))))))}
} [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}]
do_test fts3expr-1.27 {
  test_fts3expr {(one NEAR two) OR ((three OR four) AND five)}
} [list OR \
        [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]
do_test fts3expr-1.28 {
  test_fts3expr {(one NEAR/321 two) OR ((three OR four) AND five)}
} [list OR \
        [list NEAR/321 {PHRASE 3 0 one} {PHRASE 3 0 two}] \
        [list AND \
              [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \
             {PHRASE 3 0 five} \
        ] \
  ]

proc strip_phrase_data {L} {
  if {[lindex $L 0] eq "PHRASE"} {
    return [lrange $L 3 end]
  }
  return [list \
    [lindex $L 0] \
    [strip_phrase_data [lindex $L 1]] \
    [strip_phrase_data [lindex $L 2]] \
  ]
}
proc test_fts3expr2 {expr} {
  strip_phrase_data [
    db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')}
  ]
}
do_test fts3expr-2.1 {
  test_fts3expr2 "ab OR cd AND ef"
} {OR ab {AND cd ef}}
do_test fts3expr-2.2 {
  test_fts3expr2 "cd AND ef OR ab"
} {OR {AND cd ef} ab}
do_test fts3expr-2.3 {
  test_fts3expr2 "ab AND cd AND ef OR gh"
} {OR {AND {AND ab cd} ef} gh}
do_test fts3expr-2.4 {
  test_fts3expr2 "ab AND cd OR ef AND gh"
} {OR {AND ab cd} {AND ef gh}}
do_test fts3expr-2.5 {
  test_fts3expr2 "ab cd"
} {AND ab cd}

do_test fts3expr-3.1 {
  test_fts3expr2 "(ab OR cd) AND ef"
} {AND {OR ab cd} ef}
do_test fts3expr-3.2 {
  test_fts3expr2 "ef AND (ab OR cd)"
} {AND ef {OR ab cd}}
do_test fts3expr-3.3 {
  test_fts3expr2 "(ab OR cd)"
} {OR ab cd}
do_test fts3expr-3.4 {
  test_fts3expr2 "(((ab OR cd)))"
} {OR ab cd}

do_test fts3expr-3.5 {
  test_fts3expr2 "one AND (two NEAR three)"
} {AND one {NEAR/10 two three}}
do_test fts3expr-3.6 {
  test_fts3expr2 "one (two NEAR three)"
} {AND one {NEAR/10 two three}}
do_test fts3expr-3.7 {
  test_fts3expr2 "(two NEAR three) one"
} {AND {NEAR/10 two three} one}
do_test fts3expr-3.8 {
  test_fts3expr2 "(two NEAR three) AND one"
} {AND {NEAR/10 two three} one}
do_test fts3expr-3.9 {
  test_fts3expr2 "(two NEAR three) (four five)"
} {AND {NEAR/10 two three} {AND four five}}
do_test fts3expr-3.10 {
  test_fts3expr2 "(two NEAR three) AND (four five)"
} {AND {NEAR/10 two three} {AND four five}}
do_test fts3expr-3.11 {
  test_fts3expr2 "(two NEAR three) (four NEAR five)"
} {AND {NEAR/10 two three} {NEAR/10 four five}}
do_test fts3expr-3.12 {
  test_fts3expr2 "(two NEAR three) OR (four NEAR five)"
} {OR {NEAR/10 two three} {NEAR/10 four five}}

do_test fts3expr-3.13 {
  test_fts3expr2 "(two NEAR/1a three)"
} {AND {AND {AND two near} 1a} three}

do_test fts3expr-3.14 {
  test_fts3expr2 "(two NEAR// three)"
} {AND {AND two near} three}
do_test fts3expr-3.15 {
  test_fts3expr2 "(two NEAR/: three)"
} {AND {AND two near} three}

do_test fts3expr-3.16 {
  test_fts3expr2 "(two NEAR three)OR(four NEAR five)"
} {OR {NEAR/10 two three} {NEAR/10 four five}}
do_test fts3expr-3.17 {
  test_fts3expr2 "(two NEAR three)OR\"four five\""
} {OR {NEAR/10 two three} {four five}}
do_test fts3expr-3.18 {
  test_fts3expr2 "one \u0080wo"
} "AND one \u0080wo"



#------------------------------------------------------------------------
# The following tests, fts3expr-4.*, test the parsers response to syntax
# errors in query expressions. This is done using a real fts3 table and
# MATCH clauses, not the parser test interface.
# 
do_test fts3expr-4.1 {
  execsql { CREATE VIRTUAL TABLE t1 USING fts3(a, b, c) }
} {}

# Mismatched parenthesis:
do_test fts3expr-4.2.1 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example AND (hello OR world))' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.2.2 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example AND (hello OR world' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.2.3 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH '(hello' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.2.4 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH '(' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.2.5 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH ')' }
} {1 {SQL logic error or missing database}}

do_test fts3expr-4.2.6 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example (hello world' }
} {1 {SQL logic error or missing database}}

# Unterminated quotation marks:
do_test fts3expr-4.3.1 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example OR "hello world' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.3.2 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example OR hello world"' }
} {1 {SQL logic error or missing database}}

# Binary operators without the required operands.
do_test fts3expr-4.4.1 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'OR hello world' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.4.2 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'hello world OR' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.4.3 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'one (hello world OR) two' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.4.4 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'one (OR hello world) two' }
} {1 {SQL logic error or missing database}}

# NEAR operators with something other than phrases as arguments.
do_test fts3expr-4.5.1 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH '(hello OR world) NEAR one' }
} {1 {SQL logic error or missing database}}
do_test fts3expr-4.5.2 {
  catchsql { SELECT * FROM t1 WHERE t1 MATCH 'one NEAR (hello OR world)' }
} {1 {SQL logic error or missing database}}

#------------------------------------------------------------------------
# The following OOM tests are designed to cover cases in fts3_expr.c.
# 
source $testdir/malloc_common.tcl
do_malloc_test fts3expr-malloc-1 -sqlbody {
  SELECT fts3_exprtest('simple', 'a b c "d e f"', 'a', 'b', 'c')
}
do_malloc_test fts3expr-malloc-2 -tclprep {
  set sqlite_fts3_enable_parentheses 0
} -sqlbody {
  SELECT fts3_exprtest('simple', 'a -b', 'a', 'b', 'c')
} -cleanup {
  set sqlite_fts3_enable_parentheses 1
}

#------------------------------------------------------------------------
# The following tests are not very important. They cover error handling
# cases in the test code, which makes test coverage easier to measure.
# 
do_test fts3expr-5.1 {
  catchsql { SELECT fts3_exprtest('simple', 'a b') }
} {1 {Usage: fts3_exprtest(tokenizer, expr, col1, ...}}
do_test fts3expr-5.2 {
  catchsql { SELECT fts3_exprtest('doesnotexist', 'a b', 'c') }
} {1 {No such tokenizer module}}
do_test fts3expr-5.3 {
  catchsql { SELECT fts3_exprtest('simple', 'a b OR', 'c') }
} {1 {Error parsing expression}}

#------------------------------------------------------------------------
# The next set of tests verifies that things actually work as they are
# supposed to when using the new syntax.
# 
do_test fts3expr-6.1 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING fts3(a);
  }
  for {set ii 1} {$ii < 32} {incr ii} {
    set v [list]
    if {$ii & 1}  { lappend v one }
    if {$ii & 2}  { lappend v two }
    if {$ii & 4}  { lappend v three }
    if {$ii & 8}  { lappend v four }
    if {$ii & 16} { lappend v five }
    execsql { INSERT INTO t1 VALUES($v) }
  }

  execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'five four one' ORDER BY rowid}
} {25 27 29 31}

foreach {id expr res} {

  2 "five four NOT one" {24 26 28 30}

  3 "five AND four OR one" 
      {1 3 5 7 9 11 13 15 17 19 21 23 24 25 26 27 28 29 30 31}

  4 "five AND (four OR one)" {17 19 21 23 24 25 26 27 28 29 30 31}

  5 "five NOT (four OR one)" {16 18 20 22}

  6 "(five NOT (four OR one)) OR (five AND (four OR one))"
      {16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31}

  7 "(five OR one) AND two AND three" {7 15 22 23 30 31}

  8 "five OR one AND two AND three" 
    {7 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31}

  9 "five OR one two three" 
    {7 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31}

  10 "five OR \"one two three\"" 
    {7 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31}

  11 "one two OR four five NOT three" {3 7 11 15 19 23 24 25 26 27 31}

  12 "(one two OR four five) NOT three" {3 11 19 24 25 26 27}

  13 "((((((one two OR four five)))))) NOT three" {3 11 19 24 25 26 27}

} {
  do_test fts3expr-6.1.$id {
    execsql { SELECT rowid FROM t1 WHERE t1 MATCH $expr ORDER BY rowid }
  } $res
}

set sqlite_fts3_enable_parentheses 0
foreach {id expr res} {
  1 "one -two three"  {5 13 21 29}
  2 "-two one three"  {5 13 21 29}
  3 "one three -two"  {5 13 21 29}
  4 "-one -two three" {4 12 20 28}
  5 "three -one -two" {4 12 20 28}
  6 "-one three -two" {4 12 20 28}
} {
  do_test fts3expr-6.2.$id {
    execsql { SELECT rowid FROM t1 WHERE t1 MATCH $expr ORDER BY rowid }
  } $res
}
set sqlite_fts3_enable_parentheses 1

do_test fts3expr-7.1 {
  execsql {
    CREATE VIRTUAL TABLE test USING fts3 (keyword);
    INSERT INTO test VALUES ('abc');
    SELECT * FROM test WHERE keyword MATCH '""';
  }
} {}


set sqlite_fts3_enable_parentheses 0
finish_test

Added test/fts3expr2.test.













































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# 2009 January 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the FTS3 module syntax parser.
#
# $Id: fts3expr2.test,v 1.2 2009/06/05 17:09:12 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

# Test overview:
# 
#   The tests in this file are pseudo-randomly generated. They test
#   the fts3 match expression parser via the test interface
#   SQL function "fts3_exprtest" (see comments in fts3_expr.c).
#
#   Each test case works as follows:
#   
#     1. A random expression tree is generated using proc [random_expr_tree].
#     2. The expression tree is converted to the text of an equivalent
#        fts3 expression using proc [tree_to_expr].
#     3. The test SQL function "fts3_exprtest" is used to parse the 
#        expression text generated in step (2), returning a parsed expression
#        tree.
#     4. Test that the tree returned in step (3) matches that generated in 
#        step (1).
#
#   In step (2), 4 different fts3 expressions are created from each 
#   expression tree by varying the following boolean properties:
#
#     * Whether or not superflous parenthesis are included. i.e. if
#       "a OR b AND (c OR d)" or "a OR (b AND (c OR d))" is generated.
#
#     * Whether or not explict AND operators are used. i.e. if
#     "a OR b AND c" or "a OR b c" is generated.
#

set sqlite_fts3_enable_parentheses 1

proc strip_phrase_data {L} {
  if {[lindex $L 0] eq "PHRASE"} {
    return [list P [lrange $L 3 end]]
  }
  return [list \
    [lindex $L 0] \
    [strip_phrase_data [lindex $L 1]] \
    [strip_phrase_data [lindex $L 2]] \
  ]
}
proc test_fts3expr2 {expr} {
  strip_phrase_data [
    db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')}
  ]
}

proc rnd {nMax} { expr {int(rand()*$nMax)} }

proc random_phrase {} {
  set phrases [list one two three four "one two" "three four"]
  list P [lindex $phrases [rnd [llength $phrases]]]
}

# Generate and return a pseudo-random expression tree. Using the same 
# format returned by the [test_fts3expr2] proc.
#
proc random_expr_tree {iHeight} {
  if {$iHeight==0 || [rnd 3]==0} {
    return [random_phrase]
  }

  set operators [list NEAR NOT AND OR]
  set op [lindex $operators [rnd 4]]

  if {$op eq "NEAR"} {
    set iDistance [rnd 15]
    return [list $op/$iDistance [random_phrase] [random_phrase]]
  }

  set iNH [expr {$iHeight - 1}]
  return [list $op [random_expr_tree $iNH] [random_expr_tree $iNH]]
}

# Given an expression tree, generate a corresponding expression.
#
proc tree_to_expr {tree all_brackets implicit_and} {
  set prec(NOT) 2
  set prec(AND) 3
  set prec()    3
  set prec(OR)  4

  set op [lindex $tree 0]

  if {$op eq "P"} {
    set phrase [lindex $tree 1]
    if {[llength $phrase]>1} {
      return "\"$phrase\""
    } else {
      return $phrase
    }
  }

  if {$op eq "NEAR/10"} {
    set op "NEAR"
  }
  if {$op eq "AND" && $implicit_and} {
    set op ""
  }

  set lhs [lindex $tree 1]
  set rhs [lindex $tree 2]
  set zLeft  [tree_to_expr $lhs $all_brackets $implicit_and]
  set zRight [tree_to_expr $rhs $all_brackets $implicit_and]

  set iPrec 5
  set iLeftPrec 0
  set iRightPrec 0

  catch {set iPrec      $prec($op)}
  catch {set iLeftPrec  $prec([lindex $lhs 0])}
  catch {set iRightPrec $prec([lindex $rhs 0])}

  if {$iLeftPrec > $iPrec || $all_brackets} {
    set zLeft "($zLeft)"
  } 
  if {$iRightPrec >= $iPrec || $all_brackets} {
    set zRight "($zRight)"
  } 

  return "$zLeft $op $zRight"
}

proc do_exprparse_test {name expr tree} {
  uplevel do_test $name [list "test_fts3expr2 {$expr}"] [list $tree]
}

for {set iTest 1} {$iTest<500} {incr iTest} {
  set t [random_expr_tree 4]

  set e1 [tree_to_expr $t 0 0]
  set e2 [tree_to_expr $t 0 1]
  set e3 [tree_to_expr $t 1 0]
  set e4 [tree_to_expr $t 1 1]

  do_exprparse_test fts3expr2-$iTest.1 $e1 $t
  do_exprparse_test fts3expr2-$iTest.2 $e2 $t
  do_exprparse_test fts3expr2-$iTest.3 $e3 $t
  do_exprparse_test fts3expr2-$iTest.4 $e4 $t
}

set sqlite_fts3_enable_parentheses 0
finish_test

Added test/fts3near.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572

# 2007 October 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
#
# $Id: fts3near.test,v 1.3 2009/01/02 17:33:46 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_ENABLE_FTS3 is defined, omit this file.
ifcapable !fts3 {
  finish_test
  return
}

db eval {
  CREATE VIRTUAL TABLE t1 USING fts3(content);
  INSERT INTO t1(content) VALUES('one three four five');
  INSERT INTO t1(content) VALUES('two three four five');
  INSERT INTO t1(content) VALUES('one two three four five');
}

do_test fts3near-1.1 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR/0 three'}
} {1}
do_test fts3near-1.2 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR/1 two'}
} {3}
do_test fts3near-1.3 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR/1 three'}
} {1 3}
do_test fts3near-1.4 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'three NEAR/1 one'}
} {1 3}
do_test fts3near-1.5 {
  execsql {SELECT docid FROM t1 WHERE content MATCH '"one two" NEAR/1 five'}
} {}
do_test fts3near-1.6 {
  execsql {SELECT docid FROM t1 WHERE content MATCH '"one two" NEAR/2 five'}
} {3}
do_test fts3near-1.7 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR four'}
} {1 3}
do_test fts3near-1.8 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'four NEAR three'}
} {1 2 3}
do_test fts3near-1.9 {
  execsql {SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/0 three'}
} {1 2 3}
do_test fts3near-1.10 {
  execsql {SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/2 one'}
} {1 3}
do_test fts3near-1.11 {
  execsql {SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/1 one'}
} {1}
do_test fts3near-1.12 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'five NEAR/1 "two three"'}
} {2 3} 
do_test fts3near-1.13 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR five'}
} {1 3} 

do_test fts3near-1.14 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'four NEAR four'}
} {} 
do_test fts3near-1.15 {
  execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR two NEAR one'}
} {3} 


# Output format of the offsets() function:
#
#     <column number> <term number> <starting offset> <number of bytes>
#
db eval {
  INSERT INTO t1(content) VALUES('A X B C D A B');
}
do_test fts3near-2.1 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR/0 B'
  }
} {{0 0 10 1 0 1 12 1}}
do_test fts3near-2.2 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'B NEAR/0 A'
  }
} {{0 1 10 1 0 0 12 1}}
do_test fts3near-2.3 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH '"C D" NEAR/0 A'
  }
} {{0 0 6 1 0 1 8 1 0 2 10 1}}
do_test fts3near-2.4 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR/0 "C D"'
  }
} {{0 1 6 1 0 2 8 1 0 0 10 1}}
do_test fts3near-2.5 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR A'
  }
} {{0 0 0 1 0 1 0 1 0 0 10 1 0 1 10 1}}
do_test fts3near-2.6 {
  execsql {
    INSERT INTO t1 VALUES('A A A');
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR/2 A';
  }
} [list [list 0 0 0 1   0 1 0 1   0 0 2 1   0 1 2 1   0 0 4 1   0 1 4 1]]
do_test fts3near-2.7 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES('A A A A');
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR A NEAR A';
  }
} [list [list \
    0 0 0 1   0 1 0 1   0 2 0 1   0 0 2 1   \
    0 1 2 1   0 2 2 1   0 0 4 1   0 1 4 1   \
    0 2 4 1   0 0 6 1   0 1 6 1   0 2 6 1   \
]]

db eval {
  DELETE FROM t1;
  INSERT INTO t1(content) VALUES(
    'one two three two four six three six nine four eight twelve'
  );
}

do_test fts3near-3.1 {
  execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/1 one'}
} {{0 1 0 3 0 0 8 5}}
do_test fts3near-3.2 {
  execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'one NEAR/1 three'}
} {{0 0 0 3 0 1 8 5}}
do_test fts3near-3.3 {
  execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/1 two'}
} {{0 1 4 3 0 0 8 5 0 1 14 3}}
do_test fts3near-3.4 {
  execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/2 two'}
} {{0 1 4 3 0 0 8 5 0 1 14 3 0 0 27 5}}
do_test fts3near-3.5 {
  execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'two NEAR/2 three'}
} {{0 0 4 3 0 1 8 5 0 0 14 3 0 1 27 5}}
do_test fts3near-3.6 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/0 "two four"'
  }
} {{0 0 8 5 0 1 14 3 0 2 18 4}}
do_test fts3near-3.7 {
  execsql {
    SELECT offsets(t1) FROM t1 WHERE content MATCH '"two four" NEAR/0 three'}
} {{0 2 8 5 0 0 14 3 0 1 18 4}}

db eval {
  INSERT INTO t1(content) VALUES('
    This specification defines Cascading Style Sheets, level 2 (CSS2). CSS2 is a style sheet language that allows authors and users to attach style (e.g., fonts, spacing, and aural cues) to structured documents (e.g., HTML documents and XML applications). By separating the presentation style of documents from the content of documents, CSS2 simplifies Web authoring and site maintenance.

    CSS2 builds on CSS1 (see [CSS1]) and, with very few exceptions, all valid CSS1 style sheets are valid CSS2 style sheets. CSS2 supports media-specific style sheets so that authors may tailor the presentation of their documents to visual browsers, aural devices, printers, braille devices, handheld devices, etc. This specification also supports content positioning, downloadable fonts, table layout, features for internationalization, automatic counters and numbering, and some properties related to user interface.
  ') 
}
do_test fts3near-4.1 {
  execsql {
    SELECT snippet(t1) FROM t1 WHERE content MATCH 'specification NEAR supports'
  }
} {{<b>...</b> devices, handheld devices, etc. This <b>specification</b> also <b>supports</b> content positioning, downloadable fonts, <b>...</b>}}

do_test fts3near-5.1 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'specification attach'
  }
} {2}
do_test fts3near-5.2 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'specification NEAR attach'
  }
} {}
do_test fts3near-5.3 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/18 attach'
  }
} {}
do_test fts3near-5.4 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/19 attach'
  }
} {2}
do_test fts3near-5.5 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/000018 attach'
  }
} {}
do_test fts3near-5.6 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/000019 attach'
  }
} {2}

db eval {
  INSERT INTO t1 VALUES('
      abbrev aberrations abjurations aboding abr abscesses absolutistic
      abstention abuses acanthuses acceptance acclaimers accomplish
      accoutring accusation acetonic acid acolytes acquitting acrylonitrile
      actives acyclic addicted adenoid adjacently adjusting admissible
      adoption adulated advantaging advertisers aedes aerogramme aetiology
      affiliative afforest afterclap agamogenesis aggrade agings agonize
      agron ailurophile airfreight airspeed alarmists alchemizing
      alexandrines alien aliped all allergenic allocator allowances almost
      alphabetizes altho alvine amaurosis ambles ameliorate amicability amnio
      amour ampicillin amusement anadromous analogues anarchy anchormen
      anecdota aneurin angst animating anlage announcements anodized
      answerable antemeridian anthracene antiabortionist anticlimaxes
      antifriction antimitotic antiphon antiques antithetic anviled
      apatosaurus aphrodisia apodal aposiopesis apparatus appendectomies
      applications appraisingly appropriate apteryx arabinose
      arboricultural archdeaconates archipelago ardently arguers armadillo
      arnicas arrayed arrowy arthroscope artisans ascensive ashier
      aspersorium assail assentor assignees assonants astereognosis
      astringency astutest atheistical atomize attachment attenuates
      attrahent audibility augite auricle auteurists autobus autolysis
      autosome avenge avidest aw awl ayes babirusa backbeats backgrounder
      backseat backswings baddie bagnios baked balefuller ballista balmily
      bandbox bandylegged bankruptcy baptism barbering bargain barneys
      barracuda barterer bashes bassists bathers batterer bavardage
      beachfront beanstalk beauteous become bedim bedtimes beermats begat
      begun belabors bellarmine belongings bending benthos bereavements
      besieger bestialized betide bevels biases bicarbonates bidentate bigger
      bile billow bine biodynamics biomedicine biotites birding bisection
      bitingly bkg blackheads blaeberry blanking blatherer bleeper blindage
      blithefulness blockish bloodstreams bloused blubbing bluestocking
      blurted boatbill bobtailed boffo bold boltrope bondservant bonks
      bookbinding bookworm booting borating boscages botchers bougainvillea
      bounty bowlegged boyhood bracketed brainstorm brandishes
      braunschweigers brazilin breakneck breathlessness brewage bridesmaids
      brighter brisker broader brokerages bronziest browband brunets bryology
      bucking budlike bugleweed bulkily bulling bummer bunglers bureau burgs
      burrito bushfire buss butlery buttressing bylines cabdriver cached
      cadaverousnesses cafeterias cakewalk calcifies calendula callboy calms
      calyptra camisoles camps candelabrum caned cannolis canoodling cantors
      cape caponize capsuling caracoled carbolics carcase carditis caretakers
      carnallite carousel carrageenan cartels carves cashbook castanets
      casuistry catalyzer catchers categorizations cathexis caucuses
      causeway cavetto cede cella cementite centenary centrals ceramics ceria
      cervixes chafferer chalcopyrites chamfers change chaotically
      characteristically charivari chases chatterer cheats cheeks chef
      chemurgy chetah chickaree chigoes chillies chinning chirp chive
      chloroforms chokebore choplogic chorioids chromatic chronically
      chubbiest chunder chutzpah cimetidine cinque circulated circumscribe
      cirrose citrin claddagh clamorousness clapperboards classicalism
      clauses cleanse clemency clicker clinchers cliquiest clods closeting
      cloudscape clucking cnidarian coalfish coatrack coca cockfights coddled
      coeducation coexistence cognitively coiffed colatitude collage
      collections collinear colonelcy colorimetric columelliform combos
      comforters commence commercialist commit commorancy communized compar
      compendiously complainers compliance composition comprised comradery
      concelebrants concerted conciliation concourses condensate
      condonations confab confessionals confirmed conforming congeal
      congregant conjectured conjurers connoisseurs conscripting
      conservator consolable conspired constricting consuls contagious
      contemporaneity contesters continuities contractors contrarian
      contrive convalescents convents convexly convulsed cooncan coparcenary
      coprolite copyreader cordially corklike cornflour coroner corralling
      corrigible corsages cosies cosmonauts costumer cottontails counselings
      counterclaim counterpane countertenors courageously couth coveting
      coworker cozier cracklings crampon crappies craved cream credenzas
      crematoriums cresol cricoid crinkle criterion crocodile crore crossover
      crowded cruelest crunch cruzeiros cryptomeria cubism cuesta culprit
      cumquat cupped curdle curly cursoring curvy customized cutting cyclamens
      cylindrical cytaster dachshund daikon damages damselfly dangling
      darkest databanks dauphine dazzling deadpanned deathday debauchers
      debunking decameter decedents decibel decisions declinations
      decomposition decoratively decretive deduct deescalated defecating
      deferentially definiendum defluxion defrocks degrade deice dekaliters
      deli delinquencies deludedly demarcates demineralizers demodulating
      demonstrabilities demurred deniabilities denouncement denudation
      departure deplorable deposing depredatory deputizes derivational
      desalinization descriptors desexes desisted despising destitute
      detectability determiner detoxifying devalued devilries devotions
      dextrous diagenesis dialling diaphoresis diazonium dickeys diddums
      differencing dig dignified dildo dimetric dineric dinosaurs diplodocus
      directer dirty disagrees disassembler disburses disclosures
      disconcerts discountability discrete disembarrass disenthrone
      disgruntled dishpans disintegrators dislodged disobedient
      dispassionate dispiritednesses dispraised disqualifying
      dissatisfying dissidence dissolvers distich distracting distrusts
      ditto diverse divineness dizzily dockyard dodgers doggish doited dom
      dominium doohickey doozie dorsum doubleheaders dourer downbeats
      downshifted doyennes draftsman dramatic drawling dredge drifter
      drivelines droopier drowsed drunkards dubiosities duding dulcifying
      dumpcart duodecillion durable duteous dyed dysgenic eagles earplugs
      earwitness ebonite echoers economical ectothermous edibility educates
      effected effigies eggbeaters egresses ejaculates elasticize elector
      electrodynamometer electrophorus elem eligibly eloped emaciating
      embarcaderos embezzlers embosses embryectomy emfs emotionalizing
      empiricist emu enamels enchained encoded encrusts endeavored endogamous
      endothelioma energizes engager engrosses enl enologist enrolls ensphere
      enters entirety entrap entryways envies eosinophil epicentral
      epigrammatized episodic epochs equestrian equitably erect ernes
      errorless escalated eschatology espaliers essonite estop eternity
      ethnologically eudemonics euphonious euthenist evangelizations
      eventuality evilest evulsion examinee exceptionably exciter
      excremental execrably exemplars exhalant exhorter exocrine exothermic
      expected expends explainable exploratory expostulatory expunges
      extends externals extorts extrapolative extrorse eyebolt eyra
      facetiously factor faeries fairings fallacies falsities fancifulness
      fantasticalness farmhouse fascinate fatalistically fattener fave
      fearlessly featly federates feints fellowman fencers ferny
      fertilenesses feta feudality fibers fictionalize fiefs fightback
      filefish filmier finaglers fingerboards finochio firefly firmament
      fishmeal fitted fjords flagitiousnesses flamen flaps flatfooting
      flauntier fleapit fleshes flickertail flints floaty floorboards
      floristic flow fluffily fluorescein flutes flyspecks foetal folderols
      followable foolhardier footlockers foppish forceless foredo foreknows
      foreseeing foretaste forgather forlorn formidableness fortalice
      forwarding founding foxhunting fragmentarily frangipani fray freeform
      freezable freshening fridges frilliest frizzed frontbench frottages
      fruitcake fryable fugleman fulminated functionalists fungoid furfuran
      furtive fussy fwd gadolinium galabias gallinaceous galvanism gamers
      gangland gaoling garganey garrisoning gasp gate gauger gayety geed
      geminately generalissimos genii gentled geochronology geomorphic
      geriatricians gesellschaft ghat gibbeting giggles gimps girdlers
      glabella glaive glassfuls gleefully glistered globetrotted glorifier
      gloving glutathione glyptodont goaled gobsmacked goggliest golliwog
      goobers gooseberries gormandizer gouramis grabbier gradually grampuses
      grandmothers granulated graptolite gratuitously gravitates greaten
      greenmailer greys grills grippers groan gropingly grounding groveling
      grueled grunter guardroom guggle guineas gummed gunnysacks gushingly
      gutturals gynecoid gyrostabilizer habitudes haemophilia hailer hairs
      halest hallow halters hamsters handhelds handsaw hangup haranguer
      hardheartedness harlotry harps hashing hated hauntingly hayrack
      headcases headphone headword heartbreakers heaters hebephrenia
      hedonist heightening heliozoan helots hemelytron hemorrhagic hent
      herbicides hereunto heroines heteroclitics heterotrophs hexers
      hidebound hies hightails hindmost hippopotomonstrosesquipedalian
      histologist hittable hobbledehoys hogans holdings holocrine homegirls
      homesteader homogeneousness homopolar honeys hoodwinks hoovered
      horizontally horridness horseshoers hospitalization hotdogging houri
      housemate howitzers huffier humanist humid humors huntress husbandmen
      hyaenas hydride hydrokinetics hydroponically hygrothermograph
      hyperbolically hypersensitiveness hypnogogic hypodermically
      hypothermia iatrochemistry ichthyological idealist ideograms idling
      igniting illegal illuminatingly ilmenite imbibing immateriality
      immigrating immortalizes immures imparts impeder imperfection
      impersonated implant implying imposition imprecating imprimis
      improvising impv inanenesses inaugurate incapably incentivize
      incineration incloses incomparableness inconsequential incorporate
      incrementing incumbered indecorous indentation indicative indignities
      indistinguishably indoors indulges ineducation inerrable
      inexperienced infants infestations infirmnesses inflicting
      infracostal ingathered ingressions inheritances iniquity
      injuriousnesses innervated inoculates inquisitionist insectile
      insiders insolate inspirers instatement instr insulates intactness
      intellects intensifies intercalations intercontinental interferon
      interlarded intermarrying internalizing interpersonally
      interrelatednesses intersperse interviewees intolerance
      intransigents introducing intubates invades inventing inveterate
      invocate iodides irenicism ironsmith irreducibly irresistibility
      irriguous isobarisms isometrically issuable itineracies jackdaws
      jaggery jangling javelins jeeringly jeremiad jeweler jigsawing jitter
      jocosity jokester jot jowls judicative juicy jungly jurists juxtaposed
      kalpa karstify keddah kendo kermesses keynote kibbutznik kidnaper
      kilogram kindred kingpins kissers klatch kneads knobbed knowingest
      kookaburras kruller labefaction labyrinths lacquer laddered lagoons
      lambency laminates lancinate landscapist lankiness lapse larked lasso
      laterite laudableness laundrywomen lawgiver laypersons leafhoppers
      leapfrogs leaven leeches legated legislature leitmotifs lenients
      leprous letterheads levelling lexicographically liberalists
      librettist licorice lifesaving lightheadedly likelier limekiln limped
      lines linkers lipoma liquidator listeners litharge litmus
      liverishnesses loamier lobeline locative locutionary loggier loiterer
      longevity loomed loping lotion louts lowboys luaus lucrativeness lulus
      lumpier lungi lush luthern lymphangial lythraceous machinists maculate
      maggot magnetochemistry maharani maimers majored malaprops malignants
      maloti mammary manchineel manfully manicotti manipulativenesses
      mansards manufactories maraschino margin markdown marooning marshland
      mascaraing massaging masticate matchmark matings mattes mausoleum
      mayflies mealworm meataxe medevaced medievalist meetings megavitamin
      melded melodramatic memorableness mendaciousnesses mensurable
      mercenaries mere meronymous mesmerizes mestee metallurgical
      metastasize meterages meticulosity mewed microbe microcrystalline
      micromanager microsporophyll midiron miffed milder militiamen
      millesimal milometer mincing mingily minims minstrelsy mires
      misanthropic miscalculate miscomprehended misdefines misery mishears
      misled mispickel misrepresent misspending mistranslate miswriting
      mixologists mobilizers moderators modulate mojo mollies momentum monde
      monied monocles monographs monophyletic monotonousness moocher
      moorages morality morion mortally moseyed motherly motorboat mouldering
      mousers moveables mucky mudslides mulatto multicellularity
      multipartite multivalences mundanities murkiest mushed muskiness
      mutability mutisms mycelia myosotis mythicist nacred namable napkin
      narghile nastiness nattering nauseations nearliest necessitate
      necrophobia neg negotiators neologizes nephrotomy netiquette
      neurophysiology newbie newspaper niccolite nielsbohriums nightlong
      nincompoops nitpicked nix noddling nomadize nonadhesive noncandidates
      nonconducting nondigestible nones nongreasy nonjoinder nonoccurrence
      nonporousness nonrestrictive nonstaining nonuniform nooses northwards
      nostalgic notepaper nourishment noyades nuclides numberless numskulls
      nutmegged nymphaea oatmeal obis objurgators oblivious obsequiousness
      obsoletism obtruding occlusions ocher octettes odeums offcuts
      officiation ogival oilstone olestras omikron oncogenesis onsetting
      oomphs openly ophthalmoscope opposites optimum orangutans
      orchestrations ordn organophosphates origin ornithosis orthognathous
      oscillatory ossuaries ostracized ounce outbreaks outearning outgrows
      outlived outpoints outrunning outspends outwearing overabound
      overbalance overcautious overcrowds overdubbing overexpanding
      overgraze overindustrialize overlearning overoptimism overproducing
      overripe overshadowing overspreading overstuff overtones overwind ow
      oxidizing pacer packs paganish painstakingly palate palette pally
      palsying pandemic panhandled pantheism papaws papped parading
      parallelize paranoia parasitically pardners parietal parodied pars
      participator partridgeberry passerines password pastors
      paterfamiliases patination patrolman paunch pawnshops peacekeeper
      peatbog peculator pedestrianism peduncles pegboard pellucidnesses
      pendency penitentiary penstock pentylenetetrazol peptidase perched
      perennial performing perigynous peripheralize perjurer permissively
      perpetuals persistency perspicuously perturbingly pesky petcock
      petrologists pfennige pharmacies phenformin philanderers
      philosophically phonecards phosgenes photocomposer photogenic photons
      phototype phylloid physiotherapeutics picadores pickup pieces pigging
      pilaster pillion pimples pinioned pinpricks pipers pirogi pit
      pitifullest pizza placental plainly planing plasmin platforming
      playacts playwrights plectra pleurisy plopped plug plumule plussed
      poaches poetasters pointless polarize policyholder polkaed
      polyadelphous polygraphing polyphonous pomace ponderers pooch poplar
      porcelains portableness portly positioning postage posthumously
      postponed potages potholed poulard powdering practised pranksters
      preadapt preassigning precentors precipitous preconditions predefined
      predictors preengage prefers prehumans premedical prenotification
      preplanning prepuberty presbytery presentation presidia prestissimo
      preterites prevailer prewarmed priding primitively principalships
      prisage privileged probed prochurch proctoscope products proficients
      prognathism prohibiting proletarianisms prominence promulgates
      proofreading property proportions prorate proselytize prosthesis
      proteins prototypic provenances provitamin prudish pseudonymities
      psychoanalysts psychoneuroses psychrometer publishable pufferies
      pullet pulses punchy punkins purchased purities pursers pushover
      putridity pylons pyrogenous pzazz quadricepses quaff qualmish quarriers
      quasilinear queerness questionnaires quieten quintals quislings quoits
      rabidness racketeers radiative radioisotope radiotherapists ragingly
      rainband rakishness rampagers rands raped rare raspy ratiocinator
      rattlebrain ravening razz reactivation readoption realm reapportioning
      reasoning reattempts rebidding rebuts recapitulatory receptiveness
      recipes reckonings recognizee recommendatory reconciled reconnoiters
      recontaminated recoupments recruits recumbently redact redefine
      redheaded redistributable redraw redwing reeled reenlistment reexports
      refiles reflate reflowing refortified refried refuses regelate
      registrant regretting rehabilitative reigning reinduced reinstalled
      reinvesting rejoining relations relegates religiosities reluctivity
      remastered reminisce remodifying remounted rends renovate reordered
      repartee repel rephrase replicate repossessing reprint reprogramed
      repugnantly requiter rescheduling resegregate resettled residually
      resold resourcefulness respondent restating restrainedly resubmission
      resurveyed retaliating retiarius retorsion retreated retrofitting
      returning revanchism reverberated reverted revitalization
      revolutionize rewind rhapsodizing rhizogenic rhythms ricketinesses
      ridicule righteous rilles rinks rippliest ritualize riyals roast rockery
      roguish romanizations rookiest roquelaure rotation rotundity rounder
      routinizing rubberize rubricated ruefully ruining rummaged runic
      russets ruttish sackers sacrosanctly safeguarding said salaciousness
      salinity salsas salutatorians sampan sandbag saned santonin
      saprophagous sarnies satem saturant savaged sawbucks scablike scalp
      scant scared scatter schedulers schizophrenics schnauzers schoolmarms
      scintillae scleroses scoped scotched scram scratchiness screwball
      scripting scrubwomen scrutinizing scumbled scuttled seals seasickness
      seccos secretions secularizing seditiousnesses seeking segregators
      seize selfish semeiology seminarian semitropical sensate sensors
      sentimo septicemic sequentially serener serine serums
      sesquicentennials seventeen sexiest sforzandos shadowing shallot
      shampooing sharking shearer sheered shelters shifter shiner shipper
      shitted shoaled shofroth shorebirds shortsightedly showboated shrank
      shrines shucking shuttlecocks sickeningly sideling sidewise sigil
      signifiers siliceous silty simony simulative singled sinkings sirrah
      situps skateboarder sketchpad skim skirmished skulkers skywalk slander
      slating sleaziest sleepyheads slicking slink slitting slot slub
      slumlords smallest smattered smilier smokers smriti snailfish snatch
      snides snitching snooze snowblowers snub soapboxing socialite sockeyes
      softest sold solicitings solleret sombreros somnolencies sons sopor
      sorites soubrette soupspoon southpaw spaces spandex sparkers spatially
      speccing specking spectroscopists speedsters spermatics sphincter
      spiffied spindlings spirals spitball splayfeet splitter spokeswomen
      spooled sportily spousals sprightliness sprogs spurner squalene
      squattered squelches squirms stablish staggerings stalactitic stamp
      stands starflower starwort stations stayed steamroll steeplebush
      stemmatics stepfathers stereos steroid sticks stillage stinker
      stirringly stockpiling stomaching stopcock stormers strabismuses
      strainer strappado strawberries streetwise striae strikeouts strives
      stroppiest stubbed study stunting style suavity subchloride subdeb
      subfields subjoin sublittoral subnotebooks subprograms subside
      substantial subtenants subtreasuries succeeding sucked sufferers
      sugarier sulfaguanidine sulphating summerhouse sunbonnets sunned
      superagency supercontinent superheroes supernatural superscribing
      superthin supplest suppositive surcease surfs surprise survey
      suspiration svelte swamplands swashes sweatshop swellhead swindling
      switching sworn syllabuses sympathetics synchrocyclotron syndic
      synonymously syringed tablatures tabulation tackling taiga takas talker
      tamarisks tangential tans taproom tarpapers taskmaster tattiest
      tautologically taxied teacup tearjerkers technocracies teepee
      telegenic telephony telexed temperaments temptress tenderizing tensed
      tenuring tergal terned terror testatrices tetherball textile thatched
      their theorem thereof thermometers thewy thimerosal thirsty
      thoroughwort threateningly thrived through thumbnails thwacks
      ticketing tie til timekeepers timorousness tinkers tippers tisane
      titrating toastmaster toff toking tomb tongs toolmakings topes topple
      torose tortilla totalizing touchlines tousling townsmen trachea
      tradeable tragedienne traitorous trances transcendentalists
      transferrable tranship translating transmogrifying transportable
      transvestism traumatize treachery treed trenail tressing tribeswoman
      trichromatism triennials trikes trims triplicate tristich trivializes
      trombonist trots trouts trued trunnion tryster tubes tulle tundras turban
      turgescence turnround tutelar tweedinesses twill twit tympanum typists
      tzarists ulcered ultramodern umbles unaccountability unamended
      unassertivenesses unbanned unblocked unbundled uncertified unclaimed
      uncoated unconcerns unconvinced uncrossing undefined underbodice
      underemphasize undergrowth underpayment undershirts understudy
      underwritten undissolved unearthed unentered unexpended unfeeling
      unforeseen unfussy unhair unhinges unifilar unimproved uninvitingly
      universalization unknowns unlimbering unman unmet unnaturalness
      unornament unperturbed unprecedentedly unproportionate unread
      unreflecting unreproducible unripe unsatisfying unseaworthiness
      unsharable unsociable unstacking unsubtly untactfully untied untruest
      unveils unwilled unyokes upheave upraised upstart upwind urethrae
      urtexts usurers uvula vacillators vailed validation valvule vanities
      varia variously vassaled vav veggies velours venerator ventrals
      verbalizes verification vernacularized verticality vestigially via
      vicariously victoriousness viewpoint villainies vines violoncellist
      virtual viscus vital vitrify viviparous vocalizers voidable volleys
      volutes vouches vulcanology wackos waggery wainwrights waling wallowing
      wanking wardroom warmup wartiest washwoman watchman watermarks waverer
      wayzgoose weariest weatherstripped weediness weevil welcomed
      wentletrap whackers wheatworm whelp whf whinged whirl whistles whithers
      wholesomeness whosoever widows wikiup willowier windburned windsail
      wingspread winterkilled wisecracking witchgrass witling wobbliest
      womanliness woodcut woodworking woozy working worldwide worthiest
      wrappings wretched writhe wynd xylophone yardarm yea yelped yippee yoni
      yuks zealotry zigzagger zitherists zoologists zygosis');
}

do_test fts3near-6.1 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'abbrev zygosis'
  }
} {3}
do_test fts3near-6.2 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR zygosis'
  }
} {}
do_test fts3near-6.3 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR/100 zygosis'
  }
} {}
do_test fts3near-6.4 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR/1000 zygosis'
  }
} {}
do_test fts3near-6.5 {
  execsql {
    SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR/10000 zygosis'
  }
} {3}


finish_test

Added test/func.test.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing built-in functions.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table to work with.
#
do_test func-0.0 {
  execsql {CREATE TABLE tbl1(t1 text)}
  foreach word {this program is free software} {
    execsql "INSERT INTO tbl1 VALUES('$word')"
  }
  execsql {SELECT t1 FROM tbl1 ORDER BY t1}
} {free is program software this}
do_test func-0.1 {
  execsql {
     CREATE TABLE t2(a);
     INSERT INTO t2 VALUES(1);
     INSERT INTO t2 VALUES(NULL);
     INSERT INTO t2 VALUES(345);
     INSERT INTO t2 VALUES(NULL);
     INSERT INTO t2 VALUES(67890);
     SELECT * FROM t2;
  }
} {1 {} 345 {} 67890}

# Check out the length() function
#
do_test func-1.0 {
  execsql {SELECT length(t1) FROM tbl1 ORDER BY t1}
} {4 2 7 8 4}
do_test func-1.1 {
  set r [catch {execsql {SELECT length(*) FROM tbl1 ORDER BY t1}} msg]
  lappend r $msg
} {1 {wrong number of arguments to function length()}}
do_test func-1.2 {
  set r [catch {execsql {SELECT length(t1,5) FROM tbl1 ORDER BY t1}} msg]
  lappend r $msg
} {1 {wrong number of arguments to function length()}}
do_test func-1.3 {
  execsql {SELECT length(t1), count(*) FROM tbl1 GROUP BY length(t1)
           ORDER BY length(t1)}
} {2 1 4 2 7 1 8 1}
do_test func-1.4 {
  execsql {SELECT coalesce(length(a),-1) FROM t2}
} {1 -1 3 -1 5}

# Check out the substr() function
#
do_test func-2.0 {
  execsql {SELECT substr(t1,1,2) FROM tbl1 ORDER BY t1}
} {fr is pr so th}
do_test func-2.1 {
  execsql {SELECT substr(t1,2,1) FROM tbl1 ORDER BY t1}
} {r s r o h}
do_test func-2.2 {
  execsql {SELECT substr(t1,3,3) FROM tbl1 ORDER BY t1}
} {ee {} ogr ftw is}
do_test func-2.3 {
  execsql {SELECT substr(t1,-1,1) FROM tbl1 ORDER BY t1}
} {e s m e s}
do_test func-2.4 {
  execsql {SELECT substr(t1,-1,2) FROM tbl1 ORDER BY t1}
} {e s m e s}
do_test func-2.5 {
  execsql {SELECT substr(t1,-2,1) FROM tbl1 ORDER BY t1}
} {e i a r i}
do_test func-2.6 {
  execsql {SELECT substr(t1,-2,2) FROM tbl1 ORDER BY t1}
} {ee is am re is}
do_test func-2.7 {
  execsql {SELECT substr(t1,-4,2) FROM tbl1 ORDER BY t1}
} {fr {} gr wa th}
do_test func-2.8 {
  execsql {SELECT t1 FROM tbl1 ORDER BY substr(t1,2,20)}
} {this software free program is}
do_test func-2.9 {
  execsql {SELECT substr(a,1,1) FROM t2}
} {1 {} 3 {} 6}
do_test func-2.10 {
  execsql {SELECT substr(a,2,2) FROM t2}
} {{} {} 45 {} 78}

# Only do the following tests if TCL has UTF-8 capabilities
#
if {"\u1234"!="u1234"} {

# Put some UTF-8 characters in the database
#
do_test func-3.0 {
  execsql {DELETE FROM tbl1}
  foreach word "contains UTF-8 characters hi\u1234ho" {
    execsql "INSERT INTO tbl1 VALUES('$word')"
  }
  execsql {SELECT t1 FROM tbl1 ORDER BY t1}
} "UTF-8 characters contains hi\u1234ho"
do_test func-3.1 {
  execsql {SELECT length(t1) FROM tbl1 ORDER BY t1}
} {5 10 8 5}
do_test func-3.2 {
  execsql {SELECT substr(t1,1,2) FROM tbl1 ORDER BY t1}
} {UT ch co hi}
do_test func-3.3 {
  execsql {SELECT substr(t1,1,3) FROM tbl1 ORDER BY t1}
} "UTF cha con hi\u1234"
do_test func-3.4 {
  execsql {SELECT substr(t1,2,2) FROM tbl1 ORDER BY t1}
} "TF ha on i\u1234"
do_test func-3.5 {
  execsql {SELECT substr(t1,2,3) FROM tbl1 ORDER BY t1}
} "TF- har ont i\u1234h"
do_test func-3.6 {
  execsql {SELECT substr(t1,3,2) FROM tbl1 ORDER BY t1}
} "F- ar nt \u1234h"
do_test func-3.7 {
  execsql {SELECT substr(t1,4,2) FROM tbl1 ORDER BY t1}
} "-8 ra ta ho"
do_test func-3.8 {
  execsql {SELECT substr(t1,-1,1) FROM tbl1 ORDER BY t1}
} "8 s s o"
do_test func-3.9 {
  execsql {SELECT substr(t1,-3,2) FROM tbl1 ORDER BY t1}
} "F- er in \u1234h"
do_test func-3.10 {
  execsql {SELECT substr(t1,-4,3) FROM tbl1 ORDER BY t1}
} "TF- ter ain i\u1234h"
do_test func-3.99 {
  execsql {DELETE FROM tbl1}
  foreach word {this program is free software} {
    execsql "INSERT INTO tbl1 VALUES('$word')"
  }
  execsql {SELECT t1 FROM tbl1}
} {this program is free software}

} ;# End \u1234!=u1234

# Test the abs() and round() functions.
#
ifcapable !floatingpoint {
  do_test func-4.1 {
    execsql {
      CREATE TABLE t1(a,b,c);
      INSERT INTO t1 VALUES(1,2,3);
      INSERT INTO t1 VALUES(2,12345678901234,-1234567890);
      INSERT INTO t1 VALUES(3,-2,-5);
    }
    catchsql {SELECT abs(a,b) FROM t1}
  } {1 {wrong number of arguments to function abs()}}
}
ifcapable floatingpoint {
  do_test func-4.1 {
    execsql {
      CREATE TABLE t1(a,b,c);
      INSERT INTO t1 VALUES(1,2,3);
      INSERT INTO t1 VALUES(2,1.2345678901234,-12345.67890);
      INSERT INTO t1 VALUES(3,-2,-5);
    }
    catchsql {SELECT abs(a,b) FROM t1}
  } {1 {wrong number of arguments to function abs()}}
}
do_test func-4.2 {
  catchsql {SELECT abs() FROM t1}
} {1 {wrong number of arguments to function abs()}}
ifcapable floatingpoint {
  do_test func-4.3 {
    catchsql {SELECT abs(b) FROM t1 ORDER BY a}
  } {0 {2 1.2345678901234 2}}
  do_test func-4.4 {
    catchsql {SELECT abs(c) FROM t1 ORDER BY a}
  } {0 {3 12345.6789 5}}
}
ifcapable !floatingpoint {
  if {[working_64bit_int]} {
    do_test func-4.3 {
      catchsql {SELECT abs(b) FROM t1 ORDER BY a}
    } {0 {2 12345678901234 2}}
  }
  do_test func-4.4 {
    catchsql {SELECT abs(c) FROM t1 ORDER BY a}
  } {0 {3 1234567890 5}}
}
do_test func-4.4.1 {
  execsql {SELECT abs(a) FROM t2}
} {1 {} 345 {} 67890}
do_test func-4.4.2 {
  execsql {SELECT abs(t1) FROM tbl1}
} {0.0 0.0 0.0 0.0 0.0}

ifcapable floatingpoint {
  do_test func-4.5 {
    catchsql {SELECT round(a,b,c) FROM t1}
  } {1 {wrong number of arguments to function round()}}
  do_test func-4.6 {
    catchsql {SELECT round(b,2) FROM t1 ORDER BY b}
  } {0 {-2.0 1.23 2.0}}
  do_test func-4.7 {
    catchsql {SELECT round(b,0) FROM t1 ORDER BY a}
  } {0 {2.0 1.0 -2.0}}
  do_test func-4.8 {
    catchsql {SELECT round(c) FROM t1 ORDER BY a}
  } {0 {3.0 -12346.0 -5.0}}
  do_test func-4.9 {
    catchsql {SELECT round(c,a) FROM t1 ORDER BY a}
  } {0 {3.0 -12345.68 -5.0}}
  do_test func-4.10 {
    catchsql {SELECT 'x' || round(c,a) || 'y' FROM t1 ORDER BY a}
  } {0 {x3.0y x-12345.68y x-5.0y}}
  do_test func-4.11 {
    catchsql {SELECT round() FROM t1 ORDER BY a}
  } {1 {wrong number of arguments to function round()}}
  do_test func-4.12 {
    execsql {SELECT coalesce(round(a,2),'nil') FROM t2}
  } {1.0 nil 345.0 nil 67890.0}
  do_test func-4.13 {
    execsql {SELECT round(t1,2) FROM tbl1}
  } {0.0 0.0 0.0 0.0 0.0}
  do_test func-4.14 {
    execsql {SELECT typeof(round(5.1,1));}
  } {real}
  do_test func-4.15 {
    execsql {SELECT typeof(round(5.1));}
  } {real}
  do_test func-4.16 {
    catchsql {SELECT round(b,2.0) FROM t1 ORDER BY b}
  } {0 {-2.0 1.23 2.0}}
}

# Test the upper() and lower() functions
#
do_test func-5.1 {
  execsql {SELECT upper(t1) FROM tbl1}
} {THIS PROGRAM IS FREE SOFTWARE}
do_test func-5.2 {
  execsql {SELECT lower(upper(t1)) FROM tbl1}
} {this program is free software}
do_test func-5.3 {
  execsql {SELECT upper(a), lower(a) FROM t2}
} {1 1 {} {} 345 345 {} {} 67890 67890}
ifcapable !icu {
  do_test func-5.4 {
    catchsql {SELECT upper(a,5) FROM t2}
  } {1 {wrong number of arguments to function upper()}}
}
do_test func-5.5 {
  catchsql {SELECT upper(*) FROM t2}
} {1 {wrong number of arguments to function upper()}}

# Test the coalesce() and nullif() functions
#
do_test func-6.1 {
  execsql {SELECT coalesce(a,'xyz') FROM t2}
} {1 xyz 345 xyz 67890}
do_test func-6.2 {
  execsql {SELECT coalesce(upper(a),'nil') FROM t2}
} {1 nil 345 nil 67890}
do_test func-6.3 {
  execsql {SELECT coalesce(nullif(1,1),'nil')}
} {nil}
do_test func-6.4 {
  execsql {SELECT coalesce(nullif(1,2),'nil')}
} {1}
do_test func-6.5 {
  execsql {SELECT coalesce(nullif(1,NULL),'nil')}
} {1}


# Test the last_insert_rowid() function
#
do_test func-7.1 {
  execsql {SELECT last_insert_rowid()}
} [db last_insert_rowid]

# Tests for aggregate functions and how they handle NULLs.
#
ifcapable floatingpoint {
  do_test func-8.1 {
    ifcapable explain {
      execsql {EXPLAIN SELECT sum(a) FROM t2;}
    }
    execsql {
      SELECT sum(a), count(a), round(avg(a),2), min(a), max(a), count(*) FROM t2;
    }
  } {68236 3 22745.33 1 67890 5}
}
ifcapable !floatingpoint {
  do_test func-8.1 {
    ifcapable explain {
      execsql {EXPLAIN SELECT sum(a) FROM t2;}
    }
    execsql {
      SELECT sum(a), count(a), avg(a), min(a), max(a), count(*) FROM t2;
    }
  } {68236 3 22745.0 1 67890 5}
}
do_test func-8.2 {
  execsql {
    SELECT max('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t2;
  }
} {z+67890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP}

ifcapable tempdb {
  do_test func-8.3 {
    execsql {
      CREATE TEMP TABLE t3 AS SELECT a FROM t2 ORDER BY a DESC;
      SELECT min('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t3;
    }
  } {z+1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP}
} else {
  do_test func-8.3 {
    execsql {
      CREATE TABLE t3 AS SELECT a FROM t2 ORDER BY a DESC;
      SELECT min('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t3;
    }
  } {z+1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP}
}
do_test func-8.4 {
  execsql {
    SELECT max('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t3;
  }
} {z+67890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP}
ifcapable compound {
  do_test func-8.5 {
    execsql {
      SELECT sum(x) FROM (SELECT '9223372036' || '854775807' AS x
                          UNION ALL SELECT -9223372036854775807)
    }
  } {0}
  do_test func-8.6 {
    execsql {
      SELECT typeof(sum(x)) FROM (SELECT '9223372036' || '854775807' AS x
                          UNION ALL SELECT -9223372036854775807)
    }
  } {integer}
  do_test func-8.7 {
    execsql {
      SELECT typeof(sum(x)) FROM (SELECT '9223372036' || '854775808' AS x
                          UNION ALL SELECT -9223372036854775807)
    }
  } {real}
ifcapable floatingpoint {
  do_test func-8.8 {
    execsql {
      SELECT sum(x)>0.0 FROM (SELECT '9223372036' || '854775808' AS x
                          UNION ALL SELECT -9223372036850000000)
    }
  } {1}
}
ifcapable !floatingpoint {
  do_test func-8.8 {
    execsql {
      SELECT sum(x)>0 FROM (SELECT '9223372036' || '854775808' AS x
                          UNION ALL SELECT -9223372036850000000)
    }
  } {1}
}
}

# How do you test the random() function in a meaningful, deterministic way?
#
do_test func-9.1 {
  execsql {
    SELECT random() is not null;
  }
} {1}
do_test func-9.2 {
  execsql {
    SELECT typeof(random());
  }
} {integer}
do_test func-9.3 {
  execsql {
    SELECT randomblob(32) is not null;
  }
} {1}
do_test func-9.4 {
  execsql {
    SELECT typeof(randomblob(32));
  }
} {blob}
do_test func-9.5 {
  execsql {
    SELECT length(randomblob(32)), length(randomblob(-5)),
           length(randomblob(2000))
  }
} {32 1 2000}

# The "hex()" function was added in order to be able to render blobs
# generated by randomblob().  So this seems like a good place to test
# hex().
#
ifcapable bloblit {
  do_test func-9.10 {
    execsql {SELECT hex(x'00112233445566778899aAbBcCdDeEfF')}
  } {00112233445566778899AABBCCDDEEFF}
}
set encoding [db one {PRAGMA encoding}]
if {$encoding=="UTF-16le"} {
  do_test func-9.11-utf16le {
    execsql {SELECT hex(replace('abcdefg','ef','12'))}
  } {6100620063006400310032006700}
  do_test func-9.12-utf16le {
    execsql {SELECT hex(replace('abcdefg','','12'))}
  } {6100620063006400650066006700}
  do_test func-9.13-utf16le {
    execsql {SELECT hex(replace('aabcdefg','a','aaa'))}
  } {610061006100610061006100620063006400650066006700}
} elseif {$encoding=="UTF-8"} {
  do_test func-9.11-utf8 {
    execsql {SELECT hex(replace('abcdefg','ef','12'))}
  } {61626364313267}
  do_test func-9.12-utf8 {
    execsql {SELECT hex(replace('abcdefg','','12'))}
  } {61626364656667}
  do_test func-9.13-utf8 {
    execsql {SELECT hex(replace('aabcdefg','a','aaa'))}
  } {616161616161626364656667}
}
  
# Use the "sqlite_register_test_function" TCL command which is part of
# the text fixture in order to verify correct operation of some of
# the user-defined SQL function APIs that are not used by the built-in
# functions.
#
set ::DB [sqlite3_connection_pointer db]
sqlite_register_test_function $::DB testfunc
do_test func-10.1 {
  catchsql {
    SELECT testfunc(NULL,NULL);
  }
} {1 {first argument should be one of: int int64 string double null value}}
do_test func-10.2 {
  execsql {
    SELECT testfunc(
     'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
     'int', 1234
    );
  }
} {1234}
do_test func-10.3 {
  execsql {
    SELECT testfunc(
     'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
     'string', NULL
    );
  }
} {{}}

ifcapable floatingpoint {
  do_test func-10.4 {
    execsql {
      SELECT testfunc(
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'double', 1.234
      );
    }
  } {1.234}
  do_test func-10.5 {
    execsql {
      SELECT testfunc(
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'int', 1234,
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'string', NULL,
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'double', 1.234,
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'int', 1234,
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'string', NULL,
       'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
       'double', 1.234
      );
    }
  } {1.234}
}

# Test the built-in sqlite_version(*) SQL function.
#
do_test func-11.1 {
  execsql {
    SELECT sqlite_version(*);
  }
} [sqlite3 -version]

# Test that destructors passed to sqlite3 by calls to sqlite3_result_text()
# etc. are called. These tests use two special user-defined functions
# (implemented in func.c) only available in test builds. 
#
# Function test_destructor() takes one argument and returns a copy of the
# text form of that argument. A destructor is associated with the return
# value. Function test_destructor_count() returns the number of outstanding
# destructor calls for values returned by test_destructor().
#
if {[db eval {PRAGMA encoding}]=="UTF-8"} {
  do_test func-12.1-utf8 {
    execsql {
      SELECT test_destructor('hello world'), test_destructor_count();
    }
  } {{hello world} 1}
} else {
    ifcapable {utf16} {
      do_test func-12.1-utf16 {
        execsql {
          SELECT test_destructor16('hello world'), test_destructor_count();
        }
      } {{hello world} 1}
    }
}
do_test func-12.2 {
  execsql {
    SELECT test_destructor_count();
  }
} {0}
do_test func-12.3 {
  execsql {
    SELECT test_destructor('hello')||' world'
  }
} {{hello world}}
do_test func-12.4 {
  execsql {
    SELECT test_destructor_count();
  }
} {0}
do_test func-12.5 {
  execsql {
    CREATE TABLE t4(x);
    INSERT INTO t4 VALUES(test_destructor('hello'));
    INSERT INTO t4 VALUES(test_destructor('world'));
    SELECT min(test_destructor(x)), max(test_destructor(x)) FROM t4;
  }
} {hello world}
do_test func-12.6 {
  execsql {
    SELECT test_destructor_count();
  }
} {0}
do_test func-12.7 {
  execsql {
    DROP TABLE t4;
  }
} {}


# Test that the auxdata API for scalar functions works. This test uses
# a special user-defined function only available in test builds,
# test_auxdata(). Function test_auxdata() takes any number of arguments.
do_test func-13.1 {
  execsql {
    SELECT test_auxdata('hello world');
  }
} {0}

do_test func-13.2 {
  execsql {
    CREATE TABLE t4(a, b);
    INSERT INTO t4 VALUES('abc', 'def');
    INSERT INTO t4 VALUES('ghi', 'jkl');
  }
} {}
do_test func-13.3 {
  execsql {
    SELECT test_auxdata('hello world') FROM t4;
  }
} {0 1}
do_test func-13.4 {
  execsql {
    SELECT test_auxdata('hello world', 123) FROM t4;
  }
} {{0 0} {1 1}}
do_test func-13.5 {
  execsql {
    SELECT test_auxdata('hello world', a) FROM t4;
  }
} {{0 0} {1 0}}
do_test func-13.6 {
  execsql {
    SELECT test_auxdata('hello'||'world', a) FROM t4;
  }
} {{0 0} {1 0}}

# Test that auxilary data is preserved between calls for SQL variables.
do_test func-13.7 {
  set DB [sqlite3_connection_pointer db]
  set sql "SELECT test_auxdata( ? , a ) FROM t4;"
  set STMT [sqlite3_prepare $DB $sql -1 TAIL]
  sqlite3_bind_text $STMT 1 hello\000 -1
  set res [list]
  while { "SQLITE_ROW"==[sqlite3_step $STMT] } {
    lappend res [sqlite3_column_text $STMT 0]
  }
  lappend res [sqlite3_finalize $STMT]
} {{0 0} {1 0} SQLITE_OK}

# Make sure that a function with a very long name is rejected
do_test func-14.1 {
  catch {
    db function [string repeat X 254] {return "hello"}
  } 
} {0}
do_test func-14.2 {
  catch {
    db function [string repeat X 256] {return "hello"}
  }
} {1}

do_test func-15.1 {
  catchsql {select test_error(NULL)}
} {1 {}}
do_test func-15.2 {
  catchsql {select test_error('this is the error message')}
} {1 {this is the error message}}
do_test func-15.3 {
  catchsql {select test_error('this is the error message',12)}
} {1 {this is the error message}}
do_test func-15.4 {
  db errorcode
} {12}

# Test the quote function for BLOB and NULL values.
do_test func-16.1 {
  execsql {
    CREATE TABLE tbl2(a, b);
  }
  set STMT [sqlite3_prepare $::DB "INSERT INTO tbl2 VALUES(?, ?)" -1 TAIL]
  sqlite3_bind_blob $::STMT 1 abc 3
  sqlite3_step $::STMT
  sqlite3_finalize $::STMT
  execsql {
    SELECT quote(a), quote(b) FROM tbl2;
  }
} {X'616263' NULL}

# Correctly handle function error messages that include %.  Ticket #1354
#
do_test func-17.1 {
  proc testfunc1 args {error "Error %d with %s percents %p"}
  db function testfunc1 ::testfunc1
  catchsql {
    SELECT testfunc1(1,2,3);
  }
} {1 {Error %d with %s percents %p}}

# The SUM function should return integer results when all inputs are integer.
#
do_test func-18.1 {
  execsql {
    CREATE TABLE t5(x);
    INSERT INTO t5 VALUES(1);
    INSERT INTO t5 VALUES(-99);
    INSERT INTO t5 VALUES(10000);
    SELECT sum(x) FROM t5;
  }
} {9902}
ifcapable floatingpoint {
  do_test func-18.2 {
    execsql {
      INSERT INTO t5 VALUES(0.0);
      SELECT sum(x) FROM t5;
    }
  } {9902.0}
}

# The sum of nothing is NULL.  But the sum of all NULLs is NULL.
#
# The TOTAL of nothing is 0.0.
#
do_test func-18.3 {
  execsql {
    DELETE FROM t5;
    SELECT sum(x), total(x) FROM t5;
  }
} {{} 0.0}
do_test func-18.4 {
  execsql {
    INSERT INTO t5 VALUES(NULL);
    SELECT sum(x), total(x) FROM t5
  }
} {{} 0.0}
do_test func-18.5 {
  execsql {
    INSERT INTO t5 VALUES(NULL);
    SELECT sum(x), total(x) FROM t5
  }
} {{} 0.0}
do_test func-18.6 {
  execsql {
    INSERT INTO t5 VALUES(123);
    SELECT sum(x), total(x) FROM t5
  }
} {123 123.0}

# Ticket #1664, #1669, #1670, #1674: An integer overflow on SUM causes
# an error. The non-standard TOTAL() function continues to give a helpful
# result.
#
do_test func-18.10 {
  execsql {
    CREATE TABLE t6(x INTEGER);
    INSERT INTO t6 VALUES(1);
    INSERT INTO t6 VALUES(1<<62);
    SELECT sum(x) - ((1<<62)+1) from t6;
  }
} 0
do_test func-18.11 {
  execsql {
    SELECT typeof(sum(x)) FROM t6
  }
} integer
ifcapable floatingpoint {
  do_test func-18.12 {
    catchsql {
      INSERT INTO t6 VALUES(1<<62);
      SELECT sum(x) - ((1<<62)*2.0+1) from t6;
    }
  } {1 {integer overflow}}
  do_test func-18.13 {
    execsql {
      SELECT total(x) - ((1<<62)*2.0+1) FROM t6
    }
  } 0.0
}
ifcapable !floatingpoint {
  do_test func-18.12 {
    catchsql {
      INSERT INTO t6 VALUES(1<<62);
      SELECT sum(x) - ((1<<62)*2+1) from t6;
    }
  } {1 {integer overflow}}
  do_test func-18.13 {
    execsql {
      SELECT total(x) - ((1<<62)*2+1) FROM t6
    }
  } 0.0
}
if {[working_64bit_int]} {
  do_test func-18.14 {
    execsql {
      SELECT sum(-9223372036854775805);
    }
  } -9223372036854775805
}
ifcapable compound&&subquery {

do_test func-18.15 {
  catchsql {
    SELECT sum(x) FROM 
       (SELECT 9223372036854775807 AS x UNION ALL
        SELECT 10 AS x);
  }
} {1 {integer overflow}}
if {[working_64bit_int]} {
  do_test func-18.16 {
    catchsql {
      SELECT sum(x) FROM 
         (SELECT 9223372036854775807 AS x UNION ALL
          SELECT -10 AS x);
    }
  } {0 9223372036854775797}
  do_test func-18.17 {
    catchsql {
      SELECT sum(x) FROM 
         (SELECT -9223372036854775807 AS x UNION ALL
          SELECT 10 AS x);
    }
  } {0 -9223372036854775797}
}
do_test func-18.18 {
  catchsql {
    SELECT sum(x) FROM 
       (SELECT -9223372036854775807 AS x UNION ALL
        SELECT -10 AS x);
  }
} {1 {integer overflow}}
do_test func-18.19 {
  catchsql {
    SELECT sum(x) FROM (SELECT 9 AS x UNION ALL SELECT -10 AS x);
  }
} {0 -1}
do_test func-18.20 {
  catchsql {
    SELECT sum(x) FROM (SELECT -9 AS x UNION ALL SELECT 10 AS x);
  }
} {0 1}
do_test func-18.21 {
  catchsql {
    SELECT sum(x) FROM (SELECT -10 AS x UNION ALL SELECT 9 AS x);
  }
} {0 -1}
do_test func-18.22 {
  catchsql {
    SELECT sum(x) FROM (SELECT 10 AS x UNION ALL SELECT -9 AS x);
  }
} {0 1}

} ;# ifcapable compound&&subquery

# Integer overflow on abs()
#
if {[working_64bit_int]} {
  do_test func-18.31 {
    catchsql {
      SELECT abs(-9223372036854775807);
    }
  } {0 9223372036854775807}
}
do_test func-18.32 {
  catchsql {
    SELECT abs(-9223372036854775807-1);
  }
} {1 {integer overflow}}

# The MATCH function exists but is only a stub and always throws an error.
#
do_test func-19.1 {
  execsql {
    SELECT match(a,b) FROM t1 WHERE 0;
  }
} {}
do_test func-19.2 {
  catchsql {
    SELECT 'abc' MATCH 'xyz';
  }
} {1 {unable to use function MATCH in the requested context}}
do_test func-19.3 {
  catchsql {
    SELECT 'abc' NOT MATCH 'xyz';
  }
} {1 {unable to use function MATCH in the requested context}}
do_test func-19.4 {
  catchsql {
    SELECT match(1,2,3);
  }
} {1 {wrong number of arguments to function match()}}

# Soundex tests.
#
if {![catch {db eval {SELECT soundex('hello')}}]} {
  set i 0
  foreach {name sdx} {
    euler        E460
    EULER        E460
    Euler        E460
    ellery       E460
    gauss        G200
    ghosh        G200
    hilbert      H416
    Heilbronn    H416
    knuth        K530
    kant         K530
    Lloyd        L300
    LADD         L300
    Lukasiewicz  L222
    Lissajous    L222
    A            A000
    12345        ?000
  } {
    incr i
    do_test func-20.$i {
      execsql {SELECT soundex($name)}
    } $sdx
  }
}

# Tests of the REPLACE function.
#
do_test func-21.1 {
  catchsql {
    SELECT replace(1,2);
  }
} {1 {wrong number of arguments to function replace()}}
do_test func-21.2 {
  catchsql {
    SELECT replace(1,2,3,4);
  }
} {1 {wrong number of arguments to function replace()}}
do_test func-21.3 {
  execsql {
    SELECT typeof(replace("This is the main test string", NULL, "ALT"));
  }
} {null}
do_test func-21.4 {
  execsql {
    SELECT typeof(replace(NULL, "main", "ALT"));
  }
} {null}
do_test func-21.5 {
  execsql {
    SELECT typeof(replace("This is the main test string", "main", NULL));
  }
} {null}
do_test func-21.6 {
  execsql {
    SELECT replace("This is the main test string", "main", "ALT");
  }
} {{This is the ALT test string}}
do_test func-21.7 {
  execsql {
    SELECT replace("This is the main test string", "main", "larger-main");
  }
} {{This is the larger-main test string}}
do_test func-21.8 {
  execsql {
    SELECT replace("aaaaaaa", "a", "0123456789");
  }
} {0123456789012345678901234567890123456789012345678901234567890123456789}

ifcapable tclvar {
  do_test func-21.9 {
    # Attempt to exploit a buffer-overflow that at one time existed 
    # in the REPLACE function. 
    set ::str "[string repeat A 29998]CC[string repeat A 35537]"
    set ::rep [string repeat B 65536]
    execsql {
      SELECT LENGTH(REPLACE($::str, 'C', $::rep));
    }
  } [expr 29998 + 2*65536 + 35537]
}

# Tests for the TRIM, LTRIM and RTRIM functions.
#
do_test func-22.1 {
  catchsql {SELECT trim(1,2,3)}
} {1 {wrong number of arguments to function trim()}}
do_test func-22.2 {
  catchsql {SELECT ltrim(1,2,3)}
} {1 {wrong number of arguments to function ltrim()}}
do_test func-22.3 {
  catchsql {SELECT rtrim(1,2,3)}
} {1 {wrong number of arguments to function rtrim()}}
do_test func-22.4 {
  execsql {SELECT trim('  hi  ');}
} {hi}
do_test func-22.5 {
  execsql {SELECT ltrim('  hi  ');}
} {{hi  }}
do_test func-22.6 {
  execsql {SELECT rtrim('  hi  ');}
} {{  hi}}
do_test func-22.7 {
  execsql {SELECT trim('  hi  ','xyz');}
} {{  hi  }}
do_test func-22.8 {
  execsql {SELECT ltrim('  hi  ','xyz');}
} {{  hi  }}
do_test func-22.9 {
  execsql {SELECT rtrim('  hi  ','xyz');}
} {{  hi  }}
do_test func-22.10 {
  execsql {SELECT trim('xyxzy  hi  zzzy','xyz');}
} {{  hi  }}
do_test func-22.11 {
  execsql {SELECT ltrim('xyxzy  hi  zzzy','xyz');}
} {{  hi  zzzy}}
do_test func-22.12 {
  execsql {SELECT rtrim('xyxzy  hi  zzzy','xyz');}
} {{xyxzy  hi  }}
do_test func-22.13 {
  execsql {SELECT trim('  hi  ','');}
} {{  hi  }}
if {[db one {PRAGMA encoding}]=="UTF-8"} {
  do_test func-22.14 {
    execsql {SELECT hex(trim(x'c280e1bfbff48fbfbf6869',x'6162e1bfbfc280'))}
  } {F48FBFBF6869}
  do_test func-22.15 {
    execsql {SELECT hex(trim(x'6869c280e1bfbff48fbfbf61',
                             x'6162e1bfbfc280f48fbfbf'))}
  } {6869}
  do_test func-22.16 {
    execsql {SELECT hex(trim(x'ceb1ceb2ceb3',x'ceb1'));}
  } {CEB2CEB3}
}
do_test func-22.20 {
  execsql {SELECT typeof(trim(NULL));}
} {null}
do_test func-22.21 {
  execsql {SELECT typeof(trim(NULL,'xyz'));}
} {null}
do_test func-22.22 {
  execsql {SELECT typeof(trim('hello',NULL));}
} {null}

# This is to test the deprecated sqlite3_aggregate_count() API.
#
ifcapable deprecated {
  do_test func-23.1 {
    sqlite3_create_aggregate db
    execsql {
      SELECT legacy_count() FROM t6;
    }
  } {3}
}

# The group_concat() function.
#
do_test func-24.1 {
  execsql {
    SELECT group_concat(t1) FROM tbl1
  }
} {this,program,is,free,software}
do_test func-24.2 {
  execsql {
    SELECT group_concat(t1,' ') FROM tbl1
  }
} {{this program is free software}}
do_test func-24.3 {
  execsql {
    SELECT group_concat(t1,' ' || rowid || ' ') FROM tbl1
  }
} {{this 2 program 3 is 4 free 5 software}}
do_test func-24.4 {
  execsql {
    SELECT group_concat(NULL,t1) FROM tbl1
  }
} {{}}
do_test func-24.5 {
  execsql {
    SELECT group_concat(t1,NULL) FROM tbl1
  }
} {thisprogramisfreesoftware}
do_test func-24.6 {
  execsql {
    SELECT 'BEGIN-'||group_concat(t1) FROM tbl1
  }
} {BEGIN-this,program,is,free,software}

# Ticket #3179:  Make sure aggregate functions can take many arguments.
# None of the built-in aggregates do this, so use the md5sum() from the
# test extensions.
#
unset -nocomplain midargs
set midargs {}
unset -nocomplain midres
set midres {}
unset -nocomplain result
for {set i 1} {$i<[sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1]} {incr i} {
  append midargs ,'/$i'
  append midres /$i
  set result [md5 \
     "this${midres}program${midres}is${midres}free${midres}software${midres}"]
  set sql "SELECT md5sum(t1$midargs) FROM tbl1"
  do_test func-24.7.$i {
     db eval $::sql
  } $result
}

# Ticket #3806.  If the initial string in a group_concat is an empty
# string, the separator that follows should still be present.
#
do_test func-24.8 {
  execsql {
    SELECT group_concat(CASE t1 WHEN 'this' THEN '' ELSE t1 END) FROM tbl1
  }
} {,program,is,free,software}
do_test func-24.9 {
  execsql {
    SELECT group_concat(CASE WHEN t1!='software' THEN '' ELSE t1 END) FROM tbl1
  }
} {,,,,software}

# Ticket #3923.  Initial empty strings have a separator.  But initial
# NULLs do not.
#
do_test func-24.10 {
  execsql {
    SELECT group_concat(CASE t1 WHEN 'this' THEN null ELSE t1 END) FROM tbl1
  }
} {program,is,free,software}
do_test func-24.11 {
  execsql {
   SELECT group_concat(CASE WHEN t1!='software' THEN null ELSE t1 END) FROM tbl1
  }
} {software}
do_test func-24.12 {
  execsql {
    SELECT group_concat(CASE t1 WHEN 'this' THEN ''
                          WHEN 'program' THEN null ELSE t1 END) FROM tbl1
  }
} {,is,free,software}


# Use the test_isolation function to make sure that type conversions
# on function arguments do not effect subsequent arguments.
#
do_test func-25.1 {
  execsql {SELECT test_isolation(t1,t1) FROM tbl1}
} {this program is free software}

# Try to misuse the sqlite3_create_function() interface.  Verify that
# errors are returned.
#
do_test func-26.1 {
  abuse_create_function db
} {}

# The previous test (func-26.1) registered a function with a very long
# function name that takes many arguments and always returns NULL.  Verify
# that this function works correctly.
#
do_test func-26.2 {
  set a {}
  for {set i 1} {$i<=$::SQLITE_MAX_FUNCTION_ARG} {incr i} {
    lappend a $i
  }
  db eval "
     SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789([join $a ,]);
  "
} {{}}
do_test func-26.3 {
  set a {}
  for {set i 1} {$i<=$::SQLITE_MAX_FUNCTION_ARG+1} {incr i} {
    lappend a $i
  }
  catchsql "
     SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789([join $a ,]);
  "
} {1 {too many arguments on function nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789}}
do_test func-26.4 {
  set a {}
  for {set i 1} {$i<=$::SQLITE_MAX_FUNCTION_ARG-1} {incr i} {
    lappend a $i
  }
  catchsql "
     SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789([join $a ,]);
  "
} {1 {wrong number of arguments to function nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789()}}
do_test func-26.5 {
  catchsql "
     SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_12345678a(0);
  "
} {1 {no such function: nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_12345678a}}
do_test func-26.6 {
  catchsql "
     SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789a(0);
  "
} {1 {no such function: nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789a}}

do_test func-27.1 {
  catchsql {SELECT coalesce()}
} {1 {wrong number of arguments to function coalesce()}}
do_test func-27.2 {
  catchsql {SELECT coalesce(1)}
} {1 {wrong number of arguments to function coalesce()}}
do_test func-27.3 {
  catchsql {SELECT coalesce(1,2)}
} {0 1}

# Ticket 2d401a94287b5
# Unknown function in a DEFAULT expression causes a segfault.
#
do_test func-28.1 {
  db eval {
    CREATE TABLE t28(x, y DEFAULT(nosuchfunc(1)));
  }
  catchsql {
    INSERT INTO t28(x) VALUES(1);
  }
} {1 {unknown function: nosuchfunc()}}

finish_test

Added test/fuzz.test.























































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# 2007 May 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is generating semi-random strings of SQL
# (a.k.a. "fuzz") and sending it into the parser to try to 
# generate errors.
#
# The tests in this file are really about testing fuzzily generated
# SQL parse-trees. The majority of the fuzzily generated SQL is 
# valid as far as the parser is concerned. 
#
# The most complicated trees are for SELECT statements.
#
# $Id: fuzz.test,v 1.19 2009/04/28 11:10:39 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

set ::REPEATS 5000

# If running quick.test, don't do so many iterations.
if {[info exists ::ISQUICK]} {
  if {$::ISQUICK} { set ::REPEATS 20 }
}

source $testdir/fuzz_common.tcl
expr srand(0)

#----------------------------------------------------------------
# These tests caused errors that were first caught by the tests
# in this file. They are still here.
do_test fuzz-1.1 {
  execsql {
    SELECT 'abc' LIKE X'ABCD';
  }
} {0}
do_test fuzz-1.2 {
  execsql {
    SELECT 'abc' LIKE zeroblob(10);
  }
} {0}
do_test fuzz-1.3 {
  execsql {
    SELECT zeroblob(10) LIKE 'abc';
  }
} {0}
do_test fuzz-1.4 {
  execsql {
    SELECT (- -21) % NOT (456 LIKE zeroblob(10));
  }
} {0}
do_test fuzz-1.5 {
  execsql {
    SELECT (SELECT (
        SELECT (SELECT -2147483648) FROM (SELECT 1) ORDER BY 1
    ))
  }
} {-2147483648}
do_test fuzz-1.6 {
  execsql {
    SELECT 'abc', zeroblob(1) FROM (SELECT 1) ORDER BY 1
  }
} [execsql {SELECT 'abc', zeroblob(1)}]

do_test fuzz-1.7 {
  execsql {
    SELECT ( SELECT zeroblob(1000) FROM ( 
      SELECT * FROM (SELECT 'first') ORDER BY NOT 'in') 
    )
  }
} [execsql {SELECT zeroblob(1000)}]

do_test fuzz-1.8 {
  # Problems with opcode OP_ToText (did not account for MEM_Zero).
  # Also MemExpandBlob() was marking expanded blobs as nul-terminated.
  # They are not.
  execsql {
    SELECT CAST(zeroblob(1000) AS text);
  }
} {{}}

do_test fuzz-1.9 {
  # This was causing a NULL pointer dereference of Expr.pList.
  execsql {
    SELECT 1 FROM (SELECT * FROM sqlite_master WHERE random())
  }
} {}

do_test fuzz-1.10 {
  # Bug in calculation of Parse.ckOffset causing an assert() 
  # to fail. Probably harmless.
  execsql {
    SELECT coalesce(1, substr( 1, 2, length('in' IN (SELECT 1))))
  }
} {1}

do_test fuzz-1.11 {
  # The literals (A, B, C, D) are not important, they are just used
  # to make the EXPLAIN output easier to read.
  #
  # The problem here is that the EXISTS(...) expression leaves an
  # extra value on the VDBE stack. This is confusing the parent and
  # leads to an assert() failure when OP_Insert encounters an integer
  # when it expects a record blob.
  #
  # Update: Any query with (LIMIT 0) was leaking stack.
  #
  execsql {
    SELECT 'A' FROM (SELECT 'B') ORDER BY EXISTS (
      SELECT 'C' FROM (SELECT 'D' LIMIT 0)
    )
  }
} {A}

do_test fuzz-1.12.1 {
  # Create a table with a single row.
  execsql {
    CREATE TABLE abc(b);
    INSERT INTO abc VALUES('ABCDE');
  }

  # The following query was crashing. The later subquery (in the FROM)
  # clause was flattened into the parent, but the code was not repairng
  # the "b" reference in the other sub-query. When the query was executed,
  # that "b" refered to a non-existant vdbe table-cursor.
  #
  execsql {
    SELECT 1 IN ( SELECT b UNION SELECT 1 ) FROM (SELECT b FROM abc);
  }
} {1}
do_test fuzz-1.12.2 {
  # Clean up after the previous query.
  execsql {
    DROP TABLE abc;
  }
} {}


do_test fuzz-1.13 {
  # The problem here was that when there were more expressions in
  # the ORDER BY list than the result-set list. The temporary b-tree
  # used for sorting was being misconfigured in this case.
  #
  execsql {
    SELECT 'abcd' UNION SELECT 'efgh' ORDER BY 1 ASC, 1 ASC;
  }
} {abcd efgh}

do_test fuzz-1.14.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(123, 456, 789);
  }
 
  # The [a] reference in the sub-select was causing a problem. Because
  # the internal walkSelectExpr() function was not considering compound
  # SELECT operators.
  execsql {
    SELECT 1 FROM abc
    GROUP BY c HAVING EXISTS (SELECT a UNION SELECT 123);
  }
} {1}
do_test fuzz-1.14.2 {
  execsql {
    DROP TABLE abc;
  }
} {}

# Making sure previously discovered errors have been fixed.
#
do_test fuzz-1.15 {
  execsql {
    SELECT hex(CAST(zeroblob(1000) AS integer))
  }
} {30}

do_test fuzz-1.16.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE TABLE def(a, b, c);
    CREATE TABLE ghi(a, b, c);
  }
} {}
do_test fuzz-1.16.2 {
  catchsql {
    SELECT DISTINCT EXISTS(
       SELECT 1
       FROM (
         SELECT C FROM (SELECT 1)
       )
       WHERE (SELECT c)
    )
    FROM abc
  }
} {0 {}}
do_test fuzz-1.16.3 {
  catchsql {
    SELECT DISTINCT substr(-456 ISNULL,zeroblob(1000), EXISTS(
         SELECT DISTINCT EXISTS(
           SELECT DISTINCT b FROM abc
           ORDER BY EXISTS (
             SELECT DISTINCT 2147483647 UNION ALL SELECT -2147483648
           ) ASC
         )
         FROM (
           SELECT c, c FROM (
             SELECT 456, 'injection' ORDER BY 56.1 ASC, -56.1 DESC
           )
         )
         GROUP BY (SELECT ALL (SELECT DISTINCT 'hardware')) 
         HAVING (
           SELECT DISTINCT c
           FROM (
             SELECT ALL -2147483648, 'experiments'
             ORDER BY -56.1 ASC, -56.1 DESC
           )
           GROUP BY (SELECT DISTINCT 456) IN 
                   (SELECT DISTINCT 'injection') NOT IN (SELECT ALL -456)
           HAVING EXISTS (
             SELECT ALL 'injection'
           )
         )
         UNION ALL
         SELECT a IN (
           SELECT -2147483647
           UNION ALL
           SELECT ALL 'injection'
         )
         FROM sqlite_master
       ) -- end EXISTS
    ) /* end SUBSTR() */, c NOTNULL ISNULL
    FROM abc
    ORDER BY CAST(-56.1 AS blob) ASC
  }
} {0 {}}
do_test fuzz-1.16.4 {
  execsql {
    DROP TABLE abc; DROP TABLE def; DROP TABLE ghi;
  }
} {}

do_test fuzz-1.17 {
  catchsql {
    SELECT 'hardware', 56.1 NOTNULL, random()&0
    FROM (
       SELECT ALL lower(~ EXISTS (
           SELECT 1 NOT IN (SELECT ALL 1)
       )), CAST(456 AS integer), -2147483647
       FROM (
         SELECT DISTINCT -456, CAST(1 AS integer) ISNULL
         FROM (SELECT ALL 2147483647, typeof(2147483649))
       )
    )
    GROUP BY CAST(CAST('experiments' AS blob) AS blob)
    HAVING random()
  }
} {0 {hardware 1 0}}

do_test fuzz-1.18 {
  catchsql {
     SELECT -2147483649 << upper('fault' NOT IN (
        SELECT ALL (
           SELECT ALL -1
           ORDER BY -2147483649
           LIMIT (
              SELECT ALL (
                 SELECT 0 EXCEPT SELECT DISTINCT 'experiments' ORDER BY 1 ASC
              )
           )
           OFFSET EXISTS (
              SELECT ALL 
                  (SELECT ALL -2147483648) NOT IN (
                     SELECT ALL 123456789.1234567899
                  ) IN (SELECT 2147483649) 
              FROM sqlite_master
           ) NOT IN (SELECT ALL 'The')
        )
     ))
  }
} {0 -4294967298}

# At one point the following INSERT statement caused an assert() to fail.
# 
do_test fuzz-1.19 {
  execsql { CREATE TABLE t1(a) }
  catchsql {
    INSERT INTO t1 VALUES( 
      CASE WHEN NULL THEN NULL ELSE ( SELECT 0 ORDER BY 456 ) END 
    )
  }
} {1 {1st ORDER BY term out of range - should be between 1 and 1}}
do_test fuzz-1.20 {
  execsql { DROP TABLE t1 }
} {}

#----------------------------------------------------------------
# Test some fuzzily generated expressions.
#
do_fuzzy_test fuzz-2 -template  { SELECT [Expr] }

do_test fuzz-3.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE TABLE def(a, b, c);
    CREATE TABLE ghi(a, b, c);
  }
} {}
set ::TableList  [list abc def ghi]

#----------------------------------------------------------------
# Test some fuzzily generated SELECT statements.
#
do_fuzzy_test fuzz-3.2 -template  {[Select]}

#----------------------------------------------------------------
# Insert a small amount of data into the database and then run 
# some more generated SELECT statements.
#
do_test fuzz-4.1 {
  execsql {
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc VALUES(4, 5, 6);
    INSERT INTO abc VALUES(7, 8, 9);
    INSERT INTO def VALUES(1, 2, 3);
    INSERT INTO def VALUES(4, 5, 6);
    INSERT INTO def VALUES(7, 8, 9);
    INSERT INTO ghi VALUES(1, 2, 3);
    INSERT INTO ghi VALUES(4, 5, 6);
    INSERT INTO ghi VALUES(7, 8, 9);
    CREATE INDEX abc_i ON abc(a, b, c);
    CREATE INDEX def_i ON def(c, a, b);
    CREATE INDEX ghi_i ON ghi(b, c, a);
  }
} {}
do_fuzzy_test fuzz-4.2 -template {[Select]}

#----------------------------------------------------------------
# Test some fuzzy INSERT statements:
#
do_test         fuzz-5.1 {execsql BEGIN} {}
do_fuzzy_test   fuzz-5.2 -template  {[Insert]} -errorlist table
integrity_check fuzz-5.2.integrity
do_test         fuzz-5.3 {execsql COMMIT} {}
integrity_check fuzz-5.4.integrity

#----------------------------------------------------------------
# Now that there is data in the database, run some more SELECT 
# statements
#
set ::ColumnList [list a b c]
set E {{no such col} {ambiguous column name}}
do_fuzzy_test fuzz-6.1 -template {[Select]} -errorlist $E

#----------------------------------------------------------------
# Run some SELECTs, INSERTs, UPDATEs and DELETEs in a transaction.
#
set E {{no such col} {ambiguous column name} {table}}
do_test         fuzz-7.1 {execsql BEGIN} {}
do_fuzzy_test   fuzz-7.2 -template {[Statement]} -errorlist $E
integrity_check fuzz-7.3.integrity
do_test         fuzz-7.4 {execsql COMMIT} {}
integrity_check fuzz-7.5.integrity

#----------------------------------------------------------------
# Many CREATE and DROP TABLE statements:
#
set E [list table duplicate {no such col} {ambiguous column name} {use DROP}]
do_fuzzy_test fuzz-8.1 -template {[CreateOrDropTableOrView]} -errorlist $E

close $::log
finish_test

Added test/fuzz2.test.













































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# 2007 May 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# This file checks error recovery from malformed SQL strings.
#
# $Id: fuzz2.test,v 1.3 2007/05/15 16:51:37 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


proc fuzzcatch {sql} {
  return [lindex [catchsql $sql] 0]
}

do_test fuzz2-1.1 {
  fuzzcatch {SELECT ALL "AAAAAA" . * GROUP BY LIMIT round(1), #12}
} {1}
do_test fuzz2-2.0 {
  fuzzcatch {SELECT + #100}
} {1}
do_test fuzz2-2.1 {
  fuzzcatch {SELECT 1 WHERE ( #61 NOT MATCH ROUND( 1 ) )}
} {1}
do_test fuzz2-2.2 {
  fuzzcatch {SELECT 1 LIMIT NOT #59 COLLATE AAAAAA NOT IN 
    ( "AAAAAA" NOTNULL <= x'414141414141' IS NULL , ( ROUND ( 1.0 ) ) )}
} {1}
do_test fuzz2-2.3 {
  fuzzcatch {INSERT OR REPLACE INTO AAAAAA . "AAAAAA" ( "AAAAAA" ) SELECT DISTINCT * , ( SELECT #252 IN ( SELECT DISTINCT AAAAAA . * ) )}
} {1}
do_test fuzz2-2.4 {
  fuzzcatch {SELECT 1 LIMIT NOT #59 COLLATE AAAAAA NOT IN round(1.0)}
} {1}
do_test fuzz2-2.5 {
  fuzzcatch {SELECT( #239 )}
} {1}
do_test fuzz2-2.6 {
  fuzzcatch {DELETE FROM AAAAAA WHERE #65 NOT NULL}
} {1}
do_test fuzz2-2.7 {
  fuzzcatch {ATTACH ROUND( 1.0 ) in  AAAAAA . "AAAAAA" AS #122 ISNULL}
} {1}
do_test fuzz2-2.8 {
  fuzzcatch {SELECT 1 LIMIT  #122 ISNULL}
} {1}
do_test fuzz2-2.9 {
  fuzzcatch {CREATE VIEW AAAAAA . "AAAAAA" AS SELECT DISTINCT #162 IS NULL "AAAAAA"}
} {1}
do_test fuzz2-2.10 {
  fuzzcatch {DELETE FROM AAAAAA WHERE #202 IS NOT NULL ISNULL}
} {1}
do_test fuzz2-2.11 {
  fuzzcatch {UPDATE OR IGNORE "AAAAAA" . "AAAAAA" SET "AAAAAA" = NOT #96}
} {1}
do_test fuzz2-2.12 {
  fuzzcatch {SELECT - #196}
} {1}
do_test fuzz2-3.0 {
  fuzzcatch {CREATE TRIGGER "AAAAAA" . "AAAAAA" AFTER UPDATE OF "AAAAAA" , "AAAAAA" ON "AAAAAA" . "AAAAAA" FOR EACH ROW BEGIN UPDATE AAAAAA SET "AAAAAA" = #162;  END}
} {1}
do_test fuzz2-3.1 {
  fuzzcatch {CREATE TRIGGER IF NOT EXISTS "AAAAAA" UPDATE ON "AAAAAA" . AAAAAA FOR EACH ROW BEGIN DELETE FROM "AAAAAA" ; INSERT INTO AAAAAA ( "AAAAAA" ) SELECT DISTINCT "AAAAAA" "AAAAAA" , #167 AAAAAA , "AAAAAA" . * ORDER BY "AAAAAA" ASC , x'414141414141' BETWEEN RAISE ( FAIL , "AAAAAA" ) AND AAAAAA ( * ) NOT NULL DESC LIMIT AAAAAA ; REPLACE INTO AAAAAA ( AAAAAA ) VALUES ( AAAAAA ( * ) ) ; END}
} {1}
do_test fuzz2-3.2 {
  fuzzcatch {CREATE TEMP TRIGGER IF NOT EXISTS AAAAAA . "AAAAAA" BEFORE UPDATE OF "AAAAAA" ON AAAAAA . "AAAAAA" BEGIN SELECT ALL * , #175 "AAAAAA" FROM "AAAAAA" . AAAAAA;  END}
} {1}
do_test fuzz2-4.0 {
  fuzzcatch {ATTACH DATABASE #168 AS whatever}
} {1}
do_test fuzz2-4.1 {
  fuzzcatch {DETACH #133}
} {1}
do_test fuzz2-5.0 {
  fuzzcatch {SELECT 1 LIMIT ( SELECT DISTINCT * , AAAAAA , * , AAAAAA , "AAAAAA" . * FROM "AAAAAA" ON ROUND( 1 ) COLLATE AAAAAA OR "AAAAAA" USING ( AAAAAA , "AAAAAA" ) WHERE ROUND( 1 ) GROUP BY ORDER BY #84 ASC , #44 DESC , ( SELECT "AAAAAA" . * , "AAAAAA" . * FROM , ( ) "AAAAAA" USING ( )}
} {1}
do_test fuzz2-5.1 {
  fuzzcatch {SELECT 1 WHERE 1 == AAAAAA ( * ) BETWEEN + - ~ + "AAAAAA" . AAAAAA | RAISE ( IGNORE ) COLLATE AAAAAA NOT IN ( SELECT DISTINCT "AAAAAA" . * , * , * WHERE ( SELECT ALL AAAAAA AS "AAAAAA" HAVING CAST ( "AAAAAA" . "AAAAAA" . "AAAAAA" AS AAAAAA ) ORDER BY , , IS NULL ASC , ~ AND DESC LIMIT ( ( "AAAAAA" ) NOT BETWEEN ( ) NOT IN ( ) AND AAAAAA ( ) IS NOT NULL ) OFFSET AAAAAA ( ALL , , ) ) GROUP BY ORDER BY "AAAAAA" . AAAAAA ASC , NULL IN ( SELECT UNION ALL SELECT ALL WHERE HAVING ORDER BY LIMIT UNION SELECT DISTINCT FROM ( ) WHERE + HAVING >> ORDER BY LIMIT . . , "AAAAAA" ) , CAST ( ~ "AAAAAA" . AAAAAA AS "AAAAAA" AAAAAA "AAAAAA" ( + 4294967295 , - 4294967296.0 ) ) ASC LIMIT AAAAAA INTERSECT SELECT ALL * GROUP BY , AAAAAA ( DISTINCT , ) != #241 NOT IN ( , , ) , , CTIME_KW HAVING AAAAAA ORDER BY #103 DESC , #81 ASC LIMIT AAAAAA OFFSET ~ AAAAAA ( ALL AAAAAA . AAAAAA >= AAAAAA . "AAAAAA" . "AAAAAA" ) ) NOTNULL NOT NULL}
} {1}
do_test fuzz2-5.2 {
  fuzzcatch {SELECT 1 WHERE 1 == AAAAAA ( * ) BETWEEN + - ~ + "AAAAAA" . AAAAAA | RAISE ( IGNORE ) COLLATE AAAAAA NOT IN ( SELECT DISTINCT "AAAAAA" . * , * , * WHERE ( SELECT ALL AAAAAA AS "AAAAAA" HAVING CAST ( "AAAAAA" . "AAAAAA" . "AAAAAA" AS AAAAAA ) ORDER BY , , IS NULL ASC , ~ AND DESC LIMIT ( ( "AAAAAA" ) NOT BETWEEN ( ) NOT IN ( ) AND AAAAAA ( ) IS NOT NULL ) OFFSET AAAAAA ( ALL , , ) ) GROUP BY ORDER BY "AAAAAA" . AAAAAA ASC , NULL IN ( SELECT UNION ALL SELECT ALL WHERE HAVING ORDER BY LIMIT UNION SELECT DISTINCT FROM ( ) WHERE + HAVING >> ORDER BY LIMIT . . , "AAAAAA" ) , CAST ( ~ "AAAAAA" . AAAAAA AS "AAAAAA" AAAAAA "AAAAAA" ( + 4294967295 , - 4294967296.0 ) ) ASC LIMIT AAAAAA INTERSECT SELECT ALL * GROUP BY , AAAAAA ( DISTINCT , ) != #241 NOT IN ( , , ) , , CTIME_KW HAVING AAAAAA ORDER BY #103 DESC , #81 ASC LIMIT AAAAAA OFFSET ~ AAAAAA ( ALL AAAAAA . AAAAAA >= AAAAAA . "AAAAAA" . "AAAAAA" ) ) NOTNULL NOT NULL}
} {1}
do_test fuzz2-5.3 {
  fuzzcatch {UPDATE "AAAAAA" SET "AAAAAA" = - EXISTS ( SELECT DISTINCT * , * ORDER BY #202 ASC , #147 , ~ AAAAAA . "AAAAAA" ASC LIMIT AAAAAA . "AAAAAA" , RAISE ( ABORT , AAAAAA ) UNION ALL SELECT DISTINCT AAAAAA . * , * FROM ( SELECT DISTINCT}
} {1}
do_test fuzz2-5.4 {
  fuzzcatch {REPLACE INTO AAAAAA SELECT DISTINCT "AAAAAA" . * WHERE AAAAAA ( AAAAAA ( ) ) GROUP BY AAAAAA . AAAAAA . "AAAAAA" IN "AAAAAA" | AAAAAA ( ALL , ) ORDER BY #238, #92 DESC LIMIT 0 OFFSET - RAISE ( IGNORE ) NOT NULL > RAISE ( IGNORE ) IS NULL}
} {1}
do_test fuzz2-5.5 {
  fuzzcatch {SELECT ALL * GROUP BY EXISTS ( SELECT "AAAAAA" . * , AAAAAA ( * ) AS AAAAAA FROM "AAAAAA" . "AAAAAA" AS "AAAAAA" USING ( AAAAAA , "AAAAAA" , "AAAAAA" ) WHERE AAAAAA ( DISTINCT ) - RAISE ( FAIL , "AAAAAA" ) HAVING "AAAAAA" . "AAAAAA" . AAAAAA ORDER BY #182 , #55 ) BETWEEN EXISTS ( SELECT ALL * FROM ( ( }
} {1}

finish_test

Added test/fuzz3.test.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# 2007 May 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The focus
# of this file is checking the libraries response to subtly corrupting
# the database file by changing the values of pseudo-randomly selected
# bytes.
#
# $Id: fuzz3.test,v 1.3 2009/01/05 17:19:03 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


expr srand(123)

proc rstring {n} {
  set str s
  while {[string length $str] < $n} {
    append str [expr rand()]
  }
  return [string range $str 0 $n]
}

# Return a randomly generated SQL literal.
#
proc rvalue {} {
  switch -- [expr int(rand()*5)] {
    0 { # SQL NULL value.
      return NULL 
    }
    1 { # Integer value.
      return [expr int(rand()*1024)] 
    }
    2 { # Real value.
      return [expr rand()] 
    }
    3 { # String value.
      set n [expr int(rand()*2500)]
      return "'[rstring $n]'"
    }
    4 { # Blob value.
      set n [expr int(rand()*2500)]
      return "CAST('[rstring $n]' AS BLOB)"
    }
  }
}

proc db_checksum {} {
  set    cksum [execsql { SELECT md5sum(a, b, c) FROM t1 }]
  append cksum [execsql { SELECT md5sum(d, e, f) FROM t2 }]
  set cksum
}

# Modify a single byte in the file 'test.db' using tcl IO commands. The
# argument value, which must be an integer, determines both the offset of
# the byte that is modified, and the value that it is set to. The lower
# 8 bits of iMod determine the new byte value. The offset of the byte
# modified is the value of ($iMod >> 8).
#
# The return value is the iMod value required to restore the file
# to its original state. The command:
#
#   modify_database [modify_database $x]
#
# leaves the file in the same state as it was in at the start of the
# command (assuming that the file is at least ($x>>8) bytes in size).
#
proc modify_database {iMod} {
  set blob [binary format c [expr {$iMod&0xFF}]]
  set offset [expr {$iMod>>8}]

  set fd [open test.db r+]
  fconfigure $fd -encoding binary -translation binary
  seek $fd $offset
  set old_blob [read $fd 1]
  seek $fd $offset
  puts -nonewline $fd $blob
  close $fd

  binary scan $old_blob c iOld
  return [expr {($offset<<8) + ($iOld&0xFF)}]
}

proc purge_pcache {} {
  ifcapable !memorymanage {
    db close
    sqlite3 db test.db
  } else {
    sqlite3_release_memory 10000000
  }
  if {[lindex [pcache_stats] 1] != 0} {
    error "purge_pcache failed: [pcache_stats]"
  }
}

# This block creates a database to work with. 
#
do_test fuzz3-1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(d, e, f);
    CREATE INDEX i1 ON t1(a, b, c);
    CREATE INDEX i2 ON t2(d, e, f);
  }
  for {set i 0} {$i < 50} {incr i} {
    execsql "INSERT INTO t1 VALUES([rvalue], [rvalue], [rvalue])"
    execsql "INSERT INTO t2 VALUES([rvalue], [rvalue], [rvalue])"
  }
  execsql COMMIT
} {}

set ::cksum [db_checksum]
do_test fuzz3-2 {
  db_checksum
} $::cksum

for {set ii 0} {$ii < 5000} {incr ii} {
  purge_pcache

  # Randomly modify a single byte of the database file somewhere within
  # the first 100KB of the file.
  set iNew [expr int(rand()*5*1024*256)]
  set iOld [modify_database $iNew]

  set iTest 0
  foreach sql {
    {SELECT * FROM t2 ORDER BY d}      
    {SELECT * FROM t1}                 
    {SELECT * FROM t2}                 
    {SELECT * FROM t1 ORDER BY a}      
    {SELECT * FROM t1 WHERE a = (SELECT a FROM t1 WHERE rowid=25)} 
    {SELECT * FROM t2 WHERE d = (SELECT d FROM t2 WHERE rowid=1)}  
    {SELECT * FROM t2 WHERE d = (SELECT d FROM t2 WHERE rowid=50)} 
    {PRAGMA integrity_check}           
  } {
    do_test fuzz3-$ii.$iNew.[incr iTest] {
      foreach {rc msg} [catchsql $sql] {}
      if {$rc == 0 
       || $msg eq "database or disk is full"
       || $msg eq "database disk image is malformed"
       || $msg eq "file is encrypted or is not a database"
       || [string match "malformed database schema*" $msg]
      } {
        set msg ok
      }
      set msg
    } {ok}
  }

  # Restore the original database file content. Test that the correct 
  # checksum is now returned.
  #
  purge_pcache
  modify_database $iOld
  do_test fuzz3-$ii.$iNew.[incr iTest] {
    db_checksum
  } $::cksum
}

finish_test

Added test/fuzz_common.tcl.















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# 2007 May 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: fuzz_common.tcl,v 1.2 2009/01/05 19:36:30 drh Exp $

proc fuzz {TemplateList} {
  set n [llength $TemplateList]
  set i [expr {int(rand()*$n)}]
  set r [uplevel 1 subst -novar [list [lindex $TemplateList $i]]]

  string map {"\n" " "} $r
}

# Fuzzy generation primitives:
#
#     Literal
#     UnaryOp
#     BinaryOp
#     Expr
#     Table
#     Select
#     Insert
#

# Returns a string representing an SQL literal.
#
proc Literal {} {
  set TemplateList {
    456 0 -456 1 -1 
    2147483648 2147483647 2147483649 -2147483647 -2147483648 -2147483649
    'The' 'first' 'experiments' 'in' 'hardware' 'fault' 'injection'
    zeroblob(1000)
    NULL
    56.1 -56.1
    123456789.1234567899
  }
  fuzz $TemplateList
}

# Returns a string containing an SQL unary operator (e.g. "+" or "NOT").
#
proc UnaryOp {} {
  set TemplateList {+ - NOT ~}
  fuzz $TemplateList
}

# Returns a string containing an SQL binary operator (e.g. "*" or "/").
#
proc BinaryOp {} {
  set TemplateList {
    || * / % + - << >> & | < <= > >= = == != <> AND OR
    LIKE GLOB {NOT LIKE}
  }
  fuzz $TemplateList
}

# Return the complete text of an SQL expression.
#
set ::ExprDepth 0
proc Expr { {c {}} } {
  incr ::ExprDepth

  set TemplateList [concat $c $c $c {[Literal]}]
  if {$::ExprDepth < 3} {
    lappend TemplateList \
      {[Expr $c] [BinaryOp] [Expr $c]}                              \
      {[UnaryOp] [Expr $c]}                                         \
      {[Expr $c] ISNULL}                                            \
      {[Expr $c] NOTNULL}                                           \
      {CAST([Expr $c] AS blob)}                                     \
      {CAST([Expr $c] AS text)}                                     \
      {CAST([Expr $c] AS integer)}                                  \
      {CAST([Expr $c] AS real)}                                     \
      {abs([Expr])}                                                 \
      {coalesce([Expr], [Expr])}                                    \
      {hex([Expr])}                                                 \
      {length([Expr])}                                              \
      {lower([Expr])}                                               \
      {upper([Expr])}                                               \
      {quote([Expr])}                                               \
      {random()}                                                    \
      {randomblob(min(max([Expr],1), 500))}                         \
      {typeof([Expr])}                                              \
      {substr([Expr],[Expr],[Expr])}                                \
      {CASE WHEN [Expr $c] THEN [Expr $c] ELSE [Expr $c] END}       \
      {[Literal]} {[Literal]} {[Literal]}                           \
      {[Literal]} {[Literal]} {[Literal]}                           \
      {[Literal]} {[Literal]} {[Literal]}                           \
      {[Literal]} {[Literal]} {[Literal]}
  }
  if {$::SelectDepth < 4} {
    lappend TemplateList \
      {([Select 1])}                       \
      {[Expr $c] IN ([Select 1])}          \
      {[Expr $c] NOT IN ([Select 1])}      \
      {EXISTS ([Select 1])}                \
  } 
  set res [fuzz $TemplateList]
  incr ::ExprDepth -1
  return $res
}

# Return a valid table name.
#
set ::TableList [list]
proc Table {} {
  set TemplateList [concat sqlite_master $::TableList]
  fuzz $TemplateList
}

# Return one of:
#
#     "SELECT DISTINCT", "SELECT ALL" or "SELECT"
#
proc SelectKw {} {
  set TemplateList {
    "SELECT DISTINCT"
    "SELECT ALL"
    "SELECT"
  }
  fuzz $TemplateList
}

# Return a result set for a SELECT statement.
#
proc ResultSet {{nRes 0} {c ""}} {
  if {$nRes == 0} {
    set nRes [expr {rand()*2 + 1}]
  }

  set aRes [list]
  for {set ii 0} {$ii < $nRes} {incr ii} {
    lappend aRes [Expr $c]
  }

  join $aRes ", "
}

set ::SelectDepth 0
set ::ColumnList [list]
proc SimpleSelect {{nRes 0}} {

  set TemplateList {
      {[SelectKw] [ResultSet $nRes]}
  }

  # The ::SelectDepth variable contains the number of ancestor SELECT
  # statements (i.e. for a top level SELECT it is set to 0, for a
  # sub-select 1, for a sub-select of a sub-select 2 etc.).
  #
  # If this is already greater than 3, do not generate a complicated
  # SELECT statement. This tends to cause parser stack overflow (too
  # boring to bother with).
  #
  if {$::SelectDepth < 4} {
    lappend TemplateList \
        {[SelectKw] [ResultSet $nRes $::ColumnList] FROM ([Select])}     \
        {[SelectKw] [ResultSet $nRes] FROM ([Select])}                   \
        {[SelectKw] [ResultSet $nRes $::ColumnList] FROM [Table]}        \
        {
             [SelectKw] [ResultSet $nRes $::ColumnList] 
             FROM ([Select]) 
             GROUP BY [Expr]
             HAVING [Expr]
        }                                                                \

    if {0 == $nRes} {
      lappend TemplateList                                               \
          {[SelectKw] * FROM ([Select])}                                 \
          {[SelectKw] * FROM [Table]}                                    \
          {[SelectKw] * FROM [Table] WHERE [Expr $::ColumnList]}         \
          {
             [SelectKw] * 
             FROM [Table],[Table] AS t2 
             WHERE [Expr $::ColumnList] 
          } {
             [SelectKw] * 
             FROM [Table] LEFT OUTER JOIN [Table] AS t2 
             ON [Expr $::ColumnList]
             WHERE [Expr $::ColumnList] 
          }
    }
  } 

  fuzz $TemplateList
}

# Return a SELECT statement.
#
# If boolean parameter $isExpr is set to true, make sure the
# returned SELECT statement returns a single column of data.
#
proc Select {{nMulti 0}} {
  set TemplateList {
    {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} 
    {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} 
    {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} 
    {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} 
    {[SimpleSelect $nMulti] ORDER BY [Expr] DESC}
    {[SimpleSelect $nMulti] ORDER BY [Expr] ASC}
    {[SimpleSelect $nMulti] ORDER BY [Expr] ASC, [Expr] DESC}
    {[SimpleSelect $nMulti] ORDER BY [Expr] LIMIT [Expr] OFFSET [Expr]}
  }

  if {$::SelectDepth < 4} {
    if {$nMulti == 0} {
      set nMulti [expr {(rand()*2)+1}]
    }
    lappend TemplateList                                             \
        {[SimpleSelect $nMulti] UNION     [Select $nMulti]}          \
        {[SimpleSelect $nMulti] UNION ALL [Select $nMulti]}          \
        {[SimpleSelect $nMulti] EXCEPT    [Select $nMulti]}          \
        {[SimpleSelect $nMulti] INTERSECT [Select $nMulti]}
  }

  incr ::SelectDepth
  set res [fuzz $TemplateList]
  incr ::SelectDepth -1
  set res
}

# Generate and return a fuzzy INSERT statement.
#
proc Insert {} {
  set TemplateList {
      {INSERT INTO [Table] VALUES([Expr], [Expr], [Expr]);}
      {INSERT INTO [Table] VALUES([Expr], [Expr], [Expr], [Expr]);}
      {INSERT INTO [Table] VALUES([Expr], [Expr]);}
  }
  fuzz $TemplateList
}

proc Column {} {
  fuzz $::ColumnList
}

# Generate and return a fuzzy UPDATE statement.
#
proc Update {} {
  set TemplateList {
    {UPDATE [Table] 
     SET [Column] = [Expr $::ColumnList] 
     WHERE [Expr $::ColumnList]}
  }
  fuzz $TemplateList
}

proc Delete {} {
  set TemplateList {
    {DELETE FROM [Table] WHERE [Expr $::ColumnList]}
  }
  fuzz $TemplateList
}

proc Statement {} {
  set TemplateList {
    {[Update]}
    {[Insert]}
    {[Select]}
    {[Delete]}
  }
  fuzz $TemplateList
}

# Return an identifier. This just chooses randomly from a fixed set
# of strings.
proc Identifier {} {
  set TemplateList {
    This just chooses randomly a fixed 
    We would also thank the developers 
    for their analysis Samba
  }
  fuzz $TemplateList
}

proc Check {} {
  # Use a large value for $::SelectDepth, because sub-selects are
  # not allowed in expressions used by CHECK constraints.
  #
  set sd $::SelectDepth 
  set ::SelectDepth 500
  set TemplateList {
    {}
    {CHECK ([Expr])}
  }
  set res [fuzz $TemplateList]
  set ::SelectDepth $sd
  set res
}

proc Coltype {} {
  set TemplateList {
    {INTEGER PRIMARY KEY}
    {VARCHAR [Check]}
    {PRIMARY KEY}
  }
  fuzz $TemplateList
}

proc DropTable {} {
  set TemplateList {
    {DROP TABLE IF EXISTS [Identifier]}
  }
  fuzz $TemplateList
}

proc CreateView {} {
  set TemplateList {
    {CREATE VIEW [Identifier] AS [Select]}
  }
  fuzz $TemplateList
}
proc DropView {} {
  set TemplateList {
    {DROP VIEW IF EXISTS [Identifier]}
  }
  fuzz $TemplateList
}

proc CreateTable {} {
  set TemplateList {
    {CREATE TABLE [Identifier]([Identifier] [Coltype], [Identifier] [Coltype])}
    {CREATE TEMP TABLE [Identifier]([Identifier] [Coltype])}
  }
  fuzz $TemplateList
}

proc CreateOrDropTableOrView {} {
  set TemplateList {
    {[CreateTable]}
    {[DropTable]}
    {[CreateView]}
    {[DropView]}
  }
  fuzz $TemplateList
}

########################################################################

set ::log [open fuzzy.log w]

#
# Usage: do_fuzzy_test <testname> ?<options>?
# 
#     -template
#     -errorlist
#     -repeats
#     
proc do_fuzzy_test {testname args} {
  set ::fuzzyopts(-errorlist) [list]
  set ::fuzzyopts(-repeats) $::REPEATS
  array set ::fuzzyopts $args

  lappend ::fuzzyopts(-errorlist) {parser stack overflow} 
  lappend ::fuzzyopts(-errorlist) {ORDER BY}
  lappend ::fuzzyopts(-errorlist) {GROUP BY}
  lappend ::fuzzyopts(-errorlist) {datatype mismatch}

  for {set ii 0} {$ii < $::fuzzyopts(-repeats)} {incr ii} {
    do_test ${testname}.$ii {
      set ::sql [subst $::fuzzyopts(-template)]
      puts $::log $::sql
      flush $::log
      set rc [catch {execsql $::sql} msg]
      set e 1
      if {$rc} {
        set e 0
        foreach error $::fuzzyopts(-errorlist) {
          if {[string first $error $msg]>=0} {
            set e 1
            break
          }
        }
      }
      if {$e == 0} {
        puts ""
        puts $::sql
        puts $msg
      }
      set e
    } {1}
  }
}

Added test/fuzz_malloc.test.





























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#
# 2007 May 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests malloc failures in concert with fuzzy SQL generation.
#
# $Id: fuzz_malloc.test,v 1.10 2008/08/20 16:35:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !memdebug {
  finish_test
  return
}

source $testdir/malloc_common.tcl
source $testdir/fuzz_common.tcl

if {[info exists ISQUICK]} {
  set ::REPEATS 20
} elseif {[info exists SOAKTEST]} {
  set ::REPEATS 100
} else {
  set ::REPEATS 40
}

#
# Usage: do_fuzzy_malloc_test <testname> ?<options>?
# 
#     -template
#     -sqlprep
#     -repeats
#     
proc do_fuzzy_malloc_test {testname args} {
  set ::fuzzyopts(-repeats) $::REPEATS
  set ::fuzzyopts(-sqlprep) {}
  array set ::fuzzyopts $args

  sqlite3_memdebug_fail -1
  db close
  file delete test.db test.db-journal
  sqlite3 db test.db
  set ::prep $::fuzzyopts(-sqlprep)
  execsql $::prep
  set jj 0
  for {set ii 0} {$ii < $::fuzzyopts(-repeats)} {incr ii} {
    expr srand($jj)
    incr jj
    set ::sql [subst $::fuzzyopts(-template)]
    # puts fuzyy-sql=\[$::sql\]; flush stdout
    foreach {rc res} [catchsql "$::sql"] {}
    if {$rc==0} {
      do_malloc_test $testname-$ii -sqlbody $::sql -sqlprep $::prep
    } else {
      incr ii -1
    }
  }
}

#----------------------------------------------------------------
# Test malloc failure during parsing (and execution) of a fuzzily 
# generated expressions.
#
do_fuzzy_malloc_test fuzzy_malloc-1 -template {Select [Expr]}
do_fuzzy_malloc_test fuzzy_malloc-2 -template {[Select]}

set ::SQLPREP {
  BEGIN;
    CREATE TABLE abc(a, b, c);
    CREATE TABLE def(a, b, c);
    CREATE TABLE ghi(a, b, c);
    INSERT INTO abc VALUES(1.5, 3, 'a short string');
    INSERT INTO def VALUES(NULL, X'ABCDEF', 
        'a longer string. Long enough that it doesn''t fit in Mem.zShort');
    INSERT INTO ghi VALUES(zeroblob(1000), 'hello world', -1257900987654321);
  COMMIT;
}
set ::TableList  [list abc def ghi]
set ::ColumnList [list a b c]

do_fuzzy_malloc_test fuzzy_malloc-3 \
  -template {[Select]}              \
  -sqlprep $::SQLPREP

finish_test

Added test/hook.test.



































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# 2004 Jan 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for TCL interface to the
# SQLite library. 
#
# The focus of the tests in this file is the  following interface:
#
#      sqlite_commit_hook    (tests hook-1..hook-3 inclusive)
#      sqlite_update_hook    (tests hook-4-*)
#      sqlite_rollback_hook  (tests hook-5.*)
#
# $Id: hook.test,v 1.15 2009/04/07 14:14:23 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test hook-1.2 {
  db commit_hook
} {}


do_test hook-3.1 {
  set commit_cnt 0
  proc commit_hook {} {
    incr ::commit_cnt
    return 0
  }
  db commit_hook ::commit_hook
  db commit_hook
} {::commit_hook}
do_test hook-3.2 {
  set commit_cnt
} {0}
do_test hook-3.3 {
  execsql {
    CREATE TABLE t2(a,b);
  }
  set commit_cnt
} {1}
do_test hook-3.4 {
  execsql {
    INSERT INTO t2 VALUES(1,2);
    INSERT INTO t2 SELECT a+1, b+1 FROM t2;
    INSERT INTO t2 SELECT a+2, b+2 FROM t2;
  }
  set commit_cnt
} {4}
do_test hook-3.5 {
  set commit_cnt {}
  proc commit_hook {} {
    set ::commit_cnt [execsql {SELECT * FROM t2}]
    return 0
  }
  execsql {
    INSERT INTO t2 VALUES(5,6);
  }
  set commit_cnt
} {1 2 2 3 3 4 4 5 5 6}
do_test hook-3.6 {
  set commit_cnt {}
  proc commit_hook {} {
    set ::commit_cnt [execsql {SELECT * FROM t2}] 
    return 1
  }
  catchsql {
    INSERT INTO t2 VALUES(6,7);
  }
} {1 {constraint failed}}
do_test hook-3.7 {
  set ::commit_cnt
} {1 2 2 3 3 4 4 5 5 6 6 7}
do_test hook-3.8 {
  execsql {SELECT * FROM t2}
} {1 2 2 3 3 4 4 5 5 6}

# Test turnning off the commit hook
#
do_test hook-3.9 {
  db commit_hook {}
  set ::commit_cnt {}
  execsql {
    INSERT INTO t2 VALUES(7,8);
  }
  set ::commit_cnt
} {}

# Ticket #3564.
#
do_test hook-3.10 {
  file delete -force test2.db test2.db-journal
  sqlite3 db2 test2.db
  proc commit_hook {} {
    set y [db2 one {SELECT y FROM t3 WHERE y>10}]
    return [expr {$y>10}]
  }
  db2 eval {CREATE TABLE t3(x,y)}
  db2 commit_hook commit_hook
  catchsql {INSERT INTO t3 VALUES(1,2)} db2
  catchsql {INSERT INTO t3 VALUES(11,12)} db2
  catchsql {INSERT INTO t3 VALUES(3,4)} db2
  db2 eval {
    SELECT * FROM t3 ORDER BY x;
  }
} {1 2 3 4}
db2 close


#----------------------------------------------------------------------------
# Tests for the update-hook.
#
# 4.1.* - Very simple tests. Test that the update hook is invoked correctly 
#         for INSERT, DELETE and UPDATE statements, including DELETE 
#         statements with no WHERE clause.
# 4.2.* - Check that the update-hook is invoked for rows modified by trigger
#         bodies. Also that the database name is correctly reported when 
#         an attached database is modified.
# 4.3.* - Do some sorting, grouping, compound queries, population and 
#         depopulation of indices, to make sure the update-hook is not 
#         invoked incorrectly.
#

# Simple tests
do_test hook-4.1.1 {
  catchsql {
    DROP TABLE t1;
  }
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
    INSERT INTO t1 VALUES(3, 'three');
  }
  db update_hook [list lappend ::update_hook]
} {}
do_test hook-4.1.2 {
  execsql {
    INSERT INTO t1 VALUES(4, 'four');
    DELETE FROM t1 WHERE b = 'two';
    UPDATE t1 SET b = '' WHERE a = 1 OR a = 3;
    DELETE FROM t1 WHERE 1; -- Avoid the truncate optimization (for now)
  }
  set ::update_hook
} [list \
    INSERT main t1 4 \
    DELETE main t1 2 \
    UPDATE main t1 1 \
    UPDATE main t1 3 \
    DELETE main t1 1 \
    DELETE main t1 3 \
    DELETE main t1 4 \
]

ifcapable trigger {
  # Update hook is not invoked for changes to sqlite_master
  #
  do_test hook-4.1.3 {
    set ::update_hook {}
    execsql {
      CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN SELECT RAISE(IGNORE); END;
    }
    set ::update_hook
  } {}
  do_test hook-4.1.4 {
    set ::update_hook {}
    execsql {
      DROP TRIGGER r1;
    }
    set ::update_hook
  } {}
  
  set ::update_hook {}
  do_test hook-4.2.1 {
    catchsql {
      DROP TABLE t2;
    }
    execsql {
      CREATE TABLE t2(c INTEGER PRIMARY KEY, d);
      CREATE TRIGGER t1_trigger AFTER INSERT ON t1 BEGIN
        INSERT INTO t2 VALUES(new.a, new.b);
        UPDATE t2 SET d = d || ' via trigger' WHERE new.a = c;
        DELETE FROM t2 WHERE new.a = c;
      END;
    }
  } {}
  do_test hook-4.2.2 {
    execsql {
      INSERT INTO t1 VALUES(1, 'one');
      INSERT INTO t1 VALUES(2, 'two');
    }
    set ::update_hook
  } [list \
      INSERT main t1 1 \
      INSERT main t2 1 \
      UPDATE main t2 1 \
      DELETE main t2 1 \
      INSERT main t1 2 \
      INSERT main t2 2 \
      UPDATE main t2 2 \
      DELETE main t2 2 \
  ]
} else {
  execsql {
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
  }
}

# Update-hook + ATTACH
set ::update_hook {}
ifcapable attach {
  do_test hook-4.2.3 {
    file delete -force test2.db
    execsql {
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.t3(a INTEGER PRIMARY KEY, b);
      INSERT INTO aux.t3 SELECT * FROM t1;
      UPDATE t3 SET b = 'two or so' WHERE a = 2;
      DELETE FROM t3 WHERE 1; -- Avoid the truncate optimization (for now)
    }
    set ::update_hook
  } [list \
      INSERT aux t3 1 \
      INSERT aux t3 2 \
      UPDATE aux t3 2 \
      DELETE aux t3 1 \
      DELETE aux t3 2 \
  ]
}

ifcapable trigger {
  execsql {
    DROP TRIGGER t1_trigger;
  }
}

# Test that other vdbe operations involving btree structures do not 
# incorrectly invoke the update-hook.
set ::update_hook {}
do_test hook-4.3.1 {
  execsql {
    CREATE INDEX t1_i ON t1(b);
    INSERT INTO t1 VALUES(3, 'three');
    UPDATE t1 SET b = '';
    DELETE FROM t1 WHERE a > 1;
  }
  set ::update_hook
} [list \
    INSERT main t1 3 \
    UPDATE main t1 1 \
    UPDATE main t1 2 \
    UPDATE main t1 3 \
    DELETE main t1 2 \
    DELETE main t1 3 \
]
set ::update_hook {}
ifcapable compound&&attach {
  do_test hook-4.3.2 {
    execsql {
      SELECT * FROM t1 UNION SELECT * FROM t3;
      SELECT * FROM t1 UNION ALL SELECT * FROM t3;
      SELECT * FROM t1 INTERSECT SELECT * FROM t3;
      SELECT * FROM t1 EXCEPT SELECT * FROM t3;
      SELECT * FROM t1 ORDER BY b;
      SELECT * FROM t1 GROUP BY b;
    }
    set ::update_hook
  } [list]
}
db update_hook {}
#
#----------------------------------------------------------------------------

#----------------------------------------------------------------------------
# Test the rollback-hook. The rollback-hook is a bit more complicated than
# either the commit or update hooks because a rollback can happen 
# explicitly (an sql ROLLBACK statement) or implicitly (a constraint or 
# error condition).
#
# hook-5.1.* - Test explicit rollbacks.
# hook-5.2.* - Test implicit rollbacks caused by constraint failure.
#
# hook-5.3.* - Test implicit rollbacks caused by IO errors.
# hook-5.4.* - Test implicit rollbacks caused by malloc() failure.
# hook-5.5.* - Test hot-journal rollbacks. Or should the rollback hook 
#              not be called for these?
#

do_test hook-5.0 {
  # Configure the rollback hook to increment global variable 
  # $::rollback_hook each time it is invoked.
  set ::rollback_hook 0
  db rollback_hook [list incr ::rollback_hook]
} {}

# Test explicit rollbacks. Not much can really go wrong here.
#
do_test hook-5.1.1 {
  set ::rollback_hook 0
  execsql {
    BEGIN;
    ROLLBACK;
  }
  set ::rollback_hook
} {1}

# Test implicit rollbacks caused by constraints.
#
do_test hook-5.2.1 {
  set ::rollback_hook 0
  catchsql {
    DROP TABLE t1;
    CREATE TABLE t1(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES('one', 'I');
    INSERT INTO t1 VALUES('one', 'I');
  }
  set ::rollback_hook
} {1}
do_test hook-5.2.2 {
  # Check that the INSERT transaction above really was rolled back.
  execsql {
    SELECT count(*) FROM t1;
  }
} {1}

#
# End rollback-hook testing.
#----------------------------------------------------------------------------

finish_test

Added test/icu.test.











































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# 2007 May 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: icu.test,v 1.2 2008/07/12 14:52:20 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !icu {
  finish_test
  return
}

# Create a table to work with.
#
execsql {CREATE TABLE test1(i1 int, i2 int, r1 real, r2 real, t1 text, t2 text)}
execsql {INSERT INTO test1 VALUES(1,2,1.1,2.2,'hello','world')}
proc test_expr {name settings expr result} {
  do_test $name [format {
    lindex [db eval {
      BEGIN; 
      UPDATE test1 SET %s; 
      SELECT %s FROM test1; 
      ROLLBACK;
    }] 0
  } $settings $expr] $result
}

# Tests of the REGEXP operator.
#
test_expr icu-1.1 {i1='hello'} {i1 REGEXP 'hello'}  1
test_expr icu-1.2 {i1='hello'} {i1 REGEXP '.ello'}  1
test_expr icu-1.3 {i1='hello'} {i1 REGEXP '.ell'}   0
test_expr icu-1.4 {i1='hello'} {i1 REGEXP '.ell.*'} 1
test_expr icu-1.5 {i1=NULL}    {i1 REGEXP '.ell.*'} {}

# Some non-ascii characters with defined case mappings
#
set ::EGRAVE "\xC8"
set ::egrave "\xE8"

set ::OGRAVE "\xD2"
set ::ograve "\xF2"

# That German letter that looks a bit like a B. The
# upper-case version of which is "SS" (two characters).
#
set ::szlig "\xDF" 

# Tests of the upper()/lower() functions.
#
test_expr icu-2.1 {i1='HellO WorlD'} {upper(i1)} {HELLO WORLD}
test_expr icu-2.2 {i1='HellO WorlD'} {lower(i1)} {hello world}
test_expr icu-2.3 {i1=$::egrave} {lower(i1)}     $::egrave
test_expr icu-2.4 {i1=$::egrave} {upper(i1)}     $::EGRAVE
test_expr icu-2.5 {i1=$::ograve} {lower(i1)}     $::ograve
test_expr icu-2.6 {i1=$::ograve} {upper(i1)}     $::OGRAVE
test_expr icu-2.3 {i1=$::EGRAVE} {lower(i1)}     $::egrave
test_expr icu-2.4 {i1=$::EGRAVE} {upper(i1)}     $::EGRAVE
test_expr icu-2.5 {i1=$::OGRAVE} {lower(i1)}     $::ograve
test_expr icu-2.6 {i1=$::OGRAVE} {upper(i1)}     $::OGRAVE

test_expr icu-2.7 {i1=$::szlig} {upper(i1)}      "SS"
test_expr icu-2.8 {i1='SS'} {lower(i1)}          "ss"

# In turkish (locale="tr_TR"), the lower case version of I
# is "small dotless i" (code point 0x131 (decimal 305)).
#
set ::small_dotless_i "\u0131"
test_expr icu-3.1 {i1='I'} {lower(i1)}           "i"
test_expr icu-3.2 {i1='I'} {lower(i1, 'tr_tr')}  $::small_dotless_i
test_expr icu-3.3 {i1='I'} {lower(i1, 'en_AU')}  "i"

#--------------------------------------------------------------------
# Test the collation sequence function.
#
do_test icu-4.1 {
  execsql {
    CREATE TABLE fruit(name);
    INSERT INTO fruit VALUES('plum');
    INSERT INTO fruit VALUES('cherry');
    INSERT INTO fruit VALUES('apricot');
    INSERT INTO fruit VALUES('peach');
    INSERT INTO fruit VALUES('chokecherry');
    INSERT INTO fruit VALUES('yamot');
  }
} {}
do_test icu-4.2 {
  execsql {
    SELECT icu_load_collation('en_US', 'AmericanEnglish');
    SELECT icu_load_collation('lt_LT', 'Lithuanian');
  }
  execsql {
    SELECT name FROM fruit ORDER BY name COLLATE AmericanEnglish ASC;
  }
} {apricot cherry chokecherry peach plum yamot}


# Test collation using Lithuanian rules. In the Lithuanian
# alphabet, "y" comes right after "i".
#
do_test icu-4.3 {
  execsql {
    SELECT name FROM fruit ORDER BY name COLLATE Lithuanian ASC;
  }
} {apricot cherry chokecherry yamot peach plum}

finish_test

Added test/in.test.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the IN and BETWEEN operator.
#
# $Id: in.test,v 1.22 2008/08/04 03:51:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Generate the test data we will need for the first squences of tests.
#
do_test in-1.0 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a int, b int);
  }
  for {set i 1} {$i<=10} {incr i} {
    execsql "INSERT INTO t1 VALUES($i,[expr {1<<$i}])"
  }
  execsql {
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {10}

# Do basic testing of BETWEEN.
#
do_test in-1.1 {
  execsql {SELECT a FROM t1 WHERE b BETWEEN 10 AND 50 ORDER BY a}
} {4 5}
do_test in-1.2 {
  execsql {SELECT a FROM t1 WHERE b NOT BETWEEN 10 AND 50 ORDER BY a}
} {1 2 3 6 7 8 9 10}
do_test in-1.3 {
  execsql {SELECT a FROM t1 WHERE b BETWEEN a AND a*5 ORDER BY a}
} {1 2 3 4}
do_test in-1.4 {
  execsql {SELECT a FROM t1 WHERE b NOT BETWEEN a AND a*5 ORDER BY a}
} {5 6 7 8 9 10}
do_test in-1.6 {
  execsql {SELECT a FROM t1 WHERE b BETWEEN a AND a*5 OR b=512 ORDER BY a}
} {1 2 3 4 9}
do_test in-1.7 {
  execsql {SELECT a+ 100*(a BETWEEN 1 and 3) FROM t1 ORDER BY b}
} {101 102 103 4 5 6 7 8 9 10}

# The rest of this file concentrates on testing the IN operator.
# Skip this if the library is compiled with SQLITE_OMIT_SUBQUERY 
# (because the IN operator is unavailable).
#
ifcapable !subquery {
  finish_test
  return
}

# Testing of the IN operator using static lists on the right-hand side.
#
do_test in-2.1 {
  execsql {SELECT a FROM t1 WHERE b IN (8,12,16,24,32) ORDER BY a}
} {3 4 5}
do_test in-2.2 {
  execsql {SELECT a FROM t1 WHERE b NOT IN (8,12,16,24,32) ORDER BY a}
} {1 2 6 7 8 9 10}
do_test in-2.3 {
  execsql {SELECT a FROM t1 WHERE b IN (8,12,16,24,32) OR b=512 ORDER BY a}
} {3 4 5 9}
do_test in-2.4 {
  execsql {SELECT a FROM t1 WHERE b NOT IN (8,12,16,24,32) OR b=512 ORDER BY a}
} {1 2 6 7 8 9 10}
do_test in-2.5 {
  execsql {SELECT a+100*(b IN (8,16,24)) FROM t1 ORDER BY b}
} {1 2 103 104 5 6 7 8 9 10}

do_test in-2.6 {
  execsql {SELECT a FROM t1 WHERE b IN (b+8,64)}
} {6}
do_test in-2.7 {
  execsql {SELECT a FROM t1 WHERE b IN (max(5,10,b),20)}
} {4 5 6 7 8 9 10}
do_test in-2.8 {
  execsql {SELECT a FROM t1 WHERE b IN (8*2,64/2) ORDER BY b}
} {4 5}
do_test in-2.9 {
  execsql {SELECT a FROM t1 WHERE b IN (max(5,10),20)}
} {}
do_test in-2.10 {
  execsql {SELECT a FROM t1 WHERE min(0,b IN (a,30))}
} {}
do_test in-2.11 {
  set v [catch {execsql {SELECT a FROM t1 WHERE c IN (10,20)}} msg]
  lappend v $msg
} {1 {no such column: c}}

# Testing the IN operator where the right-hand side is a SELECT
#
do_test in-3.1 {
  execsql {
    SELECT a FROM t1
    WHERE b IN (SELECT b FROM t1 WHERE a<5)
    ORDER BY a
  }
} {1 2 3 4}
do_test in-3.2 {
  execsql {
    SELECT a FROM t1
    WHERE b IN (SELECT b FROM t1 WHERE a<5) OR b==512
    ORDER BY a
  }
} {1 2 3 4 9}
do_test in-3.3 {
  execsql {
    SELECT a + 100*(b IN (SELECT b FROM t1 WHERE a<5)) FROM t1 ORDER BY b
  }
} {101 102 103 104 5 6 7 8 9 10}

# Make sure the UPDATE and DELETE commands work with IN-SELECT
#
do_test in-4.1 {
  execsql {
    UPDATE t1 SET b=b*2 
    WHERE b IN (SELECT b FROM t1 WHERE a>8)
  }
  execsql {SELECT b FROM t1 ORDER BY b}
} {2 4 8 16 32 64 128 256 1024 2048}
do_test in-4.2 {
  execsql {
    DELETE FROM t1 WHERE b IN (SELECT b FROM t1 WHERE a>8)
  }
  execsql {SELECT a FROM t1 ORDER BY a}
} {1 2 3 4 5 6 7 8}
do_test in-4.3 {
  execsql {
    DELETE FROM t1 WHERE b NOT IN (SELECT b FROM t1 WHERE a>4)
  }
  execsql {SELECT a FROM t1 ORDER BY a}
} {5 6 7 8}

# Do an IN with a constant RHS but where the RHS has many, many
# elements.  We need to test that collisions in the hash table
# are resolved properly.
#
do_test in-5.1 {
  execsql {
    INSERT INTO t1 VALUES('hello', 'world');
    SELECT * FROM t1
    WHERE a IN (
       'Do','an','IN','with','a','constant','RHS','but','where','the',
       'has','many','elements','We','need','to','test','that',
       'collisions','hash','table','are','resolved','properly',
       'This','in-set','contains','thirty','one','entries','hello');
  }
} {hello world}

# Make sure the IN operator works with INTEGER PRIMARY KEY fields.
#
do_test in-6.1 {
  execsql {
    CREATE TABLE ta(a INTEGER PRIMARY KEY, b);
    INSERT INTO ta VALUES(1,1);
    INSERT INTO ta VALUES(2,2);
    INSERT INTO ta VALUES(3,3);
    INSERT INTO ta VALUES(4,4);
    INSERT INTO ta VALUES(6,6);
    INSERT INTO ta VALUES(8,8);
    INSERT INTO ta VALUES(10,
       'This is a key that is long enough to require a malloc in the VDBE');
    SELECT * FROM ta WHERE a<10;
  }
} {1 1 2 2 3 3 4 4 6 6 8 8}
do_test in-6.2 {
  execsql {
    CREATE TABLE tb(a INTEGER PRIMARY KEY, b);
    INSERT INTO tb VALUES(1,1);
    INSERT INTO tb VALUES(2,2);
    INSERT INTO tb VALUES(3,3);
    INSERT INTO tb VALUES(5,5);
    INSERT INTO tb VALUES(7,7);
    INSERT INTO tb VALUES(9,9);
    INSERT INTO tb VALUES(11,
       'This is a key that is long enough to require a malloc in the VDBE');
    SELECT * FROM tb WHERE a<10;
  }
} {1 1 2 2 3 3 5 5 7 7 9 9}
do_test in-6.3 {
  execsql {
    SELECT a FROM ta WHERE b IN (SELECT a FROM tb);
  }
} {1 2 3}
do_test in-6.4 {
  execsql {
    SELECT a FROM ta WHERE b NOT IN (SELECT a FROM tb);
  }
} {4 6 8 10}
do_test in-6.5 {
  execsql {
    SELECT a FROM ta WHERE b IN (SELECT b FROM tb);
  }
} {1 2 3 10}
do_test in-6.6 {
  execsql {
    SELECT a FROM ta WHERE b NOT IN (SELECT b FROM tb);
  }
} {4 6 8}
do_test in-6.7 {
  execsql {
    SELECT a FROM ta WHERE a IN (SELECT a FROM tb);
  }
} {1 2 3}
do_test in-6.8 {
  execsql {
    SELECT a FROM ta WHERE a NOT IN (SELECT a FROM tb);
  }
} {4 6 8 10}
do_test in-6.9 {
  execsql {
    SELECT a FROM ta WHERE a IN (SELECT b FROM tb);
  }
} {1 2 3}
do_test in-6.10 {
  execsql {
    SELECT a FROM ta WHERE a NOT IN (SELECT b FROM tb);
  }
} {4 6 8 10}

# Tests of IN operator against empty sets.  (Ticket #185)
#
do_test in-7.1 {
  execsql {
    SELECT a FROM t1 WHERE a IN ();
  }
} {}
do_test in-7.2 {
  execsql {
    SELECT a FROM t1 WHERE a IN (5);
  }
} {5}
do_test in-7.3 {
  execsql {
    SELECT a FROM t1 WHERE a NOT IN () ORDER BY a;
  }
} {5 6 7 8 hello}
do_test in-7.4 {
  execsql {
    SELECT a FROM t1 WHERE a IN (5) AND b IN ();
  }
} {}
do_test in-7.5 {
  execsql {
    SELECT a FROM t1 WHERE a IN (5) AND b NOT IN ();
  }
} {5}
do_test in-7.6 {
  execsql {
    SELECT a FROM ta WHERE a IN ();
  }
} {}
do_test in-7.7 {
  execsql {
    SELECT a FROM ta WHERE a NOT IN ();
  }
} {1 2 3 4 6 8 10}

do_test in-8.1 {
  execsql {
    SELECT b FROM t1 WHERE a IN ('hello','there')
  }
} {world}
do_test in-8.2 {
  execsql {
    SELECT b FROM t1 WHERE a IN ("hello",'there')
  }
} {world}

# Test constructs of the form:  expr IN tablename
#
do_test in-9.1 {
  execsql {
    CREATE TABLE t4 AS SELECT a FROM tb;
    SELECT * FROM t4;    
  }
} {1 2 3 5 7 9 11}
do_test in-9.2 {
  execsql {
    SELECT b FROM t1 WHERE a IN t4;
  }
} {32 128}
do_test in-9.3 {
  execsql {
    SELECT b FROM t1 WHERE a NOT IN t4;
  }
} {64 256 world}
do_test in-9.4 {
  catchsql {
    SELECT b FROM t1 WHERE a NOT IN tb;
  }
} {1 {only a single result allowed for a SELECT that is part of an expression}}

# IN clauses in CHECK constraints.  Ticket #1645
#
do_test in-10.1 {
  execsql {
    CREATE TABLE t5(
      a INTEGER,
      CHECK( a IN (111,222,333) )
    );
    INSERT INTO t5 VALUES(111);
    SELECT * FROM t5;
  }
} {111}
do_test in-10.2 {
  catchsql {
    INSERT INTO t5 VALUES(4);
  }
} {1 {constraint failed}}

# Ticket #1821
#
# Type affinity applied to the right-hand side of an IN operator.
#
do_test in-11.1 {
  execsql {
    CREATE TABLE t6(a,b NUMERIC);
    INSERT INTO t6 VALUES(1,2);
    INSERT INTO t6 VALUES(2,3);
    SELECT * FROM t6 WHERE b IN (2);
  }
} {1 2}
do_test in-11.2 {
  # The '2' should be coerced into 2 because t6.b is NUMERIC
  execsql {
    SELECT * FROM t6 WHERE b IN ('2');
  }
} {1 2}
do_test in-11.3 {
  # No coercion should occur here because of the unary + before b.
  execsql {
    SELECT * FROM t6 WHERE +b IN ('2');
  }
} {}
do_test in-11.4 {
  # No coercion because column a as affinity NONE
  execsql {
    SELECT * FROM t6 WHERE a IN ('2');
  }
} {}
do_test in-11.5 {
  execsql {
    SELECT * FROM t6 WHERE a IN (2);
  }
} {2 3}
do_test in-11.6 {
  # No coercion because column a as affinity NONE
  execsql {
    SELECT * FROM t6 WHERE +a IN ('2');
  }
} {}

# Test error conditions with expressions of the form IN(<compound select>).
#
ifcapable compound {
do_test in-12.1 {
  execsql {
    CREATE TABLE t2(a, b, c);
    CREATE TABLE t3(a, b, c);
  }
} {}
do_test in-12.2 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a, b FROM t3 UNION ALL SELECT a, b FROM t2
    );
  }
} {1 {only a single result allowed for a SELECT that is part of an expression}}
do_test in-12.3 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a, b FROM t3 UNION SELECT a, b FROM t2
    );
  }
} {1 {only a single result allowed for a SELECT that is part of an expression}}
do_test in-12.4 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a, b FROM t3 EXCEPT SELECT a, b FROM t2
    );
  }
} {1 {only a single result allowed for a SELECT that is part of an expression}}
do_test in-12.5 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a, b FROM t3 INTERSECT SELECT a, b FROM t2
    );
  }
} {1 {only a single result allowed for a SELECT that is part of an expression}}
do_test in-12.6 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a FROM t3 UNION ALL SELECT a, b FROM t2
    );
  }
} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}}
do_test in-12.7 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a FROM t3 UNION SELECT a, b FROM t2
    );
  }
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}
do_test in-12.8 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a FROM t3 EXCEPT SELECT a, b FROM t2
    );
  }
} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}}
do_test in-12.9 {
  catchsql {
    SELECT * FROM t2 WHERE a IN (
      SELECT a FROM t3 INTERSECT SELECT a, b FROM t2
    );
  }
} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}}
}


#------------------------------------------------------------------------
# The following tests check that NULL is handled correctly when it 
# appears as part of a set of values on the right-hand side of an
# IN or NOT IN operator.
#
# When it appears in such a set, NULL is handled as an "unknown value".
# If, because of the unknown value in the set, the result of the expression 
# cannot be determined, then it itself evaluates to NULL.
#

# Warm body test to demonstrate the principles being tested:
#
do_test in-13.1 {
  db nullvalue "null"
  execsql { SELECT 
    1 IN (NULL, 1, 2),     -- The value 1 is a member of the set, return true.
    3 IN (NULL, 1, 2),     -- Ambiguous, return NULL.
    1 NOT IN (NULL, 1, 2), -- The value 1 is a member of the set, return false.
    3 NOT IN (NULL, 1, 2)  -- Ambiguous, return NULL.
  }
} {1 null 0 null}

do_test in-13.2 {
  execsql { 
    CREATE TABLE t7(a, b, c NOT NULL);
    INSERT INTO t7 VALUES(1,    1, 1);
    INSERT INTO t7 VALUES(2,    2, 2);
    INSERT INTO t7 VALUES(3,    3, 3);
    INSERT INTO t7 VALUES(NULL, 4, 4);
    INSERT INTO t7 VALUES(NULL, 5, 5);
  }
} {}

do_test in-13.3 {
  execsql { SELECT 2 IN (SELECT a FROM t7) }
} {1}
do_test in-13.4 {
  execsql { SELECT 6 IN (SELECT a FROM t7) }
} {null}

do_test in-13.5 {
  execsql { SELECT 2 IN (SELECT b FROM t7) }
} {1}
do_test in-13.6 {
  execsql { SELECT 6 IN (SELECT b FROM t7) }
} {0}

do_test in-13.7 {
  execsql { SELECT 2 IN (SELECT c FROM t7) }
} {1}
do_test in-13.8 {
  execsql { SELECT 6 IN (SELECT c FROM t7) }
} {0}

do_test in-13.9 {
  execsql {
    SELECT
      2 NOT IN (SELECT a FROM t7),
      6 NOT IN (SELECT a FROM t7),
      2 NOT IN (SELECT b FROM t7),
      6 NOT IN (SELECT b FROM t7),
      2 NOT IN (SELECT c FROM t7),
      6 NOT IN (SELECT c FROM t7)
  } 
} {0 null 0 1 0 1}

do_test in-13.10 {
  execsql { 
    SELECT b IN (
      SELECT inside.a 
      FROM t7 AS inside 
      WHERE inside.b BETWEEN outside.b+1 AND outside.b+2
    )
    FROM t7 AS outside ORDER BY b;
  }
} {0 null null null 0}

do_test in-13.11 {
  execsql {
    SELECT b NOT IN (
      SELECT inside.a 
      FROM t7 AS inside 
      WHERE inside.b BETWEEN outside.b+1 AND outside.b+2
    )
    FROM t7 AS outside ORDER BY b;
  }
} {1 null null null 1}

do_test in-13.12 {
  execsql {
    CREATE INDEX i1 ON t7(a);
    CREATE INDEX i2 ON t7(b);
    CREATE INDEX i3 ON t7(c);
  }
  execsql {
    SELECT
      2 IN (SELECT a FROM t7),
      6 IN (SELECT a FROM t7),
      2 IN (SELECT b FROM t7),
      6 IN (SELECT b FROM t7),
      2 IN (SELECT c FROM t7),
      6 IN (SELECT c FROM t7)
  } 
} {1 null 1 0 1 0}

do_test in-13.13 {
  execsql {
    SELECT
      2 NOT IN (SELECT a FROM t7),
      6 NOT IN (SELECT a FROM t7),
      2 NOT IN (SELECT b FROM t7),
      6 NOT IN (SELECT b FROM t7),
      2 NOT IN (SELECT c FROM t7),
      6 NOT IN (SELECT c FROM t7)
  } 
} {0 null 0 1 0 1}

do_test in-13.14 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE a(id INTEGER);
    INSERT INTO a VALUES(1);
    INSERT INTO a VALUES(2);
    INSERT INTO a VALUES(3);
    CREATE TABLE b(id INTEGER);
    INSERT INTO b VALUES(NULL);
    INSERT INTO b VALUES(3);
    INSERT INTO b VALUES(4);
    INSERT INTO b VALUES(5);
    COMMIT;
    SELECT * FROM a WHERE id NOT IN (SELECT id FROM b);
  }
} {}
do_test in-13.14 {
  execsql {
    CREATE INDEX i5 ON b(id);
    SELECT * FROM a WHERE id NOT IN (SELECT id FROM b);
  }
} {}


do_test in-13.X {
  db nullvalue ""
} {}

finish_test

Added test/in2.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2007 May 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file tests a special case in the b-tree code that can be
# hit by the "IN" operator (or EXISTS, NOT IN, etc.).
#
# $Id: in2.test,v 1.3 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test in2-1 {
  execsql {
    CREATE TABLE a(i INTEGER PRIMARY KEY, a);
  }
} {}

set ::N 2000

do_test in2-2 {
  db transaction {
    for {set ::ii 0} {$::ii < $::N} {incr ::ii} {
      execsql {INSERT INTO a VALUES($::ii, $::ii)}
    }
    execsql {INSERT INTO a VALUES(4000, '')}

    for {set ::ii 0} {$::ii < $::N} {incr ::ii} {
      set ::t [format "x%04d" $ii]
      execsql {INSERT INTO a VALUES(NULL, $::t)}
    }
  }
} {}

# Each iteration of this loop builds a slightly different b-tree to
# evaluate the "IN (...)" operator in the SQL statement. The contents
# of the b-tree are (in sorted order):
#
#     $::ii integers.
#     a string of zero length.
#     $::N short strings.
#
# Records are inserted in sorted order.
#
# The string of zero-length is stored in a b-tree cell with 3 bytes
# of payload. Moving this cell from a leaf node to a internal node 
# during b-tree balancing was causing an assertion failure. 
#
# This bug only applied to b-trees generated to evaluate IN (..) 
# clauses, as it is impossible for persistent b-trees (SQL tables + 
# indices) to contain cells smaller than 4 bytes.
#
for {set ::ii 3} {$::ii < $::N} {incr ::ii} {
  do_test in2-$::ii {
    execsql {
      SELECT 1 IN (SELECT a FROM a WHERE (i < $::ii) OR (i >= $::N))
    }
  } {1}
}

finish_test

Added test/in3.test.



































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# 2007 November 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file tests the optimisations made in November 2007 of expressions 
# of the following form:
#
#     <value> IN (SELECT <column> FROM <table>)
#
# $Id: in3.test,v 1.5 2008/08/04 03:51:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

# Return the number of OpenEphemeral instructions used in the
# implementation of the sql statement passed as a an argument.
#
proc nEphemeral {sql} {
  set nEph 0
  foreach op [execsql "EXPLAIN $sql"] {
    if {$op eq "OpenEphemeral"} {incr nEph}
  }
  set nEph
}

# This proc works the same way as execsql, except that the number
# of OpenEphemeral instructions used in the implementation of the
# statement is inserted into the start of the returned list.
#
proc exec_neph {sql} {
  return [concat [nEphemeral $sql] [execsql $sql]]
}

do_test in3-1.1 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t1 VALUES(3, 4);
    INSERT INTO t1 VALUES(5, 6);
  }
} {}

# All of these queries should avoid using a temp-table:
#
do_test in3-1.2 {
  exec_neph { SELECT rowid FROM t1 WHERE rowid IN (SELECT rowid FROM t1); }
} {0 1 2 3}
do_test in3-1.3 {
  exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1); }
} {0 1 3 5}
do_test in3-1.4 {
  exec_neph { SELECT rowid FROM t1 WHERE rowid+0 IN (SELECT rowid FROM t1); }
} {0 1 2 3}
do_test in3-1.5 {
  exec_neph { SELECT a FROM t1 WHERE a+0 IN (SELECT a FROM t1); }
} {0 1 3 5}

# Because none of the sub-select queries in the following statements
# match the pattern ("SELECT <column> FROM <table>"), the following do 
# require a temp table.
#
do_test in3-1.6 {
  exec_neph { SELECT rowid FROM t1 WHERE rowid IN (SELECT rowid+0 FROM t1); }
} {1 1 2 3}
do_test in3-1.7 {
  exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a+0 FROM t1); }
} {1 1 3 5}
do_test in3-1.8 {
  exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 WHERE 1); }
} {1 1 3 5}
do_test in3-1.9 {
  exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 GROUP BY a); }
} {1 1 3 5}

# This should not use a temp-table. Even though the sub-select does
# not exactly match the pattern "SELECT <column> FROM <table>", in
# this case the ORDER BY is a no-op and can be ignored.
do_test in3-1.10 {
  exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 ORDER BY a); }
} {0 1 3 5}

# These do use the temp-table. Adding the LIMIT clause means the 
# ORDER BY cannot be ignored.
do_test in3-1.11 {
  exec_neph {SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 ORDER BY a LIMIT 1)}
} {1 1}
do_test in3-1.12 {
  exec_neph {
    SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 ORDER BY a LIMIT 1 OFFSET 1)
  }
} {1 3}

# Has to use a temp-table because of the compound sub-select.
#
ifcapable compound {
  do_test in3-1.13 {
    exec_neph {
      SELECT a FROM t1 WHERE a IN (
        SELECT a FROM t1 UNION ALL SELECT a FROM t1
      )
    }
  } {1 1 3 5}
}

# The first of these queries has to use the temp-table, because the 
# collation sequence used for the index on "t1.a" does not match the
# collation sequence used by the "IN" comparison. The second does not
# require a temp-table, because the collation sequences match.
#
do_test in3-1.14 {
  exec_neph { SELECT a FROM t1 WHERE a COLLATE nocase IN (SELECT a FROM t1) }
} {1 1 3 5}
do_test in3-1.15 {
  exec_neph { SELECT a FROM t1 WHERE a COLLATE binary IN (SELECT a FROM t1) }
} {0 1 3 5}

# Neither of these queries require a temp-table. The collation sequence
# makes no difference when using a rowid.
#
do_test in3-1.16 {
  exec_neph {SELECT a FROM t1 WHERE a COLLATE nocase IN (SELECT rowid FROM t1)}
} {0 1 3}
do_test in3-1.17 {
  exec_neph {SELECT a FROM t1 WHERE a COLLATE binary IN (SELECT rowid FROM t1)}
} {0 1 3}

# The following tests - in3.2.* - test a bug that was difficult to track
# down during development. They are not particularly well focused.
#
do_test in3-2.1 {
  execsql {
    DROP TABLE IF EXISTS t1;
    CREATE TABLE t1(w int, x int, y int);
    CREATE TABLE t2(p int, q int, r int, s int);
  }
  for {set i 1} {$i<=100} {incr i} {
    set w $i
    set x [expr {int(log($i)/log(2))}]
    set y [expr {$i*$i + 2*$i + 1}]
    execsql "INSERT INTO t1 VALUES($w,$x,$y)"
  }
  set maxy [execsql {select max(y) from t1}]
  db eval { INSERT INTO t2 SELECT 101-w, x, $maxy+1-y, y FROM t1 }
} {}
do_test in3-2.2 {
  execsql {
    SELECT rowid 
    FROM t1 
    WHERE rowid IN (SELECT rowid FROM t1 WHERE rowid IN (1, 2));
  }
} {1 2}
do_test in3-2.3 {
  execsql {
    select rowid from t1 where rowid IN (-1,2,4)
  }
} {2 4}
do_test in3-2.4 {
  execsql {
    SELECT rowid FROM t1 WHERE rowid IN 
       (select rowid from t1 where rowid IN (-1,2,4))
  }
} {2 4}

#-------------------------------------------------------------------------
# This next block of tests - in3-3.* - verify that column affinity is
# correctly handled in cases where an index might be used to optimise
# an IN (SELECT) expression.
#
do_test in3-3.1 {
  catch {execsql {
    DROP TABLE t1;
    DROP TABLE t2;
  }}

  execsql {

    CREATE TABLE t1(a BLOB, b NUMBER ,c TEXT);
    CREATE UNIQUE INDEX t1_i1 ON t1(a);        /* no affinity */
    CREATE UNIQUE INDEX t1_i2 ON t1(b);        /* numeric affinity */
    CREATE UNIQUE INDEX t1_i3 ON t1(c);        /* text affinity */

    CREATE TABLE t2(x BLOB, y NUMBER, z TEXT);
    CREATE UNIQUE INDEX t2_i1 ON t2(x);        /* no affinity */
    CREATE UNIQUE INDEX t2_i2 ON t2(y);        /* numeric affinity */
    CREATE UNIQUE INDEX t2_i3 ON t2(z);        /* text affinity */

    INSERT INTO t1 VALUES(1, 1, 1);
    INSERT INTO t2 VALUES('1', '1', '1');
  }
} {}

do_test in3-3.2 {
  # No affinity is applied before comparing "x" and "a". Therefore
  # the index can be used (the comparison is false, text!=number).
  exec_neph { SELECT x IN (SELECT a FROM t1) FROM t2 }
} {0 0}
do_test in3-3.3 {
  # Logically, numeric affinity is applied to both sides before 
  # the comparison.  Therefore it is possible to use index t1_i2.
  exec_neph { SELECT x IN (SELECT b FROM t1) FROM t2 }
} {0 1}
do_test in3-3.4 {
  # No affinity is applied before the comparison takes place. Making
  # it possible to use index t1_i3.
  exec_neph { SELECT x IN (SELECT c FROM t1) FROM t2 }
} {0 1}

do_test in3-3.5 {
  # Numeric affinity should be applied to each side before the comparison
  # takes place. Therefore we cannot use index t1_i1, which has no affinity.
  exec_neph { SELECT y IN (SELECT a FROM t1) FROM t2 }
} {1 1}
do_test in3-3.6 {
  # Numeric affinity is applied to both sides before 
  # the comparison.  Therefore it is possible to use index t1_i2.
  exec_neph { SELECT y IN (SELECT b FROM t1) FROM t2 }
} {0 1}
do_test in3-3.7 {
  # Numeric affinity is applied before the comparison takes place. 
  # Making it impossible to use index t1_i3.
  exec_neph { SELECT y IN (SELECT c FROM t1) FROM t2 }
} {1 1}

#---------------------------------------------------------------------
#
# Test using a multi-column index.
#
do_test in3-4.1 {
  execsql {
    CREATE TABLE t3(a, b, c);
    CREATE UNIQUE INDEX t3_i ON t3(b, a);
  }

  execsql {
    INSERT INTO t3 VALUES(1, 'numeric', 2);
    INSERT INTO t3 VALUES(2, 'text', 2);
    INSERT INTO t3 VALUES(3, 'real', 2);
    INSERT INTO t3 VALUES(4, 'none', 2);
  }
} {}
do_test in3-4.2 {
  exec_neph { SELECT 'text' IN (SELECT b FROM t3) }
} {0 1}
do_test in3-4.3 {
  exec_neph { SELECT 'TEXT' COLLATE nocase IN (SELECT b FROM t3) }
} {1 1}
do_test in3-4.4 {
  # A temp table must be used because t3_i.b is not guaranteed to be unique.
  exec_neph { SELECT b FROM t3 WHERE b IN (SELECT b FROM t3) }
} {1 none numeric real text}
do_test in3-4.5 {
  execsql { CREATE UNIQUE INDEX t3_i2 ON t3(b) }
  exec_neph { SELECT b FROM t3 WHERE b IN (SELECT b FROM t3) }
} {0 none numeric real text}
do_test in3-4.6 {
  execsql { DROP INDEX t3_i2 }
} {}

# The following two test cases verify that ticket #2991 has been fixed.
#
do_test in3-5.1 {
  execsql {
    CREATE TABLE Folders(
      folderid INTEGER PRIMARY KEY, 
      parentid INTEGER, 
      rootid INTEGER, 
      path VARCHAR(255)
    );
  }
} {}
do_test in3-5.2 {
  catchsql {
    DELETE FROM Folders WHERE folderid IN
    (SELECT folderid FROM Folder WHERE path LIKE 'C:\MP3\Albums\' || '%');
  }
} {1 {no such table: Folder}}

finish_test

Added test/in4.test.





































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# 2008 September 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: in4.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test in4-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a);
  }
} {}
do_test in4-1.2 {
  execsql {
    SELECT * FROM t1 WHERE a IN ('aaa', 'bbb', 'ccc');
  }
} {}
do_test in4-1.3 {
  execsql {
    INSERT INTO t1 VALUES('aaa', 1);
    INSERT INTO t1 VALUES('ddd', 2);
    INSERT INTO t1 VALUES('ccc', 3);
    INSERT INTO t1 VALUES('eee', 4);
    SELECT b FROM t1 WHERE a IN ('aaa', 'bbb', 'ccc');
  }
} {1 3}
do_test in4-1.4 {
  execsql {
    SELECT a FROM t1 WHERE rowid IN (1, 3);
  }
} {aaa ccc}
do_test in4-1.5 {
  execsql {
    SELECT a FROM t1 WHERE rowid IN ();
  }
} {}
do_test in4-1.6 {
  execsql {
    SELECT a FROM t1 WHERE a IN ('ddd');
  }
} {ddd}

do_test in4-2.1 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b TEXT);
    INSERT INTO t2 VALUES(-1, '-one');
    INSERT INTO t2 VALUES(0, 'zero');
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(2, 'two');
    INSERT INTO t2 VALUES(3, 'three');
  }
} {}

do_test in4-2.2 {
  execsql { SELECT b FROM t2 WHERE a IN (0, 2) }
} {zero two}

do_test in4-2.3 {
  execsql { SELECT b FROM t2 WHERE a IN (2, 0) }
} {zero two}

do_test in4-2.4 {
  execsql { SELECT b FROM t2 WHERE a IN (2, -1) }
} {-one two}

do_test in4-2.5 {
  execsql { SELECT b FROM t2 WHERE a IN (NULL, 3) }
} {three}

do_test in4-2.6 {
  execsql { SELECT b FROM t2 WHERE a IN (1.0, 2.1) }
} {one}

do_test in4-2.7 {
  execsql { SELECT b FROM t2 WHERE a IN ('1', '2') }
} {one two}

do_test in4-2.8 {
  execsql { SELECT b FROM t2 WHERE a IN ('', '0.0.0', '2') }
} {two}

# The following block of tests test expressions of the form:
#
#    <expr> IN ()
#
# i.e. IN expressions with a literal empty set. 
# 
# This has led to crashes on more than one occasion. Test case in4-3.2 
# was added in reponse to a bug reported on the mailing list on 11/7/2008.
# See also tickets #3602 and #185.
#
do_test in4-3.1 {
  execsql {
    DROP TABLE IF EXISTS t1;
    DROP TABLE IF EXISTS t2;
    CREATE TABLE t1(x, id);
    CREATE TABLE t2(x, id);
    INSERT INTO t1 VALUES(NULL, NULL);
    INSERT INTO t1 VALUES(0, NULL);
    INSERT INTO t1 VALUES(1, 3);
    INSERT INTO t1 VALUES(2, 4);
    INSERT INTO t1 VALUES(3, 5);
    INSERT INTO t1 VALUES(4, 6);
    INSERT INTO t2 VALUES(0, NULL);
    INSERT INTO t2 VALUES(4, 1);
    INSERT INTO t2 VALUES(NULL, 1);
    INSERT INTO t2 VALUES(NULL, NULL);
  }
} {}
do_test in4-3.2 {
  execsql {
    SELECT x FROM t1 WHERE id IN () AND x IN (SELECT x FROM t2 WHERE id=1)
  }
} {}
do_test in4-3.3 {
  execsql {
    CREATE TABLE t3(x, y, z);
    CREATE INDEX t3i1 ON t3(x, y);
    INSERT INTO t3 VALUES(1, 1, 1);
    INSERT INTO t3 VALUES(10, 10, 10);
  }
  execsql { SELECT * FROM t3 WHERE x IN () }
} {}
do_test in4-3.4 {
  execsql { SELECT * FROM t3 WHERE x = 10 AND y IN () }
} {}
do_test in4-3.5 {
  execsql { SELECT * FROM t3 WHERE x IN () AND y = 10 }
} {}
do_test in4-3.6 {
  execsql { SELECT * FROM t3 WHERE x IN () OR x = 10 }
} {10 10 10}
do_test in4-3.7 {
  execsql { SELECT * FROM t3 WHERE y IN () }
} {}
do_test in4-3.8 {
  execsql { SELECT x IN() AS a FROM t3 WHERE a }
} {}
do_test in4-3.9 {
  execsql { SELECT x IN() AS a FROM t3 WHERE NOT a }
} {0 0}
do_test in4-3.10 {
  execsql { SELECT * FROM t3 WHERE oid IN () }
} {}
do_test in4-3.11 {
  execsql { SELECT * FROM t3 WHERE x IN (1, 2) OR y IN ()}
} {1 1 1}
do_test in4-3.12 {
  execsql { SELECT * FROM t3 WHERE x IN (1, 2) AND y IN ()}
} {}

finish_test

Added test/incrblob.test.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# 2007 May 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: incrblob.test,v 1.24 2009/06/19 22:23:42 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!autovacuum || !pragma || !incrblob} {
  finish_test
  return
}

do_test incrblob-1.1 {
  execsql {
    CREATE TABLE blobs(k PRIMARY KEY, v BLOB);
    INSERT INTO blobs VALUES('one', X'0102030405060708090A');
    INSERT INTO blobs VALUES('two', X'0A090807060504030201');
  }
} {}

do_test incrblob-1.2.1 {
  set ::blob [db incrblob blobs v 1]
  string match incrblob_* $::blob
} {1}
unset -nocomplain data
do_test incrblob-1.2.2 {
  binary scan [read $::blob] c* data
  set data
} {1 2 3 4 5 6 7 8 9 10}
do_test incrblob-1.2.3 {
  seek $::blob 0
  puts -nonewline $::blob "1234567890"
  flush $::blob
} {}
do_test incrblob-1.2.4 {
  seek $::blob 0
  binary scan [read $::blob] c* data
  set data
} {49 50 51 52 53 54 55 56 57 48}
do_test incrblob-1.2.5 {
  close $::blob
} {}
do_test incrblob-1.2.6 {
  execsql {
    SELECT v FROM blobs WHERE rowid = 1;
  }
} {1234567890}

#--------------------------------------------------------------------
# Test cases incrblob-1.3.X check that it is possible to read and write
# regions of a blob that lie on overflow pages.
#
do_test incrblob-1.3.1 {
  set ::str "[string repeat . 10000]"
  execsql {
    INSERT INTO blobs(rowid, k, v) VALUES(3, 'three', $::str);
  }
} {}

do_test incrblob-1.3.2 {
  set ::blob [db incrblob blobs v 3]
  seek $::blob 8500
  read $::blob 10
} {..........}
do_test incrblob-1.3.3 {
  seek $::blob 8500
  puts -nonewline $::blob 1234567890
} {}
do_test incrblob-1.3.4 {
  seek $::blob 8496
  read $::blob 10
} {....123456}
do_test incrblob-1.3.10 {
  close $::blob
} {}

#------------------------------------------------------------------------
# incrblob-2.*: 
#
# Test that the following operations use ptrmap pages to reduce
# unnecessary reads:
#
#     * Reading near the end of a blob,
#     * Writing near the end of a blob, and
#     * SELECT a column value that is located on an overflow page.
#
proc nRead {db} {
  set bt [btree_from_db $db]
  db_enter $db
  array set stats [btree_pager_stats $bt]
  db_leave $db
  return $stats(read)
}
proc nWrite {db} {
  set bt [btree_from_db $db]
  db_enter $db
  array set stats [btree_pager_stats $bt]
  db_leave $db
  return $stats(write)
}

sqlite3_soft_heap_limit 0

foreach AutoVacuumMode [list 0 1] {

  if {$AutoVacuumMode>0} {
    ifcapable !autovacuum {
      break
    }
  }

  db close
  file delete -force test.db test.db-journal

  sqlite3 db test.db
  execsql "PRAGMA auto_vacuum = $AutoVacuumMode"

  do_test incrblob-2.$AutoVacuumMode.1 {
    set ::str [string repeat abcdefghij 2900]
    execsql {
      BEGIN;
      CREATE TABLE blobs(k PRIMARY KEY, v BLOB, i INTEGER);
      DELETE FROM blobs;
      INSERT INTO blobs VALUES('one', $::str || randstr(500,500), 45);
      COMMIT;
    }
    expr [file size test.db]/1024
  } [expr 31 + $AutoVacuumMode]

  ifcapable autovacuum {
    do_test incrblob-2.$AutoVacuumMode.2 {
      execsql {
        PRAGMA auto_vacuum;
      }
    } $AutoVacuumMode
  }

  do_test incrblob-2.$AutoVacuumMode.3 {
    # Open and close the db to make sure the page cache is empty.
    db close
    sqlite3 db test.db
  
    # Read the last 20 bytes of the blob via a blob handle.
    set ::blob [db incrblob blobs v 1]
    seek $::blob -20 end
    set ::fragment [read $::blob]
    close $::blob
  
    # If the database is not in auto-vacuum mode, the whole of
    # the overflow-chain must be scanned. In auto-vacuum mode,
    # sqlite uses the ptrmap pages to avoid reading the other pages.
    #
    nRead db
  } [expr $AutoVacuumMode ? 4 : 30]

  do_test incrblob-2.$AutoVacuumMode.4 {
    string range [db one {SELECT v FROM blobs}] end-19 end
  } $::fragment

  do_test incrblob-2.$AutoVacuumMode.5 {
    # Open and close the db to make sure the page cache is empty.
    db close
    sqlite3 db test.db
  
    # Write the second-to-last 20 bytes of the blob via a blob handle.
    #
    set ::blob [db incrblob blobs v 1]
    seek $::blob -40 end
    puts -nonewline $::blob "1234567890abcdefghij"
    flush $::blob
  
    # If the database is not in auto-vacuum mode, the whole of
    # the overflow-chain must be scanned. In auto-vacuum mode,
    # sqlite uses the ptrmap pages to avoid reading the other pages.
    #
    nRead db
  } [expr $AutoVacuumMode ? 4 : 30]

  # Pages 1 (the write-counter) and 32 (the blob data) were written.
  do_test incrblob-2.$AutoVacuumMode.6 {
    close $::blob
    nWrite db
  } 2

  do_test incrblob-2.$AutoVacuumMode.7 {
    string range [db one {SELECT v FROM blobs}] end-39 end-20
  } "1234567890abcdefghij"

  do_test incrblob-2.$AutoVacuumMode.8 {
    # Open and close the db to make sure the page cache is empty.
    db close
    sqlite3 db test.db

    execsql { SELECT i FROM blobs } 
  } {45}

  do_test incrblob-2.$AutoVacuumMode.9 {
    nRead db
  } [expr $AutoVacuumMode ? 4 : 30]
}
sqlite3_soft_heap_limit $soft_limit

#------------------------------------------------------------------------
# incrblob-3.*: 
#
# Test the outcome of trying to write to a read-only blob handle.
#
do_test incrblob-3.1 {
  set ::blob [db incrblob -readonly blobs v 1]
  seek $::blob -40 end
  read $::blob 20
} "1234567890abcdefghij"
do_test incrblob-3.2 {
  seek $::blob 0
  set rc [catch {
    puts -nonewline $::blob "helloworld"
  } msg]
  close $::blob
  list $rc $msg
} "1 {channel \"$::blob\" wasn't opened for writing}"

do_test incrblob-3.3 {
  set ::blob [db incrblob -readonly blobs v 1]
  seek $::blob -40 end
  read $::blob 20
} "1234567890abcdefghij"
do_test incrblob-3.4 {
  set rc [catch {
    sqlite3_blob_write $::blob 20 "qwertyuioplkjhgfds" 
  } msg]
  list $rc $msg
} {1 SQLITE_READONLY}
catch {close $::blob}

#------------------------------------------------------------------------
# incrblob-4.*: 
#
# Try a couple of error conditions:
#
#     4.1 - Attempt to open a row that does not exist.
#     4.2 - Attempt to open a column that does not exist.
#     4.3 - Attempt to open a table that does not exist.
#     4.4 - Attempt to open a database that does not exist.
#
#     4.5 - Attempt to open an integer
#     4.6 - Attempt to open a real value
#     4.7 - Attempt to open an SQL null
#
#     4.8 - Attempt to open an indexed column for writing
#     4.9 - Attempt to open an indexed column for reading (this works)
#
#     4.11 - Attempt to open a column of a view.
#     4.12 - Attempt to open a column of a virtual table.
#
do_test incrblob-4.1 {
  set rc [catch {
    set ::blob [db incrblob blobs v 2]
  } msg ] 
  list $rc $msg
} {1 {no such rowid: 2}}
do_test incrblob-4.2 {
  set rc [catch {
    set ::blob [db incrblob blobs blue 1]
  } msg ] 
  list $rc $msg
} {1 {no such column: "blue"}}
do_test incrblob-4.3 {
  set rc [catch {
    set ::blob [db incrblob nosuchtable blue 1]
  } msg ]
  list $rc $msg
} {1 {no such table: main.nosuchtable}}
do_test incrblob-4.4 {
  set rc [catch {
    set ::blob [db incrblob nosuchdb blobs v 1]
  } msg ] 
  list $rc $msg
} {1 {no such table: nosuchdb.blobs}}

do_test incrblob-4.5 {
  set rc [catch {
    set ::blob [db incrblob blobs i 1]
  } msg ] 
  list $rc $msg
} {1 {cannot open value of type integer}}
do_test incrblob-4.6 {
  execsql {
    INSERT INTO blobs(k, v, i) VALUES(123, 567.765, NULL);
  }
  set rc [catch {
    set ::blob [db incrblob blobs v 2]
  } msg ] 
  list $rc $msg
} {1 {cannot open value of type real}}
do_test incrblob-4.7 {
  set rc [catch {
    set ::blob [db incrblob blobs i 2]
  } msg ] 
  list $rc $msg
} {1 {cannot open value of type null}}

do_test incrblob-4.8.1 {
  execsql {
    INSERT INTO blobs(k, v, i) VALUES(X'010203040506070809', 'hello', 'world');
  }
  set rc [catch {
    set ::blob [db incrblob blobs k 3]
  } msg ] 
  list $rc $msg
} {1 {cannot open indexed column for writing}}
do_test incrblob-4.8.2 {
  execsql {
    CREATE TABLE t3(a INTEGER PRIMARY KEY, b);
    INSERT INTO t3 VALUES(1, 2);
  }
  set rc [catch {
    set ::blob [db incrblob -readonly t3 a 1]
  } msg ] 
  list $rc $msg
} {1 {cannot open value of type null}}
do_test incrblob-4.8.3 {
  set rc [catch {
    set ::blob [db incrblob -readonly t3 rowid 1]
  } msg ] 
  list $rc $msg
} {1 {no such column: "rowid"}}

do_test incrblob-4.9.1 {
  set rc [catch {
    set ::blob [db incrblob -readonly blobs k 3]
  } msg]
} {0}
do_test incrblob-4.9.2 {
  binary scan [read $::blob] c* c
  close $::blob
  set c
} {1 2 3 4 5 6 7 8 9}

do_test incrblob-4.10 {
  set ::blob [db incrblob -readonly blobs k 3]
  set rc [catch { sqlite3_blob_read $::blob 10 100 } msg]
  list $rc $msg
} {1 SQLITE_ERROR}
do_test incrblob-4.10.2 {
  close $::blob
} {}

ifcapable view {
  do_test incrblob-4.11 {
    execsql { CREATE VIEW blobs_view AS SELECT k, v, i FROM blobs }
    set rc [catch { db incrblob blobs_view v 3 } msg]
    list $rc $msg
  } {1 {cannot open view: blobs_view}}
}
ifcapable vtab {
  register_echo_module [sqlite3_connection_pointer db]
  do_test incrblob-4.12 {
    execsql { CREATE VIRTUAL TABLE blobs_echo USING echo(blobs) }
    set rc [catch { db incrblob blobs_echo v 3 } msg]
    list $rc $msg
  } {1 {cannot open virtual table: blobs_echo}}
}


#------------------------------------------------------------------------
# incrblob-5.*: 
#
#     Test that opening a blob in an attached database works.
#
ifcapable attach {
  do_test incrblob-5.1 {
    file delete -force test2.db test2.db-journal
    set ::size [expr [file size [info script]]]
    execsql {
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.files(name, text);
      INSERT INTO aux.files VALUES('this one', zeroblob($::size));
    }
    set fd  [db incrblob aux files text 1]
    fconfigure $fd -translation binary
    set fd2 [open [info script]]
    fconfigure $fd2 -translation binary
    puts -nonewline $fd [read $fd2]
    close $fd
    close $fd2
    set ::text [db one {select text from aux.files}]
    string length $::text
  } [file size [info script]]
  do_test incrblob-5.2 {
    set fd2 [open [info script]]
    fconfigure $fd2 -translation binary
    set ::data [read $fd2]
    close $fd2
    set ::data
  } $::text
}

# free memory
unset -nocomplain ::data
unset -nocomplain ::text

#------------------------------------------------------------------------
# incrblob-6.*: 
#
#     Test that opening a blob for write-access is impossible if
#     another connection has the database RESERVED lock.
#
#     Then test that blob writes that take place inside of a
#     transaction are not visible to external connections until
#     after the transaction is commited and the blob channel 
#     closed.
#
sqlite3_soft_heap_limit 0
do_test incrblob-6.1 {
  sqlite3 db2 test.db
  execsql {
    BEGIN;
    INSERT INTO blobs(k, v, i) VALUES('a', 'different', 'connection');
  } db2
} {}
do_test incrblob-6.2 {
  execsql {
    SELECT rowid FROM blobs
  }
} {1 2 3}
do_test incrblob-6.3 {
  set rc [catch {
    db incrblob blobs v 1
  } msg]
  list $rc $msg
} {1 {database is locked}}
do_test incrblob-6.4 {
  set rc [catch {
    db incrblob blobs v 3
  } msg]
  list $rc $msg
} {1 {database is locked}}
do_test incrblob-6.5 {
  set ::blob [db incrblob -readonly blobs v 3]
  read $::blob
} {hello}
do_test incrblob-6.6 {
  close $::blob
} {}

do_test incrblob-6.7 {
  set ::blob [db2 incrblob blobs i 4]
  gets $::blob
} {connection}
do_test incrblob-6.8 {
  tell $::blob
} {10}
do_test incrblob-6.9 {
  seek $::blob 0
  puts -nonewline $::blob "invocation"
  flush $::blob
} {}

# At this point rollback should be illegal (because 
# there is an open blob channel).  But commit is also illegal because
# the open blob is read-write.
#
do_test incrblob-6.10 {
  catchsql {
    ROLLBACK;
  } db2
} {1 {cannot rollback transaction - SQL statements in progress}}
do_test incrblob-6.11 {
  catchsql {
    COMMIT;
  } db2
} {1 {cannot commit transaction - SQL statements in progress}}

do_test incrblob-6.12 {
  execsql {
    SELECT * FROM blobs WHERE rowid = 4;
  }
} {}
do_test incrblob-6.13 {
  close $::blob
} {}
do_test incrblob-6.14 {
  catchsql {
    COMMIT;
  } db2
} {0 {}}
do_test incrblob-6.15 {
  execsql {
    SELECT * FROM blobs WHERE rowid = 4;
  }
} {a different invocation}
db2 close
sqlite3_soft_heap_limit $soft_limit

#-----------------------------------------------------------------------
# The following tests verify the behaviour of the incremental IO
# APIs in the following cases:
#
#     7.1 A row that containing an open blob is modified.
#
#     7.2 A CREATE TABLE requires that an overflow page that is part
#         of an open blob is moved.
#
#     7.3 An INCREMENTAL VACUUM moves an overflow page that is part
#         of an open blob.
#
# In the first case above, correct behaviour is for all subsequent
# read/write operations on the blob-handle to return SQLITE_ABORT.
# More accurately, blob-handles are invalidated whenever the table
# they belong to is written to.
#
# The second two cases have no external effect. They are testing
# that the internal cache of overflow page numbers is correctly
# invalidated.
#
do_test incrblob-7.1.0 {
  execsql {
    BEGIN;
    DROP TABLE blobs;
    CREATE TABLE t1 (a, b, c, d BLOB);
    INSERT INTO t1(a, b, c, d) VALUES(1, 2, 3, 4);
    COMMIT;
  }
} {}

foreach {tn arg} {1 "" 2 -readonly} {

  execsql {
    UPDATE t1 SET d = zeroblob(10000);
  }

  do_test incrblob-7.1.$tn.1 {
    set ::b [eval db incrblob $arg t1 d 1]
    binary scan [sqlite3_blob_read $::b 5000 5] c* c
    set c
  } {0 0 0 0 0}
  do_test incrblob-7.1.$tn.2 {
    execsql {
      UPDATE t1 SET d = 15;
    }
  } {}
  do_test incrblob-7.1.$tn.3 {
    set rc [catch { sqlite3_blob_read $::b 5000 5 } msg]
    list $rc $msg
  } {1 SQLITE_ABORT}
  do_test incrblob-7.1.$tn.4 {
    execsql {
      SELECT d FROM t1;
    }
  } {15}
  do_test incrblob-7.1.$tn.5 {
    set rc [catch { close $::b } msg]
    list $rc $msg
  } {0 {}}
  do_test incrblob-7.1.$tn.6 {
    execsql {
      SELECT d FROM t1;
    }
  } {15}

}

set fd [open [info script]]
fconfigure $fd -translation binary
set ::data [read $fd 14000]
close $fd

db close
file delete -force test.db test.db-journal
sqlite3 db test.db

do_test incrblob-7.2.1 {
  execsql {
    PRAGMA auto_vacuum = "incremental";
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b);        -- root@page3
    INSERT INTO t1 VALUES(123, $::data);
  }
  set ::b [db incrblob -readonly t1 b 123]
  fconfigure $::b -translation binary
  read $::b
} $::data
do_test incrblob-7.2.2 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b);        -- root@page4
  }
  seek $::b 0
  read $::b
} $::data
do_test incrblob-7.2.3 {
  close $::b
  execsql {
    SELECT rootpage FROM sqlite_master;
  }
} {3 4}

set ::otherdata "[string range $::data 0 1000][string range $::data 1001 end]"
do_test incrblob-7.3.1 {
  execsql {
    INSERT INTO t2 VALUES(456, $::otherdata);
  }
  set ::b [db incrblob -readonly t2 b 456]
  fconfigure $::b -translation binary
  read $::b
} $::otherdata
do_test incrblob-7.3.2 {
  expr [file size test.db]/1024
} 30
do_test incrblob-7.3.3 {
  execsql {
    DELETE FROM t1 WHERE a = 123;
    PRAGMA INCREMENTAL_VACUUM(0);
  }
  seek $::b 0
  read $::b
} $::otherdata

# Attempt to write on a read-only blob.  Make sure the error code
# gets set.  Ticket #2464.
#
do_test incrblob-7.4 {
  set rc [catch {sqlite3_blob_write $::b 10 HELLO} msg]
  lappend rc $msg
} {1 SQLITE_READONLY}
do_test incrblob-7.5 {
  sqlite3_errcode db
} {SQLITE_READONLY}
do_test incrblob-7.6 {
  sqlite3_errmsg db
} {attempt to write a readonly database}

# Test that if either the "offset" or "amount" arguments to
# sqlite3_blob_write() are less than zero, SQLITE_ERROR is returned.
# 
do_test incrblob-8.1 {
  execsql { INSERT INTO t1 VALUES(314159, 'sqlite') }
  set ::b [db incrblob t1 b 314159]
  fconfigure $::b -translation binary
  set rc [catch {sqlite3_blob_write $::b 10 HELLO -1} msg]
  lappend rc $msg
} {1 SQLITE_ERROR}
do_test incrblob-8.2 {
  sqlite3_errcode db
} {SQLITE_ERROR}
do_test incrblob-8.3 {
  set rc [catch {sqlite3_blob_write $::b -1 HELLO 5} msg]
  lappend rc $msg
} {1 SQLITE_ERROR}
do_test incrblob-8.4 {
  sqlite3_errcode db
} {SQLITE_ERROR}
do_test incrblob-8.5 {
  execsql {SELECT b FROM t1 WHERE a = 314159}
} {sqlite}
do_test incrblob-8.6 {
  set rc [catch {sqlite3_blob_write $::b 0 etilqs 6} msg]
  lappend rc $msg
} {0 {}}
do_test incrblob-8.7 {
  execsql {SELECT b FROM t1 WHERE a = 314159}
} {etilqs}


finish_test

Added test/incrblob2.test.





































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# 2008 June 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test that it is possible to have two open blob handles on a single
# blob object.
#
# $Id: incrblob2.test,v 1.11 2009/06/29 06:00:37 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!autovacuum || !pragma || !incrblob} {
  finish_test
  return
}

do_test incrblob2-1.0 {
  execsql {
    CREATE TABLE blobs(id INTEGER PRIMARY KEY, data BLOB);
    INSERT INTO blobs VALUES(NULL, zeroblob(5000));
    INSERT INTO blobs VALUES(NULL, zeroblob(5000));
    INSERT INTO blobs VALUES(NULL, zeroblob(5000));
    INSERT INTO blobs VALUES(NULL, zeroblob(5000));
  }
} {}

foreach iOffset [list 0 256 4094] {
  do_test incrblob2-1.$iOffset.1 {
    set fd [db incrblob blobs data 1]
    puts $fd "[string repeat x $iOffset]SQLite version 3.6.0"
    close $fd
  } {}
  
  do_test incrblob2-1.$iOffset.2 {
    set fd1 [db incrblob blobs data 1]
    set fd2 [db incrblob blobs data 1]
    fconfigure $fd1 -buffering none
    fconfigure $fd2 -buffering none
    if {$iOffset != 0} {
      seek $fd2 $iOffset start
      seek $fd1 $iOffset start
    }
    read $fd1 6
  } {SQLite}
  
  do_test incrblob2-1.$iOffset.3 {
    read $fd2 6
  } {SQLite}
  
  do_test incrblob2-1.$iOffset.4 {
    seek $fd2 $iOffset start
    seek $fd1 $iOffset start
    puts -nonewline $fd2 "etiLQS"
  } {}

  
  do_test incrblob2-1.$iOffset.5 {
    seek $fd1 $iOffset start
    read $fd1 6
  } {etiLQS}
  
  do_test incrblob2-1.$iOffset.6 {
    seek $fd2 $iOffset start
    read $fd2 6
  } {etiLQS}
  
  do_test incrblob2-1.$iOffset.7 {
    seek $fd1 $iOffset start
    read $fd1 6
  } {etiLQS}
  
  do_test incrblob2-1.$iOffset.8 {
    close $fd1
    close $fd2
  } {}
}

#--------------------------------------------------------------------------

foreach iOffset [list 0 256 4094] {

  do_test incrblob2-2.$iOffset.1 {
    set fd1 [db incrblob blobs data 1]
    seek $fd1 [expr $iOffset - 5000] end
    fconfigure $fd1 -buffering none

    set fd2 [db incrblob blobs data 1]
    seek $fd2 [expr $iOffset - 5000] end
    fconfigure $fd2 -buffering none

    puts -nonewline $fd1 "123456"
  } {}
  
  do_test incrblob2-2.$iOffset.2 {
    read $fd2 6
  } {123456}

  do_test incrblob2-2.$iOffset.3 {
    close $fd1
    close $fd2
  } {}
}

do_test incrblob2-3.1 {
  set fd1 [db incrblob blobs data 1]
  fconfigure $fd1 -buffering none
} {}
do_test incrblob2-3.2 {
  execsql {
    INSERT INTO blobs VALUES(5, zeroblob(10240));
  }
} {}
do_test incrblob2-3.3 {
  set rc [catch { read $fd1 6 } msg]
  list $rc $msg
} {0 123456}
do_test incrblob2-3.4 {
  close $fd1
} {}

#--------------------------------------------------------------------------
# The following tests - incrblob2-4.* - test that blob handles are 
# invalidated at the correct times.
#
do_test incrblob2-4.1 {
  unset -nocomplain data
  db eval BEGIN
  db eval { CREATE TABLE t1(id INTEGER PRIMARY KEY, data BLOB); }
  for {set ii 1} {$ii < 100} {incr ii} {
    set data [string repeat "blob$ii" 500]
    db eval { INSERT INTO t1 VALUES($ii, $data) }
  }
  db eval COMMIT
} {}

proc aborted_handles {} {
  global handles

  set aborted {}
  for {set ii 1} {$ii < 100} {incr ii} {
    set str "blob$ii"
    set nByte [string length $str]
    set iOffset [expr $nByte * $ii * 2]

    set rc [catch {sqlite3_blob_read $handles($ii) $iOffset $nByte} msg]
    if {$rc && $msg eq "SQLITE_ABORT"} {
      lappend aborted $ii
    } else {
      if {$rc || $msg ne $str} {
        error "blob $ii: $msg"
      }
    }
  }
  set aborted
}

do_test incrblob2-4.2 {
  for {set ii 1} {$ii < 100} {incr ii} {
    set handles($ii) [db incrblob t1 data $ii]
  }
  aborted_handles
} {}

# Update row 3. This should abort handle 3 but leave all others untouched.
#
do_test incrblob2-4.3 {
  db eval {UPDATE t1 SET data = data || '' WHERE id = 3}
  aborted_handles
} {3}

# Test that a write to handle 3 also returns SQLITE_ABORT.
#
do_test incrblob2-4.3.1 {
  set rc [catch {sqlite3_blob_write $::handles(3) 10 HELLO} msg]
  list $rc $msg
} {1 SQLITE_ABORT}

# Delete row 14. This should abort handle 6 but leave all others untouched.
#
do_test incrblob2-4.4 {
  db eval {DELETE FROM t1 WHERE id = 14}
  aborted_handles
} {3 14}

# Change the rowid of row 15 to 102. Should abort handle 15.
#
do_test incrblob2-4.5 {
  db eval {UPDATE t1 SET id = 102 WHERE id = 15}
  aborted_handles
} {3 14 15}

# Clobber row 92 using INSERT OR REPLACE.
#
do_test incrblob2-4.6 {
  db eval {INSERT OR REPLACE INTO t1 VALUES(92, zeroblob(1000))}
  aborted_handles
} {3 14 15 92}

# Clobber row 65 using UPDATE OR REPLACE on row 35. This should abort 
# handles 35 and 65.
#
do_test incrblob2-4.7 {
  db eval {UPDATE OR REPLACE t1 SET id = 65 WHERE id = 35}
  aborted_handles
} {3 14 15 35 65 92}

# Insert a couple of new rows. This should not invalidate any handles.
#
do_test incrblob2-4.9 {
  db eval {INSERT INTO t1 SELECT NULL, data FROM t1}
  aborted_handles
} {3 14 15 35 65 92}

# Delete all rows from 1 to 25. This should abort all handles up to 25.
#
do_test incrblob2-4.9 {
  db eval {DELETE FROM t1 WHERE id >=1 AND id <= 25}
  aborted_handles
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 35 65 92}

# Delete the whole table (this will use sqlite3BtreeClearTable()). All handles
# should now be aborted.
#
do_test incrblob2-4.10 {
  db eval {DELETE FROM t1}
  aborted_handles
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99}

do_test incrblob2-4.1.X {
  for {set ii 1} {$ii < 100} {incr ii} {
    close $handles($ii) 
  }
} {}

#--------------------------------------------------------------------------
# The following tests - incrblob2-5.* - test that in shared cache an open
# blob handle counts as a read-lock on its table.
#
ifcapable shared_cache {
  db close
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

  do_test incrblob2-5.1 {
    sqlite3 db test.db
    sqlite3 db2 test.db

    execsql {
      INSERT INTO t1 VALUES(1, 'abcde');
    }
  } {}

  do_test incrblob2-5.2 {
    catchsql { INSERT INTO t1 VALUES(2, 'fghij') } db2
  } {0 {}}

  do_test incrblob2-5.3 {
    set blob [db incrblob t1 data 1]
    catchsql { INSERT INTO t1 VALUES(3, 'klmno') } db2
  } {1 {database table is locked}}

  do_test incrblob2-5.4 {
    close $blob
    execsql BEGIN db2
    catchsql { INSERT INTO t1 VALUES(4, 'pqrst') } db2
  } {0 {}}

  do_test incrblob2-5.5 {
    set rc [catch { db incrblob -readonly t1 data 1 } msg]
    list $rc $msg
  } {1 {database table is locked: t1}}

  do_test incrblob2-5.6 {
    execsql { PRAGMA read_uncommitted=1 }
    set blob [db incrblob -readonly t1 data 4]
    read $blob
  } {pqrst}

  do_test incrblob2-5.7 {
    catchsql { INSERT INTO t1 VALUES(3, 'klmno') } db2
  } {0 {}}

  do_test incrblob2-5.8 {
    close $blob
  } {}

  db2 close
  db close
  sqlite3_enable_shared_cache $::enable_shared_cache
}

#--------------------------------------------------------------------------
# The following tests - incrblob2-6.* - test a specific scenario that might
# be causing an error.
#
sqlite3 db test.db
do_test incrblob2-6.1 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1, zeroblob(100));
  }
  
  set rdHandle [db incrblob -readonly t1 data 1]
  set wrHandle [db incrblob t1 data 1]

  sqlite3_blob_read $rdHandle 0 100

  sqlite3_blob_write $wrHandle 0 ABCDEF

  close $wrHandle
  close $rdHandle
} {}

do_test incrblob2-6.2 {
  set rdHandle [db incrblob -readonly t1 data 1]
  sqlite3_blob_read $rdHandle 0 2
} {AB}

do_test incrblob2-6.3 {
  set wrHandle [db incrblob t1 data 1]
  sqlite3_blob_write $wrHandle 0 ZZZZZZZZZZ
  sqlite3_blob_read $rdHandle 2 4
} {ZZZZ}

do_test incrblob2-6.4 {
  close $wrHandle
  close $rdHandle
} {}

sqlite3_memory_highwater 1
do_test incrblob2-7.1 {
  db eval {
    CREATE TABLE t2(B BLOB);
    INSERT INTO t2 VALUES(zeroblob(10 * 1024 * 1024)); 
  }
  expr {[sqlite3_memory_highwater]<(5 * 1024 * 1024)}
} {1}

do_test incrblob2-7.2 {
  set h [db incrblob t2 B 1]
  expr {[sqlite3_memory_highwater]<(5 * 1024 * 1024)}
} {1}

do_test incrblob2-7.3 {
  seek $h 0 end
  tell $h
} [expr 10 * 1024 * 1024]

do_test incrblob2-7.4 {
  expr {[sqlite3_memory_highwater]<(5 * 1024 * 1024)}
} {1}

do_test incrblob2-7.5 {
  close $h
} {}

#---------------------------------------------------------------------------
# The following tests, incrblob2-8.*, test that nothing terrible happens
# when a statement transaction is rolled back while there are open 
# incremental-blob handles. At one point an assert() was failing when
# this was attempted.
#
do_test incrblob2-8.1 {
  execsql BEGIN
  set h [db incrblob t2 B 1]
  set rc [catch {
    db eval {SELECT rowid FROM t2} { execsql "DROP TABLE t2" }
  } msg] 
  list $rc $msg
} {1 {database table is locked}}
do_test incrblob2-8.2 {
  close $h
  execsql COMMIT
} {}
do_test incrblob2-8.3 {
  execsql {
    CREATE TABLE t3(a INTEGER UNIQUE, b TEXT);
    INSERT INTO t3 VALUES(1, 'aaaaaaaaaaaaaaaaaaaa');
    INSERT INTO t3 VALUES(2, 'bbbbbbbbbbbbbbbbbbbb');
    INSERT INTO t3 VALUES(3, 'cccccccccccccccccccc');
    INSERT INTO t3 VALUES(4, 'dddddddddddddddddddd');
    INSERT INTO t3 VALUES(5, 'eeeeeeeeeeeeeeeeeeee');
  }
} {}
do_test incrblob2-8.4 {
  execsql BEGIN
  set h [db incrblob t3 b 3]
  sqlite3_blob_read $h 0 20
} {cccccccccccccccccccc}
do_test incrblob2-8.5 {
  catchsql {UPDATE t3 SET a = 6 WHERE a > 3}
} {1 {column a is not unique}}
do_test incrblob2-8.6 {
  catchsql {UPDATE t3 SET a = 6 WHERE a > 3}
} {1 {column a is not unique}}
do_test incrblob2-8.7 {
  sqlite3_blob_read $h 0 20
} {cccccccccccccccccccc}
do_test incrblob2-8.8 {
  catchsql {UPDATE t3 SET a = 6 WHERE a = 3 OR a = 5}
} {1 {column a is not unique}}
do_test incrblob2-8.9 {
  set rc [catch {sqlite3_blob_read $h 0 20} msg]
  list $rc $msg
} {1 SQLITE_ABORT}
do_test incrblob2-8.X {
  close $h
} {}

finish_test

Added test/incrblob_err.test.



















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# 2007 May 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: incrblob_err.test,v 1.14 2008/07/18 17:16:27 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!incrblob  || !memdebug || !tclvar} {
  finish_test
  return
}

source $testdir/malloc_common.tcl

unset -nocomplain ::fd ::data
set ::fd [open [info script]]
set ::data [read $::fd]
close $::fd

do_malloc_test 1 -tclprep {
  set bytes [file size [info script]]
  execsql {
    CREATE TABLE blobs(k, v BLOB);
    INSERT INTO blobs VALUES(1, zeroblob($::bytes));
  }
} -tclbody {
  set ::blob [db incrblob blobs v 1]
  set rc [catch {puts -nonewline $::blob $::data}]
  if {$rc} { error "out of memory" }
} 

do_malloc_test 2 -tclprep {
  execsql {
    CREATE TABLE blobs(k, v BLOB);
    INSERT INTO blobs VALUES(1, $::data);
  }
} -tclbody {
  set ::blob [db incrblob blobs v 1]
  set rc [catch {set ::r [read $::blob]}]
  if {$rc} { 
    error "out of memory" 
  } elseif {$::r ne $::data} {
    error "Bad data read..."
  }
}

do_malloc_test 3 -tclprep {
  execsql {
    CREATE TABLE blobs(k, v BLOB);
    INSERT INTO blobs VALUES(1, $::data);
  }
} -tclbody {
  set ::blob [db incrblob blobs v 1]
  set rc [catch {set ::r [read $::blob]}]
  if {$rc} { 
    error "out of memory" 
  } elseif {$::r ne $::data} {
    error "Bad data read..."
  }
  set rc [catch {close $::blob}]
  if {$rc} { 
    error "out of memory" 
  }
} 


do_ioerr_test incrblob_err-4 -cksum 1 -sqlprep {
  CREATE TABLE blobs(k, v BLOB);
  INSERT INTO blobs VALUES(1, $::data);
} -tclbody {
  set ::blob [db incrblob blobs v 1]
  read $::blob
}

do_ioerr_test incrblob_err-5 -cksum 1 -sqlprep {
  CREATE TABLE blobs(k, v BLOB);
  INSERT INTO blobs VALUES(1, zeroblob(length(CAST($::data AS BLOB))));
} -tclbody {
  set ::blob [db incrblob blobs v 1]
  puts -nonewline $::blob $::data
  close $::blob
}

do_ioerr_test incrblob_err-6 -cksum 1 -sqlprep {
  CREATE TABLE blobs(k, v BLOB);
  INSERT INTO blobs VALUES(1, $::data || $::data || $::data);
} -tclbody {
  set ::blob [db incrblob blobs v 1]
  seek $::blob -20 end
  puts -nonewline $::blob "12345678900987654321"
  close $::blob
}

do_ioerr_test incrblob_err-7 -cksum 1 -sqlprep {
  PRAGMA auto_vacuum = 1;
  CREATE TABLE blobs(k INTEGER PRIMARY KEY, v BLOB);
  INSERT INTO blobs VALUES(1, zeroblob(500 * 1020));
} -tclbody {
  # Read some data from the end of the large blob inserted into table 
  # "blobs". This forces the IO error to occur while reading a pointer
  # map page for the purposes of seeking to the end of the blob.
  #
  sqlite3 db2 test.db
  set ::blob [db2 incrblob blobs v 1]
  sqlite3_blob_read $::blob [expr 500*1020-20] 20
  close $::blob
}
catch {db2 close}

do_ioerr_test incrblob_err-8 -cksum 1 -sqlprep {
  PRAGMA auto_vacuum = 1;
  CREATE TABLE blobs(k INTEGER PRIMARY KEY, v BLOB);
  INSERT INTO blobs VALUES(1, zeroblob(500 * 1020));
} -tclbody {
  # Read some data from the end of the large blob inserted into table 
  # "blobs". This forces the IO error to occur while reading a pointer
  # map page for the purposes of seeking to the end of the blob.
  #
  sqlite3 db2 test.db
  set ::blob [db2 incrblob blobs v 1]
  sqlite3_blob_write $::blob [expr 500*1020-20] 12345678900987654321
  close $::blob
}

catch {db2 close}

finish_test

Added test/incrvacuum.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# 2007 April 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the incremental vacuum feature.
#
# Note: There are also some tests for incremental vacuum and IO 
# errors in incrvacuum_ioerr.test.
#
# $Id: incrvacuum.test,v 1.23 2009/02/18 20:31:18 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If this build of the library does not support auto-vacuum, omit this
# whole file.
ifcapable {!autovacuum || !pragma} {
  finish_test
  return
}

#---------------------------------------------------------------------
# Test the pragma on an empty database.
#
do_test incrvacuum-1.1 {
  execsql {
    pragma auto_vacuum;
  }
} $sqlite_options(default_autovacuum)
do_test incrvacuum-1.2.0 {
  # File size is sometimes 1 instead of 0 due to the hack we put in
  # to work around ticket #3260.  Search for comments on #3260 in
  # os_unix.c.
  expr {[file size test.db] > 1}
} {0}
do_test incrvacuum-1.2 {
  # This command will create the database.
  execsql {
    pragma auto_vacuum = 'full';
    pragma auto_vacuum;
  }
} {1}
do_test incrvacuum-1.2.1 {
  expr {[file size test.db] > 0}
} {1}
do_test incrvacuum-1.3 {
  execsql {
    pragma auto_vacuum = 'incremental';
    pragma auto_vacuum;
  }
} {2}
do_test incrvacuum-1.4 {
  # In this case the invalid value is ignored and the auto_vacuum
  # setting remains unchanged.
  execsql {
    pragma auto_vacuum = 'invalid';
    pragma auto_vacuum;
  }
} {2}
do_test incrvacuum-1.5 {
  execsql {
    pragma auto_vacuum = 1;
    pragma auto_vacuum;
  }
} {1}
do_test incrvacuum-1.6 {
  execsql {
    pragma auto_vacuum = '2';
    pragma auto_vacuum;
  }
} {2}
do_test incrvacuum-1.7 {
  # Invalid value. auto_vacuum setting remains unchanged.
  execsql {
    pragma auto_vacuum = 5;
    pragma auto_vacuum;
  }
} {2}

#---------------------------------------------------------------------
# Test the pragma on a non-empty database. It is possible to toggle
# the connection between "full" and "incremental" mode, but not to
# change from either of these to "none", or from "none" to "full" or
# "incremental".
#
do_test incrvacuum-2.1 {
  execsql {
    pragma auto_vacuum = 1;
    CREATE TABLE abc(a, b, c);
  }
} {}
do_test incrvacuum-2.2 {
  execsql {
    pragma auto_vacuum = 'none';
    pragma auto_vacuum;
  }
} {1}
do_test incrvacuum-2.2.1 {
  db close
  sqlite3 db test.db
  execsql {
    pragma auto_vacuum;
  }
} {1}
do_test incrvacuum-2.3 {
  execsql {
    pragma auto_vacuum = 'incremental';
    pragma auto_vacuum;
  }
} {2}
do_test incrvacuum-2.4 {
  execsql {
    pragma auto_vacuum = 'full';
    pragma auto_vacuum;
  }
} {1}

#---------------------------------------------------------------------
# Test that when the auto_vacuum mode is "incremental", the database
# does not shrink when pages are removed from it. But it does if
# the mode is set to "full".
#
do_test incrvacuum-3.1 {
  execsql {
    pragma auto_vacuum;
  }
} {1}
do_test incrvacuum-3.2 {
  set ::str [string repeat 1234567890 110]
  execsql {
    PRAGMA auto_vacuum = 2;
    BEGIN;
    CREATE TABLE tbl2(str);
    INSERT INTO tbl2 VALUES($::str);
    COMMIT;
  }
  # 5 pages:
  #
  #   1 -> database header
  #   2 -> first back-pointer page
  #   3 -> table abc
  #   4 -> table tbl2
  #   5 -> table tbl2 overflow page.
  #
  expr {[file size test.db] / 1024}
} {5}
do_test incrvacuum-3.3 {
  execsql {
    DROP TABLE abc;
    DELETE FROM tbl2;
  }
  expr {[file size test.db] / 1024}
} {5}
do_test incrvacuum-3.4 {
  execsql {
    PRAGMA auto_vacuum = 1;
    INSERT INTO tbl2 VALUES('hello world');
  }
  expr {[file size test.db] / 1024}
} {3}

#---------------------------------------------------------------------
# Try to run a very simple incremental vacuum. Also verify that 
# PRAGMA incremental_vacuum is a harmless no-op against a database that
# does not support auto-vacuum.
#
do_test incrvacuum-4.1 {
  set ::str [string repeat 1234567890 110]
  execsql {
    PRAGMA auto_vacuum = 2;
    INSERT INTO tbl2 VALUES($::str);
    CREATE TABLE tbl1(a, b, c);
  }
  expr {[file size test.db] / 1024}
} {5}
do_test incrvacuum-4.2 {
  execsql {
    DELETE FROM tbl2;
    DROP TABLE tbl1;
  }
  expr {[file size test.db] / 1024}
} {5}
do_test incrvacuum-4.3 {
  set ::nStep 0
  db eval {pragma incremental_vacuum(10)} {
    incr ::nStep
  }
  list [expr {[file size test.db] / 1024}] $::nStep
} {3 2}

#---------------------------------------------------------------------
# The following tests - incrvacuum-5.* - test incremental vacuum
# from within a transaction.
#
do_test incrvacuum-5.1.1 {
  expr {[file size test.db] / 1024}
} {3}
do_test incrvacuum-5.1.2 {
  execsql {
    BEGIN;
    DROP TABLE tbl2;
    PRAGMA incremental_vacuum;
    COMMIT;
  }
  expr {[file size test.db] / 1024}
} {1}

do_test incrvacuum-5.2.1 {
  set ::str [string repeat abcdefghij 110]
  execsql {
    BEGIN;
    CREATE TABLE tbl1(a);
    INSERT INTO tbl1 VALUES($::str);
    PRAGMA incremental_vacuum;                 -- this is a no-op.
    COMMIT;
  }
  expr {[file size test.db] / 1024}
} {4}
do_test incrvacuum-5.2.2 {
  set ::str [string repeat abcdefghij 110]
  execsql {
    BEGIN;
    INSERT INTO tbl1 VALUES($::str);
    INSERT INTO tbl1 SELECT * FROM tbl1;
    DELETE FROM tbl1 WHERE oid%2;        -- Put 2 overflow pages on free-list.
    COMMIT;
  }
  expr {[file size test.db] / 1024}
} {7}
do_test incrvacuum-5.2.3 {
  execsql {
    BEGIN;
    PRAGMA incremental_vacuum;           -- Vacuum up the two pages.
    CREATE TABLE tbl2(b);                -- Use one free page as a table root.
    INSERT INTO tbl2 VALUES('a nice string');
    COMMIT;
  }
  expr {[file size test.db] / 1024}
} {6}
do_test incrvacuum-5.2.4 {
  execsql {
    SELECT * FROM tbl2;
  }
} {{a nice string}}
do_test incrvacuum-5.2.5 {
  execsql {
    DROP TABLE tbl1;
    DROP TABLE tbl2;
    PRAGMA incremental_vacuum;
  }
  expr {[file size test.db] / 1024}
} {1}


# Test cases incrvacuum-5.3.* use the following list as input data.
# Two new databases are opened, one with incremental vacuum enabled,
# the other with no auto-vacuum completely disabled. After executing
# each element of the following list on both databases, test that
# the integrity-check passes and the contents of each are identical.
# 
set TestScriptList [list {
  BEGIN;
  CREATE TABLE t1(a, b);
  CREATE TABLE t2(a, b);
  CREATE INDEX t1_i ON t1(a);
  CREATE INDEX t2_i ON t2(a);
} {
  INSERT INTO t1 VALUES($::str1, $::str2);
  INSERT INTO t1 VALUES($::str1||$::str2, $::str2||$::str1);
  INSERT INTO t2 SELECT b, a FROM t1;
  INSERT INTO t2 SELECT a, b FROM t1;
  INSERT INTO t1 SELECT b, a FROM t2;
  UPDATE t2 SET b = '';
  PRAGMA incremental_vacuum;
} {
  UPDATE t2 SET b = (SELECT b FROM t1 WHERE t1.oid = t2.oid);
  PRAGMA incremental_vacuum;
} {
  CREATE TABLE t3(a, b);
  INSERT INTO t3 SELECT * FROM t2;
  DROP TABLE t2;
  PRAGMA incremental_vacuum;
} {
  CREATE INDEX t3_i ON t3(a);
  COMMIT;
} {
  BEGIN;
  DROP INDEX t3_i;
  PRAGMA incremental_vacuum;
  INSERT INTO t3 VALUES('hello', 'world');
  ROLLBACK;
} {
  INSERT INTO t3 VALUES('hello', 'world');
}
]

# If this build omits subqueries, step 2 in the above list will not
# work. Replace it with "" in this case. 
#
ifcapable !subquery { lset TestScriptList 2 "" }

# Compare the contents of databases $A and $B.
#
proc compare_dbs {A B tname} {
  set tbl_list [execsql {
    SELECT tbl_name FROM sqlite_master WHERE type = 'table'
  } $A]

  do_test ${tname}.1 [subst {
    execsql {
      SELECT tbl_name FROM sqlite_master WHERE type = 'table'
    } $B
  }] $tbl_list

  set tn 1
  foreach tbl $tbl_list {
    set control [execsql "SELECT * FROM $tbl" $A]
    do_test ${tname}.[incr tn] [subst {
      execsql "SELECT * FROM $tbl" $B
    }] $control
  }
}

set ::str1 [string repeat abcdefghij 130]
set ::str2 [string repeat 1234567890 105]

file delete -force test1.db test1.db-journal test2.db test2.db-journal
sqlite3 db1 test1.db
sqlite3 db2 test2.db
execsql { PRAGMA auto_vacuum = 'none' } db1
execsql { PRAGMA auto_vacuum = 'incremental' } db2

set tn 1
foreach sql $::TestScriptList {
  execsql $sql db1
  execsql $sql db2

  compare_dbs db1 db2 incrvacuum-5.3.${tn}
  do_test incrvacuum-5.3.${tn}.integrity1 {
    execsql { PRAGMA integrity_check; } db1
  } {ok}
  do_test incrvacuum-5.3.${tn}.integrity2 {
    execsql { PRAGMA integrity_check; } db2
  } {ok}
  incr tn
}
db1 close
db2 close
#
# End of test cases 5.3.*

#---------------------------------------------------------------------
# The following tests - incrvacuum-6.* - test running incremental 
# vacuum while another statement (a read) is being executed.
#
for {set jj 0} {$jj < 10} {incr jj} {
  # Build some test data. Two tables are created in an empty
  # database. tbl1 data is a contiguous block starting at page 5 (pages
  # 3 and 4 are the table roots). tbl2 is a contiguous block starting 
  # right after tbl1.
  #
  # Then drop tbl1 so that when an incr vacuum is run the pages
  # of tbl2 have to be moved to fill the gap.
  #
  do_test incrvacuum-6.${jj}.1 {
    execsql {
      DROP TABLE IF EXISTS tbl1;
      DROP TABLE IF EXISTS tbl2;
      PRAGMA incremental_vacuum;
      CREATE TABLE tbl1(a, b);
      CREATE TABLE tbl2(a, b);
      BEGIN;
    }
    for {set ii 0} {$ii < 1000} {incr ii} {
      db eval {INSERT INTO tbl1 VALUES($ii, $ii || $ii)}
    }
    execsql {
      INSERT INTO tbl2 SELECT * FROM tbl1;
      COMMIT;
      DROP TABLE tbl1;
    }
    expr {[file size test.db] / 1024}
  } {36}

  # Run a linear scan query on tbl2. After reading ($jj*100) rows, 
  # run the incremental vacuum to shrink the database.
  #
  do_test incrvacuum-6.${jj}.2 {
    set ::nRow 0
    db eval {SELECT a FROM tbl2} {} {
      if {$a == [expr $jj*100]} {
        db eval {PRAGMA incremental_vacuum}
      }
      incr ::nRow
    }
    list [expr {[file size test.db] / 1024}] $nRow
  } {19 1000}
}

#---------------------------------------------------------------------
# This test - incrvacuum-7.* - is to check that the database can be
# written in the middle of an incremental vacuum.
#
set ::iWrite 1
while 1 {
  do_test incrvacuum-7.${::iWrite}.1 {
    execsql {
      DROP TABLE IF EXISTS tbl1;
      DROP TABLE IF EXISTS tbl2;
      PRAGMA incremental_vacuum;
      CREATE TABLE tbl1(a, b);
      CREATE TABLE tbl2(a, b);
      BEGIN;
    }
    for {set ii 0} {$ii < 1000} {incr ii} {
      db eval {INSERT INTO tbl1 VALUES($ii, $ii || $ii)}
    }
    execsql {
      INSERT INTO tbl2 SELECT * FROM tbl1;
      COMMIT;
      DROP TABLE tbl1;
    }
    expr {[file size test.db] / 1024}
  } {36}

  do_test incrvacuum-7.${::iWrite}.2 {
    set ::nRow 0
    db eval {PRAGMA incremental_vacuum} {
      incr ::nRow
      if {$::nRow == $::iWrite} {
        db eval {
          CREATE TABLE tbl1(a, b);
          INSERT INTO tbl1 VALUES('hello', 'world');
        }
      }
    }
    list [expr {[file size test.db] / 1024}]
  } {20}

  do_test incrvacuum-7.${::iWrite}.3 {
    execsql {
      SELECT * FROM tbl1;
    }
  } {hello world}

  if {$::nRow == $::iWrite} break
  incr ::iWrite
}

#---------------------------------------------------------------------
# This test - incrvacuum-8.* - is to check that nothing goes wrong
# with an incremental-vacuum if it is the first statement executed
# after an existing database is opened.
#
# At one point, this would always return SQLITE_SCHEMA (which 
# causes an infinite loop in tclsqlite.c if using the Tcl interface).
#
do_test incrvacuum-8.1 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA incremental_vacuum(50);
  }
} {}

#---------------------------------------------------------------------
# At one point this test case was causing an assert() to fail.
#
do_test incrvacuum-9.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db

  execsql {
    PRAGMA auto_vacuum = 'incremental';
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(a, b, c);
    INSERT INTO t2 VALUES(randstr(500,500),randstr(500,500),randstr(500,500));
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
    INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1;
  }
} {}

do_test incrvacuum-9.2 {
  execsql {
    PRAGMA synchronous = 'OFF';
    BEGIN;
    UPDATE t1 SET a = a, b = b, c = c;
    DROP TABLE t2;
    PRAGMA incremental_vacuum(10);
    ROLLBACK;
  }
} {}

do_test incrvacuum-9.3 {
  execsql {
    PRAGMA cache_size = 10;
    BEGIN;
    UPDATE t1 SET a = a, b = b, c = c;
    DROP TABLE t2;
    PRAGMA incremental_vacuum(10);
    ROLLBACK;
  }
} {}

#---------------------------------------------------------------------
# Test that the parameter to the incremental_vacuum pragma works. That
# is, if the user executes "PRAGMA incremental_vacuum(N)", at most
# N pages are vacuumed.
#
do_test incrvacuum-10.1 {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
  }
  expr [file size test.db] / 1024
} {29}

do_test incrvacuum-10.2 {
  execsql {
    PRAGMA incremental_vacuum(1);
  }
  expr [file size test.db] / 1024
} {28}

do_test incrvacuum-10.3 {
  execsql {
    PRAGMA incremental_vacuum(5);
  }
  expr [file size test.db] / 1024
} {23}

do_test incrvacuum-10.4 {
  execsql {
    PRAGMA incremental_vacuum('1');
  }
  expr [file size test.db] / 1024
} {22}

do_test incrvacuum-10.5 {
  execsql {
    PRAGMA incremental_vacuum("+3");
  }
  expr [file size test.db] / 1024
} {19}

do_test incrvacuum-10.6 {
  execsql {
    PRAGMA incremental_vacuum = 1;
  }
  expr [file size test.db] / 1024
} {18}

do_test incrvacuum-10.7 {
  # Use a really big number as an argument to incremetal_vacuum. Should
  # be interpreted as "free all possible space".
  execsql {
    PRAGMA incremental_vacuum(2147483649);
  }
  expr [file size test.db] / 1024
} {1}

do_test incrvacuum-10.8 {
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(hex(randomblob(1000)));
    DROP TABLE t1;
  }
  # A negative number means free all possible space.
  execsql {
    PRAGMA incremental_vacuum=-1;
  }
  expr [file size test.db] / 1024
} {1}

#----------------------------------------------------------------
# Test that if we set the auto_vacuum mode to 'incremental', then
# create a database, thereafter that database defaults to incremental 
# vacuum mode.
#
db close
file delete -force test.db test.db-journal
sqlite3 db test.db

ifcapable default_autovacuum {
  do_test incrvacuum-11.1-av-dflt-on {
    execsql {
      PRAGMA auto_vacuum;
    }
  } $AUTOVACUUM
} else {
  do_test incrvacuum-11.1-av-dflt-off {
    execsql {
      PRAGMA auto_vacuum;
    }
  } {0}
}
do_test incrvacuum-11.2 {
  execsql {
    PRAGMA auto_vacuum = incremental;
  }
} {}
do_test incrvacuum-11.3 {
  execsql {
    PRAGMA auto_vacuum;
  }
} {2}
do_test incrvacuum-11.4 {
  # The database has now been created.
  expr {[file size test.db]>0}
} {1}
do_test incrvacuum-11.5 {
  # Close and reopen the connection.
  db close
  sqlite3 db test.db

  # Test we are still in incremental vacuum mode.
  execsql { PRAGMA auto_vacuum; }
} {2}
do_test incrvacuum-11.6 {
  execsql {
    PRAGMA auto_vacuum = 'full';
    PRAGMA auto_vacuum;
  }
} {1}
do_test incrvacuum-11.7 {
  # Close and reopen the connection.
  db close
  sqlite3 db test.db

  # Test we are still in "full" auto-vacuum mode.
  execsql { PRAGMA auto_vacuum; }
} {1}

#----------------------------------------------------------------------
# Special case: What happens if the database is locked when a "PRAGMA
# auto_vacuum = XXX" statement is executed.
#
db close
file delete -force test.db test.db-journal
sqlite3 db test.db

do_test incrvacuum-12.1 {
  execsql {
    PRAGMA auto_vacuum = 1;
  }
  expr {[file size test.db]>0}
} {1}

# Try to change the auto-vacuum from "full" to "incremental" while the
# database is locked. Nothing should change.
#
do_test incrvacuum-12.2 {
  sqlite3 db2 test.db
  execsql { BEGIN EXCLUSIVE; } db2
  catchsql { PRAGMA auto_vacuum = 2; }
} {1 {database is locked}}

do_test incrvacuum-12.3 {
  execsql { ROLLBACK; } db2
  execsql { PRAGMA auto_vacuum }
} {2}   ;# Still 2 because PRAGMA auto_vacuum setting held in case of vacuum
do_test incrvacuum-12.4 {
  db close
  sqlite3 db test.db
  execsql { PRAGMA auto_vacuum }
} {1}   ;# Revert to 1 because the database file did not change

do_test incrvacuum-12.5 {
  execsql { SELECT * FROM sqlite_master }
  execsql { PRAGMA auto_vacuum }
} {1}

#----------------------------------------------------------------------
# Special case #2: What if one process prepares a "PRAGMA auto_vacuum = XXX"
# statement when the database is empty, but doesn't execute it until
# after some other process has created the database.
#
db2 close
db close
file delete -force test.db test.db-journal
sqlite3 db test.db  ;  set ::DB [sqlite3_connection_pointer db]
sqlite3 db2 test.db

do_test incrvacuum-13.1 {
  # File size is sometimes 1 instead of 0 due to the hack we put in
  # to work around ticket #3260.  Search for comments on #3260 in
  # os_unix.c.
  expr {[file size test.db]>1}
} {0}
do_test incrvacuum-13.2 {
  set ::STMT [sqlite3_prepare $::DB {PRAGMA auto_vacuum = 2} -1 DUMMY]
  execsql {
    PRAGMA auto_vacuum = none;
    PRAGMA default_cache_size = 1024;
    PRAGMA auto_vacuum;
  } db2
} {0}
do_test incrvacuum-13.3 {
  expr {[file size test.db]>0}
} {1}
do_test incrvacuum-13.4 {
  set rc [sqlite3_step $::STMT]
  list $rc [sqlite3_finalize $::STMT]
} {SQLITE_DONE SQLITE_OK}
do_test incrvacuum-13.5 {
  execsql {
    PRAGMA auto_vacuum;
  }
} {0}


# Verify that the incremental_vacuum pragma fails gracefully if it
# is used against an invalid database file.
#
do_test incrvacuum-14.1 {
  set out [open invalid.db w]
  puts $out "This is not an SQLite database file"
  close $out
  sqlite3 db3 invalid.db
  catchsql {
    PRAGMA incremental_vacuum(10);
  } db3
} {1 {file is encrypted or is not a database}}

do_test incrvacuum-15.1 {
  db close
  db2 close
  file delete -force test.db
  sqlite3 db test.db

  set str [string repeat "abcdefghij" 500]

  execsql {
    PRAGMA cache_size = 10;
    PRAGMA auto_vacuum = incremental;
    CREATE TABLE t1(x, y);
    INSERT INTO t1 VALUES('a', $str);
    INSERT INTO t1 VALUES('b', $str);
    INSERT INTO t1 VALUES('c', $str);
    INSERT INTO t1 VALUES('d', $str);
    INSERT INTO t1 VALUES('e', $str);
    INSERT INTO t1 VALUES('f', $str);
    INSERT INTO t1 VALUES('g', $str);
    INSERT INTO t1 VALUES('h', $str);
    INSERT INTO t1 VALUES('i', $str);
    INSERT INTO t1 VALUES('j', $str);
    INSERT INTO t1 VALUES('j', $str);

    CREATE TABLE t2(x PRIMARY KEY, y);
    INSERT INTO t2 VALUES('a', $str);
    INSERT INTO t2 VALUES('b', $str);
    INSERT INTO t2 VALUES('c', $str);
    INSERT INTO t2 VALUES('d', $str);

    BEGIN;
      DELETE FROM t2;
      PRAGMA incremental_vacuum;
  }

  catchsql {INSERT INTO t2 SELECT * FROM t1}

  execsql { 
    COMMIT;
    PRAGMA integrity_check;
  }
} {ok}

db3 close
finish_test

Added test/incrvacuum2.test.

















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# 2007 May 04
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the incremental vacuum feature.
#
# $Id: incrvacuum2.test,v 1.6 2009/07/25 13:42:50 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If this build of the library does not support auto-vacuum, omit this
# whole file.
ifcapable {!autovacuum || !pragma} {
  finish_test
  return
}


# Create a database in incremental vacuum mode that has many
# pages on the freelist.
#
do_test incrvacuum2-1.1 {
  execsql {
    PRAGMA page_size=1024;
    PRAGMA auto_vacuum=incremental;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(zeroblob(30000));
    DELETE FROM t1;
  }
  file size test.db
} {32768}

# Vacuum off a single page.
#
do_test incrvacuum2-1.2 {
  execsql {
    PRAGMA incremental_vacuum(1);
  }
  file size test.db
} {31744}

# Vacuum off five pages
#
do_test incrvacuum2-1.3 {
  execsql {
    PRAGMA incremental_vacuum(5);
  }
  file size test.db
} {26624}

# Vacuum off all the rest
#
do_test incrvacuum2-1.4 {
  execsql {
    PRAGMA incremental_vacuum(1000);
  }
  file size test.db
} {3072}

# Make sure incremental vacuum works on attached databases.
#
ifcapable attach {
  do_test incrvacuum2-2.1 {
    file delete -force test2.db test2.db-journal
    execsql {
      ATTACH DATABASE 'test2.db' AS aux;
      PRAGMA aux.auto_vacuum=incremental;
      CREATE TABLE aux.t2(x);
      INSERT INTO t2 VALUES(zeroblob(30000));
      INSERT INTO t1 SELECT * FROM t2;
      DELETE FROM t2;
      DELETE FROM t1;
    }
    list [file size test.db] [file size test2.db]
  } {32768 32768}
  do_test incrvacuum2-2.2 {
    execsql {
      PRAGMA aux.incremental_vacuum(1)
    }
    list [file size test.db] [file size test2.db]
  } {32768 31744}
  do_test incrvacuum2-2.3 {
    execsql {
      PRAGMA aux.incremental_vacuum(5)
    }
    list [file size test.db] [file size test2.db]
  } {32768 26624}
  do_test incrvacuum2-2.4 {
    execsql {
      PRAGMA main.incremental_vacuum(5)
    }
    list [file size test.db] [file size test2.db]
  } {27648 26624}
  do_test incrvacuum2-2.5 {
    execsql {
      PRAGMA aux.incremental_vacuum
    }
    list [file size test.db] [file size test2.db]
  } {27648 3072}
  do_test incrvacuum2-2.6 {
    execsql {
      PRAGMA incremental_vacuum(1)
    }
    list [file size test.db] [file size test2.db]
  } {26624 3072}
}

do_test incrvacuum2-3.1 {
  execsql {
    PRAGMA auto_vacuum = 'full';
    BEGIN;
    CREATE TABLE abc(a);
    INSERT INTO abc VALUES(randstr(1500,1500));
    COMMIT;
  }
} {}
do_test incrvacuum2-3.2 {
  execsql {
    BEGIN;
    DELETE FROM abc;
    PRAGMA incremental_vacuum;
    COMMIT;
  }
} {}

integrity_check incremental2-3.3

finish_test

Added test/incrvacuum_ioerr.test.











































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# 2001 October 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of I/O errors
# such as writes failing because the disk is full.
# 
# The tests in this file use special facilities that are only
# available in the SQLite test fixture.
#
# $Id: incrvacuum_ioerr.test,v 1.6 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If this build of the library does not support auto-vacuum, omit this
# whole file.
ifcapable {!autovacuum} {
  finish_test
  return
}

do_ioerr_test incrvacuum-ioerr-1 -cksum 1 -sqlprep {
  PRAGMA auto_vacuum = 'incremental';
  CREATE TABLE abc(a);
  INSERT INTO abc VALUES(randstr(1500,1500));
} -sqlbody {
  BEGIN;
  CREATE TABLE abc2(a);
  DELETE FROM abc;
  PRAGMA incremental_vacuum;
  COMMIT;
} 

# do_ioerr_test incrvacuum-ioerr-3 -start 1 -cksum 1 -tclprep {
#   db eval {
#     PRAGMA auto_vacuum = 'full';
#     PRAGMA cache_size = 10;
#     BEGIN;
#     CREATE TABLE abc(a, UNIQUE(a));
#   }
#   for {set ii 0} {$ii < 25} {incr ii} {
#     db eval {INSERT INTO abc VALUES(randstr(1500,1500))}
#   }
#   db eval COMMIT
# } -sqlbody {
#   BEGIN;
#   DELETE FROM abc WHERE (oid%3)==0;
#   INSERT INTO abc SELECT a || '1234567890' FROM abc WHERE oid%2;
#   CREATE INDEX abc_i ON abc(a);
#   DELETE FROM abc WHERE (oid%2)==0;
#   DROP INDEX abc_i;
#   COMMIT;
# }

do_ioerr_test incrvacuum-ioerr-2 -start 1 -cksum 1 -tclprep {
  db eval {
    PRAGMA auto_vacuum = 'full';
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE abc(a, UNIQUE(a));
  }
  for {set ii 0} {$ii < 25} {incr ii} {
    db eval {INSERT INTO abc VALUES(randstr(1500,1500))}
  }
  db eval COMMIT
} -sqlbody {
  BEGIN;
  PRAGMA incremental_vacuum;
  DELETE FROM abc WHERE (oid%3)==0;
  PRAGMA incremental_vacuum;
  INSERT INTO abc SELECT a || '1234567890' FROM abc WHERE oid%2;
  PRAGMA incremental_vacuum;
  CREATE INDEX abc_i ON abc(a);
  DELETE FROM abc WHERE (oid%2)==0;
  PRAGMA incremental_vacuum;
  DROP INDEX abc_i;
  PRAGMA incremental_vacuum;
  COMMIT;
}

do_ioerr_test incrvacuum-ioerr-3 -start 1 -cksum 1 -tclprep {
  db eval {
    PRAGMA auto_vacuum = 'incremental';
    BEGIN;
    CREATE TABLE a(i integer, b blob);
    INSERT INTO a VALUES(1, randstr(1500,1500));
    INSERT INTO a VALUES(2, randstr(1500,1500));
  }
  db eval COMMIT
  db eval {DELETE FROM a WHERE oid}
} -sqlbody {
  PRAGMA incremental_vacuum(5);
} -cleanup {
  sqlite3 db test.db
  integrity_check incrvacuum-ioerr-2.$n.integritycheck
  db close
}


ifcapable shared_cache {

  catch { db close }
  file delete -force test.db
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
  
  # Create two connections to a single shared-cache:
  #
  sqlite3 db1 test.db
  sqlite3 db2 test.db
  
  # Create a database with around 20 free pages.
  #
  do_test incrvacuum-ioerr-4.0 {
    execsql {
      PRAGMA page_size = 1024;
      PRAGMA locking_mode = exclusive;
      PRAGMA auto_vacuum = 'incremental';
      BEGIN;
      CREATE TABLE a(i integer, b blob);
    } db1
    for {set ii 0} {$ii < 20} {incr ii} {
      execsql { INSERT INTO a VALUES($ii, randstr(800,1500)); } db1
    }
    execsql COMMIT db1
    execsql {DELETE FROM a WHERE oid} db1
  } {}
  
  set ::rc 1
  for {set iTest 1} {$::rc && $iTest<2000} {incr iTest} {
  
    # Figure out how big the database is and how many free pages it
    # has before running incremental-vacuum.
    #
    set nPage [expr {[file size test.db]/1024}]
    set nFree [execsql {pragma freelist_count} db1]
  
    # Now run incremental-vacuum to vacuum 5 pages from the db file.
    # The iTest'th I/O call is set to fail.
    #
    set ::sqlite_io_error_pending $iTest
    set ::sqlite_io_error_persist 1
    do_test incrvacuum-ioerr-4.$iTest.1 {
      set ::rc [catch {execsql {pragma incremental_vacuum(5)} db1} msg]
      expr {$::rc==0 || $msg eq "disk I/O error"}
    } {1}
  
    set ::sqlite_io_error_pending 0
    set ::sqlite_io_error_persist 0
    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_hardhit 0
  
    set nFree2 [execsql {pragma freelist_count} db1]
    set nPage2 [expr {[file size test.db]/1024}]
  
    do_test incrvacuum-ioerr-4.$iTest.2 {
      set shrink [expr {$nPage-$nPage2}]
      expr {$shrink==0 || $shrink==5}
    } {1}
  
    do_test incrvacuum-ioerr-4.$iTest.3 {
      expr {$nPage - $nPage2}
    } [expr {$nFree - $nFree2}]
  }
  
  # Close the two database connections and restore the default
  # shared-cache mode setting.
  #
  db1 close
  db2 close
  sqlite3_enable_shared_cache $::enable_shared_cache
}

finish_test

Added test/index.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CREATE INDEX statement.
#
# $Id: index.test,v 1.43 2008/01/16 18:20:42 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a basic index and verify it is added to sqlite_master
#
do_test index-1.1 {
  execsql {CREATE TABLE test1(f1 int, f2 int, f3 int)}
  execsql {CREATE INDEX index1 ON test1(f1)}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {index1 test1}
do_test index-1.1b {
  execsql {SELECT name, sql, tbl_name, type FROM sqlite_master 
           WHERE name='index1'}
} {index1 {CREATE INDEX index1 ON test1(f1)} test1 index}
do_test index-1.1c {
  db close
  sqlite3 db test.db
  execsql {SELECT name, sql, tbl_name, type FROM sqlite_master 
           WHERE name='index1'}
} {index1 {CREATE INDEX index1 ON test1(f1)} test1 index}
do_test index-1.1d {
  db close
  sqlite3 db test.db
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {index1 test1}

# Verify that the index dies with the table
#
do_test index-1.2 {
  execsql {DROP TABLE test1}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {}

# Try adding an index to a table that does not exist
#
do_test index-2.1 {
  set v [catch {execsql {CREATE INDEX index1 ON test1(f1)}} msg]
  lappend v $msg
} {1 {no such table: main.test1}}

# Try adding an index on a column of a table where the table
# exists but the column does not.
#
do_test index-2.1 {
  execsql {CREATE TABLE test1(f1 int, f2 int, f3 int)}
  set v [catch {execsql {CREATE INDEX index1 ON test1(f4)}} msg]
  lappend v $msg
} {1 {table test1 has no column named f4}}

# Try an index with some columns that match and others that do now.
#
do_test index-2.2 {
  set v [catch {execsql {CREATE INDEX index1 ON test1(f1, f2, f4, f3)}} msg]
  execsql {DROP TABLE test1}
  lappend v $msg
} {1 {table test1 has no column named f4}}

# Try creating a bunch of indices on the same table
#
set r {}
for {set i 1} {$i<100} {incr i} {
  lappend r [format index%02d $i]
}
do_test index-3.1 {
  execsql {CREATE TABLE test1(f1 int, f2 int, f3 int, f4 int, f5 int)}
  for {set i 1} {$i<100} {incr i} {
    set sql "CREATE INDEX [format index%02d $i] ON test1(f[expr {($i%5)+1}])"
    execsql $sql
  }
  execsql {SELECT name FROM sqlite_master 
           WHERE type='index' AND tbl_name='test1'
           ORDER BY name}
} $r
integrity_check index-3.2.1
ifcapable {reindex} {
  do_test index-3.2.2 {
    execsql REINDEX
  } {}
}
integrity_check index-3.2.3


# Verify that all the indices go away when we drop the table.
#
do_test index-3.3 {
  execsql {DROP TABLE test1}
  execsql {SELECT name FROM sqlite_master 
           WHERE type='index' AND tbl_name='test1'
           ORDER BY name}
} {}

# Create a table and insert values into that table.  Then create
# an index on that table.  Verify that we can select values
# from the table correctly using the index.
#
# Note that the index names "index9" and "indext" are chosen because
# they both have the same hash.
#
do_test index-4.1 {
  execsql {CREATE TABLE test1(cnt int, power int)}
  for {set i 1} {$i<20} {incr i} {
    execsql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])"
  }
  execsql {CREATE INDEX index9 ON test1(cnt)}
  execsql {CREATE INDEX indext ON test1(power)}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {index9 indext test1}
do_test index-4.2 {
  execsql {SELECT cnt FROM test1 WHERE power=4}
} {2}
do_test index-4.3 {
  execsql {SELECT cnt FROM test1 WHERE power=1024}
} {10}
do_test index-4.4 {
  execsql {SELECT power FROM test1 WHERE cnt=6}
} {64}
do_test index-4.5 {
  execsql {DROP INDEX indext}
  execsql {SELECT power FROM test1 WHERE cnt=6}
} {64}
do_test index-4.6 {
  execsql {SELECT cnt FROM test1 WHERE power=1024}
} {10}
do_test index-4.7 {
  execsql {CREATE INDEX indext ON test1(cnt)}
  execsql {SELECT power FROM test1 WHERE cnt=6}
} {64}
do_test index-4.8 {
  execsql {SELECT cnt FROM test1 WHERE power=1024}
} {10}
do_test index-4.9 {
  execsql {DROP INDEX index9}
  execsql {SELECT power FROM test1 WHERE cnt=6}
} {64}
do_test index-4.10 {
  execsql {SELECT cnt FROM test1 WHERE power=1024}
} {10}
do_test index-4.11 {
  execsql {DROP INDEX indext}
  execsql {SELECT power FROM test1 WHERE cnt=6}
} {64}
do_test index-4.12 {
  execsql {SELECT cnt FROM test1 WHERE power=1024}
} {10}
do_test index-4.13 {
  execsql {DROP TABLE test1}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {}
integrity_check index-4.14

# Do not allow indices to be added to sqlite_master
#
do_test index-5.1 {
  set v [catch {execsql {CREATE INDEX index1 ON sqlite_master(name)}} msg]
  lappend v $msg
} {1 {table sqlite_master may not be indexed}}
do_test index-5.2 {
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {}

# Do not allow indices with duplicate names to be added
#
do_test index-6.1 {
  execsql {CREATE TABLE test1(f1 int, f2 int)}
  execsql {CREATE TABLE test2(g1 real, g2 real)}
  execsql {CREATE INDEX index1 ON test1(f1)}
  set v [catch {execsql {CREATE INDEX index1 ON test2(g1)}} msg]
  lappend v $msg
} {1 {index index1 already exists}}
do_test index-6.1.1 {
  catchsql {CREATE INDEX [index1] ON test2(g1)}
} {1 {index index1 already exists}}
do_test index-6.1b {
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {index1 test1 test2}
do_test index-6.1c {
  catchsql {CREATE INDEX IF NOT EXISTS index1 ON test1(f1)}
} {0 {}}
do_test index-6.2 {
  set v [catch {execsql {CREATE INDEX test1 ON test2(g1)}} msg]
  lappend v $msg
} {1 {there is already a table named test1}}
do_test index-6.2b {
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {index1 test1 test2}
do_test index-6.3 {
  execsql {DROP TABLE test1}
  execsql {DROP TABLE test2}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {}
do_test index-6.4 {
  execsql {
    CREATE TABLE test1(a,b);
    CREATE INDEX index1 ON test1(a);
    CREATE INDEX index2 ON test1(b);
    CREATE INDEX index3 ON test1(a,b);
    DROP TABLE test1;
    SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name;
  }
} {}
integrity_check index-6.5


# Create a primary key
#
do_test index-7.1 {
  execsql {CREATE TABLE test1(f1 int, f2 int primary key)}
  for {set i 1} {$i<20} {incr i} {
    execsql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])"
  }
  execsql {SELECT count(*) FROM test1}
} {19}
do_test index-7.2 {
  execsql {SELECT f1 FROM test1 WHERE f2=65536}
} {16}
do_test index-7.3 {
  execsql {
    SELECT name FROM sqlite_master 
    WHERE type='index' AND tbl_name='test1'
  }
} {sqlite_autoindex_test1_1}
do_test index-7.4 {
  execsql {DROP table test1}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {}
integrity_check index-7.5

# Make sure we cannot drop a non-existant index.
#
do_test index-8.1 {
  set v [catch {execsql {DROP INDEX index1}} msg]
  lappend v $msg
} {1 {no such index: index1}}

# Make sure we don't actually create an index when the EXPLAIN keyword
# is used.
#
do_test index-9.1 {
  execsql {CREATE TABLE tab1(a int)}
  ifcapable {explain} {
    execsql {EXPLAIN CREATE INDEX idx1 ON tab1(a)}
  }
  execsql {SELECT name FROM sqlite_master WHERE tbl_name='tab1'}
} {tab1}
do_test index-9.2 {
  execsql {CREATE INDEX idx1 ON tab1(a)}
  execsql {SELECT name FROM sqlite_master WHERE tbl_name='tab1' ORDER BY name}
} {idx1 tab1}
integrity_check index-9.3

# Allow more than one entry with the same key.
#
do_test index-10.0 {
  execsql {
    CREATE TABLE t1(a int, b int);
    CREATE INDEX i1 ON t1(a);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(2,4);
    INSERT INTO t1 VALUES(3,8);
    INSERT INTO t1 VALUES(1,12);
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {2 12}
do_test index-10.1 {
  execsql {
    SELECT b FROM t1 WHERE a=2 ORDER BY b;
  }
} {4}
do_test index-10.2 {
  execsql {
    DELETE FROM t1 WHERE b=12;
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {2}
do_test index-10.3 {
  execsql {
    DELETE FROM t1 WHERE b=2;
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {}
do_test index-10.4 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES (1,1);
    INSERT INTO t1 VALUES (1,2);
    INSERT INTO t1 VALUES (1,3);
    INSERT INTO t1 VALUES (1,4);
    INSERT INTO t1 VALUES (1,5);
    INSERT INTO t1 VALUES (1,6);
    INSERT INTO t1 VALUES (1,7);
    INSERT INTO t1 VALUES (1,8);
    INSERT INTO t1 VALUES (1,9);
    INSERT INTO t1 VALUES (2,0);
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {1 2 3 4 5 6 7 8 9}
do_test index-10.5 {
  ifcapable subquery {
    execsql { DELETE FROM t1 WHERE b IN (2, 4, 6, 8); }
  } else {
    execsql { DELETE FROM t1 WHERE b = 2 OR b = 4 OR b = 6 OR b = 8; }
  }
  execsql {
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {1 3 5 7 9}
do_test index-10.6 {
  execsql {
    DELETE FROM t1 WHERE b>2;
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {1}
do_test index-10.7 {
  execsql {
    DELETE FROM t1 WHERE b=1;
    SELECT b FROM t1 WHERE a=1 ORDER BY b;
  }
} {}
do_test index-10.8 {
  execsql {
    SELECT b FROM t1 ORDER BY b;
  }
} {0}
integrity_check index-10.9

# Automatically create an index when we specify a primary key.
#
do_test index-11.1 {
  execsql {
    CREATE TABLE t3(
      a text,
      b int,
      c float,
      PRIMARY KEY(b)
    );
  }
  for {set i 1} {$i<=50} {incr i} {
    execsql "INSERT INTO t3 VALUES('x${i}x',$i,0.$i)"
  }
  set sqlite_search_count 0
  concat [execsql {SELECT c FROM t3 WHERE b==10}] $sqlite_search_count
} {0.1 3}
integrity_check index-11.2


# Numeric strings should compare as if they were numbers.  So even if the
# strings are not character-by-character the same, if they represent the
# same number they should compare equal to one another.  Verify that this
# is true in indices.
#
# Updated for sqlite3 v3: SQLite will now store these values as numbers
# (because the affinity of column a is NUMERIC) so the quirky
# representations are not retained. i.e. '+1.0' becomes '1'.
do_test index-12.1 {
  execsql {
    CREATE TABLE t4(a NUM,b);
    INSERT INTO t4 VALUES('0.0',1);
    INSERT INTO t4 VALUES('0.00',2);
    INSERT INTO t4 VALUES('abc',3);
    INSERT INTO t4 VALUES('-1.0',4);
    INSERT INTO t4 VALUES('+1.0',5);
    INSERT INTO t4 VALUES('0',6);
    INSERT INTO t4 VALUES('00000',7);
    SELECT a FROM t4 ORDER BY b;
  }
} {0 0 abc -1 1 0 0}
do_test index-12.2 {
  execsql {
    SELECT a FROM t4 WHERE a==0 ORDER BY b
  }
} {0 0 0 0}
do_test index-12.3 {
  execsql {
    SELECT a FROM t4 WHERE a<0.5 ORDER BY b
  }
} {0 0 -1 0 0}
do_test index-12.4 {
  execsql {
    SELECT a FROM t4 WHERE a>-0.5 ORDER BY b
  }
} {0 0 abc 1 0 0}
do_test index-12.5 {
  execsql {
    CREATE INDEX t4i1 ON t4(a);
    SELECT a FROM t4 WHERE a==0 ORDER BY b
  }
} {0 0 0 0}
do_test index-12.6 {
  execsql {
    SELECT a FROM t4 WHERE a<0.5 ORDER BY b
  }
} {0 0 -1 0 0}
do_test index-12.7 {
  execsql {
    SELECT a FROM t4 WHERE a>-0.5 ORDER BY b
  }
} {0 0 abc 1 0 0}
integrity_check index-12.8

# Make sure we cannot drop an automatically created index.
#
do_test index-13.1 {
  execsql {
   CREATE TABLE t5(
      a int UNIQUE,
      b float PRIMARY KEY,
      c varchar(10),
      UNIQUE(a,c)
   );
   INSERT INTO t5 VALUES(1,2,3);
   SELECT * FROM t5;
  }
} {1 2.0 3}
do_test index-13.2 {
  set ::idxlist [execsql {
    SELECT name FROM sqlite_master WHERE type="index" AND tbl_name="t5";
  }]
  llength $::idxlist
} {3}
for {set i 0} {$i<[llength $::idxlist]} {incr i} {
  do_test index-13.3.$i {
    catchsql "
      DROP INDEX '[lindex $::idxlist $i]';
    "
  } {1 {index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped}}
}
do_test index-13.4 {
  execsql {
    INSERT INTO t5 VALUES('a','b','c');
    SELECT * FROM t5;
  }
} {1 2.0 3 a b c}
integrity_check index-13.5

# Check the sort order of data in an index.
#
do_test index-14.1 {
  execsql {
    CREATE TABLE t6(a,b,c);
    CREATE INDEX t6i1 ON t6(a,b);
    INSERT INTO t6 VALUES('','',1);
    INSERT INTO t6 VALUES('',NULL,2);
    INSERT INTO t6 VALUES(NULL,'',3);
    INSERT INTO t6 VALUES('abc',123,4);
    INSERT INTO t6 VALUES(123,'abc',5);
    SELECT c FROM t6 ORDER BY a,b;
  }
} {3 5 2 1 4}
do_test index-14.2 {
  execsql {
    SELECT c FROM t6 WHERE a='';
  }
} {2 1}
do_test index-14.3 {
  execsql {
    SELECT c FROM t6 WHERE b='';
  }
} {1 3}
do_test index-14.4 {
  execsql {
    SELECT c FROM t6 WHERE a>'';
  }
} {4}
do_test index-14.5 {
  execsql {
    SELECT c FROM t6 WHERE a>='';
  }
} {2 1 4}
do_test index-14.6 {
  execsql {
    SELECT c FROM t6 WHERE a>123;
  }
} {2 1 4}
do_test index-14.7 {
  execsql {
    SELECT c FROM t6 WHERE a>=123;
  }
} {5 2 1 4}
do_test index-14.8 {
  execsql {
    SELECT c FROM t6 WHERE a<'abc';
  }
} {5 2 1}
do_test index-14.9 {
  execsql {
    SELECT c FROM t6 WHERE a<='abc';
  }
} {5 2 1 4}
do_test index-14.10 {
  execsql {
    SELECT c FROM t6 WHERE a<='';
  }
} {5 2 1}
do_test index-14.11 {
  execsql {
    SELECT c FROM t6 WHERE a<'';
  }
} {5}
integrity_check index-14.12

do_test index-15.1 {
  execsql {
    DELETE FROM t1;
    SELECT * FROM t1;
  }
} {}
do_test index-15.2 {
  execsql {
    INSERT INTO t1 VALUES('1.234e5',1);
    INSERT INTO t1 VALUES('12.33e04',2);
    INSERT INTO t1 VALUES('12.35E4',3);
    INSERT INTO t1 VALUES('12.34e',4);
    INSERT INTO t1 VALUES('12.32e+4',5);
    INSERT INTO t1 VALUES('12.36E+04',6);
    INSERT INTO t1 VALUES('12.36E+',7);
    INSERT INTO t1 VALUES('+123.10000E+0003',8);
    INSERT INTO t1 VALUES('+',9);
    INSERT INTO t1 VALUES('+12347.E+02',10);
    INSERT INTO t1 VALUES('+12347E+02',11);
    SELECT b FROM t1 ORDER BY a;
  }
} {8 5 2 1 3 6 11 9 10 4 7}
integrity_check index-15.1

# The following tests - index-16.* - test that when a table definition
# includes qualifications that specify the same constraint twice only a
# single index is generated to enforce the constraint.
#
# For example: "CREATE TABLE abc( x PRIMARY KEY, UNIQUE(x) );"
#
do_test index-16.1 {
  execsql {
    CREATE TABLE t7(c UNIQUE PRIMARY KEY);
    SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index';
  }
} {1}
do_test index-16.2 {
  execsql {
    DROP TABLE t7;
    CREATE TABLE t7(c UNIQUE PRIMARY KEY);
    SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index';
  }
} {1}
do_test index-16.3 {
  execsql {
    DROP TABLE t7;
    CREATE TABLE t7(c PRIMARY KEY, UNIQUE(c) );
    SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index';
  }
} {1}
do_test index-16.4 {
  execsql {
    DROP TABLE t7;
    CREATE TABLE t7(c, d , UNIQUE(c, d), PRIMARY KEY(c, d) );
    SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index';
  }
} {1}
do_test index-16.5 {
  execsql {
    DROP TABLE t7;
    CREATE TABLE t7(c, d , UNIQUE(c), PRIMARY KEY(c, d) );
    SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index';
  }
} {2}

# Test that automatically create indices are named correctly. The current
# convention is: "sqlite_autoindex_<table name>_<integer>"
#
# Then check that it is an error to try to drop any automtically created
# indices.
do_test index-17.1 {
  execsql {
    DROP TABLE t7;
    CREATE TABLE t7(c, d UNIQUE, UNIQUE(c), PRIMARY KEY(c, d) );
    SELECT name FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index';
  }
} {sqlite_autoindex_t7_1 sqlite_autoindex_t7_2 sqlite_autoindex_t7_3}
do_test index-17.2 {
  catchsql {
    DROP INDEX sqlite_autoindex_t7_1;
  }
} {1 {index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped}}
do_test index-17.3 {
  catchsql {
    DROP INDEX IF EXISTS sqlite_autoindex_t7_1;
  }
} {1 {index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped}}
do_test index-17.4 {
  catchsql {
    DROP INDEX IF EXISTS no_such_index;
  }
} {0 {}}


# The following tests ensure that it is not possible to explicitly name
# a schema object with a name beginning with "sqlite_". Granted that is a
# little outside the focus of this test scripts, but this has got to be
# tested somewhere.
do_test index-18.1 {
  catchsql {
    CREATE TABLE sqlite_t1(a, b, c);
  }
} {1 {object name reserved for internal use: sqlite_t1}}
do_test index-18.2 {
  catchsql {
    CREATE INDEX sqlite_i1 ON t7(c);
  }
} {1 {object name reserved for internal use: sqlite_i1}}
ifcapable view {
do_test index-18.3 {
  catchsql {
    CREATE VIEW sqlite_v1 AS SELECT * FROM t7;
  }
} {1 {object name reserved for internal use: sqlite_v1}}
} ;# ifcapable view
ifcapable {trigger} {
  do_test index-18.4 {
    catchsql {
      CREATE TRIGGER sqlite_tr1 BEFORE INSERT ON t7 BEGIN SELECT 1; END;
    }
  } {1 {object name reserved for internal use: sqlite_tr1}}
}
do_test index-18.5 {
  execsql {
    DROP TABLE t7;
  }
} {}

# These tests ensure that if multiple table definition constraints are
# implemented by a single indice, the correct ON CONFLICT policy applies.
ifcapable conflict {
  do_test index-19.1 {
    execsql {
      CREATE TABLE t7(a UNIQUE PRIMARY KEY);
      CREATE TABLE t8(a UNIQUE PRIMARY KEY ON CONFLICT ROLLBACK);
      INSERT INTO t7 VALUES(1);
      INSERT INTO t8 VALUES(1);
    }
  } {}
  do_test index-19.2 {
    catchsql {
      BEGIN;
      INSERT INTO t7 VALUES(1);
    }
  } {1 {column a is not unique}}
  do_test index-19.3 {
    catchsql {
      BEGIN;
    }
  } {1 {cannot start a transaction within a transaction}}
  do_test index-19.4 {
    catchsql {
      INSERT INTO t8 VALUES(1);
    }
  } {1 {column a is not unique}}
  do_test index-19.5 {
    catchsql {
      BEGIN;
      COMMIT;
    }
  } {0 {}}
  do_test index-19.6 {
    catchsql {
      DROP TABLE t7;
      DROP TABLE t8;
      CREATE TABLE t7(
         a PRIMARY KEY ON CONFLICT FAIL, 
         UNIQUE(a) ON CONFLICT IGNORE
      );
    }
  } {1 {conflicting ON CONFLICT clauses specified}}
} ; # end of "ifcapable conflict" block

ifcapable {reindex} {
  do_test index-19.7 {
    execsql REINDEX
  } {}
}
integrity_check index-19.8

# Drop index with a quoted name.  Ticket #695.
#
do_test index-20.1 {
  execsql {
    CREATE INDEX "t6i2" ON t6(c);
    DROP INDEX "t6i2";
  }
} {}
do_test index-20.2 {
  execsql {
    DROP INDEX "t6i1";
  }
} {}
   

finish_test

Added test/index2.test.





















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 2005 January 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CREATE INDEX statement.
#
# $Id: index2.test,v 1.3 2006/03/03 19:12:30 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table with a large number of columns
#
do_test index2-1.1 {
  set sql {CREATE TABLE t1(}
  for {set i 1} {$i<1000} {incr i} {
    append sql "c$i,"
  }
  append sql "c1000);"
  execsql $sql
} {}
do_test index2-1.2 {
  set sql {INSERT INTO t1 VALUES(}
  for {set i 1} {$i<1000} {incr i} {
    append sql $i,
  }
  append sql {1000);}
  execsql $sql
} {}
do_test index2-1.3 {
  execsql {SELECT c123 FROM t1}
} 123
do_test index2-1.4 {
  execsql BEGIN
  for {set j 1} {$j<=100} {incr j} {
    set sql {INSERT INTO t1 VALUES(}
    for {set i 1} {$i<1000} {incr i} {
      append sql [expr {$j*10000+$i}],
    }
    append sql "[expr {$j*10000+1000}]);"
    execsql $sql
  }
  execsql COMMIT
  execsql {SELECT count(*) FROM t1}
} 101
do_test index2-1.5 {
  execsql {SELECT round(sum(c1000)) FROM t1}
} {50601000.0}

# Create indices with many columns
#
do_test index2-2.1 {
  set sql "CREATE INDEX t1i1 ON t1("
  for {set i 1} {$i<1000} {incr i} {
    append sql c$i,
  }
  append sql c1000)
  execsql $sql
} {}
do_test index2-2.2 {
  ifcapable explain {
    execsql {EXPLAIN SELECT c9 FROM t1 ORDER BY c1, c2, c3, c4, c5}
  }
  execsql {SELECT c9 FROM t1 ORDER BY c1, c2, c3, c4, c5, c6 LIMIT 5}
} {9 10009 20009 30009 40009}

finish_test

Added test/index3.test.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 2005 February 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CREATE INDEX statement.
#
# $Id: index3.test,v 1.3 2008/03/19 13:03:34 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Ticket #1115.  Make sure that when a UNIQUE index is created on a
# non-unique column (or columns) that it fails and that it leaves no
# residue behind.
#
do_test index3-1.1 {
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(1);
    SELECT * FROM t1;
  }
} {1 1}
do_test index3-1.2 {
  catchsql {
    BEGIN;
    CREATE UNIQUE INDEX i1 ON t1(a);
  }
} {1 {indexed columns are not unique}}
do_test index3-1.3 {
  catchsql COMMIT;
} {0 {}}
integrity_check index3-1.4

# This test corrupts the database file so it must be the last test
# in the series.
#
do_test index3-99.1 {
  execsql {
    PRAGMA writable_schema=on;
    UPDATE sqlite_master SET sql='nonsense';
  }
  db close
  sqlite3 db test.db
  catchsql {
    DROP INDEX i1;
  }
} {1 {malformed database schema (t1) - near "nonsense": syntax error}}

finish_test

Added test/indexedby.test.





























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# 2008 October 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: indexedby.test,v 1.5 2009/03/22 20:36:19 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a schema with some indexes.
#
do_test indexedby-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a);
    CREATE INDEX i2 ON t1(b);

    CREATE TABLE t2(c, d);
    CREATE INDEX i3 ON t2(c);
    CREATE INDEX i4 ON t2(d);

    CREATE TABLE t3(e PRIMARY KEY, f);

    CREATE VIEW v1 AS SELECT * FROM t1;
  }
} {}

# Explain Query Plan
#
proc EQP {sql} {
  uplevel "execsql {EXPLAIN QUERY PLAN $sql}"
}

# These tests are to check that "EXPLAIN QUERY PLAN" is working as expected.
#
do_test indexedby-1.2 {
  EQP { select * from t1 WHERE a = 10; }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-1.3 {
  EQP { select * from t1 ; }
} {0 0 {TABLE t1}}
do_test indexedby-1.4 {
  EQP { select * from t1, t2 WHERE c = 10; }
} {0 1 {TABLE t2 WITH INDEX i3} 1 0 {TABLE t1}}

# Parser tests. Test that an INDEXED BY or NOT INDEX clause can be 
# attached to a table in the FROM clause, but not to a sub-select or
# SQL view. Also test that specifying an index that does not exist or
# is attached to a different table is detected as an error.
# 
do_test indexedby-2.1 {
  execsql { SELECT * FROM t1 NOT INDEXED WHERE a = 'one' AND b = 'two'}
} {}
do_test indexedby-2.2 {
  execsql { SELECT * FROM t1 INDEXED BY i1 WHERE a = 'one' AND b = 'two'}
} {}
do_test indexedby-2.3 {
  execsql { SELECT * FROM t1 INDEXED BY i2 WHERE a = 'one' AND b = 'two'}
} {}

do_test indexedby-2.4 {
  catchsql { SELECT * FROM t1 INDEXED BY i3 WHERE a = 'one' AND b = 'two'}
} {1 {no such index: i3}}
do_test indexedby-2.5 {
  catchsql { SELECT * FROM t1 INDEXED BY i5 WHERE a = 'one' AND b = 'two'}
} {1 {no such index: i5}}
do_test indexedby-2.6 {
  catchsql { SELECT * FROM t1 INDEXED BY WHERE a = 'one' AND b = 'two'}
} {1 {near "WHERE": syntax error}}
do_test indexedby-2.7 {
  catchsql { SELECT * FROM v1 INDEXED BY i1 WHERE a = 'one' }
} {1 {no such index: i1}}

# Tests for single table cases.
#
do_test indexedby-3.1 {
  EQP { SELECT * FROM t1 NOT INDEXED WHERE a = 'one' AND b = 'two'}
} {0 0 {TABLE t1}}
do_test indexedby-3.2 {
  EQP { SELECT * FROM t1 INDEXED BY i1 WHERE a = 'one' AND b = 'two'}
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-3.3 {
  EQP { SELECT * FROM t1 INDEXED BY i2 WHERE a = 'one' AND b = 'two'}
} {0 0 {TABLE t1 WITH INDEX i2}}
do_test indexedby-3.4 {
  catchsql { SELECT * FROM t1 INDEXED BY i2 WHERE a = 'one' }
} {1 {cannot use index: i2}}
do_test indexedby-3.5 {
  catchsql { SELECT * FROM t1 INDEXED BY i2 ORDER BY a }
} {1 {cannot use index: i2}}
do_test indexedby-3.6 {
  catchsql { SELECT * FROM t1 INDEXED BY i1 WHERE a = 'one' }
} {0 {}}
do_test indexedby-3.7 {
  catchsql { SELECT * FROM t1 INDEXED BY i1 ORDER BY a }
} {0 {}}

do_test indexedby-3.8 {
  EQP { SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_1 ORDER BY e }
} {0 0 {TABLE t3 WITH INDEX sqlite_autoindex_t3_1 ORDER BY}}
do_test indexedby-3.9 {
  EQP { SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_1 WHERE e = 10 }
} {0 0 {TABLE t3 WITH INDEX sqlite_autoindex_t3_1}}
do_test indexedby-3.10 {
  catchsql { SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_1 WHERE f = 10 }
} {1 {cannot use index: sqlite_autoindex_t3_1}}
do_test indexedby-3.11 {
  catchsql { SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_2 WHERE f = 10 }
} {1 {no such index: sqlite_autoindex_t3_2}}

# Tests for multiple table cases.
#
do_test indexedby-4.1 {
  EQP { SELECT * FROM t1, t2 WHERE a = c }
} {0 0 {TABLE t1} 1 1 {TABLE t2 WITH INDEX i3}}
do_test indexedby-4.2 {
  EQP { SELECT * FROM t1 INDEXED BY i1, t2 WHERE a = c }
} {0 1 {TABLE t2} 1 0 {TABLE t1 WITH INDEX i1}}

# Test embedding an INDEXED BY in a CREATE VIEW statement. This block
# also tests that nothing bad happens if an index refered to by
# a CREATE VIEW statement is dropped and recreated.
#
do_test indexedby-5.1 {
  execsql {
    CREATE VIEW v2 AS SELECT * FROM t1 INDEXED BY i1 WHERE a > 5;
  }
  EQP { SELECT * FROM v2 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-5.2 {
  EQP { SELECT * FROM v2 WHERE b = 10 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-5.3 {
  execsql { DROP INDEX i1 }
  catchsql { SELECT * FROM v2 }
} {1 {no such index: i1}}
do_test indexedby-5.4 {
  # Recreate index i1 in such a way as it cannot be used by the view query.
  execsql { CREATE INDEX i1 ON t1(b) }
  catchsql { SELECT * FROM v2 }
} {1 {cannot use index: i1}}
do_test indexedby-5.5 {
  # Drop and recreate index i1 again. This time, create it so that it can
  # be used by the query.
  execsql { DROP INDEX i1 ; CREATE INDEX i1 ON t1(a) }
  catchsql { SELECT * FROM v2 }
} {0 {}}

# Test that "NOT INDEXED" may use the rowid index, but not others.
# 
do_test indexedby-6.1 {
  EQP { SELECT * FROM t1 WHERE b = 10 ORDER BY rowid }
} {0 0 {TABLE t1 WITH INDEX i2 ORDER BY}}
do_test indexedby-6.2 {
  EQP { SELECT * FROM t1 NOT INDEXED WHERE b = 10 ORDER BY rowid }
} {0 0 {TABLE t1 USING PRIMARY KEY ORDER BY}}

# Test that "INDEXED BY" can be used in a DELETE statement.
# 
do_test indexedby-7.1 {
  EQP { DELETE FROM t1 WHERE a = 5 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-7.2 {
  EQP { DELETE FROM t1 NOT INDEXED WHERE a = 5 }
} {0 0 {TABLE t1}}
do_test indexedby-7.3 {
  EQP { DELETE FROM t1 INDEXED BY i1 WHERE a = 5 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-7.4 {
  EQP { DELETE FROM t1 INDEXED BY i1 WHERE a = 5 AND b = 10}
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-7.5 {
  EQP { DELETE FROM t1 INDEXED BY i2 WHERE a = 5 AND b = 10}
} {0 0 {TABLE t1 WITH INDEX i2}}
do_test indexedby-7.6 {
  catchsql { DELETE FROM t1 INDEXED BY i2 WHERE a = 5}
} {1 {cannot use index: i2}}

# Test that "INDEXED BY" can be used in an UPDATE statement.
# 
do_test indexedby-8.1 {
  EQP { UPDATE t1 SET rowid=rowid+1 WHERE a = 5 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-8.2 {
  EQP { UPDATE t1 NOT INDEXED SET rowid=rowid+1 WHERE a = 5 }
} {0 0 {TABLE t1}}
do_test indexedby-8.3 {
  EQP { UPDATE t1 INDEXED BY i1 SET rowid=rowid+1 WHERE a = 5 }
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-8.4 {
  EQP { UPDATE t1 INDEXED BY i1 SET rowid=rowid+1 WHERE a = 5 AND b = 10}
} {0 0 {TABLE t1 WITH INDEX i1}}
do_test indexedby-8.5 {
  EQP { UPDATE t1 INDEXED BY i2 SET rowid=rowid+1 WHERE a = 5 AND b = 10}
} {0 0 {TABLE t1 WITH INDEX i2}}
do_test indexedby-8.6 {
  catchsql { UPDATE t1 INDEXED BY i2 SET rowid=rowid+1 WHERE a = 5}
} {1 {cannot use index: i2}}

# Test that bug #3560 is fixed.
#
do_test indexedby-9.1 {
  execsql {
    CREATE TABLE maintable( id integer);
    CREATE TABLE joinme(id_int integer, id_text text);
    CREATE INDEX joinme_id_text_idx on joinme(id_text);
    CREATE INDEX joinme_id_int_idx on joinme(id_int);
  }
} {}
do_test indexedby-9.2 {
  catchsql {
    select * from maintable as m inner join
    joinme as j indexed by joinme_id_text_idx
    on ( m.id  = j.id_int)
  }
} {1 {cannot use index: joinme_id_text_idx}}
do_test indexedby-9.3 {
  catchsql { select * from maintable, joinme INDEXED by joinme_id_text_idx }
} {1 {cannot use index: joinme_id_text_idx}}

# Make sure we can still create tables, indices, and columns whose name
# is "indexed".
#
do_test indexedby-10.1 {
  execsql {
    CREATE TABLE indexed(x,y);
    INSERT INTO indexed VALUES(1,2);
    SELECT * FROM indexed;
  }
} {1 2}
do_test indexedby-10.2 {
  execsql {
    CREATE INDEX i10 ON indexed(x);
    SELECT * FROM indexed indexed by i10 where x>0;
  }
} {1 2}
do_test indexedby-10.3 {
  execsql {
    DROP TABLE indexed;
    CREATE TABLE t10(indexed INTEGER);
    INSERT INTO t10 VALUES(1);
    CREATE INDEX indexed ON t10(indexed);
    SELECT * FROM t10 indexed by indexed WHERE indexed>0
  }
} {1}

finish_test

Added test/init.test.































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the effects of a failure in 
# sqlite3_initialize().
#
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db close

foreach {t failed rc started} {
  1.1 {}       SQLITE_OK    {mutex mem pcache}
  1.2 {mutex}  SQLITE_ERROR {}
  1.3 {mem}    SQLITE_ERROR {mutex}
  1.4 {pcache} SQLITE_ERROR {mutex mem}
} {
  do_test init-$t.1 {
    eval init_wrapper_install $failed
    sqlite3_initialize
  } $rc
  do_test init-$t.2 {
    init_wrapper_query
  } $started
  do_test init-$t.3 {
    sqlite3_shutdown
    init_wrapper_query
  } {}
  do_test init-$t.4 {
    sqlite3_initialize
  } $rc
  do_test init-$t.5 {
    init_wrapper_query
  } $started
  do_test init-$t.6 {
    init_wrapper_clear
    sqlite3_initialize
  } SQLITE_OK
  do_test init-$t.7 {
    init_wrapper_query
  } {mutex mem pcache}
  do_test init-$t.8 {
    init_wrapper_uninstall
  } {}
}

source $testdir/malloc_common.tcl
if {$MEMDEBUG} {
  do_malloc_test init-2 -tclprep {
    db close
    init_wrapper_install
  } -tclbody {
    set rc [sqlite3_initialize]
    if {[string match "SQLITE*NOMEM" $rc]} {error "out of memory"}
  } -cleanup {
    set zRepeat "transient"
    if {$::iRepeat} {set zRepeat "persistent"}
    do_test init-2.$zRepeat.$::n.x {
      init_wrapper_clear
      sqlite3_initialize
    } SQLITE_OK
    init_wrapper_uninstall
  }
}

autoinstall_test_functions
finish_test

Added test/insert.test.















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the INSERT statement.
#
# $Id: insert.test,v 1.31 2007/04/05 11:25:59 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Try to insert into a non-existant table.
#
do_test insert-1.1 {
  set v [catch {execsql {INSERT INTO test1 VALUES(1,2,3)}} msg]
  lappend v $msg
} {1 {no such table: test1}}

# Try to insert into sqlite_master
#
do_test insert-1.2 {
  set v [catch {execsql {INSERT INTO sqlite_master VALUES(1,2,3,4)}} msg]
  lappend v $msg
} {1 {table sqlite_master may not be modified}}

# Try to insert the wrong number of entries.
#
do_test insert-1.3 {
  execsql {CREATE TABLE test1(one int, two int, three int)}
  set v [catch {execsql {INSERT INTO test1 VALUES(1,2)}} msg]
  lappend v $msg
} {1 {table test1 has 3 columns but 2 values were supplied}}
do_test insert-1.3b {
  set v [catch {execsql {INSERT INTO test1 VALUES(1,2,3,4)}} msg]
  lappend v $msg
} {1 {table test1 has 3 columns but 4 values were supplied}}
do_test insert-1.3c {
  set v [catch {execsql {INSERT INTO test1(one,two) VALUES(1,2,3,4)}} msg]
  lappend v $msg
} {1 {4 values for 2 columns}}
do_test insert-1.3d {
  set v [catch {execsql {INSERT INTO test1(one,two) VALUES(1)}} msg]
  lappend v $msg
} {1 {1 values for 2 columns}}

# Try to insert into a non-existant column of a table.
#
do_test insert-1.4 {
  set v [catch {execsql {INSERT INTO test1(one,four) VALUES(1,2)}} msg]
  lappend v $msg
} {1 {table test1 has no column named four}}

# Make sure the inserts actually happen
#
do_test insert-1.5 {
  execsql {INSERT INTO test1 VALUES(1,2,3)}
  execsql {SELECT * FROM test1}
} {1 2 3}
do_test insert-1.5b {
  execsql {INSERT INTO test1 VALUES(4,5,6)}
  execsql {SELECT * FROM test1 ORDER BY one}
} {1 2 3 4 5 6}
do_test insert-1.5c {
  execsql {INSERT INTO test1 VALUES(7,8,9)}
  execsql {SELECT * FROM test1 ORDER BY one}
} {1 2 3 4 5 6 7 8 9}

do_test insert-1.6 {
  execsql {DELETE FROM test1}
  execsql {INSERT INTO test1(one,two) VALUES(1,2)}
  execsql {SELECT * FROM test1 ORDER BY one}
} {1 2 {}}
do_test insert-1.6b {
  execsql {INSERT INTO test1(two,three) VALUES(5,6)}
  execsql {SELECT * FROM test1 ORDER BY one}
} {{} 5 6 1 2 {}}
do_test insert-1.6c {
  execsql {INSERT INTO test1(three,one) VALUES(7,8)}
  execsql {SELECT * FROM test1 ORDER BY one}
} {{} 5 6 1 2 {} 8 {} 7}

# A table to use for testing default values
#
do_test insert-2.1 {
  execsql {
    CREATE TABLE test2(
      f1 int default -111, 
      f2 real default +4.32,
      f3 int default +222,
      f4 int default 7.89
    )
  }
  execsql {SELECT * from test2}
} {}
do_test insert-2.2 {
  execsql {INSERT INTO test2(f1,f3) VALUES(+10,-10)}
  execsql {SELECT * FROM test2}
} {10 4.32 -10 7.89}
do_test insert-2.3 {
  execsql {INSERT INTO test2(f2,f4) VALUES(1.23,-3.45)}
  execsql {SELECT * FROM test2 WHERE f1==-111}
} {-111 1.23 222 -3.45}
do_test insert-2.4 {
  execsql {INSERT INTO test2(f1,f2,f4) VALUES(77,+1.23,3.45)}
  execsql {SELECT * FROM test2 WHERE f1==77}
} {77 1.23 222 3.45}
do_test insert-2.10 {
  execsql {
    DROP TABLE test2;
    CREATE TABLE test2(
      f1 int default 111, 
      f2 real default -4.32,
      f3 text default hi,
      f4 text default 'abc-123',
      f5 varchar(10)
    )
  }
  execsql {SELECT * from test2}
} {}
do_test insert-2.11 {
  execsql {INSERT INTO test2(f2,f4) VALUES(-2.22,'hi!')}
  execsql {SELECT * FROM test2}
} {111 -2.22 hi hi! {}}
do_test insert-2.12 {
  execsql {INSERT INTO test2(f1,f5) VALUES(1,'xyzzy')}
  execsql {SELECT * FROM test2 ORDER BY f1}
} {1 -4.32 hi abc-123 xyzzy 111 -2.22 hi hi! {}}

# Do additional inserts with default values, but this time
# on a table that has indices.  In particular we want to verify
# that the correct default values are inserted into the indices.
#
do_test insert-3.1 {
  execsql {
    DELETE FROM test2;
    CREATE INDEX index9 ON test2(f1,f2);
    CREATE INDEX indext ON test2(f4,f5);
    SELECT * from test2;
  }
} {}

# Update for sqlite3 v3:
# Change the 111 to '111' in the following two test cases, because
# the default value is being inserted as a string. TODO: It shouldn't be.
do_test insert-3.2 {
  execsql {INSERT INTO test2(f2,f4) VALUES(-3.33,'hum')}
  execsql {SELECT * FROM test2 WHERE f1='111' AND f2=-3.33}
} {111 -3.33 hi hum {}}
do_test insert-3.3 {
  execsql {INSERT INTO test2(f1,f2,f5) VALUES(22,-4.44,'wham')}
  execsql {SELECT * FROM test2 WHERE f1='111' AND f2=-3.33}
} {111 -3.33 hi hum {}}
do_test insert-3.4 {
  execsql {SELECT * FROM test2 WHERE f1=22 AND f2=-4.44}
} {22 -4.44 hi abc-123 wham}
ifcapable {reindex} {
  do_test insert-3.5 {
    execsql REINDEX
  } {}
}
integrity_check insert-3.5

# Test of expressions in the VALUES clause
#
do_test insert-4.1 {
  execsql {
    CREATE TABLE t3(a,b,c);
    INSERT INTO t3 VALUES(1+2+3,4,5);
    SELECT * FROM t3;
  }
} {6 4 5}
do_test insert-4.2 {
  ifcapable subquery {
    execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1,5,6);}
  } else {
    set maxa [execsql {SELECT max(a) FROM t3}]
    execsql "INSERT INTO t3 VALUES($maxa+1,5,6);"
  }
  execsql {
    SELECT * FROM t3 ORDER BY a;
  }
} {6 4 5 7 5 6}
ifcapable subquery {
  do_test insert-4.3 {
    catchsql {
      INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1,t3.a,6);
      SELECT * FROM t3 ORDER BY a;
    }
  } {1 {no such column: t3.a}}
}
do_test insert-4.4 {
  ifcapable subquery {
    execsql {INSERT INTO t3 VALUES((SELECT b FROM t3 WHERE a=0),6,7);}
  } else {
    set b [execsql {SELECT b FROM t3 WHERE a = 0}]
    if {$b==""} {set b NULL}
    execsql "INSERT INTO t3 VALUES($b,6,7);"
  }
  execsql {
    SELECT * FROM t3 ORDER BY a;
  }
} {{} 6 7 6 4 5 7 5 6}
do_test insert-4.5 {
  execsql {
    SELECT b,c FROM t3 WHERE a IS NULL;
  }
} {6 7}
do_test insert-4.6 {
  catchsql {
    INSERT INTO t3 VALUES(notafunc(2,3),2,3);
  }
} {1 {no such function: notafunc}}
do_test insert-4.7 {
  execsql {
    INSERT INTO t3 VALUES(min(1,2,3),max(1,2,3),99);
    SELECT * FROM t3 WHERE c=99;
  }
} {1 3 99}

# Test the ability to insert from a temporary table into itself.
# Ticket #275.
#
ifcapable tempdb {
  do_test insert-5.1 {
    execsql {
      CREATE TEMP TABLE t4(x);
      INSERT INTO t4 VALUES(1);
      SELECT * FROM t4;
    }
  } {1}
  do_test insert-5.2 {
    execsql {
      INSERT INTO t4 SELECT x+1 FROM t4;
      SELECT * FROM t4;
    }
  } {1 2}
  ifcapable {explain} {
    do_test insert-5.3 {
      # verify that a temporary table is used to copy t4 to t4
      set x [execsql {
        EXPLAIN INSERT INTO t4 SELECT x+2 FROM t4;
      }]
      expr {[lsearch $x OpenEphemeral]>0}
    } {1}
  }
  
  do_test insert-5.4 {
    # Verify that table "test1" begins on page 3.  This should be the same
    # page number used by "t4" above.
    #
    # Update for v3 - the first table now begins on page 2 of each file, not 3.
    execsql {
      SELECT rootpage FROM sqlite_master WHERE name='test1';
    }
  } [expr $AUTOVACUUM?3:2]
  do_test insert-5.5 {
    # Verify that "t4" begins on page 3.
    #
    # Update for v3 - the first table now begins on page 2 of each file, not 3.
    execsql {
      SELECT rootpage FROM sqlite_temp_master WHERE name='t4';
    }
  } {2}
  do_test insert-5.6 {
    # This should not use an intermediate temporary table.
    execsql {
      INSERT INTO t4 SELECT one FROM test1 WHERE three=7;
      SELECT * FROM t4
    }
  } {1 2 8}
  ifcapable {explain} {
    do_test insert-5.7 {
      # verify that no temporary table is used to copy test1 to t4
      set x [execsql {
        EXPLAIN INSERT INTO t4 SELECT one FROM test1;
      }]
      expr {[lsearch $x OpenTemp]>0}
    } {0}
  }
}

# Ticket #334:  REPLACE statement corrupting indices.
#
ifcapable conflict {
  # The REPLACE command is not available if SQLITE_OMIT_CONFLICT is 
  # defined at compilation time.
  do_test insert-6.1 {
    execsql {
      CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE);
      INSERT INTO t1 VALUES(1,2);
      INSERT INTO t1 VALUES(2,3);
      SELECT b FROM t1 WHERE b=2;
    }
  } {2}
  do_test insert-6.2 {
    execsql {
      REPLACE INTO t1 VALUES(1,4);
      SELECT b FROM t1 WHERE b=2;
    }
  } {}
  do_test insert-6.3 {
    execsql {
      UPDATE OR REPLACE t1 SET a=2 WHERE b=4;
      SELECT * FROM t1 WHERE b=4;
    }
  } {2 4}
  do_test insert-6.4 {
    execsql {
      SELECT * FROM t1 WHERE b=3;
    }
  } {}
  ifcapable {reindex} {
    do_test insert-6.5 {
      execsql REINDEX
    } {}
  }
  do_test insert-6.6 {
    execsql {
      DROP TABLE t1;
    }
  } {}
}

# Test that the special optimization for queries of the form 
# "SELECT max(x) FROM tbl" where there is an index on tbl(x) works with 
# INSERT statments.
do_test insert-7.1 {
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    CREATE INDEX i1 ON t1(a);
  }
} {}
do_test insert-7.2 {
  execsql {
    INSERT INTO t1 SELECT max(a) FROM t1;
  }
} {}
do_test insert-7.3 {
  execsql {
    SELECT a FROM t1;
  }
} {1 2 2}

# Ticket #1140:  Check for an infinite loop in the algorithm that tests
# to see if the right-hand side of an INSERT...SELECT references the left-hand
# side.
#
ifcapable subquery&&compound {
  do_test insert-8.1 {
    execsql {
      INSERT INTO t3 SELECT * FROM (SELECT * FROM t3 UNION ALL SELECT 1,2,3)
    }
  } {}
}

# Make sure the rowid cache in the VDBE is reset correctly when
# an explicit rowid is given.
#
do_test insert-9.1 {
  execsql {
    CREATE TABLE t5(x);
    INSERT INTO t5 VALUES(1);
    INSERT INTO t5 VALUES(2);
    INSERT INTO t5 VALUES(3);
    INSERT INTO t5(rowid, x) SELECT nullif(x*2+10,14), x+100 FROM t5;
    SELECT rowid, x FROM t5;
  }
} {1 1 2 2 3 3 12 101 13 102 16 103}
do_test insert-9.2 {
  execsql {
    CREATE TABLE t6(x INTEGER PRIMARY KEY, y);
    INSERT INTO t6 VALUES(1,1);
    INSERT INTO t6 VALUES(2,2);
    INSERT INTO t6 VALUES(3,3);
    INSERT INTO t6 SELECT nullif(y*2+10,14), y+100 FROM t6;
    SELECT x, y FROM t6;
  }
} {1 1 2 2 3 3 12 101 13 102 16 103}

integrity_check insert-99.0

finish_test

Added test/insert2.test.













































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the INSERT statement that takes is
# result from a SELECT.
#
# $Id: insert2.test,v 1.19 2008/01/16 18:20:42 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create some tables with data that we can select against
#
do_test insert2-1.0 {
  execsql {CREATE TABLE d1(n int, log int);}
  for {set i 1} {$i<=20} {incr i} {
    for {set j 0} {(1<<$j)<$i} {incr j} {}
    execsql "INSERT INTO d1 VALUES($i,$j)"
  }
  execsql {SELECT * FROM d1 ORDER BY n}
} {1 0 2 1 3 2 4 2 5 3 6 3 7 3 8 3 9 4 10 4 11 4 12 4 13 4 14 4 15 4 16 4 17 5 18 5 19 5 20 5}

# Insert into a new table from the old one.
#
do_test insert2-1.1.1 {
  execsql {
    CREATE TABLE t1(log int, cnt int);
    PRAGMA count_changes=on;
  }
  ifcapable explain {
    execsql {
      EXPLAIN INSERT INTO t1 SELECT log, count(*) FROM d1 GROUP BY log;
    }
  }
  execsql {
    INSERT INTO t1 SELECT log, count(*) FROM d1 GROUP BY log;
  }
} {6}
do_test insert2-1.1.2 {
  db changes
} {6}
do_test insert2-1.1.3 {
  execsql {SELECT * FROM t1 ORDER BY log}
} {0 1 1 1 2 2 3 4 4 8 5 4}

ifcapable compound {
do_test insert2-1.2.1 {
  catch {execsql {DROP TABLE t1}}
  execsql {
    CREATE TABLE t1(log int, cnt int);
    INSERT INTO t1 
       SELECT log, count(*) FROM d1 GROUP BY log
       EXCEPT SELECT n-1,log FROM d1;
  }
} {4}
do_test insert2-1.2.2 {
  execsql {
    SELECT * FROM t1 ORDER BY log;
  }
} {0 1 3 4 4 8 5 4}
do_test insert2-1.3.1 {
  catch {execsql {DROP TABLE t1}}
  execsql {
    CREATE TABLE t1(log int, cnt int);
    PRAGMA count_changes=off;
    INSERT INTO t1 
       SELECT log, count(*) FROM d1 GROUP BY log
       INTERSECT SELECT n-1,log FROM d1;
  }
} {}
do_test insert2-1.3.2 {
  execsql {
    SELECT * FROM t1 ORDER BY log;
  }
} {1 1 2 2}
} ;# ifcapable compound
execsql {PRAGMA count_changes=off;}

do_test insert2-1.4 {
  catch {execsql {DROP TABLE t1}}
  set r [execsql {
    CREATE TABLE t1(log int, cnt int);
    CREATE INDEX i1 ON t1(log);
    CREATE INDEX i2 ON t1(cnt);
    INSERT INTO t1 SELECT log, count() FROM d1 GROUP BY log;
    SELECT * FROM t1 ORDER BY log;
  }]
  lappend r [execsql {SELECT cnt FROM t1 WHERE log=3}]
  lappend r [execsql {SELECT log FROM t1 WHERE cnt=4 ORDER BY log}]
} {0 1 1 1 2 2 3 4 4 8 5 4 4 {3 5}}

do_test insert2-2.0 {
  execsql {
    CREATE TABLE t3(a,b,c);
    CREATE TABLE t4(x,y);
    INSERT INTO t4 VALUES(1,2);
    SELECT * FROM t4;
  }
} {1 2}
do_test insert2-2.1 {
  execsql {
    INSERT INTO t3(a,c) SELECT * FROM t4;
    SELECT * FROM t3;
  }
} {1 {} 2}
do_test insert2-2.2 {
  execsql {
    DELETE FROM t3;
    INSERT INTO t3(c,b) SELECT * FROM t4;
    SELECT * FROM t3;
  }
} {{} 2 1}
do_test insert2-2.3 {
  execsql {
    DELETE FROM t3;
    INSERT INTO t3(c,a,b) SELECT x, 'hi', y FROM t4;
    SELECT * FROM t3;
  }
} {hi 2 1}

integrity_check insert2-3.0

# File table t4 with lots of data
#
do_test insert2-3.1 {
  execsql {
    SELECT * from t4;
  }
} {1 2}
do_test insert2-3.2 {
  set x [db total_changes]
  execsql {
    BEGIN;
    INSERT INTO t4 VALUES(2,4);
    INSERT INTO t4 VALUES(3,6);
    INSERT INTO t4 VALUES(4,8);
    INSERT INTO t4 VALUES(5,10);
    INSERT INTO t4 VALUES(6,12);
    INSERT INTO t4 VALUES(7,14);
    INSERT INTO t4 VALUES(8,16);
    INSERT INTO t4 VALUES(9,18);
    INSERT INTO t4 VALUES(10,20);
    COMMIT;
  }
  expr [db total_changes] - $x
} {9}
do_test insert2-3.2.1 {
  execsql {
    SELECT count(*) FROM t4;
  }
} {10}
do_test insert2-3.3 {
  ifcapable subquery {
    execsql {
      BEGIN;
      INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4;
      INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4;
      INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4;
      INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4;
      COMMIT;
      SELECT count(*) FROM t4;
    }
  } else {
    db function max_x_t4 {execsql {SELECT max(x) FROM t4}}
    execsql {
      BEGIN;
      INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4;
      INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4;
      INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4;
      INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4;
      COMMIT;
      SELECT count(*) FROM t4;
    }
  }
} {160}
do_test insert2-3.4 {
  execsql {
    BEGIN;
    UPDATE t4 SET y='lots of data for the row where x=' || x
                     || ' and y=' || y || ' - even more data to fill space';
    COMMIT;
    SELECT count(*) FROM t4;
  }
} {160}
do_test insert2-3.5 {
  ifcapable subquery {
    execsql {
      BEGIN;
      INSERT INTO t4 SELECT x+(SELECT max(x)+1 FROM t4),y FROM t4;
      SELECT count(*) from t4;
      ROLLBACK;
    }
  } else {
    execsql {
      BEGIN;
      INSERT INTO t4 SELECT x+max_x_t4()+1,y FROM t4;
      SELECT count(*) from t4;
      ROLLBACK;
    }
  }
} {320}
do_test insert2-3.6 {
  execsql {
    SELECT count(*) FROM t4;
  }
} {160}
do_test insert2-3.7 {
  execsql {
    BEGIN;
    DELETE FROM t4 WHERE x!=123;
    SELECT count(*) FROM t4;
    ROLLBACK;
  }
} {1}
do_test insert2-3.8 {
  db changes
} {159}
integrity_check insert2-3.9

# Ticket #901
#
ifcapable tempdb {
  do_test insert2-4.1 {
    execsql {
      CREATE TABLE Dependencies(depId integer primary key,
        class integer, name str, flag str);
      CREATE TEMPORARY TABLE DepCheck(troveId INT, depNum INT,
        flagCount INT, isProvides BOOL, class INTEGER, name STRING,
        flag STRING);
      INSERT INTO DepCheck 
         VALUES(-1, 0, 1, 0, 2, 'libc.so.6', 'GLIBC_2.0');
      INSERT INTO Dependencies 
         SELECT DISTINCT 
             NULL, 
             DepCheck.class, 
             DepCheck.name, 
             DepCheck.flag 
         FROM DepCheck LEFT OUTER JOIN Dependencies ON 
             DepCheck.class == Dependencies.class AND 
             DepCheck.name == Dependencies.name AND 
             DepCheck.flag == Dependencies.flag 
         WHERE 
             Dependencies.depId is NULL;
    };
  } {}
}

#--------------------------------------------------------------------
# Test that the INSERT works when the SELECT statement (a) references
# the table being inserted into and (b) is optimized to use an index
# only.
do_test insert2-5.1 {
  execsql {
    CREATE TABLE t2(a, b);
    INSERT INTO t2 VALUES(1, 2);
    CREATE INDEX t2i1 ON t2(a);
    INSERT INTO t2 SELECT a, 3 FROM t2 WHERE a = 1;
    SELECT * FROM t2;
  }
} {1 2 1 3}
ifcapable subquery {
  do_test insert2-5.2 {
    execsql {
      INSERT INTO t2 SELECT (SELECT a FROM t2), 4;
      SELECT * FROM t2;
    }
  } {1 2 1 3 1 4}
}

finish_test

Added test/insert3.test.



























































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# 2005 January 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing corner cases of the INSERT statement.
#
# $Id: insert3.test,v 1.9 2009/04/23 14:58:40 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# All the tests in this file require trigger support
#
ifcapable {trigger} {

# Create a table and a corresponding insert trigger.  Do a self-insert
# into the table.
#
do_test insert3-1.0 {
  execsql {
    CREATE TABLE t1(a,b);
    CREATE TABLE log(x UNIQUE, y);
    CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN
      UPDATE log SET y=y+1 WHERE x=new.a;
      INSERT OR IGNORE INTO log VALUES(new.a, 1);
    END;
    INSERT INTO t1 VALUES('hello','world');
    INSERT INTO t1 VALUES(5,10);
    SELECT * FROM log ORDER BY x;
  }
} {5 1 hello 1}
do_test insert3-1.1 {
  execsql {
    INSERT INTO t1 SELECT a, b+10 FROM t1;
    SELECT * FROM log ORDER BY x;
  }
} {5 2 hello 2}
do_test insert3-1.2 {
  execsql {
    CREATE TABLE log2(x PRIMARY KEY,y);
    CREATE TRIGGER r2 BEFORE INSERT ON t1 BEGIN
      UPDATE log2 SET y=y+1 WHERE x=new.b;
      INSERT OR IGNORE INTO log2 VALUES(new.b,1);
    END;
    INSERT INTO t1 VALUES(453,'hi');
    SELECT * FROM log ORDER BY x;
  }
} {5 2 453 1 hello 2}
do_test insert3-1.3 {
  execsql {
    SELECT * FROM log2 ORDER BY x;
  }
} {hi 1}
ifcapable compound {
  do_test insert3-1.4.1 {
    execsql {
      INSERT INTO t1 SELECT * FROM t1;
      SELECT 'a:', x, y FROM log UNION ALL 
          SELECT 'b:', x, y FROM log2 ORDER BY x;
    }
  } {a: 5 4 b: 10 2 b: 20 1 a: 453 2 a: hello 4 b: hi 2 b: world 1}
  do_test insert3-1.4.2 {
    execsql {
      SELECT 'a:', x, y FROM log UNION ALL 
          SELECT 'b:', x, y FROM log2 ORDER BY x, y;
    }
  } {a: 5 4 b: 10 2 b: 20 1 a: 453 2 a: hello 4 b: hi 2 b: world 1}
  do_test insert3-1.5 {
    execsql {
      INSERT INTO t1(a) VALUES('xyz');
      SELECT * FROM log ORDER BY x;
    }
  } {5 4 453 2 hello 4 xyz 1}
}

do_test insert3-2.1 {
  execsql {
    CREATE TABLE t2(
      a INTEGER PRIMARY KEY,
      b DEFAULT 'b',
      c DEFAULT 'c'
    );
    CREATE TABLE t2dup(a,b,c);
    CREATE TRIGGER t2r1 BEFORE INSERT ON t2 BEGIN
      INSERT INTO t2dup(a,b,c) VALUES(new.a,new.b,new.c);
    END;
    INSERT INTO t2(a) VALUES(123);
    INSERT INTO t2(b) VALUES(234);
    INSERT INTO t2(c) VALUES(345);
    SELECT * FROM t2dup;
  }
} {123 b c -1 234 c -1 b 345}
do_test insert3-2.2 {
  execsql {
    DELETE FROM t2dup;
    INSERT INTO t2(a) SELECT 1 FROM t1 LIMIT 1;
    INSERT INTO t2(b) SELECT 987 FROM t1 LIMIT 1;
    INSERT INTO t2(c) SELECT 876 FROM t1 LIMIT 1;
    SELECT * FROM t2dup;
  }
} {1 b c -1 987 c -1 b 876}

# Test for proper detection of malformed WHEN clauses on INSERT triggers.
#
do_test insert3-3.1 {
  execsql {
    CREATE TABLE t3(a,b,c);
    CREATE TRIGGER t3r1 BEFORE INSERT on t3 WHEN nosuchcol BEGIN
      SELECT 'illegal WHEN clause';
    END;
  }
} {}
do_test insert3-3.2 {
  catchsql {
    INSERT INTO t3 VALUES(1,2,3)
  }
} {1 {no such column: nosuchcol}}
do_test insert3-3.3 {
  execsql {
    CREATE TABLE t4(a,b,c);
    CREATE TRIGGER t4r1 AFTER INSERT on t4 WHEN nosuchcol BEGIN
      SELECT 'illegal WHEN clause';
    END;
  }
} {}
do_test insert3-3.4 {
  catchsql {
    INSERT INTO t4 VALUES(1,2,3)
  }
} {1 {no such column: nosuchcol}}

} ;# ifcapable {trigger}

# Tests for the INSERT INTO ... DEFAULT VALUES construct
#
do_test insert3-3.5 {
  execsql {
    CREATE TABLE t5(
      a INTEGER PRIMARY KEY,
      b DEFAULT 'xyz'
    );
    INSERT INTO t5 DEFAULT VALUES;
    SELECT * FROM t5;
  }
} {1 xyz}
do_test insert3-3.6 {
  execsql {
    INSERT INTO t5 DEFAULT VALUES;
    SELECT * FROM t5;
  }
} {1 xyz 2 xyz}

ifcapable bloblit {
  do_test insert3-3.7 {
    execsql {
      CREATE TABLE t6(x,y DEFAULT 4.3, z DEFAULT x'6869');
      INSERT INTO t6 DEFAULT VALUES;
      SELECT * FROM t6;
    }
  } {{} 4.3 hi}
}

foreach tab [db eval {SELECT name FROM sqlite_master WHERE type = 'table'}] {
  db eval "DROP TABLE $tab"
}
db close
sqlite3 db test.db

#-------------------------------------------------------------------------
# While developing tests for a different feature (savepoint) the following
# sequence was found to cause an assert() in btree.c to fail. These
# tests are included to ensure that that bug is fixed.
#
do_test insert3-4.1 {
  execsql { 
    CREATE TABLE t1(a, b, c);
    CREATE INDEX i1 ON t1(a, b);
    BEGIN;
    INSERT INTO t1 VALUES(randstr(10,400),randstr(10,400),randstr(10,400));
  }
  set r "randstr(10,400)"
  for {set ii 0} {$ii < 10} {incr ii} {
    execsql "INSERT INTO t1 SELECT $r, $r, $r FROM t1"
  }
  execsql { COMMIT }
} {}
do_test insert3-4.2 {
  execsql {
    PRAGMA cache_size = 10;
    BEGIN;
      UPDATE t1 SET a = randstr(10,10) WHERE (rowid%4)==0;
      DELETE FROM t1 WHERE rowid%2;
      INSERT INTO t1 SELECT randstr(10,400), randstr(10,400), c FROM t1;
    COMMIT;
  }
} {}

finish_test

Added test/insert4.test.





































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# 2007 January 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the INSERT transfer optimization.
#
# $Id: insert4.test,v 1.10 2008/01/21 16:22:46 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !view||!subquery {
  finish_test
  return
}

# The sqlite3_xferopt_count variable is incremented whenever the 
# insert transfer optimization applies.
#
# This procedure runs a test to see if the sqlite3_xferopt_count is
# set to N.
#
proc xferopt_test {testname N} {
  do_test $testname {set ::sqlite3_xferopt_count} $N
}

# Create tables used for testing.
#
execsql {
  PRAGMA legacy_file_format = 0;
  CREATE TABLE t1(a int, b int, check(b>a));
  CREATE TABLE t2(x int, y int);
  CREATE VIEW v2 AS SELECT y, x FROM t2;
  CREATE TABLE t3(a int, b int);
}

# Ticket #2252.  Make sure the an INSERT from identical tables
# does not violate constraints.
#
do_test insert4-1.1 {
  set sqlite3_xferopt_count 0
  execsql {
    DELETE FROM t1;
    DELETE FROM t2;
    INSERT INTO t2 VALUES(9,1);
  }
  catchsql {
    INSERT INTO t1 SELECT * FROM t2;
  }
} {1 {constraint failed}}
xferopt_test insert4-1.2 0
do_test insert4-1.3 {
  execsql {
    SELECT * FROM t1;
  }
} {}

# Tests to make sure that the transfer optimization is not occurring
# when it is not a valid optimization.
#
# The SELECT must be against a real table.
do_test insert4-2.1.1 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 SELECT 4, 8;
    SELECT * FROM t1;
  }
} {4 8}
xferopt_test insert4-2.1.2  0
do_test insert4-2.2.1 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 SELECT * FROM v2;
    SELECT * FROM t1;
  }
} {0 {1 9}}
xferopt_test insert4-2.2.2 0

# Do not run the transfer optimization if there is a LIMIT clause
#
do_test insert4-2.3.1 {
  execsql {
    DELETE FROM t2;
    INSERT INTO t2 VALUES(9,1);
    INSERT INTO t2 SELECT y, x FROM t2;
    INSERT INTO t3 SELECT * FROM t2 LIMIT 1;
    SELECT * FROM t3;
  }
} {9 1}
xferopt_test insert4-2.3.2  0
do_test insert4-2.3.3 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 SELECT * FROM t2 LIMIT 1;
    SELECT * FROM t1;
  }
} {1 {constraint failed}}
xferopt_test insert4-2.3.4 0

# Do not run the transfer optimization if there is a DISTINCT
#
do_test insert4-2.4.1 {
  execsql {
    DELETE FROM t3;
    INSERT INTO t3 SELECT DISTINCT * FROM t2;
    SELECT * FROM t3;
  }
} {1 9 9 1}
xferopt_test insert4-2.4.2 0
do_test insert4-2.4.3 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 SELECT DISTINCT * FROM t2;
  }
} {1 {constraint failed}}
xferopt_test insert4-2.4.4 0

# The following procedure constructs two tables then tries to transfer
# data from one table to the other.  Checks are made to make sure the
# transfer is successful and that the transfer optimization was used or
# not, as appropriate.
#
#     xfer_check TESTID  XFER-USED   INIT-DATA   DEST-SCHEMA   SRC-SCHEMA 
#
# The TESTID argument is the symbolic name for this test.  The XFER-USED
# argument is true if the transfer optimization should be employed and
# false if not.  INIT-DATA is a single row of data that is to be 
# transfered.  DEST-SCHEMA and SRC-SCHEMA are table declarations for
# the destination and source tables.
#
proc xfer_check {testid xferused initdata destschema srcschema} {
  execsql "CREATE TABLE dest($destschema)"
  execsql "CREATE TABLE src($srcschema)"
  execsql "INSERT INTO src VALUES([join $initdata ,])"
  set ::sqlite3_xferopt_count 0
  do_test $testid.1 {
    execsql {
      INSERT INTO dest SELECT * FROM src;
      SELECT * FROM dest;
    }
  } $initdata
  do_test $testid.2 {
    set ::sqlite3_xferopt_count
  } $xferused
  execsql {
    DROP TABLE dest;
    DROP TABLE src;
  }
}


# Do run the transfer optimization if tables have identical
# CHECK constraints.
#
xfer_check insert4-3.1 1 {1 9} \
    {a int, b int CHECK(b>a)} \
    {x int, y int CHECK(y>x)}
xfer_check insert4-3.2 1 {1 9} \
    {a int, b int CHECK(b>a)} \
    {x int CHECK(y>x), y int}

# Do run the transfer optimization if the destination table lacks
# any CHECK constraints regardless of whether or not there are CHECK
# constraints on the source table.
#
xfer_check insert4-3.3 1 {1 9} \
    {a int, b int} \
    {x int, y int CHECK(y>x)}

# Do run the transfer optimization if the destination table omits
# NOT NULL constraints that the source table has.
#
xfer_check insert4-3.4 0 {1 9} \
    {a int, b int CHECK(b>a)} \
    {x int, y int}

# Do not run the optimization if the destination has NOT NULL
# constraints that the source table lacks.
#
xfer_check insert4-3.5 0 {1 9} \
    {a int, b int NOT NULL} \
    {x int, y int}
xfer_check insert4-3.6 0 {1 9} \
    {a int, b int NOT NULL} \
    {x int NOT NULL, y int}
xfer_check insert4-3.7 0 {1 9} \
    {a int NOT NULL, b int NOT NULL} \
    {x int NOT NULL, y int}
xfer_check insert4-3.8 0 {1 9} \
    {a int NOT NULL, b int} \
    {x int, y int}


# Do run the transfer optimization if the destination table and
# source table have the same NOT NULL constraints or if the 
# source table has extra NOT NULL constraints.
#
xfer_check insert4-3.9 1 {1 9} \
    {a int, b int} \
    {x int NOT NULL, y int}
xfer_check insert4-3.10 1 {1 9} \
    {a int, b int} \
    {x int NOT NULL, y int NOT NULL}
xfer_check insert4-3.11 1 {1 9} \
    {a int NOT NULL, b int} \
    {x int NOT NULL, y int NOT NULL}
xfer_check insert4-3.12 1 {1 9} \
    {a int, b int NOT NULL} \
    {x int NOT NULL, y int NOT NULL}

# Do not run the optimization if any corresponding table
# columns have different affinities.
#
xfer_check insert4-3.20 0 {1 9} \
    {a text, b int} \
    {x int, b int}
xfer_check insert4-3.21 0 {1 9} \
    {a int, b int} \
    {x text, b int}

# "int" and "integer" are equivalent so the optimization should
# run here.
#
xfer_check insert4-3.22 1 {1 9} \
    {a int, b int} \
    {x integer, b int}

# Ticket #2291.
#

do_test insert4-4.1a {
  execsql {CREATE TABLE t4(a, b, UNIQUE(a,b))}
} {}
ifcapable vacuum {
  do_test insert4-4.1b {
    execsql {
      INSERT INTO t4 VALUES(NULL,0);
      INSERT INTO t4 VALUES(NULL,1);
      INSERT INTO t4 VALUES(NULL,1);
      VACUUM;   
    }
  } {}
}

# Check some error conditions:
#
do_test insert4-5.1 {
  # Table does not exist.
  catchsql { INSERT INTO t2 SELECT * FROM nosuchtable }
} {1 {no such table: nosuchtable}}
do_test insert4-5.2 {
  # Number of columns does not match.
  catchsql { 
    CREATE TABLE t5(a, b, c);
    INSERT INTO t4 SELECT * FROM t5;
  }
} {1 {table t4 has 2 columns but 3 values were supplied}}

do_test insert4-6.1 {
  set ::sqlite3_xferopt_count 0
  execsql {
    CREATE INDEX t2_i2 ON t2(x, y COLLATE nocase); 
    CREATE INDEX t2_i1 ON t2(x ASC, y DESC);
    CREATE INDEX t3_i1 ON t3(a, b);
    INSERT INTO t2 SELECT * FROM t3;
  }
  set ::sqlite3_xferopt_count
} {0}
do_test insert4-6.2 {
  set ::sqlite3_xferopt_count 0
  execsql {
    DROP INDEX t2_i2;
    INSERT INTO t2 SELECT * FROM t3;
  }
  set ::sqlite3_xferopt_count
} {0}
do_test insert4-6.3 {
  set ::sqlite3_xferopt_count 0
  execsql {
    DROP INDEX t2_i1;
    CREATE INDEX t2_i1 ON t2(x ASC, y ASC);
    INSERT INTO t2 SELECT * FROM t3;
  }
  set ::sqlite3_xferopt_count
} {1}
do_test insert4-6.4 {
  set ::sqlite3_xferopt_count 0
  execsql {
    DROP INDEX t2_i1;
    CREATE INDEX t2_i1 ON t2(x ASC, y COLLATE RTRIM);
    INSERT INTO t2 SELECT * FROM t3;
  }
  set ::sqlite3_xferopt_count
} {0}




finish_test

Added test/insert5.test.











































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# 2007 November 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The tests in this file ensure that a temporary table is used
# when required by an "INSERT INTO ... SELECT ..." statement.
#
# $Id: insert5.test,v 1.5 2008/08/04 03:51:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

# Return true if the compilation of the sql passed as an argument 
# includes the opcode OpenEphemeral. An "INSERT INTO ... SELECT"
# statement includes such an opcode if a temp-table is used
# to store intermediate results.
# 
proc uses_temp_table {sql} {
  return [expr {[lsearch [execsql "EXPLAIN $sql"] OpenEphemeral]>=0}]
}

# Construct the sample database.
#
do_test insert5-1.0 {
  file delete -force test2.db test2.db-journal
  execsql {
    CREATE TABLE MAIN(Id INTEGER, Id1 INTEGER); 
    CREATE TABLE B(Id INTEGER, Id1 INTEGER); 
    CREATE VIEW v1 AS SELECT * FROM B;
    CREATE VIEW v2 AS SELECT * FROM MAIN;
    INSERT INTO MAIN(Id,Id1) VALUES(2,3); 
    INSERT INTO B(Id,Id1) VALUES(2,3); 
  }
} {}

# Run the query.
#
ifcapable compound {
  do_test insert5-1.1 {
    execsql {
      INSERT INTO B 
        SELECT * FROM B UNION ALL 
        SELECT * FROM MAIN WHERE exists (select * FROM B WHERE B.Id = MAIN.Id);
      SELECT * FROM B;
    }
  } {2 3 2 3 2 3}
} else {
  do_test insert5-1.1 {
    execsql {
      INSERT INTO B SELECT * FROM B;
      INSERT INTO B
        SELECT * FROM MAIN WHERE exists (select * FROM B WHERE B.Id = MAIN.Id);
      SELECT * FROM B;
    }
  } {2 3 2 3 2 3}
}
do_test insert5-2.1 {
  uses_temp_table { INSERT INTO b SELECT * FROM main }
} {0}
do_test insert5-2.2 {
  uses_temp_table { INSERT INTO b SELECT * FROM b }
} {1}
do_test insert5-2.3 {
  uses_temp_table { INSERT INTO b SELECT (SELECT id FROM b), id1 FROM main }
} {1}
do_test insert5-2.4 {
  uses_temp_table { INSERT INTO b SELECT id1, (SELECT id FROM b) FROM main }
} {1}
do_test insert5-2.5 {
  uses_temp_table { 
    INSERT INTO b 
      SELECT * FROM main WHERE id = (SELECT id1 FROM b WHERE main.id = b.id) }
} {1}
do_test insert5-2.6 {
  uses_temp_table { INSERT INTO b SELECT * FROM v1 }
} {1}
do_test insert5-2.7 {
  uses_temp_table { INSERT INTO b SELECT * FROM v2 }
} {0}
do_test insert5-2.8 {
  uses_temp_table { 
    INSERT INTO b 
    SELECT * FROM main WHERE id > 10 AND max(id1, (SELECT id FROM b)) > 10;
  }
} {1}

# UPDATE: Using a column from the outer query (main.id) in the GROUP BY
# or ORDER BY of a sub-query is no longer supported.
#
# do_test insert5-2.9 {
#   uses_temp_table { 
#     INSERT INTO b 
#     SELECT * FROM main 
#     WHERE id > 10 AND (SELECT count(*) FROM v2 GROUP BY main.id)
#   }
# } {}
do_test insert5-2.9 {
  catchsql { 
    INSERT INTO b 
    SELECT * FROM main 
    WHERE id > 10 AND (SELECT count(*) FROM v2 GROUP BY main.id)
  }
} {1 {no such column: main.id}}

finish_test

Added test/interrupt.test.















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# 2004 Feb 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is the sqlite_interrupt() API.
#
# $Id: interrupt.test,v 1.16 2008/01/16 17:46:38 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl
set DB [sqlite3_connection_pointer db]

# This routine attempts to execute the sql in $sql.  It triggers an
# interrupt at progressively later and later points during the processing
# and checks to make sure SQLITE_INTERRUPT is returned.  Eventually,
# the routine completes successfully.
#
proc interrupt_test {testid sql result {initcnt 0}} {
  set orig_sum [cksum]
  set i $initcnt
  while 1 {
    incr i
    set ::sqlite_interrupt_count $i
    do_test $testid.$i.1 [format {
      set ::r [catchsql %s]
      set ::code [db errorcode]
      expr {$::code==0 || $::code==9}
    } [list $sql]] 1
    if {$::code==9} {
      do_test $testid.$i.2 {
        cksum
      } $orig_sum
    } else {
      do_test $testid.$i.99 {
        set ::r
      } [list 0 $result]
      break
    }
  }
  set ::sqlite_interrupt_count 0
}

do_test interrupt-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    SELECT name FROM sqlite_master;
  }
} {t1}
interrupt_test interrupt-1.2 {DROP TABLE t1} {}
do_test interrupt-1.3 {
  execsql {
    SELECT name FROM sqlite_master;
  }
} {}
integrity_check interrupt-1.4

do_test interrrupt-2.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,randstr(300,400));
    INSERT INTO t1 SELECT a+1, randstr(300,400) FROM t1;
    INSERT INTO t1 SELECT a+2, a || '-' || b FROM t1;
    INSERT INTO t1 SELECT a+4, a || '-' || b FROM t1;
    INSERT INTO t1 SELECT a+8, a || '-' || b FROM t1;
    INSERT INTO t1 SELECT a+16, a || '-' || b FROM t1;
    INSERT INTO t1 SELECT a+32, a || '-' || b FROM t1;
    COMMIT;
    UPDATE t1 SET b=substr(b,-5,5);
    SELECT count(*) from t1;
  }
} 64
set origsize [file size test.db]
set cksum [db eval {SELECT md5sum(a || b) FROM t1}]
ifcapable {vacuum} {
  interrupt_test interrupt-2.2 {VACUUM} {} 100
}
do_test interrupt-2.3 {
  execsql {
    SELECT md5sum(a || b) FROM t1;
  }
} $cksum
ifcapable {vacuum && !default_autovacuum} {
  do_test interrupt-2.4 {
    expr {$::origsize>[file size test.db]}
  } 1
}
ifcapable {explain} {
  do_test interrupt-2.5 {
    set sql {EXPLAIN SELECT max(a,b), a, b FROM t1}
    execsql $sql
    set rc [catch {db eval $sql {sqlite3_interrupt $DB}} msg]
    lappend rc $msg
  } {1 interrupted}
}
integrity_check interrupt-2.6

# Ticket #594.  If an interrupt occurs in the middle of a transaction
# and that transaction is later rolled back, the internal schema tables do
# not reset.
#
# UPDATE: Interrupting a DML statement in the middle of a transaction now
# causes the transaction to roll back. Leaving the transaction open after
# an SQL statement was interrupted halfway through risks database corruption.
#
ifcapable tempdb {
  for {set i 1} {$i<50} {incr i 5} {
    do_test interrupt-3.$i.1 {
      execsql {
        BEGIN;
        CREATE TEMP TABLE t2(x,y);
        SELECT name FROM sqlite_temp_master;
      }
    } {t2}
    do_test interrupt-3.$i.2 {
      set ::sqlite_interrupt_count $::i
      catchsql {
        INSERT INTO t2 SELECT * FROM t1;
      }
    } {1 interrupted}
    do_test interrupt-3.$i.3 {
      execsql {
        SELECT name FROM sqlite_temp_master;
      }
    } {}
    do_test interrupt-3.$i.4 {
      catchsql {
        ROLLBACK
      }
    } {1 {cannot rollback - no transaction is active}}
    do_test interrupt-3.$i.5 {
      catchsql {SELECT name FROM sqlite_temp_master};
      execsql {
        SELECT name FROM sqlite_temp_master;
      }
    } {}
  }
}

# There are reports of a memory leak if an interrupt occurs during
# the beginning of a complex query - before the first callback.  We
# will try to reproduce it here:
#
execsql {
  CREATE TABLE t2(a,b,c);
  INSERT INTO t2 SELECT round(a/10), randstr(50,80), randstr(50,60) FROM t1;
}
set sql {
  SELECT max(min(b,c)), min(max(b,c)), a FROM t2 GROUP BY a ORDER BY a;
}
set sqlite_interrupt_count 1000000
execsql $sql
set max_count [expr {1000000-$sqlite_interrupt_count}]
for {set i 1} {$i<$max_count-5} {incr i 1} {
  do_test interrupt-4.$i.1 {
    set ::sqlite_interrupt_count $::i
    catchsql $sql
  } {1 interrupted}
}

# Interrupt during parsing
#
do_test interrupt-5.1 {
  proc fake_interrupt {args} {
    db collate fake_collation no-op
    sqlite3_interrupt db
    return SQLITE_OK
  }
  db collation_needed fake_interrupt
  catchsql {
    CREATE INDEX fake ON fake1(a COLLATE fake_collation, b, c DESC);
  }
} {1 interrupt}

finish_test

Added test/intpkey.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the special processing associated
# with INTEGER PRIMARY KEY columns.
#
# $Id: intpkey.test,v 1.24 2007/11/29 17:43:28 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table with a primary key and a datatype other than
# integer
#
do_test intpkey-1.0 {
  execsql {
    CREATE TABLE t1(a TEXT PRIMARY KEY, b, c);
  }
} {}

# There should be an index associated with the primary key
#
do_test intpkey-1.1 {
  execsql {
    SELECT name FROM sqlite_master
    WHERE type='index' AND tbl_name='t1';
  }
} {sqlite_autoindex_t1_1}

# Now create a table with an integer primary key and verify that
# there is no associated index.
#
do_test intpkey-1.2 {
  execsql {
    DROP TABLE t1;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
    SELECT name FROM sqlite_master
      WHERE type='index' AND tbl_name='t1';
  }
} {}

# Insert some records into the new table.  Specify the primary key
# and verify that the key is used as the record number.
#
do_test intpkey-1.3 {
  execsql {
    INSERT INTO t1 VALUES(5,'hello','world');
  }
  db last_insert_rowid
} {5}
do_test intpkey-1.4 {
  execsql {
    SELECT * FROM t1;
  }
} {5 hello world}
do_test intpkey-1.5 {
  execsql {
    SELECT rowid, * FROM t1;
  }
} {5 5 hello world}

# Attempting to insert a duplicate primary key should give a constraint
# failure.
#
do_test intpkey-1.6 {
  set r [catch {execsql {
     INSERT INTO t1 VALUES(5,'second','entry');
  }} msg]
  lappend r $msg
} {1 {PRIMARY KEY must be unique}}
do_test intpkey-1.7 {
  execsql {
    SELECT rowid, * FROM t1;
  }
} {5 5 hello world}
do_test intpkey-1.8 {
  set r [catch {execsql {
     INSERT INTO t1 VALUES(6,'second','entry');
  }} msg]
  lappend r $msg
} {0 {}}
do_test intpkey-1.8.1 {
  db last_insert_rowid
} {6}
do_test intpkey-1.9 {
  execsql {
    SELECT rowid, * FROM t1;
  }
} {5 5 hello world 6 6 second entry}

# A ROWID is automatically generated for new records that do not specify
# the integer primary key.
#
do_test intpkey-1.10 {
  execsql {
    INSERT INTO t1(b,c) VALUES('one','two');
    SELECT b FROM t1 ORDER BY b;
  }
} {hello one second}

# Try to change the ROWID for the new entry.
#
do_test intpkey-1.11 {
  execsql {
    UPDATE t1 SET a=4 WHERE b='one';
    SELECT * FROM t1;
  }
} {4 one two 5 hello world 6 second entry}

# Make sure SELECT statements are able to use the primary key column
# as an index.
#
do_test intpkey-1.12.1 {
  execsql {
    SELECT * FROM t1 WHERE a==4;
  }
} {4 one two}
do_test intpkey-1.12.2 {
  set sqlite_query_plan
} {t1 *}

# Try to insert a non-integer value into the primary key field.  This
# should result in a data type mismatch.
#
do_test intpkey-1.13.1 {
  set r [catch {execsql {
    INSERT INTO t1 VALUES('x','y','z');
  }} msg]
  lappend r $msg
} {1 {datatype mismatch}}
do_test intpkey-1.13.2 {
  set r [catch {execsql {
    INSERT INTO t1 VALUES('','y','z');
  }} msg]
  lappend r $msg
} {1 {datatype mismatch}}
do_test intpkey-1.14 {
  set r [catch {execsql {
    INSERT INTO t1 VALUES(3.4,'y','z');
  }} msg]
  lappend r $msg
} {1 {datatype mismatch}}
do_test intpkey-1.15 {
  set r [catch {execsql {
    INSERT INTO t1 VALUES(-3,'y','z');
  }} msg]
  lappend r $msg
} {0 {}}
do_test intpkey-1.16 {
  execsql {SELECT * FROM t1}
} {-3 y z 4 one two 5 hello world 6 second entry}

#### INDICES
# Check to make sure indices work correctly with integer primary keys
#
do_test intpkey-2.1 {
  execsql {
    CREATE INDEX i1 ON t1(b);
    SELECT * FROM t1 WHERE b=='y'
  }
} {-3 y z}
do_test intpkey-2.1.1 {
  execsql {
    SELECT * FROM t1 WHERE b=='y' AND rowid<0
  }
} {-3 y z}
do_test intpkey-2.1.2 {
  execsql {
    SELECT * FROM t1 WHERE b=='y' AND rowid<0 AND rowid>=-20
  }
} {-3 y z}
do_test intpkey-2.1.3 {
  execsql {
    SELECT * FROM t1 WHERE b>='y'
  }
} {-3 y z}
do_test intpkey-2.1.4 {
  execsql {
    SELECT * FROM t1 WHERE b>='y' AND rowid<10
  }
} {-3 y z}

do_test intpkey-2.2 {
  execsql {
    UPDATE t1 SET a=8 WHERE b=='y';
    SELECT * FROM t1 WHERE b=='y';
  }
} {8 y z}
do_test intpkey-2.3 {
  execsql {
    SELECT rowid, * FROM t1;
  }
} {4 4 one two 5 5 hello world 6 6 second entry 8 8 y z}
do_test intpkey-2.4 {
  execsql {
    SELECT rowid, * FROM t1 WHERE b<'second'
  }
} {5 5 hello world 4 4 one two}
do_test intpkey-2.4.1 {
  execsql {
    SELECT rowid, * FROM t1 WHERE 'second'>b
  }
} {5 5 hello world 4 4 one two}
do_test intpkey-2.4.2 {
  execsql {
    SELECT rowid, * FROM t1 WHERE 8>rowid AND 'second'>b
  }
} {4 4 one two 5 5 hello world}
do_test intpkey-2.4.3 {
  execsql {
    SELECT rowid, * FROM t1 WHERE 8>rowid AND 'second'>b AND 0<rowid
  }
} {4 4 one two 5 5 hello world}
do_test intpkey-2.5 {
  execsql {
    SELECT rowid, * FROM t1 WHERE b>'a'
  }
} {5 5 hello world 4 4 one two 6 6 second entry 8 8 y z}
do_test intpkey-2.6 {
  execsql {
    DELETE FROM t1 WHERE rowid=4;
    SELECT * FROM t1 WHERE b>'a';
  }
} {5 hello world 6 second entry 8 y z}
do_test intpkey-2.7 {
  execsql {
    UPDATE t1 SET a=-4 WHERE rowid=8;
    SELECT * FROM t1 WHERE b>'a';
  }
} {5 hello world 6 second entry -4 y z}
do_test intpkey-2.7 {
  execsql {
    SELECT * FROM t1
  }
} {-4 y z 5 hello world 6 second entry}

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  return [concat [execsql $sql] $::sqlite_search_count]
}

# Create indices that include the integer primary key as one of their
# columns.
#
do_test intpkey-3.1 {
  execsql {
    CREATE INDEX i2 ON t1(a);
  }
} {}
do_test intpkey-3.2 {
  count {
    SELECT * FROM t1 WHERE a=5;
  }
} {5 hello world 0}
do_test intpkey-3.3 {
  count {
    SELECT * FROM t1 WHERE a>4 AND a<6;
  }
} {5 hello world 2}
do_test intpkey-3.4 {
  count {
    SELECT * FROM t1 WHERE b>='hello' AND b<'hello2';
  }
} {5 hello world 3}
do_test intpkey-3.5 {
  execsql {
    CREATE INDEX i3 ON t1(c,a);
  }
} {}
do_test intpkey-3.6 {
  count {
    SELECT * FROM t1 WHERE c=='world';
  }
} {5 hello world 3}
do_test intpkey-3.7 {
  execsql {INSERT INTO t1 VALUES(11,'hello','world')}
  count {
    SELECT * FROM t1 WHERE c=='world';
  }
} {5 hello world 11 hello world 5}
do_test intpkey-3.8 {
  count {
    SELECT * FROM t1 WHERE c=='world' AND a>7;
  }
} {11 hello world 4}
do_test intpkey-3.9 {
  count {
    SELECT * FROM t1 WHERE 7<a;
  }
} {11 hello world 1}

# Test inequality constraints on integer primary keys and rowids
#
do_test intpkey-4.1 {
  count {
    SELECT * FROM t1 WHERE 11=rowid
  }
} {11 hello world 0}
do_test intpkey-4.2 {
  count {
    SELECT * FROM t1 WHERE 11=rowid AND b=='hello'
  }
} {11 hello world 0}
do_test intpkey-4.3 {
  count {
    SELECT * FROM t1 WHERE 11=rowid AND b=='hello' AND c IS NOT NULL;
  }
} {11 hello world 0}
do_test intpkey-4.4 {
  count {
    SELECT * FROM t1 WHERE rowid==11
  }
} {11 hello world 0}
do_test intpkey-4.5 {
  count {
    SELECT * FROM t1 WHERE oid==11 AND b=='hello'
  }
} {11 hello world 0}
do_test intpkey-4.6 {
  count {
    SELECT * FROM t1 WHERE a==11 AND b=='hello' AND c IS NOT NULL;
  }
} {11 hello world 0}

do_test intpkey-4.7 {
  count {
    SELECT * FROM t1 WHERE 8<rowid;
  }
} {11 hello world 1}
do_test intpkey-4.8 {
  count {
    SELECT * FROM t1 WHERE 8<rowid AND 11>=oid;
  }
} {11 hello world 1}
do_test intpkey-4.9 {
  count {
    SELECT * FROM t1 WHERE 11<=_rowid_ AND 12>=a;
  }
} {11 hello world 1}
do_test intpkey-4.10 {
  count {
    SELECT * FROM t1 WHERE 0>=_rowid_;
  }
} {-4 y z 1}
do_test intpkey-4.11 {
  count {
    SELECT * FROM t1 WHERE a<0;
  }
} {-4 y z 1}
do_test intpkey-4.12 {
  count {
    SELECT * FROM t1 WHERE a<0 AND a>10;
  }
} {1}

# Make sure it is OK to insert a rowid of 0
#
do_test intpkey-5.1 {
  execsql {
    INSERT INTO t1 VALUES(0,'zero','entry');
  }
  count {
    SELECT * FROM t1 WHERE a=0;
  }
} {0 zero entry 0}
do_test intpkey-5.2 {
  execsql {
    SELECT rowid, a FROM t1
  }
} {-4 -4 0 0 5 5 6 6 11 11}

# Test the ability of the COPY command to put data into a
# table that contains an integer primary key.
#
# COPY command has been removed.  But we retain these tests so
# that the tables will contain the right data for tests that follow.
#
do_test intpkey-6.1 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(20,'b-20','c-20');
    INSERT INTO t1 VALUES(21,'b-21','c-21');
    INSERT INTO t1 VALUES(22,'b-22','c-22');
    COMMIT;
    SELECT * FROM t1 WHERE a>=20;
  }
} {20 b-20 c-20 21 b-21 c-21 22 b-22 c-22}
do_test intpkey-6.2 {
  execsql {
    SELECT * FROM t1 WHERE b=='hello'
  }
} {5 hello world 11 hello world}
do_test intpkey-6.3 {
  execsql {
    DELETE FROM t1 WHERE b='b-21';
    SELECT * FROM t1 WHERE b=='b-21';
  }
} {}
do_test intpkey-6.4 {
  execsql {
    SELECT * FROM t1 WHERE a>=20
  }
} {20 b-20 c-20 22 b-22 c-22}

# Do an insert of values with the columns specified out of order.
#
do_test intpkey-7.1 {
  execsql {
    INSERT INTO t1(c,b,a) VALUES('row','new',30);
    SELECT * FROM t1 WHERE rowid>=30;
  }
} {30 new row}
do_test intpkey-7.2 {
  execsql {
    SELECT * FROM t1 WHERE rowid>20;
  }
} {22 b-22 c-22 30 new row}

# Do an insert from a select statement.
#
do_test intpkey-8.1 {
  execsql {
    CREATE TABLE t2(x INTEGER PRIMARY KEY, y, z);
    INSERT INTO t2 SELECT * FROM t1;
    SELECT rowid FROM t2;
  }
} {-4 0 5 6 11 20 22 30}
do_test intpkey-8.2 {
  execsql {
    SELECT x FROM t2;
  }
} {-4 0 5 6 11 20 22 30}

do_test intpkey-9.1 {
  execsql {
    UPDATE t1 SET c='www' WHERE c='world';
    SELECT rowid, a, c FROM t1 WHERE c=='www';
  }
} {5 5 www 11 11 www}


# Check insert of NULL for primary key
#
do_test intpkey-10.1 {
  execsql {
    DROP TABLE t2;
    CREATE TABLE t2(x INTEGER PRIMARY KEY, y, z);
    INSERT INTO t2 VALUES(NULL, 1, 2);
    SELECT * from t2;
  }
} {1 1 2}
do_test intpkey-10.2 {
  execsql {
    INSERT INTO t2 VALUES(NULL, 2, 3);
    SELECT * from t2 WHERE x=2;
  }
} {2 2 3}
do_test intpkey-10.3 {
  execsql {
    INSERT INTO t2 SELECT NULL, z, y FROM t2;
    SELECT * FROM t2;
  }
} {1 1 2 2 2 3 3 2 1 4 3 2}

# This tests checks to see if a floating point number can be used
# to reference an integer primary key.
#
do_test intpkey-11.1 {
  execsql {
    SELECT b FROM t1 WHERE a=2.0+3.0;
  }
} {hello}
do_test intpkey-11.1 {
  execsql {
    SELECT b FROM t1 WHERE a=2.0+3.5;
  }
} {}

integrity_check intpkey-12.1

# Try to use a string that looks like a floating point number as
# an integer primary key.  This should actually work when the floating
# point value can be rounded to an integer without loss of data.
#
do_test intpkey-13.1 {
  execsql {
    SELECT * FROM t1 WHERE a=1;
  }
} {}
do_test intpkey-13.2 {
  execsql {
    INSERT INTO t1 VALUES('1.0',2,3);
    SELECT * FROM t1 WHERE a=1;
  }
} {1 2 3}
do_test intpkey-13.3 {
  catchsql {
    INSERT INTO t1 VALUES('1.5',3,4);
  }
} {1 {datatype mismatch}}
ifcapable {bloblit} {
  do_test intpkey-13.4 {
    catchsql {
      INSERT INTO t1 VALUES(x'123456',3,4);
    }
  } {1 {datatype mismatch}}
}
do_test intpkey-13.5 {
  catchsql {
    INSERT INTO t1 VALUES('+1234567890',3,4);
  }
} {0 {}}

# Compare an INTEGER PRIMARY KEY against a TEXT expression. The INTEGER
# affinity should be applied to the text value before the comparison
# takes place.
#
do_test intpkey-14.1 {
  execsql {
    CREATE TABLE t3(a INTEGER PRIMARY KEY, b INTEGER, c TEXT);
    INSERT INTO t3 VALUES(1, 1, 'one');
    INSERT INTO t3 VALUES(2, 2, '2');
    INSERT INTO t3 VALUES(3, 3, 3);
  }
} {}
do_test intpkey-14.2 {
  execsql {
    SELECT * FROM t3 WHERE a>2;
  }
} {3 3 3}
do_test intpkey-14.3 {
  execsql {
    SELECT * FROM t3 WHERE a>'2';
  }
} {3 3 3}
do_test intpkey-14.4 {
  execsql {
    SELECT * FROM t3 WHERE a<'2';
  }
} {1 1 one}
do_test intpkey-14.5 {
  execsql {
    SELECT * FROM t3 WHERE a<c;
  }
} {1 1 one}
do_test intpkey-14.6 {
  execsql {
    SELECT * FROM t3 WHERE a=c;
  }
} {2 2 2 3 3 3}

# Check for proper handling of primary keys greater than 2^31.
# Ticket #1188
#
do_test intpkey-15.1 {
  execsql {
    INSERT INTO t1 VALUES(2147483647, 'big-1', 123);
    SELECT * FROM t1 WHERE a>2147483648;
  }
} {}
do_test intpkey-15.2 {
  execsql {
    INSERT INTO t1 VALUES(NULL, 'big-2', 234);
    SELECT b FROM t1 WHERE a>=2147483648;
  }
} {big-2}
do_test intpkey-15.3 {
  execsql {
    SELECT b FROM t1 WHERE a>2147483648;
  }
} {}
do_test intpkey-15.4 {
  execsql {
    SELECT b FROM t1 WHERE a>=2147483647;
  }
} {big-1 big-2}
do_test intpkey-15.5 {
  execsql {
    SELECT b FROM t1 WHERE a<2147483648;
  }
} {y zero 2 hello second hello b-20 b-22 new 3 big-1}
do_test intpkey-15.6 {
  execsql {
    SELECT b FROM t1 WHERE a<12345678901;
  }
} {y zero 2 hello second hello b-20 b-22 new 3 big-1 big-2}
do_test intpkey-15.7 {
  execsql {
    SELECT b FROM t1 WHERE a>12345678901;
  }
} {}


finish_test

Added test/io.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# 2007 August 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of this file is testing some specific characteristics of the 
# IO traffic generated by SQLite (making sure SQLite is not writing out
# more database pages than it has to, stuff like that).
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db close
sqlite3_simulate_device
sqlite3 db test.db -vfs devsym

# Test summary:
#
# io-1.* -  Test that quick-balance does not journal pages unnecessarily.
#
# io-2.* -  Test the "atomic-write optimization".
#
# io-3.* -  Test the IO traffic enhancements triggered when the 
#           IOCAP_SEQUENTIAL device capability flag is set (no 
#           fsync() calls on the journal file).
#
# io-4.* -  Test the IO traffic enhancements triggered when the 
#           IOCAP_SAFE_APPEND device capability flag is set (fewer 
#           fsync() calls on the journal file, no need to set nRec
#           field in the single journal header).
#
# io-5.* -  Test that the default page size is selected and used 
#           correctly.
#           

set ::nWrite 0
proc nWrite {db} {
  set bt [btree_from_db $db]
  db_enter $db
  array set stats [btree_pager_stats $bt]
  db_leave $db
  set res [expr $stats(write) - $::nWrite]
  set ::nWrite $stats(write)
  set res
}

set ::nSync 0
proc nSync {} {
  set res [expr {$::sqlite_sync_count - $::nSync}]
  set ::nSync $::sqlite_sync_count
  set res
}

do_test io-1.1 {
  execsql {
    PRAGMA auto_vacuum = OFF;
    PRAGMA page_size = 1024;
    CREATE TABLE abc(a,b);
  }
  nWrite db
} {2}

# Insert into the table 4 records of aproximately 240 bytes each.
# This should completely fill the root-page of the table. Each
# INSERT causes 2 db pages to be written - the root-page of "abc"
# and page 1 (db change-counter page).
do_test io-1.2 {
  set ret [list]
  execsql { INSERT INTO abc VALUES(1,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(2,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(3,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(4,randstr(230,230)); }
  lappend ret [nWrite db]
} {2 2 2 2}

# Insert another 240 byte record. This causes two leaf pages
# to be added to the root page of abc. 4 pages in total
# are written to the db file - the two leaf pages, the root
# of abc and the change-counter page.
do_test io-1.3 {
  execsql { INSERT INTO abc VALUES(5,randstr(230,230)); }
  nWrite db
} {4}

# Insert another 3 240 byte records. After this, the tree consists of 
# the root-node, which is close to empty, and two leaf pages, both of 
# which are full. 
do_test io-1.4 {
  set ret [list]
  execsql { INSERT INTO abc VALUES(6,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(7,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(8,randstr(230,230)); }
  lappend ret [nWrite db]
} {2 2 2}

# This insert should use the quick-balance trick to add a third leaf
# to the b-tree used to store table abc. It should only be necessary to
# write to 3 pages to do this: the change-counter, the root-page and
# the new leaf page.
do_test io-1.5 {
  execsql { INSERT INTO abc VALUES(9,randstr(230,230)); }
  nWrite db
} {3}

ifcapable atomicwrite {

#----------------------------------------------------------------------
# Test cases io-2.* test the atomic-write optimization.
#
do_test io-2.1 {
  execsql { DELETE FROM abc; VACUUM; }
} {}

# Clear the write and sync counts.
nWrite db ; nSync

# The following INSERT updates 2 pages and requires 4 calls to fsync():
#
#   1) The directory in which the journal file is created,
#   2) The journal file (to sync the page data),
#   3) The journal file (to sync the journal file header),
#   4) The database file.
#
do_test io-2.2 {
  execsql { INSERT INTO abc VALUES(1, 2) }
  list [nWrite db] [nSync]
} {2 4}

# Set the device-characteristic mask to include the SQLITE_IOCAP_ATOMIC,
# then do another INSERT similar to the one in io-2.2. This should
# only write 1 page and require a single fsync().
# 
# The single fsync() is the database file. Only one page is reported as
# written because page 1 - the change-counter page - is written using
# an out-of-band method that bypasses the write counter.
#
sqlite3_simulate_device -char atomic
do_test io-2.3 {
  execsql { INSERT INTO abc VALUES(3, 4) }
  list [nWrite db] [nSync]
} {1 1}

# Test that the journal file is not created and the change-counter is
# updated when the atomic-write optimization is used.
#
do_test io-2.4.1 {
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(5, 6);
  }
  sqlite3 db2 test.db -vfs devsym
  execsql { SELECT * FROM abc } db2
} {1 2 3 4}
do_test io-2.4.2 {
  file exists test.db-journal
} {0}
do_test io-2.4.3 {
  execsql { COMMIT }
  execsql { SELECT * FROM abc } db2
} {1 2 3 4 5 6}
db2 close

# Test that the journal file is created and sync()d if the transaction
# modifies more than one database page, even if the IOCAP_ATOMIC flag
# is set.
#
do_test io-2.5.1 {
  execsql { CREATE TABLE def(d, e) }
  nWrite db ; nSync
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(7, 8);
  }
  file exists test.db-journal
} {0}
do_test io-2.5.2 {
  execsql { INSERT INTO def VALUES('a', 'b'); }
  file exists test.db-journal
} {1}
do_test io-2.5.3 {
  execsql { COMMIT }
  list [nWrite db] [nSync]
} {3 4}

# Test that the journal file is created and sync()d if the transaction
# modifies a single database page and also appends a page to the file.
# Internally, this case is handled differently to the one above. The
# journal file is not actually created until the 'COMMIT' statement
# is executed.
#
do_test io-2.6.1 {
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(9, randstr(1000,1000));
  }
  file exists test.db-journal
} {0}
do_test io-2.6.2 {
  # Create a file at "test.db-journal". This will prevent SQLite from
  # opening the journal for exclusive access. As a result, the COMMIT
  # should fail with SQLITE_CANTOPEN and the transaction rolled back.
  #
  file mkdir test.db-journal
  catchsql { COMMIT }
} {1 {unable to open database file}}
do_test io-2.6.3 {
  file delete -force test.db-journal
  catchsql { COMMIT }
} {1 {cannot commit - no transaction is active}}
do_test io-2.6.4 {
  execsql { SELECT * FROM abc }
} {1 2 3 4 5 6 7 8}

# Test that if the database modification is part of multi-file commit,
# the journal file is always created. In this case, the journal file
# is created during execution of the COMMIT statement, so we have to
# use the same technique to check that it is created as in the above 
# block.
file delete -force test2.db test2.db-journal
ifcapable attach {
  do_test io-2.7.1 {
    execsql {
      ATTACH 'test2.db' AS aux;
      PRAGMA aux.page_size = 1024;
      CREATE TABLE aux.abc2(a, b);
      BEGIN;
      INSERT INTO abc VALUES(9, 10);
    }
    file exists test.db-journal
  } {0}
  do_test io-2.7.2 {
    execsql { INSERT INTO abc2 SELECT * FROM abc }
    file exists test2.db-journal
  } {0}
  do_test io-2.7.3 {
    execsql { SELECT * FROM abc UNION ALL SELECT * FROM abc2 }
  } {1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10}
  do_test io-2.7.4 {
    file mkdir test2.db-journal
    catchsql { COMMIT }
  } {1 {unable to open database file}}
  do_test io-2.7.5 {
    file delete -force test2.db-journal
    catchsql { COMMIT }
  } {1 {cannot commit - no transaction is active}}
  do_test io-2.7.6 {
    execsql { SELECT * FROM abc UNION ALL SELECT * FROM abc2 }
  } {1 2 3 4 5 6 7 8}
}

# Try an explicit ROLLBACK before the journal file is created.
#
do_test io-2.8.1 {
  execsql {
    BEGIN;
    DELETE FROM abc;
  }
  file exists test.db-journal
} {0}
do_test io-2.8.2 {
  execsql { SELECT * FROM abc }
} {}
do_test io-2.8.3 {
  execsql {
    ROLLBACK;
    SELECT * FROM abc;
  }
} {1 2 3 4 5 6 7 8}

# Test that the atomic write optimisation is not enabled if the sector
# size is larger than the page-size.
#
do_test io-2.9.1 {
  db close
  sqlite3 db test.db
  sqlite3_simulate_device -char atomic -sectorsize 2048
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(9, 10);
  }
  file exists test.db-journal
} {1}
do_test io-2.9.2 {
  execsql { ROLLBACK; }
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db -vfs devsym
  execsql {
    PRAGMA auto_vacuum = OFF;
    PRAGMA page_size = 2048;
    CREATE TABLE abc(a, b);
  }
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(9, 10);
  }
  file exists test.db-journal
} {0}
do_test io-2.9.3 {
  execsql { COMMIT }
} {}

# Test a couple of the more specific IOCAP_ATOMIC flags 
# (i.e IOCAP_ATOMIC2K etc.).
#
do_test io-2.10.1 {
  sqlite3_simulate_device -char atomic1k
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(11, 12);
  }
  file exists test.db-journal
} {1}
do_test io-2.10.2 {
  execsql { ROLLBACK }
  sqlite3_simulate_device -char atomic2k
  execsql {
    BEGIN;
    INSERT INTO abc VALUES(11, 12);
  }
  file exists test.db-journal
} {0}
do_test io-2.10.3 {
  execsql { ROLLBACK }
} {}

do_test io-2.11.0 {
  execsql { 
    PRAGMA locking_mode = exclusive;
    PRAGMA locking_mode;
  }
} {exclusive exclusive}
do_test io-2.11.1 {
  execsql { 
    INSERT INTO abc VALUES(11, 12);
  }
  file exists test.db-journal
} {0}

do_test io-2.11.2 {
  execsql { 
    PRAGMA locking_mode = normal;
    INSERT INTO abc VALUES(13, 14);
  }
  file exists test.db-journal
} {0}

} ;# /* ifcapable atomicwrite */

#----------------------------------------------------------------------
# Test cases io-3.* test the IOCAP_SEQUENTIAL optimization.
#
sqlite3_simulate_device -char sequential -sectorsize 0
ifcapable pager_pragmas {
  do_test io-3.1 {
    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db -vfs devsym
    db eval {
      PRAGMA auto_vacuum=OFF;
    }
    # File size might be 1 due to the hack to work around ticket #3260.
    # Search for #3260 in os_unix.c for additional information.
    expr {[file size test.db]>1}
  } {0}
  do_test io-3.2 {
    execsql { CREATE TABLE abc(a, b) }
    nSync
    execsql {
      PRAGMA temp_store = memory;
      PRAGMA cache_size = 10;
      BEGIN;
      INSERT INTO abc VALUES('hello', 'world');
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
      INSERT INTO abc SELECT * FROM abc;
    }
    # File has grown - showing there was a cache-spill - but there 
    # have been no calls to fsync(). The file is probably about 30KB.
    # But some VFS implementations (symbian) buffer writes so the actual
    # size may be a little less than that. So this test case just tests
    # that the file is now greater than 20000 bytes in size.
    list [expr [file size test.db]>20000] [nSync]
  } {1 0}
  do_test io-3.3 {
    # The COMMIT requires a single fsync() - to the database file.
    execsql { COMMIT }
    list [file size test.db] [nSync]
  } {39936 1}
}

#----------------------------------------------------------------------
# Test cases io-4.* test the IOCAP_SAFE_APPEND optimization.
#
sqlite3_simulate_device -char safe_append

# With the SAFE_APPEND flag set, simple transactions require 3, rather
# than 4, calls to fsync(). The fsync() calls are on:
#
#   1) The directory in which the journal file is created, (unix only)
#   2) The journal file (to sync the page data),
#   3) The database file.
#
# Normally, when the SAFE_APPEND flag is not set, there is another fsync()
# on the journal file between steps (2) and (3) above.
#
set expected_sync_count 2
if {$::tcl_platform(platform)=="unix"} {
  ifcapable dirsync {
    incr expected_sync_count
  }
}

do_test io-4.1 {
  execsql { DELETE FROM abc }
  nSync
  execsql { INSERT INTO abc VALUES('a', 'b') }
  nSync
} $expected_sync_count

# With SAFE_APPEND set, the nRec field of the journal file header should
# be set to 0xFFFFFFFF before the first journal sync. The nRec field
# occupies bytes 8-11 of the journal file.
#
do_test io-4.2.1 {
  execsql { BEGIN }
  execsql { INSERT INTO abc VALUES('c', 'd') }
  file exists test.db-journal
} {1}
if {$::tcl_platform(platform)=="unix"} {
  do_test io-4.2.2 {
    hexio_read test.db-journal 8 4
  } {FFFFFFFF}
}
do_test io-4.2.3 {
  execsql { COMMIT }
  nSync
} $expected_sync_count
sqlite3_simulate_device -char safe_append

# With SAFE_APPEND set, there should only ever be one journal-header
# written to the database, even though the sync-mode is "full".
#
do_test io-4.3.1 {
  execsql {
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
  }
  expr {[file size test.db]/1024}
} {43}
ifcapable pager_pragmas {
  do_test io-4.3.2 {
    execsql {
      PRAGMA synchronous = full;
      PRAGMA cache_size = 10;
      PRAGMA synchronous;
    }
  } {2}
}
do_test io-4.3.3 {
  execsql {
    BEGIN;
    UPDATE abc SET a = 'x';
  }
  file exists test.db-journal
} {1}
if {$tcl_platform(platform) != "symbian"} {
  # This test is not run on symbian because the file-buffer makes it
  # difficult to predict the exact size of the file as reported by 
  # [file size].
  do_test io-4.3.4 {
    # The UPDATE statement in the statement above modifies 41 pages 
    # (all pages in the database except page 1 and the root page of 
    # abc). Because the cache_size is set to 10, this must have required
    # at least 4 cache-spills. If there were no journal headers written
    # to the journal file after the cache-spill, then the size of the
    # journal file is give by:
    #
    #    <jrnl file size> = <jrnl header size> + nPage * (<page-size> + 8)
    #
    # If the journal file contains additional headers, this formula
    # will not predict the size of the journal file.
    #
    file size test.db-journal
  } [expr 512 + (1024+8)*41]
}

#----------------------------------------------------------------------
# Test cases io-5.* test that the default page size is selected and
# used correctly.
#
set tn 0
foreach {char                 sectorsize pgsize} {
         {}                     512      1024
         {}                    1024      1024
         {}                    2048      2048
         {}                    8192      8192
         {}                   16384      8192
         {atomic}               512      8192
         {atomic512}            512      1024
         {atomic2K}             512      2048
         {atomic2K}            4096      4096
         {atomic2K atomic}      512      8192
         {atomic64K}            512      1024
} {
  incr tn
  if {$pgsize>$::SQLITE_MAX_PAGE_SIZE} continue
  db close
  file delete -force test.db test.db-journal
  sqlite3_simulate_device -char $char -sectorsize $sectorsize
  sqlite3 db test.db -vfs devsym
  db eval {
    PRAGMA auto_vacuum=OFF;
  }
  ifcapable !atomicwrite {
    if {[regexp {^atomic} $char]} continue
  }
  do_test io-5.$tn {
    execsql {
      CREATE TABLE abc(a, b, c);
    }
    expr {[file size test.db]/2}
  } $pgsize
}

sqlite3_simulate_device -char {} -sectorsize 0
finish_test

Added test/ioerr.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# 2001 October 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of I/O errors
# such as writes failing because the disk is full.
# 
# The tests in this file use special facilities that are only
# available in the SQLite test fixture.
#
# $Id: ioerr.test,v 1.43 2009/04/06 17:50:03 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If SQLITE_DEFAULT_AUTOVACUUM is set to true, then a simulated IO error
# on the 8th IO operation in the SQL script below doesn't report an error.
#
# This is because the 8th IO call attempts to read page 2 of the database
# file when the file on disk is only 1 page. The pager layer detects that
# this has happened and suppresses the error returned by the OS layer.
#
do_ioerr_test ioerr-1 -erc 1 -ckrefcount 1 -sqlprep {
  SELECT * FROM sqlite_master;
} -sqlbody {
  CREATE TABLE t1(a,b,c);
  SELECT * FROM sqlite_master;
  BEGIN TRANSACTION;
  INSERT INTO t1 VALUES(1,2,3);
  INSERT INTO t1 VALUES(4,5,6);
  ROLLBACK;
  SELECT * FROM t1;
  BEGIN TRANSACTION;
  INSERT INTO t1 VALUES(1,2,3);
  INSERT INTO t1 VALUES(4,5,6);
  COMMIT;
  SELECT * FROM t1;
  DELETE FROM t1 WHERE a<100;
} -exclude [expr [string match [execsql {pragma auto_vacuum}] 1] ? 4 : 0]

# Test for IO errors during a VACUUM. 
#
# The first IO call is excluded from the test. This call attempts to read
# the file-header of the temporary database used by VACUUM. Since the
# database doesn't exist at that point, the IO error is not detected.
# 
# Additionally, if auto-vacuum is enabled, the 12th IO error is not 
# detected. Same reason as the 8th in the test case above.
# 
ifcapable vacuum {
  do_ioerr_test ioerr-2 -cksum true -ckrefcount true -sqlprep { 
    BEGIN; 
    CREATE TABLE t1(a, b, c); 
    INSERT INTO t1 VALUES(1, randstr(50,50), randstr(50,50)); 
    INSERT INTO t1 SELECT a+2, b||'-'||rowid, c||'-'||rowid FROM t1; 
    INSERT INTO t1 SELECT a+4, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+8, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+16, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+32, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+64, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+128, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 VALUES(1, randstr(600,600), randstr(600,600));
    CREATE TABLE t2 AS SELECT * FROM t1;
    CREATE TABLE t3 AS SELECT * FROM t1;
    COMMIT;
    DROP TABLE t2;
  } -sqlbody {
    VACUUM;
  } -exclude [list \
      1 [expr [string match [execsql {pragma auto_vacuum}] 1]?9:-1]]
}

do_ioerr_test ioerr-3 -ckrefcount true -tclprep {
  execsql {
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE abc(a);
    INSERT INTO abc VALUES(randstr(1500,1500)); -- Page 4 is overflow
  }
  for {set i 0} {$i<150} {incr i} {
    execsql {
      INSERT INTO abc VALUES(randstr(100,100)); 
    }
  }
  execsql COMMIT
} -sqlbody {
  CREATE TABLE abc2(a);
  BEGIN;
  DELETE FROM abc WHERE length(a)>100;
  UPDATE abc SET a = randstr(90,90);
  COMMIT;
  CREATE TABLE abc3(a);
} 

# Test IO errors that can occur retrieving a record header that flows over
# onto an overflow page.
do_ioerr_test ioerr-4 -ckrefcount true -tclprep {
  set sql "CREATE TABLE abc(a1"
  for {set i 2} {$i<1300} {incr i} {
    append sql ", a$i"
  }
  append sql ");"
  execsql $sql
  execsql {INSERT INTO abc (a1) VALUES(NULL)}
} -sqlbody {
 SELECT * FROM abc;
}


# Test IO errors that may occur during a multi-file commit.
#
# Tests 8 and 17 are excluded when auto-vacuum is enabled for the same 
# reason as in test cases ioerr-1.XXX
ifcapable attach {
  set ex ""
  if {[string match [execsql {pragma auto_vacuum}] 1]} {
    set ex [list 4 17]
  }
  do_ioerr_test ioerr-5 -restoreprng 0 -ckrefcount true -sqlprep {
    ATTACH 'test2.db' AS test2;
  } -sqlbody {
    BEGIN;
    CREATE TABLE t1(a,b,c);
    CREATE TABLE test2.t2(a,b,c);
    COMMIT;
  } -exclude $ex
}

# Test IO errors when replaying two hot journals from a 2-file 
# transaction. This test only runs on UNIX.
ifcapable crashtest&&attach {
  if {![catch {sqlite3 -has_codec} r] && !$r} {
    do_ioerr_test ioerr-6 -ckrefcount true -tclprep {
      execsql {
        ATTACH 'test2.db' as aux;
        CREATE TABLE tx(a, b);
        CREATE TABLE aux.ty(a, b);
      }
      set rc [crashsql -delay 2 -file test2.db-journal {
        ATTACH 'test2.db' as aux;
        PRAGMA cache_size = 10;
        BEGIN;
        CREATE TABLE aux.t2(a, b, c);
        CREATE TABLE t1(a, b, c);
        COMMIT;
      }]
      if {$rc!="1 {child process exited abnormally}"} {
        error "Wrong error message: $rc"
      }
    } -sqlbody {
      SELECT * FROM sqlite_master;
      SELECT * FROM aux.sqlite_master;
    }
  }
} 

# Test handling of IO errors that occur while rolling back hot journal
# files.
#
# These tests can't be run on windows because the windows version of 
# SQLite holds a mandatory exclusive lock on journal files it has open.
#
if {$tcl_platform(platform)!="windows"} {
  do_ioerr_test ioerr-7 -tclprep {
    db close
    sqlite3 db2 test2.db
    db2 eval {
      PRAGMA synchronous = 0;
      CREATE TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, 2);
      BEGIN;
      INSERT INTO t1 VALUES(3, 4);
    }
    copy_file test2.db test.db
    copy_file test2.db-journal test.db-journal
    db2 close
  } -tclbody {
    sqlite3 db test.db
    db eval {
      SELECT * FROM t1;
    }
  } -exclude 1
}

# For test coverage:  Cause an I/O failure while trying to read a
# short field (one that fits into a Mem buffer without mallocing
# for space).
#
do_ioerr_test ioerr-8 -ckrefcount true -tclprep {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(randstr(200,200), randstr(1000,1000), 2);
  }
  db close
  sqlite3 db test.db
} -sqlbody {
  SELECT c FROM t1;
}

# For test coverage: Cause an IO error whilst reading the master-journal
# name from a journal file.
if {$tcl_platform(platform)=="unix"} {
  do_ioerr_test ioerr-9 -ckrefcount true -tclprep {
    execsql {
      CREATE TABLE t1(a,b,c);
      INSERT INTO t1 VALUES(randstr(200,200), randstr(1000,1000), 2);
      BEGIN;
      INSERT INTO t1 VALUES(randstr(200,200), randstr(1000,1000), 2);
    }
    copy_file test.db-journal test2.db-journal
    execsql {
      COMMIT;
    }
    copy_file test2.db-journal test.db-journal
    set f [open test.db-journal a]
    fconfigure $f -encoding binary
    puts -nonewline $f "hello"
    puts -nonewline $f "\x00\x00\x00\x05\x01\x02\x03\x04"
    puts -nonewline $f "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7"
    close $f
  } -sqlbody {
    SELECT a FROM t1;
  }
}

# For test coverage: Cause an IO error during statement playback (i.e. 
# a constraint).
do_ioerr_test ioerr-10 -ckrefcount true -tclprep {
  execsql {
    BEGIN;
    CREATE TABLE t1(a PRIMARY KEY, b);
  }
  for {set i 0} {$i < 500} {incr i} {
    execsql {INSERT INTO t1 VALUES(:i, 'hello world');}
  }
  execsql {
    COMMIT;
  }
} -tclbody {

  catch {execsql {
    BEGIN;
    INSERT INTO t1 VALUES('abc', 123);
    INSERT INTO t1 VALUES('def', 123);
    INSERT INTO t1 VALUES('ghi', 123);
    INSERT INTO t1 SELECT (a+500)%900, 'good string' FROM t1;
  }} msg

  if {$msg != "column a is not unique"} {
    error $msg
  }
}

# Assertion fault bug reported by alex dimitrov.
#
do_ioerr_test ioerr-11 -ckrefcount true -erc 1 -sqlprep {
   CREATE TABLE A(Id INTEGER, Name TEXT);
   INSERT INTO A(Id, Name) VALUES(1, 'Name');
} -sqlbody {
   UPDATE A SET Id = 2, Name = 'Name2' WHERE Id = 1;
}

# Test that an io error encountered in a sync() caused by a call to
# sqlite3_release_memory() is handled Ok. Only try this if 
# memory-management is enabled.
#
ifcapable memorymanage {
  do_ioerr_test memmanage-ioerr1 -ckrefcount true -sqlprep {
    BEGIN;
    CREATE TABLE t1(a, b, c);
    INSERT INTO t1 VALUES(randstr(50,50), randstr(100,100), randstr(10,10));
    INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1;
  } -tclbody {
    sqlite3_release_memory 
  } -sqlbody {
    COMMIT;
  }
}

ifcapable pager_pragmas&&autovacuum {
  do_ioerr_test ioerr-12 -ckrefcount true -erc 1 -sqlprep {
     PRAGMA page_size = 512;
     PRAGMA auto_vacuum = incremental;
     CREATE TABLE t1(x);
     INSERT INTO t1 VALUES( randomblob(1   * (512-4)) );
     INSERT INTO t1 VALUES( randomblob(110 * (512-4)) );
     INSERT INTO t1 VALUES( randomblob(2   * (512-4)) );
     INSERT INTO t1 VALUES( randomblob(110 * (512-4)) );
     INSERT INTO t1 VALUES( randomblob(3 * (512-4)) );
     DELETE FROM t1 WHERE rowid = 3;
     PRAGMA incremental_vacuum = 2;
     DELETE FROM t1 WHERE rowid = 1;
  } -sqlbody {
     PRAGMA incremental_vacuum = 1;
  }
}

# Usually, after a new page is allocated from the end of the file, it does
# not need to be written to the journal. The exception is when the new page
# shares its sector with an existing page that does need to be journalled.
# This test case provokes this condition to test for the sake of coverage
# that an IO error while journalling the coresident page is handled correctly.
#
sqlite3_simulate_device -char {} -sectorsize 2048
do_ioerr_test ioerr-12 -ckrefcount true -erc 1 -tclprep {
  db close
  sqlite3 db test.db -vfs devsym

  # Create a test database. Page 2 is the root page of table t1. The only
  # row inserted into t1 has an overflow page - page 3. Page 3 will be
  # coresident on the 2048 byte sector with the next page to be allocated.
  # 
  db eval { PRAGMA page_size = 1024 }
  db eval { CREATE TABLE t1(x) }
  db eval { INSERT INTO t1 VALUES(randomblob(1100)); }
} -tclbody {
  db eval { INSERT INTO t1 VALUES(randomblob(2000)); }
}
sqlite3_simulate_device -char {} -sectorsize 0
catch {db close}

do_ioerr_test ioerr-13 -ckrefcount true -erc 1 -sqlprep {
  PRAGMA auto_vacuum = incremental;
  CREATE TABLE t1(x);
  CREATE TABLE t2(x);
  INSERT INTO t2 VALUES(randomblob(1500));
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t1 VALUES(randomblob(20));
  INSERT INTO t1 SELECT x FROM t1;
  INSERT INTO t1 SELECT x FROM t1;
  INSERT INTO t1 SELECT x FROM t1;
  INSERT INTO t1 SELECT x FROM t1;
  INSERT INTO t1 SELECT x FROM t1;
  INSERT INTO t1 SELECT x FROM t1;             /* 64 entries in t1 */
  INSERT INTO t1 SELECT x FROM t1 LIMIT 14;    /* 78 entries in t1 */
  DELETE FROM t2 WHERE rowid = 3;
} -sqlbody {
  -- This statement uses the balance_quick() optimization. The new page
  -- is appended to the database file. But the overflow page used by
  -- the new record will be positioned near the start of the database
  -- file, in the gap left by the "DELETE FROM t2 WHERE rowid=3" statement
  -- above.
  --
  -- The point of this is that the statement wil need to update two pointer
  -- map pages. Which introduces another opportunity for an IO error.
  --
  INSERT INTO t1 VALUES(randomblob(2000));
}

do_ioerr_test ioerr-14 -ckrefcount true -erc 1 -sqlprep {
  PRAGMA auto_vacuum = incremental;
  CREATE TABLE t1(x);
  CREATE TABLE t2(x);
  INSERT INTO t2 VALUES(randomblob(1500));
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;
  INSERT INTO t2 SELECT randomblob(1500) FROM t2;

  -- This statement inserts a row into t1 with an overflow page at the
  -- end of the file. A long way from its parent (the root of t1).
  INSERT INTO t1 VALUES(randomblob(1500));
  DELETE FROM t2 WHERE rowid<10;
} -sqlbody {
  -- This transaction will cause the root-page of table t1 to divide
  -- (by calling balance_deeper()). When it does, the "parent" page of the
  -- overflow page inserted in the -sqlprep block above will change and
  -- the corresponding pointer map page be updated. This test case attempts
  -- to cause an IO error during the pointer map page update.
  --
  BEGIN;
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  INSERT INTO t1 VALUES(randomblob(100));
  COMMIT;
}

do_ioerr_test ioerr-15 -tclprep {
  db eval {
    BEGIN;
    PRAGMA cache_size = 10;
    CREATE TABLE t1(a);
    CREATE INDEX i1 ON t1(a);
    CREATE TABLE t2(a);
  }
  for {set ii 1} {$ii < 100} {incr ii} {
    set v [string range [string repeat [format %.3d $ii] 200] 0 220]
    db eval {INSERT INTO t1 VALUES($v)}
  }
  db eval {
    DELETE FROM t1 WHERE oid > 85;
    COMMIT;
  }
} -sqlbody {
  BEGIN;
  INSERT INTO t2 VALUES(randstr(22000,22000));
  DELETE FROM t1 WHERE oid = 83;
  COMMIT;
} 

# This test verifies that IO errors that occur within the obscure branch
# of code executed by tkt3762.test are correctly reported.
#
ifcapable vacuum&&autovacuum&&pragma {
  do_ioerr_test ioerr-16 -erc 1 -ckrefcount 1 -sqlprep {
    PRAGMA auto_vacuum=INCREMENTAL;
    PRAGMA page_size=1024;
    BEGIN;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(zeroblob(900));
    INSERT INTO t1 VALUES(zeroblob(900));
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    DELETE FROM t1 WHERE rowid>202;
    COMMIT;
    VACUUM;
    PRAGMA cache_size = 10;
    BEGIN;
    DELETE FROM t1 WHERE rowid IN (10,11,12) ;
  } -sqlbody {
    PRAGMA incremental_vacuum(10);
    COMMIT;
  }
}

finish_test

Added test/ioerr2.test.





















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# 2007 April 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of I/O errors
# such as writes failing because the disk is full.
# 
# The tests in this file use special facilities that are only
# available in the SQLite test fixture.
#
# $Id: ioerr2.test,v 1.12 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !integrityck {
  finish_test
  return
}

do_test ioerr2-1.1 {
  execsql {
    PRAGMA cache_size = 10;
    PRAGMA default_cache_size = 10;
    CREATE TABLE t1(a, b, PRIMARY KEY(a, b));
    INSERT INTO t1 VALUES(randstr(400,400),randstr(400,400));
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 4
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 8
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 16
    INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 32
  }
} {}

set ::cksum [execsql {SELECT md5sum(a, b) FROM t1}]
proc check_db {testname} {

  # Make sure no I/O errors are simulated in this proc.
  set ::sqlite_io_error_hit 0
  set ::sqlite_io_error_persist 0
  set ::sqlite_io_error_pending 0

  # Run an integrity-check. If "disk I/O error" is returned, the
  # pager must be in error state. In this case open a new database
  # connection. Otherwise, try a ROLLBACK, in case a transaction 
  # is still active.
  set rc [catch {execsql {PRAGMA integrity_check}} msg]
  if {$rc && ($msg eq "disk I/O error" || $msg eq "database is locked")} {
    db close
    sqlite3 db test.db
    set refcnt 0
  } else {
    if {$rc || $msg ne "ok"} {
      error $msg
    }
    catch {execsql ROLLBACK}
  }

  # Check that the database checksum is still $::cksum, and that
  # the integrity-check passes.
  set ck [execsql {SELECT md5sum(a, b) FROM t1}]
  do_test ${testname}.cksum [list set ck $ck] $::cksum
  integrity_check ${testname}.integrity
  do_test ${testname}.refcnt {
    lindex [sqlite3_pager_refcounts db] 0
  } 0
}

check_db ioerr2-2

set sql {
  PRAGMA cache_size = 10;
  PRAGMA default_cache_size = 10;
  BEGIN;
  DELETE FROM t1 WHERE (oid%7)==0;
  INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) 
    WHERE (random()%7)==0;
  UPDATE t1 SET a = randstr(400,400), b = randstr(400,400) 
    WHERE (random()%7)==0;
  ROLLBACK;
}

foreach bPersist [list 0 1] {
  set ::go 1
  for {set ::N 1} {$::go} {incr ::N} {
    db close
    sqlite3 db test.db
    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_persist $bPersist
    set ::sqlite_io_error_pending $::N

    foreach {::go res} [catchsql $sql] {}
    check_db ioerr2-3.$bPersist.$::N
  }
}
foreach bPersist [list 0 1] {
  set ::go 1
  for {set ::N 1} {$::go} {incr ::N} {
    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_persist $bPersist
    set ::sqlite_io_error_pending $::N

    foreach {::go res} [catchsql $sql] {}
    check_db ioerr2-4.[expr {$bPersist+2}].$::N
  }
}

do_test ioerr2-5 {
  execsql {
    CREATE TABLE t2 AS SELECT * FROM t1;
    PRAGMA temp_store = memory;
  }
  set ::sqlite_io_error_persist 0
  set ::go 1
  set rc [catch {
    for {set ::N 2} {$::N<200} {incr ::N} {
      db eval {SELECT * FROM t1 WHERE rowid IN (1, 5, 10, 15, 20)} {
        set ::sqlite_io_error_hit 0
        set ::sqlite_io_error_pending $::N
        set sql {UPDATE t2 SET b = randstr(400,400)}
        foreach {::go res} [catchsql $sql] {}
      }
    }
  } msg]
  list $rc $msg
} {1 {callback requested query abort}}

if {$::tcl_platform(platform) == "unix"} {
  # Cause the call to xAccess used by [pragma temp_store_directory] to
  # determine if the specified directory is writable to fail. This causes
  # SQLite to report "not a writable directory", which is probably the
  # right answer.
  #
  do_test ioerr2-6 {
    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_pending 1
    catchsql {PRAGMA temp_store_directory = '/tmp/'}
  } {1 {not a writable directory}}
}

do_ioerr_test ioerr2-7 -persist 0 -sqlprep {
  PRAGMA cache_size = 10;
  PRAGMA auto_vacuum = 1;
  CREATE TABLE ab(a, b);
  CREATE TABLE de(d, e);
  INSERT INTO ab VALUES(1, randstr(200,200));
  INSERT INTO ab SELECT a+1, randstr(200,200) FROM ab;
  INSERT INTO ab SELECT a+2, randstr(200,200) FROM ab;
  INSERT INTO ab SELECT a+4, randstr(200,200) FROM ab;
  INSERT INTO ab SELECT a+8, randstr(200,200) FROM ab;
  INSERT INTO ab SELECT a+16, randstr(200,200) FROM ab;
  INSERT INTO ab SELECT a+32, randstr(200,200) FROM ab;
  INSERT INTO ab SELECT a+64, randstr(200,200) FROM ab;
  INSERT INTO de SELECT * FROM ab;
} -sqlbody {
  BEGIN;
  UPDATE ab SET b = randstr(200,200);
  UPDATE de SET e = randstr(200,200) WHERE d = (SELECT max(d) FROM de);
  DELETE FROM ab;
  COMMIT;
}

finish_test

Added test/ioerr3.test.





















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 2007 December 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of I/O errors
# in conjunction with very small soft-heap-limit values.
#
# $Id: ioerr3.test,v 1.2 2008/01/19 23:50:26 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_ioerr_test ioerr3-1 -sqlprep {
  CREATE TABLE t1(id INTEGER, name TEXT);
} -tclbody {
  sqlite3_soft_heap_limit 8192
  db cache size 0
  execsql BEGIN
  for {set ii 0} {$ii < 100} {incr ii} {
    execsql {
      INSERT INTO t1(id, name) VALUES (1,
'A1234567890B1234567890C1234567890D1234567890E1234567890F1234567890G1234567890H1234567890I1234567890J1234567890K1234567890L1234567890M1234567890N1234567890O1234567890P1234567890Q1234567890R1234567890'
      );
    }
  }
  execsql COMMIT
}

do_ioerr_test ioerr3-2 -sqlbody {
  CREATE TEMP TABLE t1(x,y);
}

sqlite3_soft_heap_limit 0

finish_test

Added test/ioerr4.test.









































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# 2007 December 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing for correct handling of I/O errors
# during incremental vacuum with a shared cache.
#
# $Id: ioerr4.test,v 1.2 2008/05/08 01:11:42 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# This test requires both shared cache and incremental vacuum.
#
ifcapable {!shared_cache || !autovacuum} {
  finish_test
  return
}

# Enable shared cache mode and incremental vacuum.
#
do_test ioerr4-1.1 {
  db close
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
} {0}
do_test ioerr4-1.2 {
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  sqlite3 db2 test.db
  db eval {
    PRAGMA auto_vacuum=INCREMENTAL;
    CREATE TABLE a(i INTEGER, b BLOB);
  }
  db2 eval {
    SELECT name FROM sqlite_master
  }
} {a}
do_test ioerr4-1.3 {
  db eval {
    PRAGMA auto_vacuum;
  }
} {2}

# Insert and delete many records in order to put lots of pages
# on the freelist.
#
do_test ioerr4-1.4 {
  db eval {
    INSERT INTO a VALUES(1, zeroblob(2000));
    INSERT INTO a VALUES(2, zeroblob(2000));
    INSERT INTO a SELECT i+2, zeroblob(2000) FROM a;
    INSERT INTO a SELECT i+4, zeroblob(2000) FROM a;
    INSERT INTO a SELECT i+8, zeroblob(2000) FROM a;
    INSERT INTO a SELECT i+16, zeroblob(2000) FROM a;
    SELECT count(*) FROM a;
  }
} {32}
do_test ioerr4-1.5 {
  db eval {
    PRAGMA freelist_count
  }
} {0}
do_test ioerr4-1.6 {
  db eval {
    DELETE FROM a;
    PRAGMA freelist_count;
  }
} {64}

# Set up for an I/O error on incremental vacuum
# with two connections on shared cache.
#
db close
db2 close
file copy -force test.db test.db-bu
do_ioerr_test ioerr4-2 -tclprep {
  catch {db2 close}
  db close
  file delete -force test.db test.db-journal
  file copy -force test.db-bu test.db
  sqlite3_enable_shared_cache 1
  set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
  db eval {PRAGMA auto_vacuum=INCREMENTAL}
  sqlite3 db2 test.db
} -tclbody {
  db eval {PRAGMA incremental_vacuum(5)}
}

db2 close
file delete -force test.db-bu
sqlite3_enable_shared_cache $::enable_shared_cache

finish_test

Added test/ioerr5.test.



























































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# 2008 May 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests that if sqlite3_release_memory() is called to reclaim
# memory from a pager that is in the error-state, SQLite does not 
# incorrectly write dirty pages out to the database (not safe to do
# once the pager is in error state).
#
# $Id: ioerr5.test,v 1.5 2008/08/28 18:35:34 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !memorymanage||!shared_cache {
  finish_test
  return
}

db close

set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
set ::soft_limit [sqlite3_soft_heap_limit 1048576]

# This procedure prepares, steps and finalizes an SQL statement via the
# UTF-16 APIs. The text representation of an SQLite error code is returned
# ("SQLITE_OK", "SQLITE_IOERR" etc.). The actual results returned by the
# SQL statement, if it is a SELECT, are not available.
#
# This can be useful for testing because it forces SQLite to make an extra 
# call to sqlite3_malloc() when translating from the supplied UTF-16 to
# the UTF-8 encoding used internally.
#
proc dosql16 {zSql {db db}} {
  set sql [encoding convertto unicode $zSql]
  append sql "\00\00"
  set stmt [sqlite3_prepare16 $db $sql -1 {}]
  sqlite3_step $stmt
  set rc [sqlite3_finalize $stmt]
}

proc compilesql16 {zSql {db db}} {
  set sql [encoding convertto unicode $zSql]
  append sql "\00\00"
  set stmt [sqlite3_prepare16 $db $sql -1 {}]
  set rc [sqlite3_finalize $stmt]
}

# Open two database connections (handle db and db2) to database "test.db".
#
proc opendatabases {} {
  catch {db close}
  catch {db2 close}
  sqlite3 db test.db
  sqlite3 db2 test.db
  db2 cache size 0
  db cache size 0
  execsql {
    pragma page_size=512;
    pragma auto_vacuum=2;
    pragma cache_size=16;
  }
}

# Open two database connections and create a single table in the db.
#
do_test ioerr5-1.0 {
  opendatabases
  execsql { CREATE TABLE A(Id INTEGER, Name TEXT) }
} {}

foreach locking_mode {normal exclusive} {
  set nPage 2
  for {set iFail 1} {$iFail<200} {incr iFail} {
    sqlite3_soft_heap_limit 1048576
    opendatabases
    execsql { pragma locking_mode=exclusive }
    set nRow [db one {SELECT count(*) FROM a}]
  
    # Dirty (at least) one of the pages in the cache.
    do_test ioerr5-1.$locking_mode-$iFail.1 {
      execsql {
        BEGIN EXCLUSIVE;
        INSERT INTO a VALUES(1, 'ABCDEFGHIJKLMNOP');
      }
    } {}
  
    # Now try to commit the transaction. Cause an IO error to occur
    # within this operation, which moves the pager into the error state.
    #
    set ::sqlite_io_error_persist 1
    set ::sqlite_io_error_pending $iFail
    do_test ioerr5-1.$locking_mode-$iFail.2 {
      set rc [catchsql {COMMIT}]
      list
    } {}
    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_persist 0
    set ::sqlite_io_error_pending 0
  
    # Read the contents of the database file into a Tcl variable.
    #
    set fd [open test.db]
    fconfigure $fd -translation binary -encoding binary
    set zDatabase [read $fd]
    close $fd

    # Set a very low soft-limit and then try to compile an SQL statement 
    # from UTF-16 text. To do this, SQLite will need to reclaim memory
    # from the pager that is in error state. Including that associated
    # with the dirty page.
    #
    do_test ioerr5-1.$locking_mode-$iFail.3 {
      set bt [btree_from_db db]
      sqlite3_soft_heap_limit 1024
      compilesql16 "SELECT 10"
      array set stats [btree_pager_stats $bt]

      # If the pager made it all the way to PAGER_SYNCED state, then 
      # both in-memory pages are clean. Following the calls to 
      # release_memory() that were made as part of the [compilesql16]
      # above, there will be zero pages left in the cache.
      #
      # If the pager did not make it as far as PAGER_SYNCED, the two
      # in memory pages are still dirty. So there will be 2 pages left
      # in the cache following the release_memory() calls.
      #
      if {$stats(state)==5} {
        set nPage 0
      }
      expr {$stats(page)==$nPage}
    } {1}

    # Ensure that nothing was written to the database while reclaiming
    # memory from the pager in error state.
    #
    do_test ioerr5-1.$locking_mode-$iFail.4 {
      set fd [open test.db]
      fconfigure $fd -translation binary -encoding binary
      set zDatabase2 [read $fd]
      close $fd
      expr {$zDatabase eq $zDatabase2}
    } {1}
  
    if {$rc eq [list 0 {}]} {
      do_test ioerr5.1-$locking_mode-$iFail.3 {
        execsql { SELECT count(*) FROM a }
      } [expr $nRow+1]
      break
    }
  }
}

# Make sure this test script doesn't leave any files open.
#
do_test ioerr5-1.X {
  catch { db close }
  catch { db2 close }
  set sqlite_open_file_count
} 0

do_test ioerr5-2.0 {
  sqlite3 db test.db
  execsql { CREATE INDEX i1 ON a(id, name); }
} {}

foreach locking_mode {exclusive normal} {
  for {set iFail 1} {$iFail<200} {incr iFail} {
    sqlite3_soft_heap_limit 1048576
    opendatabases
    execsql { pragma locking_mode=exclusive }
    set nRow [db one {SELECT count(*) FROM a}]
  
    do_test ioerr5-2.$locking_mode-$iFail.1 {
      execsql {
        BEGIN EXCLUSIVE;
        INSERT INTO a VALUES(1, 'ABCDEFGHIJKLMNOP');
      }
    } {}

    set ::sqlite_io_error_persist 1
    set ::sqlite_io_error_pending $iFail

    sqlite3_release_memory 10000

    set error_hit $::sqlite_io_error_hit
    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_persist 0
    set ::sqlite_io_error_pending 0
    if {$error_hit} {
      do_test ioerr5-2.$locking_mode-$iFail.3a {
        catchsql COMMIT
      } {1 {disk I/O error}}
    } else {
      do_test ioerr5-2.$locking_mode-$iFail.3b {
        execsql COMMIT
      } {}
      break
    }
  }
}

# Make sure this test script doesn't leave any files open.
#
do_test ioerr5-2.X {
  catch { db close }
  catch { db2 close }
  set sqlite_open_file_count
} 0

sqlite3_enable_shared_cache $::enable_shared_cache
sqlite3_soft_heap_limit $::soft_limit

finish_test

Added test/join.test.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for joins, including outer joins.
#
# $Id: join.test,v 1.27 2009/07/01 16:12:08 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test join-1.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(2,3,4);
    INSERT INTO t1 VALUES(3,4,5);
    SELECT * FROM t1;
  }  
} {1 2 3 2 3 4 3 4 5}
do_test join-1.2 {
  execsql {
    CREATE TABLE t2(b,c,d);
    INSERT INTO t2 VALUES(1,2,3);
    INSERT INTO t2 VALUES(2,3,4);
    INSERT INTO t2 VALUES(3,4,5);
    SELECT * FROM t2;
  }  
} {1 2 3 2 3 4 3 4 5}

do_test join-1.3 {
  execsql2 {
    SELECT * FROM t1 NATURAL JOIN t2;
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test join-1.3.1 {
  execsql2 {
    SELECT * FROM t2 NATURAL JOIN t1;
  }
} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2}
do_test join-1.3.2 {
  execsql2 {
    SELECT * FROM t2 AS x NATURAL JOIN t1;
  }
} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2}
do_test join-1.3.3 {
  execsql2 {
    SELECT * FROM t2 NATURAL JOIN t1 AS y;
  }
} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2}
do_test join-1.3.4 {
  execsql {
    SELECT b FROM t1 NATURAL JOIN t2;
  }
} {2 3}

# ticket #3522
do_test join-1.3.5 {
  execsql2 {
    SELECT t2.* FROM t2 NATURAL JOIN t1
  }
} {b 2 c 3 d 4 b 3 c 4 d 5}
do_test join-1.3.6 {
  execsql2 {
    SELECT xyzzy.* FROM t2 AS xyzzy NATURAL JOIN t1
  }
} {b 2 c 3 d 4 b 3 c 4 d 5}
do_test join-1.3.7 {
  execsql2 {
    SELECT t1.* FROM t2 NATURAL JOIN t1
  }
} {a 1 b 2 c 3 a 2 b 3 c 4}
do_test join-1.3.8 {
  execsql2 {
    SELECT xyzzy.* FROM t2 NATURAL JOIN t1 AS xyzzy
  }
} {a 1 b 2 c 3 a 2 b 3 c 4}
do_test join-1.3.9 {
  execsql2 {
    SELECT aaa.*, bbb.* FROM t2 AS aaa NATURAL JOIN t1 AS bbb
  }
} {b 2 c 3 d 4 a 1 b 2 c 3 b 3 c 4 d 5 a 2 b 3 c 4}
do_test join-1.3.10 {
  execsql2 {
    SELECT t1.*, t2.* FROM t2 NATURAL JOIN t1
  }
} {a 1 b 2 c 3 b 2 c 3 d 4 a 2 b 3 c 4 b 3 c 4 d 5}


do_test join-1.4.1 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test join-1.4.2 {
  execsql2 {
    SELECT * FROM t1 AS x INNER JOIN t2 USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test join-1.4.3 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 AS y USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test join-1.4.4 {
  execsql2 {
    SELECT * FROM t1 AS x INNER JOIN t2 AS y USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test join-1.4.5 {
  execsql {
    SELECT b FROM t1 JOIN t2 USING(b);
  }
} {2 3}

# Ticket #3522
do_test join-1.4.6 {
  execsql2 {
    SELECT t1.* FROM t1 JOIN t2 USING(b);
  }
} {a 1 b 2 c 3 a 2 b 3 c 4}
do_test join-1.4.7 {
  execsql2 {
    SELECT t2.* FROM t1 JOIN t2 USING(b);
  }
} {b 2 c 3 d 4 b 3 c 4 d 5}

do_test join-1.5 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(b);
  }
} {a 1 b 2 c 3 c 3 d 4 a 2 b 3 c 4 c 4 d 5}
do_test join-1.6 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(c);
  }
} {a 1 b 2 c 3 b 2 d 4 a 2 b 3 c 4 b 3 d 5}
do_test join-1.7 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(c,b);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}

do_test join-1.8 {
  execsql {
    SELECT * FROM t1 NATURAL CROSS JOIN t2;
  }
} {1 2 3 4 2 3 4 5}
do_test join-1.9 {
  execsql {
    SELECT * FROM t1 CROSS JOIN t2 USING(b,c);
  }
} {1 2 3 4 2 3 4 5}
do_test join-1.10 {
  execsql {
    SELECT * FROM t1 NATURAL INNER JOIN t2;
  }
} {1 2 3 4 2 3 4 5}
do_test join-1.11 {
  execsql {
    SELECT * FROM t1 INNER JOIN t2 USING(b,c);
  }
} {1 2 3 4 2 3 4 5}
do_test join-1.12 {
  execsql {
    SELECT * FROM t1 natural inner join t2;
  }
} {1 2 3 4 2 3 4 5}

ifcapable subquery {
  do_test join-1.13 {
    execsql2 {
      SELECT * FROM t1 NATURAL JOIN 
        (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as t3
    }
  } {a 1 b 2 c 3 d 4 e 5}
  do_test join-1.14 {
    execsql2 {
      SELECT * FROM (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as 'tx'
          NATURAL JOIN t1
    }
  } {c 3 d 4 e 5 a 1 b 2}
}

do_test join-1.15 {
  execsql {
    CREATE TABLE t3(c,d,e);
    INSERT INTO t3 VALUES(2,3,4);
    INSERT INTO t3 VALUES(3,4,5);
    INSERT INTO t3 VALUES(4,5,6);
    SELECT * FROM t3;
  }  
} {2 3 4 3 4 5 4 5 6}
do_test join-1.16 {
  execsql {
    SELECT * FROM t1 natural join t2 natural join t3;
  }
} {1 2 3 4 5 2 3 4 5 6}
do_test join-1.17 {
  execsql2 {
    SELECT * FROM t1 natural join t2 natural join t3;
  }
} {a 1 b 2 c 3 d 4 e 5 a 2 b 3 c 4 d 5 e 6}
do_test join-1.18 {
  execsql {
    CREATE TABLE t4(d,e,f);
    INSERT INTO t4 VALUES(2,3,4);
    INSERT INTO t4 VALUES(3,4,5);
    INSERT INTO t4 VALUES(4,5,6);
    SELECT * FROM t4;
  }  
} {2 3 4 3 4 5 4 5 6}
do_test join-1.19.1 {
  execsql {
    SELECT * FROM t1 natural join t2 natural join t4;
  }
} {1 2 3 4 5 6}
do_test join-1.19.2 {
  execsql2 {
    SELECT * FROM t1 natural join t2 natural join t4;
  }
} {a 1 b 2 c 3 d 4 e 5 f 6}
do_test join-1.20 {
  execsql {
    SELECT * FROM t1 natural join t2 natural join t3 WHERE t1.a=1
  }
} {1 2 3 4 5}

do_test join-2.1 {
  execsql {
    SELECT * FROM t1 NATURAL LEFT JOIN t2;
  }
} {1 2 3 4 2 3 4 5 3 4 5 {}}

# ticket #3522
do_test join-2.1.1 {
  execsql2 {
    SELECT * FROM t1 NATURAL LEFT JOIN t2;
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5 a 3 b 4 c 5 d {}}
do_test join-2.1.2 {
  execsql2 {
    SELECT t1.* FROM t1 NATURAL LEFT JOIN t2;
  }
} {a 1 b 2 c 3 a 2 b 3 c 4 a 3 b 4 c 5}
do_test join-2.1.3 {
  execsql2 {
    SELECT t2.* FROM t1 NATURAL LEFT JOIN t2;
  }
} {b 2 c 3 d 4 b 3 c 4 d 5 b {} c {} d {}}

do_test join-2.2 {
  execsql {
    SELECT * FROM t2 NATURAL LEFT OUTER JOIN t1;
  }
} {1 2 3 {} 2 3 4 1 3 4 5 2}
do_test join-2.3 {
  catchsql {
    SELECT * FROM t1 NATURAL RIGHT OUTER JOIN t2;
  }
} {1 {RIGHT and FULL OUTER JOINs are not currently supported}}
do_test join-2.4 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d
  }
} {1 2 3 {} {} {} 2 3 4 {} {} {} 3 4 5 1 2 3}
do_test join-2.5 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t1.a>1
  }
} {2 3 4 {} {} {} 3 4 5 1 2 3}
do_test join-2.6 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t2.b IS NULL OR t2.b>1
  }
} {1 2 3 {} {} {} 2 3 4 {} {} {}}

do_test join-3.1 {
  catchsql {
    SELECT * FROM t1 NATURAL JOIN t2 ON t1.a=t2.b;
  }
} {1 {a NATURAL join may not have an ON or USING clause}}
do_test join-3.2 {
  catchsql {
    SELECT * FROM t1 NATURAL JOIN t2 USING(b);
  }
} {1 {a NATURAL join may not have an ON or USING clause}}
do_test join-3.3 {
  catchsql {
    SELECT * FROM t1 JOIN t2 ON t1.a=t2.b USING(b);
  }
} {1 {cannot have both ON and USING clauses in the same join}}
do_test join-3.4.1 {
  catchsql {
    SELECT * FROM t1 JOIN t2 USING(a);
  }
} {1 {cannot join using column a - column not present in both tables}}
do_test join-3.4.2 {
  catchsql {
    SELECT * FROM t1 JOIN t2 USING(d);
  }
} {1 {cannot join using column d - column not present in both tables}}
do_test join-3.5 {
  catchsql { SELECT * FROM t1 USING(a) }
} {1 {a JOIN clause is required before USING}}
do_test join-3.6 {
  catchsql {
    SELECT * FROM t1 JOIN t2 ON t3.a=t2.b;
  }
} {1 {no such column: t3.a}}
do_test join-3.7 {
  catchsql {
    SELECT * FROM t1 INNER OUTER JOIN t2;
  }
} {1 {unknown or unsupported join type: INNER OUTER}}
do_test join-3.8 {
  catchsql {
    SELECT * FROM t1 INNER OUTER CROSS JOIN t2;
  }
} {1 {unknown or unsupported join type: INNER OUTER CROSS}}
do_test join-3.9 {
  catchsql {
    SELECT * FROM t1 OUTER NATURAL INNER JOIN t2;
  }
} {1 {unknown or unsupported join type: OUTER NATURAL INNER}}
do_test join-3.10 {
  catchsql {
    SELECT * FROM t1 LEFT BOGUS JOIN t2;
  }
} {1 {unknown or unsupported join type: LEFT BOGUS}}
do_test join-3.11 {
  catchsql {
    SELECT * FROM t1 INNER BOGUS CROSS JOIN t2;
  }
} {1 {unknown or unsupported join type: INNER BOGUS CROSS}}
do_test join-3.12 {
  catchsql {
    SELECT * FROM t1 NATURAL AWK SED JOIN t2;
  }
} {1 {unknown or unsupported join type: NATURAL AWK SED}}

do_test join-4.1 {
  execsql {
    BEGIN;
    CREATE TABLE t5(a INTEGER PRIMARY KEY);
    CREATE TABLE t6(a INTEGER);
    INSERT INTO t6 VALUES(NULL);
    INSERT INTO t6 VALUES(NULL);
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    COMMIT;
  }
  execsql {
    SELECT * FROM t6 NATURAL JOIN t5;
  }
} {}
do_test join-4.2 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a<t5.a;
  }
} {}
do_test join-4.3 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a>t5.a;
  }
} {}
do_test join-4.4 {
  execsql {
    UPDATE t6 SET a='xyz';
    SELECT * FROM t6 NATURAL JOIN t5;
  }
} {}
do_test join-4.6 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a<t5.a;
  }
} {}
do_test join-4.7 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a>t5.a;
  }
} {}
do_test join-4.8 {
  execsql {
    UPDATE t6 SET a=1;
    SELECT * FROM t6 NATURAL JOIN t5;
  }
} {}
do_test join-4.9 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a<t5.a;
  }
} {}
do_test join-4.10 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a>t5.a;
  }
} {}

do_test join-5.1 {
  execsql {
    BEGIN;
    create table centros (id integer primary key, centro);
    INSERT INTO centros VALUES(1,'xxx');
    create table usuarios (id integer primary key, nombre, apellidos,
    idcentro integer);
    INSERT INTO usuarios VALUES(1,'a','aa',1);
    INSERT INTO usuarios VALUES(2,'b','bb',1);
    INSERT INTO usuarios VALUES(3,'c','cc',NULL);
    create index idcentro on usuarios (idcentro);
    END;
    select usuarios.id, usuarios.nombre, centros.centro from
    usuarios left outer join centros on usuarios.idcentro = centros.id;
  }
} {1 a xxx 2 b xxx 3 c {}}

# A test for ticket #247.
#
do_test join-7.1 {
  execsql {
    CREATE TABLE t7 (x, y);
    INSERT INTO t7 VALUES ("pa1", 1);
    INSERT INTO t7 VALUES ("pa2", NULL);
    INSERT INTO t7 VALUES ("pa3", NULL);
    INSERT INTO t7 VALUES ("pa4", 2);
    INSERT INTO t7 VALUES ("pa30", 131);
    INSERT INTO t7 VALUES ("pa31", 130);
    INSERT INTO t7 VALUES ("pa28", NULL);

    CREATE TABLE t8 (a integer primary key, b);
    INSERT INTO t8 VALUES (1, "pa1");
    INSERT INTO t8 VALUES (2, "pa4");
    INSERT INTO t8 VALUES (3, NULL);
    INSERT INTO t8 VALUES (4, NULL);
    INSERT INTO t8 VALUES (130, "pa31");
    INSERT INTO t8 VALUES (131, "pa30");

    SELECT coalesce(t8.a,999) from t7 LEFT JOIN t8 on y=a;
  }
} {1 999 999 2 131 130 999}

# Make sure a left join where the right table is really a view that
# is itself a join works right.  Ticket #306.
#
ifcapable view {
do_test join-8.1 {
  execsql {
    BEGIN;
    CREATE TABLE t9(a INTEGER PRIMARY KEY, b);
    INSERT INTO t9 VALUES(1,11);
    INSERT INTO t9 VALUES(2,22);
    CREATE TABLE t10(x INTEGER PRIMARY KEY, y);
    INSERT INTO t10 VALUES(1,2);
    INSERT INTO t10 VALUES(3,3);    
    CREATE TABLE t11(p INTEGER PRIMARY KEY, q);
    INSERT INTO t11 VALUES(2,111);
    INSERT INTO t11 VALUES(3,333);    
    CREATE VIEW v10_11 AS SELECT x, q FROM t10, t11 WHERE t10.y=t11.p;
    COMMIT;
    SELECT * FROM t9 LEFT JOIN v10_11 ON( a=x );
  }
} {1 11 1 111 2 22 {} {}}
ifcapable subquery {
  do_test join-8.2 {
    execsql {
      SELECT * FROM t9 LEFT JOIN (SELECT x, q FROM t10, t11 WHERE t10.y=t11.p)
           ON( a=x);
    }
  } {1 11 1 111 2 22 {} {}}
}
do_test join-8.3 {
  execsql {
    SELECT * FROM v10_11 LEFT JOIN t9 ON( a=x );
  }
} {1 111 1 11 3 333 {} {}}
ifcapable subquery {
  # Constant expressions in a subquery that is the right element of a
  # LEFT JOIN evaluate to NULL for rows where the LEFT JOIN does not
  # match.  Ticket #3300
  do_test join-8.4 {
    execsql {
      SELECT * FROM t9 LEFT JOIN (SELECT 44, p, q FROM t11) AS sub1 ON p=a
    }
  } {1 11 {} {} {} 2 22 44 2 111}
}
} ;# ifcapable view

# Ticket #350 describes a scenario where LEFT OUTER JOIN does not
# function correctly if the right table in the join is really
# subquery.
#
# To test the problem, we generate the same LEFT OUTER JOIN in two
# separate selects but with on using a subquery and the other calling
# the table directly.  Then connect the two SELECTs using an EXCEPT.
# Both queries should generate the same results so the answer should
# be an empty set.
#
ifcapable compound {
do_test join-9.1 {
  execsql {
    BEGIN;
    CREATE TABLE t12(a,b);
    INSERT INTO t12 VALUES(1,11);
    INSERT INTO t12 VALUES(2,22);
    CREATE TABLE t13(b,c);
    INSERT INTO t13 VALUES(22,222);
    COMMIT;
  }
} {}

ifcapable subquery {
  do_test join-9.1.1 {
    execsql {
      SELECT * FROM t12 NATURAL LEFT JOIN t13
      EXCEPT
      SELECT * FROM t12 NATURAL LEFT JOIN (SELECT * FROM t13 WHERE b>0);
    }
  } {}
}
ifcapable view {
  do_test join-9.2 {
    execsql {
      CREATE VIEW v13 AS SELECT * FROM t13 WHERE b>0;
      SELECT * FROM t12 NATURAL LEFT JOIN t13
        EXCEPT
        SELECT * FROM t12 NATURAL LEFT JOIN v13;
    }
  } {}
} ;# ifcapable view
} ;# ifcapable compound

ifcapable subquery {
  # Ticket #1697:  Left Join WHERE clause terms that contain an
  # aggregate subquery.
  #
  do_test join-10.1 {
    execsql {
      CREATE TABLE t21(a,b,c);
      CREATE TABLE t22(p,q);
      CREATE INDEX i22 ON t22(q);
      SELECT a FROM t21 LEFT JOIN t22 ON b=p WHERE q=
         (SELECT max(m.q) FROM t22 m JOIN t21 n ON n.b=m.p WHERE n.c=1);
    }  
  } {}

  # Test a LEFT JOIN when the right-hand side of hte join is an empty
  # sub-query. Seems fine.
  #
  do_test join-10.2 {
    execsql {
      CREATE TABLE t23(a, b, c);
      CREATE TABLE t24(a, b, c);
      INSERT INTO t23 VALUES(1, 2, 3);
    }
    execsql {
      SELECT * FROM t23 LEFT JOIN t24;
    }
  } {1 2 3 {} {} {}}
  do_test join-10.3 {
    execsql {
      SELECT * FROM t23 LEFT JOIN (SELECT * FROM t24);
    }
  } {1 2 3 {} {} {}}

} ;# ifcapable subquery

#-------------------------------------------------------------------------
# The following tests are to ensure that bug b73fb0bd64 is fixed.
#
do_test join-11.1 {
  drop_all_tables
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT);
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b TEXT);
    INSERT INTO t1 VALUES(1,'abc');
    INSERT INTO t1 VALUES(2,'def');
    INSERT INTO t2 VALUES(1,'abc');
    INSERT INTO t2 VALUES(2,'def');
    SELECT * FROM t1 NATURAL JOIN t2;
  }
} {1 abc 2 def}

do_test join-11.2 {
  execsql { SELECT a FROM t1 JOIN t1 USING (a)}
} {1 2}
do_test join-11.3 {
  execsql { SELECT a FROM t1 JOIN t1 AS t2 USING (a)}
} {1 2}
do_test join-11.3 {
  execsql { SELECT * FROM t1 NATURAL JOIN t1 AS t2}
} {1 abc 2 def}
do_test join-11.4 {
  execsql { SELECT * FROM t1 NATURAL JOIN t1 }
} {1 abc 2 def}

do_test join-11.5 {
  drop_all_tables
  execsql {
    CREATE TABLE t1(a COLLATE nocase, b);
    CREATE TABLE t2(a, b);
    INSERT INTO t1 VALUES('ONE', 1);
    INSERT INTO t1 VALUES('two', 2);
    INSERT INTO t2 VALUES('one', 1);
    INSERT INTO t2 VALUES('two', 2);
  }
} {}
do_test join-11.6 {
  execsql { SELECT * FROM t1 NATURAL JOIN t2 }
} {ONE 1 two 2}
do_test join-11.7 {
  execsql { SELECT * FROM t2 NATURAL JOIN t1 }
} {two 2}

do_test join-11.8 {
  drop_all_tables
  execsql {
    CREATE TABLE t1(a, b TEXT);
    CREATE TABLE t2(b INTEGER, a);
    INSERT INTO t1 VALUES('one', '1.0');
    INSERT INTO t1 VALUES('two', '2');
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(2, 'two');
  }
} {}
do_test join-11.9 {
  execsql { SELECT * FROM t1 NATURAL JOIN t2 }
} {one 1.0 two 2}
do_test join-11.10 {
  execsql { SELECT * FROM t2 NATURAL JOIN t1 }
} {1 one 2 two}

finish_test

Added test/join2.test.























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for joins, including outer joins.
#
# $Id: join2.test,v 1.2 2005/01/21 03:12:16 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test join2-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,11);
    INSERT INTO t1 VALUES(2,22);
    INSERT INTO t1 VALUES(3,33);
    SELECT * FROM t1;
  }  
} {1 11 2 22 3 33}
do_test join2-1.2 {
  execsql {
    CREATE TABLE t2(b,c);
    INSERT INTO t2 VALUES(11,111);
    INSERT INTO t2 VALUES(33,333);
    INSERT INTO t2 VALUES(44,444);
    SELECT * FROM t2;
  }  
} {11 111 33 333 44 444};
do_test join2-1.3 {
  execsql {
    CREATE TABLE t3(c,d);
    INSERT INTO t3 VALUES(111,1111);
    INSERT INTO t3 VALUES(444,4444);
    INSERT INTO t3 VALUES(555,5555);
    SELECT * FROM t3;
  }  
} {111 1111 444 4444 555 5555}

do_test join2-1.4 {
  execsql {
    SELECT * FROM
      t1 NATURAL JOIN t2 NATURAL JOIN t3
  }
} {1 11 111 1111}
do_test join2-1.5 {
  execsql {
    SELECT * FROM
      t1 NATURAL JOIN t2 NATURAL LEFT OUTER JOIN t3
  }
} {1 11 111 1111 3 33 333 {}}
do_test join2-1.6 {
  execsql {
    SELECT * FROM
      t1 NATURAL LEFT OUTER JOIN t2 NATURAL JOIN t3
  }
} {1 11 111 1111}
ifcapable subquery {
  do_test join2-1.7 {
    execsql {
      SELECT * FROM
        t1 NATURAL LEFT OUTER JOIN (t2 NATURAL JOIN t3)
    }
  } {1 11 111 1111 2 22 {} {} 3 33 {} {}}
}

finish_test

Added test/join3.test.





























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for joins, including outer joins, where
# there are a large number of tables involved in the join.
#
# $Id: join3.test,v 1.4 2005/01/19 23:24:51 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# An unrestricted join
#
catch {unset ::result}
set result {}
for {set N 1} {$N<=$bitmask_size} {incr N} {
  lappend result $N
  do_test join3-1.$N {
    execsql "CREATE TABLE t${N}(x);"
    execsql "INSERT INTO t$N VALUES($N)"
    set sql "SELECT * FROM t1"
    for {set i 2} {$i<=$N} {incr i} {append sql ", t$i"}
    execsql $sql
  } $result
}

# Joins with a comparison
#
set result {}
for {set N 1} {$N<=$bitmask_size} {incr N} {
  lappend result $N
  do_test join3-2.$N {
    set sql "SELECT * FROM t1"
    for {set i 2} {$i<=$N} {incr i} {append sql ", t$i"}
    set sep WHERE
    for {set i 1} {$i<$N} {incr i} {
      append sql " $sep t[expr {$i+1}].x==t$i.x+1"
      set sep AND
    }
    execsql $sql
  } $result
}

# Error of too many tables in the join
#
do_test join3-3.1 {
  set sql "SELECT * FROM t1 AS t0, t1"
  for {set i 2} {$i<=$bitmask_size} {incr i} {append sql ", t$i"}
  catchsql $sql
} [list 1 "at most $bitmask_size tables in a join"]


finish_test

Added test/join4.test.





































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for left outer joins containing WHERE
# clauses that restrict the scope of the left term of the join.
#
# $Id: join4.test,v 1.4 2005/03/29 03:11:00 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable tempdb {
  do_test join4-1.1 {
    execsql {
      create temp table t1(a integer, b varchar(10));
      insert into t1 values(1,'one');
      insert into t1 values(2,'two');
      insert into t1 values(3,'three');
      insert into t1 values(4,'four');
  
      create temp table t2(x integer, y varchar(10), z varchar(10));
      insert into t2 values(2,'niban','ok');
      insert into t2 values(4,'yonban','err');
    }
    execsql {
      select * from t1 left outer join t2 on t1.a=t2.x where t2.z='ok'
    }
  } {2 two 2 niban ok}
} else {
  do_test join4-1.1 {
    execsql {
      create table t1(a integer, b varchar(10));
      insert into t1 values(1,'one');
      insert into t1 values(2,'two');
      insert into t1 values(3,'three');
      insert into t1 values(4,'four');
  
      create table t2(x integer, y varchar(10), z varchar(10));
      insert into t2 values(2,'niban','ok');
      insert into t2 values(4,'yonban','err');
    }
    execsql {
      select * from t1 left outer join t2 on t1.a=t2.x where t2.z='ok'
    }
  } {2 two 2 niban ok}
}
do_test join4-1.2 {
  execsql {
    select * from t1 left outer join t2 on t1.a=t2.x and t2.z='ok'
  }
} {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}}
do_test join4-1.3 {
  execsql {
    create index i2 on t2(z);
  }
  execsql {
    select * from t1 left outer join t2 on t1.a=t2.x where t2.z='ok'
  }
} {2 two 2 niban ok}
do_test join4-1.4 {
  execsql {
    select * from t1 left outer join t2 on t1.a=t2.x and t2.z='ok'
  }
} {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}}
do_test join4-1.5 {
  execsql {
    select * from t1 left outer join t2 on t1.a=t2.x where t2.z>='ok'
  }
} {2 two 2 niban ok}
do_test join4-1.4 {
  execsql {
    select * from t1 left outer join t2 on t1.a=t2.x and t2.z>='ok'
  }
} {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}}
ifcapable subquery {
  do_test join4-1.6 {
    execsql {
      select * from t1 left outer join t2 on t1.a=t2.x where t2.z IN ('ok')
    }
  } {2 two 2 niban ok}
  do_test join4-1.7 {
    execsql {
      select * from t1 left outer join t2 on t1.a=t2.x and t2.z IN ('ok')
    }
  } {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}}
}


finish_test

Added test/join5.test.





























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for left outer joins containing ON
# clauses that restrict the scope of the left term of the join.
#
# $Id: join5.test,v 1.2 2007/06/08 00:20:48 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


do_test join5-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a integer primary key, b integer, c integer);
    CREATE TABLE t2(x integer primary key, y);
    CREATE TABLE t3(p integer primary key, q);
    INSERT INTO t3 VALUES(11,'t3-11');
    INSERT INTO t3 VALUES(12,'t3-12');
    INSERT INTO t2 VALUES(11,'t2-11');
    INSERT INTO t2 VALUES(12,'t2-12');
    INSERT INTO t1 VALUES(1, 5, 0);
    INSERT INTO t1 VALUES(2, 11, 2);
    INSERT INTO t1 VALUES(3, 12, 1);
    COMMIT;
  }
} {}
do_test join5-1.2 {
  execsql {
    select * from t1 left join t2 on t1.b=t2.x and t1.c=1
  }
} {1 5 0 {} {} 2 11 2 {} {} 3 12 1 12 t2-12}
do_test join5-1.3 {
  execsql {
    select * from t1 left join t2 on t1.b=t2.x where t1.c=1
  }
} {3 12 1 12 t2-12}
do_test join5-1.4 {
  execsql {
    select * from t1 left join t2 on t1.b=t2.x and t1.c=1
                     left join t3 on t1.b=t3.p and t1.c=2
  }
} {1 5 0 {} {} {} {} 2 11 2 {} {} 11 t3-11 3 12 1 12 t2-12 {} {}}
do_test join5-1.5 {
  execsql {
    select * from t1 left join t2 on t1.b=t2.x and t1.c=1
                     left join t3 on t1.b=t3.p where t1.c=2
  }
} {2 11 2 {} {} 11 t3-11}

# Ticket #2403
#
do_test join5-2.1 {
  execsql {
    CREATE TABLE ab(a,b);
    INSERT INTO "ab" VALUES(1,2);
    INSERT INTO "ab" VALUES(3,NULL);

    CREATE TABLE xy(x,y);
    INSERT INTO "xy" VALUES(2,3);
    INSERT INTO "xy" VALUES(NULL,1);
  }
  execsql {SELECT * FROM xy LEFT JOIN ab ON 0}
} {2 3 {} {} {} 1 {} {}}
do_test join5-2.2 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 1}
} {2 3 1 2 2 3 3 {} {} 1 1 2 {} 1 3 {}}
do_test join5-2.3 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON NULL}
} {2 3 {} {} {} 1 {} {}}
do_test join5-2.4 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 0 WHERE 0}
} {}
do_test join5-2.5 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 1 WHERE 0}
} {}
do_test join5-2.6 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON NULL WHERE 0}
} {}
do_test join5-2.7 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 0 WHERE 1}
} {2 3 {} {} {} 1 {} {}}
do_test join5-2.8 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 1 WHERE 1}
} {2 3 1 2 2 3 3 {} {} 1 1 2 {} 1 3 {}}
do_test join5-2.9 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON NULL WHERE 1}
} {2 3 {} {} {} 1 {} {}}
do_test join5-2.10 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 0 WHERE NULL}
} {}
do_test join5-2.11 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON 1 WHERE NULL}
} {}
do_test join5-2.12 {
  execsql {SELECT * FROM xy LEFT JOIN ab ON NULL WHERE NULL}
} {}


finish_test

Added test/journal1.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2005 March 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure that leftover journals from
# prior databases do not try to rollback into new databases.
#
# $Id: journal1.test,v 1.2 2005/03/20 22:54:56 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# These tests will not work on windows because windows uses
# manditory file locking which breaks the file copy command.
#
if {$tcl_platform(platform)=="windows"} {
  finish_test
  return
}

# Create a smaple database
#
do_test journal1-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,randstr(10,400));
    INSERT INTO t1 VALUES(2,randstr(10,400));
    INSERT INTO t1 SELECT a+2, a||b FROM t1;
    INSERT INTO t1 SELECT a+4, a||b FROM t1;
    SELECT count(*) FROM t1;
  }
} 8

# Make changes to the database and save the journal file.
# Then delete the database.  Replace the the journal file
# and try to create a new database with the same name.  The
# old journal should not attempt to rollback into the new
# database.
#
do_test journal1-1.2 {
  execsql {
    BEGIN;
    DELETE FROM t1;
  }
  file copy -force test.db-journal test.db-journal-bu
  execsql {
    ROLLBACK;
  }
  db close
  file delete test.db
  file copy test.db-journal-bu test.db-journal
  sqlite3 db test.db
  catchsql {
    SELECT * FROM sqlite_master
  }
} {0 {}}

finish_test

Added test/jrnlmode.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# 2008 April 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# of these tests is the journal mode pragma.
#
# $Id: jrnlmode.test,v 1.16 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas} {
  finish_test
  return
}

if {[info exists TEMP_STORE] && $TEMP_STORE>=2} {
  set temp_persist memory
  set temp_delete memory
  set temp_truncate memory
  set temp_off off
} else {
  set temp_persist persist
  set temp_delete delete
  set temp_truncate truncate
  set temp_off off
}

proc temp_journal_mode {newmode} {
  if {[info exists ::TEMP_STORE] && $::TEMP_STORE>=2} {
    if {$newmode ne "off" && $newmode ne "memory"} {
      execsql {PRAGMA temp.journal_mode}
      set newmode [db one {PRAGMA temp.journal_mode}]
    }
  }
  set newmode
}

#----------------------------------------------------------------------
# Test cases jrnlmode-1.X test the PRAGMA logic.
#
do_test jrnlmode-1.0 {
  execsql {
    PRAGMA journal_mode;
    PRAGMA main.journal_mode;
    PRAGMA temp.journal_mode;
  } 
} [list delete delete [temp_journal_mode delete]]
do_test jrnlmode-1.1 {
  execsql {
    PRAGMA journal_mode = persist;
  } 
} {persist}
do_test jrnlmode-1.2 {
  execsql {
    PRAGMA journal_mode;
    PRAGMA main.journal_mode;
    PRAGMA temp.journal_mode;
  } 
} [list persist persist [temp_journal_mode persist]]
do_test jrnlmode-1.4 {
  execsql {
    PRAGMA journal_mode = off;
  } 
} {off}
do_test jrnlmode-1.5 {
  execsql {
    PRAGMA journal_mode;
    PRAGMA main.journal_mode;
    PRAGMA temp.journal_mode;
  } 
} [list off off [temp_journal_mode off]]
do_test jrnlmode-1.6 {
  execsql {
    PRAGMA journal_mode = delete;
  } 
} {delete}
do_test jrnlmode-1.7 {
  execsql {
    PRAGMA journal_mode;
    PRAGMA main.journal_mode;
    PRAGMA Temp.journal_mode;
  } 
} [list delete delete [temp_journal_mode delete]]
do_test jrnlmode-1.7.1 {
  execsql {
    PRAGMA journal_mode = truncate;
  } 
} {truncate}
do_test jrnlmode-1.7.2 {
  execsql {
    PRAGMA journal_mode;
    PRAGMA main.journal_mode;
    PRAGMA temp.journal_mode;
  } 
} [list truncate truncate [temp_journal_mode truncate]]
do_test jrnlmode-1.8 {
  execsql {
    PRAGMA journal_mode = off;
    PRAGMA journal_mode = invalid;
  } 
} {off off}
ifcapable attach {
  do_test jrnlmode-1.9 {
    execsql {
      PRAGMA journal_mode = PERSIST;
      ATTACH ':memory:' as aux1;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA aux1.journal_mode;
    }
  } {persist memory}
  do_test jrnlmode-1.10 {
    execsql {
      PRAGMA main.journal_mode = OFF;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA temp.journal_mode;
      PRAGMA aux1.journal_mode;
    }
  } [list off [temp_journal_mode persist] memory]
  do_test jrnlmode-1.11 {
    execsql {
      PRAGMA journal_mode;
    }
  } {persist}
  do_test jrnlmode-1.12 {
    execsql {
      ATTACH ':memory:' as aux2;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA aux1.journal_mode;
      PRAGMA aux2.journal_mode;
    }
  } {off memory memory}
  do_test jrnlmode-1.13 {
    # The journal-mode used by in-memory databases cannot be changed.
    execsql {
      PRAGMA aux1.journal_mode = DELETE;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA aux1.journal_mode;
      PRAGMA aux2.journal_mode;
    }
  } {off memory memory}
  do_test jrnlmode-1.14 {
    execsql {
      PRAGMA journal_mode = delete;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA temp.journal_mode;
      PRAGMA aux1.journal_mode;
      PRAGMA aux2.journal_mode;
    }
  } [list delete [temp_journal_mode delete] memory memory]
  do_test jrnlmode-1.15 {
    execsql {
      ATTACH ':memory:' as aux3;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA temp.journal_mode;
      PRAGMA aux1.journal_mode;
      PRAGMA aux2.journal_mode;
      PRAGMA aux3.journal_mode;
    }
  } [list delete [temp_journal_mode delete] memory memory memory]
  do_test jrnlmode-1.16 {
    execsql {
      PRAGMA journal_mode = TRUNCATE;
    }
    execsql {
      PRAGMA main.journal_mode;
      PRAGMA temp.journal_mode;
      PRAGMA aux1.journal_mode;
      PRAGMA aux2.journal_mode;
      PRAGMA aux3.journal_mode;
    }
  } [list truncate [temp_journal_mode truncate] memory memory memory]

  do_test jrnlmode-1.99 {
    execsql {
      DETACH aux1;
      DETACH aux2;
      DETACH aux3;
    }
  } {}
}

ifcapable attach {
  file delete -force test2.db
  do_test jrnlmode-2.1 {
    execsql {
      ATTACH 'test2.db' AS aux;
      PRAGMA main.journal_mode = persist;
      PRAGMA aux.journal_mode = persist;
      CREATE TABLE abc(a, b, c);
      CREATE TABLE aux.def(d, e, f);
    }
    execsql {
      BEGIN;
      INSERT INTO abc VALUES(1, 2, 3);
      INSERT INTO def VALUES(4, 5, 6);
      COMMIT;
    }
    list [file exists test.db-journal] [file exists test2.db-journal]
  } {1 1}

  do_test jrnlmode-2.2 {
    file size test.db-journal
  } {0}

  do_test jrnlmode-2.3 {
    execsql {
      SELECT * FROM abc;
    }
  } {1 2 3}

  do_test jrnlmode-2.4 {
    file size test.db-journal
  } {0}

  do_test jrnlmode-2.5 {
    execsql {
      SELECT * FROM def;
    }
  } {4 5 6}

#----------------------------------------------------------------------
# Test caes jrnlmode-3.X verify that ticket #3127 has been fixed.
#
  db close
  file delete -force test2.db
  file delete -force test.db
  sqlite3 db test.db

  do_test jrnlmode-3.1 {
    execsql { 
      CREATE TABLE x(n INTEGER); 
      ATTACH 'test2.db' AS a; 
      create table a.x ( n integer ); 
      insert into a.x values(1); 
      insert into a.x values (2); 
      insert into a.x values (3); 
      insert into a.x values (4); 
    }
  } {}
  
  do_test jrnlmode-3.2 {
    execsql { PRAGMA journal_mode=off; }
    execsql { 
      BEGIN IMMEDIATE;
      INSERT OR IGNORE INTO main.x SELECT * FROM a.x;
      COMMIT;
    }
  } {}
}

ifcapable autovacuum&&pragma {
  db close
  file delete -force test.db
  sqlite3 db test.db
  do_test jrnlmode-4.1 {
    execsql {
      PRAGMA cache_size = 1;
      PRAGMA auto_vacuum = 1;
      CREATE TABLE abc(a, b, c);
    }
    execsql { PRAGMA page_count }
  } {3}

  do_test jrnlmode-4.2 {
    execsql { PRAGMA journal_mode = off }
  } {off}

  do_test jrnlmode-4.3 {
    execsql { INSERT INTO abc VALUES(1, 2, randomblob(2000)) }
  } {}

  # This will attempt to truncate the database file. Check that this
  # is not a problem when journal_mode=off.
  do_test jrnlmode-4.4 {
    execsql { DELETE FROM abc }
  } {}

  integrity_check jrnlmode-4.5
}

#------------------------------------------------------------------------
# The following test caes, jrnlmode-5.*, test the journal_size_limit
# pragma.
ifcapable pragma {
  db close
  file delete -force test.db test2.db test3.db
  sqlite3 db test.db

  do_test jrnlmode-5.1 {
    execsql {pragma page_size=1024}
    execsql {pragma journal_mode=persist}
  } {persist}

  do_test jrnlmode-5.2 {
    execsql { PRAGMA journal_size_limit }
  } {-1}
  do_test jrnlmode-5.3 {
    execsql { 
      ATTACH 'test2.db' AS aux;
      PRAGMA aux.journal_size_limit;
    }
  } {-1}
  do_test jrnlmode-5.4.1 {
    execsql { PRAGMA aux.journal_size_limit = 999999999999 }
  } {999999999999}
  do_test jrnlmode-5.4.2 {
    execsql { PRAGMA aux.journal_size_limit = 10240 }
  } {10240}
  do_test jrnlmode-5.5 {
    execsql { PRAGMA main.journal_size_limit = 20480 }
  } {20480}
  do_test jrnlmode-5.6 {
    execsql { PRAGMA journal_size_limit }
  } {20480}
  do_test jrnlmode-5.7 {
    execsql { PRAGMA aux.journal_size_limit }
  } {10240}

  do_test jrnlmode-5.8 {
    execsql { ATTACH 'test3.db' AS aux2 }
  } {}

  do_test jrnlmode-5.9 {
    execsql {
      CREATE TABLE main.t1(a, b, c);
      CREATE TABLE aux.t2(a, b, c);
      CREATE TABLE aux2.t3(a, b, c);
    }
  } {}
  do_test jrnlmode-5.10 {
    list \
      [file exists test.db-journal]  \
      [file exists test2.db-journal] \
      [file exists test3.db-journal]
  } {1 1 1}
  do_test jrnlmode-5.11 {
    execsql {
      BEGIN;
      INSERT INTO t3 VALUES(randomblob(1000),randomblob(1000),randomblob(1000));
      INSERT INTO t3 
          SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3;
      INSERT INTO t3 
          SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3;
      INSERT INTO t3 
          SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3;
      INSERT INTO t3 
          SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3;
      INSERT INTO t3 
          SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3;
      INSERT INTO t2 SELECT * FROM t3;
      INSERT INTO t1 SELECT * FROM t2;
      COMMIT;
    }
    list \
      [file exists test.db-journal]  \
      [file exists test2.db-journal] \
      [file exists test3.db-journal] \
      [file size test.db-journal]    \
      [file size test2.db-journal]   \
      [file size test3.db-journal]
  } {1 1 1 0 0 0}

  do_test jrnlmode-5.12 {
    execsql {
      BEGIN;
      UPDATE t1 SET a = randomblob(1000);
    }
    expr {[file size test.db-journal]>30000}
  } {1}
  do_test jrnlmode-5.13 {
    execsql COMMIT
    file size test.db-journal
  } {20480}

  do_test jrnlmode-5.14 {
    execsql {
      BEGIN;
      UPDATE t2 SET a = randomblob(1000);
    }
    expr {[file size test2.db-journal]>30000}
  } {1}
  do_test jrnlmode-5.15 {
    execsql COMMIT
    file size test2.db-journal
  } {10240}

  do_test jrnlmode-5.16 {
    execsql {
      BEGIN;
      UPDATE t3 SET a = randomblob(1000);
    }
    set journalsize [file size test3.db-journal]
    expr {$journalsize>30000}
  } {1}
  do_test jrnlmode-5.17 {
    execsql COMMIT
    set sz [file size test3.db-journal]
    expr {$sz>=$journalsize}
  } {1}

  do_test jrnlmode-5.18 {
    execsql {
      PRAGMA journal_size_limit = -4;
      BEGIN;
      UPDATE t1 SET a = randomblob(1000);
    }
    set journalsize [file size test.db-journal]
    expr {$journalsize>30000}
  } {1}
  do_test jrnlmode-5.19 {
    execsql COMMIT
    set sz [file size test.db-journal]
    expr {$sz>=$journalsize}
  } {1}

  # Test a size-limit of 0.
  #
  do_test jrnlmode-5.20 {
    execsql {
      PRAGMA journal_size_limit = 0;
      BEGIN;
      UPDATE t1 SET a = randomblob(1000);
    }
  } {0}
  do_test jrnlmode-5.21 {
    expr {[file size test.db-journal] > 1024}
  } {1}
  do_test jrnlmode-5.22 {
    execsql COMMIT
    list [file exists test.db-journal] [file size test.db-journal]
  } {1 0}
}

ifcapable pragma {
  # These tests are not run as part of the "journaltest" permutation,
  # as the test_journal.c layer is incompatible with in-memory journaling.
  if {[catch {set ::permutations_test_prefix} z] || $z ne "journaltest"} {

    do_test jrnlmode-6.1 {
      execsql {
        PRAGMA journal_mode = truncate;
        CREATE TABLE t4(a, b);
        BEGIN;
          INSERT INTO t4 VALUES(1, 2);
          PRAGMA journal_mode = memory;
      }
    } {truncate truncate}
    do_test jrnlmode-6.2 {
      file exists test.db-journal
    } {1}
    do_test jrnlmode-6.3 {
      execsql {
        COMMIT;
        SELECT * FROM t4;
      }
    } {1 2}
    do_test jrnlmode-6.4 {
      file exists test.db-journal
    } {1}
    do_test jrnlmode-6.5 {
      execsql {
        PRAGMA journal_mode = MEMORY;
        BEGIN;
          INSERT INTO t4 VALUES(3, 4);
      }
      file exists test.db-journal
    } {1}
    do_test jrnlmode-6.7 {
      execsql {
        COMMIT;
        SELECT * FROM t4;
      }
    } {1 2 3 4}
    do_test jrnlmode-6.8 {
      file exists test.db-journal
    } {1}
    do_test jrnlmode-6.9 {
      execsql {
        PRAGMA journal_mode = DELETE;
        BEGIN IMMEDIATE; COMMIT;
      }
      file exists test.db-journal
    } {0}
  }
}

finish_test

Added test/jrnlmode2.test.







































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 2009 March 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: jrnlmode2.test,v 1.6 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas} {
  finish_test
  return
}

#-------------------------------------------------------------------------
# Test overview:
#
#   jrnlmode2-1.*: Demonstrate bug #3745
#   jrnlmode2-2.*: Demonstrate bug #3751
#

do_test jrnlmode2-1.1 {
  execsql {
    PRAGMA journal_mode = persist;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 2);
  }
} {persist}

do_test jrnlmode2-1.2 {
  file exists test.db-journal
} {1}

do_test jrnlmode2-1.3 {
  sqlite3 db2 test.db
  execsql { SELECT * FROM t1 } db2
} {1 2}

do_test jrnlmode2-1.4 {
  execsql {
    INSERT INTO t1 VALUES(3, 4);
    BEGIN;
    SELECT * FROM t1;
  }
  execsql { PRAGMA lock_status }
} {main shared temp closed}

do_test jrnlmode2-1.5 {
  file exists test.db-journal
} {1}

do_test jrnlmode2-1.6 {
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2 3 4}}

do_test jrnlmode2-1.7 {
  execsql { COMMIT }
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2 3 4}}



do_test jrnlmode2-2.1 {
  db2 close
  execsql { PRAGMA journal_mode = truncate }
  execsql { INSERT INTO t1 VALUES(5, 6) }
} {}

do_test jrnlmode2-2.2 {
  file exists test.db-journal
} {1}

do_test jrnlmode2-2.3 {
  file size test.db-journal
} {0}

do_test jrnlmode2-2.4 {
  sqlite3 db2 test.db -readonly 1
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2 3 4 5 6}}

do_test jrnlmode2-2.5 {
  file delete test.db-journal
} {}

do_test jrnlmode2-2.6 {
  sqlite3 db2 test.db -readonly 1
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2 3 4 5 6}}

catch { db2 close }
finish_test

Added test/jrnlmode3.test.













































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# 2009 April 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test cases inspired by ticket #3811.  Tests to make sure that
# the journal_mode can only be changed at appropriate times and that
# all reported changes are effective.
#
# $Id: jrnlmode3.test,v 1.5 2009/04/20 17:43:03 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas} {
  finish_test
  return
}

#
# Verify that journal_mode=OFF works as long as it occurs before the first
# transaction, even if locking_mode=EXCLUSIVE is enabled.  The behavior if
# journal_mode is changed after the first transaction is undefined and hence
# untested.
#
do_test jrnlmode3-1.1 {
  db eval {
    PRAGMA journal_mode=OFF;
    PRAGMA locking_mode=EXCLUSIVE;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT * FROM t1;
  }
} {off exclusive 1}
do_test jrnlmode3-1.2 {
  db eval {
    BEGIN;
    INSERT INTO t1 VALUES(2);
    ROLLBACK;
    SELECT * FROM t1;
  }
} {1 2}

db close
file delete -force test.db test.db-journal
sqlite3 db test.db

do_test jrnlmode3-2.1 {
  db eval {
    PRAGMA locking_mode=EXCLUSIVE;
    PRAGMA journal_mode=OFF;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT * FROM t1;
  }
} {exclusive off 1}
do_test jrnlmode3-2.2 {
  db eval {
    BEGIN;
    INSERT INTO t1 VALUES(2);
    ROLLBACK;
    SELECT * FROM t1;
  }
} {1 2}

# Test cases to verify that we can move from any journal_mode
# to any other, as long as we are not in a transaction.  Verify
# that we cannot change journal_mode while a transaction is active.
#
set all_journal_modes {delete persist truncate memory off}
set cnt 0
foreach fromjmode $all_journal_modes {
  foreach tojmode $all_journal_modes {

    # Skip the no-change cases
    if {$fromjmode==$tojmode} continue
    incr cnt

    # Start with a fresh database connection an empty database file.
    #
    db close
    file delete -force test.db test.db-journal
    sqlite3 db test.db

    # Initialize the journal mode.
    #
    do_test jrnlmode3-3.$cnt.1-($fromjmode-to-$tojmode) {
      db eval "PRAGMA journal_mode = $fromjmode;"
    } $fromjmode

    # Verify that the initial journal mode takes.
    #
    do_test jrnlmode3-3.$cnt.2 {
      db eval {PRAGMA main.journal_mode}
    } $fromjmode

    # Start a transaction and try to change the journal mode within
    # the transaction.  This should fail.
    #
    do_test jrnlmode3-3.$cnt.3 {
      db eval {
        CREATE TABLE t1(x);
        BEGIN;
        INSERT INTO t1 VALUES($cnt);
      }
      db eval "PRAGMA journal_mode=$tojmode"
    } $fromjmode

    # Rollback the transaction.  Verify that the rollback occurred
    # if journal_mode!=OFF.
    #
    do_test jrnlmode3-3.$cnt.4 {
      db eval {
        ROLLBACK;
        SELECT * FROM t1;
      }
    } [expr {$fromjmode=="off"?$cnt:""}]

    # Now change the journal mode again.  This time the new mode
    # should take.
    #
    do_test jrnlmode3-3.$cnt.5 {
      db eval "PRAGMA journal_mode=$tojmode"
    } $tojmode

    # Do a the transaction.  Verify that the rollback occurred
    # if journal_mode!=OFF.
    #
    do_test jrnlmode3-3.$cnt.6 {
      db eval {
        DROP TABLE IF EXISTS t1;
        CREATE TABLE t1(x);
        BEGIN;
        INSERT INTO t1 VALUES(1);
      }
      db eval ROLLBACK
      db eval {
        SELECT * FROM t1;
      }
    } [expr {$tojmode=="off"?"1":""}]
  }
}

finish_test

Added test/keyword1.test.













































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# 2009 January 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Verify that certain keywords can be used as identifiers.
#
# $Id: keyword1.test,v 1.1 2009/01/29 19:27:47 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

db eval {
  CREATE TABLE t1(a, b);
  INSERT INTO t1 VALUES(1, 'one');
  INSERT INTO t1 VALUES(2, 'two');
  INSERT INTO t1 VALUES(3, 'three');
}

set kwlist {
  abort
  after
  analyze
  asc
  attach
  before
  begin
  by
  cascade
  cast
  column
  conflict
  current_date
  current_time
  current_timestamp
  database
  deferred
  desc
  detach
  end
  each
  exclusive
  explain
  fail
  for
  glob
  if
  ignore
  immediate
  initially
  instead
  key
  like
  match
  of
  offset
  plan
  pragma
  query
  raise
  regexp
  reindex
  release
  rename
  replace
  restrict
  rollback
  row
  savepoint
  temp
  temporary
  trigger
  vacuum
  view
  virtual
};
set exprkw {
  cast
  current_date
  current_time
  current_timestamp
  raise
}
foreach kw $kwlist {  
  do_test keyword1-$kw.1 {
    if {$kw=="if"} {
      db eval "CREATE TABLE \"$kw\"($kw $kw)"
    } else {
      db eval "CREATE TABLE ${kw}($kw $kw)"
    }
    db eval "INSERT INTO $kw VALUES(99)"
    db eval "INSERT INTO $kw SELECT a FROM t1"
    if {[lsearch $exprkw $kw]<0} {
      db eval "SELECT * FROM $kw ORDER BY $kw ASC"
    } else {
      db eval "SELECT * FROM $kw ORDER BY \"$kw\" ASC"
    }
  } {1 2 3 99}
  do_test keyword1-$kw.2 {
    if {$kw=="if"} {
      db eval "DROP TABLE \"$kw\""
      db eval "CREATE INDEX \"$kw\" ON t1(a)"
    } else {
      db eval "DROP TABLE $kw"
      db eval "CREATE INDEX $kw ON t1(a)"
    }
    db eval "SELECT b FROM t1 INDEXED BY $kw WHERE a=2"
  } {two}
}

finish_test

Added test/lastinsert.test.





























































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to make sure that value returned by last_insert_rowid() (LIRID)
# is updated properly, especially inside triggers
#
# Note 1: insert into table is now the only statement which changes LIRID
# Note 2: upon entry into before or instead of triggers,
#           LIRID is unchanged (rather than -1)
# Note 3: LIRID is changed within the context of a trigger,
#           but is restored once the trigger exits
# Note 4: LIRID is not changed by an insert into a view (since everything
#           is done within instead of trigger context)
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# ----------------------------------------------------------------------------
# 1.x - basic tests (no triggers)

# LIRID changed properly after an insert into a table
do_test lastinsert-1.1 {
    catchsql {
        create table t1 (k integer primary key);
        insert into t1 values (1);
        insert into t1 values (NULL);
        insert into t1 values (NULL);
        select last_insert_rowid();
    }
} {0 3}

# LIRID unchanged after an update on a table
do_test lastinsert-1.2 {
    catchsql {
        update t1 set k=4 where k=2;
        select last_insert_rowid();
    }
} {0 3}

# LIRID unchanged after a delete from a table
do_test lastinsert-1.3 {
    catchsql {
        delete from t1 where k=4;
        select last_insert_rowid();
    }
} {0 3}

# LIRID unchanged after create table/view statements
do_test lastinsert-1.4.1 {
    catchsql {
        create table t2 (k integer primary key, val1, val2, val3);
        select last_insert_rowid();
    }
} {0 3}
ifcapable view {
do_test lastinsert-1.4.2 {
    catchsql {
        create view v as select * from t1;
        select last_insert_rowid();
    }
} {0 3}
} ;# ifcapable view

# All remaining tests involve triggers.  Skip them if triggers are not
# supported in this build.
#
ifcapable {!trigger} {
  finish_test
  return
}

# ----------------------------------------------------------------------------
# 2.x - tests with after insert trigger

# LIRID changed properly after an insert into table containing an after trigger
do_test lastinsert-2.1 {
    catchsql {
        delete from t2;
        create trigger r1 after insert on t1 for each row begin
            insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL);
            update t2 set k=k+10, val2=100+last_insert_rowid();
            update t2 set val3=1000+last_insert_rowid();
        end;
        insert into t1 values (13);
        select last_insert_rowid();
    }
} {0 13}

# LIRID equals NEW.k upon entry into after insert trigger
do_test lastinsert-2.2 {
    catchsql {
        select val1 from t2;
    }
} {0 13}

# LIRID changed properly by insert within context of after insert trigger
do_test lastinsert-2.3 {
    catchsql {
        select val2 from t2;
    }
} {0 126}

# LIRID unchanged by update within context of after insert trigger
do_test lastinsert-2.4 {
    catchsql {
        select val3 from t2;
    }
} {0 1026}

# ----------------------------------------------------------------------------
# 3.x - tests with after update trigger

# LIRID not changed after an update onto a table containing an after trigger
do_test lastinsert-3.1 {
    catchsql {
        delete from t2;
        drop trigger r1;
        create trigger r1 after update on t1 for each row begin
            insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL);
            update t2 set k=k+10, val2=100+last_insert_rowid();
            update t2 set val3=1000+last_insert_rowid();
        end;
        update t1 set k=14 where k=3;
        select last_insert_rowid();
    }
} {0 13}

# LIRID unchanged upon entry into after update trigger
do_test lastinsert-3.2 {
    catchsql {
        select val1 from t2;
    }
} {0 13}

# LIRID changed properly by insert within context of after update trigger
do_test lastinsert-3.3 {
    catchsql {
        select val2 from t2;
    }
} {0 128}

# LIRID unchanged by update within context of after update trigger
do_test lastinsert-3.4 {
    catchsql {
        select val3 from t2;
    }
} {0 1028}

# ----------------------------------------------------------------------------
# 4.x - tests with instead of insert trigger
# These may not be run if either views or triggers were disabled at 
# compile-time

ifcapable {view && trigger} {
# LIRID not changed after an insert into view containing an instead of trigger
do_test lastinsert-4.1 {
    catchsql {
        delete from t2;
        drop trigger r1;
        create trigger r1 instead of insert on v for each row begin
            insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL);
            update t2 set k=k+10, val2=100+last_insert_rowid();
            update t2 set val3=1000+last_insert_rowid();
        end;
        insert into v values (15);
        select last_insert_rowid();
    }
} {0 13}

# LIRID unchanged upon entry into instead of trigger
do_test lastinsert-4.2 {
    catchsql {
        select val1 from t2;
    }
} {0 13}

# LIRID changed properly by insert within context of instead of trigger
do_test lastinsert-4.3 {
    catchsql {
        select val2 from t2;
    }
} {0 130}

# LIRID unchanged by update within context of instead of trigger
do_test lastinsert-4.4 {
    catchsql {
        select val3 from t2;
    }
} {0 1030}
} ;# ifcapable (view && trigger)

# ----------------------------------------------------------------------------
# 5.x - tests with before delete trigger

# LIRID not changed after a delete on a table containing a before trigger
do_test lastinsert-5.1 {
    catchsql {
      drop trigger r1;  -- This was not created if views are disabled.
    }
    catchsql {
        delete from t2;
        create trigger r1 before delete on t1 for each row begin
            insert into t2 values (77, last_insert_rowid(), NULL, NULL);
            update t2 set k=k+10, val2=100+last_insert_rowid();
            update t2 set val3=1000+last_insert_rowid();
        end;
        delete from t1 where k=1;
        select last_insert_rowid();
    }
} {0 13}

# LIRID unchanged upon entry into delete trigger
do_test lastinsert-5.2 {
    catchsql {
        select val1 from t2;
    }
} {0 13}

# LIRID changed properly by insert within context of delete trigger
do_test lastinsert-5.3 {
    catchsql {
        select val2 from t2;
    }
} {0 177}

# LIRID unchanged by update within context of delete trigger
do_test lastinsert-5.4 {
    catchsql {
        select val3 from t2;
    }
} {0 1077}

# ----------------------------------------------------------------------------
# 6.x - tests with instead of update trigger
# These tests may not run if either views or triggers are disabled.

ifcapable {view && trigger} {
# LIRID not changed after an update on a view containing an instead of trigger
do_test lastinsert-6.1 {
    catchsql {
        delete from t2;
        drop trigger r1;
        create trigger r1 instead of update on v for each row begin
            insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL);
            update t2 set k=k+10, val2=100+last_insert_rowid();
            update t2 set val3=1000+last_insert_rowid();
        end;
        update v set k=16 where k=14;
        select last_insert_rowid();
    }
} {0 13}

# LIRID unchanged upon entry into instead of trigger
do_test lastinsert-6.2 {
    catchsql {
        select val1 from t2;
    }
} {0 13}

# LIRID changed properly by insert within context of instead of trigger
do_test lastinsert-6.3 {
    catchsql {
        select val2 from t2;
    }
} {0 132}

# LIRID unchanged by update within context of instead of trigger
do_test lastinsert-6.4 {
    catchsql {
        select val3 from t2;
    }
} {0 1032}
} ;# ifcapable (view && trigger)

# ----------------------------------------------------------------------------
# 7.x - complex tests with temporary tables and nested instead of triggers
# These do not run if views or triggers are disabled.

ifcapable {trigger && view && tempdb} {
do_test lastinsert-7.1 {
    catchsql {
        drop table t1; drop table t2; drop trigger r1;
        create temp table t1 (k integer primary key);
        create temp table t2 (k integer primary key);
        create temp view v1 as select * from t1;
        create temp view v2 as select * from t2;
        create temp table rid (k integer primary key, rin, rout);
        insert into rid values (1, NULL, NULL);
        insert into rid values (2, NULL, NULL);
        create temp trigger r1 instead of insert on v1 for each row begin
            update rid set rin=last_insert_rowid() where k=1;
            insert into t1 values (100+NEW.k);
            insert into v2 values (100+last_insert_rowid());
            update rid set rout=last_insert_rowid() where k=1;
        end;
        create temp trigger r2 instead of insert on v2 for each row begin
            update rid set rin=last_insert_rowid() where k=2;
            insert into t2 values (1000+NEW.k);
            update rid set rout=last_insert_rowid() where k=2;
        end;
        insert into t1 values (77);
        select last_insert_rowid();
    }
} {0 77}

do_test lastinsert-7.2 {
    catchsql {
        insert into v1 values (5);
        select last_insert_rowid();
    }
} {0 77}

do_test lastinsert-7.3 {
    catchsql {
        select rin from rid where k=1;
    }
} {0 77}

do_test lastinsert-7.4 {
    catchsql {
        select rout from rid where k=1;
    }
} {0 105}

do_test lastinsert-7.5 {
    catchsql {
        select rin from rid where k=2;
    }
} {0 105}

do_test lastinsert-7.6 {
    catchsql {
        select rout from rid where k=2;
    }
} {0 1205}

do_test lastinsert-8.1 {
  db close
  sqlite3 db test.db
  execsql {
    CREATE TABLE t2(x INTEGER PRIMARY KEY, y);
    CREATE TABLE t3(a, b);
    CREATE TRIGGER after_t2 AFTER INSERT ON t2 BEGIN
      INSERT INTO t3 VALUES(new.x, new.y);
    END;
    INSERT INTO t2 VALUES(5000000000, 1);
    SELECT last_insert_rowid();
  }
} 5000000000

do_test lastinsert-9.1 {
  db eval {INSERT INTO t2 VALUES(123456789012345,0)}
  db last_insert_rowid
} {123456789012345}


} ;# ifcapable (view && trigger)

finish_test

Added test/laststmtchanges.test.























































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to make sure that values returned by changes() and total_changes()
# are updated properly, especially inside triggers
#
# Note 1: changes() remains constant within a statement and only updates
#         once the statement is finished (triggers count as part of
#         statement).
# Note 2: changes() is changed within the context of a trigger much like 
#         last_insert_rowid() (see lastinsert.test), but is restored once
#         the trigger exits.
# Note 3: changes() is not changed by a change to a view (since everything
#         is done within instead of trigger context).
#
# $Id: laststmtchanges.test,v 1.7 2008/10/27 13:59:34 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# ----------------------------------------------------------------------------
# 1.x - basic tests (no triggers)

# changes() set properly after insert
do_test laststmtchanges-1.1 {
    catchsql {
        create table t0 (x);
        insert into t0 values (1);
        insert into t0 values (1);
        insert into t0 values (2);
        insert into t0 values (2);
        insert into t0 values (1);
        insert into t0 values (1);
        insert into t0 values (1);
        insert into t0 values (2);
        select changes(), total_changes();
    }
} {0 {1 8}}

# changes() set properly after update
do_test laststmtchanges-1.2 {
    catchsql {
        update t0 set x=3 where x=1;
        select changes(), total_changes();
    }
} {0 {5 13}}

# There was some goofy change-counting logic in sqlite3_exec() that
# appears to have been left over from SQLite version 2.  This test
# makes sure it has been removed.
#
do_test laststmtchanges-1.2.1 {
    db cache flush
    sqlite3_exec_printf db {update t0 set x=4 where x=3; select 1;} {}
    execsql {select changes()}
} {5}

# changes() unchanged within an update statement
do_test laststmtchanges-1.3 {
    execsql {update t0 set x=3 where x=4}
    catchsql {
        update t0 set x=x+changes() where x=3;
        select count() from t0 where x=8;
    }
} {0 5}

# changes() set properly after update on table where no rows changed
do_test laststmtchanges-1.4 {
    catchsql {
        update t0 set x=77 where x=88;
        select changes();
    }
} {0 0}

# changes() set properly after delete from table
do_test laststmtchanges-1.5 {
    catchsql {
        delete from t0 where x=2;
        select changes();
    }
} {0 3}

# All remaining tests involve triggers.  Skip them if triggers are not
# supported in this build.
#
ifcapable {!trigger} {
  finish_test
  return
}


# ----------------------------------------------------------------------------
# 2.x - tests with after insert trigger

# changes() changed properly after insert into table containing after trigger
do_test laststmtchanges-2.1 {
    set ::tc [db total_changes]
    catchsql {
        create table t1 (k integer primary key);
        create table t2 (k integer primary key, v1, v2);
        create trigger r1 after insert on t1 for each row begin
            insert into t2 values (NULL, changes(), NULL);
            update t0 set x=x;
            update t2 set v2=changes();
        end;
        insert into t1 values (77);
        select changes();
    }
} {0 1}

# changes() unchanged upon entry into after insert trigger
do_test laststmtchanges-2.2 {
    catchsql {
        select v1 from t2;
    }
} {0 3}

# changes() changed properly by update within context of after insert trigger
do_test laststmtchanges-2.3 {
    catchsql {
        select v2 from t2;
    }
} {0 5}

# Total changes caused by firing the trigger above:
#
#   1 from "insert into t1 values(77)" + 
#   1 from "insert into t2 values (NULL, changes(), NULL);" +
#   5 from "update t0 set x=x;" +
#   1 from "update t2 set v2=changes();"
#
do_test laststmtchanges-2.4 {
  expr [db total_changes] - $::tc
} {8}

# ----------------------------------------------------------------------------
# 3.x - tests with after update trigger

# changes() changed properly after update into table containing after trigger
do_test laststmtchanges-3.1 {
    catchsql {
        drop trigger r1;
        delete from t2; delete from t2;
        create trigger r1 after update on t1 for each row begin
            insert into t2 values (NULL, changes(), NULL);
            delete from t0 where oid=1 or oid=2;
            update t2 set v2=changes();
        end;
        update t1 set k=k;
        select changes();
    }
} {0 1}

# changes() unchanged upon entry into after update trigger
do_test laststmtchanges-3.2 {
    catchsql {
        select v1 from t2;
    }
} {0 0}

# changes() changed properly by delete within context of after update trigger
do_test laststmtchanges-3.3 {
    catchsql {
        select v2 from t2;
    }
} {0 2}

# ----------------------------------------------------------------------------
# 4.x - tests with before delete trigger

# changes() changed properly on delete from table containing before trigger
do_test laststmtchanges-4.1 {
    catchsql {
        drop trigger r1;
        delete from t2; delete from t2;
        create trigger r1 before delete on t1 for each row begin
            insert into t2 values (NULL, changes(), NULL);
            insert into t0 values (5);
            update t2 set v2=changes();
        end;
        delete from t1;
        select changes();
    }
} {0 1}

# changes() unchanged upon entry into before delete trigger
do_test laststmtchanges-4.2 {
    catchsql {
        select v1 from t2;
    }
} {0 0}

# changes() changed properly by insert within context of before delete trigger
do_test laststmtchanges-4.3 {
    catchsql {
        select v2 from t2;
    }
} {0 1}

# ----------------------------------------------------------------------------
# 5.x - complex tests with temporary tables and nested instead of triggers
# These tests cannot run if the library does not have view support enabled.

ifcapable view&&tempdb {

do_test laststmtchanges-5.1 {
    catchsql {
        drop table t0; drop table t1; drop table t2;
        create temp table t0(x);
        create temp table t1 (k integer primary key);
        create temp table t2 (k integer primary key);
        create temp view v1 as select * from t1;
        create temp view v2 as select * from t2;
        create temp table n1 (k integer primary key, n);
        create temp table n2 (k integer primary key, n);
        insert into t0 values (1);
        insert into t0 values (2);
        insert into t0 values (1);
        insert into t0 values (1);
        insert into t0 values (1);
        insert into t0 values (2);
        insert into t0 values (2);
        insert into t0 values (1);
        create temp trigger r1 instead of insert on v1 for each row begin
            insert into n1 values (NULL, changes());
            update t0 set x=x*10 where x=1;
            insert into n1 values (NULL, changes());
            insert into t1 values (NEW.k);
            insert into n1 values (NULL, changes());
            update t0 set x=x*10 where x=0;
            insert into v2 values (100+NEW.k);
            insert into n1 values (NULL, changes());
        end;
        create temp trigger r2 instead of insert on v2 for each row begin
            insert into n2 values (NULL, changes());
            insert into t2 values (1000+NEW.k);
            insert into n2 values (NULL, changes());
            update t0 set x=x*100 where x=0;
            insert into n2 values (NULL, changes());
            delete from t0 where x=2;
            insert into n2 values (NULL, changes());
        end;
        insert into t1 values (77);
        select changes();
    }
} {0 1}

do_test laststmtchanges-5.2 {
    catchsql {
        delete from t1 where k=88;
        select changes();
    }
} {0 0}

do_test laststmtchanges-5.3 {
    catchsql {
        insert into v1 values (5);
        select changes();
    }
} {0 0}

do_test laststmtchanges-5.4 {
    catchsql {
        select n from n1;
    }
} {0 {0 5 1 0}}

do_test laststmtchanges-5.5 {
    catchsql {
        select n from n2;
    }
} {0 {0 1 0 3}}

} ;# ifcapable view


# ----------------------------------------------------------------------------
# 6.x - Test "DELETE FROM <table>" in the absence of triggers
#
do_test laststmtchanges-6.1 {
  execsql {
    CREATE TABLE t3(a, b, c);
    INSERT INTO t3 VALUES(1, 2, 3);
    INSERT INTO t3 VALUES(4, 5, 6);
  }
} {}
do_test laststmtchanges-6.2 {
  execsql {
    BEGIN;
    DELETE FROM t3;
    SELECT changes();
  }
} {2}
do_test laststmtchanges-6.3 {
  execsql {
    ROLLBACK;
    BEGIN;
    DELETE FROM t3 WHERE a IS NOT NULL;
    SELECT changes();
  }
} {2}
do_test laststmtchanges-6.4 {
  execsql {
    ROLLBACK;
    CREATE INDEX t3_i1 ON t3(a);
    BEGIN;
    DELETE FROM t3;
    SELECT changes();
  }
} {2}
do_test laststmtchanges-6.5 {
  execsql { ROLLBACK }
  set nTotalChange [execsql {SELECT total_changes()}]
  expr 0
} {0}
do_test laststmtchanges-6.6 {
  execsql {
    SELECT total_changes();
    DELETE FROM t3;
    SELECT total_changes();
  }
} [list $nTotalChange [expr $nTotalChange+2]]

finish_test

Added test/like.test.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# 2005 August 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the LIKE and GLOB operators and
# in particular the optimizations that occur to help those operators
# run faster.
#
# $Id: like.test,v 1.13 2009/06/07 23:45:11 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create some sample data to work with.
#
do_test like-1.0 {
  execsql {
    CREATE TABLE t1(x TEXT);
  }
  foreach str {
    a
    ab
    abc
    abcd

    acd
    abd
    bc
    bcd

    xyz
    ABC
    CDE
    {ABC abc xyz}
  } {
    db eval {INSERT INTO t1 VALUES(:str)}
  }
  execsql {
    SELECT count(*) FROM t1;
  }
} {12}

# Test that both case sensitive and insensitive version of LIKE work.
#
do_test like-1.1 {
  execsql {
    SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1;
  }
} {ABC abc}
do_test like-1.2 {
  execsql {
    SELECT x FROM t1 WHERE x GLOB 'abc' ORDER BY 1;
  }
} {abc}
do_test like-1.3 {
  execsql {
    SELECT x FROM t1 WHERE x LIKE 'ABC' ORDER BY 1;
  }
} {ABC abc}
do_test like-1.4 {
  execsql {
    SELECT x FROM t1 WHERE x LIKE 'aBc' ORDER BY 1;
  }
} {ABC abc}
do_test like-1.5.1 {
  execsql {
    PRAGMA case_sensitive_like=on;
    SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1;
  }
} {abc}
do_test like-1.5.2 {
  execsql {
    PRAGMA case_sensitive_like; -- no argument; does not change setting
    SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1;
  }
} {abc}
do_test like-1.6 {
  execsql {
    SELECT x FROM t1 WHERE x GLOB 'abc' ORDER BY 1;
  }
} {abc}
do_test like-1.7 {
  execsql {
    SELECT x FROM t1 WHERE x LIKE 'ABC' ORDER BY 1;
  }
} {ABC}
do_test like-1.8 {
  execsql {
    SELECT x FROM t1 WHERE x LIKE 'aBc' ORDER BY 1;
  }
} {}
do_test like-1.9 {
  execsql {
    PRAGMA case_sensitive_like=off;
    SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1;
  }
} {ABC abc}
do_test like-1.10 {
  execsql {
    PRAGMA case_sensitive_like;  -- No argument, does not change setting.
    SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1;
  }
} {ABC abc}

# Tests of the REGEXP operator
#
do_test like-2.1 {
  proc test_regexp {a b} {
    return [regexp $a $b]
  }
  db function regexp test_regexp
  execsql {
    SELECT x FROM t1 WHERE x REGEXP 'abc' ORDER BY 1;
  }
} {{ABC abc xyz} abc abcd}
do_test like-2.2 {
  execsql {
    SELECT x FROM t1 WHERE x REGEXP '^abc' ORDER BY 1;
  }
} {abc abcd}

# Tests of the MATCH operator
#
do_test like-2.3 {
  proc test_match {a b} {
    return [string match $a $b]
  }
  db function match -argcount 2 test_match
  execsql {
    SELECT x FROM t1 WHERE x MATCH '*abc*' ORDER BY 1;
  }
} {{ABC abc xyz} abc abcd}
do_test like-2.4 {
  execsql {
    SELECT x FROM t1 WHERE x MATCH 'abc*' ORDER BY 1;
  }
} {abc abcd}

# For the remaining tests, we need to have the like optimizations
# enabled.
#
ifcapable !like_opt {
  finish_test
  return
} 

# This procedure executes the SQL.  Then it appends to the result the
# "sort" or "nosort" keyword (as in the cksort procedure above) then
# it appends the ::sqlite_query_plan variable.
#
proc queryplan {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return [concat $data $::sqlite_query_plan]
}

# Perform tests on the like optimization.
#
# With no index on t1.x and with case sensitivity turned off, no optimization
# is performed.
#
do_test like-3.1 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1;
  }
} {ABC {ABC abc xyz} abc abcd sort t1 {}}
do_test like-3.2 {
  set sqlite_like_count
} {12}

# With an index on t1.x and case sensitivity on, optimize completely.
#
do_test like-3.3 {
  set sqlite_like_count 0
  execsql {
    PRAGMA case_sensitive_like=on;
    CREATE INDEX i1 ON t1(x);
  }
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1;
  }
} {abc abcd nosort {} i1}
do_test like-3.4 {
  set sqlite_like_count
} 0

# Partial optimization when the pattern does not end in '%'
#
do_test like-3.5 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'a_c' ORDER BY 1;
  }
} {abc nosort {} i1}
do_test like-3.6 {
  set sqlite_like_count
} 6
do_test like-3.7 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'ab%d' ORDER BY 1;
  }
} {abcd abd nosort {} i1}
do_test like-3.8 {
  set sqlite_like_count
} 4
do_test like-3.9 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'a_c%' ORDER BY 1;
  }
} {abc abcd nosort {} i1}
do_test like-3.10 {
  set sqlite_like_count
} 6

# No optimization when the pattern begins with a wildcard.
# Note that the index is still used but only for sorting.
#
do_test like-3.11 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE '%bcd' ORDER BY 1;
  }
} {abcd bcd nosort {} i1}
do_test like-3.12 {
  set sqlite_like_count
} 12

# No optimization for case insensitive LIKE
#
do_test like-3.13 {
  set sqlite_like_count 0
  queryplan {
    PRAGMA case_sensitive_like=off;
    SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1;
  }
} {ABC {ABC abc xyz} abc abcd nosort {} i1}
do_test like-3.14 {
  set sqlite_like_count
} 12

# No optimization without an index.
#
do_test like-3.15 {
  set sqlite_like_count 0
  queryplan {
    PRAGMA case_sensitive_like=on;
    DROP INDEX i1;
    SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1;
  }
} {abc abcd sort t1 {}}
do_test like-3.16 {
  set sqlite_like_count
} 12

# No GLOB optimization without an index.
#
do_test like-3.17 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x GLOB 'abc*' ORDER BY 1;
  }
} {abc abcd sort t1 {}}
do_test like-3.18 {
  set sqlite_like_count
} 12

# GLOB is optimized regardless of the case_sensitive_like setting.
#
do_test like-3.19 {
  set sqlite_like_count 0
  queryplan {
    CREATE INDEX i1 ON t1(x);
    SELECT x FROM t1 WHERE x GLOB 'abc*' ORDER BY 1;
  }
} {abc abcd nosort {} i1}
do_test like-3.20 {
  set sqlite_like_count
} 0
do_test like-3.21 {
  set sqlite_like_count 0
  queryplan {
    PRAGMA case_sensitive_like=on;
    SELECT x FROM t1 WHERE x GLOB 'abc*' ORDER BY 1;
  }
} {abc abcd nosort {} i1}
do_test like-3.22 {
  set sqlite_like_count
} 0
do_test like-3.23 {
  set sqlite_like_count 0
  queryplan {
    PRAGMA case_sensitive_like=off;
    SELECT x FROM t1 WHERE x GLOB 'a[bc]d' ORDER BY 1;
  }
} {abd acd nosort {} i1}
do_test like-3.24 {
  set sqlite_like_count
} 6

# No optimization if the LHS of the LIKE is not a column name or
# if the RHS is not a string.
#
do_test like-4.1 {
  execsql {PRAGMA case_sensitive_like=on}
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1
  }
} {abc abcd nosort {} i1}
do_test like-4.2 {
  set sqlite_like_count
} 0
do_test like-4.3 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE +x LIKE 'abc%' ORDER BY 1
  }
} {abc abcd nosort {} i1}
do_test like-4.4 {
  set sqlite_like_count
} 12
do_test like-4.5 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE ('ab' || 'c%') ORDER BY 1
  }
} {abc abcd nosort {} i1}
do_test like-4.6 {
  set sqlite_like_count
} 12

# Collating sequences on the index disable the LIKE optimization.
# Or if the NOCASE collating sequence is used, the LIKE optimization
# is enabled when case_sensitive_like is OFF.
#
do_test like-5.1 {
  execsql {PRAGMA case_sensitive_like=off}
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1
  }
} {ABC {ABC abc xyz} abc abcd nosort {} i1}
do_test like-5.2 {
  set sqlite_like_count
} 12
do_test like-5.3 {
  execsql {
    CREATE TABLE t2(x TEXT COLLATE NOCASE);
    INSERT INTO t2 SELECT * FROM t1;
    CREATE INDEX i2 ON t2(x COLLATE NOCASE);
  }
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'abc%' ORDER BY 1
  }
} {abc ABC {ABC abc xyz} abcd nosort {} i2}
do_test like-5.4 {
  set sqlite_like_count
} 0
do_test like-5.5 {
  execsql {
    PRAGMA case_sensitive_like=on;
  }
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'abc%' ORDER BY 1
  }
} {abc abcd nosort {} i2}
do_test like-5.6 {
  set sqlite_like_count
} 12
do_test like-5.7 {
  execsql {
    PRAGMA case_sensitive_like=off;
  }
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t2 WHERE x GLOB 'abc*' ORDER BY 1
  }
} {abc abcd nosort {} i2}
do_test like-5.8 {
  set sqlite_like_count
} 12
do_test like-5.11 {
  execsql {PRAGMA case_sensitive_like=off}
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t1 WHERE x LIKE 'ABC%' ORDER BY 1
  }
} {ABC {ABC abc xyz} abc abcd nosort {} i1}
do_test like-5.12 {
  set sqlite_like_count
} 12
do_test like-5.13 {
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'ABC%' ORDER BY 1
  }
} {abc ABC {ABC abc xyz} abcd nosort {} i2}
do_test like-5.14 {
  set sqlite_like_count
} 0
do_test like-5.15 {
  execsql {
    PRAGMA case_sensitive_like=on;
  }
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'ABC%' ORDER BY 1
  }
} {ABC {ABC abc xyz} nosort {} i2}
do_test like-5.16 {
  set sqlite_like_count
} 12
do_test like-5.17 {
  execsql {
    PRAGMA case_sensitive_like=off;
  }
  set sqlite_like_count 0
  queryplan {
    SELECT x FROM t2 WHERE x GLOB 'ABC*' ORDER BY 1
  }
} {ABC {ABC abc xyz} nosort {} i2}
do_test like-5.18 {
  set sqlite_like_count
} 12

# Boundary case.  The prefix for a LIKE comparison is rounded up
# when constructing the comparison.  Example:  "ab" becomes "ac".
# In other words, the last character is increased by one.
#
# Make sure this happens correctly when the last character is a 
# "z" and we are doing case-insensitive comparisons.
#
# Ticket #2959
#
do_test like-5.21 {
  execsql {
    PRAGMA case_sensitive_like=off;
    INSERT INTO t2 VALUES('ZZ-upper-upper');
    INSERT INTO t2 VALUES('zZ-lower-upper');
    INSERT INTO t2 VALUES('Zz-upper-lower');
    INSERT INTO t2 VALUES('zz-lower-lower');
  }
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'zz%';
  }
} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2}
do_test like-5.22 {
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'zZ%';
  }
} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2}
do_test like-5.23 {
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'Zz%';
  }
} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2}
do_test like-5.24 {
  queryplan {
    SELECT x FROM t2 WHERE x LIKE 'ZZ%';
  }
} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2}
do_test like-5.25 {
  queryplan {
    PRAGMA case_sensitive_like=on;
    CREATE TABLE t3(x TEXT);
    CREATE INDEX i3 ON t3(x);
    INSERT INTO t3 VALUES('ZZ-upper-upper');
    INSERT INTO t3 VALUES('zZ-lower-upper');
    INSERT INTO t3 VALUES('Zz-upper-lower');
    INSERT INTO t3 VALUES('zz-lower-lower');
    SELECT x FROM t3 WHERE x LIKE 'zz%';
  }
} {zz-lower-lower nosort {} i3}
do_test like-5.26 {
  queryplan {
    SELECT x FROM t3 WHERE x LIKE 'zZ%';
  }
} {zZ-lower-upper nosort {} i3}
do_test like-5.27 {
  queryplan {
    SELECT x FROM t3 WHERE x LIKE 'Zz%';
  }
} {Zz-upper-lower nosort {} i3}
do_test like-5.28 {
  queryplan {
    SELECT x FROM t3 WHERE x LIKE 'ZZ%';
  }
} {ZZ-upper-upper nosort {} i3}


# ticket #2407
#
# Make sure the LIKE prefix optimization does not strip off leading
# characters of the like pattern that happen to be quote characters.
#
do_test like-6.1 {
  foreach x { 'abc 'bcd 'def 'ax } {
    set x2 '[string map {' ''} $x]'
    db eval "INSERT INTO t2 VALUES($x2)"
  }
  execsql {
    SELECT * FROM t2 WHERE x LIKE '''a%'
  }
} {'abc 'ax}

do_test like-7.1 {
  execsql {
    SELECT rowid, * FROM t1 WHERE rowid GLOB '1*' ORDER BY rowid;
  }
} {1 a 10 ABC 11 CDE 12 {ABC abc xyz}}

# ticket #3345.
#
# Overloading the LIKE function with -1 for the number of arguments
# will overload both the 2-argument and the 3-argument LIKE.
#
do_test like-8.1 {
  db eval {
    CREATE TABLE t8(x);
    INSERT INTO t8 VALUES('abcdef');
    INSERT INTO t8 VALUES('ghijkl');
    INSERT INTO t8 VALUES('mnopqr');
    SELECT 1, x FROM t8 WHERE x LIKE '%h%';
    SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x';
  }
} {1 ghijkl 2 ghijkl}
do_test like-8.2 {
  proc newlike {args} {return 1} ;# Alternative LIKE is always return TRUE
  db function like newlike       ;# Uses -1 for nArg in sqlite3_create_function
  db cache flush
  db eval {
    SELECT 1, x FROM t8 WHERE x LIKE '%h%';
    SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x';
  }
} {1 ghijkl 2 ghijkl}
do_test like-8.3 {
  db function like -argcount 2 newlike
  db eval {
    SELECT 1, x FROM t8 WHERE x LIKE '%h%';
    SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x';
  }
} {1 abcdef 1 ghijkl 1 mnopqr 2 ghijkl}
do_test like-8.4 {
  db function like -argcount 3 newlike
  db eval {
    SELECT 1, x FROM t8 WHERE x LIKE '%h%';
    SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x';
  }
} {1 abcdef 1 ghijkl 1 mnopqr 2 abcdef 2 ghijkl 2 mnopqr}


ifcapable like_opt {
  # Evaluate SQL.  Return the result set followed by the
  # and the number of full-scan steps.
  #
  db close
  sqlite3 db test.db
  proc count_steps {sql} {
    set r [db eval $sql]
    lappend r scan [db status step] sort [db status sort]
  }
  do_test like-9.1 {
    count_steps {
       SELECT x FROM t2 WHERE x LIKE 'x%'
    }
  } {xyz scan 0 sort 0}
  do_test like-9.2 {
    count_steps {
       SELECT x FROM t2 WHERE x LIKE '_y%'
    }
  } {xyz scan 19 sort 0}
  do_test like-9.3.1 {
    set res [sqlite3_exec_hex db {
       SELECT x FROM t2 WHERE x LIKE '%78%25'
    }]
  } {0 {x xyz}}
  ifcapable explain {
    do_test like-9.3.2 {
      set res [sqlite3_exec_hex db {
         EXPLAIN QUERY PLAN SELECT x FROM t2 WHERE x LIKE '%78%25'
      }]
      regexp {INDEX i2} $res
    } {1}
  }
  do_test like-9.4.1 {
    sqlite3_exec_hex db {INSERT INTO t2 VALUES('%ffhello')}
    set res [sqlite3_exec_hex db {
       SELECT substr(x,2) AS x FROM t2 WHERE +x LIKE '%ff%25'
    }]
  } {0 {x hello}}
  do_test like-9.4.2 {
    set res [sqlite3_exec_hex db {
       SELECT substr(x,2) AS x FROM t2 WHERE x LIKE '%ff%25'
    }]
  } {0 {x hello}}
  ifcapable explain {
    do_test like-9.4.3 {
      set res [sqlite3_exec_hex db {
         EXPLAIN QUERY PLAN SELECT x FROM t2 WHERE x LIKE '%ff%25'
      }]
      regexp {INDEX i2} $res
    } {0}
  }
  do_test like-9.5.1 {
    set res [sqlite3_exec_hex db {
       SELECT x FROM t2 WHERE x LIKE '%fe%25'
    }]
  } {0 {}}
  ifcapable explain {
    do_test like-9.5.2 {
      set res [sqlite3_exec_hex db {
         EXPLAIN QUERY PLAN SELECT x FROM t2 WHERE x LIKE '%fe%25'
      }]
      regexp {INDEX i2} $res
    } {1}
  }
}

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  set ::sqlite_like_count 0
  return [concat [execsql $sql] scan $::sqlite_search_count \
           like $::sqlite_like_count]
}

# The LIKE and GLOB optimizations do not work on columns with
# affinity other than TEXT.
# Ticket #3901
#
do_test like-10.1 {
  db close
  sqlite3 db test.db
  execsql {
    CREATE TABLE t10(
      a INTEGER PRIMARY KEY,
      b INTEGER COLLATE nocase UNIQUE,
      c NUMBER COLLATE nocase UNIQUE,
      d BLOB COLLATE nocase UNIQUE,
      e COLLATE nocase UNIQUE,
      f TEXT COLLATE nocase UNIQUE
    );
    INSERT INTO t10 VALUES(1,1,1,1,1,1);
    INSERT INTO t10 VALUES(12,12,12,12,12,12);
    INSERT INTO t10 VALUES(123,123,123,123,123,123);
    INSERT INTO t10 VALUES(234,234,234,234,234,234);
    INSERT INTO t10 VALUES(345,345,345,345,345,345);
    INSERT INTO t10 VALUES(45,45,45,45,45,45);
  }
  count {
    SELECT a FROM t10 WHERE b LIKE '12%' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.2 {
  count {
    SELECT a FROM t10 WHERE c LIKE '12%' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.3 {
  count {
    SELECT a FROM t10 WHERE d LIKE '12%' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.4 {
  count {
    SELECT a FROM t10 WHERE e LIKE '12%' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.5 {
  count {
    SELECT a FROM t10 WHERE f LIKE '12%' ORDER BY a;
  }
} {12 123 scan 3 like 0}
do_test like-10.6 {
  count {
    SELECT a FROM t10 WHERE a LIKE '12%' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.10 {
  execsql {
    CREATE TABLE t10b(
      a INTEGER PRIMARY KEY,
      b INTEGER UNIQUE,
      c NUMBER UNIQUE,
      d BLOB UNIQUE,
      e UNIQUE,
      f TEXT UNIQUE
    );
    INSERT INTO t10b SELECT * FROM t10;
  }
  count {
    SELECT a FROM t10b WHERE b GLOB '12*' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.11 {
  count {
    SELECT a FROM t10b WHERE c GLOB '12*' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.12 {
  count {
    SELECT a FROM t10b WHERE d GLOB '12*' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.13 {
  count {
    SELECT a FROM t10b WHERE e GLOB '12*' ORDER BY a;
  }
} {12 123 scan 5 like 6}
do_test like-10.14 {
  count {
    SELECT a FROM t10b WHERE f GLOB '12*' ORDER BY a;
  }
} {12 123 scan 3 like 0}
do_test like-10.15 {
  count {
    SELECT a FROM t10b WHERE a GLOB '12*' ORDER BY a;
  }
} {12 123 scan 5 like 6}


finish_test

Added test/like2.test.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# 2008 May 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the LIKE and GLOB operators and
# in particular the optimizations that occur to help those operators
# run faster.
#
# $Id: like2.test,v 1.1 2008/05/26 18:33:41 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test like2-1.1 {
  db eval {
    CREATE TABLE t1(x INT, y COLLATE NOCASE);
    INSERT INTO t1(x,y) VALUES(1,CAST(x'01' AS TEXT));
    INSERT INTO t1(x,y) VALUES(2,CAST(x'02' AS TEXT));
    INSERT INTO t1(x,y) VALUES(3,CAST(x'03' AS TEXT));
    INSERT INTO t1(x,y) VALUES(4,CAST(x'04' AS TEXT));
    INSERT INTO t1(x,y) VALUES(5,CAST(x'05' AS TEXT));
    INSERT INTO t1(x,y) VALUES(6,CAST(x'06' AS TEXT));
    INSERT INTO t1(x,y) VALUES(7,CAST(x'07' AS TEXT));
    INSERT INTO t1(x,y) VALUES(8,CAST(x'08' AS TEXT));
    INSERT INTO t1(x,y) VALUES(9,CAST(x'09' AS TEXT));
    INSERT INTO t1(x,y) VALUES(10,CAST(x'0a' AS TEXT));
    INSERT INTO t1(x,y) VALUES(11,CAST(x'0b' AS TEXT));
    INSERT INTO t1(x,y) VALUES(12,CAST(x'0c' AS TEXT));
    INSERT INTO t1(x,y) VALUES(13,CAST(x'0d' AS TEXT));
    INSERT INTO t1(x,y) VALUES(14,CAST(x'0e' AS TEXT));
    INSERT INTO t1(x,y) VALUES(15,CAST(x'0f' AS TEXT));
    INSERT INTO t1(x,y) VALUES(16,CAST(x'10' AS TEXT));
    INSERT INTO t1(x,y) VALUES(17,CAST(x'11' AS TEXT));
    INSERT INTO t1(x,y) VALUES(18,CAST(x'12' AS TEXT));
    INSERT INTO t1(x,y) VALUES(19,CAST(x'13' AS TEXT));
    INSERT INTO t1(x,y) VALUES(20,CAST(x'14' AS TEXT));
    INSERT INTO t1(x,y) VALUES(21,CAST(x'15' AS TEXT));
    INSERT INTO t1(x,y) VALUES(22,CAST(x'16' AS TEXT));
    INSERT INTO t1(x,y) VALUES(23,CAST(x'17' AS TEXT));
    INSERT INTO t1(x,y) VALUES(24,CAST(x'18' AS TEXT));
    INSERT INTO t1(x,y) VALUES(25,CAST(x'19' AS TEXT));
    INSERT INTO t1(x,y) VALUES(26,CAST(x'1a' AS TEXT));
    INSERT INTO t1(x,y) VALUES(27,CAST(x'1b' AS TEXT));
    INSERT INTO t1(x,y) VALUES(28,CAST(x'1c' AS TEXT));
    INSERT INTO t1(x,y) VALUES(29,CAST(x'1d' AS TEXT));
    INSERT INTO t1(x,y) VALUES(30,CAST(x'1e' AS TEXT));
    INSERT INTO t1(x,y) VALUES(31,CAST(x'1f' AS TEXT));
    INSERT INTO t1(x,y) VALUES(32,' ');
    INSERT INTO t1(x,y) VALUES(33,'!');
    INSERT INTO t1(x,y) VALUES(34,'"');
    INSERT INTO t1(x,y) VALUES(35,'#');
    INSERT INTO t1(x,y) VALUES(36,'$');
    INSERT INTO t1(x,y) VALUES(37,'%');
    INSERT INTO t1(x,y) VALUES(38,'&');
    INSERT INTO t1(x,y) VALUES(39,'''');
    INSERT INTO t1(x,y) VALUES(40,'(');
    INSERT INTO t1(x,y) VALUES(41,')');
    INSERT INTO t1(x,y) VALUES(42,'*');
    INSERT INTO t1(x,y) VALUES(43,'+');
    INSERT INTO t1(x,y) VALUES(44,',');
    INSERT INTO t1(x,y) VALUES(45,'-');
    INSERT INTO t1(x,y) VALUES(46,'.');
    INSERT INTO t1(x,y) VALUES(47,'/');
    INSERT INTO t1(x,y) VALUES(48,'0');
    INSERT INTO t1(x,y) VALUES(49,'1');
    INSERT INTO t1(x,y) VALUES(50,'2');
    INSERT INTO t1(x,y) VALUES(51,'3');
    INSERT INTO t1(x,y) VALUES(52,'4');
    INSERT INTO t1(x,y) VALUES(53,'5');
    INSERT INTO t1(x,y) VALUES(54,'6');
    INSERT INTO t1(x,y) VALUES(55,'7');
    INSERT INTO t1(x,y) VALUES(56,'8');
    INSERT INTO t1(x,y) VALUES(57,'9');
    INSERT INTO t1(x,y) VALUES(58,':');
    INSERT INTO t1(x,y) VALUES(59,';');
    INSERT INTO t1(x,y) VALUES(60,'<');
    INSERT INTO t1(x,y) VALUES(61,'=');
    INSERT INTO t1(x,y) VALUES(62,'>');
    INSERT INTO t1(x,y) VALUES(63,'?');
    INSERT INTO t1(x,y) VALUES(64,'@');
    INSERT INTO t1(x,y) VALUES(65,'A');
    INSERT INTO t1(x,y) VALUES(66,'B');
    INSERT INTO t1(x,y) VALUES(67,'C');
    INSERT INTO t1(x,y) VALUES(68,'D');
    INSERT INTO t1(x,y) VALUES(69,'E');
    INSERT INTO t1(x,y) VALUES(70,'F');
    INSERT INTO t1(x,y) VALUES(71,'G');
    INSERT INTO t1(x,y) VALUES(72,'H');
    INSERT INTO t1(x,y) VALUES(73,'I');
    INSERT INTO t1(x,y) VALUES(74,'J');
    INSERT INTO t1(x,y) VALUES(75,'K');
    INSERT INTO t1(x,y) VALUES(76,'L');
    INSERT INTO t1(x,y) VALUES(77,'M');
    INSERT INTO t1(x,y) VALUES(78,'N');
    INSERT INTO t1(x,y) VALUES(79,'O');
    INSERT INTO t1(x,y) VALUES(80,'P');
    INSERT INTO t1(x,y) VALUES(81,'Q');
    INSERT INTO t1(x,y) VALUES(82,'R');
    INSERT INTO t1(x,y) VALUES(83,'S');
    INSERT INTO t1(x,y) VALUES(84,'T');
    INSERT INTO t1(x,y) VALUES(85,'U');
    INSERT INTO t1(x,y) VALUES(86,'V');
    INSERT INTO t1(x,y) VALUES(87,'W');
    INSERT INTO t1(x,y) VALUES(88,'X');
    INSERT INTO t1(x,y) VALUES(89,'Y');
    INSERT INTO t1(x,y) VALUES(90,'Z');
    INSERT INTO t1(x,y) VALUES(91,'[');
    INSERT INTO t1(x,y) VALUES(92,'\');
    INSERT INTO t1(x,y) VALUES(93,']');
    INSERT INTO t1(x,y) VALUES(94,'^');
    INSERT INTO t1(x,y) VALUES(95,'_');
    INSERT INTO t1(x,y) VALUES(96,'`');
    INSERT INTO t1(x,y) VALUES(97,'a');
    INSERT INTO t1(x,y) VALUES(98,'b');
    INSERT INTO t1(x,y) VALUES(99,'c');
    INSERT INTO t1(x,y) VALUES(100,'d');
    INSERT INTO t1(x,y) VALUES(101,'e');
    INSERT INTO t1(x,y) VALUES(102,'f');
    INSERT INTO t1(x,y) VALUES(103,'g');
    INSERT INTO t1(x,y) VALUES(104,'h');
    INSERT INTO t1(x,y) VALUES(105,'i');
    INSERT INTO t1(x,y) VALUES(106,'j');
    INSERT INTO t1(x,y) VALUES(107,'k');
    INSERT INTO t1(x,y) VALUES(108,'l');
    INSERT INTO t1(x,y) VALUES(109,'m');
    INSERT INTO t1(x,y) VALUES(110,'n');
    INSERT INTO t1(x,y) VALUES(111,'o');
    INSERT INTO t1(x,y) VALUES(112,'p');
    INSERT INTO t1(x,y) VALUES(113,'q');
    INSERT INTO t1(x,y) VALUES(114,'r');
    INSERT INTO t1(x,y) VALUES(115,'s');
    INSERT INTO t1(x,y) VALUES(116,'t');
    INSERT INTO t1(x,y) VALUES(117,'u');
    INSERT INTO t1(x,y) VALUES(118,'v');
    INSERT INTO t1(x,y) VALUES(119,'w');
    INSERT INTO t1(x,y) VALUES(120,'x');
    INSERT INTO t1(x,y) VALUES(121,'y');
    INSERT INTO t1(x,y) VALUES(122,'z');
    INSERT INTO t1(x,y) VALUES(123,'{');
    INSERT INTO t1(x,y) VALUES(124,'|');
    INSERT INTO t1(x,y) VALUES(125,'}');
    INSERT INTO t1(x,y) VALUES(126,'~');
    INSERT INTO t1(x,y) VALUES(127,CAST(x'7f' AS TEXT));
    SELECT count(*) FROM t1;
  }
} {127}
do_test like2-1.2 {
  db eval {
    CREATE TABLE t2(x INT, y COLLATE NOCASE);
    INSERT INTO t2 SELECT * FROM t1;
    CREATE INDEX i2 ON t2(y);
    SELECT count(*) FROM t2;
  }
} {127}
do_test like2-1.3 {
  db eval {
    CREATE TABLE t3(x INT, y COLLATE NOCASE);
    INSERT INTO t3 SELECT x, 'abc' || y || 'xyz' FROM t1;
    CREATE INDEX i3 ON t3(y);
    SELECT count(*) FROM t2;
  }
} {127}
do_test like-2.32.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE ' %'"
} {32}
do_test like-2.32.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE ' %'"
} {32}
do_test like-2.32.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc %'"
} {32}
do_test like-2.33.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '!%'"
} {33}
do_test like-2.33.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '!%'"
} {33}
do_test like-2.33.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc!%'"
} {33}
do_test like-2.34.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\"%'"
} {34}
do_test like-2.34.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\"%'"
} {34}
do_test like-2.34.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\"%'"
} {34}
do_test like-2.35.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '#%'"
} {35}
do_test like-2.35.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '#%'"
} {35}
do_test like-2.35.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc#%'"
} {35}
do_test like-2.36.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\$%'"
} {36}
do_test like-2.36.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\$%'"
} {36}
do_test like-2.36.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\$%'"
} {36}
do_test like-2.38.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '&%'"
} {38}
do_test like-2.38.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '&%'"
} {38}
do_test like-2.38.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc&%'"
} {38}
do_test like-2.39.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '''%'"
} {39}
do_test like-2.39.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '''%'"
} {39}
do_test like-2.39.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc''%'"
} {39}
do_test like-2.40.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '(%'"
} {40}
do_test like-2.40.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '(%'"
} {40}
do_test like-2.40.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc(%'"
} {40}
do_test like-2.41.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE ')%'"
} {41}
do_test like-2.41.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE ')%'"
} {41}
do_test like-2.41.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc)%'"
} {41}
do_test like-2.42.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '*%'"
} {42}
do_test like-2.42.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '*%'"
} {42}
do_test like-2.42.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc*%'"
} {42}
do_test like-2.43.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '+%'"
} {43}
do_test like-2.43.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '+%'"
} {43}
do_test like-2.43.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc+%'"
} {43}
do_test like-2.44.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE ',%'"
} {44}
do_test like-2.44.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE ',%'"
} {44}
do_test like-2.44.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc,%'"
} {44}
do_test like-2.45.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '-%'"
} {45}
do_test like-2.45.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '-%'"
} {45}
do_test like-2.45.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc-%'"
} {45}
do_test like-2.46.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '.%'"
} {46}
do_test like-2.46.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '.%'"
} {46}
do_test like-2.46.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc.%'"
} {46}
do_test like-2.47.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '/%'"
} {47}
do_test like-2.47.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '/%'"
} {47}
do_test like-2.47.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc/%'"
} {47}
do_test like-2.48.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '0%'"
} {48}
do_test like-2.48.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '0%'"
} {48}
do_test like-2.48.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc0%'"
} {48}
do_test like-2.49.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '1%'"
} {49}
do_test like-2.49.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '1%'"
} {49}
do_test like-2.49.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc1%'"
} {49}
do_test like-2.50.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '2%'"
} {50}
do_test like-2.50.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '2%'"
} {50}
do_test like-2.50.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc2%'"
} {50}
do_test like-2.51.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '3%'"
} {51}
do_test like-2.51.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '3%'"
} {51}
do_test like-2.51.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc3%'"
} {51}
do_test like-2.52.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '4%'"
} {52}
do_test like-2.52.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '4%'"
} {52}
do_test like-2.52.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc4%'"
} {52}
do_test like-2.53.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '5%'"
} {53}
do_test like-2.53.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '5%'"
} {53}
do_test like-2.53.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc5%'"
} {53}
do_test like-2.54.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '6%'"
} {54}
do_test like-2.54.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '6%'"
} {54}
do_test like-2.54.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc6%'"
} {54}
do_test like-2.55.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '7%'"
} {55}
do_test like-2.55.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '7%'"
} {55}
do_test like-2.55.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc7%'"
} {55}
do_test like-2.56.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '8%'"
} {56}
do_test like-2.56.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '8%'"
} {56}
do_test like-2.56.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc8%'"
} {56}
do_test like-2.57.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '9%'"
} {57}
do_test like-2.57.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '9%'"
} {57}
do_test like-2.57.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc9%'"
} {57}
do_test like-2.58.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE ':%'"
} {58}
do_test like-2.58.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE ':%'"
} {58}
do_test like-2.58.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc:%'"
} {58}
do_test like-2.59.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE ';%'"
} {59}
do_test like-2.59.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE ';%'"
} {59}
do_test like-2.59.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc;%'"
} {59}
do_test like-2.60.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '<%'"
} {60}
do_test like-2.60.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '<%'"
} {60}
do_test like-2.60.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc<%'"
} {60}
do_test like-2.61.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '=%'"
} {61}
do_test like-2.61.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '=%'"
} {61}
do_test like-2.61.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc=%'"
} {61}
do_test like-2.62.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '>%'"
} {62}
do_test like-2.62.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '>%'"
} {62}
do_test like-2.62.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc>%'"
} {62}
do_test like-2.63.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '?%'"
} {63}
do_test like-2.63.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '?%'"
} {63}
do_test like-2.63.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc?%'"
} {63}
do_test like-2.64.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '@%'"
} {64}
do_test like-2.64.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '@%'"
} {64}
do_test like-2.64.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc@%'"
} {64}
do_test like-2.65.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'A%'"
} {65 97}
do_test like-2.65.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'A%'"
} {65 97}
do_test like-2.65.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcA%'"
} {65 97}
do_test like-2.66.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'B%'"
} {66 98}
do_test like-2.66.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'B%'"
} {66 98}
do_test like-2.66.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcB%'"
} {66 98}
do_test like-2.67.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'C%'"
} {67 99}
do_test like-2.67.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'C%'"
} {67 99}
do_test like-2.67.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcC%'"
} {67 99}
do_test like-2.68.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'D%'"
} {68 100}
do_test like-2.68.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'D%'"
} {68 100}
do_test like-2.68.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcD%'"
} {68 100}
do_test like-2.69.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'E%'"
} {69 101}
do_test like-2.69.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'E%'"
} {69 101}
do_test like-2.69.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcE%'"
} {69 101}
do_test like-2.70.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'F%'"
} {70 102}
do_test like-2.70.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'F%'"
} {70 102}
do_test like-2.70.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcF%'"
} {70 102}
do_test like-2.71.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'G%'"
} {71 103}
do_test like-2.71.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'G%'"
} {71 103}
do_test like-2.71.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcG%'"
} {71 103}
do_test like-2.72.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'H%'"
} {72 104}
do_test like-2.72.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'H%'"
} {72 104}
do_test like-2.72.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcH%'"
} {72 104}
do_test like-2.73.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'I%'"
} {73 105}
do_test like-2.73.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'I%'"
} {73 105}
do_test like-2.73.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcI%'"
} {73 105}
do_test like-2.74.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'J%'"
} {74 106}
do_test like-2.74.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'J%'"
} {74 106}
do_test like-2.74.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcJ%'"
} {74 106}
do_test like-2.75.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'K%'"
} {75 107}
do_test like-2.75.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'K%'"
} {75 107}
do_test like-2.75.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcK%'"
} {75 107}
do_test like-2.76.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'L%'"
} {76 108}
do_test like-2.76.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'L%'"
} {76 108}
do_test like-2.76.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcL%'"
} {76 108}
do_test like-2.77.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'M%'"
} {77 109}
do_test like-2.77.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'M%'"
} {77 109}
do_test like-2.77.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcM%'"
} {77 109}
do_test like-2.78.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'N%'"
} {78 110}
do_test like-2.78.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'N%'"
} {78 110}
do_test like-2.78.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcN%'"
} {78 110}
do_test like-2.79.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'O%'"
} {79 111}
do_test like-2.79.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'O%'"
} {79 111}
do_test like-2.79.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcO%'"
} {79 111}
do_test like-2.80.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'P%'"
} {80 112}
do_test like-2.80.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'P%'"
} {80 112}
do_test like-2.80.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcP%'"
} {80 112}
do_test like-2.81.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'Q%'"
} {81 113}
do_test like-2.81.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'Q%'"
} {81 113}
do_test like-2.81.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcQ%'"
} {81 113}
do_test like-2.82.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'R%'"
} {82 114}
do_test like-2.82.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'R%'"
} {82 114}
do_test like-2.82.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcR%'"
} {82 114}
do_test like-2.83.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'S%'"
} {83 115}
do_test like-2.83.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'S%'"
} {83 115}
do_test like-2.83.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcS%'"
} {83 115}
do_test like-2.84.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'T%'"
} {84 116}
do_test like-2.84.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'T%'"
} {84 116}
do_test like-2.84.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcT%'"
} {84 116}
do_test like-2.85.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'U%'"
} {85 117}
do_test like-2.85.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'U%'"
} {85 117}
do_test like-2.85.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcU%'"
} {85 117}
do_test like-2.86.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'V%'"
} {86 118}
do_test like-2.86.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'V%'"
} {86 118}
do_test like-2.86.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcV%'"
} {86 118}
do_test like-2.87.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'W%'"
} {87 119}
do_test like-2.87.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'W%'"
} {87 119}
do_test like-2.87.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcW%'"
} {87 119}
do_test like-2.88.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'X%'"
} {88 120}
do_test like-2.88.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'X%'"
} {88 120}
do_test like-2.88.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcX%'"
} {88 120}
do_test like-2.89.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'Y%'"
} {89 121}
do_test like-2.89.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'Y%'"
} {89 121}
do_test like-2.89.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcY%'"
} {89 121}
do_test like-2.90.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'Z%'"
} {90 122}
do_test like-2.90.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'Z%'"
} {90 122}
do_test like-2.90.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcZ%'"
} {90 122}
do_test like-2.91.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\[%'"
} {91}
do_test like-2.91.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\[%'"
} {91}
do_test like-2.91.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\[%'"
} {91}
do_test like-2.92.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\\%'"
} {92}
do_test like-2.92.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\\%'"
} {92}
do_test like-2.92.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\\%'"
} {92}
do_test like-2.93.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\]%'"
} {93}
do_test like-2.93.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\]%'"
} {93}
do_test like-2.93.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\]%'"
} {93}
do_test like-2.94.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '^%'"
} {94}
do_test like-2.94.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '^%'"
} {94}
do_test like-2.94.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc^%'"
} {94}
do_test like-2.96.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '`%'"
} {96}
do_test like-2.96.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '`%'"
} {96}
do_test like-2.96.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc`%'"
} {96}
do_test like-2.97.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'a%'"
} {65 97}
do_test like-2.97.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'a%'"
} {65 97}
do_test like-2.97.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abca%'"
} {65 97}
do_test like-2.98.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'b%'"
} {66 98}
do_test like-2.98.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'b%'"
} {66 98}
do_test like-2.98.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcb%'"
} {66 98}
do_test like-2.99.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'c%'"
} {67 99}
do_test like-2.99.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'c%'"
} {67 99}
do_test like-2.99.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcc%'"
} {67 99}
do_test like-2.100.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'd%'"
} {68 100}
do_test like-2.100.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'd%'"
} {68 100}
do_test like-2.100.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcd%'"
} {68 100}
do_test like-2.101.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'e%'"
} {69 101}
do_test like-2.101.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'e%'"
} {69 101}
do_test like-2.101.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abce%'"
} {69 101}
do_test like-2.102.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'f%'"
} {70 102}
do_test like-2.102.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'f%'"
} {70 102}
do_test like-2.102.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcf%'"
} {70 102}
do_test like-2.103.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'g%'"
} {71 103}
do_test like-2.103.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'g%'"
} {71 103}
do_test like-2.103.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcg%'"
} {71 103}
do_test like-2.104.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'h%'"
} {72 104}
do_test like-2.104.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'h%'"
} {72 104}
do_test like-2.104.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abch%'"
} {72 104}
do_test like-2.105.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'i%'"
} {73 105}
do_test like-2.105.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'i%'"
} {73 105}
do_test like-2.105.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abci%'"
} {73 105}
do_test like-2.106.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'j%'"
} {74 106}
do_test like-2.106.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'j%'"
} {74 106}
do_test like-2.106.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcj%'"
} {74 106}
do_test like-2.107.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'k%'"
} {75 107}
do_test like-2.107.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'k%'"
} {75 107}
do_test like-2.107.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abck%'"
} {75 107}
do_test like-2.108.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'l%'"
} {76 108}
do_test like-2.108.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'l%'"
} {76 108}
do_test like-2.108.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcl%'"
} {76 108}
do_test like-2.109.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'm%'"
} {77 109}
do_test like-2.109.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'm%'"
} {77 109}
do_test like-2.109.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcm%'"
} {77 109}
do_test like-2.110.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'n%'"
} {78 110}
do_test like-2.110.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'n%'"
} {78 110}
do_test like-2.110.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcn%'"
} {78 110}
do_test like-2.111.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'o%'"
} {79 111}
do_test like-2.111.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'o%'"
} {79 111}
do_test like-2.111.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abco%'"
} {79 111}
do_test like-2.112.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'p%'"
} {80 112}
do_test like-2.112.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'p%'"
} {80 112}
do_test like-2.112.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcp%'"
} {80 112}
do_test like-2.113.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'q%'"
} {81 113}
do_test like-2.113.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'q%'"
} {81 113}
do_test like-2.113.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcq%'"
} {81 113}
do_test like-2.114.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'r%'"
} {82 114}
do_test like-2.114.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'r%'"
} {82 114}
do_test like-2.114.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcr%'"
} {82 114}
do_test like-2.115.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 's%'"
} {83 115}
do_test like-2.115.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 's%'"
} {83 115}
do_test like-2.115.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcs%'"
} {83 115}
do_test like-2.116.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 't%'"
} {84 116}
do_test like-2.116.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 't%'"
} {84 116}
do_test like-2.116.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abct%'"
} {84 116}
do_test like-2.117.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'u%'"
} {85 117}
do_test like-2.117.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'u%'"
} {85 117}
do_test like-2.117.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcu%'"
} {85 117}
do_test like-2.118.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'v%'"
} {86 118}
do_test like-2.118.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'v%'"
} {86 118}
do_test like-2.118.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcv%'"
} {86 118}
do_test like-2.119.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'w%'"
} {87 119}
do_test like-2.119.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'w%'"
} {87 119}
do_test like-2.119.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcw%'"
} {87 119}
do_test like-2.120.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'x%'"
} {88 120}
do_test like-2.120.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'x%'"
} {88 120}
do_test like-2.120.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcx%'"
} {88 120}
do_test like-2.121.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'y%'"
} {89 121}
do_test like-2.121.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'y%'"
} {89 121}
do_test like-2.121.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcy%'"
} {89 121}
do_test like-2.122.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE 'z%'"
} {90 122}
do_test like-2.122.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE 'z%'"
} {90 122}
do_test like-2.122.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abcz%'"
} {90 122}
do_test like-2.123.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\173%'"
} {123}
do_test like-2.123.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\173%'"
} {123}
do_test like-2.123.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\173%'"
} {123}
do_test like-2.124.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '|%'"
} {124}
do_test like-2.124.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '|%'"
} {124}
do_test like-2.124.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc|%'"
} {124}
do_test like-2.125.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '\175%'"
} {125}
do_test like-2.125.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '\175%'"
} {125}
do_test like-2.125.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc\175%'"
} {125}
do_test like-2.126.1 {
  db eval "SELECT x FROM t1 WHERE y LIKE '~%'"
} {126}
do_test like-2.126.2 {
  db eval "SELECT x FROM t2 WHERE y LIKE '~%'"
} {126}
do_test like-2.126.3 {
  db eval "SELECT x FROM t3 WHERE y LIKE 'abc~%'"
} {126}


finish_test

Added test/limit.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# 2001 November 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the LIMIT ... OFFSET ... clause
#  of SELECT statements.
#
# $Id: limit.test,v 1.32 2008/08/02 03:50:39 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
execsql {
  CREATE TABLE t1(x int, y int);
  BEGIN;
}
for {set i 1} {$i<=32} {incr i} {
  for {set j 0} {(1<<$j)<$i} {incr j} {}
  execsql "INSERT INTO t1 VALUES([expr {32-$i}],[expr {10-$j}])"
}
execsql {
  COMMIT;
}

do_test limit-1.0 {
  execsql {SELECT count(*) FROM t1}
} {32}
do_test limit-1.1 {
  execsql {SELECT count(*) FROM t1 LIMIT  5}
} {32}
do_test limit-1.2.1 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 5}
} {0 1 2 3 4}
do_test limit-1.2.2 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 5 OFFSET 2}
} {2 3 4 5 6}
do_test limit-1.2.3 {
  execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT 5 OFFSET -2}
} {0 1 2 3 4}
do_test limit-1.2.4 {
  execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT 2, -5}
} {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31}
do_test limit-1.2.5 {
  execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT -2, 5}
} {0 1 2 3 4}
do_test limit-1.2.6 {
  execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT -2, -5}
} {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31}
do_test limit-1.2.7 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 2, 5}
} {2 3 4 5 6}
do_test limit-1.3 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 5 OFFSET 5}
} {5 6 7 8 9}
do_test limit-1.4.1 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 50 OFFSET 30}
} {30 31}
do_test limit-1.4.2 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 30, 50}
} {30 31}
do_test limit-1.5 {
  execsql {SELECT x FROM t1 ORDER BY x LIMIT 50 OFFSET 50}
} {}
do_test limit-1.6 {
  execsql {SELECT * FROM t1 AS a, t1 AS b ORDER BY a.x, b.x LIMIT 5}
} {0 5 0 5 0 5 1 5 0 5 2 5 0 5 3 5 0 5 4 5}
do_test limit-1.7 {
  execsql {SELECT * FROM t1 AS a, t1 AS b ORDER BY a.x, b.x LIMIT 5 OFFSET 32}
} {1 5 0 5 1 5 1 5 1 5 2 5 1 5 3 5 1 5 4 5}

ifcapable {view && subquery} {
  do_test limit-2.1 {
    execsql {
      CREATE VIEW v1 AS SELECT * FROM t1 LIMIT 2;
      SELECT count(*) FROM (SELECT * FROM v1);
    }
  } 2
} ;# ifcapable view
do_test limit-2.2 {
  execsql {
    CREATE TABLE t2 AS SELECT * FROM t1 LIMIT 2;
    SELECT count(*) FROM t2;
  }
} 2
ifcapable subquery {
  do_test limit-2.3 {
    execsql {
      SELECT count(*) FROM t1 WHERE rowid IN (SELECT rowid FROM t1 LIMIT 2);
    }
  } 2
}

ifcapable subquery {
  do_test limit-3.1 {
    execsql {
      SELECT z FROM (SELECT y*10+x AS z FROM t1 ORDER BY x LIMIT 10)
      ORDER BY z LIMIT 5;
    }
  } {50 51 52 53 54}
}

do_test limit-4.1 {
  ifcapable subquery { 
    execsql {
      BEGIN;
      CREATE TABLE t3(x);
      INSERT INTO t3 SELECT x FROM t1 ORDER BY x LIMIT 10 OFFSET 1;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3;
      END;
      SELECT count(*) FROM t3;
    }
  } else {
    execsql {
      BEGIN;
      CREATE TABLE t3(x);
      INSERT INTO t3 SELECT x FROM t1 ORDER BY x LIMIT 10 OFFSET 1;
    }
    for {set i 0} {$i<10} {incr i} {
      set max_x_t3 [execsql {SELECT max(x) FROM t3}]
      execsql "INSERT INTO t3 SELECT x+$max_x_t3 FROM t3;"
    }
    execsql {
      END;
      SELECT count(*) FROM t3;
    }
  }
} {10240}
do_test limit-4.2 {
  execsql {
    SELECT x FROM t3 LIMIT 2 OFFSET 10000
  }
} {10001 10002}
do_test limit-4.3 {
  execsql {
    CREATE TABLE t4 AS SELECT x,
       'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x ||
       'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x ||
       'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x ||
       'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x ||
       'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x AS y
    FROM t3 LIMIT 1000;
    SELECT x FROM t4 ORDER BY y DESC LIMIT 1 OFFSET 999;
  }
} {1000}

do_test limit-5.1 {
  execsql {
    CREATE TABLE t5(x,y);
    INSERT INTO t5 SELECT x-y, x+y FROM t1 WHERE x BETWEEN 10 AND 15
        ORDER BY x LIMIT 2;
    SELECT * FROM t5 ORDER BY x;
  }
} {5 15 6 16}
do_test limit-5.2 {
  execsql {
    DELETE FROM t5;
    INSERT INTO t5 SELECT x-y, x+y FROM t1 WHERE x BETWEEN 10 AND 15
        ORDER BY x DESC LIMIT 2;
    SELECT * FROM t5 ORDER BY x;
  }
} {9 19 10 20}
do_test limit-5.3 {
  execsql {
    DELETE FROM t5;
    INSERT INTO t5 SELECT x-y, x+y FROM t1 WHERE x ORDER BY x DESC LIMIT 31;
    SELECT * FROM t5 ORDER BY x LIMIT 2;
  }
} {-4 6 -3 7}
do_test limit-5.4 {
  execsql {
    SELECT * FROM t5 ORDER BY x DESC, y DESC LIMIT 2;
  }
} {21 41 21 39}
do_test limit-5.5 {
  execsql {
    DELETE FROM t5;
    INSERT INTO t5 SELECT a.x*100+b.x, a.y*100+b.y FROM t1 AS a, t1 AS b
                   ORDER BY 1, 2 LIMIT 1000;
    SELECT count(*), sum(x), sum(y), min(x), max(x), min(y), max(y) FROM t5;
  }
} {1000 1528204 593161 0 3107 505 1005}

# There is some contraversy about whether LIMIT 0 should be the same as
# no limit at all or if LIMIT 0 should result in zero output rows.
#
do_test limit-6.1 {
  execsql {
    BEGIN;
    CREATE TABLE t6(a);
    INSERT INTO t6 VALUES(1);
    INSERT INTO t6 VALUES(2);
    INSERT INTO t6 SELECT a+2 FROM t6;
    COMMIT;
    SELECT * FROM t6;
  }
} {1 2 3 4}
do_test limit-6.2 {
  execsql {
    SELECT * FROM t6 LIMIT -1 OFFSET -1;
  }
} {1 2 3 4}
do_test limit-6.3 {
  execsql {
    SELECT * FROM t6 LIMIT 2 OFFSET -123;
  }
} {1 2}
do_test limit-6.4 {
  execsql {
    SELECT * FROM t6 LIMIT -432 OFFSET 2;
  }
} {3 4}
do_test limit-6.5 {
  execsql {
    SELECT * FROM t6 LIMIT -1
  }
} {1 2 3 4}
do_test limit-6.6 {
  execsql {
    SELECT * FROM t6 LIMIT -1 OFFSET 1
  }
} {2 3 4}
do_test limit-6.7 {
  execsql {
    SELECT * FROM t6 LIMIT 0
  }
} {}
do_test limit-6.8 {
  execsql {
    SELECT * FROM t6 LIMIT 0 OFFSET 1
  }
} {}

# Make sure LIMIT works well with compound SELECT statements.
# Ticket #393
#
ifcapable compound {
do_test limit-7.1.1 {
  catchsql {
    SELECT x FROM t2 LIMIT 5 UNION ALL SELECT a FROM t6;
  }
} {1 {LIMIT clause should come after UNION ALL not before}}
do_test limit-7.1.2 {
  catchsql {
    SELECT x FROM t2 LIMIT 5 UNION SELECT a FROM t6;
  }
} {1 {LIMIT clause should come after UNION not before}}
do_test limit-7.1.3 {
  catchsql {
    SELECT x FROM t2 LIMIT 5 EXCEPT SELECT a FROM t6 LIMIT 3;
  }
} {1 {LIMIT clause should come after EXCEPT not before}}
do_test limit-7.1.4 {
  catchsql {
    SELECT x FROM t2 LIMIT 0,5 INTERSECT SELECT a FROM t6;
  }
} {1 {LIMIT clause should come after INTERSECT not before}}
do_test limit-7.2 {
  execsql {
    SELECT x FROM t2 UNION ALL SELECT a FROM t6 LIMIT 5;
  }
} {31 30 1 2 3}
do_test limit-7.3 {
  execsql {
    SELECT x FROM t2 UNION ALL SELECT a FROM t6 LIMIT 3 OFFSET 1;
  }
} {30 1 2}
do_test limit-7.4 {
  execsql {
    SELECT x FROM t2 UNION ALL SELECT a FROM t6 ORDER BY 1 LIMIT 3 OFFSET 1;
  }
} {2 3 4}
do_test limit-7.5 {
  execsql {
    SELECT x FROM t2 UNION SELECT x+2 FROM t2 LIMIT 2 OFFSET 1;
  }
} {31 32}
do_test limit-7.6 {
  execsql {
    SELECT x FROM t2 UNION SELECT x+2 FROM t2 ORDER BY 1 DESC LIMIT 2 OFFSET 1;
  }
} {32 31}
do_test limit-7.7 {
  execsql {
    SELECT a+9 FROM t6 EXCEPT SELECT y FROM t2 LIMIT 2;
  }
} {11 12}
do_test limit-7.8 {
  execsql {
    SELECT a+9 FROM t6 EXCEPT SELECT y FROM t2 ORDER BY 1 DESC LIMIT 2;
  }
} {13 12}
do_test limit-7.9 {
  execsql {
    SELECT a+26 FROM t6 INTERSECT SELECT x FROM t2 LIMIT 1;
  }
} {30}
do_test limit-7.10 {
  execsql {
    SELECT a+27 FROM t6 INTERSECT SELECT x FROM t2 LIMIT 1;
  }
} {30}
do_test limit-7.11 {
  execsql {
    SELECT a+27 FROM t6 INTERSECT SELECT x FROM t2 LIMIT 1 OFFSET 1;
  }
} {31}
do_test limit-7.12 {
  execsql {
    SELECT a+27 FROM t6 INTERSECT SELECT x FROM t2 
       ORDER BY 1 DESC LIMIT 1 OFFSET 1;
  }
} {30}
} ;# ifcapable compound

# Tests for limit in conjunction with distinct.  The distinct should
# occur before both the limit and the offset.  Ticket #749.
#
do_test limit-8.1 {
  execsql {
    SELECT DISTINCT cast(round(x/100) as integer) FROM t3 LIMIT 5;
  }
} {0 1 2 3 4}
do_test limit-8.2 {
  execsql {
    SELECT DISTINCT cast(round(x/100) as integer) FROM t3 LIMIT 5 OFFSET 5;
  }
} {5 6 7 8 9}
do_test limit-8.3 {
  execsql {
    SELECT DISTINCT cast(round(x/100) as integer) FROM t3 LIMIT 5 OFFSET 25;
  }
} {25 26 27 28 29}

# Make sure limits on multiple subqueries work correctly.
# Ticket #1035
#
ifcapable subquery {
  do_test limit-9.1 {
    execsql {
      SELECT * FROM (SELECT * FROM t6 LIMIT 3);
    }
  } {1 2 3}
}
do_test limit-9.2.1 {
  execsql {
    CREATE TABLE t7 AS SELECT * FROM t6;
  }
} {}
ifcapable subquery {
  do_test limit-9.2.2 {
    execsql {
      SELECT * FROM (SELECT * FROM t7 LIMIT 3);
    }
  } {1 2 3}
}
ifcapable compound {
  ifcapable subquery {
    do_test limit-9.3 {
      execsql {
        SELECT * FROM (SELECT * FROM t6 LIMIT 3)
        UNION
        SELECT * FROM (SELECT * FROM t7 LIMIT 3)
        ORDER BY 1
      }
    } {1 2 3}
    do_test limit-9.4 {
      execsql {
        SELECT * FROM (SELECT * FROM t6 LIMIT 3)
        UNION
        SELECT * FROM (SELECT * FROM t7 LIMIT 3)
        ORDER BY 1
        LIMIT 2
      }
    } {1 2}
  }
  do_test limit-9.5 {
    catchsql {
      SELECT * FROM t6 LIMIT 3
      UNION
      SELECT * FROM t7 LIMIT 3
    }
  } {1 {LIMIT clause should come after UNION not before}}
}

# Test LIMIT and OFFSET using SQL variables.
do_test limit-10.1 {
  set limit 10
  db eval {
    SELECT x FROM t1 LIMIT :limit;
  }
} {31 30 29 28 27 26 25 24 23 22}
do_test limit-10.2 {
  set limit 5
  set offset 5
  db eval {
    SELECT x FROM t1 LIMIT :limit OFFSET :offset;
  }
} {26 25 24 23 22}
do_test limit-10.3 {
  set limit -1
  db eval {
    SELECT x FROM t1 WHERE x<10 LIMIT :limit;
  }
} {9 8 7 6 5 4 3 2 1 0}
do_test limit-10.4 {
  set limit 1.5
  set rc [catch {
  db eval {
    SELECT x FROM t1 WHERE x<10 LIMIT :limit;
  } } msg]
  list $rc $msg
} {1 {datatype mismatch}}
do_test limit-10.5 {
  set limit "hello world"
  set rc [catch {
  db eval {
    SELECT x FROM t1 WHERE x<10 LIMIT :limit;
  } } msg]
  list $rc $msg
} {1 {datatype mismatch}}

ifcapable subquery {
do_test limit-11.1 {
  db eval {
     SELECT x FROM (SELECT x FROM t1 ORDER BY x LIMIT 0) ORDER BY x
  }
} {}
} ;# ifcapable subquery

# Test error processing.
#
do_test limit-12.1 {
  catchsql {
     SELECT * FROM t1 LIMIT replace(1)
  }
} {1 {wrong number of arguments to function replace()}}
do_test limit-12.2 {
  catchsql {
     SELECT * FROM t1 LIMIT 5 OFFSET replace(1)
  }
} {1 {wrong number of arguments to function replace()}}
do_test limit-12.3 {
  catchsql {
     SELECT * FROM t1 LIMIT x
  }
} {1 {no such column: x}}
do_test limit-12.4 {
  catchsql {
     SELECT * FROM t1 LIMIT 1 OFFSET x
  }
} {1 {no such column: x}}


finish_test

Added test/loadext.test.





































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# 2006 July 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is extension loading.
#
# $Id: loadext.test,v 1.17 2009/03/20 09:09:37 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !load_ext {
  finish_test
  return
}

# The name of the test extension varies by operating system.
#
if {$::tcl_platform(platform) eq "windows" || $::tcl_platform(platform) eq "os2"} {
  set testextension ./testloadext.dll
} else {
  set testextension ./libtestloadext.so
}
set gcc_shared "-shared -fPIC"
if {$::tcl_platform(os) eq "Darwin"} {
  set gcc_shared -dynamiclib
}

# The error messages tested by this file are operating system dependent
# (because they are returned by sqlite3OsDlError()). For now, they only
# work with UNIX (and probably only certain kinds of UNIX).
#
# When a shared-object cannot be opened because it does not exist, the
# format of the message returned is:
#
#      [format $dlerror_nosuchfile <shared-object-name>]
#
# When a shared-object cannot be opened because it consists of the 4
# characters "blah" only, we expect the error message to be:
#
#      [format $dlerror_notadll <shared-object-name>]
#
# When a symbol cannot be found within an open shared-object, the error
# message should be:
#
#      [format $dlerror_nosymbol <shared-object-name> <symbol-name>]
#
# The exact error messages are not important. The important bit is
# that SQLite is correctly copying the message from xDlError().
#
set dlerror_nosuchfile \
    {%s: cannot open shared object file: No such file or directory}
set dlerror_notadll    {%s: file too short}
set dlerror_nosymbol   {%s: undefined symbol: %s}

if {$::tcl_platform(os) eq "Darwin"} {
  set dlerror_nosuchfile {dlopen(%s, 10): image not found}
  set dlerror_notadll    {dlopen(%1$s, 10): no suitable image found.*}
  set dlerror_nosymbol   {dlsym(XXX, %2$s): symbol not found}
}

# Make sure the test extension actually exists.  If it does not
# exist, try to create it.  If unable to create it, then skip this
# test file.
#
if {![file exists $testextension]} {
  set srcdir [file dir $testdir]/src
  set testextsrc $srcdir/test_loadext.c

  set cmdline [concat exec gcc $gcc_shared]
  lappend cmdline -Wall -I$srcdir -I. -g $testextsrc -o $testextension
  
  if {[catch $cmdline msg]} {
    puts "Skipping loadext tests: Test extension not built..."
    puts $msg
    finish_test
    return
  }
}

# Test that loading the extension produces the expected results - adding
# the half() function to the specified database handle.
#
do_test loadext-1.1 {
  catchsql {
    SELECT half(1.0);
  }
} {1 {no such function: half}}
do_test loadext-1.2 {
  db enable_load_extension 1
  sqlite3_load_extension db $testextension testloadext_init
  catchsql {
    SELECT half(1.0);
  }
} {0 0.5}

# Test that a second database connection (db2) can load the extension also.
#
do_test loadext-1.3 {
  sqlite3 db2 test.db
  sqlite3_enable_load_extension db2 1
  catchsql {
    SELECT half(1.0);
  } db2
} {1 {no such function: half}}
do_test loadext-1.4 {
  sqlite3_load_extension db2 $testextension testloadext_init
  catchsql {
    SELECT half(1.0);
  } db2
} {0 0.5}

# Close the first database connection. Then check that the second database
# can still use the half() function without a problem.
#
do_test loadext-1.5 {
  db close
  catchsql {
    SELECT half(1.0);
  } db2
} {0 0.5}

db2 close
sqlite3 db test.db
sqlite3_enable_load_extension db 1

# Try to load an extension for which the file does not exist.
#
do_test loadext-2.1 {
  file delete -force ${testextension}xx
  set rc [catch {
    sqlite3_load_extension db "${testextension}xx"
  } msg]
  list $rc $msg
} [list 1 [format $dlerror_nosuchfile ${testextension}xx]]

# Try to load an extension for which the file is not a shared object
#
do_test loadext-2.2 {
  set fd [open "${testextension}xx" w]
  puts $fd blah
  close $fd
  set rc [catch {
    sqlite3_load_extension db "${testextension}xx"
  } msg]
  set expected_error_pattern [format $dlerror_notadll ${testextension}xx]
  list $rc [string match $expected_error_pattern $msg]
} [list 1 1]

# Try to load an extension for which the file is present but the
# entry point is not.
#
do_test loadext-2.3 {
  set rc [catch {
    sqlite3_load_extension db $testextension icecream
  } msg]
  if {$::tcl_platform(os) eq "Darwin"} {
    regsub {0x[1234567890abcdefABCDEF]*} $msg XXX msg
  }
  list $rc $msg
} [list 1 [format $dlerror_nosymbol $testextension icecream]]

# Try to load an extension for which the entry point fails (returns non-zero) 
#
do_test loadext-2.4 {
  set rc [catch {
    sqlite3_load_extension db $testextension testbrokenext_init
  } msg]
  list $rc $msg
} {1 {error during initialization: broken!}}

############################################################################
# Tests for the load_extension() SQL function
#

db close
sqlite3 db test.db
sqlite3_enable_load_extension db 1
do_test loadext-3.1 {
  catchsql {
    SELECT half(5);
  }
} {1 {no such function: half}}
do_test loadext-3.2 {
  set res [catchsql {
    SELECT load_extension($::testextension)
  }]
  if {$::tcl_platform(os) eq "Darwin"} {
    regsub {0x[1234567890abcdefABCDEF]*} $res XXX res
  }
  set res
} [list 1 [format $dlerror_nosymbol $testextension sqlite3_extension_init]]
do_test loadext-3.3 {
  catchsql {
    SELECT load_extension($::testextension,'testloadext_init')
  }
} {0 {{}}}
do_test loadext-3.4 {
  catchsql {
    SELECT half(5);
  }
} {0 2.5}
do_test loadext-3.5 {
  db eval {
    SELECT sqlite3_status('MEMORY_USED') AS mused
  } break
  puts -nonewline " (memory_used=$mused) "
  expr {$mused>0}
} {1}
do_test loadext-3.6 {
  catchsql {
    SELECT sqlite3_status('MEMORY_USED_X') AS mused
  }
} {1 {unknown status property: MEMORY_USED_X}}
do_test loadext-3.7 {
  catchsql {
    SELECT sqlite3_status(4.53) AS mused
  }
} {1 {unknown status type}}
do_test loadext-3.8 {
  catchsql {
    SELECT sqlite3_status(23) AS mused
  }
} {1 {sqlite3_status(23,...) returns 21}}

# Ticket #1863
# Make sure the extension loading mechanism will not work unless it
# is explicitly enabled.
#
db close
sqlite3 db test.db
do_test loadext-4.1 {
  catchsql {
    SELECT load_extension($::testextension,'testloadext_init')
  }
} {1 {not authorized}}
do_test loadext-4.2 {
  sqlite3_enable_load_extension db 1
  catchsql {
    SELECT load_extension($::testextension,'testloadext_init')
  }
} {0 {{}}}

do_test loadext-4.3 {
  sqlite3_enable_load_extension db 0
  catchsql {
    SELECT load_extension($::testextension,'testloadext_init')
  }
} {1 {not authorized}}

source $testdir/malloc_common.tcl


# Malloc failure in sqlite3_auto_extension and sqlite3_load_extension
#
do_malloc_test loadext-5 -tclprep {
  sqlite3_reset_auto_extension
} -tclbody {
  if {[autoinstall_test_functions]==7} {error "out of memory"}
}
do_malloc_test loadext-6 -tclbody {
  db enable_load_extension 1
  sqlite3_load_extension db $::testextension testloadext_init
}
autoinstall_test_functions

finish_test

Added test/loadext2.test.

































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# 2006 August 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is automatic extension loading and the
# sqlite3_auto_extension() API.
#
# $Id: loadext2.test,v 1.3 2008/03/19 16:08:54 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only run these tests if the approriate APIs are defined
# in the system under test.
#
ifcapable !load_ext {
  finish_test
  return
}
if {[info command sqlite3_auto_extension_sqr]==""} {
  finish_test
  return
}


# None of the extension are loaded by default.
#
do_test loadext2-1.1 {
  catchsql {
    SELECT sqr(2)
  }
} {1 {no such function: sqr}}
do_test loadext2-1.2 {
  catchsql {
    SELECT cube(2)
  }
} {1 {no such function: cube}}

# Register auto-loaders.  Still functions do not exist.
#
do_test loadext2-1.3 {
  sqlite3_auto_extension_sqr
  sqlite3_auto_extension_cube
  catchsql {
    SELECT sqr(2)
  }
} {1 {no such function: sqr}}
do_test loadext2-1.4 {
  catchsql {
    SELECT cube(2)
  }
} {1 {no such function: cube}}


# Functions do exist in a new database connection
#
do_test loadext2-1.5 {
  sqlite3 db test.db
  catchsql {
    SELECT sqr(2)
  }
} {0 4.0}
do_test loadext2-1.6 {
  catchsql {
    SELECT cube(2)
  }
} {0 8.0}


# Reset extension auto loading.  Existing extensions still exist.
#
do_test loadext2-1.7 {
  sqlite3_reset_auto_extension
  catchsql {
    SELECT sqr(2)
  }
} {0 4.0}
do_test loadext2-1.8 {
  catchsql {
    SELECT cube(2)
  }
} {0 8.0}


# Register only the sqr() function.
#
do_test loadext2-1.9 {
  sqlite3_auto_extension_sqr
  sqlite3 db test.db
  catchsql {
    SELECT sqr(2)
  }
} {0 4.0}
do_test loadext2-1.10 {
  catchsql {
    SELECT cube(2)
  }
} {1 {no such function: cube}}

# Register only the cube() function.
#
do_test loadext2-1.11 {
  sqlite3_reset_auto_extension
  sqlite3_auto_extension_cube
  sqlite3 db test.db
  catchsql {
    SELECT sqr(2)
  }
} {1 {no such function: sqr}}
do_test loadext2-1.12 {
  catchsql {
    SELECT cube(2)
  }
} {0 8.0}

# Register a broken entry point.
#
do_test loadext2-1.13 {
  sqlite3_auto_extension_broken
  set rc [catch {sqlite3 db test.db} errmsg]
  lappend rc $errmsg
} {1 {automatic extension loading failed: broken autoext!}}
do_test loadext2-1.14 {
  catchsql {
    SELECT sqr(2)
  }
} {1 {no such function: sqr}}
do_test loadext2-1.15 {
  catchsql {
    SELECT cube(2)
  }
} {0 8.0}


sqlite3_reset_auto_extension
autoinstall_test_functions
finish_test

Added test/lock.test.





















































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks.
#
# $Id: lock.test,v 1.40 2009/06/16 17:49:36 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create an alternative connection to the database
#
do_test lock-1.0 {
  # Give a complex pathname to stress the path simplification logic in
  # the vxworks driver and in test_async.
  file mkdir tempdir/t1/t2
  sqlite3 db2 ./tempdir/../tempdir/t1/.//t2/../../..//test.db
  set dummy {}
} {}
do_test lock-1.1 {
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test lock-1.2 {
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} db2
} {}
do_test lock-1.3 {
  execsql {CREATE TABLE t1(a int, b int)}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {t1}
do_test lock-1.5 {
  catchsql {
     SELECT name FROM sqlite_master WHERE type='table' ORDER BY name
  } db2
} {0 t1}

do_test lock-1.6 {
  execsql {INSERT INTO t1 VALUES(1,2)}
  execsql {SELECT * FROM t1}
} {1 2}
# Update: The schema is now brought up to date by test lock-1.5.
# do_test lock-1.7.1 {
#   catchsql {SELECT * FROM t1} db2
# } {1 {no such table: t1}}
do_test lock-1.7.2 {
  catchsql {SELECT * FROM t1} db2
} {0 {1 2}}
do_test lock-1.8 {
  execsql {UPDATE t1 SET a=b, b=a} db2
  execsql {SELECT * FROM t1} db2
} {2 1}
do_test lock-1.9 {
  execsql {SELECT * FROM t1}
} {2 1}
do_test lock-1.10 {
  execsql {BEGIN TRANSACTION}
  execsql {UPDATE t1 SET a = 0 WHERE 0}
  execsql {SELECT * FROM t1}
} {2 1}
do_test lock-1.11 {
  catchsql {SELECT * FROM t1} db2
} {0 {2 1}}
do_test lock-1.12 {
  execsql {ROLLBACK}
  catchsql {SELECT * FROM t1}
} {0 {2 1}}

do_test lock-1.13 {
  execsql {CREATE TABLE t2(x int, y int)}
  execsql {INSERT INTO t2 VALUES(8,9)}
  execsql {SELECT * FROM t2}
} {8 9}
do_test lock-1.14.1 {
  catchsql {SELECT * FROM t2} db2
} {0 {8 9}}
do_test lock-1.14.2 {
  catchsql {SELECT * FROM t1} db2
} {0 {2 1}}
do_test lock-1.15 {
  catchsql {SELECT * FROM t2} db2
} {0 {8 9}}

do_test lock-1.16 {
  db eval {SELECT * FROM t1} qv {
    set x [db eval {SELECT * FROM t1}]
  }
  set x
} {2 1}
do_test lock-1.17 {
  db eval {SELECT * FROM t1} qv {
    set x [db eval {SELECT * FROM t2}]
  }
  set x
} {8 9}

# You cannot UPDATE a table from within the callback of a SELECT
# on that same table because the SELECT has the table locked.
#
# 2006-08-16:  Reads no longer block writes within the same
# database connection.
#
#do_test lock-1.18 {
#  db eval {SELECT * FROM t1} qv {
#    set r [catch {db eval {UPDATE t1 SET a=b, b=a}} msg]
#    lappend r $msg
#  }
#  set r
#} {1 {database table is locked}}

# But you can UPDATE a different table from the one that is used in
# the SELECT.
#
do_test lock-1.19 {
  db eval {SELECT * FROM t1} qv {
    set r [catch {db eval {UPDATE t2 SET x=y, y=x}} msg]
    lappend r $msg
  }
  set r
} {0 {}}
do_test lock-1.20 {
  execsql {SELECT * FROM t2}
} {9 8}

# It is possible to do a SELECT of the same table within the
# callback of another SELECT on that same table because two
# or more read-only cursors can be open at once.
#
do_test lock-1.21 {
  db eval {SELECT * FROM t1} qv {
    set r [catch {db eval {SELECT a FROM t1}} msg]
    lappend r $msg
  }
  set r
} {0 2}

# Under UNIX you can do two SELECTs at once with different database
# connections, because UNIX supports reader/writer locks.  Under windows,
# this is not possible.
#
if {$::tcl_platform(platform)=="unix"} {
  do_test lock-1.22 {
    db eval {SELECT * FROM t1} qv {
      set r [catch {db2 eval {SELECT a FROM t1}} msg]
      lappend r $msg
    }
    set r
  } {0 2}
}
integrity_check lock-1.23

# If one thread has a transaction another thread cannot start
# a transaction.  -> Not true in version 3.0.  But if one thread
# as a RESERVED lock another thread cannot acquire one.
#
do_test lock-2.1 {
  execsql {BEGIN TRANSACTION}
  execsql {UPDATE t1 SET a = 0 WHERE 0}
  execsql {BEGIN TRANSACTION} db2
  set r [catch {execsql {UPDATE t1 SET a = 0 WHERE 0} db2} msg]
  execsql {ROLLBACK} db2
  lappend r $msg
} {1 {database is locked}}

# A thread can read when another has a RESERVED lock.
#
do_test lock-2.2 {
  catchsql {SELECT * FROM t2} db2
} {0 {9 8}}

# If the other thread (the one that does not hold the transaction with
# a RESERVED lock) tries to get a RESERVED lock, we do get a busy callback
# as long as we were not orginally holding a READ lock.
#
do_test lock-2.3.1 {
  proc callback {count} {
    set ::callback_value $count
    break
  }
  set ::callback_value {}
  db2 busy callback
  # db2 does not hold a lock so we should get a busy callback here
  set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg]
  lappend r $msg
  lappend r $::callback_value
} {1 {database is locked} 0}
do_test lock-2.3.2 {
  set ::callback_value {}
  execsql {BEGIN; SELECT rowid FROM sqlite_master LIMIT 1} db2
  # This time db2 does hold a read lock.  No busy callback this time.
  set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg]
  lappend r $msg
  lappend r $::callback_value
} {1 {database is locked} {}}
catch {execsql {ROLLBACK} db2}
do_test lock-2.4.1 {
  proc callback {count} {
    lappend ::callback_value $count
    if {$count>4} break
  }
  set ::callback_value {}
  db2 busy callback
  # We get a busy callback because db2 is not holding a lock
  set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg]
  lappend r $msg
  lappend r $::callback_value
} {1 {database is locked} {0 1 2 3 4 5}}
do_test lock-2.4.2 {
  proc callback {count} {
    lappend ::callback_value $count
    if {$count>4} break
  }
  set ::callback_value {}
  db2 busy callback
  execsql {BEGIN; SELECT rowid FROM sqlite_master LIMIT 1} db2
  # No busy callback this time because we are holding a lock
  set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg]
  lappend r $msg
  lappend r $::callback_value
} {1 {database is locked} {}}
catch {execsql {ROLLBACK} db2}
do_test lock-2.5 {
  proc callback {count} {
    lappend ::callback_value $count
    if {$count>4} break
  }
  set ::callback_value {}
  db2 busy callback
  set r [catch {execsql {SELECT * FROM t1} db2} msg]
  lappend r $msg
  lappend r $::callback_value
} {0 {2 1} {}}
execsql {ROLLBACK}

# Test the built-in busy timeout handler
#
do_test lock-2.8 {
  db2 timeout 400
  execsql BEGIN
  execsql {UPDATE t1 SET a = 0 WHERE 0}
  catchsql {BEGIN EXCLUSIVE;} db2
} {1 {database is locked}}
do_test lock-2.9 {
  db2 timeout 0
  execsql COMMIT
} {}
integrity_check lock-2.10

# Try to start two transactions in a row
#
do_test lock-3.1 {
  execsql {BEGIN TRANSACTION}
  set r [catch {execsql {BEGIN TRANSACTION}} msg]
  execsql {ROLLBACK}
  lappend r $msg
} {1 {cannot start a transaction within a transaction}}
integrity_check lock-3.2

# Make sure the busy handler and error messages work when
# opening a new pointer to the database while another pointer
# has the database locked.
#
do_test lock-4.1 {
  db2 close
  catch {db eval ROLLBACK}
  db eval BEGIN
  db eval {UPDATE t1 SET a=0 WHERE 0}
  sqlite3 db2 ./test.db
  catchsql {UPDATE t1 SET a=0} db2
} {1 {database is locked}}
do_test lock-4.2 {
  set ::callback_value {}
  set rc [catch {db2 eval {UPDATE t1 SET a=0}} msg]
  lappend rc $msg $::callback_value
} {1 {database is locked} {}}
do_test lock-4.3 {
  proc callback {count} {
    lappend ::callback_value $count
    if {$count>4} break
  }
  db2 busy callback
  set rc [catch {db2 eval {UPDATE t1 SET a=0}} msg]
  lappend rc $msg $::callback_value
} {1 {database is locked} {0 1 2 3 4 5}}
execsql {ROLLBACK}

# When one thread is writing, other threads cannot read.  Except if the
# writing thread is writing to its temporary tables, the other threads
# can still read.  -> Not so in 3.0.  One thread can read while another
# holds a RESERVED lock.
#
proc tx_exec {sql} {
  db2 eval $sql
}
do_test lock-5.1 {
  execsql {
    SELECT * FROM t1
  }
} {2 1}
do_test lock-5.2 {
  db function tx_exec tx_exec
  catchsql {
    INSERT INTO t1(a,b) SELECT 3, tx_exec('SELECT y FROM t2 LIMIT 1');
  }
} {0 {}}

ifcapable tempdb {
  do_test lock-5.3 {
    execsql {
      CREATE TEMP TABLE t3(x);
      SELECT * FROM t3;
    }
  } {}
  do_test lock-5.4 {
    catchsql {
      INSERT INTO t3 SELECT tx_exec('SELECT y FROM t2 LIMIT 1');
    }
  } {0 {}}
  do_test lock-5.5 {
    execsql {
      SELECT * FROM t3;
    }
  } {8}
  do_test lock-5.6 {
    catchsql {
      UPDATE t1 SET a=tx_exec('SELECT x FROM t2');
    }
  } {0 {}}
  do_test lock-5.7 {
    execsql {
      SELECT * FROM t1;
    }
  } {9 1 9 8}
  do_test lock-5.8 {
    catchsql {
      UPDATE t3 SET x=tx_exec('SELECT x FROM t2');
    }
  } {0 {}}
  do_test lock-5.9 {
    execsql {
      SELECT * FROM t3;
    }
  } {9}
}

do_test lock-6.1 {
  execsql {
    CREATE TABLE t4(a PRIMARY KEY, b);
    INSERT INTO t4 VALUES(1, 'one');
    INSERT INTO t4 VALUES(2, 'two');
    INSERT INTO t4 VALUES(3, 'three');
  }

  set STMT [sqlite3_prepare $DB "SELECT * FROM sqlite_master" -1 TAIL]
  sqlite3_step $STMT

  execsql { DELETE FROM t4 }
  execsql { SELECT * FROM sqlite_master } db2
  execsql { SELECT * FROM t4 } db2
} {}

do_test lock-6.2 {
  execsql { 
    BEGIN;
    INSERT INTO t4 VALUES(1, 'one');
    INSERT INTO t4 VALUES(2, 'two');
    INSERT INTO t4 VALUES(3, 'three');
    COMMIT;
  }

  execsql { SELECT * FROM t4 } db2
} {1 one 2 two 3 three}

do_test lock-6.3 {
  execsql { SELECT a FROM t4 ORDER BY a } db2
} {1 2 3}

do_test lock-6.4 {
  execsql { PRAGMA integrity_check } db2
} {ok}

do_test lock-6.5 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

# At one point the following set of conditions would cause SQLite to 
# retain a RESERVED or EXCLUSIVE lock after the transaction was committed:
# 
#   * The journal-mode is set to something other than 'delete', and
#   * there exists one or more active read-only statements, and
#   * a transaction that modified zero database pages is committed.
# 
set temp_status unlocked
if {$TEMP_STORE==3} {set temp_status unknown}
do_test lock-7.1 {
  set STMT [sqlite3_prepare $DB "SELECT * FROM sqlite_master" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test lock-7.2 {
  execsql { PRAGMA lock_status }
} [list main shared temp $temp_status]
do_test lock-7.3 {
  execsql {
    PRAGMA journal_mode = truncate;
    BEGIN;
    UPDATE t4 SET a = 10 WHERE 0;
    COMMIT;
  }
  execsql { PRAGMA lock_status }
} [list main shared temp $temp_status]
do_test lock-7.4 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

do_test lock-999.1 {
  rename db2 {}
} {}

finish_test

Added test/lock2.test.

























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks between competing processes.
#
# $Id: lock2.test,v 1.11 2009/05/01 10:55:34 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Launch another testfixture process to be controlled by this one. A
# channel name is returned that may be passed as the first argument to proc
# 'testfixture' to execute a command. The child testfixture process is shut
# down by closing the channel.
proc launch_testfixture {} {
  set prg [info nameofexec]
  if {$prg eq ""} {
    set prg [file join . testfixture]
  }
  set chan [open "|$prg tf_main.tcl" r+]
  fconfigure $chan -buffering line
  return $chan
}

# Execute a command in a child testfixture process, connected by two-way
# channel $chan. Return the result of the command, or an error message.
proc testfixture {chan cmd} {
  puts $chan $cmd
  puts $chan OVER
  set r ""
  while { 1 } {
    set line [gets $chan]
    if { $line == "OVER" } { 
      return $r
    }
    if {[eof $chan]} {
      return "ERROR: Child process hung up"
    }
    append r $line
  }
}

# Write the main loop for the child testfixture processes into file
# tf_main.tcl. The parent (this script) interacts with the child processes
# via a two way pipe. The parent writes a script to the stdin of the child
# process, followed by the word "OVER" on a line of its own. The child
# process evaluates the script and writes the results to stdout, followed
# by an "OVER" of its own.
set f [open tf_main.tcl w]
puts $f {
  set l [open log w]
  set script ""
  while {![eof stdin]} {
    flush stdout
    set line [gets stdin]
    puts $l "READ $line"
    if { $line == "OVER" } {
      catch {eval $script} result
      puts $result
      puts $l "WRITE $result"
      puts OVER
      puts $l "WRITE OVER"
      flush stdout
      set script ""
    } else {
      append script $line
      append script " ; "
    }
  }
  close $l
}
close $f

# Simple locking test case:
#
# lock2-1.1: Connect a second process to the database.
# lock2-1.2: Establish a RESERVED lock with this process.
# lock2-1.3: Get a SHARED lock with the second process.
# lock2-1.4: Try for a RESERVED lock with process 2. This fails.
# lock2-1.5: Try to upgrade the first process to EXCLUSIVE, this fails so
#            it gets PENDING.
# lock2-1.6: Release the SHARED lock held by the second process. 
# lock2-1.7: Attempt to reaquire a SHARED lock with the second process.
#            this fails due to the PENDING lock.
# lock2-1.8: Ensure the first process can now upgrade to EXCLUSIVE.
#
do_test lock2-1.1 {
  set ::tf1 [launch_testfixture]
  testfixture $::tf1 "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
  testfixture $::tf1 {
    sqlite3 db test.db -key xyzzy
    db eval {select * from sqlite_master}
  }
} {}
do_test lock2-1.1.1 {
  execsql {pragma lock_status}
} {main unlocked temp closed}
sqlite3_soft_heap_limit 0
do_test lock2-1.2 {
  execsql {
    BEGIN;
    CREATE TABLE abc(a, b, c);
  }
} {}
do_test lock2-1.3 {
  testfixture $::tf1 {
    db eval {
      BEGIN;
      SELECT * FROM sqlite_master;
    }
  }
} {}
do_test lock2-1.4 {
  testfixture $::tf1 {
    db eval {
      CREATE TABLE def(d, e, f)
    }
  }
} {database is locked}
do_test lock2-1.5 {
  catchsql {
    COMMIT;
  }
} {1 {database is locked}}
do_test lock2-1.6 {
  testfixture $::tf1 {
    db eval {
      SELECT * FROM sqlite_master;
      COMMIT;
    }
  }
} {}
do_test lock2-1.7 {
  testfixture $::tf1 {
    db eval {
      BEGIN;
      SELECT * FROM sqlite_master;
    }
  }
} {database is locked}
do_test lock2-1.8 {
  catchsql {
    COMMIT;
  }
} {0 {}}
do_test lock2-1.9 {
  execsql {
    SELECT * FROM sqlite_master;
  }
} "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}"
do_test lock2-1.10 {
  testfixture $::tf1 {
    db eval {
      SELECT * FROM sqlite_master;
    }
  }
} "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}"

catch {testfixture $::tf1 {db close}}
catch {close $::tf1}
sqlite3_soft_heap_limit $soft_limit

finish_test

Added test/lock3.test.































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks and the operation of the
# DEFERRED, IMMEDIATE, and EXCLUSIVE keywords as modifiers to the
# BEGIN command.
#
# $Id: lock3.test,v 1.4 2009/03/28 15:04:24 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Establish two connections to the same database.  Put some
# sample data into the database.
#
do_test lock3-1.1 {
  file mkdir tempdir/t1/t2/t3
  sqlite3 db2 ./tempdir/t1//t2/./t3//./../..//./../../tempdir/..//test.db//
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
  }
  execsql {
    SELECT * FROM t1
  } db2
} 1

# Get a deferred lock on the database using one connection.  The
# other connection should still be able to write.
#
do_test lock3-2.1 {
  execsql {BEGIN DEFERRED TRANSACTION}
  execsql {INSERT INTO t1 VALUES(2)} db2
  execsql {END TRANSACTION}
  execsql {SELECT * FROM t1}
} {1 2}

# Get an immediate lock on the database using one connection.  The
# other connection should be able to read the database but not write
# it.
#
do_test lock3-3.1 {
  execsql {BEGIN IMMEDIATE TRANSACTION}
  catchsql {SELECT * FROM t1} db2
} {0 {1 2}}
do_test lock3-3.2 {
  catchsql {INSERT INTO t1 VALUES(3)} db2
} {1 {database is locked}}
do_test lock3-3.3 {
  execsql {END TRANSACTION}
} {}


# Get an exclusive lock on the database using one connection.  The
# other connection should be unable to read or write the database.
#
do_test lock3-4.1 {
  execsql {BEGIN EXCLUSIVE TRANSACTION}
  catchsql {SELECT * FROM t1} db2
} {1 {database is locked}}
do_test lock3-4.2 {
  catchsql {INSERT INTO t1 VALUES(3)} db2
} {1 {database is locked}}
do_test lock3-4.3 {
  execsql {END TRANSACTION}
} {}

catch {db2 close}

finish_test

Added test/lock4.test.









































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# 2007 April 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks.
#
# $Id: lock4.test,v 1.10 2009/05/06 00:52:41 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Initialize the test.db database so that it is non-empty
#
do_test lock4-1.1 {
  db eval {
     PRAGMA auto_vacuum=OFF;
     CREATE TABLE t1(x);
  }
  file delete -force test2.db test2.db-journal
  sqlite3 db2 test2.db
  db2 eval {
     PRAGMA auto_vacuum=OFF;
     CREATE TABLE t2(x)
  }
  db2 close
  list [file size test.db] [file size test2.db]
} {2048 2048}

# Create a script to drive a separate process that will
#
#     1.  Create a second database test2.db
#     2.  Get an exclusive lock on test2.db
#     3.  Add an entry to test.db in table t1, waiting as necessary.
#     4.  Commit the change to test2.db.
#
# Meanwhile, this process will:
# 
#     A.  Get an exclusive lock on test.db
#     B.  Attempt to read from test2.db but get an SQLITE_BUSY error.
#     C.  Commit the changes to test.db thus alloing the other process
#         to continue.
#
do_test lock4-1.2 {
 
  # Create a script for the second process to run.
  #
  set out [open test2-script.tcl w]
  puts $out "sqlite3_test_control_pending_byte [set sqlite_pending_byte]"
  puts $out {
     sqlite3 db2 test2.db
     db2 eval {
        BEGIN;
        INSERT INTO t2 VALUES(2);
     }
     sqlite3 db test.db
     db timeout 1000000
     db eval {
        INSERT INTO t1 VALUES(2);
     }
     db close
     db2 eval COMMIT
     exit
  }
  close $out

  # Begin a transaction on test.db.
  db eval {
     BEGIN EXCLUSIVE;
     INSERT INTO t1 VALUES(1);
  }

  # Kick off the second process.
  exec [info nameofexec] ./test2-script.tcl &

  # Wait until the second process has started its transaction on test2.db.
  while {![file exists test2.db-journal]} {
    after 10
  }

  # Try to write to test2.db. We are locked out.
  sqlite3 db2 test2.db
  catchsql {
    INSERT INTO t2 VALUES(1)
  } db2
} {1 {database is locked}}
do_test lock4-1.3 {
  db eval {
     COMMIT;
  }
  while {[file exists test2.db-journal]} {
    after 10
  }
  # The other process has committed its transaction on test2.db by 
  # deleting the journal file. But it might retain the lock for a 
  # fraction longer 
  #
  after 25
  db2 eval {
     SELECT * FROM t2
  }
} {2}

    
do_test lock4-999.1 {
  rename db2 {}
} {}

finish_test

Added test/lock5.test.







































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# 2008 June 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks.
#
# $Id: lock5.test,v 1.6 2008/12/04 12:34:16 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# This file is only run if using the unix backend compiled with the
# SQLITE_ENABLE_LOCKING_STYLE macro.
db close
if {[catch {sqlite3 db test.db -vfs unix-none} msg]} {
  finish_test
  return
}
db close
file delete -force test.db.lock

ifcapable lock_proxy_pragmas {
  set ::using_proxy 0
  foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] {
    set ::using_proxy $value
  }
  # Disable the proxy locking for these tests
  set env(SQLITE_FORCE_PROXY_LOCKING) "0"
}


do_test lock5-dotfile.1 {
  sqlite3 db test.db -vfs unix-dotfile
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
  }
} {}

do_test lock5-dotfile.2 {
  file exists test.db.lock
} {1}

do_test lock5-dotfile.3 {
  execsql COMMIT
  file exists test.db.lock
} {0}

do_test lock5-dotfile.4 {
  sqlite3 db2 test.db -vfs unix-dotfile
  execsql {
    INSERT INTO t1 VALUES('a', 'b');
    SELECT * FROM t1;
  } db2
} {a b}

do_test lock5-dotfile.5 {
  execsql {
    BEGIN;
    SELECT * FROM t1;
  } db2
} {a b}

do_test lock5-dotfile.6 {
  file exists test.db.lock
} {1}

do_test lock5-dotfile.7 {
  catchsql { SELECT * FROM t1; }
} {1 {database is locked}}

do_test lock5-dotfile.8 {
  execsql {
    SELECT * FROM t1;
    ROLLBACK;
  } db2
} {a b}

do_test lock5-dotfile.9 {
  catchsql { SELECT * FROM t1; }
} {0 {a b}}

do_test lock5-dotfile.10 {
  file exists test.db.lock
} {0}

do_test lock5-dotfile.X {
  db2 close
  execsql {BEGIN EXCLUSIVE}
  db close
  file exists test.db.lock
} {0}

#####################################################################

file delete -force test.db
if {[catch {sqlite3 db test.db -vfs unix-flock} msg]} {
  finish_test
  return
}

do_test lock5-flock.1 {
  sqlite3 db test.db -vfs unix-flock
  execsql {
    CREATE TABLE t1(a, b);
    BEGIN;
    INSERT INTO t1 VALUES(1, 2);
  }
} {}

# Make sure we are not accidentally using the dotfile locking scheme.
do_test lock5-flock.2 {
  file exists test.db.lock
} {0}

do_test lock5-flock.3 {
  sqlite3 db2 test.db -vfs unix-flock
  catchsql { SELECT * FROM t1 } db2
} {1 {database is locked}}

do_test lock5-flock.4 {
  execsql COMMIT
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2}}

do_test lock5-flock.5 {
  execsql BEGIN
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2}}

do_test lock5-flock.6 {
  execsql {SELECT * FROM t1}
  catchsql { SELECT * FROM t1 } db2
} {1 {database is locked}}

do_test lock5-flock.7 {
  db close
  catchsql { SELECT * FROM t1 } db2
} {0 {1 2}}

do_test lock5-flock.8 {
  db2 close
} {}

#####################################################################

do_test lock5-none.1 {
  sqlite3 db test.db -vfs unix-none
  sqlite3 db2 test.db -vfs unix-none
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(3, 4);
  }
} {}
do_test lock5-none.2 {
  execsql { SELECT * FROM t1 }
} {1 2 3 4}
do_test lock5-flock.3 {
  execsql { SELECT * FROM t1 } db2
} {1 2}
do_test lock5-none.4 {
  execsql { 
    BEGIN;
    SELECT * FROM t1;
  } db2
} {1 2}
do_test lock5-none.5 {
  execsql COMMIT
  execsql {SELECT * FROM t1} db2
} {1 2}

ifcapable memorymanage {
  do_test lock5-none.6 {
    sqlite3_release_memory 1000000
    execsql {SELECT * FROM t1} db2
  } {1 2 3 4}
}

do_test lock5-flock.X {
  db close
  db2 close
} {}

ifcapable lock_proxy_pragmas {
  set env(SQLITE_FORCE_PROXY_LOCKING) $::using_proxy
}

finish_test

Added test/lock6.test.

















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# 2008 October 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks.
#
# $Id: lock6.test,v 1.3 2009/02/05 16:31:46 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Launch another testfixture process to be controlled by this one. A
# channel name is returned that may be passed as the first argument to proc
# 'testfixture' to execute a command. The child testfixture process is shut
# down by closing the channel.
proc launch_testfixture {} {
  set prg [info nameofexec]
  if {$prg eq ""} {
    set prg [file join . testfixture]
  }
  set chan [open "|$prg tf_main2.tcl" r+]
  fconfigure $chan -buffering line
  return $chan
}

# Execute a command in a child testfixture process, connected by two-way
# channel $chan. Return the result of the command, or an error message.
proc testfixture {chan cmd} {
  puts $chan $cmd
  puts $chan OVER
  set r ""
  while { 1 } {
    set line [gets $chan]
    if { $line == "OVER" } { 
      return $r
    }
    append r $line
  }
}

# Write the main loop for the child testfixture processes into file
# tf_main2.tcl. The parent (this script) interacts with the child processes
# via a two way pipe. The parent writes a script to the stdin of the child
# process, followed by the word "OVER" on a line of its own. The child
# process evaluates the script and writes the results to stdout, followed
# by an "OVER" of its own.
set f [open tf_main2.tcl w]
puts $f {
  set l [open log w]
  set script ""
  while {![eof stdin]} {
    flush stdout
    set line [gets stdin]
    puts $l "READ $line"
    if { $line == "OVER" } {
      catch {eval $script} result
      puts $result
      puts $l "WRITE $result"
      puts OVER
      puts $l "WRITE OVER"
      flush stdout
      set script ""
    } else {
      append script $line
      append script " ; "
    }
  }
  close $l
}
close $f


ifcapable lock_proxy_pragmas&&prefer_proxy_locking {
  set sqlite_hostid_num 1

  set using_proxy 0
  foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] {
    set using_proxy $value
  }

  # Test the lock_proxy_file pragmas.
  #
  set env(SQLITE_FORCE_PROXY_LOCKING) "1"

  do_test lock6-1.1 {
    set ::tf1 [launch_testfixture]
    testfixture $::tf1 "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
    testfixture $::tf1 {
      set sqlite_hostid_num 2    
      sqlite3 db test.db -key xyzzy
      set lockpath [db eval {
        PRAGMA lock_proxy_file=":auto:";
        select * from sqlite_master;
        PRAGMA lock_proxy_file;
      }]
      string match "*test.db:auto:" $lockpath
    }
  } {1}
  
  set sqlite_hostid_num 3   
  do_test lock6-1.2 {
    execsql {pragma lock_status}
  } {main unlocked temp closed}

  sqlite3_soft_heap_limit 0
  do_test lock6-1.3 {
    sqlite3 db test.db
    catchsql {
      select * from sqlite_master;
    } 
  } {1 {database is locked}}

  do_test lock6-1.4 {
    set lockpath [execsql {
      PRAGMA lock_proxy_file=":auto:";
      PRAGMA lock_proxy_file;
    } db]
    set lockpath
  } {{:auto: (not held)}}

  do_test lock6-1.4.1 {
    catchsql {
      PRAGMA lock_proxy_file="notmine";
      select * from sqlite_master;
    } db
  } {1 {database is locked}}

  do_test lock6-1.4.2 {
    execsql {
      PRAGMA lock_proxy_file;
    } db
  } {notmine}
    
  do_test lock6-1.5 {
    testfixture $::tf1 {
      db eval {
        BEGIN;
        SELECT * FROM sqlite_master;
      }
    }
  } {}

  catch {testfixture $::tf1 {db close}}

  do_test lock6-1.6 {
    execsql {
      PRAGMA lock_proxy_file="mine";
      select * from sqlite_master;
    } db
  } {}
  
  catch {close $::tf1}
  set env(SQLITE_FORCE_PROXY_LOCKING) $using_proxy
  set sqlite_hostid_num 0

  sqlite3_soft_heap_limit $soft_limit

}
      
finish_test

Added test/lock7.test.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 2009 August 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Check that reading the database schema from within an active transaction
# does not establish a SHARED lock on the database file if one is not
# already held (or, more accurately, that the SHARED lock is released after
# reading the database schema).
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test lock7-1.1 {
  execsql { CREATE TABLE t1(a, b) }
  db close

  sqlite3 db1 test.db
  sqlite3 db2 test.db

  db1 eval {BEGIN}
  db2 eval {BEGIN}
} {}

do_test lock7-1.2 {
  execsql { PRAGMA lock_status } db1
} {main unlocked temp closed}
do_test lock7-1.3 {
  execsql { PRAGMA lock_status } db2
} {main unlocked temp closed}

do_test lock7-1.4 {
  catchsql { INSERT INTO t1 VALUES(1, 1) } db1
} {0 {}}
do_test lock7-1.5 {
  catchsql { INSERT INTO t1 VALUES(2, 2) } db2
} {1 {database is locked}}

do_test lock7-1.6 {
  execsql { PRAGMA lock_status } db1
} {main reserved temp closed}
do_test lock7-1.7 {
  execsql { PRAGMA lock_status } db2
} {main unlocked temp closed}

do_test lock7-1.8 {
  execsql { COMMIT } db1
} {}

db1 close
db2 close

finish_test

Added test/lookaside.test.





























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# 2008 August 01
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests for the lookaside memory allocator.
#
# $Id: lookaside.test,v 1.10 2009/04/09 01:23:49 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !lookaside {
  finish_test
  return
}

catch {db close}
sqlite3_shutdown
sqlite3_config_pagecache 0 0
sqlite3_config_scratch 0 0
sqlite3_initialize
autoinstall_test_functions
sqlite3 db test.db

# Make sure sqlite3_db_config() and sqlite3_db_status are working.
#
do_test lookaside-1.1 {
  catch {sqlite3_config_error db}
} {0}
do_test lookaside-1.2 {
  sqlite3_db_config_lookaside db 1 18 18
} {0}
do_test lookaside-1.3 {
  sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 0
} {0 0 0}
do_test lookaside-1.4 {
  db eval {CREATE TABLE t1(w,x,y,z);}
  foreach {x y z} [sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 0] break
  expr {$x==0 && $y<$z && $z==18}
} {0}
do_test lookaside-1.5 {
  foreach {x y z} [sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 1] break
  expr {$x==0 && $y<$z && $z==18}
} {0}
do_test lookaside-1.6 {
  foreach {x y z} [sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 0] break
  expr {$x==0 && $y==$z && $y<18}
} {1}
do_test lookaside-1.7 {
  db cache flush
  foreach {x y z} [sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 0] break
  expr {$x==0 && $y==0 && $z<18}
} {1}
do_test lookaside-1.8 {
  db cache flush
  foreach {x y z} [sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 1] break
  expr {$x==0 && $y==0 && $z<18}
} {1}
do_test lookaside-1.9 {
  db cache flush
  sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 0
} {0 0 0}

do_test lookaside-2.1 {
  sqlite3_db_config_lookaside db 0 100 1000
} {0}
do_test lookaside-2.2 {
  db eval {CREATE TABLE t2(x);}
  foreach {x y z} [sqlite3_db_status db SQLITE_DBSTATUS_LOOKASIDE_USED 0] break
  expr {$x==0 && $y<$z && $z>10 && $z<100}
} {1}
do_test lookaside-2.3 {
  sqlite3_db_config_lookaside db 0 50 50
} {5}  ;# SQLITE_BUSY
do_test lookaside-2.4 {
  db cache flush
  sqlite3_db_config_lookaside db 0 50 50
} {0}  ;# SQLITE_OK
do_test lookaside-2.5 {
  sqlite3_db_config_lookaside db 0 -1 50
} {0}  ;# SQLITE_OK
do_test lookaside-2.6 {
  sqlite3_db_config_lookaside db 0 50 -1
} {0}  ;# SQLITE_OK

# sqlite3_db_status() with an invalid verb returns an error.
#
do_test lookaside-3.1 {
  sqlite3_db_status db 99999 0
} {1 0 0}

# Test that an invalid verb on sqlite3_config() is detected and
# reported as an error.
#
do_test lookaside-4.1 {
  db close
  sqlite3_shutdown
  catch sqlite3_config_error
} {0}
sqlite3_initialize
autoinstall_test_functions

finish_test

Added test/main.test.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is exercising the code in main.c.
#
# $Id: main.test,v 1.32 2009/04/28 04:51:29 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only do the next group of tests if the sqlite3_complete API is available
#
ifcapable {complete} {

# Tests of the sqlite_complete() function.
#
do_test main-1.1 {
  db complete {This is a test}
} {0}
do_test main-1.2 {
  db complete {
  }
} {1}
do_test main-1.3 {
  db complete {
     -- a comment ;
  }
} {1}
do_test main-1.4 {
  db complete {
     -- a comment ;
     ;
  }
} {1}
do_test main-1.5 {
  db complete {DROP TABLE 'xyz;}
} {0}
do_test main-1.6 {
  db complete {DROP TABLE 'xyz';}
} {1}
do_test main-1.7 {
  db complete {DROP TABLE "xyz;}
} {0}
do_test main-1.8 {
  db complete {DROP TABLE "xyz';}
} {0}
do_test main-1.9 {
  db complete {DROP TABLE "xyz";}
} {1}
do_test main-1.10 {
  db complete {DROP TABLE xyz; hi}
} {0}
do_test main-1.11 {
  db complete {DROP TABLE xyz; }
} {1}
do_test main-1.12 {
  db complete {DROP TABLE xyz; -- hi }
} {1}
do_test main-1.13 {
  db complete {DROP TABLE xyz; -- hi
  }
} {1}
do_test main-1.14 {
  db complete {SELECT a-b FROM t1; }
} {1}
do_test main-1.15 {
  db complete {SELECT a/e FROM t1 }
} {0}
do_test main-1.16 {
  db complete {
    CREATE TABLE abc(x,y);
  }
} {1}
ifcapable {trigger} {
  do_test main-1.17 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr;
    }
  } {0}
  do_test main-1.17.2 {
    db complete {
      EXPLAIN CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr;
    }
  } {0}
  do_test main-1.17.3 {
    db complete {
      EXPLAIN QUERY PLAN CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr;
    }
  } {0}
  do_test main-1.18 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr; END;
    }
  } {1}
  do_test main-1.19 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE abc BEGIN
         UPDATE pqr;
         unknown command;
    }
  } {0}
  do_test main-1.20 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE backend BEGIN
         UPDATE pqr;
    }
  } {0}
  do_test main-1.21 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE end BEGIN
         SELECT a, b FROM end;
    }
  } {0}
  do_test main-1.22 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE end BEGIN
         SELECT a, b FROM end;
      END;
    }
  } {1}
  do_test main-1.23 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE end BEGIN
         SELECT a, b FROM end;
      END;
      SELECT a, b FROM end;
    }
  } {1}
  do_test main-1.24 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE [;end;] BEGIN
         UPDATE pqr;
    }
  } {0}
  do_test main-1.25 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE backend BEGIN
         UPDATE cantor SET a=[;end;];;;
    }
  } {0}
  do_test main-1.26 {
    db complete {
      CREATE -- a comment
      TRIGGER exy AFTER DELETE backend BEGIN
         UPDATE pqr SET a=5;
    }
  } {0}
  do_test main-1.27.1 {
    db complete {
      CREATE -- a comment
      TRIGGERX tangentxx AFTER DELETE backend BEGIN
         UPDATE pqr SET a=5;
    }
  } {1}
  do_test main-1.27.2 {
    db complete {
      CREATE/**/TRIGGER tiger00 AFTER DELETE backend BEGIN
         UPDATE pqr SET a=5;
    }
  } {0}
  ifcapable {explain} {
    do_test main-1.27.3 {
      db complete {
        /* */ EXPLAIN -- A comment
        CREATE/**/TRIGGER ezxyz12 AFTER DELETE backend BEGIN
           UPDATE pqr SET a=5;
      }
    } {0}
  }
  do_test main-1.27.4 {
    db complete {
      BOGUS token
      CREATE  TRIGGER xyz AFTER DELETE backend BEGIN
         UPDATE pqr SET a=5;
    }
  } {1}
  ifcapable {explain} {
    do_test main-1.27.5 {
      db complete {
        EXPLAIN 
        CREATE TEMP TRIGGER xyz AFTER DELETE backend BEGIN
           UPDATE pqr SET a=5;
      }
    } {0}
  }
  do_test main-1.28 {
    db complete {
      CREATE TEMPORARY TRIGGER xyz AFTER DELETE backend BEGIN
         UPDATE pqr SET a=5;
    }
  } {0}
  do_test main-1.29 {
    db complete {
      CREATE TRIGGER xyz AFTER DELETE backend BEGIN
         UPDATE pqr SET a=5;
         EXPLAIN select * from xyz;
    }
  } {0}

} ;# end ifcapable {complete}

}
do_test main-1.30 {
  db complete {
     CREATE TABLE /* In comment ; */
  }
} {0}
do_test main-1.31 {
  db complete {
     CREATE TABLE /* In comment ; */ hi;
  }
} {1}
do_test main-1.31 {
  db complete {
     CREATE TABLE /* In comment ; */;
  }
} {1}
do_test main-1.32 {
  db complete {
     stuff;
     /*
       CREATE TABLE
       multiple lines
       of text
     */
  }
} {1}
do_test main-1.33 {
  db complete {
     /*
       CREATE TABLE
       multiple lines
       of text;
  }
} {0}
do_test main-1.34 {
  db complete {
     /*
       CREATE TABLE
       multiple lines "*/
       of text;
  }
} {1}
do_test main-1.35 {
  db complete {hi /**/ there;}
} {1}
do_test main-1.36 {
  db complete {hi there/***/;}
} {1}
do_test main-1.37 {
  db complete {hi there/**}
} {0}
do_test main-1.38 {
  db complete {hi [there}
} {0}

ifcapable {trigger} {
  # Characters less than \040 can never be part of an identifier.
  # Characters greater than \u177 are always identifier characters.
  do_test main-1.100 {
    db complete "create \037\036\035\034trigger\001\002;"
  } {1}
  do_test main-1.101 {
    db complete "create trigger\200;"
  } {1}
  do_test main-1.102 {
    db complete "create \200trigger;"
  } {1}
}


# Try to open a database with a corrupt database file.
#
do_test main-2.0 {
  catch {db close}
  file delete -force test.db
  set fd [open test.db w]
  puts $fd hi!
  close $fd
  set v [catch {sqlite3 db test.db} msg]
  if {$v} {lappend v $msg} {lappend v {}}
} {0 {}}

# Here are some tests for tokenize.c.  
#
do_test main-3.1 {
  catch {db close}
  foreach f [glob -nocomplain testdb/*] {file delete -force $f}
  file delete -force testdb
  sqlite3 db testdb
  set v [catch {execsql {SELECT * from T1 where x!!5}} msg]
  lappend v $msg
} {1 {unrecognized token: "!!"}}
do_test main-3.2 {
  catch {db close}
  foreach f [glob -nocomplain testdb/*] {file delete -force $f}
  file delete -force testdb
  sqlite3 db testdb
  set v [catch {execsql {SELECT * from T1 where ^x}} msg]
  lappend v $msg
} {1 {unrecognized token: "^"}}
do_test main-3.2.2 {
  catchsql {select 'abc}
} {1 {unrecognized token: "'abc"}}
do_test main-3.2.3 {
  catchsql {select "abc}
} {1 {unrecognized token: ""abc"}}
do_test main-3.2.4 {
  catchsql {select [abc}
} {1 {unrecognized token: "[abc"}}
do_test main-3.2.5 {
  catchsql {select x'4869}
} {1 {unrecognized token: "x'4869"}}
do_test main-3.2.6 {
  catchsql {select x'4869'}
} {0 Hi}
do_test main-3.2.7 {
  catchsql {select x'48695'}
} {1 {unrecognized token: "x'48695'"}}
do_test main-3.2.8 {
  catchsql {select x'486x'}
} {1 {unrecognized token: "x'486x'"}}
do_test main-3.2.9 {
  catchsql {select $abc(}
} {1 {unrecognized token: "$abc("}}
do_test main-3.2.10 {
  catchsql {select $abc(x}
} {1 {unrecognized token: "$abc(x"}}
set xyz 123
do_test main-3.2.11 {
  catchsql {select $::xyz}
} {0 123}
namespace eval ::testnamespace {
  variable xyz 321
}
do_test main-3.2.12 {
  catchsql {select $testnamespace::xyz}
} {0 321}
do_test main-3.2.13 {
  catchsql {select $(abc)}
} {1 {unrecognized token: "$"}}
do_test main-3.2.14 {
  set hi\u1234x 987
  db eval "select \$hi\u1234x"
} {987}
do_test main-3.2.15 {
  catchsql "select 456\u1234"
} [list 1 "unrecognized token: \"456\u1234\""]
do_test main-3.2.16 {
  catchsql {select cast(3.14e+4 AS integer)}
} {0 31400}
do_test main-3.2.17 {
  catchsql {select cast(3.14e+04 AS integer)}
} {0 31400}
do_test main-3.2.18 {
  catchsql {select cast(3.14e+004 AS integer)}
} {0 31400}
do_test main-3.2.19 {
  catchsql {select cast(3.14e4 AS integer)}
} {0 31400}
do_test main-3.2.20 {
  catchsql {select cast(3.14e04 AS integer)}
} {0 31400}
do_test main-3.2.21 {
  catchsql {select cast(3.14e004 AS integer)}
} {0 31400}
do_test main-3.2.16 {
  catchsql {select cast(3.14E+4 AS integer)}
} {0 31400}
do_test main-3.2.17 {
  catchsql {select cast(3.14E+04 AS integer)}
} {0 31400}
do_test main-3.2.18 {
  catchsql {select cast(3.14E+004 AS integer)}
} {0 31400}
do_test main-3.2.19 {
  catchsql {select cast(3.14E4 AS integer)}
} {0 31400}
do_test main-3.2.20 {
  catchsql {select cast(3.14E04 AS integer)}
} {0 31400}
do_test main-3.2.21 {
  catchsql {select cast(3.14E004 AS integer)}
} {0 31400}
do_test main-3.2.22 {
  catchsql {select cast(3.14e-4 * 1e8 AS integer)}
} {0 31400}
do_test main-3.2.23 {
  catchsql {select cast(3.14E-04 * 1E08 AS integer)}
} {0 31400}
do_test main-3.2.24 {
  catchsql {select cast(3.14e-004 * 01.0E+8 AS integer)}
} {0 31400}
do_test main-3.2.25 {
  catchsql {select 123/*abc}
} {0 123}
do_test main-3.2.26 {
  catchsql {select 123/***abc}
} {0 123}
do_test main-3.2.27 {
  catchsql {select 123/*/*2}
} {0 123}
do_test main-3.2.28 {
  catchsql {select 123/**/*2}
} {0 246}
do_test main-3.2.29 {
  catchsql {select 123/}
} {1 {near "/": syntax error}}
do_test main-3.2.30 {
  catchsql {select 123--5}
} {0 123}


do_test main-3.3 {
  catch {db close}
  foreach f [glob -nocomplain testdb/*] {file delete -force $f}
  file delete -force testdb
  sqlite3 db testdb
  execsql {
    create table T1(X REAL);  /* C-style comments allowed */
    insert into T1 values(0.5);
    insert into T1 values(0.5e2);
    insert into T1 values(0.5e-002);
    insert into T1 values(5e-002);
    insert into T1 values(-5.0e-2);
    insert into T1 values(-5.1e-2);
    insert into T1 values(0.5e2);
    insert into T1 values(0.5E+02);
    insert into T1 values(5E+02);
    insert into T1 values(5.0E+03);
    select x*10 from T1 order by x*5;
  }
} {-0.51 -0.5 0.05 0.5 5.0 500.0 500.0 500.0 5000.0 50000.0}
do_test main-3.4 {
  set v [catch {execsql {create bogus}} msg]
  lappend v $msg
} {1 {near "bogus": syntax error}}
do_test main-3.5 {
  set v [catch {execsql {create}} msg]
  lappend v $msg
} {1 {near "create": syntax error}}
do_test main-3.6 {
  catchsql {SELECT 'abc' + #9}
} {1 {near "#9": syntax error}}

# The following test-case tests the linked list code used to manage
# sqlite3_vfs structures.
if {$::tcl_platform(platform)=="unix" 
     && [info command sqlite3async_initialize]!=""} {
  ifcapable threadsafe {
    do_test main-4.1 {
      sqlite3_crash_enable 1
      sqlite3_crash_enable 0
    
      sqlite3async_initialize "" 1
      sqlite3async_shutdown
    
      sqlite3_crash_enable 1
      sqlite3async_initialize "" 1
      sqlite3_crash_enable 0
      sqlite3async_shutdown
    
      sqlite3_crash_enable 1
      sqlite3async_initialize "" 1
      sqlite3async_shutdown
      sqlite3_crash_enable 0
    
      sqlite3async_initialize "" 1
      sqlite3_crash_enable 1
      sqlite3_crash_enable 0
      sqlite3async_shutdown
    
      sqlite3async_initialize "" 1
      sqlite3_crash_enable 1
      sqlite3async_shutdown
      sqlite3_crash_enable 0
    } {}
    do_test main-4.2 {
      set rc [catch {sqlite3 db test.db -vfs crash} msg]
      list $rc $msg
    } {1 {no such vfs: crash}}
    do_test main-4.3 {
      set rc [catch {sqlite3 db test.db -vfs async} msg]
      list $rc $msg
    } {1 {no such vfs: async}}
  }
}
    
finish_test

Added test/make-where7.tcl.

















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/tclsh
#
# Run this script to generate randomized test cases for the where7.test
# script.  The output will need to be manually copied and pasted into
# the where7.test script.
#
puts "do_test where7-2.1 \173"
puts "  db eval \173"
puts "    CREATE TABLE t2(a INTEGER PRIMARY KEY,b,c,d,e,f,g);"
set NA 100
for {set a 1} {$a<=$NA} {incr a} {
  set b [expr {$a*11}]
  set div3 [expr {int(($a+2)/3)}]
  set c [expr {$div3*1001}]
  set d [expr {$a*1.001}]
  set e [expr {$div3*100.1}]
  set x [expr {$a%26}]
  set f [string range {abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz} \
           $x [expr {$x+8}]]
  set div5 [expr {int(($a+7)/5)}]
  set x [expr {$div5%26}]
  set g [string range {zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba} \
           $x [expr {$x+6}]]
  puts "    INSERT INTO t2 VALUES($a,$b,$c,$d,$e,'$f','$g');"
  lappend fidx($f) $a
  lappend gidx($g) $a
  set gof($a) $g
  set fof($a) $f

  set expr "a=$a"
  set term($expr) $a
  set expr "((a BETWEEN [expr {$a-1}] AND [expr {$a+1}]) AND a!=$a)"
  set x {}
  if {$a>1} {set x [expr {$a-1}]}
  if {$a<$NA} {lappend x [expr {$a+1}]}
  set term($expr) $x
  set expr "b=$b"
  set term($expr) $a
  set expr "b=[expr {$a*11+3}]"
  set term($expr) {}
  set expr "c=$c"
  lappend term($expr) $a
  set expr "(d>=$a.0 AND d<[expr {$a+1.0}] AND d NOT NULL)"
  lappend term($expr) $a
  set expr "f='$f'"
  lappend term($expr) $a
  set expr \
     "(f GLOB '?[string range $f 1 4]*' AND f GLOB '[string range $f 0 3]*')"
  lappend term($expr) $a
  set expr "(g='$g' AND f GLOB '[string range $f 0 4]*')"
  lappend term($expr) $a
}
puts "    CREATE INDEX t2b ON t2(b);"
puts "    CREATE INDEX t2c ON t2(c);"
puts "    CREATE INDEX t2d ON t2(d);"
puts "    CREATE INDEX t2e ON t2(e);"
puts "    CREATE INDEX t2f ON t2(f);"
puts "    CREATE INDEX t2g ON t2(g);"
puts "    CREATE TABLE t3(a INTEGER PRIMARY KEY,b,c,d,e,f,g);"
puts "    INSERT INTO t3 SELECT * FROM t2;"
puts "    CREATE INDEX t3b ON t3(b,c);"
puts "    CREATE INDEX t3c ON t3(c,e);"
puts "    CREATE INDEX t3d ON t3(d,g);"
puts "    CREATE INDEX t3e ON t3(e,f,g);"
puts "    CREATE INDEX t3f ON t3(f,b,d,c);"
puts "    CREATE INDEX t3g ON t3(g,f);"

puts "  \175"
puts "\175 {}"

set term(b<0) {}
set term(1000000<b) {}
set term(c<=10) {}
set term(c>=[expr {int(($NA+2)/3)*1001+1}]) {}
set term(d<0.0) {}
set term(d>1e10) {}
set expr {e IS NULL}
set term($expr) {}
set expr {f IS NULL}
set term($expr) {}
set expr {g IS NULL}
set term($expr) {}

set NT 1000
set termlist [array names term]
set nterm [llength $termlist]
for {set i 2} {$i<=$NT+1} {incr i} {
  set n [expr {int(rand()*10)+2}]
  set w {}
  unset -nocomplain r
  for {set j 0} {$j<$n} {incr j} {
    set k [expr {int(rand()*$nterm)}]
    set t [lindex $termlist $k]
    lappend w $t
    foreach a $term($t) {
      set r($a) 1
    }
  }
  if {[info exists seen($w)]} {
    incr i -1
    continue
  }
  set seen($w) 1
  set result [lsort -int [array names r]]
  puts "do_test where7-2.$i.1 \173"
  puts "  count_steps_sort \173"
  puts "     SELECT a FROM t2"
  set wc [join $w "\n         OR "]
  puts "      WHERE $wc"
  puts "  \175"
  puts "\175 {$result scan 0 sort 0}"
  puts "do_test where7-2.$i.2 \173"
  puts "  count_steps_sort \173"
  puts "     SELECT a FROM t3"
  set wc [join $w "\n         OR "]
  puts "      WHERE $wc"
  puts "  \175"
  puts "\175 {$result scan 0 sort 0}"
}
puts "finish_test"

Added test/malloc.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file attempts to check the behavior of the SQLite library in 
# an out-of-memory situation. When compiled with -DSQLITE_DEBUG=1, 
# the SQLite library accepts a special command (sqlite3_memdebug_fail N C)
# which causes the N-th malloc to fail.  This special feature is used
# to see what happens in the library if a malloc were to really fail
# due to an out-of-memory situation.
#
# $Id: malloc.test,v 1.81 2009/06/24 13:13:45 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Only run these tests if memory debugging is turned on.
#
source $testdir/malloc_common.tcl
if {!$MEMDEBUG} {
   puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

# Do a couple of memory dumps just to exercise the memory dump logic
# that that we can say that we have.
#
puts stderr "This is a test.  Ignore the error that follows:"
sqlite3_memdebug_dump $testdir
puts "Memory dump to file memdump.txt..."
sqlite3_memdebug_dump memdump.txt

ifcapable bloblit&&subquery {
  do_malloc_test 1 -tclprep {
    db close
  } -tclbody {
    if {[catch {sqlite3 db test.db}]} {
      error "out of memory"
    }
    sqlite3_extended_result_codes db 1
  } -sqlbody {
    DROP TABLE IF EXISTS t1;
    CREATE TABLE t1(
       a int, b float, c double, d text, e varchar(20),
       primary key(a,b,c)
    );
    CREATE INDEX i1 ON t1(a,b);
    INSERT INTO t1 VALUES(1,2.3,4.5,'hi',x'746865726500');
    INSERT INTO t1 VALUES(6,7.0,0.8,'hello','out yonder');
    SELECT * FROM t1;
    SELECT avg(b) FROM t1 GROUP BY a HAVING b>20.0;
    DELETE FROM t1 WHERE a IN (SELECT min(a) FROM t1);
    SELECT count(*), group_concat(e) FROM t1;
    SELECT b FROM t1 ORDER BY 1 COLLATE nocase;
  } 
}

# Ensure that no file descriptors were leaked.
do_test malloc-1.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

ifcapable subquery {
  do_malloc_test 2 -sqlbody {
    CREATE TABLE t1(a int, b int default 'abc', c int default 1);
    CREATE INDEX i1 ON t1(a,b);
    INSERT INTO t1 VALUES(1,1,'99 abcdefghijklmnopqrstuvwxyz');
    INSERT INTO t1 VALUES(2,4,'98 abcdefghijklmnopqrstuvwxyz');
    INSERT INTO t1 VALUES(3,9,'97 abcdefghijklmnopqrstuvwxyz');
    INSERT INTO t1 VALUES(4,16,'96 abcdefghijklmnopqrstuvwxyz');
    INSERT INTO t1 VALUES(5,25,'95 abcdefghijklmnopqrstuvwxyz');
    INSERT INTO t1 VALUES(6,36,'94 abcdefghijklmnopqrstuvwxyz');
    SELECT 'stuff', count(*) as 'other stuff', max(a+10) FROM t1;
    UPDATE t1 SET b=b||b||b||b;
    UPDATE t1 SET b=a WHERE a in (10,12,22);
    INSERT INTO t1(c,b,a) VALUES(20,10,5);
    INSERT INTO t1 SELECT * FROM t1
        WHERE a IN (SELECT a FROM t1 WHERE a<10);
    DELETE FROM t1 WHERE a>=10;
    DROP INDEX i1;
    DELETE FROM t1;
  } 
}

# Ensure that no file descriptors were leaked.
do_test malloc-2.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

do_malloc_test 3 -sqlbody {
  BEGIN TRANSACTION;
  CREATE TABLE t1(a int, b int, c int);
  CREATE INDEX i1 ON t1(a,b);
  INSERT INTO t1 VALUES(1,1,99);
  INSERT INTO t1 VALUES(2,4,98);
  INSERT INTO t1 VALUES(3,9,97);
  INSERT INTO t1 VALUES(4,16,96);
  INSERT INTO t1 VALUES(5,25,95);
  INSERT INTO t1 VALUES(6,36,94);
  INSERT INTO t1(c,b,a) VALUES(20,10,5);
  DELETE FROM t1 WHERE a>=10;
  DROP INDEX i1;
  DELETE FROM t1;
  ROLLBACK;
} 


# Ensure that no file descriptors were leaked.
do_test malloc-3.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

ifcapable subquery {
  do_malloc_test 4 -sqlbody {
    BEGIN TRANSACTION;
    CREATE TABLE t1(a int, b int, c int);
    CREATE INDEX i1 ON t1(a,b);
    INSERT INTO t1 VALUES(1,1,99);
    INSERT INTO t1 VALUES(2,4,98);
    INSERT INTO t1 VALUES(3,9,97);
    INSERT INTO t1 VALUES(4,16,96);
    INSERT INTO t1 VALUES(5,25,95);
    INSERT INTO t1 VALUES(6,36,94);
    UPDATE t1 SET b=a WHERE a in (10,12,22);
    INSERT INTO t1 SELECT * FROM t1
       WHERE a IN (SELECT a FROM t1 WHERE a<10);
    DROP INDEX i1;
    DELETE FROM t1;
    COMMIT;
  } 
}

# Ensure that no file descriptors were leaked.
do_test malloc-4.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

ifcapable trigger {
  do_malloc_test 5 -sqlbody {
    BEGIN TRANSACTION;
    CREATE TABLE t1(a,b);
    CREATE TABLE t2(x,y);
    CREATE TRIGGER r1 AFTER INSERT ON t1 WHEN new.a = 2 BEGIN
      INSERT INTO t2(x,y) VALUES(new.rowid,1);
      INSERT INTO t2(x,y) SELECT * FROM t2;
      INSERT INTO t2 SELECT * FROM t2;
      UPDATE t2 SET y=y+1 WHERE x=new.rowid;
      SELECT 123;
      DELETE FROM t2 WHERE x=new.rowid;
    END;
    INSERT INTO t1(a,b) VALUES(2,3);
    COMMIT;
  } 
}

# Ensure that no file descriptors were leaked.
do_test malloc-5.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

ifcapable vacuum {
  do_malloc_test 6 -sqlprep {
    BEGIN TRANSACTION;
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    INSERT INTO t1 SELECT a*2 FROM t1;
    DELETE FROM t1 where rowid%5 = 0;
    COMMIT;
  } -sqlbody {
    VACUUM;
  } 
}

autoinstall_test_functions
do_malloc_test 7 -sqlprep {
  CREATE TABLE t1(a, b);
  INSERT INTO t1 VALUES(1, 2);
  INSERT INTO t1 VALUES(3, 4);
  INSERT INTO t1 VALUES(5, 6);
  INSERT INTO t1 VALUES(7, randstr(1200,1200));
} -sqlbody {
  SELECT min(a) FROM t1 WHERE a<6 GROUP BY b;
  SELECT a FROM t1 WHERE a<6 ORDER BY a;
  SELECT b FROM t1 WHERE a>6;
}

# This block is designed to test that some malloc failures that may
# occur in vdbeapi.c. Specifically, if a malloc failure that occurs
# when converting UTF-16 text to integers and real numbers is handled
# correctly. 
#
# This is done by retrieving a string from the database engine and
# manipulating it using the sqlite3_column_*** APIs. This doesn't 
# actually return an error to the user when a malloc() fails.. That 
# could be viewed as a bug.
#
# These tests only run if UTF-16 support is compiled in.
#
ifcapable utf16 {
  set ::STMT {}
  do_malloc_test 8 -tclprep {
    set sql "SELECT '[string repeat abc 20]', '[string repeat def 20]', ?"
    set ::STMT [sqlite3_prepare db $sql -1 X]
    sqlite3_step $::STMT
    if { $::tcl_platform(byteOrder)=="littleEndian" } {
      set ::bomstr "\xFF\xFE"
    } else {
      set ::bomstr "\xFE\xFF"
    }
    append ::bomstr [encoding convertto unicode "123456789_123456789_123456789"]
  } -tclbody {
    sqlite3_column_text16 $::STMT 0
    sqlite3_column_int $::STMT 0
    sqlite3_column_text16 $::STMT 1
    sqlite3_column_double $::STMT 1
    set rc [sqlite3_reset $::STMT]
    if {$rc eq "SQLITE_NOMEM"} {error "out of memory"}
    sqlite3_bind_text16 $::STMT 1 $::bomstr 60
    #catch {sqlite3_finalize $::STMT}
    #if {[lindex [sqlite_malloc_stat] 2]<=0} {
    #  error "out of memory"
    #}
  } -cleanup {
    if {$::STMT!=""} {
      sqlite3_finalize $::STMT
      set ::STMT {}
    }
  }
}

# This block tests that malloc() failures that occur whilst commiting
# a multi-file transaction are handled correctly.
#
do_malloc_test 9 -sqlprep {
  ATTACH 'test2.db' as test2;
  CREATE TABLE abc1(a, b, c);
  CREATE TABLE test2.abc2(a, b, c);
} -sqlbody {
  BEGIN;
  INSERT INTO abc1 VALUES(1, 2, 3);
  INSERT INTO abc2 VALUES(1, 2, 3);
  COMMIT;
}

# This block tests malloc() failures that occur while opening a 
# connection to a database.
do_malloc_test 10 -tclprep {
  catch {db2 close}
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  sqlite3_extended_result_codes db 1
  db eval {CREATE TABLE abc(a, b, c)}
} -tclbody {
  db close
  sqlite3 db2 test.db
  sqlite3_extended_result_codes db2 1
  db2 eval {SELECT * FROM sqlite_master}
  db2 close
}

# This block tests malloc() failures that occur within calls to
# sqlite3_create_function().
do_malloc_test 11 -tclbody {
  set rc [sqlite3_create_function db]
  if {[string match $rc SQLITE_OK]} {
    set rc [sqlite3_create_aggregate db]
  }
  if {[string match $rc SQLITE_NOMEM]} {
    error "out of memory"
  }
}

do_malloc_test 12 -tclbody {
  set sql16 [encoding convertto unicode "SELECT * FROM sqlite_master"]
  append sql16 "\00\00"
  set ::STMT [sqlite3_prepare16 db $sql16 -1 DUMMY]
  sqlite3_finalize $::STMT
}

# Test malloc errors when replaying two hot journals from a 2-file 
# transaction.
ifcapable crashtest&&attach {
  do_malloc_test 13 -tclprep {
    set rc [crashsql -delay 1 -file test2.db {
      ATTACH 'test2.db' as aux;
      PRAGMA cache_size = 10;
      BEGIN;
      CREATE TABLE aux.t2(a, b, c);
      CREATE TABLE t1(a, b, c);
      COMMIT;
    }]
    if {$rc!="1 {child process exited abnormally}"} {
      error "Wrong error message: $rc"
    }
  } -tclbody {
    db eval {ATTACH 'test2.db' as aux;}
    set rc [catch {db eval {
      SELECT * FROM t1; 
      SELECT * FROM t2;
    }} err]
    if {$rc && $err!="no such table: t1"} {
      error $err
    }
  }
}

if {$tcl_platform(platform)!="windows"} {
  do_malloc_test 14 -tclprep {
    catch {db close}
    sqlite3 db2 test2.db
    sqlite3_extended_result_codes db2 1
    db2 eval {
      PRAGMA synchronous = 0;
      CREATE TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, 2);
      BEGIN;
      INSERT INTO t1 VALUES(3, 4);
    }
    copy_file test2.db test.db
    copy_file test2.db-journal test.db-journal
    db2 close
  } -tclbody {
    sqlite3 db test.db
    sqlite3_extended_result_codes db 1

    # If an out-of-memory occurs within a call to a VFS layer function during
    # hot-journal rollback, sqlite will report SQLITE_CORRUPT. See commit
    # [5668] for details.
    set rc [catch {db eval { SELECT * FROM t1 }} msg]
    if {$msg eq "database disk image is malformed"} { set msg "out of memory" }
    if {$rc} { error $msg }
    set msg
  }
}

proc string_compare {a b} {
  return [string compare $a $b]
}

# Test for malloc() failures in sqlite3_create_collation() and 
# sqlite3_create_collation16().
#
ifcapable utf16 {
  do_malloc_test 15 -start 4 -tclbody {
    db collate string_compare string_compare
    if {[catch {add_test_collate db 1 1 1} msg]} {
      if {$msg=="SQLITE_NOMEM"} {set msg "out of memory"}
      error $msg
    }
  
    db complete {SELECT "hello """||'world"' [microsoft], * FROM anicetable;}
    db complete {-- Useful comment}
  
    execsql {
      CREATE TABLE t1(a, b COLLATE string_compare);
      INSERT INTO t1 VALUES(10, 'string');
      INSERT INTO t1 VALUES(10, 'string2');
    }
  }
}

# Also test sqlite3_complete(). There are (currently) no malloc()
# calls in this function, but test anyway against future changes.
#
do_malloc_test 16 -tclbody {
  db complete {SELECT "hello """||'world"' [microsoft], * FROM anicetable;}
  db complete {-- Useful comment}
  db eval {
    SELECT * FROM sqlite_master;
  }
}

# Test handling of malloc() failures in sqlite3_open16().
#
ifcapable utf16 {
  do_malloc_test 17 -tclbody {
    set DB2 0
    set STMT 0
  
    # open database using sqlite3_open16()
    set filename [encoding convertto unicode test.db]
    append filename "\x00\x00"
    set DB2 [sqlite3_open16 $filename -unused]
    if {0==$DB2} {
      error "out of memory"
    }
    sqlite3_extended_result_codes $DB2 1
  
    # Prepare statement
    set rc [catch {sqlite3_prepare $DB2 {SELECT * FROM sqlite_master} -1 X} msg]
    if {[sqlite3_errcode $DB2] eq "SQLITE_IOERR+12"} {
      error "out of memory"
    }
    if {[regexp ".*automatic extension loading.*" [sqlite3_errmsg $DB2]]} {
      error "out of memory"
    }
    if {$rc} {
      error [string range $msg 4 end]
    }
    set STMT $msg
  
    # Finalize statement
    set rc [sqlite3_finalize $STMT]
    if {$rc!="SQLITE_OK"} {
      error [sqlite3_errmsg $DB2]
    }
    set STMT 0
  
    # Close database
    set rc [sqlite3_close $DB2]
    if {$rc!="SQLITE_OK"} {
      error [sqlite3_errmsg $DB2]
    }
    set DB2 0
  } -cleanup {
    if {$STMT!="0"} {
      sqlite3_finalize $STMT
    }
    if {$DB2!="0"} {
      set rc [sqlite3_close $DB2]
    }
  }
}

# Test handling of malloc() failures in sqlite3_errmsg16().
#
ifcapable utf16 {
  do_malloc_test 18 -tclprep {
    catch {
      db eval "SELECT [string repeat longcolumnname 10] FROM sqlite_master"
    }
  } -tclbody {
    set utf16 [sqlite3_errmsg16 [sqlite3_connection_pointer db]]
    binary scan $utf16 c* bytes
    if {[llength $bytes]==0} {
      error "out of memory"
    }
  }
}

# This test is aimed at coverage testing. Specificly, it is supposed to
# cause a malloc() only used when converting between the two utf-16 
# encodings to fail (i.e. little-endian->big-endian). It only actually 
# hits this malloc() on little-endian hosts.
#
set static_string "\x00h\x00e\x00l\x00l\x00o"
for {set l 0} {$l<10} {incr l} {
  append static_string $static_string
}
append static_string "\x00\x00"
do_malloc_test 19 -tclprep {
  execsql {
    PRAGMA encoding = "UTF16be";
    CREATE TABLE abc(a, b, c);
  }
} -tclbody {
  unset -nocomplain ::STMT
  set r [catch {
    set ::STMT [sqlite3_prepare db {SELECT ?} -1 DUMMY]
    sqlite3_bind_text16 -static $::STMT 1 $static_string 112
  } msg]
  if {$r} {error [string range $msg 4 end]}
  set msg
} -cleanup {
  if {[info exists ::STMT]} {
    sqlite3_finalize $::STMT
  }
}
unset static_string

# Make sure SQLITE_NOMEM is reported out on an ATTACH failure even
# when the malloc failure occurs within the nested parse.
#
ifcapable attach {
  do_malloc_test 20 -tclprep {
    db close
    file delete -force test2.db test2.db-journal
    sqlite3 db test2.db
    sqlite3_extended_result_codes db 1
    db eval {CREATE TABLE t1(x);}
    db close
  } -tclbody {
    if {[catch {sqlite3 db test.db}]} {
      error "out of memory"
    }
    sqlite3_extended_result_codes db 1
  } -sqlbody {
    ATTACH DATABASE 'test2.db' AS t2;
    SELECT * FROM t1;
    DETACH DATABASE t2;
  } 
}

# Test malloc failure whilst installing a foreign key.
#
ifcapable foreignkey {
  do_malloc_test 21 -sqlbody {
    CREATE TABLE abc(a, b, c, FOREIGN KEY(a) REFERENCES abc(b))
  } 
}

# Test malloc failure in an sqlite3_prepare_v2() call.
#
do_malloc_test 22 -tclbody {
  set ::STMT ""
  set r [catch {
    set ::STMT [
      sqlite3_prepare_v2 db "SELECT * FROM sqlite_master" -1 DUMMY
    ]
  } msg]
  if {$r} {error [string range $msg 4 end]}
} -cleanup {
  if {$::STMT ne ""} {
    sqlite3_finalize $::STMT
    set ::STMT ""
  }
}

ifcapable {pager_pragmas} {
  # This tests a special case - that an error that occurs while the pager
  # is trying to recover from error-state in exclusive-access mode works.
  #
  do_malloc_test 23 -tclprep {
    db eval {
      PRAGMA cache_size = 10;
      PRAGMA locking_mode = exclusive;
      BEGIN;
      CREATE TABLE abc(a, b, c);
      CREATE INDEX abc_i ON abc(a, b, c);
      INSERT INTO abc 
        VALUES(randstr(100,100), randstr(100,100), randstr(100,100));
      INSERT INTO abc 
        SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
      INSERT INTO abc 
        SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
      INSERT INTO abc 
        SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
      INSERT INTO abc 
        SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
      INSERT INTO abc 
        SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
      COMMIT;
    }
  
    # This puts the pager into error state.
    #
    db eval BEGIN
    db eval {UPDATE abc SET a = 0 WHERE oid%2}
    set ::sqlite_io_error_pending 10
    catch {db eval {ROLLBACK}} msg

  } -tclbody {
    # If an out-of-memory occurs within a call to a VFS layer function during
    # hot-journal rollback, sqlite will report SQLITE_CORRUPT. See commit
    # [5668] for details.
    set rc [catch {db eval { SELECT * FROM abc LIMIT 10 }} msg]
    if {$msg eq "database disk image is malformed"} { set msg "out of memory" }
    if {$rc} { error $msg }
    set msg
  } -cleanup {
    set e [db eval {PRAGMA integrity_check}]
    if {$e ne "ok"} {error $e}
  }
}

ifcapable compound {
  do_malloc_test 24 -sqlprep {
    CREATE TABLE t1(a, b, c)
  } -sqlbody {
    SELECT 1 FROM t1 UNION SELECT 2 FROM t1 ORDER BY 1
  }
}

ifcapable view&&trigger {
  do_malloc_test 25 -sqlprep {
    CREATE TABLE t1(a, b, c);
    CREATE VIEW v1 AS SELECT * FROM t1;
    CREATE TRIGGER v1t1 INSTEAD OF DELETE ON v1 BEGIN SELECT 1; END;
    CREATE TRIGGER v1t2 INSTEAD OF INSERT ON v1 BEGIN SELECT 1; END;
    CREATE TRIGGER v1t3 INSTEAD OF UPDATE ON v1 BEGIN SELECT 1; END;
  } -sqlbody {
    DELETE FROM v1 WHERE a = 1;
    INSERT INTO v1 VALUES(1, 2, 3);
    UPDATE v1 SET a = 1 WHERE b = 2;
  }
}

do_malloc_test 25 -sqlprep {
  CREATE TABLE abc(a, b, c);
  CREATE INDEX i1 ON abc(a, b);
  INSERT INTO abc VALUES(1, 2, 3);
  INSERT INTO abc VALUES(4, 5, 6);
} -tclbody {
  # For each UPDATE executed, the cursor used for the SELECT statement
  # must be "saved". Because the cursor is open on an index, this requires
  # a malloc() to allocate space to save the index key. This test case is
  # aimed at testing the response of the library to a failure in that
  # particular malloc() call.
  db eval {SELECT a FROM abc ORDER BY a} {
    db eval {UPDATE abc SET b = b - 1 WHERE a = $a}
  }
}

# This test is designed to test a specific juncture in the sqlite code.
# The database set up by -sqlprep script contains a single table B-Tree
# of height 2. In the -tclbody script, the existing database connection
# is closed and a new one opened and used to insert a new row into the
# table B-Tree. By using a new connection, the outcome of a malloc() 
# failure while seeking to the right-hand side of the B-Tree to insert 
# a new record can be tested.
#
do_malloc_test 26 -sqlprep {
  BEGIN;
  CREATE TABLE t1(a, b);
  INSERT INTO t1 VALUES(1, randomblob(210));
  INSERT INTO t1 VALUES(1, randomblob(210));
  INSERT INTO t1 VALUES(1, randomblob(210));
  INSERT INTO t1 VALUES(1, randomblob(210));
  INSERT INTO t1 VALUES(1, randomblob(210));
  COMMIT;
} -tclbody {
  db close
  sqlite3 db test.db
  db eval { INSERT INTO t1 VALUES(1, randomblob(210)) }
}

# Test that no memory is leaked following a malloc() failure in
# sqlite3_initialize().
#
do_malloc_test 27 -tclprep {
  db close
  sqlite3_shutdown
} -tclbody {
  set rc [sqlite3_initialize]
  if {$rc == "SQLITE_NOMEM"} {
    error "out of memory"
  }
}
autoinstall_test_functions

# Test that malloc failures that occur while processing INDEXED BY
# clauses are handled correctly.
do_malloc_test 28 -sqlprep {
  CREATE TABLE t1(a, b);
  CREATE INDEX i1 ON t1(a);
  CREATE VIEW v1 AS SELECT * FROM t1 INDEXED BY i1 WHERE a = 10;
} -sqlbody {
  SELECT * FROM t1 INDEXED BY i1 ORDER BY a;
  SELECT * FROM v1;
}

do_malloc_test 29 -sqlprep {
  CREATE TABLE t1(a TEXT, b TEXT);
} -sqlbody {
  INSERT INTO t1 VALUES(1, -234);
  INSERT INTO t1 SELECT * FROM t1 UNION ALL SELECT * FROM t1;
}

do_malloc_test 30 -tclprep {
  db eval {
    CREATE TABLE t1(x PRIMARY KEY);
    INSERT INTO t1 VALUES(randstr(500,500));
    INSERT INTO t1 VALUES(randstr(500,500));
    INSERT INTO t1 VALUES(randstr(500,500));
  }
  db close
  sqlite3 db test.db

  # The DELETE command in the following block moves the overflow pages that
  # are part of the primary key index to the free-list. But it does not
  # actually load the content of the pages. This leads to the peculiar
  # situation where cache entries exist, but are not populated with data.
  # They are populated next time they are requested by the b-tree layer.
  #
  db eval {
    BEGIN;
      DELETE FROM t1;
    ROLLBACK;
  }
} -sqlbody {
  -- This statement requires the 'no-content' pages loaded by the DELETE
  -- statement above. When requesting the pages, the content is loaded
  -- from the database file. The point of this test case is to test handling
  -- of malloc errors (including SQLITE_IOERR_NOMEM errors) when loading
  -- the content.
  SELECT * FROM t1 ORDER BY x;
}

# After committing a transaction in persistent-journal mode, if a journal
# size limit is configured SQLite may attempt to truncate the journal file.
# This test verifies the libraries response to a malloc() failure during
# this operation.
#
do_malloc_test 31 -sqlprep {
  PRAGMA journal_mode = persist;
  PRAGMA journal_size_limit = 1024;
  CREATE TABLE t1(a PRIMARY KEY, b);
} -sqlbody {
  INSERT INTO t1 VALUES(1, 2);
}

# When written, this test provoked an obscure change-counter bug.
# 
# If, when running in exclusive mode, a malloc() failure occurs
# after the database file change-counter has been written but
# before the transaction has been committed, then the transaction
# is automatically rolled back. However, internally the 
# Pager.changeCounterDone flag was being left set. This means
# that if the same connection attempts another transaction following
# the malloc failure and rollback, the change counter will not
# be updated. This could corrupt another processes cache.
#
do_malloc_test 32 -tclprep {
  # Build a small database containing an indexed table.
  #
  db eval {
    PRAGMA locking_mode = normal;
    BEGIN;
    CREATE TABLE t1(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
    INSERT INTO t1 VALUES(3, 'three');
    COMMIT;
    PRAGMA locking_mode = exclusive;
  }

  # Open a second database connection. Load the table (but not index)
  # into the second connections pager cache.
  #
  sqlite3 db2 test.db
  db2 eval { 
    PRAGMA locking_mode = normal;
    SELECT b FROM t1;
  }

} -tclbody {
  # Running in exclusive mode, perform a database transaction that 
  # modifies both the database table and index. For iterations where
  # the malloc failure occurs after updating the change counter but
  # before committing the transaction, this should result in the
  # transaction being rolled back but the changeCounterDone flag
  # left set.
  #
  db eval { UPDATE t1 SET a = a + 3 }
} -cleanup {

  # Perform another transaction using the first connection. Unlock
  # the database after doing so. If this is one of the right iterations,
  # then this should result in the database contents being updated but
  # the change-counter left as it is.
  #
  db eval { 
    PRAGMA locking_mode = normal;
    UPDATE t1 SET a = a + 3;
  }

  # Now do an integrity check with the second connection. The second
  # connection still has the database table in its cache. If this is
  # one of the magic iterations and the change counter was not modified,
  # then it won't realize that the cached data is out of date. Since
  # the cached data won't match the up to date index data read from
  # the database file, the integrity check should fail.
  #
  set zRepeat "transient"
  if {$::iRepeat} {set zRepeat "persistent"}
  do_test malloc-32.$zRepeat.${::n}.integrity {
    execsql {PRAGMA integrity_check} db2
  } {ok}
  db2 close
}

# The following two OOM tests verify that OOM handling works in the
# code used to optimize "SELECT count(*) FROM <tbl>".
#
do_malloc_test 33 -tclprep {
  db eval { PRAGMA cache_size = 10 }
  db transaction {
    db eval { CREATE TABLE abc(a, b) }
    for {set i 0} {$i<500} {incr i} {
      db eval {INSERT INTO abc VALUES(randstr(100,100), randstr(1000,1000))}
    }
  }
} -sqlbody {
  SELECT count(*) FROM abc;
}
do_malloc_test 34 -tclprep {
  db eval { PRAGMA cache_size = 10 }
  db transaction {
    db eval { CREATE TABLE abc(a PRIMARY KEY, b) }
    for {set i 0} {$i<500} {incr i} {
      db eval {INSERT INTO abc VALUES(randstr(100,100), randstr(1000,1000))}
    }
  }
} -sqlbody {
  SELECT count(*) FROM abc;
}

proc f {args} { error "Quite a long error!" }
do_malloc_test 35 -tclprep {
  db func f f
  set ::STMT [sqlite3_prepare db "SELECT f()" -1 DUMMY]
  sqlite3_step $::STMT
} -tclbody {
  sqlite3_finalize $::STMT
} -cleanup {
  # At one point an assert( !db->mallocFailed ) could fail in the following
  # call to sqlite3_errmsg(). Because sqlite3_finalize() had failed to clear
  # the flag before returning.
  sqlite3_errmsg16 db
}

do_malloc_test 36 -sqlprep {
  CREATE TABLE t1(a, b);
  INSERT INTO t1 VALUES(1, 2);
  INSERT INTO t1 VALUES(3, 4);
} -sqlbody {
  SELECT test_agg_errmsg16(), group_concat(a) FROM t1
}

# At one point, if an OOM occured immediately after obtaining a shared lock
# on the database file, the file remained locked. This test case ensures
# that bug has been fixed.i
if {[db eval {PRAGMA locking_mode}]!="exclusive"} {
  do_malloc_test 37 -tclprep {
    sqlite3 db2 test.db
    execsql {
      CREATE TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, 2);
    } db2
  } -sqlbody {
    SELECT * FROM t1;
  } -cleanup {
    # Try to write to the database using connection [db2]. If connection [db]
    # has correctly released the shared lock, this write attempt should 
    # succeed. If [db] has not released the lock, this should hit an 
    # SQLITE_BUSY error.
    do_test malloc-36.$zRepeat.${::n}.unlocked {
      execsql {INSERT INTO t1 VALUES(3, 4)} db2
    } {}
    db2 close
  }
  catch { db2 close }
}

ifcapable stat2 {
  do_malloc_test 38 -tclprep {
    add_test_collate db 0 0 1
    execsql {
      ANALYZE;
      CREATE TABLE t4(x COLLATE test_collate);
      CREATE INDEX t4x ON t4(x);
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 0, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 1, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 2, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 3, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 4, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 5, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 6, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 7, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 8, 'aaa');
      INSERT INTO sqlite_stat2 VALUES('t4', 't4x', 9, 'aaa');
    }
    db close
    sqlite3 db test.db
    sqlite3_db_config_lookaside db 0 0 0
    add_test_collate db 0 0 1
  } -sqlbody {
    SELECT * FROM t4 AS t41, t4 AS t42 WHERE t41.x>'ddd' AND t42.x>'ccc'
  }
}

# Ensure that no file descriptors were leaked.
do_test malloc-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

puts open-file-count=$sqlite_open_file_count
finish_test

Added test/malloc3.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# 2005 November 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains tests to ensure that the library handles malloc() failures
# correctly. The emphasis of these tests are the _prepare(), _step() and
# _finalize() calls.
#
# $Id: malloc3.test,v 1.24 2008/10/14 15:54:08 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping malloc3 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

#--------------------------------------------------------------------------
# NOTES ON RECOVERING FROM A MALLOC FAILURE
# 
# The tests in this file test the behaviours described in the following
# paragraphs. These tests test the behaviour of the system when malloc() fails
# inside of a call to _prepare(), _step(), _finalize() or _reset(). The
# handling of malloc() failures within ancillary procedures is tested
# elsewhere.
#
# Overview:
#
# Executing a statement is done in three stages (prepare, step and finalize). A
# malloc() failure may occur within any stage. If a memory allocation fails
# during statement preparation, no statement handle is returned. From the users
# point of view the system state is as if _prepare() had never been called.
#
# If the memory allocation fails during the _step() or _finalize() calls, then
# the database may be left in one of two states (after finalize() has been
# called):
#
#     * As if the neither _step() nor _finalize() had ever been called on
#       the statement handle (i.e. any changes made by the statement are
#       rolled back).
#     * The current transaction may be rolled back. In this case a hot-journal
#       may or may not actually be present in the filesystem.
#
# The caller can tell the difference between these two scenarios by invoking
# _get_autocommit().
#
#
# Handling of sqlite3_reset():
#
# If a malloc() fails while executing an sqlite3_reset() call, this is handled
# in the same way as a failure within _finalize(). The statement handle
# is not deleted and must be passed to _finalize() for resource deallocation.
# Attempting to _step() or _reset() the statement after a failed _reset() will
# always return SQLITE_NOMEM.
#
#
# Other active SQL statements:
#
# The effect of a malloc failure on concurrently executing SQL statements,
# particularly when the statement is executing with READ_UNCOMMITTED set and
# the malloc() failure mandates statement rollback only. Currently, if
# transaction rollback is required, all other vdbe's are aborted.
#
#     Non-transient mallocs in btree.c:
#         * The Btree structure itself
#         * Each BtCursor structure
#
#     Mallocs in pager.c:
#         readMasterJournal()  - Space to read the master journal name
#         pager_delmaster()    - Space for the entire master journal file
#
#         sqlite3pager_open()  - The pager structure itself
#         sqlite3_pagerget()   - Space for a new page
#         pager_open_journal() - Pager.aInJournal[] bitmap
#         sqlite3pager_write() - For in-memory databases only: history page and
#                                statement history page.
#         pager_stmt_begin()   - Pager.aInStmt[] bitmap
#
# None of the above are a huge problem. The most troublesome failures are the
# transient malloc() calls in btree.c, which can occur during the tree-balance
# operation. This means the tree being balanced will be internally inconsistent
# after the malloc() fails. To avoid the corrupt tree being read by a
# READ_UNCOMMITTED query, we have to make sure the transaction or statement
# rollback occurs before sqlite3_step() returns, not during a subsequent
# sqlite3_finalize().
#--------------------------------------------------------------------------

#--------------------------------------------------------------------------
# NOTES ON TEST IMPLEMENTATION
#
# The tests in this file are implemented differently from those in other
# files. Instead, tests are specified using three primitives: SQL, PREP and
# TEST. Each primitive has a single argument. Primitives are processed in
# the order they are specified in the file.
#
# A TEST primitive specifies a TCL script as its argument. When a TEST
# directive is encountered the Tcl script is evaluated. Usually, this Tcl
# script contains one or more calls to [do_test].
#
# A PREP primitive specifies an SQL script as its argument. When a PREP
# directive is encountered the SQL is evaluated using database connection
# [db].
#
# The SQL primitives are where the action happens. An SQL primitive must
# contain a single, valid SQL statement as its argument. When an SQL
# primitive is encountered, it is evaluated one or more times to test the
# behaviour of the system when malloc() fails during preparation or
# execution of said statement. The Nth time the statement is executed,
# the Nth malloc is said to fail. The statement is executed until it
# succeeds, i.e. (M+1) times, where M is the number of mallocs() required
# to prepare and execute the statement.
#
# Each time an SQL statement fails, the driver program (see proc [run_test]
# below) figures out if a transaction has been automatically rolled back.
# If not, it executes any TEST block immediately proceeding the SQL
# statement, then reexecutes the SQL statement with the next value of N.
#
# If a transaction has been automatically rolled back, then the driver
# program executes all the SQL specified as part of SQL or PREP primitives
# between the current SQL statement and the most recent "BEGIN". Any 
# TEST block immediately proceeding the SQL statement is evaluated, and
# then the SQL statement reexecuted with the incremented N value.
#
# That make any sense? If not, read the code in [run_test] and it might.
#
# Extra restriction imposed by the implementation:
#
# * If a PREP block starts a transaction, it must finish it.
# * A PREP block may not close a transaction it did not start.
#
#--------------------------------------------------------------------------


# These procs are used to build up a "program" in global variable
# ::run_test_script. At the end of this file, the proc [run_test] is used
# to execute the program (and all test cases contained therein).
#
set ::run_test_script [list]
proc TEST {id t} {lappend ::run_test_script -test [list $id $t]}
proc PREP {p} {lappend ::run_test_script -prep [string trim $p]}
proc DEBUG {s} {lappend ::run_test_script -debug $s}

# SQL --
#
#     SQL ?-norollback? <sql-text>
#
# Add an 'SQL' primitive to the program (see notes above). If the -norollback
# switch is present, then the statement is not allowed to automatically roll
# back any active transaction if malloc() fails. It must rollback the statement
# transaction only.
#
proc SQL  {a1 {a2 ""}} {
  # An SQL primitive parameter is a list of two elements, a boolean value
  # indicating if the statement may cause transaction rollback when malloc()
  # fails, and the sql statement itself.
  if {$a2 == ""} {
    lappend ::run_test_script -sql [list true [string trim $a1]]
  } else {
    lappend ::run_test_script -sql [list false [string trim $a2]]
  }
}

# TEST_AUTOCOMMIT --
# 
#     A shorthand test to see if a transaction is active or not. The first
#     argument - $id - is the integer number of the test case. The second
#     argument is either 1 or 0, the expected value of the auto-commit flag.
#
proc TEST_AUTOCOMMIT {id a} {
    TEST $id "do_test \$testid { sqlite3_get_autocommit \$::DB } {$a}"
}

#--------------------------------------------------------------------------
# Start of test program declaration
#


# Warm body test. A malloc() fails in the middle of a CREATE TABLE statement
# in a single-statement transaction on an empty database. Not too much can go
# wrong here.
#
TEST 1 {
  do_test $testid {
    execsql {SELECT tbl_name FROM sqlite_master;}
  } {}
}
SQL { 
  CREATE TABLE IF NOT EXISTS abc(a, b, c); 
}
TEST 2 {
  do_test $testid.1 {
    execsql {SELECT tbl_name FROM sqlite_master;}
  } {abc}
}

# Insert a couple of rows into the table. each insert is in its own
# transaction. test that the table is unpopulated before running the inserts
# (and hence after each failure of the first insert), and that it has been
# populated correctly after the final insert succeeds.
#
TEST 3 {
  do_test $testid.2 {
    execsql {SELECT * FROM abc}
  } {}
}
SQL {INSERT INTO abc VALUES(1, 2, 3);}
SQL {INSERT INTO abc VALUES(4, 5, 6);}
SQL {INSERT INTO abc VALUES(7, 8, 9);}
TEST 4 {
  do_test $testid {
    execsql {SELECT * FROM abc}
  } {1 2 3 4 5 6 7 8 9}
}

# Test a CREATE INDEX statement. Because the table 'abc' is so small, the index
# will all fit on a single page, so this doesn't test too much that the CREATE
# TABLE statement didn't test. A few of the transient malloc()s in btree.c
# perhaps.
#
SQL {CREATE INDEX abc_i ON abc(a, b, c);}
TEST 4 {
  do_test $testid {
    execsql {
      SELECT * FROM abc ORDER BY a DESC;
    }
  } {7 8 9 4 5 6 1 2 3}
}

# Test a DELETE statement. Also create a trigger and a view, just to make sure
# these statements don't have any obvious malloc() related bugs in them. Note
# that the test above will be executed each time the DELETE fails, so we're
# also testing rollback of a DELETE from a table with an index on it.
#
SQL {DELETE FROM abc WHERE a > 2;}
SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;}
SQL {CREATE VIEW abc_v AS SELECT * FROM abc;}
TEST 5 {
  do_test $testid {
    execsql {
      SELECT name, tbl_name FROM sqlite_master ORDER BY name;
      SELECT * FROM abc;
    }
  } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3}
}

set sql {
  BEGIN;DELETE FROM abc;
}
for {set i 1} {$i < 15} {incr i} {
  set a $i
  set b "String value $i"
  set c [string repeat X $i]
  append sql "INSERT INTO abc VALUES ($a, '$b', '$c');"
}
append sql {COMMIT;}
PREP $sql

SQL {
  DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
}
TEST 6 {
  do_test $testid.1 {
    execsql {SELECT count(*) FROM abc}
  } {94}
  do_test $testid.2 {
    execsql {
      SELECT min(
          (oid == a) AND 'String value ' || a == b AND a == length(c) 
      ) FROM abc;
    }
  } {1}
}
SQL {
  DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
}
TEST 7 {
  do_test $testid {
    execsql {SELECT count(*) FROM abc}
  } {89}
  do_test $testid {
    execsql {
      SELECT min(
          (oid == a) AND 'String value ' || a == b AND a == length(c) 
      ) FROM abc;
    }
  } {1}
}
SQL {
  DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
}
TEST 9 {
  do_test $testid {
    execsql {SELECT count(*) FROM abc}
  } {84}
  do_test $testid {
    execsql {
      SELECT min(
          (oid == a) AND 'String value ' || a == b AND a == length(c) 
      ) FROM abc;
    }
  } {1}
}

set padding [string repeat X 500]
PREP [subst {
  DROP TABLE abc;
  CREATE TABLE abc(a PRIMARY KEY, padding, b, c);
  INSERT INTO abc VALUES(0, '$padding', 2, 2);
  INSERT INTO abc VALUES(3, '$padding', 5, 5);
  INSERT INTO abc VALUES(6, '$padding', 8, 8);
}]

TEST 10 {
  do_test $testid {
    execsql {SELECT a, b, c FROM abc}
  } {0 2 2 3 5 5 6 8 8}
}

SQL {BEGIN;}
SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);}
TEST_AUTOCOMMIT 11 0
SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;}
TEST_AUTOCOMMIT 12 0
SQL {DELETE FROM abc WHERE a = 10;}
TEST_AUTOCOMMIT 13 0
SQL {COMMIT;}

TEST 14 {
  do_test $testid.1 {
    sqlite3_get_autocommit $::DB
  } {1}
  do_test $testid.2 {
    execsql {SELECT a, b, c FROM abc}
  } {1 2 3 4 5 6 7 8 9}
}

PREP [subst {
  DROP TABLE abc;
  CREATE TABLE abc(a, padding, b, c);
  INSERT INTO abc VALUES(1, '$padding', 2, 3);
  INSERT INTO abc VALUES(4, '$padding', 5, 6);
  INSERT INTO abc VALUES(7, '$padding', 8, 9);
  CREATE INDEX abc_i ON abc(a, padding, b, c);
}]

TEST 15 {
  db eval {PRAGMA cache_size = 10}
}

SQL {BEGIN;}
SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
TEST 16 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 2 4 2 7 2}
}
SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
TEST 17 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 4 4 4 7 4}
}
SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
TEST 18 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 8 4 8 7 8}
}
SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
TEST 19 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 16 4 16 7 16}
}
SQL {COMMIT;}
TEST 21 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 16 4 16 7 16}
}

SQL {BEGIN;}
SQL {DELETE FROM abc WHERE oid %2}
TEST 22 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 8 4 8 7 8}
}
SQL {DELETE FROM abc}
TEST 23 {
  do_test $testid {
    execsql {SELECT * FROM abc}
  } {}
}
SQL {ROLLBACK;}
TEST 24 {
  do_test $testid {
    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
  } {1 16 4 16 7 16}
}

# Test some schema modifications inside of a transaction. These should all
# cause transaction rollback if they fail. Also query a view, to cover a bit
# more code.
#
PREP {DROP VIEW abc_v;}
TEST 25 {
  do_test $testid {
    execsql {
      SELECT name, tbl_name FROM sqlite_master;
    }
  } {abc abc abc_i abc}
}
SQL {BEGIN;}
SQL {CREATE TABLE def(d, e, f);}
SQL {CREATE TABLE ghi(g, h, i);}
TEST 26 {
  do_test $testid {
    execsql {
      SELECT name, tbl_name FROM sqlite_master;
    }
  } {abc abc abc_i abc def def ghi ghi}
}
SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi}
SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);}
TEST 27 {
  do_test $testid {
    execsql {
      SELECT name, tbl_name FROM sqlite_master;
    }
  } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi}
}
SQL {INSERT INTO def VALUES('a', 'b', 'c')}
SQL {INSERT INTO def VALUES(1, 2, 3)}
SQL -norollback {INSERT INTO ghi SELECT * FROM def}
TEST 28 {
  do_test $testid {
    execsql {
      SELECT * FROM def, ghi WHERE d = g;
    }
  } {a b c a b c 1 2 3 1 2 3}
}
SQL {COMMIT}
TEST 29 {
  do_test $testid {
    execsql {
      SELECT * FROM v1 WHERE d = g;
    }
  } {a b c a b c 1 2 3 1 2 3}
}

# Test a simple multi-file transaction 
#
file delete -force test2.db
ifcapable attach {
  SQL {ATTACH 'test2.db' AS aux;}
  SQL {BEGIN}
  SQL {CREATE TABLE aux.tbl2(x, y, z)}
  SQL {INSERT INTO tbl2 VALUES(1, 2, 3)}
  SQL {INSERT INTO def VALUES(4, 5, 6)}
  TEST 30 {
    do_test $testid {
      execsql {
        SELECT * FROM tbl2, def WHERE d = x;
      }
    } {1 2 3 1 2 3}
  }
  SQL {COMMIT}
  TEST 31 {
    do_test $testid {
      execsql {
        SELECT * FROM tbl2, def WHERE d = x;
      }
    } {1 2 3 1 2 3}
  }
}

# Test what happens when a malloc() fails while there are other active
# statements. This changes the way sqlite3VdbeHalt() works.
TEST 32 {
  if {![info exists ::STMT32]} {
    set sql "SELECT name FROM sqlite_master"
    set ::STMT32 [sqlite3_prepare $::DB $sql -1 DUMMY]
    do_test $testid {
      sqlite3_step $::STMT32
    } {SQLITE_ROW}
  }
}
SQL BEGIN
TEST 33 { 
  do_test $testid {
    execsql {SELECT * FROM ghi}
  } {a b c 1 2 3}
}
SQL -norollback { 
  -- There is a unique index on ghi(g), so this statement may not cause
  -- an automatic ROLLBACK. Hence the "-norollback" switch.
  INSERT INTO ghi SELECT '2'||g, h, i FROM ghi;
}
TEST 34 {
  if {[info exists ::STMT32]} {
    do_test $testid {
      sqlite3_finalize $::STMT32
    } {SQLITE_OK}
    unset ::STMT32
  }
}
SQL COMMIT

#
# End of test program declaration
#--------------------------------------------------------------------------

proc run_test {arglist iRepeat {pcstart 0} {iFailStart 1}} {
  if {[llength $arglist] %2} {
    error "Uneven number of arguments to TEST"
  }

  for {set i 0} {$i < $pcstart} {incr i} {
    set k2 [lindex $arglist [expr 2 * $i]]
    set v2 [lindex $arglist [expr 2 * $i + 1]]
    set ac [sqlite3_get_autocommit $::DB]        ;# Auto-Commit
    switch -- $k2 {
      -sql  {db eval [lindex $v2 1]}
      -prep {db eval $v2}
    }
    set nac [sqlite3_get_autocommit $::DB]       ;# New Auto-Commit 
    if {$ac && !$nac} {set begin_pc $i}
  }

  db rollback_hook [list incr ::rollback_hook_count]

  set iFail $iFailStart
  set pc $pcstart
  while {$pc*2 < [llength $arglist]} {

    # Id of this iteration:
    set k [lindex $arglist [expr 2 * $pc]]
    set iterid "pc=$pc.iFail=$iFail$k"
    set v [lindex $arglist [expr 2 * $pc + 1]]

    switch -- $k {

      -test { 
        foreach {id script} $v {}
        incr pc
      }

      -sql {
        set ::rollback_hook_count 0

        set ac [sqlite3_get_autocommit $::DB]        ;# Auto-Commit
        sqlite3_memdebug_fail $iFail -repeat 0
        set rc [catch {db eval [lindex $v 1]} msg]   ;# True error occurs
        set nac [sqlite3_get_autocommit $::DB]       ;# New Auto-Commit 

        if {$rc != 0 && $nac && !$ac} {
          # Before [db eval] the auto-commit flag was clear. Now it
          # is set. Since an error occured we assume this was not a
          # commit - therefore a rollback occured. Check that the
          # rollback-hook was invoked.
          do_test malloc3-rollback_hook.$iterid {
            set ::rollback_hook_count
          } {1}
        }

        set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign]
        if {$rc == 0} {
            # Successful execution of sql. The number of failed malloc()
            # calls should be equal to the number of benign failures.
            # Otherwise a malloc() failed and the error was not reported.
            # 
            if {$nFail!=$nBenign} {
              error "Unreported malloc() failure"
            }

            if {$ac && !$nac} {
              # Before the [db eval] the auto-commit flag was set, now it
              # is clear. We can deduce that a "BEGIN" statement has just
              # been successfully executed.
              set begin_pc $pc
            } 

            incr pc
            set iFail 1
            integrity_check "malloc3-(integrity).$iterid"
        } elseif {[regexp {.*out of memory} $msg] || [db errorcode] == 3082} {
            # Out of memory error, as expected.
            #
            integrity_check "malloc3-(integrity).$iterid"
            incr iFail
            if {$nac && !$ac} {

              if {![lindex $v 0] && [db errorcode] != 3082} {
                # error "Statement \"[lindex $v 1]\" caused a rollback"
              }

              for {set i $begin_pc} {$i < $pc} {incr i} {
                set k2 [lindex $arglist [expr 2 * $i]]
                set v2 [lindex $arglist [expr 2 * $i + 1]]
                set catchupsql ""
                switch -- $k2 {
                  -sql  {set catchupsql [lindex $v2 1]}
                  -prep {set catchupsql $v2}
                }
                db eval $catchupsql
              }
            }
        } else {
            error $msg
        }

        while {[lindex $arglist [expr 2 * ($pc -1)]] == "-test"} {
          incr pc -1
        }
      }

      -prep {
        db eval $v
        incr pc
      }

      -debug {
        eval $v
        incr pc
      }

      default { error "Unknown switch: $k" }
    }
  }
}

# Turn of the Tcl interface's prepared statement caching facility. Then
# run the tests with "persistent" malloc failures.
sqlite3_extended_result_codes db 1
db cache size 0
run_test $::run_test_script 1

# Close and reopen the db.
db close
file delete -force test.db test.db-journal test2.db test2.db-journal
sqlite3 db test.db
sqlite3_extended_result_codes db 1
set ::DB [sqlite3_connection_pointer db]

# Turn of the Tcl interface's prepared statement caching facility in
# the new connnection. Then run the tests with "transient" malloc failures.
db cache size 0
run_test $::run_test_script 0

sqlite3_memdebug_fail -1
finish_test

Added test/malloc4.test.





































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# 2005 November 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains tests to ensure that the library handles malloc() failures
# correctly. The emphasis in this file is on sqlite3_column_XXX() APIs.
#
# $Id: malloc4.test,v 1.10 2008/02/18 22:24:58 drh Exp $

#---------------------------------------------------------------------------
# NOTES ON EXPECTED BEHAVIOUR
#
# [193] When a memory allocation failure occurs during sqlite3_column_name(),
#       sqlite3_column_name16(), sqlite3_column_decltype(), or
#       sqlite3_column_decltype16() the function shall return NULL.
#
#---------------------------------------------------------------------------

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
if {!$MEMDEBUG} {
   puts "Skipping malloc4 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

ifcapable !utf16 {
  finish_test
  return
}

proc do_stmt_test {id sql} {
  set ::sql $sql
  set go 1
  for {set n 0} {$go} {incr n} {
    set testid "malloc4-$id.$n"

    # Prepare the statement
    do_test ${testid}.1 {
      set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
      expr [string length $::STMT] > 0
    } {1}

    # Set the Nth malloc() to fail.
    sqlite3_memdebug_fail $n -repeat 0

    # Test malloc failure in the _name(), _name16(), decltype() and
    # decltype16() APIs. Calls that occur after the malloc() failure should
    # return NULL. No error is raised though.
    #
    # ${testid}.2.1 - Call _name()
    # ${testid}.2.2 - Call _name16()
    # ${testid}.2.3 - Call _name()
    # ${testid}.2.4 - Check that the return values of the above three calls are
    #                 consistent with each other and with the simulated
    #                 malloc() failures.
    #
    # Because the code that implements the _decltype() and _decltype16() APIs
    # is the same as the _name() and _name16() implementations, we don't worry
    # about explicitly testing them.
    #
    do_test ${testid}.2.1 {
      set mf1 [expr [sqlite3_memdebug_pending] < 0]
      set ::name8  [sqlite3_column_name $::STMT 0]
      set mf2 [expr [sqlite3_memdebug_pending] < 0]
      expr {$mf1 == $mf2 || $::name8 == ""}
    } {1}
    do_test ${testid}.2.2 {
      set mf1 [expr [sqlite3_memdebug_pending] < 0]
      set ::name16 [sqlite3_column_name16 $::STMT 0]
      set ::name16 [encoding convertfrom unicode $::name16]
      set ::name16 [string range $::name16 0 end-1]
      set mf2 [expr [sqlite3_memdebug_pending] < 0]
      expr {$mf1 == $mf2 || $::name16 == ""}
    } {1}
    do_test ${testid}.2.3 {
      set mf1 [expr [sqlite3_memdebug_pending] < 0]
      set ::name8_2 [sqlite3_column_name $::STMT 0]
      set mf2 [expr [sqlite3_memdebug_pending] < 0]
      expr {$mf1 == $mf2 || $::name8_2 == ""}
    } {1}
    set ::mallocFailed [expr [sqlite3_memdebug_pending] < 0]
    do_test ${testid}.2.4 {
      expr {
        $::name8 == $::name8_2 && $::name16 == $::name8 && !$::mallocFailed ||
        $::name8 == $::name8_2 && $::name16 == "" &&        $::mallocFailed ||
        $::name8 == $::name16 && $::name8_2 == "" &&        $::mallocFailed ||
        $::name8_2 == $::name16 && $::name8 == "" &&        $::mallocFailed
      }
    } {1}

    # Step the statement so that we can call _text() and _text16().  Before
    # running sqlite3_step(), make sure that malloc() is not about to fail.
    # Memory allocation failures that occur within sqlite3_step() are tested
    # elsewhere.
    set mf [sqlite3_memdebug_pending]
    sqlite3_memdebug_fail -1
    do_test ${testid}.3 {
      sqlite3_step $::STMT
    } {SQLITE_ROW}
    sqlite3_memdebug_fail $mf

    # Test for malloc() failures within _text() and _text16().
    #
    do_test ${testid}.4.1 {
      set ::text8 [sqlite3_column_text $::STMT 0]
      set mf [expr [sqlite3_memdebug_pending] < 0 && !$::mallocFailed]
      expr {$mf==0 || $::text8 == ""}
    } {1}
    do_test ${testid}.4.2 {
      set ::text16 [sqlite3_column_text16 $::STMT 0]
      set ::text16 [encoding convertfrom unicode $::text16]
      set ::text16 [string range $::text16 0 end-1]
      set mf [expr [sqlite3_memdebug_pending] < 0 && !$::mallocFailed]
      expr {$mf==0 || $::text16 == ""}
    } {1}
    do_test ${testid}.4.3 {
      set ::text8_2 [sqlite3_column_text $::STMT 0]
      set mf [expr [sqlite3_memdebug_pending] < 0 && !$::mallocFailed]
      expr {$mf==0 || $::text8_2 == "" || ($::text16 == "" && $::text8 != "")}
    } {1}

    # Test for malloc() failures within _int(), _int64() and _real(). The only
    # way this can occur is if the string has to be translated from UTF-16 to
    # UTF-8 before being converted to a numeric value.
    do_test ${testid}.4.4.1 {
      set mf [sqlite3_memdebug_pending]
      sqlite3_memdebug_fail -1
      sqlite3_column_text16 $::STMT 0
      sqlite3_memdebug_fail $mf
      sqlite3_column_int $::STMT 0
    } {0}
    do_test ${testid}.4.5 {
      set mf [sqlite3_memdebug_pending]
      sqlite3_memdebug_fail -1
      sqlite3_column_text16 $::STMT 0
      sqlite3_memdebug_fail $mf
      sqlite3_column_int64 $::STMT 0
    } {0}

    do_test ${testid}.4.6 {
      set mf [sqlite3_memdebug_pending]
      sqlite3_memdebug_fail -1
      sqlite3_column_text16 $::STMT 0
      sqlite3_memdebug_fail $mf
      sqlite3_column_double $::STMT 0
    } {0.0}

    set mallocFailedAfterStep [expr \
      [sqlite3_memdebug_pending] < 0 && !$::mallocFailed
    ]

    sqlite3_memdebug_fail -1
    # Test that if a malloc() failed the next call to sqlite3_step() returns
    # SQLITE_ERROR. If malloc() did not fail, it should return SQLITE_DONE.
    #
    do_test ${testid}.5 {
      sqlite3_step $::STMT
    } [expr {$mallocFailedAfterStep ? "SQLITE_ERROR" : "SQLITE_DONE"}]

    do_test ${testid}.6 {
      sqlite3_finalize $::STMT
    } [expr {$mallocFailedAfterStep ? "SQLITE_NOMEM" : "SQLITE_OK"}]

    if {$::mallocFailed == 0 && $mallocFailedAfterStep == 0} {
      sqlite3_memdebug_fail -1
      set go 0
    }
  }
}

execsql {
  CREATE TABLE tbl(
    the_first_reasonably_long_column_name that_also_has_quite_a_lengthy_type
  );
  INSERT INTO tbl VALUES(
    'An extra long string. Far too long to be stored in NBFS bytes.'
  );
}

do_stmt_test 1 "SELECT * FROM tbl"

sqlite3_memdebug_fail -1
finish_test

Added test/malloc5.test.



















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# 2005 November 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains test cases focused on the two memory-management APIs, 
# sqlite3_soft_heap_limit() and sqlite3_release_memory().
#
# Prior to version 3.6.2, calling sqlite3_release_memory() or exceeding
# the configured soft heap limit could cause sqlite to upgrade database 
# locks and flush dirty pages to the file system. As of 3.6.2, this is
# no longer the case. In version 3.6.2, sqlite3_release_memory() only
# reclaims clean pages. This test file has been updated accordingly.
#
# $Id: malloc5.test,v 1.22 2009/04/11 19:09:54 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl
db close

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping malloc5 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

# Skip these tests if OMIT_MEMORY_MANAGEMENT was defined at compile time.
ifcapable !memorymanage {
   finish_test
   return
}

sqlite3_soft_heap_limit 0
sqlite3 db test.db

do_test malloc5-1.1 {
  # Simplest possible test. Call sqlite3_release_memory when there is exactly
  # one unused page in a single pager cache. The page cannot be freed, as
  # it is dirty. So sqlite3_release_memory() returns 0.
  #
  execsql {
    PRAGMA auto_vacuum=OFF;
    BEGIN;
    CREATE TABLE abc(a, b, c);
  }
  sqlite3_release_memory
} {0}

do_test malloc5-1.2 {
  # Test that the transaction started in the above test is still active.
  # The lock on the database file should not have been upgraded (this was
  # not the case before version 3.6.2).
  #
  sqlite3 db2 test.db
  execsql { SELECT * FROM sqlite_master } db2
} {}
do_test malloc5-1.3 {
  # Call [sqlite3_release_memory] when there is exactly one unused page 
  # in the cache belonging to db2.
  #
  set ::pgalloc [sqlite3_release_memory]
  expr $::pgalloc > 0
} {1}

do_test malloc5-1.4 {
  # Commit the transaction and open a new one. Read 1 page into the cache.
  # Because the page is not dirty, it is eligible for collection even
  # before the transaction is concluded.
  #
  execsql {
    COMMIT;
    BEGIN;
    SELECT * FROM abc;
  }
  sqlite3_release_memory
} $::pgalloc

do_test malloc5-1.5 {
  # Conclude the transaction opened in the previous [do_test] block. This
  # causes another page (page 1) to become eligible for recycling.
  #
  execsql { COMMIT }
  sqlite3_release_memory
} $::pgalloc

do_test malloc5-1.6 {
  # Manipulate the cache so that it contains two unused pages. One requires 
  # a journal-sync to free, the other does not.
  db2 close
  execsql {
    BEGIN;
    SELECT * FROM abc;
    CREATE TABLE def(d, e, f);
  }
  sqlite3_release_memory 500
} $::pgalloc

do_test malloc5-1.7 {
  # Database should not be locked this time. 
  sqlite3 db2 test.db
  catchsql { SELECT * FROM abc } db2
} {0 {}}
do_test malloc5-1.8 {
  # Try to release another block of memory. This will fail as the only
  # pages currently in the cache are dirty (page 3) or pinned (page 1).
  db2 close
  sqlite3_release_memory 500
} 0
do_test malloc5-1.8 {
  # Database is still not locked.
  #
  sqlite3 db2 test.db
  catchsql { SELECT * FROM abc } db2
} {0 {}}
do_test malloc5-1.9 {
  execsql {
    COMMIT;
  }
} {}

do_test malloc5-2.1 {
  # Put some data in tables abc and def. Both tables are still wholly 
  # contained within their root pages.
  execsql {
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc VALUES(4, 5, 6);
    INSERT INTO def VALUES(7, 8, 9);
    INSERT INTO def VALUES(10,11,12);
  }
} {}
do_test malloc5-2.2 {
  # Load the root-page for table def into the cache. Then query table abc. 
  # Halfway through the query call sqlite3_release_memory(). The goal of this
  # test is to make sure we don't free pages that are in use (specifically, 
  # the root of table abc).
  sqlite3_release_memory
  set nRelease 0
  execsql { 
    BEGIN;
    SELECT * FROM def;
  }
  set data [list]
  db eval {SELECT * FROM abc} {
    incr nRelease [sqlite3_release_memory]
    lappend data $a $b $c
  }
  execsql {
    COMMIT;
  }
  list $nRelease $data
} [list $pgalloc [list 1 2 3 4 5 6]]

do_test malloc5-3.1 {
  # Simple test to show that if two pagers are opened from within this
  # thread, memory is freed from both when sqlite3_release_memory() is
  # called.
  execsql {
    BEGIN;
    SELECT * FROM abc;
  }
  execsql {
    SELECT * FROM sqlite_master;
    BEGIN;
    SELECT * FROM def;
  } db2
  sqlite3_release_memory
} [expr $::pgalloc * 2]
do_test malloc5-3.2 {
  concat \
    [execsql {SELECT * FROM abc; COMMIT}] \
    [execsql {SELECT * FROM def; COMMIT} db2]
} {1 2 3 4 5 6 7 8 9 10 11 12}

db2 close
puts "Highwater mark: [sqlite3_memory_highwater]"

# The following two test cases each execute a transaction in which 
# 10000 rows are inserted into table abc. The first test case is used
# to ensure that more than 1MB of dynamic memory is used to perform
# the transaction. 
#
# The second test case sets the "soft-heap-limit" to 100,000 bytes (0.1 MB)
# and tests to see that this limit is not exceeded at any point during 
# transaction execution.
#
# Before executing malloc5-4.* we save the value of the current soft heap 
# limit in variable ::soft_limit. The original value is restored after 
# running the tests.
#
set ::soft_limit [sqlite3_soft_heap_limit -1]
execsql {PRAGMA cache_size=2000}
do_test malloc5-4.1 {
  execsql {BEGIN;}
  execsql {DELETE FROM abc;}
  for {set i 0} {$i < 10000} {incr i} {
    execsql "INSERT INTO abc VALUES($i, $i, '[string repeat X 100]');"
  }
  execsql {COMMIT;}
  sqlite3_release_memory
  sqlite3_memory_highwater 1
  execsql {SELECT * FROM abc}
  set nMaxBytes [sqlite3_memory_highwater 1]
  puts -nonewline " (Highwater mark: $nMaxBytes) "
  expr $nMaxBytes > 1000000
} {1}
do_test malloc5-4.2 {
  sqlite3_release_memory
  sqlite3_soft_heap_limit 100000
  sqlite3_memory_highwater 1
  execsql {SELECT * FROM abc}
  set nMaxBytes [sqlite3_memory_highwater 1]
  puts -nonewline " (Highwater mark: $nMaxBytes) "
  expr $nMaxBytes <= 100000
} {1}
do_test malloc5-4.3 {
  # Check that the content of table abc is at least roughly as expected.
  execsql {
    SELECT count(*), sum(a), sum(b) FROM abc;
  }
} [list 10000 [expr int(10000.0 * 4999.5)] [expr int(10000.0 * 4999.5)]]

# Restore the soft heap limit.
sqlite3_soft_heap_limit $::soft_limit

# Test that there are no problems calling sqlite3_release_memory when
# there are open in-memory databases.
#
# At one point these tests would cause a seg-fault.
#
do_test malloc5-5.1 {
  db close
  sqlite3 db :memory:
  execsql {
    BEGIN;
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES('abcdefghi', 1234567890, NULL);
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
    INSERT INTO abc SELECT * FROM abc;
  }
  sqlite3_release_memory
} 0
do_test malloc5-5.2 {
  sqlite3_soft_heap_limit 5000
  execsql {
    COMMIT;
    PRAGMA temp_store = memory;
    SELECT * FROM abc ORDER BY a;
  }
  expr 1
} {1}
sqlite3_soft_heap_limit $::soft_limit

#-------------------------------------------------------------------------
# The following test cases (malloc5-6.*) test the new global LRU list
# used to determine the pages to recycle when sqlite3_release_memory is
# called and there is more than one pager open.
#
proc nPage {db} {
  set bt [btree_from_db $db]
  array set stats [btree_pager_stats $bt]
  set stats(page)
}
db close
file delete -force test.db test.db-journal test2.db test2.db-journal

# This block of test-cases (malloc5-6.1.*) prepares two database files
# for the subsequent tests.
do_test malloc5-6.1.1 {
  sqlite3 db test.db
  execsql {
    PRAGMA page_size=1024;
    PRAGMA default_cache_size=10;
  }
  execsql {
    PRAGMA temp_store = memory;
    BEGIN;
    CREATE TABLE abc(a PRIMARY KEY, b, c);
    INSERT INTO abc VALUES(randstr(50,50), randstr(75,75), randstr(100,100));
    INSERT INTO abc 
        SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc;
    INSERT INTO abc 
        SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc;
    INSERT INTO abc 
        SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc;
    INSERT INTO abc 
        SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc;
    INSERT INTO abc 
        SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc;
    INSERT INTO abc 
        SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc;
    COMMIT;
  } 
  copy_file test.db test2.db
  sqlite3 db2 test2.db
  list \
    [expr ([file size test.db]/1024)>20] [expr ([file size test2.db]/1024)>20]
} {1 1}
do_test malloc5-6.1.2 {
  list [execsql {PRAGMA cache_size}] [execsql {PRAGMA cache_size} db2]
} {10 10}

do_test malloc5-6.2.1 {
  execsql {SELECT * FROM abc} db2
  execsql {SELECT * FROM abc} db
  expr [nPage db] + [nPage db2]
} {20}

do_test malloc5-6.2.2 {
  # If we now try to reclaim some memory, it should come from the db2 cache.
  sqlite3_release_memory 3000
  expr [nPage db] + [nPage db2]
} {17}
do_test malloc5-6.2.3 {
  # Access the db2 cache again, so that all the db2 pages have been used
  # more recently than all the db pages. Then try to reclaim 3000 bytes.
  # This time, 3 pages should be pulled from the db cache.
  execsql { SELECT * FROM abc } db2
  sqlite3_release_memory 3000
  expr [nPage db] + [nPage db2]
} {17}

do_test malloc5-6.3.1 {
  # Now open a transaction and update 2 pages in the db2 cache. Then
  # do a SELECT on the db cache so that all the db pages are more recently
  # used than the db2 pages. When we try to free memory, SQLite should
  # free the non-dirty db2 pages, then the db pages, then finally use
  # sync() to free up the dirty db2 pages. The only page that cannot be
  # freed is page1 of db2. Because there is an open transaction, the
  # btree layer holds a reference to page 1 in the db2 cache.
  execsql {
    BEGIN;
    UPDATE abc SET c = randstr(100,100) 
    WHERE rowid = 1 OR rowid = (SELECT max(rowid) FROM abc);
  } db2
  execsql { SELECT * FROM abc } db
  expr [nPage db] + [nPage db2]
} {20}
do_test malloc5-6.3.2 {
  # Try to release 7700 bytes. This should release all the 
  # non-dirty pages held by db2.
  sqlite3_release_memory [expr 7*1100]
  list [nPage db] [nPage db2]
} {10 3}
do_test malloc5-6.3.3 {
  # Try to release another 1000 bytes. This should come fromt the db
  # cache, since all three pages held by db2 are either in-use or diry.
  sqlite3_release_memory 1000
  list [nPage db] [nPage db2]
} {9 3}
do_test malloc5-6.3.4 {
  # Now release 9900 more (about 9 pages worth). This should expunge
  # the rest of the db cache. But the db2 cache remains intact, because
  # SQLite tries to avoid calling sync().
  if {$::tcl_platform(wordSize)==8} {
    sqlite3_release_memory 10177
  } else {
    sqlite3_release_memory 9900
  }
  list [nPage db] [nPage db2]
} {0 3}
do_test malloc5-6.3.5 {
  # But if we are really insistent, SQLite will consent to call sync()
  # if there is no other option. UPDATE: As of 3.6.2, SQLite will not
  # call sync() in this scenario. So no further memory can be reclaimed.
  sqlite3_release_memory 1000
  list [nPage db] [nPage db2]
} {0 3}
do_test malloc5-6.3.6 {
  # The referenced page (page 1 of the db2 cache) will not be freed no
  # matter how much memory we ask for:
  sqlite3_release_memory 31459
  list [nPage db] [nPage db2]
} {0 3}

db2 close

sqlite3_soft_heap_limit $::soft_limit
finish_test
catch {db close}

Added test/malloc6.test.















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 2006 June 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file attempts to check the library in an out-of-memory situation.
#
# $Id: malloc6.test,v 1.5 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping malloc6 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}


set sqlite_os_trace 0
do_malloc_test malloc6-1 -tclprep {
  db close
} -tclbody {
  if {[catch {sqlite3 db test.db}]} {
    error "out of memory"
  }
  sqlite3_extended_result_codes db 1
} -sqlbody {
  DROP TABLE IF EXISTS t1;
  CREATE TABLE IF NOT EXISTS t1(
     a int, b float, c double, d text, e varchar(20),
     primary key(a,b,c)
  );
  CREATE TABLE IF NOT EXISTS t1(
     a int, b float, c double, d text, e varchar(20),
     primary key(a,b,c)
  );
  DROP TABLE IF EXISTS t1;
} 

# Ensure that no file descriptors were leaked.
do_test malloc6-1.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

finish_test

Added test/malloc7.test.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 2006 July 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file contains additional out-of-memory checks (see malloc.tcl)
# added to expose a bug in out-of-memory handling for sqlite3_prepare16().
#
# $Id: malloc7.test,v 1.5 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping malloc7 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}


do_malloc_test malloc7-1 -sqlprep {
  CREATE TABLE t1(a,b,c,d);
  CREATE INDEX i1 ON t1(b,c);
} -tclbody {
  set sql16 [encoding convertto unicode "SELECT * FROM sqlite_master"]
  append sql16 "\00\00"
  set nbyte [string length $sql16]
  set ::STMT [sqlite3_prepare16 db $sql16 $nbyte DUMMY]
  sqlite3_finalize $::STMT
} 


# Ensure that no file descriptors were leaked.
do_test malloc-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

puts open-file-count=$sqlite_open_file_count
finish_test

Added test/malloc8.test.































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# 2007 April 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file contains additional out-of-memory checks (see malloc.tcl)
# added to expose a bug in out-of-memory handling for sqlite3_value_text()
#
# $Id: malloc8.test,v 1.7 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping malloc8 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}


# The setup is a database with UTF-16 encoding that contains a single
# large string.  We will be running lots of queries against this 
# database.  Because we will be extracting the string as UTF-8, there
# is a type conversion that occurs and thus an opportunity for malloc()
# to fail and for sqlite3_value_text() to return 0 even though
# sqlite3_value_type() returns SQLITE_TEXT.
#

do_malloc_test malloc8-1 -sqlprep {
  PRAGMA encoding='UTF-16';
  CREATE TABLE t1(a);
  INSERT INTO t1 
  VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
} -sqlbody {
  SELECT lower(a), upper(a), quote(a), trim(a), trim('x',a) FROM t1;
}
do_malloc_test malloc8-2 -sqlprep {
  PRAGMA encoding='UTF-16';
  CREATE TABLE t1(a);
  INSERT INTO t1 
  VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
} -sqlbody {
  SELECT replace(a,'x','y'), replace('x',a,'y'), replace('x','y',a)
    FROM t1;
}
do_malloc_test malloc8-3 -sqlprep {
  PRAGMA encoding='UTF-16';
  CREATE TABLE t1(a);
  INSERT INTO t1 
  VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
} -sqlbody {
  SELECT length(a), substr(a, 4, 4) FROM t1;
}
ifcapable datetime {
  do_malloc_test malloc8-4 -sqlprep {
    PRAGMA encoding='UTF-16';
    CREATE TABLE t1(a);
    INSERT INTO t1 
    VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
  } -sqlbody {
    SELECT julianday(a,a) FROM t1;
  }
}
do_malloc_test malloc8-5 -sqlprep {
  PRAGMA encoding='UTF-16';
  CREATE TABLE t1(a);
  INSERT INTO t1 
  VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
} -sqlbody {
  SELECT 1 FROM t1 WHERE a LIKE 'hello' ESCAPE NULL;
}
do_malloc_test malloc8-6 -sqlprep {
  PRAGMA encoding='UTF-16';
  CREATE TABLE t1(a);
  INSERT INTO t1 
  VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
} -sqlbody {
  SELECT hex(randomblob(100));
}

# Ensure that no file descriptors were leaked.
do_test malloc-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

finish_test

Added test/malloc9.test.







































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 2007 April 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file contains additional out-of-memory checks (see malloc.tcl)
# added to expose a bug in out-of-memory handling for sqlite3_prepare().
#
# $Id: malloc9.test,v 1.5 2008/04/04 12:21:26 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping malloc9 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}


do_malloc_test malloc-9.1 -tclprep {
  set sql {CREATE TABLE t1(x)}
  set sqlbytes [string length $sql]
  append sql {; INSERT INTO t1 VALUES(1)}
} -tclbody {
  if {[catch {sqlite3_prepare db $sql $sqlbytes TAIL} STMT]} {
    set msg $STMT
    set STMT {}
    error $msg
  }
} -cleanup {
  if {$STMT!=""} {
    sqlite3_finalize $STMT
  }
}

# Ensure that no file descriptors were leaked.
do_test malloc9-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

finish_test

Added test/mallocA.test.





























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 2007 April 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file contains additional out-of-memory checks (see malloc.tcl).
#
# $Id: mallocA.test,v 1.8 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocA tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}


# Construct a test database
#
file delete -force test.db.bu
db eval {
  CREATE TABLE t1(a COLLATE NOCASE,b,c);
  INSERT INTO t1 VALUES(1,2,3);
  INSERT INTO t1 VALUES(1,2,4);
  INSERT INTO t1 VALUES(2,3,4);
  CREATE INDEX t1i1 ON t1(a);
  CREATE INDEX t1i2 ON t1(b,c);
  CREATE TABLE t2(x,y,z);
}
db close
file copy test.db test.db.bu


do_malloc_test mallocA-1 -testdb test.db.bu -sqlbody {
  ANALYZE
}
do_malloc_test mallocA-1.1 -testdb test.db.bu -sqlbody {
  ANALYZE t1
}
do_malloc_test mallocA-1.2 -testdb test.db.bu -sqlbody {
  ANALYZE main
}
do_malloc_test mallocA-1.3 -testdb test.db.bu -sqlbody {
  ANALYZE main.t1
}
ifcapable reindex {
  do_malloc_test mallocA-2 -testdb test.db.bu -sqlbody {
    REINDEX;
  }
  do_malloc_test mallocA-3 -testdb test.db.bu -sqlbody {
    REINDEX t1;
  }
  do_malloc_test mallocA-4 -testdb test.db.bu -sqlbody {
    REINDEX main.t1;
  }
  do_malloc_test mallocA-5 -testdb test.db.bu -sqlbody {
    REINDEX nocase;
  }
}

# Ensure that no file descriptors were leaked.
do_test malloc-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

file delete -force test.db.bu
finish_test

Added test/mallocAll.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all out-of-memory tests.
#
# $Id: mallocAll.test,v 1.1 2007/11/26 13:36:00 drh Exp $

proc lshift {lvar} {
  upvar $lvar l
  set ret [lindex $l 0]
  set l [lrange $l 1 end]
  return $ret
}
while {[set arg [lshift argv]] != ""} {
  switch -- $arg {
    -sharedpagercache {
      sqlite3_enable_shared_cache 1
    }
    default {
      set argv [linsert $argv 0 $arg]
      break
    }
  }
}

set testdir [file dirname $argv0]
source $testdir/tester.tcl
rename finish_test really_finish_test
proc finish_test {} {}
set ISQUICK 1

set EXCLUDE {
  mallocAll.test
}

if {[sqlite3 -has-codec]} {
  # lappend EXCLUDE \
  #  conflict.test
}


# Files to include in the test.  If this list is empty then everything
# that is not in the EXCLUDE list is run.
#
set INCLUDE {
}

foreach testfile [lsort -dictionary [glob $testdir/*malloc*.test]] {
  set tail [file tail $testfile]
  if {[lsearch -exact $EXCLUDE $tail]>=0} continue
  if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue
  source $testfile
  catch {db close}
  if {$sqlite_open_file_count>0} {
    puts "$tail did not close all files: $sqlite_open_file_count"
    incr nErr
    lappend ::failList $tail
    set sqlite_open_file_count 0
  }
}
source $testdir/misuse.test

set sqlite_open_file_count 0
really_finish_test

Added test/mallocB.test.







































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 2007 May 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file contains additional out-of-memory checks (see malloc.tcl).
# These were all discovered by fuzzy generation of SQL. Apart from
# that they have little in common.
#
#
# $Id: mallocB.test,v 1.9 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocB tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}
source $testdir/malloc_common.tcl

do_malloc_test mallocB-1 -sqlbody {SELECT - 456}
do_malloc_test mallocB-2 -sqlbody {SELECT - 456.1}
do_malloc_test mallocB-3 -sqlbody {SELECT random()}
do_malloc_test mallocB-4 -sqlbody {SELECT length(zeroblob(1000))}
ifcapable subquery {
  do_malloc_test mallocB-5 -sqlbody {SELECT * FROM (SELECT 1) GROUP BY 1;}
}

# The following test checks that there are no resource leaks following a
# malloc() failure in sqlite3_set_auxdata().
#
# Note: This problem was not discovered by fuzzy generation of SQL. Not
# that it really matters.
#
do_malloc_test mallocB-6 -sqlbody { SELECT test_auxdata('hello world'); }

do_malloc_test mallocB-7 -sqlbody {
  SELECT strftime(hex(randomblob(50)) || '%Y', 'now')
}

finish_test

Added test/mallocC.test.























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# 2007 Aug 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# 
# This file tests aspects of the malloc failure while parsing
# CREATE TABLE statements in auto_vacuum mode.
#
# $Id: mallocC.test,v 1.10 2009/04/11 16:27:50 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocC tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

proc do_mallocC_test {tn args} {
  array set ::mallocopts $args
  #set sum [allcksum db]

  for {set ::n 1} {true} {incr ::n} {

    # Run the SQL. Malloc number $::n is set to fail. A malloc() failure
    # may or may not be reported.
    sqlite3_memdebug_fail $::n -repeat 1
    do_test mallocC-$tn.$::n.1 {
      set res [catchsql [string trim $::mallocopts(-sql)]]
      set rc [expr { 
        0==[string compare $res {1 {out of memory}}] ||
        [db errorcode] == 3082 ||
        0==[lindex $res 0]
      }]
      if {$rc!=1} {
        puts "Error: $res"
      }
      set rc
    } {1}

    # If $::n is greater than the number of malloc() calls required to
    # execute the SQL, then this test is finished. Break out of the loop.
    set nFail [sqlite3_memdebug_fail -1]
    if {$nFail==0} {
      break
    }

    # Recover from the malloc failure.
    #
    # Update: The new malloc() failure handling means that a transaction may
    # still be active even if a malloc() has failed. But when these tests were
    # written this was not the case. So do a manual ROLLBACK here so that the
    # tests pass.
    do_test mallocC-$tn.$::n.2 {
      catch {
        execsql {
          ROLLBACK;
        }
      }
      expr 0
    } {0}

    # Checksum the database.
    #do_test mallocC-$tn.$::n.3 {
    #  allcksum db
    #} $sum

    #integrity_check mallocC-$tn.$::n.4
  if {$::nErr>1} return
  }
  unset ::mallocopts
}

sqlite3_extended_result_codes db 1

execsql {
  PRAGMA auto_vacuum=1;
  CREATE TABLE t0(a, b, c);
}

# The number of memory allocation failures is different on 64-bit
# and 32-bit systems due to larger structures on 64-bit systems
# overflowing the lookaside more often.  To debug problems, it is
# sometimes helpful to reduce the size of the lookaside allocation
# blocks.  But this is normally disabled.
#
if {0} {
  db close
  sqlite3_shutdown
  sqlite3_config_lookaside 50 500
  sqlite3_initialize
  autoinstall_test_functions
  sqlite3 db test.db
}

do_mallocC_test 1 -sql {
  BEGIN;
  -- Allocate 32 new root pages. This will exercise the 'extract specific 
  -- page from the freelist' code when in auto-vacuum mode (see the
  -- allocatePage() routine in btree.c).
  CREATE TABLE t1(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t2(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t3(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t4(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t5(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t6(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t7(a UNIQUE, b UNIQUE, c UNIQUE);
  CREATE TABLE t8(a UNIQUE, b UNIQUE, c UNIQUE);

  ROLLBACK;
}

finish_test

Added test/mallocD.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2007 Aug 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: mallocD.test,v 1.6 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocD tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

db close
sqlite3_simulate_device -char atomic
sqlite3 db test.db -vfs devsym

set PREP { 
  PRAGMA page_size = 1024;
  CREATE TABLE abc(a, b, c);
}

do_malloc_test mallocD-1 -sqlprep $PREP -sqlbody { 
  INSERT INTO abc VALUES(1, 2, 3);
}

do_malloc_test mallocD-2 -sqlprep $PREP -sqlbody {
  BEGIN;
  INSERT INTO abc VALUES(1, 2, 3);
  INSERT INTO abc VALUES(4, 5, 6);
  ROLLBACK;
}

do_malloc_test mallocD-3 -sqlprep $PREP -sqlbody {
  BEGIN;
  INSERT INTO abc VALUES(1, 2, 3);
  INSERT INTO abc VALUES(4, 5, randstr(1500,1500));
  COMMIT;
}

ifcapable attach {
  do_malloc_test mallocD-4 -sqlprep $PREP -sqlbody {
    ATTACH 'test2.db' AS aux;
    BEGIN;
    CREATE TABLE aux.def(d, e, f);
    INSERT INTO abc VALUES(4, 5, 6);
    COMMIT;
  }
}

sqlite3_simulate_device -char {}

finish_test

Added test/mallocE.test.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 2007 Aug 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks that tickets #2784 and #2789 have been fixed.
# 
# $Id: mallocE.test,v 1.3 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocE tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

# ticket #2784
#
set PREP { 
  PRAGMA page_size = 1024;
  CREATE TABLE t1(a, b, c);
  CREATE TABLE t2(x, y, z);
}
do_malloc_test mallocE-1 -sqlprep $PREP -sqlbody { 
  SELECT p, q FROM (SELECT a+b AS p, b+c AS q FROM t1, t2 WHERE c>5)
              LEFT JOIN t2 ON p=x;
}

# Ticket #2789
#
do_malloc_test mallocE-2 -sqlprep $PREP -sqlbody { 
  SELECT x, y2 FROM (SELECT a+b AS x, b+c AS y2 FROM t1, t2 WHERE c>5)
              LEFT JOIN t2 USING(x) WHERE y2>11;
}


finish_test

Added test/mallocF.test.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 2007 Aug 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks that tickets #2794, #2795, #2796, and #2797
# have been fixed.
# 
# $Id: mallocF.test,v 1.4 2008/02/18 22:24:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocF tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

# tickets #2794 and #2795 and #2797
#
set PREP {
  CREATE TABLE t1(x,y);
  INSERT INTO t1 VALUES('abc123', 5);
  INSERT INTO t1 VALUES('xyz987', 42);
}
do_malloc_test malloeF-1 -sqlprep $PREP -sqlbody {
  SELECT * FROM t1 WHERE x GLOB 'abc*'
}

# ticket #2796
#
set PREP {
  CREATE TABLE t1(x PRIMARY KEY,y UNIQUE);
  INSERT INTO t1 VALUES('abc123', 5);
  INSERT INTO t1 VALUES('xyz987', 42);
}
do_malloc_test malloeF-2 -sqlprep $PREP -sqlbody {
  SELECT x FROM t1
   WHERE y=1 OR y=2 OR y=3 OR y=4 OR y=5
      OR y=6 OR y=7 OR y=8 OR y=9 OR y=10
      OR y=11 OR y=12 OR y=13 OR y=14 OR y=15
      OR y=x
}

set PREP {
  CREATE TABLE t1(x PRIMARY KEY,y UNIQUE);
  INSERT INTO t1 VALUES('abc123', 5);
  INSERT INTO t1 VALUES('xyz987', 42);
}
do_malloc_test malloeF-3 -sqlprep $PREP -sqlbody {
  SELECT x FROM t1 WHERE y BETWEEN 10 AND 29
}

# Ticket #2843
#
set PREP {
  CREATE TABLE t1(x);
  CREATE TRIGGER r1 BEFORE INSERT ON t1 BEGIN
    SELECT 'hello';
  END;
}
do_malloc_test mallocF-4 -sqlprep $PREP -sqlbody {
  INSERT INTO t1 VALUES(random());
}

finish_test

Added test/mallocG.test.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 2007 Aug 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks malloc failures in various obscure operations.
# 
# $Id: mallocG.test,v 1.5 2008/08/01 18:47:02 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Only run these tests if memory debugging is turned on.
#
if {!$MEMDEBUG} {
   puts "Skipping mallocG tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

# Malloc failures while opening a database connection.
#
do_malloc_test mallocG-1 -tclbody {
  db close
  sqlite3 db test.db
}

do_malloc_test mallocG-2 -sqlprep {
  CREATE TABLE t1(x, y);
  CREATE TABLE t2(x INTEGER PRIMARY KEY);
} -sqlbody {
  SELECT y FROM t1 WHERE x IN t2;
}

do_malloc_test mallocG-3 -sqlprep {
  CREATE TABLE t1(x UNIQUE);
  INSERT INTO t1 VALUES ('hello');
  INSERT INTO t1 VALUES ('out there');
} -sqlbody {
  SELECT * FROM t1
   WHERE x BETWEEN 'a' AND 'z'
     AND x BETWEEN 'c' AND 'w'
     AND x BETWEEN 'e' AND 'u'
     AND x BETWEEN 'g' AND 'r'
     AND x BETWEEN 'i' AND 'q'
     AND x BETWEEN 'i' AND 'm'
}

proc utf16 {utf8} {
  set utf16 [encoding convertto unicode $utf8]
  append utf16 "\x00\x00"
  return $utf16
}

do_malloc_test mallocG-4 -tclbody {
  set rc [sqlite3_complete16 [utf16 "SELECT * FROM t1;"]]
  if {$rc==1} {set rc 0} {error "out of memory"}
  set rc
}

finish_test

Added test/mallocH.test.



















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# 2008 August 01
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks malloc failures in various obscure operations.
# 
# $Id: mallocH.test,v 1.2 2008/08/01 20:10:09 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Malloc failures in journaling of in-memory databases.
#
do_malloc_test mallocH-1 -tclprep {
  db close
  sqlite3 db :memory:
  db eval {
    CREATE TABLE t1(x UNIQUE, y);
    INSERT INTO t1 VALUES(1,2);
  }
} -sqlbody {
  INSERT INTO t1 SELECT x+1, y+100 FROM t1;
}

# Malloc failures while parsing a CASE expression.
#
do_malloc_test mallocH-2 -sqlbody {
   SELECT CASE WHEN 1 THEN 1 END;
}

# Malloc failures while parsing a EXISTS(SELECT ...)
#
do_malloc_test mallocH-3 -sqlbody {
   SELECT 3+EXISTS(SELECT * FROM sqlite_master);
}

# Malloc failures within the replace() function.
#
do_malloc_test mallocH-3 -sqlbody {
   SELECT replace('ababa','a','xyzzy');
}

# Malloc failures during EXPLAIN.
#
ifcapable explain {
  do_malloc_test mallocH-4 -sqlprep {
     CREATE TABLE abc(a PRIMARY KEY, b, c);
  } -sqlbody {
     EXPLAIN SELECT * FROM abc AS t2 WHERE rowid=1;
     EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 WHERE rowid=1;
  }
}

# Malloc failure during integrity_check pragma.
#
do_malloc_test mallocH-5 -sqlprep {
   CREATE TABLE t1(a PRIMARY KEY, b UNIQUE);
   CREATE TABLE t2(x,y);
   INSERT INTO t1 VALUES(1,2);
   INSERT INTO t2 SELECT * FROM t1;
} -sqlbody {
   PRAGMA integrity_check;
}

finish_test

Added test/mallocI.test.































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 2008 August 01
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks malloc failures in various obscure operations.
# 
# $Id: mallocI.test,v 1.3 2009/08/10 04:26:39 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

# Malloc failures in a view.
#
do_malloc_test mallocI-1 -sqlprep {
  CREATE TABLE t1(a,b,c,d);
  CREATE VIEW v1 AS SELECT a*b, c*d FROM t1 ORDER BY b-d;
} -sqlbody {
  SELECT * FROM v1
}

# Malloc failure while trying to service a pragma on a TEMP database.
#
do_malloc_test mallocI-2 -sqlbody {
  PRAGMA temp.page_size
}

# Malloc failure while creating a table from a SELECT statement.
#
do_malloc_test mallocI-3 -sqlprep {
  CREATE TABLE t1(a,b,c);
} -sqlbody {
  CREATE TABLE t2 AS SELECT b,c FROM t1;
}

# This tests that a malloc failure that occurs while passing the schema
# does not result in a SHARED lock being left on the database file.
#
do_malloc_test mallocI-4 -tclprep {
  sqlite3 db2 test.db
  db2 eval {
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(a, b, c);
  }
} -sqlbody {
  SELECT * FROM t1
} -cleanup {
  do_test mallocI-4.$::n.2 {
    # If this INSERT is possible then [db] does not hold a shared lock
    # on the database file.
    catchsql { INSERT INTO t1 VALUES(1, 2, 3) } db2
  } {0 {}}
}
catch { db2 close }

finish_test

Added test/mallocJ.test.



















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# 2008 August 01
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks malloc failures in LIMIT operations for 
# UPDATE/DELETE statements.
# 
# $Id: mallocJ.test,v 1.6 2009/01/09 02:49:32 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

ifcapable {update_delete_limit} {

  do_malloc_test mallocJ-1 -sqlprep {
    DROP TABLE IF EXISTS t1;
    CREATE TABLE t1(x int, y int);
    INSERT INTO t1 VALUES(1,1);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(2,1);
    INSERT INTO t1 VALUES(2,2);
    INSERT INTO t1 VALUES(2,3);
  } -sqlbody {
    UPDATE t1 SET x=1 ORDER BY y LIMIT 2 OFFSET 2;
    UPDATE t1 SET x=2 WHERE y=1 ORDER BY y LIMIT 2 OFFSET 2;
    DELETE FROM t1 WHERE x=1 ORDER BY y LIMIT 2 OFFSET 2;
    DELETE FROM t1 ORDER BY y LIMIT 2 OFFSET 2;
  }

}

# ticket #3467
do_malloc_test mallocJ-2 -sqlprep {
  CREATE TABLE t1(a,b);
  INSERT INTO t1 VALUES(1,2);
  PRAGMA vdbe_trace=ON;
} -sqlbody {
  SELECT a, b, 'abc' FROM t1
    UNION
    SELECT b, a, 'xyz' FROM t1
    ORDER BY 2, 3;
}

# ticket #3478
do_malloc_test mallocJ-3 -sqlbody {
  EXPLAIN COMMIT
}

# ticket #3485
do_malloc_test mallocJ-4 -sqlprep {
  CREATE TABLE t1(a,b,c);
  CREATE TABLE t2(x,y,z);
} -sqlbody {
  SELECT * FROM (SELECT a,b FROM t1 UNION ALL SELECT x, y FROM t2) ORDER BY 1
}

# coverage testing
do_malloc_test mallocJ-5 -sqlprep {
  CREATE TABLE t1(["a"]);
} -sqlbody {
  SELECT * FROM t1
}

finish_test

Added test/mallocK.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2008 August 01
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This test script checks malloc failures in WHERE clause analysis.
# 
# $Id: mallocK.test,v 1.3 2009/01/08 21:00:03 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

set sql {SELECT * FROM t1, t2 WHERE (a=1 OR a=2)}
for {set x 1} {$x<5} {incr x} {
  append sql " AND b=y"
  do_malloc_test mallocK-1.$x -sqlbody $sql -sqlprep {
    CREATE TABLE t1(a,b);
    CREATE TABLE t2(x,y);
  }
}

set sql {SELECT * FROM t1 WHERE a GLOB 'xyz*' AND (a=1 OR a=2)}
for {set x 1} {$x<5} {incr x} {
  append sql " AND b!=$x"
  do_malloc_test mallocK-2.$x -sqlbody $sql -sqlprep {
    CREATE TABLE t1(a,b);
  }
}

set sql {SELECT * FROM t1 WHERE a BETWEEN 5 AND 10}
for {set x 1} {$x<5} {incr x} {
  append sql " AND b=$x"
  do_malloc_test mallocK-3.$x -sqlbody $sql -sqlprep {
    CREATE TABLE t1(a,b);
  }
}

set sql {SELECT * FROM t1 WHERE b=0}
for {set x 1} {$x<5} {incr x} {
  set term "(b=$x"
  for {set y 0} {$y<$x} {incr y} {
    append term " AND a!=$y"
  }
  append sql " OR $term)"
  do_malloc_test mallocK-4.$x -sqlbody $sql -sqlprep {
    CREATE TABLE t1(a,b);
  }
}

ifcapable vtab {
  set sql {SELECT * FROM t2 WHERE a MATCH 'xyz'}
  for {set x 1} {$x<5} {incr x} {
    append sql " AND b!=$x"
    do_malloc_test mallocK-5.$x -sqlbody $sql -tclprep {
      register_echo_module [sqlite3_connection_pointer db]
      db eval {
        CREATE TABLE t1(a,b);
        CREATE VIRTUAL TABLE t2 USING echo(t1);
      }
    }
  }
}


finish_test

Added test/malloc_common.tcl.















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# 2007 May 05
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains common code used by many different malloc tests
# within the test suite.
#
# $Id: malloc_common.tcl,v 1.22 2008/09/23 16:41:30 danielk1977 Exp $

# If we did not compile with malloc testing enabled, then do nothing.
#
ifcapable builtin_test {
  set MEMDEBUG 1
} else {
  set MEMDEBUG 0
  return 0
}

# Usage: do_malloc_test <test number> <options...>
#
# The first argument, <test number>, is an integer used to name the
# tests executed by this proc. Options are as follows:
#
#     -tclprep          TCL script to run to prepare test.
#     -sqlprep          SQL script to run to prepare test.
#     -tclbody          TCL script to run with malloc failure simulation.
#     -sqlbody          TCL script to run with malloc failure simulation.
#     -cleanup          TCL script to run after the test.
#
# This command runs a series of tests to verify SQLite's ability
# to handle an out-of-memory condition gracefully. It is assumed
# that if this condition occurs a malloc() call will return a
# NULL pointer. Linux, for example, doesn't do that by default. See
# the "BUGS" section of malloc(3).
#
# Each iteration of a loop, the TCL commands in any argument passed
# to the -tclbody switch, followed by the SQL commands in any argument
# passed to the -sqlbody switch are executed. Each iteration the
# Nth call to sqliteMalloc() is made to fail, where N is increased
# each time the loop runs starting from 1. When all commands execute
# successfully, the loop ends.
#
proc do_malloc_test {tn args} {
  array unset ::mallocopts 
  array set ::mallocopts $args

  if {[string is integer $tn]} {
    set tn malloc-$tn
  }
  if {[info exists ::mallocopts(-start)]} {
    set start $::mallocopts(-start)
  } else {
    set start 0
  }
  if {[info exists ::mallocopts(-end)]} {
    set end $::mallocopts(-end)
  } else {
    set end 50000
  }
  save_prng_state

  foreach ::iRepeat {0 10000000} {
    set ::go 1
    for {set ::n $start} {$::go && $::n <= $end} {incr ::n} {

      # If $::iRepeat is 0, then the malloc() failure is transient - it
      # fails and then subsequent calls succeed. If $::iRepeat is 1, 
      # then the failure is persistent - once malloc() fails it keeps
      # failing.
      #
      set zRepeat "transient"
      if {$::iRepeat} {set zRepeat "persistent"}
      restore_prng_state
      foreach file [glob -nocomplain test.db-mj*] {file delete -force $file}

      do_test ${tn}.${zRepeat}.${::n} {
  
        # Remove all traces of database files test.db and test2.db 
        # from the file-system. Then open (empty database) "test.db" 
        # with the handle [db].
        # 
        catch {db close} 
        catch {file delete -force test.db}
        catch {file delete -force test.db-journal}
        catch {file delete -force test2.db}
        catch {file delete -force test2.db-journal}
        if {[info exists ::mallocopts(-testdb)]} {
          file copy $::mallocopts(-testdb) test.db
        }
        catch { sqlite3 db test.db }
        if {[info commands db] ne ""} {
          sqlite3_extended_result_codes db 1
        }
        sqlite3_db_config_lookaside db 0 0 0
  
        # Execute any -tclprep and -sqlprep scripts.
        #
        if {[info exists ::mallocopts(-tclprep)]} {
          eval $::mallocopts(-tclprep)
        }
        if {[info exists ::mallocopts(-sqlprep)]} {
          execsql $::mallocopts(-sqlprep)
        }
  
        # Now set the ${::n}th malloc() to fail and execute the -tclbody 
        # and -sqlbody scripts.
        #
        sqlite3_memdebug_fail $::n -repeat $::iRepeat
        set ::mallocbody {}
        if {[info exists ::mallocopts(-tclbody)]} {
          append ::mallocbody "$::mallocopts(-tclbody)\n"
        }
        if {[info exists ::mallocopts(-sqlbody)]} {
          append ::mallocbody "db eval {$::mallocopts(-sqlbody)}"
        }

        # The following block sets local variables as follows:
        #
        #     isFail  - True if an error (any error) was reported by sqlite.
        #     nFail   - The total number of simulated malloc() failures.
        #     nBenign - The number of benign simulated malloc() failures.
        #
        set isFail [catch $::mallocbody msg]
        set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign]
        # puts -nonewline " (isFail=$isFail nFail=$nFail nBenign=$nBenign) "

        # If one or more mallocs failed, run this loop body again.
        #
        set go [expr {$nFail>0}]

        if {($nFail-$nBenign)==0} {
          if {$isFail} {
            set v2 $msg
          } else {
            set isFail 1
            set v2 1
          }
        } elseif {!$isFail} {
          set v2 $msg
        } elseif {
          [info command db]=="" || 
          [db errorcode]==7 ||
          $msg=="out of memory"
        } {
          set v2 1
        } else {
          set v2 $msg
          puts [db errorcode]
        }
        lappend isFail $v2
      } {1 1}
  
      if {[info exists ::mallocopts(-cleanup)]} {
        catch [list uplevel #0 $::mallocopts(-cleanup)] msg
      }
    }
  }
  unset ::mallocopts
  sqlite3_memdebug_fail -1
}

Added test/manydb.test.













































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# 2005 October 3
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests the ability of the library to open
# many different databases at the same time without leaking memory.
#
# $Id: manydb.test,v 1.4 2008/11/21 00:10:35 aswift Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

set N 300
# if we're using proxy locks, we use 5 filedescriptors for a db
# that is open and in the middle of writing changes, normally
# sqlite uses 3 (proxy locking adds the conch and the local lock)
set using_proxy 0
foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] {
  set using_proxy value
}
set num_fd_per_openwrite_db 3
if {$using_proxy>0} {
  set num_fd_per_openwrite_db 5
} 

# First test how many file descriptors are available for use. To open a
# database for writing SQLite requires 3 file descriptors (the database, the
# journal and the directory).
set filehandles {}
catch {
  for {set i 0} {$i<($N * 3)} {incr i} {
    lappend filehandles [open testfile.1 w]
  }
}
foreach fd $filehandles {
  close $fd
}
catch {
  file delete -force testfile.1
}
set N [expr $i / $num_fd_per_openwrite_db]

# Create a bunch of random database names
#
unset -nocomplain dbname
unset -nocomplain used
for {set i 0} {$i<$N} {incr i} {
  while 1 {
    set name test-[format %08x [expr {int(rand()*0x7fffffff)}]].db
    if {[info exists used($name)]} continue
    set dbname($i) $name
    set used($name) $i
    break
  }
}

# Create a bunch of databases
#
for {set i 0} {$i<$N} {incr i} {
  do_test manydb-1.$i {
    sqlite3 db$i $dbname($i)
    execsql {
       CREATE TABLE t1(a,b);
       BEGIN;
       INSERT INTO t1 VALUES(1,2);
    } db$i
  } {}
}

# Finish the transactions
#
for {set i 0} {$i<$N} {incr i} {
  do_test manydb-2.$i {
    execsql {
       COMMIT;
       SELECT * FROM t1;
    } db$i
  } {1 2}
}


# Close the databases and erase the files.
#
for {set i 0} {$i<$N} {incr i} {
  do_test manydb-3.$i {
    db$i close
    file delete -force $dbname($i)
  } {}
}




finish_test

Added test/memdb.test.













































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is in-memory database backend.
#
# $Id: memdb.test,v 1.19 2009/05/18 16:04:38 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable memorydb {

# In the following sequence of tests, compute the MD5 sum of the content
# of a table, make lots of modifications to that table, then do a rollback.
# Verify that after the rollback, the MD5 checksum is unchanged.
#
# These tests were browed from trans.tcl.
#
do_test memdb-1.1 {
  db close
  sqlite3 db :memory:
  # sqlite3 db test.db
  execsql {
    BEGIN;
    CREATE TABLE t3(x TEXT);
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    COMMIT;
    SELECT count(*) FROM t3;
  }
} {1024}

# The following procedure computes a "signature" for table "t3".  If
# T3 changes in any way, the signature should change.  
#
# This is used to test ROLLBACK.  We gather a signature for t3, then
# make lots of changes to t3, then rollback and take another signature.
# The two signatures should be the same.
#
proc signature {{fn {}}} {
  set rx [db eval {SELECT x FROM t3}]
  # set r1 [md5 $rx\n]
  if {$fn!=""} {
    # set fd [open $fn w]
    # puts $fd $rx
    # close $fd
  }
  # set r [db eval {SELECT count(*), md5sum(x) FROM t3}]
  # puts "SIG($fn)=$r1"
  return [list [string length $rx] $rx]
}

# Do rollbacks.  Make sure the signature does not change.
#
set limit 10
for {set i 2} {$i<=$limit} {incr i} {
  set ::sig [signature one]
  # puts "sig=$sig"
  set cnt [lindex $::sig 0]
  if {$i%2==0} {
    execsql {PRAGMA synchronous=FULL}
  } else {
    execsql {PRAGMA synchronous=NORMAL}
  }
  do_test memdb-1.$i.1-$cnt {
     execsql {
       BEGIN;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       ROLLBACK;
     }
     set sig2 [signature two]
  } $sig
  # puts "sig2=$sig2"
  # if {$sig2!=$sig} exit
  do_test memdb-1.$i.2-$cnt {
     execsql {
       BEGIN;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       ROLLBACK;
     }
     signature
  } $sig
  if {$i<$limit} {
    do_test memdb-1.$i.9-$cnt {
       execsql {
         INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0;
       }
    } {}
  }
  set ::pager_old_format 0
}

integrity_check memdb-2.1

do_test memdb-3.1 {
  execsql {
    CREATE TABLE t4(a,b,c,d);
    BEGIN;
    INSERT INTO t4 VALUES(1,2,3,4);
    SELECT * FROM t4;
  }
} {1 2 3 4}
do_test memdb-3.2 {
  execsql {
    SELECT name FROM sqlite_master WHERE type='table';
  }
} {t3 t4}
do_test memdb-3.3 {
  execsql {
    DROP TABLE t4;
    SELECT name FROM sqlite_master WHERE type='table';
  }
} {t3}
do_test memdb-3.4 {
  execsql {
    ROLLBACK;
    SELECT name FROM sqlite_master WHERE type='table';
  }
} {t3 t4}

# Create tables for the first group of tests.
#
do_test memdb-4.0 {
  execsql {
    CREATE TABLE t1(a, b, c, UNIQUE(a,b));
    CREATE TABLE t2(x);
    SELECT c FROM t1 ORDER BY c;
  }
} {}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   conf   The conflict resolution algorithm on the BEGIN statement
#   cmd    An INSERT or REPLACE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "c" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t2
#
foreach {i conf cmd t0 t1 t2} {
  1 {}       INSERT                  1 {}  1
  2 {}       {INSERT OR IGNORE}      0 3   1
  3 {}       {INSERT OR REPLACE}     0 4   1
  4 {}       REPLACE                 0 4   1
  5 {}       {INSERT OR FAIL}        1 {}  1
  6 {}       {INSERT OR ABORT}       1 {}  1
  7 {}       {INSERT OR ROLLBACK}    1 {}  {}
} {

  # All tests after test 1 depend on conflict resolution. So end the
  # loop if that is not available in this build.
  ifcapable !conflict {if {$i>1} break}

  do_test memdb-4.$i {
    if {$conf!=""} {set conf "ON CONFLICT $conf"}
    set r0 [catch {execsql [subst {
      DELETE FROM t1;
      DELETE FROM t2;
      INSERT INTO t1 VALUES(1,2,3);
      BEGIN $conf;
      INSERT INTO t2 VALUES(1); 
      $cmd INTO t1 VALUES(1,2,4);
    }]} r1]
    catch {execsql {COMMIT}}
    if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]}
    set r2 [execsql {SELECT x FROM t2}]
    list $r0 $r1 $r2
  } [list $t0 $t1 $t2]
}

do_test memdb-5.0 {
  execsql {
    DROP TABLE t2;
    DROP TABLE t3;
    CREATE TABLE t2(a,b,c);
    INSERT INTO t2 VALUES(1,2,1);
    INSERT INTO t2 VALUES(2,3,2);
    INSERT INTO t2 VALUES(3,4,1);
    INSERT INTO t2 VALUES(4,5,4);
    SELECT c FROM t2 ORDER BY b;
    CREATE TABLE t3(x);
    INSERT INTO t3 VALUES(1);
  }
} {1 2 1 4}

# Six columns of configuration data as follows:
#
#   i      The reference number of the test
#   conf1  The conflict resolution algorithm on the UNIQUE constraint
#   conf2  The conflict resolution algorithm on the BEGIN statement
#   cmd    An UPDATE command to execute against table t1
#   t0     True if there is an error from $cmd
#   t1     Content of "b" column of t1 assuming no error in $cmd
#   t2     Content of "x" column of t3
#
foreach {i conf1 conf2 cmd t0 t1 t2} {
  1 {}       {}       UPDATE                  1 {6 7 8 9}  1
  2 REPLACE  {}       UPDATE                  0 {7 6 9}    1
  3 IGNORE   {}       UPDATE                  0 {6 7 3 9}  1
  4 FAIL     {}       UPDATE                  1 {6 7 3 4}  1
  5 ABORT    {}       UPDATE                  1 {1 2 3 4}  1
  6 ROLLBACK {}       UPDATE                  1 {1 2 3 4}  0
  7 REPLACE  {}       {UPDATE OR IGNORE}      0 {6 7 3 9}  1
  8 IGNORE   {}       {UPDATE OR REPLACE}     0 {7 6 9}    1
  9 FAIL     {}       {UPDATE OR IGNORE}      0 {6 7 3 9}  1
 10 ABORT    {}       {UPDATE OR REPLACE}     0 {7 6 9}    1
 11 ROLLBACK {}       {UPDATE OR IGNORE}      0 {6 7 3 9}   1
 12 {}       {}       {UPDATE OR IGNORE}      0 {6 7 3 9}  1
 13 {}       {}       {UPDATE OR REPLACE}     0 {7 6 9}    1
 14 {}       {}       {UPDATE OR FAIL}        1 {6 7 3 4}  1
 15 {}       {}       {UPDATE OR ABORT}       1 {1 2 3 4}  1
 16 {}       {}       {UPDATE OR ROLLBACK}    1 {1 2 3 4}  0
} {
  # All tests after test 1 depend on conflict resolution. So end the
  # loop if that is not available in this build.
  ifcapable !conflict {
    if {$i>1} break
  }

  if {$t0} {set t1 {column a is not unique}}
  do_test memdb-5.$i {
    if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"}
    if {$conf2!=""} {set conf2 "ON CONFLICT $conf2"}
    set r0 [catch {execsql "
      DROP TABLE t1;
      CREATE TABLE t1(a,b,c, UNIQUE(a) $conf1);
      INSERT INTO t1 SELECT * FROM t2;
      UPDATE t3 SET x=0;
      BEGIN $conf2;
      $cmd t3 SET x=1;
      $cmd t1 SET b=b*2;
      $cmd t1 SET a=c+5;
    "} r1]
    catch {execsql {COMMIT}}
    if {!$r0} {set r1 [execsql {SELECT a FROM t1 ORDER BY b}]}
    set r2 [execsql {SELECT x FROM t3}]
    list $r0 $r1 $r2
  } [list $t0 $t1 $t2]
}

do_test memdb-6.1 {
  execsql {
    SELECT * FROM t2;
  }
} {1 2 1 2 3 2 3 4 1 4 5 4}
do_test memdb-6.2 {
  execsql {
    BEGIN;
    DROP TABLE t2;
    SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1;
  }
} {t1 t3 t4}
do_test memdb-6.3 {
  execsql {
    ROLLBACK;
    SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1;
  }
} {t1 t2 t3 t4}
do_test memdb-6.4 {
  execsql {
    SELECT * FROM t2;
  }
} {1 2 1 2 3 2 3 4 1 4 5 4}
ifcapable compound {
do_test memdb-6.5 {
  execsql {
    SELECT a FROM t2 UNION SELECT b FROM t2 ORDER BY 1;
  }
} {1 2 3 4 5}
} ;# ifcapable compound 
do_test memdb-6.6 {
  execsql {
    CREATE INDEX i2 ON t2(c);
    SELECT a FROM t2 ORDER BY c;
  }
} {1 3 2 4}
do_test memdb-6.6 {
  execsql {
    SELECT a FROM t2 ORDER BY c DESC;
  }
} {4 2 3 1}
do_test memdb-6.7 {
  execsql {
    BEGIN;
    CREATE TABLE t5(x,y);
    INSERT INTO t5 VALUES(1,2);
    SELECT * FROM t5;
  }
} {1 2}
do_test memdb-6.8 {
  execsql {
    SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1;
  }
} {t1 t2 t3 t4 t5}
do_test memdb-6.9 {
  execsql {
    ROLLBACK;
    SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1;
  }
} {t1 t2 t3 t4}
do_test memdb-6.10 {
  execsql {
    CREATE TABLE t5(x PRIMARY KEY, y UNIQUE);
    SELECT * FROM t5;
  }
} {}
do_test memdb-6.11 {
  execsql {
    SELECT * FROM t5 ORDER BY y DESC;
  }
} {}

ifcapable conflict {
  do_test memdb-6.12 {
    execsql {
      INSERT INTO t5 VALUES(1,2);
      INSERT INTO t5 VALUES(3,4);
      REPLACE INTO t5 VALUES(1,4);
      SELECT rowid,* FROM t5;
    }
  } {3 1 4}
  do_test memdb-6.13 {
    execsql {
      DELETE FROM t5 WHERE x>5;
      SELECT * FROM t5;
    }
  } {1 4}
  do_test memdb-6.14 {
    execsql {
      DELETE FROM t5 WHERE y<3;
      SELECT * FROM t5;
    }
  } {1 4}
}

do_test memdb-6.15 {
  execsql {
    DELETE FROM t5 WHERE x>0;
    SELECT * FROM t5;
  }
} {}

ifcapable subquery {
  do_test memdb-7.1 {
    execsql {
      CREATE TABLE t6(x);
      INSERT INTO t6 VALUES(1);
      INSERT INTO t6 SELECT x+1 FROM t6;
      INSERT INTO t6 SELECT x+2 FROM t6;
      INSERT INTO t6 SELECT x+4 FROM t6;
      INSERT INTO t6 SELECT x+8 FROM t6;
      INSERT INTO t6 SELECT x+16 FROM t6;
      INSERT INTO t6 SELECT x+32 FROM t6;
      INSERT INTO t6 SELECT x+64 FROM t6;
      INSERT INTO t6 SELECT x+128 FROM t6;
      SELECT count(*) FROM (SELECT DISTINCT x FROM t6);
    }
  } {256}
  for {set i 1} {$i<=256} {incr i} {
    do_test memdb-7.2.$i {
       execsql "DELETE FROM t6 WHERE x=\
                (SELECT x FROM t6 ORDER BY random() LIMIT 1)"
       execsql {SELECT count(*) FROM t6}
    } [expr {256-$i}]
  }
}

# Ticket #1524
#
do_test memdb-8.1 {
  db close
  sqlite3 db {:memory:}
  execsql {
    PRAGMA auto_vacuum=TRUE;
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(randstr(5000,6000));
    INSERT INTO t1 VALUES(randstr(5000,6000));
    INSERT INTO t1 VALUES(randstr(5000,6000));
    INSERT INTO t1 VALUES(randstr(5000,6000));
    INSERT INTO t1 VALUES(randstr(5000,6000));
    SELECT count(*) FROM t1;
  }
} 5
do_test memdb-8.2 {
  execsql {
    DELETE FROM t1;
    SELECT count(*) FROM t1;
  }
} 0

# Test that auto-vacuum works with in-memory databases.
# 
ifcapable autovacuum {
  do_test memdb-9.1 {
    db close
    sqlite3 db test.db
    db cache size 0
    execsql {
      PRAGMA auto_vacuum = full;
      CREATE TABLE t1(a);
      INSERT INTO t1 VALUES(randstr(1000,1000));
      INSERT INTO t1 VALUES(randstr(1000,1000));
      INSERT INTO t1 VALUES(randstr(1000,1000));
    }
    set memused [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1]
    set pgovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 1]
    execsql { DELETE FROM t1 }
    set memused2 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1]
    expr {($memused2 + 2048 < $memused) || $pgovfl==0}
  } {1}
}

} ;# ifcapable memorydb

finish_test

Added test/memleak.test.





































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all tests.
#
# $Id: memleak.test,v 1.10 2007/03/30 17:17:52 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
rename finish_test memleak_finish_test
proc finish_test {} {
  catch {db close}
  memleak_check
}

if {[file exists ./sqlite_test_count]} {
  set COUNT [exec cat ./sqlite_test_count]
} else {
  set COUNT 3
}

# LeakList will hold a list of the number of unfreed mallocs after
# each round of the test.  This number should be constant.  If it
# grows, it may mean there is a memory leak in the library.
#
set LeakList {}

set EXCLUDE {
  all.test
  quick.test
  misuse.test
  memleak.test
  btree2.test
  async.test
  async2.test
  trans.test
  crash.test
  autovacuum_crash.test
}
# Test files btree2.test and btree4.test don't work if the 
# SQLITE_DEFAULT_AUTOVACUUM macro is defined to true (because they depend
# on tables being allocated starting at page 2).
#
ifcapable default_autovacuum {
  lappend EXCLUDE btree2.test
  lappend EXCLUDE btree4.test
}

if {[sqlite3 -has-codec]} {
  # lappend EXCLUDE 
}
if {[llength $argv]>0} {
  set FILELIST $argv
  set argv {}
} else {
  set FILELIST [lsort -dictionary [glob $testdir/*.test]]
}

foreach testfile $FILELIST {
  set tail [file tail $testfile]
  if {[lsearch -exact $EXCLUDE $tail]>=0} continue
  set LeakList {}
  for {set COUNTER 0} {$COUNTER<$COUNT} {incr COUNTER} {
    source $testfile
    if {[info exists Leak]} {
      lappend LeakList $Leak
    }
  }
  if {$LeakList!=""} {
    puts -nonewline memory-leak-test-$tail...
    incr ::nTest
    foreach x $LeakList {
      if {$x!=[lindex $LeakList 0]} {
         puts " failed! ($LeakList)"
         incr ::nErr
         lappend ::failList memory-leak-test-$tail
         break
       }
    }
    puts " Ok"
  }
}
memleak_finish_test

# Run the malloc tests and the misuse test after memory leak detection.
# Both tests leak memory.
#
#catch {source $testdir/misuse.test}
#catch {source $testdir/malloc.test}

memleak_finish_test

Added test/memsubsys1.test.











































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# 2008 June 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains tests of the memory allocation subsystem
#
# $Id: memsubsys1.test,v 1.17 2009/07/18 14:36:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
sqlite3_reset_auto_extension

# This procedure constructs a new database in test.db.  It fills
# this database with many small records (enough to force multiple
# rebalance operations in the btree-layer and to require a large
# page cache), verifies correct results, then returns.
#
proc build_test_db {testname pragmas} {
  catch {db close}
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  sqlite3_db_config_lookaside db 0 0 0
  db eval $pragmas
  db eval {
    CREATE TABLE t1(x, y);
    CREATE TABLE t2(a, b);
    CREATE INDEX i1 ON t1(x,y);
    INSERT INTO t1 VALUES(1, 100);
    INSERT INTO t1 VALUES(2, 200);
  }
  for {set i 2} {$i<5000} {incr i $i} {
    db eval {INSERT INTO t2 SELECT * FROM t1}
    db eval {INSERT INTO t1 SELECT a+$i, a+b*100 FROM t2}
    db eval {DELETE FROM t2}
  }
  do_test $testname.1 {
    db eval {SELECT count(*) FROM t1}
  } 8192
  integrity_check $testname.2
}

# Reset all of the highwater marks.
#
proc reset_highwater_marks {} {
  sqlite3_status SQLITE_STATUS_MEMORY_USED 1
  sqlite3_status SQLITE_STATUS_MALLOC_SIZE 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_USED 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 1
  sqlite3_status SQLITE_STATUS_SCRATCH_USED 1
  sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 1
  sqlite3_status SQLITE_STATUS_SCRATCH_SIZE 1
  sqlite3_status SQLITE_STATUS_PARSER_STACK 1
}

set xtra_size 256

# Test 1:  Both PAGECACHE and SCRATCH are shut down.
#
db close
sqlite3_shutdown
sqlite3_config_lookaside 0 0
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-1 {PRAGMA page_size=1024}
do_test memsubsys1-1.3 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 0
do_test memsubsys1-1.4 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 0
set max_pagecache [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2]
#show_memstats

# Test 2:  Activate PAGECACHE with 20 pages
#
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 1024+$xtra_size] 20
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-2 {PRAGMA page_size=1024}
#show_memstats
do_test memsubsys1-2.3 {
  set pg_ovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2]
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
  expr {
    ($pg_used*1024 + $pg_ovfl) < $max_pagecache &&
    ($pg_used*(1024+$xtra_size) + $pg_ovfl) >= $max_pagecache
  }
} 1
do_test memsubsys1-2.4 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 19
do_test memsubsys1-2.5 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 0

# Test 3:  Activate PAGECACHE with 20 pages but use the wrong page size
# so that PAGECACHE is not used.
#
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 512+$xtra_size] 20
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-3.1 {PRAGMA page_size=1024}
#show_memstats
do_test memsubsys1-3.1.3 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 0
do_test memsubsys1-3.1.4 {
  set overflow [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2]
} $max_pagecache
do_test memsubsys1-3.1.5 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 0
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 2048+$xtra_size] 20
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-3.2 {PRAGMA page_size=2048}
#show_memstats
do_test memsubsys1-3.2.3 {
  db eval {PRAGMA page_size}
} 2048
do_test memsubsys1-3.2.4 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 19
do_test memsubsys1-3.2.5 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 0

# Test 4:  Activate both PAGECACHE and SCRATCH.
#
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 1024+$xtra_size] 50
sqlite3_config_scratch 6000 2
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-4 {PRAGMA page_size=1024}
#show_memstats
do_test memsubsys1-4.3 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 49
do_test memsubsys1-4.4 {
  set pg_ovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2]
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
  expr {
    ($pg_used*1024 + $pg_ovfl) < $max_pagecache &&
    ($pg_used*(1024+$xtra_size) + $pg_ovfl) >= $max_pagecache
  }
} 1
do_test memsubsys1-4.5 {
  set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2]
  expr {$maxreq<7000}
} 1
do_test memsubsys1-4.6 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 1

# Test 5:  Activate both PAGECACHE and SCRATCH.  But make the page size
# such that the SCRATCH allocations are too small.
#
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 4096+$xtra_size] 24
sqlite3_config_scratch 6000 2
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-5 {PRAGMA page_size=4096}
#show_memstats
do_test memsubsys1-5.3 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 23
do_test memsubsys1-5.4 {
  set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2]
  expr {$maxreq>4096}
} 1
do_test memsubsys1-5.5 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 0
do_test memsubsys1-5.6 {
  set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2]
  expr {$s_ovfl>6000}
} 1

# Test 6:  Activate both PAGECACHE and SCRATCH with a 4k page size.
# Make it so that SCRATCH is large enough
#
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 4096+$xtra_size] 24
sqlite3_config_scratch 25300 1
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-6 {PRAGMA page_size=4096}
#show_memstats
do_test memsubsys1-6.3 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
} 23
do_test memsubsys1-6.4 {
  set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2]
  expr {$maxreq>4096 && $maxreq<=(4096+$xtra_size)}
} 1
do_test memsubsys1-6.5 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 1
do_test memsubsys1-6.6 {
  set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2]
} 0

# Test 7:  Activate both PAGECACHE and SCRATCH with a 4k page size.
# Set cache_size small so that no PAGECACHE overflow occurs.  Verify
# that maximum allocation size is small.
#
db close
sqlite3_shutdown
sqlite3_config_pagecache [expr 4096+$xtra_size] 24
sqlite3_config_scratch 25300 1
sqlite3_initialize
reset_highwater_marks
build_test_db memsubsys1-7 {
  PRAGMA page_size=4096;
  PRAGMA cache_size=10;
  PRAGMA temp_store=memory;
}
#show_memstats
do_test memsubsys1-7.3 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2]
  expr {$pg_used<24}
} 1
do_test memsubsys1-7.4 {
  set pg_ovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2]
} 0
do_test memsubsys1-7.5 {
  set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2]
  expr {$maxreq<4100}
} 1
do_test memsubsys1-7.6 {
  set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 1
do_test memsubsys1-7.7 {
  set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2]
} 0

# Test 8:  Disable PAGECACHE.  Make available SCRATCH zero.  Verify that
# the SCRATCH overflow logic works.
#
db close
sqlite3_shutdown
sqlite3_config_pagecache 0 0
sqlite3_config_scratch 25000 0
sqlite3_initialize
reset_highwater_marks
do_test memsubsys1-8.1 {
  set pg_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2]
} 0
do_test memsubsys1-8.2 {
  set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2]
} 0
do_test memsubsys1-8.3 {
  sqlite3 db :memory:
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(zeroblob(400));
    INSERT INTO t1 VALUES(zeroblob(400));
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
  }
  expr {[lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2]>0}
} 1
db close
sqlite3_shutdown
sqlite3_config_memstatus 0
sqlite3_initialize
do_test memsubsys1-8.4 {
  sqlite3 db :memory:
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(zeroblob(400));
    INSERT INTO t1 VALUES(zeroblob(400));
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 SELECT * FROM t1;
    SELECT rowid FROM t1;
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16}


db close
sqlite3_shutdown
sqlite3_config_memstatus 1
sqlite3_config_pagecache 0 0
sqlite3_config_scratch 0 0
sqlite3_config_lookaside 100 500
sqlite3_initialize
autoinstall_test_functions
finish_test

Added test/memsubsys2.test.



























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# 2008 June 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains tests of the memory allocation subsystem.
#
# $Id: memsubsys2.test,v 1.2 2008/08/12 15:21:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
sqlite3_reset_auto_extension

# This procedure constructs a new database in test.db.  It fills
# this database with many small records (enough to force multiple
# rebalance operations in the btree-layer and to require a large
# page cache), verifies correct results, then returns.
#
proc build_test_db {testname pragmas} {
  catch {db close}
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  db eval $pragmas
  db eval {
    CREATE TABLE t1(x, y);
    CREATE TABLE t2(a, b);
    CREATE INDEX i1 ON t1(x,y);
    INSERT INTO t1 VALUES(1, 100);
    INSERT INTO t1 VALUES(2, 200);
  }
  for {set i 2} {$i<5000} {incr i $i} {
    db eval {INSERT INTO t2 SELECT * FROM t1}
    db eval {INSERT INTO t1 SELECT a+$i, a+b*100 FROM t2}
    db eval {DELETE FROM t2}
  }
  do_test $testname.1 {
    db eval {SELECT count(*) FROM t1}
  } 8192
  integrity_check $testname.2
}

# Reset all of the highwater marks.
#
proc reset_highwater_marks {} {
  sqlite3_status SQLITE_STATUS_MEMORY_USED 1
  sqlite3_status SQLITE_STATUS_MALLOC_SIZE 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_USED 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 1
  sqlite3_status SQLITE_STATUS_SCRATCH_USED 1
  sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 1
  sqlite3_status SQLITE_STATUS_SCRATCH_SIZE 1
  sqlite3_status SQLITE_STATUS_PARSER_STACK 1
}

# Test 1:  Verify that calling sqlite3_malloc(0) returns a NULL
# pointer.
#
set highwater [sqlite3_memory_highwater 0]
do_test memsubsys2-1.1 {
  sqlite3_malloc 0
} {0}
do_test memsubsys2-1.2 {
  sqlite3_memory_highwater 0
} $highwater


# Test 2:  Verify that the highwater mark increases after a large
# allocation.
#
sqlite3_memory_highwater 1
set highwater [sqlite3_memory_highwater 0]
do_test memsubsys2-2.1 {
  sqlite3_free [set x [sqlite3_malloc 100000]]
  expr {$x!="0"}
} {1}
do_test memsubsys2-2.2 {
  expr {[sqlite3_memory_highwater 0]>=[sqlite3_memory_used]+$highwater}
} {1}

# Test 3: Verify that turning of memstatus disables the statistics
# tracking.
#
db close
sqlite3_shutdown
sqlite3_config_memstatus 0
sqlite3_initialize
reset_highwater_marks
set highwater [sqlite3_memory_highwater 0]
do_test memsubsys2-3.1 {
  set highwater
} {0}
do_test memsubsys2-3.2 {
  sqlite3_malloc 0
} {0}
do_test memsubsys2-3.3 {
  sqlite3_memory_highwater 0
} {0}
do_test memsubsys2-3.4 {
  sqlite3_memory_used
} {0}
do_test memsubsys2-3.5 {
  set ::allocation [sqlite3_malloc 100000]
  expr {$::allocation!="0"}
} {1}
do_test memsubsys2-3.6 {
  sqlite3_memory_highwater 0
} {0}
do_test memsubsys2-3.7 {
  sqlite3_memory_used
} {0}
do_test memsubsys2-3.8 {
  sqlite3_free $::allocation
} {}
do_test memsubsys2-3.9 {
  sqlite3_free 0
} {}
  

# Test 4: Verify that turning on memstatus reenables the statistics
# tracking.
#
sqlite3_shutdown
sqlite3_config_memstatus 1
sqlite3_initialize
reset_highwater_marks
set highwater [sqlite3_memory_highwater 0]
do_test memsubsys2-4.1 {
  set highwater
} {0}
do_test memsubsys2-4.2 {
  sqlite3_malloc 0
} {0}
do_test memsubsys2-4.3 {
  sqlite3_memory_highwater 0
} {0}
do_test memsubsys2-4.4 {
  sqlite3_memory_used
} {0}
do_test memsubsys2-4.5 {
  set ::allocation [sqlite3_malloc 100000]
  expr {$::allocation!="0"}
} {1}
do_test memsubsys2-4.6 {
  expr {[sqlite3_memory_highwater 0]>=100000}
} {1}
do_test memsubsys2-4.7 {
  expr {[sqlite3_memory_used]>=100000}
} {1}
do_test memsubsys2-4.8 {
  sqlite3_free $::allocation
} {}
do_test memsubsys2-4.9 {
  sqlite3_free 0
} {}
do_test memsubsys2-4.10 {
  expr {[sqlite3_memory_highwater 0]>=100000}
} {1}
do_test memsubsys2-4.11 {
  sqlite3_memory_used
} {0}
  



autoinstall_test_functions
finish_test

Added test/minmax.test.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing SELECT statements that contain
# aggregate min() and max() functions and which are handled as
# as a special case.
#
# $Id: minmax.test,v 1.21 2008/07/08 18:05:26 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test minmax-1.0 {
  execsql {
    BEGIN;
    CREATE TABLE t1(x, y);
    INSERT INTO t1 VALUES(1,1);
    INSERT INTO t1 VALUES(2,2);
    INSERT INTO t1 VALUES(3,2);
    INSERT INTO t1 VALUES(4,3);
    INSERT INTO t1 VALUES(5,3);
    INSERT INTO t1 VALUES(6,3);
    INSERT INTO t1 VALUES(7,3);
    INSERT INTO t1 VALUES(8,4);
    INSERT INTO t1 VALUES(9,4);
    INSERT INTO t1 VALUES(10,4);
    INSERT INTO t1 VALUES(11,4);
    INSERT INTO t1 VALUES(12,4);
    INSERT INTO t1 VALUES(13,4);
    INSERT INTO t1 VALUES(14,4);
    INSERT INTO t1 VALUES(15,4);
    INSERT INTO t1 VALUES(16,5);
    INSERT INTO t1 VALUES(17,5);
    INSERT INTO t1 VALUES(18,5);
    INSERT INTO t1 VALUES(19,5);
    INSERT INTO t1 VALUES(20,5);
    COMMIT;
    SELECT DISTINCT y FROM t1 ORDER BY y;
  }
} {1 2 3 4 5}

do_test minmax-1.1 {
  set sqlite_search_count 0
  execsql {SELECT min(x) FROM t1}
} {1}
do_test minmax-1.2 {
  set sqlite_search_count
} {19}
do_test minmax-1.3 {
  set sqlite_search_count 0
  execsql {SELECT max(x) FROM t1}
} {20}
do_test minmax-1.4 {
  set sqlite_search_count
} {19}
do_test minmax-1.5 {
  execsql {CREATE INDEX t1i1 ON t1(x)}
  set sqlite_search_count 0
  execsql {SELECT min(x) FROM t1}
} {1}
do_test minmax-1.6 {
  set sqlite_search_count
} {1}
do_test minmax-1.7 {
  set sqlite_search_count 0
  execsql {SELECT max(x) FROM t1}
} {20}
do_test minmax-1.8 {
  set sqlite_search_count
} {0}
do_test minmax-1.9 {
  set sqlite_search_count 0
  execsql {SELECT max(y) FROM t1}
} {5}
do_test minmax-1.10 {
  set sqlite_search_count
} {19}

do_test minmax-1.21 {
  execsql {SELECT min(x) FROM t1 WHERE x=5}
} {5}
do_test minmax-1.22 {
  execsql {SELECT min(x) FROM t1 WHERE x>=5}
} {5}
do_test minmax-1.23 {
  execsql {SELECT min(x) FROM t1 WHERE x>=4.5}
} {5}
do_test minmax-1.24 {
  execsql {SELECT min(x) FROM t1 WHERE x<4.5}
} {1}

do_test minmax-2.0 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
    INSERT INTO t2 SELECT * FROM t1;
  }
  set sqlite_search_count 0
  execsql {SELECT min(a) FROM t2}
} {1}
do_test minmax-2.1 {
  set sqlite_search_count
} {0}
do_test minmax-2.2 {
  set sqlite_search_count 0
  execsql {SELECT max(a) FROM t2}
} {20}
do_test minmax-2.3 {
  set sqlite_search_count
} {0}

do_test minmax-3.0 {
  ifcapable subquery {
    execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)}
  } else {
    db function max_a_t2 {execsql {SELECT max(a) FROM t2}}
    execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)}
  }
  set sqlite_search_count 0
  execsql {SELECT max(a) FROM t2}
} {21}
do_test minmax-3.1 {
  set sqlite_search_count
} {0}
do_test minmax-3.2 {
  ifcapable subquery {
    execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)}
  } else {
    db function max_a_t2 {execsql {SELECT max(a) FROM t2}}
    execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)}
  }
  set sqlite_search_count 0
  ifcapable subquery {
    execsql { SELECT b FROM t2 WHERE a=(SELECT max(a) FROM t2) }
  } else {
    execsql { SELECT b FROM t2 WHERE a=max_a_t2() }
  }
} {999}
do_test minmax-3.3 {
  set sqlite_search_count
} {0}

ifcapable {compound && subquery} {
  do_test minmax-4.1 {
    execsql {
      SELECT coalesce(min(x+0),-1), coalesce(max(x+0),-1) FROM
        (SELECT * FROM t1 UNION SELECT NULL as 'x', NULL as 'y')
    }
  } {1 20}
  do_test minmax-4.2 {
    execsql {
      SELECT y, coalesce(sum(x),0) FROM
        (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1)
      GROUP BY y ORDER BY y;
    }
  } {1 1 2 5 3 22 4 92 5 90 6 0}
  do_test minmax-4.3 {
    execsql {
      SELECT y, count(x), count(*) FROM
        (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1)
      GROUP BY y ORDER BY y;
    }
  } {1 1 1 2 2 3 3 4 5 4 8 9 5 5 6 6 0 1}
} ;# ifcapable compound

# Make sure the min(x) and max(x) optimizations work on empty tables
# including empty tables with indices. Ticket #296.
#
do_test minmax-5.1 {
  execsql {
    CREATE TABLE t3(x INTEGER UNIQUE NOT NULL);
    SELECT coalesce(min(x),999) FROM t3;
  }
} {999}
do_test minmax-5.2 {
  execsql {
    SELECT coalesce(min(rowid),999) FROM t3;
  }
} {999}
do_test minmax-5.3 {
  execsql {
    SELECT coalesce(max(x),999) FROM t3;
  }
} {999}
do_test minmax-5.4 {
  execsql {
    SELECT coalesce(max(rowid),999) FROM t3;
  }
} {999}
do_test minmax-5.5 {
  execsql {
    SELECT coalesce(max(rowid),999) FROM t3 WHERE rowid<25;
  }
} {999}

# Make sure the min(x) and max(x) optimizations work when there
# is a LIMIT clause.  Ticket #396.
#
do_test minmax-6.1 {
  execsql {
    SELECT min(a) FROM t2 LIMIT 1
  }
} {1}
do_test minmax-6.2 {
  execsql {
    SELECT max(a) FROM t2 LIMIT 3
  }
} {22}
do_test minmax-6.3 {
  execsql {
    SELECT min(a) FROM t2 LIMIT 0,100
  }
} {1}
do_test minmax-6.4 {
  execsql {
    SELECT max(a) FROM t2 LIMIT 1,100
  }
} {}
do_test minmax-6.5 {
  execsql {
    SELECT min(x) FROM t3 LIMIT 1
  }
} {{}}
do_test minmax-6.6 {
  execsql {
    SELECT max(x) FROM t3 LIMIT 0
  }
} {}
do_test minmax-6.7 {
  execsql {
    SELECT max(a) FROM t2 LIMIT 0
  }
} {}

# Make sure the max(x) and min(x) optimizations work for nested
# queries.  Ticket #587.
#
do_test minmax-7.1 {
  execsql {
    SELECT max(x) FROM t1;
  }
} 20
ifcapable subquery {
  do_test minmax-7.2 {
    execsql {
      SELECT * FROM (SELECT max(x) FROM t1);
    }
  } 20
}
do_test minmax-7.3 {
  execsql {
    SELECT min(x) FROM t1;
  }
} 1
ifcapable subquery {
  do_test minmax-7.4 {
    execsql {
      SELECT * FROM (SELECT min(x) FROM t1);
    }
  } 1
}

# Make sure min(x) and max(x) work correctly when the datatype is
# TEXT instead of NUMERIC.  Ticket #623.
#
do_test minmax-8.1 {
  execsql {
    CREATE TABLE t4(a TEXT);
    INSERT INTO t4 VALUES('1234');
    INSERT INTO t4 VALUES('234');
    INSERT INTO t4 VALUES('34');
    SELECT min(a), max(a) FROM t4;
  }
} {1234 34}
do_test minmax-8.2 {
  execsql {
    CREATE TABLE t5(a INTEGER);
    INSERT INTO t5 VALUES('1234');
    INSERT INTO t5 VALUES('234');
    INSERT INTO t5 VALUES('34');
    SELECT min(a), max(a) FROM t5;
  }
} {34 1234}

# Ticket #658:  Test the min()/max() optimization when the FROM clause
# is a subquery.
#
ifcapable {compound && subquery} {
  do_test minmax-9.1 {
    execsql {
      SELECT max(rowid) FROM (
        SELECT max(rowid) FROM t4 UNION SELECT max(rowid) FROM t5
      )
    }
  } {1}
  do_test minmax-9.2 {
    execsql {
      SELECT max(rowid) FROM (
        SELECT max(rowid) FROM t4 EXCEPT SELECT max(rowid) FROM t5
      )
    }
  } {{}}
} ;# ifcapable compound&&subquery

# If there is a NULL in an aggregate max() or min(), ignore it.  An
# aggregate min() or max() will only return NULL if all values are NULL.
#
do_test minmax-10.1 {
  execsql {
    CREATE TABLE t6(x);
    INSERT INTO t6 VALUES(1);
    INSERT INTO t6 VALUES(2);
    INSERT INTO t6 VALUES(NULL);
    SELECT coalesce(min(x),-1) FROM t6;
  }
} {1}
do_test minmax-10.2 {
  execsql {
    SELECT max(x) FROM t6;
  }
} {2}
do_test minmax-10.3 {
  execsql {
    CREATE INDEX i6 ON t6(x);
    SELECT coalesce(min(x),-1) FROM t6;
  }
} {1}
do_test minmax-10.4 {
  execsql {
    SELECT max(x) FROM t6;
  }
} {2}
do_test minmax-10.5 {
  execsql {
    DELETE FROM t6 WHERE x NOT NULL;
    SELECT count(*) FROM t6;
  }
} 1
do_test minmax-10.6 {
  execsql {
    SELECT count(x) FROM t6;
  }
} 0
ifcapable subquery {
  do_test minmax-10.7 {
    execsql {
      SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6);
    }
  } {{} {}}
}
do_test minmax-10.8 {
  execsql {
    SELECT min(x), max(x) FROM t6;
  }
} {{} {}}
do_test minmax-10.9 {
  execsql {
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    SELECT count(*) FROM t6;
  }
} 1024
do_test minmax-10.10 {
  execsql {
    SELECT count(x) FROM t6;
  }
} 0
ifcapable subquery {
  do_test minmax-10.11 {
    execsql {
      SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6);
    }
  } {{} {}}
}
do_test minmax-10.12 {
  execsql {
    SELECT min(x), max(x) FROM t6;
  }
} {{} {}}


do_test minmax-11.1 {
  execsql {
    CREATE INDEX t1i2 ON t1(y,x);
    SELECT min(x) FROM t1 WHERE y=5;
  }
} {16}
do_test minmax-11.2 {
  execsql {
    SELECT max(x) FROM t1 WHERE y=5;
  }
} {20}
do_test minmax-11.3 {
  execsql {
    SELECT min(x) FROM t1 WHERE y=6;
  }
} {{}}
do_test minmax-11.4 {
  execsql {
    SELECT max(x) FROM t1 WHERE y=6;
  }
} {{}}
do_test minmax-11.5 {
  execsql {
    SELECT min(x) FROM t1 WHERE y=1;
  }
} {1}
do_test minmax-11.6 {
  execsql {
    SELECT max(x) FROM t1 WHERE y=1;
  }
} {1}
do_test minmax-11.7 {
  execsql {
    SELECT min(x) FROM t1 WHERE y=0;
  }
} {{}}
do_test minmax-11.8 {
  execsql {
    SELECT max(x) FROM t1 WHERE y=0;
  }
} {{}}
do_test minmax-11.9 {
  execsql {
    SELECT min(x) FROM t1 WHERE y=5 AND x>=17.5;
  }
} {18}
do_test minmax-11.10 {
  execsql {
    SELECT max(x) FROM t1 WHERE y=5 AND x>=17.5;
  }
} {20}

do_test minmax-12.1 {
  execsql {
    CREATE TABLE t7(a,b,c);
    INSERT INTO t7 SELECT y, x, x*y FROM t1;
    INSERT INTO t7 SELECT y, x, x*y+1000 FROM t1;
    CREATE INDEX t7i1 ON t7(a,b,c);
    SELECT min(a) FROM t7;
  }
} {1}
do_test minmax-12.2 {
  execsql {
    SELECT max(a) FROM t7;
  }
} {5}
do_test minmax-12.3 {
  execsql {
    SELECT max(a) FROM t7 WHERE a=5;
  }
} {5}
do_test minmax-12.4 {
  execsql {
    SELECT min(b) FROM t7 WHERE a=5;
  }
} {16}
do_test minmax-12.5 {
  execsql {
    SELECT max(b) FROM t7 WHERE a=5;
  }
} {20}
do_test minmax-12.6 {
  execsql {
    SELECT min(b) FROM t7 WHERE a=4;
  }
} {8}
do_test minmax-12.7 {
  execsql {
    SELECT max(b) FROM t7 WHERE a=4;
  }
} {15}
do_test minmax-12.8 {
  execsql {
    SELECT min(c) FROM t7 WHERE a=4 AND b=10;
  }
} {40}
do_test minmax-12.9 {
  execsql {
    SELECT max(c) FROM t7 WHERE a=4 AND b=10;
  }
} {1040}
do_test minmax-12.10 {
  execsql {
    SELECT min(rowid) FROM t7;
  }
} {1}
do_test minmax-12.11 {
  execsql {
    SELECT max(rowid) FROM t7;
  }
} {40}
do_test minmax-12.12 {
  execsql {
    SELECT min(rowid) FROM t7 WHERE a=3;
  }
} {4}
do_test minmax-12.13 {
  execsql {
    SELECT max(rowid) FROM t7 WHERE a=3;
  }
} {27}
do_test minmax-12.14 {
  execsql {
    SELECT min(rowid) FROM t7 WHERE a=3 AND b=5;
  }
} {5}
do_test minmax-12.15 {
  execsql {
    SELECT max(rowid) FROM t7 WHERE a=3 AND b=5;
  }
} {25}
do_test minmax-12.16 {
  execsql {
    SELECT min(rowid) FROM t7 WHERE a=3 AND b=5 AND c=1015;
  }
} {25}
do_test minmax-12.17 {
  execsql {
    SELECT max(rowid) FROM t7 WHERE a=3 AND b=5 AND c=15;
  }
} {5}




finish_test

Added test/minmax2.test.







































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# 2007 July 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing SELECT statements that contain
# aggregate min() and max() functions and which are handled as
# as a special case.  This file makes sure that the min/max
# optimization works right in the presence of descending
# indices.  Ticket #2514.
#
# $Id: minmax2.test,v 1.2 2008/01/05 17:39:30 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test minmax2-1.0 {
  execsql {
    PRAGMA legacy_file_format=0;
    BEGIN;
    CREATE TABLE t1(x, y);
    INSERT INTO t1 VALUES(1,1);
    INSERT INTO t1 VALUES(2,2);
    INSERT INTO t1 VALUES(3,2);
    INSERT INTO t1 VALUES(4,3);
    INSERT INTO t1 VALUES(5,3);
    INSERT INTO t1 VALUES(6,3);
    INSERT INTO t1 VALUES(7,3);
    INSERT INTO t1 VALUES(8,4);
    INSERT INTO t1 VALUES(9,4);
    INSERT INTO t1 VALUES(10,4);
    INSERT INTO t1 VALUES(11,4);
    INSERT INTO t1 VALUES(12,4);
    INSERT INTO t1 VALUES(13,4);
    INSERT INTO t1 VALUES(14,4);
    INSERT INTO t1 VALUES(15,4);
    INSERT INTO t1 VALUES(16,5);
    INSERT INTO t1 VALUES(17,5);
    INSERT INTO t1 VALUES(18,5);
    INSERT INTO t1 VALUES(19,5);
    INSERT INTO t1 VALUES(20,5);
    COMMIT;
    SELECT DISTINCT y FROM t1 ORDER BY y;
  }
} {1 2 3 4 5}

do_test minmax2-1.1 {
  set sqlite_search_count 0
  execsql {SELECT min(x) FROM t1}
} {1}
do_test minmax2-1.2 {
  set sqlite_search_count
} {19}
do_test minmax2-1.3 {
  set sqlite_search_count 0
  execsql {SELECT max(x) FROM t1}
} {20}
do_test minmax2-1.4 {
  set sqlite_search_count
} {19}
do_test minmax2-1.5 {
  execsql {CREATE INDEX t1i1 ON t1(x DESC)}
  set sqlite_search_count 0
  execsql {SELECT min(x) FROM t1}
} {1}
do_test minmax2-1.6 {
  set sqlite_search_count
} {1}
do_test minmax2-1.7 {
  set sqlite_search_count 0
  execsql {SELECT max(x) FROM t1}
} {20}
do_test minmax2-1.8 {
  set sqlite_search_count
} {0}
do_test minmax2-1.9 {
  set sqlite_search_count 0
  execsql {SELECT max(y) FROM t1}
} {5}
do_test minmax2-1.10 {
  set sqlite_search_count
} {19}

do_test minmax2-2.0 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
    INSERT INTO t2 SELECT * FROM t1;
  }
  set sqlite_search_count 0
  execsql {SELECT min(a) FROM t2}
} {1}
do_test minmax2-2.1 {
  set sqlite_search_count
} {0}
do_test minmax2-2.2 {
  set sqlite_search_count 0
  execsql {SELECT max(a) FROM t2}
} {20}
do_test minmax2-2.3 {
  set sqlite_search_count
} {0}

do_test minmax2-3.0 {
  ifcapable subquery {
    execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)}
  } else {
    db function max_a_t2 {execsql {SELECT max(a) FROM t2}}
    execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)}
  }
  set sqlite_search_count 0
  execsql {SELECT max(a) FROM t2}
} {21}
do_test minmax2-3.1 {
  set sqlite_search_count
} {0}
do_test minmax2-3.2 {
  ifcapable subquery {
    execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)}
  } else {
    db function max_a_t2 {execsql {SELECT max(a) FROM t2}}
    execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)}
  }
  set sqlite_search_count 0
  ifcapable subquery {
    execsql { SELECT b FROM t2 WHERE a=(SELECT max(a) FROM t2) }
  } else {
    execsql { SELECT b FROM t2 WHERE a=max_a_t2() }
  }
} {999}
do_test minmax2-3.3 {
  set sqlite_search_count
} {0}

ifcapable {compound && subquery} {
  do_test minmax2-4.1 {
    execsql {
      SELECT coalesce(min(x+0),-1), coalesce(max(x+0),-1) FROM
        (SELECT * FROM t1 UNION SELECT NULL as 'x', NULL as 'y')
    }
  } {1 20}
  do_test minmax2-4.2 {
    execsql {
      SELECT y, coalesce(sum(x),0) FROM
        (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1)
      GROUP BY y ORDER BY y;
    }
  } {1 1 2 5 3 22 4 92 5 90 6 0}
  do_test minmax2-4.3 {
    execsql {
      SELECT y, count(x), count(*) FROM
        (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1)
      GROUP BY y ORDER BY y;
    }
  } {1 1 1 2 2 3 3 4 5 4 8 9 5 5 6 6 0 1}
} ;# ifcapable compound

# Make sure the min(x) and max(x) optimizations work on empty tables
# including empty tables with indices. Ticket #296.
#
do_test minmax2-5.1 {
  execsql {
    CREATE TABLE t3(x INTEGER UNIQUE NOT NULL);
    SELECT coalesce(min(x),999) FROM t3;
  }
} {999}
do_test minmax2-5.2 {
  execsql {
    SELECT coalesce(min(rowid),999) FROM t3;
  }
} {999}
do_test minmax2-5.3 {
  execsql {
    SELECT coalesce(max(x),999) FROM t3;
  }
} {999}
do_test minmax2-5.4 {
  execsql {
    SELECT coalesce(max(rowid),999) FROM t3;
  }
} {999}
do_test minmax2-5.5 {
  execsql {
    SELECT coalesce(max(rowid),999) FROM t3 WHERE rowid<25;
  }
} {999}

# Make sure the min(x) and max(x) optimizations work when there
# is a LIMIT clause.  Ticket #396.
#
do_test minmax2-6.1 {
  execsql {
    SELECT min(a) FROM t2 LIMIT 1
  }
} {1}
do_test minmax2-6.2 {
  execsql {
    SELECT max(a) FROM t2 LIMIT 3
  }
} {22}
do_test minmax2-6.3 {
  execsql {
    SELECT min(a) FROM t2 LIMIT 0,100
  }
} {1}
do_test minmax2-6.4 {
  execsql {
    SELECT max(a) FROM t2 LIMIT 1,100
  }
} {}
do_test minmax2-6.5 {
  execsql {
    SELECT min(x) FROM t3 LIMIT 1
  }
} {{}}
do_test minmax2-6.6 {
  execsql {
    SELECT max(x) FROM t3 LIMIT 0
  }
} {}
do_test minmax2-6.7 {
  execsql {
    SELECT max(a) FROM t2 LIMIT 0
  }
} {}

# Make sure the max(x) and min(x) optimizations work for nested
# queries.  Ticket #587.
#
do_test minmax2-7.1 {
  execsql {
    SELECT max(x) FROM t1;
  }
} 20
ifcapable subquery {
  do_test minmax2-7.2 {
    execsql {
      SELECT * FROM (SELECT max(x) FROM t1);
    }
  } 20
}
do_test minmax2-7.3 {
  execsql {
    SELECT min(x) FROM t1;
  }
} 1
ifcapable subquery {
  do_test minmax2-7.4 {
    execsql {
      SELECT * FROM (SELECT min(x) FROM t1);
    }
  } 1
}

# Make sure min(x) and max(x) work correctly when the datatype is
# TEXT instead of NUMERIC.  Ticket #623.
#
do_test minmax2-8.1 {
  execsql {
    CREATE TABLE t4(a TEXT);
    INSERT INTO t4 VALUES('1234');
    INSERT INTO t4 VALUES('234');
    INSERT INTO t4 VALUES('34');
    SELECT min(a), max(a) FROM t4;
  }
} {1234 34}
do_test minmax2-8.2 {
  execsql {
    CREATE TABLE t5(a INTEGER);
    INSERT INTO t5 VALUES('1234');
    INSERT INTO t5 VALUES('234');
    INSERT INTO t5 VALUES('34');
    SELECT min(a), max(a) FROM t5;
  }
} {34 1234}

# Ticket #658:  Test the min()/max() optimization when the FROM clause
# is a subquery.
#
ifcapable {compound && subquery} {
  do_test minmax2-9.1 {
    execsql {
      SELECT max(rowid) FROM (
        SELECT max(rowid) FROM t4 UNION SELECT max(rowid) FROM t5
      )
    }
  } {1}
  do_test minmax2-9.2 {
    execsql {
      SELECT max(rowid) FROM (
        SELECT max(rowid) FROM t4 EXCEPT SELECT max(rowid) FROM t5
      )
    }
  } {{}}
} ;# ifcapable compound&&subquery

# If there is a NULL in an aggregate max() or min(), ignore it.  An
# aggregate min() or max() will only return NULL if all values are NULL.
#
do_test minmax2-10.1 {
  execsql {
    CREATE TABLE t6(x);
    INSERT INTO t6 VALUES(1);
    INSERT INTO t6 VALUES(2);
    INSERT INTO t6 VALUES(NULL);
    SELECT coalesce(min(x),-1) FROM t6;
  }
} {1}
do_test minmax2-10.2 {
  execsql {
    SELECT max(x) FROM t6;
  }
} {2}
do_test minmax2-10.3 {
  execsql {
    CREATE INDEX i6 ON t6(x DESC);
    SELECT coalesce(min(x),-1) FROM t6;
  }
} {1}
do_test minmax2-10.4 {
  execsql {
    SELECT max(x) FROM t6;
  }
} {2}
do_test minmax2-10.5 {
  execsql {
    DELETE FROM t6 WHERE x NOT NULL;
    SELECT count(*) FROM t6;
  }
} 1
do_test minmax2-10.6 {
  execsql {
    SELECT count(x) FROM t6;
  }
} 0
ifcapable subquery {
  do_test minmax2-10.7 {
    execsql {
      SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6);
    }
  } {{} {}}
}
do_test minmax2-10.8 {
  execsql {
    SELECT min(x), max(x) FROM t6;
  }
} {{} {}}
do_test minmax2-10.9 {
  execsql {
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    SELECT count(*) FROM t6;
  }
} 1024
do_test minmax2-10.10 {
  execsql {
    SELECT count(x) FROM t6;
  }
} 0
ifcapable subquery {
  do_test minmax2-10.11 {
    execsql {
      SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6);
    }
  } {{} {}}
}
do_test minmax2-10.12 {
  execsql {
    SELECT min(x), max(x) FROM t6;
  }
} {{} {}}


finish_test

Added test/minmax3.test.



















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# 2008 January 5
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# $Id: minmax3.test,v 1.5 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  return [concat [execsql $sql] $::sqlite_search_count]
}

# This procedure sets the value of the file-format in file 'test.db'
# to $newval. Also, the schema cookie is incremented.
# 
proc set_file_format {newval} {
  hexio_write test.db 44 [hexio_render_int32 $newval]
  set schemacookie [hexio_get_int [hexio_read test.db 40 4]]
  incr schemacookie
  hexio_write test.db 40 [hexio_render_int32 $schemacookie]
  return {}
}

do_test minmax3-1.0 {
  execsql {
    CREATE TABLE t1(x, y, z);
  }
  db close
  set_file_format 4
  sqlite3 db test.db
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES('1', 'I',   'one');
    INSERT INTO t1 VALUES('2', 'IV',  'four');
    INSERT INTO t1 VALUES('2', NULL,  'three');
    INSERT INTO t1 VALUES('2', 'II',  'two');
    INSERT INTO t1 VALUES('2', 'V',   'five');
    INSERT INTO t1 VALUES('3', 'VI',  'six');
    COMMIT;
  }
} {}
do_test minmax3-1.1.1 {
  # Linear scan.
  count { SELECT max(y) FROM t1 WHERE x = '2'; }
} {V 5}
do_test minmax3-1.1.2 {
  # Index optimizes the WHERE x='2' constraint.
  execsql { CREATE INDEX i1 ON t1(x) }
  count   { SELECT max(y) FROM t1 WHERE x = '2'; }
} {V 9}
do_test minmax3-1.1.3 {
  # Index optimizes the WHERE x='2' constraint and the MAX(y).
  execsql { CREATE INDEX i2 ON t1(x,y) }
  count   { SELECT max(y) FROM t1 WHERE x = '2'; }
} {V 1}
do_test minmax3-1.1.4 {
  # Index optimizes the WHERE x='2' constraint and the MAX(y).
  execsql { DROP INDEX i2 ; CREATE INDEX i2 ON t1(x, y DESC) }
  count   { SELECT max(y) FROM t1 WHERE x = '2'; }
} {V 1}
do_test minmax3-1.1.5 {
  count   { SELECT max(y) FROM t1 WHERE x = '2' AND y != 'V'; }
} {IV 2}
do_test minmax3-1.1.6 {
  count   { SELECT max(y) FROM t1 WHERE x = '2' AND y < 'V'; }
} {IV 1}
do_test minmax3-1.1.6 {
  count   { SELECT max(y) FROM t1 WHERE x = '2' AND z != 'five'; }
} {IV 4}

do_test minmax3-1.2.1 {
  # Linear scan of t1.
  execsql { DROP INDEX i1 ; DROP INDEX i2 }
  count { SELECT min(y) FROM t1 WHERE x = '2'; }
} {II 5}
do_test minmax3-1.2.2 {
  # Index i1 optimizes the WHERE x='2' constraint.
  execsql { CREATE INDEX i1 ON t1(x) }
  count   { SELECT min(y) FROM t1 WHERE x = '2'; }
} {II 9}
do_test minmax3-1.2.3 {
  # Index i2 optimizes the WHERE x='2' constraint and the min(y).
  execsql { CREATE INDEX i2 ON t1(x,y) }
  count   { SELECT min(y) FROM t1 WHERE x = '2'; }
} {II 1}
do_test minmax3-1.2.4 {
  # Index optimizes the WHERE x='2' constraint and the MAX(y).
  execsql { DROP INDEX i2 ; CREATE INDEX i2 ON t1(x, y DESC) }
  count   { SELECT min(y) FROM t1 WHERE x = '2'; }
} {II 1}

do_test minmax3-1.3.1 {
  # Linear scan
  execsql { DROP INDEX i1 ; DROP INDEX i2 }
  count   { SELECT min(y) FROM t1; }
} {I 5}
do_test minmax3-1.3.2 {
  # Index i1 optimizes the min(y)
  execsql { CREATE INDEX i1 ON t1(y) }
  count   { SELECT min(y) FROM t1; }
} {I 1}
do_test minmax3-1.3.3 {
  # Index i1 optimizes the min(y)
  execsql { DROP INDEX i1 ; CREATE INDEX i1 ON t1(y DESC) }
  count   { SELECT min(y) FROM t1; }
} {I 1}

do_test minmax3-1.4.1 {
  # Linear scan
  execsql { DROP INDEX i1 }
  count   { SELECT max(y) FROM t1; }
} {VI 5}
do_test minmax3-1.4.2 {
  # Index i1 optimizes the max(y)
  execsql { CREATE INDEX i1 ON t1(y) }
  count   { SELECT max(y) FROM t1; }
} {VI 0}
do_test minmax3-1.4.3 {
  # Index i1 optimizes the max(y)
  execsql { DROP INDEX i1 ; CREATE INDEX i1 ON t1(y DESC) }
  execsql   { SELECT y from t1}
  count   { SELECT max(y) FROM t1; }
} {VI 0}
do_test minmax3-1.4.4 {
  execsql { DROP INDEX i1 }
} {}

do_test minmax3-2.1 {
  execsql {
    CREATE TABLE t2(a, b);
    CREATE INDEX i3 ON t2(a, b);
    INSERT INTO t2 VALUES(1, NULL);
    INSERT INTO t2 VALUES(1, 1);
    INSERT INTO t2 VALUES(1, 2);
    INSERT INTO t2 VALUES(1, 3);
    INSERT INTO t2 VALUES(2, NULL);
    INSERT INTO t2 VALUES(2, 1);
    INSERT INTO t2 VALUES(2, 2);
    INSERT INTO t2 VALUES(2, 3);
    INSERT INTO t2 VALUES(3, 1);
    INSERT INTO t2 VALUES(3, 2);
    INSERT INTO t2 VALUES(3, 3);
  }
} {}
do_test minmax3-2.2 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1; }
} {1}
do_test minmax3-2.3 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>1; }
} {2}
do_test minmax3-2.4 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>-1; }
} {1}
do_test minmax3-2.5 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1; }
} {1}
do_test minmax3-2.6 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<2; }
} {1}
do_test minmax3-2.7 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<1; }
} {{}}
do_test minmax3-2.8 {
  execsql { SELECT min(b) FROM t2 WHERE a = 3 AND b<1; }
} {{}}

do_test minmax3-2.1 {
  execsql {
    DROP TABLE t2;
    CREATE TABLE t2(a, b);
    CREATE INDEX i3 ON t2(a, b DESC);
    INSERT INTO t2 VALUES(1, NULL);
    INSERT INTO t2 VALUES(1, 1);
    INSERT INTO t2 VALUES(1, 2);
    INSERT INTO t2 VALUES(1, 3);
    INSERT INTO t2 VALUES(2, NULL);
    INSERT INTO t2 VALUES(2, 1);
    INSERT INTO t2 VALUES(2, 2);
    INSERT INTO t2 VALUES(2, 3);
    INSERT INTO t2 VALUES(3, 1);
    INSERT INTO t2 VALUES(3, 2);
    INSERT INTO t2 VALUES(3, 3);
  }
} {}
do_test minmax3-2.2 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1; }
} {1}
do_test minmax3-2.3 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>1; }
} {2}
do_test minmax3-2.4 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>-1; }
} {1}
do_test minmax3-2.5 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1; }
} {1}
do_test minmax3-2.6 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<2; }
} {1}
do_test minmax3-2.7 {
  execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<1; }
} {{}}
do_test minmax3-2.8 {
  execsql { SELECT min(b) FROM t2 WHERE a = 3 AND b<1; }
} {{}}

finish_test

Added test/misc1.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# 2001 September 15.
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for miscellanous features that were
# left out of other test files.
#
# $Id: misc1.test,v 1.42 2007/11/05 14:58:23 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Mimic the SQLite 2 collation type NUMERIC.
db collate numeric numeric_collate
proc numeric_collate {lhs rhs} {
  if {$lhs == $rhs} {return 0} 
  return [expr ($lhs>$rhs)?1:-1]
}

# Mimic the SQLite 2 collation type TEXT.
db collate text text_collate
proc numeric_collate {lhs rhs} {
  return [string compare $lhs $rhs]
}

# Test the creation and use of tables that have a large number
# of columns.
#
do_test misc1-1.1 {
  set cmd "CREATE TABLE manycol(x0 text"
  for {set i 1} {$i<=99} {incr i} {
    append cmd ",x$i text"
  }
  append cmd ")";
  execsql $cmd
  set cmd "INSERT INTO manycol VALUES(0"
  for {set i 1} {$i<=99} {incr i} {
    append cmd ",$i"
  }
  append cmd ")";
  execsql $cmd
  execsql "SELECT x99 FROM manycol"
} 99
do_test misc1-1.2 {
  execsql {SELECT x0, x10, x25, x50, x75 FROM manycol}
} {0 10 25 50 75}
do_test misc1-1.3.1 {
  for {set j 100} {$j<=1000} {incr j 100} {
    set cmd "INSERT INTO manycol VALUES($j"
    for {set i 1} {$i<=99} {incr i} {
      append cmd ",[expr {$i+$j}]"
    }
    append cmd ")"
    execsql $cmd
  }
  execsql {SELECT x50 FROM manycol ORDER BY x80+0}
} {50 150 250 350 450 550 650 750 850 950 1050}
do_test misc1-1.3.2 {
  execsql {SELECT x50 FROM manycol ORDER BY x80}
} {1050 150 250 350 450 550 650 750 50 850 950}
do_test misc1-1.4 {
  execsql {SELECT x75 FROM manycol WHERE x50=350}
} 375
do_test misc1-1.5 {
  execsql {SELECT x50 FROM manycol WHERE x99=599}
} 550
do_test misc1-1.6 {
  execsql {CREATE INDEX manycol_idx1 ON manycol(x99)}
  execsql {SELECT x50 FROM manycol WHERE x99=899}
} 850
do_test misc1-1.7 {
  execsql {SELECT count(*) FROM manycol}
} 11
do_test misc1-1.8 {
  execsql {DELETE FROM manycol WHERE x98=1234}
  execsql {SELECT count(*) FROM manycol}
} 11
do_test misc1-1.9 {
  execsql {DELETE FROM manycol WHERE x98=998}
  execsql {SELECT count(*) FROM manycol}
} 10
do_test misc1-1.10 {
  execsql {DELETE FROM manycol WHERE x99=500}
  execsql {SELECT count(*) FROM manycol}
} 10
do_test misc1-1.11 {
  execsql {DELETE FROM manycol WHERE x99=599}
  execsql {SELECT count(*) FROM manycol}
} 9

# Check GROUP BY expressions that name two or more columns.
#
do_test misc1-2.1 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE agger(one text, two text, three text, four text);
    INSERT INTO agger VALUES(1, 'one', 'hello', 'yes');
    INSERT INTO agger VALUES(2, 'two', 'howdy', 'no');
    INSERT INTO agger VALUES(3, 'thr', 'howareya', 'yes');
    INSERT INTO agger VALUES(4, 'two', 'lothere', 'yes');
    INSERT INTO agger VALUES(5, 'one', 'atcha', 'yes');
    INSERT INTO agger VALUES(6, 'two', 'hello', 'no');
    COMMIT
  }
  execsql {SELECT count(*) FROM agger}
} 6
do_test misc1-2.2 {
  execsql {SELECT sum(one), two, four FROM agger
           GROUP BY two, four ORDER BY sum(one) desc}
} {8 two no 6 one yes 4 two yes 3 thr yes}
do_test misc1-2.3 {
  execsql {SELECT sum((one)), (two), (four) FROM agger
           GROUP BY (two), (four) ORDER BY sum(one) desc}
} {8 two no 6 one yes 4 two yes 3 thr yes}

# Here's a test for a bug found by Joel Lucsy.  The code below
# was causing an assertion failure.
#
do_test misc1-3.1 {
  set r [execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES('hi');
    PRAGMA full_column_names=on;
    SELECT rowid, * FROM t1;
  }]
  lindex $r 1
} {hi}

# Here's a test for yet another bug found by Joel Lucsy.  The code
# below was causing an assertion failure.
#
do_test misc1-4.1 {
  execsql {
    BEGIN;
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES('This is a long string to use up a lot of disk -');
    UPDATE t2 SET a=a||a||a||a;
    INSERT INTO t2 SELECT '1 - ' || a FROM t2;
    INSERT INTO t2 SELECT '2 - ' || a FROM t2;
    INSERT INTO t2 SELECT '3 - ' || a FROM t2;
    INSERT INTO t2 SELECT '4 - ' || a FROM t2;
    INSERT INTO t2 SELECT '5 - ' || a FROM t2;
    INSERT INTO t2 SELECT '6 - ' || a FROM t2;
    COMMIT;
    SELECT count(*) FROM t2;
  }
} {64}

# Make sure we actually see a semicolon or end-of-file in the SQL input
# before executing a command.  Thus if "WHERE" is misspelled on an UPDATE,
# the user won't accidently update every record.
#
do_test misc1-5.1 {
  catchsql {
    CREATE TABLE t3(a,b);
    INSERT INTO t3 VALUES(1,2);
    INSERT INTO t3 VALUES(3,4);
    UPDATE t3 SET a=0 WHEREwww b=2;
  }
} {1 {near "WHEREwww": syntax error}}
do_test misc1-5.2 {
  execsql {
    SELECT * FROM t3 ORDER BY a;
  }
} {1 2 3 4}

# Certain keywords (especially non-standard keywords like "REPLACE") can
# also be used as identifiers.  The way this works in the parser is that
# the parser first detects a syntax error, the error handling routine
# sees that the special keyword caused the error, then replaces the keyword
# with "ID" and tries again.
#
# Check the operation of this logic.
#
do_test misc1-6.1 {
  catchsql {
    CREATE TABLE t4(
      abort, asc, begin, cluster, conflict, copy, delimiters, desc, end,
      explain, fail, ignore, key, offset, pragma, replace, temp,
      vacuum, view
    );
  }
} {0 {}}
do_test misc1-6.2 {
  catchsql {
    INSERT INTO t4
       VALUES(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
  }
} {0 {}}
do_test misc1-6.3 {
  execsql {
    SELECT * FROM t4
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19}
do_test misc1-6.4 {
  execsql {
    SELECT abort+asc,max(key,pragma,temp) FROM t4
  }
} {3 17}

# Test for multi-column primary keys, and for multiple primary keys.
#
do_test misc1-7.1 {
  catchsql {
    CREATE TABLE error1(
      a TYPE PRIMARY KEY,
      b TYPE PRIMARY KEY
    );
  }
} {1 {table "error1" has more than one primary key}}
do_test misc1-7.2 {
  catchsql {
    CREATE TABLE error1(
      a INTEGER PRIMARY KEY,
      b TYPE PRIMARY KEY
    );
  }
} {1 {table "error1" has more than one primary key}}
do_test misc1-7.3 {
  execsql {
    CREATE TABLE t5(a,b,c,PRIMARY KEY(a,b));
    INSERT INTO t5 VALUES(1,2,3);
    SELECT * FROM t5 ORDER BY a;
  }
} {1 2 3}
do_test misc1-7.4 {
  catchsql {
    INSERT INTO t5 VALUES(1,2,4);
  }
} {1 {columns a, b are not unique}}
do_test misc1-7.5 {
  catchsql {
    INSERT INTO t5 VALUES(0,2,4);
  }
} {0 {}}
do_test misc1-7.6 {
  execsql {
    SELECT * FROM t5 ORDER BY a;
  }
} {0 2 4 1 2 3}

do_test misc1-8.1 {
  catchsql {
    SELECT *;
  }
} {1 {no tables specified}}
do_test misc1-8.2 {
  catchsql {
    SELECT t1.*;
  }
} {1 {no such table: t1}}

execsql {
  DROP TABLE t1;
  DROP TABLE t2;
  DROP TABLE t3;
  DROP TABLE t4;
}

# 64-bit integers are represented exactly.
#
do_test misc1-9.1 {
  catchsql {
    CREATE TABLE t1(a unique not null, b unique not null);
    INSERT INTO t1 VALUES('a',1234567890123456789);
    INSERT INTO t1 VALUES('b',1234567891123456789);
    INSERT INTO t1 VALUES('c',1234567892123456789);
    SELECT * FROM t1;
  }
} {0 {a 1234567890123456789 b 1234567891123456789 c 1234567892123456789}}

# A WHERE clause is not allowed to contain more than 99 terms.  Check to
# make sure this limit is enforced.
#
# 2005-07-16: There is no longer a limit on the number of terms in a
# WHERE clause.  But keep these tests just so that we have some tests
# that use a large number of terms in the WHERE clause.
#
do_test misc1-10.0 {
  execsql {SELECT count(*) FROM manycol}
} {9}
do_test misc1-10.1 {
  set ::where {WHERE x0>=0}
  for {set i 1} {$i<=99} {incr i} {
    append ::where " AND x$i<>0"
  }
  catchsql "SELECT count(*) FROM manycol $::where"
} {0 9}
do_test misc1-10.2 {
  catchsql "SELECT count(*) FROM manycol $::where AND rowid>0"
} {0 9}
do_test misc1-10.3 {
  regsub "x0>=0" $::where "x0=0" ::where
  catchsql "DELETE FROM manycol $::where"
} {0 {}}
do_test misc1-10.4 {
  execsql {SELECT count(*) FROM manycol}
} {8}
do_test misc1-10.5 {
  catchsql "DELETE FROM manycol $::where AND rowid>0"
} {0 {}}
do_test misc1-10.6 {
  execsql {SELECT x1 FROM manycol WHERE x0=100}
} {101}
do_test misc1-10.7 {
  regsub "x0=0" $::where "x0=100" ::where
  catchsql "UPDATE manycol SET x1=x1+1 $::where"
} {0 {}}
do_test misc1-10.8 {
  execsql {SELECT x1 FROM manycol WHERE x0=100}
} {102}
do_test misc1-10.9 {
  catchsql "UPDATE manycol SET x1=x1+1 $::where AND rowid>0"
} {0 {}}
do_test misc1-10.10 {
  execsql {SELECT x1 FROM manycol WHERE x0=100}
} {103}

# Make sure the initialization works even if a database is opened while
# another process has the database locked.
#
# Update for v3: The BEGIN doesn't lock the database so the schema is read
# and the SELECT returns successfully.
do_test misc1-11.1 {
  execsql {BEGIN}
  execsql {UPDATE t1 SET a=0 WHERE 0}
  sqlite3 db2 test.db
  set rc [catch {db2 eval {SELECT count(*) FROM t1}} msg]
  lappend rc $msg
# v2 result: {1 {database is locked}}
} {0 3}
do_test misc1-11.2 {
  execsql {COMMIT}
  set rc [catch {db2 eval {SELECT count(*) FROM t1}} msg]
  db2 close
  lappend rc $msg
} {0 3}

# Make sure string comparisons really do compare strings in format4+.
# Similar tests in the format3.test file show that for format3 and earlier
# all comparisions where numeric if either operand looked like a number.
#
do_test misc1-12.1 {
  execsql {SELECT '0'=='0.0'}
} {0}
do_test misc1-12.2 {
  execsql {SELECT '0'==0.0}
} {0}
do_test misc1-12.3 {
  execsql {SELECT '12345678901234567890'=='12345678901234567891'}
} {0}
do_test misc1-12.4 {
  execsql {
    CREATE TABLE t6(a INT UNIQUE, b TEXT UNIQUE);
    INSERT INTO t6 VALUES('0','0.0');
    SELECT * FROM t6;
  }
} {0 0.0}
ifcapable conflict {
  do_test misc1-12.5 {
    execsql {
      INSERT OR IGNORE INTO t6 VALUES(0.0,'x');
      SELECT * FROM t6;
    }
  } {0 0.0}
  do_test misc1-12.6 {
    execsql {
      INSERT OR IGNORE INTO t6 VALUES('y',0);
      SELECT * FROM t6;
    }
  } {0 0.0 y 0}
}
do_test misc1-12.7 {
  execsql {
    CREATE TABLE t7(x INTEGER, y TEXT, z);
    INSERT INTO t7 VALUES(0,0,1);
    INSERT INTO t7 VALUES(0.0,0,2);
    INSERT INTO t7 VALUES(0,0.0,3);
    INSERT INTO t7 VALUES(0.0,0.0,4);
    SELECT DISTINCT x, y FROM t7 ORDER BY z;
  }
} {0 0 0 0.0}
do_test misc1-12.8 {
  execsql {
    SELECT min(z), max(z), count(z) FROM t7 GROUP BY x ORDER BY 1;
  }
} {1 4 4}
do_test misc1-12.9 {
  execsql {
    SELECT min(z), max(z), count(z) FROM t7 GROUP BY y ORDER BY 1;
  }
} {1 2 2 3 4 2}

# This used to be an error.  But we changed the code so that arbitrary
# identifiers can be used as a collating sequence.  Collation is by text
# if the identifier contains "text", "blob", or "clob" and is numeric
# otherwise.
#
# Update: In v3, it is an error again.
#
#do_test misc1-12.10 {
#  catchsql {
#    SELECT * FROM t6 ORDER BY a COLLATE unknown;
#  }
#} {0 {0 0 y 0}}
do_test misc1-12.11 {
  execsql {
    CREATE TABLE t8(x TEXT COLLATE numeric, y INTEGER COLLATE text, z);
    INSERT INTO t8 VALUES(0,0,1);
    INSERT INTO t8 VALUES(0.0,0,2);
    INSERT INTO t8 VALUES(0,0.0,3);
    INSERT INTO t8 VALUES(0.0,0.0,4);
    SELECT DISTINCT x, y FROM t8 ORDER BY z;
  }
} {0 0 0.0 0}
do_test misc1-12.12 {
  execsql {
    SELECT min(z), max(z), count(z) FROM t8 GROUP BY x ORDER BY 1;
  }
} {1 3 2 2 4 2}
do_test misc1-12.13 {
  execsql {
    SELECT min(z), max(z), count(z) FROM t8 GROUP BY y ORDER BY 1;
  }
} {1 4 4}

# There was a problem with realloc() in the OP_MemStore operation of
# the VDBE.  A buffer was being reallocated but some pointers into 
# the old copy of the buffer were not being moved over to the new copy.
# The following code tests for the problem.
#
ifcapable subquery {
  do_test misc1-13.1 {
     execsql {
       CREATE TABLE t9(x,y);
       INSERT INTO t9 VALUES('one',1);
       INSERT INTO t9 VALUES('two',2);
       INSERT INTO t9 VALUES('three',3);
       INSERT INTO t9 VALUES('four',4);
       INSERT INTO t9 VALUES('five',5);
       INSERT INTO t9 VALUES('six',6);
       INSERT INTO t9 VALUES('seven',7);
       INSERT INTO t9 VALUES('eight',8);
       INSERT INTO t9 VALUES('nine',9);
       INSERT INTO t9 VALUES('ten',10);
       INSERT INTO t9 VALUES('eleven',11);
       SELECT y FROM t9
       WHERE x=(SELECT x FROM t9 WHERE y=1)
          OR x=(SELECT x FROM t9 WHERE y=2)
          OR x=(SELECT x FROM t9 WHERE y=3)
          OR x=(SELECT x FROM t9 WHERE y=4)
          OR x=(SELECT x FROM t9 WHERE y=5)
          OR x=(SELECT x FROM t9 WHERE y=6)
          OR x=(SELECT x FROM t9 WHERE y=7)
          OR x=(SELECT x FROM t9 WHERE y=8)
          OR x=(SELECT x FROM t9 WHERE y=9)
          OR x=(SELECT x FROM t9 WHERE y=10)
          OR x=(SELECT x FROM t9 WHERE y=11)
          OR x=(SELECT x FROM t9 WHERE y=12)
          OR x=(SELECT x FROM t9 WHERE y=13)
          OR x=(SELECT x FROM t9 WHERE y=14)
       ;
     }
  } {1 2 3 4 5 6 7 8 9 10 11}
}

# Make sure a database connection still works after changing the
# working directory.
#
do_test misc1-14.1 {
  file mkdir tempdir
  cd tempdir
  execsql {BEGIN}
  file exists ./test.db-journal
} {0}
do_test misc1-14.2 {
  execsql {UPDATE t1 SET a=0 WHERE 0}
  file exists ../test.db-journal
} {1}
do_test misc1-14.3 {
  cd ..
  file delete -force tempdir
  execsql {COMMIT}
  file exists ./test.db-journal
} {0}

# A failed create table should not leave the table in the internal
# data structures.  Ticket #238.
#
do_test misc1-15.1.1 {
  catchsql {
    CREATE TABLE t10 AS SELECT c1;
  }
} {1 {no such column: c1}}
do_test misc1-15.1.2 {
  catchsql {
    CREATE TABLE t10 AS SELECT t9.c1;
  }
} {1 {no such column: t9.c1}}
do_test misc1-15.1.3 {
  catchsql {
    CREATE TABLE t10 AS SELECT main.t9.c1;
  }
} {1 {no such column: main.t9.c1}}
do_test misc1-15.2 {
  catchsql {
    CREATE TABLE t10 AS SELECT 1;
  }
  # The bug in ticket #238 causes the statement above to fail with
  # the error "table t10 alread exists"
} {0 {}}

# Test for memory leaks when a CREATE TABLE containing a primary key
# fails.  Ticket #249.
#
do_test misc1-16.1 {
  catchsql {SELECT name FROM sqlite_master LIMIT 1}
  catchsql {
    CREATE TABLE test(a integer, primary key(a));
  }
} {0 {}}
do_test misc1-16.2 {
  catchsql {
    CREATE TABLE test(a integer, primary key(a));
  }
} {1 {table test already exists}}
do_test misc1-16.3 {
  catchsql {
    CREATE TABLE test2(a text primary key, b text, primary key(a,b));
  }
} {1 {table "test2" has more than one primary key}}
do_test misc1-16.4 {
  execsql {
    INSERT INTO test VALUES(1);
    SELECT rowid, a FROM test;
  }
} {1 1}
do_test misc1-16.5 {
  execsql {
    INSERT INTO test VALUES(5);
    SELECT rowid, a FROM test;
  }
} {1 1 5 5}
do_test misc1-16.6 {
  execsql {
    INSERT INTO test VALUES(NULL);
    SELECT rowid, a FROM test;
  }
} {1 1 5 5 6 6}

ifcapable trigger&&tempdb {
# Ticket #333: Temp triggers that modify persistent tables.
#
do_test misc1-17.1 {
  execsql {
    BEGIN;
    CREATE TABLE RealTable(TestID INTEGER PRIMARY KEY, TestString TEXT);
    CREATE TEMP TABLE TempTable(TestID INTEGER PRIMARY KEY, TestString TEXT);
    CREATE TEMP TRIGGER trigTest_1 AFTER UPDATE ON TempTable BEGIN
      INSERT INTO RealTable(TestString) 
         SELECT new.TestString FROM TempTable LIMIT 1;
    END;
    INSERT INTO TempTable(TestString) VALUES ('1');
    INSERT INTO TempTable(TestString) VALUES ('2');
    UPDATE TempTable SET TestString = TestString + 1 WHERE TestID=1 OR TestId=2;
    COMMIT;
    SELECT TestString FROM RealTable ORDER BY 1;
  }
} {2 3}
}

do_test misc1-18.1 {
  set n [sqlite3_sleep 100]
  expr {$n>=100}
} {1}

finish_test

Added test/misc2.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# 2003 June 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for miscellanous features that were
# left out of other test files.
#
# $Id: misc2.test,v 1.28 2007/09/12 17:01:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# The tests in this file were written before SQLite supported recursive
# trigger invocation, and some tests depend on that to pass. So disable
# recursive triggers for this file.
catchsql { pragma recursive_triggers = off } 

ifcapable {trigger} {
# Test for ticket #360
#
do_test misc2-1.1 {
  catchsql {
    CREATE TABLE FOO(bar integer);
    CREATE TRIGGER foo_insert BEFORE INSERT ON foo BEGIN
      SELECT CASE WHEN (NOT new.bar BETWEEN 0 AND 20)
             THEN raise(rollback, 'aiieee') END;
    END;
    INSERT INTO foo(bar) VALUES (1);
  }
} {0 {}}
do_test misc2-1.2 {
  catchsql {
    INSERT INTO foo(bar) VALUES (111);
  }
} {1 aiieee}
} ;# endif trigger

# Make sure ROWID works on a view and a subquery.  Ticket #364
#
do_test misc2-2.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    CREATE TABLE t2(a,b,c);
    INSERT INTO t2 VALUES(7,8,9);
  }
} {}
ifcapable subquery {
  do_test misc2-2.2 {
    execsql {
      SELECT rowid, * FROM (SELECT * FROM t1, t2);
    }
  } {{} 1 2 3 7 8 9}
}
ifcapable view {
  do_test misc2-2.3 {
    execsql {
      CREATE VIEW v1 AS SELECT * FROM t1, t2;
      SELECT rowid, * FROM v1;
    }
  } {{} 1 2 3 7 8 9}
} ;# ifcapable view

# Ticket #2002 and #1952.
ifcapable subquery {
  do_test misc2-2.4 {
    execsql2 {
      SELECT * FROM (SELECT a, b AS 'a', c AS 'a', 4 AS 'a' FROM t1)
    }
  } {a 1 a:1 2 a:2 3 a:3 4}
}

# Check name binding precedence.  Ticket #387
#
do_test misc2-3.1 {
  catchsql {
    SELECT t1.b+t2.b AS a, t1.a, t2.a FROM t1, t2 WHERE a==10
  }
} {1 {ambiguous column name: a}}

# Make sure 32-bit integer overflow is handled properly in queries.
# ticket #408
#
do_test misc2-4.1 {
  execsql {
    INSERT INTO t1 VALUES(4000000000,'a','b');
    SELECT a FROM t1 WHERE a>1;
  }
} {4000000000}
do_test misc2-4.2 {
  execsql {
    INSERT INTO t1 VALUES(2147483648,'b2','c2');
    INSERT INTO t1 VALUES(2147483647,'b3','c3');
    SELECT a FROM t1 WHERE a>2147483647;
  }
} {4000000000 2147483648}
do_test misc2-4.3 {
  execsql {
    SELECT a FROM t1 WHERE a<2147483648;
  }
} {1 2147483647}
do_test misc2-4.4 {
  execsql {
    SELECT a FROM t1 WHERE a<=2147483648;
  }
} {1 2147483648 2147483647}
do_test misc2-4.5 {
  execsql {
    SELECT a FROM t1 WHERE a<10000000000;
  }
} {1 4000000000 2147483648 2147483647}
do_test misc2-4.6 {
  execsql {
    SELECT a FROM t1 WHERE a<1000000000000 ORDER BY 1;
  }
} {1 2147483647 2147483648 4000000000}

# There were some issues with expanding a SrcList object using a call
# to sqliteSrcListAppend() if the SrcList had previously been duplicated
# using a call to sqliteSrcListDup().  Ticket #416.  The following test
# makes sure the problem has been fixed.
#
ifcapable view {
do_test misc2-5.1 {
  execsql {
    CREATE TABLE x(a,b);
    CREATE VIEW y AS 
      SELECT x1.b AS p, x2.b AS q FROM x AS x1, x AS x2 WHERE x1.a=x2.a;
    CREATE VIEW z AS
      SELECT y1.p, y2.p FROM y AS y1, y AS y2 WHERE y1.q=y2.q;
    SELECT * from z;
  }
} {}
}

# Make sure we can open a database with an empty filename.  What this
# does is store the database in a temporary file that is deleted when
# the database is closed.  Ticket #432.
#
do_test misc2-6.1 {
  db close
  sqlite3 db {}
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    SELECT * FROM t1;
  }
} {1 2}

# Make sure we get an error message (not a segfault) on an attempt to
# update a table from within the callback of a select on that same
# table.
#
# 2006-08-16:  This has changed.  It is now permitted to update
# the table being SELECTed from within the callback of the query.
#
ifcapable tclvar {
  do_test misc2-7.1 {
    db close
    file delete -force test.db
    sqlite3 db test.db
    execsql {
      CREATE TABLE t1(x);
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      SELECT * FROM t1;
    }
  } {1 2 3}
  do_test misc2-7.2 {
    set rc [catch {
      db eval {SELECT rowid FROM t1} {} {
        db eval "DELETE FROM t1 WHERE rowid=$rowid"
      }
    } msg]
    lappend rc $msg
  } {0 {}}
  do_test misc2-7.3 {
    execsql {SELECT * FROM t1}
  } {}
  do_test misc2-7.4 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1} {
      if {$x & 1} {
        db eval {DELETE FROM t1 WHERE rowid=$rowid}
      }
    }
    execsql {SELECT * FROM t1}
  } {2 4}
  do_test misc2-7.5 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1} {
      if {$x & 1} {
        db eval {DELETE FROM t1 WHERE rowid=$rowid+1}
      }
    }
    execsql {SELECT * FROM t1}
  } {1 3}
  do_test misc2-7.6 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1} {
      if {$x & 1} {
        db eval {DELETE FROM t1}
      }
    }
    execsql {SELECT * FROM t1}
  } {}
  do_test misc2-7.7 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1} {
      if {$x & 1} {
        db eval {UPDATE t1 SET x=x+100 WHERE rowid=$rowid}
      }
    }
    execsql {SELECT * FROM t1}
  } {101 2 103 4}
  do_test misc2-7.8 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
    }
    db eval {SELECT rowid, x FROM t1} {
      if {$x<10} {
        db eval {INSERT INTO t1 VALUES($x+1)}
      }
    }
    execsql {SELECT * FROM t1}
  } {1 2 3 4 5 6 7 8 9 10}
  
  # Repeat the tests 7.1 through 7.8 about but this time do the SELECTs
  # in reverse order so that we exercise the sqlite3BtreePrev() routine
  # instead of sqlite3BtreeNext()
  #
  do_test misc2-7.11 {
    db close
    file delete -force test.db
    sqlite3 db test.db
    execsql {
      CREATE TABLE t1(x);
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      SELECT * FROM t1;
    }
  } {1 2 3}
  do_test misc2-7.12 {
    set rc [catch {
      db eval {SELECT rowid FROM t1 ORDER BY rowid DESC} {} {
        db eval "DELETE FROM t1 WHERE rowid=$rowid"
      }
    } msg]
    lappend rc $msg
  } {0 {}}
  do_test misc2-7.13 {
    execsql {SELECT * FROM t1}
  } {}
  do_test misc2-7.14 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} {
      if {$x & 1} {
        db eval {DELETE FROM t1 WHERE rowid=$rowid}
      }
    }
    execsql {SELECT * FROM t1}
  } {2 4}
  do_test misc2-7.15 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1} {
      if {$x & 1} {
        db eval {DELETE FROM t1 WHERE rowid=$rowid+1}
      }
    }
    execsql {SELECT * FROM t1}
  } {1 3}
  do_test misc2-7.16 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} {
      if {$x & 1} {
        db eval {DELETE FROM t1}
      }
    }
    execsql {SELECT * FROM t1}
  } {}
  do_test misc2-7.17 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
      INSERT INTO t1 VALUES(4);
    }
    db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} {
      if {$x & 1} {
        db eval {UPDATE t1 SET x=x+100 WHERE rowid=$rowid}
      }
    }
    execsql {SELECT * FROM t1}
  } {101 2 103 4}
  do_test misc2-7.18 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1(rowid,x) VALUES(10,10);
    }
    db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} {
      if {$x>1} {
        db eval {INSERT INTO t1(rowid,x) VALUES($x-1,$x-1)}
      }
    }
    execsql {SELECT * FROM t1}
  } {1 2 3 4 5 6 7 8 9 10}
}

db close
file delete -force test.db
sqlite3 db test.db
catchsql { pragma recursive_triggers = off } 

# Ticket #453.  If the SQL ended with "-", the tokenizer was calling that
# an incomplete token, which caused problem.  The solution was to just call
# it a minus sign.
#
do_test misc2-8.1 {
  catchsql {-}
} {1 {near "-": syntax error}}

# Ticket #513.  Make sure the VDBE stack does not grow on a 3-way join.
#
ifcapable tempdb {
  do_test misc2-9.1 {
    execsql {
      BEGIN;
      CREATE TABLE counts(n INTEGER PRIMARY KEY);
      INSERT INTO counts VALUES(0);
      INSERT INTO counts VALUES(1);
      INSERT INTO counts SELECT n+2 FROM counts;
      INSERT INTO counts SELECT n+4 FROM counts;
      INSERT INTO counts SELECT n+8 FROM counts;
      COMMIT;
  
      CREATE TEMP TABLE x AS
      SELECT dim1.n, dim2.n, dim3.n
      FROM counts AS dim1, counts AS dim2, counts AS dim3
      WHERE dim1.n<10 AND dim2.n<10 AND dim3.n<10;
  
      SELECT count(*) FROM x;
    }
  } {1000}
  do_test misc2-9.2 {
    execsql {
      DROP TABLE x;
      CREATE TEMP TABLE x AS
      SELECT dim1.n, dim2.n, dim3.n
      FROM counts AS dim1, counts AS dim2, counts AS dim3
      WHERE dim1.n>=6 AND dim2.n>=6 AND dim3.n>=6;
  
      SELECT count(*) FROM x;
    }
  } {1000}
  do_test misc2-9.3 {
    execsql {
      DROP TABLE x;
      CREATE TEMP TABLE x AS
      SELECT dim1.n, dim2.n, dim3.n, dim4.n
      FROM counts AS dim1, counts AS dim2, counts AS dim3, counts AS dim4
      WHERE dim1.n<5 AND dim2.n<5 AND dim3.n<5 AND dim4.n<5;
  
      SELECT count(*) FROM x;
    }
  } [expr 5*5*5*5]
}

# Ticket #1229.  Sometimes when a "NEW.X" appears in a SELECT without
# a FROM clause deep within a trigger, the code generator is unable to
# trace the NEW.X back to an original table and thus figure out its
# declared datatype.
#
# The SQL code below was causing a segfault.
#
ifcapable subquery&&trigger {
  do_test misc2-10.1 {
    execsql {
      CREATE TABLE t1229(x);
      CREATE TRIGGER r1229 BEFORE INSERT ON t1229 BEGIN
        INSERT INTO t1229 SELECT y FROM (SELECT new.x y);
      END;
      INSERT INTO t1229 VALUES(1);
    }
  } {}
}

finish_test

Added test/misc3.test.































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# 2003 December 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for miscellanous features that were
# left out of other test files.
#
# $Id: misc3.test,v 1.20 2009/05/06 00:49:01 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {integrityck} {
  # Ticket #529.  Make sure an ABORT does not damage the in-memory cache
  # that will be used by subsequent statements in the same transaction.
  #
  do_test misc3-1.1 {
    execsql {
      CREATE TABLE t1(a UNIQUE,b);
      INSERT INTO t1
        VALUES(1,'a23456789_b23456789_c23456789_d23456789_e23456789_');
      UPDATE t1 SET b=b||b;
      UPDATE t1 SET b=b||b;
      UPDATE t1 SET b=b||b;
      UPDATE t1 SET b=b||b;
      UPDATE t1 SET b=b||b;
      INSERT INTO t1 VALUES(2,'x');
      UPDATE t1 SET b=substr(b,1,500);
      BEGIN;
    }
    catchsql {UPDATE t1 SET a=CASE a WHEN 2 THEN 1 ELSE a END, b='y';}
    execsql {
      CREATE TABLE t2(x,y);
      COMMIT;
      PRAGMA integrity_check;
    }
  } ok
}
ifcapable {integrityck} {
  do_test misc3-1.2 {
    execsql {
      DROP TABLE t1;
      DROP TABLE t2;
    }
    ifcapable {vacuum} {execsql VACUUM}
    execsql {
      CREATE TABLE t1(a UNIQUE,b);
      INSERT INTO t1
      VALUES(1,'a23456789_b23456789_c23456789_d23456789_e23456789_');
      INSERT INTO t1 SELECT a+1, b||b FROM t1;
      INSERT INTO t1 SELECT a+2, b||b FROM t1;
      INSERT INTO t1 SELECT a+4, b FROM t1;
      INSERT INTO t1 SELECT a+8, b FROM t1;
      INSERT INTO t1 SELECT a+16, b FROM t1;
      INSERT INTO t1 SELECT a+32, b FROM t1;
      INSERT INTO t1 SELECT a+64, b FROM t1;
      BEGIN;
    }
    catchsql {UPDATE t1 SET a=CASE a WHEN 128 THEN 127 ELSE a END, b='';}
    execsql {
      INSERT INTO t1 VALUES(200,'hello out there');
      COMMIT;
      PRAGMA integrity_check;
    }
  } ok
}

# Tests of the sqliteAtoF() function in util.c
#
do_test misc3-2.1 {
  execsql {SELECT 2e-25*0.5e25}
} 1.0
do_test misc3-2.2 {
  execsql {SELECT 2.0e-25*000000.500000000000000000000000000000e+00025}
} 1.0
do_test misc3-2.3 {
  execsql {SELECT 000000000002e-0000000025*0.5e25}
} 1.0
do_test misc3-2.4 {
  execsql {SELECT 2e-25*0.5e250}
} 1e+225
do_test misc3-2.5 {
  execsql {SELECT 2.0e-250*0.5e25}
} 1e-225
do_test misc3-2.6 {
  execsql {SELECT '-2.0e-127' * '-0.5e27'}
} 1e-100
do_test misc3-2.7 {
  execsql {SELECT '+2.0e-127' * '-0.5e27'}
} -1e-100
do_test misc3-2.8 {
  execsql {SELECT 2.0e-27 * '+0.5e+127'}
} 1e+100
do_test misc3-2.9 {
  execsql {SELECT 2.0e-27 * '+0.000005e+132'}
} 1e+100

# Ticket #522.  Make sure integer overflow is handled properly in
# indices.
#
integrity_check misc3-3.1
do_test misc3-3.2 {
  execsql {
    CREATE TABLE t2(a INT UNIQUE);
  }
} {}
integrity_check misc3-3.2.1
do_test misc3-3.3 {
  execsql {
    INSERT INTO t2 VALUES(2147483648);
  }
} {}
integrity_check misc3-3.3.1
do_test misc3-3.4 {
  execsql {
    INSERT INTO t2 VALUES(-2147483649);
  }
} {}
integrity_check misc3-3.4.1
do_test misc3-3.5 {
  execsql {
    INSERT INTO t2 VALUES(+2147483649);
  }
} {}
integrity_check misc3-3.5.1
do_test misc3-3.6 {
  execsql {
    INSERT INTO t2 VALUES(+2147483647);
    INSERT INTO t2 VALUES(-2147483648);
    INSERT INTO t2 VALUES(-2147483647);
    INSERT INTO t2 VALUES(2147483646);
    SELECT * FROM t2 ORDER BY a;
  }
} {-2147483649 -2147483648 -2147483647 2147483646 2147483647 2147483648 2147483649}
do_test misc3-3.7 {
  execsql {
    SELECT * FROM t2 WHERE a>=-2147483648 ORDER BY a;
  }
} {-2147483648 -2147483647 2147483646 2147483647 2147483648 2147483649}
do_test misc3-3.8 {
  execsql {
    SELECT * FROM t2 WHERE a>-2147483648 ORDER BY a;
  }
} {-2147483647 2147483646 2147483647 2147483648 2147483649}
do_test misc3-3.9 {
  execsql {
    SELECT * FROM t2 WHERE a>-2147483649 ORDER BY a;
  }
} {-2147483648 -2147483647 2147483646 2147483647 2147483648 2147483649}
do_test misc3-3.10 {
  execsql {
    SELECT * FROM t2 WHERE a>=0 AND a<2147483649 ORDER BY a DESC;
  }
} {2147483648 2147483647 2147483646}
do_test misc3-3.11 {
  execsql {
    SELECT * FROM t2 WHERE a>=0 AND a<=2147483648 ORDER BY a DESC;
  }
} {2147483648 2147483647 2147483646}
do_test misc3-3.12 {
  execsql {
    SELECT * FROM t2 WHERE a>=0 AND a<2147483648 ORDER BY a DESC;
  }
} {2147483647 2147483646}
do_test misc3-3.13 {
  execsql {
    SELECT * FROM t2 WHERE a>=0 AND a<=2147483647 ORDER BY a DESC;
  }
} {2147483647 2147483646}
do_test misc3-3.14 {
  execsql {
    SELECT * FROM t2 WHERE a>=0 AND a<2147483647 ORDER BY a DESC;
  }
} {2147483646}

# Ticket #565.  A stack overflow is occurring when the subquery to the
# right of an IN operator contains many NULLs
#
do_test misc3-4.1 {
  execsql {
    CREATE TABLE t3(a INTEGER PRIMARY KEY, b);
    INSERT INTO t3(b) VALUES('abc');
    INSERT INTO t3(b) VALUES('xyz');
    INSERT INTO t3(b) VALUES(NULL);
    INSERT INTO t3(b) VALUES(NULL);
    INSERT INTO t3(b) SELECT b||'d' FROM t3;
    INSERT INTO t3(b) SELECT b||'e' FROM t3;
    INSERT INTO t3(b) SELECT b||'f' FROM t3;
    INSERT INTO t3(b) SELECT b||'g' FROM t3;
    INSERT INTO t3(b) SELECT b||'h' FROM t3;
    SELECT count(a), count(b) FROM t3;
  }
} {128 64}
ifcapable subquery {
do_test misc3-4.2 {
    execsql {
      SELECT count(a) FROM t3 WHERE b IN (SELECT b FROM t3);
    }
  } {64}
  do_test misc3-4.3 {
    execsql {
      SELECT count(a) FROM t3 WHERE b IN (SELECT b FROM t3 ORDER BY a+1);
    }
  } {64}
}

# Ticket #601:  Putting a left join inside "SELECT * FROM (<join-here>)"
# gives different results that if the outer "SELECT * FROM ..." is omitted.
#
ifcapable subquery {
  do_test misc3-5.1 {
    execsql {
      CREATE TABLE x1 (b, c);
      INSERT INTO x1 VALUES('dog',3);
      INSERT INTO x1 VALUES('cat',1);
      INSERT INTO x1 VALUES('dog',4);
      CREATE TABLE x2 (c, e);
      INSERT INTO x2 VALUES(1,'one');
      INSERT INTO x2 VALUES(2,'two');
      INSERT INTO x2 VALUES(3,'three');
      INSERT INTO x2 VALUES(4,'four');
      SELECT x2.c AS c, e, b FROM x2 LEFT JOIN
         (SELECT b, max(c)+0 AS c FROM x1 GROUP BY b)
         USING(c);
    }
  } {1 one cat 2 two {} 3 three {} 4 four dog}
  do_test misc3-5.2 {
    execsql {
      SELECT * FROM (
        SELECT x2.c AS c, e, b FROM x2 LEFT JOIN
           (SELECT b, max(c)+0 AS c FROM x1 GROUP BY b)
           USING(c)
      );
    }
  } {1 one cat 2 two {} 3 three {} 4 four dog}
}

ifcapable {explain} {
  # Ticket #626:  make sure EXPLAIN prevents BEGIN and COMMIT from working.
  #
  do_test misc3-6.1 {
    execsql {EXPLAIN BEGIN}
    catchsql {BEGIN}
  } {0 {}}
  do_test misc3-6.2 {
    execsql {EXPLAIN COMMIT}
    catchsql {COMMIT}
  } {0 {}}
  do_test misc3-6.3 {
    execsql {BEGIN; EXPLAIN ROLLBACK}
    catchsql {ROLLBACK}
  } {0 {}}

  # Do some additional EXPLAIN operations to exercise the displayP4 logic.
  do_test misc3-6.10 {
    set x [execsql {
      CREATE TABLE ex1(
        a INTEGER DEFAULT 54321,
        b TEXT DEFAULT "hello",
        c REAL DEFAULT 3.1415926
      );
      CREATE UNIQUE INDEX ex1i1 ON ex1(a);
      EXPLAIN REINDEX;
    }]
    regexp { IsUnique \d+ \d+ \d+ \d+ } $x
  } {1}
  if {[regexp {16} [db one {PRAGMA encoding}]]} {
    do_test misc3-6.11-utf16 {
      set x [execsql {
        EXPLAIN SELECT a+123456789012, b*4.5678, c FROM ex1 ORDER BY +a, b DESC
      }]
      set y [regexp { 123456789012 } $x]
      lappend y [regexp { 4.5678 } $x]
      lappend y [regexp {,-BINARY} $x]
    } {1 1 1}
  } else {
    do_test misc3-6.11-utf8 {
      set x [execsql {
        EXPLAIN SELECT a+123456789012, b*4.5678, c FROM ex1 ORDER BY +a, b DESC
      }]
      set y [regexp { 123456789012 } $x]
      lappend y [regexp { 4.5678 } $x]
      lappend y [regexp { hello } $x]
      lappend y [regexp {,-BINARY} $x]
    } {1 1 1 1}
  }
}

ifcapable {trigger} {
# Ticket #640:  vdbe stack overflow with a LIMIT clause on a SELECT inside
# of a trigger.
#
do_test misc3-7.1 {
  execsql {
    BEGIN;
    CREATE TABLE y1(a);
    CREATE TABLE y2(b);
    CREATE TABLE y3(c);
    CREATE TRIGGER r1 AFTER DELETE ON y1 FOR EACH ROW BEGIN
      INSERT INTO y3(c) SELECT b FROM y2 ORDER BY b LIMIT 1;
    END;
    INSERT INTO y1 VALUES(1);
    INSERT INTO y1 VALUES(2);
    INSERT INTO y1 SELECT a+2 FROM y1;
    INSERT INTO y1 SELECT a+4 FROM y1;
    INSERT INTO y1 SELECT a+8 FROM y1;
    INSERT INTO y1 SELECT a+16 FROM y1;
    INSERT INTO y2 SELECT a FROM y1;
    COMMIT;
    SELECT count(*) FROM y1;
  }
} 32
do_test misc3-7.2 {
  execsql {
    DELETE FROM y1;
    SELECT count(*) FROM y1;
  }
} 0
do_test misc3-7.3 {
  execsql {
    SELECT count(*) FROM y3;
  }
} 32
} ;# endif trigger

# Ticket #668:  VDBE stack overflow occurs when the left-hand side
# of an IN expression is NULL and the result is used as an integer, not
# as a jump.
#
ifcapable subquery {
  do_test misc-8.1 {
    execsql {
      SELECT count(CASE WHEN b IN ('abc','xyz') THEN 'x' END) FROM t3
    }
  } {2}
  do_test misc-8.2 {
    execsql {
      SELECT count(*) FROM t3 WHERE 1+(b IN ('abc','xyz'))==2
    }
  } {2}
}

finish_test

Added test/misc4.test.







































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# 2004 Jun 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for miscellanous features that were
# left out of other test files.
#
# $Id: misc4.test,v 1.23 2007/12/08 18:01:31 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Prepare a statement that will create a temporary table.  Then do
# a rollback.  Then try to execute the prepared statement.
#
do_test misc4-1.1 {
  set DB [sqlite3_connection_pointer db]
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
  }
} {}

ifcapable tempdb {
  do_test misc4-1.2 {
    set sql {CREATE TEMP TABLE t2 AS SELECT * FROM t1}
    set stmt [sqlite3_prepare $DB $sql -1 TAIL]
    execsql {
      BEGIN;
      CREATE TABLE t3(a,b,c);
      INSERT INTO t1 SELECT * FROM t1;
      ROLLBACK;
    }
  } {}

  # Because the previous transaction included a DDL statement and
  # was rolled back, statement $stmt was marked as expired. Executing it
  # now returns SQLITE_SCHEMA.
  do_test misc4-1.2.1 {
    list [sqlite3_step $stmt] [sqlite3_finalize $stmt]
  } {SQLITE_ERROR SQLITE_SCHEMA}
  do_test misc4-1.2.2 {
    set stmt [sqlite3_prepare $DB $sql -1 TAIL]
    set TAIL
  } {}

  do_test misc4-1.3 {
    sqlite3_step $stmt
  } SQLITE_DONE
  do_test misc4-1.4 {
    execsql {
      SELECT * FROM temp.t2;
    }
  } {1}
  
  # Drop the temporary table, then rerun the prepared  statement to
  # recreate it again.  This recreates ticket #807.
  #
  do_test misc4-1.5 {
    execsql {DROP TABLE t2}
    sqlite3_reset $stmt
    sqlite3_step $stmt
  } {SQLITE_ERROR}
  do_test misc4-1.6 {
    sqlite3_finalize $stmt
  } {SQLITE_SCHEMA}
}

# Prepare but do not execute various CREATE statements.  Then before
# those statements are executed, try to use the tables, indices, views,
# are triggers that were created.
#
do_test misc4-2.1 {
  set stmt [sqlite3_prepare $DB {CREATE TABLE t3(x);} -1 TAIL]
  catchsql {
    INSERT INTO t3 VALUES(1);
  }
} {1 {no such table: t3}}
do_test misc4-2.2 {
  sqlite3_step $stmt
} SQLITE_DONE
do_test misc4-2.3 {
  sqlite3_finalize $stmt
} SQLITE_OK
do_test misc4-2.4 {
  catchsql {
    INSERT INTO t3 VALUES(1);
  }
} {0 {}}

# Ticket #966
#
do_test misc4-3.1 {
  execsql { 
    CREATE TABLE Table1(ID integer primary key, Value TEXT);
    INSERT INTO Table1 VALUES(1, 'x');
    CREATE TABLE Table2(ID integer NOT NULL, Value TEXT);
    INSERT INTO Table2 VALUES(1, 'z');
    INSERT INTO Table2 VALUES (1, 'a');
  }
  catchsql { 
    SELECT ID, max(Value) FROM Table2 GROUP BY 1, 2 ORDER BY 1, 2;
  }
} {1 {aggregate functions are not allowed in the GROUP BY clause}}
ifcapable compound {
  do_test misc4-3.2 {
    execsql {
      SELECT ID, Value FROM Table1
         UNION SELECT ID, max(Value) FROM Table2 GROUP BY 1
      ORDER BY 1, 2;
    }
  } {1 x 1 z}
  do_test misc4-3.3 {
    catchsql { 
      SELECT ID, Value FROM Table1
         UNION SELECT ID, max(Value) FROM Table2 GROUP BY 1, 2
      ORDER BY 1, 2;
    }
  } {1 {aggregate functions are not allowed in the GROUP BY clause}}
  do_test misc4-3.4 {
    catchsql { 
      SELECT ID, max(Value) FROM Table2 GROUP BY 1, 2
         UNION SELECT ID, Value FROM Table1
      ORDER BY 1, 2;
    }
  } {1 {aggregate functions are not allowed in the GROUP BY clause}}
} ;# ifcapable compound

# Ticket #1047.  Make sure column types are preserved in subqueries.
#
ifcapable subquery {
  do_test misc4-4.1 {
    execsql {
      create table a(key varchar, data varchar);
      create table b(key varchar, period integer);
      insert into a values('01','data01');
      insert into a values('+1','data+1');
      
      insert into b values ('01',1);
      insert into b values ('01',2);
      insert into b values ('+1',3);
      insert into b values ('+1',4);
      
      select a.*, x.*
        from a, (select key,sum(period) from b group by key) as x
        where a.key=x.key;
    }
  } {01 data01 01 3 +1 data+1 +1 7}

  # This test case tests the same property as misc4-4.1, but it is
  # a bit smaller which makes it easier to work with while debugging.
  do_test misc4-4.2 {
    execsql {
      CREATE TABLE ab(a TEXT, b TEXT);
      INSERT INTO ab VALUES('01', '1');
    }
    execsql {
      select * from ab, (select b from ab) as x where x.b = ab.a;
    }
  } {}
}


# Ticket #1036.  When creating tables from a SELECT on a view, use the
# short names of columns.
#
ifcapable view {
  do_test misc4-5.1 {
    execsql {
      create table t4(a,b);
      create table t5(a,c);
      insert into t4 values (1,2);
      insert into t5 values (1,3);
      create view myview as select t4.a a from t4 inner join t5 on t4.a=t5.a;
      create table problem as select * from myview; 
    }
    execsql2 {
      select * FROM problem;
    }
  } {a 1}
  do_test misc4-5.2 {
    execsql2 {
      create table t6 as select * from t4, t5;
      select * from t6;
    }
  } {a 1 b 2 a:1 1 c 3}
}

# Ticket #1086
do_test misc4-6.1 {
  execsql {
    CREATE TABLE abc(a);
    INSERT INTO abc VALUES(1);
    CREATE TABLE def(d, e, f, PRIMARY KEY(d, e));
  }
} {}
do_test misc4-6.2 {
  execsql {
    SELECT a FROM abc LEFT JOIN def ON (abc.a=def.d);
  }
} {1}

finish_test

Added test/misc5.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
# 2005 Mar 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for miscellanous features that were
# left out of other test files.
#
# $Id: misc5.test,v 1.22 2008/07/29 10:26:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build records using the MakeRecord opcode such that the size of the 
# header is at the transition point in the size of a varint.
#
# This test causes an assertion failure or a buffer overrun in version
# 3.1.5 and earlier.
#
for {set i 120} {$i<140} {incr i} {
  do_test misc5-1.$i {
    catchsql {DROP TABLE t1}
    set sql1 {CREATE TABLE t1}
    set sql2 {INSERT INTO t1 VALUES}
    set sep (
    for {set j 0} {$j<$i} {incr j} {
      append sql1 ${sep}a$j
      append sql2 ${sep}$j
      set sep ,
    }
    append sql1 {);}
    append sql2 {);}
    execsql $sql1$sql2
  } {}
}

# Make sure large integers are stored correctly.
#
ifcapable conflict {
  do_test misc5-2.1 {
    execsql {
      create table t2(x unique);
      insert into t2 values(1);
      insert or ignore into t2 select x*2 from t2;
      insert or ignore into t2 select x*4 from t2;
      insert or ignore into t2 select x*16 from t2;
      insert or ignore into t2 select x*256 from t2;
      insert or ignore into t2 select x*65536 from t2;
      insert or ignore into t2 select x*2147483648 from t2;
      insert or ignore into t2 select x-1 from t2;
      insert or ignore into t2 select x+1 from t2;
      insert or ignore into t2 select -x from t2;
      select count(*) from t2;
    }
  } 371
} else {
  do_test misc5-2.1 {
    execsql {
      BEGIN;
      create table t2(x unique);
      create table t2_temp(x);
      insert into t2_temp values(1);
      insert into t2_temp select x*2 from t2_temp;
      insert into t2_temp select x*4 from t2_temp;
      insert into t2_temp select x*16 from t2_temp;
      insert into t2_temp select x*256 from t2_temp;
      insert into t2_temp select x*65536 from t2_temp;
      insert into t2_temp select x*2147483648 from t2_temp;
      insert into t2_temp select x-1 from t2_temp;
      insert into t2_temp select x+1 from t2_temp;
      insert into t2_temp select -x from t2_temp;
      INSERT INTO t2 SELECT DISTINCT(x) FROM t2_temp;
      DROP TABLE t2_temp;
      COMMIT;
      select count(*) from t2;
    }
  } 371
}
do_test misc5-2.2 {
  execsql {
    select x from t2 order by x;
  }
} \
"-4611686018427387905\
-4611686018427387904\
-4611686018427387903\
-2305843009213693953\
-2305843009213693952\
-2305843009213693951\
-1152921504606846977\
-1152921504606846976\
-1152921504606846975\
-576460752303423489\
-576460752303423488\
-576460752303423487\
-288230376151711745\
-288230376151711744\
-288230376151711743\
-144115188075855873\
-144115188075855872\
-144115188075855871\
-72057594037927937\
-72057594037927936\
-72057594037927935\
-36028797018963969\
-36028797018963968\
-36028797018963967\
-18014398509481985\
-18014398509481984\
-18014398509481983\
-9007199254740993\
-9007199254740992\
-9007199254740991\
-4503599627370497\
-4503599627370496\
-4503599627370495\
-2251799813685249\
-2251799813685248\
-2251799813685247\
-1125899906842625\
-1125899906842624\
-1125899906842623\
-562949953421313\
-562949953421312\
-562949953421311\
-281474976710657\
-281474976710656\
-281474976710655\
-140737488355329\
-140737488355328\
-140737488355327\
-70368744177665\
-70368744177664\
-70368744177663\
-35184372088833\
-35184372088832\
-35184372088831\
-17592186044417\
-17592186044416\
-17592186044415\
-8796093022209\
-8796093022208\
-8796093022207\
-4398046511105\
-4398046511104\
-4398046511103\
-2199023255553\
-2199023255552\
-2199023255551\
-1099511627777\
-1099511627776\
-1099511627775\
-549755813889\
-549755813888\
-549755813887\
-274877906945\
-274877906944\
-274877906943\
-137438953473\
-137438953472\
-137438953471\
-68719476737\
-68719476736\
-68719476735\
-34359738369\
-34359738368\
-34359738367\
-17179869185\
-17179869184\
-17179869183\
-8589934593\
-8589934592\
-8589934591\
-4294967297\
-4294967296\
-4294967295\
-2147483649\
-2147483648\
-2147483647\
-1073741825\
-1073741824\
-1073741823\
-536870913\
-536870912\
-536870911\
-268435457\
-268435456\
-268435455\
-134217729\
-134217728\
-134217727\
-67108865\
-67108864\
-67108863\
-33554433\
-33554432\
-33554431\
-16777217\
-16777216\
-16777215\
-8388609\
-8388608\
-8388607\
-4194305\
-4194304\
-4194303\
-2097153\
-2097152\
-2097151\
-1048577\
-1048576\
-1048575\
-524289\
-524288\
-524287\
-262145\
-262144\
-262143\
-131073\
-131072\
-131071\
-65537\
-65536\
-65535\
-32769\
-32768\
-32767\
-16385\
-16384\
-16383\
-8193\
-8192\
-8191\
-4097\
-4096\
-4095\
-2049\
-2048\
-2047\
-1025\
-1024\
-1023\
-513\
-512\
-511\
-257\
-256\
-255\
-129\
-128\
-127\
-65\
-64\
-63\
-33\
-32\
-31\
-17\
-16\
-15\
-9\
-8\
-7\
-5\
-4\
-3\
-2\
-1\
0\
1\
2\
3\
4\
5\
7\
8\
9\
15\
16\
17\
31\
32\
33\
63\
64\
65\
127\
128\
129\
255\
256\
257\
511\
512\
513\
1023\
1024\
1025\
2047\
2048\
2049\
4095\
4096\
4097\
8191\
8192\
8193\
16383\
16384\
16385\
32767\
32768\
32769\
65535\
65536\
65537\
131071\
131072\
131073\
262143\
262144\
262145\
524287\
524288\
524289\
1048575\
1048576\
1048577\
2097151\
2097152\
2097153\
4194303\
4194304\
4194305\
8388607\
8388608\
8388609\
16777215\
16777216\
16777217\
33554431\
33554432\
33554433\
67108863\
67108864\
67108865\
134217727\
134217728\
134217729\
268435455\
268435456\
268435457\
536870911\
536870912\
536870913\
1073741823\
1073741824\
1073741825\
2147483647\
2147483648\
2147483649\
4294967295\
4294967296\
4294967297\
8589934591\
8589934592\
8589934593\
17179869183\
17179869184\
17179869185\
34359738367\
34359738368\
34359738369\
68719476735\
68719476736\
68719476737\
137438953471\
137438953472\
137438953473\
274877906943\
274877906944\
274877906945\
549755813887\
549755813888\
549755813889\
1099511627775\
1099511627776\
1099511627777\
2199023255551\
2199023255552\
2199023255553\
4398046511103\
4398046511104\
4398046511105\
8796093022207\
8796093022208\
8796093022209\
17592186044415\
17592186044416\
17592186044417\
35184372088831\
35184372088832\
35184372088833\
70368744177663\
70368744177664\
70368744177665\
140737488355327\
140737488355328\
140737488355329\
281474976710655\
281474976710656\
281474976710657\
562949953421311\
562949953421312\
562949953421313\
1125899906842623\
1125899906842624\
1125899906842625\
2251799813685247\
2251799813685248\
2251799813685249\
4503599627370495\
4503599627370496\
4503599627370497\
9007199254740991\
9007199254740992\
9007199254740993\
18014398509481983\
18014398509481984\
18014398509481985\
36028797018963967\
36028797018963968\
36028797018963969\
72057594037927935\
72057594037927936\
72057594037927937\
144115188075855871\
144115188075855872\
144115188075855873\
288230376151711743\
288230376151711744\
288230376151711745\
576460752303423487\
576460752303423488\
576460752303423489\
1152921504606846975\
1152921504606846976\
1152921504606846977\
2305843009213693951\
2305843009213693952\
2305843009213693953\
4611686018427387903\
4611686018427387904\
4611686018427387905"

# Ticket #1210.  Do proper reference counting of Table structures
# so that deeply nested SELECT statements can be flattened correctly.
#
ifcapable subquery {
  do_test misc5-3.1 {
    execsql {
      CREATE TABLE songs(songid, artist, timesplayed);
      INSERT INTO songs VALUES(1,'one',1);
      INSERT INTO songs VALUES(2,'one',2);
      INSERT INTO songs VALUES(3,'two',3);
      INSERT INTO songs VALUES(4,'three',5);
      INSERT INTO songs VALUES(5,'one',7);
      INSERT INTO songs VALUES(6,'two',11);
      SELECT DISTINCT artist 
      FROM (    
       SELECT DISTINCT artist    
       FROM songs      
       WHERE songid IN (    
        SELECT songid    
        FROM songs    
        WHERE LOWER(artist) = (    
          -- This sub-query is indeterminate. Because there is no ORDER BY,
          -- it may return 'one', 'two' or 'three'. Because of this, the
	  -- outermost parent query may correctly return any of 'one', 'two' 
          -- or 'three' as well.
          SELECT DISTINCT LOWER(artist)    
          FROM (      
            -- This sub-query returns the table:
            --
            --     two      14
            --     one      10
            --     three    5
            --
            SELECT DISTINCT artist,sum(timesplayed) AS total      
            FROM songs      
            GROUP BY LOWER(artist)      
            ORDER BY total DESC      
            LIMIT 10    
          )    
          WHERE artist <> '' 
        )  
       )       
      )  
      ORDER BY LOWER(artist) ASC;
    }
  } {one}
}

# Ticket #1370.  Do not overwrite small files (less than 1024 bytes)
# when trying to open them as a database.
#
do_test misc5-4.1 {
  db close
  file delete -force test.db
  set fd [open test.db w]
  puts $fd "This is not really a database"
  close $fd
  sqlite3 db test.db
  catchsql {
    CREATE TABLE t1(a,b,c);
  }
} {1 {file is encrypted or is not a database}}

# Ticket #1371.  Allow floating point numbers of the form .N  or N.
#
do_test misc5-5.1 {
  execsql {SELECT .1 }
} 0.1
do_test misc5-5.2 {
  execsql {SELECT 2. }
} 2.0
do_test misc5-5.3 {
  execsql {SELECT 3.e0 }
} 3.0
do_test misc5-5.4 {
  execsql {SELECT .4e+1}
} 4.0

# Ticket #1582.  Ensure that an unknown table in a LIMIT clause applied to
# a UNION ALL query causes an error, not a crash.
#
db close
file delete -force test.db
sqlite3 db test.db
ifcapable subquery&&compound {
  do_test misc5-6.1 {
    catchsql {
      SELECT * FROM sqlite_master 
      UNION ALL 
      SELECT * FROM sqlite_master
      LIMIT (SELECT count(*) FROM blah);
    }
  } {1 {no such table: blah}}
  do_test misc5-6.2 {
    execsql {
      CREATE TABLE logs(msg TEXT, timestamp INTEGER, dbtime TEXT);
    }
    catchsql {
      SELECT * FROM logs WHERE logs.oid >= (SELECT head FROM logs_base) 
      UNION ALL 
      SELECT * FROM logs 
      LIMIT (SELECT lmt FROM logs_base) ;
    }
  } {1 {no such table: logs_base}}
}

# Overflow the lemon parser stack by providing an overly complex
# expression.  Make sure that the overflow is detected and reported.
#
do_test misc5-7.1 {
  execsql {CREATE TABLE t1(x)}
  set sql "INSERT INTO t1 VALUES("
  set tail ""
  for {set i 0} {$i<200} {incr i} {
    append sql "(1+"
    append tail ")"
  }
  append sql 2$tail
  catchsql $sql
} {1 {parser stack overflow}}

# Ticket #1911
#
ifcapable compound {
  do_test misc5-9.1 {
    execsql {
      SELECT name, type FROM sqlite_master WHERE name IS NULL
      UNION
      SELECT type, name FROM sqlite_master WHERE type IS NULL
      ORDER BY 1, 2, 1, 2, 1, 2
    }
  } {}
  do_test misc5-9.2 {
    execsql {
      SELECT name, type FROM sqlite_master WHERE name IS NULL
      UNION
      SELECT type, name FROM sqlite_master WHERE type IS NULL
      ORDER BY 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2
    }
  } {}
}

# Ticket #1912.  Make the tokenizer require a space after a numeric
# literal.
#
do_test misc5-10.1 {
  catchsql {
    SELECT 123abc
  }
} {1 {unrecognized token: "123abc"}}
do_test misc5-10.2 {
  catchsql {
    SELECT 1*123.4e5ghi;
  }
} {1 {unrecognized token: "123.4e5ghi"}}


# Additional integer encoding tests.
#
do_test misc5-11.1 {
  db eval {
    CREATE TABLE t3(x);
    INSERT INTO t3 VALUES(-18);
    INSERT INTO t3 VALUES(-17);
    INSERT INTO t3 VALUES(-16);
    INSERT INTO t3 VALUES(-15);
    INSERT INTO t3 VALUES(-14);
    INSERT INTO t3 VALUES(-13);
    INSERT INTO t3 VALUES(-12);
    INSERT INTO t3 VALUES(-11);
    INSERT INTO t3 VALUES(-10);
    INSERT INTO t3 VALUES(-9);
    INSERT INTO t3 VALUES(-8);
    INSERT INTO t3 VALUES(-7);
    INSERT INTO t3 VALUES(-6);
    INSERT INTO t3 VALUES(-5);
    INSERT INTO t3 VALUES(-4);
    INSERT INTO t3 VALUES(-3);
    INSERT INTO t3 VALUES(-2);
    INSERT INTO t3 VALUES(-1);
    INSERT INTO t3 VALUES(0);
    INSERT INTO t3 VALUES(1);
    INSERT INTO t3 VALUES(2);
    INSERT INTO t3 VALUES(3);
    INSERT INTO t3 VALUES(4);
    INSERT INTO t3 VALUES(5);
    INSERT INTO t3 VALUES(6);
    INSERT INTO t3 VALUES(7);
    INSERT INTO t3 VALUES(8);
    INSERT INTO t3 VALUES(9);
    INSERT INTO t3 VALUES(10);
    INSERT INTO t3 VALUES(11);
    INSERT INTO t3 VALUES(12);
    INSERT INTO t3 VALUES(13);
    INSERT INTO t3 VALUES(14);
    INSERT INTO t3 VALUES(15);
    INSERT INTO t3 VALUES(16);
    INSERT INTO t3 VALUES(17);
    INSERT INTO t3 VALUES(18);
    INSERT INTO t3 VALUES(30);
    INSERT INTO t3 VALUES(31);
    INSERT INTO t3 VALUES(32);
    INSERT INTO t3 VALUES(33);
    INSERT INTO t3 VALUES(34);
    INSERT INTO t3 VALUES(-30);
    INSERT INTO t3 VALUES(-31);
    INSERT INTO t3 VALUES(-32);
    INSERT INTO t3 VALUES(-33);
    INSERT INTO t3 VALUES(-34);
    INSERT INTO t3 VALUES(62);
    INSERT INTO t3 VALUES(63);
    INSERT INTO t3 VALUES(64);
    INSERT INTO t3 VALUES(65);
    INSERT INTO t3 VALUES(66);
    INSERT INTO t3 VALUES(-62);
    INSERT INTO t3 VALUES(-63);
    INSERT INTO t3 VALUES(-64);
    INSERT INTO t3 VALUES(-65);
    INSERT INTO t3 VALUES(-66);
    INSERT INTO t3 VALUES(126);
    INSERT INTO t3 VALUES(127);
    INSERT INTO t3 VALUES(128);
    INSERT INTO t3 VALUES(129);
    INSERT INTO t3 VALUES(130);
    INSERT INTO t3 VALUES(-126);
    INSERT INTO t3 VALUES(-127);
    INSERT INTO t3 VALUES(-128);
    INSERT INTO t3 VALUES(-129);
    INSERT INTO t3 VALUES(-130);
    INSERT INTO t3 VALUES(254);
    INSERT INTO t3 VALUES(255);
    INSERT INTO t3 VALUES(256);
    INSERT INTO t3 VALUES(257);
    INSERT INTO t3 VALUES(258);
    INSERT INTO t3 VALUES(-254);
    INSERT INTO t3 VALUES(-255);
    INSERT INTO t3 VALUES(-256);
    INSERT INTO t3 VALUES(-257);
    INSERT INTO t3 VALUES(-258);
    INSERT INTO t3 VALUES(510);
    INSERT INTO t3 VALUES(511);
    INSERT INTO t3 VALUES(512);
    INSERT INTO t3 VALUES(513);
    INSERT INTO t3 VALUES(514);
    INSERT INTO t3 VALUES(-510);
    INSERT INTO t3 VALUES(-511);
    INSERT INTO t3 VALUES(-512);
    INSERT INTO t3 VALUES(-513);
    INSERT INTO t3 VALUES(-514);
    INSERT INTO t3 VALUES(1022);
    INSERT INTO t3 VALUES(1023);
    INSERT INTO t3 VALUES(1024);
    INSERT INTO t3 VALUES(1025);
    INSERT INTO t3 VALUES(1026);
    INSERT INTO t3 VALUES(-1022);
    INSERT INTO t3 VALUES(-1023);
    INSERT INTO t3 VALUES(-1024);
    INSERT INTO t3 VALUES(-1025);
    INSERT INTO t3 VALUES(-1026);
    INSERT INTO t3 VALUES(2046);
    INSERT INTO t3 VALUES(2047);
    INSERT INTO t3 VALUES(2048);
    INSERT INTO t3 VALUES(2049);
    INSERT INTO t3 VALUES(2050);
    INSERT INTO t3 VALUES(-2046);
    INSERT INTO t3 VALUES(-2047);
    INSERT INTO t3 VALUES(-2048);
    INSERT INTO t3 VALUES(-2049);
    INSERT INTO t3 VALUES(-2050);
    INSERT INTO t3 VALUES(4094);
    INSERT INTO t3 VALUES(4095);
    INSERT INTO t3 VALUES(4096);
    INSERT INTO t3 VALUES(4097);
    INSERT INTO t3 VALUES(4098);
    INSERT INTO t3 VALUES(-4094);
    INSERT INTO t3 VALUES(-4095);
    INSERT INTO t3 VALUES(-4096);
    INSERT INTO t3 VALUES(-4097);
    INSERT INTO t3 VALUES(-4098);
    INSERT INTO t3 VALUES(8190);
    INSERT INTO t3 VALUES(8191);
    INSERT INTO t3 VALUES(8192);
    INSERT INTO t3 VALUES(8193);
    INSERT INTO t3 VALUES(8194);
    INSERT INTO t3 VALUES(-8190);
    INSERT INTO t3 VALUES(-8191);
    INSERT INTO t3 VALUES(-8192);
    INSERT INTO t3 VALUES(-8193);
    INSERT INTO t3 VALUES(-8194);
    INSERT INTO t3 VALUES(16382);
    INSERT INTO t3 VALUES(16383);
    INSERT INTO t3 VALUES(16384);
    INSERT INTO t3 VALUES(16385);
    INSERT INTO t3 VALUES(16386);
    INSERT INTO t3 VALUES(-16382);
    INSERT INTO t3 VALUES(-16383);
    INSERT INTO t3 VALUES(-16384);
    INSERT INTO t3 VALUES(-16385);
    INSERT INTO t3 VALUES(-16386);
    INSERT INTO t3 VALUES(32766);
    INSERT INTO t3 VALUES(32767);
    INSERT INTO t3 VALUES(32768);
    INSERT INTO t3 VALUES(32769);
    INSERT INTO t3 VALUES(32770);
    INSERT INTO t3 VALUES(-32766);
    INSERT INTO t3 VALUES(-32767);
    INSERT INTO t3 VALUES(-32768);
    INSERT INTO t3 VALUES(-32769);
    INSERT INTO t3 VALUES(-32770);
    INSERT INTO t3 VALUES(65534);
    INSERT INTO t3 VALUES(65535);
    INSERT INTO t3 VALUES(65536);
    INSERT INTO t3 VALUES(65537);
    INSERT INTO t3 VALUES(65538);
    INSERT INTO t3 VALUES(-65534);
    INSERT INTO t3 VALUES(-65535);
    INSERT INTO t3 VALUES(-65536);
    INSERT INTO t3 VALUES(-65537);
    INSERT INTO t3 VALUES(-65538);
    INSERT INTO t3 VALUES(131070);
    INSERT INTO t3 VALUES(131071);
    INSERT INTO t3 VALUES(131072);
    INSERT INTO t3 VALUES(131073);
    INSERT INTO t3 VALUES(131074);
    INSERT INTO t3 VALUES(-131070);
    INSERT INTO t3 VALUES(-131071);
    INSERT INTO t3 VALUES(-131072);
    INSERT INTO t3 VALUES(-131073);
    INSERT INTO t3 VALUES(-131074);
    INSERT INTO t3 VALUES(262142);
    INSERT INTO t3 VALUES(262143);
    INSERT INTO t3 VALUES(262144);
    INSERT INTO t3 VALUES(262145);
    INSERT INTO t3 VALUES(262146);
    INSERT INTO t3 VALUES(-262142);
    INSERT INTO t3 VALUES(-262143);
    INSERT INTO t3 VALUES(-262144);
    INSERT INTO t3 VALUES(-262145);
    INSERT INTO t3 VALUES(-262146);
    INSERT INTO t3 VALUES(524286);
    INSERT INTO t3 VALUES(524287);
    INSERT INTO t3 VALUES(524288);
    INSERT INTO t3 VALUES(524289);
    INSERT INTO t3 VALUES(524290);
    INSERT INTO t3 VALUES(-524286);
    INSERT INTO t3 VALUES(-524287);
    INSERT INTO t3 VALUES(-524288);
    INSERT INTO t3 VALUES(-524289);
    INSERT INTO t3 VALUES(-524290);
    INSERT INTO t3 VALUES(1048574);
    INSERT INTO t3 VALUES(1048575);
    INSERT INTO t3 VALUES(1048576);
    INSERT INTO t3 VALUES(1048577);
    INSERT INTO t3 VALUES(1048578);
    INSERT INTO t3 VALUES(-1048574);
    INSERT INTO t3 VALUES(-1048575);
    INSERT INTO t3 VALUES(-1048576);
    INSERT INTO t3 VALUES(-1048577);
    INSERT INTO t3 VALUES(-1048578);
    INSERT INTO t3 VALUES(2097150);
    INSERT INTO t3 VALUES(2097151);
    INSERT INTO t3 VALUES(2097152);
    INSERT INTO t3 VALUES(2097153);
    INSERT INTO t3 VALUES(2097154);
    INSERT INTO t3 VALUES(-2097150);
    INSERT INTO t3 VALUES(-2097151);
    INSERT INTO t3 VALUES(-2097152);
    INSERT INTO t3 VALUES(-2097153);
    INSERT INTO t3 VALUES(-2097154);
    INSERT INTO t3 VALUES(4194302);
    INSERT INTO t3 VALUES(4194303);
    INSERT INTO t3 VALUES(4194304);
    INSERT INTO t3 VALUES(4194305);
    INSERT INTO t3 VALUES(4194306);
    INSERT INTO t3 VALUES(-4194302);
    INSERT INTO t3 VALUES(-4194303);
    INSERT INTO t3 VALUES(-4194304);
    INSERT INTO t3 VALUES(-4194305);
    INSERT INTO t3 VALUES(-4194306);
    INSERT INTO t3 VALUES(8388606);
    INSERT INTO t3 VALUES(8388607);
    INSERT INTO t3 VALUES(8388608);
    INSERT INTO t3 VALUES(8388609);
    INSERT INTO t3 VALUES(8388610);
    INSERT INTO t3 VALUES(-8388606);
    INSERT INTO t3 VALUES(-8388607);
    INSERT INTO t3 VALUES(-8388608);
    INSERT INTO t3 VALUES(-8388609);
    INSERT INTO t3 VALUES(-8388610);
    INSERT INTO t3 VALUES(16777214);
    INSERT INTO t3 VALUES(16777215);
    INSERT INTO t3 VALUES(16777216);
    INSERT INTO t3 VALUES(16777217);
    INSERT INTO t3 VALUES(16777218);
    INSERT INTO t3 VALUES(-16777214);
    INSERT INTO t3 VALUES(-16777215);
    INSERT INTO t3 VALUES(-16777216);
    INSERT INTO t3 VALUES(-16777217);
    INSERT INTO t3 VALUES(-16777218);
    INSERT INTO t3 VALUES(33554430);
    INSERT INTO t3 VALUES(33554431);
    INSERT INTO t3 VALUES(33554432);
    INSERT INTO t3 VALUES(33554433);
    INSERT INTO t3 VALUES(33554434);
    INSERT INTO t3 VALUES(-33554430);
    INSERT INTO t3 VALUES(-33554431);
    INSERT INTO t3 VALUES(-33554432);
    INSERT INTO t3 VALUES(-33554433);
    INSERT INTO t3 VALUES(-33554434);
    INSERT INTO t3 VALUES(67108862);
    INSERT INTO t3 VALUES(67108863);
    INSERT INTO t3 VALUES(67108864);
    INSERT INTO t3 VALUES(67108865);
    INSERT INTO t3 VALUES(67108866);
    INSERT INTO t3 VALUES(-67108862);
    INSERT INTO t3 VALUES(-67108863);
    INSERT INTO t3 VALUES(-67108864);
    INSERT INTO t3 VALUES(-67108865);
    INSERT INTO t3 VALUES(-67108866);
    INSERT INTO t3 VALUES(134217726);
    INSERT INTO t3 VALUES(134217727);
    INSERT INTO t3 VALUES(134217728);
    INSERT INTO t3 VALUES(134217729);
    INSERT INTO t3 VALUES(134217730);
    INSERT INTO t3 VALUES(-134217726);
    INSERT INTO t3 VALUES(-134217727);
    INSERT INTO t3 VALUES(-134217728);
    INSERT INTO t3 VALUES(-134217729);
    INSERT INTO t3 VALUES(-134217730);
    INSERT INTO t3 VALUES(268435454);
    INSERT INTO t3 VALUES(268435455);
    INSERT INTO t3 VALUES(268435456);
    INSERT INTO t3 VALUES(268435457);
    INSERT INTO t3 VALUES(268435458);
    INSERT INTO t3 VALUES(-268435454);
    INSERT INTO t3 VALUES(-268435455);
    INSERT INTO t3 VALUES(-268435456);
    INSERT INTO t3 VALUES(-268435457);
    INSERT INTO t3 VALUES(-268435458);
    INSERT INTO t3 VALUES(536870910);
    INSERT INTO t3 VALUES(536870911);
    INSERT INTO t3 VALUES(536870912);
    INSERT INTO t3 VALUES(536870913);
    INSERT INTO t3 VALUES(536870914);
    INSERT INTO t3 VALUES(-536870910);
    INSERT INTO t3 VALUES(-536870911);
    INSERT INTO t3 VALUES(-536870912);
    INSERT INTO t3 VALUES(-536870913);
    INSERT INTO t3 VALUES(-536870914);
    INSERT INTO t3 VALUES(1073741822);
    INSERT INTO t3 VALUES(1073741823);
    INSERT INTO t3 VALUES(1073741824);
    INSERT INTO t3 VALUES(1073741825);
    INSERT INTO t3 VALUES(1073741826);
    INSERT INTO t3 VALUES(-1073741822);
    INSERT INTO t3 VALUES(-1073741823);
    INSERT INTO t3 VALUES(-1073741824);
    INSERT INTO t3 VALUES(-1073741825);
    INSERT INTO t3 VALUES(-1073741826);
    INSERT INTO t3 VALUES(2147483646);
    INSERT INTO t3 VALUES(2147483647);
    INSERT INTO t3 VALUES(2147483648);
    INSERT INTO t3 VALUES(2147483649);
    INSERT INTO t3 VALUES(2147483650);
    INSERT INTO t3 VALUES(-2147483646);
    INSERT INTO t3 VALUES(-2147483647);
    INSERT INTO t3 VALUES(-2147483648);
    INSERT INTO t3 VALUES(-2147483649);
    INSERT INTO t3 VALUES(-2147483650);
    INSERT INTO t3 VALUES(4294967294);
    INSERT INTO t3 VALUES(4294967295);
    INSERT INTO t3 VALUES(4294967296);
    INSERT INTO t3 VALUES(4294967297);
    INSERT INTO t3 VALUES(4294967298);
    INSERT INTO t3 VALUES(-4294967294);
    INSERT INTO t3 VALUES(-4294967295);
    INSERT INTO t3 VALUES(-4294967296);
    INSERT INTO t3 VALUES(-4294967297);
    INSERT INTO t3 VALUES(-4294967298);
    INSERT INTO t3 VALUES(8589934590);
    INSERT INTO t3 VALUES(8589934591);
    INSERT INTO t3 VALUES(8589934592);
    INSERT INTO t3 VALUES(8589934593);
    INSERT INTO t3 VALUES(8589934594);
    INSERT INTO t3 VALUES(-8589934590);
    INSERT INTO t3 VALUES(-8589934591);
    INSERT INTO t3 VALUES(-8589934592);
    INSERT INTO t3 VALUES(-8589934593);
    INSERT INTO t3 VALUES(-8589934594);
    INSERT INTO t3 VALUES(17179869182);
    INSERT INTO t3 VALUES(17179869183);
    INSERT INTO t3 VALUES(17179869184);
    INSERT INTO t3 VALUES(17179869185);
    INSERT INTO t3 VALUES(17179869186);
    INSERT INTO t3 VALUES(-17179869182);
    INSERT INTO t3 VALUES(-17179869183);
    INSERT INTO t3 VALUES(-17179869184);
    INSERT INTO t3 VALUES(-17179869185);
    INSERT INTO t3 VALUES(-17179869186);
    INSERT INTO t3 VALUES(34359738366);
    INSERT INTO t3 VALUES(34359738367);
    INSERT INTO t3 VALUES(34359738368);
    INSERT INTO t3 VALUES(34359738369);
    INSERT INTO t3 VALUES(34359738370);
    INSERT INTO t3 VALUES(-34359738366);
    INSERT INTO t3 VALUES(-34359738367);
    INSERT INTO t3 VALUES(-34359738368);
    INSERT INTO t3 VALUES(-34359738369);
    INSERT INTO t3 VALUES(-34359738370);
    INSERT INTO t3 VALUES(68719476734);
    INSERT INTO t3 VALUES(68719476735);
    INSERT INTO t3 VALUES(68719476736);
    INSERT INTO t3 VALUES(68719476737);
    INSERT INTO t3 VALUES(68719476738);
    INSERT INTO t3 VALUES(-68719476734);
    INSERT INTO t3 VALUES(-68719476735);
    INSERT INTO t3 VALUES(-68719476736);
    INSERT INTO t3 VALUES(-68719476737);
    INSERT INTO t3 VALUES(-68719476738);
    INSERT INTO t3 VALUES(137438953470);
    INSERT INTO t3 VALUES(137438953471);
    INSERT INTO t3 VALUES(137438953472);
    INSERT INTO t3 VALUES(137438953473);
    INSERT INTO t3 VALUES(137438953474);
    INSERT INTO t3 VALUES(-137438953470);
    INSERT INTO t3 VALUES(-137438953471);
    INSERT INTO t3 VALUES(-137438953472);
    INSERT INTO t3 VALUES(-137438953473);
    INSERT INTO t3 VALUES(-137438953474);
    INSERT INTO t3 VALUES(274877906942);
    INSERT INTO t3 VALUES(274877906943);
    INSERT INTO t3 VALUES(274877906944);
    INSERT INTO t3 VALUES(274877906945);
    INSERT INTO t3 VALUES(274877906946);
    INSERT INTO t3 VALUES(-274877906942);
    INSERT INTO t3 VALUES(-274877906943);
    INSERT INTO t3 VALUES(-274877906944);
    INSERT INTO t3 VALUES(-274877906945);
    INSERT INTO t3 VALUES(-274877906946);
    INSERT INTO t3 VALUES(549755813886);
    INSERT INTO t3 VALUES(549755813887);
    INSERT INTO t3 VALUES(549755813888);
    INSERT INTO t3 VALUES(549755813889);
    INSERT INTO t3 VALUES(549755813890);
    INSERT INTO t3 VALUES(-549755813886);
    INSERT INTO t3 VALUES(-549755813887);
    INSERT INTO t3 VALUES(-549755813888);
    INSERT INTO t3 VALUES(-549755813889);
    INSERT INTO t3 VALUES(-549755813890);
    INSERT INTO t3 VALUES(1099511627774);
    INSERT INTO t3 VALUES(1099511627775);
    INSERT INTO t3 VALUES(1099511627776);
    INSERT INTO t3 VALUES(1099511627777);
    INSERT INTO t3 VALUES(1099511627778);
    INSERT INTO t3 VALUES(-1099511627774);
    INSERT INTO t3 VALUES(-1099511627775);
    INSERT INTO t3 VALUES(-1099511627776);
    INSERT INTO t3 VALUES(-1099511627777);
    INSERT INTO t3 VALUES(-1099511627778);
    INSERT INTO t3 VALUES(2199023255550);
    INSERT INTO t3 VALUES(2199023255551);
    INSERT INTO t3 VALUES(2199023255552);
    INSERT INTO t3 VALUES(2199023255553);
    INSERT INTO t3 VALUES(2199023255554);
    INSERT INTO t3 VALUES(-2199023255550);
    INSERT INTO t3 VALUES(-2199023255551);
    INSERT INTO t3 VALUES(-2199023255552);
    INSERT INTO t3 VALUES(-2199023255553);
    INSERT INTO t3 VALUES(-2199023255554);
    INSERT INTO t3 VALUES(4398046511102);
    INSERT INTO t3 VALUES(4398046511103);
    INSERT INTO t3 VALUES(4398046511104);
    INSERT INTO t3 VALUES(4398046511105);
    INSERT INTO t3 VALUES(4398046511106);
    INSERT INTO t3 VALUES(-4398046511102);
    INSERT INTO t3 VALUES(-4398046511103);
    INSERT INTO t3 VALUES(-4398046511104);
    INSERT INTO t3 VALUES(-4398046511105);
    INSERT INTO t3 VALUES(-4398046511106);
    INSERT INTO t3 VALUES(8796093022206);
    INSERT INTO t3 VALUES(8796093022207);
    INSERT INTO t3 VALUES(8796093022208);
    INSERT INTO t3 VALUES(8796093022209);
    INSERT INTO t3 VALUES(8796093022210);
    INSERT INTO t3 VALUES(-8796093022206);
    INSERT INTO t3 VALUES(-8796093022207);
    INSERT INTO t3 VALUES(-8796093022208);
    INSERT INTO t3 VALUES(-8796093022209);
    INSERT INTO t3 VALUES(-8796093022210);
    INSERT INTO t3 VALUES(17592186044414);
    INSERT INTO t3 VALUES(17592186044415);
    INSERT INTO t3 VALUES(17592186044416);
    INSERT INTO t3 VALUES(17592186044417);
    INSERT INTO t3 VALUES(17592186044418);
    INSERT INTO t3 VALUES(-17592186044414);
    INSERT INTO t3 VALUES(-17592186044415);
    INSERT INTO t3 VALUES(-17592186044416);
    INSERT INTO t3 VALUES(-17592186044417);
    INSERT INTO t3 VALUES(-17592186044418);
    INSERT INTO t3 VALUES(35184372088830);
    INSERT INTO t3 VALUES(35184372088831);
    INSERT INTO t3 VALUES(35184372088832);
    INSERT INTO t3 VALUES(35184372088833);
    INSERT INTO t3 VALUES(35184372088834);
    INSERT INTO t3 VALUES(-35184372088830);
    INSERT INTO t3 VALUES(-35184372088831);
    INSERT INTO t3 VALUES(-35184372088832);
    INSERT INTO t3 VALUES(-35184372088833);
    INSERT INTO t3 VALUES(-35184372088834);
    INSERT INTO t3 VALUES(70368744177662);
    INSERT INTO t3 VALUES(70368744177663);
    INSERT INTO t3 VALUES(70368744177664);
    INSERT INTO t3 VALUES(70368744177665);
    INSERT INTO t3 VALUES(70368744177666);
    INSERT INTO t3 VALUES(-70368744177662);
    INSERT INTO t3 VALUES(-70368744177663);
    INSERT INTO t3 VALUES(-70368744177664);
    INSERT INTO t3 VALUES(-70368744177665);
    INSERT INTO t3 VALUES(-70368744177666);
    INSERT INTO t3 VALUES(140737488355326);
    INSERT INTO t3 VALUES(140737488355327);
    INSERT INTO t3 VALUES(140737488355328);
    INSERT INTO t3 VALUES(140737488355329);
    INSERT INTO t3 VALUES(140737488355330);
    INSERT INTO t3 VALUES(-140737488355326);
    INSERT INTO t3 VALUES(-140737488355327);
    INSERT INTO t3 VALUES(-140737488355328);
    INSERT INTO t3 VALUES(-140737488355329);
    INSERT INTO t3 VALUES(-140737488355330);
    INSERT INTO t3 VALUES(281474976710654);
    INSERT INTO t3 VALUES(281474976710655);
    INSERT INTO t3 VALUES(281474976710656);
    INSERT INTO t3 VALUES(281474976710657);
    INSERT INTO t3 VALUES(281474976710658);
    INSERT INTO t3 VALUES(-281474976710654);
    INSERT INTO t3 VALUES(-281474976710655);
    INSERT INTO t3 VALUES(-281474976710656);
    INSERT INTO t3 VALUES(-281474976710657);
    INSERT INTO t3 VALUES(-281474976710658);
    INSERT INTO t3 VALUES(562949953421310);
    INSERT INTO t3 VALUES(562949953421311);
    INSERT INTO t3 VALUES(562949953421312);
    INSERT INTO t3 VALUES(562949953421313);
    INSERT INTO t3 VALUES(562949953421314);
    INSERT INTO t3 VALUES(-562949953421310);
    INSERT INTO t3 VALUES(-562949953421311);
    INSERT INTO t3 VALUES(-562949953421312);
    INSERT INTO t3 VALUES(-562949953421313);
    INSERT INTO t3 VALUES(-562949953421314);
    INSERT INTO t3 VALUES(1125899906842622);
    INSERT INTO t3 VALUES(1125899906842623);
    INSERT INTO t3 VALUES(1125899906842624);
    INSERT INTO t3 VALUES(1125899906842625);
    INSERT INTO t3 VALUES(1125899906842626);
    INSERT INTO t3 VALUES(-1125899906842622);
    INSERT INTO t3 VALUES(-1125899906842623);
    INSERT INTO t3 VALUES(-1125899906842624);
    INSERT INTO t3 VALUES(-1125899906842625);
    INSERT INTO t3 VALUES(-1125899906842626);
    INSERT INTO t3 VALUES(2251799813685246);
    INSERT INTO t3 VALUES(2251799813685247);
    INSERT INTO t3 VALUES(2251799813685248);
    INSERT INTO t3 VALUES(2251799813685249);
    INSERT INTO t3 VALUES(2251799813685250);
    INSERT INTO t3 VALUES(-2251799813685246);
    INSERT INTO t3 VALUES(-2251799813685247);
    INSERT INTO t3 VALUES(-2251799813685248);
    INSERT INTO t3 VALUES(-2251799813685249);
    INSERT INTO t3 VALUES(-2251799813685250);
    INSERT INTO t3 VALUES(4503599627370494);
    INSERT INTO t3 VALUES(4503599627370495);
    INSERT INTO t3 VALUES(4503599627370496);
    INSERT INTO t3 VALUES(4503599627370497);
    INSERT INTO t3 VALUES(4503599627370498);
    INSERT INTO t3 VALUES(-4503599627370494);
    INSERT INTO t3 VALUES(-4503599627370495);
    INSERT INTO t3 VALUES(-4503599627370496);
    INSERT INTO t3 VALUES(-4503599627370497);
    INSERT INTO t3 VALUES(-4503599627370498);
    INSERT INTO t3 VALUES(9007199254740990);
    INSERT INTO t3 VALUES(9007199254740991);
    INSERT INTO t3 VALUES(9007199254740992);
    INSERT INTO t3 VALUES(9007199254740993);
    INSERT INTO t3 VALUES(9007199254740994);
    INSERT INTO t3 VALUES(-9007199254740990);
    INSERT INTO t3 VALUES(-9007199254740991);
    INSERT INTO t3 VALUES(-9007199254740992);
    INSERT INTO t3 VALUES(-9007199254740993);
    INSERT INTO t3 VALUES(-9007199254740994);
    INSERT INTO t3 VALUES(18014398509481982);
    INSERT INTO t3 VALUES(18014398509481983);
    INSERT INTO t3 VALUES(18014398509481984);
    INSERT INTO t3 VALUES(18014398509481985);
    INSERT INTO t3 VALUES(18014398509481986);
    INSERT INTO t3 VALUES(-18014398509481982);
    INSERT INTO t3 VALUES(-18014398509481983);
    INSERT INTO t3 VALUES(-18014398509481984);
    INSERT INTO t3 VALUES(-18014398509481985);
    INSERT INTO t3 VALUES(-18014398509481986);
    INSERT INTO t3 VALUES(36028797018963966);
    INSERT INTO t3 VALUES(36028797018963967);
    INSERT INTO t3 VALUES(36028797018963968);
    INSERT INTO t3 VALUES(36028797018963969);
    INSERT INTO t3 VALUES(36028797018963970);
    INSERT INTO t3 VALUES(-36028797018963966);
    INSERT INTO t3 VALUES(-36028797018963967);
    INSERT INTO t3 VALUES(-36028797018963968);
    INSERT INTO t3 VALUES(-36028797018963969);
    INSERT INTO t3 VALUES(-36028797018963970);
    INSERT INTO t3 VALUES(72057594037927934);
    INSERT INTO t3 VALUES(72057594037927935);
    INSERT INTO t3 VALUES(72057594037927936);
    INSERT INTO t3 VALUES(72057594037927937);
    INSERT INTO t3 VALUES(72057594037927938);
    INSERT INTO t3 VALUES(-72057594037927934);
    INSERT INTO t3 VALUES(-72057594037927935);
    INSERT INTO t3 VALUES(-72057594037927936);
    INSERT INTO t3 VALUES(-72057594037927937);
    INSERT INTO t3 VALUES(-72057594037927938);
    INSERT INTO t3 VALUES(144115188075855870);
    INSERT INTO t3 VALUES(144115188075855871);
    INSERT INTO t3 VALUES(144115188075855872);
    INSERT INTO t3 VALUES(144115188075855873);
    INSERT INTO t3 VALUES(144115188075855874);
    INSERT INTO t3 VALUES(-144115188075855870);
    INSERT INTO t3 VALUES(-144115188075855871);
    INSERT INTO t3 VALUES(-144115188075855872);
    INSERT INTO t3 VALUES(-144115188075855873);
    INSERT INTO t3 VALUES(-144115188075855874);
    INSERT INTO t3 VALUES(288230376151711742);
    INSERT INTO t3 VALUES(288230376151711743);
    INSERT INTO t3 VALUES(288230376151711744);
    INSERT INTO t3 VALUES(288230376151711745);
    INSERT INTO t3 VALUES(288230376151711746);
    INSERT INTO t3 VALUES(-288230376151711742);
    INSERT INTO t3 VALUES(-288230376151711743);
    INSERT INTO t3 VALUES(-288230376151711744);
    INSERT INTO t3 VALUES(-288230376151711745);
    INSERT INTO t3 VALUES(-288230376151711746);
    INSERT INTO t3 VALUES(576460752303423486);
    INSERT INTO t3 VALUES(576460752303423487);
    INSERT INTO t3 VALUES(576460752303423488);
    INSERT INTO t3 VALUES(576460752303423489);
    INSERT INTO t3 VALUES(576460752303423490);
    INSERT INTO t3 VALUES(-576460752303423486);
    INSERT INTO t3 VALUES(-576460752303423487);
    INSERT INTO t3 VALUES(-576460752303423488);
    INSERT INTO t3 VALUES(-576460752303423489);
    INSERT INTO t3 VALUES(-576460752303423490);
    INSERT INTO t3 VALUES(1152921504606846974);
    INSERT INTO t3 VALUES(1152921504606846975);
    INSERT INTO t3 VALUES(1152921504606846976);
    INSERT INTO t3 VALUES(1152921504606846977);
    INSERT INTO t3 VALUES(1152921504606846978);
    INSERT INTO t3 VALUES(-1152921504606846974);
    INSERT INTO t3 VALUES(-1152921504606846975);
    INSERT INTO t3 VALUES(-1152921504606846976);
    INSERT INTO t3 VALUES(-1152921504606846977);
    INSERT INTO t3 VALUES(-1152921504606846978);
    INSERT INTO t3 VALUES(2305843009213693950);
    INSERT INTO t3 VALUES(2305843009213693951);
    INSERT INTO t3 VALUES(2305843009213693952);
    INSERT INTO t3 VALUES(2305843009213693953);
    INSERT INTO t3 VALUES(2305843009213693954);
    INSERT INTO t3 VALUES(-2305843009213693950);
    INSERT INTO t3 VALUES(-2305843009213693951);
    INSERT INTO t3 VALUES(-2305843009213693952);
    INSERT INTO t3 VALUES(-2305843009213693953);
    INSERT INTO t3 VALUES(-2305843009213693954);
    INSERT INTO t3 VALUES(4611686018427387902);
    INSERT INTO t3 VALUES(4611686018427387903);
    INSERT INTO t3 VALUES(4611686018427387904);
    INSERT INTO t3 VALUES(4611686018427387905);
    INSERT INTO t3 VALUES(4611686018427387906);
    INSERT INTO t3 VALUES(-4611686018427387902);
    INSERT INTO t3 VALUES(-4611686018427387903);
    INSERT INTO t3 VALUES(-4611686018427387904);
    INSERT INTO t3 VALUES(-4611686018427387905);
    INSERT INTO t3 VALUES(-4611686018427387906);
    INSERT INTO t3 VALUES(9223372036854775806);
    INSERT INTO t3 VALUES(9223372036854775807);
    INSERT INTO t3 VALUES(-9223372036854775806);
    INSERT INTO t3 VALUES(-9223372036854775807);
    INSERT INTO t3 VALUES(-9223372036854775808);
    SELECT x FROM t3 ORDER BY x;
  }
} {-9223372036854775808\
-9223372036854775807\
-9223372036854775806\
-4611686018427387906\
-4611686018427387905\
-4611686018427387904\
-4611686018427387903\
-4611686018427387902\
-2305843009213693954\
-2305843009213693953\
-2305843009213693952\
-2305843009213693951\
-2305843009213693950\
-1152921504606846978\
-1152921504606846977\
-1152921504606846976\
-1152921504606846975\
-1152921504606846974\
-576460752303423490\
-576460752303423489\
-576460752303423488\
-576460752303423487\
-576460752303423486\
-288230376151711746\
-288230376151711745\
-288230376151711744\
-288230376151711743\
-288230376151711742\
-144115188075855874\
-144115188075855873\
-144115188075855872\
-144115188075855871\
-144115188075855870\
-72057594037927938\
-72057594037927937\
-72057594037927936\
-72057594037927935\
-72057594037927934\
-36028797018963970\
-36028797018963969\
-36028797018963968\
-36028797018963967\
-36028797018963966\
-18014398509481986\
-18014398509481985\
-18014398509481984\
-18014398509481983\
-18014398509481982\
-9007199254740994\
-9007199254740993\
-9007199254740992\
-9007199254740991\
-9007199254740990\
-4503599627370498\
-4503599627370497\
-4503599627370496\
-4503599627370495\
-4503599627370494\
-2251799813685250\
-2251799813685249\
-2251799813685248\
-2251799813685247\
-2251799813685246\
-1125899906842626\
-1125899906842625\
-1125899906842624\
-1125899906842623\
-1125899906842622\
-562949953421314\
-562949953421313\
-562949953421312\
-562949953421311\
-562949953421310\
-281474976710658\
-281474976710657\
-281474976710656\
-281474976710655\
-281474976710654\
-140737488355330\
-140737488355329\
-140737488355328\
-140737488355327\
-140737488355326\
-70368744177666\
-70368744177665\
-70368744177664\
-70368744177663\
-70368744177662\
-35184372088834\
-35184372088833\
-35184372088832\
-35184372088831\
-35184372088830\
-17592186044418\
-17592186044417\
-17592186044416\
-17592186044415\
-17592186044414\
-8796093022210\
-8796093022209\
-8796093022208\
-8796093022207\
-8796093022206\
-4398046511106\
-4398046511105\
-4398046511104\
-4398046511103\
-4398046511102\
-2199023255554\
-2199023255553\
-2199023255552\
-2199023255551\
-2199023255550\
-1099511627778\
-1099511627777\
-1099511627776\
-1099511627775\
-1099511627774\
-549755813890\
-549755813889\
-549755813888\
-549755813887\
-549755813886\
-274877906946\
-274877906945\
-274877906944\
-274877906943\
-274877906942\
-137438953474\
-137438953473\
-137438953472\
-137438953471\
-137438953470\
-68719476738\
-68719476737\
-68719476736\
-68719476735\
-68719476734\
-34359738370\
-34359738369\
-34359738368\
-34359738367\
-34359738366\
-17179869186\
-17179869185\
-17179869184\
-17179869183\
-17179869182\
-8589934594\
-8589934593\
-8589934592\
-8589934591\
-8589934590\
-4294967298\
-4294967297\
-4294967296\
-4294967295\
-4294967294\
-2147483650\
-2147483649\
-2147483648\
-2147483647\
-2147483646\
-1073741826\
-1073741825\
-1073741824\
-1073741823\
-1073741822\
-536870914\
-536870913\
-536870912\
-536870911\
-536870910\
-268435458\
-268435457\
-268435456\
-268435455\
-268435454\
-134217730\
-134217729\
-134217728\
-134217727\
-134217726\
-67108866\
-67108865\
-67108864\
-67108863\
-67108862\
-33554434\
-33554433\
-33554432\
-33554431\
-33554430\
-16777218\
-16777217\
-16777216\
-16777215\
-16777214\
-8388610\
-8388609\
-8388608\
-8388607\
-8388606\
-4194306\
-4194305\
-4194304\
-4194303\
-4194302\
-2097154\
-2097153\
-2097152\
-2097151\
-2097150\
-1048578\
-1048577\
-1048576\
-1048575\
-1048574\
-524290\
-524289\
-524288\
-524287\
-524286\
-262146\
-262145\
-262144\
-262143\
-262142\
-131074\
-131073\
-131072\
-131071\
-131070\
-65538\
-65537\
-65536\
-65535\
-65534\
-32770\
-32769\
-32768\
-32767\
-32766\
-16386\
-16385\
-16384\
-16383\
-16382\
-8194\
-8193\
-8192\
-8191\
-8190\
-4098\
-4097\
-4096\
-4095\
-4094\
-2050\
-2049\
-2048\
-2047\
-2046\
-1026\
-1025\
-1024\
-1023\
-1022\
-514\
-513\
-512\
-511\
-510\
-258\
-257\
-256\
-255\
-254\
-130\
-129\
-128\
-127\
-126\
-66\
-65\
-64\
-63\
-62\
-34\
-33\
-32\
-31\
-30\
-18\
-17\
-16\
-15\
-14\
-13\
-12\
-11\
-10\
-9\
-8\
-7\
-6\
-5\
-4\
-3\
-2\
-1\
0\
1\
2\
3\
4\
5\
6\
7\
8\
9\
10\
11\
12\
13\
14\
15\
16\
17\
18\
30\
31\
32\
33\
34\
62\
63\
64\
65\
66\
126\
127\
128\
129\
130\
254\
255\
256\
257\
258\
510\
511\
512\
513\
514\
1022\
1023\
1024\
1025\
1026\
2046\
2047\
2048\
2049\
2050\
4094\
4095\
4096\
4097\
4098\
8190\
8191\
8192\
8193\
8194\
16382\
16383\
16384\
16385\
16386\
32766\
32767\
32768\
32769\
32770\
65534\
65535\
65536\
65537\
65538\
131070\
131071\
131072\
131073\
131074\
262142\
262143\
262144\
262145\
262146\
524286\
524287\
524288\
524289\
524290\
1048574\
1048575\
1048576\
1048577\
1048578\
2097150\
2097151\
2097152\
2097153\
2097154\
4194302\
4194303\
4194304\
4194305\
4194306\
8388606\
8388607\
8388608\
8388609\
8388610\
16777214\
16777215\
16777216\
16777217\
16777218\
33554430\
33554431\
33554432\
33554433\
33554434\
67108862\
67108863\
67108864\
67108865\
67108866\
134217726\
134217727\
134217728\
134217729\
134217730\
268435454\
268435455\
268435456\
268435457\
268435458\
536870910\
536870911\
536870912\
536870913\
536870914\
1073741822\
1073741823\
1073741824\
1073741825\
1073741826\
2147483646\
2147483647\
2147483648\
2147483649\
2147483650\
4294967294\
4294967295\
4294967296\
4294967297\
4294967298\
8589934590\
8589934591\
8589934592\
8589934593\
8589934594\
17179869182\
17179869183\
17179869184\
17179869185\
17179869186\
34359738366\
34359738367\
34359738368\
34359738369\
34359738370\
68719476734\
68719476735\
68719476736\
68719476737\
68719476738\
137438953470\
137438953471\
137438953472\
137438953473\
137438953474\
274877906942\
274877906943\
274877906944\
274877906945\
274877906946\
549755813886\
549755813887\
549755813888\
549755813889\
549755813890\
1099511627774\
1099511627775\
1099511627776\
1099511627777\
1099511627778\
2199023255550\
2199023255551\
2199023255552\
2199023255553\
2199023255554\
4398046511102\
4398046511103\
4398046511104\
4398046511105\
4398046511106\
8796093022206\
8796093022207\
8796093022208\
8796093022209\
8796093022210\
17592186044414\
17592186044415\
17592186044416\
17592186044417\
17592186044418\
35184372088830\
35184372088831\
35184372088832\
35184372088833\
35184372088834\
70368744177662\
70368744177663\
70368744177664\
70368744177665\
70368744177666\
140737488355326\
140737488355327\
140737488355328\
140737488355329\
140737488355330\
281474976710654\
281474976710655\
281474976710656\
281474976710657\
281474976710658\
562949953421310\
562949953421311\
562949953421312\
562949953421313\
562949953421314\
1125899906842622\
1125899906842623\
1125899906842624\
1125899906842625\
1125899906842626\
2251799813685246\
2251799813685247\
2251799813685248\
2251799813685249\
2251799813685250\
4503599627370494\
4503599627370495\
4503599627370496\
4503599627370497\
4503599627370498\
9007199254740990\
9007199254740991\
9007199254740992\
9007199254740993\
9007199254740994\
18014398509481982\
18014398509481983\
18014398509481984\
18014398509481985\
18014398509481986\
36028797018963966\
36028797018963967\
36028797018963968\
36028797018963969\
36028797018963970\
72057594037927934\
72057594037927935\
72057594037927936\
72057594037927937\
72057594037927938\
144115188075855870\
144115188075855871\
144115188075855872\
144115188075855873\
144115188075855874\
288230376151711742\
288230376151711743\
288230376151711744\
288230376151711745\
288230376151711746\
576460752303423486\
576460752303423487\
576460752303423488\
576460752303423489\
576460752303423490\
1152921504606846974\
1152921504606846975\
1152921504606846976\
1152921504606846977\
1152921504606846978\
2305843009213693950\
2305843009213693951\
2305843009213693952\
2305843009213693953\
2305843009213693954\
4611686018427387902\
4611686018427387903\
4611686018427387904\
4611686018427387905\
4611686018427387906\
9223372036854775806\
9223372036854775807}

finish_test

Added test/misc6.test.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 2006 September 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure sqlite3_value_text()
# always returns a null-terminated string.
#
# $Id: misc6.test,v 1.3 2007/04/23 23:56:32 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test misc6-1.1 {
  set DB [sqlite3_connection_pointer db]
  sqlite3_create_function $DB
  set STMT [sqlite3_prepare $DB {SELECT hex8(?)} -1 DUMMY]
  set sqlite_static_bind_value {0123456789}
  set sqlite_static_bind_nbyte 5
  sqlite_bind $STMT 1 {} static-nbytes
  sqlite3_step $STMT
} SQLITE_ROW
do_test misc6-1.2 {
  sqlite3_column_text $STMT 0
} {3031323334}
ifcapable utf16 {
  do_test misc6-1.3 {
    sqlite3_finalize $STMT
    set STMT [sqlite3_prepare $DB {SELECT hex16(?)} -1 DUMMY]
    set sqlite_static_bind_value {0123456789}
    set sqlite_static_bind_nbyte 5
    sqlite_bind $STMT 1 {} static-nbytes
    sqlite3_step $STMT
  } SQLITE_ROW
  do_test misc6-1.4 {
    sqlite3_column_text $STMT 0
  } {00300031003200330034}
}
sqlite3_finalize $STMT

finish_test

Added test/misc7.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# 2006 September 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# $Id: misc7.test,v 1.29 2009/07/16 18:21:18 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test misc7-1-misuse {
  c_misuse_test
} {}

do_test misc7-2 {
  c_realloc_test
} {}

do_test misc7-3 {
  c_collation_test
} {}

# Try to open a directory:
#
do_test misc7-4 {
  file delete mydir
  file mkdir mydir
  set rc [catch {
    sqlite3 db2 ./mydir
  } msg]
  list $rc $msg
} {1 {unable to open database file}}

# Try to open a file with a directory where its journal file should be.
#
do_test misc7-5 {
  file delete mydir
  file mkdir mydir-journal
  sqlite3 db2 ./mydir
  catchsql {
    CREATE TABLE abc(a, b, c);
  } db2
} {1 {unable to open database file}}
db2 close

#--------------------------------------------------------------------
# The following tests, misc7-6.* test the libraries behaviour when
# it cannot open a file. To force this condition, we use up all the
# file-descriptors before running sqlite. This probably only works
# on unix.
#

proc use_up_files {} {
  set ret [list]
  catch {
    while 1 { lappend ret [open test.db] }
  }
  return $ret
}

proc do_fileopen_test {prefix sql} {
  set fd_list [use_up_files]
  set ::go 1
  set ::n 1
  set ::sql $sql
  while {$::go} {
    catch {db close}
    do_test ${prefix}.${::n} {
      set rc [catch {
        sqlite db test.db
        db eval $::sql
      } msg]
      if {$rc == 0} {set ::go 0}
  
      expr {$rc == 0 || ($rc == 1 && [string first unable $msg]==0)}
    } 1
  
    close [lindex $fd_list 0]
    set fd_list [lrange $fd_list 1 end]
    incr ::n
  }
  foreach fd $fd_list {
    close $fd
  }
  db close
}

execsql { CREATE TABLE abc(a PRIMARY KEY, b, c); }
db close

if {$tcl_platform(platform)!="windows"} {
  do_fileopen_test misc7-6.1 {
    BEGIN;
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc VALUES(2, 3, 4);
    INSERT INTO abc SELECT a+2, b, c FROM abc;
    COMMIT;
  }
  
  do_fileopen_test misc7-6.2 {
    PRAGMA temp.cache_size = 1000;
  }
}

#
# End of tests for out-of-file-descriptors condition.
#--------------------------------------------------------------------

sqlite3 db test.db
execsql {
  DELETE FROM abc;
  INSERT INTO abc VALUES(1, 2, 3);
  INSERT INTO abc VALUES(2, 3, 4);
  INSERT INTO abc SELECT a+2, b, c FROM abc;
}
  

#--------------------------------------------------------------------
# Test that the sqlite3_busy_timeout call seems to delay approximately
# the right amount of time.
#
do_test misc7-7.0 {
  sqlite3 db2 test.db
  sqlite3_busy_timeout [sqlite3_connection_pointer db] 2000
  execsql {
    BEGIN EXCLUSIVE;
  } db2

  # Now db2 has an exclusive lock on the database file, and db has
  # a busy-timeout of 2000 milliseconds. So check that trying to
  # access the database using connection db delays for at least 1500 ms.
  #
  set tm [time {
    set result [catchsql {
        SELECT * FROM sqlite_master;
      } db]
  }]
  set delay [lindex $tm 0]  ;# In microseconds
  lappend result [expr {$delay>1500000 && $delay<4000000}]
} {1 {database is locked} 1}
db2 close

#--------------------------------------------------------------------
# Test that nothing goes horribly wrong when attaching a database
# after the omit_readlock pragma has been exercised.
#
do_test misc7-7.1 {
  file delete -force test2.db
  file delete -force test2.db-journal
  execsql {
    PRAGMA omit_readlock = 1;
    ATTACH 'test2.db' AS aux;
    CREATE TABLE aux.hello(world);
    SELECT name FROM aux.sqlite_master;
  }
} {hello}
do_test misc7-7.2 {
  execsql {
    DETACH aux;
  }
} {}
do_test misc7-7.3 {
  db close
  sqlite3 db test.db -readonly 1
  execsql {
    PRAGMA omit_readlock = 1;
    ATTACH 'test2.db' AS aux;
    SELECT name FROM aux.sqlite_master;
    SELECT name FROM aux.sqlite_master;
  }
} {hello hello}
do_test misc7-7.3 {
  db close
  sqlite3 db test.db
  set ::DB [sqlite3_connection_pointer db]
  list
} {}

# Test the UTF-16 version of the "out of memory" message (used when
# malloc fails during sqlite3_open() ).
#
ifcapable utf16 {
  do_test misc7-8 {
    encoding convertfrom unicode [sqlite3_errmsg16 0x00000000]
  } {out of memory}
}

do_test misc7-9 {
  execsql {
    SELECT * 
    FROM (SELECT name+1 AS one FROM sqlite_master LIMIT 1 OFFSET 1) 
    WHERE one LIKE 'hello%';
  }
} {}

#--------------------------------------------------------------------
# Improve coverage for vtab code.
#
ifcapable vtab {
  # Run some debug code to improve reported coverage
  #

  # set sqlite_where_trace 1
  do_test misc7-10 {
    register_echo_module [sqlite3_connection_pointer db]
    execsql {
      CREATE VIRTUAL TABLE t1 USING echo(abc);
      SELECT a FROM t1 WHERE a = 1 ORDER BY b;
    }
  } {1}
  set sqlite_where_trace 0

  # Specify an ORDER BY clause that cannot be indexed.
  do_test misc7-11 {
    execsql {
      SELECT t1.a, t2.a FROM t1, t1 AS t2 ORDER BY 2 LIMIT 1;
    }
  } {1 1}

  # The whole point of this is to test an error code other than
  # SQLITE_NOMEM from the vtab xBestIndex callback.
  #
  do_ioerr_test misc7-12 -tclprep {
    sqlite3 db2 test.db
    register_echo_module [sqlite3_connection_pointer db2]
    db2 eval {
      CREATE TABLE abc(a PRIMARY KEY, b, c);
      INSERT INTO abc VALUES(1, 2, 3);
      CREATE VIRTUAL TABLE t1 USING echo(abc);
    }
    db2 close
  } -tclbody {
    register_echo_module [sqlite3_connection_pointer db]
    execsql {SELECT * FROM t1 WHERE a = 1;}
  } 

  # The case where the virtual table module returns a very large number
  # as the cost of a scan (greater than SQLITE_BIG_DOUBLE in the code).
  #
  do_test misc7-13 {
    sqlite3 db test.db
    register_echo_module [sqlite3_connection_pointer db]
    set ::echo_module_cost 2.0e+99
    execsql {SELECT * FROM t1 WHERE a = 1;}
  } {1 2 3}
  unset ::echo_module_cost
}

db close
file delete -force test.db
file delete -force test.db-journal
sqlite3 db test.db

ifcapable explain {
  do_test misc7-14.1 {
    execsql {
      CREATE TABLE abc(a PRIMARY KEY, b, c);
    }
    execsql {
      EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 WHERE rowid = 1;
    }
  } {0 0 {TABLE abc AS t2 USING PRIMARY KEY}}
  do_test misc7-14.2 {
    execsql {
      EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 WHERE a = 1;
    }
  } {0 0 {TABLE abc AS t2 WITH INDEX sqlite_autoindex_abc_1}}
  do_test misc7-14.3 {
    execsql {
      EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 ORDER BY a;
    }
  } {0 0 {TABLE abc AS t2 WITH INDEX sqlite_autoindex_abc_1 ORDER BY}}
}

db close
file delete -force test.db
file delete -force test.db-journal
sqlite3 db test.db

#--------------------------------------------------------------------
# This is all to force the pager_remove_from_stmt_list() function
# (inside pager.c) to remove a pager from the middle of the
# statement-list.
#
do_test misc7-15.1 {
  execsql {
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE abc(a PRIMARY KEY, b, c);
    INSERT INTO abc 
    VALUES(randstr(100,100), randstr(100,100), randstr(100,100));
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
    COMMIT;
  }
  expr {[file size test.db]>10240}
} {1}
do_test misc7-15.2 {
  execsql {
    DELETE FROM abc WHERE rowid > 12;
    INSERT INTO abc SELECT 
            randstr(100,100), randstr(100,100), randstr(100,100) FROM abc;
  }
} {}

db close
file delete -force test.db
file delete -force test.db-journal
sqlite3 db test.db

do_ioerr_test misc7-16 -sqlprep {
   PRAGMA cache_size = 10;
   PRAGMA default_cache_size = 10;
   CREATE TABLE t3(a, b, UNIQUE(a, b));
   INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) );
   INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
   INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
   INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
   INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
   INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3;
   UPDATE t3 
   SET b = 'hello world'
   WHERE rowid >= (SELECT max(rowid)-1 FROM t3);
} -tclbody {
  set rc [catch {db eval {
    BEGIN;
      PRAGMA cache_size = 10;
      INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) );
      UPDATE t3 SET a = b;
    COMMIT;
  }} msg]

  if {!$rc || ($rc && [string first "columns" $msg]==0)} {
    set msg
  } else {
    error $msg
  }
}

sqlite3 db test.db

do_test misc7-16.X {
  execsql {
    SELECT count(*) FROM t3;
  }
} {32}

#----------------------------------------------------------------------
# Test the situation where a hot-journal is discovered but write-access
# to it is denied. This should return SQLITE_BUSY.
#
# These tests do not work on windows due to restrictions in the
# windows file system.
#
if {$tcl_platform(platform)!="windows" && $tcl_platform(platform)!="os2"} {

  # Some network filesystems (ex: AFP) do not support setting read-only
  # permissions.  Only run these tests if full unix permission setting
  # capabilities are supported.
  #
  file attributes test.db -permissions rw-r--r--
  if {[file attributes test.db -permissions]==0644} {

    do_test misc7-17.1 {
      execsql {
        BEGIN;
        DELETE FROM t3 WHERE (oid%3)==0;
      }
      copy_file test.db bak.db
      copy_file test.db-journal bak.db-journal
      execsql {
        COMMIT;
      }
    
      db close
      copy_file bak.db test.db
      copy_file bak.db-journal test.db-journal
      sqlite3 db test.db
    
      catch {file attributes test.db-journal -permissions r--------}
      catch {file attributes test.db-journal -readonly 1}
      catchsql {
        SELECT count(*) FROM t3;
      }
    } {1 {unable to open database file}}
    do_test misc7-17.2 {
      # Note that the -readonly flag must be cleared before the -permissions
      # are set. Otherwise, when using tcl 8.5 on mac, the fact that the 
      # -readonly flag is set causes the attempt to set the permissions
      # to fail.
      catch {file attributes test.db-journal -readonly 0}
      catch {file attributes test.db-journal -permissions rw-------}
      catchsql {
        SELECT count(*) FROM t3;
      }
    } {0 32}
    
    # sqlite3_test_control_pending_page [expr ($::sqlite_pending_byte / 1024) + 1]
    set ::pending_byte_page [expr ($::sqlite_pending_byte / 1024) + 1]
    sqlite3_test_control_pending_byte $::sqlite_pending_byte 
    do_test misc7-17.3 {
      db eval {
        pragma writable_schema = true;
        UPDATE sqlite_master 
          SET rootpage = $pending_byte_page
          WHERE type = 'table' AND name = 't3';
      }
      execsql {
        SELECT rootpage FROM sqlite_master WHERE type = 'table' AND name = 't3';
      }
    } $::pending_byte_page
    
    do_test misc7-17.4 {
      db close
      sqlite3 db test.db
      catchsql {
        SELECT count(*) FROM t3;
      } 
    } {1 {database disk image is malformed}}
  }
}

# Ticket #2470
#
do_test misc7-18.1 {
  execsql {
    CREATE TABLE table_1 (col_10);
    CREATE TABLE table_2 (
      col_1, col_2, col_3, col_4, col_5,
      col_6, col_7, col_8, col_9, col_10
    );
    SELECT a.col_10
    FROM
      (SELECT table_1.col_10 AS col_10 FROM table_1) a,
      (SELECT table_1.col_10, table_2.col_9 AS qcol_9
         FROM table_1, table_2
        GROUP BY table_1.col_10, qcol_9);
  }
} {}

# Testing boundary conditions on sqlite3_status()
#
do_test misc7-19.1 {
  sqlite3_status -1 0
} {21 0 0}
do_test misc7-19.2 {
  sqlite3_status 1000 0
} {21 0 0}


# sqlite3_global_recover() is a no-op.  But we might as well test it
# if only to get the test coverage.
#
do_test misc7-20.1 {
  sqlite3_global_recover
} {SQLITE_OK}

# Try to open a really long file name.
#
do_test misc7-21.1 {
  set zFile [file join [pwd] "[string repeat abcde 104].db"]
  set rc [catch {sqlite3 db2 $zFile} msg]
  list $rc $msg
} {1 {unable to open database file}}


db close
file delete -force test.db

finish_test

Added test/misuse.test.































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# 2002 May 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the SQLITE_MISUSE detection logic.
# This test file leaks memory and file descriptors.
#
# $Id: misuse.test,v 1.11 2006/01/03 00:33:50 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc catchsql2 {sql} {
  set r [
    catch {
      set res [list]
      db eval $sql data {
        if { $res==[list] } {
          foreach f $data(*) {lappend res $f}
        }
        foreach f $data(*) {lappend res $data($f)}
      }
      set res
    } msg
  ]
  lappend r $msg
}


# Make sure the test logic works
#
do_test misuse-1.1 {
  db close
  catch {file delete -force test2.db}
  catch {file delete -force test2.db-journal}
  sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
  }
  catchsql2 {
    SELECT * FROM t1
  }
} {0 {a b 1 2}}
do_test misuse-1.2 {
  catchsql2 {
    SELECT x_coalesce(NULL,a) AS 'xyz' FROM t1
  }
} {1 {no such function: x_coalesce}}
do_test misuse-1.3 {
  sqlite3_create_function $::DB
  catchsql2 {
    SELECT x_coalesce(NULL,a) AS 'xyz' FROM t1
  }
} {0 {xyz 1}}

# Use the x_sqlite_exec() SQL function to simulate the effect of two
# threads trying to use the same database at the same time.
#
# It used to be prohibited to invoke sqlite_exec() from within a function,
# but that has changed.  The following tests used to cause errors but now
# they do not.
#
ifcapable {utf16} {
  do_test misuse-1.4 {
    catchsql2 {
       SELECT x_sqlite_exec('SELECT * FROM t1') AS xyz;
    } 
  } {0 {xyz {1 2}}}
}
do_test misuse-1.5 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}
do_test misuse-1.6 {
  catchsql {
    SELECT * FROM t1
  }
} {0 {1 2}}

# Attempt to register a new SQL function while an sqlite_exec() is active.
#
do_test misuse-2.1 {
  db close
  sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    SELECT * FROM t1
  }
} {1 2}
do_test misuse-2.2 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}

# We used to disallow creating new function from within an exec().
# But now this is acceptable.
do_test misuse-2.3 {
  set v [catch {
    db eval {SELECT * FROM t1} {} {
      sqlite3_create_function $::DB
    }
  } msg]
  lappend v $msg
} {0 {}}
do_test misuse-2.4 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}
do_test misuse-2.5 {
  catchsql {
    SELECT * FROM t1
  }
} {0 {1 2}}

# Attempt to register a new SQL aggregate while an sqlite_exec() is active.
#
do_test misuse-3.1 {
  db close
  sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    SELECT * FROM t1
  }
} {1 2}
do_test misuse-3.2 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}

# We used to disallow creating new function from within an exec().
# But now this is acceptable.
do_test misuse-3.3 {
  set v [catch {
    db eval {SELECT * FROM t1} {} {
      sqlite3_create_aggregate $::DB
    }
  } msg]
  lappend v $msg
} {0 {}}
do_test misuse-3.4 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}
do_test misuse-3.5 {
  catchsql {
    SELECT * FROM t1
  }
} {0 {1 2}}

# Attempt to close the database from an sqlite_exec callback.
#
# Update for v3: The db cannot be closed because there are active
# VMs. The sqlite3_close call would return SQLITE_BUSY.
do_test misuse-4.1 {
  db close
  sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    SELECT * FROM t1
  }
} {1 2}
do_test misuse-4.2 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}
do_test misuse-4.3 {
  set v [catch {
    db eval {SELECT * FROM t1} {} {
      set r [sqlite3_close $::DB]
    }
  } msg]
  lappend v $msg $r
} {0 {} SQLITE_BUSY}
do_test misuse-4.4 {
  # Flush the TCL statement cache here, otherwise the sqlite3_close() will
  # fail because there are still un-finalized() VDBEs.
  db cache flush
  sqlite3_close $::DB
  catchsql2 {SELECT * FROM t1}
} {1 {library routine called out of sequence}}
do_test misuse-4.5 {
  catchsql {
    SELECT * FROM t1
  }
} {1 {library routine called out of sequence}}

# Attempt to use a database after it has been closed.
#
do_test misuse-5.1 {
  db close
  sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    SELECT * FROM t1
  }
} {1 2}
do_test misuse-5.2 {
  catchsql2 {SELECT * FROM t1}
} {0 {a b 1 2}}
do_test misuse-5.3 {
  db close
  set r [catch {
    sqlite3_prepare $::DB {SELECT * FROM t1} -1 TAIL
  } msg]
  lappend r $msg
} {1 {(21) library routine called out of sequence}}

finish_test

Added test/mutex1.test.

















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# 2008 June 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: mutex1.test,v 1.20 2009/04/23 14:58:40 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !mutex {
  finish_test
  return
}
if {[info exists tester_do_binarylog]} {
  finish_test
  return
}

sqlite3_reset_auto_extension
clear_mutex_counters

proc mutex_counters {varname} {
  upvar $varname var
  set var(total) 0
  foreach {name value} [read_mutex_counters] {
    set var($name) $value
    incr var(total) $value
  }
}

#-------------------------------------------------------------------------
# Tests mutex1-1.* test that sqlite3_config() returns SQLITE_MISUSE if
# is called at the wrong time. And that the first time sqlite3_initialize 
# is called it obtains the 'static_master' mutex 3 times and a recursive
# mutex (sqlite3Config.pInitMutex) twice. Subsequent calls are no-ops 
# that do not require any mutexes.
#
do_test mutex1-1.0 {
  install_mutex_counters 1
} {SQLITE_MISUSE}

do_test mutex1-1.1 {
  db close
  install_mutex_counters 1
} {SQLITE_MISUSE}

do_test mutex1-1.2 {
  sqlite3_shutdown
  install_mutex_counters 1
} {SQLITE_OK}

do_test mutex1-1.3 {
  install_mutex_counters 0
} {SQLITE_OK}

do_test mutex1-1.4 {
  install_mutex_counters 1
} {SQLITE_OK}

do_test mutex1-1.5 {
  mutex_counters counters
  set counters(total)
} {0}

do_test mutex1-1.6 {
  sqlite3_initialize
} {SQLITE_OK}

do_test mutex1-1.7 {
  mutex_counters counters
  # list $counters(total) $counters(static_master)
  expr {$counters(total)>0}
} {1}

do_test mutex1-1.8 {
  clear_mutex_counters
  sqlite3_initialize
} {SQLITE_OK}

do_test mutex1-1.9 {
  mutex_counters counters
  list $counters(total) $counters(static_master)
} {0 0}

#-------------------------------------------------------------------------
# Tests mutex1-2.* test the three thread-safety related modes that
# can be selected using sqlite3_config:
#
#   * Serialized mode,
#   * Multi-threaded mode,
#   * Single-threaded mode.
#
ifcapable threadsafe&&shared_cache {
  set enable_shared_cache [sqlite3_enable_shared_cache 1]
  foreach {mode mutexes} {
    singlethread {}
    multithread  {fast static_lru static_master static_mem static_open static_prng }
    serialized  {fast recursive static_lru static_master static_mem static_open static_prng}
  } {

    do_test mutex1.2.$mode.1 {
      catch {db close}
      sqlite3_shutdown
      sqlite3_config $mode
    } SQLITE_OK

    do_test mutex1.2.$mode.2 {
      sqlite3_initialize
      clear_mutex_counters
      sqlite3 db test.db -nomutex 0 -fullmutex 0
      catchsql { CREATE TABLE abc(a, b, c) }
      db eval {
        INSERT INTO abc VALUES(1, 2, 3);
      }
    } {}
  
    do_test mutex1.2.$mode.3 {
      mutex_counters counters
  
      set res [list]
      foreach {key value} [array get counters] {
        if {$key ne "total" && $value > 0} {
          lappend res $key
        }
      }
      lsort $res
    } [lsort $mutexes]
  }
  sqlite3_enable_shared_cache $enable_shared_cache

  # Open and use a connection in "nomutex" mode. Test that no recursive
  # mutexes are obtained.
  do_test mutex1.3.1 {
    catch {db close}
    clear_mutex_counters
    sqlite3 db test.db -nomutex 1
    execsql { SELECT * FROM abc }
  } {1 2 3 1 2 3 1 2 3}
  do_test mutex1.3.2 {
    mutex_counters counters
    set counters(recursive)
  } {0}
}

# Test the sqlite3_db_mutex() function.
#
do_test mutex1.4.1 {
  catch {db close}
  sqlite3 db test.db
  enter_db_mutex db
  db eval {SELECT 1, 2, 3}
} {1 2 3}
do_test mutex1.4.2 {
  leave_db_mutex db
  db eval {SELECT 1, 2, 3}
} {1 2 3}
do_test mutex1.4.3 {
  catch {db close}
  sqlite3 db test.db -nomutex 1
  enter_db_mutex db
  db eval {SELECT 1, 2, 3}
} {1 2 3}
do_test mutex1.4.4 {
  leave_db_mutex db
  db eval {SELECT 1, 2, 3}
} {1 2 3}

do_test mutex1-X {
  catch {db close}
  sqlite3_shutdown
  clear_mutex_counters
  install_mutex_counters 0
  sqlite3_initialize
} {SQLITE_OK}

autoinstall_test_functions
finish_test

Added test/mutex2.test.



















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 2008 July 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test scripts for deliberate failures of mutex routines.
#
# $Id: mutex2.test,v 1.9 2008/10/07 15:25:49 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable !mutex {
  finish_test
  return
}

# deinitialize
#
catch {db close}
sqlite3_reset_auto_extension
sqlite3_shutdown
install_mutex_counters 1

# Fix the mutex subsystem so that it will not initialize.  In other words,
# make it so that sqlite3_initialize() always fails.  
#
do_test mutex2-1.1 {
  set ::disable_mutex_init 10
  sqlite3_initialize
} {SQLITE_IOERR}
do_test mutex2-1.1 {
  set ::disable_mutex_init 7
  sqlite3_initialize
} {SQLITE_NOMEM}

proc utf16 {str} {
  set r [encoding convertto unicode $str]
  append r "\x00\x00"
  return $r
}

# Now that sqlite3_initialize() is failing, try to run various APIs that
# require that SQLite be initialized.  Verify that they fail.
#
do_test mutex2-2.1 {
  set ::disable_mutex_init 7
  set rc [catch {sqlite db test.db} msg]
  lappend rc $msg
} {1 {}}
ifcapable utf16 {
  do_test mutex2-2.2 {
    set db2 [sqlite3_open16 [utf16 test.db] {}]
  } {0}
  do_test mutex2-2.3 {
    sqlite3_complete16 [utf16 {SELECT * FROM t1;}]
  } {7}
}
do_test mutex2-2.4 {
  sqlite3_mprintf_int {This is a test %d,%d,%d} 1 2 3
} {}
ifcapable load_ext {
  do_test mutex2-2.5 {
    sqlite3_auto_extension_sqr
  } {7}
}
do_test mutex2-2.6 {
  sqlite3_reset_auto_extension
} {}
do_test mutex2-2.7 {
  sqlite3_malloc 10000
} {0}
do_test mutex2-2.8 {
  sqlite3_realloc 0 10000
} {0}
ifcapable threadsafe {
  do_test mutex2-2.9 {
    alloc_dealloc_mutex
  } {0}
}
do_test mutex2-2.10 {
  vfs_initfail_test
} {}

# Restore the system to a functional state
#
install_mutex_counters 0
set disable_mutex_init 0
autoinstall_test_functions

# Mutex allocation works now.
#

do_test mutex2-3.1 {
  set ptr [alloc_dealloc_mutex]
  expr {$ptr!=0}
} {1}


finish_test

Added test/nan.test.

































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# 2008 April 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3060
#
# Make sure IEEE floating point NaN values are handled properly.
# SQLite should always convert NaN into NULL.
#
# Also verify that the decimal to IEEE754 binary conversion routines
# correctly generate 0.0, +Inf, and -Inf as appropriate for numbers
# out of range.
#
# $Id: nan.test,v 1.5 2008/09/18 11:30:13 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test nan-1.1.1 {
  db eval {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    CREATE TABLE t1(x FLOAT);
  }
  set ::STMT [sqlite3_prepare db "INSERT INTO t1 VALUES(?)" -1 TAIL]
  sqlite3_bind_double $::STMT 1 NaN
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT x, typeof(x) FROM t1}
} {{} null}
if {$tcl_platform(platform) != "symbian"} {
  do_test nan-1.1.2 {
    sqlite3_bind_double $::STMT 1 +Inf
    sqlite3_step $::STMT
    sqlite3_reset $::STMT
    db eval {SELECT x, typeof(x) FROM t1}
  } {{} null inf real}
  do_test nan-1.1.3 {
    sqlite3_bind_double $::STMT 1 -Inf
    sqlite3_step $::STMT
    sqlite3_reset $::STMT
    db eval {SELECT x, typeof(x) FROM t1}
  } {{} null inf real -inf real}
  do_test nan-1.1.4 {
    sqlite3_bind_double $::STMT 1 -NaN
    sqlite3_step $::STMT
    sqlite3_reset $::STMT
    db eval {SELECT x, typeof(x) FROM t1}
  } {{} null inf real -inf real {} null}
  do_test nan-1.1.5 {
    sqlite3_bind_double $::STMT 1 NaN0
    sqlite3_step $::STMT
    sqlite3_reset $::STMT
    db eval {SELECT x, typeof(x) FROM t1}
  } {{} null inf real -inf real {} null {} null}
  do_test nan-1.1.5 {
    sqlite3_bind_double $::STMT 1 -NaN0
    sqlite3_step $::STMT
    sqlite3_reset $::STMT
    db eval {SELECT x, typeof(x) FROM t1}
  } {{} null inf real -inf real {} null {} null {} null}
  do_test nan-1.1.6 {
    db eval {
      UPDATE t1 SET x=x-x;
      SELECT x, typeof(x) FROM t1;
    }
  } {{} null {} null {} null {} null {} null {} null}
}

# The following block of tests, nan-1.2.*, are the same as the nan-1.1.*
# tests above, except that the SELECT queries used to validate data 
# convert floating point values to text internally before returning them
# to Tcl. This allows the tests to be run on platforms where Tcl has
# problems converting "inf" and "-inf" from floating point to text format.
# It also tests the internal float->text conversion routines a bit.
#
do_test nan-1.2.1 {
  db eval {
    DELETE FROM T1;
  }
  sqlite3_bind_double $::STMT 1 NaN
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {{} null}
do_test nan-1.2.2 {
  sqlite3_bind_double $::STMT 1 +Inf
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {{} null Inf real}
do_test nan-1.2.3 {
  sqlite3_bind_double $::STMT 1 -Inf
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {{} null Inf real -Inf real}
do_test nan-1.2.4 {
  sqlite3_bind_double $::STMT 1 -NaN
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {{} null Inf real -Inf real {} null}
do_test nan-1.2.5 {
  sqlite3_bind_double $::STMT 1 NaN0
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {{} null Inf real -Inf real {} null {} null}
do_test nan-1.2.5 {
  sqlite3_bind_double $::STMT 1 -NaN0
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {{} null Inf real -Inf real {} null {} null {} null}
do_test nan-1.2.6 {
  db eval {
    UPDATE t1 SET x=x-x;
    SELECT CAST(x AS text), typeof(x) FROM t1;
  }
} {{} null {} null {} null {} null {} null {} null}

do_test nan-2.1 {
  db eval {
    DELETE FROM T1;
  }
  sqlite3_bind_double $::STMT 1 NaN
  sqlite3_step $::STMT
  sqlite3_reset $::STMT
  db eval {SELECT x, typeof(x) FROM t1}
} {{} null}
sqlite3_finalize $::STMT

# SQLite always converts NaN into NULL so it is not possible to write
# a NaN value into the database file using SQLite.  The following series
# of tests writes a normal floating point value (0.5) into the database,
# then writes directly into the database file to change the 0.5 into NaN.
# Then it reads the value of the database to verify it is converted into
# NULL.
#
do_test nan-3.1 {
  db eval {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(0.5);
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size=1024;
    VACUUM;
  }
  hexio_read test.db 2040 8
} {3FE0000000000000}
do_test nan-3.2 {
  db eval {
    SELECT x, typeof(x) FROM t1
  }
} {0.5 real}
do_test nan-3.3 {
  db close
  hexio_write test.db 2040 FFF8000000000000
  sqlite3 db test.db
  db eval {SELECT x, typeof(x) FROM t1}
} {{} null}
do_test nan-3.4 {
  db close
  hexio_write test.db 2040 7FF8000000000000
  sqlite3 db test.db
  db eval {SELECT x, typeof(x) FROM t1}
} {{} null}
do_test nan-3.5 {
  db close
  hexio_write test.db 2040 FFFFFFFFFFFFFFFF
  sqlite3 db test.db
  db eval {SELECT x, typeof(x) FROM t1}
} {{} null}
do_test nan-3.6 {
  db close
  hexio_write test.db 2040 7FFFFFFFFFFFFFFF
  sqlite3 db test.db
  db eval {SELECT x, typeof(x) FROM t1}
} {{} null}

# Verify that the sqlite3AtoF routine is able to handle extreme
# numbers.
#
do_test nan-4.1 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES([string repeat 9 307].0)"
  db eval {SELECT x, typeof(x) FROM t1}
} {1e+307 real}
do_test nan-4.2 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES([string repeat 9 308].0)"
  db eval {SELECT x, typeof(x) FROM t1}
} {1e+308 real}
do_test nan-4.3 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES(-[string repeat 9 307].0)"
  db eval {SELECT x, typeof(x) FROM t1}
} {-1e+307 real}
do_test nan-4.4 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES(-[string repeat 9 308].0)"
  db eval {SELECT x, typeof(x) FROM t1}
} {-1e+308 real}
do_test nan-4.5 {
  db eval {DELETE FROM t1}
  set big -[string repeat 0 10000][string repeat 9 308].[string repeat 0 10000]
  db eval "INSERT INTO t1 VALUES($big)"
  db eval {SELECT x, typeof(x) FROM t1}
} {-1e+308 real}
do_test nan-4.6 {
  db eval {DELETE FROM t1}
  set big [string repeat 0 10000][string repeat 9 308].[string repeat 0 10000]
  db eval "INSERT INTO t1 VALUES($big)"
  db eval {SELECT x, typeof(x) FROM t1}
} {1e+308 real}

if {$tcl_platform(platform) != "symbian"} {
  # Do not run these tests on Symbian, as the Tcl port doesn't like to
  # convert from floating point value "-inf" to a string.
  #
  do_test nan-4.7 {
    db eval {DELETE FROM t1}
    db eval "INSERT INTO t1 VALUES([string repeat 9 309].0)"
    db eval {SELECT x, typeof(x) FROM t1}
  } {inf real}
  do_test nan-4.8 {
    db eval {DELETE FROM t1}
    db eval "INSERT INTO t1 VALUES(-[string repeat 9 309].0)"
    db eval {SELECT x, typeof(x) FROM t1}
  } {-inf real}
}
do_test nan-4.9 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES([string repeat 9 309].0)"
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {Inf real}
do_test nan-4.10 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES(-[string repeat 9 309].0)"
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {-Inf real}

do_test nan-4.10 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES(1234.5[string repeat 0 10000]12345)"
  db eval {SELECT x, typeof(x) FROM t1}
} {1234.5 real}
do_test nan-4.11 {
  db eval {DELETE FROM t1}
  db eval "INSERT INTO t1 VALUES(-1234.5[string repeat 0 10000]12345)"
  db eval {SELECT x, typeof(x) FROM t1}
} {-1234.5 real}
do_test nan-4.12 {
  db eval {DELETE FROM t1}
  set small [string repeat 0 10000].[string repeat 0 324][string repeat 9 10000]
  db eval "INSERT INTO t1 VALUES($small)"
  db eval {SELECT x, typeof(x) FROM t1}
} {0.0 real}
do_test nan-4.13 {
  db eval {DELETE FROM t1}
  set small \
      -[string repeat 0 10000].[string repeat 0 324][string repeat 9 10000]
  db eval "INSERT INTO t1 VALUES($small)"
  db eval {SELECT x, typeof(x) FROM t1}
} {0.0 real}

# These tests test some really, really small floating point numbers.
#
if {$tcl_platform(platform) != "symbian"} {
  # These two are not run on symbian because tcl has trouble converting
  # the very small numbers back to text form (probably due to a difference
  # in the sprintf() implementation).
  #
  do_test nan-4.14 {
    db eval {DELETE FROM t1}
    set small \
        [string repeat 0 10000].[string repeat 0 323][string repeat 9 10000]
    db eval "INSERT INTO t1 VALUES($small)"
    db eval {SELECT x, typeof(x) FROM t1}
  } {9.88131291682493e-324 real}
  do_test nan-4.15 {
    db eval {DELETE FROM t1}
    set small \
        -[string repeat 0 10000].[string repeat 0 323][string repeat 9 10000]
    db eval "INSERT INTO t1 VALUES($small)"
    db eval {SELECT x, typeof(x) FROM t1}
  } {-9.88131291682493e-324 real}
}
do_test nan-4.16 {
  db eval {DELETE FROM t1}
  set small [string repeat 0 10000].[string repeat 0 323][string repeat 9 10000]
  db eval "INSERT INTO t1 VALUES($small)"
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {9.88131291682493e-324 real}
do_test nan-4.17 {
  db eval {DELETE FROM t1}
  set small \
      -[string repeat 0 10000].[string repeat 0 323][string repeat 9 10000]
  db eval "INSERT INTO t1 VALUES($small)"
  db eval {SELECT CAST(x AS text), typeof(x) FROM t1}
} {-9.88131291682493e-324 real}

do_test nan-4.20 {
  db eval {DELETE FROM t1}
  set big [string repeat 9 10000].0e-9000
  db eval "INSERT INTO t1 VALUES($big)"
  db eval {SELECT x, typeof(x) FROM t1}
} {inf real}



finish_test

Added test/notify1.test.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# 2009 March 04
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the sqlite3_unlock_notify() API.
#
# $Id: notify1.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !unlock_notify||!shared_cache {
  finish_test
  return
}
db close
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

#-------------------------------------------------------------------------
# Warm body test. Test that an unlock-notify callback can be registered 
# and that it is invoked.
#
do_test notify1-1.1 {
  sqlite3 db test.db
  sqlite3 db2 test.db
  execsql { CREATE TABLE t1(a, b) }
} {}
do_test notify1-1.2 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(1, 2);
  }
  catchsql { INSERT INTO t1 VALUES(3, 4) } db2
} {1 {database table is locked}}
do_test notify1-1.3 {
  set zScript ""
  db2 unlock_notify {
    set zScript "db2 eval { INSERT INTO t1 VALUES(3, 4) }"
  }
  execsql { SELECT * FROM t1 }
} {1 2}
do_test notify1-1.4 {
  set zScript
} {}
do_test notify1-1.5 {
  execsql { COMMIT }
  eval $zScript
  execsql { SELECT * FROM t1 }
} {1 2 3 4}

#-------------------------------------------------------------------------
# Verify that invoking the "unlock_notify" method with no arguments
# (which is the equivalent of invoking sqlite3_unlock_notify() with
# a NULL xNotify argument) cancels a pending notify callback.
#
do_test notify1-1.11 {
  execsql { DROP TABLE t1; CREATE TABLE t1(a, b) }
} {}
do_test notify1-1.12 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(1, 2);
  }
  catchsql { INSERT INTO t1 VALUES(3, 4) } db2
} {1 {database table is locked}}
do_test notify1-1.13 {
  set zScript ""
  db2 unlock_notify {
    set zScript "db2 eval { INSERT INTO t1 VALUES(3, 4) }"
  }
  execsql { SELECT * FROM t1 }
} {1 2}
do_test notify1-1.14 {
  set zScript
} {}
do_test notify1-1.15 {
  db2 unlock_notify
  execsql { COMMIT }
  eval $zScript
  execsql { SELECT * FROM t1 }
} {1 2}

#-------------------------------------------------------------------------
# The following tests, notify1-2.*, test that deadlock is detected 
# correctly.
# 
do_test notify1-2.1 {
  execsql { 
    CREATE TABLE t2(a, b);
    INSERT INTO t2 VALUES('I', 'II');
  }
} {}

#
# Test for simple deadlock involving two database connections.
#
# 1. Grab a write-lock on t1 with [db]. Then grab a read-lock on t2 with [db2].
# 2. Try to grab a read-lock on t1 with [db2] (fails).
# 3. Have [db2] wait on the read-lock it failed to obtain in step 2.
# 4. Try to grab a write-lock on t2 with [db] (fails).
# 5. Try to have [db] wait on the lock from step 4. Fails, as the system
#    would be deadlocked (since [db2] is already waiting on [db], and this
#    operation would have [db] wait on [db2]).
#
do_test notify1-2.2.1 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(5, 6);
  }
  execsql {
    BEGIN;
    SELECT * FROM t2;
  } db2
} {I II}
do_test notify1-2.2.2 {
  catchsql { SELECT * FROM t1 } db2
} {1 {database table is locked: t1}}
do_test notify1-2.2.3 {
  db2 unlock_notify {lappend unlock_notify db2}
} {}
do_test notify1-2.2.4 {
  catchsql { INSERT INTO t2 VALUES('III', 'IV') }
} {1 {database table is locked: t2}}
do_test notify1-2.2.5 {
  set rc [catch { db unlock_notify {lappend unlock_notify db} } msg]
  list $rc $msg
} {1 {database is deadlocked}}

#
# Test for slightly more complex deadlock involving three database
# connections: db, db2 and db3.
#
do_test notify1-2.3.1 {
  db close
  db2 close
  file delete -force test.db test2.db test3.db
  foreach con {db db2 db3} {
    sqlite3 $con test.db
    $con eval { ATTACH 'test2.db' AS aux2 }
    $con eval { ATTACH 'test3.db' AS aux3 }
  }
  execsql {
    CREATE TABLE main.t1(a, b);
    CREATE TABLE aux2.t2(a, b);
    CREATE TABLE aux3.t3(a, b);
  }
} {}
do_test notify1-2.3.2 {
  execsql { BEGIN ; INSERT INTO t1 VALUES(1, 2) } db
  execsql { BEGIN ; INSERT INTO t2 VALUES(1, 2) } db2
  execsql { BEGIN ; INSERT INTO t3 VALUES(1, 2) } db3
} {}
do_test notify1-2.3.3 {
  catchsql { SELECT * FROM t2 } db
} {1 {database table is locked: t2}}
do_test notify1-2.3.4 {
  catchsql { SELECT * FROM t3 } db2
} {1 {database table is locked: t3}}
do_test notify1-2.3.5 {
  catchsql { SELECT * FROM t1 } db3
} {1 {database table is locked: t1}}
do_test notify1-2.3.6 {
  set lUnlock [list]
  db  unlock_notify {lappend lUnlock db}
  db2 unlock_notify {lappend lUnlock db2}
} {}
do_test notify1-2.3.7 {
  set rc [catch { db3 unlock_notify {lappend lUnlock db3} } msg]
  list $rc $msg
} {1 {database is deadlocked}}
do_test notify1-2.3.8 {
  execsql { COMMIT }
  set lUnlock
} {}
do_test notify1-2.3.9 {
  db3 unlock_notify {lappend lUnlock db3} 
  set lUnlock
} {db3}
do_test notify1-2.3.10 {
  execsql { COMMIT } db2
  set lUnlock
} {db3 db}
do_test notify1-2.3.11 {
  execsql { COMMIT } db3
  set lUnlock
} {db3 db db2}
catch { db3 close }
catch { db2 close }
catch { db close }

#-------------------------------------------------------------------------
# The following tests, notify1-3.* and notify1-4.*, test that callbacks 
# can be issued when there are many (>16) connections waiting on a single 
# unlock event.
# 
foreach {tn nConn} {3 20 4 76} {
  do_test notify1-$tn.1 {
    sqlite3 db test.db
    execsql {
      BEGIN;
      INSERT INTO t1 VALUES('a', 'b');
    }
  } {}
  set lUnlock [list]
  set lUnlockFinal [list]
  for {set ii 1} {$ii <= $nConn} {incr ii} {
    do_test notify1-$tn.2.$ii.1 {
      set cmd "db$ii"
      sqlite3 $cmd test.db
      catchsql { SELECT * FROM t1 } $cmd
    } {1 {database table is locked: t1}}
    do_test notify1-$tn.2.$ii.2 {
      $cmd unlock_notify "lappend lUnlock $ii"
    } {}
    lappend lUnlockFinal $ii
  }
  do_test notify1-$tn.3 {
    set lUnlock
  } {}
  do_test notify1-$tn.4 {
    execsql {COMMIT}
    lsort -integer $lUnlock
  } $lUnlockFinal
  do_test notify1-$tn.5 {
    for {set ii 1} {$ii <= $nConn} {incr ii} {
      "db$ii" close
    }
  } {}
}
db close

#-------------------------------------------------------------------------
# These tests, notify1-5.*, test that a malloc() failure that occurs while
# allocating an array to use as an argument to an unlock-notify callback
# is handled correctly.
# 
source $testdir/malloc_common.tcl
do_malloc_test notify1-5 -tclprep {
  set ::lUnlock [list]
  execsql {
    CREATE TABLE t1(a, b);
    BEGIN;
    INSERT INTO t1 VALUES('a', 'b');
  }
  for {set ii 1} {$ii <= 60} {incr ii} {
    set cmd "db$ii"
    sqlite3 $cmd test.db
    catchsql { SELECT * FROM t1 } $cmd
    $cmd unlock_notify "lappend ::lUnlock $ii"
  }
} -sqlbody {
  COMMIT;
} -cleanup {
  # One of two things should have happened:
  #
  #   1) The transaction opened by [db] was not committed. No unlock-notify
  #      callbacks were invoked, OR
  #   2) The transaction opened by [db] was committed and 60 unlock-notify
  #      callbacks were invoked.
  #
  do_test notify1-5.systemstate {
    expr { ([llength $::lUnlock]==0 && [sqlite3_get_autocommit db]==0)
        || ([llength $::lUnlock]==60 && [sqlite3_get_autocommit db]==1)
    }
  } {1}
  for {set ii 1} {$ii <= 60} {incr ii} { "db$ii" close }
}

#-------------------------------------------------------------------------
# Test cases notify1-6.* test cases where the following occur:
# 
#   notify1-6.1.*: Test encountering an SQLITE_LOCKED error when the
#                  "blocking connection" has already been set by a previous
#                  SQLITE_LOCKED.
#
#   notify1-6.2.*: Test encountering an SQLITE_LOCKED error when already
#                  waiting on an unlock-notify callback.
#
#   notify1-6.3.*: Test that if an SQLITE_LOCKED error is encountered while
#                  already waiting on an unlock-notify callback, and then
#                  the blocker that caused the SQLITE_LOCKED commits its
#                  transaction, the unlock-notify callback is not invoked.
#
#   notify1-6.4.*: Like 6.3.*, except that instead of the second blocker
#                  committing its transaction, the first does. The 
#                  unlock-notify callback is therefore invoked.
#
db close
do_test notify1-6.1.1 {
  file delete -force test.db test2.db
  foreach conn {db db2 db3} {
    sqlite3 $conn test.db
    execsql { ATTACH 'test2.db' AS two } $conn
  }
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE two.t2(a, b);
  }
  execsql { 
    BEGIN;
    INSERT INTO t1 VALUES(1, 2);
  } db2
  execsql { 
    BEGIN;
    INSERT INTO t2 VALUES(1, 2);
  } db3
} {}
do_test notify1-6.1.2 {
  catchsql { SELECT * FROM t2 }
} {1 {database table is locked: t2}}
do_test notify1-6.1.3 {
  catchsql { SELECT * FROM t1 }
} {1 {database table is locked: t1}}

do_test notify1-6.2.1 {
  set unlocked 0
  db unlock_notify {set unlocked 1}
  set unlocked
} {0}
do_test notify1-6.2.2 {
  catchsql { SELECT * FROM t2 }
} {1 {database table is locked: t2}}
do_test notify1-6.2.3 {
  execsql { COMMIT } db2
  set unlocked
} {1}

do_test notify1-6.3.1 {
  execsql { 
    BEGIN;
    INSERT INTO t1 VALUES(3, 4);
  } db2
} {}
do_test notify1-6.3.2 {
  catchsql { SELECT * FROM t1 }
} {1 {database table is locked: t1}}
do_test notify1-6.3.3 {
  set unlocked 0
  db unlock_notify {set unlocked 1}
  set unlocked
} {0}
do_test notify1-6.3.4 {
  catchsql { SELECT * FROM t2 }
} {1 {database table is locked: t2}}
do_test notify1-6.3.5 {
  execsql { COMMIT } db3
  set unlocked
} {0}

do_test notify1-6.4.1 {
  execsql { 
    BEGIN;
    INSERT INTO t2 VALUES(3, 4);
  } db3
  catchsql { SELECT * FROM t2 }
} {1 {database table is locked: t2}}
do_test notify1-6.4.2 {
  execsql { COMMIT } db2
  set unlocked
} {1}
do_test notify1-6.4.3 {
  execsql { COMMIT } db3
} {}
db close
db2 close
db3 close

#-------------------------------------------------------------------------
# Test cases notify1-7.* tests that when more than one distinct 
# unlock-notify function is registered, all are invoked correctly.
#
proc unlock_notify {} {
  incr ::unlock_notify
}
do_test notify1-7.1 {
  foreach conn {db db2 db3} {
    sqlite3 $conn test.db
  }
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(5, 6);
  }
} {}
do_test notify1-7.2 {
  catchsql { SELECT * FROM t1 } db2
} {1 {database table is locked: t1}}
do_test notify1-7.3 {
  catchsql { SELECT * FROM t1 } db3
} {1 {database table is locked: t1}}
do_test notify1-7.4 {
  set unlock_notify 0
  db2 unlock_notify unlock_notify
  sqlite3_unlock_notify db3
} {SQLITE_OK}
do_test notify1-7.5 {
  set unlock_notify
} {0}
do_test notify1-7.6 {
  execsql { COMMIT }
  set unlock_notify
} {2}

#-------------------------------------------------------------------------
# Test cases notify1-8.* tests that the correct SQLITE_LOCKED extended 
# error code is returned in various scenarios.
#
do_test notify1-8.1 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(7, 8);
  }
  catchsql { SELECT * FROM t1 } db2
} {1 {database table is locked: t1}}
do_test notify1-8.2 {
  sqlite3_extended_errcode db2
} {SQLITE_LOCKED_SHAREDCACHE}

do_test notify1-8.3 {
  execsql {
    COMMIT;
    BEGIN EXCLUSIVE;
  }
  catchsql { SELECT * FROM t1 } db2
} {1 {database schema is locked: main}}
do_test notify1-8.4 {
  sqlite3_extended_errcode db2
} {SQLITE_LOCKED_SHAREDCACHE}

do_test notify1-8.X {
  execsql { COMMIT } 
} {}

#-------------------------------------------------------------------------
# Test cases notify1-9.* test the shared-cache 'pending-lock' feature.
#
do_test notify1-9.1 {
  execsql {
    CREATE TABLE t2(a, b);
    BEGIN;
    SELECT * FROM t1;
  } db2
} {1 2 3 4 5 6 7 8}
do_test notify1-9.2 {
  execsql { SELECT * FROM t1 } db3
} {1 2 3 4 5 6 7 8}
do_test notify1-9.3 {
  catchsql { 
    BEGIN;
    INSERT INTO t1 VALUES(9, 10);
  }
} {1 {database table is locked: t1}}
do_test notify1-9.4 {
  catchsql { SELECT * FROM t2 } db3
} {1 {database table is locked}}
do_test notify1-9.5 {
  execsql  { COMMIT } db2
  execsql { SELECT * FROM t2 } db3
} {}
do_test notify1-9.6 {
  execsql  { COMMIT }
} {}

do_test notify1-9.7 {
  execsql {
    BEGIN;
    SELECT * FROM t1;
  } db2
} {1 2 3 4 5 6 7 8}
do_test notify1-9.8 {
  execsql { SELECT * FROM t1 } db3
} {1 2 3 4 5 6 7 8}
do_test notify1-9.9 {
  catchsql { 
    BEGIN;
    INSERT INTO t1 VALUES(9, 10);
  }
} {1 {database table is locked: t1}}
do_test notify1-9.10 {
  catchsql { SELECT * FROM t2 } db3
} {1 {database table is locked}}
do_test notify1-9.11 {
  execsql  { COMMIT }
  execsql { SELECT * FROM t2 } db3
} {}
do_test notify1-9.12 {
  execsql  { COMMIT } db2
} {}

db close
db2 close
db3 close
sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/notify2.test.





































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# 2009 March 04
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: notify2.test,v 1.7 2009/03/30 11:59:31 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
if {[run_thread_tests]==0} { finish_test ; return }
ifcapable !unlock_notify||!shared_cache { finish_test ; return }

# The tests in this file test the sqlite3_blocking_step() function in
# test_thread.c. sqlite3_blocking_step() is not an SQLite API function,
# it is just a demonstration of how the sqlite3_unlock_notify() function
# can be used to synchronize multi-threaded access to SQLite databases
# in shared-cache mode.
#
# Since the implementation of sqlite3_blocking_step() is included on the
# website as example code, it is important to test that it works.
#
# notify2-1.*:
#
#   This test uses $nThread threads. Each thread opens the main database
#   and attaches two other databases. Each database contains a single table.
#
#   Each thread repeats transactions over and over for 20 seconds. Each
#   transaction consists of 3 operations. Each operation is either a read
#   or a write of one of the tables. The read operations verify an invariant
#   to make sure that things are working as expected. If an SQLITE_LOCKED
#   error is returned the current transaction is rolled back immediately.
#
#   This exercise is repeated twice, once using sqlite3_step(), and the
#   other using sqlite3_blocking_step(). The results are compared to ensure
#   that sqlite3_blocking_step() resulted in higher transaction throughput.
#

db close
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

# Number of threads to run simultaneously.
#
set nThread 6
set nSecond 5

# The Tcl script executed by each of the $nThread threads used by this test.
#
set ThreadProgram {

  # Proc used by threads to execute SQL.
  #
  proc execsql_blocking {db zSql} {
    set lRes [list]
    set rc SQLITE_OK

set sql $zSql

    while {$rc=="SQLITE_OK" && $zSql ne ""} {
      set STMT [$::xPrepare $db $zSql -1 zSql]
      while {[set rc [$::xStep $STMT]] eq "SQLITE_ROW"} {
        for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} {
          lappend lRes [sqlite3_column_text $STMT 0]
        }
      }
      set rc [sqlite3_finalize $STMT]
    }

    if {$rc != "SQLITE_OK"} { error "$rc $sql [sqlite3_errmsg $db]" }
    return $lRes
  }

  proc execsql_retry {db sql} { 
    set msg "SQLITE_LOCKED blah..."
    while { [string match SQLITE_LOCKED* $msg] } {
      catch { execsql_blocking $db $sql } msg
    }
  }

  proc select_one {args} {
    set n [llength $args]
    lindex $args [expr int($n*rand())]
  }

  proc opendb {} {
    # Open a database connection. Attach the two auxillary databases.
    set ::DB [sqlite3_open test.db]
    execsql_retry $::DB { ATTACH 'test2.db' AS aux2; }
    execsql_retry $::DB { ATTACH 'test3.db' AS aux3; }
  }

  opendb

  #after 2000

  # This loop runs for ~20 seconds.
  #
  set iStart [clock_seconds]
  while { ([clock_seconds]-$iStart) < $nSecond } {

    # Each transaction does 3 operations. Each operation is either a read
    # or write of a randomly selected table (t1, t2 or t3). Set the variables
    # $SQL(1), $SQL(2) and $SQL(3) to the SQL commands used to implement
    # each operation.
    #
    for {set ii 1} {$ii <= 3} {incr ii} {
      foreach {tbl database} [select_one {t1 main} {t2 aux2} {t3 aux3}] {}

      set SQL($ii) [string map [list xxx $tbl yyy $database] [select_one {
            SELECT 
              (SELECT b FROM xxx WHERE a=(SELECT max(a) FROM xxx))==total(a) 
              FROM xxx WHERE a!=(SELECT max(a) FROM xxx);
      } {
            DELETE FROM xxx WHERE a<(SELECT max(a)-100 FROM xxx);
            INSERT INTO xxx SELECT NULL, total(a) FROM xxx;
      } {
            CREATE INDEX IF NOT EXISTS yyy.xxx_i ON xxx(b);
      } {
            DROP INDEX IF EXISTS yyy.xxx_i;
      }
      ]]
    }

    # Execute the SQL transaction.
    #
    set rc [catch { execsql_blocking $::DB "
        BEGIN;
          $SQL(1);
          $SQL(2);
          $SQL(3);
        COMMIT;
      "
    } msg]

    if {$rc && [string match "SQLITE_LOCKED*" $msg]
            || [string match "SQLITE_SCHEMA*" $msg]
    } {
      # Hit an SQLITE_LOCKED error. Rollback the current transaction.
      set rc [catch { execsql_blocking $::DB ROLLBACK } msg]
      if {$rc && [string match "SQLITE_LOCKED*" $msg]} {
        sqlite3_close $::DB
        opendb
      } 
    } elseif {$rc} {
      # Hit some other kind of error. This is a malfunction.
      error $msg
    } else {
      # No error occured. Check that any SELECT statements in the transaction
      # returned "1". Otherwise, the invariant was false, indicating that
      # some malfunction has occured.
      foreach r $msg { if {$r != 1} { puts "Invariant check failed: $msg" } }
    }
  }

  # Close the database connection and return 0.
  #
  sqlite3_close $::DB
  expr 0
}

foreach {iTest xStep xPrepare} {
  1 sqlite3_blocking_step sqlite3_blocking_prepare_v2
  2 sqlite3_step          sqlite3_nonblocking_prepare_v2
} {
  file delete -force test.db test2.db test3.db

  set ThreadSetup "set xStep $xStep;set xPrepare $xPrepare;set nSecond $nSecond"

  # Set up the database schema used by this test. Each thread opens file
  # test.db as the main database, then attaches files test2.db and test3.db
  # as auxillary databases. Each file contains a single table (t1, t2 and t3, in
  # files test.db, test2.db and test3.db, respectively). 
  #
  do_test notify2-$iTest.1.1 {
    sqlite3 db test.db
    execsql {
      ATTACH 'test2.db' AS aux2;
      ATTACH 'test3.db' AS aux3;
      CREATE TABLE main.t1(a INTEGER PRIMARY KEY, b);
      CREATE TABLE aux2.t2(a INTEGER PRIMARY KEY, b);
      CREATE TABLE aux3.t3(a INTEGER PRIMARY KEY, b);
      INSERT INTO t1 SELECT NULL, 0;
      INSERT INTO t2 SELECT NULL, 0;
      INSERT INTO t3 SELECT NULL, 0;
    }
  } {}
  do_test notify2-$iTest.1.2 {
    db close
  } {}


  # Launch $nThread threads. Then wait for them to finish.
  #
  puts "Running $xStep test for $nSecond seconds"
  unset -nocomplain finished
  for {set ii 0} {$ii < $nThread} {incr ii} {
    thread_spawn finished($ii) $ThreadSetup $ThreadProgram
  }
  for {set ii 0} {$ii < $nThread} {incr ii} {
    do_test notify2-$iTest.2.$ii {
      if {![info exists finished($ii)]} { vwait finished($ii) }
      set finished($ii)
    } {0}
  }

  # Count the total number of succesful writes.
  do_test notify2-$iTest.3.1 {
    sqlite3 db test.db
    execsql {
      ATTACH 'test2.db' AS aux2;
      ATTACH 'test3.db' AS aux3;
    }
    set anWrite($xStep) [execsql {
      SELECT (SELECT max(a) FROM t1)
           + (SELECT max(a) FROM t2)
           + (SELECT max(a) FROM t3)
    }]
    db close
  } {}
}

# The following tests checks to make sure sqlite3_blocking_step() is
# faster than sqlite3_step().  blocking_step() is always faster on
# multi-core and is usually faster on single-core.  But sometimes, by
# chance, step() will be faster on a single core, in which case the
# following test will fail.
#
puts "The following test seeks to demonstrate that the sqlite3_unlock_notify()"
puts "interface helps multi-core systems to run faster.  This test sometimes"
puts "fails on single-core machines."
puts [array get anWrite]
do_test notify2-3 {
  expr {$anWrite(sqlite3_blocking_step) > $anWrite(sqlite3_step)}
} {1}

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/notnull.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# 2002 January 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the NOT NULL constraint.
#
# $Id: notnull.test,v 1.4 2006/01/17 09:35:02 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !conflict {
  finish_test
  return
}

do_test notnull-1.0 {
  execsql {
    CREATE TABLE t1 (
      a NOT NULL,
      b NOT NULL DEFAULT 5,
      c NOT NULL ON CONFLICT REPLACE DEFAULT 6,
      d NOT NULL ON CONFLICT IGNORE DEFAULT 7,
      e NOT NULL ON CONFLICT ABORT DEFAULT 8
    );
    SELECT * FROM t1;
  }
} {}
do_test notnull-1.1 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-1.2 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-1.3 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {}}
do_test notnull-1.4 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-1.5 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-1.6 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-1.7 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-1.8 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-1.9 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-1.10 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.b may not be NULL}}
do_test notnull-1.11 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {}}
do_test notnull-1.12 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-1.13 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 6 4 5}}
do_test notnull-1.14 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {}}
do_test notnull-1.15 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 6 4 5}}
do_test notnull-1.16 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.c may not be NULL}}
do_test notnull-1.17 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,3,null,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.d may not be NULL}}
do_test notnull-1.18 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,b,c,e) VALUES(1,2,3,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 3 7 5}}
do_test notnull-1.19 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d) VALUES(1,2,3,4);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 3 4 8}}
do_test notnull-1.20 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,null);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.e may not be NULL}}
do_test notnull-1.21 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(e,d,c,b,a) VALUES(1,2,3,null,5);
    SELECT * FROM t1 order by a;
  }
} {0 {5 5 3 2 1}}

do_test notnull-2.1 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-2.2 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR REPLACE t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-2.3 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR IGNORE t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-2.4 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR ABORT t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-2.5 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET b=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.b may not be NULL}}
do_test notnull-2.6 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR REPLACE t1 SET b=null, d=e, e=d;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 5 3 5 4}}
do_test notnull-2.7 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR IGNORE t1 SET b=null, d=e, e=d;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-2.8 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET c=null, d=e, e=d;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 6 5 4}}
do_test notnull-2.9 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET d=null, a=b, b=a;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-2.10 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET e=null, a=b, b=a;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.e may not be NULL}}

do_test notnull-3.0 {
  execsql {
    CREATE INDEX t1a ON t1(a);
    CREATE INDEX t1b ON t1(b);
    CREATE INDEX t1c ON t1(c);
    CREATE INDEX t1d ON t1(d);
    CREATE INDEX t1e ON t1(e);
    CREATE INDEX t1abc ON t1(a,b,c);
  }
} {}
do_test notnull-3.1 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-3.2 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-3.3 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {}}
do_test notnull-3.4 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-3.5 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(b,c,d,e) VALUES(2,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-3.6 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-3.7 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-3.8 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-3.9 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,c,d,e) VALUES(1,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-3.10 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.b may not be NULL}}
do_test notnull-3.11 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {}}
do_test notnull-3.12 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 5 3 4 5}}
do_test notnull-3.13 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 6 4 5}}
do_test notnull-3.14 {
  catchsql {
    DELETE FROM t1;
    INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {}}
do_test notnull-3.15 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 6 4 5}}
do_test notnull-3.16 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.c may not be NULL}}
do_test notnull-3.17 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,3,null,5);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.d may not be NULL}}
do_test notnull-3.18 {
  catchsql {
    DELETE FROM t1;
    INSERT OR ABORT INTO t1(a,b,c,e) VALUES(1,2,3,5);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 3 7 5}}
do_test notnull-3.19 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d) VALUES(1,2,3,4);
    SELECT * FROM t1 order by a;
  }
} {0 {1 2 3 4 8}}
do_test notnull-3.20 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,null);
    SELECT * FROM t1 order by a;
  }
} {1 {t1.e may not be NULL}}
do_test notnull-3.21 {
  catchsql {
    DELETE FROM t1;
    INSERT OR REPLACE INTO t1(e,d,c,b,a) VALUES(1,2,3,null,5);
    SELECT * FROM t1 order by a;
  }
} {0 {5 5 3 2 1}}

do_test notnull-4.1 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-4.2 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR REPLACE t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-4.3 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR IGNORE t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-4.4 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR ABORT t1 SET a=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.a may not be NULL}}
do_test notnull-4.5 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET b=null;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.b may not be NULL}}
do_test notnull-4.6 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR REPLACE t1 SET b=null, d=e, e=d;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 5 3 5 4}}
do_test notnull-4.7 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE OR IGNORE t1 SET b=null, d=e, e=d;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-4.8 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET c=null, d=e, e=d;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 6 5 4}}
do_test notnull-4.9 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET d=null, a=b, b=a;
    SELECT * FROM t1 ORDER BY a;
  }
} {0 {1 2 3 4 5}}
do_test notnull-4.10 {
  catchsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    UPDATE t1 SET e=null, a=b, b=a;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 {t1.e may not be NULL}}

# Test that bug 29ab7be99f is fixed.
#
do_test notnull-5.1 {
  execsql {
    DROP TABLE IF EXISTS t1;
    CREATE TABLE t1(a, b NOT NULL);
    CREATE TABLE t2(c, d);
    INSERT INTO t2 VALUES(3, 4);
    INSERT INTO t2 VALUES(5, NULL);
  }
}  {}
do_test notnull-5.2 {
  catchsql {
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t1 SELECT * FROM t2;
  }
} {1 {t1.b may not be NULL}}
do_test notnull-5.3 {
  execsql { SELECT * FROM t1 }
} {1 2}
do_test notnull-5.4 {
  catchsql {
    DELETE FROM t1;
    BEGIN;
      INSERT INTO t1 VALUES(1, 2);
      INSERT INTO t1 SELECT * FROM t2;
    COMMIT;
  }
} {1 {t1.b may not be NULL}}
do_test notnull-5.5 {
  execsql { SELECT * FROM t1 }
} {1 2}

finish_test

Added test/null.test.























































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for proper treatment of the special
# value NULL.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table and some data to work with.
#
do_test null-1.0 {
  execsql {
    begin;
    create table t1(a,b,c);
    insert into t1 values(1,0,0);
    insert into t1 values(2,0,1);
    insert into t1 values(3,1,0);
    insert into t1 values(4,1,1);
    insert into t1 values(5,null,0);
    insert into t1 values(6,null,1);
    insert into t1 values(7,null,null);
    commit;
    select * from t1;
  }
} {1 0 0 2 0 1 3 1 0 4 1 1 5 {} 0 6 {} 1 7 {} {}}

# Check for how arithmetic expressions handle NULL
#
do_test null-1.1 {
  execsql {
    select ifnull(a+b,99) from t1;
  }
} {1 2 4 5 99 99 99}
do_test null-1.2 {
  execsql {
    select ifnull(b*c,99) from t1;
  }
} {0 0 0 1 99 99 99}

# Check to see how the CASE expression handles NULL values.  The
# first WHEN for which the test expression is TRUE is selected.
# FALSE and UNKNOWN test expressions are skipped.
#
do_test null-2.1 {
  execsql {
    select ifnull(case when b<>0 then 1 else 0 end, 99) from t1;
  }
} {0 0 1 1 0 0 0}
do_test null-2.2 {
  execsql {
    select ifnull(case when not b<>0 then 1 else 0 end, 99) from t1;
  }
} {1 1 0 0 0 0 0}
do_test null-2.3 {
  execsql {
    select ifnull(case when b<>0 and c<>0 then 1 else 0 end, 99) from t1;
  }
} {0 0 0 1 0 0 0}
do_test null-2.4 {
  execsql {
    select ifnull(case when not (b<>0 and c<>0) then 1 else 0 end, 99) from t1;
  }
} {1 1 1 0 1 0 0}
do_test null-2.5 {
  execsql {
    select ifnull(case when b<>0 or c<>0 then 1 else 0 end, 99) from t1;
  }
} {0 1 1 1 0 1 0}
do_test null-2.6 {
  execsql {
    select ifnull(case when not (b<>0 or c<>0) then 1 else 0 end, 99) from t1;
  }
} {1 0 0 0 0 0 0}
do_test null-2.7 {
  execsql {
    select ifnull(case b when c then 1 else 0 end, 99) from t1;
  }
} {1 0 0 1 0 0 0}
do_test null-2.8 {
  execsql {
    select ifnull(case c when b then 1 else 0 end, 99) from t1;
  }
} {1 0 0 1 0 0 0}

# Check to see that NULL values are ignored in aggregate functions.
#
do_test null-3.1 {
  execsql {
    select count(*), count(b), count(c), sum(b), sum(c), 
           avg(b), avg(c), min(b), max(b) from t1;
  }
} {7 4 6 2 3 0.5 0.5 0 1}

# The sum of zero entries is a NULL, but the total of zero entries is 0.
#
do_test null-3.2 {
  execsql {
    SELECT sum(b), total(b) FROM t1 WHERE b<0
  }
} {{} 0.0}

# Check to see how WHERE clauses handle NULL values.  A NULL value
# is the same as UNKNOWN.  The WHERE clause should only select those
# rows that are TRUE.  FALSE and UNKNOWN rows are rejected.
#
do_test null-4.1 {
  execsql {
    select a from t1 where b<10
  }
} {1 2 3 4}
do_test null-4.2 {
  execsql {
    select a from t1 where not b>10
  }
} {1 2 3 4}
do_test null-4.3 {
  execsql {
    select a from t1 where b<10 or c=1;
  }
} {1 2 3 4 6}
do_test null-4.4 {
  execsql {
    select a from t1 where b<10 and c=1;
  }
} {2 4}
do_test null-4.5 {
  execsql {
    select a from t1 where not (b<10 and c=1);
  }
} {1 3 5}

# The DISTINCT keyword on a SELECT statement should treat NULL values
# as distinct
#
do_test null-5.1 {
  execsql {
    select distinct b from t1 order by b;
  }
} {{} 0 1}

# A UNION to two queries should treat NULL values
# as distinct.
#
# (Later:)  We also take this opportunity to test the ability
# of an ORDER BY clause to bind to either SELECT of a UNION.
# The left-most SELECT is preferred.  In standard SQL, only
# the left SELECT can be used.  The ability to match an ORDER
# BY term to the right SELECT is an SQLite extension.
#
ifcapable compound {
  do_test null-6.1 {
    execsql {
      select b from t1 union select c from t1 order by b;
    }
  } {{} 0 1}
  do_test null-6.2 {
    execsql {
      select b from t1 union select c from t1 order by 1;
    }
  } {{} 0 1}
  do_test null-6.3 {
    execsql {
      select b from t1 union select c from t1 order by t1.b;
    }
  } {{} 0 1}
  do_test null-6.4 {
    execsql {
      select b from t1 union select c from t1 order by main.t1.b;
    }
  } {{} 0 1}
  do_test null-6.5 {
    catchsql {
      select b from t1 union select c from t1 order by t1.a;
    }
  } {1 {1st ORDER BY term does not match any column in the result set}}
  do_test null-6.6 {
    catchsql {
      select b from t1 union select c from t1 order by main.t1.a;
    }
  } {1 {1st ORDER BY term does not match any column in the result set}}
} ;# ifcapable compound

# The UNIQUE constraint only applies to non-null values
#
ifcapable conflict {
do_test null-7.1 {
    execsql {
      create table t2(a, b unique on conflict ignore);
      insert into t2 values(1,1);
      insert into t2 values(2,null);
      insert into t2 values(3,null);
      insert into t2 values(4,1);
      select a from t2;
    }
  } {1 2 3}
  do_test null-7.2 {
    execsql {
      create table t3(a, b, c, unique(b,c) on conflict ignore);
      insert into t3 values(1,1,1);
      insert into t3 values(2,null,1);
      insert into t3 values(3,null,1);
      insert into t3 values(4,1,1);
      select a from t3;
    }
  } {1 2 3}
}

# Ticket #461 - Make sure nulls are handled correctly when doing a
# lookup using an index.
#
do_test null-8.1 {
  execsql {
    CREATE TABLE t4(x,y);
    INSERT INTO t4 VALUES(1,11);
    INSERT INTO t4 VALUES(2,NULL);
    SELECT x FROM t4 WHERE y=NULL;
  }
} {}
ifcapable subquery {
  do_test null-8.2 {
    execsql {
      SELECT x FROM t4 WHERE y IN (33,NULL);
    }
  } {}
}
do_test null-8.3 {
  execsql {
    SELECT x FROM t4 WHERE y<33 ORDER BY x;
  }
} {1}
do_test null-8.4 {
  execsql {
    SELECT x FROM t4 WHERE y>6 ORDER BY x;
  }
} {1}
do_test null-8.5 {
  execsql {
    SELECT x FROM t4 WHERE y!=33 ORDER BY x;
  }
} {1}
do_test null-8.11 {
  execsql {
    CREATE INDEX t4i1 ON t4(y);
    SELECT x FROM t4 WHERE y=NULL;
  }
} {}
ifcapable subquery {
  do_test null-8.12 {
    execsql {
      SELECT x FROM t4 WHERE y IN (33,NULL);
    }
  } {}
}
do_test null-8.13 {
  execsql {
    SELECT x FROM t4 WHERE y<33 ORDER BY x;
  }
} {1}
do_test null-8.14 {
  execsql {
    SELECT x FROM t4 WHERE y>6 ORDER BY x;
  }
} {1}
do_test null-8.15 {
  execsql {
    SELECT x FROM t4 WHERE y!=33 ORDER BY x;
  }
} {1}



finish_test

Added test/openv2.test.















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 2007 Sep 3
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests on the sqlite3_open_v2() interface.
#
# $Id: openv2.test,v 1.2 2009/06/11 17:32:45 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db close
file delete -force test.db test.db-journal
do_test openv2-1.1 {
  set rc [catch {sqlite3 db test.db -create 0} msg]
  lappend rc $msg
} {1 {unable to open database file}}
do_test openv2-1.2 {
  info commands db
} {}
do_test openv2-1.3 {
  sqlite3 db test.db
  db eval {CREATE TABLE t1(x)}
  db close
  sqlite3 db test.db -readonly 1
  db eval {SELECT name FROM sqlite_master}
} {t1}
do_test openv2-1.4 {
  catchsql {
    INSERT INTO t1 VALUES(123)
  }
} {1 {attempt to write a readonly database}}

# Ticket #3908
# Honor SQLITE_OPEN_READONLY even on an in-memory database, even though
# this is pointless.
#
do_test openv2-2.1 {
  db close
  sqlite3 db :memory: -readonly 1
  db eval {SELECT * FROM sqlite_master}
} {}
do_test openv2-2.2 {
  catchsql {CREATE TABLE t1(x)}
} {1 {attempt to write a readonly database}}


finish_test

Added test/pageropt.test.















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# 2007 April 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
# The focus of the tests in this file are to verify that the
# pager optimizations implemented in version 3.3.14 work.
#
# $Id: pageropt.test,v 1.5 2008/08/20 14:49:25 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!pager_pragmas||secure_delete} {
  finish_test
  return
}

# Run the SQL statement supplied by the argument and return
# the results.  Prepend four integers to the beginning of the
# result which are
#
#     (1)  The number of page reads from the database
#     (2)  The number of page writes to the database
#     (3)  The number of page writes to the journal
#     (4)  The number of cache pages freed
#
proc pagercount_sql {sql {db db}} {
  global sqlite3_pager_readdb_count
  global sqlite3_pager_writedb_count
  global sqlite3_pager_writej_count
  global sqlite3_pager_pgfree_count
  set sqlite3_pager_readdb_count 0
  set sqlite3_pager_writedb_count 0
  set sqlite3_pager_writej_count 0
  set r [$db eval $sql]
  set cnt [list $sqlite3_pager_readdb_count \
                $sqlite3_pager_writedb_count \
                $sqlite3_pager_writej_count ]
  return [concat $cnt $r]
}

# Setup the test database
#
do_test pageropt-1.1 {
  sqlite3_soft_heap_limit 0
  execsql {
    PRAGMA auto_vacuum = OFF;
    PRAGMA page_size = 1024;
  }
  pagercount_sql {
    CREATE TABLE t1(x);
  }
} {0 2 0}
do_test pageropt-1.2 {
  pagercount_sql {
    INSERT INTO t1 VALUES(randomblob(5000));
  }
} {0 6 2}

# Verify that values remain in cache on for subsequent reads.
# We should not have to go back to disk.
#
do_test pageropt-1.3 {
  pagercount_sql {
    SELECT length(x) FROM t1
  }
} {0 0 0 5000}

# If another thread reads the database, the original cache
# remains valid.
#
sqlite3 db2 test.db
set blobcontent [db2 one {SELECT hex(x) FROM t1}]
do_test pageropt-1.4 {
  pagercount_sql {
    SELECT hex(x) FROM t1
  }
} [list 0 0 0 $blobcontent]

# But if the other thread modifies the database, then the cache
# must refill.
#
do_test pageropt-1.5 {
  db2 eval {CREATE TABLE t2(y)}
  pagercount_sql {
    SELECT hex(x) FROM t1
  }
} [list 6 0 0 $blobcontent]
do_test pageropt-1.6 {
  pagercount_sql {
    SELECT hex(x) FROM t1
  }
} [list 0 0 0 $blobcontent]

# Verify that the last page of an overflow chain is not read from
# disk when deleting a row.  The one row of t1(x) has four pages
# of overflow.  So deleting that row from t1 should involve reading
# the sqlite_master table (1 page) the main page of t1 (1 page) and
# the three overflow pages of t1 for a total of 5 pages.
#
# Pages written are page 1 (for the freelist pointer), the root page
# of the table, and one of the overflow chain pointers because it
# becomes the trunk of the freelist.  Total 3.
#
do_test pageropt-2.1 {
  db close
  sqlite3 db test.db
  pagercount_sql {
    DELETE FROM t1 WHERE rowid=1
  }
} {5 3 3}

# When pulling pages off of the freelist, there is no reason
# to actually bring in the old content.
#
do_test pageropt-2.2 {
  db close
  sqlite3 db test.db
  pagercount_sql {
    INSERT INTO t1 VALUES(randomblob(1500));
  }
} {3 4 3}
do_test pageropt-2.3 {
  pagercount_sql {
    INSERT INTO t1 VALUES(randomblob(1500));
  }
} {0 4 3}

# Note the new optimization that when pulling the very last page off of the
# freelist we do not read the content of that page.
#
do_test pageropt-2.4 {
  pagercount_sql {
    INSERT INTO t1 VALUES(randomblob(1500));
  }
} {0 5 3}

# Appending a large quantity of data does not involve writing much
# to the journal file.
#
do_test pageropt-3.1 {
  pagercount_sql {
    INSERT INTO t2 SELECT * FROM t1;
  }
} {1 7 2}

# Once again, we do not need to read the last page of an overflow chain
# while deleting.
#
do_test pageropt-3.2 {
  pagercount_sql {
    DROP TABLE t2;
  }
} {0 2 3}
do_test pageropt-3.3 {
  pagercount_sql {
    DELETE FROM t1;
  }
} {0 3 3}

# There are now 11 pages on the freelist.  Move them all into an
# overflow chain by inserting a single large record.  Starting from
# a cold cache, only page 1, the root page of table t1, and the trunk
# of the freelist need to be read (3 pages).  And only those three
# pages need to be journalled.  But 13 pages need to be written:
# page1, the root page of table t1, and an 11 page overflow chain.
#
do_test pageropt-4.1 {
  db close
  sqlite3 db test.db
  pagercount_sql {
    INSERT INTO t1 VALUES(randomblob(11300))
  }
} {3 13 3}

# Now we delete that big entries starting from a cold cache and an
# empty freelist.  The first 10 of the 11 pages overflow chain have
# to be read, together with page1 and the root of the t1 table.  12
# reads total.  But only page1, the t1 root, and the trunk of the
# freelist need to be journalled and written back.
#
do_test pageropt-4.2 {
  db close
  sqlite3 db test.db
  pagercount_sql {
    DELETE FROM t1
  }
} {12 3 3}

sqlite3_soft_heap_limit $soft_limit
catch {db2 close}
finish_test

Added test/pagesize.test.



































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# 2004 September 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
# This file implements tests for the page_size PRAGMA.
#
# $Id: pagesize.test,v 1.13 2008/08/26 21:07:27 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# This test script depends entirely on "PRAGMA page_size". So if this
# pragma is not available, omit the whole file.
ifcapable !pager_pragmas {
  finish_test
  return
}

do_test pagesize-1.1 {
  execsql {PRAGMA page_size}
} 1024
ifcapable {explain} {
  do_test pagesize-1.2 {
    catch {execsql {EXPLAIN PRAGMA page_size}}
  } 0
}
do_test pagesize-1.3 {
  execsql {
    CREATE TABLE t1(a);
    PRAGMA page_size=2048;
    PRAGMA page_size;
  }
} 1024

do_test pagesize-1.4 {
  db close
  file delete -force test.db
  sqlite3 db test.db
  execsql {
    PRAGMA page_size=511;
    PRAGMA page_size;
  }
} 1024
do_test pagesize-1.5 {
  execsql {
    PRAGMA page_size=512;
    PRAGMA page_size;
  }
} 512
if {![info exists SQLITE_MAX_PAGE_SIZE] || $SQLITE_MAX_PAGE_SIZE>=8192} {
  do_test pagesize-1.6 {
    execsql {
      PRAGMA page_size=8192;
      PRAGMA page_size;
    }
  } 8192
  do_test pagesize-1.7 {
    execsql {
      PRAGMA page_size=65537;
      PRAGMA page_size;
    }
  } 8192
  do_test pagesize-1.8 {
    execsql {
      PRAGMA page_size=1234;
      PRAGMA page_size
    }
  } 8192
}  
foreach PGSZ {512 2048 4096 8192} {
  if {[info exists SQLITE_MAX_PAGE_SIZE]
           && $SQLITE_MAX_PAGE_SIZE<$PGSZ} continue
  ifcapable memorydb {
    do_test pagesize-2.$PGSZ.0.1 {
      db close
      sqlite3 db :memory:
      execsql "PRAGMA page_size=$PGSZ;"
      execsql {PRAGMA page_size}
    } $PGSZ
    do_test pagesize-2.$PGSZ.0.2 {
      execsql {CREATE TABLE t1(x UNIQUE, y UNIQUE, z UNIQUE)}
      execsql {PRAGMA page_size}
    } $PGSZ
    do_test pagesize-2.$PGSZ.0.3 {
      execsql {
        INSERT INTO t1 VALUES(1,2,3);
        INSERT INTO t1 VALUES(2,3,4);
        SELECT * FROM t1;
      }
    } {1 2 3 2 3 4}
  }
  do_test pagesize-2.$PGSZ.1 {
    db close
    file delete -force test.db
    sqlite3 db test.db
    execsql "PRAGMA page_size=$PGSZ"
    execsql {
      CREATE TABLE t1(x);
      PRAGMA page_size;
    }
  } $PGSZ
  do_test pagesize-2.$PGSZ.2 {
    db close
    sqlite3 db test.db
    execsql {
      PRAGMA page_size
    }
  } $PGSZ
  do_test pagesize-2.$PGSZ.3 {
    file size test.db
  } [expr {$PGSZ*($AUTOVACUUM?3:2)}]
  ifcapable {vacuum} {
    do_test pagesize-2.$PGSZ.4 {
      execsql {VACUUM}
    } {}
  }
  integrity_check pagesize-2.$PGSZ.5
  do_test pagesize-2.$PGSZ.6 {
    db close
    sqlite3 db test.db
    execsql {PRAGMA page_size}
  } $PGSZ
  do_test pagesize-2.$PGSZ.7 {
    execsql {
      INSERT INTO t1 VALUES(randstr(10,9000));
      INSERT INTO t1 VALUES(randstr(10,9000));
      INSERT INTO t1 VALUES(randstr(10,9000));
      BEGIN;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      SELECT count(*) FROM t1;
    }
  } 48
  do_test pagesize-2.$PGSZ.8 {
    execsql {
      ROLLBACK;
      SELECT count(*) FROM t1;
    }
  } 3
  integrity_check pagesize-2.$PGSZ.9
  do_test pagesize-2.$PGSZ.10 {
    db close
    sqlite3 db test.db
    execsql {PRAGMA page_size}
  } $PGSZ
  do_test pagesize-2.$PGSZ.11 {
    execsql {
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      INSERT INTO t1 SELECT x||x FROM t1;
      SELECT count(*) FROM t1;
    }
  } 192
  do_test pagesize-2.$PGSZ.12 {
    execsql {
      BEGIN;
      DELETE FROM t1 WHERE rowid%5!=0;
      SELECT count(*) FROM t1;
    }
  } 38
  do_test pagesize-2.$PGSZ.13 {
    execsql {
      ROLLBACK;
      SELECT count(*) FROM t1;
    }
  } 192
  integrity_check pagesize-2.$PGSZ.14
  do_test pagesize-2.$PGSZ.15 {
    execsql {DELETE FROM t1 WHERE rowid%5!=0}
    ifcapable {vacuum} {execsql VACUUM}
    execsql {SELECT count(*) FROM t1}
  } 38
  do_test pagesize-2.$PGSZ.16 {
    execsql {DROP TABLE t1}
    ifcapable {vacuum} {execsql VACUUM}
  } {}
  integrity_check pagesize-2.$PGSZ.17
}

finish_test

Added test/pcache.test.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# 2008 August 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is focused on testing the pcache module.
#
# $Id: pcache.test,v 1.5 2009/05/08 06:52:48 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# The pcache module limits the number of pages available to purgeable
# caches to the sum of the 'cache_size' values for the set of open
# caches. This block of tests, pcache-1.*, test that the library behaves
# corrctly when it is forced to exceed this limit.
#
do_test pcache-1.1 {
  db close
  pcache_stats
} {current 0 max 0 min 0 recyclable 0}

do_test pcache-1.2 {
  sqlite3 db test.db
  execsql {
    PRAGMA cache_size=12;
    PRAGMA auto_vacuum=0;
  }
  pcache_stats
} {current 1 max 12 min 10 recyclable 1}

do_test pcache-1.3 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(a, b, c);
    CREATE TABLE t3(a, b, c);
    CREATE TABLE t4(a, b, c);
    CREATE TABLE t5(a, b, c);
  }
  pcache_stats
} {current 6 max 12 min 10 recyclable 0}

do_test pcache-1.4 {
  execsql {
    CREATE TABLE t6(a, b, c);
    CREATE TABLE t7(a, b, c);
    CREATE TABLE t8(a, b, c);
    CREATE TABLE t9(a, b, c);
  }
  pcache_stats
} {current 10 max 12 min 10 recyclable 0}

do_test pcache-1.5 {
  sqlite3 db2 test.db
  execsql "PRAGMA cache_size=10" db2
  pcache_stats
} {current 11 max 22 min 20 recyclable 1}

do_test pcache-1.6.1 {
  execsql {
    BEGIN;
    SELECT * FROM sqlite_master;
  } db2
  pcache_stats
} {current 11 max 22 min 20 recyclable 0}

# At this point connection db2 has a read lock on the database file and a 
# single pinned page in its cache. Connection [db] is holding 10 dirty 
# pages. It cannot recycle them because of the read lock held by db2.
#
do_test pcache-1.6.2 {
  execsql {
    CREATE INDEX i1 ON t1(a, b);
    CREATE INDEX i2 ON t2(a, b);
    CREATE INDEX i3 ON t3(a, b);
    CREATE INDEX i4 ON t4(a, b);
    CREATE INDEX i5 ON t5(a, b);
    CREATE INDEX i6 ON t6(a, b);
    CREATE INDEX i7 ON t7(a, b);
    CREATE INDEX i8 ON t8(a, b);
    CREATE INDEX i9 ON t9(a, b);
    CREATE INDEX i10 ON t9(a, b);
    CREATE INDEX i11 ON t9(a, b);
  } 
  pcache_stats
} {current 23 max 22 min 20 recyclable 0}

do_test pcache-1.7 {
  execsql {
    CREATE TABLE t10(a, b, c);
  } 
  pcache_stats
} {current 24 max 22 min 20 recyclable 0}

# Rolling back the transaction held by db2 at this point releases a pinned
# page. Because the number of allocated pages is greater than the 
# configured maximum, this page should be freed immediately instead of
# recycled.
#
do_test pcache-1.8 {
  execsql {ROLLBACK} db2
  pcache_stats
} {current 23 max 22 min 20 recyclable 0}

do_test pcache-1.9 {
  execsql COMMIT
  pcache_stats
} {current 22 max 22 min 20 recyclable 22}

do_test pcache-1.10 {
  db2 close
  pcache_stats
} {current 12 max 12 min 10 recyclable 12}

do_test pcache-1.11 {
  execsql { PRAGMA cache_size = 20 }
  pcache_stats
} {current 12 max 20 min 10 recyclable 12}

do_test pcache-1.12 {
  execsql { 
    SELECT * FROM t1 ORDER BY a; SELECT * FROM t1;
    SELECT * FROM t2 ORDER BY a; SELECT * FROM t2;
    SELECT * FROM t3 ORDER BY a; SELECT * FROM t3;
    SELECT * FROM t4 ORDER BY a; SELECT * FROM t4;
    SELECT * FROM t5 ORDER BY a; SELECT * FROM t5;
    SELECT * FROM t6 ORDER BY a; SELECT * FROM t6;
    SELECT * FROM t7 ORDER BY a; SELECT * FROM t7;
    SELECT * FROM t8 ORDER BY a; SELECT * FROM t8;
    SELECT * FROM t9 ORDER BY a; SELECT * FROM t9;
  }
  pcache_stats
} {current 19 max 20 min 10 recyclable 19}

do_test pcache-1.13 {
  execsql { PRAGMA cache_size = 15 }
  pcache_stats
} {current 15 max 15 min 10 recyclable 15}

do_test pcache-1.14 {
  hexio_write test.db 24 [hexio_render_int32 1000]
  execsql { SELECT * FROM sqlite_master }
  pcache_stats
} {current 2 max 15 min 10 recyclable 2}

do_test pcache-1.15 {
  execsql { 
    SELECT * FROM t1 ORDER BY a; SELECT * FROM t1;
    SELECT * FROM t2 ORDER BY a; SELECT * FROM t2;
    SELECT * FROM t3 ORDER BY a; SELECT * FROM t3;
    SELECT * FROM t4 ORDER BY a; SELECT * FROM t4;
    SELECT * FROM t5 ORDER BY a; SELECT * FROM t5;
    SELECT * FROM t6 ORDER BY a; SELECT * FROM t6;
    SELECT * FROM t7 ORDER BY a; SELECT * FROM t7;
    SELECT * FROM t8 ORDER BY a; SELECT * FROM t8;
    SELECT * FROM t9 ORDER BY a; SELECT * FROM t9;
  }
  pcache_stats
} {current 14 max 15 min 10 recyclable 14}

finish_test

Added test/pcache2.test.

































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 2008 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is focused on testing the pcache module.
#
# $Id: pcache2.test,v 1.5 2009/07/18 14:36:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Set up a pcache memory pool so that we can easily track how many
# pages are being used for cache.
#
do_test pcache2-1.1 {
  db close
  sqlite3_reset_auto_extension
  sqlite3_shutdown
  sqlite3_config_pagecache 6000 100
  sqlite3_initialize
  autoinstall_test_functions
  sqlite3_status SQLITE_STATUS_PAGECACHE_USED 1
  sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0
} {0 0 0}

# Open up two database connections to separate files.
#
do_test pcache2-1.2 {
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  db eval {PRAGMA cache_size=10}
  lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 1
} {2}
do_test pcache2-1.3 {
  file delete -force test2.db test2.db-journal
  sqlite3 db2 test2.db
  db2 eval {PRAGMA cache_size=50}
  lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 1
} {4}


# Make lots of changes on the first connection.  Verify that the
# page cache usage does not grow to consume the page space set aside
# for the second connection.
#
do_test pcache2-1.4 {
  db eval {
     CREATE TABLE t1(a,b);
     CREATE TABLE t2(x,y);
     INSERT INTO t1 VALUES(1, zeroblob(800));
     INSERT INTO t1 VALUES(2, zeroblob(800));
     INSERT INTO t2 SELECT * FROM t1;
     INSERT INTO t1 SELECT x+2, y FROM t2;
     INSERT INTO t2 SELECT a+10, b FROM t1;
     INSERT INTO t1 SELECT x+10, y FROM t2;
     INSERT INTO t2 SELECT a+100, b FROM t1;
     INSERT INTO t1 SELECT x+100, y FROM t2;
     INSERT INTO t2 SELECT a+1000, b FROM t1;
     INSERT INTO t1 SELECT x+1000, y FROM t2;
  }
  sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0
} {0 13 13}

db close
catch {db2 close}
sqlite3_reset_auto_extension
sqlite3_shutdown
sqlite3_config_pagecache 0 0
sqlite3_initialize
autoinstall_test_functions

finish_test

Added test/permutations.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
# 2008 June 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: permutations.test,v 1.51 2009/07/01 18:09:02 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Argument processing.
#
#puts "PERM-DEBUG: argv=$argv"
namespace eval ::perm {
  variable testmode [lindex $::argv 0]
  variable testfile [lindex $::argv 1]
}
set argv [lrange $argv 2 end]
#puts "PERM-DEBUG: testmode=$::perm::testmode tstfile=$::perm::testfile"

set ::permutations_presql ""
set ::permutations_test_prefix ""

if {$::perm::testmode eq "veryquick"} {
  set ::perm::testmode [list persistent_journal no_journal]
  set ISQUICK 1
}
if {$::perm::testmode eq "quick"} {
  set ::perm::testmode [list persistent_journal no_journal autovacuum_ioerr]
  set ISQUICK 1
}
if {$::perm::testmode eq "all" || $::perm::testmode eq ""} {
  set ::perm::testmode {
    memsubsys1 memsubsys2 singlethread multithread onefile utf16 exclusive
    persistent_journal persistent_journal_error no_journal no_journal_error
    autovacuum_ioerr no_mutex_try fullmutex journaltest inmemory_journal
    pcache0 pcache10 pcache50 pcache90 pcache100
  }
}
if {$::perm::testmode eq "targets"} { 
  puts ""
  puts -nonewline "veryquick            "
  puts "Same as persistent_journal and no_journal"
  puts -nonewline "quick                "
  puts "Same as persistent_journal, no_journal and autovacuum_ioerr"
  puts -nonewline "all                  "
  puts "Everything except autovacuum_crash"
}
#puts "PERM-DEBUG: testmode=$::perm::testmode"

set EXCLUDE {
  all.test                  in2.test                  onefile.test
  async2.test               incrvacuum_ioerr.test     permutations.test
  async.test                jrnlmode2.test            quick.test
  autovacuum_crash.test     jrnlmode3.test            shared_err.test
  autovacuum_ioerr.test     jrnlmode4.test            soak.test
  btree8.test               loadext.test              speed1p.test
  corrupt.test              malloc2.test              speed1.test
  crash2.test               malloc3.test              speed2.test
  crash3.test               malloc4.test              speed3.test
  crash4.test               mallocAll.test            speed4p.test
  crash6.test               malloc.test               speed4.test
  crash7.test               memleak.test              sqllimits1.test
  crash.test                memsubsys1.test           thread001.test
  exclusive3.test           memsubsys2.test           thread002.test
  fts3.test                 misc7.test                utf16.test
  fuzz_malloc.test          misuse.test               veryquick.test
  fuzz.test                 mutex2.test               vtab_err.test
  lookaside.test            fuzz3.test                savepoint4.test
  savepoint6.test
}
set ALLTESTS [list]
foreach filename [glob $testdir/*.test] {
  set filename [file tail $filename]
  if {[lsearch $EXCLUDE $filename] < 0} { lappend ALLTESTS $filename }
}
set ALLTESTS [lsort $ALLTESTS]

rename finish_test really_finish_test2
proc finish_test {} {}

rename do_test really_do_test

proc do_test {name args} {
  eval really_do_test [list "perm-$::permutations_test_prefix.$name"] $args
}

# Overload the [sqlite3] command
rename sqlite3 really_sqlite3
proc sqlite3 {args} {
  set r [eval really_sqlite3 $args]
  if { [llength $args] == 2 && $::permutations_presql ne "" } {
    [lindex $args 0] eval $::permutations_presql
  }
  set r
}

# run_tests OPTIONS
#
# where available options are:  
#
#       -initialize  SCRIPT                 (default "")
#       -shutdown    SCRIPT                 (default "")
#       -include     LIST-OF-FILES          (default $::ALLTESTS)
#       -exclude     LIST-OF-FILES          (default "")
#       -presql      SQL                    (default "")
#       -description TITLE                  (default "")
#
proc run_tests {name args} {
  set ::permutations_test_prefix $name
  set options(-shutdown) ""
  set options(-initialize) ""
  set options(-exclude) ""
  set options(-include) $::ALLTESTS
  set options(-presql) ""
  set options(-description) "no description supplied (fixme)"
  array set options $args
  #puts "PERM-DEBUG: name=$name testfile=$::perm::testfile"
  #puts "PERM-DEBUG: [array get options]"

  if {$::perm::testmode eq "targets"} {
    puts [format "% -20s %s" $name [string trim $options(-description)]]
    return
  }
  if {$::perm::testmode ne "" && [lsearch $::perm::testmode $name]<0} {
    puts "skipping permutation test $name..."
    return
  }

  uplevel $options(-initialize)
  set ::permutations_presql $options(-presql)

  foreach file [lsort $options(-include)] {
    if {[lsearch $options(-exclude) $file] < 0 &&
       ( $::perm::testfile eq "" ||
         $::perm::testfile eq $file ||
        "$::perm::testfile.test" eq $file )
    } {
      set ::perm::shared_cache_setting [shared_cache_setting]
      uplevel source $::testdir/$file
      if {$::perm::shared_cache_setting ne [shared_cache_setting]} {
        error "File $::testdir/$file changed the shared cache setting from $::perm::shared_cache_setting to [shared_cache_setting]"
      }
    } else {
      # puts "skipping file $file"
    }
  }

  uplevel $options(-shutdown)
  set ::permutations_test_prefix ""
}

proc shared_cache_setting {} {
  set ret 0
  catch {
    set ret [sqlite3_enable_shared_cache]
  }
  return $ret
}

#############################################################################
# Start of tests

# Run some tests using pre-allocated page and scratch blocks.
#
run_tests "memsubsys1" -description {
  Tests using pre-allocated page and scratch blocks
} -exclude {
  ioerr5.test
  malloc5.test
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_pagecache 4096 24
  sqlite3_config_scratch 25000 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_pagecache 0 0
  sqlite3_config_scratch 0 0
  sqlite3_initialize
  autoinstall_test_functions
}

# Run some tests using pre-allocated page and scratch blocks. This time
# the allocations are too small to use in most cases.
#
# Both ioerr5.test and malloc5.test are excluded because they test the
# sqlite3_soft_heap_limit() and sqlite3_release_memory() functionality.
# This functionality is disabled if a pre-allocated page block is provided.
#
run_tests "memsubsys2" -description {
  Tests using small pre-allocated page and scratch blocks
} -exclude {
  ioerr5.test
  malloc5.test
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_pagecache 512 5
  sqlite3_config_scratch 1000 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_pagecache 0 0
  sqlite3_config_scratch 0 0
  sqlite3_initialize
  autoinstall_test_functions
}

# Run all tests with the lookaside allocator disabled.
#
run_tests "nolookaside" -description {
  OOM tests with lookaside disabled
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_lookaside 0 0
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_lookaside 100 500
  sqlite3_initialize
  autoinstall_test_functions
}

# Run some tests in SQLITE_CONFIG_SINGLETHREAD mode.
#
run_tests "singlethread" -description {
  Tests run in SQLITE_CONFIG_SINGLETHREAD mode
} -initialize {
  catch {db close}
  sqlite3_shutdown
  catch {sqlite3_config singlethread}
  sqlite3_initialize
  autoinstall_test_functions
} -include {
  delete.test   delete2.test  insert.test  rollback.test  select1.test
  select2.test  trans.test    update.test  vacuum.test    types.test
  types2.test   types3.test
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  catch {sqlite3_config serialized}
  sqlite3_initialize
  autoinstall_test_functions
}

run_tests "nomutex" -description {
  Tests run with the SQLITE_OPEN_MULTITHREADED flag passed to sqlite3_open().
} -initialize {
  rename sqlite3 sqlite3_nomutex
  proc sqlite3 {args} {
    if {[string range [lindex $args 0] 0 0] ne "-"} {
      lappend args -fullmutex 0 -nomutex 1
    }
    uplevel [concat sqlite3_nomutex $args]
  }
} -include {
  delete.test   delete2.test  insert.test  rollback.test  select1.test
  select2.test  trans.test    update.test  vacuum.test    types.test
  types2.test   types3.test
} -shutdown {
  rename sqlite3 {}
  rename sqlite3_nomutex sqlite3
}

# Run some tests in SQLITE_CONFIG_MULTITHREAD mode.
#
run_tests "multithread" -description {
  Tests run in SQLITE_CONFIG_MULTITHREAD mode
} -initialize {
  catch {db close}
  sqlite3_shutdown
  catch {sqlite3_config multithread}
  sqlite3_initialize
  autoinstall_test_functions
} -include {
  delete.test   delete2.test  insert.test  rollback.test  select1.test
  select2.test  trans.test    update.test  vacuum.test    types.test
  types2.test   types3.test
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  catch {sqlite3_config serialized}
  sqlite3_initialize
  autoinstall_test_functions
}

# Run some tests in SQLITE_OPEN_FULLMUTEX mode.
#
run_tests "fullmutex" -description {
  Tests run in SQLITE_OPEN_FULLMUTEX mode
} -initialize {
  rename sqlite3 sqlite3_fullmutex
  proc sqlite3 {args} {
    if {[string range [lindex $args 0] 0 0] ne "-"} {
      lappend args -nomutex 0 -fullmutex 1
    }
    uplevel [concat sqlite3_fullmutex $args]
  }
} -include {
  delete.test   delete2.test  insert.test  rollback.test  select1.test
  select2.test  trans.test    update.test  vacuum.test    types.test
  types2.test   types3.test
} -shutdown {
  rename sqlite3 {}
  rename sqlite3_fullmutex sqlite3
}

# Run some tests using the "onefile" demo.
#
run_tests "onefile" -description {
  Run some tests using the "test_onefile.c" demo
} -initialize {
  rename sqlite3 sqlite3_onefile
  proc sqlite3 {args} {
    if {[string range [lindex $args 0] 0 0] ne "-"} {
      lappend args -vfs fs
    }
    uplevel [concat sqlite3_onefile $args]
  }
} -include {
  conflict.test  insert.test   insert2.test  insert3.test
  rollback.test  select1.test  select2.test  select3.test
} -shutdown {
  rename sqlite3 {}
  rename sqlite3_onefile sqlite3
}

# Run some tests using UTF-16 databases.
#
run_tests "utf16" -description {
  Run tests using UTF-16 databases
} -presql {
  pragma encoding = 'UTF-16'
} -include {
    alter.test alter3.test
    auth.test bind.test blob.test capi2.test capi3.test collate1.test
    collate2.test collate3.test collate4.test collate5.test collate6.test
    conflict.test date.test delete.test expr.test fkey1.test func.test
    hook.test index.test insert2.test insert.test interrupt.test in.test
    intpkey.test ioerr.test join2.test join.test lastinsert.test
    laststmtchanges.test limit.test lock2.test lock.test main.test 
    memdb.test minmax.test misc1.test misc2.test misc3.test notnull.test
    null.test progress.test quote.test rowid.test select1.test select2.test
    select3.test select4.test select5.test select6.test sort.test 
    subselect.test tableapi.test table.test temptable.test
    trace.test trigger1.test trigger2.test trigger3.test
    trigger4.test types2.test types.test unique.test update.test
    vacuum.test view.test where.test
}

# Run some tests in exclusive locking mode.
#
run_tests "exclusive" -description {
  Run tests in exclusive locking mode.
} -presql {
  pragma locking_mode = 'exclusive'
} -include {
  rollback.test select1.test select2.test 
  malloc.test ioerr.test
} 

# Run some tests in exclusive locking mode with truncated journals.
#
run_tests "exclusive-truncate" -description {
  Run tests in exclusive locking mode and truncate journal mode.
} -presql {
  pragma locking_mode = 'exclusive';
  pragma journal_mode = TRUNCATE;
} -include {
  delete.test delete2.test insert.test rollback.test select1.test
  select2.test update.test malloc.test ioerr.test
} 

# Run some tests in persistent journal mode.
#
run_tests "persistent_journal" -description {
  Run tests in persistent-journal mode.
} -presql {
  pragma journal_mode = persist
} -include {
  delete.test delete2.test insert.test rollback.test select1.test
  select2.test trans.test update.test vacuum.test 
}

# Run some tests in truncating journal mode.
#
run_tests "truncate_journal" -description {
  Run tests in persistent-journal mode.
} -presql {
  pragma journal_mode = truncate
} -include {
  delete.test delete2.test insert.test rollback.test select1.test
  select2.test trans.test update.test vacuum.test 
  malloc.test ioerr.test
}

# Run some error tests in persistent journal mode.
#
run_tests "persistent_journal_error" -description {
  Run malloc.test and ioerr.test in persistent-journal mode.
} -presql {
  pragma journal_mode = persist
} -include {
  malloc.test ioerr.test
}

# Run some tests in no journal mode.
#
run_tests "no_journal" -description {
  Run tests in no-journal mode.
} -presql {
  pragma journal_mode = persist
} -include {
  delete.test delete2.test insert.test rollback.test select1.test
  select2.test trans.test update.test vacuum.test 
}

# Run some error tests in no journal mode.
#
run_tests "no_journal_error" -description {
  Run malloc.test and ioerr.test in no-journal mode.
} -presql {
  pragma journal_mode = persist
} -include {
  malloc.test ioerr.test
}

# Run some crash-tests in autovacuum mode.
#
run_tests "autovacuum_crash" -description {
  Run crash.test in autovacuum mode.
} -presql {
  pragma auto_vacuum = 1
} -include crash.test

# Run some ioerr-tests in autovacuum mode.
#
run_tests "autovacuum_ioerr" -description {
  Run ioerr.test in autovacuum mode.
} -presql {
  pragma auto_vacuum = 1
} -include ioerr.test

# Run tests with an in-memory journal.
#
run_tests "inmemory_journal" -description {
  Run tests with an in-memory journal file.
} -presql {
  pragma journal_mode = 'memory'
} -exclude {
  # Exclude all tests that simulate IO errors.
  autovacuum_ioerr2.test incrvacuum_ioerr.test ioerr.test
  ioerr.test ioerr2.test ioerr3.test ioerr4.test ioerr5.test
  vacuum3.test incrblob_err.test diskfull.test backup_ioerr.test

  # Exclude test scripts that use tcl IO to access journal files or count
  # the number of fsync() calls.
  pager.test exclusive.test jrnlmode.test sync.test misc1.test 
  journal1.test conflict.test crash8.test tkt3457.test io.test
}

ifcapable mem3 {
  run_tests "memsys3" -description {
    Run tests using the allocator in mem3.c.
  } -exclude {
    autovacuum.test           delete3.test              manydb.test
    bigrow.test               incrblob2.test            memdb.test
    bitvec.test               index2.test               memsubsys1.test
    capi3c.test               ioerr.test                memsubsys2.test
    capi3.test                join3.test                pagesize.test
    collate5.test             limit.test                backup_ioerr.test
    backup_malloc.test
  } -initialize {
    catch {db close}
    sqlite3_reset_auto_extension
    sqlite3_shutdown
    sqlite3_config_heap 25000000 0
    sqlite3_config_lookaside 0 0
    ifcapable mem5 {
      # If both memsys3 and memsys5 are enabled in the build, the call to
      # [sqlite3_config_heap] will initialize the system to use memsys5.
      # The following overrides this preference and installs the memsys3
      # allocator.
      sqlite3_install_memsys3
    }
    install_malloc_faultsim 1 
    sqlite3_initialize
    autoinstall_test_functions
  } -shutdown {
    catch {db close}
    sqlite3_shutdown
    sqlite3_config_heap 0 0
    sqlite3_config_lookaside 100 500
    install_malloc_faultsim 1 
    sqlite3_initialize
    autoinstall_test_functions
  }
}

ifcapable mem5 {
  run_tests "memsys5" -description {
    Run tests using the allocator in mem5.c.
  } -exclude {
    autovacuum.test           delete3.test              manydb.test
    bigrow.test               incrblob2.test            memdb.test
    bitvec.test               index2.test               memsubsys1.test
    capi3c.test               ioerr.test                memsubsys2.test
    capi3.test                join3.test                pagesize.test
    collate5.test             limit.test                zeroblob.test
  } -initialize {
    catch {db close}
    sqlite3_shutdown
    sqlite3_config_heap 25000000 64
    sqlite3_config_lookaside 0 0
    install_malloc_faultsim 1 
    sqlite3_initialize
    autoinstall_test_functions
  } -shutdown {
    catch {db close}
    sqlite3_shutdown
    sqlite3_config_heap 0 0
    sqlite3_config_lookaside 100 500
    install_malloc_faultsim 1 
    sqlite3_initialize
    autoinstall_test_functions
  }

  run_tests "memsys5-2" -description {
    Run tests using the allocator in mem5.c in a different configuration.
  } -include {
    select1.test 
  } -initialize {
    catch {db close}
    sqlite3_shutdown
    sqlite3_config_heap 40000000 16
    sqlite3_config_lookaside 0 0
    install_malloc_faultsim 1 
    sqlite3_initialize
    autoinstall_test_functions
  } -shutdown {
    catch {db close}
    sqlite3_shutdown
    sqlite3_config_heap 0 0
    sqlite3_config_lookaside 100 500
    install_malloc_faultsim 1 
    sqlite3_initialize
    autoinstall_test_functions
  }
}

ifcapable threadsafe {
  run_tests "no_mutex_try" -description {
     The sqlite3_mutex_try() interface always fails
  } -exclude [concat $EXCLUDE mutex1.test mutex2.test] \
  -initialize {
    catch {db close}
    sqlite3_shutdown
    install_mutex_counters 1
    set ::disable_mutex_try 1
    sqlite3_initialize
    autoinstall_test_functions
  } -shutdown {
    catch {db close}
    sqlite3_shutdown
    install_mutex_counters 0
    sqlite3_initialize
    autoinstall_test_functions
  }
}

# run_tests "crash_safe_append" -description {
#   Run crash.test with persistent journals on a SAFE_APPEND file-system.
# } -initialize {
#   rename crashsql sa_crashsql
#   proc crashsql {args} {
#     set options [lrange $args 0 [expr {[llength $args]-2}]]
#     lappend options -char safe_append
#     set sql [lindex $args end]
#     lappend options "
#       PRAGMA journal_mode=persistent;
#       $sql
#     "
#     set fd [open test.db-journal w]
#     puts $fd [string repeat 1234567890 100000]
#     close $fd
#     eval sa_crashsql $options
#   }
# } -shutdown {
#   rename crashsql {}
#   rename sa_crashsql crashsql
# } -include crash.test

run_tests "safe_append" -description {
  Run some tests on a SAFE_APPEND file-system.
} -initialize {
  rename sqlite3 sqlite3_safeappend
  proc sqlite3 {args} {
    if {[string range [lindex $args 0] 0 0] ne "-"} {
      lappend args -vfs devsym
    }
    uplevel [concat sqlite3_safeappend $args]
  }
  sqlite3_simulate_device -char safe_append
} -shutdown {
  rename sqlite3 {}
  rename sqlite3_shutdown sqlite3
} -include [lsort [concat shared_err.test $ALLTESTS]] \
  -exclude async3.test

# The set of tests to run on the alternative-pcache
set perm-alt-pcache-testset {
  async.test
  attach.test
  delete.test delete2.test
  index.test
  insert.test insert2.test
  join.test join2.test
  rollback.test
  select1.test select2.test
  trans.test
  update.test
}

run_tests "pcache0" -description {
  Alternative pcache implementation without random discard
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 1 0 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 0 0 0
  sqlite3_config_lookaside 100 500
  install_malloc_faultsim 1 
  sqlite3_initialize
  autoinstall_test_functions
} -include ${perm-alt-pcache-testset}

run_tests "pcache10" -description {
  Alternative pcache implementation without 10% random discard
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 1 50 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 0 0 0
  sqlite3_initialize
  autoinstall_test_functions
} -include ${perm-alt-pcache-testset}

run_tests "pcache50" -description {
  Alternative pcache implementation without 50% random discard
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 1 50 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 0 0 0
  sqlite3_initialize
  autoinstall_test_functions
} -include ${perm-alt-pcache-testset}

run_tests "pcache90" -description {
  Alternative pcache implementation without 90% random discard
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 1 50 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 0 0 0
  sqlite3_initialize
  autoinstall_test_functions
} -include ${perm-alt-pcache-testset}

run_tests "pcache100" -description {
  Alternative pcache implementation that always discards when unpinning
} -initialize {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 1 100 1
  sqlite3_initialize
  autoinstall_test_functions
} -shutdown {
  catch {db close}
  sqlite3_shutdown
  sqlite3_config_alt_pcache 0 0 0
  sqlite3_initialize
  autoinstall_test_functions
} -include ${perm-alt-pcache-testset}

run_tests "journaltest" -description {
  Check that pages are synced before being written (test_journal.c).
} -initialize {
  set ISQUICK 1
  catch {db close}
  register_jt_vfs -default ""
  #sqlite3_instvfs binarylog -default binarylog ostrace.bin
} -shutdown {
  #sqlite3_instvfs destroy binarylog
  unregister_jt_vfs
} -include [concat $::ALLTESTS savepoint6.test
] -exclude {
  incrvacuum.test
  ioerr.test
  corrupt4.test 
  io.test 
  crash8.test 
  async4.test 
}

# End of tests
#############################################################################

if {$::perm::testmode eq "targets"} { puts "" ; exit }

# Restore the [sqlite3] command.
#
rename sqlite3 {}
rename really_sqlite3 sqlite3

# Restore the [finish_test] command.
#
rename finish_test ""
rename really_finish_test2 finish_test

# Restore the [do_test] command.
#
rename do_test ""
rename really_do_test do_test

finish_test

Added test/pragma.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
# 2002 March 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the PRAGMA command.
#
# $Id: pragma.test,v 1.73 2009/01/12 14:01:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Test organization:
#
# pragma-1.*: Test cache_size, default_cache_size and synchronous on main db.
# pragma-2.*: Test synchronous on attached db.
# pragma-3.*: Test detection of table/index inconsistency by integrity_check.
# pragma-4.*: Test cache_size and default_cache_size on attached db.
# pragma-5.*: Test that pragma synchronous may not be used inside of a
#             transaction.
# pragma-6.*: Test schema-query pragmas.
# pragma-7.*: Miscellaneous tests.
# pragma-8.*: Test user_version and schema_version pragmas.
# pragma-9.*: Test temp_store and temp_store_directory.
# pragma-10.*: Test the count_changes pragma in the presence of triggers.
# pragma-11.*: Test the collation_list pragma.
# pragma-14.*: Test the page_count pragma.
# pragma-15.*: Test that the value set using the cache_size pragma is not
#              reset when the schema is reloaded.
# pragma-16.*: Test proxy locking
#

ifcapable !pragma {
  finish_test
  return
}

# Delete the preexisting database to avoid the special setup
# that the "all.test" script does.
#
db close
file delete test.db test.db-journal
file delete test3.db test3.db-journal
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]


ifcapable pager_pragmas {
set DFLT_CACHE_SZ [db one {PRAGMA default_cache_size}]
set TEMP_CACHE_SZ [db one {PRAGMA temp.default_cache_size}]
do_test pragma-1.1 {
  execsql {
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 2]
do_test pragma-1.2 {
  execsql {
    PRAGMA synchronous=OFF;
    PRAGMA cache_size=1234;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list 1234 $DFLT_CACHE_SZ 0]
do_test pragma-1.3 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 2]
do_test pragma-1.4 {
  execsql {
    PRAGMA synchronous=OFF;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 0]
do_test pragma-1.5 {
  execsql {
    PRAGMA cache_size=-4321;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list 4321 $DFLT_CACHE_SZ 0]
do_test pragma-1.6 {
  execsql {
    PRAGMA synchronous=ON;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list 4321 $DFLT_CACHE_SZ 1]
do_test pragma-1.7 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 2]
do_test pragma-1.8 {
  execsql {
    PRAGMA default_cache_size=-123;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} {123 123 2}
do_test pragma-1.9.1 {
  db close
  sqlite3 db test.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} {123 123 2}
ifcapable vacuum {
  do_test pragma-1.9.2 {
    execsql {
      VACUUM;
      PRAGMA cache_size;
      PRAGMA default_cache_size;
      PRAGMA synchronous;
    }
  } {123 123 2}
}
do_test pragma-1.10 {
  execsql {
    PRAGMA synchronous=NORMAL;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} {123 123 1}
do_test pragma-1.11 {
  execsql {
    PRAGMA synchronous=FULL;
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} {123 123 2}
do_test pragma-1.12 {
  db close
  sqlite3 db test.db; set ::DB [sqlite3_connection_pointer db]
  execsql {
    PRAGMA cache_size;
    PRAGMA default_cache_size;
    PRAGMA synchronous;
  }
} {123 123 2}

# Make sure the pragma handler understands numeric values in addition
# to keywords like "off" and "full".
#
do_test pragma-1.13 {
  execsql {
    PRAGMA synchronous=0;
    PRAGMA synchronous;
  }
} {0}
do_test pragma-1.14 {
  execsql {
    PRAGMA synchronous=2;
    PRAGMA synchronous;
  }
} {2}
} ;# ifcapable pager_pragmas

# Test turning "flag" pragmas on and off.
#
ifcapable debug {
  # Pragma "vdbe_listing" is only available if compiled with SQLITE_DEBUG
  #
  do_test pragma-1.15 {
    execsql {
      PRAGMA vdbe_listing=YES;
      PRAGMA vdbe_listing;
    }
  } {1}
  do_test pragma-1.16 {
    execsql {
      PRAGMA vdbe_listing=NO;
      PRAGMA vdbe_listing;
    }
  } {0}
}

do_test pragma-1.17 {
  execsql {
    PRAGMA parser_trace=ON;
    PRAGMA parser_trace=OFF;
  }
} {}
do_test pragma-1.18 {
  execsql {
    PRAGMA bogus = -1234;  -- Parsing of negative values
  }
} {}

# Test modifying the safety_level of an attached database.
ifcapable pager_pragmas&&attach {
  do_test pragma-2.1 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      ATTACH 'test2.db' AS aux;
    } 
  } {}
  do_test pragma-2.2 {
    execsql {
      pragma aux.synchronous;
    } 
  } {2}
  do_test pragma-2.3 {
    execsql {
      pragma aux.synchronous = OFF;
      pragma aux.synchronous;
      pragma synchronous;
    } 
  } {0 2}
  do_test pragma-2.4 {
    execsql {
      pragma aux.synchronous = ON;
      pragma synchronous;
      pragma aux.synchronous;
    } 
  } {2 1}
} ;# ifcapable pager_pragmas

# Construct a corrupted index and make sure the integrity_check
# pragma finds it.
#
# These tests won't work if the database is encrypted
#
do_test pragma-3.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum=OFF;
    BEGIN;
    CREATE TABLE t2(a,b,c);
    CREATE INDEX i2 ON t2(a);
    INSERT INTO t2 VALUES(11,2,3);
    INSERT INTO t2 VALUES(22,3,4);
    COMMIT;
    SELECT rowid, * from t2;
  }
} {1 11 2 3 2 22 3 4}
ifcapable attach {
  if {![sqlite3 -has-codec] && $sqlite_options(integrityck)} {
    do_test pragma-3.2 {
      db eval {SELECT rootpage FROM sqlite_master WHERE name='i2'} break
      set pgsz [db eval {PRAGMA page_size}]
      # overwrite the header on the rootpage of the index in order to
      # make the index appear to be empty.
      #
      set offset [expr {$pgsz*($rootpage-1)}]
      hexio_write test.db $offset 0a00000000040000000000
      db close
      sqlite3 db test.db
      execsql {PRAGMA integrity_check}
    } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}}
    do_test pragma-3.3 {
      execsql {PRAGMA integrity_check=1}
    } {{rowid 1 missing from index i2}}
    do_test pragma-3.4 {
      execsql {
        ATTACH DATABASE 'test.db' AS t2;
        PRAGMA integrity_check
      }
    } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}}
    do_test pragma-3.5 {
      execsql {
        PRAGMA integrity_check=4
      }
    } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2}}
    do_test pragma-3.6 {
      execsql {
        PRAGMA integrity_check=xyz
      }
    } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}}
    do_test pragma-3.7 {
      execsql {
        PRAGMA integrity_check=0
      }
    } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}}
  
    # Add additional corruption by appending unused pages to the end of
    # the database file testerr.db
    #
    do_test pragma-3.8 {
      execsql {DETACH t2}
      file delete -force testerr.db testerr.db-journal
      set out [open testerr.db w]
      fconfigure $out -translation binary
      set in [open test.db r]
      fconfigure $in -translation binary
      puts -nonewline $out [read $in]
      seek $in 0
      puts -nonewline $out [read $in]
      close $in
      close $out
      execsql {REINDEX t2}
      execsql {PRAGMA integrity_check}
    } {ok}
    do_test pragma-3.8.1 {
      execsql {PRAGMA quick_check}
    } {ok}
    do_test pragma-3.9 {
      execsql {
        ATTACH 'testerr.db' AS t2;
        PRAGMA integrity_check
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}}
    do_test pragma-3.10 {
      execsql {
        PRAGMA integrity_check=1
      }
    } {{*** in database t2 ***
Page 4 is never used}}
    do_test pragma-3.11 {
      execsql {
        PRAGMA integrity_check=5
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2}}
    do_test pragma-3.12 {
      execsql {
        PRAGMA integrity_check=4
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2}}
    do_test pragma-3.13 {
      execsql {
        PRAGMA integrity_check=3
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used}}
    do_test pragma-3.14 {
      execsql {
        PRAGMA integrity_check(2)
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used}}
    do_test pragma-3.15 {
      execsql {
        ATTACH 'testerr.db' AS t3;
        PRAGMA integrity_check
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}}
    do_test pragma-3.16 {
      execsql {
        PRAGMA integrity_check(10)
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2}}
    do_test pragma-3.17 {
      execsql {
        PRAGMA integrity_check=8
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 ***
Page 4 is never used
Page 5 is never used}}
    do_test pragma-3.18 {
      execsql {
        PRAGMA integrity_check=4
      }
    } {{*** in database t2 ***
Page 4 is never used
Page 5 is never used
Page 6 is never used} {rowid 1 missing from index i2}}
  }
  do_test pragma-3.19 {
    catch {db close}
    file delete -force test.db test.db-journal
    sqlite3 db test.db
    db eval {PRAGMA integrity_check}
  } {ok}
}
#exit

# Test modifying the cache_size of an attached database.
ifcapable pager_pragmas&&attach {
do_test pragma-4.1 {
  execsql {
    ATTACH 'test2.db' AS aux;
    pragma aux.cache_size;
    pragma aux.default_cache_size;
  } 
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ]
do_test pragma-4.2 {
  execsql {
    pragma aux.cache_size = 50;
    pragma aux.cache_size;
    pragma aux.default_cache_size;
  } 
} [list 50 $DFLT_CACHE_SZ]
do_test pragma-4.3 {
  execsql {
    pragma aux.default_cache_size = 456;
    pragma aux.cache_size;
    pragma aux.default_cache_size;
  } 
} {456 456}
do_test pragma-4.4 {
  execsql {
    pragma cache_size;
    pragma default_cache_size;
  } 
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ]
do_test pragma-4.5 {
  execsql {
    DETACH aux;
    ATTACH 'test3.db' AS aux;
    pragma aux.cache_size;
    pragma aux.default_cache_size;
  } 
} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ]
do_test pragma-4.6 {
  execsql {
    DETACH aux;
    ATTACH 'test2.db' AS aux;
    pragma aux.cache_size;
    pragma aux.default_cache_size;
  } 
} {456 456}
} ;# ifcapable pager_pragmas

# Test that modifying the sync-level in the middle of a transaction is
# disallowed.
ifcapable pager_pragmas {
do_test pragma-5.0 {
  execsql {
    pragma synchronous;
  } 
} {2}
do_test pragma-5.1 {
  catchsql {
    BEGIN;
    pragma synchronous = OFF;
  } 
} {1 {Safety level may not be changed inside a transaction}}
do_test pragma-5.2 {
  execsql {
    pragma synchronous;
  } 
} {2}
catchsql {COMMIT;}
} ;# ifcapable pager_pragmas

# Test schema-query pragmas
#
ifcapable schema_pragmas {
ifcapable tempdb&&attach {
  do_test pragma-6.1 {
    set res {}
    execsql {SELECT * FROM sqlite_temp_master}
    foreach {idx name file} [execsql {pragma database_list}] {
      lappend res $idx $name
    }
    set res
  } {0 main 1 temp 2 aux}
}
do_test pragma-6.2 {
  execsql {
    CREATE TABLE t2(a,b,c);
    pragma table_info(t2)
  }
} {0 a {} 0 {} 0 1 b {} 0 {} 0 2 c {} 0 {} 0}
do_test pragma-6.2.1 {
  execsql {
    pragma table_info;
  }
} {}
db nullvalue <<NULL>>
do_test pragma-6.2.2 {
  execsql {
    CREATE TABLE t5(
      a TEXT DEFAULT CURRENT_TIMESTAMP, 
      b DEFAULT (5+3),
      c TEXT,
      d INTEGER DEFAULT NULL,
      e TEXT DEFAULT ''
    );
    PRAGMA table_info(t5);
  }
} {0 a TEXT 0 CURRENT_TIMESTAMP 0 1 b {} 0 5+3 0 2 c TEXT 0 <<NULL>> 0 3 d INTEGER 0 NULL 0 4 e TEXT 0 '' 0}
db nullvalue {}
ifcapable {foreignkey} {
  do_test pragma-6.3.1 {
    execsql {
      CREATE TABLE t3(a int references t2(b), b UNIQUE);
      pragma foreign_key_list(t3);
    }
  } {0 0 t2 a b {NO ACTION} {NO ACTION} NONE}
  do_test pragma-6.3.2 {
    execsql {
      pragma foreign_key_list;
    }
  } {}
  do_test pragma-6.3.3 {
    execsql {
      pragma foreign_key_list(t3_bogus);
    }
  } {}
  do_test pragma-6.3.4 {
    execsql {
      pragma foreign_key_list(t5);
    }
  } {}
  do_test pragma-6.4 {
    execsql {
      pragma index_list(t3);
    }
  } {0 sqlite_autoindex_t3_1 1}
}
ifcapable {!foreignkey} {
  execsql {CREATE TABLE t3(a,b UNIQUE)}
}
do_test pragma-6.5.1 {
  execsql {
    CREATE INDEX t3i1 ON t3(a,b);
    pragma index_info(t3i1);
  }
} {0 0 a 1 1 b}
do_test pragma-6.5.2 {
  execsql {
    pragma index_info(t3i1_bogus);
  }
} {}

ifcapable tempdb {
  # Test for ticket #3320. When a temp table of the same name exists, make
  # sure the schema of the main table can still be queried using 
  # "pragma table_info":
  do_test pragma-6.6.1 {
    execsql {
      CREATE TABLE trial(col_main);
      CREATE TEMP TABLE trial(col_temp);
    }
  } {}
  do_test pragma-6.6.2 {
    execsql {
      PRAGMA table_info(trial);
    }
  } {0 col_temp {} 0 {} 0}
  do_test pragma-6.6.3 {
    execsql {
      PRAGMA temp.table_info(trial);
    }
  } {0 col_temp {} 0 {} 0}
  do_test pragma-6.6.4 {
    execsql {
      PRAGMA main.table_info(trial);
    }
  } {0 col_main {} 0 {} 0}
}

do_test pragma-6.7 {
  execsql {
    CREATE TABLE test_table(
      one INT NOT NULL DEFAULT -1, 
      two text,
      three VARCHAR(45, 65) DEFAULT 'abcde',
      four REAL DEFAULT X'abcdef',
      five DEFAULT CURRENT_TIME
    );
    PRAGMA table_info(test_table);
  }
} [concat \
  {0 one INT 1 -1 0} \
  {1 two text 0 {} 0} \
  {2 three {VARCHAR(45, 65)} 0 'abcde' 0} \
  {3 four REAL 0 X'abcdef' 0} \
  {4 five {} 0 CURRENT_TIME 0} \
]
} ;# ifcapable schema_pragmas
# Miscellaneous tests
#
ifcapable schema_pragmas {
do_test pragma-7.1.1 {
  # Make sure a pragma knows to read the schema if it needs to
  db close
  sqlite3 db test.db
  execsql {
    pragma index_list(t3);
  }
} {0 t3i1 0 1 sqlite_autoindex_t3_1 1}
do_test pragma-7.1.2 {
  execsql {
    pragma index_list(t3_bogus);
  }
} {}
} ;# ifcapable schema_pragmas
ifcapable {utf16} {
  do_test pragma-7.2 {
    db close
    sqlite3 db test.db
    catchsql {
      pragma encoding=bogus;
    }
  } {1 {unsupported encoding: bogus}}
}
ifcapable tempdb {
  do_test pragma-7.3 {
    db close
    sqlite3 db test.db
    execsql {
      pragma lock_status;
    }
  } {main unlocked temp closed}
} else {
  do_test pragma-7.3 {
    db close
    sqlite3 db test.db
    execsql {
      pragma lock_status;
    }
  } {main unlocked}
}


#----------------------------------------------------------------------
# Test cases pragma-8.* test the "PRAGMA schema_version" and "PRAGMA
# user_version" statements.
#
# pragma-8.1: PRAGMA schema_version
# pragma-8.2: PRAGMA user_version
#

ifcapable schema_version {

# First check that we can set the schema version and then retrieve the
# same value.
do_test pragma-8.1.1 {
  execsql {
    PRAGMA schema_version = 105;
  }
} {}
do_test pragma-8.1.2 {
  execsql2 {
    PRAGMA schema_version;
  }
} {schema_version 105}
do_test pragma-8.1.3 {
  execsql {
    PRAGMA schema_version = 106;
  }
} {}
do_test pragma-8.1.4 {
  execsql {
    PRAGMA schema_version;
  }
} 106

# Check that creating a table modifies the schema-version (this is really
# to verify that the value being read is in fact the schema version).
do_test pragma-8.1.5 {
  execsql {
    CREATE TABLE t4(a, b, c);
    INSERT INTO t4 VALUES(1, 2, 3);
    SELECT * FROM t4;
  }
} {1 2 3}
do_test pragma-8.1.6 {
  execsql {
    PRAGMA schema_version;
  }
} 107

# Now open a second connection to the database. Ensure that changing the
# schema-version using the first connection forces the second connection
# to reload the schema. This has to be done using the C-API test functions,
# because the TCL API accounts for SCHEMA_ERROR and retries the query.
do_test pragma-8.1.7 {
  sqlite3 db2 test.db; set ::DB2 [sqlite3_connection_pointer db2]
  execsql {
    SELECT * FROM t4;
  } db2
} {1 2 3}
do_test pragma-8.1.8 {
  execsql {
    PRAGMA schema_version = 108;
  }
} {}
do_test pragma-8.1.9 {
  set ::STMT [sqlite3_prepare $::DB2 "SELECT * FROM t4" -1 DUMMY]
  sqlite3_step $::STMT
} SQLITE_ERROR
do_test pragma-8.1.10 {
  sqlite3_finalize $::STMT
} SQLITE_SCHEMA

# Make sure the schema-version can be manipulated in an attached database.
file delete -force test2.db
file delete -force test2.db-journal
ifcapable attach {
  do_test pragma-8.1.11 {
    execsql {
      ATTACH 'test2.db' AS aux;
      CREATE TABLE aux.t1(a, b, c);
      PRAGMA aux.schema_version = 205;
    }
  } {}
  do_test pragma-8.1.12 {
    execsql {
      PRAGMA aux.schema_version;
    }
  } 205
}
do_test pragma-8.1.13 {
  execsql {
    PRAGMA schema_version;
  }
} 108

# And check that modifying the schema-version in an attached database
# forces the second connection to reload the schema.
ifcapable attach {
  do_test pragma-8.1.14 {
    sqlite3 db2 test.db; set ::DB2 [sqlite3_connection_pointer db2]
    execsql {
      ATTACH 'test2.db' AS aux;
      SELECT * FROM aux.t1;
    } db2
  } {}
  do_test pragma-8.1.15 {
    execsql {
      PRAGMA aux.schema_version = 206;
    }
  } {}
  do_test pragma-8.1.16 {
    set ::STMT [sqlite3_prepare $::DB2 "SELECT * FROM aux.t1" -1 DUMMY]
    sqlite3_step $::STMT
  } SQLITE_ERROR
  do_test pragma-8.1.17 {
    sqlite3_finalize $::STMT
  } SQLITE_SCHEMA
  do_test pragma-8.1.18 {
    db2 close
  } {}
}

# Now test that the user-version can be read and written (and that we aren't
# accidentally manipulating the schema-version instead).
do_test pragma-8.2.1 {
  execsql2 {
    PRAGMA user_version;
  }
} {user_version 0}
do_test pragma-8.2.2 {
  execsql {
    PRAGMA user_version = 2;
  }
} {}
do_test pragma-8.2.3.1 {
  execsql2 {
    PRAGMA user_version;
  }
} {user_version 2}
do_test pragma-8.2.3.2 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA user_version;
  }
} {2}
do_test pragma-8.2.4.1 {
  execsql {
    PRAGMA schema_version;
  }
} {108}
ifcapable vacuum {
  do_test pragma-8.2.4.2 {
    execsql {
      VACUUM;
      PRAGMA user_version;
    }
  } {2}
  do_test pragma-8.2.4.3 {
    execsql {
      PRAGMA schema_version;
    }
  } {109}
}

ifcapable attach {
  db eval {ATTACH 'test2.db' AS aux}
  
  # Check that the user-version in the auxilary database can be manipulated (
  # and that we aren't accidentally manipulating the same in the main db).
  do_test pragma-8.2.5 {
    execsql {
      PRAGMA aux.user_version;
    }
  } {0}
  do_test pragma-8.2.6 {
    execsql {
      PRAGMA aux.user_version = 3;
    }
  } {}
  do_test pragma-8.2.7 {
    execsql {
      PRAGMA aux.user_version;
    }
  } {3}
  do_test pragma-8.2.8 {
    execsql {
      PRAGMA main.user_version;
    }
  } {2}
  
  # Now check that a ROLLBACK resets the user-version if it has been modified
  # within a transaction.
  do_test pragma-8.2.9 {
    execsql {
      BEGIN;
      PRAGMA aux.user_version = 10;
      PRAGMA user_version = 11;
    }
  } {}
  do_test pragma-8.2.10 {
    execsql {
      PRAGMA aux.user_version;
    }
  } {10}
  do_test pragma-8.2.11 {
    execsql {
      PRAGMA main.user_version;
    }
  } {11}
  do_test pragma-8.2.12 {
    execsql {
      ROLLBACK;
      PRAGMA aux.user_version;
    }
  } {3}
  do_test pragma-8.2.13 {
    execsql {
      PRAGMA main.user_version;
    }
  } {2}
}

# Try a negative value for the user-version
do_test pragma-8.2.14 {
  execsql {
    PRAGMA user_version = -450;
  }
} {}
do_test pragma-8.2.15 {
  execsql {
    PRAGMA user_version;
  }
} {-450}
} ; # ifcapable schema_version

# Check to see if TEMP_STORE is memory or disk.  Return strings
# "memory" or "disk" as appropriate.
#
proc check_temp_store {} {
  db eval {CREATE TEMP TABLE IF NOT EXISTS a(b)}
  db eval {PRAGMA database_list} {
    if {$name=="temp"} {
      set bt [btree_from_db db 1]
      if {[btree_ismemdb $bt]} {
        return "memory"
      }
      return "disk"
    }
  }
  return "unknown"
}


# Test temp_store and temp_store_directory pragmas
#
ifcapable pager_pragmas {
do_test pragma-9.1 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA temp_store;
  }
} {0}
if {$TEMP_STORE<=1} {
  do_test pragma-9.1.1 {
    check_temp_store
  } {disk}
} else {
  do_test pragma-9.1.1 {
    check_temp_store
  } {memory}
}

do_test pragma-9.2 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA temp_store=file;
    PRAGMA temp_store;
  }
} {1}
if {$TEMP_STORE==3} {
  # When TEMP_STORE is 3, always use memory regardless of pragma settings.
  do_test pragma-9.2.1 {
    check_temp_store
  } {memory}
} else {
  do_test pragma-9.2.1 {
    check_temp_store
  } {disk}
}

do_test pragma-9.3 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA temp_store=memory;
    PRAGMA temp_store;
  }
} {2}
if {$TEMP_STORE==0} {
  # When TEMP_STORE is 0, always use the disk regardless of pragma settings.
  do_test pragma-9.3.1 {
    check_temp_store
  } {disk}
} else {
  do_test pragma-9.3.1 {
    check_temp_store
  } {memory}
}

do_test pragma-9.4 {
  execsql {
    PRAGMA temp_store_directory;
  }
} {}
ifcapable wsd {
  do_test pragma-9.5 {
    set pwd [string map {' ''} [file nativename [pwd]]]
    execsql "
      PRAGMA temp_store_directory='$pwd';
    "
  } {}
  do_test pragma-9.6 {
    execsql { 
      PRAGMA temp_store_directory;
    }
  } [list [file nativename [pwd]]]
  do_test pragma-9.7 {
    catchsql { 
      PRAGMA temp_store_directory='/NON/EXISTENT/PATH/FOOBAR';
    }
  } {1 {not a writable directory}}
  do_test pragma-9.8 {
    execsql { 
      PRAGMA temp_store_directory='';
    }
  } {}
  if {![info exists TEMP_STORE] || $TEMP_STORE<=1} {
    ifcapable tempdb {
      do_test pragma-9.9 {
        execsql { 
          PRAGMA temp_store_directory;
          PRAGMA temp_store=FILE;
          CREATE TEMP TABLE temp_store_directory_test(a integer);
          INSERT INTO temp_store_directory_test values (2);
          SELECT * FROM temp_store_directory_test;
        }
      } {2}
      do_test pragma-9.10 {
        catchsql "
          PRAGMA temp_store_directory='$pwd';
          SELECT * FROM temp_store_directory_test;
        "
      } {1 {no such table: temp_store_directory_test}}
    }
  }
}
do_test pragma-9.11 {
  execsql {
    PRAGMA temp_store = 0;
    PRAGMA temp_store;
  }
} {0}
do_test pragma-9.12 {
  execsql {
    PRAGMA temp_store = 1;
    PRAGMA temp_store;
  }
} {1}
do_test pragma-9.13 {
  execsql {
    PRAGMA temp_store = 2;
    PRAGMA temp_store;
  }
} {2}
do_test pragma-9.14 {
  execsql {
    PRAGMA temp_store = 3;
    PRAGMA temp_store;
  }
} {0}
do_test pragma-9.15 {
  catchsql {
    BEGIN EXCLUSIVE;
    CREATE TEMP TABLE temp_table(t);
    INSERT INTO temp_table VALUES('valuable data');
    PRAGMA temp_store = 1;
  }
} {1 {temporary storage cannot be changed from within a transaction}}
do_test pragma-9.16 {
  execsql {
    SELECT * FROM temp_table;
    COMMIT;
  }
} {{valuable data}}

do_test pragma-9.17 {
  execsql {
    INSERT INTO temp_table VALUES('valuable data II');
    SELECT * FROM temp_table;
  }
} {{valuable data} {valuable data II}}

do_test pragma-9.18 {
  set rc [catch {
    db eval {SELECT t FROM temp_table} {
      execsql {pragma temp_store = 1}
    }
  } msg]
  list $rc $msg
} {1 {temporary storage cannot be changed from within a transaction}}

} ;# ifcapable pager_pragmas

ifcapable trigger {

do_test pragma-10.0 {
  catchsql {
    DROP TABLE main.t1;
  }
  execsql {
    PRAGMA count_changes = 1;

    CREATE TABLE t1(a PRIMARY KEY);
    CREATE TABLE t1_mirror(a);
    CREATE TABLE t1_mirror2(a);
    CREATE TRIGGER t1_bi BEFORE INSERT ON t1 BEGIN 
      INSERT INTO t1_mirror VALUES(new.a);
    END;
    CREATE TRIGGER t1_ai AFTER INSERT ON t1 BEGIN 
      INSERT INTO t1_mirror2 VALUES(new.a);
    END;
    CREATE TRIGGER t1_bu BEFORE UPDATE ON t1 BEGIN 
      UPDATE t1_mirror SET a = new.a WHERE a = old.a;
    END;
    CREATE TRIGGER t1_au AFTER UPDATE ON t1 BEGIN 
      UPDATE t1_mirror2 SET a = new.a WHERE a = old.a;
    END;
    CREATE TRIGGER t1_bd BEFORE DELETE ON t1 BEGIN 
      DELETE FROM t1_mirror WHERE a = old.a;
    END;
    CREATE TRIGGER t1_ad AFTER DELETE ON t1 BEGIN 
      DELETE FROM t1_mirror2 WHERE a = old.a;
    END;
  }
} {}

do_test pragma-10.1 {
  execsql {
    INSERT INTO t1 VALUES(randstr(10,10));
  }
} {1}
do_test pragma-10.2 {
  execsql {
    UPDATE t1 SET a = randstr(10,10);
  }
} {1}
do_test pragma-10.3 {
  execsql {
    DELETE FROM t1;
  }
} {1}

} ;# ifcapable trigger

ifcapable schema_pragmas {
  do_test pragma-11.1 {
    execsql2 {
      pragma collation_list;
    }
  } {seq 0 name NOCASE seq 1 name RTRIM seq 2 name BINARY}
  do_test pragma-11.2 {
    db collate New_Collation blah...
    execsql {
      pragma collation_list;
    }
  } {0 New_Collation 1 NOCASE 2 RTRIM 3 BINARY}
}

ifcapable schema_pragmas&&tempdb {
  do_test pragma-12.1 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA temp.table_info('abc');
    } db2
  } {}
  db2 close

  do_test pragma-12.2 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA temp.default_cache_size = 200;
      PRAGMA temp.default_cache_size;
    } db2
  } {200}
  db2 close

  do_test pragma-12.3 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA temp.cache_size = 400;
      PRAGMA temp.cache_size;
    } db2
  } {400}
  db2 close
}

ifcapable bloblit {

do_test pragma-13.1 {
  execsql {
    DROP TABLE IF EXISTS t4;
    PRAGMA vdbe_trace=on;
    PRAGMA vdbe_listing=on;
    PRAGMA sql_trace=on;
    CREATE TABLE t4(a INTEGER PRIMARY KEY,b);
    INSERT INTO t4(b) VALUES(x'0123456789abcdef0123456789abcdef0123456789');
    INSERT INTO t4(b) VALUES(randstr(30,30));
    INSERT INTO t4(b) VALUES(1.23456);
    INSERT INTO t4(b) VALUES(NULL);
    INSERT INTO t4(b) VALUES(0);
    INSERT INTO t4(b) SELECT b||b||b||b FROM t4;
    SELECT * FROM t4;
  }
  execsql {
    PRAGMA vdbe_trace=off;
    PRAGMA vdbe_listing=off;
    PRAGMA sql_trace=off;
  }
} {}

} ;# ifcapable bloblit 

ifcapable pager_pragmas {
  db close
  file delete -force test.db
  sqlite3 db test.db

  do_test pragma-14.1 {
    execsql { pragma auto_vacuum = 0 }
    execsql { pragma page_count }
  } {0}

  do_test pragma-14.2 {
    execsql { 
      CREATE TABLE abc(a, b, c);
      PRAGMA page_count;
    }
  } {2}

  do_test pragma-14.3 {
    execsql { 
      BEGIN;
      CREATE TABLE def(a, b, c);
      PRAGMA page_count;
    }
  } {3}

  do_test pragma-14.4 {
    set page_size [db one {pragma page_size}]
    expr [file size test.db] / $page_size
  } {2}

  do_test pragma-14.5 {
    execsql {
      ROLLBACK;
      PRAGMA page_count;
    }
  } {2}

  do_test pragma-14.6 {
    file delete -force test2.db
    sqlite3 db2 test2.db
    execsql {
      PRAGMA auto_vacuum = 0;
      CREATE TABLE t1(a, b, c);
      CREATE TABLE t2(a, b, c);
      CREATE TABLE t3(a, b, c);
      CREATE TABLE t4(a, b, c);
    } db2
    db2 close
    execsql {
      ATTACH 'test2.db' AS aux;
      PRAGMA aux.page_count;
    } 
  } {5}
}

# Test that the value set using the cache_size pragma is not reset when the
# schema is reloaded.
#
ifcapable pager_pragmas {
  db close
  sqlite3 db test.db
  do_test pragma-15.1 {
    execsql {
      PRAGMA cache_size=59;
      PRAGMA cache_size;
    }
  } {59}
  do_test pragma-15.2 {
    sqlite3 db2 test.db
    execsql {
      CREATE TABLE newtable(a, b, c);
    } db2
    db2 close
  } {}
  do_test pragma-15.3 {
    # Evaluating this statement will cause the schema to be reloaded (because
    # the schema was changed by another connection in pragma-15.2). At one
    # point there was a bug that reset the cache_size to its default value
    # when this happened. 
    execsql { SELECT * FROM sqlite_master }
    execsql { PRAGMA cache_size }
  } {59}
}

# Reset the sqlite3_temp_directory variable for the next run of tests:
sqlite3 dbX :memory:
dbX eval {PRAGMA temp_store_directory = ""}
dbX close

ifcapable lock_proxy_pragmas&&prefer_proxy_locking {
  set sqlite_hostid_num 1

  set using_proxy 0
  foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] {
    set using_proxy $value
  }

  # Test the lock_proxy_file pragmas.
  #
  db close
  set env(SQLITE_FORCE_PROXY_LOCKING) "0"

  sqlite3 db test.db
  do_test pragma-16.1 {
    execsql {
      PRAGMA lock_proxy_file="mylittleproxy";
      select * from sqlite_master;
    }
    execsql {
      PRAGMA lock_proxy_file;
    } 
  } {mylittleproxy}

  do_test pragma-16.2 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA lock_proxy_file="mylittleproxy";
    } db2
  } {}

  db2 close
  do_test pragma-16.2.1 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA lock_proxy_file=":auto:";
      select * from sqlite_master;
    } db2
    execsql {
      PRAGMA lock_proxy_file;
    } db2
  } {mylittleproxy}

  db2 close
  do_test pragma-16.3 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA lock_proxy_file="myotherproxy";
    } db2
    catchsql {
      select * from sqlite_master;
    } db2
  } {1 {database is locked}}

  do_test pragma-16.4 {
    db2 close
    db close
    sqlite3 db2 test.db
    execsql {
      PRAGMA lock_proxy_file="myoriginalproxy";
      PRAGMA lock_proxy_file="myotherproxy";
      PRAGMA lock_proxy_file;
    } db2
  } {myotherproxy}

  db2 close
  set env(SQLITE_FORCE_PROXY_LOCKING) "1"
  do_test pragma-16.5 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA lock_proxy_file=":auto:";
      PRAGMA lock_proxy_file;
    } db2
  } {myotherproxy}
  
  do_test pragma-16.6 {
    db2 close
    sqlite3 db2 test2.db
    set lockpath [execsql {
      PRAGMA lock_proxy_file=":auto:";
      PRAGMA lock_proxy_file;
    } db2]
    string match "*test2.db:auto:" $lockpath
  } {1}
  
  set sqlite_hostid_num 2
  do_test pragma-16.7 {
    sqlite3 db test2.db
    execsql {
      PRAGMA lock_proxy_file=":auto:";
    } 
    catchsql {
      select * from sqlite_master;
    }
  } {1 {database is locked}}
  db close
  
  do_test pragma-16.8 {
    sqlite3 db test2.db
    catchsql {
      select * from sqlite_master;
    } 
  } {1 {database is locked}}

  db2 close
  do_test pragma-16.8.1 {
    execsql {
      PRAGMA lock_proxy_file="yetanotherproxy";
      PRAGMA lock_proxy_file;
    } 
  } {yetanotherproxy}
  do_test pragma-16.8.2 {
    execsql {
      create table mine(x);
    } 
  } {}

  db close
  do_test pragma-16.9 {
    sqlite3 db proxytest.db
    set lockpath2 [execsql {
      PRAGMA lock_proxy_file=":auto:";
      PRAGMA lock_proxy_file;
    } db]
    string match "*proxytest.db:auto:" $lockpath2
  } {1}

  set env(SQLITE_FORCE_PROXY_LOCKING) $using_proxy
  set sqlite_hostid_num 0
}

# Parsing of auto_vacuum settings.
#
foreach {autovac_setting val} {
  0 0
  1 1
  2 2
  3 0
  -1 0
  none 0
  NONE 0
  NoNe 0
  full 1
  FULL 1
  incremental 2
  INCREMENTAL 2
  -1234 0
  1234 0
} {
  do_test pragma-17.1.$autovac_setting {
    catch {db close}
    sqlite3 db :memory:
    execsql "
      PRAGMA auto_vacuum=$::autovac_setting;
      PRAGMA auto_vacuum;
    "
  } $val
}

# Parsing of temp_store settings.
#
foreach {temp_setting val} {
  0 0
  1 1
  2 2
  3 0
  -1 0
  file 1
  FILE 1
  fIlE 1
  memory 2
  MEMORY 2
  MeMoRy 2
} {
  do_test pragma-18.1.$temp_setting {
    catch {db close}
    sqlite3 db :memory:
    execsql "
      PRAGMA temp_store=$::temp_setting;
      PRAGMA temp_store=$::temp_setting;
      PRAGMA temp_store;
    "
  } $val
}

finish_test

Added test/pragma2.test.















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# 2002 March 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the PRAGMA command.
#
# $Id: pragma2.test,v 1.4 2007/10/09 08:29:33 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Test organization:
#
# pragma2-1.*: Test freelist_count pragma on the main database.
# pragma2-2.*: Test freelist_count pragma on an attached database.
# pragma2-3.*: Test trying to write to the freelist_count is a no-op.
#

ifcapable !pragma||!schema_pragmas {
  finish_test
  return
}

# Delete the preexisting database to avoid the special setup
# that the "all.test" script does.
#
db close
file delete test.db test.db-journal
file delete test3.db test3.db-journal
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
db eval {PRAGMA auto_vacuum=0}

do_test pragma2-1.1 {
  execsql {
    PRAGMA freelist_count;
  }
} {0}
do_test pragma2-1.2 {
  execsql {
    CREATE TABLE abc(a, b, c);
    PRAGMA freelist_count;
  }
} {0}
do_test pragma2-1.3 {
  execsql {
    DROP TABLE abc;
    PRAGMA freelist_count;
  }
} {1}
do_test pragma2-1.4 {
  execsql {
    PRAGMA main.freelist_count;
  }
} {1}

file delete -force test2.db
file delete -force test2.db-journal

ifcapable attach {
  do_test pragma2-2.1 {
    execsql {
      ATTACH 'test2.db' AS aux;
      PRAGMA aux.auto_vacuum=OFF;
      PRAGMA aux.freelist_count;
    }
  } {0}
  do_test pragma2-2.2 {
    execsql {
      CREATE TABLE aux.abc(a, b, c);
      PRAGMA aux.freelist_count;
    }
  } {0}
  do_test pragma2-2.3 {
    set ::val [string repeat 0123456789 1000]
    execsql {
      INSERT INTO aux.abc VALUES(1, 2, $::val);
      PRAGMA aux.freelist_count;
    }
  } {0}
  do_test pragma2-2.4 {
    expr {[file size test2.db] / 1024}
  } {11}
  do_test pragma2-2.5 {
    execsql {
      DELETE FROM aux.abc;
      PRAGMA aux.freelist_count;
    }
  } {9}
  
  do_test pragma2-3.1 {
    execsql {
      PRAGMA aux.freelist_count;
      PRAGMA main.freelist_count;
      PRAGMA freelist_count;
    }
  } {9 1 1}
  do_test pragma2-3.2 {
    execsql {
      PRAGMA freelist_count = 500;
      PRAGMA freelist_count;
    }
  } {1 1}
  do_test pragma2-3.3 {
    execsql {
      PRAGMA aux.freelist_count = 500;
      PRAGMA aux.freelist_count;
    }
  } {9 9}
}

finish_test

Added test/printf.test.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the sqlite_*_printf() interface.
#
# $Id: printf.test,v 1.31 2009/02/01 00:21:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


do_test printf-1.1.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       1 1 1
} {abc: 1 1 1 :xyz}
do_test printf-1.1.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       1 1 1
} {abc: (     1) (     1) (     1) :xyz}
do_test printf-1.1.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       1 1 1
} {abc: (1     ) (1     ) (1     ) :xyz}
do_test printf-1.1.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       1 1 1
} {abc: (    +1) (     1) (     1) :xyz}
do_test printf-1.1.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       1 1 1
} {abc: (000001) (000001) (000001) :xyz}
do_test printf-1.1.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       1 1 1
} {abc: (     1) (     1) (     1) :xyz}
do_test printf-1.1.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       1 1 1
} {abc: (     1) (   0x1) (    01) :xyz}
do_test printf-1.2.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       2 2 2
} {abc: 2 2 2 :xyz}
do_test printf-1.2.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       2 2 2
} {abc: (     2) (     2) (     2) :xyz}
do_test printf-1.2.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       2 2 2
} {abc: (2     ) (2     ) (2     ) :xyz}
do_test printf-1.2.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       2 2 2
} {abc: (    +2) (     2) (     2) :xyz}
do_test printf-1.2.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       2 2 2
} {abc: (000002) (000002) (000002) :xyz}
do_test printf-1.2.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       2 2 2
} {abc: (     2) (     2) (     2) :xyz}
do_test printf-1.2.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       2 2 2
} {abc: (     2) (   0x2) (    02) :xyz}
do_test printf-1.3.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       5 5 5
} {abc: 5 5 5 :xyz}
do_test printf-1.3.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       5 5 5
} {abc: (     5) (     5) (     5) :xyz}
do_test printf-1.3.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       5 5 5
} {abc: (5     ) (5     ) (5     ) :xyz}
do_test printf-1.3.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       5 5 5
} {abc: (    +5) (     5) (     5) :xyz}
do_test printf-1.3.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       5 5 5
} {abc: (000005) (000005) (000005) :xyz}
do_test printf-1.3.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       5 5 5
} {abc: (     5) (     5) (     5) :xyz}
do_test printf-1.3.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       5 5 5
} {abc: (     5) (   0x5) (    05) :xyz}
do_test printf-1.4.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       10 10 10
} {abc: 10 a 12 :xyz}
do_test printf-1.4.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       10 10 10
} {abc: (    10) (     a) (    12) :xyz}
do_test printf-1.4.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       10 10 10
} {abc: (10    ) (a     ) (12    ) :xyz}
do_test printf-1.4.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       10 10 10
} {abc: (   +10) (     a) (    12) :xyz}
do_test printf-1.4.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       10 10 10
} {abc: (000010) (00000a) (000012) :xyz}
do_test printf-1.4.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       10 10 10
} {abc: (    10) (     a) (    12) :xyz}
do_test printf-1.4.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       10 10 10
} {abc: (    10) (   0xa) (   012) :xyz}
do_test printf-1.5.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       99 99 99
} {abc: 99 63 143 :xyz}
do_test printf-1.5.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       99 99 99
} {abc: (    99) (    63) (   143) :xyz}
do_test printf-1.5.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       99 99 99
} {abc: (99    ) (63    ) (143   ) :xyz}
do_test printf-1.5.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       99 99 99
} {abc: (   +99) (    63) (   143) :xyz}
do_test printf-1.5.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       99 99 99
} {abc: (000099) (000063) (000143) :xyz}
do_test printf-1.5.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       99 99 99
} {abc: (    99) (    63) (   143) :xyz}
do_test printf-1.5.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       99 99 99
} {abc: (    99) (  0x63) (  0143) :xyz}
do_test printf-1.6.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       100 100 100
} {abc: 100 64 144 :xyz}
do_test printf-1.6.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       100 100 100
} {abc: (   100) (    64) (   144) :xyz}
do_test printf-1.6.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       100 100 100
} {abc: (100   ) (64    ) (144   ) :xyz}
do_test printf-1.6.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       100 100 100
} {abc: (  +100) (    64) (   144) :xyz}
do_test printf-1.6.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       100 100 100
} {abc: (000100) (000064) (000144) :xyz}
do_test printf-1.6.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       100 100 100
} {abc: (   100) (    64) (   144) :xyz}
do_test printf-1.6.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       100 100 100
} {abc: (   100) (  0x64) (  0144) :xyz}
do_test printf-1.7.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       1000000 1000000 1000000
} {abc: 1000000 f4240 3641100 :xyz}
do_test printf-1.7.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       1000000 1000000 1000000
} {abc: (1000000) ( f4240) (3641100) :xyz}
do_test printf-1.7.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       1000000 1000000 1000000
} {abc: (1000000) (f4240 ) (3641100) :xyz}
do_test printf-1.7.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       1000000 1000000 1000000
} {abc: (+1000000) ( f4240) (3641100) :xyz}
do_test printf-1.7.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       1000000 1000000 1000000
} {abc: (1000000) (0f4240) (3641100) :xyz}
do_test printf-1.7.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       1000000 1000000 1000000
} {abc: ( 1000000) ( f4240) (3641100) :xyz}
do_test printf-1.7.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       1000000 1000000 1000000
} {abc: (1000000) (0xf4240) (03641100) :xyz}
do_test printf-1.8.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       999999999 999999999 999999999
} {abc: 999999999 3b9ac9ff 7346544777 :xyz}
do_test printf-1.8.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       999999999 999999999 999999999
} {abc: (999999999) (3b9ac9ff) (7346544777) :xyz}
do_test printf-1.8.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       999999999 999999999 999999999
} {abc: (999999999) (3b9ac9ff) (7346544777) :xyz}
do_test printf-1.8.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       999999999 999999999 999999999
} {abc: (+999999999) (3b9ac9ff) (7346544777) :xyz}
do_test printf-1.8.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       999999999 999999999 999999999
} {abc: (999999999) (3b9ac9ff) (7346544777) :xyz}
do_test printf-1.8.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       999999999 999999999 999999999
} {abc: ( 999999999) (3b9ac9ff) (7346544777) :xyz}
do_test printf-1.8.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       999999999 999999999 999999999
} {abc: (999999999) (0x3b9ac9ff) (07346544777) :xyz}
do_test printf-1.9.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0 0 0
} {abc: 0 0 0 :xyz}
do_test printf-1.9.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0 0 0
} {abc: (     0) (     0) (     0) :xyz}
do_test printf-1.9.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0 0 0
} {abc: (0     ) (0     ) (0     ) :xyz}
do_test printf-1.9.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0 0 0
} {abc: (    +0) (     0) (     0) :xyz}
do_test printf-1.9.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0 0 0
} {abc: (000000) (000000) (000000) :xyz}
do_test printf-1.9.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0 0 0
} {abc: (     0) (     0) (     0) :xyz}
do_test printf-1.9.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0 0 0
} {abc: (     0) (     0) (     0) :xyz}
# 0xffffffff == -1
do_test printf-1.10.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: -1 ffffffff 37777777777 :xyz}
do_test printf-1.10.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: (    -1) (ffffffff) (37777777777) :xyz}
do_test printf-1.10.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: (-1    ) (ffffffff) (37777777777) :xyz}
do_test printf-1.10.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: (    -1) (ffffffff) (37777777777) :xyz}
do_test printf-1.10.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: (-00001) (ffffffff) (37777777777) :xyz}
do_test printf-1.10.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: (    -1) (ffffffff) (37777777777) :xyz}
do_test printf-1.10.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xffffffff 0xffffffff 0xffffffff
} {abc: (    -1) (0xffffffff) (037777777777) :xyz}
# 0xfffffffe == -2
do_test printf-1.11.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: -2 fffffffe 37777777776 :xyz}
do_test printf-1.11.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: (    -2) (fffffffe) (37777777776) :xyz}
do_test printf-1.11.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: (-2    ) (fffffffe) (37777777776) :xyz}
do_test printf-1.11.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: (    -2) (fffffffe) (37777777776) :xyz}
do_test printf-1.11.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: (-00002) (fffffffe) (37777777776) :xyz}
do_test printf-1.11.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: (    -2) (fffffffe) (37777777776) :xyz}
do_test printf-1.11.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xfffffffe 0xfffffffe 0xfffffffe
} {abc: (    -2) (0xfffffffe) (037777777776) :xyz}
# 0xfffffffb == -5
do_test printf-1.12.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: -5 fffffffb 37777777773 :xyz}
do_test printf-1.12.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: (    -5) (fffffffb) (37777777773) :xyz}
do_test printf-1.12.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: (-5    ) (fffffffb) (37777777773) :xyz}
do_test printf-1.12.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: (    -5) (fffffffb) (37777777773) :xyz}
do_test printf-1.12.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: (-00005) (fffffffb) (37777777773) :xyz}
do_test printf-1.12.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: (    -5) (fffffffb) (37777777773) :xyz}
do_test printf-1.12.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xfffffffb 0xfffffffb 0xfffffffb
} {abc: (    -5) (0xfffffffb) (037777777773) :xyz}
# 0xfffffff6 == -10
do_test printf-1.13.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: -10 fffffff6 37777777766 :xyz}
do_test printf-1.13.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: (   -10) (fffffff6) (37777777766) :xyz}
do_test printf-1.13.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: (-10   ) (fffffff6) (37777777766) :xyz}
do_test printf-1.13.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: (   -10) (fffffff6) (37777777766) :xyz}
do_test printf-1.13.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: (-00010) (fffffff6) (37777777766) :xyz}
do_test printf-1.13.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: (   -10) (fffffff6) (37777777766) :xyz}
do_test printf-1.13.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xfffffff6 0xfffffff6 0xfffffff6
} {abc: (   -10) (0xfffffff6) (037777777766) :xyz}
# 0xffffff9d == -99
do_test printf-1.14.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: -99 ffffff9d 37777777635 :xyz}
do_test printf-1.14.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: (   -99) (ffffff9d) (37777777635) :xyz}
do_test printf-1.14.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: (-99   ) (ffffff9d) (37777777635) :xyz}
do_test printf-1.14.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: (   -99) (ffffff9d) (37777777635) :xyz}
do_test printf-1.14.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: (-00099) (ffffff9d) (37777777635) :xyz}
do_test printf-1.14.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: (   -99) (ffffff9d) (37777777635) :xyz}
do_test printf-1.14.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xffffff9d 0xffffff9d 0xffffff9d
} {abc: (   -99) (0xffffff9d) (037777777635) :xyz}
# 0xffffff9c == -100
do_test printf-1.15.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: -100 ffffff9c 37777777634 :xyz}
do_test printf-1.15.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: (  -100) (ffffff9c) (37777777634) :xyz}
do_test printf-1.15.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: (-100  ) (ffffff9c) (37777777634) :xyz}
do_test printf-1.15.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: (  -100) (ffffff9c) (37777777634) :xyz}
do_test printf-1.15.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: (-00100) (ffffff9c) (37777777634) :xyz}
do_test printf-1.15.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: (  -100) (ffffff9c) (37777777634) :xyz}
do_test printf-1.15.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xffffff9c 0xffffff9c 0xffffff9c
} {abc: (  -100) (0xffffff9c) (037777777634) :xyz}
# 0xff676981 == -9999999
do_test printf-1.16.1 {
  sqlite3_mprintf_int {abc: %d %x %o :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: -9999999 ff676981 37731664601 :xyz}
do_test printf-1.16.2 {
  sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: (-9999999) (ff676981) (37731664601) :xyz}
do_test printf-1.16.3 {
  sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: (-9999999) (ff676981) (37731664601) :xyz}
do_test printf-1.16.4 {
  sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: (-9999999) (ff676981) (37731664601) :xyz}
do_test printf-1.16.5 {
  sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: (-9999999) (ff676981) (37731664601) :xyz}
do_test printf-1.16.6 {
  sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: (-9999999) (ff676981) (37731664601) :xyz}
do_test printf-1.16.7 {
  sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\
       0xff676981 0xff676981 0xff676981
} {abc: (-9999999) (0xff676981) (037731664601) :xyz}
do_test printf-2.1.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 0.001
} {abc: (0.0) :xyz}
do_test printf-2.1.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 0.001
} {abc: (1.0e-03) :xyz}
do_test printf-2.1.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 0.001
} {abc: (0.001) :xyz}
do_test printf-2.1.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 0.001
} {abc: 1 1 (0.001) :xyz}
do_test printf-2.1.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 0.001
} {abc: 1 1 (0.00100000) :xyz}
do_test printf-2.1.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 0.001
} {abc: 1 1 (000000.001) :xyz}
do_test printf-2.1.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 0.001
} {abc: 1 1 (0.0) :xyz}
do_test printf-2.1.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 0.001
} {abc: 1 1 (1.0e-03) :xyz}
do_test printf-2.1.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 0.001
} {abc: 1 1 (0.001) :xyz}
do_test printf-2.1.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 1.0e-20
} {abc: (0.0) :xyz}
do_test printf-2.1.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 1.0e-20
} {abc: (1.0e-20) :xyz}
do_test printf-2.1.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 1.0e-20
} {abc: (1e-20) :xyz}
do_test printf-2.1.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 1.0e-20
} {abc: 1 1 (1e-20) :xyz}
do_test printf-2.1.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 1.0e-20
} {abc: 1 1 (1.00000e-20) :xyz}
do_test printf-2.1.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 1.0e-20
} {abc: 1 1 (000001e-20) :xyz}
do_test printf-2.1.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 1.0e-20
} {abc: 1 1 (0.0) :xyz}
do_test printf-2.1.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 1.0e-20
} {abc: 1 1 (1.0e-20) :xyz}
do_test printf-2.1.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 1.0e-20
} {abc: 1 1 (1e-20) :xyz}
do_test printf-2.1.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 1.0
} {abc: (1.0) :xyz}
do_test printf-2.1.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 1.0
} {abc: (1.0e+00) :xyz}
do_test printf-2.1.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 1.0
} {abc: (1) :xyz}
do_test printf-2.1.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 1.0
} {abc: 1 1 (1) :xyz}
do_test printf-2.1.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 1.0
} {abc: 1 1 (1.00000) :xyz}
do_test printf-2.1.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 1.0
} {abc: 1 1 (0000000001) :xyz}
do_test printf-2.1.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 1.0
} {abc: 1 1 (1.0) :xyz}
do_test printf-2.1.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 1.0
} {abc: 1 1 (1.0e+00) :xyz}
do_test printf-2.1.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 1.0
} {abc: 1 1 (1) :xyz}
do_test printf-2.1.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 0.0
} {abc: (0.0) :xyz}
do_test printf-2.1.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 0.0
} {abc: (0.0e+00) :xyz}
do_test printf-2.1.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 0.0
} {abc: (0) :xyz}
do_test printf-2.1.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 0.0
} {abc: 1 1 (0) :xyz}
do_test printf-2.1.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 0.0
} {abc: 1 1 (0.00000) :xyz}
do_test printf-2.1.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 0.0
} {abc: 1 1 (0000000000) :xyz}
do_test printf-2.1.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 0.0
} {abc: 1 1 (0.0) :xyz}
do_test printf-2.1.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 0.0
} {abc: 1 1 (0.0e+00) :xyz}
do_test printf-2.1.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 0.0
} {abc: 1 1 (0) :xyz}
do_test printf-2.1.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 100.0
} {abc: (100.0) :xyz}
do_test printf-2.1.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 100.0
} {abc: (1.0e+02) :xyz}
do_test printf-2.1.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 100.0
} {abc: (1e+02) :xyz}
do_test printf-2.1.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 100.0
} {abc: 1 1 (100) :xyz}
do_test printf-2.1.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 100.0
} {abc: 1 1 (100.000) :xyz}
do_test printf-2.1.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 100.0
} {abc: 1 1 (0000000100) :xyz}
do_test printf-2.1.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 100.0
} {abc: 1 1 (100.0) :xyz}
do_test printf-2.1.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 100.0
} {abc: 1 1 (1.0e+02) :xyz}
do_test printf-2.1.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 100.0
} {abc: 1 1 (1e+02) :xyz}
do_test printf-2.1.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 9.99999
} {abc: (10.0) :xyz}
do_test printf-2.1.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 9.99999
} {abc: (1.0e+01) :xyz}
do_test printf-2.1.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 9.99999
} {abc: (1e+01) :xyz}
do_test printf-2.1.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 9.99999
} {abc: 1 1 (9.99999) :xyz}
do_test printf-2.1.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 9.99999
} {abc: 1 1 (9.99999) :xyz}
do_test printf-2.1.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 9.99999
} {abc: 1 1 (0009.99999) :xyz}
do_test printf-2.1.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 9.99999
} {abc: 1 1 (10.0) :xyz}
do_test printf-2.1.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 9.99999
} {abc: 1 1 (1.0e+01) :xyz}
do_test printf-2.1.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 9.99999
} {abc: 1 1 (1e+01) :xyz}
do_test printf-2.1.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -0.00543
} {abc: (-0.0) :xyz}
do_test printf-2.1.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -0.00543
} {abc: (-5.4e-03) :xyz}
do_test printf-2.1.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -0.00543
} {abc: (-0.005) :xyz}
do_test printf-2.1.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -0.00543
} {abc: 1 1 (-0.00543) :xyz}
do_test printf-2.1.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -0.00543
} {abc: 1 1 (-0.00543000) :xyz}
do_test printf-2.1.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -0.00543
} {abc: 1 1 (-000.00543) :xyz}
do_test printf-2.1.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -0.00543
} {abc: 1 1 (-0.0) :xyz}
do_test printf-2.1.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -0.00543
} {abc: 1 1 (-5.4e-03) :xyz}
do_test printf-2.1.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -0.00543
} {abc: 1 1 (-0.005) :xyz}
do_test printf-2.1.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -1.0
} {abc: (-1.0) :xyz}
do_test printf-2.1.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -1.0
} {abc: (-1.0e+00) :xyz}
do_test printf-2.1.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -1.0
} {abc: (-1) :xyz}
do_test printf-2.1.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -1.0
} {abc: 1 1 (-1) :xyz}
do_test printf-2.1.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -1.0
} {abc: 1 1 (-1.00000) :xyz}
do_test printf-2.1.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -1.0
} {abc: 1 1 (-000000001) :xyz}
do_test printf-2.1.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -1.0
} {abc: 1 1 (-1.0) :xyz}
do_test printf-2.1.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -1.0
} {abc: 1 1 (-1.0e+00) :xyz}
do_test printf-2.1.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -1.0
} {abc: 1 1 (-1) :xyz}
do_test printf-2.1.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -99.99999
} {abc: (-100.0) :xyz}
do_test printf-2.1.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -99.99999
} {abc: (-1.0e+02) :xyz}
do_test printf-2.1.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -99.99999
} {abc: (-1e+02) :xyz}
do_test printf-2.1.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -99.99999
} {abc: 1 1 (-100) :xyz}
do_test printf-2.1.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -99.99999
} {abc: 1 1 (-100.000) :xyz}
do_test printf-2.1.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -99.99999
} {abc: 1 1 (-000000100) :xyz}
do_test printf-2.1.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -99.99999
} {abc: 1 1 (-100.0) :xyz}
do_test printf-2.1.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -99.99999
} {abc: 1 1 (-1.0e+02) :xyz}
do_test printf-2.1.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -99.99999
} {abc: 1 1 (-1e+02) :xyz}
do_test printf-2.1.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 3.14e+9
} {abc: (3140000000.0) :xyz}
do_test printf-2.1.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 3.14e+9
} {abc: (3.1e+09) :xyz}
do_test printf-2.1.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 3.14e+9
} {abc: (3e+09) :xyz}
do_test printf-2.1.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 3.14e+9
} {abc: 1 1 (3.14e+09) :xyz}
do_test printf-2.1.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 3.14e+9
} {abc: 1 1 (3.14000e+09) :xyz}
do_test printf-2.1.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 3.14e+9
} {abc: 1 1 (003.14e+09) :xyz}
do_test printf-2.1.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 3.14e+9
} {abc: 1 1 (3140000000.0) :xyz}
do_test printf-2.1.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 3.14e+9
} {abc: 1 1 (3.1e+09) :xyz}
do_test printf-2.1.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 3.14e+9
} {abc: 1 1 (3e+09) :xyz}
do_test printf-2.1.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -4.72732e+88
} {abc: (-4.7e+88) :xyz}
do_test printf-2.1.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -4.72732e+88
} {abc: (-5e+88) :xyz}
do_test printf-2.1.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -4.72732e+88
} {abc: 1 1 (-4.72732e+88) :xyz}
do_test printf-2.1.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -4.72732e+88
} {abc: 1 1 (-4.72732e+88) :xyz}
do_test printf-2.1.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -4.72732e+88
} {abc: 1 1 (-4.72732e+88) :xyz}
do_test printf-2.1.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -4.72732e+88
} {abc: 1 1 (-4.7e+88) :xyz}
do_test printf-2.1.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -4.72732e+88
} {abc: 1 1 (-5e+88) :xyz}
do_test printf-2.1.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 9.87991e+143
} {abc: (9.9e+143) :xyz}
do_test printf-2.1.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 9.87991e+143
} {abc: (1e+144) :xyz}
do_test printf-2.1.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 9.87991e+143
} {abc: 1 1 (9.87991e+143) :xyz}
do_test printf-2.1.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 9.87991e+143
} {abc: 1 1 (9.87991e+143) :xyz}
do_test printf-2.1.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 9.87991e+143
} {abc: 1 1 (9.87991e+143) :xyz}
do_test printf-2.1.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 9.87991e+143
} {abc: 1 1 (9.9e+143) :xyz}
do_test printf-2.1.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 9.87991e+143
} {abc: 1 1 (1e+144) :xyz}
do_test printf-2.1.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -6.287291e-9
} {abc: (-0.0) :xyz}
do_test printf-2.1.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -6.287291e-9
} {abc: (-6.3e-09) :xyz}
do_test printf-2.1.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -6.287291e-9
} {abc: (-6e-09) :xyz}
do_test printf-2.1.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -6.287291e-9
} {abc: 1 1 (-6.28729e-09) :xyz}
do_test printf-2.1.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -6.287291e-9
} {abc: 1 1 (-6.28729e-09) :xyz}
do_test printf-2.1.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -6.287291e-9
} {abc: 1 1 (-6.28729e-09) :xyz}
do_test printf-2.1.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -6.287291e-9
} {abc: 1 1 (-0.0) :xyz}
do_test printf-2.1.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -6.287291e-9
} {abc: 1 1 (-6.3e-09) :xyz}
do_test printf-2.1.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -6.287291e-9
} {abc: 1 1 (-6e-09) :xyz}
do_test printf-2.1.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 3.38826392e-110
} {abc: (0.0) :xyz}
do_test printf-2.1.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 3.38826392e-110
} {abc: (3.4e-110) :xyz}
do_test printf-2.1.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 3.38826392e-110
} {abc: (3e-110) :xyz}
do_test printf-2.1.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 3.38826392e-110
} {abc: 1 1 (3.38826e-110) :xyz}
do_test printf-2.1.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 3.38826392e-110
} {abc: 1 1 (3.38826e-110) :xyz}
do_test printf-2.1.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 3.38826392e-110
} {abc: 1 1 (3.38826e-110) :xyz}
do_test printf-2.1.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 3.38826392e-110
} {abc: 1 1 (0.0) :xyz}
do_test printf-2.1.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 3.38826392e-110
} {abc: 1 1 (3.4e-110) :xyz}
do_test printf-2.1.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 3.38826392e-110
} {abc: 1 1 (3e-110) :xyz}
do_test printf-2.2.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 0.001
} {abc: (0.00100) :xyz}
do_test printf-2.2.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 0.001
} {abc: (1.00000e-03) :xyz}
do_test printf-2.2.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 0.001
} {abc: (0.001) :xyz}
do_test printf-2.2.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 0.001
} {abc: 5 5 (0.001) :xyz}
do_test printf-2.2.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 0.001
} {abc: 5 5 (0.00100000) :xyz}
do_test printf-2.2.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 0.001
} {abc: 5 5 (000000.001) :xyz}
do_test printf-2.2.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 0.001
} {abc: 5 5 (0.00100) :xyz}
do_test printf-2.2.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 0.001
} {abc: 5 5 (1.00000e-03) :xyz}
do_test printf-2.2.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 0.001
} {abc: 5 5 (0.001) :xyz}
do_test printf-2.2.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 1.0e-20
} {abc: (0.00000) :xyz}
do_test printf-2.2.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 1.0e-20
} {abc: (1.00000e-20) :xyz}
do_test printf-2.2.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 1.0e-20
} {abc: (1e-20) :xyz}
do_test printf-2.2.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 1.0e-20
} {abc: 5 5 (1e-20) :xyz}
do_test printf-2.2.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 1.0e-20
} {abc: 5 5 (1.00000e-20) :xyz}
do_test printf-2.2.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 1.0e-20
} {abc: 5 5 (000001e-20) :xyz}
do_test printf-2.2.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 1.0e-20
} {abc: 5 5 (0.00000) :xyz}
do_test printf-2.2.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 1.0e-20
} {abc: 5 5 (1.00000e-20) :xyz}
do_test printf-2.2.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 1.0e-20
} {abc: 5 5 (1e-20) :xyz}
do_test printf-2.2.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 1.0
} {abc: (1.00000) :xyz}
do_test printf-2.2.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 1.0
} {abc: (1.00000e+00) :xyz}
do_test printf-2.2.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 1.0
} {abc: (    1) :xyz}
do_test printf-2.2.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 1.0
} {abc: 5 5 (1) :xyz}
do_test printf-2.2.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 1.0
} {abc: 5 5 (1.00000) :xyz}
do_test printf-2.2.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 1.0
} {abc: 5 5 (0000000001) :xyz}
do_test printf-2.2.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 1.0
} {abc: 5 5 (1.00000) :xyz}
do_test printf-2.2.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 1.0
} {abc: 5 5 (1.00000e+00) :xyz}
do_test printf-2.2.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 1.0
} {abc: 5 5 (    1) :xyz}
do_test printf-2.2.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 0.0
} {abc: (0.00000) :xyz}
do_test printf-2.2.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 0.0
} {abc: (0.00000e+00) :xyz}
do_test printf-2.2.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 0.0
} {abc: (    0) :xyz}
do_test printf-2.2.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 0.0
} {abc: 5 5 (0) :xyz}
do_test printf-2.2.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 0.0
} {abc: 5 5 (0.00000) :xyz}
do_test printf-2.2.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 0.0
} {abc: 5 5 (0000000000) :xyz}
do_test printf-2.2.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 0.0
} {abc: 5 5 (0.00000) :xyz}
do_test printf-2.2.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 0.0
} {abc: 5 5 (0.00000e+00) :xyz}
do_test printf-2.2.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 0.0
} {abc: 5 5 (    0) :xyz}
do_test printf-2.2.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 100.0
} {abc: (100.00000) :xyz}
do_test printf-2.2.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 100.0
} {abc: (1.00000e+02) :xyz}
do_test printf-2.2.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 100.0
} {abc: (  100) :xyz}
do_test printf-2.2.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 100.0
} {abc: 5 5 (100) :xyz}
do_test printf-2.2.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 100.0
} {abc: 5 5 (100.000) :xyz}
do_test printf-2.2.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 100.0
} {abc: 5 5 (0000000100) :xyz}
do_test printf-2.2.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 100.0
} {abc: 5 5 (100.00000) :xyz}
do_test printf-2.2.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 100.0
} {abc: 5 5 (1.00000e+02) :xyz}
do_test printf-2.2.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 100.0
} {abc: 5 5 (  100) :xyz}
do_test printf-2.2.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 9.99999
} {abc: (9.99999) :xyz}
do_test printf-2.2.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 9.99999
} {abc: (9.99999e+00) :xyz}
do_test printf-2.2.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 9.99999
} {abc: (   10) :xyz}
do_test printf-2.2.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 9.99999
} {abc: 5 5 (9.99999) :xyz}
do_test printf-2.2.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 9.99999
} {abc: 5 5 (9.99999) :xyz}
do_test printf-2.2.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 9.99999
} {abc: 5 5 (0009.99999) :xyz}
do_test printf-2.2.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 9.99999
} {abc: 5 5 (9.99999) :xyz}
do_test printf-2.2.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 9.99999
} {abc: 5 5 (9.99999e+00) :xyz}
do_test printf-2.2.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 9.99999
} {abc: 5 5 (   10) :xyz}
do_test printf-2.2.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -0.00543
} {abc: (-0.00543) :xyz}
do_test printf-2.2.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -0.00543
} {abc: (-5.43000e-03) :xyz}
do_test printf-2.2.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -0.00543
} {abc: (-0.00543) :xyz}
do_test printf-2.2.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -0.00543
} {abc: 5 5 (-0.00543) :xyz}
do_test printf-2.2.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -0.00543
} {abc: 5 5 (-0.00543000) :xyz}
do_test printf-2.2.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -0.00543
} {abc: 5 5 (-000.00543) :xyz}
do_test printf-2.2.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -0.00543
} {abc: 5 5 (-0.00543) :xyz}
do_test printf-2.2.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -0.00543
} {abc: 5 5 (-5.43000e-03) :xyz}
do_test printf-2.2.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -0.00543
} {abc: 5 5 (-0.00543) :xyz}
do_test printf-2.2.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -1.0
} {abc: (-1.00000) :xyz}
do_test printf-2.2.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -1.0
} {abc: (-1.00000e+00) :xyz}
do_test printf-2.2.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -1.0
} {abc: (   -1) :xyz}
do_test printf-2.2.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -1.0
} {abc: 5 5 (-1) :xyz}
do_test printf-2.2.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -1.0
} {abc: 5 5 (-1.00000) :xyz}
do_test printf-2.2.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -1.0
} {abc: 5 5 (-000000001) :xyz}
do_test printf-2.2.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -1.0
} {abc: 5 5 (-1.00000) :xyz}
do_test printf-2.2.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -1.0
} {abc: 5 5 (-1.00000e+00) :xyz}
do_test printf-2.2.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -1.0
} {abc: 5 5 (   -1) :xyz}
do_test printf-2.2.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -99.99999
} {abc: (-99.99999) :xyz}
do_test printf-2.2.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -99.99999
} {abc: (-1.00000e+02) :xyz}
do_test printf-2.2.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -99.99999
} {abc: ( -100) :xyz}
do_test printf-2.2.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -99.99999
} {abc: 5 5 (-100) :xyz}
do_test printf-2.2.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -99.99999
} {abc: 5 5 (-100.000) :xyz}
do_test printf-2.2.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -99.99999
} {abc: 5 5 (-000000100) :xyz}
do_test printf-2.2.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -99.99999
} {abc: 5 5 (-99.99999) :xyz}
do_test printf-2.2.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -99.99999
} {abc: 5 5 (-1.00000e+02) :xyz}
do_test printf-2.2.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -99.99999
} {abc: 5 5 ( -100) :xyz}
do_test printf-2.2.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 3.14e+9
} {abc: (3140000000.00000) :xyz}
do_test printf-2.2.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 3.14e+9
} {abc: (3.14000e+09) :xyz}
do_test printf-2.2.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 3.14e+9
} {abc: (3.14e+09) :xyz}
do_test printf-2.2.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 3.14e+9
} {abc: 5 5 (3.14e+09) :xyz}
do_test printf-2.2.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 3.14e+9
} {abc: 5 5 (3.14000e+09) :xyz}
do_test printf-2.2.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 3.14e+9
} {abc: 5 5 (003.14e+09) :xyz}
do_test printf-2.2.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 3.14e+9
} {abc: 5 5 (3140000000.00000) :xyz}
do_test printf-2.2.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 3.14e+9
} {abc: 5 5 (3.14000e+09) :xyz}
do_test printf-2.2.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 3.14e+9
} {abc: 5 5 (3.14e+09) :xyz}
do_test printf-2.2.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -4.72732e+88
} {abc: (-4.72732e+88) :xyz}
do_test printf-2.2.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -4.72732e+88
} {abc: (-4.7273e+88) :xyz}
do_test printf-2.2.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -4.72732e+88
} {abc: 5 5 (-4.72732e+88) :xyz}
do_test printf-2.2.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -4.72732e+88
} {abc: 5 5 (-4.72732e+88) :xyz}
do_test printf-2.2.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -4.72732e+88
} {abc: 5 5 (-4.72732e+88) :xyz}
do_test printf-2.2.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -4.72732e+88
} {abc: 5 5 (-4.72732e+88) :xyz}
do_test printf-2.2.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -4.72732e+88
} {abc: 5 5 (-4.7273e+88) :xyz}
do_test printf-2.2.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 9.87991e+143
} {abc: (9.87991e+143) :xyz}
do_test printf-2.2.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 9.87991e+143
} {abc: (9.8799e+143) :xyz}
do_test printf-2.2.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 9.87991e+143
} {abc: 5 5 (9.87991e+143) :xyz}
do_test printf-2.2.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 9.87991e+143
} {abc: 5 5 (9.87991e+143) :xyz}
do_test printf-2.2.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 9.87991e+143
} {abc: 5 5 (9.87991e+143) :xyz}
do_test printf-2.2.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 9.87991e+143
} {abc: 5 5 (9.87991e+143) :xyz}
do_test printf-2.2.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 9.87991e+143
} {abc: 5 5 (9.8799e+143) :xyz}
do_test printf-2.2.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -6.287291e-9
} {abc: (-0.00000) :xyz}
do_test printf-2.2.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -6.287291e-9
} {abc: (-6.28729e-09) :xyz}
do_test printf-2.2.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -6.287291e-9
} {abc: (-6.2873e-09) :xyz}
do_test printf-2.2.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -6.287291e-9
} {abc: 5 5 (-6.28729e-09) :xyz}
do_test printf-2.2.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -6.287291e-9
} {abc: 5 5 (-6.28729e-09) :xyz}
do_test printf-2.2.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -6.287291e-9
} {abc: 5 5 (-6.28729e-09) :xyz}
do_test printf-2.2.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -6.287291e-9
} {abc: 5 5 (-0.00000) :xyz}
do_test printf-2.2.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -6.287291e-9
} {abc: 5 5 (-6.28729e-09) :xyz}
do_test printf-2.2.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -6.287291e-9
} {abc: 5 5 (-6.2873e-09) :xyz}
do_test printf-2.2.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 3.38826392e-110
} {abc: (0.00000) :xyz}
do_test printf-2.2.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 3.38826392e-110
} {abc: (3.38826e-110) :xyz}
do_test printf-2.2.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 3.38826392e-110
} {abc: (3.3883e-110) :xyz}
do_test printf-2.2.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 3.38826392e-110
} {abc: 5 5 (3.38826e-110) :xyz}
do_test printf-2.2.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 3.38826392e-110
} {abc: 5 5 (3.38826e-110) :xyz}
do_test printf-2.2.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 3.38826392e-110
} {abc: 5 5 (3.38826e-110) :xyz}
do_test printf-2.2.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 3.38826392e-110
} {abc: 5 5 (0.00000) :xyz}
do_test printf-2.2.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 3.38826392e-110
} {abc: 5 5 (3.38826e-110) :xyz}
do_test printf-2.2.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 3.38826392e-110
} {abc: 5 5 (3.3883e-110) :xyz}
do_test printf-2.3.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 0.001
} {abc: (0.0010000000) :xyz}
do_test printf-2.3.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 0.001
} {abc: (1.0000000000e-03) :xyz}
do_test printf-2.3.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 0.001
} {abc: (     0.001) :xyz}
do_test printf-2.3.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 0.001
} {abc: 10 10 (0.001) :xyz}
do_test printf-2.3.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 0.001
} {abc: 10 10 (0.00100000) :xyz}
do_test printf-2.3.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 0.001
} {abc: 10 10 (000000.001) :xyz}
do_test printf-2.3.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 0.001
} {abc: 10 10 (0.0010000000) :xyz}
do_test printf-2.3.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 0.001
} {abc: 10 10 (1.0000000000e-03) :xyz}
do_test printf-2.3.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 0.001
} {abc: 10 10 (     0.001) :xyz}
do_test printf-2.3.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 1.0e-20
} {abc: (0.0000000000) :xyz}
do_test printf-2.3.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 1.0e-20
} {abc: (1.0000000000e-20) :xyz}
do_test printf-2.3.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 1.0e-20
} {abc: (     1e-20) :xyz}
do_test printf-2.3.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 1.0e-20
} {abc: 10 10 (1e-20) :xyz}
do_test printf-2.3.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 1.0e-20
} {abc: 10 10 (1.00000e-20) :xyz}
do_test printf-2.3.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 1.0e-20
} {abc: 10 10 (000001e-20) :xyz}
do_test printf-2.3.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 1.0e-20
} {abc: 10 10 (0.0000000000) :xyz}
do_test printf-2.3.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 1.0e-20
} {abc: 10 10 (1.0000000000e-20) :xyz}
do_test printf-2.3.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 1.0e-20
} {abc: 10 10 (     1e-20) :xyz}
do_test printf-2.3.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 1.0
} {abc: (1.0000000000) :xyz}
do_test printf-2.3.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 1.0
} {abc: (1.0000000000e+00) :xyz}
do_test printf-2.3.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 1.0
} {abc: (         1) :xyz}
do_test printf-2.3.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 1.0
} {abc: 10 10 (1) :xyz}
do_test printf-2.3.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 1.0
} {abc: 10 10 (1.00000) :xyz}
do_test printf-2.3.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 1.0
} {abc: 10 10 (0000000001) :xyz}
do_test printf-2.3.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 1.0
} {abc: 10 10 (1.0000000000) :xyz}
do_test printf-2.3.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 1.0
} {abc: 10 10 (1.0000000000e+00) :xyz}
do_test printf-2.3.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 1.0
} {abc: 10 10 (         1) :xyz}
do_test printf-2.3.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 0.0
} {abc: (0.0000000000) :xyz}
do_test printf-2.3.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 0.0
} {abc: (0.0000000000e+00) :xyz}
do_test printf-2.3.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 0.0
} {abc: (         0) :xyz}
do_test printf-2.3.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 0.0
} {abc: 10 10 (0) :xyz}
do_test printf-2.3.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 0.0
} {abc: 10 10 (0.00000) :xyz}
do_test printf-2.3.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 0.0
} {abc: 10 10 (0000000000) :xyz}
do_test printf-2.3.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 0.0
} {abc: 10 10 (0.0000000000) :xyz}
do_test printf-2.3.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 0.0
} {abc: 10 10 (0.0000000000e+00) :xyz}
do_test printf-2.3.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 0.0
} {abc: 10 10 (         0) :xyz}
do_test printf-2.3.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 100.0
} {abc: (100.0000000000) :xyz}
do_test printf-2.3.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 100.0
} {abc: (1.0000000000e+02) :xyz}
do_test printf-2.3.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 100.0
} {abc: (       100) :xyz}
do_test printf-2.3.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 100.0
} {abc: 10 10 (100) :xyz}
do_test printf-2.3.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 100.0
} {abc: 10 10 (100.000) :xyz}
do_test printf-2.3.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 100.0
} {abc: 10 10 (0000000100) :xyz}
do_test printf-2.3.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 100.0
} {abc: 10 10 (100.0000000000) :xyz}
do_test printf-2.3.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 100.0
} {abc: 10 10 (1.0000000000e+02) :xyz}
do_test printf-2.3.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 100.0
} {abc: 10 10 (       100) :xyz}
do_test printf-2.3.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 9.99999
} {abc: (9.9999900000) :xyz}
do_test printf-2.3.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 9.99999
} {abc: (9.9999900000e+00) :xyz}
do_test printf-2.3.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 9.99999
} {abc: (   9.99999) :xyz}
do_test printf-2.3.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 9.99999
} {abc: 10 10 (9.99999) :xyz}
do_test printf-2.3.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 9.99999
} {abc: 10 10 (9.99999) :xyz}
do_test printf-2.3.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 9.99999
} {abc: 10 10 (0009.99999) :xyz}
do_test printf-2.3.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 9.99999
} {abc: 10 10 (9.9999900000) :xyz}
do_test printf-2.3.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 9.99999
} {abc: 10 10 (9.9999900000e+00) :xyz}
do_test printf-2.3.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 9.99999
} {abc: 10 10 (   9.99999) :xyz}
do_test printf-2.3.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -0.00543
} {abc: (-0.0054300000) :xyz}
do_test printf-2.3.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -0.00543
} {abc: (-5.4300000000e-03) :xyz}
do_test printf-2.3.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -0.00543
} {abc: (  -0.00543) :xyz}
do_test printf-2.3.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -0.00543
} {abc: 10 10 (-0.00543) :xyz}
do_test printf-2.3.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -0.00543
} {abc: 10 10 (-0.00543000) :xyz}
do_test printf-2.3.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -0.00543
} {abc: 10 10 (-000.00543) :xyz}
do_test printf-2.3.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -0.00543
} {abc: 10 10 (-0.0054300000) :xyz}
do_test printf-2.3.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -0.00543
} {abc: 10 10 (-5.4300000000e-03) :xyz}
do_test printf-2.3.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -0.00543
} {abc: 10 10 (  -0.00543) :xyz}
do_test printf-2.3.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -1.0
} {abc: (-1.0000000000) :xyz}
do_test printf-2.3.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -1.0
} {abc: (-1.0000000000e+00) :xyz}
do_test printf-2.3.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -1.0
} {abc: (        -1) :xyz}
do_test printf-2.3.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -1.0
} {abc: 10 10 (-1) :xyz}
do_test printf-2.3.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -1.0
} {abc: 10 10 (-1.00000) :xyz}
do_test printf-2.3.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -1.0
} {abc: 10 10 (-000000001) :xyz}
do_test printf-2.3.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -1.0
} {abc: 10 10 (-1.0000000000) :xyz}
do_test printf-2.3.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -1.0
} {abc: 10 10 (-1.0000000000e+00) :xyz}
do_test printf-2.3.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -1.0
} {abc: 10 10 (        -1) :xyz}
do_test printf-2.3.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -99.99999
} {abc: (-99.9999900000) :xyz}
do_test printf-2.3.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -99.99999
} {abc: (-9.9999990000e+01) :xyz}
do_test printf-2.3.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -99.99999
} {abc: ( -99.99999) :xyz}
do_test printf-2.3.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -99.99999
} {abc: 10 10 (-100) :xyz}
do_test printf-2.3.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -99.99999
} {abc: 10 10 (-100.000) :xyz}
do_test printf-2.3.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -99.99999
} {abc: 10 10 (-000000100) :xyz}
do_test printf-2.3.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -99.99999
} {abc: 10 10 (-99.9999900000) :xyz}
do_test printf-2.3.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -99.99999
} {abc: 10 10 (-9.9999990000e+01) :xyz}
do_test printf-2.3.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -99.99999
} {abc: 10 10 ( -99.99999) :xyz}
do_test printf-2.3.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 3.14e+9
} {abc: (3140000000.0000000000) :xyz}
do_test printf-2.3.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 3.14e+9
} {abc: (3.1400000000e+09) :xyz}
do_test printf-2.3.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 3.14e+9
} {abc: (3140000000) :xyz}
do_test printf-2.3.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 3.14e+9
} {abc: 10 10 (3.14e+09) :xyz}
do_test printf-2.3.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 3.14e+9
} {abc: 10 10 (3.14000e+09) :xyz}
do_test printf-2.3.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 3.14e+9
} {abc: 10 10 (003.14e+09) :xyz}
do_test printf-2.3.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 3.14e+9
} {abc: 10 10 (3140000000.0000000000) :xyz}
do_test printf-2.3.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 3.14e+9
} {abc: 10 10 (3.1400000000e+09) :xyz}
do_test printf-2.3.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 3.14e+9
} {abc: 10 10 (3140000000) :xyz}
do_test printf-2.3.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -4.72732e+88
} {abc: (-4.7273200000e+88) :xyz}
do_test printf-2.3.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -4.72732e+88
} {abc: (-4.72732e+88) :xyz}
do_test printf-2.3.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -4.72732e+88
} {abc: 10 10 (-4.72732e+88) :xyz}
do_test printf-2.3.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -4.72732e+88
} {abc: 10 10 (-4.72732e+88) :xyz}
do_test printf-2.3.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -4.72732e+88
} {abc: 10 10 (-4.72732e+88) :xyz}
do_test printf-2.3.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -4.72732e+88
} {abc: 10 10 (-4.7273200000e+88) :xyz}
do_test printf-2.3.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -4.72732e+88
} {abc: 10 10 (-4.72732e+88) :xyz}
do_test printf-2.3.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 9.87991e+143
} {abc: (9.8799100000e+143) :xyz}
do_test printf-2.3.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 9.87991e+143
} {abc: (9.87991e+143) :xyz}
do_test printf-2.3.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 9.87991e+143
} {abc: 10 10 (9.87991e+143) :xyz}
do_test printf-2.3.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 9.87991e+143
} {abc: 10 10 (9.87991e+143) :xyz}
do_test printf-2.3.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 9.87991e+143
} {abc: 10 10 (9.87991e+143) :xyz}
do_test printf-2.3.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 9.87991e+143
} {abc: 10 10 (9.8799100000e+143) :xyz}
do_test printf-2.3.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 9.87991e+143
} {abc: 10 10 (9.87991e+143) :xyz}
do_test printf-2.3.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -6.287291e-9
} {abc: (-0.0000000063) :xyz}
do_test printf-2.3.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -6.287291e-9
} {abc: (-6.2872910000e-09) :xyz}
do_test printf-2.3.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -6.287291e-9
} {abc: (-6.287291e-09) :xyz}
do_test printf-2.3.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -6.287291e-9
} {abc: 10 10 (-6.28729e-09) :xyz}
do_test printf-2.3.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -6.287291e-9
} {abc: 10 10 (-6.28729e-09) :xyz}
do_test printf-2.3.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -6.287291e-9
} {abc: 10 10 (-6.28729e-09) :xyz}
do_test printf-2.3.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -6.287291e-9
} {abc: 10 10 (-0.0000000063) :xyz}
do_test printf-2.3.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -6.287291e-9
} {abc: 10 10 (-6.2872910000e-09) :xyz}
do_test printf-2.3.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -6.287291e-9
} {abc: 10 10 (-6.287291e-09) :xyz}
do_test printf-2.3.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 3.38826392e-110
} {abc: (0.0000000000) :xyz}
do_test printf-2.3.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 3.38826392e-110
} {abc: (3.3882639200e-110) :xyz}
do_test printf-2.3.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 3.38826392e-110
} {abc: (3.38826392e-110) :xyz}
do_test printf-2.3.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 3.38826392e-110
} {abc: 10 10 (3.38826e-110) :xyz}
do_test printf-2.3.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 3.38826392e-110
} {abc: 10 10 (3.38826e-110) :xyz}
do_test printf-2.3.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 3.38826392e-110
} {abc: 10 10 (3.38826e-110) :xyz}
do_test printf-2.3.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 3.38826392e-110
} {abc: 10 10 (0.0000000000) :xyz}
do_test printf-2.3.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 3.38826392e-110
} {abc: 10 10 (3.3882639200e-110) :xyz}
do_test printf-2.3.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 3.38826392e-110
} {abc: 10 10 (3.38826392e-110) :xyz}
do_test printf-2.4.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 0.001
} {abc: (   0.00100) :xyz}
do_test printf-2.4.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 0.001
} {abc: (1.00000e-03) :xyz}
do_test printf-2.4.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 0.001
} {abc: (     0.001) :xyz}
do_test printf-2.4.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 0.001
} {abc: 10 5 (0.001) :xyz}
do_test printf-2.4.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 0.001
} {abc: 10 5 (0.00100000) :xyz}
do_test printf-2.4.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 0.001
} {abc: 10 5 (000000.001) :xyz}
do_test printf-2.4.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 0.001
} {abc: 10 5 (   0.00100) :xyz}
do_test printf-2.4.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 0.001
} {abc: 10 5 (1.00000e-03) :xyz}
do_test printf-2.4.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 0.001
} {abc: 10 5 (     0.001) :xyz}
do_test printf-2.4.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 1.0e-20
} {abc: (   0.00000) :xyz}
do_test printf-2.4.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 1.0e-20
} {abc: (1.00000e-20) :xyz}
do_test printf-2.4.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 1.0e-20
} {abc: (     1e-20) :xyz}
do_test printf-2.4.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 1.0e-20
} {abc: 10 5 (1e-20) :xyz}
do_test printf-2.4.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 1.0e-20
} {abc: 10 5 (1.00000e-20) :xyz}
do_test printf-2.4.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 1.0e-20
} {abc: 10 5 (000001e-20) :xyz}
do_test printf-2.4.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 1.0e-20
} {abc: 10 5 (   0.00000) :xyz}
do_test printf-2.4.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 1.0e-20
} {abc: 10 5 (1.00000e-20) :xyz}
do_test printf-2.4.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 1.0e-20
} {abc: 10 5 (     1e-20) :xyz}
do_test printf-2.4.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 1.0
} {abc: (   1.00000) :xyz}
do_test printf-2.4.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 1.0
} {abc: (1.00000e+00) :xyz}
do_test printf-2.4.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 1.0
} {abc: (         1) :xyz}
do_test printf-2.4.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 1.0
} {abc: 10 5 (1) :xyz}
do_test printf-2.4.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 1.0
} {abc: 10 5 (1.00000) :xyz}
do_test printf-2.4.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 1.0
} {abc: 10 5 (0000000001) :xyz}
do_test printf-2.4.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 1.0
} {abc: 10 5 (   1.00000) :xyz}
do_test printf-2.4.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 1.0
} {abc: 10 5 (1.00000e+00) :xyz}
do_test printf-2.4.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 1.0
} {abc: 10 5 (         1) :xyz}
do_test printf-2.4.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 0.0
} {abc: (   0.00000) :xyz}
do_test printf-2.4.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 0.0
} {abc: (0.00000e+00) :xyz}
do_test printf-2.4.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 0.0
} {abc: (         0) :xyz}
do_test printf-2.4.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 0.0
} {abc: 10 5 (0) :xyz}
do_test printf-2.4.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 0.0
} {abc: 10 5 (0.00000) :xyz}
do_test printf-2.4.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 0.0
} {abc: 10 5 (0000000000) :xyz}
do_test printf-2.4.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 0.0
} {abc: 10 5 (   0.00000) :xyz}
do_test printf-2.4.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 0.0
} {abc: 10 5 (0.00000e+00) :xyz}
do_test printf-2.4.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 0.0
} {abc: 10 5 (         0) :xyz}
do_test printf-2.4.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 100.0
} {abc: ( 100.00000) :xyz}
do_test printf-2.4.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 100.0
} {abc: (1.00000e+02) :xyz}
do_test printf-2.4.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 100.0
} {abc: (       100) :xyz}
do_test printf-2.4.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 100.0
} {abc: 10 5 (100) :xyz}
do_test printf-2.4.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 100.0
} {abc: 10 5 (100.000) :xyz}
do_test printf-2.4.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 100.0
} {abc: 10 5 (0000000100) :xyz}
do_test printf-2.4.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 100.0
} {abc: 10 5 ( 100.00000) :xyz}
do_test printf-2.4.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 100.0
} {abc: 10 5 (1.00000e+02) :xyz}
do_test printf-2.4.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 100.0
} {abc: 10 5 (       100) :xyz}
do_test printf-2.4.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 9.99999
} {abc: (   9.99999) :xyz}
do_test printf-2.4.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 9.99999
} {abc: (9.99999e+00) :xyz}
do_test printf-2.4.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 9.99999
} {abc: (        10) :xyz}
do_test printf-2.4.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 9.99999
} {abc: 10 5 (9.99999) :xyz}
do_test printf-2.4.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 9.99999
} {abc: 10 5 (9.99999) :xyz}
do_test printf-2.4.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 9.99999
} {abc: 10 5 (0009.99999) :xyz}
do_test printf-2.4.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 9.99999
} {abc: 10 5 (   9.99999) :xyz}
do_test printf-2.4.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 9.99999
} {abc: 10 5 (9.99999e+00) :xyz}
do_test printf-2.4.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 9.99999
} {abc: 10 5 (        10) :xyz}
do_test printf-2.4.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -0.00543
} {abc: (  -0.00543) :xyz}
do_test printf-2.4.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -0.00543
} {abc: (-5.43000e-03) :xyz}
do_test printf-2.4.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -0.00543
} {abc: (  -0.00543) :xyz}
do_test printf-2.4.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -0.00543
} {abc: 10 5 (-0.00543) :xyz}
do_test printf-2.4.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -0.00543
} {abc: 10 5 (-0.00543000) :xyz}
do_test printf-2.4.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -0.00543
} {abc: 10 5 (-000.00543) :xyz}
do_test printf-2.4.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -0.00543
} {abc: 10 5 (  -0.00543) :xyz}
do_test printf-2.4.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -0.00543
} {abc: 10 5 (-5.43000e-03) :xyz}
do_test printf-2.4.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -0.00543
} {abc: 10 5 (  -0.00543) :xyz}
do_test printf-2.4.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -1.0
} {abc: (  -1.00000) :xyz}
do_test printf-2.4.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -1.0
} {abc: (-1.00000e+00) :xyz}
do_test printf-2.4.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -1.0
} {abc: (        -1) :xyz}
do_test printf-2.4.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -1.0
} {abc: 10 5 (-1) :xyz}
do_test printf-2.4.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -1.0
} {abc: 10 5 (-1.00000) :xyz}
do_test printf-2.4.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -1.0
} {abc: 10 5 (-000000001) :xyz}
do_test printf-2.4.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -1.0
} {abc: 10 5 (  -1.00000) :xyz}
do_test printf-2.4.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -1.0
} {abc: 10 5 (-1.00000e+00) :xyz}
do_test printf-2.4.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -1.0
} {abc: 10 5 (        -1) :xyz}
do_test printf-2.4.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -99.99999
} {abc: ( -99.99999) :xyz}
do_test printf-2.4.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -99.99999
} {abc: (-1.00000e+02) :xyz}
do_test printf-2.4.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -99.99999
} {abc: (      -100) :xyz}
do_test printf-2.4.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -99.99999
} {abc: 10 5 (-100) :xyz}
do_test printf-2.4.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -99.99999
} {abc: 10 5 (-100.000) :xyz}
do_test printf-2.4.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -99.99999
} {abc: 10 5 (-000000100) :xyz}
do_test printf-2.4.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -99.99999
} {abc: 10 5 ( -99.99999) :xyz}
do_test printf-2.4.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -99.99999
} {abc: 10 5 (-1.00000e+02) :xyz}
do_test printf-2.4.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -99.99999
} {abc: 10 5 (      -100) :xyz}
do_test printf-2.4.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 3.14e+9
} {abc: (3140000000.00000) :xyz}
do_test printf-2.4.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 3.14e+9
} {abc: (3.14000e+09) :xyz}
do_test printf-2.4.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 3.14e+9
} {abc: (  3.14e+09) :xyz}
do_test printf-2.4.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 3.14e+9
} {abc: 10 5 (3.14e+09) :xyz}
do_test printf-2.4.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 3.14e+9
} {abc: 10 5 (3.14000e+09) :xyz}
do_test printf-2.4.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 3.14e+9
} {abc: 10 5 (003.14e+09) :xyz}
do_test printf-2.4.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 3.14e+9
} {abc: 10 5 (3140000000.00000) :xyz}
do_test printf-2.4.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 3.14e+9
} {abc: 10 5 (3.14000e+09) :xyz}
do_test printf-2.4.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 3.14e+9
} {abc: 10 5 (  3.14e+09) :xyz}
do_test printf-2.4.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -4.72732e+88
} {abc: (-4.72732e+88) :xyz}
do_test printf-2.4.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -4.72732e+88
} {abc: (-4.7273e+88) :xyz}
do_test printf-2.4.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -4.72732e+88
} {abc: 10 5 (-4.72732e+88) :xyz}
do_test printf-2.4.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -4.72732e+88
} {abc: 10 5 (-4.72732e+88) :xyz}
do_test printf-2.4.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -4.72732e+88
} {abc: 10 5 (-4.72732e+88) :xyz}
do_test printf-2.4.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -4.72732e+88
} {abc: 10 5 (-4.72732e+88) :xyz}
do_test printf-2.4.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -4.72732e+88
} {abc: 10 5 (-4.7273e+88) :xyz}
do_test printf-2.4.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 9.87991e+143
} {abc: (9.87991e+143) :xyz}
do_test printf-2.4.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 9.87991e+143
} {abc: (9.8799e+143) :xyz}
do_test printf-2.4.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 9.87991e+143
} {abc: 10 5 (9.87991e+143) :xyz}
do_test printf-2.4.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 9.87991e+143
} {abc: 10 5 (9.87991e+143) :xyz}
do_test printf-2.4.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 9.87991e+143
} {abc: 10 5 (9.87991e+143) :xyz}
do_test printf-2.4.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 9.87991e+143
} {abc: 10 5 (9.87991e+143) :xyz}
do_test printf-2.4.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 9.87991e+143
} {abc: 10 5 (9.8799e+143) :xyz}
do_test printf-2.4.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -6.287291e-9
} {abc: (  -0.00000) :xyz}
do_test printf-2.4.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -6.287291e-9
} {abc: (-6.28729e-09) :xyz}
do_test printf-2.4.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -6.287291e-9
} {abc: (-6.2873e-09) :xyz}
do_test printf-2.4.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -6.287291e-9
} {abc: 10 5 (-6.28729e-09) :xyz}
do_test printf-2.4.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -6.287291e-9
} {abc: 10 5 (-6.28729e-09) :xyz}
do_test printf-2.4.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -6.287291e-9
} {abc: 10 5 (-6.28729e-09) :xyz}
do_test printf-2.4.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -6.287291e-9
} {abc: 10 5 (  -0.00000) :xyz}
do_test printf-2.4.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -6.287291e-9
} {abc: 10 5 (-6.28729e-09) :xyz}
do_test printf-2.4.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -6.287291e-9
} {abc: 10 5 (-6.2873e-09) :xyz}
do_test printf-2.4.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 3.38826392e-110
} {abc: (   0.00000) :xyz}
do_test printf-2.4.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 3.38826392e-110
} {abc: (3.38826e-110) :xyz}
do_test printf-2.4.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 3.38826392e-110
} {abc: (3.3883e-110) :xyz}
do_test printf-2.4.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 3.38826392e-110
} {abc: 10 5 (3.38826e-110) :xyz}
do_test printf-2.4.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 3.38826392e-110
} {abc: 10 5 (3.38826e-110) :xyz}
do_test printf-2.4.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 3.38826392e-110
} {abc: 10 5 (3.38826e-110) :xyz}
do_test printf-2.4.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 3.38826392e-110
} {abc: 10 5 (   0.00000) :xyz}
do_test printf-2.4.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 3.38826392e-110
} {abc: 10 5 (3.38826e-110) :xyz}
do_test printf-2.4.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 3.38826392e-110
} {abc: 10 5 (3.3883e-110) :xyz}
do_test printf-2.5.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 0.001
} {abc: (0.00) :xyz}
do_test printf-2.5.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 0.001
} {abc: (1.00e-03) :xyz}
do_test printf-2.5.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 0.001
} {abc: (0.001) :xyz}
do_test printf-2.5.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 0.001
} {abc: 2 2 (0.001) :xyz}
do_test printf-2.5.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 0.001
} {abc: 2 2 (0.00100000) :xyz}
do_test printf-2.5.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 0.001
} {abc: 2 2 (000000.001) :xyz}
do_test printf-2.5.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 0.001
} {abc: 2 2 (0.00) :xyz}
do_test printf-2.5.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 0.001
} {abc: 2 2 (1.00e-03) :xyz}
do_test printf-2.5.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 0.001
} {abc: 2 2 (0.001) :xyz}
do_test printf-2.5.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 1.0e-20
} {abc: (0.00) :xyz}
do_test printf-2.5.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 1.0e-20
} {abc: (1.00e-20) :xyz}
do_test printf-2.5.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 1.0e-20
} {abc: (1e-20) :xyz}
do_test printf-2.5.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 1.0e-20
} {abc: 2 2 (1e-20) :xyz}
do_test printf-2.5.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 1.0e-20
} {abc: 2 2 (1.00000e-20) :xyz}
do_test printf-2.5.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 1.0e-20
} {abc: 2 2 (000001e-20) :xyz}
do_test printf-2.5.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 1.0e-20
} {abc: 2 2 (0.00) :xyz}
do_test printf-2.5.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 1.0e-20
} {abc: 2 2 (1.00e-20) :xyz}
do_test printf-2.5.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 1.0e-20
} {abc: 2 2 (1e-20) :xyz}
do_test printf-2.5.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 1.0
} {abc: (1.00) :xyz}
do_test printf-2.5.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 1.0
} {abc: (1.00e+00) :xyz}
do_test printf-2.5.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 1.0
} {abc: ( 1) :xyz}
do_test printf-2.5.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 1.0
} {abc: 2 2 (1) :xyz}
do_test printf-2.5.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 1.0
} {abc: 2 2 (1.00000) :xyz}
do_test printf-2.5.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 1.0
} {abc: 2 2 (0000000001) :xyz}
do_test printf-2.5.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 1.0
} {abc: 2 2 (1.00) :xyz}
do_test printf-2.5.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 1.0
} {abc: 2 2 (1.00e+00) :xyz}
do_test printf-2.5.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 1.0
} {abc: 2 2 ( 1) :xyz}
do_test printf-2.5.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 0.0
} {abc: (0.00) :xyz}
do_test printf-2.5.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 0.0
} {abc: (0.00e+00) :xyz}
do_test printf-2.5.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 0.0
} {abc: ( 0) :xyz}
do_test printf-2.5.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 0.0
} {abc: 2 2 (0) :xyz}
do_test printf-2.5.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 0.0
} {abc: 2 2 (0.00000) :xyz}
do_test printf-2.5.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 0.0
} {abc: 2 2 (0000000000) :xyz}
do_test printf-2.5.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 0.0
} {abc: 2 2 (0.00) :xyz}
do_test printf-2.5.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 0.0
} {abc: 2 2 (0.00e+00) :xyz}
do_test printf-2.5.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 0.0
} {abc: 2 2 ( 0) :xyz}
do_test printf-2.5.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 100.0
} {abc: (100.00) :xyz}
do_test printf-2.5.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 100.0
} {abc: (1.00e+02) :xyz}
do_test printf-2.5.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 100.0
} {abc: (1e+02) :xyz}
do_test printf-2.5.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 100.0
} {abc: 2 2 (100) :xyz}
do_test printf-2.5.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 100.0
} {abc: 2 2 (100.000) :xyz}
do_test printf-2.5.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 100.0
} {abc: 2 2 (0000000100) :xyz}
do_test printf-2.5.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 100.0
} {abc: 2 2 (100.00) :xyz}
do_test printf-2.5.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 100.0
} {abc: 2 2 (1.00e+02) :xyz}
do_test printf-2.5.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 100.0
} {abc: 2 2 (1e+02) :xyz}
do_test printf-2.5.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 9.99999
} {abc: (10.00) :xyz}
do_test printf-2.5.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 9.99999
} {abc: (1.00e+01) :xyz}
do_test printf-2.5.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 9.99999
} {abc: (10) :xyz}
do_test printf-2.5.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 9.99999
} {abc: 2 2 (9.99999) :xyz}
do_test printf-2.5.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 9.99999
} {abc: 2 2 (9.99999) :xyz}
do_test printf-2.5.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 9.99999
} {abc: 2 2 (0009.99999) :xyz}
do_test printf-2.5.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 9.99999
} {abc: 2 2 (10.00) :xyz}
do_test printf-2.5.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 9.99999
} {abc: 2 2 (1.00e+01) :xyz}
do_test printf-2.5.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 9.99999
} {abc: 2 2 (10) :xyz}
do_test printf-2.5.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -0.00543
} {abc: (-0.01) :xyz}
do_test printf-2.5.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -0.00543
} {abc: (-5.43e-03) :xyz}
do_test printf-2.5.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -0.00543
} {abc: (-0.0054) :xyz}
do_test printf-2.5.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -0.00543
} {abc: 2 2 (-0.00543) :xyz}
do_test printf-2.5.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -0.00543
} {abc: 2 2 (-0.00543000) :xyz}
do_test printf-2.5.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -0.00543
} {abc: 2 2 (-000.00543) :xyz}
do_test printf-2.5.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -0.00543
} {abc: 2 2 (-0.01) :xyz}
do_test printf-2.5.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -0.00543
} {abc: 2 2 (-5.43e-03) :xyz}
do_test printf-2.5.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -0.00543
} {abc: 2 2 (-0.0054) :xyz}
do_test printf-2.5.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -1.0
} {abc: (-1.00) :xyz}
do_test printf-2.5.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -1.0
} {abc: (-1.00e+00) :xyz}
do_test printf-2.5.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -1.0
} {abc: (-1) :xyz}
do_test printf-2.5.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -1.0
} {abc: 2 2 (-1) :xyz}
do_test printf-2.5.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -1.0
} {abc: 2 2 (-1.00000) :xyz}
do_test printf-2.5.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -1.0
} {abc: 2 2 (-000000001) :xyz}
do_test printf-2.5.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -1.0
} {abc: 2 2 (-1.00) :xyz}
do_test printf-2.5.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -1.0
} {abc: 2 2 (-1.00e+00) :xyz}
do_test printf-2.5.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -1.0
} {abc: 2 2 (-1) :xyz}
do_test printf-2.5.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -99.99999
} {abc: (-100.00) :xyz}
do_test printf-2.5.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -99.99999
} {abc: (-1.00e+02) :xyz}
do_test printf-2.5.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -99.99999
} {abc: (-1e+02) :xyz}
do_test printf-2.5.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -99.99999
} {abc: 2 2 (-100) :xyz}
do_test printf-2.5.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -99.99999
} {abc: 2 2 (-100.000) :xyz}
do_test printf-2.5.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -99.99999
} {abc: 2 2 (-000000100) :xyz}
do_test printf-2.5.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -99.99999
} {abc: 2 2 (-100.00) :xyz}
do_test printf-2.5.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -99.99999
} {abc: 2 2 (-1.00e+02) :xyz}
do_test printf-2.5.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -99.99999
} {abc: 2 2 (-1e+02) :xyz}
do_test printf-2.5.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 3.14e+9
} {abc: (3140000000.00) :xyz}
do_test printf-2.5.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 3.14e+9
} {abc: (3.14e+09) :xyz}
do_test printf-2.5.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 3.14e+9
} {abc: (3.1e+09) :xyz}
do_test printf-2.5.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 3.14e+9
} {abc: 2 2 (3.14e+09) :xyz}
do_test printf-2.5.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 3.14e+9
} {abc: 2 2 (3.14000e+09) :xyz}
do_test printf-2.5.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 3.14e+9
} {abc: 2 2 (003.14e+09) :xyz}
do_test printf-2.5.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 3.14e+9
} {abc: 2 2 (3140000000.00) :xyz}
do_test printf-2.5.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 3.14e+9
} {abc: 2 2 (3.14e+09) :xyz}
do_test printf-2.5.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 3.14e+9
} {abc: 2 2 (3.1e+09) :xyz}
do_test printf-2.5.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -4.72732e+88
} {abc: (-4.73e+88) :xyz}
do_test printf-2.5.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -4.72732e+88
} {abc: (-4.7e+88) :xyz}
do_test printf-2.5.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -4.72732e+88
} {abc: 2 2 (-4.72732e+88) :xyz}
do_test printf-2.5.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -4.72732e+88
} {abc: 2 2 (-4.72732e+88) :xyz}
do_test printf-2.5.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -4.72732e+88
} {abc: 2 2 (-4.72732e+88) :xyz}
do_test printf-2.5.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -4.72732e+88
} {abc: 2 2 (-4.73e+88) :xyz}
do_test printf-2.5.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -4.72732e+88
} {abc: 2 2 (-4.7e+88) :xyz}
do_test printf-2.5.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 9.87991e+143
} {abc: (9.88e+143) :xyz}
do_test printf-2.5.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 9.87991e+143
} {abc: (9.9e+143) :xyz}
do_test printf-2.5.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 9.87991e+143
} {abc: 2 2 (9.87991e+143) :xyz}
do_test printf-2.5.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 9.87991e+143
} {abc: 2 2 (9.87991e+143) :xyz}
do_test printf-2.5.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 9.87991e+143
} {abc: 2 2 (9.87991e+143) :xyz}
do_test printf-2.5.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 9.87991e+143
} {abc: 2 2 (9.88e+143) :xyz}
do_test printf-2.5.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 9.87991e+143
} {abc: 2 2 (9.9e+143) :xyz}
do_test printf-2.5.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -6.287291e-9
} {abc: (-0.00) :xyz}
do_test printf-2.5.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -6.287291e-9
} {abc: (-6.29e-09) :xyz}
do_test printf-2.5.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -6.287291e-9
} {abc: (-6.3e-09) :xyz}
do_test printf-2.5.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -6.287291e-9
} {abc: 2 2 (-6.28729e-09) :xyz}
do_test printf-2.5.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -6.287291e-9
} {abc: 2 2 (-6.28729e-09) :xyz}
do_test printf-2.5.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -6.287291e-9
} {abc: 2 2 (-6.28729e-09) :xyz}
do_test printf-2.5.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -6.287291e-9
} {abc: 2 2 (-0.00) :xyz}
do_test printf-2.5.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -6.287291e-9
} {abc: 2 2 (-6.29e-09) :xyz}
do_test printf-2.5.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -6.287291e-9
} {abc: 2 2 (-6.3e-09) :xyz}
do_test printf-2.5.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 3.38826392e-110
} {abc: (0.00) :xyz}
do_test printf-2.5.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 3.38826392e-110
} {abc: (3.39e-110) :xyz}
do_test printf-2.5.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 3.38826392e-110
} {abc: (3.4e-110) :xyz}
do_test printf-2.5.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 3.38826392e-110
} {abc: 2 2 (3.38826e-110) :xyz}
do_test printf-2.5.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 3.38826392e-110
} {abc: 2 2 (3.38826e-110) :xyz}
do_test printf-2.5.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 3.38826392e-110
} {abc: 2 2 (3.38826e-110) :xyz}
do_test printf-2.5.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 3.38826392e-110
} {abc: 2 2 (0.00) :xyz}
do_test printf-2.5.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 3.38826392e-110
} {abc: 2 2 (3.39e-110) :xyz}
do_test printf-2.5.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 3.38826392e-110
} {abc: 2 2 (3.4e-110) :xyz}
do_test printf-2.6.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 0.001
} {abc: (0.001) :xyz}
do_test printf-2.6.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 0.001
} {abc: (1.000e-03) :xyz}
do_test printf-2.6.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 0.001
} {abc: (0.001) :xyz}
do_test printf-2.6.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 0.001
} {abc: 2 3 (0.001) :xyz}
do_test printf-2.6.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 0.001
} {abc: 2 3 (0.00100000) :xyz}
do_test printf-2.6.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 0.001
} {abc: 2 3 (000000.001) :xyz}
do_test printf-2.6.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 0.001
} {abc: 2 3 (0.001) :xyz}
do_test printf-2.6.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 0.001
} {abc: 2 3 (1.000e-03) :xyz}
do_test printf-2.6.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 0.001
} {abc: 2 3 (0.001) :xyz}
do_test printf-2.6.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 1.0e-20
} {abc: (0.000) :xyz}
do_test printf-2.6.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 1.0e-20
} {abc: (1.000e-20) :xyz}
do_test printf-2.6.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 1.0e-20
} {abc: (1e-20) :xyz}
do_test printf-2.6.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 1.0e-20
} {abc: 2 3 (1e-20) :xyz}
do_test printf-2.6.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 1.0e-20
} {abc: 2 3 (1.00000e-20) :xyz}
do_test printf-2.6.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 1.0e-20
} {abc: 2 3 (000001e-20) :xyz}
do_test printf-2.6.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 1.0e-20
} {abc: 2 3 (0.000) :xyz}
do_test printf-2.6.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 1.0e-20
} {abc: 2 3 (1.000e-20) :xyz}
do_test printf-2.6.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 1.0e-20
} {abc: 2 3 (1e-20) :xyz}
do_test printf-2.6.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 1.0
} {abc: (1.000) :xyz}
do_test printf-2.6.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 1.0
} {abc: (1.000e+00) :xyz}
do_test printf-2.6.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 1.0
} {abc: ( 1) :xyz}
do_test printf-2.6.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 1.0
} {abc: 2 3 (1) :xyz}
do_test printf-2.6.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 1.0
} {abc: 2 3 (1.00000) :xyz}
do_test printf-2.6.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 1.0
} {abc: 2 3 (0000000001) :xyz}
do_test printf-2.6.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 1.0
} {abc: 2 3 (1.000) :xyz}
do_test printf-2.6.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 1.0
} {abc: 2 3 (1.000e+00) :xyz}
do_test printf-2.6.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 1.0
} {abc: 2 3 ( 1) :xyz}
do_test printf-2.6.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 0.0
} {abc: (0.000) :xyz}
do_test printf-2.6.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 0.0
} {abc: (0.000e+00) :xyz}
do_test printf-2.6.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 0.0
} {abc: ( 0) :xyz}
do_test printf-2.6.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 0.0
} {abc: 2 3 (0) :xyz}
do_test printf-2.6.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 0.0
} {abc: 2 3 (0.00000) :xyz}
do_test printf-2.6.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 0.0
} {abc: 2 3 (0000000000) :xyz}
do_test printf-2.6.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 0.0
} {abc: 2 3 (0.000) :xyz}
do_test printf-2.6.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 0.0
} {abc: 2 3 (0.000e+00) :xyz}
do_test printf-2.6.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 0.0
} {abc: 2 3 ( 0) :xyz}
do_test printf-2.6.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 100.0
} {abc: (100.000) :xyz}
do_test printf-2.6.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 100.0
} {abc: (1.000e+02) :xyz}
do_test printf-2.6.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 100.0
} {abc: (100) :xyz}
do_test printf-2.6.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 100.0
} {abc: 2 3 (100) :xyz}
do_test printf-2.6.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 100.0
} {abc: 2 3 (100.000) :xyz}
do_test printf-2.6.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 100.0
} {abc: 2 3 (0000000100) :xyz}
do_test printf-2.6.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 100.0
} {abc: 2 3 (100.000) :xyz}
do_test printf-2.6.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 100.0
} {abc: 2 3 (1.000e+02) :xyz}
do_test printf-2.6.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 100.0
} {abc: 2 3 (100) :xyz}
do_test printf-2.6.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 9.99999
} {abc: (10.000) :xyz}
do_test printf-2.6.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 9.99999
} {abc: (1.000e+01) :xyz}
do_test printf-2.6.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 9.99999
} {abc: (10) :xyz}
do_test printf-2.6.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 9.99999
} {abc: 2 3 (9.99999) :xyz}
do_test printf-2.6.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 9.99999
} {abc: 2 3 (9.99999) :xyz}
do_test printf-2.6.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 9.99999
} {abc: 2 3 (0009.99999) :xyz}
do_test printf-2.6.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 9.99999
} {abc: 2 3 (10.000) :xyz}
do_test printf-2.6.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 9.99999
} {abc: 2 3 (1.000e+01) :xyz}
do_test printf-2.6.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 9.99999
} {abc: 2 3 (10) :xyz}
do_test printf-2.6.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -0.00543
} {abc: (-0.005) :xyz}
do_test printf-2.6.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -0.00543
} {abc: (-5.430e-03) :xyz}
do_test printf-2.6.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -0.00543
} {abc: (-0.00543) :xyz}
do_test printf-2.6.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -0.00543
} {abc: 2 3 (-0.00543) :xyz}
do_test printf-2.6.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -0.00543
} {abc: 2 3 (-0.00543000) :xyz}
do_test printf-2.6.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -0.00543
} {abc: 2 3 (-000.00543) :xyz}
do_test printf-2.6.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -0.00543
} {abc: 2 3 (-0.005) :xyz}
do_test printf-2.6.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -0.00543
} {abc: 2 3 (-5.430e-03) :xyz}
do_test printf-2.6.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -0.00543
} {abc: 2 3 (-0.00543) :xyz}
do_test printf-2.6.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -1.0
} {abc: (-1.000) :xyz}
do_test printf-2.6.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -1.0
} {abc: (-1.000e+00) :xyz}
do_test printf-2.6.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -1.0
} {abc: (-1) :xyz}
do_test printf-2.6.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -1.0
} {abc: 2 3 (-1) :xyz}
do_test printf-2.6.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -1.0
} {abc: 2 3 (-1.00000) :xyz}
do_test printf-2.6.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -1.0
} {abc: 2 3 (-000000001) :xyz}
do_test printf-2.6.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -1.0
} {abc: 2 3 (-1.000) :xyz}
do_test printf-2.6.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -1.0
} {abc: 2 3 (-1.000e+00) :xyz}
do_test printf-2.6.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -1.0
} {abc: 2 3 (-1) :xyz}
do_test printf-2.6.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -99.99999
} {abc: (-100.000) :xyz}
do_test printf-2.6.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -99.99999
} {abc: (-1.000e+02) :xyz}
do_test printf-2.6.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -99.99999
} {abc: (-100) :xyz}
do_test printf-2.6.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -99.99999
} {abc: 2 3 (-100) :xyz}
do_test printf-2.6.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -99.99999
} {abc: 2 3 (-100.000) :xyz}
do_test printf-2.6.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -99.99999
} {abc: 2 3 (-000000100) :xyz}
do_test printf-2.6.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -99.99999
} {abc: 2 3 (-100.000) :xyz}
do_test printf-2.6.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -99.99999
} {abc: 2 3 (-1.000e+02) :xyz}
do_test printf-2.6.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -99.99999
} {abc: 2 3 (-100) :xyz}
do_test printf-2.6.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 3.14e+9
} {abc: (3140000000.000) :xyz}
do_test printf-2.6.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 3.14e+9
} {abc: (3.140e+09) :xyz}
do_test printf-2.6.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 3.14e+9
} {abc: (3.14e+09) :xyz}
do_test printf-2.6.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 3.14e+9
} {abc: 2 3 (3.14e+09) :xyz}
do_test printf-2.6.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 3.14e+9
} {abc: 2 3 (3.14000e+09) :xyz}
do_test printf-2.6.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 3.14e+9
} {abc: 2 3 (003.14e+09) :xyz}
do_test printf-2.6.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 3.14e+9
} {abc: 2 3 (3140000000.000) :xyz}
do_test printf-2.6.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 3.14e+9
} {abc: 2 3 (3.140e+09) :xyz}
do_test printf-2.6.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 3.14e+9
} {abc: 2 3 (3.14e+09) :xyz}
do_test printf-2.6.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -4.72732e+88
} {abc: (-4.727e+88) :xyz}
do_test printf-2.6.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -4.72732e+88
} {abc: (-4.73e+88) :xyz}
do_test printf-2.6.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -4.72732e+88
} {abc: 2 3 (-4.72732e+88) :xyz}
do_test printf-2.6.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -4.72732e+88
} {abc: 2 3 (-4.72732e+88) :xyz}
do_test printf-2.6.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -4.72732e+88
} {abc: 2 3 (-4.72732e+88) :xyz}
do_test printf-2.6.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -4.72732e+88
} {abc: 2 3 (-4.727e+88) :xyz}
do_test printf-2.6.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -4.72732e+88
} {abc: 2 3 (-4.73e+88) :xyz}
do_test printf-2.6.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 9.87991e+143
} {abc: (9.880e+143) :xyz}
do_test printf-2.6.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 9.87991e+143
} {abc: (9.88e+143) :xyz}
do_test printf-2.6.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 9.87991e+143
} {abc: 2 3 (9.87991e+143) :xyz}
do_test printf-2.6.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 9.87991e+143
} {abc: 2 3 (9.87991e+143) :xyz}
do_test printf-2.6.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 9.87991e+143
} {abc: 2 3 (9.87991e+143) :xyz}
do_test printf-2.6.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 9.87991e+143
} {abc: 2 3 (9.880e+143) :xyz}
do_test printf-2.6.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 9.87991e+143
} {abc: 2 3 (9.88e+143) :xyz}
do_test printf-2.6.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -6.287291e-9
} {abc: (-0.000) :xyz}
do_test printf-2.6.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -6.287291e-9
} {abc: (-6.287e-09) :xyz}
do_test printf-2.6.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -6.287291e-9
} {abc: (-6.29e-09) :xyz}
do_test printf-2.6.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -6.287291e-9
} {abc: 2 3 (-6.28729e-09) :xyz}
do_test printf-2.6.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -6.287291e-9
} {abc: 2 3 (-6.28729e-09) :xyz}
do_test printf-2.6.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -6.287291e-9
} {abc: 2 3 (-6.28729e-09) :xyz}
do_test printf-2.6.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -6.287291e-9
} {abc: 2 3 (-0.000) :xyz}
do_test printf-2.6.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -6.287291e-9
} {abc: 2 3 (-6.287e-09) :xyz}
do_test printf-2.6.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -6.287291e-9
} {abc: 2 3 (-6.29e-09) :xyz}
do_test printf-2.6.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 3.38826392e-110
} {abc: (0.000) :xyz}
do_test printf-2.6.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 3.38826392e-110
} {abc: (3.388e-110) :xyz}
do_test printf-2.6.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 3.38826392e-110
} {abc: (3.39e-110) :xyz}
do_test printf-2.6.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 3.38826392e-110
} {abc: 2 3 (3.38826e-110) :xyz}
do_test printf-2.6.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 3.38826392e-110
} {abc: 2 3 (3.38826e-110) :xyz}
do_test printf-2.6.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 3.38826392e-110
} {abc: 2 3 (3.38826e-110) :xyz}
do_test printf-2.6.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 3.38826392e-110
} {abc: 2 3 (0.000) :xyz}
do_test printf-2.6.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 3.38826392e-110
} {abc: 2 3 (3.388e-110) :xyz}
do_test printf-2.6.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 3.38826392e-110
} {abc: 2 3 (3.39e-110) :xyz}
do_test printf-2.7.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 0.001
} {abc: (0.001) :xyz}
do_test printf-2.7.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 0.001
} {abc: (1.000e-03) :xyz}
do_test printf-2.7.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 0.001
} {abc: (0.001) :xyz}
do_test printf-2.7.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 0.001
} {abc: 3 3 (0.001) :xyz}
do_test printf-2.7.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 0.001
} {abc: 3 3 (0.00100000) :xyz}
do_test printf-2.7.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 0.001
} {abc: 3 3 (000000.001) :xyz}
do_test printf-2.7.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 0.001
} {abc: 3 3 (0.001) :xyz}
do_test printf-2.7.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 0.001
} {abc: 3 3 (1.000e-03) :xyz}
do_test printf-2.7.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 0.001
} {abc: 3 3 (0.001) :xyz}
do_test printf-2.7.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 1.0e-20
} {abc: (0.000) :xyz}
do_test printf-2.7.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 1.0e-20
} {abc: (1.000e-20) :xyz}
do_test printf-2.7.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 1.0e-20
} {abc: (1e-20) :xyz}
do_test printf-2.7.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 1.0e-20
} {abc: 3 3 (1e-20) :xyz}
do_test printf-2.7.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 1.0e-20
} {abc: 3 3 (1.00000e-20) :xyz}
do_test printf-2.7.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 1.0e-20
} {abc: 3 3 (000001e-20) :xyz}
do_test printf-2.7.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 1.0e-20
} {abc: 3 3 (0.000) :xyz}
do_test printf-2.7.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 1.0e-20
} {abc: 3 3 (1.000e-20) :xyz}
do_test printf-2.7.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 1.0e-20
} {abc: 3 3 (1e-20) :xyz}
do_test printf-2.7.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 1.0
} {abc: (1.000) :xyz}
do_test printf-2.7.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 1.0
} {abc: (1.000e+00) :xyz}
do_test printf-2.7.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 1.0
} {abc: (  1) :xyz}
do_test printf-2.7.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 1.0
} {abc: 3 3 (1) :xyz}
do_test printf-2.7.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 1.0
} {abc: 3 3 (1.00000) :xyz}
do_test printf-2.7.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 1.0
} {abc: 3 3 (0000000001) :xyz}
do_test printf-2.7.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 1.0
} {abc: 3 3 (1.000) :xyz}
do_test printf-2.7.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 1.0
} {abc: 3 3 (1.000e+00) :xyz}
do_test printf-2.7.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 1.0
} {abc: 3 3 (  1) :xyz}
do_test printf-2.7.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 0.0
} {abc: (0.000) :xyz}
do_test printf-2.7.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 0.0
} {abc: (0.000e+00) :xyz}
do_test printf-2.7.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 0.0
} {abc: (  0) :xyz}
do_test printf-2.7.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 0.0
} {abc: 3 3 (0) :xyz}
do_test printf-2.7.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 0.0
} {abc: 3 3 (0.00000) :xyz}
do_test printf-2.7.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 0.0
} {abc: 3 3 (0000000000) :xyz}
do_test printf-2.7.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 0.0
} {abc: 3 3 (0.000) :xyz}
do_test printf-2.7.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 0.0
} {abc: 3 3 (0.000e+00) :xyz}
do_test printf-2.7.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 0.0
} {abc: 3 3 (  0) :xyz}
do_test printf-2.7.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 100.0
} {abc: (100.000) :xyz}
do_test printf-2.7.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 100.0
} {abc: (1.000e+02) :xyz}
do_test printf-2.7.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 100.0
} {abc: (100) :xyz}
do_test printf-2.7.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 100.0
} {abc: 3 3 (100) :xyz}
do_test printf-2.7.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 100.0
} {abc: 3 3 (100.000) :xyz}
do_test printf-2.7.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 100.0
} {abc: 3 3 (0000000100) :xyz}
do_test printf-2.7.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 100.0
} {abc: 3 3 (100.000) :xyz}
do_test printf-2.7.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 100.0
} {abc: 3 3 (1.000e+02) :xyz}
do_test printf-2.7.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 100.0
} {abc: 3 3 (100) :xyz}
do_test printf-2.7.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 9.99999
} {abc: (10.000) :xyz}
do_test printf-2.7.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 9.99999
} {abc: (1.000e+01) :xyz}
do_test printf-2.7.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 9.99999
} {abc: ( 10) :xyz}
do_test printf-2.7.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 9.99999
} {abc: 3 3 (9.99999) :xyz}
do_test printf-2.7.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 9.99999
} {abc: 3 3 (9.99999) :xyz}
do_test printf-2.7.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 9.99999
} {abc: 3 3 (0009.99999) :xyz}
do_test printf-2.7.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 9.99999
} {abc: 3 3 (10.000) :xyz}
do_test printf-2.7.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 9.99999
} {abc: 3 3 (1.000e+01) :xyz}
do_test printf-2.7.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 9.99999
} {abc: 3 3 ( 10) :xyz}
do_test printf-2.7.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -0.00543
} {abc: (-0.005) :xyz}
do_test printf-2.7.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -0.00543
} {abc: (-5.430e-03) :xyz}
do_test printf-2.7.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -0.00543
} {abc: (-0.00543) :xyz}
do_test printf-2.7.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -0.00543
} {abc: 3 3 (-0.00543) :xyz}
do_test printf-2.7.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -0.00543
} {abc: 3 3 (-0.00543000) :xyz}
do_test printf-2.7.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -0.00543
} {abc: 3 3 (-000.00543) :xyz}
do_test printf-2.7.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -0.00543
} {abc: 3 3 (-0.005) :xyz}
do_test printf-2.7.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -0.00543
} {abc: 3 3 (-5.430e-03) :xyz}
do_test printf-2.7.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -0.00543
} {abc: 3 3 (-0.00543) :xyz}
do_test printf-2.7.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -1.0
} {abc: (-1.000) :xyz}
do_test printf-2.7.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -1.0
} {abc: (-1.000e+00) :xyz}
do_test printf-2.7.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -1.0
} {abc: ( -1) :xyz}
do_test printf-2.7.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -1.0
} {abc: 3 3 (-1) :xyz}
do_test printf-2.7.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -1.0
} {abc: 3 3 (-1.00000) :xyz}
do_test printf-2.7.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -1.0
} {abc: 3 3 (-000000001) :xyz}
do_test printf-2.7.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -1.0
} {abc: 3 3 (-1.000) :xyz}
do_test printf-2.7.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -1.0
} {abc: 3 3 (-1.000e+00) :xyz}
do_test printf-2.7.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -1.0
} {abc: 3 3 ( -1) :xyz}
do_test printf-2.7.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -99.99999
} {abc: (-100.000) :xyz}
do_test printf-2.7.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -99.99999
} {abc: (-1.000e+02) :xyz}
do_test printf-2.7.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -99.99999
} {abc: (-100) :xyz}
do_test printf-2.7.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -99.99999
} {abc: 3 3 (-100) :xyz}
do_test printf-2.7.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -99.99999
} {abc: 3 3 (-100.000) :xyz}
do_test printf-2.7.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -99.99999
} {abc: 3 3 (-000000100) :xyz}
do_test printf-2.7.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -99.99999
} {abc: 3 3 (-100.000) :xyz}
do_test printf-2.7.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -99.99999
} {abc: 3 3 (-1.000e+02) :xyz}
do_test printf-2.7.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -99.99999
} {abc: 3 3 (-100) :xyz}
do_test printf-2.7.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 3.14e+9
} {abc: (3140000000.000) :xyz}
do_test printf-2.7.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 3.14e+9
} {abc: (3.140e+09) :xyz}
do_test printf-2.7.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 3.14e+9
} {abc: (3.14e+09) :xyz}
do_test printf-2.7.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 3.14e+9
} {abc: 3 3 (3.14e+09) :xyz}
do_test printf-2.7.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 3.14e+9
} {abc: 3 3 (3.14000e+09) :xyz}
do_test printf-2.7.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 3.14e+9
} {abc: 3 3 (003.14e+09) :xyz}
do_test printf-2.7.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 3.14e+9
} {abc: 3 3 (3140000000.000) :xyz}
do_test printf-2.7.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 3.14e+9
} {abc: 3 3 (3.140e+09) :xyz}
do_test printf-2.7.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 3.14e+9
} {abc: 3 3 (3.14e+09) :xyz}
do_test printf-2.7.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -4.72732e+88
} {abc: (-4.727e+88) :xyz}
do_test printf-2.7.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -4.72732e+88
} {abc: (-4.73e+88) :xyz}
do_test printf-2.7.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -4.72732e+88
} {abc: 3 3 (-4.72732e+88) :xyz}
do_test printf-2.7.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -4.72732e+88
} {abc: 3 3 (-4.72732e+88) :xyz}
do_test printf-2.7.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -4.72732e+88
} {abc: 3 3 (-4.72732e+88) :xyz}
do_test printf-2.7.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -4.72732e+88
} {abc: 3 3 (-4.727e+88) :xyz}
do_test printf-2.7.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -4.72732e+88
} {abc: 3 3 (-4.73e+88) :xyz}
do_test printf-2.7.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 9.87991e+143
} {abc: (9.880e+143) :xyz}
do_test printf-2.7.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 9.87991e+143
} {abc: (9.88e+143) :xyz}
do_test printf-2.7.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 9.87991e+143
} {abc: 3 3 (9.87991e+143) :xyz}
do_test printf-2.7.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 9.87991e+143
} {abc: 3 3 (9.87991e+143) :xyz}
do_test printf-2.7.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 9.87991e+143
} {abc: 3 3 (9.87991e+143) :xyz}
do_test printf-2.7.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 9.87991e+143
} {abc: 3 3 (9.880e+143) :xyz}
do_test printf-2.7.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 9.87991e+143
} {abc: 3 3 (9.88e+143) :xyz}
do_test printf-2.7.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -6.287291e-9
} {abc: (-0.000) :xyz}
do_test printf-2.7.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -6.287291e-9
} {abc: (-6.287e-09) :xyz}
do_test printf-2.7.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -6.287291e-9
} {abc: (-6.29e-09) :xyz}
do_test printf-2.7.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -6.287291e-9
} {abc: 3 3 (-6.28729e-09) :xyz}
do_test printf-2.7.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -6.287291e-9
} {abc: 3 3 (-6.28729e-09) :xyz}
do_test printf-2.7.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -6.287291e-9
} {abc: 3 3 (-6.28729e-09) :xyz}
do_test printf-2.7.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -6.287291e-9
} {abc: 3 3 (-0.000) :xyz}
do_test printf-2.7.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -6.287291e-9
} {abc: 3 3 (-6.287e-09) :xyz}
do_test printf-2.7.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -6.287291e-9
} {abc: 3 3 (-6.29e-09) :xyz}
do_test printf-2.7.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 3.38826392e-110
} {abc: (0.000) :xyz}
do_test printf-2.7.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 3.38826392e-110
} {abc: (3.388e-110) :xyz}
do_test printf-2.7.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 3.38826392e-110
} {abc: (3.39e-110) :xyz}
do_test printf-2.7.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 3.38826392e-110
} {abc: 3 3 (3.38826e-110) :xyz}
do_test printf-2.7.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 3.38826392e-110
} {abc: 3 3 (3.38826e-110) :xyz}
do_test printf-2.7.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 3.38826392e-110
} {abc: 3 3 (3.38826e-110) :xyz}
do_test printf-2.7.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 3.38826392e-110
} {abc: 3 3 (0.000) :xyz}
do_test printf-2.7.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 3.38826392e-110
} {abc: 3 3 (3.388e-110) :xyz}
do_test printf-2.7.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 3.38826392e-110
} {abc: 3 3 (3.39e-110) :xyz}
do_test printf-2.8.1.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 0.001
} {abc: (0.00) :xyz}
do_test printf-2.8.1.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 0.001
} {abc: (1.00e-03) :xyz}
do_test printf-2.8.1.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 0.001
} {abc: (0.001) :xyz}
do_test printf-2.8.1.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 0.001
} {abc: 3 2 (0.001) :xyz}
do_test printf-2.8.1.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 0.001
} {abc: 3 2 (0.00100000) :xyz}
do_test printf-2.8.1.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 0.001
} {abc: 3 2 (000000.001) :xyz}
do_test printf-2.8.1.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 0.001
} {abc: 3 2 (0.00) :xyz}
do_test printf-2.8.1.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 0.001
} {abc: 3 2 (1.00e-03) :xyz}
do_test printf-2.8.1.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 0.001
} {abc: 3 2 (0.001) :xyz}
do_test printf-2.8.2.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 1.0e-20
} {abc: (0.00) :xyz}
do_test printf-2.8.2.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 1.0e-20
} {abc: (1.00e-20) :xyz}
do_test printf-2.8.2.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 1.0e-20
} {abc: (1e-20) :xyz}
do_test printf-2.8.2.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 1.0e-20
} {abc: 3 2 (1e-20) :xyz}
do_test printf-2.8.2.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 1.0e-20
} {abc: 3 2 (1.00000e-20) :xyz}
do_test printf-2.8.2.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 1.0e-20
} {abc: 3 2 (000001e-20) :xyz}
do_test printf-2.8.2.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 1.0e-20
} {abc: 3 2 (0.00) :xyz}
do_test printf-2.8.2.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 1.0e-20
} {abc: 3 2 (1.00e-20) :xyz}
do_test printf-2.8.2.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 1.0e-20
} {abc: 3 2 (1e-20) :xyz}
do_test printf-2.8.3.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 1.0
} {abc: (1.00) :xyz}
do_test printf-2.8.3.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 1.0
} {abc: (1.00e+00) :xyz}
do_test printf-2.8.3.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 1.0
} {abc: (  1) :xyz}
do_test printf-2.8.3.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 1.0
} {abc: 3 2 (1) :xyz}
do_test printf-2.8.3.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 1.0
} {abc: 3 2 (1.00000) :xyz}
do_test printf-2.8.3.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 1.0
} {abc: 3 2 (0000000001) :xyz}
do_test printf-2.8.3.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 1.0
} {abc: 3 2 (1.00) :xyz}
do_test printf-2.8.3.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 1.0
} {abc: 3 2 (1.00e+00) :xyz}
do_test printf-2.8.3.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 1.0
} {abc: 3 2 (  1) :xyz}
do_test printf-2.8.4.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 0.0
} {abc: (0.00) :xyz}
do_test printf-2.8.4.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 0.0
} {abc: (0.00e+00) :xyz}
do_test printf-2.8.4.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 0.0
} {abc: (  0) :xyz}
do_test printf-2.8.4.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 0.0
} {abc: 3 2 (0) :xyz}
do_test printf-2.8.4.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 0.0
} {abc: 3 2 (0.00000) :xyz}
do_test printf-2.8.4.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 0.0
} {abc: 3 2 (0000000000) :xyz}
do_test printf-2.8.4.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 0.0
} {abc: 3 2 (0.00) :xyz}
do_test printf-2.8.4.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 0.0
} {abc: 3 2 (0.00e+00) :xyz}
do_test printf-2.8.4.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 0.0
} {abc: 3 2 (  0) :xyz}
do_test printf-2.8.5.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 100.0
} {abc: (100.00) :xyz}
do_test printf-2.8.5.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 100.0
} {abc: (1.00e+02) :xyz}
do_test printf-2.8.5.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 100.0
} {abc: (1e+02) :xyz}
do_test printf-2.8.5.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 100.0
} {abc: 3 2 (100) :xyz}
do_test printf-2.8.5.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 100.0
} {abc: 3 2 (100.000) :xyz}
do_test printf-2.8.5.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 100.0
} {abc: 3 2 (0000000100) :xyz}
do_test printf-2.8.5.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 100.0
} {abc: 3 2 (100.00) :xyz}
do_test printf-2.8.5.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 100.0
} {abc: 3 2 (1.00e+02) :xyz}
do_test printf-2.8.5.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 100.0
} {abc: 3 2 (1e+02) :xyz}
do_test printf-2.8.6.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 9.99999
} {abc: (10.00) :xyz}
do_test printf-2.8.6.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 9.99999
} {abc: (1.00e+01) :xyz}
do_test printf-2.8.6.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 9.99999
} {abc: ( 10) :xyz}
do_test printf-2.8.6.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 9.99999
} {abc: 3 2 (9.99999) :xyz}
do_test printf-2.8.6.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 9.99999
} {abc: 3 2 (9.99999) :xyz}
do_test printf-2.8.6.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 9.99999
} {abc: 3 2 (0009.99999) :xyz}
do_test printf-2.8.6.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 9.99999
} {abc: 3 2 (10.00) :xyz}
do_test printf-2.8.6.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 9.99999
} {abc: 3 2 (1.00e+01) :xyz}
do_test printf-2.8.6.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 9.99999
} {abc: 3 2 ( 10) :xyz}
do_test printf-2.8.7.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -0.00543
} {abc: (-0.01) :xyz}
do_test printf-2.8.7.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -0.00543
} {abc: (-5.43e-03) :xyz}
do_test printf-2.8.7.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -0.00543
} {abc: (-0.0054) :xyz}
do_test printf-2.8.7.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -0.00543
} {abc: 3 2 (-0.00543) :xyz}
do_test printf-2.8.7.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -0.00543
} {abc: 3 2 (-0.00543000) :xyz}
do_test printf-2.8.7.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -0.00543
} {abc: 3 2 (-000.00543) :xyz}
do_test printf-2.8.7.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -0.00543
} {abc: 3 2 (-0.01) :xyz}
do_test printf-2.8.7.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -0.00543
} {abc: 3 2 (-5.43e-03) :xyz}
do_test printf-2.8.7.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -0.00543
} {abc: 3 2 (-0.0054) :xyz}
do_test printf-2.8.8.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -1.0
} {abc: (-1.00) :xyz}
do_test printf-2.8.8.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -1.0
} {abc: (-1.00e+00) :xyz}
do_test printf-2.8.8.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -1.0
} {abc: ( -1) :xyz}
do_test printf-2.8.8.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -1.0
} {abc: 3 2 (-1) :xyz}
do_test printf-2.8.8.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -1.0
} {abc: 3 2 (-1.00000) :xyz}
do_test printf-2.8.8.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -1.0
} {abc: 3 2 (-000000001) :xyz}
do_test printf-2.8.8.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -1.0
} {abc: 3 2 (-1.00) :xyz}
do_test printf-2.8.8.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -1.0
} {abc: 3 2 (-1.00e+00) :xyz}
do_test printf-2.8.8.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -1.0
} {abc: 3 2 ( -1) :xyz}
do_test printf-2.8.9.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -99.99999
} {abc: (-100.00) :xyz}
do_test printf-2.8.9.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -99.99999
} {abc: (-1.00e+02) :xyz}
do_test printf-2.8.9.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -99.99999
} {abc: (-1e+02) :xyz}
do_test printf-2.8.9.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -99.99999
} {abc: 3 2 (-100) :xyz}
do_test printf-2.8.9.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -99.99999
} {abc: 3 2 (-100.000) :xyz}
do_test printf-2.8.9.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -99.99999
} {abc: 3 2 (-000000100) :xyz}
do_test printf-2.8.9.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -99.99999
} {abc: 3 2 (-100.00) :xyz}
do_test printf-2.8.9.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -99.99999
} {abc: 3 2 (-1.00e+02) :xyz}
do_test printf-2.8.9.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -99.99999
} {abc: 3 2 (-1e+02) :xyz}
do_test printf-2.8.10.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 3.14e+9
} {abc: (3140000000.00) :xyz}
do_test printf-2.8.10.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 3.14e+9
} {abc: (3.14e+09) :xyz}
do_test printf-2.8.10.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 3.14e+9
} {abc: (3.1e+09) :xyz}
do_test printf-2.8.10.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 3.14e+9
} {abc: 3 2 (3.14e+09) :xyz}
do_test printf-2.8.10.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 3.14e+9
} {abc: 3 2 (3.14000e+09) :xyz}
do_test printf-2.8.10.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 3.14e+9
} {abc: 3 2 (003.14e+09) :xyz}
do_test printf-2.8.10.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 3.14e+9
} {abc: 3 2 (3140000000.00) :xyz}
do_test printf-2.8.10.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 3.14e+9
} {abc: 3 2 (3.14e+09) :xyz}
do_test printf-2.8.10.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 3.14e+9
} {abc: 3 2 (3.1e+09) :xyz}
do_test printf-2.8.11.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -4.72732e+88
} {abc: (-4.73e+88) :xyz}
do_test printf-2.8.11.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -4.72732e+88
} {abc: (-4.7e+88) :xyz}
do_test printf-2.8.11.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -4.72732e+88
} {abc: 3 2 (-4.72732e+88) :xyz}
do_test printf-2.8.11.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -4.72732e+88
} {abc: 3 2 (-4.72732e+88) :xyz}
do_test printf-2.8.11.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -4.72732e+88
} {abc: 3 2 (-4.72732e+88) :xyz}
do_test printf-2.8.11.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -4.72732e+88
} {abc: 3 2 (-4.73e+88) :xyz}
do_test printf-2.8.11.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -4.72732e+88
} {abc: 3 2 (-4.7e+88) :xyz}
do_test printf-2.8.12.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 9.87991e+143
} {abc: (9.88e+143) :xyz}
do_test printf-2.8.12.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 9.87991e+143
} {abc: (9.9e+143) :xyz}
do_test printf-2.8.12.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 9.87991e+143
} {abc: 3 2 (9.87991e+143) :xyz}
do_test printf-2.8.12.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 9.87991e+143
} {abc: 3 2 (9.87991e+143) :xyz}
do_test printf-2.8.12.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 9.87991e+143
} {abc: 3 2 (9.87991e+143) :xyz}
do_test printf-2.8.12.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 9.87991e+143
} {abc: 3 2 (9.88e+143) :xyz}
do_test printf-2.8.12.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 9.87991e+143
} {abc: 3 2 (9.9e+143) :xyz}
do_test printf-2.8.13.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -6.287291e-9
} {abc: (-0.00) :xyz}
do_test printf-2.8.13.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -6.287291e-9
} {abc: (-6.29e-09) :xyz}
do_test printf-2.8.13.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -6.287291e-9
} {abc: (-6.3e-09) :xyz}
do_test printf-2.8.13.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -6.287291e-9
} {abc: 3 2 (-6.28729e-09) :xyz}
do_test printf-2.8.13.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -6.287291e-9
} {abc: 3 2 (-6.28729e-09) :xyz}
do_test printf-2.8.13.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -6.287291e-9
} {abc: 3 2 (-6.28729e-09) :xyz}
do_test printf-2.8.13.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -6.287291e-9
} {abc: 3 2 (-0.00) :xyz}
do_test printf-2.8.13.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -6.287291e-9
} {abc: 3 2 (-6.29e-09) :xyz}
do_test printf-2.8.13.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -6.287291e-9
} {abc: 3 2 (-6.3e-09) :xyz}
do_test printf-2.8.14.1 {
  sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 3.38826392e-110
} {abc: (0.00) :xyz}
do_test printf-2.8.14.2 {
  sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 3.38826392e-110
} {abc: (3.39e-110) :xyz}
do_test printf-2.8.14.3 {
  sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 3.38826392e-110
} {abc: (3.4e-110) :xyz}
do_test printf-2.8.14.4 {
  sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 (3.38826e-110) :xyz}
do_test printf-2.8.14.5 {
  sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 (3.38826e-110) :xyz}
do_test printf-2.8.14.6 {
  sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 (3.38826e-110) :xyz}
do_test printf-2.8.14.7 {
  sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 (0.00) :xyz}
do_test printf-2.8.14.8 {
  sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 (3.39e-110) :xyz}
do_test printf-2.8.14.9 {
  sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 (3.4e-110) :xyz}
do_test printf-2.8.15.1 {
  sqlite3_mprintf_double {abc: (% *.*f) :xyz} 3 2 3.38826392e-110
} {abc: ( 0.00) :xyz}
do_test printf-2.8.15.2 {
  sqlite3_mprintf_double {abc: (% *.*e) :xyz} 3 2 3.38826392e-110
} {abc: ( 3.39e-110) :xyz}
do_test printf-2.8.15.3 {
  sqlite3_mprintf_double {abc: (% *.*g) :xyz} 3 2 3.38826392e-110
} {abc: ( 3.4e-110) :xyz}
do_test printf-2.8.15.4 {
  sqlite3_mprintf_double {abc: %d %d (% g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 ( 3.38826e-110) :xyz}
do_test printf-2.8.15.5 {
  sqlite3_mprintf_double {abc: %d %d (% #g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 ( 3.38826e-110) :xyz}
do_test printf-2.8.15.6 {
  sqlite3_mprintf_double {abc: %d %d (%0 10g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 ( 3.38826e-110) :xyz}
do_test printf-2.8.15.7 {
  sqlite3_mprintf_double {abc: %d %d (% 3.2f) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 ( 0.00) :xyz}
do_test printf-2.8.15.8 {
  sqlite3_mprintf_double {abc: %d %d (% 3.2e) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 ( 3.39e-110) :xyz}
do_test printf-2.8.15.9 {
  sqlite3_mprintf_double {abc: %d %d (% 3.2g) :xyz} 3 2 3.38826392e-110
} {abc: 3 2 ( 3.4e-110) :xyz}

do_test printf-2.9.1 {
  sqlite3_mprintf_double {abc: %d %d (%5.0g) :xyz} 0 0 1.234
} {abc: 0 0 (    1) :xyz}
do_test printf-2.9.2 {
  sqlite3_mprintf_double {abc: %d %d (%+5.0g) :xyz} 0 0 1.234
} {abc: 0 0 (   +1) :xyz}
do_test printf-2.9.3 {
  sqlite3_mprintf_double {abc: %d %d (%+-5.0g) :xyz} 0 0 1.234
} {abc: 0 0 (+1   ) :xyz}

do_test printf-2.10.1 {
  sqlite3_mprintf_double {abc: %d %d (%-010.5f) :xyz} 0 0 1.234
} {abc: 0 0 (1.23400   ) :xyz}
do_test printf-2.10.2 {
  sqlite3_mprintf_double {abc: %d %d (%010.5f) :xyz} 0 0 1.234
} {abc: 0 0 (0001.23400) :xyz}
do_test printf-2.10.3 {
  sqlite3_mprintf_double {abc: %d %d (%+010.5f) :xyz} 0 0 1.234
} {abc: 0 0 (+001.23400) :xyz}

do_test printf-3.1 {
  sqlite3_mprintf_str {A String: (%*.*s)} 10 10 {This is the string}
} [format {A String: (%*.*s)} 10 10 {This is the string}]
do_test printf-3.2 {
  sqlite3_mprintf_str {A String: (%*.*s)} 10 5 {This is the string}
} [format {A String: (%*.*s)} 10 5 {This is the string}]
do_test printf-3.3 {
  sqlite3_mprintf_str {A String: (%*.*s)} -10 5 {This is the string}
} [format {A String: (%*.*s)} -10 5 {This is the string}]
do_test printf-3.4 {
  sqlite3_mprintf_str {%d %d A String: (%s)} 1 2 {This is the string}
} [format {%d %d A String: (%s)} 1 2 {This is the string}]
do_test printf-3.5 {
  sqlite3_mprintf_str {%d %d A String: (%30s)} 1 2 {This is the string}
} [format {%d %d A String: (%30s)} 1 2 {This is the string}]
do_test printf-3.6 {
  sqlite3_mprintf_str {%d %d A String: (%-30s)} 1 2 {This is the string}
} [format {%d %d A String: (%-30s)} 1 2 {This is the string}]
do_test snprintf-3.11 {
  sqlite3_snprintf_str 2 {x%d %d %s} 10 10 {This is the string}
} {x}
do_test snprintf-3.12 {
  sqlite3_snprintf_str 3 {x%d %d %s} 10 10 {This is the string}
} {x1}
do_test snprintf-3.13 {
  sqlite3_snprintf_str 4 {x%d %d %s} 10 10 {This is the string}
} {x10}
do_test snprintf-3.14 {
  sqlite3_snprintf_str 5 {x%d %d %s} 10 10 {This is the string}
} {x10 }
do_test snprintf-3.15 {
  sqlite3_snprintf_str 6 {x%d %d %s} 10 10 {This is the string}
} {x10 1}
do_test snprintf-3.16 {
  sqlite3_snprintf_str 7 {x%d %d %s} 10 10 {This is the string}
} {x10 10}
do_test snprintf-3.17 {
  sqlite3_snprintf_str 8 {x%d %d %s} 10 10 {This is the string}
} {x10 10 }
do_test snprintf-3.18 {
  sqlite3_snprintf_str 9 {x%d %d %s} 10 10 {This is the string}
} {x10 10 T}
do_test snprintf-3.19 {
  sqlite3_snprintf_str 100 {x%d %d %s} 10 10 {This is the string}
} {x10 10 This is the string}

do_test printf-4.1 {
  sqlite3_mprintf_str {%d %d A quoted string: '%q'} 1 2 {Hi Y'all}
} {1 2 A quoted string: 'Hi Y''all'}
do_test printf-4.2 {
  sqlite3_mprintf_str {%d %d A NULL pointer in %%q: '%q'} 1 2
} {1 2 A NULL pointer in %q: '(NULL)'}
do_test printf-4.3 {
  sqlite3_mprintf_str {%d %d A quoted string: %Q} 1 2 {Hi Y'all}
} {1 2 A quoted string: 'Hi Y''all'}
do_test printf-4.4 {
  sqlite3_mprintf_str {%d %d A NULL pointer in %%Q: %Q} 1 2
} {1 2 A NULL pointer in %Q: NULL}

do_test printf-5.1 {
  set x [sqlite3_mprintf_str {%d %d %100000s} 0 0 {Hello}]
  string length $x
} {344}
do_test printf-5.2 {
  sqlite3_mprintf_str {%d %d (%-10.10s) %} -9 -10 {HelloHelloHello}
} {-9 -10 (HelloHello) %}

do_test printf-6.1 {
  sqlite3_mprintf_z_test , one two three four five six
} {,one,two,three,four,five,six}


do_test printf-7.1 {
  sqlite3_mprintf_scaled {A double: %g} 1.0e307 1.0
} {A double: 1e+307}
do_test printf-7.2 {
  sqlite3_mprintf_scaled {A double: %g} 1.0e307 10.0
} {A double: 1e+308}
do_test printf-7.3 {
  sqlite3_mprintf_scaled {A double: %g} 1.0e307 100.0
} {A double: Inf}
do_test printf-7.4 {
  sqlite3_mprintf_scaled {A double: %g} -1.0e307 100.0
} {A double: -Inf}
do_test printf-7.5 {
  sqlite3_mprintf_scaled {A double: %+g} 1.0e307 100.0
} {A double: +Inf}

do_test printf-8.1 {
  sqlite3_mprintf_int {%u %u %u} 0x7fffffff 0x80000000 0xffffffff
} {2147483647 2147483648 4294967295}
do_test printf-8.2 {
  sqlite3_mprintf_long {%lu %lu %lu} 0x7fffffff 0x80000000 0xffffffff
} {2147483647 2147483648 4294967295}
do_test printf-8.3 {
  sqlite3_mprintf_int64 {%llu %llu %llu} 2147483647 2147483648 4294967296
} {2147483647 2147483648 4294967296}
do_test printf-8.4 {
  sqlite3_mprintf_int64 {%lld %lld %lld} 2147483647 2147483648 4294967296
} {2147483647 2147483648 4294967296}
do_test printf-8.5 {
  sqlite3_mprintf_int64 {%llx %llx %llx} 2147483647 2147483648 4294967296
} {7fffffff 80000000 100000000}
do_test printf-8.6 {
  sqlite3_mprintf_int64 {%llx %llo %lld} -1 -1 -1
} {ffffffffffffffff 1777777777777777777777 -1}
do_test printf-8.7 {
  sqlite3_mprintf_int64 {%llx %llx %llx} +2147483647 +2147483648 +4294967296
} {7fffffff 80000000 100000000}

do_test printf-9.1 {
  sqlite3_mprintf_int {%*.*c} 4 4 65
} {AAAA}
do_test printf-9.2 {
  sqlite3_mprintf_int {%*.*c} -4 1 66
} {B   }
do_test printf-9.3 {
  sqlite3_mprintf_int {%*.*c} 4 1 67
} {   C}
do_test printf-9.4 {
  sqlite3_mprintf_int {%d %d %c} 4 1 67
} {4 1 C}
set ten {          }
set fifty $ten$ten$ten$ten$ten
do_test printf-9.5 {
  sqlite3_mprintf_int {%d %*c} 1 -201 67
} "1 C$fifty$fifty$fifty$fifty"
do_test printf-9.6 {
  sqlite3_mprintf_int {hi%12345.12346yhello} 0 0 0
} {hi}

# Ticket #812
#
do_test printf-10.1 {
  sqlite3_mprintf_stronly %s {}
} {}

# Ticket #831
#
do_test printf-10.2 {
  sqlite3_mprintf_stronly %q {}
} {}

# Ticket #1340:  Test for loss of precision on large positive exponents
#
do_test printf-10.3 {
  sqlite3_mprintf_double {%d %d %f} 1 1 1e300
} {1 1 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000}

# The non-standard '!' flag on a 'g' conversion forces a decimal point
# and at least one digit on either side of the decimal point.
#
do_test printf-11.1 {
  sqlite3_mprintf_double {%d %d %!g} 1 1 1
} {1 1 1.0}
do_test printf-11.2 {
  sqlite3_mprintf_double {%d %d %!g} 1 1 123
} {1 1 123.0}
do_test printf-11.3 {
  sqlite3_mprintf_double {%d %d %!g} 1 1 12.3
} {1 1 12.3}
do_test printf-11.4 {
  sqlite3_mprintf_double {%d %d %!g} 1 1 0.123
} {1 1 0.123}
do_test printf-11.5 {
  sqlite3_mprintf_double {%d %d %!.15g} 1 1 1
} {1 1 1.0}
do_test printf-11.6 {
  sqlite3_mprintf_double {%d %d %!.15g} 1 1 1e10
} {1 1 10000000000.0}
do_test printf-11.7 {
  sqlite3_mprintf_double {%d %d %!.15g} 1 1 1e300
} {1 1 1.0e+300}

# Additional tests for coverage
#
do_test printf-12.1 {
  sqlite3_mprintf_double {%d %d %.2000g} 1 1 1.0
} {1 1 1}

# Floating point boundary cases
#
do_test printf-13.1 {
  sqlite3_mprintf_hexdouble %.20f 4024000000000000
} {10.00000000000000000000}
do_test printf-13.2 {
  sqlite3_mprintf_hexdouble %.20f 4197d78400000000
} {100000000.00000000000000000000}
do_test printf-13.3 {
  sqlite3_mprintf_hexdouble %.20f 4693b8b5b5056e17
} {100000000000000000000000000000000.00000000000000000000}
do_test printf-13.4 {
  sqlite3_mprintf_hexdouble %.20f 7ff0000000000000
} {Inf}
do_test printf-13.5 {
  sqlite3_mprintf_hexdouble %.20f fff0000000000000
} {-Inf}
do_test printf-13.6 {
  sqlite3_mprintf_hexdouble %.20f fff8000000000000
} {NaN}

do_test printf-14.1 {
  sqlite3_mprintf_str {abc-%y-123} 0 0 {not used}
} {abc-}
do_test printf-14.2 {
  sqlite3_mprintf_n_test {xyzzy}
} 5
do_test printf-14.3 {
  sqlite3_mprintf_str {abc-%T-123} 0 0 {not used}
} {abc-}
do_test printf-14.4 {
  sqlite3_mprintf_str {abc-%#} 0 0 {not used}
} {abc-}
do_test printf-14.5 {
  sqlite3_mprintf_str {abc-%*.*s-xyz} 10 -10 {a_very_long_string}
} {abc-a_very_lon-xyz}
do_test printf-14.6 {
  sqlite3_mprintf_str {abc-%5.10/} 0 0 {not used}
} {abc-}
do_test printf-14.7 {
  sqlite3_mprintf_str {abc-%05.5d} 123 0 {not used}
} {abc-00123}
do_test printf-14.8 {
  sqlite3_mprintf_str {abc-%05.5d} 1234567 0 {not used}
} {abc-1234567}

for {set i 2} {$i<200} {incr i} {
  set res [string repeat { } [expr {$i-1}]]x
  do_test printf-14.90.$i "
    sqlite3_mprintf_str {%*.*s} $i 500 x
  " $res
}

do_test printf-15.1 {
  sqlite3_snprintf_int 5 {12345} 0
} {1234}
do_test printf-15.2 {
  sqlite3_snprintf_int 5 {} 0
} {}
do_test printf-15.3 {
  sqlite3_snprintf_int 0 {} 0
} {abcdefghijklmnopqrstuvwxyz}

# Now test malloc() failure within a sqlite3_mprintf():
#
ifcapable memdebug {
  foreach var {a b c d} {
    set $var [string repeat $var 400]
  }
  set str1 "[string repeat A 360]%d%d%s"
  set str2 [string repeat B 5000]
  set zSuccess "[string repeat A 360]11[string repeat B 5000]"
  foreach ::iRepeat {0 1} {
    set nTestNum 1
    while {1} {
      sqlite3_memdebug_fail $nTestNum -repeat $::iRepeat
      set z [sqlite3_mprintf_str $str1 1 1 $str2]
      set nFail [sqlite3_memdebug_fail -1 -benign nBenign]
      do_test printf-malloc-$::iRepeat.$nTestNum {
        expr {($nFail>0 && $z eq "") || ($nFail==$nBenign && $z eq $zSuccess)}
      } {1}
      if {$nFail == 0} break
      incr nTestNum
    }
  }
}

finish_test

Added test/progress.test.



































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the 'progress callback'.
#
# $Id: progress.test,v 1.8 2007/06/15 14:53:53 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If the progress callback is not available in this build, skip this
# whole file.
ifcapable !progress {
  finish_test
  return
}

# Build some test data
#
execsql {
  BEGIN;
  CREATE TABLE t1(a);
  INSERT INTO t1 VALUES(1);
  INSERT INTO t1 VALUES(2);
  INSERT INTO t1 VALUES(3);
  INSERT INTO t1 VALUES(4);
  INSERT INTO t1 VALUES(5);
  INSERT INTO t1 VALUES(6);
  INSERT INTO t1 VALUES(7);
  INSERT INTO t1 VALUES(8);
  INSERT INTO t1 VALUES(9);
  INSERT INTO t1 VALUES(10);
  COMMIT;
}


# Test that the progress callback is invoked.
do_test progress-1.0 {
  set counter 0
  db progress 1 "[namespace code {incr counter}] ; expr 0"
  execsql {
    SELECT * FROM t1
  }
  expr $counter > 1
} 1
do_test progress-1.0.1 {
  db progress
} {::namespace inscope :: {incr counter} ; expr 0}
do_test progress-1.0.2 {
  set v [catch {db progress xyz bogus} msg]
  lappend v $msg
} {1 {expected integer but got "xyz"}}

# Test that the query is abandoned when the progress callback returns non-zero
do_test progress-1.1 {
  set counter 0
  db progress 1 "[namespace code {incr counter}] ; expr 1"
  set rc [catch {execsql {
    SELECT * FROM t1
  }}]
  list $counter $rc
} {1 1}

# Test that the query is rolled back when the progress callback returns
# non-zero.
do_test progress-1.2 {

  # This figures out how many opcodes it takes to copy 5 extra rows into t1.
  db progress 1 "[namespace code {incr five_rows}] ; expr 0"
  set five_rows 0
  execsql {
    INSERT INTO t1 SELECT a+10 FROM t1 WHERE a < 6
  }
  db progress 0 ""
  execsql {
    DELETE FROM t1 WHERE a > 10
  }

  # Now set up the progress callback to abandon the query after the number of
  # opcodes to copy 5 rows. That way, when we try to copy 6 rows, we know
  # some data will have been inserted into the table by the time the progress
  # callback abandons the query.
  db progress $five_rows "expr 1"
  catchsql {
    INSERT INTO t1 SELECT a+10 FROM t1 WHERE a < 9
  }
  execsql {
    SELECT count(*) FROM t1
  }
} 10

# Test that an active transaction remains active and not rolled back 
# after the progress query abandons a query. 
#
# UPDATE: It is now recognised that this is a sure route to database
# corruption. So the transaction is rolled back.
do_test progress-1.3 {

  db progress 0 ""
  execsql BEGIN
  execsql {
    INSERT INTO t1 VALUES(11)
  }
  db progress 1 "expr 1"
  catchsql {
    INSERT INTO t1 VALUES(12)
  }
  db progress 0 ""
  catchsql COMMIT
} {1 {cannot commit - no transaction is active}}
do_test progress-1.3.1 {
  execsql {
    SELECT count(*) FROM t1
  }
} 10

# Check that a value of 0 for N means no progress callback
do_test progress-1.4 {
  set counter 0
  db progress 0 "[namespace code {incr counter}] ; expr 0"
  execsql {
    SELECT * FROM t1;
  }
  set counter
} 0

db progress 0 ""

# Make sure other queries can be run from within the progress
# handler.  Ticket #1827
#
do_test progress-1.5 {
  set rx 0
  proc set_rx {args} {
    db progress 0 {}
    set ::rx [db eval {SELECT count(*) FROM t1}]
    return [expr 0]
  }
  db progress 10 set_rx
  db eval {
    SELECT sum(a) FROM t1
  }
} {55}
do_test progress-1.6 {
  set ::rx
} {10}

# Check that abandoning a query using the progress handler does
# not cause other queries to abort. Ticket #2415.
do_test progress-1.7 {
  execsql {
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc VALUES(4, 5, 6);
    INSERT INTO abc VALUES(7, 8, 9);
  }

  set ::res [list]
  db eval {SELECT a, b, c FROM abc} {
    lappend ::res $a $b $c
    db progress 10 "expr 1"
    catch {db eval {SELECT a, b, c FROM abc} { }} msg
    lappend ::res $msg
  }

  set ::res
} {1 2 3 interrupted 4 5 6 interrupted 7 8 9 interrupted}

finish_test

Added test/ptrchng.test.































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# 2007 April 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# The focus of the tests in this file are to verify that the
# underlying TEXT or BLOB representation of an sqlite3_value
# changes appropriately when APIs from the following set are
# called:
#
#     sqlite3_value_text()
#     sqlite3_value_text16()
#     sqlite3_value_blob()
#     sqlite3_value_bytes()
#     sqlite3_value_bytes16()
#
# $Id: ptrchng.test,v 1.5 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !bloblit {
  finish_test
  return
}

# Register the "pointer_change" SQL function.
#
sqlite3_create_function db

do_test ptrchng-1.1 {
  execsql {
    CREATE TABLE t1(x INTEGER PRIMARY KEY, y BLOB);
    INSERT INTO t1 VALUES(1, 'abc');
    INSERT INTO t1 VALUES(2, 
       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234356789');
    INSERT INTO t1 VALUES(3, x'626c6f62');
    INSERT INTO t1 VALUES(4,
 x'000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324'
    );
    SELECT count(*) FROM t1;
  }
} {4}

# For the short entries that fit in the Mem.zBuf[], the pointer should
# never change regardless of what type conversions occur.
#
# UPDATE: No longer true, as Mem.zBuf[] has been removed.
#
do_test ptrchng-2.1 {
  execsql {
    SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=1
  }
} {0}
do_test ptrchng-2.2 {
  execsql {
    SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=1
  }
} {0}
ifcapable utf16 {
  do_test ptrchng-2.3 {
    execsql {
      SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=1
    }
  } {1}
  do_test ptrchng-2.4 {
    execsql {
      SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=1
    }
  } {1}
  do_test ptrchng-2.5 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=1
    }
  } {0}
  do_test ptrchng-2.6 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=1
    }
  } {1}
}
do_test ptrchng-2.11 {
  execsql {
    SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=3
  }
} {0}
do_test ptrchng-2.12 {
  execsql {
    SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=3
  }
} {0}
ifcapable utf16 {
  do_test ptrchng-2.13 {
    execsql {
      SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=3
    }
  } {1}
  do_test ptrchng-2.14 {
    execsql {
      SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=3
    }
  } {1}
  do_test ptrchng-2.15 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=3
    }
  } {0}
  do_test ptrchng-2.16 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=3
    }
  } {1}
}

# For the long entries that do not fit in the Mem.zBuf[], the pointer
# should change sometimes.
#
do_test ptrchng-3.1 {
  execsql {
    SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=2
  }
} {0}
do_test ptrchng-3.2 {
  execsql {
    SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=2
  }
} {0}
ifcapable utf16 {
  do_test ptrchng-3.3 {
    execsql {
      SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=2
    }
  } {1}
  do_test ptrchng-3.4 {
    execsql {
      SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=2
    }
  } {1}
  do_test ptrchng-3.5 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=2
    }
  } {0}
  do_test ptrchng-3.6 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=2
    }
  } {1}
}
do_test ptrchng-3.11 {
  execsql {
    SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=4
  }
} {0}
do_test ptrchng-3.12 {
  execsql {
    SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=4
  }
} {0}
ifcapable utf16 {
  do_test ptrchng-3.13 {
    execsql {
      SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=4
    }
  } {1}
  do_test ptrchng-3.14 {
    execsql {
      SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=4
    }
  } {1}
  do_test ptrchng-3.15 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=4
    }
  } {0}
  do_test ptrchng-3.16 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=4
    }
  } {1}
}

# A call to _bytes() should never reformat a _text() or _blob().
#
do_test ptrchng-4.1 {
  execsql {
    SELECT pointer_change(y, 'text', 'bytes', 'text') FROM t1
  }
} {0 0 0 0}
do_test ptrchng-4.2 {
  execsql {
    SELECT pointer_change(y, 'blob', 'bytes', 'blob') FROM t1
  }
} {0 0 0 0}

# A call to _blob() should never trigger a reformat
#
do_test ptrchng-5.1 {
  execsql {
    SELECT pointer_change(y, 'text', 'bytes', 'blob') FROM t1
  }
} {0 0 0 0}
ifcapable utf16 {
  do_test ptrchng-5.2 {
    execsql {
      SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1
    }
  } {0 0 0 0}
  do_test ptrchng-5.3 {
    execsql {
      SELECT pointer_change(y, 'text16', 'bytes16', 'blob') FROM t1
    }
  } {0 0 0 0}
}

finish_test

Added test/quick.test.





















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all tests.
#
# $Id: quick.test,v 1.95 2009/03/16 14:48:19 danielk1977 Exp $

proc lshift {lvar} {
  upvar $lvar l
  set ret [lindex $l 0]
  set l [lrange $l 1 end]
  return $ret
}
while {[set arg [lshift argv]] != ""} {
  switch -- $arg {
    -sharedpagercache {
      sqlite3_enable_shared_cache 1
    }
    -soak {
       set SOAKTEST 1
    }
    -start {
       set STARTAT "[lshift argv]*"
    }
    default {
      set argv [linsert $argv 0 $arg]
      break
    }
  }
}

set testdir [file dirname $argv0]
source $testdir/tester.tcl
rename finish_test really_finish_test
proc finish_test {} {
  catch {db close}
  show_memstats
}
set ISQUICK 1

set EXCLUDE {
  all.test
  async.test
  async2.test
  async3.test
  backup_ioerr.test
  corrupt.test
  corruptC.test
  crash.test
  crash2.test
  crash3.test
  crash4.test
  crash5.test
  crash6.test
  crash7.test
  delete3.test
  fts3.test
  fkey_malloc.test
  fuzz.test
  fuzz3.test
  fuzz_malloc.test
  in2.test
  loadext.test
  memleak.test
  misc7.test
  misuse.test
  mutex2.test
  notify2.test
  onefile.test
  permutations.test
  quick.test
  savepoint4.test
  savepoint6.test
  select9.test
  soak.test
  speed1.test
  speed1p.test
  speed2.test
  speed3.test
  speed4.test
  speed4p.test
  sqllimits1.test
  tkt2686.test
  thread001.test
  thread002.test
  thread003.test
  thread004.test
  thread005.test
  trans2.test
  vacuum3.test

  incrvacuum_ioerr.test
  autovacuum_crash.test
  btree8.test
  shared_err.test
  vtab_err.test
  veryquick.test
  mallocAll.test
}

if {[sqlite3 -has-codec]} {
  # lappend EXCLUDE \
  #  conflict.test
}


# Files to include in the test.  If this list is empty then everything
# that is not in the EXCLUDE list is run.
#
set INCLUDE {
}

# If the QUICKTEST_INCLUDE environment variable is set, then interpret
# it as a list of test files. Always run these files, even if they
# begin with "malloc*" or "ioerr*" or are part of the EXCLUDE list
# defined above.
#
set QUICKTEST_INCLUDE {}
catch { set QUICKTEST_INCLUDE $env(QUICKTEST_INCLUDE) }

foreach testfile [lsort -dictionary [glob $testdir/*.test]] {
  set tail [file tail $testfile]
  if { [lsearch $QUICKTEST_INCLUDE $tail]<0 } {
    # If this is "veryquick.test", do not run any of the malloc or 
    # IO error simulations.
    if {[info exists ISVERYQUICK] && (
      [string match *malloc* $testfile] || [string match *ioerr* $testfile]
    ) } {
      continue
    }
    if {[lsearch -exact $EXCLUDE $tail]>=0} continue
  }
  if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue
  if {[info exists STARTAT] && [string match $STARTAT $tail]} {unset STARTAT}
  if {[info exists STARTAT]} continue
  source $testfile
  catch {db close}
  if {$sqlite_open_file_count>0} {
    puts "$tail did not close all files: $sqlite_open_file_count"
    incr nErr
    lappend ::failList $tail
    set sqlite_open_file_count 0
  }
}
#set argv quick
#source $testdir/permutations.test
#set argv ""
source $testdir/misuse.test

set sqlite_open_file_count 0
really_finish_test

Added test/quote.test.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is the ability to specify table and column names
# as quoted strings.
#
# $Id: quote.test,v 1.7 2007/04/25 11:32:30 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table with a strange name and with strange column names.
#
do_test quote-1.0 {
  catchsql {CREATE TABLE '@abc' ( '#xyz' int, '!pqr' text );}
} {0 {}}

# Insert, update and query the table.
#
do_test quote-1.1 {
  catchsql {INSERT INTO '@abc' VALUES(5,'hello')}
} {0 {}}
do_test quote-1.2.1 {
  catchsql {SELECT * FROM '@abc'}
} {0 {5 hello}}
do_test quote-1.2.2 {
  catchsql {SELECT * FROM [@abc]}  ;# SqlServer compatibility
} {0 {5 hello}}
do_test quote-1.2.3 {
  catchsql {SELECT * FROM `@abc`}  ;# MySQL compatibility
} {0 {5 hello}}
do_test quote-1.3 {
  catchsql {
    SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.1 {
  catchsql {
    SELECT '!pqr', '#xyz'+5 FROM '@abc'
  }
} {0 {!pqr 5}}
do_test quote-1.3.2 {
  catchsql {
    SELECT "!pqr", "#xyz"+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.3 {
  catchsql {
    SELECT [!pqr], `#xyz`+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.4 {
  set r [catch {
    execsql {SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'}
  } msg ]
  lappend r $msg
} {0 {hello 10}}
do_test quote-1.4 {
  set r [catch {
    execsql {UPDATE '@abc' SET '#xyz'=11}
  } msg ]
  lappend r $msg
} {0 {}}
do_test quote-1.5 {
  set r [catch {
    execsql {SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'}
  } msg ]
  lappend r $msg
} {0 {hello 16}}

# Drop the table with the strange name.
#
do_test quote-1.6 {
  set r [catch {
    execsql {DROP TABLE '@abc'}
  } msg ]
  lappend r $msg
} {0 {}}
 

finish_test

Added test/randexpr1.tcl.













































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# Run this TCL script to generate thousands of test cases containing
# complicated expressions.
#
# The generated tests are intended to verify expression evaluation
# in SQLite against expression evaluation TCL.  
#

# Terms of the $intexpr list each contain two sub-terms.
#
#     *  An SQL expression template
#     *  The equivalent TCL expression
#
# EXPR is replaced by an integer subexpression.  BOOL is replaced
# by a boolean subexpression.
#
set intexpr {
  {11 wide(11)}
  {13 wide(13)}
  {17 wide(17)}
  {19 wide(19)}
  {a $a}
  {b $b}
  {c $c}
  {d $d}
  {e $e}
  {f $f}
  {t1.a $a}
  {t1.b $b}
  {t1.c $c}
  {t1.d $d}
  {t1.e $e}
  {t1.f $f}
  {(EXPR) (EXPR)}
  {{ -EXPR} {-EXPR}}
  {+EXPR +EXPR}
  {~EXPR ~EXPR}
  {EXPR+EXPR EXPR+EXPR}
  {EXPR-EXPR EXPR-EXPR}
  {EXPR*EXPR EXPR*EXPR}
  {EXPR+EXPR EXPR+EXPR}
  {EXPR-EXPR EXPR-EXPR}
  {EXPR*EXPR EXPR*EXPR}
  {EXPR+EXPR EXPR+EXPR}
  {EXPR-EXPR EXPR-EXPR}
  {EXPR*EXPR EXPR*EXPR}
  {{EXPR | EXPR} {EXPR | EXPR}}
  {(abs(EXPR)/abs(EXPR)) (abs(EXPR)/abs(EXPR))}
  {
    {case when BOOL then EXPR else EXPR end}
    {((BOOL)?EXPR:EXPR)}
  }
  {
    {case when BOOL then EXPR when BOOL then EXPR else EXPR end}
    {((BOOL)?EXPR:((BOOL)?EXPR:EXPR))}
  }
  {
    {case EXPR when EXPR then EXPR else EXPR end}
    {(((EXPR)==(EXPR))?EXPR:EXPR)}
  }
  {
    {(select AGG from t1)}
    {(AGG)}
  }
  {
    {coalesce((select max(EXPR) from t1 where BOOL),EXPR)}
    {[coalesce_subquery [expr {EXPR}] [expr {BOOL}] [expr {EXPR}]]}
  }
  {
    {coalesce((select EXPR from t1 where BOOL),EXPR)}
    {[coalesce_subquery [expr {EXPR}] [expr {BOOL}] [expr {EXPR}]]}
  }
}

# The $boolexpr list contains terms that show both an SQL boolean
# expression and its equivalent TCL.
#
set boolexpr {
  {EXPR=EXPR   ((EXPR)==(EXPR))}
  {EXPR<EXPR   ((EXPR)<(EXPR))}
  {EXPR>EXPR   ((EXPR)>(EXPR))}
  {EXPR<=EXPR  ((EXPR)<=(EXPR))}
  {EXPR>=EXPR  ((EXPR)>=(EXPR))}
  {EXPR<>EXPR  ((EXPR)!=(EXPR))}
  {
    {EXPR between EXPR and EXPR}
    {[betweenop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]]}
  }
  {
    {EXPR not between EXPR and EXPR}
    {(![betweenop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]])}
  }
  {
    {EXPR in (EXPR,EXPR,EXPR)}
    {([inop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]])}
  }
  {
    {EXPR not in (EXPR,EXPR,EXPR)}
    {(![inop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]])}
  }
  {
    {EXPR in (select EXPR from t1 union select EXPR from t1)}
    {[inop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]]}
  }
  {
    {EXPR in (select AGG from t1 union select AGG from t1)}
    {[inop [expr {EXPR}] [expr {AGG}] [expr {AGG}]]}
  }
  {
    {exists(select 1 from t1 where BOOL)}
    {(BOOL)}
  }
  {
    {not exists(select 1 from t1 where BOOL)}
    {!(BOOL)}
  }
  {{not BOOL}  !BOOL}
  {{BOOL and BOOL} {BOOL tcland BOOL}}
  {{BOOL or BOOL}  {BOOL || BOOL}}
  {{BOOL and BOOL} {BOOL tcland BOOL}}
  {{BOOL or BOOL}  {BOOL || BOOL}}
  {(BOOL) (BOOL)}
  {(BOOL) (BOOL)}
}

# Aggregate expressions
#
set aggexpr {
  {count(*) wide(1)}
  {{count(distinct EXPR)} {[one {EXPR}]}}
  {{cast(avg(EXPR) AS integer)} (EXPR)}
  {min(EXPR) (EXPR)}
  {max(EXPR) (EXPR)}
  {(AGG) (AGG)}
  {{ -AGG} {-AGG}}
  {+AGG +AGG}
  {~AGG ~AGG}
  {abs(AGG)  abs(AGG)}
  {AGG+AGG   AGG+AGG}
  {AGG-AGG   AGG-AGG}
  {AGG*AGG   AGG*AGG}
  {{AGG | AGG}  {AGG | AGG}}
  {
    {case AGG when AGG then AGG else AGG end}
    {(((AGG)==(AGG))?AGG:AGG)}
  }
}

# Convert a string containing EXPR, AGG, and BOOL into a string
# that contains nothing but X, Y, and Z.
#
proc extract_vars {a} {
  regsub -all {EXPR} $a X a
  regsub -all {AGG} $a Y a
  regsub -all {BOOL} $a Z a
  regsub -all {[^XYZ]} $a {} a
  return $a
}


# Test all templates to make sure the number of EXPR, AGG, and BOOL
# expressions match.
#
foreach term [concat $aggexpr $intexpr $boolexpr] {
  foreach {a b} $term break
  if {[extract_vars $a]!=[extract_vars $b]} {
    error "mismatch: $term"
  }
}

# Generate a random expression according to the templates given above.
# If the argument is EXPR or omitted, then an integer expression is
# generated.  If the argument is BOOL then a boolean expression is
# produced.
#
proc generate_expr {{e EXPR}} {
  set tcle $e
  set ne [llength $::intexpr]
  set nb [llength $::boolexpr]
  set na [llength $::aggexpr]
  set div 2
  set mx 50
  set i 0
  while {1} {
    set cnt 0
    set re [lindex $::intexpr [expr {int(rand()*$ne)}]]
    incr cnt [regsub {EXPR} $e [lindex $re 0] e]
    regsub {EXPR} $tcle [lindex $re 1] tcle
    set rb [lindex $::boolexpr [expr {int(rand()*$nb)}]]
    incr cnt [regsub {BOOL} $e [lindex $rb 0] e]
    regsub {BOOL} $tcle [lindex $rb 1] tcle
    set ra [lindex $::aggexpr [expr {int(rand()*$na)}]]
    incr cnt [regsub {AGG} $e [lindex $ra 0] e]
    regsub {AGG} $tcle [lindex $ra 1] tcle

    if {$cnt==0} break
    incr i $cnt

    set v1 [extract_vars $e]
    if {$v1!=[extract_vars $tcle]} {
      exit
    }

    if {$i+[string length $v1]>=$mx} {
      set ne [expr {$ne/$div}]
      set nb [expr {$nb/$div}]
      set na [expr {$na/$div}]
      set div 1
      set mx [expr {$mx*1000}]
    }
  }
  regsub -all { tcland } $tcle { \&\& } tcle
  return [list $e $tcle]
}

# Implementation of routines used to implement the IN and BETWEEN
# operators.
proc inop {lhs args} {
  foreach a $args {
    if {$a==$lhs} {return 1}
  }
  return 0
}
proc betweenop {lhs first second} {
  return [expr {$lhs>=$first && $lhs<=$second}]
}
proc coalesce_subquery {a b e} {
  if {$b} {
    return $a
  } else {
    return $e
  }
}
proc one {args} {
  return 1
}

# Begin generating the test script:
#
puts {# 2008 December 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file tests randomly generated SQL expressions.  The expressions
# are generated by a TCL script.  The same TCL script also computes the
# correct value of the expression.  So, from one point of view, this
# file verifies the expression evaluation logic of SQLite against the
# expression evaluation logic of TCL.
#
# An early version of this script is how bug #3541 was detected.
#
# $Id: randexpr1.tcl,v 1.1 2008/12/15 16:33:30 drh Exp $
set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create test data
#
do_test randexpr1-1.1 {
  db eval {
    CREATE TABLE t1(a,b,c,d,e,f);
    INSERT INTO t1 VALUES(100,200,300,400,500,600);
    SELECT * FROM t1
  }
} {100 200 300 400 500 600}
}

# Test data for TCL evaluation.
#
set a [expr {wide(100)}]
set b [expr {wide(200)}]
set c [expr {wide(300)}]
set d [expr {wide(400)}]
set e [expr {wide(500)}]
set f [expr {wide(600)}]

# A procedure to generate a test case.
#
set tn 0
proc make_test_case {sql result} {
  global tn
  incr tn
  puts "do_test randexpr-2.$tn {\n  db eval {$sql}\n} {$result}"
}

# Generate many random test cases.
#
expr srand(0)
for {set i 0} {$i<1000} {incr i} {
  while {1} {
    foreach {sqle tcle} [generate_expr EXPR] break;
    if {[catch {expr $tcle} ans]} {
      #puts stderr [list $tcle]
      #puts stderr ans=$ans
      if {![regexp {divide by zero} $ans]} exit
      continue
    }
    set len [string length $sqle]
    if {$len<100 || $len>2000} continue
    if {[info exists seen($sqle)]} continue
    set seen($sqle) 1
    break
  }
  while {1} {
    foreach {sqlb tclb} [generate_expr BOOL] break;
    if {[catch {expr $tclb} bans]} {
      #puts stderr [list $tclb]
      #puts stderr bans=$bans
      if {![regexp {divide by zero} $bans]} exit
      continue
    }
    break
  }
  if {$bans} {
    make_test_case "SELECT $sqle FROM t1 WHERE $sqlb" $ans
    make_test_case "SELECT $sqle FROM t1 WHERE NOT ($sqlb)" {}
  } else {
    make_test_case "SELECT $sqle FROM t1 WHERE $sqlb" {}
    make_test_case "SELECT $sqle FROM t1 WHERE NOT ($sqlb)" $ans
  }
  if {[regexp { \| } $sqle]} {
    regsub -all { \| } $sqle { \& } sqle
    regsub -all { \| } $tcle { \& } tcle
    if {[catch {expr $tcle} ans]==0} {
      if {$bans} {
        make_test_case "SELECT $sqle FROM t1 WHERE $sqlb" $ans
      } else {
        make_test_case "SELECT $sqle FROM t1 WHERE NOT ($sqlb)" $ans
      }
    }
  }
}

# Terminate the test script
#
puts {finish_test}

Added test/randexpr1.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
# 2008 December 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file tests randomly generated SQL expressions.  The expressions
# are generated by a TCL script.  The same TCL script also computes the
# correct value of the expression.  So, from one point of view, this
# file verifies the expression evaluation logic of SQLite against the
# expression evaluation logic of TCL.
#
# An early version of this script is how bug #3541 was detected.
#
# $Id: randexpr1.test,v 1.1 2008/12/15 16:33:30 drh Exp $
set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create test data
#
do_test randexpr1-1.1 {
  db eval {
    CREATE TABLE t1(a,b,c,d,e,f);
    INSERT INTO t1 VALUES(100,200,300,400,500,600);
    SELECT * FROM t1
  }
} {100 200 300 400 500 600}

do_test randexpr-2.1 {
  db eval {SELECT coalesce((select 11 from t1 where 19 in (t1.b,+11,coalesce((select max((abs(17)/abs(t1.f))) from t1 where ((abs(t1.f)/abs(t1.b)) in (select case (min(t1.a | d*d)+(abs(count(*)-count(*)+ -count(*)*max( -t1.c))-max(f))) when  -count(distinct 19) then ((count(*))) else max(13) end from t1 union select count(distinct b) from t1)) or 19 in (t1.a,t1.c,17)),17) | 17)),13) FROM t1 WHERE not not c=a-+(select case ~case  -~+count(distinct (select count(distinct t1.a)*max(13) from t1))+max( -19*f)*max(f)*max(f)* -count(distinct d)-(count(distinct 11)) | max(t1.f)*count(*) when count(distinct b) then count(distinct t1.b) else  -min(t1.f) end*cast(avg(11) AS integer) when max(t1.f) then max(c) else count(*) end from t1)+d}
} {}
do_test randexpr-2.2 {
  db eval {SELECT coalesce((select 11 from t1 where 19 in (t1.b,+11,coalesce((select max((abs(17)/abs(t1.f))) from t1 where ((abs(t1.f)/abs(t1.b)) in (select case (min(t1.a | d*d)+(abs(count(*)-count(*)+ -count(*)*max( -t1.c))-max(f))) when  -count(distinct 19) then ((count(*))) else max(13) end from t1 union select count(distinct b) from t1)) or 19 in (t1.a,t1.c,17)),17) | 17)),13) FROM t1 WHERE NOT (not not c=a-+(select case ~case  -~+count(distinct (select count(distinct t1.a)*max(13) from t1))+max( -19*f)*max(f)*max(f)* -count(distinct d)-(count(distinct 11)) | max(t1.f)*count(*) when count(distinct b) then count(distinct t1.b) else  -min(t1.f) end*cast(avg(11) AS integer) when max(t1.f) then max(c) else count(*) end from t1)+d)}
} {13}
do_test randexpr-2.3 {
  db eval {SELECT coalesce((select 11 from t1 where 19 in (t1.b,+11,coalesce((select max((abs(17)/abs(t1.f))) from t1 where ((abs(t1.f)/abs(t1.b)) in (select case (min(t1.a & d*d)+(abs(count(*)-count(*)+ -count(*)*max( -t1.c))-max(f))) when  -count(distinct 19) then ((count(*))) else max(13) end from t1 union select count(distinct b) from t1)) or 19 in (t1.a,t1.c,17)),17) & 17)),13) FROM t1 WHERE NOT (not not c=a-+(select case ~case  -~+count(distinct (select count(distinct t1.a)*max(13) from t1))+max( -19*f)*max(f)*max(f)* -count(distinct d)-(count(distinct 11)) | max(t1.f)*count(*) when count(distinct b) then count(distinct t1.b) else  -min(t1.f) end*cast(avg(11) AS integer) when max(t1.f) then max(c) else count(*) end from t1)+d)}
} {13}
do_test randexpr-2.4 {
  db eval {SELECT t1.c*19-t1.f*19+coalesce((select 17 from t1 where e in (f,case (select cast(avg(t1.a) AS integer) from t1)-t1.d when coalesce((select +case when not exists(select 1 from t1 where 17<>t1.f and ((a))<t1.b) then t1.c when c not between b and 11 then case when t1.c<f then t1.b when e in (t1.d,t1.d, -e) then d else t1.b end else f end+11 from t1 where exists(select 1 from t1 where t1.f in (select (count(distinct f)) from t1 union select max(11) from t1))),e) then 11 else t1.a end,t1.d)),13)*b+b FROM t1 WHERE ~t1.b<case when t1.b+t1.c in (select  -count(distinct 17+coalesce((select max( -f+t1.c-d) from t1 where (19>=a) and t1.b between f and 13),t1.a))+case abs(+(max(19))) | count(distinct t1.e) | count(distinct 19) when count(*) then (max(a)) else count(distinct d) end from t1 union select (count(*)) from t1) and t1.b>=19 then d when t1.b in (select d from t1 union select c from t1) then t1.e else a end}
} {-2900}
do_test randexpr-2.5 {
  db eval {SELECT t1.c*19-t1.f*19+coalesce((select 17 from t1 where e in (f,case (select cast(avg(t1.a) AS integer) from t1)-t1.d when coalesce((select +case when not exists(select 1 from t1 where 17<>t1.f and ((a))<t1.b) then t1.c when c not between b and 11 then case when t1.c<f then t1.b when e in (t1.d,t1.d, -e) then d else t1.b end else f end+11 from t1 where exists(select 1 from t1 where t1.f in (select (count(distinct f)) from t1 union select max(11) from t1))),e) then 11 else t1.a end,t1.d)),13)*b+b FROM t1 WHERE NOT (~t1.b<case when t1.b+t1.c in (select  -count(distinct 17+coalesce((select max( -f+t1.c-d) from t1 where (19>=a) and t1.b between f and 13),t1.a))+case abs(+(max(19))) | count(distinct t1.e) | count(distinct 19) when count(*) then (max(a)) else count(distinct d) end from t1 union select (count(*)) from t1) and t1.b>=19 then d when t1.b in (select d from t1 union select c from t1) then t1.e else a end)}
} {}
do_test randexpr-2.6 {
  db eval {SELECT case when case when not exists(select 1 from t1 where e not in (~t1.d,+case when t1.c<b then t1.e else t1.a end-11 | t1.f,c) or b in (select cast(avg(b) AS integer)*(~abs((count(*))))* -( -cast(avg(e) AS integer)) from t1 union select min(t1.c) from t1)) then t1.f when not exists(select 1 from t1 where not c<>d) then 17 else t1.e end in (a,t1.e,17) or (not exists(select 1 from t1 where a in (f,t1.c,t1.a))) then 11 else 13 end FROM t1 WHERE t1.b<case when exists(select 1 from t1 where not  -(select min(t1.b*b*t1.a+t1.d)+abs(case count(*) | (cast(avg(c) AS integer)) when max(17) then min(c) else (min(13)) end)+min(e) from t1) not in (t1.c,f-d,11) and c not between (19) and e) then ~13*t1.a when 13 not in (t1.e,c,11) then b else t1.c end*c-t1.d}
} {11}
do_test randexpr-2.7 {
  db eval {SELECT case when case when not exists(select 1 from t1 where e not in (~t1.d,+case when t1.c<b then t1.e else t1.a end-11 | t1.f,c) or b in (select cast(avg(b) AS integer)*(~abs((count(*))))* -( -cast(avg(e) AS integer)) from t1 union select min(t1.c) from t1)) then t1.f when not exists(select 1 from t1 where not c<>d) then 17 else t1.e end in (a,t1.e,17) or (not exists(select 1 from t1 where a in (f,t1.c,t1.a))) then 11 else 13 end FROM t1 WHERE NOT (t1.b<case when exists(select 1 from t1 where not  -(select min(t1.b*b*t1.a+t1.d)+abs(case count(*) | (cast(avg(c) AS integer)) when max(17) then min(c) else (min(13)) end)+min(e) from t1) not in (t1.c,f-d,11) and c not between (19) and e) then ~13*t1.a when 13 not in (t1.e,c,11) then b else t1.c end*c-t1.d)}
} {}
do_test randexpr-2.8 {
  db eval {SELECT case when case when not exists(select 1 from t1 where e not in (~t1.d,+case when t1.c<b then t1.e else t1.a end-11 & t1.f,c) or b in (select cast(avg(b) AS integer)*(~abs((count(*))))* -( -cast(avg(e) AS integer)) from t1 union select min(t1.c) from t1)) then t1.f when not exists(select 1 from t1 where not c<>d) then 17 else t1.e end in (a,t1.e,17) or (not exists(select 1 from t1 where a in (f,t1.c,t1.a))) then 11 else 13 end FROM t1 WHERE t1.b<case when exists(select 1 from t1 where not  -(select min(t1.b*b*t1.a+t1.d)+abs(case count(*) | (cast(avg(c) AS integer)) when max(17) then min(c) else (min(13)) end)+min(e) from t1) not in (t1.c,f-d,11) and c not between (19) and e) then ~13*t1.a when 13 not in (t1.e,c,11) then b else t1.c end*c-t1.d}
} {11}
do_test randexpr-2.9 {
  db eval {SELECT coalesce((select max(11- -19-f-t1.b+a) from t1 where exists(select 1 from t1 where 11-~(d)-c*a*~t1.a-t1.e-t1.e+coalesce((select coalesce((select t1.c from t1 where case (c) when d then e else 11 end=t1.f),t1.d) from t1 where (t1.d)>b), -11) | f+t1.f not in (((c)),b,13))),f) FROM t1 WHERE case when 19+c>=t1.a then t1.c when not case when not exists(select 1 from t1 where +f | b*b*19+19*13-a | case when t1.e not in (t1.f,t1.c,b) then 11 when 17>t1.c then a else e end<>e) then b when 17=t1.e then b else e end<>t1.b then a else d end-t1.b=(13)}
} {}
do_test randexpr-2.10 {
  db eval {SELECT coalesce((select max(11- -19-f-t1.b+a) from t1 where exists(select 1 from t1 where 11-~(d)-c*a*~t1.a-t1.e-t1.e+coalesce((select coalesce((select t1.c from t1 where case (c) when d then e else 11 end=t1.f),t1.d) from t1 where (t1.d)>b), -11) | f+t1.f not in (((c)),b,13))),f) FROM t1 WHERE NOT (case when 19+c>=t1.a then t1.c when not case when not exists(select 1 from t1 where +f | b*b*19+19*13-a | case when t1.e not in (t1.f,t1.c,b) then 11 when 17>t1.c then a else e end<>e) then b when 17=t1.e then b else e end<>t1.b then a else d end-t1.b=(13))}
} {-670}
do_test randexpr-2.11 {
  db eval {SELECT coalesce((select max(11- -19-f-t1.b+a) from t1 where exists(select 1 from t1 where 11-~(d)-c*a*~t1.a-t1.e-t1.e+coalesce((select coalesce((select t1.c from t1 where case (c) when d then e else 11 end=t1.f),t1.d) from t1 where (t1.d)>b), -11) & f+t1.f not in (((c)),b,13))),f) FROM t1 WHERE NOT (case when 19+c>=t1.a then t1.c when not case when not exists(select 1 from t1 where +f | b*b*19+19*13-a | case when t1.e not in (t1.f,t1.c,b) then 11 when 17>t1.c then a else e end<>e) then b when 17=t1.e then b else e end<>t1.b then a else d end-t1.b=(13))}
} {-670}
do_test randexpr-2.12 {
  db eval {SELECT (abs(17)/abs(~case when (abs(t1.c* -(abs(case b | coalesce((select max(17*e*case when 11 in (select t1.b from t1 union select t1.c from t1) then 19 when d between f and t1.e then t1.e else t1.e end | b) from t1 where (13 not in (11,t1.d,e))),e)*a*d when 11 then e else d end*17)/abs(19)))/abs(t1.e))<>e then t1.b else t1.d end*(19))) FROM t1 WHERE exists(select 1 from t1 where t1.d+11 in (case t1.b++c when +a*(+case (select count(*) from t1) when 19 then t1.c else a end) then t1.a else case when (t1.b> -d) and not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs( -f*a+c*11))<>a)) then 13 else 19 end end,17,a)) or c=t1.d}
} {}
do_test randexpr-2.13 {
  db eval {SELECT (abs(17)/abs(~case when (abs(t1.c* -(abs(case b | coalesce((select max(17*e*case when 11 in (select t1.b from t1 union select t1.c from t1) then 19 when d between f and t1.e then t1.e else t1.e end | b) from t1 where (13 not in (11,t1.d,e))),e)*a*d when 11 then e else d end*17)/abs(19)))/abs(t1.e))<>e then t1.b else t1.d end*(19))) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d+11 in (case t1.b++c when +a*(+case (select count(*) from t1) when 19 then t1.c else a end) then t1.a else case when (t1.b> -d) and not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs( -f*a+c*11))<>a)) then 13 else 19 end end,17,a)) or c=t1.d)}
} {0}
do_test randexpr-2.14 {
  db eval {SELECT (abs(17)/abs(~case when (abs(t1.c* -(abs(case b & coalesce((select max(17*e*case when 11 in (select t1.b from t1 union select t1.c from t1) then 19 when d between f and t1.e then t1.e else t1.e end & b) from t1 where (13 not in (11,t1.d,e))),e)*a*d when 11 then e else d end*17)/abs(19)))/abs(t1.e))<>e then t1.b else t1.d end*(19))) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d+11 in (case t1.b++c when +a*(+case (select count(*) from t1) when 19 then t1.c else a end) then t1.a else case when (t1.b> -d) and not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs( -f*a+c*11))<>a)) then 13 else 19 end end,17,a)) or c=t1.d)}
} {0}
do_test randexpr-2.15 {
  db eval {SELECT coalesce((select t1.c from t1 where e not between 19 and b*d or not exists(select 1 from t1 where t1.a not in (case when d not between b+~(t1.d)-case when ((t1.f<=t1.e) and  -11<f) then e*(abs(t1.a)/abs((t1.c))) else c end+b and t1.e then e when not exists(select 1 from t1 where 11<17) then a else t1.f end,(c),c))),t1.d) FROM t1 WHERE t1.c*((select  -count(distinct t1.a) | + -count(distinct t1.b)*cast(avg(a) AS integer)-cast(avg(13) AS integer) | ~abs(min(17)) |  -min(c)*(count(distinct t1.e)) from t1)- -(abs(+t1.b-13)/abs(11)))+t1.f-coalesce((select max(f) from t1 where t1.d between c and t1.a),17)*a in (select 17 from t1 union select  -17 from t1)}
} {}
do_test randexpr-2.16 {
  db eval {SELECT coalesce((select t1.c from t1 where e not between 19 and b*d or not exists(select 1 from t1 where t1.a not in (case when d not between b+~(t1.d)-case when ((t1.f<=t1.e) and  -11<f) then e*(abs(t1.a)/abs((t1.c))) else c end+b and t1.e then e when not exists(select 1 from t1 where 11<17) then a else t1.f end,(c),c))),t1.d) FROM t1 WHERE NOT (t1.c*((select  -count(distinct t1.a) | + -count(distinct t1.b)*cast(avg(a) AS integer)-cast(avg(13) AS integer) | ~abs(min(17)) |  -min(c)*(count(distinct t1.e)) from t1)- -(abs(+t1.b-13)/abs(11)))+t1.f-coalesce((select max(f) from t1 where t1.d between c and t1.a),17)*a in (select 17 from t1 union select  -17 from t1))}
} {400}
do_test randexpr-2.17 {
  db eval {SELECT +t1.f*~t1.c-coalesce((select max(~b) from t1 where t1.e+11-(abs(e+case d when b then case when f=(13) then (abs(13+b*t1.f)/abs(t1.c)) when d<=t1.e then 13 else a end else 19 end*13+f)/abs((a)))*17<=c),b)-13*c FROM t1 WHERE not exists(select 1 from t1 where coalesce((select max(case when case when exists(select 1 from t1 where ~t1.d+d in (select ~count(distinct 13) from t1 union select count(*)+~abs(+(~min(t1.a))) from t1)) then t1.e+t1.c else  -(abs(t1.d)/abs(coalesce((select max(t1.d) from t1 where d not in (17,f,f)),11)*t1.c)) end<=(11) then 19 else (t1.e) end) from t1 where (13=11)),c) not between 13 and 19)}
} {}
do_test randexpr-2.18 {
  db eval {SELECT +t1.f*~t1.c-coalesce((select max(~b) from t1 where t1.e+11-(abs(e+case d when b then case when f=(13) then (abs(13+b*t1.f)/abs(t1.c)) when d<=t1.e then 13 else a end else 19 end*13+f)/abs((a)))*17<=c),b)-13*c FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select max(case when case when exists(select 1 from t1 where ~t1.d+d in (select ~count(distinct 13) from t1 union select count(*)+~abs(+(~min(t1.a))) from t1)) then t1.e+t1.c else  -(abs(t1.d)/abs(coalesce((select max(t1.d) from t1 where d not in (17,f,f)),11)*t1.c)) end<=(11) then 19 else (t1.e) end) from t1 where (13=11)),c) not between 13 and 19))}
} {-184299}
do_test randexpr-2.19 {
  db eval {SELECT case when (a not in (t1.e,(+case when t1.b<=(abs(coalesce((select max(a+(select count(distinct (select max(((abs( -t1.d)/abs(a))) | t1.c)*min(t1.e) from t1)) from t1)) from t1 where +t1.f>e),17))/abs( - -17)) then 17 else t1.d end-t1.b-d) |  -f,c)) then 11-t1.f when ( -13<e) then t1.d else a end FROM t1 WHERE t1.c not between ~case when case when (select  - -abs( -case  -count(distinct c) when count(*) then max(c) else count(distinct 13) end) | min(c) from t1) in (t1.f,b+11,19*t1.d) then 19 else a end*t1.b>13 or t1.e in (select (count(*)) from t1 union select cast(avg(t1.e) AS integer) from t1) or 19>17 and 13 not between 19 and 17 then (t1.f) when not t1.b<>t1.f or d<>b then t1.e else a end and c}
} {}
do_test randexpr-2.20 {
  db eval {SELECT case when (a not in (t1.e,(+case when t1.b<=(abs(coalesce((select max(a+(select count(distinct (select max(((abs( -t1.d)/abs(a))) | t1.c)*min(t1.e) from t1)) from t1)) from t1 where +t1.f>e),17))/abs( - -17)) then 17 else t1.d end-t1.b-d) |  -f,c)) then 11-t1.f when ( -13<e) then t1.d else a end FROM t1 WHERE NOT (t1.c not between ~case when case when (select  - -abs( -case  -count(distinct c) when count(*) then max(c) else count(distinct 13) end) | min(c) from t1) in (t1.f,b+11,19*t1.d) then 19 else a end*t1.b>13 or t1.e in (select (count(*)) from t1 union select cast(avg(t1.e) AS integer) from t1) or 19>17 and 13 not between 19 and 17 then (t1.f) when not t1.b<>t1.f or d<>b then t1.e else a end and c)}
} {-589}
do_test randexpr-2.21 {
  db eval {SELECT case when (a not in (t1.e,(+case when t1.b<=(abs(coalesce((select max(a+(select count(distinct (select max(((abs( -t1.d)/abs(a))) & t1.c)*min(t1.e) from t1)) from t1)) from t1 where +t1.f>e),17))/abs( - -17)) then 17 else t1.d end-t1.b-d) &  -f,c)) then 11-t1.f when ( -13<e) then t1.d else a end FROM t1 WHERE NOT (t1.c not between ~case when case when (select  - -abs( -case  -count(distinct c) when count(*) then max(c) else count(distinct 13) end) | min(c) from t1) in (t1.f,b+11,19*t1.d) then 19 else a end*t1.b>13 or t1.e in (select (count(*)) from t1 union select cast(avg(t1.e) AS integer) from t1) or 19>17 and 13 not between 19 and 17 then (t1.f) when not t1.b<>t1.f or d<>b then t1.e else a end and c)}
} {-589}
do_test randexpr-2.22 {
  db eval {SELECT t1.a | case when e in (select (13) from t1 union select d from t1) then (17) when c*~case (17) when coalesce((select max(case when case when 19 in (13,t1.f,11) then t1.b else t1.b end | 11>t1.a then 11 else t1.b end-b) from t1 where (13 not in (a,19,b)) and t1.a not between  -11 and t1.f),f) then e else t1.c end | a in (select 11 from t1 union select t1.d from t1) then 17 else t1.a end | f FROM t1 WHERE coalesce((select t1.a*t1.a from t1 where ~ -(abs((select abs(count(*))-count(distinct t1.d*11) from t1)*+b)/abs(~t1.c))+c not in (coalesce((select ~13*t1.a from t1 where f+(abs(d* -t1.f)/abs(t1.c))<=t1.b or not t1.a<=t1.c),t1.c),e,(t1.e))),(a))+11<>11}
} {636}
do_test randexpr-2.23 {
  db eval {SELECT t1.a | case when e in (select (13) from t1 union select d from t1) then (17) when c*~case (17) when coalesce((select max(case when case when 19 in (13,t1.f,11) then t1.b else t1.b end | 11>t1.a then 11 else t1.b end-b) from t1 where (13 not in (a,19,b)) and t1.a not between  -11 and t1.f),f) then e else t1.c end | a in (select 11 from t1 union select t1.d from t1) then 17 else t1.a end | f FROM t1 WHERE NOT (coalesce((select t1.a*t1.a from t1 where ~ -(abs((select abs(count(*))-count(distinct t1.d*11) from t1)*+b)/abs(~t1.c))+c not in (coalesce((select ~13*t1.a from t1 where f+(abs(d* -t1.f)/abs(t1.c))<=t1.b or not t1.a<=t1.c),t1.c),e,(t1.e))),(a))+11<>11)}
} {}
do_test randexpr-2.24 {
  db eval {SELECT t1.a & case when e in (select (13) from t1 union select d from t1) then (17) when c*~case (17) when coalesce((select max(case when case when 19 in (13,t1.f,11) then t1.b else t1.b end & 11>t1.a then 11 else t1.b end-b) from t1 where (13 not in (a,19,b)) and t1.a not between  -11 and t1.f),f) then e else t1.c end & a in (select 11 from t1 union select t1.d from t1) then 17 else t1.a end & f FROM t1 WHERE coalesce((select t1.a*t1.a from t1 where ~ -(abs((select abs(count(*))-count(distinct t1.d*11) from t1)*+b)/abs(~t1.c))+c not in (coalesce((select ~13*t1.a from t1 where f+(abs(d* -t1.f)/abs(t1.c))<=t1.b or not t1.a<=t1.c),t1.c),e,(t1.e))),(a))+11<>11}
} {64}
do_test randexpr-2.25 {
  db eval {SELECT c*coalesce((select ~19-e from t1 where not exists(select 1 from t1 where case when t1.b<>(d) then case when exists(select 1 from t1 where not exists(select 1 from t1 where case t1.e when e*(11) then 13 else 11 end in (select t1.a from t1 union select 13 from t1))) then coalesce((select case when f in (select t1.c from t1 union select (t1.b) from t1) then f else a end from t1 where t1.f not between 17 and f), -f) else 11 end else (a) end*d not in (e,t1.c,t1.e))),t1.e)-a FROM t1 WHERE 19+(select cast(avg((abs(t1.d)/abs(coalesce((select max(+b-(t1.e+b+ -c)*19) from t1 where 11 not between t1.b and f), -17)))*(11)) AS integer) from t1)*f in (select count(*) from t1 union select case max(t1.d)-( -min(t1.d)*(+max(e))) when max(t1.a) then cast(avg(t1.d) AS integer)-(count(distinct t1.f))-( -cast(avg(f) AS integer)) else max(t1.e) end from t1)}
} {}
do_test randexpr-2.26 {
  db eval {SELECT c*coalesce((select ~19-e from t1 where not exists(select 1 from t1 where case when t1.b<>(d) then case when exists(select 1 from t1 where not exists(select 1 from t1 where case t1.e when e*(11) then 13 else 11 end in (select t1.a from t1 union select 13 from t1))) then coalesce((select case when f in (select t1.c from t1 union select (t1.b) from t1) then f else a end from t1 where t1.f not between 17 and f), -f) else 11 end else (a) end*d not in (e,t1.c,t1.e))),t1.e)-a FROM t1 WHERE NOT (19+(select cast(avg((abs(t1.d)/abs(coalesce((select max(+b-(t1.e+b+ -c)*19) from t1 where 11 not between t1.b and f), -17)))*(11)) AS integer) from t1)*f in (select count(*) from t1 union select case max(t1.d)-( -min(t1.d)*(+max(e))) when max(t1.a) then cast(avg(t1.d) AS integer)-(count(distinct t1.f))-( -cast(avg(f) AS integer)) else max(t1.e) end from t1))}
} {149900}
do_test randexpr-2.27 {
  db eval {SELECT (abs((select (case abs(min(t1.f)) | count(distinct e) when (~+count(*)+max(e)++abs(cast(avg(~19) AS integer))) then +cast(avg(c) AS integer) else ~ -max(+t1.b)+~max(19)*count(distinct a)*min(17) | max(t1.d) end) from t1))/abs(~c+(select  -(count(distinct t1.e)) from t1)-11+t1.e)) FROM t1 WHERE 11>=t1.f}
} {}
do_test randexpr-2.28 {
  db eval {SELECT (abs((select (case abs(min(t1.f)) | count(distinct e) when (~+count(*)+max(e)++abs(cast(avg(~19) AS integer))) then +cast(avg(c) AS integer) else ~ -max(+t1.b)+~max(19)*count(distinct a)*min(17) | max(t1.d) end) from t1))/abs(~c+(select  -(count(distinct t1.e)) from t1)-11+t1.e)) FROM t1 WHERE NOT (11>=t1.f)}
} {0}
do_test randexpr-2.29 {
  db eval {SELECT (abs((select (case abs(min(t1.f)) & count(distinct e) when (~+count(*)+max(e)++abs(cast(avg(~19) AS integer))) then +cast(avg(c) AS integer) else ~ -max(+t1.b)+~max(19)*count(distinct a)*min(17) & max(t1.d) end) from t1))/abs(~c+(select  -(count(distinct t1.e)) from t1)-11+t1.e)) FROM t1 WHERE NOT (11>=t1.f)}
} {1}
do_test randexpr-2.30 {
  db eval {SELECT (select +count(distinct case when 11=a or e<+t1.f+t1.c and not exists(select 1 from t1 where not t1.a-t1.b=~a and f<=coalesce((select max((e)) from t1 where +t1.f>=b),t1.d)*13) and t1.c>t1.e and t1.a<17 then f when a<c then t1.d else c end) from t1) FROM t1 WHERE t1.b=case t1.e | f+t1.d when case when t1.f | t1.e in (select  -+min(case when t1.c in (select t1.b from t1 union select b-19*(abs(b)/abs(t1.b*case when not exists(select 1 from t1 where t1.a in (select ~cast(avg(d) AS integer) from t1 union select max(t1.f) from t1)) then ~(13) when  -c=t1.b then t1.c else f end)) from t1) then e else 17 end) from t1 union select max((a)) from t1) then  -b else t1.d end+13 then a else 13 end}
} {}
do_test randexpr-2.31 {
  db eval {SELECT (select +count(distinct case when 11=a or e<+t1.f+t1.c and not exists(select 1 from t1 where not t1.a-t1.b=~a and f<=coalesce((select max((e)) from t1 where +t1.f>=b),t1.d)*13) and t1.c>t1.e and t1.a<17 then f when a<c then t1.d else c end) from t1) FROM t1 WHERE NOT (t1.b=case t1.e | f+t1.d when case when t1.f | t1.e in (select  -+min(case when t1.c in (select t1.b from t1 union select b-19*(abs(b)/abs(t1.b*case when not exists(select 1 from t1 where t1.a in (select ~cast(avg(d) AS integer) from t1 union select max(t1.f) from t1)) then ~(13) when  -c=t1.b then t1.c else f end)) from t1) then e else 17 end) from t1 union select max((a)) from t1) then  -b else t1.d end+13 then a else 13 end)}
} {1}
do_test randexpr-2.32 {
  db eval {SELECT coalesce((select (select max(t1.a)*(max(a))*max(t1.f*~11*case when b not in ((select min(19) from t1),b,coalesce((select max((t1.f)) from t1 where t1.c in (c,t1.b,(t1.f)) or t1.a<>(c)),b)*t1.b-t1.b) then d else t1.e end | f* -13-c) from t1) from t1 where not ~a<f), -19)+t1.d+b FROM t1 WHERE 13*t1.d between coalesce((select t1.d from t1 where b in (select t1.d from t1 union select case b*t1.f+t1.a*+coalesce((select t1.a from t1 where (not exists(select 1 from t1 where b*t1.c=13))),11)+t1.e when ~f then d+case b when e then f else t1.e end*13 else f end from t1)),19) and t1.d and 19 between 17 and e and a>a}
} {}
do_test randexpr-2.33 {
  db eval {SELECT coalesce((select (select max(t1.a)*(max(a))*max(t1.f*~11*case when b not in ((select min(19) from t1),b,coalesce((select max((t1.f)) from t1 where t1.c in (c,t1.b,(t1.f)) or t1.a<>(c)),b)*t1.b-t1.b) then d else t1.e end | f* -13-c) from t1) from t1 where not ~a<f), -19)+t1.d+b FROM t1 WHERE NOT (13*t1.d between coalesce((select t1.d from t1 where b in (select t1.d from t1 union select case b*t1.f+t1.a*+coalesce((select t1.a from t1 where (not exists(select 1 from t1 where b*t1.c=13))),11)+t1.e when ~f then d+case b when e then f else t1.e end*13 else f end from t1)),19) and t1.d and 19 between 17 and e and a>a)}
} {581}
do_test randexpr-2.34 {
  db eval {SELECT coalesce((select (select max(t1.a)*(max(a))*max(t1.f*~11*case when b not in ((select min(19) from t1),b,coalesce((select max((t1.f)) from t1 where t1.c in (c,t1.b,(t1.f)) or t1.a<>(c)),b)*t1.b-t1.b) then d else t1.e end & f* -13-c) from t1) from t1 where not ~a<f), -19)+t1.d+b FROM t1 WHERE NOT (13*t1.d between coalesce((select t1.d from t1 where b in (select t1.d from t1 union select case b*t1.f+t1.a*+coalesce((select t1.a from t1 where (not exists(select 1 from t1 where b*t1.c=13))),11)+t1.e when ~f then d+case b when e then f else t1.e end*13 else f end from t1)),19) and t1.d and 19 between 17 and e and a>a)}
} {581}
do_test randexpr-2.35 {
  db eval {SELECT case when t1.d not in (t1.d,coalesce((select max(11) from t1 where f not between 13 and c-coalesce((select max(d) from t1 where 19 not in ((t1.f),f,11)),t1.d)*t1.e | a),13), -(t1.e)) then t1.b when t1.f=t1.a and exists(select 1 from t1 where b in (select c from t1 union select 11 from t1) and t1.c=b and not  -d in (t1.d,t1.d,t1.b) and d between 11 and c) or d<=17 or a not in (e,19,(t1.b)) then 17 else 11 end FROM t1 WHERE a<>f+f}
} {17}
do_test randexpr-2.36 {
  db eval {SELECT case when t1.d not in (t1.d,coalesce((select max(11) from t1 where f not between 13 and c-coalesce((select max(d) from t1 where 19 not in ((t1.f),f,11)),t1.d)*t1.e | a),13), -(t1.e)) then t1.b when t1.f=t1.a and exists(select 1 from t1 where b in (select c from t1 union select 11 from t1) and t1.c=b and not  -d in (t1.d,t1.d,t1.b) and d between 11 and c) or d<=17 or a not in (e,19,(t1.b)) then 17 else 11 end FROM t1 WHERE NOT (a<>f+f)}
} {}
do_test randexpr-2.37 {
  db eval {SELECT case when t1.d not in (t1.d,coalesce((select max(11) from t1 where f not between 13 and c-coalesce((select max(d) from t1 where 19 not in ((t1.f),f,11)),t1.d)*t1.e & a),13), -(t1.e)) then t1.b when t1.f=t1.a and exists(select 1 from t1 where b in (select c from t1 union select 11 from t1) and t1.c=b and not  -d in (t1.d,t1.d,t1.b) and d between 11 and c) or d<=17 or a not in (e,19,(t1.b)) then 17 else 11 end FROM t1 WHERE a<>f+f}
} {17}
do_test randexpr-2.38 {
  db eval {SELECT case 13 when coalesce((select t1.a*d+++b | b+(abs(t1.e)/abs(c))+(select count(*) from t1) from t1 where not exists(select 1 from t1 where 17 in (select d from t1 union select t1.f from t1))),t1.b) then ~t1.c-(select case min(case when 17 not in (19,19,t1.c) then c when 13 between (19) and t1.e then e else 19 end-19) when cast(avg( -11) AS integer) then max(t1.c)* -min(t1.d) else (count(distinct t1.f)) end from t1) | +t1.f else t1.c end FROM t1 WHERE coalesce((select max(t1.c) from t1 where (abs(t1.b)/abs(a))>=(e)),+ -case when (11<17) then t1.a when t1.a*e=19* -11 and not exists(select 1 from t1 where  -t1.d not between coalesce((select a from t1 where  -t1.c>t1.e), -19) and t1.d and not exists(select 1 from t1 where (t1.e) in (select d from t1 union select t1.c from t1))) then c else a end*a)-t1.b* -(b) in (e,d,b)}
} {}
do_test randexpr-2.39 {
  db eval {SELECT case 13 when coalesce((select t1.a*d+++b | b+(abs(t1.e)/abs(c))+(select count(*) from t1) from t1 where not exists(select 1 from t1 where 17 in (select d from t1 union select t1.f from t1))),t1.b) then ~t1.c-(select case min(case when 17 not in (19,19,t1.c) then c when 13 between (19) and t1.e then e else 19 end-19) when cast(avg( -11) AS integer) then max(t1.c)* -min(t1.d) else (count(distinct t1.f)) end from t1) | +t1.f else t1.c end FROM t1 WHERE NOT (coalesce((select max(t1.c) from t1 where (abs(t1.b)/abs(a))>=(e)),+ -case when (11<17) then t1.a when t1.a*e=19* -11 and not exists(select 1 from t1 where  -t1.d not between coalesce((select a from t1 where  -t1.c>t1.e), -19) and t1.d and not exists(select 1 from t1 where (t1.e) in (select d from t1 union select t1.c from t1))) then c else a end*a)-t1.b* -(b) in (e,d,b))}
} {300}
do_test randexpr-2.40 {
  db eval {SELECT case 13 when coalesce((select t1.a*d+++b & b+(abs(t1.e)/abs(c))+(select count(*) from t1) from t1 where not exists(select 1 from t1 where 17 in (select d from t1 union select t1.f from t1))),t1.b) then ~t1.c-(select case min(case when 17 not in (19,19,t1.c) then c when 13 between (19) and t1.e then e else 19 end-19) when cast(avg( -11) AS integer) then max(t1.c)* -min(t1.d) else (count(distinct t1.f)) end from t1) & +t1.f else t1.c end FROM t1 WHERE NOT (coalesce((select max(t1.c) from t1 where (abs(t1.b)/abs(a))>=(e)),+ -case when (11<17) then t1.a when t1.a*e=19* -11 and not exists(select 1 from t1 where  -t1.d not between coalesce((select a from t1 where  -t1.c>t1.e), -19) and t1.d and not exists(select 1 from t1 where (t1.e) in (select d from t1 union select t1.c from t1))) then c else a end*a)-t1.b* -(b) in (e,d,b))}
} {300}
do_test randexpr-2.41 {
  db eval {SELECT case when not exists(select 1 from t1 where ( -case when b in ((11),coalesce((select f from t1 where (not exists(select 1 from t1 where coalesce((select (t1.a) from t1 where e<=a),11) in (select t1.f from t1 union select 13 from t1)) or t1.a>d)),t1.a),t1.e) or not not exists(select 1 from t1 where (t1.f<=(t1.a))) then e*t1.a else t1.c end)<=d and not (t1.e)>=t1.e) then coalesce((select max( -t1.e) from t1 where t1.d between t1.b and t1.c),t1.d) else t1.c end+13*13 FROM t1 WHERE t1.b=t1.f | 19+coalesce((select max(a) from t1 where case t1.e when case when (11<=11 | t1.f and b>=b or t1.f<=a) then case when c between t1.e and b then e else +t1.f end else  -t1.c end then t1.b else 13 end*13 between t1.f and c and exists(select 1 from t1 where (b not between 11 and a)) and f>=t1.b), -t1.b)-c}
} {}
do_test randexpr-2.42 {
  db eval {SELECT case when not exists(select 1 from t1 where ( -case when b in ((11),coalesce((select f from t1 where (not exists(select 1 from t1 where coalesce((select (t1.a) from t1 where e<=a),11) in (select t1.f from t1 union select 13 from t1)) or t1.a>d)),t1.a),t1.e) or not not exists(select 1 from t1 where (t1.f<=(t1.a))) then e*t1.a else t1.c end)<=d and not (t1.e)>=t1.e) then coalesce((select max( -t1.e) from t1 where t1.d between t1.b and t1.c),t1.d) else t1.c end+13*13 FROM t1 WHERE NOT (t1.b=t1.f | 19+coalesce((select max(a) from t1 where case t1.e when case when (11<=11 | t1.f and b>=b or t1.f<=a) then case when c between t1.e and b then e else +t1.f end else  -t1.c end then t1.b else 13 end*13 between t1.f and c and exists(select 1 from t1 where (b not between 11 and a)) and f>=t1.b), -t1.b)-c)}
} {569}
do_test randexpr-2.43 {
  db eval {SELECT coalesce((select c from t1 where t1.a=case when a=t1.b+~(select case cast(avg( -b*13) AS integer) when max(f*13* -c) then (cast(avg(t1.d) AS integer)) else count(distinct t1.e*c) end from t1) then t1.d | t1.a else case when t1.a-b not between e and  -t1.c* -13 then 19 else d end end),d) | t1.d FROM t1 WHERE +13 in (f,t1.f+t1.f, -coalesce((select max(t1.f) from t1 where (t1.a-13)<=(case (select count(*) from t1) when 13 then  -+t1.e |  -(coalesce((select max(~coalesce((select ( -13) from t1 where  -c<(11) or 11 between a and t1.d),13)*t1.d) from t1 where d not between b and 13),19))*t1.a else 13 end-b-c)),t1.e)-19)}
} {}
do_test randexpr-2.44 {
  db eval {SELECT coalesce((select c from t1 where t1.a=case when a=t1.b+~(select case cast(avg( -b*13) AS integer) when max(f*13* -c) then (cast(avg(t1.d) AS integer)) else count(distinct t1.e*c) end from t1) then t1.d | t1.a else case when t1.a-b not between e and  -t1.c* -13 then 19 else d end end),d) | t1.d FROM t1 WHERE NOT (+13 in (f,t1.f+t1.f, -coalesce((select max(t1.f) from t1 where (t1.a-13)<=(case (select count(*) from t1) when 13 then  -+t1.e |  -(coalesce((select max(~coalesce((select ( -13) from t1 where  -c<(11) or 11 between a and t1.d),13)*t1.d) from t1 where d not between b and 13),19))*t1.a else 13 end-b-c)),t1.e)-19))}
} {400}
do_test randexpr-2.45 {
  db eval {SELECT coalesce((select c from t1 where t1.a=case when a=t1.b+~(select case cast(avg( -b*13) AS integer) when max(f*13* -c) then (cast(avg(t1.d) AS integer)) else count(distinct t1.e*c) end from t1) then t1.d & t1.a else case when t1.a-b not between e and  -t1.c* -13 then 19 else d end end),d) & t1.d FROM t1 WHERE NOT (+13 in (f,t1.f+t1.f, -coalesce((select max(t1.f) from t1 where (t1.a-13)<=(case (select count(*) from t1) when 13 then  -+t1.e |  -(coalesce((select max(~coalesce((select ( -13) from t1 where  -c<(11) or 11 between a and t1.d),13)*t1.d) from t1 where d not between b and 13),19))*t1.a else 13 end-b-c)),t1.e)-19))}
} {400}
do_test randexpr-2.46 {
  db eval {SELECT case ~11-13 when 11-d-case when t1.f*+a-t1.a-t1.f=t1.a then a when t1.f between 19-t1.a+coalesce((select a from t1 where e in (select case  -max(t1.c) when count(*) then max(t1.d) else  -(cast(avg((t1.e)) AS integer)) end from t1 union select (max(t1.b)) from t1)), -b) and e or ((11<c)) or e>=t1.d then t1.b else a end+13+(t1.c) then a else  -d end FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where (not +t1.b-~a*(d*t1.e | + -coalesce((select t1.c from t1 where t1.b*case t1.b when f then  -a*b else e end<>a+t1.a),17))+e*t1.e*11 | t1.a not between 13 and  -t1.a and b between d and  -f)))}
} {-400}
do_test randexpr-2.47 {
  db eval {SELECT case ~11-13 when 11-d-case when t1.f*+a-t1.a-t1.f=t1.a then a when t1.f between 19-t1.a+coalesce((select a from t1 where e in (select case  -max(t1.c) when count(*) then max(t1.d) else  -(cast(avg((t1.e)) AS integer)) end from t1 union select (max(t1.b)) from t1)), -b) and e or ((11<c)) or e>=t1.d then t1.b else a end+13+(t1.c) then a else  -d end FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where (not +t1.b-~a*(d*t1.e | + -coalesce((select t1.c from t1 where t1.b*case t1.b when f then  -a*b else e end<>a+t1.a),17))+e*t1.e*11 | t1.a not between 13 and  -t1.a and b between d and  -f))))}
} {}
do_test randexpr-2.48 {
  db eval {SELECT 11++(case 19 when t1.c-19-coalesce((select t1.b from t1 where e*19-t1.e<=+case when c in (select 19 | 17 from t1 union select 11 from t1) then (abs(a)/abs(19)) when a*t1.d>19 or (11) not in (b,t1.a,t1.a) then b else b end-11),f) then 13 else 11 end-t1.e*a) FROM t1 WHERE f in (17,t1.f | coalesce((select max(t1.e) from t1 where not 17 in (select f from t1 union select +17 from t1)),b+coalesce((select max(b) from t1 where 19 in (select case min(t1.d) when (count(*)) then min(d) else  -min(d) end from t1 union select max(d) from t1)),f)*f-17+19),b) or d<=f or t1.f>=11 or t1.b<=11 or t1.c<=11 or t1.b<=b}
} {-49978}
do_test randexpr-2.49 {
  db eval {SELECT 11++(case 19 when t1.c-19-coalesce((select t1.b from t1 where e*19-t1.e<=+case when c in (select 19 | 17 from t1 union select 11 from t1) then (abs(a)/abs(19)) when a*t1.d>19 or (11) not in (b,t1.a,t1.a) then b else b end-11),f) then 13 else 11 end-t1.e*a) FROM t1 WHERE NOT (f in (17,t1.f | coalesce((select max(t1.e) from t1 where not 17 in (select f from t1 union select +17 from t1)),b+coalesce((select max(b) from t1 where 19 in (select case min(t1.d) when (count(*)) then min(d) else  -min(d) end from t1 union select max(d) from t1)),f)*f-17+19),b) or d<=f or t1.f>=11 or t1.b<=11 or t1.c<=11 or t1.b<=b)}
} {}
do_test randexpr-2.50 {
  db eval {SELECT 11++(case 19 when t1.c-19-coalesce((select t1.b from t1 where e*19-t1.e<=+case when c in (select 19 & 17 from t1 union select 11 from t1) then (abs(a)/abs(19)) when a*t1.d>19 or (11) not in (b,t1.a,t1.a) then b else b end-11),f) then 13 else 11 end-t1.e*a) FROM t1 WHERE f in (17,t1.f | coalesce((select max(t1.e) from t1 where not 17 in (select f from t1 union select +17 from t1)),b+coalesce((select max(b) from t1 where 19 in (select case min(t1.d) when (count(*)) then min(d) else  -min(d) end from t1 union select max(d) from t1)),f)*f-17+19),b) or d<=f or t1.f>=11 or t1.b<=11 or t1.c<=11 or t1.b<=b}
} {-49978}
do_test randexpr-2.51 {
  db eval {SELECT  -c-coalesce((select max(t1.a) from t1 where (a>17-t1.a) and (select abs(min(t1.a))*case abs(case (((min((t1.c))))+min(a)) when count(distinct f) then min(11) else count(distinct b) end) when min(t1.f) then (count(distinct t1.b)) else  -count(*) end from t1)<>case d when +(select ((min(t1.a))) from t1)-(abs(c)/abs(f)) then b else 17 end+t1.c),coalesce((select t1.d from t1 where d>19),t1.a)) FROM t1 WHERE b+(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.b<=c-(select ~~max((abs(e)/abs(13 | (t1.e)-c-19))) from t1) or d in (select t1.b from t1 union select d from t1)) or 13 in (select cast(avg(19) AS integer) from t1 union select ( -cast(avg(19) AS integer) | count(*)*min(19)) from t1) or 19<=11),t1.c))-t1.d-c>f}
} {}
do_test randexpr-2.52 {
  db eval {SELECT  -c-coalesce((select max(t1.a) from t1 where (a>17-t1.a) and (select abs(min(t1.a))*case abs(case (((min((t1.c))))+min(a)) when count(distinct f) then min(11) else count(distinct b) end) when min(t1.f) then (count(distinct t1.b)) else  -count(*) end from t1)<>case d when +(select ((min(t1.a))) from t1)-(abs(c)/abs(f)) then b else 17 end+t1.c),coalesce((select t1.d from t1 where d>19),t1.a)) FROM t1 WHERE NOT (b+(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.b<=c-(select ~~max((abs(e)/abs(13 | (t1.e)-c-19))) from t1) or d in (select t1.b from t1 union select d from t1)) or 13 in (select cast(avg(19) AS integer) from t1 union select ( -cast(avg(19) AS integer) | count(*)*min(19)) from t1) or 19<=11),t1.c))-t1.d-c>f)}
} {-400}
do_test randexpr-2.53 {
  db eval {SELECT case when t1.b+coalesce((select max(a) from t1 where exists(select 1 from t1 where not not t1.d>19)),13) | case when f in (select a from t1 union select case when (a)<>t1.c then c when not exists(select 1 from t1 where t1.c not between 17 and  -(t1.d)) then f else (11) end from t1) then t1.c when (not exists(select 1 from t1 where 17 not between t1.f and a)) and d=b then t1.c else d end<=19 and (t1.c<>c and (13) not between t1.d and t1.c) and a>= -b or 11>13 and c<>13 then  -f else d end FROM t1 WHERE (case when (17 not in (f*11,+coalesce((select max(b-b) from t1 where t1.c+f not between 11 and t1.d),13),c)) or (t1.e in (select ~min(t1.f) from t1 union select ~count(*) from t1) and exists(select 1 from t1 where (not f>=19 and 17 not between a and t1.e)) or (e) not in (e,d,13) or t1.d>=f) then e when 17 between t1.c and 13 then case when 11<>19 then t1.d else t1.a end else b end in (select  -t1.a from t1 union select a from t1))}
} {}
do_test randexpr-2.54 {
  db eval {SELECT case when t1.b+coalesce((select max(a) from t1 where exists(select 1 from t1 where not not t1.d>19)),13) | case when f in (select a from t1 union select case when (a)<>t1.c then c when not exists(select 1 from t1 where t1.c not between 17 and  -(t1.d)) then f else (11) end from t1) then t1.c when (not exists(select 1 from t1 where 17 not between t1.f and a)) and d=b then t1.c else d end<=19 and (t1.c<>c and (13) not between t1.d and t1.c) and a>= -b or 11>13 and c<>13 then  -f else d end FROM t1 WHERE NOT ((case when (17 not in (f*11,+coalesce((select max(b-b) from t1 where t1.c+f not between 11 and t1.d),13),c)) or (t1.e in (select ~min(t1.f) from t1 union select ~count(*) from t1) and exists(select 1 from t1 where (not f>=19 and 17 not between a and t1.e)) or (e) not in (e,d,13) or t1.d>=f) then e when 17 between t1.c and 13 then case when 11<>19 then t1.d else t1.a end else b end in (select  -t1.a from t1 union select a from t1)))}
} {400}
do_test randexpr-2.55 {
  db eval {SELECT case when t1.b+coalesce((select max(a) from t1 where exists(select 1 from t1 where not not t1.d>19)),13) & case when f in (select a from t1 union select case when (a)<>t1.c then c when not exists(select 1 from t1 where t1.c not between 17 and  -(t1.d)) then f else (11) end from t1) then t1.c when (not exists(select 1 from t1 where 17 not between t1.f and a)) and d=b then t1.c else d end<=19 and (t1.c<>c and (13) not between t1.d and t1.c) and a>= -b or 11>13 and c<>13 then  -f else d end FROM t1 WHERE NOT ((case when (17 not in (f*11,+coalesce((select max(b-b) from t1 where t1.c+f not between 11 and t1.d),13),c)) or (t1.e in (select ~min(t1.f) from t1 union select ~count(*) from t1) and exists(select 1 from t1 where (not f>=19 and 17 not between a and t1.e)) or (e) not in (e,d,13) or t1.d>=f) then e when 17 between t1.c and 13 then case when 11<>19 then t1.d else t1.a end else b end in (select  -t1.a from t1 union select a from t1)))}
} {400}
do_test randexpr-2.56 {
  db eval {SELECT t1.e+case when d not between f and case when a in (select t1.c from t1 union select t1.e from t1) or coalesce((select 19 from t1 where 17<=t1.d or 19*t1.f*t1.b<>t1.d | t1.d | t1.a),t1.b)*case when (t1.a) in (t1.d,t1.a,a) then  -c when 17<13 then t1.f else 17 end-t1.f*e not in (19,t1.d,17) then 19 else t1.e end then  -b else t1.b end FROM t1 WHERE (coalesce((select t1.d-coalesce((select max(coalesce((select max(c+13) from t1 where ~13*t1.b in (select abs(abs(abs((cast(avg( -e) AS integer)))))- -count(distinct (13))*max(13) from t1 union select count(distinct 19) from t1)), -t1.f)) from t1 where exists(select 1 from t1 where 17 in (t1.b,13,b))),b)+d+t1.a from t1 where d not in (13,t1.b,b)),17) not between 11 and e or not 17 between d and d)}
} {300}
do_test randexpr-2.57 {
  db eval {SELECT t1.e+case when d not between f and case when a in (select t1.c from t1 union select t1.e from t1) or coalesce((select 19 from t1 where 17<=t1.d or 19*t1.f*t1.b<>t1.d | t1.d | t1.a),t1.b)*case when (t1.a) in (t1.d,t1.a,a) then  -c when 17<13 then t1.f else 17 end-t1.f*e not in (19,t1.d,17) then 19 else t1.e end then  -b else t1.b end FROM t1 WHERE NOT ((coalesce((select t1.d-coalesce((select max(coalesce((select max(c+13) from t1 where ~13*t1.b in (select abs(abs(abs((cast(avg( -e) AS integer)))))- -count(distinct (13))*max(13) from t1 union select count(distinct 19) from t1)), -t1.f)) from t1 where exists(select 1 from t1 where 17 in (t1.b,13,b))),b)+d+t1.a from t1 where d not in (13,t1.b,b)),17) not between 11 and e or not 17 between d and d))}
} {}
do_test randexpr-2.58 {
  db eval {SELECT t1.e+case when d not between f and case when a in (select t1.c from t1 union select t1.e from t1) or coalesce((select 19 from t1 where 17<=t1.d or 19*t1.f*t1.b<>t1.d & t1.d & t1.a),t1.b)*case when (t1.a) in (t1.d,t1.a,a) then  -c when 17<13 then t1.f else 17 end-t1.f*e not in (19,t1.d,17) then 19 else t1.e end then  -b else t1.b end FROM t1 WHERE (coalesce((select t1.d-coalesce((select max(coalesce((select max(c+13) from t1 where ~13*t1.b in (select abs(abs(abs((cast(avg( -e) AS integer)))))- -count(distinct (13))*max(13) from t1 union select count(distinct 19) from t1)), -t1.f)) from t1 where exists(select 1 from t1 where 17 in (t1.b,13,b))),b)+d+t1.a from t1 where d not in (13,t1.b,b)),17) not between 11 and e or not 17 between d and d)}
} {300}
do_test randexpr-2.59 {
  db eval {SELECT coalesce((select max(t1.f*case when not exists(select 1 from t1 where exists(select 1 from t1 where (select count(distinct 11) from t1) between coalesce((select max(c) from t1 where t1.e=t1.a+17),a) and t1.b) or c not in (t1.e,19,t1.e)) then 13 when exists(select 1 from t1 where t1.a between 19 and  -c) then coalesce((select coalesce((select max((( -d))) from t1 where 17 not in (t1.d,e,t1.e)),e) from t1 where c= -f),( -c)) else t1.f end) from t1 where not (11 between a and t1.e)),19) FROM t1 WHERE case c when case when (exists(select 1 from t1 where t1.d<>coalesce((select 13 from t1 where (t1.b>+e)),(17))+coalesce((select 13 from t1 where exists(select 1 from t1 where 13 in (t1.b+c,case when f between t1.f and b then t1.b else f end,(11)))),f)-17-17)) then  -c-(c) when 11 in (b,f,(t1.d)) then t1.c else t1.b end then t1.d else 11 end in (select  -count(*) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.60 {
  db eval {SELECT coalesce((select max(t1.f*case when not exists(select 1 from t1 where exists(select 1 from t1 where (select count(distinct 11) from t1) between coalesce((select max(c) from t1 where t1.e=t1.a+17),a) and t1.b) or c not in (t1.e,19,t1.e)) then 13 when exists(select 1 from t1 where t1.a between 19 and  -c) then coalesce((select coalesce((select max((( -d))) from t1 where 17 not in (t1.d,e,t1.e)),e) from t1 where c= -f),( -c)) else t1.f end) from t1 where not (11 between a and t1.e)),19) FROM t1 WHERE NOT (case c when case when (exists(select 1 from t1 where t1.d<>coalesce((select 13 from t1 where (t1.b>+e)),(17))+coalesce((select 13 from t1 where exists(select 1 from t1 where 13 in (t1.b+c,case when f between t1.f and b then t1.b else f end,(11)))),f)-17-17)) then  -c-(c) when 11 in (b,f,(t1.d)) then t1.c else t1.b end then t1.d else 11 end in (select  -count(*) from t1 union select count(*) from t1))}
} {360000}
do_test randexpr-2.61 {
  db eval {SELECT case when t1.a-coalesce((select t1.b from t1 where (d<=~a)),t1.b+t1.d | 19+13)-t1.a | ~coalesce((select ~17 from t1 where not exists(select 1 from t1 where ~case when 13 in (select +(cast(avg(b) AS integer)) from t1 union select count(*) from t1) then 17 when 11 not in (c,t1.a,t1.a) then e else e end*a not between 11 and c)),t1.c) in (11,t1.a,e) then t1.f when 19 in (select ~count(distinct d) from t1 union select cast(avg(19) AS integer) from t1) then t1.d else 19 end FROM t1 WHERE not exists(select 1 from t1 where (select count(*) from t1)+coalesce((select max(a) from t1 where t1.a between (abs(case when exists(select 1 from t1 where case when t1.e=case when 19 between 11 and e then t1.f else a end then t1.e else t1.b end in (select count(distinct d) | max(11)*abs(case count(*) when max(f) then cast(avg(e) AS integer) else count(distinct t1.e) end) from t1 union select  -cast(avg(c) AS integer) from t1)) then (select  -min(e) from t1) when (c>e) then t1.d else f end)/abs(b)) and (17)),e) not between t1.a and d)}
} {}
do_test randexpr-2.62 {
  db eval {SELECT case when t1.a-coalesce((select t1.b from t1 where (d<=~a)),t1.b+t1.d | 19+13)-t1.a | ~coalesce((select ~17 from t1 where not exists(select 1 from t1 where ~case when 13 in (select +(cast(avg(b) AS integer)) from t1 union select count(*) from t1) then 17 when 11 not in (c,t1.a,t1.a) then e else e end*a not between 11 and c)),t1.c) in (11,t1.a,e) then t1.f when 19 in (select ~count(distinct d) from t1 union select cast(avg(19) AS integer) from t1) then t1.d else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select count(*) from t1)+coalesce((select max(a) from t1 where t1.a between (abs(case when exists(select 1 from t1 where case when t1.e=case when 19 between 11 and e then t1.f else a end then t1.e else t1.b end in (select count(distinct d) | max(11)*abs(case count(*) when max(f) then cast(avg(e) AS integer) else count(distinct t1.e) end) from t1 union select  -cast(avg(c) AS integer) from t1)) then (select  -min(e) from t1) when (c>e) then t1.d else f end)/abs(b)) and (17)),e) not between t1.a and d))}
} {400}
do_test randexpr-2.63 {
  db eval {SELECT case when t1.a-coalesce((select t1.b from t1 where (d<=~a)),t1.b+t1.d & 19+13)-t1.a & ~coalesce((select ~17 from t1 where not exists(select 1 from t1 where ~case when 13 in (select +(cast(avg(b) AS integer)) from t1 union select count(*) from t1) then 17 when 11 not in (c,t1.a,t1.a) then e else e end*a not between 11 and c)),t1.c) in (11,t1.a,e) then t1.f when 19 in (select ~count(distinct d) from t1 union select cast(avg(19) AS integer) from t1) then t1.d else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select count(*) from t1)+coalesce((select max(a) from t1 where t1.a between (abs(case when exists(select 1 from t1 where case when t1.e=case when 19 between 11 and e then t1.f else a end then t1.e else t1.b end in (select count(distinct d) | max(11)*abs(case count(*) when max(f) then cast(avg(e) AS integer) else count(distinct t1.e) end) from t1 union select  -cast(avg(c) AS integer) from t1)) then (select  -min(e) from t1) when (c>e) then t1.d else f end)/abs(b)) and (17)),e) not between t1.a and d))}
} {400}
do_test randexpr-2.64 {
  db eval {SELECT case when 11 in (select max(f) from t1 union select min(19++13) | min(t1.c) from t1) and (e in (select t1.d from t1 union select t1.a | 17*case e when coalesce((select max(a) from t1 where b not in (b,f,d) or t1.a<=f),11) then t1.a else t1.b end from t1) and  -a not between b and d) then d when  -t1.f=b or t1.b between  -f and  -d then 19 else d end+d FROM t1 WHERE case when (coalesce((select case (select max(t1.b) from t1) when (b* -t1.e+e*e-t1.a) then c else a end from t1 where 17 in (select min(t1.d)-abs(count(*)) from t1 union select count(distinct c) from t1)),t1.d)=(t1.d)) and e in (select  -min(t1.b) from t1 union select count(distinct 11) from t1) and a< - -17 then t1.d | 11 else 19 end in (select 17 from t1 union select d from t1)}
} {}
do_test randexpr-2.65 {
  db eval {SELECT case when 11 in (select max(f) from t1 union select min(19++13) | min(t1.c) from t1) and (e in (select t1.d from t1 union select t1.a | 17*case e when coalesce((select max(a) from t1 where b not in (b,f,d) or t1.a<=f),11) then t1.a else t1.b end from t1) and  -a not between b and d) then d when  -t1.f=b or t1.b between  -f and  -d then 19 else d end+d FROM t1 WHERE NOT (case when (coalesce((select case (select max(t1.b) from t1) when (b* -t1.e+e*e-t1.a) then c else a end from t1 where 17 in (select min(t1.d)-abs(count(*)) from t1 union select count(distinct c) from t1)),t1.d)=(t1.d)) and e in (select  -min(t1.b) from t1 union select count(distinct 11) from t1) and a< - -17 then t1.d | 11 else 19 end in (select 17 from t1 union select d from t1))}
} {800}
do_test randexpr-2.66 {
  db eval {SELECT case when 11 in (select max(f) from t1 union select min(19++13) & min(t1.c) from t1) and (e in (select t1.d from t1 union select t1.a & 17*case e when coalesce((select max(a) from t1 where b not in (b,f,d) or t1.a<=f),11) then t1.a else t1.b end from t1) and  -a not between b and d) then d when  -t1.f=b or t1.b between  -f and  -d then 19 else d end+d FROM t1 WHERE NOT (case when (coalesce((select case (select max(t1.b) from t1) when (b* -t1.e+e*e-t1.a) then c else a end from t1 where 17 in (select min(t1.d)-abs(count(*)) from t1 union select count(distinct c) from t1)),t1.d)=(t1.d)) and e in (select  -min(t1.b) from t1 union select count(distinct 11) from t1) and a< - -17 then t1.d | 11 else 19 end in (select 17 from t1 union select d from t1))}
} {800}
do_test randexpr-2.67 {
  db eval {SELECT (abs((select min(13) from t1))/abs(coalesce((select t1.e from t1 where coalesce((select t1.f from t1 where  -11<=b-t1.c*case when (d)-t1.f+t1.e-13<>t1.b then 11 when exists(select 1 from t1 where t1.d<>((t1.b)) or t1.a not between d and 13) or t1.b<>t1.c then t1.e else  -t1.d end+t1.a or t1.c not between f and d),e)<>e), -f))) FROM t1 WHERE t1.c<>(select min((abs(( -19-t1.b*13- -++~t1.f*d-17*19*11))/abs(17))) from t1)}
} {0}
do_test randexpr-2.68 {
  db eval {SELECT (abs((select min(13) from t1))/abs(coalesce((select t1.e from t1 where coalesce((select t1.f from t1 where  -11<=b-t1.c*case when (d)-t1.f+t1.e-13<>t1.b then 11 when exists(select 1 from t1 where t1.d<>((t1.b)) or t1.a not between d and 13) or t1.b<>t1.c then t1.e else  -t1.d end+t1.a or t1.c not between f and d),e)<>e), -f))) FROM t1 WHERE NOT (t1.c<>(select min((abs(( -19-t1.b*13- -++~t1.f*d-17*19*11))/abs(17))) from t1))}
} {}
do_test randexpr-2.69 {
  db eval {SELECT case d-case when c< -case when b<=f or coalesce((select t1.e from t1 where 11<coalesce((select b+(t1.f)+t1.e-d from t1 where (t1.c<f)),t1.d)),t1.e)>e then 19 when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d>=d)) then t1.f else 17 end then e when not exists(select 1 from t1 where d=b) then t1.c else f end when 17 then 19 else t1.f end FROM t1 WHERE coalesce((select max(+t1.d) from t1 where e<>e or not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs(f))++t1.b in (select case abs(cast(avg(e) AS integer)) when cast(avg(17) AS integer) | max(d) | cast(avg(t1.e) AS integer) | min(t1.e) then (cast(avg(19) AS integer)) else cast(avg(c) AS integer) end from t1 union select cast(avg(t1.f) AS integer) from t1))) and t1.a between t1.f and b or not 17<13 or  -11= -t1.f or t1.f between c and 19),d)+(t1.d) not between b and e}
} {600}
do_test randexpr-2.70 {
  db eval {SELECT case d-case when c< -case when b<=f or coalesce((select t1.e from t1 where 11<coalesce((select b+(t1.f)+t1.e-d from t1 where (t1.c<f)),t1.d)),t1.e)>e then 19 when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d>=d)) then t1.f else 17 end then e when not exists(select 1 from t1 where d=b) then t1.c else f end when 17 then 19 else t1.f end FROM t1 WHERE NOT (coalesce((select max(+t1.d) from t1 where e<>e or not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs(f))++t1.b in (select case abs(cast(avg(e) AS integer)) when cast(avg(17) AS integer) | max(d) | cast(avg(t1.e) AS integer) | min(t1.e) then (cast(avg(19) AS integer)) else cast(avg(c) AS integer) end from t1 union select cast(avg(t1.f) AS integer) from t1))) and t1.a between t1.f and b or not 17<13 or  -11= -t1.f or t1.f between c and 19),d)+(t1.d) not between b and e)}
} {}
do_test randexpr-2.71 {
  db eval {SELECT case when t1.e in (select abs(max(case a+case when t1.a>=e+ -c then a else t1.b end+t1.a when t1.f then 19 else  -19 end)+abs( -count(distinct t1.c))+~(count(distinct t1.b)))-min(b) from t1 union select max(f) from t1) and case t1.e when  -t1.c then 19 else b end<t1.d then e+(d) when exists(select 1 from t1 where 19 not between t1.e and (19)) then  -19 else t1.c end FROM t1 WHERE (exists(select 1 from t1 where t1.e between t1.c-t1.d and (t1.a)) and ((not case 19 when 11 then e else ~d | t1.a*19 end*((b))>=t1.e))) or c in (select f from t1 union select 13 from t1) and (b)< -t1.c and f in (select max(13) from t1 union select ~+abs(count(distinct e)*abs(((count(*)))*((max(f))))) from t1)}
} {}
do_test randexpr-2.72 {
  db eval {SELECT case when t1.e in (select abs(max(case a+case when t1.a>=e+ -c then a else t1.b end+t1.a when t1.f then 19 else  -19 end)+abs( -count(distinct t1.c))+~(count(distinct t1.b)))-min(b) from t1 union select max(f) from t1) and case t1.e when  -t1.c then 19 else b end<t1.d then e+(d) when exists(select 1 from t1 where 19 not between t1.e and (19)) then  -19 else t1.c end FROM t1 WHERE NOT ((exists(select 1 from t1 where t1.e between t1.c-t1.d and (t1.a)) and ((not case 19 when 11 then e else ~d | t1.a*19 end*((b))>=t1.e))) or c in (select f from t1 union select 13 from t1) and (b)< -t1.c and f in (select max(13) from t1 union select ~+abs(count(distinct e)*abs(((count(*)))*((max(f))))) from t1))}
} {-19}
do_test randexpr-2.73 {
  db eval {SELECT c*case when t1.a in (select ~count(*) from t1 union select  -count(distinct ~case (abs(11)/abs(b-(coalesce((select 17-t1.a from t1 where not t1.d=t1.d),(abs(11)/abs(a)))))) when case when t1.d between 19 and c and t1.b between 11 and t1.a then 13 else (13) end then (13) else 19 end-19*13+11) from t1) then t1.a when t1.f<=t1.e then f else b end-19-c+f FROM t1 WHERE t1.b>=c+case when exists(select 1 from t1 where a>=+f- -c*e+coalesce((select max(b) from t1 where (b not between (t1.b) and 19) or t1.f<11),d)*f | t1.e+t1.b) then ( -t1.e)-19 when ((t1.a in (select 19 from t1 union select t1.f from t1) or b<c and b> -17)) then f else f end | d}
} {}
do_test randexpr-2.74 {
  db eval {SELECT c*case when t1.a in (select ~count(*) from t1 union select  -count(distinct ~case (abs(11)/abs(b-(coalesce((select 17-t1.a from t1 where not t1.d=t1.d),(abs(11)/abs(a)))))) when case when t1.d between 19 and c and t1.b between 11 and t1.a then 13 else (13) end then (13) else 19 end-19*13+11) from t1) then t1.a when t1.f<=t1.e then f else b end-19-c+f FROM t1 WHERE NOT (t1.b>=c+case when exists(select 1 from t1 where a>=+f- -c*e+coalesce((select max(b) from t1 where (b not between (t1.b) and 19) or t1.f<11),d)*f | t1.e+t1.b) then ( -t1.e)-19 when ((t1.a in (select 19 from t1 union select t1.f from t1) or b<c and b> -17)) then f else f end | d)}
} {60281}
do_test randexpr-2.75 {
  db eval {SELECT (abs(case when a>=b then t1.c-case when not exists(select 1 from t1 where case d when +17 then 19+c else 11 end-(abs((select  - -cast(avg(case when (11- -(abs(e)/abs(13))-t1.f<t1.e) then t1.c+d else a end-t1.c) AS integer) from t1))/abs(t1.a))<=b) then  -e+d else (t1.c) end else 19 end)/abs(c)) FROM t1 WHERE f<>11}
} {0}
do_test randexpr-2.76 {
  db eval {SELECT (abs(case when a>=b then t1.c-case when not exists(select 1 from t1 where case d when +17 then 19+c else 11 end-(abs((select  - -cast(avg(case when (11- -(abs(e)/abs(13))-t1.f<t1.e) then t1.c+d else a end-t1.c) AS integer) from t1))/abs(t1.a))<=b) then  -e+d else (t1.c) end else 19 end)/abs(c)) FROM t1 WHERE NOT (f<>11)}
} {}
do_test randexpr-2.77 {
  db eval {SELECT  -coalesce((select max(e-t1.b) from t1 where t1.e<11 and t1.b | e in ((abs(13)/abs(t1.b)),(abs((+17-case when t1.c | 13*(d) | b<>a or ((t1.e)>=a) then t1.b-t1.e when not exists(select 1 from t1 where 17<13) then  -(13) else 17 end*13))/abs(13)),t1.c)),t1.e) | c FROM t1 WHERE not exists(select 1 from t1 where 17<=(select (case (~+abs(cast(avg((t1.e)-17 | b) AS integer))-((case  -cast(avg(case when ~t1.b in (select d from t1 union select 19 from t1) then b when 13 in (t1.f,c,t1.b) then c else f end) AS integer)+count(distinct t1.f)+count(distinct t1.d) when count(*) then ((max(c))) else count(*) end)*cast(avg(t1.e) AS integer))) when ((cast(avg(a) AS integer))) then  -max(d) else ((count(*))) end) from t1))}
} {-212}
do_test randexpr-2.78 {
  db eval {SELECT  -coalesce((select max(e-t1.b) from t1 where t1.e<11 and t1.b | e in ((abs(13)/abs(t1.b)),(abs((+17-case when t1.c | 13*(d) | b<>a or ((t1.e)>=a) then t1.b-t1.e when not exists(select 1 from t1 where 17<13) then  -(13) else 17 end*13))/abs(13)),t1.c)),t1.e) | c FROM t1 WHERE NOT (not exists(select 1 from t1 where 17<=(select (case (~+abs(cast(avg((t1.e)-17 | b) AS integer))-((case  -cast(avg(case when ~t1.b in (select d from t1 union select 19 from t1) then b when 13 in (t1.f,c,t1.b) then c else f end) AS integer)+count(distinct t1.f)+count(distinct t1.d) when count(*) then ((max(c))) else count(*) end)*cast(avg(t1.e) AS integer))) when ((cast(avg(a) AS integer))) then  -max(d) else ((count(*))) end) from t1)))}
} {}
do_test randexpr-2.79 {
  db eval {SELECT  -coalesce((select max(e-t1.b) from t1 where t1.e<11 and t1.b & e in ((abs(13)/abs(t1.b)),(abs((+17-case when t1.c & 13*(d) & b<>a or ((t1.e)>=a) then t1.b-t1.e when not exists(select 1 from t1 where 17<13) then  -(13) else 17 end*13))/abs(13)),t1.c)),t1.e) & c FROM t1 WHERE not exists(select 1 from t1 where 17<=(select (case (~+abs(cast(avg((t1.e)-17 | b) AS integer))-((case  -cast(avg(case when ~t1.b in (select d from t1 union select 19 from t1) then b when 13 in (t1.f,c,t1.b) then c else f end) AS integer)+count(distinct t1.f)+count(distinct t1.d) when count(*) then ((max(c))) else count(*) end)*cast(avg(t1.e) AS integer))) when ((cast(avg(a) AS integer))) then  -max(d) else ((count(*))) end) from t1))}
} {12}
do_test randexpr-2.80 {
  db eval {SELECT 17-coalesce((select c+t1.f from t1 where (select count(distinct d)-abs(min((select case  - -count(*) when  -max(19) then  -count(*) else count(*) end from t1))-count(*)) from t1)-t1.a+case when (abs(t1.e)/abs(t1.e)) not in (a,t1.a,19) and (b between 19 and  -t1.c) then 17 else c end-19+t1.e*13<= -(t1.a)),11)-t1.d-c FROM t1 WHERE ((t1.d in ((select +cast(avg(coalesce((select max(coalesce((select max(a) from t1 where not a in (b,~(select ~count(*) from t1),case (select +max(11) |  -count(*) from t1) when 17*t1.f*17 then b else (t1.b) end+f | 17)),e)) from t1 where not exists(select 1 from t1 where 17 between a and a)),(19))) AS integer) from t1),coalesce((select max(e) from t1 where t1.e<>11),b),t1.d)))}
} {-694}
do_test randexpr-2.81 {
  db eval {SELECT 17-coalesce((select c+t1.f from t1 where (select count(distinct d)-abs(min((select case  - -count(*) when  -max(19) then  -count(*) else count(*) end from t1))-count(*)) from t1)-t1.a+case when (abs(t1.e)/abs(t1.e)) not in (a,t1.a,19) and (b between 19 and  -t1.c) then 17 else c end-19+t1.e*13<= -(t1.a)),11)-t1.d-c FROM t1 WHERE NOT (((t1.d in ((select +cast(avg(coalesce((select max(coalesce((select max(a) from t1 where not a in (b,~(select ~count(*) from t1),case (select +max(11) |  -count(*) from t1) when 17*t1.f*17 then b else (t1.b) end+f | 17)),e)) from t1 where not exists(select 1 from t1 where 17 between a and a)),(19))) AS integer) from t1),coalesce((select max(e) from t1 where t1.e<>11),b),t1.d))))}
} {}
do_test randexpr-2.82 {
  db eval {SELECT case (t1.a) when e then t1.a else t1.d end+(b)*t1.c | (select ~count(distinct (select count(distinct t1.f) from t1)) from t1)* -case c*t1.b when 19 then t1.d else (t1.b) | case when not (e)*f in (select count(distinct a)-count(distinct c) | min(a) from t1 union select  -count(*) from t1) and (t1.f in (d, -t1.c,f)) then e when t1.c not in (t1.b,t1.e,b) then t1.e else f end end FROM t1 WHERE t1.d<>coalesce((select max(case when exists(select 1 from t1 where f<=e | b) then (select min(+t1.f) from t1) else 11 end) from t1 where +case when t1.e=c then  -t1.c else t1.a end-t1.a-11-f in (select (case  -min(a) when count(*)*(( -+abs(cast(avg(a) AS integer))*max((17))) | max(19)) then min(11) else min(a) end | count(distinct  -d)) from t1 union select min(t1.e) from t1)),t1.c)}
} {60408}
do_test randexpr-2.83 {
  db eval {SELECT case (t1.a) when e then t1.a else t1.d end+(b)*t1.c | (select ~count(distinct (select count(distinct t1.f) from t1)) from t1)* -case c*t1.b when 19 then t1.d else (t1.b) | case when not (e)*f in (select count(distinct a)-count(distinct c) | min(a) from t1 union select  -count(*) from t1) and (t1.f in (d, -t1.c,f)) then e when t1.c not in (t1.b,t1.e,b) then t1.e else f end end FROM t1 WHERE NOT (t1.d<>coalesce((select max(case when exists(select 1 from t1 where f<=e | b) then (select min(+t1.f) from t1) else 11 end) from t1 where +case when t1.e=c then  -t1.c else t1.a end-t1.a-11-f in (select (case  -min(a) when count(*)*(( -+abs(cast(avg(a) AS integer))*max((17))) | max(19)) then min(11) else min(a) end | count(distinct  -d)) from t1 union select min(t1.e) from t1)),t1.c))}
} {}
do_test randexpr-2.84 {
  db eval {SELECT case (t1.a) when e then t1.a else t1.d end+(b)*t1.c & (select ~count(distinct (select count(distinct t1.f) from t1)) from t1)* -case c*t1.b when 19 then t1.d else (t1.b) & case when not (e)*f in (select count(distinct a)-count(distinct c) & min(a) from t1 union select  -count(*) from t1) and (t1.f in (d, -t1.c,f)) then e when t1.c not in (t1.b,t1.e,b) then t1.e else f end end FROM t1 WHERE t1.d<>coalesce((select max(case when exists(select 1 from t1 where f<=e | b) then (select min(+t1.f) from t1) else 11 end) from t1 where +case when t1.e=c then  -t1.c else t1.a end-t1.a-11-f in (select (case  -min(a) when count(*)*(( -+abs(cast(avg(a) AS integer))*max((17))) | max(19)) then min(11) else min(a) end | count(distinct  -d)) from t1 union select min(t1.e) from t1)),t1.c)}
} {384}
do_test randexpr-2.85 {
  db eval {SELECT (select abs(max((select (case cast(avg(t1.a) AS integer) when +~abs(cast(avg( -17+case when t1.a in (c,(e),t1.f) and f in (c,t1.d,t1.a) then d when d between c and t1.d then f else e end) AS integer))-(abs(~max((b)))-min(t1.f)) then cast(avg(t1.f) AS integer) else count(*) end) from t1)+case when (exists(select 1 from t1 where t1.a in (select  -max(e) from t1 union select  -count(*) from t1)) or e in (t1.b*d,a, - -d)) then 17*t1.c else c end)) from t1) FROM t1 WHERE ~t1.e>case 13 when e then a else coalesce((select ~t1.d from t1 where exists(select 1 from t1 where t1.f between coalesce((select t1.a from t1 where ((select min(d-d- -t1.d+a) from t1)) not between f and t1.c or exists(select 1 from t1 where b<>17)),(a)) and  -d) or not exists(select 1 from t1 where e in (select min(19)*(count(*))*cast(avg(11) AS integer) | min(b) from t1 union select (cast(avg(t1.e) AS integer)) from t1))),c) end-t1.c}
} {}
do_test randexpr-2.86 {
  db eval {SELECT (select abs(max((select (case cast(avg(t1.a) AS integer) when +~abs(cast(avg( -17+case when t1.a in (c,(e),t1.f) and f in (c,t1.d,t1.a) then d when d between c and t1.d then f else e end) AS integer))-(abs(~max((b)))-min(t1.f)) then cast(avg(t1.f) AS integer) else count(*) end) from t1)+case when (exists(select 1 from t1 where t1.a in (select  -max(e) from t1 union select  -count(*) from t1)) or e in (t1.b*d,a, - -d)) then 17*t1.c else c end)) from t1) FROM t1 WHERE NOT (~t1.e>case 13 when e then a else coalesce((select ~t1.d from t1 where exists(select 1 from t1 where t1.f between coalesce((select t1.a from t1 where ((select min(d-d- -t1.d+a) from t1)) not between f and t1.c or exists(select 1 from t1 where b<>17)),(a)) and  -d) or not exists(select 1 from t1 where e in (select min(19)*(count(*))*cast(avg(11) AS integer) | min(b) from t1 union select (cast(avg(t1.e) AS integer)) from t1))),c) end-t1.c)}
} {301}
do_test randexpr-2.87 {
  db eval {SELECT t1.c+(abs(t1.b*t1.b)/abs(++t1.a-t1.e-(abs(t1.b)/abs(d))*11*t1.f)) | 19-b-t1.e | t1.e-+~t1.d*13+a+case case when (d)+17-c=d then a else t1.b end when e then t1.a else 19 end FROM t1 WHERE not coalesce((select (abs(case t1.b when coalesce((select case when exists(select 1 from t1 where f between 17 and f) then 11 else f end from t1 where not exists(select 1 from t1 where c>=t1.d)),17)*t1.a then t1.e else 13 end)/abs(17)) from t1 where ((13 in (select abs(~min(d)*count(distinct  -(f)) | count(*)*cast(avg(11) AS integer)) from t1 union select count(*) from t1) and a<=13) and c<> -(t1.c))), -t1.a)*t1.e*f+d not in (11,d,t1.c)}
} {}
do_test randexpr-2.88 {
  db eval {SELECT t1.c+(abs(t1.b*t1.b)/abs(++t1.a-t1.e-(abs(t1.b)/abs(d))*11*t1.f)) | 19-b-t1.e | t1.e-+~t1.d*13+a+case case when (d)+17-c=d then a else t1.b end when e then t1.a else 19 end FROM t1 WHERE NOT (not coalesce((select (abs(case t1.b when coalesce((select case when exists(select 1 from t1 where f between 17 and f) then 11 else f end from t1 where not exists(select 1 from t1 where c>=t1.d)),17)*t1.a then t1.e else 13 end)/abs(17)) from t1 where ((13 in (select abs(~min(d)*count(distinct  -(f)) | count(*)*cast(avg(11) AS integer)) from t1 union select count(*) from t1) and a<=13) and c<> -(t1.c))), -t1.a)*t1.e*f+d not in (11,d,t1.c))}
} {-33}
do_test randexpr-2.89 {
  db eval {SELECT t1.c+(abs(t1.b*t1.b)/abs(++t1.a-t1.e-(abs(t1.b)/abs(d))*11*t1.f)) & 19-b-t1.e & t1.e-+~t1.d*13+a+case case when (d)+17-c=d then a else t1.b end when e then t1.a else 19 end FROM t1 WHERE NOT (not coalesce((select (abs(case t1.b when coalesce((select case when exists(select 1 from t1 where f between 17 and f) then 11 else f end from t1 where not exists(select 1 from t1 where c>=t1.d)),17)*t1.a then t1.e else 13 end)/abs(17)) from t1 where ((13 in (select abs(~min(d)*count(distinct  -(f)) | count(*)*cast(avg(11) AS integer)) from t1 union select count(*) from t1) and a<=13) and c<> -(t1.c))), -t1.a)*t1.e*f+d not in (11,d,t1.c))}
} {0}
do_test randexpr-2.90 {
  db eval {SELECT case when t1.f>t1.d then (select abs(+count(distinct c)+(abs(min((abs(+11)/abs(b)))* -count(*)))) from t1)-t1.a when d+case when (select cast(avg(t1.f) AS integer)-count(distinct 19) from t1)<>17 then c when t1.e in (select cast(avg(t1.a) AS integer) from t1 union select count(distinct f) from t1) and d>t1.c and t1.f not in (11,19,t1.b) then a else (c) end+(17)=c then t1.d else t1.c end-c FROM t1 WHERE 13 not in (e,t1.b,+coalesce((select max(b) from t1 where 13*b-t1.d-case when 11>=a then t1.a-t1.d else (t1.d)*e+19 end*t1.a+19+(11) | t1.c*t1.a-17<t1.e),b)-a+17*17*c)}
} {-399}
do_test randexpr-2.91 {
  db eval {SELECT case when t1.f>t1.d then (select abs(+count(distinct c)+(abs(min((abs(+11)/abs(b)))* -count(*)))) from t1)-t1.a when d+case when (select cast(avg(t1.f) AS integer)-count(distinct 19) from t1)<>17 then c when t1.e in (select cast(avg(t1.a) AS integer) from t1 union select count(distinct f) from t1) and d>t1.c and t1.f not in (11,19,t1.b) then a else (c) end+(17)=c then t1.d else t1.c end-c FROM t1 WHERE NOT (13 not in (e,t1.b,+coalesce((select max(b) from t1 where 13*b-t1.d-case when 11>=a then t1.a-t1.d else (t1.d)*e+19 end*t1.a+19+(11) | t1.c*t1.a-17<t1.e),b)-a+17*17*c))}
} {}
do_test randexpr-2.92 {
  db eval {SELECT coalesce((select +19 from t1 where 19-c+t1.c-f not in (coalesce((select 19 from t1 where (t1.b between t1.c*t1.a*t1.b | a-e | 13-(abs(19)/abs((select max(t1.d | coalesce((select max( -t1.c) from t1 where b in (select e from t1 union select (f) from t1)),t1.d)+(e)) from t1)+c)) and f)),11),f,17)),f) FROM t1 WHERE (select count(distinct 11)+min((coalesce((select max(case when t1.d<>(abs(t1.a)/abs(e)) then d else ~(t1.e)-e+d+13-t1.b+b*19 end) from t1 where (select max(19)-cast(avg(a) AS integer) from t1)> -t1.e),17)+e+t1.e-t1.c+(c))*17) from t1) between  -17 and t1.c}
} {}
do_test randexpr-2.93 {
  db eval {SELECT coalesce((select +19 from t1 where 19-c+t1.c-f not in (coalesce((select 19 from t1 where (t1.b between t1.c*t1.a*t1.b | a-e | 13-(abs(19)/abs((select max(t1.d | coalesce((select max( -t1.c) from t1 where b in (select e from t1 union select (f) from t1)),t1.d)+(e)) from t1)+c)) and f)),11),f,17)),f) FROM t1 WHERE NOT ((select count(distinct 11)+min((coalesce((select max(case when t1.d<>(abs(t1.a)/abs(e)) then d else ~(t1.e)-e+d+13-t1.b+b*19 end) from t1 where (select max(19)-cast(avg(a) AS integer) from t1)> -t1.e),17)+e+t1.e-t1.c+(c))*17) from t1) between  -17 and t1.c)}
} {19}
do_test randexpr-2.94 {
  db eval {SELECT coalesce((select +19 from t1 where 19-c+t1.c-f not in (coalesce((select 19 from t1 where (t1.b between t1.c*t1.a*t1.b & a-e & 13-(abs(19)/abs((select max(t1.d & coalesce((select max( -t1.c) from t1 where b in (select e from t1 union select (f) from t1)),t1.d)+(e)) from t1)+c)) and f)),11),f,17)),f) FROM t1 WHERE NOT ((select count(distinct 11)+min((coalesce((select max(case when t1.d<>(abs(t1.a)/abs(e)) then d else ~(t1.e)-e+d+13-t1.b+b*19 end) from t1 where (select max(19)-cast(avg(a) AS integer) from t1)> -t1.e),17)+e+t1.e-t1.c+(c))*17) from t1) between  -17 and t1.c)}
} {19}
do_test randexpr-2.95 {
  db eval {SELECT (case t1.a when (select (count(distinct t1.f)) from t1)-e then 11 else t1.c+17-f*~f | f+~e-a*t1.b+13 end | 13) FROM t1 WHERE (coalesce((select max(f) from t1 where (c+t1.f | (select count(distinct t1.d) from t1)>=coalesce((select b+(abs(case when t1.f>=(select case max(f) when max(19) then cast(avg(t1.a) AS integer) else count(distinct 13) end from t1) | t1.b and (a in (select (b) from t1 union select t1.b from t1)) then (a)-b when not exists(select 1 from t1 where c between t1.c and t1.a) then a else t1.a end)/abs(t1.b))- -f from t1 where b not in (t1.b,t1.f,c)),t1.d)-t1.d)), -17) between 13 and t1.f)}
} {-19491}
do_test randexpr-2.96 {
  db eval {SELECT (case t1.a when (select (count(distinct t1.f)) from t1)-e then 11 else t1.c+17-f*~f | f+~e-a*t1.b+13 end | 13) FROM t1 WHERE NOT ((coalesce((select max(f) from t1 where (c+t1.f | (select count(distinct t1.d) from t1)>=coalesce((select b+(abs(case when t1.f>=(select case max(f) when max(19) then cast(avg(t1.a) AS integer) else count(distinct 13) end from t1) | t1.b and (a in (select (b) from t1 union select t1.b from t1)) then (a)-b when not exists(select 1 from t1 where c between t1.c and t1.a) then a else t1.a end)/abs(t1.b))- -f from t1 where b not in (t1.b,t1.f,c)),t1.d)-t1.d)), -17) between 13 and t1.f))}
} {}
do_test randexpr-2.97 {
  db eval {SELECT (case t1.a when (select (count(distinct t1.f)) from t1)-e then 11 else t1.c+17-f*~f & f+~e-a*t1.b+13 end & 13) FROM t1 WHERE (coalesce((select max(f) from t1 where (c+t1.f | (select count(distinct t1.d) from t1)>=coalesce((select b+(abs(case when t1.f>=(select case max(f) when max(19) then cast(avg(t1.a) AS integer) else count(distinct 13) end from t1) | t1.b and (a in (select (b) from t1 union select t1.b from t1)) then (a)-b when not exists(select 1 from t1 where c between t1.c and t1.a) then a else t1.a end)/abs(t1.b))- -f from t1 where b not in (t1.b,t1.f,c)),t1.d)-t1.d)), -17) between 13 and t1.f)}
} {0}
do_test randexpr-2.98 {
  db eval {SELECT case when ((select  -abs(min(coalesce((select max(11 | t1.f) from t1 where coalesce((select f from t1 where e+c in (select 19 from t1 union select f from t1)),b) not in (t1.a,+case when 13>=t1.e then t1.a when 17 not in (t1.d,b,t1.e) then 13 else t1.b end-t1.e,t1.f)),t1.f))*count(*)*min(t1.c)) from t1)<17) and 13* -f+a not between (a) and f then c-11+b else 19 end FROM t1 WHERE e+case case when a<>c then (abs(case when coalesce((select (abs( -19+11)/abs(t1.c)) from t1 where (17) in (a,13,11) and 17 in (select 11 from t1 union select t1.f from t1)),t1.a) between t1.f and c then t1.d when not exists(select 1 from t1 where not exists(select 1 from t1 where 19=f)) then f else (b) end-19)/abs(e)) else 11 end when 17 then a else t1.f end-13 | e between  -t1.e and 13}
} {}
do_test randexpr-2.99 {
  db eval {SELECT case when ((select  -abs(min(coalesce((select max(11 | t1.f) from t1 where coalesce((select f from t1 where e+c in (select 19 from t1 union select f from t1)),b) not in (t1.a,+case when 13>=t1.e then t1.a when 17 not in (t1.d,b,t1.e) then 13 else t1.b end-t1.e,t1.f)),t1.f))*count(*)*min(t1.c)) from t1)<17) and 13* -f+a not between (a) and f then c-11+b else 19 end FROM t1 WHERE NOT (e+case case when a<>c then (abs(case when coalesce((select (abs( -19+11)/abs(t1.c)) from t1 where (17) in (a,13,11) and 17 in (select 11 from t1 union select t1.f from t1)),t1.a) between t1.f and c then t1.d when not exists(select 1 from t1 where not exists(select 1 from t1 where 19=f)) then f else (b) end-19)/abs(e)) else 11 end when 17 then a else t1.f end-13 | e between  -t1.e and 13)}
} {489}
do_test randexpr-2.100 {
  db eval {SELECT case when ((select  -abs(min(coalesce((select max(11 & t1.f) from t1 where coalesce((select f from t1 where e+c in (select 19 from t1 union select f from t1)),b) not in (t1.a,+case when 13>=t1.e then t1.a when 17 not in (t1.d,b,t1.e) then 13 else t1.b end-t1.e,t1.f)),t1.f))*count(*)*min(t1.c)) from t1)<17) and 13* -f+a not between (a) and f then c-11+b else 19 end FROM t1 WHERE NOT (e+case case when a<>c then (abs(case when coalesce((select (abs( -19+11)/abs(t1.c)) from t1 where (17) in (a,13,11) and 17 in (select 11 from t1 union select t1.f from t1)),t1.a) between t1.f and c then t1.d when not exists(select 1 from t1 where not exists(select 1 from t1 where 19=f)) then f else (b) end-19)/abs(e)) else 11 end when 17 then a else t1.f end-13 | e between  -t1.e and 13)}
} {489}
do_test randexpr-2.101 {
  db eval {SELECT case when t1.b-t1.e*c<>c then coalesce((select  -17 from t1 where (t1.f+((select case count(*) when  -cast(avg(19) AS integer)+count(distinct (t1.c)) | (cast(avg(19) AS integer))*max(t1.c)*count(*)-((count(*))) then cast(avg(b) AS integer) else (count(*)) end-min(a) from t1)) | case when t1.b | a in (select t1.a from t1 union select (select count(distinct e) from t1) from t1) then t1.e else b end+t1.a)<e),17) else 19 end FROM t1 WHERE case  -coalesce((select d-+t1.d-13-b from t1 where case when not exists(select 1 from t1 where (t1.a-t1.f in (select t1.e from t1 union select 17 from t1)) or 19<=t1.a) then t1.c-b else b end in (select  -max(13)++abs(max(t1.c))*+max(t1.d) from t1 union select cast(avg(t1.e) AS integer) from t1)),13) | t1.d when (t1.f) then f else a end not between 11 and b}
} {}
do_test randexpr-2.102 {
  db eval {SELECT case when t1.b-t1.e*c<>c then coalesce((select  -17 from t1 where (t1.f+((select case count(*) when  -cast(avg(19) AS integer)+count(distinct (t1.c)) | (cast(avg(19) AS integer))*max(t1.c)*count(*)-((count(*))) then cast(avg(b) AS integer) else (count(*)) end-min(a) from t1)) | case when t1.b | a in (select t1.a from t1 union select (select count(distinct e) from t1) from t1) then t1.e else b end+t1.a)<e),17) else 19 end FROM t1 WHERE NOT (case  -coalesce((select d-+t1.d-13-b from t1 where case when not exists(select 1 from t1 where (t1.a-t1.f in (select t1.e from t1 union select 17 from t1)) or 19<=t1.a) then t1.c-b else b end in (select  -max(13)++abs(max(t1.c))*+max(t1.d) from t1 union select cast(avg(t1.e) AS integer) from t1)),13) | t1.d when (t1.f) then f else a end not between 11 and b)}
} {17}
do_test randexpr-2.103 {
  db eval {SELECT case when t1.b-t1.e*c<>c then coalesce((select  -17 from t1 where (t1.f+((select case count(*) when  -cast(avg(19) AS integer)+count(distinct (t1.c)) & (cast(avg(19) AS integer))*max(t1.c)*count(*)-((count(*))) then cast(avg(b) AS integer) else (count(*)) end-min(a) from t1)) & case when t1.b & a in (select t1.a from t1 union select (select count(distinct e) from t1) from t1) then t1.e else b end+t1.a)<e),17) else 19 end FROM t1 WHERE NOT (case  -coalesce((select d-+t1.d-13-b from t1 where case when not exists(select 1 from t1 where (t1.a-t1.f in (select t1.e from t1 union select 17 from t1)) or 19<=t1.a) then t1.c-b else b end in (select  -max(13)++abs(max(t1.c))*+max(t1.d) from t1 union select cast(avg(t1.e) AS integer) from t1)),13) | t1.d when (t1.f) then f else a end not between 11 and b)}
} {-17}
do_test randexpr-2.104 {
  db eval {SELECT coalesce((select max(case when (select ~cast(avg(a) AS integer) from t1)>~t1.a then f else +~11 end) from t1 where ((select case ~abs(count(distinct t1.e)+(count(*)+count(*)+(abs( -~count(*) | max((t1.b))))))*(cast(avg(t1.a) AS integer)) when (count(*)) then min(19) else  -(min(b)) end from t1))+11<>t1.f), -c-f) FROM t1 WHERE ~e>coalesce((select max(case case case coalesce((select max(coalesce((select c from t1 where t1.a-t1.c>13),13)) from t1 where  -b not in (case d when ~t1.f | t1.c then 13 else 11 end,19,19)),t1.d) when c then t1.a else t1.b end+f-e*b when f then 19 else  -t1.b end when t1.b then 11 else 13 end) from t1 where c in (select 19 from t1 union select e from t1)),t1.d)}
} {}
do_test randexpr-2.105 {
  db eval {SELECT coalesce((select max(case when (select ~cast(avg(a) AS integer) from t1)>~t1.a then f else +~11 end) from t1 where ((select case ~abs(count(distinct t1.e)+(count(*)+count(*)+(abs( -~count(*) | max((t1.b))))))*(cast(avg(t1.a) AS integer)) when (count(*)) then min(19) else  -(min(b)) end from t1))+11<>t1.f), -c-f) FROM t1 WHERE NOT (~e>coalesce((select max(case case case coalesce((select max(coalesce((select c from t1 where t1.a-t1.c>13),13)) from t1 where  -b not in (case d when ~t1.f | t1.c then 13 else 11 end,19,19)),t1.d) when c then t1.a else t1.b end+f-e*b when f then 19 else  -t1.b end when t1.b then 11 else 13 end) from t1 where c in (select 19 from t1 union select e from t1)),t1.d))}
} {-12}
do_test randexpr-2.106 {
  db eval {SELECT coalesce((select max(case when (select ~cast(avg(a) AS integer) from t1)>~t1.a then f else +~11 end) from t1 where ((select case ~abs(count(distinct t1.e)+(count(*)+count(*)+(abs( -~count(*) & max((t1.b))))))*(cast(avg(t1.a) AS integer)) when (count(*)) then min(19) else  -(min(b)) end from t1))+11<>t1.f), -c-f) FROM t1 WHERE NOT (~e>coalesce((select max(case case case coalesce((select max(coalesce((select c from t1 where t1.a-t1.c>13),13)) from t1 where  -b not in (case d when ~t1.f | t1.c then 13 else 11 end,19,19)),t1.d) when c then t1.a else t1.b end+f-e*b when f then 19 else  -t1.b end when t1.b then 11 else 13 end) from t1 where c in (select 19 from t1 union select e from t1)),t1.d))}
} {-12}
do_test randexpr-2.107 {
  db eval {SELECT coalesce((select a from t1 where b>=~11-coalesce((select max((abs(19)/abs(t1.e))+19+t1.d) from t1 where (select abs(count(*) | count(*) | case count(*) when cast(avg(17) AS integer) then  -cast(avg(b) AS integer) else count(*) end*min(b))*(min(t1.e)) from t1) in (11*(select count(*) from t1)*17*t1.e-e*t1.b,t1.e,t1.f)),a)*t1.d),13)-f FROM t1 WHERE ~((case when not 13-+t1.c>=17 then  -~ -b+t1.f+case when t1.c<t1.b then t1.b when e*t1.b in (c,f,19) then (abs(a)/abs(case when 13=e then t1.e when  -a<>t1.d then 11 else t1.e end)) else t1.b end when d>a then (a) else t1.b end))+t1.c in (13,t1.a,13) or t1.e>c}
} {-500}
do_test randexpr-2.108 {
  db eval {SELECT coalesce((select a from t1 where b>=~11-coalesce((select max((abs(19)/abs(t1.e))+19+t1.d) from t1 where (select abs(count(*) | count(*) | case count(*) when cast(avg(17) AS integer) then  -cast(avg(b) AS integer) else count(*) end*min(b))*(min(t1.e)) from t1) in (11*(select count(*) from t1)*17*t1.e-e*t1.b,t1.e,t1.f)),a)*t1.d),13)-f FROM t1 WHERE NOT (~((case when not 13-+t1.c>=17 then  -~ -b+t1.f+case when t1.c<t1.b then t1.b when e*t1.b in (c,f,19) then (abs(a)/abs(case when 13=e then t1.e when  -a<>t1.d then 11 else t1.e end)) else t1.b end when d>a then (a) else t1.b end))+t1.c in (13,t1.a,13) or t1.e>c)}
} {}
do_test randexpr-2.109 {
  db eval {SELECT coalesce((select a from t1 where b>=~11-coalesce((select max((abs(19)/abs(t1.e))+19+t1.d) from t1 where (select abs(count(*) & count(*) & case count(*) when cast(avg(17) AS integer) then  -cast(avg(b) AS integer) else count(*) end*min(b))*(min(t1.e)) from t1) in (11*(select count(*) from t1)*17*t1.e-e*t1.b,t1.e,t1.f)),a)*t1.d),13)-f FROM t1 WHERE ~((case when not 13-+t1.c>=17 then  -~ -b+t1.f+case when t1.c<t1.b then t1.b when e*t1.b in (c,f,19) then (abs(a)/abs(case when 13=e then t1.e when  -a<>t1.d then 11 else t1.e end)) else t1.b end when d>a then (a) else t1.b end))+t1.c in (13,t1.a,13) or t1.e>c}
} {-500}
do_test randexpr-2.110 {
  db eval {SELECT case when 13>=~t1.a or (exists(select 1 from t1 where 11 not in (17,t1.f,17))) then f when not exists(select 1 from t1 where exists(select 1 from t1 where 13 not between e and ~+case b when t1.f then case  -case f when 11 then  -17 else 19 end+17 when b then b else 13 end else 13 end- -t1.a and t1.c not in (t1.f,a,c) or t1.f<11)) then t1.c else 11 end FROM t1 WHERE +t1.e in (select cast(avg(t1.c*t1.a*(abs(13)/abs(t1.e))) AS integer) from t1 union select min(c+13) from t1)}
} {}
do_test randexpr-2.111 {
  db eval {SELECT case when 13>=~t1.a or (exists(select 1 from t1 where 11 not in (17,t1.f,17))) then f when not exists(select 1 from t1 where exists(select 1 from t1 where 13 not between e and ~+case b when t1.f then case  -case f when 11 then  -17 else 19 end+17 when b then b else 13 end else 13 end- -t1.a and t1.c not in (t1.f,a,c) or t1.f<11)) then t1.c else 11 end FROM t1 WHERE NOT (+t1.e in (select cast(avg(t1.c*t1.a*(abs(13)/abs(t1.e))) AS integer) from t1 union select min(c+13) from t1))}
} {600}
do_test randexpr-2.112 {
  db eval {SELECT case when coalesce((select max(13) from t1 where coalesce((select max(c) from t1 where coalesce((select max(17) from t1 where 11 in (select ~d | case when t1.a>+19 then 11 when t1.d not in ( -e,e,c) or 13<t1.c then t1.b else d end-t1.d from t1 union select e from t1)),t1.b) in (select e from t1 union select c from t1)),d)<>d or t1.e<>b),t1.b)*13<=f then  -t1.e when 19 between  -t1.f and t1.a then  -t1.b else t1.f end FROM t1 WHERE exists(select 1 from t1 where t1.f between a and coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where coalesce((select 19 from t1 where t1.c=b),a)= -t1.b and not exists(select 1 from t1 where b between e and b) and a<= -17 or exists(select 1 from t1 where 17<=f)) or t1.a>=t1.c),13)*~13*t1.c*13 or t1.d>13 and 11>=t1.d and 11 not between c and c and t1.f>=17 and (d)=f)}
} {}
do_test randexpr-2.113 {
  db eval {SELECT case when coalesce((select max(13) from t1 where coalesce((select max(c) from t1 where coalesce((select max(17) from t1 where 11 in (select ~d | case when t1.a>+19 then 11 when t1.d not in ( -e,e,c) or 13<t1.c then t1.b else d end-t1.d from t1 union select e from t1)),t1.b) in (select e from t1 union select c from t1)),d)<>d or t1.e<>b),t1.b)*13<=f then  -t1.e when 19 between  -t1.f and t1.a then  -t1.b else t1.f end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.f between a and coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where coalesce((select 19 from t1 where t1.c=b),a)= -t1.b and not exists(select 1 from t1 where b between e and b) and a<= -17 or exists(select 1 from t1 where 17<=f)) or t1.a>=t1.c),13)*~13*t1.c*13 or t1.d>13 and 11>=t1.d and 11 not between c and c and t1.f>=17 and (d)=f))}
} {-500}
do_test randexpr-2.114 {
  db eval {SELECT case when coalesce((select max(13) from t1 where coalesce((select max(c) from t1 where coalesce((select max(17) from t1 where 11 in (select ~d & case when t1.a>+19 then 11 when t1.d not in ( -e,e,c) or 13<t1.c then t1.b else d end-t1.d from t1 union select e from t1)),t1.b) in (select e from t1 union select c from t1)),d)<>d or t1.e<>b),t1.b)*13<=f then  -t1.e when 19 between  -t1.f and t1.a then  -t1.b else t1.f end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.f between a and coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where coalesce((select 19 from t1 where t1.c=b),a)= -t1.b and not exists(select 1 from t1 where b between e and b) and a<= -17 or exists(select 1 from t1 where 17<=f)) or t1.a>=t1.c),13)*~13*t1.c*13 or t1.d>13 and 11>=t1.d and 11 not between c and c and t1.f>=17 and (d)=f))}
} {-500}
do_test randexpr-2.115 {
  db eval {SELECT case when coalesce((select +case when not exists(select 1 from t1 where 19*t1.e< -~11*a or t1.b>=t1.c and t1.a<>e) then coalesce((select max(13) from t1 where 11>11), -(e)) | t1.a when (t1.d) in (select f from t1 union select b from t1) then a else e end from t1 where t1.f<> -t1.d),t1.b) not in (d,t1.d,t1.c) then 19 when (t1.b<>t1.e or  -t1.b>=t1.b) then (f) else d end FROM t1 WHERE t1.e=a and b>=(abs(case when 19 not between ~+17 and +case when ((b+e-f=t1.d or b not in (t1.a,t1.f,t1.b) or t1.a not between 19 and e or b>=(t1.d) or t1.b not in (d,t1.a,t1.b))) then e-f else t1.e*t1.f end | f then d else  -d end)/abs(11))}
} {}
do_test randexpr-2.116 {
  db eval {SELECT case when coalesce((select +case when not exists(select 1 from t1 where 19*t1.e< -~11*a or t1.b>=t1.c and t1.a<>e) then coalesce((select max(13) from t1 where 11>11), -(e)) | t1.a when (t1.d) in (select f from t1 union select b from t1) then a else e end from t1 where t1.f<> -t1.d),t1.b) not in (d,t1.d,t1.c) then 19 when (t1.b<>t1.e or  -t1.b>=t1.b) then (f) else d end FROM t1 WHERE NOT (t1.e=a and b>=(abs(case when 19 not between ~+17 and +case when ((b+e-f=t1.d or b not in (t1.a,t1.f,t1.b) or t1.a not between 19 and e or b>=(t1.d) or t1.b not in (d,t1.a,t1.b))) then e-f else t1.e*t1.f end | f then d else  -d end)/abs(11)))}
} {19}
do_test randexpr-2.117 {
  db eval {SELECT case when coalesce((select +case when not exists(select 1 from t1 where 19*t1.e< -~11*a or t1.b>=t1.c and t1.a<>e) then coalesce((select max(13) from t1 where 11>11), -(e)) & t1.a when (t1.d) in (select f from t1 union select b from t1) then a else e end from t1 where t1.f<> -t1.d),t1.b) not in (d,t1.d,t1.c) then 19 when (t1.b<>t1.e or  -t1.b>=t1.b) then (f) else d end FROM t1 WHERE NOT (t1.e=a and b>=(abs(case when 19 not between ~+17 and +case when ((b+e-f=t1.d or b not in (t1.a,t1.f,t1.b) or t1.a not between 19 and e or b>=(t1.d) or t1.b not in (d,t1.a,t1.b))) then e-f else t1.e*t1.f end | f then d else  -d end)/abs(11)))}
} {19}
do_test randexpr-2.118 {
  db eval {SELECT (select (cast(avg(b) AS integer) | count(distinct case when coalesce((select 13 from t1 where (+(abs(e)/abs(t1.b))) in ( -b, -(a),13)),t1.e)>=b then 11 else  - -19 end-17+19) | abs(~case count(distinct t1.b) when +min(e) then +abs(~ - -count(distinct 11)-count(distinct t1.b))-count(distinct a) else  -min(b) end)*count(distinct 19)-count(distinct t1.b)) from t1) FROM t1 WHERE 11<=t1.a-t1.f-19*t1.b+19+coalesce((select e from t1 where d not between (select count(distinct coalesce((select t1.a from t1 where (select cast(avg(t1.e) AS integer)-+count(distinct c)+max((abs(t1.c)/abs(t1.f))-a)-(count(*)-cast(avg((17)) AS integer)) from t1) in (t1.e, -e | d,b)),c)) from t1) and t1.a),t1.d)-t1.d}
} {}
do_test randexpr-2.119 {
  db eval {SELECT (select (cast(avg(b) AS integer) | count(distinct case when coalesce((select 13 from t1 where (+(abs(e)/abs(t1.b))) in ( -b, -(a),13)),t1.e)>=b then 11 else  - -19 end-17+19) | abs(~case count(distinct t1.b) when +min(e) then +abs(~ - -count(distinct 11)-count(distinct t1.b))-count(distinct a) else  -min(b) end)*count(distinct 19)-count(distinct t1.b)) from t1) FROM t1 WHERE NOT (11<=t1.a-t1.f-19*t1.b+19+coalesce((select e from t1 where d not between (select count(distinct coalesce((select t1.a from t1 where (select cast(avg(t1.e) AS integer)-+count(distinct c)+max((abs(t1.c)/abs(t1.f))-a)-(count(*)-cast(avg((17)) AS integer)) from t1) in (t1.e, -e | d,b)),c)) from t1) and t1.a),t1.d)-t1.d)}
} {207}
do_test randexpr-2.120 {
  db eval {SELECT (select (cast(avg(b) AS integer) & count(distinct case when coalesce((select 13 from t1 where (+(abs(e)/abs(t1.b))) in ( -b, -(a),13)),t1.e)>=b then 11 else  - -19 end-17+19) & abs(~case count(distinct t1.b) when +min(e) then +abs(~ - -count(distinct 11)-count(distinct t1.b))-count(distinct a) else  -min(b) end)*count(distinct 19)-count(distinct t1.b)) from t1) FROM t1 WHERE NOT (11<=t1.a-t1.f-19*t1.b+19+coalesce((select e from t1 where d not between (select count(distinct coalesce((select t1.a from t1 where (select cast(avg(t1.e) AS integer)-+count(distinct c)+max((abs(t1.c)/abs(t1.f))-a)-(count(*)-cast(avg((17)) AS integer)) from t1) in (t1.e, -e | d,b)),c)) from t1) and t1.a),t1.d)-t1.d)}
} {0}
do_test randexpr-2.121 {
  db eval {SELECT 11+a*case t1.a*t1.e when 17 then coalesce((select +t1.b from t1 where t1.c<>t1.c and e between +(abs(case b+f*coalesce((select c from t1 where t1.d>17), -t1.c)+(19) when b then t1.f else t1.d end)/abs(t1.d)) and t1.c and t1.a>b or t1.f<t1.a),t1.c)*17 else  -t1.d end*t1.b FROM t1 WHERE  -19-~t1.b<(select ~count(*) from t1)+(abs(++coalesce((select max(t1.a-c) from t1 where t1.a=11),11))/abs(case when not not exists(select 1 from t1 where exists(select 1 from t1 where t1.a>c or t1.d | 11 in (select t1.e from t1 union select d from t1))) then 17 else (abs(coalesce((select max(f) from t1 where not (c)<t1.a),t1.b))/abs(d))+f end-t1.c))-t1.e-t1.e}
} {}
do_test randexpr-2.122 {
  db eval {SELECT 11+a*case t1.a*t1.e when 17 then coalesce((select +t1.b from t1 where t1.c<>t1.c and e between +(abs(case b+f*coalesce((select c from t1 where t1.d>17), -t1.c)+(19) when b then t1.f else t1.d end)/abs(t1.d)) and t1.c and t1.a>b or t1.f<t1.a),t1.c)*17 else  -t1.d end*t1.b FROM t1 WHERE NOT ( -19-~t1.b<(select ~count(*) from t1)+(abs(++coalesce((select max(t1.a-c) from t1 where t1.a=11),11))/abs(case when not not exists(select 1 from t1 where exists(select 1 from t1 where t1.a>c or t1.d | 11 in (select t1.e from t1 union select d from t1))) then 17 else (abs(coalesce((select max(f) from t1 where not (c)<t1.a),t1.b))/abs(d))+f end-t1.c))-t1.e-t1.e)}
} {-7999989}
do_test randexpr-2.123 {
  db eval {SELECT (e)+case when t1.a>e then t1.f else t1.b+case when b between coalesce((select max(t1.d-~(abs(a)/abs(c))+t1.c) from t1 where f in (select  -min(t1.f)-+cast(avg(e) AS integer) from t1 union select  -(cast(avg(13) AS integer)) from t1) and f<=a and not exists(select 1 from t1 where f not between t1.d and t1.d or (f)<=a) and (t1.f) between 11 and d),t1.a) and t1.f then e when (11<d) then 11 else d end end | t1.e FROM t1 WHERE (abs(13)/abs(a)) in (+coalesce((select 13 from t1 where (t1.e in (select cast(avg(t1.c) AS integer) from t1 union select case +count(distinct t1.c) when +count(*) then ( -min( -b)) else count(*) end*max(e) from t1)) and +case when c in (select (11) from t1 union select  -t1.c from t1) then 17 when 17 in (select 17 from t1 union select d from t1) then c else t1.a end>13),case when c<=11 then t1.e when t1.e<=b then t1.d else t1.e end)-11,11,17)}
} {}
do_test randexpr-2.124 {
  db eval {SELECT (e)+case when t1.a>e then t1.f else t1.b+case when b between coalesce((select max(t1.d-~(abs(a)/abs(c))+t1.c) from t1 where f in (select  -min(t1.f)-+cast(avg(e) AS integer) from t1 union select  -(cast(avg(13) AS integer)) from t1) and f<=a and not exists(select 1 from t1 where f not between t1.d and t1.d or (f)<=a) and (t1.f) between 11 and d),t1.a) and t1.f then e when (11<d) then 11 else d end end | t1.e FROM t1 WHERE NOT ((abs(13)/abs(a)) in (+coalesce((select 13 from t1 where (t1.e in (select cast(avg(t1.c) AS integer) from t1 union select case +count(distinct t1.c) when +count(*) then ( -min( -b)) else count(*) end*max(e) from t1)) and +case when c in (select (11) from t1 union select  -t1.c from t1) then 17 when 17 in (select 17 from t1 union select d from t1) then c else t1.a end>13),case when c<=11 then t1.e when t1.e<=b then t1.d else t1.e end)-11,11,17))}
} {1524}
do_test randexpr-2.125 {
  db eval {SELECT (e)+case when t1.a>e then t1.f else t1.b+case when b between coalesce((select max(t1.d-~(abs(a)/abs(c))+t1.c) from t1 where f in (select  -min(t1.f)-+cast(avg(e) AS integer) from t1 union select  -(cast(avg(13) AS integer)) from t1) and f<=a and not exists(select 1 from t1 where f not between t1.d and t1.d or (f)<=a) and (t1.f) between 11 and d),t1.a) and t1.f then e when (11<d) then 11 else d end end & t1.e FROM t1 WHERE NOT ((abs(13)/abs(a)) in (+coalesce((select 13 from t1 where (t1.e in (select cast(avg(t1.c) AS integer) from t1 union select case +count(distinct t1.c) when +count(*) then ( -min( -b)) else count(*) end*max(e) from t1)) and +case when c in (select (11) from t1 union select  -t1.c from t1) then 17 when 17 in (select 17 from t1 union select d from t1) then c else t1.a end>13),case when c<=11 then t1.e when t1.e<=b then t1.d else t1.e end)-11,11,17))}
} {176}
do_test randexpr-2.126 {
  db eval {SELECT coalesce((select max(~d-t1.f+b-13) from t1 where t1.c not between case when +f=t1.b then 13 when ~f not in (~t1.a,coalesce((select max(t1.b) from t1 where b between c-t1.c+e and (t1.b)),coalesce((select max(t1.d) from t1 where not e in (select 17 from t1 union select t1.c+e | a from t1)),b)),t1.e) then t1.b else a end and c),t1.a) FROM t1 WHERE (select (++ -count(*) | cast(avg(t1.b) AS integer) | ++(max(t1.d))+count(*)+max(t1.b)-count(distinct t1.e)-+abs( -+~max((abs(t1.c)/abs((select min(a) from t1)))))+count(distinct t1.a-t1.b)) from t1) between e and c}
} {}
do_test randexpr-2.127 {
  db eval {SELECT coalesce((select max(~d-t1.f+b-13) from t1 where t1.c not between case when +f=t1.b then 13 when ~f not in (~t1.a,coalesce((select max(t1.b) from t1 where b between c-t1.c+e and (t1.b)),coalesce((select max(t1.d) from t1 where not e in (select 17 from t1 union select t1.c+e | a from t1)),b)),t1.e) then t1.b else a end and c),t1.a) FROM t1 WHERE NOT ((select (++ -count(*) | cast(avg(t1.b) AS integer) | ++(max(t1.d))+count(*)+max(t1.b)-count(distinct t1.e)-+abs( -+~max((abs(t1.c)/abs((select min(a) from t1)))))+count(distinct t1.a-t1.b)) from t1) between e and c)}
} {100}
do_test randexpr-2.128 {
  db eval {SELECT coalesce((select max(~d-t1.f+b-13) from t1 where t1.c not between case when +f=t1.b then 13 when ~f not in (~t1.a,coalesce((select max(t1.b) from t1 where b between c-t1.c+e and (t1.b)),coalesce((select max(t1.d) from t1 where not e in (select 17 from t1 union select t1.c+e & a from t1)),b)),t1.e) then t1.b else a end and c),t1.a) FROM t1 WHERE NOT ((select (++ -count(*) | cast(avg(t1.b) AS integer) | ++(max(t1.d))+count(*)+max(t1.b)-count(distinct t1.e)-+abs( -+~max((abs(t1.c)/abs((select min(a) from t1)))))+count(distinct t1.a-t1.b)) from t1) between e and c)}
} {100}
do_test randexpr-2.129 {
  db eval {SELECT a+case when exists(select 1 from t1 where 19>=e) then b*b+coalesce((select max( -coalesce((select max(19 | t1.e) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where +case t1.a when a then a else (17) end*19 in (select max(d) from t1 union select max(t1.a) from t1) and not exists(select 1 from t1 where t1.a<=11)) or 11>(19))),11* -a)) from t1 where t1.e<>17),f) else t1.e end-11 FROM t1 WHERE (t1.a>=(abs(coalesce((select +13*t1.a | c from t1 where 11+case when exists(select 1 from t1 where case when +t1.d in (select case +count(*) when count(distinct 11) then count(*) else (min(11)) end from t1 union select max( -11) from t1) or 11<> -t1.f then t1.d when t1.b in (13,a,d) then c else c end+t1.b=b) then e-c else (t1.d) end>t1.d),d))/abs(t1.f)) and 11 in (select  -t1.a from t1 union select 13 from t1))}
} {}
do_test randexpr-2.130 {
  db eval {SELECT a+case when exists(select 1 from t1 where 19>=e) then b*b+coalesce((select max( -coalesce((select max(19 | t1.e) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where +case t1.a when a then a else (17) end*19 in (select max(d) from t1 union select max(t1.a) from t1) and not exists(select 1 from t1 where t1.a<=11)) or 11>(19))),11* -a)) from t1 where t1.e<>17),f) else t1.e end-11 FROM t1 WHERE NOT ((t1.a>=(abs(coalesce((select +13*t1.a | c from t1 where 11+case when exists(select 1 from t1 where case when +t1.d in (select case +count(*) when count(distinct 11) then count(*) else (min(11)) end from t1 union select max( -11) from t1) or 11<> -t1.f then t1.d when t1.b in (13,a,d) then c else c end+t1.b=b) then e-c else (t1.d) end>t1.d),d))/abs(t1.f)) and 11 in (select  -t1.a from t1 union select 13 from t1)))}
} {589}
do_test randexpr-2.131 {
  db eval {SELECT a+case when exists(select 1 from t1 where 19>=e) then b*b+coalesce((select max( -coalesce((select max(19 & t1.e) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where +case t1.a when a then a else (17) end*19 in (select max(d) from t1 union select max(t1.a) from t1) and not exists(select 1 from t1 where t1.a<=11)) or 11>(19))),11* -a)) from t1 where t1.e<>17),f) else t1.e end-11 FROM t1 WHERE NOT ((t1.a>=(abs(coalesce((select +13*t1.a | c from t1 where 11+case when exists(select 1 from t1 where case when +t1.d in (select case +count(*) when count(distinct 11) then count(*) else (min(11)) end from t1 union select max( -11) from t1) or 11<> -t1.f then t1.d when t1.b in (13,a,d) then c else c end+t1.b=b) then e-c else (t1.d) end>t1.d),d))/abs(t1.f)) and 11 in (select  -t1.a from t1 union select 13 from t1)))}
} {589}
do_test randexpr-2.132 {
  db eval {SELECT case ~13 when t1.e then e else (select case case (abs(count(*))-~count(*)+count(*) | count(*)-count(*)+max(t1.b)* -(cast(avg(13) AS integer)) |  -(count(distinct t1.c))) when min(e) then (min(13)) else count(*) end*count(*) when max(e) then count(distinct  -d) else count(*) end from t1) end-t1.d*case (abs(e | t1.b)/abs((select cast(avg(t1.c) AS integer) from t1))) when (select cast(avg(a) AS integer) from t1) then t1.c else f+13 end FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case when t1.a>t1.f-~case when ~t1.d+c+t1.f>11 then t1.a when (f between t1.f and t1.c) then t1.f else 13 end*t1.a then t1.d when c<t1.e or e>19 then c else t1.e end from t1 where e<>a and 19<>t1.f),t1.b)+t1.f-t1.e<d)}
} {-245199}
do_test randexpr-2.133 {
  db eval {SELECT case ~13 when t1.e then e else (select case case (abs(count(*))-~count(*)+count(*) | count(*)-count(*)+max(t1.b)* -(cast(avg(13) AS integer)) |  -(count(distinct t1.c))) when min(e) then (min(13)) else count(*) end*count(*) when max(e) then count(distinct  -d) else count(*) end from t1) end-t1.d*case (abs(e | t1.b)/abs((select cast(avg(t1.c) AS integer) from t1))) when (select cast(avg(a) AS integer) from t1) then t1.c else f+13 end FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select case when t1.a>t1.f-~case when ~t1.d+c+t1.f>11 then t1.a when (f between t1.f and t1.c) then t1.f else 13 end*t1.a then t1.d when c<t1.e or e>19 then c else t1.e end from t1 where e<>a and 19<>t1.f),t1.b)+t1.f-t1.e<d))}
} {}
do_test randexpr-2.134 {
  db eval {SELECT case ~13 when t1.e then e else (select case case (abs(count(*))-~count(*)+count(*) & count(*)-count(*)+max(t1.b)* -(cast(avg(13) AS integer)) &  -(count(distinct t1.c))) when min(e) then (min(13)) else count(*) end*count(*) when max(e) then count(distinct  -d) else count(*) end from t1) end-t1.d*case (abs(e & t1.b)/abs((select cast(avg(t1.c) AS integer) from t1))) when (select cast(avg(a) AS integer) from t1) then t1.c else f+13 end FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case when t1.a>t1.f-~case when ~t1.d+c+t1.f>11 then t1.a when (f between t1.f and t1.c) then t1.f else 13 end*t1.a then t1.d when c<t1.e or e>19 then c else t1.e end from t1 where e<>a and 19<>t1.f),t1.b)+t1.f-t1.e<d)}
} {-245199}
do_test randexpr-2.135 {
  db eval {SELECT 11-case when 17<=c and (select ( -abs(case count(*)+~case  -min(e) when count(distinct t1.a) then  -count(*) else min(a) end+max(t1.c) when count(*) then max(b) else  -count(distinct 19) end)*cast(avg(17) AS integer)) from t1) not in (case f when e then 19 | 11 else (t1.d) end,d, -t1.b) then +t1.c when t1.d not in (11,c,t1.a) then 13 else a end-t1.d*t1.d FROM t1 WHERE ((abs((abs(coalesce((select a from t1 where (select max(case when t1.f=b then e when 11>t1.c and 11<>e then 13 else a end-(a))-max(t1.e)*count(distinct t1.f) | case max((f)) when (count(distinct f)) then count(*) else min(t1.c) end+min(19) from t1) not in (11,19,t1.e)),t1.f*17))/abs(a)))/abs(c)) in (select t1.c from t1 union select t1.a from t1)) or ( -t1.f=e)}
} {}
do_test randexpr-2.136 {
  db eval {SELECT 11-case when 17<=c and (select ( -abs(case count(*)+~case  -min(e) when count(distinct t1.a) then  -count(*) else min(a) end+max(t1.c) when count(*) then max(b) else  -count(distinct 19) end)*cast(avg(17) AS integer)) from t1) not in (case f when e then 19 | 11 else (t1.d) end,d, -t1.b) then +t1.c when t1.d not in (11,c,t1.a) then 13 else a end-t1.d*t1.d FROM t1 WHERE NOT (((abs((abs(coalesce((select a from t1 where (select max(case when t1.f=b then e when 11>t1.c and 11<>e then 13 else a end-(a))-max(t1.e)*count(distinct t1.f) | case max((f)) when (count(distinct f)) then count(*) else min(t1.c) end+min(19) from t1) not in (11,19,t1.e)),t1.f*17))/abs(a)))/abs(c)) in (select t1.c from t1 union select t1.a from t1)) or ( -t1.f=e))}
} {-160289}
do_test randexpr-2.137 {
  db eval {SELECT 11-case when 17<=c and (select ( -abs(case count(*)+~case  -min(e) when count(distinct t1.a) then  -count(*) else min(a) end+max(t1.c) when count(*) then max(b) else  -count(distinct 19) end)*cast(avg(17) AS integer)) from t1) not in (case f when e then 19 & 11 else (t1.d) end,d, -t1.b) then +t1.c when t1.d not in (11,c,t1.a) then 13 else a end-t1.d*t1.d FROM t1 WHERE NOT (((abs((abs(coalesce((select a from t1 where (select max(case when t1.f=b then e when 11>t1.c and 11<>e then 13 else a end-(a))-max(t1.e)*count(distinct t1.f) | case max((f)) when (count(distinct f)) then count(*) else min(t1.c) end+min(19) from t1) not in (11,19,t1.e)),t1.f*17))/abs(a)))/abs(c)) in (select t1.c from t1 union select t1.a from t1)) or ( -t1.f=e))}
} {-160289}
do_test randexpr-2.138 {
  db eval {SELECT (f+case +t1.e when t1.d then 17 else f*19 end |  -(abs( -coalesce((select 17* -c+19 from t1 where (abs(case 19*e*d when (select +(cast(avg( -11) AS integer)) |  -count(*)*max( -13) from t1) then 11 | case t1.b when a then a else t1.f end else t1.a end)/abs(a)) in (select t1.b from t1 union select (a) from t1)),t1.b))/abs( -13))) FROM t1 WHERE +b in (select case case case when not ((~coalesce((select t1.e+d from t1 where (19 between f and t1.b)),(select cast(avg(c+t1.b) AS integer)++cast(avg(b) AS integer) from t1))) not in (t1.c+c,b,e)) or (13 not between d and t1.d) then 13 else b end when  -11 then 13 else 19 end*t1.e when (f) then 19 else 19 end from t1 union select f from t1)}
} {}
do_test randexpr-2.139 {
  db eval {SELECT (f+case +t1.e when t1.d then 17 else f*19 end |  -(abs( -coalesce((select 17* -c+19 from t1 where (abs(case 19*e*d when (select +(cast(avg( -11) AS integer)) |  -count(*)*max( -13) from t1) then 11 | case t1.b when a then a else t1.f end else t1.a end)/abs(a)) in (select t1.b from t1 union select (a) from t1)),t1.b))/abs( -13))) FROM t1 WHERE NOT (+b in (select case case case when not ((~coalesce((select t1.e+d from t1 where (19 between f and t1.b)),(select cast(avg(c+t1.b) AS integer)++cast(avg(b) AS integer) from t1))) not in (t1.c+c,b,e)) or (13 not between d and t1.d) then 13 else b end when  -11 then 13 else 19 end*t1.e when (f) then 19 else 19 end from t1 union select f from t1))}
} {-15}
do_test randexpr-2.140 {
  db eval {SELECT (f+case +t1.e when t1.d then 17 else f*19 end &  -(abs( -coalesce((select 17* -c+19 from t1 where (abs(case 19*e*d when (select +(cast(avg( -11) AS integer)) &  -count(*)*max( -13) from t1) then 11 & case t1.b when a then a else t1.f end else t1.a end)/abs(a)) in (select t1.b from t1 union select (a) from t1)),t1.b))/abs( -13))) FROM t1 WHERE NOT (+b in (select case case case when not ((~coalesce((select t1.e+d from t1 where (19 between f and t1.b)),(select cast(avg(c+t1.b) AS integer)++cast(avg(b) AS integer) from t1))) not in (t1.c+c,b,e)) or (13 not between d and t1.d) then 13 else b end when  -11 then 13 else 19 end*t1.e when (f) then 19 else 19 end from t1 union select f from t1))}
} {12000}
do_test randexpr-2.141 {
  db eval {SELECT 11*coalesce((select max(t1.f) from t1 where a-case t1.c when +coalesce((select t1.a-t1.b from t1 where (abs(19)/abs(b)) in (17-case when a<t1.b then t1.a when c not between 19 and t1.d then e else (t1.b) end, -t1.b,f) or 19 in (select t1.b from t1 union select t1.a from t1)),e)+t1.f*t1.b then t1.c else 13 end in (select t1.b from t1 union select f from t1) or e<>17),d)*(t1.e) FROM t1 WHERE (coalesce((select max(~t1.b) from t1 where t1.c in (select ~+case count(distinct a) when (max(t1.a)) then (count(*)) else ~+abs(cast(avg(d | t1.a) AS integer)+case (cast(avg(13) AS integer)) when cast(avg(b) AS integer) then cast(avg(t1.f) AS integer) else min(t1.a) end) | count(distinct c)*( -( -max(t1.f)))*count(*) end from t1 union select count(distinct  -e) from t1)),~a-11)<19 or t1.a*13<>t1.d and not exists(select 1 from t1 where t1.e=e))}
} {3300000}
do_test randexpr-2.142 {
  db eval {SELECT 11*coalesce((select max(t1.f) from t1 where a-case t1.c when +coalesce((select t1.a-t1.b from t1 where (abs(19)/abs(b)) in (17-case when a<t1.b then t1.a when c not between 19 and t1.d then e else (t1.b) end, -t1.b,f) or 19 in (select t1.b from t1 union select t1.a from t1)),e)+t1.f*t1.b then t1.c else 13 end in (select t1.b from t1 union select f from t1) or e<>17),d)*(t1.e) FROM t1 WHERE NOT ((coalesce((select max(~t1.b) from t1 where t1.c in (select ~+case count(distinct a) when (max(t1.a)) then (count(*)) else ~+abs(cast(avg(d | t1.a) AS integer)+case (cast(avg(13) AS integer)) when cast(avg(b) AS integer) then cast(avg(t1.f) AS integer) else min(t1.a) end) | count(distinct c)*( -( -max(t1.f)))*count(*) end from t1 union select count(distinct  -e) from t1)),~a-11)<19 or t1.a*13<>t1.d and not exists(select 1 from t1 where t1.e=e)))}
} {}
do_test randexpr-2.143 {
  db eval {SELECT 11+t1.b+17+case when 13 not between t1.d*(17)+d-t1.f and 13 then t1.d when case when case when t1.f not in (t1.b,c,t1.f) and  -d between d and 11 then d else 19 end not between a and e then t1.b when t1.d in (17,13,11) then 19 else t1.e end*a>e then t1.a else t1.d end*f*e FROM t1 WHERE not exists(select 1 from t1 where (t1.f) in (b-b,(select +(max( -13*t1.c*c+t1.e+case t1.a when +t1.d-(c) then  -t1.a else t1.c end | 19* -17)*count(distinct a) | (count(distinct t1.f)))++cast(avg(f) AS integer)-max(13) | cast(avg(b) AS integer) from t1),t1.f))}
} {}
do_test randexpr-2.144 {
  db eval {SELECT 11+t1.b+17+case when 13 not between t1.d*(17)+d-t1.f and 13 then t1.d when case when case when t1.f not in (t1.b,c,t1.f) and  -d between d and 11 then d else 19 end not between a and e then t1.b when t1.d in (17,13,11) then 19 else t1.e end*a>e then t1.a else t1.d end*f*e FROM t1 WHERE NOT (not exists(select 1 from t1 where (t1.f) in (b-b,(select +(max( -13*t1.c*c+t1.e+case t1.a when +t1.d-(c) then  -t1.a else t1.c end | 19* -17)*count(distinct a) | (count(distinct t1.f)))++cast(avg(f) AS integer)-max(13) | cast(avg(b) AS integer) from t1),t1.f)))}
} {120000228}
do_test randexpr-2.145 {
  db eval {SELECT ((abs(+((select count(*)*abs(min((abs(case (abs(c)/abs(f)) | e when case when 19>=d then 13 when a=f then 13 else f end then b else a end+t1.a)/abs(11))*t1.c*17))-cast(avg(e) AS integer)*count(*) from t1)))/abs(coalesce((select max(case when t1.a in (select t1.c from t1 union select 19 from t1) then e else t1.e end) from t1 where (t1.a<= -t1.e)),17)+c*13))) FROM t1 WHERE exists(select 1 from t1 where ~coalesce((select max(c) from t1 where exists(select 1 from t1 where case when not case coalesce((select max(coalesce((select d from t1 where exists(select 1 from t1 where a<(t1.c))),19)) from t1 where e=t1.e),13) when t1.e then t1.b else f end in (select abs((min(e))*(max(t1.d))+min(t1.e)*(( -((max(t1.a)))))) from t1 union select count(distinct t1.a) from t1) then coalesce((select t1.c from t1 where t1.a< -t1.c and a in (t1.b,t1.f,t1.c)),17) else 17 end>=t1.f)),t1.f)+t1.a*b in (select c from t1 union select 19 from t1)) or exists(select 1 from t1 where not t1.f not in (t1.f,11,t1.d) and 19<=19)}
} {23}
do_test randexpr-2.146 {
  db eval {SELECT ((abs(+((select count(*)*abs(min((abs(case (abs(c)/abs(f)) | e when case when 19>=d then 13 when a=f then 13 else f end then b else a end+t1.a)/abs(11))*t1.c*17))-cast(avg(e) AS integer)*count(*) from t1)))/abs(coalesce((select max(case when t1.a in (select t1.c from t1 union select 19 from t1) then e else t1.e end) from t1 where (t1.a<= -t1.e)),17)+c*13))) FROM t1 WHERE NOT (exists(select 1 from t1 where ~coalesce((select max(c) from t1 where exists(select 1 from t1 where case when not case coalesce((select max(coalesce((select d from t1 where exists(select 1 from t1 where a<(t1.c))),19)) from t1 where e=t1.e),13) when t1.e then t1.b else f end in (select abs((min(e))*(max(t1.d))+min(t1.e)*(( -((max(t1.a)))))) from t1 union select count(distinct t1.a) from t1) then coalesce((select t1.c from t1 where t1.a< -t1.c and a in (t1.b,t1.f,t1.c)),17) else 17 end>=t1.f)),t1.f)+t1.a*b in (select c from t1 union select 19 from t1)) or exists(select 1 from t1 where not t1.f not in (t1.f,11,t1.d) and 19<=19))}
} {}
do_test randexpr-2.147 {
  db eval {SELECT ((abs(+((select count(*)*abs(min((abs(case (abs(c)/abs(f)) & e when case when 19>=d then 13 when a=f then 13 else f end then b else a end+t1.a)/abs(11))*t1.c*17))-cast(avg(e) AS integer)*count(*) from t1)))/abs(coalesce((select max(case when t1.a in (select t1.c from t1 union select 19 from t1) then e else t1.e end) from t1 where (t1.a<= -t1.e)),17)+c*13))) FROM t1 WHERE exists(select 1 from t1 where ~coalesce((select max(c) from t1 where exists(select 1 from t1 where case when not case coalesce((select max(coalesce((select d from t1 where exists(select 1 from t1 where a<(t1.c))),19)) from t1 where e=t1.e),13) when t1.e then t1.b else f end in (select abs((min(e))*(max(t1.d))+min(t1.e)*(( -((max(t1.a)))))) from t1 union select count(distinct t1.a) from t1) then coalesce((select t1.c from t1 where t1.a< -t1.c and a in (t1.b,t1.f,t1.c)),17) else 17 end>=t1.f)),t1.f)+t1.a*b in (select c from t1 union select 19 from t1)) or exists(select 1 from t1 where not t1.f not in (t1.f,11,t1.d) and 19<=19)}
} {23}
do_test randexpr-2.148 {
  db eval {SELECT coalesce((select max(case when t1.f between 17 and 11+case when not coalesce((select max(11) from t1 where t1.f in (select max(t1.d) from t1 union select  -count(*) from t1) or 17=(13) or f in (( -t1.b),13,a)),case when d>13 then 13 else 11 end) between 19 and 19 then 19 when t1.c=d then e else 17 end then t1.e else t1.d end) from t1 where e in (select  -(+max(11)-max((t1.a))+ -count(distinct d) | cast(avg(t1.a) AS integer)*count(distinct b))-count(*)* -count(distinct t1.e) from t1 union select cast(avg(d) AS integer) from t1)),d)+b FROM t1 WHERE (select +~abs( -min(t1.a)-abs(count(*)))+ -abs(+ -+case (cast(avg(a) AS integer)) when min(e+t1.d) then +case cast(avg(coalesce((select max(t1.f+ -t1.e) from t1 where t1.c between 13 and t1.b),19)) AS integer) when ~~min(t1.f) then count(distinct 13) else cast(avg(t1.b) AS integer) end+count(distinct t1.e) else  -count(*) end | max(a)+max(t1.e)) from t1)+e<a}
} {600}
do_test randexpr-2.149 {
  db eval {SELECT coalesce((select max(case when t1.f between 17 and 11+case when not coalesce((select max(11) from t1 where t1.f in (select max(t1.d) from t1 union select  -count(*) from t1) or 17=(13) or f in (( -t1.b),13,a)),case when d>13 then 13 else 11 end) between 19 and 19 then 19 when t1.c=d then e else 17 end then t1.e else t1.d end) from t1 where e in (select  -(+max(11)-max((t1.a))+ -count(distinct d) | cast(avg(t1.a) AS integer)*count(distinct b))-count(*)* -count(distinct t1.e) from t1 union select cast(avg(d) AS integer) from t1)),d)+b FROM t1 WHERE NOT ((select +~abs( -min(t1.a)-abs(count(*)))+ -abs(+ -+case (cast(avg(a) AS integer)) when min(e+t1.d) then +case cast(avg(coalesce((select max(t1.f+ -t1.e) from t1 where t1.c between 13 and t1.b),19)) AS integer) when ~~min(t1.f) then count(distinct 13) else cast(avg(t1.b) AS integer) end+count(distinct t1.e) else  -count(*) end | max(a)+max(t1.e)) from t1)+e<a)}
} {}
do_test randexpr-2.150 {
  db eval {SELECT coalesce((select max(case when t1.f between 17 and 11+case when not coalesce((select max(11) from t1 where t1.f in (select max(t1.d) from t1 union select  -count(*) from t1) or 17=(13) or f in (( -t1.b),13,a)),case when d>13 then 13 else 11 end) between 19 and 19 then 19 when t1.c=d then e else 17 end then t1.e else t1.d end) from t1 where e in (select  -(+max(11)-max((t1.a))+ -count(distinct d) & cast(avg(t1.a) AS integer)*count(distinct b))-count(*)* -count(distinct t1.e) from t1 union select cast(avg(d) AS integer) from t1)),d)+b FROM t1 WHERE (select +~abs( -min(t1.a)-abs(count(*)))+ -abs(+ -+case (cast(avg(a) AS integer)) when min(e+t1.d) then +case cast(avg(coalesce((select max(t1.f+ -t1.e) from t1 where t1.c between 13 and t1.b),19)) AS integer) when ~~min(t1.f) then count(distinct 13) else cast(avg(t1.b) AS integer) end+count(distinct t1.e) else  -count(*) end | max(a)+max(t1.e)) from t1)+e<a}
} {600}
do_test randexpr-2.151 {
  db eval {SELECT case when ((+b in (select min(coalesce((select c from t1 where t1.b-t1.c+coalesce((select max(case when 13 in (select  -count(distinct b)*max(c) from t1 union select (( - -cast(avg(d) AS integer))) from t1) then b else t1.f end) from t1 where t1.f<t1.e),13) between (b) and  -t1.b), -e)) from t1 union select +( -case  -abs(( -count(*))) | count(distinct d) when max(17) then max(13) else  -(min(13)) end) | (count(distinct t1.a)) from t1))) then t1.f else case c when t1.d then e else 11 end end FROM t1 WHERE t1.a+case t1.c when case c when 13 then t1.f*(select count(*) | cast(avg(a) AS integer) from t1)+13*t1.a else (select abs( -count(*)) from t1) end then b else t1.c end in (t1.a,d,17) or  -(select ~ -max(c) from t1)+17<>d or t1.a not between b and 13 or f<> -19 and t1.b>a}
} {11}
do_test randexpr-2.152 {
  db eval {SELECT case when ((+b in (select min(coalesce((select c from t1 where t1.b-t1.c+coalesce((select max(case when 13 in (select  -count(distinct b)*max(c) from t1 union select (( - -cast(avg(d) AS integer))) from t1) then b else t1.f end) from t1 where t1.f<t1.e),13) between (b) and  -t1.b), -e)) from t1 union select +( -case  -abs(( -count(*))) | count(distinct d) when max(17) then max(13) else  -(min(13)) end) | (count(distinct t1.a)) from t1))) then t1.f else case c when t1.d then e else 11 end end FROM t1 WHERE NOT (t1.a+case t1.c when case c when 13 then t1.f*(select count(*) | cast(avg(a) AS integer) from t1)+13*t1.a else (select abs( -count(*)) from t1) end then b else t1.c end in (t1.a,d,17) or  -(select ~ -max(c) from t1)+17<>d or t1.a not between b and 13 or f<> -19 and t1.b>a)}
} {}
do_test randexpr-2.153 {
  db eval {SELECT case when ((+b in (select min(coalesce((select c from t1 where t1.b-t1.c+coalesce((select max(case when 13 in (select  -count(distinct b)*max(c) from t1 union select (( - -cast(avg(d) AS integer))) from t1) then b else t1.f end) from t1 where t1.f<t1.e),13) between (b) and  -t1.b), -e)) from t1 union select +( -case  -abs(( -count(*))) & count(distinct d) when max(17) then max(13) else  -(min(13)) end) & (count(distinct t1.a)) from t1))) then t1.f else case c when t1.d then e else 11 end end FROM t1 WHERE t1.a+case t1.c when case c when 13 then t1.f*(select count(*) | cast(avg(a) AS integer) from t1)+13*t1.a else (select abs( -count(*)) from t1) end then b else t1.c end in (t1.a,d,17) or  -(select ~ -max(c) from t1)+17<>d or t1.a not between b and 13 or f<> -19 and t1.b>a}
} {11}
do_test randexpr-2.154 {
  db eval {SELECT case when t1.a | (abs(case when  -t1.e in (17,11,(abs(t1.b)/abs(b+case when (17 in (select f-c from t1 union select  -a from t1)) or t1.b<=a then d when t1.e in (select  -(count(*)) from t1 union select max(t1.b) from t1) then c else c end*a-t1.f))) then t1.b else t1.e end)/abs(t1.f))>=11 and not exists(select 1 from t1 where exists(select 1 from t1 where t1.d in (select t1.d from t1 union select 17 from t1))) then c else t1.c end FROM t1 WHERE (coalesce((select f from t1 where case a-e+a when (abs(t1.d)/abs((coalesce((select ~t1.e*+t1.a+b*a*(abs(19)/abs(a))*a+e from t1 where 13<t1.e),a))))+11 then 11 else d end>=13 or t1.b<= -19),t1.f)+17* -t1.c<t1.c)}
} {300}
do_test randexpr-2.155 {
  db eval {SELECT case when t1.a | (abs(case when  -t1.e in (17,11,(abs(t1.b)/abs(b+case when (17 in (select f-c from t1 union select  -a from t1)) or t1.b<=a then d when t1.e in (select  -(count(*)) from t1 union select max(t1.b) from t1) then c else c end*a-t1.f))) then t1.b else t1.e end)/abs(t1.f))>=11 and not exists(select 1 from t1 where exists(select 1 from t1 where t1.d in (select t1.d from t1 union select 17 from t1))) then c else t1.c end FROM t1 WHERE NOT ((coalesce((select f from t1 where case a-e+a when (abs(t1.d)/abs((coalesce((select ~t1.e*+t1.a+b*a*(abs(19)/abs(a))*a+e from t1 where 13<t1.e),a))))+11 then 11 else d end>=13 or t1.b<= -19),t1.f)+17* -t1.c<t1.c))}
} {}
do_test randexpr-2.156 {
  db eval {SELECT case when t1.a & (abs(case when  -t1.e in (17,11,(abs(t1.b)/abs(b+case when (17 in (select f-c from t1 union select  -a from t1)) or t1.b<=a then d when t1.e in (select  -(count(*)) from t1 union select max(t1.b) from t1) then c else c end*a-t1.f))) then t1.b else t1.e end)/abs(t1.f))>=11 and not exists(select 1 from t1 where exists(select 1 from t1 where t1.d in (select t1.d from t1 union select 17 from t1))) then c else t1.c end FROM t1 WHERE (coalesce((select f from t1 where case a-e+a when (abs(t1.d)/abs((coalesce((select ~t1.e*+t1.a+b*a*(abs(19)/abs(a))*a+e from t1 where 13<t1.e),a))))+11 then 11 else d end>=13 or t1.b<= -19),t1.f)+17* -t1.c<t1.c)}
} {300}
do_test randexpr-2.157 {
  db eval {SELECT coalesce((select max(~t1.b) from t1 where b in (select count(distinct b) from t1 union select max(case coalesce((select max(b) from t1 where d in (select t1.f from t1 union select d from t1) and t1.a=d),t1.a) when  -t1.a then d*t1.e+t1.c-11+b | e-t1.a+e+t1.f else c end) from t1)),t1.a) FROM t1 WHERE (e<t1.f*case 17 when t1.a then t1.d else +coalesce((select max(17) from t1 where not 13<>~a-11),t1.f) end)}
} {100}
do_test randexpr-2.158 {
  db eval {SELECT coalesce((select max(~t1.b) from t1 where b in (select count(distinct b) from t1 union select max(case coalesce((select max(b) from t1 where d in (select t1.f from t1 union select d from t1) and t1.a=d),t1.a) when  -t1.a then d*t1.e+t1.c-11+b | e-t1.a+e+t1.f else c end) from t1)),t1.a) FROM t1 WHERE NOT ((e<t1.f*case 17 when t1.a then t1.d else +coalesce((select max(17) from t1 where not 13<>~a-11),t1.f) end))}
} {}
do_test randexpr-2.159 {
  db eval {SELECT coalesce((select max(~t1.b) from t1 where b in (select count(distinct b) from t1 union select max(case coalesce((select max(b) from t1 where d in (select t1.f from t1 union select d from t1) and t1.a=d),t1.a) when  -t1.a then d*t1.e+t1.c-11+b & e-t1.a+e+t1.f else c end) from t1)),t1.a) FROM t1 WHERE (e<t1.f*case 17 when t1.a then t1.d else +coalesce((select max(17) from t1 where not 13<>~a-11),t1.f) end)}
} {100}
do_test randexpr-2.160 {
  db eval {SELECT case when not t1.c not in (13,d,~case when coalesce((select max((abs(t1.c)/abs(t1.e))) from t1 where b-t1.d+b+t1.f>a),t1.a) in (select 19 from t1 union select t1.a from t1) then  -b else a end*b | d) and  -(t1.b)>=e and 11<d or ((19))<> -t1.c then t1.f else t1.f end+(t1.b)+a FROM t1 WHERE e>e}
} {}
do_test randexpr-2.161 {
  db eval {SELECT case when not t1.c not in (13,d,~case when coalesce((select max((abs(t1.c)/abs(t1.e))) from t1 where b-t1.d+b+t1.f>a),t1.a) in (select 19 from t1 union select t1.a from t1) then  -b else a end*b | d) and  -(t1.b)>=e and 11<d or ((19))<> -t1.c then t1.f else t1.f end+(t1.b)+a FROM t1 WHERE NOT (e>e)}
} {900}
do_test randexpr-2.162 {
  db eval {SELECT case when not t1.c not in (13,d,~case when coalesce((select max((abs(t1.c)/abs(t1.e))) from t1 where b-t1.d+b+t1.f>a),t1.a) in (select 19 from t1 union select t1.a from t1) then  -b else a end*b & d) and  -(t1.b)>=e and 11<d or ((19))<> -t1.c then t1.f else t1.f end+(t1.b)+a FROM t1 WHERE NOT (e>e)}
} {900}
do_test randexpr-2.163 {
  db eval {SELECT coalesce((select t1.c*c from t1 where (select (abs(cast(avg(b*13) AS integer))) from t1) in (select 11 from t1 union select e | a-17 from t1)), -case t1.c when t1.b++(select cast(avg(e) AS integer) from t1) then 17 else t1.b end)-d FROM t1 WHERE b<=t1.d}
} {-600}
do_test randexpr-2.164 {
  db eval {SELECT coalesce((select t1.c*c from t1 where (select (abs(cast(avg(b*13) AS integer))) from t1) in (select 11 from t1 union select e | a-17 from t1)), -case t1.c when t1.b++(select cast(avg(e) AS integer) from t1) then 17 else t1.b end)-d FROM t1 WHERE NOT (b<=t1.d)}
} {}
do_test randexpr-2.165 {
  db eval {SELECT coalesce((select t1.c*c from t1 where (select (abs(cast(avg(b*13) AS integer))) from t1) in (select 11 from t1 union select e & a-17 from t1)), -case t1.c when t1.b++(select cast(avg(e) AS integer) from t1) then 17 else t1.b end)-d FROM t1 WHERE b<=t1.d}
} {-600}
do_test randexpr-2.166 {
  db eval {SELECT coalesce((select max((case (abs(t1.b)/abs(e)) when 13 then ((select +case count(*)*count(distinct coalesce((select max((11)+b) from t1 where exists(select 1 from t1 where t1.e=(t1.b))), -13)) when count(distinct  -c) then count(*)*max( -d) else max((a)) end+min(c) from t1)) else t1.a end-(abs(case when a=17 and e<=b then a when a>=e then t1.c else t1.c end+13)/abs(e))*(e))) from t1 where t1.a in (select d from t1 union select  -t1.e from t1)),13) FROM t1 WHERE not coalesce((select max(case when f<=d | b | case when case when (t1.c in (f,19,c)) then t1.f when d>t1.b then t1.f else t1.f end<=c then 11 else c end- -t1.c-13 and t1.c in (select b from t1 union select  -17 from t1) then t1.b else a end) from t1 where 11 between d and a), -17) not between t1.f and t1.f and t1.f>11 or (not exists(select 1 from t1 where t1.b in (select min(t1.d) from t1 union select min(c) from t1)))}
} {13}
do_test randexpr-2.167 {
  db eval {SELECT coalesce((select max((case (abs(t1.b)/abs(e)) when 13 then ((select +case count(*)*count(distinct coalesce((select max((11)+b) from t1 where exists(select 1 from t1 where t1.e=(t1.b))), -13)) when count(distinct  -c) then count(*)*max( -d) else max((a)) end+min(c) from t1)) else t1.a end-(abs(case when a=17 and e<=b then a when a>=e then t1.c else t1.c end+13)/abs(e))*(e))) from t1 where t1.a in (select d from t1 union select  -t1.e from t1)),13) FROM t1 WHERE NOT (not coalesce((select max(case when f<=d | b | case when case when (t1.c in (f,19,c)) then t1.f when d>t1.b then t1.f else t1.f end<=c then 11 else c end- -t1.c-13 and t1.c in (select b from t1 union select  -17 from t1) then t1.b else a end) from t1 where 11 between d and a), -17) not between t1.f and t1.f and t1.f>11 or (not exists(select 1 from t1 where t1.b in (select min(t1.d) from t1 union select min(c) from t1))))}
} {}
do_test randexpr-2.168 {
  db eval {SELECT case when ((t1.e | (select min( -t1.f) from t1)*((abs(b)/abs(19)))-b<=t1.b and not e>13 or  -f in (select count(distinct e)-min(t1.a) from t1 union select count(distinct f) from t1))) then 13 when 17 between f and 19 or 11 between b and 19 or not t1.f>e then t1.d else d | f end FROM t1 WHERE not case when t1.a=t1.a then c when ~case when case when t1.e in (select + -count(distinct t1.d) from t1 union select cast(avg(t1.a) AS integer) from t1) then (t1.e) when 17 in (13, -f,a) then t1.d else d end<17 then e else f end+17+a* -e+b+b>t1.e then t1.e else t1.a end<c and a in (select max( -t1.f) | count(distinct t1.b)+~~count(distinct t1.b)-max(e)- -max(a) from t1 union select min(11) from t1)}
} {}
do_test randexpr-2.169 {
  db eval {SELECT case when ((t1.e | (select min( -t1.f) from t1)*((abs(b)/abs(19)))-b<=t1.b and not e>13 or  -f in (select count(distinct e)-min(t1.a) from t1 union select count(distinct f) from t1))) then 13 when 17 between f and 19 or 11 between b and 19 or not t1.f>e then t1.d else d | f end FROM t1 WHERE NOT (not case when t1.a=t1.a then c when ~case when case when t1.e in (select + -count(distinct t1.d) from t1 union select cast(avg(t1.a) AS integer) from t1) then (t1.e) when 17 in (13, -f,a) then t1.d else d end<17 then e else f end+17+a* -e+b+b>t1.e then t1.e else t1.a end<c and a in (select max( -t1.f) | count(distinct t1.b)+~~count(distinct t1.b)-max(e)- -max(a) from t1 union select min(11) from t1))}
} {984}
do_test randexpr-2.170 {
  db eval {SELECT case when ((t1.e & (select min( -t1.f) from t1)*((abs(b)/abs(19)))-b<=t1.b and not e>13 or  -f in (select count(distinct e)-min(t1.a) from t1 union select count(distinct f) from t1))) then 13 when 17 between f and 19 or 11 between b and 19 or not t1.f>e then t1.d else d & f end FROM t1 WHERE NOT (not case when t1.a=t1.a then c when ~case when case when t1.e in (select + -count(distinct t1.d) from t1 union select cast(avg(t1.a) AS integer) from t1) then (t1.e) when 17 in (13, -f,a) then t1.d else d end<17 then e else f end+17+a* -e+b+b>t1.e then t1.e else t1.a end<c and a in (select max( -t1.f) | count(distinct t1.b)+~~count(distinct t1.b)-max(e)- -max(a) from t1 union select min(11) from t1))}
} {16}
do_test randexpr-2.171 {
  db eval {SELECT coalesce((select (select cast(avg(~13) AS integer)-count(distinct ~19-coalesce((select d-17 from t1 where case when (case 17 when b then d else (select min(11) | min(17) from t1)++t1.a end in (d, -c,t1.d)) then b else t1.c end between t1.a and (t1.e)),19)-t1.f) from t1) | (abs(t1.e)/abs(t1.e)) from t1 where (t1.c not in (( -t1.d),(t1.b),(d)))),t1.e) FROM t1 WHERE 13 between 19 and ~ -(abs( -t1.d | coalesce((select t1.f from t1 where 19 not between + -case when ~~b+coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where (select cast(avg(19) AS integer)-cast(avg(b) AS integer) from t1)<>a and 19 between 11 and b and 11 between a and b)),t1.f) | c in ( -t1.c,13,b) then 11 when f in (select min(t1.d) from t1 union select cast(avg(f) AS integer) from t1) then t1.b else a end and t1.a),t1.c))/abs(11))+ -f}
} {}
do_test randexpr-2.172 {
  db eval {SELECT coalesce((select (select cast(avg(~13) AS integer)-count(distinct ~19-coalesce((select d-17 from t1 where case when (case 17 when b then d else (select min(11) | min(17) from t1)++t1.a end in (d, -c,t1.d)) then b else t1.c end between t1.a and (t1.e)),19)-t1.f) from t1) | (abs(t1.e)/abs(t1.e)) from t1 where (t1.c not in (( -t1.d),(t1.b),(d)))),t1.e) FROM t1 WHERE NOT (13 between 19 and ~ -(abs( -t1.d | coalesce((select t1.f from t1 where 19 not between + -case when ~~b+coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where (select cast(avg(19) AS integer)-cast(avg(b) AS integer) from t1)<>a and 19 between 11 and b and 11 between a and b)),t1.f) | c in ( -t1.c,13,b) then 11 when f in (select min(t1.d) from t1 union select cast(avg(f) AS integer) from t1) then t1.b else a end and t1.a),t1.c))/abs(11))+ -f)}
} {-15}
do_test randexpr-2.173 {
  db eval {SELECT coalesce((select (select cast(avg(~13) AS integer)-count(distinct ~19-coalesce((select d-17 from t1 where case when (case 17 when b then d else (select min(11) & min(17) from t1)++t1.a end in (d, -c,t1.d)) then b else t1.c end between t1.a and (t1.e)),19)-t1.f) from t1) & (abs(t1.e)/abs(t1.e)) from t1 where (t1.c not in (( -t1.d),(t1.b),(d)))),t1.e) FROM t1 WHERE NOT (13 between 19 and ~ -(abs( -t1.d | coalesce((select t1.f from t1 where 19 not between + -case when ~~b+coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where (select cast(avg(19) AS integer)-cast(avg(b) AS integer) from t1)<>a and 19 between 11 and b and 11 between a and b)),t1.f) | c in ( -t1.c,13,b) then 11 when f in (select min(t1.d) from t1 union select cast(avg(f) AS integer) from t1) then t1.b else a end and t1.a),t1.c))/abs(11))+ -f)}
} {1}
do_test randexpr-2.174 {
  db eval {SELECT coalesce((select max(+(d+a)*b) from t1 where (case e-t1.b when 17+11*13 then t1.a else 17 end-(17)<>(select cast(avg(t1.f) AS integer) from t1))),case when case when 11+13<>19 then 13 else t1.f end*e in (a,t1.f,t1.c) and not exists(select 1 from t1 where t1.b in (select  - -count(distinct t1.b)*( -count(*)) from t1 union select count(distinct t1.e) from t1)) then t1.c else a end) FROM t1 WHERE case when t1.d in (select count(*)-count(*)+ -min(case d when t1.c then 19 else 11 end)*count(*) | min(19)-(max((e))) from t1 union select count(*) from t1) then c when exists(select 1 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (abs(b)/abs(t1.c))>coalesce((select max(f) from t1 where f<=t1.a),t1.d)))) then f*t1.c+11 else t1.f end+e-e*t1.f<=17}
} {100000}
do_test randexpr-2.175 {
  db eval {SELECT coalesce((select max(+(d+a)*b) from t1 where (case e-t1.b when 17+11*13 then t1.a else 17 end-(17)<>(select cast(avg(t1.f) AS integer) from t1))),case when case when 11+13<>19 then 13 else t1.f end*e in (a,t1.f,t1.c) and not exists(select 1 from t1 where t1.b in (select  - -count(distinct t1.b)*( -count(*)) from t1 union select count(distinct t1.e) from t1)) then t1.c else a end) FROM t1 WHERE NOT (case when t1.d in (select count(*)-count(*)+ -min(case d when t1.c then 19 else 11 end)*count(*) | min(19)-(max((e))) from t1 union select count(*) from t1) then c when exists(select 1 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (abs(b)/abs(t1.c))>coalesce((select max(f) from t1 where f<=t1.a),t1.d)))) then f*t1.c+11 else t1.f end+e-e*t1.f<=17)}
} {}
do_test randexpr-2.176 {
  db eval {SELECT t1.c*case when t1.e>(select +cast(avg(13) AS integer)*min((11)* - -d |  - -coalesce((select max(b) from t1 where (select cast(avg((abs(a)/abs(b-(e)))) AS integer) from t1)+11*c<t1.d),e)-t1.f-t1.b+(t1.a)) from t1) then t1.c when +b in (17,a,b) then d else f end FROM t1 WHERE ((not exists(select 1 from t1 where not (exists(select 1 from t1 where (t1.c in (select t1.d from t1 union select  -c from t1)) or (select cast(avg(~(e)) AS integer) | min(case when f=t1.e and t1.e in (t1.b,t1.f,t1.a) then t1.f when t1.d>=a then t1.b else t1.b end | 19+a-c)*count(distinct t1.d)-+count(distinct t1.d) from t1) not in (19,d,b) and t1.f not between b and t1.f)))))}
} {}
do_test randexpr-2.177 {
  db eval {SELECT t1.c*case when t1.e>(select +cast(avg(13) AS integer)*min((11)* - -d |  - -coalesce((select max(b) from t1 where (select cast(avg((abs(a)/abs(b-(e)))) AS integer) from t1)+11*c<t1.d),e)-t1.f-t1.b+(t1.a)) from t1) then t1.c when +b in (17,a,b) then d else f end FROM t1 WHERE NOT (((not exists(select 1 from t1 where not (exists(select 1 from t1 where (t1.c in (select t1.d from t1 union select  -c from t1)) or (select cast(avg(~(e)) AS integer) | min(case when f=t1.e and t1.e in (t1.b,t1.f,t1.a) then t1.f when t1.d>=a then t1.b else t1.b end | 19+a-c)*count(distinct t1.d)-+count(distinct t1.d) from t1) not in (19,d,b) and t1.f not between b and t1.f))))))}
} {90000}
do_test randexpr-2.178 {
  db eval {SELECT t1.c*case when t1.e>(select +cast(avg(13) AS integer)*min((11)* - -d &  - -coalesce((select max(b) from t1 where (select cast(avg((abs(a)/abs(b-(e)))) AS integer) from t1)+11*c<t1.d),e)-t1.f-t1.b+(t1.a)) from t1) then t1.c when +b in (17,a,b) then d else f end FROM t1 WHERE NOT (((not exists(select 1 from t1 where not (exists(select 1 from t1 where (t1.c in (select t1.d from t1 union select  -c from t1)) or (select cast(avg(~(e)) AS integer) | min(case when f=t1.e and t1.e in (t1.b,t1.f,t1.a) then t1.f when t1.d>=a then t1.b else t1.b end | 19+a-c)*count(distinct t1.d)-+count(distinct t1.d) from t1) not in (19,d,b) and t1.f not between b and t1.f))))))}
} {120000}
do_test randexpr-2.179 {
  db eval {SELECT case when not exists(select 1 from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where not d*19=b))) or t1.a-a-t1.d*t1.f in (select ~case cast(avg(t1.d) AS integer) | count(*)+max(t1.c) when max(17) then cast(avg( -f) AS integer) else  -min(e) end from t1 union select max( -13) from t1)) then (select abs((+ -min(a)) | min(t1.a)-cast(avg(t1.f) AS integer)) | max(e) from t1) else 11 end*a | t1.a*f FROM t1 WHERE t1.c in (c,t1.b,~e) and 13+19-t1.b | coalesce((select max(case d when +t1.e+13*13 then coalesce((select case when f<t1.f then ~d else 19 end from t1 where not d>=e or  -f<=e and t1.d<>19),d) else d end) from t1 where t1.d<b),t1.a)*d*(a)<=t1.d}
} {61036}
do_test randexpr-2.180 {
  db eval {SELECT case when not exists(select 1 from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where not d*19=b))) or t1.a-a-t1.d*t1.f in (select ~case cast(avg(t1.d) AS integer) | count(*)+max(t1.c) when max(17) then cast(avg( -f) AS integer) else  -min(e) end from t1 union select max( -13) from t1)) then (select abs((+ -min(a)) | min(t1.a)-cast(avg(t1.f) AS integer)) | max(e) from t1) else 11 end*a | t1.a*f FROM t1 WHERE NOT (t1.c in (c,t1.b,~e) and 13+19-t1.b | coalesce((select max(case d when +t1.e+13*13 then coalesce((select case when f<t1.f then ~d else 19 end from t1 where not d>=e or  -f<=e and t1.d<>19),d) else d end) from t1 where t1.d<b),t1.a)*d*(a)<=t1.d)}
} {}
do_test randexpr-2.181 {
  db eval {SELECT case when not exists(select 1 from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where not d*19=b))) or t1.a-a-t1.d*t1.f in (select ~case cast(avg(t1.d) AS integer) & count(*)+max(t1.c) when max(17) then cast(avg( -f) AS integer) else  -min(e) end from t1 union select max( -13) from t1)) then (select abs((+ -min(a)) & min(t1.a)-cast(avg(t1.f) AS integer)) & max(e) from t1) else 11 end*a & t1.a*f FROM t1 WHERE t1.c in (c,t1.b,~e) and 13+19-t1.b | coalesce((select max(case d when +t1.e+13*13 then coalesce((select case when f<t1.f then ~d else 19 end from t1 where not d>=e or  -f<=e and t1.d<>19),d) else d end) from t1 where t1.d<b),t1.a)*d*(a)<=t1.d}
} {64}
do_test randexpr-2.182 {
  db eval {SELECT (abs(t1.f-(abs(case c when t1.a+(select max(17-coalesce((select +e-t1.a+11-13+d+11-t1.a from t1 where t1.e in (select ~coalesce((select a from t1 where t1.c-a=b),t1.c)+17 from t1 union select t1.e from t1)),c)-d) from t1) then 17 else  -t1.e end)/abs(d))-17)/abs(t1.b)) FROM t1 WHERE b in (select +count(distinct (19)-11) from t1 union select case count(*) when  -case min((abs(t1.c*(t1.c)+11)/abs(19))*~d*f) when abs(count(*)+count(*)) then (+(min(e)* -cast(avg(17) AS integer)* -cast(avg(d) AS integer)+max(t1.f))) else (count(*)) end | (min( -((t1.b)))) then (max(t1.c)) else  -count(distinct t1.d) end from t1) and not exists(select 1 from t1 where d<f)}
} {}
do_test randexpr-2.183 {
  db eval {SELECT (abs(t1.f-(abs(case c when t1.a+(select max(17-coalesce((select +e-t1.a+11-13+d+11-t1.a from t1 where t1.e in (select ~coalesce((select a from t1 where t1.c-a=b),t1.c)+17 from t1 union select t1.e from t1)),c)-d) from t1) then 17 else  -t1.e end)/abs(d))-17)/abs(t1.b)) FROM t1 WHERE NOT (b in (select +count(distinct (19)-11) from t1 union select case count(*) when  -case min((abs(t1.c*(t1.c)+11)/abs(19))*~d*f) when abs(count(*)+count(*)) then (+(min(e)* -cast(avg(17) AS integer)* -cast(avg(d) AS integer)+max(t1.f))) else (count(*)) end | (min( -((t1.b)))) then (max(t1.c)) else  -count(distinct t1.d) end from t1) and not exists(select 1 from t1 where d<f))}
} {2}
do_test randexpr-2.184 {
  db eval {SELECT ~case +~c+(case when not exists(select 1 from t1 where t1.d in (select abs( -abs(max(t1.f)-count(distinct e)* -cast(avg(11) AS integer) | count(*))+min(f)*min( -17)*cast(avg(19) AS integer)) from t1 union select count(*) from t1)) or (t1.f)<>t1.b then d*t1.f*17 else (b) end)+t1.f*13 when c then t1.a else t1.e end- -t1.f FROM t1 WHERE b-case when t1.b=t1.b and (coalesce((select max(t1.e) from t1 where t1.b in (select ~cast(avg(19) AS integer)+max(t1.b)+min(t1.e) from t1 union select max(t1.a) from t1) or exists(select 1 from t1 where 11 in (select max(t1.e) from t1 union select max(t1.f) from t1))),(abs(17)/abs(17)))) not between c and t1.a then 13 else 13 end | t1.c in (select ++cast(avg(f) AS integer)-(+(count(distinct 13) | max(19))-count(*) |  -max(t1.e)) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.185 {
  db eval {SELECT ~case +~c+(case when not exists(select 1 from t1 where t1.d in (select abs( -abs(max(t1.f)-count(distinct e)* -cast(avg(11) AS integer) | count(*))+min(f)*min( -17)*cast(avg(19) AS integer)) from t1 union select count(*) from t1)) or (t1.f)<>t1.b then d*t1.f*17 else (b) end)+t1.f*13 when c then t1.a else t1.e end- -t1.f FROM t1 WHERE NOT (b-case when t1.b=t1.b and (coalesce((select max(t1.e) from t1 where t1.b in (select ~cast(avg(19) AS integer)+max(t1.b)+min(t1.e) from t1 union select max(t1.a) from t1) or exists(select 1 from t1 where 11 in (select max(t1.e) from t1 union select max(t1.f) from t1))),(abs(17)/abs(17)))) not between c and t1.a then 13 else 13 end | t1.c in (select ++cast(avg(f) AS integer)-(+(count(distinct 13) | max(19))-count(*) |  -max(t1.e)) from t1 union select count(*) from t1))}
} {99}
do_test randexpr-2.186 {
  db eval {SELECT ~case +~c+(case when not exists(select 1 from t1 where t1.d in (select abs( -abs(max(t1.f)-count(distinct e)* -cast(avg(11) AS integer) & count(*))+min(f)*min( -17)*cast(avg(19) AS integer)) from t1 union select count(*) from t1)) or (t1.f)<>t1.b then d*t1.f*17 else (b) end)+t1.f*13 when c then t1.a else t1.e end- -t1.f FROM t1 WHERE NOT (b-case when t1.b=t1.b and (coalesce((select max(t1.e) from t1 where t1.b in (select ~cast(avg(19) AS integer)+max(t1.b)+min(t1.e) from t1 union select max(t1.a) from t1) or exists(select 1 from t1 where 11 in (select max(t1.e) from t1 union select max(t1.f) from t1))),(abs(17)/abs(17)))) not between c and t1.a then 13 else 13 end | t1.c in (select ++cast(avg(f) AS integer)-(+(count(distinct 13) | max(19))-count(*) |  -max(t1.e)) from t1 union select count(*) from t1))}
} {99}
do_test randexpr-2.187 {
  db eval {SELECT case when t1.c in (select c from t1 union select a from t1) then 11 when ((select max(19) from t1) | t1.a+e not between (case  -19 when b*e-b-case when b<>~d*t1.d+t1.c*d then t1.d when t1.c=19 then f else d end-f*t1.d then t1.d else 13 end) and 13) then 11 else t1.b end FROM t1 WHERE t1.b*coalesce((select max(t1.d) from t1 where  -f<=(select max(t1.e) from t1)*e),case when case when t1.e- -13>t1.b+t1.f+c then 13 else  -d end in (select 19 from t1 union select t1.f from t1) then e when t1.b in (select ~count(distinct t1.a)+count(*) from t1 union select abs( - -((cast(avg(c) AS integer)))*(cast(avg(t1.b) AS integer))) from t1) then 17 else d end)+ -17 | t1.a-t1.d in (t1.e,f,f)}
} {}
do_test randexpr-2.188 {
  db eval {SELECT case when t1.c in (select c from t1 union select a from t1) then 11 when ((select max(19) from t1) | t1.a+e not between (case  -19 when b*e-b-case when b<>~d*t1.d+t1.c*d then t1.d when t1.c=19 then f else d end-f*t1.d then t1.d else 13 end) and 13) then 11 else t1.b end FROM t1 WHERE NOT (t1.b*coalesce((select max(t1.d) from t1 where  -f<=(select max(t1.e) from t1)*e),case when case when t1.e- -13>t1.b+t1.f+c then 13 else  -d end in (select 19 from t1 union select t1.f from t1) then e when t1.b in (select ~count(distinct t1.a)+count(*) from t1 union select abs( - -((cast(avg(c) AS integer)))*(cast(avg(t1.b) AS integer))) from t1) then 17 else d end)+ -17 | t1.a-t1.d in (t1.e,f,f))}
} {11}
do_test randexpr-2.189 {
  db eval {SELECT case when t1.c in (select c from t1 union select a from t1) then 11 when ((select max(19) from t1) & t1.a+e not between (case  -19 when b*e-b-case when b<>~d*t1.d+t1.c*d then t1.d when t1.c=19 then f else d end-f*t1.d then t1.d else 13 end) and 13) then 11 else t1.b end FROM t1 WHERE NOT (t1.b*coalesce((select max(t1.d) from t1 where  -f<=(select max(t1.e) from t1)*e),case when case when t1.e- -13>t1.b+t1.f+c then 13 else  -d end in (select 19 from t1 union select t1.f from t1) then e when t1.b in (select ~count(distinct t1.a)+count(*) from t1 union select abs( - -((cast(avg(c) AS integer)))*(cast(avg(t1.b) AS integer))) from t1) then 17 else d end)+ -17 | t1.a-t1.d in (t1.e,f,f))}
} {11}
do_test randexpr-2.190 {
  db eval {SELECT ~(d)-(select case case cast(avg(t1.b- -~b) AS integer) when max(coalesce((select e from t1 where 11<>e),coalesce((select c from t1 where c not in (t1.e,a,(17)) or t1.b in ((b),t1.c,t1.f)),13))) then +cast(avg(d) AS integer) | case max(t1.c) when min((e)) then max(e)+cast(avg(t1.d) AS integer) else min(t1.f) end+max(d) else count(*) end |  -cast(avg(t1.f) AS integer) |  - -count(distinct c)*max(b) when count(distinct t1.d) then  - -min(a) else count(*) end from t1) FROM t1 WHERE t1.c+a=t1.e+t1.c*t1.e | case t1.d when case when 13 in (select min(c) from t1 union select max(d) from t1) or t1.f>=13 then 19 when t1.c<=11 then  -t1.b else 13 end then 13 else t1.e end or f in (select t1.a from t1 union select t1.f from t1) or (t1.a<t1.b) and e>t1.b and (((t1.d not between  -a and t1.f))) or t1.a not in ( -t1.d,13,a) and d<c or d=t1.d or e<d}
} {-402}
do_test randexpr-2.191 {
  db eval {SELECT ~(d)-(select case case cast(avg(t1.b- -~b) AS integer) when max(coalesce((select e from t1 where 11<>e),coalesce((select c from t1 where c not in (t1.e,a,(17)) or t1.b in ((b),t1.c,t1.f)),13))) then +cast(avg(d) AS integer) | case max(t1.c) when min((e)) then max(e)+cast(avg(t1.d) AS integer) else min(t1.f) end+max(d) else count(*) end |  -cast(avg(t1.f) AS integer) |  - -count(distinct c)*max(b) when count(distinct t1.d) then  - -min(a) else count(*) end from t1) FROM t1 WHERE NOT (t1.c+a=t1.e+t1.c*t1.e | case t1.d when case when 13 in (select min(c) from t1 union select max(d) from t1) or t1.f>=13 then 19 when t1.c<=11 then  -t1.b else 13 end then 13 else t1.e end or f in (select t1.a from t1 union select t1.f from t1) or (t1.a<t1.b) and e>t1.b and (((t1.d not between  -a and t1.f))) or t1.a not in ( -t1.d,13,a) and d<c or d=t1.d or e<d)}
} {}
do_test randexpr-2.192 {
  db eval {SELECT ~(d)-(select case case cast(avg(t1.b- -~b) AS integer) when max(coalesce((select e from t1 where 11<>e),coalesce((select c from t1 where c not in (t1.e,a,(17)) or t1.b in ((b),t1.c,t1.f)),13))) then +cast(avg(d) AS integer) & case max(t1.c) when min((e)) then max(e)+cast(avg(t1.d) AS integer) else min(t1.f) end+max(d) else count(*) end &  -cast(avg(t1.f) AS integer) &  - -count(distinct c)*max(b) when count(distinct t1.d) then  - -min(a) else count(*) end from t1) FROM t1 WHERE t1.c+a=t1.e+t1.c*t1.e | case t1.d when case when 13 in (select min(c) from t1 union select max(d) from t1) or t1.f>=13 then 19 when t1.c<=11 then  -t1.b else 13 end then 13 else t1.e end or f in (select t1.a from t1 union select t1.f from t1) or (t1.a<t1.b) and e>t1.b and (((t1.d not between  -a and t1.f))) or t1.a not in ( -t1.d,13,a) and d<c or d=t1.d or e<d}
} {-402}
do_test randexpr-2.193 {
  db eval {SELECT (abs(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.f<19 and coalesce((select max(case when t1.a+e in (select t1.c from t1 union select f from t1) then f else (17) end) from t1 where t1.e in (f,coalesce((select max(t1.f) from t1 where 17<=((abs(t1.d | (t1.a))/abs(13))*(a))-d),17),e)),t1.c) not between t1.b and 11 and 13<t1.f)),f+t1.d))/abs(19)) FROM t1 WHERE 11*c+17-f in (select min(t1.e*11*case when exists(select 1 from t1 where not exists(select 1 from t1 where + -17<a)) then (abs((d))/abs(13)) when 11 in (select case count(*) when count(distinct t1.f) then count(distinct 17) else cast(avg((11)) AS integer) end from t1 union select cast(avg(t1.c) AS integer) from t1) then b else e end) from t1 union select case count(*) when  -count(distinct t1.d) then max(a) else (count(distinct t1.c))-max((b)) | (count(distinct t1.e))*count(distinct (13))-count(distinct e) end-count(*)-count(*) from t1)}
} {}
do_test randexpr-2.194 {
  db eval {SELECT (abs(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.f<19 and coalesce((select max(case when t1.a+e in (select t1.c from t1 union select f from t1) then f else (17) end) from t1 where t1.e in (f,coalesce((select max(t1.f) from t1 where 17<=((abs(t1.d | (t1.a))/abs(13))*(a))-d),17),e)),t1.c) not between t1.b and 11 and 13<t1.f)),f+t1.d))/abs(19)) FROM t1 WHERE NOT (11*c+17-f in (select min(t1.e*11*case when exists(select 1 from t1 where not exists(select 1 from t1 where + -17<a)) then (abs((d))/abs(13)) when 11 in (select case count(*) when count(distinct t1.f) then count(distinct 17) else cast(avg((11)) AS integer) end from t1 union select cast(avg(t1.c) AS integer) from t1) then b else e end) from t1 union select case count(*) when  -count(distinct t1.d) then max(a) else (count(distinct t1.c))-max((b)) | (count(distinct t1.e))*count(distinct (13))-count(distinct e) end-count(*)-count(*) from t1))}
} {52}
do_test randexpr-2.195 {
  db eval {SELECT (abs(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.f<19 and coalesce((select max(case when t1.a+e in (select t1.c from t1 union select f from t1) then f else (17) end) from t1 where t1.e in (f,coalesce((select max(t1.f) from t1 where 17<=((abs(t1.d & (t1.a))/abs(13))*(a))-d),17),e)),t1.c) not between t1.b and 11 and 13<t1.f)),f+t1.d))/abs(19)) FROM t1 WHERE NOT (11*c+17-f in (select min(t1.e*11*case when exists(select 1 from t1 where not exists(select 1 from t1 where + -17<a)) then (abs((d))/abs(13)) when 11 in (select case count(*) when count(distinct t1.f) then count(distinct 17) else cast(avg((11)) AS integer) end from t1 union select cast(avg(t1.c) AS integer) from t1) then b else e end) from t1 union select case count(*) when  -count(distinct t1.d) then max(a) else (count(distinct t1.c))-max((b)) | (count(distinct t1.e))*count(distinct (13))-count(distinct e) end-count(*)-count(*) from t1))}
} {52}
do_test randexpr-2.196 {
  db eval {SELECT coalesce((select max(~t1.d) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where c>t1.c or ((t1.f>e)) and t1.e-19+c+ -d*t1.d+11<>17+coalesce((select max(t1.d) from t1 where 17+t1.c<t1.d),t1.b) or f<>11))),11) | case e when c then a else t1.b end+a FROM t1 WHERE case when d not in (a,11,(13)) then a when exists(select 1 from t1 where case when case when case when (t1.c) in (c,e,b) then f else (19) end-t1.f<t1.d then 11 else a end>=t1.a then 11 else t1.c end in (select abs(~~max(t1.c)) from t1 union select cast(avg(c) AS integer) from t1)) then 11 else t1.f end in (select (~~count(*)*cast(avg(19) AS integer)) from t1 union select min(t1.d)+ -count(distinct f) from t1)}
} {}
do_test randexpr-2.197 {
  db eval {SELECT coalesce((select max(~t1.d) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where c>t1.c or ((t1.f>e)) and t1.e-19+c+ -d*t1.d+11<>17+coalesce((select max(t1.d) from t1 where 17+t1.c<t1.d),t1.b) or f<>11))),11) | case e when c then a else t1.b end+a FROM t1 WHERE NOT (case when d not in (a,11,(13)) then a when exists(select 1 from t1 where case when case when case when (t1.c) in (c,e,b) then f else (19) end-t1.f<t1.d then 11 else a end>=t1.a then 11 else t1.c end in (select abs(~~max(t1.c)) from t1 union select cast(avg(c) AS integer) from t1)) then 11 else t1.f end in (select (~~count(*)*cast(avg(19) AS integer)) from t1 union select min(t1.d)+ -count(distinct f) from t1))}
} {303}
do_test randexpr-2.198 {
  db eval {SELECT coalesce((select max(~t1.d) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where c>t1.c or ((t1.f>e)) and t1.e-19+c+ -d*t1.d+11<>17+coalesce((select max(t1.d) from t1 where 17+t1.c<t1.d),t1.b) or f<>11))),11) & case e when c then a else t1.b end+a FROM t1 WHERE NOT (case when d not in (a,11,(13)) then a when exists(select 1 from t1 where case when case when case when (t1.c) in (c,e,b) then f else (19) end-t1.f<t1.d then 11 else a end>=t1.a then 11 else t1.c end in (select abs(~~max(t1.c)) from t1 union select cast(avg(c) AS integer) from t1)) then 11 else t1.f end in (select (~~count(*)*cast(avg(19) AS integer)) from t1 union select min(t1.d)+ -count(distinct f) from t1))}
} {8}
do_test randexpr-2.199 {
  db eval {SELECT case when t1.e*t1.b<>e then 19 else  -11-b+coalesce((select max(t1.e+t1.f) from t1 where 11+f*t1.c<>t1.a*(~f+case when t1.f in (t1.f, -((13)),19) then t1.a when t1.e>17 then a else a end+b-t1.e-(f))),13)+d end+t1.b* -c FROM t1 WHERE exists(select 1 from t1 where coalesce((select max(t1.a*t1.e+13) from t1 where 13 in ((abs(e)/abs(t1.a)),a+t1.c,17*t1.c)),(select  -case max(c) | cast(avg(e) AS integer) when ~+ -count(distinct coalesce((select d from t1 where exists(select 1 from t1 where  -17<e)),( -t1.e))) | case max(11) when cast(avg(a) AS integer) then max( -t1.f) else count(distinct  -11) end then cast(avg(t1.d) AS integer) else max((d)) end*count(distinct t1.b) from t1) | t1.b-t1.d*t1.c+11)<=b)}
} {-59981}
do_test randexpr-2.200 {
  db eval {SELECT case when t1.e*t1.b<>e then 19 else  -11-b+coalesce((select max(t1.e+t1.f) from t1 where 11+f*t1.c<>t1.a*(~f+case when t1.f in (t1.f, -((13)),19) then t1.a when t1.e>17 then a else a end+b-t1.e-(f))),13)+d end+t1.b* -c FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(t1.a*t1.e+13) from t1 where 13 in ((abs(e)/abs(t1.a)),a+t1.c,17*t1.c)),(select  -case max(c) | cast(avg(e) AS integer) when ~+ -count(distinct coalesce((select d from t1 where exists(select 1 from t1 where  -17<e)),( -t1.e))) | case max(11) when cast(avg(a) AS integer) then max( -t1.f) else count(distinct  -11) end then cast(avg(t1.d) AS integer) else max((d)) end*count(distinct t1.b) from t1) | t1.b-t1.d*t1.c+11)<=b))}
} {}
do_test randexpr-2.201 {
  db eval {SELECT coalesce((select max(coalesce((select 19 from t1 where (case when ((abs(coalesce((select max(case when t1.a between (t1.c)+ -b and d then e else d end) from t1 where t1.e in (select (count(*)) from t1 union select max( -a)-count(distinct t1.c)-((min(13))) | max((t1.f)) from t1)),11))/abs(19)))+d>c then t1.b when 17 not between t1.e and c then 11 else f end in (select a from t1 union select 13 from t1))),11)) from t1 where not exists(select 1 from t1 where f=17)),e) FROM t1 WHERE ( -13 in (13,b,case when 19=11 then t1.d else case when (d | b-case when t1.f-(select +abs(cast(avg( -17* -17) AS integer)*count(*)+max(t1.e)) from t1)*t1.f not in (f,a,c) then t1.a else t1.b end between 19 and e) then a else 13 end end-t1.a) or t1.c<19)}
} {}
do_test randexpr-2.202 {
  db eval {SELECT coalesce((select max(coalesce((select 19 from t1 where (case when ((abs(coalesce((select max(case when t1.a between (t1.c)+ -b and d then e else d end) from t1 where t1.e in (select (count(*)) from t1 union select max( -a)-count(distinct t1.c)-((min(13))) | max((t1.f)) from t1)),11))/abs(19)))+d>c then t1.b when 17 not between t1.e and c then 11 else f end in (select a from t1 union select 13 from t1))),11)) from t1 where not exists(select 1 from t1 where f=17)),e) FROM t1 WHERE NOT (( -13 in (13,b,case when 19=11 then t1.d else case when (d | b-case when t1.f-(select +abs(cast(avg( -17* -17) AS integer)*count(*)+max(t1.e)) from t1)*t1.f not in (f,a,c) then t1.a else t1.b end between 19 and e) then a else 13 end end-t1.a) or t1.c<19))}
} {11}
do_test randexpr-2.203 {
  db eval {SELECT coalesce((select max(coalesce((select 19 from t1 where (case when ((abs(coalesce((select max(case when t1.a between (t1.c)+ -b and d then e else d end) from t1 where t1.e in (select (count(*)) from t1 union select max( -a)-count(distinct t1.c)-((min(13))) & max((t1.f)) from t1)),11))/abs(19)))+d>c then t1.b when 17 not between t1.e and c then 11 else f end in (select a from t1 union select 13 from t1))),11)) from t1 where not exists(select 1 from t1 where f=17)),e) FROM t1 WHERE NOT (( -13 in (13,b,case when 19=11 then t1.d else case when (d | b-case when t1.f-(select +abs(cast(avg( -17* -17) AS integer)*count(*)+max(t1.e)) from t1)*t1.f not in (f,a,c) then t1.a else t1.b end between 19 and e) then a else 13 end end-t1.a) or t1.c<19))}
} {11}
do_test randexpr-2.204 {
  db eval {SELECT  -~d*19-a-c | t1.c+(abs(case  -19 | ~case t1.d when c then t1.f else c end when +t1.d then 17 else case case when b>case case when t1.c=d or  -t1.a=17 then ((a)) when t1.a<>d then (t1.c) else a end+19+11 when 19 then t1.a else b end-(t1.e) then f else t1.c end when 17 then t1.b else a end end)/abs(d))+t1.b FROM t1 WHERE t1.f+13<>19}
} {7671}
do_test randexpr-2.205 {
  db eval {SELECT  -~d*19-a-c | t1.c+(abs(case  -19 | ~case t1.d when c then t1.f else c end when +t1.d then 17 else case case when b>case case when t1.c=d or  -t1.a=17 then ((a)) when t1.a<>d then (t1.c) else a end+19+11 when 19 then t1.a else b end-(t1.e) then f else t1.c end when 17 then t1.b else a end end)/abs(d))+t1.b FROM t1 WHERE NOT (t1.f+13<>19)}
} {}
do_test randexpr-2.206 {
  db eval {SELECT  -~d*19-a-c & t1.c+(abs(case  -19 & ~case t1.d when c then t1.f else c end when +t1.d then 17 else case case when b>case case when t1.c=d or  -t1.a=17 then ((a)) when t1.a<>d then (t1.c) else a end+19+11 when 19 then t1.a else b end-(t1.e) then f else t1.c end when 17 then t1.b else a end end)/abs(d))+t1.b FROM t1 WHERE t1.f+13<>19}
} {48}
do_test randexpr-2.207 {
  db eval {SELECT (abs(coalesce((select b from t1 where t1.a>(abs(t1.f)/abs(coalesce((select 13 from t1 where not coalesce((select (select cast(avg(case when case when t1.e not between t1.c and 19 then t1.d when d in (11,t1.b,13) then e else 17 end*b between 13 and (t1.b) then t1.f when a<>19 and t1.c not in (a,t1.f,b) then t1.e else t1.f end) AS integer) from t1)+t1.c-b* -a*f from t1 where (t1.d in (select c from t1 union select t1.b from t1))),t1.e)-c<>c),t1.c)))),e))/abs(t1.e)) FROM t1 WHERE (t1.a-t1.c-case when e<c*17 then t1.e when case case t1.b when t1.c then coalesce((select max(t1.c) from t1 where t1.c in (select ~cast(avg(case when 17 in (t1.f,t1.f,t1.a) then c when 13<>b then f else d end | t1.d) AS integer) from t1 union select count(distinct 11) from t1)),c) else t1.f end when f then 19 else t1.b end<t1.f then t1.b else t1.e end-11 not between 11 and t1.d)}
} {0}
do_test randexpr-2.208 {
  db eval {SELECT (abs(coalesce((select b from t1 where t1.a>(abs(t1.f)/abs(coalesce((select 13 from t1 where not coalesce((select (select cast(avg(case when case when t1.e not between t1.c and 19 then t1.d when d in (11,t1.b,13) then e else 17 end*b between 13 and (t1.b) then t1.f when a<>19 and t1.c not in (a,t1.f,b) then t1.e else t1.f end) AS integer) from t1)+t1.c-b* -a*f from t1 where (t1.d in (select c from t1 union select t1.b from t1))),t1.e)-c<>c),t1.c)))),e))/abs(t1.e)) FROM t1 WHERE NOT ((t1.a-t1.c-case when e<c*17 then t1.e when case case t1.b when t1.c then coalesce((select max(t1.c) from t1 where t1.c in (select ~cast(avg(case when 17 in (t1.f,t1.f,t1.a) then c when 13<>b then f else d end | t1.d) AS integer) from t1 union select count(distinct 11) from t1)),c) else t1.f end when f then 19 else t1.b end<t1.f then t1.b else t1.e end-11 not between 11 and t1.d))}
} {}
do_test randexpr-2.209 {
  db eval {SELECT case when t1.d<>d then case 11 when ~+case t1.a when (abs(t1.a)/abs( -c))*t1.c+ -a+coalesce((select t1.c from t1 where ((abs(e)/abs((case when (11>=e) then  -17 when (11)<=a then e else b end)+t1.f))>19)),b)-d then c else 17 end+ -b then ( -t1.a) else c end when 11<=t1.f then 11 else 17 end FROM t1 WHERE (coalesce((select max(17) from t1 where ~case ((select min( -e-a)*+cast(avg(11) AS integer)*count(*)-(count(*))*max(b)*min( -13)+count(*)-min( -13) from t1)+19)+a when e then (select min(f) from t1) else coalesce((select t1.f from t1 where 17>t1.c),19) end=11 and f=t1.b),19) not between  -a and t1.a)}
} {}
do_test randexpr-2.210 {
  db eval {SELECT case when t1.d<>d then case 11 when ~+case t1.a when (abs(t1.a)/abs( -c))*t1.c+ -a+coalesce((select t1.c from t1 where ((abs(e)/abs((case when (11>=e) then  -17 when (11)<=a then e else b end)+t1.f))>19)),b)-d then c else 17 end+ -b then ( -t1.a) else c end when 11<=t1.f then 11 else 17 end FROM t1 WHERE NOT ((coalesce((select max(17) from t1 where ~case ((select min( -e-a)*+cast(avg(11) AS integer)*count(*)-(count(*))*max(b)*min( -13)+count(*)-min( -13) from t1)+19)+a when e then (select min(f) from t1) else coalesce((select t1.f from t1 where 17>t1.c),19) end=11 and f=t1.b),19) not between  -a and t1.a))}
} {11}
do_test randexpr-2.211 {
  db eval {SELECT coalesce((select max(t1.e) from t1 where not d in (select (abs(t1.f)/abs(~case when (abs(t1.e)/abs( -t1.a))+t1.b-t1.e*t1.a-t1.c between b and t1.e then f else a end+19)) from t1 union select 13 from t1) or (t1.e=(a)) and  -11 in (select t1.f from t1 union select c from t1)),a)*coalesce((select max(f) from t1 where d=f),f)*c+(t1.c) FROM t1 WHERE case when +(abs(19)/abs(13*t1.e))<>11 then 19 when coalesce((select max(c) from t1 where t1.e+t1.a between t1.f and f),t1.a)=(a) then d else  -19 end<=f or (((e in (b,t1.b,13)))) or b<(f) and t1.a<>11 or exists(select 1 from t1 where t1.d=d) or (t1.a)<>a or t1.a<>e}
} {90000300}
do_test randexpr-2.212 {
  db eval {SELECT coalesce((select max(t1.e) from t1 where not d in (select (abs(t1.f)/abs(~case when (abs(t1.e)/abs( -t1.a))+t1.b-t1.e*t1.a-t1.c between b and t1.e then f else a end+19)) from t1 union select 13 from t1) or (t1.e=(a)) and  -11 in (select t1.f from t1 union select c from t1)),a)*coalesce((select max(f) from t1 where d=f),f)*c+(t1.c) FROM t1 WHERE NOT (case when +(abs(19)/abs(13*t1.e))<>11 then 19 when coalesce((select max(c) from t1 where t1.e+t1.a between t1.f and f),t1.a)=(a) then d else  -19 end<=f or (((e in (b,t1.b,13)))) or b<(f) and t1.a<>11 or exists(select 1 from t1 where t1.d=d) or (t1.a)<>a or t1.a<>e)}
} {}
do_test randexpr-2.213 {
  db eval {SELECT case (select abs(count(distinct  -17+(abs(c)/abs(case when exists(select 1 from t1 where (17<>(f))) then e when t1.c not between 11 and t1.d then +11 else t1.e end | b))+d)*+ -(min(f)*max(t1.e))*+cast(avg(t1.f) AS integer) | count(distinct (f))- - -count(*)-cast(avg((e)) AS integer)) from t1) when (abs(11)/abs(t1.e)) then 13 else b end FROM t1 WHERE case when t1.e not between coalesce((select (select count(*)+case max(17) when count(distinct 19-t1.c*t1.c-e) then  -min(b)-cast(avg((13)) AS integer)*count(*) else min(19) end from t1)*a*t1.d-17*a+17 from t1 where t1.d not in (13,t1.f, -c)),t1.c) and e then ( -b) when (13)>=(e) then t1.c else e end in (t1.d,t1.c, -11)}
} {}
do_test randexpr-2.214 {
  db eval {SELECT case (select abs(count(distinct  -17+(abs(c)/abs(case when exists(select 1 from t1 where (17<>(f))) then e when t1.c not between 11 and t1.d then +11 else t1.e end | b))+d)*+ -(min(f)*max(t1.e))*+cast(avg(t1.f) AS integer) | count(distinct (f))- - -count(*)-cast(avg((e)) AS integer)) from t1) when (abs(11)/abs(t1.e)) then 13 else b end FROM t1 WHERE NOT (case when t1.e not between coalesce((select (select count(*)+case max(17) when count(distinct 19-t1.c*t1.c-e) then  -min(b)-cast(avg((13)) AS integer)*count(*) else min(19) end from t1)*a*t1.d-17*a+17 from t1 where t1.d not in (13,t1.f, -c)),t1.c) and e then ( -b) when (13)>=(e) then t1.c else e end in (t1.d,t1.c, -11))}
} {200}
do_test randexpr-2.215 {
  db eval {SELECT case (select abs(count(distinct  -17+(abs(c)/abs(case when exists(select 1 from t1 where (17<>(f))) then e when t1.c not between 11 and t1.d then +11 else t1.e end & b))+d)*+ -(min(f)*max(t1.e))*+cast(avg(t1.f) AS integer) & count(distinct (f))- - -count(*)-cast(avg((e)) AS integer)) from t1) when (abs(11)/abs(t1.e)) then 13 else b end FROM t1 WHERE NOT (case when t1.e not between coalesce((select (select count(*)+case max(17) when count(distinct 19-t1.c*t1.c-e) then  -min(b)-cast(avg((13)) AS integer)*count(*) else min(19) end from t1)*a*t1.d-17*a+17 from t1 where t1.d not in (13,t1.f, -c)),t1.c) and e then ( -b) when (13)>=(e) then t1.c else e end in (t1.d,t1.c, -11))}
} {200}
do_test randexpr-2.216 {
  db eval {SELECT  -case when d<d or not exists(select 1 from t1 where not exists(select 1 from t1 where not not not exists(select 1 from t1 where not e+~t1.c between t1.e and t1.c and t1.c>t1.d))) then case +coalesce((select case when 13>t1.b then 17+t1.d+d when 17 in (t1.b,b,b) and 17<=t1.e then (c) else t1.d end from t1 where 17<a),11) when f then t1.c else b end when 19 between 11 and t1.e then f else a end-19*13 FROM t1 WHERE exists(select 1 from t1 where +13 in (select count(distinct 13) from t1 union select case count(*)+ -(max(t1.c)) when count(*) | ~( -count(*)-count(distinct  -f))+min(a)-max(t1.b) then  - -max(13) else max(e) end+count(distinct 17) from t1) and d*t1.b>b+t1.a*t1.a-coalesce((select max(d) from t1 where (17 between (t1.d) and (f))),t1.e)-t1.c and t1.d>11)}
} {}
do_test randexpr-2.217 {
  db eval {SELECT  -case when d<d or not exists(select 1 from t1 where not exists(select 1 from t1 where not not not exists(select 1 from t1 where not e+~t1.c between t1.e and t1.c and t1.c>t1.d))) then case +coalesce((select case when 13>t1.b then 17+t1.d+d when 17 in (t1.b,b,b) and 17<=t1.e then (c) else t1.d end from t1 where 17<a),11) when f then t1.c else b end when 19 between 11 and t1.e then f else a end-19*13 FROM t1 WHERE NOT (exists(select 1 from t1 where +13 in (select count(distinct 13) from t1 union select case count(*)+ -(max(t1.c)) when count(*) | ~( -count(*)-count(distinct  -f))+min(a)-max(t1.b) then  - -max(13) else max(e) end+count(distinct 17) from t1) and d*t1.b>b+t1.a*t1.a-coalesce((select max(d) from t1 where (17 between (t1.d) and (f))),t1.e)-t1.c and t1.d>11))}
} {-447}
do_test randexpr-2.218 {
  db eval {SELECT (select + -max(t1.c)*abs(min(t1.b) | case (abs(min(13)))+count(*)-max(t1.a) when max(~13) then abs( -~min(t1.b)+abs(count(distinct (select +++cast(avg(t1.b) AS integer)-case  -count(*) when  -count(*) then  -count(distinct b) else count(distinct c) end from t1)))) else count(*) end-max((e))) |  -cast(avg(t1.e) AS integer) from t1) FROM t1 WHERE exists(select 1 from t1 where  -f-d*t1.f-c-coalesce((select max(t1.a) from t1 where 11 not in ((select count(*) from t1),coalesce((select max(t1.f+e) from t1 where t1.b in (select count(distinct t1.c) from t1 union select  -case abs(abs(count(distinct 13))) when max(t1.b) then abs(cast(avg(11) AS integer)) else  -cast(avg(17) AS integer) end from t1)),case t1.f when  -b then 17 else 17 end)- -t1.f,b)),a)+f+c-t1.c<t1.b)}
} {-452}
do_test randexpr-2.219 {
  db eval {SELECT (select + -max(t1.c)*abs(min(t1.b) | case (abs(min(13)))+count(*)-max(t1.a) when max(~13) then abs( -~min(t1.b)+abs(count(distinct (select +++cast(avg(t1.b) AS integer)-case  -count(*) when  -count(*) then  -count(distinct b) else count(distinct c) end from t1)))) else count(*) end-max((e))) |  -cast(avg(t1.e) AS integer) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where  -f-d*t1.f-c-coalesce((select max(t1.a) from t1 where 11 not in ((select count(*) from t1),coalesce((select max(t1.f+e) from t1 where t1.b in (select count(distinct t1.c) from t1 union select  -case abs(abs(count(distinct 13))) when max(t1.b) then abs(cast(avg(11) AS integer)) else  -cast(avg(17) AS integer) end from t1)),case t1.f when  -b then 17 else 17 end)- -t1.f,b)),a)+f+c-t1.c<t1.b))}
} {}
do_test randexpr-2.220 {
  db eval {SELECT (select + -max(t1.c)*abs(min(t1.b) & case (abs(min(13)))+count(*)-max(t1.a) when max(~13) then abs( -~min(t1.b)+abs(count(distinct (select +++cast(avg(t1.b) AS integer)-case  -count(*) when  -count(*) then  -count(distinct b) else count(distinct c) end from t1)))) else count(*) end-max((e))) &  -cast(avg(t1.e) AS integer) from t1) FROM t1 WHERE exists(select 1 from t1 where  -f-d*t1.f-c-coalesce((select max(t1.a) from t1 where 11 not in ((select count(*) from t1),coalesce((select max(t1.f+e) from t1 where t1.b in (select count(distinct t1.c) from t1 union select  -case abs(abs(count(distinct 13))) when max(t1.b) then abs(cast(avg(11) AS integer)) else  -cast(avg(17) AS integer) end from t1)),case t1.f when  -b then 17 else 17 end)- -t1.f,b)),a)+f+c-t1.c<t1.b)}
} {-2560}
do_test randexpr-2.221 {
  db eval {SELECT  -+(select count(distinct case when (case ~c | coalesce((select max(t1.e-f+t1.d) from t1 where b-coalesce((select max(b) from t1 where t1.c in (select max(t1.d) from t1 union select min(a) from t1)),t1.f) in (select t1.a from t1 union select e from t1)),c) when e then  -c else  -t1.b end in ( -19, -d,b)) then d when t1.e in (19,d,19) and (t1.b between c and t1.a) then t1.d else 17 end-d) from t1) FROM t1 WHERE f<= -b}
} {}
do_test randexpr-2.222 {
  db eval {SELECT  -+(select count(distinct case when (case ~c | coalesce((select max(t1.e-f+t1.d) from t1 where b-coalesce((select max(b) from t1 where t1.c in (select max(t1.d) from t1 union select min(a) from t1)),t1.f) in (select t1.a from t1 union select e from t1)),c) when e then  -c else  -t1.b end in ( -19, -d,b)) then d when t1.e in (19,d,19) and (t1.b between c and t1.a) then t1.d else 17 end-d) from t1) FROM t1 WHERE NOT (f<= -b)}
} {-1}
do_test randexpr-2.223 {
  db eval {SELECT  -+(select count(distinct case when (case ~c & coalesce((select max(t1.e-f+t1.d) from t1 where b-coalesce((select max(b) from t1 where t1.c in (select max(t1.d) from t1 union select min(a) from t1)),t1.f) in (select t1.a from t1 union select e from t1)),c) when e then  -c else  -t1.b end in ( -19, -d,b)) then d when t1.e in (19,d,19) and (t1.b between c and t1.a) then t1.d else 17 end-d) from t1) FROM t1 WHERE NOT (f<= -b)}
} {-1}
do_test randexpr-2.224 {
  db eval {SELECT (abs(~(+t1.b))/abs(~coalesce((select max(t1.a) from t1 where t1.f<+case when not exists(select 1 from t1 where not c+11=case c when t1.e then 13 else t1.f end+t1.e) and t1.f in (select 11 from t1 union select t1.d from t1) and c not in (t1.f,17,a) then case when a=17 or t1.c between t1.e and 19 or t1.a<>e then 19 else t1.c-t1.d end else b end),(e))-t1.a+(13)-19)) FROM t1 WHERE (not t1.e not in (case when exists(select 1 from t1 where 17<=t1.f*17*t1.b) then f+coalesce((select max(t1.b-c-11+t1.c-a) from t1 where 13 in (select t1.e from t1 union select case when a not between t1.f and d or f<t1.f then d when t1.f<=e then d else e end+17- -17 from t1)),t1.c) else t1.f end,e,t1.a) or exists(select 1 from t1 where t1.a not in (t1.c,(t1.d),(t1.c))))}
} {0}
do_test randexpr-2.225 {
  db eval {SELECT (abs(~(+t1.b))/abs(~coalesce((select max(t1.a) from t1 where t1.f<+case when not exists(select 1 from t1 where not c+11=case c when t1.e then 13 else t1.f end+t1.e) and t1.f in (select 11 from t1 union select t1.d from t1) and c not in (t1.f,17,a) then case when a=17 or t1.c between t1.e and 19 or t1.a<>e then 19 else t1.c-t1.d end else b end),(e))-t1.a+(13)-19)) FROM t1 WHERE NOT ((not t1.e not in (case when exists(select 1 from t1 where 17<=t1.f*17*t1.b) then f+coalesce((select max(t1.b-c-11+t1.c-a) from t1 where 13 in (select t1.e from t1 union select case when a not between t1.f and d or f<t1.f then d when t1.f<=e then d else e end+17- -17 from t1)),t1.c) else t1.f end,e,t1.a) or exists(select 1 from t1 where t1.a not in (t1.c,(t1.d),(t1.c)))))}
} {}
do_test randexpr-2.226 {
  db eval {SELECT (select min(b) | case case cast(avg(c) AS integer) when ~+~count(distinct  -19*f*f) then count(distinct (select cast(avg(d-case when t1.a<=19 then 19 else 11 end+f+a) AS integer) from t1))+count(distinct t1.c)+ -+ -count(*) |  - -max((17))*min(t1.b)*min((e)) else max(t1.c) end when ( - - -min(a)) then ( -min(c)) else max((11)) end from t1) FROM t1 WHERE case when (((exists(select 1 from t1 where ~t1.d-t1.f between  -+t1.f*c and f and not t1.e in (19,a,13))) or  -e>=t1.b) and (t1.e<>( -t1.d)) and (t1.c<=13)) then c else d+11 end<=case when (t1.c)>=19 then (t1.e) when (f) not between 11 and f then coalesce((select 13 from t1 where  -t1.b>=d),13) else b end}
} {203}
do_test randexpr-2.227 {
  db eval {SELECT (select min(b) | case case cast(avg(c) AS integer) when ~+~count(distinct  -19*f*f) then count(distinct (select cast(avg(d-case when t1.a<=19 then 19 else 11 end+f+a) AS integer) from t1))+count(distinct t1.c)+ -+ -count(*) |  - -max((17))*min(t1.b)*min((e)) else max(t1.c) end when ( - - -min(a)) then ( -min(c)) else max((11)) end from t1) FROM t1 WHERE NOT (case when (((exists(select 1 from t1 where ~t1.d-t1.f between  -+t1.f*c and f and not t1.e in (19,a,13))) or  -e>=t1.b) and (t1.e<>( -t1.d)) and (t1.c<=13)) then c else d+11 end<=case when (t1.c)>=19 then (t1.e) when (f) not between 11 and f then coalesce((select 13 from t1 where  -t1.b>=d),13) else b end)}
} {}
do_test randexpr-2.228 {
  db eval {SELECT (select min(b) & case case cast(avg(c) AS integer) when ~+~count(distinct  -19*f*f) then count(distinct (select cast(avg(d-case when t1.a<=19 then 19 else 11 end+f+a) AS integer) from t1))+count(distinct t1.c)+ -+ -count(*) &  - -max((17))*min(t1.b)*min((e)) else max(t1.c) end when ( - - -min(a)) then ( -min(c)) else max((11)) end from t1) FROM t1 WHERE case when (((exists(select 1 from t1 where ~t1.d-t1.f between  -+t1.f*c and f and not t1.e in (19,a,13))) or  -e>=t1.b) and (t1.e<>( -t1.d)) and (t1.c<=13)) then c else d+11 end<=case when (t1.c)>=19 then (t1.e) when (f) not between 11 and f then coalesce((select 13 from t1 where  -t1.b>=d),13) else b end}
} {8}
do_test randexpr-2.229 {
  db eval {SELECT case when 19-b in (select (min(case coalesce((select e from t1 where (c not between c and e)),(select abs(count(distinct coalesce((select max( -coalesce((select max(17) from t1 where (d)>17 and c not between d and b),11)-d) from t1 where ((11)) not in (d,d,e)), - -e))) from t1)+t1.e+t1.a) when f then t1.e else t1.a end)) from t1 union select max(11) from t1) then c else f end+t1.e FROM t1 WHERE coalesce((select max(d) from t1 where coalesce((select max(case when (a++19=case t1.d when t1.e then t1.b else t1.a end*f) and  -13=a then case t1.d+13 when t1.f then 17 else t1.f end when (11 not in (d,17,t1.f)) then e else 11 end+b*t1.b) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where t1.f in (select t1.e from t1 union select b from t1)))),(d))<=c),a) between t1.f and d}
} {}
do_test randexpr-2.230 {
  db eval {SELECT case when 19-b in (select (min(case coalesce((select e from t1 where (c not between c and e)),(select abs(count(distinct coalesce((select max( -coalesce((select max(17) from t1 where (d)>17 and c not between d and b),11)-d) from t1 where ((11)) not in (d,d,e)), - -e))) from t1)+t1.e+t1.a) when f then t1.e else t1.a end)) from t1 union select max(11) from t1) then c else f end+t1.e FROM t1 WHERE NOT (coalesce((select max(d) from t1 where coalesce((select max(case when (a++19=case t1.d when t1.e then t1.b else t1.a end*f) and  -13=a then case t1.d+13 when t1.f then 17 else t1.f end when (11 not in (d,17,t1.f)) then e else 11 end+b*t1.b) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where t1.f in (select t1.e from t1 union select b from t1)))),(d))<=c),a) between t1.f and d)}
} {1100}
do_test randexpr-2.231 {
  db eval {SELECT  -t1.e*coalesce((select max(17) from t1 where (11*(select case  -abs( -+count(*)) when  -case +(cast(avg( -f) AS integer)) | (abs(cast(avg(c) AS integer))) when min(d) then  -max(t1.f) else count(*) end then cast(avg( -t1.f) AS integer) else max(b) end from t1)*~t1.e*case (select min(e) from t1) when 17-t1.b then (e) else t1.f+t1.f end) in (select t1.d from t1 union select 19 from t1)), -t1.a) FROM t1 WHERE (select min(19) from t1) in (select 17 from t1 union select  -11+t1.d+t1.c from t1)}
} {}
do_test randexpr-2.232 {
  db eval {SELECT  -t1.e*coalesce((select max(17) from t1 where (11*(select case  -abs( -+count(*)) when  -case +(cast(avg( -f) AS integer)) | (abs(cast(avg(c) AS integer))) when min(d) then  -max(t1.f) else count(*) end then cast(avg( -t1.f) AS integer) else max(b) end from t1)*~t1.e*case (select min(e) from t1) when 17-t1.b then (e) else t1.f+t1.f end) in (select t1.d from t1 union select 19 from t1)), -t1.a) FROM t1 WHERE NOT ((select min(19) from t1) in (select 17 from t1 union select  -11+t1.d+t1.c from t1))}
} {50000}
do_test randexpr-2.233 {
  db eval {SELECT  -t1.e*coalesce((select max(17) from t1 where (11*(select case  -abs( -+count(*)) when  -case +(cast(avg( -f) AS integer)) & (abs(cast(avg(c) AS integer))) when min(d) then  -max(t1.f) else count(*) end then cast(avg( -t1.f) AS integer) else max(b) end from t1)*~t1.e*case (select min(e) from t1) when 17-t1.b then (e) else t1.f+t1.f end) in (select t1.d from t1 union select 19 from t1)), -t1.a) FROM t1 WHERE NOT ((select min(19) from t1) in (select 17 from t1 union select  -11+t1.d+t1.c from t1))}
} {50000}
do_test randexpr-2.234 {
  db eval {SELECT (coalesce((select max(case when t1.e>= -e | 13-19*d then case when c not in (+(select count(*) from t1),coalesce((select max(t1.a) from t1 where 13 in (select case count(distinct t1.a) | count(*) when cast(avg(t1.b) AS integer) then count(distinct a) else min(11) end from t1 union select count(*) from t1)),19),t1.a) then t1.c else c end when t1.f in (select t1.f from t1 union select t1.e from t1) then t1.e else  -t1.e end) from t1 where (17 in (e,d,a))),t1.d)* -19) FROM t1 WHERE (((abs(t1.f)/abs(d)) in (select case (case max(coalesce((select max(e*(t1.d*13+t1.b)-t1.b) from t1 where t1.a=13),(t1.c))) when (case max(t1.a) when  -abs(max(17))-count(distinct 19) then cast(avg(t1.d) AS integer) else max(13) end)*count(distinct t1.c) then (max((t1.b))) else min(19) end) when max(f) then  -(count(distinct t1.f)) else min(t1.b) end from t1 union select cast(avg(13) AS integer) from t1) and (13 in (select ((min(b))) from t1 union select  - -count(*) from t1))))}
} {}
do_test randexpr-2.235 {
  db eval {SELECT (coalesce((select max(case when t1.e>= -e | 13-19*d then case when c not in (+(select count(*) from t1),coalesce((select max(t1.a) from t1 where 13 in (select case count(distinct t1.a) | count(*) when cast(avg(t1.b) AS integer) then count(distinct a) else min(11) end from t1 union select count(*) from t1)),19),t1.a) then t1.c else c end when t1.f in (select t1.f from t1 union select t1.e from t1) then t1.e else  -t1.e end) from t1 where (17 in (e,d,a))),t1.d)* -19) FROM t1 WHERE NOT ((((abs(t1.f)/abs(d)) in (select case (case max(coalesce((select max(e*(t1.d*13+t1.b)-t1.b) from t1 where t1.a=13),(t1.c))) when (case max(t1.a) when  -abs(max(17))-count(distinct 19) then cast(avg(t1.d) AS integer) else max(13) end)*count(distinct t1.c) then (max((t1.b))) else min(19) end) when max(f) then  -(count(distinct t1.f)) else min(t1.b) end from t1 union select cast(avg(13) AS integer) from t1) and (13 in (select ((min(b))) from t1 union select  - -count(*) from t1)))))}
} {-7600}
do_test randexpr-2.236 {
  db eval {SELECT (coalesce((select max(case when t1.e>= -e & 13-19*d then case when c not in (+(select count(*) from t1),coalesce((select max(t1.a) from t1 where 13 in (select case count(distinct t1.a) & count(*) when cast(avg(t1.b) AS integer) then count(distinct a) else min(11) end from t1 union select count(*) from t1)),19),t1.a) then t1.c else c end when t1.f in (select t1.f from t1 union select t1.e from t1) then t1.e else  -t1.e end) from t1 where (17 in (e,d,a))),t1.d)* -19) FROM t1 WHERE NOT ((((abs(t1.f)/abs(d)) in (select case (case max(coalesce((select max(e*(t1.d*13+t1.b)-t1.b) from t1 where t1.a=13),(t1.c))) when (case max(t1.a) when  -abs(max(17))-count(distinct 19) then cast(avg(t1.d) AS integer) else max(13) end)*count(distinct t1.c) then (max((t1.b))) else min(19) end) when max(f) then  -(count(distinct t1.f)) else min(t1.b) end from t1 union select cast(avg(13) AS integer) from t1) and (13 in (select ((min(b))) from t1 union select  - -count(*) from t1)))))}
} {-7600}
do_test randexpr-2.237 {
  db eval {SELECT case when case when b in (select abs(abs( -max(case c+d when f then f else 19 end | c)-( -case min(c) when  -(cast(avg((t1.f)) AS integer)) then count(*) else ((cast(avg(t1.b) AS integer))) end))+count(*)+(max(17))) from t1 union select count(*) from t1) then t1.a when ~13*t1.a- -c not in (b,e,19) then t1.c else (t1.d) end<=(b) and 13 between t1.f and 11 then t1.f else  -19 end FROM t1 WHERE d>=case when t1.d+case when ( -17)-c>11 or b in ((select min(13)+ -cast(avg(11) AS integer) from t1)+~t1.f, -c,(13)) and e in (select (d) from t1 union select f from t1) then t1.a when d= -t1.d then a- -17 else 17 end-t1.c>d then 11 when exists(select 1 from t1 where 17 not between t1.b and t1.b) then t1.b else (t1.a) end}
} {-19}
do_test randexpr-2.238 {
  db eval {SELECT case when case when b in (select abs(abs( -max(case c+d when f then f else 19 end | c)-( -case min(c) when  -(cast(avg((t1.f)) AS integer)) then count(*) else ((cast(avg(t1.b) AS integer))) end))+count(*)+(max(17))) from t1 union select count(*) from t1) then t1.a when ~13*t1.a- -c not in (b,e,19) then t1.c else (t1.d) end<=(b) and 13 between t1.f and 11 then t1.f else  -19 end FROM t1 WHERE NOT (d>=case when t1.d+case when ( -17)-c>11 or b in ((select min(13)+ -cast(avg(11) AS integer) from t1)+~t1.f, -c,(13)) and e in (select (d) from t1 union select f from t1) then t1.a when d= -t1.d then a- -17 else 17 end-t1.c>d then 11 when exists(select 1 from t1 where 17 not between t1.b and t1.b) then t1.b else (t1.a) end)}
} {}
do_test randexpr-2.239 {
  db eval {SELECT case when case when b in (select abs(abs( -max(case c+d when f then f else 19 end & c)-( -case min(c) when  -(cast(avg((t1.f)) AS integer)) then count(*) else ((cast(avg(t1.b) AS integer))) end))+count(*)+(max(17))) from t1 union select count(*) from t1) then t1.a when ~13*t1.a- -c not in (b,e,19) then t1.c else (t1.d) end<=(b) and 13 between t1.f and 11 then t1.f else  -19 end FROM t1 WHERE d>=case when t1.d+case when ( -17)-c>11 or b in ((select min(13)+ -cast(avg(11) AS integer) from t1)+~t1.f, -c,(13)) and e in (select (d) from t1 union select f from t1) then t1.a when d= -t1.d then a- -17 else 17 end-t1.c>d then 11 when exists(select 1 from t1 where 17 not between t1.b and t1.b) then t1.b else (t1.a) end}
} {-19}
do_test randexpr-2.240 {
  db eval {SELECT e-coalesce((select coalesce((select max(19) from t1 where (coalesce((select max(case 11 when b then 13 else t1.a end) from t1 where 19 not in (c,t1.f,b)),t1.a)+t1.d in (select 17 from t1 union select 19 from t1) and 11 in (13,t1.c,17) or 19 not in (t1.f,a,17) or t1.e not between 13 and f and a>=d)),(a)-17+t1.f)+t1.a+17 from t1 where not exists(select 1 from t1 where a>t1.f)),t1.b) FROM t1 WHERE t1.a-17 in (select (abs(count(*)))-case case case abs(abs(count(*))) when min(t1.f) then count(*) else cast(avg(+t1.a+(e) | 19*e+t1.f) AS integer) end when abs(+cast(avg(b) AS integer) | count(distinct (13))*+~ -(min(e)) | cast(avg(19) AS integer)) then cast(avg(19) AS integer) else count(distinct t1.c) end | min(t1.d) when count(*) then (count(distinct d)) else (min(11)) end from t1 union select (cast(avg(t1.a) AS integer)) from t1)}
} {}
do_test randexpr-2.241 {
  db eval {SELECT e-coalesce((select coalesce((select max(19) from t1 where (coalesce((select max(case 11 when b then 13 else t1.a end) from t1 where 19 not in (c,t1.f,b)),t1.a)+t1.d in (select 17 from t1 union select 19 from t1) and 11 in (13,t1.c,17) or 19 not in (t1.f,a,17) or t1.e not between 13 and f and a>=d)),(a)-17+t1.f)+t1.a+17 from t1 where not exists(select 1 from t1 where a>t1.f)),t1.b) FROM t1 WHERE NOT (t1.a-17 in (select (abs(count(*)))-case case case abs(abs(count(*))) when min(t1.f) then count(*) else cast(avg(+t1.a+(e) | 19*e+t1.f) AS integer) end when abs(+cast(avg(b) AS integer) | count(distinct (13))*+~ -(min(e)) | cast(avg(19) AS integer)) then cast(avg(19) AS integer) else count(distinct t1.c) end | min(t1.d) when count(*) then (count(distinct d)) else (min(11)) end from t1 union select (cast(avg(t1.a) AS integer)) from t1))}
} {364}
do_test randexpr-2.242 {
  db eval {SELECT  -coalesce((select case when b>19 | f-(select abs(max(t1.b+case when e>17 then 11 else f end)+count(*)) from t1) and case when (19<11*t1.d*t1.b) then 13 else t1.e end not between c and b then d+17 else c end-f from t1 where t1.b>=f),t1.c)+17-a FROM t1 WHERE +c in (+~a+case when ((case t1.d when coalesce((select f from t1 where e in (select count(distinct t1.e) from t1 union select min((abs(t1.c)/abs(e | b)) | d* -t1.d) from t1)),t1.e)+a then c else b end in (select  -cast(avg(t1.c) AS integer)-~cast(avg(11) AS integer) from t1 union select  -count(distinct 19) from t1))) then  -e*19 else 13 end,t1.a,d)}
} {}
do_test randexpr-2.243 {
  db eval {SELECT  -coalesce((select case when b>19 | f-(select abs(max(t1.b+case when e>17 then 11 else f end)+count(*)) from t1) and case when (19<11*t1.d*t1.b) then 13 else t1.e end not between c and b then d+17 else c end-f from t1 where t1.b>=f),t1.c)+17-a FROM t1 WHERE NOT (+c in (+~a+case when ((case t1.d when coalesce((select f from t1 where e in (select count(distinct t1.e) from t1 union select min((abs(t1.c)/abs(e | b)) | d* -t1.d) from t1)),t1.e)+a then c else b end in (select  -cast(avg(t1.c) AS integer)-~cast(avg(11) AS integer) from t1 union select  -count(distinct 19) from t1))) then  -e*19 else 13 end,t1.a,d))}
} {-383}
do_test randexpr-2.244 {
  db eval {SELECT  -coalesce((select case when b>19 & f-(select abs(max(t1.b+case when e>17 then 11 else f end)+count(*)) from t1) and case when (19<11*t1.d*t1.b) then 13 else t1.e end not between c and b then d+17 else c end-f from t1 where t1.b>=f),t1.c)+17-a FROM t1 WHERE NOT (+c in (+~a+case when ((case t1.d when coalesce((select f from t1 where e in (select count(distinct t1.e) from t1 union select min((abs(t1.c)/abs(e | b)) | d* -t1.d) from t1)),t1.e)+a then c else b end in (select  -cast(avg(t1.c) AS integer)-~cast(avg(11) AS integer) from t1 union select  -count(distinct 19) from t1))) then  -e*19 else 13 end,t1.a,d))}
} {-383}
do_test randexpr-2.245 {
  db eval {SELECT case when t1.b>=+(abs(t1.e)/abs(coalesce((select c from t1 where 17<=+(e)),(e)-+~11*17+t1.d-e | +coalesce((select max(t1.d) from t1 where f>e),t1.a)*b | (e))))-t1.a and c>=t1.d or (17 not between e and b) then t1.e else d end FROM t1 WHERE exists(select 1 from t1 where (19-((17))+(b) in (select d*e*a from t1 union select ~19 from t1)) and case b-(abs(case a when coalesce((select max(19) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where b not between e and (t1.f) or a not in (t1.c,17,t1.d)))),case t1.b when  -d then 13 else 13 end)*a+t1.c then e else a end)/abs(t1.d))*t1.e when  -13 then t1.c else 19 end in (select +count(distinct e) from t1 union select count(*) from t1))}
} {}
do_test randexpr-2.246 {
  db eval {SELECT case when t1.b>=+(abs(t1.e)/abs(coalesce((select c from t1 where 17<=+(e)),(e)-+~11*17+t1.d-e | +coalesce((select max(t1.d) from t1 where f>e),t1.a)*b | (e))))-t1.a and c>=t1.d or (17 not between e and b) then t1.e else d end FROM t1 WHERE NOT (exists(select 1 from t1 where (19-((17))+(b) in (select d*e*a from t1 union select ~19 from t1)) and case b-(abs(case a when coalesce((select max(19) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where b not between e and (t1.f) or a not in (t1.c,17,t1.d)))),case t1.b when  -d then 13 else 13 end)*a+t1.c then e else a end)/abs(t1.d))*t1.e when  -13 then t1.c else 19 end in (select +count(distinct e) from t1 union select count(*) from t1)))}
} {500}
do_test randexpr-2.247 {
  db eval {SELECT case when t1.b>=+(abs(t1.e)/abs(coalesce((select c from t1 where 17<=+(e)),(e)-+~11*17+t1.d-e & +coalesce((select max(t1.d) from t1 where f>e),t1.a)*b & (e))))-t1.a and c>=t1.d or (17 not between e and b) then t1.e else d end FROM t1 WHERE NOT (exists(select 1 from t1 where (19-((17))+(b) in (select d*e*a from t1 union select ~19 from t1)) and case b-(abs(case a when coalesce((select max(19) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where b not between e and (t1.f) or a not in (t1.c,17,t1.d)))),case t1.b when  -d then 13 else 13 end)*a+t1.c then e else a end)/abs(t1.d))*t1.e when  -13 then t1.c else 19 end in (select +count(distinct e) from t1 union select count(*) from t1)))}
} {500}
do_test randexpr-2.248 {
  db eval {SELECT case when 11 in (select min(+t1.e)* -max(a)+count(distinct d*11*c)*(count(distinct (e))) | ( -min(t1.b)) | count(distinct 19) | (max(t1.f))-max(t1.b) from t1 union select (min(19)) from t1) then coalesce((select max(17) from t1 where  -17=13 or c in (select t1.d from t1 union select d from t1)),b)*t1.b-a+19 when t1.d<(d) then (d) else 19 end FROM t1 WHERE case when case when t1.c not in (f,19,b) then t1.d-t1.c-case when 17<>t1.a then  -(abs((select cast(avg(b) AS integer)- -max(t1.c) from t1))/abs(t1.c)) else t1.f end-17 | 19 when exists(select 1 from t1 where exists(select 1 from t1 where (e between 13 and (t1.a))) and e<=t1.c) then f else t1.a end>=11 then c when f<a then t1.b else t1.e end=t1.c}
} {19}
do_test randexpr-2.249 {
  db eval {SELECT case when 11 in (select min(+t1.e)* -max(a)+count(distinct d*11*c)*(count(distinct (e))) | ( -min(t1.b)) | count(distinct 19) | (max(t1.f))-max(t1.b) from t1 union select (min(19)) from t1) then coalesce((select max(17) from t1 where  -17=13 or c in (select t1.d from t1 union select d from t1)),b)*t1.b-a+19 when t1.d<(d) then (d) else 19 end FROM t1 WHERE NOT (case when case when t1.c not in (f,19,b) then t1.d-t1.c-case when 17<>t1.a then  -(abs((select cast(avg(b) AS integer)- -max(t1.c) from t1))/abs(t1.c)) else t1.f end-17 | 19 when exists(select 1 from t1 where exists(select 1 from t1 where (e between 13 and (t1.a))) and e<=t1.c) then f else t1.a end>=11 then c when f<a then t1.b else t1.e end=t1.c)}
} {}
do_test randexpr-2.250 {
  db eval {SELECT case when 11 in (select min(+t1.e)* -max(a)+count(distinct d*11*c)*(count(distinct (e))) & ( -min(t1.b)) & count(distinct 19) & (max(t1.f))-max(t1.b) from t1 union select (min(19)) from t1) then coalesce((select max(17) from t1 where  -17=13 or c in (select t1.d from t1 union select d from t1)),b)*t1.b-a+19 when t1.d<(d) then (d) else 19 end FROM t1 WHERE case when case when t1.c not in (f,19,b) then t1.d-t1.c-case when 17<>t1.a then  -(abs((select cast(avg(b) AS integer)- -max(t1.c) from t1))/abs(t1.c)) else t1.f end-17 | 19 when exists(select 1 from t1 where exists(select 1 from t1 where (e between 13 and (t1.a))) and e<=t1.c) then f else t1.a end>=11 then c when f<a then t1.b else t1.e end=t1.c}
} {19}
do_test randexpr-2.251 {
  db eval {SELECT c*~17+~case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(e)/abs(c))=case when t1.c not in (a,13,11) and t1.b>=c then t1.b else t1.f end)) and 17<>f) then case when (e) not in (t1.a,t1.f,e) then case case t1.c when 13 then 19 else t1.d end-19 when t1.d then  -t1.b else t1.f end when t1.d not in (17,t1.a,t1.d) or c in (d,(19),t1.b) then  -t1.b else c end else 19 end+t1.b-f+t1.e FROM t1 WHERE t1.f-case when (coalesce((select 13*(abs(~11)/abs(t1.b)) from t1 where ~a between +f+~+17 and t1.e),e) not between coalesce((select 19-(abs(11)/abs(t1.b)) from t1 where f<>c),t1.b) and t1.f or t1.d between (select case min(a) when cast(avg(e) AS integer) then  -((count(*))) else cast(avg(t1.a) AS integer) end | count(*) from t1) and (t1.a)) then 19 else f end=f}
} {}
do_test randexpr-2.252 {
  db eval {SELECT c*~17+~case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(e)/abs(c))=case when t1.c not in (a,13,11) and t1.b>=c then t1.b else t1.f end)) and 17<>f) then case when (e) not in (t1.a,t1.f,e) then case case t1.c when 13 then 19 else t1.d end-19 when t1.d then  -t1.b else t1.f end when t1.d not in (17,t1.a,t1.d) or c in (d,(19),t1.b) then  -t1.b else c end else 19 end+t1.b-f+t1.e FROM t1 WHERE NOT (t1.f-case when (coalesce((select 13*(abs(~11)/abs(t1.b)) from t1 where ~a between +f+~+17 and t1.e),e) not between coalesce((select 19-(abs(11)/abs(t1.b)) from t1 where f<>c),t1.b) and t1.f or t1.d between (select case min(a) when cast(avg(e) AS integer) then  -((count(*))) else cast(avg(t1.a) AS integer) end | count(*) from t1) and (t1.a)) then 19 else f end=f)}
} {-5601}
do_test randexpr-2.253 {
  db eval {SELECT coalesce((select c-t1.a | 17 | b-~t1.e-11 from t1 where not exists(select 1 from t1 where t1.c<=t1.b)),17) FROM t1 WHERE (((coalesce((select max((abs(b-t1.d-19*t1.a*e+~case when t1.e=t1.f-e then (select abs(abs(cast(avg((f)) AS integer))) from t1) else ((abs(t1.b)/abs(t1.a))) end-t1.b-t1.c)/abs(t1.b))) from t1 where not t1.c in (select count(distinct c) from t1 union select count(*) from t1) and 17< -t1.e),(c)) |  -(c))<>e))}
} {763}
do_test randexpr-2.254 {
  db eval {SELECT coalesce((select c-t1.a | 17 | b-~t1.e-11 from t1 where not exists(select 1 from t1 where t1.c<=t1.b)),17) FROM t1 WHERE NOT ((((coalesce((select max((abs(b-t1.d-19*t1.a*e+~case when t1.e=t1.f-e then (select abs(abs(cast(avg((f)) AS integer))) from t1) else ((abs(t1.b)/abs(t1.a))) end-t1.b-t1.c)/abs(t1.b))) from t1 where not t1.c in (select count(distinct c) from t1 union select count(*) from t1) and 17< -t1.e),(c)) |  -(c))<>e)))}
} {}
do_test randexpr-2.255 {
  db eval {SELECT coalesce((select c-t1.a & 17 & b-~t1.e-11 from t1 where not exists(select 1 from t1 where t1.c<=t1.b)),17) FROM t1 WHERE (((coalesce((select max((abs(b-t1.d-19*t1.a*e+~case when t1.e=t1.f-e then (select abs(abs(cast(avg((f)) AS integer))) from t1) else ((abs(t1.b)/abs(t1.a))) end-t1.b-t1.c)/abs(t1.b))) from t1 where not t1.c in (select count(distinct c) from t1 union select count(*) from t1) and 17< -t1.e),(c)) |  -(c))<>e))}
} {0}
do_test randexpr-2.256 {
  db eval {SELECT case case +(select case count(distinct case when case when (abs(f | t1.d)/abs(13))<= -c then t1.a else t1.b end+t1.b<=19 then c when 19=a then 17 else 11 end+13) when ~+case (cast(avg(t1.b) AS integer) | ((count(*)))-max(t1.d)) when count(distinct d) then count(*) else cast(avg(t1.c) AS integer) end then count(*) else count(*) end from t1) when c*t1.a then 13 else t1.a end when a then  -f else t1.a end+d FROM t1 WHERE case when coalesce((select t1.c | c*t1.e-11 from t1 where exists(select 1 from t1 where t1.d-t1.d*d between  - -t1.e and a)), -13)<=e and 11 not in (d,t1.a,f) and t1.a not between 11 and 19 or t1.e<>t1.e and t1.e<c or a between t1.c and c and d>=t1.a or  -t1.e>=b then b when 17 not between t1.f and t1.b then a else b end in (select 11 from t1 union select f from t1)}
} {}
do_test randexpr-2.257 {
  db eval {SELECT case case +(select case count(distinct case when case when (abs(f | t1.d)/abs(13))<= -c then t1.a else t1.b end+t1.b<=19 then c when 19=a then 17 else 11 end+13) when ~+case (cast(avg(t1.b) AS integer) | ((count(*)))-max(t1.d)) when count(distinct d) then count(*) else cast(avg(t1.c) AS integer) end then count(*) else count(*) end from t1) when c*t1.a then 13 else t1.a end when a then  -f else t1.a end+d FROM t1 WHERE NOT (case when coalesce((select t1.c | c*t1.e-11 from t1 where exists(select 1 from t1 where t1.d-t1.d*d between  - -t1.e and a)), -13)<=e and 11 not in (d,t1.a,f) and t1.a not between 11 and 19 or t1.e<>t1.e and t1.e<c or a between t1.c and c and d>=t1.a or  -t1.e>=b then b when 17 not between t1.f and t1.b then a else b end in (select 11 from t1 union select f from t1))}
} {-200}
do_test randexpr-2.258 {
  db eval {SELECT case case +(select case count(distinct case when case when (abs(f & t1.d)/abs(13))<= -c then t1.a else t1.b end+t1.b<=19 then c when 19=a then 17 else 11 end+13) when ~+case (cast(avg(t1.b) AS integer) & ((count(*)))-max(t1.d)) when count(distinct d) then count(*) else cast(avg(t1.c) AS integer) end then count(*) else count(*) end from t1) when c*t1.a then 13 else t1.a end when a then  -f else t1.a end+d FROM t1 WHERE NOT (case when coalesce((select t1.c | c*t1.e-11 from t1 where exists(select 1 from t1 where t1.d-t1.d*d between  - -t1.e and a)), -13)<=e and 11 not in (d,t1.a,f) and t1.a not between 11 and 19 or t1.e<>t1.e and t1.e<c or a between t1.c and c and d>=t1.a or  -t1.e>=b then b when 17 not between t1.f and t1.b then a else b end in (select 11 from t1 union select f from t1))}
} {-200}
do_test randexpr-2.259 {
  db eval {SELECT f*coalesce((select max((select count(*) from t1)) from t1 where ~case when t1.e<=case when 17>=+case when c*a in (c,t1.b,13) then t1.e when a>t1.b and a<=19 then c else t1.e end then t1.c else 17 end-f*17 or a between b and 19 then t1.c when  -f<=11 then c else  -11 end*t1.c+d>=e),17) FROM t1 WHERE (19 not between t1.b and ~e)}
} {10200}
do_test randexpr-2.260 {
  db eval {SELECT f*coalesce((select max((select count(*) from t1)) from t1 where ~case when t1.e<=case when 17>=+case when c*a in (c,t1.b,13) then t1.e when a>t1.b and a<=19 then c else t1.e end then t1.c else 17 end-f*17 or a between b and 19 then t1.c when  -f<=11 then c else  -11 end*t1.c+d>=e),17) FROM t1 WHERE NOT ((19 not between t1.b and ~e))}
} {}
do_test randexpr-2.261 {
  db eval {SELECT coalesce((select max(t1.c- -case when (~(select max(b*t1.a)*~((min(t1.e))-min((a))) |  -cast(avg(t1.e+t1.a) AS integer) from t1))<d then c else (abs( -~19)/abs(c)) end-coalesce((select max(t1.e+a) from t1 where 11<>c or (t1.b)> -(11)),11)) from t1 where  -11 in ((d),f,t1.d)),t1.a) FROM t1 WHERE c<>e+t1.c}
} {100}
do_test randexpr-2.262 {
  db eval {SELECT coalesce((select max(t1.c- -case when (~(select max(b*t1.a)*~((min(t1.e))-min((a))) |  -cast(avg(t1.e+t1.a) AS integer) from t1))<d then c else (abs( -~19)/abs(c)) end-coalesce((select max(t1.e+a) from t1 where 11<>c or (t1.b)> -(11)),11)) from t1 where  -11 in ((d),f,t1.d)),t1.a) FROM t1 WHERE NOT (c<>e+t1.c)}
} {}
do_test randexpr-2.263 {
  db eval {SELECT coalesce((select max(t1.c- -case when (~(select max(b*t1.a)*~((min(t1.e))-min((a))) &  -cast(avg(t1.e+t1.a) AS integer) from t1))<d then c else (abs( -~19)/abs(c)) end-coalesce((select max(t1.e+a) from t1 where 11<>c or (t1.b)> -(11)),11)) from t1 where  -11 in ((d),f,t1.d)),t1.a) FROM t1 WHERE c<>e+t1.c}
} {100}
do_test randexpr-2.264 {
  db eval {SELECT  -case when (not exists(select 1 from t1 where e*d*case 17 when case t1.c-t1.f when t1.a then t1.a else 11 end then t1.c else t1.b end-e+(t1.a)-e not in (e,e,t1.a) and (t1.f not between 19 and t1.e))) and t1.b<t1.a then f-d-c+b when 17=17 then 19 else d end FROM t1 WHERE f*t1.a not between coalesce((select t1.b from t1 where 17=13),17*e) and e}
} {-19}
do_test randexpr-2.265 {
  db eval {SELECT  -case when (not exists(select 1 from t1 where e*d*case 17 when case t1.c-t1.f when t1.a then t1.a else 11 end then t1.c else t1.b end-e+(t1.a)-e not in (e,e,t1.a) and (t1.f not between 19 and t1.e))) and t1.b<t1.a then f-d-c+b when 17=17 then 19 else d end FROM t1 WHERE NOT (f*t1.a not between coalesce((select t1.b from t1 where 17=13),17*e) and e)}
} {}
do_test randexpr-2.266 {
  db eval {SELECT coalesce((select 17+coalesce((select max(case when  -coalesce((select max((abs( -(abs(t1.a)/abs(t1.d))+11)/abs(e))-b) from t1 where t1.b not between f and t1.c and t1.f<>e),c) between t1.e and f then t1.e when  -f> - -b then c else t1.c end) from t1 where not 11 in (select f from t1 union select a from t1)),t1.d)-t1.a-13 from t1 where t1.d between  -t1.e and t1.a),f) FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where c in (select (abs(f)/abs(13)) from t1 union select t1.a+b from t1)))}
} {}
do_test randexpr-2.267 {
  db eval {SELECT coalesce((select 17+coalesce((select max(case when  -coalesce((select max((abs( -(abs(t1.a)/abs(t1.d))+11)/abs(e))-b) from t1 where t1.b not between f and t1.c and t1.f<>e),c) between t1.e and f then t1.e when  -f> - -b then c else t1.c end) from t1 where not 11 in (select f from t1 union select a from t1)),t1.d)-t1.a-13 from t1 where t1.d between  -t1.e and t1.a),f) FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where c in (select (abs(f)/abs(13)) from t1 union select t1.a+b from t1))))}
} {600}
do_test randexpr-2.268 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where t1.d in (select case (abs(((count(distinct t1.d-c))* -cast(avg(11) AS integer)+max(t1.c)))) when (cast(avg(t1.c+a) AS integer)*+min(a)*max(c)-max(t1.a)+cast(avg(f) AS integer))+cast(avg(t1.e) AS integer) then min(11) else (((min(11)))) end from t1 union select count(*) from t1))),coalesce((select max(b+13) from t1 where exists(select 1 from t1 where f in (select 11 from t1 union select t1.b from t1))),t1.e)) FROM t1 WHERE b>11}
} {500}
do_test randexpr-2.269 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where t1.d in (select case (abs(((count(distinct t1.d-c))* -cast(avg(11) AS integer)+max(t1.c)))) when (cast(avg(t1.c+a) AS integer)*+min(a)*max(c)-max(t1.a)+cast(avg(f) AS integer))+cast(avg(t1.e) AS integer) then min(11) else (((min(11)))) end from t1 union select count(*) from t1))),coalesce((select max(b+13) from t1 where exists(select 1 from t1 where f in (select 11 from t1 union select t1.b from t1))),t1.e)) FROM t1 WHERE NOT (b>11)}
} {}
do_test randexpr-2.270 {
  db eval {SELECT coalesce((select max( -(select count(*)-case min(19)-abs(count(*))+(max( -b)-+count(distinct (t1.e))) when max(a) then (count(distinct 19)) else count(*) end from t1)) from t1 where exists(select 1 from t1 where a<(abs(case when a-t1.c+ -19+t1.d between 11 and f then t1.f else d end+t1.a+d)/abs(c))) or t1.c>t1.c),17)*f FROM t1 WHERE not f<>t1.b}
} {}
do_test randexpr-2.271 {
  db eval {SELECT coalesce((select max( -(select count(*)-case min(19)-abs(count(*))+(max( -b)-+count(distinct (t1.e))) when max(a) then (count(distinct 19)) else count(*) end from t1)) from t1 where exists(select 1 from t1 where a<(abs(case when a-t1.c+ -19+t1.d between 11 and f then t1.f else d end+t1.a+d)/abs(c))) or t1.c>t1.c),17)*f FROM t1 WHERE NOT (not f<>t1.b)}
} {10200}
do_test randexpr-2.272 {
  db eval {SELECT case when coalesce((select f-coalesce((select +coalesce((select t1.c from t1 where (t1.c=(abs(t1.e)/abs(+t1.c+f+(f))))),13+17)+t1.b | t1.c from t1 where case when t1.a not in (d,17,t1.c) then f else f end |  -13 in (select cast(avg(t1.e) AS integer) from t1 union select min(t1.a) from t1)),c) from t1 where 17>c), -t1.b)>t1.c then 17 when t1.b<>11 then e else t1.f end FROM t1 WHERE case when t1.f in (t1.a+(abs(17)/abs((t1.d))),coalesce((select max(c) from t1 where (not (d- -case f when 17 then d else (17) end+e*t1.d) not in ((t1.d),t1.f,f))),coalesce((select c from t1 where 13 not in (19,d,b)),f)),17) then t1.b when e<=f then 17 else c end<d or t1.d> -19}
} {500}
do_test randexpr-2.273 {
  db eval {SELECT case when coalesce((select f-coalesce((select +coalesce((select t1.c from t1 where (t1.c=(abs(t1.e)/abs(+t1.c+f+(f))))),13+17)+t1.b | t1.c from t1 where case when t1.a not in (d,17,t1.c) then f else f end |  -13 in (select cast(avg(t1.e) AS integer) from t1 union select min(t1.a) from t1)),c) from t1 where 17>c), -t1.b)>t1.c then 17 when t1.b<>11 then e else t1.f end FROM t1 WHERE NOT (case when t1.f in (t1.a+(abs(17)/abs((t1.d))),coalesce((select max(c) from t1 where (not (d- -case f when 17 then d else (17) end+e*t1.d) not in ((t1.d),t1.f,f))),coalesce((select c from t1 where 13 not in (19,d,b)),f)),17) then t1.b when e<=f then 17 else c end<d or t1.d> -19)}
} {}
do_test randexpr-2.274 {
  db eval {SELECT case when coalesce((select f-coalesce((select +coalesce((select t1.c from t1 where (t1.c=(abs(t1.e)/abs(+t1.c+f+(f))))),13+17)+t1.b & t1.c from t1 where case when t1.a not in (d,17,t1.c) then f else f end &  -13 in (select cast(avg(t1.e) AS integer) from t1 union select min(t1.a) from t1)),c) from t1 where 17>c), -t1.b)>t1.c then 17 when t1.b<>11 then e else t1.f end FROM t1 WHERE case when t1.f in (t1.a+(abs(17)/abs((t1.d))),coalesce((select max(c) from t1 where (not (d- -case f when 17 then d else (17) end+e*t1.d) not in ((t1.d),t1.f,f))),coalesce((select c from t1 where 13 not in (19,d,b)),f)),17) then t1.b when e<=f then 17 else c end<d or t1.d> -19}
} {500}
do_test randexpr-2.275 {
  db eval {SELECT case when d*t1.c*a<>t1.b*~t1.b*t1.f-b then e else 17 end*t1.e+case when a not between t1.a and t1.d or (select  - -cast(avg(c) AS integer) from t1)<>17+c then case 11 when t1.f then  -t1.b else t1.b end when 13 not in (c,t1.f,19) or not exists(select 1 from t1 where 13=t1.d or t1.e<>a) then (17) else  -t1.f end FROM t1 WHERE (not (case e when e then +case when e>=a and 13<>e*t1.e or t1.d<>11 then t1.c else t1.b end else 17 end) in (select cast(avg( -t1.c) AS integer) from t1 union select case min(13) when  -+count(distinct 13) then case (+(cast(avg(e) AS integer))+((cast(avg(13) AS integer)))* - -count(distinct c)*count(*)) | count(*) when min(t1.c) then (min(11)) else max(f) end else cast(avg(17) AS integer) end from t1))}
} {250200}
do_test randexpr-2.276 {
  db eval {SELECT case when d*t1.c*a<>t1.b*~t1.b*t1.f-b then e else 17 end*t1.e+case when a not between t1.a and t1.d or (select  - -cast(avg(c) AS integer) from t1)<>17+c then case 11 when t1.f then  -t1.b else t1.b end when 13 not in (c,t1.f,19) or not exists(select 1 from t1 where 13=t1.d or t1.e<>a) then (17) else  -t1.f end FROM t1 WHERE NOT ((not (case e when e then +case when e>=a and 13<>e*t1.e or t1.d<>11 then t1.c else t1.b end else 17 end) in (select cast(avg( -t1.c) AS integer) from t1 union select case min(13) when  -+count(distinct 13) then case (+(cast(avg(e) AS integer))+((cast(avg(13) AS integer)))* - -count(distinct c)*count(*)) | count(*) when min(t1.c) then (min(11)) else max(f) end else cast(avg(17) AS integer) end from t1)))}
} {}
do_test randexpr-2.277 {
  db eval {SELECT (select max(t1.a)*abs(count(distinct f-t1.a-(abs(t1.a)/abs(case e when case t1.f when e*(b)-19 then 11 else t1.d end then t1.f else 11 end)))) | case +~cast(avg(t1.a) AS integer)-+abs(count(distinct 17)) when case count(distinct t1.b)*cast(avg(t1.a) AS integer)+count(distinct t1.c) when count(*) then min(t1.f) else count(distinct e) end then max((t1.e)) else max(d) end-count(*) from t1) FROM t1 WHERE e not between (select min(t1.a) from t1) and d+t1.d}
} {}
do_test randexpr-2.278 {
  db eval {SELECT (select max(t1.a)*abs(count(distinct f-t1.a-(abs(t1.a)/abs(case e when case t1.f when e*(b)-19 then 11 else t1.d end then t1.f else 11 end)))) | case +~cast(avg(t1.a) AS integer)-+abs(count(distinct 17)) when case count(distinct t1.b)*cast(avg(t1.a) AS integer)+count(distinct t1.c) when count(*) then min(t1.f) else count(distinct e) end then max((t1.e)) else max(d) end-count(*) from t1) FROM t1 WHERE NOT (e not between (select min(t1.a) from t1) and d+t1.d)}
} {495}
do_test randexpr-2.279 {
  db eval {SELECT (select max(t1.a)*abs(count(distinct f-t1.a-(abs(t1.a)/abs(case e when case t1.f when e*(b)-19 then 11 else t1.d end then t1.f else 11 end)))) & case +~cast(avg(t1.a) AS integer)-+abs(count(distinct 17)) when case count(distinct t1.b)*cast(avg(t1.a) AS integer)+count(distinct t1.c) when count(*) then min(t1.f) else count(distinct e) end then max((t1.e)) else max(d) end-count(*) from t1) FROM t1 WHERE NOT (e not between (select min(t1.a) from t1) and d+t1.d)}
} {4}
do_test randexpr-2.280 {
  db eval {SELECT e*c-t1.e*t1.c++(select abs(case abs(max(coalesce((select f from t1 where (b*coalesce((select max(b) from t1 where 17>f),t1.e) not between c and f or t1.a>d and t1.a<11 or a<> -f)),(t1.a)))) when  -+count(distinct e) then  -+(count(distinct 19))+min(t1.c) else  -min(t1.f) end) from t1)+t1.b-19 FROM t1 WHERE d-coalesce((select max(t1.d*c+c) from t1 where t1.f between (select count(distinct t1.b-e)+abs(~case case ~cast(avg(t1.f) AS integer)-count(distinct t1.a) when count(*) then count(distinct e) else count(*) end when min(e) then min( -t1.c) else max(a) end) from t1)+17 and  -case when d>=d-11 then t1.c else t1.a end),t1.a)*t1.a not in (t1.f,t1.f,d)}
} {781}
do_test randexpr-2.281 {
  db eval {SELECT e*c-t1.e*t1.c++(select abs(case abs(max(coalesce((select f from t1 where (b*coalesce((select max(b) from t1 where 17>f),t1.e) not between c and f or t1.a>d and t1.a<11 or a<> -f)),(t1.a)))) when  -+count(distinct e) then  -+(count(distinct 19))+min(t1.c) else  -min(t1.f) end) from t1)+t1.b-19 FROM t1 WHERE NOT (d-coalesce((select max(t1.d*c+c) from t1 where t1.f between (select count(distinct t1.b-e)+abs(~case case ~cast(avg(t1.f) AS integer)-count(distinct t1.a) when count(*) then count(distinct e) else count(*) end when min(e) then min( -t1.c) else max(a) end) from t1)+17 and  -case when d>=d-11 then t1.c else t1.a end),t1.a)*t1.a not in (t1.f,t1.f,d))}
} {}
do_test randexpr-2.282 {
  db eval {SELECT coalesce((select a from t1 where (exists(select 1 from t1 where 11-case when ((select count(distinct t1.e+d) from t1))<>t1.d*f then  -13 when t1.b in (select abs(cast(avg(c) AS integer)) from t1 union select count(distinct e)*count(distinct c)-cast(avg(e) AS integer) from t1) or c in (select t1.d from t1 union select 17 from t1) then a else t1.b end>=t1.c) and f>=d and d>=t1.f)),case when 11=19 and t1.a between t1.d and e then t1.d-b else t1.b end) FROM t1 WHERE 19 not in ( -t1.f,+19,t1.b)}
} {}
do_test randexpr-2.283 {
  db eval {SELECT coalesce((select a from t1 where (exists(select 1 from t1 where 11-case when ((select count(distinct t1.e+d) from t1))<>t1.d*f then  -13 when t1.b in (select abs(cast(avg(c) AS integer)) from t1 union select count(distinct e)*count(distinct c)-cast(avg(e) AS integer) from t1) or c in (select t1.d from t1 union select 17 from t1) then a else t1.b end>=t1.c) and f>=d and d>=t1.f)),case when 11=19 and t1.a between t1.d and e then t1.d-b else t1.b end) FROM t1 WHERE NOT (19 not in ( -t1.f,+19,t1.b))}
} {200}
do_test randexpr-2.284 {
  db eval {SELECT (~case when t1.f>(abs(t1.c)/abs(13-coalesce((select max(t1.a) from t1 where case when e not in (c,t1.a,~11) then 19+( -c) else a end in (select (19) from t1 union select t1.c from t1)),t1.b)+a)) and e>d and (t1.a)=e then t1.e when (not exists(select 1 from t1 where  -t1.d=e) and  -d in (select d from t1 union select e from t1)) then t1.b else a end) FROM t1 WHERE (t1.f in (select coalesce((select max(coalesce((select c from t1 where coalesce((select max(coalesce((select max(++13*t1.d) from t1 where case when case when e<>13 or b<= -t1.a then t1.c when t1.a not in ( - -13,t1.a,13) then a else c end not in ( -e,d,(11)) or t1.d<t1.a then t1.b when t1.a<> -b then t1.e else t1.d end<a),t1.d)) from t1 where e<>t1.b),c) not in (t1.e,c,b)),13)) from t1 where ((t1.f) in (select max(a) from t1 union select abs(abs(min(13))) from t1))),11) from t1 union select b from t1))}
} {}
do_test randexpr-2.285 {
  db eval {SELECT (~case when t1.f>(abs(t1.c)/abs(13-coalesce((select max(t1.a) from t1 where case when e not in (c,t1.a,~11) then 19+( -c) else a end in (select (19) from t1 union select t1.c from t1)),t1.b)+a)) and e>d and (t1.a)=e then t1.e when (not exists(select 1 from t1 where  -t1.d=e) and  -d in (select d from t1 union select e from t1)) then t1.b else a end) FROM t1 WHERE NOT ((t1.f in (select coalesce((select max(coalesce((select c from t1 where coalesce((select max(coalesce((select max(++13*t1.d) from t1 where case when case when e<>13 or b<= -t1.a then t1.c when t1.a not in ( - -13,t1.a,13) then a else c end not in ( -e,d,(11)) or t1.d<t1.a then t1.b when t1.a<> -b then t1.e else t1.d end<a),t1.d)) from t1 where e<>t1.b),c) not in (t1.e,c,b)),13)) from t1 where ((t1.f) in (select max(a) from t1 union select abs(abs(min(13))) from t1))),11) from t1 union select b from t1)))}
} {-101}
do_test randexpr-2.286 {
  db eval {SELECT (select count(distinct case b when 13 then (select (+(cast(avg(+(d)*case t1.f-c*(abs(case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (d<=t1.e) or d between c and t1.b)) then 11 else 19 end in ((t1.d),t1.a,t1.f) then t1.f when c<=t1.e then t1.c else b end | a)/abs(c))+t1.b when t1.c then a else d end) AS integer))) from t1) else t1.b*(e) end) from t1) FROM t1 WHERE not t1.a+t1.b | t1.f-11*(select max(+case when case ~e-(abs(d*t1.d+t1.d)/abs( -f)) when t1.a then t1.e else t1.c end in (select cast(avg((f)) AS integer) from t1 union select +~(min(t1.d)) from t1) then (t1.d) when not exists(select 1 from t1 where a not in (17,a,d)) then 19 else  -t1.a end* -t1.d) from t1)* -17>13}
} {1}
do_test randexpr-2.287 {
  db eval {SELECT (select count(distinct case b when 13 then (select (+(cast(avg(+(d)*case t1.f-c*(abs(case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (d<=t1.e) or d between c and t1.b)) then 11 else 19 end in ((t1.d),t1.a,t1.f) then t1.f when c<=t1.e then t1.c else b end | a)/abs(c))+t1.b when t1.c then a else d end) AS integer))) from t1) else t1.b*(e) end) from t1) FROM t1 WHERE NOT (not t1.a+t1.b | t1.f-11*(select max(+case when case ~e-(abs(d*t1.d+t1.d)/abs( -f)) when t1.a then t1.e else t1.c end in (select cast(avg((f)) AS integer) from t1 union select +~(min(t1.d)) from t1) then (t1.d) when not exists(select 1 from t1 where a not in (17,a,d)) then 19 else  -t1.a end* -t1.d) from t1)* -17>13)}
} {}
do_test randexpr-2.288 {
  db eval {SELECT (select count(distinct case b when 13 then (select (+(cast(avg(+(d)*case t1.f-c*(abs(case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (d<=t1.e) or d between c and t1.b)) then 11 else 19 end in ((t1.d),t1.a,t1.f) then t1.f when c<=t1.e then t1.c else b end & a)/abs(c))+t1.b when t1.c then a else d end) AS integer))) from t1) else t1.b*(e) end) from t1) FROM t1 WHERE not t1.a+t1.b | t1.f-11*(select max(+case when case ~e-(abs(d*t1.d+t1.d)/abs( -f)) when t1.a then t1.e else t1.c end in (select cast(avg((f)) AS integer) from t1 union select +~(min(t1.d)) from t1) then (t1.d) when not exists(select 1 from t1 where a not in (17,a,d)) then 19 else  -t1.a end* -t1.d) from t1)* -17>13}
} {1}
do_test randexpr-2.289 {
  db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where ((~t1.f) between b and (abs(e)/abs(f)))),13+(select case abs((+count(*)*max(19))) when (~min(b)) then  -min(a) | min( -a) else (max(t1.c)) end from t1)+17*f+11)) from t1 where not 19<=coalesce((select e from t1 where t1.d-d not between 19 and 19),11)),13) FROM t1 WHERE t1.f+t1.d=t1.f+17-case when (abs(t1.a*(case when not exists(select 1 from t1 where not exists(select 1 from t1 where (b) between d and t1.f)) then (t1.b |  -(t1.c)) | 19 when d=t1.a then 13 else d end)+ -t1.d)/abs(d)) not in (d,e,t1.d) then t1.f when 19 in (select t1.f from t1 union select t1.e from t1) then e else  -t1.a end- - -t1.e*17-t1.d-t1.d}
} {}
do_test randexpr-2.290 {
  db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where ((~t1.f) between b and (abs(e)/abs(f)))),13+(select case abs((+count(*)*max(19))) when (~min(b)) then  -min(a) | min( -a) else (max(t1.c)) end from t1)+17*f+11)) from t1 where not 19<=coalesce((select e from t1 where t1.d-d not between 19 and 19),11)),13) FROM t1 WHERE NOT (t1.f+t1.d=t1.f+17-case when (abs(t1.a*(case when not exists(select 1 from t1 where not exists(select 1 from t1 where (b) between d and t1.f)) then (t1.b |  -(t1.c)) | 19 when d=t1.a then 13 else d end)+ -t1.d)/abs(d)) not in (d,e,t1.d) then t1.f when 19 in (select t1.f from t1 union select t1.e from t1) then e else  -t1.a end- - -t1.e*17-t1.d-t1.d)}
} {13}
do_test randexpr-2.291 {
  db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where ((~t1.f) between b and (abs(e)/abs(f)))),13+(select case abs((+count(*)*max(19))) when (~min(b)) then  -min(a) & min( -a) else (max(t1.c)) end from t1)+17*f+11)) from t1 where not 19<=coalesce((select e from t1 where t1.d-d not between 19 and 19),11)),13) FROM t1 WHERE NOT (t1.f+t1.d=t1.f+17-case when (abs(t1.a*(case when not exists(select 1 from t1 where not exists(select 1 from t1 where (b) between d and t1.f)) then (t1.b |  -(t1.c)) | 19 when d=t1.a then 13 else d end)+ -t1.d)/abs(d)) not in (d,e,t1.d) then t1.f when 19 in (select t1.f from t1 union select t1.e from t1) then e else  -t1.a end- - -t1.e*17-t1.d-t1.d)}
} {13}
do_test randexpr-2.292 {
  db eval {SELECT case when  -t1.b=c and ((t1.c>t1.b)) and not exists(select 1 from t1 where (abs((select max(t1.d) from t1))/abs((abs(c+t1.b)/abs(t1.d))-t1.e))+c in (select cast(avg((t1.a)) AS integer) | abs(count(distinct t1.d))+count(*) | count(*)+count(*) from t1 union select (min(t1.d)) from t1)) then (abs(t1.b)/abs(t1.f)) when t1.b not in (a,t1.f,(a)) then t1.b else t1.d end-11 FROM t1 WHERE case when ~e in (coalesce((select 13 from t1 where 17 between t1.a and b or not exists(select 1 from t1 where (c in (11,e,a)))),t1.e),c,e) then e else t1.f end in (select ++abs(case case count(*) when (max(t1.d)) then cast(avg(t1.c) AS integer) else count(distinct b) end | count(*) when max(e) then min(c) else max(13) end | count(*)*count(*)) | max(t1.a) from t1 union select count(distinct t1.c) from t1) or b in (select cast(avg(t1.b) AS integer) from t1 union select cast(avg( -t1.a) AS integer) from t1)}
} {189}
do_test randexpr-2.293 {
  db eval {SELECT case when  -t1.b=c and ((t1.c>t1.b)) and not exists(select 1 from t1 where (abs((select max(t1.d) from t1))/abs((abs(c+t1.b)/abs(t1.d))-t1.e))+c in (select cast(avg((t1.a)) AS integer) | abs(count(distinct t1.d))+count(*) | count(*)+count(*) from t1 union select (min(t1.d)) from t1)) then (abs(t1.b)/abs(t1.f)) when t1.b not in (a,t1.f,(a)) then t1.b else t1.d end-11 FROM t1 WHERE NOT (case when ~e in (coalesce((select 13 from t1 where 17 between t1.a and b or not exists(select 1 from t1 where (c in (11,e,a)))),t1.e),c,e) then e else t1.f end in (select ++abs(case case count(*) when (max(t1.d)) then cast(avg(t1.c) AS integer) else count(distinct b) end | count(*) when max(e) then min(c) else max(13) end | count(*)*count(*)) | max(t1.a) from t1 union select count(distinct t1.c) from t1) or b in (select cast(avg(t1.b) AS integer) from t1 union select cast(avg( -t1.a) AS integer) from t1))}
} {}
do_test randexpr-2.294 {
  db eval {SELECT case when  -t1.b=c and ((t1.c>t1.b)) and not exists(select 1 from t1 where (abs((select max(t1.d) from t1))/abs((abs(c+t1.b)/abs(t1.d))-t1.e))+c in (select cast(avg((t1.a)) AS integer) & abs(count(distinct t1.d))+count(*) & count(*)+count(*) from t1 union select (min(t1.d)) from t1)) then (abs(t1.b)/abs(t1.f)) when t1.b not in (a,t1.f,(a)) then t1.b else t1.d end-11 FROM t1 WHERE case when ~e in (coalesce((select 13 from t1 where 17 between t1.a and b or not exists(select 1 from t1 where (c in (11,e,a)))),t1.e),c,e) then e else t1.f end in (select ++abs(case case count(*) when (max(t1.d)) then cast(avg(t1.c) AS integer) else count(distinct b) end | count(*) when max(e) then min(c) else max(13) end | count(*)*count(*)) | max(t1.a) from t1 union select count(distinct t1.c) from t1) or b in (select cast(avg(t1.b) AS integer) from t1 union select cast(avg( -t1.a) AS integer) from t1)}
} {189}
do_test randexpr-2.295 {
  db eval {SELECT case when (((abs(11 | e)/abs(17-d))+t1.b | a<>11)) and t1.d in (13,t1.c,11) or 17 between t1.f and b or not f in (select 19 from t1 union select t1.e from t1) and b<>19 or e between 19 and t1.d or b<=d or d<17 or t1.a<>t1.f then 17 when t1.e=t1.b then 11 else coalesce((select t1.e from t1 where (b) between  - -d and e),t1.b) end FROM t1 WHERE t1.a between d and +17-17*coalesce((select ~ -19-13-19 from t1 where 19>(select abs(count(distinct t1.d-17))+count(distinct case when 19>17 then t1.f else t1.e end+b) | max(t1.b)+count(distinct 13) from t1)-coalesce((select 13 from t1 where t1.e not in (19,17,e) and 11<=t1.d),c)),t1.f)}
} {}
do_test randexpr-2.296 {
  db eval {SELECT case when (((abs(11 | e)/abs(17-d))+t1.b | a<>11)) and t1.d in (13,t1.c,11) or 17 between t1.f and b or not f in (select 19 from t1 union select t1.e from t1) and b<>19 or e between 19 and t1.d or b<=d or d<17 or t1.a<>t1.f then 17 when t1.e=t1.b then 11 else coalesce((select t1.e from t1 where (b) between  - -d and e),t1.b) end FROM t1 WHERE NOT (t1.a between d and +17-17*coalesce((select ~ -19-13-19 from t1 where 19>(select abs(count(distinct t1.d-17))+count(distinct case when 19>17 then t1.f else t1.e end+b) | max(t1.b)+count(distinct 13) from t1)-coalesce((select 13 from t1 where t1.e not in (19,17,e) and 11<=t1.d),c)),t1.f))}
} {17}
do_test randexpr-2.297 {
  db eval {SELECT case when (((abs(11 & e)/abs(17-d))+t1.b & a<>11)) and t1.d in (13,t1.c,11) or 17 between t1.f and b or not f in (select 19 from t1 union select t1.e from t1) and b<>19 or e between 19 and t1.d or b<=d or d<17 or t1.a<>t1.f then 17 when t1.e=t1.b then 11 else coalesce((select t1.e from t1 where (b) between  - -d and e),t1.b) end FROM t1 WHERE NOT (t1.a between d and +17-17*coalesce((select ~ -19-13-19 from t1 where 19>(select abs(count(distinct t1.d-17))+count(distinct case when 19>17 then t1.f else t1.e end+b) | max(t1.b)+count(distinct 13) from t1)-coalesce((select 13 from t1 where t1.e not in (19,17,e) and 11<=t1.d),c)),t1.f))}
} {17}
do_test randexpr-2.298 {
  db eval {SELECT case when 19=13 or 13+a | 19*11+b<>b and ((19<=b+(select count(*) from t1))) then t1.d when t1.e<= -19 then d-t1.e+(select ~max(19)*+(count(distinct b)) from t1)+t1.d*t1.d+f else t1.c end FROM t1 WHERE (13*case when 19*case when 19 not between 17 and t1.e then t1.e when ((case when case case when e<>11 or t1.b not in (t1.a, -c,17) then b else a end when  -e then b else a end*a in (select 19 from t1 union select 13 from t1) then e else t1.c end in (select  -abs(+count(*)) from t1 union select count(distinct f) from t1))) then 19 else d end>=f then t1.a when t1.e>=b then a else c end>=t1.d)}
} {400}
do_test randexpr-2.299 {
  db eval {SELECT case when 19=13 or 13+a | 19*11+b<>b and ((19<=b+(select count(*) from t1))) then t1.d when t1.e<= -19 then d-t1.e+(select ~max(19)*+(count(distinct b)) from t1)+t1.d*t1.d+f else t1.c end FROM t1 WHERE NOT ((13*case when 19*case when 19 not between 17 and t1.e then t1.e when ((case when case case when e<>11 or t1.b not in (t1.a, -c,17) then b else a end when  -e then b else a end*a in (select 19 from t1 union select 13 from t1) then e else t1.c end in (select  -abs(+count(*)) from t1 union select count(distinct f) from t1))) then 19 else d end>=f then t1.a when t1.e>=b then a else c end>=t1.d))}
} {}
do_test randexpr-2.300 {
  db eval {SELECT case when 19=13 or 13+a & 19*11+b<>b and ((19<=b+(select count(*) from t1))) then t1.d when t1.e<= -19 then d-t1.e+(select ~max(19)*+(count(distinct b)) from t1)+t1.d*t1.d+f else t1.c end FROM t1 WHERE (13*case when 19*case when 19 not between 17 and t1.e then t1.e when ((case when case case when e<>11 or t1.b not in (t1.a, -c,17) then b else a end when  -e then b else a end*a in (select 19 from t1 union select 13 from t1) then e else t1.c end in (select  -abs(+count(*)) from t1 union select count(distinct f) from t1))) then 19 else d end>=f then t1.a when t1.e>=b then a else c end>=t1.d)}
} {400}
do_test randexpr-2.301 {
  db eval {SELECT +coalesce((select t1.d from t1 where coalesce((select t1.c+t1.b-case (19) when t1.c then 13+13+17 else t1.e end from t1 where (not exists(select 1 from t1 where t1.f<13)) and d not in (t1.e,11,19) and not 19>=t1.f or e in (select min(t1.c) from t1 union select cast(avg(t1.c) AS integer) from t1)), -a)-b*(13)<t1.b),(t1.c)) | t1.e FROM t1 WHERE not (11>(+b))}
} {500}
do_test randexpr-2.302 {
  db eval {SELECT +coalesce((select t1.d from t1 where coalesce((select t1.c+t1.b-case (19) when t1.c then 13+13+17 else t1.e end from t1 where (not exists(select 1 from t1 where t1.f<13)) and d not in (t1.e,11,19) and not 19>=t1.f or e in (select min(t1.c) from t1 union select cast(avg(t1.c) AS integer) from t1)), -a)-b*(13)<t1.b),(t1.c)) | t1.e FROM t1 WHERE NOT (not (11>(+b)))}
} {}
do_test randexpr-2.303 {
  db eval {SELECT +coalesce((select t1.d from t1 where coalesce((select t1.c+t1.b-case (19) when t1.c then 13+13+17 else t1.e end from t1 where (not exists(select 1 from t1 where t1.f<13)) and d not in (t1.e,11,19) and not 19>=t1.f or e in (select min(t1.c) from t1 union select cast(avg(t1.c) AS integer) from t1)), -a)-b*(13)<t1.b),(t1.c)) & t1.e FROM t1 WHERE not (11>(+b))}
} {400}
do_test randexpr-2.304 {
  db eval {SELECT case when (((t1.c)<=a-11*t1.e)) then t1.b else a end | ((abs(b*(abs(t1.e | +c)/abs(11)))/abs(t1.a))) FROM t1 WHERE case when t1.e in (select t1.a-e from t1 union select t1.e from t1) then 19*coalesce((select a*t1.c-19+f+t1.d-case case when 11>=d then f when not f<>17 then t1.d else t1.f end+t1.e-t1.c when d then b else t1.f end from t1 where t1.f>a), -t1.a)- -(t1.c)-t1.e+b else 11 end<t1.f}
} {}
do_test randexpr-2.305 {
  db eval {SELECT case when (((t1.c)<=a-11*t1.e)) then t1.b else a end | ((abs(b*(abs(t1.e | +c)/abs(11)))/abs(t1.a))) FROM t1 WHERE NOT (case when t1.e in (select t1.a-e from t1 union select t1.e from t1) then 19*coalesce((select a*t1.c-19+f+t1.d-case case when 11>=d then f when not f<>17 then t1.d else t1.f end+t1.e-t1.c when d then b else t1.f end from t1 where t1.f>a), -t1.a)- -(t1.c)-t1.e+b else 11 end<t1.f)}
} {124}
do_test randexpr-2.306 {
  db eval {SELECT case when (((t1.c)<=a-11*t1.e)) then t1.b else a end & ((abs(b*(abs(t1.e & +c)/abs(11)))/abs(t1.a))) FROM t1 WHERE NOT (case when t1.e in (select t1.a-e from t1 union select t1.e from t1) then 19*coalesce((select a*t1.c-19+f+t1.d-case case when 11>=d then f when not f<>17 then t1.d else t1.f end+t1.e-t1.c when d then b else t1.f end from t1 where t1.f>a), -t1.a)- -(t1.c)-t1.e+b else 11 end<t1.f)}
} {36}
do_test randexpr-2.307 {
  db eval {SELECT 17*case when case t1.e when 13-c+f then d else (select + -case cast(avg(b) AS integer)*count(*) when (count(distinct 17)+case abs((count(distinct t1.e))) when count(*) then count(*) else count(distinct c) end) | count(*) then  -count(distinct b) else  - -min(e) end*min(f)-min(t1.e) from t1) end-(select (count(*)) from t1) in (select 19 from t1 union select t1.a-(select count(distinct t1.c) from t1) from t1) then a-13 else t1.d end FROM t1 WHERE not exists(select 1 from t1 where (case  -17 when c then (abs(t1.d)/abs(c-(abs(case when t1.e in (17,t1.a,(abs(e)/abs(t1.d))) then +d-17*t1.b when (select +cast(avg(t1.a*t1.e+e-19) AS integer) from t1) in (select (abs(b)/abs(f)) from t1 union select (19) from t1) then b else t1.f end)/abs(e))*e))+(c) else  -t1.c end<=(11)))}
} {}
do_test randexpr-2.308 {
  db eval {SELECT 17*case when case t1.e when 13-c+f then d else (select + -case cast(avg(b) AS integer)*count(*) when (count(distinct 17)+case abs((count(distinct t1.e))) when count(*) then count(*) else count(distinct c) end) | count(*) then  -count(distinct b) else  - -min(e) end*min(f)-min(t1.e) from t1) end-(select (count(*)) from t1) in (select 19 from t1 union select t1.a-(select count(distinct t1.c) from t1) from t1) then a-13 else t1.d end FROM t1 WHERE NOT (not exists(select 1 from t1 where (case  -17 when c then (abs(t1.d)/abs(c-(abs(case when t1.e in (17,t1.a,(abs(e)/abs(t1.d))) then +d-17*t1.b when (select +cast(avg(t1.a*t1.e+e-19) AS integer) from t1) in (select (abs(b)/abs(f)) from t1 union select (19) from t1) then b else t1.f end)/abs(e))*e))+(c) else  -t1.c end<=(11))))}
} {6800}
do_test randexpr-2.309 {
  db eval {SELECT 17*case when case t1.e when 13-c+f then d else (select + -case cast(avg(b) AS integer)*count(*) when (count(distinct 17)+case abs((count(distinct t1.e))) when count(*) then count(*) else count(distinct c) end) & count(*) then  -count(distinct b) else  - -min(e) end*min(f)-min(t1.e) from t1) end-(select (count(*)) from t1) in (select 19 from t1 union select t1.a-(select count(distinct t1.c) from t1) from t1) then a-13 else t1.d end FROM t1 WHERE NOT (not exists(select 1 from t1 where (case  -17 when c then (abs(t1.d)/abs(c-(abs(case when t1.e in (17,t1.a,(abs(e)/abs(t1.d))) then +d-17*t1.b when (select +cast(avg(t1.a*t1.e+e-19) AS integer) from t1) in (select (abs(b)/abs(f)) from t1 union select (19) from t1) then b else t1.f end)/abs(e))*e))+(c) else  -t1.c end<=(11))))}
} {6800}
do_test randexpr-2.310 {
  db eval {SELECT t1.f+coalesce((select t1.b-13-(coalesce((select 17 from t1 where b>a),13)*11)-t1.c from t1 where 11 between t1.a and  -13+t1.f*~coalesce((select max(b-f) from t1 where t1.a<=13 or a not in (13,f,17)),b) or (t1.d<19 or b> -t1.c)),b) FROM t1 WHERE 11 not between d and coalesce((select  -(select (cast(avg(d) AS integer)) from t1) from t1 where case when 17<t1.a then t1.b else coalesce((select max(f) from t1 where t1.d-+case when (d<=t1.f) and t1.e not in (17,t1.d,t1.a) and 11 in (13,t1.e, -t1.a) and t1.c<13 then  -b else case when a>13 then e when 19 between t1.a and t1.b then b else b end end*13<=c),t1.c) end in (select t1.e from t1 union select d from t1)),t1.b)}
} {300}
do_test randexpr-2.311 {
  db eval {SELECT t1.f+coalesce((select t1.b-13-(coalesce((select 17 from t1 where b>a),13)*11)-t1.c from t1 where 11 between t1.a and  -13+t1.f*~coalesce((select max(b-f) from t1 where t1.a<=13 or a not in (13,f,17)),b) or (t1.d<19 or b> -t1.c)),b) FROM t1 WHERE NOT (11 not between d and coalesce((select  -(select (cast(avg(d) AS integer)) from t1) from t1 where case when 17<t1.a then t1.b else coalesce((select max(f) from t1 where t1.d-+case when (d<=t1.f) and t1.e not in (17,t1.d,t1.a) and 11 in (13,t1.e, -t1.a) and t1.c<13 then  -b else case when a>13 then e when 19 between t1.a and t1.b then b else b end end*13<=c),t1.c) end in (select t1.e from t1 union select d from t1)),t1.b))}
} {}
do_test randexpr-2.312 {
  db eval {SELECT (abs(13)/abs((select min(case when case when exists(select 1 from t1 where not exists(select 1 from t1 where (select count(distinct (t1.e)) from t1)+t1.f>t1.e) and t1.a>=13 or f in (select t1.e from t1 union select t1.e from t1)) then b when f not in (13,13,13) then coalesce((select max(d*f) from t1 where t1.e in (t1.d,t1.e,(e))),t1.e) else a end>=t1.f then b when t1.c in (e,f,t1.e) then b else t1.c end)*abs(count(*))-abs(~count(*)-min(e))-cast(avg(17) AS integer) from t1))) FROM t1 WHERE t1.b not in (a*17-17-case when  -17-t1.f in (select coalesce((select t1.a from t1 where (d)=t1.a),d) from t1 union select 19 from t1) or 13 not between 17 and 13 and (19 between (t1.e) and t1.f) or ( -t1.e)>=17 then b when t1.d not in (19,f,t1.f) then a else case when t1.a=t1.d then e when 17 in (t1.e,t1.b,t1.d) then t1.a else a end end,e,11)}
} {0}
do_test randexpr-2.313 {
  db eval {SELECT (abs(13)/abs((select min(case when case when exists(select 1 from t1 where not exists(select 1 from t1 where (select count(distinct (t1.e)) from t1)+t1.f>t1.e) and t1.a>=13 or f in (select t1.e from t1 union select t1.e from t1)) then b when f not in (13,13,13) then coalesce((select max(d*f) from t1 where t1.e in (t1.d,t1.e,(e))),t1.e) else a end>=t1.f then b when t1.c in (e,f,t1.e) then b else t1.c end)*abs(count(*))-abs(~count(*)-min(e))-cast(avg(17) AS integer) from t1))) FROM t1 WHERE NOT (t1.b not in (a*17-17-case when  -17-t1.f in (select coalesce((select t1.a from t1 where (d)=t1.a),d) from t1 union select 19 from t1) or 13 not between 17 and 13 and (19 between (t1.e) and t1.f) or ( -t1.e)>=17 then b when t1.d not in (19,f,t1.f) then a else case when t1.a=t1.d then e when 17 in (t1.e,t1.b,t1.d) then t1.a else a end end,e,11))}
} {}
do_test randexpr-2.314 {
  db eval {SELECT (abs(case coalesce((select t1.d* -case when d in (select cast(avg(13) AS integer)*abs(((cast(avg(d) AS integer)))+ -count(distinct c))-max(t1.c) from t1 union select min(e) from t1) then (abs(19)/abs(case when b not in (19,d,13) or t1.b not in (b,17,17) then e else b end)) else 19 end from t1 where a>=t1.c and 17 not in (t1.c,17,t1.f)),13)*t1.f when e then (11) else 17 end+19 | b)/abs(f))-t1.e FROM t1 WHERE not exists(select 1 from t1 where case a when coalesce((select max(case 19 when 17 then b-d else t1.e end) from t1 where ( -coalesce((select max(t1.a) from t1 where e between t1.b and (abs(e)/abs(17))),(abs(case when case when 13 between e and (t1.b) and 11 not in (t1.f,t1.e,c) then (t1.d) else  -c end< -e then 11 when 13>t1.b then 11 else t1.a end*13)/abs((f)))-t1.a) not in (e,(b),t1.c))),19) then t1.b else 13 end not between t1.b and 11)}
} {}
do_test randexpr-2.315 {
  db eval {SELECT (abs(case coalesce((select t1.d* -case when d in (select cast(avg(13) AS integer)*abs(((cast(avg(d) AS integer)))+ -count(distinct c))-max(t1.c) from t1 union select min(e) from t1) then (abs(19)/abs(case when b not in (19,d,13) or t1.b not in (b,17,17) then e else b end)) else 19 end from t1 where a>=t1.c and 17 not in (t1.c,17,t1.f)),13)*t1.f when e then (11) else 17 end+19 | b)/abs(f))-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where case a when coalesce((select max(case 19 when 17 then b-d else t1.e end) from t1 where ( -coalesce((select max(t1.a) from t1 where e between t1.b and (abs(e)/abs(17))),(abs(case when case when 13 between e and (t1.b) and 11 not in (t1.f,t1.e,c) then (t1.d) else  -c end< -e then 11 when 13>t1.b then 11 else t1.a end*13)/abs((f)))-t1.a) not in (e,(b),t1.c))),19) then t1.b else 13 end not between t1.b and 11))}
} {-500}
do_test randexpr-2.316 {
  db eval {SELECT (abs(case coalesce((select t1.d* -case when d in (select cast(avg(13) AS integer)*abs(((cast(avg(d) AS integer)))+ -count(distinct c))-max(t1.c) from t1 union select min(e) from t1) then (abs(19)/abs(case when b not in (19,d,13) or t1.b not in (b,17,17) then e else b end)) else 19 end from t1 where a>=t1.c and 17 not in (t1.c,17,t1.f)),13)*t1.f when e then (11) else 17 end+19 & b)/abs(f))-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where case a when coalesce((select max(case 19 when 17 then b-d else t1.e end) from t1 where ( -coalesce((select max(t1.a) from t1 where e between t1.b and (abs(e)/abs(17))),(abs(case when case when 13 between e and (t1.b) and 11 not in (t1.f,t1.e,c) then (t1.d) else  -c end< -e then 11 when 13>t1.b then 11 else t1.a end*13)/abs((f)))-t1.a) not in (e,(b),t1.c))),19) then t1.b else 13 end not between t1.b and 11))}
} {-500}
do_test randexpr-2.317 {
  db eval {SELECT  -(+case when ~t1.d-f-case coalesce((select max((select (min((abs(t1.f)/abs(t1.b))-17)) from t1)) from t1 where e<=17),f) when t1.f then (select case  -( -count(distinct b)) when cast(avg( -13) AS integer) then cast(avg(13) AS integer) else max(19) end from t1)-t1.e else 13 end*b between t1.c and t1.d then t1.d when e<t1.f then  -t1.b else 19 end | d*e) FROM t1 WHERE ~t1.d*~( -coalesce((select max(t1.d | t1.a) from t1 where d-(select  -( - -count(distinct 13)) | min((t1.f))+min(t1.c) from t1) not between case t1.a when t1.b then e else  -c end and c or t1.a not in (a,19,c)),d)) in (select +(max(t1.b))*max((13))++(count(distinct t1.a))+count(*)-count(distinct f) | cast(avg(t1.d) AS integer) from t1 union select cast(avg(13) AS integer) from t1)}
} {}
do_test randexpr-2.318 {
  db eval {SELECT  -(+case when ~t1.d-f-case coalesce((select max((select (min((abs(t1.f)/abs(t1.b))-17)) from t1)) from t1 where e<=17),f) when t1.f then (select case  -( -count(distinct b)) when cast(avg( -13) AS integer) then cast(avg(13) AS integer) else max(19) end from t1)-t1.e else 13 end*b between t1.c and t1.d then t1.d when e<t1.f then  -t1.b else 19 end | d*e) FROM t1 WHERE NOT (~t1.d*~( -coalesce((select max(t1.d | t1.a) from t1 where d-(select  -( - -count(distinct 13)) | min((t1.f))+min(t1.c) from t1) not between case t1.a when t1.b then e else  -c end and c or t1.a not in (a,19,c)),d)) in (select +(max(t1.b))*max((13))++(count(distinct t1.a))+count(*)-count(distinct f) | cast(avg(t1.d) AS integer) from t1 union select cast(avg(13) AS integer) from t1))}
} {136}
do_test randexpr-2.319 {
  db eval {SELECT  -(+case when ~t1.d-f-case coalesce((select max((select (min((abs(t1.f)/abs(t1.b))-17)) from t1)) from t1 where e<=17),f) when t1.f then (select case  -( -count(distinct b)) when cast(avg( -13) AS integer) then cast(avg(13) AS integer) else max(19) end from t1)-t1.e else 13 end*b between t1.c and t1.d then t1.d when e<t1.f then  -t1.b else 19 end & d*e) FROM t1 WHERE NOT (~t1.d*~( -coalesce((select max(t1.d | t1.a) from t1 where d-(select  -( - -count(distinct 13)) | min((t1.f))+min(t1.c) from t1) not between case t1.a when t1.b then e else  -c end and c or t1.a not in (a,19,c)),d)) in (select +(max(t1.b))*max((13))++(count(distinct t1.a))+count(*)-count(distinct f) | cast(avg(t1.d) AS integer) from t1 union select cast(avg(13) AS integer) from t1))}
} {-199936}
do_test randexpr-2.320 {
  db eval {SELECT ~d-coalesce((select +e from t1 where b not between b and ~d++ -t1.b),f)-f-+19-t1.a+case when d<=(abs(19)/abs(+coalesce((select 11 from t1 where not exists(select 1 from t1 where not coalesce((select t1.d from t1 where not t1.a<=t1.c),11) in (select 19 from t1 union select t1.a from t1) or t1.c<=t1.c and a<t1.b)),17-t1.e))) then f else t1.a end*c FROM t1 WHERE (select count(*) from t1)*e-17 | f not between 11 and t1.d or t1.c* -b in (select (abs(case when not 19<( -(t1.e-c*t1.b)+(d)-c) then t1.f-t1.b when t1.f<=11 or exists(select 1 from t1 where t1.e in (13,t1.f,t1.d)) then t1.f else 19 end)/abs(e)) from t1 union select 17 from t1)}
} {28380}
do_test randexpr-2.321 {
  db eval {SELECT ~d-coalesce((select +e from t1 where b not between b and ~d++ -t1.b),f)-f-+19-t1.a+case when d<=(abs(19)/abs(+coalesce((select 11 from t1 where not exists(select 1 from t1 where not coalesce((select t1.d from t1 where not t1.a<=t1.c),11) in (select 19 from t1 union select t1.a from t1) or t1.c<=t1.c and a<t1.b)),17-t1.e))) then f else t1.a end*c FROM t1 WHERE NOT ((select count(*) from t1)*e-17 | f not between 11 and t1.d or t1.c* -b in (select (abs(case when not 19<( -(t1.e-c*t1.b)+(d)-c) then t1.f-t1.b when t1.f<=11 or exists(select 1 from t1 where t1.e in (13,t1.f,t1.d)) then t1.f else 19 end)/abs(e)) from t1 union select 17 from t1))}
} {}
do_test randexpr-2.322 {
  db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where 11 in (select count(distinct d-coalesce((select t1.c-t1.f from t1 where 13 in (19,e,t1.b) and e in (select ( -count(*)) from t1 union select max(e) from t1) or t1.a>t1.f),d)*t1.e)+max(t1.f)+cast(avg(e) AS integer) | (abs((count(distinct 17)))) from t1 union select max(t1.b) from t1) or 17 in (select  -t1.b from t1 union select t1.a from t1) and exists(select 1 from t1 where t1.e=t1.c))),f+(t1.e)) FROM t1 WHERE exists(select 1 from t1 where +t1.d between (abs((abs(t1.c)/abs(case when not exists(select 1 from t1 where d*~(select abs(min(13))-( -(max(t1.f))*( -(count(distinct a)))-max(17)*min(t1.a) | (cast(avg(t1.b) AS integer))) from t1)>case when a in (select max(c) from t1 union select count(distinct  -t1.a) from t1) or +17 in (select  -count(distinct t1.f) from t1 union select cast(avg(t1.f) AS integer) from t1) then c else t1.a end) then  -t1.f else t1.f end)))/abs(c+a)) and d)}
} {17}
do_test randexpr-2.323 {
  db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where 11 in (select count(distinct d-coalesce((select t1.c-t1.f from t1 where 13 in (19,e,t1.b) and e in (select ( -count(*)) from t1 union select max(e) from t1) or t1.a>t1.f),d)*t1.e)+max(t1.f)+cast(avg(e) AS integer) | (abs((count(distinct 17)))) from t1 union select max(t1.b) from t1) or 17 in (select  -t1.b from t1 union select t1.a from t1) and exists(select 1 from t1 where t1.e=t1.c))),f+(t1.e)) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.d between (abs((abs(t1.c)/abs(case when not exists(select 1 from t1 where d*~(select abs(min(13))-( -(max(t1.f))*( -(count(distinct a)))-max(17)*min(t1.a) | (cast(avg(t1.b) AS integer))) from t1)>case when a in (select max(c) from t1 union select count(distinct  -t1.a) from t1) or +17 in (select  -count(distinct t1.f) from t1 union select cast(avg(t1.f) AS integer) from t1) then c else t1.a end) then  -t1.f else t1.f end)))/abs(c+a)) and d))}
} {}
do_test randexpr-2.324 {
  db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where 11 in (select count(distinct d-coalesce((select t1.c-t1.f from t1 where 13 in (19,e,t1.b) and e in (select ( -count(*)) from t1 union select max(e) from t1) or t1.a>t1.f),d)*t1.e)+max(t1.f)+cast(avg(e) AS integer) & (abs((count(distinct 17)))) from t1 union select max(t1.b) from t1) or 17 in (select  -t1.b from t1 union select t1.a from t1) and exists(select 1 from t1 where t1.e=t1.c))),f+(t1.e)) FROM t1 WHERE exists(select 1 from t1 where +t1.d between (abs((abs(t1.c)/abs(case when not exists(select 1 from t1 where d*~(select abs(min(13))-( -(max(t1.f))*( -(count(distinct a)))-max(17)*min(t1.a) | (cast(avg(t1.b) AS integer))) from t1)>case when a in (select max(c) from t1 union select count(distinct  -t1.a) from t1) or +17 in (select  -count(distinct t1.f) from t1 union select cast(avg(t1.f) AS integer) from t1) then c else t1.a end) then  -t1.f else t1.f end)))/abs(c+a)) and d)}
} {17}
do_test randexpr-2.325 {
  db eval {SELECT t1.d*17- -case when case (b) when t1.c then (abs(t1.f)/abs((select + -~abs(min(f) | +cast(avg(++t1.e+t1.d) AS integer) | ((count(distinct t1.a)-count(*)))) from t1))) else c*case t1.b when t1.d then (t1.c) else t1.c end*(b)-c end=t1.d then t1.c when  -17=c then t1.e else t1.c end FROM t1 WHERE t1.b in (f,b,a)}
} {7100}
do_test randexpr-2.326 {
  db eval {SELECT t1.d*17- -case when case (b) when t1.c then (abs(t1.f)/abs((select + -~abs(min(f) | +cast(avg(++t1.e+t1.d) AS integer) | ((count(distinct t1.a)-count(*)))) from t1))) else c*case t1.b when t1.d then (t1.c) else t1.c end*(b)-c end=t1.d then t1.c when  -17=c then t1.e else t1.c end FROM t1 WHERE NOT (t1.b in (f,b,a))}
} {}
do_test randexpr-2.327 {
  db eval {SELECT t1.d*17- -case when case (b) when t1.c then (abs(t1.f)/abs((select + -~abs(min(f) & +cast(avg(++t1.e+t1.d) AS integer) & ((count(distinct t1.a)-count(*)))) from t1))) else c*case t1.b when t1.d then (t1.c) else t1.c end*(b)-c end=t1.d then t1.c when  -17=c then t1.e else t1.c end FROM t1 WHERE t1.b in (f,b,a)}
} {7100}
do_test randexpr-2.328 {
  db eval {SELECT coalesce((select e-t1.d-+b*coalesce((select 11 from t1 where (t1.a<=coalesce((select  - -coalesce((select max(case case 19 when t1.d then t1.e else t1.a end when b then 13 else t1.e end) from t1 where (c)>=(b)),t1.c)+t1.b from t1 where t1.e>e and exists(select 1 from t1 where b in (t1.b,e,t1.c) or e not between a and d) and 13<b),a))),t1.e) from t1 where t1.a<t1.a),t1.e) FROM t1 WHERE exists(select 1 from t1 where coalesce((select max(coalesce((select case case coalesce((select d from t1 where b in (17,t1.a,13)),11) when (coalesce((select 11 from t1 where a++t1.d>(coalesce((select (f)+t1.c from t1 where a>t1.c),b))),t1.e)) then 19 else e end when t1.d then t1.e else b end from t1 where t1.b>=f),13)-b*17) from t1 where 11<>e),t1.b)<(c))}
} {500}
do_test randexpr-2.329 {
  db eval {SELECT coalesce((select e-t1.d-+b*coalesce((select 11 from t1 where (t1.a<=coalesce((select  - -coalesce((select max(case case 19 when t1.d then t1.e else t1.a end when b then 13 else t1.e end) from t1 where (c)>=(b)),t1.c)+t1.b from t1 where t1.e>e and exists(select 1 from t1 where b in (t1.b,e,t1.c) or e not between a and d) and 13<b),a))),t1.e) from t1 where t1.a<t1.a),t1.e) FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(coalesce((select case case coalesce((select d from t1 where b in (17,t1.a,13)),11) when (coalesce((select 11 from t1 where a++t1.d>(coalesce((select (f)+t1.c from t1 where a>t1.c),b))),t1.e)) then 19 else e end when t1.d then t1.e else b end from t1 where t1.b>=f),13)-b*17) from t1 where 11<>e),t1.b)<(c)))}
} {}
do_test randexpr-2.330 {
  db eval {SELECT (abs(case when ++e not in (~c-(19)*+case t1.c when t1.d-coalesce((select max(t1.f) from t1 where (select count(*) from t1)>case when exists(select 1 from t1 where not exists(select 1 from t1 where (not not exists(select 1 from t1 where 19<t1.c)))) then ~t1.d else case coalesce((select 17 from t1 where  -t1.b<>e),t1.e) when 13 then b else t1.c end end+f),c)*t1.c then t1.e else t1.b end,11,b) then  -(t1.b) else a end)/abs(13)) FROM t1 WHERE a*t1.a<=17 and exists(select 1 from t1 where (+case coalesce((select max(f) from t1 where d in (select ((+count(*)-( -max(b))))*min(t1.c)* -max(11) from t1 union select count(distinct (19)) from t1)),t1.c) when 13 then 19 else coalesce((select t1.a from t1 where t1.c not in (t1.c,f,13)),b) end)>t1.c) and ( -( -19) between 13 and b or b in (select 11 from t1 union select a from t1) and 19 in (t1.d,t1.d,19))}
} {}
do_test randexpr-2.331 {
  db eval {SELECT (abs(case when ++e not in (~c-(19)*+case t1.c when t1.d-coalesce((select max(t1.f) from t1 where (select count(*) from t1)>case when exists(select 1 from t1 where not exists(select 1 from t1 where (not not exists(select 1 from t1 where 19<t1.c)))) then ~t1.d else case coalesce((select 17 from t1 where  -t1.b<>e),t1.e) when 13 then b else t1.c end end+f),c)*t1.c then t1.e else t1.b end,11,b) then  -(t1.b) else a end)/abs(13)) FROM t1 WHERE NOT (a*t1.a<=17 and exists(select 1 from t1 where (+case coalesce((select max(f) from t1 where d in (select ((+count(*)-( -max(b))))*min(t1.c)* -max(11) from t1 union select count(distinct (19)) from t1)),t1.c) when 13 then 19 else coalesce((select t1.a from t1 where t1.c not in (t1.c,f,13)),b) end)>t1.c) and ( -( -19) between 13 and b or b in (select 11 from t1 union select a from t1) and 19 in (t1.d,t1.d,19)))}
} {15}
do_test randexpr-2.332 {
  db eval {SELECT case when a>=f then  -t1.a-11*t1.c when ((t1.e-t1.e+17 between (select max(c) from t1)-13 and coalesce((select t1.d from t1 where ((coalesce((select max(case when (not b>17) then t1.b-b when  -e in (c,a,13) then 11 else t1.a end) from t1 where 19<=11),t1.e)>=e))),t1.a))) then c else t1.b end | 17 FROM t1 WHERE 11-t1.d+d-13+(t1.f*case when exists(select 1 from t1 where ( -coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where 19 in (select d from t1 union select t1.f from t1)))),t1.d)<=case when 13*11+11 in (select abs(+~abs( -min(c))) from t1 union select (min(t1.e)) from t1) then t1.f else 19 end)) then t1.c else (abs(e)/abs(19)) end*t1.f*f)<(t1.d)}
} {}
do_test randexpr-2.333 {
  db eval {SELECT case when a>=f then  -t1.a-11*t1.c when ((t1.e-t1.e+17 between (select max(c) from t1)-13 and coalesce((select t1.d from t1 where ((coalesce((select max(case when (not b>17) then t1.b-b when  -e in (c,a,13) then 11 else t1.a end) from t1 where 19<=11),t1.e)>=e))),t1.a))) then c else t1.b end | 17 FROM t1 WHERE NOT (11-t1.d+d-13+(t1.f*case when exists(select 1 from t1 where ( -coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where 19 in (select d from t1 union select t1.f from t1)))),t1.d)<=case when 13*11+11 in (select abs(+~abs( -min(c))) from t1 union select (min(t1.e)) from t1) then t1.f else 19 end)) then t1.c else (abs(e)/abs(19)) end*t1.f*f)<(t1.d))}
} {217}
do_test randexpr-2.334 {
  db eval {SELECT case when a>=f then  -t1.a-11*t1.c when ((t1.e-t1.e+17 between (select max(c) from t1)-13 and coalesce((select t1.d from t1 where ((coalesce((select max(case when (not b>17) then t1.b-b when  -e in (c,a,13) then 11 else t1.a end) from t1 where 19<=11),t1.e)>=e))),t1.a))) then c else t1.b end & 17 FROM t1 WHERE NOT (11-t1.d+d-13+(t1.f*case when exists(select 1 from t1 where ( -coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where 19 in (select d from t1 union select t1.f from t1)))),t1.d)<=case when 13*11+11 in (select abs(+~abs( -min(c))) from t1 union select (min(t1.e)) from t1) then t1.f else 19 end)) then t1.c else (abs(e)/abs(19)) end*t1.f*f)<(t1.d))}
} {0}
do_test randexpr-2.335 {
  db eval {SELECT case ~13*c-t1.f- -t1.f when coalesce((select max(coalesce((select max(t1.c) from t1 where coalesce((select t1.d from t1 where 11*f-a=a),t1.e) in (select case ~count(distinct 11) | min(c) when (count(*))-count(*) then max( -17) else (min(13)) end from t1 union select  - -cast(avg(b) AS integer) from t1)),19)-t1.c) from t1 where exists(select 1 from t1 where t1.b not between t1.e and 11 and ((a<>t1.f)) and (t1.a)=t1.d)),17) then t1.d else  -b end FROM t1 WHERE case when ~13+t1.e-19>=13 then 17 else t1.c end>=a*19 and (f in (select case min(t1.e*+(abs(11)/abs(13))) when count(distinct t1.c) | abs((min(t1.b)-(max(t1.d)))+abs(max(a))+count(*)) | cast(avg(e) AS integer) then max(c) else max(c) end from t1 union select min(t1.c) from t1))}
} {}
do_test randexpr-2.336 {
  db eval {SELECT case ~13*c-t1.f- -t1.f when coalesce((select max(coalesce((select max(t1.c) from t1 where coalesce((select t1.d from t1 where 11*f-a=a),t1.e) in (select case ~count(distinct 11) | min(c) when (count(*))-count(*) then max( -17) else (min(13)) end from t1 union select  - -cast(avg(b) AS integer) from t1)),19)-t1.c) from t1 where exists(select 1 from t1 where t1.b not between t1.e and 11 and ((a<>t1.f)) and (t1.a)=t1.d)),17) then t1.d else  -b end FROM t1 WHERE NOT (case when ~13+t1.e-19>=13 then 17 else t1.c end>=a*19 and (f in (select case min(t1.e*+(abs(11)/abs(13))) when count(distinct t1.c) | abs((min(t1.b)-(max(t1.d)))+abs(max(a))+count(*)) | cast(avg(e) AS integer) then max(c) else max(c) end from t1 union select min(t1.c) from t1)))}
} {-200}
do_test randexpr-2.337 {
  db eval {SELECT case ~13*c-t1.f- -t1.f when coalesce((select max(coalesce((select max(t1.c) from t1 where coalesce((select t1.d from t1 where 11*f-a=a),t1.e) in (select case ~count(distinct 11) & min(c) when (count(*))-count(*) then max( -17) else (min(13)) end from t1 union select  - -cast(avg(b) AS integer) from t1)),19)-t1.c) from t1 where exists(select 1 from t1 where t1.b not between t1.e and 11 and ((a<>t1.f)) and (t1.a)=t1.d)),17) then t1.d else  -b end FROM t1 WHERE NOT (case when ~13+t1.e-19>=13 then 17 else t1.c end>=a*19 and (f in (select case min(t1.e*+(abs(11)/abs(13))) when count(distinct t1.c) | abs((min(t1.b)-(max(t1.d)))+abs(max(a))+count(*)) | cast(avg(e) AS integer) then max(c) else max(c) end from t1 union select min(t1.c) from t1)))}
} {-200}
do_test randexpr-2.338 {
  db eval {SELECT f*13-t1.f*(abs(19*t1.a*c-(select ~max(t1.c)- -( -cast(avg(f) AS integer))+(max(d))*cast(avg(t1.d) AS integer)*(count(*)) from t1))/abs(case when coalesce((select (coalesce((select max(t1.c) from t1 where  -(b)<> -t1.a),b)+11) from t1 where not (11)<=t1.e and c not between 17 and t1.e and b not in (f,(t1.a),t1.e)),t1.f) in (select t1.d from t1 union select 19 from t1) then t1.a when f>13 then t1.e else a end)) FROM t1 WHERE  -b<>b*t1.e}
} {-484800}
do_test randexpr-2.339 {
  db eval {SELECT f*13-t1.f*(abs(19*t1.a*c-(select ~max(t1.c)- -( -cast(avg(f) AS integer))+(max(d))*cast(avg(t1.d) AS integer)*(count(*)) from t1))/abs(case when coalesce((select (coalesce((select max(t1.c) from t1 where  -(b)<> -t1.a),b)+11) from t1 where not (11)<=t1.e and c not between 17 and t1.e and b not in (f,(t1.a),t1.e)),t1.f) in (select t1.d from t1 union select 19 from t1) then t1.a when f>13 then t1.e else a end)) FROM t1 WHERE NOT ( -b<>b*t1.e)}
} {}
do_test randexpr-2.340 {
  db eval {SELECT case when coalesce((select c from t1 where (13-(11-t1.e | t1.b) in (select +min(c)*+case +min(t1.e) when min(coalesce((select t1.e*t1.a from t1 where t1.f in (t1.d,11,t1.d) or t1.e>11 or t1.d>=c),17))+max(11)-count(distinct  -a) | max(11)+min(t1.c)-max(13) then count(distinct c) else (max(13)) end from t1 union select (( -cast(avg(11) AS integer))) from t1))),d) in (select f from t1 union select t1.a from t1) then 17 else 19 end FROM t1 WHERE not exists(select 1 from t1 where (select +min(case when not (f*e between (select min(~~t1.d) from t1)*(abs(c)/abs(d)) and case when f<t1.b then 19 else e end+t1.b) and not exists(select 1 from t1 where exists(select 1 from t1 where 11 in (select t1.e from t1 union select (a) from t1))) then case when  -c>=b then t1.f when not c>=17 then ~t1.b else 11 end else 19 end) from t1)-19 not in (d,t1.a,d))}
} {}
do_test randexpr-2.341 {
  db eval {SELECT case when coalesce((select c from t1 where (13-(11-t1.e | t1.b) in (select +min(c)*+case +min(t1.e) when min(coalesce((select t1.e*t1.a from t1 where t1.f in (t1.d,11,t1.d) or t1.e>11 or t1.d>=c),17))+max(11)-count(distinct  -a) | max(11)+min(t1.c)-max(13) then count(distinct c) else (max(13)) end from t1 union select (( -cast(avg(11) AS integer))) from t1))),d) in (select f from t1 union select t1.a from t1) then 17 else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select +min(case when not (f*e between (select min(~~t1.d) from t1)*(abs(c)/abs(d)) and case when f<t1.b then 19 else e end+t1.b) and not exists(select 1 from t1 where exists(select 1 from t1 where 11 in (select t1.e from t1 union select (a) from t1))) then case when  -c>=b then t1.f when not c>=17 then ~t1.b else 11 end else 19 end) from t1)-19 not in (d,t1.a,d)))}
} {19}
do_test randexpr-2.342 {
  db eval {SELECT case when coalesce((select c from t1 where (13-(11-t1.e & t1.b) in (select +min(c)*+case +min(t1.e) when min(coalesce((select t1.e*t1.a from t1 where t1.f in (t1.d,11,t1.d) or t1.e>11 or t1.d>=c),17))+max(11)-count(distinct  -a) & max(11)+min(t1.c)-max(13) then count(distinct c) else (max(13)) end from t1 union select (( -cast(avg(11) AS integer))) from t1))),d) in (select f from t1 union select t1.a from t1) then 17 else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select +min(case when not (f*e between (select min(~~t1.d) from t1)*(abs(c)/abs(d)) and case when f<t1.b then 19 else e end+t1.b) and not exists(select 1 from t1 where exists(select 1 from t1 where 11 in (select t1.e from t1 union select (a) from t1))) then case when  -c>=b then t1.f when not c>=17 then ~t1.b else 11 end else 19 end) from t1)-19 not in (d,t1.a,d)))}
} {19}
do_test randexpr-2.343 {
  db eval {SELECT t1.c*a+(case when t1.b+11 | case when exists(select 1 from t1 where b<>17 or not exists(select 1 from t1 where t1.f in (19,t1.f,c)) or (t1.d)<>b) then e else d end+t1.b+t1.a*b=t1.d or d=b then t1.e when not exists(select 1 from t1 where b>t1.c or 17 between t1.f and e and d>=t1.c) then t1.d else c end) FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where (abs(c)/abs(b)) in (t1.a, -e*~e*17,17)))}
} {30400}
do_test randexpr-2.344 {
  db eval {SELECT t1.c*a+(case when t1.b+11 | case when exists(select 1 from t1 where b<>17 or not exists(select 1 from t1 where t1.f in (19,t1.f,c)) or (t1.d)<>b) then e else d end+t1.b+t1.a*b=t1.d or d=b then t1.e when not exists(select 1 from t1 where b>t1.c or 17 between t1.f and e and d>=t1.c) then t1.d else c end) FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(c)/abs(b)) in (t1.a, -e*~e*17,17))))}
} {}
do_test randexpr-2.345 {
  db eval {SELECT t1.c*a+(case when t1.b+11 & case when exists(select 1 from t1 where b<>17 or not exists(select 1 from t1 where t1.f in (19,t1.f,c)) or (t1.d)<>b) then e else d end+t1.b+t1.a*b=t1.d or d=b then t1.e when not exists(select 1 from t1 where b>t1.c or 17 between t1.f and e and d>=t1.c) then t1.d else c end) FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where (abs(c)/abs(b)) in (t1.a, -e*~e*17,17)))}
} {30400}
do_test randexpr-2.346 {
  db eval {SELECT coalesce((select  -b from t1 where t1.f=d),case when case  -17-t1.b*t1.d+d when b then t1.a else t1.e end not in (t1.c,13,19) and e>f and 13 not between 17 and  -f and e not between d and a then 13 when c<=a then 13 else 19 | e end)*a-d*t1.e FROM t1 WHERE (abs(+t1.f)/abs(coalesce((select max(coalesce((select max(e) from t1 where t1.a in (select (abs( -t1.b)/abs(a)) from t1 union select e from t1)),(abs(case t1.f when c then (select (~cast(avg(b*d) AS integer))*abs(min(11)) from t1) else coalesce((select f from t1 where d in (select ( -min(e)) from t1 union select  -count(*) from t1)),t1.c) end*t1.b)/abs(c))+17)) from t1 where exists(select 1 from t1 where d not between t1.f and t1.b)),(t1.c))))*t1.d between t1.f and t1.a}
} {}
do_test randexpr-2.347 {
  db eval {SELECT coalesce((select  -b from t1 where t1.f=d),case when case  -17-t1.b*t1.d+d when b then t1.a else t1.e end not in (t1.c,13,19) and e>f and 13 not between 17 and  -f and e not between d and a then 13 when c<=a then 13 else 19 | e end)*a-d*t1.e FROM t1 WHERE NOT ((abs(+t1.f)/abs(coalesce((select max(coalesce((select max(e) from t1 where t1.a in (select (abs( -t1.b)/abs(a)) from t1 union select e from t1)),(abs(case t1.f when c then (select (~cast(avg(b*d) AS integer))*abs(min(11)) from t1) else coalesce((select f from t1 where d in (select ( -min(e)) from t1 union select  -count(*) from t1)),t1.c) end*t1.b)/abs(c))+17)) from t1 where exists(select 1 from t1 where d not between t1.f and t1.b)),(t1.c))))*t1.d between t1.f and t1.a)}
} {-149700}
do_test randexpr-2.348 {
  db eval {SELECT coalesce((select  -b from t1 where t1.f=d),case when case  -17-t1.b*t1.d+d when b then t1.a else t1.e end not in (t1.c,13,19) and e>f and 13 not between 17 and  -f and e not between d and a then 13 when c<=a then 13 else 19 & e end)*a-d*t1.e FROM t1 WHERE NOT ((abs(+t1.f)/abs(coalesce((select max(coalesce((select max(e) from t1 where t1.a in (select (abs( -t1.b)/abs(a)) from t1 union select e from t1)),(abs(case t1.f when c then (select (~cast(avg(b*d) AS integer))*abs(min(11)) from t1) else coalesce((select f from t1 where d in (select ( -min(e)) from t1 union select  -count(*) from t1)),t1.c) end*t1.b)/abs(c))+17)) from t1 where exists(select 1 from t1 where d not between t1.f and t1.b)),(t1.c))))*t1.d between t1.f and t1.a)}
} {-198400}
do_test randexpr-2.349 {
  db eval {SELECT coalesce((select t1.b*19 from t1 where ~f in (select 19 from t1 union select ~b-+case 13 when coalesce((select max(a) from t1 where (abs(d)/abs(t1.d)) | t1.e-c-t1.d-t1.c+11*f-c+t1.a>17), -a) then f else t1.d end+17 | a*f | t1.c-d from t1)),19) FROM t1 WHERE t1.e*t1.c>coalesce((select 13 from t1 where ~t1.a<>case when exists(select 1 from t1 where e<>~d and not +17 not between a+case 13 when d then case t1.d when t1.a then b else 13 end else 13 end and 13) or 13 not in (t1.e,t1.f,t1.c) then 19-e+19 when f<=t1.f then b else 11 end),e)-13}
} {19}
do_test randexpr-2.350 {
  db eval {SELECT coalesce((select t1.b*19 from t1 where ~f in (select 19 from t1 union select ~b-+case 13 when coalesce((select max(a) from t1 where (abs(d)/abs(t1.d)) | t1.e-c-t1.d-t1.c+11*f-c+t1.a>17), -a) then f else t1.d end+17 | a*f | t1.c-d from t1)),19) FROM t1 WHERE NOT (t1.e*t1.c>coalesce((select 13 from t1 where ~t1.a<>case when exists(select 1 from t1 where e<>~d and not +17 not between a+case 13 when d then case t1.d when t1.a then b else 13 end else 13 end and 13) or 13 not in (t1.e,t1.f,t1.c) then 19-e+19 when f<=t1.f then b else 11 end),e)-13)}
} {}
do_test randexpr-2.351 {
  db eval {SELECT coalesce((select t1.b*19 from t1 where ~f in (select 19 from t1 union select ~b-+case 13 when coalesce((select max(a) from t1 where (abs(d)/abs(t1.d)) & t1.e-c-t1.d-t1.c+11*f-c+t1.a>17), -a) then f else t1.d end+17 & a*f & t1.c-d from t1)),19) FROM t1 WHERE t1.e*t1.c>coalesce((select 13 from t1 where ~t1.a<>case when exists(select 1 from t1 where e<>~d and not +17 not between a+case 13 when d then case t1.d when t1.a then b else 13 end else 13 end and 13) or 13 not in (t1.e,t1.f,t1.c) then 19-e+19 when f<=t1.f then b else 11 end),e)-13}
} {19}
do_test randexpr-2.352 {
  db eval {SELECT (abs( -coalesce((select max((t1.f)) from t1 where not exists(select 1 from t1 where  -b-~b not between t1.c and f and t1.d*( -(select abs(+count(*)) from t1))-d>=a) and case when +case when ((f)) in (select  -count(distinct t1.a) from t1 union select count(*) from t1) then t1.b else d end in (select min(17) from t1 union select min(t1.e) from t1) then d else 17 end+c not between 11 and a),f)*11)/abs(a)) FROM t1 WHERE t1.f*t1.a*(+c)+case case when t1.d=f and (t1.a<>~+a*a*e*t1.e+case when t1.c between 11 and b and t1.a<>e then 13 when ( -t1.e)<>(t1.a) then (t1.b) else 13 end-t1.b-e+f) then t1.f+a else 17 end when d then 17 else d end-t1.e not in (13,t1.a,11)}
} {66}
do_test randexpr-2.353 {
  db eval {SELECT (abs( -coalesce((select max((t1.f)) from t1 where not exists(select 1 from t1 where  -b-~b not between t1.c and f and t1.d*( -(select abs(+count(*)) from t1))-d>=a) and case when +case when ((f)) in (select  -count(distinct t1.a) from t1 union select count(*) from t1) then t1.b else d end in (select min(17) from t1 union select min(t1.e) from t1) then d else 17 end+c not between 11 and a),f)*11)/abs(a)) FROM t1 WHERE NOT (t1.f*t1.a*(+c)+case case when t1.d=f and (t1.a<>~+a*a*e*t1.e+case when t1.c between 11 and b and t1.a<>e then 13 when ( -t1.e)<>(t1.a) then (t1.b) else 13 end-t1.b-e+f) then t1.f+a else 17 end when d then 17 else d end-t1.e not in (13,t1.a,11))}
} {}
do_test randexpr-2.354 {
  db eval {SELECT case t1.b- -t1.d+t1.d+t1.f when t1.f then 19+~13 else d end-case when not exists(select 1 from t1 where (f not between coalesce((select b from t1 where d in (17,13,t1.a) and 13 between c and 13 and 19>=f),13) and e or d not between 13 and f) or f>=d) then t1.f else coalesce((select max(~e-11) from t1 where t1.b in (f,13,13)),t1.a) end FROM t1 WHERE a<e}
} {300}
do_test randexpr-2.355 {
  db eval {SELECT case t1.b- -t1.d+t1.d+t1.f when t1.f then 19+~13 else d end-case when not exists(select 1 from t1 where (f not between coalesce((select b from t1 where d in (17,13,t1.a) and 13 between c and 13 and 19>=f),13) and e or d not between 13 and f) or f>=d) then t1.f else coalesce((select max(~e-11) from t1 where t1.b in (f,13,13)),t1.a) end FROM t1 WHERE NOT (a<e)}
} {}
do_test randexpr-2.356 {
  db eval {SELECT  -coalesce((select max(13) from t1 where case case when f in (select e from t1 union select coalesce((select max(e) from t1 where (select  -max(e) from t1)*t1.e<e and exists(select 1 from t1 where  -c in (a,a,a))),t1.d) from t1) and e>=t1.c and exists(select 1 from t1 where t1.f>=13) then t1.d when d between t1.d and t1.a then 19 else a end | e when (a) then e else a end between b and t1.c and not exists(select 1 from t1 where 13 in (t1.d,t1.a,13)) or t1.a>= -13),c) FROM t1 WHERE t1.e not in ( -coalesce((select max(13) from t1 where exists(select 1 from t1 where not t1.d>a) and t1.a not in (d*+case when t1.b in (select max(e*11+t1.a)+ -count(*)-( -max(t1.e))-min(11)-count(distinct t1.a) from t1 union select  - -min(t1.b) from t1) then t1.e when e in (select count(distinct t1.a) from t1 union select (max(d)) from t1) then e else  -(19) end+ -t1.d, -17,f)),case c when a then f else 17 end),d,11)}
} {-13}
do_test randexpr-2.357 {
  db eval {SELECT  -coalesce((select max(13) from t1 where case case when f in (select e from t1 union select coalesce((select max(e) from t1 where (select  -max(e) from t1)*t1.e<e and exists(select 1 from t1 where  -c in (a,a,a))),t1.d) from t1) and e>=t1.c and exists(select 1 from t1 where t1.f>=13) then t1.d when d between t1.d and t1.a then 19 else a end | e when (a) then e else a end between b and t1.c and not exists(select 1 from t1 where 13 in (t1.d,t1.a,13)) or t1.a>= -13),c) FROM t1 WHERE NOT (t1.e not in ( -coalesce((select max(13) from t1 where exists(select 1 from t1 where not t1.d>a) and t1.a not in (d*+case when t1.b in (select max(e*11+t1.a)+ -count(*)-( -max(t1.e))-min(11)-count(distinct t1.a) from t1 union select  - -min(t1.b) from t1) then t1.e when e in (select count(distinct t1.a) from t1 union select (max(d)) from t1) then e else  -(19) end+ -t1.d, -17,f)),case c when a then f else 17 end),d,11))}
} {}
do_test randexpr-2.358 {
  db eval {SELECT  -coalesce((select max(13) from t1 where case case when f in (select e from t1 union select coalesce((select max(e) from t1 where (select  -max(e) from t1)*t1.e<e and exists(select 1 from t1 where  -c in (a,a,a))),t1.d) from t1) and e>=t1.c and exists(select 1 from t1 where t1.f>=13) then t1.d when d between t1.d and t1.a then 19 else a end & e when (a) then e else a end between b and t1.c and not exists(select 1 from t1 where 13 in (t1.d,t1.a,13)) or t1.a>= -13),c) FROM t1 WHERE t1.e not in ( -coalesce((select max(13) from t1 where exists(select 1 from t1 where not t1.d>a) and t1.a not in (d*+case when t1.b in (select max(e*11+t1.a)+ -count(*)-( -max(t1.e))-min(11)-count(distinct t1.a) from t1 union select  - -min(t1.b) from t1) then t1.e when e in (select count(distinct t1.a) from t1 union select (max(d)) from t1) then e else  -(19) end+ -t1.d, -17,f)),case c when a then f else 17 end),d,11)}
} {-13}
do_test randexpr-2.359 {
  db eval {SELECT case d when  -e+coalesce((select max(case (select +abs((~case case count(distinct b) when  -count(*) then count(*) else max(t1.e) end when max(e) then min(t1.c) else count(*) end-min(c))) from t1) when t1.c then t1.a else  -11 end) from t1 where case ~t1.b when e then d else 11 end in (b,t1.e,t1.b) or not t1.f>=b or (t1.f in (a,e,t1.e)) or f<b),t1.e) then t1.b else f end FROM t1 WHERE b<=(d) and (abs(coalesce((select max(coalesce((select case when (abs(~11)/abs(((abs(17+f+t1.f)/abs(t1.c))-11*c)-d*17)) not in (b,13,((e))) then 19 else 19 end from t1 where a in (select t1.b from t1 union select t1.b from t1)),13)) from t1 where t1.d in (select a from t1 union select 13 from t1)), -e)+17*c)/abs(t1.c))=13}
} {}
do_test randexpr-2.360 {
  db eval {SELECT case d when  -e+coalesce((select max(case (select +abs((~case case count(distinct b) when  -count(*) then count(*) else max(t1.e) end when max(e) then min(t1.c) else count(*) end-min(c))) from t1) when t1.c then t1.a else  -11 end) from t1 where case ~t1.b when e then d else 11 end in (b,t1.e,t1.b) or not t1.f>=b or (t1.f in (a,e,t1.e)) or f<b),t1.e) then t1.b else f end FROM t1 WHERE NOT (b<=(d) and (abs(coalesce((select max(coalesce((select case when (abs(~11)/abs(((abs(17+f+t1.f)/abs(t1.c))-11*c)-d*17)) not in (b,13,((e))) then 19 else 19 end from t1 where a in (select t1.b from t1 union select t1.b from t1)),13)) from t1 where t1.d in (select a from t1 union select 13 from t1)), -e)+17*c)/abs(t1.c))=13)}
} {600}
do_test randexpr-2.361 {
  db eval {SELECT case a when ~c then e+17-d else case t1.a when c then t1.b else case when ((case t1.e when c then d-11 else t1.f end not in (e,(17),t1.d))) or not exists(select 1 from t1 where e not in (d,t1.f,11) and  -t1.a>t1.b) or t1.a not in (f,t1.b,t1.e) or t1.d<=t1.b and 19 not in (t1.d,11,t1.f) then t1.d else 19 end+e+17 end |  -t1.c*d end-13 FROM t1 WHERE e not in (e,t1.b,t1.d)}
} {}
do_test randexpr-2.362 {
  db eval {SELECT case a when ~c then e+17-d else case t1.a when c then t1.b else case when ((case t1.e when c then d-11 else t1.f end not in (e,(17),t1.d))) or not exists(select 1 from t1 where e not in (d,t1.f,11) and  -t1.a>t1.b) or t1.a not in (f,t1.b,t1.e) or t1.d<=t1.b and 19 not in (t1.d,11,t1.f) then t1.d else 19 end+e+17 end |  -t1.c*d end-13 FROM t1 WHERE NOT (e not in (e,t1.b,t1.d))}
} {-119864}
do_test randexpr-2.363 {
  db eval {SELECT case a when ~c then e+17-d else case t1.a when c then t1.b else case when ((case t1.e when c then d-11 else t1.f end not in (e,(17),t1.d))) or not exists(select 1 from t1 where e not in (d,t1.f,11) and  -t1.a>t1.b) or t1.a not in (f,t1.b,t1.e) or t1.d<=t1.b and 19 not in (t1.d,11,t1.f) then t1.d else 19 end+e+17 end &  -t1.c*d end-13 FROM t1 WHERE NOT (e not in (e,t1.b,t1.d))}
} {755}
do_test randexpr-2.364 {
  db eval {SELECT coalesce((select max(case t1.a when d then ~11 else t1.e end) from t1 where (t1.f*17<t1.d-(t1.a*t1.a+t1.b+case case d when coalesce((select max(19) from t1 where  -(t1.e) in (select count(distinct c) from t1 union select (count(distinct t1.f)) from t1)),13) then c else 19 end*d when c then 13 else 17 end+t1.c)) and (f>=a or t1.e=t1.a and  -c>=t1.b)),t1.b) FROM t1 WHERE a+( -t1.c) between case when case a when t1.f then ~t1.b*t1.c+17 else  -case when f not in (e,f,17) then a when 11=13 then t1.c else t1.d end end>=t1.b then b when t1.d in (select +max(19) from t1 union select abs(cast(avg(t1.f) AS integer))+case ~count(*)-max(t1.a)+max(11) when (max(a)) then (max(t1.d)) else count(distinct 11) end from t1) and e in (t1.d,17,11) then (11) else b end and a}
} {}
do_test randexpr-2.365 {
  db eval {SELECT coalesce((select max(case t1.a when d then ~11 else t1.e end) from t1 where (t1.f*17<t1.d-(t1.a*t1.a+t1.b+case case d when coalesce((select max(19) from t1 where  -(t1.e) in (select count(distinct c) from t1 union select (count(distinct t1.f)) from t1)),13) then c else 19 end*d when c then 13 else 17 end+t1.c)) and (f>=a or t1.e=t1.a and  -c>=t1.b)),t1.b) FROM t1 WHERE NOT (a+( -t1.c) between case when case a when t1.f then ~t1.b*t1.c+17 else  -case when f not in (e,f,17) then a when 11=13 then t1.c else t1.d end end>=t1.b then b when t1.d in (select +max(19) from t1 union select abs(cast(avg(t1.f) AS integer))+case ~count(*)-max(t1.a)+max(11) when (max(a)) then (max(t1.d)) else count(distinct 11) end from t1) and e in (t1.d,17,11) then (11) else b end and a)}
} {200}
do_test randexpr-2.366 {
  db eval {SELECT t1.f+case when c*f | (t1.a) in (select b*f from t1 union select  -case when d not between ~13 | 13+case a when a then e else a end and f then 11 else e-t1.d end from t1) then  -(abs(case when ((case t1.f when t1.b then t1.f else a end*f+t1.c)) in (select d from t1 union select (t1.e) from t1) then d else (t1.f) end)/abs(b)) else t1.a end FROM t1 WHERE ~(f+17-(select +max(t1.f)-case count(distinct d-19) when ~count(distinct (abs(b)/abs(a))) then cast(avg(17) AS integer) else ~count(distinct e)*count(*) end from t1)-f-coalesce((select t1.f from t1 where t1.a>=t1.c or t1.b between  -t1.a and 19 or exists(select 1 from t1 where t1.e not in (13,t1.c,e)) and d>a),t1.d)) not between d and c}
} {700}
do_test randexpr-2.367 {
  db eval {SELECT t1.f+case when c*f | (t1.a) in (select b*f from t1 union select  -case when d not between ~13 | 13+case a when a then e else a end and f then 11 else e-t1.d end from t1) then  -(abs(case when ((case t1.f when t1.b then t1.f else a end*f+t1.c)) in (select d from t1 union select (t1.e) from t1) then d else (t1.f) end)/abs(b)) else t1.a end FROM t1 WHERE NOT (~(f+17-(select +max(t1.f)-case count(distinct d-19) when ~count(distinct (abs(b)/abs(a))) then cast(avg(17) AS integer) else ~count(distinct e)*count(*) end from t1)-f-coalesce((select t1.f from t1 where t1.a>=t1.c or t1.b between  -t1.a and 19 or exists(select 1 from t1 where t1.e not in (13,t1.c,e)) and d>a),t1.d)) not between d and c)}
} {}
do_test randexpr-2.368 {
  db eval {SELECT t1.f+case when c*f & (t1.a) in (select b*f from t1 union select  -case when d not between ~13 & 13+case a when a then e else a end and f then 11 else e-t1.d end from t1) then  -(abs(case when ((case t1.f when t1.b then t1.f else a end*f+t1.c)) in (select d from t1 union select (t1.e) from t1) then d else (t1.f) end)/abs(b)) else t1.a end FROM t1 WHERE ~(f+17-(select +max(t1.f)-case count(distinct d-19) when ~count(distinct (abs(b)/abs(a))) then cast(avg(17) AS integer) else ~count(distinct e)*count(*) end from t1)-f-coalesce((select t1.f from t1 where t1.a>=t1.c or t1.b between  -t1.a and 19 or exists(select 1 from t1 where t1.e not in (13,t1.c,e)) and d>a),t1.d)) not between d and c}
} {700}
do_test randexpr-2.369 {
  db eval {SELECT case when coalesce((select d from t1 where not coalesce((select f*t1.b from t1 where exists(select 1 from t1 where (t1.f*t1.a)-19-13 in (select ~(cast(avg(t1.b) AS integer)) from t1 union select min(t1.a)+case min( -t1.a) when cast(avg(19) AS integer) then cast(avg(19) AS integer) else min(13) end+( -min(a)) from t1))),(t1.f)) between 17 and d),11)=19 then t1.b when 17<11 or exists(select 1 from t1 where d in (select 13 from t1 union select f from t1)) then 11 else t1.c end FROM t1 WHERE case c when 13 then +t1.d else t1.a end in (select abs(case + -count(*)+count(distinct coalesce((select (abs(~case when t1.c=19 | 13 then t1.c when not e>(13) then f else d end)/abs(a)) from t1 where 17>=t1.b),t1.b))+min(t1.a)*count(*) | (((max(a)))-cast(avg((17)) AS integer)) when max(d) then count(*) else cast(avg(t1.e) AS integer) end) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.370 {
  db eval {SELECT case when coalesce((select d from t1 where not coalesce((select f*t1.b from t1 where exists(select 1 from t1 where (t1.f*t1.a)-19-13 in (select ~(cast(avg(t1.b) AS integer)) from t1 union select min(t1.a)+case min( -t1.a) when cast(avg(19) AS integer) then cast(avg(19) AS integer) else min(13) end+( -min(a)) from t1))),(t1.f)) between 17 and d),11)=19 then t1.b when 17<11 or exists(select 1 from t1 where d in (select 13 from t1 union select f from t1)) then 11 else t1.c end FROM t1 WHERE NOT (case c when 13 then +t1.d else t1.a end in (select abs(case + -count(*)+count(distinct coalesce((select (abs(~case when t1.c=19 | 13 then t1.c when not e>(13) then f else d end)/abs(a)) from t1 where 17>=t1.b),t1.b))+min(t1.a)*count(*) | (((max(a)))-cast(avg((17)) AS integer)) when max(d) then count(*) else cast(avg(t1.e) AS integer) end) from t1 union select count(*) from t1))}
} {300}
do_test randexpr-2.371 {
  db eval {SELECT  -(select count(*) from t1)*(select (+(cast(avg(+f) AS integer))+++case +max(t1.b-case when t1.e+t1.e>=11 then  -a else t1.e end)-abs(min(e)+ -max(c) | ((max(11)))) when max(11) then (min(b)) else cast(avg( -b) AS integer) end-cast(avg(b) AS integer)-count(*)+count(*)) from t1)+~17- -t1.a FROM t1 WHERE f between 19*t1.d and 19}
} {}
do_test randexpr-2.372 {
  db eval {SELECT  -(select count(*) from t1)*(select (+(cast(avg(+f) AS integer))+++case +max(t1.b-case when t1.e+t1.e>=11 then  -a else t1.e end)-abs(min(e)+ -max(c) | ((max(11)))) when max(11) then (min(b)) else cast(avg( -b) AS integer) end-cast(avg(b) AS integer)-count(*)+count(*)) from t1)+~17- -t1.a FROM t1 WHERE NOT (f between 19*t1.d and 19)}
} {-118}
do_test randexpr-2.373 {
  db eval {SELECT  -(select count(*) from t1)*(select (+(cast(avg(+f) AS integer))+++case +max(t1.b-case when t1.e+t1.e>=11 then  -a else t1.e end)-abs(min(e)+ -max(c) & ((max(11)))) when max(11) then (min(b)) else cast(avg( -b) AS integer) end-cast(avg(b) AS integer)-count(*)+count(*)) from t1)+~17- -t1.a FROM t1 WHERE NOT (f between 19*t1.d and 19)}
} {-118}
do_test randexpr-2.374 {
  db eval {SELECT case when not t1.a< -~~e then b when c*(select +case max((abs( -a)/abs(a))) when min(t1.b) then case ~min(t1.d)-cast(avg(e) AS integer) | max(e) when count(distinct 11) then count(*) else max(b) end else count(*) end from t1) not between 13 and case when exists(select 1 from t1 where exists(select 1 from t1 where f not in (19,t1.f,19)) and 11 between t1.b and t1.b) then (13) else  -t1.d end then f else e end FROM t1 WHERE d>11}
} {200}
do_test randexpr-2.375 {
  db eval {SELECT case when not t1.a< -~~e then b when c*(select +case max((abs( -a)/abs(a))) when min(t1.b) then case ~min(t1.d)-cast(avg(e) AS integer) | max(e) when count(distinct 11) then count(*) else max(b) end else count(*) end from t1) not between 13 and case when exists(select 1 from t1 where exists(select 1 from t1 where f not in (19,t1.f,19)) and 11 between t1.b and t1.b) then (13) else  -t1.d end then f else e end FROM t1 WHERE NOT (d>11)}
} {}
do_test randexpr-2.376 {
  db eval {SELECT case when not t1.a< -~~e then b when c*(select +case max((abs( -a)/abs(a))) when min(t1.b) then case ~min(t1.d)-cast(avg(e) AS integer) & max(e) when count(distinct 11) then count(*) else max(b) end else count(*) end from t1) not between 13 and case when exists(select 1 from t1 where exists(select 1 from t1 where f not in (19,t1.f,19)) and 11 between t1.b and t1.b) then (13) else  -t1.d end then f else e end FROM t1 WHERE d>11}
} {200}
do_test randexpr-2.377 {
  db eval {SELECT coalesce((select max(t1.c | ~17) from t1 where exists(select 1 from t1 where t1.f<>b-(abs(13)/abs(e)))),13) FROM t1 WHERE case when case (abs(c+a+19+coalesce((select max(t1.a) from t1 where coalesce((select coalesce((select (f) from t1 where t1.d between 19 and b),t1.a) from t1 where 13=(c)),f) in (select ~case count(*) when max(t1.b) then ((count(distinct 11))) else count(*) end- -count(distinct a) from t1 union select count(distinct 13) from t1)),t1.c) | t1.b+t1.d)/abs(e)) when t1.d then a else 17 end not between 19 and t1.f then t1.b else d end in (select t1.c from t1 union select (t1.a) from t1)}
} {}
do_test randexpr-2.378 {
  db eval {SELECT coalesce((select max(t1.c | ~17) from t1 where exists(select 1 from t1 where t1.f<>b-(abs(13)/abs(e)))),13) FROM t1 WHERE NOT (case when case (abs(c+a+19+coalesce((select max(t1.a) from t1 where coalesce((select coalesce((select (f) from t1 where t1.d between 19 and b),t1.a) from t1 where 13=(c)),f) in (select ~case count(*) when max(t1.b) then ((count(distinct 11))) else count(*) end- -count(distinct a) from t1 union select count(distinct 13) from t1)),t1.c) | t1.b+t1.d)/abs(e)) when t1.d then a else 17 end not between 19 and t1.f then t1.b else d end in (select t1.c from t1 union select (t1.a) from t1))}
} {-18}
do_test randexpr-2.379 {
  db eval {SELECT coalesce((select max(t1.c & ~17) from t1 where exists(select 1 from t1 where t1.f<>b-(abs(13)/abs(e)))),13) FROM t1 WHERE NOT (case when case (abs(c+a+19+coalesce((select max(t1.a) from t1 where coalesce((select coalesce((select (f) from t1 where t1.d between 19 and b),t1.a) from t1 where 13=(c)),f) in (select ~case count(*) when max(t1.b) then ((count(distinct 11))) else count(*) end- -count(distinct a) from t1 union select count(distinct 13) from t1)),t1.c) | t1.b+t1.d)/abs(e)) when t1.d then a else 17 end not between 19 and t1.f then t1.b else d end in (select t1.c from t1 union select (t1.a) from t1))}
} {300}
do_test randexpr-2.380 {
  db eval {SELECT (coalesce((select (coalesce((select d from t1 where not exists(select 1 from t1 where 17>t1.c)),d))*c from t1 where t1.b between t1.d | (select count(distinct coalesce((select max(t1.e) from t1 where case when  -e>t1.b then f when t1.a<t1.f then t1.e else t1.d end<=c),(19))) from t1) and b or 13 in (t1.d,t1.d,t1.d)),t1.b)-b*f)+11-t1.e FROM t1 WHERE d<case when d>(abs(19*case when coalesce((select b*case when 11 not between 19 and (abs(13)/abs(t1.b-t1.d-e+b-f+19*t1.a)) then  -t1.a else f end from t1 where (b=17)),f)= -t1.d then 17 when 11<>19 then f else t1.d end)/abs(t1.b)) then d else 19 end}
} {}
do_test randexpr-2.381 {
  db eval {SELECT (coalesce((select (coalesce((select d from t1 where not exists(select 1 from t1 where 17>t1.c)),d))*c from t1 where t1.b between t1.d | (select count(distinct coalesce((select max(t1.e) from t1 where case when  -e>t1.b then f when t1.a<t1.f then t1.e else t1.d end<=c),(19))) from t1) and b or 13 in (t1.d,t1.d,t1.d)),t1.b)-b*f)+11-t1.e FROM t1 WHERE NOT (d<case when d>(abs(19*case when coalesce((select b*case when 11 not between 19 and (abs(13)/abs(t1.b-t1.d-e+b-f+19*t1.a)) then  -t1.a else f end from t1 where (b=17)),f)= -t1.d then 17 when 11<>19 then f else t1.d end)/abs(t1.b)) then d else 19 end)}
} {-120289}
do_test randexpr-2.382 {
  db eval {SELECT (coalesce((select (coalesce((select d from t1 where not exists(select 1 from t1 where 17>t1.c)),d))*c from t1 where t1.b between t1.d & (select count(distinct coalesce((select max(t1.e) from t1 where case when  -e>t1.b then f when t1.a<t1.f then t1.e else t1.d end<=c),(19))) from t1) and b or 13 in (t1.d,t1.d,t1.d)),t1.b)-b*f)+11-t1.e FROM t1 WHERE NOT (d<case when d>(abs(19*case when coalesce((select b*case when 11 not between 19 and (abs(13)/abs(t1.b-t1.d-e+b-f+19*t1.a)) then  -t1.a else f end from t1 where (b=17)),f)= -t1.d then 17 when 11<>19 then f else t1.d end)/abs(t1.b)) then d else 19 end)}
} {-489}
do_test randexpr-2.383 {
  db eval {SELECT 19*case when coalesce((select max(t1.e-c) from t1 where f=(abs(coalesce((select t1.c from t1 where not (not exists(select 1 from t1 where a in (select b from t1 union select c from t1)))),13))/abs(coalesce((select 13 from t1 where t1.b in (d,t1.d,a)), -t1.b)))),c) in (select ~min(t1.c) from t1 union select count(*) from t1) and  -f<>t1.c then t1.a-t1.e when not t1.a in (select cast(avg(a) AS integer) from t1 union select min(13) from t1) then  -19 else f end FROM t1 WHERE 11<>13}
} {11400}
do_test randexpr-2.384 {
  db eval {SELECT 19*case when coalesce((select max(t1.e-c) from t1 where f=(abs(coalesce((select t1.c from t1 where not (not exists(select 1 from t1 where a in (select b from t1 union select c from t1)))),13))/abs(coalesce((select 13 from t1 where t1.b in (d,t1.d,a)), -t1.b)))),c) in (select ~min(t1.c) from t1 union select count(*) from t1) and  -f<>t1.c then t1.a-t1.e when not t1.a in (select cast(avg(a) AS integer) from t1 union select min(13) from t1) then  -19 else f end FROM t1 WHERE NOT (11<>13)}
} {}
do_test randexpr-2.385 {
  db eval {SELECT t1.b*(select max(t1.b*coalesce((select max(t1.f*(t1.b)) from t1 where 17 not in (d,(a),(t1.b)+13)),t1.c)-t1.a) | cast(avg(t1.d) AS integer) | ~+case abs(abs(count(distinct t1.b))) when ~count(distinct e)-(count(*)) then max(t1.e) else max(d) end | max((19)) | min(19) from t1)-t1.d-t1.d*17 FROM t1 WHERE t1.f-case t1.d+19+13*case when (abs(e)/abs((select count(*)+cast(avg(a) AS integer)*count(*) from t1)-c*(abs(d)/abs(c*t1.e-19)))) not in (17,17,t1.a) then t1.f when t1.d<>t1.f then b else d end+ - -f*t1.b*d when b then 11 else  -13 end<=(t1.b)}
} {}
do_test randexpr-2.386 {
  db eval {SELECT t1.b*(select max(t1.b*coalesce((select max(t1.f*(t1.b)) from t1 where 17 not in (d,(a),(t1.b)+13)),t1.c)-t1.a) | cast(avg(t1.d) AS integer) | ~+case abs(abs(count(distinct t1.b))) when ~count(distinct e)-(count(*)) then max(t1.e) else max(d) end | max((19)) | min(19) from t1)-t1.d-t1.d*17 FROM t1 WHERE NOT (t1.f-case t1.d+19+13*case when (abs(e)/abs((select count(*)+cast(avg(a) AS integer)*count(*) from t1)-c*(abs(d)/abs(c*t1.e-19)))) not in (17,17,t1.a) then t1.f when t1.d<>t1.f then b else d end+ - -f*t1.b*d when b then 11 else  -13 end<=(t1.b))}
} {-7400}
do_test randexpr-2.387 {
  db eval {SELECT t1.b*(select max(t1.b*coalesce((select max(t1.f*(t1.b)) from t1 where 17 not in (d,(a),(t1.b)+13)),t1.c)-t1.a) & cast(avg(t1.d) AS integer) & ~+case abs(abs(count(distinct t1.b))) when ~count(distinct e)-(count(*)) then max(t1.e) else max(d) end & max((19)) & min(19) from t1)-t1.d-t1.d*17 FROM t1 WHERE NOT (t1.f-case t1.d+19+13*case when (abs(e)/abs((select count(*)+cast(avg(a) AS integer)*count(*) from t1)-c*(abs(d)/abs(c*t1.e-19)))) not in (17,17,t1.a) then t1.f when t1.d<>t1.f then b else d end+ - -f*t1.b*d when b then 11 else  -13 end<=(t1.b))}
} {-7200}
do_test randexpr-2.388 {
  db eval {SELECT (select abs(count(distinct t1.e) | min(b))-cast(avg(c) AS integer) | case +~+max(t1.a)*abs(+~ - -+cast(avg(19*f) AS integer) | count(*) | ~max(b) | ((max(t1.e)))-count(distinct t1.d)+ -(count(distinct t1.c)))* -count(distinct 17) | count(distinct a) when ((count(distinct t1.d))) then  -min(t1.c) else count(distinct t1.c) end- -min(d) from t1) FROM t1 WHERE ((not exists(select 1 from t1 where c=f)) and case when not 19+t1.c- -11+11+e>=a or t1.d>b then f else t1.e end<> -t1.c) or (t1.a in (select +count(*) from t1 union select abs((case max(d) when count(distinct d) then min( -t1.e) else count(distinct a) end-count(distinct  -t1.f)))*count(*) from t1) or not exists(select 1 from t1 where t1.d not in (c,17,e)))}
} {-99}
do_test randexpr-2.389 {
  db eval {SELECT (select abs(count(distinct t1.e) | min(b))-cast(avg(c) AS integer) | case +~+max(t1.a)*abs(+~ - -+cast(avg(19*f) AS integer) | count(*) | ~max(b) | ((max(t1.e)))-count(distinct t1.d)+ -(count(distinct t1.c)))* -count(distinct 17) | count(distinct a) when ((count(distinct t1.d))) then  -min(t1.c) else count(distinct t1.c) end- -min(d) from t1) FROM t1 WHERE NOT (((not exists(select 1 from t1 where c=f)) and case when not 19+t1.c- -11+11+e>=a or t1.d>b then f else t1.e end<> -t1.c) or (t1.a in (select +count(*) from t1 union select abs((case max(d) when count(distinct d) then min( -t1.e) else count(distinct a) end-count(distinct  -t1.f)))*count(*) from t1) or not exists(select 1 from t1 where t1.d not in (c,17,e))))}
} {}
do_test randexpr-2.390 {
  db eval {SELECT (select abs(count(distinct t1.e) & min(b))-cast(avg(c) AS integer) & case +~+max(t1.a)*abs(+~ - -+cast(avg(19*f) AS integer) & count(*) & ~max(b) & ((max(t1.e)))-count(distinct t1.d)+ -(count(distinct t1.c)))* -count(distinct 17) & count(distinct a) when ((count(distinct t1.d))) then  -min(t1.c) else count(distinct t1.c) end- -min(d) from t1) FROM t1 WHERE ((not exists(select 1 from t1 where c=f)) and case when not 19+t1.c- -11+11+e>=a or t1.d>b then f else t1.e end<> -t1.c) or (t1.a in (select +count(*) from t1 union select abs((case max(d) when count(distinct d) then min( -t1.e) else count(distinct a) end-count(distinct  -t1.f)))*count(*) from t1) or not exists(select 1 from t1 where t1.d not in (c,17,e)))}
} {144}
do_test randexpr-2.391 {
  db eval {SELECT case when exists(select 1 from t1 where coalesce((select b from t1 where case when (b<t1.b) then (select (min(a+17+a-t1.f)) from t1) else t1.a end in (select (17-a)*t1.e+c*c from t1 union select 17 from t1)),t1.f)<e) then case when t1.e in (t1.d, -t1.a,c) then 17 else  -e end when not t1.c in (select t1.e from t1 union select e from t1) then t1.c else t1.b end FROM t1 WHERE coalesce((select max(13) from t1 where e=t1.a),case when f+(d)<=~case when (case when 17*t1.a in (select 13 from t1 union select 19 from t1) then f else 17 end in (select max(t1.a) from t1 union select cast(avg(t1.e) AS integer)+max(a) | count(*) from t1)) or 13 in (b,t1.e,19) then t1.b*b when t1.a> -11 then  -t1.c else  -b end then d else t1.a end) not in (t1.b,d,t1.b)}
} {300}
do_test randexpr-2.392 {
  db eval {SELECT case when exists(select 1 from t1 where coalesce((select b from t1 where case when (b<t1.b) then (select (min(a+17+a-t1.f)) from t1) else t1.a end in (select (17-a)*t1.e+c*c from t1 union select 17 from t1)),t1.f)<e) then case when t1.e in (t1.d, -t1.a,c) then 17 else  -e end when not t1.c in (select t1.e from t1 union select e from t1) then t1.c else t1.b end FROM t1 WHERE NOT (coalesce((select max(13) from t1 where e=t1.a),case when f+(d)<=~case when (case when 17*t1.a in (select 13 from t1 union select 19 from t1) then f else 17 end in (select max(t1.a) from t1 union select cast(avg(t1.e) AS integer)+max(a) | count(*) from t1)) or 13 in (b,t1.e,19) then t1.b*b when t1.a> -11 then  -t1.c else  -b end then d else t1.a end) not in (t1.b,d,t1.b))}
} {}
do_test randexpr-2.393 {
  db eval {SELECT t1.f+coalesce((select t1.a-t1.d*f-coalesce((select max(coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where a=~t1.d+case when (c in (select abs(~( -cast(avg(e) AS integer))) from t1 union select  -min(19) from t1)) and 19<>t1.e or t1.e<11 and c in (t1.b,t1.b,t1.d) or 17 between  -t1.d and t1.d then 11 else d end)),c-f)) from t1 where t1.a<=t1.c),11)-t1.c from t1 where f between t1.a and d),19) FROM t1 WHERE exists(select 1 from t1 where case +t1.d when d then f else t1.e end in (t1.e,17,11) or 13*e-t1.b in (select t1.e from t1 union select 17 from t1)) and 11<=case  -case when not exists(select 1 from t1 where (17 | t1.e in (11,11,11) and b<(19))) then case t1.c+t1.f+c when t1.b then c else 19 end else 17 end when d then t1.b else t1.a end}
} {}
do_test randexpr-2.394 {
  db eval {SELECT t1.f+coalesce((select t1.a-t1.d*f-coalesce((select max(coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where a=~t1.d+case when (c in (select abs(~( -cast(avg(e) AS integer))) from t1 union select  -min(19) from t1)) and 19<>t1.e or t1.e<11 and c in (t1.b,t1.b,t1.d) or 17 between  -t1.d and t1.d then 11 else d end)),c-f)) from t1 where t1.a<=t1.c),11)-t1.c from t1 where f between t1.a and d),19) FROM t1 WHERE NOT (exists(select 1 from t1 where case +t1.d when d then f else t1.e end in (t1.e,17,11) or 13*e-t1.b in (select t1.e from t1 union select 17 from t1)) and 11<=case  -case when not exists(select 1 from t1 where (17 | t1.e in (11,11,11) and b<(19))) then case t1.c+t1.f+c when t1.b then c else 19 end else 17 end when d then t1.b else t1.a end)}
} {619}
do_test randexpr-2.395 {
  db eval {SELECT case when (coalesce((select coalesce((select max( -11) from t1 where not case t1.c*case when exists(select 1 from t1 where (t1.d) in (select case count(*) when count(distinct t1.c) then count(*) else count(*) end from t1 union select cast(avg(t1.c) AS integer) from t1)) then +e when f=19 then 17 else t1.e end when t1.a then 19 else c end=e),t1.a)- -d*f-a from t1 where (t1.e)<>13),19)*(a)=19) then (c) when (exists(select 1 from t1 where 17=t1.d)) then 19 else c end FROM t1 WHERE t1.d*c*(select cast(avg(((abs(t1.d*13)/abs(f)))) AS integer) from t1)+t1.d=case when +(coalesce((select t1.a from t1 where case when not exists(select 1 from t1 where not exists(select 1 from t1 where c=t1.e)) then 19 |  -17 else 13 end not in (t1.f,b,t1.b)),t1.f))*t1.a-t1.c-13 in (e,11,t1.c) then t1.a when (d between  -t1.f and f) then t1.d else t1.a end}
} {}
do_test randexpr-2.396 {
  db eval {SELECT case when (coalesce((select coalesce((select max( -11) from t1 where not case t1.c*case when exists(select 1 from t1 where (t1.d) in (select case count(*) when count(distinct t1.c) then count(*) else count(*) end from t1 union select cast(avg(t1.c) AS integer) from t1)) then +e when f=19 then 17 else t1.e end when t1.a then 19 else c end=e),t1.a)- -d*f-a from t1 where (t1.e)<>13),19)*(a)=19) then (c) when (exists(select 1 from t1 where 17=t1.d)) then 19 else c end FROM t1 WHERE NOT (t1.d*c*(select cast(avg(((abs(t1.d*13)/abs(f)))) AS integer) from t1)+t1.d=case when +(coalesce((select t1.a from t1 where case when not exists(select 1 from t1 where not exists(select 1 from t1 where c=t1.e)) then 19 |  -17 else 13 end not in (t1.f,b,t1.b)),t1.f))*t1.a-t1.c-13 in (e,11,t1.c) then t1.a when (d between  -t1.f and f) then t1.d else t1.a end)}
} {300}
do_test randexpr-2.397 {
  db eval {SELECT coalesce((select d from t1 where f in (select max(19) from t1 union select ~+max(t1.e) from t1)),b-case  -11 when 13 then t1.a-e else case when not exists(select 1 from t1 where c not in ( -t1.c,(t1.e),19)) and d+t1.b-t1.b in (select t1.a from t1 union select t1.d from t1) then 19+19*(t1.f) when t1.b<=a then 17 else t1.a end end+t1.b)*t1.a FROM t1 WHERE (select +cast(avg(~13+(select count(*) from t1)) AS integer)++min(case when (not d<>a) then coalesce((select t1.b from t1 where t1.f not between e and t1.d),13)+13 when t1.d not between 11 and t1.d then 17 else f end) | count(*) | ~count(distinct t1.e) | cast(avg(e) AS integer)-max(t1.d) from t1) not between coalesce((select case t1.a when a then e else 17 end from t1 where t1.a in (t1.e,11,( -t1.d))), -(b)) and t1.a}
} {}
do_test randexpr-2.398 {
  db eval {SELECT coalesce((select d from t1 where f in (select max(19) from t1 union select ~+max(t1.e) from t1)),b-case  -11 when 13 then t1.a-e else case when not exists(select 1 from t1 where c not in ( -t1.c,(t1.e),19)) and d+t1.b-t1.b in (select t1.a from t1 union select t1.d from t1) then 19+19*(t1.f) when t1.b<=a then 17 else t1.a end end+t1.b)*t1.a FROM t1 WHERE NOT ((select +cast(avg(~13+(select count(*) from t1)) AS integer)++min(case when (not d<>a) then coalesce((select t1.b from t1 where t1.f not between e and t1.d),13)+13 when t1.d not between 11 and t1.d then 17 else f end) | count(*) | ~count(distinct t1.e) | cast(avg(e) AS integer)-max(t1.d) from t1) not between coalesce((select case t1.a when a then e else 17 end from t1 where t1.a in (t1.e,11,( -t1.d))), -(b)) and t1.a)}
} {30000}
do_test randexpr-2.399 {
  db eval {SELECT (abs(c)/abs((coalesce((select t1.d from t1 where ((19) in (select count(distinct  - -(abs(coalesce((select max(t1.e) from t1 where t1.c*t1.a | t1.d=t1.d or t1.f in (select min(t1.f)-cast(avg(e) AS integer) from t1 union select  -count(*) from t1)),c))/abs(a))) from t1 union select case cast(avg(c) AS integer)-abs( -((count(*))))*(count(*))*min(d) when cast(avg(a) AS integer) then count(distinct 11) else count(*) end-(count(distinct 17)) from t1))),a))))*t1.e FROM t1 WHERE case when a between  -t1.a+(t1.c) and c-case when (~+t1.b-~case when t1.a not between 19*11 and 11 then t1.a when 11=f and  -t1.d not between t1.a and d then e else b end in (select min(19) from t1 union select case count(distinct 17) when count(*) then count(distinct t1.f) else min(c) end from t1)) then t1.f else 17 end then 17 else 13 end in (t1.a,t1.d,a)}
} {}
do_test randexpr-2.400 {
  db eval {SELECT (abs(c)/abs((coalesce((select t1.d from t1 where ((19) in (select count(distinct  - -(abs(coalesce((select max(t1.e) from t1 where t1.c*t1.a | t1.d=t1.d or t1.f in (select min(t1.f)-cast(avg(e) AS integer) from t1 union select  -count(*) from t1)),c))/abs(a))) from t1 union select case cast(avg(c) AS integer)-abs( -((count(*))))*(count(*))*min(d) when cast(avg(a) AS integer) then count(distinct 11) else count(*) end-(count(distinct 17)) from t1))),a))))*t1.e FROM t1 WHERE NOT (case when a between  -t1.a+(t1.c) and c-case when (~+t1.b-~case when t1.a not between 19*11 and 11 then t1.a when 11=f and  -t1.d not between t1.a and d then e else b end in (select min(19) from t1 union select case count(distinct 17) when count(*) then count(distinct t1.f) else min(c) end from t1)) then t1.f else 17 end then 17 else 13 end in (t1.a,t1.d,a))}
} {1500}
do_test randexpr-2.401 {
  db eval {SELECT (abs(c)/abs((coalesce((select t1.d from t1 where ((19) in (select count(distinct  - -(abs(coalesce((select max(t1.e) from t1 where t1.c*t1.a & t1.d=t1.d or t1.f in (select min(t1.f)-cast(avg(e) AS integer) from t1 union select  -count(*) from t1)),c))/abs(a))) from t1 union select case cast(avg(c) AS integer)-abs( -((count(*))))*(count(*))*min(d) when cast(avg(a) AS integer) then count(distinct 11) else count(*) end-(count(distinct 17)) from t1))),a))))*t1.e FROM t1 WHERE NOT (case when a between  -t1.a+(t1.c) and c-case when (~+t1.b-~case when t1.a not between 19*11 and 11 then t1.a when 11=f and  -t1.d not between t1.a and d then e else b end in (select min(19) from t1 union select case count(distinct 17) when count(*) then count(distinct t1.f) else min(c) end from t1)) then t1.f else 17 end then 17 else 13 end in (t1.a,t1.d,a))}
} {1500}
do_test randexpr-2.402 {
  db eval {SELECT case when d=c-(select (~max(t1.f*t1.c-11)) from t1) then coalesce((select max(19) from t1 where 13<coalesce((select case when (select count(distinct t1.f+13) from t1)>d then t1.e when not not exists(select 1 from t1 where t1.c not in (a,a,t1.d) and d not between b and 19) then t1.a else 11 end*f-f from t1 where t1.f between e and e and d between 19 and t1.e or 11<>t1.a),t1.c)),d) else 17 end FROM t1 WHERE (t1.e=11)}
} {}
do_test randexpr-2.403 {
  db eval {SELECT case when d=c-(select (~max(t1.f*t1.c-11)) from t1) then coalesce((select max(19) from t1 where 13<coalesce((select case when (select count(distinct t1.f+13) from t1)>d then t1.e when not not exists(select 1 from t1 where t1.c not in (a,a,t1.d) and d not between b and 19) then t1.a else 11 end*f-f from t1 where t1.f between e and e and d between 19 and t1.e or 11<>t1.a),t1.c)),d) else 17 end FROM t1 WHERE NOT ((t1.e=11))}
} {17}
do_test randexpr-2.404 {
  db eval {SELECT case when t1.a-t1.a | case when (abs(t1.d)/abs(t1.c | t1.a))<>t1.e then e*+t1.c-t1.d*coalesce((select t1.b from t1 where b>=+d+ -e*11),11)+t1.b | t1.f when not exists(select 1 from t1 where d not in (17,e,d)) then 11 else t1.d end>=13 then 11 when d=c then a else f end FROM t1 WHERE (abs(case when not t1.d<=t1.f and not t1.d not between  -f and  -17-11*t1.d and (13<t1.b) and 17 in (select min(c)-+min(13)-min(t1.b) from t1 union select  -max((( -11))) from t1) then 13 when c<>d then t1.d*coalesce((select max(t1.a) from t1 where (17) not between (t1.b) and 11),d) else t1.d end)/abs(f)) not between 13 and 19}
} {11}
do_test randexpr-2.405 {
  db eval {SELECT case when t1.a-t1.a | case when (abs(t1.d)/abs(t1.c | t1.a))<>t1.e then e*+t1.c-t1.d*coalesce((select t1.b from t1 where b>=+d+ -e*11),11)+t1.b | t1.f when not exists(select 1 from t1 where d not in (17,e,d)) then 11 else t1.d end>=13 then 11 when d=c then a else f end FROM t1 WHERE NOT ((abs(case when not t1.d<=t1.f and not t1.d not between  -f and  -17-11*t1.d and (13<t1.b) and 17 in (select min(c)-+min(13)-min(t1.b) from t1 union select  -max((( -11))) from t1) then 13 when c<>d then t1.d*coalesce((select max(t1.a) from t1 where (17) not between (t1.b) and 11),d) else t1.d end)/abs(f)) not between 13 and 19)}
} {}
do_test randexpr-2.406 {
  db eval {SELECT case when t1.a-t1.a & case when (abs(t1.d)/abs(t1.c & t1.a))<>t1.e then e*+t1.c-t1.d*coalesce((select t1.b from t1 where b>=+d+ -e*11),11)+t1.b & t1.f when not exists(select 1 from t1 where d not in (17,e,d)) then 11 else t1.d end>=13 then 11 when d=c then a else f end FROM t1 WHERE (abs(case when not t1.d<=t1.f and not t1.d not between  -f and  -17-11*t1.d and (13<t1.b) and 17 in (select min(c)-+min(13)-min(t1.b) from t1 union select  -max((( -11))) from t1) then 13 when c<>d then t1.d*coalesce((select max(t1.a) from t1 where (17) not between (t1.b) and 11),d) else t1.d end)/abs(f)) not between 13 and 19}
} {600}
do_test randexpr-2.407 {
  db eval {SELECT coalesce((select t1.f*13 from t1 where exists(select 1 from t1 where 13<=t1.e)),(abs(+ -17)/abs(c))) FROM t1 WHERE coalesce((select 17 from t1 where 11>++a-~t1.a+d | (19)),(abs(t1.c)/abs(case when case t1.c*17-case when b not between t1.b and f then t1.a when f>=a then 19 else 13 end when 19 then 13 else t1.f end not between c and a then c else 13 end)))> -e or 13 between f and c and t1.e>=b}
} {7800}
do_test randexpr-2.408 {
  db eval {SELECT coalesce((select t1.f*13 from t1 where exists(select 1 from t1 where 13<=t1.e)),(abs(+ -17)/abs(c))) FROM t1 WHERE NOT (coalesce((select 17 from t1 where 11>++a-~t1.a+d | (19)),(abs(t1.c)/abs(case when case t1.c*17-case when b not between t1.b and f then t1.a when f>=a then 19 else 13 end when 19 then 13 else t1.f end not between c and a then c else 13 end)))> -e or 13 between f and c and t1.e>=b)}
} {}
do_test randexpr-2.409 {
  db eval {SELECT ~+coalesce((select (select count(distinct +coalesce((select c from t1 where e>=13),+c)-t1.c) from t1) from t1 where case a when t1.d*(select cast(avg(case when t1.b*coalesce((select 17 from t1 where case  -a when t1.b then d else (t1.f) end not in ((t1.e),a,t1.f)),t1.c)-c in (d,a,t1.c) then c else b end) AS integer) from t1)+t1.d then 13 else t1.e end not in (19,a,17)),13) FROM t1 WHERE +c in (a,17,t1.d)}
} {}
do_test randexpr-2.410 {
  db eval {SELECT ~+coalesce((select (select count(distinct +coalesce((select c from t1 where e>=13),+c)-t1.c) from t1) from t1 where case a when t1.d*(select cast(avg(case when t1.b*coalesce((select 17 from t1 where case  -a when t1.b then d else (t1.f) end not in ((t1.e),a,t1.f)),t1.c)-c in (d,a,t1.c) then c else b end) AS integer) from t1)+t1.d then 13 else t1.e end not in (19,a,17)),13) FROM t1 WHERE NOT (+c in (a,17,t1.d))}
} {-2}
do_test randexpr-2.411 {
  db eval {SELECT f-coalesce((select t1.d from t1 where t1.a>11+t1.d),coalesce((select coalesce((select t1.d from t1 where 17>=d or (case c when t1.c then (t1.c) else t1.e end in (b,17,17) or t1.b>=t1.a) or t1.b<=e),case d when (19) then t1.d else t1.a end)-t1.d from t1 where 13 in (select ( -count(distinct (e)) | cast(avg(t1.d) AS integer)*count(*))+max( -11) | max( -c) from t1 union select count(distinct 11) from t1)),a)) FROM t1 WHERE not b<=13 or (coalesce((select max(t1.b) from t1 where b in (case when not a<>13 then 17 when  -(select ~abs( -(max(f))+count(distinct t1.a)) from t1)+13>=t1.b then case c when t1.a then d else f end-c else t1.d end-19, -t1.d,f)),19)) not in (t1.a,c,t1.d) or t1.e>t1.f}
} {500}
do_test randexpr-2.412 {
  db eval {SELECT f-coalesce((select t1.d from t1 where t1.a>11+t1.d),coalesce((select coalesce((select t1.d from t1 where 17>=d or (case c when t1.c then (t1.c) else t1.e end in (b,17,17) or t1.b>=t1.a) or t1.b<=e),case d when (19) then t1.d else t1.a end)-t1.d from t1 where 13 in (select ( -count(distinct (e)) | cast(avg(t1.d) AS integer)*count(*))+max( -11) | max( -c) from t1 union select count(distinct 11) from t1)),a)) FROM t1 WHERE NOT (not b<=13 or (coalesce((select max(t1.b) from t1 where b in (case when not a<>13 then 17 when  -(select ~abs( -(max(f))+count(distinct t1.a)) from t1)+13>=t1.b then case c when t1.a then d else f end-c else t1.d end-19, -t1.d,f)),19)) not in (t1.a,c,t1.d) or t1.e>t1.f)}
} {}
do_test randexpr-2.413 {
  db eval {SELECT f-coalesce((select t1.d from t1 where t1.a>11+t1.d),coalesce((select coalesce((select t1.d from t1 where 17>=d or (case c when t1.c then (t1.c) else t1.e end in (b,17,17) or t1.b>=t1.a) or t1.b<=e),case d when (19) then t1.d else t1.a end)-t1.d from t1 where 13 in (select ( -count(distinct (e)) & cast(avg(t1.d) AS integer)*count(*))+max( -11) & max( -c) from t1 union select count(distinct 11) from t1)),a)) FROM t1 WHERE not b<=13 or (coalesce((select max(t1.b) from t1 where b in (case when not a<>13 then 17 when  -(select ~abs( -(max(f))+count(distinct t1.a)) from t1)+13>=t1.b then case c when t1.a then d else f end-c else t1.d end-19, -t1.d,f)),19)) not in (t1.a,c,t1.d) or t1.e>t1.f}
} {500}
do_test randexpr-2.414 {
  db eval {SELECT coalesce((select e from t1 where (coalesce((select max(+e+e*11*t1.c-e) from t1 where exists(select 1 from t1 where (19<=~t1.f))),case (abs(t1.c)/abs(case t1.c when 19 then f*~case when t1.e+t1.d between  -t1.f and (d) then b when (d=a) then t1.e else e end else c end*t1.a)) | f when (d) then 17 else t1.f end)<t1.c)),13) FROM t1 WHERE a>coalesce((select coalesce((select e from t1 where case when  -d+t1.e>e then coalesce((select d+b from t1 where exists(select 1 from t1 where not 13-b not in (f,a,d)) and (t1.b between (a) and t1.c)),c) when a=13 then t1.e else a end in (select t1.d from t1 union select t1.d from t1) and e not in (d, -19,11)),d) from t1 where not f in (t1.a,19,t1.d)),t1.d)}
} {}
do_test randexpr-2.415 {
  db eval {SELECT coalesce((select e from t1 where (coalesce((select max(+e+e*11*t1.c-e) from t1 where exists(select 1 from t1 where (19<=~t1.f))),case (abs(t1.c)/abs(case t1.c when 19 then f*~case when t1.e+t1.d between  -t1.f and (d) then b when (d=a) then t1.e else e end else c end*t1.a)) | f when (d) then 17 else t1.f end)<t1.c)),13) FROM t1 WHERE NOT (a>coalesce((select coalesce((select e from t1 where case when  -d+t1.e>e then coalesce((select d+b from t1 where exists(select 1 from t1 where not 13-b not in (f,a,d)) and (t1.b between (a) and t1.c)),c) when a=13 then t1.e else a end in (select t1.d from t1 union select t1.d from t1) and e not in (d, -19,11)),d) from t1 where not f in (t1.a,19,t1.d)),t1.d))}
} {13}
do_test randexpr-2.416 {
  db eval {SELECT coalesce((select e from t1 where (coalesce((select max(+e+e*11*t1.c-e) from t1 where exists(select 1 from t1 where (19<=~t1.f))),case (abs(t1.c)/abs(case t1.c when 19 then f*~case when t1.e+t1.d between  -t1.f and (d) then b when (d=a) then t1.e else e end else c end*t1.a)) & f when (d) then 17 else t1.f end)<t1.c)),13) FROM t1 WHERE NOT (a>coalesce((select coalesce((select e from t1 where case when  -d+t1.e>e then coalesce((select d+b from t1 where exists(select 1 from t1 where not 13-b not in (f,a,d)) and (t1.b between (a) and t1.c)),c) when a=13 then t1.e else a end in (select t1.d from t1 union select t1.d from t1) and e not in (d, -19,11)),d) from t1 where not f in (t1.a,19,t1.d)),t1.d))}
} {13}
do_test randexpr-2.417 {
  db eval {SELECT (select count(distinct 11-17-11) from t1)-coalesce((select (abs(13)/abs(t1.b-c*11+coalesce((select max(f) from t1 where t1.a>t1.a),(e))*case when (abs(e)/abs(t1.b)) not between ~f and t1.e then c else (abs(t1.b)/abs(t1.d)) end | 13+b | b+t1.e)) from t1 where t1.c in (select t1.c from t1 union select (a) from t1)),19) FROM t1 WHERE t1.f>=19}
} {1}
do_test randexpr-2.418 {
  db eval {SELECT (select count(distinct 11-17-11) from t1)-coalesce((select (abs(13)/abs(t1.b-c*11+coalesce((select max(f) from t1 where t1.a>t1.a),(e))*case when (abs(e)/abs(t1.b)) not between ~f and t1.e then c else (abs(t1.b)/abs(t1.d)) end | 13+b | b+t1.e)) from t1 where t1.c in (select t1.c from t1 union select (a) from t1)),19) FROM t1 WHERE NOT (t1.f>=19)}
} {}
do_test randexpr-2.419 {
  db eval {SELECT (select count(distinct 11-17-11) from t1)-coalesce((select (abs(13)/abs(t1.b-c*11+coalesce((select max(f) from t1 where t1.a>t1.a),(e))*case when (abs(e)/abs(t1.b)) not between ~f and t1.e then c else (abs(t1.b)/abs(t1.d)) end & 13+b & b+t1.e)) from t1 where t1.c in (select t1.c from t1 union select (a) from t1)),19) FROM t1 WHERE t1.f>=19}
} {1}
do_test randexpr-2.420 {
  db eval {SELECT coalesce((select max(case when 11+(select +abs(count(*)) from t1) not in (case when (case when not exists(select 1 from t1 where t1.d=f) then a else a end+11 in (select ((13)) from t1 union select t1.d from t1)) then (abs(t1.c)/abs(t1.b)) when a>=t1.c then b else f end,t1.a,c) then t1.a when b in (select cast(avg(t1.a) AS integer) | ~ -count(distinct 17) from t1 union select min(c) from t1) then b else  -t1.e end) from t1 where d not between c and  -t1.b and b=d and b between 13 and t1.c),(17)) FROM t1 WHERE t1.a in (coalesce((select max(e) from t1 where case case (select count(*) from t1)-~19 when t1.f*t1.d+coalesce((select max((select + -(((min(t1.b)))) |  -(count(distinct t1.c)) | count(*) from t1)*11) from t1 where f>=case when d in ((d),t1.d,13) then 19 when 17=17 then 11 else a end),t1.e) then c else t1.f end when t1.e then f else t1.d end in (13,(13),c)),t1.d),t1.e,a)}
} {17}
do_test randexpr-2.421 {
  db eval {SELECT coalesce((select max(case when 11+(select +abs(count(*)) from t1) not in (case when (case when not exists(select 1 from t1 where t1.d=f) then a else a end+11 in (select ((13)) from t1 union select t1.d from t1)) then (abs(t1.c)/abs(t1.b)) when a>=t1.c then b else f end,t1.a,c) then t1.a when b in (select cast(avg(t1.a) AS integer) | ~ -count(distinct 17) from t1 union select min(c) from t1) then b else  -t1.e end) from t1 where d not between c and  -t1.b and b=d and b between 13 and t1.c),(17)) FROM t1 WHERE NOT (t1.a in (coalesce((select max(e) from t1 where case case (select count(*) from t1)-~19 when t1.f*t1.d+coalesce((select max((select + -(((min(t1.b)))) |  -(count(distinct t1.c)) | count(*) from t1)*11) from t1 where f>=case when d in ((d),t1.d,13) then 19 when 17=17 then 11 else a end),t1.e) then c else t1.f end when t1.e then f else t1.d end in (13,(13),c)),t1.d),t1.e,a))}
} {}
do_test randexpr-2.422 {
  db eval {SELECT coalesce((select max(case when 11+(select +abs(count(*)) from t1) not in (case when (case when not exists(select 1 from t1 where t1.d=f) then a else a end+11 in (select ((13)) from t1 union select t1.d from t1)) then (abs(t1.c)/abs(t1.b)) when a>=t1.c then b else f end,t1.a,c) then t1.a when b in (select cast(avg(t1.a) AS integer) & ~ -count(distinct 17) from t1 union select min(c) from t1) then b else  -t1.e end) from t1 where d not between c and  -t1.b and b=d and b between 13 and t1.c),(17)) FROM t1 WHERE t1.a in (coalesce((select max(e) from t1 where case case (select count(*) from t1)-~19 when t1.f*t1.d+coalesce((select max((select + -(((min(t1.b)))) |  -(count(distinct t1.c)) | count(*) from t1)*11) from t1 where f>=case when d in ((d),t1.d,13) then 19 when 17=17 then 11 else a end),t1.e) then c else t1.f end when t1.e then f else t1.d end in (13,(13),c)),t1.d),t1.e,a)}
} {17}
do_test randexpr-2.423 {
  db eval {SELECT coalesce((select t1.a-case t1.a when c then coalesce((select case (abs(11-(abs(t1.b)/abs(t1.a)))/abs((abs(t1.c)/abs(t1.a))))-t1.f when t1.d then f else 19 end from t1 where +t1.b*a in (select t1.e from t1 union select c from t1) and e between d and 11),t1.b) else a end from t1 where exists(select 1 from t1 where ((a in (13,c,d)))) and  -t1.e in ((t1.d),t1.a,t1.b)),t1.c) FROM t1 WHERE ++e*19 in (case when case when not (d<>case when  -case when (t1.a not between b and  -e) then 17 when f<>a then  -t1.d else t1.a end not in (a,a,c) then b when b<=c then e else b end) then 19 when (t1.b not in ( -13,t1.a,a)) then t1.b | 13 else e end* -19*t1.a<t1.f then t1.c when t1.f=t1.f then t1.a else t1.b end+d,a,11)}
} {}
do_test randexpr-2.424 {
  db eval {SELECT coalesce((select t1.a-case t1.a when c then coalesce((select case (abs(11-(abs(t1.b)/abs(t1.a)))/abs((abs(t1.c)/abs(t1.a))))-t1.f when t1.d then f else 19 end from t1 where +t1.b*a in (select t1.e from t1 union select c from t1) and e between d and 11),t1.b) else a end from t1 where exists(select 1 from t1 where ((a in (13,c,d)))) and  -t1.e in ((t1.d),t1.a,t1.b)),t1.c) FROM t1 WHERE NOT (++e*19 in (case when case when not (d<>case when  -case when (t1.a not between b and  -e) then 17 when f<>a then  -t1.d else t1.a end not in (a,a,c) then b when b<=c then e else b end) then 19 when (t1.b not in ( -13,t1.a,a)) then t1.b | 13 else e end* -19*t1.a<t1.f then t1.c when t1.f=t1.f then t1.a else t1.b end+d,a,11))}
} {300}
do_test randexpr-2.425 {
  db eval {SELECT (abs(e-((coalesce((select max(t1.c) from t1 where t1.f-a-case coalesce((select max(d) from t1 where (13<>~19)),f) when a- -t1.a | t1.f then t1.a*11-t1.e else coalesce((select max(t1.b) from t1 where not exists(select 1 from t1 where 17=t1.a or b>=f)),c) | t1.b end>19),t1.a))+c)-t1.c*e)/abs(t1.d)) FROM t1 WHERE a-t1.b not in (a,a-19-c | t1.d-d | e*t1.c*b,t1.e+t1.a)}
} {375}
do_test randexpr-2.426 {
  db eval {SELECT (abs(e-((coalesce((select max(t1.c) from t1 where t1.f-a-case coalesce((select max(d) from t1 where (13<>~19)),f) when a- -t1.a | t1.f then t1.a*11-t1.e else coalesce((select max(t1.b) from t1 where not exists(select 1 from t1 where 17=t1.a or b>=f)),c) | t1.b end>19),t1.a))+c)-t1.c*e)/abs(t1.d)) FROM t1 WHERE NOT (a-t1.b not in (a,a-19-c | t1.d-d | e*t1.c*b,t1.e+t1.a))}
} {}
do_test randexpr-2.427 {
  db eval {SELECT (abs(e-((coalesce((select max(t1.c) from t1 where t1.f-a-case coalesce((select max(d) from t1 where (13<>~19)),f) when a- -t1.a & t1.f then t1.a*11-t1.e else coalesce((select max(t1.b) from t1 where not exists(select 1 from t1 where 17=t1.a or b>=f)),c) & t1.b end>19),t1.a))+c)-t1.c*e)/abs(t1.d)) FROM t1 WHERE a-t1.b not in (a,a-19-c | t1.d-d | e*t1.c*b,t1.e+t1.a)}
} {375}
do_test randexpr-2.428 {
  db eval {SELECT t1.b-coalesce((select t1.a from t1 where (d<=f)),~~case b when coalesce((select coalesce((select t1.c from t1 where a+~+~(abs(t1.d)/abs(17)) |  -d*a*(b++ -13)*b>=b),17) | a from t1 where a<a),17)-13 then 11 else t1.a end) FROM t1 WHERE  -coalesce((select (abs(t1.d)/abs(~t1.e))-a from t1 where (c>=coalesce((select t1.d+(select case min(a) | max(t1.b) when max(e) then count(*) else  -count(distinct f) end from t1)-t1.f+( - - -19) from t1 where t1.c in (select 19 from t1 union select 17 from t1)),11))),19)+11 not in ((b),e,e) or t1.e in (select min(t1.f) from t1 union select count(*)- -(cast(avg(17) AS integer)) from t1) or e>=t1.c}
} {100}
do_test randexpr-2.429 {
  db eval {SELECT t1.b-coalesce((select t1.a from t1 where (d<=f)),~~case b when coalesce((select coalesce((select t1.c from t1 where a+~+~(abs(t1.d)/abs(17)) |  -d*a*(b++ -13)*b>=b),17) | a from t1 where a<a),17)-13 then 11 else t1.a end) FROM t1 WHERE NOT ( -coalesce((select (abs(t1.d)/abs(~t1.e))-a from t1 where (c>=coalesce((select t1.d+(select case min(a) | max(t1.b) when max(e) then count(*) else  -count(distinct f) end from t1)-t1.f+( - - -19) from t1 where t1.c in (select 19 from t1 union select 17 from t1)),11))),19)+11 not in ((b),e,e) or t1.e in (select min(t1.f) from t1 union select count(*)- -(cast(avg(17) AS integer)) from t1) or e>=t1.c)}
} {}
do_test randexpr-2.430 {
  db eval {SELECT t1.b-coalesce((select t1.a from t1 where (d<=f)),~~case b when coalesce((select coalesce((select t1.c from t1 where a+~+~(abs(t1.d)/abs(17)) &  -d*a*(b++ -13)*b>=b),17) & a from t1 where a<a),17)-13 then 11 else t1.a end) FROM t1 WHERE  -coalesce((select (abs(t1.d)/abs(~t1.e))-a from t1 where (c>=coalesce((select t1.d+(select case min(a) | max(t1.b) when max(e) then count(*) else  -count(distinct f) end from t1)-t1.f+( - - -19) from t1 where t1.c in (select 19 from t1 union select 17 from t1)),11))),19)+11 not in ((b),e,e) or t1.e in (select min(t1.f) from t1 union select count(*)- -(cast(avg(17) AS integer)) from t1) or e>=t1.c}
} {100}
do_test randexpr-2.431 {
  db eval {SELECT coalesce((select max(case when e<=t1.d then f*+case 17 when 17 then (abs((select abs(cast(avg(13) AS integer)+min(t1.b)) from t1))/abs(t1.c)) else d end*t1.c else a end) from t1 where coalesce((select t1.c from t1 where a<>t1.e+f-t1.c-a),+t1.a)+t1.d*case when d in (select t1.c from t1 union select 11 from t1) then a when 19 not in (d,e,b) then 11 else 19 end | t1.b in (select 19 from t1 union select t1.a from t1)),17)*11 FROM t1 WHERE 17>=t1.b}
} {}
do_test randexpr-2.432 {
  db eval {SELECT coalesce((select max(case when e<=t1.d then f*+case 17 when 17 then (abs((select abs(cast(avg(13) AS integer)+min(t1.b)) from t1))/abs(t1.c)) else d end*t1.c else a end) from t1 where coalesce((select t1.c from t1 where a<>t1.e+f-t1.c-a),+t1.a)+t1.d*case when d in (select t1.c from t1 union select 11 from t1) then a when 19 not in (d,e,b) then 11 else 19 end | t1.b in (select 19 from t1 union select t1.a from t1)),17)*11 FROM t1 WHERE NOT (17>=t1.b)}
} {187}
do_test randexpr-2.433 {
  db eval {SELECT coalesce((select max(case when e<=t1.d then f*+case 17 when 17 then (abs((select abs(cast(avg(13) AS integer)+min(t1.b)) from t1))/abs(t1.c)) else d end*t1.c else a end) from t1 where coalesce((select t1.c from t1 where a<>t1.e+f-t1.c-a),+t1.a)+t1.d*case when d in (select t1.c from t1 union select 11 from t1) then a when 19 not in (d,e,b) then 11 else 19 end & t1.b in (select 19 from t1 union select t1.a from t1)),17)*11 FROM t1 WHERE NOT (17>=t1.b)}
} {187}
do_test randexpr-2.434 {
  db eval {SELECT case when coalesce((select max(case f when (abs(t1.d)/abs(case when +~e not in (t1.d,c,t1.a) or 17 in (select count(distinct  -b) from t1 union select count(distinct d) from t1) and d<=t1.b or b>(f) then coalesce((select c from t1 where t1.f<t1.e),e)+(d) when 17<19 then t1.c else t1.b end)) then t1.b else f end) from t1 where (17 not between 11 and t1.b) or t1.f>f or t1.b<> -t1.c), -t1.d)<11 then c else f end FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where case  -case when case t1.c-t1.b-e when t1.b then t1.e else  -t1.c+~17 | coalesce((select max(t1.c) from t1 where 19 not between  -(a)-t1.c and 17),t1.c) end in (select (t1.f) from t1 union select b from t1) then e when c<>19 then t1.b else f end when  -11 then 11 else 19 end in ( -19,t1.a,d)) and not 17<t1.d)}
} {600}
do_test randexpr-2.435 {
  db eval {SELECT case when coalesce((select max(case f when (abs(t1.d)/abs(case when +~e not in (t1.d,c,t1.a) or 17 in (select count(distinct  -b) from t1 union select count(distinct d) from t1) and d<=t1.b or b>(f) then coalesce((select c from t1 where t1.f<t1.e),e)+(d) when 17<19 then t1.c else t1.b end)) then t1.b else f end) from t1 where (17 not between 11 and t1.b) or t1.f>f or t1.b<> -t1.c), -t1.d)<11 then c else f end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where case  -case when case t1.c-t1.b-e when t1.b then t1.e else  -t1.c+~17 | coalesce((select max(t1.c) from t1 where 19 not between  -(a)-t1.c and 17),t1.c) end in (select (t1.f) from t1 union select b from t1) then e when c<>19 then t1.b else f end when  -11 then 11 else 19 end in ( -19,t1.a,d)) and not 17<t1.d))}
} {}
do_test randexpr-2.436 {
  db eval {SELECT ((select abs(min(t1.b-t1.b)-cast(avg((t1.d-t1.a*a) | (select max(t1.e-e) | max(17)*~abs(count(*)-cast(avg(coalesce((select t1.c from t1 where t1.c<=11),19)+ -e) AS integer) | max(t1.c)) | min(b) | (count(*))*min(19)- -count(*) | (cast(avg(b) AS integer)) from t1)) AS integer)-cast(avg(t1.b) AS integer)) from t1)) FROM t1 WHERE +b+(19*19)+c+t1.d<=e-19+case 13 when t1.f+~11+(select cast(avg(t1.e) AS integer) from t1) then (case when not exists(select 1 from t1 where t1.a between d and t1.b) then case c when d then d else t1.f end when not t1.b in (11,t1.c,t1.d) or t1.c<=(d) then (t1.a) else t1.b end) else  -e end or f in (t1.f,d,t1.c)}
} {7995}
do_test randexpr-2.437 {
  db eval {SELECT ((select abs(min(t1.b-t1.b)-cast(avg((t1.d-t1.a*a) | (select max(t1.e-e) | max(17)*~abs(count(*)-cast(avg(coalesce((select t1.c from t1 where t1.c<=11),19)+ -e) AS integer) | max(t1.c)) | min(b) | (count(*))*min(19)- -count(*) | (cast(avg(b) AS integer)) from t1)) AS integer)-cast(avg(t1.b) AS integer)) from t1)) FROM t1 WHERE NOT (+b+(19*19)+c+t1.d<=e-19+case 13 when t1.f+~11+(select cast(avg(t1.e) AS integer) from t1) then (case when not exists(select 1 from t1 where t1.a between d and t1.b) then case c when d then d else t1.f end when not t1.b in (11,t1.c,t1.d) or t1.c<=(d) then (t1.a) else t1.b end) else  -e end or f in (t1.f,d,t1.c))}
} {}
do_test randexpr-2.438 {
  db eval {SELECT ((select abs(min(t1.b-t1.b)-cast(avg((t1.d-t1.a*a) & (select max(t1.e-e) & max(17)*~abs(count(*)-cast(avg(coalesce((select t1.c from t1 where t1.c<=11),19)+ -e) AS integer) & max(t1.c)) & min(b) & (count(*))*min(19)- -count(*) & (cast(avg(b) AS integer)) from t1)) AS integer)-cast(avg(t1.b) AS integer)) from t1)) FROM t1 WHERE +b+(19*19)+c+t1.d<=e-19+case 13 when t1.f+~11+(select cast(avg(t1.e) AS integer) from t1) then (case when not exists(select 1 from t1 where t1.a between d and t1.b) then case c when d then d else t1.f end when not t1.b in (11,t1.c,t1.d) or t1.c<=(d) then (t1.a) else t1.b end) else  -e end or f in (t1.f,d,t1.c)}
} {200}
do_test randexpr-2.439 {
  db eval {SELECT case when (b<coalesce((select coalesce((select max(19 | t1.c) from t1 where 13 not in (t1.f,e,t1.e) or (select (count(distinct coalesce((select d from t1 where t1.c between  -17 and b),11)) | count(*)-max(t1.d)* -(max(d))) from t1)-c*t1.e in (select 19 | f from t1 union select a from t1)),c)*a from t1 where (13 not between a and 19)),19) and b>a) then t1.f else t1.c end FROM t1 WHERE case when (((case coalesce((select  -t1.b-t1.b*19*c | 19 from t1 where (exists(select 1 from t1 where e>=t1.a))),t1.a)+11 when d then t1.e else t1.c end=t1.d))) then t1.b when not not exists(select 1 from t1 where t1.f<(t1.a)) and t1.d>=f or t1.c>t1.a or t1.b between t1.f and 19 then t1.c else ~t1.c end=11 or (t1.e) not between 13 and t1.c}
} {600}
do_test randexpr-2.440 {
  db eval {SELECT case when (b<coalesce((select coalesce((select max(19 | t1.c) from t1 where 13 not in (t1.f,e,t1.e) or (select (count(distinct coalesce((select d from t1 where t1.c between  -17 and b),11)) | count(*)-max(t1.d)* -(max(d))) from t1)-c*t1.e in (select 19 | f from t1 union select a from t1)),c)*a from t1 where (13 not between a and 19)),19) and b>a) then t1.f else t1.c end FROM t1 WHERE NOT (case when (((case coalesce((select  -t1.b-t1.b*19*c | 19 from t1 where (exists(select 1 from t1 where e>=t1.a))),t1.a)+11 when d then t1.e else t1.c end=t1.d))) then t1.b when not not exists(select 1 from t1 where t1.f<(t1.a)) and t1.d>=f or t1.c>t1.a or t1.b between t1.f and 19 then t1.c else ~t1.c end=11 or (t1.e) not between 13 and t1.c)}
} {}
do_test randexpr-2.441 {
  db eval {SELECT case when (b<coalesce((select coalesce((select max(19 & t1.c) from t1 where 13 not in (t1.f,e,t1.e) or (select (count(distinct coalesce((select d from t1 where t1.c between  -17 and b),11)) & count(*)-max(t1.d)* -(max(d))) from t1)-c*t1.e in (select 19 & f from t1 union select a from t1)),c)*a from t1 where (13 not between a and 19)),19) and b>a) then t1.f else t1.c end FROM t1 WHERE case when (((case coalesce((select  -t1.b-t1.b*19*c | 19 from t1 where (exists(select 1 from t1 where e>=t1.a))),t1.a)+11 when d then t1.e else t1.c end=t1.d))) then t1.b when not not exists(select 1 from t1 where t1.f<(t1.a)) and t1.d>=f or t1.c>t1.a or t1.b between t1.f and 19 then t1.c else ~t1.c end=11 or (t1.e) not between 13 and t1.c}
} {300}
do_test randexpr-2.442 {
  db eval {SELECT case when not t1.d not in (coalesce((select 17 |  -coalesce((select (select min(a-t1.a+t1.a-t1.c*t1.e) from t1) from t1 where t1.d<=a),11) | 19 from t1 where not ( -13 in ( -t1.d,t1.d,19))),e)+11,11,13) then e when ((t1.b<t1.c) or d=19) then (t1.a) else a end FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where ~f-e+t1.b*d+case when coalesce((select max(d) from t1 where (t1.c*t1.b in (b,t1.e,17)) or t1.b not in (t1.c,t1.a,t1.c)), -17) in (select count(distinct 13) from t1 union select  - -~min( -11) | cast(avg(c) AS integer) from t1) then f else a end+e*t1.c+t1.c>t1.f and a>=17))}
} {}
do_test randexpr-2.443 {
  db eval {SELECT case when not t1.d not in (coalesce((select 17 |  -coalesce((select (select min(a-t1.a+t1.a-t1.c*t1.e) from t1) from t1 where t1.d<=a),11) | 19 from t1 where not ( -13 in ( -t1.d,t1.d,19))),e)+11,11,13) then e when ((t1.b<t1.c) or d=19) then (t1.a) else a end FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where ~f-e+t1.b*d+case when coalesce((select max(d) from t1 where (t1.c*t1.b in (b,t1.e,17)) or t1.b not in (t1.c,t1.a,t1.c)), -17) in (select count(distinct 13) from t1 union select  - -~min( -11) | cast(avg(c) AS integer) from t1) then f else a end+e*t1.c+t1.c>t1.f and a>=17)))}
} {100}
do_test randexpr-2.444 {
  db eval {SELECT case when not t1.d not in (coalesce((select 17 &  -coalesce((select (select min(a-t1.a+t1.a-t1.c*t1.e) from t1) from t1 where t1.d<=a),11) & 19 from t1 where not ( -13 in ( -t1.d,t1.d,19))),e)+11,11,13) then e when ((t1.b<t1.c) or d=19) then (t1.a) else a end FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where ~f-e+t1.b*d+case when coalesce((select max(d) from t1 where (t1.c*t1.b in (b,t1.e,17)) or t1.b not in (t1.c,t1.a,t1.c)), -17) in (select count(distinct 13) from t1 union select  - -~min( -11) | cast(avg(c) AS integer) from t1) then f else a end+e*t1.c+t1.c>t1.f and a>=17)))}
} {100}
do_test randexpr-2.445 {
  db eval {SELECT e+c-(c)+t1.e*(abs(case when 13 in (select abs(max(17)*case  -count(*) when cast(avg(a) AS integer) then count(distinct b) else  -max(f) end | (cast(avg(t1.e) AS integer)) |  -min(f)) from t1 union select count(distinct d) from t1) and case when (t1.e+a> -(a)) then e when not c<t1.f or t1.d=f then e else t1.e end<=t1.f then  -a when t1.d<=13 then a else t1.b end)/abs( -t1.a))-t1.b+t1.b FROM t1 WHERE case when  -case when t1.f<t1.c then  -(t1.e) when 11 between e and coalesce((select c from t1 where not exists(select 1 from t1 where b>=e)),coalesce((select max(case t1.e when t1.c then t1.a else a end) from t1 where b>=t1.c and b<>t1.c),13)) then t1.b else a end<11 then b when (11 in (select a from t1 union select t1.b from t1)) or t1.b=e or a between a and 13 then t1.b else b end>19}
} {1500}
do_test randexpr-2.446 {
  db eval {SELECT e+c-(c)+t1.e*(abs(case when 13 in (select abs(max(17)*case  -count(*) when cast(avg(a) AS integer) then count(distinct b) else  -max(f) end | (cast(avg(t1.e) AS integer)) |  -min(f)) from t1 union select count(distinct d) from t1) and case when (t1.e+a> -(a)) then e when not c<t1.f or t1.d=f then e else t1.e end<=t1.f then  -a when t1.d<=13 then a else t1.b end)/abs( -t1.a))-t1.b+t1.b FROM t1 WHERE NOT (case when  -case when t1.f<t1.c then  -(t1.e) when 11 between e and coalesce((select c from t1 where not exists(select 1 from t1 where b>=e)),coalesce((select max(case t1.e when t1.c then t1.a else a end) from t1 where b>=t1.c and b<>t1.c),13)) then t1.b else a end<11 then b when (11 in (select a from t1 union select t1.b from t1)) or t1.b=e or a between a and 13 then t1.b else b end>19)}
} {}
do_test randexpr-2.447 {
  db eval {SELECT e+c-(c)+t1.e*(abs(case when 13 in (select abs(max(17)*case  -count(*) when cast(avg(a) AS integer) then count(distinct b) else  -max(f) end & (cast(avg(t1.e) AS integer)) &  -min(f)) from t1 union select count(distinct d) from t1) and case when (t1.e+a> -(a)) then e when not c<t1.f or t1.d=f then e else t1.e end<=t1.f then  -a when t1.d<=13 then a else t1.b end)/abs( -t1.a))-t1.b+t1.b FROM t1 WHERE case when  -case when t1.f<t1.c then  -(t1.e) when 11 between e and coalesce((select c from t1 where not exists(select 1 from t1 where b>=e)),coalesce((select max(case t1.e when t1.c then t1.a else a end) from t1 where b>=t1.c and b<>t1.c),13)) then t1.b else a end<11 then b when (11 in (select a from t1 union select t1.b from t1)) or t1.b=e or a between a and 13 then t1.b else b end>19}
} {1500}
do_test randexpr-2.448 {
  db eval {SELECT 13-coalesce((select t1.a*a from t1 where not exists(select 1 from t1 where 17 not between case +coalesce((select  -case 19 when a*b then 19 else f end from t1 where (t1.d-t1.e between case f when (select abs(case abs( -min(13)) when min(t1.b) then  -(count(distinct f)) else min(t1.b) end) from t1) then 17*( -13) | f else t1.e end and  -t1.a)),d)*c when 13 then 11 else t1.a end and c)),t1.a)*19 FROM t1 WHERE ((not f-c<=(abs(a)/abs(+t1.a)) or t1.e not between coalesce((select 11 from t1 where  - -a*t1.d*case coalesce((select max(d) from t1 where ((t1.b<=t1.c))),case when f>t1.d or t1.d=t1.a or t1.c<=c then a else  -c end*t1.b) when (f) then 11 else 19 end-t1.a<=b),c) and 13))}
} {-1887}
do_test randexpr-2.449 {
  db eval {SELECT 13-coalesce((select t1.a*a from t1 where not exists(select 1 from t1 where 17 not between case +coalesce((select  -case 19 when a*b then 19 else f end from t1 where (t1.d-t1.e between case f when (select abs(case abs( -min(13)) when min(t1.b) then  -(count(distinct f)) else min(t1.b) end) from t1) then 17*( -13) | f else t1.e end and  -t1.a)),d)*c when 13 then 11 else t1.a end and c)),t1.a)*19 FROM t1 WHERE NOT (((not f-c<=(abs(a)/abs(+t1.a)) or t1.e not between coalesce((select 11 from t1 where  - -a*t1.d*case coalesce((select max(d) from t1 where ((t1.b<=t1.c))),case when f>t1.d or t1.d=t1.a or t1.c<=c then a else  -c end*t1.b) when (f) then 11 else 19 end-t1.a<=b),c) and 13)))}
} {}
do_test randexpr-2.450 {
  db eval {SELECT 13-coalesce((select t1.a*a from t1 where not exists(select 1 from t1 where 17 not between case +coalesce((select  -case 19 when a*b then 19 else f end from t1 where (t1.d-t1.e between case f when (select abs(case abs( -min(13)) when min(t1.b) then  -(count(distinct f)) else min(t1.b) end) from t1) then 17*( -13) & f else t1.e end and  -t1.a)),d)*c when 13 then 11 else t1.a end and c)),t1.a)*19 FROM t1 WHERE ((not f-c<=(abs(a)/abs(+t1.a)) or t1.e not between coalesce((select 11 from t1 where  - -a*t1.d*case coalesce((select max(d) from t1 where ((t1.b<=t1.c))),case when f>t1.d or t1.d=t1.a or t1.c<=c then a else  -c end*t1.b) when (f) then 11 else 19 end-t1.a<=b),c) and 13))}
} {-1887}
do_test randexpr-2.451 {
  db eval {SELECT ~case when (t1.d | 17 in (b*t1.e,19*case when t1.d<= -a then t1.d*~t1.c*e*t1.c-19 else ~t1.b+17 end-d,(t1.c))) then +t1.d else (abs( -case t1.e when t1.c then (t1.b) else t1.f end-11+ -a)/abs(f))+a end FROM t1 WHERE not exists(select 1 from t1 where not c in (select case count(distinct (f)-19) when ~( -+~cast(avg(c) AS integer) | count(distinct 11)-max(d)+min(t1.a)+ -( -count(distinct b))+(count(*)))-count(*)+cast(avg(c) AS integer) then count(distinct d) else ((max(t1.b))) end-min(b) from t1 union select min(t1.c) from t1)) and t1.c in (select +d from t1 union select case when c+b=17 then a else 13 end+11 from t1)}
} {}
do_test randexpr-2.452 {
  db eval {SELECT ~case when (t1.d | 17 in (b*t1.e,19*case when t1.d<= -a then t1.d*~t1.c*e*t1.c-19 else ~t1.b+17 end-d,(t1.c))) then +t1.d else (abs( -case t1.e when t1.c then (t1.b) else t1.f end-11+ -a)/abs(f))+a end FROM t1 WHERE NOT (not exists(select 1 from t1 where not c in (select case count(distinct (f)-19) when ~( -+~cast(avg(c) AS integer) | count(distinct 11)-max(d)+min(t1.a)+ -( -count(distinct b))+(count(*)))-count(*)+cast(avg(c) AS integer) then count(distinct d) else ((max(t1.b))) end-min(b) from t1 union select min(t1.c) from t1)) and t1.c in (select +d from t1 union select case when c+b=17 then a else 13 end+11 from t1))}
} {-102}
do_test randexpr-2.453 {
  db eval {SELECT ~case when (t1.d & 17 in (b*t1.e,19*case when t1.d<= -a then t1.d*~t1.c*e*t1.c-19 else ~t1.b+17 end-d,(t1.c))) then +t1.d else (abs( -case t1.e when t1.c then (t1.b) else t1.f end-11+ -a)/abs(f))+a end FROM t1 WHERE NOT (not exists(select 1 from t1 where not c in (select case count(distinct (f)-19) when ~( -+~cast(avg(c) AS integer) | count(distinct 11)-max(d)+min(t1.a)+ -( -count(distinct b))+(count(*)))-count(*)+cast(avg(c) AS integer) then count(distinct d) else ((max(t1.b))) end-min(b) from t1 union select min(t1.c) from t1)) and t1.c in (select +d from t1 union select case when c+b=17 then a else 13 end+11 from t1))}
} {-102}
do_test randexpr-2.454 {
  db eval {SELECT (select case case min(d) when abs(cast(avg((abs(a)/abs(coalesce((select (select abs(cast(avg(t1.f) AS integer)) from t1) from t1 where (case when t1.e in (select 11 from t1 union select 17 from t1) then  -t1.e- -t1.e else a end<>a) and not not exists(select 1 from t1 where t1.b in (select ~+max( -t1.b) | max(t1.c) from t1 union select count(distinct  -t1.a) from t1))),t1.a)))) AS integer)) then (count(*) | ((count(distinct b)))-count(*)) else min(11) end when max(a) then count(distinct f) else (min(17)) end from t1) FROM t1 WHERE coalesce((select max(13) from t1 where t1.b not in ( -case when 13 not between 17 and b then f when t1.e+~+e between coalesce((select max(case 19 when e then 17 else coalesce((select coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.b not between t1.a and a)),e)*b*t1.f from t1 where t1.f>=t1.c),c) end) from t1 where e>b),t1.f) | f and f then c else 11 end,(c),t1.e)),19)-t1.c in (select t1.a from t1 union select e from t1)}
} {}
do_test randexpr-2.455 {
  db eval {SELECT (select case case min(d) when abs(cast(avg((abs(a)/abs(coalesce((select (select abs(cast(avg(t1.f) AS integer)) from t1) from t1 where (case when t1.e in (select 11 from t1 union select 17 from t1) then  -t1.e- -t1.e else a end<>a) and not not exists(select 1 from t1 where t1.b in (select ~+max( -t1.b) | max(t1.c) from t1 union select count(distinct  -t1.a) from t1))),t1.a)))) AS integer)) then (count(*) | ((count(distinct b)))-count(*)) else min(11) end when max(a) then count(distinct f) else (min(17)) end from t1) FROM t1 WHERE NOT (coalesce((select max(13) from t1 where t1.b not in ( -case when 13 not between 17 and b then f when t1.e+~+e between coalesce((select max(case 19 when e then 17 else coalesce((select coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.b not between t1.a and a)),e)*b*t1.f from t1 where t1.f>=t1.c),c) end) from t1 where e>b),t1.f) | f and f then c else 11 end,(c),t1.e)),19)-t1.c in (select t1.a from t1 union select e from t1))}
} {17}
do_test randexpr-2.456 {
  db eval {SELECT (select case case min(d) when abs(cast(avg((abs(a)/abs(coalesce((select (select abs(cast(avg(t1.f) AS integer)) from t1) from t1 where (case when t1.e in (select 11 from t1 union select 17 from t1) then  -t1.e- -t1.e else a end<>a) and not not exists(select 1 from t1 where t1.b in (select ~+max( -t1.b) & max(t1.c) from t1 union select count(distinct  -t1.a) from t1))),t1.a)))) AS integer)) then (count(*) & ((count(distinct b)))-count(*)) else min(11) end when max(a) then count(distinct f) else (min(17)) end from t1) FROM t1 WHERE NOT (coalesce((select max(13) from t1 where t1.b not in ( -case when 13 not between 17 and b then f when t1.e+~+e between coalesce((select max(case 19 when e then 17 else coalesce((select coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.b not between t1.a and a)),e)*b*t1.f from t1 where t1.f>=t1.c),c) end) from t1 where e>b),t1.f) | f and f then c else 11 end,(c),t1.e)),19)-t1.c in (select t1.a from t1 union select e from t1))}
} {17}
do_test randexpr-2.457 {
  db eval {SELECT (a*f+c | ~b*(select cast(avg(19) AS integer) from t1)+17*(select max(a*b-d) from t1)+(abs((select count(distinct b) from t1))/abs(case when  -13*c between t1.f and t1.c then c when not 17 between 17 and 11 and 17<=((t1.c)) then c else a end*t1.c))-a*a)-c FROM t1 WHERE exists(select 1 from t1 where t1.e-11+t1.d*e+(abs(coalesce((select max(t1.b) from t1 where 19-13- -coalesce((select c*t1.e+t1.f*f from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (17<=d or  -11 in (select cast(avg(c) AS integer) from t1 union select +count(*) from t1))))),t1.b)<a),(t1.c)))/abs(t1.c))<=a or 13 between t1.e and  -t1.b)}
} {}
do_test randexpr-2.458 {
  db eval {SELECT (a*f+c | ~b*(select cast(avg(19) AS integer) from t1)+17*(select max(a*b-d) from t1)+(abs((select count(distinct b) from t1))/abs(case when  -13*c between t1.f and t1.c then c when not 17 between 17 and 11 and 17<=((t1.c)) then c else a end*t1.c))-a*a)-c FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e-11+t1.d*e+(abs(coalesce((select max(t1.b) from t1 where 19-13- -coalesce((select c*t1.e+t1.f*f from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (17<=d or  -11 in (select cast(avg(c) AS integer) from t1 union select +count(*) from t1))))),t1.b)<a),(t1.c)))/abs(t1.c))<=a or 13 between t1.e and  -t1.b))}
} {327281}
do_test randexpr-2.459 {
  db eval {SELECT (a*f+c & ~b*(select cast(avg(19) AS integer) from t1)+17*(select max(a*b-d) from t1)+(abs((select count(distinct b) from t1))/abs(case when  -13*c between t1.f and t1.c then c when not 17 between 17 and 11 and 17<=((t1.c)) then c else a end*t1.c))-a*a)-c FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e-11+t1.d*e+(abs(coalesce((select max(t1.b) from t1 where 19-13- -coalesce((select c*t1.e+t1.f*f from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (17<=d or  -11 in (select cast(avg(c) AS integer) from t1 union select +count(*) from t1))))),t1.b)<a),(t1.c)))/abs(t1.c))<=a or 13 between t1.e and  -t1.b))}
} {51800}
do_test randexpr-2.460 {
  db eval {SELECT coalesce((select max(case when not ((select ((count(distinct t1.f)*(cast(avg(e) AS integer)))-min(t1.d)*min(t1.c)) from t1)*(select min(t1.d) from t1) not in ((select count(distinct b) from t1),f*d,19) and  -a in (t1.d,b,a)) and d>=t1.c or t1.b>t1.c or 19 not between c and t1.e then 17 else t1.b end) from t1 where (e<=t1.b)),11) FROM t1 WHERE t1.a in (f,t1.d*+a,t1.c* -(select (abs(case +(max(coalesce((select max((select count(*)-cast(avg(b) AS integer) from t1)) from t1 where (c<c)),b)-t1.d))+max(c)*+count(distinct coalesce((select max((17)) from t1 where d in (select 11 from t1 union select 17 from t1)),t1.e))*count(*) when ~count(*) then cast(avg(d) AS integer) else max(t1.a) end*count(distinct c))) from t1))}
} {}
do_test randexpr-2.461 {
  db eval {SELECT coalesce((select max(case when not ((select ((count(distinct t1.f)*(cast(avg(e) AS integer)))-min(t1.d)*min(t1.c)) from t1)*(select min(t1.d) from t1) not in ((select count(distinct b) from t1),f*d,19) and  -a in (t1.d,b,a)) and d>=t1.c or t1.b>t1.c or 19 not between c and t1.e then 17 else t1.b end) from t1 where (e<=t1.b)),11) FROM t1 WHERE NOT (t1.a in (f,t1.d*+a,t1.c* -(select (abs(case +(max(coalesce((select max((select count(*)-cast(avg(b) AS integer) from t1)) from t1 where (c<c)),b)-t1.d))+max(c)*+count(distinct coalesce((select max((17)) from t1 where d in (select 11 from t1 union select 17 from t1)),t1.e))*count(*) when ~count(*) then cast(avg(d) AS integer) else max(t1.a) end*count(distinct c))) from t1)))}
} {11}
do_test randexpr-2.462 {
  db eval {SELECT (case case when +c>e then case t1.d when 13 then t1.c else 19 end-13 else t1.e+coalesce((select max(19) from t1 where case when e in (+b,coalesce((select a+(11) from t1 where b not between c and d or t1.b not in (a,11,17)),b),11) then 19 when (c) not in (t1.c,t1.b,d) then t1.c else t1.d end*f not between t1.a and d),13) end when c then 11 else c end) FROM t1 WHERE 19 not between coalesce((select max(d*t1.c) from t1 where (select cast(avg((b)) AS integer) from t1) in (select ( - -(abs(case max(b) when cast(avg( -13-11) AS integer) then count(distinct a-e) else ~ -cast(avg((c)) AS integer)-min(17)+count(*) end) | (min(e)))-min((19))) from t1 union select count(distinct 13) from t1)),case when  -e | 19 between  -11 and f then 19 else 19 end) and (f)}
} {}
do_test randexpr-2.463 {
  db eval {SELECT (case case when +c>e then case t1.d when 13 then t1.c else 19 end-13 else t1.e+coalesce((select max(19) from t1 where case when e in (+b,coalesce((select a+(11) from t1 where b not between c and d or t1.b not in (a,11,17)),b),11) then 19 when (c) not in (t1.c,t1.b,d) then t1.c else t1.d end*f not between t1.a and d),13) end when c then 11 else c end) FROM t1 WHERE NOT (19 not between coalesce((select max(d*t1.c) from t1 where (select cast(avg((b)) AS integer) from t1) in (select ( - -(abs(case max(b) when cast(avg( -13-11) AS integer) then count(distinct a-e) else ~ -cast(avg((c)) AS integer)-min(17)+count(*) end) | (min(e)))-min((19))) from t1 union select count(distinct 13) from t1)),case when  -e | 19 between  -11 and f then 19 else 19 end) and (f))}
} {300}
do_test randexpr-2.464 {
  db eval {SELECT (abs((select abs(case  -max(e)+max(t1.f)+(count(*)* -count(distinct case e when 19 then c else 13 end))*~min(t1.a) when cast(avg(t1.a) AS integer) then  -min(e) else  -count(*) end) from t1)*coalesce((select (t1.a) from t1 where case when c+t1.b-b | d in (select max(d) from t1 union select  -max(19) from t1) then t1.b else f end=t1.d),t1.b)*(t1.d) | e+t1.a)/abs(t1.d)) FROM t1 WHERE t1.f in (19,d*t1.d,(select min((select count(*)*min((17)+(abs(11)/abs(+~coalesce((select max(f) from t1 where 13 not between t1.c and t1.a),t1.e)-11))) from t1)) from t1)+17)}
} {}
do_test randexpr-2.465 {
  db eval {SELECT (abs((select abs(case  -max(e)+max(t1.f)+(count(*)* -count(distinct case e when 19 then c else 13 end))*~min(t1.a) when cast(avg(t1.a) AS integer) then  -min(e) else  -count(*) end) from t1)*coalesce((select (t1.a) from t1 where case when c+t1.b-b | d in (select max(d) from t1 union select  -max(19) from t1) then t1.b else f end=t1.d),t1.b)*(t1.d) | e+t1.a)/abs(t1.d)) FROM t1 WHERE NOT (t1.f in (19,d*t1.d,(select min((select count(*)*min((17)+(abs(11)/abs(+~coalesce((select max(f) from t1 where 13 not between t1.c and t1.a),t1.e)-11))) from t1)) from t1)+17))}
} {201}
do_test randexpr-2.466 {
  db eval {SELECT (abs((select abs(case  -max(e)+max(t1.f)+(count(*)* -count(distinct case e when 19 then c else 13 end))*~min(t1.a) when cast(avg(t1.a) AS integer) then  -min(e) else  -count(*) end) from t1)*coalesce((select (t1.a) from t1 where case when c+t1.b-b & d in (select max(d) from t1 union select  -max(19) from t1) then t1.b else f end=t1.d),t1.b)*(t1.d) & e+t1.a)/abs(t1.d)) FROM t1 WHERE NOT (t1.f in (19,d*t1.d,(select min((select count(*)*min((17)+(abs(11)/abs(+~coalesce((select max(f) from t1 where 13 not between t1.c and t1.a),t1.e)-11))) from t1)) from t1)+17))}
} {0}
do_test randexpr-2.467 {
  db eval {SELECT d+case when (coalesce((select max(t1.a) from t1 where t1.a not in (t1.d,f*(select count(distinct t1.d) from t1)+t1.f,c)),b)-c-17-t1.c)-case when 13*t1.a-19*e<>11 then f when t1.f not between 11 and t1.d then b else f end=t1.d then t1.f when not e>t1.f then 17 else b end FROM t1 WHERE exists(select 1 from t1 where 11* -d>=e) or t1.c<+ -e*11 or (17 not between t1.d and case t1.a when t1.a then t1.d+f-b else 11 end | t1.e)}
} {417}
do_test randexpr-2.468 {
  db eval {SELECT d+case when (coalesce((select max(t1.a) from t1 where t1.a not in (t1.d,f*(select count(distinct t1.d) from t1)+t1.f,c)),b)-c-17-t1.c)-case when 13*t1.a-19*e<>11 then f when t1.f not between 11 and t1.d then b else f end=t1.d then t1.f when not e>t1.f then 17 else b end FROM t1 WHERE NOT (exists(select 1 from t1 where 11* -d>=e) or t1.c<+ -e*11 or (17 not between t1.d and case t1.a when t1.a then t1.d+f-b else 11 end | t1.e))}
} {}
do_test randexpr-2.469 {
  db eval {SELECT t1.f-coalesce((select max(+e | b) from t1 where case when  -(abs(11)/abs(~(19 | t1.d)))-~c*e not in (19,b*t1.b,b) then 11 when f<=13 then d else t1.d end in (select (count(*))-cast(avg(11 | 17*t1.b) AS integer) from t1 union select count(distinct a-17) from t1)),t1.c)-c FROM t1 WHERE case when (t1.f*a<=11+d+coalesce((select max(19+19) from t1 where 13 in (select min(f)+cast(avg((abs(t1.e)/abs((select count(distinct c) from t1)))) AS integer)+(~cast(avg(e) AS integer))-min(c) from t1 union select count(*) from t1)),b)) then (a) else t1.b end-t1.b<=t1.b and 13 in (select t1.e from t1 union select t1.e from t1) and a<e}
} {}
do_test randexpr-2.470 {
  db eval {SELECT t1.f-coalesce((select max(+e | b) from t1 where case when  -(abs(11)/abs(~(19 | t1.d)))-~c*e not in (19,b*t1.b,b) then 11 when f<=13 then d else t1.d end in (select (count(*))-cast(avg(11 | 17*t1.b) AS integer) from t1 union select count(distinct a-17) from t1)),t1.c)-c FROM t1 WHERE NOT (case when (t1.f*a<=11+d+coalesce((select max(19+19) from t1 where 13 in (select min(f)+cast(avg((abs(t1.e)/abs((select count(distinct c) from t1)))) AS integer)+(~cast(avg(e) AS integer))-min(c) from t1 union select count(*) from t1)),b)) then (a) else t1.b end-t1.b<=t1.b and 13 in (select t1.e from t1 union select t1.e from t1) and a<e)}
} {0}
do_test randexpr-2.471 {
  db eval {SELECT t1.f-coalesce((select max(+e & b) from t1 where case when  -(abs(11)/abs(~(19 & t1.d)))-~c*e not in (19,b*t1.b,b) then 11 when f<=13 then d else t1.d end in (select (count(*))-cast(avg(11 & 17*t1.b) AS integer) from t1 union select count(distinct a-17) from t1)),t1.c)-c FROM t1 WHERE NOT (case when (t1.f*a<=11+d+coalesce((select max(19+19) from t1 where 13 in (select min(f)+cast(avg((abs(t1.e)/abs((select count(distinct c) from t1)))) AS integer)+(~cast(avg(e) AS integer))-min(c) from t1 union select count(*) from t1)),b)) then (a) else t1.b end-t1.b<=t1.b and 13 in (select t1.e from t1 union select t1.e from t1) and a<e)}
} {0}
do_test randexpr-2.472 {
  db eval {SELECT coalesce((select max(t1.c) from t1 where case when (t1.e*19*f-t1.b in (select cast(avg(d-~d) AS integer) from t1 union select +( -case +~count(*)*count(distinct (c)) when cast(avg(19) AS integer) then min(c) else count(distinct 17) end*cast(avg((13)) AS integer)-max(11)+(count(distinct b))) from t1)) then +11 else t1.b end>=t1.d or (exists(select 1 from t1 where (t1.e=t1.c)))),t1.c)-11 FROM t1 WHERE (not exists(select 1 from t1 where 11+t1.c-13>=t1.c or not exists(select 1 from t1 where a in (select b from t1 union select 19-d from t1) and ((abs(a+(abs(coalesce((select t1.d from t1 where exists(select 1 from t1 where case when t1.e>= -13 or  -e<>f then d when t1.c=13 then (b) else t1.c end not between 13 and b)),d))/abs(t1.d))-b)/abs(t1.a))<> -13 and exists(select 1 from t1 where 19<>e) or 13>=19))))}
} {}
do_test randexpr-2.473 {
  db eval {SELECT coalesce((select max(t1.c) from t1 where case when (t1.e*19*f-t1.b in (select cast(avg(d-~d) AS integer) from t1 union select +( -case +~count(*)*count(distinct (c)) when cast(avg(19) AS integer) then min(c) else count(distinct 17) end*cast(avg((13)) AS integer)-max(11)+(count(distinct b))) from t1)) then +11 else t1.b end>=t1.d or (exists(select 1 from t1 where (t1.e=t1.c)))),t1.c)-11 FROM t1 WHERE NOT ((not exists(select 1 from t1 where 11+t1.c-13>=t1.c or not exists(select 1 from t1 where a in (select b from t1 union select 19-d from t1) and ((abs(a+(abs(coalesce((select t1.d from t1 where exists(select 1 from t1 where case when t1.e>= -13 or  -e<>f then d when t1.c=13 then (b) else t1.c end not between 13 and b)),d))/abs(t1.d))-b)/abs(t1.a))<> -13 and exists(select 1 from t1 where 19<>e) or 13>=19)))))}
} {289}
do_test randexpr-2.474 {
  db eval {SELECT +coalesce((select max(11) from t1 where not case d+t1.c*coalesce((select max(coalesce((select d | e from t1 where 17 not between coalesce((select (t1.d) from t1 where t1.a between (select max(t1.b+d+t1.a) from t1)-t1.e and 17),t1.a) and 11),19)) from t1 where t1.d<t1.b),d)+t1.e when t1.f then t1.d else t1.f end not in (e,t1.c,t1.c)),c) | c FROM t1 WHERE exists(select 1 from t1 where c in (t1.a,(select count(distinct  -t1.d) from t1),t1.b)) or (~d=t1.e)}
} {}
do_test randexpr-2.475 {
  db eval {SELECT +coalesce((select max(11) from t1 where not case d+t1.c*coalesce((select max(coalesce((select d | e from t1 where 17 not between coalesce((select (t1.d) from t1 where t1.a between (select max(t1.b+d+t1.a) from t1)-t1.e and 17),t1.a) and 11),19)) from t1 where t1.d<t1.b),d)+t1.e when t1.f then t1.d else t1.f end not in (e,t1.c,t1.c)),c) | c FROM t1 WHERE NOT (exists(select 1 from t1 where c in (t1.a,(select count(distinct  -t1.d) from t1),t1.b)) or (~d=t1.e))}
} {300}
do_test randexpr-2.476 {
  db eval {SELECT +coalesce((select max(11) from t1 where not case d+t1.c*coalesce((select max(coalesce((select d & e from t1 where 17 not between coalesce((select (t1.d) from t1 where t1.a between (select max(t1.b+d+t1.a) from t1)-t1.e and 17),t1.a) and 11),19)) from t1 where t1.d<t1.b),d)+t1.e when t1.f then t1.d else t1.f end not in (e,t1.c,t1.c)),c) & c FROM t1 WHERE NOT (exists(select 1 from t1 where c in (t1.a,(select count(distinct  -t1.d) from t1),t1.b)) or (~d=t1.e))}
} {300}
do_test randexpr-2.477 {
  db eval {SELECT case when ((select  -min(e)+cast(avg(t1.a) AS integer) from t1)>t1.d*a) then (abs(~a)/abs(+11))*f when (c-(coalesce((select 11 from t1 where t1.d in (case when (19)+11>=c then 19 when e<>b then 13 else c end,a,13)),17))+13) not between 11 and t1.c then (t1.b) else 17 end+b FROM t1 WHERE a*b*11 in (select case when not coalesce((select max(~13 | (select abs((count(distinct t1.f))*cast(avg(t1.f) AS integer)+(max(t1.e))) from t1)) from t1 where coalesce((select max(11) from t1 where t1.b=19),b) in (f,11,19) and t1.f between a and t1.c or 19=t1.a and d=17 or c>=t1.f or t1.d<>t1.c),11)*c in (select f from t1 union select  -t1.b from t1) then t1.c when c not between f and 13 then e else  -e end from t1 union select e from t1)}
} {}
do_test randexpr-2.478 {
  db eval {SELECT case when ((select  -min(e)+cast(avg(t1.a) AS integer) from t1)>t1.d*a) then (abs(~a)/abs(+11))*f when (c-(coalesce((select 11 from t1 where t1.d in (case when (19)+11>=c then 19 when e<>b then 13 else c end,a,13)),17))+13) not between 11 and t1.c then (t1.b) else 17 end+b FROM t1 WHERE NOT (a*b*11 in (select case when not coalesce((select max(~13 | (select abs((count(distinct t1.f))*cast(avg(t1.f) AS integer)+(max(t1.e))) from t1)) from t1 where coalesce((select max(11) from t1 where t1.b=19),b) in (f,11,19) and t1.f between a and t1.c or 19=t1.a and d=17 or c>=t1.f or t1.d<>t1.c),11)*c in (select f from t1 union select  -t1.b from t1) then t1.c when c not between f and 13 then e else  -e end from t1 union select e from t1))}
} {217}
do_test randexpr-2.479 {
  db eval {SELECT t1.d-coalesce((select  -t1.c from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d<=case t1.d+e when case when d>19 then 11+t1.c else t1.b end-t1.f-t1.e then (abs(t1.d-19*t1.b)/abs(13+case when t1.f in (select count(*)-count(distinct t1.b) from t1 union select (max((t1.f))) from t1) then (((t1.d))) when t1.b not in (t1.d,13,a) then t1.d else 19 end*t1.c))-t1.d else e end))),13)+c*t1.a FROM t1 WHERE exists(select 1 from t1 where ~coalesce((select a+t1.a from t1 where ~(abs(c)/abs(17 | +13))-t1.f in (select f from t1 union select case when t1.b between 11*e and f then e when a in (e* -t1.f-f,coalesce((select 17 from t1 where t1.e in (select (cast(avg(e) AS integer)) from t1 union select max(b) from t1)),a),d) then t1.c else (f) end from t1)),f) between  -19 and (13) or t1.f<>t1.a)}
} {30700}
do_test randexpr-2.480 {
  db eval {SELECT t1.d-coalesce((select  -t1.c from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d<=case t1.d+e when case when d>19 then 11+t1.c else t1.b end-t1.f-t1.e then (abs(t1.d-19*t1.b)/abs(13+case when t1.f in (select count(*)-count(distinct t1.b) from t1 union select (max((t1.f))) from t1) then (((t1.d))) when t1.b not in (t1.d,13,a) then t1.d else 19 end*t1.c))-t1.d else e end))),13)+c*t1.a FROM t1 WHERE NOT (exists(select 1 from t1 where ~coalesce((select a+t1.a from t1 where ~(abs(c)/abs(17 | +13))-t1.f in (select f from t1 union select case when t1.b between 11*e and f then e when a in (e* -t1.f-f,coalesce((select 17 from t1 where t1.e in (select (cast(avg(e) AS integer)) from t1 union select max(b) from t1)),a),d) then t1.c else (f) end from t1)),f) between  -19 and (13) or t1.f<>t1.a))}
} {}
do_test randexpr-2.481 {
  db eval {SELECT (abs((abs(t1.b*t1.b*t1.f+a)/abs(t1.f))*t1.a-case  -(abs(coalesce((select (case when 11*19 in (select count(*) from t1 union select  -min(13)-(max(t1.a)) from t1) then 19 else  -17 end) from t1 where t1.e between 13 and (a)),t1.b)+d)/abs(t1.f))-t1.b-t1.c | d when  -t1.f then c else 17 end)/abs(13))-b*t1.d FROM t1 WHERE 13 in (t1.b,17*e+c*a,coalesce((select max(d) from t1 where +f+b not in (a,t1.a*~t1.c | t1.b-case when t1.a<=case when t1.f in (b,11,e) then d else t1.e end+f then 19 else (f) end-b*13- -t1.f-17,t1.c)),17))}
} {}
do_test randexpr-2.482 {
  db eval {SELECT (abs((abs(t1.b*t1.b*t1.f+a)/abs(t1.f))*t1.a-case  -(abs(coalesce((select (case when 11*19 in (select count(*) from t1 union select  -min(13)-(max(t1.a)) from t1) then 19 else  -17 end) from t1 where t1.e between 13 and (a)),t1.b)+d)/abs(t1.f))-t1.b-t1.c | d when  -t1.f then c else 17 end)/abs(13))-b*t1.d FROM t1 WHERE NOT (13 in (t1.b,17*e+c*a,coalesce((select max(d) from t1 where +f+b not in (a,t1.a*~t1.c | t1.b-case when t1.a<=case when t1.f in (b,11,e) then d else t1.e end+f then 19 else (f) end-b*13- -t1.f-17,t1.c)),17)))}
} {227691}
do_test randexpr-2.483 {
  db eval {SELECT (abs((abs(t1.b*t1.b*t1.f+a)/abs(t1.f))*t1.a-case  -(abs(coalesce((select (case when 11*19 in (select count(*) from t1 union select  -min(13)-(max(t1.a)) from t1) then 19 else  -17 end) from t1 where t1.e between 13 and (a)),t1.b)+d)/abs(t1.f))-t1.b-t1.c & d when  -t1.f then c else 17 end)/abs(13))-b*t1.d FROM t1 WHERE NOT (13 in (t1.b,17*e+c*a,coalesce((select max(d) from t1 where +f+b not in (a,t1.a*~t1.c | t1.b-case when t1.a<=case when t1.f in (b,11,e) then d else t1.e end+f then 19 else (f) end-b*13- -t1.f-17,t1.c)),17)))}
} {227691}
do_test randexpr-2.484 {
  db eval {SELECT coalesce((select t1.c*f from t1 where t1.f-+coalesce((select max(t1.d) from t1 where  - -t1.e in (select f from t1 union select t1.e from t1)),a)+case when 19 not in (t1.e,case when ~t1.a<>e+a then  -t1.d else t1.e end,f) then t1.b when  -(t1.e) in (e,(19),t1.c) then t1.f else e end+17*t1.c+d>b),t1.c)+a FROM t1 WHERE t1.b>=~b}
} {180100}
do_test randexpr-2.485 {
  db eval {SELECT coalesce((select t1.c*f from t1 where t1.f-+coalesce((select max(t1.d) from t1 where  - -t1.e in (select f from t1 union select t1.e from t1)),a)+case when 19 not in (t1.e,case when ~t1.a<>e+a then  -t1.d else t1.e end,f) then t1.b when  -(t1.e) in (e,(19),t1.c) then t1.f else e end+17*t1.c+d>b),t1.c)+a FROM t1 WHERE NOT (t1.b>=~b)}
} {}
do_test randexpr-2.486 {
  db eval {SELECT case case when case when 13 between coalesce((select max(t1.f) from t1 where b+f in (b+(coalesce((select t1.f from t1 where (t1.c)>=17 or 19 not in (11,t1.e,c)),13)),b,t1.e) and c<=e and not t1.b<>13 and 19 not between t1.c and a or c between f and f),t1.c) and b then t1.b when 13<>t1.a then 11 else d end in (select 13 from t1 union select 19 from t1) then t1.c when t1.f not in (17,b,b) then t1.f else e end when t1.e then t1.e else  -d end FROM t1 WHERE case when not exists(select 1 from t1 where t1.f not between coalesce((select coalesce((select max(+case t1.a when f then t1.a else t1.e end+case when t1.f>t1.d or 11 in (t1.e,11,b) then b else a end) from t1 where t1.f in (select a from t1 union select d from t1)),t1.d) from t1 where t1.a=b),(t1.c)) and d) then (select case max(t1.a) when ~min((11)) | min(e) then max(t1.e) else abs(max(t1.c)*count(distinct 19)) end from t1) else t1.b end<>b}
} {}
do_test randexpr-2.487 {
  db eval {SELECT case case when case when 13 between coalesce((select max(t1.f) from t1 where b+f in (b+(coalesce((select t1.f from t1 where (t1.c)>=17 or 19 not in (11,t1.e,c)),13)),b,t1.e) and c<=e and not t1.b<>13 and 19 not between t1.c and a or c between f and f),t1.c) and b then t1.b when 13<>t1.a then 11 else d end in (select 13 from t1 union select 19 from t1) then t1.c when t1.f not in (17,b,b) then t1.f else e end when t1.e then t1.e else  -d end FROM t1 WHERE NOT (case when not exists(select 1 from t1 where t1.f not between coalesce((select coalesce((select max(+case t1.a when f then t1.a else t1.e end+case when t1.f>t1.d or 11 in (t1.e,11,b) then b else a end) from t1 where t1.f in (select a from t1 union select d from t1)),t1.d) from t1 where t1.a=b),(t1.c)) and d) then (select case max(t1.a) when ~min((11)) | min(e) then max(t1.e) else abs(max(t1.c)*count(distinct 19)) end from t1) else t1.b end<>b)}
} {-400}
do_test randexpr-2.488 {
  db eval {SELECT case  -coalesce((select max(case when case when t1.e in (11*t1.e*17,(select (min(b) |  - -+cast(avg(17) AS integer)*max((t1.c))+cast(avg(t1.a) AS integer))+(( -(min(t1.c))))*count(*) from t1), -~b*t1.d+t1.d) then d else t1.a end<(t1.c) then t1.f else e end) from t1 where 13<>c),e)-(t1.b) when t1.a then 17 else t1.f end FROM t1 WHERE coalesce((select max(t1.e) from t1 where (not exists(select 1 from t1 where b<+c))),case when b | ~case t1.a when  -t1.b then  -t1.f else t1.f end*f+f in (select t1.b from t1 union select t1.c from t1) then  -(t1.f) when a<>11 then (d) else 11 end) in (select abs(~(abs(case (min(t1.b)*abs(count(distinct a)+count(*) |  -count(distinct a)))- -max(19) when max(t1.e) then min(d) else (max(a)) end))) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.489 {
  db eval {SELECT case  -coalesce((select max(case when case when t1.e in (11*t1.e*17,(select (min(b) |  - -+cast(avg(17) AS integer)*max((t1.c))+cast(avg(t1.a) AS integer))+(( -(min(t1.c))))*count(*) from t1), -~b*t1.d+t1.d) then d else t1.a end<(t1.c) then t1.f else e end) from t1 where 13<>c),e)-(t1.b) when t1.a then 17 else t1.f end FROM t1 WHERE NOT (coalesce((select max(t1.e) from t1 where (not exists(select 1 from t1 where b<+c))),case when b | ~case t1.a when  -t1.b then  -t1.f else t1.f end*f+f in (select t1.b from t1 union select t1.c from t1) then  -(t1.f) when a<>11 then (d) else 11 end) in (select abs(~(abs(case (min(t1.b)*abs(count(distinct a)+count(*) |  -count(distinct a)))- -max(19) when max(t1.e) then min(d) else (max(a)) end))) from t1 union select count(*) from t1))}
} {600}
do_test randexpr-2.490 {
  db eval {SELECT case  -coalesce((select max(case when case when t1.e in (11*t1.e*17,(select (min(b) &  - -+cast(avg(17) AS integer)*max((t1.c))+cast(avg(t1.a) AS integer))+(( -(min(t1.c))))*count(*) from t1), -~b*t1.d+t1.d) then d else t1.a end<(t1.c) then t1.f else e end) from t1 where 13<>c),e)-(t1.b) when t1.a then 17 else t1.f end FROM t1 WHERE NOT (coalesce((select max(t1.e) from t1 where (not exists(select 1 from t1 where b<+c))),case when b | ~case t1.a when  -t1.b then  -t1.f else t1.f end*f+f in (select t1.b from t1 union select t1.c from t1) then  -(t1.f) when a<>11 then (d) else 11 end) in (select abs(~(abs(case (min(t1.b)*abs(count(distinct a)+count(*) |  -count(distinct a)))- -max(19) when max(t1.e) then min(d) else (max(a)) end))) from t1 union select count(*) from t1))}
} {600}
do_test randexpr-2.491 {
  db eval {SELECT +case when case when ~t1.b<=case when ~17*19 | 11*11*f between t1.c and b then t1.a when e in (t1.a,t1.e,e) then t1.c else 19 end-t1.c-17+a then (t1.d) when 13 not between 13 and 19 then c else c end=(f) or d<t1.f then  -t1.f else t1.d end FROM t1 WHERE 19*++t1.e=coalesce((select case  -t1.f when case when d-t1.a*d*coalesce((select max(t1.d) from t1 where b-b> -coalesce((select t1.b from t1 where c*13+c<>t1.f),a)),t1.e)+t1.f=t1.f then  - - -f else b end then  -11 else  -d end from t1 where ( -t1.c<f)),t1.e)+19}
} {}
do_test randexpr-2.492 {
  db eval {SELECT +case when case when ~t1.b<=case when ~17*19 | 11*11*f between t1.c and b then t1.a when e in (t1.a,t1.e,e) then t1.c else 19 end-t1.c-17+a then (t1.d) when 13 not between 13 and 19 then c else c end=(f) or d<t1.f then  -t1.f else t1.d end FROM t1 WHERE NOT (19*++t1.e=coalesce((select case  -t1.f when case when d-t1.a*d*coalesce((select max(t1.d) from t1 where b-b> -coalesce((select t1.b from t1 where c*13+c<>t1.f),a)),t1.e)+t1.f=t1.f then  - - -f else b end then  -11 else  -d end from t1 where ( -t1.c<f)),t1.e)+19)}
} {-600}
do_test randexpr-2.493 {
  db eval {SELECT +case when case when ~t1.b<=case when ~17*19 & 11*11*f between t1.c and b then t1.a when e in (t1.a,t1.e,e) then t1.c else 19 end-t1.c-17+a then (t1.d) when 13 not between 13 and 19 then c else c end=(f) or d<t1.f then  -t1.f else t1.d end FROM t1 WHERE NOT (19*++t1.e=coalesce((select case  -t1.f when case when d-t1.a*d*coalesce((select max(t1.d) from t1 where b-b> -coalesce((select t1.b from t1 where c*13+c<>t1.f),a)),t1.e)+t1.f=t1.f then  - - -f else b end then  -11 else  -d end from t1 where ( -t1.c<f)),t1.e)+19)}
} {-600}
do_test randexpr-2.494 {
  db eval {SELECT case when case when 19 in (select abs(abs(count(distinct f))*~~~count(*)-abs(+abs(count(*))* -cast(avg(17) AS integer) | cast(avg(t1.d) AS integer))+count(distinct  -t1.a)+count(*)) from t1 union select  -cast(avg(19) AS integer) from t1) then b* -b-c else t1.e*c end=17 then d else coalesce((select  -11 from t1 where e<e),a)-c end+d*t1.a FROM t1 WHERE (a-t1.b+19<>case when b between ~11 and (abs(case when (coalesce((select max(+13) from t1 where not not exists(select 1 from t1 where t1.b+e in (b,t1.b,t1.d)) and 13 not in (d,f,17)),t1.a) not in (t1.f,17,17)) then coalesce((select max(19) from t1 where (17) in (t1.a,17,a)),t1.b) when b in (13,t1.a,b) then t1.c else d end)/abs(11)) then t1.f when t1.d>19 then d else d end)}
} {39800}
do_test randexpr-2.495 {
  db eval {SELECT case when case when 19 in (select abs(abs(count(distinct f))*~~~count(*)-abs(+abs(count(*))* -cast(avg(17) AS integer) | cast(avg(t1.d) AS integer))+count(distinct  -t1.a)+count(*)) from t1 union select  -cast(avg(19) AS integer) from t1) then b* -b-c else t1.e*c end=17 then d else coalesce((select  -11 from t1 where e<e),a)-c end+d*t1.a FROM t1 WHERE NOT ((a-t1.b+19<>case when b between ~11 and (abs(case when (coalesce((select max(+13) from t1 where not not exists(select 1 from t1 where t1.b+e in (b,t1.b,t1.d)) and 13 not in (d,f,17)),t1.a) not in (t1.f,17,17)) then coalesce((select max(19) from t1 where (17) in (t1.a,17,a)),t1.b) when b in (13,t1.a,b) then t1.c else d end)/abs(11)) then t1.f when t1.d>19 then d else d end))}
} {}
do_test randexpr-2.496 {
  db eval {SELECT case when case when 19 in (select abs(abs(count(distinct f))*~~~count(*)-abs(+abs(count(*))* -cast(avg(17) AS integer) & cast(avg(t1.d) AS integer))+count(distinct  -t1.a)+count(*)) from t1 union select  -cast(avg(19) AS integer) from t1) then b* -b-c else t1.e*c end=17 then d else coalesce((select  -11 from t1 where e<e),a)-c end+d*t1.a FROM t1 WHERE (a-t1.b+19<>case when b between ~11 and (abs(case when (coalesce((select max(+13) from t1 where not not exists(select 1 from t1 where t1.b+e in (b,t1.b,t1.d)) and 13 not in (d,f,17)),t1.a) not in (t1.f,17,17)) then coalesce((select max(19) from t1 where (17) in (t1.a,17,a)),t1.b) when b in (13,t1.a,b) then t1.c else d end)/abs(11)) then t1.f when t1.d>19 then d else d end)}
} {39800}
do_test randexpr-2.497 {
  db eval {SELECT t1.a-coalesce((select t1.e from t1 where not exists(select 1 from t1 where a in (select min(d-11) | cast(avg((select  -case count(*) when count(*) then +abs(+case ~min((abs(13- -a)/abs(t1.c))) when ~~count(*)+min((13)) then max(t1.e) else cast(avg(t1.a) AS integer) end | max(c))+count(*) else count(*) end*max(t1.d) from t1)) AS integer)+max(t1.c)*count(distinct f) from t1 union select  -count(*) from t1))),~17) FROM t1 WHERE case 11 when coalesce((select coalesce((select 19 from t1 where t1.b not between t1.e and e and not not exists(select 1 from t1 where (e in ((abs(c)/abs(17)),(d) | e,(select count(distinct t1.b) from t1)-b)))),case d when a then f else t1.c end) | (t1.d) | b from t1 where t1.c not in (t1.a,19,11)),t1.b)-d then t1.e else t1.d end*t1.d<>f}
} {-400}
do_test randexpr-2.498 {
  db eval {SELECT t1.a-coalesce((select t1.e from t1 where not exists(select 1 from t1 where a in (select min(d-11) | cast(avg((select  -case count(*) when count(*) then +abs(+case ~min((abs(13- -a)/abs(t1.c))) when ~~count(*)+min((13)) then max(t1.e) else cast(avg(t1.a) AS integer) end | max(c))+count(*) else count(*) end*max(t1.d) from t1)) AS integer)+max(t1.c)*count(distinct f) from t1 union select  -count(*) from t1))),~17) FROM t1 WHERE NOT (case 11 when coalesce((select coalesce((select 19 from t1 where t1.b not between t1.e and e and not not exists(select 1 from t1 where (e in ((abs(c)/abs(17)),(d) | e,(select count(distinct t1.b) from t1)-b)))),case d when a then f else t1.c end) | (t1.d) | b from t1 where t1.c not in (t1.a,19,11)),t1.b)-d then t1.e else t1.d end*t1.d<>f)}
} {}
do_test randexpr-2.499 {
  db eval {SELECT t1.a-coalesce((select t1.e from t1 where not exists(select 1 from t1 where a in (select min(d-11) & cast(avg((select  -case count(*) when count(*) then +abs(+case ~min((abs(13- -a)/abs(t1.c))) when ~~count(*)+min((13)) then max(t1.e) else cast(avg(t1.a) AS integer) end & max(c))+count(*) else count(*) end*max(t1.d) from t1)) AS integer)+max(t1.c)*count(distinct f) from t1 union select  -count(*) from t1))),~17) FROM t1 WHERE case 11 when coalesce((select coalesce((select 19 from t1 where t1.b not between t1.e and e and not not exists(select 1 from t1 where (e in ((abs(c)/abs(17)),(d) | e,(select count(distinct t1.b) from t1)-b)))),case d when a then f else t1.c end) | (t1.d) | b from t1 where t1.c not in (t1.a,19,11)),t1.b)-d then t1.e else t1.d end*t1.d<>f}
} {-400}
do_test randexpr-2.500 {
  db eval {SELECT case b*coalesce((select coalesce((select max(coalesce((select t1.b from t1 where t1.a<>11),17+~19)) from t1 where (t1.e<>e)),case 13 when 17 then 13 else c-coalesce((select max(case when (select min(d) from t1) in (select max(13) from t1 union select min(t1.f) from t1) then 13 else t1.a end*c) from t1 where t1.b<(t1.b)),f) end) from t1 where 19<=t1.e),(t1.b)) when t1.b then e else t1.d end+t1.c FROM t1 WHERE b+coalesce((select max((d)) from t1 where e=b),t1.c)*((select  -(min(coalesce((select 19+(abs((abs((t1.a)*case f when c then t1.b else t1.d end-e)/abs((t1.f))))/abs( -t1.e))+b from t1 where 13 not between d and t1.c),t1.f))) from t1))*case e when 19 then t1.d else t1.b end+t1.e not in (t1.d,t1.a,17)}
} {700}
do_test randexpr-2.501 {
  db eval {SELECT case b*coalesce((select coalesce((select max(coalesce((select t1.b from t1 where t1.a<>11),17+~19)) from t1 where (t1.e<>e)),case 13 when 17 then 13 else c-coalesce((select max(case when (select min(d) from t1) in (select max(13) from t1 union select min(t1.f) from t1) then 13 else t1.a end*c) from t1 where t1.b<(t1.b)),f) end) from t1 where 19<=t1.e),(t1.b)) when t1.b then e else t1.d end+t1.c FROM t1 WHERE NOT (b+coalesce((select max((d)) from t1 where e=b),t1.c)*((select  -(min(coalesce((select 19+(abs((abs((t1.a)*case f when c then t1.b else t1.d end-e)/abs((t1.f))))/abs( -t1.e))+b from t1 where 13 not between d and t1.c),t1.f))) from t1))*case e when 19 then t1.d else t1.b end+t1.e not in (t1.d,t1.a,17))}
} {}
do_test randexpr-2.502 {
  db eval {SELECT case when case when exists(select 1 from t1 where 17 in (select b from t1 union select 13 from t1)) and 19+a in (select count(distinct  -(select min(t1.a-f) from t1)) from t1 union select min(case when 11 between coalesce((select max(t1.b) from t1 where case when t1.d<>c or t1.b>=t1.a then ( -11) else t1.d end>=t1.a),t1.c) and  -17 then  -t1.f else e end) from t1) then a else 19 end+t1.e in (select e from t1 union select  -t1.b from t1) then t1.b when not (f) between f and t1.c then t1.e else e end FROM t1 WHERE 17>coalesce((select t1.b from t1 where t1.a+case when b in (19,t1.c,case t1.e when d-(b) then t1.f else 13 end) then 13 when d in (select count(distinct t1.a) from t1 union select case ~max(f) when cast(avg(b) AS integer) then max(d) else min(t1.f) end*min(e) from t1) or (t1.c<a) then t1.f else  -t1.c end<f or 13<=f),c) or 19>=t1.e}
} {}
do_test randexpr-2.503 {
  db eval {SELECT case when case when exists(select 1 from t1 where 17 in (select b from t1 union select 13 from t1)) and 19+a in (select count(distinct  -(select min(t1.a-f) from t1)) from t1 union select min(case when 11 between coalesce((select max(t1.b) from t1 where case when t1.d<>c or t1.b>=t1.a then ( -11) else t1.d end>=t1.a),t1.c) and  -17 then  -t1.f else e end) from t1) then a else 19 end+t1.e in (select e from t1 union select  -t1.b from t1) then t1.b when not (f) between f and t1.c then t1.e else e end FROM t1 WHERE NOT (17>coalesce((select t1.b from t1 where t1.a+case when b in (19,t1.c,case t1.e when d-(b) then t1.f else 13 end) then 13 when d in (select count(distinct t1.a) from t1 union select case ~max(f) when cast(avg(b) AS integer) then max(d) else min(t1.f) end*min(e) from t1) or (t1.c<a) then t1.f else  -t1.c end<f or 13<=f),c) or 19>=t1.e)}
} {500}
do_test randexpr-2.504 {
  db eval {SELECT c*(select (count(distinct (abs(case when t1.c<>e then e else 19 end)/abs(case when case when +case when a | t1.e+t1.e in (select  -count(*) from t1 union select (max(case when 11 not in (t1.f,11,f) then c when c not in (d,t1.f,t1.f) then  -t1.a else 13 end)) from t1) then 17 else 13 end>=t1.e then  -11 when (t1.f)>c then 11 else 11 end<=11 and not exists(select 1 from t1 where t1.a between t1.e and e) then 19 else (17) end)))) from t1) FROM t1 WHERE ((select  -case min(a-13*17+c*coalesce((select 19 from t1 where 19>=t1.d),(t1.b))+t1.e) when +(min(17)) then min(17) else +min(b) end* -cast(avg(19) AS integer)*count(*) from t1) not between a and d) and +c in (c,t1.d,d) or d<>t1.f}
} {300}
do_test randexpr-2.505 {
  db eval {SELECT c*(select (count(distinct (abs(case when t1.c<>e then e else 19 end)/abs(case when case when +case when a | t1.e+t1.e in (select  -count(*) from t1 union select (max(case when 11 not in (t1.f,11,f) then c when c not in (d,t1.f,t1.f) then  -t1.a else 13 end)) from t1) then 17 else 13 end>=t1.e then  -11 when (t1.f)>c then 11 else 11 end<=11 and not exists(select 1 from t1 where t1.a between t1.e and e) then 19 else (17) end)))) from t1) FROM t1 WHERE NOT (((select  -case min(a-13*17+c*coalesce((select 19 from t1 where 19>=t1.d),(t1.b))+t1.e) when +(min(17)) then min(17) else +min(b) end* -cast(avg(19) AS integer)*count(*) from t1) not between a and d) and +c in (c,t1.d,d) or d<>t1.f)}
} {}
do_test randexpr-2.506 {
  db eval {SELECT c*(select (count(distinct (abs(case when t1.c<>e then e else 19 end)/abs(case when case when +case when a & t1.e+t1.e in (select  -count(*) from t1 union select (max(case when 11 not in (t1.f,11,f) then c when c not in (d,t1.f,t1.f) then  -t1.a else 13 end)) from t1) then 17 else 13 end>=t1.e then  -11 when (t1.f)>c then 11 else 11 end<=11 and not exists(select 1 from t1 where t1.a between t1.e and e) then 19 else (17) end)))) from t1) FROM t1 WHERE ((select  -case min(a-13*17+c*coalesce((select 19 from t1 where 19>=t1.d),(t1.b))+t1.e) when +(min(17)) then min(17) else +min(b) end* -cast(avg(19) AS integer)*count(*) from t1) not between a and d) and +c in (c,t1.d,d) or d<>t1.f}
} {300}
do_test randexpr-2.507 {
  db eval {SELECT a*coalesce((select t1.d+17 from t1 where 13*case a when t1.a then 11 else  -t1.a-d-11-coalesce((select max(e-coalesce((select d from t1 where a<=t1.d*(coalesce((select max( -t1.d) from t1 where t1.f not in (11, -t1.d,17) and t1.a between (13) and c and e not in (t1.b,t1.b,b)),b))), -17)) from t1 where t1.b<>a),19)+t1.d+t1.c end<13),t1.e) FROM t1 WHERE t1.e not between f and 19}
} {50000}
do_test randexpr-2.508 {
  db eval {SELECT a*coalesce((select t1.d+17 from t1 where 13*case a when t1.a then 11 else  -t1.a-d-11-coalesce((select max(e-coalesce((select d from t1 where a<=t1.d*(coalesce((select max( -t1.d) from t1 where t1.f not in (11, -t1.d,17) and t1.a between (13) and c and e not in (t1.b,t1.b,b)),b))), -17)) from t1 where t1.b<>a),19)+t1.d+t1.c end<13),t1.e) FROM t1 WHERE NOT (t1.e not between f and 19)}
} {}
do_test randexpr-2.509 {
  db eval {SELECT 17 | case case when exists(select 1 from t1 where (not t1.d between a and f)) then t1.e when not (b=coalesce((select ~t1.c-case when (select (count(*))*(count(distinct t1.f)) from t1)>=11 then b else 19 end from t1 where not not (13<=e) and t1.b=t1.b),13)) then coalesce((select max((abs(11)/abs(t1.b))) from t1 where t1.a not between t1.e and t1.b),(t1.a)) else t1.a end when c then 13 else 19 end+b FROM t1 WHERE ~t1.a+t1.d+c*17 | (select max(t1.d)*abs(case (max(t1.f)+count(distinct t1.b))*(count(distinct f)) when count(distinct e) then  -min(t1.e) else min(t1.f) end)+max(b)+count(distinct t1.d) from t1) in (select max(t1.d*(19)) from t1 union select count(distinct case when t1.c+b in (select max(e) from t1 union select cast(avg(f) AS integer) from t1) then (17) when e not in (c,d,19) or 11=19 then (19) else t1.e end+t1.a) from t1)}
} {}
do_test randexpr-2.510 {
  db eval {SELECT 17 | case case when exists(select 1 from t1 where (not t1.d between a and f)) then t1.e when not (b=coalesce((select ~t1.c-case when (select (count(*))*(count(distinct t1.f)) from t1)>=11 then b else 19 end from t1 where not not (13<=e) and t1.b=t1.b),13)) then coalesce((select max((abs(11)/abs(t1.b))) from t1 where t1.a not between t1.e and t1.b),(t1.a)) else t1.a end when c then 13 else 19 end+b FROM t1 WHERE NOT (~t1.a+t1.d+c*17 | (select max(t1.d)*abs(case (max(t1.f)+count(distinct t1.b))*(count(distinct f)) when count(distinct e) then  -min(t1.e) else min(t1.f) end)+max(b)+count(distinct t1.d) from t1) in (select max(t1.d*(19)) from t1 union select count(distinct case when t1.c+b in (select max(e) from t1 union select cast(avg(f) AS integer) from t1) then (17) when e not in (c,d,19) or 11=19 then (19) else t1.e end+t1.a) from t1))}
} {219}
do_test randexpr-2.511 {
  db eval {SELECT 17 & case case when exists(select 1 from t1 where (not t1.d between a and f)) then t1.e when not (b=coalesce((select ~t1.c-case when (select (count(*))*(count(distinct t1.f)) from t1)>=11 then b else 19 end from t1 where not not (13<=e) and t1.b=t1.b),13)) then coalesce((select max((abs(11)/abs(t1.b))) from t1 where t1.a not between t1.e and t1.b),(t1.a)) else t1.a end when c then 13 else 19 end+b FROM t1 WHERE NOT (~t1.a+t1.d+c*17 | (select max(t1.d)*abs(case (max(t1.f)+count(distinct t1.b))*(count(distinct f)) when count(distinct e) then  -min(t1.e) else min(t1.f) end)+max(b)+count(distinct t1.d) from t1) in (select max(t1.d*(19)) from t1 union select count(distinct case when t1.c+b in (select max(e) from t1 union select cast(avg(f) AS integer) from t1) then (17) when e not in (c,d,19) or 11=19 then (19) else t1.e end+t1.a) from t1))}
} {17}
do_test randexpr-2.512 {
  db eval {SELECT case when coalesce((select max((+t1.a+17+11+case when (abs(19)/abs(t1.a)) in (select ~(case count(*) when min( -c) then count(distinct b) else count(*) end) from t1 union select  -min(t1.e) from t1) or 13>=t1.a then case c when 13 then t1.d else e end when  -t1.e<=t1.a then t1.c else t1.c end)) from t1 where not t1.c= -t1.f),b)=f and t1.e<=(t1.f) then ~(t1.a) when 17=e then 19 else t1.b end FROM t1 WHERE case when  -t1.f in (select (13) from t1 union select coalesce((select max(coalesce((select (~13) from t1 where t1.b>(11)),e*t1.c)) from t1 where (not (abs(t1.c)/abs(a))>=c)),t1.d) from t1) then  -t1.e+ -a-coalesce((select t1.d from t1 where not exists(select 1 from t1 where  -b=t1.f-f)),t1.c)*17 when 19<=11 then 19 else t1.d end>=b}
} {200}
do_test randexpr-2.513 {
  db eval {SELECT case when coalesce((select max((+t1.a+17+11+case when (abs(19)/abs(t1.a)) in (select ~(case count(*) when min( -c) then count(distinct b) else count(*) end) from t1 union select  -min(t1.e) from t1) or 13>=t1.a then case c when 13 then t1.d else e end when  -t1.e<=t1.a then t1.c else t1.c end)) from t1 where not t1.c= -t1.f),b)=f and t1.e<=(t1.f) then ~(t1.a) when 17=e then 19 else t1.b end FROM t1 WHERE NOT (case when  -t1.f in (select (13) from t1 union select coalesce((select max(coalesce((select (~13) from t1 where t1.b>(11)),e*t1.c)) from t1 where (not (abs(t1.c)/abs(a))>=c)),t1.d) from t1) then  -t1.e+ -a-coalesce((select t1.d from t1 where not exists(select 1 from t1 where  -b=t1.f-f)),t1.c)*17 when 19<=11 then 19 else t1.d end>=b)}
} {}
do_test randexpr-2.514 {
  db eval {SELECT +(case when t1.a<=a then t1.d when ((abs(t1.a)/abs((coalesce((select t1.e from t1 where t1.f>=t1.c),e))))) between coalesce((select case when not 19> -11 then (case when t1.d in (select e from t1 union select f from t1) then  -d when t1.b not between 11 and t1.d then (19) else c end) else t1.e end from t1 where not exists(select 1 from t1 where e not in (t1.d,a, -a)) and t1.d>t1.b),a) and t1.a then d else b end)-17 FROM t1 WHERE (+e*t1.d in (select (+abs(abs(min(~+b)-min(a)-case  -case abs(max(t1.c)) when max(e) then count(*) else count(distinct 19) end- -max(t1.a) when count(distinct t1.a) then (count(*)) else min(t1.f) end)))-(count(*)) from t1 union select max(t1.f) from t1) or ~c*case when not exists(select 1 from t1 where t1.f in (t1.f,t1.a,d)) then t1.c when t1.c<t1.d then (17) else e end+t1.b |  -((c)) not between a and 17)}
} {383}
do_test randexpr-2.515 {
  db eval {SELECT +(case when t1.a<=a then t1.d when ((abs(t1.a)/abs((coalesce((select t1.e from t1 where t1.f>=t1.c),e))))) between coalesce((select case when not 19> -11 then (case when t1.d in (select e from t1 union select f from t1) then  -d when t1.b not between 11 and t1.d then (19) else c end) else t1.e end from t1 where not exists(select 1 from t1 where e not in (t1.d,a, -a)) and t1.d>t1.b),a) and t1.a then d else b end)-17 FROM t1 WHERE NOT ((+e*t1.d in (select (+abs(abs(min(~+b)-min(a)-case  -case abs(max(t1.c)) when max(e) then count(*) else count(distinct 19) end- -max(t1.a) when count(distinct t1.a) then (count(*)) else min(t1.f) end)))-(count(*)) from t1 union select max(t1.f) from t1) or ~c*case when not exists(select 1 from t1 where t1.f in (t1.f,t1.a,d)) then t1.c when t1.c<t1.d then (17) else e end+t1.b |  -((c)) not between a and 17))}
} {}
do_test randexpr-2.516 {
  db eval {SELECT  -case when coalesce((select max(case when ~(+case when t1.b*t1.b>t1.e then t1.a when  -d=t1.e or t1.c not between t1.c and e then c else t1.d end)- -17 in (select a from t1 union select  -t1.e from t1) then 19 else a end) from t1 where t1.a in (select  -a from t1 union select 19 from t1)),t1.a)<>t1.d then 13 when a in (19,d,c) and a<11 then t1.a else b end+t1.a-t1.b FROM t1 WHERE c>=t1.e}
} {}
do_test randexpr-2.517 {
  db eval {SELECT  -case when coalesce((select max(case when ~(+case when t1.b*t1.b>t1.e then t1.a when  -d=t1.e or t1.c not between t1.c and e then c else t1.d end)- -17 in (select a from t1 union select  -t1.e from t1) then 19 else a end) from t1 where t1.a in (select  -a from t1 union select 19 from t1)),t1.a)<>t1.d then 13 when a in (19,d,c) and a<11 then t1.a else b end+t1.a-t1.b FROM t1 WHERE NOT (c>=t1.e)}
} {-113}
do_test randexpr-2.518 {
  db eval {SELECT coalesce((select case coalesce((select max(19) from t1 where +case when exists(select 1 from t1 where not exists(select 1 from t1 where not c in (case when e>=c then b else t1.b end,t1.b,t1.e))) then a-f+13-t1.f+19 when f>=t1.e then t1.e else t1.c end+17 in (select count(distinct 19) from t1 union select cast(avg(b) AS integer) | count(distinct 11)-count(*) from t1)),a) when b then 17 else c end from t1 where t1.f<=t1.e),t1.e) FROM t1 WHERE ~~+d-d*19*case ~(select count(*) from t1)-11 when 19 then  -+(abs(t1.a)/abs(a)) | (f)-(abs(+t1.c)/abs((select ~+max(13*e)+min(f)*count(distinct 13) from t1)))*t1.a else  -t1.f-t1.b end*t1.a not between  -e and t1.e}
} {500}
do_test randexpr-2.519 {
  db eval {SELECT coalesce((select case coalesce((select max(19) from t1 where +case when exists(select 1 from t1 where not exists(select 1 from t1 where not c in (case when e>=c then b else t1.b end,t1.b,t1.e))) then a-f+13-t1.f+19 when f>=t1.e then t1.e else t1.c end+17 in (select count(distinct 19) from t1 union select cast(avg(b) AS integer) | count(distinct 11)-count(*) from t1)),a) when b then 17 else c end from t1 where t1.f<=t1.e),t1.e) FROM t1 WHERE NOT (~~+d-d*19*case ~(select count(*) from t1)-11 when 19 then  -+(abs(t1.a)/abs(a)) | (f)-(abs(+t1.c)/abs((select ~+max(13*e)+min(f)*count(distinct 13) from t1)))*t1.a else  -t1.f-t1.b end*t1.a not between  -e and t1.e)}
} {}
do_test randexpr-2.520 {
  db eval {SELECT coalesce((select case coalesce((select max(19) from t1 where +case when exists(select 1 from t1 where not exists(select 1 from t1 where not c in (case when e>=c then b else t1.b end,t1.b,t1.e))) then a-f+13-t1.f+19 when f>=t1.e then t1.e else t1.c end+17 in (select count(distinct 19) from t1 union select cast(avg(b) AS integer) & count(distinct 11)-count(*) from t1)),a) when b then 17 else c end from t1 where t1.f<=t1.e),t1.e) FROM t1 WHERE ~~+d-d*19*case ~(select count(*) from t1)-11 when 19 then  -+(abs(t1.a)/abs(a)) | (f)-(abs(+t1.c)/abs((select ~+max(13*e)+min(f)*count(distinct 13) from t1)))*t1.a else  -t1.f-t1.b end*t1.a not between  -e and t1.e}
} {500}
do_test randexpr-2.521 {
  db eval {SELECT a*17+ -case when not exists(select 1 from t1 where 11=t1.d) then 11-b when case when t1.c<>t1.c++t1.a or t1.c*t1.a+d-f between 19 and case when not t1.e>=11 and t1.b<=t1.c then coalesce((select max(a) from t1 where 19=11),f) when f not in (t1.b,13,b) then f else  -d end then d else t1.c end in (select 17 from t1 union select d from t1) then 17 else b end FROM t1 WHERE  -(+~ -d++c+b)>=t1.a-case when coalesce((select t1.a-(select max(t1.e) from t1)-(abs(11)/abs(17))+t1.d from t1 where not (not exists(select 1 from t1 where c=t1.c)) or t1.b in (select abs(max(11)+count(*)) from t1 union select ((max(a))) from t1)),f)>=a then t1.f when d not in (11,c,17) then a else 19 end}
} {}
do_test randexpr-2.522 {
  db eval {SELECT a*17+ -case when not exists(select 1 from t1 where 11=t1.d) then 11-b when case when t1.c<>t1.c++t1.a or t1.c*t1.a+d-f between 19 and case when not t1.e>=11 and t1.b<=t1.c then coalesce((select max(a) from t1 where 19=11),f) when f not in (t1.b,13,b) then f else  -d end then d else t1.c end in (select 17 from t1 union select d from t1) then 17 else b end FROM t1 WHERE NOT ( -(+~ -d++c+b)>=t1.a-case when coalesce((select t1.a-(select max(t1.e) from t1)-(abs(11)/abs(17))+t1.d from t1 where not (not exists(select 1 from t1 where c=t1.c)) or t1.b in (select abs(max(11)+count(*)) from t1 union select ((max(a))) from t1)),f)>=a then t1.f when d not in (11,c,17) then a else 19 end)}
} {1889}
do_test randexpr-2.523 {
  db eval {SELECT coalesce((select max(t1.b+a) from t1 where case (select count(distinct b*case when t1.f*+~a | b+17*13+a+11 in (select c from t1 union select d from t1) then t1.f else t1.b end) from t1) when t1.a then f else t1.c end+ -f between 17 and d and b in (13,t1.e,t1.e) and d not between t1.f and d),13) FROM t1 WHERE coalesce((select max(t1.d) from t1 where (coalesce((select ~t1.c from t1 where  -t1.a<=c*+d or not (case when (t1.b)>=t1.d then t1.e when 17<d then (a) else 11 end>a and a<>e and t1.e<t1.e) or 19<=t1.c),(c))+b*t1.c+17*t1.a | 11+(t1.f)>=19)),19)<>t1.c}
} {13}
do_test randexpr-2.524 {
  db eval {SELECT coalesce((select max(t1.b+a) from t1 where case (select count(distinct b*case when t1.f*+~a | b+17*13+a+11 in (select c from t1 union select d from t1) then t1.f else t1.b end) from t1) when t1.a then f else t1.c end+ -f between 17 and d and b in (13,t1.e,t1.e) and d not between t1.f and d),13) FROM t1 WHERE NOT (coalesce((select max(t1.d) from t1 where (coalesce((select ~t1.c from t1 where  -t1.a<=c*+d or not (case when (t1.b)>=t1.d then t1.e when 17<d then (a) else 11 end>a and a<>e and t1.e<t1.e) or 19<=t1.c),(c))+b*t1.c+17*t1.a | 11+(t1.f)>=19)),19)<>t1.c)}
} {}
do_test randexpr-2.525 {
  db eval {SELECT coalesce((select max(t1.b+a) from t1 where case (select count(distinct b*case when t1.f*+~a & b+17*13+a+11 in (select c from t1 union select d from t1) then t1.f else t1.b end) from t1) when t1.a then f else t1.c end+ -f between 17 and d and b in (13,t1.e,t1.e) and d not between t1.f and d),13) FROM t1 WHERE coalesce((select max(t1.d) from t1 where (coalesce((select ~t1.c from t1 where  -t1.a<=c*+d or not (case when (t1.b)>=t1.d then t1.e when 17<d then (a) else 11 end>a and a<>e and t1.e<t1.e) or 19<=t1.c),(c))+b*t1.c+17*t1.a | 11+(t1.f)>=19)),19)<>t1.c}
} {13}
do_test randexpr-2.526 {
  db eval {SELECT coalesce((select (t1.b-(abs(t1.b-~17 | 13+13)/abs(t1.e))* -t1.a- -19+t1.d) from t1 where exists(select 1 from t1 where 19 in (select t1.a from t1 union select  -19 from t1) and a in (c,e,13) and 19 in (select t1.a from t1 union select b from t1) or 13 in (select 19 from t1 union select d from t1) and not t1.c=t1.f or ( -t1.d between e and 19) or  -((17))<>c)),e) FROM t1 WHERE ((abs(a)/abs(f-a)) between  -(abs(++t1.b)/abs(13)) and t1.c)}
} {619}
do_test randexpr-2.527 {
  db eval {SELECT coalesce((select (t1.b-(abs(t1.b-~17 | 13+13)/abs(t1.e))* -t1.a- -19+t1.d) from t1 where exists(select 1 from t1 where 19 in (select t1.a from t1 union select  -19 from t1) and a in (c,e,13) and 19 in (select t1.a from t1 union select b from t1) or 13 in (select 19 from t1 union select d from t1) and not t1.c=t1.f or ( -t1.d between e and 19) or  -((17))<>c)),e) FROM t1 WHERE NOT (((abs(a)/abs(f-a)) between  -(abs(++t1.b)/abs(13)) and t1.c))}
} {}
do_test randexpr-2.528 {
  db eval {SELECT coalesce((select (t1.b-(abs(t1.b-~17 & 13+13)/abs(t1.e))* -t1.a- -19+t1.d) from t1 where exists(select 1 from t1 where 19 in (select t1.a from t1 union select  -19 from t1) and a in (c,e,13) and 19 in (select t1.a from t1 union select b from t1) or 13 in (select 19 from t1 union select d from t1) and not t1.c=t1.f or ( -t1.d between e and 19) or  -((17))<>c)),e) FROM t1 WHERE ((abs(a)/abs(f-a)) between  -(abs(++t1.b)/abs(13)) and t1.c)}
} {619}
do_test randexpr-2.529 {
  db eval {SELECT case when coalesce((select max(c- -b-t1.c) from t1 where t1.d between 11 and case when b | ~t1.e*(t1.f)>t1.f then a when (19<13) and not exists(select 1 from t1 where f not in (t1.a,((b)),17)) or d in ((a),t1.c,19) or (f)>13 then t1.e else f end*t1.a),t1.a)>=e then t1.d when t1.e>=c then 13 else f end FROM t1 WHERE +11 between case when t1.f>t1.c then t1.b else t1.b end and ((select count(distinct case when t1.a between (abs(coalesce((select t1.b from t1 where case when t1.d<=(abs((c))/abs(coalesce((select max(17) from t1 where 11=b),13))) then 17 when b=t1.e then d else e end-13>=(e)), -d))/abs(b)) and b then t1.d when (b) in (13,t1.b,t1.a) then f else 19 end) from t1))-d}
} {}
do_test randexpr-2.530 {
  db eval {SELECT case when coalesce((select max(c- -b-t1.c) from t1 where t1.d between 11 and case when b | ~t1.e*(t1.f)>t1.f then a when (19<13) and not exists(select 1 from t1 where f not in (t1.a,((b)),17)) or d in ((a),t1.c,19) or (f)>13 then t1.e else f end*t1.a),t1.a)>=e then t1.d when t1.e>=c then 13 else f end FROM t1 WHERE NOT (+11 between case when t1.f>t1.c then t1.b else t1.b end and ((select count(distinct case when t1.a between (abs(coalesce((select t1.b from t1 where case when t1.d<=(abs((c))/abs(coalesce((select max(17) from t1 where 11=b),13))) then 17 when b=t1.e then d else e end-13>=(e)), -d))/abs(b)) and b then t1.d when (b) in (13,t1.b,t1.a) then f else 19 end) from t1))-d)}
} {13}
do_test randexpr-2.531 {
  db eval {SELECT case when coalesce((select max(c- -b-t1.c) from t1 where t1.d between 11 and case when b & ~t1.e*(t1.f)>t1.f then a when (19<13) and not exists(select 1 from t1 where f not in (t1.a,((b)),17)) or d in ((a),t1.c,19) or (f)>13 then t1.e else f end*t1.a),t1.a)>=e then t1.d when t1.e>=c then 13 else f end FROM t1 WHERE NOT (+11 between case when t1.f>t1.c then t1.b else t1.b end and ((select count(distinct case when t1.a between (abs(coalesce((select t1.b from t1 where case when t1.d<=(abs((c))/abs(coalesce((select max(17) from t1 where 11=b),13))) then 17 when b=t1.e then d else e end-13>=(e)), -d))/abs(b)) and b then t1.d when (b) in (13,t1.b,t1.a) then f else 19 end) from t1))-d)}
} {13}
do_test randexpr-2.532 {
  db eval {SELECT (select ~abs(max(case when (case when ( -t1.a>e) then t1.a else (select (~count(*) | max(case when t1.d<>c then  -+13 else case when b between 19 and 17 or (t1.a)>=13 then 19 else t1.c end end)) from t1) end<>t1.e) then 19 when c*e+t1.b<=19 then f else (t1.d) end | b)) from t1)+c FROM t1 WHERE f | t1.a+b>=t1.d}
} {80}
do_test randexpr-2.533 {
  db eval {SELECT (select ~abs(max(case when (case when ( -t1.a>e) then t1.a else (select (~count(*) | max(case when t1.d<>c then  -+13 else case when b between 19 and 17 or (t1.a)>=13 then 19 else t1.c end end)) from t1) end<>t1.e) then 19 when c*e+t1.b<=19 then f else (t1.d) end | b)) from t1)+c FROM t1 WHERE NOT (f | t1.a+b>=t1.d)}
} {}
do_test randexpr-2.534 {
  db eval {SELECT (select ~abs(max(case when (case when ( -t1.a>e) then t1.a else (select (~count(*) & max(case when t1.d<>c then  -+13 else case when b between 19 and 17 or (t1.a)>=13 then 19 else t1.c end end)) from t1) end<>t1.e) then 19 when c*e+t1.b<=19 then f else (t1.d) end & b)) from t1)+c FROM t1 WHERE f | t1.a+b>=t1.d}
} {299}
do_test randexpr-2.535 {
  db eval {SELECT  -case when ~case t1.f+13+t1.a when coalesce((select max(17) from t1 where coalesce((select max(( -11)) from t1 where not exists(select 1 from t1 where case case when not exists(select 1 from t1 where (a in (select f from t1 union select b from t1))) then d when (a) in (f,t1.a, -f) then t1.a else b end when t1.d then c else t1.b end<>a and 11= -t1.a and 19=a)),11) in (select c from t1 union select 17 from t1)),t1.c) then e else 11 end=t1.d then 17 else 17 end FROM t1 WHERE not exists(select 1 from t1 where f<d or exists(select 1 from t1 where ~t1.a not between coalesce((select max(case b+(select  -case max(t1.b)- -count(distinct c)*max(t1.b) when min(17) then (count(*)) else cast(avg(t1.d) AS integer) end*max(f) from t1)+case when (abs((abs(19)/abs(e)))/abs(t1.d))*t1.a not between b and 13 then e else (e) end when d then b else 17 end) from t1 where t1.c between b and t1.f),t1.b) and a))}
} {}
do_test randexpr-2.536 {
  db eval {SELECT  -case when ~case t1.f+13+t1.a when coalesce((select max(17) from t1 where coalesce((select max(( -11)) from t1 where not exists(select 1 from t1 where case case when not exists(select 1 from t1 where (a in (select f from t1 union select b from t1))) then d when (a) in (f,t1.a, -f) then t1.a else b end when t1.d then c else t1.b end<>a and 11= -t1.a and 19=a)),11) in (select c from t1 union select 17 from t1)),t1.c) then e else 11 end=t1.d then 17 else 17 end FROM t1 WHERE NOT (not exists(select 1 from t1 where f<d or exists(select 1 from t1 where ~t1.a not between coalesce((select max(case b+(select  -case max(t1.b)- -count(distinct c)*max(t1.b) when min(17) then (count(*)) else cast(avg(t1.d) AS integer) end*max(f) from t1)+case when (abs((abs(19)/abs(e)))/abs(t1.d))*t1.a not between b and 13 then e else (e) end when d then b else 17 end) from t1 where t1.c between b and t1.f),t1.b) and a)))}
} {-17}
do_test randexpr-2.537 {
  db eval {SELECT t1.f-t1.b | coalesce((select max((select max(case  -case when t1.f>coalesce((select max(case when (17> -t1.e) then f when 19=t1.a then t1.a else a end) from t1 where t1.c<=t1.e or (t1.d)>=t1.d),t1.a)+a then f when b not in (e,t1.e,t1.b) or t1.f not in (f,t1.c, -d) or e<=13 then f else (17) end-t1.d+t1.f*13 when (t1.c) then b else  -t1.e end) from t1)) from t1 where t1.b in (t1.b,t1.f,(t1.e))),t1.e)*(a) FROM t1 WHERE t1.f<=a}
} {}
do_test randexpr-2.538 {
  db eval {SELECT t1.f-t1.b | coalesce((select max((select max(case  -case when t1.f>coalesce((select max(case when (17> -t1.e) then f when 19=t1.a then t1.a else a end) from t1 where t1.c<=t1.e or (t1.d)>=t1.d),t1.a)+a then f when b not in (e,t1.e,t1.b) or t1.f not in (f,t1.c, -d) or e<=13 then f else (17) end-t1.d+t1.f*13 when (t1.c) then b else  -t1.e end) from t1)) from t1 where t1.b in (t1.b,t1.f,(t1.e))),t1.e)*(a) FROM t1 WHERE NOT (t1.f<=a)}
} {-49744}
do_test randexpr-2.539 {
  db eval {SELECT t1.f-t1.b & coalesce((select max((select max(case  -case when t1.f>coalesce((select max(case when (17> -t1.e) then f when 19=t1.a then t1.a else a end) from t1 where t1.c<=t1.e or (t1.d)>=t1.d),t1.a)+a then f when b not in (e,t1.e,t1.b) or t1.f not in (f,t1.c, -d) or e<=13 then f else (17) end-t1.d+t1.f*13 when (t1.c) then b else  -t1.e end) from t1)) from t1 where t1.b in (t1.b,t1.f,(t1.e))),t1.e)*(a) FROM t1 WHERE NOT (t1.f<=a)}
} {144}
do_test randexpr-2.540 {
  db eval {SELECT t1.e+t1.a*case when not t1.f<=d-(c)*13 then t1.e+13*(abs(case when exists(select 1 from t1 where (select  -count(*)* -max(t1.a) | ((((cast(avg((e)) AS integer))))) from t1)>=+c+b) then +11 when t1.a not between t1.c and c then t1.b else  -19 end)/abs(b)) | (19) when not exists(select 1 from t1 where t1.c between t1.e and t1.c) then d else t1.f end FROM t1 WHERE b in (+c,case b when f*~19-t1.b*t1.f then t1.f else a end,a | t1.a)}
} {}
do_test randexpr-2.541 {
  db eval {SELECT t1.e+t1.a*case when not t1.f<=d-(c)*13 then t1.e+13*(abs(case when exists(select 1 from t1 where (select  -count(*)* -max(t1.a) | ((((cast(avg((e)) AS integer))))) from t1)>=+c+b) then +11 when t1.a not between t1.c and c then t1.b else  -19 end)/abs(b)) | (19) when not exists(select 1 from t1 where t1.c between t1.e and t1.c) then d else t1.f end FROM t1 WHERE NOT (b in (+c,case b when f*~19-t1.b*t1.f then t1.f else a end,a | t1.a))}
} {50800}
do_test randexpr-2.542 {
  db eval {SELECT t1.e+t1.a*case when not t1.f<=d-(c)*13 then t1.e+13*(abs(case when exists(select 1 from t1 where (select  -count(*)* -max(t1.a) & ((((cast(avg((e)) AS integer))))) from t1)>=+c+b) then +11 when t1.a not between t1.c and c then t1.b else  -19 end)/abs(b)) & (19) when not exists(select 1 from t1 where t1.c between t1.e and t1.c) then d else t1.f end FROM t1 WHERE NOT (b in (+c,case b when f*~19-t1.b*t1.f then t1.f else a end,a | t1.a))}
} {600}
do_test randexpr-2.543 {
  db eval {SELECT t1.e++a-c-a+coalesce((select t1.e from t1 where 11=case when t1.f not between 13 and t1.b+a*t1.c then 17 when (select min((select cast(avg(17) AS integer)*max(d)-(cast(avg(c) AS integer))*count(distinct t1.b) from t1)) from t1)>=case coalesce((select t1.b | e from t1 where t1.d in (t1.c,17,t1.c)),a) when 13 then t1.a else 19 end then t1.a else e end),t1.d) FROM t1 WHERE +t1.a*t1.c between case when case coalesce((select max(+t1.f-t1.b*(select min((b))+count(distinct c) from t1)) from t1 where  -b between 11 and t1.b or b in (select  -max(19) from t1 union select  -count(*)+ -count(*) from t1) and 17=d),13)-t1.b*a when t1.b then (17) else c end>b then e else 11 end and ( -b) or t1.e not between a and 11}
} {600}
do_test randexpr-2.544 {
  db eval {SELECT t1.e++a-c-a+coalesce((select t1.e from t1 where 11=case when t1.f not between 13 and t1.b+a*t1.c then 17 when (select min((select cast(avg(17) AS integer)*max(d)-(cast(avg(c) AS integer))*count(distinct t1.b) from t1)) from t1)>=case coalesce((select t1.b | e from t1 where t1.d in (t1.c,17,t1.c)),a) when 13 then t1.a else 19 end then t1.a else e end),t1.d) FROM t1 WHERE NOT (+t1.a*t1.c between case when case coalesce((select max(+t1.f-t1.b*(select min((b))+count(distinct c) from t1)) from t1 where  -b between 11 and t1.b or b in (select  -max(19) from t1 union select  -count(*)+ -count(*) from t1) and 17=d),13)-t1.b*a when t1.b then (17) else c end>b then e else 11 end and ( -b) or t1.e not between a and 11)}
} {}
do_test randexpr-2.545 {
  db eval {SELECT t1.e++a-c-a+coalesce((select t1.e from t1 where 11=case when t1.f not between 13 and t1.b+a*t1.c then 17 when (select min((select cast(avg(17) AS integer)*max(d)-(cast(avg(c) AS integer))*count(distinct t1.b) from t1)) from t1)>=case coalesce((select t1.b & e from t1 where t1.d in (t1.c,17,t1.c)),a) when 13 then t1.a else 19 end then t1.a else e end),t1.d) FROM t1 WHERE +t1.a*t1.c between case when case coalesce((select max(+t1.f-t1.b*(select min((b))+count(distinct c) from t1)) from t1 where  -b between 11 and t1.b or b in (select  -max(19) from t1 union select  -count(*)+ -count(*) from t1) and 17=d),13)-t1.b*a when t1.b then (17) else c end>b then e else 11 end and ( -b) or t1.e not between a and 11}
} {600}
do_test randexpr-2.546 {
  db eval {SELECT (select case ~case count(*) when (count(distinct d)*min(17)+min(13)+min(11))-max(t1.a) then count(distinct  -13) else min(t1.c) end-max( - -t1.d)*count(*) when  -count(*) then count(*) else (cast(avg(e) AS integer)) end from t1)-case when a>b then t1.d+case when (e= -t1.a) and c<c then coalesce((select t1.f+f from t1 where t1.b not in (f,13,t1.b)),t1.d) else d end+ -t1.a-c+e else 19 end FROM t1 WHERE t1.b not between a and 11 and t1.c in (select +case count(*) when count(*)*cast(avg(13) AS integer) then min(~b-c-t1.e*(abs(a)/abs(case when t1.d>=(13) and t1.e<=c then 11 else t1.f end | t1.a)))-abs(abs(count(*)))-+~min(t1.e)+~count(distinct 11)* -count(*) | max(t1.d)-( -cast(avg(13) AS integer))*(min(e)) else  -min(t1.a) end from t1 union select max(t1.f) from t1)}
} {}
do_test randexpr-2.547 {
  db eval {SELECT (select case ~case count(*) when (count(distinct d)*min(17)+min(13)+min(11))-max(t1.a) then count(distinct  -13) else min(t1.c) end-max( - -t1.d)*count(*) when  -count(*) then count(*) else (cast(avg(e) AS integer)) end from t1)-case when a>b then t1.d+case when (e= -t1.a) and c<c then coalesce((select t1.f+f from t1 where t1.b not in (f,13,t1.b)),t1.d) else d end+ -t1.a-c+e else 19 end FROM t1 WHERE NOT (t1.b not between a and 11 and t1.c in (select +case count(*) when count(*)*cast(avg(13) AS integer) then min(~b-c-t1.e*(abs(a)/abs(case when t1.d>=(13) and t1.e<=c then 11 else t1.f end | t1.a)))-abs(abs(count(*)))-+~min(t1.e)+~count(distinct 11)* -count(*) | max(t1.d)-( -cast(avg(13) AS integer))*(min(e)) else  -min(t1.a) end from t1 union select max(t1.f) from t1))}
} {481}
do_test randexpr-2.548 {
  db eval {SELECT case ~case 19 when t1.e then f else 19*f end*case when exists(select 1 from t1 where t1.e not between t1.f-~case case  -e when f then t1.d else case when t1.b in (t1.e,f,11) then e when 11<=d then  -t1.d else 17 end end when 13 then 19 else c end and 19) then coalesce((select t1.b from t1 where not exists(select 1 from t1 where (a<>b))),b) else t1.c end | e+t1.b when a then f else 19 end FROM t1 WHERE 17 in (select count(distinct t1.f)+~min(coalesce((select max(e*f-case when case when 11<>e and t1.e<=t1.d or (t1.d)<=t1.e then d when ( -17) not between  -t1.c and t1.a then coalesce((select max((19)) from t1 where  -b between e and 11), -a) else d end in (b,t1.d,a) and 19 in (13,13,t1.c) or b not in (f,(t1.e),19) then t1.c when 17 not in ((19),(t1.b),f) then +t1.d else f end) from t1 where (not a between 19 and d and (d>a))),d)) from t1 union select cast(avg(f) AS integer) from t1)}
} {}
do_test randexpr-2.549 {
  db eval {SELECT case ~case 19 when t1.e then f else 19*f end*case when exists(select 1 from t1 where t1.e not between t1.f-~case case  -e when f then t1.d else case when t1.b in (t1.e,f,11) then e when 11<=d then  -t1.d else 17 end end when 13 then 19 else c end and 19) then coalesce((select t1.b from t1 where not exists(select 1 from t1 where (a<>b))),b) else t1.c end | e+t1.b when a then f else 19 end FROM t1 WHERE NOT (17 in (select count(distinct t1.f)+~min(coalesce((select max(e*f-case when case when 11<>e and t1.e<=t1.d or (t1.d)<=t1.e then d when ( -17) not between  -t1.c and t1.a then coalesce((select max((19)) from t1 where  -b between e and 11), -a) else d end in (b,t1.d,a) and 19 in (13,13,t1.c) or b not in (f,(t1.e),19) then t1.c when 17 not in ((19),(t1.b),f) then +t1.d else f end) from t1 where (not a between 19 and d and (d>a))),d)) from t1 union select cast(avg(f) AS integer) from t1))}
} {19}
do_test randexpr-2.550 {
  db eval {SELECT case ~case 19 when t1.e then f else 19*f end*case when exists(select 1 from t1 where t1.e not between t1.f-~case case  -e when f then t1.d else case when t1.b in (t1.e,f,11) then e when 11<=d then  -t1.d else 17 end end when 13 then 19 else c end and 19) then coalesce((select t1.b from t1 where not exists(select 1 from t1 where (a<>b))),b) else t1.c end & e+t1.b when a then f else 19 end FROM t1 WHERE NOT (17 in (select count(distinct t1.f)+~min(coalesce((select max(e*f-case when case when 11<>e and t1.e<=t1.d or (t1.d)<=t1.e then d when ( -17) not between  -t1.c and t1.a then coalesce((select max((19)) from t1 where  -b between e and 11), -a) else d end in (b,t1.d,a) and 19 in (13,13,t1.c) or b not in (f,(t1.e),19) then t1.c when 17 not in ((19),(t1.b),f) then +t1.d else f end) from t1 where (not a between 19 and d and (d>a))),d)) from t1 union select cast(avg(f) AS integer) from t1))}
} {19}
do_test randexpr-2.551 {
  db eval {SELECT (abs(11*coalesce((select max(t1.a) from t1 where d>=case when coalesce((select case when not exists(select 1 from t1 where  -d in (select b-(abs(13)/abs(t1.e)) from t1 union select e from t1)) then ~c when not exists(select 1 from t1 where not exists(select 1 from t1 where  -t1.d in (select cast(avg(c) AS integer) | count(distinct e)+max( -t1.d)-(max(f)) from t1 union select count(*) from t1))) then t1.a else e end from t1 where exists(select 1 from t1 where t1.f between d and t1.b) or 17 in (11,17,d)),11) not between t1.c and t1.d then 17 when 13=t1.a then 19 else (13) end), -t1.b)-e)/abs(a)) FROM t1 WHERE t1.c+t1.c=t1.f}
} {6}
do_test randexpr-2.552 {
  db eval {SELECT (abs(11*coalesce((select max(t1.a) from t1 where d>=case when coalesce((select case when not exists(select 1 from t1 where  -d in (select b-(abs(13)/abs(t1.e)) from t1 union select e from t1)) then ~c when not exists(select 1 from t1 where not exists(select 1 from t1 where  -t1.d in (select cast(avg(c) AS integer) | count(distinct e)+max( -t1.d)-(max(f)) from t1 union select count(*) from t1))) then t1.a else e end from t1 where exists(select 1 from t1 where t1.f between d and t1.b) or 17 in (11,17,d)),11) not between t1.c and t1.d then 17 when 13=t1.a then 19 else (13) end), -t1.b)-e)/abs(a)) FROM t1 WHERE NOT (t1.c+t1.c=t1.f)}
} {}
do_test randexpr-2.553 {
  db eval {SELECT (abs(11*coalesce((select max(t1.a) from t1 where d>=case when coalesce((select case when not exists(select 1 from t1 where  -d in (select b-(abs(13)/abs(t1.e)) from t1 union select e from t1)) then ~c when not exists(select 1 from t1 where not exists(select 1 from t1 where  -t1.d in (select cast(avg(c) AS integer) & count(distinct e)+max( -t1.d)-(max(f)) from t1 union select count(*) from t1))) then t1.a else e end from t1 where exists(select 1 from t1 where t1.f between d and t1.b) or 17 in (11,17,d)),11) not between t1.c and t1.d then 17 when 13=t1.a then 19 else (13) end), -t1.b)-e)/abs(a)) FROM t1 WHERE t1.c+t1.c=t1.f}
} {6}
do_test randexpr-2.554 {
  db eval {SELECT  -t1.a*coalesce((select max(c) from t1 where  -(17 | case when (select cast(avg(17+coalesce((select max(c) from t1 where exists(select 1 from t1 where (coalesce((select max( -f) from t1 where (t1.b<=t1.b)),t1.e)<>e))),f |  -t1.a)) AS integer) from t1) in (13,e,t1.c) then f when (f>e) then b else t1.a end)*c*e not between 19 and t1.b),11)+13-19*(19) FROM t1 WHERE (c<=t1.e)}
} {-30348}
do_test randexpr-2.555 {
  db eval {SELECT  -t1.a*coalesce((select max(c) from t1 where  -(17 | case when (select cast(avg(17+coalesce((select max(c) from t1 where exists(select 1 from t1 where (coalesce((select max( -f) from t1 where (t1.b<=t1.b)),t1.e)<>e))),f |  -t1.a)) AS integer) from t1) in (13,e,t1.c) then f when (f>e) then b else t1.a end)*c*e not between 19 and t1.b),11)+13-19*(19) FROM t1 WHERE NOT ((c<=t1.e))}
} {}
do_test randexpr-2.556 {
  db eval {SELECT  -t1.a*coalesce((select max(c) from t1 where  -(17 & case when (select cast(avg(17+coalesce((select max(c) from t1 where exists(select 1 from t1 where (coalesce((select max( -f) from t1 where (t1.b<=t1.b)),t1.e)<>e))),f &  -t1.a)) AS integer) from t1) in (13,e,t1.c) then f when (f>e) then b else t1.a end)*c*e not between 19 and t1.b),11)+13-19*(19) FROM t1 WHERE (c<=t1.e)}
} {-30348}
do_test randexpr-2.557 {
  db eval {SELECT 19-coalesce((select max(case when 17 | t1.a in (select case case coalesce((select max(t1.b) from t1 where t1.f not between case when  -b in (13,f,a) then a else a end and t1.f or (a not in (d,d,t1.c))),c) when a then t1.e else f end when 13 then 13 else b end from t1 union select 17 from t1) then c when not b not in (d, -t1.e,c) then 17 else b end) from t1 where e not in (17,t1.e,b)),t1.e) FROM t1 WHERE t1.a in (select  -count(*) from t1 union select min((select (cast(avg((select +max(t1.b) from t1)) AS integer)) from t1)+17*c) from t1)}
} {}
do_test randexpr-2.558 {
  db eval {SELECT 19-coalesce((select max(case when 17 | t1.a in (select case case coalesce((select max(t1.b) from t1 where t1.f not between case when  -b in (13,f,a) then a else a end and t1.f or (a not in (d,d,t1.c))),c) when a then t1.e else f end when 13 then 13 else b end from t1 union select 17 from t1) then c when not b not in (d, -t1.e,c) then 17 else b end) from t1 where e not in (17,t1.e,b)),t1.e) FROM t1 WHERE NOT (t1.a in (select  -count(*) from t1 union select min((select (cast(avg((select +max(t1.b) from t1)) AS integer)) from t1)+17*c) from t1))}
} {-481}
do_test randexpr-2.559 {
  db eval {SELECT 19-coalesce((select max(case when 17 & t1.a in (select case case coalesce((select max(t1.b) from t1 where t1.f not between case when  -b in (13,f,a) then a else a end and t1.f or (a not in (d,d,t1.c))),c) when a then t1.e else f end when 13 then 13 else b end from t1 union select 17 from t1) then c when not b not in (d, -t1.e,c) then 17 else b end) from t1 where e not in (17,t1.e,b)),t1.e) FROM t1 WHERE NOT (t1.a in (select  -count(*) from t1 union select min((select (cast(avg((select +max(t1.b) from t1)) AS integer)) from t1)+17*c) from t1))}
} {-481}
do_test randexpr-2.560 {
  db eval {SELECT  -f-coalesce((select max(case a-t1.a when t1.f then 13 else +t1.a-t1.f end) from t1 where (select count(distinct a) from t1)>d),( -~t1.a+17+case when (not exists(select 1 from t1 where c=t1.b and c>t1.d)) then ~coalesce((select t1.f from t1 where t1.e not between t1.b and t1.e),11)+a when b<=t1.d then t1.c else 11 end+t1.b)*d)*17+d FROM t1 WHERE +t1.c in (select max(~case when 17>t1.f then 19 else  -case when d=11 or t1.b> -t1.e or d not in (b,t1.a,t1.e) then e-( -13)+d else 11 end end-t1.d) from t1 union select max(17)+case min(t1.a) | case + -case abs(cast(avg(t1.d) AS integer)) when  -count(*) then count(*) else max(19) end when min(e) then count(*) else cast(avg(t1.c) AS integer) end when min(t1.f) then count(*) else min(b) end from t1)}
} {}
do_test randexpr-2.561 {
  db eval {SELECT  -f-coalesce((select max(case a-t1.a when t1.f then 13 else +t1.a-t1.f end) from t1 where (select count(distinct a) from t1)>d),( -~t1.a+17+case when (not exists(select 1 from t1 where c=t1.b and c>t1.d)) then ~coalesce((select t1.f from t1 where t1.e not between t1.b and t1.e),11)+a when b<=t1.d then t1.c else 11 end+t1.b)*d)*17+d FROM t1 WHERE NOT (+t1.c in (select max(~case when 17>t1.f then 19 else  -case when d=11 or t1.b> -t1.e or d not in (b,t1.a,t1.e) then e-( -13)+d else 11 end end-t1.d) from t1 union select max(17)+case min(t1.a) | case + -case abs(cast(avg(t1.d) AS integer)) when  -count(*) then count(*) else max(19) end when min(e) then count(*) else cast(avg(t1.c) AS integer) end when min(t1.f) then count(*) else min(b) end from t1))}
} {-2761000}
do_test randexpr-2.562 {
  db eval {SELECT coalesce((select 11 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not (select +count(*)* -count(distinct case when exists(select 1 from t1 where 13+a=t1.b) then d else 13 end-t1.b) from t1)<=17 | e-13)) or not exists(select 1 from t1 where not t1.e in ((13),17,19) and not t1.d>a and t1.e not between t1.e and b)),coalesce((select max(coalesce((select max(b) from t1 where (b)>11),d)) from t1 where 11> -19),f)-c) FROM t1 WHERE case when  -13 not in (b,(abs(coalesce((select max(case when  -17<>t1.f then b when coalesce((select t1.b from t1 where t1.c in (select (a) from t1 union select c from t1)),17)<=t1.e then b else f end) from t1 where b<=11),t1.c))/abs((d))),19) then t1.b when (exists(select 1 from t1 where not exists(select 1 from t1 where ((13)=e and t1.f between 17 and t1.a) or t1.f between (a) and  -(t1.f)))) and t1.e between b and 13 or b<>(f) then t1.f else d end>=a or d>=13}
} {11}
do_test randexpr-2.563 {
  db eval {SELECT coalesce((select 11 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not (select +count(*)* -count(distinct case when exists(select 1 from t1 where 13+a=t1.b) then d else 13 end-t1.b) from t1)<=17 | e-13)) or not exists(select 1 from t1 where not t1.e in ((13),17,19) and not t1.d>a and t1.e not between t1.e and b)),coalesce((select max(coalesce((select max(b) from t1 where (b)>11),d)) from t1 where 11> -19),f)-c) FROM t1 WHERE NOT (case when  -13 not in (b,(abs(coalesce((select max(case when  -17<>t1.f then b when coalesce((select t1.b from t1 where t1.c in (select (a) from t1 union select c from t1)),17)<=t1.e then b else f end) from t1 where b<=11),t1.c))/abs((d))),19) then t1.b when (exists(select 1 from t1 where not exists(select 1 from t1 where ((13)=e and t1.f between 17 and t1.a) or t1.f between (a) and  -(t1.f)))) and t1.e between b and 13 or b<>(f) then t1.f else d end>=a or d>=13)}
} {}
do_test randexpr-2.564 {
  db eval {SELECT coalesce((select 11 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not (select +count(*)* -count(distinct case when exists(select 1 from t1 where 13+a=t1.b) then d else 13 end-t1.b) from t1)<=17 & e-13)) or not exists(select 1 from t1 where not t1.e in ((13),17,19) and not t1.d>a and t1.e not between t1.e and b)),coalesce((select max(coalesce((select max(b) from t1 where (b)>11),d)) from t1 where 11> -19),f)-c) FROM t1 WHERE case when  -13 not in (b,(abs(coalesce((select max(case when  -17<>t1.f then b when coalesce((select t1.b from t1 where t1.c in (select (a) from t1 union select c from t1)),17)<=t1.e then b else f end) from t1 where b<=11),t1.c))/abs((d))),19) then t1.b when (exists(select 1 from t1 where not exists(select 1 from t1 where ((13)=e and t1.f between 17 and t1.a) or t1.f between (a) and  -(t1.f)))) and t1.e between b and 13 or b<>(f) then t1.f else d end>=a or d>=13}
} {11}
do_test randexpr-2.565 {
  db eval {SELECT coalesce((select max(coalesce((select max(13+f | c+a) from t1 where 17<t1.a),~case when 17 in (select count(distinct 11) from t1 union select ++cast(avg(a | 11) AS integer)-count(*) from t1) then t1.a else 17 end)) from t1 where case t1.d when 17 then t1.a else 17 end not between 13 and case t1.c when t1.b*case when t1.d<>d then 13 else c end-c then e else t1.e end),c) FROM t1 WHERE exists(select 1 from t1 where t1.a+( -case when exists(select 1 from t1 where exists(select 1 from t1 where b | c-c+t1.d not between 19 and 11)) then coalesce((select t1.c from t1 where c+17 in (f,13,c) or t1.e*coalesce((select case when (not exists(select 1 from t1 where 17>e)) then t1.d else ~t1.e end from t1 where (t1.f not in (19,a,t1.b) or c=f)),c)=c), -11) else e end)<=t1.b)}
} {300}
do_test randexpr-2.566 {
  db eval {SELECT coalesce((select max(coalesce((select max(13+f | c+a) from t1 where 17<t1.a),~case when 17 in (select count(distinct 11) from t1 union select ++cast(avg(a | 11) AS integer)-count(*) from t1) then t1.a else 17 end)) from t1 where case t1.d when 17 then t1.a else 17 end not between 13 and case t1.c when t1.b*case when t1.d<>d then 13 else c end-c then e else t1.e end),c) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.a+( -case when exists(select 1 from t1 where exists(select 1 from t1 where b | c-c+t1.d not between 19 and 11)) then coalesce((select t1.c from t1 where c+17 in (f,13,c) or t1.e*coalesce((select case when (not exists(select 1 from t1 where 17>e)) then t1.d else ~t1.e end from t1 where (t1.f not in (19,a,t1.b) or c=f)),c)=c), -11) else e end)<=t1.b))}
} {}
do_test randexpr-2.567 {
  db eval {SELECT coalesce((select max(coalesce((select max(13+f & c+a) from t1 where 17<t1.a),~case when 17 in (select count(distinct 11) from t1 union select ++cast(avg(a & 11) AS integer)-count(*) from t1) then t1.a else 17 end)) from t1 where case t1.d when 17 then t1.a else 17 end not between 13 and case t1.c when t1.b*case when t1.d<>d then 13 else c end-c then e else t1.e end),c) FROM t1 WHERE exists(select 1 from t1 where t1.a+( -case when exists(select 1 from t1 where exists(select 1 from t1 where b | c-c+t1.d not between 19 and 11)) then coalesce((select t1.c from t1 where c+17 in (f,13,c) or t1.e*coalesce((select case when (not exists(select 1 from t1 where 17>e)) then t1.d else ~t1.e end from t1 where (t1.f not in (19,a,t1.b) or c=f)),c)=c), -11) else e end)<=t1.b)}
} {300}
do_test randexpr-2.568 {
  db eval {SELECT case when ((coalesce((select max((select ~cast(avg((~d*f)) AS integer) from t1)) from t1 where  - -t1.f<>d),e) in (select cast(avg(+13) AS integer)*~count(*) | case count(*) when  -abs(abs(max(f))) then cast(avg(e) AS integer) else (count(distinct b)) end from t1 union select count(*) from t1) and b>= -t1.d)) then (17) when b between 13 and t1.d then  -e+t1.a else t1.f end FROM t1 WHERE (case when +t1.f-(select abs(count(distinct d)) from t1)*case when c in (select min(b) from t1 union select max(c+f*case 11*t1.b when b then t1.c else c end | t1.a) from t1) then d else f end | t1.a*b in (t1.d,17,a) then  -t1.a else t1.d end) in (e,t1.c,f) and  -((t1.c)) in (11,t1.e,t1.c)}
} {}
do_test randexpr-2.569 {
  db eval {SELECT case when ((coalesce((select max((select ~cast(avg((~d*f)) AS integer) from t1)) from t1 where  - -t1.f<>d),e) in (select cast(avg(+13) AS integer)*~count(*) | case count(*) when  -abs(abs(max(f))) then cast(avg(e) AS integer) else (count(distinct b)) end from t1 union select count(*) from t1) and b>= -t1.d)) then (17) when b between 13 and t1.d then  -e+t1.a else t1.f end FROM t1 WHERE NOT ((case when +t1.f-(select abs(count(distinct d)) from t1)*case when c in (select min(b) from t1 union select max(c+f*case 11*t1.b when b then t1.c else c end | t1.a) from t1) then d else f end | t1.a*b in (t1.d,17,a) then  -t1.a else t1.d end) in (e,t1.c,f) and  -((t1.c)) in (11,t1.e,t1.c))}
} {-400}
do_test randexpr-2.570 {
  db eval {SELECT case when ((coalesce((select max((select ~cast(avg((~d*f)) AS integer) from t1)) from t1 where  - -t1.f<>d),e) in (select cast(avg(+13) AS integer)*~count(*) & case count(*) when  -abs(abs(max(f))) then cast(avg(e) AS integer) else (count(distinct b)) end from t1 union select count(*) from t1) and b>= -t1.d)) then (17) when b between 13 and t1.d then  -e+t1.a else t1.f end FROM t1 WHERE NOT ((case when +t1.f-(select abs(count(distinct d)) from t1)*case when c in (select min(b) from t1 union select max(c+f*case 11*t1.b when b then t1.c else c end | t1.a) from t1) then d else f end | t1.a*b in (t1.d,17,a) then  -t1.a else t1.d end) in (e,t1.c,f) and  -((t1.c)) in (11,t1.e,t1.c))}
} {-400}
do_test randexpr-2.571 {
  db eval {SELECT t1.d-case when e in (17,coalesce((select max((select count(*) from t1)) from t1 where (~t1.f++19*t1.f+b in (a,t1.b, -t1.e)) and b in (select count(distinct t1.a) from t1 union select (abs(abs(abs(max(t1.e)*max(t1.d))-min(11)* -count(*)))) from t1)),17),13) and t1.f in (select t1.b from t1 union select f from t1) then t1.c else c end+f FROM t1 WHERE not (select (abs(abs((+count(*)*~ -cast(avg(+t1.f-c) AS integer)*count(distinct +coalesce((select max((abs(c)/abs(t1.e))) from t1 where coalesce((select coalesce((select max(f) from t1 where t1.d<=t1.d),e)*c from t1 where t1.f<>f),c) not between t1.a and c),t1.e)+13)-count(distinct f) | abs(cast(avg(t1.b) AS integer)))))) from t1)-13<t1.c}
} {700}
do_test randexpr-2.572 {
  db eval {SELECT t1.d-case when e in (17,coalesce((select max((select count(*) from t1)) from t1 where (~t1.f++19*t1.f+b in (a,t1.b, -t1.e)) and b in (select count(distinct t1.a) from t1 union select (abs(abs(abs(max(t1.e)*max(t1.d))-min(11)* -count(*)))) from t1)),17),13) and t1.f in (select t1.b from t1 union select f from t1) then t1.c else c end+f FROM t1 WHERE NOT (not (select (abs(abs((+count(*)*~ -cast(avg(+t1.f-c) AS integer)*count(distinct +coalesce((select max((abs(c)/abs(t1.e))) from t1 where coalesce((select coalesce((select max(f) from t1 where t1.d<=t1.d),e)*c from t1 where t1.f<>f),c) not between t1.a and c),t1.e)+13)-count(distinct f) | abs(cast(avg(t1.b) AS integer)))))) from t1)-13<t1.c)}
} {}
do_test randexpr-2.573 {
  db eval {SELECT (abs(t1.f*case when (abs(t1.f+17-(t1.a*11*(abs(d)/abs(coalesce((select max(11) from t1 where e=a-t1.a or e not between 17 and 11 or (t1.f)>=c or f<>e),+d))) | t1.c*b+t1.d)- -f)/abs(13))<>t1.e then  -t1.e when t1.e not between f and t1.a then t1.c else t1.c end)/abs(t1.e)) FROM t1 WHERE (abs(b*t1.e+t1.a)/abs(t1.c))<case when 13 in (coalesce((select max(~(abs( -11*t1.a)/abs(c))+t1.e) from t1 where t1.d in (f,c,(f))),f)-f,b,t1.b) then e when not exists(select 1 from t1 where f in (select max(19) from t1 union select cast(avg(t1.e) AS integer)- -min(11) | abs((cast(avg(t1.d) AS integer))) from t1)) then d else d end and e<e}
} {}
do_test randexpr-2.574 {
  db eval {SELECT (abs(t1.f*case when (abs(t1.f+17-(t1.a*11*(abs(d)/abs(coalesce((select max(11) from t1 where e=a-t1.a or e not between 17 and 11 or (t1.f)>=c or f<>e),+d))) | t1.c*b+t1.d)- -f)/abs(13))<>t1.e then  -t1.e when t1.e not between f and t1.a then t1.c else t1.c end)/abs(t1.e)) FROM t1 WHERE NOT ((abs(b*t1.e+t1.a)/abs(t1.c))<case when 13 in (coalesce((select max(~(abs( -11*t1.a)/abs(c))+t1.e) from t1 where t1.d in (f,c,(f))),f)-f,b,t1.b) then e when not exists(select 1 from t1 where f in (select max(19) from t1 union select cast(avg(t1.e) AS integer)- -min(11) | abs((cast(avg(t1.d) AS integer))) from t1)) then d else d end and e<e)}
} {600}
do_test randexpr-2.575 {
  db eval {SELECT (abs(t1.f*case when (abs(t1.f+17-(t1.a*11*(abs(d)/abs(coalesce((select max(11) from t1 where e=a-t1.a or e not between 17 and 11 or (t1.f)>=c or f<>e),+d))) & t1.c*b+t1.d)- -f)/abs(13))<>t1.e then  -t1.e when t1.e not between f and t1.a then t1.c else t1.c end)/abs(t1.e)) FROM t1 WHERE NOT ((abs(b*t1.e+t1.a)/abs(t1.c))<case when 13 in (coalesce((select max(~(abs( -11*t1.a)/abs(c))+t1.e) from t1 where t1.d in (f,c,(f))),f)-f,b,t1.b) then e when not exists(select 1 from t1 where f in (select max(19) from t1 union select cast(avg(t1.e) AS integer)- -min(11) | abs((cast(avg(t1.d) AS integer))) from t1)) then d else d end and e<e)}
} {600}
do_test randexpr-2.576 {
  db eval {SELECT (abs(t1.c-case when +coalesce((select max(coalesce((select max(a-a*t1.f) from t1 where ~t1.a*t1.a-t1.b+f* -19 not in (t1.d,e,b)),11)*t1.a) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (c) in (b,c,t1.c))) or t1.e between  -b and b),a)+a<=e then t1.d else 17 end)/abs(f)) FROM t1 WHERE t1.d-t1.c+~t1.c<>case when (17) in (select + -abs(count(distinct t1.e*17*c+f)-max(19)) from t1 union select count(*)-max(case t1.f when a then (11+19*t1.b+t1.f) else (19) end*t1.c) from t1) then (abs(b- -f)/abs(f)) else t1.f end}
} {0}
do_test randexpr-2.577 {
  db eval {SELECT (abs(t1.c-case when +coalesce((select max(coalesce((select max(a-a*t1.f) from t1 where ~t1.a*t1.a-t1.b+f* -19 not in (t1.d,e,b)),11)*t1.a) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (c) in (b,c,t1.c))) or t1.e between  -b and b),a)+a<=e then t1.d else 17 end)/abs(f)) FROM t1 WHERE NOT (t1.d-t1.c+~t1.c<>case when (17) in (select + -abs(count(distinct t1.e*17*c+f)-max(19)) from t1 union select count(*)-max(case t1.f when a then (11+19*t1.b+t1.f) else (19) end*t1.c) from t1) then (abs(b- -f)/abs(f)) else t1.f end)}
} {}
do_test randexpr-2.578 {
  db eval {SELECT (abs( -coalesce((select 11 from t1 where (case f when (19+ -(select count(*) from t1)) then (select ++~count(distinct 17+t1.f*(17)) | cast(avg(c) AS integer) from t1) else 13-t1.b*t1.b end*t1.c*(select max(e)*cast(avg(t1.b) AS integer) from t1) | 13) | 17 between 11 and 17),(e))+d)/abs(t1.b))-t1.d FROM t1 WHERE 11<>t1.b}
} {-400}
do_test randexpr-2.579 {
  db eval {SELECT (abs( -coalesce((select 11 from t1 where (case f when (19+ -(select count(*) from t1)) then (select ++~count(distinct 17+t1.f*(17)) | cast(avg(c) AS integer) from t1) else 13-t1.b*t1.b end*t1.c*(select max(e)*cast(avg(t1.b) AS integer) from t1) | 13) | 17 between 11 and 17),(e))+d)/abs(t1.b))-t1.d FROM t1 WHERE NOT (11<>t1.b)}
} {}
do_test randexpr-2.580 {
  db eval {SELECT (abs( -coalesce((select 11 from t1 where (case f when (19+ -(select count(*) from t1)) then (select ++~count(distinct 17+t1.f*(17)) & cast(avg(c) AS integer) from t1) else 13-t1.b*t1.b end*t1.c*(select max(e)*cast(avg(t1.b) AS integer) from t1) & 13) & 17 between 11 and 17),(e))+d)/abs(t1.b))-t1.d FROM t1 WHERE 11<>t1.b}
} {-400}
do_test randexpr-2.581 {
  db eval {SELECT ( -13)-case when (13)+19 between (select cast(avg(11+coalesce((select d from t1 where t1.a in (select b from t1 union select c from t1)),11)+t1.e*d) AS integer)*+(max(t1.c))+cast(avg((c)) AS integer)*count(*) | max( -t1.b) from t1)-t1.d and t1.a then t1.b when b<>t1.f then t1.c else a end-b-t1.b FROM t1 WHERE 11<=t1.e+19*+t1.d}
} {-613}
do_test randexpr-2.582 {
  db eval {SELECT ( -13)-case when (13)+19 between (select cast(avg(11+coalesce((select d from t1 where t1.a in (select b from t1 union select c from t1)),11)+t1.e*d) AS integer)*+(max(t1.c))+cast(avg((c)) AS integer)*count(*) | max( -t1.b) from t1)-t1.d and t1.a then t1.b when b<>t1.f then t1.c else a end-b-t1.b FROM t1 WHERE NOT (11<=t1.e+19*+t1.d)}
} {}
do_test randexpr-2.583 {
  db eval {SELECT ( -13)-case when (13)+19 between (select cast(avg(11+coalesce((select d from t1 where t1.a in (select b from t1 union select c from t1)),11)+t1.e*d) AS integer)*+(max(t1.c))+cast(avg((c)) AS integer)*count(*) & max( -t1.b) from t1)-t1.d and t1.a then t1.b when b<>t1.f then t1.c else a end-b-t1.b FROM t1 WHERE 11<=t1.e+19*+t1.d}
} {-713}
do_test randexpr-2.584 {
  db eval {SELECT coalesce((select max(t1.e++case ~t1.c when t1.f-c then t1.b*+coalesce((select max(+t1.c) from t1 where 19-19-13 | t1.d+(select ~min(17) from t1) not in (case when t1.a<>b then e else  -e end,(t1.d),t1.a)),b)+((e))* -t1.e else t1.d end | b) from t1 where a not between 13 and c),t1.e) FROM t1 WHERE not case when (exists(select 1 from t1 where (((abs(19)/abs((case when exists(select 1 from t1 where +t1.f>c) then 19 when f in (t1.d,t1.a,13) and b=t1.e then t1.f else t1.a end))) in (e, -t1.c,t1.b))))) then  -t1.f when b in (d,11, -d) then t1.e*t1.a else a end+d<>t1.f and (t1.f=( -17))}
} {}
do_test randexpr-2.585 {
  db eval {SELECT coalesce((select max(t1.e++case ~t1.c when t1.f-c then t1.b*+coalesce((select max(+t1.c) from t1 where 19-19-13 | t1.d+(select ~min(17) from t1) not in (case when t1.a<>b then e else  -e end,(t1.d),t1.a)),b)+((e))* -t1.e else t1.d end | b) from t1 where a not between 13 and c),t1.e) FROM t1 WHERE NOT (not case when (exists(select 1 from t1 where (((abs(19)/abs((case when exists(select 1 from t1 where +t1.f>c) then 19 when f in (t1.d,t1.a,13) and b=t1.e then t1.f else t1.a end))) in (e, -t1.c,t1.b))))) then  -t1.f when b in (d,11, -d) then t1.e*t1.a else a end+d<>t1.f and (t1.f=( -17)))}
} {500}
do_test randexpr-2.586 {
  db eval {SELECT coalesce((select max(t1.e++case ~t1.c when t1.f-c then t1.b*+coalesce((select max(+t1.c) from t1 where 19-19-13 & t1.d+(select ~min(17) from t1) not in (case when t1.a<>b then e else  -e end,(t1.d),t1.a)),b)+((e))* -t1.e else t1.d end & b) from t1 where a not between 13 and c),t1.e) FROM t1 WHERE NOT (not case when (exists(select 1 from t1 where (((abs(19)/abs((case when exists(select 1 from t1 where +t1.f>c) then 19 when f in (t1.d,t1.a,13) and b=t1.e then t1.f else t1.a end))) in (e, -t1.c,t1.b))))) then  -t1.f when b in (d,11, -d) then t1.e*t1.a else a end+d<>t1.f and (t1.f=( -17)))}
} {500}
do_test randexpr-2.587 {
  db eval {SELECT case when t1.d-~case t1.b when coalesce((select max(b) from t1 where exists(select 1 from t1 where t1.c<>b)),case when 17 in (select min(c+17) from t1 union select ~ -count(distinct 11) | max(d) from t1) then d when ((t1.a not between t1.f and t1.f)) then t1.a else t1.b end) then (c) else (t1.c) end<t1.a then t1.d when f not between 19 and c and 17 in (t1.f,t1.d,c) then t1.f else 11 end+t1.e*( -11) FROM t1 WHERE case c when f then case (abs(t1.d | case when ((13))*a+c+19>=d then  -13 when b in (select cast(avg((a)) AS integer) from t1 union select  -~abs(count(*))*min(t1.f) from t1) then d else 19 end)/abs(19)) when 11 then 11 else t1.f end+13-t1.d else t1.b end+b>=d and not exists(select 1 from t1 where e>=19)}
} {}
do_test randexpr-2.588 {
  db eval {SELECT case when t1.d-~case t1.b when coalesce((select max(b) from t1 where exists(select 1 from t1 where t1.c<>b)),case when 17 in (select min(c+17) from t1 union select ~ -count(distinct 11) | max(d) from t1) then d when ((t1.a not between t1.f and t1.f)) then t1.a else t1.b end) then (c) else (t1.c) end<t1.a then t1.d when f not between 19 and c and 17 in (t1.f,t1.d,c) then t1.f else 11 end+t1.e*( -11) FROM t1 WHERE NOT (case c when f then case (abs(t1.d | case when ((13))*a+c+19>=d then  -13 when b in (select cast(avg((a)) AS integer) from t1 union select  -~abs(count(*))*min(t1.f) from t1) then d else 19 end)/abs(19)) when 11 then 11 else t1.f end+13-t1.d else t1.b end+b>=d and not exists(select 1 from t1 where e>=19))}
} {-5489}
do_test randexpr-2.589 {
  db eval {SELECT case when t1.d-~case t1.b when coalesce((select max(b) from t1 where exists(select 1 from t1 where t1.c<>b)),case when 17 in (select min(c+17) from t1 union select ~ -count(distinct 11) & max(d) from t1) then d when ((t1.a not between t1.f and t1.f)) then t1.a else t1.b end) then (c) else (t1.c) end<t1.a then t1.d when f not between 19 and c and 17 in (t1.f,t1.d,c) then t1.f else 11 end+t1.e*( -11) FROM t1 WHERE NOT (case c when f then case (abs(t1.d | case when ((13))*a+c+19>=d then  -13 when b in (select cast(avg((a)) AS integer) from t1 union select  -~abs(count(*))*min(t1.f) from t1) then d else 19 end)/abs(19)) when 11 then 11 else t1.f end+13-t1.d else t1.b end+b>=d and not exists(select 1 from t1 where e>=19))}
} {-5489}
do_test randexpr-2.590 {
  db eval {SELECT b+coalesce((select (t1.e) from t1 where coalesce((select max((select abs(cast(avg( -t1.f*17) AS integer))+count(*) from t1)-19*coalesce((select b*+~(t1.c)*(abs(c)/abs(a))+t1.e from t1 where 11 in (t1.a,17,b* -t1.f)),t1.e)*t1.b) from t1 where t1.f<>17),17) in (11,11, -t1.f)),t1.e) FROM t1 WHERE coalesce((select max(coalesce((select 19-e from t1 where t1.b not in (coalesce((select max(t1.e+coalesce((select 11+ -coalesce((select max(t1.a) from t1 where t1.a in (select cast(avg( -11) AS integer) from t1 union select  -max(c) from t1)),11)*t1.a from t1 where exists(select 1 from t1 where a= -e)),e)-t1.c | t1.d) from t1 where t1.e=t1.a),17),(t1.e),c)),t1.b)) from t1 where not exists(select 1 from t1 where (13>=a) or exists(select 1 from t1 where d<>11))), -19)<=t1.b}
} {700}
do_test randexpr-2.591 {
  db eval {SELECT b+coalesce((select (t1.e) from t1 where coalesce((select max((select abs(cast(avg( -t1.f*17) AS integer))+count(*) from t1)-19*coalesce((select b*+~(t1.c)*(abs(c)/abs(a))+t1.e from t1 where 11 in (t1.a,17,b* -t1.f)),t1.e)*t1.b) from t1 where t1.f<>17),17) in (11,11, -t1.f)),t1.e) FROM t1 WHERE NOT (coalesce((select max(coalesce((select 19-e from t1 where t1.b not in (coalesce((select max(t1.e+coalesce((select 11+ -coalesce((select max(t1.a) from t1 where t1.a in (select cast(avg( -11) AS integer) from t1 union select  -max(c) from t1)),11)*t1.a from t1 where exists(select 1 from t1 where a= -e)),e)-t1.c | t1.d) from t1 where t1.e=t1.a),17),(t1.e),c)),t1.b)) from t1 where not exists(select 1 from t1 where (13>=a) or exists(select 1 from t1 where d<>11))), -19)<=t1.b)}
} {}
do_test randexpr-2.592 {
  db eval {SELECT (select count(distinct t1.a)-cast(avg(~c+coalesce((select e from t1 where e in (select t1.f from t1 union select d from t1) or t1.d not in (case when a not in (t1.d,t1.c,t1.b) then a-case when ~t1.b+t1.e |  -t1.e not in (a,(b),19) then t1.d else 11 end*b when 13 in (c,13,t1.a) then  -t1.a else 17 end,c,d)),t1.e)) AS integer) from t1) FROM t1 WHERE ~e<=(a-(select count(*) from t1)+c+(select  -abs(abs( -(max((abs(coalesce((select a*(abs(b-b)/abs((c*a*b)-11+coalesce((select max(b) from t1 where a<c),e))) from t1 where 17<>e),e))/abs(11))*t1.e)))) | abs((count(*))) from t1))}
} {-198}
do_test randexpr-2.593 {
  db eval {SELECT (select count(distinct t1.a)-cast(avg(~c+coalesce((select e from t1 where e in (select t1.f from t1 union select d from t1) or t1.d not in (case when a not in (t1.d,t1.c,t1.b) then a-case when ~t1.b+t1.e |  -t1.e not in (a,(b),19) then t1.d else 11 end*b when 13 in (c,13,t1.a) then  -t1.a else 17 end,c,d)),t1.e)) AS integer) from t1) FROM t1 WHERE NOT (~e<=(a-(select count(*) from t1)+c+(select  -abs(abs( -(max((abs(coalesce((select a*(abs(b-b)/abs((c*a*b)-11+coalesce((select max(b) from t1 where a<c),e))) from t1 where 17<>e),e))/abs(11))*t1.e)))) | abs((count(*))) from t1)))}
} {}
do_test randexpr-2.594 {
  db eval {SELECT (select count(distinct t1.a)-cast(avg(~c+coalesce((select e from t1 where e in (select t1.f from t1 union select d from t1) or t1.d not in (case when a not in (t1.d,t1.c,t1.b) then a-case when ~t1.b+t1.e &  -t1.e not in (a,(b),19) then t1.d else 11 end*b when 13 in (c,13,t1.a) then  -t1.a else 17 end,c,d)),t1.e)) AS integer) from t1) FROM t1 WHERE ~e<=(a-(select count(*) from t1)+c+(select  -abs(abs( -(max((abs(coalesce((select a*(abs(b-b)/abs((c*a*b)-11+coalesce((select max(b) from t1 where a<c),e))) from t1 where 17<>e),e))/abs(11))*t1.e)))) | abs((count(*))) from t1))}
} {-198}
do_test randexpr-2.595 {
  db eval {SELECT 13-(select cast(avg(t1.c-13) AS integer) from t1) | 11+t1.b | coalesce((select max(case when b in (select case  -case max(17) when ~cast(avg(13-t1.a) AS integer) then count(distinct 13) else  - -((cast(avg(e) AS integer))) end when cast(avg(t1.c) AS integer) then count(distinct d) else count(*) end from t1 union select count(*) from t1) then case when t1.d<>~13 then b when t1.c<>13 then t1.a else a end else t1.a end) from t1 where t1.f<>( -(17))),t1.e)+c FROM t1 WHERE (~coalesce((select (11+t1.d) from t1 where 17 in (select f+a from t1 union select case when 11>coalesce((select  -case when (11 not in (t1.f,(abs(t1.a)/abs((select count(distinct  -case when 13<=e then c when d between (t1.d) and t1.d then a else 11 end) from t1)-f)),c)) then f when (t1.f>t1.d) then 17 else 13 end from t1 where t1.e>a),17) then f else t1.b end from t1)),b)*13>e)}
} {}
do_test randexpr-2.596 {
  db eval {SELECT 13-(select cast(avg(t1.c-13) AS integer) from t1) | 11+t1.b | coalesce((select max(case when b in (select case  -case max(17) when ~cast(avg(13-t1.a) AS integer) then count(distinct 13) else  - -((cast(avg(e) AS integer))) end when cast(avg(t1.c) AS integer) then count(distinct d) else count(*) end from t1 union select count(*) from t1) then case when t1.d<>~13 then b when t1.c<>13 then t1.a else a end else t1.a end) from t1 where t1.f<>( -(17))),t1.e)+c FROM t1 WHERE NOT ((~coalesce((select (11+t1.d) from t1 where 17 in (select f+a from t1 union select case when 11>coalesce((select  -case when (11 not in (t1.f,(abs(t1.a)/abs((select count(distinct  -case when 13<=e then c when d between (t1.d) and t1.d then a else 11 end) from t1)-f)),c)) then f when (t1.f>t1.d) then 17 else 13 end from t1 where t1.e>a),17) then f else t1.b end from t1)),b)*13>e))}
} {-1}
do_test randexpr-2.597 {
  db eval {SELECT 13-(select cast(avg(t1.c-13) AS integer) from t1) & 11+t1.b & coalesce((select max(case when b in (select case  -case max(17) when ~cast(avg(13-t1.a) AS integer) then count(distinct 13) else  - -((cast(avg(e) AS integer))) end when cast(avg(t1.c) AS integer) then count(distinct d) else count(*) end from t1 union select count(*) from t1) then case when t1.d<>~13 then b when t1.c<>13 then t1.a else a end else t1.a end) from t1 where t1.f<>( -(17))),t1.e)+c FROM t1 WHERE NOT ((~coalesce((select (11+t1.d) from t1 where 17 in (select f+a from t1 union select case when 11>coalesce((select  -case when (11 not in (t1.f,(abs(t1.a)/abs((select count(distinct  -case when 13<=e then c when d between (t1.d) and t1.d then a else 11 end) from t1)-f)),c)) then f when (t1.f>t1.d) then 17 else 13 end from t1 where t1.e>a),17) then f else t1.b end from t1)),b)*13>e))}
} {128}
do_test randexpr-2.598 {
  db eval {SELECT f+coalesce((select case when ~case when coalesce((select max(b) from t1 where not exists(select 1 from t1 where 11*t1.b>case t1.b when 13 then 11 else b end)),t1.b) not in (a,b,+t1.e | case when t1.a<>17 then 17 else t1.e end) then c when (t1.e)<>d then 11 else f end*(e) not between d and e then 17 else 17 end from t1 where 13 not between 19 and f),t1.b)*11 FROM t1 WHERE not exists(select 1 from t1 where 11 between c and b and  -case when 13 between  -f | case when t1.b<+c then b when t1.f>13 then a else (d) end and d then t1.d when t1.a in (select 19 from t1 union select 11 from t1) or not exists(select 1 from t1 where exists(select 1 from t1 where not b=t1.b)) then  -19 else t1.b end in (select max(17) from t1 union select count(distinct a)+count(distinct 11) from t1) and t1.f<t1.d or b not in (d,t1.d,a))}
} {}
do_test randexpr-2.599 {
  db eval {SELECT f+coalesce((select case when ~case when coalesce((select max(b) from t1 where not exists(select 1 from t1 where 11*t1.b>case t1.b when 13 then 11 else b end)),t1.b) not in (a,b,+t1.e | case when t1.a<>17 then 17 else t1.e end) then c when (t1.e)<>d then 11 else f end*(e) not between d and e then 17 else 17 end from t1 where 13 not between 19 and f),t1.b)*11 FROM t1 WHERE NOT (not exists(select 1 from t1 where 11 between c and b and  -case when 13 between  -f | case when t1.b<+c then b when t1.f>13 then a else (d) end and d then t1.d when t1.a in (select 19 from t1 union select 11 from t1) or not exists(select 1 from t1 where exists(select 1 from t1 where not b=t1.b)) then  -19 else t1.b end in (select max(17) from t1 union select count(distinct a)+count(distinct 11) from t1) and t1.f<t1.d or b not in (d,t1.d,a)))}
} {787}
do_test randexpr-2.600 {
  db eval {SELECT f+coalesce((select case when ~case when coalesce((select max(b) from t1 where not exists(select 1 from t1 where 11*t1.b>case t1.b when 13 then 11 else b end)),t1.b) not in (a,b,+t1.e & case when t1.a<>17 then 17 else t1.e end) then c when (t1.e)<>d then 11 else f end*(e) not between d and e then 17 else 17 end from t1 where 13 not between 19 and f),t1.b)*11 FROM t1 WHERE NOT (not exists(select 1 from t1 where 11 between c and b and  -case when 13 between  -f | case when t1.b<+c then b when t1.f>13 then a else (d) end and d then t1.d when t1.a in (select 19 from t1 union select 11 from t1) or not exists(select 1 from t1 where exists(select 1 from t1 where not b=t1.b)) then  -19 else t1.b end in (select max(17) from t1 union select count(distinct a)+count(distinct 11) from t1) and t1.f<t1.d or b not in (d,t1.d,a)))}
} {787}
do_test randexpr-2.601 {
  db eval {SELECT coalesce((select max(e) from t1 where e*~t1.b*e+c*case when +(abs(coalesce((select max(t1.b) from t1 where t1.b>=t1.a-11),11))/abs(17))=t1.f and ((t1.f)=t1.e) then t1.a+t1.d when not exists(select 1 from t1 where  -b>c) or t1.a>=11 then t1.e else e end*13*t1.f | d>=19),t1.b)+t1.a FROM t1 WHERE t1.e not in (t1.f+case when f-d not between coalesce((select max(d) from t1 where (coalesce((select max(17) from t1 where not 19 in (select cast(avg(c) AS integer)-~count(distinct f- -e)+cast(avg(19) AS integer) from t1 union select cast(avg(d) AS integer) from t1)),b) not in (13,t1.c,13))),17)+ -e+t1.f and  -(t1.b) then (t1.d) when t1.b in (select min(a) from t1 union select min(17) from t1) then c else 11 end,c, -13)}
} {600}
do_test randexpr-2.602 {
  db eval {SELECT coalesce((select max(e) from t1 where e*~t1.b*e+c*case when +(abs(coalesce((select max(t1.b) from t1 where t1.b>=t1.a-11),11))/abs(17))=t1.f and ((t1.f)=t1.e) then t1.a+t1.d when not exists(select 1 from t1 where  -b>c) or t1.a>=11 then t1.e else e end*13*t1.f | d>=19),t1.b)+t1.a FROM t1 WHERE NOT (t1.e not in (t1.f+case when f-d not between coalesce((select max(d) from t1 where (coalesce((select max(17) from t1 where not 19 in (select cast(avg(c) AS integer)-~count(distinct f- -e)+cast(avg(19) AS integer) from t1 union select cast(avg(d) AS integer) from t1)),b) not in (13,t1.c,13))),17)+ -e+t1.f and  -(t1.b) then (t1.d) when t1.b in (select min(a) from t1 union select min(17) from t1) then c else 11 end,c, -13))}
} {}
do_test randexpr-2.603 {
  db eval {SELECT coalesce((select max(e) from t1 where e*~t1.b*e+c*case when +(abs(coalesce((select max(t1.b) from t1 where t1.b>=t1.a-11),11))/abs(17))=t1.f and ((t1.f)=t1.e) then t1.a+t1.d when not exists(select 1 from t1 where  -b>c) or t1.a>=11 then t1.e else e end*13*t1.f & d>=19),t1.b)+t1.a FROM t1 WHERE t1.e not in (t1.f+case when f-d not between coalesce((select max(d) from t1 where (coalesce((select max(17) from t1 where not 19 in (select cast(avg(c) AS integer)-~count(distinct f- -e)+cast(avg(19) AS integer) from t1 union select cast(avg(d) AS integer) from t1)),b) not in (13,t1.c,13))),17)+ -e+t1.f and  -(t1.b) then (t1.d) when t1.b in (select min(a) from t1 union select min(17) from t1) then c else 11 end,c, -13)}
} {600}
do_test randexpr-2.604 {
  db eval {SELECT case when exists(select 1 from t1 where f in (select cast(avg(t1.c) AS integer) from t1 union select min(t1.b) from t1)) then c+d-d when (coalesce((select a from t1 where a<(select abs(count(*)) from t1)),(select count(distinct t1.e) | abs(+ -count(distinct t1.e)*min(t1.b) | count(distinct 11)) from t1))) not in (17,(abs(t1.d)/abs(coalesce((select max(t1.f) from t1 where t1.a*t1.f>=t1.c),t1.f))),t1.e) then t1.c else t1.e end-f FROM t1 WHERE 13*~~(abs(b)/abs(coalesce((select max(t1.a) from t1 where t1.e in ( -(13-17)-b+(e | (abs(t1.e)/abs(case when ~t1.d between t1.e and c and t1.b in (select t1.c from t1 union select b from t1) then 11+t1.b when a=t1.d then b else c end)))*17,t1.c, -17)),13)))-e+b-19>19}
} {}
do_test randexpr-2.605 {
  db eval {SELECT case when exists(select 1 from t1 where f in (select cast(avg(t1.c) AS integer) from t1 union select min(t1.b) from t1)) then c+d-d when (coalesce((select a from t1 where a<(select abs(count(*)) from t1)),(select count(distinct t1.e) | abs(+ -count(distinct t1.e)*min(t1.b) | count(distinct 11)) from t1))) not in (17,(abs(t1.d)/abs(coalesce((select max(t1.f) from t1 where t1.a*t1.f>=t1.c),t1.f))),t1.e) then t1.c else t1.e end-f FROM t1 WHERE NOT (13*~~(abs(b)/abs(coalesce((select max(t1.a) from t1 where t1.e in ( -(13-17)-b+(e | (abs(t1.e)/abs(case when ~t1.d between t1.e and c and t1.b in (select t1.c from t1 union select b from t1) then 11+t1.b when a=t1.d then b else c end)))*17,t1.c, -17)),13)))-e+b-19>19)}
} {-300}
do_test randexpr-2.606 {
  db eval {SELECT case when exists(select 1 from t1 where f in (select cast(avg(t1.c) AS integer) from t1 union select min(t1.b) from t1)) then c+d-d when (coalesce((select a from t1 where a<(select abs(count(*)) from t1)),(select count(distinct t1.e) & abs(+ -count(distinct t1.e)*min(t1.b) & count(distinct 11)) from t1))) not in (17,(abs(t1.d)/abs(coalesce((select max(t1.f) from t1 where t1.a*t1.f>=t1.c),t1.f))),t1.e) then t1.c else t1.e end-f FROM t1 WHERE NOT (13*~~(abs(b)/abs(coalesce((select max(t1.a) from t1 where t1.e in ( -(13-17)-b+(e | (abs(t1.e)/abs(case when ~t1.d between t1.e and c and t1.b in (select t1.c from t1 union select b from t1) then 11+t1.b when a=t1.d then b else c end)))*17,t1.c, -17)),13)))-e+b-19>19)}
} {-100}
do_test randexpr-2.607 {
  db eval {SELECT case when t1.f<d or t1.d>=17 then t1.d-19-11*f*t1.a*t1.b-case (select +cast(avg(a) AS integer) from t1) when 19 then 17 else a end when t1.a between case t1.c when t1.c*t1.c then (d) else t1.c end and c then e else t1.a end FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where (abs(+f-( -~(select count(distinct ~a*e | (select max(f)*count(distinct t1.f) from t1)) |  -max(17)+(count(*))+max(11)+count(distinct t1.e)- - -count(distinct f) from t1)+b*b-t1.c) | t1.e)/abs(17))*c*b in (17,19,t1.e)))}
} {-131999719}
do_test randexpr-2.608 {
  db eval {SELECT case when t1.f<d or t1.d>=17 then t1.d-19-11*f*t1.a*t1.b-case (select +cast(avg(a) AS integer) from t1) when 19 then 17 else a end when t1.a between case t1.c when t1.c*t1.c then (d) else t1.c end and c then e else t1.a end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (abs(+f-( -~(select count(distinct ~a*e | (select max(f)*count(distinct t1.f) from t1)) |  -max(17)+(count(*))+max(11)+count(distinct t1.e)- - -count(distinct f) from t1)+b*b-t1.c) | t1.e)/abs(17))*c*b in (17,19,t1.e))))}
} {}
do_test randexpr-2.609 {
  db eval {SELECT f-~+17*(abs(t1.f)/abs(a*case when case when (case when d>=t1.b or t1.b>=11 then t1.c when t1.b>t1.d then t1.d else t1.a end+17) not in (11,t1.e,17) then c when (t1.b>=a and b>b) then t1.d else d end in (select +abs( -max(t1.e)) from t1 union select count(*) | max(17) from t1) then (t1.a) else a end+(t1.e)))*(11)-f | t1.a-f FROM t1 WHERE ((t1.d>=t1.c))}
} {-500}
do_test randexpr-2.610 {
  db eval {SELECT f-~+17*(abs(t1.f)/abs(a*case when case when (case when d>=t1.b or t1.b>=11 then t1.c when t1.b>t1.d then t1.d else t1.a end+17) not in (11,t1.e,17) then c when (t1.b>=a and b>b) then t1.d else d end in (select +abs( -max(t1.e)) from t1 union select count(*) | max(17) from t1) then (t1.a) else a end+(t1.e)))*(11)-f | t1.a-f FROM t1 WHERE NOT (((t1.d>=t1.c)))}
} {}
do_test randexpr-2.611 {
  db eval {SELECT f-~+17*(abs(t1.f)/abs(a*case when case when (case when d>=t1.b or t1.b>=11 then t1.c when t1.b>t1.d then t1.d else t1.a end+17) not in (11,t1.e,17) then c when (t1.b>=a and b>b) then t1.d else d end in (select +abs( -max(t1.e)) from t1 union select count(*) & max(17) from t1) then (t1.a) else a end+(t1.e)))*(11)-f & t1.a-f FROM t1 WHERE ((t1.d>=t1.c))}
} {0}
do_test randexpr-2.612 {
  db eval {SELECT e+ -((abs(f)/abs(17))) | t1.e*11-coalesce((select max(f) from t1 where ((abs(~+t1.b-coalesce((select coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where ((f) not in (11,19,t1.b)))),11* -t1.b) from t1 where  -a<=c),t1.f))/abs( -b)) between t1.c and e and not exists(select 1 from t1 where f not in ( -t1.f,19,t1.e)))),case t1.c when 19 then (11) else (t1.a) end) | (13) FROM t1 WHERE d<>13 or t1.c in (select count(distinct  -c*11-( -e)-t1.e)-( -case +max(t1.c)-min((select +cast(avg(19*17) AS integer) from t1)* -t1.f)+~(~count(distinct f))+count(*)-cast(avg(t1.c) AS integer) when count(distinct t1.f) then count(distinct e) else  -count(*) end-count(*)) from t1 union select count(distinct 11) from t1)}
} {5597}
do_test randexpr-2.613 {
  db eval {SELECT e+ -((abs(f)/abs(17))) | t1.e*11-coalesce((select max(f) from t1 where ((abs(~+t1.b-coalesce((select coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where ((f) not in (11,19,t1.b)))),11* -t1.b) from t1 where  -a<=c),t1.f))/abs( -b)) between t1.c and e and not exists(select 1 from t1 where f not in ( -t1.f,19,t1.e)))),case t1.c when 19 then (11) else (t1.a) end) | (13) FROM t1 WHERE NOT (d<>13 or t1.c in (select count(distinct  -c*11-( -e)-t1.e)-( -case +max(t1.c)-min((select +cast(avg(19*17) AS integer) from t1)* -t1.f)+~(~count(distinct f))+count(*)-cast(avg(t1.c) AS integer) when count(distinct t1.f) then count(distinct e) else  -count(*) end-count(*)) from t1 union select count(distinct 11) from t1))}
} {}
do_test randexpr-2.614 {
  db eval {SELECT e+ -((abs(f)/abs(17))) & t1.e*11-coalesce((select max(f) from t1 where ((abs(~+t1.b-coalesce((select coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where ((f) not in (11,19,t1.b)))),11* -t1.b) from t1 where  -a<=c),t1.f))/abs( -b)) between t1.c and e and not exists(select 1 from t1 where f not in ( -t1.f,19,t1.e)))),case t1.c when 19 then (11) else (t1.a) end) & (13) FROM t1 WHERE d<>13 or t1.c in (select count(distinct  -c*11-( -e)-t1.e)-( -case +max(t1.c)-min((select +cast(avg(19*17) AS integer) from t1)* -t1.f)+~(~count(distinct f))+count(*)-cast(avg(t1.c) AS integer) when count(distinct t1.f) then count(distinct e) else  -count(*) end-count(*)) from t1 union select count(distinct 11) from t1)}
} {0}
do_test randexpr-2.615 {
  db eval {SELECT coalesce((select case t1.e when t1.d then  -t1.b else b | t1.f end from t1 where case e when case 11 when t1.f then 13 else c end-19 then case  -(select count(distinct 19+ - -d*t1.f+d) from t1)*(abs(c)/abs(coalesce((select max(e) from t1 where not t1.c>t1.d),(17-t1.a)))) when 11 then t1.f else t1.a end else a end<>t1.c),t1.e) FROM t1 WHERE (select case count(*)* -+abs(+count(*)+min(t1.d)) | max(+(17)) when ~count(*)*(count(*))-(count(distinct t1.b)) then count(distinct 11) else max(t1.e) end from t1)>=(abs(coalesce((select t1.b from t1 where (a<f)),b-t1.a))/abs((11*c)-t1.f-b)) and 13 not between (t1.b) and t1.b}
} {728}
do_test randexpr-2.616 {
  db eval {SELECT coalesce((select case t1.e when t1.d then  -t1.b else b | t1.f end from t1 where case e when case 11 when t1.f then 13 else c end-19 then case  -(select count(distinct 19+ - -d*t1.f+d) from t1)*(abs(c)/abs(coalesce((select max(e) from t1 where not t1.c>t1.d),(17-t1.a)))) when 11 then t1.f else t1.a end else a end<>t1.c),t1.e) FROM t1 WHERE NOT ((select case count(*)* -+abs(+count(*)+min(t1.d)) | max(+(17)) when ~count(*)*(count(*))-(count(distinct t1.b)) then count(distinct 11) else max(t1.e) end from t1)>=(abs(coalesce((select t1.b from t1 where (a<f)),b-t1.a))/abs((11*c)-t1.f-b)) and 13 not between (t1.b) and t1.b)}
} {}
do_test randexpr-2.617 {
  db eval {SELECT coalesce((select case t1.e when t1.d then  -t1.b else b & t1.f end from t1 where case e when case 11 when t1.f then 13 else c end-19 then case  -(select count(distinct 19+ - -d*t1.f+d) from t1)*(abs(c)/abs(coalesce((select max(e) from t1 where not t1.c>t1.d),(17-t1.a)))) when 11 then t1.f else t1.a end else a end<>t1.c),t1.e) FROM t1 WHERE (select case count(*)* -+abs(+count(*)+min(t1.d)) | max(+(17)) when ~count(*)*(count(*))-(count(distinct t1.b)) then count(distinct 11) else max(t1.e) end from t1)>=(abs(coalesce((select t1.b from t1 where (a<f)),b-t1.a))/abs((11*c)-t1.f-b)) and 13 not between (t1.b) and t1.b}
} {72}
do_test randexpr-2.618 {
  db eval {SELECT case when 13<11 then 19 when  -(abs(f)/abs(13))*17-13 | case t1.b when ~((select (count(*)-abs(case cast(avg(19) AS integer) when count(distinct 19)*(count(*))-count(*) then count(distinct t1.d) else  -count(distinct 17) end)+max(17)) from t1)) then t1.c else d end+11*t1.e*t1.a | e>(t1.c) then t1.d else t1.d end FROM t1 WHERE case when 17-t1.f in (select case  -~max(c-~e+19)*max(c)*count(*)+~count(distinct f)+case count(distinct d) when max(t1.b) then cast(avg(t1.d) AS integer) else count(distinct d) end-count(distinct d)*max(f)+ -count(distinct 13) when count(*) then ( -min(t1.c)) else min(( -d)) end from t1 union select  -min(c) from t1) then 13 else case t1.c when t1.c then f else d end end-e-(17) in (select c from t1 union select c from t1)}
} {}
do_test randexpr-2.619 {
  db eval {SELECT case when 13<11 then 19 when  -(abs(f)/abs(13))*17-13 | case t1.b when ~((select (count(*)-abs(case cast(avg(19) AS integer) when count(distinct 19)*(count(*))-count(*) then count(distinct t1.d) else  -count(distinct 17) end)+max(17)) from t1)) then t1.c else d end+11*t1.e*t1.a | e>(t1.c) then t1.d else t1.d end FROM t1 WHERE NOT (case when 17-t1.f in (select case  -~max(c-~e+19)*max(c)*count(*)+~count(distinct f)+case count(distinct d) when max(t1.b) then cast(avg(t1.d) AS integer) else count(distinct d) end-count(distinct d)*max(f)+ -count(distinct 13) when count(*) then ( -min(t1.c)) else min(( -d)) end from t1 union select  -min(c) from t1) then 13 else case t1.c when t1.c then f else d end end-e-(17) in (select c from t1 union select c from t1))}
} {400}
do_test randexpr-2.620 {
  db eval {SELECT case when 13<11 then 19 when  -(abs(f)/abs(13))*17-13 & case t1.b when ~((select (count(*)-abs(case cast(avg(19) AS integer) when count(distinct 19)*(count(*))-count(*) then count(distinct t1.d) else  -count(distinct 17) end)+max(17)) from t1)) then t1.c else d end+11*t1.e*t1.a & e>(t1.c) then t1.d else t1.d end FROM t1 WHERE NOT (case when 17-t1.f in (select case  -~max(c-~e+19)*max(c)*count(*)+~count(distinct f)+case count(distinct d) when max(t1.b) then cast(avg(t1.d) AS integer) else count(distinct d) end-count(distinct d)*max(f)+ -count(distinct 13) when count(*) then ( -min(t1.c)) else min(( -d)) end from t1 union select  -min(c) from t1) then 13 else case t1.c when t1.c then f else d end end-e-(17) in (select c from t1 union select c from t1))}
} {400}
do_test randexpr-2.621 {
  db eval {SELECT coalesce((select case ~(case when  -f between t1.e and f then coalesce((select max(t1.a-t1.d) from t1 where d=b),case when (f*11-a-t1.d-c>t1.e and b>=19) then  -+d when t1.b>= -13 then 17 else t1.f end) else (19) end) when 11 then b else f end from t1 where  -t1.e<=t1.d),a) FROM t1 WHERE (+coalesce((select max((abs(19*a-t1.b+t1.a*a)/abs(19))) from t1 where not t1.f in (select case  -count(*)-cast(avg(c) AS integer)+cast(avg(e) AS integer)*count(*) when min(t1.d) then  -(cast(avg(t1.f) AS integer)) else max(13) end+min(t1.d)+count(*) | count(*) | min(11) | count(distinct f) from t1 union select  -count(*) from t1)),e))-t1.e*d | f in (t1.d,e,e)}
} {}
do_test randexpr-2.622 {
  db eval {SELECT coalesce((select case ~(case when  -f between t1.e and f then coalesce((select max(t1.a-t1.d) from t1 where d=b),case when (f*11-a-t1.d-c>t1.e and b>=19) then  -+d when t1.b>= -13 then 17 else t1.f end) else (19) end) when 11 then b else f end from t1 where  -t1.e<=t1.d),a) FROM t1 WHERE NOT ((+coalesce((select max((abs(19*a-t1.b+t1.a*a)/abs(19))) from t1 where not t1.f in (select case  -count(*)-cast(avg(c) AS integer)+cast(avg(e) AS integer)*count(*) when min(t1.d) then  -(cast(avg(t1.f) AS integer)) else max(13) end+min(t1.d)+count(*) | count(*) | min(11) | count(distinct f) from t1 union select  -count(*) from t1)),e))-t1.e*d | f in (t1.d,e,e))}
} {600}
do_test randexpr-2.623 {
  db eval {SELECT case d*t1.f when  -t1.a then t1.c+(coalesce((select max(13+case when  -t1.d*13*c*d | case t1.e when t1.e then t1.b+t1.d else (abs(t1.b)/abs(case when c>b or d in (t1.e,a,d) then d else e end))+f end=t1.f then a when t1.a<=19 then 17 else d end) from t1 where (t1.f>t1.b)),(f))) else f end+t1.a FROM t1 WHERE t1.f+case d when 19 then +t1.c else 19-(abs((t1.b)*~coalesce((select f from t1 where (case when +case when t1.d>13 then t1.e else (t1.a) end<13 then f when t1.c<=e then d else t1.a end*t1.d in (select +case ~min(b) when  -max(13) then cast(avg( -(11)) AS integer) else  -cast(avg(17) AS integer) end+count(distinct t1.a) from t1 union select min(t1.f) from t1))),t1.a))/abs(f)) end+(a) in (b,t1.c,t1.a)}
} {}
do_test randexpr-2.624 {
  db eval {SELECT case d*t1.f when  -t1.a then t1.c+(coalesce((select max(13+case when  -t1.d*13*c*d | case t1.e when t1.e then t1.b+t1.d else (abs(t1.b)/abs(case when c>b or d in (t1.e,a,d) then d else e end))+f end=t1.f then a when t1.a<=19 then 17 else d end) from t1 where (t1.f>t1.b)),(f))) else f end+t1.a FROM t1 WHERE NOT (t1.f+case d when 19 then +t1.c else 19-(abs((t1.b)*~coalesce((select f from t1 where (case when +case when t1.d>13 then t1.e else (t1.a) end<13 then f when t1.c<=e then d else t1.a end*t1.d in (select +case ~min(b) when  -max(13) then cast(avg( -(11)) AS integer) else  -cast(avg(17) AS integer) end+count(distinct t1.a) from t1 union select min(t1.f) from t1))),t1.a))/abs(f)) end+(a) in (b,t1.c,t1.a))}
} {700}
do_test randexpr-2.625 {
  db eval {SELECT case d*t1.f when  -t1.a then t1.c+(coalesce((select max(13+case when  -t1.d*13*c*d & case t1.e when t1.e then t1.b+t1.d else (abs(t1.b)/abs(case when c>b or d in (t1.e,a,d) then d else e end))+f end=t1.f then a when t1.a<=19 then 17 else d end) from t1 where (t1.f>t1.b)),(f))) else f end+t1.a FROM t1 WHERE NOT (t1.f+case d when 19 then +t1.c else 19-(abs((t1.b)*~coalesce((select f from t1 where (case when +case when t1.d>13 then t1.e else (t1.a) end<13 then f when t1.c<=e then d else t1.a end*t1.d in (select +case ~min(b) when  -max(13) then cast(avg( -(11)) AS integer) else  -cast(avg(17) AS integer) end+count(distinct t1.a) from t1 union select min(t1.f) from t1))),t1.a))/abs(f)) end+(a) in (b,t1.c,t1.a))}
} {700}
do_test randexpr-2.626 {
  db eval {SELECT case case when (not exists(select 1 from t1 where  -e in (select t1.c from t1 union select b from t1))) then coalesce((select max(t1.d) from t1 where (17+~t1.c in (select min(t1.b) from t1 union select min(13) from t1))),t1.d)*t1.a+d when not a=a and t1.b not in (b,13,d) or d<13 or t1.f not between t1.c and f or t1.c<>c then t1.e else t1.d end when t1.c then (t1.d) else  -f end FROM t1 WHERE (abs(case when (t1.e in (17,19+t1.b,t1.a)) or (t1.d-19)+(t1.d)+t1.d in (select t1.f from t1 union select t1.e from t1) and 13 in (select t1.c from t1 union select c from t1) or 11 not between e and 17 then  -17-a else d end*13)/abs((b)))*d-f-13 between t1.d and (b)}
} {}
do_test randexpr-2.627 {
  db eval {SELECT case case when (not exists(select 1 from t1 where  -e in (select t1.c from t1 union select b from t1))) then coalesce((select max(t1.d) from t1 where (17+~t1.c in (select min(t1.b) from t1 union select min(13) from t1))),t1.d)*t1.a+d when not a=a and t1.b not in (b,13,d) or d<13 or t1.f not between t1.c and f or t1.c<>c then t1.e else t1.d end when t1.c then (t1.d) else  -f end FROM t1 WHERE NOT ((abs(case when (t1.e in (17,19+t1.b,t1.a)) or (t1.d-19)+(t1.d)+t1.d in (select t1.f from t1 union select t1.e from t1) and 13 in (select t1.c from t1 union select c from t1) or 11 not between e and 17 then  -17-a else d end*13)/abs((b)))*d-f-13 between t1.d and (b))}
} {-600}
do_test randexpr-2.628 {
  db eval {SELECT a+a+(f)-(t1.f+d+t1.e | case when case (13) when t1.c then case coalesce((select  -t1.b-t1.f-13 from t1 where t1.f between t1.d and (a)),t1.b) when b then 13 else t1.f end-f else t1.d end>=e then 19 else t1.c end*t1.c)*f-(t1.d)-b FROM t1 WHERE (t1.b)=t1.a+t1.d-13 | +~f+13 | e+t1.c+coalesce((select t1.a+e from t1 where b in (select (~max(b-t1.b-coalesce((select ((a)) from t1 where e=d or b not between b and t1.e),t1.b)))++~case case count(*) when  -max(t1.c) then min(b) else min(17) end when max( -t1.a) then (min(t1.f)) else max((a)) end*cast(avg(f) AS integer)+max(19) from t1 union select count(distinct f) from t1)),(t1.e)) | t1.b}
} {}
do_test randexpr-2.629 {
  db eval {SELECT a+a+(f)-(t1.f+d+t1.e | case when case (13) when t1.c then case coalesce((select  -t1.b-t1.f-13 from t1 where t1.f between t1.d and (a)),t1.b) when b then 13 else t1.f end-f else t1.d end>=e then 19 else t1.c end*t1.c)*f-(t1.d)-b FROM t1 WHERE NOT ((t1.b)=t1.a+t1.d-13 | +~f+13 | e+t1.c+coalesce((select t1.a+e from t1 where b in (select (~max(b-t1.b-coalesce((select ((a)) from t1 where e=d or b not between b and t1.e),t1.b)))++~case case count(*) when  -max(t1.c) then min(b) else min(17) end when max( -t1.a) then (min(t1.f)) else max((a)) end*cast(avg(f) AS integer)+max(19) from t1 union select count(distinct f) from t1)),(t1.e)) | t1.b)}
} {-54045400}
do_test randexpr-2.630 {
  db eval {SELECT a+a+(f)-(t1.f+d+t1.e & case when case (13) when t1.c then case coalesce((select  -t1.b-t1.f-13 from t1 where t1.f between t1.d and (a)),t1.b) when b then 13 else t1.f end-f else t1.d end>=e then 19 else t1.c end*t1.c)*f-(t1.d)-b FROM t1 WHERE NOT ((t1.b)=t1.a+t1.d-13 | +~f+13 | e+t1.c+coalesce((select t1.a+e from t1 where b in (select (~max(b-t1.b-coalesce((select ((a)) from t1 where e=d or b not between b and t1.e),t1.b)))++~case case count(*) when  -max(t1.c) then min(b) else min(17) end when max( -t1.a) then (min(t1.f)) else max((a)) end*cast(avg(f) AS integer)+max(19) from t1 union select count(distinct f) from t1)),(t1.e)) | t1.b)}
} {-854200}
do_test randexpr-2.631 {
  db eval {SELECT 19-e+t1.d | 19-(abs(11)/abs(t1.b-(select case cast(avg(t1.f) AS integer)-count(*)-count(distinct t1.c)-abs(count(*))-(cast(avg(case when 11<b then d when (c) in (t1.a,t1.b,t1.a) then t1.a else t1.f end) AS integer) | min(t1.a) | (max(t1.a)))+max((t1.d)) when min(t1.a) then  -count(*) else min((e)) end from t1)*19))-c+13 FROM t1 WHERE case when case when not b-(t1.c)-11 in (case  -(b*11) when t1.d then coalesce((select 13 from t1 where e<>b),t1.d) else ~11 end+t1.b,11,19) then t1.a else  -t1.d-case d*a when t1.d then t1.e else 13 end end+e+b>19 then t1.a else t1.f end not between t1.d and e}
} {-1}
do_test randexpr-2.632 {
  db eval {SELECT 19-e+t1.d | 19-(abs(11)/abs(t1.b-(select case cast(avg(t1.f) AS integer)-count(*)-count(distinct t1.c)-abs(count(*))-(cast(avg(case when 11<b then d when (c) in (t1.a,t1.b,t1.a) then t1.a else t1.f end) AS integer) | min(t1.a) | (max(t1.a)))+max((t1.d)) when min(t1.a) then  -count(*) else min((e)) end from t1)*19))-c+13 FROM t1 WHERE NOT (case when case when not b-(t1.c)-11 in (case  -(b*11) when t1.d then coalesce((select 13 from t1 where e<>b),t1.d) else ~11 end+t1.b,11,19) then t1.a else  -t1.d-case d*a when t1.d then t1.e else 13 end end+e+b>19 then t1.a else t1.f end not between t1.d and e)}
} {}
do_test randexpr-2.633 {
  db eval {SELECT 19-e+t1.d & 19-(abs(11)/abs(t1.b-(select case cast(avg(t1.f) AS integer)-count(*)-count(distinct t1.c)-abs(count(*))-(cast(avg(case when 11<b then d when (c) in (t1.a,t1.b,t1.a) then t1.a else t1.f end) AS integer) & min(t1.a) & (max(t1.a)))+max((t1.d)) when min(t1.a) then  -count(*) else min((e)) end from t1)*19))-c+13 FROM t1 WHERE case when case when not b-(t1.c)-11 in (case  -(b*11) when t1.d then coalesce((select 13 from t1 where e<>b),t1.d) else ~11 end+t1.b,11,19) then t1.a else  -t1.d-case d*a when t1.d then t1.e else 13 end end+e+b>19 then t1.a else t1.f end not between t1.d and e}
} {-348}
do_test randexpr-2.634 {
  db eval {SELECT (select abs(abs(~ -min(case t1.a-d when (abs(f)/abs(f+t1.b)) then ~e-11-+ -13*t1.a else 13 end)-count(*)*case + -count(*) when (count(distinct t1.e)) then max(t1.f) else (count(*)* - -+count(*) | min(17)) end+(cast(avg(t1.f) AS integer))+min(d))) from t1) FROM t1 WHERE not t1.f>=t1.a or not exists(select 1 from t1 where 19=17) and 13 in (select abs(count(*) | ((count(*)))) from t1 union select count(distinct  -t1.c | t1.a) | abs(abs(min(d+c))) from t1)}
} {}
do_test randexpr-2.635 {
  db eval {SELECT (select abs(abs(~ -min(case t1.a-d when (abs(f)/abs(f+t1.b)) then ~e-11-+ -13*t1.a else 13 end)-count(*)*case + -count(*) when (count(distinct t1.e)) then max(t1.f) else (count(*)* - -+count(*) | min(17)) end+(cast(avg(t1.f) AS integer))+min(d))) from t1) FROM t1 WHERE NOT (not t1.f>=t1.a or not exists(select 1 from t1 where 19=17) and 13 in (select abs(count(*) | ((count(*)))) from t1 union select count(distinct  -t1.c | t1.a) | abs(abs(min(d+c))) from t1))}
} {995}
do_test randexpr-2.636 {
  db eval {SELECT (select abs(abs(~ -min(case t1.a-d when (abs(f)/abs(f+t1.b)) then ~e-11-+ -13*t1.a else 13 end)-count(*)*case + -count(*) when (count(distinct t1.e)) then max(t1.f) else (count(*)* - -+count(*) & min(17)) end+(cast(avg(t1.f) AS integer))+min(d))) from t1) FROM t1 WHERE NOT (not t1.f>=t1.a or not exists(select 1 from t1 where 19=17) and 13 in (select abs(count(*) | ((count(*)))) from t1 union select count(distinct  -t1.c | t1.a) | abs(abs(min(d+c))) from t1))}
} {1011}
do_test randexpr-2.637 {
  db eval {SELECT (case when not exists(select 1 from t1 where ((not t1.f in (b,17-d,t1.a) and f<t1.f)) or b=t1.e or a in (select  - -count(distinct t1.c) from t1 union select min(11) from t1)) then (select case max( -t1.c) when (~ -count(distinct (b))-count(*))* -count(*) then count(distinct 11) else  -cast(avg(c) AS integer) end | min(t1.e)*cast(avg(13) AS integer) from t1)+b else (abs(t1.c)/abs( -b)) end-t1.b) FROM t1 WHERE exists(select 1 from t1 where (13>=t1.a))}
} {}
do_test randexpr-2.638 {
  db eval {SELECT (case when not exists(select 1 from t1 where ((not t1.f in (b,17-d,t1.a) and f<t1.f)) or b=t1.e or a in (select  - -count(distinct t1.c) from t1 union select min(11) from t1)) then (select case max( -t1.c) when (~ -count(distinct (b))-count(*))* -count(*) then count(distinct 11) else  -cast(avg(c) AS integer) end | min(t1.e)*cast(avg(13) AS integer) from t1)+b else (abs(t1.c)/abs( -b)) end-t1.b) FROM t1 WHERE NOT (exists(select 1 from t1 where (13>=t1.a)))}
} {-12}
do_test randexpr-2.639 {
  db eval {SELECT (case when not exists(select 1 from t1 where ((not t1.f in (b,17-d,t1.a) and f<t1.f)) or b=t1.e or a in (select  - -count(distinct t1.c) from t1 union select min(11) from t1)) then (select case max( -t1.c) when (~ -count(distinct (b))-count(*))* -count(*) then count(distinct 11) else  -cast(avg(c) AS integer) end & min(t1.e)*cast(avg(13) AS integer) from t1)+b else (abs(t1.c)/abs( -b)) end-t1.b) FROM t1 WHERE NOT (exists(select 1 from t1 where (13>=t1.a)))}
} {6212}
do_test randexpr-2.640 {
  db eval {SELECT coalesce((select t1.a from t1 where case when +(abs(e)/abs(19))+(abs(coalesce((select max(b) from t1 where 19 not in (f,(c),11) or  -c not in (t1.f,e,d)),13)*e+t1.f)/abs((d)))<>t1.b then t1.e when t1.d not in (t1.f,17,t1.b) or t1.f not between t1.d and 13 then t1.a else t1.e end>e or not exists(select 1 from t1 where a>=e or not exists(select 1 from t1 where d<>t1.b))),f)+19 FROM t1 WHERE 13 in (case when (select +max( -t1.b+a*case when not 13*13<t1.c then 19 else d end*11*c)+max(b) from t1)<>t1.f and ~e>= -t1.b then t1.c when 11 not between t1.d and e and (d<c) then t1.f else d end | e,a,t1.c)}
} {}
do_test randexpr-2.641 {
  db eval {SELECT coalesce((select t1.a from t1 where case when +(abs(e)/abs(19))+(abs(coalesce((select max(b) from t1 where 19 not in (f,(c),11) or  -c not in (t1.f,e,d)),13)*e+t1.f)/abs((d)))<>t1.b then t1.e when t1.d not in (t1.f,17,t1.b) or t1.f not between t1.d and 13 then t1.a else t1.e end>e or not exists(select 1 from t1 where a>=e or not exists(select 1 from t1 where d<>t1.b))),f)+19 FROM t1 WHERE NOT (13 in (case when (select +max( -t1.b+a*case when not 13*13<t1.c then 19 else d end*11*c)+max(b) from t1)<>t1.f and ~e>= -t1.b then t1.c when 11 not between t1.d and e and (d<c) then t1.f else d end | e,a,t1.c))}
} {119}
do_test randexpr-2.642 {
  db eval {SELECT +coalesce((select case when coalesce((select f+t1.e from t1 where b not in (case when not exists(select 1 from t1 where (f not in (t1.f-t1.b,t1.d,t1.d))) then t1.a when t1.f*t1.c*17>+(t1.e*(d))-t1.d then t1.f else 11 end,17,f)),e) | 19-13<d then t1.a else t1.d end from t1 where d not between c and e),19) FROM t1 WHERE not exists(select 1 from t1 where ((t1.c not between case d-c+(t1.b) when d then 17 else 13 end+f and coalesce((select t1.f from t1 where ((t1.f*case when not exists(select 1 from t1 where t1.f>=t1.b) then (select max(11)-(count(distinct f)) from t1) else t1.a end+c in (t1.d,e,f) or e in (11,11,11)))),b)*t1.b*11))) and t1.b>=a}
} {}
do_test randexpr-2.643 {
  db eval {SELECT +coalesce((select case when coalesce((select f+t1.e from t1 where b not in (case when not exists(select 1 from t1 where (f not in (t1.f-t1.b,t1.d,t1.d))) then t1.a when t1.f*t1.c*17>+(t1.e*(d))-t1.d then t1.f else 11 end,17,f)),e) | 19-13<d then t1.a else t1.d end from t1 where d not between c and e),19) FROM t1 WHERE NOT (not exists(select 1 from t1 where ((t1.c not between case d-c+(t1.b) when d then 17 else 13 end+f and coalesce((select t1.f from t1 where ((t1.f*case when not exists(select 1 from t1 where t1.f>=t1.b) then (select max(11)-(count(distinct f)) from t1) else t1.a end+c in (t1.d,e,f) or e in (11,11,11)))),b)*t1.b*11))) and t1.b>=a)}
} {19}
do_test randexpr-2.644 {
  db eval {SELECT +coalesce((select case when coalesce((select f+t1.e from t1 where b not in (case when not exists(select 1 from t1 where (f not in (t1.f-t1.b,t1.d,t1.d))) then t1.a when t1.f*t1.c*17>+(t1.e*(d))-t1.d then t1.f else 11 end,17,f)),e) & 19-13<d then t1.a else t1.d end from t1 where d not between c and e),19) FROM t1 WHERE NOT (not exists(select 1 from t1 where ((t1.c not between case d-c+(t1.b) when d then 17 else 13 end+f and coalesce((select t1.f from t1 where ((t1.f*case when not exists(select 1 from t1 where t1.f>=t1.b) then (select max(11)-(count(distinct f)) from t1) else t1.a end+c in (t1.d,e,f) or e in (11,11,11)))),b)*t1.b*11))) and t1.b>=a)}
} {19}
do_test randexpr-2.645 {
  db eval {SELECT (case when case 19 when b then 13 else t1.e end in (select (c) from t1 union select a from t1) then 11 else (d*coalesce((select t1.b from t1 where 19 | (t1.c)+case when  -17>t1.a then t1.a when (19>=13) then t1.a else t1.e end=f and (e)>a or 11 in (select e from t1 union select t1.b from t1)),t1.d*t1.e))+c+a end) FROM t1 WHERE case case when case when not (abs(t1.d | f)/abs(a)) in (d,a,t1.c) then  -d when (not exists(select 1 from t1 where f>=c)) then t1.a else e end+t1.d not in (t1.b,(t1.f),11) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b in (19,t1.c,13))) then b+t1.c when t1.d>=t1.a then t1.c else (c) end when (13) then t1.e else b end in (t1.a,t1.b,13)}
} {80000400}
do_test randexpr-2.646 {
  db eval {SELECT (case when case 19 when b then 13 else t1.e end in (select (c) from t1 union select a from t1) then 11 else (d*coalesce((select t1.b from t1 where 19 | (t1.c)+case when  -17>t1.a then t1.a when (19>=13) then t1.a else t1.e end=f and (e)>a or 11 in (select e from t1 union select t1.b from t1)),t1.d*t1.e))+c+a end) FROM t1 WHERE NOT (case case when case when not (abs(t1.d | f)/abs(a)) in (d,a,t1.c) then  -d when (not exists(select 1 from t1 where f>=c)) then t1.a else e end+t1.d not in (t1.b,(t1.f),11) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b in (19,t1.c,13))) then b+t1.c when t1.d>=t1.a then t1.c else (c) end when (13) then t1.e else b end in (t1.a,t1.b,13))}
} {}
do_test randexpr-2.647 {
  db eval {SELECT (case when case 19 when b then 13 else t1.e end in (select (c) from t1 union select a from t1) then 11 else (d*coalesce((select t1.b from t1 where 19 & (t1.c)+case when  -17>t1.a then t1.a when (19>=13) then t1.a else t1.e end=f and (e)>a or 11 in (select e from t1 union select t1.b from t1)),t1.d*t1.e))+c+a end) FROM t1 WHERE case case when case when not (abs(t1.d | f)/abs(a)) in (d,a,t1.c) then  -d when (not exists(select 1 from t1 where f>=c)) then t1.a else e end+t1.d not in (t1.b,(t1.f),11) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b in (19,t1.c,13))) then b+t1.c when t1.d>=t1.a then t1.c else (c) end when (13) then t1.e else b end in (t1.a,t1.b,13)}
} {80000400}
do_test randexpr-2.648 {
  db eval {SELECT case when 19<=19 then d when not exists(select 1 from t1 where case case when case when (select  -min(((t1.f)))*((cast(avg(t1.d) AS integer))) from t1) in (select t1.a-b from t1 union select 17 from t1) then f when (19 not between t1.c and 13 and f>13) then d else a end | b-t1.b in (t1.e,t1.f, -d) then t1.e when c<t1.e then ( -b) else (c) end-t1.e | (17)+17 when 13 then t1.a else d end+19>=17) then t1.e else t1.e end FROM t1 WHERE coalesce((select +a- -t1.d*b*coalesce((select t1.c from t1 where t1.a in (select (abs(11)/abs(case when not exists(select 1 from t1 where +e=t1.e) then case t1.b when a-c then b else b end when (not exists(select 1 from t1 where 19 in (select 13 from t1 union select t1.b from t1))) and e in (t1.e, -f,e) then 19 else t1.a end)) from t1 union select b from t1)),17)*d from t1 where t1.f not in (t1.a,(t1.b),t1.d)),13)<=(13)}
} {}
do_test randexpr-2.649 {
  db eval {SELECT case when 19<=19 then d when not exists(select 1 from t1 where case case when case when (select  -min(((t1.f)))*((cast(avg(t1.d) AS integer))) from t1) in (select t1.a-b from t1 union select 17 from t1) then f when (19 not between t1.c and 13 and f>13) then d else a end | b-t1.b in (t1.e,t1.f, -d) then t1.e when c<t1.e then ( -b) else (c) end-t1.e | (17)+17 when 13 then t1.a else d end+19>=17) then t1.e else t1.e end FROM t1 WHERE NOT (coalesce((select +a- -t1.d*b*coalesce((select t1.c from t1 where t1.a in (select (abs(11)/abs(case when not exists(select 1 from t1 where +e=t1.e) then case t1.b when a-c then b else b end when (not exists(select 1 from t1 where 19 in (select 13 from t1 union select t1.b from t1))) and e in (t1.e, -f,e) then 19 else t1.a end)) from t1 union select b from t1)),17)*d from t1 where t1.f not in (t1.a,(t1.b),t1.d)),13)<=(13))}
} {400}
do_test randexpr-2.650 {
  db eval {SELECT case when 19<=19 then d when not exists(select 1 from t1 where case case when case when (select  -min(((t1.f)))*((cast(avg(t1.d) AS integer))) from t1) in (select t1.a-b from t1 union select 17 from t1) then f when (19 not between t1.c and 13 and f>13) then d else a end & b-t1.b in (t1.e,t1.f, -d) then t1.e when c<t1.e then ( -b) else (c) end-t1.e & (17)+17 when 13 then t1.a else d end+19>=17) then t1.e else t1.e end FROM t1 WHERE NOT (coalesce((select +a- -t1.d*b*coalesce((select t1.c from t1 where t1.a in (select (abs(11)/abs(case when not exists(select 1 from t1 where +e=t1.e) then case t1.b when a-c then b else b end when (not exists(select 1 from t1 where 19 in (select 13 from t1 union select t1.b from t1))) and e in (t1.e, -f,e) then 19 else t1.a end)) from t1 union select b from t1)),17)*d from t1 where t1.f not in (t1.a,(t1.b),t1.d)),13)<=(13))}
} {400}
do_test randexpr-2.651 {
  db eval {SELECT case when c<=t1.b*e+case when not exists(select 1 from t1 where a+ -t1.f= -t1.e*(17)+f and 19 in (select  -13 from t1 union select t1.f from t1) and 19>=t1.a or  -11 in (select a from t1 union select 17 from t1)) then t1.f else 19 end+t1.d or ((c))<>a then t1.f-t1.c when c not between ((t1.b)) and f then a else d end FROM t1 WHERE coalesce((select t1.e from t1 where t1.c in (t1.a,f,coalesce((select max( -f) from t1 where t1.f<coalesce((select (select cast(avg(b) AS integer) from t1) from t1 where a>=(abs(13)/abs(~19+(abs((select count(distinct t1.f) from t1))/abs(coalesce((select 13 from t1 where d | 17*c*a*b+d<>t1.a),b)-(b)))))),b)),19))),t1.e)*c<>t1.e}
} {300}
do_test randexpr-2.652 {
  db eval {SELECT case when c<=t1.b*e+case when not exists(select 1 from t1 where a+ -t1.f= -t1.e*(17)+f and 19 in (select  -13 from t1 union select t1.f from t1) and 19>=t1.a or  -11 in (select a from t1 union select 17 from t1)) then t1.f else 19 end+t1.d or ((c))<>a then t1.f-t1.c when c not between ((t1.b)) and f then a else d end FROM t1 WHERE NOT (coalesce((select t1.e from t1 where t1.c in (t1.a,f,coalesce((select max( -f) from t1 where t1.f<coalesce((select (select cast(avg(b) AS integer) from t1) from t1 where a>=(abs(13)/abs(~19+(abs((select count(distinct t1.f) from t1))/abs(coalesce((select 13 from t1 where d | 17*c*a*b+d<>t1.a),b)-(b)))))),b)),19))),t1.e)*c<>t1.e)}
} {}
do_test randexpr-2.653 {
  db eval {SELECT case when t1.c>=13 or d in (select case ((case min(t1.f)+min(f) when max( -11) then min(19) else cast(avg( -t1.d) AS integer) end | count(*))) when count(distinct 13) then  -cast(avg( -t1.e) AS integer) else min(e) end from t1 union select max( -a) from t1) then case when +c-11+(t1.d)<e or f in (select 17 from t1 union select 13 from t1) then f when t1.c in (select t1.c from t1 union select 19 from t1) then t1.f else  -f end when e in (a,19,t1.e) then t1.d else f end FROM t1 WHERE (c<=t1.f or 11<case when t1.b+ -~a*case when exists(select 1 from t1 where case when b | 17 not between 17 and c then 11 else t1.e end in (d,a,b)) then t1.b when t1.b not in (t1.f,b,c) then 11 else b end>13 then d when not exists(select 1 from t1 where t1.c in (f,t1.b,t1.b)) then a else 19 end*t1.c and t1.d>=19)}
} {600}
do_test randexpr-2.654 {
  db eval {SELECT case when t1.c>=13 or d in (select case ((case min(t1.f)+min(f) when max( -11) then min(19) else cast(avg( -t1.d) AS integer) end | count(*))) when count(distinct 13) then  -cast(avg( -t1.e) AS integer) else min(e) end from t1 union select max( -a) from t1) then case when +c-11+(t1.d)<e or f in (select 17 from t1 union select 13 from t1) then f when t1.c in (select t1.c from t1 union select 19 from t1) then t1.f else  -f end when e in (a,19,t1.e) then t1.d else f end FROM t1 WHERE NOT ((c<=t1.f or 11<case when t1.b+ -~a*case when exists(select 1 from t1 where case when b | 17 not between 17 and c then 11 else t1.e end in (d,a,b)) then t1.b when t1.b not in (t1.f,b,c) then 11 else b end>13 then d when not exists(select 1 from t1 where t1.c in (f,t1.b,t1.b)) then a else 19 end*t1.c and t1.d>=19))}
} {}
do_test randexpr-2.655 {
  db eval {SELECT case when t1.c>=13 or d in (select case ((case min(t1.f)+min(f) when max( -11) then min(19) else cast(avg( -t1.d) AS integer) end & count(*))) when count(distinct 13) then  -cast(avg( -t1.e) AS integer) else min(e) end from t1 union select max( -a) from t1) then case when +c-11+(t1.d)<e or f in (select 17 from t1 union select 13 from t1) then f when t1.c in (select t1.c from t1 union select 19 from t1) then t1.f else  -f end when e in (a,19,t1.e) then t1.d else f end FROM t1 WHERE (c<=t1.f or 11<case when t1.b+ -~a*case when exists(select 1 from t1 where case when b | 17 not between 17 and c then 11 else t1.e end in (d,a,b)) then t1.b when t1.b not in (t1.f,b,c) then 11 else b end>13 then d when not exists(select 1 from t1 where t1.c in (f,t1.b,t1.b)) then a else 19 end*t1.c and t1.d>=19)}
} {600}
do_test randexpr-2.656 {
  db eval {SELECT t1.a+(e*a)*t1.d+(abs(d)/abs(case when case f when t1.a then t1.f else d end*t1.f*t1.e*c*17+coalesce((select t1.d from t1 where c<=~t1.f | 13),e)*t1.a<case when 13 between a and 19 and c<a then t1.b else f end then t1.e when exists(select 1 from t1 where ((t1.b)=t1.f)) then t1.c else f end)) FROM t1 WHERE d*19 between 11 and f}
} {}
do_test randexpr-2.657 {
  db eval {SELECT t1.a+(e*a)*t1.d+(abs(d)/abs(case when case f when t1.a then t1.f else d end*t1.f*t1.e*c*17+coalesce((select t1.d from t1 where c<=~t1.f | 13),e)*t1.a<case when 13 between a and 19 and c<a then t1.b else f end then t1.e when exists(select 1 from t1 where ((t1.b)=t1.f)) then t1.c else f end)) FROM t1 WHERE NOT (d*19 between 11 and f)}
} {20000100}
do_test randexpr-2.658 {
  db eval {SELECT t1.a+(e*a)*t1.d+(abs(d)/abs(case when case f when t1.a then t1.f else d end*t1.f*t1.e*c*17+coalesce((select t1.d from t1 where c<=~t1.f & 13),e)*t1.a<case when 13 between a and 19 and c<a then t1.b else f end then t1.e when exists(select 1 from t1 where ((t1.b)=t1.f)) then t1.c else f end)) FROM t1 WHERE NOT (d*19 between 11 and f)}
} {20000100}
do_test randexpr-2.659 {
  db eval {SELECT case f when (abs(t1.f)/abs(case when d+case when exists(select 1 from t1 where exists(select 1 from t1 where exists(select 1 from t1 where case when not case when +11>=t1.d then t1.d when (t1.b)<>17 or t1.b<=t1.c then a else (e) end in (select min(t1.e) from t1 union select abs( -max((17))) from t1) then c when 19<>17 then 13 else  -d end>t1.d))) then 17 when t1.a<=13 then coalesce((select (17) | t1.c from t1 where t1.e>d),b) else 13 end in (select min(f) from t1 union select count(*) from t1) then 19 else t1.f end)) then t1.f else f end FROM t1 WHERE coalesce((select max(11 | e+case c*t1.b+13 when 19 | ~t1.f+case when d>11 then t1.f-(case t1.d when a then 19+t1.f else t1.b end) else d-case e when c+t1.a then 13 else case when not exists(select 1 from t1 where (t1.d)<>17) then d when b in ( -f,11,17) then 11 else t1.f end end end+d then e else t1.a end) from t1 where t1.a>= -11),b)>t1.c}
} {600}
do_test randexpr-2.660 {
  db eval {SELECT case f when (abs(t1.f)/abs(case when d+case when exists(select 1 from t1 where exists(select 1 from t1 where exists(select 1 from t1 where case when not case when +11>=t1.d then t1.d when (t1.b)<>17 or t1.b<=t1.c then a else (e) end in (select min(t1.e) from t1 union select abs( -max((17))) from t1) then c when 19<>17 then 13 else  -d end>t1.d))) then 17 when t1.a<=13 then coalesce((select (17) | t1.c from t1 where t1.e>d),b) else 13 end in (select min(f) from t1 union select count(*) from t1) then 19 else t1.f end)) then t1.f else f end FROM t1 WHERE NOT (coalesce((select max(11 | e+case c*t1.b+13 when 19 | ~t1.f+case when d>11 then t1.f-(case t1.d when a then 19+t1.f else t1.b end) else d-case e when c+t1.a then 13 else case when not exists(select 1 from t1 where (t1.d)<>17) then d when b in ( -f,11,17) then 11 else t1.f end end end+d then e else t1.a end) from t1 where t1.a>= -11),b)>t1.c)}
} {}
do_test randexpr-2.661 {
  db eval {SELECT case f when (abs(t1.f)/abs(case when d+case when exists(select 1 from t1 where exists(select 1 from t1 where exists(select 1 from t1 where case when not case when +11>=t1.d then t1.d when (t1.b)<>17 or t1.b<=t1.c then a else (e) end in (select min(t1.e) from t1 union select abs( -max((17))) from t1) then c when 19<>17 then 13 else  -d end>t1.d))) then 17 when t1.a<=13 then coalesce((select (17) & t1.c from t1 where t1.e>d),b) else 13 end in (select min(f) from t1 union select count(*) from t1) then 19 else t1.f end)) then t1.f else f end FROM t1 WHERE coalesce((select max(11 | e+case c*t1.b+13 when 19 | ~t1.f+case when d>11 then t1.f-(case t1.d when a then 19+t1.f else t1.b end) else d-case e when c+t1.a then 13 else case when not exists(select 1 from t1 where (t1.d)<>17) then d when b in ( -f,11,17) then 11 else t1.f end end end+d then e else t1.a end) from t1 where t1.a>= -11),b)>t1.c}
} {600}
do_test randexpr-2.662 {
  db eval {SELECT (select abs(case max(t1.b)-(min(17))* -count(distinct case when case t1.f when t1.b then case e when c then t1.c else c end else t1.b end>=t1.e then d else e end) | ~+count(distinct t1.c)-(abs( -count(*))- -max(c)) | count(distinct t1.c) when count(distinct ( -t1.c)) then count(*) else max(t1.b) end* -count(*))-cast(avg( -11) AS integer)*min(19)+max(e) from t1) FROM t1 WHERE t1.a+t1.a>13}
} {909}
do_test randexpr-2.663 {
  db eval {SELECT (select abs(case max(t1.b)-(min(17))* -count(distinct case when case t1.f when t1.b then case e when c then t1.c else c end else t1.b end>=t1.e then d else e end) | ~+count(distinct t1.c)-(abs( -count(*))- -max(c)) | count(distinct t1.c) when count(distinct ( -t1.c)) then count(*) else max(t1.b) end* -count(*))-cast(avg( -11) AS integer)*min(19)+max(e) from t1) FROM t1 WHERE NOT (t1.a+t1.a>13)}
} {}
do_test randexpr-2.664 {
  db eval {SELECT (select abs(case max(t1.b)-(min(17))* -count(distinct case when case t1.f when t1.b then case e when c then t1.c else c end else t1.b end>=t1.e then d else e end) & ~+count(distinct t1.c)-(abs( -count(*))- -max(c)) & count(distinct t1.c) when count(distinct ( -t1.c)) then count(*) else max(t1.b) end* -count(*))-cast(avg( -11) AS integer)*min(19)+max(e) from t1) FROM t1 WHERE t1.a+t1.a>13}
} {710}
do_test randexpr-2.665 {
  db eval {SELECT (t1.d- -c+e-f++case when a between case f when case when ~~~11-coalesce((select b from t1 where coalesce((select max(e) from t1 where not t1.d>= -11),a)+a between 11 and t1.a), -d)*17-a-13 | 13>=17 then a else 11 end then t1.a else t1.d end and t1.f then 19 else t1.a end) FROM t1 WHERE t1.f<> -13}
} {700}
do_test randexpr-2.666 {
  db eval {SELECT (t1.d- -c+e-f++case when a between case f when case when ~~~11-coalesce((select b from t1 where coalesce((select max(e) from t1 where not t1.d>= -11),a)+a between 11 and t1.a), -d)*17-a-13 | 13>=17 then a else 11 end then t1.a else t1.d end and t1.f then 19 else t1.a end) FROM t1 WHERE NOT (t1.f<> -13)}
} {}
do_test randexpr-2.667 {
  db eval {SELECT (t1.d- -c+e-f++case when a between case f when case when ~~~11-coalesce((select b from t1 where coalesce((select max(e) from t1 where not t1.d>= -11),a)+a between 11 and t1.a), -d)*17-a-13 & 13>=17 then a else 11 end then t1.a else t1.d end and t1.f then 19 else t1.a end) FROM t1 WHERE t1.f<> -13}
} {700}
do_test randexpr-2.668 {
  db eval {SELECT (abs(case when (c<=b+t1.b) then  -11+t1.a-d when b*(select count(distinct e)*+max(~t1.a*case when (select count(*)*+min(t1.b)+max(t1.a) from t1) in (c,t1.d,t1.d) then (select  -(count(*)) from t1) else e end) from t1)<=a-11 then 11 else t1.e end)/abs(t1.e))+c FROM t1 WHERE a<+coalesce((select t1.f from t1 where exists(select 1 from t1 where ~case when (e not between t1.a-~case d when b then  -c else 13 end and d) then 11 else a end+17-f-a*19*t1.f not in (f, -t1.d,11))),c)-t1.f and (t1.d<17) and t1.f=c or f<= -e}
} {}
do_test randexpr-2.669 {
  db eval {SELECT (abs(case when (c<=b+t1.b) then  -11+t1.a-d when b*(select count(distinct e)*+max(~t1.a*case when (select count(*)*+min(t1.b)+max(t1.a) from t1) in (c,t1.d,t1.d) then (select  -(count(*)) from t1) else e end) from t1)<=a-11 then 11 else t1.e end)/abs(t1.e))+c FROM t1 WHERE NOT (a<+coalesce((select t1.f from t1 where exists(select 1 from t1 where ~case when (e not between t1.a-~case d when b then  -c else 13 end and d) then 11 else a end+17-f-a*19*t1.f not in (f, -t1.d,11))),c)-t1.f and (t1.d<17) and t1.f=c or f<= -e)}
} {300}
do_test randexpr-2.670 {
  db eval {SELECT case when case when c in (select abs((max(d*case t1.b when t1.b+t1.f then d else b end+d))- - -~count(*)*cast(avg(t1.b) AS integer)-min(d)*cast(avg(b) AS integer)*count(*)) from t1 union select  -count(distinct t1.f) from t1) then case when 17 between t1.f and 11 then c else d end when t1.c>=13 then a else a end<=c then t1.d else 13 end+e FROM t1 WHERE t1.f between  -11 and b}
} {}
do_test randexpr-2.671 {
  db eval {SELECT case when case when c in (select abs((max(d*case t1.b when t1.b+t1.f then d else b end+d))- - -~count(*)*cast(avg(t1.b) AS integer)-min(d)*cast(avg(b) AS integer)*count(*)) from t1 union select  -count(distinct t1.f) from t1) then case when 17 between t1.f and 11 then c else d end when t1.c>=13 then a else a end<=c then t1.d else 13 end+e FROM t1 WHERE NOT (t1.f between  -11 and b)}
} {900}
do_test randexpr-2.672 {
  db eval {SELECT b*~~t1.b*(a-t1.c+t1.b)+13-+~case t1.b when d then case 17*13 when t1.e then case when case when t1.c<>~(11) then t1.e else coalesce((select max( -c) from t1 where (f<>e)),t1.f) end<=a then (t1.c) else t1.c end else  -f end else 13 end*t1.e-t1.f | 13 FROM t1 WHERE b between (d) and t1.c*(abs(t1.c-13 | t1.d+t1.a)/abs(13))}
} {}
do_test randexpr-2.673 {
  db eval {SELECT b*~~t1.b*(a-t1.c+t1.b)+13-+~case t1.b when d then case 17*13 when t1.e then case when case when t1.c<>~(11) then t1.e else coalesce((select max( -c) from t1 where (f<>e)),t1.f) end<=a then (t1.c) else t1.c end else  -f end else 13 end*t1.e-t1.f | 13 FROM t1 WHERE NOT (b between (d) and t1.c*(abs(t1.c-13 | t1.d+t1.a)/abs(13)))}
} {6413}
do_test randexpr-2.674 {
  db eval {SELECT b*~~t1.b*(a-t1.c+t1.b)+13-+~case t1.b when d then case 17*13 when t1.e then case when case when t1.c<>~(11) then t1.e else coalesce((select max( -c) from t1 where (f<>e)),t1.f) end<=a then (t1.c) else t1.c end else  -f end else 13 end*t1.e-t1.f & 13 FROM t1 WHERE NOT (b between (d) and t1.c*(abs(t1.c-13 | t1.d+t1.a)/abs(13)))}
} {13}
do_test randexpr-2.675 {
  db eval {SELECT case when t1.b in (select case 13 when 13 | t1.e then case +(select (min((e)))-case count(*) | max(t1.b*d+17+e) when abs(count(distinct (11))*count(*)-cast(avg(a) AS integer) | max( -t1.a)) then (count(distinct 13)) else  -(cast(avg(t1.b) AS integer)) end from t1) when (select count(distinct e) from t1) then t1.e else a+(t1.b) end-d-t1.d else t1.e end from t1 union select (f) from t1) then t1.b else (b) end FROM t1 WHERE b in (select a from t1 union select 11+t1.e from t1)}
} {}
do_test randexpr-2.676 {
  db eval {SELECT case when t1.b in (select case 13 when 13 | t1.e then case +(select (min((e)))-case count(*) | max(t1.b*d+17+e) when abs(count(distinct (11))*count(*)-cast(avg(a) AS integer) | max( -t1.a)) then (count(distinct 13)) else  -(cast(avg(t1.b) AS integer)) end from t1) when (select count(distinct e) from t1) then t1.e else a+(t1.b) end-d-t1.d else t1.e end from t1 union select (f) from t1) then t1.b else (b) end FROM t1 WHERE NOT (b in (select a from t1 union select 11+t1.e from t1))}
} {200}
do_test randexpr-2.677 {
  db eval {SELECT case when t1.b in (select case 13 when 13 & t1.e then case +(select (min((e)))-case count(*) & max(t1.b*d+17+e) when abs(count(distinct (11))*count(*)-cast(avg(a) AS integer) & max( -t1.a)) then (count(distinct 13)) else  -(cast(avg(t1.b) AS integer)) end from t1) when (select count(distinct e) from t1) then t1.e else a+(t1.b) end-d-t1.d else t1.e end from t1 union select (f) from t1) then t1.b else (b) end FROM t1 WHERE NOT (b in (select a from t1 union select 11+t1.e from t1))}
} {200}
do_test randexpr-2.678 {
  db eval {SELECT coalesce((select 17 from t1 where d between 17 and 13),case when t1.f in (select c+a from t1 union select a from t1) and (abs(f)/abs(t1.b))-t1.e>=case when not exists(select 1 from t1 where t1.e>(select count(distinct t1.f) from t1)) then t1.f when (11)-~t1.f<case 13 when f then 19 else coalesce((select  -t1.c from t1 where 11<=t1.e),e) end then t1.e else 13 end*t1.e then t1.f else b end) FROM t1 WHERE  -coalesce((select max(11) from t1 where (abs( -case 19 when (abs(coalesce((select max(coalesce((select 13 from t1 where a>e),b)) from t1 where (t1.f) in (13,e,t1.c) or t1.c>13),t1.b))/abs(13)) then t1.b else d end)/abs(13)) in (t1.f,t1.e,t1.a) or 17 between 13 and f or (f>11 and t1.f<t1.b)),case when 19 not between  -17 and d then 11 when t1.c=d then t1.a else t1.f end)>=t1.e}
} {}
do_test randexpr-2.679 {
  db eval {SELECT coalesce((select 17 from t1 where d between 17 and 13),case when t1.f in (select c+a from t1 union select a from t1) and (abs(f)/abs(t1.b))-t1.e>=case when not exists(select 1 from t1 where t1.e>(select count(distinct t1.f) from t1)) then t1.f when (11)-~t1.f<case 13 when f then 19 else coalesce((select  -t1.c from t1 where 11<=t1.e),e) end then t1.e else 13 end*t1.e then t1.f else b end) FROM t1 WHERE NOT ( -coalesce((select max(11) from t1 where (abs( -case 19 when (abs(coalesce((select max(coalesce((select 13 from t1 where a>e),b)) from t1 where (t1.f) in (13,e,t1.c) or t1.c>13),t1.b))/abs(13)) then t1.b else d end)/abs(13)) in (t1.f,t1.e,t1.a) or 17 between 13 and f or (f>11 and t1.f<t1.b)),case when 19 not between  -17 and d then 11 when t1.c=d then t1.a else t1.f end)>=t1.e)}
} {200}
do_test randexpr-2.680 {
  db eval {SELECT (select min(19-case 19 when  -t1.a+13 then coalesce((select c from t1 where (abs(13)/abs(11))>=coalesce((select f+b*+t1.c from t1 where t1.c=+11+t1.e),11) or (e in (a,a,13) and t1.a<f) and t1.c not between t1.f and  -b),t1.b) else t1.b end) from t1) | f FROM t1 WHERE case 13-t1.e when 13 then f*c else ~f+(abs(t1.f | t1.e-c)/abs((coalesce((select max((select  -cast(avg(b) AS integer) from t1)-b) from t1 where 17 in (c,( -(f)),11) and 17>=f or t1.a=t1.e),t1.f)*t1.a+t1.f)*19)) end*f-t1.f in (select d from t1 union select t1.c from t1) and b in (t1.f,t1.d,c)}
} {}
do_test randexpr-2.681 {
  db eval {SELECT (select min(19-case 19 when  -t1.a+13 then coalesce((select c from t1 where (abs(13)/abs(11))>=coalesce((select f+b*+t1.c from t1 where t1.c=+11+t1.e),11) or (e in (a,a,13) and t1.a<f) and t1.c not between t1.f and  -b),t1.b) else t1.b end) from t1) | f FROM t1 WHERE NOT (case 13-t1.e when 13 then f*c else ~f+(abs(t1.f | t1.e-c)/abs((coalesce((select max((select  -cast(avg(b) AS integer) from t1)-b) from t1 where 17 in (c,( -(f)),11) and 17>=f or t1.a=t1.e),t1.f)*t1.a+t1.f)*19)) end*f-t1.f in (select d from t1 union select t1.c from t1) and b in (t1.f,t1.d,c))}
} {-165}
do_test randexpr-2.682 {
  db eval {SELECT (select min(19-case 19 when  -t1.a+13 then coalesce((select c from t1 where (abs(13)/abs(11))>=coalesce((select f+b*+t1.c from t1 where t1.c=+11+t1.e),11) or (e in (a,a,13) and t1.a<f) and t1.c not between t1.f and  -b),t1.b) else t1.b end) from t1) & f FROM t1 WHERE NOT (case 13-t1.e when 13 then f*c else ~f+(abs(t1.f | t1.e-c)/abs((coalesce((select max((select  -cast(avg(b) AS integer) from t1)-b) from t1 where 17 in (c,( -(f)),11) and 17>=f or t1.a=t1.e),t1.f)*t1.a+t1.f)*19)) end*f-t1.f in (select d from t1 union select t1.c from t1) and b in (t1.f,t1.d,c))}
} {584}
do_test randexpr-2.683 {
  db eval {SELECT ~case when exists(select 1 from t1 where t1.c not between case case ~t1.b*19 when b then t1.c*t1.e else t1.d end when c then case ++13 when case when a+d+~~11 not between e and  -19 then 19 else b end then t1.d else 19 end else t1.a end and d) then 19 when c in (select abs(count(distinct 17)) from t1 union select max(t1.b) from t1) then (d) else t1.e end | 19 FROM t1 WHERE t1.d between 11 and ~19-coalesce((select d from t1 where (d>=c)),t1.d)*+t1.e+t1.e}
} {}
do_test randexpr-2.684 {
  db eval {SELECT ~case when exists(select 1 from t1 where t1.c not between case case ~t1.b*19 when b then t1.c*t1.e else t1.d end when c then case ++13 when case when a+d+~~11 not between e and  -19 then 19 else b end then t1.d else 19 end else t1.a end and d) then 19 when c in (select abs(count(distinct 17)) from t1 union select max(t1.b) from t1) then (d) else t1.e end | 19 FROM t1 WHERE NOT (t1.d between 11 and ~19-coalesce((select d from t1 where (d>=c)),t1.d)*+t1.e+t1.e)}
} {-485}
do_test randexpr-2.685 {
  db eval {SELECT ~case when exists(select 1 from t1 where t1.c not between case case ~t1.b*19 when b then t1.c*t1.e else t1.d end when c then case ++13 when case when a+d+~~11 not between e and  -19 then 19 else b end then t1.d else 19 end else t1.a end and d) then 19 when c in (select abs(count(distinct 17)) from t1 union select max(t1.b) from t1) then (d) else t1.e end & 19 FROM t1 WHERE NOT (t1.d between 11 and ~19-coalesce((select d from t1 where (d>=c)),t1.d)*+t1.e+t1.e)}
} {3}
do_test randexpr-2.686 {
  db eval {SELECT +t1.b-17*11-coalesce((select coalesce((select max(t1.f+a-t1.c+b) from t1 where 17* -b+t1.e=13),coalesce((select +t1.f*coalesce((select b from t1 where 19 between  -a and c),t1.d) from t1 where 17<>b),17)*11) from t1 where f<c),e) |  -t1.e-b-t1.b-t1.e FROM t1 WHERE t1.b=11}
} {}
do_test randexpr-2.687 {
  db eval {SELECT +t1.b-17*11-coalesce((select coalesce((select max(t1.f+a-t1.c+b) from t1 where 17* -b+t1.e=13),coalesce((select +t1.f*coalesce((select b from t1 where 19 between  -a and c),t1.d) from t1 where 17<>b),17)*11) from t1 where f<c),e) |  -t1.e-b-t1.b-t1.e FROM t1 WHERE NOT (t1.b=11)}
} {-359}
do_test randexpr-2.688 {
  db eval {SELECT +t1.b-17*11-coalesce((select coalesce((select max(t1.f+a-t1.c+b) from t1 where 17* -b+t1.e=13),coalesce((select +t1.f*coalesce((select b from t1 where 19 between  -a and c),t1.d) from t1 where 17<>b),17)*11) from t1 where f<c),e) &  -t1.e-b-t1.b-t1.e FROM t1 WHERE NOT (t1.b=11)}
} {-1528}
do_test randexpr-2.689 {
  db eval {SELECT  -d+t1.d-t1.a-+t1.c-(select +min((abs(+(case when b>=case when b not between  -t1.f and c then e else f end or a<=11 or t1.e between a and 11 or t1.d not in (b,d,d) then case when f>=c then t1.c else 19 end when t1.e=a then e else t1.e end) | f)/abs(t1.a))) from t1)+e* -t1.a+f+d FROM t1 WHERE t1.b<=t1.c+ -(abs(t1.b)/abs(case t1.b+t1.e when 11 then t1.c else 17 end))*coalesce((select coalesce((select coalesce((select 13 from t1 where b=t1.b),f) | t1.f-11 from t1 where (t1.c) in (select +min(19)*(~max(b)-max(11))*max(11) from t1 union select min(f) from t1)),t1.f) from t1 where f in (select case count(distinct 19) when max(t1.b) then  -cast(avg(t1.e) AS integer) else cast(avg(b) AS integer) end from t1 union select count(*) from t1)),t1.a)}
} {}
do_test randexpr-2.690 {
  db eval {SELECT  -d+t1.d-t1.a-+t1.c-(select +min((abs(+(case when b>=case when b not between  -t1.f and c then e else f end or a<=11 or t1.e between a and 11 or t1.d not in (b,d,d) then case when f>=c then t1.c else 19 end when t1.e=a then e else t1.e end) | f)/abs(t1.a))) from t1)+e* -t1.a+f+d FROM t1 WHERE NOT (t1.b<=t1.c+ -(abs(t1.b)/abs(case t1.b+t1.e when 11 then t1.c else 17 end))*coalesce((select coalesce((select coalesce((select 13 from t1 where b=t1.b),f) | t1.f-11 from t1 where (t1.c) in (select +min(19)*(~max(b)-max(11))*max(11) from t1 union select min(f) from t1)),t1.f) from t1 where f in (select case count(distinct 19) when max(t1.b) then  -cast(avg(t1.e) AS integer) else cast(avg(b) AS integer) end from t1 union select count(*) from t1)),t1.a))}
} {-49410}
do_test randexpr-2.691 {
  db eval {SELECT  -d+t1.d-t1.a-+t1.c-(select +min((abs(+(case when b>=case when b not between  -t1.f and c then e else f end or a<=11 or t1.e between a and 11 or t1.d not in (b,d,d) then case when f>=c then t1.c else 19 end when t1.e=a then e else t1.e end) & f)/abs(t1.a))) from t1)+e* -t1.a+f+d FROM t1 WHERE NOT (t1.b<=t1.c+ -(abs(t1.b)/abs(case t1.b+t1.e when 11 then t1.c else 17 end))*coalesce((select coalesce((select coalesce((select 13 from t1 where b=t1.b),f) | t1.f-11 from t1 where (t1.c) in (select +min(19)*(~max(b)-max(11))*max(11) from t1 union select min(f) from t1)),t1.f) from t1 where f in (select case count(distinct 19) when max(t1.b) then  -cast(avg(t1.e) AS integer) else cast(avg(b) AS integer) end from t1 union select count(*) from t1)),t1.a))}
} {-49400}
do_test randexpr-2.692 {
  db eval {SELECT ~case +t1.a when t1.a then 19 else coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where t1.b*f<>e and e not in (17,t1.c-case when t1.e<19 then t1.c else (abs(t1.c)/abs(d*coalesce((select t1.e from t1 where exists(select 1 from t1 where t1.c in (select t1.f from t1 union select 11 from t1)) or t1.a<=t1.d),a))) end*t1.e,t1.e))),coalesce((select max(a) from t1 where (b) in ((11),e,b)),17)) end FROM t1 WHERE not (c)+c*d>t1.e and exists(select 1 from t1 where d*coalesce((select +case when ((select cast(avg((c)) AS integer)- -cast(avg(a) AS integer) from t1) in (select min(b)-count(*) from t1 union select count(distinct 19) from t1)) or not t1.b between 19 and 19 then t1.c else coalesce((select e from t1 where t1.e>=e),c) end from t1 where ( -f)<a),17)>19) and 17<> -t1.e and b>=a}
} {}
do_test randexpr-2.693 {
  db eval {SELECT ~case +t1.a when t1.a then 19 else coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where t1.b*f<>e and e not in (17,t1.c-case when t1.e<19 then t1.c else (abs(t1.c)/abs(d*coalesce((select t1.e from t1 where exists(select 1 from t1 where t1.c in (select t1.f from t1 union select 11 from t1)) or t1.a<=t1.d),a))) end*t1.e,t1.e))),coalesce((select max(a) from t1 where (b) in ((11),e,b)),17)) end FROM t1 WHERE NOT (not (c)+c*d>t1.e and exists(select 1 from t1 where d*coalesce((select +case when ((select cast(avg((c)) AS integer)- -cast(avg(a) AS integer) from t1) in (select min(b)-count(*) from t1 union select count(distinct 19) from t1)) or not t1.b between 19 and 19 then t1.c else coalesce((select e from t1 where t1.e>=e),c) end from t1 where ( -f)<a),17)>19) and 17<> -t1.e and b>=a)}
} {-20}
do_test randexpr-2.694 {
  db eval {SELECT coalesce((select max(t1.d-t1.e) from t1 where not exists(select 1 from t1 where c*+19<=(d)) or c+e not between a and ~f*t1.f*case when t1.e<> -coalesce((select case when ((e between t1.d and f)) then  -(17) | b else t1.d end from t1 where b in (select t1.c from t1 union select 11 from t1)),d) then t1.d when e not in ( -t1.b,t1.c,(t1.e)) then t1.c else d end), -b) FROM t1 WHERE t1.d<>d}
} {}
do_test randexpr-2.695 {
  db eval {SELECT coalesce((select max(t1.d-t1.e) from t1 where not exists(select 1 from t1 where c*+19<=(d)) or c+e not between a and ~f*t1.f*case when t1.e<> -coalesce((select case when ((e between t1.d and f)) then  -(17) | b else t1.d end from t1 where b in (select t1.c from t1 union select 11 from t1)),d) then t1.d when e not in ( -t1.b,t1.c,(t1.e)) then t1.c else d end), -b) FROM t1 WHERE NOT (t1.d<>d)}
} {-100}
do_test randexpr-2.696 {
  db eval {SELECT coalesce((select max(t1.d-t1.e) from t1 where not exists(select 1 from t1 where c*+19<=(d)) or c+e not between a and ~f*t1.f*case when t1.e<> -coalesce((select case when ((e between t1.d and f)) then  -(17) & b else t1.d end from t1 where b in (select t1.c from t1 union select 11 from t1)),d) then t1.d when e not in ( -t1.b,t1.c,(t1.e)) then t1.c else d end), -b) FROM t1 WHERE NOT (t1.d<>d)}
} {-100}
do_test randexpr-2.697 {
  db eval {SELECT case when a in (select max(17) from t1 union select abs(count(*)) from t1) then t1.a- -e-t1.d | e- -t1.f*19+(select  -abs(max(a))*count(distinct e)*max(19) from t1)-11-13-d*11+t1.a else d end-b FROM t1 WHERE t1.e in (select (abs(case when (abs(f)/abs((select ~min(a) from t1)+coalesce((select t1.f from t1 where 11<>t1.b),19)))*t1.e+ -t1.d | e<=t1.f then  -e when (b)>t1.a then t1.d else t1.a end)/abs(11)) from t1 union select 13 from t1) and f not between t1.b and e or not exists(select 1 from t1 where not exists(select 1 from t1 where 19<c)) and t1.c not in (t1.d,e,t1.a)}
} {200}
do_test randexpr-2.698 {
  db eval {SELECT case when a in (select max(17) from t1 union select abs(count(*)) from t1) then t1.a- -e-t1.d | e- -t1.f*19+(select  -abs(max(a))*count(distinct e)*max(19) from t1)-11-13-d*11+t1.a else d end-b FROM t1 WHERE NOT (t1.e in (select (abs(case when (abs(f)/abs((select ~min(a) from t1)+coalesce((select t1.f from t1 where 11<>t1.b),19)))*t1.e+ -t1.d | e<=t1.f then  -e when (b)>t1.a then t1.d else t1.a end)/abs(11)) from t1 union select 13 from t1) and f not between t1.b and e or not exists(select 1 from t1 where not exists(select 1 from t1 where 19<c)) and t1.c not in (t1.d,e,t1.a))}
} {}
do_test randexpr-2.699 {
  db eval {SELECT case when a in (select max(17) from t1 union select abs(count(*)) from t1) then t1.a- -e-t1.d & e- -t1.f*19+(select  -abs(max(a))*count(distinct e)*max(19) from t1)-11-13-d*11+t1.a else d end-b FROM t1 WHERE t1.e in (select (abs(case when (abs(f)/abs((select ~min(a) from t1)+coalesce((select t1.f from t1 where 11<>t1.b),19)))*t1.e+ -t1.d | e<=t1.f then  -e when (b)>t1.a then t1.d else t1.a end)/abs(11)) from t1 union select 13 from t1) and f not between t1.b and e or not exists(select 1 from t1 where not exists(select 1 from t1 where 19<c)) and t1.c not in (t1.d,e,t1.a)}
} {200}
do_test randexpr-2.700 {
  db eval {SELECT coalesce((select f from t1 where (case t1.a*t1.b*c when t1.d*coalesce((select max(coalesce((select 19 from t1 where t1.b in (select max(~case  -e when c+coalesce((select max(e) from t1 where (t1.d) not between c and t1.f),17) then c else 13 end) from t1 union select count(distinct a) from t1)),t1.f)) from t1 where f>t1.d),c) then 19 else 17 end between t1.b and t1.f and t1.d not in (c,e,(17)))),11) FROM t1 WHERE (((select min(t1.f) from t1)<=e))}
} {}
do_test randexpr-2.701 {
  db eval {SELECT coalesce((select f from t1 where (case t1.a*t1.b*c when t1.d*coalesce((select max(coalesce((select 19 from t1 where t1.b in (select max(~case  -e when c+coalesce((select max(e) from t1 where (t1.d) not between c and t1.f),17) then c else 13 end) from t1 union select count(distinct a) from t1)),t1.f)) from t1 where f>t1.d),c) then 19 else 17 end between t1.b and t1.f and t1.d not in (c,e,(17)))),11) FROM t1 WHERE NOT ((((select min(t1.f) from t1)<=e)))}
} {11}
do_test randexpr-2.702 {
  db eval {SELECT case t1.a when e*t1.e then case when exists(select 1 from t1 where (coalesce((select max(17) from t1 where (not (case when not a>=13*c then t1.f else (11)*t1.b end between 11 and t1.f or t1.c>(t1.c)))),t1.b*~t1.c)*b*d>=13)) then (abs(17)/abs(e)) else b end else t1.f end | t1.c+t1.f FROM t1 WHERE coalesce((select max(11) from t1 where c-d not between ~case when (select +~count(distinct t1.f)*cast(avg(t1.e) AS integer) from t1)+19 not in (t1.e,t1.f,t1.a) then t1.a when a in (e,t1.d,d) then t1.b else t1.e end and t1.b and c>=e or (t1.d<>b) and not exists(select 1 from t1 where (t1.f between 13 and a))),t1.a)-e<=t1.e}
} {988}
do_test randexpr-2.703 {
  db eval {SELECT case t1.a when e*t1.e then case when exists(select 1 from t1 where (coalesce((select max(17) from t1 where (not (case when not a>=13*c then t1.f else (11)*t1.b end between 11 and t1.f or t1.c>(t1.c)))),t1.b*~t1.c)*b*d>=13)) then (abs(17)/abs(e)) else b end else t1.f end | t1.c+t1.f FROM t1 WHERE NOT (coalesce((select max(11) from t1 where c-d not between ~case when (select +~count(distinct t1.f)*cast(avg(t1.e) AS integer) from t1)+19 not in (t1.e,t1.f,t1.a) then t1.a when a in (e,t1.d,d) then t1.b else t1.e end and t1.b and c>=e or (t1.d<>b) and not exists(select 1 from t1 where (t1.f between 13 and a))),t1.a)-e<=t1.e)}
} {}
do_test randexpr-2.704 {
  db eval {SELECT case t1.a when e*t1.e then case when exists(select 1 from t1 where (coalesce((select max(17) from t1 where (not (case when not a>=13*c then t1.f else (11)*t1.b end between 11 and t1.f or t1.c>(t1.c)))),t1.b*~t1.c)*b*d>=13)) then (abs(17)/abs(e)) else b end else t1.f end & t1.c+t1.f FROM t1 WHERE coalesce((select max(11) from t1 where c-d not between ~case when (select +~count(distinct t1.f)*cast(avg(t1.e) AS integer) from t1)+19 not in (t1.e,t1.f,t1.a) then t1.a when a in (e,t1.d,d) then t1.b else t1.e end and t1.b and c>=e or (t1.d<>b) and not exists(select 1 from t1 where (t1.f between 13 and a))),t1.a)-e<=t1.e}
} {512}
do_test randexpr-2.705 {
  db eval {SELECT coalesce((select max(t1.e+(t1.b)) from t1 where 17<=t1.d-(select ~+cast(avg(b) AS integer) | case  -case cast(avg(t1.e) AS integer) when min((abs((a))/abs(t1.e))) then cast(avg(t1.c) AS integer)+count(*) else min(d) end when max(t1.e) then count(*) else ( -count(*)) end-min(t1.b)-count(distinct  -a)*count(*) from t1) | c+coalesce((select f from t1 where (19=t1.c-t1.b)),t1.f+17)),f) FROM t1 WHERE c not between (abs(t1.f)/abs(case when t1.f+e<=t1.c+t1.d then case when d in (select +count(distinct case when  -t1.a*19-t1.c not between 11 and c then t1.e when (19<>19) then t1.d else d end) from t1 union select cast(avg(e) AS integer) from t1) then t1.e when c in (select count(*) from t1 union select cast(avg(f) AS integer)* - - -cast(avg(t1.e) AS integer) from t1) then b else (t1.b) end when not (11>=11) then  -t1.e else b end)) and t1.f}
} {}
do_test randexpr-2.706 {
  db eval {SELECT coalesce((select max(t1.e+(t1.b)) from t1 where 17<=t1.d-(select ~+cast(avg(b) AS integer) | case  -case cast(avg(t1.e) AS integer) when min((abs((a))/abs(t1.e))) then cast(avg(t1.c) AS integer)+count(*) else min(d) end when max(t1.e) then count(*) else ( -count(*)) end-min(t1.b)-count(distinct  -a)*count(*) from t1) | c+coalesce((select f from t1 where (19=t1.c-t1.b)),t1.f+17)),f) FROM t1 WHERE NOT (c not between (abs(t1.f)/abs(case when t1.f+e<=t1.c+t1.d then case when d in (select +count(distinct case when  -t1.a*19-t1.c not between 11 and c then t1.e when (19<>19) then t1.d else d end) from t1 union select cast(avg(e) AS integer) from t1) then t1.e when c in (select count(*) from t1 union select cast(avg(f) AS integer)* - - -cast(avg(t1.e) AS integer) from t1) then b else (t1.b) end when not (11>=11) then  -t1.e else b end)) and t1.f)}
} {700}
do_test randexpr-2.707 {
  db eval {SELECT coalesce((select max(t1.e+(t1.b)) from t1 where 17<=t1.d-(select ~+cast(avg(b) AS integer) & case  -case cast(avg(t1.e) AS integer) when min((abs((a))/abs(t1.e))) then cast(avg(t1.c) AS integer)+count(*) else min(d) end when max(t1.e) then count(*) else ( -count(*)) end-min(t1.b)-count(distinct  -a)*count(*) from t1) & c+coalesce((select f from t1 where (19=t1.c-t1.b)),t1.f+17)),f) FROM t1 WHERE NOT (c not between (abs(t1.f)/abs(case when t1.f+e<=t1.c+t1.d then case when d in (select +count(distinct case when  -t1.a*19-t1.c not between 11 and c then t1.e when (19<>19) then t1.d else d end) from t1 union select cast(avg(e) AS integer) from t1) then t1.e when c in (select count(*) from t1 union select cast(avg(f) AS integer)* - - -cast(avg(t1.e) AS integer) from t1) then b else (t1.b) end when not (11>=11) then  -t1.e else b end)) and t1.f)}
} {700}
do_test randexpr-2.708 {
  db eval {SELECT 17-(abs(case when t1.e<+(select count(distinct  -f) from t1)+t1.b then +case when t1.b not in (coalesce((select max(coalesce((select case when 17<e then 13 else t1.e end+t1.b from t1 where not (t1.f) between d and ((t1.d))),t1.f)) from t1 where t1.f>=a and 13 not in (b,t1.f,d)),b),t1.d, -13) then (e) else (13) end-19 when not exists(select 1 from t1 where 19<>f) then c else t1.e end | t1.d)/abs((13)))*f FROM t1 WHERE coalesce((select f from t1 where coalesce((select ~d*19-d*~case c when case a when t1.e*19 then (select  - -( -max(t1.f))*cast(avg(t1.c) AS integer) from t1) else 13 end*13-11 then  -11 else t1.f end | t1.e | t1.f*19 from t1 where t1.f>t1.a),b)*b not in (17,17,t1.e)),t1.a)-b*d>=11}
} {}
do_test randexpr-2.709 {
  db eval {SELECT 17-(abs(case when t1.e<+(select count(distinct  -f) from t1)+t1.b then +case when t1.b not in (coalesce((select max(coalesce((select case when 17<e then 13 else t1.e end+t1.b from t1 where not (t1.f) between d and ((t1.d))),t1.f)) from t1 where t1.f>=a and 13 not in (b,t1.f,d)),b),t1.d, -13) then (e) else (13) end-19 when not exists(select 1 from t1 where 19<>f) then c else t1.e end | t1.d)/abs((13)))*f FROM t1 WHERE NOT (coalesce((select f from t1 where coalesce((select ~d*19-d*~case c when case a when t1.e*19 then (select  - -( -max(t1.f))*cast(avg(t1.c) AS integer) from t1) else 13 end*13-11 then  -11 else t1.f end | t1.e | t1.f*19 from t1 where t1.f>t1.a),b)*b not in (17,17,t1.e)),t1.a)-b*d>=11)}
} {-22783}
do_test randexpr-2.710 {
  db eval {SELECT 17-(abs(case when t1.e<+(select count(distinct  -f) from t1)+t1.b then +case when t1.b not in (coalesce((select max(coalesce((select case when 17<e then 13 else t1.e end+t1.b from t1 where not (t1.f) between d and ((t1.d))),t1.f)) from t1 where t1.f>=a and 13 not in (b,t1.f,d)),b),t1.d, -13) then (e) else (13) end-19 when not exists(select 1 from t1 where 19<>f) then c else t1.e end & t1.d)/abs((13)))*f FROM t1 WHERE NOT (coalesce((select f from t1 where coalesce((select ~d*19-d*~case c when case a when t1.e*19 then (select  - -( -max(t1.f))*cast(avg(t1.c) AS integer) from t1) else 13 end*13-11 then  -11 else t1.f end | t1.e | t1.f*19 from t1 where t1.f>t1.a),b)*b not in (17,17,t1.e)),t1.a)-b*d>=11)}
} {-17983}
do_test randexpr-2.711 {
  db eval {SELECT (select cast(avg(case when (e=case when e>d and case coalesce((select ((t1.b)) from t1 where 17<=t1.c),a) when t1.b then f else d end*b>t1.d then (t1.a) else 11 end or 17 not in (19,f,d) or not not exists(select 1 from t1 where  - -e>=13)) and 17 in ( -t1.b,c,t1.f) then t1.c when t1.c not between t1.f and 17 then t1.c else d end) AS integer) from t1)+b+a FROM t1 WHERE (((coalesce((select coalesce((select max(19) from t1 where d between ~t1.a and 11),c+d-coalesce((select e from t1 where (abs(b)/abs(coalesce((select 13 from t1 where case when (17) not in (19,t1.c,t1.b) or 17 not in (t1.b,t1.f,t1.e) then 11 else 19 end<>t1.c),11)*17))=t1.b),d)) from t1 where d not in (b,b,d)),t1.a) not between b and b) and d>=t1.d) and t1.d in (13,c,t1.b))}
} {}
do_test randexpr-2.712 {
  db eval {SELECT (select cast(avg(case when (e=case when e>d and case coalesce((select ((t1.b)) from t1 where 17<=t1.c),a) when t1.b then f else d end*b>t1.d then (t1.a) else 11 end or 17 not in (19,f,d) or not not exists(select 1 from t1 where  - -e>=13)) and 17 in ( -t1.b,c,t1.f) then t1.c when t1.c not between t1.f and 17 then t1.c else d end) AS integer) from t1)+b+a FROM t1 WHERE NOT ((((coalesce((select coalesce((select max(19) from t1 where d between ~t1.a and 11),c+d-coalesce((select e from t1 where (abs(b)/abs(coalesce((select 13 from t1 where case when (17) not in (19,t1.c,t1.b) or 17 not in (t1.b,t1.f,t1.e) then 11 else 19 end<>t1.c),11)*17))=t1.b),d)) from t1 where d not in (b,b,d)),t1.a) not between b and b) and d>=t1.d) and t1.d in (13,c,t1.b)))}
} {600}
do_test randexpr-2.713 {
  db eval {SELECT (abs((select +abs(+max(b) | abs(~~count(distinct  -19))) from t1))/abs(coalesce((select max(19*11*d) from t1 where (t1.e<=t1.e)),t1.f)))+case e when (t1.e) then d else c*13 | 11 end FROM t1 WHERE t1.d>=(case when (select count(*) from t1)*t1.c*t1.e+e<>t1.e*13 | f+(select (min(13+t1.b) | ~+~count(*)) from t1)*e*coalesce((select max(19+t1.a) from t1 where t1.e in (select +(count(distinct b))+count(*) from t1 union select ( -min(17)) from t1)),t1.a)-t1.d* -t1.e then e else  -a end)}
} {}
do_test randexpr-2.714 {
  db eval {SELECT (abs((select +abs(+max(b) | abs(~~count(distinct  -19))) from t1))/abs(coalesce((select max(19*11*d) from t1 where (t1.e<=t1.e)),t1.f)))+case e when (t1.e) then d else c*13 | 11 end FROM t1 WHERE NOT (t1.d>=(case when (select count(*) from t1)*t1.c*t1.e+e<>t1.e*13 | f+(select (min(13+t1.b) | ~+~count(*)) from t1)*e*coalesce((select max(19+t1.a) from t1 where t1.e in (select +(count(distinct b))+count(*) from t1 union select ( -min(17)) from t1)),t1.a)-t1.d* -t1.e then e else  -a end))}
} {400}
do_test randexpr-2.715 {
  db eval {SELECT (abs((select +abs(+max(b) & abs(~~count(distinct  -19))) from t1))/abs(coalesce((select max(19*11*d) from t1 where (t1.e<=t1.e)),t1.f)))+case e when (t1.e) then d else c*13 & 11 end FROM t1 WHERE NOT (t1.d>=(case when (select count(*) from t1)*t1.c*t1.e+e<>t1.e*13 | f+(select (min(13+t1.b) | ~+~count(*)) from t1)*e*coalesce((select max(19+t1.a) from t1 where t1.e in (select +(count(distinct b))+count(*) from t1 union select ( -min(17)) from t1)),t1.a)-t1.d* -t1.e then e else  -a end))}
} {400}
do_test randexpr-2.716 {
  db eval {SELECT  -17+c-(abs(t1.a)/abs(t1.c))-case when t1.a<>c then case when exists(select 1 from t1 where 11 not between + -d and d and 13 not between 13 and 17 or not  -f<=19 or (t1.a)<a or t1.a>(11)) and 11<t1.b then t1.e else coalesce((select case when t1.f not in (c,t1.c,t1.e) then (select +count(*) from t1) when  -t1.f>=t1.f then b else a end from t1 where t1.e in (e,t1.c,b)),11) end else  -17 end FROM t1 WHERE not exists(select 1 from t1 where t1.a>=coalesce((select t1.f from t1 where + -19*t1.c<~+t1.a*13),a))}
} {-217}
do_test randexpr-2.717 {
  db eval {SELECT  -17+c-(abs(t1.a)/abs(t1.c))-case when t1.a<>c then case when exists(select 1 from t1 where 11 not between + -d and d and 13 not between 13 and 17 or not  -f<=19 or (t1.a)<a or t1.a>(11)) and 11<t1.b then t1.e else coalesce((select case when t1.f not in (c,t1.c,t1.e) then (select +count(*) from t1) when  -t1.f>=t1.f then b else a end from t1 where t1.e in (e,t1.c,b)),11) end else  -17 end FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a>=coalesce((select t1.f from t1 where + -19*t1.c<~+t1.a*13),a)))}
} {}
do_test randexpr-2.718 {
  db eval {SELECT f*19+17*(select max(b)+count(*)- -~count(*)-min(case when (e<=b-t1.b) then case when t1.b>t1.a or f not in (c, -c,f) or f in (e,13,13) then t1.b else t1.b end else a end*a) from t1)+t1.f*(abs(case b | t1.c+t1.a when ((f)) then f else c end+b)/abs(17))-(c) FROM t1 WHERE t1.e>11}
} {-138117}
do_test randexpr-2.719 {
  db eval {SELECT f*19+17*(select max(b)+count(*)- -~count(*)-min(case when (e<=b-t1.b) then case when t1.b>t1.a or f not in (c, -c,f) or f in (e,13,13) then t1.b else t1.b end else a end*a) from t1)+t1.f*(abs(case b | t1.c+t1.a when ((f)) then f else c end+b)/abs(17))-(c) FROM t1 WHERE NOT (t1.e>11)}
} {}
do_test randexpr-2.720 {
  db eval {SELECT f*19+17*(select max(b)+count(*)- -~count(*)-min(case when (e<=b-t1.b) then case when t1.b>t1.a or f not in (c, -c,f) or f in (e,13,13) then t1.b else t1.b end else a end*a) from t1)+t1.f*(abs(case b & t1.c+t1.a when ((f)) then f else c end+b)/abs(17))-(c) FROM t1 WHERE t1.e>11}
} {-138117}
do_test randexpr-2.721 {
  db eval {SELECT  -case when case when (case (abs(13)/abs(t1.e-13*t1.f)) when b- -13+t1.d then 11 else a end) not between t1.b and b then t1.c when d not between t1.e and t1.c or t1.f in (select 11 from t1 union select f from t1) and 17=d then 13 else t1.a end+11>=f then a when f>b then t1.d else 17 end-t1.e FROM t1 WHERE (case when not exists(select 1 from t1 where exists(select 1 from t1 where (abs(b*d-t1.e)/abs(t1.b))>c)) and t1.d in (13,t1.f,17) then e else ( - -t1.a)+11+c end*t1.b in (select (case  -+min(17) when +count(*) | min(t1.a) | cast(avg(11) AS integer) then cast(avg(11) AS integer) else cast(avg(a) AS integer) end)-cast(avg(t1.a) AS integer) from t1 union select (min(t1.e)) from t1) or not t1.c in ((f),t1.c,(t1.e)))}
} {}
do_test randexpr-2.722 {
  db eval {SELECT  -case when case when (case (abs(13)/abs(t1.e-13*t1.f)) when b- -13+t1.d then 11 else a end) not between t1.b and b then t1.c when d not between t1.e and t1.c or t1.f in (select 11 from t1 union select f from t1) and 17=d then 13 else t1.a end+11>=f then a when f>b then t1.d else 17 end-t1.e FROM t1 WHERE NOT ((case when not exists(select 1 from t1 where exists(select 1 from t1 where (abs(b*d-t1.e)/abs(t1.b))>c)) and t1.d in (13,t1.f,17) then e else ( - -t1.a)+11+c end*t1.b in (select (case  -+min(17) when +count(*) | min(t1.a) | cast(avg(11) AS integer) then cast(avg(11) AS integer) else cast(avg(a) AS integer) end)-cast(avg(t1.a) AS integer) from t1 union select (min(t1.e)) from t1) or not t1.c in ((f),t1.c,(t1.e))))}
} {-900}
do_test randexpr-2.723 {
  db eval {SELECT case t1.a when a then t1.c else  -case coalesce((select t1.e from t1 where (abs(case when not (a*case when f>=f*13-19 then t1.e else +t1.a end=t1.a) then (select min(a)+min(+19) from t1) else case when t1.a=(f) then c else c end+17 end)/abs(t1.e)) between 17 and 13),e) when 17 then 13 else t1.d end end FROM t1 WHERE 17 in (select case cast(avg(b+b) AS integer) when abs(abs(count(*))) then min(case t1.c+t1.b+t1.e+17+case case when t1.b<>17 and t1.e>=t1.b then b else  -t1.f end when 11 then 13 else f end*t1.f*b when 19 then  -11 else t1.d end- -t1.f) else min(t1.c) end from t1 union select abs(abs(count(distinct b)*max(t1.d))+count(distinct 13)-count(*)) from t1)}
} {}
do_test randexpr-2.724 {
  db eval {SELECT case t1.a when a then t1.c else  -case coalesce((select t1.e from t1 where (abs(case when not (a*case when f>=f*13-19 then t1.e else +t1.a end=t1.a) then (select min(a)+min(+19) from t1) else case when t1.a=(f) then c else c end+17 end)/abs(t1.e)) between 17 and 13),e) when 17 then 13 else t1.d end end FROM t1 WHERE NOT (17 in (select case cast(avg(b+b) AS integer) when abs(abs(count(*))) then min(case t1.c+t1.b+t1.e+17+case case when t1.b<>17 and t1.e>=t1.b then b else  -t1.f end when 11 then 13 else f end*t1.f*b when 19 then  -11 else t1.d end- -t1.f) else min(t1.c) end from t1 union select abs(abs(count(distinct b)*max(t1.d))+count(distinct 13)-count(*)) from t1))}
} {300}
do_test randexpr-2.725 {
  db eval {SELECT case when coalesce((select e from t1 where coalesce((select coalesce((select max( -coalesce((select max(case when exists(select 1 from t1 where not exists(select 1 from t1 where b in (select e+d from t1 union select t1.e from t1))) then t1.d else t1.f end) from t1 where exists(select 1 from t1 where f not in ((c),a,11))),e)) from t1 where t1.b=t1.f and e<d or d>t1.b),t1.b) from t1 where t1.a in (select a from t1 union select  -f from t1)),17)>=17),((b))) not in (t1.e,b,e) then 19 when not  -a<=f then t1.f else t1.b end FROM t1 WHERE 13=t1.d}
} {}
do_test randexpr-2.726 {
  db eval {SELECT case when coalesce((select e from t1 where coalesce((select coalesce((select max( -coalesce((select max(case when exists(select 1 from t1 where not exists(select 1 from t1 where b in (select e+d from t1 union select t1.e from t1))) then t1.d else t1.f end) from t1 where exists(select 1 from t1 where f not in ((c),a,11))),e)) from t1 where t1.b=t1.f and e<d or d>t1.b),t1.b) from t1 where t1.a in (select a from t1 union select  -f from t1)),17)>=17),((b))) not in (t1.e,b,e) then 19 when not  -a<=f then t1.f else t1.b end FROM t1 WHERE NOT (13=t1.d)}
} {200}
do_test randexpr-2.727 {
  db eval {SELECT 19*13+((abs(case when 17*d in ((abs((case (abs((abs((select abs(min(d))+cast(avg(19) AS integer) from t1) | t1.d | 11 | b)/abs(19)))/abs(b)) when 11 then a else e end))/abs(13)),t1.f,b) then t1.b when t1.c>=t1.d then (t1.c) else c end*d)/abs(f))) | t1.a-a-17 FROM t1 WHERE ( -t1.d+coalesce((select max(11) from t1 where t1.c between 13 and t1.d and case d when b then 13+ -~t1.a else +case when coalesce((select max((select +case (cast(avg(e) AS integer)) when count(distinct t1.a) then count(*) else min(( -d)) end from t1)-+a+d) from t1 where (e in (17,t1.e, -a))),b)<>f then a else 11 end end<(t1.e)),t1.d) in (select t1.a from t1 union select b from t1))}
} {}
do_test randexpr-2.728 {
  db eval {SELECT 19*13+((abs(case when 17*d in ((abs((case (abs((abs((select abs(min(d))+cast(avg(19) AS integer) from t1) | t1.d | 11 | b)/abs(19)))/abs(b)) when 11 then a else e end))/abs(13)),t1.f,b) then t1.b when t1.c>=t1.d then (t1.c) else c end*d)/abs(f))) | t1.a-a-17 FROM t1 WHERE NOT (( -t1.d+coalesce((select max(11) from t1 where t1.c between 13 and t1.d and case d when b then 13+ -~t1.a else +case when coalesce((select max((select +case (cast(avg(e) AS integer)) when count(distinct t1.a) then count(*) else min(( -d)) end from t1)-+a+d) from t1 where (e in (17,t1.e, -a))),b)<>f then a else 11 end end<(t1.e)),t1.d) in (select t1.a from t1 union select b from t1)))}
} {-1}
do_test randexpr-2.729 {
  db eval {SELECT 19*13+((abs(case when 17*d in ((abs((case (abs((abs((select abs(min(d))+cast(avg(19) AS integer) from t1) & t1.d & 11 & b)/abs(19)))/abs(b)) when 11 then a else e end))/abs(13)),t1.f,b) then t1.b when t1.c>=t1.d then (t1.c) else c end*d)/abs(f))) & t1.a-a-17 FROM t1 WHERE NOT (( -t1.d+coalesce((select max(11) from t1 where t1.c between 13 and t1.d and case d when b then 13+ -~t1.a else +case when coalesce((select max((select +case (cast(avg(e) AS integer)) when count(distinct t1.a) then count(*) else min(( -d)) end from t1)-+a+d) from t1 where (e in (17,t1.e, -a))),b)<>f then a else 11 end end<(t1.e)),t1.d) in (select t1.a from t1 union select b from t1)))}
} {431}
do_test randexpr-2.730 {
  db eval {SELECT case when (19*b)+11*~f-coalesce((select max(11) from t1 where f<>case when case 17 when 11 then 17 else c end-11 in (t1.c,c,t1.e) and 19=t1.a or 17<=e or e<=19 then 19 | c when t1.b=t1.f then d else 19 end or t1.e not in (13,19,c)),b) |  -c not between  -e and  -a then (t1.c) else t1.d end FROM t1 WHERE c in (select case abs((count(*))) when  -max(t1.c) | abs(abs(+count(*)))-~case (case  -max(e) when max(11)- -count(*) then ((max(t1.e))) else count(*) end) when count(distinct t1.e) then cast(avg(f) AS integer) else cast(avg(t1.c) AS integer) end* -cast(avg(f) AS integer) then max(f) else (max(b)) end from t1 union select (max(13)) from t1) and not exists(select 1 from t1 where case when t1.e<=19-b then c else c end in (select c from t1 union select (select  -((count(distinct t1.d))) from t1)-t1.b from t1))}
} {}
do_test randexpr-2.731 {
  db eval {SELECT case when (19*b)+11*~f-coalesce((select max(11) from t1 where f<>case when case 17 when 11 then 17 else c end-11 in (t1.c,c,t1.e) and 19=t1.a or 17<=e or e<=19 then 19 | c when t1.b=t1.f then d else 19 end or t1.e not in (13,19,c)),b) |  -c not between  -e and  -a then (t1.c) else t1.d end FROM t1 WHERE NOT (c in (select case abs((count(*))) when  -max(t1.c) | abs(abs(+count(*)))-~case (case  -max(e) when max(11)- -count(*) then ((max(t1.e))) else count(*) end) when count(distinct t1.e) then cast(avg(f) AS integer) else cast(avg(t1.c) AS integer) end* -cast(avg(f) AS integer) then max(f) else (max(b)) end from t1 union select (max(13)) from t1) and not exists(select 1 from t1 where case when t1.e<=19-b then c else c end in (select c from t1 union select (select  -((count(distinct t1.d))) from t1)-t1.b from t1)))}
} {400}
do_test randexpr-2.732 {
  db eval {SELECT case when (19*b)+11*~f-coalesce((select max(11) from t1 where f<>case when case 17 when 11 then 17 else c end-11 in (t1.c,c,t1.e) and 19=t1.a or 17<=e or e<=19 then 19 & c when t1.b=t1.f then d else 19 end or t1.e not in (13,19,c)),b) &  -c not between  -e and  -a then (t1.c) else t1.d end FROM t1 WHERE NOT (c in (select case abs((count(*))) when  -max(t1.c) | abs(abs(+count(*)))-~case (case  -max(e) when max(11)- -count(*) then ((max(t1.e))) else count(*) end) when count(distinct t1.e) then cast(avg(f) AS integer) else cast(avg(t1.c) AS integer) end* -cast(avg(f) AS integer) then max(f) else (max(b)) end from t1 union select (max(13)) from t1) and not exists(select 1 from t1 where case when t1.e<=19-b then c else c end in (select c from t1 union select (select  -((count(distinct t1.d))) from t1)-t1.b from t1)))}
} {300}
do_test randexpr-2.733 {
  db eval {SELECT case when t1.e not between e and 13 then (select count(*) from t1) when f>=case when c in (select a from t1 union select t1.e+coalesce((select 11 from t1 where (select count(distinct t1.b) from t1)+17 not in (b,t1.c,t1.f-(select ~count(distinct 17) from t1)+ -e)),13) from t1) or 19 between d and t1.f then (select min(19) from t1) when not (e not between c and a) then d else a end then d else (t1.c) end FROM t1 WHERE f not in (17,f+d | f+case when  -f=19 then (select max((select +abs(abs(max(((select ((max(t1.d))+count(distinct t1.e))-min(t1.a) from t1))+t1.e)-abs(count(distinct  -t1.b)-count(distinct 11)))*min(a)-count(*))-min(t1.a) from t1)) from t1) else t1.f end,c-a) and c<>11}
} {1}
do_test randexpr-2.734 {
  db eval {SELECT case when t1.e not between e and 13 then (select count(*) from t1) when f>=case when c in (select a from t1 union select t1.e+coalesce((select 11 from t1 where (select count(distinct t1.b) from t1)+17 not in (b,t1.c,t1.f-(select ~count(distinct 17) from t1)+ -e)),13) from t1) or 19 between d and t1.f then (select min(19) from t1) when not (e not between c and a) then d else a end then d else (t1.c) end FROM t1 WHERE NOT (f not in (17,f+d | f+case when  -f=19 then (select max((select +abs(abs(max(((select ((max(t1.d))+count(distinct t1.e))-min(t1.a) from t1))+t1.e)-abs(count(distinct  -t1.b)-count(distinct 11)))*min(a)-count(*))-min(t1.a) from t1)) from t1) else t1.f end,c-a) and c<>11)}
} {}
do_test randexpr-2.735 {
  db eval {SELECT case c-+case when t1.f in (t1.a,t1.e,19) then t1.b else case when a<>t1.a then case ~(t1.d) when t1.e then (select max(t1.f) from t1)-(select +(cast(avg(b) AS integer))*cast(avg(t1.a) AS integer)+max(d)*count(*)+count(*) from t1)* -t1.f else 13 end else t1.a+a end*t1.f-t1.b*(e) end when d then d else 17 end FROM t1 WHERE case when not exists(select 1 from t1 where not exists(select 1 from t1 where c in (select t1.a*t1.b from t1 union select t1.d | e from t1))) and (coalesce((select (abs(11)/abs(13-17*c)) from t1 where b in (select 13 from t1 union select (t1.c) from t1)),11) not in (17,b,b)) then (abs(+t1.f)/abs(c)) when exists(select 1 from t1 where not exists(select 1 from t1 where not (not exists(select 1 from t1 where e<=19 and e>19)))) then c else t1.e end not between t1.f and c}
} {17}
do_test randexpr-2.736 {
  db eval {SELECT case c-+case when t1.f in (t1.a,t1.e,19) then t1.b else case when a<>t1.a then case ~(t1.d) when t1.e then (select max(t1.f) from t1)-(select +(cast(avg(b) AS integer))*cast(avg(t1.a) AS integer)+max(d)*count(*)+count(*) from t1)* -t1.f else 13 end else t1.a+a end*t1.f-t1.b*(e) end when d then d else 17 end FROM t1 WHERE NOT (case when not exists(select 1 from t1 where not exists(select 1 from t1 where c in (select t1.a*t1.b from t1 union select t1.d | e from t1))) and (coalesce((select (abs(11)/abs(13-17*c)) from t1 where b in (select 13 from t1 union select (t1.c) from t1)),11) not in (17,b,b)) then (abs(+t1.f)/abs(c)) when exists(select 1 from t1 where not exists(select 1 from t1 where not (not exists(select 1 from t1 where e<=19 and e>19)))) then c else t1.e end not between t1.f and c)}
} {}
do_test randexpr-2.737 {
  db eval {SELECT 11+a+(select count(distinct coalesce((select  -coalesce((select case when (t1.a<=a) then (case when 17=t1.c then (select count(distinct e)-min(11) from t1) else f end) when f>=t1.f and t1.c not in (t1.e,a,17) and 17=t1.f then  -t1.d else 11 end*t1.d from t1 where t1.a<=t1.b),t1.b) from t1 where t1.e not between d and 13),t1.a)) | +max(t1.c) from t1) FROM t1 WHERE 11 in (t1.a,+t1.c* -t1.f | t1.d*+t1.c-b-(abs((select min(case when 19 in (select abs(count(distinct c)) from t1 union select ~ -min(t1.c) from t1) then case (11) when a then t1.c else t1.d end when (f)<=t1.b then t1.b else t1.a end)+min((t1.d)) | min(b) from t1))/abs(t1.e))+case 13 when t1.b then b else  - -t1.b end*b-11, -f)}
} {}
do_test randexpr-2.738 {
  db eval {SELECT 11+a+(select count(distinct coalesce((select  -coalesce((select case when (t1.a<=a) then (case when 17=t1.c then (select count(distinct e)-min(11) from t1) else f end) when f>=t1.f and t1.c not in (t1.e,a,17) and 17=t1.f then  -t1.d else 11 end*t1.d from t1 where t1.a<=t1.b),t1.b) from t1 where t1.e not between d and 13),t1.a)) | +max(t1.c) from t1) FROM t1 WHERE NOT (11 in (t1.a,+t1.c* -t1.f | t1.d*+t1.c-b-(abs((select min(case when 19 in (select abs(count(distinct c)) from t1 union select ~ -min(t1.c) from t1) then case (11) when a then t1.c else t1.d end when (f)<=t1.b then t1.b else t1.a end)+min((t1.d)) | min(b) from t1))/abs(t1.e))+case 13 when t1.b then b else  - -t1.b end*b-11, -f))}
} {412}
do_test randexpr-2.739 {
  db eval {SELECT 11+a+(select count(distinct coalesce((select  -coalesce((select case when (t1.a<=a) then (case when 17=t1.c then (select count(distinct e)-min(11) from t1) else f end) when f>=t1.f and t1.c not in (t1.e,a,17) and 17=t1.f then  -t1.d else 11 end*t1.d from t1 where t1.a<=t1.b),t1.b) from t1 where t1.e not between d and 13),t1.a)) & +max(t1.c) from t1) FROM t1 WHERE NOT (11 in (t1.a,+t1.c* -t1.f | t1.d*+t1.c-b-(abs((select min(case when 19 in (select abs(count(distinct c)) from t1 union select ~ -min(t1.c) from t1) then case (11) when a then t1.c else t1.d end when (f)<=t1.b then t1.b else t1.a end)+min((t1.d)) | min(b) from t1))/abs(t1.e))+case 13 when t1.b then b else  - -t1.b end*b-11, -f))}
} {111}
do_test randexpr-2.740 {
  db eval {SELECT  -c-case 11 when ++e*(select cast(avg( -t1.f+case when case when 19=t1.e+((select min(17 | a) from t1)) then t1.f else t1.b end>=t1.e then t1.e when (((exists(select 1 from t1 where b in (select case  -count(*) when (count(distinct d)) then count(*) else (cast(avg(t1.b) AS integer)) end from t1 union select  -count(*) from t1))))) then t1.a else a end+t1.a*d) AS integer) from t1) then 13 else f end*e FROM t1 WHERE (select cast(avg(case when +d>=e+17 and (not case when 13>=(select case  -count(distinct t1.e) when cast(avg(c) AS integer) then cast(avg(19) AS integer) else count(distinct t1.a) end from t1) then t1.e else t1.f end in (select t1.b from t1 union select 13 from t1)) or t1.a<=e and e in (select count(*) from t1 union select  -count(*) from t1) and b>=t1.b or t1.e between c and 19 then c when f between 19 and b then coalesce((select max(t1.d) from t1 where a<>t1.b),13)* -(d) else t1.e end) AS integer) from t1)<=19}
} {}
do_test randexpr-2.741 {
  db eval {SELECT  -c-case 11 when ++e*(select cast(avg( -t1.f+case when case when 19=t1.e+((select min(17 | a) from t1)) then t1.f else t1.b end>=t1.e then t1.e when (((exists(select 1 from t1 where b in (select case  -count(*) when (count(distinct d)) then count(*) else (cast(avg(t1.b) AS integer)) end from t1 union select  -count(*) from t1))))) then t1.a else a end+t1.a*d) AS integer) from t1) then 13 else f end*e FROM t1 WHERE NOT ((select cast(avg(case when +d>=e+17 and (not case when 13>=(select case  -count(distinct t1.e) when cast(avg(c) AS integer) then cast(avg(19) AS integer) else count(distinct t1.a) end from t1) then t1.e else t1.f end in (select t1.b from t1 union select 13 from t1)) or t1.a<=e and e in (select count(*) from t1 union select  -count(*) from t1) and b>=t1.b or t1.e between c and 19 then c when f between 19 and b then coalesce((select max(t1.d) from t1 where a<>t1.b),13)* -(d) else t1.e end) AS integer) from t1)<=19)}
} {-300300}
do_test randexpr-2.742 {
  db eval {SELECT  -c-case 11 when ++e*(select cast(avg( -t1.f+case when case when 19=t1.e+((select min(17 & a) from t1)) then t1.f else t1.b end>=t1.e then t1.e when (((exists(select 1 from t1 where b in (select case  -count(*) when (count(distinct d)) then count(*) else (cast(avg(t1.b) AS integer)) end from t1 union select  -count(*) from t1))))) then t1.a else a end+t1.a*d) AS integer) from t1) then 13 else f end*e FROM t1 WHERE NOT ((select cast(avg(case when +d>=e+17 and (not case when 13>=(select case  -count(distinct t1.e) when cast(avg(c) AS integer) then cast(avg(19) AS integer) else count(distinct t1.a) end from t1) then t1.e else t1.f end in (select t1.b from t1 union select 13 from t1)) or t1.a<=e and e in (select count(*) from t1 union select  -count(*) from t1) and b>=t1.b or t1.e between c and 19 then c when f between 19 and b then coalesce((select max(t1.d) from t1 where a<>t1.b),13)* -(d) else t1.e end) AS integer) from t1)<=19)}
} {-300300}
do_test randexpr-2.743 {
  db eval {SELECT case d when 11 then t1.d-(abs(t1.d)/abs(19))+coalesce((select d*d from t1 where (select cast(avg(case when f | c+case when e in (select min(coalesce((select t1.f from t1 where 11 not between t1.b and 19),t1.f)) from t1 union select (max(t1.b)) from t1) then 19 when t1.b=b or t1.c>=c then 13 else e end*19 in (select 17 from t1 union select 11 from t1) then  -c else t1.d end) AS integer) from t1)<13),d) else 11 end FROM t1 WHERE (b>~t1.c-+(abs(case when 11>(c) and t1.a>13 then t1.d else (b) end)/abs(t1.d))-13 or t1.f between t1.a and 19 and 11 in (select (min(t1.e))-~( -+count(*)) from t1 union select count(distinct t1.c) from t1)) and 17 not in (f,(t1.b),t1.c) and (t1.f<>t1.e) or d in (f,t1.a,t1.d) or (d)<=t1.e}
} {11}
do_test randexpr-2.744 {
  db eval {SELECT case d when 11 then t1.d-(abs(t1.d)/abs(19))+coalesce((select d*d from t1 where (select cast(avg(case when f | c+case when e in (select min(coalesce((select t1.f from t1 where 11 not between t1.b and 19),t1.f)) from t1 union select (max(t1.b)) from t1) then 19 when t1.b=b or t1.c>=c then 13 else e end*19 in (select 17 from t1 union select 11 from t1) then  -c else t1.d end) AS integer) from t1)<13),d) else 11 end FROM t1 WHERE NOT ((b>~t1.c-+(abs(case when 11>(c) and t1.a>13 then t1.d else (b) end)/abs(t1.d))-13 or t1.f between t1.a and 19 and 11 in (select (min(t1.e))-~( -+count(*)) from t1 union select count(distinct t1.c) from t1)) and 17 not in (f,(t1.b),t1.c) and (t1.f<>t1.e) or d in (f,t1.a,t1.d) or (d)<=t1.e)}
} {}
do_test randexpr-2.745 {
  db eval {SELECT case d when 11 then t1.d-(abs(t1.d)/abs(19))+coalesce((select d*d from t1 where (select cast(avg(case when f & c+case when e in (select min(coalesce((select t1.f from t1 where 11 not between t1.b and 19),t1.f)) from t1 union select (max(t1.b)) from t1) then 19 when t1.b=b or t1.c>=c then 13 else e end*19 in (select 17 from t1 union select 11 from t1) then  -c else t1.d end) AS integer) from t1)<13),d) else 11 end FROM t1 WHERE (b>~t1.c-+(abs(case when 11>(c) and t1.a>13 then t1.d else (b) end)/abs(t1.d))-13 or t1.f between t1.a and 19 and 11 in (select (min(t1.e))-~( -+count(*)) from t1 union select count(distinct t1.c) from t1)) and 17 not in (f,(t1.b),t1.c) and (t1.f<>t1.e) or d in (f,t1.a,t1.d) or (d)<=t1.e}
} {11}
do_test randexpr-2.746 {
  db eval {SELECT (select  -~count(distinct ~+case when c<>coalesce((select max(case when ~13 in (t1.a,t1.f,13+t1.d+(19)*t1.d*f-e) then 13 else a end) from t1 where  -t1.d<>19),(a))*d+a then t1.d when exists(select 1 from t1 where b=d) then t1.f else 17 end*11) | count(*)-max(t1.e) from t1) FROM t1 WHERE 19 in (select max(b) from t1 union select count(*) from t1) and +t1.b+c*d+coalesce((select max(17) from t1 where case when t1.a=coalesce((select max((select (min(t1.f)) from t1)) from t1 where not case when not exists(select 1 from t1 where ( -t1.b)=13 and d in (f,c,e)) or 17 between 17 and e then t1.e-t1.c else 11 end>=d),19)-11 then 11 else 17 end<=t1.a),t1.f)+t1.f-f<>17}
} {}
do_test randexpr-2.747 {
  db eval {SELECT (select  -~count(distinct ~+case when c<>coalesce((select max(case when ~13 in (t1.a,t1.f,13+t1.d+(19)*t1.d*f-e) then 13 else a end) from t1 where  -t1.d<>19),(a))*d+a then t1.d when exists(select 1 from t1 where b=d) then t1.f else 17 end*11) | count(*)-max(t1.e) from t1) FROM t1 WHERE NOT (19 in (select max(b) from t1 union select count(*) from t1) and +t1.b+c*d+coalesce((select max(17) from t1 where case when t1.a=coalesce((select max((select (min(t1.f)) from t1)) from t1 where not case when not exists(select 1 from t1 where ( -t1.b)=13 and d in (f,c,e)) or 17 between 17 and e then t1.e-t1.c else 11 end>=d),19)-11 then 11 else 17 end<=t1.a),t1.f)+t1.f-f<>17)}
} {-497}
do_test randexpr-2.748 {
  db eval {SELECT (select  -~count(distinct ~+case when c<>coalesce((select max(case when ~13 in (t1.a,t1.f,13+t1.d+(19)*t1.d*f-e) then 13 else a end) from t1 where  -t1.d<>19),(a))*d+a then t1.d when exists(select 1 from t1 where b=d) then t1.f else 17 end*11) & count(*)-max(t1.e) from t1) FROM t1 WHERE NOT (19 in (select max(b) from t1 union select count(*) from t1) and +t1.b+c*d+coalesce((select max(17) from t1 where case when t1.a=coalesce((select max((select (min(t1.f)) from t1)) from t1 where not case when not exists(select 1 from t1 where ( -t1.b)=13 and d in (f,c,e)) or 17 between 17 and e then t1.e-t1.c else 11 end>=d),19)-11 then 11 else 17 end<=t1.a),t1.f)+t1.f-f<>17)}
} {0}
do_test randexpr-2.749 {
  db eval {SELECT coalesce((select max(a) from t1 where exists(select 1 from t1 where (abs(t1.f)/abs(case when (t1.a+case when exists(select 1 from t1 where t1.e>=(abs(coalesce((select f from t1 where (((b>=t1.d) or t1.e= -a) or 17=a)),case when t1.d between t1.a and b then t1.b when e in (e,t1.a,t1.e) then 13 else (f) end))/abs(13))) then 11 else t1.d end* - -t1.f)<=c then d else t1.d end))-t1.c-19>=t1.a)),((t1.b))) FROM t1 WHERE case when t1.f in (e,19,(abs(t1.e)/abs(t1.e))) and (17 between 11+(select +max(case case when f=(t1.b) then e when t1.e in (13,19,c) then c else  -t1.b end- -c when (13) then d else t1.f end) from t1) and 17 and (19 in (b,t1.d,11))) and f not between 19 and b then e when 13 not between (t1.e) and t1.a then 11 else 11 end not between d and t1.a}
} {200}
do_test randexpr-2.750 {
  db eval {SELECT coalesce((select max(a) from t1 where exists(select 1 from t1 where (abs(t1.f)/abs(case when (t1.a+case when exists(select 1 from t1 where t1.e>=(abs(coalesce((select f from t1 where (((b>=t1.d) or t1.e= -a) or 17=a)),case when t1.d between t1.a and b then t1.b when e in (e,t1.a,t1.e) then 13 else (f) end))/abs(13))) then 11 else t1.d end* - -t1.f)<=c then d else t1.d end))-t1.c-19>=t1.a)),((t1.b))) FROM t1 WHERE NOT (case when t1.f in (e,19,(abs(t1.e)/abs(t1.e))) and (17 between 11+(select +max(case case when f=(t1.b) then e when t1.e in (13,19,c) then c else  -t1.b end- -c when (13) then d else t1.f end) from t1) and 17 and (19 in (b,t1.d,11))) and f not between 19 and b then e when 13 not between (t1.e) and t1.a then 11 else 11 end not between d and t1.a)}
} {}
do_test randexpr-2.751 {
  db eval {SELECT 11-17 | case when 11<t1.c then case when ~f<=(abs(t1.e)/abs(19))-t1.f then 17 when 11>=c or 11 in (select cast(avg(t1.c) AS integer)-case cast(avg(t1.b) AS integer) when count(distinct e) then min(t1.a) else  -count(distinct 19) end from t1 union select count(*) from t1) or e in (t1.e,t1.b,b) or 13=t1.f and e>=t1.a then e else e end when ( -19<=e) then 13 else e end+a FROM t1 WHERE t1.c*d not in ( -t1.a,coalesce((select d from t1 where coalesce((select c from t1 where ((d<=11))),(17)+(abs(coalesce((select (select ( -+count(*))+count(distinct d) from t1) from t1 where (coalesce((select b from t1 where ~a<>13),(t1.c))) not between d and t1.d),17))/abs(d)))*f<a and t1.b<>17),e),t1.b)}
} {-1}
do_test randexpr-2.752 {
  db eval {SELECT 11-17 | case when 11<t1.c then case when ~f<=(abs(t1.e)/abs(19))-t1.f then 17 when 11>=c or 11 in (select cast(avg(t1.c) AS integer)-case cast(avg(t1.b) AS integer) when count(distinct e) then min(t1.a) else  -count(distinct 19) end from t1 union select count(*) from t1) or e in (t1.e,t1.b,b) or 13=t1.f and e>=t1.a then e else e end when ( -19<=e) then 13 else e end+a FROM t1 WHERE NOT (t1.c*d not in ( -t1.a,coalesce((select d from t1 where coalesce((select c from t1 where ((d<=11))),(17)+(abs(coalesce((select (select ( -+count(*))+count(distinct d) from t1) from t1 where (coalesce((select b from t1 where ~a<>13),(t1.c))) not between d and t1.d),17))/abs(d)))*f<a and t1.b<>17),e),t1.b))}
} {}
do_test randexpr-2.753 {
  db eval {SELECT 11-17 & case when 11<t1.c then case when ~f<=(abs(t1.e)/abs(19))-t1.f then 17 when 11>=c or 11 in (select cast(avg(t1.c) AS integer)-case cast(avg(t1.b) AS integer) when count(distinct e) then min(t1.a) else  -count(distinct 19) end from t1 union select count(*) from t1) or e in (t1.e,t1.b,b) or 13=t1.f and e>=t1.a then e else e end when ( -19<=e) then 13 else e end+a FROM t1 WHERE t1.c*d not in ( -t1.a,coalesce((select d from t1 where coalesce((select c from t1 where ((d<=11))),(17)+(abs(coalesce((select (select ( -+count(*))+count(distinct d) from t1) from t1 where (coalesce((select b from t1 where ~a<>13),(t1.c))) not between d and t1.d),17))/abs(d)))*f<a and t1.b<>17),e),t1.b)}
} {112}
do_test randexpr-2.754 {
  db eval {SELECT (abs(f-case when +(t1.f)-c<case when 17=case when not exists(select 1 from t1 where (19)=17 or c<>13 and  -f<t1.a) then (select max((select min(t1.b) | count(distinct 19) from t1)) from t1) when e not between t1.b and e then t1.e else 17 end+t1.e or t1.c in (t1.f,f,t1.d) then (11)+f when t1.c=11 and t1.e not in (a,(t1.e),a) then a else t1.f end-d then 11 else (t1.e) end-t1.b)/abs(11))*11 FROM t1 WHERE (case when (f not in (~(t1.f*case when case when case 11 when t1.e then t1.c else a end | 19 in (select t1.a from t1 union select t1.e from t1) then f when d>t1.c then 11 else  -11 end<>t1.c and t1.f not between (11) and (t1.f) then b else 11 end)*b+t1.f,a,t1.d)) then 11 else t1.d end=e) or e<(t1.f)}
} {99}
do_test randexpr-2.755 {
  db eval {SELECT (abs(f-case when +(t1.f)-c<case when 17=case when not exists(select 1 from t1 where (19)=17 or c<>13 and  -f<t1.a) then (select max((select min(t1.b) | count(distinct 19) from t1)) from t1) when e not between t1.b and e then t1.e else 17 end+t1.e or t1.c in (t1.f,f,t1.d) then (11)+f when t1.c=11 and t1.e not in (a,(t1.e),a) then a else t1.f end-d then 11 else (t1.e) end-t1.b)/abs(11))*11 FROM t1 WHERE NOT ((case when (f not in (~(t1.f*case when case when case 11 when t1.e then t1.c else a end | 19 in (select t1.a from t1 union select t1.e from t1) then f when d>t1.c then 11 else  -11 end<>t1.c and t1.f not between (11) and (t1.f) then b else 11 end)*b+t1.f,a,t1.d)) then 11 else t1.d end=e) or e<(t1.f))}
} {}
do_test randexpr-2.756 {
  db eval {SELECT (abs(f-case when +(t1.f)-c<case when 17=case when not exists(select 1 from t1 where (19)=17 or c<>13 and  -f<t1.a) then (select max((select min(t1.b) & count(distinct 19) from t1)) from t1) when e not between t1.b and e then t1.e else 17 end+t1.e or t1.c in (t1.f,f,t1.d) then (11)+f when t1.c=11 and t1.e not in (a,(t1.e),a) then a else t1.f end-d then 11 else (t1.e) end-t1.b)/abs(11))*11 FROM t1 WHERE (case when (f not in (~(t1.f*case when case when case 11 when t1.e then t1.c else a end | 19 in (select t1.a from t1 union select t1.e from t1) then f when d>t1.c then 11 else  -11 end<>t1.c and t1.f not between (11) and (t1.f) then b else 11 end)*b+t1.f,a,t1.d)) then 11 else t1.d end=e) or e<(t1.f)}
} {99}
do_test randexpr-2.757 {
  db eval {SELECT +(select (max(case when not (((exists(select 1 from t1 where b not between t1.a and t1.d) or t1.a>=coalesce((select max(17) from t1 where  -t1.e between t1.e and a),f)-11) or 11<=t1.c)) then b when 19 between 19 and b then t1.f else +d+ -t1.a-t1.f-e end | f-t1.b+ -t1.b)+min(t1.b)) from t1)*t1.c FROM t1 WHERE b in (t1.b-b,coalesce((select max(e) from t1 where t1.d not between 11 and case when d>=+13 then case when t1.a between e and a then t1.c else (t1.f)+(t1.b) end else case (d)*e when b then f else a end end or t1.d in (select cast(avg(d) AS integer) from t1 union select +abs( -max(e))*max(19) | max(d) from t1)),11),t1.c)}
} {}
do_test randexpr-2.758 {
  db eval {SELECT +(select (max(case when not (((exists(select 1 from t1 where b not between t1.a and t1.d) or t1.a>=coalesce((select max(17) from t1 where  -t1.e between t1.e and a),f)-11) or 11<=t1.c)) then b when 19 between 19 and b then t1.f else +d+ -t1.a-t1.f-e end | f-t1.b+ -t1.b)+min(t1.b)) from t1)*t1.c FROM t1 WHERE NOT (b in (t1.b-b,coalesce((select max(e) from t1 where t1.d not between 11 and case when d>=+13 then case when t1.a between e and a then t1.c else (t1.f)+(t1.b) end else case (d)*e when b then f else a end end or t1.d in (select cast(avg(d) AS integer) from t1 union select +abs( -max(e))*max(19) | max(d) from t1)),11),t1.c))}
} {278400}
do_test randexpr-2.759 {
  db eval {SELECT +(select (max(case when not (((exists(select 1 from t1 where b not between t1.a and t1.d) or t1.a>=coalesce((select max(17) from t1 where  -t1.e between t1.e and a),f)-11) or 11<=t1.c)) then b when 19 between 19 and b then t1.f else +d+ -t1.a-t1.f-e end & f-t1.b+ -t1.b)+min(t1.b)) from t1)*t1.c FROM t1 WHERE NOT (b in (t1.b-b,coalesce((select max(e) from t1 where t1.d not between 11 and case when d>=+13 then case when t1.a between e and a then t1.c else (t1.f)+(t1.b) end else case (d)*e when b then f else a end end or t1.d in (select cast(avg(d) AS integer) from t1 union select +abs( -max(e))*max(19) | max(d) from t1)),11),t1.c))}
} {81600}
do_test randexpr-2.760 {
  db eval {SELECT t1.e*t1.c*(select count(*)+abs(cast(avg(case t1.a when (select  -count(*)-(min(t1.a)) | +(abs(case max(a) when abs(min(17)) then +cast(avg(a) AS integer) | count(distinct d) else count(*) end)) from t1) then a else  -+b-coalesce((select max(f*19) from t1 where ~~c in (a,13,t1.a)),t1.b) end) AS integer)) from t1) FROM t1 WHERE 19-(abs(b)/abs(t1.b)) | case when t1.e in (select case (+cast(avg(t1.c+a) AS integer) | (cast(avg(t1.d) AS integer) |  -cast(avg( -d) AS integer)* -( -count(*))+min(17))) when min(13) then max( -11) else count(*) end from t1 union select min(17) from t1) or 13 in (case when t1.e between e and coalesce((select c from t1 where not exists(select 1 from t1 where (b)>=t1.e)),t1.b) then 19 else 11 end,17,f) then 11 else b end in (select c from t1 union select 19 from t1)}
} {}
do_test randexpr-2.761 {
  db eval {SELECT t1.e*t1.c*(select count(*)+abs(cast(avg(case t1.a when (select  -count(*)-(min(t1.a)) | +(abs(case max(a) when abs(min(17)) then +cast(avg(a) AS integer) | count(distinct d) else count(*) end)) from t1) then a else  -+b-coalesce((select max(f*19) from t1 where ~~c in (a,13,t1.a)),t1.b) end) AS integer)) from t1) FROM t1 WHERE NOT (19-(abs(b)/abs(t1.b)) | case when t1.e in (select case (+cast(avg(t1.c+a) AS integer) | (cast(avg(t1.d) AS integer) |  -cast(avg( -d) AS integer)* -( -count(*))+min(17))) when min(13) then max( -11) else count(*) end from t1 union select min(17) from t1) or 13 in (case when t1.e between e and coalesce((select c from t1 where not exists(select 1 from t1 where (b)>=t1.e)),t1.b) then 19 else 11 end,17,f) then 11 else b end in (select c from t1 union select 19 from t1))}
} {60150000}
do_test randexpr-2.762 {
  db eval {SELECT t1.e*t1.c*(select count(*)+abs(cast(avg(case t1.a when (select  -count(*)-(min(t1.a)) & +(abs(case max(a) when abs(min(17)) then +cast(avg(a) AS integer) & count(distinct d) else count(*) end)) from t1) then a else  -+b-coalesce((select max(f*19) from t1 where ~~c in (a,13,t1.a)),t1.b) end) AS integer)) from t1) FROM t1 WHERE NOT (19-(abs(b)/abs(t1.b)) | case when t1.e in (select case (+cast(avg(t1.c+a) AS integer) | (cast(avg(t1.d) AS integer) |  -cast(avg( -d) AS integer)* -( -count(*))+min(17))) when min(13) then max( -11) else count(*) end from t1 union select min(17) from t1) or 13 in (case when t1.e between e and coalesce((select c from t1 where not exists(select 1 from t1 where (b)>=t1.e)),t1.b) then 19 else 11 end,17,f) then 11 else b end in (select c from t1 union select 19 from t1))}
} {60150000}
do_test randexpr-2.763 {
  db eval {SELECT t1.b+case when e+(select abs(abs(min(d+case 11 when t1.d+19 | b | case when e<=b+coalesce((select 11 from t1 where 11<>13),17)-17 then t1.d else d end+19 then 11 else d end))) from t1)- -d-(t1.e) in (select 17 from t1 union select 11 from t1) then t1.e when exists(select 1 from t1 where e>t1.c) then t1.b else 13 end FROM t1 WHERE e in (select count(*) from t1 union select min(case when (select abs(cast(avg(+17) AS integer)) from t1) not between t1.e and 17+t1.f then f when ((case when ((select cast(avg(t1.d) AS integer) from t1)=17) then 19 else t1.f end)<>t1.c or t1.a in (select  -+abs(cast(avg(t1.b) AS integer)) from t1 union select +((cast(avg(11) AS integer)))+ -min(b) from t1)) or not exists(select 1 from t1 where ((t1.d in (b,a,17)) and f<=t1.a)) and t1.f<> - -t1.a then d else  - -t1.d end) from t1)}
} {}
do_test randexpr-2.764 {
  db eval {SELECT t1.b+case when e+(select abs(abs(min(d+case 11 when t1.d+19 | b | case when e<=b+coalesce((select 11 from t1 where 11<>13),17)-17 then t1.d else d end+19 then 11 else d end))) from t1)- -d-(t1.e) in (select 17 from t1 union select 11 from t1) then t1.e when exists(select 1 from t1 where e>t1.c) then t1.b else 13 end FROM t1 WHERE NOT (e in (select count(*) from t1 union select min(case when (select abs(cast(avg(+17) AS integer)) from t1) not between t1.e and 17+t1.f then f when ((case when ((select cast(avg(t1.d) AS integer) from t1)=17) then 19 else t1.f end)<>t1.c or t1.a in (select  -+abs(cast(avg(t1.b) AS integer)) from t1 union select +((cast(avg(11) AS integer)))+ -min(b) from t1)) or not exists(select 1 from t1 where ((t1.d in (b,a,17)) and f<=t1.a)) and t1.f<> - -t1.a then d else  - -t1.d end) from t1))}
} {400}
do_test randexpr-2.765 {
  db eval {SELECT t1.b+case when e+(select abs(abs(min(d+case 11 when t1.d+19 & b & case when e<=b+coalesce((select 11 from t1 where 11<>13),17)-17 then t1.d else d end+19 then 11 else d end))) from t1)- -d-(t1.e) in (select 17 from t1 union select 11 from t1) then t1.e when exists(select 1 from t1 where e>t1.c) then t1.b else 13 end FROM t1 WHERE NOT (e in (select count(*) from t1 union select min(case when (select abs(cast(avg(+17) AS integer)) from t1) not between t1.e and 17+t1.f then f when ((case when ((select cast(avg(t1.d) AS integer) from t1)=17) then 19 else t1.f end)<>t1.c or t1.a in (select  -+abs(cast(avg(t1.b) AS integer)) from t1 union select +((cast(avg(11) AS integer)))+ -min(b) from t1)) or not exists(select 1 from t1 where ((t1.d in (b,a,17)) and f<=t1.a)) and t1.f<> - -t1.a then d else  - -t1.d end) from t1))}
} {400}
do_test randexpr-2.766 {
  db eval {SELECT (select cast(avg( -coalesce((select max(+(abs(t1.d)/abs(~d))*+c*t1.c) from t1 where e in (select coalesce((select f from t1 where t1.f<> -11),17)+c*19 from t1 union select f from t1)),t1.c)) AS integer)-~case ~count(distinct 17)*count(distinct 19) when count(distinct t1.c)*count(*)-count(distinct 19) then +(max(a)+case  - - - -min(t1.f) when max(c) then count(distinct (f)) else min(13) end) else ( -cast(avg( -t1.b) AS integer)) end from t1) FROM t1 WHERE exists(select 1 from t1 where (abs(e*coalesce((select (abs(b*(t1.b)+f)/abs(d)) from t1 where t1.c in (select min(a | t1.b) from t1 union select abs(case  -case ~ -~cast(avg(e) AS integer) when ++min(17)+( -cast(avg(a) AS integer))-max(t1.c) then cast(avg(t1.b) AS integer) else cast(avg(f) AS integer) end when  - -max((t1.d)) then  -min(t1.b) else cast(avg(t1.c) AS integer) end) from t1)),b))/abs(t1.d)) in (select min(t1.c)-cast(avg( -e) AS integer)- -cast(avg(t1.f) AS integer) from t1 union select (max((19))) from t1))}
} {}
do_test randexpr-2.767 {
  db eval {SELECT (select cast(avg( -coalesce((select max(+(abs(t1.d)/abs(~d))*+c*t1.c) from t1 where e in (select coalesce((select f from t1 where t1.f<> -11),17)+c*19 from t1 union select f from t1)),t1.c)) AS integer)-~case ~count(distinct 17)*count(distinct 19) when count(distinct t1.c)*count(*)-count(distinct 19) then +(max(a)+case  - - - -min(t1.f) when max(c) then count(distinct (f)) else min(13) end) else ( -cast(avg( -t1.b) AS integer)) end from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where (abs(e*coalesce((select (abs(b*(t1.b)+f)/abs(d)) from t1 where t1.c in (select min(a | t1.b) from t1 union select abs(case  -case ~ -~cast(avg(e) AS integer) when ++min(17)+( -cast(avg(a) AS integer))-max(t1.c) then cast(avg(t1.b) AS integer) else cast(avg(f) AS integer) end when  - -max((t1.d)) then  -min(t1.b) else cast(avg(t1.c) AS integer) end) from t1)),b))/abs(t1.d)) in (select min(t1.c)-cast(avg( -e) AS integer)- -cast(avg(t1.f) AS integer) from t1 union select (max((19))) from t1)))}
} {-99}
do_test randexpr-2.768 {
  db eval {SELECT t1.a+11*coalesce((select max( -t1.e-coalesce((select max((abs(t1.c)/abs((13*e+t1.c)-t1.f))) from t1 where exists(select 1 from t1 where d<>a) or ~(select case abs(count(distinct f)) when (count(*)) then count(*) else min(t1.f) end from t1)+coalesce((select f from t1 where d in (select min(t1.d) from t1 union select count(*) from t1)),c) in (11,t1.a,t1.b)),11)- -11) from t1 where 13<11),t1.b) FROM t1 WHERE not ++coalesce((select t1.f from t1 where not exists(select 1 from t1 where ((select min(b) from t1)<>case t1.d when coalesce((select max(case e-t1.c when 19-t1.c+f+(t1.c*coalesce((select max(17) from t1 where 17 between 11 and t1.a),t1.d)+b) then  -17 else d end-a) from t1 where t1.d>11),b) then 11 else c end))),b | t1.d)*17 not between t1.e and 17}
} {}
do_test randexpr-2.769 {
  db eval {SELECT t1.a+11*coalesce((select max( -t1.e-coalesce((select max((abs(t1.c)/abs((13*e+t1.c)-t1.f))) from t1 where exists(select 1 from t1 where d<>a) or ~(select case abs(count(distinct f)) when (count(*)) then count(*) else min(t1.f) end from t1)+coalesce((select f from t1 where d in (select min(t1.d) from t1 union select count(*) from t1)),c) in (11,t1.a,t1.b)),11)- -11) from t1 where 13<11),t1.b) FROM t1 WHERE NOT (not ++coalesce((select t1.f from t1 where not exists(select 1 from t1 where ((select min(b) from t1)<>case t1.d when coalesce((select max(case e-t1.c when 19-t1.c+f+(t1.c*coalesce((select max(17) from t1 where 17 between 11 and t1.a),t1.d)+b) then  -17 else d end-a) from t1 where t1.d>11),b) then 11 else c end))),b | t1.d)*17 not between t1.e and 17)}
} {2300}
do_test randexpr-2.770 {
  db eval {SELECT coalesce((select max(coalesce((select ((abs(coalesce((select max((select ~(count(distinct e-11)-cast(avg(t1.a) AS integer) | count(*)) from t1)) from t1 where t1.f<case when not exists(select 1 from t1 where exists(select 1 from t1 where t1.a not in (11,e,13))) then t1.b when t1.d<t1.b then t1.e else t1.b end+ -c or t1.e>b or t1.c in (select c from t1 union select 19 from t1)),e | b))/abs(t1.f))) from t1 where e in (select  -(b) from t1 union select 13 from t1)),t1.a)) from t1 where f<>11),t1.e) FROM t1 WHERE  -11 in (a,case when exists(select 1 from t1 where 11 in (select 13 from t1 union select t1.d from t1)) and exists(select 1 from t1 where exists(select 1 from t1 where (t1.a) not between t1.c and t1.c)) then ~case when ~t1.f not between +t1.b-11 and e or not b in (c,17,e) and (not exists(select 1 from t1 where b in (( -t1.e), -t1.c,t1.c))) or 17 not in (t1.e,t1.c,t1.f) then c when 19= - -11 then t1.b else t1.c end when (13) between t1.f and ( -t1.e) then t1.d else  -t1.d end*c,d)}
} {}
do_test randexpr-2.771 {
  db eval {SELECT coalesce((select max(coalesce((select ((abs(coalesce((select max((select ~(count(distinct e-11)-cast(avg(t1.a) AS integer) | count(*)) from t1)) from t1 where t1.f<case when not exists(select 1 from t1 where exists(select 1 from t1 where t1.a not in (11,e,13))) then t1.b when t1.d<t1.b then t1.e else t1.b end+ -c or t1.e>b or t1.c in (select c from t1 union select 19 from t1)),e | b))/abs(t1.f))) from t1 where e in (select  -(b) from t1 union select 13 from t1)),t1.a)) from t1 where f<>11),t1.e) FROM t1 WHERE NOT ( -11 in (a,case when exists(select 1 from t1 where 11 in (select 13 from t1 union select t1.d from t1)) and exists(select 1 from t1 where exists(select 1 from t1 where (t1.a) not between t1.c and t1.c)) then ~case when ~t1.f not between +t1.b-11 and e or not b in (c,17,e) and (not exists(select 1 from t1 where b in (( -t1.e), -t1.c,t1.c))) or 17 not in (t1.e,t1.c,t1.f) then c when 19= - -11 then t1.b else t1.c end when (13) between t1.f and ( -t1.e) then t1.d else  -t1.d end*c,d))}
} {100}
do_test randexpr-2.772 {
  db eval {SELECT coalesce((select max(coalesce((select ((abs(coalesce((select max((select ~(count(distinct e-11)-cast(avg(t1.a) AS integer) & count(*)) from t1)) from t1 where t1.f<case when not exists(select 1 from t1 where exists(select 1 from t1 where t1.a not in (11,e,13))) then t1.b when t1.d<t1.b then t1.e else t1.b end+ -c or t1.e>b or t1.c in (select c from t1 union select 19 from t1)),e & b))/abs(t1.f))) from t1 where e in (select  -(b) from t1 union select 13 from t1)),t1.a)) from t1 where f<>11),t1.e) FROM t1 WHERE NOT ( -11 in (a,case when exists(select 1 from t1 where 11 in (select 13 from t1 union select t1.d from t1)) and exists(select 1 from t1 where exists(select 1 from t1 where (t1.a) not between t1.c and t1.c)) then ~case when ~t1.f not between +t1.b-11 and e or not b in (c,17,e) and (not exists(select 1 from t1 where b in (( -t1.e), -t1.c,t1.c))) or 17 not in (t1.e,t1.c,t1.f) then c when 19= - -11 then t1.b else t1.c end when (13) between t1.f and ( -t1.e) then t1.d else  -t1.d end*c,d))}
} {100}
do_test randexpr-2.773 {
  db eval {SELECT 17-13-case 19 when 17+case case t1.b when t1.b then coalesce((select coalesce((select 11 from t1 where (coalesce((select t1.a from t1 where (abs(f)/abs(case t1.e when 11 then a else t1.c end))<c),b)*a- -t1.e) not between t1.e and  -13),19) from t1 where d>19 or d not between f and t1.e),(t1.c)) else 11 end when  -a then 13 else e end then t1.b else b end+t1.c FROM t1 WHERE not exists(select 1 from t1 where coalesce((select e from t1 where case when not exists(select 1 from t1 where not not exists(select 1 from t1 where f<> -t1.e-t1.c)) or coalesce((select max(17+t1.c) from t1 where t1.f in (select cast(avg(17) AS integer) from t1 union select cast(avg(t1.c) AS integer) from t1)),t1.d)<>19 then 19 else t1.a+ -(b)+t1.c end<=t1.c),t1.b)>t1.d) or (e) in (t1.c,f,13) or d in (select +count(*) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.774 {
  db eval {SELECT 17-13-case 19 when 17+case case t1.b when t1.b then coalesce((select coalesce((select 11 from t1 where (coalesce((select t1.a from t1 where (abs(f)/abs(case t1.e when 11 then a else t1.c end))<c),b)*a- -t1.e) not between t1.e and  -13),19) from t1 where d>19 or d not between f and t1.e),(t1.c)) else 11 end when  -a then 13 else e end then t1.b else b end+t1.c FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select e from t1 where case when not exists(select 1 from t1 where not not exists(select 1 from t1 where f<> -t1.e-t1.c)) or coalesce((select max(17+t1.c) from t1 where t1.f in (select cast(avg(17) AS integer) from t1 union select cast(avg(t1.c) AS integer) from t1)),t1.d)<>19 then 19 else t1.a+ -(b)+t1.c end<=t1.c),t1.b)>t1.d) or (e) in (t1.c,f,13) or d in (select +count(*) from t1 union select count(*) from t1))}
} {104}
do_test randexpr-2.775 {
  db eval {SELECT t1.e*(abs(coalesce((select max(case when t1.c in (select (case when d>13 then t1.c else 11 end+e) from t1 union select t1.a from t1) or t1.a between 17 and c then c when t1.d>=a then t1.c else t1.e end-t1.e*t1.b-d) from t1 where b<>(t1.c) or not exists(select 1 from t1 where b in (t1.d,13,a))),11)*t1.a)/abs(t1.a))+t1.c FROM t1 WHERE a>c}
} {}
do_test randexpr-2.776 {
  db eval {SELECT t1.e*(abs(coalesce((select max(case when t1.c in (select (case when d>13 then t1.c else 11 end+e) from t1 union select t1.a from t1) or t1.a between 17 and c then c when t1.d>=a then t1.c else t1.e end-t1.e*t1.b-d) from t1 where b<>(t1.c) or not exists(select 1 from t1 where b in (t1.d,13,a))),11)*t1.a)/abs(t1.a))+t1.c FROM t1 WHERE NOT (a>c)}
} {50050300}
do_test randexpr-2.777 {
  db eval {SELECT t1.d*(+coalesce((select max(case when coalesce((select (abs(f)/abs((abs(d)/abs((select cast(avg(19+11) AS integer) from t1)))+t1.b)) from t1 where exists(select 1 from t1 where t1.d not between t1.f and t1.e)),17) not in (17,t1.f, -t1.b) then 19 else  -19 end) from t1 where exists(select 1 from t1 where 11 in (select abs(count(distinct t1.f)) from t1 union select cast(avg(t1.e) AS integer) from t1) and exists(select 1 from t1 where t1.f<t1.c) or 17<f)),13)+13) FROM t1 WHERE not exists(select 1 from t1 where t1.c*coalesce((select max(19) from t1 where a between (select abs(+min(b)*case cast(avg(b) AS integer) when case  -(count(distinct 11)) when max(coalesce((select 11 from t1 where c in (13,17,t1.b)),b)) then  -count(*) else (cast(avg(19) AS integer)) end+max(11) then max(t1.e) else count(*) end | count(*))+count(*) from t1) and ~a),(select  -count(*) from t1)) between t1.c and 13-d)}
} {12800}
do_test randexpr-2.778 {
  db eval {SELECT t1.d*(+coalesce((select max(case when coalesce((select (abs(f)/abs((abs(d)/abs((select cast(avg(19+11) AS integer) from t1)))+t1.b)) from t1 where exists(select 1 from t1 where t1.d not between t1.f and t1.e)),17) not in (17,t1.f, -t1.b) then 19 else  -19 end) from t1 where exists(select 1 from t1 where 11 in (select abs(count(distinct t1.f)) from t1 union select cast(avg(t1.e) AS integer) from t1) and exists(select 1 from t1 where t1.f<t1.c) or 17<f)),13)+13) FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.c*coalesce((select max(19) from t1 where a between (select abs(+min(b)*case cast(avg(b) AS integer) when case  -(count(distinct 11)) when max(coalesce((select 11 from t1 where c in (13,17,t1.b)),b)) then  -count(*) else (cast(avg(19) AS integer)) end+max(11) then max(t1.e) else count(*) end | count(*))+count(*) from t1) and ~a),(select  -count(*) from t1)) between t1.c and 13-d))}
} {}
do_test randexpr-2.779 {
  db eval {SELECT coalesce((select max(coalesce((select (select cast(avg(d) AS integer) | case max(~f) | count(distinct t1.d) when count(*) then count(*) else  -min(17) end from t1) from t1 where b=t1.e+ -e or t1.a not in (t1.f,t1.d,t1.d) or f not in (t1.a, -t1.b,f)),t1.c)+b | 13-d) from t1 where t1.b> -11),(17)) | b-19*d FROM t1 WHERE b>coalesce((select max(13+d) from t1 where 17>=11),t1.b)}
} {}
do_test randexpr-2.780 {
  db eval {SELECT coalesce((select max(coalesce((select (select cast(avg(d) AS integer) | case max(~f) | count(distinct t1.d) when count(*) then count(*) else  -min(17) end from t1) from t1 where b=t1.e+ -e or t1.a not in (t1.f,t1.d,t1.d) or f not in (t1.a, -t1.b,f)),t1.c)+b | 13-d) from t1 where t1.b> -11),(17)) | b-19*d FROM t1 WHERE NOT (b>coalesce((select max(13+d) from t1 where 17>=11),t1.b))}
} {-1}
do_test randexpr-2.781 {
  db eval {SELECT coalesce((select max(coalesce((select (select cast(avg(d) AS integer) & case max(~f) & count(distinct t1.d) when count(*) then count(*) else  -min(17) end from t1) from t1 where b=t1.e+ -e or t1.a not in (t1.f,t1.d,t1.d) or f not in (t1.a, -t1.b,f)),t1.c)+b & 13-d) from t1 where t1.b> -11),(17)) & b-19*d FROM t1 WHERE NOT (b>coalesce((select max(13+d) from t1 where 17>=11),t1.b))}
} {8}
do_test randexpr-2.782 {
  db eval {SELECT (d+f*t1.c-t1.e+coalesce((select c from t1 where c>=a),case when (c in (select e from t1 union select 13 from t1)) then 11+a else f end))-13 FROM t1 WHERE c not between c and b+coalesce((select c from t1 where t1.d<case when 13 not in (case a when b then coalesce((select max(case when f in (select case when ((t1.c | t1.f not between c and 13)) then t1.e-(t1.a) else 17 end from t1 union select 13 from t1) then t1.e else e end*a) from t1 where 11=17),t1.f) else f end,17,t1.f) then t1.d else t1.d end+t1.a | b),f)}
} {}
do_test randexpr-2.783 {
  db eval {SELECT (d+f*t1.c-t1.e+coalesce((select c from t1 where c>=a),case when (c in (select e from t1 union select 13 from t1)) then 11+a else f end))-13 FROM t1 WHERE NOT (c not between c and b+coalesce((select c from t1 where t1.d<case when 13 not in (case a when b then coalesce((select max(case when f in (select case when ((t1.c | t1.f not between c and 13)) then t1.e-(t1.a) else 17 end from t1 union select 13 from t1) then t1.e else e end*a) from t1 where 11=17),t1.f) else f end,17,t1.f) then t1.d else t1.d end+t1.a | b),f))}
} {180187}
do_test randexpr-2.784 {
  db eval {SELECT case when t1.e not in (t1.a,~case when case when 17>=d then (abs(13)/abs(t1.f)) when (d in ((select abs(min(19)) from t1), -(select count(*)-abs( -count(*)) from t1),t1.e)) then coalesce((select max(19) from t1 where (c)>t1.f),17) else 13 end<>a then 11 when b<(d) then b else c end,d) then 17 when (17 in (13,t1.a,t1.c)) then e else c end+t1.c FROM t1 WHERE t1.a+t1.e in (select 19 from t1 union select t1.c from t1)}
} {}
do_test randexpr-2.785 {
  db eval {SELECT case when t1.e not in (t1.a,~case when case when 17>=d then (abs(13)/abs(t1.f)) when (d in ((select abs(min(19)) from t1), -(select count(*)-abs( -count(*)) from t1),t1.e)) then coalesce((select max(19) from t1 where (c)>t1.f),17) else 13 end<>a then 11 when b<(d) then b else c end,d) then 17 when (17 in (13,t1.a,t1.c)) then e else c end+t1.c FROM t1 WHERE NOT (t1.a+t1.e in (select 19 from t1 union select t1.c from t1))}
} {317}
do_test randexpr-2.786 {
  db eval {SELECT (select ~cast(avg(t1.c) AS integer)*case count(*) | +min(case +case when a<13 or case t1.f when c then 17 else t1.d end in (11,a,(t1.a)) and a<>a then t1.b+f when f not in (d,t1.a,c) then t1.f else t1.e end when t1.f then 17 else f end)+abs(++count(distinct 19))*(count(distinct 13))-count(distinct t1.e)-(count(*))*max(19) when max(11) then cast(avg(a) AS integer) else min(t1.f) end from t1) FROM t1 WHERE t1.a not between 17 and d}
} {}
do_test randexpr-2.787 {
  db eval {SELECT (select ~cast(avg(t1.c) AS integer)*case count(*) | +min(case +case when a<13 or case t1.f when c then 17 else t1.d end in (11,a,(t1.a)) and a<>a then t1.b+f when f not in (d,t1.a,c) then t1.f else t1.e end when t1.f then 17 else f end)+abs(++count(distinct 19))*(count(distinct 13))-count(distinct t1.e)-(count(*))*max(19) when max(11) then cast(avg(a) AS integer) else min(t1.f) end from t1) FROM t1 WHERE NOT (t1.a not between 17 and d)}
} {-180600}
do_test randexpr-2.788 {
  db eval {SELECT (select ~cast(avg(t1.c) AS integer)*case count(*) & +min(case +case when a<13 or case t1.f when c then 17 else t1.d end in (11,a,(t1.a)) and a<>a then t1.b+f when f not in (d,t1.a,c) then t1.f else t1.e end when t1.f then 17 else f end)+abs(++count(distinct 19))*(count(distinct 13))-count(distinct t1.e)-(count(*))*max(19) when max(11) then cast(avg(a) AS integer) else min(t1.f) end from t1) FROM t1 WHERE NOT (t1.a not between 17 and d)}
} {-180600}
do_test randexpr-2.789 {
  db eval {SELECT case t1.a when c then  -~t1.d*t1.e-coalesce((select max((abs(d+e+d)/abs(case when 11-t1.d in (select t1.d from t1 union select coalesce((select t1.c from t1 where 17<=t1.d and e between 11 and a),c) from t1) or 11 in (select ( -+(count(*))) from t1 union select count(distinct  -t1.a) from t1) then (f) when b=a then c else t1.b end))) from t1 where t1.c not between 17 and t1.b),13)+t1.f else d end FROM t1 WHERE not exists(select 1 from t1 where f<=a)}
} {400}
do_test randexpr-2.790 {
  db eval {SELECT case t1.a when c then  -~t1.d*t1.e-coalesce((select max((abs(d+e+d)/abs(case when 11-t1.d in (select t1.d from t1 union select coalesce((select t1.c from t1 where 17<=t1.d and e between 11 and a),c) from t1) or 11 in (select ( -+(count(*))) from t1 union select count(distinct  -t1.a) from t1) then (f) when b=a then c else t1.b end))) from t1 where t1.c not between 17 and t1.b),13)+t1.f else d end FROM t1 WHERE NOT (not exists(select 1 from t1 where f<=a))}
} {}
do_test randexpr-2.791 {
  db eval {SELECT (select  -max(d) from t1)+coalesce((select max(t1.e*t1.d*f) from t1 where t1.b-coalesce((select  -a*d from t1 where t1.c not in (t1.f,coalesce((select b+t1.b from t1 where t1.a not between f and t1.b),coalesce((select  -b from t1 where (t1.d>=t1.c) and 19<>t1.f),t1.a))-e*a,e)),(t1.a))+t1.f between 19 and e),t1.a)*a FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where case when t1.d-t1.b-t1.d*(case when t1.b>= -t1.d then c when t1.d not between c and t1.d then (19) else d end*e)+t1.d | 19>t1.c then e when exists(select 1 from t1 where t1.e not between d and t1.b or (17 in (t1.e, - -a,t1.d))) then t1.f else (e) end between 13 and e or 11>t1.b))}
} {9600}
do_test randexpr-2.792 {
  db eval {SELECT (select  -max(d) from t1)+coalesce((select max(t1.e*t1.d*f) from t1 where t1.b-coalesce((select  -a*d from t1 where t1.c not in (t1.f,coalesce((select b+t1.b from t1 where t1.a not between f and t1.b),coalesce((select  -b from t1 where (t1.d>=t1.c) and 19<>t1.f),t1.a))-e*a,e)),(t1.a))+t1.f between 19 and e),t1.a)*a FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where case when t1.d-t1.b-t1.d*(case when t1.b>= -t1.d then c when t1.d not between c and t1.d then (19) else d end*e)+t1.d | 19>t1.c then e when exists(select 1 from t1 where t1.e not between d and t1.b or (17 in (t1.e, - -a,t1.d))) then t1.f else (e) end between 13 and e or 11>t1.b)))}
} {}
do_test randexpr-2.793 {
  db eval {SELECT 11-t1.d-t1.e-case when (select count(distinct t1.b+coalesce((select max((abs(19)/abs(case when coalesce((select t1.f from t1 where e not between t1.f and t1.f),f)*( -11)=((e)) then 11 else d end))) from t1 where e in (17,t1.b,t1.b)), -t1.a)-(t1.c)) from t1)>t1.f then t1.b when 11>13 and a>=f then 11 else d end-t1.f FROM t1 WHERE (select min(d)-case cast(avg(case (d-~t1.c+~(select max(+d-coalesce((select max(t1.f) from t1 where c<>e),t1.a))-(( - -(cast(avg(13) AS integer)))-count(distinct e))*max(17) from t1) | 19-13*b) when  -t1.d then 13 else  -13 end) AS integer) when min(t1.c) then cast(avg(e) AS integer) else ~count(*) end from t1)<b}
} {}
do_test randexpr-2.794 {
  db eval {SELECT 11-t1.d-t1.e-case when (select count(distinct t1.b+coalesce((select max((abs(19)/abs(case when coalesce((select t1.f from t1 where e not between t1.f and t1.f),f)*( -11)=((e)) then 11 else d end))) from t1 where e in (17,t1.b,t1.b)), -t1.a)-(t1.c)) from t1)>t1.f then t1.b when 11>13 and a>=f then 11 else d end-t1.f FROM t1 WHERE NOT ((select min(d)-case cast(avg(case (d-~t1.c+~(select max(+d-coalesce((select max(t1.f) from t1 where c<>e),t1.a))-(( - -(cast(avg(13) AS integer)))-count(distinct e))*max(17) from t1) | 19-13*b) when  -t1.d then 13 else  -13 end) AS integer) when min(t1.c) then cast(avg(e) AS integer) else ~count(*) end from t1)<b)}
} {-1889}
do_test randexpr-2.795 {
  db eval {SELECT case f when 13 then 19 else case when (case when c not between b and d then t1.c when +~t1.d+(select  -+cast(avg(t1.a) AS integer) | ((max(t1.d)))*(max(e)) from t1)-19+t1.a*t1.d in (select ~max(c) from t1 union select count(distinct d)-count(distinct b) from t1) then f else  -11 end not between 11 and 11) or 17>(c) then t1.d else 13 end end FROM t1 WHERE not ((abs(f)/abs(t1.b))<=(select min(+t1.d)+~+case count(distinct (abs(case d when 11 then coalesce((select coalesce((select max(t1.a) from t1 where t1.b=t1.e),t1.f) | a from t1 where 13<>(a)),d) else 17 end*f)/abs(t1.f))) when cast(avg(t1.c) AS integer) then case count(*) when min(t1.b) | cast(avg(t1.c) AS integer) then count(distinct f) else max(17) end else cast(avg((c)) AS integer) end from t1))}
} {}
do_test randexpr-2.796 {
  db eval {SELECT case f when 13 then 19 else case when (case when c not between b and d then t1.c when +~t1.d+(select  -+cast(avg(t1.a) AS integer) | ((max(t1.d)))*(max(e)) from t1)-19+t1.a*t1.d in (select ~max(c) from t1 union select count(distinct d)-count(distinct b) from t1) then f else  -11 end not between 11 and 11) or 17>(c) then t1.d else 13 end end FROM t1 WHERE NOT (not ((abs(f)/abs(t1.b))<=(select min(+t1.d)+~+case count(distinct (abs(case d when 11 then coalesce((select coalesce((select max(t1.a) from t1 where t1.b=t1.e),t1.f) | a from t1 where 13<>(a)),d) else 17 end*f)/abs(t1.f))) when cast(avg(t1.c) AS integer) then case count(*) when min(t1.b) | cast(avg(t1.c) AS integer) then count(distinct f) else max(17) end else cast(avg((c)) AS integer) end from t1)))}
} {400}
do_test randexpr-2.797 {
  db eval {SELECT case f when 13 then 19 else case when (case when c not between b and d then t1.c when +~t1.d+(select  -+cast(avg(t1.a) AS integer) & ((max(t1.d)))*(max(e)) from t1)-19+t1.a*t1.d in (select ~max(c) from t1 union select count(distinct d)-count(distinct b) from t1) then f else  -11 end not between 11 and 11) or 17>(c) then t1.d else 13 end end FROM t1 WHERE NOT (not ((abs(f)/abs(t1.b))<=(select min(+t1.d)+~+case count(distinct (abs(case d when 11 then coalesce((select coalesce((select max(t1.a) from t1 where t1.b=t1.e),t1.f) | a from t1 where 13<>(a)),d) else 17 end*f)/abs(t1.f))) when cast(avg(t1.c) AS integer) then case count(*) when min(t1.b) | cast(avg(t1.c) AS integer) then count(distinct f) else max(17) end else cast(avg((c)) AS integer) end from t1)))}
} {400}
do_test randexpr-2.798 {
  db eval {SELECT f+case when (not exists(select 1 from t1 where ((17<>+t1.b+t1.f or b between t1.e and t1.e)))) then (abs( -(abs(case when exists(select 1 from t1 where not exists(select 1 from t1 where d in (select (select cast(avg((t1.b)) AS integer)-count(*) from t1) from t1 union select t1.e+(11) from t1))) then c when not t1.d between f and 11 or d>a then (a) else 13 end+t1.e+e)/abs(d)))/abs(t1.b)) else f end-13 FROM t1 WHERE case when 17< - -t1.b-case when not exists(select 1 from t1 where 19<>t1.d) then 13+coalesce((select max((abs((case case when  - -t1.c*11 in (select +max(t1.d)*count(distinct  -t1.c) from t1 union select max(t1.b) from t1) then 13 else 19 end when f then 19 else (t1.d) end)+e)/abs(f))) from t1 where (13 between t1.d and 19)),t1.b) else 13 end then a else t1.a end-13 not in (t1.d,d,(t1.f))}
} {1187}
do_test randexpr-2.799 {
  db eval {SELECT f+case when (not exists(select 1 from t1 where ((17<>+t1.b+t1.f or b between t1.e and t1.e)))) then (abs( -(abs(case when exists(select 1 from t1 where not exists(select 1 from t1 where d in (select (select cast(avg((t1.b)) AS integer)-count(*) from t1) from t1 union select t1.e+(11) from t1))) then c when not t1.d between f and 11 or d>a then (a) else 13 end+t1.e+e)/abs(d)))/abs(t1.b)) else f end-13 FROM t1 WHERE NOT (case when 17< - -t1.b-case when not exists(select 1 from t1 where 19<>t1.d) then 13+coalesce((select max((abs((case case when  - -t1.c*11 in (select +max(t1.d)*count(distinct  -t1.c) from t1 union select max(t1.b) from t1) then 13 else 19 end when f then 19 else (t1.d) end)+e)/abs(f))) from t1 where (13 between t1.d and 19)),t1.b) else 13 end then a else t1.a end-13 not in (t1.d,d,(t1.f)))}
} {}
do_test randexpr-2.800 {
  db eval {SELECT +~t1.a-(abs(+case when (((t1.d*t1.c+11 in (select cast(avg(17) AS integer) from t1 union select  -(count(*)) from t1)))) then  -coalesce((select t1.e-b from t1 where not exists(select 1 from t1 where t1.c in (select max(f) from t1 union select max(e) | max( -t1.e)-count(*) from t1))),f) else f end)/abs(t1.f))-e+11+t1.b+t1.a- -17 FROM t1 WHERE +b between case when c<=t1.a then t1.b when case when  -t1.a*d-17+17*~e- -13 in (select + -max(19) | +cast(avg(19) AS integer) from t1 union select (count(distinct  -19)*case max((13)) when max(e)*count(*) then min(t1.d) else count(*) end) from t1) then t1.f else (d) end in (select e from t1 union select d from t1) then f else  -t1.b end and b}
} {}
do_test randexpr-2.801 {
  db eval {SELECT +~t1.a-(abs(+case when (((t1.d*t1.c+11 in (select cast(avg(17) AS integer) from t1 union select  -(count(*)) from t1)))) then  -coalesce((select t1.e-b from t1 where not exists(select 1 from t1 where t1.c in (select max(f) from t1 union select max(e) | max( -t1.e)-count(*) from t1))),f) else f end)/abs(t1.f))-e+11+t1.b+t1.a- -17 FROM t1 WHERE NOT (+b between case when c<=t1.a then t1.b when case when  -t1.a*d-17+17*~e- -13 in (select + -max(19) | +cast(avg(19) AS integer) from t1 union select (count(distinct  -19)*case max((13)) when max(e)*count(*) then min(t1.d) else count(*) end) from t1) then t1.f else (d) end in (select e from t1 union select d from t1) then f else  -t1.b end and b)}
} {-274}
do_test randexpr-2.802 {
  db eval {SELECT +~t1.a-(abs(+case when (((t1.d*t1.c+11 in (select cast(avg(17) AS integer) from t1 union select  -(count(*)) from t1)))) then  -coalesce((select t1.e-b from t1 where not exists(select 1 from t1 where t1.c in (select max(f) from t1 union select max(e) & max( -t1.e)-count(*) from t1))),f) else f end)/abs(t1.f))-e+11+t1.b+t1.a- -17 FROM t1 WHERE NOT (+b between case when c<=t1.a then t1.b when case when  -t1.a*d-17+17*~e- -13 in (select + -max(19) | +cast(avg(19) AS integer) from t1 union select (count(distinct  -19)*case max((13)) when max(e)*count(*) then min(t1.d) else count(*) end) from t1) then t1.f else (d) end in (select e from t1 union select d from t1) then f else  -t1.b end and b)}
} {-274}
do_test randexpr-2.803 {
  db eval {SELECT case when 19=(select ( -count(*)* -(cast(avg(t1.e) AS integer))+count(distinct 13)*min(t1.f)) | cast(avg(t1.e) AS integer) |  -cast(avg(13) AS integer)-(min(d)) from t1) then 13*a when t1.a+((select min((t1.d)) from t1)) in (select t1.b from t1 union select 11 from t1) or not exists(select 1 from t1 where not exists(select 1 from t1 where  - -e in (select t1.e from t1 union select t1.d from t1) or t1.d in (select count(distinct t1.a) from t1 union select count(*) from t1)) or  -b=(19) and 11<c) then b else t1.c end*a FROM t1 WHERE 17-case 19 when t1.f-+(t1.d)-t1.a*t1.a then ~t1.d | e*coalesce((select b from t1 where 17< -17), -f)-17 else 19 end-case when (~t1.d)*17<f then f when t1.c in (f,a,t1.e) then t1.f else 17 end not in (t1.c,e,t1.d)}
} {20000}
do_test randexpr-2.804 {
  db eval {SELECT case when 19=(select ( -count(*)* -(cast(avg(t1.e) AS integer))+count(distinct 13)*min(t1.f)) | cast(avg(t1.e) AS integer) |  -cast(avg(13) AS integer)-(min(d)) from t1) then 13*a when t1.a+((select min((t1.d)) from t1)) in (select t1.b from t1 union select 11 from t1) or not exists(select 1 from t1 where not exists(select 1 from t1 where  - -e in (select t1.e from t1 union select t1.d from t1) or t1.d in (select count(distinct t1.a) from t1 union select count(*) from t1)) or  -b=(19) and 11<c) then b else t1.c end*a FROM t1 WHERE NOT (17-case 19 when t1.f-+(t1.d)-t1.a*t1.a then ~t1.d | e*coalesce((select b from t1 where 17< -17), -f)-17 else 19 end-case when (~t1.d)*17<f then f when t1.c in (f,a,t1.e) then t1.f else 17 end not in (t1.c,e,t1.d))}
} {}
do_test randexpr-2.805 {
  db eval {SELECT case when 19=(select ( -count(*)* -(cast(avg(t1.e) AS integer))+count(distinct 13)*min(t1.f)) & cast(avg(t1.e) AS integer) &  -cast(avg(13) AS integer)-(min(d)) from t1) then 13*a when t1.a+((select min((t1.d)) from t1)) in (select t1.b from t1 union select 11 from t1) or not exists(select 1 from t1 where not exists(select 1 from t1 where  - -e in (select t1.e from t1 union select t1.d from t1) or t1.d in (select count(distinct t1.a) from t1 union select count(*) from t1)) or  -b=(19) and 11<c) then b else t1.c end*a FROM t1 WHERE 17-case 19 when t1.f-+(t1.d)-t1.a*t1.a then ~t1.d | e*coalesce((select b from t1 where 17< -17), -f)-17 else 19 end-case when (~t1.d)*17<f then f when t1.c in (f,a,t1.e) then t1.f else 17 end not in (t1.c,e,t1.d)}
} {20000}
do_test randexpr-2.806 {
  db eval {SELECT +t1.a*11+case when 19<13-11 or exists(select 1 from t1 where not (abs(f)/abs(+t1.a+t1.c*t1.d-t1.c))*t1.a between t1.e and 17) then coalesce((select max(t1.a) from t1 where t1.b not between t1.a and t1.a),17) when 13 not between  -f and  -t1.d then t1.c else d end-13-13*c*t1.e FROM t1 WHERE 19<=case t1.b when  -t1.d+c-t1.a-19-t1.f*t1.b-coalesce((select max(coalesce((select max( -b) from t1 where not t1.f+19 in (select case cast(avg(17) AS integer) when min(t1.a) then max((d)) else max(b) end | count(*) from t1 union select max(13) from t1) and not exists(select 1 from t1 where t1.c not between 19 and 11)),t1.e)*19) from t1 where 13 in (select  -d from t1 union select t1.f from t1)),b)-e-(t1.e) then t1.f else t1.e end}
} {-1948813}
do_test randexpr-2.807 {
  db eval {SELECT +t1.a*11+case when 19<13-11 or exists(select 1 from t1 where not (abs(f)/abs(+t1.a+t1.c*t1.d-t1.c))*t1.a between t1.e and 17) then coalesce((select max(t1.a) from t1 where t1.b not between t1.a and t1.a),17) when 13 not between  -f and  -t1.d then t1.c else d end-13-13*c*t1.e FROM t1 WHERE NOT (19<=case t1.b when  -t1.d+c-t1.a-19-t1.f*t1.b-coalesce((select max(coalesce((select max( -b) from t1 where not t1.f+19 in (select case cast(avg(17) AS integer) when min(t1.a) then max((d)) else max(b) end | count(*) from t1 union select max(13) from t1) and not exists(select 1 from t1 where t1.c not between 19 and 11)),t1.e)*19) from t1 where 13 in (select  -d from t1 union select t1.f from t1)),b)-e-(t1.e) then t1.f else t1.e end)}
} {}
do_test randexpr-2.808 {
  db eval {SELECT case (abs(f)/abs(f)) when t1.e*t1.f then (abs(t1.d)/abs(t1.b*11)) else ~case when case ~~19 when t1.f then e else case coalesce((select (abs(f)/abs(a)) from t1 where t1.a<>17 and t1.a>= -t1.b),t1.f) when t1.d then c else t1.d end end in (select count(*) from t1 union select ~abs(min(t1.a)) | count(*) from t1) then 17 when t1.f not between (e) and t1.c then f else b end+c+a end FROM t1 WHERE t1.f in (case when ~(select max(d) from t1)*t1.f>=case when 17*d<t1.f then d when (t1.d) not between t1.e-t1.d-e and +(t1.e*13*(select case count(*) when  -count(distinct e) then max(13) else count(distinct t1.b) end from t1)-case when c<e then c else 11 end)-17 then  -c else t1.c end then e else (13) end+d,t1.a,11)}
} {}
do_test randexpr-2.809 {
  db eval {SELECT case (abs(f)/abs(f)) when t1.e*t1.f then (abs(t1.d)/abs(t1.b*11)) else ~case when case ~~19 when t1.f then e else case coalesce((select (abs(f)/abs(a)) from t1 where t1.a<>17 and t1.a>= -t1.b),t1.f) when t1.d then c else t1.d end end in (select count(*) from t1 union select ~abs(min(t1.a)) | count(*) from t1) then 17 when t1.f not between (e) and t1.c then f else b end+c+a end FROM t1 WHERE NOT (t1.f in (case when ~(select max(d) from t1)*t1.f>=case when 17*d<t1.f then d when (t1.d) not between t1.e-t1.d-e and +(t1.e*13*(select case count(*) when  -count(distinct e) then max(13) else count(distinct t1.b) end from t1)-case when c<e then c else 11 end)-17 then  -c else t1.c end then e else (13) end+d,t1.a,11))}
} {-201}
do_test randexpr-2.810 {
  db eval {SELECT case (abs(f)/abs(f)) when t1.e*t1.f then (abs(t1.d)/abs(t1.b*11)) else ~case when case ~~19 when t1.f then e else case coalesce((select (abs(f)/abs(a)) from t1 where t1.a<>17 and t1.a>= -t1.b),t1.f) when t1.d then c else t1.d end end in (select count(*) from t1 union select ~abs(min(t1.a)) & count(*) from t1) then 17 when t1.f not between (e) and t1.c then f else b end+c+a end FROM t1 WHERE NOT (t1.f in (case when ~(select max(d) from t1)*t1.f>=case when 17*d<t1.f then d when (t1.d) not between t1.e-t1.d-e and +(t1.e*13*(select case count(*) when  -count(distinct e) then max(13) else count(distinct t1.b) end from t1)-case when c<e then c else 11 end)-17 then  -c else t1.c end then e else (13) end+d,t1.a,11))}
} {-201}
do_test randexpr-2.811 {
  db eval {SELECT (abs(case when a*case when e<+(t1.e) then e else d end+t1.f<c then t1.e when d not between +13 and case when (e>=(select cast(avg(13) AS integer) from t1)) and (exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select t1.c from t1 where (b between d and 13)),t1.e)>13))) then case when b not between 19 and t1.c then a else 13 end+t1.b when t1.c>11 then c else b end then 13 else t1.d end*t1.f)/abs(17)) FROM t1 WHERE c not in (coalesce((select max(d) from t1 where (select min(t1.e) from t1)-17<=coalesce((select t1.c from t1 where exists(select 1 from t1 where 17<19 or coalesce((select 13 from t1 where t1.e not in (a+t1.c,t1.e*t1.a+t1.d* -a*(a)*f,((b)))),19) not in (c,t1.f,t1.b))),(select abs( -max(19)) from t1))),t1.f)-t1.b, -f,17)}
} {458}
do_test randexpr-2.812 {
  db eval {SELECT (abs(case when a*case when e<+(t1.e) then e else d end+t1.f<c then t1.e when d not between +13 and case when (e>=(select cast(avg(13) AS integer) from t1)) and (exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select t1.c from t1 where (b between d and 13)),t1.e)>13))) then case when b not between 19 and t1.c then a else 13 end+t1.b when t1.c>11 then c else b end then 13 else t1.d end*t1.f)/abs(17)) FROM t1 WHERE NOT (c not in (coalesce((select max(d) from t1 where (select min(t1.e) from t1)-17<=coalesce((select t1.c from t1 where exists(select 1 from t1 where 17<19 or coalesce((select 13 from t1 where t1.e not in (a+t1.c,t1.e*t1.a+t1.d* -a*(a)*f,((b)))),19) not in (c,t1.f,t1.b))),(select abs( -max(19)) from t1))),t1.f)-t1.b, -f,17))}
} {}
do_test randexpr-2.813 {
  db eval {SELECT t1.c*case when (t1.f in (select case (coalesce((select t1.d from t1 where not (coalesce((select d from t1 where f<=(11)),19)*e in (select ((min((17)) |  -min(t1.b))) from t1 union select  -cast(avg(t1.f) AS integer) from t1))),19)+11)*t1.a when t1.d then t1.a else f end-e-t1.a*( -17) from t1 union select c from t1) or 13 not between t1.e and b) then d+19-t1.f else t1.c end-e FROM t1 WHERE t1.f in (~t1.b,13,+e) and 11<>d-case when t1.e<>t1.b or f>t1.f and 19 not between 17 and case when (b not in (b,t1.d,a)) then e else (abs(11)/abs(d)) end and not exists(select 1 from t1 where t1.a<>c) then t1.f when not (t1.b) in (select t1.d from t1 union select t1.c from t1) then 13 else t1.b+a end}
} {}
do_test randexpr-2.814 {
  db eval {SELECT t1.c*case when (t1.f in (select case (coalesce((select t1.d from t1 where not (coalesce((select d from t1 where f<=(11)),19)*e in (select ((min((17)) |  -min(t1.b))) from t1 union select  -cast(avg(t1.f) AS integer) from t1))),19)+11)*t1.a when t1.d then t1.a else f end-e-t1.a*( -17) from t1 union select c from t1) or 13 not between t1.e and b) then d+19-t1.f else t1.c end-e FROM t1 WHERE NOT (t1.f in (~t1.b,13,+e) and 11<>d-case when t1.e<>t1.b or f>t1.f and 19 not between 17 and case when (b not in (b,t1.d,a)) then e else (abs(11)/abs(d)) end and not exists(select 1 from t1 where t1.a<>c) then t1.f when not (t1.b) in (select t1.d from t1 union select t1.c from t1) then 13 else t1.b+a end)}
} {-54800}
do_test randexpr-2.815 {
  db eval {SELECT t1.c*case when (t1.f in (select case (coalesce((select t1.d from t1 where not (coalesce((select d from t1 where f<=(11)),19)*e in (select ((min((17)) &  -min(t1.b))) from t1 union select  -cast(avg(t1.f) AS integer) from t1))),19)+11)*t1.a when t1.d then t1.a else f end-e-t1.a*( -17) from t1 union select c from t1) or 13 not between t1.e and b) then d+19-t1.f else t1.c end-e FROM t1 WHERE NOT (t1.f in (~t1.b,13,+e) and 11<>d-case when t1.e<>t1.b or f>t1.f and 19 not between 17 and case when (b not in (b,t1.d,a)) then e else (abs(11)/abs(d)) end and not exists(select 1 from t1 where t1.a<>c) then t1.f when not (t1.b) in (select t1.d from t1 union select t1.c from t1) then 13 else t1.b+a end)}
} {-54800}
do_test randexpr-2.816 {
  db eval {SELECT e-t1.e+a*f*11*c*case when ~f*t1.d-t1.c*b-13*19+(abs(t1.d)/abs(case when t1.c=13 then 17 else 19 end))*a between b*(select abs(cast(avg(( -13)) AS integer)) from t1)-19+19 and t1.b then t1.d else t1.d end+13 FROM t1 WHERE t1.b not between a and e}
} {}
do_test randexpr-2.817 {
  db eval {SELECT e-t1.e+a*f*11*c*case when ~f*t1.d-t1.c*b-13*19+(abs(t1.d)/abs(case when t1.c=13 then 17 else 19 end))*a between b*(select abs(cast(avg(( -13)) AS integer)) from t1)-19+19 and t1.b then t1.d else t1.d end+13 FROM t1 WHERE NOT (t1.b not between a and e)}
} {79200000013}
do_test randexpr-2.818 {
  db eval {SELECT case case when coalesce((select b from t1 where not exists(select 1 from t1 where d-e+coalesce((select max(b) from t1 where case case when t1.d-t1.e not between t1.f and e then 11 else t1.d end when t1.e then f else b end+t1.e=13),t1.c) not in (( -c),c,t1.d))),t1.f)<>a and c not in (t1.b,c,t1.a) then (select count(*) from t1) else c end-11 when t1.d then t1.e else c end FROM t1 WHERE ~b | coalesce((select case (select +count(distinct b) from t1) when coalesce((select case when coalesce((select e from t1 where c>b),t1.c) between 11 and (b) then t1.d else t1.b end-e from t1 where t1.d in (13,t1.a,f)),17) then e else 17 end from t1 where not b=t1.c or t1.d in (select abs(abs( -min(13)*(cast(avg(t1.c) AS integer)))) from t1 union select (max(c)) from t1) and b>t1.a),t1.f) in (select 11 from t1 union select c from t1)}
} {}
do_test randexpr-2.819 {
  db eval {SELECT case case when coalesce((select b from t1 where not exists(select 1 from t1 where d-e+coalesce((select max(b) from t1 where case case when t1.d-t1.e not between t1.f and e then 11 else t1.d end when t1.e then f else b end+t1.e=13),t1.c) not in (( -c),c,t1.d))),t1.f)<>a and c not in (t1.b,c,t1.a) then (select count(*) from t1) else c end-11 when t1.d then t1.e else c end FROM t1 WHERE NOT (~b | coalesce((select case (select +count(distinct b) from t1) when coalesce((select case when coalesce((select e from t1 where c>b),t1.c) between 11 and (b) then t1.d else t1.b end-e from t1 where t1.d in (13,t1.a,f)),17) then e else 17 end from t1 where not b=t1.c or t1.d in (select abs(abs( -min(13)*(cast(avg(t1.c) AS integer)))) from t1 union select (max(c)) from t1) and b>t1.a),t1.f) in (select 11 from t1 union select c from t1))}
} {300}
do_test randexpr-2.820 {
  db eval {SELECT case t1.c when t1.e then 19 else  -case when not exists(select 1 from t1 where t1.b in (select (t1.b) from t1 union select +13 from t1)) then coalesce((select max(c*t1.b) from t1 where 17>=19*e),coalesce((select (select abs(~min(coalesce((select max(t1.a) from t1 where  -19 in (f,a,13)),f)))+min(e) | ( -(min(13))) from t1) from t1 where f between  -a and t1.c),t1.e)) when 19<>a then 13 else c end end FROM t1 WHERE t1.e<>f}
} {-13}
do_test randexpr-2.821 {
  db eval {SELECT case t1.c when t1.e then 19 else  -case when not exists(select 1 from t1 where t1.b in (select (t1.b) from t1 union select +13 from t1)) then coalesce((select max(c*t1.b) from t1 where 17>=19*e),coalesce((select (select abs(~min(coalesce((select max(t1.a) from t1 where  -19 in (f,a,13)),f)))+min(e) | ( -(min(13))) from t1) from t1 where f between  -a and t1.c),t1.e)) when 19<>a then 13 else c end end FROM t1 WHERE NOT (t1.e<>f)}
} {}
do_test randexpr-2.822 {
  db eval {SELECT case t1.c when t1.e then 19 else  -case when not exists(select 1 from t1 where t1.b in (select (t1.b) from t1 union select +13 from t1)) then coalesce((select max(c*t1.b) from t1 where 17>=19*e),coalesce((select (select abs(~min(coalesce((select max(t1.a) from t1 where  -19 in (f,a,13)),f)))+min(e) & ( -(min(13))) from t1) from t1 where f between  -a and t1.c),t1.e)) when 19<>a then 13 else c end end FROM t1 WHERE t1.e<>f}
} {-13}
do_test randexpr-2.823 {
  db eval {SELECT 13- -(abs(coalesce((select max(17) from t1 where f*b in (select count(*)*case  -min(~t1.f)+min(coalesce((select  -(select min(17) from t1) from t1 where (t1.b in (select abs(min(t1.f)) from t1 union select  -max(t1.e) from t1))),17)+d) when count(distinct a) then abs(count(*)) else count(*) end from t1 union select min(t1.c) from t1)),coalesce((select max(f) from t1 where d in (select t1.b from t1 union select t1.e from t1)),17)) | t1.a)/abs(c)) | t1.f FROM t1 WHERE (abs(t1.f*11++ -f)/abs(19 | (abs(((abs(f)/abs(17))))/abs(case when a not in (t1.d,(c)-~c*f |  -13-t1.b+ -d,13) then t1.f when 11=11 then c else d end))*d+t1.c))+e+ -(t1.d) in (select t1.a from t1 union select 19 from t1)}
} {}
do_test randexpr-2.824 {
  db eval {SELECT 13- -(abs(coalesce((select max(17) from t1 where f*b in (select count(*)*case  -min(~t1.f)+min(coalesce((select  -(select min(17) from t1) from t1 where (t1.b in (select abs(min(t1.f)) from t1 union select  -max(t1.e) from t1))),17)+d) when count(distinct a) then abs(count(*)) else count(*) end from t1 union select min(t1.c) from t1)),coalesce((select max(f) from t1 where d in (select t1.b from t1 union select t1.e from t1)),17)) | t1.a)/abs(c)) | t1.f FROM t1 WHERE NOT ((abs(t1.f*11++ -f)/abs(19 | (abs(((abs(f)/abs(17))))/abs(case when a not in (t1.d,(c)-~c*f |  -13-t1.b+ -d,13) then t1.f when 11=11 then c else d end))*d+t1.c))+e+ -(t1.d) in (select t1.a from t1 union select 19 from t1))}
} {605}
do_test randexpr-2.825 {
  db eval {SELECT 13- -(abs(coalesce((select max(17) from t1 where f*b in (select count(*)*case  -min(~t1.f)+min(coalesce((select  -(select min(17) from t1) from t1 where (t1.b in (select abs(min(t1.f)) from t1 union select  -max(t1.e) from t1))),17)+d) when count(distinct a) then abs(count(*)) else count(*) end from t1 union select min(t1.c) from t1)),coalesce((select max(f) from t1 where d in (select t1.b from t1 union select t1.e from t1)),17)) & t1.a)/abs(c)) & t1.f FROM t1 WHERE NOT ((abs(t1.f*11++ -f)/abs(19 | (abs(((abs(f)/abs(17))))/abs(case when a not in (t1.d,(c)-~c*f |  -13-t1.b+ -d,13) then t1.f when 11=11 then c else d end))*d+t1.c))+e+ -(t1.d) in (select t1.a from t1 union select 19 from t1))}
} {8}
do_test randexpr-2.826 {
  db eval {SELECT (a+case when (exists(select 1 from t1 where not exists(select 1 from t1 where not t1.e*13=13-f or (e)=t1.c or  -d not between t1.b and t1.a or e not between 17 and (a) and 11 not in (a,(t1.f),a) or t1.e<>13 or t1.d between t1.e and t1.c or t1.d=17 or a>=b))) and a between t1.e and t1.b then case when e not between (17) and t1.d then ~c*coalesce((select t1.a | 13+d from t1 where t1.e not between b and 11),t1.a) else t1.f end else t1.f end-11) FROM t1 WHERE case when case case when case when  -(select +min(11) from t1)*(13)>11 then t1.e when 13<e then 19 else c end in (t1.a,a,t1.e) then 17 when c<>t1.a then t1.d else  -t1.e end when (a) then a else t1.e end>t1.a then 13 when t1.a not in (t1.f,t1.b,t1.a) then a else t1.c end in (select cast(avg(13) AS integer) from t1 union select (max(t1.e)+min(17)) from t1)}
} {689}
do_test randexpr-2.827 {
  db eval {SELECT (a+case when (exists(select 1 from t1 where not exists(select 1 from t1 where not t1.e*13=13-f or (e)=t1.c or  -d not between t1.b and t1.a or e not between 17 and (a) and 11 not in (a,(t1.f),a) or t1.e<>13 or t1.d between t1.e and t1.c or t1.d=17 or a>=b))) and a between t1.e and t1.b then case when e not between (17) and t1.d then ~c*coalesce((select t1.a | 13+d from t1 where t1.e not between b and 11),t1.a) else t1.f end else t1.f end-11) FROM t1 WHERE NOT (case when case case when case when  -(select +min(11) from t1)*(13)>11 then t1.e when 13<e then 19 else c end in (t1.a,a,t1.e) then 17 when c<>t1.a then t1.d else  -t1.e end when (a) then a else t1.e end>t1.a then 13 when t1.a not in (t1.f,t1.b,t1.a) then a else t1.c end in (select cast(avg(13) AS integer) from t1 union select (max(t1.e)+min(17)) from t1))}
} {}
do_test randexpr-2.828 {
  db eval {SELECT (a+case when (exists(select 1 from t1 where not exists(select 1 from t1 where not t1.e*13=13-f or (e)=t1.c or  -d not between t1.b and t1.a or e not between 17 and (a) and 11 not in (a,(t1.f),a) or t1.e<>13 or t1.d between t1.e and t1.c or t1.d=17 or a>=b))) and a between t1.e and t1.b then case when e not between (17) and t1.d then ~c*coalesce((select t1.a & 13+d from t1 where t1.e not between b and 11),t1.a) else t1.f end else t1.f end-11) FROM t1 WHERE case when case case when case when  -(select +min(11) from t1)*(13)>11 then t1.e when 13<e then 19 else c end in (t1.a,a,t1.e) then 17 when c<>t1.a then t1.d else  -t1.e end when (a) then a else t1.e end>t1.a then 13 when t1.a not in (t1.f,t1.b,t1.a) then a else t1.c end in (select cast(avg(13) AS integer) from t1 union select (max(t1.e)+min(17)) from t1)}
} {689}
do_test randexpr-2.829 {
  db eval {SELECT ~b-t1.a-f*+case when exists(select 1 from t1 where 17<>t1.d-f or not exists(select 1 from t1 where (select (min(a)+count(distinct d)) from t1)+( -f)- -c<t1.e or d not between t1.a and b and exists(select 1 from t1 where 11<(a)) and 13=d or 13 between (t1.f) and f)) then t1.b when a not in (e,d,d) then (select ((count(*))) from t1) else case d when d then  -e else 11 end end FROM t1 WHERE ~(abs(17)/abs((a)))*~t1.e-coalesce((select (abs((select abs(cast(avg(d) AS integer)) from t1) | 13*e+17)/abs(t1.f)) from t1 where t1.c<>f and not exists(select 1 from t1 where t1.c<b or 19 in (17,19,b) or 17 not between a and f) or a not in (c,b,17)),t1.c)+t1.a-e-t1.f*e+ -a-t1.a*d not in (d,( -f),t1.a)}
} {-120301}
do_test randexpr-2.830 {
  db eval {SELECT ~b-t1.a-f*+case when exists(select 1 from t1 where 17<>t1.d-f or not exists(select 1 from t1 where (select (min(a)+count(distinct d)) from t1)+( -f)- -c<t1.e or d not between t1.a and b and exists(select 1 from t1 where 11<(a)) and 13=d or 13 between (t1.f) and f)) then t1.b when a not in (e,d,d) then (select ((count(*))) from t1) else case d when d then  -e else 11 end end FROM t1 WHERE NOT (~(abs(17)/abs((a)))*~t1.e-coalesce((select (abs((select abs(cast(avg(d) AS integer)) from t1) | 13*e+17)/abs(t1.f)) from t1 where t1.c<>f and not exists(select 1 from t1 where t1.c<b or 19 in (17,19,b) or 17 not between a and f) or a not in (c,b,17)),t1.c)+t1.a-e-t1.f*e+ -a-t1.a*d not in (d,( -f),t1.a))}
} {}
do_test randexpr-2.831 {
  db eval {SELECT (t1.a)*t1.d*t1.c+t1.b*case when (select case count(*) when (count(*))+ - -count(*)+cast(avg(t1.d) AS integer)- - -min(f) then min(11) else cast(avg(c) AS integer) end from t1) in (select (cast(avg((19)) AS integer)) from t1 union select max(t1.e) from t1) then b when d=a then t1.f else coalesce((select t1.c from t1 where not exists(select 1 from t1 where (~+a not in ((a),b,t1.f)))),case e when 13 then t1.f else 13 end) end FROM t1 WHERE c | a | ~(t1.d)+t1.b not in (t1.a* -+13+~(abs( -case when (11) in (select e from t1 union select t1.f*coalesce((select case when e<e then t1.f when (13) in (13,t1.d,t1.c) then c else t1.d end from t1 where t1.b between  -11 and e),e) from t1) then t1.a else d end*t1.a)/abs(t1.e)),19,d) or t1.e<b}
} {12002600}
do_test randexpr-2.832 {
  db eval {SELECT (t1.a)*t1.d*t1.c+t1.b*case when (select case count(*) when (count(*))+ - -count(*)+cast(avg(t1.d) AS integer)- - -min(f) then min(11) else cast(avg(c) AS integer) end from t1) in (select (cast(avg((19)) AS integer)) from t1 union select max(t1.e) from t1) then b when d=a then t1.f else coalesce((select t1.c from t1 where not exists(select 1 from t1 where (~+a not in ((a),b,t1.f)))),case e when 13 then t1.f else 13 end) end FROM t1 WHERE NOT (c | a | ~(t1.d)+t1.b not in (t1.a* -+13+~(abs( -case when (11) in (select e from t1 union select t1.f*coalesce((select case when e<e then t1.f when (13) in (13,t1.d,t1.c) then c else t1.d end from t1 where t1.b between  -11 and e),e) from t1) then t1.a else d end*t1.a)/abs(t1.e)),19,d) or t1.e<b)}
} {}
do_test randexpr-2.833 {
  db eval {SELECT case when case ~( -t1.e)-a when coalesce((select max(case +t1.e when t1.b*~19 | t1.a*case when c-c<>19 then 13 else c end*d+t1.c then f else 17 end) from t1 where d<=e), -d) then 19 else 17 end in (t1.b,19,c) then 19 when t1.a in (select a from t1 union select 13 from t1) then t1.d else t1.d end FROM t1 WHERE (select abs(cast(avg(t1.d*t1.f) AS integer))-cast(avg(b) AS integer) from t1)-~coalesce((select max(t1.a+t1.d-coalesce((select max(a*case when t1.e<=e then f when t1.d<>a then 11 else 11 end*t1.a*11) from t1 where t1.d>=d),t1.f)) from t1 where 11 not between (13) and 17),f)*t1.b+17-e not in (t1.d,t1.f,t1.f)}
} {400}
do_test randexpr-2.834 {
  db eval {SELECT case when case ~( -t1.e)-a when coalesce((select max(case +t1.e when t1.b*~19 | t1.a*case when c-c<>19 then 13 else c end*d+t1.c then f else 17 end) from t1 where d<=e), -d) then 19 else 17 end in (t1.b,19,c) then 19 when t1.a in (select a from t1 union select 13 from t1) then t1.d else t1.d end FROM t1 WHERE NOT ((select abs(cast(avg(t1.d*t1.f) AS integer))-cast(avg(b) AS integer) from t1)-~coalesce((select max(t1.a+t1.d-coalesce((select max(a*case when t1.e<=e then f when t1.d<>a then 11 else 11 end*t1.a*11) from t1 where t1.d>=d),t1.f)) from t1 where 11 not between (13) and 17),f)*t1.b+17-e not in (t1.d,t1.f,t1.f))}
} {}
do_test randexpr-2.835 {
  db eval {SELECT case when case ~( -t1.e)-a when coalesce((select max(case +t1.e when t1.b*~19 & t1.a*case when c-c<>19 then 13 else c end*d+t1.c then f else 17 end) from t1 where d<=e), -d) then 19 else 17 end in (t1.b,19,c) then 19 when t1.a in (select a from t1 union select 13 from t1) then t1.d else t1.d end FROM t1 WHERE (select abs(cast(avg(t1.d*t1.f) AS integer))-cast(avg(b) AS integer) from t1)-~coalesce((select max(t1.a+t1.d-coalesce((select max(a*case when t1.e<=e then f when t1.d<>a then 11 else 11 end*t1.a*11) from t1 where t1.d>=d),t1.f)) from t1 where 11 not between (13) and 17),f)*t1.b+17-e not in (t1.d,t1.f,t1.f)}
} {400}
do_test randexpr-2.836 {
  db eval {SELECT t1.d+case when case when case when (19 not between ~(t1.a)*b and t1.c) then (select (abs(case count(distinct t1.e) when min( -f) then  -max(t1.d) else cast(avg(19) AS integer) end-(count(distinct t1.e)))) from t1) when a<>t1.f then  -19 else 11 end>f or b in ((13),f,11) then t1.a when t1.e in (e,f,t1.f) then (t1.d) else t1.d end in (17,t1.c,17) then 13 when b not between t1.a and (19) then t1.e else  -11 end+a+((f)) FROM t1 WHERE t1.f in (select case +cast(avg(t1.f+c) AS integer)++count(*) when count(*) then ~~(count(distinct 11+t1.a)) else +(case max(e-f) | ~ -max(t1.f) |  -abs(abs(min(e-19+e))-abs(count(*)))-abs(cast(avg(f) AS integer)) when (min(f)) then cast(avg(a) AS integer) else min(13) end) end from t1 union select  -count(distinct 13) from t1)}
} {}
do_test randexpr-2.837 {
  db eval {SELECT t1.d+case when case when case when (19 not between ~(t1.a)*b and t1.c) then (select (abs(case count(distinct t1.e) when min( -f) then  -max(t1.d) else cast(avg(19) AS integer) end-(count(distinct t1.e)))) from t1) when a<>t1.f then  -19 else 11 end>f or b in ((13),f,11) then t1.a when t1.e in (e,f,t1.f) then (t1.d) else t1.d end in (17,t1.c,17) then 13 when b not between t1.a and (19) then t1.e else  -11 end+a+((f)) FROM t1 WHERE NOT (t1.f in (select case +cast(avg(t1.f+c) AS integer)++count(*) when count(*) then ~~(count(distinct 11+t1.a)) else +(case max(e-f) | ~ -max(t1.f) |  -abs(abs(min(e-19+e))-abs(count(*)))-abs(cast(avg(f) AS integer)) when (min(f)) then cast(avg(a) AS integer) else min(13) end) end from t1 union select  -count(distinct 13) from t1))}
} {1600}
do_test randexpr-2.838 {
  db eval {SELECT (select (min(case when b+b*(select cast(avg(e+19-t1.f*case when case when not (c) in (select (e) from t1 union select f from t1) or t1.b not in (t1.e,t1.b,11) or 19= -t1.a then 17 else  -d end<e then e when t1.b>13 then 13 else t1.f end+11*19) AS integer) from t1)+d not between 11 and c then t1.c else t1.c end)) from t1) FROM t1 WHERE 13 not between +b* -f and coalesce((select f*19-case when not a=~f+t1.d then case when d*b not in (case when d not between  -c and t1.d then e else 13 end+17,c,t1.a) then b when t1.e>t1.f then b else  -d end else f end-e+(d) from t1 where 17 between t1.a and t1.e),t1.d) | t1.b}
} {}
do_test randexpr-2.839 {
  db eval {SELECT (select (min(case when b+b*(select cast(avg(e+19-t1.f*case when case when not (c) in (select (e) from t1 union select f from t1) or t1.b not in (t1.e,t1.b,11) or 19= -t1.a then 17 else  -d end<e then e when t1.b>13 then 13 else t1.f end+11*19) AS integer) from t1)+d not between 11 and c then t1.c else t1.c end)) from t1) FROM t1 WHERE NOT (13 not between +b* -f and coalesce((select f*19-case when not a=~f+t1.d then case when d*b not in (case when d not between  -c and t1.d then e else 13 end+17,c,t1.a) then b when t1.e>t1.f then b else  -d end else f end-e+(d) from t1 where 17 between t1.a and t1.e),t1.d) | t1.b)}
} {300}
do_test randexpr-2.840 {
  db eval {SELECT t1.c-(abs((select (case abs(count(distinct 11-c*11)) when count(*) then count(*) else  -min(+e+~e+coalesce((select d-a*t1.d+t1.e from t1 where (t1.f>=17) and t1.e in (11,a,e)),13)*t1.d) end) from t1)-(a-t1.f)-t1.d)/abs(d)) FROM t1 WHERE t1.c in (select d from t1 union select ( -t1.e) from t1)}
} {}
do_test randexpr-2.841 {
  db eval {SELECT t1.c-(abs((select (case abs(count(distinct 11-c*11)) when count(*) then count(*) else  -min(+e+~e+coalesce((select d-a*t1.d+t1.e from t1 where (t1.f>=17) and t1.e in (11,a,e)),13)*t1.d) end) from t1)-(a-t1.f)-t1.d)/abs(d)) FROM t1 WHERE NOT (t1.c in (select d from t1 union select ( -t1.e) from t1))}
} {300}
do_test randexpr-2.842 {
  db eval {SELECT case when coalesce((select max(t1.a-case when not (coalesce((select d+c from t1 where c between ( -(a)) and b or 17 between 11 and (c)),(t1.f)))=f then b | d when f not in (t1.b,f,a) then t1.a else f end-t1.f) from t1 where 19<=11 and t1.c between 19 and t1.a or t1.f>11), -t1.e)*e between b and 17 then  -t1.f when  -a<=19 or  -11<>t1.f then  -19 else d end FROM t1 WHERE ((13 in (t1.b,f,b)))}
} {}
do_test randexpr-2.843 {
  db eval {SELECT case when coalesce((select max(t1.a-case when not (coalesce((select d+c from t1 where c between ( -(a)) and b or 17 between 11 and (c)),(t1.f)))=f then b | d when f not in (t1.b,f,a) then t1.a else f end-t1.f) from t1 where 19<=11 and t1.c between 19 and t1.a or t1.f>11), -t1.e)*e between b and 17 then  -t1.f when  -a<=19 or  -11<>t1.f then  -19 else d end FROM t1 WHERE NOT (((13 in (t1.b,f,b))))}
} {-19}
do_test randexpr-2.844 {
  db eval {SELECT case when coalesce((select max(t1.a-case when not (coalesce((select d+c from t1 where c between ( -(a)) and b or 17 between 11 and (c)),(t1.f)))=f then b & d when f not in (t1.b,f,a) then t1.a else f end-t1.f) from t1 where 19<=11 and t1.c between 19 and t1.a or t1.f>11), -t1.e)*e between b and 17 then  -t1.f when  -a<=19 or  -11<>t1.f then  -19 else d end FROM t1 WHERE NOT (((13 in (t1.b,f,b))))}
} {-19}
do_test randexpr-2.845 {
  db eval {SELECT case  -(abs(t1.b-13*d*b*t1.e- -11)/abs(+d-t1.f*(11+ -13)-t1.c))+c+(e*t1.c)+f*17*a | t1.e-13+f when t1.d then t1.e else f end-t1.f FROM t1 WHERE  -b*t1.c>13}
} {}
do_test randexpr-2.846 {
  db eval {SELECT case  -(abs(t1.b-13*d*b*t1.e- -11)/abs(+d-t1.f*(11+ -13)-t1.c))+c+(e*t1.c)+f*17*a | t1.e-13+f when t1.d then t1.e else f end-t1.f FROM t1 WHERE NOT ( -b*t1.c>13)}
} {0}
do_test randexpr-2.847 {
  db eval {SELECT case  -(abs(t1.b-13*d*b*t1.e- -11)/abs(+d-t1.f*(11+ -13)-t1.c))+c+(e*t1.c)+f*17*a & t1.e-13+f when t1.d then t1.e else f end-t1.f FROM t1 WHERE NOT ( -b*t1.c>13)}
} {0}
do_test randexpr-2.848 {
  db eval {SELECT case when t1.c between t1.e and ~t1.d+(abs(~d*case t1.b-19 when t1.e then e else e end)/abs(case case t1.b when c then t1.d else 13+17 | e end when (select abs(abs(min(11) | max((a)))) from t1) then d else ~t1.f end)) | t1.b then t1.c when (not (11>=b)) then 13 else e end-a FROM t1 WHERE +13*case when +11*t1.f=f+t1.b then t1.f else t1.b end not between coalesce((select max(f) from t1 where (not exists(select 1 from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where t1.c in (select abs(min(e)) from t1 union select ~ -case cast(avg(~17) AS integer) when min(e | 17) then min(e) else cast(avg(c) AS integer) end from t1)))) or f>e*t1.a+e)),t1.c) and 17}
} {-87}
do_test randexpr-2.849 {
  db eval {SELECT case when t1.c between t1.e and ~t1.d+(abs(~d*case t1.b-19 when t1.e then e else e end)/abs(case case t1.b when c then t1.d else 13+17 | e end when (select abs(abs(min(11) | max((a)))) from t1) then d else ~t1.f end)) | t1.b then t1.c when (not (11>=b)) then 13 else e end-a FROM t1 WHERE NOT (+13*case when +11*t1.f=f+t1.b then t1.f else t1.b end not between coalesce((select max(f) from t1 where (not exists(select 1 from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where t1.c in (select abs(min(e)) from t1 union select ~ -case cast(avg(~17) AS integer) when min(e | 17) then min(e) else cast(avg(c) AS integer) end from t1)))) or f>e*t1.a+e)),t1.c) and 17)}
} {}
do_test randexpr-2.850 {
  db eval {SELECT case when t1.c between t1.e and ~t1.d+(abs(~d*case t1.b-19 when t1.e then e else e end)/abs(case case t1.b when c then t1.d else 13+17 & e end when (select abs(abs(min(11) & max((a)))) from t1) then d else ~t1.f end)) & t1.b then t1.c when (not (11>=b)) then 13 else e end-a FROM t1 WHERE +13*case when +11*t1.f=f+t1.b then t1.f else t1.b end not between coalesce((select max(f) from t1 where (not exists(select 1 from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where t1.c in (select abs(min(e)) from t1 union select ~ -case cast(avg(~17) AS integer) when min(e | 17) then min(e) else cast(avg(c) AS integer) end from t1)))) or f>e*t1.a+e)),t1.c) and 17}
} {-87}
do_test randexpr-2.851 {
  db eval {SELECT coalesce((select +case when case d when b then e else (select min(case b when 17 then b else t1.c end)+ -+ -(abs(max(t1.e))-min(t1.d)+max( -d)) | count(distinct t1.e)+( -cast(avg(13) AS integer)) | max(t1.f)+min(e)+count(*) from t1) end<>b then t1.a else 19*~t1.e-c | t1.c end from t1 where b in ( -c,t1.f,t1.c)),19) FROM t1 WHERE (abs(d)/abs(coalesce((select max(coalesce((select d*c from t1 where ((abs(t1.b)/abs(t1.d))-(abs(t1.f)/abs(t1.c))+(t1.a)*13-t1.e not between t1.e and ~f*11+t1.f-11 | t1.a+13+d)),19)) from t1 where c not in (+ -11,a,c)),t1.c))) in (b,b,a)}
} {}
do_test randexpr-2.852 {
  db eval {SELECT coalesce((select +case when case d when b then e else (select min(case b when 17 then b else t1.c end)+ -+ -(abs(max(t1.e))-min(t1.d)+max( -d)) | count(distinct t1.e)+( -cast(avg(13) AS integer)) | max(t1.f)+min(e)+count(*) from t1) end<>b then t1.a else 19*~t1.e-c | t1.c end from t1 where b in ( -c,t1.f,t1.c)),19) FROM t1 WHERE NOT ((abs(d)/abs(coalesce((select max(coalesce((select d*c from t1 where ((abs(t1.b)/abs(t1.d))-(abs(t1.f)/abs(t1.c))+(t1.a)*13-t1.e not between t1.e and ~f*11+t1.f-11 | t1.a+13+d)),19)) from t1 where c not in (+ -11,a,c)),t1.c))) in (b,b,a))}
} {19}
do_test randexpr-2.853 {
  db eval {SELECT coalesce((select +case when case d when b then e else (select min(case b when 17 then b else t1.c end)+ -+ -(abs(max(t1.e))-min(t1.d)+max( -d)) & count(distinct t1.e)+( -cast(avg(13) AS integer)) & max(t1.f)+min(e)+count(*) from t1) end<>b then t1.a else 19*~t1.e-c & t1.c end from t1 where b in ( -c,t1.f,t1.c)),19) FROM t1 WHERE NOT ((abs(d)/abs(coalesce((select max(coalesce((select d*c from t1 where ((abs(t1.b)/abs(t1.d))-(abs(t1.f)/abs(t1.c))+(t1.a)*13-t1.e not between t1.e and ~f*11+t1.f-11 | t1.a+13+d)),19)) from t1 where c not in (+ -11,a,c)),t1.c))) in (b,b,a))}
} {19}
do_test randexpr-2.854 {
  db eval {SELECT a-a-(abs(f)/abs(coalesce((select 17+19 from t1 where (select min(t1.e*e) from t1)>t1.b+case when not exists(select 1 from t1 where e not between 11 and t1.f-e) then coalesce((select max(f*case when t1.f not in (19,t1.c,(t1.a)) and c<=17 then 11 when 17 not between 11 and 17 then c else 17 end) from t1 where d not between t1.a and 13),t1.c) else t1.b end-13 and a=t1.e),17)+t1.c))-f FROM t1 WHERE +(select cast(avg(13-t1.a-t1.b++t1.a-(select count(*) from t1)+case b-(select +~ -min(case when exists(select 1 from t1 where ((select count(*)+ -(min(13)) from t1)) not between 13 and 13) then d else e end) from t1) when f*t1.b*t1.b then t1.a else b end*t1.a) AS integer) from t1)*t1.b in (t1.f,17,f)}
} {}
do_test randexpr-2.855 {
  db eval {SELECT a-a-(abs(f)/abs(coalesce((select 17+19 from t1 where (select min(t1.e*e) from t1)>t1.b+case when not exists(select 1 from t1 where e not between 11 and t1.f-e) then coalesce((select max(f*case when t1.f not in (19,t1.c,(t1.a)) and c<=17 then 11 when 17 not between 11 and 17 then c else 17 end) from t1 where d not between t1.a and 13),t1.c) else t1.b end-13 and a=t1.e),17)+t1.c))-f FROM t1 WHERE NOT (+(select cast(avg(13-t1.a-t1.b++t1.a-(select count(*) from t1)+case b-(select +~ -min(case when exists(select 1 from t1 where ((select count(*)+ -(min(13)) from t1)) not between 13 and 13) then d else e end) from t1) when f*t1.b*t1.b then t1.a else b end*t1.a) AS integer) from t1)*t1.b in (t1.f,17,f))}
} {-601}
do_test randexpr-2.856 {
  db eval {SELECT case when (11+19 | t1.e-e*17=t1.e*~d+t1.a+ -d | a-~(abs((abs((case when 13 not in (b,((t1.a)),f) then t1.d else t1.a end+e))/abs(t1.f))*b+t1.b)/abs(17))+t1.e+t1.a) then 11 else t1.a end FROM t1 WHERE case (case when (select +~ -~ -cast(avg(b*e*case when t1.a between t1.c and a and d<13 then b else 19 end* -f*d) AS integer) | count(*)++~+min((11))*max(19)-min((b)) from t1) in (select 13 from t1 union select (select min(19) from t1) from t1) then t1.f+t1.d else 13 end-t1.e) when t1.e then t1.f else a end<e}
} {100}
do_test randexpr-2.857 {
  db eval {SELECT case when (11+19 | t1.e-e*17=t1.e*~d+t1.a+ -d | a-~(abs((abs((case when 13 not in (b,((t1.a)),f) then t1.d else t1.a end+e))/abs(t1.f))*b+t1.b)/abs(17))+t1.e+t1.a) then 11 else t1.a end FROM t1 WHERE NOT (case (case when (select +~ -~ -cast(avg(b*e*case when t1.a between t1.c and a and d<13 then b else 19 end* -f*d) AS integer) | count(*)++~+min((11))*max(19)-min((b)) from t1) in (select 13 from t1 union select (select min(19) from t1) from t1) then t1.f+t1.d else 13 end-t1.e) when t1.e then t1.f else a end<e)}
} {}
do_test randexpr-2.858 {
  db eval {SELECT case when (11+19 & t1.e-e*17=t1.e*~d+t1.a+ -d & a-~(abs((abs((case when 13 not in (b,((t1.a)),f) then t1.d else t1.a end+e))/abs(t1.f))*b+t1.b)/abs(17))+t1.e+t1.a) then 11 else t1.a end FROM t1 WHERE case (case when (select +~ -~ -cast(avg(b*e*case when t1.a between t1.c and a and d<13 then b else 19 end* -f*d) AS integer) | count(*)++~+min((11))*max(19)-min((b)) from t1) in (select 13 from t1 union select (select min(19) from t1) from t1) then t1.f+t1.d else 13 end-t1.e) when t1.e then t1.f else a end<e}
} {100}
do_test randexpr-2.859 {
  db eval {SELECT coalesce((select max(+t1.a) from t1 where c in (select  -max(d | coalesce((select max(t1.b) from t1 where (abs(case d when t1.f then t1.e else t1.c end-t1.f)/abs(13))<=11), -a)) | min(t1.c) | (max(f))++abs(case max(b) when (count(distinct e)) then count(*) else min(17) end) from t1 union select (min(19)) from t1) or not exists(select 1 from t1 where coalesce((select c from t1 where b in (select  - - - -count(*) from t1 union select  -min((a)) from t1)),13)<t1.d)),17) FROM t1 WHERE ~a in (select count(*) from t1 union select case +abs((abs(abs(count(*))))+min(a))*max(case when exists(select 1 from t1 where d between 17+(b)-a and 17) then (select count(*) from t1) when 13<> -t1.b then t1.f else t1.e end)*min(t1.a)+ -count(*) | +max(e)*(min(t1.e)) | count(distinct t1.d) | (count(*)) when count(distinct ((19))) then count(*) else max(t1.f) end from t1)}
} {}
do_test randexpr-2.860 {
  db eval {SELECT coalesce((select max(+t1.a) from t1 where c in (select  -max(d | coalesce((select max(t1.b) from t1 where (abs(case d when t1.f then t1.e else t1.c end-t1.f)/abs(13))<=11), -a)) | min(t1.c) | (max(f))++abs(case max(b) when (count(distinct e)) then count(*) else min(17) end) from t1 union select (min(19)) from t1) or not exists(select 1 from t1 where coalesce((select c from t1 where b in (select  - - - -count(*) from t1 union select  -min((a)) from t1)),13)<t1.d)),17) FROM t1 WHERE NOT (~a in (select count(*) from t1 union select case +abs((abs(abs(count(*))))+min(a))*max(case when exists(select 1 from t1 where d between 17+(b)-a and 17) then (select count(*) from t1) when 13<> -t1.b then t1.f else t1.e end)*min(t1.a)+ -count(*) | +max(e)*(min(t1.e)) | count(distinct t1.d) | (count(*)) when count(distinct ((19))) then count(*) else max(t1.f) end from t1))}
} {17}
do_test randexpr-2.861 {
  db eval {SELECT coalesce((select max(+t1.a) from t1 where c in (select  -max(d & coalesce((select max(t1.b) from t1 where (abs(case d when t1.f then t1.e else t1.c end-t1.f)/abs(13))<=11), -a)) & min(t1.c) & (max(f))++abs(case max(b) when (count(distinct e)) then count(*) else min(17) end) from t1 union select (min(19)) from t1) or not exists(select 1 from t1 where coalesce((select c from t1 where b in (select  - - - -count(*) from t1 union select  -min((a)) from t1)),13)<t1.d)),17) FROM t1 WHERE NOT (~a in (select count(*) from t1 union select case +abs((abs(abs(count(*))))+min(a))*max(case when exists(select 1 from t1 where d between 17+(b)-a and 17) then (select count(*) from t1) when 13<> -t1.b then t1.f else t1.e end)*min(t1.a)+ -count(*) | +max(e)*(min(t1.e)) | count(distinct t1.d) | (count(*)) when count(distinct ((19))) then count(*) else max(t1.f) end from t1))}
} {17}
do_test randexpr-2.862 {
  db eval {SELECT case 17 when (select ~count(distinct t1.d) from t1) then e else case when not not exists(select 1 from t1 where (abs(~coalesce((select (coalesce((select max(13) from t1 where e>a),19)) from t1 where (not exists(select 1 from t1 where t1.c in (f,b,c)))),c)*t1.c | 17-(e))/abs(t1.f)) | 17*17*a in (select e from t1 union select f from t1)) then 13 when t1.a not between (b) and t1.c then (abs(17)/abs(17)) else t1.d end*f end FROM t1 WHERE t1.a>t1.c-19}
} {}
do_test randexpr-2.863 {
  db eval {SELECT case 17 when (select ~count(distinct t1.d) from t1) then e else case when not not exists(select 1 from t1 where (abs(~coalesce((select (coalesce((select max(13) from t1 where e>a),19)) from t1 where (not exists(select 1 from t1 where t1.c in (f,b,c)))),c)*t1.c | 17-(e))/abs(t1.f)) | 17*17*a in (select e from t1 union select f from t1)) then 13 when t1.a not between (b) and t1.c then (abs(17)/abs(17)) else t1.d end*f end FROM t1 WHERE NOT (t1.a>t1.c-19)}
} {600}
do_test randexpr-2.864 {
  db eval {SELECT case 17 when (select ~count(distinct t1.d) from t1) then e else case when not not exists(select 1 from t1 where (abs(~coalesce((select (coalesce((select max(13) from t1 where e>a),19)) from t1 where (not exists(select 1 from t1 where t1.c in (f,b,c)))),c)*t1.c & 17-(e))/abs(t1.f)) & 17*17*a in (select e from t1 union select f from t1)) then 13 when t1.a not between (b) and t1.c then (abs(17)/abs(17)) else t1.d end*f end FROM t1 WHERE NOT (t1.a>t1.c-19)}
} {600}
do_test randexpr-2.865 {
  db eval {SELECT case when f>=t1.c then t1.d when coalesce((select max(+11-b) from t1 where a-t1.d in (select +case when f in (13,b | 11,t1.b) then  -t1.d when f in (select ~count(distinct 17) from t1 union select count(distinct t1.a) from t1) then 19 else c end-d+b from t1 union select a from t1) and (17) in (t1.f,11,t1.c)),f)< -a then d else t1.c end-11 FROM t1 WHERE a<(select count(distinct +11*coalesce((select max(coalesce((select max(t1.d) from t1 where t1.e>t1.b),b)*t1.f) from t1 where case 11 when t1.a then  -t1.e else a end<=17),e)-11+c-19) | count(distinct 19)*count(*)* -(count(distinct t1.f))+cast(avg(17) AS integer)-(~~(count(*)))-cast(avg(11) AS integer) | cast(avg((19)) AS integer) from t1)-t1.c}
} {}
do_test randexpr-2.866 {
  db eval {SELECT case when f>=t1.c then t1.d when coalesce((select max(+11-b) from t1 where a-t1.d in (select +case when f in (13,b | 11,t1.b) then  -t1.d when f in (select ~count(distinct 17) from t1 union select count(distinct t1.a) from t1) then 19 else c end-d+b from t1 union select a from t1) and (17) in (t1.f,11,t1.c)),f)< -a then d else t1.c end-11 FROM t1 WHERE NOT (a<(select count(distinct +11*coalesce((select max(coalesce((select max(t1.d) from t1 where t1.e>t1.b),b)*t1.f) from t1 where case 11 when t1.a then  -t1.e else a end<=17),e)-11+c-19) | count(distinct 19)*count(*)* -(count(distinct t1.f))+cast(avg(17) AS integer)-(~~(count(*)))-cast(avg(11) AS integer) | cast(avg((19)) AS integer) from t1)-t1.c)}
} {389}
do_test randexpr-2.867 {
  db eval {SELECT case when f>=t1.c then t1.d when coalesce((select max(+11-b) from t1 where a-t1.d in (select +case when f in (13,b & 11,t1.b) then  -t1.d when f in (select ~count(distinct 17) from t1 union select count(distinct t1.a) from t1) then 19 else c end-d+b from t1 union select a from t1) and (17) in (t1.f,11,t1.c)),f)< -a then d else t1.c end-11 FROM t1 WHERE NOT (a<(select count(distinct +11*coalesce((select max(coalesce((select max(t1.d) from t1 where t1.e>t1.b),b)*t1.f) from t1 where case 11 when t1.a then  -t1.e else a end<=17),e)-11+c-19) | count(distinct 19)*count(*)* -(count(distinct t1.f))+cast(avg(17) AS integer)-(~~(count(*)))-cast(avg(11) AS integer) | cast(avg((19)) AS integer) from t1)-t1.c)}
} {389}
do_test randexpr-2.868 {
  db eval {SELECT coalesce((select max(17) from t1 where  -coalesce((select t1.b+coalesce((select case when case t1.f when c then (e) else a end+t1.c+(f)>17 and e>=f and (13>t1.f) then (select ~(cast(avg(t1.e) AS integer)) | min(t1.a) from t1) when  -c>c then 19 else t1.f end from t1 where (17<t1.f)),t1.f) from t1 where not exists(select 1 from t1 where 13 not between t1.a and c)),d)*17< -t1.c),b) FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where  -11=17*t1.d*f))}
} {}
do_test randexpr-2.869 {
  db eval {SELECT coalesce((select max(17) from t1 where  -coalesce((select t1.b+coalesce((select case when case t1.f when c then (e) else a end+t1.c+(f)>17 and e>=f and (13>t1.f) then (select ~(cast(avg(t1.e) AS integer)) | min(t1.a) from t1) when  -c>c then 19 else t1.f end from t1 where (17<t1.f)),t1.f) from t1 where not exists(select 1 from t1 where 13 not between t1.a and c)),d)*17< -t1.c),b) FROM t1 WHERE NOT (not exists(select 1 from t1 where not exists(select 1 from t1 where  -11=17*t1.d*f)))}
} {17}
do_test randexpr-2.870 {
  db eval {SELECT coalesce((select max(17) from t1 where  -coalesce((select t1.b+coalesce((select case when case t1.f when c then (e) else a end+t1.c+(f)>17 and e>=f and (13>t1.f) then (select ~(cast(avg(t1.e) AS integer)) & min(t1.a) from t1) when  -c>c then 19 else t1.f end from t1 where (17<t1.f)),t1.f) from t1 where not exists(select 1 from t1 where 13 not between t1.a and c)),d)*17< -t1.c),b) FROM t1 WHERE NOT (not exists(select 1 from t1 where not exists(select 1 from t1 where  -11=17*t1.d*f)))}
} {17}
do_test randexpr-2.871 {
  db eval {SELECT case when a*t1.a*a in (select case (e- -11+case when ~c>=a then 13 when ((case when t1.d<t1.d then f when t1.c not between a and t1.e then  -f else t1.f end>=a)) then 19 else t1.b end-t1.f) when 19 then  - -13 else 17 end from t1 union select  -17 from t1) and 19 in (select d from t1 union select e from t1) then (select abs(min(t1.f)) from t1) else c end FROM t1 WHERE case coalesce((select 19 from t1 where 13<coalesce((select 19 | case when t1.e>=e then d when (case when not exists(select 1 from t1 where (a>d and d not between e and ((19)) and c in (e,t1.b,(b)) and e not in (t1.f,t1.a,t1.b))) then t1.b when f not between 11 and d then t1.d else d end<=11) then (abs(13)/abs(11)) else  -11 end from t1 where (t1.b)<d),b)),11) | d when c then 17 else (e) end not in (t1.e,t1.c,a)}
} {}
do_test randexpr-2.872 {
  db eval {SELECT case when a*t1.a*a in (select case (e- -11+case when ~c>=a then 13 when ((case when t1.d<t1.d then f when t1.c not between a and t1.e then  -f else t1.f end>=a)) then 19 else t1.b end-t1.f) when 19 then  - -13 else 17 end from t1 union select  -17 from t1) and 19 in (select d from t1 union select e from t1) then (select abs(min(t1.f)) from t1) else c end FROM t1 WHERE NOT (case coalesce((select 19 from t1 where 13<coalesce((select 19 | case when t1.e>=e then d when (case when not exists(select 1 from t1 where (a>d and d not between e and ((19)) and c in (e,t1.b,(b)) and e not in (t1.f,t1.a,t1.b))) then t1.b when f not between 11 and d then t1.d else d end<=11) then (abs(13)/abs(11)) else  -11 end from t1 where (t1.b)<d),b)),11) | d when c then 17 else (e) end not in (t1.e,t1.c,a))}
} {300}
do_test randexpr-2.873 {
  db eval {SELECT case when t1.e not between (select +max(17) from t1)*t1.f and d then t1.c+case when e+f<=coalesce((select max((19)) from t1 where t1.e not in ((abs( -17-17)/abs(t1.e)),(c),(t1.b))),d) and 13 in (select d from t1 union select c from t1) then 19 else c end-19 when exists(select 1 from t1 where t1.a in (select t1.a from t1 union select 13 from t1)) and not exists(select 1 from t1 where a<19) then b else t1.b end FROM t1 WHERE not t1.d=b}
} {581}
do_test randexpr-2.874 {
  db eval {SELECT case when t1.e not between (select +max(17) from t1)*t1.f and d then t1.c+case when e+f<=coalesce((select max((19)) from t1 where t1.e not in ((abs( -17-17)/abs(t1.e)),(c),(t1.b))),d) and 13 in (select d from t1 union select c from t1) then 19 else c end-19 when exists(select 1 from t1 where t1.a in (select t1.a from t1 union select 13 from t1)) and not exists(select 1 from t1 where a<19) then b else t1.b end FROM t1 WHERE NOT (not t1.d=b)}
} {}
do_test randexpr-2.875 {
  db eval {SELECT +17+(11)-coalesce((select max(case (11) when f then +e+case when +11< -13-f or b between (b) and t1.b and e<>t1.c and e not between 13 and t1.d and t1.e in (t1.d,17,t1.c) then c+t1.e*t1.d when t1.f>=t1.d then t1.a else t1.c end else t1.e end-e) from t1 where t1.b not in (t1.b,t1.d,d)), -c)*13 FROM t1 WHERE (abs(e+17)/abs((select count(distinct 11-t1.b)*cast(avg(case c when coalesce((select max(19-coalesce((select max(f) from t1 where 19 in (17,t1.f,11)),t1.d)) from t1 where c in (t1.a,11,13) and t1.a<=t1.c),t1.c) then t1.c else e end) AS integer) | max(e) | (+~case case cast(avg(t1.d) AS integer) when  -min(13) then count(*) else count(*) end when max(t1.c) then count(distinct f) else count(*) end-count(distinct 19)) from t1)))>=t1.e | f}
} {}
do_test randexpr-2.876 {
  db eval {SELECT +17+(11)-coalesce((select max(case (11) when f then +e+case when +11< -13-f or b between (b) and t1.b and e<>t1.c and e not between 13 and t1.d and t1.e in (t1.d,17,t1.c) then c+t1.e*t1.d when t1.f>=t1.d then t1.a else t1.c end else t1.e end-e) from t1 where t1.b not in (t1.b,t1.d,d)), -c)*13 FROM t1 WHERE NOT ((abs(e+17)/abs((select count(distinct 11-t1.b)*cast(avg(case c when coalesce((select max(19-coalesce((select max(f) from t1 where 19 in (17,t1.f,11)),t1.d)) from t1 where c in (t1.a,11,13) and t1.a<=t1.c),t1.c) then t1.c else e end) AS integer) | max(e) | (+~case case cast(avg(t1.d) AS integer) when  -min(13) then count(*) else count(*) end when max(t1.c) then count(distinct f) else count(*) end-count(distinct 19)) from t1)))>=t1.e | f)}
} {3928}
do_test randexpr-2.877 {
  db eval {SELECT case when case when d*c not in (13,a,d) then (t1.b-f)+coalesce((select max((select count(distinct 13)-case max(11) when count(*) then count(*) else min(t1.b) end*min(17)+(min(t1.c)) from t1)) from t1 where not exists(select 1 from t1 where t1.c between 17-d | d and t1.e)),b) else t1.e end<=d then e when f in (a,13,d) or t1.b between f and  -b then c else t1.a end FROM t1 WHERE t1.d<>t1.a}
} {500}
do_test randexpr-2.878 {
  db eval {SELECT case when case when d*c not in (13,a,d) then (t1.b-f)+coalesce((select max((select count(distinct 13)-case max(11) when count(*) then count(*) else min(t1.b) end*min(17)+(min(t1.c)) from t1)) from t1 where not exists(select 1 from t1 where t1.c between 17-d | d and t1.e)),b) else t1.e end<=d then e when f in (a,13,d) or t1.b between f and  -b then c else t1.a end FROM t1 WHERE NOT (t1.d<>t1.a)}
} {}
do_test randexpr-2.879 {
  db eval {SELECT case when case when d*c not in (13,a,d) then (t1.b-f)+coalesce((select max((select count(distinct 13)-case max(11) when count(*) then count(*) else min(t1.b) end*min(17)+(min(t1.c)) from t1)) from t1 where not exists(select 1 from t1 where t1.c between 17-d & d and t1.e)),b) else t1.e end<=d then e when f in (a,13,d) or t1.b between f and  -b then c else t1.a end FROM t1 WHERE t1.d<>t1.a}
} {500}
do_test randexpr-2.880 {
  db eval {SELECT case case c when  -b then (abs(b)/abs(c)) else (select count(distinct f) | (~abs(min(c-+case 11 when case when t1.a between b and t1.e-case when (13<=b) then (select  -count(*) from t1) else a end then t1.e when e>=11 then (19) else b end then d else 17 end | e))) from t1) end when  -13 then t1.f else +17 end FROM t1 WHERE 17 in (select +(count(*) | case abs( -abs(abs( -min(d)))) | max(+11) when  -+~count(distinct  -(abs(coalesce((select max(f) from t1 where t1.e in (select e from t1 union select t1.a from t1)),f) | t1.c-t1.b)/abs(13))) | +abs(case max(b) when count(*) then  -min(t1.e) else (cast(avg(t1.f) AS integer)) end)- -count(*) then  -count(*) else max(19) end* -cast(avg(t1.b) AS integer))+(max(t1.f)) from t1 union select count(distinct b) from t1)}
} {}
do_test randexpr-2.881 {
  db eval {SELECT case case c when  -b then (abs(b)/abs(c)) else (select count(distinct f) | (~abs(min(c-+case 11 when case when t1.a between b and t1.e-case when (13<=b) then (select  -count(*) from t1) else a end then t1.e when e>=11 then (19) else b end then d else 17 end | e))) from t1) end when  -13 then t1.f else +17 end FROM t1 WHERE NOT (17 in (select +(count(*) | case abs( -abs(abs( -min(d)))) | max(+11) when  -+~count(distinct  -(abs(coalesce((select max(f) from t1 where t1.e in (select e from t1 union select t1.a from t1)),f) | t1.c-t1.b)/abs(13))) | +abs(case max(b) when count(*) then  -min(t1.e) else (cast(avg(t1.f) AS integer)) end)- -count(*) then  -count(*) else max(19) end* -cast(avg(t1.b) AS integer))+(max(t1.f)) from t1 union select count(distinct b) from t1))}
} {17}
do_test randexpr-2.882 {
  db eval {SELECT case case c when  -b then (abs(b)/abs(c)) else (select count(distinct f) & (~abs(min(c-+case 11 when case when t1.a between b and t1.e-case when (13<=b) then (select  -count(*) from t1) else a end then t1.e when e>=11 then (19) else b end then d else 17 end & e))) from t1) end when  -13 then t1.f else +17 end FROM t1 WHERE NOT (17 in (select +(count(*) | case abs( -abs(abs( -min(d)))) | max(+11) when  -+~count(distinct  -(abs(coalesce((select max(f) from t1 where t1.e in (select e from t1 union select t1.a from t1)),f) | t1.c-t1.b)/abs(13))) | +abs(case max(b) when count(*) then  -min(t1.e) else (cast(avg(t1.f) AS integer)) end)- -count(*) then  -count(*) else max(19) end* -cast(avg(t1.b) AS integer))+(max(t1.f)) from t1 union select count(distinct b) from t1))}
} {17}
do_test randexpr-2.883 {
  db eval {SELECT case 11 when (case when t1.e in (select +cast(avg(coalesce((select max(13) from t1 where case when exists(select 1 from t1 where t1.b in ((a),d,(t1.e))) then case when 19 in (select  -max(17) from t1 union select min(t1.f) from t1) then t1.b else 17 end when a not in ((t1.f),11,t1.e) then 17 else t1.c end<t1.b),11)*a) AS integer) from t1 union select max(b) | case (+min(t1.f)) when cast(avg(a) AS integer) then count(distinct 13) else max(t1.c) end from t1) then t1.e when c<=t1.d then t1.b else t1.f end-17) then b else t1.e end FROM t1 WHERE e-case when a*b between t1.d-(abs(11)/abs(coalesce((select t1.b from t1 where not exists(select 1 from t1 where c=17) or a not between (coalesce((select t1.c from t1 where 19>(19)),c)) and c and (11 in (select t1.b from t1 union select 13 from t1) and ( -t1.d)=d)),e | 19*t1.a))) and t1.a then t1.a when 19>=t1.a then e else c end> -e}
} {500}
do_test randexpr-2.884 {
  db eval {SELECT case 11 when (case when t1.e in (select +cast(avg(coalesce((select max(13) from t1 where case when exists(select 1 from t1 where t1.b in ((a),d,(t1.e))) then case when 19 in (select  -max(17) from t1 union select min(t1.f) from t1) then t1.b else 17 end when a not in ((t1.f),11,t1.e) then 17 else t1.c end<t1.b),11)*a) AS integer) from t1 union select max(b) | case (+min(t1.f)) when cast(avg(a) AS integer) then count(distinct 13) else max(t1.c) end from t1) then t1.e when c<=t1.d then t1.b else t1.f end-17) then b else t1.e end FROM t1 WHERE NOT (e-case when a*b between t1.d-(abs(11)/abs(coalesce((select t1.b from t1 where not exists(select 1 from t1 where c=17) or a not between (coalesce((select t1.c from t1 where 19>(19)),c)) and c and (11 in (select t1.b from t1 union select 13 from t1) and ( -t1.d)=d)),e | 19*t1.a))) and t1.a then t1.a when 19>=t1.a then e else c end> -e)}
} {}
do_test randexpr-2.885 {
  db eval {SELECT case 11 when (case when t1.e in (select +cast(avg(coalesce((select max(13) from t1 where case when exists(select 1 from t1 where t1.b in ((a),d,(t1.e))) then case when 19 in (select  -max(17) from t1 union select min(t1.f) from t1) then t1.b else 17 end when a not in ((t1.f),11,t1.e) then 17 else t1.c end<t1.b),11)*a) AS integer) from t1 union select max(b) & case (+min(t1.f)) when cast(avg(a) AS integer) then count(distinct 13) else max(t1.c) end from t1) then t1.e when c<=t1.d then t1.b else t1.f end-17) then b else t1.e end FROM t1 WHERE e-case when a*b between t1.d-(abs(11)/abs(coalesce((select t1.b from t1 where not exists(select 1 from t1 where c=17) or a not between (coalesce((select t1.c from t1 where 19>(19)),c)) and c and (11 in (select t1.b from t1 union select 13 from t1) and ( -t1.d)=d)),e | 19*t1.a))) and t1.a then t1.a when 19>=t1.a then e else c end> -e}
} {500}
do_test randexpr-2.886 {
  db eval {SELECT case a*t1.a when ~++a*(abs(e)/abs(19)) | t1.d+(select count(*) from t1) then b else t1.a end*coalesce((select max(f) from t1 where f<>t1.d),b) FROM t1 WHERE (abs(c-~t1.b)/abs(d))-((+coalesce((select max(c) from t1 where  -+(select ~ -(cast(avg((13+case 11*t1.c when t1.b then f else ~e-coalesce((select max((f)) from t1 where t1.f<a), -t1.c-(t1.c)) end)) AS integer)) from t1)=d*a),t1.d)+a))* -t1.e=t1.f}
} {}
do_test randexpr-2.887 {
  db eval {SELECT case a*t1.a when ~++a*(abs(e)/abs(19)) | t1.d+(select count(*) from t1) then b else t1.a end*coalesce((select max(f) from t1 where f<>t1.d),b) FROM t1 WHERE NOT ((abs(c-~t1.b)/abs(d))-((+coalesce((select max(c) from t1 where  -+(select ~ -(cast(avg((13+case 11*t1.c when t1.b then f else ~e-coalesce((select max((f)) from t1 where t1.f<a), -t1.c-(t1.c)) end)) AS integer)) from t1)=d*a),t1.d)+a))* -t1.e=t1.f)}
} {60000}
do_test randexpr-2.888 {
  db eval {SELECT case a*t1.a when ~++a*(abs(e)/abs(19)) & t1.d+(select count(*) from t1) then b else t1.a end*coalesce((select max(f) from t1 where f<>t1.d),b) FROM t1 WHERE NOT ((abs(c-~t1.b)/abs(d))-((+coalesce((select max(c) from t1 where  -+(select ~ -(cast(avg((13+case 11*t1.c when t1.b then f else ~e-coalesce((select max((f)) from t1 where t1.f<a), -t1.c-(t1.c)) end)) AS integer)) from t1)=d*a),t1.d)+a))* -t1.e=t1.f)}
} {60000}
do_test randexpr-2.889 {
  db eval {SELECT t1.c-t1.f-coalesce((select max(a) from t1 where e in ((abs(a)/abs(t1.d))*coalesce((select max((abs(case when e>=+t1.b then f when t1.c+f<a or e<>13 then t1.d else t1.a end)/abs(t1.d))) from t1 where t1.c not between t1.c and 11 and e>d),f)*t1.e+d,a,13)),e) | t1.b FROM t1 WHERE (abs(+(+t1.a)+case a-case when c>=d then 13 when t1.c not in (17,17,e) then a else t1.d end when c then  -f else b end*d)/abs(17))<=11 and 11 in (select cast(avg(17) AS integer) from t1 union select min( -19)+(case max(a) when abs(count(*)) then  -abs(count(*)*min(t1.e)+max(11)) else min(c) end) from t1)}
} {}
do_test randexpr-2.890 {
  db eval {SELECT t1.c-t1.f-coalesce((select max(a) from t1 where e in ((abs(a)/abs(t1.d))*coalesce((select max((abs(case when e>=+t1.b then f when t1.c+f<a or e<>13 then t1.d else t1.a end)/abs(t1.d))) from t1 where t1.c not between t1.c and 11 and e>d),f)*t1.e+d,a,13)),e) | t1.b FROM t1 WHERE NOT ((abs(+(+t1.a)+case a-case when c>=d then 13 when t1.c not in (17,17,e) then a else t1.d end when c then  -f else b end*d)/abs(17))<=11 and 11 in (select cast(avg(17) AS integer) from t1 union select min( -19)+(case max(a) when abs(count(*)) then  -abs(count(*)*min(t1.e)+max(11)) else min(c) end) from t1))}
} {-792}
do_test randexpr-2.891 {
  db eval {SELECT t1.c-t1.f-coalesce((select max(a) from t1 where e in ((abs(a)/abs(t1.d))*coalesce((select max((abs(case when e>=+t1.b then f when t1.c+f<a or e<>13 then t1.d else t1.a end)/abs(t1.d))) from t1 where t1.c not between t1.c and 11 and e>d),f)*t1.e+d,a,13)),e) & t1.b FROM t1 WHERE NOT ((abs(+(+t1.a)+case a-case when c>=d then 13 when t1.c not in (17,17,e) then a else t1.d end when c then  -f else b end*d)/abs(17))<=11 and 11 in (select cast(avg(17) AS integer) from t1 union select min( -19)+(case max(a) when abs(count(*)) then  -abs(count(*)*min(t1.e)+max(11)) else min(c) end) from t1))}
} {192}
do_test randexpr-2.892 {
  db eval {SELECT coalesce((select (select count(*) from t1)*a*b from t1 where ((~b*a-t1.d+11*e-(select  -count(*) | count(*) | count(*) from t1)*(select min((abs(coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where  -17 in (t1.b,t1.f,t1.d))),11))/abs(t1.d))) from t1)-17+(abs(11)/abs(11)) | b+d | 11 in (select t1.a from t1 union select 13 from t1)))),t1.a) FROM t1 WHERE f>case when f-case when not exists(select 1 from t1 where case when b in (select abs(max(coalesce((select max(~t1.c) from t1 where t1.f<=13),17))) from t1 union select cast(avg(t1.c) AS integer) from t1) then t1.e else (13) end> -t1.e) or d<>19 then coalesce((select max((select abs(max(d)+cast(avg(d) AS integer)) from t1)) from t1 where t1.e<t1.c),19) when  -t1.c in (t1.e,t1.f,e) then 11 else t1.a end<>19 then b when t1.a<=11 then 11 else t1.d end}
} {100}
do_test randexpr-2.893 {
  db eval {SELECT coalesce((select (select count(*) from t1)*a*b from t1 where ((~b*a-t1.d+11*e-(select  -count(*) | count(*) | count(*) from t1)*(select min((abs(coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where  -17 in (t1.b,t1.f,t1.d))),11))/abs(t1.d))) from t1)-17+(abs(11)/abs(11)) | b+d | 11 in (select t1.a from t1 union select 13 from t1)))),t1.a) FROM t1 WHERE NOT (f>case when f-case when not exists(select 1 from t1 where case when b in (select abs(max(coalesce((select max(~t1.c) from t1 where t1.f<=13),17))) from t1 union select cast(avg(t1.c) AS integer) from t1) then t1.e else (13) end> -t1.e) or d<>19 then coalesce((select max((select abs(max(d)+cast(avg(d) AS integer)) from t1)) from t1 where t1.e<t1.c),19) when  -t1.c in (t1.e,t1.f,e) then 11 else t1.a end<>19 then b when t1.a<=11 then 11 else t1.d end)}
} {}
do_test randexpr-2.894 {
  db eval {SELECT coalesce((select (select count(*) from t1)*a*b from t1 where ((~b*a-t1.d+11*e-(select  -count(*) & count(*) & count(*) from t1)*(select min((abs(coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where  -17 in (t1.b,t1.f,t1.d))),11))/abs(t1.d))) from t1)-17+(abs(11)/abs(11)) & b+d & 11 in (select t1.a from t1 union select 13 from t1)))),t1.a) FROM t1 WHERE f>case when f-case when not exists(select 1 from t1 where case when b in (select abs(max(coalesce((select max(~t1.c) from t1 where t1.f<=13),17))) from t1 union select cast(avg(t1.c) AS integer) from t1) then t1.e else (13) end> -t1.e) or d<>19 then coalesce((select max((select abs(max(d)+cast(avg(d) AS integer)) from t1)) from t1 where t1.e<t1.c),19) when  -t1.c in (t1.e,t1.f,e) then 11 else t1.a end<>19 then b when t1.a<=11 then 11 else t1.d end}
} {100}
do_test randexpr-2.895 {
  db eval {SELECT coalesce((select e from t1 where ((abs((select case (~max(f) | ~max(19-t1.d) | cast(avg(11) AS integer)) when min(+t1.d*c) then max(case when 19+13 not between 13 and t1.c or t1.c not in ((b),11,(e)) then d else t1.d end+ -t1.d) else min(a) end from t1))/abs(11)))<17),t1.b)+17 FROM t1 WHERE (13 in (a,t1.a,~+(e)+t1.c*t1.c | t1.c- -t1.b-t1.b+e*b | t1.e-t1.e-e*coalesce((select max(t1.b) from t1 where t1.a*d<>coalesce((select max(t1.e-t1.b) from t1 where exists(select 1 from t1 where coalesce((select e from t1 where (17 not between 13 and t1.c)),t1.c)>=t1.c)),b)),t1.f)+17))}
} {}
do_test randexpr-2.896 {
  db eval {SELECT coalesce((select e from t1 where ((abs((select case (~max(f) | ~max(19-t1.d) | cast(avg(11) AS integer)) when min(+t1.d*c) then max(case when 19+13 not between 13 and t1.c or t1.c not in ((b),11,(e)) then d else t1.d end+ -t1.d) else min(a) end from t1))/abs(11)))<17),t1.b)+17 FROM t1 WHERE NOT ((13 in (a,t1.a,~+(e)+t1.c*t1.c | t1.c- -t1.b-t1.b+e*b | t1.e-t1.e-e*coalesce((select max(t1.b) from t1 where t1.a*d<>coalesce((select max(t1.e-t1.b) from t1 where exists(select 1 from t1 where coalesce((select e from t1 where (17 not between 13 and t1.c)),t1.c)>=t1.c)),b)),t1.f)+17)))}
} {517}
do_test randexpr-2.897 {
  db eval {SELECT coalesce((select e from t1 where ((abs((select case (~max(f) & ~max(19-t1.d) & cast(avg(11) AS integer)) when min(+t1.d*c) then max(case when 19+13 not between 13 and t1.c or t1.c not in ((b),11,(e)) then d else t1.d end+ -t1.d) else min(a) end from t1))/abs(11)))<17),t1.b)+17 FROM t1 WHERE NOT ((13 in (a,t1.a,~+(e)+t1.c*t1.c | t1.c- -t1.b-t1.b+e*b | t1.e-t1.e-e*coalesce((select max(t1.b) from t1 where t1.a*d<>coalesce((select max(t1.e-t1.b) from t1 where exists(select 1 from t1 where coalesce((select e from t1 where (17 not between 13 and t1.c)),t1.c)>=t1.c)),b)),t1.f)+17)))}
} {517}
do_test randexpr-2.898 {
  db eval {SELECT c | coalesce((select max(~b*case +coalesce((select max( -(abs(c)/abs(11))+case when t1.c*17 not in (a,a,c) then t1.e when t1.b in (select 13 from t1 union select (c) from t1) then  -(t1.c) else d end* -t1.c+a) from t1 where t1.f>=11),17) | t1.b when t1.b then c else t1.a end) from t1 where t1.f>t1.a),t1.c)+13*17 FROM t1 WHERE t1.e<t1.c*(select min((select count(*) from t1)) from t1)*f}
} {-19587}
do_test randexpr-2.899 {
  db eval {SELECT c | coalesce((select max(~b*case +coalesce((select max( -(abs(c)/abs(11))+case when t1.c*17 not in (a,a,c) then t1.e when t1.b in (select 13 from t1 union select (c) from t1) then  -(t1.c) else d end* -t1.c+a) from t1 where t1.f>=11),17) | t1.b when t1.b then c else t1.a end) from t1 where t1.f>t1.a),t1.c)+13*17 FROM t1 WHERE NOT (t1.e<t1.c*(select min((select count(*) from t1)) from t1)*f)}
} {}
do_test randexpr-2.900 {
  db eval {SELECT c & coalesce((select max(~b*case +coalesce((select max( -(abs(c)/abs(11))+case when t1.c*17 not in (a,a,c) then t1.e when t1.b in (select 13 from t1 union select (c) from t1) then  -(t1.c) else d end* -t1.c+a) from t1 where t1.f>=11),17) & t1.b when t1.b then c else t1.a end) from t1 where t1.f>t1.a),t1.c)+13*17 FROM t1 WHERE t1.e<t1.c*(select min((select count(*) from t1)) from t1)*f}
} {8}
do_test randexpr-2.901 {
  db eval {SELECT coalesce((select max(a) from t1 where t1.b<t1.b),13 |  -(coalesce((select max((abs(~t1.a | (abs(11)/abs((abs(t1.e)/abs(coalesce((select max(t1.e) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where (t1.d)<>e) and not exists(select 1 from t1 where (19)=t1.e))),19*t1.e)-t1.c)) | 17))*t1.b)/abs(17))) from t1 where (t1.b) between d and t1.b),t1.c)) | t1.f-c-d) FROM t1 WHERE 13 not in (f,t1.c+11*c,coalesce((select e from t1 where case t1.b when c- -case (select cast(avg(+t1.c*t1.f) AS integer) from t1) when 13*case when not case when  -17 in (select (t1.c) from t1 union select t1.c from t1) or t1.f in (t1.b,t1.d,t1.b) then t1.a when 11<>t1.c then e else a end>=(11) and a=d or  -t1.f between c and b then e else t1.f end then 19 else t1.d end then t1.c else t1.b end<>13),d))}
} {-35}
do_test randexpr-2.902 {
  db eval {SELECT coalesce((select max(a) from t1 where t1.b<t1.b),13 |  -(coalesce((select max((abs(~t1.a | (abs(11)/abs((abs(t1.e)/abs(coalesce((select max(t1.e) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where (t1.d)<>e) and not exists(select 1 from t1 where (19)=t1.e))),19*t1.e)-t1.c)) | 17))*t1.b)/abs(17))) from t1 where (t1.b) between d and t1.b),t1.c)) | t1.f-c-d) FROM t1 WHERE NOT (13 not in (f,t1.c+11*c,coalesce((select e from t1 where case t1.b when c- -case (select cast(avg(+t1.c*t1.f) AS integer) from t1) when 13*case when not case when  -17 in (select (t1.c) from t1 union select t1.c from t1) or t1.f in (t1.b,t1.d,t1.b) then t1.a when 11<>t1.c then e else a end>=(11) and a=d or  -t1.f between c and b then e else t1.f end then 19 else t1.d end then t1.c else t1.b end<>13),d)))}
} {}
do_test randexpr-2.903 {
  db eval {SELECT f+b+(t1.a+c)+(case when (select (cast(avg(coalesce((select max(t1.b) from t1 where case  -(select +cast(avg(b-t1.e) AS integer)-abs(cast(avg(~(abs(f)/abs(f))) AS integer)) from t1)+d when 11 then d else 13 end+t1.e<>t1.e),(t1.e))-13+13) AS integer)) from t1)-t1.b<>a then t1.e else e end) FROM t1 WHERE c in (select abs((max(t1.d))) from t1 union select count(*) from t1) and (coalesce((select max(+ -(t1.f-d)* -b) from t1 where not exists(select 1 from t1 where (b not in (coalesce((select t1.e-a from t1 where not t1.a between 13 and f or t1.b in (t1.e,e,17)),11),17,t1.a) and (b<>d)))),b) in (select  -min(17) from t1 union select abs(max(e)) from t1))}
} {}
do_test randexpr-2.904 {
  db eval {SELECT f+b+(t1.a+c)+(case when (select (cast(avg(coalesce((select max(t1.b) from t1 where case  -(select +cast(avg(b-t1.e) AS integer)-abs(cast(avg(~(abs(f)/abs(f))) AS integer)) from t1)+d when 11 then d else 13 end+t1.e<>t1.e),(t1.e))-13+13) AS integer)) from t1)-t1.b<>a then t1.e else e end) FROM t1 WHERE NOT (c in (select abs((max(t1.d))) from t1 union select count(*) from t1) and (coalesce((select max(+ -(t1.f-d)* -b) from t1 where not exists(select 1 from t1 where (b not in (coalesce((select t1.e-a from t1 where not t1.a between 13 and f or t1.b in (t1.e,e,17)),11),17,t1.a) and (b<>d)))),b) in (select  -min(17) from t1 union select abs(max(e)) from t1)))}
} {1700}
do_test randexpr-2.905 {
  db eval {SELECT case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (select  -min(t1.e) from t1) in (select f from t1 union select d from t1) then +e else d end | t1.e not between t1.a and t1.b))) and not exists(select 1 from t1 where a>=t1.e) and b=e then 13 else coalesce((select 19 from t1 where t1.d>=t1.e),13) end<11*t1.b then 17 when 17 in (19,t1.e, -t1.c) or 17<f then t1.d else t1.b end FROM t1 WHERE exists(select 1 from t1 where f<=19)}
} {}
do_test randexpr-2.906 {
  db eval {SELECT case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (select  -min(t1.e) from t1) in (select f from t1 union select d from t1) then +e else d end | t1.e not between t1.a and t1.b))) and not exists(select 1 from t1 where a>=t1.e) and b=e then 13 else coalesce((select 19 from t1 where t1.d>=t1.e),13) end<11*t1.b then 17 when 17 in (19,t1.e, -t1.c) or 17<f then t1.d else t1.b end FROM t1 WHERE NOT (exists(select 1 from t1 where f<=19))}
} {17}
do_test randexpr-2.907 {
  db eval {SELECT case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (select  -min(t1.e) from t1) in (select f from t1 union select d from t1) then +e else d end & t1.e not between t1.a and t1.b))) and not exists(select 1 from t1 where a>=t1.e) and b=e then 13 else coalesce((select 19 from t1 where t1.d>=t1.e),13) end<11*t1.b then 17 when 17 in (19,t1.e, -t1.c) or 17<f then t1.d else t1.b end FROM t1 WHERE NOT (exists(select 1 from t1 where f<=19))}
} {17}
do_test randexpr-2.908 {
  db eval {SELECT 11*t1.c* -case when t1.d<=t1.c then case when case case +t1.b-case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.e not in (t1.a,a,11)))) then (abs((select case count(distinct d) when cast(avg(19) AS integer) then  -min(t1.a) else (cast(avg(f) AS integer)) end from t1))/abs(b)) when t1.c<>t1.a then c else 19 end when t1.c then e else t1.d end when 17 then t1.d else  -d end between e and t1.e then 13 when (13<>13) then t1.c else 17 end when exists(select 1 from t1 where (t1.c between b and 11)) then e else f end FROM t1 WHERE ~a* -b+11-case when coalesce((select max(case when (t1.c in (case t1.b when t1.c then 13 else 17 end,17,19)) then case e when a then c else 13 end else c end) from t1 where a between b and t1.c),t1.a)=c or (17>d) then case when f= -t1.a then t1.b when (t1.d)<t1.e then (f) else t1.e end else c end+d<a}
} {}
do_test randexpr-2.909 {
  db eval {SELECT 11*t1.c* -case when t1.d<=t1.c then case when case case +t1.b-case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.e not in (t1.a,a,11)))) then (abs((select case count(distinct d) when cast(avg(19) AS integer) then  -min(t1.a) else (cast(avg(f) AS integer)) end from t1))/abs(b)) when t1.c<>t1.a then c else 19 end when t1.c then e else t1.d end when 17 then t1.d else  -d end between e and t1.e then 13 when (13<>13) then t1.c else 17 end when exists(select 1 from t1 where (t1.c between b and 11)) then e else f end FROM t1 WHERE NOT (~a* -b+11-case when coalesce((select max(case when (t1.c in (case t1.b when t1.c then 13 else 17 end,17,19)) then case e when a then c else 13 end else c end) from t1 where a between b and t1.c),t1.a)=c or (17>d) then case when f= -t1.a then t1.b when (t1.d)<t1.e then (f) else t1.e end else c end+d<a)}
} {-1980000}
do_test randexpr-2.910 {
  db eval {SELECT +case when e in (13, -b,11) then d else coalesce((select max(13 | d | d+19+(abs(case when (19) between (abs(case f when t1.f then (13) else 17 end)/abs(a)) and d then 19 when (not exists(select 1 from t1 where t1.a>=t1.f)) and t1.f>t1.a or e<>c then 17 else d end)/abs(a))) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (t1.f) in (t1.c,(t1.e),17)))),t1.a) end+e FROM t1 WHERE exists(select 1 from t1 where 17>(case coalesce((select max((abs(+t1.f-case when 11=(abs((select count(*) from t1)-13*13)/abs(t1.d)) then coalesce((select max(t1.c) from t1 where 19 in (select ((max(19))) from t1 union select min(t1.d) from t1) or  -t1.a=t1.a and f<17),t1.e-d) when not exists(select 1 from t1 where t1.b not between (d) and  -t1.f) then 11 else t1.a end)/abs(t1.a))) from t1 where t1.e not in ((f),11,t1.f)),t1.c) when b then  -t1.a else 13 end)-t1.c)}
} {947}
do_test randexpr-2.911 {
  db eval {SELECT +case when e in (13, -b,11) then d else coalesce((select max(13 | d | d+19+(abs(case when (19) between (abs(case f when t1.f then (13) else 17 end)/abs(a)) and d then 19 when (not exists(select 1 from t1 where t1.a>=t1.f)) and t1.f>t1.a or e<>c then 17 else d end)/abs(a))) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (t1.f) in (t1.c,(t1.e),17)))),t1.a) end+e FROM t1 WHERE NOT (exists(select 1 from t1 where 17>(case coalesce((select max((abs(+t1.f-case when 11=(abs((select count(*) from t1)-13*13)/abs(t1.d)) then coalesce((select max(t1.c) from t1 where 19 in (select ((max(19))) from t1 union select min(t1.d) from t1) or  -t1.a=t1.a and f<17),t1.e-d) when not exists(select 1 from t1 where t1.b not between (d) and  -t1.f) then 11 else t1.a end)/abs(t1.a))) from t1 where t1.e not in ((f),11,t1.f)),t1.c) when b then  -t1.a else 13 end)-t1.c))}
} {}
do_test randexpr-2.912 {
  db eval {SELECT +case when e in (13, -b,11) then d else coalesce((select max(13 & d & d+19+(abs(case when (19) between (abs(case f when t1.f then (13) else 17 end)/abs(a)) and d then 19 when (not exists(select 1 from t1 where t1.a>=t1.f)) and t1.f>t1.a or e<>c then 17 else d end)/abs(a))) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (t1.f) in (t1.c,(t1.e),17)))),t1.a) end+e FROM t1 WHERE exists(select 1 from t1 where 17>(case coalesce((select max((abs(+t1.f-case when 11=(abs((select count(*) from t1)-13*13)/abs(t1.d)) then coalesce((select max(t1.c) from t1 where 19 in (select ((max(19))) from t1 union select min(t1.d) from t1) or  -t1.a=t1.a and f<17),t1.e-d) when not exists(select 1 from t1 where t1.b not between (d) and  -t1.f) then 11 else t1.a end)/abs(t1.a))) from t1 where t1.e not in ((f),11,t1.f)),t1.c) when b then  -t1.a else 13 end)-t1.c)}
} {500}
do_test randexpr-2.913 {
  db eval {SELECT (13*case when exists(select 1 from t1 where exists(select 1 from t1 where coalesce((select max(b) from t1 where t1.b=e),a)<(b-a)+13)) then 11 else t1.e end*coalesce((select 17 from t1 where not ((select cast(avg(13) AS integer) from t1)< -t1.c) and 17 between 13 and 13),case when f<c then b when t1.c<t1.a then  -d else e end)*d+b)+ - -t1.b+11 FROM t1 WHERE not exists(select 1 from t1 where b>=case when exists(select 1 from t1 where (13 in ( -(b)*(select count(*)* -cast(avg(case t1.e when t1.b then (f)-f-f else e end) AS integer)*cast(avg(17) AS integer) | cast(avg((17)) AS integer) | min(d) | count(distinct e) from t1),19+(abs(19)/abs(17))*f,t1.b))) then 11 when 17>t1.f then +a else t1.d end)}
} {28600411}
do_test randexpr-2.914 {
  db eval {SELECT (13*case when exists(select 1 from t1 where exists(select 1 from t1 where coalesce((select max(b) from t1 where t1.b=e),a)<(b-a)+13)) then 11 else t1.e end*coalesce((select 17 from t1 where not ((select cast(avg(13) AS integer) from t1)< -t1.c) and 17 between 13 and 13),case when f<c then b when t1.c<t1.a then  -d else e end)*d+b)+ - -t1.b+11 FROM t1 WHERE NOT (not exists(select 1 from t1 where b>=case when exists(select 1 from t1 where (13 in ( -(b)*(select count(*)* -cast(avg(case t1.e when t1.b then (f)-f-f else e end) AS integer)*cast(avg(17) AS integer) | cast(avg((17)) AS integer) | min(d) | count(distinct e) from t1),19+(abs(19)/abs(17))*f,t1.b))) then 11 when 17>t1.f then +a else t1.d end))}
} {}
do_test randexpr-2.915 {
  db eval {SELECT case when +11 | (select min(case 13+a when e then d else 17-t1.b-~b*a end) from t1)-f*t1.f=(coalesce((select e from t1 where a<=f and not exists(select 1 from t1 where d-case 19 when 11 then (b) else t1.e end not between  -t1.a and (t1.c))),e)) then t1.e when  -17>=d then t1.f else t1.b end*t1.a FROM t1 WHERE e<=19}
} {}
do_test randexpr-2.916 {
  db eval {SELECT case when +11 | (select min(case 13+a when e then d else 17-t1.b-~b*a end) from t1)-f*t1.f=(coalesce((select e from t1 where a<=f and not exists(select 1 from t1 where d-case 19 when 11 then (b) else t1.e end not between  -t1.a and (t1.c))),e)) then t1.e when  -17>=d then t1.f else t1.b end*t1.a FROM t1 WHERE NOT (e<=19)}
} {20000}
do_test randexpr-2.917 {
  db eval {SELECT case when +11 & (select min(case 13+a when e then d else 17-t1.b-~b*a end) from t1)-f*t1.f=(coalesce((select e from t1 where a<=f and not exists(select 1 from t1 where d-case 19 when 11 then (b) else t1.e end not between  -t1.a and (t1.c))),e)) then t1.e when  -17>=d then t1.f else t1.b end*t1.a FROM t1 WHERE NOT (e<=19)}
} {20000}
do_test randexpr-2.918 {
  db eval {SELECT 11-coalesce((select max(coalesce((select max((select abs(case +max((e)) when abs(abs( -count(distinct e))) then +cast(avg(f) AS integer) else count(*) end+count(*)+min( -e)) from t1)) from t1 where t1.b in (select count(distinct (17 | case case when e in (13,t1.a,e) or t1.d>=t1.e then 17 else a end when t1.e then 17 else t1.d end*t1.c)) from t1 union select cast(avg(t1.a) AS integer) from t1)),17)) from t1 where t1.c in (select ~cast(avg(t1.b) AS integer) from t1 union select  -(cast(avg(t1.c) AS integer)) from t1)),(t1.c)) FROM t1 WHERE t1.b not in (case when 11 in (select case +min(t1.f) when (+cast(avg((case t1.c when a then f else a end-f)) AS integer)) then +count(distinct (t1.f))-count(distinct t1.f) else count(*) end-count(*) | count(*) from t1 union select min(e) from t1) then (abs(b | 13-f | c)/abs(t1.f)) else t1.c end,f,t1.b) or not  -t1.a<t1.f or t1.f>=11}
} {-289}
do_test randexpr-2.919 {
  db eval {SELECT 11-coalesce((select max(coalesce((select max((select abs(case +max((e)) when abs(abs( -count(distinct e))) then +cast(avg(f) AS integer) else count(*) end+count(*)+min( -e)) from t1)) from t1 where t1.b in (select count(distinct (17 | case case when e in (13,t1.a,e) or t1.d>=t1.e then 17 else a end when t1.e then 17 else t1.d end*t1.c)) from t1 union select cast(avg(t1.a) AS integer) from t1)),17)) from t1 where t1.c in (select ~cast(avg(t1.b) AS integer) from t1 union select  -(cast(avg(t1.c) AS integer)) from t1)),(t1.c)) FROM t1 WHERE NOT (t1.b not in (case when 11 in (select case +min(t1.f) when (+cast(avg((case t1.c when a then f else a end-f)) AS integer)) then +count(distinct (t1.f))-count(distinct t1.f) else count(*) end-count(*) | count(*) from t1 union select min(e) from t1) then (abs(b | 13-f | c)/abs(t1.f)) else t1.c end,f,t1.b) or not  -t1.a<t1.f or t1.f>=11)}
} {}
do_test randexpr-2.920 {
  db eval {SELECT 11-coalesce((select max(coalesce((select max((select abs(case +max((e)) when abs(abs( -count(distinct e))) then +cast(avg(f) AS integer) else count(*) end+count(*)+min( -e)) from t1)) from t1 where t1.b in (select count(distinct (17 & case case when e in (13,t1.a,e) or t1.d>=t1.e then 17 else a end when t1.e then 17 else t1.d end*t1.c)) from t1 union select cast(avg(t1.a) AS integer) from t1)),17)) from t1 where t1.c in (select ~cast(avg(t1.b) AS integer) from t1 union select  -(cast(avg(t1.c) AS integer)) from t1)),(t1.c)) FROM t1 WHERE t1.b not in (case when 11 in (select case +min(t1.f) when (+cast(avg((case t1.c when a then f else a end-f)) AS integer)) then +count(distinct (t1.f))-count(distinct t1.f) else count(*) end-count(*) | count(*) from t1 union select min(e) from t1) then (abs(b | 13-f | c)/abs(t1.f)) else t1.c end,f,t1.b) or not  -t1.a<t1.f or t1.f>=11}
} {-289}
do_test randexpr-2.921 {
  db eval {SELECT (select  -abs(max(+(select +count(*) from t1)))-max(case when b in (select (abs(13)/abs(b)) from t1 union select case when exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(coalesce((select max(+19*t1.e+case t1.f when (abs(f)/abs(t1.f)) then t1.f else e end) from t1 where 19<17),t1.a)))+11 in (select b from t1 union select t1.e from t1))) then d else t1.c end from t1) then f when 13=d then  -a else t1.a end) from t1) FROM t1 WHERE ~(select ~ -(min(f)- -cast(avg(f) AS integer)-abs(count(distinct case when t1.d=b then d when e in (select +cast(avg(e) AS integer) from t1 union select count(*) from t1) then t1.f else c end*17*f))) | (count(*)) from t1)-f<>case when (select + -max(t1.e) from t1)+(select  -min(17) from t1)*13 between 17 and 19 then t1.b else t1.d end}
} {-101}
do_test randexpr-2.922 {
  db eval {SELECT (select  -abs(max(+(select +count(*) from t1)))-max(case when b in (select (abs(13)/abs(b)) from t1 union select case when exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(coalesce((select max(+19*t1.e+case t1.f when (abs(f)/abs(t1.f)) then t1.f else e end) from t1 where 19<17),t1.a)))+11 in (select b from t1 union select t1.e from t1))) then d else t1.c end from t1) then f when 13=d then  -a else t1.a end) from t1) FROM t1 WHERE NOT (~(select ~ -(min(f)- -cast(avg(f) AS integer)-abs(count(distinct case when t1.d=b then d when e in (select +cast(avg(e) AS integer) from t1 union select count(*) from t1) then t1.f else c end*17*f))) | (count(*)) from t1)-f<>case when (select + -max(t1.e) from t1)+(select  -min(17) from t1)*13 between 17 and 19 then t1.b else t1.d end)}
} {}
do_test randexpr-2.923 {
  db eval {SELECT case (select ( - - -(+max(c))+min(e)-(count(*))+cast(avg(t1.e) AS integer)-min(t1.a)*(cast(avg(11) AS integer))) from t1) when t1.d then t1.c else case (select max(a) from t1) when  -t1.b then case when not 17<>case when t1.e<=t1.d or ((t1.e))=t1.e then t1.f when e>=t1.b then 11 else t1.d end or d in (t1.f,t1.a,t1.a) then c | 17 when t1.f between t1.a and  -t1.e then d else t1.c end else t1.c end end-t1.c FROM t1 WHERE not (exists(select 1 from t1 where a<>11+t1.d-t1.a+(select count(distinct t1.d)++max(case e when coalesce((select 11 from t1 where a>=case when coalesce((select f from t1 where exists(select 1 from t1 where 13 in (t1.c,13,t1.a))),(d))+f not between d and t1.e then d else (t1.c) end-13),(d))-t1.d then t1.a else 17 end) from t1)) and not a<(d)*19)}
} {0}
do_test randexpr-2.924 {
  db eval {SELECT case (select ( - - -(+max(c))+min(e)-(count(*))+cast(avg(t1.e) AS integer)-min(t1.a)*(cast(avg(11) AS integer))) from t1) when t1.d then t1.c else case (select max(a) from t1) when  -t1.b then case when not 17<>case when t1.e<=t1.d or ((t1.e))=t1.e then t1.f when e>=t1.b then 11 else t1.d end or d in (t1.f,t1.a,t1.a) then c | 17 when t1.f between t1.a and  -t1.e then d else t1.c end else t1.c end end-t1.c FROM t1 WHERE NOT (not (exists(select 1 from t1 where a<>11+t1.d-t1.a+(select count(distinct t1.d)++max(case e when coalesce((select 11 from t1 where a>=case when coalesce((select f from t1 where exists(select 1 from t1 where 13 in (t1.c,13,t1.a))),(d))+f not between d and t1.e then d else (t1.c) end-13),(d))-t1.d then t1.a else 17 end) from t1)) and not a<(d)*19))}
} {}
do_test randexpr-2.925 {
  db eval {SELECT case (select ( - - -(+max(c))+min(e)-(count(*))+cast(avg(t1.e) AS integer)-min(t1.a)*(cast(avg(11) AS integer))) from t1) when t1.d then t1.c else case (select max(a) from t1) when  -t1.b then case when not 17<>case when t1.e<=t1.d or ((t1.e))=t1.e then t1.f when e>=t1.b then 11 else t1.d end or d in (t1.f,t1.a,t1.a) then c & 17 when t1.f between t1.a and  -t1.e then d else t1.c end else t1.c end end-t1.c FROM t1 WHERE not (exists(select 1 from t1 where a<>11+t1.d-t1.a+(select count(distinct t1.d)++max(case e when coalesce((select 11 from t1 where a>=case when coalesce((select f from t1 where exists(select 1 from t1 where 13 in (t1.c,13,t1.a))),(d))+f not between d and t1.e then d else (t1.c) end-13),(d))-t1.d then t1.a else 17 end) from t1)) and not a<(d)*19)}
} {0}
do_test randexpr-2.926 {
  db eval {SELECT case t1.b when c*(case when ((select ++case abs(cast(avg(a) AS integer))*min(c) when min(t1.c) then cast(avg(t1.b) AS integer) else count(*) end | (count(distinct t1.c)) | ((max(t1.a))) | count(distinct b) from t1) not between t1.e and 11 and coalesce((select max(e) from t1 where a between t1.c and c+b),e) in (select t1.d from t1 union select t1.b from t1) or (not exists(select 1 from t1 where 13<>t1.a))) then 11*b else t1.b end) then t1.c else e end FROM t1 WHERE exists(select 1 from t1 where t1.d>=f)}
} {}
do_test randexpr-2.927 {
  db eval {SELECT case t1.b when c*(case when ((select ++case abs(cast(avg(a) AS integer))*min(c) when min(t1.c) then cast(avg(t1.b) AS integer) else count(*) end | (count(distinct t1.c)) | ((max(t1.a))) | count(distinct b) from t1) not between t1.e and 11 and coalesce((select max(e) from t1 where a between t1.c and c+b),e) in (select t1.d from t1 union select t1.b from t1) or (not exists(select 1 from t1 where 13<>t1.a))) then 11*b else t1.b end) then t1.c else e end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d>=f))}
} {500}
do_test randexpr-2.928 {
  db eval {SELECT case t1.b when c*(case when ((select ++case abs(cast(avg(a) AS integer))*min(c) when min(t1.c) then cast(avg(t1.b) AS integer) else count(*) end & (count(distinct t1.c)) & ((max(t1.a))) & count(distinct b) from t1) not between t1.e and 11 and coalesce((select max(e) from t1 where a between t1.c and c+b),e) in (select t1.d from t1 union select t1.b from t1) or (not exists(select 1 from t1 where 13<>t1.a))) then 11*b else t1.b end) then t1.c else e end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d>=f))}
} {500}
do_test randexpr-2.929 {
  db eval {SELECT d-coalesce((select d from t1 where case when ~11*a*c>=17 then coalesce((select (abs(t1.e+c+(abs(f*(select abs((min(e))) from t1)-t1.f)/abs( - -a))-a)/abs(t1.d)) from t1 where f not in (e,b,t1.f) and c<>f),f)*19 else f end in (b,e,17)),13)-19 FROM t1 WHERE not f>=11}
} {}
do_test randexpr-2.930 {
  db eval {SELECT d-coalesce((select d from t1 where case when ~11*a*c>=17 then coalesce((select (abs(t1.e+c+(abs(f*(select abs((min(e))) from t1)-t1.f)/abs( - -a))-a)/abs(t1.d)) from t1 where f not in (e,b,t1.f) and c<>f),f)*19 else f end in (b,e,17)),13)-19 FROM t1 WHERE NOT (not f>=11)}
} {368}
do_test randexpr-2.931 {
  db eval {SELECT f*t1.d+coalesce((select a+17-t1.e from t1 where 13=t1.f and not (t1.f | b*t1.d-t1.c*coalesce((select max(coalesce((select t1.f from t1 where f not in (13,a,d)),d)) from t1 where t1.a in (select cast(avg(c) AS integer) from t1 union select count(distinct b)*count(distinct t1.c) from t1)),((17)))+ -b+19+13)=t1.f and 19>=t1.a or  - -a>=t1.b),a) FROM t1 WHERE f not in (coalesce((select max(19) from t1 where (t1.e<=+t1.f*case when ~(abs(b)/abs(b)) in (f,t1.d,17) then (abs(t1.e-11 | d)/abs(coalesce((select d from t1 where not coalesce((select t1.a from t1 where not exists(select 1 from t1 where c>=t1.c)),d) in (select count(distinct f)*cast(avg(19) AS integer) from t1 union select count(distinct d) from t1)),13))) when not 11<=t1.a then t1.f else 19 end-19)),f)-17, -a,e)}
} {240100}
do_test randexpr-2.932 {
  db eval {SELECT f*t1.d+coalesce((select a+17-t1.e from t1 where 13=t1.f and not (t1.f | b*t1.d-t1.c*coalesce((select max(coalesce((select t1.f from t1 where f not in (13,a,d)),d)) from t1 where t1.a in (select cast(avg(c) AS integer) from t1 union select count(distinct b)*count(distinct t1.c) from t1)),((17)))+ -b+19+13)=t1.f and 19>=t1.a or  - -a>=t1.b),a) FROM t1 WHERE NOT (f not in (coalesce((select max(19) from t1 where (t1.e<=+t1.f*case when ~(abs(b)/abs(b)) in (f,t1.d,17) then (abs(t1.e-11 | d)/abs(coalesce((select d from t1 where not coalesce((select t1.a from t1 where not exists(select 1 from t1 where c>=t1.c)),d) in (select count(distinct f)*cast(avg(19) AS integer) from t1 union select count(distinct d) from t1)),13))) when not 11<=t1.a then t1.f else 19 end-19)),f)-17, -a,e))}
} {}
do_test randexpr-2.933 {
  db eval {SELECT f*t1.d+coalesce((select a+17-t1.e from t1 where 13=t1.f and not (t1.f & b*t1.d-t1.c*coalesce((select max(coalesce((select t1.f from t1 where f not in (13,a,d)),d)) from t1 where t1.a in (select cast(avg(c) AS integer) from t1 union select count(distinct b)*count(distinct t1.c) from t1)),((17)))+ -b+19+13)=t1.f and 19>=t1.a or  - -a>=t1.b),a) FROM t1 WHERE f not in (coalesce((select max(19) from t1 where (t1.e<=+t1.f*case when ~(abs(b)/abs(b)) in (f,t1.d,17) then (abs(t1.e-11 | d)/abs(coalesce((select d from t1 where not coalesce((select t1.a from t1 where not exists(select 1 from t1 where c>=t1.c)),d) in (select count(distinct f)*cast(avg(19) AS integer) from t1 union select count(distinct d) from t1)),13))) when not 11<=t1.a then t1.f else 19 end-19)),f)-17, -a,e)}
} {240100}
do_test randexpr-2.934 {
  db eval {SELECT coalesce((select case e*+(abs(t1.f-t1.b)/abs(e))-d when coalesce((select t1.e from t1 where exists(select 1 from t1 where +d+ -t1.e not between case when (abs(b)/abs(t1.b)) between a and 17 then t1.b when not 11 not between b and d then 19 else 19 end and t1.f and t1.a between 17 and b)), -13) then (t1.a) else 13 end from t1 where 17 between b and 13), -19) | c FROM t1 WHERE case when t1.e*t1.b | f+d | f+11+(a)-+a+ -t1.c-t1.f | coalesce((select case t1.e when 17 then e else t1.a end from t1 where t1.a<t1.b),t1.b)*f<= -t1.a and c<t1.f then (select (max((b))) from t1) else t1.b end not in (a,a,t1.c)}
} {-19}
do_test randexpr-2.935 {
  db eval {SELECT coalesce((select case e*+(abs(t1.f-t1.b)/abs(e))-d when coalesce((select t1.e from t1 where exists(select 1 from t1 where +d+ -t1.e not between case when (abs(b)/abs(t1.b)) between a and 17 then t1.b when not 11 not between b and d then 19 else 19 end and t1.f and t1.a between 17 and b)), -13) then (t1.a) else 13 end from t1 where 17 between b and 13), -19) | c FROM t1 WHERE NOT (case when t1.e*t1.b | f+d | f+11+(a)-+a+ -t1.c-t1.f | coalesce((select case t1.e when 17 then e else t1.a end from t1 where t1.a<t1.b),t1.b)*f<= -t1.a and c<t1.f then (select (max((b))) from t1) else t1.b end not in (a,a,t1.c))}
} {}
do_test randexpr-2.936 {
  db eval {SELECT coalesce((select case e*+(abs(t1.f-t1.b)/abs(e))-d when coalesce((select t1.e from t1 where exists(select 1 from t1 where +d+ -t1.e not between case when (abs(b)/abs(t1.b)) between a and 17 then t1.b when not 11 not between b and d then 19 else 19 end and t1.f and t1.a between 17 and b)), -13) then (t1.a) else 13 end from t1 where 17 between b and 13), -19) & c FROM t1 WHERE case when t1.e*t1.b | f+d | f+11+(a)-+a+ -t1.c-t1.f | coalesce((select case t1.e when 17 then e else t1.a end from t1 where t1.a<t1.b),t1.b)*f<= -t1.a and c<t1.f then (select (max((b))) from t1) else t1.b end not in (a,a,t1.c)}
} {300}
do_test randexpr-2.937 {
  db eval {SELECT coalesce((select max(t1.d*case when case when ~ -t1.d+17-b-13*t1.f*(abs(t1.b+13)/abs(t1.a))+a*t1.e*t1.a+c*t1.d-t1.a in (select t1.b from t1 union select t1.d from t1) then t1.e else t1.e end not in (t1.f,t1.e,19) then t1.d else 11 end) from t1 where d not between t1.a and a),c) FROM t1 WHERE t1.e in (select a from t1 union select +b-t1.b from t1)}
} {}
do_test randexpr-2.938 {
  db eval {SELECT coalesce((select max(t1.d*case when case when ~ -t1.d+17-b-13*t1.f*(abs(t1.b+13)/abs(t1.a))+a*t1.e*t1.a+c*t1.d-t1.a in (select t1.b from t1 union select t1.d from t1) then t1.e else t1.e end not in (t1.f,t1.e,19) then t1.d else 11 end) from t1 where d not between t1.a and a),c) FROM t1 WHERE NOT (t1.e in (select a from t1 union select +b-t1.b from t1))}
} {4400}
do_test randexpr-2.939 {
  db eval {SELECT d*(select  - - -max( -(abs(e)/abs(~t1.c))) from t1)-13 | coalesce((select max(+t1.a*a) from t1 where t1.e+case e when a then t1.f+(select case ~ -max(d)* - -cast(avg(c) AS integer) when  -min( -t1.b) then min(t1.b) else count(distinct 13) end from t1)-a else ~case when t1.f not in (b,b,a) or c between d and t1.a then c when t1.b>b then e else t1.d end end-11>=13),e) | 13 FROM t1 WHERE not exists(select 1 from t1 where t1.c< -d or t1.e between c and  -t1.d or d<=17)}
} {10143}
do_test randexpr-2.940 {
  db eval {SELECT d*(select  - - -max( -(abs(e)/abs(~t1.c))) from t1)-13 | coalesce((select max(+t1.a*a) from t1 where t1.e+case e when a then t1.f+(select case ~ -max(d)* - -cast(avg(c) AS integer) when  -min( -t1.b) then min(t1.b) else count(distinct 13) end from t1)-a else ~case when t1.f not in (b,b,a) or c between d and t1.a then c when t1.b>b then e else t1.d end end-11>=13),e) | 13 FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.c< -d or t1.e between c and  -t1.d or d<=17))}
} {}
do_test randexpr-2.941 {
  db eval {SELECT d*(select  - - -max( -(abs(e)/abs(~t1.c))) from t1)-13 & coalesce((select max(+t1.a*a) from t1 where t1.e+case e when a then t1.f+(select case ~ -max(d)* - -cast(avg(c) AS integer) when  -min( -t1.b) then min(t1.b) else count(distinct 13) end from t1)-a else ~case when t1.f not in (b,b,a) or c between d and t1.a then c when t1.b>b then e else t1.d end end-11>=13),e) & 13 FROM t1 WHERE not exists(select 1 from t1 where t1.c< -d or t1.e between c and  -t1.d or d<=17)}
} {0}
do_test randexpr-2.942 {
  db eval {SELECT t1.c*+case when a<>+case when b>t1.e or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e in (select coalesce((select b from t1 where (d<f) or t1.e in ((t1.f),(t1.a),13) and (t1.e)<>( -t1.d)),(( -b))) from t1 union select t1.d from t1))) then (select  -max(t1.e)-count(*) from t1) else (t1.c) end+b+(t1.f) | f | e then t1.d when t1.f not in (19,13,e) then 13 else 11 end FROM t1 WHERE (f<>coalesce((select max(a) from t1 where (exists(select 1 from t1 where c between t1.b and case when (abs(19)/abs(t1.f)) in (t1.f,17,t1.a) then t1.b when t1.d<=t1.a then t1.a else c end or c<c) or 13>=b and c>=t1.d and t1.d between c and t1.c)),e+case (select count(distinct case 19 when 13 then t1.b else 11 end) from t1) when 13 then b else t1.b end)-17-17)}
} {120000}
do_test randexpr-2.943 {
  db eval {SELECT t1.c*+case when a<>+case when b>t1.e or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e in (select coalesce((select b from t1 where (d<f) or t1.e in ((t1.f),(t1.a),13) and (t1.e)<>( -t1.d)),(( -b))) from t1 union select t1.d from t1))) then (select  -max(t1.e)-count(*) from t1) else (t1.c) end+b+(t1.f) | f | e then t1.d when t1.f not in (19,13,e) then 13 else 11 end FROM t1 WHERE NOT ((f<>coalesce((select max(a) from t1 where (exists(select 1 from t1 where c between t1.b and case when (abs(19)/abs(t1.f)) in (t1.f,17,t1.a) then t1.b when t1.d<=t1.a then t1.a else c end or c<c) or 13>=b and c>=t1.d and t1.d between c and t1.c)),e+case (select count(distinct case 19 when 13 then t1.b else 11 end) from t1) when 13 then b else t1.b end)-17-17))}
} {}
do_test randexpr-2.944 {
  db eval {SELECT t1.c*+case when a<>+case when b>t1.e or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e in (select coalesce((select b from t1 where (d<f) or t1.e in ((t1.f),(t1.a),13) and (t1.e)<>( -t1.d)),(( -b))) from t1 union select t1.d from t1))) then (select  -max(t1.e)-count(*) from t1) else (t1.c) end+b+(t1.f) & f & e then t1.d when t1.f not in (19,13,e) then 13 else 11 end FROM t1 WHERE (f<>coalesce((select max(a) from t1 where (exists(select 1 from t1 where c between t1.b and case when (abs(19)/abs(t1.f)) in (t1.f,17,t1.a) then t1.b when t1.d<=t1.a then t1.a else c end or c<c) or 13>=b and c>=t1.d and t1.d between c and t1.c)),e+case (select count(distinct case 19 when 13 then t1.b else 11 end) from t1) when 13 then b else t1.b end)-17-17)}
} {120000}
do_test randexpr-2.945 {
  db eval {SELECT case when (e)- -((select case min(case when e in (select coalesce((select max(d) from t1 where 13<>(t1.d-e)),e) from t1 union select c from t1) then d else  -11 end+a) when count(distinct  -f) then count(*) else  -(case cast(avg(17) AS integer)- -count(distinct t1.c)+cast(avg(b) AS integer) when  -max(11) then count(*) else cast(avg(t1.e) AS integer) end+max(t1.f)) end from t1))<=t1.b | t1.e then t1.d when not exists(select 1 from t1 where c<>13) then 11 else d end FROM t1 WHERE (select max(t1.a*case f when b then ~case when not exists(select 1 from t1 where f-d>(select abs(cast(avg(~17+b+d) AS integer)) from t1) or f-e in (select b from t1 union select t1.d from t1) or exists(select 1 from t1 where 13<>b)) then (abs(a)/abs( -d)) when (d<t1.a) then e else t1.e end else t1.a end) from t1)*t1.e in (select t1.f from t1 union select t1.b from t1)}
} {}
do_test randexpr-2.946 {
  db eval {SELECT case when (e)- -((select case min(case when e in (select coalesce((select max(d) from t1 where 13<>(t1.d-e)),e) from t1 union select c from t1) then d else  -11 end+a) when count(distinct  -f) then count(*) else  -(case cast(avg(17) AS integer)- -count(distinct t1.c)+cast(avg(b) AS integer) when  -max(11) then count(*) else cast(avg(t1.e) AS integer) end+max(t1.f)) end from t1))<=t1.b | t1.e then t1.d when not exists(select 1 from t1 where c<>13) then 11 else d end FROM t1 WHERE NOT ((select max(t1.a*case f when b then ~case when not exists(select 1 from t1 where f-d>(select abs(cast(avg(~17+b+d) AS integer)) from t1) or f-e in (select b from t1 union select t1.d from t1) or exists(select 1 from t1 where 13<>b)) then (abs(a)/abs( -d)) when (d<t1.a) then e else t1.e end else t1.a end) from t1)*t1.e in (select t1.f from t1 union select t1.b from t1))}
} {400}
do_test randexpr-2.947 {
  db eval {SELECT case when (e)- -((select case min(case when e in (select coalesce((select max(d) from t1 where 13<>(t1.d-e)),e) from t1 union select c from t1) then d else  -11 end+a) when count(distinct  -f) then count(*) else  -(case cast(avg(17) AS integer)- -count(distinct t1.c)+cast(avg(b) AS integer) when  -max(11) then count(*) else cast(avg(t1.e) AS integer) end+max(t1.f)) end from t1))<=t1.b & t1.e then t1.d when not exists(select 1 from t1 where c<>13) then 11 else d end FROM t1 WHERE NOT ((select max(t1.a*case f when b then ~case when not exists(select 1 from t1 where f-d>(select abs(cast(avg(~17+b+d) AS integer)) from t1) or f-e in (select b from t1 union select t1.d from t1) or exists(select 1 from t1 where 13<>b)) then (abs(a)/abs( -d)) when (d<t1.a) then e else t1.e end else t1.a end) from t1)*t1.e in (select t1.f from t1 union select t1.b from t1))}
} {400}
do_test randexpr-2.948 {
  db eval {SELECT (t1.b+coalesce((select case when e-13+11 | f+case when not t1.b not between t1.f and t1.f then e else (t1.e) end-c-b+c>=e and d between d and a then t1.c when (t1.c>19) then  -11 else a end from t1 where a<d),e)+f+t1.e*d)*17 FROM t1 WHERE t1.b in (select cast(avg(17) AS integer) from t1 union select ~case (+abs(cast(avg((d)) AS integer))) when count(distinct case when (case when c>c then t1.e else  -d end-t1.e) between b and 11 then b when exists(select 1 from t1 where a<=d) then 11 else 13 end) then cast(avg(t1.b) AS integer)-(cast(avg(11) AS integer)-min(a))-count(distinct  -e) else cast(avg(13) AS integer) end*max(b) from t1) or (t1.f not between t1.d and 17 | 19*e)}
} {}
do_test randexpr-2.949 {
  db eval {SELECT (t1.b+coalesce((select case when e-13+11 | f+case when not t1.b not between t1.f and t1.f then e else (t1.e) end-c-b+c>=e and d between d and a then t1.c when (t1.c>19) then  -11 else a end from t1 where a<d),e)+f+t1.e*d)*17 FROM t1 WHERE NOT (t1.b in (select cast(avg(17) AS integer) from t1 union select ~case (+abs(cast(avg((d)) AS integer))) when count(distinct case when (case when c>c then t1.e else  -d end-t1.e) between b and 11 then b when exists(select 1 from t1 where a<=d) then 11 else 13 end) then cast(avg(t1.b) AS integer)-(cast(avg(11) AS integer)-min(a))-count(distinct  -e) else cast(avg(13) AS integer) end*max(b) from t1) or (t1.f not between t1.d and 17 | 19*e))}
} {3413413}
do_test randexpr-2.950 {
  db eval {SELECT (t1.b+coalesce((select case when e-13+11 & f+case when not t1.b not between t1.f and t1.f then e else (t1.e) end-c-b+c>=e and d between d and a then t1.c when (t1.c>19) then  -11 else a end from t1 where a<d),e)+f+t1.e*d)*17 FROM t1 WHERE NOT (t1.b in (select cast(avg(17) AS integer) from t1 union select ~case (+abs(cast(avg((d)) AS integer))) when count(distinct case when (case when c>c then t1.e else  -d end-t1.e) between b and 11 then b when exists(select 1 from t1 where a<=d) then 11 else 13 end) then cast(avg(t1.b) AS integer)-(cast(avg(11) AS integer)-min(a))-count(distinct  -e) else cast(avg(13) AS integer) end*max(b) from t1) or (t1.f not between t1.d and 17 | 19*e))}
} {3413413}
do_test randexpr-2.951 {
  db eval {SELECT coalesce((select max(+19) from t1 where t1.f>=(abs(19)/abs(t1.c*(select count(distinct (abs(t1.f)/abs(t1.c))*coalesce((select max(case when (select count(*) from t1)*t1.f in (t1.b,17,t1.f) then d when t1.e not in (t1.b,t1.a,t1.b) then  -17 else t1.d end) from t1 where (11 not in (t1.b,(f),t1.c)) and t1.c>=t1.f),e)) from t1))) or ((t1.d<=t1.b))),13) FROM t1 WHERE t1.a<>(coalesce((select coalesce((select max(t1.a) from t1 where case  -t1.c when t1.b then coalesce((select t1.b from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where ((select count(*)++count(distinct a) from t1) not between b and +(17))))),19)*t1.e else f end<=(t1.b)),t1.c) from t1 where d<>b),13)-17+a)+d+(19)+a or d between 11 and  -11}
} {19}
do_test randexpr-2.952 {
  db eval {SELECT coalesce((select max(+19) from t1 where t1.f>=(abs(19)/abs(t1.c*(select count(distinct (abs(t1.f)/abs(t1.c))*coalesce((select max(case when (select count(*) from t1)*t1.f in (t1.b,17,t1.f) then d when t1.e not in (t1.b,t1.a,t1.b) then  -17 else t1.d end) from t1 where (11 not in (t1.b,(f),t1.c)) and t1.c>=t1.f),e)) from t1))) or ((t1.d<=t1.b))),13) FROM t1 WHERE NOT (t1.a<>(coalesce((select coalesce((select max(t1.a) from t1 where case  -t1.c when t1.b then coalesce((select t1.b from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where ((select count(*)++count(distinct a) from t1) not between b and +(17))))),19)*t1.e else f end<=(t1.b)),t1.c) from t1 where d<>b),13)-17+a)+d+(19)+a or d between 11 and  -11)}
} {}
do_test randexpr-2.953 {
  db eval {SELECT t1.b-coalesce((select max(~t1.a) from t1 where coalesce((select max(t1.d) from t1 where coalesce((select max(coalesce((select t1.c*t1.d from t1 where not f>=a-t1.c+ -coalesce((select t1.f*e from t1 where (not exists(select 1 from t1 where d<=19))),b)-d),13)* -e) from t1 where (d<19 or 13 not between t1.f and t1.d)),11) between 17 and 19),t1.c)< -b),d) FROM t1 WHERE +case when b in (b+~b+t1.f,coalesce((select max(13) from t1 where exists(select 1 from t1 where 17<>+a or not exists(select 1 from t1 where e+19=f))),(e)),case when c>case when coalesce((select 13 from t1 where f>=t1.b and c not between t1.e and t1.d),11) in (select (case max(11) when (min(b)) then min( -d) else cast(avg(t1.e) AS integer) end) from t1 union select max(19) from t1) then t1.d else 13 end then t1.f else t1.e end) or b>=(t1.f) then t1.e else t1.e end*b>f}
} {-200}
do_test randexpr-2.954 {
  db eval {SELECT t1.b-coalesce((select max(~t1.a) from t1 where coalesce((select max(t1.d) from t1 where coalesce((select max(coalesce((select t1.c*t1.d from t1 where not f>=a-t1.c+ -coalesce((select t1.f*e from t1 where (not exists(select 1 from t1 where d<=19))),b)-d),13)* -e) from t1 where (d<19 or 13 not between t1.f and t1.d)),11) between 17 and 19),t1.c)< -b),d) FROM t1 WHERE NOT (+case when b in (b+~b+t1.f,coalesce((select max(13) from t1 where exists(select 1 from t1 where 17<>+a or not exists(select 1 from t1 where e+19=f))),(e)),case when c>case when coalesce((select 13 from t1 where f>=t1.b and c not between t1.e and t1.d),11) in (select (case max(11) when (min(b)) then min( -d) else cast(avg(t1.e) AS integer) end) from t1 union select max(19) from t1) then t1.d else 13 end then t1.f else t1.e end) or b>=(t1.f) then t1.e else t1.e end*b>f)}
} {}
do_test randexpr-2.955 {
  db eval {SELECT (select count(distinct + - -f-c-17*a+(t1.d)-+((select abs( - - -count(distinct 13)-count(*)*count(distinct t1.d)*count(*))-cast(avg(f) AS integer) from t1))-~19+13- -d*t1.e*(19)+ -f- -b) from t1)-e FROM t1 WHERE not t1.c between t1.f and coalesce((select coalesce((select case when exists(select 1 from t1 where +~f=case when d<>t1.d then t1.f else  -d end and d between 17 and t1.c) then ~case when a in (d,c,t1.d) then 17 else t1.f end when f=f then d else  -b end from t1 where c>f),e) from t1 where not exists(select 1 from t1 where t1.d<=c) and 19=(11) and t1.e<>19),a)}
} {-499}
do_test randexpr-2.956 {
  db eval {SELECT (select count(distinct + - -f-c-17*a+(t1.d)-+((select abs( - - -count(distinct 13)-count(*)*count(distinct t1.d)*count(*))-cast(avg(f) AS integer) from t1))-~19+13- -d*t1.e*(19)+ -f- -b) from t1)-e FROM t1 WHERE NOT (not t1.c between t1.f and coalesce((select coalesce((select case when exists(select 1 from t1 where +~f=case when d<>t1.d then t1.f else  -d end and d between 17 and t1.c) then ~case when a in (d,c,t1.d) then 17 else t1.f end when f=f then d else  -b end from t1 where c>f),e) from t1 where not exists(select 1 from t1 where t1.d<=c) and 19=(11) and t1.e<>19),a))}
} {}
do_test randexpr-2.957 {
  db eval {SELECT case when f-t1.b*coalesce((select max(11) from t1 where exists(select 1 from t1 where (abs(t1.b)/abs(13-11))=(19+c))),coalesce((select t1.c | f from t1 where (abs(c*19)/abs(17))=t1.e),19))-e between t1.f and  -((19)) and 13 not between t1.c and 11 and not exists(select 1 from t1 where t1.b>b) then t1.d when t1.c>=13 then c else f end FROM t1 WHERE e-t1.c=+e*~coalesce((select max(t1.f) from t1 where (t1.f in (coalesce((select max(11) from t1 where  -13<>(13)-(select (count(*)) from t1)*t1.f and ( -11+t1.b+b*b-(select max(13) from t1)) in (t1.f,a,f)),d),17,13))),t1.f)-e}
} {}
do_test randexpr-2.958 {
  db eval {SELECT case when f-t1.b*coalesce((select max(11) from t1 where exists(select 1 from t1 where (abs(t1.b)/abs(13-11))=(19+c))),coalesce((select t1.c | f from t1 where (abs(c*19)/abs(17))=t1.e),19))-e between t1.f and  -((19)) and 13 not between t1.c and 11 and not exists(select 1 from t1 where t1.b>b) then t1.d when t1.c>=13 then c else f end FROM t1 WHERE NOT (e-t1.c=+e*~coalesce((select max(t1.f) from t1 where (t1.f in (coalesce((select max(11) from t1 where  -13<>(13)-(select (count(*)) from t1)*t1.f and ( -11+t1.b+b*b-(select max(13) from t1)) in (t1.f,a,f)),d),17,13))),t1.f)-e)}
} {300}
do_test randexpr-2.959 {
  db eval {SELECT case when f-t1.b*coalesce((select max(11) from t1 where exists(select 1 from t1 where (abs(t1.b)/abs(13-11))=(19+c))),coalesce((select t1.c & f from t1 where (abs(c*19)/abs(17))=t1.e),19))-e between t1.f and  -((19)) and 13 not between t1.c and 11 and not exists(select 1 from t1 where t1.b>b) then t1.d when t1.c>=13 then c else f end FROM t1 WHERE NOT (e-t1.c=+e*~coalesce((select max(t1.f) from t1 where (t1.f in (coalesce((select max(11) from t1 where  -13<>(13)-(select (count(*)) from t1)*t1.f and ( -11+t1.b+b*b-(select max(13) from t1)) in (t1.f,a,f)),d),17,13))),t1.f)-e)}
} {300}
do_test randexpr-2.960 {
  db eval {SELECT t1.e+case when coalesce((select  -(abs(t1.e)/abs(t1.c-t1.e)) from t1 where d | d between  -t1.d and ~case t1.d when t1.f then ((abs((select ((min(b)+abs(cast(avg(t1.a) AS integer)*(max(19))))-(cast(avg(t1.d) AS integer))) from t1)*~f)/abs(t1.a*t1.c)))*17 else 19 end),f)- -c<>t1.c then f else t1.f end FROM t1 WHERE 19*coalesce((select max(a) from t1 where not (select count(distinct ~t1.b | t1.d) from t1)<case when b+(case when t1.c not in (f,(b),t1.c) then t1.d else 19 end)>t1.e then c when  -b<11 then t1.c else  -t1.e end and not d in ( -t1.d,t1.a,f) and c=t1.f and f<>t1.a),t1.b) between t1.a and b}
} {}
do_test randexpr-2.961 {
  db eval {SELECT t1.e+case when coalesce((select  -(abs(t1.e)/abs(t1.c-t1.e)) from t1 where d | d between  -t1.d and ~case t1.d when t1.f then ((abs((select ((min(b)+abs(cast(avg(t1.a) AS integer)*(max(19))))-(cast(avg(t1.d) AS integer))) from t1)*~f)/abs(t1.a*t1.c)))*17 else 19 end),f)- -c<>t1.c then f else t1.f end FROM t1 WHERE NOT (19*coalesce((select max(a) from t1 where not (select count(distinct ~t1.b | t1.d) from t1)<case when b+(case when t1.c not in (f,(b),t1.c) then t1.d else 19 end)>t1.e then c when  -b<11 then t1.c else  -t1.e end and not d in ( -t1.d,t1.a,f) and c=t1.f and f<>t1.a),t1.b) between t1.a and b)}
} {1100}
do_test randexpr-2.962 {
  db eval {SELECT t1.e+case when coalesce((select  -(abs(t1.e)/abs(t1.c-t1.e)) from t1 where d & d between  -t1.d and ~case t1.d when t1.f then ((abs((select ((min(b)+abs(cast(avg(t1.a) AS integer)*(max(19))))-(cast(avg(t1.d) AS integer))) from t1)*~f)/abs(t1.a*t1.c)))*17 else 19 end),f)- -c<>t1.c then f else t1.f end FROM t1 WHERE NOT (19*coalesce((select max(a) from t1 where not (select count(distinct ~t1.b | t1.d) from t1)<case when b+(case when t1.c not in (f,(b),t1.c) then t1.d else 19 end)>t1.e then c when  -b<11 then t1.c else  -t1.e end and not d in ( -t1.d,t1.a,f) and c=t1.f and f<>t1.a),t1.b) between t1.a and b)}
} {1100}
do_test randexpr-2.963 {
  db eval {SELECT t1.b*coalesce((select max(e) from t1 where ((t1.d))<=case case when +coalesce((select (abs(t1.a)/abs(c))-(abs( -e)/abs(11* -t1.b+t1.d* -c))-t1.c from t1 where not exists(select 1 from t1 where t1.c=(11))), -11) between 17 and t1.a then t1.a when t1.b>t1.e then (b) else b end-c when d then d else t1.f end),((t1.e))) FROM t1 WHERE ~ -case when not exists(select 1 from t1 where t1.b between b and 11 | d) then  -(abs(17+d)/abs(e)) else case when not (t1.d>=case when case a when case t1.f when (e) then 17 else 19 end then 13 else 19 end in (t1.e,b,((t1.b))) then d when t1.d not in (19,t1.a, -c) then 11 else  -a end) then 11 else c end end*17*t1.b not in (a,b,13)}
} {100000}
do_test randexpr-2.964 {
  db eval {SELECT t1.b*coalesce((select max(e) from t1 where ((t1.d))<=case case when +coalesce((select (abs(t1.a)/abs(c))-(abs( -e)/abs(11* -t1.b+t1.d* -c))-t1.c from t1 where not exists(select 1 from t1 where t1.c=(11))), -11) between 17 and t1.a then t1.a when t1.b>t1.e then (b) else b end-c when d then d else t1.f end),((t1.e))) FROM t1 WHERE NOT (~ -case when not exists(select 1 from t1 where t1.b between b and 11 | d) then  -(abs(17+d)/abs(e)) else case when not (t1.d>=case when case a when case t1.f when (e) then 17 else 19 end then 13 else 19 end in (t1.e,b,((t1.b))) then d when t1.d not in (19,t1.a, -c) then 11 else  -a end) then 11 else c end end*17*t1.b not in (a,b,13))}
} {}
do_test randexpr-2.965 {
  db eval {SELECT e*case +case when not (select max(17) from t1)>=case when not d=c+t1.c then 11 else 11 end or (c in (select t1.c from t1 union select c from t1) or 11<=t1.a) or d<=11 or 19 in ( -13,d,19) or a not between 13 and (t1.c) then case when t1.f<=(t1.a) then t1.e+13*e when (t1.b) not between f and a then c else 11 end*11 else a end when 19 then t1.a else 17 end FROM t1 WHERE b<>17}
} {8500}
do_test randexpr-2.966 {
  db eval {SELECT e*case +case when not (select max(17) from t1)>=case when not d=c+t1.c then 11 else 11 end or (c in (select t1.c from t1 union select c from t1) or 11<=t1.a) or d<=11 or 19 in ( -13,d,19) or a not between 13 and (t1.c) then case when t1.f<=(t1.a) then t1.e+13*e when (t1.b) not between f and a then c else 11 end*11 else a end when 19 then t1.a else 17 end FROM t1 WHERE NOT (b<>17)}
} {}
do_test randexpr-2.967 {
  db eval {SELECT (abs(case when (13+e in (select min(a) | case abs(min(case when t1.e in (select b from t1 union select a from t1) then t1.e when t1.b=t1.c then t1.b else c end-f)) when ~(cast(avg(c) AS integer)) then min(t1.e) else count(*) end from t1 union select min(f) from t1)) and t1.d not between c and 13 then coalesce((select t1.d from t1 where t1.e<>a),19)-t1.d else 19 end)/abs(c))-c+11+c FROM t1 WHERE t1.e<f+11-b}
} {}
do_test randexpr-2.968 {
  db eval {SELECT (abs(case when (13+e in (select min(a) | case abs(min(case when t1.e in (select b from t1 union select a from t1) then t1.e when t1.b=t1.c then t1.b else c end-f)) when ~(cast(avg(c) AS integer)) then min(t1.e) else count(*) end from t1 union select min(f) from t1)) and t1.d not between c and 13 then coalesce((select t1.d from t1 where t1.e<>a),19)-t1.d else 19 end)/abs(c))-c+11+c FROM t1 WHERE NOT (t1.e<f+11-b)}
} {11}
do_test randexpr-2.969 {
  db eval {SELECT (abs(case when (13+e in (select min(a) & case abs(min(case when t1.e in (select b from t1 union select a from t1) then t1.e when t1.b=t1.c then t1.b else c end-f)) when ~(cast(avg(c) AS integer)) then min(t1.e) else count(*) end from t1 union select min(f) from t1)) and t1.d not between c and 13 then coalesce((select t1.d from t1 where t1.e<>a),19)-t1.d else 19 end)/abs(c))-c+11+c FROM t1 WHERE NOT (t1.e<f+11-b)}
} {11}
do_test randexpr-2.970 {
  db eval {SELECT case when case when not exists(select 1 from t1 where (11 not between ~~t1.d-case c when coalesce((select case f when coalesce((select max(t1.f) from t1 where 11 not in (((13)),d,t1.d)),11) then f else a end from t1 where 11 not between (t1.a) and 17),t1.c)-c*17 then (17) else t1.b end+t1.d+t1.a and d)) then t1.e-11+19 else (d) end*d<=11 then t1.b else f end FROM t1 WHERE not exists(select 1 from t1 where d>=t1.f)}
} {600}
do_test randexpr-2.971 {
  db eval {SELECT case when case when not exists(select 1 from t1 where (11 not between ~~t1.d-case c when coalesce((select case f when coalesce((select max(t1.f) from t1 where 11 not in (((13)),d,t1.d)),11) then f else a end from t1 where 11 not between (t1.a) and 17),t1.c)-c*17 then (17) else t1.b end+t1.d+t1.a and d)) then t1.e-11+19 else (d) end*d<=11 then t1.b else f end FROM t1 WHERE NOT (not exists(select 1 from t1 where d>=t1.f))}
} {}
do_test randexpr-2.972 {
  db eval {SELECT 13 | t1.c+case when (not t1.d-c between +t1.b and  -coalesce((select (select count(distinct 17) from t1)*a from t1 where  -case when not t1.f in (select count(distinct 13) from t1 union select min( -t1.a) from t1) then case when (t1.e)< -11 then  -c else t1.a end else d end-c*t1.a-d+ -e-t1.a not in (17,e,t1.a)),b) | t1.f) then c else 11 end FROM t1 WHERE case when (+e | (t1.e) | 11)<>b then t1.b when t1.e<>~(case when (t1.a*b) in (select d from t1 union select b from t1) or t1.c not in (t1.a,t1.d,13) and t1.f in (select case min(19) when min(17) then min(19) else count(distinct t1.e) end from t1 union select (count(*)) from t1) then t1.f else b end)+11 then b else 13 end+t1.d between b and 17}
} {}
do_test randexpr-2.973 {
  db eval {SELECT 13 | t1.c+case when (not t1.d-c between +t1.b and  -coalesce((select (select count(distinct 17) from t1)*a from t1 where  -case when not t1.f in (select count(distinct 13) from t1 union select min( -t1.a) from t1) then case when (t1.e)< -11 then  -c else t1.a end else d end-c*t1.a-d+ -e-t1.a not in (17,e,t1.a)),b) | t1.f) then c else 11 end FROM t1 WHERE NOT (case when (+e | (t1.e) | 11)<>b then t1.b when t1.e<>~(case when (t1.a*b) in (select d from t1 union select b from t1) or t1.c not in (t1.a,t1.d,13) and t1.f in (select case min(19) when min(17) then min(19) else count(distinct t1.e) end from t1 union select (count(*)) from t1) then t1.f else b end)+11 then b else 13 end+t1.d between b and 17)}
} {605}
do_test randexpr-2.974 {
  db eval {SELECT 13 & t1.c+case when (not t1.d-c between +t1.b and  -coalesce((select (select count(distinct 17) from t1)*a from t1 where  -case when not t1.f in (select count(distinct 13) from t1 union select min( -t1.a) from t1) then case when (t1.e)< -11 then  -c else t1.a end else d end-c*t1.a-d+ -e-t1.a not in (17,e,t1.a)),b) & t1.f) then c else 11 end FROM t1 WHERE NOT (case when (+e | (t1.e) | 11)<>b then t1.b when t1.e<>~(case when (t1.a*b) in (select d from t1 union select b from t1) or t1.c not in (t1.a,t1.d,13) and t1.f in (select case min(19) when min(17) then min(19) else count(distinct t1.e) end from t1 union select (count(*)) from t1) then t1.f else b end)+11 then b else 13 end+t1.d between b and 17)}
} {8}
do_test randexpr-2.975 {
  db eval {SELECT case when case when t1.a<>t1.d then d*t1.a*11-e-(+11+d)-e else (select case  -count(distinct t1.e) when cast(avg(b) AS integer) then count(distinct t1.d) else cast(avg(13) AS integer) end*cast(avg(19) AS integer) from t1) end<>case e when e then t1.e else (t1.f) end or not exists(select 1 from t1 where 19=f) and  -t1.d>t1.e then t1.e+e*e when 11=t1.c then e else c end FROM t1 WHERE ~c>(case when t1.e<=e then case when case when 17+f in (d,t1.d | t1.c,t1.b) and 13<>19 or not t1.c<f then coalesce((select max(b) from t1 where c not between b and t1.c),c)+(17) when d<=t1.c then t1.b else t1.c end-b not in (a,f,11) then c else 17 end else f end)}
} {}
do_test randexpr-2.976 {
  db eval {SELECT case when case when t1.a<>t1.d then d*t1.a*11-e-(+11+d)-e else (select case  -count(distinct t1.e) when cast(avg(b) AS integer) then count(distinct t1.d) else cast(avg(13) AS integer) end*cast(avg(19) AS integer) from t1) end<>case e when e then t1.e else (t1.f) end or not exists(select 1 from t1 where 19=f) and  -t1.d>t1.e then t1.e+e*e when 11=t1.c then e else c end FROM t1 WHERE NOT (~c>(case when t1.e<=e then case when case when 17+f in (d,t1.d | t1.c,t1.b) and 13<>19 or not t1.c<f then coalesce((select max(b) from t1 where c not between b and t1.c),c)+(17) when d<=t1.c then t1.b else t1.c end-b not in (a,f,11) then c else 17 end else f end))}
} {250500}
do_test randexpr-2.977 {
  db eval {SELECT case when (13 in (select ~t1.c from t1 union select case when t1.a in (select t1.f-t1.e | t1.c+19 from t1 union select coalesce((select max(13) from t1 where e in (select ~19-(select case count(*)-cast(avg(c) AS integer) when cast(avg(t1.f) AS integer) then  -max(d) else min(t1.d) end | ( -cast(avg(t1.a) AS integer)) from t1)-b*d-coalesce((select max(f) from t1 where not t1.c=c),b) from t1 union select 13 from t1)),a) from t1) then t1.c else t1.b end from t1)) then (abs(c)/abs(19)) else c end FROM t1 WHERE coalesce((select  -case (select count(*) from t1) when d*+b then a else d end from t1 where b not in (11*case t1.e when case +coalesce((select b+19*+case t1.c when t1.a then t1.b else t1.f end*f*11 from t1 where t1.a=t1.f),c) when t1.e then 17 else d end then t1.f else t1.b end,f,d)),t1.d) in (13,e, -b)}
} {}
do_test randexpr-2.978 {
  db eval {SELECT case when (13 in (select ~t1.c from t1 union select case when t1.a in (select t1.f-t1.e | t1.c+19 from t1 union select coalesce((select max(13) from t1 where e in (select ~19-(select case count(*)-cast(avg(c) AS integer) when cast(avg(t1.f) AS integer) then  -max(d) else min(t1.d) end | ( -cast(avg(t1.a) AS integer)) from t1)-b*d-coalesce((select max(f) from t1 where not t1.c=c),b) from t1 union select 13 from t1)),a) from t1) then t1.c else t1.b end from t1)) then (abs(c)/abs(19)) else c end FROM t1 WHERE NOT (coalesce((select  -case (select count(*) from t1) when d*+b then a else d end from t1 where b not in (11*case t1.e when case +coalesce((select b+19*+case t1.c when t1.a then t1.b else t1.f end*f*11 from t1 where t1.a=t1.f),c) when t1.e then 17 else d end then t1.f else t1.b end,f,d)),t1.d) in (13,e, -b))}
} {300}
do_test randexpr-2.979 {
  db eval {SELECT case when (13 in (select ~t1.c from t1 union select case when t1.a in (select t1.f-t1.e & t1.c+19 from t1 union select coalesce((select max(13) from t1 where e in (select ~19-(select case count(*)-cast(avg(c) AS integer) when cast(avg(t1.f) AS integer) then  -max(d) else min(t1.d) end & ( -cast(avg(t1.a) AS integer)) from t1)-b*d-coalesce((select max(f) from t1 where not t1.c=c),b) from t1 union select 13 from t1)),a) from t1) then t1.c else t1.b end from t1)) then (abs(c)/abs(19)) else c end FROM t1 WHERE NOT (coalesce((select  -case (select count(*) from t1) when d*+b then a else d end from t1 where b not in (11*case t1.e when case +coalesce((select b+19*+case t1.c when t1.a then t1.b else t1.f end*f*11 from t1 where t1.a=t1.f),c) when t1.e then 17 else d end then t1.f else t1.b end,f,d)),t1.d) in (13,e, -b))}
} {300}
do_test randexpr-2.980 {
  db eval {SELECT ~case when exists(select 1 from t1 where ((coalesce((select d from t1 where t1.e-f | +t1.d between t1.c and t1.a or exists(select 1 from t1 where 19 in (11,11,13)) and 17 in (select case min(d) when count(*) then (min(13)) else  -(cast(avg( -c) AS integer)) end*count(distinct 19) from t1 union select count(distinct e) from t1)),f) | c*b<= -b or not not t1.c<13 or (t1.f)>=t1.f))) and t1.c not in (17,b,e) then a else (select count(distinct t1.d) from t1) end FROM t1 WHERE (select (count(*)) from t1) between 11 and t1.d}
} {}
do_test randexpr-2.981 {
  db eval {SELECT ~case when exists(select 1 from t1 where ((coalesce((select d from t1 where t1.e-f | +t1.d between t1.c and t1.a or exists(select 1 from t1 where 19 in (11,11,13)) and 17 in (select case min(d) when count(*) then (min(13)) else  -(cast(avg( -c) AS integer)) end*count(distinct 19) from t1 union select count(distinct e) from t1)),f) | c*b<= -b or not not t1.c<13 or (t1.f)>=t1.f))) and t1.c not in (17,b,e) then a else (select count(distinct t1.d) from t1) end FROM t1 WHERE NOT ((select (count(*)) from t1) between 11 and t1.d)}
} {-101}
do_test randexpr-2.982 {
  db eval {SELECT ~case when exists(select 1 from t1 where ((coalesce((select d from t1 where t1.e-f & +t1.d between t1.c and t1.a or exists(select 1 from t1 where 19 in (11,11,13)) and 17 in (select case min(d) when count(*) then (min(13)) else  -(cast(avg( -c) AS integer)) end*count(distinct 19) from t1 union select count(distinct e) from t1)),f) & c*b<= -b or not not t1.c<13 or (t1.f)>=t1.f))) and t1.c not in (17,b,e) then a else (select count(distinct t1.d) from t1) end FROM t1 WHERE NOT ((select (count(*)) from t1) between 11 and t1.d)}
} {-101}
do_test randexpr-2.983 {
  db eval {SELECT coalesce((select max(b) from t1 where not not c*t1.e>=19 or case when 17<=t1.b and case when 13 not between d and  -f then case e when 11 then case when e in (select ( -d) from t1 union select e from t1) and 19<=(a) then t1.a else (19) end else f end else t1.a end+t1.a<19 then ~d when e in (a,11, -b) then b else e end not between f and 13),a) FROM t1 WHERE t1.a>=+a}
} {200}
do_test randexpr-2.984 {
  db eval {SELECT coalesce((select max(b) from t1 where not not c*t1.e>=19 or case when 17<=t1.b and case when 13 not between d and  -f then case e when 11 then case when e in (select ( -d) from t1 union select e from t1) and 19<=(a) then t1.a else (19) end else f end else t1.a end+t1.a<19 then ~d when e in (a,11, -b) then b else e end not between f and 13),a) FROM t1 WHERE NOT (t1.a>=+a)}
} {}
do_test randexpr-2.985 {
  db eval {SELECT case when case when 11 between a+a+t1.b and b then c*e-t1.c*t1.a when +b<= -t1.c-t1.e-19*t1.b+c*t1.b then e else d end-(11)-e<d then 11 when 13=t1.e then a else 13 end+c-d FROM t1 WHERE ~coalesce((select max((select count(*) from t1)+t1.f) from t1 where 17 in (~t1.a,d,13)), -(select max(13) from t1) | coalesce((select c from t1 where t1.e* -coalesce((select 17 from t1 where (abs(t1.a+t1.d)/abs(t1.f))*t1.e | 17 | 11 not in ((t1.d),c,t1.c)),13)*13 in (11,t1.e,a)),19)) in (13,13,c)}
} {}
do_test randexpr-2.986 {
  db eval {SELECT case when case when 11 between a+a+t1.b and b then c*e-t1.c*t1.a when +b<= -t1.c-t1.e-19*t1.b+c*t1.b then e else d end-(11)-e<d then 11 when 13=t1.e then a else 13 end+c-d FROM t1 WHERE NOT (~coalesce((select max((select count(*) from t1)+t1.f) from t1 where 17 in (~t1.a,d,13)), -(select max(13) from t1) | coalesce((select c from t1 where t1.e* -coalesce((select 17 from t1 where (abs(t1.a+t1.d)/abs(t1.f))*t1.e | 17 | 11 not in ((t1.d),c,t1.c)),13)*13 in (11,t1.e,a)),19)) in (13,13,c))}
} {-89}
do_test randexpr-2.987 {
  db eval {SELECT c-case 17 when c+b-t1.a-a*coalesce((select max(t1.c) from t1 where t1.b- -(abs(13)/abs(t1.e)) in (case t1.f when f then coalesce((select max(coalesce((select 13 from t1 where exists(select 1 from t1 where f not between e and c)),e)) from t1 where d not between t1.a and 13),d)-b else a end, -13,(t1.f)) and 13 between e and 17),a) | a then t1.d else e end+ -t1.e FROM t1 WHERE not exists(select 1 from t1 where coalesce((select  -+t1.c | case when a in (select case max(+b) when ~count(*) then count(*) else (abs((max(f)))) end from t1 union select  -max(e) from t1) then case when (t1.d>=11) or t1.c not between t1.d and  - -11 then t1.a when 11 not between  -t1.e and t1.a then 11 else t1.b end when (d not in (a,c,19)) then f else c end*17 from t1 where  -11<=t1.c),t1.c)+f not in (t1.f, -d,19))}
} {}
do_test randexpr-2.988 {
  db eval {SELECT c-case 17 when c+b-t1.a-a*coalesce((select max(t1.c) from t1 where t1.b- -(abs(13)/abs(t1.e)) in (case t1.f when f then coalesce((select max(coalesce((select 13 from t1 where exists(select 1 from t1 where f not between e and c)),e)) from t1 where d not between t1.a and 13),d)-b else a end, -13,(t1.f)) and 13 between e and 17),a) | a then t1.d else e end+ -t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select  -+t1.c | case when a in (select case max(+b) when ~count(*) then count(*) else (abs((max(f)))) end from t1 union select  -max(e) from t1) then case when (t1.d>=11) or t1.c not between t1.d and  - -11 then t1.a when 11 not between  -t1.e and t1.a then 11 else t1.b end when (d not in (a,c,19)) then f else c end*17 from t1 where  -11<=t1.c),t1.c)+f not in (t1.f, -d,19)))}
} {-700}
do_test randexpr-2.989 {
  db eval {SELECT c-case 17 when c+b-t1.a-a*coalesce((select max(t1.c) from t1 where t1.b- -(abs(13)/abs(t1.e)) in (case t1.f when f then coalesce((select max(coalesce((select 13 from t1 where exists(select 1 from t1 where f not between e and c)),e)) from t1 where d not between t1.a and 13),d)-b else a end, -13,(t1.f)) and 13 between e and 17),a) & a then t1.d else e end+ -t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select  -+t1.c | case when a in (select case max(+b) when ~count(*) then count(*) else (abs((max(f)))) end from t1 union select  -max(e) from t1) then case when (t1.d>=11) or t1.c not between t1.d and  - -11 then t1.a when 11 not between  -t1.e and t1.a then 11 else t1.b end when (d not in (a,c,19)) then f else c end*17 from t1 where  -11<=t1.c),t1.c)+f not in (t1.f, -d,19)))}
} {-700}
do_test randexpr-2.990 {
  db eval {SELECT (select ( -count(distinct case case a when e then c*case when e<=t1.d+b then a when (abs(t1.f)/abs(case when b-coalesce((select max(t1.f-t1.b) from t1 where not exists(select 1 from t1 where 17 in (b,13,(b)) or b in (d,c,t1.e))),t1.b) not in (d,((c)),t1.b) then  -19 when c between a and 13 then 19 else t1.f end))=13 then f else 13 end else 17 end when 13 then t1.f else t1.b end-t1.c)) from t1) FROM t1 WHERE coalesce((select max(t1.d) from t1 where t1.c<>t1.c-13),t1.a)>=d or b*coalesce((select max((d)) from t1 where c not between +coalesce((select max(13) from t1 where e between  -(abs(( -coalesce((select max(case f when t1.f then e else  -t1.c end) from t1 where 11>e and t1.b<t1.e),t1.c)))/abs(b)) and d),a) and t1.e),t1.b)* -19 not between (17) and t1.f and (t1.e<=a)}
} {-1}
do_test randexpr-2.991 {
  db eval {SELECT (select ( -count(distinct case case a when e then c*case when e<=t1.d+b then a when (abs(t1.f)/abs(case when b-coalesce((select max(t1.f-t1.b) from t1 where not exists(select 1 from t1 where 17 in (b,13,(b)) or b in (d,c,t1.e))),t1.b) not in (d,((c)),t1.b) then  -19 when c between a and 13 then 19 else t1.f end))=13 then f else 13 end else 17 end when 13 then t1.f else t1.b end-t1.c)) from t1) FROM t1 WHERE NOT (coalesce((select max(t1.d) from t1 where t1.c<>t1.c-13),t1.a)>=d or b*coalesce((select max((d)) from t1 where c not between +coalesce((select max(13) from t1 where e between  -(abs(( -coalesce((select max(case f when t1.f then e else  -t1.c end) from t1 where 11>e and t1.b<t1.e),t1.c)))/abs(b)) and d),a) and t1.e),t1.b)* -19 not between (17) and t1.f and (t1.e<=a))}
} {}
do_test randexpr-2.992 {
  db eval {SELECT case when (11=(t1.b)) then t1.c-coalesce((select case when t1.f*c-b<>b then t1.a else e end | f from t1 where 13 in (select abs(~max((17))) from t1 union select cast(avg(t1.b) AS integer)-min(19) from t1)), -t1.a) when c<d or (e=17 or t1.f in (select min(t1.a) from t1 union select max(a) from t1)) then e else d end*b+t1.e FROM t1 WHERE (select case case case cast(avg(+(select abs(+count(distinct t1.d)-count(distinct t1.b) | max(17)) |  -cast(avg(f) AS integer)*count(*) from t1)) AS integer) when  -count(*)* - -max(b) then (count(distinct 19)) else max(t1.e) end when count(*) then count(*) else cast(avg(t1.c) AS integer) end when max(c) then (cast(avg(t1.c) AS integer)) else min(t1.f) end-max(17) | min((11)) from t1)<>+case ~e+~t1.d | 13 when case when t1.c<=t1.c or (11)=t1.a then 11 when  -11 in (17,11, -d) then t1.a else t1.b end then 19 else 13 end* -t1.c}
} {100500}
do_test randexpr-2.993 {
  db eval {SELECT case when (11=(t1.b)) then t1.c-coalesce((select case when t1.f*c-b<>b then t1.a else e end | f from t1 where 13 in (select abs(~max((17))) from t1 union select cast(avg(t1.b) AS integer)-min(19) from t1)), -t1.a) when c<d or (e=17 or t1.f in (select min(t1.a) from t1 union select max(a) from t1)) then e else d end*b+t1.e FROM t1 WHERE NOT ((select case case case cast(avg(+(select abs(+count(distinct t1.d)-count(distinct t1.b) | max(17)) |  -cast(avg(f) AS integer)*count(*) from t1)) AS integer) when  -count(*)* - -max(b) then (count(distinct 19)) else max(t1.e) end when count(*) then count(*) else cast(avg(t1.c) AS integer) end when max(c) then (cast(avg(t1.c) AS integer)) else min(t1.f) end-max(17) | min((11)) from t1)<>+case ~e+~t1.d | 13 when case when t1.c<=t1.c or (11)=t1.a then 11 when  -11 in (17,11, -d) then t1.a else t1.b end then 19 else 13 end* -t1.c)}
} {}
do_test randexpr-2.994 {
  db eval {SELECT case when (11=(t1.b)) then t1.c-coalesce((select case when t1.f*c-b<>b then t1.a else e end & f from t1 where 13 in (select abs(~max((17))) from t1 union select cast(avg(t1.b) AS integer)-min(19) from t1)), -t1.a) when c<d or (e=17 or t1.f in (select min(t1.a) from t1 union select max(a) from t1)) then e else d end*b+t1.e FROM t1 WHERE (select case case case cast(avg(+(select abs(+count(distinct t1.d)-count(distinct t1.b) | max(17)) |  -cast(avg(f) AS integer)*count(*) from t1)) AS integer) when  -count(*)* - -max(b) then (count(distinct 19)) else max(t1.e) end when count(*) then count(*) else cast(avg(t1.c) AS integer) end when max(c) then (cast(avg(t1.c) AS integer)) else min(t1.f) end-max(17) | min((11)) from t1)<>+case ~e+~t1.d | 13 when case when t1.c<=t1.c or (11)=t1.a then 11 when  -11 in (17,11, -d) then t1.a else t1.b end then 19 else 13 end* -t1.c}
} {100500}
do_test randexpr-2.995 {
  db eval {SELECT case when (f in (select count(distinct 17) from t1 union select count(distinct t1.b) from t1)) then d when e in (coalesce((select max(e+e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where 11-t1.a in (select case  -max(11)-max(b) when min(t1.f) then count(distinct f) else count(distinct t1.c) end | count(*) from t1 union select min( -a) from t1)) and t1.e in (select count(distinct  -t1.e) from t1 union select count(distinct a) from t1) and d not in (b,f,t1.d)) and a between t1.c and t1.e),f),c,11) then c else t1.f end | a FROM t1 WHERE coalesce((select a from t1 where t1.a | (17-coalesce((select t1.b from t1 where ~t1.f | t1.e=d and a<=19+(select (cast(avg(c) AS integer)) from t1)),t1.c))+t1.e*t1.d+t1.c not between t1.d and 19), -t1.d) in (select (count(*)) from t1 union select (++~min(c)*+max(t1.a)+cast(avg( -(t1.e)) AS integer)) from t1)}
} {}
do_test randexpr-2.996 {
  db eval {SELECT case when (f in (select count(distinct 17) from t1 union select count(distinct t1.b) from t1)) then d when e in (coalesce((select max(e+e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where 11-t1.a in (select case  -max(11)-max(b) when min(t1.f) then count(distinct f) else count(distinct t1.c) end | count(*) from t1 union select min( -a) from t1)) and t1.e in (select count(distinct  -t1.e) from t1 union select count(distinct a) from t1) and d not in (b,f,t1.d)) and a between t1.c and t1.e),f),c,11) then c else t1.f end | a FROM t1 WHERE NOT (coalesce((select a from t1 where t1.a | (17-coalesce((select t1.b from t1 where ~t1.f | t1.e=d and a<=19+(select (cast(avg(c) AS integer)) from t1)),t1.c))+t1.e*t1.d+t1.c not between t1.d and 19), -t1.d) in (select (count(*)) from t1 union select (++~min(c)*+max(t1.a)+cast(avg( -(t1.e)) AS integer)) from t1))}
} {636}
do_test randexpr-2.997 {
  db eval {SELECT case when (f in (select count(distinct 17) from t1 union select count(distinct t1.b) from t1)) then d when e in (coalesce((select max(e+e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where 11-t1.a in (select case  -max(11)-max(b) when min(t1.f) then count(distinct f) else count(distinct t1.c) end & count(*) from t1 union select min( -a) from t1)) and t1.e in (select count(distinct  -t1.e) from t1 union select count(distinct a) from t1) and d not in (b,f,t1.d)) and a between t1.c and t1.e),f),c,11) then c else t1.f end & a FROM t1 WHERE NOT (coalesce((select a from t1 where t1.a | (17-coalesce((select t1.b from t1 where ~t1.f | t1.e=d and a<=19+(select (cast(avg(c) AS integer)) from t1)),t1.c))+t1.e*t1.d+t1.c not between t1.d and 19), -t1.d) in (select (count(*)) from t1 union select (++~min(c)*+max(t1.a)+cast(avg( -(t1.e)) AS integer)) from t1))}
} {64}
do_test randexpr-2.998 {
  db eval {SELECT case when coalesce((select t1.b from t1 where a not in (19,coalesce((select max(t1.f) from t1 where (select count(distinct t1.b) from t1) in (t1.e,t1.f*13-11,d)),(t1.f))-17*c,c) or t1.c<=11),19)>13 and f not in (t1.a,11,t1.d) then (((e))) when f=11 or f not in (a,19,17) then 13 else e end FROM t1 WHERE c in (select min(t1.a*a+(select count(distinct t1.b+(t1.a)- - -c) from t1)-t1.e) from t1 union select count(*) from t1) and c in (select min(t1.d) from t1 union select cast(avg(d) AS integer)+abs(case count(*) when count(distinct 11) then  -count(distinct 19) else count(distinct (t1.b)) end) | cast(avg((t1.c)) AS integer)+count(*) from t1) and e=13 and t1.d>c or 13 not in (17,(t1.f),t1.a) or (11)=t1.b and t1.e>=a or 11<=t1.b or d<=17}
} {500}
do_test randexpr-2.999 {
  db eval {SELECT case when coalesce((select t1.b from t1 where a not in (19,coalesce((select max(t1.f) from t1 where (select count(distinct t1.b) from t1) in (t1.e,t1.f*13-11,d)),(t1.f))-17*c,c) or t1.c<=11),19)>13 and f not in (t1.a,11,t1.d) then (((e))) when f=11 or f not in (a,19,17) then 13 else e end FROM t1 WHERE NOT (c in (select min(t1.a*a+(select count(distinct t1.b+(t1.a)- - -c) from t1)-t1.e) from t1 union select count(*) from t1) and c in (select min(t1.d) from t1 union select cast(avg(d) AS integer)+abs(case count(*) when count(distinct 11) then  -count(distinct 19) else count(distinct (t1.b)) end) | cast(avg((t1.c)) AS integer)+count(*) from t1) and e=13 and t1.d>c or 13 not in (17,(t1.f),t1.a) or (11)=t1.b and t1.e>=a or 11<=t1.b or d<=17)}
} {}
do_test randexpr-2.1000 {
  db eval {SELECT case when t1.d not between (abs(d)/abs(t1.e))+t1.f*t1.a*a and 17*e then case when 11 between a and coalesce((select max(t1.b) from t1 where (case when t1.e+(t1.b) not in (t1.e,d,f) or 13<>17 then 17 when a>e then 11 else a end in (select count(*) from t1 union select min(a) from t1))),17) then 19 when  -11 in (select t1.c from t1 union select  -19 from t1) or  - - -t1.e=t1.a then 17 else t1.a end else t1.e end FROM t1 WHERE (select +count(distinct f) from t1)-t1.f between t1.f and c}
} {}
do_test randexpr-2.1001 {
  db eval {SELECT case when t1.d not between (abs(d)/abs(t1.e))+t1.f*t1.a*a and 17*e then case when 11 between a and coalesce((select max(t1.b) from t1 where (case when t1.e+(t1.b) not in (t1.e,d,f) or 13<>17 then 17 when a>e then 11 else a end in (select count(*) from t1 union select min(a) from t1))),17) then 19 when  -11 in (select t1.c from t1 union select  -19 from t1) or  - - -t1.e=t1.a then 17 else t1.a end else t1.e end FROM t1 WHERE NOT ((select +count(distinct f) from t1)-t1.f between t1.f and c)}
} {100}
do_test randexpr-2.1002 {
  db eval {SELECT case when (case when e between t1.b and c+(select cast(avg( -case c when a then t1.f+c else 17 end) AS integer) from t1) then t1.e when not 19>=t1.a then 17 else d end in (select cast(avg(13) AS integer)-max(11) | +count(*) from t1 union select case (cast(avg(d) AS integer)) when min(a) then abs( -max(19)) else count(*) end from t1)) then (t1.a) else c end |  -e*a FROM t1 WHERE f*t1.d*(abs(case d when coalesce((select max((abs(t1.e)/abs(t1.f))) from t1 where ((e between (b) and 13) or t1.d=(c)) and t1.f between 17 and t1.e),a) then  -b else  -e end+ -t1.e)/abs(t1.c))+f<=17 or t1.f not between f and t1.e or (t1.c in (select 17 from t1 union select f from t1)) or exists(select 1 from t1 where (a not in (d,t1.a,t1.e) and t1.a in (t1.a,c,19))) and f not in (t1.d,t1.c,c)}
} {-49732}
do_test randexpr-2.1003 {
  db eval {SELECT case when (case when e between t1.b and c+(select cast(avg( -case c when a then t1.f+c else 17 end) AS integer) from t1) then t1.e when not 19>=t1.a then 17 else d end in (select cast(avg(13) AS integer)-max(11) | +count(*) from t1 union select case (cast(avg(d) AS integer)) when min(a) then abs( -max(19)) else count(*) end from t1)) then (t1.a) else c end |  -e*a FROM t1 WHERE NOT (f*t1.d*(abs(case d when coalesce((select max((abs(t1.e)/abs(t1.f))) from t1 where ((e between (b) and 13) or t1.d=(c)) and t1.f between 17 and t1.e),a) then  -b else  -e end+ -t1.e)/abs(t1.c))+f<=17 or t1.f not between f and t1.e or (t1.c in (select 17 from t1 union select f from t1)) or exists(select 1 from t1 where (a not in (d,t1.a,t1.e) and t1.a in (t1.a,c,19))) and f not in (t1.d,t1.c,c))}
} {}
do_test randexpr-2.1004 {
  db eval {SELECT case when (case when e between t1.b and c+(select cast(avg( -case c when a then t1.f+c else 17 end) AS integer) from t1) then t1.e when not 19>=t1.a then 17 else d end in (select cast(avg(13) AS integer)-max(11) & +count(*) from t1 union select case (cast(avg(d) AS integer)) when min(a) then abs( -max(19)) else count(*) end from t1)) then (t1.a) else c end &  -e*a FROM t1 WHERE f*t1.d*(abs(case d when coalesce((select max((abs(t1.e)/abs(t1.f))) from t1 where ((e between (b) and 13) or t1.d=(c)) and t1.f between 17 and t1.e),a) then  -b else  -e end+ -t1.e)/abs(t1.c))+f<=17 or t1.f not between f and t1.e or (t1.c in (select 17 from t1 union select f from t1)) or exists(select 1 from t1 where (a not in (d,t1.a,t1.e) and t1.a in (t1.a,c,19))) and f not in (t1.d,t1.c,c)}
} {32}
do_test randexpr-2.1005 {
  db eval {SELECT  -case coalesce((select case when f<>t1.d | c-(e)*t1.b and 17 in (select t1.b from t1 union select  -(t1.c) from t1) or t1.e>=11 and t1.f not between b and f or e not in (11,19,t1.e) and t1.c<=a then coalesce((select max(t1.f+t1.f) from t1 where  -t1.a<t1.f),t1.c) when e not in (t1.c,t1.d,t1.e) then t1.f else t1.e end-d from t1 where e>=13),e) when t1.e then c else t1.a end FROM t1 WHERE coalesce((select t1.f from t1 where (t1.e>=case (abs(11)/abs(t1.a)) when 11 then case t1.c when t1.a then t1.e else a end else t1.f end+t1.d) and (exists(select 1 from t1 where t1.b not in (t1.b,a,19))) or t1.a>=11),(select abs((~cast(avg(t1.b) AS integer)-~cast(avg((t1.b)) AS integer)* -count(*))+ -count(distinct t1.b)) from t1)*19)<=f and b in (select count(*) from t1 union select  -min(d) from t1)}
} {}
do_test randexpr-2.1006 {
  db eval {SELECT  -case coalesce((select case when f<>t1.d | c-(e)*t1.b and 17 in (select t1.b from t1 union select  -(t1.c) from t1) or t1.e>=11 and t1.f not between b and f or e not in (11,19,t1.e) and t1.c<=a then coalesce((select max(t1.f+t1.f) from t1 where  -t1.a<t1.f),t1.c) when e not in (t1.c,t1.d,t1.e) then t1.f else t1.e end-d from t1 where e>=13),e) when t1.e then c else t1.a end FROM t1 WHERE NOT (coalesce((select t1.f from t1 where (t1.e>=case (abs(11)/abs(t1.a)) when 11 then case t1.c when t1.a then t1.e else a end else t1.f end+t1.d) and (exists(select 1 from t1 where t1.b not in (t1.b,a,19))) or t1.a>=11),(select abs((~cast(avg(t1.b) AS integer)-~cast(avg((t1.b)) AS integer)* -count(*))+ -count(distinct t1.b)) from t1)*19)<=f and b in (select count(*) from t1 union select  -min(d) from t1))}
} {-100}
do_test randexpr-2.1007 {
  db eval {SELECT  -case coalesce((select case when f<>t1.d & c-(e)*t1.b and 17 in (select t1.b from t1 union select  -(t1.c) from t1) or t1.e>=11 and t1.f not between b and f or e not in (11,19,t1.e) and t1.c<=a then coalesce((select max(t1.f+t1.f) from t1 where  -t1.a<t1.f),t1.c) when e not in (t1.c,t1.d,t1.e) then t1.f else t1.e end-d from t1 where e>=13),e) when t1.e then c else t1.a end FROM t1 WHERE NOT (coalesce((select t1.f from t1 where (t1.e>=case (abs(11)/abs(t1.a)) when 11 then case t1.c when t1.a then t1.e else a end else t1.f end+t1.d) and (exists(select 1 from t1 where t1.b not in (t1.b,a,19))) or t1.a>=11),(select abs((~cast(avg(t1.b) AS integer)-~cast(avg((t1.b)) AS integer)* -count(*))+ -count(distinct t1.b)) from t1)*19)<=f and b in (select count(*) from t1 union select  -min(d) from t1))}
} {-100}
do_test randexpr-2.1008 {
  db eval {SELECT case when exists(select 1 from t1 where exists(select 1 from t1 where  -case when t1.d<=coalesce((select t1.d | (f)*t1.a from t1 where not exists(select 1 from t1 where t1.f not in ((e),t1.e,13) or t1.a not between a and  -t1.d or (f) not between f and 13)),19) then e when (t1.f)<19 or e<=d then b else d end in (select case ~ -(cast(avg(b) AS integer)*cast(avg(t1.b) AS integer)*min(t1.f)) | count(*) when min(t1.c) then ( - -count(distinct  -d)) else count(*) end from t1 union select cast(avg(f) AS integer) from t1) and b<a)) then t1.b else t1.d end FROM t1 WHERE case case when case when not d<t1.a+t1.d+t1.c then ~f when ((not exists(select 1 from t1 where 19 in ( -(t1.f),17, -e)))) or f not between a and a then t1.f else 19 end in (select min(e)-~ -count(*)*(count(*))+count(*)*min(e) from t1 union select  -( -( -count(*))) from t1) then 11 when e<=f then 17 else 13 end+(19)+f when c then b else c end<>t1.b or 19<>t1.f}
} {400}
do_test randexpr-2.1009 {
  db eval {SELECT case when exists(select 1 from t1 where exists(select 1 from t1 where  -case when t1.d<=coalesce((select t1.d | (f)*t1.a from t1 where not exists(select 1 from t1 where t1.f not in ((e),t1.e,13) or t1.a not between a and  -t1.d or (f) not between f and 13)),19) then e when (t1.f)<19 or e<=d then b else d end in (select case ~ -(cast(avg(b) AS integer)*cast(avg(t1.b) AS integer)*min(t1.f)) | count(*) when min(t1.c) then ( - -count(distinct  -d)) else count(*) end from t1 union select cast(avg(f) AS integer) from t1) and b<a)) then t1.b else t1.d end FROM t1 WHERE NOT (case case when case when not d<t1.a+t1.d+t1.c then ~f when ((not exists(select 1 from t1 where 19 in ( -(t1.f),17, -e)))) or f not between a and a then t1.f else 19 end in (select min(e)-~ -count(*)*(count(*))+count(*)*min(e) from t1 union select  -( -( -count(*))) from t1) then 11 when e<=f then 17 else 13 end+(19)+f when c then b else c end<>t1.b or 19<>t1.f)}
} {}
do_test randexpr-2.1010 {
  db eval {SELECT case when exists(select 1 from t1 where exists(select 1 from t1 where  -case when t1.d<=coalesce((select t1.d & (f)*t1.a from t1 where not exists(select 1 from t1 where t1.f not in ((e),t1.e,13) or t1.a not between a and  -t1.d or (f) not between f and 13)),19) then e when (t1.f)<19 or e<=d then b else d end in (select case ~ -(cast(avg(b) AS integer)*cast(avg(t1.b) AS integer)*min(t1.f)) & count(*) when min(t1.c) then ( - -count(distinct  -d)) else count(*) end from t1 union select cast(avg(f) AS integer) from t1) and b<a)) then t1.b else t1.d end FROM t1 WHERE case case when case when not d<t1.a+t1.d+t1.c then ~f when ((not exists(select 1 from t1 where 19 in ( -(t1.f),17, -e)))) or f not between a and a then t1.f else 19 end in (select min(e)-~ -count(*)*(count(*))+count(*)*min(e) from t1 union select  -( -( -count(*))) from t1) then 11 when e<=f then 17 else 13 end+(19)+f when c then b else c end<>t1.b or 19<>t1.f}
} {400}
do_test randexpr-2.1011 {
  db eval {SELECT case when ~+11<>f then case e when 11 then coalesce((select case d when t1.e-coalesce((select a+t1.c from t1 where (d) in (select +min(t1.f)+count(*) from t1 union select count(distinct t1.e) from t1)),t1.f) then t1.c else d end from t1 where t1.f in (select t1.f from t1 union select b from t1) or (t1.a not in ( -a,t1.a,t1.b))),t1.c) else t1.f end-t1.f when not exists(select 1 from t1 where b between f and t1.a) then t1.c else t1.f end FROM t1 WHERE t1.a<=coalesce((select max(b) from t1 where coalesce((select t1.c*case when coalesce((select max((select count(*) from t1)) from t1 where not not exists(select 1 from t1 where case t1.b | a when t1.f then c else 11 end<>f and 13>=13 and f between t1.b and c)),13)=case e when a then 19 else d end then t1.b when t1.a not in (a,t1.b,a) then e else b end-d from t1 where t1.f between t1.d and t1.e),e)>t1.f),17)+t1.f}
} {0}
do_test randexpr-2.1012 {
  db eval {SELECT case when ~+11<>f then case e when 11 then coalesce((select case d when t1.e-coalesce((select a+t1.c from t1 where (d) in (select +min(t1.f)+count(*) from t1 union select count(distinct t1.e) from t1)),t1.f) then t1.c else d end from t1 where t1.f in (select t1.f from t1 union select b from t1) or (t1.a not in ( -a,t1.a,t1.b))),t1.c) else t1.f end-t1.f when not exists(select 1 from t1 where b between f and t1.a) then t1.c else t1.f end FROM t1 WHERE NOT (t1.a<=coalesce((select max(b) from t1 where coalesce((select t1.c*case when coalesce((select max((select count(*) from t1)) from t1 where not not exists(select 1 from t1 where case t1.b | a when t1.f then c else 11 end<>f and 13>=13 and f between t1.b and c)),13)=case e when a then 19 else d end then t1.b when t1.a not in (a,t1.b,a) then e else b end-d from t1 where t1.f between t1.d and t1.e),e)>t1.f),17)+t1.f)}
} {}
do_test randexpr-2.1013 {
  db eval {SELECT (abs(d)/abs(t1.f++(select cast(avg(coalesce((select max(b) from t1 where case when t1.a*+(abs( -t1.b)/abs((select cast(avg(13) AS integer) from t1)))<=(t1.c-t1.d- -t1.c) then case d when 17 then  -t1.d else f end when t1.b between t1.b and t1.b then a else t1.d end in (select count(*) from t1 union select abs(cast(avg(13) AS integer)) | min(t1.c) from t1) or ((13))>=b),17)) AS integer) from t1)+13)) FROM t1 WHERE coalesce((select +t1.a from t1 where not exists(select 1 from t1 where (select cast(avg(13) AS integer) from t1)<=(abs( -11)/abs(t1.f))*coalesce((select t1.e from t1 where not t1.f in (select max(+b-t1.d) from t1 union select + -(abs(cast(avg((t1.b)) AS integer)))-+count(*)-(min(13)) from t1)),d+t1.d*t1.d) | (17)-t1.b)),f) in (select max(t1.c) from t1 union select count(distinct f) from t1)}
} {}
do_test randexpr-2.1014 {
  db eval {SELECT (abs(d)/abs(t1.f++(select cast(avg(coalesce((select max(b) from t1 where case when t1.a*+(abs( -t1.b)/abs((select cast(avg(13) AS integer) from t1)))<=(t1.c-t1.d- -t1.c) then case d when 17 then  -t1.d else f end when t1.b between t1.b and t1.b then a else t1.d end in (select count(*) from t1 union select abs(cast(avg(13) AS integer)) | min(t1.c) from t1) or ((13))>=b),17)) AS integer) from t1)+13)) FROM t1 WHERE NOT (coalesce((select +t1.a from t1 where not exists(select 1 from t1 where (select cast(avg(13) AS integer) from t1)<=(abs( -11)/abs(t1.f))*coalesce((select t1.e from t1 where not t1.f in (select max(+b-t1.d) from t1 union select + -(abs(cast(avg((t1.b)) AS integer)))-+count(*)-(min(13)) from t1)),d+t1.d*t1.d) | (17)-t1.b)),f) in (select max(t1.c) from t1 union select count(distinct f) from t1))}
} {0}
do_test randexpr-2.1015 {
  db eval {SELECT (abs(d)/abs(t1.f++(select cast(avg(coalesce((select max(b) from t1 where case when t1.a*+(abs( -t1.b)/abs((select cast(avg(13) AS integer) from t1)))<=(t1.c-t1.d- -t1.c) then case d when 17 then  -t1.d else f end when t1.b between t1.b and t1.b then a else t1.d end in (select count(*) from t1 union select abs(cast(avg(13) AS integer)) & min(t1.c) from t1) or ((13))>=b),17)) AS integer) from t1)+13)) FROM t1 WHERE NOT (coalesce((select +t1.a from t1 where not exists(select 1 from t1 where (select cast(avg(13) AS integer) from t1)<=(abs( -11)/abs(t1.f))*coalesce((select t1.e from t1 where not t1.f in (select max(+b-t1.d) from t1 union select + -(abs(cast(avg((t1.b)) AS integer)))-+count(*)-(min(13)) from t1)),d+t1.d*t1.d) | (17)-t1.b)),f) in (select max(t1.c) from t1 union select count(distinct f) from t1))}
} {0}
do_test randexpr-2.1016 {
  db eval {SELECT case t1.a when (select ~max(coalesce((select (t1.b-a*+t1.c-t1.e) from t1 where not 11*t1.f++t1.f-t1.a*f*+t1.e*t1.b>17 and 19+e not in (t1.c,t1.b,a)),19)) from t1) then 19*11 else d end | (17) | t1.d FROM t1 WHERE exists(select 1 from t1 where coalesce((select max(13) from t1 where t1.e not in (d,13-19,17) or e*19=d or ((t1.a< -t1.a or 11- -t1.d-case when 13<( -t1.e) then a else e end*t1.b+t1.e in (select t1.d from t1 union select t1.e from t1) and 19<>d))),b)+11*11=t1.e)}
} {}
do_test randexpr-2.1017 {
  db eval {SELECT case t1.a when (select ~max(coalesce((select (t1.b-a*+t1.c-t1.e) from t1 where not 11*t1.f++t1.f-t1.a*f*+t1.e*t1.b>17 and 19+e not in (t1.c,t1.b,a)),19)) from t1) then 19*11 else d end | (17) | t1.d FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(13) from t1 where t1.e not in (d,13-19,17) or e*19=d or ((t1.a< -t1.a or 11- -t1.d-case when 13<( -t1.e) then a else e end*t1.b+t1.e in (select t1.d from t1 union select t1.e from t1) and 19<>d))),b)+11*11=t1.e))}
} {401}
do_test randexpr-2.1018 {
  db eval {SELECT case t1.a when (select ~max(coalesce((select (t1.b-a*+t1.c-t1.e) from t1 where not 11*t1.f++t1.f-t1.a*f*+t1.e*t1.b>17 and 19+e not in (t1.c,t1.b,a)),19)) from t1) then 19*11 else d end & (17) & t1.d FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(13) from t1 where t1.e not in (d,13-19,17) or e*19=d or ((t1.a< -t1.a or 11- -t1.d-case when 13<( -t1.e) then a else e end*t1.b+t1.e in (select t1.d from t1 union select t1.e from t1) and 19<>d))),b)+11*11=t1.e))}
} {16}
do_test randexpr-2.1019 {
  db eval {SELECT t1.a-coalesce((select 11-case when 11<19-f+t1.a then a | (t1.a+++(select cast(avg((abs(t1.d | e)/abs((abs(t1.a)/abs(13))))) AS integer)-max(a) from t1)+e+13*19+t1.a-c) else 13 end+t1.e-19 from t1 where 13>t1.f),e) FROM t1 WHERE ~(abs((select max( -case when d+(11)*d between coalesce((select 11 from t1 where (t1.f)=e),d*f) and t1.e then d-case when a<> -17+(abs(t1.d)/abs(t1.f)) then t1.f else t1.e end*11+c-(c) else d end) from t1)*t1.e)/abs((t1.f)))-f<>11}
} {-400}
do_test randexpr-2.1020 {
  db eval {SELECT t1.a-coalesce((select 11-case when 11<19-f+t1.a then a | (t1.a+++(select cast(avg((abs(t1.d | e)/abs((abs(t1.a)/abs(13))))) AS integer)-max(a) from t1)+e+13*19+t1.a-c) else 13 end+t1.e-19 from t1 where 13>t1.f),e) FROM t1 WHERE NOT (~(abs((select max( -case when d+(11)*d between coalesce((select 11 from t1 where (t1.f)=e),d*f) and t1.e then d-case when a<> -17+(abs(t1.d)/abs(t1.f)) then t1.f else t1.e end*11+c-(c) else d end) from t1)*t1.e)/abs((t1.f)))-f<>11)}
} {}
do_test randexpr-2.1021 {
  db eval {SELECT t1.a-coalesce((select 11-case when 11<19-f+t1.a then a & (t1.a+++(select cast(avg((abs(t1.d & e)/abs((abs(t1.a)/abs(13))))) AS integer)-max(a) from t1)+e+13*19+t1.a-c) else 13 end+t1.e-19 from t1 where 13>t1.f),e) FROM t1 WHERE ~(abs((select max( -case when d+(11)*d between coalesce((select 11 from t1 where (t1.f)=e),d*f) and t1.e then d-case when a<> -17+(abs(t1.d)/abs(t1.f)) then t1.f else t1.e end*11+c-(c) else d end) from t1)*t1.e)/abs((t1.f)))-f<>11}
} {-400}
do_test randexpr-2.1022 {
  db eval {SELECT d | (select (cast(avg((abs(case when b*(abs((abs(case f when 17 then t1.e else t1.c end)/abs( -d)))/abs(t1.c)) in (d,a,a) then 19 when (exists(select 1 from t1 where t1.c=t1.a) or a<>d) then a else c end)/abs(t1.e))-17) AS integer)* -min(19)-count(distinct a)-+count(distinct 17)*min(t1.a)+ -cast(avg(t1.a) AS integer)- -max(17) | max(e)) from t1) FROM t1 WHERE  -f-t1.f++e+case when not (((select abs(count(*)) from t1)) not in ((case when (t1.b>t1.c) then t1.b else f end),e,13)) and not exists(select 1 from t1 where 11 in (select t1.f from t1 union select ((t1.f)) from t1)) then (t1.e)+c-c+c when  -b in (13,19,t1.c) then 17 else 13 end-d | t1.a not in (a,b,b)}
} {511}
do_test randexpr-2.1023 {
  db eval {SELECT d | (select (cast(avg((abs(case when b*(abs((abs(case f when 17 then t1.e else t1.c end)/abs( -d)))/abs(t1.c)) in (d,a,a) then 19 when (exists(select 1 from t1 where t1.c=t1.a) or a<>d) then a else c end)/abs(t1.e))-17) AS integer)* -min(19)-count(distinct a)-+count(distinct 17)*min(t1.a)+ -cast(avg(t1.a) AS integer)- -max(17) | max(e)) from t1) FROM t1 WHERE NOT ( -f-t1.f++e+case when not (((select abs(count(*)) from t1)) not in ((case when (t1.b>t1.c) then t1.b else f end),e,13)) and not exists(select 1 from t1 where 11 in (select t1.f from t1 union select ((t1.f)) from t1)) then (t1.e)+c-c+c when  -b in (13,19,t1.c) then 17 else 13 end-d | t1.a not in (a,b,b))}
} {}
do_test randexpr-2.1024 {
  db eval {SELECT d & (select (cast(avg((abs(case when b*(abs((abs(case f when 17 then t1.e else t1.c end)/abs( -d)))/abs(t1.c)) in (d,a,a) then 19 when (exists(select 1 from t1 where t1.c=t1.a) or a<>d) then a else c end)/abs(t1.e))-17) AS integer)* -min(19)-count(distinct a)-+count(distinct 17)*min(t1.a)+ -cast(avg(t1.a) AS integer)- -max(17) & max(e)) from t1) FROM t1 WHERE  -f-t1.f++e+case when not (((select abs(count(*)) from t1)) not in ((case when (t1.b>t1.c) then t1.b else f end),e,13)) and not exists(select 1 from t1 where 11 in (select t1.f from t1 union select ((t1.f)) from t1)) then (t1.e)+c-c+c when  -b in (13,19,t1.c) then 17 else 13 end-d | t1.a not in (a,b,b)}
} {128}
do_test randexpr-2.1025 {
  db eval {SELECT 11-(select min((abs(e)/abs(f*t1.e*c+17+~case when f | 11 between (select case  -max(19) when (cast(avg(t1.a) AS integer)) then count(distinct t1.f) else count(*) end from t1) and coalesce((select 13 from t1 where a<=(t1.d)),f)-a then t1.a when f in (select 17 from t1 union select  -b from t1) and t1.d<a or d<>(17) or 19>=d then (f) else 11 end))) from t1) FROM t1 WHERE e in (e, -17*t1.c*17,e)}
} {11}
do_test randexpr-2.1026 {
  db eval {SELECT 11-(select min((abs(e)/abs(f*t1.e*c+17+~case when f | 11 between (select case  -max(19) when (cast(avg(t1.a) AS integer)) then count(distinct t1.f) else count(*) end from t1) and coalesce((select 13 from t1 where a<=(t1.d)),f)-a then t1.a when f in (select 17 from t1 union select  -b from t1) and t1.d<a or d<>(17) or 19>=d then (f) else 11 end))) from t1) FROM t1 WHERE NOT (e in (e, -17*t1.c*17,e))}
} {}
do_test randexpr-2.1027 {
  db eval {SELECT 11-(select min((abs(e)/abs(f*t1.e*c+17+~case when f & 11 between (select case  -max(19) when (cast(avg(t1.a) AS integer)) then count(distinct t1.f) else count(*) end from t1) and coalesce((select 13 from t1 where a<=(t1.d)),f)-a then t1.a when f in (select 17 from t1 union select  -b from t1) and t1.d<a or d<>(17) or 19>=d then (f) else 11 end))) from t1) FROM t1 WHERE e in (e, -17*t1.c*17,e)}
} {11}
do_test randexpr-2.1028 {
  db eval {SELECT coalesce((select max( -t1.d-f+~t1.d*t1.b) from t1 where (select ~+min(t1.f)+abs(min(+(select cast(avg((b)) AS integer) from t1)-d*d))-max(f)-count(distinct 19) | count(*)*count(*) from t1)>c),case 13 when +t1.c-t1.c-t1.a then c else c end*d) FROM t1 WHERE ((t1.b>=case when not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where e>=t1.a or (coalesce((select max(coalesce((select case when a in (select t1.d from t1 union select t1.c from t1) then a when  -b in (17,c,t1.f) then f else b end from t1 where not exists(select 1 from t1 where f<=13)),17)) from t1 where t1.f>=t1.b),d) between t1.f and 11) or t1.b between 13 and t1.b))) then a when e<=17 then t1.b+ -~11 else a end and not e>= - -b or 13 not in (c,f,11)) and d not between 11 and t1.a)}
} {-81200}
do_test randexpr-2.1029 {
  db eval {SELECT coalesce((select max( -t1.d-f+~t1.d*t1.b) from t1 where (select ~+min(t1.f)+abs(min(+(select cast(avg((b)) AS integer) from t1)-d*d))-max(f)-count(distinct 19) | count(*)*count(*) from t1)>c),case 13 when +t1.c-t1.c-t1.a then c else c end*d) FROM t1 WHERE NOT (((t1.b>=case when not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where e>=t1.a or (coalesce((select max(coalesce((select case when a in (select t1.d from t1 union select t1.c from t1) then a when  -b in (17,c,t1.f) then f else b end from t1 where not exists(select 1 from t1 where f<=13)),17)) from t1 where t1.f>=t1.b),d) between t1.f and 11) or t1.b between 13 and t1.b))) then a when e<=17 then t1.b+ -~11 else a end and not e>= - -b or 13 not in (c,f,11)) and d not between 11 and t1.a))}
} {}
do_test randexpr-2.1030 {
  db eval {SELECT coalesce((select max( -t1.d-f+~t1.d*t1.b) from t1 where (select ~+min(t1.f)+abs(min(+(select cast(avg((b)) AS integer) from t1)-d*d))-max(f)-count(distinct 19) & count(*)*count(*) from t1)>c),case 13 when +t1.c-t1.c-t1.a then c else c end*d) FROM t1 WHERE ((t1.b>=case when not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where e>=t1.a or (coalesce((select max(coalesce((select case when a in (select t1.d from t1 union select t1.c from t1) then a when  -b in (17,c,t1.f) then f else b end from t1 where not exists(select 1 from t1 where f<=13)),17)) from t1 where t1.f>=t1.b),d) between t1.f and 11) or t1.b between 13 and t1.b))) then a when e<=17 then t1.b+ -~11 else a end and not e>= - -b or 13 not in (c,f,11)) and d not between 11 and t1.a)}
} {120000}
do_test randexpr-2.1031 {
  db eval {SELECT case when t1.d<>coalesce((select 13 from t1 where (d in (select case when (13<>t1.a*d-19-+11*13-t1.c) then case when t1.c=d then e else t1.b end when not exists(select 1 from t1 where 17<>t1.b) then t1.e else t1.e end | t1.a+t1.e from t1 union select t1.d from t1))),t1.f) or a> -t1.e then 11 else 17 end*d FROM t1 WHERE t1.a-d<=d-(abs(coalesce((select b from t1 where ~e<case when (case when case when d>=13 then t1.d else (t1.c) end not between t1.a and 13 then a when (17) not between 11 and t1.c then a else a end) not between 13 and t1.d then 13 else a end),19))/abs(t1.e))+t1.c+t1.e*b+c or ((17 in (select f from t1 union select t1.e from t1)))}
} {4400}
do_test randexpr-2.1032 {
  db eval {SELECT case when t1.d<>coalesce((select 13 from t1 where (d in (select case when (13<>t1.a*d-19-+11*13-t1.c) then case when t1.c=d then e else t1.b end when not exists(select 1 from t1 where 17<>t1.b) then t1.e else t1.e end | t1.a+t1.e from t1 union select t1.d from t1))),t1.f) or a> -t1.e then 11 else 17 end*d FROM t1 WHERE NOT (t1.a-d<=d-(abs(coalesce((select b from t1 where ~e<case when (case when case when d>=13 then t1.d else (t1.c) end not between t1.a and 13 then a when (17) not between 11 and t1.c then a else a end) not between 13 and t1.d then 13 else a end),19))/abs(t1.e))+t1.c+t1.e*b+c or ((17 in (select f from t1 union select t1.e from t1))))}
} {}
do_test randexpr-2.1033 {
  db eval {SELECT case when t1.d<>coalesce((select 13 from t1 where (d in (select case when (13<>t1.a*d-19-+11*13-t1.c) then case when t1.c=d then e else t1.b end when not exists(select 1 from t1 where 17<>t1.b) then t1.e else t1.e end & t1.a+t1.e from t1 union select t1.d from t1))),t1.f) or a> -t1.e then 11 else 17 end*d FROM t1 WHERE t1.a-d<=d-(abs(coalesce((select b from t1 where ~e<case when (case when case when d>=13 then t1.d else (t1.c) end not between t1.a and 13 then a when (17) not between 11 and t1.c then a else a end) not between 13 and t1.d then 13 else a end),19))/abs(t1.e))+t1.c+t1.e*b+c or ((17 in (select f from t1 union select t1.e from t1)))}
} {4400}
do_test randexpr-2.1034 {
  db eval {SELECT coalesce((select (abs(c)/abs(case when 13<=11 then t1.a when case t1.d when (11) then coalesce((select coalesce((select d-17 from t1 where t1.e=a),11) from t1 where 13 in (select t1.e from t1 union select c from t1)),19) else d end>=t1.f or 11 in (select cast(avg(t1.f) AS integer) from t1 union select ( - -count(*)) from t1) and t1.c between 13 and  -b then f else e end)) from t1 where d<=(19)),d)-t1.b FROM t1 WHERE 17>=case when t1.c not in (f,t1.a,c*17*a | t1.c-~t1.d+(+coalesce((select max(case when exists(select 1 from t1 where (t1.e in (select  -t1.e from t1 union select t1.c from t1))) then t1.b else t1.b*t1.b end) from t1 where not exists(select 1 from t1 where 17=t1.a)),d))+t1.e | (13)*t1.e+c) and e in (select  -c from t1 union select 17 from t1) then t1.d*13 else c end- -e}
} {}
do_test randexpr-2.1035 {
  db eval {SELECT coalesce((select (abs(c)/abs(case when 13<=11 then t1.a when case t1.d when (11) then coalesce((select coalesce((select d-17 from t1 where t1.e=a),11) from t1 where 13 in (select t1.e from t1 union select c from t1)),19) else d end>=t1.f or 11 in (select cast(avg(t1.f) AS integer) from t1 union select ( - -count(*)) from t1) and t1.c between 13 and  -b then f else e end)) from t1 where d<=(19)),d)-t1.b FROM t1 WHERE NOT (17>=case when t1.c not in (f,t1.a,c*17*a | t1.c-~t1.d+(+coalesce((select max(case when exists(select 1 from t1 where (t1.e in (select  -t1.e from t1 union select t1.c from t1))) then t1.b else t1.b*t1.b end) from t1 where not exists(select 1 from t1 where 17=t1.a)),d))+t1.e | (13)*t1.e+c) and e in (select  -c from t1 union select 17 from t1) then t1.d*13 else c end- -e)}
} {200}
do_test randexpr-2.1036 {
  db eval {SELECT (abs(case when t1.a in (select case when d=(select ~cast(avg(t1.a) AS integer) | ~+min(17*(abs(19)/abs(t1.a))) from t1) or 13 in (select count(distinct t1.b | 11) from t1 union select count(*) | count(distinct c) | count(distinct 17) from t1) and not b<=17 then t1.a when 11=t1.f then (abs(t1.c)/abs(11)) else f end from t1 union select c from t1) then t1.c else a end)/abs(t1.d))-t1.d FROM t1 WHERE ((abs(e)/abs(t1.a* -(coalesce((select max(t1.b-t1.d) from t1 where f>=13),~a+ -a)) | case when not exists(select 1 from t1 where coalesce((select max(c) from t1 where 19-t1.a | e<=17),~( -t1.a)) in (select f from t1 union select t1.d from t1)) then t1.d else (t1.c) end)) in (17,f,t1.a)) or 19=13 or 19=17}
} {}
do_test randexpr-2.1037 {
  db eval {SELECT (abs(case when t1.a in (select case when d=(select ~cast(avg(t1.a) AS integer) | ~+min(17*(abs(19)/abs(t1.a))) from t1) or 13 in (select count(distinct t1.b | 11) from t1 union select count(*) | count(distinct c) | count(distinct 17) from t1) and not b<=17 then t1.a when 11=t1.f then (abs(t1.c)/abs(11)) else f end from t1 union select c from t1) then t1.c else a end)/abs(t1.d))-t1.d FROM t1 WHERE NOT (((abs(e)/abs(t1.a* -(coalesce((select max(t1.b-t1.d) from t1 where f>=13),~a+ -a)) | case when not exists(select 1 from t1 where coalesce((select max(c) from t1 where 19-t1.a | e<=17),~( -t1.a)) in (select f from t1 union select t1.d from t1)) then t1.d else (t1.c) end)) in (17,f,t1.a)) or 19=13 or 19=17)}
} {-400}
do_test randexpr-2.1038 {
  db eval {SELECT (abs(case when t1.a in (select case when d=(select ~cast(avg(t1.a) AS integer) & ~+min(17*(abs(19)/abs(t1.a))) from t1) or 13 in (select count(distinct t1.b & 11) from t1 union select count(*) & count(distinct c) & count(distinct 17) from t1) and not b<=17 then t1.a when 11=t1.f then (abs(t1.c)/abs(11)) else f end from t1 union select c from t1) then t1.c else a end)/abs(t1.d))-t1.d FROM t1 WHERE NOT (((abs(e)/abs(t1.a* -(coalesce((select max(t1.b-t1.d) from t1 where f>=13),~a+ -a)) | case when not exists(select 1 from t1 where coalesce((select max(c) from t1 where 19-t1.a | e<=17),~( -t1.a)) in (select f from t1 union select t1.d from t1)) then t1.d else (t1.c) end)) in (17,f,t1.a)) or 19=13 or 19=17)}
} {-400}
do_test randexpr-2.1039 {
  db eval {SELECT case when f>coalesce((select c from t1 where coalesce((select max(c+c) from t1 where t1.f in (select  - -abs(max(19))+(min(a)) from t1 union select count(distinct  -t1.d) from t1)),e)>=e),t1.f) | t1.a | 19 or (t1.c) not in (19, - -t1.f,t1.c) or exists(select 1 from t1 where t1.b not between t1.a and  -11) then coalesce((select  -b from t1 where  -t1.a in (select c from t1 union select 17 from t1)),t1.d) when t1.a=c then c else t1.e end FROM t1 WHERE t1.e in (select +cast(avg(f) AS integer) from t1 union select case +max(19) | count(*) when count(*)*+count(*) then ~+count(*) else count(*) end from t1)}
} {}
do_test randexpr-2.1040 {
  db eval {SELECT case when f>coalesce((select c from t1 where coalesce((select max(c+c) from t1 where t1.f in (select  - -abs(max(19))+(min(a)) from t1 union select count(distinct  -t1.d) from t1)),e)>=e),t1.f) | t1.a | 19 or (t1.c) not in (19, - -t1.f,t1.c) or exists(select 1 from t1 where t1.b not between t1.a and  -11) then coalesce((select  -b from t1 where  -t1.a in (select c from t1 union select 17 from t1)),t1.d) when t1.a=c then c else t1.e end FROM t1 WHERE NOT (t1.e in (select +cast(avg(f) AS integer) from t1 union select case +max(19) | count(*) when count(*)*+count(*) then ~+count(*) else count(*) end from t1))}
} {400}
do_test randexpr-2.1041 {
  db eval {SELECT case when f>coalesce((select c from t1 where coalesce((select max(c+c) from t1 where t1.f in (select  - -abs(max(19))+(min(a)) from t1 union select count(distinct  -t1.d) from t1)),e)>=e),t1.f) & t1.a & 19 or (t1.c) not in (19, - -t1.f,t1.c) or exists(select 1 from t1 where t1.b not between t1.a and  -11) then coalesce((select  -b from t1 where  -t1.a in (select c from t1 union select 17 from t1)),t1.d) when t1.a=c then c else t1.e end FROM t1 WHERE NOT (t1.e in (select +cast(avg(f) AS integer) from t1 union select case +max(19) | count(*) when count(*)*+count(*) then ~+count(*) else count(*) end from t1))}
} {400}
do_test randexpr-2.1042 {
  db eval {SELECT +case t1.d when d then t1.f else +t1.b+(select  -count(distinct coalesce((select max(c) from t1 where exists(select 1 from t1 where 17 not between d and e)),case when t1.f+f-~17<>d then case when exists(select 1 from t1 where t1.d=(13)) then t1.e when c=t1.e then  -a else f end when not 17>11 then t1.b else e end))-max(t1.d) from t1)+ -e-(t1.d) end-11-b FROM t1 WHERE e-case +t1.e when e*e then t1.d else case (abs(case when (abs(case when t1.a+11+t1.a>11-t1.e then +t1.f when e<=a then (c) else b end)/abs(13))*b between b and t1.f then  -a else t1.c end+d)/abs(a)) when d then 13 else t1.e end end+e+t1.d<=c}
} {}
do_test randexpr-2.1043 {
  db eval {SELECT +case t1.d when d then t1.f else +t1.b+(select  -count(distinct coalesce((select max(c) from t1 where exists(select 1 from t1 where 17 not between d and e)),case when t1.f+f-~17<>d then case when exists(select 1 from t1 where t1.d=(13)) then t1.e when c=t1.e then  -a else f end when not 17>11 then t1.b else e end))-max(t1.d) from t1)+ -e-(t1.d) end-11-b FROM t1 WHERE NOT (e-case +t1.e when e*e then t1.d else case (abs(case when (abs(case when t1.a+11+t1.a>11-t1.e then +t1.f when e<=a then (c) else b end)/abs(13))*b between b and t1.f then  -a else t1.c end+d)/abs(a)) when d then 13 else t1.e end end+e+t1.d<=c)}
} {389}
do_test randexpr-2.1044 {
  db eval {SELECT + -(select count(*) from t1)*(t1.b)-a-t1.e+17*coalesce((select max(13) from t1 where not exists(select 1 from t1 where case when t1.f<coalesce((select a from t1 where t1.a not in (t1.b,t1.a,19)),t1.a)*f and not exists(select 1 from t1 where exists(select 1 from t1 where (t1.d)=19)) then +t1.d when c<>t1.d then 17 else  -17 end* -(t1.f)=(t1.a))), -d)*t1.f*t1.a* -e FROM t1 WHERE not exists(select 1 from t1 where ~case when d+ -t1.c+11*t1.e-t1.c*a*(t1.b)<=~~t1.b then f else case b when t1.b*t1.c-t1.d then c-b else  -t1.c end end-13+f>=case when d not between t1.c and (t1.b) then t1.e else t1.c end) or t1.d in (d,t1.c,t1.c)}
} {-6630000800}
do_test randexpr-2.1045 {
  db eval {SELECT + -(select count(*) from t1)*(t1.b)-a-t1.e+17*coalesce((select max(13) from t1 where not exists(select 1 from t1 where case when t1.f<coalesce((select a from t1 where t1.a not in (t1.b,t1.a,19)),t1.a)*f and not exists(select 1 from t1 where exists(select 1 from t1 where (t1.d)=19)) then +t1.d when c<>t1.d then 17 else  -17 end* -(t1.f)=(t1.a))), -d)*t1.f*t1.a* -e FROM t1 WHERE NOT (not exists(select 1 from t1 where ~case when d+ -t1.c+11*t1.e-t1.c*a*(t1.b)<=~~t1.b then f else case b when t1.b*t1.c-t1.d then c-b else  -t1.c end end-13+f>=case when d not between t1.c and (t1.b) then t1.e else t1.c end) or t1.d in (d,t1.c,t1.c))}
} {}
do_test randexpr-2.1046 {
  db eval {SELECT (abs((select  -~~ -count(*)+++count(distinct c) from t1))/abs(coalesce((select e from t1 where (case when case when b not between case t1.d when f then  -t1.c else t1.e end and c then d when b=19 then t1.c else d end in (select max(13) from t1 union select count(distinct b) from t1) and t1.d not in (a,t1.b,a) or  -t1.d between 13 and e then 17+t1.e when 19 not between t1.f and 17 then t1.b else t1.a end in (17,(t1.e),t1.a))),b) | 17)) FROM t1 WHERE 11>t1.b}
} {}
do_test randexpr-2.1047 {
  db eval {SELECT (abs((select  -~~ -count(*)+++count(distinct c) from t1))/abs(coalesce((select e from t1 where (case when case when b not between case t1.d when f then  -t1.c else t1.e end and c then d when b=19 then t1.c else d end in (select max(13) from t1 union select count(distinct b) from t1) and t1.d not in (a,t1.b,a) or  -t1.d between 13 and e then 17+t1.e when 19 not between t1.f and 17 then t1.b else t1.a end in (17,(t1.e),t1.a))),b) | 17)) FROM t1 WHERE NOT (11>t1.b)}
} {0}
do_test randexpr-2.1048 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where coalesce((select e from t1 where case when (c)<>11+case f when t1.a then (select abs( -cast(avg(t1.c) AS integer)) | max((17)) | cast(avg(t1.d) AS integer)-count(distinct e) from t1) else 17*(abs(case t1.d when t1.b then a else b end)/abs(b)) end- -c-17+c*t1.c- -t1.d then t1.c else e end>=f),d)<>t1.a), -t1.f) FROM t1 WHERE not a<=17-t1.f}
} {400}
do_test randexpr-2.1049 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where coalesce((select e from t1 where case when (c)<>11+case f when t1.a then (select abs( -cast(avg(t1.c) AS integer)) | max((17)) | cast(avg(t1.d) AS integer)-count(distinct e) from t1) else 17*(abs(case t1.d when t1.b then a else b end)/abs(b)) end- -c-17+c*t1.c- -t1.d then t1.c else e end>=f),d)<>t1.a), -t1.f) FROM t1 WHERE NOT (not a<=17-t1.f)}
} {}
do_test randexpr-2.1050 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where coalesce((select e from t1 where case when (c)<>11+case f when t1.a then (select abs( -cast(avg(t1.c) AS integer)) & max((17)) & cast(avg(t1.d) AS integer)-count(distinct e) from t1) else 17*(abs(case t1.d when t1.b then a else b end)/abs(b)) end- -c-17+c*t1.c- -t1.d then t1.c else e end>=f),d)<>t1.a), -t1.f) FROM t1 WHERE not a<=17-t1.f}
} {400}
do_test randexpr-2.1051 {
  db eval {SELECT coalesce((select coalesce((select ~d from t1 where t1.b-t1.c+13 not between t1.b and (abs(t1.a-case t1.c when t1.c | (select max((abs(case when (select count(*) from t1)<>(~t1.e-13*+d+d) then  -t1.e else  -t1.f end*13)/abs(f))-t1.f) from t1) then t1.f else t1.c end)/abs(c))),t1.e) from t1 where t1.f=f), - -11) FROM t1 WHERE case ((abs(t1.e)/abs(case b when ~17 then 19+(t1.d)+13 else case t1.a*17 when c then 19*case when c<>coalesce((select max(~a) from t1 where 19<>case case when t1.d in (select +count(distinct 11) from t1 union select ( -max(a)) from t1) then t1.f else b end when t1.f then d else t1.a end-t1.b),11) then t1.b else t1.d end else 11 end end))) when t1.b then 11 else t1.d end*t1.c= -t1.f}
} {}
do_test randexpr-2.1052 {
  db eval {SELECT coalesce((select coalesce((select ~d from t1 where t1.b-t1.c+13 not between t1.b and (abs(t1.a-case t1.c when t1.c | (select max((abs(case when (select count(*) from t1)<>(~t1.e-13*+d+d) then  -t1.e else  -t1.f end*13)/abs(f))-t1.f) from t1) then t1.f else t1.c end)/abs(c))),t1.e) from t1 where t1.f=f), - -11) FROM t1 WHERE NOT (case ((abs(t1.e)/abs(case b when ~17 then 19+(t1.d)+13 else case t1.a*17 when c then 19*case when c<>coalesce((select max(~a) from t1 where 19<>case case when t1.d in (select +count(distinct 11) from t1 union select ( -max(a)) from t1) then t1.f else b end when t1.f then d else t1.a end-t1.b),11) then t1.b else t1.d end else 11 end end))) when t1.b then 11 else t1.d end*t1.c= -t1.f)}
} {-401}
do_test randexpr-2.1053 {
  db eval {SELECT coalesce((select coalesce((select ~d from t1 where t1.b-t1.c+13 not between t1.b and (abs(t1.a-case t1.c when t1.c & (select max((abs(case when (select count(*) from t1)<>(~t1.e-13*+d+d) then  -t1.e else  -t1.f end*13)/abs(f))-t1.f) from t1) then t1.f else t1.c end)/abs(c))),t1.e) from t1 where t1.f=f), - -11) FROM t1 WHERE NOT (case ((abs(t1.e)/abs(case b when ~17 then 19+(t1.d)+13 else case t1.a*17 when c then 19*case when c<>coalesce((select max(~a) from t1 where 19<>case case when t1.d in (select +count(distinct 11) from t1 union select ( -max(a)) from t1) then t1.f else b end when t1.f then d else t1.a end-t1.b),11) then t1.b else t1.d end else 11 end end))) when t1.b then 11 else t1.d end*t1.c= -t1.f)}
} {-401}
do_test randexpr-2.1054 {
  db eval {SELECT  -13-case when (not d<=11-t1.c*t1.e+t1.b) then case when t1.f | coalesce((select +d from t1 where t1.d= -c),(t1.a)) not between b and t1.a then t1.f+a when t1.a<11 and exists(select 1 from t1 where t1.f in (t1.b,17,11)) then b else 19 end when (t1.b between t1.d and e) then b else  -t1.c end FROM t1 WHERE case when b between case when coalesce((select t1.c-t1.c from t1 where 13*(select case min(11) when cast(avg(t1.c) AS integer) then (count(*)) else count(distinct 11) end+cast(avg( -f) AS integer) from t1)>=t1.a),t1.c) in ( -t1.c,d,b) then t1.e when f in (select e from t1 union select t1.d from t1) then f else c end and a and 13<>c and exists(select 1 from t1 where f<>c) then case when c in (11,b, -11) then t1.e else e end else 13 end<=t1.c}
} {-713}
do_test randexpr-2.1055 {
  db eval {SELECT  -13-case when (not d<=11-t1.c*t1.e+t1.b) then case when t1.f | coalesce((select +d from t1 where t1.d= -c),(t1.a)) not between b and t1.a then t1.f+a when t1.a<11 and exists(select 1 from t1 where t1.f in (t1.b,17,11)) then b else 19 end when (t1.b between t1.d and e) then b else  -t1.c end FROM t1 WHERE NOT (case when b between case when coalesce((select t1.c-t1.c from t1 where 13*(select case min(11) when cast(avg(t1.c) AS integer) then (count(*)) else count(distinct 11) end+cast(avg( -f) AS integer) from t1)>=t1.a),t1.c) in ( -t1.c,d,b) then t1.e when f in (select e from t1 union select t1.d from t1) then f else c end and a and 13<>c and exists(select 1 from t1 where f<>c) then case when c in (11,b, -11) then t1.e else e end else 13 end<=t1.c)}
} {}
do_test randexpr-2.1056 {
  db eval {SELECT  -13-case when (not d<=11-t1.c*t1.e+t1.b) then case when t1.f & coalesce((select +d from t1 where t1.d= -c),(t1.a)) not between b and t1.a then t1.f+a when t1.a<11 and exists(select 1 from t1 where t1.f in (t1.b,17,11)) then b else 19 end when (t1.b between t1.d and e) then b else  -t1.c end FROM t1 WHERE case when b between case when coalesce((select t1.c-t1.c from t1 where 13*(select case min(11) when cast(avg(t1.c) AS integer) then (count(*)) else count(distinct 11) end+cast(avg( -f) AS integer) from t1)>=t1.a),t1.c) in ( -t1.c,d,b) then t1.e when f in (select e from t1 union select t1.d from t1) then f else c end and a and 13<>c and exists(select 1 from t1 where f<>c) then case when c in (11,b, -11) then t1.e else e end else 13 end<=t1.c}
} {-713}
do_test randexpr-2.1057 {
  db eval {SELECT t1.b | (abs( -(select ~ -~abs(case ~min((c* -b+c))+min(f) when ~abs(count(distinct 13))+(min(13)) then max(11) else count(*) end) from t1)-11 | +(abs(t1.d-t1.e)/abs(t1.b))-t1.f*19+t1.c*17)/abs(f))+t1.b FROM t1 WHERE (a between t1.e and  -13)}
} {}
do_test randexpr-2.1058 {
  db eval {SELECT t1.b | (abs( -(select ~ -~abs(case ~min((c* -b+c))+min(f) when ~abs(count(distinct 13))+(min(13)) then max(11) else count(*) end) from t1)-11 | +(abs(t1.d-t1.e)/abs(t1.b))-t1.f*19+t1.c*17)/abs(f))+t1.b FROM t1 WHERE NOT ((a between t1.e and  -13))}
} {200}
do_test randexpr-2.1059 {
  db eval {SELECT t1.b & (abs( -(select ~ -~abs(case ~min((c* -b+c))+min(f) when ~abs(count(distinct 13))+(min(13)) then max(11) else count(*) end) from t1)-11 & +(abs(t1.d-t1.e)/abs(t1.b))-t1.f*19+t1.c*17)/abs(f))+t1.b FROM t1 WHERE NOT ((a between t1.e and  -13))}
} {192}
do_test randexpr-2.1060 {
  db eval {SELECT t1.c-case t1.b when t1.f-t1.b-f then +coalesce((select b from t1 where (t1.d in (select (select count(*)+abs(count(*)) | ~cast(avg(b | case when 11 between b and (f) then b when (19)>19 then 17 else t1.e end) AS integer) | min(d) from t1) from t1 union select 19 from t1))),(abs(c*c)/abs(11))-a-t1.c+t1.f-t1.c)+b else b end FROM t1 WHERE (t1.d)+t1.b<( -t1.b)}
} {}
do_test randexpr-2.1061 {
  db eval {SELECT t1.c-case t1.b when t1.f-t1.b-f then +coalesce((select b from t1 where (t1.d in (select (select count(*)+abs(count(*)) | ~cast(avg(b | case when 11 between b and (f) then b when (19)>19 then 17 else t1.e end) AS integer) | min(d) from t1) from t1 union select 19 from t1))),(abs(c*c)/abs(11))-a-t1.c+t1.f-t1.c)+b else b end FROM t1 WHERE NOT ((t1.d)+t1.b<( -t1.b))}
} {100}
do_test randexpr-2.1062 {
  db eval {SELECT t1.c-case t1.b when t1.f-t1.b-f then +coalesce((select b from t1 where (t1.d in (select (select count(*)+abs(count(*)) & ~cast(avg(b & case when 11 between b and (f) then b when (19)>19 then 17 else t1.e end) AS integer) & min(d) from t1) from t1 union select 19 from t1))),(abs(c*c)/abs(11))-a-t1.c+t1.f-t1.c)+b else b end FROM t1 WHERE NOT ((t1.d)+t1.b<( -t1.b))}
} {100}
do_test randexpr-2.1063 {
  db eval {SELECT 17*(select (case case min(t1.d+( -d | case 11* -11*11 when 13 then t1.c else  -17 end)-d*t1.d)-count(*)-abs( -max(17)+~max(t1.b)) | +abs(cast(avg((a)) AS integer))+(count(*)) when  -max(17) then  -max(19) else (cast(avg(d) AS integer)) end when count(distinct t1.c) then min(b) else count(*) end) from t1) FROM t1 WHERE d>=(abs(coalesce((select max(d) from t1 where not not case when a in (select count(*)* -case +min(case when t1.e<t1.e then 11 else a end-19)*case count(*) when max(13) then count(*) else min(b) end | ( -cast(avg(b) AS integer)) when max(t1.d) then (cast(avg((t1.a)) AS integer)) else min(f) end |  -max(t1.d) from t1 union select  -min(c) from t1) then e else e end<(select max(t1.c) from t1)),c++t1.f*c))/abs(e))+t1.d}
} {}
do_test randexpr-2.1064 {
  db eval {SELECT 17*(select (case case min(t1.d+( -d | case 11* -11*11 when 13 then t1.c else  -17 end)-d*t1.d)-count(*)-abs( -max(17)+~max(t1.b)) | +abs(cast(avg((a)) AS integer))+(count(*)) when  -max(17) then  -max(19) else (cast(avg(d) AS integer)) end when count(distinct t1.c) then min(b) else count(*) end) from t1) FROM t1 WHERE NOT (d>=(abs(coalesce((select max(d) from t1 where not not case when a in (select count(*)* -case +min(case when t1.e<t1.e then 11 else a end-19)*case count(*) when max(13) then count(*) else min(b) end | ( -cast(avg(b) AS integer)) when max(t1.d) then (cast(avg((t1.a)) AS integer)) else min(f) end |  -max(t1.d) from t1 union select  -min(c) from t1) then e else e end<(select max(t1.c) from t1)),c++t1.f*c))/abs(e))+t1.d)}
} {17}
do_test randexpr-2.1065 {
  db eval {SELECT 17*(select (case case min(t1.d+( -d & case 11* -11*11 when 13 then t1.c else  -17 end)-d*t1.d)-count(*)-abs( -max(17)+~max(t1.b)) & +abs(cast(avg((a)) AS integer))+(count(*)) when  -max(17) then  -max(19) else (cast(avg(d) AS integer)) end when count(distinct t1.c) then min(b) else count(*) end) from t1) FROM t1 WHERE NOT (d>=(abs(coalesce((select max(d) from t1 where not not case when a in (select count(*)* -case +min(case when t1.e<t1.e then 11 else a end-19)*case count(*) when max(13) then count(*) else min(b) end | ( -cast(avg(b) AS integer)) when max(t1.d) then (cast(avg((t1.a)) AS integer)) else min(f) end |  -max(t1.d) from t1 union select  -min(c) from t1) then e else e end<(select max(t1.c) from t1)),c++t1.f*c))/abs(e))+t1.d)}
} {17}
do_test randexpr-2.1066 {
  db eval {SELECT 11 | ~case case when e between 17 and coalesce((select max(((f-t1.f))) from t1 where d<>f),t1.f) and 11 not between 13 and 13 and ( -11<>c and t1.b>c) or 19<>t1.e and t1.b<=t1.f then +f*b when t1.d>=e then  -13 else t1.c end when b then (17) else t1.d end+a+f*a FROM t1 WHERE not exists(select 1 from t1 where a between t1.f and 17 or e>=(d)*19+t1.e*c)}
} {59707}
do_test randexpr-2.1067 {
  db eval {SELECT 11 | ~case case when e between 17 and coalesce((select max(((f-t1.f))) from t1 where d<>f),t1.f) and 11 not between 13 and 13 and ( -11<>c and t1.b>c) or 19<>t1.e and t1.b<=t1.f then +f*b when t1.d>=e then  -13 else t1.c end when b then (17) else t1.d end+a+f*a FROM t1 WHERE NOT (not exists(select 1 from t1 where a between t1.f and 17 or e>=(d)*19+t1.e*c))}
} {}
do_test randexpr-2.1068 {
  db eval {SELECT 11 & ~case case when e between 17 and coalesce((select max(((f-t1.f))) from t1 where d<>f),t1.f) and 11 not between 13 and 13 and ( -11<>c and t1.b>c) or 19<>t1.e and t1.b<=t1.f then +f*b when t1.d>=e then  -13 else t1.c end when b then (17) else t1.d end+a+f*a FROM t1 WHERE not exists(select 1 from t1 where a between t1.f and 17 or e>=(d)*19+t1.e*c)}
} {3}
do_test randexpr-2.1069 {
  db eval {SELECT  -case when t1.d | ~b<>coalesce((select max(t1.c) from t1 where t1.c not between coalesce((select max(coalesce((select max(e) from t1 where 11 not in (case when 13 not between d and c then 17 when (t1.a) not in (e,b,b) then 19 else c end,a,t1.d)),b)+f) from t1 where t1.d not in (11,f,t1.e)),t1.b) and f),11) or 11<>(d) then  -f* -d else (e) end*f FROM t1 WHERE case f when 11 then coalesce((select b from t1 where 19+case when 17*t1.d-t1.f+t1.f between t1.d-case when +d=coalesce((select max(f) from t1 where e>t1.f),17) and c=t1.e and b not in (17,11,(t1.f)) then  -17 else t1.c end and c then  -t1.a else t1.d end+11*e not between t1.f and d),13)+t1.d else  -13 end=c}
} {}
do_test randexpr-2.1070 {
  db eval {SELECT  -case when t1.d | ~b<>coalesce((select max(t1.c) from t1 where t1.c not between coalesce((select max(coalesce((select max(e) from t1 where 11 not in (case when 13 not between d and c then 17 when (t1.a) not in (e,b,b) then 19 else c end,a,t1.d)),b)+f) from t1 where t1.d not in (11,f,t1.e)),t1.b) and f),11) or 11<>(d) then  -f* -d else (e) end*f FROM t1 WHERE NOT (case f when 11 then coalesce((select b from t1 where 19+case when 17*t1.d-t1.f+t1.f between t1.d-case when +d=coalesce((select max(f) from t1 where e>t1.f),17) and c=t1.e and b not in (17,11,(t1.f)) then  -17 else t1.c end and c then  -t1.a else t1.d end+11*e not between t1.f and d),13)+t1.d else  -13 end=c)}
} {-144000000}
do_test randexpr-2.1071 {
  db eval {SELECT  -case when t1.d & ~b<>coalesce((select max(t1.c) from t1 where t1.c not between coalesce((select max(coalesce((select max(e) from t1 where 11 not in (case when 13 not between d and c then 17 when (t1.a) not in (e,b,b) then 19 else c end,a,t1.d)),b)+f) from t1 where t1.d not in (11,f,t1.e)),t1.b) and f),11) or 11<>(d) then  -f* -d else (e) end*f FROM t1 WHERE NOT (case f when 11 then coalesce((select b from t1 where 19+case when 17*t1.d-t1.f+t1.f between t1.d-case when +d=coalesce((select max(f) from t1 where e>t1.f),17) and c=t1.e and b not in (17,11,(t1.f)) then  -17 else t1.c end and c then  -t1.a else t1.d end+11*e not between t1.f and d),13)+t1.d else  -13 end=c)}
} {-144000000}
do_test randexpr-2.1072 {
  db eval {SELECT coalesce((select t1.b from t1 where not (t1.c>19) and 11<=+(abs(t1.b-19)/abs(a))+case when ((coalesce((select 13 from t1 where c in (b,t1.b,t1.d)),e))<>13) or f in ((t1.b),t1.e, -b) then 11+(c) else b end or b<>d),t1.f+t1.f+13) |  - -a FROM t1 WHERE 13 between t1.c and 13+~19+c+(select min(f-(abs(17)/abs((t1.e)))) from t1)}
} {}
do_test randexpr-2.1073 {
  db eval {SELECT coalesce((select t1.b from t1 where not (t1.c>19) and 11<=+(abs(t1.b-19)/abs(a))+case when ((coalesce((select 13 from t1 where c in (b,t1.b,t1.d)),e))<>13) or f in ((t1.b),t1.e, -b) then 11+(c) else b end or b<>d),t1.f+t1.f+13) |  - -a FROM t1 WHERE NOT (13 between t1.c and 13+~19+c+(select min(f-(abs(17)/abs((t1.e)))) from t1))}
} {236}
do_test randexpr-2.1074 {
  db eval {SELECT coalesce((select t1.b from t1 where not (t1.c>19) and 11<=+(abs(t1.b-19)/abs(a))+case when ((coalesce((select 13 from t1 where c in (b,t1.b,t1.d)),e))<>13) or f in ((t1.b),t1.e, -b) then 11+(c) else b end or b<>d),t1.f+t1.f+13) &  - -a FROM t1 WHERE NOT (13 between t1.c and 13+~19+c+(select min(f-(abs(17)/abs((t1.e)))) from t1))}
} {64}
do_test randexpr-2.1075 {
  db eval {SELECT  -(coalesce((select max(coalesce((select t1.f from t1 where not exists(select 1 from t1 where (abs(+b+19+19)/abs(t1.b))<t1.b) or 19+f>=(select  -max(19) from t1)+t1.f),t1.e+t1.f)* -t1.e+19-f) from t1 where (( -t1.c<19) or d>=c)),t1.c))*c*((t1.b))-17 FROM t1 WHERE t1.e not between t1.f*c and t1.f+ -d}
} {18034859983}
do_test randexpr-2.1076 {
  db eval {SELECT  -(coalesce((select max(coalesce((select t1.f from t1 where not exists(select 1 from t1 where (abs(+b+19+19)/abs(t1.b))<t1.b) or 19+f>=(select  -max(19) from t1)+t1.f),t1.e+t1.f)* -t1.e+19-f) from t1 where (( -t1.c<19) or d>=c)),t1.c))*c*((t1.b))-17 FROM t1 WHERE NOT (t1.e not between t1.f*c and t1.f+ -d)}
} {}
do_test randexpr-2.1077 {
  db eval {SELECT case 17 when (t1.d)*coalesce((select (select case (cast(avg(c) AS integer)+max(case when (not d+ -t1.e not between 11 and  -f) then f when b<(11) then t1.b else 11 end))+count(distinct t1.c)*max(b) when  -min(e) |  -count(distinct t1.c) then cast(avg(e) AS integer) else count(*) end from t1) from t1 where case c when a then a else t1.d end-11<>19),t1.a)+t1.b then f else t1.f end FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where (abs(d)/abs((f*+coalesce((select  -~case when exists(select 1 from t1 where b<c) then t1.b else 17 end+case (select (min(coalesce((select b from t1 where 11<>t1.c or ((t1.c))<>e),(t1.e)))) from t1)*17 when e then a else t1.e end-t1.b-19 from t1 where t1.e in (select abs(+min(f)+cast(avg( -a) AS integer)) from t1 union select count(distinct c) from t1)),d))))<>f))}
} {}
do_test randexpr-2.1078 {
  db eval {SELECT case 17 when (t1.d)*coalesce((select (select case (cast(avg(c) AS integer)+max(case when (not d+ -t1.e not between 11 and  -f) then f when b<(11) then t1.b else 11 end))+count(distinct t1.c)*max(b) when  -min(e) |  -count(distinct t1.c) then cast(avg(e) AS integer) else count(*) end from t1) from t1 where case c when a then a else t1.d end-11<>19),t1.a)+t1.b then f else t1.f end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (abs(d)/abs((f*+coalesce((select  -~case when exists(select 1 from t1 where b<c) then t1.b else 17 end+case (select (min(coalesce((select b from t1 where 11<>t1.c or ((t1.c))<>e),(t1.e)))) from t1)*17 when e then a else t1.e end-t1.b-19 from t1 where t1.e in (select abs(+min(f)+cast(avg( -a) AS integer)) from t1 union select count(distinct c) from t1)),d))))<>f)))}
} {600}
do_test randexpr-2.1079 {
  db eval {SELECT case 17 when (t1.d)*coalesce((select (select case (cast(avg(c) AS integer)+max(case when (not d+ -t1.e not between 11 and  -f) then f when b<(11) then t1.b else 11 end))+count(distinct t1.c)*max(b) when  -min(e) &  -count(distinct t1.c) then cast(avg(e) AS integer) else count(*) end from t1) from t1 where case c when a then a else t1.d end-11<>19),t1.a)+t1.b then f else t1.f end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (abs(d)/abs((f*+coalesce((select  -~case when exists(select 1 from t1 where b<c) then t1.b else 17 end+case (select (min(coalesce((select b from t1 where 11<>t1.c or ((t1.c))<>e),(t1.e)))) from t1)*17 when e then a else t1.e end-t1.b-19 from t1 where t1.e in (select abs(+min(f)+cast(avg( -a) AS integer)) from t1 union select count(distinct c) from t1)),d))))<>f)))}
} {600}
do_test randexpr-2.1080 {
  db eval {SELECT ((select  -case min(17 | (abs(a)/abs(case (select max(a) from t1)+13+t1.c when c then (abs(case when 17<>a and t1.c=d then ((17)) else e end)/abs(t1.b)) else 17 end)) | f*a) when abs(~(count(distinct t1.e))-abs((~max(c)))-count(*) | min(t1.f)+max(11)) then  -cast(avg((b)) AS integer) else min(b) end from t1))*a FROM t1 WHERE (13)-(t1.a*17-t1.b)-coalesce((select (select  -cast(avg(t1.c) AS integer)+case  - -count(*) | (count(distinct t1.a)) when  -min(t1.e) then (max(t1.d)) else count(distinct t1.b) end from t1)-e+(abs(17)/abs(e)) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (d)>=13 and (t1.b not in (c,a, -t1.d) or t1.e in (select c from t1 union select t1.c from t1)) or 11<=t1.d))),17) in (select e from t1 union select e from t1)}
} {}
do_test randexpr-2.1081 {
  db eval {SELECT ((select  -case min(17 | (abs(a)/abs(case (select max(a) from t1)+13+t1.c when c then (abs(case when 17<>a and t1.c=d then ((17)) else e end)/abs(t1.b)) else 17 end)) | f*a) when abs(~(count(distinct t1.e))-abs((~max(c)))-count(*) | min(t1.f)+max(11)) then  -cast(avg((b)) AS integer) else min(b) end from t1))*a FROM t1 WHERE NOT ((13)-(t1.a*17-t1.b)-coalesce((select (select  -cast(avg(t1.c) AS integer)+case  - -count(*) | (count(distinct t1.a)) when  -min(t1.e) then (max(t1.d)) else count(distinct t1.b) end from t1)-e+(abs(17)/abs(e)) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (d)>=13 and (t1.b not in (c,a, -t1.d) or t1.e in (select c from t1 union select t1.c from t1)) or 11<=t1.d))),17) in (select e from t1 union select e from t1))}
} {-20000}
do_test randexpr-2.1082 {
  db eval {SELECT ((select  -case min(17 & (abs(a)/abs(case (select max(a) from t1)+13+t1.c when c then (abs(case when 17<>a and t1.c=d then ((17)) else e end)/abs(t1.b)) else 17 end)) & f*a) when abs(~(count(distinct t1.e))-abs((~max(c)))-count(*) & min(t1.f)+max(11)) then  -cast(avg((b)) AS integer) else min(b) end from t1))*a FROM t1 WHERE NOT ((13)-(t1.a*17-t1.b)-coalesce((select (select  -cast(avg(t1.c) AS integer)+case  - -count(*) | (count(distinct t1.a)) when  -min(t1.e) then (max(t1.d)) else count(distinct t1.b) end from t1)-e+(abs(17)/abs(e)) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (d)>=13 and (t1.b not in (c,a, -t1.d) or t1.e in (select c from t1 union select t1.c from t1)) or 11<=t1.d))),17) in (select e from t1 union select e from t1))}
} {-20000}
do_test randexpr-2.1083 {
  db eval {SELECT case when (select  -min(11) from t1)<>(abs(17)/abs(t1.d | e)) then case 11+case 11 when b | e-e then 19+e else b end*(abs(t1.a)/abs(b | a)) | coalesce((select case when a in (select cast(avg(d) AS integer) from t1 union select  - - -max(c) from t1) or e not in (c,d,a) then +13 when t1.a>a then 19 else f end from t1 where t1.c=13 or f<>t1.e),a) when f then f else c end else t1.e end FROM t1 WHERE ~17 in (11,t1.c,19)}
} {}
do_test randexpr-2.1084 {
  db eval {SELECT case when (select  -min(11) from t1)<>(abs(17)/abs(t1.d | e)) then case 11+case 11 when b | e-e then 19+e else b end*(abs(t1.a)/abs(b | a)) | coalesce((select case when a in (select cast(avg(d) AS integer) from t1 union select  - - -max(c) from t1) or e not in (c,d,a) then +13 when t1.a>a then 19 else f end from t1 where t1.c=13 or f<>t1.e),a) when f then f else c end else t1.e end FROM t1 WHERE NOT (~17 in (11,t1.c,19))}
} {300}
do_test randexpr-2.1085 {
  db eval {SELECT case when (select  -min(11) from t1)<>(abs(17)/abs(t1.d & e)) then case 11+case 11 when b & e-e then 19+e else b end*(abs(t1.a)/abs(b & a)) & coalesce((select case when a in (select cast(avg(d) AS integer) from t1 union select  - - -max(c) from t1) or e not in (c,d,a) then +13 when t1.a>a then 19 else f end from t1 where t1.c=13 or f<>t1.e),a) when f then f else c end else t1.e end FROM t1 WHERE NOT (~17 in (11,t1.c,19))}
} {300}
do_test randexpr-2.1086 {
  db eval {SELECT (select case +cast(avg(+19) AS integer) when (abs(count(*))) then (cast(avg(e*t1.b) AS integer)) else cast(avg(t1.a) AS integer) end+count(*) | +max(f-t1.e*t1.e | (f)* -19+ -b*d) | count(*)*count(*)* -count(*) | ~count(distinct  -b)*cast(avg(t1.f) AS integer)+count(*) from t1)-t1.c+t1.b FROM t1 WHERE ((select  -count(*)+min(case ~coalesce((select max(d) from t1 where (not not exists(select 1 from t1 where t1.b not in ((select  -max(a)+(count(*)) from t1) | c+case when t1.e not in (13,e,c) then (t1.f) else t1.c end+17*c+19,c,e)))),t1.f) when (f) then t1.a else t1.f end | b | t1.a) from t1) in (c,t1.c+ -a,f))}
} {}
do_test randexpr-2.1087 {
  db eval {SELECT (select case +cast(avg(+19) AS integer) when (abs(count(*))) then (cast(avg(e*t1.b) AS integer)) else cast(avg(t1.a) AS integer) end+count(*) | +max(f-t1.e*t1.e | (f)* -19+ -b*d) | count(*)*count(*)* -count(*) | ~count(distinct  -b)*cast(avg(t1.f) AS integer)+count(*) from t1)-t1.c+t1.b FROM t1 WHERE NOT (((select  -count(*)+min(case ~coalesce((select max(d) from t1 where (not not exists(select 1 from t1 where t1.b not in ((select  -max(a)+(count(*)) from t1) | c+case when t1.e not in (13,e,c) then (t1.f) else t1.c end+17*c+19,c,e)))),t1.f) when (f) then t1.a else t1.f end | b | t1.a) from t1) in (c,t1.c+ -a,f)))}
} {-101}
do_test randexpr-2.1088 {
  db eval {SELECT (select case +cast(avg(+19) AS integer) when (abs(count(*))) then (cast(avg(e*t1.b) AS integer)) else cast(avg(t1.a) AS integer) end+count(*) & +max(f-t1.e*t1.e & (f)* -19+ -b*d) & count(*)*count(*)* -count(*) & ~count(distinct  -b)*cast(avg(t1.f) AS integer)+count(*) from t1)-t1.c+t1.b FROM t1 WHERE NOT (((select  -count(*)+min(case ~coalesce((select max(d) from t1 where (not not exists(select 1 from t1 where t1.b not in ((select  -max(a)+(count(*)) from t1) | c+case when t1.e not in (13,e,c) then (t1.f) else t1.c end+17*c+19,c,e)))),t1.f) when (f) then t1.a else t1.f end | b | t1.a) from t1) in (c,t1.c+ -a,f)))}
} {-36}
do_test randexpr-2.1089 {
  db eval {SELECT (coalesce((select (select  -~+ -abs(case cast(avg(a*t1.d) AS integer) when case ~case count(distinct ((abs(t1.a)/abs(d)))) when case cast(avg(17) AS integer)-count(*) when  -count(*) then count(distinct d) else (max(t1.d)) end*count(*) then count(distinct t1.c) else min(19) end-count(*) when cast(avg(t1.a) AS integer) then ((count(*))) else min(a) end then (count(*)) else max(e) end)*(count(*))*max(a) from t1) from t1 where (19>=(17))),d)) FROM t1 WHERE exists(select 1 from t1 where 19 in (t1.a*coalesce((select a from t1 where (11<case a when (t1.e+c-t1.a) then t1.b else t1.c end) or d between +t1.e-+coalesce((select max(coalesce((select (select cast(avg((19)) AS integer) from t1) from t1 where t1.e>t1.b),t1.e)) from t1 where e not between 13 and t1.c),(a))-t1.d and 13),13*b)-17, -b,17))}
} {}
do_test randexpr-2.1090 {
  db eval {SELECT (coalesce((select (select  -~+ -abs(case cast(avg(a*t1.d) AS integer) when case ~case count(distinct ((abs(t1.a)/abs(d)))) when case cast(avg(17) AS integer)-count(*) when  -count(*) then count(distinct d) else (max(t1.d)) end*count(*) then count(distinct t1.c) else min(19) end-count(*) when cast(avg(t1.a) AS integer) then ((count(*))) else min(a) end then (count(*)) else max(e) end)*(count(*))*max(a) from t1) from t1 where (19>=(17))),d)) FROM t1 WHERE NOT (exists(select 1 from t1 where 19 in (t1.a*coalesce((select a from t1 where (11<case a when (t1.e+c-t1.a) then t1.b else t1.c end) or d between +t1.e-+coalesce((select max(coalesce((select (select cast(avg((19)) AS integer) from t1) from t1 where t1.e>t1.b),t1.e)) from t1 where e not between 13 and t1.c),(a))-t1.d and 13),13*b)-17, -b,17)))}
} {-49900}
do_test randexpr-2.1091 {
  db eval {SELECT case when (coalesce((select max((select +max(c) from t1)) from t1 where t1.c<>t1.a),d) not in (t1.d,+case when 17>19 then e when t1.b<>+(select count(*) from t1) then t1.e else t1.d end,t1.c)) then (select count(*)-count(distinct t1.d)+ -max( -t1.c-a)*case cast(avg((f)) AS integer) when count(distinct d) then max((13)) else max(t1.d) end from t1)*t1.b else t1.c end |  -13*t1.d*t1.c FROM t1 WHERE c in (select case count(distinct ~(abs( -a)/abs(d))) when ~count(*) then ~min(coalesce((select max((abs(e)/abs(d))) from t1 where not exists(select 1 from t1 where t1.e>( -+t1.a-t1.e*17))),19))+count(*) else case ~ -cast(avg((11)) AS integer) | +cast(avg(d) AS integer) | (cast(avg(c) AS integer))+min(t1.e) when min(t1.c) then max(11) else  -count(*) end end+max(t1.c) from t1 union select  -count(*) from t1)}
} {}
do_test randexpr-2.1092 {
  db eval {SELECT case when (coalesce((select max((select +max(c) from t1)) from t1 where t1.c<>t1.a),d) not in (t1.d,+case when 17>19 then e when t1.b<>+(select count(*) from t1) then t1.e else t1.d end,t1.c)) then (select count(*)-count(distinct t1.d)+ -max( -t1.c-a)*case cast(avg((f)) AS integer) when count(distinct d) then max((13)) else max(t1.d) end from t1)*t1.b else t1.c end |  -13*t1.d*t1.c FROM t1 WHERE NOT (c in (select case count(distinct ~(abs( -a)/abs(d))) when ~count(*) then ~min(coalesce((select max((abs(e)/abs(d))) from t1 where not exists(select 1 from t1 where t1.e>( -+t1.a-t1.e*17))),19))+count(*) else case ~ -cast(avg((11)) AS integer) | +cast(avg(d) AS integer) | (cast(avg(c) AS integer))+min(t1.e) when min(t1.c) then max(11) else  -count(*) end end+max(t1.c) from t1 union select  -count(*) from t1))}
} {-1559700}
do_test randexpr-2.1093 {
  db eval {SELECT case when (coalesce((select max((select +max(c) from t1)) from t1 where t1.c<>t1.a),d) not in (t1.d,+case when 17>19 then e when t1.b<>+(select count(*) from t1) then t1.e else t1.d end,t1.c)) then (select count(*)-count(distinct t1.d)+ -max( -t1.c-a)*case cast(avg((f)) AS integer) when count(distinct d) then max((13)) else max(t1.d) end from t1)*t1.b else t1.c end &  -13*t1.d*t1.c FROM t1 WHERE NOT (c in (select case count(distinct ~(abs( -a)/abs(d))) when ~count(*) then ~min(coalesce((select max((abs(e)/abs(d))) from t1 where not exists(select 1 from t1 where t1.e>( -+t1.a-t1.e*17))),19))+count(*) else case ~ -cast(avg((11)) AS integer) | +cast(avg(d) AS integer) | (cast(avg(c) AS integer))+min(t1.e) when min(t1.c) then max(11) else  -count(*) end end+max(t1.c) from t1 union select  -count(*) from t1))}
} {0}
do_test randexpr-2.1094 {
  db eval {SELECT coalesce((select max(t1.c+t1.b-t1.b+(abs(d++t1.f)/abs(t1.a)) | 13*17) from t1 where coalesce((select 11 from t1 where case case case c when d then t1.d else 13 end when b then  -11 else t1.b end when 13 then (t1.a) else d end not in (c,13,a)),t1.c) | f not in (t1.a,t1.c,13) and not exists(select 1 from t1 where t1.c in (select e from t1 union select  -11 from t1))),t1.f) FROM t1 WHERE (((13+coalesce((select max(13) from t1 where not exists(select 1 from t1 where ((abs(c-case when not exists(select 1 from t1 where ((f) between c and 13)) then (select case min(f) when max(17) then min(13) else min(b) end from t1) when 17 in (t1.e,13,f) then  -13 else 11 end)/abs(t1.f)) in (select min(c) from t1 union select  -count(*) | + -min(19) from t1))) and f<13),t1.e+t1.c) in (select count(distinct c)-count(*) from t1 union select  -case min((e))+cast(avg(t1.a) AS integer) when ((min(t1.c))) then count(distinct e) else  -cast(avg(t1.d) AS integer) end from t1))))}
} {}
do_test randexpr-2.1095 {
  db eval {SELECT coalesce((select max(t1.c+t1.b-t1.b+(abs(d++t1.f)/abs(t1.a)) | 13*17) from t1 where coalesce((select 11 from t1 where case case case c when d then t1.d else 13 end when b then  -11 else t1.b end when 13 then (t1.a) else d end not in (c,13,a)),t1.c) | f not in (t1.a,t1.c,13) and not exists(select 1 from t1 where t1.c in (select e from t1 union select  -11 from t1))),t1.f) FROM t1 WHERE NOT ((((13+coalesce((select max(13) from t1 where not exists(select 1 from t1 where ((abs(c-case when not exists(select 1 from t1 where ((f) between c and 13)) then (select case min(f) when max(17) then min(13) else min(b) end from t1) when 17 in (t1.e,13,f) then  -13 else 11 end)/abs(t1.f)) in (select min(c) from t1 union select  -count(*) | + -min(19) from t1))) and f<13),t1.e+t1.c) in (select count(distinct c)-count(*) from t1 union select  -case min((e))+cast(avg(t1.a) AS integer) when ((min(t1.c))) then count(distinct e) else  -cast(avg(t1.d) AS integer) end from t1)))))}
} {511}
do_test randexpr-2.1096 {
  db eval {SELECT coalesce((select max(t1.c+t1.b-t1.b+(abs(d++t1.f)/abs(t1.a)) & 13*17) from t1 where coalesce((select 11 from t1 where case case case c when d then t1.d else 13 end when b then  -11 else t1.b end when 13 then (t1.a) else d end not in (c,13,a)),t1.c) & f not in (t1.a,t1.c,13) and not exists(select 1 from t1 where t1.c in (select e from t1 union select  -11 from t1))),t1.f) FROM t1 WHERE NOT ((((13+coalesce((select max(13) from t1 where not exists(select 1 from t1 where ((abs(c-case when not exists(select 1 from t1 where ((f) between c and 13)) then (select case min(f) when max(17) then min(13) else min(b) end from t1) when 17 in (t1.e,13,f) then  -13 else 11 end)/abs(t1.f)) in (select min(c) from t1 union select  -count(*) | + -min(19) from t1))) and f<13),t1.e+t1.c) in (select count(distinct c)-count(*) from t1 union select  -case min((e))+cast(avg(t1.a) AS integer) when ((min(t1.c))) then count(distinct e) else  -cast(avg(t1.d) AS integer) end from t1)))))}
} {20}
do_test randexpr-2.1097 {
  db eval {SELECT case when t1.a in (select t1.e*case when t1.b between t1.d and 11 or c-case when (t1.e=13) then ~e when e<>a then t1.d else t1.f end in (11,t1.e,t1.c) and 11 not between t1.a and 13 and 19<11 then 11 else t1.e end*t1.d from t1 union select t1.c from t1) then a when e between e and b then ((19)) else 11 end FROM t1 WHERE coalesce((select (select count(distinct t1.f) from t1) from t1 where case coalesce((select max(t1.d) from t1 where 17<>19),t1.d) when a then coalesce((select ~t1.f- - -c-c*17-f-c-t1.a from t1 where (t1.f) in (select max(11) from t1 union select ~cast(avg(17) AS integer) | ~count(*)+max(f)- -cast(avg(11) AS integer) from t1)),13) else e end in (a,t1.c,11)),c)>=t1.e}
} {}
do_test randexpr-2.1098 {
  db eval {SELECT case when t1.a in (select t1.e*case when t1.b between t1.d and 11 or c-case when (t1.e=13) then ~e when e<>a then t1.d else t1.f end in (11,t1.e,t1.c) and 11 not between t1.a and 13 and 19<11 then 11 else t1.e end*t1.d from t1 union select t1.c from t1) then a when e between e and b then ((19)) else 11 end FROM t1 WHERE NOT (coalesce((select (select count(distinct t1.f) from t1) from t1 where case coalesce((select max(t1.d) from t1 where 17<>19),t1.d) when a then coalesce((select ~t1.f- - -c-c*17-f-c-t1.a from t1 where (t1.f) in (select max(11) from t1 union select ~cast(avg(17) AS integer) | ~count(*)+max(f)- -cast(avg(11) AS integer) from t1)),13) else e end in (a,t1.c,11)),c)>=t1.e)}
} {11}
do_test randexpr-2.1099 {
  db eval {SELECT coalesce((select max(case t1.b+(select ~((cast(avg(17) AS integer)))*min(a)+ -count(distinct b)*cast(avg(t1.b) AS integer)-count(*)+max(19) from t1)-(e) when d then 13 else 13*c end+t1.c) from t1 where t1.b in (select +cast(avg(e) AS integer)*case count(*) when cast(avg(13) AS integer) then count(distinct t1.b) else count(*) end-(count(distinct 19))*min(t1.d) from t1 union select max(a) from t1)),(f))*e+t1.f*19 FROM t1 WHERE 17 not between  -t1.e and d}
} {}
do_test randexpr-2.1100 {
  db eval {SELECT coalesce((select max(case t1.b+(select ~((cast(avg(17) AS integer)))*min(a)+ -count(distinct b)*cast(avg(t1.b) AS integer)-count(*)+max(19) from t1)-(e) when d then 13 else 13*c end+t1.c) from t1 where t1.b in (select +cast(avg(e) AS integer)*case count(*) when cast(avg(13) AS integer) then count(distinct t1.b) else count(*) end-(count(distinct 19))*min(t1.d) from t1 union select max(a) from t1)),(f))*e+t1.f*19 FROM t1 WHERE NOT (17 not between  -t1.e and d)}
} {311400}
do_test randexpr-2.1101 {
  db eval {SELECT coalesce((select max(~19) from t1 where 11 in (select t1.b-11*coalesce((select max(b) from t1 where coalesce((select max(e) from t1 where c*case 19*19+coalesce((select 19 from t1 where (11 not in (13+t1.d,b,(11)))),13)*d when t1.e then t1.b else t1.b end+t1.e between d and t1.b),t1.b) | (f)<>13), - -17)+c from t1 union select  -19 from t1)),17) FROM t1 WHERE ~t1.d not between 11*13-+t1.d-11-f and t1.d}
} {}
do_test randexpr-2.1102 {
  db eval {SELECT coalesce((select max(~19) from t1 where 11 in (select t1.b-11*coalesce((select max(b) from t1 where coalesce((select max(e) from t1 where c*case 19*19+coalesce((select 19 from t1 where (11 not in (13+t1.d,b,(11)))),13)*d when t1.e then t1.b else t1.b end+t1.e between d and t1.b),t1.b) | (f)<>13), - -17)+c from t1 union select  -19 from t1)),17) FROM t1 WHERE NOT (~t1.d not between 11*13-+t1.d-11-f and t1.d)}
} {17}
do_test randexpr-2.1103 {
  db eval {SELECT coalesce((select max(~19) from t1 where 11 in (select t1.b-11*coalesce((select max(b) from t1 where coalesce((select max(e) from t1 where c*case 19*19+coalesce((select 19 from t1 where (11 not in (13+t1.d,b,(11)))),13)*d when t1.e then t1.b else t1.b end+t1.e between d and t1.b),t1.b) & (f)<>13), - -17)+c from t1 union select  -19 from t1)),17) FROM t1 WHERE NOT (~t1.d not between 11*13-+t1.d-11-f and t1.d)}
} {17}
do_test randexpr-2.1104 {
  db eval {SELECT case t1.b when coalesce((select max(17+coalesce((select max(coalesce((select (select count(distinct case f when 19 then coalesce((select coalesce((select max(11-(abs(d)/abs(11))) from t1 where not  -a in (19,t1.b,17)),17) from t1 where (f in (b,f,t1.a))),b) else b end) from t1) from t1 where 17 between e and t1.f),t1.a)) from t1 where 13>=e),b)) from t1 where t1.f>t1.f),t1.b) then 17 else t1.f end FROM t1 WHERE not exists(select 1 from t1 where 13 between a+17 and (t1.c))}
} {17}
do_test randexpr-2.1105 {
  db eval {SELECT case t1.b when coalesce((select max(17+coalesce((select max(coalesce((select (select count(distinct case f when 19 then coalesce((select coalesce((select max(11-(abs(d)/abs(11))) from t1 where not  -a in (19,t1.b,17)),17) from t1 where (f in (b,f,t1.a))),b) else b end) from t1) from t1 where 17 between e and t1.f),t1.a)) from t1 where 13>=e),b)) from t1 where t1.f>t1.f),t1.b) then 17 else t1.f end FROM t1 WHERE NOT (not exists(select 1 from t1 where 13 between a+17 and (t1.c)))}
} {}
do_test randexpr-2.1106 {
  db eval {SELECT case when coalesce((select max(d) from t1 where t1.a in (select a-a from t1 union select a from t1)),t1.b)*(select max(t1.b) from t1)>=case when t1.b<case 17 when 19 then t1.a else t1.a end then b when 17<19 then t1.e else t1.b end and (t1.e=t1.c or (not exists(select 1 from t1 where not exists(select 1 from t1 where a=(13)))) or t1.b between 17 and t1.d and b in (t1.f,f,13) or t1.d<e) then t1.c when t1.c between 19 and 11 then d else a end FROM t1 WHERE t1.c>=t1.a}
} {300}
do_test randexpr-2.1107 {
  db eval {SELECT case when coalesce((select max(d) from t1 where t1.a in (select a-a from t1 union select a from t1)),t1.b)*(select max(t1.b) from t1)>=case when t1.b<case 17 when 19 then t1.a else t1.a end then b when 17<19 then t1.e else t1.b end and (t1.e=t1.c or (not exists(select 1 from t1 where not exists(select 1 from t1 where a=(13)))) or t1.b between 17 and t1.d and b in (t1.f,f,13) or t1.d<e) then t1.c when t1.c between 19 and 11 then d else a end FROM t1 WHERE NOT (t1.c>=t1.a)}
} {}
do_test randexpr-2.1108 {
  db eval {SELECT case when case when f*~case when t1.c*t1.f in (c,t1.b,(17)) then 17 when 11>t1.c then 13 else t1.e end+t1.f in (select +max(e)+case (count(distinct a)*count(*))+max(19) when  -max(11) then count(distinct a) else ((count(distinct t1.d))) end from t1 union select count(distinct c) from t1) then 17 else d end+(t1.c)<17 then b when not exists(select 1 from t1 where 11>t1.b) then t1.d else t1.a end FROM t1 WHERE t1.b< -f}
} {}
do_test randexpr-2.1109 {
  db eval {SELECT case when case when f*~case when t1.c*t1.f in (c,t1.b,(17)) then 17 when 11>t1.c then 13 else t1.e end+t1.f in (select +max(e)+case (count(distinct a)*count(*))+max(19) when  -max(11) then count(distinct a) else ((count(distinct t1.d))) end from t1 union select count(distinct c) from t1) then 17 else d end+(t1.c)<17 then b when not exists(select 1 from t1 where 11>t1.b) then t1.d else t1.a end FROM t1 WHERE NOT (t1.b< -f)}
} {400}
do_test randexpr-2.1110 {
  db eval {SELECT (select cast(avg(f) AS integer) | ~++cast(avg((abs(17)/abs( -f+(c-coalesce((select case when c=d and t1.e=t1.b then e when e in (t1.b,19,t1.c) then 17 else d end from t1 where e between t1.a and t1.c),a))+a))) AS integer)-abs( -min(t1.c))-abs(max((t1.b)) |  -~(count(*))+max(17))+cast(avg(t1.a) AS integer) | min(a)*(count(*))*min(17) from t1) FROM t1 WHERE b-(t1.e*t1.e)-t1.d=t1.c}
} {}
do_test randexpr-2.1111 {
  db eval {SELECT (select cast(avg(f) AS integer) | ~++cast(avg((abs(17)/abs( -f+(c-coalesce((select case when c=d and t1.e=t1.b then e when e in (t1.b,19,t1.c) then 17 else d end from t1 where e between t1.a and t1.c),a))+a))) AS integer)-abs( -min(t1.c))-abs(max((t1.b)) |  -~(count(*))+max(17))+cast(avg(t1.a) AS integer) | min(a)*(count(*))*min(17) from t1) FROM t1 WHERE NOT (b-(t1.e*t1.e)-t1.d=t1.c)}
} {-260}
do_test randexpr-2.1112 {
  db eval {SELECT (select cast(avg(f) AS integer) & ~++cast(avg((abs(17)/abs( -f+(c-coalesce((select case when c=d and t1.e=t1.b then e when e in (t1.b,19,t1.c) then 17 else d end from t1 where e between t1.a and t1.c),a))+a))) AS integer)-abs( -min(t1.c))-abs(max((t1.b)) &  -~(count(*))+max(17))+cast(avg(t1.a) AS integer) & min(a)*(count(*))*min(17) from t1) FROM t1 WHERE NOT (b-(t1.e*t1.e)-t1.d=t1.c)}
} {512}
do_test randexpr-2.1113 {
  db eval {SELECT ~+coalesce((select case when t1.f>d then b when (abs(t1.a)/abs((abs(f)/abs(t1.c))))*case ~b when e then (select cast(avg( -+t1.f) AS integer) from t1) else c end+coalesce((select max(17*case t1.a+b when t1.b then t1.d else t1.f end) from t1 where d=e),t1.f)+13>=17 then 19 else f end from t1 where t1.a in (select d from t1 union select e from t1)),b) FROM t1 WHERE 17<>f-~t1.a-case when  -b in (t1.b,(select min( -coalesce((select max(coalesce((select a- -t1.b from t1 where 11 in (t1.b,13, -t1.e) and f not between  -13 and t1.b),c)) from t1 where b not in (a,11,17)),t1.e)) from t1),e) or not exists(select 1 from t1 where t1.c in (select t1.b from t1 union select t1.b from t1)) then coalesce((select  -t1.e from t1 where e<>t1.e),f) when not t1.e<>t1.c then 19 else e end}
} {-201}
do_test randexpr-2.1114 {
  db eval {SELECT ~+coalesce((select case when t1.f>d then b when (abs(t1.a)/abs((abs(f)/abs(t1.c))))*case ~b when e then (select cast(avg( -+t1.f) AS integer) from t1) else c end+coalesce((select max(17*case t1.a+b when t1.b then t1.d else t1.f end) from t1 where d=e),t1.f)+13>=17 then 19 else f end from t1 where t1.a in (select d from t1 union select e from t1)),b) FROM t1 WHERE NOT (17<>f-~t1.a-case when  -b in (t1.b,(select min( -coalesce((select max(coalesce((select a- -t1.b from t1 where 11 in (t1.b,13, -t1.e) and f not between  -13 and t1.b),c)) from t1 where b not in (a,11,17)),t1.e)) from t1),e) or not exists(select 1 from t1 where t1.c in (select t1.b from t1 union select t1.b from t1)) then coalesce((select  -t1.e from t1 where e<>t1.e),f) when not t1.e<>t1.c then 19 else e end)}
} {}
do_test randexpr-2.1115 {
  db eval {SELECT d- -e*(abs(t1.c)/abs(d)) | t1.a+ -coalesce((select max(t1.e) from t1 where case when case when (a in (13,b,t1.b)) and d in (t1.c,17,a) then 17+t1.e when 19>=t1.b then a else 11 end=t1.f and d between c and (d) then (abs(17)/abs(d)) else t1.d end*f>e and not f<=13 and  -t1.f>=t1.e and t1.b<t1.b),t1.e)-case when t1.c<>e then t1.b else c end FROM t1 WHERE b-coalesce((select (coalesce((select max((coalesce((select d from t1 where not  -case when case 13 when +~(select case count(*) when  -max(t1.b) then max(a) else min(c) end from t1) then c else  -a end in (17,t1.b,(b)) then f else b end-f+17<=t1.a),t1.f)-d)) from t1 where t1.e=b),t1.b)) from t1 where (t1.a=t1.c)), -t1.a) not between 19 and 19}
} {-584}
do_test randexpr-2.1116 {
  db eval {SELECT d- -e*(abs(t1.c)/abs(d)) | t1.a+ -coalesce((select max(t1.e) from t1 where case when case when (a in (13,b,t1.b)) and d in (t1.c,17,a) then 17+t1.e when 19>=t1.b then a else 11 end=t1.f and d between c and (d) then (abs(17)/abs(d)) else t1.d end*f>e and not f<=13 and  -t1.f>=t1.e and t1.b<t1.b),t1.e)-case when t1.c<>e then t1.b else c end FROM t1 WHERE NOT (b-coalesce((select (coalesce((select max((coalesce((select d from t1 where not  -case when case 13 when +~(select case count(*) when  -max(t1.b) then max(a) else min(c) end from t1) then c else  -a end in (17,t1.b,(b)) then f else b end-f+17<=t1.a),t1.f)-d)) from t1 where t1.e=b),t1.b)) from t1 where (t1.a=t1.c)), -t1.a) not between 19 and 19)}
} {}
do_test randexpr-2.1117 {
  db eval {SELECT d- -e*(abs(t1.c)/abs(d)) & t1.a+ -coalesce((select max(t1.e) from t1 where case when case when (a in (13,b,t1.b)) and d in (t1.c,17,a) then 17+t1.e when 19>=t1.b then a else 11 end=t1.f and d between c and (d) then (abs(17)/abs(d)) else t1.d end*f>e and not f<=13 and  -t1.f>=t1.e and t1.b<t1.b),t1.e)-case when t1.c<>e then t1.b else c end FROM t1 WHERE b-coalesce((select (coalesce((select max((coalesce((select d from t1 where not  -case when case 13 when +~(select case count(*) when  -max(t1.b) then max(a) else min(c) end from t1) then c else  -a end in (17,t1.b,(b)) then f else b end-f+17<=t1.a),t1.f)-d)) from t1 where t1.e=b),t1.b)) from t1 where (t1.a=t1.c)), -t1.a) not between 19 and 19}
} {384}
do_test randexpr-2.1118 {
  db eval {SELECT 19-case 13-f when b then t1.a*11-t1.d-+17*t1.b-coalesce((select 17 from t1 where 13<=f),+coalesce((select (abs(17+~coalesce((select a from t1 where 11<>t1.b and 11 not between t1.e and 19),17)+t1.e+t1.d | b)/abs(c))+f from t1 where 19 not between 19 and c),d)) else 19 end*t1.e+b FROM t1 WHERE 11+11 not in (t1.c,t1.e,19) and f+19*19*case when ~t1.a+19*b between t1.a-case case when f=(t1.d) then ((t1.d)) else  -d end*e when c then e else t1.a end*t1.e and c then t1.e else b end in (select d from t1 union select t1.a from t1) or t1.d>=t1.f or not exists(select 1 from t1 where a<=13)}
} {-9281}
do_test randexpr-2.1119 {
  db eval {SELECT 19-case 13-f when b then t1.a*11-t1.d-+17*t1.b-coalesce((select 17 from t1 where 13<=f),+coalesce((select (abs(17+~coalesce((select a from t1 where 11<>t1.b and 11 not between t1.e and 19),17)+t1.e+t1.d | b)/abs(c))+f from t1 where 19 not between 19 and c),d)) else 19 end*t1.e+b FROM t1 WHERE NOT (11+11 not in (t1.c,t1.e,19) and f+19*19*case when ~t1.a+19*b between t1.a-case case when f=(t1.d) then ((t1.d)) else  -d end*e when c then e else t1.a end*t1.e and c then t1.e else b end in (select d from t1 union select t1.a from t1) or t1.d>=t1.f or not exists(select 1 from t1 where a<=13))}
} {}
do_test randexpr-2.1120 {
  db eval {SELECT 19-case 13-f when b then t1.a*11-t1.d-+17*t1.b-coalesce((select 17 from t1 where 13<=f),+coalesce((select (abs(17+~coalesce((select a from t1 where 11<>t1.b and 11 not between t1.e and 19),17)+t1.e+t1.d & b)/abs(c))+f from t1 where 19 not between 19 and c),d)) else 19 end*t1.e+b FROM t1 WHERE 11+11 not in (t1.c,t1.e,19) and f+19*19*case when ~t1.a+19*b between t1.a-case case when f=(t1.d) then ((t1.d)) else  -d end*e when c then e else t1.a end*t1.e and c then t1.e else b end in (select d from t1 union select t1.a from t1) or t1.d>=t1.f or not exists(select 1 from t1 where a<=13)}
} {-9281}
do_test randexpr-2.1121 {
  db eval {SELECT case 19 when e then t1.b-t1.d else 11+coalesce((select 19 from t1 where not (t1.a)+(abs(case coalesce((select coalesce((select t1.e from t1 where 11=d),a) from t1 where t1.d<=13),a) when 17 then 13 else t1.a end)/abs(t1.b))-t1.d*e+t1.d not between b and b or e in (select  -min(c) from t1 union select min(t1.b) from t1)),(abs(e)/abs(t1.b)))+t1.c end FROM t1 WHERE exists(select 1 from t1 where c in (select t1.a from t1 union select f from t1))}
} {}
do_test randexpr-2.1122 {
  db eval {SELECT case 19 when e then t1.b-t1.d else 11+coalesce((select 19 from t1 where not (t1.a)+(abs(case coalesce((select coalesce((select t1.e from t1 where 11=d),a) from t1 where t1.d<=13),a) when 17 then 13 else t1.a end)/abs(t1.b))-t1.d*e+t1.d not between b and b or e in (select  -min(c) from t1 union select min(t1.b) from t1)),(abs(e)/abs(t1.b)))+t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where c in (select t1.a from t1 union select f from t1)))}
} {313}
do_test randexpr-2.1123 {
  db eval {SELECT 17 | t1.d-(select +max(case when not exists(select 1 from t1 where (a<=t1.f)) then  -19 else  -t1.d end)- -min(t1.f+t1.f-(select (count(*)) from t1)) from t1)- -19 | b-d+coalesce((select max(d) from t1 where e-t1.a in (19,b,11) or e in (19,t1.b,c)),11) FROM t1 WHERE (11<=11 and case coalesce((select max((f)) from t1 where t1.b | case 11 when t1.e*t1.e then e else case when ~b-case when 19 not in (t1.d,13,e) then 13 when c between t1.e and b then 19 else t1.c end-(c) in (select  -t1.f from t1 union select d from t1) then c else t1.b end end*t1.a in (19,e,c)),t1.a) when t1.d then t1.a else  -a end not in (t1.c,b,t1.f))}
} {-41}
do_test randexpr-2.1124 {
  db eval {SELECT 17 | t1.d-(select +max(case when not exists(select 1 from t1 where (a<=t1.f)) then  -19 else  -t1.d end)- -min(t1.f+t1.f-(select (count(*)) from t1)) from t1)- -19 | b-d+coalesce((select max(d) from t1 where e-t1.a in (19,b,11) or e in (19,t1.b,c)),11) FROM t1 WHERE NOT ((11<=11 and case coalesce((select max((f)) from t1 where t1.b | case 11 when t1.e*t1.e then e else case when ~b-case when 19 not in (t1.d,13,e) then 13 when c between t1.e and b then 19 else t1.c end-(c) in (select  -t1.f from t1 union select d from t1) then c else t1.b end end*t1.a in (19,e,c)),t1.a) when t1.d then t1.a else  -a end not in (t1.c,b,t1.f)))}
} {}
do_test randexpr-2.1125 {
  db eval {SELECT 17 & t1.d-(select +max(case when not exists(select 1 from t1 where (a<=t1.f)) then  -19 else  -t1.d end)- -min(t1.f+t1.f-(select (count(*)) from t1)) from t1)- -19 & b-d+coalesce((select max(d) from t1 where e-t1.a in (19,b,11) or e in (19,t1.b,c)),11) FROM t1 WHERE (11<=11 and case coalesce((select max((f)) from t1 where t1.b | case 11 when t1.e*t1.e then e else case when ~b-case when 19 not in (t1.d,13,e) then 13 when c between t1.e and b then 19 else t1.c end-(c) in (select  -t1.f from t1 union select d from t1) then c else t1.b end end*t1.a in (19,e,c)),t1.a) when t1.d then t1.a else  -a end not in (t1.c,b,t1.f))}
} {0}
do_test randexpr-2.1126 {
  db eval {SELECT case t1.e-d+b when coalesce((select (select max(t1.a | a |  -(select (count(*))+( - - -count(*)) from t1)*19+ -f+t1.e) from t1) from t1 where not exists(select 1 from t1 where (d not between a and 11) or not d>=11 and exists(select 1 from t1 where not t1.a<>13)) or 19 not in (17,t1.c,t1.c)),19)*t1.c+d then b else c end-b FROM t1 WHERE c<17}
} {}
do_test randexpr-2.1127 {
  db eval {SELECT case t1.e-d+b when coalesce((select (select max(t1.a | a |  -(select (count(*))+( - - -count(*)) from t1)*19+ -f+t1.e) from t1) from t1 where not exists(select 1 from t1 where (d not between a and 11) or not d>=11 and exists(select 1 from t1 where not t1.a<>13)) or 19 not in (17,t1.c,t1.c)),19)*t1.c+d then b else c end-b FROM t1 WHERE NOT (c<17)}
} {100}
do_test randexpr-2.1128 {
  db eval {SELECT case t1.e-d+b when coalesce((select (select max(t1.a & a &  -(select (count(*))+( - - -count(*)) from t1)*19+ -f+t1.e) from t1) from t1 where not exists(select 1 from t1 where (d not between a and 11) or not d>=11 and exists(select 1 from t1 where not t1.a<>13)) or 19 not in (17,t1.c,t1.c)),19)*t1.c+d then b else c end-b FROM t1 WHERE NOT (c<17)}
} {100}
do_test randexpr-2.1129 {
  db eval {SELECT f*f*(abs(case when (17-coalesce((select max(11) from t1 where coalesce((select max(t1.c-11*t1.a) from t1 where +e=(abs(d)/abs(11))+ -13),t1.b)<b and exists(select 1 from t1 where t1.f between d and  -t1.c)),19)-19 in (select max(t1.e) | min(t1.e) from t1 union select count(*) from t1) and 17>t1.e) then e else 17 end)/abs(c)) FROM t1 WHERE (t1.a in ((t1.f-t1.c)+b,11,t1.a+f))}
} {}
do_test randexpr-2.1130 {
  db eval {SELECT f*f*(abs(case when (17-coalesce((select max(11) from t1 where coalesce((select max(t1.c-11*t1.a) from t1 where +e=(abs(d)/abs(11))+ -13),t1.b)<b and exists(select 1 from t1 where t1.f between d and  -t1.c)),19)-19 in (select max(t1.e) | min(t1.e) from t1 union select count(*) from t1) and 17>t1.e) then e else 17 end)/abs(c)) FROM t1 WHERE NOT ((t1.a in ((t1.f-t1.c)+b,11,t1.a+f)))}
} {0}
do_test randexpr-2.1131 {
  db eval {SELECT f*f*(abs(case when (17-coalesce((select max(11) from t1 where coalesce((select max(t1.c-11*t1.a) from t1 where +e=(abs(d)/abs(11))+ -13),t1.b)<b and exists(select 1 from t1 where t1.f between d and  -t1.c)),19)-19 in (select max(t1.e) & min(t1.e) from t1 union select count(*) from t1) and 17>t1.e) then e else 17 end)/abs(c)) FROM t1 WHERE NOT ((t1.a in ((t1.f-t1.c)+b,11,t1.a+f)))}
} {0}
do_test randexpr-2.1132 {
  db eval {SELECT ( -19-f+coalesce((select max( -~case when case 11 when ~coalesce((select max(13) from t1 where not (e)<>(t1.c)),19)+11 |  -19-f then  -13 else t1.c end-e<=t1.a then 11 when not exists(select 1 from t1 where (not t1.c<19) and not (13<>17)) then  -e else f end) from t1 where (b)<=t1.e),t1.d)+ -t1.c) | b FROM t1 WHERE (~(select (max(f)-count(distinct c)) from t1) | case when e>=t1.c then t1.b+(select abs(count(*)+max(c)*abs(count(distinct e)+max(t1.f))+cast(avg(c) AS integer)) | cast(avg(t1.d) AS integer)*min(11) from t1)-t1.c else c end in (select case  -t1.b when 17 then 17 else  -case when not t1.c not in (17,t1.d,17) then 19 else a end end from t1 union select a from t1)) or (11)<=t1.b}
} {-771}
do_test randexpr-2.1133 {
  db eval {SELECT ( -19-f+coalesce((select max( -~case when case 11 when ~coalesce((select max(13) from t1 where not (e)<>(t1.c)),19)+11 |  -19-f then  -13 else t1.c end-e<=t1.a then 11 when not exists(select 1 from t1 where (not t1.c<19) and not (13<>17)) then  -e else f end) from t1 where (b)<=t1.e),t1.d)+ -t1.c) | b FROM t1 WHERE NOT ((~(select (max(f)-count(distinct c)) from t1) | case when e>=t1.c then t1.b+(select abs(count(*)+max(c)*abs(count(distinct e)+max(t1.f))+cast(avg(c) AS integer)) | cast(avg(t1.d) AS integer)*min(11) from t1)-t1.c else c end in (select case  -t1.b when 17 then 17 else  -case when not t1.c not in (17,t1.d,17) then 19 else a end end from t1 union select a from t1)) or (11)<=t1.b)}
} {}
do_test randexpr-2.1134 {
  db eval {SELECT ( -19-f+coalesce((select max( -~case when case 11 when ~coalesce((select max(13) from t1 where not (e)<>(t1.c)),19)+11 &  -19-f then  -13 else t1.c end-e<=t1.a then 11 when not exists(select 1 from t1 where (not t1.c<19) and not (13<>17)) then  -e else f end) from t1 where (b)<=t1.e),t1.d)+ -t1.c) & b FROM t1 WHERE (~(select (max(f)-count(distinct c)) from t1) | case when e>=t1.c then t1.b+(select abs(count(*)+max(c)*abs(count(distinct e)+max(t1.f))+cast(avg(c) AS integer)) | cast(avg(t1.d) AS integer)*min(11) from t1)-t1.c else c end in (select case  -t1.b when 17 then 17 else  -case when not t1.c not in (17,t1.d,17) then 19 else a end end from t1 union select a from t1)) or (11)<=t1.b}
} {64}
do_test randexpr-2.1135 {
  db eval {SELECT +case when (not exists(select 1 from t1 where (abs(t1.a+coalesce((select max(b+ -case when e=t1.f then (abs(d)/abs(t1.e)) when not exists(select 1 from t1 where 17<t1.c) then d else f end |  -(t1.e) | 13*e) from t1 where f in (select t1.e from t1 union select t1.f from t1)),d) | 11)/abs(t1.b))-b not between b and t1.d) and t1.d>t1.c) then e else e end FROM t1 WHERE not t1.d-d+case b when t1.a+t1.a then t1.f+ -t1.e else 11+b*coalesce((select max(t1.f) from t1 where 11>= -f+t1.d),t1.c)*19 end not between d and t1.c-(11)+17}
} {}
do_test randexpr-2.1136 {
  db eval {SELECT +case when (not exists(select 1 from t1 where (abs(t1.a+coalesce((select max(b+ -case when e=t1.f then (abs(d)/abs(t1.e)) when not exists(select 1 from t1 where 17<t1.c) then d else f end |  -(t1.e) | 13*e) from t1 where f in (select t1.e from t1 union select t1.f from t1)),d) | 11)/abs(t1.b))-b not between b and t1.d) and t1.d>t1.c) then e else e end FROM t1 WHERE NOT (not t1.d-d+case b when t1.a+t1.a then t1.f+ -t1.e else 11+b*coalesce((select max(t1.f) from t1 where 11>= -f+t1.d),t1.c)*19 end not between d and t1.c-(11)+17)}
} {500}
do_test randexpr-2.1137 {
  db eval {SELECT +case when (not exists(select 1 from t1 where (abs(t1.a+coalesce((select max(b+ -case when e=t1.f then (abs(d)/abs(t1.e)) when not exists(select 1 from t1 where 17<t1.c) then d else f end &  -(t1.e) & 13*e) from t1 where f in (select t1.e from t1 union select t1.f from t1)),d) & 11)/abs(t1.b))-b not between b and t1.d) and t1.d>t1.c) then e else e end FROM t1 WHERE NOT (not t1.d-d+case b when t1.a+t1.a then t1.f+ -t1.e else 11+b*coalesce((select max(t1.f) from t1 where 11>= -f+t1.d),t1.c)*19 end not between d and t1.c-(11)+17)}
} {500}
do_test randexpr-2.1138 {
  db eval {SELECT t1.d+case when (t1.a)<=11 then ~t1.a else ~19 end-+~ -coalesce((select t1.d from t1 where ~t1.f in (select (cast(avg(t1.e+c) AS integer)) from t1 union select count(distinct (abs(coalesce((select max(19) from t1 where not ~11-t1.a=t1.c+case when t1.d between c and t1.d then 11 when t1.f>=17 then f else 19 end*t1.c),17)+f)/abs(f))) from t1)),11) FROM t1 WHERE e>c}
} {370}
do_test randexpr-2.1139 {
  db eval {SELECT t1.d+case when (t1.a)<=11 then ~t1.a else ~19 end-+~ -coalesce((select t1.d from t1 where ~t1.f in (select (cast(avg(t1.e+c) AS integer)) from t1 union select count(distinct (abs(coalesce((select max(19) from t1 where not ~11-t1.a=t1.c+case when t1.d between c and t1.d then 11 when t1.f>=17 then f else 19 end*t1.c),17)+f)/abs(f))) from t1)),11) FROM t1 WHERE NOT (e>c)}
} {}
do_test randexpr-2.1140 {
  db eval {SELECT case when coalesce((select max(case b | d*(abs(t1.e)/abs(a))-f | t1.b when t1.e then coalesce((select max(t1.e) from t1 where t1.e between (select ~count(*)*cast(avg(19) AS integer) from t1) and case c when a then 13 else a end),t1.f)+e*c else t1.d end) from t1 where t1.a in (select t1.d from t1 union select 17 from t1)),e)+17<19 then t1.a else 19 end | 11+e-17*19 FROM t1 WHERE d*t1.c-case when case when ((13 in (17+e,b,11)) or 19>(13)) then (abs(coalesce((select t1.a from t1 where t1.a not in (13,c,t1.f)),11))/abs(t1.e))-f when t1.b not between t1.b and f then t1.d else t1.a end in (a,e,t1.d) then t1.f else t1.f end+f+t1.e in (t1.d,e,b)}
} {}
do_test randexpr-2.1141 {
  db eval {SELECT case when coalesce((select max(case b | d*(abs(t1.e)/abs(a))-f | t1.b when t1.e then coalesce((select max(t1.e) from t1 where t1.e between (select ~count(*)*cast(avg(19) AS integer) from t1) and case c when a then 13 else a end),t1.f)+e*c else t1.d end) from t1 where t1.a in (select t1.d from t1 union select 17 from t1)),e)+17<19 then t1.a else 19 end | 11+e-17*19 FROM t1 WHERE NOT (d*t1.c-case when case when ((13 in (17+e,b,11)) or 19>(13)) then (abs(coalesce((select t1.a from t1 where t1.a not in (13,c,t1.f)),11))/abs(t1.e))-f when t1.b not between t1.b and f then t1.d else t1.a end in (a,e,t1.d) then t1.f else t1.f end+f+t1.e in (t1.d,e,b))}
} {191}
do_test randexpr-2.1142 {
  db eval {SELECT case when coalesce((select max(case b & d*(abs(t1.e)/abs(a))-f & t1.b when t1.e then coalesce((select max(t1.e) from t1 where t1.e between (select ~count(*)*cast(avg(19) AS integer) from t1) and case c when a then 13 else a end),t1.f)+e*c else t1.d end) from t1 where t1.a in (select t1.d from t1 union select 17 from t1)),e)+17<19 then t1.a else 19 end & 11+e-17*19 FROM t1 WHERE NOT (d*t1.c-case when case when ((13 in (17+e,b,11)) or 19>(13)) then (abs(coalesce((select t1.a from t1 where t1.a not in (13,c,t1.f)),11))/abs(t1.e))-f when t1.b not between t1.b and f then t1.d else t1.a end in (a,e,t1.d) then t1.f else t1.f end+f+t1.e in (t1.d,e,b))}
} {16}
do_test randexpr-2.1143 {
  db eval {SELECT ((select (count(*) | +~(case ++(min(t1.f+17+(11-case when b between d and d and t1.a not in (13,c,t1.c) and e< -t1.b then 17+(11) else t1.e end+ -b))) when case min(e) when min( -13) | ~max(t1.f) then count(distinct t1.f) | ~count(distinct t1.d) else count(*) end then min(t1.c) else  -cast(avg(11) AS integer) end)+count(distinct (f))) from t1)+e) FROM t1 WHERE (a in (11*a-t1.a | t1.b+e*13,(f | a | (select min((select min(13)-min(17)*((count(distinct t1.d))) from t1)) from t1)+t1.a- -11)+(11),t1.c) and (a) between t1.d and t1.f or t1.d not between t1.c and f or d not in (t1.c,t1.f,c))}
} {511}
do_test randexpr-2.1144 {
  db eval {SELECT ((select (count(*) | +~(case ++(min(t1.f+17+(11-case when b between d and d and t1.a not in (13,c,t1.c) and e< -t1.b then 17+(11) else t1.e end+ -b))) when case min(e) when min( -13) | ~max(t1.f) then count(distinct t1.f) | ~count(distinct t1.d) else count(*) end then min(t1.c) else  -cast(avg(11) AS integer) end)+count(distinct (f))) from t1)+e) FROM t1 WHERE NOT ((a in (11*a-t1.a | t1.b+e*13,(f | a | (select min((select min(13)-min(17)*((count(distinct t1.d))) from t1)) from t1)+t1.a- -11)+(11),t1.c) and (a) between t1.d and t1.f or t1.d not between t1.c and f or d not in (t1.c,t1.f,c)))}
} {}
do_test randexpr-2.1145 {
  db eval {SELECT ((select (count(*) & +~(case ++(min(t1.f+17+(11-case when b between d and d and t1.a not in (13,c,t1.c) and e< -t1.b then 17+(11) else t1.e end+ -b))) when case min(e) when min( -13) & ~max(t1.f) then count(distinct t1.f) & ~count(distinct t1.d) else count(*) end then min(t1.c) else  -cast(avg(11) AS integer) end)+count(distinct (f))) from t1)+e) FROM t1 WHERE (a in (11*a-t1.a | t1.b+e*13,(f | a | (select min((select min(13)-min(17)*((count(distinct t1.d))) from t1)) from t1)+t1.a- -11)+(11),t1.c) and (a) between t1.d and t1.f or t1.d not between t1.c and f or d not in (t1.c,t1.f,c))}
} {501}
do_test randexpr-2.1146 {
  db eval {SELECT coalesce((select max(13) from t1 where d in (select (max(19)*count(distinct case when t1.f between ~e and  -b-t1.f then b else d end)-count(distinct f)) from t1 union select cast(avg(case e when case t1.b when  -a | t1.e*19 then t1.a else  -t1.c end then  -d else t1.e end) AS integer) from t1)),case when t1.d in (select t1.e from t1 union select b from t1) then t1.f when t1.f between 13 and f then f else f end) FROM t1 WHERE c in (select (t1.a) from t1 union select e from t1)}
} {}
do_test randexpr-2.1147 {
  db eval {SELECT coalesce((select max(13) from t1 where d in (select (max(19)*count(distinct case when t1.f between ~e and  -b-t1.f then b else d end)-count(distinct f)) from t1 union select cast(avg(case e when case t1.b when  -a | t1.e*19 then t1.a else  -t1.c end then  -d else t1.e end) AS integer) from t1)),case when t1.d in (select t1.e from t1 union select b from t1) then t1.f when t1.f between 13 and f then f else f end) FROM t1 WHERE NOT (c in (select (t1.a) from t1 union select e from t1))}
} {600}
do_test randexpr-2.1148 {
  db eval {SELECT coalesce((select max(13) from t1 where d in (select (max(19)*count(distinct case when t1.f between ~e and  -b-t1.f then b else d end)-count(distinct f)) from t1 union select cast(avg(case e when case t1.b when  -a & t1.e*19 then t1.a else  -t1.c end then  -d else t1.e end) AS integer) from t1)),case when t1.d in (select t1.e from t1 union select b from t1) then t1.f when t1.f between 13 and f then f else f end) FROM t1 WHERE NOT (c in (select (t1.a) from t1 union select e from t1))}
} {600}
do_test randexpr-2.1149 {
  db eval {SELECT (abs(t1.d+b)/abs(~t1.f+case when t1.f=t1.c or exists(select 1 from t1 where c>=+~t1.c*17) or exists(select 1 from t1 where (select  -cast(avg(case when 19<>t1.f then  -c when c<>b then t1.e else t1.d end) AS integer) from t1) in (d-t1.f,b,19)) then d+b when 11<b then t1.c else d end* -t1.a-19)) FROM t1 WHERE t1.a-(select cast(avg(a) AS integer) from t1) in (select t1.c from t1 union select 19 from t1) and not exists(select 1 from t1 where coalesce((select max(11) from t1 where case when not d>(19) then c else  -case when 11>b or t1.c<=c then f when t1.f>t1.a then t1.a else t1.e end*d-11 end+d*t1.b>t1.e),d)>t1.b and c<>d and not exists(select 1 from t1 where 17>=(t1.f)) and t1.e not in (f,t1.b,t1.b))}
} {}
do_test randexpr-2.1150 {
  db eval {SELECT (abs(t1.d+b)/abs(~t1.f+case when t1.f=t1.c or exists(select 1 from t1 where c>=+~t1.c*17) or exists(select 1 from t1 where (select  -cast(avg(case when 19<>t1.f then  -c when c<>b then t1.e else t1.d end) AS integer) from t1) in (d-t1.f,b,19)) then d+b when 11<b then t1.c else d end* -t1.a-19)) FROM t1 WHERE NOT (t1.a-(select cast(avg(a) AS integer) from t1) in (select t1.c from t1 union select 19 from t1) and not exists(select 1 from t1 where coalesce((select max(11) from t1 where case when not d>(19) then c else  -case when 11>b or t1.c<=c then f when t1.f>t1.a then t1.a else t1.e end*d-11 end+d*t1.b>t1.e),d)>t1.b and c<>d and not exists(select 1 from t1 where 17>=(t1.f)) and t1.e not in (f,t1.b,t1.b)))}
} {0}
do_test randexpr-2.1151 {
  db eval {SELECT t1.b-~case when +a in (select ~min(11) from t1 union select  -count(*)+count(distinct ~coalesce((select coalesce((select t1.b-19+c from t1 where a<>13 or 13 in (t1.b,d,t1.e)),11) from t1 where 19 in (19,e,17)),e)) from t1) then (select  -min(19)+cast(avg(t1.d) AS integer) from t1) else d end | 17 | t1.e FROM t1 WHERE c-b+e*11+(c+13+11)+(13)+(select cast(avg((abs(e-d+a)/abs(t1.f))) AS integer) from t1)-t1.d+~13<=t1.e-c-17}
} {}
do_test randexpr-2.1152 {
  db eval {SELECT t1.b-~case when +a in (select ~min(11) from t1 union select  -count(*)+count(distinct ~coalesce((select coalesce((select t1.b-19+c from t1 where a<>13 or 13 in (t1.b,d,t1.e)),11) from t1 where 19 in (19,e,17)),e)) from t1) then (select  -min(19)+cast(avg(t1.d) AS integer) from t1) else d end | 17 | t1.e FROM t1 WHERE NOT (c-b+e*11+(c+13+11)+(13)+(select cast(avg((abs(e-d+a)/abs(t1.f))) AS integer) from t1)-t1.d+~13<=t1.e-c-17)}
} {1021}
do_test randexpr-2.1153 {
  db eval {SELECT t1.b-~case when +a in (select ~min(11) from t1 union select  -count(*)+count(distinct ~coalesce((select coalesce((select t1.b-19+c from t1 where a<>13 or 13 in (t1.b,d,t1.e)),11) from t1 where 19 in (19,e,17)),e)) from t1) then (select  -min(19)+cast(avg(t1.d) AS integer) from t1) else d end & 17 & t1.e FROM t1 WHERE NOT (c-b+e*11+(c+13+11)+(13)+(select cast(avg((abs(e-d+a)/abs(t1.f))) AS integer) from t1)-t1.d+~13<=t1.e-c-17)}
} {16}
do_test randexpr-2.1154 {
  db eval {SELECT coalesce((select max(b) from t1 where t1.e<t1.b-11*case when ( -c*case d when case +t1.c+t1.b when ~11*(select count(distinct d) from t1) then a else t1.d end then t1.b else (abs((select max(+coalesce((select (t1.d) from t1 where 19 not between t1.b and t1.a and t1.d between 19 and  -13),t1.a)) from t1))/abs(f)) end)<>t1.e then 17 when 19 not between 11 and b then t1.e else 19 end*t1.c),t1.c) FROM t1 WHERE not t1.f*(abs(case when ~19-17*e>=t1.d then t1.b when (select cast(avg(t1.e) AS integer) from t1) in ((abs(t1.e)/abs(t1.e))-case when f not in (t1.d,13,c) then c else t1.e end-t1.b-t1.a | b-(t1.c), -a,e) then t1.e else e end+a)/abs(t1.d)) | b not between b and t1.d}
} {}
do_test randexpr-2.1155 {
  db eval {SELECT coalesce((select max(b) from t1 where t1.e<t1.b-11*case when ( -c*case d when case +t1.c+t1.b when ~11*(select count(distinct d) from t1) then a else t1.d end then t1.b else (abs((select max(+coalesce((select (t1.d) from t1 where 19 not between t1.b and t1.a and t1.d between 19 and  -13),t1.a)) from t1))/abs(f)) end)<>t1.e then 17 when 19 not between 11 and b then t1.e else 19 end*t1.c),t1.c) FROM t1 WHERE NOT (not t1.f*(abs(case when ~19-17*e>=t1.d then t1.b when (select cast(avg(t1.e) AS integer) from t1) in ((abs(t1.e)/abs(t1.e))-case when f not in (t1.d,13,c) then c else t1.e end-t1.b-t1.a | b-(t1.c), -a,e) then t1.e else e end+a)/abs(t1.d)) | b not between b and t1.d)}
} {300}
do_test randexpr-2.1156 {
  db eval {SELECT  -f+( - -case when 13-b not between case when (a<>t1.f or case when not exists(select 1 from t1 where 11<>t1.a) then b when c<=t1.b then t1.f else 11 end in (select 17 from t1 union select t1.b from t1)) then b-c-b when t1.f=13 then a else 19 end | t1.d and t1.e and not exists(select 1 from t1 where 19=t1.f) then  -c else 19 end+17) FROM t1 WHERE not not exists(select 1 from t1 where ~(select cast(avg(t1.d) AS integer) from t1) | +~~case case when f-case when exists(select 1 from t1 where 13 not in (d,11,case when not exists(select 1 from t1 where f between t1.d and e) then 13 when t1.e<>19 then f else 11 end) or b in ( -d,t1.c,17)) then b else f end-(t1.d) in (t1.c,t1.c,b) then t1.b else e end when 11 then t1.e else  -c end-c<>t1.b)}
} {-883}
do_test randexpr-2.1157 {
  db eval {SELECT  -f+( - -case when 13-b not between case when (a<>t1.f or case when not exists(select 1 from t1 where 11<>t1.a) then b when c<=t1.b then t1.f else 11 end in (select 17 from t1 union select t1.b from t1)) then b-c-b when t1.f=13 then a else 19 end | t1.d and t1.e and not exists(select 1 from t1 where 19=t1.f) then  -c else 19 end+17) FROM t1 WHERE NOT (not not exists(select 1 from t1 where ~(select cast(avg(t1.d) AS integer) from t1) | +~~case case when f-case when exists(select 1 from t1 where 13 not in (d,11,case when not exists(select 1 from t1 where f between t1.d and e) then 13 when t1.e<>19 then f else 11 end) or b in ( -d,t1.c,17)) then b else f end-(t1.d) in (t1.c,t1.c,b) then t1.b else e end when 11 then t1.e else  -c end-c<>t1.b))}
} {}
do_test randexpr-2.1158 {
  db eval {SELECT  -f+( - -case when 13-b not between case when (a<>t1.f or case when not exists(select 1 from t1 where 11<>t1.a) then b when c<=t1.b then t1.f else 11 end in (select 17 from t1 union select t1.b from t1)) then b-c-b when t1.f=13 then a else 19 end & t1.d and t1.e and not exists(select 1 from t1 where 19=t1.f) then  -c else 19 end+17) FROM t1 WHERE not not exists(select 1 from t1 where ~(select cast(avg(t1.d) AS integer) from t1) | +~~case case when f-case when exists(select 1 from t1 where 13 not in (d,11,case when not exists(select 1 from t1 where f between t1.d and e) then 13 when t1.e<>19 then f else 11 end) or b in ( -d,t1.c,17)) then b else f end-(t1.d) in (t1.c,t1.c,b) then t1.b else e end when 11 then t1.e else  -c end-c<>t1.b)}
} {-883}
do_test randexpr-2.1159 {
  db eval {SELECT +(abs(d+d+a+b+t1.d)/abs(coalesce((select (select abs(cast(avg(17-11+e*t1.d) AS integer)++cast(avg(coalesce((select max(11-+t1.f- -e-a* -19+t1.a) from t1 where  -a in (select 11 from t1 union select  -11 from t1)),e)) AS integer)) from t1) from t1 where f=17),t1.b)*a)) FROM t1 WHERE t1.b in (select t1.e from t1 union select coalesce((select max(11) from t1 where d<t1.f),f) from t1)}
} {}
do_test randexpr-2.1160 {
  db eval {SELECT +(abs(d+d+a+b+t1.d)/abs(coalesce((select (select abs(cast(avg(17-11+e*t1.d) AS integer)++cast(avg(coalesce((select max(11-+t1.f- -e-a* -19+t1.a) from t1 where  -a in (select 11 from t1 union select  -11 from t1)),e)) AS integer)) from t1) from t1 where f=17),t1.b)*a)) FROM t1 WHERE NOT (t1.b in (select t1.e from t1 union select coalesce((select max(11) from t1 where d<t1.f),f) from t1))}
} {0}
do_test randexpr-2.1161 {
  db eval {SELECT case when t1.b*t1.c=coalesce((select t1.f from t1 where case when exists(select 1 from t1 where t1.d in (select e from t1 union select 19 from t1)) or t1.e>t1.e then t1.a+e-a when 19>t1.c then c else t1.c end+c not between b and t1.d),t1.f) and  -(t1.b) between t1.e and  -t1.d or b<>19 then (select ~(min(13))+max(f) from t1) else (t1.b) end*t1.b FROM t1 WHERE b in (b,e,case coalesce((select max(t1.b) from t1 where e>13 or ( -(select case  -~count(distinct 17)-cast(avg((t1.f)) AS integer)*cast(avg(d) AS integer) when  -cast(avg(f) AS integer) then max(17) else  -(count(*)) end from t1)-(coalesce((select (b) from t1 where t1.b>=t1.e),t1.c)) in (17,t1.e,b)) or (exists(select 1 from t1 where (t1.d=(d))))),t1.c) when b then c else (e) end)}
} {117200}
do_test randexpr-2.1162 {
  db eval {SELECT case when t1.b*t1.c=coalesce((select t1.f from t1 where case when exists(select 1 from t1 where t1.d in (select e from t1 union select 19 from t1)) or t1.e>t1.e then t1.a+e-a when 19>t1.c then c else t1.c end+c not between b and t1.d),t1.f) and  -(t1.b) between t1.e and  -t1.d or b<>19 then (select ~(min(13))+max(f) from t1) else (t1.b) end*t1.b FROM t1 WHERE NOT (b in (b,e,case coalesce((select max(t1.b) from t1 where e>13 or ( -(select case  -~count(distinct 17)-cast(avg((t1.f)) AS integer)*cast(avg(d) AS integer) when  -cast(avg(f) AS integer) then max(17) else  -(count(*)) end from t1)-(coalesce((select (b) from t1 where t1.b>=t1.e),t1.c)) in (17,t1.e,b)) or (exists(select 1 from t1 where (t1.d=(d))))),t1.c) when b then c else (e) end))}
} {}
do_test randexpr-2.1163 {
  db eval {SELECT +t1.c+case when t1.e not in ((e)-(case when 17<11 then 19 when (t1.d in (d,coalesce((select max(t1.a) from t1 where not b<>t1.b),case t1.b when coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where e not in (t1.f,11,17))),(19))*t1.f then c else t1.c end+ -t1.d)-t1.b+t1.e,d)) then 19 else b end)-e,t1.c, -13) then e else 17 end FROM t1 WHERE t1.e*t1.b | t1.b<>17*+coalesce((select max(t1.b) from t1 where case when coalesce((select max(b) from t1 where case when (b between 17 and d) then t1.f when t1.c between b and t1.a then t1.e else t1.a end not in (11,19,13)),11) in (t1.d,17,17) then t1.f when d<>13 then 11 else t1.a end+a<17),t1.a)-17+t1.f*d-a}
} {800}
do_test randexpr-2.1164 {
  db eval {SELECT +t1.c+case when t1.e not in ((e)-(case when 17<11 then 19 when (t1.d in (d,coalesce((select max(t1.a) from t1 where not b<>t1.b),case t1.b when coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where e not in (t1.f,11,17))),(19))*t1.f then c else t1.c end+ -t1.d)-t1.b+t1.e,d)) then 19 else b end)-e,t1.c, -13) then e else 17 end FROM t1 WHERE NOT (t1.e*t1.b | t1.b<>17*+coalesce((select max(t1.b) from t1 where case when coalesce((select max(b) from t1 where case when (b between 17 and d) then t1.f when t1.c between b and t1.a then t1.e else t1.a end not in (11,19,13)),11) in (t1.d,17,17) then t1.f when d<>13 then 11 else t1.a end+a<17),t1.a)-17+t1.f*d-a)}
} {}
do_test randexpr-2.1165 {
  db eval {SELECT 11+case when case case f when (abs(t1.a)/abs(19))+t1.e then (abs(19)/abs(b+e)) else 13 end | 11 when (select ~~+min(t1.e) from t1) then t1.c else  -e end<>case t1.a when 17 then case when (c not between 19 and t1.b) and t1.b<>t1.d then coalesce((select a from t1 where t1.d in (t1.e,t1.f,f)),t1.e) else 13 end else d end or t1.c<t1.d then t1.f else 17 end-f FROM t1 WHERE (f*c*coalesce((select e from t1 where (exists(select 1 from t1 where +t1.e<= -e | t1.f))),a)+b in (select t1.c from t1 union select c from t1) or (t1.e between b and (19)) and 13 between t1.e and 13 and 11 in (13,t1.c,17) and exists(select 1 from t1 where t1.d in (select count(*)-max(e)-((max((11)))) from t1 union select max(17) from t1)) and c>f)}
} {}
do_test randexpr-2.1166 {
  db eval {SELECT 11+case when case case f when (abs(t1.a)/abs(19))+t1.e then (abs(19)/abs(b+e)) else 13 end | 11 when (select ~~+min(t1.e) from t1) then t1.c else  -e end<>case t1.a when 17 then case when (c not between 19 and t1.b) and t1.b<>t1.d then coalesce((select a from t1 where t1.d in (t1.e,t1.f,f)),t1.e) else 13 end else d end or t1.c<t1.d then t1.f else 17 end-f FROM t1 WHERE NOT ((f*c*coalesce((select e from t1 where (exists(select 1 from t1 where +t1.e<= -e | t1.f))),a)+b in (select t1.c from t1 union select c from t1) or (t1.e between b and (19)) and 13 between t1.e and 13 and 11 in (13,t1.c,17) and exists(select 1 from t1 where t1.d in (select count(*)-max(e)-((max((11)))) from t1 union select max(17) from t1)) and c>f))}
} {11}
do_test randexpr-2.1167 {
  db eval {SELECT 11+case when case case f when (abs(t1.a)/abs(19))+t1.e then (abs(19)/abs(b+e)) else 13 end & 11 when (select ~~+min(t1.e) from t1) then t1.c else  -e end<>case t1.a when 17 then case when (c not between 19 and t1.b) and t1.b<>t1.d then coalesce((select a from t1 where t1.d in (t1.e,t1.f,f)),t1.e) else 13 end else d end or t1.c<t1.d then t1.f else 17 end-f FROM t1 WHERE NOT ((f*c*coalesce((select e from t1 where (exists(select 1 from t1 where +t1.e<= -e | t1.f))),a)+b in (select t1.c from t1 union select c from t1) or (t1.e between b and (19)) and 13 between t1.e and 13 and 11 in (13,t1.c,17) and exists(select 1 from t1 where t1.d in (select count(*)-max(e)-((max((11)))) from t1 union select max(17) from t1)) and c>f))}
} {11}
do_test randexpr-2.1168 {
  db eval {SELECT d-case when ~c<>case when not exists(select 1 from t1 where  -t1.b<>19) then coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where (t1.c in (select ~~+~max(~case when 13 not between t1.d and t1.d or c between c and f then t1.f else t1.a end)*abs(count(*)+(min( -t1.e))) from t1 union select cast(avg(e) AS integer) from t1) and (abs(t1.f*f-t1.a)/abs(d))>t1.b)) and (17) not in ( -t1.f,13,17)),19) else a end then b else f end FROM t1 WHERE f=(select case ~ -~count(distinct t1.b)+count(distinct d) |  -count(distinct t1.e)*count(*)* -cast(avg(b) AS integer)*(cast(avg(13) AS integer)) when  -min(19) then min(t1.e) else ((cast(avg(17) AS integer))) end from t1) or 19>=(19) and not exists(select 1 from t1 where (select count(*) from t1)*t1.d not between 19+11 and d) and  -t1.e not in (e,t1.a, -a) and t1.e between t1.f and (t1.b) or c in ( -11,17,t1.c) or t1.a in (a,11,t1.d)}
} {200}
do_test randexpr-2.1169 {
  db eval {SELECT d-case when ~c<>case when not exists(select 1 from t1 where  -t1.b<>19) then coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where (t1.c in (select ~~+~max(~case when 13 not between t1.d and t1.d or c between c and f then t1.f else t1.a end)*abs(count(*)+(min( -t1.e))) from t1 union select cast(avg(e) AS integer) from t1) and (abs(t1.f*f-t1.a)/abs(d))>t1.b)) and (17) not in ( -t1.f,13,17)),19) else a end then b else f end FROM t1 WHERE NOT (f=(select case ~ -~count(distinct t1.b)+count(distinct d) |  -count(distinct t1.e)*count(*)* -cast(avg(b) AS integer)*(cast(avg(13) AS integer)) when  -min(19) then min(t1.e) else ((cast(avg(17) AS integer))) end from t1) or 19>=(19) and not exists(select 1 from t1 where (select count(*) from t1)*t1.d not between 19+11 and d) and  -t1.e not in (e,t1.a, -a) and t1.e between t1.f and (t1.b) or c in ( -11,17,t1.c) or t1.a in (a,11,t1.d))}
} {}
do_test randexpr-2.1170 {
  db eval {SELECT case when a in (select t1.b from t1 union select coalesce((select ~19 from t1 where e>13*t1.d or c in (select b from t1 union select case a*t1.f when e then (t1.c) else (t1.b) end from t1)),t1.a) from t1) and t1.d>b or not exists(select 1 from t1 where t1.e in (select count(*)*min(t1.b)*~count(*) from t1 union select case  -min((19)) when  -max(b) then (min(t1.a)) else (count(distinct t1.d)) end from t1)) then (t1.c) when exists(select 1 from t1 where f not between 19 and f) then 19 else t1.c end-a FROM t1 WHERE a=coalesce((select f from t1 where t1.c in (11,(abs(coalesce((select max(t1.d) from t1 where (abs(t1.c | 13)/abs(11)) not in (b+case when coalesce((select max(b) from t1 where 11 between d and t1.a),b)<a then 19 when (e) not in (t1.e,13,t1.d) then t1.c else  - -t1.e end-19,a,17)),19))/abs(t1.a)),t1.b) or (((13)>=t1.b))),c) and f between 19 and t1.d or c>(f)}
} {}
do_test randexpr-2.1171 {
  db eval {SELECT case when a in (select t1.b from t1 union select coalesce((select ~19 from t1 where e>13*t1.d or c in (select b from t1 union select case a*t1.f when e then (t1.c) else (t1.b) end from t1)),t1.a) from t1) and t1.d>b or not exists(select 1 from t1 where t1.e in (select count(*)*min(t1.b)*~count(*) from t1 union select case  -min((19)) when  -max(b) then (min(t1.a)) else (count(distinct t1.d)) end from t1)) then (t1.c) when exists(select 1 from t1 where f not between 19 and f) then 19 else t1.c end-a FROM t1 WHERE NOT (a=coalesce((select f from t1 where t1.c in (11,(abs(coalesce((select max(t1.d) from t1 where (abs(t1.c | 13)/abs(11)) not in (b+case when coalesce((select max(b) from t1 where 11 between d and t1.a),b)<a then 19 when (e) not in (t1.e,13,t1.d) then t1.c else  - -t1.e end-19,a,17)),19))/abs(t1.a)),t1.b) or (((13)>=t1.b))),c) and f between 19 and t1.d or c>(f))}
} {200}
do_test randexpr-2.1172 {
  db eval {SELECT case when  -(t1.f)- -case when t1.e not in ((t1.d)+a-t1.a,t1.c, - -a) then t1.b when (not exists(select 1 from t1 where t1.d>= -t1.f)) then  -19 else f end-t1.f in (select cast(avg(19) AS integer)*case count(*) when abs((++min( -11))*max(13)-count(distinct 13)) then min(t1.a) else count(distinct 17) end from t1 union select count(distinct t1.a) from t1) then t1.c when b not between t1.f and 13 then e else t1.a end FROM t1 WHERE 11 not between ~17+d and ~case when t1.b in (c*((abs(case 13 when  -(select abs(count(distinct coalesce((select max(coalesce((select t1.b from t1 where not exists(select 1 from t1 where (t1.c) in (t1.a,e,13))),t1.d)) from t1 where not t1.d>c),b))) from t1) then t1.f else t1.b end- -t1.c)/abs(c))+a),t1.d,t1.a) then (t1.c) else (d) end-13 or  -t1.a in (17,a,f)}
} {500}
do_test randexpr-2.1173 {
  db eval {SELECT case when  -(t1.f)- -case when t1.e not in ((t1.d)+a-t1.a,t1.c, - -a) then t1.b when (not exists(select 1 from t1 where t1.d>= -t1.f)) then  -19 else f end-t1.f in (select cast(avg(19) AS integer)*case count(*) when abs((++min( -11))*max(13)-count(distinct 13)) then min(t1.a) else count(distinct 17) end from t1 union select count(distinct t1.a) from t1) then t1.c when b not between t1.f and 13 then e else t1.a end FROM t1 WHERE NOT (11 not between ~17+d and ~case when t1.b in (c*((abs(case 13 when  -(select abs(count(distinct coalesce((select max(coalesce((select t1.b from t1 where not exists(select 1 from t1 where (t1.c) in (t1.a,e,13))),t1.d)) from t1 where not t1.d>c),b))) from t1) then t1.f else t1.b end- -t1.c)/abs(c))+a),t1.d,t1.a) then (t1.c) else (d) end-13 or  -t1.a in (17,a,f))}
} {}
do_test randexpr-2.1174 {
  db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where (t1.b- -b+(select +case max(b)-~count(distinct e*(select case max(c) when abs((count(*))) then max(t1.f) else max(t1.c) end+cast(avg(t1.b) AS integer) from t1)) when abs(count(distinct e*19)) then max(b) else max(t1.c) end | count(distinct t1.e) from t1)-b*+t1.b not in ((11),17,13)))),t1.e) FROM t1 WHERE t1.c in (select min(coalesce((select 17 from t1 where t1.c | 17>=(abs(t1.a)/abs(case when t1.e not in (19,t1.d,19) then a when 13<=case when not exists(select 1 from t1 where (abs(e)/abs(t1.c)) in (select 19 from t1 union select d from t1) and t1.c>=17 or 19=t1.a) then f else a end then t1.d else e end))-f),e))*min(f) | ++min(a) from t1 union select cast(avg(f) AS integer) from t1)}
} {}
do_test randexpr-2.1175 {
  db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where (t1.b- -b+(select +case max(b)-~count(distinct e*(select case max(c) when abs((count(*))) then max(t1.f) else max(t1.c) end+cast(avg(t1.b) AS integer) from t1)) when abs(count(distinct e*19)) then max(b) else max(t1.c) end | count(distinct t1.e) from t1)-b*+t1.b not in ((11),17,13)))),t1.e) FROM t1 WHERE NOT (t1.c in (select min(coalesce((select 17 from t1 where t1.c | 17>=(abs(t1.a)/abs(case when t1.e not in (19,t1.d,19) then a when 13<=case when not exists(select 1 from t1 where (abs(e)/abs(t1.c)) in (select 19 from t1 union select d from t1) and t1.c>=17 or 19=t1.a) then f else a end then t1.d else e end))-f),e))*min(f) | ++min(a) from t1 union select cast(avg(f) AS integer) from t1))}
} {500}
do_test randexpr-2.1176 {
  db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where (t1.b- -b+(select +case max(b)-~count(distinct e*(select case max(c) when abs((count(*))) then max(t1.f) else max(t1.c) end+cast(avg(t1.b) AS integer) from t1)) when abs(count(distinct e*19)) then max(b) else max(t1.c) end & count(distinct t1.e) from t1)-b*+t1.b not in ((11),17,13)))),t1.e) FROM t1 WHERE NOT (t1.c in (select min(coalesce((select 17 from t1 where t1.c | 17>=(abs(t1.a)/abs(case when t1.e not in (19,t1.d,19) then a when 13<=case when not exists(select 1 from t1 where (abs(e)/abs(t1.c)) in (select 19 from t1 union select d from t1) and t1.c>=17 or 19=t1.a) then f else a end then t1.d else e end))-f),e))*min(f) | ++min(a) from t1 union select cast(avg(f) AS integer) from t1))}
} {500}
do_test randexpr-2.1177 {
  db eval {SELECT case coalesce((select t1.e from t1 where +coalesce((select a from t1 where 13 | b | t1.b<=11*a*case when exists(select 1 from t1 where (a-t1.d+t1.e-f<17 and  -17 between 19 and a)) then c when 17 between f and t1.c then a*11 else t1.d end),t1.e) not in (b,t1.f,t1.d)),a) when c then  -c else t1.b end FROM t1 WHERE (exists(select 1 from t1 where case when not exists(select 1 from t1 where (select cast(avg(d) AS integer) from t1) in (select a from t1 union select case case when t1.e>t1.d or t1.b in (select c from t1 union select e from t1) or t1.a>=f and b>=11 then t1.c-(t1.c)*19 when b not in (e,c,t1.d) then t1.b else t1.c end when 13 then f else  -t1.f end from t1)) then 17 when not exists(select 1 from t1 where not exists(select 1 from t1 where f not in (t1.d,f, -t1.b)) or  -19<=t1.c) or t1.e between 13 and t1.a then f else d end<>t1.f) and f between 11 and t1.c and t1.e not in (t1.d,c,t1.e)) or d not between t1.b and t1.d}
} {}
do_test randexpr-2.1178 {
  db eval {SELECT case coalesce((select t1.e from t1 where +coalesce((select a from t1 where 13 | b | t1.b<=11*a*case when exists(select 1 from t1 where (a-t1.d+t1.e-f<17 and  -17 between 19 and a)) then c when 17 between f and t1.c then a*11 else t1.d end),t1.e) not in (b,t1.f,t1.d)),a) when c then  -c else t1.b end FROM t1 WHERE NOT ((exists(select 1 from t1 where case when not exists(select 1 from t1 where (select cast(avg(d) AS integer) from t1) in (select a from t1 union select case case when t1.e>t1.d or t1.b in (select c from t1 union select e from t1) or t1.a>=f and b>=11 then t1.c-(t1.c)*19 when b not in (e,c,t1.d) then t1.b else t1.c end when 13 then f else  -t1.f end from t1)) then 17 when not exists(select 1 from t1 where not exists(select 1 from t1 where f not in (t1.d,f, -t1.b)) or  -19<=t1.c) or t1.e between 13 and t1.a then f else d end<>t1.f) and f between 11 and t1.c and t1.e not in (t1.d,c,t1.e)) or d not between t1.b and t1.d)}
} {200}
do_test randexpr-2.1179 {
  db eval {SELECT case coalesce((select t1.e from t1 where +coalesce((select a from t1 where 13 & b & t1.b<=11*a*case when exists(select 1 from t1 where (a-t1.d+t1.e-f<17 and  -17 between 19 and a)) then c when 17 between f and t1.c then a*11 else t1.d end),t1.e) not in (b,t1.f,t1.d)),a) when c then  -c else t1.b end FROM t1 WHERE NOT ((exists(select 1 from t1 where case when not exists(select 1 from t1 where (select cast(avg(d) AS integer) from t1) in (select a from t1 union select case case when t1.e>t1.d or t1.b in (select c from t1 union select e from t1) or t1.a>=f and b>=11 then t1.c-(t1.c)*19 when b not in (e,c,t1.d) then t1.b else t1.c end when 13 then f else  -t1.f end from t1)) then 17 when not exists(select 1 from t1 where not exists(select 1 from t1 where f not in (t1.d,f, -t1.b)) or  -19<=t1.c) or t1.e between 13 and t1.a then f else d end<>t1.f) and f between 11 and t1.c and t1.e not in (t1.d,c,t1.e)) or d not between t1.b and t1.d)}
} {200}
do_test randexpr-2.1180 {
  db eval {SELECT case when exists(select 1 from t1 where b<>coalesce((select (select + - -count(*)-~count(*)+~+case  - -count(distinct (t1.d)) when max(t1.d) then count(*) else max(a) end+(cast(avg(17) AS integer)) from t1) | d from t1 where not exists(select 1 from t1 where (abs(f)/abs(t1.c)) between 13+a and  -t1.d)),19) or (coalesce((select t1.d from t1 where (( - -19)>a)),t1.f) in (e,e,t1.e))) then t1.b*t1.f when t1.d not between (a) and a then e else b end FROM t1 WHERE not exists(select 1 from t1 where a in (select 13 from t1 union select 17 from t1))}
} {120000}
do_test randexpr-2.1181 {
  db eval {SELECT case when exists(select 1 from t1 where b<>coalesce((select (select + - -count(*)-~count(*)+~+case  - -count(distinct (t1.d)) when max(t1.d) then count(*) else max(a) end+(cast(avg(17) AS integer)) from t1) | d from t1 where not exists(select 1 from t1 where (abs(f)/abs(t1.c)) between 13+a and  -t1.d)),19) or (coalesce((select t1.d from t1 where (( - -19)>a)),t1.f) in (e,e,t1.e))) then t1.b*t1.f when t1.d not between (a) and a then e else b end FROM t1 WHERE NOT (not exists(select 1 from t1 where a in (select 13 from t1 union select 17 from t1)))}
} {}
do_test randexpr-2.1182 {
  db eval {SELECT case when exists(select 1 from t1 where b<>coalesce((select (select + - -count(*)-~count(*)+~+case  - -count(distinct (t1.d)) when max(t1.d) then count(*) else max(a) end+(cast(avg(17) AS integer)) from t1) & d from t1 where not exists(select 1 from t1 where (abs(f)/abs(t1.c)) between 13+a and  -t1.d)),19) or (coalesce((select t1.d from t1 where (( - -19)>a)),t1.f) in (e,e,t1.e))) then t1.b*t1.f when t1.d not between (a) and a then e else b end FROM t1 WHERE not exists(select 1 from t1 where a in (select 13 from t1 union select 17 from t1))}
} {120000}
do_test randexpr-2.1183 {
  db eval {SELECT coalesce((select case when f>17-t1.f then (select +max(coalesce((select +11 from t1 where coalesce((select max(d) from t1 where +t1.c between (f) and c),t1.f) not in (c, -f,t1.e)),d)) from t1) else 17+19 end from t1 where not not exists(select 1 from t1 where t1.a in (select a from t1 union select t1.a from t1) and 17=d or (17)<=(( -19)) and t1.f in (select d from t1 union select 13 from t1) or 19>13 or t1.b not in (t1.b,17,d))), -(t1.c)) FROM t1 WHERE +t1.a-13+(select count(distinct a) from t1)-e*e*case when coalesce((select max(coalesce((select a from t1 where ((case b+t1.c-t1.c*d*17 when t1.a then t1.a else f end<>c))),t1.b+13)) from t1 where t1.f between 17 and t1.d),t1.c)<=(b) then f else t1.e end-13<>t1.f}
} {11}
do_test randexpr-2.1184 {
  db eval {SELECT coalesce((select case when f>17-t1.f then (select +max(coalesce((select +11 from t1 where coalesce((select max(d) from t1 where +t1.c between (f) and c),t1.f) not in (c, -f,t1.e)),d)) from t1) else 17+19 end from t1 where not not exists(select 1 from t1 where t1.a in (select a from t1 union select t1.a from t1) and 17=d or (17)<=(( -19)) and t1.f in (select d from t1 union select 13 from t1) or 19>13 or t1.b not in (t1.b,17,d))), -(t1.c)) FROM t1 WHERE NOT (+t1.a-13+(select count(distinct a) from t1)-e*e*case when coalesce((select max(coalesce((select a from t1 where ((case b+t1.c-t1.c*d*17 when t1.a then t1.a else f end<>c))),t1.b+13)) from t1 where t1.f between 17 and t1.d),t1.c)<=(b) then f else t1.e end-13<>t1.f)}
} {}
do_test randexpr-2.1185 {
  db eval {SELECT coalesce((select 13 from t1 where ~(select max(b) from t1)<= -+d*f+t1.b*f or coalesce((select max(case when d=(abs(19)/abs(t1.f)) then case b+d when (abs(coalesce((select 11 from t1 where t1.f between  -d and c),t1.f))/abs(t1.a)) then b else t1.d end when a<t1.d then 13 else 11 end) from t1 where a not between t1.e and b),t1.d)>=t1.e),17)+ -c FROM t1 WHERE t1.b-+(t1.b) in (select a from t1 union select 19 from t1)}
} {}
do_test randexpr-2.1186 {
  db eval {SELECT coalesce((select 13 from t1 where ~(select max(b) from t1)<= -+d*f+t1.b*f or coalesce((select max(case when d=(abs(19)/abs(t1.f)) then case b+d when (abs(coalesce((select 11 from t1 where t1.f between  -d and c),t1.f))/abs(t1.a)) then b else t1.d end when a<t1.d then 13 else 11 end) from t1 where a not between t1.e and b),t1.d)>=t1.e),17)+ -c FROM t1 WHERE NOT (t1.b-+(t1.b) in (select a from t1 union select 19 from t1))}
} {-283}
do_test randexpr-2.1187 {
  db eval {SELECT case when (abs((abs(d)/abs(t1.f-c)))/abs( -t1.f))*case when (t1.c not in (case when t1.b>case t1.d when t1.b then e else 11 end then t1.a when ( -t1.d in (select  -count(*)-cast(avg(f) AS integer) from t1 union select count(*) from t1)) or 11 in (e,t1.e,c) then a else b end,t1.a,11) or t1.a in (17,t1.a,t1.d) and b>(t1.a)) then 11 when c<b then t1.f+t1.e else b end+t1.a>t1.b then t1.c else 17 end FROM t1 WHERE t1.b>f}
} {}
do_test randexpr-2.1188 {
  db eval {SELECT case when (abs((abs(d)/abs(t1.f-c)))/abs( -t1.f))*case when (t1.c not in (case when t1.b>case t1.d when t1.b then e else 11 end then t1.a when ( -t1.d in (select  -count(*)-cast(avg(f) AS integer) from t1 union select count(*) from t1)) or 11 in (e,t1.e,c) then a else b end,t1.a,11) or t1.a in (17,t1.a,t1.d) and b>(t1.a)) then 11 when c<b then t1.f+t1.e else b end+t1.a>t1.b then t1.c else 17 end FROM t1 WHERE NOT (t1.b>f)}
} {17}
do_test randexpr-2.1189 {
  db eval {SELECT t1.e-case when case when ((exists(select 1 from t1 where not exists(select 1 from t1 where case when not 13<=13 or (t1.c<>t1.e) then t1.d else +13 end+13 in (select max(13) | max((t1.b)) from t1 union select max(f) from t1))))) then t1.f else ~t1.e | t1.d*t1.b end+11 not between t1.c and 13 then b when (t1.f not in (19,t1.f,t1.d)) then c else  -b end FROM t1 WHERE ( -(select  -min(13-t1.b) from t1)-coalesce((select case when  -d>=t1.e or 11 between 17 and  -t1.e then 19+f when t1.f=11 then  -t1.c else t1.b end from t1 where t1.a not in (11,t1.e,t1.a)),t1.c)*11 in (select  -case abs((abs(min(t1.d)))) when max(19) then cast(avg(f) AS integer) else case count(*) when count(*) then (count(distinct t1.f)) else cast(avg(11) AS integer) end end from t1 union select min(d) from t1)) or b in (select (count(*)) from t1 union select max(t1.a) from t1)}
} {}
do_test randexpr-2.1190 {
  db eval {SELECT t1.e-case when case when ((exists(select 1 from t1 where not exists(select 1 from t1 where case when not 13<=13 or (t1.c<>t1.e) then t1.d else +13 end+13 in (select max(13) | max((t1.b)) from t1 union select max(f) from t1))))) then t1.f else ~t1.e | t1.d*t1.b end+11 not between t1.c and 13 then b when (t1.f not in (19,t1.f,t1.d)) then c else  -b end FROM t1 WHERE NOT (( -(select  -min(13-t1.b) from t1)-coalesce((select case when  -d>=t1.e or 11 between 17 and  -t1.e then 19+f when t1.f=11 then  -t1.c else t1.b end from t1 where t1.a not in (11,t1.e,t1.a)),t1.c)*11 in (select  -case abs((abs(min(t1.d)))) when max(19) then cast(avg(f) AS integer) else case count(*) when count(*) then (count(distinct t1.f)) else cast(avg(11) AS integer) end end from t1 union select min(d) from t1)) or b in (select (count(*)) from t1 union select max(t1.a) from t1))}
} {300}
do_test randexpr-2.1191 {
  db eval {SELECT t1.e-case when case when ((exists(select 1 from t1 where not exists(select 1 from t1 where case when not 13<=13 or (t1.c<>t1.e) then t1.d else +13 end+13 in (select max(13) & max((t1.b)) from t1 union select max(f) from t1))))) then t1.f else ~t1.e & t1.d*t1.b end+11 not between t1.c and 13 then b when (t1.f not in (19,t1.f,t1.d)) then c else  -b end FROM t1 WHERE NOT (( -(select  -min(13-t1.b) from t1)-coalesce((select case when  -d>=t1.e or 11 between 17 and  -t1.e then 19+f when t1.f=11 then  -t1.c else t1.b end from t1 where t1.a not in (11,t1.e,t1.a)),t1.c)*11 in (select  -case abs((abs(min(t1.d)))) when max(19) then cast(avg(f) AS integer) else case count(*) when count(*) then (count(distinct t1.f)) else cast(avg(11) AS integer) end end from t1 union select min(d) from t1)) or b in (select (count(*)) from t1 union select max(t1.a) from t1))}
} {300}
do_test randexpr-2.1192 {
  db eval {SELECT (coalesce((select c*(select +~count(distinct 19)-cast(avg(~ -c) AS integer)-max( -f)-cast(avg(t1.d) AS integer) from t1)+t1.a*t1.f+t1.e-a*b from t1 where not t1.e<t1.b or 11=d and 19<>d and 11<=t1.e and (not exists(select 1 from t1 where exists(select 1 from t1 where (13=a)) or t1.e>t1.b))),19)) FROM t1 WHERE coalesce((select max(t1.f*11) from t1 where not exists(select 1 from t1 where t1.a<>17) and t1.b>case (abs(b* -t1.a)/abs(11)) when b*case case when f>=t1.e then 11 when t1.b<=d then 17 else a end* -a when e then 11 else c end then (t1.b) else 19 end or t1.f<13), -b)>=e and ((d in (select f from t1 union select f from t1)))}
} {}
do_test randexpr-2.1193 {
  db eval {SELECT (coalesce((select c*(select +~count(distinct 19)-cast(avg(~ -c) AS integer)-max( -f)-cast(avg(t1.d) AS integer) from t1)+t1.a*t1.f+t1.e-a*b from t1 where not t1.e<t1.b or 11=d and 19<>d and 11<=t1.e and (not exists(select 1 from t1 where exists(select 1 from t1 where (13=a)) or t1.e>t1.b))),19)) FROM t1 WHERE NOT (coalesce((select max(t1.f*11) from t1 where not exists(select 1 from t1 where t1.a<>17) and t1.b>case (abs(b* -t1.a)/abs(11)) when b*case case when f>=t1.e then 11 when t1.b<=d then 17 else a end* -a when e then 11 else c end then (t1.b) else 19 end or t1.f<13), -b)>=e and ((d in (select f from t1 union select f from t1))))}
} {10200}
do_test randexpr-2.1194 {
  db eval {SELECT b-b+case when d+e between 17 and case when exists(select 1 from t1 where coalesce((select max(coalesce((select 11 from t1 where t1.e not between 13 and case when t1.e<>c then c | 19+t1.a else 17 end),t1.a)) from t1 where t1.d<=17 or a not in (b,11,a)),(t1.b))+b>=t1.a) then 11 else a end then d else a end+11*f FROM t1 WHERE (t1.b*19<=17)}
} {}
do_test randexpr-2.1195 {
  db eval {SELECT b-b+case when d+e between 17 and case when exists(select 1 from t1 where coalesce((select max(coalesce((select 11 from t1 where t1.e not between 13 and case when t1.e<>c then c | 19+t1.a else 17 end),t1.a)) from t1 where t1.d<=17 or a not in (b,11,a)),(t1.b))+b>=t1.a) then 11 else a end then d else a end+11*f FROM t1 WHERE NOT ((t1.b*19<=17))}
} {6700}
do_test randexpr-2.1196 {
  db eval {SELECT b-b+case when d+e between 17 and case when exists(select 1 from t1 where coalesce((select max(coalesce((select 11 from t1 where t1.e not between 13 and case when t1.e<>c then c & 19+t1.a else 17 end),t1.a)) from t1 where t1.d<=17 or a not in (b,11,a)),(t1.b))+b>=t1.a) then 11 else a end then d else a end+11*f FROM t1 WHERE NOT ((t1.b*19<=17))}
} {6700}
do_test randexpr-2.1197 {
  db eval {SELECT +(abs(13)/abs(+~~case t1.e | +11-b-coalesce((select max(c) from t1 where 19 in (select cast(avg(coalesce((select max(case when t1.a<t1.d and t1.f<(11) then t1.f else  -a end*t1.c) from t1 where e<=d and c<f),17)) AS integer)- -max(t1.e)-count(distinct a) from t1 union select max(f) from t1)),t1.c) when t1.a then t1.e else t1.c end*17)) FROM t1 WHERE t1.a between 19 and (t1.b)}
} {0}
do_test randexpr-2.1198 {
  db eval {SELECT +(abs(13)/abs(+~~case t1.e | +11-b-coalesce((select max(c) from t1 where 19 in (select cast(avg(coalesce((select max(case when t1.a<t1.d and t1.f<(11) then t1.f else  -a end*t1.c) from t1 where e<=d and c<f),17)) AS integer)- -max(t1.e)-count(distinct a) from t1 union select max(f) from t1)),t1.c) when t1.a then t1.e else t1.c end*17)) FROM t1 WHERE NOT (t1.a between 19 and (t1.b))}
} {}
do_test randexpr-2.1199 {
  db eval {SELECT +(abs(13)/abs(+~~case t1.e & +11-b-coalesce((select max(c) from t1 where 19 in (select cast(avg(coalesce((select max(case when t1.a<t1.d and t1.f<(11) then t1.f else  -a end*t1.c) from t1 where e<=d and c<f),17)) AS integer)- -max(t1.e)-count(distinct a) from t1 union select max(f) from t1)),t1.c) when t1.a then t1.e else t1.c end*17)) FROM t1 WHERE t1.a between 19 and (t1.b)}
} {0}
do_test randexpr-2.1200 {
  db eval {SELECT coalesce((select t1.f from t1 where case d-(select case cast(avg(coalesce((select case when not 11<>e*c then 11 else 13 end from t1 where  -t1.c not between t1.f and 11),t1.e)) AS integer) when case max( -d) when ((min(17))) then cast(avg(t1.a) AS integer) else min(e) end+cast(avg((t1.b)) AS integer) then cast(avg(t1.d) AS integer) else  -(max(c)) end from t1)-f | b*13+e when t1.b then (f) else t1.a end in (select d from t1 union select 17 from t1)),d) FROM t1 WHERE t1.e*c>13-+t1.f | (abs((select abs(min(b)-abs( - -count(distinct 17-d-13+ -e-(t1.d)*e)+max(t1.e)) | (~abs((max(c)))+cast(avg(17) AS integer)-count(*)*cast(avg(11) AS integer))) from t1))/abs(t1.f))}
} {400}
do_test randexpr-2.1201 {
  db eval {SELECT coalesce((select t1.f from t1 where case d-(select case cast(avg(coalesce((select case when not 11<>e*c then 11 else 13 end from t1 where  -t1.c not between t1.f and 11),t1.e)) AS integer) when case max( -d) when ((min(17))) then cast(avg(t1.a) AS integer) else min(e) end+cast(avg((t1.b)) AS integer) then cast(avg(t1.d) AS integer) else  -(max(c)) end from t1)-f | b*13+e when t1.b then (f) else t1.a end in (select d from t1 union select 17 from t1)),d) FROM t1 WHERE NOT (t1.e*c>13-+t1.f | (abs((select abs(min(b)-abs( - -count(distinct 17-d-13+ -e-(t1.d)*e)+max(t1.e)) | (~abs((max(c)))+cast(avg(17) AS integer)-count(*)*cast(avg(11) AS integer))) from t1))/abs(t1.f)))}
} {}
do_test randexpr-2.1202 {
  db eval {SELECT coalesce((select t1.f from t1 where case d-(select case cast(avg(coalesce((select case when not 11<>e*c then 11 else 13 end from t1 where  -t1.c not between t1.f and 11),t1.e)) AS integer) when case max( -d) when ((min(17))) then cast(avg(t1.a) AS integer) else min(e) end+cast(avg((t1.b)) AS integer) then cast(avg(t1.d) AS integer) else  -(max(c)) end from t1)-f & b*13+e when t1.b then (f) else t1.a end in (select d from t1 union select 17 from t1)),d) FROM t1 WHERE t1.e*c>13-+t1.f | (abs((select abs(min(b)-abs( - -count(distinct 17-d-13+ -e-(t1.d)*e)+max(t1.e)) | (~abs((max(c)))+cast(avg(17) AS integer)-count(*)*cast(avg(11) AS integer))) from t1))/abs(t1.f))}
} {400}
do_test randexpr-2.1203 {
  db eval {SELECT t1.b-~case when ~(abs(17)/abs(t1.a))+17+t1.b in (select count(distinct d) | count(*) from t1 union select case count(*) | count(distinct e) when count(*) then  -count(*) else cast(avg(11) AS integer) end from t1) and t1.e>b or e not between (e) and c and 17 in (t1.c,b,b) and t1.a not between a and (t1.f) then coalesce((select t1.a*t1.c from t1 where  -11 in (t1.a,(t1.f), -f)),13)*t1.c else t1.f end FROM t1 WHERE (t1.e<>t1.a+~~c-t1.a+13*e-17+t1.b)}
} {801}
do_test randexpr-2.1204 {
  db eval {SELECT t1.b-~case when ~(abs(17)/abs(t1.a))+17+t1.b in (select count(distinct d) | count(*) from t1 union select case count(*) | count(distinct e) when count(*) then  -count(*) else cast(avg(11) AS integer) end from t1) and t1.e>b or e not between (e) and c and 17 in (t1.c,b,b) and t1.a not between a and (t1.f) then coalesce((select t1.a*t1.c from t1 where  -11 in (t1.a,(t1.f), -f)),13)*t1.c else t1.f end FROM t1 WHERE NOT ((t1.e<>t1.a+~~c-t1.a+13*e-17+t1.b))}
} {}
do_test randexpr-2.1205 {
  db eval {SELECT t1.b-~case when ~(abs(17)/abs(t1.a))+17+t1.b in (select count(distinct d) & count(*) from t1 union select case count(*) & count(distinct e) when count(*) then  -count(*) else cast(avg(11) AS integer) end from t1) and t1.e>b or e not between (e) and c and 17 in (t1.c,b,b) and t1.a not between a and (t1.f) then coalesce((select t1.a*t1.c from t1 where  -11 in (t1.a,(t1.f), -f)),13)*t1.c else t1.f end FROM t1 WHERE (t1.e<>t1.a+~~c-t1.a+13*e-17+t1.b)}
} {801}
do_test randexpr-2.1206 {
  db eval {SELECT ((abs(b)/abs(t1.e+coalesce((select max((abs(coalesce((select max(11) from t1 where t1.a<=coalesce((select case when t1.a in (case t1.b when t1.d then t1.d else a end,17,11) then 13 when t1.a>b then 19 else d end from t1 where c in (select (~case count(*) when min(f) then  -min(d) else count(distinct (t1.f)) end)*(count(*)) from t1 union select  -min((t1.c)) from t1)),11) and (b<=t1.c)),t1.f))/abs(e))-13) from t1 where b not in (d,( -e),e)),c)-t1.c))) FROM t1 WHERE (exists(select 1 from t1 where b in (select +( -abs(max(19+((select case  -+cast(avg(e) AS integer) when  -max(19)-min(t1.c) | count(*) then count(distinct t1.e) else min(f) end-cast(avg( -19) AS integer)*count(*) | count(*) from t1))-17)) | +cast(avg((select cast(avg(a) AS integer) from t1)*f) AS integer)-cast(avg(13-t1.a+b) AS integer))+ -max(t1.a) from t1 union select cast(avg( -f) AS integer) from t1)))}
} {}
do_test randexpr-2.1207 {
  db eval {SELECT ((abs(b)/abs(t1.e+coalesce((select max((abs(coalesce((select max(11) from t1 where t1.a<=coalesce((select case when t1.a in (case t1.b when t1.d then t1.d else a end,17,11) then 13 when t1.a>b then 19 else d end from t1 where c in (select (~case count(*) when min(f) then  -min(d) else count(distinct (t1.f)) end)*(count(*)) from t1 union select  -min((t1.c)) from t1)),11) and (b<=t1.c)),t1.f))/abs(e))-13) from t1 where b not in (d,( -e),e)),c)-t1.c))) FROM t1 WHERE NOT ((exists(select 1 from t1 where b in (select +( -abs(max(19+((select case  -+cast(avg(e) AS integer) when  -max(19)-min(t1.c) | count(*) then count(distinct t1.e) else min(f) end-cast(avg( -19) AS integer)*count(*) | count(*) from t1))-17)) | +cast(avg((select cast(avg(a) AS integer) from t1)*f) AS integer)-cast(avg(13-t1.a+b) AS integer))+ -max(t1.a) from t1 union select cast(avg( -f) AS integer) from t1))))}
} {1}
do_test randexpr-2.1208 {
  db eval {SELECT t1.f-17+(abs(case when ~e*coalesce((select max(coalesce((select d from t1 where not  -(19*t1.d*17) not in (t1.a*t1.c,b,b)),f)) from t1 where 13 between t1.d and 19),11* -t1.e)-(t1.a)>d then 17 when (e in (select  -(t1.d) from t1 union select  -(t1.b) from t1)) then e else  -t1.d end)/abs(17))*a FROM t1 WHERE 17 in (select 19 from t1 union select  -17 | d from t1)}
} {}
do_test randexpr-2.1209 {
  db eval {SELECT t1.f-17+(abs(case when ~e*coalesce((select max(coalesce((select d from t1 where not  -(19*t1.d*17) not in (t1.a*t1.c,b,b)),f)) from t1 where 13 between t1.d and 19),11* -t1.e)-(t1.a)>d then 17 when (e in (select  -(t1.d) from t1 union select  -(t1.b) from t1)) then e else  -t1.d end)/abs(17))*a FROM t1 WHERE NOT (17 in (select 19 from t1 union select  -17 | d from t1))}
} {683}
do_test randexpr-2.1210 {
  db eval {SELECT case t1.a when case when 13+( -f-b)*c-t1.d-t1.c | c+d>=d*case when not ++c+t1.d<>+b- -a*t1.e then  -f else 17 end+t1.f then t1.e when 11<>19 then c else 11 end then e else f end FROM t1 WHERE (case when (abs(t1.f+case f-case when exists(select 1 from t1 where t1.c>13) then t1.e when t1.f>= -f then b else e end when 13 then t1.e else t1.c end)/abs(c)) in (select max(f)*max(f)*( -max( -17)) | min(t1.a) | cast(avg(13) AS integer)+count(*) from t1 union select ( -max(e)) from t1) then ( -d) when c not between f and ( -c) then 13 else b end between t1.a and e) and 19 not between 19 and c}
} {}
do_test randexpr-2.1211 {
  db eval {SELECT case t1.a when case when 13+( -f-b)*c-t1.d-t1.c | c+d>=d*case when not ++c+t1.d<>+b- -a*t1.e then  -f else 17 end+t1.f then t1.e when 11<>19 then c else 11 end then e else f end FROM t1 WHERE NOT ((case when (abs(t1.f+case f-case when exists(select 1 from t1 where t1.c>13) then t1.e when t1.f>= -f then b else e end when 13 then t1.e else t1.c end)/abs(c)) in (select max(f)*max(f)*( -max( -17)) | min(t1.a) | cast(avg(13) AS integer)+count(*) from t1 union select ( -max(e)) from t1) then ( -d) when c not between f and ( -c) then 13 else b end between t1.a and e) and 19 not between 19 and c)}
} {600}
do_test randexpr-2.1212 {
  db eval {SELECT case t1.a when case when 13+( -f-b)*c-t1.d-t1.c & c+d>=d*case when not ++c+t1.d<>+b- -a*t1.e then  -f else 17 end+t1.f then t1.e when 11<>19 then c else 11 end then e else f end FROM t1 WHERE NOT ((case when (abs(t1.f+case f-case when exists(select 1 from t1 where t1.c>13) then t1.e when t1.f>= -f then b else e end when 13 then t1.e else t1.c end)/abs(c)) in (select max(f)*max(f)*( -max( -17)) | min(t1.a) | cast(avg(13) AS integer)+count(*) from t1 union select ( -max(e)) from t1) then ( -d) when c not between f and ( -c) then 13 else b end between t1.a and e) and 19 not between 19 and c)}
} {600}
do_test randexpr-2.1213 {
  db eval {SELECT case when 19=t1.e or (abs(t1.f)/abs(((select  -count(distinct f+~t1.e-t1.b-coalesce((select max(b*c) from t1 where 17<>b),b))+~cast(avg(d) AS integer) from t1)))) not between f and d then coalesce((select max( -a) from t1 where 13<=11 or t1.d>=f),t1.d) when 17 in (select 11 from t1 union select t1.a from t1) then t1.d else t1.c end | 19 FROM t1 WHERE (case t1.d when ~a then coalesce((select max((abs( -~+b)/abs(t1.c))) from t1 where case t1.e when (abs((abs(case t1.a++t1.d | 19-coalesce((select e from t1 where b not between t1.f+b+c and t1.b), -t1.f) when t1.e then t1.a else f end)/abs(t1.b)))/abs(t1.e)) then t1.d else t1.d end>t1.f),t1.d)*t1.b else t1.f end not between a and e)}
} {403}
do_test randexpr-2.1214 {
  db eval {SELECT case when 19=t1.e or (abs(t1.f)/abs(((select  -count(distinct f+~t1.e-t1.b-coalesce((select max(b*c) from t1 where 17<>b),b))+~cast(avg(d) AS integer) from t1)))) not between f and d then coalesce((select max( -a) from t1 where 13<=11 or t1.d>=f),t1.d) when 17 in (select 11 from t1 union select t1.a from t1) then t1.d else t1.c end | 19 FROM t1 WHERE NOT ((case t1.d when ~a then coalesce((select max((abs( -~+b)/abs(t1.c))) from t1 where case t1.e when (abs((abs(case t1.a++t1.d | 19-coalesce((select e from t1 where b not between t1.f+b+c and t1.b), -t1.f) when t1.e then t1.a else f end)/abs(t1.b)))/abs(t1.e)) then t1.d else t1.d end>t1.f),t1.d)*t1.b else t1.f end not between a and e))}
} {}
do_test randexpr-2.1215 {
  db eval {SELECT case when 19=t1.e or (abs(t1.f)/abs(((select  -count(distinct f+~t1.e-t1.b-coalesce((select max(b*c) from t1 where 17<>b),b))+~cast(avg(d) AS integer) from t1)))) not between f and d then coalesce((select max( -a) from t1 where 13<=11 or t1.d>=f),t1.d) when 17 in (select 11 from t1 union select t1.a from t1) then t1.d else t1.c end & 19 FROM t1 WHERE (case t1.d when ~a then coalesce((select max((abs( -~+b)/abs(t1.c))) from t1 where case t1.e when (abs((abs(case t1.a++t1.d | 19-coalesce((select e from t1 where b not between t1.f+b+c and t1.b), -t1.f) when t1.e then t1.a else f end)/abs(t1.b)))/abs(t1.e)) then t1.d else t1.d end>t1.f),t1.d)*t1.b else t1.f end not between a and e)}
} {16}
do_test randexpr-2.1216 {
  db eval {SELECT coalesce((select t1.c from t1 where  -a in (select e from t1 union select 13 from t1)),(select count(distinct coalesce((select max((17)) from t1 where c not between case 19-t1.b when a then ~+(abs((select count(distinct (t1.a)) from t1)+(t1.b))/abs((t1.a)*a+13 | t1.d | t1.a)) else a end and 13 or d in (a,a,t1.f)),d)) from t1) | t1.d) FROM t1 WHERE e<d or case case when  -t1.a between coalesce((select coalesce((select d from t1 where (t1.f=~coalesce((select max(t1.d) from t1 where t1.d<=t1.e),f)*19)),17) from t1 where (t1.f in ( -11,t1.f,a)) or 19<=13),t1.b) and c then t1.f when t1.d=f then t1.f else f end when t1.d then 11 else 17 end*t1.e not in (t1.a,t1.f,e)}
} {401}
do_test randexpr-2.1217 {
  db eval {SELECT coalesce((select t1.c from t1 where  -a in (select e from t1 union select 13 from t1)),(select count(distinct coalesce((select max((17)) from t1 where c not between case 19-t1.b when a then ~+(abs((select count(distinct (t1.a)) from t1)+(t1.b))/abs((t1.a)*a+13 | t1.d | t1.a)) else a end and 13 or d in (a,a,t1.f)),d)) from t1) | t1.d) FROM t1 WHERE NOT (e<d or case case when  -t1.a between coalesce((select coalesce((select d from t1 where (t1.f=~coalesce((select max(t1.d) from t1 where t1.d<=t1.e),f)*19)),17) from t1 where (t1.f in ( -11,t1.f,a)) or 19<=13),t1.b) and c then t1.f when t1.d=f then t1.f else f end when t1.d then 11 else 17 end*t1.e not in (t1.a,t1.f,e))}
} {}
do_test randexpr-2.1218 {
  db eval {SELECT coalesce((select t1.c from t1 where  -a in (select e from t1 union select 13 from t1)),(select count(distinct coalesce((select max((17)) from t1 where c not between case 19-t1.b when a then ~+(abs((select count(distinct (t1.a)) from t1)+(t1.b))/abs((t1.a)*a+13 & t1.d & t1.a)) else a end and 13 or d in (a,a,t1.f)),d)) from t1) & t1.d) FROM t1 WHERE e<d or case case when  -t1.a between coalesce((select coalesce((select d from t1 where (t1.f=~coalesce((select max(t1.d) from t1 where t1.d<=t1.e),f)*19)),17) from t1 where (t1.f in ( -11,t1.f,a)) or 19<=13),t1.b) and c then t1.f when t1.d=f then t1.f else f end when t1.d then 11 else 17 end*t1.e not in (t1.a,t1.f,e)}
} {0}
do_test randexpr-2.1219 {
  db eval {SELECT case when case when t1.b<=f+coalesce((select max(11) from t1 where not e in (select count(distinct f) from t1 union select count(*) from t1)),t1.d) or 19 between (e) and 19 and f not in (t1.d,(19),t1.e) and exists(select 1 from t1 where t1.e<=19) or t1.e>t1.a then (select +abs(count(distinct t1.f)*max(13)) from t1) else +d end>=b+t1.c and b not in (f,13,b) then t1.d when b>b then d else t1.d end*11 FROM t1 WHERE d<>b}
} {4400}
do_test randexpr-2.1220 {
  db eval {SELECT case when case when t1.b<=f+coalesce((select max(11) from t1 where not e in (select count(distinct f) from t1 union select count(*) from t1)),t1.d) or 19 between (e) and 19 and f not in (t1.d,(19),t1.e) and exists(select 1 from t1 where t1.e<=19) or t1.e>t1.a then (select +abs(count(distinct t1.f)*max(13)) from t1) else +d end>=b+t1.c and b not in (f,13,b) then t1.d when b>b then d else t1.d end*11 FROM t1 WHERE NOT (d<>b)}
} {}
do_test randexpr-2.1221 {
  db eval {SELECT ~(abs(case when t1.a not between  -t1.d*(b) and 17 then f when e<=t1.f then b*t1.d else 13*(a) end)/abs((coalesce((select d from t1 where +(abs((select (min(a)) from t1))/abs((select count(distinct a) from t1)))- -t1.a in (select  -case max(e)+count(distinct d) when cast(avg(( -t1.e)) AS integer) then ( -(count(*))) else  -min(d) end+max(t1.f) from t1 union select max(t1.a) from t1)),t1.d)))) FROM t1 WHERE (t1.a<t1.a)}
} {}
do_test randexpr-2.1222 {
  db eval {SELECT ~(abs(case when t1.a not between  -t1.d*(b) and 17 then f when e<=t1.f then b*t1.d else 13*(a) end)/abs((coalesce((select d from t1 where +(abs((select (min(a)) from t1))/abs((select count(distinct a) from t1)))- -t1.a in (select  -case max(e)+count(distinct d) when cast(avg(( -t1.e)) AS integer) then ( -(count(*))) else  -min(d) end+max(t1.f) from t1 union select max(t1.a) from t1)),t1.d)))) FROM t1 WHERE NOT ((t1.a<t1.a))}
} {-2}
do_test randexpr-2.1223 {
  db eval {SELECT f+case when (~t1.c between case when +d between (select  -abs(count(distinct t1.a+17+t1.f))+case min(19)*count(distinct  -t1.a) when (count(*)) then ((count(*))) else ((max(t1.e))) end from t1) and case when  -t1.b>=13 then 11 else a end then  -17 else a end and (t1.c) and (b=17)) then (+(t1.c)) when t1.a<=t1.f then t1.d else 11 end FROM t1 WHERE c<>~13}
} {1000}
do_test randexpr-2.1224 {
  db eval {SELECT f+case when (~t1.c between case when +d between (select  -abs(count(distinct t1.a+17+t1.f))+case min(19)*count(distinct  -t1.a) when (count(*)) then ((count(*))) else ((max(t1.e))) end from t1) and case when  -t1.b>=13 then 11 else a end then  -17 else a end and (t1.c) and (b=17)) then (+(t1.c)) when t1.a<=t1.f then t1.d else 11 end FROM t1 WHERE NOT (c<>~13)}
} {}
do_test randexpr-2.1225 {
  db eval {SELECT case when ~(abs((select count(*) from t1))/abs(c))<>case when 17*case when coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.f=t1.e)),t1.a) in (select min(t1.f) from t1 union select  -min(t1.d) from t1) then 11 when 11<=(a) then f else  -e end |  -t1.b< -c then d else f end then ((t1.a)) when t1.f in (select ~(++(count(*))+cast(avg(t1.f) AS integer))+max(( -t1.d)) from t1 union select cast(avg(e) AS integer) from t1) then 11 else d end FROM t1 WHERE t1.a between case when t1.d=t1.a*11 | (select (cast(avg(t1.a) AS integer)+abs( -count(distinct e)) | ~count(distinct coalesce((select max(b) from t1 where not exists(select 1 from t1 where  -e>=13)),(t1.e)))- -( -max(d))* -count(*)) from t1)+(abs(t1.f)/abs((select cast(avg(11) AS integer) from t1))) then t1.a else coalesce((select max(c) from t1 where 11>=t1.e or 11 in (t1.b,t1.b,t1.d) or t1.a>=t1.a),13)*a end and t1.c}
} {}
do_test randexpr-2.1226 {
  db eval {SELECT case when ~(abs((select count(*) from t1))/abs(c))<>case when 17*case when coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.f=t1.e)),t1.a) in (select min(t1.f) from t1 union select  -min(t1.d) from t1) then 11 when 11<=(a) then f else  -e end |  -t1.b< -c then d else f end then ((t1.a)) when t1.f in (select ~(++(count(*))+cast(avg(t1.f) AS integer))+max(( -t1.d)) from t1 union select cast(avg(e) AS integer) from t1) then 11 else d end FROM t1 WHERE NOT (t1.a between case when t1.d=t1.a*11 | (select (cast(avg(t1.a) AS integer)+abs( -count(distinct e)) | ~count(distinct coalesce((select max(b) from t1 where not exists(select 1 from t1 where  -e>=13)),(t1.e)))- -( -max(d))* -count(*)) from t1)+(abs(t1.f)/abs((select cast(avg(11) AS integer) from t1))) then t1.a else coalesce((select max(c) from t1 where 11>=t1.e or 11 in (t1.b,t1.b,t1.d) or t1.a>=t1.a),13)*a end and t1.c)}
} {100}
do_test randexpr-2.1227 {
  db eval {SELECT case when ~(abs((select count(*) from t1))/abs(c))<>case when 17*case when coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.f=t1.e)),t1.a) in (select min(t1.f) from t1 union select  -min(t1.d) from t1) then 11 when 11<=(a) then f else  -e end &  -t1.b< -c then d else f end then ((t1.a)) when t1.f in (select ~(++(count(*))+cast(avg(t1.f) AS integer))+max(( -t1.d)) from t1 union select cast(avg(e) AS integer) from t1) then 11 else d end FROM t1 WHERE NOT (t1.a between case when t1.d=t1.a*11 | (select (cast(avg(t1.a) AS integer)+abs( -count(distinct e)) | ~count(distinct coalesce((select max(b) from t1 where not exists(select 1 from t1 where  -e>=13)),(t1.e)))- -( -max(d))* -count(*)) from t1)+(abs(t1.f)/abs((select cast(avg(11) AS integer) from t1))) then t1.a else coalesce((select max(c) from t1 where 11>=t1.e or 11 in (t1.b,t1.b,t1.d) or t1.a>=t1.a),13)*a end and t1.c)}
} {100}
do_test randexpr-2.1228 {
  db eval {SELECT (coalesce((select 19 from t1 where  - -t1.d | t1.c+~(select max(11) |  -~count(*)+count(*)-cast(avg(case when t1.e in (select a from t1 union select f from t1) then c else 11 end) AS integer) from t1)*coalesce((select t1.b from t1 where ((abs(t1.b)/abs(coalesce((select (b)-f from t1 where t1.f not in ( -e, -t1.b, -t1.d) and t1.d>=a or 19 not in (a,13,t1.f)),b))))<t1.e),f)+b<t1.c),d)) FROM t1 WHERE t1.f | +19+f*t1.d+t1.b*d<case when (select min(t1.e) from t1) not in (t1.b,11, -b*case c when coalesce((select max(t1.b+b) from t1 where 19+13=t1.f),coalesce((select max(19*f) from t1 where t1.a=a),a)) then d else t1.f end) then t1.f when f=t1.c then a else 19 end}
} {}
do_test randexpr-2.1229 {
  db eval {SELECT (coalesce((select 19 from t1 where  - -t1.d | t1.c+~(select max(11) |  -~count(*)+count(*)-cast(avg(case when t1.e in (select a from t1 union select f from t1) then c else 11 end) AS integer) from t1)*coalesce((select t1.b from t1 where ((abs(t1.b)/abs(coalesce((select (b)-f from t1 where t1.f not in ( -e, -t1.b, -t1.d) and t1.d>=a or 19 not in (a,13,t1.f)),b))))<t1.e),f)+b<t1.c),d)) FROM t1 WHERE NOT (t1.f | +19+f*t1.d+t1.b*d<case when (select min(t1.e) from t1) not in (t1.b,11, -b*case c when coalesce((select max(t1.b+b) from t1 where 19+13=t1.f),coalesce((select max(19*f) from t1 where t1.a=a),a)) then d else t1.f end) then t1.f when f=t1.c then a else 19 end)}
} {400}
do_test randexpr-2.1230 {
  db eval {SELECT (coalesce((select 19 from t1 where  - -t1.d & t1.c+~(select max(11) &  -~count(*)+count(*)-cast(avg(case when t1.e in (select a from t1 union select f from t1) then c else 11 end) AS integer) from t1)*coalesce((select t1.b from t1 where ((abs(t1.b)/abs(coalesce((select (b)-f from t1 where t1.f not in ( -e, -t1.b, -t1.d) and t1.d>=a or 19 not in (a,13,t1.f)),b))))<t1.e),f)+b<t1.c),d)) FROM t1 WHERE NOT (t1.f | +19+f*t1.d+t1.b*d<case when (select min(t1.e) from t1) not in (t1.b,11, -b*case c when coalesce((select max(t1.b+b) from t1 where 19+13=t1.f),coalesce((select max(19*f) from t1 where t1.a=a),a)) then d else t1.f end) then t1.f when f=t1.c then a else 19 end)}
} {19}
do_test randexpr-2.1231 {
  db eval {SELECT +case when t1.f<c then 19 when f<=case t1.c when c*d then case when (t1.d=17) and not (d-case when 11<19 then t1.b when t1.d in (t1.e, - -e,c) then a else t1.d end+b in (t1.a,19,11)) then case 19 when c then t1.d else t1.d end when d in (select a from t1 union select 11 from t1) then (t1.e) else 11 end else 19 end then c else 19 end FROM t1 WHERE exists(select 1 from t1 where 19 in (select ++min(t1.f)+case abs((count(distinct 11-t1.a-t1.f)-case ((min(13))) when count(distinct t1.f) then  - -cast(avg(t1.d) AS integer) else cast(avg(t1.d) AS integer) end | count(*)*max(b)- -min(b)))- -min((b)) | min(b) | count(*)*count(*) when count(*) then max(19) else max(19) end | cast(avg(t1.b) AS integer)+min(t1.d)* -max(t1.c) | ( -( -min(t1.e)))*min(d)- -min(d) from t1 union select ((min(b))) from t1))}
} {}
do_test randexpr-2.1232 {
  db eval {SELECT +case when t1.f<c then 19 when f<=case t1.c when c*d then case when (t1.d=17) and not (d-case when 11<19 then t1.b when t1.d in (t1.e, - -e,c) then a else t1.d end+b in (t1.a,19,11)) then case 19 when c then t1.d else t1.d end when d in (select a from t1 union select 11 from t1) then (t1.e) else 11 end else 19 end then c else 19 end FROM t1 WHERE NOT (exists(select 1 from t1 where 19 in (select ++min(t1.f)+case abs((count(distinct 11-t1.a-t1.f)-case ((min(13))) when count(distinct t1.f) then  - -cast(avg(t1.d) AS integer) else cast(avg(t1.d) AS integer) end | count(*)*max(b)- -min(b)))- -min((b)) | min(b) | count(*)*count(*) when count(*) then max(19) else max(19) end | cast(avg(t1.b) AS integer)+min(t1.d)* -max(t1.c) | ( -( -min(t1.e)))*min(d)- -min(d) from t1 union select ((min(b))) from t1)))}
} {19}
do_test randexpr-2.1233 {
  db eval {SELECT ~case when exists(select 1 from t1 where t1.c in (t1.a,e+t1.b+e-19 | coalesce((select max(t1.f | t1.a+11*a) from t1 where (abs((abs(f)/abs(d)))/abs(coalesce((select max(t1.a) from t1 where (13 between (f) and f and t1.e between e and t1.b)),t1.c)))<=(f)),e)+f+13, -t1.c)) then t1.b when t1.d<>t1.d then (17) else e end+t1.d-19 FROM t1 WHERE not  -t1.e+t1.c not between case when  -case case when exists(select 1 from t1 where 17 in (select min(19) from t1 union select  -min(19) from t1) and 13 not in (17,a,t1.e)) then case when f>=19 then (c) when t1.f>13 then 19 else 19 end | t1.a else e end when b then t1.c else b end in (select  -max(13) from t1 union select count(distinct 17) from t1) and 11 not in (11,t1.a,f) and t1.c=f then ~(abs(t1.e)/abs(t1.d)) when f<13 then 17 else 19 end*b and t1.e}
} {}
do_test randexpr-2.1234 {
  db eval {SELECT ~case when exists(select 1 from t1 where t1.c in (t1.a,e+t1.b+e-19 | coalesce((select max(t1.f | t1.a+11*a) from t1 where (abs((abs(f)/abs(d)))/abs(coalesce((select max(t1.a) from t1 where (13 between (f) and f and t1.e between e and t1.b)),t1.c)))<=(f)),e)+f+13, -t1.c)) then t1.b when t1.d<>t1.d then (17) else e end+t1.d-19 FROM t1 WHERE NOT (not  -t1.e+t1.c not between case when  -case case when exists(select 1 from t1 where 17 in (select min(19) from t1 union select  -min(19) from t1) and 13 not in (17,a,t1.e)) then case when f>=19 then (c) when t1.f>13 then 19 else 19 end | t1.a else e end when b then t1.c else b end in (select  -max(13) from t1 union select count(distinct 17) from t1) and 11 not in (11,t1.a,f) and t1.c=f then ~(abs(t1.e)/abs(t1.d)) when f<13 then 17 else 19 end*b and t1.e)}
} {-120}
do_test randexpr-2.1235 {
  db eval {SELECT ~case when exists(select 1 from t1 where t1.c in (t1.a,e+t1.b+e-19 & coalesce((select max(t1.f & t1.a+11*a) from t1 where (abs((abs(f)/abs(d)))/abs(coalesce((select max(t1.a) from t1 where (13 between (f) and f and t1.e between e and t1.b)),t1.c)))<=(f)),e)+f+13, -t1.c)) then t1.b when t1.d<>t1.d then (17) else e end+t1.d-19 FROM t1 WHERE NOT (not  -t1.e+t1.c not between case when  -case case when exists(select 1 from t1 where 17 in (select min(19) from t1 union select  -min(19) from t1) and 13 not in (17,a,t1.e)) then case when f>=19 then (c) when t1.f>13 then 19 else 19 end | t1.a else e end when b then t1.c else b end in (select  -max(13) from t1 union select count(distinct 17) from t1) and 11 not in (11,t1.a,f) and t1.c=f then ~(abs(t1.e)/abs(t1.d)) when f<13 then 17 else 19 end*b and t1.e)}
} {-120}
do_test randexpr-2.1236 {
  db eval {SELECT ((select min(e+case when b not between coalesce((select t1.d | b from t1 where not exists(select 1 from t1 where 17>11)), -c) and (t1.a) or e<t1.b and (11)<>d then a when 19>11 then  -13 else t1.b end+13)+count(distinct d)+count(*)* -count(distinct t1.f)-((count(distinct t1.c)))+min(a) | max(c) from t1)*t1.e*19*11) FROM t1 WHERE b<>(select count(distinct f) from t1)}
} {104918000}
do_test randexpr-2.1237 {
  db eval {SELECT ((select min(e+case when b not between coalesce((select t1.d | b from t1 where not exists(select 1 from t1 where 17>11)), -c) and (t1.a) or e<t1.b and (11)<>d then a when 19>11 then  -13 else t1.b end+13)+count(distinct d)+count(*)* -count(distinct t1.f)-((count(distinct t1.c)))+min(a) | max(c) from t1)*t1.e*19*11) FROM t1 WHERE NOT (b<>(select count(distinct f) from t1))}
} {}
do_test randexpr-2.1238 {
  db eval {SELECT ((select min(e+case when b not between coalesce((select t1.d & b from t1 where not exists(select 1 from t1 where 17>11)), -c) and (t1.a) or e<t1.b and (11)<>d then a when 19>11 then  -13 else t1.b end+13)+count(distinct d)+count(*)* -count(distinct t1.f)-((count(distinct t1.c)))+min(a) & max(c) from t1)*t1.e*19*11) FROM t1 WHERE b<>(select count(distinct f) from t1)}
} {836000}
do_test randexpr-2.1239 {
  db eval {SELECT coalesce((select max(t1.a) from t1 where +b-b+t1.e<>(case when (case when ((select case  -cast(avg(17) AS integer) when max(17) then count(*) else count(distinct t1.d) end from t1))-case 19 when 11 then e else t1.f end<=e then 19 when b not between t1.c and 13 then e else 17 end+t1.c in (select 19 from t1 union select a from t1)) then e-t1.c else t1.f end*t1.b)-e),a) FROM t1 WHERE coalesce((select 13 from t1 where t1.c<>t1.b | t1.e*19-e),f+t1.d) not in (13,(c)*a,e)}
} {}
do_test randexpr-2.1240 {
  db eval {SELECT coalesce((select max(t1.a) from t1 where +b-b+t1.e<>(case when (case when ((select case  -cast(avg(17) AS integer) when max(17) then count(*) else count(distinct t1.d) end from t1))-case 19 when 11 then e else t1.f end<=e then 19 when b not between t1.c and 13 then e else 17 end+t1.c in (select 19 from t1 union select a from t1)) then e-t1.c else t1.f end*t1.b)-e),a) FROM t1 WHERE NOT (coalesce((select 13 from t1 where t1.c<>t1.b | t1.e*19-e),f+t1.d) not in (13,(c)*a,e))}
} {100}
do_test randexpr-2.1241 {
  db eval {SELECT t1.d-case when (11) not between coalesce((select max(a) from t1 where f in (select cast(avg(t1.c+(select case case case max(a) when  -count(*) then min(b) else  - -(min((t1.a))) end when (max((19))) then max(t1.f) else count(*) end when max(t1.a) then  -min(t1.c) else count(*) end from t1)+c+t1.d) AS integer)-min(a) |  -cast(avg(f) AS integer)*(cast(avg(f) AS integer))-( -count(*)) from t1 union select min( -c) from t1)),t1.a) and  -c then (d) when t1.f<=((t1.c)) then  - -13 else c end FROM t1 WHERE 13-e>(abs(t1.f)/abs((t1.d)*d))}
} {}
do_test randexpr-2.1242 {
  db eval {SELECT t1.d-case when (11) not between coalesce((select max(a) from t1 where f in (select cast(avg(t1.c+(select case case case max(a) when  -count(*) then min(b) else  - -(min((t1.a))) end when (max((19))) then max(t1.f) else count(*) end when max(t1.a) then  -min(t1.c) else count(*) end from t1)+c+t1.d) AS integer)-min(a) |  -cast(avg(f) AS integer)*(cast(avg(f) AS integer))-( -count(*)) from t1 union select min( -c) from t1)),t1.a) and  -c then (d) when t1.f<=((t1.c)) then  - -13 else c end FROM t1 WHERE NOT (13-e>(abs(t1.f)/abs((t1.d)*d)))}
} {0}
do_test randexpr-2.1243 {
  db eval {SELECT t1.d-case when (11) not between coalesce((select max(a) from t1 where f in (select cast(avg(t1.c+(select case case case max(a) when  -count(*) then min(b) else  - -(min((t1.a))) end when (max((19))) then max(t1.f) else count(*) end when max(t1.a) then  -min(t1.c) else count(*) end from t1)+c+t1.d) AS integer)-min(a) &  -cast(avg(f) AS integer)*(cast(avg(f) AS integer))-( -count(*)) from t1 union select min( -c) from t1)),t1.a) and  -c then (d) when t1.f<=((t1.c)) then  - -13 else c end FROM t1 WHERE NOT (13-e>(abs(t1.f)/abs((t1.d)*d)))}
} {0}
do_test randexpr-2.1244 {
  db eval {SELECT (abs(coalesce((select max(b) from t1 where not exists(select 1 from t1 where 19>(t1.c))),(11+(abs(c)/abs(19)))+b)+coalesce((select max(t1.c) from t1 where t1.a<=13),t1.d+t1.b+case when exists(select 1 from t1 where  -t1.b in (select min(t1.a-+13) from t1 union select max(t1.c) from t1)) then (select ++(cast(avg(11) AS integer)) | cast(avg(b) AS integer)*cast(avg(d) AS integer) from t1) when f>=b then 19 else 19 end))/abs(b)) FROM t1 WHERE not b in (select case when t1.e in (select +cast(avg(d) AS integer)-count(*)*count(*)-(case ~count(distinct d)*cast(avg(t1.b) AS integer) when count(distinct t1.e) then max(19) else cast(avg(t1.b) AS integer) end+(count(distinct t1.c))) from t1 union select  -min(t1.f) from t1) or 19<=+11 then ((select (min(t1.b)) from t1)*a-19+17*13) | a when (11 in (select d from t1 union select t1.e from t1)) then 19 else t1.b end from t1 union select t1.c from t1)}
} {}
do_test randexpr-2.1245 {
  db eval {SELECT (abs(coalesce((select max(b) from t1 where not exists(select 1 from t1 where 19>(t1.c))),(11+(abs(c)/abs(19)))+b)+coalesce((select max(t1.c) from t1 where t1.a<=13),t1.d+t1.b+case when exists(select 1 from t1 where  -t1.b in (select min(t1.a-+13) from t1 union select max(t1.c) from t1)) then (select ++(cast(avg(11) AS integer)) | cast(avg(b) AS integer)*cast(avg(d) AS integer) from t1) when f>=b then 19 else 19 end))/abs(b)) FROM t1 WHERE NOT (not b in (select case when t1.e in (select +cast(avg(d) AS integer)-count(*)*count(*)-(case ~count(distinct d)*cast(avg(t1.b) AS integer) when count(distinct t1.e) then max(19) else cast(avg(t1.b) AS integer) end+(count(distinct t1.c))) from t1 union select  -min(t1.f) from t1) or 19<=+11 then ((select (min(t1.b)) from t1)*a-19+17*13) | a when (11 in (select d from t1 union select t1.e from t1)) then 19 else t1.b end from t1 union select t1.c from t1))}
} {4}
do_test randexpr-2.1246 {
  db eval {SELECT (abs(coalesce((select max(b) from t1 where not exists(select 1 from t1 where 19>(t1.c))),(11+(abs(c)/abs(19)))+b)+coalesce((select max(t1.c) from t1 where t1.a<=13),t1.d+t1.b+case when exists(select 1 from t1 where  -t1.b in (select min(t1.a-+13) from t1 union select max(t1.c) from t1)) then (select ++(cast(avg(11) AS integer)) & cast(avg(b) AS integer)*cast(avg(d) AS integer) from t1) when f>=b then 19 else 19 end))/abs(b)) FROM t1 WHERE NOT (not b in (select case when t1.e in (select +cast(avg(d) AS integer)-count(*)*count(*)-(case ~count(distinct d)*cast(avg(t1.b) AS integer) when count(distinct t1.e) then max(19) else cast(avg(t1.b) AS integer) end+(count(distinct t1.c))) from t1 union select  -min(t1.f) from t1) or 19<=+11 then ((select (min(t1.b)) from t1)*a-19+17*13) | a when (11 in (select d from t1 union select t1.e from t1)) then 19 else t1.b end from t1 union select t1.c from t1))}
} {4}
do_test randexpr-2.1247 {
  db eval {SELECT +case ~t1.d when case when b*f in (select b from t1 union select 17 from t1) and ((case when t1.f | e in (select ~abs(~(case cast(avg(t1.f) AS integer) when min(b) then min(t1.d) else  - -count(distinct e) end | count(*)*( -cast(avg(t1.b) AS integer)))) from t1 union select (count(distinct t1.b)) from t1) then t1.f else t1.f*17+a end-13+e<>t1.c)) then d else t1.c end then t1.f else t1.e end+19 FROM t1 WHERE b>=+t1.e or f<=t1.b and  -c*17-t1.d*19 not in (c+coalesce((select (abs(~+d*t1.f)/abs(11)) from t1 where +case when t1.d+ -t1.e in (select max(t1.d)*count(distinct b) from t1 union select count(distinct 11) from t1) then (17) when (t1.e>t1.a) then e else e end not in (e,f,t1.a)),t1.f),t1.a,b)}
} {}
do_test randexpr-2.1248 {
  db eval {SELECT +case ~t1.d when case when b*f in (select b from t1 union select 17 from t1) and ((case when t1.f | e in (select ~abs(~(case cast(avg(t1.f) AS integer) when min(b) then min(t1.d) else  - -count(distinct e) end | count(*)*( -cast(avg(t1.b) AS integer)))) from t1 union select (count(distinct t1.b)) from t1) then t1.f else t1.f*17+a end-13+e<>t1.c)) then d else t1.c end then t1.f else t1.e end+19 FROM t1 WHERE NOT (b>=+t1.e or f<=t1.b and  -c*17-t1.d*19 not in (c+coalesce((select (abs(~+d*t1.f)/abs(11)) from t1 where +case when t1.d+ -t1.e in (select max(t1.d)*count(distinct b) from t1 union select count(distinct 11) from t1) then (17) when (t1.e>t1.a) then e else e end not in (e,f,t1.a)),t1.f),t1.a,b))}
} {519}
do_test randexpr-2.1249 {
  db eval {SELECT +case ~t1.d when case when b*f in (select b from t1 union select 17 from t1) and ((case when t1.f & e in (select ~abs(~(case cast(avg(t1.f) AS integer) when min(b) then min(t1.d) else  - -count(distinct e) end & count(*)*( -cast(avg(t1.b) AS integer)))) from t1 union select (count(distinct t1.b)) from t1) then t1.f else t1.f*17+a end-13+e<>t1.c)) then d else t1.c end then t1.f else t1.e end+19 FROM t1 WHERE NOT (b>=+t1.e or f<=t1.b and  -c*17-t1.d*19 not in (c+coalesce((select (abs(~+d*t1.f)/abs(11)) from t1 where +case when t1.d+ -t1.e in (select max(t1.d)*count(distinct b) from t1 union select count(distinct 11) from t1) then (17) when (t1.e>t1.a) then e else e end not in (e,f,t1.a)),t1.f),t1.a,b))}
} {519}
do_test randexpr-2.1250 {
  db eval {SELECT (abs((abs(t1.a)/abs(~17 | coalesce((select ~coalesce((select (d) from t1 where t1.b>=t1.a),case when t1.e-(select ~max( -19*c | e+t1.c) from t1) not between (abs(c)/abs(e)) and t1.e then a else 17 end*17)+13 from t1 where a in (select max(t1.f) from t1 union select ~count(distinct b) from t1)),b) | 13)))/abs(e)) FROM t1 WHERE exists(select 1 from t1 where t1.a+t1.d-11<=t1.e)}
} {0}
do_test randexpr-2.1251 {
  db eval {SELECT (abs((abs(t1.a)/abs(~17 | coalesce((select ~coalesce((select (d) from t1 where t1.b>=t1.a),case when t1.e-(select ~max( -19*c | e+t1.c) from t1) not between (abs(c)/abs(e)) and t1.e then a else 17 end*17)+13 from t1 where a in (select max(t1.f) from t1 union select ~count(distinct b) from t1)),b) | 13)))/abs(e)) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.a+t1.d-11<=t1.e))}
} {}
do_test randexpr-2.1252 {
  db eval {SELECT (abs((abs(t1.a)/abs(~17 & coalesce((select ~coalesce((select (d) from t1 where t1.b>=t1.a),case when t1.e-(select ~max( -19*c & e+t1.c) from t1) not between (abs(c)/abs(e)) and t1.e then a else 17 end*17)+13 from t1 where a in (select max(t1.f) from t1 union select ~count(distinct b) from t1)),b) & 13)))/abs(e)) FROM t1 WHERE exists(select 1 from t1 where t1.a+t1.d-11<=t1.e)}
} {0}
do_test randexpr-2.1253 {
  db eval {SELECT coalesce((select max(d) from t1 where not exists(select 1 from t1 where t1.e not in (13,e,coalesce((select f from t1 where (abs(case  -t1.e when ~f then (t1.c)*13-t1.b+a-d+ -t1.a else a end)/abs(11))*19*t1.d>=a),(t1.b)))) or d not in (f,e,19)),coalesce((select max(17) from t1 where e in (select t1.e from t1 union select 17 from t1)),t1.c)) | t1.f FROM t1 WHERE t1.e not in (13,(select +count(*)+abs(cast(avg(case t1.d when 17 then  -t1.e+13 else (abs( -c)/abs(case when t1.e*+coalesce((select max(13) from t1 where a>t1.b),t1.f)>=(13) then  -f else t1.a end)) end) AS integer)) from t1)*(13),(select ((max(t1.d))) from t1)) and not exists(select 1 from t1 where e+b not in (b,t1.c,t1.e))}
} {}
do_test randexpr-2.1254 {
  db eval {SELECT coalesce((select max(d) from t1 where not exists(select 1 from t1 where t1.e not in (13,e,coalesce((select f from t1 where (abs(case  -t1.e when ~f then (t1.c)*13-t1.b+a-d+ -t1.a else a end)/abs(11))*19*t1.d>=a),(t1.b)))) or d not in (f,e,19)),coalesce((select max(17) from t1 where e in (select t1.e from t1 union select 17 from t1)),t1.c)) | t1.f FROM t1 WHERE NOT (t1.e not in (13,(select +count(*)+abs(cast(avg(case t1.d when 17 then  -t1.e+13 else (abs( -c)/abs(case when t1.e*+coalesce((select max(13) from t1 where a>t1.b),t1.f)>=(13) then  -f else t1.a end)) end) AS integer)) from t1)*(13),(select ((max(t1.d))) from t1)) and not exists(select 1 from t1 where e+b not in (b,t1.c,t1.e)))}
} {984}
do_test randexpr-2.1255 {
  db eval {SELECT coalesce((select max(d) from t1 where not exists(select 1 from t1 where t1.e not in (13,e,coalesce((select f from t1 where (abs(case  -t1.e when ~f then (t1.c)*13-t1.b+a-d+ -t1.a else a end)/abs(11))*19*t1.d>=a),(t1.b)))) or d not in (f,e,19)),coalesce((select max(17) from t1 where e in (select t1.e from t1 union select 17 from t1)),t1.c)) & t1.f FROM t1 WHERE NOT (t1.e not in (13,(select +count(*)+abs(cast(avg(case t1.d when 17 then  -t1.e+13 else (abs( -c)/abs(case when t1.e*+coalesce((select max(13) from t1 where a>t1.b),t1.f)>=(13) then  -f else t1.a end)) end) AS integer)) from t1)*(13),(select ((max(t1.d))) from t1)) and not exists(select 1 from t1 where e+b not in (b,t1.c,t1.e)))}
} {16}
do_test randexpr-2.1256 {
  db eval {SELECT (abs(case when (t1.d*coalesce((select max(case coalesce((select max(e) from t1 where t1.a not in (coalesce((select (select count(distinct t1.e) from t1) from t1 where c>=t1.c),f),19,a)),t1.a) when t1.c then t1.a else b end-a) from t1 where c>t1.d),b)<= -11) then t1.a when not exists(select 1 from t1 where not (t1.d=e) or t1.f between t1.a and  -e and (t1.c)=f and a not in (t1.c,a,c)) then t1.a else t1.a end)/abs( -13))+e-d FROM t1 WHERE 17 not in (13,19,t1.c)}
} {107}
do_test randexpr-2.1257 {
  db eval {SELECT (abs(case when (t1.d*coalesce((select max(case coalesce((select max(e) from t1 where t1.a not in (coalesce((select (select count(distinct t1.e) from t1) from t1 where c>=t1.c),f),19,a)),t1.a) when t1.c then t1.a else b end-a) from t1 where c>t1.d),b)<= -11) then t1.a when not exists(select 1 from t1 where not (t1.d=e) or t1.f between t1.a and  -e and (t1.c)=f and a not in (t1.c,a,c)) then t1.a else t1.a end)/abs( -13))+e-d FROM t1 WHERE NOT (17 not in (13,19,t1.c))}
} {}
do_test randexpr-2.1258 {
  db eval {SELECT ~ -coalesce((select c from t1 where (case when b<= -e*t1.f then +coalesce((select case when (select count(*) from t1)=e then t1.f | c else f end from t1 where e>=(select ~case count(*) when  -abs(max(11)-count(distinct  -t1.d)) then count(distinct e) else max(f) end*count(*) from t1)),13) else 19 end>=t1.e)),case when t1.c<t1.a then t1.f else a end |  -a*d)-13-17 FROM t1 WHERE (abs(coalesce((select  -coalesce((select max((select +count(distinct a | t1.d)- -(((count(distinct d))))-max(t1.c) from t1)) from t1 where (( -case t1.b when 17 then 17 else 13 end<c))),t1.b) from t1 where d not in (t1.c,19,17) or t1.a in (select (max(b)) from t1 union select (cast(avg(b) AS integer)) from t1)),(t1.b))*19)/abs(e))<a or (not exists(select 1 from t1 where t1.f not in (a, -17,e))) and (t1.a) in (select cast(avg(e) AS integer) from t1 union select max(19) from t1)}
} {-39995}
do_test randexpr-2.1259 {
  db eval {SELECT ~ -coalesce((select c from t1 where (case when b<= -e*t1.f then +coalesce((select case when (select count(*) from t1)=e then t1.f | c else f end from t1 where e>=(select ~case count(*) when  -abs(max(11)-count(distinct  -t1.d)) then count(distinct e) else max(f) end*count(*) from t1)),13) else 19 end>=t1.e)),case when t1.c<t1.a then t1.f else a end |  -a*d)-13-17 FROM t1 WHERE NOT ((abs(coalesce((select  -coalesce((select max((select +count(distinct a | t1.d)- -(((count(distinct d))))-max(t1.c) from t1)) from t1 where (( -case t1.b when 17 then 17 else 13 end<c))),t1.b) from t1 where d not in (t1.c,19,17) or t1.a in (select (max(b)) from t1 union select (cast(avg(b) AS integer)) from t1)),(t1.b))*19)/abs(e))<a or (not exists(select 1 from t1 where t1.f not in (a, -17,e))) and (t1.a) in (select cast(avg(e) AS integer) from t1 union select max(19) from t1))}
} {}
do_test randexpr-2.1260 {
  db eval {SELECT ~ -coalesce((select c from t1 where (case when b<= -e*t1.f then +coalesce((select case when (select count(*) from t1)=e then t1.f & c else f end from t1 where e>=(select ~case count(*) when  -abs(max(11)-count(distinct  -t1.d)) then count(distinct e) else max(f) end*count(*) from t1)),13) else 19 end>=t1.e)),case when t1.c<t1.a then t1.f else a end &  -a*d)-13-17 FROM t1 WHERE (abs(coalesce((select  -coalesce((select max((select +count(distinct a | t1.d)- -(((count(distinct d))))-max(t1.c) from t1)) from t1 where (( -case t1.b when 17 then 17 else 13 end<c))),t1.b) from t1 where d not in (t1.c,19,17) or t1.a in (select (max(b)) from t1 union select (cast(avg(b) AS integer)) from t1)),(t1.b))*19)/abs(e))<a or (not exists(select 1 from t1 where t1.f not in (a, -17,e))) and (t1.a) in (select cast(avg(e) AS integer) from t1 union select max(19) from t1)}
} {33}
do_test randexpr-2.1261 {
  db eval {SELECT case t1.b when coalesce((select t1.b from t1 where not exists(select 1 from t1 where +case ( -case f when 13 then (abs(t1.b+f)/abs(c)) else t1.d end) when f*t1.f+t1.d then e else coalesce((select coalesce((select max(b) from t1 where t1.a<=t1.a or t1.d+f<=19 or t1.b in (select (11) from t1 union select (19) from t1)),t1.d) from t1 where not exists(select 1 from t1 where 17=b)),c)+e end between t1.c and b)),d) then c else t1.d end FROM t1 WHERE b>t1.e | case when exists(select 1 from t1 where not ~+11<=coalesce((select max(a) from t1 where ~17*case when a=+(select cast(avg(t1.a*e) AS integer) from t1) then t1.e when c<11 then b else f end+c not between t1.e and  -17), -t1.c)) then e+c when not exists(select 1 from t1 where t1.c not between 13 and  -f) then 17 else  -t1.d end or (f)<=c}
} {300}
do_test randexpr-2.1262 {
  db eval {SELECT case t1.b when coalesce((select t1.b from t1 where not exists(select 1 from t1 where +case ( -case f when 13 then (abs(t1.b+f)/abs(c)) else t1.d end) when f*t1.f+t1.d then e else coalesce((select coalesce((select max(b) from t1 where t1.a<=t1.a or t1.d+f<=19 or t1.b in (select (11) from t1 union select (19) from t1)),t1.d) from t1 where not exists(select 1 from t1 where 17=b)),c)+e end between t1.c and b)),d) then c else t1.d end FROM t1 WHERE NOT (b>t1.e | case when exists(select 1 from t1 where not ~+11<=coalesce((select max(a) from t1 where ~17*case when a=+(select cast(avg(t1.a*e) AS integer) from t1) then t1.e when c<11 then b else f end+c not between t1.e and  -17), -t1.c)) then e+c when not exists(select 1 from t1 where t1.c not between 13 and  -f) then 17 else  -t1.d end or (f)<=c)}
} {}
do_test randexpr-2.1263 {
  db eval {SELECT case when case when case when exists(select 1 from t1 where exists(select 1 from t1 where t1.a+t1.a | case when t1.b between f and 19 and t1.c<a then t1.e else t1.d end<e)) then a else coalesce((select 11 from t1 where c in (select  -(abs(count(*)) | cast(avg(t1.b) AS integer))+( -min(17))+ -(count(distinct t1.e)) from t1 union select max((t1.a)) from t1)),a) end-t1.d=13 then t1.a else e end*t1.e*t1.c>=t1.e then t1.e else 19 end | a FROM t1 WHERE t1.b not in ((a),t1.d,b)}
} {}
do_test randexpr-2.1264 {
  db eval {SELECT case when case when case when exists(select 1 from t1 where exists(select 1 from t1 where t1.a+t1.a | case when t1.b between f and 19 and t1.c<a then t1.e else t1.d end<e)) then a else coalesce((select 11 from t1 where c in (select  -(abs(count(*)) | cast(avg(t1.b) AS integer))+( -min(17))+ -(count(distinct t1.e)) from t1 union select max((t1.a)) from t1)),a) end-t1.d=13 then t1.a else e end*t1.e*t1.c>=t1.e then t1.e else 19 end | a FROM t1 WHERE NOT (t1.b not in ((a),t1.d,b))}
} {500}
do_test randexpr-2.1265 {
  db eval {SELECT case when case when case when exists(select 1 from t1 where exists(select 1 from t1 where t1.a+t1.a & case when t1.b between f and 19 and t1.c<a then t1.e else t1.d end<e)) then a else coalesce((select 11 from t1 where c in (select  -(abs(count(*)) & cast(avg(t1.b) AS integer))+( -min(17))+ -(count(distinct t1.e)) from t1 union select max((t1.a)) from t1)),a) end-t1.d=13 then t1.a else e end*t1.e*t1.c>=t1.e then t1.e else 19 end & a FROM t1 WHERE NOT (t1.b not in ((a),t1.d,b))}
} {100}
do_test randexpr-2.1266 {
  db eval {SELECT case when exists(select 1 from t1 where a between 13+t1.e and t1.e and (abs((abs(case when not 19 between t1.e and b and not exists(select 1 from t1 where (abs(17)/abs(f-c)) not between (d) and t1.e) then t1.e else 19 end)/abs(11)))/abs(19))=f) or t1.e<= -a then t1.b when exists(select 1 from t1 where t1.d>t1.c) and t1.b<19 then a else 11 end*d FROM t1 WHERE exists(select 1 from t1 where t1.e<>(select count(distinct ((coalesce((select coalesce((select max( -coalesce((select max( -e) from t1 where ((abs(t1.a)/abs(d)) in (select ~~count(*) from t1 union select count(*) from t1) or a in (d,t1.f,d) and  -c in (b,e,t1.d))),t1.c)-19 | 11-t1.e) from t1 where exists(select 1 from t1 where a<=e) and f not in (17,t1.b,t1.c) or (t1.a)>=t1.d),e)-t1.c from t1 where b<t1.d or d<= -t1.c),t1.e)))) from t1))}
} {4400}
do_test randexpr-2.1267 {
  db eval {SELECT case when exists(select 1 from t1 where a between 13+t1.e and t1.e and (abs((abs(case when not 19 between t1.e and b and not exists(select 1 from t1 where (abs(17)/abs(f-c)) not between (d) and t1.e) then t1.e else 19 end)/abs(11)))/abs(19))=f) or t1.e<= -a then t1.b when exists(select 1 from t1 where t1.d>t1.c) and t1.b<19 then a else 11 end*d FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e<>(select count(distinct ((coalesce((select coalesce((select max( -coalesce((select max( -e) from t1 where ((abs(t1.a)/abs(d)) in (select ~~count(*) from t1 union select count(*) from t1) or a in (d,t1.f,d) and  -c in (b,e,t1.d))),t1.c)-19 | 11-t1.e) from t1 where exists(select 1 from t1 where a<=e) and f not in (17,t1.b,t1.c) or (t1.a)>=t1.d),e)-t1.c from t1 where b<t1.d or d<= -t1.c),t1.e)))) from t1)))}
} {}
do_test randexpr-2.1268 {
  db eval {SELECT t1.c | 13-19-d+case when t1.d-t1.b+t1.f*t1.a-coalesce((select max(c-17-case when t1.e<c then t1.f when exists(select 1 from t1 where d between  -c and f) then t1.a else 17 end) from t1 where 11 in (select a from t1 union select 17 from t1)),c)*11-d in (select c from t1 union select t1.c from t1) then 17 when 11 between a and (a) then a else t1.a end FROM t1 WHERE t1.a<b}
} {-18}
do_test randexpr-2.1269 {
  db eval {SELECT t1.c | 13-19-d+case when t1.d-t1.b+t1.f*t1.a-coalesce((select max(c-17-case when t1.e<c then t1.f when exists(select 1 from t1 where d between  -c and f) then t1.a else 17 end) from t1 where 11 in (select a from t1 union select 17 from t1)),c)*11-d in (select c from t1 union select t1.c from t1) then 17 when 11 between a and (a) then a else t1.a end FROM t1 WHERE NOT (t1.a<b)}
} {}
do_test randexpr-2.1270 {
  db eval {SELECT t1.c & 13-19-d+case when t1.d-t1.b+t1.f*t1.a-coalesce((select max(c-17-case when t1.e<c then t1.f when exists(select 1 from t1 where d between  -c and f) then t1.a else 17 end) from t1 where 11 in (select a from t1 union select 17 from t1)),c)*11-d in (select c from t1 union select t1.c from t1) then 17 when 11 between a and (a) then a else t1.a end FROM t1 WHERE t1.a<b}
} {12}
do_test randexpr-2.1271 {
  db eval {SELECT case when coalesce((select b from t1 where t1.d not in (t1.c,case when t1.d not in (d,coalesce((select (select count(distinct d) from t1)*e from t1 where not exists(select 1 from t1 where t1.d>=t1.f) or 11+t1.a between (select  -cast(avg( -t1.b | 19) AS integer)+case min(t1.d) when  -max(t1.e) then  -count(distinct 11) else  - -max((t1.c)) end from t1) and f),(e)),13) then t1.a else d end* -t1.f,13)),d)>=e then 17 else  -11 end FROM t1 WHERE t1.d*b<=+~t1.c-t1.d+d*~b | e}
} {}
do_test randexpr-2.1272 {
  db eval {SELECT case when coalesce((select b from t1 where t1.d not in (t1.c,case when t1.d not in (d,coalesce((select (select count(distinct d) from t1)*e from t1 where not exists(select 1 from t1 where t1.d>=t1.f) or 11+t1.a between (select  -cast(avg( -t1.b | 19) AS integer)+case min(t1.d) when  -max(t1.e) then  -count(distinct 11) else  - -max((t1.c)) end from t1) and f),(e)),13) then t1.a else d end* -t1.f,13)),d)>=e then 17 else  -11 end FROM t1 WHERE NOT (t1.d*b<=+~t1.c-t1.d+d*~b | e)}
} {-11}
do_test randexpr-2.1273 {
  db eval {SELECT case when coalesce((select b from t1 where t1.d not in (t1.c,case when t1.d not in (d,coalesce((select (select count(distinct d) from t1)*e from t1 where not exists(select 1 from t1 where t1.d>=t1.f) or 11+t1.a between (select  -cast(avg( -t1.b & 19) AS integer)+case min(t1.d) when  -max(t1.e) then  -count(distinct 11) else  - -max((t1.c)) end from t1) and f),(e)),13) then t1.a else d end* -t1.f,13)),d)>=e then 17 else  -11 end FROM t1 WHERE NOT (t1.d*b<=+~t1.c-t1.d+d*~b | e)}
} {-11}
do_test randexpr-2.1274 {
  db eval {SELECT t1.a*a+11-case when exists(select 1 from t1 where (t1.d)<d and (b=case when t1.d+(t1.c*c)*t1.b=t1.f then t1.e else  -11 end)) or not exists(select 1 from t1 where t1.d between 13 and  -19 and d<>b) and (19 not in ((t1.a),11,a)) then ~t1.b when t1.c<c then ~c else a end FROM t1 WHERE a+d> -coalesce((select (select max(e) | min(coalesce((select coalesce((select t1.d from t1 where a<a),11)+c from t1 where (b<e)),19)+t1.c)*abs(count(*))*case count(*) when  -min(a) then min(t1.c) else max( -19) end* -count(*) from t1) from t1 where (abs((abs(e)/abs(t1.e)))/abs(t1.e)) between a and b),((t1.a)))-17 and t1.e not between 13 and 17}
} {10212}
do_test randexpr-2.1275 {
  db eval {SELECT t1.a*a+11-case when exists(select 1 from t1 where (t1.d)<d and (b=case when t1.d+(t1.c*c)*t1.b=t1.f then t1.e else  -11 end)) or not exists(select 1 from t1 where t1.d between 13 and  -19 and d<>b) and (19 not in ((t1.a),11,a)) then ~t1.b when t1.c<c then ~c else a end FROM t1 WHERE NOT (a+d> -coalesce((select (select max(e) | min(coalesce((select coalesce((select t1.d from t1 where a<a),11)+c from t1 where (b<e)),19)+t1.c)*abs(count(*))*case count(*) when  -min(a) then min(t1.c) else max( -19) end* -count(*) from t1) from t1 where (abs((abs(e)/abs(t1.e)))/abs(t1.e)) between a and b),((t1.a)))-17 and t1.e not between 13 and 17)}
} {}
do_test randexpr-2.1276 {
  db eval {SELECT case when case when case (abs(t1.b)/abs(t1.a)) when e then f else t1.a end>c then 19 else b end- -11 in (select case case count(distinct t1.f) | (max(17)) when (count(*)) then count(distinct b) else count(distinct 19) end when min(t1.f) then (count(distinct t1.f)) else count(*) end-min(13) from t1 union select cast(avg( -t1.c) AS integer) from t1) or f<>t1.a then coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where t1.e>=t1.e)), -t1.a) when exists(select 1 from t1 where 17 between t1.f and t1.d) then t1.c else c end FROM t1 WHERE t1.b=t1.b}
} {200}
do_test randexpr-2.1277 {
  db eval {SELECT case when case when case (abs(t1.b)/abs(t1.a)) when e then f else t1.a end>c then 19 else b end- -11 in (select case case count(distinct t1.f) | (max(17)) when (count(*)) then count(distinct b) else count(distinct 19) end when min(t1.f) then (count(distinct t1.f)) else count(*) end-min(13) from t1 union select cast(avg( -t1.c) AS integer) from t1) or f<>t1.a then coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where t1.e>=t1.e)), -t1.a) when exists(select 1 from t1 where 17 between t1.f and t1.d) then t1.c else c end FROM t1 WHERE NOT (t1.b=t1.b)}
} {}
do_test randexpr-2.1278 {
  db eval {SELECT case when case when case (abs(t1.b)/abs(t1.a)) when e then f else t1.a end>c then 19 else b end- -11 in (select case case count(distinct t1.f) & (max(17)) when (count(*)) then count(distinct b) else count(distinct 19) end when min(t1.f) then (count(distinct t1.f)) else count(*) end-min(13) from t1 union select cast(avg( -t1.c) AS integer) from t1) or f<>t1.a then coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where t1.e>=t1.e)), -t1.a) when exists(select 1 from t1 where 17 between t1.f and t1.d) then t1.c else c end FROM t1 WHERE t1.b=t1.b}
} {200}
do_test randexpr-2.1279 {
  db eval {SELECT (abs(b)/abs(case 19 when case e+13*~t1.c*11 when case when (select ~min(t1.a) from t1)>t1.c then (case when 11 between (a) and (19) then d else d+t1.c end) else f end then (abs((e+t1.d)*e*19-t1.d)/abs(c)) else t1.b end then 11 else ( -t1.b) end*13)) FROM t1 WHERE case when ((select min( -case when b in (d-t1.e,case when e in (select d from t1 union select 17 from t1) then 11 else c end,( -t1.d)) then t1.b when b>e then c else  -t1.f end)+ -((min(t1.f)))-+min(f) | ( -(cast(avg(a) AS integer))) from t1)) in (select 11 from t1 union select 19 from t1) then 19 when not exists(select 1 from t1 where  -17>t1.f and t1.e in (select t1.e from t1 union select d from t1)) then 11 else d end=t1.d}
} {}
do_test randexpr-2.1280 {
  db eval {SELECT (abs(b)/abs(case 19 when case e+13*~t1.c*11 when case when (select ~min(t1.a) from t1)>t1.c then (case when 11 between (a) and (19) then d else d+t1.c end) else f end then (abs((e+t1.d)*e*19-t1.d)/abs(c)) else t1.b end then 11 else ( -t1.b) end*13)) FROM t1 WHERE NOT (case when ((select min( -case when b in (d-t1.e,case when e in (select d from t1 union select 17 from t1) then 11 else c end,( -t1.d)) then t1.b when b>e then c else  -t1.f end)+ -((min(t1.f)))-+min(f) | ( -(cast(avg(a) AS integer))) from t1)) in (select 11 from t1 union select 19 from t1) then 19 when not exists(select 1 from t1 where  -17>t1.f and t1.e in (select t1.e from t1 union select d from t1)) then 11 else d end=t1.d)}
} {0}
do_test randexpr-2.1281 {
  db eval {SELECT coalesce((select max(11) from t1 where not not exists(select 1 from t1 where ((abs(b)/abs(t1.f))-19+f-case ~11 when 19 then c else t1.a end)> -c+t1.a)),(11))- -b FROM t1 WHERE b*case when 19 not in (t1.e,a*+t1.d,(abs(+c)/abs(case 11 when b then +case when (not exists(select 1 from t1 where d<=c or c<t1.d or f<=b)) then e*19 | d+f else (t1.d) end | t1.d else b end))) then t1.b when not exists(select 1 from t1 where  -t1.e between 11 and e) then a else 17 end*t1.f between  -c and  -t1.d}
} {}
do_test randexpr-2.1282 {
  db eval {SELECT coalesce((select max(11) from t1 where not not exists(select 1 from t1 where ((abs(b)/abs(t1.f))-19+f-case ~11 when 19 then c else t1.a end)> -c+t1.a)),(11))- -b FROM t1 WHERE NOT (b*case when 19 not in (t1.e,a*+t1.d,(abs(+c)/abs(case 11 when b then +case when (not exists(select 1 from t1 where d<=c or c<t1.d or f<=b)) then e*19 | d+f else (t1.d) end | t1.d else b end))) then t1.b when not exists(select 1 from t1 where  -t1.e between 11 and e) then a else 17 end*t1.f between  -c and  -t1.d)}
} {211}
do_test randexpr-2.1283 {
  db eval {SELECT case when ((select count(*) from t1) not between b+t1.f and  -(coalesce((select max(coalesce((select max((select count(*) from t1) |  -case when ~19-b between a and 17 and (t1.c) between (13) and d and t1.a<=a then f-19 when 19<t1.d then f else t1.d end) from t1 where  - -t1.d between t1.b and a),t1.c)) from t1 where 11<(11)),e)-t1.c)) then b+t1.f else (b) end+13 FROM t1 WHERE e in (case when 17+b-17*+11 | +case when ~b-17*t1.d in (13,19, -t1.b) or 13 between t1.a and d and 11 not in (t1.e,f, -b) then t1.d*17 else b end not in (17,17,t1.c) then t1.c when t1.d not in (f,e,b) then t1.d else 11 end,11,t1.a)}
} {}
do_test randexpr-2.1284 {
  db eval {SELECT case when ((select count(*) from t1) not between b+t1.f and  -(coalesce((select max(coalesce((select max((select count(*) from t1) |  -case when ~19-b between a and 17 and (t1.c) between (13) and d and t1.a<=a then f-19 when 19<t1.d then f else t1.d end) from t1 where  - -t1.d between t1.b and a),t1.c)) from t1 where 11<(11)),e)-t1.c)) then b+t1.f else (b) end+13 FROM t1 WHERE NOT (e in (case when 17+b-17*+11 | +case when ~b-17*t1.d in (13,19, -t1.b) or 13 between t1.a and d and 11 not in (t1.e,f, -b) then t1.d*17 else b end not in (17,17,t1.c) then t1.c when t1.d not in (f,e,b) then t1.d else 11 end,11,t1.a))}
} {813}
do_test randexpr-2.1285 {
  db eval {SELECT case when ((select count(*) from t1) not between b+t1.f and  -(coalesce((select max(coalesce((select max((select count(*) from t1) &  -case when ~19-b between a and 17 and (t1.c) between (13) and d and t1.a<=a then f-19 when 19<t1.d then f else t1.d end) from t1 where  - -t1.d between t1.b and a),t1.c)) from t1 where 11<(11)),e)-t1.c)) then b+t1.f else (b) end+13 FROM t1 WHERE NOT (e in (case when 17+b-17*+11 | +case when ~b-17*t1.d in (13,19, -t1.b) or 13 between t1.a and d and 11 not in (t1.e,f, -b) then t1.d*17 else b end not in (17,17,t1.c) then t1.c when t1.d not in (f,e,b) then t1.d else 11 end,11,t1.a))}
} {813}
do_test randexpr-2.1286 {
  db eval {SELECT case coalesce((select t1.e from t1 where 19 in (select 13 from t1 union select 11 | coalesce((select  -(t1.c) from t1 where t1.a<=t1.c),case when ~case when t1.e not between 11 and t1.e then d else 19 end+t1.a+f in (select  -(count(distinct  -c))-max(d)+count(distinct t1.d) from t1 union select cast(avg((b)) AS integer) from t1) then (t1.d) when not (t1.a not in ( -t1.e,t1.b,17) and 11<d) then e else b end) from t1)),11) when t1.c then a else a end-t1.b FROM t1 WHERE t1.d>=11*t1.d}
} {}
do_test randexpr-2.1287 {
  db eval {SELECT case coalesce((select t1.e from t1 where 19 in (select 13 from t1 union select 11 | coalesce((select  -(t1.c) from t1 where t1.a<=t1.c),case when ~case when t1.e not between 11 and t1.e then d else 19 end+t1.a+f in (select  -(count(distinct  -c))-max(d)+count(distinct t1.d) from t1 union select cast(avg((b)) AS integer) from t1) then (t1.d) when not (t1.a not in ( -t1.e,t1.b,17) and 11<d) then e else b end) from t1)),11) when t1.c then a else a end-t1.b FROM t1 WHERE NOT (t1.d>=11*t1.d)}
} {-100}
do_test randexpr-2.1288 {
  db eval {SELECT case coalesce((select t1.e from t1 where 19 in (select 13 from t1 union select 11 & coalesce((select  -(t1.c) from t1 where t1.a<=t1.c),case when ~case when t1.e not between 11 and t1.e then d else 19 end+t1.a+f in (select  -(count(distinct  -c))-max(d)+count(distinct t1.d) from t1 union select cast(avg((b)) AS integer) from t1) then (t1.d) when not (t1.a not in ( -t1.e,t1.b,17) and 11<d) then e else b end) from t1)),11) when t1.c then a else a end-t1.b FROM t1 WHERE NOT (t1.d>=11*t1.d)}
} {-100}
do_test randexpr-2.1289 {
  db eval {SELECT (select min(coalesce((select max(case (b | case  -e when 11 then +(abs(17)/abs((19))) else 13 end) when t1.f then 17 else a end) from t1 where 17 not between e and  -a and 19=13 or t1.f=19 and t1.c<e and t1.c in (select cast(avg(19) AS integer)*min(c) from t1 union select +count(*) from t1)),t1.c)) from t1)*t1.e-t1.a FROM t1 WHERE (19)<>t1.b}
} {149900}
do_test randexpr-2.1290 {
  db eval {SELECT (select min(coalesce((select max(case (b | case  -e when 11 then +(abs(17)/abs((19))) else 13 end) when t1.f then 17 else a end) from t1 where 17 not between e and  -a and 19=13 or t1.f=19 and t1.c<e and t1.c in (select cast(avg(19) AS integer)*min(c) from t1 union select +count(*) from t1)),t1.c)) from t1)*t1.e-t1.a FROM t1 WHERE NOT ((19)<>t1.b)}
} {}
do_test randexpr-2.1291 {
  db eval {SELECT (select min(coalesce((select max(case (b & case  -e when 11 then +(abs(17)/abs((19))) else 13 end) when t1.f then 17 else a end) from t1 where 17 not between e and  -a and 19=13 or t1.f=19 and t1.c<e and t1.c in (select cast(avg(19) AS integer)*min(c) from t1 union select +count(*) from t1)),t1.c)) from t1)*t1.e-t1.a FROM t1 WHERE (19)<>t1.b}
} {149900}
do_test randexpr-2.1292 {
  db eval {SELECT t1.f*b | coalesce((select max(t1.f) from t1 where (case when (select cast(avg((select (count(distinct e+t1.c)) from t1)) AS integer) from t1)=t1.d then case when not exists(select 1 from t1 where (b)+t1.e+t1.f in (select min(e) from t1 union select case count(distinct t1.c) when count(distinct f) then cast(avg((t1.f)) AS integer) else (cast(avg(13) AS integer)) end from t1)) and not exists(select 1 from t1 where (d=b)) then t1.d when 13 in (f,c,c) then case t1.c when 11 then  -a else t1.b end else 13 end else 19 end)<17),19)-t1.a FROM t1 WHERE c>=case when d<t1.e then t1.b when t1.f not between 11 and 17 then coalesce((select max( -~e | (17-c)) from t1 where not exists(select 1 from t1 where (( -13-b) in (select ++cast(avg(b) AS integer) from t1 union select case  -case ~max(e)-count(*) when (min(19)) then count(*) else max(t1.c) end |  -cast(avg(11) AS integer) when max(b) then (max(e)) else count(*) end | min(t1.d) from t1)))),t1.d) else t1.c end}
} {-17}
do_test randexpr-2.1293 {
  db eval {SELECT t1.f*b | coalesce((select max(t1.f) from t1 where (case when (select cast(avg((select (count(distinct e+t1.c)) from t1)) AS integer) from t1)=t1.d then case when not exists(select 1 from t1 where (b)+t1.e+t1.f in (select min(e) from t1 union select case count(distinct t1.c) when count(distinct f) then cast(avg((t1.f)) AS integer) else (cast(avg(13) AS integer)) end from t1)) and not exists(select 1 from t1 where (d=b)) then t1.d when 13 in (f,c,c) then case t1.c when 11 then  -a else t1.b end else 13 end else 19 end)<17),19)-t1.a FROM t1 WHERE NOT (c>=case when d<t1.e then t1.b when t1.f not between 11 and 17 then coalesce((select max( -~e | (17-c)) from t1 where not exists(select 1 from t1 where (( -13-b) in (select ++cast(avg(b) AS integer) from t1 union select case  -case ~max(e)-count(*) when (min(19)) then count(*) else max(t1.c) end |  -cast(avg(11) AS integer) when max(b) then (max(e)) else count(*) end | min(t1.d) from t1)))),t1.d) else t1.c end)}
} {}
do_test randexpr-2.1294 {
  db eval {SELECT t1.f*b & coalesce((select max(t1.f) from t1 where (case when (select cast(avg((select (count(distinct e+t1.c)) from t1)) AS integer) from t1)=t1.d then case when not exists(select 1 from t1 where (b)+t1.e+t1.f in (select min(e) from t1 union select case count(distinct t1.c) when count(distinct f) then cast(avg((t1.f)) AS integer) else (cast(avg(13) AS integer)) end from t1)) and not exists(select 1 from t1 where (d=b)) then t1.d when 13 in (f,c,c) then case t1.c when 11 then  -a else t1.b end else 13 end else 19 end)<17),19)-t1.a FROM t1 WHERE c>=case when d<t1.e then t1.b when t1.f not between 11 and 17 then coalesce((select max( -~e | (17-c)) from t1 where not exists(select 1 from t1 where (( -13-b) in (select ++cast(avg(b) AS integer) from t1 union select case  -case ~max(e)-count(*) when (min(19)) then count(*) else max(t1.c) end |  -cast(avg(11) AS integer) when max(b) then (max(e)) else count(*) end | min(t1.d) from t1)))),t1.d) else t1.c end}
} {119936}
do_test randexpr-2.1295 {
  db eval {SELECT +case when b in (13,(t1.f),19+a) and not exists(select 1 from t1 where  -case when case when case (abs(coalesce((select b from t1 where t1.b>=t1.a),t1.e))/abs(13)) when t1.b then b else  -a end=11 then 13 else a end<>t1.f or 19 not in (b,(t1.b), -19) then b else e end<>e) then t1.f else c end | t1.a+d- -f+f FROM t1 WHERE a in (13+17,case when (t1.a>t1.e) then ~t1.c+d*case coalesce((select coalesce((select d from t1 where 11 not between t1.e and coalesce((select t1.b from t1 where  -coalesce((select max(t1.b) from t1 where t1.d in (a,11,d) and b=c),c) between b and d),(t1.e))),t1.f) from t1 where t1.e=a),t1.a) when 17 then (t1.f) else t1.d end+b+c when a>=t1.d then t1.a else f end,b)}
} {}
do_test randexpr-2.1296 {
  db eval {SELECT +case when b in (13,(t1.f),19+a) and not exists(select 1 from t1 where  -case when case when case (abs(coalesce((select b from t1 where t1.b>=t1.a),t1.e))/abs(13)) when t1.b then b else  -a end=11 then 13 else a end<>t1.f or 19 not in (b,(t1.b), -19) then b else e end<>e) then t1.f else c end | t1.a+d- -f+f FROM t1 WHERE NOT (a in (13+17,case when (t1.a>t1.e) then ~t1.c+d*case coalesce((select coalesce((select d from t1 where 11 not between t1.e and coalesce((select t1.b from t1 where  -coalesce((select max(t1.b) from t1 where t1.d in (a,11,d) and b=c),c) between b and d),(t1.e))),t1.f) from t1 where t1.e=a),t1.a) when 17 then (t1.f) else t1.d end+b+c when a>=t1.d then t1.a else f end,b))}
} {1964}
do_test randexpr-2.1297 {
  db eval {SELECT +case when b in (13,(t1.f),19+a) and not exists(select 1 from t1 where  -case when case when case (abs(coalesce((select b from t1 where t1.b>=t1.a),t1.e))/abs(13)) when t1.b then b else  -a end=11 then 13 else a end<>t1.f or 19 not in (b,(t1.b), -19) then b else e end<>e) then t1.f else c end & t1.a+d- -f+f FROM t1 WHERE NOT (a in (13+17,case when (t1.a>t1.e) then ~t1.c+d*case coalesce((select coalesce((select d from t1 where 11 not between t1.e and coalesce((select t1.b from t1 where  -coalesce((select max(t1.b) from t1 where t1.d in (a,11,d) and b=c),c) between b and d),(t1.e))),t1.f) from t1 where t1.e=a),t1.a) when 17 then (t1.f) else t1.d end+b+c when a>=t1.d then t1.a else f end,b))}
} {36}
do_test randexpr-2.1298 {
  db eval {SELECT coalesce((select t1.b from t1 where 17+13+t1.b in (e,19,case when 17 in (select case max(b*17-d*t1.b*t1.d)+case max((19)) when ~ -max(t1.f) then +count(*) else cast(avg(13) AS integer) end when count(distinct 11) then min(e) else max(t1.c) end from t1 union select min(d) from t1) then t1.a* -(t1.a) when t1.c=19 then (t1.c) else t1.f end) and t1.f<=13),17) FROM t1 WHERE t1.e<>~t1.b}
} {17}
do_test randexpr-2.1299 {
  db eval {SELECT coalesce((select t1.b from t1 where 17+13+t1.b in (e,19,case when 17 in (select case max(b*17-d*t1.b*t1.d)+case max((19)) when ~ -max(t1.f) then +count(*) else cast(avg(13) AS integer) end when count(distinct 11) then min(e) else max(t1.c) end from t1 union select min(d) from t1) then t1.a* -(t1.a) when t1.c=19 then (t1.c) else t1.f end) and t1.f<=13),17) FROM t1 WHERE NOT (t1.e<>~t1.b)}
} {}
do_test randexpr-2.1300 {
  db eval {SELECT (abs(coalesce((select  -~(abs(t1.d)/abs(a)) from t1 where case when f in (select ~~(+abs( - -count(*)) | cast(avg(d) AS integer)) from t1 union select (min(f)) from t1) then (abs(t1.c)/abs( -13)) | f-13+d*17 when a in (t1.f,t1.c,11) then f else  -(f) end*c not in (13,d,d) and 19 in (t1.d,t1.d,b)),13))/abs(17)) FROM t1 WHERE exists(select 1 from t1 where t1.d<>case case when not exists(select 1 from t1 where t1.b<e and t1.c>(abs(c)/abs(t1.a))) then t1.b else 17 end when +~(e- -coalesce((select e from t1 where not (b) in (select max(t1.b) from t1 union select case max(t1.e)-max(17)-count(distinct (13)) when  -cast(avg( -t1.b) AS integer) then count(distinct d) else min(t1.f) end from t1)),c*d))*a*13 | f then (13) else c end)}
} {0}
do_test randexpr-2.1301 {
  db eval {SELECT (abs(coalesce((select  -~(abs(t1.d)/abs(a)) from t1 where case when f in (select ~~(+abs( - -count(*)) | cast(avg(d) AS integer)) from t1 union select (min(f)) from t1) then (abs(t1.c)/abs( -13)) | f-13+d*17 when a in (t1.f,t1.c,11) then f else  -(f) end*c not in (13,d,d) and 19 in (t1.d,t1.d,b)),13))/abs(17)) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d<>case case when not exists(select 1 from t1 where t1.b<e and t1.c>(abs(c)/abs(t1.a))) then t1.b else 17 end when +~(e- -coalesce((select e from t1 where not (b) in (select max(t1.b) from t1 union select case max(t1.e)-max(17)-count(distinct (13)) when  -cast(avg( -t1.b) AS integer) then count(distinct d) else min(t1.f) end from t1)),c*d))*a*13 | f then (13) else c end))}
} {}
do_test randexpr-2.1302 {
  db eval {SELECT (abs(coalesce((select  -~(abs(t1.d)/abs(a)) from t1 where case when f in (select ~~(+abs( - -count(*)) & cast(avg(d) AS integer)) from t1 union select (min(f)) from t1) then (abs(t1.c)/abs( -13)) & f-13+d*17 when a in (t1.f,t1.c,11) then f else  -(f) end*c not in (13,d,d) and 19 in (t1.d,t1.d,b)),13))/abs(17)) FROM t1 WHERE exists(select 1 from t1 where t1.d<>case case when not exists(select 1 from t1 where t1.b<e and t1.c>(abs(c)/abs(t1.a))) then t1.b else 17 end when +~(e- -coalesce((select e from t1 where not (b) in (select max(t1.b) from t1 union select case max(t1.e)-max(17)-count(distinct (13)) when  -cast(avg( -t1.b) AS integer) then count(distinct d) else min(t1.f) end from t1)),c*d))*a*13 | f then (13) else c end)}
} {0}
do_test randexpr-2.1303 {
  db eval {SELECT t1.f*+case when ( -17-a*t1.f | case when (coalesce((select max((case a when +13*19* -b then a else 17 end)) from t1 where (t1.b) not between 13 and t1.a),e))-t1.b=t1.f then f else 17 end-b*a*d)<>11 then f else t1.c end-t1.c*e FROM t1 WHERE (select +cast(avg(case when 13*a in (select 11 from t1 union select b from t1) then e when t1.f in (select ~count(distinct f) | count(*) from t1 union select count(distinct 13*t1.a+coalesce((select max(e) from t1 where ~(abs(t1.e)/abs(a)) not in (t1.a+e-c,t1.e,case when t1.f>t1.c or f>t1.c then 13 when t1.c>c then t1.a else  -t1.d end)),f)*19) from t1) then d else d end) AS integer) from t1)=d}
} {210000}
do_test randexpr-2.1304 {
  db eval {SELECT t1.f*+case when ( -17-a*t1.f | case when (coalesce((select max((case a when +13*19* -b then a else 17 end)) from t1 where (t1.b) not between 13 and t1.a),e))-t1.b=t1.f then f else 17 end-b*a*d)<>11 then f else t1.c end-t1.c*e FROM t1 WHERE NOT ((select +cast(avg(case when 13*a in (select 11 from t1 union select b from t1) then e when t1.f in (select ~count(distinct f) | count(*) from t1 union select count(distinct 13*t1.a+coalesce((select max(e) from t1 where ~(abs(t1.e)/abs(a)) not in (t1.a+e-c,t1.e,case when t1.f>t1.c or f>t1.c then 13 when t1.c>c then t1.a else  -t1.d end)),f)*19) from t1) then d else d end) AS integer) from t1)=d)}
} {}
do_test randexpr-2.1305 {
  db eval {SELECT t1.f*+case when ( -17-a*t1.f & case when (coalesce((select max((case a when +13*19* -b then a else 17 end)) from t1 where (t1.b) not between 13 and t1.a),e))-t1.b=t1.f then f else 17 end-b*a*d)<>11 then f else t1.c end-t1.c*e FROM t1 WHERE (select +cast(avg(case when 13*a in (select 11 from t1 union select b from t1) then e when t1.f in (select ~count(distinct f) | count(*) from t1 union select count(distinct 13*t1.a+coalesce((select max(e) from t1 where ~(abs(t1.e)/abs(a)) not in (t1.a+e-c,t1.e,case when t1.f>t1.c or f>t1.c then 13 when t1.c>c then t1.a else  -t1.d end)),f)*19) from t1) then d else d end) AS integer) from t1)=d}
} {210000}
do_test randexpr-2.1306 {
  db eval {SELECT t1.c+case when t1.a in (select max(coalesce((select coalesce((select coalesce((select max(19+case t1.f when a then e else t1.d end) from t1 where t1.d> -c),b) from t1 where (t1.c=e) and t1.f=17), -a) from t1 where (e not between e and 11)),t1.f)) | cast(avg(t1.a) AS integer)*max(t1.c) from t1 union select count(distinct c)-max(a) | min(t1.b) | (count(*))* -min(f) from t1) then t1.a when exists(select 1 from t1 where not exists(select 1 from t1 where  -17>11)) then (13) else 13 end FROM t1 WHERE 19=case when exists(select 1 from t1 where t1.f not between 11 and ~c+b-t1.c*case when t1.f<13+(t1.d) and  -t1.f<17 or (b<>b) then ~d else t1.b end) or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e=19)) then c+f*17 else t1.a end and t1.e<13}
} {}
do_test randexpr-2.1307 {
  db eval {SELECT t1.c+case when t1.a in (select max(coalesce((select coalesce((select coalesce((select max(19+case t1.f when a then e else t1.d end) from t1 where t1.d> -c),b) from t1 where (t1.c=e) and t1.f=17), -a) from t1 where (e not between e and 11)),t1.f)) | cast(avg(t1.a) AS integer)*max(t1.c) from t1 union select count(distinct c)-max(a) | min(t1.b) | (count(*))* -min(f) from t1) then t1.a when exists(select 1 from t1 where not exists(select 1 from t1 where  -17>11)) then (13) else 13 end FROM t1 WHERE NOT (19=case when exists(select 1 from t1 where t1.f not between 11 and ~c+b-t1.c*case when t1.f<13+(t1.d) and  -t1.f<17 or (b<>b) then ~d else t1.b end) or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e=19)) then c+f*17 else t1.a end and t1.e<13)}
} {313}
do_test randexpr-2.1308 {
  db eval {SELECT t1.c+case when t1.a in (select max(coalesce((select coalesce((select coalesce((select max(19+case t1.f when a then e else t1.d end) from t1 where t1.d> -c),b) from t1 where (t1.c=e) and t1.f=17), -a) from t1 where (e not between e and 11)),t1.f)) & cast(avg(t1.a) AS integer)*max(t1.c) from t1 union select count(distinct c)-max(a) & min(t1.b) & (count(*))* -min(f) from t1) then t1.a when exists(select 1 from t1 where not exists(select 1 from t1 where  -17>11)) then (13) else 13 end FROM t1 WHERE NOT (19=case when exists(select 1 from t1 where t1.f not between 11 and ~c+b-t1.c*case when t1.f<13+(t1.d) and  -t1.f<17 or (b<>b) then ~d else t1.b end) or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e=19)) then c+f*17 else t1.a end and t1.e<13)}
} {313}
do_test randexpr-2.1309 {
  db eval {SELECT 13-case when exists(select 1 from t1 where f+b>t1.f+t1.c) or +17 |  -coalesce((select case coalesce((select 13-(select (cast(avg(13) AS integer))-max(t1.b) from t1) from t1 where  -c in (select max(17) from t1 union select max(t1.b) from t1)),t1.a) when t1.d then 19 else d end from t1 where d>=11),b) between 13 and 11 and 17<=13 then a | t1.c+t1.f else c end FROM t1 WHERE (case when a not in (t1.d+t1.f,b,t1.b) then case when case f | t1.c when t1.e then e else (t1.a)-d | 13 end<>f then t1.e when (((13) in (select min(t1.a) from t1 union select max( -e) from t1) or t1.f between 13 and  -t1.b or (f>=f) or 19<c or t1.d<=13)) then 13 else 19 end else  -t1.b end) not between 17 and e}
} {}
do_test randexpr-2.1310 {
  db eval {SELECT 13-case when exists(select 1 from t1 where f+b>t1.f+t1.c) or +17 |  -coalesce((select case coalesce((select 13-(select (cast(avg(13) AS integer))-max(t1.b) from t1) from t1 where  -c in (select max(17) from t1 union select max(t1.b) from t1)),t1.a) when t1.d then 19 else d end from t1 where d>=11),b) between 13 and 11 and 17<=13 then a | t1.c+t1.f else c end FROM t1 WHERE NOT ((case when a not in (t1.d+t1.f,b,t1.b) then case when case f | t1.c when t1.e then e else (t1.a)-d | 13 end<>f then t1.e when (((13) in (select min(t1.a) from t1 union select max( -e) from t1) or t1.f between 13 and  -t1.b or (f>=f) or 19<c or t1.d<=13)) then 13 else 19 end else  -t1.b end) not between 17 and e)}
} {-287}
do_test randexpr-2.1311 {
  db eval {SELECT 13-case when exists(select 1 from t1 where f+b>t1.f+t1.c) or +17 &  -coalesce((select case coalesce((select 13-(select (cast(avg(13) AS integer))-max(t1.b) from t1) from t1 where  -c in (select max(17) from t1 union select max(t1.b) from t1)),t1.a) when t1.d then 19 else d end from t1 where d>=11),b) between 13 and 11 and 17<=13 then a & t1.c+t1.f else c end FROM t1 WHERE NOT ((case when a not in (t1.d+t1.f,b,t1.b) then case when case f | t1.c when t1.e then e else (t1.a)-d | 13 end<>f then t1.e when (((13) in (select min(t1.a) from t1 union select max( -e) from t1) or t1.f between 13 and  -t1.b or (f>=f) or 19<c or t1.d<=13)) then 13 else 19 end else  -t1.b end) not between 17 and e)}
} {-287}
do_test randexpr-2.1312 {
  db eval {SELECT a+case when ((~t1.d*13<=e or (coalesce((select coalesce((select case when  -t1.e<>t1.e or f between b and 13 then t1.c else c end |  -b from t1 where 17<=17),t1.e) from t1 where 11<c and t1.b not between f and t1.d or 13<=17),t1.f)) not in (13,t1.e,13) and ((13>=d) and t1.e>17))) then t1.a | (select ~ - -cast(avg( -c) AS integer) from t1) else c end FROM t1 WHERE t1.f>=e and t1.f in (select 17 from t1 union select case when (not exists(select 1 from t1 where case when coalesce((select max(19+t1.c) from t1 where 17>=t1.f),c)+19+t1.c< -d then t1.d when t1.c not in (c,t1.f,e) then 17 else t1.d end<t1.e) or (f<=t1.b)) and t1.a not in (a,11, -t1.f) then coalesce((select f from t1 where 17 not in (e,b,t1.f)),t1.f-t1.d) | t1.b when  -19<>11 then d else 13 end from t1)}
} {}
do_test randexpr-2.1313 {
  db eval {SELECT a+case when ((~t1.d*13<=e or (coalesce((select coalesce((select case when  -t1.e<>t1.e or f between b and 13 then t1.c else c end |  -b from t1 where 17<=17),t1.e) from t1 where 11<c and t1.b not between f and t1.d or 13<=17),t1.f)) not in (13,t1.e,13) and ((13>=d) and t1.e>17))) then t1.a | (select ~ - -cast(avg( -c) AS integer) from t1) else c end FROM t1 WHERE NOT (t1.f>=e and t1.f in (select 17 from t1 union select case when (not exists(select 1 from t1 where case when coalesce((select max(19+t1.c) from t1 where 17>=t1.f),c)+19+t1.c< -d then t1.d when t1.c not in (c,t1.f,e) then 17 else t1.d end<t1.e) or (f<=t1.b)) and t1.a not in (a,11, -t1.f) then coalesce((select f from t1 where 17 not in (e,b,t1.f)),t1.f-t1.d) | t1.b when  -19<>11 then d else 13 end from t1))}
} {467}
do_test randexpr-2.1314 {
  db eval {SELECT a+case when ((~t1.d*13<=e or (coalesce((select coalesce((select case when  -t1.e<>t1.e or f between b and 13 then t1.c else c end &  -b from t1 where 17<=17),t1.e) from t1 where 11<c and t1.b not between f and t1.d or 13<=17),t1.f)) not in (13,t1.e,13) and ((13>=d) and t1.e>17))) then t1.a & (select ~ - -cast(avg( -c) AS integer) from t1) else c end FROM t1 WHERE NOT (t1.f>=e and t1.f in (select 17 from t1 union select case when (not exists(select 1 from t1 where case when coalesce((select max(19+t1.c) from t1 where 17>=t1.f),c)+19+t1.c< -d then t1.d when t1.c not in (c,t1.f,e) then 17 else t1.d end<t1.e) or (f<=t1.b)) and t1.a not in (a,11, -t1.f) then coalesce((select f from t1 where 17 not in (e,b,t1.f)),t1.f-t1.d) | t1.b when  -19<>11 then d else 13 end from t1))}
} {132}
do_test randexpr-2.1315 {
  db eval {SELECT case when t1.b not in (17 | t1.e*t1.a,11,(select +case max((select  -+case (max(t1.f)) when count(*) then count(distinct d) else  -( -(cast(avg(f) AS integer))) end-count(distinct t1.a) from t1)) | count(distinct (t1.e)) when  -min(c) then count(*) else  -count(distinct e) end | cast(avg(17) AS integer) from t1)) then case when d<=t1.c and (exists(select 1 from t1 where (select count(distinct (e)) from t1)=(abs(17)/abs(d)))) then (abs(t1.f)/abs(t1.c)) when t1.f<>e or t1.c<=d and t1.e<=t1.d then 19 else  - -d end-t1.e else (t1.f) end FROM t1 WHERE not t1.b=coalesce((select (abs(c)/abs(11)) from t1 where exists(select 1 from t1 where  -coalesce((select max(((abs(coalesce((select max(case (select min((abs(19)/abs(19))+19)*count(*)- -cast(avg(t1.d) AS integer)-max(17)+min( -11) from t1) when e then t1.e else f end) from t1 where t1.d<=t1.f), -f)- -t1.e)/abs(d))-t1.b)) from t1 where c<11),t1.b)*a not in (d,d,f))),c)}
} {-481}
do_test randexpr-2.1316 {
  db eval {SELECT case when t1.b not in (17 | t1.e*t1.a,11,(select +case max((select  -+case (max(t1.f)) when count(*) then count(distinct d) else  -( -(cast(avg(f) AS integer))) end-count(distinct t1.a) from t1)) | count(distinct (t1.e)) when  -min(c) then count(*) else  -count(distinct e) end | cast(avg(17) AS integer) from t1)) then case when d<=t1.c and (exists(select 1 from t1 where (select count(distinct (e)) from t1)=(abs(17)/abs(d)))) then (abs(t1.f)/abs(t1.c)) when t1.f<>e or t1.c<=d and t1.e<=t1.d then 19 else  - -d end-t1.e else (t1.f) end FROM t1 WHERE NOT (not t1.b=coalesce((select (abs(c)/abs(11)) from t1 where exists(select 1 from t1 where  -coalesce((select max(((abs(coalesce((select max(case (select min((abs(19)/abs(19))+19)*count(*)- -cast(avg(t1.d) AS integer)-max(17)+min( -11) from t1) when e then t1.e else f end) from t1 where t1.d<=t1.f), -f)- -t1.e)/abs(d))-t1.b)) from t1 where c<11),t1.b)*a not in (d,d,f))),c))}
} {}
do_test randexpr-2.1317 {
  db eval {SELECT case when t1.b not in (17 & t1.e*t1.a,11,(select +case max((select  -+case (max(t1.f)) when count(*) then count(distinct d) else  -( -(cast(avg(f) AS integer))) end-count(distinct t1.a) from t1)) & count(distinct (t1.e)) when  -min(c) then count(*) else  -count(distinct e) end & cast(avg(17) AS integer) from t1)) then case when d<=t1.c and (exists(select 1 from t1 where (select count(distinct (e)) from t1)=(abs(17)/abs(d)))) then (abs(t1.f)/abs(t1.c)) when t1.f<>e or t1.c<=d and t1.e<=t1.d then 19 else  - -d end-t1.e else (t1.f) end FROM t1 WHERE not t1.b=coalesce((select (abs(c)/abs(11)) from t1 where exists(select 1 from t1 where  -coalesce((select max(((abs(coalesce((select max(case (select min((abs(19)/abs(19))+19)*count(*)- -cast(avg(t1.d) AS integer)-max(17)+min( -11) from t1) when e then t1.e else f end) from t1 where t1.d<=t1.f), -f)- -t1.e)/abs(d))-t1.b)) from t1 where c<11),t1.b)*a not in (d,d,f))),c)}
} {-481}
do_test randexpr-2.1318 {
  db eval {SELECT  -t1.a*(select (cast(avg((select count(*)-abs(count(*)*count(*)) from t1)) AS integer)++max(t1.d))*cast(avg(t1.a) AS integer) from t1)+t1.c+t1.c+d-e | 11+t1.b-coalesce((select max(case when exists(select 1 from t1 where t1.a+11=t1.b) then c when t1.a not between t1.f and t1.d or 13<11 then  -b else 19 end) from t1 where c>=t1.f),t1.f) FROM t1 WHERE exists(select 1 from t1 where (f=(d)*e))}
} {}
do_test randexpr-2.1319 {
  db eval {SELECT  -t1.a*(select (cast(avg((select count(*)-abs(count(*)*count(*)) from t1)) AS integer)++max(t1.d))*cast(avg(t1.a) AS integer) from t1)+t1.c+t1.c+d-e | 11+t1.b-coalesce((select max(case when exists(select 1 from t1 where t1.a+11=t1.b) then c when t1.a not between t1.f and t1.d or 13<11 then  -b else 19 end) from t1 where c>=t1.f),t1.f) FROM t1 WHERE NOT (exists(select 1 from t1 where (f=(d)*e)))}
} {-257}
do_test randexpr-2.1320 {
  db eval {SELECT  -t1.a*(select (cast(avg((select count(*)-abs(count(*)*count(*)) from t1)) AS integer)++max(t1.d))*cast(avg(t1.a) AS integer) from t1)+t1.c+t1.c+d-e & 11+t1.b-coalesce((select max(case when exists(select 1 from t1 where t1.a+11=t1.b) then c when t1.a not between t1.f and t1.d or 13<11 then  -b else 19 end) from t1 where c>=t1.f),t1.f) FROM t1 WHERE NOT (exists(select 1 from t1 where (f=(d)*e)))}
} {-3999632}
do_test randexpr-2.1321 {
  db eval {SELECT  -case when t1.a+ -c+coalesce((select d from t1 where (t1.d between a and case when t1.c*t1.b*a between a and 13 then t1.d else 11 end) or not t1.e in (select max(d) from t1 union select max(t1.e)-( -count(distinct t1.e)) from t1) or t1.c>=t1.b or a not in (c,t1.f,t1.d) and b<=t1.c),13)+d-(17) | t1.c*17<=t1.a then t1.c else d end FROM t1 WHERE case a when e then f else case when  -t1.c not between e*f | b and t1.d then case (select max((b)) from t1)+coalesce((select max(case when 19 in (b,e,17) then 13 when 11 in (t1.a,t1.a,t1.a) then t1.e else 19 end) from t1 where a<=e and 13 between t1.e and  -t1.f),13) when 17 then a else t1.d end when e in (select f from t1 union select  -t1.d from t1) then t1.a else c end*d end-13*a not in (19,t1.d,19)}
} {-400}
do_test randexpr-2.1322 {
  db eval {SELECT  -case when t1.a+ -c+coalesce((select d from t1 where (t1.d between a and case when t1.c*t1.b*a between a and 13 then t1.d else 11 end) or not t1.e in (select max(d) from t1 union select max(t1.e)-( -count(distinct t1.e)) from t1) or t1.c>=t1.b or a not in (c,t1.f,t1.d) and b<=t1.c),13)+d-(17) | t1.c*17<=t1.a then t1.c else d end FROM t1 WHERE NOT (case a when e then f else case when  -t1.c not between e*f | b and t1.d then case (select max((b)) from t1)+coalesce((select max(case when 19 in (b,e,17) then 13 when 11 in (t1.a,t1.a,t1.a) then t1.e else 19 end) from t1 where a<=e and 13 between t1.e and  -t1.f),13) when 17 then a else t1.d end when e in (select f from t1 union select  -t1.d from t1) then t1.a else c end*d end-13*a not in (19,t1.d,19))}
} {}
do_test randexpr-2.1323 {
  db eval {SELECT  -case when t1.a+ -c+coalesce((select d from t1 where (t1.d between a and case when t1.c*t1.b*a between a and 13 then t1.d else 11 end) or not t1.e in (select max(d) from t1 union select max(t1.e)-( -count(distinct t1.e)) from t1) or t1.c>=t1.b or a not in (c,t1.f,t1.d) and b<=t1.c),13)+d-(17) & t1.c*17<=t1.a then t1.c else d end FROM t1 WHERE case a when e then f else case when  -t1.c not between e*f | b and t1.d then case (select max((b)) from t1)+coalesce((select max(case when 19 in (b,e,17) then 13 when 11 in (t1.a,t1.a,t1.a) then t1.e else 19 end) from t1 where a<=e and 13 between t1.e and  -t1.f),13) when 17 then a else t1.d end when e in (select f from t1 union select  -t1.d from t1) then t1.a else c end*d end-13*a not in (19,t1.d,19)}
} {-400}
do_test randexpr-2.1324 {
  db eval {SELECT coalesce((select (abs(t1.a)/abs(13)) from t1 where a<>(select max(b)-abs(+min(f+13*17+~coalesce((select case when 11-t1.c<>19 then t1.c when (c) not between t1.e and d and 11 in (t1.f,13,((c))) then 19 else 11 end from t1 where ( -d)<e and 17>f),11)+c-t1.c)) |  - - -+max(19) from t1)-f),b) FROM t1 WHERE t1.b-t1.a+case ((t1.a)) when t1.f then (abs(e*e-(e)*c)/abs(t1.f)) else (abs(t1.a)/abs(t1.b)) end between f and (select case cast(avg(13) AS integer) when (count(*)) then (~abs( -case count(*) when abs((count(*))) then count(distinct 13) else count(*) end)-(count(distinct 11)))-count(distinct 19)*((max(t1.c)))-cast(avg(11) AS integer) else (max(19)) end from t1)}
} {}
do_test randexpr-2.1325 {
  db eval {SELECT coalesce((select (abs(t1.a)/abs(13)) from t1 where a<>(select max(b)-abs(+min(f+13*17+~coalesce((select case when 11-t1.c<>19 then t1.c when (c) not between t1.e and d and 11 in (t1.f,13,((c))) then 19 else 11 end from t1 where ( -d)<e and 17>f),11)+c-t1.c)) |  - - -+max(19) from t1)-f),b) FROM t1 WHERE NOT (t1.b-t1.a+case ((t1.a)) when t1.f then (abs(e*e-(e)*c)/abs(t1.f)) else (abs(t1.a)/abs(t1.b)) end between f and (select case cast(avg(13) AS integer) when (count(*)) then (~abs( -case count(*) when abs((count(*))) then count(distinct 13) else count(*) end)-(count(distinct 11)))-count(distinct 19)*((max(t1.c)))-cast(avg(11) AS integer) else (max(19)) end from t1))}
} {7}
do_test randexpr-2.1326 {
  db eval {SELECT coalesce((select (abs(t1.a)/abs(13)) from t1 where a<>(select max(b)-abs(+min(f+13*17+~coalesce((select case when 11-t1.c<>19 then t1.c when (c) not between t1.e and d and 11 in (t1.f,13,((c))) then 19 else 11 end from t1 where ( -d)<e and 17>f),11)+c-t1.c)) &  - - -+max(19) from t1)-f),b) FROM t1 WHERE NOT (t1.b-t1.a+case ((t1.a)) when t1.f then (abs(e*e-(e)*c)/abs(t1.f)) else (abs(t1.a)/abs(t1.b)) end between f and (select case cast(avg(13) AS integer) when (count(*)) then (~abs( -case count(*) when abs((count(*))) then count(distinct 13) else count(*) end)-(count(distinct 11)))-count(distinct 19)*((max(t1.c)))-cast(avg(11) AS integer) else (max(19)) end from t1))}
} {7}
do_test randexpr-2.1327 {
  db eval {SELECT t1.d*coalesce((select d from t1 where coalesce((select max(t1.c) from t1 where 11<>13),e)<=(select ~min(13) from t1)*t1.a),c)-coalesce((select (t1.b+17) | (abs( -~17)/abs(t1.d)) from t1 where not exists(select 1 from t1 where case t1.d when case when t1.f not in (t1.e,e,17) then f when t1.c not between 11 and  -t1.a then b else 17 end+13 then t1.f else t1.b end+13+t1.b between 17 and 13)),t1.b)+t1.a FROM t1 WHERE (not d in (t1.d,(select max(e) from t1),case d*case when not exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where t1.b<=11-d+(select  -max(13-t1.f) from t1)*t1.a),19)>t1.c) and c not between d and 19) then 11+~ -t1.a when t1.e<t1.d then f else t1.a end when 17 then t1.b else t1.c end))}
} {}
do_test randexpr-2.1328 {
  db eval {SELECT t1.d*coalesce((select d from t1 where coalesce((select max(t1.c) from t1 where 11<>13),e)<=(select ~min(13) from t1)*t1.a),c)-coalesce((select (t1.b+17) | (abs( -~17)/abs(t1.d)) from t1 where not exists(select 1 from t1 where case t1.d when case when t1.f not in (t1.e,e,17) then f when t1.c not between 11 and  -t1.a then b else 17 end+13 then t1.f else t1.b end+13+t1.b between 17 and 13)),t1.b)+t1.a FROM t1 WHERE NOT ((not d in (t1.d,(select max(e) from t1),case d*case when not exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where t1.b<=11-d+(select  -max(13-t1.f) from t1)*t1.a),19)>t1.c) and c not between d and 19) then 11+~ -t1.a when t1.e<t1.d then f else t1.a end when 17 then t1.b else t1.c end)))}
} {119883}
do_test randexpr-2.1329 {
  db eval {SELECT t1.d*coalesce((select d from t1 where coalesce((select max(t1.c) from t1 where 11<>13),e)<=(select ~min(13) from t1)*t1.a),c)-coalesce((select (t1.b+17) & (abs( -~17)/abs(t1.d)) from t1 where not exists(select 1 from t1 where case t1.d when case when t1.f not in (t1.e,e,17) then f when t1.c not between 11 and  -t1.a then b else 17 end+13 then t1.f else t1.b end+13+t1.b between 17 and 13)),t1.b)+t1.a FROM t1 WHERE NOT ((not d in (t1.d,(select max(e) from t1),case d*case when not exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where t1.b<=11-d+(select  -max(13-t1.f) from t1)*t1.a),19)>t1.c) and c not between d and 19) then 11+~ -t1.a when t1.e<t1.d then f else t1.a end when 17 then t1.b else t1.c end)))}
} {120100}
do_test randexpr-2.1330 {
  db eval {SELECT d+~e-case when exists(select 1 from t1 where  -a in (select max( -(select  -count(*)-min(e)++cast(avg(case when d in (select +max(c) from t1 union select ((count(distinct (e)))) from t1) then (c) when t1.c<e then 13 else t1.f end) AS integer) from t1)++case 19 when a*t1.e then (t1.c) else 13 end+t1.b) from t1 union select max(11) from t1)) then (abs(19)/abs(t1.b)) when f>=f then t1.b else t1.a end*a+19-13 FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where (select min(case when 13 not in (19,e-t1.a*17,17- -case 19 when 17+17 then a else t1.d end+f-t1.a*11) then 17 else t1.b end*17+11-b) from t1) between 11 and f or t1.e<>t1.d)) or c not in (t1.c,17,d)}
} {}
do_test randexpr-2.1331 {
  db eval {SELECT d+~e-case when exists(select 1 from t1 where  -a in (select max( -(select  -count(*)-min(e)++cast(avg(case when d in (select +max(c) from t1 union select ((count(distinct (e)))) from t1) then (c) when t1.c<e then 13 else t1.f end) AS integer) from t1)++case 19 when a*t1.e then (t1.c) else 13 end+t1.b) from t1 union select max(11) from t1)) then (abs(19)/abs(t1.b)) when f>=f then t1.b else t1.a end*a+19-13 FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (select min(case when 13 not in (19,e-t1.a*17,17- -case 19 when 17+17 then a else t1.d end+f-t1.a*11) then 17 else t1.b end*17+11-b) from t1) between 11 and f or t1.e<>t1.d)) or c not in (t1.c,17,d))}
} {-20095}
do_test randexpr-2.1332 {
  db eval {SELECT case coalesce((select 11*19*t1.a+(abs(t1.e*(select count(distinct  -d) from t1)*case t1.f when +c then d else c end+b)/abs(d)) from t1 where t1.b*13=(e)),13) when (t1.d)*b-19*(e)*e-19+(t1.d) then 13 else b end*a FROM t1 WHERE not d=19 and (abs(t1.c)/abs(17))-a<coalesce((select max(d-+d+case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.b<>b))) then case when 13 not between t1.e and t1.a then c when t1.c>t1.c then 13 else a end | 19 else (19) end*f*13) from t1 where 17=t1.d and (b<>11)),t1.b)+t1.a | d}
} {20000}
do_test randexpr-2.1333 {
  db eval {SELECT case coalesce((select 11*19*t1.a+(abs(t1.e*(select count(distinct  -d) from t1)*case t1.f when +c then d else c end+b)/abs(d)) from t1 where t1.b*13=(e)),13) when (t1.d)*b-19*(e)*e-19+(t1.d) then 13 else b end*a FROM t1 WHERE NOT (not d=19 and (abs(t1.c)/abs(17))-a<coalesce((select max(d-+d+case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.b<>b))) then case when 13 not between t1.e and t1.a then c when t1.c>t1.c then 13 else a end | 19 else (19) end*f*13) from t1 where 17=t1.d and (b<>11)),t1.b)+t1.a | d)}
} {}
do_test randexpr-2.1334 {
  db eval {SELECT (c*(abs(coalesce((select t1.b from t1 where (select ~~count(*)+ -count(distinct coalesce((select max(case coalesce((select max(a+(t1.e)) from t1 where  -(a)>=t1.e or t1.e<17),c) when t1.d then t1.a else 17 end) from t1 where t1.b not in (e,(c),t1.a)),f)) from t1) between t1.a and b),case when exists(select 1 from t1 where t1.c>=t1.a) then 19 else t1.e end+t1.c))/abs(b))-11 | 19) FROM t1 WHERE not t1.e<=d or not exists(select 1 from t1 where exists(select 1 from t1 where ( -t1.c+d)>t1.a+case when f |  -b not between 17 and e then  -t1.d else (19) end) or 11 not between 17 and t1.f) or a in (select  -cast(avg(13) AS integer)*count(distinct 17)-min(b)- -max(11) | (count(*)) from t1 union select ((((max(b))))) from t1) and t1.e in (13,(13),b)}
} {307}
do_test randexpr-2.1335 {
  db eval {SELECT (c*(abs(coalesce((select t1.b from t1 where (select ~~count(*)+ -count(distinct coalesce((select max(case coalesce((select max(a+(t1.e)) from t1 where  -(a)>=t1.e or t1.e<17),c) when t1.d then t1.a else 17 end) from t1 where t1.b not in (e,(c),t1.a)),f)) from t1) between t1.a and b),case when exists(select 1 from t1 where t1.c>=t1.a) then 19 else t1.e end+t1.c))/abs(b))-11 | 19) FROM t1 WHERE NOT (not t1.e<=d or not exists(select 1 from t1 where exists(select 1 from t1 where ( -t1.c+d)>t1.a+case when f |  -b not between 17 and e then  -t1.d else (19) end) or 11 not between 17 and t1.f) or a in (select  -cast(avg(13) AS integer)*count(distinct 17)-min(b)- -max(11) | (count(*)) from t1 union select ((((max(b))))) from t1) and t1.e in (13,(13),b))}
} {}
do_test randexpr-2.1336 {
  db eval {SELECT (c*(abs(coalesce((select t1.b from t1 where (select ~~count(*)+ -count(distinct coalesce((select max(case coalesce((select max(a+(t1.e)) from t1 where  -(a)>=t1.e or t1.e<17),c) when t1.d then t1.a else 17 end) from t1 where t1.b not in (e,(c),t1.a)),f)) from t1) between t1.a and b),case when exists(select 1 from t1 where t1.c>=t1.a) then 19 else t1.e end+t1.c))/abs(b))-11 & 19) FROM t1 WHERE not t1.e<=d or not exists(select 1 from t1 where exists(select 1 from t1 where ( -t1.c+d)>t1.a+case when f |  -b not between 17 and e then  -t1.d else (19) end) or 11 not between 17 and t1.f) or a in (select  -cast(avg(13) AS integer)*count(distinct 17)-min(b)- -max(11) | (count(*)) from t1 union select ((((max(b))))) from t1) and t1.e in (13,(13),b)}
} {1}
do_test randexpr-2.1337 {
  db eval {SELECT (select cast(avg(13*13* -coalesce((select b from t1 where case +(abs(17)/abs(d))*e+c-case  -case when not a in (d,13,t1.b) then t1.b when t1.f<=b then e else  -f end-17 when t1.e then t1.d else a end when c then b else f end<>e or e<b),f)+t1.a-d*a+t1.c) AS integer) from t1) FROM t1 WHERE 19 in (select  -~count(distinct case when not not not exists(select 1 from t1 where (d in ((abs(19*t1.f-t1.e*e)/abs(11))*13,t1.f,t1.f))) then 13 else t1.a+17-13 end)-min(t1.f) from t1 union select ( -abs(count(distinct d)))-min(t1.b)*+(+count(*) | (min(19)))+min(c) from t1)}
} {}
do_test randexpr-2.1338 {
  db eval {SELECT (select cast(avg(13*13* -coalesce((select b from t1 where case +(abs(17)/abs(d))*e+c-case  -case when not a in (d,13,t1.b) then t1.b when t1.f<=b then e else  -f end-17 when t1.e then t1.d else a end when c then b else f end<>e or e<b),f)+t1.a-d*a+t1.c) AS integer) from t1) FROM t1 WHERE NOT (19 in (select  -~count(distinct case when not not not exists(select 1 from t1 where (d in ((abs(19*t1.f-t1.e*e)/abs(11))*13,t1.f,t1.f))) then 13 else t1.a+17-13 end)-min(t1.f) from t1 union select ( -abs(count(distinct d)))-min(t1.b)*+(+count(*) | (min(19)))+min(c) from t1))}
} {-73400}
do_test randexpr-2.1339 {
  db eval {SELECT b | t1.d- -coalesce((select case coalesce((select max((select (abs(cast(avg(coalesce((select max(coalesce((select 17 from t1 where  -11=t1.e),a)) from t1 where not exists(select 1 from t1 where 13 between t1.f and 13)),11)-c) AS integer)))+min( -b) from t1)+b) from t1 where t1.d not in (b*19,t1.a,a)),t1.e) when t1.e then t1.b else t1.d end from t1 where (e not in (b,t1.a,(a)))),13) FROM t1 WHERE t1.c=coalesce((select t1.d*(select count(*) from t1) from t1 where ((abs(e)/abs(case 13 when t1.d then t1.e else 11 end+13))>t1.d) or (t1.f in (select 11 from t1 union select t1.c from t1) or c>t1.e and b not in (t1.b, -t1.e,t1.a)) or c<>b),(a))-19*t1.c-c*t1.d and exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (t1.b,e,19) or not exists(select 1 from t1 where t1.c=19)))}
} {}
do_test randexpr-2.1340 {
  db eval {SELECT b | t1.d- -coalesce((select case coalesce((select max((select (abs(cast(avg(coalesce((select max(coalesce((select 17 from t1 where  -11=t1.e),a)) from t1 where not exists(select 1 from t1 where 13 between t1.f and 13)),11)-c) AS integer)))+min( -b) from t1)+b) from t1 where t1.d not in (b*19,t1.a,a)),t1.e) when t1.e then t1.b else t1.d end from t1 where (e not in (b,t1.a,(a)))),13) FROM t1 WHERE NOT (t1.c=coalesce((select t1.d*(select count(*) from t1) from t1 where ((abs(e)/abs(case 13 when t1.d then t1.e else 11 end+13))>t1.d) or (t1.f in (select 11 from t1 union select t1.c from t1) or c>t1.e and b not in (t1.b, -t1.e,t1.a)) or c<>b),(a))-19*t1.c-c*t1.d and exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (t1.b,e,19) or not exists(select 1 from t1 where t1.c=19))))}
} {1000}
do_test randexpr-2.1341 {
  db eval {SELECT b & t1.d- -coalesce((select case coalesce((select max((select (abs(cast(avg(coalesce((select max(coalesce((select 17 from t1 where  -11=t1.e),a)) from t1 where not exists(select 1 from t1 where 13 between t1.f and 13)),11)-c) AS integer)))+min( -b) from t1)+b) from t1 where t1.d not in (b*19,t1.a,a)),t1.e) when t1.e then t1.b else t1.d end from t1 where (e not in (b,t1.a,(a)))),13) FROM t1 WHERE NOT (t1.c=coalesce((select t1.d*(select count(*) from t1) from t1 where ((abs(e)/abs(case 13 when t1.d then t1.e else 11 end+13))>t1.d) or (t1.f in (select 11 from t1 union select t1.c from t1) or c>t1.e and b not in (t1.b, -t1.e,t1.a)) or c<>b),(a))-19*t1.c-c*t1.d and exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (t1.b,e,19) or not exists(select 1 from t1 where t1.c=19))))}
} {0}
do_test randexpr-2.1342 {
  db eval {SELECT coalesce((select 19 from t1 where not exists(select 1 from t1 where 11+d between b and 19-case when t1.e>e*f+case when 13 in (select count(*) from t1 union select ~min(a*t1.d)+count(*) from t1) then c when (select min(d) from t1) in (select cast(avg(17) AS integer) from t1 union select min(t1.a) from t1) and 11<>(f) then  -f else 19 end | c then 13 else 19 end*b*t1.b)),a) FROM t1 WHERE (coalesce((select d from t1 where coalesce((select ~(coalesce((select max(t1.a) from t1 where 13+t1.c-c*coalesce((select t1.a from t1 where ( -t1.d not between a and d)),t1.e)+t1.e- - -11-t1.d*11<17),d)) from t1 where f between t1.a and t1.a),t1.c)<>e),t1.d)*(19)-t1.e- -17-a>=d or t1.c between f and a)}
} {19}
do_test randexpr-2.1343 {
  db eval {SELECT coalesce((select 19 from t1 where not exists(select 1 from t1 where 11+d between b and 19-case when t1.e>e*f+case when 13 in (select count(*) from t1 union select ~min(a*t1.d)+count(*) from t1) then c when (select min(d) from t1) in (select cast(avg(17) AS integer) from t1 union select min(t1.a) from t1) and 11<>(f) then  -f else 19 end | c then 13 else 19 end*b*t1.b)),a) FROM t1 WHERE NOT ((coalesce((select d from t1 where coalesce((select ~(coalesce((select max(t1.a) from t1 where 13+t1.c-c*coalesce((select t1.a from t1 where ( -t1.d not between a and d)),t1.e)+t1.e- - -11-t1.d*11<17),d)) from t1 where f between t1.a and t1.a),t1.c)<>e),t1.d)*(19)-t1.e- -17-a>=d or t1.c between f and a))}
} {}
do_test randexpr-2.1344 {
  db eval {SELECT coalesce((select 19 from t1 where not exists(select 1 from t1 where 11+d between b and 19-case when t1.e>e*f+case when 13 in (select count(*) from t1 union select ~min(a*t1.d)+count(*) from t1) then c when (select min(d) from t1) in (select cast(avg(17) AS integer) from t1 union select min(t1.a) from t1) and 11<>(f) then  -f else 19 end & c then 13 else 19 end*b*t1.b)),a) FROM t1 WHERE (coalesce((select d from t1 where coalesce((select ~(coalesce((select max(t1.a) from t1 where 13+t1.c-c*coalesce((select t1.a from t1 where ( -t1.d not between a and d)),t1.e)+t1.e- - -11-t1.d*11<17),d)) from t1 where f between t1.a and t1.a),t1.c)<>e),t1.d)*(19)-t1.e- -17-a>=d or t1.c between f and a)}
} {19}
do_test randexpr-2.1345 {
  db eval {SELECT coalesce((select +case case when f>t1.d then a+t1.b-f when coalesce((select max(t1.b-case f when 13*t1.a then 11 else 11 end*c) from t1 where f in (select min(t1.d) from t1 union select +count(distinct f) from t1)),17) not in (e,b,t1.a) then f else t1.b end-e*t1.a when  -11 then 19 else (t1.d) end from t1 where 17 not between  -13 and t1.e),19) FROM t1 WHERE not t1.b*coalesce((select max(17 | coalesce((select coalesce((select +coalesce((select max(case when (b not in (a,t1.b, -t1.a)) and t1.f=t1.b then t1.c-t1.f when 11>d then 17 else 11 end+f) from t1 where t1.e<>b), -t1.e) from t1 where t1.f in (select min(b) from t1 union select max(19)+count(distinct e)+(count(distinct e)) |  - -count(distinct 17)*count(*) from t1)),13) from t1 where t1.f>=t1.f),t1.f)) from t1 where t1.f>=b),c)<t1.d}
} {19}
do_test randexpr-2.1346 {
  db eval {SELECT coalesce((select +case case when f>t1.d then a+t1.b-f when coalesce((select max(t1.b-case f when 13*t1.a then 11 else 11 end*c) from t1 where f in (select min(t1.d) from t1 union select +count(distinct f) from t1)),17) not in (e,b,t1.a) then f else t1.b end-e*t1.a when  -11 then 19 else (t1.d) end from t1 where 17 not between  -13 and t1.e),19) FROM t1 WHERE NOT (not t1.b*coalesce((select max(17 | coalesce((select coalesce((select +coalesce((select max(case when (b not in (a,t1.b, -t1.a)) and t1.f=t1.b then t1.c-t1.f when 11>d then 17 else 11 end+f) from t1 where t1.e<>b), -t1.e) from t1 where t1.f in (select min(b) from t1 union select max(19)+count(distinct e)+(count(distinct e)) |  - -count(distinct 17)*count(*) from t1)),13) from t1 where t1.f>=t1.f),t1.f)) from t1 where t1.f>=b),c)<t1.d)}
} {}
do_test randexpr-2.1347 {
  db eval {SELECT  -11* -t1.b-t1.b+ -case when t1.e-(select max((select abs((cast(avg(t1.f) AS integer)+++ -cast(avg(a | a) AS integer))) from t1))+(( -max( -b))) from t1)<=(abs(11)/abs((select count(distinct t1.e) from t1)-b*case when t1.a<>11 then t1.a when 17 not between d and 13 or t1.f in (b,b,t1.a) then t1.d else c end)) then  -t1.e else b end*t1.a FROM t1 WHERE a in ((abs(t1.c*+(abs(17-(abs(19)/abs(b-coalesce((select max(t1.c) from t1 where c>t1.f),t1.e))))/abs(t1.e))+t1.b | t1.d*t1.a)/abs(coalesce((select case when t1.f in (case when  -e<=t1.a then f else 17 end,f,b) then b else t1.c end from t1 where not a in (t1.d,t1.a,c)),t1.f))),b,t1.b) and e in (select f from t1 union select e from t1)}
} {}
do_test randexpr-2.1348 {
  db eval {SELECT  -11* -t1.b-t1.b+ -case when t1.e-(select max((select abs((cast(avg(t1.f) AS integer)+++ -cast(avg(a | a) AS integer))) from t1))+(( -max( -b))) from t1)<=(abs(11)/abs((select count(distinct t1.e) from t1)-b*case when t1.a<>11 then t1.a when 17 not between d and 13 or t1.f in (b,b,t1.a) then t1.d else c end)) then  -t1.e else b end*t1.a FROM t1 WHERE NOT (a in ((abs(t1.c*+(abs(17-(abs(19)/abs(b-coalesce((select max(t1.c) from t1 where c>t1.f),t1.e))))/abs(t1.e))+t1.b | t1.d*t1.a)/abs(coalesce((select case when t1.f in (case when  -e<=t1.a then f else 17 end,f,b) then b else t1.c end from t1 where not a in (t1.d,t1.a,c)),t1.f))),b,t1.b) and e in (select f from t1 union select e from t1))}
} {52000}
do_test randexpr-2.1349 {
  db eval {SELECT  -11* -t1.b-t1.b+ -case when t1.e-(select max((select abs((cast(avg(t1.f) AS integer)+++ -cast(avg(a & a) AS integer))) from t1))+(( -max( -b))) from t1)<=(abs(11)/abs((select count(distinct t1.e) from t1)-b*case when t1.a<>11 then t1.a when 17 not between d and 13 or t1.f in (b,b,t1.a) then t1.d else c end)) then  -t1.e else b end*t1.a FROM t1 WHERE NOT (a in ((abs(t1.c*+(abs(17-(abs(19)/abs(b-coalesce((select max(t1.c) from t1 where c>t1.f),t1.e))))/abs(t1.e))+t1.b | t1.d*t1.a)/abs(coalesce((select case when t1.f in (case when  -e<=t1.a then f else 17 end,f,b) then b else t1.c end from t1 where not a in (t1.d,t1.a,c)),t1.f))),b,t1.b) and e in (select f from t1 union select e from t1))}
} {52000}
do_test randexpr-2.1350 {
  db eval {SELECT case when ((select count(*) | min(case when (a*e in (select  -+ -min(a) | cast(avg(11) AS integer) from t1 union select count(distinct t1.e) from t1) and exists(select 1 from t1 where not 13 in (select count(distinct 11) from t1 union select (max(19)) from t1) or (t1.f) between t1.e and (t1.e)) or t1.a<=f) or t1.e<t1.a then t1.a when t1.e not between t1.c and t1.b then t1.c | a*t1.c else  -b end) from t1))+19-17<=c then f when 19>t1.c then t1.e else t1.b end FROM t1 WHERE (c not between +(select + -~~max(coalesce((select case when t1.b<=t1.d*a then t1.c else t1.e end*t1.e from t1 where t1.d>=t1.b and c=(f) or t1.e>t1.d and b<e),t1.b))-count(*) | max(d)+cast(avg(19) AS integer) | count(distinct 17) from t1)*t1.a and ((coalesce((select max(t1.b) from t1 where t1.f in (select 17 from t1 union select a from t1)),e))*c))}
} {}
do_test randexpr-2.1351 {
  db eval {SELECT case when ((select count(*) | min(case when (a*e in (select  -+ -min(a) | cast(avg(11) AS integer) from t1 union select count(distinct t1.e) from t1) and exists(select 1 from t1 where not 13 in (select count(distinct 11) from t1 union select (max(19)) from t1) or (t1.f) between t1.e and (t1.e)) or t1.a<=f) or t1.e<t1.a then t1.a when t1.e not between t1.c and t1.b then t1.c | a*t1.c else  -b end) from t1))+19-17<=c then f when 19>t1.c then t1.e else t1.b end FROM t1 WHERE NOT ((c not between +(select + -~~max(coalesce((select case when t1.b<=t1.d*a then t1.c else t1.e end*t1.e from t1 where t1.d>=t1.b and c=(f) or t1.e>t1.d and b<e),t1.b))-count(*) | max(d)+cast(avg(19) AS integer) | count(distinct 17) from t1)*t1.a and ((coalesce((select max(t1.b) from t1 where t1.f in (select 17 from t1 union select a from t1)),e))*c)))}
} {600}
do_test randexpr-2.1352 {
  db eval {SELECT case when ((select count(*) & min(case when (a*e in (select  -+ -min(a) & cast(avg(11) AS integer) from t1 union select count(distinct t1.e) from t1) and exists(select 1 from t1 where not 13 in (select count(distinct 11) from t1 union select (max(19)) from t1) or (t1.f) between t1.e and (t1.e)) or t1.a<=f) or t1.e<t1.a then t1.a when t1.e not between t1.c and t1.b then t1.c & a*t1.c else  -b end) from t1))+19-17<=c then f when 19>t1.c then t1.e else t1.b end FROM t1 WHERE NOT ((c not between +(select + -~~max(coalesce((select case when t1.b<=t1.d*a then t1.c else t1.e end*t1.e from t1 where t1.d>=t1.b and c=(f) or t1.e>t1.d and b<e),t1.b))-count(*) | max(d)+cast(avg(19) AS integer) | count(distinct 17) from t1)*t1.a and ((coalesce((select max(t1.b) from t1 where t1.f in (select 17 from t1 union select a from t1)),e))*c)))}
} {600}
do_test randexpr-2.1353 {
  db eval {SELECT coalesce((select max(coalesce((select max((abs((11))/abs(13))-e) from t1 where 11 not in (c,f,(select count(distinct  -17+t1.a) from t1)) or (d*coalesce((select b | coalesce((select max(17) from t1 where e in (d,t1.c,t1.c)),+b) from t1 where d in (d-13,t1.c,f)),13))<>t1.c),t1.d)) from t1 where b not in (t1.e, -13,f)),f) FROM t1 WHERE d*a | 19<> -t1.d}
} {-500}
do_test randexpr-2.1354 {
  db eval {SELECT coalesce((select max(coalesce((select max((abs((11))/abs(13))-e) from t1 where 11 not in (c,f,(select count(distinct  -17+t1.a) from t1)) or (d*coalesce((select b | coalesce((select max(17) from t1 where e in (d,t1.c,t1.c)),+b) from t1 where d in (d-13,t1.c,f)),13))<>t1.c),t1.d)) from t1 where b not in (t1.e, -13,f)),f) FROM t1 WHERE NOT (d*a | 19<> -t1.d)}
} {}
do_test randexpr-2.1355 {
  db eval {SELECT coalesce((select max(coalesce((select max((abs((11))/abs(13))-e) from t1 where 11 not in (c,f,(select count(distinct  -17+t1.a) from t1)) or (d*coalesce((select b & coalesce((select max(17) from t1 where e in (d,t1.c,t1.c)),+b) from t1 where d in (d-13,t1.c,f)),13))<>t1.c),t1.d)) from t1 where b not in (t1.e, -13,f)),f) FROM t1 WHERE d*a | 19<> -t1.d}
} {-500}
do_test randexpr-2.1356 {
  db eval {SELECT coalesce((select t1.f from t1 where case when 19<>(c*case when 19 |  -t1.e in (select ~+(max(c)) from t1 union select min(19) from t1) then  -t1.f else 13 end-f) then ( -17) else  -19 end-b in (t1.b,t1.f,b) or c in (select ~case max( -t1.d) | count(*)*cast(avg(b) AS integer) when count(distinct t1.f) then cast(avg(t1.f) AS integer) else cast(avg(f) AS integer) end | (cast(avg( -t1.e) AS integer)) from t1 union select max(c) from t1) and t1.f in (select max(17) from t1 union select max(11) from t1)),e) FROM t1 WHERE not 13 in (select (t1.b)*(coalesce((select (abs(t1.f)/abs( -t1.f-d))-coalesce((select 19 from t1 where not exists(select 1 from t1 where (select count(distinct t1.f+19-(abs(e)/abs(e))) from t1)- -e<>d)),t1.e)* -t1.a-t1.a-(t1.f)*t1.e*t1.d-t1.b from t1 where t1.e between t1.a and b),11)) from t1 union select d from t1)}
} {500}
do_test randexpr-2.1357 {
  db eval {SELECT coalesce((select t1.f from t1 where case when 19<>(c*case when 19 |  -t1.e in (select ~+(max(c)) from t1 union select min(19) from t1) then  -t1.f else 13 end-f) then ( -17) else  -19 end-b in (t1.b,t1.f,b) or c in (select ~case max( -t1.d) | count(*)*cast(avg(b) AS integer) when count(distinct t1.f) then cast(avg(t1.f) AS integer) else cast(avg(f) AS integer) end | (cast(avg( -t1.e) AS integer)) from t1 union select max(c) from t1) and t1.f in (select max(17) from t1 union select max(11) from t1)),e) FROM t1 WHERE NOT (not 13 in (select (t1.b)*(coalesce((select (abs(t1.f)/abs( -t1.f-d))-coalesce((select 19 from t1 where not exists(select 1 from t1 where (select count(distinct t1.f+19-(abs(e)/abs(e))) from t1)- -e<>d)),t1.e)* -t1.a-t1.a-(t1.f)*t1.e*t1.d-t1.b from t1 where t1.e between t1.a and b),11)) from t1 union select d from t1))}
} {}
do_test randexpr-2.1358 {
  db eval {SELECT coalesce((select t1.f from t1 where case when 19<>(c*case when 19 &  -t1.e in (select ~+(max(c)) from t1 union select min(19) from t1) then  -t1.f else 13 end-f) then ( -17) else  -19 end-b in (t1.b,t1.f,b) or c in (select ~case max( -t1.d) & count(*)*cast(avg(b) AS integer) when count(distinct t1.f) then cast(avg(t1.f) AS integer) else cast(avg(f) AS integer) end & (cast(avg( -t1.e) AS integer)) from t1 union select max(c) from t1) and t1.f in (select max(17) from t1 union select max(11) from t1)),e) FROM t1 WHERE not 13 in (select (t1.b)*(coalesce((select (abs(t1.f)/abs( -t1.f-d))-coalesce((select 19 from t1 where not exists(select 1 from t1 where (select count(distinct t1.f+19-(abs(e)/abs(e))) from t1)- -e<>d)),t1.e)* -t1.a-t1.a-(t1.f)*t1.e*t1.d-t1.b from t1 where t1.e between t1.a and b),11)) from t1 union select d from t1)}
} {500}
do_test randexpr-2.1359 {
  db eval {SELECT ~ -case when t1.d in (17,t1.e,case t1.b*c when  -c+f-11 | coalesce((select 11 from t1 where (select (min(13)-max(t1.c))+count(*) from t1)+13<=(( -(t1.f)))),b)+17 then t1.d else b end) then c when c between 13 and f and b>17 then f else t1.a end-t1.f FROM t1 WHERE t1.e>= -f}
} {-1}
do_test randexpr-2.1360 {
  db eval {SELECT ~ -case when t1.d in (17,t1.e,case t1.b*c when  -c+f-11 | coalesce((select 11 from t1 where (select (min(13)-max(t1.c))+count(*) from t1)+13<=(( -(t1.f)))),b)+17 then t1.d else b end) then c when c between 13 and f and b>17 then f else t1.a end-t1.f FROM t1 WHERE NOT (t1.e>= -f)}
} {}
do_test randexpr-2.1361 {
  db eval {SELECT ~ -case when t1.d in (17,t1.e,case t1.b*c when  -c+f-11 & coalesce((select 11 from t1 where (select (min(13)-max(t1.c))+count(*) from t1)+13<=(( -(t1.f)))),b)+17 then t1.d else b end) then c when c between 13 and f and b>17 then f else t1.a end-t1.f FROM t1 WHERE t1.e>= -f}
} {-1}
do_test randexpr-2.1362 {
  db eval {SELECT ((abs(13)/abs( -b | coalesce((select 17 | t1.e from t1 where (d in (select coalesce((select 17 | (a) | c*case when case when t1.c in (select max(13) | cast(avg(t1.b) AS integer) from t1 union select count(*) from t1) then t1.c when 13>=17 then (11) else t1.e end>t1.d and t1.b>=t1.f then 13 when 11 not in (t1.d, -f,13) then f else 11 end from t1 where b<>11),d) from t1 union select t1.e from t1) or b not in (t1.e,b,e))),t1.e)))) FROM t1 WHERE 11<=coalesce((select max(t1.d) from t1 where coalesce((select ~d+t1.d-case when c not in (t1.b-f,19+~coalesce((select t1.a from t1 where t1.f<=b),case when not (e not between f and t1.e) then (t1.e)-d else b end), -t1.d) then 17 when t1.d not between 13 and t1.d then d else (c) end from t1 where c>t1.a),t1.b)<d),t1.c)}
} {3}
do_test randexpr-2.1363 {
  db eval {SELECT ((abs(13)/abs( -b | coalesce((select 17 | t1.e from t1 where (d in (select coalesce((select 17 | (a) | c*case when case when t1.c in (select max(13) | cast(avg(t1.b) AS integer) from t1 union select count(*) from t1) then t1.c when 13>=17 then (11) else t1.e end>t1.d and t1.b>=t1.f then 13 when 11 not in (t1.d, -f,13) then f else 11 end from t1 where b<>11),d) from t1 union select t1.e from t1) or b not in (t1.e,b,e))),t1.e)))) FROM t1 WHERE NOT (11<=coalesce((select max(t1.d) from t1 where coalesce((select ~d+t1.d-case when c not in (t1.b-f,19+~coalesce((select t1.a from t1 where t1.f<=b),case when not (e not between f and t1.e) then (t1.e)-d else b end), -t1.d) then 17 when t1.d not between 13 and t1.d then d else (c) end from t1 where c>t1.a),t1.b)<d),t1.c))}
} {}
do_test randexpr-2.1364 {
  db eval {SELECT ((abs(13)/abs( -b & coalesce((select 17 & t1.e from t1 where (d in (select coalesce((select 17 & (a) & c*case when case when t1.c in (select max(13) & cast(avg(t1.b) AS integer) from t1 union select count(*) from t1) then t1.c when 13>=17 then (11) else t1.e end>t1.d and t1.b>=t1.f then 13 when 11 not in (t1.d, -f,13) then f else 11 end from t1 where b<>11),d) from t1 union select t1.e from t1) or b not in (t1.e,b,e))),t1.e)))) FROM t1 WHERE 11<=coalesce((select max(t1.d) from t1 where coalesce((select ~d+t1.d-case when c not in (t1.b-f,19+~coalesce((select t1.a from t1 where t1.f<=b),case when not (e not between f and t1.e) then (t1.e)-d else b end), -t1.d) then 17 when t1.d not between 13 and t1.d then d else (c) end from t1 where c>t1.a),t1.b)<d),t1.c)}
} {0}
do_test randexpr-2.1365 {
  db eval {SELECT case when (c between 11 and t1.e*t1.a | c) then case when (case when (b=(select max((t1.c))-min(t1.d) from t1)*b) then t1.c else 17 end-e>t1.d and a between d and d) then c else d end when exists(select 1 from t1 where (11)>19) or a in (t1.b,(t1.c),(a)) and  - -11<>13 and t1.b not between  -b and d then 19 else a end FROM t1 WHERE 19 | t1.d not between (select ~case case count(distinct t1.c) when (count(*)) then ~~~count(*) else  -count(*)- -max(coalesce((select max(19) from t1 where (abs(t1.b-b)/abs(d))+11<a and 17>=t1.a),11))*max(t1.e) | count(*)-abs(max((c)))*max(t1.d) end when  -count(*) then cast(avg(f) AS integer) else  -(max(c)) end from t1) and t1.c}
} {400}
do_test randexpr-2.1366 {
  db eval {SELECT case when (c between 11 and t1.e*t1.a | c) then case when (case when (b=(select max((t1.c))-min(t1.d) from t1)*b) then t1.c else 17 end-e>t1.d and a between d and d) then c else d end when exists(select 1 from t1 where (11)>19) or a in (t1.b,(t1.c),(a)) and  - -11<>13 and t1.b not between  -b and d then 19 else a end FROM t1 WHERE NOT (19 | t1.d not between (select ~case case count(distinct t1.c) when (count(*)) then ~~~count(*) else  -count(*)- -max(coalesce((select max(19) from t1 where (abs(t1.b-b)/abs(d))+11<a and 17>=t1.a),11))*max(t1.e) | count(*)-abs(max((c)))*max(t1.d) end when  -count(*) then cast(avg(f) AS integer) else  -(max(c)) end from t1) and t1.c)}
} {}
do_test randexpr-2.1367 {
  db eval {SELECT case when (c between 11 and t1.e*t1.a & c) then case when (case when (b=(select max((t1.c))-min(t1.d) from t1)*b) then t1.c else 17 end-e>t1.d and a between d and d) then c else d end when exists(select 1 from t1 where (11)>19) or a in (t1.b,(t1.c),(a)) and  - -11<>13 and t1.b not between  -b and d then 19 else a end FROM t1 WHERE 19 | t1.d not between (select ~case case count(distinct t1.c) when (count(*)) then ~~~count(*) else  -count(*)- -max(coalesce((select max(19) from t1 where (abs(t1.b-b)/abs(d))+11<a and 17>=t1.a),11))*max(t1.e) | count(*)-abs(max((c)))*max(t1.d) end when  -count(*) then cast(avg(f) AS integer) else  -(max(c)) end from t1) and t1.c}
} {100}
do_test randexpr-2.1368 {
  db eval {SELECT case when not exists(select 1 from t1 where t1.c not in (t1.d,17,t1.c | coalesce((select t1.f from t1 where t1.c*t1.c-t1.e not in (t1.e*(case when (f) not between c and +f then (a) else t1.e end)+17,13, -((t1.a))) and f not between f and t1.d), -t1.e))) then (abs(e)/abs(a)) when 17<17 or 13<>a then f else (f) end FROM t1 WHERE t1.f in (e,(19),case when not exists(select 1 from t1 where coalesce((select max( -(abs(case  -t1.d when t1.d*13+coalesce((select a from t1 where d>19),t1.c) then f else b end)/abs(t1.b))) from t1 where f in (t1.a,t1.d,(c))),t1.d)+c+17<t1.b) then t1.c*t1.b else d end) and (((17 not in (17,t1.c,19))))}
} {}
do_test randexpr-2.1369 {
  db eval {SELECT case when not exists(select 1 from t1 where t1.c not in (t1.d,17,t1.c | coalesce((select t1.f from t1 where t1.c*t1.c-t1.e not in (t1.e*(case when (f) not between c and +f then (a) else t1.e end)+17,13, -((t1.a))) and f not between f and t1.d), -t1.e))) then (abs(e)/abs(a)) when 17<17 or 13<>a then f else (f) end FROM t1 WHERE NOT (t1.f in (e,(19),case when not exists(select 1 from t1 where coalesce((select max( -(abs(case  -t1.d when t1.d*13+coalesce((select a from t1 where d>19),t1.c) then f else b end)/abs(t1.b))) from t1 where f in (t1.a,t1.d,(c))),t1.d)+c+17<t1.b) then t1.c*t1.b else d end) and (((17 not in (17,t1.c,19)))))}
} {600}
do_test randexpr-2.1370 {
  db eval {SELECT case when not exists(select 1 from t1 where t1.c not in (t1.d,17,t1.c & coalesce((select t1.f from t1 where t1.c*t1.c-t1.e not in (t1.e*(case when (f) not between c and +f then (a) else t1.e end)+17,13, -((t1.a))) and f not between f and t1.d), -t1.e))) then (abs(e)/abs(a)) when 17<17 or 13<>a then f else (f) end FROM t1 WHERE NOT (t1.f in (e,(19),case when not exists(select 1 from t1 where coalesce((select max( -(abs(case  -t1.d when t1.d*13+coalesce((select a from t1 where d>19),t1.c) then f else b end)/abs(t1.b))) from t1 where f in (t1.a,t1.d,(c))),t1.d)+c+17<t1.b) then t1.c*t1.b else d end) and (((17 not in (17,t1.c,19)))))}
} {600}
do_test randexpr-2.1371 {
  db eval {SELECT case +b when coalesce((select max(b) from t1 where exists(select 1 from t1 where (((+~13) in (select case cast(avg(t1.e+(11)+t1.b*e) AS integer) when max(((t1.e))) then min(b)-case  -cast(avg(17) AS integer) when min(e) then cast(avg(t1.c) AS integer) else (max(d)) end-count(distinct t1.f) else count(distinct d) end+count(*) from t1 union select max(d) from t1))))),(abs(~d)/abs(11))) then  -e else  - -13 end+d | t1.d FROM t1 WHERE ((a)>coalesce((select max(coalesce((select max(case when case case when 19 in (select case min(11) when  - -cast(avg(c) AS integer) then count(*) else count(*) end-cast(avg(19) AS integer) | cast(avg(17) AS integer) from t1 union select min(t1.d) from t1) then t1.b*t1.a else  -t1.a end when t1.f then e else t1.d end<a then t1.a when b between  -a and t1.d then  -a else t1.f end) from t1 where b<>d),t1.d)) from t1 where t1.c<>e and  -17<=a),t1.d))}
} {413}
do_test randexpr-2.1372 {
  db eval {SELECT case +b when coalesce((select max(b) from t1 where exists(select 1 from t1 where (((+~13) in (select case cast(avg(t1.e+(11)+t1.b*e) AS integer) when max(((t1.e))) then min(b)-case  -cast(avg(17) AS integer) when min(e) then cast(avg(t1.c) AS integer) else (max(d)) end-count(distinct t1.f) else count(distinct d) end+count(*) from t1 union select max(d) from t1))))),(abs(~d)/abs(11))) then  -e else  - -13 end+d | t1.d FROM t1 WHERE NOT (((a)>coalesce((select max(coalesce((select max(case when case case when 19 in (select case min(11) when  - -cast(avg(c) AS integer) then count(*) else count(*) end-cast(avg(19) AS integer) | cast(avg(17) AS integer) from t1 union select min(t1.d) from t1) then t1.b*t1.a else  -t1.a end when t1.f then e else t1.d end<a then t1.a when b between  -a and t1.d then  -a else t1.f end) from t1 where b<>d),t1.d)) from t1 where t1.c<>e and  -17<=a),t1.d)))}
} {}
do_test randexpr-2.1373 {
  db eval {SELECT case +b when coalesce((select max(b) from t1 where exists(select 1 from t1 where (((+~13) in (select case cast(avg(t1.e+(11)+t1.b*e) AS integer) when max(((t1.e))) then min(b)-case  -cast(avg(17) AS integer) when min(e) then cast(avg(t1.c) AS integer) else (max(d)) end-count(distinct t1.f) else count(distinct d) end+count(*) from t1 union select max(d) from t1))))),(abs(~d)/abs(11))) then  -e else  - -13 end+d & t1.d FROM t1 WHERE ((a)>coalesce((select max(coalesce((select max(case when case case when 19 in (select case min(11) when  - -cast(avg(c) AS integer) then count(*) else count(*) end-cast(avg(19) AS integer) | cast(avg(17) AS integer) from t1 union select min(t1.d) from t1) then t1.b*t1.a else  -t1.a end when t1.f then e else t1.d end<a then t1.a when b between  -a and t1.d then  -a else t1.f end) from t1 where b<>d),t1.d)) from t1 where t1.c<>e and  -17<=a),t1.d))}
} {400}
do_test randexpr-2.1374 {
  db eval {SELECT +c+case when (~t1.e in (+(select case cast(avg(17) AS integer)+min(19)+count(*) when  -max(c) then count(distinct t1.c) else  - - -(max(13)) end*count(distinct ( -17)) from t1)-case when d+case when f<>d or t1.d<=t1.e then t1.a else  -11 end in (select cast(avg(t1.e) AS integer) from t1 union select cast(avg(b) AS integer) from t1) then 19 when ((t1.c) between e and a and  -13 not in (d,f,e)) then t1.e else d end,a,t1.b)) then case when t1.b<19 then 13 else 19 end else t1.c end FROM t1 WHERE not exists(select 1 from t1 where 19>t1.f+coalesce((select 13 from t1 where t1.d in (coalesce((select max(e) from t1 where c<t1.c),case when exists(select 1 from t1 where not exists(select 1 from t1 where not (coalesce((select 19 from t1 where case when not exists(select 1 from t1 where 17<17) then t1.f else a end>=t1.c),t1.d) between t1.b and c))) then  -f+(t1.b)-t1.e-t1.c+t1.c when c in (select  -( -f) from t1 union select 13 from t1) then t1.e else t1.a end),t1.b,a)),11))}
} {600}
do_test randexpr-2.1375 {
  db eval {SELECT +c+case when (~t1.e in (+(select case cast(avg(17) AS integer)+min(19)+count(*) when  -max(c) then count(distinct t1.c) else  - - -(max(13)) end*count(distinct ( -17)) from t1)-case when d+case when f<>d or t1.d<=t1.e then t1.a else  -11 end in (select cast(avg(t1.e) AS integer) from t1 union select cast(avg(b) AS integer) from t1) then 19 when ((t1.c) between e and a and  -13 not in (d,f,e)) then t1.e else d end,a,t1.b)) then case when t1.b<19 then 13 else 19 end else t1.c end FROM t1 WHERE NOT (not exists(select 1 from t1 where 19>t1.f+coalesce((select 13 from t1 where t1.d in (coalesce((select max(e) from t1 where c<t1.c),case when exists(select 1 from t1 where not exists(select 1 from t1 where not (coalesce((select 19 from t1 where case when not exists(select 1 from t1 where 17<17) then t1.f else a end>=t1.c),t1.d) between t1.b and c))) then  -f+(t1.b)-t1.e-t1.c+t1.c when c in (select  -( -f) from t1 union select 13 from t1) then t1.e else t1.a end),t1.b,a)),11)))}
} {}
do_test randexpr-2.1376 {
  db eval {SELECT (17-t1.e-17*t1.d+coalesce((select  -(abs(t1.a)/abs(t1.e))-t1.e*13*c*c-c from t1 where coalesce((select max(t1.a) from t1 where +case when t1.a not in (e,(t1.b),t1.f) then 11 when t1.b not between t1.c and t1.c then d else b end not in (13,t1.c,b)),f) between f and 11),d)-t1.d)-f+13 FROM t1 WHERE t1.f<>case when 11 in (coalesce((select e from t1 where not exists(select 1 from t1 where not case when t1.c between 11 and f then +t1.d else (((abs(coalesce((select  -t1.c from t1 where (c in (b,b,t1.e))),13) | t1.e*t1.d)/abs(c))-t1.f)) end-t1.d<a and a>=c)),t1.e),d,t1.e) or t1.b<t1.a then 13 when 11=a then t1.a else t1.a end}
} {-7870}
do_test randexpr-2.1377 {
  db eval {SELECT (17-t1.e-17*t1.d+coalesce((select  -(abs(t1.a)/abs(t1.e))-t1.e*13*c*c-c from t1 where coalesce((select max(t1.a) from t1 where +case when t1.a not in (e,(t1.b),t1.f) then 11 when t1.b not between t1.c and t1.c then d else b end not in (13,t1.c,b)),f) between f and 11),d)-t1.d)-f+13 FROM t1 WHERE NOT (t1.f<>case when 11 in (coalesce((select e from t1 where not exists(select 1 from t1 where not case when t1.c between 11 and f then +t1.d else (((abs(coalesce((select  -t1.c from t1 where (c in (b,b,t1.e))),13) | t1.e*t1.d)/abs(c))-t1.f)) end-t1.d<a and a>=c)),t1.e),d,t1.e) or t1.b<t1.a then 13 when 11=a then t1.a else t1.a end)}
} {}
do_test randexpr-2.1378 {
  db eval {SELECT case +c when 19*t1.b*coalesce((select t1.b-(19* -case when (coalesce((select t1.a from t1 where c>=e or t1.a not in (t1.c,e,t1.f)),t1.b)+19<=t1.a) then ((b)) when d>=b or d not between 19 and t1.e then t1.c else t1.b end-t1.a*f) from t1 where 13 between t1.f and t1.b or e not in (t1.e,b,19)),t1.a) then d else t1.a end FROM t1 WHERE  -b>=(select max(19) from t1)}
} {}
do_test randexpr-2.1379 {
  db eval {SELECT case +c when 19*t1.b*coalesce((select t1.b-(19* -case when (coalesce((select t1.a from t1 where c>=e or t1.a not in (t1.c,e,t1.f)),t1.b)+19<=t1.a) then ((b)) when d>=b or d not between 19 and t1.e then t1.c else t1.b end-t1.a*f) from t1 where 13 between t1.f and t1.b or e not in (t1.e,b,19)),t1.a) then d else t1.a end FROM t1 WHERE NOT ( -b>=(select max(19) from t1))}
} {100}
do_test randexpr-2.1380 {
  db eval {SELECT d+(abs(case t1.e when e*(abs(17)/abs(b)) then f else case when not not 13=c then coalesce((select t1.b from t1 where ((e-11 in (select 19 from t1 union select 17 from t1))) or f>=f),d) else case when c in (t1.a,t1.c,d) then t1.e when  -11 in (t1.a,e,t1.d) then t1.a else 19 end end-t1.e end*19)/abs(t1.c))-t1.e+d*t1.f FROM t1 WHERE t1.d+t1.c*coalesce((select e from t1 where coalesce((select max(t1.f) from t1 where not f in (select abs(case min(case when a not between a and f then 17 when e>17 then t1.d else 13 end) when abs(case cast(avg(t1.a) AS integer) when  -min(t1.b) then count(distinct 17) else (count(distinct t1.a)) end)-count(distinct  -b) then count(distinct d) else max(t1.f) end)+count(*)*max(e) from t1 union select (cast(avg(t1.c) AS integer)) from t1)),b*case 19 when t1.a then 11 else e end)<=f),17)=c}
} {}
do_test randexpr-2.1381 {
  db eval {SELECT d+(abs(case t1.e when e*(abs(17)/abs(b)) then f else case when not not 13=c then coalesce((select t1.b from t1 where ((e-11 in (select 19 from t1 union select 17 from t1))) or f>=f),d) else case when c in (t1.a,t1.c,d) then t1.e when  -11 in (t1.a,e,t1.d) then t1.a else 19 end end-t1.e end*19)/abs(t1.c))-t1.e+d*t1.f FROM t1 WHERE NOT (t1.d+t1.c*coalesce((select e from t1 where coalesce((select max(t1.f) from t1 where not f in (select abs(case min(case when a not between a and f then 17 when e>17 then t1.d else 13 end) when abs(case cast(avg(t1.a) AS integer) when  -min(t1.b) then count(distinct 17) else (count(distinct t1.a)) end)-count(distinct  -b) then count(distinct d) else max(t1.f) end)+count(*)*max(e) from t1 union select (cast(avg(t1.c) AS integer)) from t1)),b*case 19 when t1.a then 11 else e end)<=f),17)=c)}
} {239900}
do_test randexpr-2.1382 {
  db eval {SELECT case when ~t1.b=t1.b-coalesce((select 17 from t1 where t1.d-a>=(abs(case when c*11 between 19+(select cast(avg(13*b) AS integer) from t1) and case t1.e-t1.f when t1.a then 11 else a end then 19 else 17 end-c+a)/abs(t1.a))),e) then (f) when exists(select 1 from t1 where (11) in (c,t1.c,t1.b)) then f else 19 end*t1.f FROM t1 WHERE case 19 when t1.b then b*case t1.a when +t1.f then e else 17+t1.a end-11++(select ~~abs(~count(*))+count(distinct 13) from t1)*t1.b-t1.c- -a else 17 end>=t1.e}
} {}
do_test randexpr-2.1383 {
  db eval {SELECT case when ~t1.b=t1.b-coalesce((select 17 from t1 where t1.d-a>=(abs(case when c*11 between 19+(select cast(avg(13*b) AS integer) from t1) and case t1.e-t1.f when t1.a then 11 else a end then 19 else 17 end-c+a)/abs(t1.a))),e) then (f) when exists(select 1 from t1 where (11) in (c,t1.c,t1.b)) then f else 19 end*t1.f FROM t1 WHERE NOT (case 19 when t1.b then b*case t1.a when +t1.f then e else 17+t1.a end-11++(select ~~abs(~count(*))+count(distinct 13) from t1)*t1.b-t1.c- -a else 17 end>=t1.e)}
} {11400}
do_test randexpr-2.1384 {
  db eval {SELECT case when t1.a<=e and d*(t1.d)+t1.d++a-t1.f-a<=e or c not between b and d and 19 not between t1.e and 11 or  -t1.b in (select b from t1 union select 17 from t1) and t1.d<>t1.e or t1.d in (select t1.c from t1 union select t1.d from t1) then t1.e else 17 end+f+t1.b FROM t1 WHERE t1.c*~case 19+coalesce((select 19 from t1 where e>11-d),t1.e) when coalesce((select max(11) from t1 where not t1.f in (select ~abs(cast(avg(coalesce((select max(b+f) from t1 where  -f=(t1.b) and a between t1.c and t1.b),a)) AS integer))+ -count(distinct t1.b)- -max(f)*max((f)) from t1 union select min(t1.e) from t1) or a in (select +d*d from t1 union select t1.c from t1)),t1.e) then t1.d else t1.c end*t1.b<t1.b}
} {1300}
do_test randexpr-2.1385 {
  db eval {SELECT case when t1.a<=e and d*(t1.d)+t1.d++a-t1.f-a<=e or c not between b and d and 19 not between t1.e and 11 or  -t1.b in (select b from t1 union select 17 from t1) and t1.d<>t1.e or t1.d in (select t1.c from t1 union select t1.d from t1) then t1.e else 17 end+f+t1.b FROM t1 WHERE NOT (t1.c*~case 19+coalesce((select 19 from t1 where e>11-d),t1.e) when coalesce((select max(11) from t1 where not t1.f in (select ~abs(cast(avg(coalesce((select max(b+f) from t1 where  -f=(t1.b) and a between t1.c and t1.b),a)) AS integer))+ -count(distinct t1.b)- -max(f)*max((f)) from t1 union select min(t1.e) from t1) or a in (select +d*d from t1 union select t1.c from t1)),t1.e) then t1.d else t1.c end*t1.b<t1.b)}
} {}
do_test randexpr-2.1386 {
  db eval {SELECT coalesce((select 17 from t1 where (~f=(abs(coalesce((select t1.d from t1 where case (select count(distinct c | 13)- -(cast(avg(11) AS integer)) from t1)+coalesce((select 19 from t1 where d in (select t1.c from t1 union select 17 from t1)),t1.f) when e then t1.c else t1.d end*d<=19 and not exists(select 1 from t1 where (e)<>b)),e)-13)/abs(t1.e))+17)),t1.a)*t1.d+b FROM t1 WHERE not exists(select 1 from t1 where t1.b=case 19 when f then d+case when t1.c not between 13 and d | (select abs((min(17) | (min(t1.f)))) from t1) and coalesce((select max(11*19) from t1 where not exists(select 1 from t1 where (e>=t1.b))),11) not in (t1.c,19,t1.c) or t1.a in (select count(*) from t1 union select max(c)+cast(avg(11) AS integer) from t1) and (c) not between t1.a and t1.d and t1.b between 11 and a then t1.d else c end else (t1.f) end)}
} {40200}
do_test randexpr-2.1387 {
  db eval {SELECT coalesce((select 17 from t1 where (~f=(abs(coalesce((select t1.d from t1 where case (select count(distinct c | 13)- -(cast(avg(11) AS integer)) from t1)+coalesce((select 19 from t1 where d in (select t1.c from t1 union select 17 from t1)),t1.f) when e then t1.c else t1.d end*d<=19 and not exists(select 1 from t1 where (e)<>b)),e)-13)/abs(t1.e))+17)),t1.a)*t1.d+b FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.b=case 19 when f then d+case when t1.c not between 13 and d | (select abs((min(17) | (min(t1.f)))) from t1) and coalesce((select max(11*19) from t1 where not exists(select 1 from t1 where (e>=t1.b))),11) not in (t1.c,19,t1.c) or t1.a in (select count(*) from t1 union select max(c)+cast(avg(11) AS integer) from t1) and (c) not between t1.a and t1.d and t1.b between 11 and a then t1.d else c end else (t1.f) end))}
} {}
do_test randexpr-2.1388 {
  db eval {SELECT coalesce((select 17 from t1 where (~f=(abs(coalesce((select t1.d from t1 where case (select count(distinct c & 13)- -(cast(avg(11) AS integer)) from t1)+coalesce((select 19 from t1 where d in (select t1.c from t1 union select 17 from t1)),t1.f) when e then t1.c else t1.d end*d<=19 and not exists(select 1 from t1 where (e)<>b)),e)-13)/abs(t1.e))+17)),t1.a)*t1.d+b FROM t1 WHERE not exists(select 1 from t1 where t1.b=case 19 when f then d+case when t1.c not between 13 and d | (select abs((min(17) | (min(t1.f)))) from t1) and coalesce((select max(11*19) from t1 where not exists(select 1 from t1 where (e>=t1.b))),11) not in (t1.c,19,t1.c) or t1.a in (select count(*) from t1 union select max(c)+cast(avg(11) AS integer) from t1) and (c) not between t1.a and t1.d and t1.b between 11 and a then t1.d else c end else (t1.f) end)}
} {40200}
do_test randexpr-2.1389 {
  db eval {SELECT coalesce((select max(t1.f+19+case  -d when t1.f then t1.e else e end+case when +d in (select case when exists(select 1 from t1 where coalesce((select max( -17-d+t1.b-t1.d) from t1 where e not in (f,t1.e,11)),c) | t1.e>=c) then b else d end from t1 union select c from t1) then t1.b else d end-e*b+11) from t1 where f<>t1.b),d) FROM t1 WHERE (exists(select 1 from t1 where f> -t1.a*11 or e in (a-~ -t1.e,+a | e*case when coalesce((select t1.c from t1 where t1.f in (select (count(*)) from t1 union select ((count(*))) from t1)),a)-t1.e not in (e,t1.a,d) or 19 in (t1.b,t1.c,13) and c>19 then b*d else ( -t1.d) end-t1.a*t1.b*19,b)))}
} {-98470}
do_test randexpr-2.1390 {
  db eval {SELECT coalesce((select max(t1.f+19+case  -d when t1.f then t1.e else e end+case when +d in (select case when exists(select 1 from t1 where coalesce((select max( -17-d+t1.b-t1.d) from t1 where e not in (f,t1.e,11)),c) | t1.e>=c) then b else d end from t1 union select c from t1) then t1.b else d end-e*b+11) from t1 where f<>t1.b),d) FROM t1 WHERE NOT ((exists(select 1 from t1 where f> -t1.a*11 or e in (a-~ -t1.e,+a | e*case when coalesce((select t1.c from t1 where t1.f in (select (count(*)) from t1 union select ((count(*))) from t1)),a)-t1.e not in (e,t1.a,d) or 19 in (t1.b,t1.c,13) and c>19 then b*d else ( -t1.d) end-t1.a*t1.b*19,b))))}
} {}
do_test randexpr-2.1391 {
  db eval {SELECT coalesce((select max(t1.f+19+case  -d when t1.f then t1.e else e end+case when +d in (select case when exists(select 1 from t1 where coalesce((select max( -17-d+t1.b-t1.d) from t1 where e not in (f,t1.e,11)),c) & t1.e>=c) then b else d end from t1 union select c from t1) then t1.b else d end-e*b+11) from t1 where f<>t1.b),d) FROM t1 WHERE (exists(select 1 from t1 where f> -t1.a*11 or e in (a-~ -t1.e,+a | e*case when coalesce((select t1.c from t1 where t1.f in (select (count(*)) from t1 union select ((count(*))) from t1)),a)-t1.e not in (e,t1.a,d) or 19 in (t1.b,t1.c,13) and c>19 then b*d else ( -t1.d) end-t1.a*t1.b*19,b)))}
} {-98670}
do_test randexpr-2.1392 {
  db eval {SELECT case t1.b* -(abs(e)/abs(d+b)) when ~a-11 then coalesce((select max(case when (~~19- -t1.d<t1.f or t1.e>=f) then +(abs(t1.c)/abs(t1.e)) when (t1.d>e or t1.a>=t1.a) then 19 else t1.a end*b-(19)-a-t1.c) from t1 where t1.f>=11),13) else b end FROM t1 WHERE (not exists(select 1 from t1 where t1.e<=t1.f) or c- -e*17 in (t1.c+c, -b-17, -coalesce((select case when +coalesce((select max(coalesce((select t1.f from t1 where t1.d in (select max(t1.d)-count(*) from t1 union select max( -t1.a) from t1)),e)+11) from t1 where ( -19)>=t1.a),t1.e)-13 not between t1.a and d then t1.d else 19 end+t1.b from t1 where t1.d<>19),11)))}
} {}
do_test randexpr-2.1393 {
  db eval {SELECT case t1.b* -(abs(e)/abs(d+b)) when ~a-11 then coalesce((select max(case when (~~19- -t1.d<t1.f or t1.e>=f) then +(abs(t1.c)/abs(t1.e)) when (t1.d>e or t1.a>=t1.a) then 19 else t1.a end*b-(19)-a-t1.c) from t1 where t1.f>=11),13) else b end FROM t1 WHERE NOT ((not exists(select 1 from t1 where t1.e<=t1.f) or c- -e*17 in (t1.c+c, -b-17, -coalesce((select case when +coalesce((select max(coalesce((select t1.f from t1 where t1.d in (select max(t1.d)-count(*) from t1 union select max( -t1.a) from t1)),e)+11) from t1 where ( -19)>=t1.a),t1.e)-13 not between t1.a and d then t1.d else 19 end+t1.b from t1 where t1.d<>19),11))))}
} {200}
do_test randexpr-2.1394 {
  db eval {SELECT (select case case min(d-t1.c)-max(t1.a) when ~count(distinct d+case  -f*t1.d+11 when b then b else b end)-min(c) then case +max(t1.a)*~abs(count(*)) when  -min(13) then max(17) else count(*) end else  -max(e) end when max(t1.a) then max(d) else max(17) end-count(distinct t1.b) from t1)-(d) FROM t1 WHERE +19 between b*11 and (select max(d-13) | ~+~+~((count(*)))*cast(avg(b) AS integer) from t1)+b}
} {}
do_test randexpr-2.1395 {
  db eval {SELECT (select case case min(d-t1.c)-max(t1.a) when ~count(distinct d+case  -f*t1.d+11 when b then b else b end)-min(c) then case +max(t1.a)*~abs(count(*)) when  -min(13) then max(17) else count(*) end else  -max(e) end when max(t1.a) then max(d) else max(17) end-count(distinct t1.b) from t1)-(d) FROM t1 WHERE NOT (+19 between b*11 and (select max(d-13) | ~+~+~((count(*)))*cast(avg(b) AS integer) from t1)+b)}
} {-384}
do_test randexpr-2.1396 {
  db eval {SELECT (abs(case when +a*t1.e+(abs(t1.e | 11+coalesce((select max(d) from t1 where (not not b<coalesce((select e from t1 where e<>19),17)) and t1.b>13 and d=t1.a and 13 in (d,t1.a,11)),t1.e)*d)/abs(11+t1.a-19))=c or b<>c then t1.e when b<>19 then 17 else b end)/abs(11)) FROM t1 WHERE (coalesce((select max(case when exists(select 1 from t1 where coalesce((select a from t1 where not 19-~(coalesce((select t1.d from t1 where d between e and 17),t1.a)-t1.a-17) in (t1.d,t1.e,19)),19)*11*d in (select d from t1 union select t1.b from t1)) then c when d between t1.a and  -19 then t1.e else 19 end-d*c) from t1 where (t1.f>=t1.c)),11)) not in (17,17,a)}
} {45}
do_test randexpr-2.1397 {
  db eval {SELECT (abs(case when +a*t1.e+(abs(t1.e | 11+coalesce((select max(d) from t1 where (not not b<coalesce((select e from t1 where e<>19),17)) and t1.b>13 and d=t1.a and 13 in (d,t1.a,11)),t1.e)*d)/abs(11+t1.a-19))=c or b<>c then t1.e when b<>19 then 17 else b end)/abs(11)) FROM t1 WHERE NOT ((coalesce((select max(case when exists(select 1 from t1 where coalesce((select a from t1 where not 19-~(coalesce((select t1.d from t1 where d between e and 17),t1.a)-t1.a-17) in (t1.d,t1.e,19)),19)*11*d in (select d from t1 union select t1.b from t1)) then c when d between t1.a and  -19 then t1.e else 19 end-d*c) from t1 where (t1.f>=t1.c)),11)) not in (17,17,a))}
} {}
do_test randexpr-2.1398 {
  db eval {SELECT (abs(case when +a*t1.e+(abs(t1.e & 11+coalesce((select max(d) from t1 where (not not b<coalesce((select e from t1 where e<>19),17)) and t1.b>13 and d=t1.a and 13 in (d,t1.a,11)),t1.e)*d)/abs(11+t1.a-19))=c or b<>c then t1.e when b<>19 then 17 else b end)/abs(11)) FROM t1 WHERE (coalesce((select max(case when exists(select 1 from t1 where coalesce((select a from t1 where not 19-~(coalesce((select t1.d from t1 where d between e and 17),t1.a)-t1.a-17) in (t1.d,t1.e,19)),19)*11*d in (select d from t1 union select t1.b from t1)) then c when d between t1.a and  -19 then t1.e else 19 end-d*c) from t1 where (t1.f>=t1.c)),11)) not in (17,17,a)}
} {45}
do_test randexpr-2.1399 {
  db eval {SELECT 19+(t1.f)*case coalesce((select max(b) from t1 where not f not between coalesce((select (select (count(distinct t1.c))+ -max( -(f)) from t1)+t1.c from t1 where t1.c<=d),17)-c-19 and 17 or f<>13),case when not exists(select 1 from t1 where ((a)) between b and t1.f) then c when not ( -f not in (t1.b,t1.a,t1.c)) then  -t1.b else 19 end)-t1.d-t1.e when t1.e then 11 else 19 end FROM t1 WHERE not not exists(select 1 from t1 where not 11=c and a*e between coalesce((select max(t1.e) from t1 where f=t1.b*19+case when (e not in (t1.d,t1.d, -c) or t1.a<e or 13 in (select  - -count(*) from t1 union select min(17) from t1)) then t1.c when  -19 in (13,f,e) then  -t1.d else 17 end+t1.b*d),f)*d and t1.a)}
} {}
do_test randexpr-2.1400 {
  db eval {SELECT 19+(t1.f)*case coalesce((select max(b) from t1 where not f not between coalesce((select (select (count(distinct t1.c))+ -max( -(f)) from t1)+t1.c from t1 where t1.c<=d),17)-c-19 and 17 or f<>13),case when not exists(select 1 from t1 where ((a)) between b and t1.f) then c when not ( -f not in (t1.b,t1.a,t1.c)) then  -t1.b else 19 end)-t1.d-t1.e when t1.e then 11 else 19 end FROM t1 WHERE NOT (not not exists(select 1 from t1 where not 11=c and a*e between coalesce((select max(t1.e) from t1 where f=t1.b*19+case when (e not in (t1.d,t1.d, -c) or t1.a<e or 13 in (select  - -count(*) from t1 union select min(17) from t1)) then t1.c when  -19 in (13,f,e) then  -t1.d else 17 end+t1.b*d),f)*d and t1.a))}
} {11419}
do_test randexpr-2.1401 {
  db eval {SELECT coalesce((select max(19) from t1 where e-coalesce((select 13 from t1 where exists(select 1 from t1 where ((+(case when d*t1.b not in (t1.d,t1.f,e) then 11 else t1.c end))+19*11+e<=11))),19+t1.d) between t1.c and  -e and exists(select 1 from t1 where t1.d=c and exists(select 1 from t1 where exists(select 1 from t1 where t1.f=b and a in (19,t1.b,d) or t1.b=11) or t1.c>19) or t1.d=a)),19) FROM t1 WHERE t1.c not between f and d}
} {19}
do_test randexpr-2.1402 {
  db eval {SELECT coalesce((select max(19) from t1 where e-coalesce((select 13 from t1 where exists(select 1 from t1 where ((+(case when d*t1.b not in (t1.d,t1.f,e) then 11 else t1.c end))+19*11+e<=11))),19+t1.d) between t1.c and  -e and exists(select 1 from t1 where t1.d=c and exists(select 1 from t1 where exists(select 1 from t1 where t1.f=b and a in (19,t1.b,d) or t1.b=11) or t1.c>19) or t1.d=a)),19) FROM t1 WHERE NOT (t1.c not between f and d)}
} {}
do_test randexpr-2.1403 {
  db eval {SELECT case e when (t1.e+case when t1.e not between t1.c and case when d+coalesce((select t1.d+13+case case a when t1.a then t1.b else t1.c end when 17 then t1.b else f end+19 from t1 where exists(select 1 from t1 where t1.f< -17)),11)>=d then 13 else 13 end*(t1.c) then  -c when t1.e not between t1.f and t1.d then t1.a else ( - -t1.a) end-d) then t1.a else t1.d end FROM t1 WHERE t1.d between case when  -(t1.e-c)+a between  -+coalesce((select max(+t1.c) from t1 where (coalesce((select max(case when d>~t1.e then t1.c when t1.f in (select t1.d from t1 union select t1.e from t1) then (19) else t1.e end) from t1 where not exists(select 1 from t1 where t1.e< -(11))),t1.f) in (select min(t1.f) from t1 union select count(distinct 13) from t1))),t1.e) and t1.d then a when 13<=c then b else t1.c end-c and f}
} {400}
do_test randexpr-2.1404 {
  db eval {SELECT case e when (t1.e+case when t1.e not between t1.c and case when d+coalesce((select t1.d+13+case case a when t1.a then t1.b else t1.c end when 17 then t1.b else f end+19 from t1 where exists(select 1 from t1 where t1.f< -17)),11)>=d then 13 else 13 end*(t1.c) then  -c when t1.e not between t1.f and t1.d then t1.a else ( - -t1.a) end-d) then t1.a else t1.d end FROM t1 WHERE NOT (t1.d between case when  -(t1.e-c)+a between  -+coalesce((select max(+t1.c) from t1 where (coalesce((select max(case when d>~t1.e then t1.c when t1.f in (select t1.d from t1 union select t1.e from t1) then (19) else t1.e end) from t1 where not exists(select 1 from t1 where t1.e< -(11))),t1.f) in (select min(t1.f) from t1 union select count(distinct 13) from t1))),t1.e) and t1.d then a when 13<=c then b else t1.c end-c and f)}
} {}
do_test randexpr-2.1405 {
  db eval {SELECT (select abs(min(case when d not between coalesce((select max(case case t1.e when e-t1.f-a then case when (not exists(select 1 from t1 where coalesce((select max(t1.f) from t1 where 19<>17 and e not between  -13 and t1.a),t1.c)>=t1.e)) then (select abs(cast(avg(17) AS integer)) from t1) when c between e and 17 then (select (count(*)) from t1) else 11 end else 11 end when e then 11 else a end) from t1 where t1.b>t1.b),t1.e) and 13 then t1.d else 17 end))*min(b) |  -count(distinct t1.f) from t1) FROM t1 WHERE (e) in (select +t1.f from t1 union select t1.f+coalesce((select t1.d+e from t1 where t1.f not in (t1.b,t1.f,e)),(19))*case when t1.a<=a and t1.e<=e then t1.d else t1.c end from t1) and (t1.c not between 11 and e) or d in (select count(*)-cast(avg(t1.a) AS integer) from t1 union select max(19) from t1) and not t1.a not in (11,t1.d,b) or 17>=t1.a}
} {}
do_test randexpr-2.1406 {
  db eval {SELECT (select abs(min(case when d not between coalesce((select max(case case t1.e when e-t1.f-a then case when (not exists(select 1 from t1 where coalesce((select max(t1.f) from t1 where 19<>17 and e not between  -13 and t1.a),t1.c)>=t1.e)) then (select abs(cast(avg(17) AS integer)) from t1) when c between e and 17 then (select (count(*)) from t1) else 11 end else 11 end when e then 11 else a end) from t1 where t1.b>t1.b),t1.e) and 13 then t1.d else 17 end))*min(b) |  -count(distinct t1.f) from t1) FROM t1 WHERE NOT ((e) in (select +t1.f from t1 union select t1.f+coalesce((select t1.d+e from t1 where t1.f not in (t1.b,t1.f,e)),(19))*case when t1.a<=a and t1.e<=e then t1.d else t1.c end from t1) and (t1.c not between 11 and e) or d in (select count(*)-cast(avg(t1.a) AS integer) from t1 union select max(19) from t1) and not t1.a not in (11,t1.d,b) or 17>=t1.a)}
} {-1}
do_test randexpr-2.1407 {
  db eval {SELECT (select abs(min(case when d not between coalesce((select max(case case t1.e when e-t1.f-a then case when (not exists(select 1 from t1 where coalesce((select max(t1.f) from t1 where 19<>17 and e not between  -13 and t1.a),t1.c)>=t1.e)) then (select abs(cast(avg(17) AS integer)) from t1) when c between e and 17 then (select (count(*)) from t1) else 11 end else 11 end when e then 11 else a end) from t1 where t1.b>t1.b),t1.e) and 13 then t1.d else 17 end))*min(b) &  -count(distinct t1.f) from t1) FROM t1 WHERE NOT ((e) in (select +t1.f from t1 union select t1.f+coalesce((select t1.d+e from t1 where t1.f not in (t1.b,t1.f,e)),(19))*case when t1.a<=a and t1.e<=e then t1.d else t1.c end from t1) and (t1.c not between 11 and e) or d in (select count(*)-cast(avg(t1.a) AS integer) from t1 union select max(19) from t1) and not t1.a not in (11,t1.d,b) or 17>=t1.a)}
} {80000}
do_test randexpr-2.1408 {
  db eval {SELECT case when ++coalesce((select (abs(a)/abs((select max((abs(13*f)/abs(t1.d))-t1.d*t1.e) from t1)))+b-t1.c+(select +(cast(avg(c) AS integer))*count(*) from t1)-t1.d-b*t1.e+19 from t1 where t1.c not between 11 and t1.d),19)<=t1.d then t1.d when not exists(select 1 from t1 where  -11=t1.a) then e else 11 end FROM t1 WHERE (coalesce((select max(coalesce((select a-19 | ~~t1.b from t1 where (abs(t1.f)/abs(b)) not between case when t1.d<=case when not exists(select 1 from t1 where 19<=t1.d) then case when t1.a<=c then f else t1.d end when d>=17 then t1.c else (b) end*t1.c then  - -t1.c when c<>t1.a then t1.f else 11 end and e),t1.e)-(t1.a)) from t1 where e<=a),17)<=t1.e) and t1.d=(f)}
} {}
do_test randexpr-2.1409 {
  db eval {SELECT case when ++coalesce((select (abs(a)/abs((select max((abs(13*f)/abs(t1.d))-t1.d*t1.e) from t1)))+b-t1.c+(select +(cast(avg(c) AS integer))*count(*) from t1)-t1.d-b*t1.e+19 from t1 where t1.c not between 11 and t1.d),19)<=t1.d then t1.d when not exists(select 1 from t1 where  -11=t1.a) then e else 11 end FROM t1 WHERE NOT ((coalesce((select max(coalesce((select a-19 | ~~t1.b from t1 where (abs(t1.f)/abs(b)) not between case when t1.d<=case when not exists(select 1 from t1 where 19<=t1.d) then case when t1.a<=c then f else t1.d end when d>=17 then t1.c else (b) end*t1.c then  - -t1.c when c<>t1.a then t1.f else 11 end and e),t1.e)-(t1.a)) from t1 where e<=a),17)<=t1.e) and t1.d=(f))}
} {400}
do_test randexpr-2.1410 {
  db eval {SELECT c*t1.c*(abs(case 11 when case when 11*11 not between b and t1.a then t1.d else  -coalesce((select t1.c from t1 where (not exists(select 1 from t1 where e*~13 not in (a*t1.c, -t1.a,case when 13=t1.c or 13 between 11 and a then  - -a when e<=t1.e then 13 else 11 end)))),t1.b+t1.b) end then t1.c else ((e)) end)/abs(t1.a))+t1.a-e-13 FROM t1 WHERE t1.a*13+case when (select count(distinct b++(select case count(distinct 19*(select  -+min((13*f))-count(distinct t1.c)-max(t1.e) | (count(distinct 11)) from t1)*(f)) when count(*) then min(a)+(cast(avg(t1.d) AS integer)) else  -min(17) end from t1) | t1.c-f) from t1)>t1.b then 19 else c end+17<c}
} {}
do_test randexpr-2.1411 {
  db eval {SELECT c*t1.c*(abs(case 11 when case when 11*11 not between b and t1.a then t1.d else  -coalesce((select t1.c from t1 where (not exists(select 1 from t1 where e*~13 not in (a*t1.c, -t1.a,case when 13=t1.c or 13 between 11 and a then  - -a when e<=t1.e then 13 else 11 end)))),t1.b+t1.b) end then t1.c else ((e)) end)/abs(t1.a))+t1.a-e-13 FROM t1 WHERE NOT (t1.a*13+case when (select count(distinct b++(select case count(distinct 19*(select  -+min((13*f))-count(distinct t1.c)-max(t1.e) | (count(distinct 11)) from t1)*(f)) when count(*) then min(a)+(cast(avg(t1.d) AS integer)) else  -min(17) end from t1) | t1.c-f) from t1)>t1.b then 19 else c end+17<c)}
} {449587}
do_test randexpr-2.1412 {
  db eval {SELECT ~coalesce((select b from t1 where b between e and case when t1.c+coalesce((select 11 from t1 where (a in (+d-11,t1.f-a,b)) and t1.c in (select t1.f from t1 union select c from t1) or b between 13 and t1.b and t1.e<(c) and a>=t1.c and e between d and t1.f),case when (13)<>(t1.e) then d when t1.a<=t1.e then 13 else d end) not in (17,b,17) then t1.d else t1.a end+a),t1.d) FROM t1 WHERE case t1.f when 11 then t1.e | f*case when ((select max(17) from t1) | 11>17+~coalesce((select max(t1.b) from t1 where (coalesce((select max(t1.e) from t1 where t1.e in (select (cast(avg( -t1.a) AS integer)) from t1 union select count(*) from t1)),a)) in (t1.f,a,t1.e)),f)+17) then t1.a when 19 in (t1.c, -e,11) or not exists(select 1 from t1 where t1.e between d and a) then 13 else 19 end+t1.f else 11 end<17}
} {-401}
do_test randexpr-2.1413 {
  db eval {SELECT ~coalesce((select b from t1 where b between e and case when t1.c+coalesce((select 11 from t1 where (a in (+d-11,t1.f-a,b)) and t1.c in (select t1.f from t1 union select c from t1) or b between 13 and t1.b and t1.e<(c) and a>=t1.c and e between d and t1.f),case when (13)<>(t1.e) then d when t1.a<=t1.e then 13 else d end) not in (17,b,17) then t1.d else t1.a end+a),t1.d) FROM t1 WHERE NOT (case t1.f when 11 then t1.e | f*case when ((select max(17) from t1) | 11>17+~coalesce((select max(t1.b) from t1 where (coalesce((select max(t1.e) from t1 where t1.e in (select (cast(avg( -t1.a) AS integer)) from t1 union select count(*) from t1)),a)) in (t1.f,a,t1.e)),f)+17) then t1.a when 19 in (t1.c, -e,11) or not exists(select 1 from t1 where t1.e between d and a) then 13 else 19 end+t1.f else 11 end<17)}
} {}
do_test randexpr-2.1414 {
  db eval {SELECT ~case when (a<> -++ -11) then e+case when c*t1.a<t1.d then 19 when not not 11>d then t1.a else b end else a end | case when not exists(select 1 from t1 where not exists(select 1 from t1 where 13 | d in (select a from t1 union select d from t1))) or t1.f not between c and 19 then +t1.a else c-a end-17*c FROM t1 WHERE (case when (case when b in (select 11*coalesce((select 11 from t1 where (d not between 13 and 13+17)),coalesce((select max(13) from t1 where t1.c in (select max(e) from t1 union select count(*) from t1)),t1.b)) from t1 union select  -t1.e from t1) then 13 when t1.f in ( -f, -(f),c) then 19 else f end in (select t1.a from t1 union select (t1.c) from t1)) then (abs(19)/abs(t1.b)) when (e in (b,11,19)) and t1.a<c then 19 else a end between d and 11)}
} {}
do_test randexpr-2.1415 {
  db eval {SELECT ~case when (a<> -++ -11) then e+case when c*t1.a<t1.d then 19 when not not 11>d then t1.a else b end else a end | case when not exists(select 1 from t1 where not exists(select 1 from t1 where 13 | d in (select a from t1 union select d from t1))) or t1.f not between c and 19 then +t1.a else c-a end-17*c FROM t1 WHERE NOT ((case when (case when b in (select 11*coalesce((select 11 from t1 where (d not between 13 and 13+17)),coalesce((select max(13) from t1 where t1.c in (select max(e) from t1 union select count(*) from t1)),t1.b)) from t1 union select  -t1.e from t1) then 13 when t1.f in ( -f, -(f),c) then 19 else f end in (select t1.a from t1 union select (t1.c) from t1)) then (abs(19)/abs(t1.b)) when (e in (b,11,19)) and t1.a<c then 19 else a end between d and 11))}
} {-645}
do_test randexpr-2.1416 {
  db eval {SELECT ~case when (a<> -++ -11) then e+case when c*t1.a<t1.d then 19 when not not 11>d then t1.a else b end else a end & case when not exists(select 1 from t1 where not exists(select 1 from t1 where 13 & d in (select a from t1 union select d from t1))) or t1.f not between c and 19 then +t1.a else c-a end-17*c FROM t1 WHERE NOT ((case when (case when b in (select 11*coalesce((select 11 from t1 where (d not between 13 and 13+17)),coalesce((select max(13) from t1 where t1.c in (select max(e) from t1 union select count(*) from t1)),t1.b)) from t1 union select  -t1.e from t1) then 13 when t1.f in ( -f, -(f),c) then 19 else f end in (select t1.a from t1 union select (t1.c) from t1)) then (abs(19)/abs(t1.b)) when (e in (b,11,19)) and t1.a<c then 19 else a end between d and 11))}
} {-5056}
do_test randexpr-2.1417 {
  db eval {SELECT case when t1.d in (select case when exists(select 1 from t1 where 13>19) then  -d when ~c in (select min(e) from t1 union select cast(avg(case when c not between b and t1.a then b else 13-e+t1.e end) AS integer) from t1) then 13-coalesce((select max(coalesce((select max(19) from t1 where (17=a)),13)) from t1 where t1.a>=c),a) else t1.d end*(t1.c) from t1 union select (11) from t1) then a when b not in (e,t1.f,13) then t1.f else 13 end FROM t1 WHERE 13<>e or t1.a in (select f from t1 union select f from t1)}
} {600}
do_test randexpr-2.1418 {
  db eval {SELECT case when t1.d in (select case when exists(select 1 from t1 where 13>19) then  -d when ~c in (select min(e) from t1 union select cast(avg(case when c not between b and t1.a then b else 13-e+t1.e end) AS integer) from t1) then 13-coalesce((select max(coalesce((select max(19) from t1 where (17=a)),13)) from t1 where t1.a>=c),a) else t1.d end*(t1.c) from t1 union select (11) from t1) then a when b not in (e,t1.f,13) then t1.f else 13 end FROM t1 WHERE NOT (13<>e or t1.a in (select f from t1 union select f from t1))}
} {}
do_test randexpr-2.1419 {
  db eval {SELECT 17-(select case max(t1.f*~case when 17>=b then t1.d else t1.a end) when (count(distinct t1.c)) then count(distinct t1.d+~13*19) else  -min((select +case abs(count(*)) when abs(+count(*)) then ~case count(distinct a) when max(t1.c) then max(t1.c) else min(t1.f) end+max(17) else count(*) end from t1))- -cast(avg(f) AS integer)-min(a) end from t1) FROM t1 WHERE (select count(*) from t1) in (select abs(min(coalesce((select t1.d from t1 where coalesce((select max((t1.d)) from t1 where not b+t1.e*(select min(t1.a+t1.e) from t1)<=(abs(t1.d)/abs(t1.c))+t1.d),f*17+d+case when f between e and d and t1.c= -c then ~13 when b not between 11 and e then (11) else e end+t1.d)=13),t1.e))) from t1 union select (cast(avg(b) AS integer)) from t1)}
} {}
do_test randexpr-2.1420 {
  db eval {SELECT 17-(select case max(t1.f*~case when 17>=b then t1.d else t1.a end) when (count(distinct t1.c)) then count(distinct t1.d+~13*19) else  -min((select +case abs(count(*)) when abs(+count(*)) then ~case count(distinct a) when max(t1.c) then max(t1.c) else min(t1.f) end+max(17) else count(*) end from t1))- -cast(avg(f) AS integer)-min(a) end from t1) FROM t1 WHERE NOT ((select count(*) from t1) in (select abs(min(coalesce((select t1.d from t1 where coalesce((select max((t1.d)) from t1 where not b+t1.e*(select min(t1.a+t1.e) from t1)<=(abs(t1.d)/abs(t1.c))+t1.d),f*17+d+case when f between e and d and t1.c= -c then ~13 when b not between 11 and e then (11) else e end+t1.d)=13),t1.e))) from t1 union select (cast(avg(b) AS integer)) from t1))}
} {-1067}
do_test randexpr-2.1421 {
  db eval {SELECT case when +coalesce((select 19 from t1 where c between f and 13),t1.f)<>t1.c*t1.d then coalesce((select max(d) from t1 where t1.d between t1.a and t1.a),t1.f-f)-(13 | case when 11 in (select abs(max(t1.b)*cast(avg(t1.c) AS integer))+count(*) from t1 union select count(distinct b) from t1) and t1.a not in (b,t1.a,e) or a not in (e,19,(t1.e)) then t1.b else 17+t1.a end*t1.a) when 13 in (select e from t1 union select c from t1) then a else e end FROM t1 WHERE (select  -count(*) from t1)*case when not coalesce((select max(11) from t1 where t1.f<>a),t1.a)<>b then c else ~case when not 19+13-t1.d=t1.d or c>c or (t1.a=t1.d) or 13>=a then a when t1.c not between 13 and 17 then (abs(13+t1.d-t1.a)/abs(b)) else d end end+a | 11<=e}
} {-20013}
do_test randexpr-2.1422 {
  db eval {SELECT case when +coalesce((select 19 from t1 where c between f and 13),t1.f)<>t1.c*t1.d then coalesce((select max(d) from t1 where t1.d between t1.a and t1.a),t1.f-f)-(13 | case when 11 in (select abs(max(t1.b)*cast(avg(t1.c) AS integer))+count(*) from t1 union select count(distinct b) from t1) and t1.a not in (b,t1.a,e) or a not in (e,19,(t1.e)) then t1.b else 17+t1.a end*t1.a) when 13 in (select e from t1 union select c from t1) then a else e end FROM t1 WHERE NOT ((select  -count(*) from t1)*case when not coalesce((select max(11) from t1 where t1.f<>a),t1.a)<>b then c else ~case when not 19+13-t1.d=t1.d or c>c or (t1.a=t1.d) or 13>=a then a when t1.c not between 13 and 17 then (abs(13+t1.d-t1.a)/abs(b)) else d end end+a | 11<=e)}
} {}
do_test randexpr-2.1423 {
  db eval {SELECT case when +coalesce((select 19 from t1 where c between f and 13),t1.f)<>t1.c*t1.d then coalesce((select max(d) from t1 where t1.d between t1.a and t1.a),t1.f-f)-(13 & case when 11 in (select abs(max(t1.b)*cast(avg(t1.c) AS integer))+count(*) from t1 union select count(distinct b) from t1) and t1.a not in (b,t1.a,e) or a not in (e,19,(t1.e)) then t1.b else 17+t1.a end*t1.a) when 13 in (select e from t1 union select c from t1) then a else e end FROM t1 WHERE (select  -count(*) from t1)*case when not coalesce((select max(11) from t1 where t1.f<>a),t1.a)<>b then c else ~case when not 19+13-t1.d=t1.d or c>c or (t1.a=t1.d) or 13>=a then a when t1.c not between 13 and 17 then (abs(13+t1.d-t1.a)/abs(b)) else d end end+a | 11<=e}
} {0}
do_test randexpr-2.1424 {
  db eval {SELECT case t1.d | t1.f+(e)+case when +t1.e-d*t1.a+17-b*(abs(t1.f)/abs( -a))-case when 19>=e then ~t1.a*case when t1.e>19 and t1.f<>d then t1.a else t1.d end | b*e else 17 end+t1.a=17 then t1.c else t1.b end when 17 then t1.b else t1.b end FROM t1 WHERE case when c<=13*t1.a then 11 else  -case when t1.f*e>= -((19)) then case when a>=t1.c then t1.d*e else b end else coalesce((select t1.b from t1 where 11+d-17-t1.d-t1.b not in (case d-17 when f then t1.d else t1.b end,e,t1.c)),t1.c) end*19 end<>b}
} {200}
do_test randexpr-2.1425 {
  db eval {SELECT case t1.d | t1.f+(e)+case when +t1.e-d*t1.a+17-b*(abs(t1.f)/abs( -a))-case when 19>=e then ~t1.a*case when t1.e>19 and t1.f<>d then t1.a else t1.d end | b*e else 17 end+t1.a=17 then t1.c else t1.b end when 17 then t1.b else t1.b end FROM t1 WHERE NOT (case when c<=13*t1.a then 11 else  -case when t1.f*e>= -((19)) then case when a>=t1.c then t1.d*e else b end else coalesce((select t1.b from t1 where 11+d-17-t1.d-t1.b not in (case d-17 when f then t1.d else t1.b end,e,t1.c)),t1.c) end*19 end<>b)}
} {}
do_test randexpr-2.1426 {
  db eval {SELECT case t1.d & t1.f+(e)+case when +t1.e-d*t1.a+17-b*(abs(t1.f)/abs( -a))-case when 19>=e then ~t1.a*case when t1.e>19 and t1.f<>d then t1.a else t1.d end & b*e else 17 end+t1.a=17 then t1.c else t1.b end when 17 then t1.b else t1.b end FROM t1 WHERE case when c<=13*t1.a then 11 else  -case when t1.f*e>= -((19)) then case when a>=t1.c then t1.d*e else b end else coalesce((select t1.b from t1 where 11+d-17-t1.d-t1.b not in (case d-17 when f then t1.d else t1.b end,e,t1.c)),t1.c) end*19 end<>b}
} {200}
do_test randexpr-2.1427 {
  db eval {SELECT (coalesce((select max(~t1.d*19*t1.f) from t1 where (abs(17)/abs(t1.f-case when not exists(select 1 from t1 where case when a in (f,t1.a,c) then c when t1.a not in (13,t1.c,a) then e else t1.a end in (select abs(abs(min(t1.e))) from t1 union select cast(avg(11) AS integer) from t1)) or c<a then t1.f else a+d end-11))<>13 or t1.e in (e,t1.c,d)),t1.e) | 13)-d*e FROM t1 WHERE 11 in (select max(+(select max(d | b) from t1)*17-e) from t1 union select (cast(avg(+a-+((coalesce((select t1.e from t1 where exists(select 1 from t1 where (abs( -case when coalesce((select max(b-17) from t1 where not exists(select 1 from t1 where t1.f not between a and 11)),t1.c) in (select t1.d from t1 union select (17) from t1) then t1.c else ( - -t1.d) end)/abs(t1.f))+11>f)),b)))*19) AS integer))-count(distinct t1.f) from t1)}
} {}
do_test randexpr-2.1428 {
  db eval {SELECT (coalesce((select max(~t1.d*19*t1.f) from t1 where (abs(17)/abs(t1.f-case when not exists(select 1 from t1 where case when a in (f,t1.a,c) then c when t1.a not in (13,t1.c,a) then e else t1.a end in (select abs(abs(min(t1.e))) from t1 union select cast(avg(11) AS integer) from t1)) or c<a then t1.f else a+d end-11))<>13 or t1.e in (e,t1.c,d)),t1.e) | 13)-d*e FROM t1 WHERE NOT (11 in (select max(+(select max(d | b) from t1)*17-e) from t1 union select (cast(avg(+a-+((coalesce((select t1.e from t1 where exists(select 1 from t1 where (abs( -case when coalesce((select max(b-17) from t1 where not exists(select 1 from t1 where t1.f not between a and 11)),t1.c) in (select t1.d from t1 union select (17) from t1) then t1.c else ( - -t1.d) end)/abs(t1.f))+11>f)),b)))*19) AS integer))-count(distinct t1.f) from t1))}
} {-4771395}
do_test randexpr-2.1429 {
  db eval {SELECT (coalesce((select max(~t1.d*19*t1.f) from t1 where (abs(17)/abs(t1.f-case when not exists(select 1 from t1 where case when a in (f,t1.a,c) then c when t1.a not in (13,t1.c,a) then e else t1.a end in (select abs(abs(min(t1.e))) from t1 union select cast(avg(11) AS integer) from t1)) or c<a then t1.f else a+d end-11))<>13 or t1.e in (e,t1.c,d)),t1.e) & 13)-d*e FROM t1 WHERE NOT (11 in (select max(+(select max(d | b) from t1)*17-e) from t1 union select (cast(avg(+a-+((coalesce((select t1.e from t1 where exists(select 1 from t1 where (abs( -case when coalesce((select max(b-17) from t1 where not exists(select 1 from t1 where t1.f not between a and 11)),t1.c) in (select t1.d from t1 union select (17) from t1) then t1.c else ( - -t1.d) end)/abs(t1.f))+11>f)),b)))*19) AS integer))-count(distinct t1.f) from t1))}
} {-199992}
do_test randexpr-2.1430 {
  db eval {SELECT coalesce((select t1.e from t1 where +~case when d-(abs(+t1.b)/abs( -19*t1.c-(select (abs( -cast(avg((abs(d)/abs(t1.d))) AS integer))) from t1)))+11<19 then t1.a-19-a-f when not (c in (case f when t1.a then 17 else 11 end-a,t1.d, -e)) then 17 else (t1.b) end<d),t1.d) FROM t1 WHERE exists(select 1 from t1 where f not between ~17+t1.e and coalesce((select max(t1.f) from t1 where 17+19=t1.c),case when case  -case when e not in (+c, - -19,t1.c) then 19 else (b)*t1.a end+t1.c when c then 19 else t1.d end<>(t1.b) then t1.d when (not exists(select 1 from t1 where t1.f<>t1.c)) then t1.b else 17 end-e)-19)}
} {500}
do_test randexpr-2.1431 {
  db eval {SELECT coalesce((select t1.e from t1 where +~case when d-(abs(+t1.b)/abs( -19*t1.c-(select (abs( -cast(avg((abs(d)/abs(t1.d))) AS integer))) from t1)))+11<19 then t1.a-19-a-f when not (c in (case f when t1.a then 17 else 11 end-a,t1.d, -e)) then 17 else (t1.b) end<d),t1.d) FROM t1 WHERE NOT (exists(select 1 from t1 where f not between ~17+t1.e and coalesce((select max(t1.f) from t1 where 17+19=t1.c),case when case  -case when e not in (+c, - -19,t1.c) then 19 else (b)*t1.a end+t1.c when c then 19 else t1.d end<>(t1.b) then t1.d when (not exists(select 1 from t1 where t1.f<>t1.c)) then t1.b else 17 end-e)-19))}
} {}
do_test randexpr-2.1432 {
  db eval {SELECT case when (abs(17)/abs(t1.e))<t1.b then t1.d when (select count(distinct coalesce((select d from t1 where exists(select 1 from t1 where 19<(select abs(max(t1.b)) from t1)*case when t1.e>=case when (exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<>19))) then coalesce((select 11 from t1 where not exists(select 1 from t1 where t1.e not in ( -t1.d,(b),t1.d))),t1.a)+t1.f*11 else t1.a end then b else e end)),17)) from t1) not in (13,e,17) then t1.e else 11 end FROM t1 WHERE not (t1.e<>coalesce((select (case t1.c when (coalesce((select 19 from t1 where (case when not exists(select 1 from t1 where e not in (c,e,t1.f)) then t1.f | t1.a else t1.a end in (d,19,t1.a)) or t1.f<=t1.c),+13))*t1.b-t1.d then  -t1.c else b end) from t1 where 17<f), -e) or ((a)<=a)) or e<t1.e and  -(13) between 19 and 19}
} {}
do_test randexpr-2.1433 {
  db eval {SELECT case when (abs(17)/abs(t1.e))<t1.b then t1.d when (select count(distinct coalesce((select d from t1 where exists(select 1 from t1 where 19<(select abs(max(t1.b)) from t1)*case when t1.e>=case when (exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<>19))) then coalesce((select 11 from t1 where not exists(select 1 from t1 where t1.e not in ( -t1.d,(b),t1.d))),t1.a)+t1.f*11 else t1.a end then b else e end)),17)) from t1) not in (13,e,17) then t1.e else 11 end FROM t1 WHERE NOT (not (t1.e<>coalesce((select (case t1.c when (coalesce((select 19 from t1 where (case when not exists(select 1 from t1 where e not in (c,e,t1.f)) then t1.f | t1.a else t1.a end in (d,19,t1.a)) or t1.f<=t1.c),+13))*t1.b-t1.d then  -t1.c else b end) from t1 where 17<f), -e) or ((a)<=a)) or e<t1.e and  -(13) between 19 and 19)}
} {400}
do_test randexpr-2.1434 {
  db eval {SELECT (select max(t1.c) from t1) | case when d=(abs(t1.d)/abs(t1.b)) then 19 else case b when a then b+17+c-t1.d+d-a*t1.c else e+t1.f+ -(select abs(~+count(distinct case when b<d and t1.f<> -19 then e when a in (17,d,t1.f) then  -t1.f else f end)+count(*)-max(t1.f) | count(distinct t1.a) | cast(avg(t1.c) AS integer)) |  -max(a) from t1) end end FROM t1 WHERE a | t1.c in (select f from t1 union select case  -t1.c when (abs(c | t1.c)/abs(17)) then (abs(t1.e)/abs(t1.c))+~19 else coalesce((select b from t1 where 11<=case d+coalesce((select max((select ( -(cast(avg(17) AS integer)))*max(t1.e)-max(t1.d)*cast(avg(t1.e) AS integer) from t1)) from t1 where (abs(case t1.f when 19 then b else t1.c end)/abs(t1.e))=b),d)*t1.f when  -t1.b then t1.d else 19 end),a) end+d+e from t1)}
} {}
do_test randexpr-2.1435 {
  db eval {SELECT (select max(t1.c) from t1) | case when d=(abs(t1.d)/abs(t1.b)) then 19 else case b when a then b+17+c-t1.d+d-a*t1.c else e+t1.f+ -(select abs(~+count(distinct case when b<d and t1.f<> -19 then e when a in (17,d,t1.f) then  -t1.f else f end)+count(*)-max(t1.f) | count(distinct t1.a) | cast(avg(t1.c) AS integer)) |  -max(a) from t1) end end FROM t1 WHERE NOT (a | t1.c in (select f from t1 union select case  -t1.c when (abs(c | t1.c)/abs(17)) then (abs(t1.e)/abs(t1.c))+~19 else coalesce((select b from t1 where 11<=case d+coalesce((select max((select ( -(cast(avg(17) AS integer)))*max(t1.e)-max(t1.d)*cast(avg(t1.e) AS integer) from t1)) from t1 where (abs(case t1.f when 19 then b else t1.c end)/abs(t1.e))=b),d)*t1.f when  -t1.b then t1.d else 19 end),a) end+d+e from t1))}
} {1391}
do_test randexpr-2.1436 {
  db eval {SELECT (select max(t1.c) from t1) & case when d=(abs(t1.d)/abs(t1.b)) then 19 else case b when a then b+17+c-t1.d+d-a*t1.c else e+t1.f+ -(select abs(~+count(distinct case when b<d and t1.f<> -19 then e when a in (17,d,t1.f) then  -t1.f else f end)+count(*)-max(t1.f) & count(distinct t1.a) & cast(avg(t1.c) AS integer)) &  -max(a) from t1) end end FROM t1 WHERE NOT (a | t1.c in (select f from t1 union select case  -t1.c when (abs(c | t1.c)/abs(17)) then (abs(t1.e)/abs(t1.c))+~19 else coalesce((select b from t1 where 11<=case d+coalesce((select max((select ( -(cast(avg(17) AS integer)))*max(t1.e)-max(t1.d)*cast(avg(t1.e) AS integer) from t1)) from t1 where (abs(case t1.f when 19 then b else t1.c end)/abs(t1.e))=b),d)*t1.f when  -t1.b then t1.d else 19 end),a) end+d+e from t1))}
} {12}
do_test randexpr-2.1437 {
  db eval {SELECT case e*case when case coalesce((select max(13) from t1 where exists(select 1 from t1 where t1.a in (17,b,17))),t1.e)-t1.c when c then 19 else  -t1.d end+17 in (t1.d,c,11) or b<= -( - -a) then ~(a) when f in (select case case (max(e)) when count(*) then max(17) else (max(17)) end+count(distinct e)- -count(distinct d) when  -count(*) then  -count(distinct d) else ((min(t1.f))) end from t1 union select min( -19) from t1) then c else (13) end when b then t1.b else f end FROM t1 WHERE t1.b<t1.e}
} {600}
do_test randexpr-2.1438 {
  db eval {SELECT case e*case when case coalesce((select max(13) from t1 where exists(select 1 from t1 where t1.a in (17,b,17))),t1.e)-t1.c when c then 19 else  -t1.d end+17 in (t1.d,c,11) or b<= -( - -a) then ~(a) when f in (select case case (max(e)) when count(*) then max(17) else (max(17)) end+count(distinct e)- -count(distinct d) when  -count(*) then  -count(distinct d) else ((min(t1.f))) end from t1 union select min( -19) from t1) then c else (13) end when b then t1.b else f end FROM t1 WHERE NOT (t1.b<t1.e)}
} {}
do_test randexpr-2.1439 {
  db eval {SELECT case when d in (c,t1.a*19,+++case when exists(select 1 from t1 where case 17 when ~t1.b then f-e*~b-17+ -t1.c else c end<>17 or (t1.c in (19,c,a))) then 13 else c end-11+11*11) then t1.e when (11)<13 then  - -t1.c else t1.d end FROM t1 WHERE ((t1.c+17 not between case b*(11-coalesce((select max(t1.a) from t1 where ~case when (not t1.d*17=f) then t1.c-13+c else t1.d end+t1.c>=(b)),b)*e) when t1.f then b else f end-f- -17 and d or t1.d not in (t1.c,11,b)))}
} {300}
do_test randexpr-2.1440 {
  db eval {SELECT case when d in (c,t1.a*19,+++case when exists(select 1 from t1 where case 17 when ~t1.b then f-e*~b-17+ -t1.c else c end<>17 or (t1.c in (19,c,a))) then 13 else c end-11+11*11) then t1.e when (11)<13 then  - -t1.c else t1.d end FROM t1 WHERE NOT (((t1.c+17 not between case b*(11-coalesce((select max(t1.a) from t1 where ~case when (not t1.d*17=f) then t1.c-13+c else t1.d end+t1.c>=(b)),b)*e) when t1.f then b else f end-f- -17 and d or t1.d not in (t1.c,11,b))))}
} {}
do_test randexpr-2.1441 {
  db eval {SELECT t1.e*coalesce((select 17 from t1 where (19>(abs(case coalesce((select coalesce((select ~11 from t1 where b not between (13) and b),17) from t1 where 19 not between e+b+13 and  -t1.d),t1.f) when d then t1.e else t1.d end-e | f)/abs((e)))) and (t1.b<=a and 11<> - -t1.e) and t1.d<d),c) FROM t1 WHERE t1.a>t1.a | t1.c}
} {}
do_test randexpr-2.1442 {
  db eval {SELECT t1.e*coalesce((select 17 from t1 where (19>(abs(case coalesce((select coalesce((select ~11 from t1 where b not between (13) and b),17) from t1 where 19 not between e+b+13 and  -t1.d),t1.f) when d then t1.e else t1.d end-e | f)/abs((e)))) and (t1.b<=a and 11<> - -t1.e) and t1.d<d),c) FROM t1 WHERE NOT (t1.a>t1.a | t1.c)}
} {150000}
do_test randexpr-2.1443 {
  db eval {SELECT t1.e*coalesce((select 17 from t1 where (19>(abs(case coalesce((select coalesce((select ~11 from t1 where b not between (13) and b),17) from t1 where 19 not between e+b+13 and  -t1.d),t1.f) when d then t1.e else t1.d end-e & f)/abs((e)))) and (t1.b<=a and 11<> - -t1.e) and t1.d<d),c) FROM t1 WHERE NOT (t1.a>t1.a | t1.c)}
} {150000}
do_test randexpr-2.1444 {
  db eval {SELECT ~coalesce((select max(t1.a) from t1 where ((t1.c)<=case 11-~t1.b++(t1.a+ -c)*t1.d-b | d when ~e then 17 else (abs(f)/abs(t1.f-t1.c)) end-19 | b-~t1.e*a-t1.b | +c)),b)*a FROM t1 WHERE not exists(select 1 from t1 where t1.a=((abs(coalesce((select coalesce((select max(+d) from t1 where not exists(select 1 from t1 where  -t1.d in (select  -max(13)-(min((t1.a))) from t1 union select count(distinct f) from t1)) and 11 in (select f from t1 union select 17 from t1) and a<>13),case when e>(11) then  -c else d end) from t1 where e<>11 and e<d),t1.d)+t1.b)/abs(17))* -19)-b or t1.e not in (a,11,t1.f) or not exists(select 1 from t1 where (exists(select 1 from t1 where  -11=b and (d)<>t1.e))))}
} {}
do_test randexpr-2.1445 {
  db eval {SELECT ~coalesce((select max(t1.a) from t1 where ((t1.c)<=case 11-~t1.b++(t1.a+ -c)*t1.d-b | d when ~e then 17 else (abs(f)/abs(t1.f-t1.c)) end-19 | b-~t1.e*a-t1.b | +c)),b)*a FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a=((abs(coalesce((select coalesce((select max(+d) from t1 where not exists(select 1 from t1 where  -t1.d in (select  -max(13)-(min((t1.a))) from t1 union select count(distinct f) from t1)) and 11 in (select f from t1 union select 17 from t1) and a<>13),case when e>(11) then  -c else d end) from t1 where e<>11 and e<d),t1.d)+t1.b)/abs(17))* -19)-b or t1.e not in (a,11,t1.f) or not exists(select 1 from t1 where (exists(select 1 from t1 where  -11=b and (d)<>t1.e)))))}
} {-20100}
do_test randexpr-2.1446 {
  db eval {SELECT ~coalesce((select max(t1.a) from t1 where ((t1.c)<=case 11-~t1.b++(t1.a+ -c)*t1.d-b & d when ~e then 17 else (abs(f)/abs(t1.f-t1.c)) end-19 & b-~t1.e*a-t1.b & +c)),b)*a FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a=((abs(coalesce((select coalesce((select max(+d) from t1 where not exists(select 1 from t1 where  -t1.d in (select  -max(13)-(min((t1.a))) from t1 union select count(distinct f) from t1)) and 11 in (select f from t1 union select 17 from t1) and a<>13),case when e>(11) then  -c else d end) from t1 where e<>11 and e<d),t1.d)+t1.b)/abs(17))* -19)-b or t1.e not in (a,11,t1.f) or not exists(select 1 from t1 where (exists(select 1 from t1 where  -11=b and (d)<>t1.e)))))}
} {-20100}
do_test randexpr-2.1447 {
  db eval {SELECT (select count(distinct ~(((abs(b-a)/abs(case (select min((select case cast(avg(11+t1.e) AS integer) when case min( -~coalesce((select 13 from t1 where case t1.e when f then d else 17 end>=b),e)) when case max(t1.b) when (~ -count(*)+(( -max( -t1.a)))-(count(*))) then  -count(distinct (t1.c)) else min( -t1.e) end then count(*) else cast(avg( -(e)) AS integer) end then cast(avg(13) AS integer) else max(17) end from t1)) from t1) when 13 then c else (d) end))))) from t1)*t1.b FROM t1 WHERE not t1.c>=t1.b}
} {}
do_test randexpr-2.1448 {
  db eval {SELECT (select count(distinct ~(((abs(b-a)/abs(case (select min((select case cast(avg(11+t1.e) AS integer) when case min( -~coalesce((select 13 from t1 where case t1.e when f then d else 17 end>=b),e)) when case max(t1.b) when (~ -count(*)+(( -max( -t1.a)))-(count(*))) then  -count(distinct (t1.c)) else min( -t1.e) end then count(*) else cast(avg( -(e)) AS integer) end then cast(avg(13) AS integer) else max(17) end from t1)) from t1) when 13 then c else (d) end))))) from t1)*t1.b FROM t1 WHERE NOT (not t1.c>=t1.b)}
} {200}
do_test randexpr-2.1449 {
  db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where t1.b in (select e from t1 union select t1.e from t1)),t1.a)) from t1 where case when t1.d=case when d not between t1.a and case when not t1.c in ((t1.e),a,t1.c) then 19 | t1.c when a not between 19 and b then (19) else 13 end then t1.d else b end-11 and not t1.f=t1.c or 19 not in (t1.d,c, -t1.f) and 17< -t1.d then e when t1.b not between 17 and t1.b then f else d end<11),t1.c)*f FROM t1 WHERE t1.b<=(coalesce((select c from t1 where e in (t1.a,t1.c,case when 17 not between 19 and (19)-t1.a-(abs(coalesce((select d from t1 where case (t1.b+e*b*t1.c) when 13 then t1.b else 19 end<>19),17))/abs(a))*t1.a then 17 when exists(select 1 from t1 where ( -e)=a) or 13>=d then 17 else t1.f end)),c))}
} {180000}
do_test randexpr-2.1450 {
  db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where t1.b in (select e from t1 union select t1.e from t1)),t1.a)) from t1 where case when t1.d=case when d not between t1.a and case when not t1.c in ((t1.e),a,t1.c) then 19 | t1.c when a not between 19 and b then (19) else 13 end then t1.d else b end-11 and not t1.f=t1.c or 19 not in (t1.d,c, -t1.f) and 17< -t1.d then e when t1.b not between 17 and t1.b then f else d end<11),t1.c)*f FROM t1 WHERE NOT (t1.b<=(coalesce((select c from t1 where e in (t1.a,t1.c,case when 17 not between 19 and (19)-t1.a-(abs(coalesce((select d from t1 where case (t1.b+e*b*t1.c) when 13 then t1.b else 19 end<>19),17))/abs(a))*t1.a then 17 when exists(select 1 from t1 where ( -e)=a) or 13>=d then 17 else t1.f end)),c)))}
} {}
do_test randexpr-2.1451 {
  db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where t1.b in (select e from t1 union select t1.e from t1)),t1.a)) from t1 where case when t1.d=case when d not between t1.a and case when not t1.c in ((t1.e),a,t1.c) then 19 & t1.c when a not between 19 and b then (19) else 13 end then t1.d else b end-11 and not t1.f=t1.c or 19 not in (t1.d,c, -t1.f) and 17< -t1.d then e when t1.b not between 17 and t1.b then f else d end<11),t1.c)*f FROM t1 WHERE t1.b<=(coalesce((select c from t1 where e in (t1.a,t1.c,case when 17 not between 19 and (19)-t1.a-(abs(coalesce((select d from t1 where case (t1.b+e*b*t1.c) when 13 then t1.b else 19 end<>19),17))/abs(a))*t1.a then 17 when exists(select 1 from t1 where ( -e)=a) or 13>=d then 17 else t1.f end)),c))}
} {180000}
do_test randexpr-2.1452 {
  db eval {SELECT (d)+(select  -abs(+cast(avg((select max((coalesce((select d from t1 where case when 13>=e then t1.c else 19 end>=d),coalesce((select 19-(select count(distinct 19 | (abs(19)/abs(~13))) from t1) | t1.d from t1 where coalesce((select max(11) from t1 where t1.a in (select t1.d from t1 union select c from t1)),19)>t1.d),e)+t1.b))) from t1)) AS integer)+abs( -max(b))) from t1) FROM t1 WHERE c-t1.c not between t1.c and +case when +case  -case when 17 not in (17,(e),t1.c) then a else 19 end-13 when t1.e then b else 13 end>19 or 17 in (select b from t1 union select t1.c from t1) then case c when t1.c then d else c end when not t1.f in (select  -cast(avg(a) AS integer)*count(distinct (17))+min(f)* - - -cast(avg(b) AS integer) from t1 union select (count(*)) from t1) then d else a end}
} {-500}
do_test randexpr-2.1453 {
  db eval {SELECT (d)+(select  -abs(+cast(avg((select max((coalesce((select d from t1 where case when 13>=e then t1.c else 19 end>=d),coalesce((select 19-(select count(distinct 19 | (abs(19)/abs(~13))) from t1) | t1.d from t1 where coalesce((select max(11) from t1 where t1.a in (select t1.d from t1 union select c from t1)),19)>t1.d),e)+t1.b))) from t1)) AS integer)+abs( -max(b))) from t1) FROM t1 WHERE NOT (c-t1.c not between t1.c and +case when +case  -case when 17 not in (17,(e),t1.c) then a else 19 end-13 when t1.e then b else 13 end>19 or 17 in (select b from t1 union select t1.c from t1) then case c when t1.c then d else c end when not t1.f in (select  -cast(avg(a) AS integer)*count(distinct (17))+min(f)* - - -cast(avg(b) AS integer) from t1 union select (count(*)) from t1) then d else a end)}
} {}
do_test randexpr-2.1454 {
  db eval {SELECT (d)+(select  -abs(+cast(avg((select max((coalesce((select d from t1 where case when 13>=e then t1.c else 19 end>=d),coalesce((select 19-(select count(distinct 19 & (abs(19)/abs(~13))) from t1) & t1.d from t1 where coalesce((select max(11) from t1 where t1.a in (select t1.d from t1 union select c from t1)),19)>t1.d),e)+t1.b))) from t1)) AS integer)+abs( -max(b))) from t1) FROM t1 WHERE c-t1.c not between t1.c and +case when +case  -case when 17 not in (17,(e),t1.c) then a else 19 end-13 when t1.e then b else 13 end>19 or 17 in (select b from t1 union select t1.c from t1) then case c when t1.c then d else c end when not t1.f in (select  -cast(avg(a) AS integer)*count(distinct (17))+min(f)* - - -cast(avg(b) AS integer) from t1 union select (count(*)) from t1) then d else a end}
} {-500}
do_test randexpr-2.1455 {
  db eval {SELECT case when 19 in (case when coalesce((select max(case when e*t1.b in (coalesce((select t1.a from t1 where (abs(f)/abs(coalesce((select f from t1 where t1.f in (a,b,t1.d)),13))) in (b,b,11)),c),t1.a,17) then b else d end) from t1 where f>=13 and a>=17 and not exists(select 1 from t1 where (b<>f))), -t1.c) between d and 11 then d else t1.f end,t1.c,11) then 13 else 17 end FROM t1 WHERE t1.d in (select (abs(t1.a)/abs(t1.f)) from t1 union select e from t1) and ((b*coalesce((select  -11 from t1 where (coalesce((select max( -t1.e+ -coalesce((select d from t1 where t1.c<= - -t1.d),t1.c)) from t1 where b in (select  -count(distinct d)+count(distinct d)- -((min(e))) from t1 union select count(*) from t1)),(t1.e))-19*d<>t1.e)),a)*t1.f)=b)}
} {}
do_test randexpr-2.1456 {
  db eval {SELECT case when 19 in (case when coalesce((select max(case when e*t1.b in (coalesce((select t1.a from t1 where (abs(f)/abs(coalesce((select f from t1 where t1.f in (a,b,t1.d)),13))) in (b,b,11)),c),t1.a,17) then b else d end) from t1 where f>=13 and a>=17 and not exists(select 1 from t1 where (b<>f))), -t1.c) between d and 11 then d else t1.f end,t1.c,11) then 13 else 17 end FROM t1 WHERE NOT (t1.d in (select (abs(t1.a)/abs(t1.f)) from t1 union select e from t1) and ((b*coalesce((select  -11 from t1 where (coalesce((select max( -t1.e+ -coalesce((select d from t1 where t1.c<= - -t1.d),t1.c)) from t1 where b in (select  -count(distinct d)+count(distinct d)- -((min(e))) from t1 union select count(*) from t1)),(t1.e))-19*d<>t1.e)),a)*t1.f)=b))}
} {17}
do_test randexpr-2.1457 {
  db eval {SELECT coalesce((select max((select count(*) from t1)) from t1 where coalesce((select max(t1.a-coalesce((select t1.d+case when exists(select 1 from t1 where exists(select 1 from t1 where t1.f between t1.a and f)) or d | b between 19 and 19 then f+17 else (t1.b) end from t1 where t1.e not between  -t1.d and (19)),(17))) from t1 where not exists(select 1 from t1 where 19 between t1.b and 13 or t1.b>t1.c) or 19>=19),b) between 13 and f), -t1.a) FROM t1 WHERE exists(select 1 from t1 where +t1.f+t1.e<(abs(t1.b)/abs( -f*e))) or case t1.c when case when 19 not between 17 and case when t1.e<>e then t1.b when not exists(select 1 from t1 where coalesce((select max(b) from t1 where (e<t1.a)),e)>t1.d or (t1.d<>t1.e)) then t1.c else 17 end then t1.c when e<>b then 17 else e end then t1.d else t1.e end between d and b}
} {}
do_test randexpr-2.1458 {
  db eval {SELECT coalesce((select max((select count(*) from t1)) from t1 where coalesce((select max(t1.a-coalesce((select t1.d+case when exists(select 1 from t1 where exists(select 1 from t1 where t1.f between t1.a and f)) or d | b between 19 and 19 then f+17 else (t1.b) end from t1 where t1.e not between  -t1.d and (19)),(17))) from t1 where not exists(select 1 from t1 where 19 between t1.b and 13 or t1.b>t1.c) or 19>=19),b) between 13 and f), -t1.a) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.f+t1.e<(abs(t1.b)/abs( -f*e))) or case t1.c when case when 19 not between 17 and case when t1.e<>e then t1.b when not exists(select 1 from t1 where coalesce((select max(b) from t1 where (e<t1.a)),e)>t1.d or (t1.d<>t1.e)) then t1.c else 17 end then t1.c when e<>b then 17 else e end then t1.d else t1.e end between d and b)}
} {-100}
do_test randexpr-2.1459 {
  db eval {SELECT coalesce((select max((select count(*) from t1)) from t1 where coalesce((select max(t1.a-coalesce((select t1.d+case when exists(select 1 from t1 where exists(select 1 from t1 where t1.f between t1.a and f)) or d & b between 19 and 19 then f+17 else (t1.b) end from t1 where t1.e not between  -t1.d and (19)),(17))) from t1 where not exists(select 1 from t1 where 19 between t1.b and 13 or t1.b>t1.c) or 19>=19),b) between 13 and f), -t1.a) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.f+t1.e<(abs(t1.b)/abs( -f*e))) or case t1.c when case when 19 not between 17 and case when t1.e<>e then t1.b when not exists(select 1 from t1 where coalesce((select max(b) from t1 where (e<t1.a)),e)>t1.d or (t1.d<>t1.e)) then t1.c else 17 end then t1.c when e<>b then 17 else e end then t1.d else t1.e end between d and b)}
} {-100}
do_test randexpr-2.1460 {
  db eval {SELECT case when not case 11 when t1.e*coalesce((select max(t1.b) from t1 where (abs(t1.c)/abs(~11)) not between coalesce((select max((abs(a)/abs(c))) from t1 where t1.b>=t1.a or b= -e),t1.f) and e and c not in (t1.a,t1.f,t1.c) and not (a)<t1.b or t1.b not between b and t1.a),17)*11+b+f then f else 17 end not between t1.f and a then b else t1.a end FROM t1 WHERE not exists(select 1 from t1 where a in (select coalesce((select max(13) from t1 where t1.e not in (t1.d,case when t1.b not in ((select (count(distinct case when  -t1.a not between a and t1.f then t1.c when 13 not in (t1.a,t1.b,d) then f else 19 end)) from t1),b,t1.f) then c when 11 in (select min(a)+max(19) from t1 union select cast(avg(11) AS integer) from t1) and t1.c in (f,13,t1.e) or a>17 then c else a end | t1.b,a) or not (t1.d<11)),d) from t1 union select t1.a from t1) and f in (select b from t1 union select b from t1))}
} {100}
do_test randexpr-2.1461 {
  db eval {SELECT case when not case 11 when t1.e*coalesce((select max(t1.b) from t1 where (abs(t1.c)/abs(~11)) not between coalesce((select max((abs(a)/abs(c))) from t1 where t1.b>=t1.a or b= -e),t1.f) and e and c not in (t1.a,t1.f,t1.c) and not (a)<t1.b or t1.b not between b and t1.a),17)*11+b+f then f else 17 end not between t1.f and a then b else t1.a end FROM t1 WHERE NOT (not exists(select 1 from t1 where a in (select coalesce((select max(13) from t1 where t1.e not in (t1.d,case when t1.b not in ((select (count(distinct case when  -t1.a not between a and t1.f then t1.c when 13 not in (t1.a,t1.b,d) then f else 19 end)) from t1),b,t1.f) then c when 11 in (select min(a)+max(19) from t1 union select cast(avg(11) AS integer) from t1) and t1.c in (f,13,t1.e) or a>17 then c else a end | t1.b,a) or not (t1.d<11)),d) from t1 union select t1.a from t1) and f in (select b from t1 union select b from t1)))}
} {}
do_test randexpr-2.1462 {
  db eval {SELECT case when case when coalesce((select max(case when ((a<=case t1.a+t1.a when t1.d then  -c else b end or t1.b<>e)) then 17 else 19*19*a end*13) from t1 where d<>t1.d),d)<=a or 11<=t1.e then t1.c when 17<11 then 17 else e end<=t1.a then t1.d when e= -e then t1.d else 19 end FROM t1 WHERE t1.e<=t1.a or (abs(+a+coalesce((select max(t1.b) from t1 where (select ~count(distinct 17) from t1)-b in (select t1.b+t1.b from t1 union select 19 from t1)), -11))/abs(case when not exists(select 1 from t1 where t1.d not between 17 and c- -c+e) or t1.e>t1.f then t1.d when t1.d not in (17,e,d) then a else 17 end)) in (c,d,11)}
} {}
do_test randexpr-2.1463 {
  db eval {SELECT case when case when coalesce((select max(case when ((a<=case t1.a+t1.a when t1.d then  -c else b end or t1.b<>e)) then 17 else 19*19*a end*13) from t1 where d<>t1.d),d)<=a or 11<=t1.e then t1.c when 17<11 then 17 else e end<=t1.a then t1.d when e= -e then t1.d else 19 end FROM t1 WHERE NOT (t1.e<=t1.a or (abs(+a+coalesce((select max(t1.b) from t1 where (select ~count(distinct 17) from t1)-b in (select t1.b+t1.b from t1 union select 19 from t1)), -11))/abs(case when not exists(select 1 from t1 where t1.d not between 17 and c- -c+e) or t1.e>t1.f then t1.d when t1.d not in (17,e,d) then a else 17 end)) in (c,d,11))}
} {19}
do_test randexpr-2.1464 {
  db eval {SELECT ~case when t1.e<=t1.a then b else (11) end+(select  -((cast(avg(coalesce((select a from t1 where (select cast(avg(t1.d) AS integer) | case case min((t1.e)) when cast(avg(t1.b) AS integer) then max(t1.c) else max(19) end*count(*) when  -count(distinct e) then count(*) else max( - -17) end from t1) not between c and  -t1.e-f+f),11)-11) AS integer)))*max(e) from t1)+e* - -a-t1.d*e FROM t1 WHERE coalesce((select max(case when 11 between d and d then e | b else case (select (case count(distinct coalesce((select  -coalesce((select max(t1.f) from t1 where t1.b in (select 11 from t1 union select 19 from t1)),t1.e) from t1 where 13<>17),17)) when (max( -t1.e)) then max(17)+max(11) else ((count(*))) end)*(count(*)) from t1) when 11 then  -13+19 else t1.e end end) from t1 where ((t1.a not between d and  -t1.c))),t1.a)<11}
} {}
do_test randexpr-2.1465 {
  db eval {SELECT ~case when t1.e<=t1.a then b else (11) end+(select  -((cast(avg(coalesce((select a from t1 where (select cast(avg(t1.d) AS integer) | case case min((t1.e)) when cast(avg(t1.b) AS integer) then max(t1.c) else max(19) end*count(*) when  -count(distinct e) then count(*) else max( - -17) end from t1) not between c and  -t1.e-f+f),11)-11) AS integer)))*max(e) from t1)+e* - -a-t1.d*e FROM t1 WHERE NOT (coalesce((select max(case when 11 between d and d then e | b else case (select (case count(distinct coalesce((select  -coalesce((select max(t1.f) from t1 where t1.b in (select 11 from t1 union select 19 from t1)),t1.e) from t1 where 13<>17),17)) when (max( -t1.e)) then max(17)+max(11) else ((count(*))) end)*(count(*)) from t1) when 11 then  -13+19 else t1.e end end) from t1 where ((t1.a not between d and  -t1.c))),t1.a)<11)}
} {-194512}
do_test randexpr-2.1466 {
  db eval {SELECT ~case when t1.e<=t1.a then b else (11) end+(select  -((cast(avg(coalesce((select a from t1 where (select cast(avg(t1.d) AS integer) & case case min((t1.e)) when cast(avg(t1.b) AS integer) then max(t1.c) else max(19) end*count(*) when  -count(distinct e) then count(*) else max( - -17) end from t1) not between c and  -t1.e-f+f),11)-11) AS integer)))*max(e) from t1)+e* - -a-t1.d*e FROM t1 WHERE NOT (coalesce((select max(case when 11 between d and d then e | b else case (select (case count(distinct coalesce((select  -coalesce((select max(t1.f) from t1 where t1.b in (select 11 from t1 union select 19 from t1)),t1.e) from t1 where 13<>17),17)) when (max( -t1.e)) then max(17)+max(11) else ((count(*))) end)*(count(*)) from t1) when 11 then  -13+19 else t1.e end end) from t1 where ((t1.a not between d and  -t1.c))),t1.a)<11)}
} {-194512}
do_test randexpr-2.1467 {
  db eval {SELECT t1.e*~13-t1.a-~case when (abs(t1.a)/abs(coalesce((select max(t1.a) from t1 where e not between f and e-t1.b+13),case when (a in (select ( -c) from t1 union select 11 from t1) or exists(select 1 from t1 where 11 between f and t1.f)) then t1.b-a else  -t1.e end)+13*t1.f)) | 13<t1.a then t1.f when (t1.a in (select 19 from t1 union select c from t1)) then a else  -19 end FROM t1 WHERE exists(select 1 from t1 where t1.c*coalesce((select f from t1 where  - -f+b-(select min(t1.b) from t1) not in (c,17-t1.b*t1.a,t1.c)),case when (select abs(count(*)) from t1)<> -19-a then (a)-coalesce((select max(case when a in (13,t1.b,11) then t1.b else (13) end) from t1 where not exists(select 1 from t1 where t1.b>=b)),t1.c) else  -13 end)*(a)<17)}
} {}
do_test randexpr-2.1468 {
  db eval {SELECT t1.e*~13-t1.a-~case when (abs(t1.a)/abs(coalesce((select max(t1.a) from t1 where e not between f and e-t1.b+13),case when (a in (select ( -c) from t1 union select 11 from t1) or exists(select 1 from t1 where 11 between f and t1.f)) then t1.b-a else  -t1.e end)+13*t1.f)) | 13<t1.a then t1.f when (t1.a in (select 19 from t1 union select c from t1)) then a else  -19 end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.c*coalesce((select f from t1 where  - -f+b-(select min(t1.b) from t1) not in (c,17-t1.b*t1.a,t1.c)),case when (select abs(count(*)) from t1)<> -19-a then (a)-coalesce((select max(case when a in (13,t1.b,11) then t1.b else (13) end) from t1 where not exists(select 1 from t1 where t1.b>=b)),t1.c) else  -13 end)*(a)<17))}
} {-6499}
do_test randexpr-2.1469 {
  db eval {SELECT t1.e*~13-t1.a-~case when (abs(t1.a)/abs(coalesce((select max(t1.a) from t1 where e not between f and e-t1.b+13),case when (a in (select ( -c) from t1 union select 11 from t1) or exists(select 1 from t1 where 11 between f and t1.f)) then t1.b-a else  -t1.e end)+13*t1.f)) & 13<t1.a then t1.f when (t1.a in (select 19 from t1 union select c from t1)) then a else  -19 end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.c*coalesce((select f from t1 where  - -f+b-(select min(t1.b) from t1) not in (c,17-t1.b*t1.a,t1.c)),case when (select abs(count(*)) from t1)<> -19-a then (a)-coalesce((select max(case when a in (13,t1.b,11) then t1.b else (13) end) from t1 where not exists(select 1 from t1 where t1.b>=b)),t1.c) else  -13 end)*(a)<17))}
} {-6499}
do_test randexpr-2.1470 {
  db eval {SELECT coalesce((select max(f*b | case when f in (t1.b,t1.b*(select count(*) from t1)+(select  -count(*) from t1), -b) and +13<(abs( -~d-case when t1.a in (select  -f from t1 union select t1.c from t1) then (t1.a) when t1.a<e then t1.d else a end)/abs(t1.c)) then t1.b*19 else e end+t1.c | t1.d) from t1 where 13 not in (t1.e,13,c)),11)-11 FROM t1 WHERE b not between e-case when case 11 when t1.a then t1.e*17 else t1.c end in (select ~t1.a | b+(abs(f)/abs(case coalesce((select (select abs( -cast(avg(17) AS integer)) from t1) from t1 where not f=t1.b or 11>=a),coalesce((select 11 from t1 where 11 not between 19 and t1.c),t1.a))-19 when t1.e then t1.f else e end)) from t1 union select  -d from t1) then d when t1.f between 17 and d then t1.d else t1.d end and (f) or d<17}
} {}
do_test randexpr-2.1471 {
  db eval {SELECT coalesce((select max(f*b | case when f in (t1.b,t1.b*(select count(*) from t1)+(select  -count(*) from t1), -b) and +13<(abs( -~d-case when t1.a in (select  -f from t1 union select t1.c from t1) then (t1.a) when t1.a<e then t1.d else a end)/abs(t1.c)) then t1.b*19 else e end+t1.c | t1.d) from t1 where 13 not in (t1.e,13,c)),11)-11 FROM t1 WHERE NOT (b not between e-case when case 11 when t1.a then t1.e*17 else t1.c end in (select ~t1.a | b+(abs(f)/abs(case coalesce((select (select abs( -cast(avg(17) AS integer)) from t1) from t1 where not f=t1.b or 11>=a),coalesce((select 11 from t1 where 11 not between 19 and t1.c),t1.a))-19 when t1.e then t1.f else e end)) from t1 union select  -d from t1) then d when t1.f between 17 and d then t1.d else t1.d end and (f) or d<17)}
} {0}
do_test randexpr-2.1472 {
  db eval {SELECT coalesce((select max(f*b & case when f in (t1.b,t1.b*(select count(*) from t1)+(select  -count(*) from t1), -b) and +13<(abs( -~d-case when t1.a in (select  -f from t1 union select t1.c from t1) then (t1.a) when t1.a<e then t1.d else a end)/abs(t1.c)) then t1.b*19 else e end+t1.c & t1.d) from t1 where 13 not in (t1.e,13,c)),11)-11 FROM t1 WHERE NOT (b not between e-case when case 11 when t1.a then t1.e*17 else t1.c end in (select ~t1.a | b+(abs(f)/abs(case coalesce((select (select abs( -cast(avg(17) AS integer)) from t1) from t1 where not f=t1.b or 11>=a),coalesce((select 11 from t1 where 11 not between 19 and t1.c),t1.a))-19 when t1.e then t1.f else e end)) from t1 union select  -d from t1) then d when t1.f between 17 and d then t1.d else t1.d end and (f) or d<17)}
} {0}
do_test randexpr-2.1473 {
  db eval {SELECT case when (t1.b+case when a in (select coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where 11=case e when (e) then t1.b else t1.c end or c in (t1.f,f,11))),t1.f) from t1 union select t1.d from t1) and t1.e<>e then t1.f when t1.a in (t1.d,a,13) then 17 else t1.d end not in (t1.f,t1.d,17)) or c<> -19 then b when f<t1.c and t1.b in (e,11,t1.f) then t1.b-t1.c else  - -d end FROM t1 WHERE t1.f- -t1.d in (select case a when 13+coalesce((select coalesce((select coalesce((select case when b>a-e then b else 19 end from t1 where 11<>t1.b),a) from t1 where not 19 in (select max(19)*count(distinct a) from t1 union select cast(avg(11) AS integer) from t1)),11) from t1 where t1.e<>a),17) then d else 19 end from t1 union select f from t1) and c in (select count(distinct c) from t1 union select  -+max(d) | abs(count(*)) from t1)}
} {}
do_test randexpr-2.1474 {
  db eval {SELECT case when (t1.b+case when a in (select coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where 11=case e when (e) then t1.b else t1.c end or c in (t1.f,f,11))),t1.f) from t1 union select t1.d from t1) and t1.e<>e then t1.f when t1.a in (t1.d,a,13) then 17 else t1.d end not in (t1.f,t1.d,17)) or c<> -19 then b when f<t1.c and t1.b in (e,11,t1.f) then t1.b-t1.c else  - -d end FROM t1 WHERE NOT (t1.f- -t1.d in (select case a when 13+coalesce((select coalesce((select coalesce((select case when b>a-e then b else 19 end from t1 where 11<>t1.b),a) from t1 where not 19 in (select max(19)*count(distinct a) from t1 union select cast(avg(11) AS integer) from t1)),11) from t1 where t1.e<>a),17) then d else 19 end from t1 union select f from t1) and c in (select count(distinct c) from t1 union select  -+max(d) | abs(count(*)) from t1))}
} {200}
do_test randexpr-2.1475 {
  db eval {SELECT 17+coalesce((select max(19) from t1 where  -(select max(t1.d) from t1)>coalesce((select max((13)) from t1 where (coalesce((select 11 from t1 where  -e-t1.d-b-(abs(t1.b)/abs(11))*t1.f*b-e not between (f) and t1.e or 11 in (t1.b,t1.e, -e)),t1.a) in (select t1.b from t1 union select 19 from t1)) and exists(select 1 from t1 where 13<19)),t1.e)),e) FROM t1 WHERE t1.a<>t1.d or not exists(select 1 from t1 where t1.a>=coalesce((select case t1.e*d when  -case d*11 when t1.f then t1.e else t1.c end then 13*coalesce((select max(f*b*t1.e*t1.c) from t1 where t1.d in (select t1.c from t1 union select f from t1) or ((t1.e<f or t1.e=t1.b))),t1.d) | t1.b else d end from t1 where t1.f between t1.c and a),(13)))}
} {517}
do_test randexpr-2.1476 {
  db eval {SELECT 17+coalesce((select max(19) from t1 where  -(select max(t1.d) from t1)>coalesce((select max((13)) from t1 where (coalesce((select 11 from t1 where  -e-t1.d-b-(abs(t1.b)/abs(11))*t1.f*b-e not between (f) and t1.e or 11 in (t1.b,t1.e, -e)),t1.a) in (select t1.b from t1 union select 19 from t1)) and exists(select 1 from t1 where 13<19)),t1.e)),e) FROM t1 WHERE NOT (t1.a<>t1.d or not exists(select 1 from t1 where t1.a>=coalesce((select case t1.e*d when  -case d*11 when t1.f then t1.e else t1.c end then 13*coalesce((select max(f*b*t1.e*t1.c) from t1 where t1.d in (select t1.c from t1 union select f from t1) or ((t1.e<f or t1.e=t1.b))),t1.d) | t1.b else d end from t1 where t1.f between t1.c and a),(13))))}
} {}
do_test randexpr-2.1477 {
  db eval {SELECT case +a when (coalesce((select d*f*t1.d from t1 where t1.f between (case when e* -13<~ - -t1.e then e when 13>=t1.a then f-coalesce((select  -(select max((select min(a)-count(distinct c) from t1)) from t1) from t1 where a between f and d),c) else d end) and c or not exists(select 1 from t1 where 11<=13)),f)) then (e) else t1.b end FROM t1 WHERE not  -c between  -d+f | 17+t1.a and 11 or 11*e=(+case when c>=d then coalesce((select max(d-t1.f*f) from t1 where 11 in (select count(distinct t1.e) from t1 union select (~case count(*) when  -max(t1.f) then count(distinct t1.d) else (cast(avg(t1.f) AS integer)) end) from t1)),t1.c) else d end+t1.b-t1.c+b)+t1.c- -(13)}
} {200}
do_test randexpr-2.1478 {
  db eval {SELECT case +a when (coalesce((select d*f*t1.d from t1 where t1.f between (case when e* -13<~ - -t1.e then e when 13>=t1.a then f-coalesce((select  -(select max((select min(a)-count(distinct c) from t1)) from t1) from t1 where a between f and d),c) else d end) and c or not exists(select 1 from t1 where 11<=13)),f)) then (e) else t1.b end FROM t1 WHERE NOT (not  -c between  -d+f | 17+t1.a and 11 or 11*e=(+case when c>=d then coalesce((select max(d-t1.f*f) from t1 where 11 in (select count(distinct t1.e) from t1 union select (~case count(*) when  -max(t1.f) then count(distinct t1.d) else (cast(avg(t1.f) AS integer)) end) from t1)),t1.c) else d end+t1.b-t1.c+b)+t1.c- -(13))}
} {}
do_test randexpr-2.1479 {
  db eval {SELECT case when case when not exists(select 1 from t1 where a between +d-case when t1.c+e not between case 11 when +t1.b+11 then 19 else  -t1.f end+(11) and d and exists(select 1 from t1 where (a)>b) and not exists(select 1 from t1 where 11 in (a,11,t1.c)) then 19 else t1.a end and t1.a) then 17 when t1.d<>e then (t1.a) else e end-a<=e then c else 11 end FROM t1 WHERE coalesce((select a from t1 where not exists(select 1 from t1 where  -t1.c not between b and t1.a)),case when t1.d<=19-13 then coalesce((select max((select count(*)*cast(avg(~t1.a-e*~17+t1.e) AS integer) from t1)) from t1 where (exists(select 1 from t1 where + - -e-11*a-t1.d in (11,(t1.b),c)))),19+e)* -b else c end)>=17}
} {300}
do_test randexpr-2.1480 {
  db eval {SELECT case when case when not exists(select 1 from t1 where a between +d-case when t1.c+e not between case 11 when +t1.b+11 then 19 else  -t1.f end+(11) and d and exists(select 1 from t1 where (a)>b) and not exists(select 1 from t1 where 11 in (a,11,t1.c)) then 19 else t1.a end and t1.a) then 17 when t1.d<>e then (t1.a) else e end-a<=e then c else 11 end FROM t1 WHERE NOT (coalesce((select a from t1 where not exists(select 1 from t1 where  -t1.c not between b and t1.a)),case when t1.d<=19-13 then coalesce((select max((select count(*)*cast(avg(~t1.a-e*~17+t1.e) AS integer) from t1)) from t1 where (exists(select 1 from t1 where + - -e-11*a-t1.d in (11,(t1.b),c)))),19+e)* -b else c end)>=17)}
} {}
do_test randexpr-2.1481 {
  db eval {SELECT coalesce((select t1.c-~t1.e*19++case t1.b when coalesce((select 17 from t1 where t1.f not between t1.c-+coalesce((select max(a+ -t1.c) from t1 where (select count(distinct 11) from t1) in (select  -+case when a not between f and b or b>=t1.d then (t1.d) when a in (t1.e,b,13) then t1.d else t1.c end*a from t1 union select t1.f from t1)),f) and 17),a) | 17*c then 19 else d end+t1.c from t1 where e<>t1.b),19) FROM t1 WHERE not (t1.e not between ~17 and +t1.e*(~b)*e)}
} {}
do_test randexpr-2.1482 {
  db eval {SELECT coalesce((select t1.c-~t1.e*19++case t1.b when coalesce((select 17 from t1 where t1.f not between t1.c-+coalesce((select max(a+ -t1.c) from t1 where (select count(distinct 11) from t1) in (select  -+case when a not between f and b or b>=t1.d then (t1.d) when a in (t1.e,b,13) then t1.d else t1.c end*a from t1 union select t1.f from t1)),f) and 17),a) | 17*c then 19 else d end+t1.c from t1 where e<>t1.b),19) FROM t1 WHERE NOT (not (t1.e not between ~17 and +t1.e*(~b)*e))}
} {10519}
do_test randexpr-2.1483 {
  db eval {SELECT coalesce((select t1.c-~t1.e*19++case t1.b when coalesce((select 17 from t1 where t1.f not between t1.c-+coalesce((select max(a+ -t1.c) from t1 where (select count(distinct 11) from t1) in (select  -+case when a not between f and b or b>=t1.d then (t1.d) when a in (t1.e,b,13) then t1.d else t1.c end*a from t1 union select t1.f from t1)),f) and 17),a) & 17*c then 19 else d end+t1.c from t1 where e<>t1.b),19) FROM t1 WHERE NOT (not (t1.e not between ~17 and +t1.e*(~b)*e))}
} {10519}
do_test randexpr-2.1484 {
  db eval {SELECT ~case when b<=(t1.c | (abs(d)/abs(a*f)))+case when (13*(t1.b) not in (19,b,t1.d)) and exists(select 1 from t1 where 19 between t1.d and 11) then (select case count(distinct t1.f) when +( -count(distinct c) | cast(avg(t1.d) AS integer)) then cast(avg(t1.c) AS integer) else min(f) end from t1) else 13 end*t1.c or exists(select 1 from t1 where  -f in (select e from t1 union select  -t1.a from t1)) then t1.d else t1.c end FROM t1 WHERE exists(select 1 from t1 where t1.c+b-t1.d between 11 and 17)}
} {}
do_test randexpr-2.1485 {
  db eval {SELECT ~case when b<=(t1.c | (abs(d)/abs(a*f)))+case when (13*(t1.b) not in (19,b,t1.d)) and exists(select 1 from t1 where 19 between t1.d and 11) then (select case count(distinct t1.f) when +( -count(distinct c) | cast(avg(t1.d) AS integer)) then cast(avg(t1.c) AS integer) else min(f) end from t1) else 13 end*t1.c or exists(select 1 from t1 where  -f in (select e from t1 union select  -t1.a from t1)) then t1.d else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.c+b-t1.d between 11 and 17))}
} {-401}
do_test randexpr-2.1486 {
  db eval {SELECT ~case when b<=(t1.c & (abs(d)/abs(a*f)))+case when (13*(t1.b) not in (19,b,t1.d)) and exists(select 1 from t1 where 19 between t1.d and 11) then (select case count(distinct t1.f) when +( -count(distinct c) & cast(avg(t1.d) AS integer)) then cast(avg(t1.c) AS integer) else min(f) end from t1) else 13 end*t1.c or exists(select 1 from t1 where  -f in (select e from t1 union select  -t1.a from t1)) then t1.d else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.c+b-t1.d between 11 and 17))}
} {-401}
do_test randexpr-2.1487 {
  db eval {SELECT coalesce((select max(~coalesce((select 19+~coalesce((select (abs((19)*c+~t1.a-t1.a*19)/abs(case when t1.d<>t1.b then t1.f when 13<>19 then (11) else t1.c end)) from t1 where f= -t1.a or t1.d not between t1.d and  -f),t1.f) from t1 where not exists(select 1 from t1 where  -19 not between d and f)),d)*t1.a-f) from t1 where c not in (c,c,c)),t1.b) FROM t1 WHERE (coalesce((select max( -t1.d+19+11+coalesce((select a from t1 where 11 not between e and t1.d),t1.d)) from t1 where not ( -t1.f not between b and f) and t1.e in (b,11,f)),f)+t1.e<=19) or c>t1.d or e in (a,19,11) or t1.f>b or  -t1.f<=13 and a between 11 and t1.a}
} {200}
do_test randexpr-2.1488 {
  db eval {SELECT coalesce((select max(~coalesce((select 19+~coalesce((select (abs((19)*c+~t1.a-t1.a*19)/abs(case when t1.d<>t1.b then t1.f when 13<>19 then (11) else t1.c end)) from t1 where f= -t1.a or t1.d not between t1.d and  -f),t1.f) from t1 where not exists(select 1 from t1 where  -19 not between d and f)),d)*t1.a-f) from t1 where c not in (c,c,c)),t1.b) FROM t1 WHERE NOT ((coalesce((select max( -t1.d+19+11+coalesce((select a from t1 where 11 not between e and t1.d),t1.d)) from t1 where not ( -t1.f not between b and f) and t1.e in (b,11,f)),f)+t1.e<=19) or c>t1.d or e in (a,19,11) or t1.f>b or  -t1.f<=13 and a between 11 and t1.a)}
} {}
do_test randexpr-2.1489 {
  db eval {SELECT case t1.d when 17 then 11 | t1.a-17+13+t1.f*t1.e+t1.e-case when d | t1.e in (t1.b,t1.a,c) then  -13 else (b*19) end-(select cast(avg(coalesce((select a from t1 where e in (t1.f,t1.b,f)), -e)) AS integer) from t1)*d-11-t1.e-t1.a else t1.f end FROM t1 WHERE d*13 in (select abs(min(d)) from t1 union select cast(avg(d) AS integer) from t1)}
} {}
do_test randexpr-2.1490 {
  db eval {SELECT case t1.d when 17 then 11 | t1.a-17+13+t1.f*t1.e+t1.e-case when d | t1.e in (t1.b,t1.a,c) then  -13 else (b*19) end-(select cast(avg(coalesce((select a from t1 where e in (t1.f,t1.b,f)), -e)) AS integer) from t1)*d-11-t1.e-t1.a else t1.f end FROM t1 WHERE NOT (d*13 in (select abs(min(d)) from t1 union select cast(avg(d) AS integer) from t1))}
} {600}
do_test randexpr-2.1491 {
  db eval {SELECT case t1.d when 17 then 11 & t1.a-17+13+t1.f*t1.e+t1.e-case when d & t1.e in (t1.b,t1.a,c) then  -13 else (b*19) end-(select cast(avg(coalesce((select a from t1 where e in (t1.f,t1.b,f)), -e)) AS integer) from t1)*d-11-t1.e-t1.a else t1.f end FROM t1 WHERE NOT (d*13 in (select abs(min(d)) from t1 union select cast(avg(d) AS integer) from t1))}
} {600}
do_test randexpr-2.1492 {
  db eval {SELECT coalesce((select max(19-(abs(t1.c)/abs( -13))-(select count(*)*abs(max(t1.a-b)) from t1)-t1.d) from t1 where (case coalesce((select max(~(select ~count(*) from t1)) from t1 where b=(abs(17)/abs(d))),11*case when not t1.c>=e or 17=c then d else 17*b end*t1.d) when 13 then 11 else t1.c end) in (select c from t1 union select t1.c from t1)),13) FROM t1 WHERE case t1.a*(select  -case count(distinct ~(case 13-+t1.d-f when d then c else (19) end)*19)* -max(19) |  -count(*)+abs(min(19)) | cast(avg(d) AS integer) when min(a) then count(distinct 11) else count(*) end from t1)*(abs(t1.a)/abs(11))-f-t1.b+(t1.f) when 11 then 17 else 19 end<>d}
} {-504}
do_test randexpr-2.1493 {
  db eval {SELECT coalesce((select max(19-(abs(t1.c)/abs( -13))-(select count(*)*abs(max(t1.a-b)) from t1)-t1.d) from t1 where (case coalesce((select max(~(select ~count(*) from t1)) from t1 where b=(abs(17)/abs(d))),11*case when not t1.c>=e or 17=c then d else 17*b end*t1.d) when 13 then 11 else t1.c end) in (select c from t1 union select t1.c from t1)),13) FROM t1 WHERE NOT (case t1.a*(select  -case count(distinct ~(case 13-+t1.d-f when d then c else (19) end)*19)* -max(19) |  -count(*)+abs(min(19)) | cast(avg(d) AS integer) when min(a) then count(distinct 11) else count(*) end from t1)*(abs(t1.a)/abs(11))-f-t1.b+(t1.f) when 11 then 17 else 19 end<>d)}
} {}
do_test randexpr-2.1494 {
  db eval {SELECT +(select abs( -abs(count(distinct case when (abs(t1.f)/abs(t1.a-t1.d)) in (select count(distinct 19) from t1 union select +abs(+ -cast(avg(c) AS integer)) from t1) then  -(f) else e end-17)) | case count(distinct b) when count(*) then cast(avg(13) AS integer) else ( -count(distinct d)) end-count(*)* - -cast(avg(a) AS integer)) from t1)+case when t1.f in (select d*b | t1.d from t1 union select d from t1) then t1.f when 19<>t1.e then t1.b else 11 end+11 FROM t1 WHERE f<a+t1.f}
} {212}
do_test randexpr-2.1495 {
  db eval {SELECT +(select abs( -abs(count(distinct case when (abs(t1.f)/abs(t1.a-t1.d)) in (select count(distinct 19) from t1 union select +abs(+ -cast(avg(c) AS integer)) from t1) then  -(f) else e end-17)) | case count(distinct b) when count(*) then cast(avg(13) AS integer) else ( -count(distinct d)) end-count(*)* - -cast(avg(a) AS integer)) from t1)+case when t1.f in (select d*b | t1.d from t1 union select d from t1) then t1.f when 19<>t1.e then t1.b else 11 end+11 FROM t1 WHERE NOT (f<a+t1.f)}
} {}
do_test randexpr-2.1496 {
  db eval {SELECT +(select abs( -abs(count(distinct case when (abs(t1.f)/abs(t1.a-t1.d)) in (select count(distinct 19) from t1 union select +abs(+ -cast(avg(c) AS integer)) from t1) then  -(f) else e end-17)) & case count(distinct b) when count(*) then cast(avg(13) AS integer) else ( -count(distinct d)) end-count(*)* - -cast(avg(a) AS integer)) from t1)+case when t1.f in (select d*b & t1.d from t1 union select d from t1) then t1.f when 19<>t1.e then t1.b else 11 end+11 FROM t1 WHERE f<a+t1.f}
} {298}
do_test randexpr-2.1497 {
  db eval {SELECT case when e in (+(select ~(max(t1.f)-+count(distinct 11)) from t1)*t1.b+t1.c*a*t1.b+e,a,t1.c) and (19)<>17 or 17 between 13 and a and exists(select 1 from t1 where c not between t1.f and t1.d) then coalesce((select max(d) from t1 where t1.e<>19),17) else a end*(( -f))+t1.d FROM t1 WHERE exists(select 1 from t1 where exists(select 1 from t1 where t1.c between case when (a<a and not exists(select 1 from t1 where exists(select 1 from t1 where d<~t1.f-+t1.a or (abs(17)/abs(t1.c)) in (select 19 from t1 union select 11 from t1)))) then +e when d<>13 or b>=e or 19 between t1.d and  -t1.e then t1.f else f end and f) and c>((t1.c))) and not exists(select 1 from t1 where 17<t1.c)}
} {}
do_test randexpr-2.1498 {
  db eval {SELECT case when e in (+(select ~(max(t1.f)-+count(distinct 11)) from t1)*t1.b+t1.c*a*t1.b+e,a,t1.c) and (19)<>17 or 17 between 13 and a and exists(select 1 from t1 where c not between t1.f and t1.d) then coalesce((select max(d) from t1 where t1.e<>19),17) else a end*(( -f))+t1.d FROM t1 WHERE NOT (exists(select 1 from t1 where exists(select 1 from t1 where t1.c between case when (a<a and not exists(select 1 from t1 where exists(select 1 from t1 where d<~t1.f-+t1.a or (abs(17)/abs(t1.c)) in (select 19 from t1 union select 11 from t1)))) then +e when d<>13 or b>=e or 19 between t1.d and  -t1.e then t1.f else f end and f) and c>((t1.c))) and not exists(select 1 from t1 where 17<t1.c))}
} {-239600}
do_test randexpr-2.1499 {
  db eval {SELECT 17+11+d+t1.d | t1.c+(abs(case when 11 in (select count(distinct 11*+t1.d) from t1 union select ~cast(avg(t1.c) AS integer)*case (count(distinct 19)) when (cast(avg(t1.c) AS integer) | min(t1.a-f)) then cast(avg(a) AS integer) else cast(avg(t1.b) AS integer) end+max( - -d) from t1) then t1.a-13 when (11)>=13 then t1.e else t1.c end)/abs(19)) | (t1.d) FROM t1 WHERE d>=(case when ((t1.a)) between t1.f and a then case when 11 between 19-case when (~coalesce((select t1.e from t1 where d>t1.c and e<>t1.f),e))>=13 then t1.b when t1.d in (select (count(*)-min(19)) from t1 union select cast(avg(t1.e) AS integer) from t1) then 17 else (t1.d) end*t1.a and (13) then 11 when not exists(select 1 from t1 where not 19<>(t1.e) and t1.a between d and d and t1.c=a) then 17 else t1.a end-17 else e end)}
} {}
do_test randexpr-2.1500 {
  db eval {SELECT 17+11+d+t1.d | t1.c+(abs(case when 11 in (select count(distinct 11*+t1.d) from t1 union select ~cast(avg(t1.c) AS integer)*case (count(distinct 19)) when (cast(avg(t1.c) AS integer) | min(t1.a-f)) then cast(avg(a) AS integer) else cast(avg(t1.b) AS integer) end+max( - -d) from t1) then t1.a-13 when (11)>=13 then t1.e else t1.c end)/abs(19)) | (t1.d) FROM t1 WHERE NOT (d>=(case when ((t1.a)) between t1.f and a then case when 11 between 19-case when (~coalesce((select t1.e from t1 where d>t1.c and e<>t1.f),e))>=13 then t1.b when t1.d in (select (count(*)-min(19)) from t1 union select cast(avg(t1.e) AS integer) from t1) then 17 else (t1.d) end*t1.a and (13) then 11 when not exists(select 1 from t1 where not 19<>(t1.e) and t1.a between d and d and t1.c=a) then 17 else t1.a end-17 else e end))}
} {959}
do_test randexpr-2.1501 {
  db eval {SELECT 17+11+d+t1.d & t1.c+(abs(case when 11 in (select count(distinct 11*+t1.d) from t1 union select ~cast(avg(t1.c) AS integer)*case (count(distinct 19)) when (cast(avg(t1.c) AS integer) & min(t1.a-f)) then cast(avg(a) AS integer) else cast(avg(t1.b) AS integer) end+max( - -d) from t1) then t1.a-13 when (11)>=13 then t1.e else t1.c end)/abs(19)) & (t1.d) FROM t1 WHERE NOT (d>=(case when ((t1.a)) between t1.f and a then case when 11 between 19-case when (~coalesce((select t1.e from t1 where d>t1.c and e<>t1.f),e))>=13 then t1.b when t1.d in (select (count(*)-min(19)) from t1 union select cast(avg(t1.e) AS integer) from t1) then 17 else (t1.d) end*t1.a and (13) then 11 when not exists(select 1 from t1 where not 19<>(t1.e) and t1.a between d and d and t1.c=a) then 17 else t1.a end-17 else e end))}
} {272}
do_test randexpr-2.1502 {
  db eval {SELECT coalesce((select 17 from t1 where ((abs(19)/abs(case when ((f+17<(d))) and (abs(t1.c)/abs((t1.b)))>11 then ~a+11 when (t1.f)>t1.d then 19 else c end))<>t1.b) or (b in (( -t1.d),b,e) and (t1.a)<>c) and (17) not in (t1.f,11,17) or (f) not between t1.c and  -t1.c),t1.a) FROM t1 WHERE 17 between  -t1.b+f-19 | 17 and t1.e+t1.c}
} {}
do_test randexpr-2.1503 {
  db eval {SELECT coalesce((select 17 from t1 where ((abs(19)/abs(case when ((f+17<(d))) and (abs(t1.c)/abs((t1.b)))>11 then ~a+11 when (t1.f)>t1.d then 19 else c end))<>t1.b) or (b in (( -t1.d),b,e) and (t1.a)<>c) and (17) not in (t1.f,11,17) or (f) not between t1.c and  -t1.c),t1.a) FROM t1 WHERE NOT (17 between  -t1.b+f-19 | 17 and t1.e+t1.c)}
} {17}
do_test randexpr-2.1504 {
  db eval {SELECT +(11)-19-case when 19+13-19+f*19*c not in (coalesce((select max((select ~min(t1.b)+(count(distinct t1.d)) | min(13)*count(distinct t1.a)*max(a) from t1)) from t1 where not 19 in (select t1.d from t1 union select 19 from t1) or 19<=t1.c),t1.b | f) | e-f,d,d) then t1.a else d end FROM t1 WHERE t1.d in (select case when t1.e>(case coalesce((select (11)-t1.e from t1 where case t1.e when t1.c then (coalesce((select max(+t1.b) from t1 where (a in (case when 19 in (select cast(avg((t1.b)) AS integer) from t1 union select cast(avg( - -17) AS integer) from t1) then a when 17>=13 then c else t1.e end,11,11) or not 19 between t1.b and t1.a)),t1.e)) else d end<=t1.c),13) when e then a else d end) then a when 19 in (select (11) from t1 union select t1.e from t1) then (e) else t1.d end from t1 union select t1.d from t1)}
} {-108}
do_test randexpr-2.1505 {
  db eval {SELECT +(11)-19-case when 19+13-19+f*19*c not in (coalesce((select max((select ~min(t1.b)+(count(distinct t1.d)) | min(13)*count(distinct t1.a)*max(a) from t1)) from t1 where not 19 in (select t1.d from t1 union select 19 from t1) or 19<=t1.c),t1.b | f) | e-f,d,d) then t1.a else d end FROM t1 WHERE NOT (t1.d in (select case when t1.e>(case coalesce((select (11)-t1.e from t1 where case t1.e when t1.c then (coalesce((select max(+t1.b) from t1 where (a in (case when 19 in (select cast(avg((t1.b)) AS integer) from t1 union select cast(avg( - -17) AS integer) from t1) then a when 17>=13 then c else t1.e end,11,11) or not 19 between t1.b and t1.a)),t1.e)) else d end<=t1.c),13) when e then a else d end) then a when 19 in (select (11) from t1 union select t1.e from t1) then (e) else t1.d end from t1 union select t1.d from t1))}
} {}
do_test randexpr-2.1506 {
  db eval {SELECT +(11)-19-case when 19+13-19+f*19*c not in (coalesce((select max((select ~min(t1.b)+(count(distinct t1.d)) & min(13)*count(distinct t1.a)*max(a) from t1)) from t1 where not 19 in (select t1.d from t1 union select 19 from t1) or 19<=t1.c),t1.b & f) & e-f,d,d) then t1.a else d end FROM t1 WHERE t1.d in (select case when t1.e>(case coalesce((select (11)-t1.e from t1 where case t1.e when t1.c then (coalesce((select max(+t1.b) from t1 where (a in (case when 19 in (select cast(avg((t1.b)) AS integer) from t1 union select cast(avg( - -17) AS integer) from t1) then a when 17>=13 then c else t1.e end,11,11) or not 19 between t1.b and t1.a)),t1.e)) else d end<=t1.c),13) when e then a else d end) then a when 19 in (select (11) from t1 union select t1.e from t1) then (e) else t1.d end from t1 union select t1.d from t1)}
} {-108}
do_test randexpr-2.1507 {
  db eval {SELECT (abs(case t1.f when (abs((abs( -t1.b+t1.f | case when t1.e-b*19<=17 then 13 when t1.d<>c-coalesce((select max(coalesce((select t1.d from t1 where (not exists(select 1 from t1 where (19)<=a) or 11 between t1.e and f)),d | t1.f)) from t1 where (t1.a between 19 and t1.a)),13) then 19 else f end)/abs(t1.f))-t1.a)/abs(e))+t1.e then t1.b else b end)/abs(19))+t1.a FROM t1 WHERE 17 in (select f*f from t1 union select a+d from t1)}
} {}
do_test randexpr-2.1508 {
  db eval {SELECT (abs(case t1.f when (abs((abs( -t1.b+t1.f | case when t1.e-b*19<=17 then 13 when t1.d<>c-coalesce((select max(coalesce((select t1.d from t1 where (not exists(select 1 from t1 where (19)<=a) or 11 between t1.e and f)),d | t1.f)) from t1 where (t1.a between 19 and t1.a)),13) then 19 else f end)/abs(t1.f))-t1.a)/abs(e))+t1.e then t1.b else b end)/abs(19))+t1.a FROM t1 WHERE NOT (17 in (select f*f from t1 union select a+d from t1))}
} {110}
do_test randexpr-2.1509 {
  db eval {SELECT (abs(case t1.f when (abs((abs( -t1.b+t1.f & case when t1.e-b*19<=17 then 13 when t1.d<>c-coalesce((select max(coalesce((select t1.d from t1 where (not exists(select 1 from t1 where (19)<=a) or 11 between t1.e and f)),d & t1.f)) from t1 where (t1.a between 19 and t1.a)),13) then 19 else f end)/abs(t1.f))-t1.a)/abs(e))+t1.e then t1.b else b end)/abs(19))+t1.a FROM t1 WHERE NOT (17 in (select f*f from t1 union select a+d from t1))}
} {110}
do_test randexpr-2.1510 {
  db eval {SELECT (coalesce((select t1.e from t1 where +case when t1.c+f<>d-17 then t1.a when not (abs(t1.c)/abs(case case  -f when f then a else t1.b end-t1.e-t1.f when t1.b then  -e else t1.c end))>e or t1.b=a or exists(select 1 from t1 where 19>=t1.b) and t1.c< -e then t1.e else 13 end<=t1.b),b)) | d FROM t1 WHERE case 13 when 13 then 17-f else a end=e and (exists(select 1 from t1 where b in (select t1.f from t1 union select coalesce((select case when (abs(t1.c)/abs(17)) in (a,f*c,11) then c when ( -t1.d) in (select ~count(distinct t1.b) from t1 union select min((t1.c)) from t1) then t1.a else t1.e end from t1 where exists(select 1 from t1 where (t1.f) in (t1.d,17, -11))),b)-d*11*c+a from t1)))}
} {}
do_test randexpr-2.1511 {
  db eval {SELECT (coalesce((select t1.e from t1 where +case when t1.c+f<>d-17 then t1.a when not (abs(t1.c)/abs(case case  -f when f then a else t1.b end-t1.e-t1.f when t1.b then  -e else t1.c end))>e or t1.b=a or exists(select 1 from t1 where 19>=t1.b) and t1.c< -e then t1.e else 13 end<=t1.b),b)) | d FROM t1 WHERE NOT (case 13 when 13 then 17-f else a end=e and (exists(select 1 from t1 where b in (select t1.f from t1 union select coalesce((select case when (abs(t1.c)/abs(17)) in (a,f*c,11) then c when ( -t1.d) in (select ~count(distinct t1.b) from t1 union select min((t1.c)) from t1) then t1.a else t1.e end from t1 where exists(select 1 from t1 where (t1.f) in (t1.d,17, -11))),b)-d*11*c+a from t1))))}
} {500}
do_test randexpr-2.1512 {
  db eval {SELECT (coalesce((select t1.e from t1 where +case when t1.c+f<>d-17 then t1.a when not (abs(t1.c)/abs(case case  -f when f then a else t1.b end-t1.e-t1.f when t1.b then  -e else t1.c end))>e or t1.b=a or exists(select 1 from t1 where 19>=t1.b) and t1.c< -e then t1.e else 13 end<=t1.b),b)) & d FROM t1 WHERE NOT (case 13 when 13 then 17-f else a end=e and (exists(select 1 from t1 where b in (select t1.f from t1 union select coalesce((select case when (abs(t1.c)/abs(17)) in (a,f*c,11) then c when ( -t1.d) in (select ~count(distinct t1.b) from t1 union select min((t1.c)) from t1) then t1.a else t1.e end from t1 where exists(select 1 from t1 where (t1.f) in (t1.d,17, -11))),b)-d*11*c+a from t1))))}
} {400}
do_test randexpr-2.1513 {
  db eval {SELECT (abs( -case when exists(select 1 from t1 where (abs(e++11-(abs(c)/abs(t1.f)))/abs(19+t1.b))+t1.b-c=(b)) or d in (~d, -f,c) then (select min(13) from t1)+11+~t1.a*t1.a else d end-t1.d)/abs((select (max(d))+count(*)-min(t1.c) from t1))) FROM t1 WHERE (select +min(c+d) | (max(13)+min(case when t1.e not in (t1.d,t1.d,19*t1.d) then t1.a when 17=d then t1.b else a end)+ - -max(t1.a)*count(distinct f) | count(*)+max(t1.d) | count(distinct d))-count(distinct 17)-count(*) from t1) not in (e,d+11,(t1.a+t1.f))}
} {7}
do_test randexpr-2.1514 {
  db eval {SELECT (abs( -case when exists(select 1 from t1 where (abs(e++11-(abs(c)/abs(t1.f)))/abs(19+t1.b))+t1.b-c=(b)) or d in (~d, -f,c) then (select min(13) from t1)+11+~t1.a*t1.a else d end-t1.d)/abs((select (max(d))+count(*)-min(t1.c) from t1))) FROM t1 WHERE NOT ((select +min(c+d) | (max(13)+min(case when t1.e not in (t1.d,t1.d,19*t1.d) then t1.a when 17=d then t1.b else a end)+ - -max(t1.a)*count(distinct f) | count(*)+max(t1.d) | count(distinct d))-count(distinct 17)-count(*) from t1) not in (e,d+11,(t1.a+t1.f)))}
} {}
do_test randexpr-2.1515 {
  db eval {SELECT case when not exists(select 1 from t1 where (not case t1.b when d then c else coalesce((select max(b+case c+c when t1.c then coalesce((select ((e)) from t1 where c in (e,t1.f,t1.d)),t1.a) else t1.f end+t1.e) from t1 where not t1.e not between t1.f and t1.a),19) end+f<>b)) then e when f in (19,t1.d, -c) then 19 else case when e>=t1.f then 19 else 19 end end FROM t1 WHERE 19 between e+case when d>(select ~max(t1.d)+max(t1.d*t1.c)-~count(distinct c)-count(*)-count(distinct t1.b)* -(count(*)) from t1) then ~a when not exists(select 1 from t1 where t1.c>=13) or (t1.f=t1.a or c in ((f), -c,t1.e)) and b=b and e not between t1.b and  -11 or t1.c in (t1.c,17,t1.c) and t1.f=t1.d then t1.a*t1.d*t1.c else d end and e}
} {}
do_test randexpr-2.1516 {
  db eval {SELECT case when not exists(select 1 from t1 where (not case t1.b when d then c else coalesce((select max(b+case c+c when t1.c then coalesce((select ((e)) from t1 where c in (e,t1.f,t1.d)),t1.a) else t1.f end+t1.e) from t1 where not t1.e not between t1.f and t1.a),19) end+f<>b)) then e when f in (19,t1.d, -c) then 19 else case when e>=t1.f then 19 else 19 end end FROM t1 WHERE NOT (19 between e+case when d>(select ~max(t1.d)+max(t1.d*t1.c)-~count(distinct c)-count(*)-count(distinct t1.b)* -(count(*)) from t1) then ~a when not exists(select 1 from t1 where t1.c>=13) or (t1.f=t1.a or c in ((f), -c,t1.e)) and b=b and e not between t1.b and  -11 or t1.c in (t1.c,17,t1.c) and t1.f=t1.d then t1.a*t1.d*t1.c else d end and e)}
} {500}
do_test randexpr-2.1517 {
  db eval {SELECT (select  -+case  -(case  -max(d) when ~+ -+(count(*)) then abs(max(case 17+t1.a-11-t1.c when 19 then f else e end*((t1.c))+b)) else (min(d)*count(distinct t1.e)) end)++abs(count(*))- -cast(avg(c) AS integer)+max(d) when count(distinct c) then min(f) else (count(distinct a)) end from t1) FROM t1 WHERE ((case  -a when case when f between 11 and t1.d then d else c+17 end then b else a end+11-c between  -a and t1.a) or b>t1.f and t1.a<t1.e and (t1.d)<=b or 19 in (select f from t1 union select e from t1) and t1.f not between 19 and 11 or t1.b not in (t1.e,t1.e,11))}
} {-1}
do_test randexpr-2.1518 {
  db eval {SELECT (select  -+case  -(case  -max(d) when ~+ -+(count(*)) then abs(max(case 17+t1.a-11-t1.c when 19 then f else e end*((t1.c))+b)) else (min(d)*count(distinct t1.e)) end)++abs(count(*))- -cast(avg(c) AS integer)+max(d) when count(distinct c) then min(f) else (count(distinct a)) end from t1) FROM t1 WHERE NOT (((case  -a when case when f between 11 and t1.d then d else c+17 end then b else a end+11-c between  -a and t1.a) or b>t1.f and t1.a<t1.e and (t1.d)<=b or 19 in (select f from t1 union select e from t1) and t1.f not between 19 and 11 or t1.b not in (t1.e,t1.e,11)))}
} {}
do_test randexpr-2.1519 {
  db eval {SELECT  -coalesce((select max((select case +count(*)+(case min((abs(d)/abs(b))) when +count(*) | (min(b)) then  -min((t1.a)) else max( -t1.a) end*max( -t1.e))+max(f) when (count(*)) then count(distinct 17) else cast(avg((t1.c)) AS integer) end from t1)) from t1 where t1.d in (select 13 from t1 union select t1.c from t1)),(abs(case when ((c>=f) or f in (t1.a,(t1.a),a)) then  -~c-d else t1.e end)/abs(13))) FROM t1 WHERE (select (+~max(case when t1.e>=coalesce((select max(t1.d) from t1 where +f not in (coalesce((select 11 from t1 where 13 | c in (select c from t1 union select b from t1)),f),t1.c, -a)),13) then e else 19 end)-min(t1.a)) from t1)+((coalesce((select t1.e from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.c=t1.a))),a)))+13 in (select d from t1 union select t1.a from t1) and e>=b}
} {}
do_test randexpr-2.1520 {
  db eval {SELECT  -coalesce((select max((select case +count(*)+(case min((abs(d)/abs(b))) when +count(*) | (min(b)) then  -min((t1.a)) else max( -t1.a) end*max( -t1.e))+max(f) when (count(*)) then count(distinct 17) else cast(avg((t1.c)) AS integer) end from t1)) from t1 where t1.d in (select 13 from t1 union select t1.c from t1)),(abs(case when ((c>=f) or f in (t1.a,(t1.a),a)) then  -~c-d else t1.e end)/abs(13))) FROM t1 WHERE NOT ((select (+~max(case when t1.e>=coalesce((select max(t1.d) from t1 where +f not in (coalesce((select 11 from t1 where 13 | c in (select c from t1 union select b from t1)),f),t1.c, -a)),13) then e else 19 end)-min(t1.a)) from t1)+((coalesce((select t1.e from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.c=t1.a))),a)))+13 in (select d from t1 union select t1.a from t1) and e>=b)}
} {-38}
do_test randexpr-2.1521 {
  db eval {SELECT  -coalesce((select max((select case +count(*)+(case min((abs(d)/abs(b))) when +count(*) & (min(b)) then  -min((t1.a)) else max( -t1.a) end*max( -t1.e))+max(f) when (count(*)) then count(distinct 17) else cast(avg((t1.c)) AS integer) end from t1)) from t1 where t1.d in (select 13 from t1 union select t1.c from t1)),(abs(case when ((c>=f) or f in (t1.a,(t1.a),a)) then  -~c-d else t1.e end)/abs(13))) FROM t1 WHERE NOT ((select (+~max(case when t1.e>=coalesce((select max(t1.d) from t1 where +f not in (coalesce((select 11 from t1 where 13 | c in (select c from t1 union select b from t1)),f),t1.c, -a)),13) then e else 19 end)-min(t1.a)) from t1)+((coalesce((select t1.e from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.c=t1.a))),a)))+13 in (select d from t1 union select t1.a from t1) and e>=b)}
} {-38}
do_test randexpr-2.1522 {
  db eval {SELECT +(select +abs(+cast(avg(t1.b) AS integer)*abs(case  -max( -(t1.a*t1.f)+t1.e* -t1.f*13 | 17 | f+t1.c) when abs(cast(avg(d) AS integer))-(++~min(t1.f) | count(*)-cast(avg(f) AS integer)) then count(*) else cast(avg(13) AS integer) end+ -min(b)))+min(a) from t1) FROM t1 WHERE case t1.a-t1.e*+t1.f-(select abs(count(*)) from t1)+coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where ~t1.b in (select +count(*) | count(distinct case b when t1.a then f else case when (t1.d-t1.b)<11 then t1.d else f end end) from t1 union select +cast(avg(( -d)) AS integer) from t1))),t1.d*t1.a) | e when t1.f then (t1.d) else t1.f end not in (d,f,e)}
} {}
do_test randexpr-2.1523 {
  db eval {SELECT +(select +abs(+cast(avg(t1.b) AS integer)*abs(case  -max( -(t1.a*t1.f)+t1.e* -t1.f*13 | 17 | f+t1.c) when abs(cast(avg(d) AS integer))-(++~min(t1.f) | count(*)-cast(avg(f) AS integer)) then count(*) else cast(avg(13) AS integer) end+ -min(b)))+min(a) from t1) FROM t1 WHERE NOT (case t1.a-t1.e*+t1.f-(select abs(count(*)) from t1)+coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where ~t1.b in (select +count(*) | count(distinct case b when t1.a then f else case when (t1.d-t1.b)<11 then t1.d else f end end) from t1 union select +cast(avg(( -d)) AS integer) from t1))),t1.d*t1.a) | e when t1.f then (t1.d) else t1.f end not in (d,f,e))}
} {37500}
do_test randexpr-2.1524 {
  db eval {SELECT +(select +abs(+cast(avg(t1.b) AS integer)*abs(case  -max( -(t1.a*t1.f)+t1.e* -t1.f*13 & 17 & f+t1.c) when abs(cast(avg(d) AS integer))-(++~min(t1.f) & count(*)-cast(avg(f) AS integer)) then count(*) else cast(avg(13) AS integer) end+ -min(b)))+min(a) from t1) FROM t1 WHERE NOT (case t1.a-t1.e*+t1.f-(select abs(count(*)) from t1)+coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where ~t1.b in (select +count(*) | count(distinct case b when t1.a then f else case when (t1.d-t1.b)<11 then t1.d else f end end) from t1 union select +cast(avg(( -d)) AS integer) from t1))),t1.d*t1.a) | e when t1.f then (t1.d) else t1.f end not in (d,f,e))}
} {37500}
do_test randexpr-2.1525 {
  db eval {SELECT t1.d+case when coalesce((select b from t1 where case when (select max(t1.a*(select case count(distinct c) when max(17+c) then  - -max(d)-count(*) else cast(avg((e)) AS integer) end from t1)) from t1) not between t1.d and t1.d then t1.d when t1.c not between c and t1.f then ( -t1.d) else t1.d end not between e and t1.e),d)<>17 then (t1.f) when 11=t1.c then 11 else t1.f end*c*t1.a-c FROM t1 WHERE (case when coalesce((select ~coalesce((select max(a) from t1 where 11 in (select ~case  -count(*) when cast(avg(d) AS integer) then  -max(t1.f) else (count(distinct 11)) end+cast(avg( - -13) AS integer) | count(*)-min(f) from t1 union select count(*) from t1)),t1.b*t1.f*17) from t1 where not exists(select 1 from t1 where t1.a not between d and 11)),b)-17*t1.d+t1.a in ( -t1.c,t1.e,11) then b else t1.d end in (select 17 from t1 union select 13 from t1)) and  -t1.a in (select (d) from t1 union select t1.b from t1)}
} {}
do_test randexpr-2.1526 {
  db eval {SELECT t1.d+case when coalesce((select b from t1 where case when (select max(t1.a*(select case count(distinct c) when max(17+c) then  - -max(d)-count(*) else cast(avg((e)) AS integer) end from t1)) from t1) not between t1.d and t1.d then t1.d when t1.c not between c and t1.f then ( -t1.d) else t1.d end not between e and t1.e),d)<>17 then (t1.f) when 11=t1.c then 11 else t1.f end*c*t1.a-c FROM t1 WHERE NOT ((case when coalesce((select ~coalesce((select max(a) from t1 where 11 in (select ~case  -count(*) when cast(avg(d) AS integer) then  -max(t1.f) else (count(distinct 11)) end+cast(avg( - -13) AS integer) | count(*)-min(f) from t1 union select count(*) from t1)),t1.b*t1.f*17) from t1 where not exists(select 1 from t1 where t1.a not between d and 11)),b)-17*t1.d+t1.a in ( -t1.c,t1.e,11) then b else t1.d end in (select 17 from t1 union select 13 from t1)) and  -t1.a in (select (d) from t1 union select t1.b from t1))}
} {18000100}
do_test randexpr-2.1527 {
  db eval {SELECT coalesce((select (abs(b+t1.c)/abs(coalesce((select max( -~t1.d) from t1 where coalesce((select max(11) from t1 where not t1.d>=(select count(*) from t1)),case b-coalesce((select t1.e-f from t1 where coalesce((select max(case a when t1.e then t1.f else 11 end) from t1 where t1.b>=t1.f),t1.d) not in (f,e,13)),t1.f) when  -11 then t1.c else 19 end)-d not in (f,f,b)),f))) from t1 where d<=t1.d),f) FROM t1 WHERE c+case when coalesce((select d from t1 where coalesce((select max(17) from t1 where c>17-11),17)<c),case when not (t1.d) in (select 19 from t1 union select t1.a from t1) then case when  -d<=17 then f else t1.a end else 19 end)+e in (select 17 from t1 union select  -t1.b from t1) then b when 17<t1.b or 17<f then  -11 else t1.d end*b-t1.d in (select count(distinct d) from t1 union select count(distinct c) from t1)}
} {}
do_test randexpr-2.1528 {
  db eval {SELECT coalesce((select (abs(b+t1.c)/abs(coalesce((select max( -~t1.d) from t1 where coalesce((select max(11) from t1 where not t1.d>=(select count(*) from t1)),case b-coalesce((select t1.e-f from t1 where coalesce((select max(case a when t1.e then t1.f else 11 end) from t1 where t1.b>=t1.f),t1.d) not in (f,e,13)),t1.f) when  -11 then t1.c else 19 end)-d not in (f,f,b)),f))) from t1 where d<=t1.d),f) FROM t1 WHERE NOT (c+case when coalesce((select d from t1 where coalesce((select max(17) from t1 where c>17-11),17)<c),case when not (t1.d) in (select 19 from t1 union select t1.a from t1) then case when  -d<=17 then f else t1.a end else 19 end)+e in (select 17 from t1 union select  -t1.b from t1) then b when 17<t1.b or 17<f then  -11 else t1.d end*b-t1.d in (select count(distinct d) from t1 union select count(distinct c) from t1))}
} {1}
do_test randexpr-2.1529 {
  db eval {SELECT (abs(19)/abs(coalesce((select max((abs((abs(t1.a)/abs(e)))/abs(b))) from t1 where not t1.f<13 and 17-(abs(b-13*f*(abs(+17-f+t1.a)/abs(t1.d)))/abs(t1.e))+e-17>f and (exists(select 1 from t1 where (17 in (e, -t1.f,c)) and t1.f<=19))),d))) FROM t1 WHERE f*t1.c<>t1.b}
} {0}
do_test randexpr-2.1530 {
  db eval {SELECT (abs(19)/abs(coalesce((select max((abs((abs(t1.a)/abs(e)))/abs(b))) from t1 where not t1.f<13 and 17-(abs(b-13*f*(abs(+17-f+t1.a)/abs(t1.d)))/abs(t1.e))+e-17>f and (exists(select 1 from t1 where (17 in (e, -t1.f,c)) and t1.f<=19))),d))) FROM t1 WHERE NOT (f*t1.c<>t1.b)}
} {}
do_test randexpr-2.1531 {
  db eval {SELECT case when t1.d in (select count(distinct 11) from t1 union select case abs(++cast(avg(t1.b) AS integer)+count(*) |  -(count(*))) when count(*) then count(distinct t1.b) else count(distinct  -t1.a) end | max(t1.c) from t1) and t1.f<=case when exists(select 1 from t1 where t1.f+t1.f<>17 and t1.b>d) then 19 when t1.e=a then coalesce((select b from t1 where 13 not in (t1.b,t1.a,t1.a)),t1.c) else t1.d end and t1.d>(t1.b) and c in (e,t1.d,t1.b) then b | c when f=t1.e then e else 19 end FROM t1 WHERE t1.f between (c-t1.d+t1.f*t1.f) and 11+t1.e*coalesce((select max(coalesce((select max(t1.e) from t1 where exists(select 1 from t1 where (c-13 between t1.e*a and 11 or (t1.f>f) or t1.c>=t1.f))),t1.b-b-11)) from t1 where (f>t1.f)),11)-t1.b*e}
} {}
do_test randexpr-2.1532 {
  db eval {SELECT case when t1.d in (select count(distinct 11) from t1 union select case abs(++cast(avg(t1.b) AS integer)+count(*) |  -(count(*))) when count(*) then count(distinct t1.b) else count(distinct  -t1.a) end | max(t1.c) from t1) and t1.f<=case when exists(select 1 from t1 where t1.f+t1.f<>17 and t1.b>d) then 19 when t1.e=a then coalesce((select b from t1 where 13 not in (t1.b,t1.a,t1.a)),t1.c) else t1.d end and t1.d>(t1.b) and c in (e,t1.d,t1.b) then b | c when f=t1.e then e else 19 end FROM t1 WHERE NOT (t1.f between (c-t1.d+t1.f*t1.f) and 11+t1.e*coalesce((select max(coalesce((select max(t1.e) from t1 where exists(select 1 from t1 where (c-13 between t1.e*a and 11 or (t1.f>f) or t1.c>=t1.f))),t1.b-b-11)) from t1 where (f>t1.f)),11)-t1.b*e)}
} {19}
do_test randexpr-2.1533 {
  db eval {SELECT case when t1.d in (select count(distinct 11) from t1 union select case abs(++cast(avg(t1.b) AS integer)+count(*) &  -(count(*))) when count(*) then count(distinct t1.b) else count(distinct  -t1.a) end & max(t1.c) from t1) and t1.f<=case when exists(select 1 from t1 where t1.f+t1.f<>17 and t1.b>d) then 19 when t1.e=a then coalesce((select b from t1 where 13 not in (t1.b,t1.a,t1.a)),t1.c) else t1.d end and t1.d>(t1.b) and c in (e,t1.d,t1.b) then b & c when f=t1.e then e else 19 end FROM t1 WHERE NOT (t1.f between (c-t1.d+t1.f*t1.f) and 11+t1.e*coalesce((select max(coalesce((select max(t1.e) from t1 where exists(select 1 from t1 where (c-13 between t1.e*a and 11 or (t1.f>f) or t1.c>=t1.f))),t1.b-b-11)) from t1 where (f>t1.f)),11)-t1.b*e)}
} {19}
do_test randexpr-2.1534 {
  db eval {SELECT coalesce((select t1.e from t1 where (case when 19>=t1.c then t1.d else coalesce((select max(11*t1.b) from t1 where case ~t1.c-(select max(11) from t1)*~t1.b+f*~coalesce((select max(d) from t1 where d>=b),d)-t1.a*t1.c*t1.d when  -t1.c then 13 else f end in (select b from t1 union select 13 from t1)),t1.f) end | b<>a)),t1.e) FROM t1 WHERE not exists(select 1 from t1 where not (t1.e<t1.b and t1.e<>t1.b+case (select count(distinct e)*cast(avg(case c when e then case a when f then b else d end-a-13 else 13 end*t1.a+ -t1.d) AS integer) from t1)+c | (t1.f)*f when  -c then d else 19 end) and  -17 in (select min(t1.b) from t1 union select count(distinct f) from t1))}
} {500}
do_test randexpr-2.1535 {
  db eval {SELECT coalesce((select t1.e from t1 where (case when 19>=t1.c then t1.d else coalesce((select max(11*t1.b) from t1 where case ~t1.c-(select max(11) from t1)*~t1.b+f*~coalesce((select max(d) from t1 where d>=b),d)-t1.a*t1.c*t1.d when  -t1.c then 13 else f end in (select b from t1 union select 13 from t1)),t1.f) end | b<>a)),t1.e) FROM t1 WHERE NOT (not exists(select 1 from t1 where not (t1.e<t1.b and t1.e<>t1.b+case (select count(distinct e)*cast(avg(case c when e then case a when f then b else d end-a-13 else 13 end*t1.a+ -t1.d) AS integer) from t1)+c | (t1.f)*f when  -c then d else 19 end) and  -17 in (select min(t1.b) from t1 union select count(distinct f) from t1)))}
} {}
do_test randexpr-2.1536 {
  db eval {SELECT coalesce((select t1.e from t1 where (case when 19>=t1.c then t1.d else coalesce((select max(11*t1.b) from t1 where case ~t1.c-(select max(11) from t1)*~t1.b+f*~coalesce((select max(d) from t1 where d>=b),d)-t1.a*t1.c*t1.d when  -t1.c then 13 else f end in (select b from t1 union select 13 from t1)),t1.f) end & b<>a)),t1.e) FROM t1 WHERE not exists(select 1 from t1 where not (t1.e<t1.b and t1.e<>t1.b+case (select count(distinct e)*cast(avg(case c when e then case a when f then b else d end-a-13 else 13 end*t1.a+ -t1.d) AS integer) from t1)+c | (t1.f)*f when  -c then d else 19 end) and  -17 in (select min(t1.b) from t1 union select count(distinct f) from t1))}
} {500}
do_test randexpr-2.1537 {
  db eval {SELECT coalesce((select t1.c from t1 where f between case when (abs(coalesce((select 11* -~coalesce((select a*case coalesce((select max(a) from t1 where exists(select 1 from t1 where e in (17,t1.b,13))), -t1.e) when  -a then d else c end from t1 where t1.a>=t1.e),17)+t1.a-t1.d from t1 where exists(select 1 from t1 where  -b>t1.b)),e))/abs(d))<>17 then t1.d when 11< -f then d else d end*d and 17),b)-f-t1.d FROM t1 WHERE case when e<t1.d then t1.a when t1.f>=(abs(t1.b)/abs((abs(t1.f)/abs( -case b when 19 then ((abs((case when (+case when f between e and c then t1.f when t1.b>19 then t1.e else t1.f end+11+t1.a in (select t1.c from t1 union select f from t1)) then e-(13) when not exists(select 1 from t1 where not exists(select 1 from t1 where (13)>t1.f)) then t1.c else t1.f end))/abs(t1.d))) else c end)))) then b else (t1.d) end not between t1.a and t1.a}
} {-800}
do_test randexpr-2.1538 {
  db eval {SELECT coalesce((select t1.c from t1 where f between case when (abs(coalesce((select 11* -~coalesce((select a*case coalesce((select max(a) from t1 where exists(select 1 from t1 where e in (17,t1.b,13))), -t1.e) when  -a then d else c end from t1 where t1.a>=t1.e),17)+t1.a-t1.d from t1 where exists(select 1 from t1 where  -b>t1.b)),e))/abs(d))<>17 then t1.d when 11< -f then d else d end*d and 17),b)-f-t1.d FROM t1 WHERE NOT (case when e<t1.d then t1.a when t1.f>=(abs(t1.b)/abs((abs(t1.f)/abs( -case b when 19 then ((abs((case when (+case when f between e and c then t1.f when t1.b>19 then t1.e else t1.f end+11+t1.a in (select t1.c from t1 union select f from t1)) then e-(13) when not exists(select 1 from t1 where not exists(select 1 from t1 where (13)>t1.f)) then t1.c else t1.f end))/abs(t1.d))) else c end)))) then b else (t1.d) end not between t1.a and t1.a)}
} {}
do_test randexpr-2.1539 {
  db eval {SELECT case when not exists(select 1 from t1 where (coalesce((select max(coalesce((select 11 from t1 where t1.b*t1.d<=+case t1.c when (select max(case when not exists(select 1 from t1 where e=t1.b) then t1.a else f end) from t1)*t1.b | t1.a then 17 else 13 end-f | t1.e),13)) from t1 where a in (t1.b,t1.b,(t1.e))),11)*11 not in (d,t1.a,17))) then 13 when c in (select e from t1 union select t1.d from t1) then 19 else 13 end FROM t1 WHERE not exists(select 1 from t1 where case when  -b*13>+d then t1.e else coalesce((select case when not exists(select 1 from t1 where 11 in (c,+case when (case when e between t1.b and f then t1.a when t1.c not in (a,(c),t1.a) then  -t1.b else t1.a end<>d or f>e) then t1.e else t1.c end,t1.b)) then 19 else  -17 end*t1.d from t1 where (17 in (19,17,t1.f))),(t1.e)) end between 11 and t1.b and t1.a<>b)}
} {13}
do_test randexpr-2.1540 {
  db eval {SELECT case when not exists(select 1 from t1 where (coalesce((select max(coalesce((select 11 from t1 where t1.b*t1.d<=+case t1.c when (select max(case when not exists(select 1 from t1 where e=t1.b) then t1.a else f end) from t1)*t1.b | t1.a then 17 else 13 end-f | t1.e),13)) from t1 where a in (t1.b,t1.b,(t1.e))),11)*11 not in (d,t1.a,17))) then 13 when c in (select e from t1 union select t1.d from t1) then 19 else 13 end FROM t1 WHERE NOT (not exists(select 1 from t1 where case when  -b*13>+d then t1.e else coalesce((select case when not exists(select 1 from t1 where 11 in (c,+case when (case when e between t1.b and f then t1.a when t1.c not in (a,(c),t1.a) then  -t1.b else t1.a end<>d or f>e) then t1.e else t1.c end,t1.b)) then 19 else  -17 end*t1.d from t1 where (17 in (19,17,t1.f))),(t1.e)) end between 11 and t1.b and t1.a<>b))}
} {}
do_test randexpr-2.1541 {
  db eval {SELECT case when not exists(select 1 from t1 where (coalesce((select max(coalesce((select 11 from t1 where t1.b*t1.d<=+case t1.c when (select max(case when not exists(select 1 from t1 where e=t1.b) then t1.a else f end) from t1)*t1.b & t1.a then 17 else 13 end-f & t1.e),13)) from t1 where a in (t1.b,t1.b,(t1.e))),11)*11 not in (d,t1.a,17))) then 13 when c in (select e from t1 union select t1.d from t1) then 19 else 13 end FROM t1 WHERE not exists(select 1 from t1 where case when  -b*13>+d then t1.e else coalesce((select case when not exists(select 1 from t1 where 11 in (c,+case when (case when e between t1.b and f then t1.a when t1.c not in (a,(c),t1.a) then  -t1.b else t1.a end<>d or f>e) then t1.e else t1.c end,t1.b)) then 19 else  -17 end*t1.d from t1 where (17 in (19,17,t1.f))),(t1.e)) end between 11 and t1.b and t1.a<>b)}
} {13}
do_test randexpr-2.1542 {
  db eval {SELECT a-coalesce((select max(++19) from t1 where (select count(distinct coalesce((select max(t1.c) from t1 where not (t1.c+t1.c)-case when (not coalesce((select max(t1.a-t1.a) from t1 where t1.d>t1.b),e) in (t1.d,19,(t1.e))) then b when exists(select 1 from t1 where t1.e> -13) then c else e end<>c),17)) from t1) not between 19 and t1.f),t1.b) | 19-t1.d*f+b FROM t1 WHERE t1.f | coalesce((select case when c>=t1.f then t1.e+t1.e when  -19 | (a)+t1.f in (b,coalesce((select t1.c | (f+e)-e*17 from t1 where  -c not in (t1.d,c,(13))),19),t1.e) then t1.c else 17 end+b from t1 where t1.a not in (17,d,c)),17) in (select f from t1 union select f from t1)}
} {}
do_test randexpr-2.1543 {
  db eval {SELECT a-coalesce((select max(++19) from t1 where (select count(distinct coalesce((select max(t1.c) from t1 where not (t1.c+t1.c)-case when (not coalesce((select max(t1.a-t1.a) from t1 where t1.d>t1.b),e) in (t1.d,19,(t1.e))) then b when exists(select 1 from t1 where t1.e> -13) then c else e end<>c),17)) from t1) not between 19 and t1.f),t1.b) | 19-t1.d*f+b FROM t1 WHERE NOT (t1.f | coalesce((select case when c>=t1.f then t1.e+t1.e when  -19 | (a)+t1.f in (b,coalesce((select t1.c | (f+e)-e*17 from t1 where  -c not in (t1.d,c,(13))),19),t1.e) then t1.c else 17 end+b from t1 where t1.a not in (17,d,c)),17) in (select f from t1 union select f from t1))}
} {-239781}
do_test randexpr-2.1544 {
  db eval {SELECT a-coalesce((select max(++19) from t1 where (select count(distinct coalesce((select max(t1.c) from t1 where not (t1.c+t1.c)-case when (not coalesce((select max(t1.a-t1.a) from t1 where t1.d>t1.b),e) in (t1.d,19,(t1.e))) then b when exists(select 1 from t1 where t1.e> -13) then c else e end<>c),17)) from t1) not between 19 and t1.f),t1.b) & 19-t1.d*f+b FROM t1 WHERE NOT (t1.f | coalesce((select case when c>=t1.f then t1.e+t1.e when  -19 | (a)+t1.f in (b,coalesce((select t1.c | (f+e)-e*17 from t1 where  -c not in (t1.d,c,(13))),19),t1.e) then t1.c else 17 end+b from t1 where t1.a not in (17,d,c)),17) in (select f from t1 union select f from t1))}
} {81}
do_test randexpr-2.1545 {
  db eval {SELECT coalesce((select (t1.d) from t1 where not not case when c<coalesce((select f from t1 where 13 | t1.d in (select 11*t1.f*case when exists(select 1 from t1 where d>=case when f<>( -t1.c) then c when 19<>t1.d then t1.f else d end) then e-f when c in (select d from t1 union select f from t1) then a else t1.b end | t1.a-f from t1 union select  -19 from t1)),19) then 19 when 11 between f and t1.f then t1.c else 19 end=a),t1.f) FROM t1 WHERE coalesce((select t1.d from t1 where (case when exists(select 1 from t1 where not  - -19 in (17,f,t1.b)) and 19>c or t1.c in (select t1.e from t1 union select 17 from t1) then a when exists(select 1 from t1 where (t1.c<>d)) and  -t1.c not between b and e then 11 else (select cast(avg((abs(b)/abs(d))) AS integer) from t1) end+t1.d not in (t1.f,11,b) and f not between 17 and t1.d)),t1.e)=t1.a}
} {}
do_test randexpr-2.1546 {
  db eval {SELECT coalesce((select (t1.d) from t1 where not not case when c<coalesce((select f from t1 where 13 | t1.d in (select 11*t1.f*case when exists(select 1 from t1 where d>=case when f<>( -t1.c) then c when 19<>t1.d then t1.f else d end) then e-f when c in (select d from t1 union select f from t1) then a else t1.b end | t1.a-f from t1 union select  -19 from t1)),19) then 19 when 11 between f and t1.f then t1.c else 19 end=a),t1.f) FROM t1 WHERE NOT (coalesce((select t1.d from t1 where (case when exists(select 1 from t1 where not  - -19 in (17,f,t1.b)) and 19>c or t1.c in (select t1.e from t1 union select 17 from t1) then a when exists(select 1 from t1 where (t1.c<>d)) and  -t1.c not between b and e then 11 else (select cast(avg((abs(b)/abs(d))) AS integer) from t1) end+t1.d not in (t1.f,11,b) and f not between 17 and t1.d)),t1.e)=t1.a)}
} {600}
do_test randexpr-2.1547 {
  db eval {SELECT coalesce((select (t1.d) from t1 where not not case when c<coalesce((select f from t1 where 13 & t1.d in (select 11*t1.f*case when exists(select 1 from t1 where d>=case when f<>( -t1.c) then c when 19<>t1.d then t1.f else d end) then e-f when c in (select d from t1 union select f from t1) then a else t1.b end & t1.a-f from t1 union select  -19 from t1)),19) then 19 when 11 between f and t1.f then t1.c else 19 end=a),t1.f) FROM t1 WHERE NOT (coalesce((select t1.d from t1 where (case when exists(select 1 from t1 where not  - -19 in (17,f,t1.b)) and 19>c or t1.c in (select t1.e from t1 union select 17 from t1) then a when exists(select 1 from t1 where (t1.c<>d)) and  -t1.c not between b and e then 11 else (select cast(avg((abs(b)/abs(d))) AS integer) from t1) end+t1.d not in (t1.f,11,b) and f not between 17 and t1.d)),t1.e)=t1.a)}
} {600}
do_test randexpr-2.1548 {
  db eval {SELECT coalesce((select max(case when  -++t1.c++(abs(case when t1.b<case when exists(select 1 from t1 where  -t1.b-13=t1.e) then t1.b else c end then t1.f else case when t1.a<t1.b+t1.d then 19 when t1.f not in (t1.c,c,c) then t1.d else t1.f end end)/abs(19))*b-d>b then 11 else b end) from t1 where ((t1.b)) between e and e),t1.e) FROM t1 WHERE not ~t1.c-(coalesce((select max(~case t1.e | b*11+d+19 when t1.a then t1.b else t1.d end) from t1 where (13 not in (t1.a,t1.a,13))),e)) not between t1.a and 11 or exists(select 1 from t1 where (t1.d) not in (11,13,t1.a) and (c<>b or  -13<>t1.b and c in (t1.f, -c,t1.d)))}
} {500}
do_test randexpr-2.1549 {
  db eval {SELECT coalesce((select max(case when  -++t1.c++(abs(case when t1.b<case when exists(select 1 from t1 where  -t1.b-13=t1.e) then t1.b else c end then t1.f else case when t1.a<t1.b+t1.d then 19 when t1.f not in (t1.c,c,c) then t1.d else t1.f end end)/abs(19))*b-d>b then 11 else b end) from t1 where ((t1.b)) between e and e),t1.e) FROM t1 WHERE NOT (not ~t1.c-(coalesce((select max(~case t1.e | b*11+d+19 when t1.a then t1.b else t1.d end) from t1 where (13 not in (t1.a,t1.a,13))),e)) not between t1.a and 11 or exists(select 1 from t1 where (t1.d) not in (11,13,t1.a) and (c<>b or  -13<>t1.b and c in (t1.f, -c,t1.d))))}
} {}
do_test randexpr-2.1550 {
  db eval {SELECT case 19*d-+t1.a | coalesce((select f from t1 where +b between coalesce((select +t1.f from t1 where not exists(select 1 from t1 where case 17 when b then f else f end>=~13)),t1.f) and t1.d),c+11)- -t1.e | 17+case t1.b when t1.a then 17 else t1.f end*t1.c+a when f then  -f else t1.f end | t1.b FROM t1 WHERE t1.f=f and not exists(select 1 from t1 where case when t1.b>e then (abs(13)/abs(t1.f | 17))+(t1.f) else ~t1.a-(~e) end in (select count(distinct coalesce((select max(coalesce((select 11 from t1 where t1.a<d),(b))*17) from t1 where (e in (select count(*) from t1 union select max(t1.a)-cast(avg(17) AS integer)-(cast(avg(11) AS integer)) from t1))),t1.d)) from t1 union select cast(avg(c) AS integer) from t1)) and e between c and f}
} {728}
do_test randexpr-2.1551 {
  db eval {SELECT case 19*d-+t1.a | coalesce((select f from t1 where +b between coalesce((select +t1.f from t1 where not exists(select 1 from t1 where case 17 when b then f else f end>=~13)),t1.f) and t1.d),c+11)- -t1.e | 17+case t1.b when t1.a then 17 else t1.f end*t1.c+a when f then  -f else t1.f end | t1.b FROM t1 WHERE NOT (t1.f=f and not exists(select 1 from t1 where case when t1.b>e then (abs(13)/abs(t1.f | 17))+(t1.f) else ~t1.a-(~e) end in (select count(distinct coalesce((select max(coalesce((select 11 from t1 where t1.a<d),(b))*17) from t1 where (e in (select count(*) from t1 union select max(t1.a)-cast(avg(17) AS integer)-(cast(avg(11) AS integer)) from t1))),t1.d)) from t1 union select cast(avg(c) AS integer) from t1)) and e between c and f)}
} {}
do_test randexpr-2.1552 {
  db eval {SELECT case 19*d-+t1.a & coalesce((select f from t1 where +b between coalesce((select +t1.f from t1 where not exists(select 1 from t1 where case 17 when b then f else f end>=~13)),t1.f) and t1.d),c+11)- -t1.e & 17+case t1.b when t1.a then 17 else t1.f end*t1.c+a when f then  -f else t1.f end & t1.b FROM t1 WHERE t1.f=f and not exists(select 1 from t1 where case when t1.b>e then (abs(13)/abs(t1.f | 17))+(t1.f) else ~t1.a-(~e) end in (select count(distinct coalesce((select max(coalesce((select 11 from t1 where t1.a<d),(b))*17) from t1 where (e in (select count(*) from t1 union select max(t1.a)-cast(avg(17) AS integer)-(cast(avg(11) AS integer)) from t1))),t1.d)) from t1 union select cast(avg(c) AS integer) from t1)) and e between c and f}
} {72}
do_test randexpr-2.1553 {
  db eval {SELECT (coalesce((select max(coalesce((select (abs(t1.e* -b*coalesce((select max( -t1.e*t1.e+t1.f) from t1 where  -case when b>=t1.e and e>f then 11 | 19 else t1.c end | b in (select a from t1 union select 13 from t1)),b)+t1.b | (d)*11)/abs(e)) from t1 where a=19),t1.e)*13) from t1 where 13>f),t1.f)) FROM t1 WHERE coalesce((select max(~t1.a*t1.f*t1.b+f+a) from t1 where case when d in (select  -+count(distinct (t1.c))*max(t1.e+b)-(( -count(distinct 17))) from t1 union select  -count(distinct t1.d) from t1) then t1.d else (abs(case when t1.e in (select t1.c from t1 union select c from t1) then c else d end)/abs(f)) end in (select max( -c) from t1 union select abs(count(distinct 19)) from t1)), -a) not in (d,t1.f,13)}
} {600}
do_test randexpr-2.1554 {
  db eval {SELECT (coalesce((select max(coalesce((select (abs(t1.e* -b*coalesce((select max( -t1.e*t1.e+t1.f) from t1 where  -case when b>=t1.e and e>f then 11 | 19 else t1.c end | b in (select a from t1 union select 13 from t1)),b)+t1.b | (d)*11)/abs(e)) from t1 where a=19),t1.e)*13) from t1 where 13>f),t1.f)) FROM t1 WHERE NOT (coalesce((select max(~t1.a*t1.f*t1.b+f+a) from t1 where case when d in (select  -+count(distinct (t1.c))*max(t1.e+b)-(( -count(distinct 17))) from t1 union select  -count(distinct t1.d) from t1) then t1.d else (abs(case when t1.e in (select t1.c from t1 union select c from t1) then c else d end)/abs(f)) end in (select max( -c) from t1 union select abs(count(distinct 19)) from t1)), -a) not in (d,t1.f,13))}
} {}
do_test randexpr-2.1555 {
  db eval {SELECT (coalesce((select max(coalesce((select (abs(t1.e* -b*coalesce((select max( -t1.e*t1.e+t1.f) from t1 where  -case when b>=t1.e and e>f then 11 & 19 else t1.c end & b in (select a from t1 union select 13 from t1)),b)+t1.b & (d)*11)/abs(e)) from t1 where a=19),t1.e)*13) from t1 where 13>f),t1.f)) FROM t1 WHERE coalesce((select max(~t1.a*t1.f*t1.b+f+a) from t1 where case when d in (select  -+count(distinct (t1.c))*max(t1.e+b)-(( -count(distinct 17))) from t1 union select  -count(distinct t1.d) from t1) then t1.d else (abs(case when t1.e in (select t1.c from t1 union select c from t1) then c else d end)/abs(f)) end in (select max( -c) from t1 union select abs(count(distinct 19)) from t1)), -a) not in (d,t1.f,13)}
} {600}
do_test randexpr-2.1556 {
  db eval {SELECT +(abs(17*(abs(a | t1.a)/abs(11)) | f)/abs(coalesce((select +t1.b+~a from t1 where case when a=t1.b then c when t1.d=t1.e then t1.b else 17 end<=t1.f and (b<>13) or t1.a<>a or t1.d>d and 11 between 17 and t1.a and t1.b<> -e and  -13<(17)),a)+ -t1.e))*(t1.c) FROM t1 WHERE not a not between t1.a and 11+ -coalesce((select  -c*coalesce((select max(~f*a+11-t1.a |  -a+t1.a*t1.b*f) from t1 where 11=11),t1.a)+d from t1 where 13>=e),d) | t1.b or t1.a not between  -b and f or 17<>13}
} {300}
do_test randexpr-2.1557 {
  db eval {SELECT +(abs(17*(abs(a | t1.a)/abs(11)) | f)/abs(coalesce((select +t1.b+~a from t1 where case when a=t1.b then c when t1.d=t1.e then t1.b else 17 end<=t1.f and (b<>13) or t1.a<>a or t1.d>d and 11 between 17 and t1.a and t1.b<> -e and  -13<(17)),a)+ -t1.e))*(t1.c) FROM t1 WHERE NOT (not a not between t1.a and 11+ -coalesce((select  -c*coalesce((select max(~f*a+11-t1.a |  -a+t1.a*t1.b*f) from t1 where 11=11),t1.a)+d from t1 where 13>=e),d) | t1.b or t1.a not between  -b and f or 17<>13)}
} {}
do_test randexpr-2.1558 {
  db eval {SELECT +(abs(17*(abs(a & t1.a)/abs(11)) & f)/abs(coalesce((select +t1.b+~a from t1 where case when a=t1.b then c when t1.d=t1.e then t1.b else 17 end<=t1.f and (b<>13) or t1.a<>a or t1.d>d and 11 between 17 and t1.a and t1.b<> -e and  -13<(17)),a)+ -t1.e))*(t1.c) FROM t1 WHERE not a not between t1.a and 11+ -coalesce((select  -c*coalesce((select max(~f*a+11-t1.a |  -a+t1.a*t1.b*f) from t1 where 11=11),t1.a)+d from t1 where 13>=e),d) | t1.b or t1.a not between  -b and f or 17<>13}
} {0}
do_test randexpr-2.1559 {
  db eval {SELECT b-case e*13+case when not not t1.d in (select t1.b from t1 union select f from t1) then t1.c when coalesce((select max(coalesce((select (select ~min(coalesce((select max(a*f) from t1 where t1.f<=t1.b or a<=f),t1.a)) |  -(count(distinct 19)) from t1) from t1 where f between (t1.f) and 11),a)) from t1 where 11 not in (f, -11,19)),e)>=d then t1.f else t1.c end when  -a then 11 else t1.e end FROM t1 WHERE coalesce((select case case when case when (coalesce((select max(t1.e) from t1 where c>c and  -19>= -a),d) not in (11,t1.b,t1.a)) then d else a end between 11 and t1.c then b else a end+13-t1.a when t1.d then (b) else t1.d end from t1 where b between e and t1.f),11) in (select (+abs(count(*)+case  -count(distinct t1.e) when  -(max(19)) then (count(distinct 19)) else  -count(distinct e) end-max(t1.b)) | count(distinct t1.e) | (cast(avg(11) AS integer))) from t1 union select cast(avg(c) AS integer) from t1)}
} {}
do_test randexpr-2.1560 {
  db eval {SELECT b-case e*13+case when not not t1.d in (select t1.b from t1 union select f from t1) then t1.c when coalesce((select max(coalesce((select (select ~min(coalesce((select max(a*f) from t1 where t1.f<=t1.b or a<=f),t1.a)) |  -(count(distinct 19)) from t1) from t1 where f between (t1.f) and 11),a)) from t1 where 11 not in (f, -11,19)),e)>=d then t1.f else t1.c end when  -a then 11 else t1.e end FROM t1 WHERE NOT (coalesce((select case case when case when (coalesce((select max(t1.e) from t1 where c>c and  -19>= -a),d) not in (11,t1.b,t1.a)) then d else a end between 11 and t1.c then b else a end+13-t1.a when t1.d then (b) else t1.d end from t1 where b between e and t1.f),11) in (select (+abs(count(*)+case  -count(distinct t1.e) when  -(max(19)) then (count(distinct 19)) else  -count(distinct e) end-max(t1.b)) | count(distinct t1.e) | (cast(avg(11) AS integer))) from t1 union select cast(avg(c) AS integer) from t1))}
} {-300}
do_test randexpr-2.1561 {
  db eval {SELECT b-case e*13+case when not not t1.d in (select t1.b from t1 union select f from t1) then t1.c when coalesce((select max(coalesce((select (select ~min(coalesce((select max(a*f) from t1 where t1.f<=t1.b or a<=f),t1.a)) &  -(count(distinct 19)) from t1) from t1 where f between (t1.f) and 11),a)) from t1 where 11 not in (f, -11,19)),e)>=d then t1.f else t1.c end when  -a then 11 else t1.e end FROM t1 WHERE NOT (coalesce((select case case when case when (coalesce((select max(t1.e) from t1 where c>c and  -19>= -a),d) not in (11,t1.b,t1.a)) then d else a end between 11 and t1.c then b else a end+13-t1.a when t1.d then (b) else t1.d end from t1 where b between e and t1.f),11) in (select (+abs(count(*)+case  -count(distinct t1.e) when  -(max(19)) then (count(distinct 19)) else  -count(distinct e) end-max(t1.b)) | count(distinct t1.e) | (cast(avg(11) AS integer))) from t1 union select cast(avg(c) AS integer) from t1))}
} {-300}
do_test randexpr-2.1562 {
  db eval {SELECT coalesce((select case when a not in (~17,a,c) then b when t1.c<>t1.f-13 then +f else 11 end+t1.e*t1.a+case when ((a-c)>case when (exists(select 1 from t1 where (c) between d and  -t1.b)) then a+t1.f else f end) or e between t1.c and 13 then  -t1.c else t1.e end-t1.d from t1 where ( -17=a)),e) FROM t1 WHERE +case when not exists(select 1 from t1 where f+(select ~ -min(b) | abs(+max(+c)) from t1)+b not between 13-a*17 and t1.e-t1.b) then t1.a when b not between ((11)) and 11 then 13 else 17 end+ - -t1.f in (f,t1.d,f) or t1.b>t1.a and not exists(select 1 from t1 where t1.d in (t1.c,d,t1.c))}
} {}
do_test randexpr-2.1563 {
  db eval {SELECT coalesce((select case when a not in (~17,a,c) then b when t1.c<>t1.f-13 then +f else 11 end+t1.e*t1.a+case when ((a-c)>case when (exists(select 1 from t1 where (c) between d and  -t1.b)) then a+t1.f else f end) or e between t1.c and 13 then  -t1.c else t1.e end-t1.d from t1 where ( -17=a)),e) FROM t1 WHERE NOT (+case when not exists(select 1 from t1 where f+(select ~ -min(b) | abs(+max(+c)) from t1)+b not between 13-a*17 and t1.e-t1.b) then t1.a when b not between ((11)) and 11 then 13 else 17 end+ - -t1.f in (f,t1.d,f) or t1.b>t1.a and not exists(select 1 from t1 where t1.d in (t1.c,d,t1.c)))}
} {500}
do_test randexpr-2.1564 {
  db eval {SELECT case coalesce((select 19-case when case when f in (select t1.c from t1 union select (select count(*) from t1) from t1) then a+e else 19 end*19-19-13 not in (11,19,a) then f when (13<>(t1.c) or d>e and b=b) then t1.a else 13 end from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where t1.a=17)))),a) when t1.d then 19 else e end FROM t1 WHERE 13-coalesce((select (abs(19)/abs(11)) from t1 where case when a in (select d from t1 union select case when  -11-11<>d or t1.e between (t1.d) and b then t1.f else f end from t1) then t1.e else  -a end not between 13 and 19 or exists(select 1 from t1 where f< -( -t1.d)) and t1.a not between  -e and t1.e or t1.f<f and 13=13 and t1.f>(t1.f)),t1.d)=11}
} {}
do_test randexpr-2.1565 {
  db eval {SELECT case coalesce((select 19-case when case when f in (select t1.c from t1 union select (select count(*) from t1) from t1) then a+e else 19 end*19-19-13 not in (11,19,a) then f when (13<>(t1.c) or d>e and b=b) then t1.a else 13 end from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where t1.a=17)))),a) when t1.d then 19 else e end FROM t1 WHERE NOT (13-coalesce((select (abs(19)/abs(11)) from t1 where case when a in (select d from t1 union select case when  -11-11<>d or t1.e between (t1.d) and b then t1.f else f end from t1) then t1.e else  -a end not between 13 and 19 or exists(select 1 from t1 where f< -( -t1.d)) and t1.a not between  -e and t1.e or t1.f<f and 13=13 and t1.f>(t1.f)),t1.d)=11)}
} {500}
do_test randexpr-2.1566 {
  db eval {SELECT (select  -count(distinct  -case (select (max( -c-t1.b+~f)*count(distinct 11) | +cast(avg(11) AS integer)-min(t1.f)+ -(cast(avg(( -11)) AS integer))-count(distinct t1.d)*(max(13))*(max(d))-(count(*))-min(e)) from t1) when + -c then t1.d else t1.b*19 end-a | t1.d+t1.d) from t1) FROM t1 WHERE not 11-t1.a=a+11}
} {-1}
do_test randexpr-2.1567 {
  db eval {SELECT (select  -count(distinct  -case (select (max( -c-t1.b+~f)*count(distinct 11) | +cast(avg(11) AS integer)-min(t1.f)+ -(cast(avg(( -11)) AS integer))-count(distinct t1.d)*(max(13))*(max(d))-(count(*))-min(e)) from t1) when + -c then t1.d else t1.b*19 end-a | t1.d+t1.d) from t1) FROM t1 WHERE NOT (not 11-t1.a=a+11)}
} {}
do_test randexpr-2.1568 {
  db eval {SELECT (select  -count(distinct  -case (select (max( -c-t1.b+~f)*count(distinct 11) & +cast(avg(11) AS integer)-min(t1.f)+ -(cast(avg(( -11)) AS integer))-count(distinct t1.d)*(max(13))*(max(d))-(count(*))-min(e)) from t1) when + -c then t1.d else t1.b*19 end-a & t1.d+t1.d) from t1) FROM t1 WHERE not 11-t1.a=a+11}
} {-1}
do_test randexpr-2.1569 {
  db eval {SELECT (select ~count(distinct t1.d*e+19)+abs(+cast(avg((select (count(*)) from t1)) AS integer)-cast(avg(t1.c) AS integer) | min(case when d | f* -19 in (select min(c) from t1 union select ~count(*)-max(17) from t1) then t1.e when (t1.b between 17 and (b)) then t1.d else t1.d end)*cast(avg(e) AS integer))-count(distinct t1.f) | cast(avg( -d) AS integer)*cast(avg(f) AS integer) from t1)*t1.e FROM t1 WHERE coalesce((select 17 from t1 where coalesce((select max(case when 13-b+coalesce((select case when (f>a) then t1.f when t1.c<=19 then a else a end from t1 where c in (select (e) from t1 union select 13 from t1)),13)<13 then 13 else t1.b end) from t1 where (13)<>13),17) in (select +min(b) from t1 union select ~max(t1.d)*max( -t1.b)*min(t1.e) from t1) and e>c),f) between ((t1.f)) and b and t1.a=19}
} {}
do_test randexpr-2.1570 {
  db eval {SELECT (select ~count(distinct t1.d*e+19)+abs(+cast(avg((select (count(*)) from t1)) AS integer)-cast(avg(t1.c) AS integer) | min(case when d | f* -19 in (select min(c) from t1 union select ~count(*)-max(17) from t1) then t1.e when (t1.b between 17 and (b)) then t1.d else t1.d end)*cast(avg(e) AS integer))-count(distinct t1.f) | cast(avg( -d) AS integer)*cast(avg(f) AS integer) from t1)*t1.e FROM t1 WHERE NOT (coalesce((select 17 from t1 where coalesce((select max(case when 13-b+coalesce((select case when (f>a) then t1.f when t1.c<=19 then a else a end from t1 where c in (select (e) from t1 union select 13 from t1)),13)<13 then 13 else t1.b end) from t1 where (13)<>13),17) in (select +min(b) from t1 union select ~max(t1.d)*max( -t1.b)*min(t1.e) from t1) and e>c),f) between ((t1.f)) and b and t1.a=19)}
} {-119980000}
do_test randexpr-2.1571 {
  db eval {SELECT (select ~count(distinct t1.d*e+19)+abs(+cast(avg((select (count(*)) from t1)) AS integer)-cast(avg(t1.c) AS integer) & min(case when d & f* -19 in (select min(c) from t1 union select ~count(*)-max(17) from t1) then t1.e when (t1.b between 17 and (b)) then t1.d else t1.d end)*cast(avg(e) AS integer))-count(distinct t1.f) & cast(avg( -d) AS integer)*cast(avg(f) AS integer) from t1)*t1.e FROM t1 WHERE NOT (coalesce((select 17 from t1 where coalesce((select max(case when 13-b+coalesce((select case when (f>a) then t1.f when t1.c<=19 then a else a end from t1 where c in (select (e) from t1 union select 13 from t1)),13)<13 then 13 else t1.b end) from t1 where (13)<>13),17) in (select +min(b) from t1 union select ~max(t1.d)*max( -t1.b)*min(t1.e) from t1) and e>c),f) between ((t1.f)) and b and t1.a=19)}
} {512000}
do_test randexpr-2.1572 {
  db eval {SELECT coalesce((select d from t1 where case when (17 between c+t1.d-t1.a and b and t1.b in (13,t1.d,19)) then case when t1.c<(a) then t1.c when t1.e not in (a,11,(t1.d)) then t1.d else d end else t1.a end in (select abs(min(a) | ~~count(distinct t1.e)+min(b)-count(*)) from t1 union select count(*) from t1) and not exists(select 1 from t1 where (t1.a) between t1.a and t1.d)),t1.f)-t1.a FROM t1 WHERE case when t1.e not in (coalesce((select max(coalesce((select max(b+t1.c-19*(e)-~11) from t1 where t1.a in (select ~cast(avg(~t1.a) AS integer) from t1 union select abs(~cast(avg(f) AS integer)) from t1)),e)* -c-c-b-t1.d-f) from t1 where t1.f>=t1.c),((t1.d)))- - -19,17,t1.b) then b else t1.f end<d}
} {500}
do_test randexpr-2.1573 {
  db eval {SELECT coalesce((select d from t1 where case when (17 between c+t1.d-t1.a and b and t1.b in (13,t1.d,19)) then case when t1.c<(a) then t1.c when t1.e not in (a,11,(t1.d)) then t1.d else d end else t1.a end in (select abs(min(a) | ~~count(distinct t1.e)+min(b)-count(*)) from t1 union select count(*) from t1) and not exists(select 1 from t1 where (t1.a) between t1.a and t1.d)),t1.f)-t1.a FROM t1 WHERE NOT (case when t1.e not in (coalesce((select max(coalesce((select max(b+t1.c-19*(e)-~11) from t1 where t1.a in (select ~cast(avg(~t1.a) AS integer) from t1 union select abs(~cast(avg(f) AS integer)) from t1)),e)* -c-c-b-t1.d-f) from t1 where t1.f>=t1.c),((t1.d)))- - -19,17,t1.b) then b else t1.f end<d)}
} {}
do_test randexpr-2.1574 {
  db eval {SELECT coalesce((select d from t1 where case when (17 between c+t1.d-t1.a and b and t1.b in (13,t1.d,19)) then case when t1.c<(a) then t1.c when t1.e not in (a,11,(t1.d)) then t1.d else d end else t1.a end in (select abs(min(a) & ~~count(distinct t1.e)+min(b)-count(*)) from t1 union select count(*) from t1) and not exists(select 1 from t1 where (t1.a) between t1.a and t1.d)),t1.f)-t1.a FROM t1 WHERE case when t1.e not in (coalesce((select max(coalesce((select max(b+t1.c-19*(e)-~11) from t1 where t1.a in (select ~cast(avg(~t1.a) AS integer) from t1 union select abs(~cast(avg(f) AS integer)) from t1)),e)* -c-c-b-t1.d-f) from t1 where t1.f>=t1.c),((t1.d)))- - -19,17,t1.b) then b else t1.f end<d}
} {500}
do_test randexpr-2.1575 {
  db eval {SELECT (abs((select min(t1.a)*~+ -count(*)-max(t1.f) from t1))/abs((abs(13*~t1.c- -e-( -19) | case 17*~13 when t1.c+case when not 19 between 13 and a then t1.c when  -11 not between e and 17 then 19 else a end then 19 else 17 end*19)/abs(t1.d)))) FROM t1 WHERE t1.e in (select d from t1 union select case when not exists(select 1 from t1 where c+a*17 not between case when t1.f>=(t1.f)+a then t1.d else 19 end and t1.c or exists(select 1 from t1 where (b in (13,13,b)) and (t1.f<>t1.e)) or (13)<>17 and e<=f and e<= -c) and t1.f>f then t1.e*19-t1.e-b else 17 end from t1)}
} {}
do_test randexpr-2.1576 {
  db eval {SELECT (abs((select min(t1.a)*~+ -count(*)-max(t1.f) from t1))/abs((abs(13*~t1.c- -e-( -19) | case 17*~13 when t1.c+case when not 19 between 13 and a then t1.c when  -11 not between e and 17 then 19 else a end then 19 else 17 end*19)/abs(t1.d)))) FROM t1 WHERE NOT (t1.e in (select d from t1 union select case when not exists(select 1 from t1 where c+a*17 not between case when t1.f>=(t1.f)+a then t1.d else 19 end and t1.c or exists(select 1 from t1 where (b in (13,13,b)) and (t1.f<>t1.e)) or (13)<>17 and e<=f and e<= -c) and t1.f>f then t1.e*19-t1.e-b else 17 end from t1))}
} {85}
do_test randexpr-2.1577 {
  db eval {SELECT b-t1.b-coalesce((select (abs(case t1.c+coalesce((select +17*case when b in (select abs(max(19) | count(distinct t1.e)) | cast(avg(t1.d) AS integer) from t1 union select (count(*)) from t1) then +11+t1.a when 11<d then  -b else t1.c end from t1 where t1.f not between d and t1.c),t1.d)-13*t1.b when e then t1.e else  -17 end)/abs( - -d)) from t1 where (t1.a<>e)),d) FROM t1 WHERE t1.a<> -a}
} {0}
do_test randexpr-2.1578 {
  db eval {SELECT b-t1.b-coalesce((select (abs(case t1.c+coalesce((select +17*case when b in (select abs(max(19) | count(distinct t1.e)) | cast(avg(t1.d) AS integer) from t1 union select (count(*)) from t1) then +11+t1.a when 11<d then  -b else t1.c end from t1 where t1.f not between d and t1.c),t1.d)-13*t1.b when e then t1.e else  -17 end)/abs( - -d)) from t1 where (t1.a<>e)),d) FROM t1 WHERE NOT (t1.a<> -a)}
} {}
do_test randexpr-2.1579 {
  db eval {SELECT b-t1.b-coalesce((select (abs(case t1.c+coalesce((select +17*case when b in (select abs(max(19) & count(distinct t1.e)) & cast(avg(t1.d) AS integer) from t1 union select (count(*)) from t1) then +11+t1.a when 11<d then  -b else t1.c end from t1 where t1.f not between d and t1.c),t1.d)-13*t1.b when e then t1.e else  -17 end)/abs( - -d)) from t1 where (t1.a<>e)),d) FROM t1 WHERE t1.a<> -a}
} {0}
do_test randexpr-2.1580 {
  db eval {SELECT ~(abs(b*t1.b)/abs(case when coalesce((select max((abs(a)/abs(case t1.e when t1.e then c*(t1.d) else t1.a end))) from t1 where b in (select min((t1.a)) from t1 union select + -max(b) from t1)),19)+a not between t1.e and  -19 and 13<=a then (select case cast(avg((a)) AS integer) when min(e)*max(f) then  -(count(distinct 13)) else cast(avg(13) AS integer) end-count(*) | count(distinct d) |  -count(*) from t1) else b end)) FROM t1 WHERE f not between t1.d and b}
} {-40001}
do_test randexpr-2.1581 {
  db eval {SELECT ~(abs(b*t1.b)/abs(case when coalesce((select max((abs(a)/abs(case t1.e when t1.e then c*(t1.d) else t1.a end))) from t1 where b in (select min((t1.a)) from t1 union select + -max(b) from t1)),19)+a not between t1.e and  -19 and 13<=a then (select case cast(avg((a)) AS integer) when min(e)*max(f) then  -(count(distinct 13)) else cast(avg(13) AS integer) end-count(*) | count(distinct d) |  -count(*) from t1) else b end)) FROM t1 WHERE NOT (f not between t1.d and b)}
} {}
do_test randexpr-2.1582 {
  db eval {SELECT +(abs(19)/abs(d | 11*t1.f))*t1.e-coalesce((select t1.b from t1 where not ((f*case when a>=17 then t1.c else (a) end-b not in (t1.b,t1.f,t1.f) or not exists(select 1 from t1 where t1.c>t1.a) and c not in (t1.d,t1.b,c)))),e) | coalesce((select ( - -f) from t1 where 19 not between 17 and 17),(a))-17*d*c FROM t1 WHERE t1.b>=e}
} {}
do_test randexpr-2.1583 {
  db eval {SELECT +(abs(19)/abs(d | 11*t1.f))*t1.e-coalesce((select t1.b from t1 where not ((f*case when a>=17 then t1.c else (a) end-b not in (t1.b,t1.f,t1.f) or not exists(select 1 from t1 where t1.c>t1.a) and c not in (t1.d,t1.b,c)))),e) | coalesce((select ( - -f) from t1 where 19 not between 17 and 17),(a))-17*d*c FROM t1 WHERE NOT (t1.b>=e)}
} {-100}
do_test randexpr-2.1584 {
  db eval {SELECT +(abs(19)/abs(d & 11*t1.f))*t1.e-coalesce((select t1.b from t1 where not ((f*case when a>=17 then t1.c else (a) end-b not in (t1.b,t1.f,t1.f) or not exists(select 1 from t1 where t1.c>t1.a) and c not in (t1.d,t1.b,c)))),e) & coalesce((select ( - -f) from t1 where 19 not between 17 and 17),(a))-17*d*c FROM t1 WHERE NOT (t1.b>=e)}
} {-2039800}
do_test randexpr-2.1585 {
  db eval {SELECT (abs((abs(a)/abs(~17+t1.b-e+(abs(a)/abs(coalesce((select max(13) from t1 where c not in (c-(abs(+coalesce((select max(t1.b-f) from t1 where (abs(13+case ~t1.f when t1.c then t1.b else b end-e)/abs(c))-t1.e>t1.c),t1.c))/abs(11))+t1.b,t1.a,11)),t1.a)))))+19)/abs( - -t1.c)) FROM t1 WHERE ~t1.e+t1.a+(abs(case when d+e+17*~t1.a-t1.a-a*~(abs(~f)/abs( -13))*+(t1.c | a)*t1.b=e then t1.d when ( -e) not between c and  -d then  -(t1.f) else t1.b end)/abs(19))>t1.f and 11<(11)}
} {}
do_test randexpr-2.1586 {
  db eval {SELECT (abs((abs(a)/abs(~17+t1.b-e+(abs(a)/abs(coalesce((select max(13) from t1 where c not in (c-(abs(+coalesce((select max(t1.b-f) from t1 where (abs(13+case ~t1.f when t1.c then t1.b else b end-e)/abs(c))-t1.e>t1.c),t1.c))/abs(11))+t1.b,t1.a,11)),t1.a)))))+19)/abs( - -t1.c)) FROM t1 WHERE NOT (~t1.e+t1.a+(abs(case when d+e+17*~t1.a-t1.a-a*~(abs(~f)/abs( -13))*+(t1.c | a)*t1.b=e then t1.d when ( -e) not between c and  -d then  -(t1.f) else t1.b end)/abs(19))>t1.f and 11<(11))}
} {0}
do_test randexpr-2.1587 {
  db eval {SELECT (abs((abs( -t1.e)/abs(~17+b)))/abs((case 19 when case when t1.b in (select ~cast(avg(19) AS integer) from t1 union select max(t1.b) from t1) then case when case when exists(select 1 from t1 where t1.c not between d and e) then (11) when t1.d<11 then ( -t1.f) else c end in (select count(distinct 17) from t1 union select ~min(a) | max( -t1.a)- -min(b) from t1) then d else 17 end when 13> -t1.b then f else d end then (t1.b) else c end))) FROM t1 WHERE d in (b,+(abs(t1.b | t1.e)/abs(coalesce((select max(t1.b) from t1 where t1.f=(e*+t1.b-t1.d+b-t1.f-t1.a-case case a*t1.b when coalesce((select max(f) from t1 where c<11),(a)) then  -t1.b else t1.f end when e then d else 19 end*t1.e+19)*d),t1.b))),t1.b)}
} {}
do_test randexpr-2.1588 {
  db eval {SELECT (abs((abs( -t1.e)/abs(~17+b)))/abs((case 19 when case when t1.b in (select ~cast(avg(19) AS integer) from t1 union select max(t1.b) from t1) then case when case when exists(select 1 from t1 where t1.c not between d and e) then (11) when t1.d<11 then ( -t1.f) else c end in (select count(distinct 17) from t1 union select ~min(a) | max( -t1.a)- -min(b) from t1) then d else 17 end when 13> -t1.b then f else d end then (t1.b) else c end))) FROM t1 WHERE NOT (d in (b,+(abs(t1.b | t1.e)/abs(coalesce((select max(t1.b) from t1 where t1.f=(e*+t1.b-t1.d+b-t1.f-t1.a-case case a*t1.b when coalesce((select max(f) from t1 where c<11),(a)) then  -t1.b else t1.f end when e then d else 19 end*t1.e+19)*d),t1.b))),t1.b))}
} {0}
do_test randexpr-2.1589 {
  db eval {SELECT (abs((abs( -t1.e)/abs(~17+b)))/abs((case 19 when case when t1.b in (select ~cast(avg(19) AS integer) from t1 union select max(t1.b) from t1) then case when case when exists(select 1 from t1 where t1.c not between d and e) then (11) when t1.d<11 then ( -t1.f) else c end in (select count(distinct 17) from t1 union select ~min(a) & max( -t1.a)- -min(b) from t1) then d else 17 end when 13> -t1.b then f else d end then (t1.b) else c end))) FROM t1 WHERE NOT (d in (b,+(abs(t1.b | t1.e)/abs(coalesce((select max(t1.b) from t1 where t1.f=(e*+t1.b-t1.d+b-t1.f-t1.a-case case a*t1.b when coalesce((select max(f) from t1 where c<11),(a)) then  -t1.b else t1.f end when e then d else 19 end*t1.e+19)*d),t1.b))),t1.b))}
} {0}
do_test randexpr-2.1590 {
  db eval {SELECT c | case when e<=(abs(case when case when not exists(select 1 from t1 where case when t1.f>case when 19>=17 or f in (19,c,t1.d) then t1.b else b end then t1.e else  -t1.b end*t1.d in (select t1.e from t1 union select c from t1)) then e else f end<>t1.d then  -a when (11 in (select b from t1 union select a from t1)) then 19 else t1.a end-(c))/abs(c))+t1.d | t1.a then  -19 else 17 end+t1.d-(t1.a) FROM t1 WHERE coalesce((select 13 from t1 where not exists(select 1 from t1 where t1.e*t1.d*t1.f>=(11) and d in (13,coalesce((select t1.f+t1.b from t1 where coalesce((select max(t1.a) from t1 where not (t1.d)<=t1.c),c) not in (t1.e,t1.d,b)),b)+f,d)) or (t1.f>f) or 11<=t1.d and 17<>13),a)<(t1.a)}
} {317}
do_test randexpr-2.1591 {
  db eval {SELECT c | case when e<=(abs(case when case when not exists(select 1 from t1 where case when t1.f>case when 19>=17 or f in (19,c,t1.d) then t1.b else b end then t1.e else  -t1.b end*t1.d in (select t1.e from t1 union select c from t1)) then e else f end<>t1.d then  -a when (11 in (select b from t1 union select a from t1)) then 19 else t1.a end-(c))/abs(c))+t1.d | t1.a then  -19 else 17 end+t1.d-(t1.a) FROM t1 WHERE NOT (coalesce((select 13 from t1 where not exists(select 1 from t1 where t1.e*t1.d*t1.f>=(11) and d in (13,coalesce((select t1.f+t1.b from t1 where coalesce((select max(t1.a) from t1 where not (t1.d)<=t1.c),c) not in (t1.e,t1.d,b)),b)+f,d)) or (t1.f>f) or 11<=t1.d and 17<>13),a)<(t1.a))}
} {}
do_test randexpr-2.1592 {
  db eval {SELECT c & case when e<=(abs(case when case when not exists(select 1 from t1 where case when t1.f>case when 19>=17 or f in (19,c,t1.d) then t1.b else b end then t1.e else  -t1.b end*t1.d in (select t1.e from t1 union select c from t1)) then e else f end<>t1.d then  -a when (11 in (select b from t1 union select a from t1)) then 19 else t1.a end-(c))/abs(c))+t1.d & t1.a then  -19 else 17 end+t1.d-(t1.a) FROM t1 WHERE coalesce((select 13 from t1 where not exists(select 1 from t1 where t1.e*t1.d*t1.f>=(11) and d in (13,coalesce((select t1.f+t1.b from t1 where coalesce((select max(t1.a) from t1 where not (t1.d)<=t1.c),c) not in (t1.e,t1.d,b)),b)+f,d)) or (t1.f>f) or 11<=t1.d and 17<>13),a)<(t1.a)}
} {300}
do_test randexpr-2.1593 {
  db eval {SELECT  -+t1.f*coalesce((select 17 from t1 where b in (coalesce((select f- -11 from t1 where not exists(select 1 from t1 where t1.d*a<=(case when  -17<t1.c or d in (c,t1.f,c) then 13 else 13 end-e+t1.d) or 17 in (select count(distinct t1.c) from t1 union select  -count(*)-~+cast(avg(11) AS integer) | cast(avg((t1.b)) AS integer)* -cast(avg(d) AS integer)+count(distinct t1.c) from t1))),19),t1.f,e)),(f))+11-e FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where ((exists(select 1 from t1 where not b | t1.d<t1.f)))) or t1.b | f | b>=d-coalesce((select a from t1 where coalesce((select max(19) from t1 where case when 13 between coalesce((select max(b) from t1 where t1.e in (c,t1.a,17)),(a)) and ((17)) then t1.b when f=t1.b then t1.f else 17 end>t1.b),e)+b*a>=t1.a),c))}
} {}
do_test randexpr-2.1594 {
  db eval {SELECT  -+t1.f*coalesce((select 17 from t1 where b in (coalesce((select f- -11 from t1 where not exists(select 1 from t1 where t1.d*a<=(case when  -17<t1.c or d in (c,t1.f,c) then 13 else 13 end-e+t1.d) or 17 in (select count(distinct t1.c) from t1 union select  -count(*)-~+cast(avg(11) AS integer) | cast(avg((t1.b)) AS integer)* -cast(avg(d) AS integer)+count(distinct t1.c) from t1))),19),t1.f,e)),(f))+11-e FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where ((exists(select 1 from t1 where not b | t1.d<t1.f)))) or t1.b | f | b>=d-coalesce((select a from t1 where coalesce((select max(19) from t1 where case when 13 between coalesce((select max(b) from t1 where t1.e in (c,t1.a,17)),(a)) and ((17)) then t1.b when f=t1.b then t1.f else 17 end>t1.b),e)+b*a>=t1.a),c)))}
} {-360489}
do_test randexpr-2.1595 {
  db eval {SELECT  -+t1.f*coalesce((select 17 from t1 where b in (coalesce((select f- -11 from t1 where not exists(select 1 from t1 where t1.d*a<=(case when  -17<t1.c or d in (c,t1.f,c) then 13 else 13 end-e+t1.d) or 17 in (select count(distinct t1.c) from t1 union select  -count(*)-~+cast(avg(11) AS integer) & cast(avg((t1.b)) AS integer)* -cast(avg(d) AS integer)+count(distinct t1.c) from t1))),19),t1.f,e)),(f))+11-e FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where ((exists(select 1 from t1 where not b | t1.d<t1.f)))) or t1.b | f | b>=d-coalesce((select a from t1 where coalesce((select max(19) from t1 where case when 13 between coalesce((select max(b) from t1 where t1.e in (c,t1.a,17)),(a)) and ((17)) then t1.b when f=t1.b then t1.f else 17 end>t1.b),e)+b*a>=t1.a),c)))}
} {-360489}
do_test randexpr-2.1596 {
  db eval {SELECT ~f+coalesce((select max(17+~a+t1.b) from t1 where 17>t1.c),c+case when t1.f*d not between t1.f-13 and ~t1.b then 19 when t1.a between case coalesce((select 17 from t1 where (e in (f,e,t1.b))),13) | t1.a* - -c*t1.f-a+a when e then t1.a else 13 end and b then b else e end)-11 FROM t1 WHERE 17=19*~d-case when (exists(select 1 from t1 where 17-e not between t1.b and f) or  -f not in ( -13,b,c) and t1.f not between t1.f and 13) then 13 else coalesce((select t1.f from t1 where 11 not in (a,(e),t1.f)),(t1.c)) end+t1.c or 17 in (select +(count(*)) from t1 union select ~+case  -min(t1.b) when case case max(19) when cast(avg((b)) AS integer) then (count(distinct t1.b)) else  -cast(avg(t1.b) AS integer) end when ( -max(t1.e)) then max(17) else  -count(distinct t1.f) end then cast(avg(19) AS integer) else count(*) end-count(*) |  -cast(avg(11) AS integer) from t1)}
} {}
do_test randexpr-2.1597 {
  db eval {SELECT ~f+coalesce((select max(17+~a+t1.b) from t1 where 17>t1.c),c+case when t1.f*d not between t1.f-13 and ~t1.b then 19 when t1.a between case coalesce((select 17 from t1 where (e in (f,e,t1.b))),13) | t1.a* - -c*t1.f-a+a when e then t1.a else 13 end and b then b else e end)-11 FROM t1 WHERE NOT (17=19*~d-case when (exists(select 1 from t1 where 17-e not between t1.b and f) or  -f not in ( -13,b,c) and t1.f not between t1.f and 13) then 13 else coalesce((select t1.f from t1 where 11 not in (a,(e),t1.f)),(t1.c)) end+t1.c or 17 in (select +(count(*)) from t1 union select ~+case  -min(t1.b) when case case max(19) when cast(avg((b)) AS integer) then (count(distinct t1.b)) else  -cast(avg(t1.b) AS integer) end when ( -max(t1.e)) then max(17) else  -count(distinct t1.f) end then cast(avg(19) AS integer) else count(*) end-count(*) |  -cast(avg(11) AS integer) from t1))}
} {-293}
do_test randexpr-2.1598 {
  db eval {SELECT ~f+coalesce((select max(17+~a+t1.b) from t1 where 17>t1.c),c+case when t1.f*d not between t1.f-13 and ~t1.b then 19 when t1.a between case coalesce((select 17 from t1 where (e in (f,e,t1.b))),13) & t1.a* - -c*t1.f-a+a when e then t1.a else 13 end and b then b else e end)-11 FROM t1 WHERE NOT (17=19*~d-case when (exists(select 1 from t1 where 17-e not between t1.b and f) or  -f not in ( -13,b,c) and t1.f not between t1.f and 13) then 13 else coalesce((select t1.f from t1 where 11 not in (a,(e),t1.f)),(t1.c)) end+t1.c or 17 in (select +(count(*)) from t1 union select ~+case  -min(t1.b) when case case max(19) when cast(avg((b)) AS integer) then (count(distinct t1.b)) else  -cast(avg(t1.b) AS integer) end when ( -max(t1.e)) then max(17) else  -count(distinct t1.f) end then cast(avg(19) AS integer) else count(*) end-count(*) |  -cast(avg(11) AS integer) from t1))}
} {-293}
do_test randexpr-2.1599 {
  db eval {SELECT (case when (select count(*) from t1)++t1.d+b*t1.e | t1.a+coalesce((select max(t1.d) from t1 where d-19<>c),t1.a)+t1.f in (select coalesce((select max(b) from t1 where t1.c-case when t1.c in (select c from t1 union select t1.f from t1) then f when t1.c not in ( -e,t1.e,11) then (t1.e) else 13 end in (f,t1.e,t1.f) or t1.a not between 19 and 17),t1.c) from t1 union select e from t1) then  -t1.e else t1.a end) FROM t1 WHERE 11*b+~ -coalesce((select t1.e from t1 where not exists(select 1 from t1 where 19=t1.f)),t1.d+(abs( -a)/abs(t1.d)))-t1.d-19<=11}
} {}
do_test randexpr-2.1600 {
  db eval {SELECT (case when (select count(*) from t1)++t1.d+b*t1.e | t1.a+coalesce((select max(t1.d) from t1 where d-19<>c),t1.a)+t1.f in (select coalesce((select max(b) from t1 where t1.c-case when t1.c in (select c from t1 union select t1.f from t1) then f when t1.c not in ( -e,t1.e,11) then (t1.e) else 13 end in (f,t1.e,t1.f) or t1.a not between 19 and 17),t1.c) from t1 union select e from t1) then  -t1.e else t1.a end) FROM t1 WHERE NOT (11*b+~ -coalesce((select t1.e from t1 where not exists(select 1 from t1 where 19=t1.f)),t1.d+(abs( -a)/abs(t1.d)))-t1.d-19<=11)}
} {100}
do_test randexpr-2.1601 {
  db eval {SELECT (case when (select count(*) from t1)++t1.d+b*t1.e & t1.a+coalesce((select max(t1.d) from t1 where d-19<>c),t1.a)+t1.f in (select coalesce((select max(b) from t1 where t1.c-case when t1.c in (select c from t1 union select t1.f from t1) then f when t1.c not in ( -e,t1.e,11) then (t1.e) else 13 end in (f,t1.e,t1.f) or t1.a not between 19 and 17),t1.c) from t1 union select e from t1) then  -t1.e else t1.a end) FROM t1 WHERE NOT (11*b+~ -coalesce((select t1.e from t1 where not exists(select 1 from t1 where 19=t1.f)),t1.d+(abs( -a)/abs(t1.d)))-t1.d-19<=11)}
} {100}
do_test randexpr-2.1602 {
  db eval {SELECT 19+~case when not not (select + - -min(f | f)-count(*)+count(*)-min(b)+count(distinct a) from t1)<=13-case when +13 between t1.a and a then 11 else 11 end and (11 not in (17, -t1.d,(f))) then t1.b | a-t1.f when t1.d<>17 then e else 17 end FROM t1 WHERE +t1.e-c<>case when c in (select d from t1 union select f from t1) then case (case when 13 in (select +c*a*13-11 from t1 union select b from t1) then t1.a when t1.f in ( -t1.f,11,a) or t1.a<=f or (exists(select 1 from t1 where 13>=d)) then t1.c else b end) when t1.d then 11 else e end when t1.b in (19,t1.d,(19)) then c else a end}
} {-482}
do_test randexpr-2.1603 {
  db eval {SELECT 19+~case when not not (select + - -min(f | f)-count(*)+count(*)-min(b)+count(distinct a) from t1)<=13-case when +13 between t1.a and a then 11 else 11 end and (11 not in (17, -t1.d,(f))) then t1.b | a-t1.f when t1.d<>17 then e else 17 end FROM t1 WHERE NOT (+t1.e-c<>case when c in (select d from t1 union select f from t1) then case (case when 13 in (select +c*a*13-11 from t1 union select b from t1) then t1.a when t1.f in ( -t1.f,11,a) or t1.a<=f or (exists(select 1 from t1 where 13>=d)) then t1.c else b end) when t1.d then 11 else e end when t1.b in (19,t1.d,(19)) then c else a end)}
} {}
do_test randexpr-2.1604 {
  db eval {SELECT 19+~case when not not (select + - -min(f & f)-count(*)+count(*)-min(b)+count(distinct a) from t1)<=13-case when +13 between t1.a and a then 11 else 11 end and (11 not in (17, -t1.d,(f))) then t1.b & a-t1.f when t1.d<>17 then e else 17 end FROM t1 WHERE +t1.e-c<>case when c in (select d from t1 union select f from t1) then case (case when 13 in (select +c*a*13-11 from t1 union select b from t1) then t1.a when t1.f in ( -t1.f,11,a) or t1.a<=f or (exists(select 1 from t1 where 13>=d)) then t1.c else b end) when t1.d then 11 else e end when t1.b in (19,t1.d,(19)) then c else a end}
} {-482}
do_test randexpr-2.1605 {
  db eval {SELECT (case when e not between 19 and t1.a then case coalesce((select t1.e from t1 where (exists(select 1 from t1 where c in (select case count(distinct t1.b) when max(b) then min((t1.d)) else count(distinct 11) end+ -count(*) |  - -count(distinct t1.e) from t1 union select min(f) from t1))) or (select min(17) from t1) not between 13 and b and  - -c<e),t1.a)+f when (select cast(avg(a) AS integer) from t1) then 19 else 19 end when not 13>=17 and 17 between t1.e and 13 or 13>d or 11>= -t1.d then a else 13 end)+t1.f FROM t1 WHERE b<=13}
} {}
do_test randexpr-2.1606 {
  db eval {SELECT (case when e not between 19 and t1.a then case coalesce((select t1.e from t1 where (exists(select 1 from t1 where c in (select case count(distinct t1.b) when max(b) then min((t1.d)) else count(distinct 11) end+ -count(*) |  - -count(distinct t1.e) from t1 union select min(f) from t1))) or (select min(17) from t1) not between 13 and b and  - -c<e),t1.a)+f when (select cast(avg(a) AS integer) from t1) then 19 else 19 end when not 13>=17 and 17 between t1.e and 13 or 13>d or 11>= -t1.d then a else 13 end)+t1.f FROM t1 WHERE NOT (b<=13)}
} {619}
do_test randexpr-2.1607 {
  db eval {SELECT (case when e not between 19 and t1.a then case coalesce((select t1.e from t1 where (exists(select 1 from t1 where c in (select case count(distinct t1.b) when max(b) then min((t1.d)) else count(distinct 11) end+ -count(*) &  - -count(distinct t1.e) from t1 union select min(f) from t1))) or (select min(17) from t1) not between 13 and b and  - -c<e),t1.a)+f when (select cast(avg(a) AS integer) from t1) then 19 else 19 end when not 13>=17 and 17 between t1.e and 13 or 13>d or 11>= -t1.d then a else 13 end)+t1.f FROM t1 WHERE NOT (b<=13)}
} {619}
do_test randexpr-2.1608 {
  db eval {SELECT case c when d then +e else 17-e+case when exists(select 1 from t1 where not  -f<19) then (a) when t1.a between case when t1.d- -~t1.a+(select case min(t1.a) when count(distinct t1.e) then max(f) else max(t1.f) end-min(t1.b) from t1)*(select max(17) from t1)+e*13-f in (t1.d,f,d) then f else t1.b end and b then t1.d else d end end FROM t1 WHERE b<>c*f}
} {-83}
do_test randexpr-2.1609 {
  db eval {SELECT case c when d then +e else 17-e+case when exists(select 1 from t1 where not  -f<19) then (a) when t1.a between case when t1.d- -~t1.a+(select case min(t1.a) when count(distinct t1.e) then max(f) else max(t1.f) end-min(t1.b) from t1)*(select max(17) from t1)+e*13-f in (t1.d,f,d) then f else t1.b end and b then t1.d else d end end FROM t1 WHERE NOT (b<>c*f)}
} {}
do_test randexpr-2.1610 {
  db eval {SELECT  -(select min(coalesce((select max(case when d>=t1.c then f-t1.c else t1.b end) from t1 where case when (17)-13<=(abs(a-e)/abs(19-t1.a)) then (select  -max(c++t1.d | +case when 19 in (select b from t1 union select t1.c from t1) then t1.d else f end) from t1) else 11-19 end not in (e,t1.e,17)),c)+t1.b) from t1) FROM t1 WHERE  -case when case when e=case when not 17>+t1.d and b*b in (e, -d,13) then  -b*c else t1.e end then t1.f when e>=a then c else 19 end+t1.e<> -t1.d then 11 when not 11<>13 then 13 else e end*17*t1.d+t1.f in (select e from t1 union select t1.b from t1)}
} {}
do_test randexpr-2.1611 {
  db eval {SELECT  -(select min(coalesce((select max(case when d>=t1.c then f-t1.c else t1.b end) from t1 where case when (17)-13<=(abs(a-e)/abs(19-t1.a)) then (select  -max(c++t1.d | +case when 19 in (select b from t1 union select t1.c from t1) then t1.d else f end) from t1) else 11-19 end not in (e,t1.e,17)),c)+t1.b) from t1) FROM t1 WHERE NOT ( -case when case when e=case when not 17>+t1.d and b*b in (e, -d,13) then  -b*c else t1.e end then t1.f when e>=a then c else 19 end+t1.e<> -t1.d then 11 when not 11<>13 then 13 else e end*17*t1.d+t1.f in (select e from t1 union select t1.b from t1))}
} {-500}
do_test randexpr-2.1612 {
  db eval {SELECT  -(select min(coalesce((select max(case when d>=t1.c then f-t1.c else t1.b end) from t1 where case when (17)-13<=(abs(a-e)/abs(19-t1.a)) then (select  -max(c++t1.d & +case when 19 in (select b from t1 union select t1.c from t1) then t1.d else f end) from t1) else 11-19 end not in (e,t1.e,17)),c)+t1.b) from t1) FROM t1 WHERE NOT ( -case when case when e=case when not 17>+t1.d and b*b in (e, -d,13) then  -b*c else t1.e end then t1.f when e>=a then c else 19 end+t1.e<> -t1.d then 11 when not 11<>13 then 13 else e end*17*t1.d+t1.f in (select e from t1 union select t1.b from t1))}
} {-500}
do_test randexpr-2.1613 {
  db eval {SELECT case when b<=(abs(19)/abs(t1.a)) | 13-b then +f | ~d else ~case when case case when t1.c in (select 13+19 from t1 union select t1.a from t1) then  -c when 13 between t1.a and b then 17 else c end when t1.c then e else 11 end between t1.e and 11 or f in (select 17 from t1 union select (a) from t1) then t1.f-d when t1.b in (select t1.f from t1 union select t1.f from t1) then t1.c else t1.b end end FROM t1 WHERE (t1.e in (select +17 from t1 union select 11 from t1))}
} {}
do_test randexpr-2.1614 {
  db eval {SELECT case when b<=(abs(19)/abs(t1.a)) | 13-b then +f | ~d else ~case when case case when t1.c in (select 13+19 from t1 union select t1.a from t1) then  -c when 13 between t1.a and b then 17 else c end when t1.c then e else 11 end between t1.e and 11 or f in (select 17 from t1 union select (a) from t1) then t1.f-d when t1.b in (select t1.f from t1 union select t1.f from t1) then t1.c else t1.b end end FROM t1 WHERE NOT ((t1.e in (select +17 from t1 union select 11 from t1)))}
} {-201}
do_test randexpr-2.1615 {
  db eval {SELECT case when b<=(abs(19)/abs(t1.a)) & 13-b then +f & ~d else ~case when case case when t1.c in (select 13+19 from t1 union select t1.a from t1) then  -c when 13 between t1.a and b then 17 else c end when t1.c then e else 11 end between t1.e and 11 or f in (select 17 from t1 union select (a) from t1) then t1.f-d when t1.b in (select t1.f from t1 union select t1.f from t1) then t1.c else t1.b end end FROM t1 WHERE NOT ((t1.e in (select +17 from t1 union select 11 from t1)))}
} {-201}
do_test randexpr-2.1616 {
  db eval {SELECT coalesce((select coalesce((select coalesce((select ~e+coalesce((select  -e-+17 from t1 where (select cast(avg(11) AS integer) from t1) between case when +13+13 between 19 and t1.c then t1.d else 13 end and 13),t1.c)* -(19)+17-t1.a+e from t1 where t1.b>=t1.f),t1.b) | t1.f from t1 where f in (select d from t1 union select 11 from t1)),t1.b) from t1 where t1.b=13),t1.d) FROM t1 WHERE t1.f<>(abs(t1.c)/abs(t1.a))}
} {400}
do_test randexpr-2.1617 {
  db eval {SELECT coalesce((select coalesce((select coalesce((select ~e+coalesce((select  -e-+17 from t1 where (select cast(avg(11) AS integer) from t1) between case when +13+13 between 19 and t1.c then t1.d else 13 end and 13),t1.c)* -(19)+17-t1.a+e from t1 where t1.b>=t1.f),t1.b) | t1.f from t1 where f in (select d from t1 union select 11 from t1)),t1.b) from t1 where t1.b=13),t1.d) FROM t1 WHERE NOT (t1.f<>(abs(t1.c)/abs(t1.a)))}
} {}
do_test randexpr-2.1618 {
  db eval {SELECT coalesce((select coalesce((select coalesce((select ~e+coalesce((select  -e-+17 from t1 where (select cast(avg(11) AS integer) from t1) between case when +13+13 between 19 and t1.c then t1.d else 13 end and 13),t1.c)* -(19)+17-t1.a+e from t1 where t1.b>=t1.f),t1.b) & t1.f from t1 where f in (select d from t1 union select 11 from t1)),t1.b) from t1 where t1.b=13),t1.d) FROM t1 WHERE t1.f<>(abs(t1.c)/abs(t1.a))}
} {400}
do_test randexpr-2.1619 {
  db eval {SELECT (abs(a)/abs(coalesce((select case when coalesce((select d from t1 where d+case (coalesce((select max(e) from t1 where 17+f*13-(case 19 when t1.f then 17 else t1.e end)<>b),17)) when t1.e then t1.e else t1.a end- -13+ -t1.f between b and f),11)+t1.d between 13 and t1.d then b else (19) end-t1.c from t1 where c in (select t1.e from t1 union select f from t1)),b))) FROM t1 WHERE d>t1.a}
} {0}
do_test randexpr-2.1620 {
  db eval {SELECT (abs(a)/abs(coalesce((select case when coalesce((select d from t1 where d+case (coalesce((select max(e) from t1 where 17+f*13-(case 19 when t1.f then 17 else t1.e end)<>b),17)) when t1.e then t1.e else t1.a end- -13+ -t1.f between b and f),11)+t1.d between 13 and t1.d then b else (19) end-t1.c from t1 where c in (select t1.e from t1 union select f from t1)),b))) FROM t1 WHERE NOT (d>t1.a)}
} {}
do_test randexpr-2.1621 {
  db eval {SELECT coalesce((select case when coalesce((select max(coalesce((select max(e-c-coalesce((select max(c) from t1 where 19 between 13 and 13),(abs(case when c<=17 or f in (t1.a, -17,t1.f) then b else t1.c end)/abs(e))+t1.b)) from t1 where not exists(select 1 from t1 where t1.e>=b)),e)) from t1 where not exists(select 1 from t1 where 13<=t1.b or t1.f in (select d from t1 union select t1.d from t1))),17) in (select 11 from t1 union select t1.d from t1) then c else t1.e end from t1 where t1.c in (select b from t1 union select b from t1)),f) | t1.c FROM t1 WHERE c<=e}
} {892}
do_test randexpr-2.1622 {
  db eval {SELECT coalesce((select case when coalesce((select max(coalesce((select max(e-c-coalesce((select max(c) from t1 where 19 between 13 and 13),(abs(case when c<=17 or f in (t1.a, -17,t1.f) then b else t1.c end)/abs(e))+t1.b)) from t1 where not exists(select 1 from t1 where t1.e>=b)),e)) from t1 where not exists(select 1 from t1 where 13<=t1.b or t1.f in (select d from t1 union select t1.d from t1))),17) in (select 11 from t1 union select t1.d from t1) then c else t1.e end from t1 where t1.c in (select b from t1 union select b from t1)),f) | t1.c FROM t1 WHERE NOT (c<=e)}
} {}
do_test randexpr-2.1623 {
  db eval {SELECT coalesce((select case when coalesce((select max(coalesce((select max(e-c-coalesce((select max(c) from t1 where 19 between 13 and 13),(abs(case when c<=17 or f in (t1.a, -17,t1.f) then b else t1.c end)/abs(e))+t1.b)) from t1 where not exists(select 1 from t1 where t1.e>=b)),e)) from t1 where not exists(select 1 from t1 where 13<=t1.b or t1.f in (select d from t1 union select t1.d from t1))),17) in (select 11 from t1 union select t1.d from t1) then c else t1.e end from t1 where t1.c in (select b from t1 union select b from t1)),f) & t1.c FROM t1 WHERE c<=e}
} {8}
do_test randexpr-2.1624 {
  db eval {SELECT (select +max(case when t1.a in (f,case when f in (t1.b,+ -(select count(*)-min(17) from t1)+19,11) then  -19 else 19 end*(abs(b)/abs(a)),a) then t1.b when (case a when 17 then c | t1.d else t1.c end+11)-13 in (b,11,f) then b else 17 end*17) from t1) FROM t1 WHERE c between (abs(case when (abs(d+19)/abs(19))-c*t1.d+t1.e+case when  -(abs(case when exists(select 1 from t1 where exists(select 1 from t1 where 13 in (select cast(avg(t1.b) AS integer) from t1 union select max(d) from t1))) then ~c when t1.d not between 13 and d then  -t1.b else  -f end)/abs(t1.b))+d in (t1.e,(13),e) then e when (b)<>d then t1.b else 19 end in (select 17 from t1 union select e from t1) then t1.e else t1.e end)/abs(t1.f)) and t1.e}
} {3400}
do_test randexpr-2.1625 {
  db eval {SELECT (select +max(case when t1.a in (f,case when f in (t1.b,+ -(select count(*)-min(17) from t1)+19,11) then  -19 else 19 end*(abs(b)/abs(a)),a) then t1.b when (case a when 17 then c | t1.d else t1.c end+11)-13 in (b,11,f) then b else 17 end*17) from t1) FROM t1 WHERE NOT (c between (abs(case when (abs(d+19)/abs(19))-c*t1.d+t1.e+case when  -(abs(case when exists(select 1 from t1 where exists(select 1 from t1 where 13 in (select cast(avg(t1.b) AS integer) from t1 union select max(d) from t1))) then ~c when t1.d not between 13 and d then  -t1.b else  -f end)/abs(t1.b))+d in (t1.e,(13),e) then e when (b)<>d then t1.b else 19 end in (select 17 from t1 union select e from t1) then t1.e else t1.e end)/abs(t1.f)) and t1.e)}
} {}
do_test randexpr-2.1626 {
  db eval {SELECT (select +max(case when t1.a in (f,case when f in (t1.b,+ -(select count(*)-min(17) from t1)+19,11) then  -19 else 19 end*(abs(b)/abs(a)),a) then t1.b when (case a when 17 then c & t1.d else t1.c end+11)-13 in (b,11,f) then b else 17 end*17) from t1) FROM t1 WHERE c between (abs(case when (abs(d+19)/abs(19))-c*t1.d+t1.e+case when  -(abs(case when exists(select 1 from t1 where exists(select 1 from t1 where 13 in (select cast(avg(t1.b) AS integer) from t1 union select max(d) from t1))) then ~c when t1.d not between 13 and d then  -t1.b else  -f end)/abs(t1.b))+d in (t1.e,(13),e) then e when (b)<>d then t1.b else 19 end in (select 17 from t1 union select e from t1) then t1.e else t1.e end)/abs(t1.f)) and t1.e}
} {3400}
do_test randexpr-2.1627 {
  db eval {SELECT case when c between f and t1.f*t1.f then (coalesce((select max(d | coalesce((select 19+t1.c from t1 where t1.a between d and (b)),(t1.f))*t1.f*t1.b) from t1 where 11>13 or 19 not between 13 and 11 or t1.a>=b or b>t1.e or 11=a and t1.b<=d),f)) when a in (select min(t1.b)-abs(count(distinct 11)) from t1 union select cast(avg(t1.d) AS integer) from t1) then f else c end-t1.e FROM t1 WHERE (t1.f+a)*t1.b+(abs(b)/abs(b)) in (t1.e,case when 11-t1.a+e+case 19 when +11+ -t1.b then case ~t1.f*(f)-b when d then a else ( -c) end*(c) else t1.a end+t1.a not in (17,11,t1.e) then t1.b else (d) end*19,t1.a)}
} {}
do_test randexpr-2.1628 {
  db eval {SELECT case when c between f and t1.f*t1.f then (coalesce((select max(d | coalesce((select 19+t1.c from t1 where t1.a between d and (b)),(t1.f))*t1.f*t1.b) from t1 where 11>13 or 19 not between 13 and 11 or t1.a>=b or b>t1.e or 11=a and t1.b<=d),f)) when a in (select min(t1.b)-abs(count(distinct 11)) from t1 union select cast(avg(t1.d) AS integer) from t1) then f else c end-t1.e FROM t1 WHERE NOT ((t1.f+a)*t1.b+(abs(b)/abs(b)) in (t1.e,case when 11-t1.a+e+case 19 when +11+ -t1.b then case ~t1.f*(f)-b when d then a else ( -c) end*(c) else t1.a end+t1.a not in (17,11,t1.e) then t1.b else (d) end*19,t1.a))}
} {-200}
do_test randexpr-2.1629 {
  db eval {SELECT case when c between f and t1.f*t1.f then (coalesce((select max(d & coalesce((select 19+t1.c from t1 where t1.a between d and (b)),(t1.f))*t1.f*t1.b) from t1 where 11>13 or 19 not between 13 and 11 or t1.a>=b or b>t1.e or 11=a and t1.b<=d),f)) when a in (select min(t1.b)-abs(count(distinct 11)) from t1 union select cast(avg(t1.d) AS integer) from t1) then f else c end-t1.e FROM t1 WHERE NOT ((t1.f+a)*t1.b+(abs(b)/abs(b)) in (t1.e,case when 11-t1.a+e+case 19 when +11+ -t1.b then case ~t1.f*(f)-b when d then a else ( -c) end*(c) else t1.a end+t1.a not in (17,11,t1.e) then t1.b else (d) end*19,t1.a))}
} {-200}
do_test randexpr-2.1630 {
  db eval {SELECT coalesce((select max(f) from t1 where (a+13>19*t1.e+a | a | 17*e or ~c not between 17 and 19*(select +(~count(distinct e)*(cast(avg(t1.b) AS integer))) | count(distinct t1.c) from t1)-f and t1.a*t1.f+c not between t1.f and f)),t1.c*(t1.e)*e) FROM t1 WHERE case case t1.f when ~17 then 11 else t1.d end when a then t1.a else e end>d*11}
} {}
do_test randexpr-2.1631 {
  db eval {SELECT coalesce((select max(f) from t1 where (a+13>19*t1.e+a | a | 17*e or ~c not between 17 and 19*(select +(~count(distinct e)*(cast(avg(t1.b) AS integer))) | count(distinct t1.c) from t1)-f and t1.a*t1.f+c not between t1.f and f)),t1.c*(t1.e)*e) FROM t1 WHERE NOT (case case t1.f when ~17 then 11 else t1.d end when a then t1.a else e end>d*11)}
} {600}
do_test randexpr-2.1632 {
  db eval {SELECT coalesce((select max(f) from t1 where (a+13>19*t1.e+a & a & 17*e or ~c not between 17 and 19*(select +(~count(distinct e)*(cast(avg(t1.b) AS integer))) & count(distinct t1.c) from t1)-f and t1.a*t1.f+c not between t1.f and f)),t1.c*(t1.e)*e) FROM t1 WHERE NOT (case case t1.f when ~17 then 11 else t1.d end when a then t1.a else e end>d*11)}
} {600}
do_test randexpr-2.1633 {
  db eval {SELECT case when e<11 then (case case t1.a when coalesce((select max(11) from t1 where t1.c<=case when exists(select 1 from t1 where 13=e) then case when c not in (t1.f,t1.e,c) then c else ~(c)+d*f end when a>b then 11 else 11 end),(t1.c)) | 11 then b else t1.a end when 11 then t1.f else t1.d end) when d<c then t1.f else (e) end | t1.d FROM t1 WHERE 17 in (select case t1.e+ -coalesce((select max(coalesce((select max(e+t1.a) from t1 where  -t1.a in (select min(coalesce((select 11 from t1 where  -t1.a in (select a from t1 union select t1.e from t1)),t1.c))+(~cast(avg(f) AS integer)) from t1 union select case abs(( -count(distinct t1.e))) when count(distinct  -11) then count(distinct t1.b) else (max(t1.c)) end from t1)),t1.f)) from t1 where t1.c in (t1.c,t1.f,f)),c)-t1.b-t1.c-(t1.d) when 17 then 17 else t1.c end from t1 union select c from t1)}
} {}
do_test randexpr-2.1634 {
  db eval {SELECT case when e<11 then (case case t1.a when coalesce((select max(11) from t1 where t1.c<=case when exists(select 1 from t1 where 13=e) then case when c not in (t1.f,t1.e,c) then c else ~(c)+d*f end when a>b then 11 else 11 end),(t1.c)) | 11 then b else t1.a end when 11 then t1.f else t1.d end) when d<c then t1.f else (e) end | t1.d FROM t1 WHERE NOT (17 in (select case t1.e+ -coalesce((select max(coalesce((select max(e+t1.a) from t1 where  -t1.a in (select min(coalesce((select 11 from t1 where  -t1.a in (select a from t1 union select t1.e from t1)),t1.c))+(~cast(avg(f) AS integer)) from t1 union select case abs(( -count(distinct t1.e))) when count(distinct  -11) then count(distinct t1.b) else (max(t1.c)) end from t1)),t1.f)) from t1 where t1.c in (t1.c,t1.f,f)),c)-t1.b-t1.c-(t1.d) when 17 then 17 else t1.c end from t1 union select c from t1))}
} {500}
do_test randexpr-2.1635 {
  db eval {SELECT case when e<11 then (case case t1.a when coalesce((select max(11) from t1 where t1.c<=case when exists(select 1 from t1 where 13=e) then case when c not in (t1.f,t1.e,c) then c else ~(c)+d*f end when a>b then 11 else 11 end),(t1.c)) & 11 then b else t1.a end when 11 then t1.f else t1.d end) when d<c then t1.f else (e) end & t1.d FROM t1 WHERE NOT (17 in (select case t1.e+ -coalesce((select max(coalesce((select max(e+t1.a) from t1 where  -t1.a in (select min(coalesce((select 11 from t1 where  -t1.a in (select a from t1 union select t1.e from t1)),t1.c))+(~cast(avg(f) AS integer)) from t1 union select case abs(( -count(distinct t1.e))) when count(distinct  -11) then count(distinct t1.b) else (max(t1.c)) end from t1)),t1.f)) from t1 where t1.c in (t1.c,t1.f,f)),c)-t1.b-t1.c-(t1.d) when 17 then 17 else t1.c end from t1 union select c from t1))}
} {400}
do_test randexpr-2.1636 {
  db eval {SELECT case coalesce((select a from t1 where exists(select 1 from t1 where t1.e>f)),17) when coalesce((select max((b)) from t1 where not case (abs(t1.b)/abs(t1.d+t1.b)) when t1.d then f-coalesce((select max(a) from t1 where case t1.e when c then c else 11 end not between b and  -t1.b),t1.e) else t1.a end-17 between t1.e and f and (t1.e<e) and t1.d>17), -e)*19 then t1.b else t1.c end FROM t1 WHERE not  -coalesce((select d from t1 where exists(select 1 from t1 where coalesce((select max(case when 11 not in (case when d*11<>17-(t1.e) then 13 else c end,t1.d,t1.c) then e else t1.c end) from t1 where t1.d<= - -d),11) in (select + -case (+ -cast(avg(19) AS integer)+ - -(count(*))* -count(distinct ((t1.e)))*max(d)) when count(*) then max(b) else count(*) end from t1 union select count(*) from t1))),t1.d)+13>a}
} {300}
do_test randexpr-2.1637 {
  db eval {SELECT case coalesce((select a from t1 where exists(select 1 from t1 where t1.e>f)),17) when coalesce((select max((b)) from t1 where not case (abs(t1.b)/abs(t1.d+t1.b)) when t1.d then f-coalesce((select max(a) from t1 where case t1.e when c then c else 11 end not between b and  -t1.b),t1.e) else t1.a end-17 between t1.e and f and (t1.e<e) and t1.d>17), -e)*19 then t1.b else t1.c end FROM t1 WHERE NOT (not  -coalesce((select d from t1 where exists(select 1 from t1 where coalesce((select max(case when 11 not in (case when d*11<>17-(t1.e) then 13 else c end,t1.d,t1.c) then e else t1.c end) from t1 where t1.d<= - -d),11) in (select + -case (+ -cast(avg(19) AS integer)+ - -(count(*))* -count(distinct ((t1.e)))*max(d)) when count(*) then max(b) else count(*) end from t1 union select count(*) from t1))),t1.d)+13>a)}
} {}
do_test randexpr-2.1638 {
  db eval {SELECT ~coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.e-t1.e in (select t1.c+case d when case when not case when t1.f between ( -t1.a) and (b) or 11<>19 then (abs(t1.e)/abs(t1.f)) else e end between t1.b and e then t1.d | t1.e when 19>b then 13 else t1.a end*e*13 | 11+t1.f then t1.b else 17 end from t1 union select e from t1))),t1.a-t1.b)*t1.d*e FROM t1 WHERE d in (select 11 from t1 union select +11 from t1) or coalesce((select max(coalesce((select b-e*case when (c) | e | b in (select 19*t1.d from t1 union select t1.e from t1) then t1.d else e end from t1 where t1.a<11),d)) from t1 where (not ((17 not in ( -t1.a,e,d) and 13<11) and f>=11))),t1.b)<11}
} {}
do_test randexpr-2.1639 {
  db eval {SELECT ~coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.e-t1.e in (select t1.c+case d when case when not case when t1.f between ( -t1.a) and (b) or 11<>19 then (abs(t1.e)/abs(t1.f)) else e end between t1.b and e then t1.d | t1.e when 19>b then 13 else t1.a end*e*13 | 11+t1.f then t1.b else 17 end from t1 union select e from t1))),t1.a-t1.b)*t1.d*e FROM t1 WHERE NOT (d in (select 11 from t1 union select +11 from t1) or coalesce((select max(coalesce((select b-e*case when (c) | e | b in (select 19*t1.d from t1 union select t1.e from t1) then t1.d else e end from t1 where t1.a<11),d)) from t1 where (not ((17 not in ( -t1.a,e,d) and 13<11) and f>=11))),t1.b)<11)}
} {-3600000}
do_test randexpr-2.1640 {
  db eval {SELECT ~coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.e-t1.e in (select t1.c+case d when case when not case when t1.f between ( -t1.a) and (b) or 11<>19 then (abs(t1.e)/abs(t1.f)) else e end between t1.b and e then t1.d & t1.e when 19>b then 13 else t1.a end*e*13 & 11+t1.f then t1.b else 17 end from t1 union select e from t1))),t1.a-t1.b)*t1.d*e FROM t1 WHERE NOT (d in (select 11 from t1 union select +11 from t1) or coalesce((select max(coalesce((select b-e*case when (c) | e | b in (select 19*t1.d from t1 union select t1.e from t1) then t1.d else e end from t1 where t1.a<11),d)) from t1 where (not ((17 not in ( -t1.a,e,d) and 13<11) and f>=11))),t1.b)<11)}
} {-3600000}
do_test randexpr-2.1641 {
  db eval {SELECT case b-f when t1.a then  -case when not (case t1.a when (select case cast(avg(c) AS integer) when count(distinct t1.f) then +max(t1.e) |  -((( -(count(*))))) else cast(avg(f) AS integer) end from t1)-b then a else coalesce((select t1.a from t1 where (e<d)),t1.d) end not between t1.a and t1.f) then coalesce((select max(13) from t1 where (13)=e),t1.d) when d not in (a,t1.f,c) then  -11 else t1.a end else 17 end FROM t1 WHERE  -13*t1.b-c-e+case when t1.b | b in (select cast(avg(t1.a | +(select abs(+count(*))-count(distinct (t1.f))*abs(min(t1.d))+count(distinct case when exists(select 1 from t1 where (19)>=a and e>c) or c not between a and 19 then 11 when t1.b not between e and t1.a then 17 else 11 end) from t1)) AS integer) from t1 union select cast(avg((abs(b)/abs(t1.f))) AS integer) from t1) then 17 else t1.e end>=a}
} {}
do_test randexpr-2.1642 {
  db eval {SELECT case b-f when t1.a then  -case when not (case t1.a when (select case cast(avg(c) AS integer) when count(distinct t1.f) then +max(t1.e) |  -((( -(count(*))))) else cast(avg(f) AS integer) end from t1)-b then a else coalesce((select t1.a from t1 where (e<d)),t1.d) end not between t1.a and t1.f) then coalesce((select max(13) from t1 where (13)=e),t1.d) when d not in (a,t1.f,c) then  -11 else t1.a end else 17 end FROM t1 WHERE NOT ( -13*t1.b-c-e+case when t1.b | b in (select cast(avg(t1.a | +(select abs(+count(*))-count(distinct (t1.f))*abs(min(t1.d))+count(distinct case when exists(select 1 from t1 where (19)>=a and e>c) or c not between a and 19 then 11 when t1.b not between e and t1.a then 17 else 11 end) from t1)) AS integer) from t1 union select cast(avg((abs(b)/abs(t1.f))) AS integer) from t1) then 17 else t1.e end>=a)}
} {17}
do_test randexpr-2.1643 {
  db eval {SELECT case b-f when t1.a then  -case when not (case t1.a when (select case cast(avg(c) AS integer) when count(distinct t1.f) then +max(t1.e) &  -((( -(count(*))))) else cast(avg(f) AS integer) end from t1)-b then a else coalesce((select t1.a from t1 where (e<d)),t1.d) end not between t1.a and t1.f) then coalesce((select max(13) from t1 where (13)=e),t1.d) when d not in (a,t1.f,c) then  -11 else t1.a end else 17 end FROM t1 WHERE NOT ( -13*t1.b-c-e+case when t1.b | b in (select cast(avg(t1.a | +(select abs(+count(*))-count(distinct (t1.f))*abs(min(t1.d))+count(distinct case when exists(select 1 from t1 where (19)>=a and e>c) or c not between a and 19 then 11 when t1.b not between e and t1.a then 17 else 11 end) from t1)) AS integer) from t1 union select cast(avg((abs(b)/abs(t1.f))) AS integer) from t1) then 17 else t1.e end>=a)}
} {17}
do_test randexpr-2.1644 {
  db eval {SELECT coalesce((select max((abs(t1.b*t1.d*case when f*t1.d<a*17* -t1.c+coalesce((select max(a) from t1 where 11>b),t1.d*19)*e+c+t1.d then t1.c when exists(select 1 from t1 where 13>=e) then t1.e else f end-f*e)/abs(13))) from t1 where (a)<=t1.d),13) | e FROM t1 WHERE +t1.c>t1.d}
} {}
do_test randexpr-2.1645 {
  db eval {SELECT coalesce((select max((abs(t1.b*t1.d*case when f*t1.d<a*17* -t1.c+coalesce((select max(a) from t1 where 11>b),t1.d*19)*e+c+t1.d then t1.c when exists(select 1 from t1 where 13>=e) then t1.e else f end-f*e)/abs(13))) from t1 where (a)<=t1.d),13) | e FROM t1 WHERE NOT (+t1.c>t1.d)}
} {1823220}
do_test randexpr-2.1646 {
  db eval {SELECT coalesce((select max((abs(t1.b*t1.d*case when f*t1.d<a*17* -t1.c+coalesce((select max(a) from t1 where 11>b),t1.d*19)*e+c+t1.d then t1.c when exists(select 1 from t1 where 13>=e) then t1.e else f end-f*e)/abs(13))) from t1 where (a)<=t1.d),13) & e FROM t1 WHERE NOT (+t1.c>t1.d)}
} {356}
do_test randexpr-2.1647 {
  db eval {SELECT case when not exists(select 1 from t1 where 17>=19) or t1.c in (select min(19)-(cast(avg(f) AS integer)) from t1 union select cast(avg(19) AS integer) from t1) and e in (select ~+count(distinct 19)*max(13) from t1 union select min(17+d) from t1) or t1.f in (select count(*) from t1 union select (max(a)) from t1) then coalesce((select  -d- -t1.d from t1 where b in (select cast(avg(c) AS integer) from t1 union select (count(*)) from t1) or b<=11),e) else t1.e end FROM t1 WHERE a< -13}
} {}
do_test randexpr-2.1648 {
  db eval {SELECT case when not exists(select 1 from t1 where 17>=19) or t1.c in (select min(19)-(cast(avg(f) AS integer)) from t1 union select cast(avg(19) AS integer) from t1) and e in (select ~+count(distinct 19)*max(13) from t1 union select min(17+d) from t1) or t1.f in (select count(*) from t1 union select (max(a)) from t1) then coalesce((select  -d- -t1.d from t1 where b in (select cast(avg(c) AS integer) from t1 union select (count(*)) from t1) or b<=11),e) else t1.e end FROM t1 WHERE NOT (a< -13)}
} {500}
do_test randexpr-2.1649 {
  db eval {SELECT f+case when 17-t1.f in (select ~count(distinct (abs((abs(c)/abs(c)))/abs((abs(11)/abs(+case  -t1.a when t1.d then  -13 else 17 end))))-t1.c) from t1 union select ~case cast(avg(t1.c) AS integer) when  -~ -count(*)*max((t1.f))+count(*) then (min(d)) else max(a) end-count(distinct t1.a)+ -count(*)-count(*) from t1) then d when b not between t1.f and t1.e then a else 11 end+t1.a FROM t1 WHERE (exists(select 1 from t1 where case when exists(select 1 from t1 where case when (t1.e+case (t1.b) when f then case t1.c when 11 |  -13-coalesce((select max(d) from t1 where c not in ( -t1.e,t1.c,17) and t1.c<17),e)*17+t1.a then t1.b else 11 end else d end)+t1.f not in (d,13,d) then f else t1.d end not between (c) and f) then t1.e else f end-t1.c in (t1.b,t1.a,f)))}
} {}
do_test randexpr-2.1650 {
  db eval {SELECT f+case when 17-t1.f in (select ~count(distinct (abs((abs(c)/abs(c)))/abs((abs(11)/abs(+case  -t1.a when t1.d then  -13 else 17 end))))-t1.c) from t1 union select ~case cast(avg(t1.c) AS integer) when  -~ -count(*)*max((t1.f))+count(*) then (min(d)) else max(a) end-count(distinct t1.a)+ -count(*)-count(*) from t1) then d when b not between t1.f and t1.e then a else 11 end+t1.a FROM t1 WHERE NOT ((exists(select 1 from t1 where case when exists(select 1 from t1 where case when (t1.e+case (t1.b) when f then case t1.c when 11 |  -13-coalesce((select max(d) from t1 where c not in ( -t1.e,t1.c,17) and t1.c<17),e)*17+t1.a then t1.b else 11 end else d end)+t1.f not in (d,13,d) then f else t1.d end not between (c) and f) then t1.e else f end-t1.c in (t1.b,t1.a,f))))}
} {800}
do_test randexpr-2.1651 {
  db eval {SELECT case ~t1.d when case when c in (select count(*) from t1 union select +(( -min(17)-~cast(avg(t1.c) AS integer)))* -min(t1.f)-max(t1.d)*count(*) | cast(avg(17) AS integer) from t1) then 17*e*t1.f | t1.e else 19-coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where t1.c>=e)),t1.f) end | 13+13 then 17 else t1.f end FROM t1 WHERE (not exists(select 1 from t1 where +c-19 in (select (~((min(b)))-+count(*) | cast(avg(case when 11 in (select (abs((t1.b))/abs(e)) from t1 union select (17) from t1) then t1.c when  -a<=b then t1.a else t1.e end) AS integer)++case max(t1.b) when cast(avg(c) AS integer) then count(*) else cast(avg(f) AS integer) end |  -count(*)-(count(*))*max(t1.e)*count(*)*cast(avg(a) AS integer))+min(11) from t1 union select max((d)) from t1)))}
} {600}
do_test randexpr-2.1652 {
  db eval {SELECT case ~t1.d when case when c in (select count(*) from t1 union select +(( -min(17)-~cast(avg(t1.c) AS integer)))* -min(t1.f)-max(t1.d)*count(*) | cast(avg(17) AS integer) from t1) then 17*e*t1.f | t1.e else 19-coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where t1.c>=e)),t1.f) end | 13+13 then 17 else t1.f end FROM t1 WHERE NOT ((not exists(select 1 from t1 where +c-19 in (select (~((min(b)))-+count(*) | cast(avg(case when 11 in (select (abs((t1.b))/abs(e)) from t1 union select (17) from t1) then t1.c when  -a<=b then t1.a else t1.e end) AS integer)++case max(t1.b) when cast(avg(c) AS integer) then count(*) else cast(avg(f) AS integer) end |  -count(*)-(count(*))*max(t1.e)*count(*)*cast(avg(a) AS integer))+min(11) from t1 union select max((d)) from t1))))}
} {}
do_test randexpr-2.1653 {
  db eval {SELECT case ~t1.d when case when c in (select count(*) from t1 union select +(( -min(17)-~cast(avg(t1.c) AS integer)))* -min(t1.f)-max(t1.d)*count(*) & cast(avg(17) AS integer) from t1) then 17*e*t1.f & t1.e else 19-coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where t1.c>=e)),t1.f) end & 13+13 then 17 else t1.f end FROM t1 WHERE (not exists(select 1 from t1 where +c-19 in (select (~((min(b)))-+count(*) | cast(avg(case when 11 in (select (abs((t1.b))/abs(e)) from t1 union select (17) from t1) then t1.c when  -a<=b then t1.a else t1.e end) AS integer)++case max(t1.b) when cast(avg(c) AS integer) then count(*) else cast(avg(f) AS integer) end |  -count(*)-(count(*))*max(t1.e)*count(*)*cast(avg(a) AS integer))+min(11) from t1 union select max((d)) from t1)))}
} {600}
do_test randexpr-2.1654 {
  db eval {SELECT 19 | case when not (select min(17) from t1)>t1.e then coalesce((select max(coalesce((select b from t1 where (t1.a not in (a | t1.c,t1.d,19) or not exists(select 1 from t1 where t1.b in (select t1.d from t1 union select a from t1)) and (a in (select count(*) from t1 union select max(t1.b) from t1) and t1.c in (t1.b,f,t1.d)))),t1.c)) from t1 where f=d and  -b>c),t1.f)-t1.c when c in ((a),11,t1.c) then 13 else 13 end-c FROM t1 WHERE (t1.e)*case when +a*t1.f*t1.e>=+d*a+b-t1.f*~13 | t1.d*11-f-~f+17-coalesce((select max( -f) from t1 where b<t1.a),t1.b) | a-(17)-13-f then e else c end<17}
} {}
do_test randexpr-2.1655 {
  db eval {SELECT 19 | case when not (select min(17) from t1)>t1.e then coalesce((select max(coalesce((select b from t1 where (t1.a not in (a | t1.c,t1.d,19) or not exists(select 1 from t1 where t1.b in (select t1.d from t1 union select a from t1)) and (a in (select count(*) from t1 union select max(t1.b) from t1) and t1.c in (t1.b,f,t1.d)))),t1.c)) from t1 where f=d and  -b>c),t1.f)-t1.c when c in ((a),11,t1.c) then 13 else 13 end-c FROM t1 WHERE NOT ((t1.e)*case when +a*t1.f*t1.e>=+d*a+b-t1.f*~13 | t1.d*11-f-~f+17-coalesce((select max( -f) from t1 where b<t1.a),t1.b) | a-(17)-13-f then e else c end<17)}
} {19}
do_test randexpr-2.1656 {
  db eval {SELECT 19 & case when not (select min(17) from t1)>t1.e then coalesce((select max(coalesce((select b from t1 where (t1.a not in (a & t1.c,t1.d,19) or not exists(select 1 from t1 where t1.b in (select t1.d from t1 union select a from t1)) and (a in (select count(*) from t1 union select max(t1.b) from t1) and t1.c in (t1.b,f,t1.d)))),t1.c)) from t1 where f=d and  -b>c),t1.f)-t1.c when c in ((a),11,t1.c) then 13 else 13 end-c FROM t1 WHERE NOT ((t1.e)*case when +a*t1.f*t1.e>=+d*a+b-t1.f*~13 | t1.d*11-f-~f+17-coalesce((select max( -f) from t1 where b<t1.a),t1.b) | a-(17)-13-f then e else c end<17)}
} {0}
do_test randexpr-2.1657 {
  db eval {SELECT case when not exists(select 1 from t1 where not not not d=17) then t1.b when (not coalesce((select coalesce((select max(d) from t1 where c+c>t1.c),11)*e*t1.e from t1 where e<=t1.d),t1.a)*f<t1.b) then coalesce((select case when 19>=11 then e when t1.a in (select e from t1 union select b from t1) then t1.b-t1.a else e end from t1 where a=t1.a), -17) else e end FROM t1 WHERE not exists(select 1 from t1 where t1.e in (select max((abs(~+t1.a-t1.c*a)/abs(17))) from t1 union select min(11*t1.c+t1.f) from t1))}
} {500}
do_test randexpr-2.1658 {
  db eval {SELECT case when not exists(select 1 from t1 where not not not d=17) then t1.b when (not coalesce((select coalesce((select max(d) from t1 where c+c>t1.c),11)*e*t1.e from t1 where e<=t1.d),t1.a)*f<t1.b) then coalesce((select case when 19>=11 then e when t1.a in (select e from t1 union select b from t1) then t1.b-t1.a else e end from t1 where a=t1.a), -17) else e end FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.e in (select max((abs(~+t1.a-t1.c*a)/abs(17))) from t1 union select min(11*t1.c+t1.f) from t1)))}
} {}
do_test randexpr-2.1659 {
  db eval {SELECT coalesce((select coalesce((select max(case when not a not in ((abs(11)/abs(coalesce((select t1.d from t1 where 17 in (select count(*) from t1 union select count(distinct t1.a) from t1)),b)*t1.e*c)),t1.a,t1.b) or t1.c<=t1.f or (t1.d>= -a) then (select cast(avg(~t1.f-t1.f) AS integer) from t1) else 17 end) from t1 where t1.b<=c and t1.b<=a),11) from t1 where exists(select 1 from t1 where e<c) and 11 not between t1.d and c),a) FROM t1 WHERE e>=(select min(coalesce((select max(19) from t1 where not exists(select 1 from t1 where (select count(distinct +case when coalesce((select max(case when e<a then b else (c) end) from t1 where f<>t1.d),t1.d) in (select abs(cast(avg(t1.d) AS integer)-min(t1.c)) from t1 union select  -cast(avg(19) AS integer) from t1) then b when t1.e< -t1.c then t1.b else t1.c end-19*e) from t1)<=a)),17))+ -(max(a))- -cast(avg(11) AS integer)+ -count(distinct c) from t1)-11}
} {100}
do_test randexpr-2.1660 {
  db eval {SELECT coalesce((select coalesce((select max(case when not a not in ((abs(11)/abs(coalesce((select t1.d from t1 where 17 in (select count(*) from t1 union select count(distinct t1.a) from t1)),b)*t1.e*c)),t1.a,t1.b) or t1.c<=t1.f or (t1.d>= -a) then (select cast(avg(~t1.f-t1.f) AS integer) from t1) else 17 end) from t1 where t1.b<=c and t1.b<=a),11) from t1 where exists(select 1 from t1 where e<c) and 11 not between t1.d and c),a) FROM t1 WHERE NOT (e>=(select min(coalesce((select max(19) from t1 where not exists(select 1 from t1 where (select count(distinct +case when coalesce((select max(case when e<a then b else (c) end) from t1 where f<>t1.d),t1.d) in (select abs(cast(avg(t1.d) AS integer)-min(t1.c)) from t1 union select  -cast(avg(19) AS integer) from t1) then b when t1.e< -t1.c then t1.b else t1.c end-19*e) from t1)<=a)),17))+ -(max(a))- -cast(avg(11) AS integer)+ -count(distinct c) from t1)-11)}
} {}
do_test randexpr-2.1661 {
  db eval {SELECT e*(case when +t1.c+t1.e+f<=13 then (select case cast(avg(coalesce((select (t1.f*a)*11 from t1 where c<>t1.a),b)) AS integer)+cast(avg(b) AS integer)+max( -b)-min(e) when max(11) then cast(avg(t1.e) AS integer) else cast(avg(t1.b) AS integer) end from t1) when ~11*t1.d<=t1.b or (t1.e=t1.a) then t1.b else  -19 end)+e FROM t1 WHERE a>13*d+t1.e+c}
} {}
do_test randexpr-2.1662 {
  db eval {SELECT e*(case when +t1.c+t1.e+f<=13 then (select case cast(avg(coalesce((select (t1.f*a)*11 from t1 where c<>t1.a),b)) AS integer)+cast(avg(b) AS integer)+max( -b)-min(e) when max(11) then cast(avg(t1.e) AS integer) else cast(avg(t1.b) AS integer) end from t1) when ~11*t1.d<=t1.b or (t1.e=t1.a) then t1.b else  -19 end)+e FROM t1 WHERE NOT (a>13*d+t1.e+c)}
} {100500}
do_test randexpr-2.1663 {
  db eval {SELECT (abs(t1.d-t1.b)/abs(t1.c))+t1.a*coalesce((select max(coalesce((select max(~11+11) from t1 where e-a>=case when 11*t1.d+13+(select cast(avg(t1.d+f) AS integer) from t1)-d+t1.d-b not between a and a then e else coalesce((select e from t1 where d>b and b between 11 and t1.d),t1.b) end), -t1.b)) from t1 where t1.e<=c),17)+ -t1.d FROM t1 WHERE case when (19>b) then case (abs(t1.d+case when not exists(select 1 from t1 where f in (19,d,11) and f not between t1.e and a) then (19) when a<=t1.d then 17 else t1.c end* -c*13)/abs(d))*f when 19 then t1.c else  - - -t1.d end when c in (select max(t1.e) from t1 union select ( - -abs(cast(avg(t1.f) AS integer))-case cast(avg(a) AS integer) when (min(t1.f)) then max(13) else max(11) end |  -((min(11)))+max((a))) from t1) then c else  -b end*t1.d>d}
} {}
do_test randexpr-2.1664 {
  db eval {SELECT (abs(t1.d-t1.b)/abs(t1.c))+t1.a*coalesce((select max(coalesce((select max(~11+11) from t1 where e-a>=case when 11*t1.d+13+(select cast(avg(t1.d+f) AS integer) from t1)-d+t1.d-b not between a and a then e else coalesce((select e from t1 where d>b and b between 11 and t1.d),t1.b) end), -t1.b)) from t1 where t1.e<=c),17)+ -t1.d FROM t1 WHERE NOT (case when (19>b) then case (abs(t1.d+case when not exists(select 1 from t1 where f in (19,d,11) and f not between t1.e and a) then (19) when a<=t1.d then 17 else t1.c end* -c*13)/abs(d))*f when 19 then t1.c else  - - -t1.d end when c in (select max(t1.e) from t1 union select ( - -abs(cast(avg(t1.f) AS integer))-case cast(avg(a) AS integer) when (min(t1.f)) then max(13) else max(11) end |  -((min(11)))+max((a))) from t1) then c else  -b end*t1.d>d)}
} {1300}
do_test randexpr-2.1665 {
  db eval {SELECT ~t1.a*(case when not not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where (select count(distinct b | case 13 | case when  -11<>a then t1.a else b end when t1.e then t1.b else d end*t1.f) from t1)<>17 or t1.a not between c and t1.a),11) in (t1.e,c,c)) and  -11>f then t1.d else f end-17)+ -(t1.b) FROM t1 WHERE (13-coalesce((select  -case when 19+c=a then f else 11 end*(e) from t1 where (t1.b in (select t1.a from t1 union select 11 from t1))),(t1.f))*e+f*(t1.f)=a and not 17 in (select max(f) from t1 union select max(19) from t1) or 19<>t1.f) and 13 between f and f and d<>b}
} {}
do_test randexpr-2.1666 {
  db eval {SELECT ~t1.a*(case when not not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where (select count(distinct b | case 13 | case when  -11<>a then t1.a else b end when t1.e then t1.b else d end*t1.f) from t1)<>17 or t1.a not between c and t1.a),11) in (t1.e,c,c)) and  -11>f then t1.d else f end-17)+ -(t1.b) FROM t1 WHERE NOT ((13-coalesce((select  -case when 19+c=a then f else 11 end*(e) from t1 where (t1.b in (select t1.a from t1 union select 11 from t1))),(t1.f))*e+f*(t1.f)=a and not 17 in (select max(f) from t1 union select max(19) from t1) or 19<>t1.f) and 13 between f and f and d<>b)}
} {-59083}
do_test randexpr-2.1667 {
  db eval {SELECT ~t1.a*(case when not not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where (select count(distinct b & case 13 & case when  -11<>a then t1.a else b end when t1.e then t1.b else d end*t1.f) from t1)<>17 or t1.a not between c and t1.a),11) in (t1.e,c,c)) and  -11>f then t1.d else f end-17)+ -(t1.b) FROM t1 WHERE NOT ((13-coalesce((select  -case when 19+c=a then f else 11 end*(e) from t1 where (t1.b in (select t1.a from t1 union select 11 from t1))),(t1.f))*e+f*(t1.f)=a and not 17 in (select max(f) from t1 union select max(19) from t1) or 19<>t1.f) and 13 between f and f and d<>b)}
} {-59083}
do_test randexpr-2.1668 {
  db eval {SELECT ~13+case when (t1.e-~b+13*case when b>(select max(case when (19*f in (select ~count(distinct a)+count(distinct (e)) from t1 union select (cast(avg(t1.c) AS integer)) from t1)) then coalesce((select  -19 from t1 where t1.f<=c or 19 not in (t1.c, -b,19)),t1.e) when t1.e>c then e else 13 end | f) from t1) then 13 else d end in (select t1.f from t1 union select c from t1)) then t1.f when not exists(select 1 from t1 where a between f and f) then (d) else t1.c end FROM t1 WHERE exists(select 1 from t1 where case when 19 in (19,+(abs(case t1.f when e then case (select +cast(avg(a) AS integer)*min(e) from t1) when case when 19 not between  -t1.c and d then 11 else t1.f end then f else t1.c end else e end+17+b)/abs(t1.d))*13,t1.f) then a when t1.d not in (f,d, -c) then t1.c else t1.b end not between d and c and t1.b not between t1.b and f)}
} {}
do_test randexpr-2.1669 {
  db eval {SELECT ~13+case when (t1.e-~b+13*case when b>(select max(case when (19*f in (select ~count(distinct a)+count(distinct (e)) from t1 union select (cast(avg(t1.c) AS integer)) from t1)) then coalesce((select  -19 from t1 where t1.f<=c or 19 not in (t1.c, -b,19)),t1.e) when t1.e>c then e else 13 end | f) from t1) then 13 else d end in (select t1.f from t1 union select c from t1)) then t1.f when not exists(select 1 from t1 where a between f and f) then (d) else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where case when 19 in (19,+(abs(case t1.f when e then case (select +cast(avg(a) AS integer)*min(e) from t1) when case when 19 not between  -t1.c and d then 11 else t1.f end then f else t1.c end else e end+17+b)/abs(t1.d))*13,t1.f) then a when t1.d not in (f,d, -c) then t1.c else t1.b end not between d and c and t1.b not between t1.b and f))}
} {386}
do_test randexpr-2.1670 {
  db eval {SELECT ~13+case when (t1.e-~b+13*case when b>(select max(case when (19*f in (select ~count(distinct a)+count(distinct (e)) from t1 union select (cast(avg(t1.c) AS integer)) from t1)) then coalesce((select  -19 from t1 where t1.f<=c or 19 not in (t1.c, -b,19)),t1.e) when t1.e>c then e else 13 end & f) from t1) then 13 else d end in (select t1.f from t1 union select c from t1)) then t1.f when not exists(select 1 from t1 where a between f and f) then (d) else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where case when 19 in (19,+(abs(case t1.f when e then case (select +cast(avg(a) AS integer)*min(e) from t1) when case when 19 not between  -t1.c and d then 11 else t1.f end then f else t1.c end else e end+17+b)/abs(t1.d))*13,t1.f) then a when t1.d not in (f,d, -c) then t1.c else t1.b end not between d and c and t1.b not between t1.b and f))}
} {386}
do_test randexpr-2.1671 {
  db eval {SELECT  -case coalesce((select max((case when a>t1.c | t1.a then (select abs(count(distinct a)) from t1) when (e not in (coalesce((select c from t1 where exists(select 1 from t1 where c<=11) and t1.a>e),e),d,a)) or t1.d<>e then t1.c else c end)- -11*b) from t1 where not exists(select 1 from t1 where not (c in ((t1.e),d,19)))),(t1.c))*b when 17 then t1.b else 19 end FROM t1 WHERE e<=coalesce((select t1.b from t1 where coalesce((select c*19 | (a) from t1 where not exists(select 1 from t1 where 19>=13 or case when coalesce((select max(19) from t1 where t1.e=t1.d or t1.f<>e),t1.f)>19 and t1.f=t1.d then 11+ -t1.d when  -t1.f not between f and f then t1.a else d end not in ((t1.a),13,t1.a) and c in (select (13) from t1 union select f from t1) and 17<(f)) and t1.a<>t1.e),t1.d)>=t1.c),t1.f)}
} {}
do_test randexpr-2.1672 {
  db eval {SELECT  -case coalesce((select max((case when a>t1.c | t1.a then (select abs(count(distinct a)) from t1) when (e not in (coalesce((select c from t1 where exists(select 1 from t1 where c<=11) and t1.a>e),e),d,a)) or t1.d<>e then t1.c else c end)- -11*b) from t1 where not exists(select 1 from t1 where not (c in ((t1.e),d,19)))),(t1.c))*b when 17 then t1.b else 19 end FROM t1 WHERE NOT (e<=coalesce((select t1.b from t1 where coalesce((select c*19 | (a) from t1 where not exists(select 1 from t1 where 19>=13 or case when coalesce((select max(19) from t1 where t1.e=t1.d or t1.f<>e),t1.f)>19 and t1.f=t1.d then 11+ -t1.d when  -t1.f not between f and f then t1.a else d end not in ((t1.a),13,t1.a) and c in (select (13) from t1 union select f from t1) and 17<(f)) and t1.a<>t1.e),t1.d)>=t1.c),t1.f))}
} {-19}
do_test randexpr-2.1673 {
  db eval {SELECT  -case coalesce((select max((case when a>t1.c & t1.a then (select abs(count(distinct a)) from t1) when (e not in (coalesce((select c from t1 where exists(select 1 from t1 where c<=11) and t1.a>e),e),d,a)) or t1.d<>e then t1.c else c end)- -11*b) from t1 where not exists(select 1 from t1 where not (c in ((t1.e),d,19)))),(t1.c))*b when 17 then t1.b else 19 end FROM t1 WHERE NOT (e<=coalesce((select t1.b from t1 where coalesce((select c*19 | (a) from t1 where not exists(select 1 from t1 where 19>=13 or case when coalesce((select max(19) from t1 where t1.e=t1.d or t1.f<>e),t1.f)>19 and t1.f=t1.d then 11+ -t1.d when  -t1.f not between f and f then t1.a else d end not in ((t1.a),13,t1.a) and c in (select (13) from t1 union select f from t1) and 17<(f)) and t1.a<>t1.e),t1.d)>=t1.c),t1.f))}
} {-19}
do_test randexpr-2.1674 {
  db eval {SELECT coalesce((select (11) from t1 where not e in (select  -min(d*13) from t1 union select count(distinct f) from t1)),t1.f*t1.d | t1.f) FROM t1 WHERE  -t1.c*d>case d when ~coalesce((select max(e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not e=c))),+coalesce((select +t1.e from t1 where not exists(select 1 from t1 where c>=t1.b)),(abs( -t1.c+case t1.c when ~~t1.c+a-t1.c then coalesce((select max(case when t1.b<=c then 19 else f end) from t1 where 13<b),d) else t1.d end)/abs(a))*(d))) then  -t1.e else (13) end}
} {}
do_test randexpr-2.1675 {
  db eval {SELECT coalesce((select (11) from t1 where not e in (select  -min(d*13) from t1 union select count(distinct f) from t1)),t1.f*t1.d | t1.f) FROM t1 WHERE NOT ( -t1.c*d>case d when ~coalesce((select max(e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not e=c))),+coalesce((select +t1.e from t1 where not exists(select 1 from t1 where c>=t1.b)),(abs( -t1.c+case t1.c when ~~t1.c+a-t1.c then coalesce((select max(case when t1.b<=c then 19 else f end) from t1 where 13<b),d) else t1.d end)/abs(a))*(d))) then  -t1.e else (13) end)}
} {11}
do_test randexpr-2.1676 {
  db eval {SELECT coalesce((select (11) from t1 where not e in (select  -min(d*13) from t1 union select count(distinct f) from t1)),t1.f*t1.d & t1.f) FROM t1 WHERE NOT ( -t1.c*d>case d when ~coalesce((select max(e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not e=c))),+coalesce((select +t1.e from t1 where not exists(select 1 from t1 where c>=t1.b)),(abs( -t1.c+case t1.c when ~~t1.c+a-t1.c then coalesce((select max(case when t1.b<=c then 19 else f end) from t1 where 13<b),d) else t1.d end)/abs(a))*(d))) then  -t1.e else (13) end)}
} {11}
do_test randexpr-2.1677 {
  db eval {SELECT +case when t1.e>=(select max(17) from t1) then case 11 when e then coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.d in (select t1.a from t1 union select e from t1) and e=case when 11<19 and t1.e<19 then t1.e when t1.c in (t1.b,t1.e,t1.d) then 13 else 13 end and e<=d or b between 19 and t1.a or t1.a<=(13))),t1.a) else t1.e-t1.d end*t1.a when  -11 not in (17,t1.d,a) then t1.c else b end*19 FROM t1 WHERE not t1.b>t1.e or t1.d not in (~t1.f,d+case when (b+(abs(19*~t1.c | t1.b*d*(b)-t1.e-t1.e+a)/abs(t1.c)) not in (17,b,t1.e)) then 13+f else b end-t1.f,t1.e) or t1.e not in (f,a,t1.d)}
} {190000}
do_test randexpr-2.1678 {
  db eval {SELECT +case when t1.e>=(select max(17) from t1) then case 11 when e then coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.d in (select t1.a from t1 union select e from t1) and e=case when 11<19 and t1.e<19 then t1.e when t1.c in (t1.b,t1.e,t1.d) then 13 else 13 end and e<=d or b between 19 and t1.a or t1.a<=(13))),t1.a) else t1.e-t1.d end*t1.a when  -11 not in (17,t1.d,a) then t1.c else b end*19 FROM t1 WHERE NOT (not t1.b>t1.e or t1.d not in (~t1.f,d+case when (b+(abs(19*~t1.c | t1.b*d*(b)-t1.e-t1.e+a)/abs(t1.c)) not in (17,b,t1.e)) then 13+f else b end-t1.f,t1.e) or t1.e not in (f,a,t1.d))}
} {}
do_test randexpr-2.1679 {
  db eval {SELECT t1.e | t1.b+a*coalesce((select t1.a from t1 where ~(d)-f<>e-c or 17+f in (select  -(~case max(t1.c) when abs(count(*)) then abs( - -cast(avg(b) AS integer)*count(*)) else cast(avg(t1.c) AS integer) end) from t1 union select count(distinct (11)) from t1) and exists(select 1 from t1 where not 13>t1.e) or t1.c<d),~b)- -b FROM t1 WHERE d between t1.f and t1.c}
} {}
do_test randexpr-2.1680 {
  db eval {SELECT t1.e | t1.b+a*coalesce((select t1.a from t1 where ~(d)-f<>e-c or 17+f in (select  -(~case max(t1.c) when abs(count(*)) then abs( - -cast(avg(b) AS integer)*count(*)) else cast(avg(t1.c) AS integer) end) from t1 union select count(distinct (11)) from t1) and exists(select 1 from t1 where not 13>t1.e) or t1.c<d),~b)- -b FROM t1 WHERE NOT (d between t1.f and t1.c)}
} {10740}
do_test randexpr-2.1681 {
  db eval {SELECT t1.e & t1.b+a*coalesce((select t1.a from t1 where ~(d)-f<>e-c or 17+f in (select  -(~case max(t1.c) when abs(count(*)) then abs( - -cast(avg(b) AS integer)*count(*)) else cast(avg(t1.c) AS integer) end) from t1 union select count(distinct (11)) from t1) and exists(select 1 from t1 where not 13>t1.e) or t1.c<d),~b)- -b FROM t1 WHERE NOT (d between t1.f and t1.c)}
} {160}
do_test randexpr-2.1682 {
  db eval {SELECT ~(select +~count(distinct 17)*count(distinct t1.e) from t1)-t1.e+a*11-case when 13<>t1.b then 19 when case when case (select ( -max(c)) from t1) when 11 then d else e end*t1.d<>d then a else 11 end=t1.b or 17=d then b else t1.e end+11+t1.a*a-e FROM t1 WHERE coalesce((select coalesce((select max(c) from t1 where  -+ -e-t1.d*case when coalesce((select d from t1 where (c=a)),f) between t1.b and t1.b or (13)<>c and e in (t1.e,e,(t1.a)) then b*t1.c else b end+t1.c in (select t1.f from t1 union select t1.b from t1)),19) from t1 where t1.f in (select count(*) from t1 union select cast(avg(t1.e) AS integer)*min((a))*+(max(t1.b))+max(17) from t1)),t1.d)< -e}
} {}
do_test randexpr-2.1683 {
  db eval {SELECT ~(select +~count(distinct 17)*count(distinct t1.e) from t1)-t1.e+a*11-case when 13<>t1.b then 19 when case when case (select ( -max(c)) from t1) when 11 then d else e end*t1.d<>d then a else 11 end=t1.b or 17=d then b else t1.e end+11+t1.a*a-e FROM t1 WHERE NOT (coalesce((select coalesce((select max(c) from t1 where  -+ -e-t1.d*case when coalesce((select d from t1 where (c=a)),f) between t1.b and t1.b or (13)<>c and e in (t1.e,e,(t1.a)) then b*t1.c else b end+t1.c in (select t1.f from t1 union select t1.b from t1)),19) from t1 where t1.f in (select count(*) from t1 union select cast(avg(t1.e) AS integer)*min((a))*+(max(t1.b))+max(17) from t1)),t1.d)< -e)}
} {10093}
do_test randexpr-2.1684 {
  db eval {SELECT coalesce((select max(case when f<=(17-coalesce((select ~t1.e+11 from t1 where t1.f in (select c from t1 union select b from t1)),f)) then  -case when e>case when 17+ -t1.b in (select cast(avg(f) AS integer) from t1 union select min(c-17+a) from t1) then  -17 else t1.d end then a when 19<11 then t1.a else t1.b end | t1.f else a end) from t1 where e between a and d),19) FROM t1 WHERE case 19 when ((select max(f) from t1)) then 13 else t1.d end-t1.c>a-b-t1.d}
} {19}
do_test randexpr-2.1685 {
  db eval {SELECT coalesce((select max(case when f<=(17-coalesce((select ~t1.e+11 from t1 where t1.f in (select c from t1 union select b from t1)),f)) then  -case when e>case when 17+ -t1.b in (select cast(avg(f) AS integer) from t1 union select min(c-17+a) from t1) then  -17 else t1.d end then a when 19<11 then t1.a else t1.b end | t1.f else a end) from t1 where e between a and d),19) FROM t1 WHERE NOT (case 19 when ((select max(f) from t1)) then 13 else t1.d end-t1.c>a-b-t1.d)}
} {}
do_test randexpr-2.1686 {
  db eval {SELECT coalesce((select max(case when f<=(17-coalesce((select ~t1.e+11 from t1 where t1.f in (select c from t1 union select b from t1)),f)) then  -case when e>case when 17+ -t1.b in (select cast(avg(f) AS integer) from t1 union select min(c-17+a) from t1) then  -17 else t1.d end then a when 19<11 then t1.a else t1.b end & t1.f else a end) from t1 where e between a and d),19) FROM t1 WHERE case 19 when ((select max(f) from t1)) then 13 else t1.d end-t1.c>a-b-t1.d}
} {19}
do_test randexpr-2.1687 {
  db eval {SELECT case when (select case min(t1.b) when max(13) | +max(t1.e)*max(f) then abs( -+count(*)) else max(t1.f) end from t1)*t1.a+(abs(case 19 when 19 then d else ((13)) end)/abs(13))+(19) between f and 13 or (not not 17<e) then (abs(17)/abs((f))) when f in (select min(f) from t1 union select cast(avg(11) AS integer) from t1) then c else b end FROM t1 WHERE exists(select 1 from t1 where f<13)}
} {}
do_test randexpr-2.1688 {
  db eval {SELECT case when (select case min(t1.b) when max(13) | +max(t1.e)*max(f) then abs( -+count(*)) else max(t1.f) end from t1)*t1.a+(abs(case 19 when 19 then d else ((13)) end)/abs(13))+(19) between f and 13 or (not not 17<e) then (abs(17)/abs((f))) when f in (select min(f) from t1 union select cast(avg(11) AS integer) from t1) then c else b end FROM t1 WHERE NOT (exists(select 1 from t1 where f<13))}
} {0}
do_test randexpr-2.1689 {
  db eval {SELECT case when (select case min(t1.b) when max(13) & +max(t1.e)*max(f) then abs( -+count(*)) else max(t1.f) end from t1)*t1.a+(abs(case 19 when 19 then d else ((13)) end)/abs(13))+(19) between f and 13 or (not not 17<e) then (abs(17)/abs((f))) when f in (select min(f) from t1 union select cast(avg(11) AS integer) from t1) then c else b end FROM t1 WHERE NOT (exists(select 1 from t1 where f<13))}
} {0}
do_test randexpr-2.1690 {
  db eval {SELECT coalesce((select +(select max(coalesce((select (abs(((t1.e)+b))/abs(f))+e from t1 where (select (case min(t1.b) when count(*) then count(*) else abs(++count(distinct t1.a)+cast(avg(d) AS integer)) end)+min(f)-max(11) from t1)<>~17),t1.e+(select count(*) from t1) | 11-coalesce((select 13 from t1 where 11 not in ( -t1.f,t1.e,t1.f)),t1.b))+ -(t1.c)) from t1) from t1 where t1.a=(13)), -a)*e FROM t1 WHERE not exists(select 1 from t1 where (select count(distinct t1.e) from t1)<=coalesce((select case when not exists(select 1 from t1 where e=t1.b*coalesce((select max(+b) from t1 where exists(select 1 from t1 where not (not not exists(select 1 from t1 where t1.c in (select 11 from t1 union select 19+13 from t1)))) and not t1.b<a),case when b in (t1.c,t1.e,f) and b=t1.a then ~b when 13 not between d and 11 then  -t1.d-c else t1.d end)) then (abs((11))/abs(17)) else b end from t1 where t1.b not in (t1.f,t1.e,17)), -t1.d))}
} {-50000}
do_test randexpr-2.1691 {
  db eval {SELECT coalesce((select +(select max(coalesce((select (abs(((t1.e)+b))/abs(f))+e from t1 where (select (case min(t1.b) when count(*) then count(*) else abs(++count(distinct t1.a)+cast(avg(d) AS integer)) end)+min(f)-max(11) from t1)<>~17),t1.e+(select count(*) from t1) | 11-coalesce((select 13 from t1 where 11 not in ( -t1.f,t1.e,t1.f)),t1.b))+ -(t1.c)) from t1) from t1 where t1.a=(13)), -a)*e FROM t1 WHERE NOT (not exists(select 1 from t1 where (select count(distinct t1.e) from t1)<=coalesce((select case when not exists(select 1 from t1 where e=t1.b*coalesce((select max(+b) from t1 where exists(select 1 from t1 where not (not not exists(select 1 from t1 where t1.c in (select 11 from t1 union select 19+13 from t1)))) and not t1.b<a),case when b in (t1.c,t1.e,f) and b=t1.a then ~b when 13 not between d and 11 then  -t1.d-c else t1.d end)) then (abs((11))/abs(17)) else b end from t1 where t1.b not in (t1.f,t1.e,17)), -t1.d)))}
} {}
do_test randexpr-2.1692 {
  db eval {SELECT coalesce((select +(select max(coalesce((select (abs(((t1.e)+b))/abs(f))+e from t1 where (select (case min(t1.b) when count(*) then count(*) else abs(++count(distinct t1.a)+cast(avg(d) AS integer)) end)+min(f)-max(11) from t1)<>~17),t1.e+(select count(*) from t1) & 11-coalesce((select 13 from t1 where 11 not in ( -t1.f,t1.e,t1.f)),t1.b))+ -(t1.c)) from t1) from t1 where t1.a=(13)), -a)*e FROM t1 WHERE not exists(select 1 from t1 where (select count(distinct t1.e) from t1)<=coalesce((select case when not exists(select 1 from t1 where e=t1.b*coalesce((select max(+b) from t1 where exists(select 1 from t1 where not (not not exists(select 1 from t1 where t1.c in (select 11 from t1 union select 19+13 from t1)))) and not t1.b<a),case when b in (t1.c,t1.e,f) and b=t1.a then ~b when 13 not between d and 11 then  -t1.d-c else t1.d end)) then (abs((11))/abs(17)) else b end from t1 where t1.b not in (t1.f,t1.e,17)), -t1.d))}
} {-50000}
do_test randexpr-2.1693 {
  db eval {SELECT ~~t1.b | 11+d*coalesce((select max(t1.f-a) from t1 where not exists(select 1 from t1 where (a-coalesce((select b from t1 where t1.f<case when not exists(select 1 from t1 where 11=b or d<>e) then t1.e*c else c end-13+t1.a),f)+t1.d- -t1.a)*t1.c<>f) and t1.b not between (e) and t1.c),f)+11*t1.f FROM t1 WHERE (17 in (select 13 from t1 union select case coalesce((select max( -case when not b in ((select  -+case max((b)) when cast(avg(13) AS integer) then count(*) else max(a) end+min(b)-max(d) from t1),coalesce((select t1.d from t1 where case when  -13 in ( -t1.e,f,t1.e) then t1.c else e end | 11<=(t1.b)),t1.c)-11,t1.e) then t1.f else 13 end) from t1 where b>=t1.e),f) when e then t1.c else c end from t1))}
} {}
do_test randexpr-2.1694 {
  db eval {SELECT ~~t1.b | 11+d*coalesce((select max(t1.f-a) from t1 where not exists(select 1 from t1 where (a-coalesce((select b from t1 where t1.f<case when not exists(select 1 from t1 where 11=b or d<>e) then t1.e*c else c end-13+t1.a),f)+t1.d- -t1.a)*t1.c<>f) and t1.b not between (e) and t1.c),f)+11*t1.f FROM t1 WHERE NOT ((17 in (select 13 from t1 union select case coalesce((select max( -case when not b in ((select  -+case max((b)) when cast(avg(13) AS integer) then count(*) else max(a) end+min(b)-max(d) from t1),coalesce((select t1.d from t1 where case when  -13 in ( -t1.e,f,t1.e) then t1.c else e end | 11<=(t1.b)),t1.c)-11,t1.e) then t1.f else 13 end) from t1 where b>=t1.e),f) when e then t1.c else c end from t1)))}
} {246747}
do_test randexpr-2.1695 {
  db eval {SELECT ~~t1.b & 11+d*coalesce((select max(t1.f-a) from t1 where not exists(select 1 from t1 where (a-coalesce((select b from t1 where t1.f<case when not exists(select 1 from t1 where 11=b or d<>e) then t1.e*c else c end-13+t1.a),f)+t1.d- -t1.a)*t1.c<>f) and t1.b not between (e) and t1.c),f)+11*t1.f FROM t1 WHERE NOT ((17 in (select 13 from t1 union select case coalesce((select max( -case when not b in ((select  -+case max((b)) when cast(avg(13) AS integer) then count(*) else max(a) end+min(b)-max(d) from t1),coalesce((select t1.d from t1 where case when  -13 in ( -t1.e,f,t1.e) then t1.c else e end | 11<=(t1.b)),t1.c)-11,t1.e) then t1.f else 13 end) from t1 where b>=t1.e),f) when e then t1.c else c end from t1)))}
} {64}
do_test randexpr-2.1696 {
  db eval {SELECT case case when not ++b+~e-11-d-f*e*case when (t1.f) not between t1.c and t1.e or (13>e) then (abs(17)/abs(d)) when 11 not between 17 and (t1.b) then c else 13 end-(f)-f between t1.c and t1.f then t1.c when a between t1.d and 13 then t1.e else t1.a end when a then f else 13 end FROM t1 WHERE t1.a in (select case when (+e*t1.f not in ( -(select (case max(+t1.e-case when not exists(select 1 from t1 where 19 in (select 13 from t1 union select ((t1.d)) from t1)) then 13-t1.b else 19 end) when count(*)-(cast(avg(t1.b) AS integer)-cast(avg(b) AS integer)) then count(distinct t1.b) else count(distinct t1.c) end | cast(avg((19)) AS integer)) from t1),~17-f,c)) then (select count(*) from t1) when t1.a>t1.a then b else t1.d end+(f) from t1 union select b from t1)}
} {}
do_test randexpr-2.1697 {
  db eval {SELECT case case when not ++b+~e-11-d-f*e*case when (t1.f) not between t1.c and t1.e or (13>e) then (abs(17)/abs(d)) when 11 not between 17 and (t1.b) then c else 13 end-(f)-f between t1.c and t1.f then t1.c when a between t1.d and 13 then t1.e else t1.a end when a then f else 13 end FROM t1 WHERE NOT (t1.a in (select case when (+e*t1.f not in ( -(select (case max(+t1.e-case when not exists(select 1 from t1 where 19 in (select 13 from t1 union select ((t1.d)) from t1)) then 13-t1.b else 19 end) when count(*)-(cast(avg(t1.b) AS integer)-cast(avg(b) AS integer)) then count(distinct t1.b) else count(distinct t1.c) end | cast(avg((19)) AS integer)) from t1),~17-f,c)) then (select count(*) from t1) when t1.a>t1.a then b else t1.d end+(f) from t1 union select b from t1))}
} {13}
do_test randexpr-2.1698 {
  db eval {SELECT 13-case when a<=case when e not between t1.b*(abs(t1.c)/abs(e | 19-(select  -~count(distinct t1.b)+min(t1.a-t1.c-f+t1.d+t1.d+t1.d) from t1)))-t1.e and coalesce((select 11 from t1 where c<e),d)* -d then 17 else t1.e end then t1.c else 17 end+f FROM t1 WHERE (t1.f<>t1.c)}
} {596}
do_test randexpr-2.1699 {
  db eval {SELECT 13-case when a<=case when e not between t1.b*(abs(t1.c)/abs(e | 19-(select  -~count(distinct t1.b)+min(t1.a-t1.c-f+t1.d+t1.d+t1.d) from t1)))-t1.e and coalesce((select 11 from t1 where c<e),d)* -d then 17 else t1.e end then t1.c else 17 end+f FROM t1 WHERE NOT ((t1.f<>t1.c))}
} {}
do_test randexpr-2.1700 {
  db eval {SELECT 13-case when a<=case when e not between t1.b*(abs(t1.c)/abs(e & 19-(select  -~count(distinct t1.b)+min(t1.a-t1.c-f+t1.d+t1.d+t1.d) from t1)))-t1.e and coalesce((select 11 from t1 where c<e),d)* -d then 17 else t1.e end then t1.c else 17 end+f FROM t1 WHERE (t1.f<>t1.c)}
} {596}
do_test randexpr-2.1701 {
  db eval {SELECT (case when coalesce((select max(~case coalesce((select max(b) from t1 where case (select count(distinct 17) from t1)-e when b then d else t1.b end<13),f) when c then (( -c)) else 13 end) from t1 where t1.e between a and b),t1.b) in (select  -min(t1.f) from t1 union select case cast(avg(t1.d) AS integer) when count(distinct b) then case +~ -cast(avg(b) AS integer) when max(t1.f) then count(*) else (max(e)) end else count(*) end from t1) then c when 13<=t1.f then ( -17) else t1.b end) FROM t1 WHERE (select min(19*coalesce((select max(t1.e) from t1 where ~coalesce((select t1.a-coalesce((select max((abs(a)/abs(d))) from t1 where  -13 not in ((d)*t1.a+t1.e,13,t1.c) or 17 not in (a,b,t1.d)), -t1.a) from t1 where c<>t1.e),a) | 11+17 between b and 17),c))*~ -max(e) from t1)<>11}
} {-17}
do_test randexpr-2.1702 {
  db eval {SELECT (case when coalesce((select max(~case coalesce((select max(b) from t1 where case (select count(distinct 17) from t1)-e when b then d else t1.b end<13),f) when c then (( -c)) else 13 end) from t1 where t1.e between a and b),t1.b) in (select  -min(t1.f) from t1 union select case cast(avg(t1.d) AS integer) when count(distinct b) then case +~ -cast(avg(b) AS integer) when max(t1.f) then count(*) else (max(e)) end else count(*) end from t1) then c when 13<=t1.f then ( -17) else t1.b end) FROM t1 WHERE NOT ((select min(19*coalesce((select max(t1.e) from t1 where ~coalesce((select t1.a-coalesce((select max((abs(a)/abs(d))) from t1 where  -13 not in ((d)*t1.a+t1.e,13,t1.c) or 17 not in (a,b,t1.d)), -t1.a) from t1 where c<>t1.e),a) | 11+17 between b and 17),c))*~ -max(e) from t1)<>11)}
} {}
do_test randexpr-2.1703 {
  db eval {SELECT t1.f* -t1.e-c | b++19*(select (case max(t1.c) when +abs(count(distinct case when e<t1.a then 19 else d end)) then  -count(distinct e) else (((count(distinct t1.d)))) end | max(e)+(cast(avg(t1.c) AS integer)))+count(*) from t1)+case when t1.d>=13 then coalesce((select max(t1.c) from t1 where not  -c+b-t1.f<>d),a) else b end FROM t1 WHERE d in (select 11 from t1 union select  -d*~t1.b from t1)}
} {}
do_test randexpr-2.1704 {
  db eval {SELECT t1.f* -t1.e-c | b++19*(select (case max(t1.c) when +abs(count(distinct case when e<t1.a then 19 else d end)) then  -count(distinct e) else (((count(distinct t1.d)))) end | max(e)+(cast(avg(t1.c) AS integer)))+count(*) from t1)+case when t1.d>=13 then coalesce((select max(t1.c) from t1 where not  -c+b-t1.f<>d),a) else b end FROM t1 WHERE NOT (d in (select 11 from t1 union select  -d*~t1.b from t1))}
} {-295178}
do_test randexpr-2.1705 {
  db eval {SELECT t1.f* -t1.e-c & b++19*(select (case max(t1.c) when +abs(count(distinct case when e<t1.a then 19 else d end)) then  -count(distinct e) else (((count(distinct t1.d)))) end & max(e)+(cast(avg(t1.c) AS integer)))+count(*) from t1)+case when t1.d>=13 then coalesce((select max(t1.c) from t1 where not  -c+b-t1.f<>d),a) else b end FROM t1 WHERE NOT (d in (select 11 from t1 union select  -d*~t1.b from t1))}
} {52}
do_test randexpr-2.1706 {
  db eval {SELECT 11-t1.e+d+case case when (b between  -+case when f not between case coalesce((select t1.a from t1 where e not between (t1.d) and t1.a or 17<11),t1.d) when 17 then t1.f else t1.e end and d then 17 when e>=t1.f then t1.b else t1.b end and t1.e) then case f when t1.d then t1.c else  -e end when (not exists(select 1 from t1 where  -(11)>a) or t1.c<b) then 17 else 11 end when (t1.e) then d else t1.e end FROM t1 WHERE not (f)>t1.e}
} {}
do_test randexpr-2.1707 {
  db eval {SELECT 11-t1.e+d+case case when (b between  -+case when f not between case coalesce((select t1.a from t1 where e not between (t1.d) and t1.a or 17<11),t1.d) when 17 then t1.f else t1.e end and d then 17 when e>=t1.f then t1.b else t1.b end and t1.e) then case f when t1.d then t1.c else  -e end when (not exists(select 1 from t1 where  -(11)>a) or t1.c<b) then 17 else 11 end when (t1.e) then d else t1.e end FROM t1 WHERE NOT (not (f)>t1.e)}
} {411}
do_test randexpr-2.1708 {
  db eval {SELECT coalesce((select max(case when f>11 then 13 when 19*e+(select  -count(distinct t1.c)-max(c) | count(distinct 13) from t1) between coalesce((select max(case when t1.a<t1.c and (t1.a)<=d then c when 17 between t1.b and b then (t1.c) else a end) from t1 where  -19 in (select min(11) from t1 union select count(*) from t1)),11) and 11 or (exists(select 1 from t1 where not exists(select 1 from t1 where c not between ( -b) and e))) and b not between 17 and t1.a and 19<b then 17 else f end) from t1 where t1.b between t1.c and 13 and t1.b<>e),17) FROM t1 WHERE case case 13+coalesce((select max( -t1.b*t1.c) from t1 where t1.c*c<>(select  -(count(distinct e)) from t1)-t1.c | t1.d*t1.e+11*t1.a+11-t1.a*b),d)+t1.d+e when t1.f then e else  -11 end-d when t1.e then 11 else f end+f=19}
} {}
do_test randexpr-2.1709 {
  db eval {SELECT coalesce((select max(case when f>11 then 13 when 19*e+(select  -count(distinct t1.c)-max(c) | count(distinct 13) from t1) between coalesce((select max(case when t1.a<t1.c and (t1.a)<=d then c when 17 between t1.b and b then (t1.c) else a end) from t1 where  -19 in (select min(11) from t1 union select count(*) from t1)),11) and 11 or (exists(select 1 from t1 where not exists(select 1 from t1 where c not between ( -b) and e))) and b not between 17 and t1.a and 19<b then 17 else f end) from t1 where t1.b between t1.c and 13 and t1.b<>e),17) FROM t1 WHERE NOT (case case 13+coalesce((select max( -t1.b*t1.c) from t1 where t1.c*c<>(select  -(count(distinct e)) from t1)-t1.c | t1.d*t1.e+11*t1.a+11-t1.a*b),d)+t1.d+e when t1.f then e else  -11 end-d when t1.e then 11 else f end+f=19)}
} {17}
do_test randexpr-2.1710 {
  db eval {SELECT coalesce((select max(case when f>11 then 13 when 19*e+(select  -count(distinct t1.c)-max(c) & count(distinct 13) from t1) between coalesce((select max(case when t1.a<t1.c and (t1.a)<=d then c when 17 between t1.b and b then (t1.c) else a end) from t1 where  -19 in (select min(11) from t1 union select count(*) from t1)),11) and 11 or (exists(select 1 from t1 where not exists(select 1 from t1 where c not between ( -b) and e))) and b not between 17 and t1.a and 19<b then 17 else f end) from t1 where t1.b between t1.c and 13 and t1.b<>e),17) FROM t1 WHERE NOT (case case 13+coalesce((select max( -t1.b*t1.c) from t1 where t1.c*c<>(select  -(count(distinct e)) from t1)-t1.c | t1.d*t1.e+11*t1.a+11-t1.a*b),d)+t1.d+e when t1.f then e else  -11 end-d when t1.e then 11 else f end+f=19)}
} {17}
do_test randexpr-2.1711 {
  db eval {SELECT 13+coalesce((select  -(abs(b)/abs(coalesce((select (abs(e+t1.a)/abs(13)) from t1 where a<c), -19)+t1.a+t1.c)) from t1 where (not t1.a not between e and e)),t1.d) FROM t1 WHERE ~(abs(t1.f)/abs(f)) not in (f,case c when coalesce((select max(17) from t1 where case when 17 not between 13 and 11+case when exists(select 1 from t1 where t1.e<c) then case when d between f and t1.c then 19 when 11 in (t1.a,11,e) then a else t1.e end else 13 end | 11+17 then t1.e else e end<>17 and t1.d<>t1.f),17)+a- -t1.d then t1.d else  -t1.b end,b)}
} {413}
do_test randexpr-2.1712 {
  db eval {SELECT 13+coalesce((select  -(abs(b)/abs(coalesce((select (abs(e+t1.a)/abs(13)) from t1 where a<c), -19)+t1.a+t1.c)) from t1 where (not t1.a not between e and e)),t1.d) FROM t1 WHERE NOT (~(abs(t1.f)/abs(f)) not in (f,case c when coalesce((select max(17) from t1 where case when 17 not between 13 and 11+case when exists(select 1 from t1 where t1.e<c) then case when d between f and t1.c then 19 when 11 in (t1.a,11,e) then a else t1.e end else 13 end | 11+17 then t1.e else e end<>17 and t1.d<>t1.f),17)+a- -t1.d then t1.d else  -t1.b end,b))}
} {}
do_test randexpr-2.1713 {
  db eval {SELECT (~(abs(case when t1.f*17 not in (coalesce((select 13 from t1 where d in (select count(distinct t1.e- -t1.e+t1.e*11) from t1 union select (abs(~~(cast(avg(d) AS integer))* -(min(13))+max(d) | min(13))) from t1)),d),a,t1.e) then c else t1.c end-c)/abs((t1.d)))*t1.c)*t1.d+t1.b-b FROM t1 WHERE (abs(case when (t1.e+case when t1.f+t1.d*t1.c<=t1.f or t1.c>=a and a not between 19 and t1.e then e else b end-t1.c) | t1.b<>19 then t1.f when 19<=t1.d and not  -t1.c>=11 and t1.a between t1.f and (19) then b else t1.c end)/abs(b))+11>=t1.f and t1.f not between f and t1.a}
} {}
do_test randexpr-2.1714 {
  db eval {SELECT (~(abs(case when t1.f*17 not in (coalesce((select 13 from t1 where d in (select count(distinct t1.e- -t1.e+t1.e*11) from t1 union select (abs(~~(cast(avg(d) AS integer))* -(min(13))+max(d) | min(13))) from t1)),d),a,t1.e) then c else t1.c end-c)/abs((t1.d)))*t1.c)*t1.d+t1.b-b FROM t1 WHERE NOT ((abs(case when (t1.e+case when t1.f+t1.d*t1.c<=t1.f or t1.c>=a and a not between 19 and t1.e then e else b end-t1.c) | t1.b<>19 then t1.f when 19<=t1.d and not  -t1.c>=11 and t1.a between t1.f and (19) then b else t1.c end)/abs(b))+11>=t1.f and t1.f not between f and t1.a)}
} {-120000}
do_test randexpr-2.1715 {
  db eval {SELECT (~(abs(case when t1.f*17 not in (coalesce((select 13 from t1 where d in (select count(distinct t1.e- -t1.e+t1.e*11) from t1 union select (abs(~~(cast(avg(d) AS integer))* -(min(13))+max(d) & min(13))) from t1)),d),a,t1.e) then c else t1.c end-c)/abs((t1.d)))*t1.c)*t1.d+t1.b-b FROM t1 WHERE NOT ((abs(case when (t1.e+case when t1.f+t1.d*t1.c<=t1.f or t1.c>=a and a not between 19 and t1.e then e else b end-t1.c) | t1.b<>19 then t1.f when 19<=t1.d and not  -t1.c>=11 and t1.a between t1.f and (19) then b else t1.c end)/abs(b))+11>=t1.f and t1.f not between f and t1.a)}
} {-120000}
do_test randexpr-2.1716 {
  db eval {SELECT (abs(a)/abs(case when (not t1.f in (select count(*) from t1 union select  - -min(c) | min(13*t1.d) from t1)) and ( -t1.a*t1.d)>=d or (t1.a in (a,11,f)) or (c>=t1.a) then 17+case when not exists(select 1 from t1 where e<t1.f) then + -(e)-d when t1.e in (19,19, -e) then  -t1.f else t1.a end else t1.b end)) FROM t1 WHERE t1.d in (select min(t1.d) from t1 union select +~case abs(max(case when t1.e not between 19-f | f | t1.c and b then t1.b else e end+b) | count(distinct f)) when count(distinct e) then count(*) else (+count(*)-(count(*))+min(t1.d)) end from t1) and (f)*coalesce((select 17 from t1 where f between t1.e and a),(13))<=b}
} {}
do_test randexpr-2.1717 {
  db eval {SELECT (abs(a)/abs(case when (not t1.f in (select count(*) from t1 union select  - -min(c) | min(13*t1.d) from t1)) and ( -t1.a*t1.d)>=d or (t1.a in (a,11,f)) or (c>=t1.a) then 17+case when not exists(select 1 from t1 where e<t1.f) then + -(e)-d when t1.e in (19,19, -e) then  -t1.f else t1.a end else t1.b end)) FROM t1 WHERE NOT (t1.d in (select min(t1.d) from t1 union select +~case abs(max(case when t1.e not between 19-f | f | t1.c and b then t1.b else e end+b) | count(distinct f)) when count(distinct e) then count(*) else (+count(*)-(count(*))+min(t1.d)) end from t1) and (f)*coalesce((select 17 from t1 where f between t1.e and a),(13))<=b)}
} {0}
do_test randexpr-2.1718 {
  db eval {SELECT (abs(a)/abs(case when (not t1.f in (select count(*) from t1 union select  - -min(c) & min(13*t1.d) from t1)) and ( -t1.a*t1.d)>=d or (t1.a in (a,11,f)) or (c>=t1.a) then 17+case when not exists(select 1 from t1 where e<t1.f) then + -(e)-d when t1.e in (19,19, -e) then  -t1.f else t1.a end else t1.b end)) FROM t1 WHERE NOT (t1.d in (select min(t1.d) from t1 union select +~case abs(max(case when t1.e not between 19-f | f | t1.c and b then t1.b else e end+b) | count(distinct f)) when count(distinct e) then count(*) else (+count(*)-(count(*))+min(t1.d)) end from t1) and (f)*coalesce((select 17 from t1 where f between t1.e and a),(13))<=b)}
} {0}
do_test randexpr-2.1719 {
  db eval {SELECT +case when case when coalesce((select c from t1 where (exists(select 1 from t1 where not (abs(b)/abs(t1.b)) not between f and 19 and  -b>c)) and 13 between t1.c and 17 or a=13),coalesce((select a from t1 where (t1.d) in (c,11,t1.c)),t1.d)) | c | coalesce((select max(d) from t1 where t1.b>b),t1.a)=19 then e else 13 end between t1.a and t1.f and 17>=c then a when d in (e,13,c) or t1.b<> -19 then (17) else 17 end FROM t1 WHERE  -b in (t1.b,t1.f,case when a in (select case +(min(t1.c)*+~cast(avg(+t1.f) AS integer)*cast(avg(d) AS integer) | abs(count(*))+count(*)*count(distinct 17)) when count(distinct e) then  -cast(avg(t1.a) AS integer) else min(11) end from t1 union select ((min(13))) from t1) then (abs(t1.d)/abs(case when  -19<b then t1.e- -f+f else b end)) when t1.a between t1.f and 13 then f else t1.e end)}
} {}
do_test randexpr-2.1720 {
  db eval {SELECT +case when case when coalesce((select c from t1 where (exists(select 1 from t1 where not (abs(b)/abs(t1.b)) not between f and 19 and  -b>c)) and 13 between t1.c and 17 or a=13),coalesce((select a from t1 where (t1.d) in (c,11,t1.c)),t1.d)) | c | coalesce((select max(d) from t1 where t1.b>b),t1.a)=19 then e else 13 end between t1.a and t1.f and 17>=c then a when d in (e,13,c) or t1.b<> -19 then (17) else 17 end FROM t1 WHERE NOT ( -b in (t1.b,t1.f,case when a in (select case +(min(t1.c)*+~cast(avg(+t1.f) AS integer)*cast(avg(d) AS integer) | abs(count(*))+count(*)*count(distinct 17)) when count(distinct e) then  -cast(avg(t1.a) AS integer) else min(11) end from t1 union select ((min(13))) from t1) then (abs(t1.d)/abs(case when  -19<b then t1.e- -f+f else b end)) when t1.a between t1.f and 13 then f else t1.e end))}
} {17}
do_test randexpr-2.1721 {
  db eval {SELECT +case when case when coalesce((select c from t1 where (exists(select 1 from t1 where not (abs(b)/abs(t1.b)) not between f and 19 and  -b>c)) and 13 between t1.c and 17 or a=13),coalesce((select a from t1 where (t1.d) in (c,11,t1.c)),t1.d)) & c & coalesce((select max(d) from t1 where t1.b>b),t1.a)=19 then e else 13 end between t1.a and t1.f and 17>=c then a when d in (e,13,c) or t1.b<> -19 then (17) else 17 end FROM t1 WHERE NOT ( -b in (t1.b,t1.f,case when a in (select case +(min(t1.c)*+~cast(avg(+t1.f) AS integer)*cast(avg(d) AS integer) | abs(count(*))+count(*)*count(distinct 17)) when count(distinct e) then  -cast(avg(t1.a) AS integer) else min(11) end from t1 union select ((min(13))) from t1) then (abs(t1.d)/abs(case when  -19<b then t1.e- -f+f else b end)) when t1.a between t1.f and 13 then f else t1.e end))}
} {17}
do_test randexpr-2.1722 {
  db eval {SELECT coalesce((select t1.b from t1 where not exists(select 1 from t1 where 13 in (select count(*) | ~min((select max((abs(d)/abs(t1.e+t1.e))) from t1)* -case when f*case e*~a when case e when (d) then 19 else (b) end then d else 17 end*t1.b between 11 and 13 then e when d in (a,(19),e) then c else 13 end-e*17) from t1 union select (count(*)) from t1))),f) FROM t1 WHERE not exists(select 1 from t1 where t1.a<>e)}
} {}
do_test randexpr-2.1723 {
  db eval {SELECT coalesce((select t1.b from t1 where not exists(select 1 from t1 where 13 in (select count(*) | ~min((select max((abs(d)/abs(t1.e+t1.e))) from t1)* -case when f*case e*~a when case e when (d) then 19 else (b) end then d else 17 end*t1.b between 11 and 13 then e when d in (a,(19),e) then c else 13 end-e*17) from t1 union select (count(*)) from t1))),f) FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a<>e))}
} {200}
do_test randexpr-2.1724 {
  db eval {SELECT coalesce((select t1.b from t1 where not exists(select 1 from t1 where 13 in (select count(*) & ~min((select max((abs(d)/abs(t1.e+t1.e))) from t1)* -case when f*case e*~a when case e when (d) then 19 else (b) end then d else 17 end*t1.b between 11 and 13 then e when d in (a,(19),e) then c else 13 end-e*17) from t1 union select (count(*)) from t1))),f) FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a<>e))}
} {200}
do_test randexpr-2.1725 {
  db eval {SELECT  - -case b when +~coalesce((select max(coalesce((select c from t1 where coalesce((select max(t1.a+f) from t1 where (t1.a not between t1.a and t1.e)),t1.a)-b not between e and  -t1.d),d)+19) from t1 where (f in (select ( -count(*) | count(*)+cast(avg(11) AS integer)) from t1 union select count(distinct 13) from t1) or  -b<>19 or 17>=t1.a)),t1.e)-c-t1.d then t1.a else 19 end- - -11 FROM t1 WHERE d+a*~coalesce((select max((select count(distinct t1.e)-max(t1.d) from t1)) from t1 where not exists(select 1 from t1 where t1.e in (11-f*19,a,c-b)) and 11=t1.b),t1.a)=(t1.b) and  -t1.b<case when (+11 | coalesce((select t1.f from t1 where b<=(t1.b) and  -t1.e<=(t1.f)),13) | t1.e between 13 and 19) then 17 else 11 end}
} {}
do_test randexpr-2.1726 {
  db eval {SELECT  - -case b when +~coalesce((select max(coalesce((select c from t1 where coalesce((select max(t1.a+f) from t1 where (t1.a not between t1.a and t1.e)),t1.a)-b not between e and  -t1.d),d)+19) from t1 where (f in (select ( -count(*) | count(*)+cast(avg(11) AS integer)) from t1 union select count(distinct 13) from t1) or  -b<>19 or 17>=t1.a)),t1.e)-c-t1.d then t1.a else 19 end- - -11 FROM t1 WHERE NOT (d+a*~coalesce((select max((select count(distinct t1.e)-max(t1.d) from t1)) from t1 where not exists(select 1 from t1 where t1.e in (11-f*19,a,c-b)) and 11=t1.b),t1.a)=(t1.b) and  -t1.b<case when (+11 | coalesce((select t1.f from t1 where b<=(t1.b) and  -t1.e<=(t1.f)),13) | t1.e between 13 and 19) then 17 else 11 end)}
} {8}
do_test randexpr-2.1727 {
  db eval {SELECT  - -case b when +~coalesce((select max(coalesce((select c from t1 where coalesce((select max(t1.a+f) from t1 where (t1.a not between t1.a and t1.e)),t1.a)-b not between e and  -t1.d),d)+19) from t1 where (f in (select ( -count(*) & count(*)+cast(avg(11) AS integer)) from t1 union select count(distinct 13) from t1) or  -b<>19 or 17>=t1.a)),t1.e)-c-t1.d then t1.a else 19 end- - -11 FROM t1 WHERE NOT (d+a*~coalesce((select max((select count(distinct t1.e)-max(t1.d) from t1)) from t1 where not exists(select 1 from t1 where t1.e in (11-f*19,a,c-b)) and 11=t1.b),t1.a)=(t1.b) and  -t1.b<case when (+11 | coalesce((select t1.f from t1 where b<=(t1.b) and  -t1.e<=(t1.f)),13) | t1.e between 13 and 19) then 17 else 11 end)}
} {8}
do_test randexpr-2.1728 {
  db eval {SELECT  -(abs(t1.a)/abs(case when coalesce((select max( -c) from t1 where t1.a*e>coalesce((select max(coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where e | t1.f-19 between t1.e-a and b and e>=t1.d)),+d)) from t1 where (exists(select 1 from t1 where t1.b in (select 19 from t1 union select 17 from t1) or 11 between t1.b and d))),c)),t1.e)*t1.a<=c then b else t1.d end)) FROM t1 WHERE (select abs( -abs(abs(case count(*) when ~ -min(f)+case  - -abs(+cast(avg(c*17) AS integer)) when count(*) then max(t1.a) else max(11) end+(cast(avg(e) AS integer)) then min(17) else count(*) end-cast(avg(a) AS integer)-count(*))))+ -cast(avg(t1.a) AS integer) | ((count(*))) from t1)+f in (select max((abs(+11*t1.a)/abs(t1.f))) from t1 union select max(d)-(( -count(distinct 11))) from t1)}
} {}
do_test randexpr-2.1729 {
  db eval {SELECT  -(abs(t1.a)/abs(case when coalesce((select max( -c) from t1 where t1.a*e>coalesce((select max(coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where e | t1.f-19 between t1.e-a and b and e>=t1.d)),+d)) from t1 where (exists(select 1 from t1 where t1.b in (select 19 from t1 union select 17 from t1) or 11 between t1.b and d))),c)),t1.e)*t1.a<=c then b else t1.d end)) FROM t1 WHERE NOT ((select abs( -abs(abs(case count(*) when ~ -min(f)+case  - -abs(+cast(avg(c*17) AS integer)) when count(*) then max(t1.a) else max(11) end+(cast(avg(e) AS integer)) then min(17) else count(*) end-cast(avg(a) AS integer)-count(*))))+ -cast(avg(t1.a) AS integer) | ((count(*))) from t1)+f in (select max((abs(+11*t1.a)/abs(t1.f))) from t1 union select max(d)-(( -count(distinct 11))) from t1))}
} {0}
do_test randexpr-2.1730 {
  db eval {SELECT  -(abs(t1.a)/abs(case when coalesce((select max( -c) from t1 where t1.a*e>coalesce((select max(coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where e & t1.f-19 between t1.e-a and b and e>=t1.d)),+d)) from t1 where (exists(select 1 from t1 where t1.b in (select 19 from t1 union select 17 from t1) or 11 between t1.b and d))),c)),t1.e)*t1.a<=c then b else t1.d end)) FROM t1 WHERE NOT ((select abs( -abs(abs(case count(*) when ~ -min(f)+case  - -abs(+cast(avg(c*17) AS integer)) when count(*) then max(t1.a) else max(11) end+(cast(avg(e) AS integer)) then min(17) else count(*) end-cast(avg(a) AS integer)-count(*))))+ -cast(avg(t1.a) AS integer) | ((count(*))) from t1)+f in (select max((abs(+11*t1.a)/abs(t1.f))) from t1 union select max(d)-(( -count(distinct 11))) from t1))}
} {0}
do_test randexpr-2.1731 {
  db eval {SELECT case when ((select (+~~max(13)*count(distinct t1.c)) from t1)<>(select (+ -count(*)) from t1)) then +(17) else 19 end+~(abs(13)/abs(d))-t1.d FROM t1 WHERE coalesce((select (select  -+ -count(distinct a)*count(*)+max(t1.b) from t1) from t1 where exists(select 1 from t1 where t1.b=c)),t1.c)+f<>t1.f}
} {-384}
do_test randexpr-2.1732 {
  db eval {SELECT case when ((select (+~~max(13)*count(distinct t1.c)) from t1)<>(select (+ -count(*)) from t1)) then +(17) else 19 end+~(abs(13)/abs(d))-t1.d FROM t1 WHERE NOT (coalesce((select (select  -+ -count(distinct a)*count(*)+max(t1.b) from t1) from t1 where exists(select 1 from t1 where t1.b=c)),t1.c)+f<>t1.f)}
} {}
do_test randexpr-2.1733 {
  db eval {SELECT case t1.f when case when 17<=c and coalesce((select case when e in (case when (t1.a=c) then b else  -13 end,t1.d,t1.a) then 13 else t1.b end from t1 where (b)=13),t1.d) in ((t1.e),b,t1.b) and d not between 19 and 11 then +(select ~ -~max(e)+count(*)+cast(avg((t1.c)) AS integer) from t1) when t1.f<>e and t1.e<d then t1.c else 19 end then t1.a else t1.f end FROM t1 WHERE t1.b between t1.b and case when ((select abs(cast(avg( -17+f) AS integer)) from t1) between  -a and c) then case when coalesce((select max(d) from t1 where 11 in (select max(c) | (count(distinct 13)) from t1 union select count(*) from t1)),13) | t1.a between 13 and t1.f then f else (c) end-c when f in (19,(f), -13) then f else (t1.f) end-d or (f) not in (b,c,d)}
} {600}
do_test randexpr-2.1734 {
  db eval {SELECT case t1.f when case when 17<=c and coalesce((select case when e in (case when (t1.a=c) then b else  -13 end,t1.d,t1.a) then 13 else t1.b end from t1 where (b)=13),t1.d) in ((t1.e),b,t1.b) and d not between 19 and 11 then +(select ~ -~max(e)+count(*)+cast(avg((t1.c)) AS integer) from t1) when t1.f<>e and t1.e<d then t1.c else 19 end then t1.a else t1.f end FROM t1 WHERE NOT (t1.b between t1.b and case when ((select abs(cast(avg( -17+f) AS integer)) from t1) between  -a and c) then case when coalesce((select max(d) from t1 where 11 in (select max(c) | (count(distinct 13)) from t1 union select count(*) from t1)),13) | t1.a between 13 and t1.f then f else (c) end-c when f in (19,(f), -13) then f else (t1.f) end-d or (f) not in (b,c,d))}
} {}
do_test randexpr-2.1735 {
  db eval {SELECT t1.c+b+t1.c*case when f in (select max(case when not t1.e<case when (select ~+(min(13)) from t1)+t1.e in (select  -+count(*) from t1 union select ((cast(avg(e) AS integer))) from t1) then c when t1.f not between f and t1.f or (c) in (t1.e,c,d) then c else 11 end then +f else b end)-count(*) from t1 union select +min(11)-count(distinct t1.e) from t1) then d else 17 end-19 FROM t1 WHERE (select abs(case (count(distinct case when not exists(select 1 from t1 where  -t1.c=t1.c) and t1.d not in (13,t1.c,t1.c) then case (19)-c when t1.b then 11 else t1.f end else t1.d end+t1.c)+max(11)) when (count(distinct t1.f)*count(distinct 19)) then  -max(f) else count(*) end) from t1)*coalesce((select max(e) from t1 where (abs(case  -d when t1.b then 19 else t1.e end)/abs(c))< -e), -b)-e<=f}
} {5581}
do_test randexpr-2.1736 {
  db eval {SELECT t1.c+b+t1.c*case when f in (select max(case when not t1.e<case when (select ~+(min(13)) from t1)+t1.e in (select  -+count(*) from t1 union select ((cast(avg(e) AS integer))) from t1) then c when t1.f not between f and t1.f or (c) in (t1.e,c,d) then c else 11 end then +f else b end)-count(*) from t1 union select +min(11)-count(distinct t1.e) from t1) then d else 17 end-19 FROM t1 WHERE NOT ((select abs(case (count(distinct case when not exists(select 1 from t1 where  -t1.c=t1.c) and t1.d not in (13,t1.c,t1.c) then case (19)-c when t1.b then 11 else t1.f end else t1.d end+t1.c)+max(11)) when (count(distinct t1.f)*count(distinct 19)) then  -max(f) else count(*) end) from t1)*coalesce((select max(e) from t1 where (abs(case  -d when t1.b then 19 else t1.e end)/abs(c))< -e), -b)-e<=f)}
} {}
do_test randexpr-2.1737 {
  db eval {SELECT +case + -(+t1.a)-~13+t1.b*t1.b+ -c+(select abs(case ~max(t1.c)++min( -13)+ -count(*)+(count(*)) | ((cast(avg(t1.e) AS integer))) when min(t1.c) then min(t1.d) else min(b) end)+min(13) | count(distinct f) | min(t1.a) from t1) when t1.e then 11-17 else t1.b*c end FROM t1 WHERE (~coalesce((select max(coalesce((select max(19) from t1 where case when case f-(coalesce((select ~11 from t1 where  -19= -t1.f or b=t1.b),13)) when 19 then t1.d else t1.b end<=17 then 17 when t1.b>t1.e then t1.d else (d) end in (select count(*) from t1 union select  -abs(~abs(count(distinct d)) | min(t1.e))*count(*) from t1)),t1.f)) from t1 where a>13),d) not between t1.d and c)}
} {60000}
do_test randexpr-2.1738 {
  db eval {SELECT +case + -(+t1.a)-~13+t1.b*t1.b+ -c+(select abs(case ~max(t1.c)++min( -13)+ -count(*)+(count(*)) | ((cast(avg(t1.e) AS integer))) when min(t1.c) then min(t1.d) else min(b) end)+min(13) | count(distinct f) | min(t1.a) from t1) when t1.e then 11-17 else t1.b*c end FROM t1 WHERE NOT ((~coalesce((select max(coalesce((select max(19) from t1 where case when case f-(coalesce((select ~11 from t1 where  -19= -t1.f or b=t1.b),13)) when 19 then t1.d else t1.b end<=17 then 17 when t1.b>t1.e then t1.d else (d) end in (select count(*) from t1 union select  -abs(~abs(count(distinct d)) | min(t1.e))*count(*) from t1)),t1.f)) from t1 where a>13),d) not between t1.d and c))}
} {}
do_test randexpr-2.1739 {
  db eval {SELECT +case + -(+t1.a)-~13+t1.b*t1.b+ -c+(select abs(case ~max(t1.c)++min( -13)+ -count(*)+(count(*)) & ((cast(avg(t1.e) AS integer))) when min(t1.c) then min(t1.d) else min(b) end)+min(13) & count(distinct f) & min(t1.a) from t1) when t1.e then 11-17 else t1.b*c end FROM t1 WHERE (~coalesce((select max(coalesce((select max(19) from t1 where case when case f-(coalesce((select ~11 from t1 where  -19= -t1.f or b=t1.b),13)) when 19 then t1.d else t1.b end<=17 then 17 when t1.b>t1.e then t1.d else (d) end in (select count(*) from t1 union select  -abs(~abs(count(distinct d)) | min(t1.e))*count(*) from t1)),t1.f)) from t1 where a>13),d) not between t1.d and c)}
} {60000}
do_test randexpr-2.1740 {
  db eval {SELECT (abs(e)/abs((+b)*coalesce((select c+c+t1.a+t1.e+t1.a+t1.a | 17+e*(t1.c) from t1 where a in (select count(distinct t1.c)-+count(*) from t1 union select  - -( -max(t1.f))-count(distinct t1.b)+min(t1.b)*count(*)+count(distinct a) from t1)),t1.a)+e))*19 FROM t1 WHERE coalesce((select 11 from t1 where case t1.e-(t1.a) when (f) then ((19)) else t1.f end+ -t1.b+a+coalesce((select coalesce((select d from t1 where exists(select 1 from t1 where 13+(t1.a)<>19 or 17 not in (c,e,t1.c) or f not in (t1.e,t1.a, -f))),~ -13+e) from t1 where b between (11) and t1.f),t1.a)<=t1.d), -c)<=11}
} {0}
do_test randexpr-2.1741 {
  db eval {SELECT (abs(e)/abs((+b)*coalesce((select c+c+t1.a+t1.e+t1.a+t1.a | 17+e*(t1.c) from t1 where a in (select count(distinct t1.c)-+count(*) from t1 union select  - -( -max(t1.f))-count(distinct t1.b)+min(t1.b)*count(*)+count(distinct a) from t1)),t1.a)+e))*19 FROM t1 WHERE NOT (coalesce((select 11 from t1 where case t1.e-(t1.a) when (f) then ((19)) else t1.f end+ -t1.b+a+coalesce((select coalesce((select d from t1 where exists(select 1 from t1 where 13+(t1.a)<>19 or 17 not in (c,e,t1.c) or f not in (t1.e,t1.a, -f))),~ -13+e) from t1 where b between (11) and t1.f),t1.a)<=t1.d), -c)<=11)}
} {}
do_test randexpr-2.1742 {
  db eval {SELECT (abs(e)/abs((+b)*coalesce((select c+c+t1.a+t1.e+t1.a+t1.a & 17+e*(t1.c) from t1 where a in (select count(distinct t1.c)-+count(*) from t1 union select  - -( -max(t1.f))-count(distinct t1.b)+min(t1.b)*count(*)+count(distinct a) from t1)),t1.a)+e))*19 FROM t1 WHERE coalesce((select 11 from t1 where case t1.e-(t1.a) when (f) then ((19)) else t1.f end+ -t1.b+a+coalesce((select coalesce((select d from t1 where exists(select 1 from t1 where 13+(t1.a)<>19 or 17 not in (c,e,t1.c) or f not in (t1.e,t1.a, -f))),~ -13+e) from t1 where b between (11) and t1.f),t1.a)<=t1.d), -c)<=11}
} {0}
do_test randexpr-2.1743 {
  db eval {SELECT case coalesce((select t1.f from t1 where not exists(select 1 from t1 where coalesce((select max(d) from t1 where 13 not in (11,coalesce((select max((+f)) from t1 where not d>=f or e in (select 11-t1.b from t1 union select t1.d from t1) or not exists(select 1 from t1 where  -b in (select t1.d from t1 union select b from t1) or t1.a<>b or t1.d>e) or t1.a not between (t1.f) and t1.e),+f),t1.e)),t1.f)*t1.b not in (13,t1.b,t1.f))),t1.a)*b when c then b else t1.f end FROM t1 WHERE case when c*coalesce((select max(19+t1.e*~case case t1.e when t1.f then  -t1.a else 11 end when 11 then t1.a else (select cast(avg(a) AS integer) from t1) end- -t1.b*coalesce((select 19 from t1 where t1.f in ((a),t1.d,t1.c)),a)) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where t1.a not in (t1.b,t1.a,17)))),13)>=a then b when t1.c>t1.a then d else 17 end not in (a,17,t1.b)}
} {600}
do_test randexpr-2.1744 {
  db eval {SELECT case coalesce((select t1.f from t1 where not exists(select 1 from t1 where coalesce((select max(d) from t1 where 13 not in (11,coalesce((select max((+f)) from t1 where not d>=f or e in (select 11-t1.b from t1 union select t1.d from t1) or not exists(select 1 from t1 where  -b in (select t1.d from t1 union select b from t1) or t1.a<>b or t1.d>e) or t1.a not between (t1.f) and t1.e),+f),t1.e)),t1.f)*t1.b not in (13,t1.b,t1.f))),t1.a)*b when c then b else t1.f end FROM t1 WHERE NOT (case when c*coalesce((select max(19+t1.e*~case case t1.e when t1.f then  -t1.a else 11 end when 11 then t1.a else (select cast(avg(a) AS integer) from t1) end- -t1.b*coalesce((select 19 from t1 where t1.f in ((a),t1.d,t1.c)),a)) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where t1.a not in (t1.b,t1.a,17)))),13)>=a then b when t1.c>t1.a then d else 17 end not in (a,17,t1.b))}
} {}
do_test randexpr-2.1745 {
  db eval {SELECT (abs(case when (c*+~t1.d++t1.b+a-case when (select +case count(*)+min(d) when  -count(distinct 17) then max(t1.b) else  -cast(avg(d) AS integer) end from t1) in (select cast(avg(c) AS integer) from t1 union select ((count(*))) from t1) then t1.a* -f else f end*c*19-(f)-t1.c-t1.f+t1.d>=f) then (t1.d) else d end)/abs(t1.b)) FROM t1 WHERE coalesce((select a from t1 where t1.d not in ( -13*d,19,t1.a)),(abs(coalesce((select case when c>=t1.e then b else case ~t1.d+a-+t1.b+17 when case when t1.e+t1.e not between e and (c) then t1.d when d>a then t1.d else t1.c end | t1.a-(d) then t1.f else c end end from t1 where d>=t1.c),13))/abs(t1.c)))=t1.e}
} {}
do_test randexpr-2.1746 {
  db eval {SELECT (abs(case when (c*+~t1.d++t1.b+a-case when (select +case count(*)+min(d) when  -count(distinct 17) then max(t1.b) else  -cast(avg(d) AS integer) end from t1) in (select cast(avg(c) AS integer) from t1 union select ((count(*))) from t1) then t1.a* -f else f end*c*19-(f)-t1.c-t1.f+t1.d>=f) then (t1.d) else d end)/abs(t1.b)) FROM t1 WHERE NOT (coalesce((select a from t1 where t1.d not in ( -13*d,19,t1.a)),(abs(coalesce((select case when c>=t1.e then b else case ~t1.d+a-+t1.b+17 when case when t1.e+t1.e not between e and (c) then t1.d when d>a then t1.d else t1.c end | t1.a-(d) then t1.f else c end end from t1 where d>=t1.c),13))/abs(t1.c)))=t1.e)}
} {2}
do_test randexpr-2.1747 {
  db eval {SELECT d+coalesce((select max(coalesce((select f from t1 where coalesce((select 17 | t1.b from t1 where 11 not in ((t1.e),+a-f,t1.c | b+17*t1.e-c)), -c) in (select  -count(distinct e)-+max(t1.b) from t1 union select count(distinct c)+cast(avg(t1.b) AS integer) from t1)),17)) from t1 where not t1.c<t1.e),17)+b+e FROM t1 WHERE case t1.f when t1.a then t1.e else d-case when e<>(select ~~+(min(11-11)) | ~ -(count(*)) from t1)*(case when t1.d=19 then a when not t1.a in (11,t1.e,c) or t1.a not between t1.f and e then t1.a else t1.e end+19) then 13 when 19 between  -17 and t1.a then t1.a else 19 end end>=t1.f and t1.e>t1.a}
} {}
do_test randexpr-2.1748 {
  db eval {SELECT d+coalesce((select max(coalesce((select f from t1 where coalesce((select 17 | t1.b from t1 where 11 not in ((t1.e),+a-f,t1.c | b+17*t1.e-c)), -c) in (select  -count(distinct e)-+max(t1.b) from t1 union select count(distinct c)+cast(avg(t1.b) AS integer) from t1)),17)) from t1 where not t1.c<t1.e),17)+b+e FROM t1 WHERE NOT (case t1.f when t1.a then t1.e else d-case when e<>(select ~~+(min(11-11)) | ~ -(count(*)) from t1)*(case when t1.d=19 then a when not t1.a in (11,t1.e,c) or t1.a not between t1.f and e then t1.a else t1.e end+19) then 13 when 19 between  -17 and t1.a then t1.a else 19 end end>=t1.f and t1.e>t1.a)}
} {1117}
do_test randexpr-2.1749 {
  db eval {SELECT d+coalesce((select max(coalesce((select f from t1 where coalesce((select 17 & t1.b from t1 where 11 not in ((t1.e),+a-f,t1.c & b+17*t1.e-c)), -c) in (select  -count(distinct e)-+max(t1.b) from t1 union select count(distinct c)+cast(avg(t1.b) AS integer) from t1)),17)) from t1 where not t1.c<t1.e),17)+b+e FROM t1 WHERE NOT (case t1.f when t1.a then t1.e else d-case when e<>(select ~~+(min(11-11)) | ~ -(count(*)) from t1)*(case when t1.d=19 then a when not t1.a in (11,t1.e,c) or t1.a not between t1.f and e then t1.a else t1.e end+19) then 13 when 19 between  -17 and t1.a then t1.a else 19 end end>=t1.f and t1.e>t1.a)}
} {1117}
do_test randexpr-2.1750 {
  db eval {SELECT (select case ~ -(~case case cast(avg(t1.e) AS integer) when min(case when t1.c between coalesce((select t1.b from t1 where d in (select f from t1 union select t1.e from t1)),(e)) and t1.d and (19=(11)) then 17 else b end) | max((13))-min(t1.c) |  -count(distinct t1.d)*max(11) then count(*) else max(f) end*count(*)-(( -count(distinct f))) when min(t1.c) then (count(distinct (13))) else max((b)) end)+max(t1.a) when (max(t1.c)) then  -cast(avg(a) AS integer) else cast(avg(t1.c) AS integer) end from t1) FROM t1 WHERE (f) not between c and 17 | t1.b | coalesce((select t1.d from t1 where t1.d*~case when a<=f or (case t1.f when d+17+17 then e else +case when (11<>17) then 11 when  -t1.b not in (e,19,(f)) then t1.c else a end+13 end>= -t1.f) then ~ -t1.c else c end*t1.f*a*17<=t1.f),17)}
} {300}
do_test randexpr-2.1751 {
  db eval {SELECT (select case ~ -(~case case cast(avg(t1.e) AS integer) when min(case when t1.c between coalesce((select t1.b from t1 where d in (select f from t1 union select t1.e from t1)),(e)) and t1.d and (19=(11)) then 17 else b end) | max((13))-min(t1.c) |  -count(distinct t1.d)*max(11) then count(*) else max(f) end*count(*)-(( -count(distinct f))) when min(t1.c) then (count(distinct (13))) else max((b)) end)+max(t1.a) when (max(t1.c)) then  -cast(avg(a) AS integer) else cast(avg(t1.c) AS integer) end from t1) FROM t1 WHERE NOT ((f) not between c and 17 | t1.b | coalesce((select t1.d from t1 where t1.d*~case when a<=f or (case t1.f when d+17+17 then e else +case when (11<>17) then 11 when  -t1.b not in (e,19,(f)) then t1.c else a end+13 end>= -t1.f) then ~ -t1.c else c end*t1.f*a*17<=t1.f),17))}
} {}
do_test randexpr-2.1752 {
  db eval {SELECT (select case ~ -(~case case cast(avg(t1.e) AS integer) when min(case when t1.c between coalesce((select t1.b from t1 where d in (select f from t1 union select t1.e from t1)),(e)) and t1.d and (19=(11)) then 17 else b end) & max((13))-min(t1.c) &  -count(distinct t1.d)*max(11) then count(*) else max(f) end*count(*)-(( -count(distinct f))) when min(t1.c) then (count(distinct (13))) else max((b)) end)+max(t1.a) when (max(t1.c)) then  -cast(avg(a) AS integer) else cast(avg(t1.c) AS integer) end from t1) FROM t1 WHERE (f) not between c and 17 | t1.b | coalesce((select t1.d from t1 where t1.d*~case when a<=f or (case t1.f when d+17+17 then e else +case when (11<>17) then 11 when  -t1.b not in (e,19,(f)) then t1.c else a end+13 end>= -t1.f) then ~ -t1.c else c end*t1.f*a*17<=t1.f),17)}
} {300}
do_test randexpr-2.1753 {
  db eval {SELECT (select abs(min(t1.b)) from t1)-f | case when +t1.d*d not in (t1.f,t1.a,case when ~t1.f-17*c<>t1.a then 11 when 19 in (select (+count(distinct b)) | cast(avg(19) AS integer)*count(*) from t1 union select count(distinct t1.d) from t1) then d else d end+19+b) then (a) else 17 end*13+d FROM t1 WHERE t1.f<>(abs(t1.a)/abs(coalesce((select max(case when coalesce((select max((select count(*) from t1)) from t1 where f<>t1.a),coalesce((select max(11) from t1 where 17+coalesce((select t1.a from t1 where a in (select +~cast(avg(d+11) AS integer) from t1 union select count(distinct coalesce((select max((13)) from t1 where not (t1.f)<>19),f)*d) from t1)),19)+t1.e between 13 and (t1.b)),e))>=e then d else t1.f end) from t1 where ((not f>= -t1.b))),t1.c)))}
} {-268}
do_test randexpr-2.1754 {
  db eval {SELECT (select abs(min(t1.b)) from t1)-f | case when +t1.d*d not in (t1.f,t1.a,case when ~t1.f-17*c<>t1.a then 11 when 19 in (select (+count(distinct b)) | cast(avg(19) AS integer)*count(*) from t1 union select count(distinct t1.d) from t1) then d else d end+19+b) then (a) else 17 end*13+d FROM t1 WHERE NOT (t1.f<>(abs(t1.a)/abs(coalesce((select max(case when coalesce((select max((select count(*) from t1)) from t1 where f<>t1.a),coalesce((select max(11) from t1 where 17+coalesce((select t1.a from t1 where a in (select +~cast(avg(d+11) AS integer) from t1 union select count(distinct coalesce((select max((13)) from t1 where not (t1.f)<>19),f)*d) from t1)),19)+t1.e between 13 and (t1.b)),e))>=e then d else t1.f end) from t1 where ((not f>= -t1.b))),t1.c))))}
} {}
do_test randexpr-2.1755 {
  db eval {SELECT (select abs(min(t1.b)) from t1)-f & case when +t1.d*d not in (t1.f,t1.a,case when ~t1.f-17*c<>t1.a then 11 when 19 in (select (+count(distinct b)) & cast(avg(19) AS integer)*count(*) from t1 union select count(distinct t1.d) from t1) then d else d end+19+b) then (a) else 17 end*13+d FROM t1 WHERE t1.f<>(abs(t1.a)/abs(coalesce((select max(case when coalesce((select max((select count(*) from t1)) from t1 where f<>t1.a),coalesce((select max(11) from t1 where 17+coalesce((select t1.a from t1 where a in (select +~cast(avg(d+11) AS integer) from t1 union select count(distinct coalesce((select max((13)) from t1 where not (t1.f)<>19),f)*d) from t1)),19)+t1.e between 13 and (t1.b)),e))>=e then d else t1.f end) from t1 where ((not f>= -t1.b))),t1.c)))}
} {1568}
do_test randexpr-2.1756 {
  db eval {SELECT coalesce((select max(a) from t1 where a>a*(((t1.d)) | a)-+case t1.a-t1.d-19+coalesce((select max(t1.c) from t1 where ~(select  -cast(avg(a+d) AS integer) from t1) not in (~((17)),t1.a,(t1.e))),b)+a*(c) when t1.f then a else t1.f end-17+c),13)*t1.a FROM t1 WHERE t1.b*t1.d*11*case 13 | t1.a when (case when not exists(select 1 from t1 where t1.a not between coalesce((select f-a from t1 where a not in (11,d,(a)) or e<=d and 11=t1.e),d)+e and t1.c) and (t1.a>=t1.f or (t1.a)>=t1.a) then (c)+t1.d else a end)* -t1.a then e else t1.f end | 13>=b}
} {1300}
do_test randexpr-2.1757 {
  db eval {SELECT coalesce((select max(a) from t1 where a>a*(((t1.d)) | a)-+case t1.a-t1.d-19+coalesce((select max(t1.c) from t1 where ~(select  -cast(avg(a+d) AS integer) from t1) not in (~((17)),t1.a,(t1.e))),b)+a*(c) when t1.f then a else t1.f end-17+c),13)*t1.a FROM t1 WHERE NOT (t1.b*t1.d*11*case 13 | t1.a when (case when not exists(select 1 from t1 where t1.a not between coalesce((select f-a from t1 where a not in (11,d,(a)) or e<=d and 11=t1.e),d)+e and t1.c) and (t1.a>=t1.f or (t1.a)>=t1.a) then (c)+t1.d else a end)* -t1.a then e else t1.f end | 13>=b)}
} {}
do_test randexpr-2.1758 {
  db eval {SELECT coalesce((select max(a) from t1 where a>a*(((t1.d)) & a)-+case t1.a-t1.d-19+coalesce((select max(t1.c) from t1 where ~(select  -cast(avg(a+d) AS integer) from t1) not in (~((17)),t1.a,(t1.e))),b)+a*(c) when t1.f then a else t1.f end-17+c),13)*t1.a FROM t1 WHERE t1.b*t1.d*11*case 13 | t1.a when (case when not exists(select 1 from t1 where t1.a not between coalesce((select f-a from t1 where a not in (11,d,(a)) or e<=d and 11=t1.e),d)+e and t1.c) and (t1.a>=t1.f or (t1.a)>=t1.a) then (c)+t1.d else a end)* -t1.a then e else t1.f end | 13>=b}
} {10000}
do_test randexpr-2.1759 {
  db eval {SELECT (abs(t1.f)/abs(11*19 | case when (e+t1.b*t1.d+(abs(case  -13+t1.d*t1.a-+coalesce((select t1.d from t1 where t1.b not between b and d and d in (select c from t1 union select d from t1)),(19)) when d then 13 else d end*t1.e)/abs(d))+f not between e and t1.a) then ( -f) else d end*a)) FROM t1 WHERE a in (select abs(max(b))-count(distinct case when d not between coalesce((select max(13) from t1 where a+a<+(19)), -f*case (select  -cast(avg(t1.c) AS integer)*cast(avg(c) AS integer)-cast(avg(13) AS integer) from t1)*coalesce((select d from t1 where (e=(f))),t1.d) when t1.a then 17 else 19 end) and d then t1.f when (19 between t1.e and  -a) then t1.a else (t1.c) end) from t1 union select max(t1.e)+~min(t1.c) from t1)}
} {}
do_test randexpr-2.1760 {
  db eval {SELECT (abs(t1.f)/abs(11*19 | case when (e+t1.b*t1.d+(abs(case  -13+t1.d*t1.a-+coalesce((select t1.d from t1 where t1.b not between b and d and d in (select c from t1 union select d from t1)),(19)) when d then 13 else d end*t1.e)/abs(d))+f not between e and t1.a) then ( -f) else d end*a)) FROM t1 WHERE NOT (a in (select abs(max(b))-count(distinct case when d not between coalesce((select max(13) from t1 where a+a<+(19)), -f*case (select  -cast(avg(t1.c) AS integer)*cast(avg(c) AS integer)-cast(avg(13) AS integer) from t1)*coalesce((select d from t1 where (e=(f))),t1.d) when t1.a then 17 else 19 end) and d then t1.f when (19 between t1.e and  -a) then t1.a else (t1.c) end) from t1 union select max(t1.e)+~min(t1.c) from t1))}
} {0}
do_test randexpr-2.1761 {
  db eval {SELECT (abs(t1.f)/abs(11*19 & case when (e+t1.b*t1.d+(abs(case  -13+t1.d*t1.a-+coalesce((select t1.d from t1 where t1.b not between b and d and d in (select c from t1 union select d from t1)),(19)) when d then 13 else d end*t1.e)/abs(d))+f not between e and t1.a) then ( -f) else d end*a)) FROM t1 WHERE NOT (a in (select abs(max(b))-count(distinct case when d not between coalesce((select max(13) from t1 where a+a<+(19)), -f*case (select  -cast(avg(t1.c) AS integer)*cast(avg(c) AS integer)-cast(avg(13) AS integer) from t1)*coalesce((select d from t1 where (e=(f))),t1.d) when t1.a then 17 else 19 end) and d then t1.f when (19 between t1.e and  -a) then t1.a else (t1.c) end) from t1 union select max(t1.e)+~min(t1.c) from t1))}
} {4}
do_test randexpr-2.1762 {
  db eval {SELECT +t1.d | (d)*t1.e | (select case abs((max(t1.e)-abs(+case min(a) | (~(min(~t1.c)))*(abs(abs(count(*))+count(distinct b)*count(distinct 17)))*max(c) when max(t1.c) then max(t1.d) else cast(avg(d) AS integer) end | max(t1.a))))*cast(avg(11) AS integer) when (cast(avg( -a) AS integer)) then min(19) else  -count(distinct 13) end from t1)+t1.b FROM t1 WHERE not exists(select 1 from t1 where e<t1.a)}
} {200151}
do_test randexpr-2.1763 {
  db eval {SELECT +t1.d | (d)*t1.e | (select case abs((max(t1.e)-abs(+case min(a) | (~(min(~t1.c)))*(abs(abs(count(*))+count(distinct b)*count(distinct 17)))*max(c) when max(t1.c) then max(t1.d) else cast(avg(d) AS integer) end | max(t1.a))))*cast(avg(11) AS integer) when (cast(avg( -a) AS integer)) then min(19) else  -count(distinct 13) end from t1)+t1.b FROM t1 WHERE NOT (not exists(select 1 from t1 where e<t1.a))}
} {}
do_test randexpr-2.1764 {
  db eval {SELECT +t1.d & (d)*t1.e & (select case abs((max(t1.e)-abs(+case min(a) & (~(min(~t1.c)))*(abs(abs(count(*))+count(distinct b)*count(distinct 17)))*max(c) when max(t1.c) then max(t1.d) else cast(avg(d) AS integer) end & max(t1.a))))*cast(avg(11) AS integer) when (cast(avg( -a) AS integer)) then min(19) else  -count(distinct 13) end from t1)+t1.b FROM t1 WHERE not exists(select 1 from t1 where e<t1.a)}
} {0}
do_test randexpr-2.1765 {
  db eval {SELECT coalesce((select max(e) from t1 where  -(abs(~(t1.f+b))/abs(t1.f)) not in (~case 11+c*case when  -t1.d not between coalesce((select max(d) from t1 where f- -t1.f+t1.f-13-e<c),(f)) and a then t1.d else t1.a end when d then 17 else 13 end,d,c) or exists(select 1 from t1 where b<d)),13) FROM t1 WHERE (case when (t1.f<>13) or t1.a*t1.f- -a>=t1.d or d in (select  -case cast(avg(b) AS integer) when max(19) then count(distinct  -t1.f) else count(distinct f) end* -max(t1.d) from t1 union select  -cast(avg(13) AS integer) from t1) and 11 between t1.f and d then case when t1.f not between b and 13 then f else t1.e end-t1.c when t1.d in (t1.e,b,d) then t1.f else  -t1.d end-t1.d)*d*f>=a}
} {}
do_test randexpr-2.1766 {
  db eval {SELECT coalesce((select max(e) from t1 where  -(abs(~(t1.f+b))/abs(t1.f)) not in (~case 11+c*case when  -t1.d not between coalesce((select max(d) from t1 where f- -t1.f+t1.f-13-e<c),(f)) and a then t1.d else t1.a end when d then 17 else 13 end,d,c) or exists(select 1 from t1 where b<d)),13) FROM t1 WHERE NOT ((case when (t1.f<>13) or t1.a*t1.f- -a>=t1.d or d in (select  -case cast(avg(b) AS integer) when max(19) then count(distinct  -t1.f) else count(distinct f) end* -max(t1.d) from t1 union select  -cast(avg(13) AS integer) from t1) and 11 between t1.f and d then case when t1.f not between b and 13 then f else t1.e end-t1.c when t1.d in (t1.e,b,d) then t1.f else  -t1.d end-t1.d)*d*f>=a)}
} {500}
do_test randexpr-2.1767 {
  db eval {SELECT case when ~case when t1.a | case when exists(select 1 from t1 where 19 in (select (count(*))-count(*) from t1 union select  -min(b) from t1) or t1.f not in (17,11,t1.c) and t1.d in (a,19,t1.a)) then ~c | 11 else 17 end* -19 in (select count(*) from t1 union select abs( - -case ~cast(avg(t1.b) AS integer) when min(b) then max(a) else (max( -d)) end | count(*)) from t1) then t1.a else t1.c end | b in (select f from t1 union select 13 from t1) then t1.b when t1.a<>(17) then c else t1.a end FROM t1 WHERE exists(select 1 from t1 where d<>13)}
} {300}
do_test randexpr-2.1768 {
  db eval {SELECT case when ~case when t1.a | case when exists(select 1 from t1 where 19 in (select (count(*))-count(*) from t1 union select  -min(b) from t1) or t1.f not in (17,11,t1.c) and t1.d in (a,19,t1.a)) then ~c | 11 else 17 end* -19 in (select count(*) from t1 union select abs( - -case ~cast(avg(t1.b) AS integer) when min(b) then max(a) else (max( -d)) end | count(*)) from t1) then t1.a else t1.c end | b in (select f from t1 union select 13 from t1) then t1.b when t1.a<>(17) then c else t1.a end FROM t1 WHERE NOT (exists(select 1 from t1 where d<>13))}
} {}
do_test randexpr-2.1769 {
  db eval {SELECT case when ~case when t1.a & case when exists(select 1 from t1 where 19 in (select (count(*))-count(*) from t1 union select  -min(b) from t1) or t1.f not in (17,11,t1.c) and t1.d in (a,19,t1.a)) then ~c & 11 else 17 end* -19 in (select count(*) from t1 union select abs( - -case ~cast(avg(t1.b) AS integer) when min(b) then max(a) else (max( -d)) end & count(*)) from t1) then t1.a else t1.c end & b in (select f from t1 union select 13 from t1) then t1.b when t1.a<>(17) then c else t1.a end FROM t1 WHERE exists(select 1 from t1 where d<>13)}
} {300}
do_test randexpr-2.1770 {
  db eval {SELECT coalesce((select a+t1.d from t1 where t1.d+coalesce((select max(case when e not between 11 and case when (abs(f)/abs(t1.f+19*t1.b))>e then ~d when not not 17 in (13,17,t1.a) then f else t1.f end then 11 when b<17 then t1.b else f end) from t1 where exists(select 1 from t1 where (c<>c))), -f)+t1.c in (select (t1.e) from t1 union select c from t1)),c) FROM t1 WHERE not (t1.a)<=case a when t1.f then +coalesce((select max(c) from t1 where (abs(d-11)/abs(t1.a))+t1.f<=d*d*t1.a+coalesce((select 19 from t1 where (select cast(avg(f) AS integer) from t1)*t1.f+19+ -13 in ((t1.d),c,t1.a)),t1.c) or ((not exists(select 1 from t1 where 19 in (select e from t1 union select  -11 from t1))))),c) else e end}
} {}
do_test randexpr-2.1771 {
  db eval {SELECT coalesce((select a+t1.d from t1 where t1.d+coalesce((select max(case when e not between 11 and case when (abs(f)/abs(t1.f+19*t1.b))>e then ~d when not not 17 in (13,17,t1.a) then f else t1.f end then 11 when b<17 then t1.b else f end) from t1 where exists(select 1 from t1 where (c<>c))), -f)+t1.c in (select (t1.e) from t1 union select c from t1)),c) FROM t1 WHERE NOT (not (t1.a)<=case a when t1.f then +coalesce((select max(c) from t1 where (abs(d-11)/abs(t1.a))+t1.f<=d*d*t1.a+coalesce((select 19 from t1 where (select cast(avg(f) AS integer) from t1)*t1.f+19+ -13 in ((t1.d),c,t1.a)),t1.c) or ((not exists(select 1 from t1 where 19 in (select e from t1 union select  -11 from t1))))),c) else e end)}
} {300}
do_test randexpr-2.1772 {
  db eval {SELECT (abs( -c+b)/abs(case when ~11 in (select t1.c from t1 union select coalesce((select t1.f from t1 where coalesce((select max(17) from t1 where coalesce((select case  -t1.d when t1.e then a else b end-(t1.d) from t1 where t1.a not between  -a and t1.b or t1.f<t1.e and e<=a),t1.e)*t1.d not in (b,11,t1.f)),19)<19 and not exists(select 1 from t1 where t1.f>=t1.b) and (f)>= -13),t1.b) from t1) then t1.c when t1.b<=t1.f then 13 else t1.e end)) FROM t1 WHERE (d-coalesce((select max(case 11 when +13-17 | 13 | coalesce((select t1.b from t1 where ((abs(t1.b)/abs((abs(b)/abs(+(19)))*t1.c)) | a in ( -t1.c,t1.a,t1.b))),d)* -d then 13 else 11 end) from t1 where e not in (d,11,11) or t1.e>t1.e),17)+t1.a>b)}
} {7}
do_test randexpr-2.1773 {
  db eval {SELECT (abs( -c+b)/abs(case when ~11 in (select t1.c from t1 union select coalesce((select t1.f from t1 where coalesce((select max(17) from t1 where coalesce((select case  -t1.d when t1.e then a else b end-(t1.d) from t1 where t1.a not between  -a and t1.b or t1.f<t1.e and e<=a),t1.e)*t1.d not in (b,11,t1.f)),19)<19 and not exists(select 1 from t1 where t1.f>=t1.b) and (f)>= -13),t1.b) from t1) then t1.c when t1.b<=t1.f then 13 else t1.e end)) FROM t1 WHERE NOT ((d-coalesce((select max(case 11 when +13-17 | 13 | coalesce((select t1.b from t1 where ((abs(t1.b)/abs((abs(b)/abs(+(19)))*t1.c)) | a in ( -t1.c,t1.a,t1.b))),d)* -d then 13 else 11 end) from t1 where e not in (d,11,11) or t1.e>t1.e),17)+t1.a>b))}
} {}
do_test randexpr-2.1774 {
  db eval {SELECT coalesce((select max(17) from t1 where (e* -t1.f*e*c-coalesce((select max(t1.f) from t1 where t1.c between case when e+~ -t1.e+11 in (select c from t1 union select t1.a from t1) and t1.d>=c then 19 else ( - -(t1.a)) end*c+f and t1.b),13) not in (t1.b,e,t1.c) and (11) not in (b,( -t1.b),13))),19) FROM t1 WHERE d>e+f}
} {}
do_test randexpr-2.1775 {
  db eval {SELECT coalesce((select max(17) from t1 where (e* -t1.f*e*c-coalesce((select max(t1.f) from t1 where t1.c between case when e+~ -t1.e+11 in (select c from t1 union select t1.a from t1) and t1.d>=c then 19 else ( - -(t1.a)) end*c+f and t1.b),13) not in (t1.b,e,t1.c) and (11) not in (b,( -t1.b),13))),19) FROM t1 WHERE NOT (d>e+f)}
} {17}
do_test randexpr-2.1776 {
  db eval {SELECT case when t1.b in (select case 13-(select case count(*) when count(distinct (abs(19)/abs(t1.d)))*~count(distinct 13)*(max((abs(t1.e*d*f)/abs(17)))) then  -case  - -count(distinct e) when min(19) then (cast(avg(17) AS integer)) else count(distinct t1.a) end*max(t1.b)-cast(avg(a) AS integer) else count(distinct t1.d) end from t1)+t1.b*d when t1.c+t1.a then f else t1.f end from t1 union select t1.c from t1) then t1.a when a in (select 11 from t1 union select a from t1) then a else e end FROM t1 WHERE (case when case 11+case f when e then d else (abs(e)/abs(19))*a end when 19 then b else d end<t1.d then t1.c when b>= -19 then 13 else t1.e end between 17 and t1.a or b>=17 and ((( -t1.f))>=t1.c and 17 between t1.c and 19 and t1.c between t1.d and a or t1.d=17) or c in (b,13,17))}
} {}
do_test randexpr-2.1777 {
  db eval {SELECT case when t1.b in (select case 13-(select case count(*) when count(distinct (abs(19)/abs(t1.d)))*~count(distinct 13)*(max((abs(t1.e*d*f)/abs(17)))) then  -case  - -count(distinct e) when min(19) then (cast(avg(17) AS integer)) else count(distinct t1.a) end*max(t1.b)-cast(avg(a) AS integer) else count(distinct t1.d) end from t1)+t1.b*d when t1.c+t1.a then f else t1.f end from t1 union select t1.c from t1) then t1.a when a in (select 11 from t1 union select a from t1) then a else e end FROM t1 WHERE NOT ((case when case 11+case f when e then d else (abs(e)/abs(19))*a end when 19 then b else d end<t1.d then t1.c when b>= -19 then 13 else t1.e end between 17 and t1.a or b>=17 and ((( -t1.f))>=t1.c and 17 between t1.c and 19 and t1.c between t1.d and a or t1.d=17) or c in (b,13,17)))}
} {100}
do_test randexpr-2.1778 {
  db eval {SELECT case when coalesce((select case when (not exists(select 1 from t1 where t1.f<>t1.f)) then case when d-t1.e*t1.d=((select (count(distinct t1.a)) from t1)) then t1.a when 13 not in ( -b,13,19) then t1.b else e end when t1.e=13 then e else 17 end-17*b from t1 where (t1.d in (d,t1.e,t1.f))),( -f)) not in (d,t1.e,c) then t1.d else  -t1.f end* -t1.b FROM t1 WHERE not exists(select 1 from t1 where 11 in (select max(coalesce((select max(case when e+coalesce((select max(d) from t1 where not a<t1.c),(a)) in (((f)),c,13) then t1.e else e end-d) from t1 where 17 between (c) and t1.c),17)) from t1 union select ( -case cast(avg(c) AS integer) when case min(11) when ( -min(e)) then min(t1.b) else min(f) end then  -min(b) else count(distinct 13) end+min(13)- - -count(*)) from t1) or 17 in (19,t1.d,(a)) and exists(select 1 from t1 where t1.e in (t1.d,e,11)))}
} {}
do_test randexpr-2.1779 {
  db eval {SELECT case when coalesce((select case when (not exists(select 1 from t1 where t1.f<>t1.f)) then case when d-t1.e*t1.d=((select (count(distinct t1.a)) from t1)) then t1.a when 13 not in ( -b,13,19) then t1.b else e end when t1.e=13 then e else 17 end-17*b from t1 where (t1.d in (d,t1.e,t1.f))),( -f)) not in (d,t1.e,c) then t1.d else  -t1.f end* -t1.b FROM t1 WHERE NOT (not exists(select 1 from t1 where 11 in (select max(coalesce((select max(case when e+coalesce((select max(d) from t1 where not a<t1.c),(a)) in (((f)),c,13) then t1.e else e end-d) from t1 where 17 between (c) and t1.c),17)) from t1 union select ( -case cast(avg(c) AS integer) when case min(11) when ( -min(e)) then min(t1.b) else min(f) end then  -min(b) else count(distinct 13) end+min(13)- - -count(*)) from t1) or 17 in (19,t1.d,(a)) and exists(select 1 from t1 where t1.e in (t1.d,e,11))))}
} {-80000}
do_test randexpr-2.1780 {
  db eval {SELECT coalesce((select (abs(~c*t1.a+t1.b*coalesce((select case c when b+coalesce((select t1.b-case e when 19 then b else b end*11 from t1 where t1.b<>b or not t1.f in (11,t1.a,t1.e)),t1.a) | e then c else e end from t1 where  -t1.a<11),13))/abs(t1.b))-t1.b*17 from t1 where c=t1.c),17) FROM t1 WHERE t1.e+e>=coalesce((select max(t1.d) from t1 where +(t1.f) not between c and f),case when exists(select 1 from t1 where t1.e+t1.c<>(abs(e*(select  -count(*) from t1))/abs(t1.e*coalesce((select max((select cast(avg(13) AS integer) from t1)) from t1 where not (a) not between  -c and  -17), -d)+ -a+t1.f))) then case when e between 17 and d then a else 19 end when not c between e and 11 then 13 else t1.a end)}
} {-3051}
do_test randexpr-2.1781 {
  db eval {SELECT coalesce((select (abs(~c*t1.a+t1.b*coalesce((select case c when b+coalesce((select t1.b-case e when 19 then b else b end*11 from t1 where t1.b<>b or not t1.f in (11,t1.a,t1.e)),t1.a) | e then c else e end from t1 where  -t1.a<11),13))/abs(t1.b))-t1.b*17 from t1 where c=t1.c),17) FROM t1 WHERE NOT (t1.e+e>=coalesce((select max(t1.d) from t1 where +(t1.f) not between c and f),case when exists(select 1 from t1 where t1.e+t1.c<>(abs(e*(select  -count(*) from t1))/abs(t1.e*coalesce((select max((select cast(avg(13) AS integer) from t1)) from t1 where not (a) not between  -c and  -17), -d)+ -a+t1.f))) then case when e between 17 and d then a else 19 end when not c between e and 11 then 13 else t1.a end))}
} {}
do_test randexpr-2.1782 {
  db eval {SELECT coalesce((select (abs(~c*t1.a+t1.b*coalesce((select case c when b+coalesce((select t1.b-case e when 19 then b else b end*11 from t1 where t1.b<>b or not t1.f in (11,t1.a,t1.e)),t1.a) & e then c else e end from t1 where  -t1.a<11),13))/abs(t1.b))-t1.b*17 from t1 where c=t1.c),17) FROM t1 WHERE t1.e+e>=coalesce((select max(t1.d) from t1 where +(t1.f) not between c and f),case when exists(select 1 from t1 where t1.e+t1.c<>(abs(e*(select  -count(*) from t1))/abs(t1.e*coalesce((select max((select cast(avg(13) AS integer) from t1)) from t1 where not (a) not between  -c and  -17), -d)+ -a+t1.f))) then case when e between 17 and d then a else 19 end when not c between e and 11 then 13 else t1.a end)}
} {-3051}
do_test randexpr-2.1783 {
  db eval {SELECT t1.a-~17-t1.c+t1.c | (c) | (13)*coalesce((select max((case when 11 in (case when (19 in (select abs(max(c)) from t1 union select ( -cast(avg(19) AS integer)) from t1)) then 13 when t1.a= -t1.a then t1.b else c end,a,13) then t1.e when t1.b in (t1.a,13, -19) then d else t1.a end)) from t1 where t1.d between t1.d and t1.b and t1.d<=17),t1.d)*11 | t1.e FROM t1 WHERE e in (select 11 from t1 union select a from t1)}
} {}
do_test randexpr-2.1784 {
  db eval {SELECT t1.a-~17-t1.c+t1.c | (c) | (13)*coalesce((select max((case when 11 in (case when (19 in (select abs(max(c)) from t1 union select ( -cast(avg(19) AS integer)) from t1)) then 13 when t1.a= -t1.a then t1.b else c end,a,13) then t1.e when t1.b in (t1.a,13, -19) then d else t1.a end)) from t1 where t1.d between t1.d and t1.b and t1.d<=17),t1.d)*11 | t1.e FROM t1 WHERE NOT (e in (select 11 from t1 union select a from t1))}
} {57342}
do_test randexpr-2.1785 {
  db eval {SELECT t1.a-~17-t1.c+t1.c & (c) & (13)*coalesce((select max((case when 11 in (case when (19 in (select abs(max(c)) from t1 union select ( -cast(avg(19) AS integer)) from t1)) then 13 when t1.a= -t1.a then t1.b else c end,a,13) then t1.e when t1.b in (t1.a,13, -19) then d else t1.a end)) from t1 where t1.d between t1.d and t1.b and t1.d<=17),t1.d)*11 & t1.e FROM t1 WHERE NOT (e in (select 11 from t1 union select a from t1))}
} {32}
do_test randexpr-2.1786 {
  db eval {SELECT (abs(case when 11 not between t1.d and case coalesce((select case c+case when b in (case when a<=t1.b then (t1.a) when f not in (d,t1.f, -(a)) then (t1.a) else c end,t1.a,b) then 11 when (t1.c not between 17 and  -d) then t1.d else e end+e*t1.a when 19 then b else t1.e end from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where  -(19)=d))),t1.d) when c then a else  -17 end or a>=19 then 17 else b end+ -13)/abs(b)) FROM t1 WHERE not exists(select 1 from t1 where not e+case 13 when 11 then +t1.d else t1.f+11 end*a-19+t1.c+a in (~e | coalesce((select ~a*+(abs( -case case b*e when f then e else  -13 end when t1.d then t1.b else t1.b end)/abs(17))+t1.b from t1 where t1.a=e),d),e,e))}
} {}
do_test randexpr-2.1787 {
  db eval {SELECT (abs(case when 11 not between t1.d and case coalesce((select case c+case when b in (case when a<=t1.b then (t1.a) when f not in (d,t1.f, -(a)) then (t1.a) else c end,t1.a,b) then 11 when (t1.c not between 17 and  -d) then t1.d else e end+e*t1.a when 19 then b else t1.e end from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where  -(19)=d))),t1.d) when c then a else  -17 end or a>=19 then 17 else b end+ -13)/abs(b)) FROM t1 WHERE NOT (not exists(select 1 from t1 where not e+case 13 when 11 then +t1.d else t1.f+11 end*a-19+t1.c+a in (~e | coalesce((select ~a*+(abs( -case case b*e when f then e else  -13 end when t1.d then t1.b else t1.b end)/abs(17))+t1.b from t1 where t1.a=e),d),e,e)))}
} {0}
do_test randexpr-2.1788 {
  db eval {SELECT t1.c-coalesce((select t1.e from t1 where not 17 | (select abs(min((t1.c) | +case 19 when d then f else t1.c end*(13)+a)- -count(*)) from t1)>t1.c and (exists(select 1 from t1 where c in (select f from t1 union select a from t1))) or t1.e>t1.c),coalesce((select e*(e) from t1 where not exists(select 1 from t1 where b not in (f,a,19))),c)) FROM t1 WHERE t1.f*t1.e*b+coalesce((select case when 17 not in (case e++t1.d+19*11 when case when 11 in (select  -min(t1.a)*min(t1.e)+cast(avg(t1.a) AS integer) from t1 union select  -count(*) from t1) then 13 else 11 end*17 then a else t1.a end,(t1.b),t1.d) then t1.f else  -b end from t1 where t1.b not between 17 and (a)),d)-t1.d-c*b<c}
} {}
do_test randexpr-2.1789 {
  db eval {SELECT t1.c-coalesce((select t1.e from t1 where not 17 | (select abs(min((t1.c) | +case 19 when d then f else t1.c end*(13)+a)- -count(*)) from t1)>t1.c and (exists(select 1 from t1 where c in (select f from t1 union select a from t1))) or t1.e>t1.c),coalesce((select e*(e) from t1 where not exists(select 1 from t1 where b not in (f,a,19))),c)) FROM t1 WHERE NOT (t1.f*t1.e*b+coalesce((select case when 17 not in (case e++t1.d+19*11 when case when 11 in (select  -min(t1.a)*min(t1.e)+cast(avg(t1.a) AS integer) from t1 union select  -count(*) from t1) then 13 else 11 end*17 then a else t1.a end,(t1.b),t1.d) then t1.f else  -b end from t1 where t1.b not between 17 and (a)),d)-t1.d-c*b<c)}
} {-200}
do_test randexpr-2.1790 {
  db eval {SELECT t1.c-coalesce((select t1.e from t1 where not 17 & (select abs(min((t1.c) & +case 19 when d then f else t1.c end*(13)+a)- -count(*)) from t1)>t1.c and (exists(select 1 from t1 where c in (select f from t1 union select a from t1))) or t1.e>t1.c),coalesce((select e*(e) from t1 where not exists(select 1 from t1 where b not in (f,a,19))),c)) FROM t1 WHERE NOT (t1.f*t1.e*b+coalesce((select case when 17 not in (case e++t1.d+19*11 when case when 11 in (select  -min(t1.a)*min(t1.e)+cast(avg(t1.a) AS integer) from t1 union select  -count(*) from t1) then 13 else 11 end*17 then a else t1.a end,(t1.b),t1.d) then t1.f else  -b end from t1 where t1.b not between 17 and (a)),d)-t1.d-c*b<c)}
} {-200}
do_test randexpr-2.1791 {
  db eval {SELECT c-coalesce((select max(case when (case t1.a when a then case f when e*e then ~c | case when +c>= -b+t1.f | 19 then t1.d else 11 end else t1.a end-t1.e else d end not between f and t1.f) then c else e end) from t1 where f>=t1.b and t1.c between t1.f and t1.a),e)*d*b FROM t1 WHERE t1.b in (select 11-case when (t1.a+19<=case when c>=(19) then 11 else t1.e+t1.a*c end*e and t1.f in (select case abs(+abs( -count(*) | count(*)*count(distinct c)+max(13))) when min(d) then min(b) else min(t1.b) end | cast(avg(t1.e) AS integer) from t1 union select count(distinct t1.e) from t1)) then t1.a else t1.f end*17 from t1 union select t1.a from t1)}
} {}
do_test randexpr-2.1792 {
  db eval {SELECT c-coalesce((select max(case when (case t1.a when a then case f when e*e then ~c | case when +c>= -b+t1.f | 19 then t1.d else 11 end else t1.a end-t1.e else d end not between f and t1.f) then c else e end) from t1 where f>=t1.b and t1.c between t1.f and t1.a),e)*d*b FROM t1 WHERE NOT (t1.b in (select 11-case when (t1.a+19<=case when c>=(19) then 11 else t1.e+t1.a*c end*e and t1.f in (select case abs(+abs( -count(*) | count(*)*count(distinct c)+max(13))) when min(d) then min(b) else min(t1.b) end | cast(avg(t1.e) AS integer) from t1 union select count(distinct t1.e) from t1)) then t1.a else t1.f end*17 from t1 union select t1.a from t1))}
} {-39999700}
do_test randexpr-2.1793 {
  db eval {SELECT c-coalesce((select max(case when (case t1.a when a then case f when e*e then ~c & case when +c>= -b+t1.f & 19 then t1.d else 11 end else t1.a end-t1.e else d end not between f and t1.f) then c else e end) from t1 where f>=t1.b and t1.c between t1.f and t1.a),e)*d*b FROM t1 WHERE NOT (t1.b in (select 11-case when (t1.a+19<=case when c>=(19) then 11 else t1.e+t1.a*c end*e and t1.f in (select case abs(+abs( -count(*) | count(*)*count(distinct c)+max(13))) when min(d) then min(b) else min(t1.b) end | cast(avg(t1.e) AS integer) from t1 union select count(distinct t1.e) from t1)) then t1.a else t1.f end*17 from t1 union select t1.a from t1))}
} {-39999700}
do_test randexpr-2.1794 {
  db eval {SELECT coalesce((select f from t1 where ~coalesce((select max(b-e) from t1 where 13 in (select d from t1 union select d from t1)),(abs(t1.f)/abs(t1.f)))-t1.d+case a when t1.b then 13 else case when 19>case a when t1.a then 13 else  -d end or e<>c then coalesce((select max(a) from t1 where t1.e not between (13) and t1.d),11) when b in (select t1.a from t1 union select t1.f from t1) then 19 else a end end-b>11),17) FROM t1 WHERE b in (select e-17 from t1 union select d from t1)}
} {}
do_test randexpr-2.1795 {
  db eval {SELECT coalesce((select f from t1 where ~coalesce((select max(b-e) from t1 where 13 in (select d from t1 union select d from t1)),(abs(t1.f)/abs(t1.f)))-t1.d+case a when t1.b then 13 else case when 19>case a when t1.a then 13 else  -d end or e<>c then coalesce((select max(a) from t1 where t1.e not between (13) and t1.d),11) when b in (select t1.a from t1 union select t1.f from t1) then 19 else a end end-b>11),17) FROM t1 WHERE NOT (b in (select e-17 from t1 union select d from t1))}
} {17}
do_test randexpr-2.1796 {
  db eval {SELECT coalesce((select case case when 13<>((abs(t1.b)/abs(f+t1.c))) then 11 else coalesce((select max(b) from t1 where (b=(abs((select min((select case  -min(11) when count(distinct d) then count(*) else min(t1.c) end from t1)) from t1))/abs(t1.f))-c)), -19)*e end*d* -e+t1.d when 13 then c else c end+b from t1 where d>13 or (b between t1.e and 19)),a) FROM t1 WHERE not exists(select 1 from t1 where ((not not exists(select 1 from t1 where ((case when coalesce((select max(19) from t1 where case when b>=e and f between t1.d and t1.c or ( -t1.b)=t1.f then b+a else 11 end in (d,t1.d,(17))),t1.d)>t1.b then (t1.f) else d end*e*t1.e<=t1.b)) or 13<>13)) or 17<d) and t1.f in (t1.e,d,t1.b)) and e<=a}
} {}
do_test randexpr-2.1797 {
  db eval {SELECT coalesce((select case case when 13<>((abs(t1.b)/abs(f+t1.c))) then 11 else coalesce((select max(b) from t1 where (b=(abs((select min((select case  -min(11) when count(distinct d) then count(*) else min(t1.c) end from t1)) from t1))/abs(t1.f))-c)), -19)*e end*d* -e+t1.d when 13 then c else c end+b from t1 where d>13 or (b between t1.e and 19)),a) FROM t1 WHERE NOT (not exists(select 1 from t1 where ((not not exists(select 1 from t1 where ((case when coalesce((select max(19) from t1 where case when b>=e and f between t1.d and t1.c or ( -t1.b)=t1.f then b+a else 11 end in (d,t1.d,(17))),t1.d)>t1.b then (t1.f) else d end*e*t1.e<=t1.b)) or 13<>13)) or 17<d) and t1.f in (t1.e,d,t1.b)) and e<=a)}
} {500}
do_test randexpr-2.1798 {
  db eval {SELECT ~case when 19 not between ~case when coalesce((select max(t1.c*(select cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where case when (t1.b in (d,b,t1.c)) and 13>t1.d then e+t1.c when 19 between t1.f and t1.f then 11 else e end between t1.e and 17) and c=t1.f),t1.c) not between t1.a and (19) then c else t1.b end*a-19 and b then b when a not in (a,t1.f,11) then a else a end FROM t1 WHERE (select abs((+min(t1.c)*min(t1.d)*count(*)))*count(*)++count(distinct ~13*11+t1.f) | case abs(+count(*)) when min(t1.e) then count(*) else max(13) end from t1)*t1.b between d and a++19 and t1.c in (select ~((abs(17)/abs(c)))-d from t1 union select t1.f from t1)}
} {}
do_test randexpr-2.1799 {
  db eval {SELECT ~case when 19 not between ~case when coalesce((select max(t1.c*(select cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where case when (t1.b in (d,b,t1.c)) and 13>t1.d then e+t1.c when 19 between t1.f and t1.f then 11 else e end between t1.e and 17) and c=t1.f),t1.c) not between t1.a and (19) then c else t1.b end*a-19 and b then b when a not in (a,t1.f,11) then a else a end FROM t1 WHERE NOT ((select abs((+min(t1.c)*min(t1.d)*count(*)))*count(*)++count(distinct ~13*11+t1.f) | case abs(+count(*)) when min(t1.e) then count(*) else max(13) end from t1)*t1.b between d and a++19 and t1.c in (select ~((abs(17)/abs(c)))-d from t1 union select t1.f from t1))}
} {-101}
do_test randexpr-2.1800 {
  db eval {SELECT (t1.d)+(abs(coalesce((select ((abs(case t1.e when a+(abs(11)/abs(b)) then t1.f else case coalesce((select max(d+c) from t1 where +19+11<b),t1.d)-t1.d-t1.d*d when t1.c then  -e else t1.d end end-c)/abs(17))) from t1 where 17<>t1.c),d))/abs(t1.d))-11 | (17) | b FROM t1 WHERE (select ~min(b)+count(distinct 17) from t1)>(select max((abs((13))/abs(coalesce((select case when b*13 in (case when e=t1.b then c when 11<>e then f else t1.b end,t1.f,t1.a) then d when not exists(select 1 from t1 where t1.f<>e) then t1.a else c end from t1 where t1.e=13),t1.f) | b)))+(~~cast(avg(f) AS integer)-min((13))) from t1)}
} {}
do_test randexpr-2.1801 {
  db eval {SELECT (t1.d)+(abs(coalesce((select ((abs(case t1.e when a+(abs(11)/abs(b)) then t1.f else case coalesce((select max(d+c) from t1 where +19+11<b),t1.d)-t1.d-t1.d*d when t1.c then  -e else t1.d end end-c)/abs(17))) from t1 where 17<>t1.c),d))/abs(t1.d))-11 | (17) | b FROM t1 WHERE NOT ((select ~min(b)+count(distinct 17) from t1)>(select max((abs((13))/abs(coalesce((select case when b*13 in (case when e=t1.b then c when 11<>e then f else t1.b end,t1.f,t1.a) then d when not exists(select 1 from t1 where t1.f<>e) then t1.a else c end from t1 where t1.e=13),t1.f) | b)))+(~~cast(avg(f) AS integer)-min((13))) from t1))}
} {477}
do_test randexpr-2.1802 {
  db eval {SELECT (t1.d)+(abs(coalesce((select ((abs(case t1.e when a+(abs(11)/abs(b)) then t1.f else case coalesce((select max(d+c) from t1 where +19+11<b),t1.d)-t1.d-t1.d*d when t1.c then  -e else t1.d end end-c)/abs(17))) from t1 where 17<>t1.c),d))/abs(t1.d))-11 & (17) & b FROM t1 WHERE NOT ((select ~min(b)+count(distinct 17) from t1)>(select max((abs((13))/abs(coalesce((select case when b*13 in (case when e=t1.b then c when 11<>e then f else t1.b end,t1.f,t1.a) then d when not exists(select 1 from t1 where t1.f<>e) then t1.a else c end from t1 where t1.e=13),t1.f) | b)))+(~~cast(avg(f) AS integer)-min((13))) from t1))}
} {0}
do_test randexpr-2.1803 {
  db eval {SELECT d+case coalesce((select t1.f from t1 where coalesce((select max((11)) from t1 where (coalesce((select d from t1 where ((case b when ( -a) then 19 else e end)) not in ( -d,t1.c,13)),b))>t1.b and ((c in (select ~~cast(avg(t1.b) AS integer)+ -(max(t1.e)) from t1 union select max(c) from t1) and (e) in (select  -count(distinct 17) from t1 union select count(*) from t1) or 11<>t1.c))),t1.b) not between (f) and 11),t1.d) when (19) then e else 13 end-t1.f FROM t1 WHERE exists(select 1 from t1 where (t1.a between case when e | b*c-19 | a<t1.a or (19 in (select coalesce((select max(f) from t1 where e<19),t1.e-17 | t1.e) from t1 union select 13 from t1)) then coalesce((select t1.e from t1 where not exists(select 1 from t1 where 11<=19) or exists(select 1 from t1 where  -(e) between a and 19) or b between b and c),c) else f end and 19))}
} {}
do_test randexpr-2.1804 {
  db eval {SELECT d+case coalesce((select t1.f from t1 where coalesce((select max((11)) from t1 where (coalesce((select d from t1 where ((case b when ( -a) then 19 else e end)) not in ( -d,t1.c,13)),b))>t1.b and ((c in (select ~~cast(avg(t1.b) AS integer)+ -(max(t1.e)) from t1 union select max(c) from t1) and (e) in (select  -count(distinct 17) from t1 union select count(*) from t1) or 11<>t1.c))),t1.b) not between (f) and 11),t1.d) when (19) then e else 13 end-t1.f FROM t1 WHERE NOT (exists(select 1 from t1 where (t1.a between case when e | b*c-19 | a<t1.a or (19 in (select coalesce((select max(f) from t1 where e<19),t1.e-17 | t1.e) from t1 union select 13 from t1)) then coalesce((select t1.e from t1 where not exists(select 1 from t1 where 11<=19) or exists(select 1 from t1 where  -(e) between a and 19) or b between b and c),c) else f end and 19)))}
} {-187}
do_test randexpr-2.1805 {
  db eval {SELECT coalesce((select c from t1 where  - -19-coalesce((select t1.e from t1 where not f<=b-17 or not  -13>=f or (select  -count(*) from t1) in (select t1.c from t1 union select 17 from t1)),b)*e not between case coalesce((select max(~case when 17>t1.e then d else 13 end) from t1 where not t1.c<=17),t1.c) when 13 then c else t1.e end+t1.c-t1.e and t1.e),t1.e) FROM t1 WHERE case ~case when not exists(select 1 from t1 where f<=~t1.d) then (abs(coalesce((select ~19 from t1 where d+t1.f=b),d))/abs(e)) when d in (select +min(11) from t1 union select ( -abs(count(distinct e)))+count(distinct t1.a) from t1) then e else t1.d end when  -d then t1.e else t1.b end=t1.f or t1.d not in (t1.c,t1.e,t1.e) and t1.c not in (17,t1.a,e)}
} {300}
do_test randexpr-2.1806 {
  db eval {SELECT coalesce((select c from t1 where  - -19-coalesce((select t1.e from t1 where not f<=b-17 or not  -13>=f or (select  -count(*) from t1) in (select t1.c from t1 union select 17 from t1)),b)*e not between case coalesce((select max(~case when 17>t1.e then d else 13 end) from t1 where not t1.c<=17),t1.c) when 13 then c else t1.e end+t1.c-t1.e and t1.e),t1.e) FROM t1 WHERE NOT (case ~case when not exists(select 1 from t1 where f<=~t1.d) then (abs(coalesce((select ~19 from t1 where d+t1.f=b),d))/abs(e)) when d in (select +min(11) from t1 union select ( -abs(count(distinct e)))+count(distinct t1.a) from t1) then e else t1.d end when  -d then t1.e else t1.b end=t1.f or t1.d not in (t1.c,t1.e,t1.e) and t1.c not in (17,t1.a,e))}
} {}
do_test randexpr-2.1807 {
  db eval {SELECT case when t1.e<=~d then case when t1.d-e in (~t1.c-case e*case when t1.e not in (t1.d,19,f) then e else b end*e when (19) then t1.a else  -e end,19,17) then t1.f when t1.d not in (t1.b,b,17) then t1.b else 19 end when 13= -t1.f and not (19=t1.d) then t1.f else (d) end FROM t1 WHERE 19<>d}
} {400}
do_test randexpr-2.1808 {
  db eval {SELECT case when t1.e<=~d then case when t1.d-e in (~t1.c-case e*case when t1.e not in (t1.d,19,f) then e else b end*e when (19) then t1.a else  -e end,19,17) then t1.f when t1.d not in (t1.b,b,17) then t1.b else 19 end when 13= -t1.f and not (19=t1.d) then t1.f else (d) end FROM t1 WHERE NOT (19<>d)}
} {}
do_test randexpr-2.1809 {
  db eval {SELECT (select max(case when (t1.d<=t1.a*t1.b) then t1.e else case when t1.a> -t1.c*t1.f then b else b*(a) end end)*min(+ -19-(select min(a) from t1)-+17*case when not exists(select 1 from t1 where (select abs(cast(avg(a) AS integer)) from t1)=t1.a) then e when 19>=a then 13 else t1.a end*19-e) from t1) FROM t1 WHERE t1.e in (select max(t1.e)-cast(avg(e) AS integer) from t1 union select (~+count(*) | count(*) | cast(avg((abs(coalesce((select max(case f+c-17 when t1.b then t1.e else t1.d end) from t1 where 17 in (select a from t1 union select t1.b from t1)),a))/abs( -t1.e))) AS integer)+~case count(*) when cast(avg(t1.d) AS integer) then  -cast(avg(t1.e) AS integer) else count(distinct d) end-max(13)+ -min(t1.a) | min((17)) | count(distinct d))-min(e) from t1)}
} {}
do_test randexpr-2.1810 {
  db eval {SELECT (select max(case when (t1.d<=t1.a*t1.b) then t1.e else case when t1.a> -t1.c*t1.f then b else b*(a) end end)*min(+ -19-(select min(a) from t1)-+17*case when not exists(select 1 from t1 where (select abs(cast(avg(a) AS integer)) from t1)=t1.a) then e when 19>=a then 13 else t1.a end*19-e) from t1) FROM t1 WHERE NOT (t1.e in (select max(t1.e)-cast(avg(e) AS integer) from t1 union select (~+count(*) | count(*) | cast(avg((abs(coalesce((select max(case f+c-17 when t1.b then t1.e else t1.d end) from t1 where 17 in (select a from t1 union select t1.b from t1)),a))/abs( -t1.e))) AS integer)+~case count(*) when cast(avg(t1.d) AS integer) then  -cast(avg(t1.e) AS integer) else count(distinct d) end-max(13)+ -min(t1.a) | min((17)) | count(distinct d))-min(e) from t1))}
} {-16459500}
do_test randexpr-2.1811 {
  db eval {SELECT case when case (select max(t1.b)*min(case when (abs(t1.e)/abs(d)) in (select 19 from t1 union select +t1.d from t1) then t1.d when t1.d=d or 11 in (t1.c,b,t1.b) and 13 in (select max(b)-count(distinct b) from t1 union select count(distinct  -t1.c) from t1) then f else 17 end) from t1) when t1.a then 11 else t1.d end+t1.a>c or t1.c between 13 and a then f when (t1.b)>=t1.a then d else b end FROM t1 WHERE (not exists(select 1 from t1 where coalesce((select max(e) from t1 where  -b+a-(abs(c)/abs(b))-( -t1.a)-t1.c>=d),d) in (select count(distinct a) from t1 union select cast(avg(t1.b) AS integer) from t1) and exists(select 1 from t1 where not t1.d<>f) and t1.a in (select min(t1.a)+max(a)*max(19)*count(distinct c) from t1 union select ((count(distinct 11))) from t1) or t1.c>(13) and a between (t1.f) and 13))}
} {600}
do_test randexpr-2.1812 {
  db eval {SELECT case when case (select max(t1.b)*min(case when (abs(t1.e)/abs(d)) in (select 19 from t1 union select +t1.d from t1) then t1.d when t1.d=d or 11 in (t1.c,b,t1.b) and 13 in (select max(b)-count(distinct b) from t1 union select count(distinct  -t1.c) from t1) then f else 17 end) from t1) when t1.a then 11 else t1.d end+t1.a>c or t1.c between 13 and a then f when (t1.b)>=t1.a then d else b end FROM t1 WHERE NOT ((not exists(select 1 from t1 where coalesce((select max(e) from t1 where  -b+a-(abs(c)/abs(b))-( -t1.a)-t1.c>=d),d) in (select count(distinct a) from t1 union select cast(avg(t1.b) AS integer) from t1) and exists(select 1 from t1 where not t1.d<>f) and t1.a in (select min(t1.a)+max(a)*max(19)*count(distinct c) from t1 union select ((count(distinct 11))) from t1) or t1.c>(13) and a between (t1.f) and 13)))}
} {}
do_test randexpr-2.1813 {
  db eval {SELECT f*~13*(abs(13*d- -(abs(case when ~coalesce((select max(c) from t1 where b>case when not exists(select 1 from t1 where f not in ( - -(t1.b),t1.b,t1.f)) then e when t1.c<>f then c else 13 end),17) |  -19 not in (f,b,f) then  -b when not 13 in (select max((19)) from t1 union select count(*) | count(*) from t1) and 11 not between t1.b and e or 13 in (t1.a, -e,(t1.c)) then a else 11 end)/abs(t1.c))*b | t1.b)/abs(f))*f*f FROM t1 WHERE ~case f when coalesce((select max(17) from t1 where b+t1.f*case 11 when coalesce((select max(t1.f) from t1 where 17>t1.f),19)-t1.b-t1.b | d then b else c end+t1.d*11-t1.c<=case when b>=a then 19 else f end | t1.a),13) then f else t1.e end*t1.e*17-d in (select 13 from t1 union select t1.e from t1)}
} {}
do_test randexpr-2.1814 {
  db eval {SELECT f*~13*(abs(13*d- -(abs(case when ~coalesce((select max(c) from t1 where b>case when not exists(select 1 from t1 where f not in ( - -(t1.b),t1.b,t1.f)) then e when t1.c<>f then c else 13 end),17) |  -19 not in (f,b,f) then  -b when not 13 in (select max((19)) from t1 union select count(*) | count(*) from t1) and 11 not between t1.b and e or 13 in (t1.a, -e,(t1.c)) then a else 11 end)/abs(t1.c))*b | t1.b)/abs(f))*f*f FROM t1 WHERE NOT (~case f when coalesce((select max(17) from t1 where b+t1.f*case 11 when coalesce((select max(t1.f) from t1 where 17>t1.f),19)-t1.b-t1.b | d then b else c end+t1.d*11-t1.c<=case when b>=a then 19 else f end | t1.a),13) then f else t1.e end*t1.e*17-d in (select 13 from t1 union select t1.e from t1))}
} {-24192000000}
do_test randexpr-2.1815 {
  db eval {SELECT f*~13*(abs(13*d- -(abs(case when ~coalesce((select max(c) from t1 where b>case when not exists(select 1 from t1 where f not in ( - -(t1.b),t1.b,t1.f)) then e when t1.c<>f then c else 13 end),17) &  -19 not in (f,b,f) then  -b when not 13 in (select max((19)) from t1 union select count(*) & count(*) from t1) and 11 not between t1.b and e or 13 in (t1.a, -e,(t1.c)) then a else 11 end)/abs(t1.c))*b & t1.b)/abs(f))*f*f FROM t1 WHERE NOT (~case f when coalesce((select max(17) from t1 where b+t1.f*case 11 when coalesce((select max(t1.f) from t1 where 17>t1.f),19)-t1.b-t1.b | d then b else c end+t1.d*11-t1.c<=case when b>=a then 19 else f end | t1.a),13) then f else t1.e end*t1.e*17-d in (select 13 from t1 union select t1.e from t1))}
} {0}
do_test randexpr-2.1816 {
  db eval {SELECT t1.b | (select case max( -17)-min(17) when cast(avg(a) AS integer)*(+cast(avg(f) AS integer)-cast(avg(case when not exists(select 1 from t1 where not case when t1.c<>t1.b or  -d not between b and a then 11 when (11)=11 then b else t1.b end in (t1.d,t1.c,13)) then 13 when t1.e not between 17 and t1.b then t1.c else t1.d end*t1.b) AS integer))-cast(avg(19) AS integer)*~max(t1.c)-((max(13)))*(count(*))+(max(11)) then count(distinct 13) else cast(avg(17) AS integer) end from t1) FROM t1 WHERE (abs(t1.c)/abs(case t1.d when t1.f then 13 else t1.f+13 end)) not between c and 19}
} {217}
do_test randexpr-2.1817 {
  db eval {SELECT t1.b | (select case max( -17)-min(17) when cast(avg(a) AS integer)*(+cast(avg(f) AS integer)-cast(avg(case when not exists(select 1 from t1 where not case when t1.c<>t1.b or  -d not between b and a then 11 when (11)=11 then b else t1.b end in (t1.d,t1.c,13)) then 13 when t1.e not between 17 and t1.b then t1.c else t1.d end*t1.b) AS integer))-cast(avg(19) AS integer)*~max(t1.c)-((max(13)))*(count(*))+(max(11)) then count(distinct 13) else cast(avg(17) AS integer) end from t1) FROM t1 WHERE NOT ((abs(t1.c)/abs(case t1.d when t1.f then 13 else t1.f+13 end)) not between c and 19)}
} {}
do_test randexpr-2.1818 {
  db eval {SELECT t1.b & (select case max( -17)-min(17) when cast(avg(a) AS integer)*(+cast(avg(f) AS integer)-cast(avg(case when not exists(select 1 from t1 where not case when t1.c<>t1.b or  -d not between b and a then 11 when (11)=11 then b else t1.b end in (t1.d,t1.c,13)) then 13 when t1.e not between 17 and t1.b then t1.c else t1.d end*t1.b) AS integer))-cast(avg(19) AS integer)*~max(t1.c)-((max(13)))*(count(*))+(max(11)) then count(distinct 13) else cast(avg(17) AS integer) end from t1) FROM t1 WHERE (abs(t1.c)/abs(case t1.d when t1.f then 13 else t1.f+13 end)) not between c and 19}
} {0}
do_test randexpr-2.1819 {
  db eval {SELECT case +c-case (select case count(distinct 13) when min(19*e) then ~count(*) else ~min(case when not +13*(case when e*c>=e then e else f end)-a+c not in (b,t1.b,t1.e) then 19 else 17 end*a) end from t1) when 11 then 11 else c end+t1.c when t1.b then d else 19 end FROM t1 WHERE t1.a<>~coalesce((select max(e) from t1 where 13-17*13<>19*17-f or coalesce((select max(~case +t1.d-f*e | c+(17)+a | c*((b)) when a then t1.a else d end-d) from t1 where t1.c>= -t1.a),t1.b) | 19>t1.a),c)}
} {19}
do_test randexpr-2.1820 {
  db eval {SELECT case +c-case (select case count(distinct 13) when min(19*e) then ~count(*) else ~min(case when not +13*(case when e*c>=e then e else f end)-a+c not in (b,t1.b,t1.e) then 19 else 17 end*a) end from t1) when 11 then 11 else c end+t1.c when t1.b then d else 19 end FROM t1 WHERE NOT (t1.a<>~coalesce((select max(e) from t1 where 13-17*13<>19*17-f or coalesce((select max(~case +t1.d-f*e | c+(17)+a | c*((b)) when a then t1.a else d end-d) from t1 where t1.c>= -t1.a),t1.b) | 19>t1.a),c))}
} {}
do_test randexpr-2.1821 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where f between case when (19 not in (t1.b,(a),t1.a)) or t1.a=t1.b |  -(select +cast(avg(17-case when  -c<=17 then a when  -11 not in (11,19,a) then e else 11 end-t1.a*d) AS integer) from t1) then t1.b when (11)*f in (13,t1.a,a) or t1.a<t1.d then b*t1.f else a end and  -11), -b) FROM t1 WHERE (f-b<case case (a) when a then 19+coalesce((select t1.a from t1 where 11 between +coalesce((select max(case when t1.b not in (t1.f,f,t1.b) and a in (select 11 from t1 union select c from t1) then ~(t1.e) else 13 end) from t1 where t1.c>=e),f)*b-f and t1.f),t1.b) else d end+19 when t1.a then 11 else e end-t1.a)}
} {}
do_test randexpr-2.1822 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where f between case when (19 not in (t1.b,(a),t1.a)) or t1.a=t1.b |  -(select +cast(avg(17-case when  -c<=17 then a when  -11 not in (11,19,a) then e else 11 end-t1.a*d) AS integer) from t1) then t1.b when (11)*f in (13,t1.a,a) or t1.a<t1.d then b*t1.f else a end and  -11), -b) FROM t1 WHERE NOT ((f-b<case case (a) when a then 19+coalesce((select t1.a from t1 where 11 between +coalesce((select max(case when t1.b not in (t1.f,f,t1.b) and a in (select 11 from t1 union select c from t1) then ~(t1.e) else 13 end) from t1 where t1.c>=e),f)*b-f and t1.f),t1.b) else d end+19 when t1.a then 11 else e end-t1.a))}
} {-200}
do_test randexpr-2.1823 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where f between case when (19 not in (t1.b,(a),t1.a)) or t1.a=t1.b &  -(select +cast(avg(17-case when  -c<=17 then a when  -11 not in (11,19,a) then e else 11 end-t1.a*d) AS integer) from t1) then t1.b when (11)*f in (13,t1.a,a) or t1.a<t1.d then b*t1.f else a end and  -11), -b) FROM t1 WHERE NOT ((f-b<case case (a) when a then 19+coalesce((select t1.a from t1 where 11 between +coalesce((select max(case when t1.b not in (t1.f,f,t1.b) and a in (select 11 from t1 union select c from t1) then ~(t1.e) else 13 end) from t1 where t1.c>=e),f)*b-f and t1.f),t1.b) else d end+19 when t1.a then 11 else e end-t1.a))}
} {-200}
do_test randexpr-2.1824 {
  db eval {SELECT case when not  -t1.c in (coalesce((select d from t1 where t1.a not in (t1.c+f, -f,19) and t1.b in (select max(t1.d)+min(19)*min(t1.e) from t1 union select count(distinct d) from t1) and (t1.d) in (select  -count(*) from t1 union select  -count(*) from t1)),d* -t1.e),b,f) or  -c not in (a, -t1.a,t1.e) then case when b between 17 and t1.b and a not in (t1.a,e,t1.e) then t1.d else 19 end*t1.b else t1.d end+t1.d FROM t1 WHERE (abs((17))/abs(11 | e*e+d++t1.d)) in (19+t1.f,e,(abs(13)/abs( -t1.c)))}
} {4200}
do_test randexpr-2.1825 {
  db eval {SELECT case when not  -t1.c in (coalesce((select d from t1 where t1.a not in (t1.c+f, -f,19) and t1.b in (select max(t1.d)+min(19)*min(t1.e) from t1 union select count(distinct d) from t1) and (t1.d) in (select  -count(*) from t1 union select  -count(*) from t1)),d* -t1.e),b,f) or  -c not in (a, -t1.a,t1.e) then case when b between 17 and t1.b and a not in (t1.a,e,t1.e) then t1.d else 19 end*t1.b else t1.d end+t1.d FROM t1 WHERE NOT ((abs((17))/abs(11 | e*e+d++t1.d)) in (19+t1.f,e,(abs(13)/abs( -t1.c))))}
} {}
do_test randexpr-2.1826 {
  db eval {SELECT case when ( -(select ~ -~ -(max(c))-min(t1.e) | count(distinct (11)) | min(t1.a) from t1)-case when case d when a then case when t1.e=t1.a then t1.c else c end else c end<=t1.f then t1.b when t1.c not in (a,19,c) then b else 17 end>=19) or d in (19,f, -11) then 19 else (select case min(t1.a)-(cast(avg(t1.f) AS integer))-(min(11)) when count(*) then count(*) else count(distinct a) end from t1) end FROM t1 WHERE not exists(select 1 from t1 where (abs(11-13)/abs(f))>19*~19+t1.d-t1.f+coalesce((select max(f) from t1 where t1.a-t1.e+case when case when a not between t1.c and 19 and  -t1.e>t1.c then case when t1.f in (t1.d,e,t1.f) then d when c not in (11,t1.c,d) then t1.a else a end when t1.b=11 then t1.c else t1.e end>e then e else e end-11<t1.f),c)- -c-17) or 19<>t1.f}
} {1}
do_test randexpr-2.1827 {
  db eval {SELECT case when ( -(select ~ -~ -(max(c))-min(t1.e) | count(distinct (11)) | min(t1.a) from t1)-case when case d when a then case when t1.e=t1.a then t1.c else c end else c end<=t1.f then t1.b when t1.c not in (a,19,c) then b else 17 end>=19) or d in (19,f, -11) then 19 else (select case min(t1.a)-(cast(avg(t1.f) AS integer))-(min(11)) when count(*) then count(*) else count(distinct a) end from t1) end FROM t1 WHERE NOT (not exists(select 1 from t1 where (abs(11-13)/abs(f))>19*~19+t1.d-t1.f+coalesce((select max(f) from t1 where t1.a-t1.e+case when case when a not between t1.c and 19 and  -t1.e>t1.c then case when t1.f in (t1.d,e,t1.f) then d when c not in (11,t1.c,d) then t1.a else a end when t1.b=11 then t1.c else t1.e end>e then e else e end-11<t1.f),c)- -c-17) or 19<>t1.f)}
} {}
do_test randexpr-2.1828 {
  db eval {SELECT case when ( -(select ~ -~ -(max(c))-min(t1.e) & count(distinct (11)) & min(t1.a) from t1)-case when case d when a then case when t1.e=t1.a then t1.c else c end else c end<=t1.f then t1.b when t1.c not in (a,19,c) then b else 17 end>=19) or d in (19,f, -11) then 19 else (select case min(t1.a)-(cast(avg(t1.f) AS integer))-(min(11)) when count(*) then count(*) else count(distinct a) end from t1) end FROM t1 WHERE not exists(select 1 from t1 where (abs(11-13)/abs(f))>19*~19+t1.d-t1.f+coalesce((select max(f) from t1 where t1.a-t1.e+case when case when a not between t1.c and 19 and  -t1.e>t1.c then case when t1.f in (t1.d,e,t1.f) then d when c not in (11,t1.c,d) then t1.a else a end when t1.b=11 then t1.c else t1.e end>e then e else e end-11<t1.f),c)- -c-17) or 19<>t1.f}
} {1}
do_test randexpr-2.1829 {
  db eval {SELECT t1.e | t1.a*~(17)-t1.c*f*f-coalesce((select max( -t1.a+coalesce((select t1.a from t1 where 19 not between 17 and f),(t1.b))*c+11) from t1 where 19 in (select  -cast(avg(f) AS integer)-cast(avg(a) AS integer)*count(distinct d) from t1 union select count(*) from t1) and t1.d in (17,t1.d, -t1.c) or 19<>19),a)*11 FROM t1 WHERE not +19+coalesce((select  -19 from t1 where t1.c | e in (select ~ -abs(case ~abs(+(count(distinct 17) | case ~(max(t1.a))+(+~ -min(17)) when abs(min(t1.c)) then count(distinct 17) else  -cast(avg(t1.e) AS integer) end)*cast(avg(c) AS integer)*cast(avg(t1.b) AS integer)) when count(distinct t1.d) then min(b) else  -cast(avg(d) AS integer) end) from t1 union select count(*) from t1)),13)>13}
} {}
do_test randexpr-2.1830 {
  db eval {SELECT t1.e | t1.a*~(17)-t1.c*f*f-coalesce((select max( -t1.a+coalesce((select t1.a from t1 where 19 not between 17 and f),(t1.b))*c+11) from t1 where 19 in (select  -cast(avg(f) AS integer)-cast(avg(a) AS integer)*count(distinct d) from t1 union select count(*) from t1) and t1.d in (17,t1.d, -t1.c) or 19<>19),a)*11 FROM t1 WHERE NOT (not +19+coalesce((select  -19 from t1 where t1.c | e in (select ~ -abs(case ~abs(+(count(distinct 17) | case ~(max(t1.a))+(+~ -min(17)) when abs(min(t1.c)) then count(distinct 17) else  -cast(avg(t1.e) AS integer) end)*cast(avg(c) AS integer)*cast(avg(t1.b) AS integer)) when count(distinct t1.d) then min(b) else  -cast(avg(d) AS integer) end) from t1 union select count(*) from t1)),13)>13)}
} {-108002820}
do_test randexpr-2.1831 {
  db eval {SELECT t1.e & t1.a*~(17)-t1.c*f*f-coalesce((select max( -t1.a+coalesce((select t1.a from t1 where 19 not between 17 and f),(t1.b))*c+11) from t1 where 19 in (select  -cast(avg(f) AS integer)-cast(avg(a) AS integer)*count(distinct d) from t1 union select count(*) from t1) and t1.d in (17,t1.d, -t1.c) or 19<>19),a)*11 FROM t1 WHERE NOT (not +19+coalesce((select  -19 from t1 where t1.c | e in (select ~ -abs(case ~abs(+(count(distinct 17) | case ~(max(t1.a))+(+~ -min(17)) when abs(min(t1.c)) then count(distinct 17) else  -cast(avg(t1.e) AS integer) end)*cast(avg(c) AS integer)*cast(avg(t1.b) AS integer)) when count(distinct t1.d) then min(b) else  -cast(avg(d) AS integer) end) from t1 union select count(*) from t1)),13)>13)}
} {420}
do_test randexpr-2.1832 {
  db eval {SELECT case when t1.a<(abs((abs(13)/abs(case t1.e+11*17*case +case case when ~19>=t1.c then f when f not in (a,e,d) then 19 else b end when 19 then 19 else b end |  -c when c then t1.c else c end*d-t1.e when e then 13 else c end)))/abs(t1.b)) then 17 when t1.b not in (t1.a,13,e) then e else  -t1.c end FROM t1 WHERE 19>=11}
} {500}
do_test randexpr-2.1833 {
  db eval {SELECT case when t1.a<(abs((abs(13)/abs(case t1.e+11*17*case +case case when ~19>=t1.c then f when f not in (a,e,d) then 19 else b end when 19 then 19 else b end |  -c when c then t1.c else c end*d-t1.e when e then 13 else c end)))/abs(t1.b)) then 17 when t1.b not in (t1.a,13,e) then e else  -t1.c end FROM t1 WHERE NOT (19>=11)}
} {}
do_test randexpr-2.1834 {
  db eval {SELECT case when t1.a<(abs((abs(13)/abs(case t1.e+11*17*case +case case when ~19>=t1.c then f when f not in (a,e,d) then 19 else b end when 19 then 19 else b end &  -c when c then t1.c else c end*d-t1.e when e then 13 else c end)))/abs(t1.b)) then 17 when t1.b not in (t1.a,13,e) then e else  -t1.c end FROM t1 WHERE 19>=11}
} {500}
do_test randexpr-2.1835 {
  db eval {SELECT coalesce((select (select count(*)-+count(*) from t1) from t1 where +t1.f+t1.f<~case when exists(select 1 from t1 where coalesce((select t1.a from t1 where b-19<t1.f),11) in (case when  -(select count(distinct t1.a) from t1)-c-t1.d between b and (d) then d else t1.e end,f,c)) then t1.b when t1.e<>(11) then d else (c) end+e+t1.d),c) FROM t1 WHERE case when t1.f+(select min(t1.c+(abs(13+(abs(t1.e+d-11-e+d+c)/abs(t1.e))-c*t1.f)/abs(t1.b))) from t1)+f=d or t1.b not between t1.e and t1.a then 11-a when (13 in (13,19,19)) then t1.d else t1.b end<t1.f}
} {300}
do_test randexpr-2.1836 {
  db eval {SELECT coalesce((select (select count(*)-+count(*) from t1) from t1 where +t1.f+t1.f<~case when exists(select 1 from t1 where coalesce((select t1.a from t1 where b-19<t1.f),11) in (case when  -(select count(distinct t1.a) from t1)-c-t1.d between b and (d) then d else t1.e end,f,c)) then t1.b when t1.e<>(11) then d else (c) end+e+t1.d),c) FROM t1 WHERE NOT (case when t1.f+(select min(t1.c+(abs(13+(abs(t1.e+d-11-e+d+c)/abs(t1.e))-c*t1.f)/abs(t1.b))) from t1)+f=d or t1.b not between t1.e and t1.a then 11-a when (13 in (13,19,19)) then t1.d else t1.b end<t1.f)}
} {}
do_test randexpr-2.1837 {
  db eval {SELECT case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (abs(a)/abs(t1.f))<a then t1.a when t1.b not in (11,t1.f,(c+d*t1.d)+t1.b+d-t1.a+e) then e else e end<=d))) then (select ~max(13) from t1) when 13 not between coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where 13>=t1.b)),((d))) and t1.c then 19 else 13 end FROM t1 WHERE d*a in (case when 19>t1.e then c | (select +~count(distinct t1.b)-++abs(min(11)+ -~min(t1.b)+ -(max(t1.d))-min(t1.b)-count(distinct t1.f)) | max(f) from t1) else a+t1.c end,t1.a+case 19 when (11*a)*t1.c then d else a end*t1.a-d,f)}
} {}
do_test randexpr-2.1838 {
  db eval {SELECT case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (abs(a)/abs(t1.f))<a then t1.a when t1.b not in (11,t1.f,(c+d*t1.d)+t1.b+d-t1.a+e) then e else e end<=d))) then (select ~max(13) from t1) when 13 not between coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where 13>=t1.b)),((d))) and t1.c then 19 else 13 end FROM t1 WHERE NOT (d*a in (case when 19>t1.e then c | (select +~count(distinct t1.b)-++abs(min(11)+ -~min(t1.b)+ -(max(t1.d))-min(t1.b)-count(distinct t1.f)) | max(f) from t1) else a+t1.c end,t1.a+case 19 when (11*a)*t1.c then d else a end*t1.a-d,f))}
} {-14}
do_test randexpr-2.1839 {
  db eval {SELECT case when b<= -coalesce((select max(t1.b+t1.c+a*a-t1.c-e) from t1 where not 11>e or c<=17 and b<=b), -t1.d)+13 and 17 not between a and c and not exists(select 1 from t1 where f not between t1.d and t1.e and t1.d between 13 and  -t1.a) then t1.b when e not in (a,t1.f, -t1.d) then t1.c else e end FROM t1 WHERE not coalesce((select max((c)) from t1 where d* -coalesce((select max(coalesce((select t1.d from t1 where (d<=d)),d)) from t1 where (abs(case 11 when (select  -+count(distinct 13)*min(c) | count(*) from t1) then 11 else case when (19 between (19) and 17 or t1.c in (c,19,d)) then c when  -t1.e>=c then c else c end end*11)/abs((13))) not in (17, -t1.e, -t1.e)),t1.e)=17),t1.c) between 13 and t1.f}
} {}
do_test randexpr-2.1840 {
  db eval {SELECT case when b<= -coalesce((select max(t1.b+t1.c+a*a-t1.c-e) from t1 where not 11>e or c<=17 and b<=b), -t1.d)+13 and 17 not between a and c and not exists(select 1 from t1 where f not between t1.d and t1.e and t1.d between 13 and  -t1.a) then t1.b when e not in (a,t1.f, -t1.d) then t1.c else e end FROM t1 WHERE NOT (not coalesce((select max((c)) from t1 where d* -coalesce((select max(coalesce((select t1.d from t1 where (d<=d)),d)) from t1 where (abs(case 11 when (select  -+count(distinct 13)*min(c) | count(*) from t1) then 11 else case when (19 between (19) and 17 or t1.c in (c,19,d)) then c when  -t1.e>=c then c else c end end*11)/abs((13))) not in (17, -t1.e, -t1.e)),t1.e)=17),t1.c) between 13 and t1.f)}
} {300}
do_test randexpr-2.1841 {
  db eval {SELECT 17 |  -(case when (a) not between 11 and case (abs(~(abs(13-case (abs(17)/abs(19+e | t1.e)) when (t1.d) then  -(t1.c) else t1.f end+t1.f*t1.c)/abs(a)))/abs(17)) when 19 then d else t1.d end then 17 when not exists(select 1 from t1 where t1.e not in (t1.b,t1.b,b) or a between a and 17) then 11 else b end) | t1.e FROM t1 WHERE 17>=e}
} {}
do_test randexpr-2.1842 {
  db eval {SELECT 17 |  -(case when (a) not between 11 and case (abs(~(abs(13-case (abs(17)/abs(19+e | t1.e)) when (t1.d) then  -(t1.c) else t1.f end+t1.f*t1.c)/abs(a)))/abs(17)) when 19 then d else t1.d end then 17 when not exists(select 1 from t1 where t1.e not in (t1.b,t1.b,b) or a between a and 17) then 11 else b end) | t1.e FROM t1 WHERE NOT (17>=e)}
} {-3}
do_test randexpr-2.1843 {
  db eval {SELECT 17 &  -(case when (a) not between 11 and case (abs(~(abs(13-case (abs(17)/abs(19+e & t1.e)) when (t1.d) then  -(t1.c) else t1.f end+t1.f*t1.c)/abs(a)))/abs(17)) when 19 then d else t1.d end then 17 when not exists(select 1 from t1 where t1.e not in (t1.b,t1.b,b) or a between a and 17) then 11 else b end) & t1.e FROM t1 WHERE NOT (17>=e)}
} {16}
do_test randexpr-2.1844 {
  db eval {SELECT (abs(11 | t1.e)/abs(case 13 when 17*+t1.a+d*+d then ~ -17*+ - -case f when b then a-b else t1.d end-f+t1.f+17 else t1.a end)) FROM t1 WHERE t1.f<>17}
} {5}
do_test randexpr-2.1845 {
  db eval {SELECT (abs(11 | t1.e)/abs(case 13 when 17*+t1.a+d*+d then ~ -17*+ - -case f when b then a-b else t1.d end-f+t1.f+17 else t1.a end)) FROM t1 WHERE NOT (t1.f<>17)}
} {}
do_test randexpr-2.1846 {
  db eval {SELECT (abs(11 & t1.e)/abs(case 13 when 17*+t1.a+d*+d then ~ -17*+ - -case f when b then a-b else t1.d end-f+t1.f+17 else t1.a end)) FROM t1 WHERE t1.f<>17}
} {0}
do_test randexpr-2.1847 {
  db eval {SELECT case when not coalesce((select max(case 11 when case d when coalesce((select f from t1 where case when (t1.d) | case 11 when t1.d then 11 else (t1.a) end | t1.b in (e,c,(11)) then 17 when c between e and f then t1.e else t1.a end>t1.e),t1.d) then 13 else c end then c else c end) from t1 where t1.e not between (a) and (t1.d)),c) not in ((11),((19)),a) then (t1.c) else (c) end FROM t1 WHERE t1.d-t1.c>=13}
} {300}
do_test randexpr-2.1848 {
  db eval {SELECT case when not coalesce((select max(case 11 when case d when coalesce((select f from t1 where case when (t1.d) | case 11 when t1.d then 11 else (t1.a) end | t1.b in (e,c,(11)) then 17 when c between e and f then t1.e else t1.a end>t1.e),t1.d) then 13 else c end then c else c end) from t1 where t1.e not between (a) and (t1.d)),c) not in ((11),((19)),a) then (t1.c) else (c) end FROM t1 WHERE NOT (t1.d-t1.c>=13)}
} {}
do_test randexpr-2.1849 {
  db eval {SELECT case when not coalesce((select max(case 11 when case d when coalesce((select f from t1 where case when (t1.d) & case 11 when t1.d then 11 else (t1.a) end & t1.b in (e,c,(11)) then 17 when c between e and f then t1.e else t1.a end>t1.e),t1.d) then 13 else c end then c else c end) from t1 where t1.e not between (a) and (t1.d)),c) not in ((11),((19)),a) then (t1.c) else (c) end FROM t1 WHERE t1.d-t1.c>=13}
} {300}
do_test randexpr-2.1850 {
  db eval {SELECT (select case count(distinct ~case when (abs(coalesce((select t1.e from t1 where (not exists(select 1 from t1 where a | e between c and coalesce((select (t1.d) from t1 where (t1.a=t1.a)), -(c))))),b+19))/abs(d))>11 then b else t1.d end) when count(distinct 17) then ~min((t1.d))-case  -(case  -cast(avg(t1.b) AS integer) when  -max(13) then (min(t1.d)) else count(distinct t1.b) end+(min(t1.e)))*(cast(avg( -17) AS integer)) when  -count(distinct 19) then count(*) else max(t1.c) end else count(distinct f) end from t1) FROM t1 WHERE t1.e=t1.d}
} {}
do_test randexpr-2.1851 {
  db eval {SELECT (select case count(distinct ~case when (abs(coalesce((select t1.e from t1 where (not exists(select 1 from t1 where a | e between c and coalesce((select (t1.d) from t1 where (t1.a=t1.a)), -(c))))),b+19))/abs(d))>11 then b else t1.d end) when count(distinct 17) then ~min((t1.d))-case  -(case  -cast(avg(t1.b) AS integer) when  -max(13) then (min(t1.d)) else count(distinct t1.b) end+(min(t1.e)))*(cast(avg( -17) AS integer)) when  -count(distinct 19) then count(*) else max(t1.c) end else count(distinct f) end from t1) FROM t1 WHERE NOT (t1.e=t1.d)}
} {-701}
do_test randexpr-2.1852 {
  db eval {SELECT (select case count(distinct ~case when (abs(coalesce((select t1.e from t1 where (not exists(select 1 from t1 where a & e between c and coalesce((select (t1.d) from t1 where (t1.a=t1.a)), -(c))))),b+19))/abs(d))>11 then b else t1.d end) when count(distinct 17) then ~min((t1.d))-case  -(case  -cast(avg(t1.b) AS integer) when  -max(13) then (min(t1.d)) else count(distinct t1.b) end+(min(t1.e)))*(cast(avg( -17) AS integer)) when  -count(distinct 19) then count(*) else max(t1.c) end else count(distinct f) end from t1) FROM t1 WHERE NOT (t1.e=t1.d)}
} {-701}
do_test randexpr-2.1853 {
  db eval {SELECT case when t1.d<>t1.a and a-t1.b-c in (13,t1.e-(abs(d)/abs(coalesce((select max(e) from t1 where 19 not between  -b and 17),b))),t1.b) or (not exists(select 1 from t1 where t1.f not between  -17 and a)) then case when e>t1.e then t1.d when t1.c<d or (19<=13) then (13) else b end+t1.e when c<=a then t1.d else f end+17 FROM t1 WHERE (t1.d)-case when not exists(select 1 from t1 where c<>f-11 and not not b<coalesce((select max(a) from t1 where (select cast(avg(case t1.a*19 when (select abs(cast(avg(c) AS integer)+(count(*))) from t1) | t1.f+11* -b then ((e)) else t1.a end) AS integer) from t1)-t1.f in (a,a,e)),19)) then 13*e else t1.b end not between 13 and t1.c}
} {617}
do_test randexpr-2.1854 {
  db eval {SELECT case when t1.d<>t1.a and a-t1.b-c in (13,t1.e-(abs(d)/abs(coalesce((select max(e) from t1 where 19 not between  -b and 17),b))),t1.b) or (not exists(select 1 from t1 where t1.f not between  -17 and a)) then case when e>t1.e then t1.d when t1.c<d or (19<=13) then (13) else b end+t1.e when c<=a then t1.d else f end+17 FROM t1 WHERE NOT ((t1.d)-case when not exists(select 1 from t1 where c<>f-11 and not not b<coalesce((select max(a) from t1 where (select cast(avg(case t1.a*19 when (select abs(cast(avg(c) AS integer)+(count(*))) from t1) | t1.f+11* -b then ((e)) else t1.a end) AS integer) from t1)-t1.f in (a,a,e)),19)) then 13*e else t1.b end not between 13 and t1.c)}
} {}
do_test randexpr-2.1855 {
  db eval {SELECT ~case 17 when t1.c then coalesce((select max((case when not exists(select 1 from t1 where 11<>coalesce((select d from t1 where not exists(select 1 from t1 where c*b in (t1.b*t1.d,t1.c,b) or c between d and a)),19)-t1.c*e) then coalesce((select f from t1 where 11 in (select c from t1 union select b from t1)),(c)) when 17<>t1.b then d else 19 end)) from t1 where f in (a,t1.f,t1.d)),(19)) else t1.e end FROM t1 WHERE not not exists(select 1 from t1 where (select abs(min(19-19))*count(*) | min(13)*min((a))+cast(avg(t1.e) AS integer)+(cast(avg(19) AS integer)) from t1) in (17,+(select min(b) from t1),(select cast(avg(f) AS integer) from t1)) and 11 in (select ( -(min(c))) from t1 union select (min(13)) from t1)) or t1.d between c and  -(f) or not t1.c in (select min(e) from t1 union select  -(max(e)) from t1) and t1.e in (t1.f,a,11) and f not between a and 17 and 19<=17 and 13 not in (b,t1.b,13)}
} {}
do_test randexpr-2.1856 {
  db eval {SELECT ~case 17 when t1.c then coalesce((select max((case when not exists(select 1 from t1 where 11<>coalesce((select d from t1 where not exists(select 1 from t1 where c*b in (t1.b*t1.d,t1.c,b) or c between d and a)),19)-t1.c*e) then coalesce((select f from t1 where 11 in (select c from t1 union select b from t1)),(c)) when 17<>t1.b then d else 19 end)) from t1 where f in (a,t1.f,t1.d)),(19)) else t1.e end FROM t1 WHERE NOT (not not exists(select 1 from t1 where (select abs(min(19-19))*count(*) | min(13)*min((a))+cast(avg(t1.e) AS integer)+(cast(avg(19) AS integer)) from t1) in (17,+(select min(b) from t1),(select cast(avg(f) AS integer) from t1)) and 11 in (select ( -(min(c))) from t1 union select (min(13)) from t1)) or t1.d between c and  -(f) or not t1.c in (select min(e) from t1 union select  -(max(e)) from t1) and t1.e in (t1.f,a,11) and f not between a and 17 and 19<=17 and 13 not in (b,t1.b,13))}
} {-501}
do_test randexpr-2.1857 {
  db eval {SELECT coalesce((select +f+coalesce((select case when b- -f*t1.d-t1.a>d and t1.e in (select b from t1 union select t1.d from t1) then 11 else  -a end from t1 where (not (t1.f) not between 13 and t1.f)),11) from t1 where t1.c<=c and (d) between 11 and t1.b or b in (select d from t1 union select t1.e from t1) and 19<>t1.e or 19 not between a and a),19) FROM t1 WHERE t1.e<>(select cast(avg((b)*(select abs( -max(t1.f)) from t1)) AS integer) from t1)}
} {500}
do_test randexpr-2.1858 {
  db eval {SELECT coalesce((select +f+coalesce((select case when b- -f*t1.d-t1.a>d and t1.e in (select b from t1 union select t1.d from t1) then 11 else  -a end from t1 where (not (t1.f) not between 13 and t1.f)),11) from t1 where t1.c<=c and (d) between 11 and t1.b or b in (select d from t1 union select t1.e from t1) and 19<>t1.e or 19 not between a and a),19) FROM t1 WHERE NOT (t1.e<>(select cast(avg((b)*(select abs( -max(t1.f)) from t1)) AS integer) from t1))}
} {}
do_test randexpr-2.1859 {
  db eval {SELECT coalesce((select max(coalesce((select (t1.f) from t1 where f in (select t1.f+(select case count(distinct 19) when count(*) then max(t1.d) else  -count(*) end from t1) from t1 union select 13 from t1)),c)) from t1 where not exists(select 1 from t1 where coalesce((select (select +count(*) | ~(~ -count(distinct  -13)) from t1) from t1 where case when d*~f-13<>((d)) then 19 else t1.a end not between d and t1.e),t1.f) | t1.d in (select t1.d from t1 union select t1.d from t1))),13) FROM t1 WHERE b= -~case f-t1.a | ~case coalesce((select max(t1.b) from t1 where b>t1.e or t1.d=17-(abs(coalesce((select 17 from t1 where 17 between c and c),a)-c+a)/abs(t1.f))-c and d not in (17,19,c)),c) when 11 then e else t1.d end | t1.c-d when t1.c then c else e end | a}
} {}
do_test randexpr-2.1860 {
  db eval {SELECT coalesce((select max(coalesce((select (t1.f) from t1 where f in (select t1.f+(select case count(distinct 19) when count(*) then max(t1.d) else  -count(*) end from t1) from t1 union select 13 from t1)),c)) from t1 where not exists(select 1 from t1 where coalesce((select (select +count(*) | ~(~ -count(distinct  -13)) from t1) from t1 where case when d*~f-13<>((d)) then 19 else t1.a end not between d and t1.e),t1.f) | t1.d in (select t1.d from t1 union select t1.d from t1))),13) FROM t1 WHERE NOT (b= -~case f-t1.a | ~case coalesce((select max(t1.b) from t1 where b>t1.e or t1.d=17-(abs(coalesce((select 17 from t1 where 17 between c and c),a)-c+a)/abs(t1.f))-c and d not in (17,19,c)),c) when 11 then e else t1.d end | t1.c-d when t1.c then c else e end | a)}
} {300}
do_test randexpr-2.1861 {
  db eval {SELECT coalesce((select max(coalesce((select (t1.f) from t1 where f in (select t1.f+(select case count(distinct 19) when count(*) then max(t1.d) else  -count(*) end from t1) from t1 union select 13 from t1)),c)) from t1 where not exists(select 1 from t1 where coalesce((select (select +count(*) & ~(~ -count(distinct  -13)) from t1) from t1 where case when d*~f-13<>((d)) then 19 else t1.a end not between d and t1.e),t1.f) & t1.d in (select t1.d from t1 union select t1.d from t1))),13) FROM t1 WHERE NOT (b= -~case f-t1.a | ~case coalesce((select max(t1.b) from t1 where b>t1.e or t1.d=17-(abs(coalesce((select 17 from t1 where 17 between c and c),a)-c+a)/abs(t1.f))-c and d not in (17,19,c)),c) when 11 then e else t1.d end | t1.c-d when t1.c then c else e end | a)}
} {300}
do_test randexpr-2.1862 {
  db eval {SELECT coalesce((select max(( -17-case when t1.c-13<+11 | (t1.a)-e then 13*t1.a when coalesce((select 11 from t1 where t1.a>t1.c),17)+f+t1.a not between 13 and e then t1.f else c end)) from t1 where exists(select 1 from t1 where (19>=t1.f)) and f in (select max(13) from t1 union select count(*) from t1) and (19)>=t1.f),d) FROM t1 WHERE t1.f in (select 19 from t1 union select  -17*11+t1.d from t1)}
} {}
do_test randexpr-2.1863 {
  db eval {SELECT coalesce((select max(( -17-case when t1.c-13<+11 | (t1.a)-e then 13*t1.a when coalesce((select 11 from t1 where t1.a>t1.c),17)+f+t1.a not between 13 and e then t1.f else c end)) from t1 where exists(select 1 from t1 where (19>=t1.f)) and f in (select max(13) from t1 union select count(*) from t1) and (19)>=t1.f),d) FROM t1 WHERE NOT (t1.f in (select 19 from t1 union select  -17*11+t1.d from t1))}
} {400}
do_test randexpr-2.1864 {
  db eval {SELECT coalesce((select max(( -17-case when t1.c-13<+11 & (t1.a)-e then 13*t1.a when coalesce((select 11 from t1 where t1.a>t1.c),17)+f+t1.a not between 13 and e then t1.f else c end)) from t1 where exists(select 1 from t1 where (19>=t1.f)) and f in (select max(13) from t1 union select count(*) from t1) and (19)>=t1.f),d) FROM t1 WHERE NOT (t1.f in (select 19 from t1 union select  -17*11+t1.d from t1))}
} {400}
do_test randexpr-2.1865 {
  db eval {SELECT (t1.a)+c*case when not b in (select 11 from t1 union select 13 from t1) and a=case when not exists(select 1 from t1 where exists(select 1 from t1 where ~+( -(17)) | t1.d>=b)) then case t1.d when c then 19 else t1.c end*a else d end-a then e when b not between f and d and t1.b>=11 or not (t1.e>=b) and 11<=17 then 13 else t1.d end FROM t1 WHERE b in (e | 19,t1.c,case 17 when 19 then +(case when 19> -coalesce((select max(a) from t1 where t1.a not in (case e when t1.d then (c)-c else 11 end | (11)-c*t1.f,e,t1.f)),13) then t1.e else t1.e end)*e else 13 end-19+ - -t1.d* -b) or  -t1.e>b}
} {}
do_test randexpr-2.1866 {
  db eval {SELECT (t1.a)+c*case when not b in (select 11 from t1 union select 13 from t1) and a=case when not exists(select 1 from t1 where exists(select 1 from t1 where ~+( -(17)) | t1.d>=b)) then case t1.d when c then 19 else t1.c end*a else d end-a then e when b not between f and d and t1.b>=11 or not (t1.e>=b) and 11<=17 then 13 else t1.d end FROM t1 WHERE NOT (b in (e | 19,t1.c,case 17 when 19 then +(case when 19> -coalesce((select max(a) from t1 where t1.a not in (case e when t1.d then (c)-c else 11 end | (11)-c*t1.f,e,t1.f)),13) then t1.e else t1.e end)*e else 13 end-19+ - -t1.d* -b) or  -t1.e>b)}
} {4000}
do_test randexpr-2.1867 {
  db eval {SELECT (t1.a)+c*case when not b in (select 11 from t1 union select 13 from t1) and a=case when not exists(select 1 from t1 where exists(select 1 from t1 where ~+( -(17)) & t1.d>=b)) then case t1.d when c then 19 else t1.c end*a else d end-a then e when b not between f and d and t1.b>=11 or not (t1.e>=b) and 11<=17 then 13 else t1.d end FROM t1 WHERE NOT (b in (e | 19,t1.c,case 17 when 19 then +(case when 19> -coalesce((select max(a) from t1 where t1.a not in (case e when t1.d then (c)-c else 11 end | (11)-c*t1.f,e,t1.f)),13) then t1.e else t1.e end)*e else 13 end-19+ - -t1.d* -b) or  -t1.e>b)}
} {4000}
do_test randexpr-2.1868 {
  db eval {SELECT case when b | case when 13 between ~coalesce((select 19 from t1 where b in (select max(a*17) from t1 union select cast(avg( -19) AS integer)+abs(cast(avg(a) AS integer)) from t1)),17) and 11 then a when not exists(select 1 from t1 where not exists(select 1 from t1 where 19<=e)) and d in (select 17 from t1 union select 17 from t1) then  -b else a end-a in (select max(t1.c) from t1 union select min(e) | count(*)+count(*) from t1) then t1.b when not (not 19<=t1.b) then 13 else a end-b FROM t1 WHERE +~+13>=t1.c}
} {}
do_test randexpr-2.1869 {
  db eval {SELECT case when b | case when 13 between ~coalesce((select 19 from t1 where b in (select max(a*17) from t1 union select cast(avg( -19) AS integer)+abs(cast(avg(a) AS integer)) from t1)),17) and 11 then a when not exists(select 1 from t1 where not exists(select 1 from t1 where 19<=e)) and d in (select 17 from t1 union select 17 from t1) then  -b else a end-a in (select max(t1.c) from t1 union select min(e) | count(*)+count(*) from t1) then t1.b when not (not 19<=t1.b) then 13 else a end-b FROM t1 WHERE NOT (+~+13>=t1.c)}
} {-187}
do_test randexpr-2.1870 {
  db eval {SELECT case when b & case when 13 between ~coalesce((select 19 from t1 where b in (select max(a*17) from t1 union select cast(avg( -19) AS integer)+abs(cast(avg(a) AS integer)) from t1)),17) and 11 then a when not exists(select 1 from t1 where not exists(select 1 from t1 where 19<=e)) and d in (select 17 from t1 union select 17 from t1) then  -b else a end-a in (select max(t1.c) from t1 union select min(e) & count(*)+count(*) from t1) then t1.b when not (not 19<=t1.b) then 13 else a end-b FROM t1 WHERE NOT (+~+13>=t1.c)}
} {0}
do_test randexpr-2.1871 {
  db eval {SELECT coalesce((select case when t1.d in (select min(f) from t1 union select ~ -count(*) from t1) then d else 13 end from t1 where 19<=case when 13>=+17-c+(select count(*)-min(11) from t1)+t1.f*t1.e*c*t1.d then c else t1.b end),t1.c | +t1.e) FROM t1 WHERE a between (abs(coalesce((select max(case when (t1.d+a*coalesce((select d-13 from t1 where a<=19),t1.f))>= -c then c else 13 end) from t1 where f>=d or t1.a>t1.d),t1.a))/abs(t1.f)) and 19 and 13=t1.e and not exists(select 1 from t1 where 13 in (select  -( -count(distinct (a))) |  -cast(avg(t1.c) AS integer) from t1 union select (min(t1.c)) from t1) or t1.f not between t1.c and t1.c)}
} {}
do_test randexpr-2.1872 {
  db eval {SELECT coalesce((select case when t1.d in (select min(f) from t1 union select ~ -count(*) from t1) then d else 13 end from t1 where 19<=case when 13>=+17-c+(select count(*)-min(11) from t1)+t1.f*t1.e*c*t1.d then c else t1.b end),t1.c | +t1.e) FROM t1 WHERE NOT (a between (abs(coalesce((select max(case when (t1.d+a*coalesce((select d-13 from t1 where a<=19),t1.f))>= -c then c else 13 end) from t1 where f>=d or t1.a>t1.d),t1.a))/abs(t1.f)) and 19 and 13=t1.e and not exists(select 1 from t1 where 13 in (select  -( -count(distinct (a))) |  -cast(avg(t1.c) AS integer) from t1 union select (min(t1.c)) from t1) or t1.f not between t1.c and t1.c))}
} {13}
do_test randexpr-2.1873 {
  db eval {SELECT coalesce((select case when t1.d in (select min(f) from t1 union select ~ -count(*) from t1) then d else 13 end from t1 where 19<=case when 13>=+17-c+(select count(*)-min(11) from t1)+t1.f*t1.e*c*t1.d then c else t1.b end),t1.c & +t1.e) FROM t1 WHERE NOT (a between (abs(coalesce((select max(case when (t1.d+a*coalesce((select d-13 from t1 where a<=19),t1.f))>= -c then c else 13 end) from t1 where f>=d or t1.a>t1.d),t1.a))/abs(t1.f)) and 19 and 13=t1.e and not exists(select 1 from t1 where 13 in (select  -( -count(distinct (a))) |  -cast(avg(t1.c) AS integer) from t1 union select (min(t1.c)) from t1) or t1.f not between t1.c and t1.c))}
} {13}
do_test randexpr-2.1874 {
  db eval {SELECT coalesce((select max(f) from t1 where coalesce((select max(+(select cast(avg(t1.d) AS integer) from t1)*19) from t1 where (abs(t1.d*t1.c)/abs(f))+t1.e> -t1.d*t1.e-a),13-case +coalesce((select max(t1.c) from t1 where d<=d and  - -t1.a<=(t1.f) or f<>19 and 17<19),(t1.c)) | c*t1.f*b when t1.a then 19 else (b) end)>=a),t1.f) FROM t1 WHERE (~c-13*case when case when a+19-c in (select case count(distinct c)-case cast(avg(t1.a) AS integer) when max( -b) then cast(avg(t1.f) AS integer) else cast(avg((t1.d)) AS integer) end when min(b) then cast(avg(b) AS integer) else count(*) end from t1 union select max(t1.f) from t1) and 17 between (t1.b) and c and 19>t1.d or 19 in (t1.f,t1.a,(b)) then a else t1.e end in (13,t1.a,b) then 17 else t1.e end*t1.d+a+t1.b+t1.f)<t1.d}
} {600}
do_test randexpr-2.1875 {
  db eval {SELECT coalesce((select max(f) from t1 where coalesce((select max(+(select cast(avg(t1.d) AS integer) from t1)*19) from t1 where (abs(t1.d*t1.c)/abs(f))+t1.e> -t1.d*t1.e-a),13-case +coalesce((select max(t1.c) from t1 where d<=d and  - -t1.a<=(t1.f) or f<>19 and 17<19),(t1.c)) | c*t1.f*b when t1.a then 19 else (b) end)>=a),t1.f) FROM t1 WHERE NOT ((~c-13*case when case when a+19-c in (select case count(distinct c)-case cast(avg(t1.a) AS integer) when max( -b) then cast(avg(t1.f) AS integer) else cast(avg((t1.d)) AS integer) end when min(b) then cast(avg(b) AS integer) else count(*) end from t1 union select max(t1.f) from t1) and 17 between (t1.b) and c and 19>t1.d or 19 in (t1.f,t1.a,(b)) then a else t1.e end in (13,t1.a,b) then 17 else t1.e end*t1.d+a+t1.b+t1.f)<t1.d)}
} {}
do_test randexpr-2.1876 {
  db eval {SELECT coalesce((select max(f) from t1 where coalesce((select max(+(select cast(avg(t1.d) AS integer) from t1)*19) from t1 where (abs(t1.d*t1.c)/abs(f))+t1.e> -t1.d*t1.e-a),13-case +coalesce((select max(t1.c) from t1 where d<=d and  - -t1.a<=(t1.f) or f<>19 and 17<19),(t1.c)) & c*t1.f*b when t1.a then 19 else (b) end)>=a),t1.f) FROM t1 WHERE (~c-13*case when case when a+19-c in (select case count(distinct c)-case cast(avg(t1.a) AS integer) when max( -b) then cast(avg(t1.f) AS integer) else cast(avg((t1.d)) AS integer) end when min(b) then cast(avg(b) AS integer) else count(*) end from t1 union select max(t1.f) from t1) and 17 between (t1.b) and c and 19>t1.d or 19 in (t1.f,t1.a,(b)) then a else t1.e end in (13,t1.a,b) then 17 else t1.e end*t1.d+a+t1.b+t1.f)<t1.d}
} {600}
do_test randexpr-2.1877 {
  db eval {SELECT a | t1.c-case t1.b when case when f< -(c*case when f<13 then t1.e | 13-coalesce((select max( -13+13+t1.a) from t1 where not exists(select 1 from t1 where 17=11)),19) else a end+t1.e*t1.d)+11+(13) then t1.f when not t1.f> -b then a else f end then t1.e else f end FROM t1 WHERE t1.f-~coalesce((select 17 from t1 where (e+ -case when (d<coalesce((select max(a) from t1 where a | a<t1.a and t1.c<=17 or t1.d not between a and b),13)) then 17*t1.d else t1.f end in (select ~~~cast(avg(f) AS integer)*max(t1.c)-count(distinct t1.e)-( -min(t1.f))+( -count(*)) from t1 union select max(a) from t1))),13)*t1.c-t1.d not between 17 and d}
} {-268}
do_test randexpr-2.1878 {
  db eval {SELECT a | t1.c-case t1.b when case when f< -(c*case when f<13 then t1.e | 13-coalesce((select max( -13+13+t1.a) from t1 where not exists(select 1 from t1 where 17=11)),19) else a end+t1.e*t1.d)+11+(13) then t1.f when not t1.f> -b then a else f end then t1.e else f end FROM t1 WHERE NOT (t1.f-~coalesce((select 17 from t1 where (e+ -case when (d<coalesce((select max(a) from t1 where a | a<t1.a and t1.c<=17 or t1.d not between a and b),13)) then 17*t1.d else t1.f end in (select ~~~cast(avg(f) AS integer)*max(t1.c)-count(distinct t1.e)-( -min(t1.f))+( -count(*)) from t1 union select max(a) from t1))),13)*t1.c-t1.d not between 17 and d)}
} {}
do_test randexpr-2.1879 {
  db eval {SELECT a & t1.c-case t1.b when case when f< -(c*case when f<13 then t1.e & 13-coalesce((select max( -13+13+t1.a) from t1 where not exists(select 1 from t1 where 17=11)),19) else a end+t1.e*t1.d)+11+(13) then t1.f when not t1.f> -b then a else f end then t1.e else f end FROM t1 WHERE t1.f-~coalesce((select 17 from t1 where (e+ -case when (d<coalesce((select max(a) from t1 where a | a<t1.a and t1.c<=17 or t1.d not between a and b),13)) then 17*t1.d else t1.f end in (select ~~~cast(avg(f) AS integer)*max(t1.c)-count(distinct t1.e)-( -min(t1.f))+( -count(*)) from t1 union select max(a) from t1))),13)*t1.c-t1.d not between 17 and d}
} {68}
do_test randexpr-2.1880 {
  db eval {SELECT  -(17-case (select max(a)+min( -(abs(t1.c-t1.a | t1.e- -t1.b+19*t1.c)/abs(c)))+ -case min(a) when count(distinct  -a) then count(distinct 19) else count(*) end-count(distinct t1.e)*(max(t1.a))-(count(distinct 19)) from t1) when (select count(*) from t1) then b else t1.d end*11)-11* -c FROM t1 WHERE f between (case case when +(f) in (select t1.f from t1 union select case when t1.b in ((abs(19)/abs(11)),f,c) and (d) in (select  -count(distinct b)*count(*) from t1 union select count(distinct  -13) from t1) or (t1.e>19) then case when f in (11,11,d) then t1.e when t1.a<=19 then a else e end else  -t1.e end from t1) then e when t1.c=t1.b then 19 else e end when f then 19 else c end) | d-c and a}
} {}
do_test randexpr-2.1881 {
  db eval {SELECT  -(17-case (select max(a)+min( -(abs(t1.c-t1.a | t1.e- -t1.b+19*t1.c)/abs(c)))+ -case min(a) when count(distinct  -a) then count(distinct 19) else count(*) end-count(distinct t1.e)*(max(t1.a))-(count(distinct 19)) from t1) when (select count(*) from t1) then b else t1.d end*11)-11* -c FROM t1 WHERE NOT (f between (case case when +(f) in (select t1.f from t1 union select case when t1.b in ((abs(19)/abs(11)),f,c) and (d) in (select  -count(distinct b)*count(*) from t1 union select count(distinct  -13) from t1) or (t1.e>19) then case when f in (11,11,d) then t1.e when t1.a<=19 then a else e end else  -t1.e end from t1) then e when t1.c=t1.b then 19 else e end when f then 19 else c end) | d-c and a)}
} {7683}
do_test randexpr-2.1882 {
  db eval {SELECT  -(17-case (select max(a)+min( -(abs(t1.c-t1.a & t1.e- -t1.b+19*t1.c)/abs(c)))+ -case min(a) when count(distinct  -a) then count(distinct 19) else count(*) end-count(distinct t1.e)*(max(t1.a))-(count(distinct 19)) from t1) when (select count(*) from t1) then b else t1.d end*11)-11* -c FROM t1 WHERE NOT (f between (case case when +(f) in (select t1.f from t1 union select case when t1.b in ((abs(19)/abs(11)),f,c) and (d) in (select  -count(distinct b)*count(*) from t1 union select count(distinct  -13) from t1) or (t1.e>19) then case when f in (11,11,d) then t1.e when t1.a<=19 then a else e end else  -t1.e end from t1) then e when t1.c=t1.b then 19 else e end when f then 19 else c end) | d-c and a)}
} {7683}
do_test randexpr-2.1883 {
  db eval {SELECT (case coalesce((select +a from t1 where exists(select 1 from t1 where t1.e not between t1.f-b and (select count(*) from t1)-t1.f | e)),t1.d+case when t1.b not between t1.d and 17+case when a in (t1.d,a,(abs(~case when (t1.f)<=t1.c then  -17 else t1.f end)/abs(19))*d*t1.d) then (b) else a end then 11 else f end+(t1.a)) when f then 17 else t1.e end) FROM t1 WHERE a-e*case t1.d+case c when (abs(~t1.d*(select min(case when not exists(select 1 from t1 where ((d)+(19) between 11 and 19)) then 11+13 when e not in (t1.f,17,e) and t1.c<>a then t1.e else 19 end*t1.a-f) from t1))/abs(b)) then 13 else 17 end when t1.f then (f) else t1.c end<b and 19 between t1.a and t1.a or d<f}
} {500}
do_test randexpr-2.1884 {
  db eval {SELECT (case coalesce((select +a from t1 where exists(select 1 from t1 where t1.e not between t1.f-b and (select count(*) from t1)-t1.f | e)),t1.d+case when t1.b not between t1.d and 17+case when a in (t1.d,a,(abs(~case when (t1.f)<=t1.c then  -17 else t1.f end)/abs(19))*d*t1.d) then (b) else a end then 11 else f end+(t1.a)) when f then 17 else t1.e end) FROM t1 WHERE NOT (a-e*case t1.d+case c when (abs(~t1.d*(select min(case when not exists(select 1 from t1 where ((d)+(19) between 11 and 19)) then 11+13 when e not in (t1.f,17,e) and t1.c<>a then t1.e else 19 end*t1.a-f) from t1))/abs(b)) then 13 else 17 end when t1.f then (f) else t1.c end<b and 19 between t1.a and t1.a or d<f)}
} {}
do_test randexpr-2.1885 {
  db eval {SELECT (case coalesce((select +a from t1 where exists(select 1 from t1 where t1.e not between t1.f-b and (select count(*) from t1)-t1.f & e)),t1.d+case when t1.b not between t1.d and 17+case when a in (t1.d,a,(abs(~case when (t1.f)<=t1.c then  -17 else t1.f end)/abs(19))*d*t1.d) then (b) else a end then 11 else f end+(t1.a)) when f then 17 else t1.e end) FROM t1 WHERE a-e*case t1.d+case c when (abs(~t1.d*(select min(case when not exists(select 1 from t1 where ((d)+(19) between 11 and 19)) then 11+13 when e not in (t1.f,17,e) and t1.c<>a then t1.e else 19 end*t1.a-f) from t1))/abs(b)) then 13 else 17 end when t1.f then (f) else t1.c end<b and 19 between t1.a and t1.a or d<f}
} {500}
do_test randexpr-2.1886 {
  db eval {SELECT  -19 | t1.c*coalesce((select max(+(select cast(avg(case when  -e+t1.d in (select t1.e*a from t1 union select a from t1) then t1.b when 17 in (select t1.a from t1 union select 11 from t1) then 19 else 11 end-19+a+t1.f) AS integer)+count(distinct t1.a) from t1)+(t1.b)) from t1 where (19) not in (17,d,a)),t1.a)*t1.b*19* -11 FROM t1 WHERE case t1.e when f then (select ~count(distinct a) | abs((count(distinct d*f+d+t1.b+17+~t1.f))) from t1) else coalesce((select e from t1 where t1.f not between 17+t1.f+19 and (abs(f)/abs(t1.f))*~t1.b*(b)),coalesce((select t1.b from t1 where 19 in (select count(distinct (t1.d)) from t1 union select  -count(distinct a) from t1)),19)) | 17 end not between t1.c and t1.c}
} {-19}
do_test randexpr-2.1887 {
  db eval {SELECT  -19 | t1.c*coalesce((select max(+(select cast(avg(case when  -e+t1.d in (select t1.e*a from t1 union select a from t1) then t1.b when 17 in (select t1.a from t1 union select 11 from t1) then 19 else 11 end-19+a+t1.f) AS integer)+count(distinct t1.a) from t1)+(t1.b)) from t1 where (19) not in (17,d,a)),t1.a)*t1.b*19* -11 FROM t1 WHERE NOT (case t1.e when f then (select ~count(distinct a) | abs((count(distinct d*f+d+t1.b+17+~t1.f))) from t1) else coalesce((select e from t1 where t1.f not between 17+t1.f+19 and (abs(f)/abs(t1.f))*~t1.b*(b)),coalesce((select t1.b from t1 where 19 in (select count(distinct (t1.d)) from t1 union select  -count(distinct a) from t1)),19)) | 17 end not between t1.c and t1.c)}
} {}
do_test randexpr-2.1888 {
  db eval {SELECT  -19 & t1.c*coalesce((select max(+(select cast(avg(case when  -e+t1.d in (select t1.e*a from t1 union select a from t1) then t1.b when 17 in (select t1.a from t1 union select 11 from t1) then 19 else 11 end-19+a+t1.f) AS integer)+count(distinct t1.a) from t1)+(t1.b)) from t1 where (19) not in (17,d,a)),t1.a)*t1.b*19* -11 FROM t1 WHERE case t1.e when f then (select ~count(distinct a) | abs((count(distinct d*f+d+t1.b+17+~t1.f))) from t1) else coalesce((select e from t1 where t1.f not between 17+t1.f+19 and (abs(f)/abs(t1.f))*~t1.b*(b)),coalesce((select t1.b from t1 where 19 in (select count(distinct (t1.d)) from t1 union select  -count(distinct a) from t1)),19)) | 17 end not between t1.c and t1.c}
} {-11198220000}
do_test randexpr-2.1889 {
  db eval {SELECT (abs(b)/abs((select max(c) from t1)))+case when (select +cast(avg(17 | ~coalesce((select e from t1 where t1.b>(13) |  -11 and c>f),19)+t1.c) AS integer)-(~case cast(avg(t1.f) AS integer)*abs(max(b)+(count(*))+count(distinct b)) when min(c) then cast(avg(t1.b) AS integer) else count(*) end) from t1) in (select t1.e from t1 union select t1.c from t1) then f when d<t1.e then t1.e else 19 end FROM t1 WHERE not ( -a*(select case min(coalesce((select max(a) from t1 where case when 11 between t1.c and d then c when t1.c not in (t1.a,e,t1.c) then d else 13 end*d>=(c)),b)) when max(d) then ( -max(c))+((min(11)))+max(t1.c) else max(t1.a) end from t1)-e+t1.b-(b)-11-t1.d*t1.c<>t1.c)}
} {}
do_test randexpr-2.1890 {
  db eval {SELECT (abs(b)/abs((select max(c) from t1)))+case when (select +cast(avg(17 | ~coalesce((select e from t1 where t1.b>(13) |  -11 and c>f),19)+t1.c) AS integer)-(~case cast(avg(t1.f) AS integer)*abs(max(b)+(count(*))+count(distinct b)) when min(c) then cast(avg(t1.b) AS integer) else count(*) end) from t1) in (select t1.e from t1 union select t1.c from t1) then f when d<t1.e then t1.e else 19 end FROM t1 WHERE NOT (not ( -a*(select case min(coalesce((select max(a) from t1 where case when 11 between t1.c and d then c when t1.c not in (t1.a,e,t1.c) then d else 13 end*d>=(c)),b)) when max(d) then ( -max(c))+((min(11)))+max(t1.c) else max(t1.a) end from t1)-e+t1.b-(b)-11-t1.d*t1.c<>t1.c))}
} {500}
do_test randexpr-2.1891 {
  db eval {SELECT (abs(b)/abs((select max(c) from t1)))+case when (select +cast(avg(17 & ~coalesce((select e from t1 where t1.b>(13) &  -11 and c>f),19)+t1.c) AS integer)-(~case cast(avg(t1.f) AS integer)*abs(max(b)+(count(*))+count(distinct b)) when min(c) then cast(avg(t1.b) AS integer) else count(*) end) from t1) in (select t1.e from t1 union select t1.c from t1) then f when d<t1.e then t1.e else 19 end FROM t1 WHERE NOT (not ( -a*(select case min(coalesce((select max(a) from t1 where case when 11 between t1.c and d then c when t1.c not in (t1.a,e,t1.c) then d else 13 end*d>=(c)),b)) when max(d) then ( -max(c))+((min(11)))+max(t1.c) else max(t1.a) end from t1)-e+t1.b-(b)-11-t1.d*t1.c<>t1.c))}
} {500}
do_test randexpr-2.1892 {
  db eval {SELECT coalesce((select max(case 13 when +coalesce((select max(c) from t1 where t1.a+f in (t1.b,t1.b,(abs(19)/abs(+17+~(abs(t1.a+f)/abs(~t1.c))+case when not exists(select 1 from t1 where coalesce((select max(e) from t1 where (b)> -t1.a),c)=t1.b) then 19 else b end))-f)),t1.a)+a then f else 17 end*t1.e) from t1 where 13<>t1.f),t1.f) FROM t1 WHERE not exists(select 1 from t1 where coalesce((select max(case when 13 not in (t1.b,b,t1.c) then t1.c | t1.a else 13-19+a+t1.e-t1.e end+t1.a*17+( -d)-17 | t1.c-t1.a | 19+b) from t1 where not a=e),11) in (select 17 from t1 union select c from t1) or t1.c>=t1.e)}
} {8500}
do_test randexpr-2.1893 {
  db eval {SELECT coalesce((select max(case 13 when +coalesce((select max(c) from t1 where t1.a+f in (t1.b,t1.b,(abs(19)/abs(+17+~(abs(t1.a+f)/abs(~t1.c))+case when not exists(select 1 from t1 where coalesce((select max(e) from t1 where (b)> -t1.a),c)=t1.b) then 19 else b end))-f)),t1.a)+a then f else 17 end*t1.e) from t1 where 13<>t1.f),t1.f) FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select max(case when 13 not in (t1.b,b,t1.c) then t1.c | t1.a else 13-19+a+t1.e-t1.e end+t1.a*17+( -d)-17 | t1.c-t1.a | 19+b) from t1 where not a=e),11) in (select 17 from t1 union select c from t1) or t1.c>=t1.e))}
} {}
do_test randexpr-2.1894 {
  db eval {SELECT t1.f++c*coalesce((select +t1.f from t1 where a<~13),case when exists(select 1 from t1 where not exists(select 1 from t1 where 17 in (select 11 from t1 union select (17) from t1))) then b else + -19 | coalesce((select case when (select cast(avg(a) AS integer) from t1)>e then case when (11=(e) and 17<f) then (e)+ -c else e end else c end from t1 where 13 not in (f,t1.b,e)),t1.d) end*t1.c) FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where t1.e=+(abs((coalesce((select max( -a | case when coalesce((select c from t1 where not 17 not between t1.e and t1.b),e)-(a) not between t1.e and t1.b then f when c>=t1.a then  -c else 19 end-f) from t1 where not exists(select 1 from t1 where d in (select  -~count(distinct 11)+max(t1.a) from t1 union select count(distinct e)* -count(distinct t1.b) from t1)) or (c<t1.c)),t1.f)))/abs(t1.c))))}
} {-1709400}
do_test randexpr-2.1895 {
  db eval {SELECT t1.f++c*coalesce((select +t1.f from t1 where a<~13),case when exists(select 1 from t1 where not exists(select 1 from t1 where 17 in (select 11 from t1 union select (17) from t1))) then b else + -19 | coalesce((select case when (select cast(avg(a) AS integer) from t1)>e then case when (11=(e) and 17<f) then (e)+ -c else e end else c end from t1 where 13 not in (f,t1.b,e)),t1.d) end*t1.c) FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where t1.e=+(abs((coalesce((select max( -a | case when coalesce((select c from t1 where not 17 not between t1.e and t1.b),e)-(a) not between t1.e and t1.b then f when c>=t1.a then  -c else 19 end-f) from t1 where not exists(select 1 from t1 where d in (select  -~count(distinct 11)+max(t1.a) from t1 union select count(distinct e)* -count(distinct t1.b) from t1)) or (c<t1.c)),t1.f)))/abs(t1.c)))))}
} {}
do_test randexpr-2.1896 {
  db eval {SELECT t1.f++c*coalesce((select +t1.f from t1 where a<~13),case when exists(select 1 from t1 where not exists(select 1 from t1 where 17 in (select 11 from t1 union select (17) from t1))) then b else + -19 & coalesce((select case when (select cast(avg(a) AS integer) from t1)>e then case when (11=(e) and 17<f) then (e)+ -c else e end else c end from t1 where 13 not in (f,t1.b,e)),t1.d) end*t1.c) FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where t1.e=+(abs((coalesce((select max( -a | case when coalesce((select c from t1 where not 17 not between t1.e and t1.b),e)-(a) not between t1.e and t1.b then f when c>=t1.a then  -c else 19 end-f) from t1 where not exists(select 1 from t1 where d in (select  -~count(distinct 11)+max(t1.a) from t1 union select count(distinct e)* -count(distinct t1.b) from t1)) or (c<t1.c)),t1.f)))/abs(t1.c))))}
} {27000600}
do_test randexpr-2.1897 {
  db eval {SELECT (select + -min(case when case when exists(select 1 from t1 where a<=c or coalesce((select max(11) from t1 where d=17),19)*11<=f and t1.e in (select t1.c from t1 union select a from t1)) then (f)-d when a<t1.a then t1.b else a end in (select ~( -min(f)) from t1 union select case  -max(t1.d)-count(distinct t1.c) when min(f) then cast(avg( -e) AS integer) else ( -count(distinct 17)) end from t1) then d when t1.f>=t1.c then f else t1.f end-f) from t1) FROM t1 WHERE (~ -t1.c in (select d from t1 union select t1.c*case when (17 in (+case c when t1.f then t1.c else c+e+t1.c*e+coalesce((select max((c)) from t1 where (t1.e)>a),19)-t1.e end | e-t1.b,t1.d,c)) then d when t1.e in (select (max( -e)-~~count(*)) from t1 union select count(*) from t1) then d else t1.f end from t1))}
} {}
do_test randexpr-2.1898 {
  db eval {SELECT (select + -min(case when case when exists(select 1 from t1 where a<=c or coalesce((select max(11) from t1 where d=17),19)*11<=f and t1.e in (select t1.c from t1 union select a from t1)) then (f)-d when a<t1.a then t1.b else a end in (select ~( -min(f)) from t1 union select case  -max(t1.d)-count(distinct t1.c) when min(f) then cast(avg( -e) AS integer) else ( -count(distinct 17)) end from t1) then d when t1.f>=t1.c then f else t1.f end-f) from t1) FROM t1 WHERE NOT ((~ -t1.c in (select d from t1 union select t1.c*case when (17 in (+case c when t1.f then t1.c else c+e+t1.c*e+coalesce((select max((c)) from t1 where (t1.e)>a),19)-t1.e end | e-t1.b,t1.d,c)) then d when t1.e in (select (max( -e)-~~count(*)) from t1 union select count(*) from t1) then d else t1.f end from t1)))}
} {0}
do_test randexpr-2.1899 {
  db eval {SELECT ~+t1.f-coalesce((select t1.f from t1 where case when t1.d>=t1.f then b else case c when 11 then t1.f*case when (select (count(*)) from t1)<>a+t1.b | +11-coalesce((select max(t1.f-a) from t1 where (f<=t1.c and t1.d=c)),d)-11 then b when (t1.c)<=t1.b then 19 else 11 end else c end end*19-13< - -b),e) FROM t1 WHERE (exists(select 1 from t1 where  -t1.f not between ~17 and t1.a+(b+d+13)))}
} {-1101}
do_test randexpr-2.1900 {
  db eval {SELECT ~+t1.f-coalesce((select t1.f from t1 where case when t1.d>=t1.f then b else case c when 11 then t1.f*case when (select (count(*)) from t1)<>a+t1.b | +11-coalesce((select max(t1.f-a) from t1 where (f<=t1.c and t1.d=c)),d)-11 then b when (t1.c)<=t1.b then 19 else 11 end else c end end*19-13< - -b),e) FROM t1 WHERE NOT ((exists(select 1 from t1 where  -t1.f not between ~17 and t1.a+(b+d+13))))}
} {}
do_test randexpr-2.1901 {
  db eval {SELECT ~+t1.f-coalesce((select t1.f from t1 where case when t1.d>=t1.f then b else case c when 11 then t1.f*case when (select (count(*)) from t1)<>a+t1.b & +11-coalesce((select max(t1.f-a) from t1 where (f<=t1.c and t1.d=c)),d)-11 then b when (t1.c)<=t1.b then 19 else 11 end else c end end*19-13< - -b),e) FROM t1 WHERE (exists(select 1 from t1 where  -t1.f not between ~17 and t1.a+(b+d+13)))}
} {-1101}
do_test randexpr-2.1902 {
  db eval {SELECT  -t1.e+coalesce((select (d) from t1 where t1.f=t1.f*(select +count(distinct case when (coalesce((select max(case when a in (select b+17 from t1 union select  -17 from t1) then 19 when 17<c then t1.b else c end | t1.e) from t1 where exists(select 1 from t1 where  -e in (t1.b,t1.d,c) and f not between t1.f and b) and 17<>a),e)<>f or d not between (e) and b) then 11 else (abs(13)/abs( -(d))) end*t1.c) from t1)),e-f) FROM t1 WHERE ((case when t1.e+d*~coalesce((select coalesce((select max(b) from t1 where ~case when t1.f not between t1.c and coalesce((select t1.b from t1 where  -t1.e in (select (( - -min(19))) from t1 union select count(distinct t1.d) from t1)),t1.d) then c when t1.f=e then t1.f else b end=13),13) from t1 where t1.e not between 13 and 11 or not exists(select 1 from t1 where t1.a not between (11) and d and 11>=a)),t1.f) in (select count(*) from t1 union select ~max( -13) from t1) then  -13 else 17 end) | d in (a,d,13))}
} {}
do_test randexpr-2.1903 {
  db eval {SELECT  -t1.e+coalesce((select (d) from t1 where t1.f=t1.f*(select +count(distinct case when (coalesce((select max(case when a in (select b+17 from t1 union select  -17 from t1) then 19 when 17<c then t1.b else c end | t1.e) from t1 where exists(select 1 from t1 where  -e in (t1.b,t1.d,c) and f not between t1.f and b) and 17<>a),e)<>f or d not between (e) and b) then 11 else (abs(13)/abs( -(d))) end*t1.c) from t1)),e-f) FROM t1 WHERE NOT (((case when t1.e+d*~coalesce((select coalesce((select max(b) from t1 where ~case when t1.f not between t1.c and coalesce((select t1.b from t1 where  -t1.e in (select (( - -min(19))) from t1 union select count(distinct t1.d) from t1)),t1.d) then c when t1.f=e then t1.f else b end=13),13) from t1 where t1.e not between 13 and 11 or not exists(select 1 from t1 where t1.a not between (11) and d and 11>=a)),t1.f) in (select count(*) from t1 union select ~max( -13) from t1) then  -13 else 17 end) | d in (a,d,13)))}
} {-100}
do_test randexpr-2.1904 {
  db eval {SELECT  -t1.e+coalesce((select (d) from t1 where t1.f=t1.f*(select +count(distinct case when (coalesce((select max(case when a in (select b+17 from t1 union select  -17 from t1) then 19 when 17<c then t1.b else c end & t1.e) from t1 where exists(select 1 from t1 where  -e in (t1.b,t1.d,c) and f not between t1.f and b) and 17<>a),e)<>f or d not between (e) and b) then 11 else (abs(13)/abs( -(d))) end*t1.c) from t1)),e-f) FROM t1 WHERE NOT (((case when t1.e+d*~coalesce((select coalesce((select max(b) from t1 where ~case when t1.f not between t1.c and coalesce((select t1.b from t1 where  -t1.e in (select (( - -min(19))) from t1 union select count(distinct t1.d) from t1)),t1.d) then c when t1.f=e then t1.f else b end=13),13) from t1 where t1.e not between 13 and 11 or not exists(select 1 from t1 where t1.a not between (11) and d and 11>=a)),t1.f) in (select count(*) from t1 union select ~max( -13) from t1) then  -13 else 17 end) | d in (a,d,13)))}
} {-100}
do_test randexpr-2.1905 {
  db eval {SELECT coalesce((select max((19)) from t1 where d* -a<=(select count(*) from t1)+19*19*a-e-d or b in (t1.c+ -t1.b,t1.a,b+t1.b)),d) FROM t1 WHERE exists(select 1 from t1 where exists(select 1 from t1 where not t1.e>e))}
} {19}
do_test randexpr-2.1906 {
  db eval {SELECT coalesce((select max((19)) from t1 where d* -a<=(select count(*) from t1)+19*19*a-e-d or b in (t1.c+ -t1.b,t1.a,b+t1.b)),d) FROM t1 WHERE NOT (exists(select 1 from t1 where exists(select 1 from t1 where not t1.e>e)))}
} {}
do_test randexpr-2.1907 {
  db eval {SELECT (select  -~count(distinct (abs(11)/abs(f-17-+(select cast(avg(+(select count(*) from t1)) AS integer) from t1)))) from t1) FROM t1 WHERE (abs((a))/abs(t1.b))>(select count(distinct case case when 17 in (select  -b-case when 17 in (select +(( - -max(t1.b))) from t1 union select max((t1.b)) from t1) then f when t1.e=(t1.d) then 17 else e end | e-t1.d | t1.c* -13*d*t1.b from t1 union select 11 from t1) then c when c>=a then 13 else 13 end+t1.b when  -f then 19 else 13 end)*min(t1.f) from t1)-19-f}
} {2}
do_test randexpr-2.1908 {
  db eval {SELECT (select  -~count(distinct (abs(11)/abs(f-17-+(select cast(avg(+(select count(*) from t1)) AS integer) from t1)))) from t1) FROM t1 WHERE NOT ((abs((a))/abs(t1.b))>(select count(distinct case case when 17 in (select  -b-case when 17 in (select +(( - -max(t1.b))) from t1 union select max((t1.b)) from t1) then f when t1.e=(t1.d) then 17 else e end | e-t1.d | t1.c* -13*d*t1.b from t1 union select 11 from t1) then c when c>=a then 13 else 13 end+t1.b when  -f then 19 else 13 end)*min(t1.f) from t1)-19-f)}
} {}
do_test randexpr-2.1909 {
  db eval {SELECT  -(select cast(avg(coalesce((select max(f) from t1 where  -case coalesce((select max(~c-case when exists(select 1 from t1 where  -b in (~e,t1.e,t1.e)) then t1.e when (17 in (select ++ -(count(distinct t1.a)) from t1 union select (max( -f)) from t1)) then b else t1.f end) from t1 where (13 in (19,b,11))),t1.e) when c then (b) else 11 end-a*b*13=t1.e),13)) AS integer) from t1) FROM t1 WHERE exists(select 1 from t1 where case when not (case when ~17*d>=b then a when c*(abs((abs(f)/abs(t1.c)))/abs(t1.b))+d*t1.b<19 and not case 13 when a then 11 else  -t1.e end<>f then 11 else c end+t1.d) not in (t1.c,t1.f,d) then (abs(c)/abs(t1.f)) else t1.a end*t1.f not between t1.d and c)}
} {-13}
do_test randexpr-2.1910 {
  db eval {SELECT  -(select cast(avg(coalesce((select max(f) from t1 where  -case coalesce((select max(~c-case when exists(select 1 from t1 where  -b in (~e,t1.e,t1.e)) then t1.e when (17 in (select ++ -(count(distinct t1.a)) from t1 union select (max( -f)) from t1)) then b else t1.f end) from t1 where (13 in (19,b,11))),t1.e) when c then (b) else 11 end-a*b*13=t1.e),13)) AS integer) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where case when not (case when ~17*d>=b then a when c*(abs((abs(f)/abs(t1.c)))/abs(t1.b))+d*t1.b<19 and not case 13 when a then 11 else  -t1.e end<>f then 11 else c end+t1.d) not in (t1.c,t1.f,d) then (abs(c)/abs(t1.f)) else t1.a end*t1.f not between t1.d and c))}
} {}
do_test randexpr-2.1911 {
  db eval {SELECT case t1.c when (select abs( -max(t1.a*t1.f*t1.a*e)) from t1)*case when not exists(select 1 from t1 where (select cast(avg(c) AS integer) from t1) in (select case case when ( -case t1.f when 17 then t1.c else e end=17) then 19 else e end when e then c else  -a end*t1.d from t1 union select d from t1)) then e*t1.a else b end+e*t1.d+t1.b then t1.d else c end+t1.e FROM t1 WHERE 13 in (select +abs(case count(distinct t1.e+(abs((abs(coalesce((select t1.b from t1 where coalesce((select max(case when (19<=t1.d) then (13) when a>=13 then 13 else t1.f end) from t1 where a in (t1.c,19,t1.b)),19)>13),d))/abs(f))+t1.a*t1.b)/abs(e))) when +cast(avg(c) AS integer) then ~~+max(f) | cast(avg(t1.c) AS integer) else count(distinct 13)+min(t1.b) | count(*) end)*max(t1.d)-count(*) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.1912 {
  db eval {SELECT case t1.c when (select abs( -max(t1.a*t1.f*t1.a*e)) from t1)*case when not exists(select 1 from t1 where (select cast(avg(c) AS integer) from t1) in (select case case when ( -case t1.f when 17 then t1.c else e end=17) then 19 else e end when e then c else  -a end*t1.d from t1 union select d from t1)) then e*t1.a else b end+e*t1.d+t1.b then t1.d else c end+t1.e FROM t1 WHERE NOT (13 in (select +abs(case count(distinct t1.e+(abs((abs(coalesce((select t1.b from t1 where coalesce((select max(case when (19<=t1.d) then (13) when a>=13 then 13 else t1.f end) from t1 where a in (t1.c,19,t1.b)),19)>13),d))/abs(f))+t1.a*t1.b)/abs(e))) when +cast(avg(c) AS integer) then ~~+max(f) | cast(avg(t1.c) AS integer) else count(distinct 13)+min(t1.b) | count(*) end)*max(t1.d)-count(*) from t1 union select count(*) from t1))}
} {800}
do_test randexpr-2.1913 {
  db eval {SELECT case when f in (d, -case when (case 11 when (select max(t1.d) from t1) then (abs(a)/abs(+t1.b)) else ~b end<19) then (abs( -(abs(17)/abs(t1.f)))/abs((select count(*) from t1))) when (f) not between coalesce((select 13 from t1 where t1.a<=case t1.a when 13 then  -t1.c else 13 end and 13 not between t1.f and 11),11) and 19 then e else b end,t1.d) then b else t1.b end FROM t1 WHERE t1.f between f and a-c-t1.d-t1.d+t1.d*case when exists(select 1 from t1 where d between (select ~cast(avg(17) AS integer) from t1) and a) then case when case b when f then 13 else b end<c then t1.d when (t1.a) in (select  -( -b) from t1 union select  -t1.f from t1) and f not in (t1.b,t1.d,t1.a) then  -d else (13) end when d in (c,((t1.d)),c) then b else 19 end and exists(select 1 from t1 where not t1.a=17)}
} {200}
do_test randexpr-2.1914 {
  db eval {SELECT case when f in (d, -case when (case 11 when (select max(t1.d) from t1) then (abs(a)/abs(+t1.b)) else ~b end<19) then (abs( -(abs(17)/abs(t1.f)))/abs((select count(*) from t1))) when (f) not between coalesce((select 13 from t1 where t1.a<=case t1.a when 13 then  -t1.c else 13 end and 13 not between t1.f and 11),11) and 19 then e else b end,t1.d) then b else t1.b end FROM t1 WHERE NOT (t1.f between f and a-c-t1.d-t1.d+t1.d*case when exists(select 1 from t1 where d between (select ~cast(avg(17) AS integer) from t1) and a) then case when case b when f then 13 else b end<c then t1.d when (t1.a) in (select  -( -b) from t1 union select  -t1.f from t1) and f not in (t1.b,t1.d,t1.a) then  -d else (13) end when d in (c,((t1.d)),c) then b else 19 end and exists(select 1 from t1 where not t1.a=17))}
} {}
do_test randexpr-2.1915 {
  db eval {SELECT (abs(case when 11<=case 17 when t1.d then t1.b+~19-~case when not t1.b not in (t1.a,b,coalesce((select a+(a) from t1 where t1.b>19),t1.b)) or ((t1.a>19)) or e<>19 then  -t1.e else  -13 end-b+t1.d else a end then 19 when d between b and t1.c then t1.e else e end)/abs(t1.a)) FROM t1 WHERE b | t1.b>b-case when a-f in (select 17 from t1 union select coalesce((select coalesce((select t1.e+t1.a+d+d from t1 where 13 not between t1.e+19 and 13),(select count(distinct t1.e) from t1)*11) from t1 where b not in (b,(t1.f),t1.a)),13) from t1) then b else c end+a-13-13*(13) | 11}
} {0}
do_test randexpr-2.1916 {
  db eval {SELECT (abs(case when 11<=case 17 when t1.d then t1.b+~19-~case when not t1.b not in (t1.a,b,coalesce((select a+(a) from t1 where t1.b>19),t1.b)) or ((t1.a>19)) or e<>19 then  -t1.e else  -13 end-b+t1.d else a end then 19 when d between b and t1.c then t1.e else e end)/abs(t1.a)) FROM t1 WHERE NOT (b | t1.b>b-case when a-f in (select 17 from t1 union select coalesce((select coalesce((select t1.e+t1.a+d+d from t1 where 13 not between t1.e+19 and 13),(select count(distinct t1.e) from t1)*11) from t1 where b not in (b,(t1.f),t1.a)),13) from t1) then b else c end+a-13-13*(13) | 11)}
} {}
do_test randexpr-2.1917 {
  db eval {SELECT  -t1.a | coalesce((select t1.f*(select min(f)+min(( -(select  -case (min(13)) when  -abs(min(t1.b)) then count(distinct a) else count(*) end from t1)*(select  - -count(*) from t1)))* -count(*) from t1) from t1 where t1.d in (select case case when t1.a<(f) then c else 19 end when f then b else  -c end*a*t1.c from t1 union select t1.b from t1)),b) | a FROM t1 WHERE +19*case when exists(select 1 from t1 where e<+13 | f or t1.d=19) then t1.a when case when exists(select 1 from t1 where t1.c in (select 11 from t1 union select c from t1)) then 13*t1.e else 19 end<=c and (t1.e between (b) and 13) or 11 not between t1.f and 13 or 17 between b and 13 then t1.e+a else 17 end not between b and d or t1.e not between 13 and 17}
} {-4}
do_test randexpr-2.1918 {
  db eval {SELECT  -t1.a | coalesce((select t1.f*(select min(f)+min(( -(select  -case (min(13)) when  -abs(min(t1.b)) then count(distinct a) else count(*) end from t1)*(select  - -count(*) from t1)))* -count(*) from t1) from t1 where t1.d in (select case case when t1.a<(f) then c else 19 end when f then b else  -c end*a*t1.c from t1 union select t1.b from t1)),b) | a FROM t1 WHERE NOT (+19*case when exists(select 1 from t1 where e<+13 | f or t1.d=19) then t1.a when case when exists(select 1 from t1 where t1.c in (select 11 from t1 union select c from t1)) then 13*t1.e else 19 end<=c and (t1.e between (b) and 13) or 11 not between t1.f and 13 or 17 between b and 13 then t1.e+a else 17 end not between b and d or t1.e not between 13 and 17)}
} {}
do_test randexpr-2.1919 {
  db eval {SELECT  -t1.a & coalesce((select t1.f*(select min(f)+min(( -(select  -case (min(13)) when  -abs(min(t1.b)) then count(distinct a) else count(*) end from t1)*(select  - -count(*) from t1)))* -count(*) from t1) from t1 where t1.d in (select case case when t1.a<(f) then c else 19 end when f then b else  -c end*a*t1.c from t1 union select t1.b from t1)),b) & a FROM t1 WHERE +19*case when exists(select 1 from t1 where e<+13 | f or t1.d=19) then t1.a when case when exists(select 1 from t1 where t1.c in (select 11 from t1 union select c from t1)) then 13*t1.e else 19 end<=c and (t1.e between (b) and 13) or 11 not between t1.f and 13 or 17 between b and 13 then t1.e+a else 17 end not between b and d or t1.e not between 13 and 17}
} {0}
do_test randexpr-2.1920 {
  db eval {SELECT (select  -case +count(distinct case when  -+ -~case when ((t1.e)) not between e and f then e when t1.b between  -11 and t1.b then d else t1.a end*19 in (select t1.f from t1 union select t1.d from t1) then t1.b when a in (select  -19 from t1 union select c from t1) then a else f end) when +~ -(count(*)) then  -( -count(distinct t1.e))-count(distinct c) else max(t1.c) end-count(distinct t1.c)-count(distinct 19)-(max(11)) from t1) FROM t1 WHERE  -~coalesce((select max(19*t1.b) from t1 where t1.d in (select max( -coalesce((select max(t1.c) from t1 where case 13 when f+ -13+t1.b-case 13 when t1.a | (abs(t1.a)/abs(t1.f)) then 11 else f end then f else 17 end in (b,t1.d,(e))),13)) from t1 union select ~~min(b)*abs(cast(avg(b) AS integer)) from t1)),e)*((t1.d))<>t1.d}
} {-313}
do_test randexpr-2.1921 {
  db eval {SELECT (select  -case +count(distinct case when  -+ -~case when ((t1.e)) not between e and f then e when t1.b between  -11 and t1.b then d else t1.a end*19 in (select t1.f from t1 union select t1.d from t1) then t1.b when a in (select  -19 from t1 union select c from t1) then a else f end) when +~ -(count(*)) then  -( -count(distinct t1.e))-count(distinct c) else max(t1.c) end-count(distinct t1.c)-count(distinct 19)-(max(11)) from t1) FROM t1 WHERE NOT ( -~coalesce((select max(19*t1.b) from t1 where t1.d in (select max( -coalesce((select max(t1.c) from t1 where case 13 when f+ -13+t1.b-case 13 when t1.a | (abs(t1.a)/abs(t1.f)) then 11 else f end then f else 17 end in (b,t1.d,(e))),13)) from t1 union select ~~min(b)*abs(cast(avg(b) AS integer)) from t1)),e)*((t1.d))<>t1.d)}
} {}
do_test randexpr-2.1922 {
  db eval {SELECT case a when c then (abs((select abs(~(+~~case max(t1.d) when +count(distinct ~d | (select case max(17) when count(*) then count(distinct (t1.c)) else count(distinct 11) end from t1)) then (+cast(avg((17)) AS integer))+count(*) else  -(( - -(cast(avg(c) AS integer)))) end)+count(distinct t1.e)+min(13)) from t1)*+11-((abs(t1.a)/abs(coalesce((select c from t1 where ((t1.f<>d))),(t1.c))))) | t1.d)/abs( -(d))) else a end FROM t1 WHERE coalesce((select max(case t1.a when +t1.e then case when t1.c+(select (max(t1.d))-max(13)+cast(avg(c) AS integer)+min((e)) | max(a) from t1)<= -t1.a | case when not exists(select 1 from t1 where  -t1.d<=t1.a) then t1.f when 11<a then f else t1.f end then b when  -t1.c>=c then a else 13 end | t1.c else t1.a end) from t1 where 19<=e and t1.e between t1.d and 11),13) not in (e,a,c)}
} {100}
do_test randexpr-2.1923 {
  db eval {SELECT case a when c then (abs((select abs(~(+~~case max(t1.d) when +count(distinct ~d | (select case max(17) when count(*) then count(distinct (t1.c)) else count(distinct 11) end from t1)) then (+cast(avg((17)) AS integer))+count(*) else  -(( - -(cast(avg(c) AS integer)))) end)+count(distinct t1.e)+min(13)) from t1)*+11-((abs(t1.a)/abs(coalesce((select c from t1 where ((t1.f<>d))),(t1.c))))) | t1.d)/abs( -(d))) else a end FROM t1 WHERE NOT (coalesce((select max(case t1.a when +t1.e then case when t1.c+(select (max(t1.d))-max(13)+cast(avg(c) AS integer)+min((e)) | max(a) from t1)<= -t1.a | case when not exists(select 1 from t1 where  -t1.d<=t1.a) then t1.f when 11<a then f else t1.f end then b when  -t1.c>=c then a else 13 end | t1.c else t1.a end) from t1 where 19<=e and t1.e between t1.d and 11),13) not in (e,a,c))}
} {}
do_test randexpr-2.1924 {
  db eval {SELECT case a when c then (abs((select abs(~(+~~case max(t1.d) when +count(distinct ~d & (select case max(17) when count(*) then count(distinct (t1.c)) else count(distinct 11) end from t1)) then (+cast(avg((17)) AS integer))+count(*) else  -(( - -(cast(avg(c) AS integer)))) end)+count(distinct t1.e)+min(13)) from t1)*+11-((abs(t1.a)/abs(coalesce((select c from t1 where ((t1.f<>d))),(t1.c))))) & t1.d)/abs( -(d))) else a end FROM t1 WHERE coalesce((select max(case t1.a when +t1.e then case when t1.c+(select (max(t1.d))-max(13)+cast(avg(c) AS integer)+min((e)) | max(a) from t1)<= -t1.a | case when not exists(select 1 from t1 where  -t1.d<=t1.a) then t1.f when 11<a then f else t1.f end then b when  -t1.c>=c then a else 13 end | t1.c else t1.a end) from t1 where 19<=e and t1.e between t1.d and 11),13) not in (e,a,c)}
} {100}
do_test randexpr-2.1925 {
  db eval {SELECT t1.d-+case ~(select ~+~count(distinct case when case when case when 11 not between t1.c and t1.a-e then t1.d else e end*d-(d) between  -13 and e then a else c end in (select b from t1 union select 17 from t1) then a else 13 end)*cast(avg(d) AS integer) from t1) when t1.e then (abs(11)/abs(coalesce((select max(19) from t1 where (a)<>t1.e),19))) else t1.c end+t1.c FROM t1 WHERE 19 not in (t1.a*+case when  -c+~t1.a-t1.c in (t1.a,b*case t1.a | coalesce((select max(coalesce((select 17 from t1 where t1.e>t1.a),t1.d)) from t1 where not 11=19),17) when 11 then t1.d else (f) end*b-t1.a+c, -b) then d when a<>f then a else b end-c,d,t1.b)}
} {400}
do_test randexpr-2.1926 {
  db eval {SELECT t1.d-+case ~(select ~+~count(distinct case when case when case when 11 not between t1.c and t1.a-e then t1.d else e end*d-(d) between  -13 and e then a else c end in (select b from t1 union select 17 from t1) then a else 13 end)*cast(avg(d) AS integer) from t1) when t1.e then (abs(11)/abs(coalesce((select max(19) from t1 where (a)<>t1.e),19))) else t1.c end+t1.c FROM t1 WHERE NOT (19 not in (t1.a*+case when  -c+~t1.a-t1.c in (t1.a,b*case t1.a | coalesce((select max(coalesce((select 17 from t1 where t1.e>t1.a),t1.d)) from t1 where not 11=19),17) when 11 then t1.d else (f) end*b-t1.a+c, -b) then d when a<>f then a else b end-c,d,t1.b))}
} {}
do_test randexpr-2.1927 {
  db eval {SELECT case when case (select +min(~ -11+f*~b) | case abs(cast(avg(t1.f) AS integer))*~min(c) when count(*)+max( -11) then abs(count(*)) else max(13) end from t1) when coalesce((select max(coalesce((select max(19) from t1 where (17>=17)),t1.f)) from t1 where c<b),13) then t1.f else (f) end*t1.f>t1.a then  -d else  -t1.b end FROM t1 WHERE t1.a+b-t1.c*17>=c}
} {}
do_test randexpr-2.1928 {
  db eval {SELECT case when case (select +min(~ -11+f*~b) | case abs(cast(avg(t1.f) AS integer))*~min(c) when count(*)+max( -11) then abs(count(*)) else max(13) end from t1) when coalesce((select max(coalesce((select max(19) from t1 where (17>=17)),t1.f)) from t1 where c<b),13) then t1.f else (f) end*t1.f>t1.a then  -d else  -t1.b end FROM t1 WHERE NOT (t1.a+b-t1.c*17>=c)}
} {-400}
do_test randexpr-2.1929 {
  db eval {SELECT case when case (select +min(~ -11+f*~b) & case abs(cast(avg(t1.f) AS integer))*~min(c) when count(*)+max( -11) then abs(count(*)) else max(13) end from t1) when coalesce((select max(coalesce((select max(19) from t1 where (17>=17)),t1.f)) from t1 where c<b),13) then t1.f else (f) end*t1.f>t1.a then  -d else  -t1.b end FROM t1 WHERE NOT (t1.a+b-t1.c*17>=c)}
} {-400}
do_test randexpr-2.1930 {
  db eval {SELECT case when ~case when t1.f>11*t1.a then f when case when (t1.c*19<(t1.f)) then (e) when a<t1.f then c else  -e end not in (11,b,19) then t1.a else f end=17 or not t1.a>t1.e and a in (d,t1.c,13) then t1.b when  -17 not between f and d then f else t1.c end FROM t1 WHERE c in (select + -min(case (select count(*) from t1) when t1.a then t1.c else coalesce((select max(b) from t1 where d in (select  -abs(cast(avg(t1.b) AS integer)) | (min(t1.f)) | count(distinct a)+abs(cast(avg(b) AS integer))*( -min(b)) | cast(avg(t1.c) AS integer)*((min(t1.e))) from t1 union select cast(avg(f) AS integer) from t1)),t1.e) | +case b when  -t1.c then (select (count(*)) from t1) else b end | 13 end) from t1 union select min(t1.d) from t1)}
} {}
do_test randexpr-2.1931 {
  db eval {SELECT case when ~case when t1.f>11*t1.a then f when case when (t1.c*19<(t1.f)) then (e) when a<t1.f then c else  -e end not in (11,b,19) then t1.a else f end=17 or not t1.a>t1.e and a in (d,t1.c,13) then t1.b when  -17 not between f and d then f else t1.c end FROM t1 WHERE NOT (c in (select + -min(case (select count(*) from t1) when t1.a then t1.c else coalesce((select max(b) from t1 where d in (select  -abs(cast(avg(t1.b) AS integer)) | (min(t1.f)) | count(distinct a)+abs(cast(avg(b) AS integer))*( -min(b)) | cast(avg(t1.c) AS integer)*((min(t1.e))) from t1 union select cast(avg(f) AS integer) from t1)),t1.e) | +case b when  -t1.c then (select (count(*)) from t1) else b end | 13 end) from t1 union select min(t1.d) from t1))}
} {600}
do_test randexpr-2.1932 {
  db eval {SELECT case when (b) between 19 and case when t1.a* -t1.d+t1.a-t1.d-b-a<=d then t1.c when not exists(select 1 from t1 where (13>t1.e) and ((a>a))) and  -(13)>t1.b then t1.d else 11 end or d=e then 13+t1.f when ( -a) not between t1.e and t1.b then (c) else t1.e end+t1.a+17 FROM t1 WHERE (case when a<=f+t1.a | f then t1.c*a-coalesce((select max( -e) from t1 where t1.a=t1.d),b)*d- -f else t1.b end) in (select min(t1.f)+~max(b) | count(distinct t1.d)*+ - -case (count(*)) when +count(distinct e) then count(*) else  -cast(avg(d) AS integer) end from t1 union select count(*) from t1) and d between 11 and t1.a}
} {}
do_test randexpr-2.1933 {
  db eval {SELECT case when (b) between 19 and case when t1.a* -t1.d+t1.a-t1.d-b-a<=d then t1.c when not exists(select 1 from t1 where (13>t1.e) and ((a>a))) and  -(13)>t1.b then t1.d else 11 end or d=e then 13+t1.f when ( -a) not between t1.e and t1.b then (c) else t1.e end+t1.a+17 FROM t1 WHERE NOT ((case when a<=f+t1.a | f then t1.c*a-coalesce((select max( -e) from t1 where t1.a=t1.d),b)*d- -f else t1.b end) in (select min(t1.f)+~max(b) | count(distinct t1.d)*+ - -case (count(*)) when +count(distinct e) then count(*) else  -cast(avg(d) AS integer) end from t1 union select count(*) from t1) and d between 11 and t1.a)}
} {730}
do_test randexpr-2.1934 {
  db eval {SELECT +f*19*~~ -t1.c-13-case when t1.b in (select +case when not exists(select 1 from t1 where (((abs((abs((select count(*)*(count(distinct t1.d)) from t1))/abs(b)))/abs(e))*(e))>=d)) then f when t1.a=f then b else t1.e end+19 | (17) from t1 union select t1.b from t1) or  -e<t1.d then 11 else a end-t1.b FROM t1 WHERE (e in (17,t1.b*19+(abs(19)/abs(coalesce((select t1.b+d from t1 where not exists(select 1 from t1 where 19* -t1.c+ -t1.b-~e not between 11-c+b and 11) or e=a),d))),a)) and d<=b or b>e and t1.e<=t1.b}
} {}
do_test randexpr-2.1935 {
  db eval {SELECT +f*19*~~ -t1.c-13-case when t1.b in (select +case when not exists(select 1 from t1 where (((abs((abs((select count(*)*(count(distinct t1.d)) from t1))/abs(b)))/abs(e))*(e))>=d)) then f when t1.a=f then b else t1.e end+19 | (17) from t1 union select t1.b from t1) or  -e<t1.d then 11 else a end-t1.b FROM t1 WHERE NOT ((e in (17,t1.b*19+(abs(19)/abs(coalesce((select t1.b+d from t1 where not exists(select 1 from t1 where 19* -t1.c+ -t1.b-~e not between 11-c+b and 11) or e=a),d))),a)) and d<=b or b>e and t1.e<=t1.b)}
} {-3420224}
do_test randexpr-2.1936 {
  db eval {SELECT +f*19*~~ -t1.c-13-case when t1.b in (select +case when not exists(select 1 from t1 where (((abs((abs((select count(*)*(count(distinct t1.d)) from t1))/abs(b)))/abs(e))*(e))>=d)) then f when t1.a=f then b else t1.e end+19 & (17) from t1 union select t1.b from t1) or  -e<t1.d then 11 else a end-t1.b FROM t1 WHERE NOT ((e in (17,t1.b*19+(abs(19)/abs(coalesce((select t1.b+d from t1 where not exists(select 1 from t1 where 19* -t1.c+ -t1.b-~e not between 11-c+b and 11) or e=a),d))),a)) and d<=b or b>e and t1.e<=t1.b)}
} {-3420224}
do_test randexpr-2.1937 {
  db eval {SELECT f-coalesce((select max(d+~+ - -(a)*(select min(t1.d) from t1)*t1.f+case when ( -13)*t1.e<>11 |  -t1.e or c=11 then (t1.e) when  -t1.d<=t1.b and (t1.f<>t1.c) then a else  -t1.f end) from t1 where 11 not between t1.e and b),t1.f)-13 FROM t1 WHERE  -a not in (17+~coalesce((select t1.a from t1 where (exists(select 1 from t1 where 11>c))),11)+17-11,11,t1.c) or f in (select case (min((t1.a))) when max(b) then min(13) else cast(avg(c) AS integer) end*max(d)*(case cast(avg(19) AS integer) when ( -min(19)) then count(*) else count(*) end) |  -cast(avg(19) AS integer) from t1 union select cast(avg(b) AS integer) from t1) or t1.f>= -t1.d}
} {24239687}
do_test randexpr-2.1938 {
  db eval {SELECT f-coalesce((select max(d+~+ - -(a)*(select min(t1.d) from t1)*t1.f+case when ( -13)*t1.e<>11 |  -t1.e or c=11 then (t1.e) when  -t1.d<=t1.b and (t1.f<>t1.c) then a else  -t1.f end) from t1 where 11 not between t1.e and b),t1.f)-13 FROM t1 WHERE NOT ( -a not in (17+~coalesce((select t1.a from t1 where (exists(select 1 from t1 where 11>c))),11)+17-11,11,t1.c) or f in (select case (min((t1.a))) when max(b) then min(13) else cast(avg(c) AS integer) end*max(d)*(case cast(avg(19) AS integer) when ( -min(19)) then count(*) else count(*) end) |  -cast(avg(19) AS integer) from t1 union select cast(avg(b) AS integer) from t1) or t1.f>= -t1.d)}
} {}
do_test randexpr-2.1939 {
  db eval {SELECT f-coalesce((select max(d+~+ - -(a)*(select min(t1.d) from t1)*t1.f+case when ( -13)*t1.e<>11 &  -t1.e or c=11 then (t1.e) when  -t1.d<=t1.b and (t1.f<>t1.c) then a else  -t1.f end) from t1 where 11 not between t1.e and b),t1.f)-13 FROM t1 WHERE  -a not in (17+~coalesce((select t1.a from t1 where (exists(select 1 from t1 where 11>c))),11)+17-11,11,t1.c) or f in (select case (min((t1.a))) when max(b) then min(13) else cast(avg(c) AS integer) end*max(d)*(case cast(avg(19) AS integer) when ( -min(19)) then count(*) else count(*) end) |  -cast(avg(19) AS integer) from t1 union select cast(avg(b) AS integer) from t1) or t1.f>= -t1.d}
} {24239687}
do_test randexpr-2.1940 {
  db eval {SELECT ~case when ~coalesce((select max(f) from t1 where b | (select +max(13) from t1)+t1.b<~13*t1.d*coalesce((select  -t1.b from t1 where coalesce((select t1.e+a from t1 where 11=17),a) between 19 and e),17)*d),t1.b) in (select cast(avg(t1.d) AS integer) from t1 union select ~count(distinct 11) from t1) then 11 when t1.d>=t1.b then 13 else f end-t1.e FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case t1.b when  -t1.c then c-17 else case f when (abs(case when ((13*case  -e when case when b>c and 11>11 then  -a when  -(t1.c)>t1.e then d else t1.d end then t1.d else t1.e end<=11)) then ~t1.b+f when (d)<=c then t1.a else (t1.a) end+b)/abs(b)) then  -b else 11 end end-19 from t1 where t1.e<=t1.b),a)>t1.a)}
} {-514}
do_test randexpr-2.1941 {
  db eval {SELECT ~case when ~coalesce((select max(f) from t1 where b | (select +max(13) from t1)+t1.b<~13*t1.d*coalesce((select  -t1.b from t1 where coalesce((select t1.e+a from t1 where 11=17),a) between 19 and e),17)*d),t1.b) in (select cast(avg(t1.d) AS integer) from t1 union select ~count(distinct 11) from t1) then 11 when t1.d>=t1.b then 13 else f end-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select case t1.b when  -t1.c then c-17 else case f when (abs(case when ((13*case  -e when case when b>c and 11>11 then  -a when  -(t1.c)>t1.e then d else t1.d end then t1.d else t1.e end<=11)) then ~t1.b+f when (d)<=c then t1.a else (t1.a) end+b)/abs(b)) then  -b else 11 end end-19 from t1 where t1.e<=t1.b),a)>t1.a))}
} {}
do_test randexpr-2.1942 {
  db eval {SELECT ~case when ~coalesce((select max(f) from t1 where b & (select +max(13) from t1)+t1.b<~13*t1.d*coalesce((select  -t1.b from t1 where coalesce((select t1.e+a from t1 where 11=17),a) between 19 and e),17)*d),t1.b) in (select cast(avg(t1.d) AS integer) from t1 union select ~count(distinct 11) from t1) then 11 when t1.d>=t1.b then 13 else f end-t1.e FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case t1.b when  -t1.c then c-17 else case f when (abs(case when ((13*case  -e when case when b>c and 11>11 then  -a when  -(t1.c)>t1.e then d else t1.d end then t1.d else t1.e end<=11)) then ~t1.b+f when (d)<=c then t1.a else (t1.a) end+b)/abs(b)) then  -b else 11 end end-19 from t1 where t1.e<=t1.b),a)>t1.a)}
} {-514}
do_test randexpr-2.1943 {
  db eval {SELECT +(case when (not exists(select 1 from t1 where t1.c in (select +(abs(a)/abs( -coalesce((select max(17) from t1 where (not (c>=t1.d and t1.c>=f) and t1.e>e)),19-17))) from t1 union select case when (b)>d then d when c not in (f,t1.b,t1.d) then t1.f else t1.d end from t1) or a not in (t1.d,a, -b))) and exists(select 1 from t1 where b<11) then c when t1.c not between e and  -19 then t1.b else ~c end) FROM t1 WHERE t1.e*f-a- -13-b= -d}
} {}
do_test randexpr-2.1944 {
  db eval {SELECT +(case when (not exists(select 1 from t1 where t1.c in (select +(abs(a)/abs( -coalesce((select max(17) from t1 where (not (c>=t1.d and t1.c>=f) and t1.e>e)),19-17))) from t1 union select case when (b)>d then d when c not in (f,t1.b,t1.d) then t1.f else t1.d end from t1) or a not in (t1.d,a, -b))) and exists(select 1 from t1 where b<11) then c when t1.c not between e and  -19 then t1.b else ~c end) FROM t1 WHERE NOT (t1.e*f-a- -13-b= -d)}
} {200}
do_test randexpr-2.1945 {
  db eval {SELECT b-case when a not between t1.f and case when t1.d in (select count(*) from t1 union select cast(avg(coalesce((select +11*t1.e from t1 where e+b<case when 19 not in (t1.a | c,t1.a,f) then 13 when  -b<=17 then t1.e else a end),17)) AS integer) from t1) then 13 when not exists(select 1 from t1 where 13 between e and 17) or (a= -13) then t1.e else  -11 end then 11 else t1.a end FROM t1 WHERE not exists(select 1 from t1 where (e+17+t1.f)<=(case b when ~t1.f+(select +max(t1.f*case t1.b when +t1.f then t1.b else case when (not case when c=d then t1.c when t1.c<>b and t1.d between c and b then t1.d else t1.d end<t1.b) then t1.d when f<= -a then case when 17<c then a else a end else t1.e end end) from t1)*+t1.f then e else 17 end))}
} {189}
do_test randexpr-2.1946 {
  db eval {SELECT b-case when a not between t1.f and case when t1.d in (select count(*) from t1 union select cast(avg(coalesce((select +11*t1.e from t1 where e+b<case when 19 not in (t1.a | c,t1.a,f) then 13 when  -b<=17 then t1.e else a end),17)) AS integer) from t1) then 13 when not exists(select 1 from t1 where 13 between e and 17) or (a= -13) then t1.e else  -11 end then 11 else t1.a end FROM t1 WHERE NOT (not exists(select 1 from t1 where (e+17+t1.f)<=(case b when ~t1.f+(select +max(t1.f*case t1.b when +t1.f then t1.b else case when (not case when c=d then t1.c when t1.c<>b and t1.d between c and b then t1.d else t1.d end<t1.b) then t1.d when f<= -a then case when 17<c then a else a end else t1.e end end) from t1)*+t1.f then e else 17 end)))}
} {}
do_test randexpr-2.1947 {
  db eval {SELECT b-case when a not between t1.f and case when t1.d in (select count(*) from t1 union select cast(avg(coalesce((select +11*t1.e from t1 where e+b<case when 19 not in (t1.a & c,t1.a,f) then 13 when  -b<=17 then t1.e else a end),17)) AS integer) from t1) then 13 when not exists(select 1 from t1 where 13 between e and 17) or (a= -13) then t1.e else  -11 end then 11 else t1.a end FROM t1 WHERE not exists(select 1 from t1 where (e+17+t1.f)<=(case b when ~t1.f+(select +max(t1.f*case t1.b when +t1.f then t1.b else case when (not case when c=d then t1.c when t1.c<>b and t1.d between c and b then t1.d else t1.d end<t1.b) then t1.d when f<= -a then case when 17<c then a else a end else t1.e end end) from t1)*+t1.f then e else 17 end))}
} {189}
do_test randexpr-2.1948 {
  db eval {SELECT (select (min(coalesce((select max((case when t1.f<coalesce((select max(e+case when (t1.d in (select cast(avg(b) AS integer)+count(*) from t1 union select max(13) from t1)) then e*a else c end-t1.e) from t1 where (t1.c between b and t1.f and  -t1.b between  -t1.d and  -t1.a or c in (t1.b,t1.f,(f)))),13)+t1.c*19 then f else c end)) from t1 where  -t1.b not between t1.b and t1.c),11)-19))+count(distinct t1.e) from t1) FROM t1 WHERE  - -+t1.b*(19-t1.a | e*(select abs((count(distinct  -f+t1.d-11*t1.a))) from t1))*+(abs(c)/abs(t1.c))+t1.c*(t1.a)+case when b>=t1.d and 17<=13 or f between  -t1.c and 11 then case d when t1.c then 13 else t1.e end when (11)>b then a else c end in (t1.e,a,b)}
} {}
do_test randexpr-2.1949 {
  db eval {SELECT (select (min(coalesce((select max((case when t1.f<coalesce((select max(e+case when (t1.d in (select cast(avg(b) AS integer)+count(*) from t1 union select max(13) from t1)) then e*a else c end-t1.e) from t1 where (t1.c between b and t1.f and  -t1.b between  -t1.d and  -t1.a or c in (t1.b,t1.f,(f)))),13)+t1.c*19 then f else c end)) from t1 where  -t1.b not between t1.b and t1.c),11)-19))+count(distinct t1.e) from t1) FROM t1 WHERE NOT ( - -+t1.b*(19-t1.a | e*(select abs((count(distinct  -f+t1.d-11*t1.a))) from t1))*+(abs(c)/abs(t1.c))+t1.c*(t1.a)+case when b>=t1.d and 17<=13 or f between  -t1.c and 11 then case d when t1.c then 13 else t1.e end when (11)>b then a else c end in (t1.e,a,b))}
} {582}
do_test randexpr-2.1950 {
  db eval {SELECT coalesce((select max((abs(e)/abs(t1.a))) from t1 where (select (count(distinct ~ - -11- -t1.a-a*t1.d | 11-19+t1.f+17*c)-cast(avg(17) AS integer)+(cast(avg((19)) AS integer))) from t1)>a),17 | 11+17)+e-(c)-d-b FROM t1 WHERE (d>t1.d-case when case +(abs(t1.d | t1.f)/abs(t1.b)) when +b then coalesce((select max(t1.d | t1.c+(11+t1.d-t1.c)) from t1 where ((t1.e=17))),17) else t1.c end>=b then a else t1.f end) and (not (e<=c)) and not (t1.c<>b)}
} {}
do_test randexpr-2.1951 {
  db eval {SELECT coalesce((select max((abs(e)/abs(t1.a))) from t1 where (select (count(distinct ~ - -11- -t1.a-a*t1.d | 11-19+t1.f+17*c)-cast(avg(17) AS integer)+(cast(avg((19)) AS integer))) from t1)>a),17 | 11+17)+e-(c)-d-b FROM t1 WHERE NOT ((d>t1.d-case when case +(abs(t1.d | t1.f)/abs(t1.b)) when +b then coalesce((select max(t1.d | t1.c+(11+t1.d-t1.c)) from t1 where ((t1.e=17))),17) else t1.c end>=b then a else t1.f end) and (not (e<=c)) and not (t1.c<>b))}
} {-371}
do_test randexpr-2.1952 {
  db eval {SELECT coalesce((select max((abs(e)/abs(t1.a))) from t1 where (select (count(distinct ~ - -11- -t1.a-a*t1.d & 11-19+t1.f+17*c)-cast(avg(17) AS integer)+(cast(avg((19)) AS integer))) from t1)>a),17 & 11+17)+e-(c)-d-b FROM t1 WHERE NOT ((d>t1.d-case when case +(abs(t1.d | t1.f)/abs(t1.b)) when +b then coalesce((select max(t1.d | t1.c+(11+t1.d-t1.c)) from t1 where ((t1.e=17))),17) else t1.c end>=b then a else t1.f end) and (not (e<=c)) and not (t1.c<>b))}
} {-384}
do_test randexpr-2.1953 {
  db eval {SELECT coalesce((select c from t1 where case b when t1.a*(17) | case b++b when e then d else t1.b+f end+a+t1.d then d else t1.b | +e end<+~(select (count(*)) from t1)),17) FROM t1 WHERE (b+t1.c*c in (11, -t1.f,t1.b))}
} {}
do_test randexpr-2.1954 {
  db eval {SELECT coalesce((select c from t1 where case b when t1.a*(17) | case b++b when e then d else t1.b+f end+a+t1.d then d else t1.b | +e end<+~(select (count(*)) from t1)),17) FROM t1 WHERE NOT ((b+t1.c*c in (11, -t1.f,t1.b)))}
} {17}
do_test randexpr-2.1955 {
  db eval {SELECT coalesce((select c from t1 where case b when t1.a*(17) & case b++b when e then d else t1.b+f end+a+t1.d then d else t1.b & +e end<+~(select (count(*)) from t1)),17) FROM t1 WHERE NOT ((b+t1.c*c in (11, -t1.f,t1.b)))}
} {17}
do_test randexpr-2.1956 {
  db eval {SELECT case when coalesce((select max((abs(c)/abs(t1.d))) from t1 where t1.f*case when t1.a in (select (abs(17)/abs(c))*(t1.a) from t1 union select t1.e from t1) then t1.b else b end<19),e)+a-d in (select case max(t1.b)-count(distinct t1.c) when +case abs(cast(avg(t1.f) AS integer)) when +cast(avg(f) AS integer)-min(f) then count(distinct c) else cast(avg(d) AS integer) end then count(distinct t1.a) else cast(avg(b) AS integer) end from t1 union select count(distinct t1.e) from t1) then t1.c else f end FROM t1 WHERE ((19 in (t1.b,case t1.f when 11 then 11 else  -+t1.b | 19 end+coalesce((select 11 from t1 where c<=t1.c* -e),f),t1.f)) or (b between t1.b and 17) or not exists(select 1 from t1 where  -17 between  -f and t1.e or (not b<>11) and 19 in (select 11 from t1 union select t1.b from t1))) or 13>(t1.e)}
} {}
do_test randexpr-2.1957 {
  db eval {SELECT case when coalesce((select max((abs(c)/abs(t1.d))) from t1 where t1.f*case when t1.a in (select (abs(17)/abs(c))*(t1.a) from t1 union select t1.e from t1) then t1.b else b end<19),e)+a-d in (select case max(t1.b)-count(distinct t1.c) when +case abs(cast(avg(t1.f) AS integer)) when +cast(avg(f) AS integer)-min(f) then count(distinct c) else cast(avg(d) AS integer) end then count(distinct t1.a) else cast(avg(b) AS integer) end from t1 union select count(distinct t1.e) from t1) then t1.c else f end FROM t1 WHERE NOT (((19 in (t1.b,case t1.f when 11 then 11 else  -+t1.b | 19 end+coalesce((select 11 from t1 where c<=t1.c* -e),f),t1.f)) or (b between t1.b and 17) or not exists(select 1 from t1 where  -17 between  -f and t1.e or (not b<>11) and 19 in (select 11 from t1 union select t1.b from t1))) or 13>(t1.e))}
} {300}
do_test randexpr-2.1958 {
  db eval {SELECT f+case when e>+11+t1.e or ~t1.a=f+t1.e+t1.c then t1.a+case when b*coalesce((select max(a) from t1 where not exists(select 1 from t1 where (t1.f=case when exists(select 1 from t1 where t1.f<b) then f when 19<13 then t1.e else f end))),coalesce((select max(11) from t1 where (t1.d) between t1.c and  - -f and d<>f),11))<(e) then t1.e else 19 end+(c) else t1.a end*c-t1.c FROM t1 WHERE not ~coalesce((select max(t1.f*coalesce((select max(f) from t1 where case 17 when e*19 then case t1.a when 17 then f else t1.c+t1.d end | (e) else ~a end>=e or not t1.b in (select a from t1 union select d from t1)),19)) from t1 where e>coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.c=t1.a)),case t1.b when t1.b then a else 19 end)),13)*t1.b not between t1.e and t1.e}
} {}
do_test randexpr-2.1959 {
  db eval {SELECT f+case when e>+11+t1.e or ~t1.a=f+t1.e+t1.c then t1.a+case when b*coalesce((select max(a) from t1 where not exists(select 1 from t1 where (t1.f=case when exists(select 1 from t1 where t1.f<b) then f when 19<13 then t1.e else f end))),coalesce((select max(11) from t1 where (t1.d) between t1.c and  - -f and d<>f),11))<(e) then t1.e else 19 end+(c) else t1.a end*c-t1.c FROM t1 WHERE NOT (not ~coalesce((select max(t1.f*coalesce((select max(f) from t1 where case 17 when e*19 then case t1.a when 17 then f else t1.c+t1.d end | (e) else ~a end>=e or not t1.b in (select a from t1 union select d from t1)),19)) from t1 where e>coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.c=t1.a)),case t1.b when t1.b then a else 19 end)),13)*t1.b not between t1.e and t1.e)}
} {30300}
do_test randexpr-2.1960 {
  db eval {SELECT e*(select  -max((case when  -case when (+(abs(f)/abs(17))*13)> -a then 17 else f end |  -t1.f-e*11<>11 then c when exists(select 1 from t1 where not exists(select 1 from t1 where t1.b not in (t1.d,19,d) and t1.d<>11)) or 13<= -t1.f then 11 else d end-t1.a)*e) from t1) FROM t1 WHERE exists(select 1 from t1 where c<>a)}
} {-50000000}
do_test randexpr-2.1961 {
  db eval {SELECT e*(select  -max((case when  -case when (+(abs(f)/abs(17))*13)> -a then 17 else f end |  -t1.f-e*11<>11 then c when exists(select 1 from t1 where not exists(select 1 from t1 where t1.b not in (t1.d,19,d) and t1.d<>11)) or 13<= -t1.f then 11 else d end-t1.a)*e) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where c<>a))}
} {}
do_test randexpr-2.1962 {
  db eval {SELECT e*(select  -max((case when  -case when (+(abs(f)/abs(17))*13)> -a then 17 else f end &  -t1.f-e*11<>11 then c when exists(select 1 from t1 where not exists(select 1 from t1 where t1.b not in (t1.d,19,d) and t1.d<>11)) or 13<= -t1.f then 11 else d end-t1.a)*e) from t1) FROM t1 WHERE exists(select 1 from t1 where c<>a)}
} {-50000000}
do_test randexpr-2.1963 {
  db eval {SELECT a-t1.b | (case case when 13 in (t1.c,(t1.c),t1.e) then e+b when b in (select e from t1 union select d from t1) then (select count(distinct (abs(case when t1.e not between c and c then f else case t1.a when t1.c then e+t1.d else c end end)/abs(b))) from t1) else t1.b- -t1.d end when t1.c then 11 else e end- -a)+d-t1.b FROM t1 WHERE (case when f between f+(abs(coalesce((select t1.c*t1.c from t1 where f between 19 and (select count(distinct coalesce((select max(case case when t1.b<>t1.c then t1.d when 19<d then t1.c else d end | 19-17 when b then 11 else f end) from t1 where c in (select 11 from t1 union select t1.e from t1)),e)) from t1)),13))/abs(19)) and (e) then c when 17 in ((c),t1.e,f) and a in (select 19 from t1 union select t1.e from t1) then t1.f else 13 end<13)}
} {}
do_test randexpr-2.1964 {
  db eval {SELECT a-t1.b | (case case when 13 in (t1.c,(t1.c),t1.e) then e+b when b in (select e from t1 union select d from t1) then (select count(distinct (abs(case when t1.e not between c and c then f else case t1.a when t1.c then e+t1.d else c end end)/abs(b))) from t1) else t1.b- -t1.d end when t1.c then 11 else e end- -a)+d-t1.b FROM t1 WHERE NOT ((case when f between f+(abs(coalesce((select t1.c*t1.c from t1 where f between 19 and (select count(distinct coalesce((select max(case case when t1.b<>t1.c then t1.d when 19<d then t1.c else d end | 19-17 when b then 11 else f end) from t1 where c in (select 11 from t1 union select t1.e from t1)),e)) from t1)),13))/abs(19)) and (e) then c when 17 in ((c),t1.e,f) and a in (select 19 from t1 union select t1.e from t1) then t1.f else 13 end<13))}
} {-68}
do_test randexpr-2.1965 {
  db eval {SELECT a-t1.b & (case case when 13 in (t1.c,(t1.c),t1.e) then e+b when b in (select e from t1 union select d from t1) then (select count(distinct (abs(case when t1.e not between c and c then f else case t1.a when t1.c then e+t1.d else c end end)/abs(b))) from t1) else t1.b- -t1.d end when t1.c then 11 else e end- -a)+d-t1.b FROM t1 WHERE NOT ((case when f between f+(abs(coalesce((select t1.c*t1.c from t1 where f between 19 and (select count(distinct coalesce((select max(case case when t1.b<>t1.c then t1.d when 19<d then t1.c else d end | 19-17 when b then 11 else f end) from t1 where c in (select 11 from t1 union select t1.e from t1)),e)) from t1)),13))/abs(19)) and (e) then c when 17 in ((c),t1.e,f) and a in (select 19 from t1 union select t1.e from t1) then t1.f else 13 end<13))}
} {768}
do_test randexpr-2.1966 {
  db eval {SELECT (abs(case t1.f | d when coalesce((select max(~b) from t1 where +t1.a<> -case t1.f when +b-case when (17 in (select count(distinct b)+count(distinct t1.a) from t1 union select count(distinct 13) from t1)) then d else 13 end+t1.d | d* -11+t1.d*t1.f | a-17 then 13 else c end*t1.e),d) then t1.b else d end)/abs(t1.a))*19 FROM t1 WHERE t1.f in (select count(*) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.1967 {
  db eval {SELECT (abs(case t1.f | d when coalesce((select max(~b) from t1 where +t1.a<> -case t1.f when +b-case when (17 in (select count(distinct b)+count(distinct t1.a) from t1 union select count(distinct 13) from t1)) then d else 13 end+t1.d | d* -11+t1.d*t1.f | a-17 then 13 else c end*t1.e),d) then t1.b else d end)/abs(t1.a))*19 FROM t1 WHERE NOT (t1.f in (select count(*) from t1 union select count(*) from t1))}
} {76}
do_test randexpr-2.1968 {
  db eval {SELECT (abs(case t1.f & d when coalesce((select max(~b) from t1 where +t1.a<> -case t1.f when +b-case when (17 in (select count(distinct b)+count(distinct t1.a) from t1 union select count(distinct 13) from t1)) then d else 13 end+t1.d & d* -11+t1.d*t1.f & a-17 then 13 else c end*t1.e),d) then t1.b else d end)/abs(t1.a))*19 FROM t1 WHERE NOT (t1.f in (select count(*) from t1 union select count(*) from t1))}
} {76}
do_test randexpr-2.1969 {
  db eval {SELECT t1.d+coalesce((select max(t1.b*t1.b | ~case a | c | t1.d when t1.c then t1.a else t1.e end | e-13*b) from t1 where  -t1.a in (select e from t1 union select t1.b from t1) and not exists(select 1 from t1 where (a) in (select min(13)* -cast(avg(t1.e) AS integer)*~case count(*) when count(*) then ((cast(avg(e) AS integer))) else count(*) end | (min(t1.e)) |  -count(*) from t1 union select max(t1.a) from t1))), -t1.b)+a FROM t1 WHERE not exists(select 1 from t1 where 11*d+a>=(t1.a-e+17*(select +cast(avg((select cast(avg((abs(case when (abs(t1.a)/abs(coalesce((select max(c+t1.e) from t1 where not exists(select 1 from t1 where 13 in (select  -t1.c from t1 union select t1.f from t1))),17) | e*e)) not between e and t1.f then 19 else t1.b end)/abs(19))) AS integer)* -count(*) from t1)) AS integer)*count(distinct 11)-abs(cast(avg(b) AS integer)) from t1)))}
} {}
do_test randexpr-2.1970 {
  db eval {SELECT t1.d+coalesce((select max(t1.b*t1.b | ~case a | c | t1.d when t1.c then t1.a else t1.e end | e-13*b) from t1 where  -t1.a in (select e from t1 union select t1.b from t1) and not exists(select 1 from t1 where (a) in (select min(13)* -cast(avg(t1.e) AS integer)*~case count(*) when count(*) then ((cast(avg(e) AS integer))) else count(*) end | (min(t1.e)) |  -count(*) from t1 union select max(t1.a) from t1))), -t1.b)+a FROM t1 WHERE NOT (not exists(select 1 from t1 where 11*d+a>=(t1.a-e+17*(select +cast(avg((select cast(avg((abs(case when (abs(t1.a)/abs(coalesce((select max(c+t1.e) from t1 where not exists(select 1 from t1 where 13 in (select  -t1.c from t1 union select t1.f from t1))),17) | e*e)) not between e and t1.f then 19 else t1.b end)/abs(19))) AS integer)* -count(*) from t1)) AS integer)*count(distinct 11)-abs(cast(avg(b) AS integer)) from t1))))}
} {300}
do_test randexpr-2.1971 {
  db eval {SELECT t1.d+coalesce((select max(t1.b*t1.b & ~case a & c & t1.d when t1.c then t1.a else t1.e end & e-13*b) from t1 where  -t1.a in (select e from t1 union select t1.b from t1) and not exists(select 1 from t1 where (a) in (select min(13)* -cast(avg(t1.e) AS integer)*~case count(*) when count(*) then ((cast(avg(e) AS integer))) else count(*) end & (min(t1.e)) &  -count(*) from t1 union select max(t1.a) from t1))), -t1.b)+a FROM t1 WHERE NOT (not exists(select 1 from t1 where 11*d+a>=(t1.a-e+17*(select +cast(avg((select cast(avg((abs(case when (abs(t1.a)/abs(coalesce((select max(c+t1.e) from t1 where not exists(select 1 from t1 where 13 in (select  -t1.c from t1 union select t1.f from t1))),17) | e*e)) not between e and t1.f then 19 else t1.b end)/abs(19))) AS integer)* -count(*) from t1)) AS integer)*count(distinct 11)-abs(cast(avg(b) AS integer)) from t1))))}
} {300}
do_test randexpr-2.1972 {
  db eval {SELECT ~case when case when +d+case b when 11 then coalesce((select max(b) from t1 where (((abs(f)/abs((abs(11)/abs(e))+t1.b))>t1.f))),(select max(t1.e) from t1)) else t1.f end*t1.f*17>=(t1.e) or 17>t1.f then t1.a else t1.a end in (c,13,c) then t1.f when t1.a not in (t1.d, -t1.b,a) then  -t1.b else 11 end FROM t1 WHERE t1.a in (+e,17,11*13) and b not between t1.f*(abs(t1.c-((abs(t1.a | coalesce((select max(case when  -f-t1.c<=t1.f then 19 when (t1.a)<>t1.f and 13 between a and t1.e then  -11 else 17 end) from t1 where c>19),f)-t1.e)/abs(e))))/abs(b))-t1.e | (19) and  -t1.a and t1.f in (select 13 from t1 union select a from t1)}
} {}
do_test randexpr-2.1973 {
  db eval {SELECT ~case when case when +d+case b when 11 then coalesce((select max(b) from t1 where (((abs(f)/abs((abs(11)/abs(e))+t1.b))>t1.f))),(select max(t1.e) from t1)) else t1.f end*t1.f*17>=(t1.e) or 17>t1.f then t1.a else t1.a end in (c,13,c) then t1.f when t1.a not in (t1.d, -t1.b,a) then  -t1.b else 11 end FROM t1 WHERE NOT (t1.a in (+e,17,11*13) and b not between t1.f*(abs(t1.c-((abs(t1.a | coalesce((select max(case when  -f-t1.c<=t1.f then 19 when (t1.a)<>t1.f and 13 between a and t1.e then  -11 else 17 end) from t1 where c>19),f)-t1.e)/abs(e))))/abs(b))-t1.e | (19) and  -t1.a and t1.f in (select 13 from t1 union select a from t1))}
} {-12}
do_test randexpr-2.1974 {
  db eval {SELECT case when case 17 when case when (abs(t1.c)/abs(t1.c | coalesce((select max(t1.d) from t1 where not t1.e<17 or 11 not in (t1.a,t1.c,a) or c=d and (t1.b)<f and t1.c>=t1.e and 17 in ( -t1.c,a,d) and t1.f not in (19,a,b)),11) | (select  -max(+t1.b) from t1)+19-19 | f))<>t1.a or e>17 then f else a end then 11 else f end=t1.a then f else  -t1.f end FROM t1 WHERE  -t1.b+a>= -t1.a}
} {-600}
do_test randexpr-2.1975 {
  db eval {SELECT case when case 17 when case when (abs(t1.c)/abs(t1.c | coalesce((select max(t1.d) from t1 where not t1.e<17 or 11 not in (t1.a,t1.c,a) or c=d and (t1.b)<f and t1.c>=t1.e and 17 in ( -t1.c,a,d) and t1.f not in (19,a,b)),11) | (select  -max(+t1.b) from t1)+19-19 | f))<>t1.a or e>17 then f else a end then 11 else f end=t1.a then f else  -t1.f end FROM t1 WHERE NOT ( -t1.b+a>= -t1.a)}
} {}
do_test randexpr-2.1976 {
  db eval {SELECT (abs(coalesce((select ((t1.c)) from t1 where not exists(select 1 from t1 where t1.e*17<13*coalesce((select max(a) from t1 where 19 in (select max(e*11) from t1 union select cast(avg(t1.b) AS integer) from t1)),a | a))),case when f-13<d+17 and not exists(select 1 from t1 where e<= -13) or a between e and d then case t1.a when t1.b then f else t1.f end when  - -t1.f<>t1.e then t1.b else f end))/abs(17)) FROM t1 WHERE ((d not between  -a and b))}
} {17}
do_test randexpr-2.1977 {
  db eval {SELECT (abs(coalesce((select ((t1.c)) from t1 where not exists(select 1 from t1 where t1.e*17<13*coalesce((select max(a) from t1 where 19 in (select max(e*11) from t1 union select cast(avg(t1.b) AS integer) from t1)),a | a))),case when f-13<d+17 and not exists(select 1 from t1 where e<= -13) or a between e and d then case t1.a when t1.b then f else t1.f end when  - -t1.f<>t1.e then t1.b else f end))/abs(17)) FROM t1 WHERE NOT (((d not between  -a and b)))}
} {}
do_test randexpr-2.1978 {
  db eval {SELECT (abs(coalesce((select ((t1.c)) from t1 where not exists(select 1 from t1 where t1.e*17<13*coalesce((select max(a) from t1 where 19 in (select max(e*11) from t1 union select cast(avg(t1.b) AS integer) from t1)),a & a))),case when f-13<d+17 and not exists(select 1 from t1 where e<= -13) or a between e and d then case t1.a when t1.b then f else t1.f end when  - -t1.f<>t1.e then t1.b else f end))/abs(17)) FROM t1 WHERE ((d not between  -a and b))}
} {17}
do_test randexpr-2.1979 {
  db eval {SELECT case f when (d)-case when coalesce((select max(coalesce((select 11 from t1 where case when (t1.f<=17 or exists(select 1 from t1 where 11 | d in (select (abs(max(t1.f))) from t1 union select ( -min(c)) from t1))) then a when t1.f not in (e,13,13) then t1.c else e end between 19 and c),t1.a)) from t1 where f>=t1.d),17) not between e and t1.c and 11<=17 then t1.e-19 when t1.a not in (c,t1.e,t1.c) then 11 else t1.b end then t1.e else t1.f end FROM t1 WHERE (not (case 17 when d then t1.c else c end=f | (select case count(*) when count(*)++max(11)+ -(abs(+cast(avg(c) AS integer)-(~count(*))+count(*)*(~case max( -c) when  - -cast(avg(t1.f) AS integer) then (count(*)) else  -max(t1.b) end*cast(avg(a) AS integer))-count(*) | ( -( -max(11)))) | ( -min(17))+count(*)) then (max(19)) else max(t1.c) end from t1)))}
} {600}
do_test randexpr-2.1980 {
  db eval {SELECT case f when (d)-case when coalesce((select max(coalesce((select 11 from t1 where case when (t1.f<=17 or exists(select 1 from t1 where 11 | d in (select (abs(max(t1.f))) from t1 union select ( -min(c)) from t1))) then a when t1.f not in (e,13,13) then t1.c else e end between 19 and c),t1.a)) from t1 where f>=t1.d),17) not between e and t1.c and 11<=17 then t1.e-19 when t1.a not in (c,t1.e,t1.c) then 11 else t1.b end then t1.e else t1.f end FROM t1 WHERE NOT ((not (case 17 when d then t1.c else c end=f | (select case count(*) when count(*)++max(11)+ -(abs(+cast(avg(c) AS integer)-(~count(*))+count(*)*(~case max( -c) when  - -cast(avg(t1.f) AS integer) then (count(*)) else  -max(t1.b) end*cast(avg(a) AS integer))-count(*) | ( -( -max(11)))) | ( -min(17))+count(*)) then (max(19)) else max(t1.c) end from t1))))}
} {}
do_test randexpr-2.1981 {
  db eval {SELECT case f when (d)-case when coalesce((select max(coalesce((select 11 from t1 where case when (t1.f<=17 or exists(select 1 from t1 where 11 & d in (select (abs(max(t1.f))) from t1 union select ( -min(c)) from t1))) then a when t1.f not in (e,13,13) then t1.c else e end between 19 and c),t1.a)) from t1 where f>=t1.d),17) not between e and t1.c and 11<=17 then t1.e-19 when t1.a not in (c,t1.e,t1.c) then 11 else t1.b end then t1.e else t1.f end FROM t1 WHERE (not (case 17 when d then t1.c else c end=f | (select case count(*) when count(*)++max(11)+ -(abs(+cast(avg(c) AS integer)-(~count(*))+count(*)*(~case max( -c) when  - -cast(avg(t1.f) AS integer) then (count(*)) else  -max(t1.b) end*cast(avg(a) AS integer))-count(*) | ( -( -max(11)))) | ( -min(17))+count(*)) then (max(19)) else max(t1.c) end from t1)))}
} {600}
do_test randexpr-2.1982 {
  db eval {SELECT case when d+t1.d not between t1.f and + -t1.c then ~+a+(select +count(*) from t1) else (select +abs(count(*)) from t1)-t1.a end FROM t1 WHERE t1.b+f | d+a in (select +cast(avg(b) AS integer)++case min(coalesce((select t1.c from t1 where (e) in ((a)+17,t1.b,d)),t1.f)) when ~~cast(avg(17) AS integer)-max((t1.a)) then case min(13) when count(*) then count(distinct t1.a) else cast(avg(b) AS integer) end*max(d)+max(t1.b) else  -count(*) end-count(*) from t1 union select cast(avg(t1.f) AS integer) from t1)}
} {}
do_test randexpr-2.1983 {
  db eval {SELECT case when d+t1.d not between t1.f and + -t1.c then ~+a+(select +count(*) from t1) else (select +abs(count(*)) from t1)-t1.a end FROM t1 WHERE NOT (t1.b+f | d+a in (select +cast(avg(b) AS integer)++case min(coalesce((select t1.c from t1 where (e) in ((a)+17,t1.b,d)),t1.f)) when ~~cast(avg(17) AS integer)-max((t1.a)) then case min(13) when count(*) then count(distinct t1.a) else cast(avg(b) AS integer) end*max(d)+max(t1.b) else  -count(*) end-count(*) from t1 union select cast(avg(t1.f) AS integer) from t1))}
} {-100}
do_test randexpr-2.1984 {
  db eval {SELECT case when case when case case when (case when (( -f<t1.a)) and a between t1.b and 17 then c else +t1.c end-f+11+e between (17) and a) then t1.d else f end+t1.e*11-11 when  -11 then 17 else f end in (select t1.d from t1 union select b from t1) then c when t1.d<=(a) then t1.e else  -f end<t1.d then a else 11 end-19*f FROM t1 WHERE t1.b in (case +t1.f | d*~(case when b not between c and e+t1.d-coalesce((select  -t1.f* -t1.c from t1 where (f in (select t1.d from t1 union select  -t1.d from t1))),t1.b) then t1.c when not exists(select 1 from t1 where a<>t1.c or exists(select 1 from t1 where not exists(select 1 from t1 where (a not between b and  -t1.e)) and t1.f>=(t1.a)) and t1.f<(t1.b)) then 19 else e end) when a then t1.e else 11 end,(a),19)}
} {}
do_test randexpr-2.1985 {
  db eval {SELECT case when case when case case when (case when (( -f<t1.a)) and a between t1.b and 17 then c else +t1.c end-f+11+e between (17) and a) then t1.d else f end+t1.e*11-11 when  -11 then 17 else f end in (select t1.d from t1 union select b from t1) then c when t1.d<=(a) then t1.e else  -f end<t1.d then a else 11 end-19*f FROM t1 WHERE NOT (t1.b in (case +t1.f | d*~(case when b not between c and e+t1.d-coalesce((select  -t1.f* -t1.c from t1 where (f in (select t1.d from t1 union select  -t1.d from t1))),t1.b) then t1.c when not exists(select 1 from t1 where a<>t1.c or exists(select 1 from t1 where not exists(select 1 from t1 where (a not between b and  -t1.e)) and t1.f>=(t1.a)) and t1.f<(t1.b)) then 19 else e end) when a then t1.e else 11 end,(a),19))}
} {-11300}
do_test randexpr-2.1986 {
  db eval {SELECT coalesce((select 11 from t1 where 19 in (select ((count(*)*min(11)*(abs(max(a)))-max(b)*+count(*))) from t1 union select case abs(abs(min(t1.b))*case count(distinct b) when count(distinct t1.a) then count(distinct t1.f-t1.f) else max(11) end) when cast(avg(e) AS integer) then count(*) else count(*) end from t1)),d)*11+t1.c+b | 13+19 FROM t1 WHERE t1.c in (select 19 from t1 union select ~t1.f-t1.f+17- -17 from t1)}
} {}
do_test randexpr-2.1987 {
  db eval {SELECT coalesce((select 11 from t1 where 19 in (select ((count(*)*min(11)*(abs(max(a)))-max(b)*+count(*))) from t1 union select case abs(abs(min(t1.b))*case count(distinct b) when count(distinct t1.a) then count(distinct t1.f-t1.f) else max(11) end) when cast(avg(e) AS integer) then count(*) else count(*) end from t1)),d)*11+t1.c+b | 13+19 FROM t1 WHERE NOT (t1.c in (select 19 from t1 union select ~t1.f-t1.f+17- -17 from t1))}
} {4900}
do_test randexpr-2.1988 {
  db eval {SELECT coalesce((select 11 from t1 where 19 in (select ((count(*)*min(11)*(abs(max(a)))-max(b)*+count(*))) from t1 union select case abs(abs(min(t1.b))*case count(distinct b) when count(distinct t1.a) then count(distinct t1.f-t1.f) else max(11) end) when cast(avg(e) AS integer) then count(*) else count(*) end from t1)),d)*11+t1.c+b & 13+19 FROM t1 WHERE NOT (t1.c in (select 19 from t1 union select ~t1.f-t1.f+17- -17 from t1))}
} {32}
do_test randexpr-2.1989 {
  db eval {SELECT case f when (select ++abs(max(d))+case case count(*) when min(t1.c) then (count(*)) else min(t1.e) end when  -count(distinct t1.e) then count(distinct a) else min(t1.b) end from t1) then coalesce((select case when e in (select d from t1 union select f from t1) and t1.a not between b and 13 and d in (select 17 from t1 union select b from t1) then 17 when 11=f then 19 else d end from t1 where 11 not in (t1.c,t1.c,t1.d)),a) else e end-t1.e-t1.d-17*t1.f FROM t1 WHERE case when coalesce((select max(c) from t1 where 19 not between 11 and t1.e and t1.b in (select count(*) from t1 union select ~min(case c when (abs(case when d=( -t1.e) or t1.b<>t1.f then b else t1.b end)/abs(t1.c))+19 then t1.f else d end) from t1) and  -b in (select min(17) from t1 union select min( -c) | count(distinct 17)- -(count(*))+max(t1.c) |  -cast(avg(t1.c) AS integer) from t1)),t1.c)*t1.f not between  -t1.e and t1.f then 11 else f end>f}
} {}
do_test randexpr-2.1990 {
  db eval {SELECT case f when (select ++abs(max(d))+case case count(*) when min(t1.c) then (count(*)) else min(t1.e) end when  -count(distinct t1.e) then count(distinct a) else min(t1.b) end from t1) then coalesce((select case when e in (select d from t1 union select f from t1) and t1.a not between b and 13 and d in (select 17 from t1 union select b from t1) then 17 when 11=f then 19 else d end from t1 where 11 not in (t1.c,t1.c,t1.d)),a) else e end-t1.e-t1.d-17*t1.f FROM t1 WHERE NOT (case when coalesce((select max(c) from t1 where 19 not between 11 and t1.e and t1.b in (select count(*) from t1 union select ~min(case c when (abs(case when d=( -t1.e) or t1.b<>t1.f then b else t1.b end)/abs(t1.c))+19 then t1.f else d end) from t1) and  -b in (select min(17) from t1 union select min( -c) | count(distinct 17)- -(count(*))+max(t1.c) |  -cast(avg(t1.c) AS integer) from t1)),t1.c)*t1.f not between  -t1.e and t1.f then 11 else f end>f)}
} {-10700}
do_test randexpr-2.1991 {
  db eval {SELECT case when ((coalesce((select t1.a from t1 where exists(select 1 from t1 where t1.a<=t1.b-e*coalesce((select max(a) from t1 where t1.e in (select min(13+13) from t1 union select  -(count(distinct t1.f)-count(*)) from t1)),17)-f-t1.f) or t1.d in (select t1.a from t1 union select b from t1)),t1.d*t1.f)<>a)) then t1.d when not exists(select 1 from t1 where ((t1.f in (c,19,f)))) then t1.f else 17 end FROM t1 WHERE t1.c<=a}
} {}
do_test randexpr-2.1992 {
  db eval {SELECT case when ((coalesce((select t1.a from t1 where exists(select 1 from t1 where t1.a<=t1.b-e*coalesce((select max(a) from t1 where t1.e in (select min(13+13) from t1 union select  -(count(distinct t1.f)-count(*)) from t1)),17)-f-t1.f) or t1.d in (select t1.a from t1 union select b from t1)),t1.d*t1.f)<>a)) then t1.d when not exists(select 1 from t1 where ((t1.f in (c,19,f)))) then t1.f else 17 end FROM t1 WHERE NOT (t1.c<=a)}
} {400}
do_test randexpr-2.1993 {
  db eval {SELECT case 17 when t1.f then 11 else (case when (c between case when ~t1.e+13-t1.c+case coalesce((select t1.c from t1 where t1.a not between a and 17),coalesce((select max(case when exists(select 1 from t1 where a>=t1.a) then ((t1.e)) when t1.e>=11 then 17 else t1.b end) from t1 where ( -11<e)),a)*t1.c) when t1.f then t1.d else b end | 13<t1.d then f else t1.f end and e) then case t1.b when t1.b then  -t1.c else 17 end else t1.b end) end FROM t1 WHERE d- -coalesce((select max( -(17)+(t1.d)* -coalesce((select max(+d) from t1 where case when t1.e between 19 and t1.d then a when t1.d between t1.e and 17 then e else t1.c end+13 between a and t1.b or (c) in (select t1.b from t1 union select a from t1) or 11<>d),t1.c) | b- -17-(17)*c) from t1 where (19<13)),t1.c) not between a and t1.a}
} {200}
do_test randexpr-2.1994 {
  db eval {SELECT case 17 when t1.f then 11 else (case when (c between case when ~t1.e+13-t1.c+case coalesce((select t1.c from t1 where t1.a not between a and 17),coalesce((select max(case when exists(select 1 from t1 where a>=t1.a) then ((t1.e)) when t1.e>=11 then 17 else t1.b end) from t1 where ( -11<e)),a)*t1.c) when t1.f then t1.d else b end | 13<t1.d then f else t1.f end and e) then case t1.b when t1.b then  -t1.c else 17 end else t1.b end) end FROM t1 WHERE NOT (d- -coalesce((select max( -(17)+(t1.d)* -coalesce((select max(+d) from t1 where case when t1.e between 19 and t1.d then a when t1.d between t1.e and 17 then e else t1.c end+13 between a and t1.b or (c) in (select t1.b from t1 union select a from t1) or 11<>d),t1.c) | b- -17-(17)*c) from t1 where (19<13)),t1.c) not between a and t1.a)}
} {}
do_test randexpr-2.1995 {
  db eval {SELECT case 17 when t1.f then 11 else (case when (c between case when ~t1.e+13-t1.c+case coalesce((select t1.c from t1 where t1.a not between a and 17),coalesce((select max(case when exists(select 1 from t1 where a>=t1.a) then ((t1.e)) when t1.e>=11 then 17 else t1.b end) from t1 where ( -11<e)),a)*t1.c) when t1.f then t1.d else b end & 13<t1.d then f else t1.f end and e) then case t1.b when t1.b then  -t1.c else 17 end else t1.b end) end FROM t1 WHERE d- -coalesce((select max( -(17)+(t1.d)* -coalesce((select max(+d) from t1 where case when t1.e between 19 and t1.d then a when t1.d between t1.e and 17 then e else t1.c end+13 between a and t1.b or (c) in (select t1.b from t1 union select a from t1) or 11<>d),t1.c) | b- -17-(17)*c) from t1 where (19<13)),t1.c) not between a and t1.a}
} {200}
do_test randexpr-2.1996 {
  db eval {SELECT 17+(select case ~max((abs(t1.c+coalesce((select max(t1.f) from t1 where t1.f in (select 13-c-case when not a>=t1.c then f else t1.c end+t1.c from t1 union select 19 from t1) or exists(select 1 from t1 where 13<t1.e)),17)*(19))/abs(b))) when ~abs( -+max(t1.a)) then +abs(cast(avg(t1.e) AS integer)) | ~abs(~cast(avg(b) AS integer)) else cast(avg(t1.f) AS integer) end from t1) | t1.d FROM t1 WHERE (case when case when 13<>17 | e*d-17*t1.e*case a when case when (not f>=19 and t1.f<=t1.b) then coalesce((select case 11 when  -c then t1.f else (t1.f) end from t1 where 13 between t1.e and t1.f),(e)) when  -t1.f not between b and d then t1.d else t1.a end then 11 else 19 end then d when a<t1.d then 19 else 11 end=t1.e then t1.a else t1.d end+f>d)}
} {1017}
do_test randexpr-2.1997 {
  db eval {SELECT 17+(select case ~max((abs(t1.c+coalesce((select max(t1.f) from t1 where t1.f in (select 13-c-case when not a>=t1.c then f else t1.c end+t1.c from t1 union select 19 from t1) or exists(select 1 from t1 where 13<t1.e)),17)*(19))/abs(b))) when ~abs( -+max(t1.a)) then +abs(cast(avg(t1.e) AS integer)) | ~abs(~cast(avg(b) AS integer)) else cast(avg(t1.f) AS integer) end from t1) | t1.d FROM t1 WHERE NOT ((case when case when 13<>17 | e*d-17*t1.e*case a when case when (not f>=19 and t1.f<=t1.b) then coalesce((select case 11 when  -c then t1.f else (t1.f) end from t1 where 13 between t1.e and t1.f),(e)) when  -t1.f not between b and d then t1.d else t1.a end then 11 else 19 end then d when a<t1.d then 19 else 11 end=t1.e then t1.a else t1.d end+f>d))}
} {}
do_test randexpr-2.1998 {
  db eval {SELECT 17+(select case ~max((abs(t1.c+coalesce((select max(t1.f) from t1 where t1.f in (select 13-c-case when not a>=t1.c then f else t1.c end+t1.c from t1 union select 19 from t1) or exists(select 1 from t1 where 13<t1.e)),17)*(19))/abs(b))) when ~abs( -+max(t1.a)) then +abs(cast(avg(t1.e) AS integer)) & ~abs(~cast(avg(b) AS integer)) else cast(avg(t1.f) AS integer) end from t1) & t1.d FROM t1 WHERE (case when case when 13<>17 | e*d-17*t1.e*case a when case when (not f>=19 and t1.f<=t1.b) then coalesce((select case 11 when  -c then t1.f else (t1.f) end from t1 where 13 between t1.e and t1.f),(e)) when  -t1.f not between b and d then t1.d else t1.a end then 11 else 19 end then d when a<t1.d then 19 else 11 end=t1.e then t1.a else t1.d end+f>d)}
} {0}
do_test randexpr-2.1999 {
  db eval {SELECT ~c-t1.a*case  -case 19 when d then t1.f else t1.a end-d when 11 then coalesce((select max(case when (case when exists(select 1 from t1 where 11*11>13) then t1.c else 11 end)<=(select min(~d+case 19 when e then 13 else e end) from t1) then c when ((f))<=17 then d else t1.c end+t1.f) from t1 where (t1.b between  -c and t1.e)),t1.e) else 17 end FROM t1 WHERE +(abs(d-(select cast(avg((select (abs(max(t1.d*+d*( -e*(13)) | 17)+ -min(t1.d)+~ - -max(17) | max(t1.a) |  -count(distinct t1.a)-count(distinct 13)*(count(distinct t1.a)) | (count(distinct 17)))) from t1)) AS integer) from t1)-11)/abs(c+d-t1.e))>=t1.d}
} {}
do_test randexpr-2.2000 {
  db eval {SELECT ~c-t1.a*case  -case 19 when d then t1.f else t1.a end-d when 11 then coalesce((select max(case when (case when exists(select 1 from t1 where 11*11>13) then t1.c else 11 end)<=(select min(~d+case 19 when e then 13 else e end) from t1) then c when ((f))<=17 then d else t1.c end+t1.f) from t1 where (t1.b between  -c and t1.e)),t1.e) else 17 end FROM t1 WHERE NOT (+(abs(d-(select cast(avg((select (abs(max(t1.d*+d*( -e*(13)) | 17)+ -min(t1.d)+~ - -max(17) | max(t1.a) |  -count(distinct t1.a)-count(distinct 13)*(count(distinct t1.a)) | (count(distinct 17)))) from t1)) AS integer) from t1)-11)/abs(c+d-t1.e))>=t1.d)}
} {-2001}
do_test randexpr-2.2001 {
  db eval {SELECT coalesce((select 11 from t1 where a not in (17,e,(select  -abs(case ( -count(distinct t1.e)) when count(distinct 13) | max((abs(case 11 when  -(abs(19)/abs(17 | t1.c*t1.e))*t1.c | t1.b then a else +d end)/abs(b*t1.a))) then max(c*13) else cast(avg(t1.f) AS integer) end)-max(11) from t1)*d)),t1.d) FROM t1 WHERE 19-c*coalesce((select max(case (select count(distinct t1.f) from t1) | t1.a when case a when (abs(case when not c+t1.d>=e then 17*t1.e+a when not exists(select 1 from t1 where 11>b) then c else a end)/abs(t1.e))+t1.f*13 then 11 else t1.f end then 19 else d end-b) from t1 where (d) not between f and e),t1.d)= -c}
} {}
do_test randexpr-2.2002 {
  db eval {SELECT coalesce((select 11 from t1 where a not in (17,e,(select  -abs(case ( -count(distinct t1.e)) when count(distinct 13) | max((abs(case 11 when  -(abs(19)/abs(17 | t1.c*t1.e))*t1.c | t1.b then a else +d end)/abs(b*t1.a))) then max(c*13) else cast(avg(t1.f) AS integer) end)-max(11) from t1)*d)),t1.d) FROM t1 WHERE NOT (19-c*coalesce((select max(case (select count(distinct t1.f) from t1) | t1.a when case a when (abs(case when not c+t1.d>=e then 17*t1.e+a when not exists(select 1 from t1 where 11>b) then c else a end)/abs(t1.e))+t1.f*13 then 11 else t1.f end then 19 else d end-b) from t1 where (d) not between f and e),t1.d)= -c)}
} {11}
do_test randexpr-2.2003 {
  db eval {SELECT coalesce((select 11 from t1 where a not in (17,e,(select  -abs(case ( -count(distinct t1.e)) when count(distinct 13) & max((abs(case 11 when  -(abs(19)/abs(17 & t1.c*t1.e))*t1.c & t1.b then a else +d end)/abs(b*t1.a))) then max(c*13) else cast(avg(t1.f) AS integer) end)-max(11) from t1)*d)),t1.d) FROM t1 WHERE NOT (19-c*coalesce((select max(case (select count(distinct t1.f) from t1) | t1.a when case a when (abs(case when not c+t1.d>=e then 17*t1.e+a when not exists(select 1 from t1 where 11>b) then c else a end)/abs(t1.e))+t1.f*13 then 11 else t1.f end then 19 else d end-b) from t1 where (d) not between f and e),t1.d)= -c)}
} {11}
do_test randexpr-2.2004 {
  db eval {SELECT 11+t1.b*~c*17-13-a+t1.d | t1.f+t1.b*coalesce((select 17 from t1 where t1.e in (select (select cast(avg(case case e when (t1.d) then 17 else (abs((abs(case when d<t1.d then b when t1.c<>19 then 19 else a end)/abs(f)))/abs((t1.e))) end when b then (11) else f end+17) AS integer) from t1) from t1 union select t1.c from t1)),(17)) FROM t1 WHERE e=11}
} {}
do_test randexpr-2.2005 {
  db eval {SELECT 11+t1.b*~c*17-13-a+t1.d | t1.f+t1.b*coalesce((select 17 from t1 where t1.e in (select (select cast(avg(case case e when (t1.d) then 17 else (abs((abs(case when d<t1.d then b when t1.c<>19 then 19 else a end)/abs(f)))/abs((t1.e))) end when b then (11) else f end+17) AS integer) from t1) from t1 union select t1.c from t1)),(17)) FROM t1 WHERE NOT (e=11)}
} {-1019998}
do_test randexpr-2.2006 {
  db eval {SELECT 11+t1.b*~c*17-13-a+t1.d & t1.f+t1.b*coalesce((select 17 from t1 where t1.e in (select (select cast(avg(case case e when (t1.d) then 17 else (abs((abs(case when d<t1.d then b when t1.c<>19 then 19 else a end)/abs(f)))/abs((t1.e))) end when b then (11) else f end+17) AS integer) from t1) from t1 union select t1.c from t1)),(17)) FROM t1 WHERE NOT (e=11)}
} {896}
do_test randexpr-2.2007 {
  db eval {SELECT e*~~(coalesce((select +case when not exists(select 1 from t1 where 13*coalesce((select max(coalesce((select max(11) from t1 where not exists(select 1 from t1 where (select  -count(distinct 11) | min(11) from t1)>case b when b then c else d end)),13)) from t1 where  -c<>d),13)<>t1.f and 13 between 13 and 19) then b-t1.e+e else (t1.f) end from t1 where ((not not e>t1.c and c not between a and e))),t1.d)) FROM t1 WHERE exists(select 1 from t1 where case when case when e<c then  -coalesce((select max((abs(17)/abs(coalesce((select max(d) from t1 where (abs(13)/abs(t1.b)) between 11 and e),19)*f+d))*t1.f) from t1 where not exists(select 1 from t1 where 11 not in (t1.d, -t1.a,11))),t1.b)-e when (t1.c=17) then b else e end=f then d else t1.b end<=t1.d or t1.a<> -b)}
} {200000}
do_test randexpr-2.2008 {
  db eval {SELECT e*~~(coalesce((select +case when not exists(select 1 from t1 where 13*coalesce((select max(coalesce((select max(11) from t1 where not exists(select 1 from t1 where (select  -count(distinct 11) | min(11) from t1)>case b when b then c else d end)),13)) from t1 where  -c<>d),13)<>t1.f and 13 between 13 and 19) then b-t1.e+e else (t1.f) end from t1 where ((not not e>t1.c and c not between a and e))),t1.d)) FROM t1 WHERE NOT (exists(select 1 from t1 where case when case when e<c then  -coalesce((select max((abs(17)/abs(coalesce((select max(d) from t1 where (abs(13)/abs(t1.b)) between 11 and e),19)*f+d))*t1.f) from t1 where not exists(select 1 from t1 where 11 not in (t1.d, -t1.a,11))),t1.b)-e when (t1.c=17) then b else e end=f then d else t1.b end<=t1.d or t1.a<> -b))}
} {}
do_test randexpr-2.2009 {
  db eval {SELECT e*~~(coalesce((select +case when not exists(select 1 from t1 where 13*coalesce((select max(coalesce((select max(11) from t1 where not exists(select 1 from t1 where (select  -count(distinct 11) & min(11) from t1)>case b when b then c else d end)),13)) from t1 where  -c<>d),13)<>t1.f and 13 between 13 and 19) then b-t1.e+e else (t1.f) end from t1 where ((not not e>t1.c and c not between a and e))),t1.d)) FROM t1 WHERE exists(select 1 from t1 where case when case when e<c then  -coalesce((select max((abs(17)/abs(coalesce((select max(d) from t1 where (abs(13)/abs(t1.b)) between 11 and e),19)*f+d))*t1.f) from t1 where not exists(select 1 from t1 where 11 not in (t1.d, -t1.a,11))),t1.b)-e when (t1.c=17) then b else e end=f then d else t1.b end<=t1.d or t1.a<> -b)}
} {200000}
do_test randexpr-2.2010 {
  db eval {SELECT (case t1.b-coalesce((select max(t1.f) from t1 where +t1.c=e or coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where ((13-(select +cast(avg( -t1.b) AS integer) from t1) in (case f when (19) then t1.f else t1.f end,11,t1.e))))),(t1.a)+t1.e) not in (t1.f,t1.a,b) and t1.e not in (11,t1.b,t1.b)),d) when 19 then t1.e else c end-t1.e*t1.f) FROM t1 WHERE t1.e<t1.e}
} {}
do_test randexpr-2.2011 {
  db eval {SELECT (case t1.b-coalesce((select max(t1.f) from t1 where +t1.c=e or coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where ((13-(select +cast(avg( -t1.b) AS integer) from t1) in (case f when (19) then t1.f else t1.f end,11,t1.e))))),(t1.a)+t1.e) not in (t1.f,t1.a,b) and t1.e not in (11,t1.b,t1.b)),d) when 19 then t1.e else c end-t1.e*t1.f) FROM t1 WHERE NOT (t1.e<t1.e)}
} {-299700}
do_test randexpr-2.2012 {
  db eval {SELECT t1.a+e-case when 19<+17 then case when 19 not between t1.e and t1.e then (abs(case when e+17*(select count(distinct (abs(+17)/abs(t1.c))) from t1)<>coalesce((select max(f) from t1 where 19>=b),19) then f else t1.e end-f)/abs(t1.a))-11 else t1.e end when exists(select 1 from t1 where not exists(select 1 from t1 where ((c)) not in (b,a,e))) then t1.c else ((11)) end FROM t1 WHERE (not 13 not in (17,a,e))}
} {}
do_test randexpr-2.2013 {
  db eval {SELECT t1.a+e-case when 19<+17 then case when 19 not between t1.e and t1.e then (abs(case when e+17*(select count(distinct (abs(+17)/abs(t1.c))) from t1)<>coalesce((select max(f) from t1 where 19>=b),19) then f else t1.e end-f)/abs(t1.a))-11 else t1.e end when exists(select 1 from t1 where not exists(select 1 from t1 where ((c)) not in (b,a,e))) then t1.c else ((11)) end FROM t1 WHERE NOT ((not 13 not in (17,a,e)))}
} {589}
do_test randexpr-2.2014 {
  db eval {SELECT case when not exists(select 1 from t1 where case when  -~(19)=t1.c then t1.f*~case when t1.f<=(select max(t1.c) from t1) then e when (c<>13) then t1.a else (b) end when t1.b between 19 and 17 then 17 else e end-e+t1.a>e or  -19 in (select max(13) from t1 union select min( -19) from t1)) then t1.b when  -11>=a then ~b else 19 end FROM t1 WHERE (c not between coalesce((select max(c) from t1 where (not t1.c<>t1.a)), -(abs(case when t1.e<=t1.c then t1.d when exists(select 1 from t1 where 17 in (select case when coalesce((select c from t1 where 17-t1.a-coalesce((select 17 from t1 where t1.f in (t1.b,19,t1.c)),17) not between e and 13),t1.b) not in (e,13,t1.a) then t1.c else b end | f from t1 union select t1.f from t1)) then t1.f else 11 end)/abs(t1.a))) and t1.e)}
} {}
do_test randexpr-2.2015 {
  db eval {SELECT case when not exists(select 1 from t1 where case when  -~(19)=t1.c then t1.f*~case when t1.f<=(select max(t1.c) from t1) then e when (c<>13) then t1.a else (b) end when t1.b between 19 and 17 then 17 else e end-e+t1.a>e or  -19 in (select max(13) from t1 union select min( -19) from t1)) then t1.b when  -11>=a then ~b else 19 end FROM t1 WHERE NOT ((c not between coalesce((select max(c) from t1 where (not t1.c<>t1.a)), -(abs(case when t1.e<=t1.c then t1.d when exists(select 1 from t1 where 17 in (select case when coalesce((select c from t1 where 17-t1.a-coalesce((select 17 from t1 where t1.f in (t1.b,19,t1.c)),17) not between e and 13),t1.b) not in (e,13,t1.a) then t1.c else b end | f from t1 union select t1.f from t1)) then t1.f else 11 end)/abs(t1.a))) and t1.e))}
} {19}
do_test randexpr-2.2016 {
  db eval {SELECT case t1.c | t1.b when t1.f-c then case when c<t1.c then t1.e when not t1.f in (select case when exists(select 1 from t1 where t1.e<=coalesce((select (select case count(distinct  -e*a) when ~( -min(11)) then count(*) else count(*) end from t1) from t1 where (b-d<= -t1.f)),t1.e) or exists(select 1 from t1 where t1.d>=11) or t1.c<=t1.e) then + - -b+11 else 13 end from t1 union select (t1.c) from t1) then 17 else 11 end else t1.a end FROM t1 WHERE t1.f | 13+coalesce((select max(11) from t1 where e>=(select ~case cast(avg(19*f+(c)) AS integer) when (min(c))-min(t1.a) then cast(avg(13) AS integer) else count(distinct e) end from t1)),t1.f)>=coalesce((select c from t1 where (exists(select 1 from t1 where t1.f>=f and (t1.d)<>t1.a))),c) or not exists(select 1 from t1 where not 11>=t1.d) or (b between c and 11 and 11< -t1.b and t1.e>=t1.b) or t1.c>e}
} {100}
do_test randexpr-2.2017 {
  db eval {SELECT case t1.c | t1.b when t1.f-c then case when c<t1.c then t1.e when not t1.f in (select case when exists(select 1 from t1 where t1.e<=coalesce((select (select case count(distinct  -e*a) when ~( -min(11)) then count(*) else count(*) end from t1) from t1 where (b-d<= -t1.f)),t1.e) or exists(select 1 from t1 where t1.d>=11) or t1.c<=t1.e) then + - -b+11 else 13 end from t1 union select (t1.c) from t1) then 17 else 11 end else t1.a end FROM t1 WHERE NOT (t1.f | 13+coalesce((select max(11) from t1 where e>=(select ~case cast(avg(19*f+(c)) AS integer) when (min(c))-min(t1.a) then cast(avg(13) AS integer) else count(distinct e) end from t1)),t1.f)>=coalesce((select c from t1 where (exists(select 1 from t1 where t1.f>=f and (t1.d)<>t1.a))),c) or not exists(select 1 from t1 where not 11>=t1.d) or (b between c and 11 and 11< -t1.b and t1.e>=t1.b) or t1.c>e)}
} {}
do_test randexpr-2.2018 {
  db eval {SELECT case t1.c & t1.b when t1.f-c then case when c<t1.c then t1.e when not t1.f in (select case when exists(select 1 from t1 where t1.e<=coalesce((select (select case count(distinct  -e*a) when ~( -min(11)) then count(*) else count(*) end from t1) from t1 where (b-d<= -t1.f)),t1.e) or exists(select 1 from t1 where t1.d>=11) or t1.c<=t1.e) then + - -b+11 else 13 end from t1 union select (t1.c) from t1) then 17 else 11 end else t1.a end FROM t1 WHERE t1.f | 13+coalesce((select max(11) from t1 where e>=(select ~case cast(avg(19*f+(c)) AS integer) when (min(c))-min(t1.a) then cast(avg(13) AS integer) else count(distinct e) end from t1)),t1.f)>=coalesce((select c from t1 where (exists(select 1 from t1 where t1.f>=f and (t1.d)<>t1.a))),c) or not exists(select 1 from t1 where not 11>=t1.d) or (b between c and 11 and 11< -t1.b and t1.e>=t1.b) or t1.c>e}
} {100}
do_test randexpr-2.2019 {
  db eval {SELECT coalesce((select 19 from t1 where a<=case (abs(e)/abs(case b+f when b then t1.e else e end)) when + -t1.b+coalesce((select max(t1.f) from t1 where (19<=+e) and (c*b)>= -t1.e and (c>=c)),11+(e)+a)-t1.b then 17 else 17 end-t1.e),a) FROM t1 WHERE +d*t1.f+c+t1.c*13<>t1.e}
} {100}
do_test randexpr-2.2020 {
  db eval {SELECT coalesce((select 19 from t1 where a<=case (abs(e)/abs(case b+f when b then t1.e else e end)) when + -t1.b+coalesce((select max(t1.f) from t1 where (19<=+e) and (c*b)>= -t1.e and (c>=c)),11+(e)+a)-t1.b then 17 else 17 end-t1.e),a) FROM t1 WHERE NOT (+d*t1.f+c+t1.c*13<>t1.e)}
} {}
do_test randexpr-2.2021 {
  db eval {SELECT (abs(t1.e)/abs(coalesce((select +t1.a*c from t1 where (abs(e)/abs(d)) in (select +~count(*)-min(t1.d) from t1 union select abs(abs(cast(avg(t1.b) AS integer))+cast(avg(b) AS integer)) from t1)),d))) FROM t1 WHERE not b not between (select max(13) from t1) and 13}
} {}
do_test randexpr-2.2022 {
  db eval {SELECT (abs(t1.e)/abs(coalesce((select +t1.a*c from t1 where (abs(e)/abs(d)) in (select +~count(*)-min(t1.d) from t1 union select abs(abs(cast(avg(t1.b) AS integer))+cast(avg(b) AS integer)) from t1)),d))) FROM t1 WHERE NOT (not b not between (select max(13) from t1) and 13)}
} {1}
do_test randexpr-2.2023 {
  db eval {SELECT +(select +~(count(distinct (abs((abs(coalesce((select max(t1.c) from t1 where  -e in (select t1.e from t1 union select (e) from t1)),c)-11)/abs(19))*t1.c)/abs(19))))*count(distinct t1.a)*+count(distinct a)*count(distinct t1.d) | count(*)-max(11)+cast(avg(t1.b) AS integer)*min(t1.a) from t1)+19+t1.c*19+~coalesce((select e from t1 where 13 in (select count(distinct 17) from t1 union select count(distinct 11) from t1) or t1.f<>c),17) FROM t1 WHERE exists(select 1 from t1 where coalesce((select t1.f from t1 where t1.a in (case when exists(select 1 from t1 where b*t1.e in (select (t1.a) from t1 union select (case  -13 when f then t1.b else t1.a end) from t1)) then t1.d else 17 end,d,11)),c) not in (17,19,t1.b)) or (b) in (select abs(~~abs(count(*)) |  - -min(c)-min(11)+count(*) | max(a) | count(*)-count(distinct 11)) from t1 union select max(t1.f) from t1) or t1.b>=19}
} {5216}
do_test randexpr-2.2024 {
  db eval {SELECT +(select +~(count(distinct (abs((abs(coalesce((select max(t1.c) from t1 where  -e in (select t1.e from t1 union select (e) from t1)),c)-11)/abs(19))*t1.c)/abs(19))))*count(distinct t1.a)*+count(distinct a)*count(distinct t1.d) | count(*)-max(11)+cast(avg(t1.b) AS integer)*min(t1.a) from t1)+19+t1.c*19+~coalesce((select e from t1 where 13 in (select count(distinct 17) from t1 union select count(distinct 11) from t1) or t1.f<>c),17) FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select t1.f from t1 where t1.a in (case when exists(select 1 from t1 where b*t1.e in (select (t1.a) from t1 union select (case  -13 when f then t1.b else t1.a end) from t1)) then t1.d else 17 end,d,11)),c) not in (17,19,t1.b)) or (b) in (select abs(~~abs(count(*)) |  - -min(c)-min(11)+count(*) | max(a) | count(*)-count(distinct 11)) from t1 union select max(t1.f) from t1) or t1.b>=19)}
} {}
do_test randexpr-2.2025 {
  db eval {SELECT +(select +~(count(distinct (abs((abs(coalesce((select max(t1.c) from t1 where  -e in (select t1.e from t1 union select (e) from t1)),c)-11)/abs(19))*t1.c)/abs(19))))*count(distinct t1.a)*+count(distinct a)*count(distinct t1.d) & count(*)-max(11)+cast(avg(t1.b) AS integer)*min(t1.a) from t1)+19+t1.c*19+~coalesce((select e from t1 where 13 in (select count(distinct 17) from t1 union select count(distinct 11) from t1) or t1.f<>c),17) FROM t1 WHERE exists(select 1 from t1 where coalesce((select t1.f from t1 where t1.a in (case when exists(select 1 from t1 where b*t1.e in (select (t1.a) from t1 union select (case  -13 when f then t1.b else t1.a end) from t1)) then t1.d else 17 end,d,11)),c) not in (17,19,t1.b)) or (b) in (select abs(~~abs(count(*)) |  - -min(c)-min(11)+count(*) | max(a) | count(*)-count(distinct 11)) from t1 union select max(t1.f) from t1) or t1.b>=19}
} {25208}
do_test randexpr-2.2026 {
  db eval {SELECT (abs(case t1.c when ~coalesce((select max(case coalesce((select max(b) from t1 where not a<b or e*coalesce((select case t1.d when c then e else 13 end from t1 where not t1.c in (select t1.e from t1 union select 11 from t1)),(d))+c in (select +min(t1.d) from t1 union select cast(avg(13) AS integer) from t1)),e-f)*e when t1.e then t1.f else 19 end) from t1 where e>a),e) then 17 else a end)/abs(19)) FROM t1 WHERE d not in (d,d+case coalesce((select t1.e from t1 where (case when 17*case case f-+t1.c+coalesce((select t1.c from t1 where t1.d<e),t1.e) when  -t1.d then e else t1.f end when d then t1.c else  -17 end*17*b<=t1.f then b when t1.a<e then 11 else 13 end>f)),d) when t1.e then (t1.c) else  -e end,t1.f)}
} {}
do_test randexpr-2.2027 {
  db eval {SELECT (abs(case t1.c when ~coalesce((select max(case coalesce((select max(b) from t1 where not a<b or e*coalesce((select case t1.d when c then e else 13 end from t1 where not t1.c in (select t1.e from t1 union select 11 from t1)),(d))+c in (select +min(t1.d) from t1 union select cast(avg(13) AS integer) from t1)),e-f)*e when t1.e then t1.f else 19 end) from t1 where e>a),e) then 17 else a end)/abs(19)) FROM t1 WHERE NOT (d not in (d,d+case coalesce((select t1.e from t1 where (case when 17*case case f-+t1.c+coalesce((select t1.c from t1 where t1.d<e),t1.e) when  -t1.d then e else t1.f end when d then t1.c else  -17 end*17*b<=t1.f then b when t1.a<e then 11 else 13 end>f)),d) when t1.e then (t1.c) else  -e end,t1.f))}
} {5}
do_test randexpr-2.2028 {
  db eval {SELECT case 13 when 13 then case when 11 between case case when not 17 not between f-t1.e and (abs(19)/abs(((t1.b))))*19 then t1.a when exists(select 1 from t1 where t1.e not between d and 13) then t1.c else  -e end when t1.e then t1.c else e end and 17 then 19 when not exists(select 1 from t1 where 11=f) and exists(select 1 from t1 where d<>t1.a) or t1.f>=17 then a else t1.e end else 19 end*11 FROM t1 WHERE case 17 when t1.f then 11 else c end+d=t1.f}
} {}
do_test randexpr-2.2029 {
  db eval {SELECT case 13 when 13 then case when 11 between case case when not 17 not between f-t1.e and (abs(19)/abs(((t1.b))))*19 then t1.a when exists(select 1 from t1 where t1.e not between d and 13) then t1.c else  -e end when t1.e then t1.c else e end and 17 then 19 when not exists(select 1 from t1 where 11=f) and exists(select 1 from t1 where d<>t1.a) or t1.f>=17 then a else t1.e end else 19 end*11 FROM t1 WHERE NOT (case 17 when t1.f then 11 else c end+d=t1.f)}
} {1100}
do_test randexpr-2.2030 {
  db eval {SELECT coalesce((select max(b-case when exists(select 1 from t1 where case when t1.c>t1.b then t1.c*19 else coalesce((select max((abs(t1.a)/abs(~(select +max(t1.c)*max(a)*cast(avg(t1.d) AS integer) from t1)+case when e=t1.c or t1.c between e and b then +a else 13 end))) from t1 where 17=b),t1.a) end not between f and t1.c) then c else e end+ - -d-17) from t1 where t1.e<d),17) FROM t1 WHERE  -a>=(select cast(avg(d) AS integer) from t1)}
} {}
do_test randexpr-2.2031 {
  db eval {SELECT coalesce((select max(b-case when exists(select 1 from t1 where case when t1.c>t1.b then t1.c*19 else coalesce((select max((abs(t1.a)/abs(~(select +max(t1.c)*max(a)*cast(avg(t1.d) AS integer) from t1)+case when e=t1.c or t1.c between e and b then +a else 13 end))) from t1 where 17=b),t1.a) end not between f and t1.c) then c else e end+ - -d-17) from t1 where t1.e<d),17) FROM t1 WHERE NOT ( -a>=(select cast(avg(d) AS integer) from t1))}
} {17}
do_test randexpr-2.2032 {
  db eval {SELECT case when  -13 in (select +case when case when exists(select 1 from t1 where ~coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.a not between t1.b and  -t1.e)),t1.c)+c | b not between f and t1.b) then  -11-19 else t1.d end in (select ~abs(max(19))+cast(avg(e) AS integer)-max(13)-count(*) from t1 union select min(f) from t1) then t1.f else b end+t1.e from t1 union select t1.f from t1) then b when e<t1.f then d else t1.f end+11 FROM t1 WHERE (select count(distinct +t1.e) from t1) in (select max(coalesce((select case when exists(select 1 from t1 where +19*a<>(select count(distinct d) from t1)) then t1.a when +(select cast(avg(e-19*~case 19 when t1.f then (t1.d) else t1.e end*t1.d*c) AS integer) from t1) in (e,t1.c,t1.e) then 13 else a end from t1 where d not between t1.b and f),a)) from t1 union select min((t1.b)) from t1) or (t1.e<=13)}
} {}
do_test randexpr-2.2033 {
  db eval {SELECT case when  -13 in (select +case when case when exists(select 1 from t1 where ~coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.a not between t1.b and  -t1.e)),t1.c)+c | b not between f and t1.b) then  -11-19 else t1.d end in (select ~abs(max(19))+cast(avg(e) AS integer)-max(13)-count(*) from t1 union select min(f) from t1) then t1.f else b end+t1.e from t1 union select t1.f from t1) then b when e<t1.f then d else t1.f end+11 FROM t1 WHERE NOT ((select count(distinct +t1.e) from t1) in (select max(coalesce((select case when exists(select 1 from t1 where +19*a<>(select count(distinct d) from t1)) then t1.a when +(select cast(avg(e-19*~case 19 when t1.f then (t1.d) else t1.e end*t1.d*c) AS integer) from t1) in (e,t1.c,t1.e) then 13 else a end from t1 where d not between t1.b and f),a)) from t1 union select min((t1.b)) from t1) or (t1.e<=13))}
} {411}
do_test randexpr-2.2034 {
  db eval {SELECT case when  -13 in (select +case when case when exists(select 1 from t1 where ~coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.a not between t1.b and  -t1.e)),t1.c)+c & b not between f and t1.b) then  -11-19 else t1.d end in (select ~abs(max(19))+cast(avg(e) AS integer)-max(13)-count(*) from t1 union select min(f) from t1) then t1.f else b end+t1.e from t1 union select t1.f from t1) then b when e<t1.f then d else t1.f end+11 FROM t1 WHERE NOT ((select count(distinct +t1.e) from t1) in (select max(coalesce((select case when exists(select 1 from t1 where +19*a<>(select count(distinct d) from t1)) then t1.a when +(select cast(avg(e-19*~case 19 when t1.f then (t1.d) else t1.e end*t1.d*c) AS integer) from t1) in (e,t1.c,t1.e) then 13 else a end from t1 where d not between t1.b and f),a)) from t1 union select min((t1.b)) from t1) or (t1.e<=13))}
} {411}
do_test randexpr-2.2035 {
  db eval {SELECT (+coalesce((select max(c) from t1 where case when ( -t1.f between t1.a |  -a*(abs(11 | e+case when not exists(select 1 from t1 where t1.b<>f or a=t1.a) then 17*(a) else 17 end*c)/abs(c))-d+f* -e-t1.a and b) then  -11-a else t1.a end*19+b | t1.a<=t1.e),t1.b)) FROM t1 WHERE t1.e between  -case when e not in (t1.e,case when d+t1.c-b-t1.b+case when  -e<f then + -t1.c*t1.d+a*13*e when ( -t1.f<=a) then f else 13 end*t1.e-a-t1.b<(t1.e) then t1.d else t1.d end,t1.f) then f else t1.d end and t1.c}
} {}
do_test randexpr-2.2036 {
  db eval {SELECT (+coalesce((select max(c) from t1 where case when ( -t1.f between t1.a |  -a*(abs(11 | e+case when not exists(select 1 from t1 where t1.b<>f or a=t1.a) then 17*(a) else 17 end*c)/abs(c))-d+f* -e-t1.a and b) then  -11-a else t1.a end*19+b | t1.a<=t1.e),t1.b)) FROM t1 WHERE NOT (t1.e between  -case when e not in (t1.e,case when d+t1.c-b-t1.b+case when  -e<f then + -t1.c*t1.d+a*13*e when ( -t1.f<=a) then f else 13 end*t1.e-a-t1.b<(t1.e) then t1.d else t1.d end,t1.f) then f else t1.d end and t1.c)}
} {300}
do_test randexpr-2.2037 {
  db eval {SELECT (+coalesce((select max(c) from t1 where case when ( -t1.f between t1.a &  -a*(abs(11 & e+case when not exists(select 1 from t1 where t1.b<>f or a=t1.a) then 17*(a) else 17 end*c)/abs(c))-d+f* -e-t1.a and b) then  -11-a else t1.a end*19+b & t1.a<=t1.e),t1.b)) FROM t1 WHERE NOT (t1.e between  -case when e not in (t1.e,case when d+t1.c-b-t1.b+case when  -e<f then + -t1.c*t1.d+a*13*e when ( -t1.f<=a) then f else 13 end*t1.e-a-t1.b<(t1.e) then t1.d else t1.d end,t1.f) then f else t1.d end and t1.c)}
} {300}
do_test randexpr-2.2038 {
  db eval {SELECT (select +~~ -(count(*))+max((select ~count(*)+count(distinct d)*~cast(avg(19) AS integer)+case count(*)- -abs(abs(~abs(++abs(cast(avg(t1.c) AS integer)))+count(distinct e)+count(*)))+(min(19) | ( -cast(avg(b) AS integer) |  - -(count(distinct t1.f)))) when  -count(*) then max( -b) else max((t1.d)) end from t1)) from t1) FROM t1 WHERE (abs(c)/abs((select (abs(count(*))) from t1))) not between t1.b and (select abs(count(*)* -~min(~e+case when t1.a+(a)>e then t1.d else a end+f)-case (+min(t1.f)*min(e)+cast(avg(c) AS integer))*count(*) when  - -((count(distinct f))) then max(a) else count(*) end |  -cast(avg(11) AS integer)*count(*))-count(*)*( -max(f)) from t1)}
} {}
do_test randexpr-2.2039 {
  db eval {SELECT (select +~~ -(count(*))+max((select ~count(*)+count(distinct d)*~cast(avg(19) AS integer)+case count(*)- -abs(abs(~abs(++abs(cast(avg(t1.c) AS integer)))+count(distinct e)+count(*)))+(min(19) | ( -cast(avg(b) AS integer) |  - -(count(distinct t1.f)))) when  -count(*) then max( -b) else max((t1.d)) end from t1)) from t1) FROM t1 WHERE NOT ((abs(c)/abs((select (abs(count(*))) from t1))) not between t1.b and (select abs(count(*)* -~min(~e+case when t1.a+(a)>e then t1.d else a end+f)-case (+min(t1.f)*min(e)+cast(avg(c) AS integer))*count(*) when  - -((count(distinct f))) then max(a) else count(*) end |  -cast(avg(11) AS integer)*count(*))-count(*)*( -max(f)) from t1))}
} {377}
do_test randexpr-2.2040 {
  db eval {SELECT (select +~~ -(count(*))+max((select ~count(*)+count(distinct d)*~cast(avg(19) AS integer)+case count(*)- -abs(abs(~abs(++abs(cast(avg(t1.c) AS integer)))+count(distinct e)+count(*)))+(min(19) & ( -cast(avg(b) AS integer) &  - -(count(distinct t1.f)))) when  -count(*) then max( -b) else max((t1.d)) end from t1)) from t1) FROM t1 WHERE NOT ((abs(c)/abs((select (abs(count(*))) from t1))) not between t1.b and (select abs(count(*)* -~min(~e+case when t1.a+(a)>e then t1.d else a end+f)-case (+min(t1.f)*min(e)+cast(avg(c) AS integer))*count(*) when  - -((count(distinct f))) then max(a) else count(*) end |  -cast(avg(11) AS integer)*count(*))-count(*)*( -max(f)) from t1))}
} {377}
do_test randexpr-2.2041 {
  db eval {SELECT case when ((select abs((count(*)))+min(case 17 when b then 13 | 11+c | f else 19 end) | +count(*)- - -max(t1.d) from t1) not between 19-case when t1.c not between ~e and (e) then t1.d else t1.c end and t1.e) then t1.d when t1.d in (select  -~count(distinct t1.f)*(min(t1.b)) from t1 union select (cast(avg(17) AS integer)) from t1) then d else t1.b end FROM t1 WHERE not exists(select 1 from t1 where d in (coalesce((select max((select abs(~min(f))++~count(distinct t1.a)+cast(avg(t1.b) AS integer)*cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where (exists(select 1 from t1 where 11<e or t1.a not between t1.a and c)) or e<t1.f)) or t1.a not in (13,f,13)),case when t1.b>=13 then ~19*13 | t1.c+t1.e when c between t1.d and a then t1.b else t1.d end)-13,17,11))}
} {400}
do_test randexpr-2.2042 {
  db eval {SELECT case when ((select abs((count(*)))+min(case 17 when b then 13 | 11+c | f else 19 end) | +count(*)- - -max(t1.d) from t1) not between 19-case when t1.c not between ~e and (e) then t1.d else t1.c end and t1.e) then t1.d when t1.d in (select  -~count(distinct t1.f)*(min(t1.b)) from t1 union select (cast(avg(17) AS integer)) from t1) then d else t1.b end FROM t1 WHERE NOT (not exists(select 1 from t1 where d in (coalesce((select max((select abs(~min(f))++~count(distinct t1.a)+cast(avg(t1.b) AS integer)*cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where (exists(select 1 from t1 where 11<e or t1.a not between t1.a and c)) or e<t1.f)) or t1.a not in (13,f,13)),case when t1.b>=13 then ~19*13 | t1.c+t1.e when c between t1.d and a then t1.b else t1.d end)-13,17,11)))}
} {}
do_test randexpr-2.2043 {
  db eval {SELECT case when ((select abs((count(*)))+min(case 17 when b then 13 & 11+c & f else 19 end) & +count(*)- - -max(t1.d) from t1) not between 19-case when t1.c not between ~e and (e) then t1.d else t1.c end and t1.e) then t1.d when t1.d in (select  -~count(distinct t1.f)*(min(t1.b)) from t1 union select (cast(avg(17) AS integer)) from t1) then d else t1.b end FROM t1 WHERE not exists(select 1 from t1 where d in (coalesce((select max((select abs(~min(f))++~count(distinct t1.a)+cast(avg(t1.b) AS integer)*cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where (exists(select 1 from t1 where 11<e or t1.a not between t1.a and c)) or e<t1.f)) or t1.a not in (13,f,13)),case when t1.b>=13 then ~19*13 | t1.c+t1.e when c between t1.d and a then t1.b else t1.d end)-13,17,11))}
} {400}
do_test randexpr-2.2044 {
  db eval {SELECT case when not exists(select 1 from t1 where e in (select +(count(distinct (abs(case when ((abs(coalesce((select coalesce((select case when c>f and a in (19, -e,t1.c) then +t1.a else t1.e end from t1 where c<b and f=13),13) from t1 where 11 not between t1.f and f and t1.c<=(11)),t1.e))/abs(t1.e))+17)<=c then t1.b when not exists(select 1 from t1 where t1.f in (select c from t1 union select 11 from t1)) then t1.f else 17 end)/abs(t1.e)))) from t1 union select max(t1.e) from t1)) then f else c end*t1.d FROM t1 WHERE (select max(t1.c) from t1) in (t1.f+coalesce((select max(d) from t1 where (c in (select 11*case when e=c then a else t1.f end from t1 union select b from t1)) and t1.c in (select b from t1 union select d from t1) and not exists(select 1 from t1 where t1.c in (t1.a,17,t1.b)) and t1.e=17 or c<>t1.f),(select case abs(count(distinct t1.e)-cast(avg(t1.d) AS integer)*cast(avg(t1.b) AS integer)) when min(19) then count(*) else min(c) end+count(distinct t1.c) from t1))+t1.b,t1.d, -d)}
} {}
do_test randexpr-2.2045 {
  db eval {SELECT case when not exists(select 1 from t1 where e in (select +(count(distinct (abs(case when ((abs(coalesce((select coalesce((select case when c>f and a in (19, -e,t1.c) then +t1.a else t1.e end from t1 where c<b and f=13),13) from t1 where 11 not between t1.f and f and t1.c<=(11)),t1.e))/abs(t1.e))+17)<=c then t1.b when not exists(select 1 from t1 where t1.f in (select c from t1 union select 11 from t1)) then t1.f else 17 end)/abs(t1.e)))) from t1 union select max(t1.e) from t1)) then f else c end*t1.d FROM t1 WHERE NOT ((select max(t1.c) from t1) in (t1.f+coalesce((select max(d) from t1 where (c in (select 11*case when e=c then a else t1.f end from t1 union select b from t1)) and t1.c in (select b from t1 union select d from t1) and not exists(select 1 from t1 where t1.c in (t1.a,17,t1.b)) and t1.e=17 or c<>t1.f),(select case abs(count(distinct t1.e)-cast(avg(t1.d) AS integer)*cast(avg(t1.b) AS integer)) when min(19) then count(*) else min(c) end+count(distinct t1.c) from t1))+t1.b,t1.d, -d))}
} {120000}
do_test randexpr-2.2046 {
  db eval {SELECT  -case when  -b=t1.c then t1.a when (select min(t1.b) from t1)<=d+coalesce((select max(11+a) from t1 where (not exists(select 1 from t1 where c |  -((case case when (t1.f between a and t1.b) then b else c end-t1.c when 19 then t1.c else f end+t1.c)+t1.b | a)-t1.c-(c)<=19))),t1.c) then e else  -t1.d end-(17) FROM t1 WHERE (t1.b | case t1.b when ((t1.e)) then (abs(19)/abs(t1.a))-coalesce((select max(t1.e*case b when a then 11 else t1.a end) from t1 where +~case when 13=17 and t1.e+11 in (select t1.f from t1 union select t1.d from t1) then t1.b when (b<17 and a>= -17) then f else  -t1.e end+(17)<=13),d) else b end | b between t1.d and t1.f)}
} {}
do_test randexpr-2.2047 {
  db eval {SELECT  -case when  -b=t1.c then t1.a when (select min(t1.b) from t1)<=d+coalesce((select max(11+a) from t1 where (not exists(select 1 from t1 where c |  -((case case when (t1.f between a and t1.b) then b else c end-t1.c when 19 then t1.c else f end+t1.c)+t1.b | a)-t1.c-(c)<=19))),t1.c) then e else  -t1.d end-(17) FROM t1 WHERE NOT ((t1.b | case t1.b when ((t1.e)) then (abs(19)/abs(t1.a))-coalesce((select max(t1.e*case b when a then 11 else t1.a end) from t1 where +~case when 13=17 and t1.e+11 in (select t1.f from t1 union select t1.d from t1) then t1.b when (b<17 and a>= -17) then f else  -t1.e end+(17)<=13),d) else b end | b between t1.d and t1.f))}
} {-517}
do_test randexpr-2.2048 {
  db eval {SELECT  -case when  -b=t1.c then t1.a when (select min(t1.b) from t1)<=d+coalesce((select max(11+a) from t1 where (not exists(select 1 from t1 where c &  -((case case when (t1.f between a and t1.b) then b else c end-t1.c when 19 then t1.c else f end+t1.c)+t1.b & a)-t1.c-(c)<=19))),t1.c) then e else  -t1.d end-(17) FROM t1 WHERE NOT ((t1.b | case t1.b when ((t1.e)) then (abs(19)/abs(t1.a))-coalesce((select max(t1.e*case b when a then 11 else t1.a end) from t1 where +~case when 13=17 and t1.e+11 in (select t1.f from t1 union select t1.d from t1) then t1.b when (b<17 and a>= -17) then f else  -t1.e end+(17)<=13),d) else b end | b between t1.d and t1.f))}
} {-517}
do_test randexpr-2.2049 {
  db eval {SELECT case when not c<b and case when not (11 not in (c+b+t1.d- -13+e,(select  -min((case (abs(t1.a)/abs(a)) when 13 then b else  -19 end+11)) from t1),d)) and 13 in (19,t1.c,t1.e) then t1.b else 17 end<=~t1.e then +b*t1.c else t1.b end FROM t1 WHERE (abs(a)/abs(coalesce((select (e) from t1 where case when not d<=c then b else (19) end in (select ~( -(~(((count(*)))) | (count(distinct t1.e)))+min(t1.b)-(cast(avg(d) AS integer))-count(distinct b))-min(e)*max(t1.a) from t1 union select count(distinct f) from t1)),19 | t1.b)*t1.c+13)) in (select ~ -count(distinct e)*max((b)) | min(a) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.2050 {
  db eval {SELECT case when not c<b and case when not (11 not in (c+b+t1.d- -13+e,(select  -min((case (abs(t1.a)/abs(a)) when 13 then b else  -19 end+11)) from t1),d)) and 13 in (19,t1.c,t1.e) then t1.b else 17 end<=~t1.e then +b*t1.c else t1.b end FROM t1 WHERE NOT ((abs(a)/abs(coalesce((select (e) from t1 where case when not d<=c then b else (19) end in (select ~( -(~(((count(*)))) | (count(distinct t1.e)))+min(t1.b)-(cast(avg(d) AS integer))-count(distinct b))-min(e)*max(t1.a) from t1 union select count(distinct f) from t1)),19 | t1.b)*t1.c+13)) in (select ~ -count(distinct e)*max((b)) | min(a) from t1 union select count(*) from t1))}
} {200}
do_test randexpr-2.2051 {
  db eval {SELECT +11+~coalesce((select  -19 from t1 where exists(select 1 from t1 where f*t1.e not in ( -f*~t1.a-f*case when t1.f in ((e),coalesce((select b from t1 where b>=t1.f | t1.d),19),t1.a) then (t1.d) when  -a<=( -t1.a) then a else f end*a,13,19)) or e=17),a)*17 FROM t1 WHERE (select case min(+19) when abs((max(17)* -min(a*(abs(case e when t1.b then t1.f else  -t1.c end*f)/abs(t1.d))*e)-count(*) | max(19))) then  - -case count(distinct 11) when min(11) then max(19) else min(13) end-( -count(distinct 13)) else  -(count(distinct b)) end*cast(avg(17) AS integer)-max(e) from t1) between t1.d and coalesce((select max(13) from t1 where not 17>a-f-e),13)}
} {}
do_test randexpr-2.2052 {
  db eval {SELECT +11+~coalesce((select  -19 from t1 where exists(select 1 from t1 where f*t1.e not in ( -f*~t1.a-f*case when t1.f in ((e),coalesce((select b from t1 where b>=t1.f | t1.d),19),t1.a) then (t1.d) when  -a<=( -t1.a) then a else f end*a,13,19)) or e=17),a)*17 FROM t1 WHERE NOT ((select case min(+19) when abs((max(17)* -min(a*(abs(case e when t1.b then t1.f else  -t1.c end*f)/abs(t1.d))*e)-count(*) | max(19))) then  - -case count(distinct 11) when min(11) then max(19) else min(13) end-( -count(distinct 13)) else  -(count(distinct b)) end*cast(avg(17) AS integer)-max(e) from t1) between t1.d and coalesce((select max(13) from t1 where not 17>a-f-e),13))}
} {317}
do_test randexpr-2.2053 {
  db eval {SELECT +11+~coalesce((select  -19 from t1 where exists(select 1 from t1 where f*t1.e not in ( -f*~t1.a-f*case when t1.f in ((e),coalesce((select b from t1 where b>=t1.f & t1.d),19),t1.a) then (t1.d) when  -a<=( -t1.a) then a else f end*a,13,19)) or e=17),a)*17 FROM t1 WHERE NOT ((select case min(+19) when abs((max(17)* -min(a*(abs(case e when t1.b then t1.f else  -t1.c end*f)/abs(t1.d))*e)-count(*) | max(19))) then  - -case count(distinct 11) when min(11) then max(19) else min(13) end-( -count(distinct 13)) else  -(count(distinct b)) end*cast(avg(17) AS integer)-max(e) from t1) between t1.d and coalesce((select max(13) from t1 where not 17>a-f-e),13))}
} {317}
do_test randexpr-2.2054 {
  db eval {SELECT coalesce((select 11 from t1 where (b-case (select count(distinct t1.f*e) from t1) when t1.f | 11 | 11*coalesce((select 19 from t1 where (~coalesce((select f from t1 where (t1.c>17)),a)+t1.c not between f and t1.e or 19>=c)),(t1.d)) then a else t1.f end>=f and exists(select 1 from t1 where 13<>c) or  - -t1.f<t1.f)),13) FROM t1 WHERE a not in (f,t1.e,11)}
} {13}
do_test randexpr-2.2055 {
  db eval {SELECT coalesce((select 11 from t1 where (b-case (select count(distinct t1.f*e) from t1) when t1.f | 11 | 11*coalesce((select 19 from t1 where (~coalesce((select f from t1 where (t1.c>17)),a)+t1.c not between f and t1.e or 19>=c)),(t1.d)) then a else t1.f end>=f and exists(select 1 from t1 where 13<>c) or  - -t1.f<t1.f)),13) FROM t1 WHERE NOT (a not in (f,t1.e,11))}
} {}
do_test randexpr-2.2056 {
  db eval {SELECT coalesce((select 11 from t1 where (b-case (select count(distinct t1.f*e) from t1) when t1.f & 11 & 11*coalesce((select 19 from t1 where (~coalesce((select f from t1 where (t1.c>17)),a)+t1.c not between f and t1.e or 19>=c)),(t1.d)) then a else t1.f end>=f and exists(select 1 from t1 where 13<>c) or  - -t1.f<t1.f)),13) FROM t1 WHERE a not in (f,t1.e,11)}
} {13}
do_test randexpr-2.2057 {
  db eval {SELECT (abs(coalesce((select max(t1.e) from t1 where c>coalesce((select max(coalesce((select t1.e from t1 where not (abs(a+t1.e*c | case when t1.b in (select  -max(t1.b)*cast(avg(19) AS integer) from t1 union select  -max(13) from t1) then t1.f else 19 end-f+(19)+19)/abs(t1.e)) in (d,13,e) or t1.e<=t1.e),t1.b-17)) from t1 where  -11<>17 or e in (select max(19) from t1 union select (cast(avg(f) AS integer)) from t1)),a)),17))/abs(t1.e)) FROM t1 WHERE t1.e<>13 | (t1.f)+c-((13))-~13 | (abs(e)/abs(coalesce((select max(t1.c) from t1 where (d)<=t1.d),case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(t1.d))>coalesce((select max(a) from t1 where t1.c not between t1.f and t1.f and f not in (t1.f, -t1.c,13)),t1.c)))) then c else 19 end))) | t1.a*11* -e*t1.c or not exists(select 1 from t1 where f>c)}
} {0}
do_test randexpr-2.2058 {
  db eval {SELECT (abs(coalesce((select max(t1.e) from t1 where c>coalesce((select max(coalesce((select t1.e from t1 where not (abs(a+t1.e*c | case when t1.b in (select  -max(t1.b)*cast(avg(19) AS integer) from t1 union select  -max(13) from t1) then t1.f else 19 end-f+(19)+19)/abs(t1.e)) in (d,13,e) or t1.e<=t1.e),t1.b-17)) from t1 where  -11<>17 or e in (select max(19) from t1 union select (cast(avg(f) AS integer)) from t1)),a)),17))/abs(t1.e)) FROM t1 WHERE NOT (t1.e<>13 | (t1.f)+c-((13))-~13 | (abs(e)/abs(coalesce((select max(t1.c) from t1 where (d)<=t1.d),case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(t1.d))>coalesce((select max(a) from t1 where t1.c not between t1.f and t1.f and f not in (t1.f, -t1.c,13)),t1.c)))) then c else 19 end))) | t1.a*11* -e*t1.c or not exists(select 1 from t1 where f>c))}
} {}
do_test randexpr-2.2059 {
  db eval {SELECT (abs(coalesce((select max(t1.e) from t1 where c>coalesce((select max(coalesce((select t1.e from t1 where not (abs(a+t1.e*c & case when t1.b in (select  -max(t1.b)*cast(avg(19) AS integer) from t1 union select  -max(13) from t1) then t1.f else 19 end-f+(19)+19)/abs(t1.e)) in (d,13,e) or t1.e<=t1.e),t1.b-17)) from t1 where  -11<>17 or e in (select max(19) from t1 union select (cast(avg(f) AS integer)) from t1)),a)),17))/abs(t1.e)) FROM t1 WHERE t1.e<>13 | (t1.f)+c-((13))-~13 | (abs(e)/abs(coalesce((select max(t1.c) from t1 where (d)<=t1.d),case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(t1.d))>coalesce((select max(a) from t1 where t1.c not between t1.f and t1.f and f not in (t1.f, -t1.c,13)),t1.c)))) then c else 19 end))) | t1.a*11* -e*t1.c or not exists(select 1 from t1 where f>c)}
} {0}
do_test randexpr-2.2060 {
  db eval {SELECT case t1.e when a then case when not exists(select 1 from t1 where (abs(~coalesce((select c from t1 where (case when not case when a between t1.b and t1.a then t1.c when  -17 not in (11,t1.d,11) then a else t1.a end in (select count(distinct t1.a)+count(distinct t1.a) from t1 union select count(*) from t1) then t1.c when t1.b<(11) then f else a end>=11 and (t1.f)=11)),+11))/abs(e)) not between 17 and  -t1.a) or c not between 19 and t1.b then t1.c when t1.e<t1.a then  -e*t1.d else 17 end | t1.e else t1.b end FROM t1 WHERE f+17<=17}
} {}
do_test randexpr-2.2061 {
  db eval {SELECT case t1.e when a then case when not exists(select 1 from t1 where (abs(~coalesce((select c from t1 where (case when not case when a between t1.b and t1.a then t1.c when  -17 not in (11,t1.d,11) then a else t1.a end in (select count(distinct t1.a)+count(distinct t1.a) from t1 union select count(*) from t1) then t1.c when t1.b<(11) then f else a end>=11 and (t1.f)=11)),+11))/abs(e)) not between 17 and  -t1.a) or c not between 19 and t1.b then t1.c when t1.e<t1.a then  -e*t1.d else 17 end | t1.e else t1.b end FROM t1 WHERE NOT (f+17<=17)}
} {200}
do_test randexpr-2.2062 {
  db eval {SELECT case t1.e when a then case when not exists(select 1 from t1 where (abs(~coalesce((select c from t1 where (case when not case when a between t1.b and t1.a then t1.c when  -17 not in (11,t1.d,11) then a else t1.a end in (select count(distinct t1.a)+count(distinct t1.a) from t1 union select count(*) from t1) then t1.c when t1.b<(11) then f else a end>=11 and (t1.f)=11)),+11))/abs(e)) not between 17 and  -t1.a) or c not between 19 and t1.b then t1.c when t1.e<t1.a then  -e*t1.d else 17 end & t1.e else t1.b end FROM t1 WHERE NOT (f+17<=17)}
} {200}
do_test randexpr-2.2063 {
  db eval {SELECT ~~coalesce((select t1.a from t1 where case f*+e when ~11-coalesce((select max(t1.f) from t1 where t1.f>b),~case when b between 17 and e | coalesce((select max(a) from t1 where (f in (t1.b,f,a))),13) then f when  -d<=d then t1.e else e end+13)+13 then d else d end+t1.f=d),b)+b FROM t1 WHERE b=b}
} {400}
do_test randexpr-2.2064 {
  db eval {SELECT ~~coalesce((select t1.a from t1 where case f*+e when ~11-coalesce((select max(t1.f) from t1 where t1.f>b),~case when b between 17 and e | coalesce((select max(a) from t1 where (f in (t1.b,f,a))),13) then f when  -d<=d then t1.e else e end+13)+13 then d else d end+t1.f=d),b)+b FROM t1 WHERE NOT (b=b)}
} {}
do_test randexpr-2.2065 {
  db eval {SELECT ~~coalesce((select t1.a from t1 where case f*+e when ~11-coalesce((select max(t1.f) from t1 where t1.f>b),~case when b between 17 and e & coalesce((select max(a) from t1 where (f in (t1.b,f,a))),13) then f when  -d<=d then t1.e else e end+13)+13 then d else d end+t1.f=d),b)+b FROM t1 WHERE b=b}
} {400}
do_test randexpr-2.2066 {
  db eval {SELECT e | t1.e*case d when t1.e then a else case when t1.a<= -~+e then b else 17-t1.e end*c*f+case when case when +c in (select +min(11) from t1 union select cast(avg(f) AS integer) from t1) and b between c and t1.f then 11+t1.a when f>=c then d else t1.c end<t1.c and t1.d between t1.a and t1.e then 19 when t1.a<=t1.c then t1.d else f end end FROM t1 WHERE 13 in (select case when ++(select abs(max((select count(*) from t1)+~13)) from t1)*11 not in ((d*~19),(abs(f)/abs(t1.b)),case when not exists(select 1 from t1 where b<=e+t1.d) then b*f when d in (select min(t1.d) from t1 union select min(e) from t1) then 19 else f end*a) then t1.c else  -c end from t1 union select t1.a from t1) or f<c}
} {}
do_test randexpr-2.2067 {
  db eval {SELECT e | t1.e*case d when t1.e then a else case when t1.a<= -~+e then b else 17-t1.e end*c*f+case when case when +c in (select +min(11) from t1 union select cast(avg(f) AS integer) from t1) and b between c and t1.f then 11+t1.a when f>=c then d else t1.c end<t1.c and t1.d between t1.a and t1.e then 19 when t1.a<=t1.c then t1.d else f end end FROM t1 WHERE NOT (13 in (select case when ++(select abs(max((select count(*) from t1)+~13)) from t1)*11 not in ((d*~19),(abs(f)/abs(t1.b)),case when not exists(select 1 from t1 where b<=e+t1.d) then b*f when d in (select min(t1.d) from t1 union select min(e) from t1) then 19 else f end*a) then t1.c else  -c end from t1 union select t1.a from t1) or f<c)}
} {18000200180}
do_test randexpr-2.2068 {
  db eval {SELECT e & t1.e*case d when t1.e then a else case when t1.a<= -~+e then b else 17-t1.e end*c*f+case when case when +c in (select +min(11) from t1 union select cast(avg(f) AS integer) from t1) and b between c and t1.f then 11+t1.a when f>=c then d else t1.c end<t1.c and t1.d between t1.a and t1.e then 19 when t1.a<=t1.c then t1.d else f end end FROM t1 WHERE NOT (13 in (select case when ++(select abs(max((select count(*) from t1)+~13)) from t1)*11 not in ((d*~19),(abs(f)/abs(t1.b)),case when not exists(select 1 from t1 where b<=e+t1.d) then b*f when d in (select min(t1.d) from t1 union select min(e) from t1) then 19 else f end*a) then t1.c else  -c end from t1 union select t1.a from t1) or f<c)}
} {320}
do_test randexpr-2.2069 {
  db eval {SELECT coalesce((select  -(select min(f)-+min(f)*~case +cast(avg(t1.e) AS integer) when max(13)-abs( -max(a)) then +count(distinct a) | abs(max( -c+13)) else (count(*)) end from t1) from t1 where t1.a<>t1.e), -t1.d) FROM t1 WHERE t1.b between coalesce((select (coalesce((select max(case when case when not exists(select 1 from t1 where (17) not in (13,case when 19 not in (19,t1.f,t1.e) and b>=t1.a then e when b<=t1.c then 11 else b end,11)) then c | t1.a else 17 end | 19 in (c,t1.b,d) then t1.a else t1.a end | t1.c) from t1 where not exists(select 1 from t1 where t1.a<=t1.e)),t1.c)) from t1 where t1.d<=t1.a),17)*c-11 and d}
} {}
do_test randexpr-2.2070 {
  db eval {SELECT coalesce((select  -(select min(f)-+min(f)*~case +cast(avg(t1.e) AS integer) when max(13)-abs( -max(a)) then +count(distinct a) | abs(max( -c+13)) else (count(*)) end from t1) from t1 where t1.a<>t1.e), -t1.d) FROM t1 WHERE NOT (t1.b between coalesce((select (coalesce((select max(case when case when not exists(select 1 from t1 where (17) not in (13,case when 19 not in (19,t1.f,t1.e) and b>=t1.a then e when b<=t1.c then 11 else b end,11)) then c | t1.a else 17 end | 19 in (c,t1.b,d) then t1.a else t1.a end | t1.c) from t1 where not exists(select 1 from t1 where t1.a<=t1.e)),t1.c)) from t1 where t1.d<=t1.a),17)*c-11 and d)}
} {-1800}
do_test randexpr-2.2071 {
  db eval {SELECT coalesce((select  -(select min(f)-+min(f)*~case +cast(avg(t1.e) AS integer) when max(13)-abs( -max(a)) then +count(distinct a) & abs(max( -c+13)) else (count(*)) end from t1) from t1 where t1.a<>t1.e), -t1.d) FROM t1 WHERE NOT (t1.b between coalesce((select (coalesce((select max(case when case when not exists(select 1 from t1 where (17) not in (13,case when 19 not in (19,t1.f,t1.e) and b>=t1.a then e when b<=t1.c then 11 else b end,11)) then c | t1.a else 17 end | 19 in (c,t1.b,d) then t1.a else t1.a end | t1.c) from t1 where not exists(select 1 from t1 where t1.a<=t1.e)),t1.c)) from t1 where t1.d<=t1.a),17)*c-11 and d)}
} {-1800}
do_test randexpr-2.2072 {
  db eval {SELECT coalesce((select c from t1 where case when +case when not 11 | c not in (11,case when 13> -d then e when a>t1.c then 17 else t1.e end,t1.b) then t1.d when c<>t1.a then t1.b else 19 end-b>=17 or 11<t1.c then case when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<t1.c)) then t1.f when not exists(select 1 from t1 where 19 not in (t1.d,t1.b,t1.a)) then t1.c else t1.a end else  - -f end>=19 and b<=e),d) FROM t1 WHERE (+a*t1.a+(19-(abs(case  -c when d then (abs(f)/abs(case t1.a when 19 then b else +~( -case t1.f*t1.a | 17 when  -t1.a then d else (t1.e) end*d)+t1.a-a end)) else 13 end)/abs(11))*t1.c)+17-d not in (11,a,b))}
} {300}
do_test randexpr-2.2073 {
  db eval {SELECT coalesce((select c from t1 where case when +case when not 11 | c not in (11,case when 13> -d then e when a>t1.c then 17 else t1.e end,t1.b) then t1.d when c<>t1.a then t1.b else 19 end-b>=17 or 11<t1.c then case when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<t1.c)) then t1.f when not exists(select 1 from t1 where 19 not in (t1.d,t1.b,t1.a)) then t1.c else t1.a end else  - -f end>=19 and b<=e),d) FROM t1 WHERE NOT ((+a*t1.a+(19-(abs(case  -c when d then (abs(f)/abs(case t1.a when 19 then b else +~( -case t1.f*t1.a | 17 when  -t1.a then d else (t1.e) end*d)+t1.a-a end)) else 13 end)/abs(11))*t1.c)+17-d not in (11,a,b)))}
} {}
do_test randexpr-2.2074 {
  db eval {SELECT coalesce((select c from t1 where case when +case when not 11 & c not in (11,case when 13> -d then e when a>t1.c then 17 else t1.e end,t1.b) then t1.d when c<>t1.a then t1.b else 19 end-b>=17 or 11<t1.c then case when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<t1.c)) then t1.f when not exists(select 1 from t1 where 19 not in (t1.d,t1.b,t1.a)) then t1.c else t1.a end else  - -f end>=19 and b<=e),d) FROM t1 WHERE (+a*t1.a+(19-(abs(case  -c when d then (abs(f)/abs(case t1.a when 19 then b else +~( -case t1.f*t1.a | 17 when  -t1.a then d else (t1.e) end*d)+t1.a-a end)) else 13 end)/abs(11))*t1.c)+17-d not in (11,a,b))}
} {300}
do_test randexpr-2.2075 {
  db eval {SELECT case 17 when t1.c then t1.c*f | t1.b+t1.d+b+c-t1.e+t1.c+t1.c-t1.c*t1.f else case when t1.f+case when (abs(t1.a-coalesce((select a from t1 where (t1.c) in (t1.c,d,19)), -t1.a))/abs(f)) between t1.c and a then  -(t1.b) else b end not in (11, -t1.d,t1.d) then t1.d else d end end FROM t1 WHERE ~17 between (select  -count(distinct b+b)++max(t1.b)*(~(max(t1.d)))-abs(cast(avg(17) AS integer)*count(*))-max(f) | count(distinct t1.a)-count(distinct 13)-cast(avg(c) AS integer) from t1) and c-case when f<>t1.e then (abs(~(a)+e+t1.a | t1.a)/abs(t1.c)) else 13 end- -t1.e}
} {400}
do_test randexpr-2.2076 {
  db eval {SELECT case 17 when t1.c then t1.c*f | t1.b+t1.d+b+c-t1.e+t1.c+t1.c-t1.c*t1.f else case when t1.f+case when (abs(t1.a-coalesce((select a from t1 where (t1.c) in (t1.c,d,19)), -t1.a))/abs(f)) between t1.c and a then  -(t1.b) else b end not in (11, -t1.d,t1.d) then t1.d else d end end FROM t1 WHERE NOT (~17 between (select  -count(distinct b+b)++max(t1.b)*(~(max(t1.d)))-abs(cast(avg(17) AS integer)*count(*))-max(f) | count(distinct t1.a)-count(distinct 13)-cast(avg(c) AS integer) from t1) and c-case when f<>t1.e then (abs(~(a)+e+t1.a | t1.a)/abs(t1.c)) else 13 end- -t1.e)}
} {}
do_test randexpr-2.2077 {
  db eval {SELECT case 17 when t1.c then t1.c*f & t1.b+t1.d+b+c-t1.e+t1.c+t1.c-t1.c*t1.f else case when t1.f+case when (abs(t1.a-coalesce((select a from t1 where (t1.c) in (t1.c,d,19)), -t1.a))/abs(f)) between t1.c and a then  -(t1.b) else b end not in (11, -t1.d,t1.d) then t1.d else d end end FROM t1 WHERE ~17 between (select  -count(distinct b+b)++max(t1.b)*(~(max(t1.d)))-abs(cast(avg(17) AS integer)*count(*))-max(f) | count(distinct t1.a)-count(distinct 13)-cast(avg(c) AS integer) from t1) and c-case when f<>t1.e then (abs(~(a)+e+t1.a | t1.a)/abs(t1.c)) else 13 end- -t1.e}
} {400}
do_test randexpr-2.2078 {
  db eval {SELECT (select cast(avg(coalesce((select max(coalesce((select e from t1 where not ((coalesce((select b from t1 where coalesce((select max(11) from t1 where exists(select 1 from t1 where (a in (select count(*)+max(((t1.a))) from t1 union select cast(avg(a) AS integer) from t1)))),b)<=19), -b))*f<t1.b and not exists(select 1 from t1 where d>=t1.e) and 17<>11 and e in (t1.f,f,17)) or a not between  -a and (17)),+~b)-17*b) from t1 where t1.b>=b),t1.a)) AS integer) from t1) FROM t1 WHERE f in (select cast(avg(t1.e-f-t1.e) AS integer)+min(t1.d) from t1 union select max(case b when 11 then case case when f in (a,a,f) then t1.b when (t1.f)>d then  -19 else t1.a end when 11 then a else t1.e end else (t1.b) end*a)*cast(avg(a) AS integer)+ -+cast(avg(t1.e) AS integer)*case cast(avg(t1.e) AS integer) when (cast(avg( -t1.a) AS integer)) then count(*) else count(*) end*min(t1.d)*min(e) from t1) and (a between d and t1.f)}
} {}
do_test randexpr-2.2079 {
  db eval {SELECT (select cast(avg(coalesce((select max(coalesce((select e from t1 where not ((coalesce((select b from t1 where coalesce((select max(11) from t1 where exists(select 1 from t1 where (a in (select count(*)+max(((t1.a))) from t1 union select cast(avg(a) AS integer) from t1)))),b)<=19), -b))*f<t1.b and not exists(select 1 from t1 where d>=t1.e) and 17<>11 and e in (t1.f,f,17)) or a not between  -a and (17)),+~b)-17*b) from t1 where t1.b>=b),t1.a)) AS integer) from t1) FROM t1 WHERE NOT (f in (select cast(avg(t1.e-f-t1.e) AS integer)+min(t1.d) from t1 union select max(case b when 11 then case case when f in (a,a,f) then t1.b when (t1.f)>d then  -19 else t1.a end when 11 then a else t1.e end else (t1.b) end*a)*cast(avg(a) AS integer)+ -+cast(avg(t1.e) AS integer)*case cast(avg(t1.e) AS integer) when (cast(avg( -t1.a) AS integer)) then count(*) else count(*) end*min(t1.d)*min(e) from t1) and (a between d and t1.f))}
} {-2900}
do_test randexpr-2.2080 {
  db eval {SELECT case when coalesce((select max(coalesce((select max((select min(13) from t1)*d*case when not 19<>(t1.c)-d then 11 else 17 end) from t1 where 13<t1.f and t1.e not between (t1.a) and d),c)) from t1 where t1.d between (d) and 19 or t1.c in (t1.f,(11),17)), -11)>=t1.e then t1.d when not exists(select 1 from t1 where t1.c in (select (count(*)) from t1 union select +count(*) from t1)) then t1.c else 19 end FROM t1 WHERE ((11>=11))}
} {300}
do_test randexpr-2.2081 {
  db eval {SELECT case when coalesce((select max(coalesce((select max((select min(13) from t1)*d*case when not 19<>(t1.c)-d then 11 else 17 end) from t1 where 13<t1.f and t1.e not between (t1.a) and d),c)) from t1 where t1.d between (d) and 19 or t1.c in (t1.f,(11),17)), -11)>=t1.e then t1.d when not exists(select 1 from t1 where t1.c in (select (count(*)) from t1 union select +count(*) from t1)) then t1.c else 19 end FROM t1 WHERE NOT (((11>=11)))}
} {}
do_test randexpr-2.2082 {
  db eval {SELECT  -case when 19 in (select abs((count(*))) from t1 union select abs(min(t1.f)*min(e*e)) from t1) and case when not not (17>a) or d>=c and (19)<=t1.b and  - -t1.f<>t1.f then f when t1.b between d and t1.f then case when t1.e=e then coalesce((select max(d) from t1 where t1.b>=b),a) when t1.a not between c and e then e else 13 end else (17) end>t1.d then b else b end+t1.b-a FROM t1 WHERE exists(select 1 from t1 where +coalesce((select 19 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where case when (select max(11-(select +count(distinct +case + -coalesce((select t1.d from t1 where exists(select 1 from t1 where (b)>t1.c)),t1.f)*11 when  -a then 19 else 19 end) from t1)) from t1)<=t1.d-c then f when exists(select 1 from t1 where t1.f not between b and a) then  -d else t1.d end not in (t1.b,t1.e, -t1.f)))),f) not in (f,e,13))}
} {}
do_test randexpr-2.2083 {
  db eval {SELECT  -case when 19 in (select abs((count(*))) from t1 union select abs(min(t1.f)*min(e*e)) from t1) and case when not not (17>a) or d>=c and (19)<=t1.b and  - -t1.f<>t1.f then f when t1.b between d and t1.f then case when t1.e=e then coalesce((select max(d) from t1 where t1.b>=b),a) when t1.a not between c and e then e else 13 end else (17) end>t1.d then b else b end+t1.b-a FROM t1 WHERE NOT (exists(select 1 from t1 where +coalesce((select 19 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where case when (select max(11-(select +count(distinct +case + -coalesce((select t1.d from t1 where exists(select 1 from t1 where (b)>t1.c)),t1.f)*11 when  -a then 19 else 19 end) from t1)) from t1)<=t1.d-c then f when exists(select 1 from t1 where t1.f not between b and a) then  -d else t1.d end not in (t1.b,t1.e, -t1.f)))),f) not in (f,e,13)))}
} {-100}
do_test randexpr-2.2084 {
  db eval {SELECT coalesce((select max(b) from t1 where d not between a-t1.e and a),coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where t1.e<t1.a)),e)+19) FROM t1 WHERE +case f when case  -~c-case when d=17 then t1.c*(select abs(case (cast(avg(19) AS integer)) when ( -count(*)) then min(19) else count(*) end*min(a)) from t1) when b* -(e)-t1.b in (select max(19) | max(t1.c) from t1 union select max(17) from t1) then c else a end when  -f then 13 else 19 end then t1.d else t1.c end<>e or 11 between b and 13}
} {200}
do_test randexpr-2.2085 {
  db eval {SELECT coalesce((select max(b) from t1 where d not between a-t1.e and a),coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where t1.e<t1.a)),e)+19) FROM t1 WHERE NOT (+case f when case  -~c-case when d=17 then t1.c*(select abs(case (cast(avg(19) AS integer)) when ( -count(*)) then min(19) else count(*) end*min(a)) from t1) when b* -(e)-t1.b in (select max(19) | max(t1.c) from t1 union select max(17) from t1) then c else a end when  -f then 13 else 19 end then t1.d else t1.c end<>e or 11 between b and 13)}
} {}
do_test randexpr-2.2086 {
  db eval {SELECT (select case count(*) when ~(case case  -abs(count(*) | (case case ~case  -count(distinct case when t1.a< -t1.d then b when 19 in (t1.e, - -19,t1.b) then t1.c else t1.f end)-count(distinct (t1.f)) when count(*) then max(c) else count(distinct 17) end when count(*) then ((cast(avg(b) AS integer))) else  -count(*) end when  -count(distinct t1.f) then count(distinct t1.a) else count(distinct t1.e) end))+count(*) when cast(avg(19) AS integer) then  -min( -t1.c) else count(*) end when (min(t1.e)) then cast(avg(c) AS integer) else min(t1.f) end) then min(e) else count(*) end | max(11) from t1)+19 FROM t1 WHERE case when (((d not between (+t1.a-coalesce((select max(b*t1.b* -t1.f) from t1 where a>a),13)) and a)) and c>=d or f<c) then coalesce((select (abs(17)/abs(13))*e from t1 where f in (t1.a,13,t1.b) and (t1.c)<>e and t1.c< -11 and f<>b or t1.b<17),c) else t1.a end>=11}
} {30}
do_test randexpr-2.2087 {
  db eval {SELECT (select case count(*) when ~(case case  -abs(count(*) | (case case ~case  -count(distinct case when t1.a< -t1.d then b when 19 in (t1.e, - -19,t1.b) then t1.c else t1.f end)-count(distinct (t1.f)) when count(*) then max(c) else count(distinct 17) end when count(*) then ((cast(avg(b) AS integer))) else  -count(*) end when  -count(distinct t1.f) then count(distinct t1.a) else count(distinct t1.e) end))+count(*) when cast(avg(19) AS integer) then  -min( -t1.c) else count(*) end when (min(t1.e)) then cast(avg(c) AS integer) else min(t1.f) end) then min(e) else count(*) end | max(11) from t1)+19 FROM t1 WHERE NOT (case when (((d not between (+t1.a-coalesce((select max(b*t1.b* -t1.f) from t1 where a>a),13)) and a)) and c>=d or f<c) then coalesce((select (abs(17)/abs(13))*e from t1 where f in (t1.a,13,t1.b) and (t1.c)<>e and t1.c< -11 and f<>b or t1.b<17),c) else t1.a end>=11)}
} {}
do_test randexpr-2.2088 {
  db eval {SELECT (select case count(*) when ~(case case  -abs(count(*) & (case case ~case  -count(distinct case when t1.a< -t1.d then b when 19 in (t1.e, - -19,t1.b) then t1.c else t1.f end)-count(distinct (t1.f)) when count(*) then max(c) else count(distinct 17) end when count(*) then ((cast(avg(b) AS integer))) else  -count(*) end when  -count(distinct t1.f) then count(distinct t1.a) else count(distinct t1.e) end))+count(*) when cast(avg(19) AS integer) then  -min( -t1.c) else count(*) end when (min(t1.e)) then cast(avg(c) AS integer) else min(t1.f) end) then min(e) else count(*) end & max(11) from t1)+19 FROM t1 WHERE case when (((d not between (+t1.a-coalesce((select max(b*t1.b* -t1.f) from t1 where a>a),13)) and a)) and c>=d or f<c) then coalesce((select (abs(17)/abs(13))*e from t1 where f in (t1.a,13,t1.b) and (t1.c)<>e and t1.c< -11 and f<>b or t1.b<17),c) else t1.a end>=11}
} {20}
do_test randexpr-2.2089 {
  db eval {SELECT case when case when t1.a*~t1.a-19-c | 17+t1.d*f*c=d then f else  -13 end+t1.b+a in (t1.f,t1.d,t1.f) and (not c=11) and t1.e<>f then coalesce((select f from t1 where t1.d not in (t1.e,f,11)), -17) else f end-b FROM t1 WHERE not exists(select 1 from t1 where +d between d*13 and ((abs(13+e+e)/abs(+case when not t1.c in (~(select cast(avg(case e when b then 11 else 13 end) AS integer) from t1)*b*17,t1.e,t1.e) then 11* -c when t1.f in (select min(e)*count(distinct c) from t1 union select  - - - -max(e) | cast(avg((d)) AS integer) from t1) then (c) else e end)))) or d<17}
} {400}
do_test randexpr-2.2090 {
  db eval {SELECT case when case when t1.a*~t1.a-19-c | 17+t1.d*f*c=d then f else  -13 end+t1.b+a in (t1.f,t1.d,t1.f) and (not c=11) and t1.e<>f then coalesce((select f from t1 where t1.d not in (t1.e,f,11)), -17) else f end-b FROM t1 WHERE NOT (not exists(select 1 from t1 where +d between d*13 and ((abs(13+e+e)/abs(+case when not t1.c in (~(select cast(avg(case e when b then 11 else 13 end) AS integer) from t1)*b*17,t1.e,t1.e) then 11* -c when t1.f in (select min(e)*count(distinct c) from t1 union select  - - - -max(e) | cast(avg((d)) AS integer) from t1) then (c) else e end)))) or d<17)}
} {}
do_test randexpr-2.2091 {
  db eval {SELECT case when case when t1.a*~t1.a-19-c & 17+t1.d*f*c=d then f else  -13 end+t1.b+a in (t1.f,t1.d,t1.f) and (not c=11) and t1.e<>f then coalesce((select f from t1 where t1.d not in (t1.e,f,11)), -17) else f end-b FROM t1 WHERE not exists(select 1 from t1 where +d between d*13 and ((abs(13+e+e)/abs(+case when not t1.c in (~(select cast(avg(case e when b then 11 else 13 end) AS integer) from t1)*b*17,t1.e,t1.e) then 11* -c when t1.f in (select min(e)*count(distinct c) from t1 union select  - - - -max(e) | cast(avg((d)) AS integer) from t1) then (c) else e end)))) or d<17}
} {400}
do_test randexpr-2.2092 {
  db eval {SELECT coalesce((select c from t1 where t1.b between t1.b and  -17),coalesce((select  -t1.e from t1 where (select count(distinct coalesce((select case t1.b-t1.a*(b)*13 when 11 then (a) else 11 end from t1 where a not in ((t1.e),c,11) and e>b),13)) from t1) in (t1.d,b,13) and not t1.b<13 or 11<> -17 or (11)>17 or t1.f not between b and (t1.a)),(b))) FROM t1 WHERE ((+case +d when f then (d) else case t1.f-(b)-11 when d then  -t1.c else a end end not in ( -17,(t1.d),13) and (11 not in ((c),t1.f,t1.d)) and (e in (select 13 from t1 union select t1.a from t1) and d in (select t1.e from t1 union select 19 from t1))) or exists(select 1 from t1 where  -t1.a= -t1.d)) and exists(select 1 from t1 where t1.b not between f and e or 19>=t1.d)}
} {}
do_test randexpr-2.2093 {
  db eval {SELECT coalesce((select c from t1 where t1.b between t1.b and  -17),coalesce((select  -t1.e from t1 where (select count(distinct coalesce((select case t1.b-t1.a*(b)*13 when 11 then (a) else 11 end from t1 where a not in ((t1.e),c,11) and e>b),13)) from t1) in (t1.d,b,13) and not t1.b<13 or 11<> -17 or (11)>17 or t1.f not between b and (t1.a)),(b))) FROM t1 WHERE NOT (((+case +d when f then (d) else case t1.f-(b)-11 when d then  -t1.c else a end end not in ( -17,(t1.d),13) and (11 not in ((c),t1.f,t1.d)) and (e in (select 13 from t1 union select t1.a from t1) and d in (select t1.e from t1 union select 19 from t1))) or exists(select 1 from t1 where  -t1.a= -t1.d)) and exists(select 1 from t1 where t1.b not between f and e or 19>=t1.d))}
} {-500}
do_test randexpr-2.2094 {
  db eval {SELECT case d when f then case when (abs(coalesce((select ~f*case when t1.f<(select  -count(distinct (select count(*)-min(13) from t1)) from t1) then d when t1.d between t1.b and f and not (t1.b between ( -t1.f) and f) then  -d else b end-b | t1.f*17 from t1 where ((d>t1.d))),17))/abs(11))-13=t1.c then a else 11 end else b end FROM t1 WHERE t1.b between coalesce((select case when coalesce((select t1.c from t1 where not ((t1.a>=11+17 and (13+(11)<>13))) and b<=c and c in (c, -c,(e)) and d not in (f,b,c) or t1.d>=13 and 13 between 19 and a),d) not between 13-case when t1.f<>t1.b then t1.f else t1.c end | d and d then b when c<c then 13 else 11 end*t1.e from t1 where b>= -d),19) and c}
} {}
do_test randexpr-2.2095 {
  db eval {SELECT case d when f then case when (abs(coalesce((select ~f*case when t1.f<(select  -count(distinct (select count(*)-min(13) from t1)) from t1) then d when t1.d between t1.b and f and not (t1.b between ( -t1.f) and f) then  -d else b end-b | t1.f*17 from t1 where ((d>t1.d))),17))/abs(11))-13=t1.c then a else 11 end else b end FROM t1 WHERE NOT (t1.b between coalesce((select case when coalesce((select t1.c from t1 where not ((t1.a>=11+17 and (13+(11)<>13))) and b<=c and c in (c, -c,(e)) and d not in (f,b,c) or t1.d>=13 and 13 between 19 and a),d) not between 13-case when t1.f<>t1.b then t1.f else t1.c end | d and d then b when c<c then 13 else 11 end*t1.e from t1 where b>= -d),19) and c)}
} {200}
do_test randexpr-2.2096 {
  db eval {SELECT case d when f then case when (abs(coalesce((select ~f*case when t1.f<(select  -count(distinct (select count(*)-min(13) from t1)) from t1) then d when t1.d between t1.b and f and not (t1.b between ( -t1.f) and f) then  -d else b end-b & t1.f*17 from t1 where ((d>t1.d))),17))/abs(11))-13=t1.c then a else 11 end else b end FROM t1 WHERE NOT (t1.b between coalesce((select case when coalesce((select t1.c from t1 where not ((t1.a>=11+17 and (13+(11)<>13))) and b<=c and c in (c, -c,(e)) and d not in (f,b,c) or t1.d>=13 and 13 between 19 and a),d) not between 13-case when t1.f<>t1.b then t1.f else t1.c end | d and d then b when c<c then 13 else 11 end*t1.e from t1 where b>= -d),19) and c)}
} {200}
do_test randexpr-2.2097 {
  db eval {SELECT (coalesce((select case when exists(select 1 from t1 where case when (t1.b)>=f+e*coalesce((select max( -+t1.c) from t1 where case a when e then e else 11 end in (select 17 from t1 union select d from t1) or e not between d and a),t1.f) then ( -t1.d) else e end in (11,c,b)) then 17 else t1.f end+t1.f from t1 where not d in ((b),(f),11) and t1.f<f),19)) FROM t1 WHERE exists(select 1 from t1 where coalesce((select max(case when t1.d in (select  -a from t1 union select 11 from t1) then t1.b when case when t1.f not in (t1.d, -19,t1.e) and t1.a>=t1.b and 19<13 then 19 else 13 end<a then e else b end) from t1 where t1.f in (select +count(distinct  - -13)* - -case max(t1.f) when max(13) then (min(t1.c)) else (max(t1.b)) end from t1 union select cast(avg(t1.a) AS integer) from t1) or t1.e not in (b,17,e)), -17)>=19) and b not in (c,t1.a,d) or b between e and  -t1.f or t1.b between t1.e and c and t1.a<=t1.d}
} {}
do_test randexpr-2.2098 {
  db eval {SELECT (coalesce((select case when exists(select 1 from t1 where case when (t1.b)>=f+e*coalesce((select max( -+t1.c) from t1 where case a when e then e else 11 end in (select 17 from t1 union select d from t1) or e not between d and a),t1.f) then ( -t1.d) else e end in (11,c,b)) then 17 else t1.f end+t1.f from t1 where not d in ((b),(f),11) and t1.f<f),19)) FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(case when t1.d in (select  -a from t1 union select 11 from t1) then t1.b when case when t1.f not in (t1.d, -19,t1.e) and t1.a>=t1.b and 19<13 then 19 else 13 end<a then e else b end) from t1 where t1.f in (select +count(distinct  - -13)* - -case max(t1.f) when max(13) then (min(t1.c)) else (max(t1.b)) end from t1 union select cast(avg(t1.a) AS integer) from t1) or t1.e not in (b,17,e)), -17)>=19) and b not in (c,t1.a,d) or b between e and  -t1.f or t1.b between t1.e and c and t1.a<=t1.d)}
} {19}
do_test randexpr-2.2099 {
  db eval {SELECT 11+17+case when case 17 when coalesce((select max(d) from t1 where 13+(t1.c-e)+19+e-t1.e>=b and not 11 not in (19,t1.e,13) and (t1.f)>b),19)*19 then c else  -d end not in (c,19,t1.c) then d when d<=t1.d then 13 else 11 end+ -a FROM t1 WHERE coalesce((select max(~t1.f) from t1 where (13*t1.e)<=case when 17 | a<=t1.e then coalesce((select max(19) from t1 where case when not not exists(select 1 from t1 where 19 in (t1.d+19,11,t1.f) or not exists(select 1 from t1 where a<e)) then case when t1.d<(t1.b) then t1.d when 13>=t1.c then  - -11 else t1.b end else f end-f<=b),t1.b) else t1.e end),f)-19>=13}
} {328}
do_test randexpr-2.2100 {
  db eval {SELECT 11+17+case when case 17 when coalesce((select max(d) from t1 where 13+(t1.c-e)+19+e-t1.e>=b and not 11 not in (19,t1.e,13) and (t1.f)>b),19)*19 then c else  -d end not in (c,19,t1.c) then d when d<=t1.d then 13 else 11 end+ -a FROM t1 WHERE NOT (coalesce((select max(~t1.f) from t1 where (13*t1.e)<=case when 17 | a<=t1.e then coalesce((select max(19) from t1 where case when not not exists(select 1 from t1 where 19 in (t1.d+19,11,t1.f) or not exists(select 1 from t1 where a<e)) then case when t1.d<(t1.b) then t1.d when 13>=t1.c then  - -11 else t1.b end else f end-f<=b),t1.b) else t1.e end),f)-19>=13)}
} {}
do_test randexpr-2.2101 {
  db eval {SELECT coalesce((select max(t1.a+(select count(distinct 11-case when coalesce((select max(11) from t1 where t1.f<(t1.a)-t1.b),b) in (select ~abs(min(c-case when (case 13 when  -coalesce((select (t1.e) from t1 where  -a not in (f,t1.d,d)),(11)) then b else t1.e end not between b and  -t1.e) then e else t1.a end)) | count(*) from t1 union select  -min(17) from t1) then t1.a else t1.d end) from t1)-t1.b) from t1 where 17<t1.e),t1.e) FROM t1 WHERE case when not (not exists(select 1 from t1 where c*case when (a>11) then e else a end-t1.c+(d)*(13) in (select ~count(distinct (t1.f))+ -~ -count(distinct t1.e)+(min(13)) from t1 union select cast(avg(11) AS integer) from t1) or t1.e<>t1.f)) then f when not a<19 then coalesce((select max(11) from t1 where (t1.d) between  -d and  -t1.e or t1.f not between d and a and  -b=19),t1.b) else +t1.f end not between a and e}
} {-99}
do_test randexpr-2.2102 {
  db eval {SELECT coalesce((select max(t1.a+(select count(distinct 11-case when coalesce((select max(11) from t1 where t1.f<(t1.a)-t1.b),b) in (select ~abs(min(c-case when (case 13 when  -coalesce((select (t1.e) from t1 where  -a not in (f,t1.d,d)),(11)) then b else t1.e end not between b and  -t1.e) then e else t1.a end)) | count(*) from t1 union select  -min(17) from t1) then t1.a else t1.d end) from t1)-t1.b) from t1 where 17<t1.e),t1.e) FROM t1 WHERE NOT (case when not (not exists(select 1 from t1 where c*case when (a>11) then e else a end-t1.c+(d)*(13) in (select ~count(distinct (t1.f))+ -~ -count(distinct t1.e)+(min(13)) from t1 union select cast(avg(11) AS integer) from t1) or t1.e<>t1.f)) then f when not a<19 then coalesce((select max(11) from t1 where (t1.d) between  -d and  -t1.e or t1.f not between d and a and  -b=19),t1.b) else +t1.f end not between a and e)}
} {}
do_test randexpr-2.2103 {
  db eval {SELECT coalesce((select max(t1.a+(select count(distinct 11-case when coalesce((select max(11) from t1 where t1.f<(t1.a)-t1.b),b) in (select ~abs(min(c-case when (case 13 when  -coalesce((select (t1.e) from t1 where  -a not in (f,t1.d,d)),(11)) then b else t1.e end not between b and  -t1.e) then e else t1.a end)) & count(*) from t1 union select  -min(17) from t1) then t1.a else t1.d end) from t1)-t1.b) from t1 where 17<t1.e),t1.e) FROM t1 WHERE case when not (not exists(select 1 from t1 where c*case when (a>11) then e else a end-t1.c+(d)*(13) in (select ~count(distinct (t1.f))+ -~ -count(distinct t1.e)+(min(13)) from t1 union select cast(avg(11) AS integer) from t1) or t1.e<>t1.f)) then f when not a<19 then coalesce((select max(11) from t1 where (t1.d) between  -d and  -t1.e or t1.f not between d and a and  -b=19),t1.b) else +t1.f end not between a and e}
} {-99}
do_test randexpr-2.2104 {
  db eval {SELECT t1.b-case when 13 not between 13 and (select +count(*) from t1) then t1.e when +11 in (coalesce((select t1.f from t1 where d-((f))*coalesce((select d from t1 where 17 between ~(select max(d) | count(*) | cast(avg(e) AS integer)+count(*) from t1) and case when c<13 or 17>13 then a else e end-t1.b),e)-t1.a<=(t1.e)),19),b,13) then e else b end-t1.b FROM t1 WHERE t1.b>=coalesce((select max(d-c) from t1 where exists(select 1 from t1 where (~a*(select  -count(distinct 11-d*13+d+19) from t1)* -b in (f,t1.d-c,a-(abs(c)/abs(case when (abs(13- -(19))/abs(t1.f)) in (select c from t1 union select  -a from t1) then t1.c when b<=c then t1.a else  -13 end)))))),19)}
} {-500}
do_test randexpr-2.2105 {
  db eval {SELECT t1.b-case when 13 not between 13 and (select +count(*) from t1) then t1.e when +11 in (coalesce((select t1.f from t1 where d-((f))*coalesce((select d from t1 where 17 between ~(select max(d) | count(*) | cast(avg(e) AS integer)+count(*) from t1) and case when c<13 or 17>13 then a else e end-t1.b),e)-t1.a<=(t1.e)),19),b,13) then e else b end-t1.b FROM t1 WHERE NOT (t1.b>=coalesce((select max(d-c) from t1 where exists(select 1 from t1 where (~a*(select  -count(distinct 11-d*13+d+19) from t1)* -b in (f,t1.d-c,a-(abs(c)/abs(case when (abs(13- -(19))/abs(t1.f)) in (select c from t1 union select  -a from t1) then t1.c when b<=c then t1.a else  -13 end)))))),19))}
} {}
do_test randexpr-2.2106 {
  db eval {SELECT t1.b-case when 13 not between 13 and (select +count(*) from t1) then t1.e when +11 in (coalesce((select t1.f from t1 where d-((f))*coalesce((select d from t1 where 17 between ~(select max(d) & count(*) & cast(avg(e) AS integer)+count(*) from t1) and case when c<13 or 17>13 then a else e end-t1.b),e)-t1.a<=(t1.e)),19),b,13) then e else b end-t1.b FROM t1 WHERE t1.b>=coalesce((select max(d-c) from t1 where exists(select 1 from t1 where (~a*(select  -count(distinct 11-d*13+d+19) from t1)* -b in (f,t1.d-c,a-(abs(c)/abs(case when (abs(13- -(19))/abs(t1.f)) in (select c from t1 union select  -a from t1) then t1.c when b<=c then t1.a else  -13 end)))))),19)}
} {-500}
do_test randexpr-2.2107 {
  db eval {SELECT t1.f*case when c*case when t1.d*t1.b-(~19) in (select (cast(avg(d-t1.d) AS integer)) from t1 union select min(11)+cast(avg(e) AS integer) | abs(count(distinct t1.a) | min(19)) from t1) then t1.d when not 11 not in (d,t1.e,13) then t1.a else 11 end in (select (t1.c) from t1 union select 11 from t1) or t1.e not in (f, -t1.f,t1.e) then c else d end FROM t1 WHERE case when t1.e=t1.c and (abs(case when (11* -17 not in (c,t1.f-t1.c-coalesce((select max(c) from t1 where c in (select min(19) from t1 union select ~count(*)*max(t1.f) from t1)),a),t1.a)) then coalesce((select max(17) from t1 where  -b>=(t1.c)),19) else f end+19)/abs(t1.f))*t1.d between d and b then t1.b-t1.e else c end=19}
} {}
do_test randexpr-2.2108 {
  db eval {SELECT t1.f*case when c*case when t1.d*t1.b-(~19) in (select (cast(avg(d-t1.d) AS integer)) from t1 union select min(11)+cast(avg(e) AS integer) | abs(count(distinct t1.a) | min(19)) from t1) then t1.d when not 11 not in (d,t1.e,13) then t1.a else 11 end in (select (t1.c) from t1 union select 11 from t1) or t1.e not in (f, -t1.f,t1.e) then c else d end FROM t1 WHERE NOT (case when t1.e=t1.c and (abs(case when (11* -17 not in (c,t1.f-t1.c-coalesce((select max(c) from t1 where c in (select min(19) from t1 union select ~count(*)*max(t1.f) from t1)),a),t1.a)) then coalesce((select max(17) from t1 where  -b>=(t1.c)),19) else f end+19)/abs(t1.f))*t1.d between d and b then t1.b-t1.e else c end=19)}
} {240000}
do_test randexpr-2.2109 {
  db eval {SELECT t1.f*case when c*case when t1.d*t1.b-(~19) in (select (cast(avg(d-t1.d) AS integer)) from t1 union select min(11)+cast(avg(e) AS integer) & abs(count(distinct t1.a) & min(19)) from t1) then t1.d when not 11 not in (d,t1.e,13) then t1.a else 11 end in (select (t1.c) from t1 union select 11 from t1) or t1.e not in (f, -t1.f,t1.e) then c else d end FROM t1 WHERE NOT (case when t1.e=t1.c and (abs(case when (11* -17 not in (c,t1.f-t1.c-coalesce((select max(c) from t1 where c in (select min(19) from t1 union select ~count(*)*max(t1.f) from t1)),a),t1.a)) then coalesce((select max(17) from t1 where  -b>=(t1.c)),19) else f end+19)/abs(t1.f))*t1.d between d and b then t1.b-t1.e else c end=19)}
} {240000}
do_test randexpr-2.2110 {
  db eval {SELECT coalesce((select max((abs(t1.d)/abs((coalesce((select c from t1 where (abs(+f)/abs(t1.b))-t1.a between 13 and case (13+c+((abs(coalesce((select 11 from t1 where 11+19<b),case t1.f when t1.f then b else 11 end)*a)/abs(c)))+t1.f) when f then  -c else t1.f end),e)-t1.e*19)))) from t1 where e<e),t1.c) FROM t1 WHERE c in (select c+19 from t1 union select +t1.f from t1) and t1.e<case when case (abs(t1.a)/abs(t1.b))-coalesce((select (abs(e+t1.e | b)/abs(e))*13 from t1 where (c=11) and b< -f or 13=b or  -d< -(e)),b) when e then 11 else t1.e end between b and (19) then t1.b else c end}
} {}
do_test randexpr-2.2111 {
  db eval {SELECT coalesce((select max((abs(t1.d)/abs((coalesce((select c from t1 where (abs(+f)/abs(t1.b))-t1.a between 13 and case (13+c+((abs(coalesce((select 11 from t1 where 11+19<b),case t1.f when t1.f then b else 11 end)*a)/abs(c)))+t1.f) when f then  -c else t1.f end),e)-t1.e*19)))) from t1 where e<e),t1.c) FROM t1 WHERE NOT (c in (select c+19 from t1 union select +t1.f from t1) and t1.e<case when case (abs(t1.a)/abs(t1.b))-coalesce((select (abs(e+t1.e | b)/abs(e))*13 from t1 where (c=11) and b< -f or 13=b or  -d< -(e)),b) when e then 11 else t1.e end between b and (19) then t1.b else c end)}
} {300}
do_test randexpr-2.2112 {
  db eval {SELECT f+coalesce((select max(t1.f) from t1 where (case when 13<>a then (coalesce((select  -e from t1 where case coalesce((select case when 19 in (select t1.e from t1 union select f from t1) then b when t1.c=11 then a else (13) end from t1 where t1.a in (select ( -cast(avg(13) AS integer)+max(t1.e)) from t1 union select cast(avg(19) AS integer) from t1)),19) when f then f else ( -t1.c) end+17<=e and a>=t1.b or t1.c>=b),t1.e)) else e end)>=e),b)+f FROM t1 WHERE exists(select 1 from t1 where 17 in (select  -abs(case (min(t1.b)) when count(*)*max(a) then  -abs((max(e))) | ~max( -coalesce((select max(coalesce((select e from t1 where f>=11 or exists(select 1 from t1 where 11 not in (11,t1.c,f))),d)) from t1 where 13=t1.d and 17<>f),t1.d))+count(distinct t1.e) else count(*)+~cast(avg(t1.f) AS integer) end | count(distinct t1.a))+count(distinct t1.a) from t1 union select count(*) from t1))}
} {}
do_test randexpr-2.2113 {
  db eval {SELECT f+coalesce((select max(t1.f) from t1 where (case when 13<>a then (coalesce((select  -e from t1 where case coalesce((select case when 19 in (select t1.e from t1 union select f from t1) then b when t1.c=11 then a else (13) end from t1 where t1.a in (select ( -cast(avg(13) AS integer)+max(t1.e)) from t1 union select cast(avg(19) AS integer) from t1)),19) when f then f else ( -t1.c) end+17<=e and a>=t1.b or t1.c>=b),t1.e)) else e end)>=e),b)+f FROM t1 WHERE NOT (exists(select 1 from t1 where 17 in (select  -abs(case (min(t1.b)) when count(*)*max(a) then  -abs((max(e))) | ~max( -coalesce((select max(coalesce((select e from t1 where f>=11 or exists(select 1 from t1 where 11 not in (11,t1.c,f))),d)) from t1 where 13=t1.d and 17<>f),t1.d))+count(distinct t1.e) else count(*)+~cast(avg(t1.f) AS integer) end | count(distinct t1.a))+count(distinct t1.a) from t1 union select count(*) from t1)))}
} {1400}
do_test randexpr-2.2114 {
  db eval {SELECT case when case when (abs( -t1.b)/abs(case case case (select ~ -(+abs(case min(19) when (( -min(t1.e))) then count(distinct (t1.e)) else cast(avg(11) AS integer) end)) from t1) when t1.e then (select min(19) from t1) else 17 end when (13)-a*17 then t1.d else t1.a end when a then 19 else  -( -f) end))>=d then t1.e else 13 end between f and 19 then f when t1.c<=t1.a or (t1.b>(11)) then 11 else t1.b end FROM t1 WHERE t1.c in (select case when 11<17 then case when (t1.b*coalesce((select (abs((coalesce((select a-19 from t1 where t1.c between e and f and d<>17 and t1.d not between 19 and 19),a)))/abs(t1.c))+t1.b-17 from t1 where c=a), -t1.d)+c>t1.f) then  -13+(t1.e) when 11<>t1.c then 13 else t1.c end when 11=c then t1.c else (c) end from t1 union select t1.e from t1)}
} {}
do_test randexpr-2.2115 {
  db eval {SELECT case when case when (abs( -t1.b)/abs(case case case (select ~ -(+abs(case min(19) when (( -min(t1.e))) then count(distinct (t1.e)) else cast(avg(11) AS integer) end)) from t1) when t1.e then (select min(19) from t1) else 17 end when (13)-a*17 then t1.d else t1.a end when a then 19 else  -( -f) end))>=d then t1.e else 13 end between f and 19 then f when t1.c<=t1.a or (t1.b>(11)) then 11 else t1.b end FROM t1 WHERE NOT (t1.c in (select case when 11<17 then case when (t1.b*coalesce((select (abs((coalesce((select a-19 from t1 where t1.c between e and f and d<>17 and t1.d not between 19 and 19),a)))/abs(t1.c))+t1.b-17 from t1 where c=a), -t1.d)+c>t1.f) then  -13+(t1.e) when 11<>t1.c then 13 else t1.c end when 11=c then t1.c else (c) end from t1 union select t1.e from t1))}
} {11}
do_test randexpr-2.2116 {
  db eval {SELECT t1.e+coalesce((select case t1.a-case when t1.a in (case (abs(coalesce((select t1.e from t1 where t1.a>t1.b),~c))/abs(t1.b))* -(select count(distinct t1.c)-cast(avg(coalesce((select 19 from t1 where c not between (abs(b-11)/abs( -t1.e)) and (17)),17)) AS integer) from t1) when t1.e then f else 17 end,t1.c,t1.c) then d else t1.e end when d then 17 else 13 end from t1 where 11<11),t1.f) FROM t1 WHERE 11* -19 in (select case when ~coalesce((select t1.b from t1 where coalesce((select d from t1 where t1.a=17*~e+t1.d*case when 11< -~t1.b*t1.b*c+a then (c) else 19 end*a),e)>e),11)<=19 then t1.c when (not exists(select 1 from t1 where t1.d<17)) then b else c end from t1 union select t1.a from t1)}
} {}
do_test randexpr-2.2117 {
  db eval {SELECT t1.e+coalesce((select case t1.a-case when t1.a in (case (abs(coalesce((select t1.e from t1 where t1.a>t1.b),~c))/abs(t1.b))* -(select count(distinct t1.c)-cast(avg(coalesce((select 19 from t1 where c not between (abs(b-11)/abs( -t1.e)) and (17)),17)) AS integer) from t1) when t1.e then f else 17 end,t1.c,t1.c) then d else t1.e end when d then 17 else 13 end from t1 where 11<11),t1.f) FROM t1 WHERE NOT (11* -19 in (select case when ~coalesce((select t1.b from t1 where coalesce((select d from t1 where t1.a=17*~e+t1.d*case when 11< -~t1.b*t1.b*c+a then (c) else 19 end*a),e)>e),11)<=19 then t1.c when (not exists(select 1 from t1 where t1.d<17)) then b else c end from t1 union select t1.a from t1))}
} {1100}
do_test randexpr-2.2118 {
  db eval {SELECT 19* -coalesce((select coalesce((select t1.d*17 from t1 where t1.b<=t1.b+17), -(a | 17)) from t1 where t1.d in (select case abs(count(*))*count(distinct (17)) when max(11) then abs(+max(13)-case  -cast(avg(t1.d) AS integer)- -(max(19))-count(distinct d) when min(t1.c) then cast(avg(c) AS integer) else count(distinct t1.f) end | max(c)) else max(t1.d) end from t1 union select count(*) from t1)),t1.f)-t1.e+c FROM t1 WHERE ~(abs(case 17 when d then coalesce((select t1.d from t1 where 13 in (select t1.d-f | case when (17 in (t1.a,19,t1.f)) then case when a*f in (select e from t1 union select t1.a from t1) or 11=t1.c or t1.a>=(19) and ( -b)<f or e<>13 then b when t1.e in (t1.c, -t1.b,a) then 19 else 19 end else a end from t1 union select t1.b from t1)),d) else 13 end)/abs(11))+19*t1.e in (e, -t1.e,a)}
} {}
do_test randexpr-2.2119 {
  db eval {SELECT 19* -coalesce((select coalesce((select t1.d*17 from t1 where t1.b<=t1.b+17), -(a | 17)) from t1 where t1.d in (select case abs(count(*))*count(distinct (17)) when max(11) then abs(+max(13)-case  -cast(avg(t1.d) AS integer)- -(max(19))-count(distinct d) when min(t1.c) then cast(avg(c) AS integer) else count(distinct t1.f) end | max(c)) else max(t1.d) end from t1 union select count(*) from t1)),t1.f)-t1.e+c FROM t1 WHERE NOT (~(abs(case 17 when d then coalesce((select t1.d from t1 where 13 in (select t1.d-f | case when (17 in (t1.a,19,t1.f)) then case when a*f in (select e from t1 union select t1.a from t1) or 11=t1.c or t1.a>=(19) and ( -b)<f or e<>13 then b when t1.e in (t1.c, -t1.b,a) then 19 else 19 end else a end from t1 union select t1.b from t1)),d) else 13 end)/abs(11))+19*t1.e in (e, -t1.e,a))}
} {-129400}
do_test randexpr-2.2120 {
  db eval {SELECT 19* -coalesce((select coalesce((select t1.d*17 from t1 where t1.b<=t1.b+17), -(a & 17)) from t1 where t1.d in (select case abs(count(*))*count(distinct (17)) when max(11) then abs(+max(13)-case  -cast(avg(t1.d) AS integer)- -(max(19))-count(distinct d) when min(t1.c) then cast(avg(c) AS integer) else count(distinct t1.f) end & max(c)) else max(t1.d) end from t1 union select count(*) from t1)),t1.f)-t1.e+c FROM t1 WHERE NOT (~(abs(case 17 when d then coalesce((select t1.d from t1 where 13 in (select t1.d-f | case when (17 in (t1.a,19,t1.f)) then case when a*f in (select e from t1 union select t1.a from t1) or 11=t1.c or t1.a>=(19) and ( -b)<f or e<>13 then b when t1.e in (t1.c, -t1.b,a) then 19 else 19 end else a end from t1 union select t1.b from t1)),d) else 13 end)/abs(11))+19*t1.e in (e, -t1.e,a))}
} {-129400}
do_test randexpr-2.2121 {
  db eval {SELECT case t1.f when f then t1.a-case d+t1.d+coalesce((select (select cast(avg( -case when t1.d in (select  -min(17)-count(*)+max(f) from t1 union select  -count(distinct 13) from t1) then t1.e else a end*a) AS integer) from t1)-t1.d from t1 where  -t1.b not in (11, -(t1.b),t1.d) and c in (select b from t1 union select 19 from t1) and t1.a in (select  -e from t1 union select t1.e from t1)),a)*t1.f when 19 then t1.f else 11 end else c end FROM t1 WHERE t1.c>11}
} {89}
do_test randexpr-2.2122 {
  db eval {SELECT case t1.f when f then t1.a-case d+t1.d+coalesce((select (select cast(avg( -case when t1.d in (select  -min(17)-count(*)+max(f) from t1 union select  -count(distinct 13) from t1) then t1.e else a end*a) AS integer) from t1)-t1.d from t1 where  -t1.b not in (11, -(t1.b),t1.d) and c in (select b from t1 union select 19 from t1) and t1.a in (select  -e from t1 union select t1.e from t1)),a)*t1.f when 19 then t1.f else 11 end else c end FROM t1 WHERE NOT (t1.c>11)}
} {}
do_test randexpr-2.2123 {
  db eval {SELECT case when (case when (e not in (e | e,17,e)) then 13 else t1.b end>+t1.b*f-b+t1.d-e) or 19 between b and t1.a then 11 when exists(select 1 from t1 where (t1.d) | t1.d in (case when (e>=(11)) or (t1.a)>=t1.f then c-b when t1.c<>t1.e then t1.a else (17) end,c,13)) then 17 else t1.b end FROM t1 WHERE (select min(case when a not in (coalesce((select 19 from t1 where t1.f<((abs(e)/abs(t1.a+e)) | d)-e),e),t1.f,t1.a) then c else 13 end)-(count(distinct d)-abs(count(distinct t1.c)-cast(avg(d) AS integer) | min(b)+(cast(avg(19) AS integer) | case count(distinct t1.c) when cast(avg( -t1.b) AS integer) then cast(avg(t1.a) AS integer) else max(13) end))) from t1) not between b | a and 19}
} {200}
do_test randexpr-2.2124 {
  db eval {SELECT case when (case when (e not in (e | e,17,e)) then 13 else t1.b end>+t1.b*f-b+t1.d-e) or 19 between b and t1.a then 11 when exists(select 1 from t1 where (t1.d) | t1.d in (case when (e>=(11)) or (t1.a)>=t1.f then c-b when t1.c<>t1.e then t1.a else (17) end,c,13)) then 17 else t1.b end FROM t1 WHERE NOT ((select min(case when a not in (coalesce((select 19 from t1 where t1.f<((abs(e)/abs(t1.a+e)) | d)-e),e),t1.f,t1.a) then c else 13 end)-(count(distinct d)-abs(count(distinct t1.c)-cast(avg(d) AS integer) | min(b)+(cast(avg(19) AS integer) | case count(distinct t1.c) when cast(avg( -t1.b) AS integer) then cast(avg(t1.a) AS integer) else max(13) end))) from t1) not between b | a and 19)}
} {}
do_test randexpr-2.2125 {
  db eval {SELECT case when (case when (e not in (e & e,17,e)) then 13 else t1.b end>+t1.b*f-b+t1.d-e) or 19 between b and t1.a then 11 when exists(select 1 from t1 where (t1.d) & t1.d in (case when (e>=(11)) or (t1.a)>=t1.f then c-b when t1.c<>t1.e then t1.a else (17) end,c,13)) then 17 else t1.b end FROM t1 WHERE (select min(case when a not in (coalesce((select 19 from t1 where t1.f<((abs(e)/abs(t1.a+e)) | d)-e),e),t1.f,t1.a) then c else 13 end)-(count(distinct d)-abs(count(distinct t1.c)-cast(avg(d) AS integer) | min(b)+(cast(avg(19) AS integer) | case count(distinct t1.c) when cast(avg( -t1.b) AS integer) then cast(avg(t1.a) AS integer) else max(13) end))) from t1) not between b | a and 19}
} {200}
do_test randexpr-2.2126 {
  db eval {SELECT case when case when t1.c+13<13 then 11 when (t1.b) not in (t1.b,e,t1.c) then t1.f else  -t1.c end- -a | 13 in (select max(a) from t1 union select count(distinct 17)* -case count(*) when count(*) then  -((count(distinct 17))) else max(t1.b) end | ( -count(*)) from t1) and e<=17 and t1.c<=d then coalesce((select max(coalesce((select max(e) from t1 where t1.f not in (e,17,t1.b) and d= -t1.b),t1.d)) from t1 where t1.d<f),b) when  -c not between f and t1.f then b else t1.a end FROM t1 WHERE a<=case b when coalesce((select max(19) from t1 where (coalesce((select max(11) from t1 where ((not coalesce((select max(t1.e) from t1 where  -19 in (select count(*) from t1 union select (max(t1.c)) from t1)),t1.a)-11 between f and t1.c))),case when exists(select 1 from t1 where  -(17)< -a) then 17*17 else a end) not in (17,b,t1.e)) or 17 between a and t1.f and  -a<11 and 19<=(t1.b)),t1.c) then ~case when 11>(f) then t1.e else 17 end else t1.c end-19}
} {200}
do_test randexpr-2.2127 {
  db eval {SELECT case when case when t1.c+13<13 then 11 when (t1.b) not in (t1.b,e,t1.c) then t1.f else  -t1.c end- -a | 13 in (select max(a) from t1 union select count(distinct 17)* -case count(*) when count(*) then  -((count(distinct 17))) else max(t1.b) end | ( -count(*)) from t1) and e<=17 and t1.c<=d then coalesce((select max(coalesce((select max(e) from t1 where t1.f not in (e,17,t1.b) and d= -t1.b),t1.d)) from t1 where t1.d<f),b) when  -c not between f and t1.f then b else t1.a end FROM t1 WHERE NOT (a<=case b when coalesce((select max(19) from t1 where (coalesce((select max(11) from t1 where ((not coalesce((select max(t1.e) from t1 where  -19 in (select count(*) from t1 union select (max(t1.c)) from t1)),t1.a)-11 between f and t1.c))),case when exists(select 1 from t1 where  -(17)< -a) then 17*17 else a end) not in (17,b,t1.e)) or 17 between a and t1.f and  -a<11 and 19<=(t1.b)),t1.c) then ~case when 11>(f) then t1.e else 17 end else t1.c end-19)}
} {}
do_test randexpr-2.2128 {
  db eval {SELECT case when case when t1.c+13<13 then 11 when (t1.b) not in (t1.b,e,t1.c) then t1.f else  -t1.c end- -a & 13 in (select max(a) from t1 union select count(distinct 17)* -case count(*) when count(*) then  -((count(distinct 17))) else max(t1.b) end & ( -count(*)) from t1) and e<=17 and t1.c<=d then coalesce((select max(coalesce((select max(e) from t1 where t1.f not in (e,17,t1.b) and d= -t1.b),t1.d)) from t1 where t1.d<f),b) when  -c not between f and t1.f then b else t1.a end FROM t1 WHERE a<=case b when coalesce((select max(19) from t1 where (coalesce((select max(11) from t1 where ((not coalesce((select max(t1.e) from t1 where  -19 in (select count(*) from t1 union select (max(t1.c)) from t1)),t1.a)-11 between f and t1.c))),case when exists(select 1 from t1 where  -(17)< -a) then 17*17 else a end) not in (17,b,t1.e)) or 17 between a and t1.f and  -a<11 and 19<=(t1.b)),t1.c) then ~case when 11>(f) then t1.e else 17 end else t1.c end-19}
} {200}
do_test randexpr-2.2129 {
  db eval {SELECT coalesce((select case t1.e when coalesce((select max(e- -coalesce((select 17-d-e from t1 where ( -e*(d)>t1.c and 17=(t1.b) or not 11>(a) and b not between ((f)) and t1.d)),t1.c)-f-(f)*b+t1.a) from t1 where f<>13),t1.b) then t1.c else t1.b end from t1 where c in (select t1.a from t1 union select (t1.e) from t1)),e) FROM t1 WHERE (c in (select ~abs(cast(avg(19) AS integer))- -(case (++abs(max( -(select case case ( -abs(+cast(avg(b) AS integer) | count(distinct t1.b*17)*min( -11)*count(distinct t1.e))) when (max( -t1.b)) then count(distinct e) else max(11) end when  -min(d) then count(*) else cast(avg(t1.a) AS integer) end from t1))*max(11))) when min(b) then max(19) else (count(*)) end)* -(max(t1.a))-count(*) from t1 union select count(distinct t1.a) from t1))}
} {}
do_test randexpr-2.2130 {
  db eval {SELECT coalesce((select case t1.e when coalesce((select max(e- -coalesce((select 17-d-e from t1 where ( -e*(d)>t1.c and 17=(t1.b) or not 11>(a) and b not between ((f)) and t1.d)),t1.c)-f-(f)*b+t1.a) from t1 where f<>13),t1.b) then t1.c else t1.b end from t1 where c in (select t1.a from t1 union select (t1.e) from t1)),e) FROM t1 WHERE NOT ((c in (select ~abs(cast(avg(19) AS integer))- -(case (++abs(max( -(select case case ( -abs(+cast(avg(b) AS integer) | count(distinct t1.b*17)*min( -11)*count(distinct t1.e))) when (max( -t1.b)) then count(distinct e) else max(11) end when  -min(d) then count(*) else cast(avg(t1.a) AS integer) end from t1))*max(11))) when min(b) then max(19) else (count(*)) end)* -(max(t1.a))-count(*) from t1 union select count(distinct t1.a) from t1)))}
} {500}
do_test randexpr-2.2131 {
  db eval {SELECT t1.e+13-(abs(f)/abs(e | coalesce((select case when (f>=~t1.c*case t1.a when  -d then (11) else 17 end*19) then case a when t1.e then b else e end else t1.c end from t1 where e in (select t1.a from t1 union select a from t1) or t1.d not in (f,f,17) and t1.b not between f and 17 and e=c),t1.c)*17+d+t1.d)) FROM t1 WHERE coalesce((select ~f+t1.c*t1.d | t1.d*t1.d-t1.b from t1 where t1.b | t1.a between case when (abs(coalesce((select f from t1 where t1.e between 11-17 and t1.c),e)-t1.d*b)/abs(((d))))-d between t1.b and d then a when  -(f) between e and t1.e then t1.a else a end and t1.b),t1.a)-11=d}
} {}
do_test randexpr-2.2132 {
  db eval {SELECT t1.e+13-(abs(f)/abs(e | coalesce((select case when (f>=~t1.c*case t1.a when  -d then (11) else 17 end*19) then case a when t1.e then b else e end else t1.c end from t1 where e in (select t1.a from t1 union select a from t1) or t1.d not in (f,f,17) and t1.b not between f and 17 and e=c),t1.c)*17+d+t1.d)) FROM t1 WHERE NOT (coalesce((select ~f+t1.c*t1.d | t1.d*t1.d-t1.b from t1 where t1.b | t1.a between case when (abs(coalesce((select f from t1 where t1.e between 11-17 and t1.c),e)-t1.d*b)/abs(((d))))-d between t1.b and d then a when  -(f) between e and t1.e then t1.a else a end and t1.b),t1.a)-11=d)}
} {513}
do_test randexpr-2.2133 {
  db eval {SELECT t1.e+13-(abs(f)/abs(e & coalesce((select case when (f>=~t1.c*case t1.a when  -d then (11) else 17 end*19) then case a when t1.e then b else e end else t1.c end from t1 where e in (select t1.a from t1 union select a from t1) or t1.d not in (f,f,17) and t1.b not between f and 17 and e=c),t1.c)*17+d+t1.d)) FROM t1 WHERE NOT (coalesce((select ~f+t1.c*t1.d | t1.d*t1.d-t1.b from t1 where t1.b | t1.a between case when (abs(coalesce((select f from t1 where t1.e between 11-17 and t1.c),e)-t1.d*b)/abs(((d))))-d between t1.b and d then a when  -(f) between e and t1.e then t1.a else a end and t1.b),t1.a)-11=d)}
} {511}
do_test randexpr-2.2134 {
  db eval {SELECT +(abs(~+13+(abs(t1.c)/abs(t1.c | coalesce((select t1.a from t1 where (select min(t1.c) from t1)<>(abs(t1.f | coalesce((select c from t1 where b=17),f)-b)/abs(coalesce((select max(d-t1.e) from t1 where not exists(select 1 from t1 where t1.e in (select f from t1 union select t1.d from t1))),19)*e+19)) or t1.a in (select 13 from t1 union select t1.d from t1) and (b)<= -t1.f),11))))/abs(e)) FROM t1 WHERE t1.e<>coalesce((select case 17 when f then coalesce((select max(t1.c) from t1 where coalesce((select coalesce((select ~e from t1 where not 17<=e | 17),11)+t1.d+t1.e from t1 where (e>=f or (not t1.e>=t1.a or e between f and t1.f))),t1.b) not in (13,17,c) or t1.a> -t1.d),19) else t1.c end from t1 where (not 17 not in (t1.b,11,b) and f>=t1.f) or 19<=t1.f),d)-11}
} {0}
do_test randexpr-2.2135 {
  db eval {SELECT +(abs(~+13+(abs(t1.c)/abs(t1.c | coalesce((select t1.a from t1 where (select min(t1.c) from t1)<>(abs(t1.f | coalesce((select c from t1 where b=17),f)-b)/abs(coalesce((select max(d-t1.e) from t1 where not exists(select 1 from t1 where t1.e in (select f from t1 union select t1.d from t1))),19)*e+19)) or t1.a in (select 13 from t1 union select t1.d from t1) and (b)<= -t1.f),11))))/abs(e)) FROM t1 WHERE NOT (t1.e<>coalesce((select case 17 when f then coalesce((select max(t1.c) from t1 where coalesce((select coalesce((select ~e from t1 where not 17<=e | 17),11)+t1.d+t1.e from t1 where (e>=f or (not t1.e>=t1.a or e between f and t1.f))),t1.b) not in (13,17,c) or t1.a> -t1.d),19) else t1.c end from t1 where (not 17 not in (t1.b,11,b) and f>=t1.f) or 19<=t1.f),d)-11)}
} {}
do_test randexpr-2.2136 {
  db eval {SELECT +(abs(~+13+(abs(t1.c)/abs(t1.c & coalesce((select t1.a from t1 where (select min(t1.c) from t1)<>(abs(t1.f & coalesce((select c from t1 where b=17),f)-b)/abs(coalesce((select max(d-t1.e) from t1 where not exists(select 1 from t1 where t1.e in (select f from t1 union select t1.d from t1))),19)*e+19)) or t1.a in (select 13 from t1 union select t1.d from t1) and (b)<= -t1.f),11))))/abs(e)) FROM t1 WHERE t1.e<>coalesce((select case 17 when f then coalesce((select max(t1.c) from t1 where coalesce((select coalesce((select ~e from t1 where not 17<=e | 17),11)+t1.d+t1.e from t1 where (e>=f or (not t1.e>=t1.a or e between f and t1.f))),t1.b) not in (13,17,c) or t1.a> -t1.d),19) else t1.c end from t1 where (not 17 not in (t1.b,11,b) and f>=t1.f) or 19<=t1.f),d)-11}
} {0}
do_test randexpr-2.2137 {
  db eval {SELECT (case when not case when ((e not between d and case when not exists(select 1 from t1 where 11>=(a)*t1.d*11 or  -(d) not in (a,11,t1.f)) then f else ~f end or not d<>t1.e or t1.c in (a,t1.d,t1.c))) then case when  -b between 11 and b then (select count(distinct 17) from t1) when t1.e<>11 then f else d end else t1.d end<=a then (abs(t1.d)/abs(e)) when t1.d<t1.f then d else t1.e end) FROM t1 WHERE case when ~ -13*case when (not exists(select 1 from t1 where t1.c in (a,case case when 11<=17 then e else 13 end when 11 then 11 else b end,f))) then t1.a when not exists(select 1 from t1 where (t1.a>=t1.b and 17=t1.e)) then f else 19 end-t1.a*t1.a-e<=t1.b and 17 in (t1.d,13,t1.b) then c else t1.b end<>t1.b or not exists(select 1 from t1 where 17 between (d) and ( -(t1.d)))}
} {0}
do_test randexpr-2.2138 {
  db eval {SELECT (case when not case when ((e not between d and case when not exists(select 1 from t1 where 11>=(a)*t1.d*11 or  -(d) not in (a,11,t1.f)) then f else ~f end or not d<>t1.e or t1.c in (a,t1.d,t1.c))) then case when  -b between 11 and b then (select count(distinct 17) from t1) when t1.e<>11 then f else d end else t1.d end<=a then (abs(t1.d)/abs(e)) when t1.d<t1.f then d else t1.e end) FROM t1 WHERE NOT (case when ~ -13*case when (not exists(select 1 from t1 where t1.c in (a,case case when 11<=17 then e else 13 end when 11 then 11 else b end,f))) then t1.a when not exists(select 1 from t1 where (t1.a>=t1.b and 17=t1.e)) then f else 19 end-t1.a*t1.a-e<=t1.b and 17 in (t1.d,13,t1.b) then c else t1.b end<>t1.b or not exists(select 1 from t1 where 17 between (d) and ( -(t1.d))))}
} {}
do_test randexpr-2.2139 {
  db eval {SELECT t1.b+case when f+f not in (c+case when t1.f<>d then 11 when f between 11 and t1.d then 11 else 13 end,e,(t1.f)) and not exists(select 1 from t1 where (exists(select 1 from t1 where 19<11)) or 11 in ((t1.d),t1.c,b) and t1.b>13) and t1.b=t1.b then (abs(t1.d)/abs(13)) when a not between t1.c and 19 then t1.f else 19 end+13*17-t1.e FROM t1 WHERE not exists(select 1 from t1 where (exists(select 1 from t1 where t1.c>=19)))}
} {}
do_test randexpr-2.2140 {
  db eval {SELECT t1.b+case when f+f not in (c+case when t1.f<>d then 11 when f between 11 and t1.d then 11 else 13 end,e,(t1.f)) and not exists(select 1 from t1 where (exists(select 1 from t1 where 19<11)) or 11 in ((t1.d),t1.c,b) and t1.b>13) and t1.b=t1.b then (abs(t1.d)/abs(13)) when a not between t1.c and 19 then t1.f else 19 end+13*17-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where (exists(select 1 from t1 where t1.c>=19))))}
} {-49}
do_test randexpr-2.2141 {
  db eval {SELECT (case when f>(select abs((((count(*)-+cast(avg(d) AS integer)))) | count(distinct a)) from t1) then case when (abs(coalesce((select max(t1.d) from t1 where coalesce((select max(case when t1.b between t1.f and a then  -f when f<> -b then t1.e else  -19 end) from t1 where not exists(select 1 from t1 where t1.c not in (t1.f,t1.c,t1.a))),t1.c)<=b), -t1.c))/abs(t1.a))<t1.b and exists(select 1 from t1 where t1.c between d and t1.f) then t1.a else t1.d end when a not in (e, -t1.f,t1.a) or f in (d,t1.c,(f)) and d in (t1.e,17,c) then 19 else (b) end)+t1.b FROM t1 WHERE t1.d>11}
} {600}
do_test randexpr-2.2142 {
  db eval {SELECT (case when f>(select abs((((count(*)-+cast(avg(d) AS integer)))) | count(distinct a)) from t1) then case when (abs(coalesce((select max(t1.d) from t1 where coalesce((select max(case when t1.b between t1.f and a then  -f when f<> -b then t1.e else  -19 end) from t1 where not exists(select 1 from t1 where t1.c not in (t1.f,t1.c,t1.a))),t1.c)<=b), -t1.c))/abs(t1.a))<t1.b and exists(select 1 from t1 where t1.c between d and t1.f) then t1.a else t1.d end when a not in (e, -t1.f,t1.a) or f in (d,t1.c,(f)) and d in (t1.e,17,c) then 19 else (b) end)+t1.b FROM t1 WHERE NOT (t1.d>11)}
} {}
do_test randexpr-2.2143 {
  db eval {SELECT (case when f>(select abs((((count(*)-+cast(avg(d) AS integer)))) & count(distinct a)) from t1) then case when (abs(coalesce((select max(t1.d) from t1 where coalesce((select max(case when t1.b between t1.f and a then  -f when f<> -b then t1.e else  -19 end) from t1 where not exists(select 1 from t1 where t1.c not in (t1.f,t1.c,t1.a))),t1.c)<=b), -t1.c))/abs(t1.a))<t1.b and exists(select 1 from t1 where t1.c between d and t1.f) then t1.a else t1.d end when a not in (e, -t1.f,t1.a) or f in (d,t1.c,(f)) and d in (t1.e,17,c) then 19 else (b) end)+t1.b FROM t1 WHERE t1.d>11}
} {600}
do_test randexpr-2.2144 {
  db eval {SELECT (abs(+coalesce((select t1.f from t1 where not exists(select 1 from t1 where (((c)<=t1.a)))),f+(select count(distinct t1.b) from t1)*t1.b+case when case (select count(*) from t1) when coalesce((select max(t1.f-e+13) from t1 where (t1.e>a and 19 not in (13,b,19))),t1.c)+e then t1.b else t1.b end in (select  -c from t1 union select c from t1) then f when t1.a>t1.e then t1.c else d end+ -13))/abs((t1.f))) FROM t1 WHERE coalesce((select t1.f from t1 where a>=e),13) between  -c and t1.a}
} {1}
do_test randexpr-2.2145 {
  db eval {SELECT (abs(+coalesce((select t1.f from t1 where not exists(select 1 from t1 where (((c)<=t1.a)))),f+(select count(distinct t1.b) from t1)*t1.b+case when case (select count(*) from t1) when coalesce((select max(t1.f-e+13) from t1 where (t1.e>a and 19 not in (13,b,19))),t1.c)+e then t1.b else t1.b end in (select  -c from t1 union select c from t1) then f when t1.a>t1.e then t1.c else d end+ -13))/abs((t1.f))) FROM t1 WHERE NOT (coalesce((select t1.f from t1 where a>=e),13) between  -c and t1.a)}
} {}
do_test randexpr-2.2146 {
  db eval {SELECT coalesce((select max(~19) from t1 where t1.a between case t1.c when t1.b then t1.e else +~f end and case when 19 not in (e+b,t1.e-d,(select max(e) from t1)) then t1.a else case 13 when case e when e then t1.f else f end-a+t1.f then 19 else t1.b end+11 end-t1.d-17 or t1.b<>t1.a),13)-t1.b | 11 FROM t1 WHERE (+(17)-(select cast(avg( -((17)*case t1.b when 13+f then t1.f else t1.b end)) AS integer) | case case cast(avg(e) AS integer) when abs((case (~min(t1.c)) when max(t1.e) then cast(avg(t1.b) AS integer) else (( -count(*))) end-max(b)))+(min(t1.c)) then  -cast(avg(c) AS integer) else min(f) end when cast(avg(17) AS integer) then max(f) else (min(d)) end from t1)+e+c*19>=13)}
} {-209}
do_test randexpr-2.2147 {
  db eval {SELECT coalesce((select max(~19) from t1 where t1.a between case t1.c when t1.b then t1.e else +~f end and case when 19 not in (e+b,t1.e-d,(select max(e) from t1)) then t1.a else case 13 when case e when e then t1.f else f end-a+t1.f then 19 else t1.b end+11 end-t1.d-17 or t1.b<>t1.a),13)-t1.b | 11 FROM t1 WHERE NOT ((+(17)-(select cast(avg( -((17)*case t1.b when 13+f then t1.f else t1.b end)) AS integer) | case case cast(avg(e) AS integer) when abs((case (~min(t1.c)) when max(t1.e) then cast(avg(t1.b) AS integer) else (( -count(*))) end-max(b)))+(min(t1.c)) then  -cast(avg(c) AS integer) else min(f) end when cast(avg(17) AS integer) then max(f) else (min(d)) end from t1)+e+c*19>=13))}
} {}
do_test randexpr-2.2148 {
  db eval {SELECT coalesce((select max(~19) from t1 where t1.a between case t1.c when t1.b then t1.e else +~f end and case when 19 not in (e+b,t1.e-d,(select max(e) from t1)) then t1.a else case 13 when case e when e then t1.f else f end-a+t1.f then 19 else t1.b end+11 end-t1.d-17 or t1.b<>t1.a),13)-t1.b & 11 FROM t1 WHERE (+(17)-(select cast(avg( -((17)*case t1.b when 13+f then t1.f else t1.b end)) AS integer) | case case cast(avg(e) AS integer) when abs((case (~min(t1.c)) when max(t1.e) then cast(avg(t1.b) AS integer) else (( -count(*))) end-max(b)))+(min(t1.c)) then  -cast(avg(c) AS integer) else min(f) end when cast(avg(17) AS integer) then max(f) else (min(d)) end from t1)+e+c*19>=13)}
} {0}
do_test randexpr-2.2149 {
  db eval {SELECT coalesce((select max(e) from t1 where 11>=coalesce((select max(b) from t1 where (abs(13)/abs(coalesce((select max(11) from t1 where f not between t1.a and t1.d),t1.d)))=case when 11 in (select (11 | d)-coalesce((select t1.e | coalesce((select t1.e from t1 where t1.f in (select 13 from t1 union select t1.c from t1) and d in (select t1.b from t1 union select 17 from t1)),(c))-17-19 from t1 where (t1.b)<=t1.b),(d)) from t1 union select t1.d from t1) then t1.a else (b) end),c)),19) FROM t1 WHERE ~t1.b not in (~++(select (case ~ -min( -11) when abs(count(*)*count(*)) then +~max(t1.a-11 | (19)) else case abs((cast(avg(f) AS integer)))-count(distinct t1.a) when (( -(max(a)))) then (min(t1.d)) else (min(a)) end end) from t1)+(abs(+t1.b)/abs(a))-t1.f+~t1.d+b+t1.c,13,e)}
} {19}
do_test randexpr-2.2150 {
  db eval {SELECT coalesce((select max(e) from t1 where 11>=coalesce((select max(b) from t1 where (abs(13)/abs(coalesce((select max(11) from t1 where f not between t1.a and t1.d),t1.d)))=case when 11 in (select (11 | d)-coalesce((select t1.e | coalesce((select t1.e from t1 where t1.f in (select 13 from t1 union select t1.c from t1) and d in (select t1.b from t1 union select 17 from t1)),(c))-17-19 from t1 where (t1.b)<=t1.b),(d)) from t1 union select t1.d from t1) then t1.a else (b) end),c)),19) FROM t1 WHERE NOT (~t1.b not in (~++(select (case ~ -min( -11) when abs(count(*)*count(*)) then +~max(t1.a-11 | (19)) else case abs((cast(avg(f) AS integer)))-count(distinct t1.a) when (( -(max(a)))) then (min(t1.d)) else (min(a)) end end) from t1)+(abs(+t1.b)/abs(a))-t1.f+~t1.d+b+t1.c,13,e))}
} {}
do_test randexpr-2.2151 {
  db eval {SELECT coalesce((select max(e) from t1 where 11>=coalesce((select max(b) from t1 where (abs(13)/abs(coalesce((select max(11) from t1 where f not between t1.a and t1.d),t1.d)))=case when 11 in (select (11 & d)-coalesce((select t1.e & coalesce((select t1.e from t1 where t1.f in (select 13 from t1 union select t1.c from t1) and d in (select t1.b from t1 union select 17 from t1)),(c))-17-19 from t1 where (t1.b)<=t1.b),(d)) from t1 union select t1.d from t1) then t1.a else (b) end),c)),19) FROM t1 WHERE ~t1.b not in (~++(select (case ~ -min( -11) when abs(count(*)*count(*)) then +~max(t1.a-11 | (19)) else case abs((cast(avg(f) AS integer)))-count(distinct t1.a) when (( -(max(a)))) then (min(t1.d)) else (min(a)) end end) from t1)+(abs(+t1.b)/abs(a))-t1.f+~t1.d+b+t1.c,13,e)}
} {19}
do_test randexpr-2.2152 {
  db eval {SELECT (abs(+b)/abs(coalesce((select max(t1.b) from t1 where (not t1.a not between t1.c-(abs(b)/abs(d)) and c)),19)+19*t1.e | t1.e))-t1.f*coalesce((select case d when e*t1.d*f then 17 else t1.c+t1.c end from t1 where t1.b>=(select count(*) from t1)),+f+t1.b-t1.b+19- -b) FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where not (b>=(abs(case when case (select count(*) from t1) when t1.a then a+case t1.f when a+ -t1.a*t1.d then 19 else e end+t1.a+f else  -d end>=e then f when t1.b>=t1.d or not d<f or t1.f>t1.b then t1.e else d end)/abs(f)) or a>e))))}
} {-360000}
do_test randexpr-2.2153 {
  db eval {SELECT (abs(+b)/abs(coalesce((select max(t1.b) from t1 where (not t1.a not between t1.c-(abs(b)/abs(d)) and c)),19)+19*t1.e | t1.e))-t1.f*coalesce((select case d when e*t1.d*f then 17 else t1.c+t1.c end from t1 where t1.b>=(select count(*) from t1)),+f+t1.b-t1.b+19- -b) FROM t1 WHERE NOT (not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where not (b>=(abs(case when case (select count(*) from t1) when t1.a then a+case t1.f when a+ -t1.a*t1.d then 19 else e end+t1.a+f else  -d end>=e then f when t1.b>=t1.d or not d<f or t1.f>t1.b then t1.e else d end)/abs(f)) or a>e)))))}
} {}
do_test randexpr-2.2154 {
  db eval {SELECT (abs(+b)/abs(coalesce((select max(t1.b) from t1 where (not t1.a not between t1.c-(abs(b)/abs(d)) and c)),19)+19*t1.e & t1.e))-t1.f*coalesce((select case d when e*t1.d*f then 17 else t1.c+t1.c end from t1 where t1.b>=(select count(*) from t1)),+f+t1.b-t1.b+19- -b) FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where not (b>=(abs(case when case (select count(*) from t1) when t1.a then a+case t1.f when a+ -t1.a*t1.d then 19 else e end+t1.a+f else  -d end>=e then f when t1.b>=t1.d or not d<f or t1.f>t1.b then t1.e else d end)/abs(f)) or a>e))))}
} {-360000}
do_test randexpr-2.2155 {
  db eval {SELECT (abs((select +abs(case count(*) when +max(19) then count(distinct b)*count(distinct (13+(select max(t1.d) from t1)* -a+t1.e*t1.b*a))+cast(avg(13) AS integer) | min(13)*cast(avg(c) AS integer)-count(distinct t1.e)-((min(f))) | cast(avg(17) AS integer)-( -cast(avg(( -t1.d)) AS integer))- -cast(avg(t1.d) AS integer) | count(*) else max(t1.f) end) from t1))/abs(t1.a)) FROM t1 WHERE b<=e or exists(select 1 from t1 where 17 in (select ~e+coalesce((select d from t1 where 11* -~+case when not (b) not between t1.f and b then  -~t1.c-11*+19+((b)) when f not between f and 11 then b else a end+11-(b)-t1.f<>17),d) from t1 union select t1.a from t1))}
} {6}
do_test randexpr-2.2156 {
  db eval {SELECT (abs((select +abs(case count(*) when +max(19) then count(distinct b)*count(distinct (13+(select max(t1.d) from t1)* -a+t1.e*t1.b*a))+cast(avg(13) AS integer) | min(13)*cast(avg(c) AS integer)-count(distinct t1.e)-((min(f))) | cast(avg(17) AS integer)-( -cast(avg(( -t1.d)) AS integer))- -cast(avg(t1.d) AS integer) | count(*) else max(t1.f) end) from t1))/abs(t1.a)) FROM t1 WHERE NOT (b<=e or exists(select 1 from t1 where 17 in (select ~e+coalesce((select d from t1 where 11* -~+case when not (b) not between t1.f and b then  -~t1.c-11*+19+((b)) when f not between f and 11 then b else a end+11-(b)-t1.f<>17),d) from t1 union select t1.a from t1)))}
} {}
do_test randexpr-2.2157 {
  db eval {SELECT (abs((select +abs(case count(*) when +max(19) then count(distinct b)*count(distinct (13+(select max(t1.d) from t1)* -a+t1.e*t1.b*a))+cast(avg(13) AS integer) & min(13)*cast(avg(c) AS integer)-count(distinct t1.e)-((min(f))) & cast(avg(17) AS integer)-( -cast(avg(( -t1.d)) AS integer))- -cast(avg(t1.d) AS integer) & count(*) else max(t1.f) end) from t1))/abs(t1.a)) FROM t1 WHERE b<=e or exists(select 1 from t1 where 17 in (select ~e+coalesce((select d from t1 where 11* -~+case when not (b) not between t1.f and b then  -~t1.c-11*+19+((b)) when f not between f and 11 then b else a end+11-(b)-t1.f<>17),d) from t1 union select t1.a from t1))}
} {6}
do_test randexpr-2.2158 {
  db eval {SELECT coalesce((select max(11) from t1 where c=(abs(coalesce((select case when t1.c-t1.f+coalesce((select max(b) from t1 where case when (11<>17) then t1.c else c end in (select b from t1 union select t1.b from t1) and 13=11),f)+t1.b>=t1.f then 11 when c>t1.f then 19 else 19 end from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (e>19)))),t1.d))/abs(b)) and  -t1.d between t1.b and 13 or 17<>t1.e), -((11))) FROM t1 WHERE case when case when (not exists(select 1 from t1 where 19 not between case when coalesce((select b from t1 where (abs(t1.c)/abs(17))+t1.e between case when not exists(select 1 from t1 where not a<=t1.e) then t1.e when d<t1.c then 17 else  -d end and f),e)<13 then t1.a else t1.c end and e)) then +t1.a else d end not in (e,t1.d,t1.a) then t1.a when a in (select 19 from t1 union select t1.a from t1) then 19 else  -e end<t1.c}
} {11}
do_test randexpr-2.2159 {
  db eval {SELECT coalesce((select max(11) from t1 where c=(abs(coalesce((select case when t1.c-t1.f+coalesce((select max(b) from t1 where case when (11<>17) then t1.c else c end in (select b from t1 union select t1.b from t1) and 13=11),f)+t1.b>=t1.f then 11 when c>t1.f then 19 else 19 end from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (e>19)))),t1.d))/abs(b)) and  -t1.d between t1.b and 13 or 17<>t1.e), -((11))) FROM t1 WHERE NOT (case when case when (not exists(select 1 from t1 where 19 not between case when coalesce((select b from t1 where (abs(t1.c)/abs(17))+t1.e between case when not exists(select 1 from t1 where not a<=t1.e) then t1.e when d<t1.c then 17 else  -d end and f),e)<13 then t1.a else t1.c end and e)) then +t1.a else d end not in (e,t1.d,t1.a) then t1.a when a in (select 19 from t1 union select t1.a from t1) then 19 else  -e end<t1.c)}
} {}
do_test randexpr-2.2160 {
  db eval {SELECT coalesce((select ( -t1.e*(abs((case when not 13 not in (case coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where d between  -b and f)),11) when 11 then 19 else a end,t1.a,t1.a) then f-t1.f when t1.c in (select  -abs(count(*)+(max((t1.a)))) from t1 union select  -max((19)) from t1) then d else 13 end-19))/abs(t1.b))-t1.d*e-19) from t1 where t1.e not between 13 and c),19)*13 FROM t1 WHERE 19<>(t1.c)}
} {-2600247}
do_test randexpr-2.2161 {
  db eval {SELECT coalesce((select ( -t1.e*(abs((case when not 13 not in (case coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where d between  -b and f)),11) when 11 then 19 else a end,t1.a,t1.a) then f-t1.f when t1.c in (select  -abs(count(*)+(max((t1.a)))) from t1 union select  -max((19)) from t1) then d else 13 end-19))/abs(t1.b))-t1.d*e-19) from t1 where t1.e not between 13 and c),19)*13 FROM t1 WHERE NOT (19<>(t1.c))}
} {}
do_test randexpr-2.2162 {
  db eval {SELECT coalesce((select max(13) from t1 where f= -case when exists(select 1 from t1 where not t1.b>=e and b in (select b from t1 union select (+(t1.f-d)) from t1) or 19 in (select min(e) from t1 union select  -~+++ -abs(min(17*t1.d)) from t1) or not t1.a>a) then 13 else t1.c end+a | ~11),19) FROM t1 WHERE (exists(select 1 from t1 where t1.c>19)) and a>d-a}
} {}
do_test randexpr-2.2163 {
  db eval {SELECT coalesce((select max(13) from t1 where f= -case when exists(select 1 from t1 where not t1.b>=e and b in (select b from t1 union select (+(t1.f-d)) from t1) or 19 in (select min(e) from t1 union select  -~+++ -abs(min(17*t1.d)) from t1) or not t1.a>a) then 13 else t1.c end+a | ~11),19) FROM t1 WHERE NOT ((exists(select 1 from t1 where t1.c>19)) and a>d-a)}
} {19}
do_test randexpr-2.2164 {
  db eval {SELECT coalesce((select max(13) from t1 where f= -case when exists(select 1 from t1 where not t1.b>=e and b in (select b from t1 union select (+(t1.f-d)) from t1) or 19 in (select min(e) from t1 union select  -~+++ -abs(min(17*t1.d)) from t1) or not t1.a>a) then 13 else t1.c end+a & ~11),19) FROM t1 WHERE NOT ((exists(select 1 from t1 where t1.c>19)) and a>d-a)}
} {19}
do_test randexpr-2.2165 {
  db eval {SELECT coalesce((select case when a between (select count(distinct 19) from t1) and case when d<t1.d and (select min(d)*min(a) from t1)<=t1.c+d then case 11 when 13 then t1.b else t1.a end else t1.d end+19 and exists(select 1 from t1 where t1.b between  -t1.e and t1.d) then f-d when 13 not between  -(c) and 13 then t1.c else 17 end from t1 where t1.e not in (c,f,t1.b)), -b) FROM t1 WHERE case 13*(abs(c)/abs(c*d-~t1.f-case coalesce((select +t1.f-a from t1 where b in (13,t1.f,f+19*+c)),b-a+coalesce((select max(c) from t1 where t1.f=d),d)-t1.a) when 13 then t1.d else t1.d end)) when 19 then 13 else  -11 end | 19=t1.c}
} {}
do_test randexpr-2.2166 {
  db eval {SELECT coalesce((select case when a between (select count(distinct 19) from t1) and case when d<t1.d and (select min(d)*min(a) from t1)<=t1.c+d then case 11 when 13 then t1.b else t1.a end else t1.d end+19 and exists(select 1 from t1 where t1.b between  -t1.e and t1.d) then f-d when 13 not between  -(c) and 13 then t1.c else 17 end from t1 where t1.e not in (c,f,t1.b)), -b) FROM t1 WHERE NOT (case 13*(abs(c)/abs(c*d-~t1.f-case coalesce((select +t1.f-a from t1 where b in (13,t1.f,f+19*+c)),b-a+coalesce((select max(c) from t1 where t1.f=d),d)-t1.a) when 13 then t1.d else t1.d end)) when 19 then 13 else  -11 end | 19=t1.c)}
} {200}
do_test randexpr-2.2167 {
  db eval {SELECT case 17 when  -b then e*c else (abs(coalesce((select max(coalesce((select coalesce((select max(case when t1.d<=19 and t1.d>e then b*t1.e else a end) from t1 where t1.e=t1.e),t1.f) from t1 where (d not between 13 and (f))),17)-d) from t1 where (11<>19)),t1.e)+t1.c)/abs(t1.e))*11*c-t1.d*t1.d+a end FROM t1 WHERE 13-e*t1.e<case when (coalesce((select max(c*13) from t1 where not exists(select 1 from t1 where (19+(coalesce((select coalesce((select max(a) from t1 where 17>=19),(abs(e)/abs((abs( -d+e)/abs(a))))+t1.a) from t1 where t1.b in (t1.e,(t1.e),t1.f)),f))=t1.e)) or b<=19),t1.b)<=13) then 13 else t1.f end-f}
} {-159900}
do_test randexpr-2.2168 {
  db eval {SELECT case 17 when  -b then e*c else (abs(coalesce((select max(coalesce((select coalesce((select max(case when t1.d<=19 and t1.d>e then b*t1.e else a end) from t1 where t1.e=t1.e),t1.f) from t1 where (d not between 13 and (f))),17)-d) from t1 where (11<>19)),t1.e)+t1.c)/abs(t1.e))*11*c-t1.d*t1.d+a end FROM t1 WHERE NOT (13-e*t1.e<case when (coalesce((select max(c*13) from t1 where not exists(select 1 from t1 where (19+(coalesce((select coalesce((select max(a) from t1 where 17>=19),(abs(e)/abs((abs( -d+e)/abs(a))))+t1.a) from t1 where t1.b in (t1.e,(t1.e),t1.f)),f))=t1.e)) or b<=19),t1.b)<=13) then 13 else t1.f end-f)}
} {}
do_test randexpr-2.2169 {
  db eval {SELECT case when case when e*(d-case a when 13 then (19) else d end) between 13 and f then f when exists(select 1 from t1 where 19<>t1.a) then e else b end in (select  -max(e)+min(11)-case ~~cast(avg(t1.c) AS integer) when max(19) then max(f) else  -cast(avg(f) AS integer) end from t1 union select  -max(13) from t1) and f>d and (t1.f=c) then t1.b else t1.c+ -t1.f end FROM t1 WHERE t1.e+11>=~t1.a-11}
} {-300}
do_test randexpr-2.2170 {
  db eval {SELECT case when case when e*(d-case a when 13 then (19) else d end) between 13 and f then f when exists(select 1 from t1 where 19<>t1.a) then e else b end in (select  -max(e)+min(11)-case ~~cast(avg(t1.c) AS integer) when max(19) then max(f) else  -cast(avg(f) AS integer) end from t1 union select  -max(13) from t1) and f>d and (t1.f=c) then t1.b else t1.c+ -t1.f end FROM t1 WHERE NOT (t1.e+11>=~t1.a-11)}
} {}
do_test randexpr-2.2171 {
  db eval {SELECT coalesce((select t1.f from t1 where not (abs(coalesce((select 17*13+(select cast(avg(t1.a) AS integer)-(count(distinct t1.c)*+cast(avg((select count(*) from t1)) AS integer))+count(*) from t1) from t1 where (select count(distinct t1.d*(((t1.d)))+f) from t1) in ( -b*t1.e-11,t1.d,d) and exists(select 1 from t1 where t1.d>c)),t1.e))/abs(b)) not in (t1.f,11,d)),t1.d) FROM t1 WHERE exists(select 1 from t1 where +t1.c-case when exists(select 1 from t1 where (select +case count(distinct case when 19*d in (select (cast(avg(11) AS integer)*cast(avg( -13) AS integer)) from t1 union select count(*) from t1) then t1.c else 13 end) when count(*) then count(*) else (min(t1.b)) end from t1)<>case when (not t1.f<b) or b>t1.d then case when f>=17 then t1.a else t1.e end else b end) then 11+t1.f when d<>17 then t1.e else a end- -13<>e) and t1.a<=17}
} {}
do_test randexpr-2.2172 {
  db eval {SELECT coalesce((select t1.f from t1 where not (abs(coalesce((select 17*13+(select cast(avg(t1.a) AS integer)-(count(distinct t1.c)*+cast(avg((select count(*) from t1)) AS integer))+count(*) from t1) from t1 where (select count(distinct t1.d*(((t1.d)))+f) from t1) in ( -b*t1.e-11,t1.d,d) and exists(select 1 from t1 where t1.d>c)),t1.e))/abs(b)) not in (t1.f,11,d)),t1.d) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.c-case when exists(select 1 from t1 where (select +case count(distinct case when 19*d in (select (cast(avg(11) AS integer)*cast(avg( -13) AS integer)) from t1 union select count(*) from t1) then t1.c else 13 end) when count(*) then count(*) else (min(t1.b)) end from t1)<>case when (not t1.f<b) or b>t1.d then case when f>=17 then t1.a else t1.e end else b end) then 11+t1.f when d<>17 then t1.e else a end- -13<>e) and t1.a<=17)}
} {400}
do_test randexpr-2.2173 {
  db eval {SELECT case when not (select  - -count(distinct t1.f)-(max(case when e not between f and t1.b+(13)+ -d-t1.a then t1.d else 11 end))+ -max(t1.b)*cast(avg(13) AS integer)-count(*) | (max(t1.e)) from t1)<>~t1.d then b when  -coalesce((select (abs(t1.e)/abs(t1.b)) from t1 where a<>b), - -17)<=t1.a then  -f else 11 end FROM t1 WHERE t1.a<>(select max(19) from t1)}
} {-600}
do_test randexpr-2.2174 {
  db eval {SELECT case when not (select  - -count(distinct t1.f)-(max(case when e not between f and t1.b+(13)+ -d-t1.a then t1.d else 11 end))+ -max(t1.b)*cast(avg(13) AS integer)-count(*) | (max(t1.e)) from t1)<>~t1.d then b when  -coalesce((select (abs(t1.e)/abs(t1.b)) from t1 where a<>b), - -17)<=t1.a then  -f else 11 end FROM t1 WHERE NOT (t1.a<>(select max(19) from t1))}
} {}
do_test randexpr-2.2175 {
  db eval {SELECT case when not (select  - -count(distinct t1.f)-(max(case when e not between f and t1.b+(13)+ -d-t1.a then t1.d else 11 end))+ -max(t1.b)*cast(avg(13) AS integer)-count(*) & (max(t1.e)) from t1)<>~t1.d then b when  -coalesce((select (abs(t1.e)/abs(t1.b)) from t1 where a<>b), - -17)<=t1.a then  -f else 11 end FROM t1 WHERE t1.a<>(select max(19) from t1)}
} {-600}
do_test randexpr-2.2176 {
  db eval {SELECT case when case coalesce((select t1.d+a*11 from t1 where e<=t1.d),19) when 19 then  -t1.d-t1.a else t1.e end not between 17 and d then t1.f when not (t1.c<=e and ((13<>e or t1.c not between t1.c and 13)) or t1.c=17 and t1.a not in (t1.e, -t1.d,t1.b) and b<t1.e) and c>=b then t1.d else 13 end FROM t1 WHERE (case t1.f when t1.b then case when case when not exists(select 1 from t1 where (t1.d+t1.a in (c,coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where (t1.a>=c))),+b), -t1.b))) then (select abs( -case ((abs( - - -count(*)+count(*)))) when min(d) then  -(cast(avg(t1.d) AS integer)) else cast(avg(e) AS integer) end | ((max((t1.f)))))+(min(t1.c)) from t1) else 11 end>f then 19 else t1.b end else b end)<=13 or (t1.f>b)}
} {600}
do_test randexpr-2.2177 {
  db eval {SELECT case when case coalesce((select t1.d+a*11 from t1 where e<=t1.d),19) when 19 then  -t1.d-t1.a else t1.e end not between 17 and d then t1.f when not (t1.c<=e and ((13<>e or t1.c not between t1.c and 13)) or t1.c=17 and t1.a not in (t1.e, -t1.d,t1.b) and b<t1.e) and c>=b then t1.d else 13 end FROM t1 WHERE NOT ((case t1.f when t1.b then case when case when not exists(select 1 from t1 where (t1.d+t1.a in (c,coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where (t1.a>=c))),+b), -t1.b))) then (select abs( -case ((abs( - - -count(*)+count(*)))) when min(d) then  -(cast(avg(t1.d) AS integer)) else cast(avg(e) AS integer) end | ((max((t1.f)))))+(min(t1.c)) from t1) else 11 end>f then 19 else t1.b end else b end)<=13 or (t1.f>b))}
} {}
do_test randexpr-2.2178 {
  db eval {SELECT (((d)+t1.f))-case +t1.d when coalesce((select max(13) from t1 where (select  -max(17*case when d>=coalesce((select 19 from t1 where a<>t1.e),t1.b) then e when  -c<>d then e else t1.a end*t1.f)+ -case count(*) when (+cast(avg(c) AS integer)) then count(*) else  -count(distinct t1.f) end+count(*) from t1)<=(abs(t1.c)/abs(t1.f))),17) then 17 else t1.d end-t1.b FROM t1 WHERE ~d-c in (select cast(avg(19) AS integer) from t1 union select  - -abs((abs((cast(avg(f) AS integer)) | abs(count(distinct 19))))) from t1)}
} {}
do_test randexpr-2.2179 {
  db eval {SELECT (((d)+t1.f))-case +t1.d when coalesce((select max(13) from t1 where (select  -max(17*case when d>=coalesce((select 19 from t1 where a<>t1.e),t1.b) then e when  -c<>d then e else t1.a end*t1.f)+ -case count(*) when (+cast(avg(c) AS integer)) then count(*) else  -count(distinct t1.f) end+count(*) from t1)<=(abs(t1.c)/abs(t1.f))),17) then 17 else t1.d end-t1.b FROM t1 WHERE NOT (~d-c in (select cast(avg(19) AS integer) from t1 union select  - -abs((abs((cast(avg(f) AS integer)) | abs(count(distinct 19))))) from t1))}
} {400}
do_test randexpr-2.2180 {
  db eval {SELECT coalesce((select max(f+t1.c*b) from t1 where (select abs(cast(avg(f) AS integer)) from t1)-c*~ -b+ -coalesce((select max(t1.a) from t1 where (select cast(avg((c) | ~t1.d) AS integer) from t1) not between t1.d-+(abs(t1.d)/abs(t1.c))+d and 11 and 17>=t1.e),t1.e)-b in (t1.c,d,e)),a)+c FROM t1 WHERE 19*e not in (a,t1.d,coalesce((select coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where not exists(select 1 from t1 where e*case when ~c | f+11* -a in ( -t1.c,17,(t1.b)) then (f) when e=e or t1.d=f and (e)>(e) then (11) else a end+a*c in (select d from t1 union select  -11 from t1))))),t1.f) from t1 where t1.d<=d),13))}
} {400}
do_test randexpr-2.2181 {
  db eval {SELECT coalesce((select max(f+t1.c*b) from t1 where (select abs(cast(avg(f) AS integer)) from t1)-c*~ -b+ -coalesce((select max(t1.a) from t1 where (select cast(avg((c) | ~t1.d) AS integer) from t1) not between t1.d-+(abs(t1.d)/abs(t1.c))+d and 11 and 17>=t1.e),t1.e)-b in (t1.c,d,e)),a)+c FROM t1 WHERE NOT (19*e not in (a,t1.d,coalesce((select coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where not exists(select 1 from t1 where e*case when ~c | f+11* -a in ( -t1.c,17,(t1.b)) then (f) when e=e or t1.d=f and (e)>(e) then (11) else a end+a*c in (select d from t1 union select  -11 from t1))))),t1.f) from t1 where t1.d<=d),13)))}
} {}
do_test randexpr-2.2182 {
  db eval {SELECT coalesce((select max(f+t1.c*b) from t1 where (select abs(cast(avg(f) AS integer)) from t1)-c*~ -b+ -coalesce((select max(t1.a) from t1 where (select cast(avg((c) & ~t1.d) AS integer) from t1) not between t1.d-+(abs(t1.d)/abs(t1.c))+d and 11 and 17>=t1.e),t1.e)-b in (t1.c,d,e)),a)+c FROM t1 WHERE 19*e not in (a,t1.d,coalesce((select coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where not exists(select 1 from t1 where e*case when ~c | f+11* -a in ( -t1.c,17,(t1.b)) then (f) when e=e or t1.d=f and (e)>(e) then (11) else a end+a*c in (select d from t1 union select  -11 from t1))))),t1.f) from t1 where t1.d<=d),13))}
} {400}
do_test randexpr-2.2183 {
  db eval {SELECT c*~case ((abs(t1.b)/abs(t1.b))) when c then e else t1.c end-(case when (c)>=case coalesce((select max((abs(d)/abs(c))) from t1 where 13 not in (a-t1.e-(select count(*) | min(e)+min(c) from t1)*19*t1.b,11,a)),e) when e then b else t1.d end then d when 17<11 then c else t1.d end) | t1.f FROM t1 WHERE case when not (abs(t1.d | (abs( - -coalesce((select max(coalesce((select c+e from t1 where not t1.b in ((c),b,(f))),t1.b)) from t1 where 11=b),t1.f)+13*t1.f*e)/abs(t1.e)))/abs(t1.b))>=c then coalesce((select (t1.c) from t1 where t1.e in (11,e,t1.a)),a) when 13<=t1.b then t1.f else t1.d end in (select e from t1 union select (t1.d) from t1)}
} {}
do_test randexpr-2.2184 {
  db eval {SELECT c*~case ((abs(t1.b)/abs(t1.b))) when c then e else t1.c end-(case when (c)>=case coalesce((select max((abs(d)/abs(c))) from t1 where 13 not in (a-t1.e-(select count(*) | min(e)+min(c) from t1)*19*t1.b,11,a)),e) when e then b else t1.d end then d when 17<11 then c else t1.d end) | t1.f FROM t1 WHERE NOT (case when not (abs(t1.d | (abs( - -coalesce((select max(coalesce((select c+e from t1 where not t1.b in ((c),b,(f))),t1.b)) from t1 where 11=b),t1.f)+13*t1.f*e)/abs(t1.e)))/abs(t1.b))>=c then coalesce((select (t1.c) from t1 where t1.e in (11,e,t1.a)),a) when 13<=t1.b then t1.f else t1.d end in (select e from t1 union select (t1.d) from t1))}
} {-90116}
do_test randexpr-2.2185 {
  db eval {SELECT c*~case ((abs(t1.b)/abs(t1.b))) when c then e else t1.c end-(case when (c)>=case coalesce((select max((abs(d)/abs(c))) from t1 where 13 not in (a-t1.e-(select count(*) & min(e)+min(c) from t1)*19*t1.b,11,a)),e) when e then b else t1.d end then d when 17<11 then c else t1.d end) & t1.f FROM t1 WHERE NOT (case when not (abs(t1.d | (abs( - -coalesce((select max(coalesce((select c+e from t1 where not t1.b in ((c),b,(f))),t1.b)) from t1 where 11=b),t1.f)+13*t1.f*e)/abs(t1.e)))/abs(t1.b))>=c then coalesce((select (t1.c) from t1 where t1.e in (11,e,t1.a)),a) when 13<=t1.b then t1.f else t1.d end in (select e from t1 union select (t1.d) from t1))}
} {16}
do_test randexpr-2.2186 {
  db eval {SELECT case when a+13*+ -~case when 17=t1.c*17 then 19 | (t1.b) when f+t1.e+(d)+b+c not between (d) and e or (a between t1.b and t1.a) then 17 else a end-17-(e)<=17 then b when c in (select 17 from t1 union select t1.a from t1) then c else t1.e end FROM t1 WHERE e-coalesce((select f-case 17+t1.a*(abs(t1.e)/abs((abs(coalesce((select max(+ -case when t1.a>=d then c else t1.e end-d) from t1 where (not exists(select 1 from t1 where (t1.d in ( -f,d,t1.b))) or  -t1.f not between  -b and t1.b)),11))/abs(13)))) when 13 then d else t1.f end from t1 where t1.e in ((19),t1.e,17) or e>=t1.d),e)<>17 or 19<=19}
} {200}
do_test randexpr-2.2187 {
  db eval {SELECT case when a+13*+ -~case when 17=t1.c*17 then 19 | (t1.b) when f+t1.e+(d)+b+c not between (d) and e or (a between t1.b and t1.a) then 17 else a end-17-(e)<=17 then b when c in (select 17 from t1 union select t1.a from t1) then c else t1.e end FROM t1 WHERE NOT (e-coalesce((select f-case 17+t1.a*(abs(t1.e)/abs((abs(coalesce((select max(+ -case when t1.a>=d then c else t1.e end-d) from t1 where (not exists(select 1 from t1 where (t1.d in ( -f,d,t1.b))) or  -t1.f not between  -b and t1.b)),11))/abs(13)))) when 13 then d else t1.f end from t1 where t1.e in ((19),t1.e,17) or e>=t1.d),e)<>17 or 19<=19)}
} {}
do_test randexpr-2.2188 {
  db eval {SELECT case when a+13*+ -~case when 17=t1.c*17 then 19 & (t1.b) when f+t1.e+(d)+b+c not between (d) and e or (a between t1.b and t1.a) then 17 else a end-17-(e)<=17 then b when c in (select 17 from t1 union select t1.a from t1) then c else t1.e end FROM t1 WHERE e-coalesce((select f-case 17+t1.a*(abs(t1.e)/abs((abs(coalesce((select max(+ -case when t1.a>=d then c else t1.e end-d) from t1 where (not exists(select 1 from t1 where (t1.d in ( -f,d,t1.b))) or  -t1.f not between  -b and t1.b)),11))/abs(13)))) when 13 then d else t1.f end from t1 where t1.e in ((19),t1.e,17) or e>=t1.d),e)<>17 or 19<=19}
} {200}
do_test randexpr-2.2189 {
  db eval {SELECT 17-t1.a*(select abs(~count(*)*abs(count(distinct a)) | (~count(distinct case (a* -coalesce((select a from t1 where (13 in (select max((abs(t1.e)/abs(case when not exists(select 1 from t1 where (b<>c)) then (11)-t1.f-e else e end))) from t1 union select (count(distinct 11)) from t1))),t1.b)+11) when (17) then e else f end))) from t1) FROM t1 WHERE 13>case (e) when t1.a then t1.a else 11 end-t1.b}
} {-183}
do_test randexpr-2.2190 {
  db eval {SELECT 17-t1.a*(select abs(~count(*)*abs(count(distinct a)) | (~count(distinct case (a* -coalesce((select a from t1 where (13 in (select max((abs(t1.e)/abs(case when not exists(select 1 from t1 where (b<>c)) then (11)-t1.f-e else e end))) from t1 union select (count(distinct 11)) from t1))),t1.b)+11) when (17) then e else f end))) from t1) FROM t1 WHERE NOT (13>case (e) when t1.a then t1.a else 11 end-t1.b)}
} {}
do_test randexpr-2.2191 {
  db eval {SELECT 17-t1.a*(select abs(~count(*)*abs(count(distinct a)) & (~count(distinct case (a* -coalesce((select a from t1 where (13 in (select max((abs(t1.e)/abs(case when not exists(select 1 from t1 where (b<>c)) then (11)-t1.f-e else e end))) from t1 union select (count(distinct 11)) from t1))),t1.b)+11) when (17) then e else f end))) from t1) FROM t1 WHERE 13>case (e) when t1.a then t1.a else 11 end-t1.b}
} {-183}
do_test randexpr-2.2192 {
  db eval {SELECT case when t1.b= -b then e else (select  -(count(distinct t1.a))*max(c)-count(*)+count(distinct t1.b+d)*min(t1.f-case when 19 in (select t1.d from t1 union select e from t1) then 17 when f<=t1.c then t1.b else e end-(d)*c)-count(distinct t1.d)*case +max(f) when max(17) | max(d) |  -(cast(avg(d) AS integer)) then  -cast(avg(11) AS integer) else  -count(distinct 11) end*min(t1.d) from t1) end FROM t1 WHERE t1.f>=f}
} {-119801}
do_test randexpr-2.2193 {
  db eval {SELECT case when t1.b= -b then e else (select  -(count(distinct t1.a))*max(c)-count(*)+count(distinct t1.b+d)*min(t1.f-case when 19 in (select t1.d from t1 union select e from t1) then 17 when f<=t1.c then t1.b else e end-(d)*c)-count(distinct t1.d)*case +max(f) when max(17) | max(d) |  -(cast(avg(d) AS integer)) then  -cast(avg(11) AS integer) else  -count(distinct 11) end*min(t1.d) from t1) end FROM t1 WHERE NOT (t1.f>=f)}
} {}
do_test randexpr-2.2194 {
  db eval {SELECT case when t1.b= -b then e else (select  -(count(distinct t1.a))*max(c)-count(*)+count(distinct t1.b+d)*min(t1.f-case when 19 in (select t1.d from t1 union select e from t1) then 17 when f<=t1.c then t1.b else e end-(d)*c)-count(distinct t1.d)*case +max(f) when max(17) & max(d) &  -(cast(avg(d) AS integer)) then  -cast(avg(11) AS integer) else  -count(distinct 11) end*min(t1.d) from t1) end FROM t1 WHERE t1.f>=f}
} {-119801}
do_test randexpr-2.2195 {
  db eval {SELECT  -~f | (abs(13+t1.b)/abs((select max(t1.b | t1.f+ -17-11) | +case min(e) when count(*) | case (~ -min(c)*cast(avg(19) AS integer)) when  -count(*) then min(a) else min(13) end then  -((max(t1.c))) else max(e) end-(count(distinct  -t1.a)) from t1)))+~(abs((abs(case when a<>19 then t1.a when f>17 then a else b end)/abs(t1.b)))/abs(t1.f)) FROM t1 WHERE (17 between t1.f*(abs(b)/abs((abs((select max(17) from t1) | 17)/abs(13))+c-coalesce((select max(d) from t1 where d between f-a-11-d and a+t1.a+d-t1.b+17+13),case when a not between a and t1.b then t1.d when t1.d not in ((e),a,d) then c else b end*d))) and b and t1.e> -17)}
} {}
do_test randexpr-2.2196 {
  db eval {SELECT  -~f | (abs(13+t1.b)/abs((select max(t1.b | t1.f+ -17-11) | +case min(e) when count(*) | case (~ -min(c)*cast(avg(19) AS integer)) when  -count(*) then min(a) else min(13) end then  -((max(t1.c))) else max(e) end-(count(distinct  -t1.a)) from t1)))+~(abs((abs(case when a<>19 then t1.a when f>17 then a else b end)/abs(t1.b)))/abs(t1.f)) FROM t1 WHERE NOT ((17 between t1.f*(abs(b)/abs((abs((select max(17) from t1) | 17)/abs(13))+c-coalesce((select max(d) from t1 where d between f-a-11-d and a+t1.a+d-t1.b+17+13),case when a not between a and t1.b then t1.d when t1.d not in ((e),a,d) then c else b end*d))) and b and t1.e> -17))}
} {-1}
do_test randexpr-2.2197 {
  db eval {SELECT (select abs(abs( -case case ~count(distinct t1.f+(t1.f)+coalesce((select (abs(t1.e+(b)+a)/abs(11))+b from t1 where exists(select 1 from t1 where t1.f not in (t1.b,(b),e) and not (t1.b)>c)),f)) when ~count(*)-min(t1.f) then +(count(*))*( -count(*)-max(t1.a)) else min(11) end when count(distinct (f)) then  -count(distinct a) else count(*) end | count(distinct 13))) from t1) FROM t1 WHERE exists(select 1 from t1 where case when t1.f>(abs(b)/abs(a)) then ~case when t1.e+13-b<=(coalesce((select max(11) from t1 where (select abs(min(11)) from t1) in (select case d when f then 17 else t1.f end from t1 union select t1.f from t1)),b)*13)-19 then 11 when not 19 between t1.c and t1.b then a else e end-t1.a when (t1.a) not between b and t1.f then t1.a else c end=t1.e)}
} {}
do_test randexpr-2.2198 {
  db eval {SELECT (select abs(abs( -case case ~count(distinct t1.f+(t1.f)+coalesce((select (abs(t1.e+(b)+a)/abs(11))+b from t1 where exists(select 1 from t1 where t1.f not in (t1.b,(b),e) and not (t1.b)>c)),f)) when ~count(*)-min(t1.f) then +(count(*))*( -count(*)-max(t1.a)) else min(11) end when count(distinct (f)) then  -count(distinct a) else count(*) end | count(distinct 13))) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where case when t1.f>(abs(b)/abs(a)) then ~case when t1.e+13-b<=(coalesce((select max(11) from t1 where (select abs(min(11)) from t1) in (select case d when f then 17 else t1.f end from t1 union select t1.f from t1)),b)*13)-19 then 11 when not 19 between t1.c and t1.b then a else e end-t1.a when (t1.a) not between b and t1.f then t1.a else c end=t1.e))}
} {1}
do_test randexpr-2.2199 {
  db eval {SELECT (select abs(abs( -case case ~count(distinct t1.f+(t1.f)+coalesce((select (abs(t1.e+(b)+a)/abs(11))+b from t1 where exists(select 1 from t1 where t1.f not in (t1.b,(b),e) and not (t1.b)>c)),f)) when ~count(*)-min(t1.f) then +(count(*))*( -count(*)-max(t1.a)) else min(11) end when count(distinct (f)) then  -count(distinct a) else count(*) end & count(distinct 13))) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where case when t1.f>(abs(b)/abs(a)) then ~case when t1.e+13-b<=(coalesce((select max(11) from t1 where (select abs(min(11)) from t1) in (select case d when f then 17 else t1.f end from t1 union select t1.f from t1)),b)*13)-19 then 11 when not 19 between t1.c and t1.b then a else e end-t1.a when (t1.a) not between b and t1.f then t1.a else c end=t1.e))}
} {1}
do_test randexpr-2.2200 {
  db eval {SELECT 19 | t1.a*(select case max(case when t1.b*17>=t1.b then coalesce((select max(e) from t1 where e in (select count(*) from t1 union select count(distinct t1.f) from t1)),d) when t1.a in (select min(11) from t1 union select (( -( -max(t1.f)))) from t1) and 17 in (select count(distinct 17) from t1 union select  -count(distinct d) from t1) and (d)<>t1.c and t1.c not between b and b then a else 11 end)+cast(avg(t1.a) AS integer) when ~count(distinct t1.e) then count(distinct d) else count(distinct e) end from t1) | e*t1.b-t1.d FROM t1 WHERE (((abs(19)/abs(case ~c*d+(abs(e)/abs((coalesce((select case when (f in (select count(*) from t1 union select  -min(d) from t1)) then case when  -t1.f between t1.c and t1.f then b when 11<>a then t1.a else t1.c end when 13=13 then 13 else t1.a end from t1 where 19 not between 11 and t1.b or t1.b not in ((e),(b),c)),a)- -((t1.c))-c)))+t1.b+17 when 13 then ((13)) else t1.f end*t1.b)) in ( -17,t1.a,11)))}
} {}
do_test randexpr-2.2201 {
  db eval {SELECT 19 | t1.a*(select case max(case when t1.b*17>=t1.b then coalesce((select max(e) from t1 where e in (select count(*) from t1 union select count(distinct t1.f) from t1)),d) when t1.a in (select min(11) from t1 union select (( -( -max(t1.f)))) from t1) and 17 in (select count(distinct 17) from t1 union select  -count(distinct d) from t1) and (d)<>t1.c and t1.c not between b and b then a else 11 end)+cast(avg(t1.a) AS integer) when ~count(distinct t1.e) then count(distinct d) else count(distinct e) end from t1) | e*t1.b-t1.d FROM t1 WHERE NOT ((((abs(19)/abs(case ~c*d+(abs(e)/abs((coalesce((select case when (f in (select count(*) from t1 union select  -min(d) from t1)) then case when  -t1.f between t1.c and t1.f then b when 11<>a then t1.a else t1.c end when 13=13 then 13 else t1.a end from t1 where 19 not between 11 and t1.b or t1.b not in ((e),(b),c)),a)- -((t1.c))-c)))+t1.b+17 when 13 then ((13)) else t1.f end*t1.b)) in ( -17,t1.a,11))))}
} {99703}
do_test randexpr-2.2202 {
  db eval {SELECT 19 & t1.a*(select case max(case when t1.b*17>=t1.b then coalesce((select max(e) from t1 where e in (select count(*) from t1 union select count(distinct t1.f) from t1)),d) when t1.a in (select min(11) from t1 union select (( -( -max(t1.f)))) from t1) and 17 in (select count(distinct 17) from t1 union select  -count(distinct d) from t1) and (d)<>t1.c and t1.c not between b and b then a else 11 end)+cast(avg(t1.a) AS integer) when ~count(distinct t1.e) then count(distinct d) else count(distinct e) end from t1) & e*t1.b-t1.d FROM t1 WHERE NOT ((((abs(19)/abs(case ~c*d+(abs(e)/abs((coalesce((select case when (f in (select count(*) from t1 union select  -min(d) from t1)) then case when  -t1.f between t1.c and t1.f then b when 11<>a then t1.a else t1.c end when 13=13 then 13 else t1.a end from t1 where 19 not between 11 and t1.b or t1.b not in ((e),(b),c)),a)- -((t1.c))-c)))+t1.b+17 when 13 then ((13)) else t1.f end*t1.b)) in ( -17,t1.a,11))))}
} {0}
do_test randexpr-2.2203 {
  db eval {SELECT c-coalesce((select  -coalesce((select max(case when (abs(~~case when case when t1.e<=e and t1.f>t1.d then b when t1.a<>t1.a then 17 else 17 end+t1.c>=t1.a then (c) when c not in (f,e,t1.c) then t1.d else 13 end)/abs(t1.a))<t1.b then t1.e when c<=t1.a then b else d end) from t1 where (19) not in (13,t1.e,f)),17) from t1 where 19>c),t1.a)*19 FROM t1 WHERE (17) | case when 19 not in ((case when (e*19=f) then case t1.f when a then 13 else t1.d end when b<t1.f then f else a end)*t1.d,c, -t1.f) then t1.f when (e=(d) and 19<>t1.b) then f else a end in (select c from t1 union select  -13 from t1) or 17 in (select 19 from t1 union select d from t1) and t1.b in (c,b,19) and t1.b>=( -b)}
} {}
do_test randexpr-2.2204 {
  db eval {SELECT c-coalesce((select  -coalesce((select max(case when (abs(~~case when case when t1.e<=e and t1.f>t1.d then b when t1.a<>t1.a then 17 else 17 end+t1.c>=t1.a then (c) when c not in (f,e,t1.c) then t1.d else 13 end)/abs(t1.a))<t1.b then t1.e when c<=t1.a then b else d end) from t1 where (19) not in (13,t1.e,f)),17) from t1 where 19>c),t1.a)*19 FROM t1 WHERE NOT ((17) | case when 19 not in ((case when (e*19=f) then case t1.f when a then 13 else t1.d end when b<t1.f then f else a end)*t1.d,c, -t1.f) then t1.f when (e=(d) and 19<>t1.b) then f else a end in (select c from t1 union select  -13 from t1) or 17 in (select 19 from t1 union select d from t1) and t1.b in (c,b,19) and t1.b>=( -b))}
} {-1600}
do_test randexpr-2.2205 {
  db eval {SELECT 13+case when not (t1.d in (11,f,t1.a)) then coalesce((select +t1.e from t1 where case t1.e when t1.b then 19+t1.a+~e+a*t1.a else 11 end not between 19 and 19),(abs(t1.f-case when (19)<t1.a and d=t1.d then a else a end-f)/abs(13))*c+t1.c)+c else 19 end*t1.e FROM t1 WHERE t1.e in (select +count(distinct a-(select count(*)+count(distinct (abs((select max(coalesce((select case d++11+(t1.c-t1.d-t1.e*t1.e) when t1.a then t1.b else t1.b end from t1 where f in (select (abs(case when e not between  -t1.a and f then 11 when t1.b>=17 then t1.c else t1.f end)/abs(19)) from t1 union select c from t1)), -d)) from t1))/abs(t1.d))) from t1)*(c) | 11+t1.c*t1.b) from t1 union select cast(avg(t1.c) AS integer) from t1)}
} {}
do_test randexpr-2.2206 {
  db eval {SELECT 13+case when not (t1.d in (11,f,t1.a)) then coalesce((select +t1.e from t1 where case t1.e when t1.b then 19+t1.a+~e+a*t1.a else 11 end not between 19 and 19),(abs(t1.f-case when (19)<t1.a and d=t1.d then a else a end-f)/abs(13))*c+t1.c)+c else 19 end*t1.e FROM t1 WHERE NOT (t1.e in (select +count(distinct a-(select count(*)+count(distinct (abs((select max(coalesce((select case d++11+(t1.c-t1.d-t1.e*t1.e) when t1.a then t1.b else t1.b end from t1 where f in (select (abs(case when e not between  -t1.a and f then 11 when t1.b>=17 then t1.c else t1.f end)/abs(19)) from t1 union select c from t1)), -d)) from t1))/abs(t1.d))) from t1)*(c) | 11+t1.c*t1.b) from t1 union select cast(avg(t1.c) AS integer) from t1))}
} {400013}
do_test randexpr-2.2207 {
  db eval {SELECT case when  -11-t1.b-f-t1.b>~c then t1.e else case when t1.d<>b*~17+t1.d*(select max(+(select count(distinct t1.a)+ -cast(avg(d) AS integer)*max(13) from t1)) from t1) or (abs(c)/abs(c)) not in (11,d,t1.c) then 13 when d in (select f from t1 union select b from t1) then t1.f else  -t1.a end+ -f end FROM t1 WHERE ~t1.b*19-d not between ~b and t1.f}
} {-587}
do_test randexpr-2.2208 {
  db eval {SELECT case when  -11-t1.b-f-t1.b>~c then t1.e else case when t1.d<>b*~17+t1.d*(select max(+(select count(distinct t1.a)+ -cast(avg(d) AS integer)*max(13) from t1)) from t1) or (abs(c)/abs(c)) not in (11,d,t1.c) then 13 when d in (select f from t1 union select b from t1) then t1.f else  -t1.a end+ -f end FROM t1 WHERE NOT (~t1.b*19-d not between ~b and t1.f)}
} {}
do_test randexpr-2.2209 {
  db eval {SELECT coalesce((select t1.b from t1 where coalesce((select max(coalesce((select max(t1.a) from t1 where t1.c=t1.e),case b-f when f then e else 13 end-t1.d)) from t1 where not exists(select 1 from t1 where  -t1.f>=17)),a)*(19) in (select max(d) from t1 union select case  -count(*) when +count(distinct (t1.f)) then min(t1.d) else count(*) end from t1) and a<=f and d not between b and 19 and not exists(select 1 from t1 where b between t1.c and e or c<>t1.f)),17) FROM t1 WHERE t1.a-19<>c*d}
} {17}
do_test randexpr-2.2210 {
  db eval {SELECT coalesce((select t1.b from t1 where coalesce((select max(coalesce((select max(t1.a) from t1 where t1.c=t1.e),case b-f when f then e else 13 end-t1.d)) from t1 where not exists(select 1 from t1 where  -t1.f>=17)),a)*(19) in (select max(d) from t1 union select case  -count(*) when +count(distinct (t1.f)) then min(t1.d) else count(*) end from t1) and a<=f and d not between b and 19 and not exists(select 1 from t1 where b between t1.c and e or c<>t1.f)),17) FROM t1 WHERE NOT (t1.a-19<>c*d)}
} {}
do_test randexpr-2.2211 {
  db eval {SELECT (coalesce((select case (select ~count(*) | max(b+t1.b)+case max((abs(+coalesce((select max(f) from t1 where not (17=e)),t1.f))/abs(b))*a) when  -~~ -(cast(avg(13) AS integer)) | count(*) then min(13) else count(*) end-count(distinct d) from t1) when 17+t1.d then t1.a else 13 end from t1 where e not between 13 and 11),11)+t1.e+b) FROM t1 WHERE not f in (select t1.e from t1 union select t1.f from t1) or 13 not in (t1.b | t1.e,t1.f,d) or (abs(f)/abs(+(abs(f+(select max(case when ((13<>t1.c)) then 13 else t1.c end) | ~min(t1.a)+cast(avg(a) AS integer) from t1)*(d)-b)/abs(d))*e))-t1.b not in (t1.c,f,t1.d) and t1.b<>t1.f}
} {713}
do_test randexpr-2.2212 {
  db eval {SELECT (coalesce((select case (select ~count(*) | max(b+t1.b)+case max((abs(+coalesce((select max(f) from t1 where not (17=e)),t1.f))/abs(b))*a) when  -~~ -(cast(avg(13) AS integer)) | count(*) then min(13) else count(*) end-count(distinct d) from t1) when 17+t1.d then t1.a else 13 end from t1 where e not between 13 and 11),11)+t1.e+b) FROM t1 WHERE NOT (not f in (select t1.e from t1 union select t1.f from t1) or 13 not in (t1.b | t1.e,t1.f,d) or (abs(f)/abs(+(abs(f+(select max(case when ((13<>t1.c)) then 13 else t1.c end) | ~min(t1.a)+cast(avg(a) AS integer) from t1)*(d)-b)/abs(d))*e))-t1.b not in (t1.c,f,t1.d) and t1.b<>t1.f)}
} {}
do_test randexpr-2.2213 {
  db eval {SELECT (coalesce((select case (select ~count(*) & max(b+t1.b)+case max((abs(+coalesce((select max(f) from t1 where not (17=e)),t1.f))/abs(b))*a) when  -~~ -(cast(avg(13) AS integer)) & count(*) then min(13) else count(*) end-count(distinct d) from t1) when 17+t1.d then t1.a else 13 end from t1 where e not between 13 and 11),11)+t1.e+b) FROM t1 WHERE not f in (select t1.e from t1 union select t1.f from t1) or 13 not in (t1.b | t1.e,t1.f,d) or (abs(f)/abs(+(abs(f+(select max(case when ((13<>t1.c)) then 13 else t1.c end) | ~min(t1.a)+cast(avg(a) AS integer) from t1)*(d)-b)/abs(d))*e))-t1.b not in (t1.c,f,t1.d) and t1.b<>t1.f}
} {713}
do_test randexpr-2.2214 {
  db eval {SELECT t1.b-c*a*t1.b+ -f | (case when 13<f then d else t1.a+case (select +min(a) from t1) when case when a<=d*a | e then b when not f not between e and 17 or not 19=coalesce((select 13 from t1 where t1.f in (t1.b,t1.d,t1.a)),d) then 11 else (13) end then 11 else (a) end end-b) FROM t1 WHERE exists(select 1 from t1 where t1.a>17)}
} {-6000392}
do_test randexpr-2.2215 {
  db eval {SELECT t1.b-c*a*t1.b+ -f | (case when 13<f then d else t1.a+case (select +min(a) from t1) when case when a<=d*a | e then b when not f not between e and 17 or not 19=coalesce((select 13 from t1 where t1.f in (t1.b,t1.d,t1.a)),d) then 11 else (13) end then 11 else (a) end end-b) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.a>17))}
} {}
do_test randexpr-2.2216 {
  db eval {SELECT t1.b-c*a*t1.b+ -f & (case when 13<f then d else t1.a+case (select +min(a) from t1) when case when a<=d*a & e then b when not f not between e and 17 or not 19=coalesce((select 13 from t1 where t1.f in (t1.b,t1.d,t1.a)),d) then 11 else (13) end then 11 else (a) end end-b) FROM t1 WHERE exists(select 1 from t1 where t1.a>17)}
} {192}
do_test randexpr-2.2217 {
  db eval {SELECT ~(select (abs(cast(avg(((b)-d*t1.a-c+17+f+e+ -17)) AS integer))) from t1)*t1.c++ -(11-t1.b*~f-e*t1.b)-coalesce((select max(case when not c=13 then 17 else b end) from t1 where (t1.a>17)),c) |  -f-f FROM t1 WHERE a+coalesce((select max(coalesce((select max(f) from t1 where ((not b in (select t1.b from t1 union select (select  -cast(avg(t1.b) AS integer) from t1) from t1)) or not t1.d= -t1.c and 19<=t1.c)),t1.f)-coalesce((select c from t1 where d<=t1.a), -e)) from t1 where d in (select t1.d from t1 union select t1.d from t1)),t1.d)-a | t1.b>(f) or t1.d between 19 and t1.c and exists(select 1 from t1 where b=13) and not 13 not in (t1.d,(c),d) and e not between 17 and 13}
} {-1040}
do_test randexpr-2.2218 {
  db eval {SELECT ~(select (abs(cast(avg(((b)-d*t1.a-c+17+f+e+ -17)) AS integer))) from t1)*t1.c++ -(11-t1.b*~f-e*t1.b)-coalesce((select max(case when not c=13 then 17 else b end) from t1 where (t1.a>17)),c) |  -f-f FROM t1 WHERE NOT (a+coalesce((select max(coalesce((select max(f) from t1 where ((not b in (select t1.b from t1 union select (select  -cast(avg(t1.b) AS integer) from t1) from t1)) or not t1.d= -t1.c and 19<=t1.c)),t1.f)-coalesce((select c from t1 where d<=t1.a), -e)) from t1 where d in (select t1.d from t1 union select t1.d from t1)),t1.d)-a | t1.b>(f) or t1.d between 19 and t1.c and exists(select 1 from t1 where b=13) and not 13 not in (t1.d,(c),d) and e not between 17 and 13)}
} {}
do_test randexpr-2.2219 {
  db eval {SELECT ~(select (abs(cast(avg(((b)-d*t1.a-c+17+f+e+ -17)) AS integer))) from t1)*t1.c++ -(11-t1.b*~f-e*t1.b)-coalesce((select max(case when not c=13 then 17 else b end) from t1 where (t1.a>17)),c) &  -f-f FROM t1 WHERE a+coalesce((select max(coalesce((select max(f) from t1 where ((not b in (select t1.b from t1 union select (select  -cast(avg(t1.b) AS integer) from t1) from t1)) or not t1.d= -t1.c and 19<=t1.c)),t1.f)-coalesce((select c from t1 where d<=t1.a), -e)) from t1 where d in (select t1.d from t1 union select t1.d from t1)),t1.d)-a | t1.b>(f) or t1.d between 19 and t1.c and exists(select 1 from t1 where b=13) and not 13 not in (t1.d,(c),d) and e not between 17 and 13}
} {-11720688}
do_test randexpr-2.2220 {
  db eval {SELECT case when t1.a in (select count(*) from t1 union select cast(avg(t1.a) AS integer)*count(distinct 17) |  -count(*) from t1) then ~coalesce((select max(19+t1.a) from t1 where +d=t1.a),case t1.c-(select count(*) from t1) when coalesce((select (abs((select (cast(avg(13) AS integer)) from t1))/abs(13)) from t1 where f<~13-(t1.a)*19),d) then a else 19 end) | b when t1.d>a then f else b end FROM t1 WHERE 19<=case when (t1.a*11*19-e<>(select abs(min(e))+case  -abs(abs( - -( -(( -max(c)))))-(min(c))) when min(e) then  -(min(f)) else  - -min(t1.a) end from t1)*t1.d) then e+f+coalesce((select max(e-a) from t1 where (t1.b) between 11 and  -t1.c),c) when t1.c<=17 then 17 else t1.b end and 19<>t1.f}
} {600}
do_test randexpr-2.2221 {
  db eval {SELECT case when t1.a in (select count(*) from t1 union select cast(avg(t1.a) AS integer)*count(distinct 17) |  -count(*) from t1) then ~coalesce((select max(19+t1.a) from t1 where +d=t1.a),case t1.c-(select count(*) from t1) when coalesce((select (abs((select (cast(avg(13) AS integer)) from t1))/abs(13)) from t1 where f<~13-(t1.a)*19),d) then a else 19 end) | b when t1.d>a then f else b end FROM t1 WHERE NOT (19<=case when (t1.a*11*19-e<>(select abs(min(e))+case  -abs(abs( - -( -(( -max(c)))))-(min(c))) when min(e) then  -(min(f)) else  - -min(t1.a) end from t1)*t1.d) then e+f+coalesce((select max(e-a) from t1 where (t1.b) between 11 and  -t1.c),c) when t1.c<=17 then 17 else t1.b end and 19<>t1.f)}
} {}
do_test randexpr-2.2222 {
  db eval {SELECT case when t1.a in (select count(*) from t1 union select cast(avg(t1.a) AS integer)*count(distinct 17) &  -count(*) from t1) then ~coalesce((select max(19+t1.a) from t1 where +d=t1.a),case t1.c-(select count(*) from t1) when coalesce((select (abs((select (cast(avg(13) AS integer)) from t1))/abs(13)) from t1 where f<~13-(t1.a)*19),d) then a else 19 end) & b when t1.d>a then f else b end FROM t1 WHERE 19<=case when (t1.a*11*19-e<>(select abs(min(e))+case  -abs(abs( - -( -(( -max(c)))))-(min(c))) when min(e) then  -(min(f)) else  - -min(t1.a) end from t1)*t1.d) then e+f+coalesce((select max(e-a) from t1 where (t1.b) between 11 and  -t1.c),c) when t1.c<=17 then 17 else t1.b end and 19<>t1.f}
} {200}
do_test randexpr-2.2223 {
  db eval {SELECT c-case when t1.e>coalesce((select case  -t1.d-case when d in (select  -t1.f from t1 union select t1.c+t1.c from t1) and (t1.a<=t1.a) then 11*(17) when d between 11 and e or  -c<>t1.f then 19 else 19 end+11 when 19 then b else t1.b end-t1.a from t1 where not e<=f),( -t1.f)) then b when ((d<c)) then 19 else f end FROM t1 WHERE t1.c in (t1.c,~19,13)}
} {100}
do_test randexpr-2.2224 {
  db eval {SELECT c-case when t1.e>coalesce((select case  -t1.d-case when d in (select  -t1.f from t1 union select t1.c+t1.c from t1) and (t1.a<=t1.a) then 11*(17) when d between 11 and e or  -c<>t1.f then 19 else 19 end+11 when 19 then b else t1.b end-t1.a from t1 where not e<=f),( -t1.f)) then b when ((d<c)) then 19 else f end FROM t1 WHERE NOT (t1.c in (t1.c,~19,13))}
} {}
do_test randexpr-2.2225 {
  db eval {SELECT (abs(~(select case max(t1.a) when min(coalesce((select ~coalesce((select max((abs(e)/abs(t1.d))*t1.b*13+t1.b) from t1 where t1.d=t1.f),t1.e)-d from t1 where e between t1.f and 19),(b))) then ~case ~cast(avg(t1.b) AS integer)+~case cast(avg(f) AS integer) when min(19) then  -min(t1.f) else (cast(avg(e) AS integer)) end when cast(avg(f) AS integer) then count(*) else count(distinct c) end-cast(avg(11) AS integer) else cast(avg(t1.f) AS integer) end | min(b) from t1))/abs(t1.b)) FROM t1 WHERE e<a}
} {}
do_test randexpr-2.2226 {
  db eval {SELECT (abs(~(select case max(t1.a) when min(coalesce((select ~coalesce((select max((abs(e)/abs(t1.d))*t1.b*13+t1.b) from t1 where t1.d=t1.f),t1.e)-d from t1 where e between t1.f and 19),(b))) then ~case ~cast(avg(t1.b) AS integer)+~case cast(avg(f) AS integer) when min(19) then  -min(t1.f) else (cast(avg(e) AS integer)) end when cast(avg(f) AS integer) then count(*) else count(distinct c) end-cast(avg(11) AS integer) else cast(avg(t1.f) AS integer) end | min(b) from t1))/abs(t1.b)) FROM t1 WHERE NOT (e<a)}
} {3}
do_test randexpr-2.2227 {
  db eval {SELECT (abs(~(select case max(t1.a) when min(coalesce((select ~coalesce((select max((abs(e)/abs(t1.d))*t1.b*13+t1.b) from t1 where t1.d=t1.f),t1.e)-d from t1 where e between t1.f and 19),(b))) then ~case ~cast(avg(t1.b) AS integer)+~case cast(avg(f) AS integer) when min(19) then  -min(t1.f) else (cast(avg(e) AS integer)) end when cast(avg(f) AS integer) then count(*) else count(distinct c) end-cast(avg(11) AS integer) else cast(avg(t1.f) AS integer) end & min(b) from t1))/abs(t1.b)) FROM t1 WHERE NOT (e<a)}
} {0}
do_test randexpr-2.2228 {
  db eval {SELECT case when not (select  -case (( -(count(*)) | cast(avg(d) AS integer))) | min((e)) when cast(avg(d) AS integer) then count(*) else count(distinct t1.e) end+max((17)) | max(t1.a)+ -count(*) from t1)-e in (t1.a,11-t1.d,t1.b) and coalesce((select max(t1.c) from t1 where case t1.d when t1.f then d else b end<>t1.d),d)>=13 then coalesce((select  -17+e from t1 where t1.a<=19),b) else (19) end FROM t1 WHERE (abs( -t1.f)/abs(t1.a))<=t1.d}
} {200}
do_test randexpr-2.2229 {
  db eval {SELECT case when not (select  -case (( -(count(*)) | cast(avg(d) AS integer))) | min((e)) when cast(avg(d) AS integer) then count(*) else count(distinct t1.e) end+max((17)) | max(t1.a)+ -count(*) from t1)-e in (t1.a,11-t1.d,t1.b) and coalesce((select max(t1.c) from t1 where case t1.d when t1.f then d else b end<>t1.d),d)>=13 then coalesce((select  -17+e from t1 where t1.a<=19),b) else (19) end FROM t1 WHERE NOT ((abs( -t1.f)/abs(t1.a))<=t1.d)}
} {}
do_test randexpr-2.2230 {
  db eval {SELECT case when not (select  -case (( -(count(*)) & cast(avg(d) AS integer))) & min((e)) when cast(avg(d) AS integer) then count(*) else count(distinct t1.e) end+max((17)) & max(t1.a)+ -count(*) from t1)-e in (t1.a,11-t1.d,t1.b) and coalesce((select max(t1.c) from t1 where case t1.d when t1.f then d else b end<>t1.d),d)>=13 then coalesce((select  -17+e from t1 where t1.a<=19),b) else (19) end FROM t1 WHERE (abs( -t1.f)/abs(t1.a))<=t1.d}
} {200}
do_test randexpr-2.2231 {
  db eval {SELECT case when 13 in (select cast(avg(11) AS integer) from t1 union select count(*) from t1) then t1.f-case c-(abs(d+~+t1.d-(abs(13)/abs(t1.e-t1.b-t1.c))*e)/abs(17*19+t1.e)) when 19 then 17 else a end when (t1.a in (select count(distinct 13) from t1 union select max(t1.f) from t1)) and c between ((c)) and (t1.a) then c else 19 end+t1.e FROM t1 WHERE 19<>t1.c}
} {519}
do_test randexpr-2.2232 {
  db eval {SELECT case when 13 in (select cast(avg(11) AS integer) from t1 union select count(*) from t1) then t1.f-case c-(abs(d+~+t1.d-(abs(13)/abs(t1.e-t1.b-t1.c))*e)/abs(17*19+t1.e)) when 19 then 17 else a end when (t1.a in (select count(distinct 13) from t1 union select max(t1.f) from t1)) and c between ((c)) and (t1.a) then c else 19 end+t1.e FROM t1 WHERE NOT (19<>t1.c)}
} {}
do_test randexpr-2.2233 {
  db eval {SELECT coalesce((select max(case when not exists(select 1 from t1 where coalesce((select a from t1 where (t1.c+t1.d<=t1.b and exists(select 1 from t1 where t1.f not in (~case when t1.d>d then t1.a else a end,( -e),t1.b))) and (c<>17)),e) in (select e from t1 union select d from t1)) then case when b not in (a,17,e) or f=t1.e then t1.d else d end else a end*19) from t1 where ((t1.c not between e and t1.e))),13) FROM t1 WHERE c not in (~t1.e,t1.e,a)}
} {1900}
do_test randexpr-2.2234 {
  db eval {SELECT coalesce((select max(case when not exists(select 1 from t1 where coalesce((select a from t1 where (t1.c+t1.d<=t1.b and exists(select 1 from t1 where t1.f not in (~case when t1.d>d then t1.a else a end,( -e),t1.b))) and (c<>17)),e) in (select e from t1 union select d from t1)) then case when b not in (a,17,e) or f=t1.e then t1.d else d end else a end*19) from t1 where ((t1.c not between e and t1.e))),13) FROM t1 WHERE NOT (c not in (~t1.e,t1.e,a))}
} {}
do_test randexpr-2.2235 {
  db eval {SELECT coalesce((select t1.f from t1 where d+(select count(distinct e) from t1)+~+ -~e-a+t1.a-b- -a*coalesce((select c-t1.d*case when ( -11<=e or b>= - -c and t1.c<t1.f) then (t1.d)-11 when a not between t1.b and t1.e then 11 else b end from t1 where t1.e<=11),t1.f)*t1.e<>19),t1.f) FROM t1 WHERE t1.f<>c}
} {600}
do_test randexpr-2.2236 {
  db eval {SELECT coalesce((select t1.f from t1 where d+(select count(distinct e) from t1)+~+ -~e-a+t1.a-b- -a*coalesce((select c-t1.d*case when ( -11<=e or b>= - -c and t1.c<t1.f) then (t1.d)-11 when a not between t1.b and t1.e then 11 else b end from t1 where t1.e<=11),t1.f)*t1.e<>19),t1.f) FROM t1 WHERE NOT (t1.f<>c)}
} {}
do_test randexpr-2.2237 {
  db eval {SELECT 19+case when d between t1.b and 19+t1.d*(select ~min(t1.e | a) from t1)-case when exists(select 1 from t1 where 19<>t1.a and 19 between case +19 when 19 then t1.e else e end and t1.a) then a when t1.a between 13 and f or (t1.f<19) and d>=t1.c and f not between a and t1.b then a else t1.d end then b else t1.a end+ -d FROM t1 WHERE f>=t1.d+(t1.a)}
} {-281}
do_test randexpr-2.2238 {
  db eval {SELECT 19+case when d between t1.b and 19+t1.d*(select ~min(t1.e | a) from t1)-case when exists(select 1 from t1 where 19<>t1.a and 19 between case +19 when 19 then t1.e else e end and t1.a) then a when t1.a between 13 and f or (t1.f<19) and d>=t1.c and f not between a and t1.b then a else t1.d end then b else t1.a end+ -d FROM t1 WHERE NOT (f>=t1.d+(t1.a))}
} {}
do_test randexpr-2.2239 {
  db eval {SELECT 19+case when d between t1.b and 19+t1.d*(select ~min(t1.e & a) from t1)-case when exists(select 1 from t1 where 19<>t1.a and 19 between case +19 when 19 then t1.e else e end and t1.a) then a when t1.a between 13 and f or (t1.f<19) and d>=t1.c and f not between a and t1.b then a else t1.d end then b else t1.a end+ -d FROM t1 WHERE f>=t1.d+(t1.a)}
} {-281}
do_test randexpr-2.2240 {
  db eval {SELECT t1.d+(select case max(t1.f) when count(distinct ~coalesce((select case when 17 in (select t1.b from t1 union select t1.e from t1) then c when (d<= -(abs(t1.a)/abs(t1.d))) then t1.b+ -case when t1.b<b then f when d not in ( - -f,11,t1.c) then d else t1.d end*a | d else e end-t1.e from t1 where a<f or a=f),c)) then cast(avg(17) AS integer) else  -~count(*) end from t1)+e FROM t1 WHERE (e-coalesce((select b+11+( -t1.e) | coalesce((select (abs(c)/abs(coalesce((select max(t1.b) from t1 where t1.d<=f),c)*t1.b)) from t1 where 13 not in (f,19,b)),e)+t1.b+t1.e+13+19-t1.b-t1.c from t1 where d>t1.a or t1.d>=t1.f),t1.a)-e)<=t1.e}
} {902}
do_test randexpr-2.2241 {
  db eval {SELECT t1.d+(select case max(t1.f) when count(distinct ~coalesce((select case when 17 in (select t1.b from t1 union select t1.e from t1) then c when (d<= -(abs(t1.a)/abs(t1.d))) then t1.b+ -case when t1.b<b then f when d not in ( - -f,11,t1.c) then d else t1.d end*a | d else e end-t1.e from t1 where a<f or a=f),c)) then cast(avg(17) AS integer) else  -~count(*) end from t1)+e FROM t1 WHERE NOT ((e-coalesce((select b+11+( -t1.e) | coalesce((select (abs(c)/abs(coalesce((select max(t1.b) from t1 where t1.d<=f),c)*t1.b)) from t1 where 13 not in (f,19,b)),e)+t1.b+t1.e+13+19-t1.b-t1.c from t1 where d>t1.a or t1.d>=t1.f),t1.a)-e)<=t1.e)}
} {}
do_test randexpr-2.2242 {
  db eval {SELECT t1.d+(select case max(t1.f) when count(distinct ~coalesce((select case when 17 in (select t1.b from t1 union select t1.e from t1) then c when (d<= -(abs(t1.a)/abs(t1.d))) then t1.b+ -case when t1.b<b then f when d not in ( - -f,11,t1.c) then d else t1.d end*a & d else e end-t1.e from t1 where a<f or a=f),c)) then cast(avg(17) AS integer) else  -~count(*) end from t1)+e FROM t1 WHERE (e-coalesce((select b+11+( -t1.e) | coalesce((select (abs(c)/abs(coalesce((select max(t1.b) from t1 where t1.d<=f),c)*t1.b)) from t1 where 13 not in (f,19,b)),e)+t1.b+t1.e+13+19-t1.b-t1.c from t1 where d>t1.a or t1.d>=t1.f),t1.a)-e)<=t1.e}
} {902}
do_test randexpr-2.2243 {
  db eval {SELECT (select count(distinct (select case ~abs(~+abs(case (max(17)) when max(coalesce((select ~b from t1 where (not exists(select 1 from t1 where  -17<>f or t1.d>=b and 19 between 19 and t1.b))),(abs(case when 19<>a then t1.c else t1.b end)/abs(19)))) then ~+cast(avg(19) AS integer) else min(t1.a) end) | case min(13) when max(11) then count(distinct  -d) else count(distinct t1.d) end)*max(t1.d) when count(*) then  -min(e) else (count(*)) end+count(*) from t1)) from t1) FROM t1 WHERE (d in (select abs(count(*) | case max((case when b<=13 then t1.b*e when case when t1.c between t1.d and a then t1.a when (f< -19) then t1.c else d end between t1.d and b then t1.e else t1.b end))-max((t1.c)) when max(t1.f) then  -abs(+cast(avg(19) AS integer)) else abs(max(t1.c)) end++max(17))- -cast(avg(f) AS integer) from t1 union select min(11) from t1))}
} {}
do_test randexpr-2.2244 {
  db eval {SELECT (select count(distinct (select case ~abs(~+abs(case (max(17)) when max(coalesce((select ~b from t1 where (not exists(select 1 from t1 where  -17<>f or t1.d>=b and 19 between 19 and t1.b))),(abs(case when 19<>a then t1.c else t1.b end)/abs(19)))) then ~+cast(avg(19) AS integer) else min(t1.a) end) | case min(13) when max(11) then count(distinct  -d) else count(distinct t1.d) end)*max(t1.d) when count(*) then  -min(e) else (count(*)) end+count(*) from t1)) from t1) FROM t1 WHERE NOT ((d in (select abs(count(*) | case max((case when b<=13 then t1.b*e when case when t1.c between t1.d and a then t1.a when (f< -19) then t1.c else d end between t1.d and b then t1.e else t1.b end))-max((t1.c)) when max(t1.f) then  -abs(+cast(avg(19) AS integer)) else abs(max(t1.c)) end++max(17))- -cast(avg(f) AS integer) from t1 union select min(11) from t1)))}
} {1}
do_test randexpr-2.2245 {
  db eval {SELECT (select count(distinct (select case ~abs(~+abs(case (max(17)) when max(coalesce((select ~b from t1 where (not exists(select 1 from t1 where  -17<>f or t1.d>=b and 19 between 19 and t1.b))),(abs(case when 19<>a then t1.c else t1.b end)/abs(19)))) then ~+cast(avg(19) AS integer) else min(t1.a) end) & case min(13) when max(11) then count(distinct  -d) else count(distinct t1.d) end)*max(t1.d) when count(*) then  -min(e) else (count(*)) end+count(*) from t1)) from t1) FROM t1 WHERE NOT ((d in (select abs(count(*) | case max((case when b<=13 then t1.b*e when case when t1.c between t1.d and a then t1.a when (f< -19) then t1.c else d end between t1.d and b then t1.e else t1.b end))-max((t1.c)) when max(t1.f) then  -abs(+cast(avg(19) AS integer)) else abs(max(t1.c)) end++max(17))- -cast(avg(f) AS integer) from t1 union select min(11) from t1)))}
} {1}
do_test randexpr-2.2246 {
  db eval {SELECT case d*coalesce((select e from t1 where t1.f in (case when not exists(select 1 from t1 where 19>=(+f-13)) then case when not not exists(select 1 from t1 where 17>=t1.d-13) then f else d end else t1.c end,c,+(abs(e)/abs(19*d | case 19 when b then 17 else b end-b))) or e between 13 and a),19) when b then c else t1.b end FROM t1 WHERE t1.b<=coalesce((select coalesce((select t1.a from t1 where not t1.b*(select max(t1.d) from t1)<a),e)-b-~11+t1.d from t1 where c not in (((abs((select  -case  -case abs(+count(*)-(count(distinct a))) when min(a) then min(d) else cast(avg(t1.a) AS integer) end when min(19) then cast(avg(a) AS integer) else min(d) end from t1) | d)/abs(d)))+19,17,11-c)),t1.c)}
} {200}
do_test randexpr-2.2247 {
  db eval {SELECT case d*coalesce((select e from t1 where t1.f in (case when not exists(select 1 from t1 where 19>=(+f-13)) then case when not not exists(select 1 from t1 where 17>=t1.d-13) then f else d end else t1.c end,c,+(abs(e)/abs(19*d | case 19 when b then 17 else b end-b))) or e between 13 and a),19) when b then c else t1.b end FROM t1 WHERE NOT (t1.b<=coalesce((select coalesce((select t1.a from t1 where not t1.b*(select max(t1.d) from t1)<a),e)-b-~11+t1.d from t1 where c not in (((abs((select  -case  -case abs(+count(*)-(count(distinct a))) when min(a) then min(d) else cast(avg(t1.a) AS integer) end when min(19) then cast(avg(a) AS integer) else min(d) end from t1) | d)/abs(d)))+19,17,11-c)),t1.c))}
} {}
do_test randexpr-2.2248 {
  db eval {SELECT 13-case when f in (select t1.f from t1 union select ~17 from t1) then ~t1.c*t1.f-(abs(17-e*c)/abs(b))*t1.b-11-a+19-coalesce((select (abs(case  -(abs(coalesce((select t1.f from t1 where t1.e in (t1.a,b,f)),t1.a))/abs(c)) when c then t1.c else c end)/abs(17)) from t1 where e<t1.c),f) else t1.c end- -d FROM t1 WHERE 17 in (select t1.f from t1 union select t1.d from t1) and (select max((case when t1.d*19 not between  -t1.e-case when e=t1.f then (select abs(max( -17)-count(*)-min(13)) from t1) else b- -(c) end*d* -t1.c and 11 then 19 else e end-t1.a-t1.f)+(a)) from t1) in (t1.b,b,t1.f) and 11<=e}
} {}
do_test randexpr-2.2249 {
  db eval {SELECT 13-case when f in (select t1.f from t1 union select ~17 from t1) then ~t1.c*t1.f-(abs(17-e*c)/abs(b))*t1.b-11-a+19-coalesce((select (abs(case  -(abs(coalesce((select t1.f from t1 where t1.e in (t1.a,b,f)),t1.a))/abs(c)) when c then t1.c else c end)/abs(17)) from t1 where e<t1.c),f) else t1.c end- -d FROM t1 WHERE NOT (17 in (select t1.f from t1 union select t1.d from t1) and (select max((case when t1.d*19 not between  -t1.e-case when e=t1.f then (select abs(max( -17)-count(*)-min(13)) from t1) else b- -(c) end*d* -t1.c and 11 then 19 else e end-t1.a-t1.f)+(a)) from t1) in (t1.b,b,t1.f) and 11<=e)}
} {331505}
do_test randexpr-2.2250 {
  db eval {SELECT case when case when case when case when t1.b<> -c then (b)* -19 else t1.d end<=11 or 17 not between t1.f and 13 or a not in (t1.c,t1.b,11) then c else c end<>t1.a and (f) in (select cast(avg(11) AS integer) from t1 union select case max(b) when (min(t1.c)) then count(distinct f) else max(19) end from t1) then 13 else d end | f-t1.d<=t1.f then f else 19 end FROM t1 WHERE ((f not between t1.f and d))}
} {600}
do_test randexpr-2.2251 {
  db eval {SELECT case when case when case when case when t1.b<> -c then (b)* -19 else t1.d end<=11 or 17 not between t1.f and 13 or a not in (t1.c,t1.b,11) then c else c end<>t1.a and (f) in (select cast(avg(11) AS integer) from t1 union select case max(b) when (min(t1.c)) then count(distinct f) else max(19) end from t1) then 13 else d end | f-t1.d<=t1.f then f else 19 end FROM t1 WHERE NOT (((f not between t1.f and d)))}
} {}
do_test randexpr-2.2252 {
  db eval {SELECT case when case when case when case when t1.b<> -c then (b)* -19 else t1.d end<=11 or 17 not between t1.f and 13 or a not in (t1.c,t1.b,11) then c else c end<>t1.a and (f) in (select cast(avg(11) AS integer) from t1 union select case max(b) when (min(t1.c)) then count(distinct f) else max(19) end from t1) then 13 else d end & f-t1.d<=t1.f then f else 19 end FROM t1 WHERE ((f not between t1.f and d))}
} {600}
do_test randexpr-2.2253 {
  db eval {SELECT d-b-(abs(a)/abs(coalesce((select b from t1 where coalesce((select t1.f from t1 where 13>=f-b),t1.c)*case when coalesce((select case (d*t1.e+b) when t1.a-13 then  - -t1.d else t1.a end+13 from t1 where e>=t1.f),11) | b<t1.e then d else c end between c and d),11)-19))+11 FROM t1 WHERE d>=case when coalesce((select max(case when f<>~b | coalesce((select max(11*c) from t1 where 17=t1.f),t1.d)*d then b when a in (c,(t1.d),(f)) then a else 19 end-t1.f) from t1 where not 13 in (select cast(avg(t1.b) AS integer)-cast(avg( -t1.a) AS integer) from t1 union select count(*) from t1)),17) not in ((t1.f),c, -19) and e between 11 and (19) then 19 else t1.d end}
} {199}
do_test randexpr-2.2254 {
  db eval {SELECT d-b-(abs(a)/abs(coalesce((select b from t1 where coalesce((select t1.f from t1 where 13>=f-b),t1.c)*case when coalesce((select case (d*t1.e+b) when t1.a-13 then  - -t1.d else t1.a end+13 from t1 where e>=t1.f),11) | b<t1.e then d else c end between c and d),11)-19))+11 FROM t1 WHERE NOT (d>=case when coalesce((select max(case when f<>~b | coalesce((select max(11*c) from t1 where 17=t1.f),t1.d)*d then b when a in (c,(t1.d),(f)) then a else 19 end-t1.f) from t1 where not 13 in (select cast(avg(t1.b) AS integer)-cast(avg( -t1.a) AS integer) from t1 union select count(*) from t1)),17) not in ((t1.f),c, -19) and e between 11 and (19) then 19 else t1.d end)}
} {}
do_test randexpr-2.2255 {
  db eval {SELECT d-b-(abs(a)/abs(coalesce((select b from t1 where coalesce((select t1.f from t1 where 13>=f-b),t1.c)*case when coalesce((select case (d*t1.e+b) when t1.a-13 then  - -t1.d else t1.a end+13 from t1 where e>=t1.f),11) & b<t1.e then d else c end between c and d),11)-19))+11 FROM t1 WHERE d>=case when coalesce((select max(case when f<>~b | coalesce((select max(11*c) from t1 where 17=t1.f),t1.d)*d then b when a in (c,(t1.d),(f)) then a else 19 end-t1.f) from t1 where not 13 in (select cast(avg(t1.b) AS integer)-cast(avg( -t1.a) AS integer) from t1 union select count(*) from t1)),17) not in ((t1.f),c, -19) and e between 11 and (19) then 19 else t1.d end}
} {199}
do_test randexpr-2.2256 {
  db eval {SELECT coalesce((select max(coalesce((select 13 from t1 where not t1.b<>e*b),t1.c*case when d>=case case 13 when coalesce((select ~~t1.f*(abs(t1.f)/abs(t1.e))-e |  -t1.b from t1 where a in (11,13,t1.e)),d)*t1.e then  -e else t1.b end when t1.e then 11 else t1.e end then  -f else c end) | t1.a) from t1 where e>t1.d), -(t1.f)) FROM t1 WHERE not  -13 in (select (+(case case min(a+t1.a) when abs(count(*)-count(distinct t1.d-+(f)-case 19 when b then t1.b else a end)) then case count(*)*max(c) when ~ -count(*)*cast(avg(t1.e) AS integer)*count(distinct  -a) then count(*) else cast(avg(19) AS integer) end else cast(avg(b) AS integer) end when min(f) then max( -a) else (count(*)) end)*count(distinct t1.f)-count(*)) from t1 union select count(distinct f) from t1)}
} {90100}
do_test randexpr-2.2257 {
  db eval {SELECT coalesce((select max(coalesce((select 13 from t1 where not t1.b<>e*b),t1.c*case when d>=case case 13 when coalesce((select ~~t1.f*(abs(t1.f)/abs(t1.e))-e |  -t1.b from t1 where a in (11,13,t1.e)),d)*t1.e then  -e else t1.b end when t1.e then 11 else t1.e end then  -f else c end) | t1.a) from t1 where e>t1.d), -(t1.f)) FROM t1 WHERE NOT (not  -13 in (select (+(case case min(a+t1.a) when abs(count(*)-count(distinct t1.d-+(f)-case 19 when b then t1.b else a end)) then case count(*)*max(c) when ~ -count(*)*cast(avg(t1.e) AS integer)*count(distinct  -a) then count(*) else cast(avg(19) AS integer) end else cast(avg(b) AS integer) end when min(f) then max( -a) else (count(*)) end)*count(distinct t1.f)-count(*)) from t1 union select count(distinct f) from t1))}
} {}
do_test randexpr-2.2258 {
  db eval {SELECT coalesce((select max(coalesce((select 13 from t1 where not t1.b<>e*b),t1.c*case when d>=case case 13 when coalesce((select ~~t1.f*(abs(t1.f)/abs(t1.e))-e &  -t1.b from t1 where a in (11,13,t1.e)),d)*t1.e then  -e else t1.b end when t1.e then 11 else t1.e end then  -f else c end) & t1.a) from t1 where e>t1.d), -(t1.f)) FROM t1 WHERE not  -13 in (select (+(case case min(a+t1.a) when abs(count(*)-count(distinct t1.d-+(f)-case 19 when b then t1.b else a end)) then case count(*)*max(c) when ~ -count(*)*cast(avg(t1.e) AS integer)*count(distinct  -a) then count(*) else cast(avg(19) AS integer) end else cast(avg(b) AS integer) end when min(f) then max( -a) else (count(*)) end)*count(distinct t1.f)-count(*)) from t1 union select count(distinct f) from t1)}
} {0}
do_test randexpr-2.2259 {
  db eval {SELECT coalesce((select max(t1.e*~t1.b- -t1.b-t1.b-coalesce((select t1.a from t1 where exists(select 1 from t1 where ~d+case case when a between b and f then 13 else  -17 end-13 when  -19 then t1.f else d end+t1.b<>e or not t1.e between 19 and t1.a or 11 in (19,c, -19))),a)*e) from t1 where t1.f<19),t1.e)-13 FROM t1 WHERE t1.b not between e and 13}
} {487}
do_test randexpr-2.2260 {
  db eval {SELECT coalesce((select max(t1.e*~t1.b- -t1.b-t1.b-coalesce((select t1.a from t1 where exists(select 1 from t1 where ~d+case case when a between b and f then 13 else  -17 end-13 when  -19 then t1.f else d end+t1.b<>e or not t1.e between 19 and t1.a or 11 in (19,c, -19))),a)*e) from t1 where t1.f<19),t1.e)-13 FROM t1 WHERE NOT (t1.b not between e and 13)}
} {}
do_test randexpr-2.2261 {
  db eval {SELECT (select (count(distinct case t1.d+case when (coalesce((select max((select + -cast(avg(b) AS integer)-min(19) | (cast(avg(19) AS integer)) from t1)) from t1 where ~c+t1.c<t1.d),(c)) in (select t1.c from t1 union select t1.f from t1)) then (select abs( -min(t1.e)) | min(t1.c) from t1) when 11 not between  -d and a or a<>t1.a and f between t1.e and d and f<=19 then t1.f else t1.b end-c*a when t1.f then e else t1.b end)) from t1) FROM t1 WHERE not b*c+d<>b}
} {}
do_test randexpr-2.2262 {
  db eval {SELECT (select (count(distinct case t1.d+case when (coalesce((select max((select + -cast(avg(b) AS integer)-min(19) | (cast(avg(19) AS integer)) from t1)) from t1 where ~c+t1.c<t1.d),(c)) in (select t1.c from t1 union select t1.f from t1)) then (select abs( -min(t1.e)) | min(t1.c) from t1) when 11 not between  -d and a or a<>t1.a and f between t1.e and d and f<=19 then t1.f else t1.b end-c*a when t1.f then e else t1.b end)) from t1) FROM t1 WHERE NOT (not b*c+d<>b)}
} {1}
do_test randexpr-2.2263 {
  db eval {SELECT (select (count(distinct case t1.d+case when (coalesce((select max((select + -cast(avg(b) AS integer)-min(19) & (cast(avg(19) AS integer)) from t1)) from t1 where ~c+t1.c<t1.d),(c)) in (select t1.c from t1 union select t1.f from t1)) then (select abs( -min(t1.e)) & min(t1.c) from t1) when 11 not between  -d and a or a<>t1.a and f between t1.e and d and f<=19 then t1.f else t1.b end-c*a when t1.f then e else t1.b end)) from t1) FROM t1 WHERE NOT (not b*c+d<>b)}
} {1}
do_test randexpr-2.2264 {
  db eval {SELECT t1.b+case case c when f-((abs(t1.f)/abs(coalesce((select max(f+t1.d | t1.c*e+f+~case when c not between b and t1.a or 11<19 then c-d else t1.f end+e-t1.b*11+t1.e) from t1 where 17 not between e and 19),19)))) then d else a end when (t1.c) then t1.f else f end FROM t1 WHERE (b)-t1.c*19-t1.b>17*b-13}
} {}
do_test randexpr-2.2265 {
  db eval {SELECT t1.b+case case c when f-((abs(t1.f)/abs(coalesce((select max(f+t1.d | t1.c*e+f+~case when c not between b and t1.a or 11<19 then c-d else t1.f end+e-t1.b*11+t1.e) from t1 where 17 not between e and 19),19)))) then d else a end when (t1.c) then t1.f else f end FROM t1 WHERE NOT ((b)-t1.c*19-t1.b>17*b-13)}
} {800}
do_test randexpr-2.2266 {
  db eval {SELECT t1.b+case case c when f-((abs(t1.f)/abs(coalesce((select max(f+t1.d & t1.c*e+f+~case when c not between b and t1.a or 11<19 then c-d else t1.f end+e-t1.b*11+t1.e) from t1 where 17 not between e and 19),19)))) then d else a end when (t1.c) then t1.f else f end FROM t1 WHERE NOT ((b)-t1.c*19-t1.b>17*b-13)}
} {800}
do_test randexpr-2.2267 {
  db eval {SELECT coalesce((select coalesce((select ((abs(19)/abs(17))) from t1 where +13 | d>d),13-(select abs(abs(~count(*)))+~count(*) from t1)+(t1.c*t1.e*(abs(19+(13))/abs(a)))-coalesce((select 17 from t1 where c<>e and b not in ((d),t1.b,b)),t1.c)+t1.d)-13 from t1 where t1.f<b),11)+ -t1.c FROM t1 WHERE (t1.e in (select  -(+min(f*t1.c)- -max(t1.a))-+min(b) | count(distinct 17) from t1 union select abs(case count(*) when abs(min(d*t1.c-t1.b*~b+c) | (max(case when not 19<(e) then 19 when  -17>19 then 17 else t1.c end)-count(*))) then max(11) else +max(b) end) from t1))}
} {}
do_test randexpr-2.2268 {
  db eval {SELECT coalesce((select coalesce((select ((abs(19)/abs(17))) from t1 where +13 | d>d),13-(select abs(abs(~count(*)))+~count(*) from t1)+(t1.c*t1.e*(abs(19+(13))/abs(a)))-coalesce((select 17 from t1 where c<>e and b not in ((d),t1.b,b)),t1.c)+t1.d)-13 from t1 where t1.f<b),11)+ -t1.c FROM t1 WHERE NOT ((t1.e in (select  -(+min(f*t1.c)- -max(t1.a))-+min(b) | count(distinct 17) from t1 union select abs(case count(*) when abs(min(d*t1.c-t1.b*~b+c) | (max(case when not 19<(e) then 19 when  -17>19 then 17 else t1.c end)-count(*))) then max(11) else +max(b) end) from t1)))}
} {-289}
do_test randexpr-2.2269 {
  db eval {SELECT coalesce((select coalesce((select ((abs(19)/abs(17))) from t1 where +13 & d>d),13-(select abs(abs(~count(*)))+~count(*) from t1)+(t1.c*t1.e*(abs(19+(13))/abs(a)))-coalesce((select 17 from t1 where c<>e and b not in ((d),t1.b,b)),t1.c)+t1.d)-13 from t1 where t1.f<b),11)+ -t1.c FROM t1 WHERE NOT ((t1.e in (select  -(+min(f*t1.c)- -max(t1.a))-+min(b) | count(distinct 17) from t1 union select abs(case count(*) when abs(min(d*t1.c-t1.b*~b+c) | (max(case when not 19<(e) then 19 when  -17>19 then 17 else t1.c end)-count(*))) then max(11) else +max(b) end) from t1)))}
} {-289}
do_test randexpr-2.2270 {
  db eval {SELECT coalesce((select case d when e then t1.f else d++(abs((select count(*) from t1)-case when t1.f*case when t1.b-c in (select  -cast(avg(e) AS integer) from t1 union select max(t1.a) from t1) or b between t1.a and  -17 and  -t1.f not between 17 and a then t1.e when 17<>11 then (abs(19)/abs(f)) else 17 end-17 not in (13,11,c) then t1.f else t1.c end)/abs(c))*t1.e end from t1 where f between t1.c and 17),t1.f) FROM t1 WHERE t1.b<>19}
} {600}
do_test randexpr-2.2271 {
  db eval {SELECT coalesce((select case d when e then t1.f else d++(abs((select count(*) from t1)-case when t1.f*case when t1.b-c in (select  -cast(avg(e) AS integer) from t1 union select max(t1.a) from t1) or b between t1.a and  -17 and  -t1.f not between 17 and a then t1.e when 17<>11 then (abs(19)/abs(f)) else 17 end-17 not in (13,11,c) then t1.f else t1.c end)/abs(c))*t1.e end from t1 where f between t1.c and 17),t1.f) FROM t1 WHERE NOT (t1.b<>19)}
} {}
do_test randexpr-2.2272 {
  db eval {SELECT t1.f-case when ((t1.a in (select case case +min(case when coalesce((select max(a) from t1 where t1.e not between f and t1.b),f)<>(t1.d) then  - -t1.f else 19 end)-case count(*)+(count(distinct t1.d)) when  -min(e) then max(t1.f) else min(19) end when cast(avg(13) AS integer) then cast(avg( -t1.a) AS integer) else (min(t1.f)) end when (count(distinct t1.e)) then  -cast(avg(a) AS integer) else cast(avg(19) AS integer) end | count(distinct 13)+ -count(*) from t1 union select  -max(t1.b) from t1))) then a when d between a and 11 or t1.e<>c then +t1.a-(t1.e) else t1.e end FROM t1 WHERE t1.e between d | t1.a*13 and 11+13*17+b*c++13-~b}
} {}
do_test randexpr-2.2273 {
  db eval {SELECT t1.f-case when ((t1.a in (select case case +min(case when coalesce((select max(a) from t1 where t1.e not between f and t1.b),f)<>(t1.d) then  - -t1.f else 19 end)-case count(*)+(count(distinct t1.d)) when  -min(e) then max(t1.f) else min(19) end when cast(avg(13) AS integer) then cast(avg( -t1.a) AS integer) else (min(t1.f)) end when (count(distinct t1.e)) then  -cast(avg(a) AS integer) else cast(avg(19) AS integer) end | count(distinct 13)+ -count(*) from t1 union select  -max(t1.b) from t1))) then a when d between a and 11 or t1.e<>c then +t1.a-(t1.e) else t1.e end FROM t1 WHERE NOT (t1.e between d | t1.a*13 and 11+13*17+b*c++13-~b)}
} {1000}
do_test randexpr-2.2274 {
  db eval {SELECT t1.f-case when ((t1.a in (select case case +min(case when coalesce((select max(a) from t1 where t1.e not between f and t1.b),f)<>(t1.d) then  - -t1.f else 19 end)-case count(*)+(count(distinct t1.d)) when  -min(e) then max(t1.f) else min(19) end when cast(avg(13) AS integer) then cast(avg( -t1.a) AS integer) else (min(t1.f)) end when (count(distinct t1.e)) then  -cast(avg(a) AS integer) else cast(avg(19) AS integer) end & count(distinct 13)+ -count(*) from t1 union select  -max(t1.b) from t1))) then a when d between a and 11 or t1.e<>c then +t1.a-(t1.e) else t1.e end FROM t1 WHERE NOT (t1.e between d | t1.a*13 and 11+13*17+b*c++13-~b)}
} {1000}
do_test randexpr-2.2275 {
  db eval {SELECT coalesce((select ~(abs(e)/abs(case when exists(select 1 from t1 where 19=+c or exists(select 1 from t1 where not exists(select 1 from t1 where 11>=d or b not between b and 19)) or t1.a not in (t1.a,(11),13)) then e-13+a-c else a end))*t1.f-(19) | 19 from t1 where t1.d in (select  -(cast(avg(19) AS integer)) from t1 union select count(distinct (t1.e)) from t1) and (f in (a,c,(t1.a))) and a between 11 and 11 and t1.d>=t1.f and 11 not in ((t1.f),e,(f)) and 13 not in (t1.c,t1.d,t1.c)),t1.d) FROM t1 WHERE not exists(select 1 from t1 where not coalesce((select max(b) from t1 where coalesce((select t1.f from t1 where t1.f not between t1.e and coalesce((select 13*+ -t1.a | e+case when t1.a not in (case t1.f when d then 19 else 11 end,f*e+19,t1.e+(d)) then 13 else t1.d end+t1.c-17 from t1 where t1.c>=t1.d),t1.c)),t1.d)>t1.c),11) not between b and t1.f)}
} {}
do_test randexpr-2.2276 {
  db eval {SELECT coalesce((select ~(abs(e)/abs(case when exists(select 1 from t1 where 19=+c or exists(select 1 from t1 where not exists(select 1 from t1 where 11>=d or b not between b and 19)) or t1.a not in (t1.a,(11),13)) then e-13+a-c else a end))*t1.f-(19) | 19 from t1 where t1.d in (select  -(cast(avg(19) AS integer)) from t1 union select count(distinct (t1.e)) from t1) and (f in (a,c,(t1.a))) and a between 11 and 11 and t1.d>=t1.f and 11 not in ((t1.f),e,(f)) and 13 not in (t1.c,t1.d,t1.c)),t1.d) FROM t1 WHERE NOT (not exists(select 1 from t1 where not coalesce((select max(b) from t1 where coalesce((select t1.f from t1 where t1.f not between t1.e and coalesce((select 13*+ -t1.a | e+case when t1.a not in (case t1.f when d then 19 else 11 end,f*e+19,t1.e+(d)) then 13 else t1.d end+t1.c-17 from t1 where t1.c>=t1.d),t1.c)),t1.d)>t1.c),11) not between b and t1.f))}
} {400}
do_test randexpr-2.2277 {
  db eval {SELECT coalesce((select ~(abs(e)/abs(case when exists(select 1 from t1 where 19=+c or exists(select 1 from t1 where not exists(select 1 from t1 where 11>=d or b not between b and 19)) or t1.a not in (t1.a,(11),13)) then e-13+a-c else a end))*t1.f-(19) & 19 from t1 where t1.d in (select  -(cast(avg(19) AS integer)) from t1 union select count(distinct (t1.e)) from t1) and (f in (a,c,(t1.a))) and a between 11 and 11 and t1.d>=t1.f and 11 not in ((t1.f),e,(f)) and 13 not in (t1.c,t1.d,t1.c)),t1.d) FROM t1 WHERE NOT (not exists(select 1 from t1 where not coalesce((select max(b) from t1 where coalesce((select t1.f from t1 where t1.f not between t1.e and coalesce((select 13*+ -t1.a | e+case when t1.a not in (case t1.f when d then 19 else 11 end,f*e+19,t1.e+(d)) then 13 else t1.d end+t1.c-17 from t1 where t1.c>=t1.d),t1.c)),t1.d)>t1.c),11) not between b and t1.f))}
} {400}
do_test randexpr-2.2278 {
  db eval {SELECT case when (select +case  -+ -case min(t1.f) when cast(avg(t1.a) AS integer) then abs(~case (min(t1.a)) when (count(*)) then (min(e)) else count(*) end) else ( -cast(avg(b) AS integer)) end*count(*) | count(distinct 11) when  -cast(avg(13) AS integer) then  -min(13) else max(b) end+max(a) from t1) in ((abs(coalesce((select max(11*a) from t1 where t1.b>11-(select  -cast(avg(t1.d) AS integer) from t1)),case when exists(select 1 from t1 where t1.f<13) then a else e end))/abs(c)) | t1.f,f,f) then t1.e else a end FROM t1 WHERE (select case min(case when not 17<11 then (abs(+(d)*t1.c+e-f)/abs(13)) when b between a and 11 then e else b end) when abs(min(t1.b) | (+count(*))) | ~case ( -count(*))-cast(avg(a) AS integer) when count(distinct t1.a) then  -count(distinct f) else count(distinct 11) end then max( -t1.d) else  -max(f) end from t1)-~c*t1.a not in (t1.e,t1.c,t1.a)}
} {100}
do_test randexpr-2.2279 {
  db eval {SELECT case when (select +case  -+ -case min(t1.f) when cast(avg(t1.a) AS integer) then abs(~case (min(t1.a)) when (count(*)) then (min(e)) else count(*) end) else ( -cast(avg(b) AS integer)) end*count(*) | count(distinct 11) when  -cast(avg(13) AS integer) then  -min(13) else max(b) end+max(a) from t1) in ((abs(coalesce((select max(11*a) from t1 where t1.b>11-(select  -cast(avg(t1.d) AS integer) from t1)),case when exists(select 1 from t1 where t1.f<13) then a else e end))/abs(c)) | t1.f,f,f) then t1.e else a end FROM t1 WHERE NOT ((select case min(case when not 17<11 then (abs(+(d)*t1.c+e-f)/abs(13)) when b between a and 11 then e else b end) when abs(min(t1.b) | (+count(*))) | ~case ( -count(*))-cast(avg(a) AS integer) when count(distinct t1.a) then  -count(distinct f) else count(distinct 11) end then max( -t1.d) else  -max(f) end from t1)-~c*t1.a not in (t1.e,t1.c,t1.a))}
} {}
do_test randexpr-2.2280 {
  db eval {SELECT case when (select +case  -+ -case min(t1.f) when cast(avg(t1.a) AS integer) then abs(~case (min(t1.a)) when (count(*)) then (min(e)) else count(*) end) else ( -cast(avg(b) AS integer)) end*count(*) & count(distinct 11) when  -cast(avg(13) AS integer) then  -min(13) else max(b) end+max(a) from t1) in ((abs(coalesce((select max(11*a) from t1 where t1.b>11-(select  -cast(avg(t1.d) AS integer) from t1)),case when exists(select 1 from t1 where t1.f<13) then a else e end))/abs(c)) & t1.f,f,f) then t1.e else a end FROM t1 WHERE (select case min(case when not 17<11 then (abs(+(d)*t1.c+e-f)/abs(13)) when b between a and 11 then e else b end) when abs(min(t1.b) | (+count(*))) | ~case ( -count(*))-cast(avg(a) AS integer) when count(distinct t1.a) then  -count(distinct f) else count(distinct 11) end then max( -t1.d) else  -max(f) end from t1)-~c*t1.a not in (t1.e,t1.c,t1.a)}
} {100}
do_test randexpr-2.2281 {
  db eval {SELECT case when ~t1.b | 13>=~coalesce((select t1.e from t1 where 11 in (select  -case +max(case when (t1.f) in (t1.b,t1.a,t1.f) then f else e end) when max(f)*cast(avg(t1.d) AS integer) then cast(avg(c) AS integer) else  -( - -max(t1.f)) end from t1 union select count(*) from t1)),b | ( -t1.e))*t1.c*t1.a*t1.d-f then a when 19 not between  -t1.e and t1.e or f not between  -a and 19 then d else 11 end FROM t1 WHERE not (d in (select t1.c from t1 union select 11 from t1))}
} {400}
do_test randexpr-2.2282 {
  db eval {SELECT case when ~t1.b | 13>=~coalesce((select t1.e from t1 where 11 in (select  -case +max(case when (t1.f) in (t1.b,t1.a,t1.f) then f else e end) when max(f)*cast(avg(t1.d) AS integer) then cast(avg(c) AS integer) else  -( - -max(t1.f)) end from t1 union select count(*) from t1)),b | ( -t1.e))*t1.c*t1.a*t1.d-f then a when 19 not between  -t1.e and t1.e or f not between  -a and 19 then d else 11 end FROM t1 WHERE NOT (not (d in (select t1.c from t1 union select 11 from t1)))}
} {}
do_test randexpr-2.2283 {
  db eval {SELECT case when ~t1.b & 13>=~coalesce((select t1.e from t1 where 11 in (select  -case +max(case when (t1.f) in (t1.b,t1.a,t1.f) then f else e end) when max(f)*cast(avg(t1.d) AS integer) then cast(avg(c) AS integer) else  -( - -max(t1.f)) end from t1 union select count(*) from t1)),b & ( -t1.e))*t1.c*t1.a*t1.d-f then a when 19 not between  -t1.e and t1.e or f not between  -a and 19 then d else 11 end FROM t1 WHERE not (d in (select t1.c from t1 union select 11 from t1))}
} {100}
do_test randexpr-2.2284 {
  db eval {SELECT coalesce((select c from t1 where 19 in (select case count(*) when count(distinct c)*+cast(avg(13) AS integer) then max(t1.d) else max(case case when exists(select 1 from t1 where 13 not in (d,e,(19)) and 13 between t1.d and t1.f) then t1.a when b in (t1.a,a,17) then case when t1.a not between 13 and c then (t1.b) else t1.b end else 19 end when 13 then a else 19 end) end from t1 union select (abs(abs(~cast(avg(t1.d) AS integer))) | cast(avg(t1.a) AS integer)) from t1)),t1.e-11)*(t1.a) FROM t1 WHERE not exists(select 1 from t1 where t1.e in (coalesce((select max(13) from t1 where 19 in (select f from t1 union select a from t1) or (not exists(select 1 from t1 where t1.a<=(19)*c*c | 13))),+e-(f)*case when t1.c not in (coalesce((select max(t1.a) from t1 where not c<(19)),19),e,(19)) then d else f end)+a,19,17)) or (d<t1.a)}
} {30000}
do_test randexpr-2.2285 {
  db eval {SELECT coalesce((select c from t1 where 19 in (select case count(*) when count(distinct c)*+cast(avg(13) AS integer) then max(t1.d) else max(case case when exists(select 1 from t1 where 13 not in (d,e,(19)) and 13 between t1.d and t1.f) then t1.a when b in (t1.a,a,17) then case when t1.a not between 13 and c then (t1.b) else t1.b end else 19 end when 13 then a else 19 end) end from t1 union select (abs(abs(~cast(avg(t1.d) AS integer))) | cast(avg(t1.a) AS integer)) from t1)),t1.e-11)*(t1.a) FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.e in (coalesce((select max(13) from t1 where 19 in (select f from t1 union select a from t1) or (not exists(select 1 from t1 where t1.a<=(19)*c*c | 13))),+e-(f)*case when t1.c not in (coalesce((select max(t1.a) from t1 where not c<(19)),19),e,(19)) then d else f end)+a,19,17)) or (d<t1.a))}
} {}
do_test randexpr-2.2286 {
  db eval {SELECT coalesce((select c from t1 where 19 in (select case count(*) when count(distinct c)*+cast(avg(13) AS integer) then max(t1.d) else max(case case when exists(select 1 from t1 where 13 not in (d,e,(19)) and 13 between t1.d and t1.f) then t1.a when b in (t1.a,a,17) then case when t1.a not between 13 and c then (t1.b) else t1.b end else 19 end when 13 then a else 19 end) end from t1 union select (abs(abs(~cast(avg(t1.d) AS integer))) & cast(avg(t1.a) AS integer)) from t1)),t1.e-11)*(t1.a) FROM t1 WHERE not exists(select 1 from t1 where t1.e in (coalesce((select max(13) from t1 where 19 in (select f from t1 union select a from t1) or (not exists(select 1 from t1 where t1.a<=(19)*c*c | 13))),+e-(f)*case when t1.c not in (coalesce((select max(t1.a) from t1 where not c<(19)),19),e,(19)) then d else f end)+a,19,17)) or (d<t1.a)}
} {30000}
do_test randexpr-2.2287 {
  db eval {SELECT  -~a+d-case d when  -(select max(d)*~min(coalesce((select max(t1.e) from t1 where (exists(select 1 from t1 where 17<>13))),t1.a)-f-a+t1.f) | case (cast(avg(t1.c) AS integer)) when cast(avg(t1.a) AS integer)-(count(*))+max(19) then  - -max(19) else cast(avg(e) AS integer) end from t1)+(select cast(avg(b) AS integer) from t1) then t1.a else e-t1.d end-17+11 FROM t1 WHERE +c-(c)*d in (coalesce((select max( -t1.d-d-13) from t1 where (t1.c) not between (abs(13)/abs(t1.c)) and t1.b),d),11,c)}
} {}
do_test randexpr-2.2288 {
  db eval {SELECT  -~a+d-case d when  -(select max(d)*~min(coalesce((select max(t1.e) from t1 where (exists(select 1 from t1 where 17<>13))),t1.a)-f-a+t1.f) | case (cast(avg(t1.c) AS integer)) when cast(avg(t1.a) AS integer)-(count(*))+max(19) then  - -max(19) else cast(avg(e) AS integer) end from t1)+(select cast(avg(b) AS integer) from t1) then t1.a else e-t1.d end-17+11 FROM t1 WHERE NOT (+c-(c)*d in (coalesce((select max( -t1.d-d-13) from t1 where (t1.c) not between (abs(13)/abs(t1.c)) and t1.b),d),11,c))}
} {395}
do_test randexpr-2.2289 {
  db eval {SELECT  -~a+d-case d when  -(select max(d)*~min(coalesce((select max(t1.e) from t1 where (exists(select 1 from t1 where 17<>13))),t1.a)-f-a+t1.f) & case (cast(avg(t1.c) AS integer)) when cast(avg(t1.a) AS integer)-(count(*))+max(19) then  - -max(19) else cast(avg(e) AS integer) end from t1)+(select cast(avg(b) AS integer) from t1) then t1.a else e-t1.d end-17+11 FROM t1 WHERE NOT (+c-(c)*d in (coalesce((select max( -t1.d-d-13) from t1 where (t1.c) not between (abs(13)/abs(t1.c)) and t1.b),d),11,c))}
} {395}
do_test randexpr-2.2290 {
  db eval {SELECT case when 17 in (case (abs(coalesce((select max((select cast(avg(case when 17-(t1.b)+t1.a | b+b in (select b from t1 union select 17 from t1) then c when t1.f in (select t1.a from t1 union select 19 from t1) then 11 else t1.c end) AS integer) from t1)) from t1 where t1.e>=t1.e or (b)<b or t1.a>=b and c not in (f,t1.a,t1.a)),d))/abs(t1.b)) when 17 then t1.b else 13 end-a,13,17) then t1.a else  -d end FROM t1 WHERE t1.e<t1.e}
} {}
do_test randexpr-2.2291 {
  db eval {SELECT case when 17 in (case (abs(coalesce((select max((select cast(avg(case when 17-(t1.b)+t1.a | b+b in (select b from t1 union select 17 from t1) then c when t1.f in (select t1.a from t1 union select 19 from t1) then 11 else t1.c end) AS integer) from t1)) from t1 where t1.e>=t1.e or (b)<b or t1.a>=b and c not in (f,t1.a,t1.a)),d))/abs(t1.b)) when 17 then t1.b else 13 end-a,13,17) then t1.a else  -d end FROM t1 WHERE NOT (t1.e<t1.e)}
} {100}
do_test randexpr-2.2292 {
  db eval {SELECT case when 17 in (case (abs(coalesce((select max((select cast(avg(case when 17-(t1.b)+t1.a & b+b in (select b from t1 union select 17 from t1) then c when t1.f in (select t1.a from t1 union select 19 from t1) then 11 else t1.c end) AS integer) from t1)) from t1 where t1.e>=t1.e or (b)<b or t1.a>=b and c not in (f,t1.a,t1.a)),d))/abs(t1.b)) when 17 then t1.b else 13 end-a,13,17) then t1.a else  -d end FROM t1 WHERE NOT (t1.e<t1.e)}
} {100}
do_test randexpr-2.2293 {
  db eval {SELECT case t1.a when coalesce((select a from t1 where t1.b>19),b-case when +13>case when (coalesce((select b from t1 where coalesce((select max(t1.f) from t1 where 17<=case c when t1.e+f then d else case when 11<17 and t1.d<=t1.e then 13 when t1.d<>f then (t1.f) else c end end*t1.c),a) in (select 17 from t1 union select b from t1)),t1.c)>= -11) then (a)*t1.a else 19 end then 13 else 17 end*19) then d else (t1.a) end FROM t1 WHERE t1.d+t1.b not in (b,f,coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where c-t1.b not between case when coalesce((select max(~t1.e) from t1 where f not in (t1.b,17,t1.a)),t1.e) not in (e,13,(t1.d)) then 11 when t1.d>=17 then t1.c else 11 end and (11) and (exists(select 1 from t1 where t1.b<>11))) or 13 in (select max(t1.d) from t1 union select max(b) from t1)),t1.b+19+a))}
} {}
do_test randexpr-2.2294 {
  db eval {SELECT case t1.a when coalesce((select a from t1 where t1.b>19),b-case when +13>case when (coalesce((select b from t1 where coalesce((select max(t1.f) from t1 where 17<=case c when t1.e+f then d else case when 11<17 and t1.d<=t1.e then 13 when t1.d<>f then (t1.f) else c end end*t1.c),a) in (select 17 from t1 union select b from t1)),t1.c)>= -11) then (a)*t1.a else 19 end then 13 else 17 end*19) then d else (t1.a) end FROM t1 WHERE NOT (t1.d+t1.b not in (b,f,coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where c-t1.b not between case when coalesce((select max(~t1.e) from t1 where f not in (t1.b,17,t1.a)),t1.e) not in (e,13,(t1.d)) then 11 when t1.d>=17 then t1.c else 11 end and (11) and (exists(select 1 from t1 where t1.b<>11))) or 13 in (select max(t1.d) from t1 union select max(b) from t1)),t1.b+19+a)))}
} {400}
do_test randexpr-2.2295 {
  db eval {SELECT coalesce((select max((coalesce((select coalesce((select max(case when case when e<case 17 when case when t1.e=f then a else t1.b end then 13 else d end then t1.b when 13<>t1.f then t1.b else c end<b or 13<17 then e* -17 else 11 end*e | e) from t1 where 19<>19),t1.f) from t1 where t1.e<>t1.d),t1.b))) from t1 where 11=t1.c), -c) FROM t1 WHERE not exists(select 1 from t1 where  -~e not in (c++case when 17+t1.c<coalesce((select max(t1.c) from t1 where (not exists(select 1 from t1 where 19+coalesce((select a from t1 where d in (( -t1.a), - -b, -t1.f)),e)-a-c>=d))),f-13) then a else (t1.a) end+f*19-a,b,f)) and t1.a=b}
} {}
do_test randexpr-2.2296 {
  db eval {SELECT coalesce((select max((coalesce((select coalesce((select max(case when case when e<case 17 when case when t1.e=f then a else t1.b end then 13 else d end then t1.b when 13<>t1.f then t1.b else c end<b or 13<17 then e* -17 else 11 end*e | e) from t1 where 19<>19),t1.f) from t1 where t1.e<>t1.d),t1.b))) from t1 where 11=t1.c), -c) FROM t1 WHERE NOT (not exists(select 1 from t1 where  -~e not in (c++case when 17+t1.c<coalesce((select max(t1.c) from t1 where (not exists(select 1 from t1 where 19+coalesce((select a from t1 where d in (( -t1.a), - -b, -t1.f)),e)-a-c>=d))),f-13) then a else (t1.a) end+f*19-a,b,f)) and t1.a=b)}
} {-300}
do_test randexpr-2.2297 {
  db eval {SELECT coalesce((select max((coalesce((select coalesce((select max(case when case when e<case 17 when case when t1.e=f then a else t1.b end then 13 else d end then t1.b when 13<>t1.f then t1.b else c end<b or 13<17 then e* -17 else 11 end*e & e) from t1 where 19<>19),t1.f) from t1 where t1.e<>t1.d),t1.b))) from t1 where 11=t1.c), -c) FROM t1 WHERE NOT (not exists(select 1 from t1 where  -~e not in (c++case when 17+t1.c<coalesce((select max(t1.c) from t1 where (not exists(select 1 from t1 where 19+coalesce((select a from t1 where d in (( -t1.a), - -b, -t1.f)),e)-a-c>=d))),f-13) then a else (t1.a) end+f*19-a,b,f)) and t1.a=b)}
} {-300}
do_test randexpr-2.2298 {
  db eval {SELECT t1.b-11-case when t1.d+13+t1.c | 17+case when (+a*t1.b*t1.c not in (e,t1.f,t1.e)) then coalesce((select max(e) from t1 where t1.f>=f), -d) when f>b and t1.e<t1.a or t1.f>t1.c then 17 else  -13 end not in (f,t1.f,a) and exists(select 1 from t1 where a<=11) then t1.e else c end FROM t1 WHERE case f+~d*case when t1.f<=t1.b*t1.a then e*t1.e else f end*a+f when ~case when 11 not between +(abs(b)/abs(case b+d when t1.a then f else t1.e end*13))+a and (b) then t1.e when t1.e<>11 then t1.d else 17 end+11 then t1.d else t1.b end<=13}
} {}
do_test randexpr-2.2299 {
  db eval {SELECT t1.b-11-case when t1.d+13+t1.c | 17+case when (+a*t1.b*t1.c not in (e,t1.f,t1.e)) then coalesce((select max(e) from t1 where t1.f>=f), -d) when f>b and t1.e<t1.a or t1.f>t1.c then 17 else  -13 end not in (f,t1.f,a) and exists(select 1 from t1 where a<=11) then t1.e else c end FROM t1 WHERE NOT (case f+~d*case when t1.f<=t1.b*t1.a then e*t1.e else f end*a+f when ~case when 11 not between +(abs(b)/abs(case b+d when t1.a then f else t1.e end*13))+a and (b) then t1.e when t1.e<>11 then t1.d else 17 end+11 then t1.d else t1.b end<=13)}
} {-111}
do_test randexpr-2.2300 {
  db eval {SELECT t1.b-11-case when t1.d+13+t1.c & 17+case when (+a*t1.b*t1.c not in (e,t1.f,t1.e)) then coalesce((select max(e) from t1 where t1.f>=f), -d) when f>b and t1.e<t1.a or t1.f>t1.c then 17 else  -13 end not in (f,t1.f,a) and exists(select 1 from t1 where a<=11) then t1.e else c end FROM t1 WHERE NOT (case f+~d*case when t1.f<=t1.b*t1.a then e*t1.e else f end*a+f when ~case when 11 not between +(abs(b)/abs(case b+d when t1.a then f else t1.e end*13))+a and (b) then t1.e when t1.e<>11 then t1.d else 17 end+11 then t1.d else t1.b end<=13)}
} {-111}
do_test randexpr-2.2301 {
  db eval {SELECT coalesce((select t1.a from t1 where d not between 11 and 13 or case 13*17 when  -c then case when (coalesce((select 17 from t1 where (~case when t1.e=d then 19 when 11 in (t1.d,b,17) then t1.c else c end-11 in (select max(e) from t1 union select (case cast(avg((t1.b)) AS integer) when max(11) then min(17) else ( -count(*)) end) from t1))),(19))>d) then t1.d else 11 end else t1.c end<=a),c) FROM t1 WHERE 19 | (abs(t1.d)/abs(11))=b}
} {}
do_test randexpr-2.2302 {
  db eval {SELECT coalesce((select t1.a from t1 where d not between 11 and 13 or case 13*17 when  -c then case when (coalesce((select 17 from t1 where (~case when t1.e=d then 19 when 11 in (t1.d,b,17) then t1.c else c end-11 in (select max(e) from t1 union select (case cast(avg((t1.b)) AS integer) when max(11) then min(17) else ( -count(*)) end) from t1))),(19))>d) then t1.d else 11 end else t1.c end<=a),c) FROM t1 WHERE NOT (19 | (abs(t1.d)/abs(11))=b)}
} {100}
do_test randexpr-2.2303 {
  db eval {SELECT coalesce((select max(17-t1.e-17) from t1 where (t1.c>d)),case when coalesce((select +f+~coalesce((select coalesce((select case when (select cast(avg(17) AS integer) | cast(avg(t1.e) AS integer) from t1)<>coalesce((select t1.e from t1 where 19 in (select count(*) from t1 union select  -( -count(*)) from t1)), -d) then b when exists(select 1 from t1 where t1.b between (t1.b) and 13) then a else  -b end from t1 where 19=e),t1.c) from t1 where t1.c<=b),t1.d) from t1 where 17 between t1.a and b),t1.e) between c and t1.e then  -t1.d else 13 end) FROM t1 WHERE exists(select 1 from t1 where t1.e-13-17-f*f*t1.d*coalesce((select 19-case when not not t1.d>e then case when t1.f<t1.a then case when e<=t1.c then t1.e when (c)>=t1.c then 19 else f end else  -t1.b end when e in (f,t1.e,17) then t1.a else t1.b end*t1.d from t1 where ((f)) in (select (~case count(distinct 11) when count(distinct t1.d) | count(distinct t1.b)-max( -f) then max(e) else (count(distinct (((a))))) end) from t1 union select max(e) from t1)),f)+c>=t1.f)}
} {}
do_test randexpr-2.2304 {
  db eval {SELECT coalesce((select max(17-t1.e-17) from t1 where (t1.c>d)),case when coalesce((select +f+~coalesce((select coalesce((select case when (select cast(avg(17) AS integer) | cast(avg(t1.e) AS integer) from t1)<>coalesce((select t1.e from t1 where 19 in (select count(*) from t1 union select  -( -count(*)) from t1)), -d) then b when exists(select 1 from t1 where t1.b between (t1.b) and 13) then a else  -b end from t1 where 19=e),t1.c) from t1 where t1.c<=b),t1.d) from t1 where 17 between t1.a and b),t1.e) between c and t1.e then  -t1.d else 13 end) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e-13-17-f*f*t1.d*coalesce((select 19-case when not not t1.d>e then case when t1.f<t1.a then case when e<=t1.c then t1.e when (c)>=t1.c then 19 else f end else  -t1.b end when e in (f,t1.e,17) then t1.a else t1.b end*t1.d from t1 where ((f)) in (select (~case count(distinct 11) when count(distinct t1.d) | count(distinct t1.b)-max( -f) then max(e) else (count(distinct (((a))))) end) from t1 union select max(e) from t1)),f)+c>=t1.f))}
} {-400}
do_test randexpr-2.2305 {
  db eval {SELECT coalesce((select max(17-t1.e-17) from t1 where (t1.c>d)),case when coalesce((select +f+~coalesce((select coalesce((select case when (select cast(avg(17) AS integer) & cast(avg(t1.e) AS integer) from t1)<>coalesce((select t1.e from t1 where 19 in (select count(*) from t1 union select  -( -count(*)) from t1)), -d) then b when exists(select 1 from t1 where t1.b between (t1.b) and 13) then a else  -b end from t1 where 19=e),t1.c) from t1 where t1.c<=b),t1.d) from t1 where 17 between t1.a and b),t1.e) between c and t1.e then  -t1.d else 13 end) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e-13-17-f*f*t1.d*coalesce((select 19-case when not not t1.d>e then case when t1.f<t1.a then case when e<=t1.c then t1.e when (c)>=t1.c then 19 else f end else  -t1.b end when e in (f,t1.e,17) then t1.a else t1.b end*t1.d from t1 where ((f)) in (select (~case count(distinct 11) when count(distinct t1.d) | count(distinct t1.b)-max( -f) then max(e) else (count(distinct (((a))))) end) from t1 union select max(e) from t1)),f)+c>=t1.f))}
} {-400}
do_test randexpr-2.2306 {
  db eval {SELECT coalesce((select t1.b from t1 where exists(select 1 from t1 where (abs(~case (~13*case when c in (select (max(case when b<>11 then d when 13 not in (19,c,e) then t1.f else 19 end*t1.d)) from t1 union select abs(count(*)) | min(19) from t1) then t1.a else t1.c end-a-13-f*e*17) when f then t1.a else 13 end*t1.c)/abs(a))>t1.b)),13) FROM t1 WHERE ++case when a<=t1.a then 17 else 13 end>+f+(coalesce((select max(19) from t1 where 11 not in (case when t1.e<(abs(11)/abs(19*d*t1.c)) and (c in (select t1.c from t1 union select f from t1) or a>a) then t1.a when 11 not between t1.c and t1.a or t1.e not in ( -t1.a,17,f) then t1.d else e end+t1.f,19,(17))),17))* -11}
} {}
do_test randexpr-2.2307 {
  db eval {SELECT coalesce((select t1.b from t1 where exists(select 1 from t1 where (abs(~case (~13*case when c in (select (max(case when b<>11 then d when 13 not in (19,c,e) then t1.f else 19 end*t1.d)) from t1 union select abs(count(*)) | min(19) from t1) then t1.a else t1.c end-a-13-f*e*17) when f then t1.a else 13 end*t1.c)/abs(a))>t1.b)),13) FROM t1 WHERE NOT (++case when a<=t1.a then 17 else 13 end>+f+(coalesce((select max(19) from t1 where 11 not in (case when t1.e<(abs(11)/abs(19*d*t1.c)) and (c in (select t1.c from t1 union select f from t1) or a>a) then t1.a when 11 not between t1.c and t1.a or t1.e not in ( -t1.a,17,f) then t1.d else e end+t1.f,19,(17))),17))* -11)}
} {13}
do_test randexpr-2.2308 {
  db eval {SELECT coalesce((select t1.b from t1 where exists(select 1 from t1 where (abs(~case (~13*case when c in (select (max(case when b<>11 then d when 13 not in (19,c,e) then t1.f else 19 end*t1.d)) from t1 union select abs(count(*)) & min(19) from t1) then t1.a else t1.c end-a-13-f*e*17) when f then t1.a else 13 end*t1.c)/abs(a))>t1.b)),13) FROM t1 WHERE NOT (++case when a<=t1.a then 17 else 13 end>+f+(coalesce((select max(19) from t1 where 11 not in (case when t1.e<(abs(11)/abs(19*d*t1.c)) and (c in (select t1.c from t1 union select f from t1) or a>a) then t1.a when 11 not between t1.c and t1.a or t1.e not in ( -t1.a,17,f) then t1.d else e end+t1.f,19,(17))),17))* -11)}
} {13}
do_test randexpr-2.2309 {
  db eval {SELECT case when c*(abs(t1.f)/abs(c))*b-11-t1.a<coalesce((select max(case when coalesce((select max(c*+(t1.e)) from t1 where t1.c+ - -t1.f*t1.b in (select a from t1 union select d from t1)),t1.e)<>t1.d then  -d else t1.f end*e) from t1 where (b)<>t1.a or 11 between ( -a) and a),t1.b) then t1.d when e=t1.e then t1.c else t1.e end FROM t1 WHERE (coalesce((select (t1.b)+f*case case +coalesce((select 13 from t1 where t1.e<=d),f)-a when d then t1.b else t1.c end+t1.e when a then 17 else t1.e end from t1 where not t1.d in (select b from t1 union select 19 from t1) or not (17<t1.a) or t1.c in (select count(*) from t1 union select max(t1.c) from t1)),t1.e) in (b,t1.b,t1.f) or not exists(select 1 from t1 where not t1.d between 11 and  -t1.f))}
} {}
do_test randexpr-2.2310 {
  db eval {SELECT case when c*(abs(t1.f)/abs(c))*b-11-t1.a<coalesce((select max(case when coalesce((select max(c*+(t1.e)) from t1 where t1.c+ - -t1.f*t1.b in (select a from t1 union select d from t1)),t1.e)<>t1.d then  -d else t1.f end*e) from t1 where (b)<>t1.a or 11 between ( -a) and a),t1.b) then t1.d when e=t1.e then t1.c else t1.e end FROM t1 WHERE NOT ((coalesce((select (t1.b)+f*case case +coalesce((select 13 from t1 where t1.e<=d),f)-a when d then t1.b else t1.c end+t1.e when a then 17 else t1.e end from t1 where not t1.d in (select b from t1 union select 19 from t1) or not (17<t1.a) or t1.c in (select count(*) from t1 union select max(t1.c) from t1)),t1.e) in (b,t1.b,t1.f) or not exists(select 1 from t1 where not t1.d between 11 and  -t1.f)))}
} {300}
do_test randexpr-2.2311 {
  db eval {SELECT (17)+coalesce((select (case when (case (case t1.d when t1.d then 11 else 13 end) when e then e else 13 end*11)*t1.c not between a and 11 then (17) else c end)+t1.a from t1 where 17 in (select max(t1.d)*count(distinct 17) from t1 union select  -cast(avg(t1.d) AS integer)*case case +min(t1.c) when min(e) then cast(avg(b) AS integer) else max(t1.d) end when (max(c)) then cast(avg(t1.b) AS integer) else count(distinct 17) end from t1)),b)-a FROM t1 WHERE ((abs(t1.c)/abs(a)) between 11 | 11 and  -b)}
} {}
do_test randexpr-2.2312 {
  db eval {SELECT (17)+coalesce((select (case when (case (case t1.d when t1.d then 11 else 13 end) when e then e else 13 end*11)*t1.c not between a and 11 then (17) else c end)+t1.a from t1 where 17 in (select max(t1.d)*count(distinct 17) from t1 union select  -cast(avg(t1.d) AS integer)*case case +min(t1.c) when min(e) then cast(avg(b) AS integer) else max(t1.d) end when (max(c)) then cast(avg(t1.b) AS integer) else count(distinct 17) end from t1)),b)-a FROM t1 WHERE NOT (((abs(t1.c)/abs(a)) between 11 | 11 and  -b))}
} {117}
do_test randexpr-2.2313 {
  db eval {SELECT case when case when  -f-case when t1.a between 13 and (e) then t1.d | a else 13 end<t1.d and  -(13) in (select cast(avg(13) AS integer) from t1 union select +count(distinct c)-cast(avg(t1.c) AS integer) from t1) or not exists(select 1 from t1 where (not exists(select 1 from t1 where t1.e<>a) or ( -d) between c and c or (19) between t1.f and t1.b) or (b) not in (t1.d,t1.c,e)) then t1.b*t1.b when a>19 then t1.d else 11 end>=11 then t1.e else  -e end FROM t1 WHERE not exists(select 1 from t1 where ((11<=+11)))}
} {}
do_test randexpr-2.2314 {
  db eval {SELECT case when case when  -f-case when t1.a between 13 and (e) then t1.d | a else 13 end<t1.d and  -(13) in (select cast(avg(13) AS integer) from t1 union select +count(distinct c)-cast(avg(t1.c) AS integer) from t1) or not exists(select 1 from t1 where (not exists(select 1 from t1 where t1.e<>a) or ( -d) between c and c or (19) between t1.f and t1.b) or (b) not in (t1.d,t1.c,e)) then t1.b*t1.b when a>19 then t1.d else 11 end>=11 then t1.e else  -e end FROM t1 WHERE NOT (not exists(select 1 from t1 where ((11<=+11))))}
} {500}
do_test randexpr-2.2315 {
  db eval {SELECT case when case when  -f-case when t1.a between 13 and (e) then t1.d & a else 13 end<t1.d and  -(13) in (select cast(avg(13) AS integer) from t1 union select +count(distinct c)-cast(avg(t1.c) AS integer) from t1) or not exists(select 1 from t1 where (not exists(select 1 from t1 where t1.e<>a) or ( -d) between c and c or (19) between t1.f and t1.b) or (b) not in (t1.d,t1.c,e)) then t1.b*t1.b when a>19 then t1.d else 11 end>=11 then t1.e else  -e end FROM t1 WHERE NOT (not exists(select 1 from t1 where ((11<=+11))))}
} {500}
do_test randexpr-2.2316 {
  db eval {SELECT (abs(+case when 11*t1.d not between 13 and t1.d then coalesce((select 17 from t1 where case ~e when (abs(+(b+(select ~ -cast(avg(t1.c) AS integer) from t1)))/abs(case 17 when 17 then c else a end)) then t1.d else t1.d end<>t1.a),f) when not exists(select 1 from t1 where (19<=(f))) and 17=t1.b or 19 not between a and a then t1.d else d end)/abs(b)) FROM t1 WHERE t1.d-13 in (t1.a,d,(t1.b))}
} {}
do_test randexpr-2.2317 {
  db eval {SELECT (abs(+case when 11*t1.d not between 13 and t1.d then coalesce((select 17 from t1 where case ~e when (abs(+(b+(select ~ -cast(avg(t1.c) AS integer) from t1)))/abs(case 17 when 17 then c else a end)) then t1.d else t1.d end<>t1.a),f) when not exists(select 1 from t1 where (19<=(f))) and 17=t1.b or 19 not between a and a then t1.d else d end)/abs(b)) FROM t1 WHERE NOT (t1.d-13 in (t1.a,d,(t1.b)))}
} {0}
do_test randexpr-2.2318 {
  db eval {SELECT b+(select case ~min(t1.a+13) when (cast(avg(t1.a) AS integer)) then max(d) else max(case when case t1.b when t1.e then t1.c else t1.f end+19<>+(select count(*) from t1) then case when b in (t1.e,t1.d,t1.e) and t1.c not between t1.f and 13 then (t1.c) when 17>t1.b then 19 else t1.b end-t1.d when d in (e,f,t1.f) and (a)<t1.c then 13 else  -t1.e end) end from t1)* -11-t1.f FROM t1 WHERE t1.a between (abs(e)/abs(a)) and t1.f-case when not (19)<>+t1.e then e+case when (exists(select 1 from t1 where d<17) and d<(abs(t1.e)/abs(+ - -t1.f+d))) then coalesce((select max((t1.f)) from t1 where not 19=t1.e),t1.e)+t1.e else t1.d end when not exists(select 1 from t1 where t1.d not in (19,11,t1.c)) then (t1.f) else d end}
} {1800}
do_test randexpr-2.2319 {
  db eval {SELECT b+(select case ~min(t1.a+13) when (cast(avg(t1.a) AS integer)) then max(d) else max(case when case t1.b when t1.e then t1.c else t1.f end+19<>+(select count(*) from t1) then case when b in (t1.e,t1.d,t1.e) and t1.c not between t1.f and 13 then (t1.c) when 17>t1.b then 19 else t1.b end-t1.d when d in (e,f,t1.f) and (a)<t1.c then 13 else  -t1.e end) end from t1)* -11-t1.f FROM t1 WHERE NOT (t1.a between (abs(e)/abs(a)) and t1.f-case when not (19)<>+t1.e then e+case when (exists(select 1 from t1 where d<17) and d<(abs(t1.e)/abs(+ - -t1.f+d))) then coalesce((select max((t1.f)) from t1 where not 19=t1.e),t1.e)+t1.e else t1.d end when not exists(select 1 from t1 where t1.d not in (19,11,t1.c)) then (t1.f) else d end)}
} {}
do_test randexpr-2.2320 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where t1.b+b in (select (t1.c)*11*e+f+ -c-t1.b*coalesce((select max(a) from t1 where t1.a*17 between 19 and (((abs(f)/abs(t1.c+d))))),t1.c-(abs(t1.c)/abs(19)) | case when t1.d= -t1.f then b when (t1.c) not in (e, -11,19) then 19 else t1.a end-c)*t1.a-c from t1 union select t1.d from t1)),a) FROM t1 WHERE (select abs(+min(b)) from t1)<=d+t1.a}
} {400}
do_test randexpr-2.2321 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where t1.b+b in (select (t1.c)*11*e+f+ -c-t1.b*coalesce((select max(a) from t1 where t1.a*17 between 19 and (((abs(f)/abs(t1.c+d))))),t1.c-(abs(t1.c)/abs(19)) | case when t1.d= -t1.f then b when (t1.c) not in (e, -11,19) then 19 else t1.a end-c)*t1.a-c from t1 union select t1.d from t1)),a) FROM t1 WHERE NOT ((select abs(+min(b)) from t1)<=d+t1.a)}
} {}
do_test randexpr-2.2322 {
  db eval {SELECT coalesce((select max(t1.d) from t1 where t1.b+b in (select (t1.c)*11*e+f+ -c-t1.b*coalesce((select max(a) from t1 where t1.a*17 between 19 and (((abs(f)/abs(t1.c+d))))),t1.c-(abs(t1.c)/abs(19)) & case when t1.d= -t1.f then b when (t1.c) not in (e, -11,19) then 19 else t1.a end-c)*t1.a-c from t1 union select t1.d from t1)),a) FROM t1 WHERE (select abs(+min(b)) from t1)<=d+t1.a}
} {400}
do_test randexpr-2.2323 {
  db eval {SELECT case when coalesce((select c from t1 where (~13<>d)),t1.d-+d+13*coalesce((select max(17) from t1 where  -f<case when (abs(a+coalesce((select max(19) from t1 where not t1.d<>d),e))/abs(13))*f not in (t1.e,t1.c,e) then 19 when 17 not between t1.f and 17 then t1.f else t1.e end),f)+t1.c) | d<>11 then a else 19 end FROM t1 WHERE 13=b}
} {}
do_test randexpr-2.2324 {
  db eval {SELECT case when coalesce((select c from t1 where (~13<>d)),t1.d-+d+13*coalesce((select max(17) from t1 where  -f<case when (abs(a+coalesce((select max(19) from t1 where not t1.d<>d),e))/abs(13))*f not in (t1.e,t1.c,e) then 19 when 17 not between t1.f and 17 then t1.f else t1.e end),f)+t1.c) | d<>11 then a else 19 end FROM t1 WHERE NOT (13=b)}
} {100}
do_test randexpr-2.2325 {
  db eval {SELECT case when coalesce((select c from t1 where (~13<>d)),t1.d-+d+13*coalesce((select max(17) from t1 where  -f<case when (abs(a+coalesce((select max(19) from t1 where not t1.d<>d),e))/abs(13))*f not in (t1.e,t1.c,e) then 19 when 17 not between t1.f and 17 then t1.f else t1.e end),f)+t1.c) & d<>11 then a else 19 end FROM t1 WHERE NOT (13=b)}
} {100}
do_test randexpr-2.2326 {
  db eval {SELECT case case t1.e+13 when case when not  -f>coalesce((select max(t1.b) from t1 where (select min(a) from t1)<a),a) then case when not exists(select 1 from t1 where d>t1.d and t1.c<19 and d between b and ( -c)) then (select case ~max( -( - -t1.f)) when min(e) then  -count(*) else count(*) end-cast(avg(b) AS integer) from t1) when 17<>11 then f else case  -17 when t1.d then b else  -t1.f end end+t1.e when t1.d>=11 then 17 else 11 end then t1.d else t1.d end when t1.c then t1.a else 11 end FROM t1 WHERE (coalesce((select coalesce((select max(coalesce((select max( -(select + -case ++case (count(*)) when cast(avg(11) AS integer) then count(*) else  -min(13) end when max(19) then  -cast(avg(11) AS integer) else count(distinct (b)) end | max(t1.a)+max(b) from t1)) from t1 where 11 in (select b from t1 union select 13 from t1)),case (select count(*) from t1) when 19 then case when d not between  -d and b then t1.f else t1.b end else t1.c end)+d-t1.e) from t1 where t1.f not between t1.c and 19),t1.b) from t1 where t1.c between d and  -t1.b),t1.b))>=c}
} {}
do_test randexpr-2.2327 {
  db eval {SELECT case case t1.e+13 when case when not  -f>coalesce((select max(t1.b) from t1 where (select min(a) from t1)<a),a) then case when not exists(select 1 from t1 where d>t1.d and t1.c<19 and d between b and ( -c)) then (select case ~max( -( - -t1.f)) when min(e) then  -count(*) else count(*) end-cast(avg(b) AS integer) from t1) when 17<>11 then f else case  -17 when t1.d then b else  -t1.f end end+t1.e when t1.d>=11 then 17 else 11 end then t1.d else t1.d end when t1.c then t1.a else 11 end FROM t1 WHERE NOT ((coalesce((select coalesce((select max(coalesce((select max( -(select + -case ++case (count(*)) when cast(avg(11) AS integer) then count(*) else  -min(13) end when max(19) then  -cast(avg(11) AS integer) else count(distinct (b)) end | max(t1.a)+max(b) from t1)) from t1 where 11 in (select b from t1 union select 13 from t1)),case (select count(*) from t1) when 19 then case when d not between  -d and b then t1.f else t1.b end else t1.c end)+d-t1.e) from t1 where t1.f not between t1.c and 19),t1.b) from t1 where t1.c between d and  -t1.b),t1.b))>=c)}
} {11}
do_test randexpr-2.2328 {
  db eval {SELECT case when +case when coalesce((select t1.b from t1 where not exists(select 1 from t1 where f<=coalesce((select c from t1 where t1.a in (select ~f from t1 union select coalesce((select max(case  -(13) when 13 then t1.f else a end | 13) from t1 where c<= -c or b not between f and t1.d and t1.b not in (e,t1.a,17)),a)+d from t1)),13) or t1.a>c)),11*19) between e and 17 then c else  -(c) end>=t1.c then t1.d else c end FROM t1 WHERE t1.d<17-t1.a | a-+11}
} {}
do_test randexpr-2.2329 {
  db eval {SELECT case when +case when coalesce((select t1.b from t1 where not exists(select 1 from t1 where f<=coalesce((select c from t1 where t1.a in (select ~f from t1 union select coalesce((select max(case  -(13) when 13 then t1.f else a end | 13) from t1 where c<= -c or b not between f and t1.d and t1.b not in (e,t1.a,17)),a)+d from t1)),13) or t1.a>c)),11*19) between e and 17 then c else  -(c) end>=t1.c then t1.d else c end FROM t1 WHERE NOT (t1.d<17-t1.a | a-+11)}
} {300}
do_test randexpr-2.2330 {
  db eval {SELECT case when +case when coalesce((select t1.b from t1 where not exists(select 1 from t1 where f<=coalesce((select c from t1 where t1.a in (select ~f from t1 union select coalesce((select max(case  -(13) when 13 then t1.f else a end & 13) from t1 where c<= -c or b not between f and t1.d and t1.b not in (e,t1.a,17)),a)+d from t1)),13) or t1.a>c)),11*19) between e and 17 then c else  -(c) end>=t1.c then t1.d else c end FROM t1 WHERE NOT (t1.d<17-t1.a | a-+11)}
} {300}
do_test randexpr-2.2331 {
  db eval {SELECT t1.c+c- -d*t1.d+t1.e | case when t1.e<=e and (a*t1.c) in (select ((abs(f)/abs(( -+(select abs(~(min( -c))-max( - -b)-count(*)) from t1))))) from t1 union select b from t1) then +a*t1.c-t1.d*t1.c else e end-t1.d+t1.f FROM t1 WHERE (exists(select 1 from t1 where coalesce((select max(++11+coalesce((select max(17) from t1 where case case when exists(select 1 from t1 where c not between t1.e and 17) then 19 else f end when  -t1.f then t1.f else t1.a end<=t1.e or 11 in (b,a,e) and e between 11 and 11), -(a)-19)*t1.f) from t1 where t1.b between d and 17 and 17=e),19) not in (a,b,b))) and (e>=d) or b not in (c,13,19)}
} {161788}
do_test randexpr-2.2332 {
  db eval {SELECT t1.c+c- -d*t1.d+t1.e | case when t1.e<=e and (a*t1.c) in (select ((abs(f)/abs(( -+(select abs(~(min( -c))-max( - -b)-count(*)) from t1))))) from t1 union select b from t1) then +a*t1.c-t1.d*t1.c else e end-t1.d+t1.f FROM t1 WHERE NOT ((exists(select 1 from t1 where coalesce((select max(++11+coalesce((select max(17) from t1 where case case when exists(select 1 from t1 where c not between t1.e and 17) then 19 else f end when  -t1.f then t1.f else t1.a end<=t1.e or 11 in (b,a,e) and e between 11 and 11), -(a)-19)*t1.f) from t1 where t1.b between d and 17 and 17=e),19) not in (a,b,b))) and (e>=d) or b not in (c,13,19))}
} {}
do_test randexpr-2.2333 {
  db eval {SELECT t1.c+c- -d*t1.d+t1.e & case when t1.e<=e and (a*t1.c) in (select ((abs(f)/abs(( -+(select abs(~(min( -c))-max( - -b)-count(*)) from t1))))) from t1 union select b from t1) then +a*t1.c-t1.d*t1.c else e end-t1.d+t1.f FROM t1 WHERE (exists(select 1 from t1 where coalesce((select max(++11+coalesce((select max(17) from t1 where case case when exists(select 1 from t1 where c not between t1.e and 17) then 19 else f end when  -t1.f then t1.f else t1.a end<=t1.e or 11 in (b,a,e) and e between 11 and 11), -(a)-19)*t1.f) from t1 where t1.b between d and 17 and 17=e),19) not in (a,b,b))) and (e>=d) or b not in (c,13,19)}
} {12}
do_test randexpr-2.2334 {
  db eval {SELECT b-case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.a not between 17 and a+t1.f) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b+f+a in (select max(19) |  -max(t1.e)-cast(avg(t1.c) AS integer)- -count(distinct t1.b) from t1 union select max(t1.b) from t1)) or not exists(select 1 from t1 where not exists(select 1 from t1 where 11>c or (13) in ( -11,c,19)) or 11>f))) and t1.c not in ( -(d),t1.a,t1.a) and 17 in (t1.b,13,19)) then coalesce((select max(+19) from t1 where 17<b),13) else (abs(11)/abs(t1.e)) end FROM t1 WHERE not exists(select 1 from t1 where (13 between f and (e) or (f-d in (select t1.c*t1.d | f-19 from t1 union select 19*t1.d*coalesce((select coalesce((select max(t1.d-c*11) from t1 where 17= -t1.a),t1.a)-c from t1 where exists(select 1 from t1 where 17>e)),b) from t1))) or ((t1.d<f)))}
} {}
do_test randexpr-2.2335 {
  db eval {SELECT b-case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.a not between 17 and a+t1.f) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b+f+a in (select max(19) |  -max(t1.e)-cast(avg(t1.c) AS integer)- -count(distinct t1.b) from t1 union select max(t1.b) from t1)) or not exists(select 1 from t1 where not exists(select 1 from t1 where 11>c or (13) in ( -11,c,19)) or 11>f))) and t1.c not in ( -(d),t1.a,t1.a) and 17 in (t1.b,13,19)) then coalesce((select max(+19) from t1 where 17<b),13) else (abs(11)/abs(t1.e)) end FROM t1 WHERE NOT (not exists(select 1 from t1 where (13 between f and (e) or (f-d in (select t1.c*t1.d | f-19 from t1 union select 19*t1.d*coalesce((select coalesce((select max(t1.d-c*11) from t1 where 17= -t1.a),t1.a)-c from t1 where exists(select 1 from t1 where 17>e)),b) from t1))) or ((t1.d<f))))}
} {200}
do_test randexpr-2.2336 {
  db eval {SELECT b-case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.a not between 17 and a+t1.f) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b+f+a in (select max(19) &  -max(t1.e)-cast(avg(t1.c) AS integer)- -count(distinct t1.b) from t1 union select max(t1.b) from t1)) or not exists(select 1 from t1 where not exists(select 1 from t1 where 11>c or (13) in ( -11,c,19)) or 11>f))) and t1.c not in ( -(d),t1.a,t1.a) and 17 in (t1.b,13,19)) then coalesce((select max(+19) from t1 where 17<b),13) else (abs(11)/abs(t1.e)) end FROM t1 WHERE NOT (not exists(select 1 from t1 where (13 between f and (e) or (f-d in (select t1.c*t1.d | f-19 from t1 union select 19*t1.d*coalesce((select coalesce((select max(t1.d-c*11) from t1 where 17= -t1.a),t1.a)-c from t1 where exists(select 1 from t1 where 17>e)),b) from t1))) or ((t1.d<f))))}
} {200}
do_test randexpr-2.2337 {
  db eval {SELECT coalesce((select t1.f*t1.b+case t1.a when 17 then  -t1.c else coalesce((select b from t1 where 19 in (f,d+b,coalesce((select t1.e-b from t1 where t1.b*d+case t1.c when case coalesce((select t1.b from t1 where c not in (b,a,13)),(13)) when t1.b then 19 else 19 end then t1.d else 19 end+ -b>= -t1.f),t1.c))),b) end from t1 where not a=11),t1.c) FROM t1 WHERE not 13<>11+17-case when 17 between (abs(case f when 19 | t1.a then +(select cast(avg(case when not exists(select 1 from t1 where ~ -13*(select  -cast(avg(t1.b*d) AS integer) from t1)+17<>(t1.b)) then ~t1.c when b>t1.d then c else (f) end) AS integer) from t1) else a end)/abs(19)) and t1.f then t1.b when a<>t1.c then t1.e else b end}
} {}
do_test randexpr-2.2338 {
  db eval {SELECT coalesce((select t1.f*t1.b+case t1.a when 17 then  -t1.c else coalesce((select b from t1 where 19 in (f,d+b,coalesce((select t1.e-b from t1 where t1.b*d+case t1.c when case coalesce((select t1.b from t1 where c not in (b,a,13)),(13)) when t1.b then 19 else 19 end then t1.d else 19 end+ -b>= -t1.f),t1.c))),b) end from t1 where not a=11),t1.c) FROM t1 WHERE NOT (not 13<>11+17-case when 17 between (abs(case f when 19 | t1.a then +(select cast(avg(case when not exists(select 1 from t1 where ~ -13*(select  -cast(avg(t1.b*d) AS integer) from t1)+17<>(t1.b)) then ~t1.c when b>t1.d then c else (f) end) AS integer) from t1) else a end)/abs(19)) and t1.f then t1.b when a<>t1.c then t1.e else b end)}
} {120200}
do_test randexpr-2.2339 {
  db eval {SELECT coalesce((select max(19) from t1 where t1.f*17+case t1.f when 11 then coalesce((select max(t1.a) from t1 where 13<>t1.d),(abs(13+b-case when not c+(abs(case when t1.c not between a and t1.f then  -(e) else t1.d end)/abs( -17))<a then 11 else t1.c end)/abs(17)))*d*t1.a else c end-((f))-e*t1.a<17),t1.f)+t1.a FROM t1 WHERE e>=13}
} {119}
do_test randexpr-2.2340 {
  db eval {SELECT coalesce((select max(19) from t1 where t1.f*17+case t1.f when 11 then coalesce((select max(t1.a) from t1 where 13<>t1.d),(abs(13+b-case when not c+(abs(case when t1.c not between a and t1.f then  -(e) else t1.d end)/abs( -17))<a then 11 else t1.c end)/abs(17)))*d*t1.a else c end-((f))-e*t1.a<17),t1.f)+t1.a FROM t1 WHERE NOT (e>=13)}
} {}
do_test randexpr-2.2341 {
  db eval {SELECT +coalesce((select max(e) from t1 where  -(case 13*(t1.b* -case when e<=19 then b when t1.e=c then (b) else f end*t1.e) when e then 13 else t1.f end)=t1.b and t1.a in (select count(*) | case case min(b)*(count(*)) when abs(cast(avg(13) AS integer))-max(t1.d) then min(19) else  -cast(avg(b) AS integer) end when count(*) then (max(c)) else count(distinct 19) end+cast(avg((b)) AS integer) from t1 union select count(*) from t1)),t1.a) FROM t1 WHERE (select (min(13-(abs(c)/abs(case when coalesce((select case when coalesce((select  -a from t1 where case a*f when t1.a then  -c else (f) end between t1.a and t1.c),b) not between t1.e and b then 19 when 17 not in (19,d,11) then b else a end from t1 where b in (select t1.e from t1 union select t1.b from t1)),t1.a) not in (t1.e,t1.a,t1.f) then (d) else 19 end)))) from t1) in (select +13 from t1 union select 17 from t1)}
} {100}
do_test randexpr-2.2342 {
  db eval {SELECT +coalesce((select max(e) from t1 where  -(case 13*(t1.b* -case when e<=19 then b when t1.e=c then (b) else f end*t1.e) when e then 13 else t1.f end)=t1.b and t1.a in (select count(*) | case case min(b)*(count(*)) when abs(cast(avg(13) AS integer))-max(t1.d) then min(19) else  -cast(avg(b) AS integer) end when count(*) then (max(c)) else count(distinct 19) end+cast(avg((b)) AS integer) from t1 union select count(*) from t1)),t1.a) FROM t1 WHERE NOT ((select (min(13-(abs(c)/abs(case when coalesce((select case when coalesce((select  -a from t1 where case a*f when t1.a then  -c else (f) end between t1.a and t1.c),b) not between t1.e and b then 19 when 17 not in (19,d,11) then b else a end from t1 where b in (select t1.e from t1 union select t1.b from t1)),t1.a) not in (t1.e,t1.a,t1.f) then (d) else 19 end)))) from t1) in (select +13 from t1 union select 17 from t1))}
} {}
do_test randexpr-2.2343 {
  db eval {SELECT +coalesce((select max(e) from t1 where  -(case 13*(t1.b* -case when e<=19 then b when t1.e=c then (b) else f end*t1.e) when e then 13 else t1.f end)=t1.b and t1.a in (select count(*) & case case min(b)*(count(*)) when abs(cast(avg(13) AS integer))-max(t1.d) then min(19) else  -cast(avg(b) AS integer) end when count(*) then (max(c)) else count(distinct 19) end+cast(avg((b)) AS integer) from t1 union select count(*) from t1)),t1.a) FROM t1 WHERE (select (min(13-(abs(c)/abs(case when coalesce((select case when coalesce((select  -a from t1 where case a*f when t1.a then  -c else (f) end between t1.a and t1.c),b) not between t1.e and b then 19 when 17 not in (19,d,11) then b else a end from t1 where b in (select t1.e from t1 union select t1.b from t1)),t1.a) not in (t1.e,t1.a,t1.f) then (d) else 19 end)))) from t1) in (select +13 from t1 union select 17 from t1)}
} {100}
do_test randexpr-2.2344 {
  db eval {SELECT case when b in (select 19 from t1 union select c from t1) then  -d else 19-13+coalesce((select t1.c from t1 where t1.d>=case when e in (select f*t1.b from t1 union select t1.d from t1) then t1.c when not exists(select 1 from t1 where t1.f not in (17,t1.c,11) and b between b and 17 or c in (t1.b,17,a) or t1.d>t1.d and t1.c<>11 and 13=e and t1.f not in ( -t1.c,19,f)) then coalesce((select max(case when t1.c in (t1.e,d,b) then t1.f else t1.a end) from t1 where e<=t1.f),11) else t1.b end*11),t1.e) end FROM t1 WHERE 13 not between +19 and a}
} {506}
do_test randexpr-2.2345 {
  db eval {SELECT case when b in (select 19 from t1 union select c from t1) then  -d else 19-13+coalesce((select t1.c from t1 where t1.d>=case when e in (select f*t1.b from t1 union select t1.d from t1) then t1.c when not exists(select 1 from t1 where t1.f not in (17,t1.c,11) and b between b and 17 or c in (t1.b,17,a) or t1.d>t1.d and t1.c<>11 and 13=e and t1.f not in ( -t1.c,19,f)) then coalesce((select max(case when t1.c in (t1.e,d,b) then t1.f else t1.a end) from t1 where e<=t1.f),11) else t1.b end*11),t1.e) end FROM t1 WHERE NOT (13 not between +19 and a)}
} {}
do_test randexpr-2.2346 {
  db eval {SELECT (abs(13)/abs(case when t1.f not between a and f then 19-t1.d-t1.d*d | c+(select case count(*) | (~ -count(*)) when cast(avg( -19) AS integer) then min(d) else (cast(avg(e) AS integer)) end from t1) | t1.f-t1.b when f<>case when f<>b and 19 in (d,( -t1.a),t1.c) then 11 when e not between b and (t1.d) then t1.e else t1.d end-t1.e or t1.b not in (f,c,(a)) then  -d else t1.f end-t1.f)) FROM t1 WHERE (select  -count(*) from t1)=d+11}
} {}
do_test randexpr-2.2347 {
  db eval {SELECT (abs(13)/abs(case when t1.f not between a and f then 19-t1.d-t1.d*d | c+(select case count(*) | (~ -count(*)) when cast(avg( -19) AS integer) then min(d) else (cast(avg(e) AS integer)) end from t1) | t1.f-t1.b when f<>case when f<>b and 19 in (d,( -t1.a),t1.c) then 11 when e not between b and (t1.d) then t1.e else t1.d end-t1.e or t1.b not in (f,c,(a)) then  -d else t1.f end-t1.f)) FROM t1 WHERE NOT ((select  -count(*) from t1)=d+11)}
} {0}
do_test randexpr-2.2348 {
  db eval {SELECT (abs(13)/abs(case when t1.f not between a and f then 19-t1.d-t1.d*d & c+(select case count(*) & (~ -count(*)) when cast(avg( -19) AS integer) then min(d) else (cast(avg(e) AS integer)) end from t1) & t1.f-t1.b when f<>case when f<>b and 19 in (d,( -t1.a),t1.c) then 11 when e not between b and (t1.d) then t1.e else t1.d end-t1.e or t1.b not in (f,c,(a)) then  -d else t1.f end-t1.f)) FROM t1 WHERE NOT ((select  -count(*) from t1)=d+11)}
} {0}
do_test randexpr-2.2349 {
  db eval {SELECT ((select count(distinct 11+19 | case (d) when t1.b then coalesce((select case coalesce((select max(+c*t1.f) from t1 where (t1.e=f and 13<=t1.d)), -17)+11-t1.a when (t1.c) then 19 else 13 end from t1 where t1.c in (select ~+ -count(distinct t1.f) from t1 union select count(*)+count(distinct b)*min(11) from t1)),e) else 19 end+d) | count(*) from t1)) FROM t1 WHERE case b when 19 then ~b-~e-d+d+t1.c else a end in (select max(t1.b)-~count(*)+abs(abs((case min((abs(~t1.c*t1.f)/abs(t1.e))) when case max(b) when abs(count(distinct t1.b)) then +cast(avg((13)) AS integer) else +case min(b) when count(*) then count(*) else count(distinct t1.f) end end then max(19) else ( -count(*)) end)))*count(distinct f)*cast(avg(t1.c) AS integer) from t1 union select count(distinct a) from t1)}
} {}
do_test randexpr-2.2350 {
  db eval {SELECT ((select count(distinct 11+19 | case (d) when t1.b then coalesce((select case coalesce((select max(+c*t1.f) from t1 where (t1.e=f and 13<=t1.d)), -17)+11-t1.a when (t1.c) then 19 else 13 end from t1 where t1.c in (select ~+ -count(distinct t1.f) from t1 union select count(*)+count(distinct b)*min(11) from t1)),e) else 19 end+d) | count(*) from t1)) FROM t1 WHERE NOT (case b when 19 then ~b-~e-d+d+t1.c else a end in (select max(t1.b)-~count(*)+abs(abs((case min((abs(~t1.c*t1.f)/abs(t1.e))) when case max(b) when abs(count(distinct t1.b)) then +cast(avg((13)) AS integer) else +case min(b) when count(*) then count(*) else count(distinct t1.f) end end then max(19) else ( -count(*)) end)))*count(distinct f)*cast(avg(t1.c) AS integer) from t1 union select count(distinct a) from t1))}
} {1}
do_test randexpr-2.2351 {
  db eval {SELECT ((select count(distinct 11+19 & case (d) when t1.b then coalesce((select case coalesce((select max(+c*t1.f) from t1 where (t1.e=f and 13<=t1.d)), -17)+11-t1.a when (t1.c) then 19 else 13 end from t1 where t1.c in (select ~+ -count(distinct t1.f) from t1 union select count(*)+count(distinct b)*min(11) from t1)),e) else 19 end+d) & count(*) from t1)) FROM t1 WHERE NOT (case b when 19 then ~b-~e-d+d+t1.c else a end in (select max(t1.b)-~count(*)+abs(abs((case min((abs(~t1.c*t1.f)/abs(t1.e))) when case max(b) when abs(count(distinct t1.b)) then +cast(avg((13)) AS integer) else +case min(b) when count(*) then count(*) else count(distinct t1.f) end end then max(19) else ( -count(*)) end)))*count(distinct f)*cast(avg(t1.c) AS integer) from t1 union select count(distinct a) from t1))}
} {1}
do_test randexpr-2.2352 {
  db eval {SELECT 17+ -(abs(case case when a>t1.c then t1.e else a end*11-case when not exists(select 1 from t1 where coalesce((select  -t1.e-11+coalesce((select t1.e from t1 where 13=t1.e),d) from t1 where t1.e between t1.d and a),13)-t1.e in (select t1.d from t1 union select d from t1)) then t1.b else t1.d end-t1.e-13+b when 19 then t1.b else c end)/abs(t1.d)) FROM t1 WHERE coalesce((select max(t1.d) from t1 where t1.a+t1.d<19),t1.a) in (select t1.b from t1 union select c from t1) or t1.c in (select  -abs(max(case when  -f<>t1.b and b<>11 then t1.f when t1.a=e then t1.d else  -(f) end) | case cast(avg(f) AS integer) when count(distinct t1.f) then min(e) else  -count(*) end+cast(avg((t1.f)) AS integer)) from t1 union select max(17) from t1) or t1.c between ((c)) and  -t1.b and  -c not between d and 11 or b>=19}
} {17}
do_test randexpr-2.2353 {
  db eval {SELECT 17+ -(abs(case case when a>t1.c then t1.e else a end*11-case when not exists(select 1 from t1 where coalesce((select  -t1.e-11+coalesce((select t1.e from t1 where 13=t1.e),d) from t1 where t1.e between t1.d and a),13)-t1.e in (select t1.d from t1 union select d from t1)) then t1.b else t1.d end-t1.e-13+b when 19 then t1.b else c end)/abs(t1.d)) FROM t1 WHERE NOT (coalesce((select max(t1.d) from t1 where t1.a+t1.d<19),t1.a) in (select t1.b from t1 union select c from t1) or t1.c in (select  -abs(max(case when  -f<>t1.b and b<>11 then t1.f when t1.a=e then t1.d else  -(f) end) | case cast(avg(f) AS integer) when count(distinct t1.f) then min(e) else  -count(*) end+cast(avg((t1.f)) AS integer)) from t1 union select max(17) from t1) or t1.c between ((c)) and  -t1.b and  -c not between d and 11 or b>=19)}
} {}
do_test randexpr-2.2354 {
  db eval {SELECT e*~+(e)-(abs(~case when (t1.f)>13+~t1.d then case when d=t1.b+13 then 17 when 11 in (t1.d,e,e) then ~19*t1.a else coalesce((select t1.c from t1 where 19*(abs(t1.e)/abs(b)) between t1.c and t1.c),t1.d) end when a not between 13 and  -17 then 19 else b end)/abs(t1.b)) FROM t1 WHERE (not d>case t1.b+t1.f when +(~(select (case abs(cast(avg(13) AS integer)) when cast(avg(+a) AS integer) then abs(abs(count(distinct case when t1.f*e<=11 then 13 when exists(select 1 from t1 where t1.e<17 or t1.a>=t1.a) then (11) else f end))) else min(t1.b)-min(11) end) from t1))+17*t1.b*f*17 then e else 11 end)}
} {}
do_test randexpr-2.2355 {
  db eval {SELECT e*~+(e)-(abs(~case when (t1.f)>13+~t1.d then case when d=t1.b+13 then 17 when 11 in (t1.d,e,e) then ~19*t1.a else coalesce((select t1.c from t1 where 19*(abs(t1.e)/abs(b)) between t1.c and t1.c),t1.d) end when a not between 13 and  -17 then 19 else b end)/abs(t1.b)) FROM t1 WHERE NOT ((not d>case t1.b+t1.f when +(~(select (case abs(cast(avg(13) AS integer)) when cast(avg(+a) AS integer) then abs(abs(count(distinct case when t1.f*e<=11 then 13 when exists(select 1 from t1 where t1.e<17 or t1.a>=t1.a) then (11) else f end))) else min(t1.b)-min(11) end) from t1))+17*t1.b*f*17 then e else 11 end))}
} {-250502}
do_test randexpr-2.2356 {
  db eval {SELECT  -case when t1.c<= -case coalesce((select max((coalesce((select case 11 when t1.b then t1.f else 11 end-d from t1 where c in (select count(*) | ~count(distinct f) from t1 union select count(*) from t1)),a)*t1.a)-t1.f) from t1 where not exists(select 1 from t1 where ((t1.f not in ( -c,t1.d,b)) or t1.a not in (b,11,t1.c)) or t1.d not in (17,a,t1.a))),19)-t1.b when d then t1.e else t1.e end-19 | e then b else  -13 end*e-c FROM t1 WHERE b<>coalesce((select max((abs((abs(11)/abs(13)))/abs(case when t1.e between 11 and 19 then t1.d when 11>=b-19 then (select count(distinct ~a | 19*f+case when f not in (t1.e,t1.f, -t1.f) then 17 when c not in ( -t1.a,t1.c,b) then f else 11 end) from t1) else t1.e end))-t1.e*a) from t1 where e in (t1.c,17,17)),t1.a) or a=t1.e or d>t1.b}
} {6200}
do_test randexpr-2.2357 {
  db eval {SELECT  -case when t1.c<= -case coalesce((select max((coalesce((select case 11 when t1.b then t1.f else 11 end-d from t1 where c in (select count(*) | ~count(distinct f) from t1 union select count(*) from t1)),a)*t1.a)-t1.f) from t1 where not exists(select 1 from t1 where ((t1.f not in ( -c,t1.d,b)) or t1.a not in (b,11,t1.c)) or t1.d not in (17,a,t1.a))),19)-t1.b when d then t1.e else t1.e end-19 | e then b else  -13 end*e-c FROM t1 WHERE NOT (b<>coalesce((select max((abs((abs(11)/abs(13)))/abs(case when t1.e between 11 and 19 then t1.d when 11>=b-19 then (select count(distinct ~a | 19*f+case when f not in (t1.e,t1.f, -t1.f) then 17 when c not in ( -t1.a,t1.c,b) then f else 11 end) from t1) else t1.e end))-t1.e*a) from t1 where e in (t1.c,17,17)),t1.a) or a=t1.e or d>t1.b)}
} {}
do_test randexpr-2.2358 {
  db eval {SELECT  -case when t1.c<= -case coalesce((select max((coalesce((select case 11 when t1.b then t1.f else 11 end-d from t1 where c in (select count(*) & ~count(distinct f) from t1 union select count(*) from t1)),a)*t1.a)-t1.f) from t1 where not exists(select 1 from t1 where ((t1.f not in ( -c,t1.d,b)) or t1.a not in (b,11,t1.c)) or t1.d not in (17,a,t1.a))),19)-t1.b when d then t1.e else t1.e end-19 & e then b else  -13 end*e-c FROM t1 WHERE b<>coalesce((select max((abs((abs(11)/abs(13)))/abs(case when t1.e between 11 and 19 then t1.d when 11>=b-19 then (select count(distinct ~a | 19*f+case when f not in (t1.e,t1.f, -t1.f) then 17 when c not in ( -t1.a,t1.c,b) then f else 11 end) from t1) else t1.e end))-t1.e*a) from t1 where e in (t1.c,17,17)),t1.a) or a=t1.e or d>t1.b}
} {-100300}
do_test randexpr-2.2359 {
  db eval {SELECT (abs(case when t1.d not in (t1.f,t1.d,(select abs(min(((select +count(*)*case max(t1.e-coalesce((select max(case t1.b when 13 then a else e end) from t1 where t1.b>b),19)+d)- -+count(*) when +cast(avg(d) AS integer) then max(c) else (cast(avg(c) AS integer)) end | count(*) from t1)+t1.f)))-max(t1.c) from t1)) then t1.b*t1.f else f end)/abs(b+19)) FROM t1 WHERE a not in ((11),(t1.d),a) or case when f<t1.e | 11+t1.b+17-coalesce((select t1.f+case when ((not (t1.d)>(abs(d)/abs(t1.d)))) then a when f not between t1.f | t1.b and t1.d then a else 13 end from t1 where 19<=c),f) then t1.a else f end between 13 and 11}
} {}
do_test randexpr-2.2360 {
  db eval {SELECT (abs(case when t1.d not in (t1.f,t1.d,(select abs(min(((select +count(*)*case max(t1.e-coalesce((select max(case t1.b when 13 then a else e end) from t1 where t1.b>b),19)+d)- -+count(*) when +cast(avg(d) AS integer) then max(c) else (cast(avg(c) AS integer)) end | count(*) from t1)+t1.f)))-max(t1.c) from t1)) then t1.b*t1.f else f end)/abs(b+19)) FROM t1 WHERE NOT (a not in ((11),(t1.d),a) or case when f<t1.e | 11+t1.b+17-coalesce((select t1.f+case when ((not (t1.d)>(abs(d)/abs(t1.d)))) then a when f not between t1.f | t1.b and t1.d then a else 13 end from t1 where 19<=c),f) then t1.a else f end between 13 and 11)}
} {2}
do_test randexpr-2.2361 {
  db eval {SELECT (abs(case when t1.d not in (t1.f,t1.d,(select abs(min(((select +count(*)*case max(t1.e-coalesce((select max(case t1.b when 13 then a else e end) from t1 where t1.b>b),19)+d)- -+count(*) when +cast(avg(d) AS integer) then max(c) else (cast(avg(c) AS integer)) end & count(*) from t1)+t1.f)))-max(t1.c) from t1)) then t1.b*t1.f else f end)/abs(b+19)) FROM t1 WHERE NOT (a not in ((11),(t1.d),a) or case when f<t1.e | 11+t1.b+17-coalesce((select t1.f+case when ((not (t1.d)>(abs(d)/abs(t1.d)))) then a when f not between t1.f | t1.b and t1.d then a else 13 end from t1 where 19<=c),f) then t1.a else f end between 13 and 11)}
} {2}
do_test randexpr-2.2362 {
  db eval {SELECT t1.a+d | +case when +t1.a-t1.f++t1.c+(select case ~count(*) when (+cast(avg(f*t1.f) AS integer) | min(t1.b)) then  -(cast(avg(t1.f) AS integer)) else min(e) end from t1)-b* - -13-f+c in (select b from t1 union select t1.d from t1) or e<e then b | 13 else t1.c end FROM t1 WHERE coalesce((select max(coalesce((select  -e*a from t1 where (select max(case t1.a when b then d else 17 end) from t1) in (select 17 from t1 union select  -case when exists(select 1 from t1 where coalesce((select t1.d from t1 where t1.a not between t1.d and 17 and 19=17),t1.c)-t1.e+b<=a) then 17 | c when  -e<=d then 13 else (b) end from t1)),e)) from t1 where t1.e not in (11, -t1.b,(f))),t1.c) not in ( -c,t1.d,t1.d) and b<=13}
} {}
do_test randexpr-2.2363 {
  db eval {SELECT t1.a+d | +case when +t1.a-t1.f++t1.c+(select case ~count(*) when (+cast(avg(f*t1.f) AS integer) | min(t1.b)) then  -(cast(avg(t1.f) AS integer)) else min(e) end from t1)-b* - -13-f+c in (select b from t1 union select t1.d from t1) or e<e then b | 13 else t1.c end FROM t1 WHERE NOT (coalesce((select max(coalesce((select  -e*a from t1 where (select max(case t1.a when b then d else 17 end) from t1) in (select 17 from t1 union select  -case when exists(select 1 from t1 where coalesce((select t1.d from t1 where t1.a not between t1.d and 17 and 19=17),t1.c)-t1.e+b<=a) then 17 | c when  -e<=d then 13 else (b) end from t1)),e)) from t1 where t1.e not in (11, -t1.b,(f))),t1.c) not in ( -c,t1.d,t1.d) and b<=13)}
} {508}
do_test randexpr-2.2364 {
  db eval {SELECT t1.a+d & +case when +t1.a-t1.f++t1.c+(select case ~count(*) when (+cast(avg(f*t1.f) AS integer) & min(t1.b)) then  -(cast(avg(t1.f) AS integer)) else min(e) end from t1)-b* - -13-f+c in (select b from t1 union select t1.d from t1) or e<e then b & 13 else t1.c end FROM t1 WHERE NOT (coalesce((select max(coalesce((select  -e*a from t1 where (select max(case t1.a when b then d else 17 end) from t1) in (select 17 from t1 union select  -case when exists(select 1 from t1 where coalesce((select t1.d from t1 where t1.a not between t1.d and 17 and 19=17),t1.c)-t1.e+b<=a) then 17 | c when  -e<=d then 13 else (b) end from t1)),e)) from t1 where t1.e not in (11, -t1.b,(f))),t1.c) not in ( -c,t1.d,t1.d) and b<=13)}
} {292}
do_test randexpr-2.2365 {
  db eval {SELECT coalesce((select max((select (max((abs(coalesce((select max(+case when ~t1.d=t1.a then a when coalesce((select case when t1.c in (select 19 from t1 union select (d) from t1) then e else f end from t1 where t1.a<>t1.a),t1.f) between t1.a and 19 then ( -b) else t1.a end) from t1 where t1.c in (a,(f),e)),t1.c))/abs(a)))) from t1)) from t1 where case when exists(select 1 from t1 where e<11) and 17 in (select 11 from t1 union select a from t1) then d else (d) end in (select cast(avg(f) AS integer) from t1 union select count(*) from t1)),t1.d) FROM t1 WHERE exists(select 1 from t1 where b not between case 11 when d then (select + -(abs(abs(case  -min(d)+ - -count(*)-max(c) when count(*) then max(t1.b) else count(*) end))) from t1)+t1.f-f*t1.b*((select min(a) from t1))-b+f else t1.e end | t1.c+13 and 19) and b<t1.c or (17>t1.e)}
} {400}
do_test randexpr-2.2366 {
  db eval {SELECT coalesce((select max((select (max((abs(coalesce((select max(+case when ~t1.d=t1.a then a when coalesce((select case when t1.c in (select 19 from t1 union select (d) from t1) then e else f end from t1 where t1.a<>t1.a),t1.f) between t1.a and 19 then ( -b) else t1.a end) from t1 where t1.c in (a,(f),e)),t1.c))/abs(a)))) from t1)) from t1 where case when exists(select 1 from t1 where e<11) and 17 in (select 11 from t1 union select a from t1) then d else (d) end in (select cast(avg(f) AS integer) from t1 union select count(*) from t1)),t1.d) FROM t1 WHERE NOT (exists(select 1 from t1 where b not between case 11 when d then (select + -(abs(abs(case  -min(d)+ - -count(*)-max(c) when count(*) then max(t1.b) else count(*) end))) from t1)+t1.f-f*t1.b*((select min(a) from t1))-b+f else t1.e end | t1.c+13 and 19) and b<t1.c or (17>t1.e))}
} {}
do_test randexpr-2.2367 {
  db eval {SELECT case when t1.d+b+c | case +a-t1.d-f*(select cast(avg(17) AS integer)+count(distinct e)-count(distinct t1.a) |  - -cast(avg(t1.b) AS integer) from t1)+~t1.e-a when d then t1.f else d end+t1.e*b<>11 then f when t1.a=b or t1.b>(t1.d) then 19 else t1.f end+19 FROM t1 WHERE coalesce((select case t1.e-case coalesce((select (select min(t1.d) from t1) from t1 where coalesce((select max(coalesce((select max(a) from t1 where t1.d in (select cast(avg(t1.b) AS integer) from t1 union select count(distinct a) from t1)), -19)*t1.e) from t1 where d>11),t1.f)>17),t1.f) when (17) then e else d end when b then (19) else 19 end from t1 where not t1.f in (select ( -max(13)) from t1 union select max(c) from t1)),11)-d not in ( -19,13,d)}
} {619}
do_test randexpr-2.2368 {
  db eval {SELECT case when t1.d+b+c | case +a-t1.d-f*(select cast(avg(17) AS integer)+count(distinct e)-count(distinct t1.a) |  - -cast(avg(t1.b) AS integer) from t1)+~t1.e-a when d then t1.f else d end+t1.e*b<>11 then f when t1.a=b or t1.b>(t1.d) then 19 else t1.f end+19 FROM t1 WHERE NOT (coalesce((select case t1.e-case coalesce((select (select min(t1.d) from t1) from t1 where coalesce((select max(coalesce((select max(a) from t1 where t1.d in (select cast(avg(t1.b) AS integer) from t1 union select count(distinct a) from t1)), -19)*t1.e) from t1 where d>11),t1.f)>17),t1.f) when (17) then e else d end when b then (19) else 19 end from t1 where not t1.f in (select ( -max(13)) from t1 union select max(c) from t1)),11)-d not in ( -19,13,d))}
} {}
do_test randexpr-2.2369 {
  db eval {SELECT case when t1.d+b+c & case +a-t1.d-f*(select cast(avg(17) AS integer)+count(distinct e)-count(distinct t1.a) &  - -cast(avg(t1.b) AS integer) from t1)+~t1.e-a when d then t1.f else d end+t1.e*b<>11 then f when t1.a=b or t1.b>(t1.d) then 19 else t1.f end+19 FROM t1 WHERE coalesce((select case t1.e-case coalesce((select (select min(t1.d) from t1) from t1 where coalesce((select max(coalesce((select max(a) from t1 where t1.d in (select cast(avg(t1.b) AS integer) from t1 union select count(distinct a) from t1)), -19)*t1.e) from t1 where d>11),t1.f)>17),t1.f) when (17) then e else d end when b then (19) else 19 end from t1 where not t1.f in (select ( -max(13)) from t1 union select max(c) from t1)),11)-d not in ( -19,13,d)}
} {619}
do_test randexpr-2.2370 {
  db eval {SELECT case when (t1.a not in (coalesce((select 17 from t1 where case when t1.b*(abs( -t1.b*f*coalesce((select 17 from t1 where not t1.d<t1.d),t1.b)*t1.a+19* -17)/abs(b))<=b then t1.b else 13 end+t1.d not between t1.b and  - -11),d),11,t1.e) or a<=19) or t1.e not between t1.c and 13 then 13 else e end FROM t1 WHERE t1.f+(abs(f)/abs((abs(t1.e+19)/abs(t1.c))*t1.d)) in (e*11,(select count(*) from t1),t1.e)}
} {}
do_test randexpr-2.2371 {
  db eval {SELECT case when (t1.a not in (coalesce((select 17 from t1 where case when t1.b*(abs( -t1.b*f*coalesce((select 17 from t1 where not t1.d<t1.d),t1.b)*t1.a+19* -17)/abs(b))<=b then t1.b else 13 end+t1.d not between t1.b and  - -11),d),11,t1.e) or a<=19) or t1.e not between t1.c and 13 then 13 else e end FROM t1 WHERE NOT (t1.f+(abs(f)/abs((abs(t1.e+19)/abs(t1.c))*t1.d)) in (e*11,(select count(*) from t1),t1.e))}
} {13}
do_test randexpr-2.2372 {
  db eval {SELECT case when case when (case (t1.a)*case when c<f and t1.e<>t1.d then 13 when c>b then c else 11 end when e then a else t1.e end>c) or 19 in (select ++min(f) from t1 union select  -count(distinct t1.a) from t1) then (case when t1.f in (select t1.f from t1 union select  -t1.a from t1) then c when b not between t1.a and b then  -t1.c else t1.a end) else t1.c end not in (f,a,17) then 11 else 11 end FROM t1 WHERE not c not between (select abs(max(~(19*e-t1.a*c*t1.d))*~abs((abs(min(a)-min(c) | cast(avg(19) AS integer))) | count(distinct 19)) | (cast(avg(d) AS integer))) from t1) and (abs(case coalesce((select max(19) from t1 where b not between a and f or 19 in (t1.c,t1.c,b)),t1.e) when c then f else 11 end)/abs(c))}
} {}
do_test randexpr-2.2373 {
  db eval {SELECT case when case when (case (t1.a)*case when c<f and t1.e<>t1.d then 13 when c>b then c else 11 end when e then a else t1.e end>c) or 19 in (select ++min(f) from t1 union select  -count(distinct t1.a) from t1) then (case when t1.f in (select t1.f from t1 union select  -t1.a from t1) then c when b not between t1.a and b then  -t1.c else t1.a end) else t1.c end not in (f,a,17) then 11 else 11 end FROM t1 WHERE NOT (not c not between (select abs(max(~(19*e-t1.a*c*t1.d))*~abs((abs(min(a)-min(c) | cast(avg(19) AS integer))) | count(distinct 19)) | (cast(avg(d) AS integer))) from t1) and (abs(case coalesce((select max(19) from t1 where b not between a and f or 19 in (t1.c,t1.c,b)),t1.e) when c then f else 11 end)/abs(c)))}
} {11}
do_test randexpr-2.2374 {
  db eval {SELECT (select count(*)-+ -(max(~coalesce((select ~b from t1 where not t1.c | 19 not between c+t1.c and d),a)*(abs(t1.a)/abs(d*(case t1.a*case when 17>e then 11 else 13 end when 19 then e else t1.d end)))+17))-cast(avg(c) AS integer) | count(distinct f) from t1)+(select abs(min(11)) from t1) FROM t1 WHERE coalesce((select max(11) from t1 where case when b<=13-~case when ~~(select count(*)+count(*)* -count(*) from t1)>17*17 then t1.f+case when not case when 19 in (t1.e,a,19) then 17 when f<=19 then 17 else  -d end=19 then f when a>=19 then d else f end else t1.c end | f then 19 else b end*t1.d between e and b),f)<c}
} {}
do_test randexpr-2.2375 {
  db eval {SELECT (select count(*)-+ -(max(~coalesce((select ~b from t1 where not t1.c | 19 not between c+t1.c and d),a)*(abs(t1.a)/abs(d*(case t1.a*case when 17>e then 11 else 13 end when 19 then e else t1.d end)))+17))-cast(avg(c) AS integer) | count(distinct f) from t1)+(select abs(min(11)) from t1) FROM t1 WHERE NOT (coalesce((select max(11) from t1 where case when b<=13-~case when ~~(select count(*)+count(*)* -count(*) from t1)>17*17 then t1.f+case when not case when 19 in (t1.e,a,19) then 17 when f<=19 then 17 else  -d end=19 then f when a>=19 then d else f end else t1.c end | f then 19 else b end*t1.d between e and b),f)<c)}
} {-270}
do_test randexpr-2.2376 {
  db eval {SELECT (select count(*)-+ -(max(~coalesce((select ~b from t1 where not t1.c & 19 not between c+t1.c and d),a)*(abs(t1.a)/abs(d*(case t1.a*case when 17>e then 11 else 13 end when 19 then e else t1.d end)))+17))-cast(avg(c) AS integer) & count(distinct f) from t1)+(select abs(min(11)) from t1) FROM t1 WHERE NOT (coalesce((select max(11) from t1 where case when b<=13-~case when ~~(select count(*)+count(*)* -count(*) from t1)>17*17 then t1.f+case when not case when 19 in (t1.e,a,19) then 17 when f<=19 then 17 else  -d end=19 then f when a>=19 then d else f end else t1.c end | f then 19 else b end*t1.d between e and b),f)<c)}
} {11}
do_test randexpr-2.2377 {
  db eval {SELECT case when ((select max((t1.e+19 | (abs((select case ++cast(avg(b-coalesce((select t1.c from t1 where t1.e not in (t1.a, -e,e)),c)) AS integer) when count(distinct t1.b) then count(distinct  -t1.a) |  - -count(distinct t1.b) else count(*) end*( -(min(11)))+(min(t1.f))-(count(*)) from t1))/abs(b+t1.b+t1.d | t1.e-19+t1.a))*t1.c)) from t1))>19 then 11 else 17 end-t1.d FROM t1 WHERE (select min(a) from t1)<t1.e}
} {-389}
do_test randexpr-2.2378 {
  db eval {SELECT case when ((select max((t1.e+19 | (abs((select case ++cast(avg(b-coalesce((select t1.c from t1 where t1.e not in (t1.a, -e,e)),c)) AS integer) when count(distinct t1.b) then count(distinct  -t1.a) |  - -count(distinct t1.b) else count(*) end*( -(min(11)))+(min(t1.f))-(count(*)) from t1))/abs(b+t1.b+t1.d | t1.e-19+t1.a))*t1.c)) from t1))>19 then 11 else 17 end-t1.d FROM t1 WHERE NOT ((select min(a) from t1)<t1.e)}
} {}
do_test randexpr-2.2379 {
  db eval {SELECT case when ((select max((t1.e+19 & (abs((select case ++cast(avg(b-coalesce((select t1.c from t1 where t1.e not in (t1.a, -e,e)),c)) AS integer) when count(distinct t1.b) then count(distinct  -t1.a) &  - -count(distinct t1.b) else count(*) end*( -(min(11)))+(min(t1.f))-(count(*)) from t1))/abs(b+t1.b+t1.d & t1.e-19+t1.a))*t1.c)) from t1))>19 then 11 else 17 end-t1.d FROM t1 WHERE (select min(a) from t1)<t1.e}
} {-383}
do_test randexpr-2.2380 {
  db eval {SELECT t1.d*11-case 11 when a then 11 else  - -t1.b-(t1.b)+c+t1.a* -case when not exists(select 1 from t1 where coalesce((select t1.c from t1 where t1.c=case when 13 in (coalesce((select max(coalesce((select max(t1.c) from t1 where c between t1.d and t1.f and t1.a<=b),e)) from t1 where (11 not in (b,19,c))),b),e, -b) then 17 when t1.a in (b,t1.d,b) and t1.f>c then t1.a else (d) end),d)<= -t1.c) then t1.e*t1.c else 13 end end FROM t1 WHERE exists(select 1 from t1 where ((b not between f and t1.a)))}
} {15004100}
do_test randexpr-2.2381 {
  db eval {SELECT t1.d*11-case 11 when a then 11 else  - -t1.b-(t1.b)+c+t1.a* -case when not exists(select 1 from t1 where coalesce((select t1.c from t1 where t1.c=case when 13 in (coalesce((select max(coalesce((select max(t1.c) from t1 where c between t1.d and t1.f and t1.a<=b),e)) from t1 where (11 not in (b,19,c))),b),e, -b) then 17 when t1.a in (b,t1.d,b) and t1.f>c then t1.a else (d) end),d)<= -t1.c) then t1.e*t1.c else 13 end end FROM t1 WHERE NOT (exists(select 1 from t1 where ((b not between f and t1.a))))}
} {}
do_test randexpr-2.2382 {
  db eval {SELECT t1.c*case when not b>(+coalesce((select t1.e from t1 where t1.b>(abs(case when t1.d<=c+ -17*t1.f*19*17 then 11+a-13-t1.d else case (select abs(count(distinct 19))+ -count(distinct 17) from t1) when 17*t1.d then a else t1.a end end)/abs(17))),(11)))+17 then (t1.c)*f else 17 end FROM t1 WHERE (t1.b)-b<=t1.a*13}
} {54000000}
do_test randexpr-2.2383 {
  db eval {SELECT t1.c*case when not b>(+coalesce((select t1.e from t1 where t1.b>(abs(case when t1.d<=c+ -17*t1.f*19*17 then 11+a-13-t1.d else case (select abs(count(distinct 19))+ -count(distinct 17) from t1) when 17*t1.d then a else t1.a end end)/abs(17))),(11)))+17 then (t1.c)*f else 17 end FROM t1 WHERE NOT ((t1.b)-b<=t1.a*13)}
} {}
do_test randexpr-2.2384 {
  db eval {SELECT t1.b+coalesce((select max(~e- -t1.d+case +b+f when a-case when t1.a-d+t1.c between t1.e and a*e then (abs(e)/abs(t1.a)) else f |  -f*t1.b-t1.c end*t1.e+f then 19 else t1.b end*19) from t1 where 19 in (select e from t1 union select 17 from t1)),19) FROM t1 WHERE d in (11,t1.c+c*t1.d+case when t1.c-case when ~(19+13)*c=11 and d<>17 or t1.e>=c then case t1.a when c then f else 11 end+t1.c when t1.f in (select max(13) from t1 union select cast(avg(c) AS integer) from t1) or t1.c<t1.b then 13 else b end=13 then 11 when d<>t1.b then t1.e else 19 end,a)}
} {}
do_test randexpr-2.2385 {
  db eval {SELECT t1.b+coalesce((select max(~e- -t1.d+case +b+f when a-case when t1.a-d+t1.c between t1.e and a*e then (abs(e)/abs(t1.a)) else f |  -f*t1.b-t1.c end*t1.e+f then 19 else t1.b end*19) from t1 where 19 in (select e from t1 union select 17 from t1)),19) FROM t1 WHERE NOT (d in (11,t1.c+c*t1.d+case when t1.c-case when ~(19+13)*c=11 and d<>17 or t1.e>=c then case t1.a when c then f else 11 end+t1.c when t1.f in (select max(13) from t1 union select cast(avg(c) AS integer) from t1) or t1.c<t1.b then 13 else b end=13 then 11 when d<>t1.b then t1.e else 19 end,a))}
} {219}
do_test randexpr-2.2386 {
  db eval {SELECT t1.b+coalesce((select max(~e- -t1.d+case +b+f when a-case when t1.a-d+t1.c between t1.e and a*e then (abs(e)/abs(t1.a)) else f &  -f*t1.b-t1.c end*t1.e+f then 19 else t1.b end*19) from t1 where 19 in (select e from t1 union select 17 from t1)),19) FROM t1 WHERE NOT (d in (11,t1.c+c*t1.d+case when t1.c-case when ~(19+13)*c=11 and d<>17 or t1.e>=c then case t1.a when c then f else 11 end+t1.c when t1.f in (select max(13) from t1 union select cast(avg(c) AS integer) from t1) or t1.c<t1.b then 13 else b end=13 then 11 when d<>t1.b then t1.e else 19 end,a))}
} {219}
do_test randexpr-2.2387 {
  db eval {SELECT (abs((select (case (abs(max( -t1.a))* -case count(*) when case min(c) when max(d) then count(*) else max(17) end-cast(avg(17) AS integer) then max(11) else cast(avg(t1.d) AS integer) end | max(13)+max(f)) when cast(avg(f) AS integer) then cast(avg(19) AS integer) else (max(11)) end) from t1) | coalesce((select (select max( -t1.d) from t1) from t1 where t1.b-~e in (select d from t1 union select e from t1) and t1.e=t1.d), -t1.e)-17)/abs(t1.e)) |  -t1.e FROM t1 WHERE exists(select 1 from t1 where coalesce((select +19 from t1 where (coalesce((select max(e) from t1 where ((coalesce((select max(19) from t1 where coalesce((select t1.d*19+(t1.c) from t1 where e in (select  -11 from t1 union select t1.f from t1) and (t1.d) in (select ~max(t1.e) from t1 union select (( -count(*))) from t1) or 19>=(a)),f) in ((e),e,t1.a)),t1.a)<=t1.c))),t1.f+t1.c)>13)),11) in (11,17,t1.d) and e>=t1.b)}
} {}
do_test randexpr-2.2388 {
  db eval {SELECT (abs((select (case (abs(max( -t1.a))* -case count(*) when case min(c) when max(d) then count(*) else max(17) end-cast(avg(17) AS integer) then max(11) else cast(avg(t1.d) AS integer) end | max(13)+max(f)) when cast(avg(f) AS integer) then cast(avg(19) AS integer) else (max(11)) end) from t1) | coalesce((select (select max( -t1.d) from t1) from t1 where t1.b-~e in (select d from t1 union select e from t1) and t1.e=t1.d), -t1.e)-17)/abs(t1.e)) |  -t1.e FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select +19 from t1 where (coalesce((select max(e) from t1 where ((coalesce((select max(19) from t1 where coalesce((select t1.d*19+(t1.c) from t1 where e in (select  -11 from t1 union select t1.f from t1) and (t1.d) in (select ~max(t1.e) from t1 union select (( -count(*))) from t1) or 19>=(a)),f) in ((e),e,t1.a)),t1.a)<=t1.c))),t1.f+t1.c)>13)),11) in (11,17,t1.d) and e>=t1.b))}
} {-499}
do_test randexpr-2.2389 {
  db eval {SELECT (abs((select (case (abs(max( -t1.a))* -case count(*) when case min(c) when max(d) then count(*) else max(17) end-cast(avg(17) AS integer) then max(11) else cast(avg(t1.d) AS integer) end & max(13)+max(f)) when cast(avg(f) AS integer) then cast(avg(19) AS integer) else (max(11)) end) from t1) & coalesce((select (select max( -t1.d) from t1) from t1 where t1.b-~e in (select d from t1 union select e from t1) and t1.e=t1.d), -t1.e)-17)/abs(t1.e)) &  -t1.e FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select +19 from t1 where (coalesce((select max(e) from t1 where ((coalesce((select max(19) from t1 where coalesce((select t1.d*19+(t1.c) from t1 where e in (select  -11 from t1 union select t1.f from t1) and (t1.d) in (select ~max(t1.e) from t1 union select (( -count(*))) from t1) or 19>=(a)),f) in ((e),e,t1.a)),t1.a)<=t1.c))),t1.f+t1.c)>13)),11) in (11,17,t1.d) and e>=t1.b))}
} {0}
do_test randexpr-2.2390 {
  db eval {SELECT f-coalesce((select 19+t1.e+t1.f from t1 where +11>coalesce((select +t1.f from t1 where t1.a between ~ -(select case cast(avg((abs(t1.d)/abs(t1.b))) AS integer) when  -~max(19) then  - -case count(distinct c) when count(*) then min((a)) else  -min(t1.d) end else max( -t1.b) end from t1) and (select count(distinct f) from t1)),(coalesce((select max(t1.e) from t1 where not 11>=d),t1.c)))),19)-t1.f+19+f*t1.d FROM t1 WHERE f in (select (min((abs(d-t1.c+coalesce((select t1.f from t1 where f<t1.a),t1.c)+a-t1.d*(f)-19)/abs(11))) | abs((count(*))))+(abs(~case count(*) | max(t1.a) when max(t1.d) then count(distinct 19) else count(distinct e) end)+cast(avg((t1.e)) AS integer))+max(t1.c) from t1 union select count(*) from t1) and c*t1.a in (select e from t1 union select f from t1)}
} {}
do_test randexpr-2.2391 {
  db eval {SELECT f-coalesce((select 19+t1.e+t1.f from t1 where +11>coalesce((select +t1.f from t1 where t1.a between ~ -(select case cast(avg((abs(t1.d)/abs(t1.b))) AS integer) when  -~max(19) then  - -case count(distinct c) when count(*) then min((a)) else  -min(t1.d) end else max( -t1.b) end from t1) and (select count(distinct f) from t1)),(coalesce((select max(t1.e) from t1 where not 11>=d),t1.c)))),19)-t1.f+19+f*t1.d FROM t1 WHERE NOT (f in (select (min((abs(d-t1.c+coalesce((select t1.f from t1 where f<t1.a),t1.c)+a-t1.d*(f)-19)/abs(11))) | abs((count(*))))+(abs(~case count(*) | max(t1.a) when max(t1.d) then count(distinct 19) else count(distinct e) end)+cast(avg((t1.e)) AS integer))+max(t1.c) from t1 union select count(*) from t1) and c*t1.a in (select e from t1 union select f from t1))}
} {240000}
do_test randexpr-2.2392 {
  db eval {SELECT t1.b-case when b not between 17 and t1.d*11*f*t1.a or t1.c+case when  -t1.e between t1.d and coalesce((select coalesce((select max((select ~count(*) from t1)) from t1 where  -17*13-19-((d))<>(c)), -a) from t1 where (e)<=t1.a),d) then d when e<t1.f then 19 else e end>=a then t1.f else f end FROM t1 WHERE f in (13*13-(abs(d)/abs(e)),19,case t1.b+coalesce((select max((abs((abs(17)/abs(a)))/abs(11+t1.c))) from t1 where  -t1.c>=t1.f and e in (select count(*) | min(t1.c) from t1 union select cast(avg(e) AS integer) from t1) or 11 not in (e,b,a) or t1.c< -a and t1.e not in (t1.e,b,t1.d)),t1.b) when f then 19 else b end-11) or d>t1.b}
} {-400}
do_test randexpr-2.2393 {
  db eval {SELECT t1.b-case when b not between 17 and t1.d*11*f*t1.a or t1.c+case when  -t1.e between t1.d and coalesce((select coalesce((select max((select ~count(*) from t1)) from t1 where  -17*13-19-((d))<>(c)), -a) from t1 where (e)<=t1.a),d) then d when e<t1.f then 19 else e end>=a then t1.f else f end FROM t1 WHERE NOT (f in (13*13-(abs(d)/abs(e)),19,case t1.b+coalesce((select max((abs((abs(17)/abs(a)))/abs(11+t1.c))) from t1 where  -t1.c>=t1.f and e in (select count(*) | min(t1.c) from t1 union select cast(avg(e) AS integer) from t1) or 11 not in (e,b,a) or t1.c< -a and t1.e not in (t1.e,b,t1.d)),t1.b) when f then 19 else b end-11) or d>t1.b)}
} {}
do_test randexpr-2.2394 {
  db eval {SELECT case t1.d when (abs(17)/abs(coalesce((select max(e) from t1 where a not in (t1.e,case when 11+t1.d not between t1.e and  -t1.c | t1.a*(abs(b)/abs(c)) then  -d when a in (select +11 from t1 union select c from t1) then  -t1.c else 13 end | t1.c,t1.b)),d)-f)) | t1.c then case when 13<c then t1.b when d<>t1.d then 13 else f end else b end FROM t1 WHERE 17>d*~t1.e+case when not t1.f<>(select count(distinct 19)+min(e) from t1) then case when (13-a<= -t1.b) and t1.f<=t1.f then 19*d else f end-t1.f*d+t1.d when b not in (t1.b,19,19) or t1.d not between t1.b and a then t1.f else b end}
} {200}
do_test randexpr-2.2395 {
  db eval {SELECT case t1.d when (abs(17)/abs(coalesce((select max(e) from t1 where a not in (t1.e,case when 11+t1.d not between t1.e and  -t1.c | t1.a*(abs(b)/abs(c)) then  -d when a in (select +11 from t1 union select c from t1) then  -t1.c else 13 end | t1.c,t1.b)),d)-f)) | t1.c then case when 13<c then t1.b when d<>t1.d then 13 else f end else b end FROM t1 WHERE NOT (17>d*~t1.e+case when not t1.f<>(select count(distinct 19)+min(e) from t1) then case when (13-a<= -t1.b) and t1.f<=t1.f then 19*d else f end-t1.f*d+t1.d when b not in (t1.b,19,19) or t1.d not between t1.b and a then t1.f else b end)}
} {}
do_test randexpr-2.2396 {
  db eval {SELECT case t1.d when (abs(17)/abs(coalesce((select max(e) from t1 where a not in (t1.e,case when 11+t1.d not between t1.e and  -t1.c & t1.a*(abs(b)/abs(c)) then  -d when a in (select +11 from t1 union select c from t1) then  -t1.c else 13 end & t1.c,t1.b)),d)-f)) & t1.c then case when 13<c then t1.b when d<>t1.d then 13 else f end else b end FROM t1 WHERE 17>d*~t1.e+case when not t1.f<>(select count(distinct 19)+min(e) from t1) then case when (13-a<= -t1.b) and t1.f<=t1.f then 19*d else f end-t1.f*d+t1.d when b not in (t1.b,19,19) or t1.d not between t1.b and a then t1.f else b end}
} {200}
do_test randexpr-2.2397 {
  db eval {SELECT coalesce((select max(d) from t1 where coalesce((select t1.c from t1 where 17>b),d*coalesce((select max(11*19) from t1 where coalesce((select c from t1 where 19<(abs((case a when b then ~case t1.a+(select min(t1.f)+min(b) from t1) when (d) then e else t1.b end else t1.c end+f+t1.f))/abs(t1.b))),c)<=19),13))*d | e<e),t1.e) FROM t1 WHERE (t1.d*t1.c not in (t1.b,t1.b*t1.f,t1.c))}
} {}
do_test randexpr-2.2398 {
  db eval {SELECT coalesce((select max(d) from t1 where coalesce((select t1.c from t1 where 17>b),d*coalesce((select max(11*19) from t1 where coalesce((select c from t1 where 19<(abs((case a when b then ~case t1.a+(select min(t1.f)+min(b) from t1) when (d) then e else t1.b end else t1.c end+f+t1.f))/abs(t1.b))),c)<=19),13))*d | e<e),t1.e) FROM t1 WHERE NOT ((t1.d*t1.c not in (t1.b,t1.b*t1.f,t1.c)))}
} {500}
do_test randexpr-2.2399 {
  db eval {SELECT coalesce((select max(d) from t1 where coalesce((select t1.c from t1 where 17>b),d*coalesce((select max(11*19) from t1 where coalesce((select c from t1 where 19<(abs((case a when b then ~case t1.a+(select min(t1.f)+min(b) from t1) when (d) then e else t1.b end else t1.c end+f+t1.f))/abs(t1.b))),c)<=19),13))*d & e<e),t1.e) FROM t1 WHERE NOT ((t1.d*t1.c not in (t1.b,t1.b*t1.f,t1.c)))}
} {400}
do_test randexpr-2.2400 {
  db eval {SELECT t1.b+ -t1.d*(select max(t1.a) | count(*) | abs(cast(avg(f+a-(select ~(min((abs(a)/abs(13+case when f=coalesce((select t1.b from t1 where d<>t1.e and 11 in (t1.e,t1.e,d)),f)+13 then t1.b else c end))- -f)) from t1)) AS integer))-count(distinct 11+11+13)+count(distinct t1.a) from t1) FROM t1 WHERE t1.d<c+t1.c | (select max((t1.e)) from t1)+case when t1.f-t1.d<a then t1.c-(abs(c)/abs(b*t1.c)) when case when not  -c>=b then t1.c when  -f*e<=t1.b then e else 17 end not between 17 and t1.f then t1.c else t1.b end-19+f+19*(t1.c)}
} {-558600}
do_test randexpr-2.2401 {
  db eval {SELECT t1.b+ -t1.d*(select max(t1.a) | count(*) | abs(cast(avg(f+a-(select ~(min((abs(a)/abs(13+case when f=coalesce((select t1.b from t1 where d<>t1.e and 11 in (t1.e,t1.e,d)),f)+13 then t1.b else c end))- -f)) from t1)) AS integer))-count(distinct 11+11+13)+count(distinct t1.a) from t1) FROM t1 WHERE NOT (t1.d<c+t1.c | (select max((t1.e)) from t1)+case when t1.f-t1.d<a then t1.c-(abs(c)/abs(b*t1.c)) when case when not  -c>=b then t1.c when  -f*e<=t1.b then e else 17 end not between 17 and t1.f then t1.c else t1.b end-19+f+19*(t1.c))}
} {}
do_test randexpr-2.2402 {
  db eval {SELECT t1.b+ -t1.d*(select max(t1.a) & count(*) & abs(cast(avg(f+a-(select ~(min((abs(a)/abs(13+case when f=coalesce((select t1.b from t1 where d<>t1.e and 11 in (t1.e,t1.e,d)),f)+13 then t1.b else c end))- -f)) from t1)) AS integer))-count(distinct 11+11+13)+count(distinct t1.a) from t1) FROM t1 WHERE t1.d<c+t1.c | (select max((t1.e)) from t1)+case when t1.f-t1.d<a then t1.c-(abs(c)/abs(b*t1.c)) when case when not  -c>=b then t1.c when  -f*e<=t1.b then e else 17 end not between 17 and t1.f then t1.c else t1.b end-19+f+19*(t1.c)}
} {200}
do_test randexpr-2.2403 {
  db eval {SELECT case when case when t1.e<~17 or (case case case t1.d*17*13 when t1.a then e+c else c end when d*f+coalesce((select 17 from t1 where 13 not between 13 and  -13),(17)) then t1.b else b end when t1.a then a else t1.c end*d<>d) then ~t1.c else a end<>t1.f then  -t1.d else t1.a end+11-t1.c-e FROM t1 WHERE (case when (~f- -e in (17,case when d in (select t1.f from t1 union select a+(abs(coalesce((select (t1.c) from t1 where a in (select min(13) | (max(t1.e)) from t1 union select count(distinct t1.d) from t1)),b)+13)/abs(e))*19*f from t1) then b when not a between 13 and 13 then t1.f else 17 end,t1.c)) then (select max(t1.e)-count(*) | count(*) from t1) else c end)>(t1.e)}
} {}
do_test randexpr-2.2404 {
  db eval {SELECT case when case when t1.e<~17 or (case case case t1.d*17*13 when t1.a then e+c else c end when d*f+coalesce((select 17 from t1 where 13 not between 13 and  -13),(17)) then t1.b else b end when t1.a then a else t1.c end*d<>d) then ~t1.c else a end<>t1.f then  -t1.d else t1.a end+11-t1.c-e FROM t1 WHERE NOT ((case when (~f- -e in (17,case when d in (select t1.f from t1 union select a+(abs(coalesce((select (t1.c) from t1 where a in (select min(13) | (max(t1.e)) from t1 union select count(distinct t1.d) from t1)),b)+13)/abs(e))*19*f from t1) then b when not a between 13 and 13 then t1.f else 17 end,t1.c)) then (select max(t1.e)-count(*) | count(*) from t1) else c end)>(t1.e))}
} {-1189}
do_test randexpr-2.2405 {
  db eval {SELECT coalesce((select max(t1.a-(abs(e*coalesce((select max(d) from t1 where (case when case e when case when (t1.e)=d then t1.a+11 else 17 end then (c) else b end<=a then b when 19 in (t1.b,b,t1.e) then f else  -19 end+17 between 19 and c or b in (select t1.c from t1 union select t1.a from t1))),t1.a))/abs( -t1.d))) from t1 where 13=17),t1.b)+(t1.b) FROM t1 WHERE coalesce((select  -case when (d)>=(select ~case +(+~~cast(avg(a) AS integer)*abs(( -count(*))) | count(distinct 11)) when (count(*)) then count(distinct 19) else min(t1.a) end+min(t1.a) from t1)*13-t1.f then 13 else (e) | t1.c*(select (min(17)) from t1) end*case when (c) in (select 11 from t1 union select t1.f from t1) then 17 else 19 end from t1 where t1.c<t1.f),19)*19<>c}
} {400}
do_test randexpr-2.2406 {
  db eval {SELECT coalesce((select max(t1.a-(abs(e*coalesce((select max(d) from t1 where (case when case e when case when (t1.e)=d then t1.a+11 else 17 end then (c) else b end<=a then b when 19 in (t1.b,b,t1.e) then f else  -19 end+17 between 19 and c or b in (select t1.c from t1 union select t1.a from t1))),t1.a))/abs( -t1.d))) from t1 where 13=17),t1.b)+(t1.b) FROM t1 WHERE NOT (coalesce((select  -case when (d)>=(select ~case +(+~~cast(avg(a) AS integer)*abs(( -count(*))) | count(distinct 11)) when (count(*)) then count(distinct 19) else min(t1.a) end+min(t1.a) from t1)*13-t1.f then 13 else (e) | t1.c*(select (min(17)) from t1) end*case when (c) in (select 11 from t1 union select t1.f from t1) then 17 else 19 end from t1 where t1.c<t1.f),19)*19<>c)}
} {}
do_test randexpr-2.2407 {
  db eval {SELECT t1.b-t1.d-case when exists(select 1 from t1 where  -coalesce((select t1.a from t1 where a in (c,coalesce((select max((abs(t1.d)/abs(e))) from t1 where case t1.b when t1.e then t1.d else t1.d end-17 between b and t1.f),17)-t1.f-t1.e,t1.a) or t1.b in (t1.a,19,t1.f)),19)>=d) then 19-b when t1.c between (f) and t1.f then t1.d else t1.f end-11 FROM t1 WHERE coalesce((select 13 from t1 where ( -t1.a<d)),(abs(t1.d)/abs(case when ( -11)+f+d+ -17+f*e not between t1.b and  -11 and not t1.a<>13 or a in (select cast(avg(d) AS integer) | count(*)* -max(t1.f) from t1 union select count(*) from t1) then 17 when not exists(select 1 from t1 where b>=c) then e else 17 end |  -t1.a))*b)*t1.d>=b}
} {-811}
do_test randexpr-2.2408 {
  db eval {SELECT t1.b-t1.d-case when exists(select 1 from t1 where  -coalesce((select t1.a from t1 where a in (c,coalesce((select max((abs(t1.d)/abs(e))) from t1 where case t1.b when t1.e then t1.d else t1.d end-17 between b and t1.f),17)-t1.f-t1.e,t1.a) or t1.b in (t1.a,19,t1.f)),19)>=d) then 19-b when t1.c between (f) and t1.f then t1.d else t1.f end-11 FROM t1 WHERE NOT (coalesce((select 13 from t1 where ( -t1.a<d)),(abs(t1.d)/abs(case when ( -11)+f+d+ -17+f*e not between t1.b and  -11 and not t1.a<>13 or a in (select cast(avg(d) AS integer) | count(*)* -max(t1.f) from t1 union select count(*) from t1) then 17 when not exists(select 1 from t1 where b>=c) then e else 17 end |  -t1.a))*b)*t1.d>=b)}
} {}
do_test randexpr-2.2409 {
  db eval {SELECT 17 | t1.c*t1.a | case when ~ -~(abs(t1.b)/abs(coalesce((select max(coalesce((select max(+t1.d) from t1 where (t1.b not between 17 and t1.b) and d not between c and 19),d)*(t1.d)-d) from t1 where t1.a in (t1.c,(t1.c),t1.f)),19)))-b+19+ -17>=t1.a then 19 when 19 in (select t1.f from t1 union select t1.b from t1) then t1.c else f end-19*t1.c FROM t1 WHERE (17-t1.f in (d | b-17,t1.f,coalesce((select e+(abs(11)/abs(case t1.c when case (abs(a)/abs(11)) when e then t1.c else 17+c end then b else 11+t1.e end)) from t1 where (13 not between + -b and 13)),t1.c)) and 17 between t1.d | t1.f and t1.e)}
} {}
do_test randexpr-2.2410 {
  db eval {SELECT 17 | t1.c*t1.a | case when ~ -~(abs(t1.b)/abs(coalesce((select max(coalesce((select max(+t1.d) from t1 where (t1.b not between 17 and t1.b) and d not between c and 19),d)*(t1.d)-d) from t1 where t1.a in (t1.c,(t1.c),t1.f)),19)))-b+19+ -17>=t1.a then 19 when 19 in (select t1.f from t1 union select t1.b from t1) then t1.c else f end-19*t1.c FROM t1 WHERE NOT ((17-t1.f in (d | b-17,t1.f,coalesce((select e+(abs(11)/abs(case t1.c when case (abs(a)/abs(11)) when e then t1.c else 17+c end then b else 11+t1.e end)) from t1 where (13 not between + -b and 13)),t1.c)) and 17 between t1.d | t1.f and t1.e))}
} {-715}
do_test randexpr-2.2411 {
  db eval {SELECT 17 & t1.c*t1.a & case when ~ -~(abs(t1.b)/abs(coalesce((select max(coalesce((select max(+t1.d) from t1 where (t1.b not between 17 and t1.b) and d not between c and 19),d)*(t1.d)-d) from t1 where t1.a in (t1.c,(t1.c),t1.f)),19)))-b+19+ -17>=t1.a then 19 when 19 in (select t1.f from t1 union select t1.b from t1) then t1.c else f end-19*t1.c FROM t1 WHERE NOT ((17-t1.f in (d | b-17,t1.f,coalesce((select e+(abs(11)/abs(case t1.c when case (abs(a)/abs(11)) when e then t1.c else 17+c end then b else 11+t1.e end)) from t1 where (13 not between + -b and 13)),t1.c)) and 17 between t1.d | t1.f and t1.e))}
} {16}
do_test randexpr-2.2412 {
  db eval {SELECT coalesce((select t1.a*a+t1.f | t1.d from t1 where t1.d<+t1.c*d-c*19+t1.e-(abs( -t1.e)/abs(19))), -t1.c+coalesce((select t1.b from t1 where not not (select max(t1.c) from t1)-17+e in (e,t1.c,b) and not (d in (select ( -((max(b)))) from t1 union select min(d) from t1))),t1.b) | t1.a) FROM t1 WHERE not t1.f in (select ((select abs(count(*)) from t1)-11) from t1 union select t1.a-17 from t1) or not exists(select 1 from t1 where case (abs(e)/abs(+c)) when coalesce((select max((select +(count(distinct t1.a)) from t1)) from t1 where not (e<=c*t1.a)),~(case when t1.c<=17 then e when t1.c<=t1.c then e else 17 end)) then 13 else d end*b-a= -d)}
} {10744}
do_test randexpr-2.2413 {
  db eval {SELECT coalesce((select t1.a*a+t1.f | t1.d from t1 where t1.d<+t1.c*d-c*19+t1.e-(abs( -t1.e)/abs(19))), -t1.c+coalesce((select t1.b from t1 where not not (select max(t1.c) from t1)-17+e in (e,t1.c,b) and not (d in (select ( -((max(b)))) from t1 union select min(d) from t1))),t1.b) | t1.a) FROM t1 WHERE NOT (not t1.f in (select ((select abs(count(*)) from t1)-11) from t1 union select t1.a-17 from t1) or not exists(select 1 from t1 where case (abs(e)/abs(+c)) when coalesce((select max((select +(count(distinct t1.a)) from t1)) from t1 where not (e<=c*t1.a)),~(case when t1.c<=17 then e when t1.c<=t1.c then e else 17 end)) then 13 else d end*b-a= -d))}
} {}
do_test randexpr-2.2414 {
  db eval {SELECT coalesce((select t1.a*a+t1.f & t1.d from t1 where t1.d<+t1.c*d-c*19+t1.e-(abs( -t1.e)/abs(19))), -t1.c+coalesce((select t1.b from t1 where not not (select max(t1.c) from t1)-17+e in (e,t1.c,b) and not (d in (select ( -((max(b)))) from t1 union select min(d) from t1))),t1.b) & t1.a) FROM t1 WHERE not t1.f in (select ((select abs(count(*)) from t1)-11) from t1 union select t1.a-17 from t1) or not exists(select 1 from t1 where case (abs(e)/abs(+c)) when coalesce((select max((select +(count(distinct t1.a)) from t1)) from t1 where not (e<=c*t1.a)),~(case when t1.c<=17 then e when t1.c<=t1.c then e else 17 end)) then 13 else d end*b-a= -d)}
} {256}
do_test randexpr-2.2415 {
  db eval {SELECT case a+(abs(+13)/abs(a)) when ~(e)*(abs(b* -t1.d*19-t1.c+a-~t1.b*b-coalesce((select max(case when not exists(select 1 from t1 where d in (f,t1.c,f) or t1.c not in (13,f,t1.a)) then case when t1.a>= -t1.e then (( - -b)) else t1.b end else c end+e) from t1 where (a>11)),13)*17)/abs(e)) then 11 else c end FROM t1 WHERE 17 between a and t1.a}
} {}
do_test randexpr-2.2416 {
  db eval {SELECT case a+(abs(+13)/abs(a)) when ~(e)*(abs(b* -t1.d*19-t1.c+a-~t1.b*b-coalesce((select max(case when not exists(select 1 from t1 where d in (f,t1.c,f) or t1.c not in (13,f,t1.a)) then case when t1.a>= -t1.e then (( - -b)) else t1.b end else c end+e) from t1 where (a>11)),13)*17)/abs(e)) then 11 else c end FROM t1 WHERE NOT (17 between a and t1.a)}
} {300}
do_test randexpr-2.2417 {
  db eval {SELECT +~t1.f-c*case when t1.f between coalesce((select max(a) from t1 where (t1.c-17*t1.b | c=e)),t1.b) and (abs(coalesce((select max(19) from t1 where t1.b not between c+(select min(t1.d) from t1)-t1.d+d+t1.d+t1.c*t1.e and 11),t1.a))/abs(a))-c*b then 17 else 13 end FROM t1 WHERE t1.c not between (abs(+case when not  -19 in (case when t1.b+~d+11+f>e then (select  -cast(avg(coalesce((select 17 from t1 where (t1.b>=f)),19)) AS integer)*min(d)*(min(e))* -min(b) from t1) when 17+b not between 17 and t1.a then 11 else a end,19,(t1.e)) then f else 19 end*t1.a)/abs(b)) and 19}
} {-4501}
do_test randexpr-2.2418 {
  db eval {SELECT +~t1.f-c*case when t1.f between coalesce((select max(a) from t1 where (t1.c-17*t1.b | c=e)),t1.b) and (abs(coalesce((select max(19) from t1 where t1.b not between c+(select min(t1.d) from t1)-t1.d+d+t1.d+t1.c*t1.e and 11),t1.a))/abs(a))-c*b then 17 else 13 end FROM t1 WHERE NOT (t1.c not between (abs(+case when not  -19 in (case when t1.b+~d+11+f>e then (select  -cast(avg(coalesce((select 17 from t1 where (t1.b>=f)),19)) AS integer)*min(d)*(min(e))* -min(b) from t1) when 17+b not between 17 and t1.a then 11 else a end,19,(t1.e)) then f else 19 end*t1.a)/abs(b)) and 19)}
} {}
do_test randexpr-2.2419 {
  db eval {SELECT +~t1.f-c*case when t1.f between coalesce((select max(a) from t1 where (t1.c-17*t1.b & c=e)),t1.b) and (abs(coalesce((select max(19) from t1 where t1.b not between c+(select min(t1.d) from t1)-t1.d+d+t1.d+t1.c*t1.e and 11),t1.a))/abs(a))-c*b then 17 else 13 end FROM t1 WHERE t1.c not between (abs(+case when not  -19 in (case when t1.b+~d+11+f>e then (select  -cast(avg(coalesce((select 17 from t1 where (t1.b>=f)),19)) AS integer)*min(d)*(min(e))* -min(b) from t1) when 17+b not between 17 and t1.a then 11 else a end,19,(t1.e)) then f else 19 end*t1.a)/abs(b)) and 19}
} {-4501}
do_test randexpr-2.2420 {
  db eval {SELECT +(abs(case t1.a when coalesce((select max(13) from t1 where d<=case when t1.b=(select abs(count(distinct t1.e)) from t1) and (select  -count(distinct e) from t1) not in ( -11,e,13) then 13 else t1.e end and (not exists(select 1 from t1 where t1.d in (select count(*) from t1 union select max(f) from t1))) and 19<f and t1.f>=13 or  -e=17),coalesce((select (abs(17)/abs(b))-t1.b from t1 where (19)<=t1.f),t1.d))*t1.b then 17 else 13 end)/abs(19)) FROM t1 WHERE a in (select case max(13)-~cast(avg(case when t1.d>13 or exists(select 1 from t1 where not (( -c<=e)) and (b)*t1.a in (select count(*) from t1 union select cast(avg(t1.c) AS integer)+max(f) from t1)) then t1.a else t1.c end) AS integer) when abs(count(distinct t1.d)) then count(distinct (~t1.a)) else count(distinct c)-cast(avg(e) AS integer) end from t1 union select abs(count(distinct a)*max(t1.d)) from t1)}
} {}
do_test randexpr-2.2421 {
  db eval {SELECT +(abs(case t1.a when coalesce((select max(13) from t1 where d<=case when t1.b=(select abs(count(distinct t1.e)) from t1) and (select  -count(distinct e) from t1) not in ( -11,e,13) then 13 else t1.e end and (not exists(select 1 from t1 where t1.d in (select count(*) from t1 union select max(f) from t1))) and 19<f and t1.f>=13 or  -e=17),coalesce((select (abs(17)/abs(b))-t1.b from t1 where (19)<=t1.f),t1.d))*t1.b then 17 else 13 end)/abs(19)) FROM t1 WHERE NOT (a in (select case max(13)-~cast(avg(case when t1.d>13 or exists(select 1 from t1 where not (( -c<=e)) and (b)*t1.a in (select count(*) from t1 union select cast(avg(t1.c) AS integer)+max(f) from t1)) then t1.a else t1.c end) AS integer) when abs(count(distinct t1.d)) then count(distinct (~t1.a)) else count(distinct c)-cast(avg(e) AS integer) end from t1 union select abs(count(distinct a)*max(t1.d)) from t1))}
} {0}
do_test randexpr-2.2422 {
  db eval {SELECT +coalesce((select max(f+c) from t1 where t1.b in (select +max(b+t1.b) from t1 union select cast(avg(d-b | f-11-t1.b | coalesce((select ~t1.a from t1 where (t1.a=case when not exists(select 1 from t1 where 13 not in (t1.b,t1.e,t1.f)) then (abs(t1.d)/abs(c)) when c<>17 then c else 19 end)),t1.c)) AS integer) from t1) and t1.e not in (b,d,(13))),t1.b) FROM t1 WHERE (select cast(avg(~t1.f) AS integer) from t1) not in ( -c,17,11*c)}
} {200}
do_test randexpr-2.2423 {
  db eval {SELECT +coalesce((select max(f+c) from t1 where t1.b in (select +max(b+t1.b) from t1 union select cast(avg(d-b | f-11-t1.b | coalesce((select ~t1.a from t1 where (t1.a=case when not exists(select 1 from t1 where 13 not in (t1.b,t1.e,t1.f)) then (abs(t1.d)/abs(c)) when c<>17 then c else 19 end)),t1.c)) AS integer) from t1) and t1.e not in (b,d,(13))),t1.b) FROM t1 WHERE NOT ((select cast(avg(~t1.f) AS integer) from t1) not in ( -c,17,11*c))}
} {}
do_test randexpr-2.2424 {
  db eval {SELECT +coalesce((select max(f+c) from t1 where t1.b in (select +max(b+t1.b) from t1 union select cast(avg(d-b & f-11-t1.b & coalesce((select ~t1.a from t1 where (t1.a=case when not exists(select 1 from t1 where 13 not in (t1.b,t1.e,t1.f)) then (abs(t1.d)/abs(c)) when c<>17 then c else 19 end)),t1.c)) AS integer) from t1) and t1.e not in (b,d,(13))),t1.b) FROM t1 WHERE (select cast(avg(~t1.f) AS integer) from t1) not in ( -c,17,11*c)}
} {200}
do_test randexpr-2.2425 {
  db eval {SELECT t1.e*case when ((13)-13-13-t1.d+t1.c*b>11) then b when case when (t1.a*b not in (t1.a,t1.b,t1.f)) then 11+e else t1.f end<= -f or f in (t1.a,11,13) or exists(select 1 from t1 where not exists(select 1 from t1 where f in (f,d,t1.e))) then t1.d else b end FROM t1 WHERE coalesce((select 19 from t1 where 13-t1.b*c-t1.a+case when case when coalesce((select +t1.b from t1 where a<>b),13) in ((b),t1.f,b) and not t1.b in (select  -cast(avg(13) AS integer) from t1 union select cast(avg(11) AS integer) from t1) or a>=13 then (abs(t1.b+a)/abs(11)) else t1.e end-17+t1.d<>b then (19) else f end=e),13)>=t1.c}
} {}
do_test randexpr-2.2426 {
  db eval {SELECT t1.e*case when ((13)-13-13-t1.d+t1.c*b>11) then b when case when (t1.a*b not in (t1.a,t1.b,t1.f)) then 11+e else t1.f end<= -f or f in (t1.a,11,13) or exists(select 1 from t1 where not exists(select 1 from t1 where f in (f,d,t1.e))) then t1.d else b end FROM t1 WHERE NOT (coalesce((select 19 from t1 where 13-t1.b*c-t1.a+case when case when coalesce((select +t1.b from t1 where a<>b),13) in ((b),t1.f,b) and not t1.b in (select  -cast(avg(13) AS integer) from t1 union select cast(avg(11) AS integer) from t1) or a>=13 then (abs(t1.b+a)/abs(11)) else t1.e end-17+t1.d<>b then (19) else f end=e),13)>=t1.c)}
} {100000}
do_test randexpr-2.2427 {
  db eval {SELECT coalesce((select max(d) from t1 where 19+case t1.b when t1.a-a then (abs(case when (e>=case t1.a when coalesce((select max(t1.d) from t1 where (select case  -max(c)+cast(avg(t1.a) AS integer) when cast(avg(t1.a) AS integer) then cast(avg(19) AS integer) else cast(avg(t1.b) AS integer) end from t1)>t1.c),coalesce((select max(d) from t1 where 19<>17 and d<=b), -(t1.c)))+e then c else t1.d end+b) then b when 19 between c and 17 then 11 else e end)/abs( -t1.b)) else t1.a end+13>=d),d) FROM t1 WHERE a=case when t1.f in (select (max(f)-++(min(t1.a))-max(19)-count(*)) from t1 union select +max(t1.b) from t1) then t1.b*19*19 when t1.f>d then 17-d else t1.f end and exists(select 1 from t1 where not exists(select 1 from t1 where d in (select count(distinct 11)+max(a) from t1 union select cast(avg(13) AS integer) from t1) or 19 not in (t1.b,c,13)))}
} {}
do_test randexpr-2.2428 {
  db eval {SELECT coalesce((select max(d) from t1 where 19+case t1.b when t1.a-a then (abs(case when (e>=case t1.a when coalesce((select max(t1.d) from t1 where (select case  -max(c)+cast(avg(t1.a) AS integer) when cast(avg(t1.a) AS integer) then cast(avg(19) AS integer) else cast(avg(t1.b) AS integer) end from t1)>t1.c),coalesce((select max(d) from t1 where 19<>17 and d<=b), -(t1.c)))+e then c else t1.d end+b) then b when 19 between c and 17 then 11 else e end)/abs( -t1.b)) else t1.a end+13>=d),d) FROM t1 WHERE NOT (a=case when t1.f in (select (max(f)-++(min(t1.a))-max(19)-count(*)) from t1 union select +max(t1.b) from t1) then t1.b*19*19 when t1.f>d then 17-d else t1.f end and exists(select 1 from t1 where not exists(select 1 from t1 where d in (select count(distinct 11)+max(a) from t1 union select cast(avg(13) AS integer) from t1) or 19 not in (t1.b,c,13))))}
} {400}
do_test randexpr-2.2429 {
  db eval {SELECT coalesce((select max(case t1.c | b-t1.d+13 when 17 then c else 13 end) from t1 where case when exists(select 1 from t1 where b<>t1.c) then t1.d when a not between (abs(t1.d)/abs((t1.b))) and (t1.c) or (a in (select ~max(((17))) from t1 union select case  -(count(distinct  -t1.c)) when count(distinct t1.c) then (count(*)) else max(f) end from t1)) and t1.f>19 or a<>11 then t1.b else t1.b end>(11)),13)+b*(b) FROM t1 WHERE case when not exists(select 1 from t1 where (19<>11+t1.b*c+d)) and 13<>b or t1.d between t1.c and b and f between t1.b and  -a or 19 between 19 and 17 or t1.e not between e and t1.d then ~13 else coalesce((select max(t1.b) from t1 where f=a),(a)) end in (select  -( -+count(distinct 11)-count(*))*count(distinct ( -t1.c))+(count(distinct t1.c))+max(17)-count(*) from t1 union select count(*) from t1)}
} {}
do_test randexpr-2.2430 {
  db eval {SELECT coalesce((select max(case t1.c | b-t1.d+13 when 17 then c else 13 end) from t1 where case when exists(select 1 from t1 where b<>t1.c) then t1.d when a not between (abs(t1.d)/abs((t1.b))) and (t1.c) or (a in (select ~max(((17))) from t1 union select case  -(count(distinct  -t1.c)) when count(distinct t1.c) then (count(*)) else max(f) end from t1)) and t1.f>19 or a<>11 then t1.b else t1.b end>(11)),13)+b*(b) FROM t1 WHERE NOT (case when not exists(select 1 from t1 where (19<>11+t1.b*c+d)) and 13<>b or t1.d between t1.c and b and f between t1.b and  -a or 19 between 19 and 17 or t1.e not between e and t1.d then ~13 else coalesce((select max(t1.b) from t1 where f=a),(a)) end in (select  -( -+count(distinct 11)-count(*))*count(distinct ( -t1.c))+(count(distinct t1.c))+max(17)-count(*) from t1 union select count(*) from t1))}
} {40013}
do_test randexpr-2.2431 {
  db eval {SELECT coalesce((select max(case t1.c & b-t1.d+13 when 17 then c else 13 end) from t1 where case when exists(select 1 from t1 where b<>t1.c) then t1.d when a not between (abs(t1.d)/abs((t1.b))) and (t1.c) or (a in (select ~max(((17))) from t1 union select case  -(count(distinct  -t1.c)) when count(distinct t1.c) then (count(*)) else max(f) end from t1)) and t1.f>19 or a<>11 then t1.b else t1.b end>(11)),13)+b*(b) FROM t1 WHERE NOT (case when not exists(select 1 from t1 where (19<>11+t1.b*c+d)) and 13<>b or t1.d between t1.c and b and f between t1.b and  -a or 19 between 19 and 17 or t1.e not between e and t1.d then ~13 else coalesce((select max(t1.b) from t1 where f=a),(a)) end in (select  -( -+count(distinct 11)-count(*))*count(distinct ( -t1.c))+(count(distinct t1.c))+max(17)-count(*) from t1 union select count(*) from t1))}
} {40013}
do_test randexpr-2.2432 {
  db eval {SELECT coalesce((select max(coalesce((select max(11) from t1 where t1.b< -t1.b),e)+coalesce((select t1.b from t1 where not case when ~case when  -17+t1.d> - -t1.d then t1.b when t1.b between 13 and c or t1.a>= -f then t1.b else t1.e end+t1.c<= -c then 19 else t1.f end not in (c,d,e) or t1.f not between t1.b and 19 and 13>= -t1.f or 13 in (e,(t1.b),11)),t1.b)) from t1 where  -(f) not in (f,(t1.e),b)),t1.f) FROM t1 WHERE f in (select f from t1 union select t1.f*t1.b from t1)}
} {700}
do_test randexpr-2.2433 {
  db eval {SELECT coalesce((select max(coalesce((select max(11) from t1 where t1.b< -t1.b),e)+coalesce((select t1.b from t1 where not case when ~case when  -17+t1.d> - -t1.d then t1.b when t1.b between 13 and c or t1.a>= -f then t1.b else t1.e end+t1.c<= -c then 19 else t1.f end not in (c,d,e) or t1.f not between t1.b and 19 and 13>= -t1.f or 13 in (e,(t1.b),11)),t1.b)) from t1 where  -(f) not in (f,(t1.e),b)),t1.f) FROM t1 WHERE NOT (f in (select f from t1 union select t1.f*t1.b from t1))}
} {}
do_test randexpr-2.2434 {
  db eval {SELECT ( -+(a)*(abs(case coalesce((select max(d) from t1 where t1.d<>c*(select count(distinct e*coalesce((select 13-17 from t1 where not exists(select 1 from t1 where t1.a in (select f from t1 union select (a) from t1))),t1.f)+(t1.c)) from t1) | t1.e*19 and not t1.a<13),t1.b)+t1.b when t1.d then (t1.f) else t1.c end)/abs(t1.f))-13*t1.f) FROM t1 WHERE f>=t1.a+ -(select (count(*))-(~case cast(avg(t1.b-13-e) AS integer) when count(*) then (max(t1.f*case 13 when 11 then 13 else c end))- -cast(avg(t1.f) AS integer)*count(*)-min(19) else count(distinct d) end)+min(t1.d) |  -max(t1.b) from t1) | t1.b*17+t1.d+t1.b-d}
} {}
do_test randexpr-2.2435 {
  db eval {SELECT ( -+(a)*(abs(case coalesce((select max(d) from t1 where t1.d<>c*(select count(distinct e*coalesce((select 13-17 from t1 where not exists(select 1 from t1 where t1.a in (select f from t1 union select (a) from t1))),t1.f)+(t1.c)) from t1) | t1.e*19 and not t1.a<13),t1.b)+t1.b when t1.d then (t1.f) else t1.c end)/abs(t1.f))-13*t1.f) FROM t1 WHERE NOT (f>=t1.a+ -(select (count(*))-(~case cast(avg(t1.b-13-e) AS integer) when count(*) then (max(t1.f*case 13 when 11 then 13 else c end))- -cast(avg(t1.f) AS integer)*count(*)-min(19) else count(distinct d) end)+min(t1.d) |  -max(t1.b) from t1) | t1.b*17+t1.d+t1.b-d)}
} {-7800}
do_test randexpr-2.2436 {
  db eval {SELECT ( -+(a)*(abs(case coalesce((select max(d) from t1 where t1.d<>c*(select count(distinct e*coalesce((select 13-17 from t1 where not exists(select 1 from t1 where t1.a in (select f from t1 union select (a) from t1))),t1.f)+(t1.c)) from t1) & t1.e*19 and not t1.a<13),t1.b)+t1.b when t1.d then (t1.f) else t1.c end)/abs(t1.f))-13*t1.f) FROM t1 WHERE NOT (f>=t1.a+ -(select (count(*))-(~case cast(avg(t1.b-13-e) AS integer) when count(*) then (max(t1.f*case 13 when 11 then 13 else c end))- -cast(avg(t1.f) AS integer)*count(*)-min(19) else count(distinct d) end)+min(t1.d) |  -max(t1.b) from t1) | t1.b*17+t1.d+t1.b-d)}
} {-7800}
do_test randexpr-2.2437 {
  db eval {SELECT coalesce((select t1.a from t1 where c in (select a from t1 union select t1.a*f from t1) and t1.b in (select (select count(*) from t1)*11 from t1 union select  -13 from t1)),13) FROM t1 WHERE (d<t1.b)}
} {}
do_test randexpr-2.2438 {
  db eval {SELECT coalesce((select t1.a from t1 where c in (select a from t1 union select t1.a*f from t1) and t1.b in (select (select count(*) from t1)*11 from t1 union select  -13 from t1)),13) FROM t1 WHERE NOT ((d<t1.b))}
} {13}
do_test randexpr-2.2439 {
  db eval {SELECT case when (not exists(select 1 from t1 where a<=case a | e-case t1.f when c then e else 19 end | t1.b when t1.c then t1.e else 19 end+d)) or f between a and b and (t1.f) not in (d,t1.e,11) then case 17+e | t1.c when 19 then 13 else  -(19) end | 11 else a end-t1.f-f*t1.c FROM t1 WHERE case when t1.b in ( - -case when case when t1.f-case when 19<=c then a else 19 end between 13 and t1.d and not a not in ((f),d,f) then t1.c-a when t1.d not in ( -b,c,11) then 13 else f end>=17 then d when f<=t1.c then t1.a else d end,t1.e,e) or not 19>c then t1.c-19 else 13 end<>t1.c}
} {-180500}
do_test randexpr-2.2440 {
  db eval {SELECT case when (not exists(select 1 from t1 where a<=case a | e-case t1.f when c then e else 19 end | t1.b when t1.c then t1.e else 19 end+d)) or f between a and b and (t1.f) not in (d,t1.e,11) then case 17+e | t1.c when 19 then 13 else  -(19) end | 11 else a end-t1.f-f*t1.c FROM t1 WHERE NOT (case when t1.b in ( - -case when case when t1.f-case when 19<=c then a else 19 end between 13 and t1.d and not a not in ((f),d,f) then t1.c-a when t1.d not in ( -b,c,11) then 13 else f end>=17 then d when f<=t1.c then t1.a else d end,t1.e,e) or not 19>c then t1.c-19 else 13 end<>t1.c)}
} {}
do_test randexpr-2.2441 {
  db eval {SELECT case when (not exists(select 1 from t1 where a<=case a & e-case t1.f when c then e else 19 end & t1.b when t1.c then t1.e else 19 end+d)) or f between a and b and (t1.f) not in (d,t1.e,11) then case 17+e & t1.c when 19 then 13 else  -(19) end & 11 else a end-t1.f-f*t1.c FROM t1 WHERE case when t1.b in ( - -case when case when t1.f-case when 19<=c then a else 19 end between 13 and t1.d and not a not in ((f),d,f) then t1.c-a when t1.d not in ( -b,c,11) then 13 else f end>=17 then d when f<=t1.c then t1.a else d end,t1.e,e) or not 19>c then t1.c-19 else 13 end<>t1.c}
} {-180500}
do_test randexpr-2.2442 {
  db eval {SELECT coalesce((select d-(abs(case when +coalesce((select 19 from t1 where not exists(select 1 from t1 where d | f in (select ~case count(distinct f) when ( -(cast(avg((( -19))) AS integer))) then (count(*)) else count(distinct 17) end*(max(t1.d)) from t1 union select min(b) from t1))),13) | t1.b+t1.e in (13,(t1.b),t1.a) then t1.a when a in (select t1.f from t1 union select t1.b from t1) then t1.e else a end)/abs(f))-t1.e from t1 where not exists(select 1 from t1 where not 19 in (select t1.b from t1 union select t1.f from t1) or 13 in (select e from t1 union select e from t1))),f) FROM t1 WHERE not exists(select 1 from t1 where case when not exists(select 1 from t1 where a<+case c when (abs(t1.b)/abs(e))+t1.b-b-t1.b then (t1.d)*t1.c else t1.d end) then b else 19 end in (select  -count(distinct c)*(max(f)) | ~+case min(t1.a) when cast(avg(c) AS integer) then cast(avg(t1.a) AS integer) | count(distinct t1.d)* -count(distinct t1.e) else ( -count(*)) end |  -cast(avg(t1.d) AS integer)+min(a)*count(distinct b) from t1 union select max(13) from t1))}
} {600}
do_test randexpr-2.2443 {
  db eval {SELECT coalesce((select d-(abs(case when +coalesce((select 19 from t1 where not exists(select 1 from t1 where d | f in (select ~case count(distinct f) when ( -(cast(avg((( -19))) AS integer))) then (count(*)) else count(distinct 17) end*(max(t1.d)) from t1 union select min(b) from t1))),13) | t1.b+t1.e in (13,(t1.b),t1.a) then t1.a when a in (select t1.f from t1 union select t1.b from t1) then t1.e else a end)/abs(f))-t1.e from t1 where not exists(select 1 from t1 where not 19 in (select t1.b from t1 union select t1.f from t1) or 13 in (select e from t1 union select e from t1))),f) FROM t1 WHERE NOT (not exists(select 1 from t1 where case when not exists(select 1 from t1 where a<+case c when (abs(t1.b)/abs(e))+t1.b-b-t1.b then (t1.d)*t1.c else t1.d end) then b else 19 end in (select  -count(distinct c)*(max(f)) | ~+case min(t1.a) when cast(avg(c) AS integer) then cast(avg(t1.a) AS integer) | count(distinct t1.d)* -count(distinct t1.e) else ( -count(*)) end |  -cast(avg(t1.d) AS integer)+min(a)*count(distinct b) from t1 union select max(13) from t1)))}
} {}
do_test randexpr-2.2444 {
  db eval {SELECT coalesce((select d-(abs(case when +coalesce((select 19 from t1 where not exists(select 1 from t1 where d & f in (select ~case count(distinct f) when ( -(cast(avg((( -19))) AS integer))) then (count(*)) else count(distinct 17) end*(max(t1.d)) from t1 union select min(b) from t1))),13) & t1.b+t1.e in (13,(t1.b),t1.a) then t1.a when a in (select t1.f from t1 union select t1.b from t1) then t1.e else a end)/abs(f))-t1.e from t1 where not exists(select 1 from t1 where not 19 in (select t1.b from t1 union select t1.f from t1) or 13 in (select e from t1 union select e from t1))),f) FROM t1 WHERE not exists(select 1 from t1 where case when not exists(select 1 from t1 where a<+case c when (abs(t1.b)/abs(e))+t1.b-b-t1.b then (t1.d)*t1.c else t1.d end) then b else 19 end in (select  -count(distinct c)*(max(f)) | ~+case min(t1.a) when cast(avg(c) AS integer) then cast(avg(t1.a) AS integer) | count(distinct t1.d)* -count(distinct t1.e) else ( -count(*)) end |  -cast(avg(t1.d) AS integer)+min(a)*count(distinct b) from t1 union select max(13) from t1))}
} {600}
do_test randexpr-2.2445 {
  db eval {SELECT (t1.e)+t1.c-coalesce((select max((abs(coalesce((select case when f>=(abs(coalesce((select max(a) from t1 where 11*(t1.f)*a*t1.d=11),t1.b))/abs(t1.d))+t1.b then c when not exists(select 1 from t1 where t1.c<>b) then 13 else 11 end from t1 where (13 not in (f,t1.c,13))),b)+t1.d)/abs(t1.f))) from t1 where b<>t1.a),t1.a) | t1.d FROM t1 WHERE ~a<>a or d<>t1.e}
} {927}
do_test randexpr-2.2446 {
  db eval {SELECT (t1.e)+t1.c-coalesce((select max((abs(coalesce((select case when f>=(abs(coalesce((select max(a) from t1 where 11*(t1.f)*a*t1.d=11),t1.b))/abs(t1.d))+t1.b then c when not exists(select 1 from t1 where t1.c<>b) then 13 else 11 end from t1 where (13 not in (f,t1.c,13))),b)+t1.d)/abs(t1.f))) from t1 where b<>t1.a),t1.a) | t1.d FROM t1 WHERE NOT (~a<>a or d<>t1.e)}
} {}
do_test randexpr-2.2447 {
  db eval {SELECT (t1.e)+t1.c-coalesce((select max((abs(coalesce((select case when f>=(abs(coalesce((select max(a) from t1 where 11*(t1.f)*a*t1.d=11),t1.b))/abs(t1.d))+t1.b then c when not exists(select 1 from t1 where t1.c<>b) then 13 else 11 end from t1 where (13 not in (f,t1.c,13))),b)+t1.d)/abs(t1.f))) from t1 where b<>t1.a),t1.a) & t1.d FROM t1 WHERE ~a<>a or d<>t1.e}
} {272}
do_test randexpr-2.2448 {
  db eval {SELECT case when coalesce((select 11 from t1 where exists(select 1 from t1 where t1.a<= -19)),t1.c-t1.e*e-19-t1.d-t1.e-~a*coalesce((select max(b) from t1 where b>(abs(+c+case c when 11 then t1.f else 11 end)/abs(b))),t1.e)-f+t1.c+19+e-t1.e)<=t1.f then e else c end FROM t1 WHERE (abs(t1.d)/abs(~b)) in (select count(distinct case when t1.c+t1.f<coalesce((select b from t1 where ((select case min( -d+d+f+d) when ~max(t1.c) then case max(d) when  -( - -min(d)) then cast(avg(t1.d) AS integer) else (max( -c)) end else cast(avg(t1.e) AS integer) end from t1)<t1.b)),17) or t1.b=f then case when t1.f<>e and ((d) between t1.a and d) then t1.b else 13 end else 11 end) from t1 union select count(*) from t1)}
} {500}
do_test randexpr-2.2449 {
  db eval {SELECT case when coalesce((select 11 from t1 where exists(select 1 from t1 where t1.a<= -19)),t1.c-t1.e*e-19-t1.d-t1.e-~a*coalesce((select max(b) from t1 where b>(abs(+c+case c when 11 then t1.f else 11 end)/abs(b))),t1.e)-f+t1.c+19+e-t1.e)<=t1.f then e else c end FROM t1 WHERE NOT ((abs(t1.d)/abs(~b)) in (select count(distinct case when t1.c+t1.f<coalesce((select b from t1 where ((select case min( -d+d+f+d) when ~max(t1.c) then case max(d) when  -( - -min(d)) then cast(avg(t1.d) AS integer) else (max( -c)) end else cast(avg(t1.e) AS integer) end from t1)<t1.b)),17) or t1.b=f then case when t1.f<>e and ((d) between t1.a and d) then t1.b else 13 end else 11 end) from t1 union select count(*) from t1))}
} {}
do_test randexpr-2.2450 {
  db eval {SELECT case when 19*case when case when t1.e>((t1.d)) and 11>t1.d then  -17 else e end in (select count(distinct a) from t1 union select min(d) from t1) then (d) else e end | t1.c+a in (select count(*) from t1 union select case +(max(19))+count(distinct  -t1.d) when min(19) then cast(avg(e) AS integer) else cast(avg(t1.a) AS integer) end from t1) and 17 between 17 and t1.b then  -(t1.e) when b between t1.c and 13 then b else 11 end+t1.f*(t1.d)+t1.c FROM t1 WHERE ~+e+11>b}
} {}
do_test randexpr-2.2451 {
  db eval {SELECT case when 19*case when case when t1.e>((t1.d)) and 11>t1.d then  -17 else e end in (select count(distinct a) from t1 union select min(d) from t1) then (d) else e end | t1.c+a in (select count(*) from t1 union select case +(max(19))+count(distinct  -t1.d) when min(19) then cast(avg(e) AS integer) else cast(avg(t1.a) AS integer) end from t1) and 17 between 17 and t1.b then  -(t1.e) when b between t1.c and 13 then b else 11 end+t1.f*(t1.d)+t1.c FROM t1 WHERE NOT (~+e+11>b)}
} {240311}
do_test randexpr-2.2452 {
  db eval {SELECT case when 19*case when case when t1.e>((t1.d)) and 11>t1.d then  -17 else e end in (select count(distinct a) from t1 union select min(d) from t1) then (d) else e end & t1.c+a in (select count(*) from t1 union select case +(max(19))+count(distinct  -t1.d) when min(19) then cast(avg(e) AS integer) else cast(avg(t1.a) AS integer) end from t1) and 17 between 17 and t1.b then  -(t1.e) when b between t1.c and 13 then b else 11 end+t1.f*(t1.d)+t1.c FROM t1 WHERE NOT (~+e+11>b)}
} {240311}
do_test randexpr-2.2453 {
  db eval {SELECT coalesce((select max((e)) from t1 where not (((abs(c)/abs((abs(t1.e)/abs(t1.d)))) between d and a+t1.f+19-a or (not exists(select 1 from t1 where f*11 in (19,t1.d,case when (11 in (19,17,19) and t1.a>t1.d) then t1.e-19 else t1.e end+f))) and a<11) and 19<>a)),c+d) FROM t1 WHERE 17+case b*f when b then a+e else d end*t1.b<=case when not f=11 then c when t1.e<f-coalesce((select max(d) from t1 where e in (select (select count(*) from t1) | coalesce((select e from t1 where t1.d>d and exists(select 1 from t1 where 19 in (t1.e,t1.a,(e)))),a)*c from t1 union select f from t1)),t1.a)+f+17 then t1.c else b end}
} {}
do_test randexpr-2.2454 {
  db eval {SELECT coalesce((select max((e)) from t1 where not (((abs(c)/abs((abs(t1.e)/abs(t1.d)))) between d and a+t1.f+19-a or (not exists(select 1 from t1 where f*11 in (19,t1.d,case when (11 in (19,17,19) and t1.a>t1.d) then t1.e-19 else t1.e end+f))) and a<11) and 19<>a)),c+d) FROM t1 WHERE NOT (17+case b*f when b then a+e else d end*t1.b<=case when not f=11 then c when t1.e<f-coalesce((select max(d) from t1 where e in (select (select count(*) from t1) | coalesce((select e from t1 where t1.d>d and exists(select 1 from t1 where 19 in (t1.e,t1.a,(e)))),a)*c from t1 union select f from t1)),t1.a)+f+17 then t1.c else b end)}
} {500}
do_test randexpr-2.2455 {
  db eval {SELECT ((select cast(avg(case a when t1.d then (abs(coalesce((select coalesce((select coalesce((select e-a from t1 where not exists(select 1 from t1 where t1.f>11 or t1.a= -f)), -t1.a) from t1 where 11<= -t1.f),t1.f)-13 from t1 where not exists(select 1 from t1 where t1.e in (f,t1.b,d))),t1.d))/abs(11)) else (17) end) AS integer)+abs( -count(distinct e)+count(*)) |  -count(*)*+min(e)*count(distinct b)*cast(avg(11) AS integer) from t1)) FROM t1 WHERE d= -19}
} {}
do_test randexpr-2.2456 {
  db eval {SELECT ((select cast(avg(case a when t1.d then (abs(coalesce((select coalesce((select coalesce((select e-a from t1 where not exists(select 1 from t1 where t1.f>11 or t1.a= -f)), -t1.a) from t1 where 11<= -t1.f),t1.f)-13 from t1 where not exists(select 1 from t1 where t1.e in (f,t1.b,d))),t1.d))/abs(11)) else (17) end) AS integer)+abs( -count(distinct e)+count(*)) |  -count(*)*+min(e)*count(distinct b)*cast(avg(11) AS integer) from t1)) FROM t1 WHERE NOT (d= -19)}
} {-5483}
do_test randexpr-2.2457 {
  db eval {SELECT ((select cast(avg(case a when t1.d then (abs(coalesce((select coalesce((select coalesce((select e-a from t1 where not exists(select 1 from t1 where t1.f>11 or t1.a= -f)), -t1.a) from t1 where 11<= -t1.f),t1.f)-13 from t1 where not exists(select 1 from t1 where t1.e in (f,t1.b,d))),t1.d))/abs(11)) else (17) end) AS integer)+abs( -count(distinct e)+count(*)) &  -count(*)*+min(e)*count(distinct b)*cast(avg(11) AS integer) from t1)) FROM t1 WHERE NOT (d= -19)}
} {0}
do_test randexpr-2.2458 {
  db eval {SELECT 11+t1.e*c | t1.a+t1.a*coalesce((select max(b*t1.d*case when c in (select t1.b from t1 union select case when (t1.b>=d) then 19 else case when ((((t1.a<>t1.b)))) then b when f<=11 then case when e not in (19,t1.d,a) then coalesce((select 11 from t1 where e between a and e),e) when 11<=e then t1.a else 13 end else t1.c end end from t1) then 19 else (t1.d) end-a) from t1 where (t1.d)<= -e),t1.f) FROM t1 WHERE ((f not between t1.a and (abs(19)/abs(17 | (a))) and ((exists(select 1 from t1 where coalesce((select case e*(17) when b-(abs((abs(11)/abs(t1.c+e+t1.c)))/abs(17-((t1.f-t1.e | 11)))) then e else a end from t1 where t1.c not in (19,t1.b,t1.d)),c)=b)))))}
} {}
do_test randexpr-2.2459 {
  db eval {SELECT 11+t1.e*c | t1.a+t1.a*coalesce((select max(b*t1.d*case when c in (select t1.b from t1 union select case when (t1.b>=d) then 19 else case when ((((t1.a<>t1.b)))) then b when f<=11 then case when e not in (19,t1.d,a) then coalesce((select 11 from t1 where e between a and e),e) when 11<=e then t1.a else 13 end else t1.c end end from t1) then 19 else (t1.d) end-a) from t1 where (t1.d)<= -e),t1.f) FROM t1 WHERE NOT (((f not between t1.a and (abs(19)/abs(17 | (a))) and ((exists(select 1 from t1 where coalesce((select case e*(17) when b-(abs((abs(11)/abs(t1.c+e+t1.c)))/abs(17-((t1.f-t1.e | 11)))) then e else a end from t1 where t1.c not in (19,t1.b,t1.d)),c)=b))))))}
} {191487}
do_test randexpr-2.2460 {
  db eval {SELECT 11+t1.e*c & t1.a+t1.a*coalesce((select max(b*t1.d*case when c in (select t1.b from t1 union select case when (t1.b>=d) then 19 else case when ((((t1.a<>t1.b)))) then b when f<=11 then case when e not in (19,t1.d,a) then coalesce((select 11 from t1 where e between a and e),e) when 11<=e then t1.a else 13 end else t1.c end end from t1) then 19 else (t1.d) end-a) from t1 where (t1.d)<= -e),t1.f) FROM t1 WHERE NOT (((f not between t1.a and (abs(19)/abs(17 | (a))) and ((exists(select 1 from t1 where coalesce((select case e*(17) when b-(abs((abs(11)/abs(t1.c+e+t1.c)))/abs(17-((t1.f-t1.e | 11)))) then e else a end from t1 where t1.c not in (19,t1.b,t1.d)),c)=b))))))}
} {18624}
do_test randexpr-2.2461 {
  db eval {SELECT (select (case +~ -abs(count(distinct + -(select (case ~((min(t1.b)+max(a))+count(*))*cast(avg(e) AS integer) when count(distinct (17)) then count(distinct t1.d) else max(a) end) from t1)*(17)-t1.f+case (abs( -t1.e)/abs(17)) when t1.f then b else 11 end)) | max(c)-case max(f) when (max(t1.f)) then min(c) else cast(avg((t1.d)) AS integer) end when count(*) then min(t1.a) else cast(avg(t1.c) AS integer) end) from t1) FROM t1 WHERE 13 in ((select ~ -abs((abs( -max(c)+count(distinct c)-~case +max(f) when min(13) then count(distinct t1.e) else count(*) end-((cast(avg(t1.c) AS integer)))))) from t1),~t1.c-t1.e,case when exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (select case when t1.c<d or e>a then b else (c) end+t1.d from t1 union select  -t1.e from t1)) or 11 not between b and d or e>e) then t1.f else t1.f end*t1.b- -t1.b)}
} {}
do_test randexpr-2.2462 {
  db eval {SELECT (select (case +~ -abs(count(distinct + -(select (case ~((min(t1.b)+max(a))+count(*))*cast(avg(e) AS integer) when count(distinct (17)) then count(distinct t1.d) else max(a) end) from t1)*(17)-t1.f+case (abs( -t1.e)/abs(17)) when t1.f then b else 11 end)) | max(c)-case max(f) when (max(t1.f)) then min(c) else cast(avg((t1.d)) AS integer) end when count(*) then min(t1.a) else cast(avg(t1.c) AS integer) end) from t1) FROM t1 WHERE NOT (13 in ((select ~ -abs((abs( -max(c)+count(distinct c)-~case +max(f) when min(13) then count(distinct t1.e) else count(*) end-((cast(avg(t1.c) AS integer)))))) from t1),~t1.c-t1.e,case when exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (select case when t1.c<d or e>a then b else (c) end+t1.d from t1 union select  -t1.e from t1)) or 11 not between b and d or e>e) then t1.f else t1.f end*t1.b- -t1.b))}
} {300}
do_test randexpr-2.2463 {
  db eval {SELECT (select (case +~ -abs(count(distinct + -(select (case ~((min(t1.b)+max(a))+count(*))*cast(avg(e) AS integer) when count(distinct (17)) then count(distinct t1.d) else max(a) end) from t1)*(17)-t1.f+case (abs( -t1.e)/abs(17)) when t1.f then b else 11 end)) & max(c)-case max(f) when (max(t1.f)) then min(c) else cast(avg((t1.d)) AS integer) end when count(*) then min(t1.a) else cast(avg(t1.c) AS integer) end) from t1) FROM t1 WHERE NOT (13 in ((select ~ -abs((abs( -max(c)+count(distinct c)-~case +max(f) when min(13) then count(distinct t1.e) else count(*) end-((cast(avg(t1.c) AS integer)))))) from t1),~t1.c-t1.e,case when exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (select case when t1.c<d or e>a then b else (c) end+t1.d from t1 union select  -t1.e from t1)) or 11 not between b and d or e>e) then t1.f else t1.f end*t1.b- -t1.b))}
} {300}
do_test randexpr-2.2464 {
  db eval {SELECT case when (abs(~(t1.e))/abs(case when (( -13<d or b not in (t1.d,a,19)) and t1.b<d) or a<13 then +~c else 17 end)) in (select cast(avg(t1.b |  -t1.f) AS integer)- - -case (~min(t1.e)+count(*)) when  -max(13) then max(t1.c) else  -cast(avg(11) AS integer) end from t1 union select cast(avg(11) AS integer) from t1) then t1.e when not exists(select 1 from t1 where (19 not between d and 13)) then 19 else c end-t1.c FROM t1 WHERE  -t1.a-+case when c between b and t1.a then 19 else t1.b end | (coalesce((select t1.f from t1 where case ~((abs(case case t1.e when t1.b then  -13 else f end when t1.a then t1.f else t1.b end+(e)-t1.b)/abs(c))+t1.d) when 19 then 11 else a end not in ( - -13,a,11)),b))+t1.b+e in (select t1.d from t1 union select d from t1)}
} {}
do_test randexpr-2.2465 {
  db eval {SELECT case when (abs(~(t1.e))/abs(case when (( -13<d or b not in (t1.d,a,19)) and t1.b<d) or a<13 then +~c else 17 end)) in (select cast(avg(t1.b |  -t1.f) AS integer)- - -case (~min(t1.e)+count(*)) when  -max(13) then max(t1.c) else  -cast(avg(11) AS integer) end from t1 union select cast(avg(11) AS integer) from t1) then t1.e when not exists(select 1 from t1 where (19 not between d and 13)) then 19 else c end-t1.c FROM t1 WHERE NOT ( -t1.a-+case when c between b and t1.a then 19 else t1.b end | (coalesce((select t1.f from t1 where case ~((abs(case case t1.e when t1.b then  -13 else f end when t1.a then t1.f else t1.b end+(e)-t1.b)/abs(c))+t1.d) when 19 then 11 else a end not in ( - -13,a,11)),b))+t1.b+e in (select t1.d from t1 union select d from t1))}
} {0}
do_test randexpr-2.2466 {
  db eval {SELECT case when (abs(~(t1.e))/abs(case when (( -13<d or b not in (t1.d,a,19)) and t1.b<d) or a<13 then +~c else 17 end)) in (select cast(avg(t1.b &  -t1.f) AS integer)- - -case (~min(t1.e)+count(*)) when  -max(13) then max(t1.c) else  -cast(avg(11) AS integer) end from t1 union select cast(avg(11) AS integer) from t1) then t1.e when not exists(select 1 from t1 where (19 not between d and 13)) then 19 else c end-t1.c FROM t1 WHERE NOT ( -t1.a-+case when c between b and t1.a then 19 else t1.b end | (coalesce((select t1.f from t1 where case ~((abs(case case t1.e when t1.b then  -13 else f end when t1.a then t1.f else t1.b end+(e)-t1.b)/abs(c))+t1.d) when 19 then 11 else a end not in ( - -13,a,11)),b))+t1.b+e in (select t1.d from t1 union select d from t1))}
} {0}
do_test randexpr-2.2467 {
  db eval {SELECT case when (select  -case abs(min(c)) when count(distinct a)-min(t1.c) then  -~abs(max(c)) | min( -13) |  -count(*)+min(d)*count(*) else  -(count(distinct t1.f)) end from t1) in (select count(distinct b)+max(f) from t1 union select cast(avg(19) AS integer) from t1) then (t1.d) when b<=case d when t1.d then t1.a else t1.d end then coalesce((select t1.d from t1 where not exists(select 1 from t1 where t1.a not in (11,e,13))),13) else 17 end FROM t1 WHERE t1.f in (select count(*)-max(case f+(abs(e-17*(abs(11+17+e)/abs(f)) | t1.e*b+t1.d)/abs(e))+t1.a when t1.a then  -t1.d else 13 end) | abs( -cast(avg(b) AS integer)-count(distinct 13) | (count(*))+count(*))-cast(avg(((a))) AS integer) from t1 union select count(distinct 11) from t1)}
} {}
do_test randexpr-2.2468 {
  db eval {SELECT case when (select  -case abs(min(c)) when count(distinct a)-min(t1.c) then  -~abs(max(c)) | min( -13) |  -count(*)+min(d)*count(*) else  -(count(distinct t1.f)) end from t1) in (select count(distinct b)+max(f) from t1 union select cast(avg(19) AS integer) from t1) then (t1.d) when b<=case d when t1.d then t1.a else t1.d end then coalesce((select t1.d from t1 where not exists(select 1 from t1 where t1.a not in (11,e,13))),13) else 17 end FROM t1 WHERE NOT (t1.f in (select count(*)-max(case f+(abs(e-17*(abs(11+17+e)/abs(f)) | t1.e*b+t1.d)/abs(e))+t1.a when t1.a then  -t1.d else 13 end) | abs( -cast(avg(b) AS integer)-count(distinct 13) | (count(*))+count(*))-cast(avg(((a))) AS integer) from t1 union select count(distinct 11) from t1))}
} {17}
do_test randexpr-2.2469 {
  db eval {SELECT case when (select  -case abs(min(c)) when count(distinct a)-min(t1.c) then  -~abs(max(c)) & min( -13) &  -count(*)+min(d)*count(*) else  -(count(distinct t1.f)) end from t1) in (select count(distinct b)+max(f) from t1 union select cast(avg(19) AS integer) from t1) then (t1.d) when b<=case d when t1.d then t1.a else t1.d end then coalesce((select t1.d from t1 where not exists(select 1 from t1 where t1.a not in (11,e,13))),13) else 17 end FROM t1 WHERE NOT (t1.f in (select count(*)-max(case f+(abs(e-17*(abs(11+17+e)/abs(f)) | t1.e*b+t1.d)/abs(e))+t1.a when t1.a then  -t1.d else 13 end) | abs( -cast(avg(b) AS integer)-count(distinct 13) | (count(*))+count(*))-cast(avg(((a))) AS integer) from t1 union select count(distinct 11) from t1))}
} {17}
do_test randexpr-2.2470 {
  db eval {SELECT (select min(coalesce((select max(t1.c-case t1.e | (abs(coalesce((select max(t1.b) from t1 where 19<f-13 or exists(select 1 from t1 where  -case coalesce((select max( -17-19) from t1 where (e>c)),f)+t1.b when 13 then t1.c else t1.b end<>a) or t1.a=a),e+t1.e))/abs((f))) when a then e else f end) from t1 where t1.a>t1.d),19)) from t1) FROM t1 WHERE 19*~case when (case when t1.f<>t1.a*17*(abs(t1.e)/abs(a))*a*(select case +min(11)*cast(avg(b) AS integer)*cast(avg(19) AS integer) when count(distinct t1.f) then max( -t1.e) else cast(avg( -f) AS integer) end from t1)*(select min(t1.b) from t1)*t1.d then coalesce((select max(11) from t1 where t1.a between t1.d and 17 and 19 not between 17 and a),17) else 17 end in (select t1.f from t1 union select 17 from t1)) then ~t1.b else t1.d end<=b}
} {}
do_test randexpr-2.2471 {
  db eval {SELECT (select min(coalesce((select max(t1.c-case t1.e | (abs(coalesce((select max(t1.b) from t1 where 19<f-13 or exists(select 1 from t1 where  -case coalesce((select max( -17-19) from t1 where (e>c)),f)+t1.b when 13 then t1.c else t1.b end<>a) or t1.a=a),e+t1.e))/abs((f))) when a then e else f end) from t1 where t1.a>t1.d),19)) from t1) FROM t1 WHERE NOT (19*~case when (case when t1.f<>t1.a*17*(abs(t1.e)/abs(a))*a*(select case +min(11)*cast(avg(b) AS integer)*cast(avg(19) AS integer) when count(distinct t1.f) then max( -t1.e) else cast(avg( -f) AS integer) end from t1)*(select min(t1.b) from t1)*t1.d then coalesce((select max(11) from t1 where t1.a between t1.d and 17 and 19 not between 17 and a),17) else 17 end in (select t1.f from t1 union select 17 from t1)) then ~t1.b else t1.d end<=b)}
} {19}
do_test randexpr-2.2472 {
  db eval {SELECT (select min(coalesce((select max(t1.c-case t1.e & (abs(coalesce((select max(t1.b) from t1 where 19<f-13 or exists(select 1 from t1 where  -case coalesce((select max( -17-19) from t1 where (e>c)),f)+t1.b when 13 then t1.c else t1.b end<>a) or t1.a=a),e+t1.e))/abs((f))) when a then e else f end) from t1 where t1.a>t1.d),19)) from t1) FROM t1 WHERE NOT (19*~case when (case when t1.f<>t1.a*17*(abs(t1.e)/abs(a))*a*(select case +min(11)*cast(avg(b) AS integer)*cast(avg(19) AS integer) when count(distinct t1.f) then max( -t1.e) else cast(avg( -f) AS integer) end from t1)*(select min(t1.b) from t1)*t1.d then coalesce((select max(11) from t1 where t1.a between t1.d and 17 and 19 not between 17 and a),17) else 17 end in (select t1.f from t1 union select 17 from t1)) then ~t1.b else t1.d end<=b)}
} {19}
do_test randexpr-2.2473 {
  db eval {SELECT  -case (select ~count(*)-~abs(~ -(count(*)+count(*)))*count(*) from t1)*13++coalesce((select max( -+17+case when f not between e and t1.c and t1.f between t1.e and t1.a then e when (b)>19 then f else t1.b end) from t1 where 17 not in (a,t1.f,17) or (d>=t1.e) or a<=17),d) when t1.c then 19 else t1.f end FROM t1 WHERE (19<+case when not 17>e then +t1.f when e | 13 in (select ~(abs(a)/abs(t1.b)) from t1 union select t1.f from t1) then case when f between case case b*f+19-case t1.c when f then 13 else c end when t1.d then b else b end*11 when 19 then 13 else t1.c end and t1.f then c when t1.b<=c then t1.d else 13 end else t1.d end)}
} {-600}
do_test randexpr-2.2474 {
  db eval {SELECT  -case (select ~count(*)-~abs(~ -(count(*)+count(*)))*count(*) from t1)*13++coalesce((select max( -+17+case when f not between e and t1.c and t1.f between t1.e and t1.a then e when (b)>19 then f else t1.b end) from t1 where 17 not in (a,t1.f,17) or (d>=t1.e) or a<=17),d) when t1.c then 19 else t1.f end FROM t1 WHERE NOT ((19<+case when not 17>e then +t1.f when e | 13 in (select ~(abs(a)/abs(t1.b)) from t1 union select t1.f from t1) then case when f between case case b*f+19-case t1.c when f then 13 else c end when t1.d then b else b end*11 when 19 then 13 else t1.c end and t1.f then c when t1.b<=c then t1.d else 13 end else t1.d end))}
} {}
do_test randexpr-2.2475 {
  db eval {SELECT case when e not in (t1.a,t1.b,t1.e-t1.a) then f-coalesce((select max(~19-t1.b-f) from t1 where case when (select count(*)*count(*) from t1)-coalesce((select max(13) from t1 where (abs(13)/abs(19-f)) in (select count(distinct f) from t1 union select ~ - -count(distinct  -f) from t1)),t1.b) between t1.f and t1.d then d else f end between t1.f and a),t1.f)+ -t1.f else t1.e end FROM t1 WHERE d not in (c,t1.d, -coalesce((select max( -coalesce((select f from t1 where t1.b>t1.c* - -t1.f),case when (t1.e-t1.e | 19*t1.c+e<19 and 19<=e or not exists(select 1 from t1 where t1.a<=t1.d or e in (a,t1.e,b))) then  -e when f in ((t1.a),d,11) then 13 else d end)) from t1 where c between 19 and f),b))}
} {}
do_test randexpr-2.2476 {
  db eval {SELECT case when e not in (t1.a,t1.b,t1.e-t1.a) then f-coalesce((select max(~19-t1.b-f) from t1 where case when (select count(*)*count(*) from t1)-coalesce((select max(13) from t1 where (abs(13)/abs(19-f)) in (select count(distinct f) from t1 union select ~ - -count(distinct  -f) from t1)),t1.b) between t1.f and t1.d then d else f end between t1.f and a),t1.f)+ -t1.f else t1.e end FROM t1 WHERE NOT (d not in (c,t1.d, -coalesce((select max( -coalesce((select f from t1 where t1.b>t1.c* - -t1.f),case when (t1.e-t1.e | 19*t1.c+e<19 and 19<=e or not exists(select 1 from t1 where t1.a<=t1.d or e in (a,t1.e,b))) then  -e when f in ((t1.a),d,11) then 13 else d end)) from t1 where c between 19 and f),b)))}
} {-600}
do_test randexpr-2.2477 {
  db eval {SELECT  -case when (17<>t1.b-d+t1.a | t1.f) then ~c when ((19)-coalesce((select case t1.d-t1.f when (abs(((select abs(cast(avg(13) AS integer) | cast(avg( -(t1.b)) AS integer)) from t1)))/abs(case d when t1.b then  -11 else 19 end))*17 then t1.e else t1.a end from t1 where (19 not in (f,t1.d,t1.e))),t1.d)<>a) then t1.d else t1.c end FROM t1 WHERE a in (~b-t1.f*c,13 | coalesce((select max(t1.a) from t1 where  -t1.a-~case when b in (case when t1.e in (select 11 from t1 union select d from t1) and 13>19 then 13*c when f not in (t1.d,c,13) then t1.a else a end,t1.f,d) then a else 11 end+b in (select +(min(11)) from t1 union select max(11)+cast(avg(19) AS integer) from t1)),13),t1.f)}
} {}
do_test randexpr-2.2478 {
  db eval {SELECT  -case when (17<>t1.b-d+t1.a | t1.f) then ~c when ((19)-coalesce((select case t1.d-t1.f when (abs(((select abs(cast(avg(13) AS integer) | cast(avg( -(t1.b)) AS integer)) from t1)))/abs(case d when t1.b then  -11 else 19 end))*17 then t1.e else t1.a end from t1 where (19 not in (f,t1.d,t1.e))),t1.d)<>a) then t1.d else t1.c end FROM t1 WHERE NOT (a in (~b-t1.f*c,13 | coalesce((select max(t1.a) from t1 where  -t1.a-~case when b in (case when t1.e in (select 11 from t1 union select d from t1) and 13>19 then 13*c when f not in (t1.d,c,13) then t1.a else a end,t1.f,d) then a else 11 end+b in (select +(min(11)) from t1 union select max(11)+cast(avg(19) AS integer) from t1)),13),t1.f))}
} {301}
do_test randexpr-2.2479 {
  db eval {SELECT  -case when (17<>t1.b-d+t1.a & t1.f) then ~c when ((19)-coalesce((select case t1.d-t1.f when (abs(((select abs(cast(avg(13) AS integer) & cast(avg( -(t1.b)) AS integer)) from t1)))/abs(case d when t1.b then  -11 else 19 end))*17 then t1.e else t1.a end from t1 where (19 not in (f,t1.d,t1.e))),t1.d)<>a) then t1.d else t1.c end FROM t1 WHERE NOT (a in (~b-t1.f*c,13 | coalesce((select max(t1.a) from t1 where  -t1.a-~case when b in (case when t1.e in (select 11 from t1 union select d from t1) and 13>19 then 13*c when f not in (t1.d,c,13) then t1.a else a end,t1.f,d) then a else 11 end+b in (select +(min(11)) from t1 union select max(11)+cast(avg(19) AS integer) from t1)),13),t1.f))}
} {301}
do_test randexpr-2.2480 {
  db eval {SELECT case f when case when +t1.a between a and case e when 17 then t1.e else f-t1.e+a-((select ++count(distinct d) | cast(avg(t1.e) AS integer)+count(distinct e) |  -count(*) from t1)) end-t1.b*f and t1.b | t1.b-b<=c then  -t1.b+d when 11 in (select t1.e from t1 union select 11 from t1) then 13 else a end then b else c end FROM t1 WHERE case when ++c-13*d>t1.a and f=t1.d-t1.b then (select count(distinct 11)*(+cast(avg(t1.b) AS integer)+case cast(avg(e) AS integer) when max(d) | min(11) then min(f) else ( -min(t1.b)) end*(count(*)))* -min(19) from t1) else t1.e end*11 in (select a from t1 union select t1.e from t1) and e=17 or 11 not in ( -t1.d,f,t1.f)}
} {300}
do_test randexpr-2.2481 {
  db eval {SELECT case f when case when +t1.a between a and case e when 17 then t1.e else f-t1.e+a-((select ++count(distinct d) | cast(avg(t1.e) AS integer)+count(distinct e) |  -count(*) from t1)) end-t1.b*f and t1.b | t1.b-b<=c then  -t1.b+d when 11 in (select t1.e from t1 union select 11 from t1) then 13 else a end then b else c end FROM t1 WHERE NOT (case when ++c-13*d>t1.a and f=t1.d-t1.b then (select count(distinct 11)*(+cast(avg(t1.b) AS integer)+case cast(avg(e) AS integer) when max(d) | min(11) then min(f) else ( -min(t1.b)) end*(count(*)))* -min(19) from t1) else t1.e end*11 in (select a from t1 union select t1.e from t1) and e=17 or 11 not in ( -t1.d,f,t1.f))}
} {}
do_test randexpr-2.2482 {
  db eval {SELECT case f when case when +t1.a between a and case e when 17 then t1.e else f-t1.e+a-((select ++count(distinct d) & cast(avg(t1.e) AS integer)+count(distinct e) &  -count(*) from t1)) end-t1.b*f and t1.b & t1.b-b<=c then  -t1.b+d when 11 in (select t1.e from t1 union select 11 from t1) then 13 else a end then b else c end FROM t1 WHERE case when ++c-13*d>t1.a and f=t1.d-t1.b then (select count(distinct 11)*(+cast(avg(t1.b) AS integer)+case cast(avg(e) AS integer) when max(d) | min(11) then min(f) else ( -min(t1.b)) end*(count(*)))* -min(19) from t1) else t1.e end*11 in (select a from t1 union select t1.e from t1) and e=17 or 11 not in ( -t1.d,f,t1.f)}
} {300}
do_test randexpr-2.2483 {
  db eval {SELECT  -(19)-coalesce((select max(t1.e) from t1 where c not in (t1.b,17,t1.c)),case coalesce((select b+f+coalesce((select t1.a from t1 where t1.e>=t1.e+t1.a+t1.c or t1.f between c and t1.f),t1.e) from t1 where 11<>13 or t1.a=b),t1.c)*f+a when a then 17 else 17 end+t1.e)+a FROM t1 WHERE e | a not between  -case when not c between case when exists(select 1 from t1 where (f not in (coalesce((select max(t1.d) from t1 where t1.e=t1.d),t1.e)+a,19,t1.c)) or not exists(select 1 from t1 where a in (19,a,e) and 11>=t1.f)) or 11<17 then t1.e+19*t1.f-b when t1.c in (e,t1.b,e) then f else t1.f end and t1.b or (11>=(t1.a)) then e when t1.a=t1.a then (select count(*) from t1) else e end and t1.b}
} {-436}
do_test randexpr-2.2484 {
  db eval {SELECT  -(19)-coalesce((select max(t1.e) from t1 where c not in (t1.b,17,t1.c)),case coalesce((select b+f+coalesce((select t1.a from t1 where t1.e>=t1.e+t1.a+t1.c or t1.f between c and t1.f),t1.e) from t1 where 11<>13 or t1.a=b),t1.c)*f+a when a then 17 else 17 end+t1.e)+a FROM t1 WHERE NOT (e | a not between  -case when not c between case when exists(select 1 from t1 where (f not in (coalesce((select max(t1.d) from t1 where t1.e=t1.d),t1.e)+a,19,t1.c)) or not exists(select 1 from t1 where a in (19,a,e) and 11>=t1.f)) or 11<17 then t1.e+19*t1.f-b when t1.c in (e,t1.b,e) then f else t1.f end and t1.b or (11>=(t1.a)) then e when t1.a=t1.a then (select count(*) from t1) else e end and t1.b)}
} {}
do_test randexpr-2.2485 {
  db eval {SELECT case (abs(case when 13 not in (t1.f,a,t1.b) then d*(abs((coalesce((select coalesce((select coalesce((select max(t1.d-t1.a) from t1 where (t1.c between 19 and (c) and c<t1.c)),17) from t1 where (11>=17)),t1.f) from t1 where t1.e between e and 17),17))-b)/abs(d)) | b+t1.b when e between t1.f and d then 19 else 17 end*f)/abs(a)) when t1.c then 11 else t1.d end FROM t1 WHERE d>=e}
} {}
do_test randexpr-2.2486 {
  db eval {SELECT case (abs(case when 13 not in (t1.f,a,t1.b) then d*(abs((coalesce((select coalesce((select coalesce((select max(t1.d-t1.a) from t1 where (t1.c between 19 and (c) and c<t1.c)),17) from t1 where (11>=17)),t1.f) from t1 where t1.e between e and 17),17))-b)/abs(d)) | b+t1.b when e between t1.f and d then 19 else 17 end*f)/abs(a)) when t1.c then 11 else t1.d end FROM t1 WHERE NOT (d>=e)}
} {400}
do_test randexpr-2.2487 {
  db eval {SELECT case (abs(case when 13 not in (t1.f,a,t1.b) then d*(abs((coalesce((select coalesce((select coalesce((select max(t1.d-t1.a) from t1 where (t1.c between 19 and (c) and c<t1.c)),17) from t1 where (11>=17)),t1.f) from t1 where t1.e between e and 17),17))-b)/abs(d)) & b+t1.b when e between t1.f and d then 19 else 17 end*f)/abs(a)) when t1.c then 11 else t1.d end FROM t1 WHERE NOT (d>=e)}
} {400}
do_test randexpr-2.2488 {
  db eval {SELECT case ((abs(case when case  -(select count(distinct case when t1.d in (select t1.b from t1 union select t1.b from t1) then b when f not in (t1.a,b,a) then c else 17 end) | cast(avg(d) AS integer) | min(b) from t1) | +b-e when t1.e then f else a end not between 11 and 13 then f when 17>e and 17<c or exists(select 1 from t1 where b>=t1.f) or d in ( -t1.c,f,t1.a) then  -a else t1.f end)/abs(t1.b))) when 17 then t1.f else t1.f end FROM t1 WHERE t1.d=t1.b+case c-11+coalesce((select case when +(select +(case max(t1.e) when count(*) then (count(*)) else cast(avg(d) AS integer) end) from t1)-d between b and t1.d then 11 else f end from t1 where t1.f<=t1.c and exists(select 1 from t1 where exists(select 1 from t1 where e between t1.e and t1.e))),t1.b)-19 when t1.d then t1.f else (t1.f) end | e-c or t1.f not in (b, -f, -f)}
} {600}
do_test randexpr-2.2489 {
  db eval {SELECT case ((abs(case when case  -(select count(distinct case when t1.d in (select t1.b from t1 union select t1.b from t1) then b when f not in (t1.a,b,a) then c else 17 end) | cast(avg(d) AS integer) | min(b) from t1) | +b-e when t1.e then f else a end not between 11 and 13 then f when 17>e and 17<c or exists(select 1 from t1 where b>=t1.f) or d in ( -t1.c,f,t1.a) then  -a else t1.f end)/abs(t1.b))) when 17 then t1.f else t1.f end FROM t1 WHERE NOT (t1.d=t1.b+case c-11+coalesce((select case when +(select +(case max(t1.e) when count(*) then (count(*)) else cast(avg(d) AS integer) end) from t1)-d between b and t1.d then 11 else f end from t1 where t1.f<=t1.c and exists(select 1 from t1 where exists(select 1 from t1 where e between t1.e and t1.e))),t1.b)-19 when t1.d then t1.f else (t1.f) end | e-c or t1.f not in (b, -f, -f))}
} {}
do_test randexpr-2.2490 {
  db eval {SELECT case ((abs(case when case  -(select count(distinct case when t1.d in (select t1.b from t1 union select t1.b from t1) then b when f not in (t1.a,b,a) then c else 17 end) & cast(avg(d) AS integer) & min(b) from t1) & +b-e when t1.e then f else a end not between 11 and 13 then f when 17>e and 17<c or exists(select 1 from t1 where b>=t1.f) or d in ( -t1.c,f,t1.a) then  -a else t1.f end)/abs(t1.b))) when 17 then t1.f else t1.f end FROM t1 WHERE t1.d=t1.b+case c-11+coalesce((select case when +(select +(case max(t1.e) when count(*) then (count(*)) else cast(avg(d) AS integer) end) from t1)-d between b and t1.d then 11 else f end from t1 where t1.f<=t1.c and exists(select 1 from t1 where exists(select 1 from t1 where e between t1.e and t1.e))),t1.b)-19 when t1.d then t1.f else (t1.f) end | e-c or t1.f not in (b, -f, -f)}
} {600}
do_test randexpr-2.2491 {
  db eval {SELECT coalesce((select max(11) from t1 where 17 not in (11,case when (case when t1.f>b then t1.d*t1.d else (abs((abs(19)/abs(coalesce((select 17*t1.e-t1.c from t1 where 17<13 and (t1.a in (select (min(17)) from t1 union select max(c) from t1) and  -t1.d not in ((t1.b),d,a))), -17))))/abs(c))*13 end)<>(t1.f) then a when a=t1.a then 17 else  -19 end-d,a)),e) FROM t1 WHERE 19<=case when not exists(select 1 from t1 where case when case when case when ((t1.a in (select +min(t1.c) from t1 union select max(t1.a) from t1))) or 19 between t1.d and b then +c | 11*f else d end<b and 17 not in (t1.b,t1.e,t1.c) then case when f=t1.b then t1.c when d between t1.c and t1.c then 17 else 19 end else t1.d end<>b then c else t1.d end in (17,( -b),t1.c)) then t1.e when t1.f in (t1.a,13,d) then 17 else t1.f end*11*t1.d and a<=t1.d}
} {11}
do_test randexpr-2.2492 {
  db eval {SELECT coalesce((select max(11) from t1 where 17 not in (11,case when (case when t1.f>b then t1.d*t1.d else (abs((abs(19)/abs(coalesce((select 17*t1.e-t1.c from t1 where 17<13 and (t1.a in (select (min(17)) from t1 union select max(c) from t1) and  -t1.d not in ((t1.b),d,a))), -17))))/abs(c))*13 end)<>(t1.f) then a when a=t1.a then 17 else  -19 end-d,a)),e) FROM t1 WHERE NOT (19<=case when not exists(select 1 from t1 where case when case when case when ((t1.a in (select +min(t1.c) from t1 union select max(t1.a) from t1))) or 19 between t1.d and b then +c | 11*f else d end<b and 17 not in (t1.b,t1.e,t1.c) then case when f=t1.b then t1.c when d between t1.c and t1.c then 17 else 19 end else t1.d end<>b then c else t1.d end in (17,( -b),t1.c)) then t1.e when t1.f in (t1.a,13,d) then 17 else t1.f end*11*t1.d and a<=t1.d)}
} {}
do_test randexpr-2.2493 {
  db eval {SELECT b*case when t1.f not in (a,f,t1.e-e) and t1.b in (select coalesce((select max(t1.e) from t1 where coalesce((select max(~d) from t1 where case when t1.b not in (t1.c,17, -c) then t1.f when t1.c>17 then 17 else e end>t1.f and t1.f not in (b,f,d)),17)>=t1.c or 19<=t1.e),t1.a) from t1 union select (e) from t1) then d when t1.c<e then  -t1.b else b end*c FROM t1 WHERE b not between 13 and d}
} {}
do_test randexpr-2.2494 {
  db eval {SELECT b*case when t1.f not in (a,f,t1.e-e) and t1.b in (select coalesce((select max(t1.e) from t1 where coalesce((select max(~d) from t1 where case when t1.b not in (t1.c,17, -c) then t1.f when t1.c>17 then 17 else e end>t1.f and t1.f not in (b,f,d)),17)>=t1.c or 19<=t1.e),t1.a) from t1 union select (e) from t1) then d when t1.c<e then  -t1.b else b end*c FROM t1 WHERE NOT (b not between 13 and d)}
} {-12000000}
do_test randexpr-2.2495 {
  db eval {SELECT +(select ~(~cast(avg(t1.c) AS integer)* -cast(avg(c) AS integer))-case min(t1.e) when case count(*)*~(count(*)-+count(*)*cast(avg(case t1.d when 19 then d else (t1.a) end*e) AS integer) | cast(avg(13) AS integer)-cast(avg( -11) AS integer)+max(b)+cast(avg(19) AS integer) | (max(t1.e))) | min(f) when  -max(19) then (count(distinct  -t1.a)) else (count(distinct 17)) end then max(t1.d) else cast(avg(t1.e) AS integer) end from t1) FROM t1 WHERE t1.c-case f when 17 | b then case +case f | case when +t1.a>c and e in (select +max(17) from t1 union select count(*) from t1) then (abs( -c)/abs(a)) when b>=t1.f then t1.b else 11 end when t1.f then 17 else t1.d end*(c)+17 when e then c else t1.f end else  -c end-t1.c-c-19+c+a not in (t1.a,13,e)}
} {-90801}
do_test randexpr-2.2496 {
  db eval {SELECT +(select ~(~cast(avg(t1.c) AS integer)* -cast(avg(c) AS integer))-case min(t1.e) when case count(*)*~(count(*)-+count(*)*cast(avg(case t1.d when 19 then d else (t1.a) end*e) AS integer) | cast(avg(13) AS integer)-cast(avg( -11) AS integer)+max(b)+cast(avg(19) AS integer) | (max(t1.e))) | min(f) when  -max(19) then (count(distinct  -t1.a)) else (count(distinct 17)) end then max(t1.d) else cast(avg(t1.e) AS integer) end from t1) FROM t1 WHERE NOT (t1.c-case f when 17 | b then case +case f | case when +t1.a>c and e in (select +max(17) from t1 union select count(*) from t1) then (abs( -c)/abs(a)) when b>=t1.f then t1.b else 11 end when t1.f then 17 else t1.d end*(c)+17 when e then c else t1.f end else  -c end-t1.c-c-19+c+a not in (t1.a,13,e))}
} {}
do_test randexpr-2.2497 {
  db eval {SELECT +(select ~(~cast(avg(t1.c) AS integer)* -cast(avg(c) AS integer))-case min(t1.e) when case count(*)*~(count(*)-+count(*)*cast(avg(case t1.d when 19 then d else (t1.a) end*e) AS integer) & cast(avg(13) AS integer)-cast(avg( -11) AS integer)+max(b)+cast(avg(19) AS integer) & (max(t1.e))) & min(f) when  -max(19) then (count(distinct  -t1.a)) else (count(distinct 17)) end then max(t1.d) else cast(avg(t1.e) AS integer) end from t1) FROM t1 WHERE t1.c-case f when 17 | b then case +case f | case when +t1.a>c and e in (select +max(17) from t1 union select count(*) from t1) then (abs( -c)/abs(a)) when b>=t1.f then t1.b else 11 end when t1.f then 17 else t1.d end*(c)+17 when e then c else t1.f end else  -c end-t1.c-c-19+c+a not in (t1.a,13,e)}
} {-90801}
do_test randexpr-2.2498 {
  db eval {SELECT case t1.d when e then t1.d else (abs(e-b)/abs(t1.c+a*a | 17+19*coalesce((select 17 from t1 where 11 between +(select abs(+cast(avg(13) AS integer)) from t1)*19 and t1.e),t1.e-11-t1.e+( -t1.e*13)*t1.e | e*t1.b)*f)) end FROM t1 WHERE (abs(t1.d)/abs(t1.c)) not between +13 and t1.c}
} {0}
do_test randexpr-2.2499 {
  db eval {SELECT case t1.d when e then t1.d else (abs(e-b)/abs(t1.c+a*a | 17+19*coalesce((select 17 from t1 where 11 between +(select abs(+cast(avg(13) AS integer)) from t1)*19 and t1.e),t1.e-11-t1.e+( -t1.e*13)*t1.e | e*t1.b)*f)) end FROM t1 WHERE NOT ((abs(t1.d)/abs(t1.c)) not between +13 and t1.c)}
} {}
do_test randexpr-2.2500 {
  db eval {SELECT case t1.d when e then t1.d else (abs(e-b)/abs(t1.c+a*a & 17+19*coalesce((select 17 from t1 where 11 between +(select abs(+cast(avg(13) AS integer)) from t1)*19 and t1.e),t1.e-11-t1.e+( -t1.e*13)*t1.e & e*t1.b)*f)) end FROM t1 WHERE (abs(t1.d)/abs(t1.c)) not between +13 and t1.c}
} {18}
do_test randexpr-2.2501 {
  db eval {SELECT coalesce((select coalesce((select t1.e from t1 where case when c+a in (select t1.f from t1 union select 13 from t1) then c when not not exists(select 1 from t1 where d>= -11) then t1.d else  -t1.f end between b and 11 or d not between e and 11), -f)+e+ -11*17 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where t1.e in (select ~min(e) from t1 union select case case count(distinct f) | min(19)+min(a) when count(*) then max( -t1.c) else max(17) end when (max(t1.c)) then min(11) else min(t1.c) end from t1)) or d=a)),t1.e) FROM t1 WHERE +t1.e<~case when t1.e in (select (abs(c)/abs(~t1.d)) from t1 union select a from t1) then coalesce((select e from t1 where t1.d+ -coalesce((select max(11-t1.e*b) from t1 where 19 in (11,t1.b,e)),11)*t1.e+19 in (select t1.d from t1 union select  -t1.d from t1)),17) | t1.e+e when t1.f in (17,f,f) then t1.b else 17 end*13}
} {}
do_test randexpr-2.2502 {
  db eval {SELECT coalesce((select coalesce((select t1.e from t1 where case when c+a in (select t1.f from t1 union select 13 from t1) then c when not not exists(select 1 from t1 where d>= -11) then t1.d else  -t1.f end between b and 11 or d not between e and 11), -f)+e+ -11*17 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where t1.e in (select ~min(e) from t1 union select case case count(distinct f) | min(19)+min(a) when count(*) then max( -t1.c) else max(17) end when (max(t1.c)) then min(11) else min(t1.c) end from t1)) or d=a)),t1.e) FROM t1 WHERE NOT (+t1.e<~case when t1.e in (select (abs(c)/abs(~t1.d)) from t1 union select a from t1) then coalesce((select e from t1 where t1.d+ -coalesce((select max(11-t1.e*b) from t1 where 19 in (11,t1.b,e)),11)*t1.e+19 in (select t1.d from t1 union select  -t1.d from t1)),17) | t1.e+e when t1.f in (17,f,f) then t1.b else 17 end*13)}
} {813}
do_test randexpr-2.2503 {
  db eval {SELECT coalesce((select coalesce((select t1.e from t1 where case when c+a in (select t1.f from t1 union select 13 from t1) then c when not not exists(select 1 from t1 where d>= -11) then t1.d else  -t1.f end between b and 11 or d not between e and 11), -f)+e+ -11*17 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where t1.e in (select ~min(e) from t1 union select case case count(distinct f) & min(19)+min(a) when count(*) then max( -t1.c) else max(17) end when (max(t1.c)) then min(11) else min(t1.c) end from t1)) or d=a)),t1.e) FROM t1 WHERE NOT (+t1.e<~case when t1.e in (select (abs(c)/abs(~t1.d)) from t1 union select a from t1) then coalesce((select e from t1 where t1.d+ -coalesce((select max(11-t1.e*b) from t1 where 19 in (11,t1.b,e)),11)*t1.e+19 in (select t1.d from t1 union select  -t1.d from t1)),17) | t1.e+e when t1.f in (17,f,f) then t1.b else 17 end*13)}
} {813}
do_test randexpr-2.2504 {
  db eval {SELECT case when ((t1.f)+coalesce((select coalesce((select ++d from t1 where not t1.d not between e and e),19) from t1 where t1.d<>19),a)-c*a not between c and t1.a and not exists(select 1 from t1 where 17<=a) and exists(select 1 from t1 where not e in (select t1.b from t1 union select t1.e from t1)) and t1.f between 11 and t1.d) or e between c and 13 then t1.a+e when t1.a not between a and d then 17 else t1.a end FROM t1 WHERE (a)+t1.f>t1.e+a}
} {100}
do_test randexpr-2.2505 {
  db eval {SELECT case when ((t1.f)+coalesce((select coalesce((select ++d from t1 where not t1.d not between e and e),19) from t1 where t1.d<>19),a)-c*a not between c and t1.a and not exists(select 1 from t1 where 17<=a) and exists(select 1 from t1 where not e in (select t1.b from t1 union select t1.e from t1)) and t1.f between 11 and t1.d) or e between c and 13 then t1.a+e when t1.a not between a and d then 17 else t1.a end FROM t1 WHERE NOT ((a)+t1.f>t1.e+a)}
} {}
do_test randexpr-2.2506 {
  db eval {SELECT b*b+case d*d when t1.f then c else coalesce((select coalesce((select max(f) from t1 where (d=t1.b or case when e=11 then t1.a else f end<>t1.d and exists(select 1 from t1 where f not between t1.c and a))),(select count(distinct f) from t1)+case when t1.b between a and (19) and t1.e=a then 13 else 17 end) from t1 where d>=11),f)*t1.e end-11-a- -(11) FROM t1 WHERE (c<19)}
} {}
do_test randexpr-2.2507 {
  db eval {SELECT b*b+case d*d when t1.f then c else coalesce((select coalesce((select max(f) from t1 where (d=t1.b or case when e=11 then t1.a else f end<>t1.d and exists(select 1 from t1 where f not between t1.c and a))),(select count(distinct f) from t1)+case when t1.b between a and (19) and t1.e=a then 13 else 17 end) from t1 where d>=11),f)*t1.e end-11-a- -(11) FROM t1 WHERE NOT ((c<19))}
} {339900}
do_test randexpr-2.2508 {
  db eval {SELECT coalesce((select max(c) from t1 where ((d between t1.c and c)) and b not between t1.a and a or f+c in (d | +f*d*coalesce((select case when not  -t1.c<t1.b then t1.b when  -t1.a between t1.a and e then 11 else c end from t1 where (t1.d>=a)),e)*f,b,11) or  -19>=t1.c and t1.a in (b,t1.f,c)),13) FROM t1 WHERE t1.c in (select count(distinct t1.a)*max(d) | +case (~ -~+count(distinct 13)*min(19) | (max(e))+ -(count(*))) when count(distinct t1.a) then max(d) else count(*) end+min(t1.c) from t1 union select min(e) from t1) and 17=t1.c-t1.d or t1.c-d not in ( -c,(abs(case a when t1.a then 13 else e end+f)/abs(e)),t1.a)}
} {13}
do_test randexpr-2.2509 {
  db eval {SELECT coalesce((select max(c) from t1 where ((d between t1.c and c)) and b not between t1.a and a or f+c in (d | +f*d*coalesce((select case when not  -t1.c<t1.b then t1.b when  -t1.a between t1.a and e then 11 else c end from t1 where (t1.d>=a)),e)*f,b,11) or  -19>=t1.c and t1.a in (b,t1.f,c)),13) FROM t1 WHERE NOT (t1.c in (select count(distinct t1.a)*max(d) | +case (~ -~+count(distinct 13)*min(19) | (max(e))+ -(count(*))) when count(distinct t1.a) then max(d) else count(*) end+min(t1.c) from t1 union select min(e) from t1) and 17=t1.c-t1.d or t1.c-d not in ( -c,(abs(case a when t1.a then 13 else e end+f)/abs(e)),t1.a))}
} {}
do_test randexpr-2.2510 {
  db eval {SELECT coalesce((select max(c) from t1 where ((d between t1.c and c)) and b not between t1.a and a or f+c in (d & +f*d*coalesce((select case when not  -t1.c<t1.b then t1.b when  -t1.a between t1.a and e then 11 else c end from t1 where (t1.d>=a)),e)*f,b,11) or  -19>=t1.c and t1.a in (b,t1.f,c)),13) FROM t1 WHERE t1.c in (select count(distinct t1.a)*max(d) | +case (~ -~+count(distinct 13)*min(19) | (max(e))+ -(count(*))) when count(distinct t1.a) then max(d) else count(*) end+min(t1.c) from t1 union select min(e) from t1) and 17=t1.c-t1.d or t1.c-d not in ( -c,(abs(case a when t1.a then 13 else e end+f)/abs(e)),t1.a)}
} {13}
do_test randexpr-2.2511 {
  db eval {SELECT case case when not (abs(t1.d)/abs(17))>=t1.a+((19))+ -e-b or 11 between t1.a and 11 then 13 when t1.f in (select case count(distinct t1.d) when abs( -+(cast(avg(t1.c) AS integer)))*count(distinct (t1.e)) then max(19) else case count(distinct t1.a) when cast(avg(19) AS integer) then count(*) else cast(avg((t1.a)) AS integer) end end from t1 union select max(13) from t1) then  -t1.b else t1.f end when c then  -c else b end FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where 13>=f))}
} {}
do_test randexpr-2.2512 {
  db eval {SELECT case case when not (abs(t1.d)/abs(17))>=t1.a+((19))+ -e-b or 11 between t1.a and 11 then 13 when t1.f in (select case count(distinct t1.d) when abs( -+(cast(avg(t1.c) AS integer)))*count(distinct (t1.e)) then max(19) else case count(distinct t1.a) when cast(avg(19) AS integer) then count(*) else cast(avg((t1.a)) AS integer) end end from t1 union select max(13) from t1) then  -t1.b else t1.f end when c then  -c else b end FROM t1 WHERE NOT (not exists(select 1 from t1 where not exists(select 1 from t1 where 13>=f)))}
} {200}
do_test randexpr-2.2513 {
  db eval {SELECT 11-(abs( -(select ((count(*)-(abs( -min(~19)))+case min(case when not exists(select 1 from t1 where (exists(select 1 from t1 where 17>f) or t1.c>=a)) then d else 11 end) | abs(cast(avg(19) AS integer)) when (count(distinct t1.f*19))-+ -( -count(*)) then ((cast(avg(t1.d) AS integer))) else cast(avg(t1.a) AS integer) end*count(distinct t1.d))+cast(avg(c) AS integer))-max(17) from t1)-17)/abs(t1.f)) FROM t1 WHERE  - - -f+d in (select 19 from t1 union select t1.b from t1) or ((abs(a)/abs( -11+case when t1.e>=( -f) | d then ~t1.a when coalesce((select t1.d from t1 where e not in (e-(d)+a,e,t1.b)),a)<>t1.b then a else  -t1.c end)))<=t1.e and t1.e in (13,t1.a,t1.f)}
} {}
do_test randexpr-2.2514 {
  db eval {SELECT 11-(abs( -(select ((count(*)-(abs( -min(~19)))+case min(case when not exists(select 1 from t1 where (exists(select 1 from t1 where 17>f) or t1.c>=a)) then d else 11 end) | abs(cast(avg(19) AS integer)) when (count(distinct t1.f*19))-+ -( -count(*)) then ((cast(avg(t1.d) AS integer))) else cast(avg(t1.a) AS integer) end*count(distinct t1.d))+cast(avg(c) AS integer))-max(17) from t1)-17)/abs(t1.f)) FROM t1 WHERE NOT ( - - -f+d in (select 19 from t1 union select t1.b from t1) or ((abs(a)/abs( -11+case when t1.e>=( -f) | d then ~t1.a when coalesce((select t1.d from t1 where e not in (e-(d)+a,e,t1.b)),a)<>t1.b then a else  -t1.c end)))<=t1.e and t1.e in (13,t1.a,t1.f))}
} {11}
do_test randexpr-2.2515 {
  db eval {SELECT 11-(abs( -(select ((count(*)-(abs( -min(~19)))+case min(case when not exists(select 1 from t1 where (exists(select 1 from t1 where 17>f) or t1.c>=a)) then d else 11 end) & abs(cast(avg(19) AS integer)) when (count(distinct t1.f*19))-+ -( -count(*)) then ((cast(avg(t1.d) AS integer))) else cast(avg(t1.a) AS integer) end*count(distinct t1.d))+cast(avg(c) AS integer))-max(17) from t1)-17)/abs(t1.f)) FROM t1 WHERE NOT ( - - -f+d in (select 19 from t1 union select t1.b from t1) or ((abs(a)/abs( -11+case when t1.e>=( -f) | d then ~t1.a when coalesce((select t1.d from t1 where e not in (e-(d)+a,e,t1.b)),a)<>t1.b then a else  -t1.c end)))<=t1.e and t1.e in (13,t1.a,t1.f))}
} {11}
do_test randexpr-2.2516 {
  db eval {SELECT coalesce((select ~11*b from t1 where (not exists(select 1 from t1 where case d when t1.b then t1.b else d end not between b and t1.b and f in (select ~count(*) from t1 union select count(distinct coalesce((select max( -c+(abs(coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where d>a)),t1.b)-17)/abs((b)))*(a)) from t1 where t1.f>b),f)) from t1) or t1.e not in ((d),c,c)))),c)*17+t1.c FROM t1 WHERE coalesce((select 17*case when exists(select 1 from t1 where coalesce((select t1.e from t1 where f<>e and e not between c and 11),d) in (select 11 from t1 union select c from t1)) then t1.b when t1.a between t1.f and 19 then t1.d else t1.c end*f | 19 from t1 where a between t1.c and b or t1.e in ((b),b,t1.f)),17) in (select ( -~case case (((count(*)))) when max(e) then max(e) else cast(avg(c) AS integer) end when min(17) then cast(avg(13) AS integer) else cast(avg(t1.b) AS integer) end+ -count(*)* -count(*))+min(d) from t1 union select count(distinct t1.e) from t1)}
} {}
do_test randexpr-2.2517 {
  db eval {SELECT coalesce((select ~11*b from t1 where (not exists(select 1 from t1 where case d when t1.b then t1.b else d end not between b and t1.b and f in (select ~count(*) from t1 union select count(distinct coalesce((select max( -c+(abs(coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where d>a)),t1.b)-17)/abs((b)))*(a)) from t1 where t1.f>b),f)) from t1) or t1.e not in ((d),c,c)))),c)*17+t1.c FROM t1 WHERE NOT (coalesce((select 17*case when exists(select 1 from t1 where coalesce((select t1.e from t1 where f<>e and e not between c and 11),d) in (select 11 from t1 union select c from t1)) then t1.b when t1.a between t1.f and 19 then t1.d else t1.c end*f | 19 from t1 where a between t1.c and b or t1.e in ((b),b,t1.f)),17) in (select ( -~case case (((count(*)))) when max(e) then max(e) else cast(avg(c) AS integer) end when min(17) then cast(avg(13) AS integer) else cast(avg(t1.b) AS integer) end+ -count(*)* -count(*))+min(d) from t1 union select count(distinct t1.e) from t1))}
} {5400}
do_test randexpr-2.2518 {
  db eval {SELECT (abs(case when not +c<>coalesce((select max(19) from t1 where not (abs(c)/abs(a))*a-t1.a>=case when (exists(select 1 from t1 where d=11)) then t1.a*~b else case when b in (select (f) from t1 union select 17 from t1) or not 17 not between f and  -b then t1.a when f<t1.e then a else t1.c end end),t1.c) then case when 19 between 13 and a then 13 else t1.f end else 11 end)/abs(a)) FROM t1 WHERE (t1.f in (select case case ~abs(case case  -cast(avg((select +max((select min(c) from t1)) from t1)) AS integer) when  -abs( -max(f)*count(*)) then ~case max(c)-count(distinct (t1.f))-(cast(avg(t1.d) AS integer)) when ( -cast(avg( -11) AS integer)) then min( -13) else count(*) end else  -cast(avg(f) AS integer) end when ((min(e))) then min(t1.f) else (count(distinct 17)) end | cast(avg(11) AS integer)-cast(avg(13) AS integer)) when count(*) then count(*) else max(b) end when count(distinct 17) then  -count(distinct t1.d) else count(distinct  -e) end*min(t1.c) from t1 union select count(distinct 17) from t1))}
} {}
do_test randexpr-2.2519 {
  db eval {SELECT (abs(case when not +c<>coalesce((select max(19) from t1 where not (abs(c)/abs(a))*a-t1.a>=case when (exists(select 1 from t1 where d=11)) then t1.a*~b else case when b in (select (f) from t1 union select 17 from t1) or not 17 not between f and  -b then t1.a when f<t1.e then a else t1.c end end),t1.c) then case when 19 between 13 and a then 13 else t1.f end else 11 end)/abs(a)) FROM t1 WHERE NOT ((t1.f in (select case case ~abs(case case  -cast(avg((select +max((select min(c) from t1)) from t1)) AS integer) when  -abs( -max(f)*count(*)) then ~case max(c)-count(distinct (t1.f))-(cast(avg(t1.d) AS integer)) when ( -cast(avg( -11) AS integer)) then min( -13) else count(*) end else  -cast(avg(f) AS integer) end when ((min(e))) then min(t1.f) else (count(distinct 17)) end | cast(avg(11) AS integer)-cast(avg(13) AS integer)) when count(*) then count(*) else max(b) end when count(distinct 17) then  -count(distinct t1.d) else count(distinct  -e) end*min(t1.c) from t1 union select count(distinct 17) from t1)))}
} {0}
do_test randexpr-2.2520 {
  db eval {SELECT ~case when case 11*17 when f then t1.a else t1.e end in ( -coalesce((select max(case coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.c in (case t1.e when  -d then c else (d) end,t1.e,t1.a))), -t1.c) when 19 then 11 else t1.e end) from t1 where t1.e in (19, -t1.b,a)),17)+f-11,17,19) then a when ((d<d)) then 11 else  -t1.e end FROM t1 WHERE not e>=t1.b and (b not in (c,t1.e,t1.a))}
} {}
do_test randexpr-2.2521 {
  db eval {SELECT ~case when case 11*17 when f then t1.a else t1.e end in ( -coalesce((select max(case coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.c in (case t1.e when  -d then c else (d) end,t1.e,t1.a))), -t1.c) when 19 then 11 else t1.e end) from t1 where t1.e in (19, -t1.b,a)),17)+f-11,17,19) then a when ((d<d)) then 11 else  -t1.e end FROM t1 WHERE NOT (not e>=t1.b and (b not in (c,t1.e,t1.a)))}
} {499}
do_test randexpr-2.2522 {
  db eval {SELECT (abs(case f when case when d+f between e and t1.f then f when coalesce((select max(t1.f) from t1 where c in (select t1.a from t1 union select case when a not between t1.c and 13 then a else t1.c end from t1) or f*f not in (case when (11<=d) then case when 13<t1.a then (t1.d) else t1.a end else t1.a end-t1.d,17,f) or a>= -d),b)<=t1.b then t1.e else 13 end then f else t1.b end)/abs(f)) FROM t1 WHERE c between c and coalesce((select max(f) from t1 where b in (select count(*) from t1 union select max(13) from t1)),19)}
} {}
do_test randexpr-2.2523 {
  db eval {SELECT (abs(case f when case when d+f between e and t1.f then f when coalesce((select max(t1.f) from t1 where c in (select t1.a from t1 union select case when a not between t1.c and 13 then a else t1.c end from t1) or f*f not in (case when (11<=d) then case when 13<t1.a then (t1.d) else t1.a end else t1.a end-t1.d,17,f) or a>= -d),b)<=t1.b then t1.e else 13 end then f else t1.b end)/abs(f)) FROM t1 WHERE NOT (c between c and coalesce((select max(f) from t1 where b in (select count(*) from t1 union select max(13) from t1)),19))}
} {0}
do_test randexpr-2.2524 {
  db eval {SELECT d++11*a+coalesce((select max(t1.a) from t1 where 17+case when (19>=a) then t1.b when f>=f then  -(select cast(avg(t1.e-t1.f*t1.a) AS integer) from t1)-f else t1.f end*a+f*t1.a not in (t1.e,e,13)),17)- -t1.b-a-c*19 FROM t1 WHERE f*t1.a*t1.b>17 and case when 13 not in (19, -(select count(*) from t1),coalesce((select max(coalesce((select max(t1.a) from t1 where  -coalesce((select max(case when not t1.f<=(t1.d) then t1.a else (a) end) from t1 where t1.f>c or 13<(t1.a)),17)>=t1.a or not exists(select 1 from t1 where  - -c not in (a,t1.b,t1.e))),t1.e)) from t1 where (f not in (b,f,f))),c)) then (t1.e) when t1.a<>e then e else b end- -t1.f not in (a, -c,(c))}
} {-4000}
do_test randexpr-2.2525 {
  db eval {SELECT d++11*a+coalesce((select max(t1.a) from t1 where 17+case when (19>=a) then t1.b when f>=f then  -(select cast(avg(t1.e-t1.f*t1.a) AS integer) from t1)-f else t1.f end*a+f*t1.a not in (t1.e,e,13)),17)- -t1.b-a-c*19 FROM t1 WHERE NOT (f*t1.a*t1.b>17 and case when 13 not in (19, -(select count(*) from t1),coalesce((select max(coalesce((select max(t1.a) from t1 where  -coalesce((select max(case when not t1.f<=(t1.d) then t1.a else (a) end) from t1 where t1.f>c or 13<(t1.a)),17)>=t1.a or not exists(select 1 from t1 where  - -c not in (a,t1.b,t1.e))),t1.e)) from t1 where (f not in (b,f,f))),c)) then (t1.e) when t1.a<>e then e else b end- -t1.f not in (a, -c,(c)))}
} {}
do_test randexpr-2.2526 {
  db eval {SELECT coalesce((select (a) from t1 where 11-11+t1.b<=17-b),case when case when not t1.e*f>= -t1.f and a in (11,t1.c,t1.b) or 19>e then (select case min((f)-f) when cast(avg(t1.a) AS integer) then (cast(avg(17) AS integer)) else ((cast(avg((13)) AS integer))) end from t1) when 13 not between f and t1.c then (abs(e)/abs(17)) else t1.e end |  -17<=f then b when f<19 or t1.b<=t1.d then f else f end) FROM t1 WHERE  -f | t1.f*c-t1.a | t1.c+11*case ~17 when  -coalesce((select max(t1.e) from t1 where 13*(17)>=11),t1.a) then case case when (t1.b>= -t1.b) then t1.f when t1.f<a or 11>a and t1.e in (e,(t1.d),19) then t1.f else t1.c end when a then t1.a else t1.e end else a end*t1.a-13<c}
} {200}
do_test randexpr-2.2527 {
  db eval {SELECT coalesce((select (a) from t1 where 11-11+t1.b<=17-b),case when case when not t1.e*f>= -t1.f and a in (11,t1.c,t1.b) or 19>e then (select case min((f)-f) when cast(avg(t1.a) AS integer) then (cast(avg(17) AS integer)) else ((cast(avg((13)) AS integer))) end from t1) when 13 not between f and t1.c then (abs(e)/abs(17)) else t1.e end |  -17<=f then b when f<19 or t1.b<=t1.d then f else f end) FROM t1 WHERE NOT ( -f | t1.f*c-t1.a | t1.c+11*case ~17 when  -coalesce((select max(t1.e) from t1 where 13*(17)>=11),t1.a) then case case when (t1.b>= -t1.b) then t1.f when t1.f<a or 11>a and t1.e in (e,(t1.d),19) then t1.f else t1.c end when a then t1.a else t1.e end else a end*t1.a-13<c)}
} {}
do_test randexpr-2.2528 {
  db eval {SELECT coalesce((select (a) from t1 where 11-11+t1.b<=17-b),case when case when not t1.e*f>= -t1.f and a in (11,t1.c,t1.b) or 19>e then (select case min((f)-f) when cast(avg(t1.a) AS integer) then (cast(avg(17) AS integer)) else ((cast(avg((13)) AS integer))) end from t1) when 13 not between f and t1.c then (abs(e)/abs(17)) else t1.e end &  -17<=f then b when f<19 or t1.b<=t1.d then f else f end) FROM t1 WHERE  -f | t1.f*c-t1.a | t1.c+11*case ~17 when  -coalesce((select max(t1.e) from t1 where 13*(17)>=11),t1.a) then case case when (t1.b>= -t1.b) then t1.f when t1.f<a or 11>a and t1.e in (e,(t1.d),19) then t1.f else t1.c end when a then t1.a else t1.e end else a end*t1.a-13<c}
} {200}
do_test randexpr-2.2529 {
  db eval {SELECT (abs(case when exists(select 1 from t1 where b not between ~case when (t1.e-(c-t1.c) | t1.a) in (select abs(~((min(t1.f) | cast(avg(c) AS integer))*(min(b))-count(distinct 19)*min(e)) |  -((count(*))))-cast(avg(d) AS integer) from t1 union select  -count(distinct t1.a) from t1) or f>a then 11 else e end*11 and t1.e) then t1.e when  -17<11 then 17 else t1.a end)/abs(a)) FROM t1 WHERE c<=19}
} {}
do_test randexpr-2.2530 {
  db eval {SELECT (abs(case when exists(select 1 from t1 where b not between ~case when (t1.e-(c-t1.c) | t1.a) in (select abs(~((min(t1.f) | cast(avg(c) AS integer))*(min(b))-count(distinct 19)*min(e)) |  -((count(*))))-cast(avg(d) AS integer) from t1 union select  -count(distinct t1.a) from t1) or f>a then 11 else e end*11 and t1.e) then t1.e when  -17<11 then 17 else t1.a end)/abs(a)) FROM t1 WHERE NOT (c<=19)}
} {0}
do_test randexpr-2.2531 {
  db eval {SELECT (abs(case when exists(select 1 from t1 where b not between ~case when (t1.e-(c-t1.c) & t1.a) in (select abs(~((min(t1.f) & cast(avg(c) AS integer))*(min(b))-count(distinct 19)*min(e)) &  -((count(*))))-cast(avg(d) AS integer) from t1 union select  -count(distinct t1.a) from t1) or f>a then 11 else e end*11 and t1.e) then t1.e when  -17<11 then 17 else t1.a end)/abs(a)) FROM t1 WHERE NOT (c<=19)}
} {0}
do_test randexpr-2.2532 {
  db eval {SELECT case when t1.e-19 in (case (abs(t1.a*+~c*coalesce((select c from t1 where ~ -(select abs(case cast(avg(13) AS integer) when  - -cast(avg(f) AS integer) then count(distinct t1.d) else (count(*)) end+count(*)) from t1) not between (abs(a | t1.a)/abs(t1.c)) and 19),t1.b)-c*17*(t1.f))/abs(d)) when 13 then 19 else t1.b end,(b),17) then 19 when (11)>=t1.b then b else b end*11 FROM t1 WHERE (case 11 when case t1.e when coalesce((select a from t1 where t1.a<t1.e),t1.e | case when 13 in (coalesce((select max( -b) from t1 where d not between (t1.a) and t1.e and t1.e>=t1.a),t1.f),d,13) then c when 11 between t1.b and 17 then d else 19 end) then f else 19 end then t1.d else c end< -c) and a not in (11,c,11) or 11<>e or exists(select 1 from t1 where b<17)}
} {2200}
do_test randexpr-2.2533 {
  db eval {SELECT case when t1.e-19 in (case (abs(t1.a*+~c*coalesce((select c from t1 where ~ -(select abs(case cast(avg(13) AS integer) when  - -cast(avg(f) AS integer) then count(distinct t1.d) else (count(*)) end+count(*)) from t1) not between (abs(a | t1.a)/abs(t1.c)) and 19),t1.b)-c*17*(t1.f))/abs(d)) when 13 then 19 else t1.b end,(b),17) then 19 when (11)>=t1.b then b else b end*11 FROM t1 WHERE NOT ((case 11 when case t1.e when coalesce((select a from t1 where t1.a<t1.e),t1.e | case when 13 in (coalesce((select max( -b) from t1 where d not between (t1.a) and t1.e and t1.e>=t1.a),t1.f),d,13) then c when 11 between t1.b and 17 then d else 19 end) then f else 19 end then t1.d else c end< -c) and a not in (11,c,11) or 11<>e or exists(select 1 from t1 where b<17))}
} {}
do_test randexpr-2.2534 {
  db eval {SELECT case when t1.e-19 in (case (abs(t1.a*+~c*coalesce((select c from t1 where ~ -(select abs(case cast(avg(13) AS integer) when  - -cast(avg(f) AS integer) then count(distinct t1.d) else (count(*)) end+count(*)) from t1) not between (abs(a & t1.a)/abs(t1.c)) and 19),t1.b)-c*17*(t1.f))/abs(d)) when 13 then 19 else t1.b end,(b),17) then 19 when (11)>=t1.b then b else b end*11 FROM t1 WHERE (case 11 when case t1.e when coalesce((select a from t1 where t1.a<t1.e),t1.e | case when 13 in (coalesce((select max( -b) from t1 where d not between (t1.a) and t1.e and t1.e>=t1.a),t1.f),d,13) then c when 11 between t1.b and 17 then d else 19 end) then f else 19 end then t1.d else c end< -c) and a not in (11,c,11) or 11<>e or exists(select 1 from t1 where b<17)}
} {2200}
do_test randexpr-2.2535 {
  db eval {SELECT t1.b*case when (abs(t1.c+case when d not in (a,case when b=(t1.a) then (e) when b not between f and t1.c then t1.b else t1.e end, -11) then t1.d when not exists(select 1 from t1 where 19 not between (a) and a or t1.c>d) then d else b end+t1.a+13-19+d)/abs(t1.d))> -t1.f then t1.a when t1.d in (select d from t1 union select c from t1) or 13 not between d and t1.f then t1.b else e end+ - -a FROM t1 WHERE t1.f<=11}
} {}
do_test randexpr-2.2536 {
  db eval {SELECT t1.b*case when (abs(t1.c+case when d not in (a,case when b=(t1.a) then (e) when b not between f and t1.c then t1.b else t1.e end, -11) then t1.d when not exists(select 1 from t1 where 19 not between (a) and a or t1.c>d) then d else b end+t1.a+13-19+d)/abs(t1.d))> -t1.f then t1.a when t1.d in (select d from t1 union select c from t1) or 13 not between d and t1.f then t1.b else e end+ - -a FROM t1 WHERE NOT (t1.f<=11)}
} {20100}
do_test randexpr-2.2537 {
  db eval {SELECT coalesce((select max(coalesce((select e+t1.c from t1 where f*11+coalesce((select max(17) from t1 where not ~case a when t1.f+13*e-(11)*t1.f then d else a end>d and (a not between t1.c and t1.c)),t1.d)- -f-b+11=b),19)-t1.f) from t1 where exists(select 1 from t1 where 19<>11)),c) FROM t1 WHERE case when 11 in (select  -abs(abs( - -(cast(avg(+11-c) AS integer)+cast(avg(~a) AS integer))*max(11))+cast(avg(d) AS integer)-cast(avg(e) AS integer)-((max(t1.e))))+count(*) from t1 union select ( -count(*)) from t1) then t1.a when e>d then c- - -t1.a else 19 end in (select count(distinct  -f) from t1 union select count(distinct d) from t1) and not e<17}
} {}
do_test randexpr-2.2538 {
  db eval {SELECT coalesce((select max(coalesce((select e+t1.c from t1 where f*11+coalesce((select max(17) from t1 where not ~case a when t1.f+13*e-(11)*t1.f then d else a end>d and (a not between t1.c and t1.c)),t1.d)- -f-b+11=b),19)-t1.f) from t1 where exists(select 1 from t1 where 19<>11)),c) FROM t1 WHERE NOT (case when 11 in (select  -abs(abs( - -(cast(avg(+11-c) AS integer)+cast(avg(~a) AS integer))*max(11))+cast(avg(d) AS integer)-cast(avg(e) AS integer)-((max(t1.e))))+count(*) from t1 union select ( -count(*)) from t1) then t1.a when e>d then c- - -t1.a else 19 end in (select count(distinct  -f) from t1 union select count(distinct d) from t1) and not e<17)}
} {-581}
do_test randexpr-2.2539 {
  db eval {SELECT case when (coalesce((select max(a*case when 17+f>f-t1.d*t1.f then t1.d when t1.c not between t1.e and d then 19 else (c) end) from t1 where not t1.d not between  - -17 and 19),t1.a) in (select min((13)) from t1 union select ~(abs(count(distinct t1.a))*((( -max( -t1.f)))+max( -t1.c) | count(*)))-cast(avg(11) AS integer) from t1)) then c- - -d when t1.d>=d then d else 13 end FROM t1 WHERE ((abs(t1.a-t1.a*t1.d*coalesce((select coalesce((select max(11) from t1 where exists(select 1 from t1 where 11+t1.d |  -t1.c-case when b+d in (select count(*) from t1 union select max(17)+ -count(distinct t1.d) from t1) then t1.c else d end-a | 13<>c)),t1.c) from t1 where 13 not in (d,t1.a,f) and 19=t1.f),(13))+(t1.d))/abs(t1.c)) between t1.f and t1.d)}
} {}
do_test randexpr-2.2540 {
  db eval {SELECT case when (coalesce((select max(a*case when 17+f>f-t1.d*t1.f then t1.d when t1.c not between t1.e and d then 19 else (c) end) from t1 where not t1.d not between  - -17 and 19),t1.a) in (select min((13)) from t1 union select ~(abs(count(distinct t1.a))*((( -max( -t1.f)))+max( -t1.c) | count(*)))-cast(avg(11) AS integer) from t1)) then c- - -d when t1.d>=d then d else 13 end FROM t1 WHERE NOT (((abs(t1.a-t1.a*t1.d*coalesce((select coalesce((select max(11) from t1 where exists(select 1 from t1 where 11+t1.d |  -t1.c-case when b+d in (select count(*) from t1 union select max(17)+ -count(distinct t1.d) from t1) then t1.c else d end-a | 13<>c)),t1.c) from t1 where 13 not in (d,t1.a,f) and 19=t1.f),(13))+(t1.d))/abs(t1.c)) between t1.f and t1.d))}
} {400}
do_test randexpr-2.2541 {
  db eval {SELECT case when (coalesce((select max(a*case when 17+f>f-t1.d*t1.f then t1.d when t1.c not between t1.e and d then 19 else (c) end) from t1 where not t1.d not between  - -17 and 19),t1.a) in (select min((13)) from t1 union select ~(abs(count(distinct t1.a))*((( -max( -t1.f)))+max( -t1.c) & count(*)))-cast(avg(11) AS integer) from t1)) then c- - -d when t1.d>=d then d else 13 end FROM t1 WHERE NOT (((abs(t1.a-t1.a*t1.d*coalesce((select coalesce((select max(11) from t1 where exists(select 1 from t1 where 11+t1.d |  -t1.c-case when b+d in (select count(*) from t1 union select max(17)+ -count(distinct t1.d) from t1) then t1.c else d end-a | 13<>c)),t1.c) from t1 where 13 not in (d,t1.a,f) and 19=t1.f),(13))+(t1.d))/abs(t1.c)) between t1.f and t1.d))}
} {400}
do_test randexpr-2.2542 {
  db eval {SELECT case when f | c>t1.d-case when (abs(t1.b-t1.d*f)/abs(c))=t1.e then 17 when not exists(select 1 from t1 where t1.b=(11) or c not in (13,17,b)) or a<e then t1.f else 19 end+b-t1.f and t1.b between t1.b and t1.f and e in (t1.f,b,b) then (select cast(avg(e) AS integer)-~ -~count(*) from t1) else 11 end FROM t1 WHERE e<=case when (case when 17<>a then t1.c when not 11<(f) then case when t1.c= -b then c else 11 end else e end | f>=t1.b and b not between  -(t1.e) and f) then 17 when f in (select  -count(distinct t1.e) from t1 union select case min(f) when case cast(avg( -t1.b) AS integer) when cast(avg(e) AS integer) then  -max(e) else min(t1.b) end then count(*) else (cast(avg(t1.e) AS integer)) end from t1) then case c when e then t1.f else 13 end else t1.d end}
} {}
do_test randexpr-2.2543 {
  db eval {SELECT case when f | c>t1.d-case when (abs(t1.b-t1.d*f)/abs(c))=t1.e then 17 when not exists(select 1 from t1 where t1.b=(11) or c not in (13,17,b)) or a<e then t1.f else 19 end+b-t1.f and t1.b between t1.b and t1.f and e in (t1.f,b,b) then (select cast(avg(e) AS integer)-~ -~count(*) from t1) else 11 end FROM t1 WHERE NOT (e<=case when (case when 17<>a then t1.c when not 11<(f) then case when t1.c= -b then c else 11 end else e end | f>=t1.b and b not between  -(t1.e) and f) then 17 when f in (select  -count(distinct t1.e) from t1 union select case min(f) when case cast(avg( -t1.b) AS integer) when cast(avg(e) AS integer) then  -max(e) else min(t1.b) end then count(*) else (cast(avg(t1.e) AS integer)) end from t1) then case c when e then t1.f else 13 end else t1.d end)}
} {11}
do_test randexpr-2.2544 {
  db eval {SELECT case when f & c>t1.d-case when (abs(t1.b-t1.d*f)/abs(c))=t1.e then 17 when not exists(select 1 from t1 where t1.b=(11) or c not in (13,17,b)) or a<e then t1.f else 19 end+b-t1.f and t1.b between t1.b and t1.f and e in (t1.f,b,b) then (select cast(avg(e) AS integer)-~ -~count(*) from t1) else 11 end FROM t1 WHERE NOT (e<=case when (case when 17<>a then t1.c when not 11<(f) then case when t1.c= -b then c else 11 end else e end | f>=t1.b and b not between  -(t1.e) and f) then 17 when f in (select  -count(distinct t1.e) from t1 union select case min(f) when case cast(avg( -t1.b) AS integer) when cast(avg(e) AS integer) then  -max(e) else min(t1.b) end then count(*) else (cast(avg(t1.e) AS integer)) end from t1) then case c when e then t1.f else 13 end else t1.d end)}
} {11}
do_test randexpr-2.2545 {
  db eval {SELECT 17+coalesce((select max(19) from t1 where 11 in (select (abs((abs(~(case +b+17 when t1.e*t1.b then 17 else case when t1.b+17+d*a in (select (~count(distinct a)) from t1 union select case cast(avg(t1.e) AS integer) when count(*) then count(distinct t1.d) else count(distinct b) end from t1) then t1.f when (t1.e in ( -t1.a,t1.e,d)) then 17 else t1.e end | e end)- -b)/abs(t1.f)))/abs(13)) from t1 union select t1.d from t1)),17) FROM t1 WHERE e+t1.b not in (d,a,t1.c) and case case e when (case when +case 13 when t1.a then 19 else 19 end+d in (select count(*)-min(b) from t1 union select  - -min(t1.d) from t1) or f in (select ( -min(t1.e)) from t1 union select cast(avg( -19) AS integer) from t1) or (t1.f in (select  -max( -t1.c) from t1 union select (min(t1.c)) from t1)) then b else +t1.b end)-t1.b then b else 19 end when a then b else e end between ( -(t1.c)) and a}
} {}
do_test randexpr-2.2546 {
  db eval {SELECT 17+coalesce((select max(19) from t1 where 11 in (select (abs((abs(~(case +b+17 when t1.e*t1.b then 17 else case when t1.b+17+d*a in (select (~count(distinct a)) from t1 union select case cast(avg(t1.e) AS integer) when count(*) then count(distinct t1.d) else count(distinct b) end from t1) then t1.f when (t1.e in ( -t1.a,t1.e,d)) then 17 else t1.e end | e end)- -b)/abs(t1.f)))/abs(13)) from t1 union select t1.d from t1)),17) FROM t1 WHERE NOT (e+t1.b not in (d,a,t1.c) and case case e when (case when +case 13 when t1.a then 19 else 19 end+d in (select count(*)-min(b) from t1 union select  - -min(t1.d) from t1) or f in (select ( -min(t1.e)) from t1 union select cast(avg( -19) AS integer) from t1) or (t1.f in (select  -max( -t1.c) from t1 union select (min(t1.c)) from t1)) then b else +t1.b end)-t1.b then b else 19 end when a then b else e end between ( -(t1.c)) and a)}
} {34}
do_test randexpr-2.2547 {
  db eval {SELECT 17+coalesce((select max(19) from t1 where 11 in (select (abs((abs(~(case +b+17 when t1.e*t1.b then 17 else case when t1.b+17+d*a in (select (~count(distinct a)) from t1 union select case cast(avg(t1.e) AS integer) when count(*) then count(distinct t1.d) else count(distinct b) end from t1) then t1.f when (t1.e in ( -t1.a,t1.e,d)) then 17 else t1.e end & e end)- -b)/abs(t1.f)))/abs(13)) from t1 union select t1.d from t1)),17) FROM t1 WHERE NOT (e+t1.b not in (d,a,t1.c) and case case e when (case when +case 13 when t1.a then 19 else 19 end+d in (select count(*)-min(b) from t1 union select  - -min(t1.d) from t1) or f in (select ( -min(t1.e)) from t1 union select cast(avg( -19) AS integer) from t1) or (t1.f in (select  -max( -t1.c) from t1 union select (min(t1.c)) from t1)) then b else +t1.b end)-t1.b then b else 19 end when a then b else e end between ( -(t1.c)) and a)}
} {34}
do_test randexpr-2.2548 {
  db eval {SELECT (abs(~(abs((select ~count(*) | +(max( -coalesce((select max(13) from t1 where coalesce((select max(t1.d) from t1 where 11<+coalesce((select max((case when 19=t1.a then (d) else 19 end)) from t1 where (11) in (17,c,b)),c)*t1.e),t1.c)<13),11)*b | t1.c+17)) from t1))/abs(~b-f))-t1.d*a)/abs(e)) FROM t1 WHERE c not in (coalesce((select t1.a from t1 where  -(t1.a+17*~case when coalesce((select max(t1.c) from t1 where (coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where a<=t1.a)),11) in (select (count(distinct t1.d)+count(distinct c)) from t1 union select count(distinct e) from t1))),13)*f=d then d when t1.d in (select t1.d from t1 union select t1.f from t1) then d else t1.f end+c*c | f)+t1.c*t1.a in (select 17 from t1 union select 13 from t1)),t1.f),17,t1.f)}
} {80}
do_test randexpr-2.2549 {
  db eval {SELECT (abs(~(abs((select ~count(*) | +(max( -coalesce((select max(13) from t1 where coalesce((select max(t1.d) from t1 where 11<+coalesce((select max((case when 19=t1.a then (d) else 19 end)) from t1 where (11) in (17,c,b)),c)*t1.e),t1.c)<13),11)*b | t1.c+17)) from t1))/abs(~b-f))-t1.d*a)/abs(e)) FROM t1 WHERE NOT (c not in (coalesce((select t1.a from t1 where  -(t1.a+17*~case when coalesce((select max(t1.c) from t1 where (coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where a<=t1.a)),11) in (select (count(distinct t1.d)+count(distinct c)) from t1 union select count(distinct e) from t1))),13)*f=d then d when t1.d in (select t1.d from t1 union select t1.f from t1) then d else t1.f end+c*c | f)+t1.c*t1.a in (select 17 from t1 union select 13 from t1)),t1.f),17,t1.f))}
} {}
do_test randexpr-2.2550 {
  db eval {SELECT (abs(~(abs((select ~count(*) & +(max( -coalesce((select max(13) from t1 where coalesce((select max(t1.d) from t1 where 11<+coalesce((select max((case when 19=t1.a then (d) else 19 end)) from t1 where (11) in (17,c,b)),c)*t1.e),t1.c)<13),11)*b & t1.c+17)) from t1))/abs(~b-f))-t1.d*a)/abs(e)) FROM t1 WHERE c not in (coalesce((select t1.a from t1 where  -(t1.a+17*~case when coalesce((select max(t1.c) from t1 where (coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where a<=t1.a)),11) in (select (count(distinct t1.d)+count(distinct c)) from t1 union select count(distinct e) from t1))),13)*f=d then d when t1.d in (select t1.d from t1 union select t1.f from t1) then d else t1.f end+c*c | f)+t1.c*t1.a in (select 17 from t1 union select 13 from t1)),t1.f),17,t1.f)}
} {80}
do_test randexpr-2.2551 {
  db eval {SELECT case (19) when t1.a then t1.f+coalesce((select max(t1.f) from t1 where case when t1.c=t1.a or (t1.d | case when t1.f=t1.d then a else coalesce((select max(case when 11>=a then t1.b else d end+t1.a) from t1 where  -t1.a not between t1.e and 19),11) end<>t1.d) then t1.e else c end-t1.f*b+f=19),t1.b) | (t1.a)+e else a end FROM t1 WHERE (case e when d then +(select (min(t1.a)) from t1) else case when a in ((select min(case  -t1.c when d then d else f end+ -e)-+cast(avg(19) AS integer)+max(d) from t1)*t1.d |  -t1.c,b,e) then t1.d when t1.b in (select +min(e) | min(t1.b) from t1 union select  -count(distinct e) from t1) then d else 11 end*13-(e) end not in (t1.c,c,17))}
} {100}
do_test randexpr-2.2552 {
  db eval {SELECT case (19) when t1.a then t1.f+coalesce((select max(t1.f) from t1 where case when t1.c=t1.a or (t1.d | case when t1.f=t1.d then a else coalesce((select max(case when 11>=a then t1.b else d end+t1.a) from t1 where  -t1.a not between t1.e and 19),11) end<>t1.d) then t1.e else c end-t1.f*b+f=19),t1.b) | (t1.a)+e else a end FROM t1 WHERE NOT ((case e when d then +(select (min(t1.a)) from t1) else case when a in ((select min(case  -t1.c when d then d else f end+ -e)-+cast(avg(19) AS integer)+max(d) from t1)*t1.d |  -t1.c,b,e) then t1.d when t1.b in (select +min(e) | min(t1.b) from t1 union select  -count(distinct e) from t1) then d else 11 end*13-(e) end not in (t1.c,c,17)))}
} {}
do_test randexpr-2.2553 {
  db eval {SELECT case (19) when t1.a then t1.f+coalesce((select max(t1.f) from t1 where case when t1.c=t1.a or (t1.d & case when t1.f=t1.d then a else coalesce((select max(case when 11>=a then t1.b else d end+t1.a) from t1 where  -t1.a not between t1.e and 19),11) end<>t1.d) then t1.e else c end-t1.f*b+f=19),t1.b) & (t1.a)+e else a end FROM t1 WHERE (case e when d then +(select (min(t1.a)) from t1) else case when a in ((select min(case  -t1.c when d then d else f end+ -e)-+cast(avg(19) AS integer)+max(d) from t1)*t1.d |  -t1.c,b,e) then t1.d when t1.b in (select +min(e) | min(t1.b) from t1 union select  -count(distinct e) from t1) then d else 11 end*13-(e) end not in (t1.c,c,17))}
} {100}
do_test randexpr-2.2554 {
  db eval {SELECT (abs(( -case when 11*coalesce((select coalesce((select d from t1 where ((+t1.f*(select max(t1.f)*min(t1.a) from t1)*d*t1.f between 11 and 13))), -t1.c) from t1 where ((e)>=t1.b) or not t1.a in (select f from t1 union select c from t1) and 11<=a or c between (t1.c) and t1.d),t1.f)<t1.b then 13 else c end-d-t1.e))/abs(17)) FROM t1 WHERE +(select ~case  -++(( -~count(distinct t1.b)))*min(c)*max(t1.f) when ~+count(distinct  -(abs(d)/abs(t1.a))+t1.d+c-13) then count(*) else case (~max(d))+((count(distinct f))) when max(t1.e) then min(t1.c) else (cast(avg(t1.e) AS integer)) end end from t1)-+(select min(17) from t1)+19>t1.f}
} {}
do_test randexpr-2.2555 {
  db eval {SELECT (abs(( -case when 11*coalesce((select coalesce((select d from t1 where ((+t1.f*(select max(t1.f)*min(t1.a) from t1)*d*t1.f between 11 and 13))), -t1.c) from t1 where ((e)>=t1.b) or not t1.a in (select f from t1 union select c from t1) and 11<=a or c between (t1.c) and t1.d),t1.f)<t1.b then 13 else c end-d-t1.e))/abs(17)) FROM t1 WHERE NOT (+(select ~case  -++(( -~count(distinct t1.b)))*min(c)*max(t1.f) when ~+count(distinct  -(abs(d)/abs(t1.a))+t1.d+c-13) then count(*) else case (~max(d))+((count(distinct f))) when max(t1.e) then min(t1.c) else (cast(avg(t1.e) AS integer)) end end from t1)-+(select min(17) from t1)+19>t1.f)}
} {53}
do_test randexpr-2.2556 {
  db eval {SELECT case (t1.b) | t1.d-+t1.e*(select (~count(*) | min(c)-case max(case when e | b in (select t1.b from t1 union select t1.b from t1) then d when 17 between 13 and t1.d then d else t1.c end) when abs(count(distinct (t1.e)))- -min(t1.e) then cast(avg(17) AS integer) else count(distinct c) end) from t1) | b-a-+f-t1.f when +a then t1.d else d end FROM t1 WHERE (17>t1.d) and coalesce((select max((t1.a)+coalesce((select max(17*b) from t1 where t1.d-coalesce((select t1.e from t1 where t1.b<>13 or 19=t1.a),t1.d)*f<=(19) or (t1.c<11 and not not d<t1.a)), -11)-17) from t1 where t1.d not in (19,a,t1.c)),e)*13>t1.d or d=11}
} {}
do_test randexpr-2.2557 {
  db eval {SELECT case (t1.b) | t1.d-+t1.e*(select (~count(*) | min(c)-case max(case when e | b in (select t1.b from t1 union select t1.b from t1) then d when 17 between 13 and t1.d then d else t1.c end) when abs(count(distinct (t1.e)))- -min(t1.e) then cast(avg(17) AS integer) else count(distinct c) end) from t1) | b-a-+f-t1.f when +a then t1.d else d end FROM t1 WHERE NOT ((17>t1.d) and coalesce((select max((t1.a)+coalesce((select max(17*b) from t1 where t1.d-coalesce((select t1.e from t1 where t1.b<>13 or 19=t1.a),t1.d)*f<=(19) or (t1.c<11 and not not d<t1.a)), -11)-17) from t1 where t1.d not in (19,a,t1.c)),e)*13>t1.d or d=11)}
} {400}
do_test randexpr-2.2558 {
  db eval {SELECT case (t1.b) & t1.d-+t1.e*(select (~count(*) & min(c)-case max(case when e & b in (select t1.b from t1 union select t1.b from t1) then d when 17 between 13 and t1.d then d else t1.c end) when abs(count(distinct (t1.e)))- -min(t1.e) then cast(avg(17) AS integer) else count(distinct c) end) from t1) & b-a-+f-t1.f when +a then t1.d else d end FROM t1 WHERE NOT ((17>t1.d) and coalesce((select max((t1.a)+coalesce((select max(17*b) from t1 where t1.d-coalesce((select t1.e from t1 where t1.b<>13 or 19=t1.a),t1.d)*f<=(19) or (t1.c<11 and not not d<t1.a)), -11)-17) from t1 where t1.d not in (19,a,t1.c)),e)*13>t1.d or d=11)}
} {400}
do_test randexpr-2.2559 {
  db eval {SELECT case when case when coalesce((select max(c*case (select min(case when f in (select t1.e from t1 union select f+case when d<=d then t1.f when b<=11 then t1.c else t1.b end*11 from t1) then f else c end) from t1) when f then 11 else b end) from t1 where d in (t1.b,t1.a,c)),d) between (d) and 19 then  -a else a end in ( -c,t1.d,t1.d) then c when e<> -d then a else t1.c end FROM t1 WHERE a=c or case when e<coalesce((select t1.c from t1 where exists(select 1 from t1 where (f not in (case (select case +(min(11)) when cast(avg(t1.c) AS integer) then count(*) else  - -cast(avg(t1.a) AS integer) end from t1) when t1.b then d else t1.b end,13,a) and t1.c<= -t1.d and (t1.a)<=b or e not between t1.a and b) or a not between t1.b and t1.f) or 19>=(e)),t1.a) then c | t1.f when exists(select 1 from t1 where a not between 19 and e) then t1.a else 17 end>t1.d}
} {}
do_test randexpr-2.2560 {
  db eval {SELECT case when case when coalesce((select max(c*case (select min(case when f in (select t1.e from t1 union select f+case when d<=d then t1.f when b<=11 then t1.c else t1.b end*11 from t1) then f else c end) from t1) when f then 11 else b end) from t1 where d in (t1.b,t1.a,c)),d) between (d) and 19 then  -a else a end in ( -c,t1.d,t1.d) then c when e<> -d then a else t1.c end FROM t1 WHERE NOT (a=c or case when e<coalesce((select t1.c from t1 where exists(select 1 from t1 where (f not in (case (select case +(min(11)) when cast(avg(t1.c) AS integer) then count(*) else  - -cast(avg(t1.a) AS integer) end from t1) when t1.b then d else t1.b end,13,a) and t1.c<= -t1.d and (t1.a)<=b or e not between t1.a and b) or a not between t1.b and t1.f) or 19>=(e)),t1.a) then c | t1.f when exists(select 1 from t1 where a not between 19 and e) then t1.a else 17 end>t1.d)}
} {100}
do_test randexpr-2.2561 {
  db eval {SELECT 13+(select  -abs(+cast(avg((select cast(avg(t1.e*(t1.c)- -(abs(b+e)/abs(f))) AS integer) from t1)) AS integer)-~ -+abs(abs(count(*))) | min(t1.e | t1.e-t1.b)*max(e)-max(t1.f) | min(c)*min(t1.b)+min(t1.e)-count(distinct 11) | min(b)*( - -count(distinct 19)))-count(*) from t1) FROM t1 WHERE d in (select count(*) from t1 union select case count(*) when max(17) |  -max(coalesce((select case t1.d*t1.e when t1.a then 11 else 13 end*f- -f from t1 where b in (select case ~abs(max(13)) when case ((max(c))) when cast(avg(t1.c) AS integer) then max(13) else count(distinct t1.d) end then cast(avg(t1.a) AS integer) else cast(avg(11) AS integer) end from t1 union select  -max(13) from t1)),13))*cast(avg(f) AS integer) then count(*) else count(distinct e) end from t1) and exists(select 1 from t1 where case d when  -(abs(17)/abs(t1.f)) then t1.a else t1.d end<t1.a)}
} {}
do_test randexpr-2.2562 {
  db eval {SELECT 13+(select  -abs(+cast(avg((select cast(avg(t1.e*(t1.c)- -(abs(b+e)/abs(f))) AS integer) from t1)) AS integer)-~ -+abs(abs(count(*))) | min(t1.e | t1.e-t1.b)*max(e)-max(t1.f) | min(c)*min(t1.b)+min(t1.e)-count(distinct 11) | min(b)*( - -count(distinct 19)))-count(*) from t1) FROM t1 WHERE NOT (d in (select count(*) from t1 union select case count(*) when max(17) |  -max(coalesce((select case t1.d*t1.e when t1.a then 11 else 13 end*f- -f from t1 where b in (select case ~abs(max(13)) when case ((max(c))) when cast(avg(t1.c) AS integer) then max(13) else count(distinct t1.d) end then cast(avg(t1.a) AS integer) else cast(avg(11) AS integer) end from t1 union select  -max(13) from t1)),13))*cast(avg(f) AS integer) then count(*) else count(distinct e) end from t1) and exists(select 1 from t1 where case d when  -(abs(17)/abs(t1.f)) then t1.a else t1.d end<t1.a))}
} {-261615}
do_test randexpr-2.2563 {
  db eval {SELECT 13+(select  -abs(+cast(avg((select cast(avg(t1.e*(t1.c)- -(abs(b+e)/abs(f))) AS integer) from t1)) AS integer)-~ -+abs(abs(count(*))) & min(t1.e & t1.e-t1.b)*max(e)-max(t1.f) & min(c)*min(t1.b)+min(t1.e)-count(distinct 11) & min(b)*( - -count(distinct 19)))-count(*) from t1) FROM t1 WHERE NOT (d in (select count(*) from t1 union select case count(*) when max(17) |  -max(coalesce((select case t1.d*t1.e when t1.a then 11 else 13 end*f- -f from t1 where b in (select case ~abs(max(13)) when case ((max(c))) when cast(avg(t1.c) AS integer) then max(13) else count(distinct t1.d) end then cast(avg(t1.a) AS integer) else cast(avg(11) AS integer) end from t1 union select  -max(13) from t1)),13))*cast(avg(f) AS integer) then count(*) else count(distinct e) end from t1) and exists(select 1 from t1 where case d when  -(abs(17)/abs(t1.f)) then t1.a else t1.d end<t1.a))}
} {-52}
do_test randexpr-2.2564 {
  db eval {SELECT c+c*(abs(t1.c+coalesce((select case when 17 not in (t1.f,t1.e,t1.d) or (17<t1.d) then case d when t1.a then t1.f else 11 end else t1.e end*d from t1 where 19 in (select abs(~count(distinct a)) from t1 union select case cast(avg(t1.c) AS integer) when  -max(t1.b) then min(c) else min(f) end+ -max(t1.d) from t1)),t1.b)+t1.e)/abs(17))+t1.b+ -t1.f+17-t1.c FROM t1 WHERE (13)+19>=19}
} {17017}
do_test randexpr-2.2565 {
  db eval {SELECT c+c*(abs(t1.c+coalesce((select case when 17 not in (t1.f,t1.e,t1.d) or (17<t1.d) then case d when t1.a then t1.f else 11 end else t1.e end*d from t1 where 19 in (select abs(~count(distinct a)) from t1 union select case cast(avg(t1.c) AS integer) when  -max(t1.b) then min(c) else min(f) end+ -max(t1.d) from t1)),t1.b)+t1.e)/abs(17))+t1.b+ -t1.f+17-t1.c FROM t1 WHERE NOT ((13)+19>=19)}
} {}
do_test randexpr-2.2566 {
  db eval {SELECT +case when not c in (select count(distinct t1.b) from t1 union select  -+(cast(avg(b*t1.b) AS integer))*max(case 17 when b then 13 else t1.a end)-count(distinct a) | cast(avg(t1.f) AS integer)+max(t1.d) from t1) then t1.e when a<=case t1.a when (e) then t1.d else d end then d else t1.b end*11-a | 17 | t1.a-f FROM t1 WHERE (c not in (t1.b,(select case case ++(min(19))*(count(distinct t1.a))+count(distinct e) | cast(avg(t1.e) AS integer) when min( -t1.d) then cast(avg(13) AS integer) else min(17) end*cast(avg(a) AS integer) when count(distinct  -b) then cast(avg(11) AS integer) else  - -(cast(avg(c) AS integer)) end from t1)-11+t1.e,t1.a) or d*case d when a then t1.c else 17 end*19 not between b and t1.c or  -17=b or f in (select a from t1 union select  -b from t1))}
} {-227}
do_test randexpr-2.2567 {
  db eval {SELECT +case when not c in (select count(distinct t1.b) from t1 union select  -+(cast(avg(b*t1.b) AS integer))*max(case 17 when b then 13 else t1.a end)-count(distinct a) | cast(avg(t1.f) AS integer)+max(t1.d) from t1) then t1.e when a<=case t1.a when (e) then t1.d else d end then d else t1.b end*11-a | 17 | t1.a-f FROM t1 WHERE NOT ((c not in (t1.b,(select case case ++(min(19))*(count(distinct t1.a))+count(distinct e) | cast(avg(t1.e) AS integer) when min( -t1.d) then cast(avg(13) AS integer) else min(17) end*cast(avg(a) AS integer) when count(distinct  -b) then cast(avg(11) AS integer) else  - -(cast(avg(c) AS integer)) end from t1)-11+t1.e,t1.a) or d*case d when a then t1.c else 17 end*19 not between b and t1.c or  -17=b or f in (select a from t1 union select  -b from t1)))}
} {}
do_test randexpr-2.2568 {
  db eval {SELECT +case when not c in (select count(distinct t1.b) from t1 union select  -+(cast(avg(b*t1.b) AS integer))*max(case 17 when b then 13 else t1.a end)-count(distinct a) & cast(avg(t1.f) AS integer)+max(t1.d) from t1) then t1.e when a<=case t1.a when (e) then t1.d else d end then d else t1.b end*11-a & 17 & t1.a-f FROM t1 WHERE (c not in (t1.b,(select case case ++(min(19))*(count(distinct t1.a))+count(distinct e) | cast(avg(t1.e) AS integer) when min( -t1.d) then cast(avg(13) AS integer) else min(17) end*cast(avg(a) AS integer) when count(distinct  -b) then cast(avg(11) AS integer) else  - -(cast(avg(c) AS integer)) end from t1)-11+t1.e,t1.a) or d*case d when a then t1.c else 17 end*19 not between b and t1.c or  -17=b or f in (select a from t1 union select  -b from t1))}
} {0}
do_test randexpr-2.2569 {
  db eval {SELECT coalesce((select (abs(f)/abs(coalesce((select max(19*b+d*coalesce((select max(t1.c) from t1 where case when d>=(abs((11))/abs(t1.a*13+(13)-d*e+11)) then t1.c when t1.c>=a then 19 else  -17 end*t1.e> -e),t1.f)) from t1 where 13<=t1.e),t1.d))) from t1 where t1.d in (select d from t1 union select a from t1)),t1.e) FROM t1 WHERE t1.c between (11) and coalesce((select max(b*case t1.c when t1.f then t1.f else 11 end) from t1 where +(select count(distinct case when f not between  -13 and 19 then t1.f++(f) | t1.e*(+13)* -(t1.c)-t1.b when 13=t1.d then 19 else t1.b end*t1.a) from t1) in (t1.e,11, -19)),d)+f}
} {0}
do_test randexpr-2.2570 {
  db eval {SELECT coalesce((select (abs(f)/abs(coalesce((select max(19*b+d*coalesce((select max(t1.c) from t1 where case when d>=(abs((11))/abs(t1.a*13+(13)-d*e+11)) then t1.c when t1.c>=a then 19 else  -17 end*t1.e> -e),t1.f)) from t1 where 13<=t1.e),t1.d))) from t1 where t1.d in (select d from t1 union select a from t1)),t1.e) FROM t1 WHERE NOT (t1.c between (11) and coalesce((select max(b*case t1.c when t1.f then t1.f else 11 end) from t1 where +(select count(distinct case when f not between  -13 and 19 then t1.f++(f) | t1.e*(+13)* -(t1.c)-t1.b when 13=t1.d then 19 else t1.b end*t1.a) from t1) in (t1.e,11, -19)),d)+f)}
} {}
do_test randexpr-2.2571 {
  db eval {SELECT case when (not 19>=(abs(t1.b)/abs(+f))) then case 13 when case t1.c when t1.b then f else 13 end then t1.e else t1.a end+coalesce((select max(c) from t1 where a not between t1.d*17*coalesce((select max(e*b) from t1 where t1.a=11),t1.c) and t1.d),t1.d) when (case when t1.d not in (e,t1.a,t1.b) then 19 else t1.f end between t1.c and 19) then t1.e else 11 end FROM t1 WHERE t1.b*+c>=17}
} {11}
do_test randexpr-2.2572 {
  db eval {SELECT case when (not 19>=(abs(t1.b)/abs(+f))) then case 13 when case t1.c when t1.b then f else 13 end then t1.e else t1.a end+coalesce((select max(c) from t1 where a not between t1.d*17*coalesce((select max(e*b) from t1 where t1.a=11),t1.c) and t1.d),t1.d) when (case when t1.d not in (e,t1.a,t1.b) then 19 else t1.f end between t1.c and 19) then t1.e else 11 end FROM t1 WHERE NOT (t1.b*+c>=17)}
} {}
do_test randexpr-2.2573 {
  db eval {SELECT case when d-t1.c<>e then c when (11 not between 13 and 13) then 13 else  -case when c*t1.d>=b*b then  -t1.f else b-t1.c | d*(case t1.d when  -case t1.b when t1.b then t1.b else 19 end*19*(t1.d) then 13 else 19 end) end+19*11 end+b FROM t1 WHERE ~~case when t1.d+(abs(t1.b+coalesce((select coalesce((select max(b-a-a) from t1 where 17 not in (e,case when (t1.d)<=t1.f or  -a not between c and t1.b then c when  -19 in ( -d,(t1.a),19) then b else f end,t1.e)), -13) from t1 where not b in (t1.b, -t1.b,c)),e))/abs(11)) between 13 and d then (t1.b) when t1.e<13 then 19 else a end-(19)-d*t1.d not in (d,t1.c,13)}
} {500}
do_test randexpr-2.2574 {
  db eval {SELECT case when d-t1.c<>e then c when (11 not between 13 and 13) then 13 else  -case when c*t1.d>=b*b then  -t1.f else b-t1.c | d*(case t1.d when  -case t1.b when t1.b then t1.b else 19 end*19*(t1.d) then 13 else 19 end) end+19*11 end+b FROM t1 WHERE NOT (~~case when t1.d+(abs(t1.b+coalesce((select coalesce((select max(b-a-a) from t1 where 17 not in (e,case when (t1.d)<=t1.f or  -a not between c and t1.b then c when  -19 in ( -d,(t1.a),19) then b else f end,t1.e)), -13) from t1 where not b in (t1.b, -t1.b,c)),e))/abs(11)) between 13 and d then (t1.b) when t1.e<13 then 19 else a end-(19)-d*t1.d not in (d,t1.c,13))}
} {}
do_test randexpr-2.2575 {
  db eval {SELECT case when d-t1.c<>e then c when (11 not between 13 and 13) then 13 else  -case when c*t1.d>=b*b then  -t1.f else b-t1.c & d*(case t1.d when  -case t1.b when t1.b then t1.b else 19 end*19*(t1.d) then 13 else 19 end) end+19*11 end+b FROM t1 WHERE ~~case when t1.d+(abs(t1.b+coalesce((select coalesce((select max(b-a-a) from t1 where 17 not in (e,case when (t1.d)<=t1.f or  -a not between c and t1.b then c when  -19 in ( -d,(t1.a),19) then b else f end,t1.e)), -13) from t1 where not b in (t1.b, -t1.b,c)),e))/abs(11)) between 13 and d then (t1.b) when t1.e<13 then 19 else a end-(19)-d*t1.d not in (d,t1.c,13)}
} {500}
do_test randexpr-2.2576 {
  db eval {SELECT 19+t1.d+d-t1.c*case when 11 not between e and ~c+(select min((abs(t1.b*t1.b)/abs(+t1.c-e))) from t1) then 17 when case when 17*13 not in (t1.b,(abs(~c)/abs( -17-e)),(t1.e)) then 17 else (t1.c) end+c+t1.f not in (t1.f,19,t1.f) then  -t1.e else t1.f end FROM t1 WHERE (+13) between +b and t1.e+11}
} {}
do_test randexpr-2.2577 {
  db eval {SELECT 19+t1.d+d-t1.c*case when 11 not between e and ~c+(select min((abs(t1.b*t1.b)/abs(+t1.c-e))) from t1) then 17 when case when 17*13 not in (t1.b,(abs(~c)/abs( -17-e)),(t1.e)) then 17 else (t1.c) end+c+t1.f not in (t1.f,19,t1.f) then  -t1.e else t1.f end FROM t1 WHERE NOT ((+13) between +b and t1.e+11)}
} {-4281}
do_test randexpr-2.2578 {
  db eval {SELECT 17+d*~(abs(coalesce((select 19 | f | e*~+((abs(e)/abs(+19))-t1.c-case 17 when t1.f then f else 19 end-17) from t1 where (e in (select ~(11) from t1 union select case when (f)>a then b when e between  -e and t1.b then 17 else t1.f end*t1.a from t1))),t1.b)*e)/abs(17))-t1.a-19 FROM t1 WHERE t1.e not in (d,e,case 19 when  - -~case when exists(select 1 from t1 where 17 not in (t1.d,t1.a,coalesce((select max(11-a) from t1 where coalesce((select +c from t1 where exists(select 1 from t1 where case when t1.f not in (19+(f),d,t1.c) then t1.c when (exists(select 1 from t1 where t1.c>19)) then 19 else f end not between a and t1.f)),t1.c)<=b),17))) then t1.d-11 else t1.b end then (d) else t1.f end-(c))}
} {}
do_test randexpr-2.2579 {
  db eval {SELECT 17+d*~(abs(coalesce((select 19 | f | e*~+((abs(e)/abs(+19))-t1.c-case 17 when t1.f then f else 19 end-17) from t1 where (e in (select ~(11) from t1 union select case when (f)>a then b when e between  -e and t1.b then 17 else t1.f end*t1.a from t1))),t1.b)*e)/abs(17))-t1.a-19 FROM t1 WHERE NOT (t1.e not in (d,e,case 19 when  - -~case when exists(select 1 from t1 where 17 not in (t1.d,t1.a,coalesce((select max(11-a) from t1 where coalesce((select +c from t1 where exists(select 1 from t1 where case when t1.f not in (19+(f),d,t1.c) then t1.c when (exists(select 1 from t1 where t1.c>19)) then 19 else f end not between a and t1.f)),t1.c)<=b),17))) then t1.d-11 else t1.b end then (d) else t1.f end-(c)))}
} {-2353302}
do_test randexpr-2.2580 {
  db eval {SELECT 17+d*~(abs(coalesce((select 19 & f & e*~+((abs(e)/abs(+19))-t1.c-case 17 when t1.f then f else 19 end-17) from t1 where (e in (select ~(11) from t1 union select case when (f)>a then b when e between  -e and t1.b then 17 else t1.f end*t1.a from t1))),t1.b)*e)/abs(17))-t1.a-19 FROM t1 WHERE NOT (t1.e not in (d,e,case 19 when  - -~case when exists(select 1 from t1 where 17 not in (t1.d,t1.a,coalesce((select max(11-a) from t1 where coalesce((select +c from t1 where exists(select 1 from t1 where case when t1.f not in (19+(f),d,t1.c) then t1.c when (exists(select 1 from t1 where t1.c>19)) then 19 else f end not between a and t1.f)),t1.c)<=b),17))) then t1.d-11 else t1.b end then (d) else t1.f end-(c)))}
} {-2353302}
do_test randexpr-2.2581 {
  db eval {SELECT case a when b-coalesce((select coalesce((select max(c-(abs((19))/abs(coalesce((select t1.c+d from t1 where 17 not in (d,t1.c, -t1.e)),t1.b)-(e)))) from t1 where t1.d in (t1.e,e,t1.f)),(e)) from t1 where t1.b=t1.e or t1.b not between b and e or t1.f not between t1.b and e or c not between  -b and a),d) then 13 else 17 end FROM t1 WHERE a+17+(17) in ( -t1.a,13,coalesce((select max(e) from t1 where b+a-13<=b),e)) or e in (select abs( -+~abs(+(min(c))))+count(distinct b) from t1 union select abs(+((max(t1.c)) | min(t1.b))) from t1) and 13 not between f and 19 or not e not in ( -17,13,t1.a)}
} {}
do_test randexpr-2.2582 {
  db eval {SELECT case a when b-coalesce((select coalesce((select max(c-(abs((19))/abs(coalesce((select t1.c+d from t1 where 17 not in (d,t1.c, -t1.e)),t1.b)-(e)))) from t1 where t1.d in (t1.e,e,t1.f)),(e)) from t1 where t1.b=t1.e or t1.b not between b and e or t1.f not between t1.b and e or c not between  -b and a),d) then 13 else 17 end FROM t1 WHERE NOT (a+17+(17) in ( -t1.a,13,coalesce((select max(e) from t1 where b+a-13<=b),e)) or e in (select abs( -+~abs(+(min(c))))+count(distinct b) from t1 union select abs(+((max(t1.c)) | min(t1.b))) from t1) and 13 not between f and 19 or not e not in ( -17,13,t1.a))}
} {17}
do_test randexpr-2.2583 {
  db eval {SELECT case when not t1.e between 17 and a then 11+ -(select ~case count(distinct +13+t1.c | c*13)- -+ -cast(avg(c) AS integer)-min(19)+case  -max(c) when  -cast(avg(b) AS integer) then max(11) else max(13) end+count(distinct t1.f) when max(( -d)) then cast(avg(t1.c) AS integer) else (min((t1.b))) end | cast(avg(t1.f) AS integer)*count(distinct 17) from t1)+b else +t1.e |  -t1.a-a end FROM t1 WHERE (t1.f<=~c+f)}
} {}
do_test randexpr-2.2584 {
  db eval {SELECT case when not t1.e between 17 and a then 11+ -(select ~case count(distinct +13+t1.c | c*13)- -+ -cast(avg(c) AS integer)-min(19)+case  -max(c) when  -cast(avg(b) AS integer) then max(11) else max(13) end+count(distinct t1.f) when max(( -d)) then cast(avg(t1.c) AS integer) else (min((t1.b))) end | cast(avg(t1.f) AS integer)*count(distinct 17) from t1)+b else +t1.e |  -t1.a-a end FROM t1 WHERE NOT ((t1.f<=~c+f))}
} {340}
do_test randexpr-2.2585 {
  db eval {SELECT case when not t1.e between 17 and a then 11+ -(select ~case count(distinct +13+t1.c & c*13)- -+ -cast(avg(c) AS integer)-min(19)+case  -max(c) when  -cast(avg(b) AS integer) then max(11) else max(13) end+count(distinct t1.f) when max(( -d)) then cast(avg(t1.c) AS integer) else (min((t1.b))) end & cast(avg(t1.f) AS integer)*count(distinct 17) from t1)+b else +t1.e &  -t1.a-a end FROM t1 WHERE NOT ((t1.f<=~c+f))}
} {-317}
do_test randexpr-2.2586 {
  db eval {SELECT t1.f-coalesce((select max(case when b<>~t1.f then b+f else coalesce((select t1.c from t1 where case a when 19*t1.e+a then 19 else 13 end between 13 and a),t1.d)+b end) from t1 where (t1.c) in (select  -~min(c) | max(t1.d) from t1 union select  -cast(avg(t1.a) AS integer) from t1) and t1.c in (t1.a,d,11) or 11<t1.c),t1.a) FROM t1 WHERE not exists(select 1 from t1 where +case when 19+~coalesce((select max(+c*t1.c-d) from t1 where t1.f>13 and not exists(select 1 from t1 where (((t1.d<=t1.b))))),e)*b*t1.f>t1.a or not exists(select 1 from t1 where (13) not in (11,t1.b,t1.c)) then c+d else t1.e end>=t1.f) or (not exists(select 1 from t1 where  -11 in (c,t1.d, -a)) or a not between  - - -(b) and b) or 13 between t1.b and f}
} {-200}
do_test randexpr-2.2587 {
  db eval {SELECT t1.f-coalesce((select max(case when b<>~t1.f then b+f else coalesce((select t1.c from t1 where case a when 19*t1.e+a then 19 else 13 end between 13 and a),t1.d)+b end) from t1 where (t1.c) in (select  -~min(c) | max(t1.d) from t1 union select  -cast(avg(t1.a) AS integer) from t1) and t1.c in (t1.a,d,11) or 11<t1.c),t1.a) FROM t1 WHERE NOT (not exists(select 1 from t1 where +case when 19+~coalesce((select max(+c*t1.c-d) from t1 where t1.f>13 and not exists(select 1 from t1 where (((t1.d<=t1.b))))),e)*b*t1.f>t1.a or not exists(select 1 from t1 where (13) not in (11,t1.b,t1.c)) then c+d else t1.e end>=t1.f) or (not exists(select 1 from t1 where  -11 in (c,t1.d, -a)) or a not between  - - -(b) and b) or 13 between t1.b and f)}
} {}
do_test randexpr-2.2588 {
  db eval {SELECT t1.f-coalesce((select max(case when b<>~t1.f then b+f else coalesce((select t1.c from t1 where case a when 19*t1.e+a then 19 else 13 end between 13 and a),t1.d)+b end) from t1 where (t1.c) in (select  -~min(c) & max(t1.d) from t1 union select  -cast(avg(t1.a) AS integer) from t1) and t1.c in (t1.a,d,11) or 11<t1.c),t1.a) FROM t1 WHERE not exists(select 1 from t1 where +case when 19+~coalesce((select max(+c*t1.c-d) from t1 where t1.f>13 and not exists(select 1 from t1 where (((t1.d<=t1.b))))),e)*b*t1.f>t1.a or not exists(select 1 from t1 where (13) not in (11,t1.b,t1.c)) then c+d else t1.e end>=t1.f) or (not exists(select 1 from t1 where  -11 in (c,t1.d, -a)) or a not between  - - -(b) and b) or 13 between t1.b and f}
} {-200}
do_test randexpr-2.2589 {
  db eval {SELECT case when ( -c=~t1.b and coalesce((select max(coalesce((select b from t1 where t1.f between case when t1.e between t1.f and 19 then (t1.b) else t1.a end and t1.f),a)) from t1 where 11=t1.f),t1.f)+t1.c=d) and a>t1.c and 19> -19 and exists(select 1 from t1 where (b=17)) and 17 between 19 and 13 then 19*case (d) when c then b else a end when t1.d not in ( -t1.a,f,13) then  -t1.f else (d) end FROM t1 WHERE 11*case when d | (abs(+t1.e-t1.e*b+(select case abs(count(*)) when count(*) then count(*) else cast(avg(t1.c) AS integer) end from t1)*17+(d)-13-11)/abs(c))-f- -t1.c-d | t1.a not between 19 and f then t1.a when t1.d in (select 11 from t1 union select d from t1) then e else e end-t1.c between 19 and c}
} {}
do_test randexpr-2.2590 {
  db eval {SELECT case when ( -c=~t1.b and coalesce((select max(coalesce((select b from t1 where t1.f between case when t1.e between t1.f and 19 then (t1.b) else t1.a end and t1.f),a)) from t1 where 11=t1.f),t1.f)+t1.c=d) and a>t1.c and 19> -19 and exists(select 1 from t1 where (b=17)) and 17 between 19 and 13 then 19*case (d) when c then b else a end when t1.d not in ( -t1.a,f,13) then  -t1.f else (d) end FROM t1 WHERE NOT (11*case when d | (abs(+t1.e-t1.e*b+(select case abs(count(*)) when count(*) then count(*) else cast(avg(t1.c) AS integer) end from t1)*17+(d)-13-11)/abs(c))-f- -t1.c-d | t1.a not between 19 and f then t1.a when t1.d in (select 11 from t1 union select d from t1) then e else e end-t1.c between 19 and c)}
} {-600}
do_test randexpr-2.2591 {
  db eval {SELECT +case when t1.a-17 in (select cast(avg(t1.a*t1.d+(abs( -t1.e)/abs(case when t1.e>t1.a or a>t1.d then t1.f when 13<11 then t1.b else c end))*t1.d) AS integer) from t1 union select count(distinct t1.a) from t1) then t1.c when d in (select +count(distinct b)-case case  - -cast(avg(d) AS integer) when case max(11) when min(17) then count(*) else (cast(avg(a) AS integer)) end then  -count(*) else  -cast(avg(17) AS integer) end when max(19) then count(distinct t1.f) else count(distinct  -t1.d) end | min(e) from t1 union select count(*) from t1) then t1.d else t1.a end FROM t1 WHERE  -+b>=19}
} {}
do_test randexpr-2.2592 {
  db eval {SELECT +case when t1.a-17 in (select cast(avg(t1.a*t1.d+(abs( -t1.e)/abs(case when t1.e>t1.a or a>t1.d then t1.f when 13<11 then t1.b else c end))*t1.d) AS integer) from t1 union select count(distinct t1.a) from t1) then t1.c when d in (select +count(distinct b)-case case  - -cast(avg(d) AS integer) when case max(11) when min(17) then count(*) else (cast(avg(a) AS integer)) end then  -count(*) else  -cast(avg(17) AS integer) end when max(19) then count(distinct t1.f) else count(distinct  -t1.d) end | min(e) from t1 union select count(*) from t1) then t1.d else t1.a end FROM t1 WHERE NOT ( -+b>=19)}
} {100}
do_test randexpr-2.2593 {
  db eval {SELECT +case when t1.a-17 in (select cast(avg(t1.a*t1.d+(abs( -t1.e)/abs(case when t1.e>t1.a or a>t1.d then t1.f when 13<11 then t1.b else c end))*t1.d) AS integer) from t1 union select count(distinct t1.a) from t1) then t1.c when d in (select +count(distinct b)-case case  - -cast(avg(d) AS integer) when case max(11) when min(17) then count(*) else (cast(avg(a) AS integer)) end then  -count(*) else  -cast(avg(17) AS integer) end when max(19) then count(distinct t1.f) else count(distinct  -t1.d) end & min(e) from t1 union select count(*) from t1) then t1.d else t1.a end FROM t1 WHERE NOT ( -+b>=19)}
} {100}
do_test randexpr-2.2594 {
  db eval {SELECT case ~(t1.f)-t1.b-t1.e*c when coalesce((select case when d*13 | d=case when 19 between b+e+a | t1.f and a+11+t1.b*(t1.f) then d else b end then t1.c when e not between 13 and 13 then 19 else a end from t1 where 13=t1.b),c) then t1.c else b end FROM t1 WHERE not t1.d in (select cast(avg(t1.e) AS integer)-~~min(coalesce((select (abs(11)/abs(11+(select count(*)+min(17)+ -cast(avg(t1.d) AS integer) from t1)*13+coalesce((select max(b) from t1 where (t1.c)<>t1.e or e<(a)),13)-d*t1.c))*t1.b from t1 where 19<=e),c))++abs(count(distinct t1.b))+~max(11)*max(11) from t1 union select +max(11) from t1)}
} {200}
do_test randexpr-2.2595 {
  db eval {SELECT case ~(t1.f)-t1.b-t1.e*c when coalesce((select case when d*13 | d=case when 19 between b+e+a | t1.f and a+11+t1.b*(t1.f) then d else b end then t1.c when e not between 13 and 13 then 19 else a end from t1 where 13=t1.b),c) then t1.c else b end FROM t1 WHERE NOT (not t1.d in (select cast(avg(t1.e) AS integer)-~~min(coalesce((select (abs(11)/abs(11+(select count(*)+min(17)+ -cast(avg(t1.d) AS integer) from t1)*13+coalesce((select max(b) from t1 where (t1.c)<>t1.e or e<(a)),13)-d*t1.c))*t1.b from t1 where 19<=e),c))++abs(count(distinct t1.b))+~max(11)*max(11) from t1 union select +max(11) from t1))}
} {}
do_test randexpr-2.2596 {
  db eval {SELECT case ~(t1.f)-t1.b-t1.e*c when coalesce((select case when d*13 & d=case when 19 between b+e+a & t1.f and a+11+t1.b*(t1.f) then d else b end then t1.c when e not between 13 and 13 then 19 else a end from t1 where 13=t1.b),c) then t1.c else b end FROM t1 WHERE not t1.d in (select cast(avg(t1.e) AS integer)-~~min(coalesce((select (abs(11)/abs(11+(select count(*)+min(17)+ -cast(avg(t1.d) AS integer) from t1)*13+coalesce((select max(b) from t1 where (t1.c)<>t1.e or e<(a)),13)-d*t1.c))*t1.b from t1 where 19<=e),c))++abs(count(distinct t1.b))+~max(11)*max(11) from t1 union select +max(11) from t1)}
} {200}
do_test randexpr-2.2597 {
  db eval {SELECT t1.d+(abs(11)/abs(e*~(select  -+ -case min(t1.e) when count(distinct case when (exists(select 1 from t1 where (t1.d not in (19+11,t1.e,t1.c)))) then c*b-t1.a else  -c end) then count(*)+case (cast(avg(a) AS integer))-count(distinct f) when  -(count(*)) then count(distinct e) else max(t1.b) end- -count(distinct 17)* -min(t1.c) else count(distinct  -19) end-count(distinct b) | cast(avg(19) AS integer) from t1)))-~t1.c FROM t1 WHERE c*coalesce((select e from t1 where case when exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select +b | 13 from t1 where ((17<(select (+~min(coalesce((select t1.c from t1 where case e when 13 then a else 11 end not in ( -b,t1.b,e)),(a)))) from t1)+d-19))),17) not between t1.b and t1.a)) then 11*d else t1.a end in (select c from t1 union select t1.e from t1)),t1.f) not between ( -d) and 13}
} {701}
do_test randexpr-2.2598 {
  db eval {SELECT t1.d+(abs(11)/abs(e*~(select  -+ -case min(t1.e) when count(distinct case when (exists(select 1 from t1 where (t1.d not in (19+11,t1.e,t1.c)))) then c*b-t1.a else  -c end) then count(*)+case (cast(avg(a) AS integer))-count(distinct f) when  -(count(*)) then count(distinct e) else max(t1.b) end- -count(distinct 17)* -min(t1.c) else count(distinct  -19) end-count(distinct b) | cast(avg(19) AS integer) from t1)))-~t1.c FROM t1 WHERE NOT (c*coalesce((select e from t1 where case when exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select +b | 13 from t1 where ((17<(select (+~min(coalesce((select t1.c from t1 where case e when 13 then a else 11 end not in ( -b,t1.b,e)),(a)))) from t1)+d-19))),17) not between t1.b and t1.a)) then 11*d else t1.a end in (select c from t1 union select t1.e from t1)),t1.f) not between ( -d) and 13)}
} {}
do_test randexpr-2.2599 {
  db eval {SELECT t1.d+(abs(11)/abs(e*~(select  -+ -case min(t1.e) when count(distinct case when (exists(select 1 from t1 where (t1.d not in (19+11,t1.e,t1.c)))) then c*b-t1.a else  -c end) then count(*)+case (cast(avg(a) AS integer))-count(distinct f) when  -(count(*)) then count(distinct e) else max(t1.b) end- -count(distinct 17)* -min(t1.c) else count(distinct  -19) end-count(distinct b) & cast(avg(19) AS integer) from t1)))-~t1.c FROM t1 WHERE c*coalesce((select e from t1 where case when exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select +b | 13 from t1 where ((17<(select (+~min(coalesce((select t1.c from t1 where case e when 13 then a else 11 end not in ( -b,t1.b,e)),(a)))) from t1)+d-19))),17) not between t1.b and t1.a)) then 11*d else t1.a end in (select c from t1 union select t1.e from t1)),t1.f) not between ( -d) and 13}
} {701}
finish_test

Added test/rdonly.test.





























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 2007 April 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure SQLite treats a database
# as readonly if its write version is set to  high.
#
# $Id: rdonly.test,v 1.2 2008/07/08 10:19:58 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Create a database.
#
do_test rdonly-1.1 {
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT * FROM t1;
  }
} {1}

# Changes the write version from 1 to 2.  Verify that the database
# can be read but not written.
#
do_test rdonly-1.2 {
  db close
  hexio_get_int [hexio_read test.db 18 1]
} 1
do_test rdonly-1.3 {
  hexio_write test.db 18 02
  sqlite3 db test.db
  execsql {
    SELECT * FROM t1;
  }
} {1}
do_test rdonly-1.4 {
  catchsql {
    INSERT INTO t1 VALUES(2)
  }
} {1 {attempt to write a readonly database}}

# Change the write version back to 1.  Verify that the database
# is read-write again.
#
do_test rdonly-1.5 {
  db close
  hexio_write test.db 18 01
  sqlite3 db test.db
  catchsql {
    INSERT INTO t1 VALUES(2);
    SELECT * FROM t1;
  }
} {0 {1 2}}

# Now, after connection [db] has loaded the database schema, modify the
# write-version of the file (and the change-counter, so that the 
# write-version is reloaded). This way, SQLite does not discover that
# the database is read-only until after it is locked.
#
do_test rdonly-1.6 {
  hexio_write test.db 18 02              ; # write-version
  hexio_write test.db 24 11223344        ; # change-counter
  catchsql {
    INSERT INTO t1 VALUES(2);
  }
} {1 {attempt to write a readonly database}}

finish_test

Added test/reindex.test.























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# 2004 November 5
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
# This file implements tests for the REINDEX command.
#
# $Id: reindex.test,v 1.4 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# There is nothing to test if REINDEX is disable for this build.
#
ifcapable {!reindex} {
  finish_test
  return
}

# Basic sanity checks.
#
do_test reindex-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    CREATE INDEX i1 ON t1(a);
    REINDEX;
  }
} {}
integrity_check reindex-1.2
do_test reindex-1.3 {
  execsql {
    REINDEX t1;
  }
} {}
integrity_check reindex-1.4
do_test reindex-1.5 {
  execsql {
    REINDEX i1;
  }
} {}
integrity_check reindex-1.6
do_test reindex-1.7 {
  execsql {
    REINDEX main.t1;
  }
} {}
do_test reindex-1.8 {
  execsql {
    REINDEX main.i1;
  }
} {}
do_test reindex-1.9 {
  catchsql {
    REINDEX bogus
  }
} {1 {unable to identify the object to be reindexed}}

# Set up a table for testing that includes several different collating
# sequences including some that we can modify.
#
do_test reindex-2.1 {
  proc c1 {a b} {
    return [expr {-[string compare $a $b]}]
  }
  proc c2 {a b} {
    return [expr {-[string compare [string tolower $a] [string tolower $b]]}]
  }
  db collate c1 c1
  db collate c2 c2
  execsql {
    CREATE TABLE t2(
      a TEXT PRIMARY KEY COLLATE c1,
      b TEXT UNIQUE COLLATE c2,
      c TEXT COLLATE nocase,
      d TEST COLLATE binary
    );
    INSERT INTO t2 VALUES('abc','abc','abc','abc');
    INSERT INTO t2 VALUES('ABCD','ABCD','ABCD','ABCD');
    INSERT INTO t2 VALUES('bcd','bcd','bcd','bcd');
    INSERT INTO t2 VALUES('BCDE','BCDE','BCDE','BCDE');
    SELECT a FROM t2 ORDER BY a;
  }
} {bcd abc BCDE ABCD}
do_test reindex-2.2 {
  execsql {
    SELECT b FROM t2 ORDER BY b;
  }
} {BCDE bcd ABCD abc}
do_test reindex-2.3 {
  execsql {
    SELECT c FROM t2 ORDER BY c;
  }
} {abc ABCD bcd BCDE}
do_test reindex-2.4 {
  execsql {
    SELECT d FROM t2 ORDER BY d;
  }
} {ABCD BCDE abc bcd}

# Change a collating sequence function.  Verify that REINDEX rebuilds
# the index.
#
do_test reindex-2.5 {
  proc c1 {a b} {
    return [string compare $a $b]
  }
  execsql {
    SELECT a FROM t2 ORDER BY a;
  }
} {bcd abc BCDE ABCD}
ifcapable {integrityck} {
  do_test reindex-2.5.1 {
    string equal ok [execsql {PRAGMA integrity_check}]
  } {0}
}
do_test reindex-2.6 {
  execsql {
    REINDEX c2;
    SELECT a FROM t2 ORDER BY a;
  }
} {bcd abc BCDE ABCD}
do_test reindex-2.7 {
  execsql {
    REINDEX t1;
    SELECT a FROM t2 ORDER BY a;
  }
} {bcd abc BCDE ABCD}
do_test reindex-2.8 {
  execsql {
    REINDEX c1;
    SELECT a FROM t2 ORDER BY a;
  }
} {ABCD BCDE abc bcd}
integrity_check reindex-2.8.1

# Try to REINDEX an index for which the collation sequence is not available.
#
do_test reindex-3.1 {
  sqlite3 db2 test.db
  catchsql {
    REINDEX c1;
  } db2
} {1 {no such collation sequence: c1}}
do_test reindex-3.2 {
  proc need_collate {collation} {
    db2 collate c1 c1
  }
  db2 collation_needed need_collate
  catchsql {
    REINDEX c1;
  } db2
} {0 {}}
do_test reindex-3.3 {
  catchsql {
    REINDEX;
  } db2
} {1 {no such collation sequence: c2}}

do_test reindex-3.99 {
  db2 close
} {}

finish_test

Added test/rollback.test.

















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# 2004 June 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is verifying that a rollback in one statement
# caused by an ON CONFLICT ROLLBACK clause aborts any other pending
# statements.
#
# $Id: rollback.test,v 1.11 2009/06/26 07:12:07 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

set DB [sqlite3_connection_pointer db]

do_test rollback-1.1 {
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES(3);
    INSERT INTO t1 VALUES(4);
    SELECT * FROM t1;
  }
} {1 2 3 4}

ifcapable conflict {
  do_test rollback-1.2 {
    execsql {
      CREATE TABLE t3(a unique on conflict rollback);
      INSERT INTO t3 SELECT a FROM t1;
      BEGIN;
      INSERT INTO t1 SELECT * FROM t1;
    }
  } {}
}
do_test rollback-1.3 {
  set STMT [sqlite3_prepare $DB "SELECT a FROM t1" -1 TAIL]
  sqlite3_step $STMT
} {SQLITE_ROW}

ifcapable conflict {
  # This causes a ROLLBACK, which deletes the table out from underneath the
  # SELECT statement.
  #
  do_test rollback-1.4 {
    catchsql {
      INSERT INTO t3 SELECT a FROM t1;
    }
  } {1 {column a is not unique}}
  
  # Try to continue with the SELECT statement
  #
  do_test rollback-1.5 {
    sqlite3_step $STMT
  } {SQLITE_ERROR}

  # Restart the SELECT statement
  #
  do_test rollback-1.6 { sqlite3_reset $STMT } {SQLITE_ABORT}
} else {
  do_test rollback-1.6 { sqlite3_reset $STMT } {SQLITE_OK}
}

do_test rollback-1.7 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test rollback-1.8 {
  sqlite3_step $STMT
} {SQLITE_ROW}
do_test rollback-1.9 {
  sqlite3_finalize $STMT
} {SQLITE_OK}

set permutation ""
catch {set permutation $::permutations_test_prefix}
if {$tcl_platform(platform) == "unix" 
 && $permutation ne "onefile"
 && $permutation ne "inmemory_journal"
} {
  do_test rollback-2.1 {
    execsql {
      BEGIN;
      INSERT INTO t3 VALUES('hello world');
    }
    file copy -force test.db testA.db
    file copy -force test.db-journal testA.db-journal
    execsql {
      COMMIT;
    }
  } {}

  # At this point files testA.db and testA.db-journal are present in the
  # file system. This block adds a master-journal file pointer to the
  # end of testA.db-journal. The master-journal file does not exist.
  # 
  set mj [file normalize testA.db-mj-123]
  binary scan $mj c* a
  set cksum 0
  foreach i $a { incr cksum $i }
  set mj_pgno [expr $sqlite_pending_byte / 1024]
  set zAppend [binary format Ia*IIa8 $mj_pgno $mj [string length $mj] $cksum \
    "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7"
  ]
  set iOffset [expr (([file size testA.db-journal] + 511)/512)*512]
  set fd [open testA.db-journal a+]
  fconfigure $fd -encoding binary -translation binary
  seek $fd $iOffset
  puts -nonewline $fd $zAppend

  # Also, fix the first journal-header in the journal-file. Because the
  # journal file has not yet been synced, the 8-byte magic string at the
  # start of the first journal-header has not been written by SQLite.
  # So write it now.
  seek $fd 0
  puts -nonewline $fd "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7"
  close $fd

  # Open a handle on testA.db and use it to query the database. At one
  # point the first query would attempt a hot rollback, attempt to open
  # the master-journal file and return SQLITE_CANTOPEN when it could not
  # be opened. This is incorrect, it should simply delete the journal
  # file and proceed with the query.
  # 
  do_test rollback-2.2 {
    sqlite3 db2 testA.db
    execsql {
      SELECT distinct tbl_name FROM sqlite_master;
    } db2
  } {t1 t3}
  if {[lsearch {exclusive persistent_journal no_journal} $permutation]<0} {
    do_test rollback-2.3 {
      file exists testA.db-journal
    } 0
  }
  do_test rollback-2.4 {
    execsql {
      SELECT distinct tbl_name FROM sqlite_master;
    } db2
  } {t1 t3}

  db2 close
}

finish_test

Added test/rowhash.test.

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 2009 April 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this file is the code in rowhash.c.
#
# $Id: rowhash.test,v 1.5 2009/05/02 12:02:02 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test rowhash-1.1 {
  execsql {
    CREATE TABLE t1(id INTEGER PRIMARY KEY, a, b, c);
    CREATE INDEX i1 ON t1(a);
    CREATE INDEX i2 ON t1(b);
    CREATE INDEX i3 ON t1(c);
  }
} {}

proc do_keyset_test {name lKey} {
  db transaction {
    execsql { DELETE FROM t1 }
    foreach key $lKey {
      execsql { INSERT OR IGNORE INTO t1 VALUES($key, 'a', 'b', 'c') }
    }
  }
  do_test $name {
    lsort -integer [execsql {
      SELECT id FROM t1 WHERE a = 'a' OR b = 'b' OR c = 'c';
    }]
  } [lsort -integer -unique $lKey]
}

do_keyset_test rowhash-2.1 {1 2 3}
do_keyset_test rowhash-2.2 {0 1 2 3}
do_keyset_test rowhash-2.3 {62 125 188}
if {[working_64bit_int]} {
  expr srand(1)
  for {set i 4} {$i < 10} {incr i} {
    for {set j 0} {$j < 5000} {incr j} {
        lappend L [expr int(rand()*1000000000)]
    }
    do_keyset_test rowhash-2.$i $L
  }
}

finish_test

Added test/rowid.test.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the magic ROWID column that is
# found on all tables.
#
# $Id: rowid.test,v 1.21 2009/06/26 15:14:55 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Basic ROWID functionality tests.
#
do_test rowid-1.1 {
  execsql {
    CREATE TABLE t1(x int, y int);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    SELECT x FROM t1 ORDER BY y;
  }
} {1 3}
do_test rowid-1.2 {
  set r [execsql {SELECT rowid FROM t1 ORDER BY x}]
  global x2rowid rowid2x
  set x2rowid(1) [lindex $r 0]
  set x2rowid(3) [lindex $r 1]
  set rowid2x($x2rowid(1)) 1
  set rowid2x($x2rowid(3)) 3
  llength $r
} {2}
do_test rowid-1.3 {
  global x2rowid
  set sql "SELECT x FROM t1 WHERE rowid==$x2rowid(1)"
  execsql $sql
} {1}
do_test rowid-1.4 {
  global x2rowid
  set sql "SELECT x FROM t1 WHERE rowid==$x2rowid(3)"
  execsql $sql
} {3}
do_test rowid-1.5 {
  global x2rowid
  set sql "SELECT x FROM t1 WHERE oid==$x2rowid(1)"
  execsql $sql
} {1}
do_test rowid-1.6 {
  global x2rowid
  set sql "SELECT x FROM t1 WHERE OID==$x2rowid(3)"
  execsql $sql
} {3}
do_test rowid-1.7 {
  global x2rowid
  set sql "SELECT x FROM t1 WHERE _rowid_==$x2rowid(1)"
  execsql $sql
} {1}
do_test rowid-1.7.1 {
  while 1 {
    set norow [expr {int(rand()*1000000)}]
    if {$norow!=$x2rowid(1) && $norow!=$x2rowid(3)} break
  }
  execsql "SELECT x FROM t1 WHERE rowid=$norow"
} {}
do_test rowid-1.8 {
  global x2rowid
  set v [execsql {SELECT x, oid FROM t1 order by x}]
  set v2 [list 1 $x2rowid(1) 3 $x2rowid(3)]
  expr {$v==$v2}
} {1}
do_test rowid-1.9 {
  global x2rowid
  set v [execsql {SELECT x, RowID FROM t1 order by x}]
  set v2 [list 1 $x2rowid(1) 3 $x2rowid(3)]
  expr {$v==$v2}
} {1}
do_test rowid-1.10 {
  global x2rowid
  set v [execsql {SELECT x, _rowid_ FROM t1 order by x}]
  set v2 [list 1 $x2rowid(1) 3 $x2rowid(3)]
  expr {$v==$v2}
} {1}

# We can insert or update the ROWID column.
#
do_test rowid-2.1 {
  catchsql {
    INSERT INTO t1(rowid,x,y) VALUES(1234,5,6);
    SELECT rowid, * FROM t1;
  }
} {0 {1 1 2 2 3 4 1234 5 6}}
do_test rowid-2.2 {
  catchsql {
    UPDATE t1 SET rowid=12345 WHERE x==1;
    SELECT rowid, * FROM t1
  }
} {0 {2 3 4 1234 5 6 12345 1 2}}
do_test rowid-2.3 {
  catchsql {
    INSERT INTO t1(y,x,oid) VALUES(8,7,1235);
    SELECT rowid, * FROM t1 WHERE rowid>1000;
  }
} {0 {1234 5 6 1235 7 8 12345 1 2}}
do_test rowid-2.4 {
  catchsql {
    UPDATE t1 SET oid=12346 WHERE x==1;
    SELECT rowid, * FROM t1;
  }
} {0 {2 3 4 1234 5 6 1235 7 8 12346 1 2}}
do_test rowid-2.5 {
  catchsql {
    INSERT INTO t1(x,_rowid_,y) VALUES(9,1236,10);
    SELECT rowid, * FROM t1 WHERE rowid>1000;
  }
} {0 {1234 5 6 1235 7 8 1236 9 10 12346 1 2}}
do_test rowid-2.6 {
  catchsql {
    UPDATE t1 SET _rowid_=12347 WHERE x==1;
    SELECT rowid, * FROM t1 WHERE rowid>1000;
  }
} {0 {1234 5 6 1235 7 8 1236 9 10 12347 1 2}}

# But we can use ROWID in the WHERE clause of an UPDATE that does not
# change the ROWID.
#
do_test rowid-2.7 {
  global x2rowid
  set sql "UPDATE t1 SET x=2 WHERE OID==$x2rowid(3)"
  execsql $sql
  execsql {SELECT x FROM t1 ORDER BY x}
} {1 2 5 7 9}
do_test rowid-2.8 {
  global x2rowid
  set sql "UPDATE t1 SET x=3 WHERE _rowid_==$x2rowid(3)"
  execsql $sql
  execsql {SELECT x FROM t1 ORDER BY x}
} {1 3 5 7 9}

# We cannot index by ROWID
#
do_test rowid-2.9 {
  set v [catch {execsql {CREATE INDEX idxt1 ON t1(rowid)}} msg]
  lappend v $msg
} {1 {table t1 has no column named rowid}}
do_test rowid-2.10 {
  set v [catch {execsql {CREATE INDEX idxt1 ON t1(_rowid_)}} msg]
  lappend v $msg
} {1 {table t1 has no column named _rowid_}}
do_test rowid-2.11 {
  set v [catch {execsql {CREATE INDEX idxt1 ON t1(oid)}} msg]
  lappend v $msg
} {1 {table t1 has no column named oid}}
do_test rowid-2.12 {
  set v [catch {execsql {CREATE INDEX idxt1 ON t1(x, rowid)}} msg]
  lappend v $msg
} {1 {table t1 has no column named rowid}}

# Columns defined in the CREATE statement override the buildin ROWID
# column names.
#
do_test rowid-3.1 {
  execsql {
    CREATE TABLE t2(rowid int, x int, y int);
    INSERT INTO t2 VALUES(0,2,3);
    INSERT INTO t2 VALUES(4,5,6);
    INSERT INTO t2 VALUES(7,8,9);
    SELECT * FROM t2 ORDER BY x;
  }
} {0 2 3 4 5 6 7 8 9}
do_test rowid-3.2 {
  execsql {SELECT * FROM t2 ORDER BY rowid}
} {0 2 3 4 5 6 7 8 9}
do_test rowid-3.3 {
  execsql {SELECT rowid, x, y FROM t2 ORDER BY rowid}
} {0 2 3 4 5 6 7 8 9}
do_test rowid-3.4 {
  set r1 [execsql {SELECT _rowid_, rowid FROM t2 ORDER BY rowid}]
  foreach {a b c d e f} $r1 {}
  set r2 [execsql {SELECT _rowid_, rowid FROM t2 ORDER BY x DESC}]
  foreach {u v w x y z} $r2 {}
  expr {$u==$e && $w==$c && $y==$a}
} {1}
# sqlite3 v3 - do_probtest doesn't exist anymore?
if 0 {
do_probtest rowid-3.5 {
  set r1 [execsql {SELECT _rowid_, rowid FROM t2 ORDER BY rowid}]
  foreach {a b c d e f} $r1 {}
  expr {$a!=$b && $c!=$d && $e!=$f}
} {1}
}

# Let's try some more complex examples, including some joins.
#
do_test rowid-4.1 {
  execsql {
    DELETE FROM t1;
    DELETE FROM t2;
  }
  for {set i 1} {$i<=50} {incr i} {
    execsql "INSERT INTO t1(x,y) VALUES($i,[expr {$i*$i}])"
  }
  execsql {INSERT INTO t2 SELECT _rowid_, x*y, y*y FROM t1}
  execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1.rowid==t2.rowid}
} {256}
do_test rowid-4.2 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1.rowid==t2.rowid}
} {256}
do_test rowid-4.2.1 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1.oid==t2.rowid}
} {256}
do_test rowid-4.2.2 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1._rowid_==t2.rowid}
} {256}
do_test rowid-4.2.3 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t2.rowid==t1.rowid}
} {256}
do_test rowid-4.2.4 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t2.rowid==t1.oid AND t1.x==4}
} {256}
do_test rowid-4.2.5 {
  execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1._rowid_==t2.rowid}
} {256}
do_test rowid-4.2.6 {
  execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t2.rowid==t1.rowid}
} {256}
do_test rowid-4.2.7 {
  execsql {SELECT t2.y FROM t1, t2 WHERE t2.rowid==t1.oid AND t1.x==4}
} {256}
do_test rowid-4.3 {
  execsql {CREATE INDEX idxt1 ON t1(x)}
  execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1.rowid==t2.rowid}
} {256}
do_test rowid-4.3.1 {
  execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1._rowid_==t2.rowid}
} {256}
do_test rowid-4.3.2 {
  execsql {SELECT t2.y FROM t1, t2 WHERE t2.rowid==t1.oid AND 4==t1.x}
} {256}
do_test rowid-4.4 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1.rowid==t2.rowid}
} {256}
do_test rowid-4.4.1 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1._rowid_==t2.rowid}
} {256}
do_test rowid-4.4.2 {
  execsql {SELECT t2.y FROM t2, t1 WHERE t2.rowid==t1.oid AND 4==t1.x}
} {256}
do_test rowid-4.5 {
  execsql {CREATE INDEX idxt2 ON t2(y)}
  set sqlite_search_count 0
  concat [execsql {
    SELECT t1.x FROM t2, t1 
    WHERE t2.y==256 AND t1.rowid==t2.rowid
  }] $sqlite_search_count
} {4 3}
do_test rowid-4.5.1 {
  set sqlite_search_count 0
  concat [execsql {
    SELECT t1.x FROM t2, t1 
    WHERE t1.OID==t2.rowid AND t2.y==81
  }] $sqlite_search_count
} {3 3}
do_test rowid-4.6 {
  execsql {
    SELECT t1.x FROM t1, t2
    WHERE t2.y==256 AND t1.rowid==t2.rowid
  }
} {4}

do_test rowid-5.1.1 {
  ifcapable subquery {
    execsql {DELETE FROM t1 WHERE _rowid_ IN (SELECT oid FROM t1 WHERE x>8)}
  } else {
    set oids [execsql {SELECT oid FROM t1 WHERE x>8}]
    set where "_rowid_ = [join $oids { OR _rowid_ = }]"
    execsql "DELETE FROM t1 WHERE $where"
  }
} {}
do_test rowid-5.1.2 {
  execsql {SELECT max(x) FROM t1}
} {8}

# Make sure a "WHERE rowid=X" clause works when there is no ROWID of X.
#
do_test rowid-6.1 {
  execsql {
    SELECT x FROM t1
  }
} {1 2 3 4 5 6 7 8}
do_test rowid-6.2 {
  for {set ::norow 1} {1} {incr ::norow} {
    if {[execsql "SELECT x FROM t1 WHERE rowid=$::norow"]==""}  break
  }
  execsql [subst {
    DELETE FROM t1 WHERE rowid=$::norow
  }]
} {}
do_test rowid-6.3 {
  execsql {
    SELECT x FROM t1
  }
} {1 2 3 4 5 6 7 8}

# Beginning with version 2.3.4, SQLite computes rowids of new rows by
# finding the maximum current rowid and adding one.  It falls back to
# the old random algorithm if the maximum rowid is the largest integer.
# The following tests are for this new behavior.
#
do_test rowid-7.0 {
  execsql {
    DELETE FROM t1;
    DROP TABLE t2;
    DROP INDEX idxt1;
    INSERT INTO t1 VALUES(1,2);
    SELECT rowid, * FROM t1;
  }
} {1 1 2}
do_test rowid-7.1 {
  execsql {
    INSERT INTO t1 VALUES(99,100);
    SELECT rowid,* FROM t1
  }
} {1 1 2 2 99 100}
do_test rowid-7.2 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
    INSERT INTO t2(b) VALUES(55);
    SELECT * FROM t2;
  }
} {1 55}
do_test rowid-7.3 {
  execsql {
    INSERT INTO t2(b) VALUES(66);
    SELECT * FROM t2;
  }
} {1 55 2 66}
do_test rowid-7.4 {
  execsql {
    INSERT INTO t2(a,b) VALUES(1000000,77);
    INSERT INTO t2(b) VALUES(88);
    SELECT * FROM t2;
  }
} {1 55 2 66 1000000 77 1000001 88}
do_test rowid-7.5 {
  execsql {
    INSERT INTO t2(a,b) VALUES(2147483647,99);
    INSERT INTO t2(b) VALUES(11);
    SELECT b FROM t2 ORDER BY b;
  }
} {11 55 66 77 88 99}
ifcapable subquery {
  do_test rowid-7.6 {
    execsql {
      SELECT b FROM t2 WHERE a NOT IN(1,2,1000000,1000001,2147483647);
    }
  } {11}
  do_test rowid-7.7 {
    execsql {
      INSERT INTO t2(b) VALUES(22);
      INSERT INTO t2(b) VALUES(33);
      INSERT INTO t2(b) VALUES(44);
      INSERT INTO t2(b) VALUES(55);
      SELECT b FROM t2 WHERE a NOT IN(1,2,1000000,1000001,2147483647) 
          ORDER BY b;
    }
  } {11 22 33 44 55}
}
do_test rowid-7.8 {
  execsql {
    DELETE FROM t2 WHERE a!=2;
    INSERT INTO t2(b) VALUES(111);
    SELECT * FROM t2;
  }
} {2 66 3 111}

ifcapable {trigger} {
# Make sure AFTER triggers that do INSERTs do not change the last_insert_rowid.
# Ticket #290
#
do_test rowid-8.1 {
  execsql {
    CREATE TABLE t3(a integer primary key);
    CREATE TABLE t4(x);
    INSERT INTO t4 VALUES(1);
    CREATE TRIGGER r3 AFTER INSERT on t3 FOR EACH ROW BEGIN
      INSERT INTO t4 VALUES(NEW.a+10);
    END;
    SELECT * FROM t3;
  }
} {}
do_test rowid-8.2 {
  execsql {
    SELECT rowid, * FROM t4;
  }
} {1 1}
do_test rowid-8.3 {
  execsql {
    INSERT INTO t3 VALUES(123);
    SELECT last_insert_rowid();
  }
} {123}
do_test rowid-8.4 {
  execsql {
    SELECT * FROM t3;
  }
} {123}
do_test rowid-8.5 {
  execsql {
    SELECT rowid, * FROM t4;
  }
} {1 1 2 133}
do_test rowid-8.6 {
  execsql {
    INSERT INTO t3 VALUES(NULL);
    SELECT last_insert_rowid();
  }
} {124}
do_test rowid-8.7 {
  execsql {
    SELECT * FROM t3;
  }
} {123 124}
do_test rowid-8.8 {
  execsql {
    SELECT rowid, * FROM t4;
  }
} {1 1 2 133 3 134}
} ;# endif trigger

# If triggers are not enable, simulate their effect for the tests that
# follow.
ifcapable {!trigger} {
  execsql {
    CREATE TABLE t3(a integer primary key);
    INSERT INTO t3 VALUES(123);
    INSERT INTO t3 VALUES(124);
  }
}

# ticket #377: Comparison between integer primiary key and floating point
# values.
#
do_test rowid-9.1 {
  execsql {
    SELECT * FROM t3 WHERE a<123.5
  }
} {123}
do_test rowid-9.2 {
  execsql {
    SELECT * FROM t3 WHERE a<124.5
  }
} {123 124}
do_test rowid-9.3 {
  execsql {
    SELECT * FROM t3 WHERE a>123.5
  }
} {124}
do_test rowid-9.4 {
  execsql {
    SELECT * FROM t3 WHERE a>122.5
  }
} {123 124}
do_test rowid-9.5 {
  execsql {
    SELECT * FROM t3 WHERE a==123.5
  }
} {}
do_test rowid-9.6 {
  execsql {
    SELECT * FROM t3 WHERE a==123.000
  }
} {123}
do_test rowid-9.7 {
  execsql {
    SELECT * FROM t3 WHERE a>100.5 AND a<200.5
  }
} {123 124}
do_test rowid-9.8 {
  execsql {
    SELECT * FROM t3 WHERE a>'xyz';
  }
} {}
do_test rowid-9.9 {
  execsql {
    SELECT * FROM t3 WHERE a<'xyz';
  }
} {123 124}
do_test rowid-9.10 {
  execsql {
    SELECT * FROM t3 WHERE a>=122.9 AND a<=123.1
  }
} {123}

# Ticket #567.  Comparisons of ROWID or integery primary key against
# floating point numbers still do not always work.
#
do_test rowid-10.1 {
  execsql {
    CREATE TABLE t5(a);
    INSERT INTO t5 VALUES(1);
    INSERT INTO t5 VALUES(2);
    INSERT INTO t5 SELECT a+2 FROM t5;
    INSERT INTO t5 SELECT a+4 FROM t5;
    SELECT rowid, * FROM t5;
  }
} {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8}
do_test rowid-10.2 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.5}
} {6 6 7 7 8 8}
do_test rowid-10.3 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.0}
} {5 5 6 6 7 7 8 8}
do_test rowid-10.4 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>5.5}
} {6 6 7 7 8 8}
do_test rowid-10.3.2 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>5.0}
} {6 6 7 7 8 8}
do_test rowid-10.5 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5<=rowid}
} {6 6 7 7 8 8}
do_test rowid-10.6 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5<rowid}
} {6 6 7 7 8 8}
do_test rowid-10.7 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid<=5.5}
} {1 1 2 2 3 3 4 4 5 5}
do_test rowid-10.8 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid<5.5}
} {1 1 2 2 3 3 4 4 5 5}
do_test rowid-10.9 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5>=rowid}
} {1 1 2 2 3 3 4 4 5 5}
do_test rowid-10.10 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5>rowid}
} {1 1 2 2 3 3 4 4 5 5}
do_test rowid-10.11 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.5 ORDER BY rowid DESC}
} {8 8 7 7 6 6}
do_test rowid-10.11.2 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.0 ORDER BY rowid DESC}
} {8 8 7 7 6 6 5 5}
do_test rowid-10.12 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>5.5 ORDER BY rowid DESC}
} {8 8 7 7 6 6}
do_test rowid-10.12.2 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>5.0 ORDER BY rowid DESC}
} {8 8 7 7 6 6}
do_test rowid-10.13 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5<=rowid ORDER BY rowid DESC}
} {8 8 7 7 6 6}
do_test rowid-10.14 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5<rowid ORDER BY rowid DESC}
} {8 8 7 7 6 6}
do_test rowid-10.15 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid<=5.5 ORDER BY rowid DESC}
} {5 5 4 4 3 3 2 2 1 1}
do_test rowid-10.16 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid<5.5 ORDER BY rowid DESC}
} {5 5 4 4 3 3 2 2 1 1}
do_test rowid-10.17 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5>=rowid ORDER BY rowid DESC}
} {5 5 4 4 3 3 2 2 1 1}
do_test rowid-10.18 {
  execsql {SELECT rowid, a FROM t5 WHERE 5.5>rowid ORDER BY rowid DESC}
} {5 5 4 4 3 3 2 2 1 1}

do_test rowid-10.30 {
  execsql {
    CREATE TABLE t6(a);
    INSERT INTO t6(rowid,a) SELECT -a,a FROM t5;
    SELECT rowid, * FROM t6;
  }
} {-8 8 -7 7 -6 6 -5 5 -4 4 -3 3 -2 2 -1 1}
do_test rowid-10.31.1 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.5}
} {-5 5 -4 4 -3 3 -2 2 -1 1}
do_test rowid-10.31.2 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.0}
} {-5 5 -4 4 -3 3 -2 2 -1 1}
do_test rowid-10.32.1 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.5 ORDER BY rowid DESC}
} {-1 1 -2 2 -3 3 -4 4 -5 5}
do_test rowid-10.32.1 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.0 ORDER BY rowid DESC}
} {-1 1 -2 2 -3 3 -4 4 -5 5}
do_test rowid-10.33 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5<=rowid}
} {-5 5 -4 4 -3 3 -2 2 -1 1}
do_test rowid-10.34 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5<=rowid ORDER BY rowid DESC}
} {-1 1 -2 2 -3 3 -4 4 -5 5}
do_test rowid-10.35.1 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.5}
} {-5 5 -4 4 -3 3 -2 2 -1 1}
do_test rowid-10.35.2 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.0}
} {-4 4 -3 3 -2 2 -1 1}
do_test rowid-10.36.1 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.5 ORDER BY rowid DESC}
} {-1 1 -2 2 -3 3 -4 4 -5 5}
do_test rowid-10.36.2 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.0 ORDER BY rowid DESC}
} {-1 1 -2 2 -3 3 -4 4}
do_test rowid-10.37 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5<rowid}
} {-5 5 -4 4 -3 3 -2 2 -1 1}
do_test rowid-10.38 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5<rowid ORDER BY rowid DESC}
} {-1 1 -2 2 -3 3 -4 4 -5 5}
do_test rowid-10.39 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid<=-5.5}
} {-8 8 -7 7 -6 6}
do_test rowid-10.40 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid<=-5.5 ORDER BY rowid DESC}
} {-6 6 -7 7 -8 8}
do_test rowid-10.41 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5>=rowid}
} {-8 8 -7 7 -6 6}
do_test rowid-10.42 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5>=rowid ORDER BY rowid DESC}
} {-6 6 -7 7 -8 8}
do_test rowid-10.43 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid<-5.5}
} {-8 8 -7 7 -6 6}
do_test rowid-10.44 {
  execsql {SELECT rowid, a FROM t6 WHERE rowid<-5.5 ORDER BY rowid DESC}
} {-6 6 -7 7 -8 8}
do_test rowid-10.44 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5>rowid}
} {-8 8 -7 7 -6 6}
do_test rowid-10.46 {
  execsql {SELECT rowid, a FROM t6 WHERE -5.5>rowid ORDER BY rowid DESC}
} {-6 6 -7 7 -8 8}

# Comparison of rowid against string values.
#
do_test rowid-11.1 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>'abc'}
} {}
do_test rowid-11.2 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid>='abc'}
} {}
do_test rowid-11.3 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid<'abc'}
} {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8}
do_test rowid-11.4 {
  execsql {SELECT rowid, a FROM t5 WHERE rowid<='abc'}
} {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8}

# Test the automatic generation of rowids when the table already contains
# a rowid with the maximum value.
#
# Once the the maximum rowid is taken, rowids are normally chosen at
# random.  By by reseting the random number generator, we can cause
# the rowid guessing loop to collide with prior rowids, and test the
# loop out to its limit of 100 iterations.  After 100 collisions, the
# rowid guesser gives up and reports SQLITE_FULL.
#
do_test rowid-12.1 {
  execsql {
    CREATE TABLE t7(x INTEGER PRIMARY KEY, y);
    CREATE TABLE t7temp(a INTEGER PRIMARY KEY);
    INSERT INTO t7 VALUES(9223372036854775807,'a');
    SELECT y FROM t7;
  }
} {a}
do_test rowid-12.2 {
  db close
  sqlite3 db test.db
  save_prng_state
  execsql {
    INSERT INTO t7 VALUES(NULL,'b');
    SELECT x, y FROM t7;
  }
} {1 b 9223372036854775807 a}
execsql {INSERT INTO t7 VALUES(2,'y');}
for {set i 1} {$i<100} {incr i} {
  do_test rowid-12.3.$i {
    db eval {DELETE FROM t7temp; INSERT INTO t7temp VALUES(1);}
    restore_prng_state
    execsql {
      INSERT INTO t7 VALUES(NULL,'x');
      SELECT count(*) FROM t7 WHERE y=='x';
    }
  } $i
}
do_test rowid-12.4 {
  db eval {DELETE FROM t7temp; INSERT INTO t7temp VALUES(1);}
  restore_prng_state
  catchsql {
    INSERT INTO t7 VALUES(NULL,'x');
  }
} {1 {database or disk is full}}


finish_test

Added test/rtree.test.

















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all rtree related tests.
#
# $Id: rtree.test,v 1.3 2009/05/25 14:17:35 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

rename finish_test rtree_finish_test
proc finish_test {} {}

set RTREE_EXCLUDE { }
if {[info exists ISQUICK] && $ISQUICK} { 
  set RTREE_EXCLUDE rtree3.test
}

set rtreedir [file join $testdir .. ext rtree]

foreach testfile [lsort -dictionary [glob -nocomplain $rtreedir/*.test]] {
  set tail [file tail $testfile]
  if {[lsearch -exact $RTREE_EXCLUDE $tail]>=0} continue
  source $testfile
  catch {db close}
  if {$sqlite_open_file_count>0} {
    puts "$tail did not close all files: $sqlite_open_file_count"
    incr nErr
    lappend ::failList $tail
    set sqlite_open_file_count 0
  }
}

set sqlite_open_file_count 0
rtree_finish_test
rename finish_test {}
rename rtree_finish_test finish_test

Added test/safety.test.



























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 2005 January 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the sqlite3SafetyOn and sqlite3SafetyOff
# functions.  Those routines are not strictly necessary - they are
# designed to detect misuse of the library.
#
# $Id: safety.test,v 1.4 2008/03/18 13:46:53 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !debug {
  puts "Skipping safety tests since SQLITE_DEBUG is off"
  finish_test
  return
}

# Return the UTF-8 representation of the supplied UTF-16 string $str. 
proc utf8 {str} {
  # If $str ends in two 0x00 0x00 bytes, knock these off before
  # converting to UTF-8 using TCL.
  binary scan $str \c* vals
  if {[lindex $vals end]==0 && [lindex $vals end-1]==0} {
    set str [binary format \c* [lrange $vals 0 end-2]]
  }

  set r [encoding convertfrom unicode $str]
  return $r
}


do_test safety-1.1 {
  set DB [sqlite3_connection_pointer db]
  db eval {CREATE TABLE t1(a)}
  sqlite_set_magic $DB SQLITE_MAGIC_BUSY
  catchsql {
    SELECT name FROM sqlite_master;
  }
} {1 {library routine called out of sequence}}
do_test safety-1.2 {
  sqlite_set_magic $DB SQLITE_MAGIC_OPEN
  catchsql {
    SELECT name FROM sqlite_master
  }
} {0 t1}

do_test safety-2.1 {
  proc safety_on {} "sqlite_set_magic $DB SQLITE_MAGIC_BUSY"
  db function safety_on safety_on
  catchsql {
    SELECT safety_on(), name FROM sqlite_master
  }
} {1 {library routine called out of sequence}}
ifcapable {utf16} {
  do_test safety-2.1.1 {
    utf8 [sqlite3_errmsg16 db]
  } {library routine called out of sequence}
}
do_test safety-2.2 {
  catchsql {
    SELECT 'hello'
  }
} {1 {library routine called out of sequence}}
do_test safety-2.3 {
  sqlite3_close $DB
} {SQLITE_MISUSE}
do_test safety-2.4 {
  sqlite_set_magic $DB SQLITE_MAGIC_OPEN
  execsql {
    SELECT name FROM sqlite_master
  }
} {t1}

do_test safety-3.1 {
  set rc [catch {
    db eval {SELECT name FROM sqlite_master} {
      sqlite_set_magic $DB SQLITE_MAGIC_BUSY
    }
  } msg]
  lappend rc $msg
} {1 {library routine called out of sequence}}
sqlite_set_magic $DB SQLITE_MAGIC_OPEN

finish_test

Added test/savepoint.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
# 2008 December 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: savepoint.test,v 1.13 2009/07/18 08:30:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl


#----------------------------------------------------------------------
# The following tests - savepoint-1.* - test that the SAVEPOINT, RELEASE
# and ROLLBACK TO comands are correctly parsed, and that the auto-commit
# flag is correctly set and unset as a result.
#
do_test savepoint-1.1 {
  execsql {
    SAVEPOINT sp1;
    RELEASE sp1;
  }
} {}
do_test savepoint-1.2 {
  execsql {
    SAVEPOINT sp1;
    ROLLBACK TO sp1;
  }
} {}
do_test savepoint-1.3 {
  execsql { SAVEPOINT sp1 }
  db close
} {}
sqlite3 db test.db
do_test savepoint-1.4.1 {
  execsql {
    SAVEPOINT sp1;
    SAVEPOINT sp2;
    RELEASE sp1;
  }
  sqlite3_get_autocommit db
} {1}
do_test savepoint-1.4.2 {
  execsql {
    SAVEPOINT sp1;
    SAVEPOINT sp2;
    RELEASE sp2;
  }
  sqlite3_get_autocommit db
} {0}
do_test savepoint-1.4.3 {
  execsql { RELEASE sp1 }
  sqlite3_get_autocommit db
} {1}
do_test savepoint-1.4.4 {
  execsql {
    SAVEPOINT sp1;
    SAVEPOINT sp2;
    ROLLBACK TO sp1;
  }
  sqlite3_get_autocommit db
} {0}
do_test savepoint-1.4.5 {
  execsql { RELEASE SAVEPOINT sp1 }
  sqlite3_get_autocommit db
} {1}
do_test savepoint-1.4.6 {
  execsql {
    SAVEPOINT sp1;
    SAVEPOINT sp2;
    SAVEPOINT sp3;
    ROLLBACK TO SAVEPOINT sp3;
    ROLLBACK TRANSACTION TO sp2;
    ROLLBACK TRANSACTION TO SAVEPOINT sp1;
  }
  sqlite3_get_autocommit db
} {0}
do_test savepoint-1.4.7 {
  execsql { RELEASE SAVEPOINT SP1 }
  sqlite3_get_autocommit db
} {1}
do_test savepoint-1.5 {
  execsql {
    SAVEPOINT sp1;
    ROLLBACK TO sp1;
  }
} {}
do_test savepoint-1.6 {
  execsql COMMIT
} {}

#------------------------------------------------------------------------
# These tests - savepoint-2.* - test rollbacks and releases of savepoints
# with a very simple data set.
# 

do_test savepoint-2.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    BEGIN;
    INSERT INTO t1 VALUES(1, 2, 3);
    SAVEPOINT one;
    UPDATE t1 SET a = 2, b = 3, c = 4;
  }
  execsql { SELECT * FROM t1 }
} {2 3 4}
do_test savepoint-2.2 {
  execsql {
    ROLLBACK TO one;
  }
  execsql { SELECT * FROM t1 }
} {1 2 3}
do_test savepoint-2.3 {
  execsql {
    INSERT INTO t1 VALUES(4, 5, 6);
  }
  execsql { SELECT * FROM t1 }
} {1 2 3 4 5 6}
do_test savepoint-2.4 {
  execsql {
    ROLLBACK TO one;
  }
  execsql { SELECT * FROM t1 }
} {1 2 3}


do_test savepoint-2.5 {
  execsql {
    INSERT INTO t1 VALUES(7, 8, 9);
    SAVEPOINT two;
    INSERT INTO t1 VALUES(10, 11, 12);
  }
  execsql { SELECT * FROM t1 }
} {1 2 3 7 8 9 10 11 12}
do_test savepoint-2.6 {
  execsql {
    ROLLBACK TO two;
  }
  execsql { SELECT * FROM t1 }
} {1 2 3 7 8 9}
do_test savepoint-2.7 {
  execsql {
    INSERT INTO t1 VALUES(10, 11, 12);
  }
  execsql { SELECT * FROM t1 }
} {1 2 3 7 8 9 10 11 12}
do_test savepoint-2.8 {
  execsql {
    ROLLBACK TO one;
  }
  execsql { SELECT * FROM t1 }
} {1 2 3}
do_test savepoint-2.9 {
  execsql {
    INSERT INTO t1 VALUES('a', 'b', 'c');
    SAVEPOINT two;
    INSERT INTO t1 VALUES('d', 'e', 'f');
  }
  execsql { SELECT * FROM t1 }
} {1 2 3 a b c d e f}
do_test savepoint-2.10 {
  execsql {
    RELEASE two;
  }
  execsql { SELECT * FROM t1 }
} {1 2 3 a b c d e f}
do_test savepoint-2.11 {
  execsql {
    ROLLBACK;
  }
  execsql { SELECT * FROM t1 }
} {}

#------------------------------------------------------------------------
# This block of tests - savepoint-3.* - test that when a transaction
# savepoint is rolled back, locks are not released from database files.
# And that when a transaction savepoint is released, they are released.
# 
do_test savepoint-3.1 {
  execsql { SAVEPOINT "transaction" }
  execsql { PRAGMA lock_status }
} {main unlocked temp closed}

do_test savepoint-3.2 {
  execsql { INSERT INTO t1 VALUES(1, 2, 3) }
  execsql { PRAGMA lock_status }
} {main reserved temp closed}

do_test savepoint-3.3 {
  execsql { ROLLBACK TO "transaction" }
  execsql { PRAGMA lock_status }
} {main reserved temp closed}

do_test savepoint-3.4 {
  execsql { INSERT INTO t1 VALUES(1, 2, 3) }
  execsql { PRAGMA lock_status }
} {main reserved temp closed}

do_test savepoint-3.5 {
  execsql { RELEASE "transaction" }
  execsql { PRAGMA lock_status }
} {main unlocked temp closed}

#------------------------------------------------------------------------
# Test that savepoints that include schema modifications are handled
# correctly. Test cases savepoint-4.*.
# 
do_test savepoint-4.1 {
  execsql {
    CREATE TABLE t2(d, e, f);
    SELECT sql FROM sqlite_master;
  }
} {{CREATE TABLE t1(a, b, c)} {CREATE TABLE t2(d, e, f)}}
do_test savepoint-4.2 {
  execsql {
    BEGIN;
    CREATE TABLE t3(g,h);
    INSERT INTO t3 VALUES('I', 'II');
    SAVEPOINT one;
    DROP TABLE t3;
  }
} {}
do_test savepoint-4.3 {
  execsql {
    CREATE TABLE t3(g, h, i);
    INSERT INTO t3 VALUES('III', 'IV', 'V');
  }
  execsql {SELECT * FROM t3}
} {III IV V}
do_test savepoint-4.4 {
  execsql { ROLLBACK TO one; }
  execsql {SELECT * FROM t3}
} {I II}
do_test savepoint-4.5 {
  execsql {
    ROLLBACK;
    SELECT sql FROM sqlite_master;
  }
} {{CREATE TABLE t1(a, b, c)} {CREATE TABLE t2(d, e, f)}}

do_test savepoint-4.6 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES('o', 't', 't');
    SAVEPOINT sp1;
    CREATE TABLE t3(a, b, c);
    INSERT INTO t3 VALUES('z', 'y', 'x');
  }
  execsql {SELECT * FROM t3}
} {z y x}
do_test savepoint-4.7 {
  execsql {
    ROLLBACK TO sp1;
    CREATE TABLE t3(a);
    INSERT INTO t3 VALUES('value');
  }
  execsql {SELECT * FROM t3}
} {value}
do_test savepoint-4.8 {
  execsql COMMIT
} {}

#------------------------------------------------------------------------
# Test some logic errors to do with the savepoint feature.
# 

ifcapable incrblob {
  do_test savepoint-5.1.1 {
    execsql {
      CREATE TABLE blobs(x);
      INSERT INTO blobs VALUES('a twentyeight character blob');
    }
    set fd [db incrblob blobs x 1]
    puts -nonewline $fd "hello"
    catchsql {SAVEPOINT abc}
  } {1 {cannot open savepoint - SQL statements in progress}}
  do_test savepoint-5.1.2 {
    close $fd
    catchsql {SAVEPOINT abc}
  } {0 {}}
  
  do_test savepoint-5.2 {
    execsql  {RELEASE abc}
    catchsql {RELEASE abc}
  } {1 {no such savepoint: abc}}
  
  do_test savepoint-5.3.1 {
    execsql  {SAVEPOINT abc}
    catchsql {ROLLBACK TO def}
  } {1 {no such savepoint: def}}
  do_test savepoint-5.3.2 {
    execsql  {SAVEPOINT def}
    set fd [db incrblob -readonly blobs x 1]
    catchsql {ROLLBACK TO def}
  } {1 {cannot rollback savepoint - SQL statements in progress}}
  do_test savepoint-5.3.3 {
    catchsql  {RELEASE def}
  } {0 {}}
  do_test savepoint-5.3.4 {
    close $fd
    execsql  {savepoint def}
    set fd [db incrblob blobs x 1]
    catchsql {release def}
  } {1 {cannot release savepoint - SQL statements in progress}}
  do_test savepoint-5.3.5 {
    close $fd
    execsql {release abc}
  } {}
  
  do_test savepoint-5.4.1 {
    execsql {
      SAVEPOINT main;
      INSERT INTO blobs VALUES('another blob');
    }
  } {}
  do_test savepoint-5.4.2 {
    sqlite3 db2 test.db
    execsql { BEGIN ; SELECT * FROM blobs } db2
    catchsql { RELEASE main }
  } {1 {database is locked}}
  do_test savepoint-5.4.3 {
    db2 close
    catchsql { RELEASE main }
  } {0 {}}
  do_test savepoint-5.4.4 {
    execsql { SELECT x FROM blobs WHERE rowid = 2 }
  } {{another blob}}
}

#-------------------------------------------------------------------------
# The following tests, savepoint-6.*, test an incr-vacuum inside of a
# couple of nested savepoints.
#
ifcapable {autovacuum && pragma} {
  db close
  file delete -force test.db
  sqlite3 db test.db

  do_test savepoint-6.1 {
    execsql { 
      PRAGMA auto_vacuum = incremental;
      CREATE TABLE t1(a, b, c);
      CREATE INDEX i1 ON t1(a, b);
      BEGIN;
      INSERT INTO t1 VALUES(randstr(10,400),randstr(10,400),randstr(10,400));
    }
    set r "randstr(10,400)"
    for {set ii 0} {$ii < 10} {incr ii} {
      execsql "INSERT INTO t1 SELECT $r, $r, $r FROM t1"
    }
    execsql { COMMIT }
  } {}

  integrity_check savepoint-6.2

  do_test savepoint-6.3 {
    execsql {
      PRAGMA cache_size = 10;
      BEGIN;
        UPDATE t1 SET a = randstr(10,10) WHERE (rowid%4)==0;
        SAVEPOINT one;
          DELETE FROM t1 WHERE rowid%2;
          PRAGMA incr_vacuum;
          SAVEPOINT two;
            INSERT INTO t1 SELECT randstr(10,400), randstr(10,400), c FROM t1;
            DELETE FROM t1 WHERE rowid%2;
            PRAGMA incr_vacuum;
        ROLLBACK TO one;
      COMMIT;
    }
  } {}

  integrity_check savepoint-6.4
}

#-------------------------------------------------------------------------
# The following tests, savepoint-7.*, attempt to break the logic 
# surrounding savepoints by growing and shrinking the database file.
#
db close
file delete -force test.db
sqlite3 db test.db

do_test savepoint-7.1 {
  execsql {
    PRAGMA auto_vacuum = incremental;
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE t1(a PRIMARY KEY, b);
      INSERT INTO t1(a) VALUES('alligator');
      INSERT INTO t1(a) VALUES('angelfish');
      INSERT INTO t1(a) VALUES('ant');
      INSERT INTO t1(a) VALUES('antelope');
      INSERT INTO t1(a) VALUES('ape');
      INSERT INTO t1(a) VALUES('baboon');
      INSERT INTO t1(a) VALUES('badger');
      INSERT INTO t1(a) VALUES('bear');
      INSERT INTO t1(a) VALUES('beetle');
      INSERT INTO t1(a) VALUES('bird');
      INSERT INTO t1(a) VALUES('bison');
      UPDATE t1 SET b =    randstr(1000,1000);
      UPDATE t1 SET b = b||randstr(1000,1000);
      UPDATE t1 SET b = b||randstr(1000,1000);
      UPDATE t1 SET b = b||randstr(10,1000);
    COMMIT;
  }
  expr ([execsql { PRAGMA page_count }] > 20)
} {1}
do_test savepoint-7.2.1 {
  execsql {
    BEGIN;
      SAVEPOINT one;
      CREATE TABLE t2(a, b);
      INSERT INTO t2 SELECT a, b FROM t1;
      ROLLBACK TO one;
  }
  execsql {
    PRAGMA integrity_check;
  }
} {ok}
do_test savepoint-7.2.2 {
  execsql {
    COMMIT;
    PRAGMA integrity_check;
  }
} {ok}

do_test savepoint-7.3.1 {
  execsql {
    CREATE TABLE t2(a, b);
    INSERT INTO t2 SELECT a, b FROM t1;
  }
} {}
do_test savepoint-7.3.2 {
  execsql {
    BEGIN;
      SAVEPOINT one;
        DELETE FROM t2;
        PRAGMA incremental_vacuum;
        SAVEPOINT two;
          INSERT INTO t2 SELECT a, b FROM t1;
        ROLLBACK TO two;
    COMMIT;
  }
  execsql { PRAGMA integrity_check }
} {ok}

do_test savepoint-7.4.1 {
  db close
  file delete -force test.db
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum = incremental;
    CREATE TABLE t1(a, b, PRIMARY KEY(a, b));
    INSERT INTO t1 VALUES(randstr(1000,1000), randstr(1000,1000));
    BEGIN;
      DELETE FROM t1;
      SAVEPOINT one;
      PRAGMA incremental_vacuum;
      ROLLBACK TO one;
    COMMIT;
  }

  execsql { PRAGMA integrity_check }
} {ok}

do_test savepoint-7.5.1 {
  execsql {
    PRAGMA incremental_vacuum;
    CREATE TABLE t5(x, y);
    INSERT INTO t5 VALUES(1, randstr(1000,1000));
    INSERT INTO t5 VALUES(2, randstr(1000,1000));
    INSERT INTO t5 VALUES(3, randstr(1000,1000));

    BEGIN;
      INSERT INTO t5 VALUES(4, randstr(1000,1000));
      INSERT INTO t5 VALUES(5, randstr(1000,1000));
      DELETE FROM t5 WHERE x=1 OR x=2;
      SAVEPOINT one;
        PRAGMA incremental_vacuum;
        SAVEPOINT two;
          INSERT INTO t5 VALUES(1, randstr(1000,1000));
          INSERT INTO t5 VALUES(2, randstr(1000,1000));
        ROLLBACK TO two;
      ROLLBACK TO one;
    COMMIT;
    PRAGMA integrity_check;
  }
} {ok}
do_test savepoint-7.5.2 {
  execsql {
    DROP TABLE t5;
  }
} {}

# Test oddly named and quoted savepoints.
#
do_test savepoint-8-1 {
  execsql { SAVEPOINT "save1" }
  execsql { RELEASE save1 }
} {}
do_test savepoint-8-2 {
  execsql { SAVEPOINT "Including whitespace " }
  execsql { RELEASE "including Whitespace " }
} {}

# Test that the authorization callback works.
#
ifcapable auth {
  proc auth {args} {
    eval lappend ::authdata $args
    return SQLITE_OK
  }
  db auth auth

  do_test savepoint-9.1 {
    set ::authdata [list]
    execsql { SAVEPOINT sp1 }
    set ::authdata
  } {SQLITE_SAVEPOINT BEGIN sp1 {} {}}
  do_test savepoint-9.2 {
    set ::authdata [list]
    execsql { ROLLBACK TO sp1 }
    set ::authdata
  } {SQLITE_SAVEPOINT ROLLBACK sp1 {} {}}
  do_test savepoint-9.3 {
    set ::authdata [list]
    execsql { RELEASE sp1 }
    set ::authdata
  } {SQLITE_SAVEPOINT RELEASE sp1 {} {}}

  proc auth {args} {
    eval lappend ::authdata $args
    return SQLITE_DENY
  }
  db auth auth

  do_test savepoint-9.4 {
    set ::authdata [list]
    set res [catchsql { SAVEPOINT sp1 }]
    concat $::authdata $res
  } {SQLITE_SAVEPOINT BEGIN sp1 {} {} 1 {not authorized}}
  do_test savepoint-9.5 {
    set ::authdata [list]
    set res [catchsql { ROLLBACK TO sp1 }]
    concat $::authdata $res
  } {SQLITE_SAVEPOINT ROLLBACK sp1 {} {} 1 {not authorized}}
  do_test savepoint-9.6 {
    set ::authdata [list]
    set res [catchsql { RELEASE sp1 }]
    concat $::authdata $res
  } {SQLITE_SAVEPOINT RELEASE sp1 {} {} 1 {not authorized}}

  catch { db eval ROLLBACK }
  db auth ""
}

#-------------------------------------------------------------------------
# The following tests - savepoint-10.* - test the interaction of 
# savepoints and ATTACH statements.
# 

# First make sure it is not possible to attach or detach a database while
# a savepoint is open (it is not possible if any transaction is open).
#
do_test savepoint-10.1.1 {
  catchsql {
    SAVEPOINT one;
    ATTACH 'test2.db' AS aux;
  }
} {1 {cannot ATTACH database within transaction}}
do_test savepoint-10.1.2 {
  execsql {
    RELEASE one;
    ATTACH 'test2.db' AS aux;
  }
  catchsql {
    SAVEPOINT one;
    DETACH aux;
  }
} {1 {cannot DETACH database within transaction}}
do_test savepoint-10.1.3 {
  execsql {
    RELEASE one;
    DETACH aux;
  }
} {}

# The lock state of the TEMP database can vary if SQLITE_TEMP_STORE=3
# And the following set of tests is only really interested in the status
# of the aux1 and aux2 locks.  So record the current lock status of
# TEMP for use in the answers.
set templockstate [lindex [db eval {PRAGMA lock_status}] 3]


do_test savepoint-10.2.1 {
  file delete -force test3.db
  file delete -force test2.db
  execsql {
    ATTACH 'test2.db' AS aux1;
    ATTACH 'test3.db' AS aux2;
    DROP TABLE t1;
    CREATE TABLE main.t1(x, y);
    CREATE TABLE aux1.t2(x, y);
    CREATE TABLE aux2.t3(x, y);
    SELECT name FROM sqlite_master 
      UNION ALL
    SELECT name FROM aux1.sqlite_master 
      UNION ALL
    SELECT name FROM aux2.sqlite_master;
  }
} {t1 t2 t3}
do_test savepoint-10.2.2 {
  execsql { PRAGMA lock_status }
} [list main unlocked temp $templockstate aux1 unlocked aux2 unlocked]

do_test savepoint-10.2.3 {
  execsql {
    SAVEPOINT one;
    INSERT INTO t1 VALUES(1, 2);
    PRAGMA lock_status;
  }
} [list main reserved temp $templockstate aux1 unlocked aux2 unlocked]
do_test savepoint-10.2.4 {
  execsql {
    INSERT INTO t3 VALUES(3, 4);
    PRAGMA lock_status;
  }
} [list main reserved temp $templockstate aux1 unlocked aux2 reserved]
do_test savepoint-10.2.5 {
  execsql {
    SAVEPOINT two;
    INSERT INTO t2 VALUES(5, 6);
    PRAGMA lock_status;
  }
} [list main reserved temp $templockstate aux1 reserved aux2 reserved]
do_test savepoint-10.2.6 {
  execsql { SELECT * FROM t2 }
} {5 6}
do_test savepoint-10.2.7 {
  execsql { ROLLBACK TO two }
  execsql { SELECT * FROM t2 }
} {}
do_test savepoint-10.2.8 {
  execsql { PRAGMA lock_status }
} [list main reserved temp $templockstate aux1 reserved aux2 reserved]
do_test savepoint-10.2.9 {
  execsql { SELECT 'a', * FROM t1 UNION ALL SELECT 'b', * FROM t3 }
} {a 1 2 b 3 4}
do_test savepoint-10.2.9 {
  execsql {
    INSERT INTO t2 VALUES(5, 6);
    RELEASE one;
  }
  execsql { 
    SELECT * FROM t1;
    SELECT * FROM t2;
    SELECT * FROM t3;
  }
} {1 2 5 6 3 4}
do_test savepoint-10.2.9 {
  execsql { PRAGMA lock_status }
} [list main unlocked temp $templockstate aux1 unlocked aux2 unlocked]

do_test savepoint-10.2.10 {
  execsql { 
    SAVEPOINT one;
      INSERT INTO t1 VALUES('a', 'b');
      SAVEPOINT two;
        INSERT INTO t2 VALUES('c', 'd');
        SAVEPOINT three;
          INSERT INTO t3 VALUES('e', 'f');
  }
  execsql { 
    SELECT * FROM t1;
    SELECT * FROM t2;
    SELECT * FROM t3;
  }
} {1 2 a b 5 6 c d 3 4 e f}
do_test savepoint-10.2.11 {
  execsql { ROLLBACK TO two }
  execsql { 
    SELECT * FROM t1;
    SELECT * FROM t2;
    SELECT * FROM t3;
  }
} {1 2 a b 5 6 3 4}
do_test savepoint-10.2.12 {
  execsql { 
    INSERT INTO t3 VALUES('g', 'h');
    ROLLBACK TO two;
  }
  execsql { 
    SELECT * FROM t1;
    SELECT * FROM t2;
    SELECT * FROM t3;
  }
} {1 2 a b 5 6 3 4}
do_test savepoint-10.2.13 {
  execsql { ROLLBACK }
  execsql { 
    SELECT * FROM t1;
    SELECT * FROM t2;
    SELECT * FROM t3;
  }
} {1 2 5 6 3 4}
do_test savepoint-10.2.14 {
  execsql { PRAGMA lock_status }
} [list main unlocked temp $templockstate aux1 unlocked aux2 unlocked]

#-------------------------------------------------------------------------
# The following tests - savepoint-11.* - test the interaction of 
# savepoints and creating or dropping tables and indexes in 
# auto-vacuum mode.
# 
do_test savepoint-11.1 {
  db close
  file delete -force test.db
  sqlite3 db test.db
  execsql {
    PRAGMA auto_vacuum = full;
    CREATE TABLE t1(a, b, UNIQUE(a, b));
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 VALUES(2, randstr(1000,1000));
  }
} {}
do_test savepoint-11.2 {
  execsql {
    SAVEPOINT one;
      CREATE TABLE t2(a, b, UNIQUE(a, b));
      SAVEPOINT two;
        CREATE TABLE t3(a, b, UNIQUE(a, b));
  }
} {}
integrity_check savepoint-11.3
do_test savepoint-11.4 {
  execsql { ROLLBACK TO two }
} {}
integrity_check savepoint-11.5
do_test savepoint-11.6 {
  execsql { 
    CREATE TABLE t3(a, b, UNIQUE(a, b));
    ROLLBACK TO one;
  }
} {}
integrity_check savepoint-11.7
do_test savepoint-11.8 {
  execsql { ROLLBACK }
  file size test.db
} {8192}


do_test savepoint-11.9 {
  execsql {
    DROP TABLE IF EXISTS t1;
    DROP TABLE IF EXISTS t2;
    DROP TABLE IF EXISTS t3;
  }
} {}
do_test savepoint-11.10 {
  execsql {
    BEGIN;
      CREATE TABLE t1(a, b);
      CREATE TABLE t2(x, y);
      INSERT INTO t2 VALUES(1, 2);
      SAVEPOINT one;
        INSERT INTO t2 VALUES(3, 4);
        SAVEPOINT two;
          DROP TABLE t1;
        ROLLBACK TO two;
  }
  execsql {SELECT * FROM t2}
} {1 2 3 4}
do_test savepoint-11.11 {
  execsql COMMIT
} {}
do_test savepoint-11.12 {
  execsql {SELECT * FROM t2}
} {1 2 3 4}

#-------------------------------------------------------------------------
# The following tests - savepoint-12.* - test the interaction of 
# savepoints and "ON CONFLICT ROLLBACK" clauses.
# 
do_test savepoint-12.1 {
  execsql {
    CREATE TABLE t4(a PRIMARY KEY, b);
    INSERT INTO t4 VALUES(1, 'one');
  }
} {}
do_test savepoint-12.2 {
  # The final statement of the following SQL hits a constraint when the
  # conflict handling mode is "OR ROLLBACK" and there are a couple of
  # open savepoints. At one point this would fail to clear the internal
  # record of the open savepoints, resulting in an assert() failure 
  # later on.
  # 
  catchsql {
    BEGIN;
      INSERT INTO t4 VALUES(2, 'two');
      SAVEPOINT sp1;
        INSERT INTO t4 VALUES(3, 'three');
        SAVEPOINT sp2;
          INSERT OR ROLLBACK INTO t4 VALUES(1, 'one');
  }
} {1 {column a is not unique}}
do_test savepoint-12.3 {
  sqlite3_get_autocommit db
} {1}
do_test savepoint-12.4 {
  execsql { SAVEPOINT one }
} {}

#-------------------------------------------------------------------------
# The following tests - savepoint-13.* - test the interaction of 
# savepoints and "journal_mode = off".
# 
do_test savepoint-13.1 {
  db close
  catch {file delete -force test.db}
  sqlite3 db test.db
  execsql {
    BEGIN;
      CREATE TABLE t1(a PRIMARY KEY, b);
      INSERT INTO t1 VALUES(1, 2);
    COMMIT;
    PRAGMA journal_mode = off;
  }
} {off}
do_test savepoint-13.2 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(3, 4);
    INSERT INTO t1 SELECT a+4,b+4  FROM t1;
    COMMIT;
  }
} {}
do_test savepoint-13.3 {
  execsql {
    BEGIN;
      INSERT INTO t1 VALUES(9, 10);
      SAVEPOINT s1;
        INSERT INTO t1 VALUES(11, 12);
    COMMIT;
  }
} {}
do_test savepoint-13.4 {
  execsql {
    BEGIN;
      INSERT INTO t1 VALUES(13, 14);
      SAVEPOINT s1;
        INSERT INTO t1 VALUES(15, 16);
      ROLLBACK TO s1;
    ROLLBACK;
    SELECT * FROM t1;
  }
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16}

finish_test

Added test/savepoint2.test.









































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# 2008 December 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: savepoint2.test,v 1.5 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Tests in this file are quite similar to those run by trans.test and
# avtrans.test.
#

proc signature {} {
  return [db eval {SELECT count(*), md5sum(x) FROM t3}]
}

do_test savepoint2-1 {
  execsql {
    PRAGMA cache_size=10;
    BEGIN;
    CREATE TABLE t3(x TEXT);
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    COMMIT;
    SELECT count(*) FROM t3;
  }
} {1024}

unset -nocomplain ::sig
unset -nocomplain SQL

set iterations 20

set SQL(1) {
  DELETE FROM t3 WHERE random()%10!=0;
  INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
  INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
}
set SQL(2) {
  DELETE FROM t3 WHERE random()%10!=0;
  INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
  DELETE FROM t3 WHERE random()%10!=0;
  INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
} 
set SQL(3) {
  UPDATE t3 SET x = randstr(10, 400) WHERE random()%10;
  INSERT INTO t3 SELECT x FROM t3 WHERE random()%10;
  DELETE FROM t3 WHERE random()%10;
}
set SQL(4) {
  INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE (random()%10 == 0);
}



for {set ii 2} {$ii < ($iterations+2)} {incr ii} {

  # Record the database signature. Optionally (every second run) open a
  # transaction. In all cases open savepoint "one", which may or may
  # not be a transaction savepoint, depending on whether or not a real
  # transaction has been opened.
  #
  do_test savepoint2-$ii.1 {
    if {$ii % 2} { execsql BEGIN }
    set ::sig(one) [signature]
    execsql "SAVEPOINT one"
  } {}

  # Execute some SQL on the database. Then rollback to savepoint "one".
  # Check that the database signature is as it was when "one" was opened.
  # 
  do_test savepoint2-$ii.2 {
    execsql $SQL(1)
    execsql "ROLLBACK to one"
    signature
  } $::sig(one)
  integrity_check savepoint2-$ii.2.1

  # Execute some SQL. Then open savepoint "two". Savepoint "two" is therefore
  # nested in savepoint "one".
  #
  do_test savepoint2-$ii.3 {
    execsql $SQL(1)
    set ::sig(two) [signature]
    execsql "SAVEPOINT two"
  } {}

  # More SQL changes. The rollback to savepoint "two". Check that the 
  # signature is as it was when savepoint "two" was opened.
  #
  do_test savepoint2-$ii.4 {
    execsql $SQL(2)
    execsql "ROLLBACK to two"
    signature
  } $::sig(two)
  integrity_check savepoint2-$ii.4.1

  # More SQL changes. The rollback to savepoint "two". Check that the 
  # signature is as it was when savepoint "two" was opened.
  #
  do_test savepoint2-$ii.5 {
    execsql $SQL(2)
    execsql "SAVEPOINT three"
    execsql $SQL(3)
    execsql "RELEASE three"
    execsql "ROLLBACK to one"
    signature
  } $::sig(one)

  # By this point the database is in the same state as it was at the 
  # top of the for{} loop (everything having been rolled back by the 
  # "ROLLBACK TO one" command above). So make a few changes to the 
  # database and COMMIT the open transaction, so that the next iteration
  # of the for{} loop works on a different dataset.
  # 
  # The transaction being committed here may have been opened normally using
  # "BEGIN", or may have been opened using a transaction savepoint created
  # by the "SAVEPOINT one" statement.
  #
  do_test savepoint2-$ii.6 {
    execsql $SQL(4)
    execsql COMMIT
    sqlite3_get_autocommit db
  } {1}
  integrity_check savepoint2-$ii.6.1
}

unset -nocomplain ::sig
unset -nocomplain SQL

finish_test

Added test/savepoint3.test.

















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# 2008 December 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: savepoint3.test,v 1.5 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

source $testdir/malloc_common.tcl

do_malloc_test savepoint3-1 -sqlprep {
  CREATE TABLE t1(a, b, c);
  INSERT INTO t1 VALUES(1, 2, 3);
} -sqlbody {
  SAVEPOINT one;
    INSERT INTO t1 VALUES(4, 5, 6);
    SAVEPOINT two;
      DELETE FROM t1;
    ROLLBACK TO two;
  RELEASE one;
}

do_malloc_test savepoint3-2 -sqlprep {
  PRAGMA cache_size = 10;
  CREATE TABLE t1(a, b, c);
  INSERT INTO t1 VALUES(randstr(400,400), randstr(400,400), randstr(400,400));
  INSERT INTO t1 SELECT 
    randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
  INSERT INTO t1 
    SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1;
} -sqlbody {
  PRAGMA cache_size = 10;
  SAVEPOINT one;
    DELETE FROM t1 WHERE rowid < 5;
    SAVEPOINT two;
      DELETE FROM t1 WHERE rowid > 10;
    ROLLBACK TO two;
  ROLLBACK TO one;
  RELEASE one;
}

do_ioerr_test savepoint3.3 -sqlprep {
  CREATE TABLE t1(a, b, c);
  INSERT INTO t1 VALUES(1, randstr(1000,1000), randstr(1000,1000));
  INSERT INTO t1 VALUES(2, randstr(1000,1000), randstr(1000,1000));
} -sqlbody {
  BEGIN;
    UPDATE t1 SET a = 3 WHERE a = 1;
    SAVEPOINT one;
      UPDATE t1 SET a = 4 WHERE a = 2;
  COMMIT;
} -cleanup {
  db eval {
    SAVEPOINT one;
    RELEASE one;
  }
}

# The following test does a really big savepoint rollback. One involving
# more than 4000 pages. The idea is to get a specific sqlite3BitvecSet()
# operation in pagerPlaybackSavepoint() to fail.
#do_malloc_test savepoint3-4 -sqlprep {
#  BEGIN;
#    CREATE TABLE t1(a, b);
#    CREATE INDEX i1 ON t1(a);
#    CREATE INDEX i2 ON t1(b);
#    INSERT INTO t1 VALUES(randstr(500,500), randstr(500,500));        --     1
#    INSERT INTO t1 VALUES(randstr(500,500), randstr(500,500));        --     2
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --     4
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --     8
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --    16
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --    32
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --    64
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --   128
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --   256
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --   512
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --  1024
#    INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; --  2048
#  COMMIT;
#  BEGIN;
#    SAVEPOINT abc;
#      UPDATE t1 SET a = randstr(500,500);
#} -sqlbody {
#    ROLLBACK TO abc;
#}


# Cause a specific malloc in savepoint rollback code to fail.
#
do_malloc_test savepoint3-4 -start 7 -sqlprep {
  PRAGMA auto_vacuum = incremental;
  PRAGMA cache_size = 1000;

  CREATE TABLE t1(a, b);
  CREATE TABLE t2(a, b);
  CREATE TABLE t3(a, b);
  INSERT INTO t1 VALUES(1, randstr(500,500));
  INSERT INTO t1 VALUES(2, randstr(500,500));
  INSERT INTO t1 VALUES(3, randstr(500,500));
  DELETE FROM t1;

  BEGIN;
    INSERT INTO t1 VALUES(1, randstr(500,500));
    INSERT INTO t1 VALUES(2, randstr(500,500));
    INSERT INTO t1 VALUES(3, randstr(500,500));
    DROP TABLE t3;                  -- Page 5 of the database file is now free.
    DROP TABLE t2;                  -- Page 4 of the database file is now free.

    SAVEPOINT abc;
      PRAGMA incremental_vacuum;
} -sqlbody {
  ROLLBACK TO abc;
}


finish_test

Added test/savepoint4.test.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# 2008 December 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: savepoint4.test,v 1.7 2009/06/09 15:25:33 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !crashtest {
  finish_test
  return
}

proc signature {} {
  return [db eval {SELECT count(*), md5sum(x) FROM t1}]
}

set ITERATIONS 25                   ;# Number of iterations for savepoint4-1
set ITERATIONS2 13                  ;# Number of iterations for savepoint4-2
expr srand(0)

do_test savepoint4-1 {
  execsql {
    PRAGMA cache_size=10;
    BEGIN;
    CREATE TABLE t1(x TEXT);
    INSERT INTO t1 VALUES(randstr(10,400));
    INSERT INTO t1 VALUES(randstr(10,400));
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {1024}


unset -nocomplain ::sig

for {set ii 1} {$ii<=$ITERATIONS} {incr ii} {
  set ::sig [signature]

  for {set iDelay 1 ; set crashed 1} {$crashed} {incr iDelay} {

    do_test savepoint4-1.$ii.1.$iDelay {
      set ret [crashsql -delay $iDelay -file test.db-journal {
        PRAGMA cache_size = 20;
        SAVEPOINT one;
          DELETE FROM t1 WHERE random()%2==0;
          SAVEPOINT two;
            INSERT INTO t1 SELECT randstr(10,10)||x FROM t1;
           ROLLBACK TO two;
            UPDATE t1 SET x = randstr(10, 400) WHERE random()%10;
          RELEASE two;
        ROLLBACK TO one;
        RELEASE one;
      }]
      signature
    } $::sig

    set crashed [lindex $ret 0]
    integrity_check savepoint4-1.$ii.1.$iDelay.integrity
  }

  do_test savepoint4-1.$ii.2 {
    execsql {
      DELETE FROM t1 WHERE random()%10==0;
      INSERT INTO t1 SELECT randstr(10,10)||x FROM t1 WHERE random()%9==0;
    }
  } {}
}

do_test savepoint4-2 {
  execsql {
    PRAGMA cache_size=10;
    DROP TABLE IF EXISTS t1;
    BEGIN;
    CREATE TABLE t1(x TEXT);
    CREATE INDEX i1 ON t1(x);
    INSERT INTO t1 VALUES(randstr(10,400));
    INSERT INTO t1 VALUES(randstr(10,400));
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    INSERT INTO t1 SELECT randstr(10,400) FROM t1;
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {256}

for {set ii 1} {$ii<=$ITERATIONS2} {incr ii} {
  set ::sig [signature]
  set file test.db-journal

  for {set iDelay 1 ; set crashed 1} {$crashed} {incr iDelay} {

    do_test savepoint4-2.$ii.1.$iDelay {

      set ret [crashsql -delay $iDelay -file $file {
        SAVEPOINT one;
          INSERT INTO t1 SELECT * FROM t1 WHERE rowid<50;
         ROLLBACK TO one;
          INSERT INTO t1 SELECT * FROM t1 WHERE rowid<50;
          SAVEPOINT two;
            DELETE FROM t1 WHERE (random()%10)==0;
            SAVEPOINT three;
              DELETE FROM t1 WHERE (random()%10)==0;
              SAVEPOINT four;
                DELETE FROM t1 WHERE (random()%10)==0;
          RELEASE two;

          SAVEPOINT three;
            UPDATE t1 SET x = substr(x||x, 12, 100000) WHERE (rowid%12)==0;
            SAVEPOINT four;
              UPDATE t1 SET x = substr(x||x, 14, 100000) WHERE (rowid%14)==0;
           ROLLBACK TO three;
            UPDATE t1 SET x = substr(x||x, 13, 100000) WHERE (rowid%13)==0;
          RELEASE three;

        DELETE FROM t1 WHERE rowid > (
          SELECT rowid FROM t1 ORDER BY rowid ASC LIMIT 1 OFFSET 256
        );
        RELEASE one;
      }]

      set crashed [lindex $ret 0]
      if {$crashed} {
        signature
      } else {
        set ::sig
      }
    } $::sig

    integrity_check savepoint4-2.$ii.1.$iDelay.integrity

    if {$crashed == 0 && $file == "test.db-journal"} {
      set crashed 1
      set iDelay 0
      set file test.db
      set ::sig [signature]
    }
  }

  do_test savepoint4-2.$ii.2 {
    execsql {
      DELETE FROM t1 WHERE random()%10==0;
      INSERT INTO t1 SELECT randstr(10,10)||x FROM t1 WHERE random()%9==0;
    }
  } {}
}

finish_test

Added test/savepoint5.test.





























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 2009 January 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Verify that a SAVEPOINT on a new, empty database followed by a
# ROLLBACK TO that savepoint starts over again with another new
# empty database.
#
# $Id: savepoint5.test,v 1.1 2009/01/02 21:08:09 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test savepoint5-1.1 {
  db eval {
    SAVEPOINT sp1;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT count(*) FROM sqlite_master;
    SELECT * FROM t1;
  }
} {1 1}
do_test savepoint5-1.2 {
  db eval {
    ROLLBACK TO sp1;
    SELECT count(*) FROM sqlite_master;
  }
} {0}
do_test savepoint5-1.3 {
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT count(*) FROM sqlite_master;
    SELECT * FROM t1;
  }
} {1 1}


finish_test

Added test/savepoint6.test.

































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# 2009 January 3
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: savepoint6.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc sql {zSql} {
  uplevel db eval [list $zSql]
  #puts stderr "$zSql ;"
}

set DATABASE_SCHEMA {
    PRAGMA auto_vacuum = incremental;
    CREATE TABLE t1(x, y);
    CREATE UNIQUE INDEX i1 ON t1(x);
    CREATE INDEX i2 ON t1(y);
}

#--------------------------------------------------------------------------
# In memory database state.
#
# ::lSavepoint is a list containing one entry for each active savepoint. The
# first entry in the list corresponds to the most recently opened savepoint.
# Each entry consists of two elements:
#
#   1. The savepoint name.
#
#   2. A serialized Tcl array representing the contents of table t1 at the
#      start of the savepoint. The keys of the array are the x values. The
#      values are the y values.
#  
# Array ::aEntry contains the contents of database table t1. Array keys are
# x values, the array data values are y values.
#
set lSavepoint [list]
array set aEntry [list]

proc x_to_y {x} {
  set nChar [expr int(rand()*250) + 250]
  set str " $nChar [string repeat $x. $nChar]"
  string range $str 1 $nChar
}
#--------------------------------------------------------------------------

#-------------------------------------------------------------------------
# Procs to operate on database:
#
#   savepoint NAME
#   rollback  NAME
#   release   NAME
#
#   insert_rows XVALUES
#   delete_rows XVALUES
#
proc savepoint {zName} {
  catch { sql "SAVEPOINT $zName" }
  lappend ::lSavepoint [list $zName [array get ::aEntry]]
}

proc rollback {zName} {
  catch { sql "ROLLBACK TO $zName" }
  for {set i [expr {[llength $::lSavepoint]-1}]} {$i>=0} {incr i -1} {
    set zSavepoint [lindex $::lSavepoint $i 0]
    if {$zSavepoint eq $zName} {
      unset -nocomplain ::aEntry
      array set ::aEntry [lindex $::lSavepoint $i 1]


      if {$i+1 < [llength $::lSavepoint]} {
        set ::lSavepoint [lreplace $::lSavepoint [expr $i+1] end]
      }
      break
    }
  }
}

proc release {zName} {
  catch { sql "RELEASE $zName" }
  for {set i [expr {[llength $::lSavepoint]-1}]} {$i>=0} {incr i -1} {
    set zSavepoint [lindex $::lSavepoint $i 0]
    if {$zSavepoint eq $zName} {
      set ::lSavepoint [lreplace $::lSavepoint $i end]
      break
    }
  }

  if {[llength $::lSavepoint] == 0} {
    #puts stderr "-- End of transaction!!!!!!!!!!!!!"
  }
}

proc insert_rows {lX} {
  foreach x $lX {
    set y [x_to_y $x]

    # Update database [db]
    sql "INSERT OR REPLACE INTO t1 VALUES($x, '$y')"

    # Update the Tcl database.
    set ::aEntry($x) $y
  }
}

proc delete_rows {lX} {
  foreach x $lX {
    # Update database [db]
    sql "DELETE FROM t1 WHERE x = $x"

    # Update the Tcl database.
    unset -nocomplain ::aEntry($x)
  }
}
#-------------------------------------------------------------------------

#-------------------------------------------------------------------------
# Proc to compare database content with the in-memory representation.
#
#   checkdb
#
proc checkdb {} {
  set nEntry [db one {SELECT count(*) FROM t1}]
  set nEntry2 [array size ::aEntry]
  if {$nEntry != $nEntry2} {
    error "$nEntry entries in database, $nEntry2 entries in array"
  }
  db eval {SELECT x, y FROM t1} {
    if {![info exists ::aEntry($x)]} {
      error "Entry $x exists in database, but not in array"
    }
    if {$::aEntry($x) ne $y} {
      error "Entry $x is set to {$y} in database, {$::aEntry($x)} in array"
    }
  }

  db eval { PRAGMA integrity_check }
}
#-------------------------------------------------------------------------

#-------------------------------------------------------------------------
# Proc to return random set of x values.
#
#   random_integers
#
proc random_integers {nRes nRange} {
  set ret [list]
  for {set i 0} {$i<$nRes} {incr i} {
    lappend ret [expr int(rand()*$nRange)]
  }
  return $ret
} 
#-------------------------------------------------------------------------

proc database_op {} {
  set i [expr int(rand()*2)] 
  if {$i==0} {
    insert_rows [random_integers 100 1000]
  }
  if {$i==1} {
    delete_rows [random_integers 100 1000]
    set i [expr int(rand()*3)] 
    if {$i==0} {
      sql {PRAGMA incremental_vacuum}
    }
  }
}

proc savepoint_op {} {
  set names {one two three four five}
  set cmds  {savepoint savepoint savepoint savepoint release rollback}

  set C [lindex $cmds [expr int(rand()*6)]]
  set N [lindex $names [expr int(rand()*5)]]

  #puts stderr "   $C $N ;  "
  #flush stderr

  $C $N
  return ok
}

expr srand(0)

############################################################################
############################################################################
# Start of test cases.

do_test savepoint6-1.1 {
  sql $DATABASE_SCHEMA
} {}
do_test savepoint6-1.2 {
  insert_rows {
    497 166 230 355 779 588 394 317 290 475 362 193 805 851 564 
    763 44 930 389 819 765 760 966 280 538 414 500 18 25 287 320 
    30 382 751 87 283 981 429 630 974 421 270 810 405 
  }

  savepoint one
  insert_rows 858
  delete_rows 930
  savepoint two
    execsql {PRAGMA incremental_vacuum}
    savepoint three
      insert_rows 144
     rollback three
    rollback two
  release one

  execsql {SELECT count(*) FROM t1}
} {44}

foreach zSetup [list {
  set testname normal
  sqlite3 db test.db
} {
  set testname tempdb
  sqlite3 db ""
} {
  if {[catch {set ::permutations_test_prefix} z] == 0 && $z eq "journaltest"} {
    continue
  }
  set testname nosync
  sqlite3 db test.db
  sql { PRAGMA synchronous = off }
} {
  set testname smallcache
  sqlite3 db test.db
  sql { PRAGMA cache_size = 10 }
}] {

  unset -nocomplain ::lSavepoint
  unset -nocomplain ::aEntry

  catch { db close }
  file delete -force test.db
  eval $zSetup
  sql $DATABASE_SCHEMA

  do_test savepoint6-$testname.setup {
    savepoint one
    insert_rows [random_integers 100 1000]
    release one
    checkdb
  } {ok}
  
  for {set i 0} {$i < 1000} {incr i} {
    do_test savepoint6-$testname.$i.1 {
      savepoint_op
      checkdb
    } {ok}
  
    do_test savepoint6-$testname.$i.2 {
      database_op
      database_op
      checkdb
    } {ok}
  }
}

unset -nocomplain ::lSavepoint
unset -nocomplain ::aEntry

finish_test

Added test/schema.test.







































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# 2005 Jan 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file tests the various conditions under which an SQLITE_SCHEMA
# error should be returned.
#
# $Id: schema.test,v 1.9 2009/02/04 17:40:58 drh Exp $

#---------------------------------------------------------------------
# When any of the following types of SQL statements or actions are 
# executed, all pre-compiled statements are invalidated. An attempt
# to execute an invalidated statement always returns SQLITE_SCHEMA.
#
# CREATE/DROP TABLE...................................schema-1.*
# CREATE/DROP VIEW....................................schema-2.*
# CREATE/DROP TRIGGER.................................schema-3.*
# CREATE/DROP INDEX...................................schema-4.*
# DETACH..............................................schema-5.*
# Deleting a user-function............................schema-6.*
# Deleting a collation sequence.......................schema-7.*
# Setting or changing the authorization function......schema-8.*
# Rollback of a DDL statement.........................schema-12.*
#
# Test cases schema-9.* and schema-10.* test some specific bugs
# that came up during development.
#
# Test cases schema-11.* test that it is impossible to delete or
# change a collation sequence or user-function while SQL statements
# are executing. Adding new collations or functions is allowed.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test schema-1.1 {
  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    CREATE TABLE abc(a, b, c);
  }
  sqlite3_step $::STMT
} {SQLITE_ERROR}
do_test schema-1.2 {
  sqlite3_finalize $::STMT
} {SQLITE_SCHEMA}
do_test schema-1.3 {
  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    DROP TABLE abc;
  }
  sqlite3_step $::STMT
} {SQLITE_ERROR}
do_test schema-1.4 {
  sqlite3_finalize $::STMT
} {SQLITE_SCHEMA}

ifcapable view {
  do_test schema-2.1 {
    set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      CREATE VIEW v1 AS SELECT * FROM sqlite_master;
    }
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-2.2 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
  do_test schema-2.3 {
    set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      DROP VIEW v1;
    }
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-2.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
}

ifcapable trigger {
  do_test schema-3.1 {
    execsql {
      CREATE TABLE abc(a, b, c);
    }
    set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      CREATE TRIGGER abc_trig AFTER INSERT ON abc BEGIN
        SELECT 1, 2, 3;
      END;
    }
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-3.2 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
  do_test schema-3.3 {
    set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      DROP TRIGGER abc_trig;
    }
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-3.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
}

do_test schema-4.1 {
  catchsql {
    CREATE TABLE abc(a, b, c);
  }
  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    CREATE INDEX abc_index ON abc(a);
  }
  sqlite3_step $::STMT
} {SQLITE_ERROR}
do_test schema-4.2 {
  sqlite3_finalize $::STMT
} {SQLITE_SCHEMA}
do_test schema-4.3 {
  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    DROP INDEX abc_index;
  }
  sqlite3_step $::STMT
} {SQLITE_ERROR}
do_test schema-4.4 {
  sqlite3_finalize $::STMT
} {SQLITE_SCHEMA}

#---------------------------------------------------------------------
# Tests 5.1 to 5.4 check that prepared statements are invalidated when
# a database is DETACHed (but not when one is ATTACHed).
#
ifcapable attach {
  do_test schema-5.1 {
    set sql {SELECT * FROM abc;}
    set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
    execsql {
      ATTACH 'test2.db' AS aux;
    }
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema-5.2 {
    sqlite3_reset $::STMT
  } {SQLITE_OK}
  do_test schema-5.3 {
    execsql {
      DETACH aux;
    }
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-5.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
}

#---------------------------------------------------------------------
# Tests 6.* check that prepared statements are invalidated when
# a user-function is deleted (but not when one is added).
do_test schema-6.1 {
  set sql {SELECT * FROM abc;}
  set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
  db function hello_function {}
  sqlite3_step $::STMT
} {SQLITE_DONE}
do_test schema-6.2 {
  sqlite3_reset $::STMT
} {SQLITE_OK}
do_test schema-6.3 {
  sqlite_delete_function $::DB hello_function
  sqlite3_step $::STMT
} {SQLITE_ERROR}
do_test schema-6.4 {
  sqlite3_finalize $::STMT
} {SQLITE_SCHEMA}

#---------------------------------------------------------------------
# Tests 7.* check that prepared statements are invalidated when
# a collation sequence is deleted (but not when one is added).
#
ifcapable utf16 {
  do_test schema-7.1 {
    set sql {SELECT * FROM abc;}
    set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
    add_test_collate $::DB 1 1 1
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema-7.2 {
    sqlite3_reset $::STMT
  } {SQLITE_OK}
  do_test schema-7.3 {
    add_test_collate $::DB 0 0 0 
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-7.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
}

#---------------------------------------------------------------------
# Tests 8.1 and 8.2 check that prepared statements are invalidated when
# the authorization function is set.
#
ifcapable auth {
  do_test schema-8.1 {
    set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    db auth {}
    sqlite3_step $::STMT
  } {SQLITE_ERROR}
  do_test schema-8.3 {
    sqlite3_finalize $::STMT
  } {SQLITE_SCHEMA}
}

#---------------------------------------------------------------------
# schema-9.1: Test that if a table is dropped by one database connection, 
#             other database connections are aware of the schema change.
# schema-9.2: Test that if a view is dropped by one database connection,
#             other database connections are aware of the schema change.
#
do_test schema-9.1 {
  sqlite3 db2 test.db
  execsql {
    DROP TABLE abc;
  } db2
  db2 close
  catchsql {
    SELECT * FROM abc;
  }
} {1 {no such table: abc}}
execsql {
  CREATE TABLE abc(a, b, c);
}
ifcapable view {
  do_test schema-9.2 {
    execsql {
      CREATE VIEW abcview AS SELECT * FROM abc;
    }
    sqlite3 db2 test.db
    execsql {
      DROP VIEW abcview;
    } db2
    db2 close
    catchsql {
      SELECT * FROM abcview;
    }
  } {1 {no such table: abcview}}
}

#---------------------------------------------------------------------
# Test that if a CREATE TABLE statement fails because there are other
# btree cursors open on the same database file it does not corrupt
# the sqlite_master table.
#
# 2007-05-02: These tests have been overcome by events.  Open btree
# cursors no longer block CREATE TABLE.  But there is no reason not
# to keep the tests in the test suite.
#
do_test schema-10.1 {
  execsql {
    INSERT INTO abc VALUES(1, 2, 3);
  }
  set sql {SELECT * FROM abc}
  set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema-10.2 {
  catchsql {
    CREATE TABLE t2(a, b, c);
  }
} {0 {}}
do_test schema-10.3 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test schema-10.4 {
  sqlite3 db2 test.db
  execsql {
    SELECT * FROM abc
  } db2
} {1 2 3}
do_test schema-10.5 {
  db2 close
} {}

#---------------------------------------------------------------------
# Attempting to delete or replace a user-function or collation sequence 
# while there are active statements returns an SQLITE_BUSY error.
#
# schema-11.1 - 11.4: User function.
# schema-11.5 - 11.8: Collation sequence.
#
do_test schema-11.1 {
  db function tstfunc {}
  set sql {SELECT * FROM abc}
  set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema-11.2 {
  sqlite_delete_function $::DB tstfunc
} {SQLITE_BUSY}
do_test schema-11.3 {
  set rc [catch {
    db function tstfunc {}
  } msg]
  list $rc $msg
} {1 {unable to delete/modify user-function due to active statements}}
do_test schema-11.4 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test schema-11.5 {
  db collate tstcollate {}
  set sql {SELECT * FROM abc}
  set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema-11.6 {
  sqlite_delete_collation $::DB tstcollate
} {SQLITE_BUSY}
do_test schema-11.7 {
  set rc [catch {
    db collate tstcollate {}
  } msg]
  list $rc $msg
} {1 {unable to delete/modify collation sequence due to active statements}}
do_test schema-11.8 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}

# The following demonstrates why statements need to be expired whenever
# there is a rollback (explicit or otherwise).
#
do_test schema-12.1 {
  # Begin a transaction and create a table. This increments 
  # the schema cookie. Then compile an SQL statement, using
  # the current (incremented) value of the cookie.
  execsql {
    BEGIN;
    CREATE TABLE t3(a, b, c);
  }
  set ::STMT [sqlite3_prepare $::DB "CREATE TABLE t4(a,b,c)" -1 TAIL]

  # Rollback the transaction, resetting the schema cookie to the value
  # it had at the start of this test case. Then create a table, 
  # incrementing the schema cookie.
  execsql {
    ROLLBACK;
    CREATE TABLE t4(a, b, c);
  }

  # The schema cookie now has the same value as it did when SQL statement
  # $::STMT was prepared. So unless it has been expired, it would be
  # possible to run the "CREATE TABLE t4" statement and create a
  # duplicate table.
  list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT]
} {SQLITE_ERROR SQLITE_SCHEMA}

do_test schema-13.1 {
  set S [sqlite3_prepare_v2 db "SELECT * FROM sqlite_master" -1 dummy]
  db function hello hello
  db function hello {}
  db auth auth
  proc auth {args} {
    if {[lindex $args 0] == "SQLITE_READ"} {return SQLITE_DENY}
    return SQLITE_OK
  }
  sqlite3_step $S
} {SQLITE_SCHEMA}

do_test schema-13.2 {
  sqlite3_step $S
} {SQLITE_SCHEMA}

do_test schema-13.3 {
  sqlite3_finalize $S
} {SQLITE_SCHEMA}

finish_test

Added test/schema2.test.









































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# 2006 November 08
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file tests the various conditions under which an SQLITE_SCHEMA
# error should be returned.  This is a copy of schema.test that
# has been altered to use sqlite3_prepare_v2 instead of sqlite3_prepare
#
# $Id: schema2.test,v 1.4 2009/02/04 17:40:58 drh Exp $

#---------------------------------------------------------------------
# When any of the following types of SQL statements or actions are 
# executed, all pre-compiled statements are invalidated. An attempt
# to execute an invalidated statement always returns SQLITE_SCHEMA.
#
# CREATE/DROP TABLE...................................schema2-1.*
# CREATE/DROP VIEW....................................schema2-2.*
# CREATE/DROP TRIGGER.................................schema2-3.*
# CREATE/DROP INDEX...................................schema2-4.*
# DETACH..............................................schema2-5.*
# Deleting a user-function............................schema2-6.*
# Deleting a collation sequence.......................schema2-7.*
# Setting or changing the authorization function......schema2-8.*
#
# Test cases schema2-9.* and schema2-10.* test some specific bugs
# that came up during development.
#
# Test cases schema2-11.* test that it is impossible to delete or
# change a collation sequence or user-function while SQL statements
# are executing. Adding new collations or functions is allowed.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test schema2-1.1 {
  set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    CREATE TABLE abc(a, b, c);
  }
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema2-1.2 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test schema2-1.3 {
  set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    DROP TABLE abc;
  }
  sqlite3_step $::STMT
} {SQLITE_DONE}
do_test schema2-1.4 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}


ifcapable view {
  do_test schema2-2.1 {
    set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      CREATE VIEW v1 AS SELECT * FROM sqlite_master;
    }
    sqlite3_step $::STMT
  } {SQLITE_ROW}
  do_test schema2-2.2 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
  do_test schema2-2.3 {
    set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      DROP VIEW v1;
    }
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema2-2.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
}

ifcapable trigger {
  do_test schema2-3.1 {
    execsql {
      CREATE TABLE abc(a, b, c);
    }
    set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      CREATE TRIGGER abc_trig AFTER INSERT ON abc BEGIN
        SELECT 1, 2, 3;
      END;
    }
    sqlite3_step $::STMT
  } {SQLITE_ROW}
  do_test schema2-3.2 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
  do_test schema2-3.3 {
    set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    execsql {
      DROP TRIGGER abc_trig;
    }
    sqlite3_step $::STMT
  } {SQLITE_ROW}
  do_test schema2-3.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
}

do_test schema2-4.1 {
  catchsql {
    CREATE TABLE abc(a, b, c);
  }
  set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    CREATE INDEX abc_index ON abc(a);
  }
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema2-4.2 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test schema2-4.3 {
  set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
    DROP INDEX abc_index;
  }
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema2-4.4 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}

#---------------------------------------------------------------------
# Tests 5.1 to 5.4 check that prepared statements are invalidated when
# a database is DETACHed (but not when one is ATTACHed).
#
ifcapable attach {
  do_test schema2-5.1 {
    set sql {SELECT * FROM abc;}
    set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL]
    execsql {
      ATTACH 'test2.db' AS aux;
    }
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema2-5.2 {
    sqlite3_reset $::STMT
  } {SQLITE_OK}
  do_test schema2-5.3 {
    execsql {
      DETACH aux;
    }
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema2-5.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
}

#---------------------------------------------------------------------
# Tests 6.* check that prepared statements are invalidated when
# a user-function is deleted (but not when one is added).
do_test schema2-6.1 {
  set sql {SELECT * FROM abc;}
  set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL]
  db function hello_function {}
  sqlite3_step $::STMT
} {SQLITE_DONE}
do_test schema2-6.2 {
  sqlite3_reset $::STMT
} {SQLITE_OK}
do_test schema2-6.3 {
  sqlite_delete_function $::DB hello_function
  sqlite3_step $::STMT
} {SQLITE_DONE}
do_test schema2-6.4 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}

#---------------------------------------------------------------------
# Tests 7.* check that prepared statements are invalidated when
# a collation sequence is deleted (but not when one is added).
#
ifcapable utf16 {
  do_test schema2-7.1 {
    set sql {SELECT * FROM abc;}
    set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL]
    add_test_collate $::DB 1 1 1
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema2-7.2 {
    sqlite3_reset $::STMT
  } {SQLITE_OK}
  do_test schema2-7.3 {
    add_test_collate $::DB 0 0 0 
    sqlite3_step $::STMT
  } {SQLITE_DONE}
  do_test schema2-7.4 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
}

#---------------------------------------------------------------------
# Tests 8.1 and 8.2 check that prepared statements are invalidated when
# the authorization function is set.
#
ifcapable auth {
  do_test schema2-8.1 {
    set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    db auth {}
    sqlite3_step $::STMT
  } {SQLITE_ROW}
  do_test schema2-8.3 {
    sqlite3_finalize $::STMT
  } {SQLITE_OK}
}

#---------------------------------------------------------------------
# schema2-9.1: Test that if a table is dropped by one database connection, 
#             other database connections are aware of the schema change.
# schema2-9.2: Test that if a view is dropped by one database connection,
#             other database connections are aware of the schema change.
#
do_test schema2-9.1 {
  sqlite3 db2 test.db
  execsql {
    DROP TABLE abc;
  } db2
  db2 close
  catchsql {
    SELECT * FROM abc;
  }
} {1 {no such table: abc}}
execsql {
  CREATE TABLE abc(a, b, c);
}
ifcapable view {
  do_test schema2-9.2 {
    execsql {
      CREATE VIEW abcview AS SELECT * FROM abc;
    }
    sqlite3 db2 test.db
    execsql {
      DROP VIEW abcview;
    } db2
    db2 close
    catchsql {
      SELECT * FROM abcview;
    }
  } {1 {no such table: abcview}}
}

#---------------------------------------------------------------------
# Test that if a CREATE TABLE statement fails because there are other
# btree cursors open on the same database file it does not corrupt
# the sqlite_master table.
#
# 2007-05-02: These tests have been overcome by events.  Open btree
# cursors no longer block CREATE TABLE.  But there is no reason not
# to keep the tests in the test suite.
#
do_test schema2-10.1 {
  execsql {
    INSERT INTO abc VALUES(1, 2, 3);
  }
  set sql {SELECT * FROM abc}
  set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema2-10.2 {
  catchsql {
    CREATE TABLE t2(a, b, c);
  }
} {0 {}}
do_test schema2-10.3 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test schema2-10.4 {
  sqlite3 db2 test.db
  execsql {
    SELECT * FROM abc
  } db2
} {1 2 3}
do_test schema2-10.5 {
  db2 close
} {}

#---------------------------------------------------------------------
# Attempting to delete or replace a user-function or collation sequence 
# while there are active statements returns an SQLITE_BUSY error.
#
# schema2-11.1 - 11.4: User function.
# schema2-11.5 - 11.8: Collation sequence.
#
do_test schema2-11.1 {
  db function tstfunc {}
  set sql {SELECT * FROM abc}
  set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema2-11.2 {
  sqlite_delete_function $::DB tstfunc
} {SQLITE_BUSY}
do_test schema2-11.3 {
  set rc [catch {
    db function tstfunc {}
  } msg]
  list $rc $msg
} {1 {unable to delete/modify user-function due to active statements}}
do_test schema2-11.4 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test schema2-11.5 {
  db collate tstcollate {}
  set sql {SELECT * FROM abc}
  set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test schema2-11.6 {
  sqlite_delete_collation $::DB tstcollate
} {SQLITE_BUSY}
do_test schema2-11.7 {
  set rc [catch {
    db collate tstcollate {}
  } msg]
  list $rc $msg
} {1 {unable to delete/modify collation sequence due to active statements}}
do_test schema2-11.8 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}

finish_test

Added test/select1.test.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the SELECT statement.
#
# $Id: select1.test,v 1.70 2009/05/28 01:00:56 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Try to select on a non-existant table.
#
do_test select1-1.1 {
  set v [catch {execsql {SELECT * FROM test1}} msg]
  lappend v $msg
} {1 {no such table: test1}}


execsql {CREATE TABLE test1(f1 int, f2 int)}

do_test select1-1.2 {
  set v [catch {execsql {SELECT * FROM test1, test2}} msg]
  lappend v $msg
} {1 {no such table: test2}}
do_test select1-1.3 {
  set v [catch {execsql {SELECT * FROM test2, test1}} msg]
  lappend v $msg
} {1 {no such table: test2}}

execsql {INSERT INTO test1(f1,f2) VALUES(11,22)}


# Make sure the columns are extracted correctly.
#
do_test select1-1.4 {
  execsql {SELECT f1 FROM test1}
} {11}
do_test select1-1.5 {
  execsql {SELECT f2 FROM test1}
} {22}
do_test select1-1.6 {
  execsql {SELECT f2, f1 FROM test1}
} {22 11}
do_test select1-1.7 {
  execsql {SELECT f1, f2 FROM test1}
} {11 22}
do_test select1-1.8 {
  execsql {SELECT * FROM test1}
} {11 22}
do_test select1-1.8.1 {
  execsql {SELECT *, * FROM test1}
} {11 22 11 22}
do_test select1-1.8.2 {
  execsql {SELECT *, min(f1,f2), max(f1,f2) FROM test1}
} {11 22 11 22}
do_test select1-1.8.3 {
  execsql {SELECT 'one', *, 'two', * FROM test1}
} {one 11 22 two 11 22}

execsql {CREATE TABLE test2(r1 real, r2 real)}
execsql {INSERT INTO test2(r1,r2) VALUES(1.1,2.2)}

do_test select1-1.9 {
  execsql {SELECT * FROM test1, test2}
} {11 22 1.1 2.2}
do_test select1-1.9.1 {
  execsql {SELECT *, 'hi' FROM test1, test2}
} {11 22 1.1 2.2 hi}
do_test select1-1.9.2 {
  execsql {SELECT 'one', *, 'two', * FROM test1, test2}
} {one 11 22 1.1 2.2 two 11 22 1.1 2.2}
do_test select1-1.10 {
  execsql {SELECT test1.f1, test2.r1 FROM test1, test2}
} {11 1.1}
do_test select1-1.11 {
  execsql {SELECT test1.f1, test2.r1 FROM test2, test1}
} {11 1.1}
do_test select1-1.11.1 {
  execsql {SELECT * FROM test2, test1}
} {1.1 2.2 11 22}
do_test select1-1.11.2 {
  execsql {SELECT * FROM test1 AS a, test1 AS b}
} {11 22 11 22}
do_test select1-1.12 {
  execsql {SELECT max(test1.f1,test2.r1), min(test1.f2,test2.r2)
           FROM test2, test1}
} {11 2.2}
do_test select1-1.13 {
  execsql {SELECT min(test1.f1,test2.r1), max(test1.f2,test2.r2)
           FROM test1, test2}
} {1.1 22}

set long {This is a string that is too big to fit inside a NBFS buffer}
do_test select1-2.0 {
  execsql "
    DROP TABLE test2;
    DELETE FROM test1;
    INSERT INTO test1 VALUES(11,22);
    INSERT INTO test1 VALUES(33,44);
    CREATE TABLE t3(a,b);
    INSERT INTO t3 VALUES('abc',NULL);
    INSERT INTO t3 VALUES(NULL,'xyz');
    INSERT INTO t3 SELECT * FROM test1;
    CREATE TABLE t4(a,b);
    INSERT INTO t4 VALUES(NULL,'$long');
    SELECT * FROM t3;
  "
} {abc {} {} xyz 11 22 33 44}

# Error messges from sqliteExprCheck
#
do_test select1-2.1 {
  set v [catch {execsql {SELECT count(f1,f2) FROM test1}} msg]
  lappend v $msg
} {1 {wrong number of arguments to function count()}}
do_test select1-2.2 {
  set v [catch {execsql {SELECT count(f1) FROM test1}} msg]
  lappend v $msg
} {0 2}
do_test select1-2.3 {
  set v [catch {execsql {SELECT Count() FROM test1}} msg]
  lappend v $msg
} {0 2}
do_test select1-2.4 {
  set v [catch {execsql {SELECT COUNT(*) FROM test1}} msg]
  lappend v $msg
} {0 2}
do_test select1-2.5 {
  set v [catch {execsql {SELECT COUNT(*)+1 FROM test1}} msg]
  lappend v $msg
} {0 3}
do_test select1-2.5.1 {
  execsql {SELECT count(*),count(a),count(b) FROM t3}
} {4 3 3}
do_test select1-2.5.2 {
  execsql {SELECT count(*),count(a),count(b) FROM t4}
} {1 0 1}
do_test select1-2.5.3 {
  execsql {SELECT count(*),count(a),count(b) FROM t4 WHERE b=5}
} {0 0 0}
do_test select1-2.6 {
  set v [catch {execsql {SELECT min(*) FROM test1}} msg]
  lappend v $msg
} {1 {wrong number of arguments to function min()}}
do_test select1-2.7 {
  set v [catch {execsql {SELECT Min(f1) FROM test1}} msg]
  lappend v $msg
} {0 11}
do_test select1-2.8 {
  set v [catch {execsql {SELECT MIN(f1,f2) FROM test1}} msg]
  lappend v [lsort $msg]
} {0 {11 33}}
do_test select1-2.8.1 {
  execsql {SELECT coalesce(min(a),'xyzzy') FROM t3}
} {11}
do_test select1-2.8.2 {
  execsql {SELECT min(coalesce(a,'xyzzy')) FROM t3}
} {11}
do_test select1-2.8.3 {
  execsql {SELECT min(b), min(b) FROM t4}
} [list $long $long]
do_test select1-2.9 {
  set v [catch {execsql {SELECT MAX(*) FROM test1}} msg]
  lappend v $msg
} {1 {wrong number of arguments to function MAX()}}
do_test select1-2.10 {
  set v [catch {execsql {SELECT Max(f1) FROM test1}} msg]
  lappend v $msg
} {0 33}
do_test select1-2.11 {
  set v [catch {execsql {SELECT max(f1,f2) FROM test1}} msg]
  lappend v [lsort $msg]
} {0 {22 44}}
do_test select1-2.12 {
  set v [catch {execsql {SELECT MAX(f1,f2)+1 FROM test1}} msg]
  lappend v [lsort $msg]
} {0 {23 45}}
do_test select1-2.13 {
  set v [catch {execsql {SELECT MAX(f1)+1 FROM test1}} msg]
  lappend v $msg
} {0 34}
do_test select1-2.13.1 {
  execsql {SELECT coalesce(max(a),'xyzzy') FROM t3}
} {abc}
do_test select1-2.13.2 {
  execsql {SELECT max(coalesce(a,'xyzzy')) FROM t3}
} {xyzzy}
do_test select1-2.14 {
  set v [catch {execsql {SELECT SUM(*) FROM test1}} msg]
  lappend v $msg
} {1 {wrong number of arguments to function SUM()}}
do_test select1-2.15 {
  set v [catch {execsql {SELECT Sum(f1) FROM test1}} msg]
  lappend v $msg
} {0 44}
do_test select1-2.16 {
  set v [catch {execsql {SELECT sum(f1,f2) FROM test1}} msg]
  lappend v $msg
} {1 {wrong number of arguments to function sum()}}
do_test select1-2.17 {
  set v [catch {execsql {SELECT SUM(f1)+1 FROM test1}} msg]
  lappend v $msg
} {0 45}
do_test select1-2.17.1 {
  execsql {SELECT sum(a) FROM t3}
} {44.0}
do_test select1-2.18 {
  set v [catch {execsql {SELECT XYZZY(f1) FROM test1}} msg]
  lappend v $msg
} {1 {no such function: XYZZY}}
do_test select1-2.19 {
  set v [catch {execsql {SELECT SUM(min(f1,f2)) FROM test1}} msg]
  lappend v $msg
} {0 44}
do_test select1-2.20 {
  set v [catch {execsql {SELECT SUM(min(f1)) FROM test1}} msg]
  lappend v $msg
} {1 {misuse of aggregate function min()}}

# Ticket #2526
#
do_test select1-2.21 {
  catchsql {
     SELECT min(f1) AS m FROM test1 GROUP BY f1 HAVING max(m+5)<10
  }
} {1 {misuse of aliased aggregate m}}
do_test select1-2.22 {
  catchsql {
     SELECT coalesce(min(f1)+5,11) AS m FROM test1
      GROUP BY f1
     HAVING max(m+5)<10
  }
} {1 {misuse of aliased aggregate m}}
do_test select1-2.23 {
  execsql {
    CREATE TABLE tkt2526(a,b,c PRIMARY KEY);
    INSERT INTO tkt2526 VALUES('x','y',NULL);
    INSERT INTO tkt2526 VALUES('x','z',NULL);
  }
  catchsql {
    SELECT count(a) AS cn FROM tkt2526 GROUP BY a HAVING cn<max(cn)
  }
} {1 {misuse of aliased aggregate cn}}

# WHERE clause expressions
#
do_test select1-3.1 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE f1<11}} msg]
  lappend v $msg
} {0 {}}
do_test select1-3.2 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE f1<=11}} msg]
  lappend v $msg
} {0 11}
do_test select1-3.3 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE f1=11}} msg]
  lappend v $msg
} {0 11}
do_test select1-3.4 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE f1>=11}} msg]
  lappend v [lsort $msg]
} {0 {11 33}}
do_test select1-3.5 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE f1>11}} msg]
  lappend v [lsort $msg]
} {0 33}
do_test select1-3.6 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE f1!=11}} msg]
  lappend v [lsort $msg]
} {0 33}
do_test select1-3.7 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE min(f1,f2)!=11}} msg]
  lappend v [lsort $msg]
} {0 33}
do_test select1-3.8 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE max(f1,f2)!=11}} msg]
  lappend v [lsort $msg]
} {0 {11 33}}
do_test select1-3.9 {
  set v [catch {execsql {SELECT f1 FROM test1 WHERE count(f1,f2)!=11}} msg]
  lappend v $msg
} {1 {wrong number of arguments to function count()}}

# ORDER BY expressions
#
do_test select1-4.1 {
  set v [catch {execsql {SELECT f1 FROM test1 ORDER BY f1}} msg]
  lappend v $msg
} {0 {11 33}}
do_test select1-4.2 {
  set v [catch {execsql {SELECT f1 FROM test1 ORDER BY -f1}} msg]
  lappend v $msg
} {0 {33 11}}
do_test select1-4.3 {
  set v [catch {execsql {SELECT f1 FROM test1 ORDER BY min(f1,f2)}} msg]
  lappend v $msg
} {0 {11 33}}
do_test select1-4.4 {
  set v [catch {execsql {SELECT f1 FROM test1 ORDER BY min(f1)}} msg]
  lappend v $msg
} {1 {misuse of aggregate: min()}}

# The restriction not allowing constants in the ORDER BY clause
# has been removed.  See ticket #1768
#do_test select1-4.5 {
#  catchsql {
#    SELECT f1 FROM test1 ORDER BY 8.4;
#  }
#} {1 {ORDER BY terms must not be non-integer constants}}
#do_test select1-4.6 {
#  catchsql {
#    SELECT f1 FROM test1 ORDER BY '8.4';
#  }
#} {1 {ORDER BY terms must not be non-integer constants}}
#do_test select1-4.7.1 {
#  catchsql {
#    SELECT f1 FROM test1 ORDER BY 'xyz';
#  }
#} {1 {ORDER BY terms must not be non-integer constants}}
#do_test select1-4.7.2 {
#  catchsql {
#    SELECT f1 FROM test1 ORDER BY -8.4;
#  }
#} {1 {ORDER BY terms must not be non-integer constants}}
#do_test select1-4.7.3 {
#  catchsql {
#    SELECT f1 FROM test1 ORDER BY +8.4;
#  }
#} {1 {ORDER BY terms must not be non-integer constants}}
#do_test select1-4.7.4 {
#  catchsql {
#    SELECT f1 FROM test1 ORDER BY 4294967296; -- constant larger than 32 bits
#  }
#} {1 {ORDER BY terms must not be non-integer constants}}

do_test select1-4.5 {
  execsql {
    SELECT f1 FROM test1 ORDER BY 8.4
  }
} {11 33}
do_test select1-4.6 {
  execsql {
    SELECT f1 FROM test1 ORDER BY '8.4'
  }
} {11 33}

do_test select1-4.8 {
  execsql {
    CREATE TABLE t5(a,b);
    INSERT INTO t5 VALUES(1,10);
    INSERT INTO t5 VALUES(2,9);
    SELECT * FROM t5 ORDER BY 1;
  }
} {1 10 2 9}
do_test select1-4.9.1 {
  execsql {
    SELECT * FROM t5 ORDER BY 2;
  }
} {2 9 1 10}
do_test select1-4.9.2 {
  execsql {
    SELECT * FROM t5 ORDER BY +2;
  }
} {2 9 1 10}
do_test select1-4.10.1 {
  catchsql {
    SELECT * FROM t5 ORDER BY 3;
  }
} {1 {1st ORDER BY term out of range - should be between 1 and 2}}
do_test select1-4.10.2 {
  catchsql {
    SELECT * FROM t5 ORDER BY -1;
  }
} {1 {1st ORDER BY term out of range - should be between 1 and 2}}
do_test select1-4.11 {
  execsql {
    INSERT INTO t5 VALUES(3,10);
    SELECT * FROM t5 ORDER BY 2, 1 DESC;
  }
} {2 9 3 10 1 10}
do_test select1-4.12 {
  execsql {
    SELECT * FROM t5 ORDER BY 1 DESC, b;
  }
} {3 10 2 9 1 10}
do_test select1-4.13 {
  execsql {
    SELECT * FROM t5 ORDER BY b DESC, 1;
  }
} {1 10 3 10 2 9}


# ORDER BY ignored on an aggregate query
#
do_test select1-5.1 {
  set v [catch {execsql {SELECT max(f1) FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 33}

execsql {CREATE TABLE test2(t1 text, t2 text)}
execsql {INSERT INTO test2 VALUES('abc','xyz')}

# Check for column naming
#
do_test select1-6.1 {
  set v [catch {execsql2 {SELECT f1 FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {f1 11 f1 33}}
do_test select1-6.1.1 {
  db eval {PRAGMA full_column_names=on}
  set v [catch {execsql2 {SELECT f1 FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {test1.f1 11 test1.f1 33}}
do_test select1-6.1.2 {
  set v [catch {execsql2 {SELECT f1 as 'f1' FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {f1 11 f1 33}}
do_test select1-6.1.3 {
  set v [catch {execsql2 {SELECT * FROM test1 WHERE f1==11}} msg]
  lappend v $msg
} {0 {f1 11 f2 22}}
do_test select1-6.1.4 {
  set v [catch {execsql2 {SELECT DISTINCT * FROM test1 WHERE f1==11}} msg]
  db eval {PRAGMA full_column_names=off}
  lappend v $msg
} {0 {f1 11 f2 22}}
do_test select1-6.1.5 {
  set v [catch {execsql2 {SELECT * FROM test1 WHERE f1==11}} msg]
  lappend v $msg
} {0 {f1 11 f2 22}}
do_test select1-6.1.6 {
  set v [catch {execsql2 {SELECT DISTINCT * FROM test1 WHERE f1==11}} msg]
  lappend v $msg
} {0 {f1 11 f2 22}}
do_test select1-6.2 {
  set v [catch {execsql2 {SELECT f1 as xyzzy FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {xyzzy 11 xyzzy 33}}
do_test select1-6.3 {
  set v [catch {execsql2 {SELECT f1 as "xyzzy" FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {xyzzy 11 xyzzy 33}}
do_test select1-6.3.1 {
  set v [catch {execsql2 {SELECT f1 as 'xyzzy ' FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {{xyzzy } 11 {xyzzy } 33}}
do_test select1-6.4 {
  set v [catch {execsql2 {SELECT f1+F2 as xyzzy FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {xyzzy 33 xyzzy 77}}
do_test select1-6.4a {
  set v [catch {execsql2 {SELECT f1+F2 FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {f1+F2 33 f1+F2 77}}
do_test select1-6.5 {
  set v [catch {execsql2 {SELECT test1.f1+F2 FROM test1 ORDER BY f2}} msg]
  lappend v $msg
} {0 {test1.f1+F2 33 test1.f1+F2 77}}
do_test select1-6.5.1 {
  execsql2 {PRAGMA full_column_names=on}
  set v [catch {execsql2 {SELECT test1.f1+F2 FROM test1 ORDER BY f2}} msg]
  execsql2 {PRAGMA full_column_names=off}
  lappend v $msg
} {0 {test1.f1+F2 33 test1.f1+F2 77}}
do_test select1-6.6 {
  set v [catch {execsql2 {SELECT test1.f1+F2, t1 FROM test1, test2 
         ORDER BY f2}} msg]
  lappend v $msg
} {0 {test1.f1+F2 33 t1 abc test1.f1+F2 77 t1 abc}}
do_test select1-6.7 {
  set v [catch {execsql2 {SELECT A.f1, t1 FROM test1 as A, test2 
         ORDER BY f2}} msg]
  lappend v $msg
} {0 {f1 11 t1 abc f1 33 t1 abc}}
do_test select1-6.8 {
  set v [catch {execsql2 {SELECT A.f1, f1 FROM test1 as A, test1 as B 
         ORDER BY f2}} msg]
  lappend v $msg
} {1 {ambiguous column name: f1}}
do_test select1-6.8b {
  set v [catch {execsql2 {SELECT A.f1, B.f1 FROM test1 as A, test1 as B 
         ORDER BY f2}} msg]
  lappend v $msg
} {1 {ambiguous column name: f2}}
do_test select1-6.8c {
  set v [catch {execsql2 {SELECT A.f1, f1 FROM test1 as A, test1 as A 
         ORDER BY f2}} msg]
  lappend v $msg
} {1 {ambiguous column name: A.f1}}
do_test select1-6.9.1 {
  set v [catch {execsql {SELECT A.f1, B.f1 FROM test1 as A, test1 as B 
         ORDER BY A.f1, B.f1}} msg]
  lappend v $msg
} {0 {11 11 11 33 33 11 33 33}}
do_test select1-6.9.2 {
  set v [catch {execsql2 {SELECT A.f1, B.f1 FROM test1 as A, test1 as B 
         ORDER BY A.f1, B.f1}} msg]
  lappend v $msg
} {0 {f1 11 f1 11 f1 33 f1 33 f1 11 f1 11 f1 33 f1 33}}

do_test select1-6.9.3 {
  db eval {
     PRAGMA short_column_names=OFF;
     PRAGMA full_column_names=OFF;
  }
  execsql2 {
     SELECT test1 . f1, test1 . f2 FROM test1 LIMIT 1
  }
} {{test1 . f1} 11 {test1 . f2} 22}
do_test select1-6.9.4 {
  db eval {
     PRAGMA short_column_names=OFF;
     PRAGMA full_column_names=ON;
  }
  execsql2 {
     SELECT test1 . f1, test1 . f2 FROM test1 LIMIT 1
  }
} {test1.f1 11 test1.f2 22}
do_test select1-6.9.5 {
  db eval {
     PRAGMA short_column_names=OFF;
     PRAGMA full_column_names=ON;
  }
  execsql2 {
     SELECT 123.45;
  }
} {123.45 123.45}
do_test select1-6.9.6 {
  execsql2 {
     SELECT * FROM test1 a, test1 b LIMIT 1
  }
} {a.f1 11 a.f2 22 b.f1 11 b.f2 22}
do_test select1-6.9.7 {
  set x [execsql2 {
     SELECT * FROM test1 a, (select 5, 6) LIMIT 1
  }]
  regsub -all {subquery_[0-9a-fA-F]+_} $x {subquery} x
  set x
} {a.f1 11 a.f2 22 sqlite_subquery.5 5 sqlite_subquery.6 6}
do_test select1-6.9.8 {
  set x [execsql2 {
     SELECT * FROM test1 a, (select 5 AS x, 6 AS y) AS b LIMIT 1
  }]
  regsub -all {subquery_[0-9a-fA-F]+_} $x {subquery} x
  set x
} {a.f1 11 a.f2 22 b.x 5 b.y 6}
do_test select1-6.9.9 {
  execsql2 {
     SELECT a.f1, b.f2 FROM test1 a, test1 b LIMIT 1
  }
} {test1.f1 11 test1.f2 22}
do_test select1-6.9.10 {
  execsql2 {
     SELECT f1, t1 FROM test1, test2 LIMIT 1
  }
} {test1.f1 11 test2.t1 abc}
do_test select1-6.9.11 {
  db eval {
     PRAGMA short_column_names=ON;
     PRAGMA full_column_names=ON;
  }
  execsql2 {
     SELECT a.f1, b.f2 FROM test1 a, test1 b LIMIT 1
  }
} {test1.f1 11 test1.f2 22}
do_test select1-6.9.12 {
  execsql2 {
     SELECT f1, t1 FROM test1, test2 LIMIT 1
  }
} {test1.f1 11 test2.t1 abc}
do_test select1-6.9.13 {
  db eval {
     PRAGMA short_column_names=ON;
     PRAGMA full_column_names=OFF;
  }
  execsql2 {
     SELECT a.f1, b.f1 FROM test1 a, test1 b LIMIT 1
  }
} {f1 11 f1 11}
do_test select1-6.9.14 {
  execsql2 {
     SELECT f1, t1 FROM test1, test2 LIMIT 1
  }
} {f1 11 t1 abc}
do_test select1-6.9.15 {
  db eval {
     PRAGMA short_column_names=OFF;
     PRAGMA full_column_names=ON;
  }
  execsql2 {
     SELECT a.f1, b.f1 FROM test1 a, test1 b LIMIT 1
  }
} {test1.f1 11 test1.f1 11}
do_test select1-6.9.16 {
  execsql2 {
     SELECT f1, t1 FROM test1, test2 LIMIT 1
  }
} {test1.f1 11 test2.t1 abc}


db eval {
  PRAGMA short_column_names=ON;
  PRAGMA full_column_names=OFF;
}

ifcapable compound {
do_test select1-6.10 {
  set v [catch {execsql2 {
    SELECT f1 FROM test1 UNION SELECT f2 FROM test1
    ORDER BY f2;
  }} msg]
  lappend v $msg
} {0 {f1 11 f1 22 f1 33 f1 44}}
do_test select1-6.11 {
  set v [catch {execsql2 {
    SELECT f1 FROM test1 UNION SELECT f2+100 FROM test1
    ORDER BY f2+101;
  }} msg]
  lappend v $msg
} {1 {1st ORDER BY term does not match any column in the result set}}

# Ticket #2296
ifcapable subquery&&compound {
do_test select1-6.20 {
   execsql {
     CREATE TABLE t6(a TEXT, b TEXT);
     INSERT INTO t6 VALUES('a','0');
     INSERT INTO t6 VALUES('b','1');
     INSERT INTO t6 VALUES('c','2');
     INSERT INTO t6 VALUES('d','3');
     SELECT a FROM t6 WHERE b IN 
        (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x
                 ORDER BY 1 LIMIT 1)
   }
} {a}
do_test select1-6.21 {
   execsql {
     SELECT a FROM t6 WHERE b IN 
        (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x
                 ORDER BY 1 DESC LIMIT 1)
   }
} {d}
do_test select1-6.22 {
   execsql {
     SELECT a FROM t6 WHERE b IN 
        (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x
                 ORDER BY b LIMIT 2)
     ORDER BY a;
   }
} {a b}
do_test select1-6.23 {
   execsql {
     SELECT a FROM t6 WHERE b IN 
        (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x
                 ORDER BY x DESC LIMIT 2)
     ORDER BY a;
   }
} {b d}
}

} ;#ifcapable compound

do_test select1-7.1 {
  set v [catch {execsql {
     SELECT f1 FROM test1 WHERE f2=;
  }} msg]
  lappend v $msg
} {1 {near ";": syntax error}}
ifcapable compound {
do_test select1-7.2 {
  set v [catch {execsql {
     SELECT f1 FROM test1 UNION SELECT WHERE;
  }} msg]
  lappend v $msg
} {1 {near "WHERE": syntax error}}
} ;# ifcapable compound
do_test select1-7.3 {
  set v [catch {execsql {SELECT f1 FROM test1 as 'hi', test2 as}} msg]
  lappend v $msg
} {1 {near "as": syntax error}}
do_test select1-7.4 {
  set v [catch {execsql {
     SELECT f1 FROM test1 ORDER BY;
  }} msg]
  lappend v $msg
} {1 {near ";": syntax error}}
do_test select1-7.5 {
  set v [catch {execsql {
     SELECT f1 FROM test1 ORDER BY f1 desc, f2 where;
  }} msg]
  lappend v $msg
} {1 {near "where": syntax error}}
do_test select1-7.6 {
  set v [catch {execsql {
     SELECT count(f1,f2 FROM test1;
  }} msg]
  lappend v $msg
} {1 {near "FROM": syntax error}}
do_test select1-7.7 {
  set v [catch {execsql {
     SELECT count(f1,f2+) FROM test1;
  }} msg]
  lappend v $msg
} {1 {near ")": syntax error}}
do_test select1-7.8 {
  set v [catch {execsql {
     SELECT f1 FROM test1 ORDER BY f2, f1+;
  }} msg]
  lappend v $msg
} {1 {near ";": syntax error}}
do_test select1-7.9 {
  catchsql {
     SELECT f1 FROM test1 LIMIT 5+3 OFFSET 11 ORDER BY f2;
  }
} {1 {near "ORDER": syntax error}}

do_test select1-8.1 {
  execsql {SELECT f1 FROM test1 WHERE 4.3+2.4 OR 1 ORDER BY f1}
} {11 33}
do_test select1-8.2 {
  execsql {
    SELECT f1 FROM test1 WHERE ('x' || f1) BETWEEN 'x10' AND 'x20'
    ORDER BY f1
  }
} {11}
do_test select1-8.3 {
  execsql {
    SELECT f1 FROM test1 WHERE 5-3==2
    ORDER BY f1
  }
} {11 33}

# TODO: This test is failing because f1 is now being loaded off the
# disk as a vdbe integer, not a string. Hence the value of f1/(f1-11)
# changes because of rounding. Disable the test for now.
if 0 {
do_test select1-8.4 {
  execsql {
    SELECT coalesce(f1/(f1-11),'x'),
           coalesce(min(f1/(f1-11),5),'y'),
           coalesce(max(f1/(f1-33),6),'z')
    FROM test1 ORDER BY f1
  }
} {x y 6 1.5 1.5 z}
}
do_test select1-8.5 {
  execsql {
    SELECT min(1,2,3), -max(1,2,3)
    FROM test1 ORDER BY f1
  }
} {1 -3 1 -3}


# Check the behavior when the result set is empty
#
# SQLite v3 always sets r(*).
#
# do_test select1-9.1 {
#   catch {unset r}
#   set r(*) {}
#   db eval {SELECT * FROM test1 WHERE f1<0} r {}
#   set r(*)
# } {}
do_test select1-9.2 {
  execsql {PRAGMA empty_result_callbacks=on}
  catch {unset r}
  set r(*) {}
  db eval {SELECT * FROM test1 WHERE f1<0} r {}
  set r(*)
} {f1 f2}
ifcapable subquery {
  do_test select1-9.3 {
    set r(*) {}
    db eval {SELECT * FROM test1 WHERE f1<(select count(*) from test2)} r {}
    set r(*)
  } {f1 f2}
}
do_test select1-9.4 {
  set r(*) {}
  db eval {SELECT * FROM test1 ORDER BY f1} r {}
  set r(*)
} {f1 f2}
do_test select1-9.5 {
  set r(*) {}
  db eval {SELECT * FROM test1 WHERE f1<0 ORDER BY f1} r {}
  set r(*)
} {f1 f2}
unset r

# Check for ORDER BY clauses that refer to an AS name in the column list
#
do_test select1-10.1 {
  execsql {
    SELECT f1 AS x FROM test1 ORDER BY x
  }
} {11 33}
do_test select1-10.2 {
  execsql {
    SELECT f1 AS x FROM test1 ORDER BY -x
  }
} {33 11}
do_test select1-10.3 {
  execsql {
    SELECT f1-23 AS x FROM test1 ORDER BY abs(x)
  }
} {10 -12}
do_test select1-10.4 {
  execsql {
    SELECT f1-23 AS x FROM test1 ORDER BY -abs(x)
  }
} {-12 10}
do_test select1-10.5 {
  execsql {
    SELECT f1-22 AS x, f2-22 as y FROM test1
  }
} {-11 0 11 22}
do_test select1-10.6 {
  execsql {
    SELECT f1-22 AS x, f2-22 as y FROM test1 WHERE x>0 AND y<50
  }
} {11 22}
do_test select1-10.7 {
  execsql {
    SELECT f1 COLLATE nocase AS x FROM test1 ORDER BY x
  }
} {11 33}

# Check the ability to specify "TABLE.*" in the result set of a SELECT
#
do_test select1-11.1 {
  execsql {
    DELETE FROM t3;
    DELETE FROM t4;
    INSERT INTO t3 VALUES(1,2);
    INSERT INTO t4 VALUES(3,4);
    SELECT * FROM t3, t4;
  }
} {1 2 3 4}
do_test select1-11.2.1 {
  execsql {
    SELECT * FROM t3, t4;
  }
} {1 2 3 4}
do_test select1-11.2.2 {
  execsql2 {
    SELECT * FROM t3, t4;
  }
} {a 3 b 4 a 3 b 4}
do_test select1-11.4.1 {
  execsql {
    SELECT t3.*, t4.b FROM t3, t4;
  }
} {1 2 4}
do_test select1-11.4.2 {
  execsql {
    SELECT "t3".*, t4.b FROM t3, t4;
  }
} {1 2 4}
do_test select1-11.5.1 {
  execsql2 {
    SELECT t3.*, t4.b FROM t3, t4;
  }
} {a 1 b 4 b 4}
do_test select1-11.6 {
  execsql2 {
    SELECT x.*, y.b FROM t3 AS x, t4 AS y;
  }
} {a 1 b 4 b 4}
do_test select1-11.7 {
  execsql {
    SELECT t3.b, t4.* FROM t3, t4;
  }
} {2 3 4}
do_test select1-11.8 {
  execsql2 {
    SELECT t3.b, t4.* FROM t3, t4;
  }
} {b 4 a 3 b 4}
do_test select1-11.9 {
  execsql2 {
    SELECT x.b, y.* FROM t3 AS x, t4 AS y;
  }
} {b 4 a 3 b 4}
do_test select1-11.10 {
  catchsql {
    SELECT t5.* FROM t3, t4;
  }
} {1 {no such table: t5}}
do_test select1-11.11 {
  catchsql {
    SELECT t3.* FROM t3 AS x, t4;
  }
} {1 {no such table: t3}}
ifcapable subquery {
  do_test select1-11.12 {
    execsql2 {
      SELECT t3.* FROM t3, (SELECT max(a), max(b) FROM t4)
    }
  } {a 1 b 2}
  do_test select1-11.13 {
    execsql2 {
      SELECT t3.* FROM (SELECT max(a), max(b) FROM t4), t3
    }
  } {a 1 b 2}
  do_test select1-11.14 {
    execsql2 {
      SELECT * FROM t3, (SELECT max(a), max(b) FROM t4) AS 'tx'
    }
  } {a 1 b 2 max(a) 3 max(b) 4}
  do_test select1-11.15 {
    execsql2 {
      SELECT y.*, t3.* FROM t3, (SELECT max(a), max(b) FROM t4) AS y
    }
  } {max(a) 3 max(b) 4 a 1 b 2}
}
do_test select1-11.16 {
  execsql2 {
    SELECT y.* FROM t3 as y, t4 as z
  }
} {a 1 b 2}

# Tests of SELECT statements without a FROM clause.
#
do_test select1-12.1 {
  execsql2 {
    SELECT 1+2+3
  }
} {1+2+3 6}
do_test select1-12.2 {
  execsql2 {
    SELECT 1,'hello',2
  }
} {1 1 'hello' hello 2 2}
do_test select1-12.3 {
  execsql2 {
    SELECT 1 AS 'a','hello' AS 'b',2 AS 'c'
  }
} {a 1 b hello c 2}
do_test select1-12.4 {
  execsql {
    DELETE FROM t3;
    INSERT INTO t3 VALUES(1,2);
  }
} {}

ifcapable compound {
do_test select1-12.5 {
  execsql {
    SELECT * FROM t3 UNION SELECT 3 AS 'a', 4 ORDER BY a;
  }
} {1 2 3 4}

do_test select1-12.6 {
  execsql {
    SELECT 3, 4 UNION SELECT * FROM t3;
  }
} {1 2 3 4}
} ;# ifcapable compound

ifcapable subquery {
  do_test select1-12.7 {
    execsql {
      SELECT * FROM t3 WHERE a=(SELECT 1);
    }
  } {1 2}
  do_test select1-12.8 {
    execsql {
      SELECT * FROM t3 WHERE a=(SELECT 2);
    }
  } {}
}

ifcapable {compound && subquery} {
  do_test select1-12.9 {
    execsql2 {
      SELECT x FROM (
        SELECT a AS x, b AS y FROM t3 UNION SELECT a,b FROM t4 ORDER BY a,b
      ) ORDER BY x;
    }
  } {x 1 x 3}
  do_test select1-12.10 {
    execsql2 {
      SELECT z.x FROM (
        SELECT a AS x,b AS y FROM t3 UNION SELECT a, b FROM t4 ORDER BY a,b
      ) AS 'z' ORDER BY x;
    }
  } {x 1 x 3}
} ;# ifcapable compound


# Check for a VDBE stack growth problem that existed at one point.
#
ifcapable subquery {
  do_test select1-13.1 {
    execsql {
      BEGIN;
      create TABLE abc(a, b, c, PRIMARY KEY(a, b));
      INSERT INTO abc VALUES(1, 1, 1);
    }
    for {set i 0} {$i<10} {incr i} {
      execsql {
        INSERT INTO abc SELECT a+(select max(a) FROM abc), 
            b+(select max(a) FROM abc), c+(select max(a) FROM abc) FROM abc;
      }
    }
    execsql {COMMIT}
  
    # This used to seg-fault when the problem existed.
    execsql {
      SELECT count(
        (SELECT a FROM abc WHERE a = NULL AND b >= upper.c) 
      ) FROM abc AS upper;
    }
  } {0}
}

foreach tab [db eval {SELECT name FROM sqlite_master WHERE type = 'table'}] {
  db eval "DROP TABLE $tab"
}
db close
sqlite3 db test.db

do_test select1-14.1 {
  execsql { 
    SELECT * FROM sqlite_master WHERE rowid>10; 
    SELECT * FROM sqlite_master WHERE rowid=10;
    SELECT * FROM sqlite_master WHERE rowid<10;
    SELECT * FROM sqlite_master WHERE rowid<=10;
    SELECT * FROM sqlite_master WHERE rowid>=10;
    SELECT * FROM sqlite_master;
  }
} {}
do_test select1-14.2 {
  execsql { 
    SELECT 10 IN (SELECT rowid FROM sqlite_master);
  }
} {0}

if {[db one {PRAGMA locking_mode}]=="normal"} {
  # Check that ticket #3771 has been fixed.  This test does not
  # work with locking_mode=EXCLUSIVE so disable in that case.
  #
  do_test select1-15.1 {
    execsql {
      CREATE TABLE t1(a);
      CREATE INDEX i1 ON t1(a);
      INSERT INTO t1 VALUES(1);
      INSERT INTO t1 VALUES(2);
      INSERT INTO t1 VALUES(3);
    }
  } {}
  do_test select1-15.2 {
    sqlite3 db2 test.db
    execsql { DROP INDEX i1 } db2
    db2 close
  } {}
  do_test select1-15.3 {
    execsql { SELECT 2 IN (SELECT a FROM t1) }
  } {1}
}
  
finish_test

Added test/select2.test.



















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the SELECT statement.
#
# $Id: select2.test,v 1.28 2009/01/15 15:23:59 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a table with some data
#
execsql {CREATE TABLE tbl1(f1 int, f2 int)}
execsql {BEGIN}
for {set i 0} {$i<=30} {incr i} {
  execsql "INSERT INTO tbl1 VALUES([expr {$i%9}],[expr {$i%10}])"
}
execsql {COMMIT}

# Do a second query inside a first.
#
do_test select2-1.1 {
  set sql {SELECT DISTINCT f1 FROM tbl1 ORDER BY f1}
  set r {}
  catch {unset data}
  db eval $sql data {
    set f1 $data(f1)
    lappend r $f1:
    set sql2 "SELECT f2 FROM tbl1 WHERE f1=$f1 ORDER BY f2"
    db eval $sql2 d2 {
      lappend r $d2(f2)
    }
  }
  set r
} {0: 0 7 8 9 1: 0 1 8 9 2: 0 1 2 9 3: 0 1 2 3 4: 2 3 4 5: 3 4 5 6: 4 5 6 7: 5 6 7 8: 6 7 8}

do_test select2-1.2 {
  set sql {SELECT DISTINCT f1 FROM tbl1 WHERE f1>3 AND f1<5}
  set r {}
  db eval $sql data {
    set f1 $data(f1)
    lappend r $f1:
    set sql2 "SELECT f2 FROM tbl1 WHERE f1=$f1 ORDER BY f2"
    db eval $sql2 d2 {
      lappend r $d2(f2)
    }
  }
  set r
} {4: 2 3 4}
unset data

# Create a largish table. Do this twice, once using the TCL cache and once
# without.  Compare the performance to make sure things go faster with the
# cache turned on.
#
ifcapable tclvar {
  do_test select2-2.0.1 {
    set t1 [time {
      execsql {CREATE TABLE tbl2(f1 int, f2 int, f3 int); BEGIN;}
      for {set i 1} {$i<=30000} {incr i} {
        set i2 [expr {$i*2}]
        set i3 [expr {$i*3}]
        db eval {INSERT INTO tbl2 VALUES($i,$i2,$i3)}
      }
      execsql {COMMIT}
    }]
    list
  } {}
  puts "time with cache: $::t1"
}
catch {execsql {DROP TABLE tbl2}}
do_test select2-2.0.2 {
  set t2 [time {
    execsql {CREATE TABLE tbl2(f1 int, f2 int, f3 int); BEGIN;}
    for {set i 1} {$i<=30000} {incr i} {
      set i2 [expr {$i*2}]
      set i3 [expr {$i*3}]
      execsql "INSERT INTO tbl2 VALUES($i,$i2,$i3)"
    }
    execsql {COMMIT}
  }]
  list
} {}
puts "time without cache: $t2"
#ifcapable tclvar {
#  do_test select2-2.0.3 {
#    expr {[lindex $t1 0]<[lindex $t2 0]}
#  } 1
#}

do_test select2-2.1 {
  execsql {SELECT count(*) FROM tbl2}
} {30000}
do_test select2-2.2 {
  execsql {SELECT count(*) FROM tbl2 WHERE f2>1000}
} {29500}

do_test select2-3.1 {
  execsql {SELECT f1 FROM tbl2 WHERE 1000=f2}
} {500}

do_test select2-3.2a {
  execsql {CREATE INDEX idx1 ON tbl2(f2)}
} {}
do_test select2-3.2b {
  execsql {SELECT f1 FROM tbl2 WHERE 1000=f2}
} {500}
do_test select2-3.2c {
  execsql {SELECT f1 FROM tbl2 WHERE f2=1000}
} {500}
do_test select2-3.2d {
  set sqlite_search_count 0
  execsql {SELECT * FROM tbl2 WHERE 1000=f2}
  set sqlite_search_count
} {3}
do_test select2-3.2e {
  set sqlite_search_count 0
  execsql {SELECT * FROM tbl2 WHERE f2=1000}
  set sqlite_search_count
} {3}

# Make sure queries run faster with an index than without
#
do_test select2-3.3 {
  execsql {DROP INDEX idx1}
  set sqlite_search_count 0
  execsql {SELECT f1 FROM tbl2 WHERE f2==2000}
  set sqlite_search_count
} {29999}

# Make sure we can optimize functions in the WHERE clause that
# use fields from two or more different table.  (Bug #6)
#
do_test select2-4.1 {
  execsql {
    CREATE TABLE aa(a);
    CREATE TABLE bb(b);
    INSERT INTO aa VALUES(1);
    INSERT INTO aa VALUES(3);
    INSERT INTO bb VALUES(2);
    INSERT INTO bb VALUES(4);
    SELECT * FROM aa, bb WHERE max(a,b)>2;
  }
} {1 4 3 2 3 4}
do_test select2-4.2 {
  execsql {
    INSERT INTO bb VALUES(0);
    SELECT * FROM aa, bb WHERE b;
  }
} {1 2 1 4 3 2 3 4}
do_test select2-4.3 {
  execsql {
    SELECT * FROM aa, bb WHERE NOT b;
  }
} {1 0 3 0}
do_test select2-4.4 {
  execsql {
    SELECT * FROM aa, bb WHERE min(a,b);
  }
} {1 2 1 4 3 2 3 4}
do_test select2-4.5 {
  execsql {
    SELECT * FROM aa, bb WHERE NOT min(a,b);
  }
} {1 0 3 0}
do_test select2-4.6 {
  execsql {
    SELECT * FROM aa, bb WHERE CASE WHEN a=b-1 THEN 1 END;
  }
} {1 2 3 4}
do_test select2-4.7 {
  execsql {
    SELECT * FROM aa, bb WHERE CASE WHEN a=b-1 THEN 0 ELSE 1 END;
  }
} {1 4 1 0 3 2 3 0}

finish_test

Added test/select3.test.

















































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing aggregate functions and the
# GROUP BY and HAVING clauses of SELECT statements.
#
# $Id: select3.test,v 1.23 2008/01/16 18:20:42 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
do_test select3-1.0 {
  execsql {
    CREATE TABLE t1(n int, log int);
    BEGIN;
  }
  for {set i 1} {$i<32} {incr i} {
    for {set j 0} {(1<<$j)<$i} {incr j} {}
    execsql "INSERT INTO t1 VALUES($i,$j)"
  }
  execsql {
    COMMIT
  }
  execsql {SELECT DISTINCT log FROM t1 ORDER BY log}
} {0 1 2 3 4 5}

# Basic aggregate functions.
#
do_test select3-1.1 {
  execsql {SELECT count(*) FROM t1}
} {31}
do_test select3-1.2 {
  execsql {
    SELECT min(n),min(log),max(n),max(log),sum(n),sum(log),avg(n),avg(log)
    FROM t1
  }
} {1 0 31 5 496 124 16.0 4.0}
do_test select3-1.3 {
  execsql {SELECT max(n)/avg(n), max(log)/avg(log) FROM t1}
} {1.9375 1.25}

# Try some basic GROUP BY clauses
#
do_test select3-2.1 {
  execsql {SELECT log, count(*) FROM t1 GROUP BY log ORDER BY log}
} {0 1 1 1 2 2 3 4 4 8 5 15}
do_test select3-2.2 {
  execsql {SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log}
} {0 1 1 2 2 3 3 5 4 9 5 17}
do_test select3-2.3.1 {
  execsql {SELECT log, avg(n) FROM t1 GROUP BY log ORDER BY log}
} {0 1.0 1 2.0 2 3.5 3 6.5 4 12.5 5 24.0}
do_test select3-2.3.2 {
  execsql {SELECT log, avg(n)+1 FROM t1 GROUP BY log ORDER BY log}
} {0 2.0 1 3.0 2 4.5 3 7.5 4 13.5 5 25.0}
do_test select3-2.4 {
  execsql {SELECT log, avg(n)-min(n) FROM t1 GROUP BY log ORDER BY log}
} {0 0.0 1 0.0 2 0.5 3 1.5 4 3.5 5 7.0}
do_test select3-2.5 {
  execsql {SELECT log*2+1, avg(n)-min(n) FROM t1 GROUP BY log ORDER BY log}
} {1 0.0 3 0.0 5 0.5 7 1.5 9 3.5 11 7.0}
do_test select3-2.6 {
  execsql {
    SELECT log*2+1 as x, count(*) FROM t1 GROUP BY x ORDER BY x
  }
} {1 1 3 1 5 2 7 4 9 8 11 15}
do_test select3-2.7 {
  execsql {
    SELECT log*2+1 AS x, count(*) AS y FROM t1 GROUP BY x ORDER BY y, x
  }
} {1 1 3 1 5 2 7 4 9 8 11 15}
do_test select3-2.8 {
  execsql {
    SELECT log*2+1 AS x, count(*) AS y FROM t1 GROUP BY x ORDER BY 10-(x+y)
  }
} {11 15 9 8 7 4 5 2 3 1 1 1}
#do_test select3-2.9 {
#  catchsql {
#    SELECT log, count(*) FROM t1 GROUP BY 'x' ORDER BY log;
#  }
#} {1 {GROUP BY terms must not be non-integer constants}}
do_test select3-2.10 {
  catchsql {
    SELECT log, count(*) FROM t1 GROUP BY 0 ORDER BY log;
  }
} {1 {1st GROUP BY term out of range - should be between 1 and 2}}
do_test select3-2.11 {
  catchsql {
    SELECT log, count(*) FROM t1 GROUP BY 3 ORDER BY log;
  }
} {1 {1st GROUP BY term out of range - should be between 1 and 2}}
do_test select3-2.12 {
  catchsql {
    SELECT log, count(*) FROM t1 GROUP BY 1 ORDER BY log;
  }
} {0 {0 1 1 1 2 2 3 4 4 8 5 15}}

# Cannot have an empty GROUP BY
do_test select3-2.13 {
  catchsql {
    SELECT log, count(*) FROM t1 GROUP BY ORDER BY log;
  }
} {1 {near "ORDER": syntax error}}
do_test select3-2.14 {
  catchsql {
    SELECT log, count(*) FROM t1 GROUP BY;
  }
} {1 {near ";": syntax error}}

# Cannot have a HAVING without a GROUP BY
#
do_test select3-3.1 {
  set v [catch {execsql {SELECT log, count(*) FROM t1 HAVING log>=4}} msg]
  lappend v $msg
} {1 {a GROUP BY clause is required before HAVING}}

# Toss in some HAVING clauses
#
do_test select3-4.1 {
  execsql {SELECT log, count(*) FROM t1 GROUP BY log HAVING log>=4 ORDER BY log}
} {4 8 5 15}
do_test select3-4.2 {
  execsql {
    SELECT log, count(*) FROM t1 
    GROUP BY log 
    HAVING count(*)>=4 
    ORDER BY log
  }
} {3 4 4 8 5 15}
do_test select3-4.3 {
  execsql {
    SELECT log, count(*) FROM t1 
    GROUP BY log 
    HAVING count(*)>=4 
    ORDER BY max(n)+0
  }
} {3 4 4 8 5 15}
do_test select3-4.4 {
  execsql {
    SELECT log AS x, count(*) AS y FROM t1 
    GROUP BY x
    HAVING y>=4 
    ORDER BY max(n)+0
  }
} {3 4 4 8 5 15}
do_test select3-4.5 {
  execsql {
    SELECT log AS x FROM t1 
    GROUP BY x
    HAVING count(*)>=4 
    ORDER BY max(n)+0
  }
} {3 4 5}

do_test select3-5.1 {
  execsql {
    SELECT log, count(*), avg(n), max(n+log*2) FROM t1 
    GROUP BY log 
    ORDER BY max(n+log*2)+0, avg(n)+0
  }
} {0 1 1.0 1 1 1 2.0 4 2 2 3.5 8 3 4 6.5 14 4 8 12.5 24 5 15 24.0 41}
do_test select3-5.2 {
  execsql {
    SELECT log, count(*), avg(n), max(n+log*2) FROM t1 
    GROUP BY log 
    ORDER BY max(n+log*2)+0, min(log,avg(n))+0
  }
} {0 1 1.0 1 1 1 2.0 4 2 2 3.5 8 3 4 6.5 14 4 8 12.5 24 5 15 24.0 41}

# Test sorting of GROUP BY results in the presence of an index
# on the GROUP BY column.
#
do_test select3-6.1 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log;
  }
} {0 1 1 2 2 3 3 5 4 9 5 17}
do_test select3-6.2 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log DESC;
  }
} {5 17 4 9 3 5 2 3 1 2 0 1}
do_test select3-6.3 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1;
  }
} {0 1 1 2 2 3 3 5 4 9 5 17}
do_test select3-6.4 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1 DESC;
  }
} {5 17 4 9 3 5 2 3 1 2 0 1}
do_test select3-6.5 {
  execsql {
    CREATE INDEX i1 ON t1(log);
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log;
  }
} {0 1 1 2 2 3 3 5 4 9 5 17}
do_test select3-6.6 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log DESC;
  }
} {5 17 4 9 3 5 2 3 1 2 0 1}
do_test select3-6.7 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1;
  }
} {0 1 1 2 2 3 3 5 4 9 5 17}
do_test select3-6.8 {
  execsql {
    SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1 DESC;
  }
} {5 17 4 9 3 5 2 3 1 2 0 1}

# Sometimes an aggregate query can return no rows at all.
#
do_test select3-7.1 {
  execsql {
    CREATE TABLE t2(a,b);
    INSERT INTO t2 VALUES(1,2);
    SELECT a, sum(b) FROM t2 WHERE b=5 GROUP BY a;
  }
} {}
do_test select3-7.2 {
  execsql {
    SELECT a, sum(b) FROM t2 WHERE b=5;
  }
} {{} {}}

# If a table column is of type REAL but we are storing integer values
# in it, the values are stored as integers to take up less space.  The
# values are converted by to REAL as they are read out of the table.
# Make sure the GROUP BY clause does this conversion correctly.
# Ticket #2251.
#
do_test select3-8.1 {
  execsql {
    CREATE TABLE A (
      A1 DOUBLE,
      A2 VARCHAR COLLATE NOCASE,
      A3 DOUBLE
    );
    INSERT INTO A VALUES(39136,'ABC',1201900000);
    INSERT INTO A VALUES(39136,'ABC',1207000000);
    SELECT typeof(sum(a3)) FROM a;
  }
} {real}
do_test select3-8.2 {
  execsql {
    SELECT typeof(sum(a3)) FROM a GROUP BY a1;
  }
} {real}

finish_test

Added test/select4.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing UNION, INTERSECT and EXCEPT operators
# in SELECT statements.
#
# $Id: select4.test,v 1.30 2009/04/16 00:24:24 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Most tests in this file depend on compound-select. But there are a couple
# right at the end that test DISTINCT, so we cannot omit the entire file.
#
ifcapable compound {

# Build some test data
#
execsql {
  CREATE TABLE t1(n int, log int);
  BEGIN;
}
for {set i 1} {$i<32} {incr i} {
  for {set j 0} {(1<<$j)<$i} {incr j} {}
  execsql "INSERT INTO t1 VALUES($i,$j)"
}
execsql {
  COMMIT;
}

do_test select4-1.0 {
  execsql {SELECT DISTINCT log FROM t1 ORDER BY log}
} {0 1 2 3 4 5}

# Union All operator
#
do_test select4-1.1a {
  lsort [execsql {SELECT DISTINCT log FROM t1}]
} {0 1 2 3 4 5}
do_test select4-1.1b {
  lsort [execsql {SELECT n FROM t1 WHERE log=3}]
} {5 6 7 8}
do_test select4-1.1c {
  execsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }
} {0 1 2 3 4 5 5 6 7 8}
do_test select4-1.1d {
  execsql {
    CREATE TABLE t2 AS
      SELECT DISTINCT log FROM t1
      UNION ALL
      SELECT n FROM t1 WHERE log=3
      ORDER BY log;
    SELECT * FROM t2;
  }
} {0 1 2 3 4 5 5 6 7 8}
execsql {DROP TABLE t2}
do_test select4-1.1e {
  execsql {
    CREATE TABLE t2 AS
      SELECT DISTINCT log FROM t1
      UNION ALL
      SELECT n FROM t1 WHERE log=3
      ORDER BY log DESC;
    SELECT * FROM t2;
  }
} {8 7 6 5 5 4 3 2 1 0}
execsql {DROP TABLE t2}
do_test select4-1.1f {
  execsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=2
  }
} {0 1 2 3 4 5 3 4}
do_test select4-1.1g {
  execsql {
    CREATE TABLE t2 AS 
      SELECT DISTINCT log FROM t1
      UNION ALL
      SELECT n FROM t1 WHERE log=2;
    SELECT * FROM t2;
  }
} {0 1 2 3 4 5 3 4}
execsql {DROP TABLE t2}
ifcapable subquery {
  do_test select4-1.2 {
    execsql {
      SELECT log FROM t1 WHERE n IN 
        (SELECT DISTINCT log FROM t1 UNION ALL
         SELECT n FROM t1 WHERE log=3)
      ORDER BY log;
    }
  } {0 1 2 2 3 3 3 3}
}
do_test select4-1.3 {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }} msg]
  lappend v $msg
} {1 {ORDER BY clause should come after UNION ALL not before}}

# Union operator
#
do_test select4-2.1 {
  execsql {
    SELECT DISTINCT log FROM t1
    UNION
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }
} {0 1 2 3 4 5 6 7 8}
ifcapable subquery {
  do_test select4-2.2 {
    execsql {
      SELECT log FROM t1 WHERE n IN 
        (SELECT DISTINCT log FROM t1 UNION
         SELECT n FROM t1 WHERE log=3)
      ORDER BY log;
    }
  } {0 1 2 2 3 3 3 3}
}
do_test select4-2.3 {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log
    UNION
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }} msg]
  lappend v $msg
} {1 {ORDER BY clause should come after UNION not before}}

# Except operator
#
do_test select4-3.1.1 {
  execsql {
    SELECT DISTINCT log FROM t1
    EXCEPT
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }
} {0 1 2 3 4}
do_test select4-3.1.2 {
  execsql {
    CREATE TABLE t2 AS 
      SELECT DISTINCT log FROM t1
      EXCEPT
      SELECT n FROM t1 WHERE log=3
      ORDER BY log;
    SELECT * FROM t2;
  }
} {0 1 2 3 4}
execsql {DROP TABLE t2}
do_test select4-3.1.3 {
  execsql {
    CREATE TABLE t2 AS 
      SELECT DISTINCT log FROM t1
      EXCEPT
      SELECT n FROM t1 WHERE log=3
      ORDER BY log DESC;
    SELECT * FROM t2;
  }
} {4 3 2 1 0}
execsql {DROP TABLE t2}
ifcapable subquery {
  do_test select4-3.2 {
    execsql {
      SELECT log FROM t1 WHERE n IN 
        (SELECT DISTINCT log FROM t1 EXCEPT
         SELECT n FROM t1 WHERE log=3)
      ORDER BY log;
    }
  } {0 1 2 2}
}
do_test select4-3.3 {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log
    EXCEPT
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }} msg]
  lappend v $msg
} {1 {ORDER BY clause should come after EXCEPT not before}}

# Intersect operator
#
do_test select4-4.1.1 {
  execsql {
    SELECT DISTINCT log FROM t1
    INTERSECT
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }
} {5}

do_test select4-4.1.2 {
  execsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT 6
    INTERSECT
    SELECT n FROM t1 WHERE log=3
    ORDER BY t1.log;
  }
} {5 6}

do_test select4-4.1.3 {
  execsql {
    CREATE TABLE t2 AS
      SELECT DISTINCT log FROM t1 UNION ALL SELECT 6
      INTERSECT
      SELECT n FROM t1 WHERE log=3
      ORDER BY log;
    SELECT * FROM t2;
  }
} {5 6}
execsql {DROP TABLE t2}
do_test select4-4.1.4 {
  execsql {
    CREATE TABLE t2 AS
      SELECT DISTINCT log FROM t1 UNION ALL SELECT 6
      INTERSECT
      SELECT n FROM t1 WHERE log=3
      ORDER BY log DESC;
    SELECT * FROM t2;
  }
} {6 5}
execsql {DROP TABLE t2}
ifcapable subquery {
  do_test select4-4.2 {
    execsql {
      SELECT log FROM t1 WHERE n IN 
        (SELECT DISTINCT log FROM t1 INTERSECT
         SELECT n FROM t1 WHERE log=3)
      ORDER BY log;
    }
  } {3}
}
do_test select4-4.3 {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log
    INTERSECT
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }} msg]
  lappend v $msg
} {1 {ORDER BY clause should come after INTERSECT not before}}

# Various error messages while processing UNION or INTERSECT
#
do_test select4-5.1 {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t2
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }} msg]
  lappend v $msg
} {1 {no such table: t2}}
do_test select4-5.2 {
  set v [catch {execsql {
    SELECT DISTINCT log AS "xyzzy" FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY xyzzy;
  }} msg]
  lappend v $msg
} {0 {0 1 2 3 4 5 5 6 7 8}}
do_test select4-5.2b {
  set v [catch {execsql {
    SELECT DISTINCT log AS xyzzy FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY "xyzzy";
  }} msg]
  lappend v $msg
} {0 {0 1 2 3 4 5 5 6 7 8}}
do_test select4-5.2c {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY "xyzzy";
  }} msg]
  lappend v $msg
} {1 {1st ORDER BY term does not match any column in the result set}}
do_test select4-5.2d {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1
    INTERSECT
    SELECT n FROM t1 WHERE log=3
    ORDER BY "xyzzy";
  }} msg]
  lappend v $msg
} {1 {1st ORDER BY term does not match any column in the result set}}
do_test select4-5.2e {
  set v [catch {execsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY n;
  }} msg]
  lappend v $msg
} {0 {0 1 2 3 4 5 5 6 7 8}}
do_test select4-5.2f {
  catchsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }
} {0 {0 1 2 3 4 5 5 6 7 8}}
do_test select4-5.2g {
  catchsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY 1;
  }
} {0 {0 1 2 3 4 5 5 6 7 8}}
do_test select4-5.2h {
  catchsql {
    SELECT DISTINCT log FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY 2;
  }
} {1 {1st ORDER BY term out of range - should be between 1 and 1}}
do_test select4-5.2i {
  catchsql {
    SELECT DISTINCT 1, log FROM t1
    UNION ALL
    SELECT 2, n FROM t1 WHERE log=3
    ORDER BY 2, 1;
  }
} {0 {1 0 1 1 1 2 1 3 1 4 1 5 2 5 2 6 2 7 2 8}}
do_test select4-5.2j {
  catchsql {
    SELECT DISTINCT 1, log FROM t1
    UNION ALL
    SELECT 2, n FROM t1 WHERE log=3
    ORDER BY 1, 2 DESC;
  }
} {0 {1 5 1 4 1 3 1 2 1 1 1 0 2 8 2 7 2 6 2 5}}
do_test select4-5.2k {
  catchsql {
    SELECT DISTINCT 1, log FROM t1
    UNION ALL
    SELECT 2, n FROM t1 WHERE log=3
    ORDER BY n, 1;
  }
} {0 {1 0 1 1 1 2 1 3 1 4 1 5 2 5 2 6 2 7 2 8}}
do_test select4-5.3 {
  set v [catch {execsql {
    SELECT DISTINCT log, n FROM t1
    UNION ALL
    SELECT n FROM t1 WHERE log=3
    ORDER BY log;
  }} msg]
  lappend v $msg
} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}}
do_test select4-5.3-3807-1 {
  catchsql {
    SELECT 1 UNION SELECT 2, 3 UNION SELECT 4, 5 ORDER BY 1;
  }
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}
do_test select4-5.4 {
  set v [catch {execsql {
    SELECT log FROM t1 WHERE n=2
    UNION ALL
    SELECT log FROM t1 WHERE n=3
    UNION ALL
    SELECT log FROM t1 WHERE n=4
    UNION ALL
    SELECT log FROM t1 WHERE n=5
    ORDER BY log;
  }} msg]
  lappend v $msg
} {0 {1 2 2 3}}

do_test select4-6.1 {
  execsql {
    SELECT log, count(*) as cnt FROM t1 GROUP BY log
    UNION
    SELECT log, n FROM t1 WHERE n=7
    ORDER BY cnt, log;
  }
} {0 1 1 1 2 2 3 4 3 7 4 8 5 15}
do_test select4-6.2 {
  execsql {
    SELECT log, count(*) FROM t1 GROUP BY log
    UNION
    SELECT log, n FROM t1 WHERE n=7
    ORDER BY count(*), log;
  }
} {0 1 1 1 2 2 3 4 3 7 4 8 5 15}

# NULLs are indistinct for the UNION operator.
# Make sure the UNION operator recognizes this
#
do_test select4-6.3 {
  execsql {
    SELECT NULL UNION SELECT NULL UNION
    SELECT 1 UNION SELECT 2 AS 'x'
    ORDER BY x;
  }
} {{} 1 2}
do_test select4-6.3.1 {
  execsql {
    SELECT NULL UNION ALL SELECT NULL UNION ALL
    SELECT 1 UNION ALL SELECT 2 AS 'x'
    ORDER BY x;
  }
} {{} {} 1 2}

# Make sure the DISTINCT keyword treats NULLs as indistinct.
#
ifcapable subquery {
  do_test select4-6.4 {
    execsql {
      SELECT * FROM (
         SELECT NULL, 1 UNION ALL SELECT NULL, 1
      );
    }
  } {{} 1 {} 1}
  do_test select4-6.5 {
    execsql {
      SELECT DISTINCT * FROM (
         SELECT NULL, 1 UNION ALL SELECT NULL, 1
      );
    }
  } {{} 1}
  do_test select4-6.6 {
    execsql {
      SELECT DISTINCT * FROM (
         SELECT 1,2  UNION ALL SELECT 1,2
      );
    }
  } {1 2}
}

# Test distinctness of NULL in other ways.
#
do_test select4-6.7 {
  execsql {
    SELECT NULL EXCEPT SELECT NULL
  }
} {}


# Make sure column names are correct when a compound select appears as
# an expression in the WHERE clause.
#
do_test select4-7.1 {
  execsql {
    CREATE TABLE t2 AS SELECT log AS 'x', count(*) AS 'y' FROM t1 GROUP BY log;
    SELECT * FROM t2 ORDER BY x;
  }
} {0 1 1 1 2 2 3 4 4 8 5 15}  
ifcapable subquery {
  do_test select4-7.2 {
    execsql2 {
      SELECT * FROM t1 WHERE n IN (SELECT n FROM t1 INTERSECT SELECT x FROM t2)
      ORDER BY n
    }
  } {n 1 log 0 n 2 log 1 n 3 log 2 n 4 log 2 n 5 log 3}
  do_test select4-7.3 {
    execsql2 {
      SELECT * FROM t1 WHERE n IN (SELECT n FROM t1 EXCEPT SELECT x FROM t2)
      ORDER BY n LIMIT 2
    }
  } {n 6 log 3 n 7 log 3}
  do_test select4-7.4 {
    execsql2 {
      SELECT * FROM t1 WHERE n IN (SELECT n FROM t1 UNION SELECT x FROM t2)
      ORDER BY n LIMIT 2
    }
  } {n 1 log 0 n 2 log 1}
} ;# ifcapable subquery

} ;# ifcapable compound

# Make sure DISTINCT works appropriately on TEXT and NUMERIC columns.
do_test select4-8.1 {
  execsql {
    BEGIN;
    CREATE TABLE t3(a text, b float, c text);
    INSERT INTO t3 VALUES(1, 1.1, '1.1');
    INSERT INTO t3 VALUES(2, 1.10, '1.10');
    INSERT INTO t3 VALUES(3, 1.10, '1.1');
    INSERT INTO t3 VALUES(4, 1.1, '1.10');
    INSERT INTO t3 VALUES(5, 1.2, '1.2');
    INSERT INTO t3 VALUES(6, 1.3, '1.3');
    COMMIT;
  }
  execsql {
    SELECT DISTINCT b FROM t3 ORDER BY c;
  }
} {1.1 1.2 1.3}
do_test select4-8.2 {
  execsql {
    SELECT DISTINCT c FROM t3 ORDER BY c;
  }
} {1.1 1.10 1.2 1.3}

# Make sure the names of columns are taken from the right-most subquery
# right in a compound query.  Ticket #1721
#
ifcapable compound {

do_test select4-9.1 {
  execsql2 {
    SELECT x, y FROM t2 UNION SELECT a, b FROM t3 ORDER BY x LIMIT 1
  }
} {x 0 y 1}
do_test select4-9.2 {
  execsql2 {
    SELECT x, y FROM t2 UNION ALL SELECT a, b FROM t3 ORDER BY x LIMIT 1
  }
} {x 0 y 1}
do_test select4-9.3 {
  execsql2 {
    SELECT x, y FROM t2 EXCEPT SELECT a, b FROM t3 ORDER BY x LIMIT 1
  }
} {x 0 y 1}
do_test select4-9.4 {
  execsql2 {
    SELECT x, y FROM t2 INTERSECT SELECT 0 AS a, 1 AS b;
  }
} {x 0 y 1}
do_test select4-9.5 {
  execsql2 {
    SELECT 0 AS x, 1 AS y
    UNION
    SELECT 2 AS p, 3 AS q
    UNION
    SELECT 4 AS a, 5 AS b
    ORDER BY x LIMIT 1
  }
} {x 0 y 1}

ifcapable subquery {
do_test select4-9.6 {
  execsql2 {
    SELECT * FROM (
      SELECT 0 AS x, 1 AS y
      UNION
      SELECT 2 AS p, 3 AS q
      UNION
      SELECT 4 AS a, 5 AS b
    ) ORDER BY 1 LIMIT 1;
  }
} {x 0 y 1}
do_test select4-9.7 {
  execsql2 {
    SELECT * FROM (
      SELECT 0 AS x, 1 AS y
      UNION
      SELECT 2 AS p, 3 AS q
      UNION
      SELECT 4 AS a, 5 AS b
    ) ORDER BY x LIMIT 1;
  }
} {x 0 y 1}
} ;# ifcapable subquery

do_test select4-9.8 {
  execsql {
    SELECT 0 AS x, 1 AS y
    UNION
    SELECT 2 AS y, -3 AS x
    ORDER BY x LIMIT 1;
  }
} {0 1}

do_test select4-9.9.1 {
  execsql2 {
    SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS b, 4 AS a
  }
} {a 1 b 2 a 3 b 4}

ifcapable subquery {
do_test select4-9.9.2 {
  execsql2 {
    SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS b, 4 AS a)
     WHERE b=3
  }
} {}
do_test select4-9.10 {
  execsql2 {
    SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS b, 4 AS a)
     WHERE b=2
  }
} {a 1 b 2}
do_test select4-9.11 {
  execsql2 {
    SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS e, 4 AS b)
     WHERE b=2
  }
} {a 1 b 2}
do_test select4-9.12 {
  execsql2 {
    SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS e, 4 AS b)
     WHERE b>0
  }
} {a 1 b 2 a 3 b 4}
} ;# ifcapable subquery

# Try combining DISTINCT, LIMIT, and OFFSET.  Make sure they all work
# together.
#
do_test select4-10.1 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log
  }
} {0 1 2 3 4 5}
do_test select4-10.2 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 4
  }
} {0 1 2 3}
do_test select4-10.3 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 0
  }
} {}
do_test select4-10.4 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log LIMIT -1
  }
} {0 1 2 3 4 5}
do_test select4-10.5 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log LIMIT -1 OFFSET 2
  }
} {2 3 4 5}
do_test select4-10.6 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 3 OFFSET 2
  }
} {2 3 4}
do_test select4-10.7 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY +log LIMIT 3 OFFSET 20
  }
} {}
do_test select4-10.8 {
  execsql {
    SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 0 OFFSET 3
  }
} {}
do_test select4-10.9 {
  execsql {
    SELECT DISTINCT max(n), log FROM t1 ORDER BY +log; -- LIMIT 2 OFFSET 1
  }
} {31 5}

# Make sure compound SELECTs with wildly different numbers of columns
# do not cause assertion faults due to register allocation issues.
#
do_test select4-11.1 {
  catchsql {
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    UNION
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}
do_test select4-11.2 {
  catchsql {
    SELECT x FROM t2
    UNION
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
  }
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}
do_test select4-11.3 {
  catchsql {
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    UNION ALL
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}}
do_test select4-11.4 {
  catchsql {
    SELECT x FROM t2
    UNION ALL
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
  }
} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}}
do_test select4-11.5 {
  catchsql {
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    EXCEPT
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}}
do_test select4-11.6 {
  catchsql {
    SELECT x FROM t2
    EXCEPT
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
  }
} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}}
do_test select4-11.7 {
  catchsql {
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    INTERSECT
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}}
do_test select4-11.8 {
  catchsql {
    SELECT x FROM t2
    INTERSECT
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
  }
} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}}

do_test select4-11.11 {
  catchsql {
    SELECT x FROM t2
    UNION
    SELECT x FROM t2
    UNION ALL
    SELECT x FROM t2
    EXCEPT
    SELECT x FROM t2
    INTERSECT
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
  }
} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}}
do_test select4-11.12 {
  catchsql {
    SELECT x FROM t2
    UNION
    SELECT x FROM t2
    UNION ALL
    SELECT x FROM t2
    EXCEPT
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    EXCEPT
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}}
do_test select4-11.13 {
  catchsql {
    SELECT x FROM t2
    UNION
    SELECT x FROM t2
    UNION ALL
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    UNION ALL
    SELECT x FROM t2
    EXCEPT
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}}
do_test select4-11.14 {
  catchsql {
    SELECT x FROM t2
    UNION
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    UNION
    SELECT x FROM t2
    UNION ALL
    SELECT x FROM t2
    EXCEPT
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}
do_test select4-11.15 {
  catchsql {
    SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2
    UNION
    SELECT x FROM t2
    INTERSECT
    SELECT x FROM t2
    UNION ALL
    SELECT x FROM t2
    EXCEPT
    SELECT x FROM t2
  }
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}

do_test select4-12.1 {
  sqlite3 db2 :memory:
  catchsql {
    SELECT 1 UNION SELECT 2,3 UNION SELECT 4,5 ORDER BY 1;
  } db2
} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}}

} ;# ifcapable compound

finish_test

Added test/select5.test.



































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing aggregate functions and the
# GROUP BY and HAVING clauses of SELECT statements.
#
# $Id: select5.test,v 1.20 2008/08/21 14:15:59 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
execsql {
  CREATE TABLE t1(x int, y int);
  BEGIN;
}
for {set i 1} {$i<32} {incr i} {
  for {set j 0} {(1<<$j)<$i} {incr j} {}
  execsql "INSERT INTO t1 VALUES([expr {32-$i}],[expr {10-$j}])"
}
execsql {
  COMMIT
}

do_test select5-1.0 {
  execsql {SELECT DISTINCT y FROM t1 ORDER BY y}
} {5 6 7 8 9 10}

# Sort by an aggregate function.
#
do_test select5-1.1 {
  execsql {SELECT y, count(*) FROM t1 GROUP BY y ORDER BY y}
} {5 15 6 8 7 4 8 2 9 1 10 1}
do_test select5-1.2 {
  execsql {SELECT y, count(*) FROM t1 GROUP BY y ORDER BY count(*), y}
} {9 1 10 1 8 2 7 4 6 8 5 15}
do_test select5-1.3 {
  execsql {SELECT count(*), y FROM t1 GROUP BY y ORDER BY count(*), y}
} {1 9 1 10 2 8 4 7 8 6 15 5}

# Some error messages associated with aggregates and GROUP BY
#
do_test select5-2.1.1 {
  catchsql {
    SELECT y, count(*) FROM t1 GROUP BY z ORDER BY y
  }
} {1 {no such column: z}}
do_test select5-2.1.2 {
  catchsql {
    SELECT y, count(*) FROM t1 GROUP BY temp.t1.y ORDER BY y
  }
} {1 {no such column: temp.t1.y}}
do_test select5-2.2 {
  set v [catch {execsql {
    SELECT y, count(*) FROM t1 GROUP BY z(y) ORDER BY y
  }} msg]
  lappend v $msg
} {1 {no such function: z}}
do_test select5-2.3 {
  set v [catch {execsql {
    SELECT y, count(*) FROM t1 GROUP BY y HAVING count(*)<3 ORDER BY y
  }} msg]
  lappend v $msg
} {0 {8 2 9 1 10 1}}
do_test select5-2.4 {
  set v [catch {execsql {
    SELECT y, count(*) FROM t1 GROUP BY y HAVING z(y)<3 ORDER BY y
  }} msg]
  lappend v $msg
} {1 {no such function: z}}
do_test select5-2.5 {
  set v [catch {execsql {
    SELECT y, count(*) FROM t1 GROUP BY y HAVING count(*)<z ORDER BY y
  }} msg]
  lappend v $msg
} {1 {no such column: z}}

# Get the Agg function to rehash in vdbe.c
#
do_test select5-3.1 {
  execsql {
    SELECT x, count(*), avg(y) FROM t1 GROUP BY x HAVING x<4 ORDER BY x
  }
} {1 1 5.0 2 1 5.0 3 1 5.0}

# Run various aggregate functions when the count is zero.
#
do_test select5-4.1 {
  execsql {
    SELECT avg(x) FROM t1 WHERE x>100
  }
} {{}}
do_test select5-4.2 {
  execsql {
    SELECT count(x) FROM t1 WHERE x>100
  }
} {0}
do_test select5-4.3 {
  execsql {
    SELECT min(x) FROM t1 WHERE x>100
  }
} {{}}
do_test select5-4.4 {
  execsql {
    SELECT max(x) FROM t1 WHERE x>100
  }
} {{}}
do_test select5-4.5 {
  execsql {
    SELECT sum(x) FROM t1 WHERE x>100
  }
} {{}}

# Some tests for queries with a GROUP BY clause but no aggregate functions.
#
# Note: The query in test cases 5.1 through 5.5 are not legal SQL. So if the 
# implementation changes in the future and it returns different results,
# this is not such a big deal.
#
do_test select5-5.1 {
  execsql {
    CREATE TABLE t2(a, b, c);
    INSERT INTO t2 VALUES(1, 2, 3);
    INSERT INTO t2 VALUES(1, 4, 5);
    INSERT INTO t2 VALUES(6, 4, 7);
    CREATE INDEX t2_idx ON t2(a);
  } 
} {}
do_test select5-5.2 {
  execsql {
    SELECT a FROM t2 GROUP BY a;
  } 
} {1 6}
do_test select5-5.3 {
  execsql {
    SELECT a FROM t2 WHERE a>2 GROUP BY a;
  } 
} {6}
do_test select5-5.4 {
  execsql {
    SELECT a, b FROM t2 GROUP BY a, b;
  } 
} {1 2 1 4 6 4}
do_test select5-5.5 {
  execsql {
    SELECT a, b FROM t2 GROUP BY a;
  } 
} {1 4 6 4}

# Test rendering of columns for the GROUP BY clause.
#
do_test select5-5.11 {
  execsql {
    SELECT max(c), b*a, b, a FROM t2 GROUP BY b*a, b, a
  }
} {3 2 2 1 5 4 4 1 7 24 4 6}

# NULL compare equal to each other for the purposes of processing
# the GROUP BY clause.
#
do_test select5-6.1 {
  execsql {
    CREATE TABLE t3(x,y);
    INSERT INTO t3 VALUES(1,NULL);
    INSERT INTO t3 VALUES(2,NULL);
    INSERT INTO t3 VALUES(3,4);
    SELECT count(x), y FROM t3 GROUP BY y ORDER BY 1
  }
} {1 4 2 {}}
do_test select5-6.2 {
  execsql {
    CREATE TABLE t4(x,y,z);
    INSERT INTO t4 VALUES(1,2,NULL);
    INSERT INTO t4 VALUES(2,3,NULL);
    INSERT INTO t4 VALUES(3,NULL,5);
    INSERT INTO t4 VALUES(4,NULL,6);
    INSERT INTO t4 VALUES(4,NULL,6);
    INSERT INTO t4 VALUES(5,NULL,NULL);
    INSERT INTO t4 VALUES(5,NULL,NULL);
    INSERT INTO t4 VALUES(6,7,8);
    SELECT max(x), count(x), y, z FROM t4 GROUP BY y, z ORDER BY 1
  }
} {1 1 2 {} 2 1 3 {} 3 1 {} 5 4 2 {} 6 5 2 {} {} 6 1 7 8}

do_test select5-7.2 {
  execsql {
    SELECT count(*), count(x) as cnt FROM t4 GROUP BY y ORDER BY cnt;
  }
} {1 1 1 1 1 1 5 5}

# See ticket #3324.
#
do_test select5-8.1 {
  execsql {
    CREATE TABLE t8a(a,b);
    CREATE TABLE t8b(x);
    INSERT INTO t8a VALUES('one', 1);
    INSERT INTO t8a VALUES('one', 2);
    INSERT INTO t8a VALUES('two', 3);
    INSERT INTO t8a VALUES('one', NULL);
    INSERT INTO t8b(rowid,x) VALUES(1,111);
    INSERT INTO t8b(rowid,x) VALUES(2,222);
    INSERT INTO t8b(rowid,x) VALUES(3,333);
    SELECT a, count(b) FROM t8a, t8b WHERE b=t8b.rowid GROUP BY a ORDER BY a;
  }
} {one 2 two 1}
do_test select5-8.2 {
  execsql {
    SELECT a, count(b) FROM t8a, t8b WHERE b=+t8b.rowid GROUP BY a ORDER BY a;
  }
} {one 2 two 1}
do_test select5-8.3 {
  execsql {
    SELECT t8a.a, count(t8a.b) FROM t8a, t8b WHERE t8a.b=t8b.rowid
     GROUP BY 1 ORDER BY 1;
  }
} {one 2 two 1}
do_test select5-8.4 {
  execsql {
    SELECT a, count(*) FROM t8a, t8b WHERE b=+t8b.rowid GROUP BY a ORDER BY a;
  }
} {one 2 two 1}
do_test select5-8.5 {
  execsql {
    SELECT a, count(b) FROM t8a, t8b WHERE b<x GROUP BY a ORDER BY a;
  }
} {one 6 two 3}
do_test select5-8.6 {
  execsql {
    SELECT a, count(t8a.b) FROM t8a, t8b WHERE b=t8b.rowid 
     GROUP BY a ORDER BY 2;
  }
} {two 1 one 2}
do_test select5-8.7 {
  execsql {
    SELECT a, count(b) FROM t8a, t8b GROUP BY a ORDER BY 2;
  }
} {two 3 one 6}
do_test select5-8.8 {
  execsql {
    SELECT a, count(*) FROM t8a, t8b GROUP BY a ORDER BY 2;
  }
} {two 3 one 9}



 
finish_test

Added test/select6.test.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing SELECT statements that contain
# subqueries in their FROM clause.
#
# $Id: select6.test,v 1.29 2009/01/09 01:12:28 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Omit this whole file if the library is build without subquery support.
ifcapable !subquery {
  finish_test
  return
}

do_test select6-1.0 {
  execsql {
    BEGIN;
    CREATE TABLE t1(x, y);
    INSERT INTO t1 VALUES(1,1);
    INSERT INTO t1 VALUES(2,2);
    INSERT INTO t1 VALUES(3,2);
    INSERT INTO t1 VALUES(4,3);
    INSERT INTO t1 VALUES(5,3);
    INSERT INTO t1 VALUES(6,3);
    INSERT INTO t1 VALUES(7,3);
    INSERT INTO t1 VALUES(8,4);
    INSERT INTO t1 VALUES(9,4);
    INSERT INTO t1 VALUES(10,4);
    INSERT INTO t1 VALUES(11,4);
    INSERT INTO t1 VALUES(12,4);
    INSERT INTO t1 VALUES(13,4);
    INSERT INTO t1 VALUES(14,4);
    INSERT INTO t1 VALUES(15,4);
    INSERT INTO t1 VALUES(16,5);
    INSERT INTO t1 VALUES(17,5);
    INSERT INTO t1 VALUES(18,5);
    INSERT INTO t1 VALUES(19,5);
    INSERT INTO t1 VALUES(20,5);
    COMMIT;
    SELECT DISTINCT y FROM t1 ORDER BY y;
  }
} {1 2 3 4 5}

do_test select6-1.1 {
  execsql2 {SELECT * FROM (SELECT x, y FROM t1 WHERE x<2)}
} {x 1 y 1}
do_test select6-1.2 {
  execsql {SELECT count(*) FROM (SELECT y FROM t1)}
} {20}
do_test select6-1.3 {
  execsql {SELECT count(*) FROM (SELECT DISTINCT y FROM t1)}
} {5}
do_test select6-1.4 {
  execsql {SELECT count(*) FROM (SELECT DISTINCT * FROM (SELECT y FROM t1))}
} {5}
do_test select6-1.5 {
  execsql {SELECT count(*) FROM (SELECT * FROM (SELECT DISTINCT y FROM t1))}
} {5}

do_test select6-1.6 {
  execsql {
    SELECT * 
    FROM (SELECT count(*),y FROM t1 GROUP BY y) AS a,
         (SELECT max(x),y FROM t1 GROUP BY y) as b
    WHERE a.y=b.y ORDER BY a.y
  }
} {1 1 1 1 2 2 3 2 4 3 7 3 8 4 15 4 5 5 20 5}
do_test select6-1.7 {
  execsql {
    SELECT a.y, a.[count(*)], [max(x)], [count(*)]
    FROM (SELECT count(*),y FROM t1 GROUP BY y) AS a,
         (SELECT max(x),y FROM t1 GROUP BY y) as b
    WHERE a.y=b.y ORDER BY a.y
  }
} {1 1 1 1 2 2 3 2 3 4 7 4 4 8 15 8 5 5 20 5}
do_test select6-1.8 {
  execsql {
    SELECT q, p, r
    FROM (SELECT count(*) as p , y as q FROM t1 GROUP BY y) AS a,
         (SELECT max(x) as r, y as s FROM t1 GROUP BY y) as b
    WHERE q=s ORDER BY s
  }
} {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
do_test select6-1.9 {
  execsql {
    SELECT q, p, r, b.[min(x)+y]
    FROM (SELECT count(*) as p , y as q FROM t1 GROUP BY y) AS a,
         (SELECT max(x) as r, y as s, min(x)+y FROM t1 GROUP BY y) as b
    WHERE q=s ORDER BY s
  }
} {1 1 1 2 2 2 3 4 3 4 7 7 4 8 15 12 5 5 20 21}

do_test select6-2.0 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
    INSERT INTO t2 SELECT * FROM t1;
    SELECT DISTINCT b FROM t2 ORDER BY b;
  }
} {1 2 3 4 5}
do_test select6-2.1 {
  execsql2 {SELECT * FROM (SELECT a, b FROM t2 WHERE a<2)}
} {a 1 b 1}
do_test select6-2.2 {
  execsql {SELECT count(*) FROM (SELECT b FROM t2)}
} {20}
do_test select6-2.3 {
  execsql {SELECT count(*) FROM (SELECT DISTINCT b FROM t2)}
} {5}
do_test select6-2.4 {
  execsql {SELECT count(*) FROM (SELECT DISTINCT * FROM (SELECT b FROM t2))}
} {5}
do_test select6-2.5 {
  execsql {SELECT count(*) FROM (SELECT * FROM (SELECT DISTINCT b FROM t2))}
} {5}

do_test select6-2.6 {
  execsql {
    SELECT * 
    FROM (SELECT count(*),b FROM t2 GROUP BY b) AS a,
         (SELECT max(a),b FROM t2 GROUP BY b) as b
    WHERE a.b=b.b ORDER BY a.b
  }
} {1 1 1 1 2 2 3 2 4 3 7 3 8 4 15 4 5 5 20 5}
do_test select6-2.7 {
  execsql {
    SELECT a.b, a.[count(*)], [max(a)], [count(*)]
    FROM (SELECT count(*),b FROM t2 GROUP BY b) AS a,
         (SELECT max(a),b FROM t2 GROUP BY b) as b
    WHERE a.b=b.b ORDER BY a.b
  }
} {1 1 1 1 2 2 3 2 3 4 7 4 4 8 15 8 5 5 20 5}
do_test select6-2.8 {
  execsql {
    SELECT q, p, r
    FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY b) AS a,
         (SELECT max(a) as r, b as s FROM t2 GROUP BY b) as b
    WHERE q=s ORDER BY s
  }
} {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
do_test select6-2.9 {
  execsql {
    SELECT a.q, a.p, b.r
    FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY q) AS a,
         (SELECT max(a) as r, b as s FROM t2 GROUP BY s) as b
    WHERE a.q=b.s ORDER BY a.q
  }
} {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}

do_test select6-3.1 {
  execsql2 {
    SELECT * FROM (SELECT * FROM (SELECT * FROM t1 WHERE x=3));
  }
} {x 3 y 2}
do_test select6-3.2 {
  execsql {
    SELECT * FROM
      (SELECT a.q, a.p, b.r
       FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY q) AS a,
            (SELECT max(a) as r, b as s FROM t2 GROUP BY s) as b
       WHERE a.q=b.s ORDER BY a.q)
    ORDER BY "a.q"
  }
} {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
do_test select6-3.3 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1)
  }
} {10.5 3.7 14.2}
do_test select6-3.4 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1 WHERE y=4)
  }
} {11.5 4.0 15.5}
do_test select6-3.5 {
  execsql {
    SELECT x,y,x+y FROM (SELECT avg(a) as 'x', avg(b) as 'y' FROM t2 WHERE a=4)
  }
} {4.0 3.0 7.0}
do_test select6-3.6 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1)
    WHERE a>10
  }
} {10.5 3.7 14.2}
do_test select6-3.7 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1)
    WHERE a<10
  }
} {}
do_test select6-3.8 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1 WHERE y=4)
    WHERE a>10
  }
} {11.5 4.0 15.5}
do_test select6-3.9 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1 WHERE y=4)
    WHERE a<10
  }
} {}
do_test select6-3.10 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b)
    ORDER BY a
  }
} {1.0 1 2.0 2.5 2 4.5 5.5 3 8.5 11.5 4 15.5 18.0 5 23.0}
do_test select6-3.11 {
  execsql {
    SELECT a,b,a+b FROM 
       (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b)
    WHERE b<4 ORDER BY a
  }
} {1.0 1 2.0 2.5 2 4.5 5.5 3 8.5}
do_test select6-3.12 {
  execsql {
    SELECT a,b,a+b FROM 
       (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b HAVING a>1)
    WHERE b<4 ORDER BY a
  }
} {2.5 2 4.5 5.5 3 8.5}
do_test select6-3.13 {
  execsql {
    SELECT a,b,a+b FROM 
       (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b HAVING a>1)
    ORDER BY a
  }
} {2.5 2 4.5 5.5 3 8.5 11.5 4 15.5 18.0 5 23.0}
do_test select6-3.14 {
  execsql {
    SELECT [count(*)],y FROM (SELECT count(*), y FROM t1 GROUP BY y)
    ORDER BY [count(*)]
  }
} {1 1 2 2 4 3 5 5 8 4}
do_test select6-3.15 {
  execsql {
    SELECT [count(*)],y FROM (SELECT count(*), y FROM t1 GROUP BY y)
    ORDER BY y
  }
} {1 1 2 2 4 3 8 4 5 5}

do_test select6-4.1 {
  execsql {
    SELECT a,b,c FROM 
      (SELECT x AS 'a', y AS 'b', x+y AS 'c' FROM t1 WHERE y=4)
    WHERE a<10 ORDER BY a;
  }
} {8 4 12 9 4 13}
do_test select6-4.2 {
  execsql {
    SELECT y FROM (SELECT DISTINCT y FROM t1) WHERE y<5 ORDER BY y
  }
} {1 2 3 4}
do_test select6-4.3 {
  execsql {
    SELECT DISTINCT y FROM (SELECT y FROM t1) WHERE y<5 ORDER BY y
  }
} {1 2 3 4}
do_test select6-4.4 {
  execsql {
    SELECT avg(y) FROM (SELECT DISTINCT y FROM t1) WHERE y<5 ORDER BY y
  }
} {2.5}
do_test select6-4.5 {
  execsql {
    SELECT avg(y) FROM (SELECT DISTINCT y FROM t1 WHERE y<5) ORDER BY y
  }
} {2.5}

do_test select6-5.1 {
  execsql {
    SELECT a,x,b FROM
      (SELECT x+3 AS 'a', x FROM t1 WHERE y=3) AS 'p',
      (SELECT x AS 'b' FROM t1 WHERE y=4) AS 'q'
    WHERE a=b
    ORDER BY a
  }
} {8 5 8 9 6 9 10 7 10}
do_test select6-5.2 {
  execsql {
    SELECT a,x,b FROM
      (SELECT x+3 AS 'a', x FROM t1 WHERE y=3),
      (SELECT x AS 'b' FROM t1 WHERE y=4)
    WHERE a=b
    ORDER BY a
  }
} {8 5 8 9 6 9 10 7 10}

# Tests of compound sub-selects
#
do_test select6-6.1 {
  execsql {
    DELETE FROM t1 WHERE x>4;
    SELECT * FROM t1
  }
} {1 1 2 2 3 2 4 3}
ifcapable compound {
  do_test select6-6.2 {
    execsql {
      SELECT * FROM (
        SELECT x AS 'a' FROM t1 UNION ALL SELECT x+10 AS 'a' FROM t1
      ) ORDER BY a;
    }
  } {1 2 3 4 11 12 13 14}
  do_test select6-6.3 {
    execsql {
      SELECT * FROM (
        SELECT x AS 'a' FROM t1 UNION ALL SELECT x+1 AS 'a' FROM t1
      ) ORDER BY a;
    }
  } {1 2 2 3 3 4 4 5}
  do_test select6-6.4 {
    execsql {
      SELECT * FROM (
        SELECT x AS 'a' FROM t1 UNION SELECT x+1 AS 'a' FROM t1
      ) ORDER BY a;
    }
  } {1 2 3 4 5}
  do_test select6-6.5 {
    execsql {
      SELECT * FROM (
        SELECT x AS 'a' FROM t1 INTERSECT SELECT x+1 AS 'a' FROM t1
      ) ORDER BY a;
    }
  } {2 3 4}
  do_test select6-6.6 {
    execsql {
      SELECT * FROM (
        SELECT x AS 'a' FROM t1 EXCEPT SELECT x*2 AS 'a' FROM t1
      ) ORDER BY a;
    }
  } {1 3}
} ;# ifcapable compound

# Subselects with no FROM clause
#
do_test select6-7.1 {
  execsql {
    SELECT * FROM (SELECT 1)
  }
} {1}
do_test select6-7.2 {
  execsql {
    SELECT c,b,a,* FROM (SELECT 1 AS 'a', 2 AS 'b', 'abc' AS 'c')
  }
} {abc 2 1 1 2 abc}
do_test select6-7.3 {
  execsql {
    SELECT c,b,a,* FROM (SELECT 1 AS 'a', 2 AS 'b', 'abc' AS 'c' WHERE 0)
  }
} {}
do_test select6-7.4 {
  execsql2 {
    SELECT c,b,a,* FROM (SELECT 1 AS 'a', 2 AS 'b', 'abc' AS 'c' WHERE 1)
  }
} {c abc b 2 a 1 a 1 b 2 c abc}

# The remaining tests in this file depend on the EXPLAIN keyword.
# Skip these tests if EXPLAIN is disabled in the current build.
#
ifcapable {!explain} {
  finish_test
  return
}

# The following procedure compiles the SQL given as an argument and returns
# TRUE if that SQL uses any transient tables and returns FALSE if no
# transient tables are used.  This is used to make sure that the
# sqliteFlattenSubquery() routine in select.c is doing its job.
#
proc is_flat {sql} {
  return [expr 0>[lsearch [execsql "EXPLAIN $sql"] OpenEphemeral]]
}

# Check that the flattener works correctly for deeply nested subqueries
# involving joins.
#
do_test select6-8.1 {
  execsql {
    BEGIN;
    CREATE TABLE t3(p,q);
    INSERT INTO t3 VALUES(1,11);
    INSERT INTO t3 VALUES(2,22);
    CREATE TABLE t4(q,r);
    INSERT INTO t4 VALUES(11,111);
    INSERT INTO t4 VALUES(22,222);
    COMMIT;
    SELECT * FROM t3 NATURAL JOIN t4;
  }
} {1 11 111 2 22 222}
do_test select6-8.2 {
  execsql {
    SELECT y, p, q, r FROM
       (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m,
       (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n
    WHERE  y=p
  }
} {1 1 11 111 2 2 22 222 2 2 22 222}
# If view support is omitted from the build, then so is the query 
# "flattener". So omit this test and test select6-8.6 in that case.
ifcapable view {
do_test select6-8.3 {
  is_flat {
    SELECT y, p, q, r FROM
       (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m,
       (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n
    WHERE  y=p
  }
} {1}
} ;# ifcapable view
do_test select6-8.4 {
  execsql {
    SELECT DISTINCT y, p, q, r FROM
       (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m,
       (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n
    WHERE  y=p
  }
} {1 1 11 111 2 2 22 222}
do_test select6-8.5 {
  execsql {
    SELECT * FROM 
      (SELECT y, p, q, r FROM
         (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m,
         (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n
      WHERE  y=p) AS e,
      (SELECT r AS z FROM t4 WHERE q=11) AS f
    WHERE e.r=f.z
  }
} {1 1 11 111 111}
ifcapable view {
do_test select6-8.6 {
  is_flat {
    SELECT * FROM 
      (SELECT y, p, q, r FROM
         (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m,
         (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n
      WHERE  y=p) AS e,
      (SELECT r AS z FROM t4 WHERE q=11) AS f
    WHERE e.r=f.z
  }
} {1}
} ;# ifcapable view

# Ticket #1634
#
do_test select6-9.1 {
  execsql {
    SELECT a.x, b.x FROM t1 AS a, (SELECT x FROM t1 LIMIT 2) AS b
  }
} {1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2}
do_test select6-9.2 {
  execsql {
    SELECT x FROM (SELECT x FROM t1 LIMIT 2);
  }
} {1 2}
do_test select6-9.3 {
  execsql {
    SELECT x FROM (SELECT x FROM t1 LIMIT 2 OFFSET 1);
  }
} {2 3}
do_test select6-9.4 {
  execsql {
    SELECT x FROM (SELECT x FROM t1) LIMIT 2;
  }
} {1 2}
do_test select6-9.5 {
  execsql {
    SELECT x FROM (SELECT x FROM t1) LIMIT 2 OFFSET 1;
  }
} {2 3}
do_test select6-9.6 {
  execsql {
    SELECT x FROM (SELECT x FROM t1 LIMIT 2) LIMIT 3;
  }
} {1 2}
do_test select6-9.7 {
  execsql {
    SELECT x FROM (SELECT x FROM t1 LIMIT -1) LIMIT 3;
  }
} {1 2 3}
do_test select6-9.8 {
  execsql {
    SELECT x FROM (SELECT x FROM t1 LIMIT -1);
  }
} {1 2 3 4}
do_test select6-9.9 {
  execsql {
    SELECT x FROM (SELECT x FROM t1 LIMIT -1 OFFSET 1);
  }
} {2 3 4}
do_test select6-9.10 {
  execsql {
    SELECT x, y FROM (SELECT x, (SELECT 10+x) y FROM t1 LIMIT -1 OFFSET 1);
  }
} {2 12 3 13 4 14}
do_test select6-9.11 {
  execsql {
    SELECT x, y FROM (SELECT x, (SELECT 10)+x y FROM t1 LIMIT -1 OFFSET 1);
  }
} {2 12 3 13 4 14}



finish_test

Added test/select7.test.































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing compute SELECT statements and nested
# views.
#
# $Id: select7.test,v 1.11 2007/09/12 17:01:45 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable compound {

# A 3-way INTERSECT.  Ticket #875
ifcapable tempdb {
  do_test select7-1.1 {
    execsql {
      create temp table t1(x);
      insert into t1 values('amx');
      insert into t1 values('anx');
      insert into t1 values('amy');
      insert into t1 values('bmy');
      select * from t1 where x like 'a__'
        intersect select * from t1 where x like '_m_'
        intersect select * from t1 where x like '__x';
    }
  } {amx}
}


# Nested views do not handle * properly.  Ticket #826.
#
ifcapable view {
do_test select7-2.1 {
  execsql {
    CREATE TABLE x(id integer primary key, a TEXT NULL);
    INSERT INTO x (a) VALUES ('first');
    CREATE TABLE tempx(id integer primary key, a TEXT NULL);
    INSERT INTO tempx (a) VALUES ('t-first');
    CREATE VIEW tv1 AS SELECT x.id, tx.id FROM x JOIN tempx tx ON tx.id=x.id;
    CREATE VIEW tv1b AS SELECT x.id, tx.id FROM x JOIN tempx tx on tx.id=x.id;
    CREATE VIEW tv2 AS SELECT * FROM tv1 UNION SELECT * FROM tv1b;
    SELECT * FROM tv2;
  }
} {1 1}
} ;# ifcapable view

} ;# ifcapable compound

# Do not allow GROUP BY without an aggregate. Ticket #1039.
#
# Change: force any query with a GROUP BY clause to be processed as
# an aggregate query, whether it contains aggregates or not.
#
ifcapable subquery {
  # do_test select7-3.1 {
  #   catchsql {
  #     SELECT * FROM (SELECT * FROM sqlite_master) GROUP BY name
  #   }
  # } {1 {GROUP BY may only be used on aggregate queries}}
  do_test select7-3.1 {
    catchsql {
      SELECT * FROM (SELECT * FROM sqlite_master) GROUP BY name
    }
  } [list 0 [execsql {SELECT * FROM sqlite_master ORDER BY name}]]
}

# Ticket #2018 - Make sure names are resolved correctly on all
# SELECT statements of a compound subquery.
#
ifcapable {subquery && compound} {
  do_test select7-4.1 {
    execsql {
      CREATE TABLE IF NOT EXISTS photo(pk integer primary key, x);
      CREATE TABLE IF NOT EXISTS tag(pk integer primary key, fk int, name);
    
      SELECT P.pk from PHOTO P WHERE NOT EXISTS ( 
           SELECT T2.pk from TAG T2 WHERE T2.fk = P.pk 
           EXCEPT 
           SELECT T3.pk from TAG T3 WHERE T3.fk = P.pk AND T3.name LIKE '%foo%'
      );
    }
  } {}
  do_test select7-4.2 {
    execsql {
      INSERT INTO photo VALUES(1,1);
      INSERT INTO photo VALUES(2,2);
      INSERT INTO photo VALUES(3,3);
      INSERT INTO tag VALUES(11,1,'one');
      INSERT INTO tag VALUES(12,1,'two');
      INSERT INTO tag VALUES(21,1,'one-b');
      SELECT P.pk from PHOTO P WHERE NOT EXISTS ( 
           SELECT T2.pk from TAG T2 WHERE T2.fk = P.pk 
           EXCEPT 
           SELECT T3.pk from TAG T3 WHERE T3.fk = P.pk AND T3.name LIKE '%foo%'
      );
    }
  } {2 3}
}

# ticket #2347
#
ifcapable {subquery && compound} {
  do_test select7-5.1 {
    catchsql {
      CREATE TABLE t2(a,b);
      SELECT 5 IN (SELECT a,b FROM t2);
    }
  } [list 1 \
     {only a single result allowed for a SELECT that is part of an expression}]
  do_test select7-5.2 {
    catchsql {
      SELECT 5 IN (SELECT * FROM t2);
    }
  } [list 1 \
     {only a single result allowed for a SELECT that is part of an expression}]
  do_test select7-5.3 {
    catchsql {
      SELECT 5 IN (SELECT a,b FROM t2 UNION SELECT b,a FROM t2);
    }
  } [list 1 \
     {only a single result allowed for a SELECT that is part of an expression}]
  do_test select7-5.4 {
    catchsql {
      SELECT 5 IN (SELECT * FROM t2 UNION SELECT * FROM t2);
    }
  } [list 1 \
     {only a single result allowed for a SELECT that is part of an expression}]
}

# Verify that an error occurs if you have too many terms on a
# compound select statement.
#
ifcapable compound {
  if {$SQLITE_MAX_COMPOUND_SELECT>0} {
    set sql {SELECT 0}
    set result 0
    for {set i 1} {$i<$SQLITE_MAX_COMPOUND_SELECT} {incr i} {
      append sql " UNION ALL SELECT $i"
      lappend result $i
    }
    do_test select7-6.1 {
      catchsql $sql
    } [list 0 $result]
    append sql { UNION ALL SELECT 99999999}
    do_test select7-6.2 {
      catchsql $sql
    } {1 {too many terms in compound SELECT}}
  }
}

finish_test

Added test/select8.test.





























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# The focus of this file is testing that LIMIT and OFFSET work for
# unusual combinations SELECT statements.
#
# $Id: select8.test,v 1.1 2008/01/12 12:48:09 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

execsql {
  CREATE TABLE songs(songid, artist, timesplayed);
  INSERT INTO songs VALUES(1,'one',1);
  INSERT INTO songs VALUES(2,'one',2);
  INSERT INTO songs VALUES(3,'two',3);
  INSERT INTO songs VALUES(4,'three',5);
  INSERT INTO songs VALUES(5,'one',7);
  INSERT INTO songs VALUES(6,'two',11);
}
set result [execsql {
  SELECT DISTINCT artist,sum(timesplayed) AS total      
  FROM songs      
  GROUP BY LOWER(artist)      
}]
puts result=$result
do_test select8-1.1 {
  execsql {
    SELECT DISTINCT artist,sum(timesplayed) AS total      
    FROM songs      
    GROUP BY LOWER(artist)      
    LIMIT 1 OFFSET 1
  }
} [lrange $result 2 3]
do_test select8-1.2 {
  execsql {
    SELECT DISTINCT artist,sum(timesplayed) AS total      
    FROM songs      
    GROUP BY LOWER(artist)      
    LIMIT 2 OFFSET 1
  }
} [lrange $result 2 5]
do_test select8-1.3 {
  execsql {
    SELECT DISTINCT artist,sum(timesplayed) AS total      
    FROM songs      
    GROUP BY LOWER(artist)      
    LIMIT -1 OFFSET 2
  }
} [lrange $result 4 end]


finish_test

Added test/select9.test.











































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# 2008 June 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# $Id: select9.test,v 1.4 2008/07/01 14:39:35 danielk1977 Exp $

# The tests in this file are focused on test compound SELECT statements 
# that have any or all of an ORDER BY, LIMIT or OFFSET clauses. As of
# version 3.6.0, SQLite contains code to use SQL indexes where possible 
# to optimize such statements.
#

# TODO Points:
#
#   * Are there any "column affinity" issues to consider?

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#set ISQUICK 1

#-------------------------------------------------------------------------
# test_compound_select TESTNAME SELECT RESULT
#
#   This command is used to run multiple LIMIT/OFFSET test cases based on 
#   the single SELECT statement passed as the second argument. The SELECT
#   statement may not contain a LIMIT or OFFSET clause. This proc tests
#   many statements of the form:
#    
#     "$SELECT limit $X offset $Y"
#    
#   for various values of $X and $Y.
#    
#   The third argument, $RESULT, should contain the expected result of
#   the command [execsql $SELECT].
#    
#   The first argument, $TESTNAME, is used as the base test case name to
#   pass to [do_test] for each individual LIMIT OFFSET test case.
# 
proc test_compound_select {testname sql result} {

  set nCol 1
  db eval $sql A {
    set nCol [llength $A(*)]
    break
  }
  set nRow [expr {[llength $result] / $nCol}]

  set ::compound_sql $sql
  do_test $testname { 
    execsql $::compound_sql
  } $result
#return

  set iLimitIncr  1
  set iOffsetIncr 1
  if {[info exists ::ISQUICK] && $::ISQUICK && $nRow>=5} {
    set iOffsetIncr [expr $nRow / 5]
    set iLimitIncr [expr $nRow / 5]
  }

  set iLimitEnd   [expr $nRow+$iLimitIncr]
  set iOffsetEnd  [expr $nRow+$iOffsetIncr]

  for {set iOffset 0} {$iOffset < $iOffsetEnd} {incr iOffset $iOffsetIncr} {
    for {set iLimit 0} {$iLimit < $iLimitEnd} {incr iLimit} {
  
      set ::compound_sql "$sql LIMIT $iLimit"
      if {$iOffset != 0} {
        append ::compound_sql " OFFSET $iOffset"
      }
  
      set iStart [expr {$iOffset*$nCol}]
      set iEnd [expr {($iOffset*$nCol) + ($iLimit*$nCol) -1}]
  
      do_test $testname.limit=$iLimit.offset=$iOffset { 
        execsql $::compound_sql
      } [lrange $result $iStart $iEnd]
    }
  }
}

#-------------------------------------------------------------------------
# test_compound_select_flippable TESTNAME SELECT RESULT
#
#   This command is for testing statements of the form:
#
#     <simple select 1> <compound op> <simple select 2> ORDER BY <order by>
#
#   where each <simple select> is a simple (non-compound) select statement
#   and <compound op> is one of "INTERSECT", "UNION ALL" or "UNION".
#
#   This proc calls [test_compound_select] twice, once with the select
#   statement as it is passed to this command, and once with the positions
#   of <select statement 1> and <select statement 2> exchanged.
#
proc test_compound_select_flippable {testname sql result} {
  test_compound_select $testname $sql $result

  set select [string trim $sql]
  set RE {(.*)(UNION ALL|INTERSECT|UNION)(.*)(ORDER BY.*)}
  set rc [regexp $RE $select -> s1 op s2 order_by]
  if {!$rc} {error "Statement is unflippable: $select"}

  set flipsql "$s2 $op $s1 $order_by"
  test_compound_select $testname.flipped $flipsql $result
}

#############################################################################
# Begin tests.
#

# Create and populate a sample database.
#
do_test select9-1.0 {
  execsql {
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(d, e, f);
    BEGIN;
      INSERT INTO t1 VALUES(1,  'one',   'I');
      INSERT INTO t1 VALUES(3,  NULL,    NULL);
      INSERT INTO t1 VALUES(5,  'five',  'V');
      INSERT INTO t1 VALUES(7,  'seven', 'VII');
      INSERT INTO t1 VALUES(9,  NULL,    NULL);
      INSERT INTO t1 VALUES(2,  'two',   'II');
      INSERT INTO t1 VALUES(4,  'four',  'IV');
      INSERT INTO t1 VALUES(6,  NULL,    NULL);
      INSERT INTO t1 VALUES(8,  'eight', 'VIII');
      INSERT INTO t1 VALUES(10, 'ten',   'X');

      INSERT INTO t2 VALUES(1,  'two',      'IV');
      INSERT INTO t2 VALUES(2,  'four',     'VIII');
      INSERT INTO t2 VALUES(3,  NULL,       NULL);
      INSERT INTO t2 VALUES(4,  'eight',    'XVI');
      INSERT INTO t2 VALUES(5,  'ten',      'XX');
      INSERT INTO t2 VALUES(6,  NULL,       NULL);
      INSERT INTO t2 VALUES(7,  'fourteen', 'XXVIII');
      INSERT INTO t2 VALUES(8,  'sixteen',  'XXXII');
      INSERT INTO t2 VALUES(9,  NULL,       NULL);
      INSERT INTO t2 VALUES(10, 'twenty',   'XL');

    COMMIT;
  }
} {}

# Each iteration of this loop runs the same tests with a different set
# of indexes present within the database schema. The data returned by
# the compound SELECT statements in the test cases should be the same 
# in each case.
#
set iOuterLoop 1
foreach indexes [list {
  /* Do not create any indexes. */
} {
  CREATE INDEX i1 ON t1(a)
} {
  CREATE INDEX i2 ON t1(b)
} {
  CREATE INDEX i3 ON t2(d)
} {
  CREATE INDEX i4 ON t2(e)
}] {

  do_test select9-1.$iOuterLoop.1 {
    execsql $indexes
  } {}

  # Test some 2-way UNION ALL queries. No WHERE clauses.
  #
  test_compound_select select9-1.$iOuterLoop.2 {
    SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 
  } {1 one 3 {} 5 five 7 seven 9 {} 2 two 4 four 6 {} 8 eight 10 ten 1 two 2 four 3 {} 4 eight 5 ten 6 {} 7 fourteen 8 sixteen 9 {} 10 twenty}
  test_compound_select select9-1.$iOuterLoop.3 {
    SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 1 
  } {1 one 1 two 2 two 2 four 3 {} 3 {} 4 four 4 eight 5 five 5 ten 6 {} 6 {} 7 seven 7 fourteen 8 eight 8 sixteen 9 {} 9 {} 10 ten 10 twenty}
  test_compound_select select9-1.$iOuterLoop.4 {
    SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 2 
  } {3 {} 9 {} 6 {} 3 {} 6 {} 9 {} 8 eight 4 eight 5 five 4 four 2 four 7 fourteen 1 one 7 seven 8 sixteen 10 ten 5 ten 10 twenty 2 two 1 two}
  test_compound_select_flippable select9-1.$iOuterLoop.5 {
    SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 1, 2
  } {1 one 1 two 2 four 2 two 3 {} 3 {} 4 eight 4 four 5 five 5 ten 6 {} 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 9 {} 10 ten 10 twenty}
  test_compound_select_flippable select9-1.$iOuterLoop.6 {
    SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 2, 1
  } {3 {} 3 {} 6 {} 6 {} 9 {} 9 {} 4 eight 8 eight 5 five 2 four 4 four 7 fourteen 1 one 7 seven 8 sixteen 5 ten 10 ten 10 twenty 1 two 2 two}

  # Test some 2-way UNION queries.
  #
  test_compound_select select9-1.$iOuterLoop.7 {
    SELECT a, b FROM t1 UNION SELECT d, e FROM t2 
  } {1 one 1 two 2 four 2 two 3 {} 4 eight 4 four 5 five 5 ten 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 10 ten 10 twenty}

  test_compound_select select9-1.$iOuterLoop.8 {
    SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 1 
  } {1 one 1 two 2 four 2 two 3 {} 4 eight 4 four 5 five 5 ten 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 10 ten 10 twenty}

  test_compound_select select9-1.$iOuterLoop.9 {
    SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 2 
  } {3 {} 6 {} 9 {} 4 eight 8 eight 5 five 2 four 4 four 7 fourteen 1 one 7 seven 8 sixteen 5 ten 10 ten 10 twenty 1 two 2 two}

  test_compound_select_flippable select9-1.$iOuterLoop.10 {
    SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 1, 2
  } {1 one 1 two 2 four 2 two 3 {} 4 eight 4 four 5 five 5 ten 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 10 ten 10 twenty}

  test_compound_select_flippable select9-1.$iOuterLoop.11 {
    SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 2, 1
  } {3 {} 6 {} 9 {} 4 eight 8 eight 5 five 2 four 4 four 7 fourteen 1 one 7 seven 8 sixteen 5 ten 10 ten 10 twenty 1 two 2 two}

  # Test some 2-way INTERSECT queries.
  #
  test_compound_select select9-1.$iOuterLoop.11 {
    SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 
  } {3 {} 6 {} 9 {}}
  test_compound_select_flippable select9-1.$iOuterLoop.12 {
    SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 1
  } {3 {} 6 {} 9 {}}
  test_compound_select select9-1.$iOuterLoop.13 {
    SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 2
  } {3 {} 6 {} 9 {}}
  test_compound_select_flippable select9-1.$iOuterLoop.14 {
    SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 2, 1
  } {3 {} 6 {} 9 {}}
  test_compound_select_flippable select9-1.$iOuterLoop.15 {
    SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 1, 2
  } {3 {} 6 {} 9 {}}

  # Test some 2-way EXCEPT queries.
  #
  test_compound_select select9-1.$iOuterLoop.16 {
    SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 
  } {1 one 2 two 4 four 5 five 7 seven 8 eight 10 ten}

  test_compound_select select9-1.$iOuterLoop.17 {
    SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 1 
  } {1 one 2 two 4 four 5 five 7 seven 8 eight 10 ten}

  test_compound_select select9-1.$iOuterLoop.18 {
    SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 2 
  } {8 eight 5 five 4 four 1 one 7 seven 10 ten 2 two}

  test_compound_select select9-1.$iOuterLoop.19 {
    SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 1, 2
  } {1 one 2 two 4 four 5 five 7 seven 8 eight 10 ten}

  test_compound_select select9-1.$iOuterLoop.20 {
    SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 2, 1
  } {8 eight 5 five 4 four 1 one 7 seven 10 ten 2 two}

  incr iOuterLoop
}

do_test select9-2.0 {
  execsql {
    DROP INDEX i1;
    DROP INDEX i2;
    DROP INDEX i3;
    DROP INDEX i4;
  }
} {}

proc reverse {lhs rhs} {
  return [string compare $rhs $lhs]
}
db collate reverse reverse

# This loop is similar to the previous one (test cases select9-1.*) 
# except that the simple select statements have WHERE clauses attached
# to them. Sometimes the WHERE clause may be satisfied using the same
# index used for ORDER BY, sometimes not.
#
set iOuterLoop 1
foreach indexes [list {
  /* Do not create any indexes. */
} {
  CREATE INDEX i1 ON t1(a)
} {
  DROP INDEX i1;
  CREATE INDEX i1 ON t1(b, a)
} {
  CREATE INDEX i2 ON t2(d DESC, e COLLATE REVERSE ASC);
} {
  CREATE INDEX i3 ON t1(a DESC);
}] {
  do_test select9-2.$iOuterLoop.1 {
    execsql $indexes
  } {}

  test_compound_select_flippable select9-2.$iOuterLoop.2 {
    SELECT * FROM t1 WHERE a<5 UNION SELECT * FROM t2 WHERE d>=5 ORDER BY 1
  } {1 one I 2 two II 3 {} {} 4 four IV 5 ten XX 6 {} {} 7 fourteen XXVIII 8 sixteen XXXII 9 {} {} 10 twenty XL}

  test_compound_select_flippable select9-2.$iOuterLoop.2 {
    SELECT * FROM t1 WHERE a<5 UNION SELECT * FROM t2 WHERE d>=5 ORDER BY 2, 1
  } {3 {} {} 6 {} {} 9 {} {} 4 four IV 7 fourteen XXVIII 1 one I 8 sixteen XXXII 5 ten XX 10 twenty XL 2 two II}

  test_compound_select_flippable select9-2.$iOuterLoop.3 {
    SELECT * FROM t1 WHERE a<5 UNION SELECT * FROM t2 WHERE d>=5 
    ORDER BY 2 COLLATE reverse, 1
  } {3 {} {} 6 {} {} 9 {} {} 2 two II 10 twenty XL 5 ten XX 8 sixteen XXXII 1 one I 7 fourteen XXVIII 4 four IV}

  test_compound_select_flippable select9-2.$iOuterLoop.4 {
    SELECT * FROM t1 WHERE a<5 UNION ALL SELECT * FROM t2 WHERE d>=5 ORDER BY 1
  } {1 one I 2 two II 3 {} {} 4 four IV 5 ten XX 6 {} {} 7 fourteen XXVIII 8 sixteen XXXII 9 {} {} 10 twenty XL}

  test_compound_select_flippable select9-2.$iOuterLoop.5 {
    SELECT * FROM t1 WHERE a<5 UNION ALL SELECT * FROM t2 WHERE d>=5 ORDER BY 2, 1
  } {3 {} {} 6 {} {} 9 {} {} 4 four IV 7 fourteen XXVIII 1 one I 8 sixteen XXXII 5 ten XX 10 twenty XL 2 two II}

  test_compound_select_flippable select9-2.$iOuterLoop.6 {
    SELECT * FROM t1 WHERE a<5 UNION ALL SELECT * FROM t2 WHERE d>=5 
    ORDER BY 2 COLLATE reverse, 1
  } {3 {} {} 6 {} {} 9 {} {} 2 two II 10 twenty XL 5 ten XX 8 sixteen XXXII 1 one I 7 fourteen XXVIII 4 four IV}

  test_compound_select select9-2.$iOuterLoop.4 {
    SELECT a FROM t1 WHERE a<8 EXCEPT SELECT d FROM t2 WHERE d<=3 ORDER BY 1
  } {4 5 6 7}

  test_compound_select select9-2.$iOuterLoop.4 {
    SELECT a FROM t1 WHERE a<8 INTERSECT SELECT d FROM t2 WHERE d<=3 ORDER BY 1
  } {1 2 3}

}

do_test select9-2.X {
  execsql {
    DROP INDEX i1;
    DROP INDEX i2;
    DROP INDEX i3;
  }
} {}

# This procedure executes the SQL.  Then it checks the generated program
# for the SQL and appends a "nosort" to the result if the program contains the
# SortCallback opcode.  If the program does not contain the SortCallback
# opcode it appends "sort"
#
proc cksort {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

# If the right indexes exist, the following query:
#
#     SELECT t1.a FROM t1 UNION ALL SELECT t2.d FROM t2 ORDER BY 1
#
# can use indexes to run without doing a in-memory sort operation.
# This block of tests (select9-3.*) is used to check if the same 
# is possible with:
#
#     CREATE VIEW v1 AS SELECT a FROM t1 UNION ALL SELECT d FROM t2
#     SELECT a FROM v1 ORDER BY 1
#
# It turns out that it is.
#
do_test select9-3.1 {
  cksort { SELECT a FROM t1 ORDER BY 1 }
} {1 2 3 4 5 6 7 8 9 10 sort}
do_test select9-3.2 {
  execsql { CREATE INDEX i1 ON t1(a) }
  cksort { SELECT a FROM t1 ORDER BY 1 }
} {1 2 3 4 5 6 7 8 9 10 nosort}
do_test select9-3.3 {
  cksort { SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 5 }
} {1 1 2 2 3 sort}
do_test select9-3.4 {
  execsql { CREATE INDEX i2 ON t2(d) }
  cksort { SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 5 }
} {1 1 2 2 3 nosort}
do_test select9-3.5 {
  execsql { CREATE VIEW v1 AS SELECT a FROM t1 UNION ALL SELECT d FROM t2 }
  cksort { SELECT a FROM v1 ORDER BY 1 LIMIT 5 }
} {1 1 2 2 3 nosort}
do_test select9-3.X {
  execsql {
    DROP INDEX i1;
    DROP INDEX i2;
    DROP VIEW v1;
  }
} {}

# This block of tests is the same as the preceding one, except that
# "UNION" is tested instead of "UNION ALL".
#
do_test select9-4.1 {
  cksort { SELECT a FROM t1 ORDER BY 1 }
} {1 2 3 4 5 6 7 8 9 10 sort}
do_test select9-4.2 {
  execsql { CREATE INDEX i1 ON t1(a) }
  cksort { SELECT a FROM t1 ORDER BY 1 }
} {1 2 3 4 5 6 7 8 9 10 nosort}
do_test select9-4.3 {
  cksort { SELECT a FROM t1 UNION SELECT d FROM t2 ORDER BY 1 LIMIT 5 }
} {1 2 3 4 5 sort}
do_test select9-4.4 {
  execsql { CREATE INDEX i2 ON t2(d) }
  cksort { SELECT a FROM t1 UNION SELECT d FROM t2 ORDER BY 1 LIMIT 5 }
} {1 2 3 4 5 nosort}
do_test select9-4.5 {
  execsql { CREATE VIEW v1 AS SELECT a FROM t1 UNION SELECT d FROM t2 }
  cksort { SELECT a FROM v1 ORDER BY 1 LIMIT 5 }
} {1 2 3 4 5 sort}
do_test select9-4.X {
  execsql {
    DROP INDEX i1;
    DROP INDEX i2;
    DROP VIEW v1;
  }
} {}


finish_test

Added test/selectA.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# 2008 June 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# The focus of this file is testing the compound-SELECT merge
# optimization.  Or, in other words, making sure that all
# possible combinations of UNION, UNION ALL, EXCEPT, and
# INTERSECT work together with an ORDER BY clause (with or w/o
# explicit sort order and explicit collating secquites) and
# with and without optional LIMIT and OFFSET clauses.
#
# $Id: selectA.test,v 1.6 2008/08/21 14:24:29 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound {
  finish_test
  return
}

do_test selectA-1.0 {
  execsql {
    CREATE TABLE t1(a,b,c COLLATE NOCASE);
    INSERT INTO t1 VALUES(1,'a','a');
    INSERT INTO t1 VALUES(9.9, 'b', 'B');
    INSERT INTO t1 VALUES(NULL, 'C', 'c');
    INSERT INTO t1 VALUES('hello', 'd', 'D');
    INSERT INTO t1 VALUES(x'616263', 'e', 'e');
    SELECT * FROM t1;
  }
} {1 a a 9.9 b B {} C c hello d D abc e e}
do_test selectA-1.1 {
  execsql {
    CREATE TABLE t2(x,y,z COLLATE NOCASE);
    INSERT INTO t2 VALUES(NULL,'U','u');
    INSERT INTO t2 VALUES('mad', 'Z', 'z');
    INSERT INTO t2 VALUES(x'68617265', 'm', 'M');
    INSERT INTO t2 VALUES(5.2e6, 'X', 'x');
    INSERT INTO t2 VALUES(-23, 'Y', 'y');
    SELECT * FROM t2;
  }
} {{} U u mad Z z hare m M 5200000.0 X x -23 Y y}
do_test selectA-1.2 {
  execsql {
    CREATE TABLE t3(a,b,c COLLATE NOCASE);
    INSERT INTO t3 SELECT * FROM t1;
    INSERT INTO t3 SELECT * FROM t2;
    INSERT INTO t3 SELECT * FROM t1;
    INSERT INTO t3 SELECT * FROM t2;
    INSERT INTO t3 SELECT * FROM t1;
    INSERT INTO t3 SELECT * FROM t2;
    SELECT count(*) FROM t3;
  }
} {30}

do_test selectA-2.1 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.1.1 {   # Ticket #3314
  execsql {
    SELECT t1.a, t1.b, t1.c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.1.2 {   # Ticket #3314
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY t1.a, t1.b, t1.c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.2 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-2.3 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.4 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-2.5 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.6 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.7 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.8 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.9 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.10 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-2.11 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.12 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-2.13 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.14 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-2.15 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.16 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.17 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.18 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.19 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.20 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-2.21 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.22 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-2.23 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.24 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-2.25 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.26 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.27 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.28 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.29 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.30 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-2.31 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.32 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-2.33 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.34 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-2.35 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.36 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.37 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.38 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.39 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.40 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-2.41 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a,b,c
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-2.42 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a,b,c
  }
} {hello d D abc e e}
do_test selectA-2.43 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {hello d D abc e e}
do_test selectA-2.44 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a,b,c
  }
} {hello d D abc e e}
do_test selectA-2.45 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a,b,c
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-2.46 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-2.47 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a DESC
  }
} {9.9 b B 1 a a {} C c}
do_test selectA-2.48 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a DESC
  }
} {abc e e hello d D}
do_test selectA-2.49 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a DESC
  }
} {abc e e hello d D}
do_test selectA-2.50 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a DESC
  }
} {abc e e hello d D}
do_test selectA-2.51 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a DESC
  }
} {9.9 b B 1 a a {} C c}
do_test selectA-2.52 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a DESC
  }
} {9.9 b B 1 a a {} C c}
do_test selectA-2.53 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY b, a DESC
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-2.54 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY b
  }
} {hello d D abc e e}
do_test selectA-2.55 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY b DESC, c
  }
} {abc e e hello d D}
do_test selectA-2.56 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY b, c DESC, a
  }
} {hello d D abc e e}
do_test selectA-2.57 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY b COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.58 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY b
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-2.59 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY c, a DESC
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.60 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY c
  }
} {hello d D abc e e}
do_test selectA-2.61 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY c COLLATE BINARY, b DESC, c, a, b, c, a, b, c
  }
} {hello d D abc e e}
do_test selectA-2.62 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY c DESC, a
  }
} {abc e e hello d D}
do_test selectA-2.63 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY c COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.64 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.65 {
  execsql {
    SELECT a,b,c FROM t3 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY c COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.66 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t3
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.67 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t3 WHERE b<'d'
    ORDER BY c DESC, a
  }
} {abc e e hello d D}
do_test selectA-2.68 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    ORDER BY c DESC, a
  }
} {abc e e hello d D}
do_test selectA-2.69 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    ORDER BY c COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.70 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.71 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d'
    INTERSECT SELECT a,b,c FROM t1
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    INTERSECT SELECT a,b,c FROM t1
    EXCEPT SELECT x,y,z FROM t2
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT y,x,z FROM t2
    INTERSECT SELECT a,b,c FROM t1
    EXCEPT SELECT c,b,a FROM t3
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-2.72 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.73 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-2.74 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.75 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-2.76 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.77 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.78 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.79 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.80 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.81 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-2.82 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.83 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-2.84 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-2.85 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-2.86 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.87 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY y COLLATE NOCASE DESC,x,z
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.88 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.89 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-2.90 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.91 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-2.92 {
  execsql {
    SELECT x,y,z FROM t2
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT c,b,a FROM t1
    UNION SELECT a,b,c FROM t3
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT c,b,a FROM t1
    UNION SELECT a,b,c FROM t3
    ORDER BY y COLLATE NOCASE DESC,x,z
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-2.93 {
  execsql {
    SELECT upper((SELECT c FROM t1 UNION SELECT z FROM t2 ORDER BY 1));
  }
} {A}
do_test selectA-2.94 {
  execsql {
    SELECT lower((SELECT c FROM t1 UNION ALL SELECT z FROM t2 ORDER BY 1));
  }
} {a}
do_test selectA-2.95 {
  execsql {
    SELECT lower((SELECT c FROM t1 INTERSECT SELECT z FROM t2 ORDER BY 1));
  }
} {{}}
do_test selectA-2.96 {
  execsql {
    SELECT lower((SELECT z FROM t2 EXCEPT SELECT c FROM t1 ORDER BY 1));
  }
} {m}


do_test selectA-3.0 {
  execsql {
    CREATE UNIQUE INDEX t1a ON t1(a);
    CREATE UNIQUE INDEX t1b ON t1(b);
    CREATE UNIQUE INDEX t1c ON t1(c);
    CREATE UNIQUE INDEX t2x ON t2(x);
    CREATE UNIQUE INDEX t2y ON t2(y);
    CREATE UNIQUE INDEX t2z ON t2(z);
    SELECT name FROM sqlite_master WHERE type='index'
  }
} {t1a t1b t1c t2x t2y t2z}
do_test selectA-3.1 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.1.1 {  # Ticket #3314
  execsql {
    SELECT t1.a,b,t1.c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a,t1.b,t1.c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.2 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-3.3 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.4 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-3.5 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.6 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.7 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.8 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.9 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.10 {
  execsql {
    SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-3.11 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.12 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-3.13 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.14 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-3.15 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.16 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.17 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.18 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.19 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.20 {
  execsql {
    SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-3.21 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.22 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-3.23 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.24 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-3.25 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.26 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.27 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.28 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.29 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.30 {
  execsql {
    SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-3.31 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.32 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-3.33 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.34 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-3.35 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.36 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.37 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.38 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.39 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.40 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-3.41 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a,b,c
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-3.42 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a,b,c
  }
} {hello d D abc e e}
do_test selectA-3.43 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {hello d D abc e e}
do_test selectA-3.44 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a,b,c
  }
} {hello d D abc e e}
do_test selectA-3.45 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a,b,c
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-3.46 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a,b,c
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-3.47 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a DESC
  }
} {9.9 b B 1 a a {} C c}
do_test selectA-3.48 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY a DESC
  }
} {abc e e hello d D}
do_test selectA-3.49 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a DESC
  }
} {abc e e hello d D}
do_test selectA-3.50 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a DESC
  }
} {abc e e hello d D}
do_test selectA-3.51 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY a DESC
  }
} {9.9 b B 1 a a {} C c}
do_test selectA-3.52 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY a DESC
  }
} {9.9 b B 1 a a {} C c}
do_test selectA-3.53 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY b, a DESC
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-3.54 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY b
  }
} {hello d D abc e e}
do_test selectA-3.55 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY b DESC, c
  }
} {abc e e hello d D}
do_test selectA-3.56 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY b, c DESC, a
  }
} {hello d D abc e e}
do_test selectA-3.57 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY b COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.58 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY b
  }
} {{} C c 1 a a 9.9 b B}
do_test selectA-3.59 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY c, a DESC
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.60 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d'
    ORDER BY c
  }
} {hello d D abc e e}
do_test selectA-3.61 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY c COLLATE BINARY, b DESC, c, a, b, c, a, b, c
  }
} {hello d D abc e e}
do_test selectA-3.62 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY c DESC, a
  }
} {abc e e hello d D}
do_test selectA-3.63 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY c COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.64 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.65 {
  execsql {
    SELECT a,b,c FROM t3 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    ORDER BY c COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.66 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t3
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.67 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t3 WHERE b<'d'
    ORDER BY c DESC, a
  }
} {abc e e hello d D}
do_test selectA-3.68 {
  execsql {
    SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d'
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    ORDER BY c DESC, a
  }
} {abc e e hello d D}
do_test selectA-3.69 {
  execsql {
    SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d'
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    ORDER BY c COLLATE NOCASE
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.70 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.71 {
  execsql {
    SELECT a,b,c FROM t1 WHERE b<'d'
    INTERSECT SELECT a,b,c FROM t1
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT b,c,a FROM t3
    INTERSECT SELECT a,b,c FROM t1
    EXCEPT SELECT x,y,z FROM t2
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT y,x,z FROM t2
    INTERSECT SELECT a,b,c FROM t1
    EXCEPT SELECT c,b,a FROM t3
    ORDER BY c
  }
} {1 a a 9.9 b B {} C c}
do_test selectA-3.72 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.73 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-3.74 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.75 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-3.76 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.77 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY b COLLATE NOCASE DESC,a,c
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.78 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.79 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.80 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.81 {
  execsql {
    SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-3.82 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY a,b,c
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.83 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY a DESC,b,c
  }
} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u}
do_test selectA-3.84 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY a,c,b
  }
} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M}
do_test selectA-3.85 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY b,a,c
  }
} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M}
do_test selectA-3.86 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY b COLLATE NOCASE,a,c
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.87 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY y COLLATE NOCASE DESC,x,z
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.88 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c,b,a
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.89 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c,a,b
  }
} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z}
do_test selectA-3.90 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.91 {
  execsql {
    SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3
    ORDER BY c COLLATE BINARY DESC,a,b
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B}
do_test selectA-3.92 {
  execsql {
    SELECT x,y,z FROM t2
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT c,b,a FROM t1
    UNION SELECT a,b,c FROM t3
    INTERSECT SELECT a,b,c FROM t3
    EXCEPT SELECT c,b,a FROM t1
    UNION SELECT a,b,c FROM t3
    ORDER BY y COLLATE NOCASE DESC,x,z
  }
} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a}
do_test selectA-3.93 {
  execsql {
    SELECT upper((SELECT c FROM t1 UNION SELECT z FROM t2 ORDER BY 1));
  }
} {A}
do_test selectA-3.94 {
  execsql {
    SELECT lower((SELECT c FROM t1 UNION ALL SELECT z FROM t2 ORDER BY 1));
  }
} {a}
do_test selectA-3.95 {
  execsql {
    SELECT lower((SELECT c FROM t1 INTERSECT SELECT z FROM t2 ORDER BY 1));
  }
} {{}}
do_test selectA-3.96 {
  execsql {
    SELECT lower((SELECT z FROM t2 EXCEPT SELECT c FROM t1 ORDER BY 1));
  }
} {m}
do_test selectA-3.97 {
  execsql {
    SELECT upper((SELECT x FROM (
      SELECT x,y,z FROM t2
      INTERSECT SELECT a,b,c FROM t3
      EXCEPT SELECT c,b,a FROM t1
      UNION SELECT a,b,c FROM t3
      INTERSECT SELECT a,b,c FROM t3
      EXCEPT SELECT c,b,a FROM t1
      UNION SELECT a,b,c FROM t3
      ORDER BY y COLLATE NOCASE DESC,x,z)))
  }
} {MAD}

finish_test

Added test/selectB.test.



























































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# 2008 June 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# $Id: selectB.test,v 1.10 2009/04/02 16:59:47 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound {
  finish_test
  return
}

proc test_transform {testname sql1 sql2 results} {
  set ::vdbe1 [list]
  set ::vdbe2 [list]
  db eval "explain $sql1" { lappend ::vdbe1 $opcode }
  db eval "explain $sql2" { lappend ::vdbe2 $opcode }

  do_test $testname.transform {
    set ::vdbe1
  } $::vdbe2

  set ::sql1 $sql1
  do_test $testname.sql1 {
    execsql $::sql1
  } $results

  set ::sql2 $sql2
  do_test $testname.sql2 {
    execsql $::sql2
  } $results
}

do_test selectB-1.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(d, e, f);

    INSERT INTO t1 VALUES( 2,  4,  6);
    INSERT INTO t1 VALUES( 8, 10, 12);
    INSERT INTO t1 VALUES(14, 16, 18);

    INSERT INTO t2 VALUES(3,   6,  9);
    INSERT INTO t2 VALUES(12, 15, 18);
    INSERT INTO t2 VALUES(21, 24, 27);
  }
} {}

for {set ii 1} {$ii <= 2} {incr ii} {

  if {$ii == 2} {
    do_test selectB-2.1 {
      execsql {
        CREATE INDEX i1 ON t1(a);
        CREATE INDEX i2 ON t2(d);
      }
    } {}
  }

  test_transform selectB-$ii.2 {
    SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2
  } {2 8 14 3 12 21}
  
  test_transform selectB-$ii.3 {
    SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1
  } {2 3 8 12 14 21}
  
  test_transform selectB-$ii.4 {
    SELECT * FROM 
      (SELECT a FROM t1 UNION ALL SELECT d FROM t2) 
    WHERE a>10 ORDER BY 1
  } {
    SELECT a FROM t1 WHERE a>10 UNION ALL SELECT d FROM t2 WHERE d>10 ORDER BY 1
  } {12 14 21}
  
  test_transform selectB-$ii.5 {
    SELECT * FROM 
      (SELECT a FROM t1 UNION ALL SELECT d FROM t2) 
    WHERE a>10 ORDER BY a
  } {
    SELECT a FROM t1 WHERE a>10 
      UNION ALL 
    SELECT d FROM t2 WHERE d>10 
    ORDER BY a
  } {12 14 21}
  
  test_transform selectB-$ii.6 {
    SELECT * FROM 
      (SELECT a FROM t1 UNION ALL SELECT d FROM t2 WHERE d > 12) 
    WHERE a>10 ORDER BY a
  } {
    SELECT a FROM t1 WHERE a>10
      UNION ALL 
    SELECT d FROM t2 WHERE d>12 AND d>10
    ORDER BY a
  } {14 21}
  
  test_transform selectB-$ii.7 {
    SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1 
    LIMIT 2
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 2
  } {2 3}
  
  test_transform selectB-$ii.8 {
    SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1 
    LIMIT 2 OFFSET 3
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 2 OFFSET 3
  } {12 14}

  test_transform selectB-$ii.9 {
    SELECT * FROM (
      SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
    ) 
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
  } {2 8 14 3 12 21 6 12 18}
  
  test_transform selectB-$ii.10 {
    SELECT * FROM (
      SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
    ) ORDER BY 1
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
    ORDER BY 1
  } {2 3 6 8 12 12 14 18 21}
  
  test_transform selectB-$ii.11 {
    SELECT * FROM (
      SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
    ) WHERE a>=10 ORDER BY 1 LIMIT 3
  } {
    SELECT a FROM t1 WHERE a>=10 UNION ALL SELECT d FROM t2 WHERE d>=10
    UNION ALL SELECT c FROM t1 WHERE c>=10
    ORDER BY 1 LIMIT 3
  } {12 12 14}

  test_transform selectB-$ii.12 {
    SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 2)
  } {
    SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 2
  } {2 8}

  # An ORDER BY in a compound subqueries defeats flattening.  Ticket #3773
  # test_transform selectB-$ii.13 {
  #   SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a ASC)
  # } {
  #   SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 ASC
  # } {2 3 8 12 14 21}
  # 
  # test_transform selectB-$ii.14 {
  #  SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a DESC)
  # } {
  #  SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 DESC
  # } {21 14 12 8 3 2}
  #
  # test_transform selectB-$ii.14 {
  #   SELECT * FROM (
  #     SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a DESC
  #   ) LIMIT 2 OFFSET 2
  # } {
  #   SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 DESC
  #    LIMIT 2 OFFSET 2
  # } {12 8}
  #
  # test_transform selectB-$ii.15 {
  #   SELECT * FROM (
  #     SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY a ASC, e DESC
  #  )
  # } {
  #   SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY a ASC, e DESC
  # } {2 4 3 6 8 10 12 15 14 16 21 24}
}

do_test selectB-3.0 {
  execsql {
    DROP INDEX i1;
    DROP INDEX i2;
  }
} {}

for {set ii 3} {$ii <= 4} {incr ii} {

  if {$ii == 4} {
    do_test selectB-4.0 {
      execsql {
        CREATE INDEX i1 ON t1(a);
        CREATE INDEX i2 ON t1(b);
        CREATE INDEX i3 ON t1(c);
        CREATE INDEX i4 ON t2(d);
        CREATE INDEX i5 ON t2(e);
        CREATE INDEX i6 ON t2(f);
      }
    } {}
  }

  do_test selectB-$ii.1 {
    execsql {
      SELECT DISTINCT * FROM 
        (SELECT c FROM t1 UNION ALL SELECT e FROM t2) 
      ORDER BY 1;
    }
  } {6 12 15 18 24}
  
  do_test selectB-$ii.2 {
    execsql {
      SELECT c, count(*) FROM 
        (SELECT c FROM t1 UNION ALL SELECT e FROM t2) 
      GROUP BY c ORDER BY 1;
    }
  } {6 2 12 1 15 1 18 1 24 1}
  do_test selectB-$ii.3 {
    execsql {
      SELECT c, count(*) FROM 
        (SELECT c FROM t1 UNION ALL SELECT e FROM t2) 
      GROUP BY c HAVING count(*)>1;
    }
  } {6 2}
  do_test selectB-$ii.4 {
    execsql {
      SELECT t4.c, t3.a FROM 
        (SELECT c FROM t1 UNION ALL SELECT e FROM t2) AS t4, t1 AS t3
      WHERE t3.a=14
      ORDER BY 1
    }
  } {6 14 6 14 12 14 15 14 18 14 24 14}
  
  do_test selectB-$ii.5 {
    execsql {
      SELECT d FROM t2 
      EXCEPT 
      SELECT a FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
    }
  } {}
  do_test selectB-$ii.6 {
    execsql {
      SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
      EXCEPT 
      SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
    }
  } {}
  do_test selectB-$ii.7 {
    execsql {
      SELECT c FROM t1
      EXCEPT 
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
    }
  } {12}
  do_test selectB-$ii.8 {
    execsql {
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      EXCEPT 
      SELECT c FROM t1
    }
  } {9 15 24 27}
  do_test selectB-$ii.9 {
    execsql {
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      EXCEPT 
      SELECT c FROM t1
      ORDER BY c DESC
    }
  } {27 24 15 9}
  
  do_test selectB-$ii.10 {
    execsql {
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      UNION 
      SELECT c FROM t1
      ORDER BY c DESC
    }
  } {27 24 18 15 12 9 6}
  do_test selectB-$ii.11 {
    execsql {
      SELECT c FROM t1
      UNION 
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      ORDER BY c
    }
  } {6 9 12 15 18 24 27}
  do_test selectB-$ii.12 {
    execsql {
      SELECT c FROM t1 UNION SELECT e FROM t2 UNION ALL SELECT f FROM t2
      ORDER BY c
    }
  } {6 9 12 15 18 18 24 27}
  do_test selectB-$ii.13 {
    execsql {
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      UNION 
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      ORDER BY 1
    }
  } {6 9 15 18 24 27}
  
  do_test selectB-$ii.14 {
    execsql {
      SELECT c FROM t1
      INTERSECT 
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      ORDER BY 1
    }
  } {6 18}
  do_test selectB-$ii.15 {
    execsql {
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      INTERSECT 
      SELECT c FROM t1
      ORDER BY 1
    }
  } {6 18}
  do_test selectB-$ii.16 {
    execsql {
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      INTERSECT 
      SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
      ORDER BY 1
    }
  } {6 9 15 18 24 27}

  do_test selectB-$ii.17 {
    execsql {
      SELECT * FROM (
        SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 4
      ) LIMIT 2
    }
  } {2 8}

  do_test selectB-$ii.18 {
    execsql {
      SELECT * FROM (
        SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 4 OFFSET 2
      ) LIMIT 2
    }
  } {14 3}

  do_test selectB-$ii.19 {
    execsql {
      SELECT * FROM (
        SELECT DISTINCT (a/10) FROM t1 UNION ALL SELECT DISTINCT(d%2) FROM t2
      )
    }
  } {0 1 0 1}

  do_test selectB-$ii.20 {
    execsql {
      SELECT DISTINCT * FROM (
        SELECT DISTINCT (a/10) FROM t1 UNION ALL SELECT DISTINCT(d%2) FROM t2
      )
    }
  } {0 1}

  do_test selectB-$ii.21 {
    execsql {
      SELECT * FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) ORDER BY a+b
    }
  } {2 4 6 3 6 9 8 10 12 12 15 18 14 16 18 21 24 27}

  do_test selectB-$ii.21 {
    execsql {
      SELECT * FROM (SELECT 345 UNION ALL SELECT d FROM t2) ORDER BY 1;
    }
  } {3 12 21 345}
}

finish_test

Added test/selectC.test.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# 2008 September 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# $Id: selectC.test,v 1.5 2009/05/17 15:26:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Ticket #
do_test selectC-1.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    INSERT INTO t1 VALUES(1,'aaa','bbb');
    INSERT INTO t1 SELECT * FROM t1;
    INSERT INTO t1 VALUES(2,'ccc','ddd');

    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE y IN ('aaabbb','xxx');
  }
} {1 aaabbb}
do_test selectC-1.2 {
  execsql {
    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE b||c IN ('aaabbb','xxx');
  }
} {1 aaabbb}
do_test selectC-1.3 {
  execsql {
    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE y='aaabbb'
  }
} {1 aaabbb}
do_test selectC-1.4 {
  execsql {
    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE b||c='aaabbb'
  }
} {1 aaabbb}
do_test selectC-1.5 {
  execsql {
    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE x=2
  }
} {2 cccddd}
do_test selectC-1.6 {
  execsql {
    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE a=2
  }
} {2 cccddd}
do_test selectC-1.7 {
  execsql {
    SELECT DISTINCT a AS x, b||c AS y
      FROM t1
     WHERE +y='aaabbb'
  }
} {1 aaabbb}
do_test selectC-1.8 {
  execsql {
    SELECT a AS x, b||c AS y
      FROM t1
     GROUP BY x, y
    HAVING y='aaabbb'
  }
} {1 aaabbb}
do_test selectC-1.9 {
  execsql {
    SELECT a AS x, b||c AS y
      FROM t1
     GROUP BY x, y
    HAVING b||c='aaabbb'
  }
} {1 aaabbb}
do_test selectC-1.10 {
  execsql {
    SELECT a AS x, b||c AS y
      FROM t1
     WHERE y='aaabbb'
     GROUP BY x, y
  }
} {1 aaabbb}
do_test selectC-1.11 {
  execsql {
    SELECT a AS x, b||c AS y
      FROM t1
     WHERE b||c='aaabbb'
     GROUP BY x, y
  }
} {1 aaabbb}
proc longname_toupper x {return [string toupper $x]}
db function uppercaseconversionfunctionwithaverylongname longname_toupper
do_test selectC-1.12.1 {
  execsql {
    SELECT DISTINCT upper(b) AS x
      FROM t1
     ORDER BY x
  }
} {AAA CCC}
do_test selectC-1.12.2 {
  execsql {
    SELECT DISTINCT uppercaseconversionfunctionwithaverylongname(b) AS x
      FROM t1
     ORDER BY x
  }
} {AAA CCC}
do_test selectC-1.13.1 {
  execsql {
    SELECT upper(b) AS x
      FROM t1
     GROUP BY x
     ORDER BY x
  }
} {AAA CCC}
do_test selectC-1.13.2 {
  execsql {
    SELECT uppercaseconversionfunctionwithaverylongname(b) AS x
      FROM t1
     GROUP BY x
     ORDER BY x
  }
} {AAA CCC}
do_test selectC-1.14.1 {
  execsql {
    SELECT upper(b) AS x
      FROM t1
     ORDER BY x DESC
  }
} {CCC AAA AAA}
do_test selectC-1.14.2 {
  execsql {
    SELECT uppercaseconversionfunctionwithaverylongname(b) AS x
      FROM t1
     ORDER BY x DESC
  }
} {CCC AAA AAA}

# The following query used to leak memory.  Verify that has been fixed.
#
ifcapable trigger {
  do_test selectC-2.1 {
    catchsql {
      CREATE TABLE t21a(a,b);
      INSERT INTO t21a VALUES(1,2);
      CREATE TABLE t21b(n);
      CREATE TRIGGER r21 AFTER INSERT ON t21b BEGIN
        SELECT a FROM t21a WHERE a>new.x UNION ALL
        SELECT b FROM t21a WHERE b>new.x ORDER BY 1 LIMIT 2;
      END;
      INSERT INTO t21b VALUES(6);
    }
  } {1 {no such column: new.x}}
}

finish_test

Added test/server1.test.























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# 2006 January 09
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing the server mode of SQLite.
#
# This file is derived from thread1.test
#
# $Id: server1.test,v 1.5 2007/08/29 18:20:17 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Skip this whole file if the server testing code is not enabled
#
if {[llength [info command client_step]]==0 || [sqlite3 -has-codec]} {
  finish_test
  return
}

# The sample server implementation does not work right when memory
# management is enabled.
#
ifcapable memorymanage {
  finish_test
  return
}

# Create some data to work with
#
do_test server1-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,'abcdefgh');
    INSERT INTO t1 SELECT a+1, b||b FROM t1;
    INSERT INTO t1 SELECT a+2, b||b FROM t1;
    INSERT INTO t1 SELECT a+4, b||b FROM t1;
    SELECT count(*), max(length(b)) FROM t1;
  }
} {8 64}

# Interleave two threads on read access.  Then make sure a third
# thread can write the database.  In other words:
#
#    read-lock A
#    read-lock B
#    unlock A
#    unlock B
#    write-lock C
#
do_test server1-1.2 {
  client_create A test.db
  client_create B test.db
  client_create C test.db
  client_compile A {SELECT a FROM t1}
  client_step A
  client_result A
} SQLITE_ROW
do_test server1-1.3 {
  client_argc A
} 1
do_test server1-1.4 {
  client_argv A 0
} 1
do_test server1-1.5 {
  client_compile B {SELECT b FROM t1}
  client_step B
  client_result B
} SQLITE_ROW
do_test server1-1.6 {
  client_argc B
} 1
do_test server1-1.7 {
  client_argv B 0
} abcdefgh
do_test server1-1.8 {
  client_finalize A
  client_result A
} SQLITE_OK
do_test server1-1.9 {
  client_finalize B
  client_result B
} SQLITE_OK
do_test server1-1.10 {
  client_compile C {CREATE TABLE t2(x,y)}
  client_step C
  client_result C
} SQLITE_DONE
do_test server1-1.11 {
  client_finalize C
  client_result C
} SQLITE_OK
do_test server1-1.12 {
  catchsql {SELECT name FROM sqlite_master}
  execsql {SELECT name FROM sqlite_master}
} {t1 t2}


# Read from table t1.  Do not finalize the statement.  This
# will leave the lock pending.
#
do_test server1-2.1 {
  client_halt *
  client_create A test.db
  client_compile A {SELECT a FROM t1}
  client_step A
  client_result A
} SQLITE_ROW

# Read from the same table from another thread.  This is allows.
#
do_test server1-2.2 {
  client_create B test.db
  client_compile B {SELECT b FROM t1}
  client_step B
  client_result B
} SQLITE_ROW

# Write to a different table from another thread.  This is allowed
# because in server mode with a shared cache we have table-level locking.
#
do_test server1-2.3 {
  client_create C test.db
  client_compile C {INSERT INTO t2 VALUES(98,99)}
  client_step C
  client_result C
  client_finalize C
  client_result C
} SQLITE_OK

# But we cannot insert into table t1 because threads A and B have it locked.
#
do_test server1-2.4 {
  client_compile C {INSERT INTO t1 VALUES(98,99)}
  client_step C
  client_result C
  client_finalize C
  client_result C
} SQLITE_LOCKED
do_test server1-2.5 {
  client_finalize B
  client_wait B
  client_compile C {INSERT INTO t1 VALUES(98,99)}
  client_step C
  client_result C
  client_finalize C
  client_result C
} SQLITE_LOCKED

# Insert into t1 is successful after finishing the other two threads.
do_test server1-2.6 {
  client_finalize A
  client_wait A
  client_compile C {INSERT INTO t1 VALUES(98,99)}
  client_step C
  client_result C
  client_finalize C
  client_result C
} SQLITE_OK

client_halt *   
sqlite3_enable_shared_cache 0
finish_test

Added test/shared.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
# 2005 December 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: shared.test,v 1.36 2009/03/16 13:19:36 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close

# These tests cannot be run without the ATTACH command.
#
ifcapable !shared_cache||!attach {
  finish_test
  return
}

set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

foreach av [list 0 1] {

# Open the database connection and execute the auto-vacuum pragma
file delete -force test.db
sqlite3 db test.db

ifcapable autovacuum {
  do_test shared-[expr $av+1].1.0 {
    execsql "pragma auto_vacuum=$::av"
    execsql {pragma auto_vacuum}
  } "$av"
} else {
  if {$av} {
    db close
    break
  }
}

# if we're using proxy locks, we use 2 filedescriptors for a db
# that is open but NOT yet locked, after a lock is taken we'll have 3, 
# normally sqlite uses 1 (proxy locking adds the conch and the local lock)
set using_proxy 0
foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] {
  set using_proxy $value
}
set extrafds_prelock 0
set extrafds_postlock 0
if {$using_proxy>0} {
  set extrafds_prelock 1
  set extrafds_postlock 2
} 

# $av is currently 0 if this loop iteration is to test with auto-vacuum turned
# off, and 1 if it is turned on. Increment it so that (1 -> no auto-vacuum) 
# and (2 -> auto-vacuum). The sole reason for this is so that it looks nicer
# when we use this variable as part of test-case names.
#
incr av

# Test organization:
#
# shared-1.*: Simple test to verify basic sanity of table level locking when
#             two connections share a pager cache.
# shared-2.*: Test that a read transaction can co-exist with a 
#             write-transaction, including a simple test to ensure the 
#             external locking protocol is still working.
# shared-3.*: Simple test of read-uncommitted mode.
# shared-4.*: Check that the schema is locked and unlocked correctly.
# shared-5.*: Test that creating/dropping schema items works when databases
#             are attached in different orders to different handles.
# shared-6.*: Locking, UNION ALL queries and sub-queries.
# shared-7.*: Autovacuum and shared-cache.
# shared-8.*: Tests related to the text encoding of shared-cache databases.
# shared-9.*: TEMP triggers and shared-cache databases.
# shared-10.*: Tests of sqlite3_close().
# shared-11.*: Test transaction locking.
#

do_test shared-$av.1.1 {
  # Open a second database on the file test.db. It should use the same pager
  # cache and schema as the original connection. Verify that only 1 file is 
  # opened.
  sqlite3 db2 test.db
  set ::sqlite_open_file_count
  expr $sqlite_open_file_count-$extrafds_postlock
} {1}
do_test shared-$av.1.2 {
  # Add a table and a single row of data via the first connection. 
  # Ensure that the second connection can see them.
  execsql {
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
  } db
  execsql {
    SELECT * FROM abc;
  } db2
} {1 2 3}
do_test shared-$av.1.3 {
  # Have the first connection begin a transaction and obtain a read-lock
  # on table abc. This should not prevent the second connection from 
  # querying abc.
  execsql {
    BEGIN;
    SELECT * FROM abc;
  }
  execsql {
    SELECT * FROM abc;
  } db2
} {1 2 3}
do_test shared-$av.1.4 {
  # Try to insert a row into abc via connection 2. This should fail because
  # of the read-lock connection 1 is holding on table abc (obtained in the
  # previous test case).
  catchsql {
    INSERT INTO abc VALUES(4, 5, 6);
  } db2
} {1 {database table is locked: abc}}
do_test shared-$av.1.5 {
  # Using connection 2 (the one without the open transaction), try to create
  # a new table. This should fail because of the open read transaction 
  # held by connection 1.
  catchsql {
    CREATE TABLE def(d, e, f);
  } db2
} {1 {database table is locked: sqlite_master}}
do_test shared-$av.1.6 {
  # Upgrade connection 1's transaction to a write transaction. Create
  # a new table - def - and insert a row into it. Because the connection 1
  # transaction modifies the schema, it should not be possible for 
  # connection 2 to access the database at all until the connection 1 
  # has finished the transaction.
  execsql {
    CREATE TABLE def(d, e, f);
    INSERT INTO def VALUES('IV', 'V', 'VI');
  }
} {}
do_test shared-$av.1.7 {
  # Read from the sqlite_master table with connection 1 (inside the 
  # transaction). Then test that we can not do this with connection 2. This
  # is because of the schema-modified lock established by connection 1 
  # in the previous test case.
  execsql {
    SELECT * FROM sqlite_master;
  }
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {database schema is locked: main}}
do_test shared-$av.1.8 {
  # Commit the connection 1 transaction.
  execsql {
    COMMIT;
  }
} {}

do_test shared-$av.2.1 {
  # Open connection db3 to the database. Use a different path to the same
  # file so that db3 does *not* share the same pager cache as db and db2
  # (there should be two open file handles).
  if {$::tcl_platform(platform)=="unix"} {
    sqlite3 db3 ./test.db
  } else {
    sqlite3 db3 TEST.DB
  }
  set ::sqlite_open_file_count
  expr $sqlite_open_file_count-($extrafds_prelock+$extrafds_postlock)
} {2}
do_test shared-$av.2.2 {
  # Start read transactions on db and db2 (the shared pager cache). Ensure
  # db3 cannot write to the database.
  execsql {
    BEGIN;
    SELECT * FROM abc;
  }
  execsql {
    BEGIN;
    SELECT * FROM abc;
  } db2
  catchsql {
    INSERT INTO abc VALUES(1, 2, 3);
  } db2
} {1 {database table is locked: abc}}
do_test shared-$av.2.3 {
  # Turn db's transaction into a write-transaction. db3 should still be
  # able to read from table def (but will not see the new row). Connection
  # db2 should not be able to read def (because of the write-lock).

# Todo: The failed "INSERT INTO abc ..." statement in the above test
# has started a write-transaction on db2 (should this be so?). This 
# would prevent connection db from starting a write-transaction. So roll the
# db2 transaction back and replace it with a new read transaction.
  execsql {
    ROLLBACK;
    BEGIN;
    SELECT * FROM abc;
  } db2

  execsql {
    INSERT INTO def VALUES('VII', 'VIII', 'IX');
  }
  concat [
    catchsql { SELECT * FROM def; } db3
  ] [
    catchsql { SELECT * FROM def; } db2
  ]
} {0 {IV V VI} 1 {database table is locked: def}}
do_test shared-$av.2.4 {
  # Commit the open transaction on db. db2 still holds a read-transaction.
  # This should prevent db3 from writing to the database, but not from 
  # reading.
  execsql {
    COMMIT;
  }
  concat [
    catchsql { SELECT * FROM def; } db3
  ] [
    catchsql { INSERT INTO def VALUES('X', 'XI', 'XII'); } db3
  ]
} {0 {IV V VI VII VIII IX} 1 {database is locked}}

catchsql COMMIT db2

do_test shared-$av.3.1.1 {
  # This test case starts a linear scan of table 'seq' using a 
  # read-uncommitted connection. In the middle of the scan, rows are added
  # to the end of the seq table (ahead of the current cursor position).
  # The uncommitted rows should be included in the results of the scan.
  execsql "
    CREATE TABLE seq(i PRIMARY KEY, x);
    INSERT INTO seq VALUES(1, '[string repeat X 500]');
    INSERT INTO seq VALUES(2, '[string repeat X 500]');
  "
  execsql {SELECT * FROM sqlite_master} db2
  execsql {PRAGMA read_uncommitted = 1} db2

  set ret [list]
  db2 eval {SELECT i FROM seq ORDER BY i} {
    if {$i < 4} {
      set max [execsql {SELECT max(i) FROM seq}]
      db eval {
        INSERT INTO seq SELECT i + :max, x FROM seq;
      }
    }
    lappend ret $i
  }
  set ret
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16}
do_test shared-$av.3.1.2 {
  # Another linear scan through table seq using a read-uncommitted connection.
  # This time, delete each row as it is read. Should not affect the results of
  # the scan, but the table should be empty after the scan is concluded 
  # (test 3.1.3 verifies this).
  set ret [list]
  db2 eval {SELECT i FROM seq} {
    db eval {DELETE FROM seq WHERE i = :i}
    lappend ret $i
  }
  set ret
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16}
do_test shared-$av.3.1.3 {
  execsql {
    SELECT * FROM seq;
  }
} {}

catch {db close}
catch {db2 close}
catch {db3 close}

#--------------------------------------------------------------------------
# Tests shared-4.* test that the schema locking rules are applied 
# correctly. i.e.:
#
# 1. All transactions require a read-lock on the schemas of databases they
#    access.
# 2. Transactions that modify a database schema require a write-lock on that
#    schema.
# 3. It is not possible to compile a statement while another handle has a 
#    write-lock on the schema.
#

# Open two database handles db and db2. Each has a single attach database
# (as well as main):
#
#     db.main   ->   ./test.db
#     db.test2  ->   ./test2.db
#     db2.main  ->   ./test2.db
#     db2.test  ->   ./test.db
#
file delete -force test.db
file delete -force test2.db
file delete -force test2.db-journal
sqlite3 db  test.db
sqlite3 db2 test2.db
do_test shared-$av.4.1.1 {
  set sqlite_open_file_count
  expr $sqlite_open_file_count-($extrafds_prelock*2)
} {2}
do_test shared-$av.4.1.2 {
  execsql {ATTACH 'test2.db' AS test2}
  set sqlite_open_file_count
  expr $sqlite_open_file_count-($extrafds_postlock*2)
} {2}
do_test shared-$av.4.1.3 {
  execsql {ATTACH 'test.db' AS test} db2
  set sqlite_open_file_count
  expr $sqlite_open_file_count-($extrafds_postlock*2)
} {2}

# Sanity check: Create a table in ./test.db via handle db, and test that handle
# db2 can "see" the new table immediately. A handle using a seperate pager
# cache would have to reload the database schema before this were possible.
#
do_test shared-$av.4.2.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE TABLE def(d, e, f);
    INSERT INTO abc VALUES('i', 'ii', 'iii');
    INSERT INTO def VALUES('I', 'II', 'III');
  }
} {}
do_test shared-$av.4.2.2 {
  execsql {
    SELECT * FROM test.abc;
  } db2
} {i ii iii}

# Open a read-transaction and read from table abc via handle 2. Check that
# handle 1 can read table abc. Check that handle 1 cannot modify table abc
# or the database schema. Then check that handle 1 can modify table def.
#
do_test shared-$av.4.3.1 {
  execsql {
    BEGIN;
    SELECT * FROM test.abc;
  } db2
} {i ii iii}
do_test shared-$av.4.3.2 {
  catchsql {
    INSERT INTO abc VALUES('iv', 'v', 'vi');
  }
} {1 {database table is locked: abc}}
do_test shared-$av.4.3.3 {
  catchsql {
    CREATE TABLE ghi(g, h, i);
  }
} {1 {database table is locked: sqlite_master}}
do_test shared-$av.4.3.3 {
  catchsql {
    INSERT INTO def VALUES('IV', 'V', 'VI');
  }
} {0 {}}
do_test shared-$av.4.3.4 {
  # Cleanup: commit the transaction opened by db2.
  execsql {
    COMMIT
  } db2
} {}

# Open a write-transaction using handle 1 and modify the database schema.
# Then try to execute a compiled statement to read from the same 
# database via handle 2 (fails to get the lock on sqlite_master). Also
# try to compile a read of the same database using handle 2 (also fails).
# Finally, compile a read of the other database using handle 2. This
# should also fail.
#
ifcapable compound {
  do_test shared-$av.4.4.1.2 {
    # Sanity check 1: Check that the schema is what we think it is when viewed
    # via handle 1.
    execsql {
      CREATE TABLE test2.ghi(g, h, i);
      SELECT 'test.db:'||name FROM sqlite_master 
      UNION ALL
      SELECT 'test2.db:'||name FROM test2.sqlite_master;
    }
  } {test.db:abc test.db:def test2.db:ghi}
  do_test shared-$av.4.4.1.2 {
    # Sanity check 2: Check that the schema is what we think it is when viewed
    # via handle 2.
    execsql {
      SELECT 'test2.db:'||name FROM sqlite_master 
      UNION ALL
      SELECT 'test.db:'||name FROM test.sqlite_master;
    } db2
  } {test2.db:ghi test.db:abc test.db:def}
}

do_test shared-$av.4.4.2 {
  set ::DB2 [sqlite3_connection_pointer db2]
  set sql {SELECT * FROM abc}
  set ::STMT1 [sqlite3_prepare $::DB2 $sql -1 DUMMY]
  execsql {
    BEGIN;
    CREATE TABLE jkl(j, k, l);
  }
  sqlite3_step $::STMT1
} {SQLITE_ERROR}
do_test shared-$av.4.4.3 {
  sqlite3_finalize $::STMT1
} {SQLITE_LOCKED}
do_test shared-$av.4.4.4 {
  set rc [catch {
    set ::STMT1 [sqlite3_prepare $::DB2 $sql -1 DUMMY]
  } msg]
  list $rc $msg
} {1 {(6) database schema is locked: test}}
do_test shared-$av.4.4.5 {
  set rc [catch {
    set ::STMT1 [sqlite3_prepare $::DB2 "SELECT * FROM ghi" -1 DUMMY]
  } msg]
  list $rc $msg
} {1 {(6) database schema is locked: test}}


catch {db2 close}
catch {db close}

#--------------------------------------------------------------------------
# Tests shared-5.* 
#
foreach db [list test.db test1.db test2.db test3.db] {
  file delete -force $db ${db}-journal
}
do_test shared-$av.5.1.1 {
  sqlite3 db1 test.db
  sqlite3 db2 test.db
  execsql {
    ATTACH 'test1.db' AS test1;
    ATTACH 'test2.db' AS test2;
    ATTACH 'test3.db' AS test3;
  } db1
  execsql {
    ATTACH 'test3.db' AS test3;
    ATTACH 'test2.db' AS test2;
    ATTACH 'test1.db' AS test1;
  } db2
} {}
do_test shared-$av.5.1.2 {
  execsql {
    CREATE TABLE test1.t1(a, b);
    CREATE INDEX test1.i1 ON t1(a, b);
  } db1
} {}
ifcapable view {
  do_test shared-$av.5.1.3 {
    execsql {
      CREATE VIEW test1.v1 AS SELECT * FROM t1;
    } db1
  } {}
}
ifcapable trigger {
  do_test shared-$av.5.1.4 {
    execsql {
      CREATE TRIGGER test1.trig1 AFTER INSERT ON t1 BEGIN
        INSERT INTO t1 VALUES(new.a, new.b);
      END;
    } db1
  } {}
}
do_test shared-$av.5.1.5 {
  execsql {
    DROP INDEX i1;
  } db2
} {}
ifcapable view {
  do_test shared-$av.5.1.6 {
    execsql {
      DROP VIEW v1;
    } db2
  } {}
}
ifcapable trigger {
  do_test shared-$av.5.1.7 {
    execsql {
      DROP TRIGGER trig1;
    } db2
  } {}
}
do_test shared-$av.5.1.8 {
  execsql {
    DROP TABLE t1;
  } db2
} {}
ifcapable compound {
  do_test shared-$av.5.1.9 {
    execsql {
      SELECT * FROM sqlite_master UNION ALL SELECT * FROM test1.sqlite_master
    } db1
  } {}
}

#--------------------------------------------------------------------------
# Tests shared-6.* test that a query obtains all the read-locks it needs
# before starting execution of the query. This means that there is no chance
# some rows of data will be returned before a lock fails and SQLITE_LOCK
# is returned.
#
do_test shared-$av.6.1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(a, b);
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t2 VALUES(3, 4);
  } db1
} {}
ifcapable compound {
  do_test shared-$av.6.1.2 {
    execsql {
      SELECT * FROM t1 UNION ALL SELECT * FROM t2;
    } db2
  } {1 2 3 4}
}
do_test shared-$av.6.1.3 {
  # Establish a write lock on table t2 via connection db2. Then make a 
  # UNION all query using connection db1 that first accesses t1, followed 
  # by t2. If the locks are grabbed at the start of the statement (as 
  # they should be), no rows are returned. If (as was previously the case)
  # they are grabbed as the tables are accessed, the t1 rows will be 
  # returned before the query fails.
  #
  execsql {
    BEGIN;
    INSERT INTO t2 VALUES(5, 6);
  } db2
  set ret [list]
  catch {
    db1 eval {SELECT * FROM t1 UNION ALL SELECT * FROM t2} {
      lappend ret $a $b
    }
  }
  set ret
} {}
do_test shared-$av.6.1.4 {
  execsql {
    COMMIT;
    BEGIN;
    INSERT INTO t1 VALUES(7, 8);
  } db2
  set ret [list]
  catch {
    db1 eval {
      SELECT (CASE WHEN a>4 THEN (SELECT a FROM t1) ELSE 0 END) AS d FROM t2;
    } {
      lappend ret $d
    }
  }
  set ret
} {}

catch {db1 close}
catch {db2 close}
foreach f [list test.db test2.db] {
  file delete -force $f ${f}-journal
}

#--------------------------------------------------------------------------
# Tests shared-7.* test auto-vacuum does not invalidate cursors from
# other shared-cache users when it reorganizes the database on 
# COMMIT.
#
do_test shared-$av.7.1 {
  # This test case sets up a test database in auto-vacuum mode consisting 
  # of two tables, t1 and t2. Both have a single index. Table t1 is 
  # populated first (so consists of pages toward the start of the db file), 
  # t2 second (pages toward the end of the file). 
  sqlite3 db test.db
  sqlite3 db2 test.db
  execsql {
    BEGIN;
    CREATE TABLE t1(a PRIMARY KEY, b);
    CREATE TABLE t2(a PRIMARY KEY, b);
  }
  set ::contents {}
  for {set i 0} {$i < 100} {incr i} {
    set a [string repeat "$i " 20]
    set b [string repeat "$i " 20]
    db eval {
      INSERT INTO t1 VALUES(:a, :b);
    }
    lappend ::contents [list [expr $i+1] $a $b]
  }
  execsql {
    INSERT INTO t2 SELECT * FROM t1;
    COMMIT;
  }
} {}
do_test shared-$av.7.2 {
  # This test case deletes the contents of table t1 (the one at the start of
  # the file) while many cursors are open on table t2 and its index. All of
  # the non-root pages will be moved from the end to the start of the file
  # when the DELETE is committed - this test verifies that moving the pages
  # does not disturb the open cursors.
  #

  proc lockrow {db tbl oids body} {
    set ret [list]
    db eval "SELECT oid AS i, a, b FROM $tbl ORDER BY a" {
      if {$i==[lindex $oids 0]} {
        set noids [lrange $oids 1 end]
        if {[llength $noids]==0} {
          set subret [eval $body]
        } else {
          set subret [lockrow $db $tbl $noids $body]
        }
      }
      lappend ret [list $i $a $b]
    }
    return [linsert $subret 0 $ret]
  }
  proc locktblrows {db tbl body} {
    set oids [db eval "SELECT oid FROM $tbl"]
    lockrow $db $tbl $oids $body
  }

  set scans [locktblrows db t2 {
    execsql {
      DELETE FROM t1;
    } db2
  }]
  set error 0

  # Test that each SELECT query returned the expected contents of t2.
  foreach s $scans {
    if {[lsort -integer -index 0 $s]!=$::contents} {
      set error 1
    }
  }
  set error
} {0}

catch {db close}
catch {db2 close}
unset -nocomplain contents

#--------------------------------------------------------------------------
# The following tests try to trick the shared-cache code into assuming
# the wrong encoding for a database.
#
file delete -force test.db test.db-journal
ifcapable utf16 {
  do_test shared-$av.8.1.1 {
    sqlite3 db test.db
    execsql {
      PRAGMA encoding = 'UTF-16';
      SELECT * FROM sqlite_master;
    }
  } {}
  do_test shared-$av.8.1.2 {
    string range [execsql {PRAGMA encoding;}] 0 end-2
  } {UTF-16}

  do_test shared-$av.8.1.3 {
    sqlite3 db2 test.db
    execsql {
      PRAGMA encoding = 'UTF-8';
      CREATE TABLE abc(a, b, c);
    } db2
  } {}
  do_test shared-$av.8.1.4 {
    execsql {
      SELECT * FROM sqlite_master;
    }
  } "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}"
  do_test shared-$av.8.1.5 {
    db2 close
    execsql {
      PRAGMA encoding;
    }
  } {UTF-8}

  file delete -force test2.db test2.db-journal
  do_test shared-$av.8.2.1 {
    execsql {
      ATTACH 'test2.db' AS aux;
      SELECT * FROM aux.sqlite_master;
    }
  } {}
  do_test shared-$av.8.2.2 {
    sqlite3 db2 test2.db
    execsql {
      PRAGMA encoding = 'UTF-16';
      CREATE TABLE def(d, e, f);
    } db2
    string range [execsql {PRAGMA encoding;} db2] 0 end-2
  } {UTF-16}

  catch {db close}
  catch {db2 close}
  file delete -force test.db test2.db

  do_test shared-$av.8.3.2 {
    sqlite3 db test.db
    execsql { CREATE TABLE def(d, e, f) }
    execsql { PRAGMA encoding }
  } {UTF-8}
  do_test shared-$av.8.3.3 {
    set zDb16 "[encoding convertto unicode test.db]\x00\x00"
    set db16 [sqlite3_open16 $zDb16 {}]

    set stmt [sqlite3_prepare $db16 "SELECT sql FROM sqlite_master" -1 DUMMY]
    sqlite3_step $stmt
    set sql [sqlite3_column_text $stmt 0]
    sqlite3_finalize $stmt
    set sql
  } {CREATE TABLE def(d, e, f)}
  do_test shared-$av.8.3.4 {
    set stmt [sqlite3_prepare $db16 "PRAGMA encoding" -1 DUMMY]
    sqlite3_step $stmt
    set enc [sqlite3_column_text $stmt 0]
    sqlite3_finalize $stmt
    set enc
  } {UTF-8}

  sqlite3_close $db16

# Bug #2547 is causing this to fail.
if 0 {
  do_test shared-$av.8.2.3 {
    catchsql {
      SELECT * FROM aux.sqlite_master;
    }
  } {1 {attached databases must use the same text encoding as main database}}
}
}

catch {db close}
catch {db2 close}
file delete -force test.db test2.db

#---------------------------------------------------------------------------
# The following tests - shared-9.* - test interactions between TEMP triggers
# and shared-schemas.
#
ifcapable trigger&&tempdb {

do_test shared-$av.9.1 {
  sqlite3 db test.db
  sqlite3 db2 test.db
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE TABLE abc_mirror(a, b, c);
    CREATE TEMP TRIGGER BEFORE INSERT ON abc BEGIN 
      INSERT INTO abc_mirror(a, b, c) VALUES(new.a, new.b, new.c);
    END;
    INSERT INTO abc VALUES(1, 2, 3);
    SELECT * FROM abc_mirror;
  }
} {1 2 3}
do_test shared-$av.9.2 {
  execsql {
    INSERT INTO abc VALUES(4, 5, 6);
    SELECT * FROM abc_mirror;
  } db2
} {1 2 3}
do_test shared-$av.9.3 {
  db close
  db2 close
} {}

} ; # End shared-9.*

#---------------------------------------------------------------------------
# The following tests - shared-10.* - test that the library behaves 
# correctly when a connection to a shared-cache is closed. 
#
do_test shared-$av.10.1 {
  # Create a small sample database with two connections to it (db and db2).
  file delete -force test.db
  sqlite3 db  test.db
  sqlite3 db2 test.db
  execsql {
    CREATE TABLE ab(a PRIMARY KEY, b);
    CREATE TABLE de(d PRIMARY KEY, e);
    INSERT INTO ab VALUES('Chiang Mai', 100000);
    INSERT INTO ab VALUES('Bangkok', 8000000);
    INSERT INTO de VALUES('Ubon', 120000);
    INSERT INTO de VALUES('Khon Kaen', 200000);
  }
} {}
do_test shared-$av.10.2 {
  # Open a read-transaction with the first connection, a write-transaction
  # with the second.
  execsql {
    BEGIN;
    SELECT * FROM ab;
  }
  execsql {
    BEGIN;
    INSERT INTO de VALUES('Pataya', 30000);
  } db2
} {}
do_test shared-$av.10.3 {
  # An external connection should be able to read the database, but not
  # prepare a write operation.
  if {$::tcl_platform(platform)=="unix"} {
    sqlite3 db3 ./test.db
  } else {
    sqlite3 db3 TEST.DB
  }
  execsql {
    SELECT * FROM ab;
  } db3
  catchsql {
    BEGIN;
    INSERT INTO de VALUES('Pataya', 30000);
  } db3
} {1 {database is locked}}
do_test shared-$av.10.4 {
  # Close the connection with the write-transaction open
  db2 close
} {}
do_test shared-$av.10.5 {
  # Test that the db2 transaction has been automatically rolled back.
  # If it has not the ('Pataya', 30000) entry will still be in the table.
  execsql {
    SELECT * FROM de;
  }
} {Ubon 120000 {Khon Kaen} 200000}
do_test shared-$av.10.5 {
  # Closing db2 should have dropped the shared-cache back to a read-lock.
  # So db3 should be able to prepare a write...
  catchsql {INSERT INTO de VALUES('Pataya', 30000);} db3
} {0 {}}
do_test shared-$av.10.6 {
  # ... but not commit it.
  catchsql {COMMIT} db3
} {1 {database is locked}}
do_test shared-$av.10.7 {
  # Commit the (read-only) db transaction. Check via db3 to make sure the 
  # contents of table "de" are still as they should be.
  execsql {
    COMMIT;
  }
  execsql {
    SELECT * FROM de;
  } db3
} {Ubon 120000 {Khon Kaen} 200000 Pataya 30000}
do_test shared-$av.10.9 {
  # Commit the external transaction.
  catchsql {COMMIT} db3
} {0 {}}
integrity_check shared-$av.10.10
do_test shared-$av.10.11 {
  db close
  db3 close
} {}

do_test shared-$av.11.1 {
  file delete -force test.db
  sqlite3 db  test.db
  sqlite3 db2 test.db
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE TABLE abc2(a, b, c);
    BEGIN;
    INSERT INTO abc VALUES(1, 2, 3);
  }
} {}
do_test shared-$av.11.2 {
  catchsql {BEGIN;} db2
  catchsql {SELECT * FROM abc;} db2
} {1 {database table is locked: abc}}
do_test shared-$av.11.3 {
  catchsql {BEGIN} db2
} {1 {cannot start a transaction within a transaction}}
do_test shared-$av.11.4 {
  catchsql {SELECT * FROM abc2;} db2
} {0 {}}
do_test shared-$av.11.5 {
  catchsql {INSERT INTO abc2 VALUES(1, 2, 3);} db2
} {1 {database table is locked}}
do_test shared-$av.11.6 {
  catchsql {SELECT * FROM abc2}
} {0 {}}
do_test shared-$av.11.6 {
  execsql {
    ROLLBACK;
    PRAGMA read_uncommitted = 1;
  } db2
} {}
do_test shared-$av.11.7 {
  execsql {
    INSERT INTO abc2 VALUES(4, 5, 6);
    INSERT INTO abc2 VALUES(7, 8, 9);
  }
} {}
do_test shared-$av.11.8 {
  set res [list]
  db2 eval {
    SELECT abc.a as I, abc2.a as II FROM abc, abc2;
  } {
    execsql {
      DELETE FROM abc WHERE 1;
    }
    lappend res $I $II
  }
  set res
} {1 4 {} 7}
if {[llength [info command sqlite3_shared_cache_report]]==1} {
  do_test shared-$av.11.9 {
    string tolower [sqlite3_shared_cache_report]
  } [string tolower [list [file nativename [file normalize test.db]] 2]]
}

do_test shared-$av.11.11 {
  db close
  db2 close
} {}

# This tests that if it is impossible to free any pages, SQLite will
# exceed the limit set by PRAGMA cache_size.
file delete -force test.db test.db-journal
sqlite3 db test.db 
ifcapable pager_pragmas {
  do_test shared-$av.12.1 {
    execsql {
      PRAGMA cache_size = 10;
      PRAGMA cache_size;
    }
  } {10}
}
do_test shared-$av.12.2 {
  set ::db_handles [list]
  for {set i 1} {$i < 15} {incr i} {
    lappend ::db_handles db$i
    sqlite3 db$i test.db 
    execsql "CREATE TABLE db${i}(a, b, c)" db$i 
    execsql "INSERT INTO db${i} VALUES(1, 2, 3)"
  }
} {}
proc nested_select {handles} {
  [lindex $handles 0] eval "SELECT * FROM [lindex $handles 0]" {
    lappend ::res $a $b $c
    if {[llength $handles]>1} {
      nested_select [lrange $handles 1 end]
    }
  }
}
do_test shared-$av.12.3 {
  set ::res [list]
  nested_select $::db_handles
  set ::res
} [string range [string repeat "1 2 3 " [llength $::db_handles]] 0 end-1]

do_test shared-$av.12.X {
  db close
  foreach h $::db_handles { 
    $h close
  }
} {}

# Internally, locks are acquired on shared B-Tree structures in the order
# that the structures appear in the virtual memory address space. This
# test case attempts to cause the order of the structures in memory 
# to be different from the order in which they are attached to a given
# database handle. This covers an extra line or two.
#
do_test shared-$av.13.1 {
  file delete -force test2.db test3.db test4.db test5.db
  sqlite3 db :memory:
  execsql {
    ATTACH 'test2.db' AS aux2;
    ATTACH 'test3.db' AS aux3;
    ATTACH 'test4.db' AS aux4;
    ATTACH 'test5.db' AS aux5;
    DETACH aux2;
    DETACH aux3;
    DETACH aux4;
    ATTACH 'test2.db' AS aux2;
    ATTACH 'test3.db' AS aux3;
    ATTACH 'test4.db' AS aux4;
  }
} {}
do_test shared-$av.13.2 {
  execsql {
    CREATE TABLE t1(a, b, c);
    CREATE TABLE aux2.t2(a, b, c);
    CREATE TABLE aux3.t3(a, b, c);
    CREATE TABLE aux4.t4(a, b, c);
    CREATE TABLE aux5.t5(a, b, c);
    SELECT count(*) FROM 
      aux2.sqlite_master, 
      aux3.sqlite_master, 
      aux4.sqlite_master, 
      aux5.sqlite_master
  }
} {1}
do_test shared-$av.13.3 {
  db close
} {}

# Test that nothing horrible happens if a connection to a shared B-Tree 
# structure is closed while some other connection has an open cursor.
#
do_test shared-$av.14.1 {
  sqlite3 db test.db
  sqlite3 db2 test.db
  execsql {SELECT name FROM sqlite_master}
} {db1 db2 db3 db4 db5 db6 db7 db8 db9 db10 db11 db12 db13 db14}
do_test shared-$av.14.2 {
  set res [list]
  db eval {SELECT name FROM sqlite_master} {
    if {$name eq "db7"} {
      db2 close
    }
    lappend res $name
  }
  set res
} {db1 db2 db3 db4 db5 db6 db7 db8 db9 db10 db11 db12 db13 db14}
do_test shared-$av.14.3 {
  db close
} {}

}

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shared2.test.





















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# 2005 January 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: shared2.test,v 1.8 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close

ifcapable !shared_cache {
  finish_test
  return
}
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

# Test that if we delete all rows from a table any read-uncommitted 
# cursors are correctly invalidated. Test on both table and index btrees.
do_test shared2-1.1 {
  sqlite3 db1 test.db
  sqlite3 db2 test.db

  # Set up some data. Table "numbers" has 64 rows after this block 
  # is executed.
  execsql {
    BEGIN;
    CREATE TABLE numbers(a PRIMARY KEY, b);
    INSERT INTO numbers(oid) VALUES(NULL);
    INSERT INTO numbers(oid) SELECT NULL FROM numbers;
    INSERT INTO numbers(oid) SELECT NULL FROM numbers;
    INSERT INTO numbers(oid) SELECT NULL FROM numbers;
    INSERT INTO numbers(oid) SELECT NULL FROM numbers;
    INSERT INTO numbers(oid) SELECT NULL FROM numbers;
    INSERT INTO numbers(oid) SELECT NULL FROM numbers;
    UPDATE numbers set a = oid, b = 'abcdefghijklmnopqrstuvwxyz0123456789';
    COMMIT;
  } db1
} {}
do_test shared2-1.2 {
  # Put connection 2 in read-uncommitted mode and start a SELECT on table 
  # 'numbers'. Half way through the SELECT, use connection 1 to delete the
  # contents of this table.
  execsql {
    pragma read_uncommitted = 1;
  } db2
  set count [execsql {SELECT count(*) FROM numbers} db2]
  db2 eval {SELECT a FROM numbers ORDER BY oid} {
    if {$a==32} {
      execsql {
        BEGIN;
        DELETE FROM numbers;
      } db1
    }
  }
  list $a $count
} {32 64}
do_test shared2-1.3 {
  # Same test as 1.2, except scan using the index this time.
  execsql {
    ROLLBACK;
  } db1
  set count [execsql {SELECT count(*) FROM numbers} db2]
  db2 eval {SELECT a, b FROM numbers ORDER BY a} {
    if {$a==32} {
      execsql {
        DELETE FROM numbers;
      } db1
    }
  }
  list $a $count
} {32 64}

#---------------------------------------------------------------------------
# These tests, shared2.2.*, test the outcome when data is added to or 
# removed from a table due to a rollback while a read-uncommitted 
# cursor is scanning it.
#
do_test shared2-2.1 {
  execsql {
    INSERT INTO numbers VALUES(1, 'Medium length text field');
    INSERT INTO numbers VALUES(2, 'Medium length text field');
    INSERT INTO numbers VALUES(3, 'Medium length text field');
    INSERT INTO numbers VALUES(4, 'Medium length text field');
    BEGIN;
    DELETE FROM numbers WHERE (a%2)=0;
  } db1
  set res [list]
  db2 eval {
    SELECT a FROM numbers ORDER BY a;
  } {
    lappend res $a
    if {$a==3} {
      execsql {ROLLBACK} db1
    }
  }
  set res
} {1 3 4}
do_test shared2-2.2 {
  execsql {
    BEGIN;
    INSERT INTO numbers VALUES(5, 'Medium length text field');
    INSERT INTO numbers VALUES(6, 'Medium length text field');
  } db1
  set res [list]
  db2 eval {
    SELECT a FROM numbers ORDER BY a;
  } {
    lappend res $a
    if {$a==5} {
      execsql {ROLLBACK} db1
    }
  }
  set res
} {1 2 3 4 5}

db1 close
db2 close

do_test shared2-3.2 {
  sqlite3_enable_shared_cache 1
} {1}

file delete -force test.db

sqlite3 db test.db
do_test shared2-4.1 {
  execsql {
    CREATE TABLE t0(a, b);
    CREATE TABLE t1(a, b DEFAULT 'hello world');
  }
} {}
db close

sqlite3 db test.db
sqlite3 db2 test.db

do_test shared2-4.2 {
  execsql { SELECT a, b FROM t0 } db
  execsql { INSERT INTO t1(a) VALUES(1) } db2
} {}

do_test shared2-4.3 {
  db2 close
  db close
} {}

# At one point, this was causing a crash.
#
do_test shared2-5.1 {
  sqlite3 db test.db
  sqlite3 db2 test.db
  execsql { CREATE TABLE t2(a, b, c) }
  
  # The following statement would crash when attempting to sqlite3_free()
  # a pointer allocated from a lookaside buffer.
  execsql { CREATE INDEX i1 ON t2(a) } db2
} {}

db close
db2 close

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shared3.test.























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# 2005 January 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: shared3.test,v 1.4 2008/08/20 14:49:25 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close

ifcapable !shared_cache {
  finish_test
  return
}
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

# Ticket #1824
#
do_test shared3-1.1 {
  file delete -force test.db test.db-journal
  sqlite3 db1 test.db
  db1 eval {
    PRAGMA encoding=UTF16;
    CREATE TABLE t1(x,y);
    INSERT INTO t1 VALUES('abc','This is a test string');
  }
  db1 close
  sqlite3 db1 test.db
  db1 eval {SELECT * FROM t1}
} {abc {This is a test string}}
do_test shared3-1.2 {
  sqlite3 db2 test.db
  db2 eval {SELECT y FROM t1 WHERE x='abc'}
} {{This is a test string}}

db1 close
db2 close

do_test shared3-2.1 {
  sqlite3 db1 test.db
  execsql {
    PRAGMA main.cache_size = 10;
  } db1
} {}
do_test shared3-2.2 {
  execsql { PRAGMA main.cache_size } db1
} {10}
do_test shared3-2.3 {
  sqlite3 db2 test.db
  execsql { PRAGMA main.cache_size } db1
} {10}
do_test shared3-2.4 {
  execsql { PRAGMA main.cache_size } db2
} {10}
do_test shared3-2.5 {
  execsql { PRAGMA main.cache_size } db1
} {10}

# The cache-size should now be 10 pages. However at one point there was
# a bug that caused the cache size to return to the default value when
# a second connection was opened on the shared-cache (as happened in
# test case shared3-2.3 above). The goal of the following tests is to
# ensure that the cache-size really is 10 pages.
#
if {$::tcl_platform(platform)=="unix"} {
  set alternative_name ./test.db
} else {
  set alternative_name TEST.DB
}
do_test shared3-2.6 {
  sqlite3 db3 $alternative_name
  catchsql {select count(*) from sqlite_master} db3
} {0 1}
do_test shared3-2.7 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(10, randomblob(5000))
  } db1
  catchsql {select count(*) from sqlite_master} db3
} {0 1}
do_test shared3-2.8 {
  db3 close
  execsql {
    INSERT INTO t1 VALUES(10, randomblob(10000))
  } db1
  sqlite3 db3 $alternative_name

  # If the pager-cache is really still limited to 10 pages, then the INSERT
  # statement above should have caused the pager to grab an exclusive lock
  # on the database file so that the cache could be spilled.
  #
  catchsql {select count(*) from sqlite_master} db3
} {1 {database is locked}}

db1 close
db2 close
db3 close

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shared4.test.



























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# 2008 July 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test the btree mutex protocol for shared cache mode.
#
# $Id: shared4.test,v 1.2 2008/08/04 03:51:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close
puts hello

# This script is only valid if we are running shared-cache mode in a
# threadsafe-capable database engine.
#
ifcapable !shared_cache||!compound {
  finish_test
  return
}
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

# Prepare multiple databases in shared cache mode.
#
do_test shared4-1.1 {
  file delete -force test1.db test1.db-journal
  file delete -force test2.db test2.db-journal
  file delete -force test3.db test3.db-journal
  file delete -force test4.db test4.db-journal
  sqlite3 db1 test1.db
  sqlite3 db2 test2.db
  sqlite3 db3 test3.db
  sqlite3 db4 test4.db
  db1 eval {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(111);
  }
  db2 eval {
    CREATE TABLE t2(b);
    INSERT INTO t2 VALUES(222);
  }
  db3 eval {
    CREATE TABLE t3(c);
    INSERT INTO t3 VALUES(333);
  }
  db4 eval {
    CREATE TABLE t4(d);
    INSERT INTO t4 VALUES(444);
  }
  db1 eval {
    ATTACH DATABASE 'test2.db' AS two;
    ATTACH DATABASE 'test3.db' AS three;
    ATTACH DATABASE 'test4.db' AS four;
  }
  db2 eval {
    ATTACH DATABASE 'test4.db' AS four;
    ATTACH DATABASE 'test3.db' AS three;
    ATTACH DATABASE 'test1.db' AS one;
  }
  db3 eval {
    ATTACH DATABASE 'test1.db' AS one;
    ATTACH DATABASE 'test2.db' AS two;
    ATTACH DATABASE 'test4.db' AS four;
  }
  db4 eval {
    ATTACH DATABASE 'test3.db' AS three;
    ATTACH DATABASE 'test2.db' AS two;
    ATTACH DATABASE 'test1.db' AS one;
  }
  db1 eval {
     SELECT a FROM t1 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT d FROM t4;
  }
} {111 222 333 444}
do_test shared4-1.2 {
  db2 eval {
     SELECT a FROM t1 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT c FROM t3;
  }
} {111 222 444 333}
do_test shared4-1.3 {
  db3 eval {
     SELECT a FROM t1 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT d FROM t4;
  }
} {111 333 222 444}
do_test shared4-1.4 {
  db4 eval {
     SELECT a FROM t1 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT b FROM t2;
  }
} {111 333 444 222}
do_test shared4-1.5 {
  db3 eval {
     SELECT a FROM t1 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT c FROM t3;
  }
} {111 444 222 333}
do_test shared4-1.6 {
  db4 eval {
     SELECT a FROM t1 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT b FROM t2;
  }
} {111 444 333 222}
do_test shared4-1.7 {
  db1 eval {
     SELECT b FROM t2 UNION ALL
     SELECT a FROM t1 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT d FROM t4;
  }
} {222 111 333 444}
do_test shared4-1.8 {
  db2 eval {
     SELECT b FROM t2 UNION ALL
     SELECT a FROM t1 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT c FROM t3;
  }
} {222 111 444 333}
do_test shared4-1.9 {
  db3 eval {
     SELECT b FROM t2 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT a FROM t1 UNION ALL
     SELECT d FROM t4;
  }
} {222 333 111 444}
do_test shared4-1.10 {
  db4 eval {
     SELECT b FROM t2 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT a FROM t1;
  }
} {222 333 444 111}
do_test shared4-1.11 {
  db1 eval {
     SELECT c FROM t3 UNION ALL
     SELECT a FROM t1 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT d FROM t4;
  }
} {333 111 222 444}
do_test shared4-1.12 {
  db2 eval {
     SELECT c FROM t3 UNION ALL
     SELECT a FROM t1 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT b FROM t2;
  }
} {333 111 444 222}

do_test shared4-2.1 {
  db1 eval {
    UPDATE t1 SET a=a+1000;
    UPDATE t2 SET b=b+2000;
    UPDATE t3 SET c=c+3000;
    UPDATE t4 SET d=d+4000;
  }
  db2 eval {
    UPDATE t1 SET a=a+10000;
    UPDATE t2 SET b=b+20000;
    UPDATE t3 SET c=c+30000;
    UPDATE t4 SET d=d+40000;
  }
  db3 eval {
    UPDATE t1 SET a=a+100000;
    UPDATE t2 SET b=b+200000;
    UPDATE t3 SET c=c+300000;
    UPDATE t4 SET d=d+400000;
  }
  db4 eval {
    UPDATE t1 SET a=a+1000000;
    UPDATE t2 SET b=b+2000000;
    UPDATE t3 SET c=c+3000000;
    UPDATE t4 SET d=d+4000000;
  }
  db1 eval {
     SELECT a FROM t1 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT d FROM t4;
  }
} {1111111 2222222 3333333 4444444}
do_test shared4-2.2 {
  db2 eval {
     SELECT a FROM t1 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT c FROM t3;
  }
} {1111111 2222222 4444444 3333333}
do_test shared4-2.3 {
  db3 eval {
     SELECT a FROM t1 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT b FROM t2 UNION ALL
     SELECT d FROM t4;
  }
} {1111111 3333333 2222222 4444444}
do_test shared4-2.4 {
  db4 eval {
     SELECT a FROM t1 UNION ALL
     SELECT c FROM t3 UNION ALL
     SELECT d FROM t4 UNION ALL
     SELECT b FROM t2;
  }
} {1111111 3333333 4444444 2222222}


db1 close
db2 close
db3 close
db4 close

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shared6.test.































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# 2009 April 01
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: shared6.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable !shared_cache { finish_test ; return }

do_test shared6-1.1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(c, d);
    CREATE TABLE t3(e, f);
  }
  db close
} {}
do_test shared6-1.1.2 {
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
  sqlite3_enable_shared_cache
} {1}

do_test shared6-1.1.3 {
  sqlite3 db1 test.db
  sqlite3 db2 test.db
} {}

# Exclusive shared-cache locks. Test the following:
#
#   1.2.1: If [db1] has an exclusive lock, [db2] cannot read.
#   1.2.2: If [db1] has an exclusive lock, [db1] can read.
#   1.2.3: If [db1] has a non-exclusive write-lock, [db2] can read.
# 
do_test shared6-1.2.1 {
  execsql { SELECT * FROM t1 } db2    ;# Cache a compiled statement
  execsql { BEGIN EXCLUSIVE } db1
  catchsql { SELECT * FROM t1 } db2   ;# Execute the cached compiled statement
} {1 {database table is locked}}
do_test shared6-1.2.2 {
  execsql { SELECT * FROM t1 } db1
} {}
do_test shared6-1.2.3 {
  execsql {
    COMMIT;
    BEGIN;
    INSERT INTO t2 VALUES(3, 4);
  } db1
  execsql { SELECT * FROM t1 } db2
} {}
do_test shared6-1.2.X {
  execsql { COMMIT } db1
} {}

# Regular shared-cache locks. Verify the following:
#
#   1.3.1: If [db1] has a write-lock on t1, [db1] can read from t1.
#   1.3.2: If [db1] has a write-lock on t1, [db2] can read from t2.
#   1.3.3: If [db1] has a write-lock on t1, [db2] cannot read from t1.
#   1.3.4: If [db1] has a write-lock on t1, [db2] cannot write to t1.
#   1.3.5: If [db1] has a read-lock on t1, [db2] can read from t1.
#   1.3.6: If [db1] has a read-lock on t1, [db2] cannot write to t1.
#
do_test shared6-1.3.1 {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(1, 2);
  } db1
  execsql { SELECT * FROM t1 } db1
} {1 2}
do_test shared6-1.3.2 {
  execsql { SELECT * FROM t2 } db2
} {3 4}
do_test shared6-1.3.3 {
  catchsql { SELECT * FROM t1 } db2
} {1 {database table is locked: t1}}
do_test shared6-1.3.4 {
  catchsql { INSERT INTO t2 VALUES(1, 2) } db2
} {1 {database table is locked}}
do_test shared6-1.3.5 {
  execsql {
    COMMIT;
    BEGIN;
    SELECT * FROM t1;
  } db1
  execsql { SELECT * FROM t1 } db2
} {1 2}
do_test shared6-1.3.5 {
  catchsql { INSERT INTO t1 VALUES(5, 6) } db2
} {1 {database table is locked: t1}}
do_test shared6-1.3.X {
  execsql { COMMIT } db1
} {}

# Read-uncommitted mode.
#
# For these tests, connection [db2] is in read-uncommitted mode.
#
#   1.4.1: If [db1] has a write-lock on t1, [db2] can still read from t1.
#   1.4.2: If [db1] has a write-lock on the db schema (sqlite_master table), 
#          [db2] cannot read from the schema.
#   1.4.3: If [db1] has a read-lock on t1, [db2] cannot write to t1.
#
do_test shared6-1.4.1 {
  execsql { PRAGMA read_uncommitted = 1 } db2
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(5, 6);
  } db1
  execsql { SELECT * FROM t1 } db2
} {1 2 5 6}
do_test shared6-1.4.2 {
  execsql { CREATE TABLE t4(a, b) } db1
  catchsql { SELECT * FROM t1 } db2
} {1 {database table is locked}}
do_test shared6-1.4.3 {
  execsql {
    COMMIT;
    BEGIN;
    SELECT * FROM t1;
  } db1
  catchsql { INSERT INTO t1 VALUES(7, 8) } db2
} {1 {database table is locked: t1}}

do_test shared6-1.X {
  db1 close
  db2 close
} {}

#-------------------------------------------------------------------------
# The following tests - shared6-2.* - test that two database connections
# that connect to the same file using different VFS implementations do
# not share a cache.
#
if {$::tcl_platform(platform) eq "unix"} {
  do_test shared6-2.1 {
    sqlite3 db1 test.db -vfs unix
    sqlite3 db2 test.db -vfs unix
    sqlite3 db3 test.db -vfs unix-none
    sqlite3 db4 test.db -vfs unix-none
  } {}

  do_test shared6-2.2 {
    execsql { BEGIN; INSERT INTO t1 VALUES(9, 10); } db1
    catchsql { SELECT * FROM t1 } db2
  } {1 {database table is locked: t1}}
  do_test shared6-2.3 {
    execsql { SELECT * FROM t1 } db3
  } {1 2 5 6}

  do_test shared6-2.3 {
    execsql { COMMIT } db1
    execsql { BEGIN; INSERT INTO t1 VALUES(11, 12); } db3
    catchsql { SELECT * FROM t1 } db4
  } {1 {database table is locked: t1}}

  do_test shared6-2.4 {
    execsql { SELECT * FROM t1 } db1
  } {1 2 5 6 9 10}

  do_test shared6-2.5 {
    execsql { COMMIT } db3
  } {}

  do_test shared6-2.X {
    db1 close
    db2 close
    db3 close
    db4 close
  } {}
}

#-------------------------------------------------------------------------
# Test that it is possible to open an exclusive transaction while 
# already holding a read-lock on the database file. And that it is
# not possible if some other connection holds such a lock.
#
do_test shared6-3.1 {
  sqlite3 db1 test.db
  sqlite3 db2 test.db
  sqlite3 db3 test.db
} {}
db1 eval {SELECT * FROM t1} {
  # Within this block [db1] is holding a read-lock on t1. Test that
  # this means t1 cannot be written by [db2].
  #
  do_test shared6-3.2 {
    catchsql { INSERT INTO t1 VALUES(1, 2) } db2
  } {1 {database table is locked: t1}}

  do_test shared6-3.3 {
    execsql { BEGIN EXCLUSIVE } db1
  } {}
  break
}
do_test shared6-3.4 {
  catchsql { SELECT * FROM t1 } db2
} {1 {database schema is locked: main}}
do_test shared6-3.5 {
  execsql COMMIT db1
} {}
db2 eval {SELECT * FROM t1} {
  do_test shared6-3.6 {
    catchsql { BEGIN EXCLUSIVE } db1
  } {1 {database table is locked}}
  break
}
do_test shared6-3.7 {
  execsql { BEGIN } db1
  execsql { BEGIN } db2
} {}
db2 eval {SELECT * FROM t1} {
  do_test shared6-3.8 {
    catchsql { INSERT INTO t1 VALUES(1, 2) } db1
  } {1 {database table is locked: t1}}
  break
}
do_test shared6-3.9 {
  execsql { BEGIN ; ROLLBACK } db3
} {}
do_test shared6-3.10 {
  catchsql { SELECT * FROM t1 } db3
} {1 {database table is locked}}
do_test shared6-3.X {
  db1 close
  db2 close
  db3 close
} {}

do_test shared6-4.1 {
  #file delete -force test.db test.db-journal
  sqlite3 db1 test.db
  sqlite3 db2 test.db

  set ::STMT [sqlite3_prepare_v2 db1 "SELECT * FROM t1" -1 DUMMY]
  execsql { CREATE TABLE t5(a, b) } db2
} {}
do_test shared6-4.2 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test shared6-4.X {
  
  db1 close
  db2 close
} {}

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shared7.test.















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 2009 April 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Make sure that attaching the same database multiple times in
# shared cache mode fails.
#
# $Id: shared7.test,v 1.1 2009/04/30 13:30:33 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable !shared_cache { finish_test ; return }

do_test shared7-1.1 {
  set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
  sqlite3_enable_shared_cache
} {1}

do_test shared7-1.2 {
  db close
  sqlite3 db test.db
  db eval {
    CREATE TABLE t1(x);
  }
  catchsql {
    ATTACH 'test.db' AS err1;
  }
} {1 {database is already attached}}

do_test shared7-1.3 {
  file delete -force test2.db test2.db-journal
  db eval {
    ATTACH 'test2.db' AS test2;
    CREATE TABLE test2.t2(y);
  }
  catchsql {
    ATTACH 'test2.db' AS err2;
  }
} {1 {database is already attached}}
do_test shared7-1.4 {
  catchsql {
    ATTACH 'test.db' AS err1;
  }
} {1 {database is already attached}}


sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shared_err.test.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# 2005 December 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# The focus of the tests in this file are IO errors that occur in a shared
# cache context. What happens to connection B if one connection A encounters
# an IO-error whilst reading or writing the file-system?
#
# $Id: shared_err.test,v 1.24 2008/10/12 00:27:54 shane Exp $

proc skip {args} {}


set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl
db close

ifcapable !shared_cache||!subquery {
  finish_test
  return
}

set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

do_ioerr_test shared_ioerr-1 -tclprep {
  sqlite3 db2 test.db
  execsql {
    PRAGMA read_uncommitted = 1;
    CREATE TABLE t1(a,b,c);
    BEGIN;
    SELECT * FROM sqlite_master;
  } db2
} -sqlbody {
  SELECT * FROM sqlite_master;
  INSERT INTO t1 VALUES(1,2,3);
  BEGIN TRANSACTION;
  INSERT INTO t1 VALUES(1,2,3);
  INSERT INTO t1 VALUES(4,5,6);
  ROLLBACK;
  SELECT * FROM t1;
  BEGIN TRANSACTION;
  INSERT INTO t1 VALUES(1,2,3);
  INSERT INTO t1 VALUES(4,5,6);
  COMMIT;
  SELECT * FROM t1;
  DELETE FROM t1 WHERE a<100;
} -cleanup {
  do_test shared_ioerr-1.$n.cleanup.1 {
    set res [catchsql {
      SELECT * FROM t1;
    } db2]
    set possible_results [list               \
      "1 {disk I/O error}"                   \
      "0 {1 2 3}"                            \
      "0 {1 2 3 1 2 3 4 5 6}"                \
      "0 {1 2 3 1 2 3 4 5 6 1 2 3 4 5 6}"    \
      "0 {}"                                 \
      "1 {database disk image is malformed}" \
    ]
    set rc [expr [lsearch -exact $possible_results $res] >= 0]
    if {$rc != 1} {
      puts ""
      puts "Result: $res"
    }
    set rc
  } {1}

  # The "database disk image is malformed" is a special case that can
  # occur if an IO error occurs during a rollback in the {SELECT * FROM t1}
  # statement above. This test is to make sure there is no real database
  # corruption.
  db2 close
  do_test shared_ioerr-1.$n.cleanup.2 {
    execsql {pragma integrity_check} db
  } {ok}
}

do_ioerr_test shared_ioerr-2 -tclprep {
  sqlite3 db2 test.db
  execsql {
    PRAGMA read_uncommitted = 1;
    BEGIN;
    CREATE TABLE t1(a, b);
    INSERT INTO t1(oid) VALUES(NULL);
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    INSERT INTO t1(oid) SELECT NULL FROM t1;
    UPDATE t1 set a = oid, b = 'abcdefghijklmnopqrstuvwxyz0123456789';
    CREATE INDEX i1 ON t1(a);
    COMMIT;
    BEGIN;
    SELECT * FROM sqlite_master;
  } db2
} -tclbody {
  set ::residx 0
  execsql {DELETE FROM t1 WHERE 0 = (a % 2);}
  incr ::residx

  # When this transaction begins the table contains 512 entries. The
  # two statements together add 512+146 more if it succeeds. 
  # (1024/7==146)
  execsql {BEGIN;}
  execsql {INSERT INTO t1 SELECT a+1, b FROM t1;}
  execsql {INSERT INTO t1 SELECT 'string' || a, b FROM t1 WHERE 0 = (a%7);}
  execsql {COMMIT;}

  incr ::residx
} -cleanup {
  catchsql ROLLBACK
  do_test shared_ioerr-2.$n.cleanup.1 {
    set res [catchsql {
      SELECT max(a), min(a), count(*) FROM (SELECT a FROM t1 order by a);
    } db2]
    set possible_results [list \
      {0 {1024 1 1024}}        \
      {0 {1023 1 512}}         \
      {0 {string994 1 1170}}   \
    ]
    set idx [lsearch -exact $possible_results $res]
    set success [expr {$idx==$::residx || $res=="1 {disk I/O error}"}]
    if {!$success} {
      puts ""
      puts "Result: \"$res\" ($::residx)"
    }
    set success
  } {1}
  db2 close
}

# This test is designed to provoke an IO error when a cursor position is
# "saved" (because another cursor is going to modify the underlying table). 
# 
do_ioerr_test shared_ioerr-3 -tclprep {
  sqlite3 db2 test.db
  execsql {
    PRAGMA read_uncommitted = 1;
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE t1(a, b, UNIQUE(a, b));
  } db2
  for {set i 0} {$i < 200} {incr i} {
    set a [string range [string repeat "[format %03d $i]." 5] 0 end-1]

    set b [string repeat $i 2000]
    execsql {INSERT INTO t1 VALUES($a, $b)} db2
  }
  execsql {COMMIT} db2
  set ::DB2 [sqlite3_connection_pointer db2]
  set ::STMT [sqlite3_prepare $::DB2 "SELECT a FROM t1 ORDER BY a" -1 DUMMY]
  sqlite3_step $::STMT       ;# Cursor points at 000.000.000.000
  sqlite3_step $::STMT       ;# Cursor points at 001.001.001.001

} -tclbody {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES('201.201.201.201.201', NULL);
    UPDATE t1 SET a = '202.202.202.202.202' WHERE a LIKE '201%';
    COMMIT;
  }
} -cleanup {
  set ::steprc  [sqlite3_step $::STMT]
  set ::column  [sqlite3_column_text $::STMT 0]
  set ::finalrc [sqlite3_finalize $::STMT]

  # There are three possible outcomes here (assuming persistent IO errors):
  #
  # 1. If the [sqlite3_step] did not require any IO (required pages in
  #    the cache), then the next row ("002...") may be retrieved 
  #    successfully.
  #
  # 2. If the [sqlite3_step] does require IO, then [sqlite3_step] returns
  #    SQLITE_ERROR and [sqlite3_finalize] returns IOERR.
  #
  # 3. If, after the initial IO error, SQLite tried to rollback the
  #    active transaction and a second IO error was encountered, then
  #    statement $::STMT will have been aborted. This means [sqlite3_stmt]
  #    returns SQLITE_ABORT, and the statement cursor does not move. i.e.
  #    [sqlite3_column] still returns the current row ("001...") and
  #    [sqlite3_finalize] returns SQLITE_OK.
  #

  do_test shared_ioerr-3.$n.cleanup.1 {
    expr {
      $::steprc eq "SQLITE_ROW" || 
      $::steprc eq "SQLITE_ERROR" ||
      $::steprc eq "SQLITE_ABORT" 
    }
  } {1}
  do_test shared_ioerr-3.$n.cleanup.2 {
    expr {
      ($::steprc eq "SQLITE_ROW" && $::column eq "002.002.002.002.002") ||
      ($::steprc eq "SQLITE_ERROR" && $::column eq "") ||
      ($::steprc eq "SQLITE_ABORT" && $::column eq "001.001.001.001.001") 
    }
  } {1}
  do_test shared_ioerr-3.$n.cleanup.3 {
    expr {
      ($::steprc eq "SQLITE_ROW" && $::finalrc eq "SQLITE_OK") ||
      ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_IOERR") ||
      ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_ABORT")
    }
  } {1}

# db2 eval {select * from sqlite_master}
  db2 close
}

# This is a repeat of the previous test except that this time we
# are doing a reverse-order scan of the table when the cursor is
# "saved".
# 
do_ioerr_test shared_ioerr-3rev -tclprep {
  sqlite3 db2 test.db
  execsql {
    PRAGMA read_uncommitted = 1;
    PRAGMA cache_size = 10;
    BEGIN;
    CREATE TABLE t1(a, b, UNIQUE(a, b));
  } db2
  for {set i 0} {$i < 200} {incr i} {
    set a [string range [string repeat "[format %03d $i]." 5] 0 end-1]

    set b [string repeat $i 2000]
    execsql {INSERT INTO t1 VALUES($a, $b)} db2
  }
  execsql {COMMIT} db2
  set ::DB2 [sqlite3_connection_pointer db2]
  set ::STMT [sqlite3_prepare $::DB2 \
           "SELECT a FROM t1 ORDER BY a DESC" -1 DUMMY]
  sqlite3_step $::STMT       ;# Cursor points at 199.199.199.199.199
  sqlite3_step $::STMT       ;# Cursor points at 198.198.198.198.198

} -tclbody {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES('201.201.201.201.201', NULL);
    UPDATE t1 SET a = '202.202.202.202.202' WHERE a LIKE '201%';
    COMMIT;
  }
} -cleanup {
  set ::steprc  [sqlite3_step $::STMT]
  set ::column  [sqlite3_column_text $::STMT 0]
  set ::finalrc [sqlite3_finalize $::STMT]

  # There are three possible outcomes here (assuming persistent IO errors):
  #
  # 1. If the [sqlite3_step] did not require any IO (required pages in
  #    the cache), then the next row ("002...") may be retrieved 
  #    successfully.
  #
  # 2. If the [sqlite3_step] does require IO, then [sqlite3_step] returns
  #    SQLITE_ERROR and [sqlite3_finalize] returns IOERR.
  #
  # 3. If, after the initial IO error, SQLite tried to rollback the
  #    active transaction and a second IO error was encountered, then
  #    statement $::STMT will have been aborted. This means [sqlite3_stmt]
  #    returns SQLITE_ABORT, and the statement cursor does not move. i.e.
  #    [sqlite3_column] still returns the current row ("001...") and
  #    [sqlite3_finalize] returns SQLITE_OK.
  #

  do_test shared_ioerr-3rev.$n.cleanup.1 {
    expr {
      $::steprc eq "SQLITE_ROW" || 
      $::steprc eq "SQLITE_ERROR" ||
      $::steprc eq "SQLITE_ABORT" 
    }
  } {1}
  do_test shared_ioerr-3rev.$n.cleanup.2 {
    expr {
      ($::steprc eq "SQLITE_ROW" && $::column eq "197.197.197.197.197") ||
      ($::steprc eq "SQLITE_ERROR" && $::column eq "") ||
      ($::steprc eq "SQLITE_ABORT" && $::column eq "198.198.198.198.198") 
    }
  } {1}
  do_test shared_ioerr-3rev.$n.cleanup.3 {
    expr {
      ($::steprc eq "SQLITE_ROW" && $::finalrc eq "SQLITE_OK") ||
      ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_IOERR") ||
      ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_ABORT")
    }
  } {1}

# db2 eval {select * from sqlite_master}
  db2 close
}

# Provoke a malloc() failure when a cursor position is being saved. This
# only happens with index cursors (because they malloc() space to save the
# current key value). It does not happen with tables, because an integer
# key does not require a malloc() to store. 
#
# The library should return an SQLITE_NOMEM to the caller. The query that
# owns the cursor (the one for which the position is not saved) should
# continue unaffected.
# 
do_malloc_test shared_err-4 -tclprep {
  sqlite3 db2 test.db
  execsql {
    PRAGMA read_uncommitted = 1;
    BEGIN;
    CREATE TABLE t1(a, b, UNIQUE(a, b));
  } db2
  for {set i 0} {$i < 5} {incr i} {
    set a [string repeat $i 10]
    set b [string repeat $i 2000]
    execsql {INSERT INTO t1 VALUES($a, $b)} db2
  }
  execsql {COMMIT} db2
  set ::DB2 [sqlite3_connection_pointer db2]
  set ::STMT [sqlite3_prepare $::DB2 "SELECT a FROM t1 ORDER BY a" -1 DUMMY]
  sqlite3_step $::STMT       ;# Cursor points at 0000000000
  sqlite3_step $::STMT       ;# Cursor points at 1111111111
} -tclbody {
  execsql {
    INSERT INTO t1 VALUES(6, NULL);
  }
} -cleanup {
  do_test shared_malloc-4.$::n.cleanup.1 {
    set ::rc [sqlite3_step $::STMT]
    expr {$::rc=="SQLITE_ROW" || $::rc=="SQLITE_ERROR"}
  } {1}
  if {$::rc=="SQLITE_ROW"} {
    do_test shared_malloc-4.$::n.cleanup.2 {
      sqlite3_column_text $::STMT 0
    } {2222222222}
  }
  do_test shared_malloc-4.$::n.cleanup.3 {
   set rc [sqlite3_finalize $::STMT]
   expr {$rc=="SQLITE_OK" || $rc=="SQLITE_ABORT" ||
         $rc=="SQLITE_NOMEM" || $rc=="SQLITE_IOERR"}
  } {1}
# db2 eval {select * from sqlite_master}
  db2 close
}

do_malloc_test shared_err-5 -tclbody {
  db close
  sqlite3 dbX test.db
  sqlite3 dbY test.db
  dbX close
  dbY close
} -cleanup {
  catch {dbX close}
  catch {dbY close}
}

do_malloc_test shared_err-6 -tclbody {
  catch {db close}
  ifcapable deprecated {
    sqlite3_thread_cleanup
  }
  sqlite3_enable_shared_cache 0
} -cleanup {
  sqlite3_enable_shared_cache 1
}

# As of 3.5.0, sqlite3_enable_shared_cache can be called at
# any time and from any thread
#do_test shared_err-misuse-7.1 {
#  sqlite3 db test.db
#  catch {
#    sqlite3_enable_shared_cache 0
#  } msg
#  set msg
#} {library routine called out of sequence}

# Again provoke a malloc() failure when a cursor position is being saved, 
# this time during a ROLLBACK operation by some other handle. 
#
# The library should return an SQLITE_NOMEM to the caller. The query that
# owns the cursor (the one for which the position is not saved) should
# be aborted.
# 
set ::aborted 0
do_malloc_test shared_err-8 -tclprep {
  sqlite3 db2 test.db
  execsql {
    PRAGMA read_uncommitted = 1;
    BEGIN;
    CREATE TABLE t1(a, b, UNIQUE(a, b));
  } db2
  for {set i 0} {$i < 2} {incr i} {
    set a [string repeat $i 10]
    set b [string repeat $i 2000]
    execsql {INSERT INTO t1 VALUES($a, $b)} db2
  }
  execsql {COMMIT} db2
  set ::DB2 [sqlite3_connection_pointer db2]
  set ::STMT [sqlite3_prepare $::DB2 "SELECT a FROM t1 ORDER BY a" -1 DUMMY]
  sqlite3_step $::STMT       ;# Cursor points at 0000000000
  sqlite3_step $::STMT       ;# Cursor points at 1111111111
} -tclbody {
  execsql {
    BEGIN;
    INSERT INTO t1 VALUES(6, NULL);
    ROLLBACK;
  }
} -cleanup {
  # UPDATE: As of [5668], if the rollback fails SQLITE_CORRUPT is returned. 
  # So these tests have been updated to expect SQLITE_CORRUPT and its
  # associated English language error message.
  #
  do_test shared_malloc-8.$::n.cleanup.1 {
    set res [catchsql {SELECT a FROM t1} db2]
    set ans [lindex $res 1]
    if {[lindex $res 0]} {
       set r [expr {
         $ans=="disk I/O error" ||
         $ans=="out of memory" ||
         $ans=="database disk image is malformed"
       }]
    } else {
       set r [expr {[lrange $ans 0 1]=="0000000000 1111111111"}]
    }
  } {1}
  do_test shared_malloc-8.$::n.cleanup.2 {
    set rc1 [sqlite3_step $::STMT]
    set rc2 [sqlite3_finalize $::STMT]
    if {$rc2=="SQLITE_ABORT"} {
      incr ::aborted
    }
    expr {
      ($rc1=="SQLITE_DONE" && $rc2=="SQLITE_OK") || 
      ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_ABORT") ||
      ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_NOMEM") ||
      ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_IOERR") ||
      ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_CORRUPT")
    }
  } {1}
  db2 close
}
do_test shared_malloc-8.X {
  # Test that one or more queries were aborted due to the malloc() failure.
  expr $::aborted>=1
} {1}

# This test is designed to catch a specific bug that was present during
# development of 3.5.0. If a malloc() failed while setting the page-size,
# a buffer (Pager.pTmpSpace) was being freed. This could cause a seg-fault
# later if another connection tried to use the pager.
#
# This test will crash 3.4.2.
#
do_malloc_test shared_err-9 -tclprep {
  sqlite3 db2 test.db
} -sqlbody {
  PRAGMA page_size = 4096;
  PRAGMA page_size = 1024;
} -cleanup {
  db2 eval {
    CREATE TABLE abc(a, b, c);
    BEGIN;
    INSERT INTO abc VALUES(1, 2, 3);
    ROLLBACK;
  }     
  db2 close
}     

catch {db close}
catch {db2 close}
do_malloc_test shared_err-10 -tclprep {
  sqlite3 db test.db
  sqlite3 db2 test.db
  
  db eval { SELECT * FROM sqlite_master }
  db2 eval { 
    BEGIN;
    CREATE TABLE abc(a, b, c);
  }
} -tclbody {
  catch {db eval {SELECT * FROM sqlite_master}}
  error 1
} -cleanup {
  execsql { SELECT * FROM sqlite_master }
}

do_malloc_test shared_err-11 -tclprep {
  sqlite3 db test.db
  sqlite3 db2 test.db
  
  db eval { SELECT * FROM sqlite_master }
  db2 eval { 
    BEGIN;
    CREATE TABLE abc(a, b, c);
  }
} -tclbody {
  catch {db eval {SELECT * FROM sqlite_master}}
  catch {sqlite3_errmsg16 db}
  error 1
} -cleanup {
  execsql { SELECT * FROM sqlite_master }
}

catch {db close}
catch {db2 close}

do_malloc_test shared_err-12 -sqlbody {
  CREATE TABLE abc(a, b, c);
  INSERT INTO abc VALUES(1, 2, 3);
}

catch {db close}
catch {db2 close}
sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/sharedlock.test.















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 2009 July 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: sharedlock.test,v 1.1 2009/07/02 17:21:58 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close

ifcapable !shared_cache {
  finish_test
  return
}

set ::enable_shared_cache [sqlite3_enable_shared_cache 1]
sqlite3 db  test.db
sqlite3 db2 test.db

do_test sharedlock-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
  }
} {}

do_test sharedlock-1.2 {
  set res [list]
  db eval { SELECT * FROM t1 ORDER BY rowid } {
    lappend res $a $b
    if {$a == 1} { catch { db  eval "INSERT INTO t1 VALUES(3, 'three')" } }

    # This should fail. Connection [db] has a read-lock on t1, which should
    # prevent connection [db2] from obtaining the write-lock it needs to
    # modify t1. At one point there was a bug causing the previous INSERT
    # to drop the read-lock belonging to [db].
    if {$a == 2} { catch { db2 eval "INSERT INTO t1 VALUES(4, 'four')"  } }
  }
  set res
} {1 one 2 two 3 three}

db close
db2 close

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/shortread1.test.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 2007 Sep 13
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file attempts to duplicate an error scenario seen on a
# customer system using version 3.2.2.  The problem appears to
# have been fixed (perhaps by accident) with check-in [3503].
# These tests will prevent an accidental recurrance.
#
# $Id: shortread1.test,v 1.1 2007/09/14 01:48:12 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test shortread1-1.1 {
  execsql {
    CREATE TABLE t1(a TEXT);
    BEGIN;
    INSERT INTO t1 VALUES(hex(randomblob(5000)));
    INSERT INTO t1 VALUES(hex(randomblob(100)));
    PRAGMA freelist_count;
  }
} {0}
do_test shortread1-1.2 {
  execsql {
    DELETE FROM t1 WHERE rowid=1;
    PRAGMA freelist_count;
  }
} {11}
do_test shortread1-1.3 {
  sqlite3_release_memory [expr {1024*9}]
  execsql {
    INSERT INTO t1 VALUES(hex(randomblob(5000)));
    PRAGMA freelist_count;
  }
} {0}
do_test shortread1-1.4 {
  execsql {
    COMMIT;
    SELECT count(*) FROM t1;
  }
} {2}

finish_test

Added test/sidedelete.test.

























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# 2007 Dec 12
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains test cases for stressing database
# changes that involve side effects that delete rows from
# the table being changed.  Ticket #2832 shows that in
# older versions of SQLite that behavior was implemented
# incorrectly and resulted in corrupt database files.
#
# $Id: sidedelete.test,v 1.2 2008/08/04 03:51:24 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# The sequence table is created to store a sequence of integers
# starting with 1.  This is used to reinitialize other tables
# as part of other tests.
#
do_test sidedelete-1.1 {
  execsql {
    CREATE TABLE sequence(a INTEGER PRIMARY KEY);
    INSERT INTO sequence VALUES(1);
    INSERT INTO sequence VALUES(2);
  }
  for {set i 0} {$i<8} {incr i} {
    execsql {
      INSERT INTO sequence SELECT a+(SELECT max(a) FROM sequence) FROM sequence;
    }
  }
  execsql {SELECT count(*) FROM sequence}
} {512}

# Make a series of changes using an UPDATE OR REPLACE and a
# correlated subquery.  This would cause database corruption
# prior to the fix for ticket #2832.
#
do_test sidedelete-2.0 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    CREATE TABLE chng(a PRIMARY KEY, b);
    SELECT count(*) FROM t1;
    SELECT count(*) FROM chng;
  }
} {0 0}
for {set i 2} {$i<=100} {incr i} {
  set n [expr {($i+2)/2}]
  do_test sidedelete-2.$i.1 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 SELECT a, a FROM sequence WHERE a<=$i;
      DELETE FROM chng;
      INSERT INTO chng SELECT a*2, a*2+1 FROM sequence WHERE a<=$i/2;
      UPDATE OR REPLACE t1 SET a=(SELECT b FROM chng WHERE a=t1.a);
      SELECT count(*), sum(a) FROM t1;
    }
  } [list $n [expr {$n*$n-1}]]
  integrity_check sidedelete-2.$i.2
}

# This will cause stacks leaks but not database corruption prior
# to the #2832 fix.
#
do_test sidedelete-3.0 {
  execsql {
     DROP TABLE t1;
     CREATE TABLE t1(a PRIMARY KEY);
     SELECT * FROM t1;
  }
} {}
for {set i 1} {$i<=100} {incr i} {
  set n [expr {($i+1)/2}]
  do_test sidedelete-3.$i.1 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 SELECT a FROM sequence WHERE a<=$i;
      UPDATE OR REPLACE t1 SET a=a+1;
      SELECT count(*), sum(a) FROM t1;
    }
  } [list $n [expr {$n*($n+1)}]]
  integrity_check sidedelete-3.$i.2
}

finish_test

Added test/soak.test.





















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 2007 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file is the driver for the "soak" tests. It is a peer of the
# quick.test and all.test scripts.
#
# $Id: soak.test,v 1.4 2008/11/13 18:29:51 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
rename finish_test really_finish_test
proc finish_test {} {}

# By default, guarantee that the tests will run for at least 1 hour.
#
set TIMEOUT 3600

# Process command-line arguments. 
#
if {[llength $argv]>0} {
  foreach {name value} $argv {
    switch -- $name {
      -timeout {
        set TIMEOUT $value
      }
      default {
         puts stderr "Unknown option: $name"
         exit
      }
    }
  }
}
set argv [list]

# Test plan:
#
# The general principle is to run those SQLite tests that use
# pseudo-random data in some way over and over again for a very 
# long time. The number of tests run depends on the value of 
# global variable $TIMEOUT - tests are run for at least $TIMEOUT 
# seconds.
#
#   fuzz.test     (pseudo-random SQL statements)
#   trans.test    (pseudo-random changes to a database followed by rollbacks)
#   fuzz_malloc.test
#   corruptC.test (pseudo-random corruption to a database)
#
# Many database changes maintaining some kind of invariant. 
# Storing checksums etc.
#

# List of test files that are run by this file.
#
set SOAKTESTS {
  fuzz.test
  fuzz_malloc.test
  trans.test
  corruptC.test
}

set ISQUICK 1

set soak_starttime  [clock seconds]
set soak_finishtime [expr {$soak_starttime + $TIMEOUT}]

# Loop until the timeout is reached or an error occurs.
#
for {set iRun 0} {[clock seconds] < $soak_finishtime && $nErr==0} {incr iRun} {

  set iIdx [expr {$iRun % [llength $SOAKTESTS]}]
  source [file join $testdir [lindex $SOAKTESTS $iIdx]]
  catch {db close}

  if {$sqlite_open_file_count>0} {
    puts "$tail did not close all files: $sqlite_open_file_count"
    incr nErr
    lappend ::failList $tail
    set sqlite_open_file_count 0
  }

}

really_finish_test

Added test/softheap1.test.





































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 2007 Aug 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# 
# This test script reproduces the problem reported by ticket #2565,
# A database corruption bug that occurs in auto_vacuum mode when
# the soft_heap_limit is set low enough to be triggered.
#
# $Id: softheap1.test,v 1.5 2008/07/08 17:13:59 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !integrityck {
  finish_test
  return
}

sqlite3_soft_heap_limit -1
sqlite3_soft_heap_limit 0
sqlite3_soft_heap_limit 5000
do_test softheap1-1.1 {
  execsql {
    PRAGMA auto_vacuum=1;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(hex(randomblob(1000)));
    BEGIN;
  }
  execsql {
    CREATE TABLE t2 AS SELECT * FROM t1;
  }
  execsql {
    ROLLBACK;
  }
  execsql {
    PRAGMA integrity_check;
  }
} {ok}

sqlite3_soft_heap_limit $soft_limit
   
finish_test

Added test/sort.test.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# 2001 September 15.
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CREATE TABLE statement.
#
# $Id: sort.test,v 1.25 2005/11/14 22:29:06 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a bunch of data to sort against
#
do_test sort-1.0 {
  execsql {
    CREATE TABLE t1(
       n int,
       v varchar(10),
       log int,
       roman varchar(10),
       flt real
    );
    INSERT INTO t1 VALUES(1,'one',0,'I',3.141592653);
    INSERT INTO t1 VALUES(2,'two',1,'II',2.15);
    INSERT INTO t1 VALUES(3,'three',1,'III',4221.0);
    INSERT INTO t1 VALUES(4,'four',2,'IV',-0.0013442);
    INSERT INTO t1 VALUES(5,'five',2,'V',-11);
    INSERT INTO t1 VALUES(6,'six',2,'VI',0.123);
    INSERT INTO t1 VALUES(7,'seven',2,'VII',123.0);
    INSERT INTO t1 VALUES(8,'eight',3,'VIII',-1.6);
  }
  execsql {SELECT count(*) FROM t1}
} {8}

do_test sort-1.1 {
  execsql {SELECT n FROM t1 ORDER BY n}
} {1 2 3 4 5 6 7 8}
do_test sort-1.1.1 {
  execsql {SELECT n FROM t1 ORDER BY n ASC}
} {1 2 3 4 5 6 7 8}
do_test sort-1.1.1 {
  execsql {SELECT ALL n FROM t1 ORDER BY n ASC}
} {1 2 3 4 5 6 7 8}
do_test sort-1.2 {
  execsql {SELECT n FROM t1 ORDER BY n DESC}
} {8 7 6 5 4 3 2 1}
do_test sort-1.3a {
  execsql {SELECT v FROM t1 ORDER BY v}
} {eight five four one seven six three two}
do_test sort-1.3b {
  execsql {SELECT n FROM t1 ORDER BY v}
} {8 5 4 1 7 6 3 2}
do_test sort-1.4 {
  execsql {SELECT n FROM t1 ORDER BY v DESC}
} {2 3 6 7 1 4 5 8}
do_test sort-1.5 {
  execsql {SELECT flt FROM t1 ORDER BY flt}
} {-11.0 -1.6 -0.0013442 0.123 2.15 3.141592653 123.0 4221.0}
do_test sort-1.6 {
  execsql {SELECT flt FROM t1 ORDER BY flt DESC}
} {4221.0 123.0 3.141592653 2.15 0.123 -0.0013442 -1.6 -11.0}
do_test sort-1.7 {
  execsql {SELECT roman FROM t1 ORDER BY roman}
} {I II III IV V VI VII VIII}
do_test sort-1.8 {
  execsql {SELECT n FROM t1 ORDER BY log, flt}
} {1 2 3 5 4 6 7 8}
do_test sort-1.8.1 {
  execsql {SELECT n FROM t1 ORDER BY log asc, flt}
} {1 2 3 5 4 6 7 8}
do_test sort-1.8.2 {
  execsql {SELECT n FROM t1 ORDER BY log, flt ASC}
} {1 2 3 5 4 6 7 8}
do_test sort-1.8.3 {
  execsql {SELECT n FROM t1 ORDER BY log ASC, flt asc}
} {1 2 3 5 4 6 7 8}
do_test sort-1.9 {
  execsql {SELECT n FROM t1 ORDER BY log, flt DESC}
} {1 3 2 7 6 4 5 8}
do_test sort-1.9.1 {
  execsql {SELECT n FROM t1 ORDER BY log ASC, flt DESC}
} {1 3 2 7 6 4 5 8}
do_test sort-1.10 {
  execsql {SELECT n FROM t1 ORDER BY log DESC, flt}
} {8 5 4 6 7 2 3 1}
do_test sort-1.11 {
  execsql {SELECT n FROM t1 ORDER BY log DESC, flt DESC}
} {8 7 6 4 5 3 2 1}

# These tests are designed to reach some hard-to-reach places
# inside the string comparison routines.
#
# (Later) The sorting behavior changed in 2.7.0.  But we will
# keep these tests.  You can never have too many test cases!
#
do_test sort-2.1.1 {
  execsql {
    UPDATE t1 SET v='x' || -flt;
    UPDATE t1 SET v='x-2b' where v=='x-0.123';
    SELECT v FROM t1 ORDER BY v;
  }
} {x-123.0 x-2.15 x-2b x-3.141592653 x-4221.0 x0.0013442 x1.6 x11.0}
do_test sort-2.1.2 {
  execsql {
    SELECT v FROM t1 ORDER BY substr(v,2,999);
  }
} {x-123.0 x-2.15 x-2b x-3.141592653 x-4221.0 x0.0013442 x1.6 x11.0}
do_test sort-2.1.3 {
  execsql {
    SELECT v FROM t1 ORDER BY substr(v,2,999)+0.0;
  }
} {x-4221.0 x-123.0 x-3.141592653 x-2.15 x-2b x0.0013442 x1.6 x11.0}
do_test sort-2.1.4 {
  execsql {
    SELECT v FROM t1 ORDER BY substr(v,2,999) DESC;
  }
} {x11.0 x1.6 x0.0013442 x-4221.0 x-3.141592653 x-2b x-2.15 x-123.0}
do_test sort-2.1.5 {
  execsql {
    SELECT v FROM t1 ORDER BY substr(v,2,999)+0.0 DESC;
  }
} {x11.0 x1.6 x0.0013442 x-2b x-2.15 x-3.141592653 x-123.0 x-4221.0}

# This is a bug fix for 2.2.4.
# Strings are normally mapped to upper-case for a caseless comparison.
# But this can cause problems for characters in between 'Z' and 'a'.
#
do_test sort-3.1 {
  execsql {
    CREATE TABLE t2(a,b);
    INSERT INTO t2 VALUES('AGLIENTU',1);
    INSERT INTO t2 VALUES('AGLIE`',2);
    INSERT INTO t2 VALUES('AGNA',3);
    SELECT a, b FROM t2 ORDER BY a;
  }
} {AGLIENTU 1 AGLIE` 2 AGNA 3}
do_test sort-3.2 {
  execsql {
    SELECT a, b FROM t2 ORDER BY a DESC;
  }
} {AGNA 3 AGLIE` 2 AGLIENTU 1}
do_test sort-3.3 {
  execsql {
    DELETE FROM t2;
    INSERT INTO t2 VALUES('aglientu',1);
    INSERT INTO t2 VALUES('aglie`',2);
    INSERT INTO t2 VALUES('agna',3);
    SELECT a, b FROM t2 ORDER BY a;
  }
} {aglie` 2 aglientu 1 agna 3}
do_test sort-3.4 {
  execsql {
    SELECT a, b FROM t2 ORDER BY a DESC;
  }
} {agna 3 aglientu 1 aglie` 2}

# Version 2.7.0 testing.
#
do_test sort-4.1 {
  execsql {
    INSERT INTO t1 VALUES(9,'x2.7',3,'IX',4.0e5);
    INSERT INTO t1 VALUES(10,'x5.0e10',3,'X',-4.0e5);
    INSERT INTO t1 VALUES(11,'x-4.0e9',3,'XI',4.1e4);
    INSERT INTO t1 VALUES(12,'x01234567890123456789',3,'XII',-4.2e3);
    SELECT n FROM t1 ORDER BY n;
  }
} {1 2 3 4 5 6 7 8 9 10 11 12}
do_test sort-4.2 {
  execsql {
    SELECT n||'' FROM t1 ORDER BY 1;
  }
} {1 10 11 12 2 3 4 5 6 7 8 9}
do_test sort-4.3 {
  execsql {
    SELECT n+0 FROM t1 ORDER BY 1;
  }
} {1 2 3 4 5 6 7 8 9 10 11 12}
do_test sort-4.4 {
  execsql {
    SELECT n||'' FROM t1 ORDER BY 1 DESC;
  }
} {9 8 7 6 5 4 3 2 12 11 10 1}
do_test sort-4.5 {
  execsql {
    SELECT n+0 FROM t1 ORDER BY 1 DESC;
  }
} {12 11 10 9 8 7 6 5 4 3 2 1}
do_test sort-4.6 {
  execsql {
    SELECT v FROM t1 ORDER BY 1;
  }
} {x-123.0 x-2.15 x-2b x-3.141592653 x-4.0e9 x-4221.0 x0.0013442 x01234567890123456789 x1.6 x11.0 x2.7 x5.0e10}
do_test sort-4.7 {
  execsql {
    SELECT v FROM t1 ORDER BY 1 DESC;
  }
} {x5.0e10 x2.7 x11.0 x1.6 x01234567890123456789 x0.0013442 x-4221.0 x-4.0e9 x-3.141592653 x-2b x-2.15 x-123.0}
do_test sort-4.8 {
  execsql {
    SELECT substr(v,2,99) FROM t1 ORDER BY 1;
  }
} {-123.0 -2.15 -2b -3.141592653 -4.0e9 -4221.0 0.0013442 01234567890123456789 1.6 11.0 2.7 5.0e10}
#do_test sort-4.9 {
#  execsql {
#    SELECT substr(v,2,99)+0.0 FROM t1 ORDER BY 1;
#  }
#} {-4000000000 -4221 -123 -3.141592653 -2.15 -2 0.0013442 1.6 2.7 11 50000000000 1.23456789012346e+18}

do_test sort-5.1 {
  execsql {
    create table t3(a,b);
    insert into t3 values(5,NULL);
    insert into t3 values(6,NULL);
    insert into t3 values(3,NULL);
    insert into t3 values(4,'cd');
    insert into t3 values(1,'ab');
    insert into t3 values(2,NULL);
    select a from t3 order by b, a;
  }
} {2 3 5 6 1 4}
do_test sort-5.2 {
  execsql {
    select a from t3 order by b, a desc;
  }
} {6 5 3 2 1 4}
do_test sort-5.3 {
  execsql {
    select a from t3 order by b desc, a;
  }
} {4 1 2 3 5 6}
do_test sort-5.4 {
  execsql {
    select a from t3 order by b desc, a desc;
  }
} {4 1 6 5 3 2}

do_test sort-6.1 {
  execsql {
    create index i3 on t3(b,a);
    select a from t3 order by b, a;
  }
} {2 3 5 6 1 4}
do_test sort-6.2 {
  execsql {
    select a from t3 order by b, a desc;
  }
} {6 5 3 2 1 4}
do_test sort-6.3 {
  execsql {
    select a from t3 order by b desc, a;
  }
} {4 1 2 3 5 6}
do_test sort-6.4 {
  execsql {
    select a from t3 order by b desc, a desc;
  }
} {4 1 6 5 3 2}

do_test sort-7.1 {
  execsql {
    CREATE TABLE t4(
      a INTEGER,
      b VARCHAR(30)
    );
    INSERT INTO t4 VALUES(1,1);
    INSERT INTO t4 VALUES(2,2);
    INSERT INTO t4 VALUES(11,11);
    INSERT INTO t4 VALUES(12,12);
    SELECT a FROM t4 ORDER BY 1;
  }
} {1 2 11 12}
do_test sort-7.2 {
  execsql {
    SELECT b FROM t4 ORDER BY 1
  }
} {1 11 12 2}

# Omit tests sort-7.3 to sort-7.8 if view support was disabled at
# compilatation time.
ifcapable view {
do_test sort-7.3 {
  execsql {
    CREATE VIEW v4 AS SELECT * FROM t4;
    SELECT a FROM v4 ORDER BY 1;
  }
} {1 2 11 12}
do_test sort-7.4 {
  execsql {
    SELECT b FROM v4 ORDER BY 1;
  }
} {1 11 12 2}

ifcapable compound {
do_test sort-7.5 {
  execsql {
    SELECT a FROM t4 UNION SELECT a FROM v4 ORDER BY 1;
  }
} {1 2 11 12}
do_test sort-7.6 {
  execsql {
    SELECT b FROM t4 UNION SELECT a FROM v4 ORDER BY 1;
  }
} {1 2 11 12 1 11 12 2}  ;# text from t4.b and numeric from v4.a
do_test sort-7.7 {
  execsql {
    SELECT a FROM t4 UNION SELECT b FROM v4 ORDER BY 1;
  }
} {1 2 11 12 1 11 12 2} ;# numeric from t4.a and text from v4.b
do_test sort-7.8 {
  execsql {
    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1;
  }
} {1 11 12 2}
} ;# ifcapable compound
} ;# ifcapable view

#### Version 3 works differently here:
#do_test sort-7.9 {
#  execsql {
#    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE numeric;
#  }
#} {1 2 11 12}
#do_test sort-7.10 {
#  execsql {
#    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE integer;
#  }
#} {1 2 11 12}
#do_test sort-7.11 {
#  execsql {
#    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE text;
#  }
#} {1 11 12 2}
#do_test sort-7.12 {
#  execsql {
#    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE blob;
#  }
#} {1 11 12 2}
#do_test sort-7.13 {
#  execsql {
#    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE clob;
#  }
#} {1 11 12 2}
#do_test sort-7.14 {
#  execsql {
#    SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE varchar;
#  }
#} {1 11 12 2}

# Ticket #297
#
do_test sort-8.1 {
  execsql {
    CREATE TABLE t5(a real, b text);
    INSERT INTO t5 VALUES(100,'A1');
    INSERT INTO t5 VALUES(100.0,'A2');
    SELECT * FROM t5 ORDER BY a, b;
  }
} {100.0 A1 100.0 A2}


ifcapable {bloblit} {
# BLOBs should sort after TEXT
#
do_test sort-9.1 {
  execsql {
    CREATE TABLE t6(x, y);
    INSERT INTO t6 VALUES(1,1);
    INSERT INTO t6 VALUES(2,'1');
    INSERT INTO t6 VALUES(3,x'31');
    INSERT INTO t6 VALUES(4,NULL);
    SELECT x FROM t6 ORDER BY y;
  }
} {4 1 2 3}
do_test sort-9.2 {
  execsql {
    SELECT x FROM t6 ORDER BY y DESC;
  }
} {3 2 1 4}
do_test sort-9.3 {
  execsql {
    SELECT x FROM t6 WHERE y<1
  }
} {}
do_test sort-9.4 {
  execsql {
    SELECT x FROM t6 WHERE y<'1'
  }
} {1}
do_test sort-9.5 {
  execsql {
    SELECT x FROM t6 WHERE y<x'31'
  }
} {1 2}
do_test sort-9.6 {
  execsql {
    SELECT x FROM t6 WHERE y>1
  }
} {2 3}
do_test sort-9.7 {
  execsql {
    SELECT x FROM t6 WHERE y>'1'
  }
} {3}
} ;# endif bloblit

# Ticket #1092 - ORDER BY on rowid fields.
do_test sort-10.1 {
  execsql {
    CREATE TABLE t7(c INTEGER PRIMARY KEY);
    INSERT INTO t7 VALUES(1);
    INSERT INTO t7 VALUES(2);
    INSERT INTO t7 VALUES(3);
    INSERT INTO t7 VALUES(4);
  }
} {}
do_test sort-10.2 {
  execsql {
    SELECT c FROM t7 WHERE c<=3 ORDER BY c DESC;
  }
} {3 2 1}
do_test sort-10.3 {
  execsql {
    SELECT c FROM t7 WHERE c<3 ORDER BY c DESC;
  }
} {2 1}

# ticket #1358.  Just because one table in a join gives a unique
# result does not mean they all do.  We cannot disable sorting unless
# all tables in the join give unique results.
#
do_test sort-11.1 {
  execsql {
    create table t8(a unique, b, c);
    insert into t8 values(1,2,3);
    insert into t8 values(2,3,4);
    create table t9(x,y);
    insert into t9 values(2,4);
    insert into t9 values(2,3);
    select y from t8, t9 where a=1 order by a, y;
  }
} {3 4}

# Trouble reported on the mailing list.  Check for overly aggressive
# (which is to say, incorrect) optimization of order-by with a rowid
# in a join.
#
do_test sort-12.1 {
  execsql {
    create table a (id integer primary key);
    create table b (id integer primary key, aId integer, text);
    insert into a values (1);
    insert into b values (2, 1, 'xxx');
    insert into b values (1, 1, 'zzz');
    insert into b values (3, 1, 'yyy');
    select a.id, b.id, b.text from a join b on (a.id = b.aId)
      order by a.id, b.text;
  }
} {1 2 xxx 1 3 yyy 1 1 zzz}

finish_test

Added test/speed1.test.





















































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# 2006 November 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed.
#
# $Id: speed1.test,v 1.11 2009/04/09 01:23:49 drh Exp $
#

sqlite3_shutdown
#sqlite3_config_scratch 29000 1
set old_lookaside [sqlite3_config_lookaside 1000 300]
#sqlite3_config_pagecache 1024 10000
set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

set sqlout [open speed1.txt w]
proc tracesql {sql} {
  puts $::sqlout $sql\;
}
#db trace tracesql

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Create a database schema.
#
do_test speed1-1.0 {
  execsql {
    PRAGMA page_size=1024;
    PRAGMA cache_size=8192;
    PRAGMA locking_mode=EXCLUSIVE;
    CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
    CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT);
    CREATE INDEX i2a ON t2(a);
    CREATE INDEX i2b ON t2(b);
  }
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1;
  }
} {i2a i2b t1 t2}


# 50000 INSERTs on an unindexed table
#
set sql {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');\n"
}
db eval BEGIN
speed_trial speed1-insert1 50000 row $sql
db eval COMMIT

# 50000 INSERTs on an indexed table
#
set sql {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');\n"
}
db eval BEGIN
speed_trial speed1-insert2 50000 row $sql
db eval COMMIT



# 50 SELECTs on an integer comparison.  There is no index so
# a full table scan is required.
#
set sql {}
for {set i 0} {$i<50} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}
db eval BEGIN
speed_trial speed1-select1 [expr {50*50000}] row $sql
db eval COMMIT

# 50 SELECTs on an LIKE comparison.  There is no index so a full
# table scan is required.
#
set sql {}
for {set i 0} {$i<50} {incr i} {
  append sql \
    "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';"
}
db eval BEGIN
speed_trial speed1-select2 [expr {50*50000}] row $sql
db eval COMMIT

# Create indices
#
db eval BEGIN
speed_trial speed1-createidx 150000 row {
  CREATE INDEX i1a ON t1(a);
  CREATE INDEX i1b ON t1(b);
  CREATE INDEX i1c ON t1(c);
}
db eval COMMIT

# 5000 SELECTs on an integer comparison where the integer is
# indexed.
#
set sql {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}
db eval BEGIN
speed_trial speed1-select3 5000 stmt $sql
db eval COMMIT

# 100000 random SELECTs against rowid.
#
set sql {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  append sql "SELECT c FROM t1 WHERE rowid=$id;"
}
db eval BEGIN
speed_trial speed1-select4 100000 row $sql
db eval COMMIT

# 100000 random SELECTs against a unique indexed column.
#
set sql {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  append sql "SELECT c FROM t1 WHERE a=$id;"
}
db eval BEGIN
speed_trial speed1-select5 100000 row $sql
db eval COMMIT

# 50000 random SELECTs against an indexed column text column
#
set sql {}
db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000} {
  append sql "SELECT c FROM t1 WHERE c='$c';"
}
db eval BEGIN
speed_trial speed1-select6 50000 row $sql
db eval COMMIT


# Vacuum
speed_trial speed1-vacuum 100000 row VACUUM

# 5000 updates of ranges where the field being compared is indexed.
#
set sql {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*2}]
  set upr [expr {($i+1)*2}]
  append sql "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;"
}
db eval BEGIN
speed_trial speed1-update1 5000 stmt $sql
db eval COMMIT

# 50000 single-row updates.  An index is used to find the row quickly.
#
set sql {}
for {set i 0} {$i<50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "UPDATE t1 SET b=$r WHERE a=$i;"
}
db eval BEGIN
speed_trial speed1-update2 50000 row $sql
db eval COMMIT

# 1 big text update that touches every row in the table.
#
speed_trial speed1-update3 50000 row {
  UPDATE t1 SET c=a;
}

# Many individual text updates.  Each row in the table is
# touched through an index.
#
set sql {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;"
}
db eval BEGIN
speed_trial speed1-update4 50000 row $sql
db eval COMMIT

# Delete all content in a table.
#
speed_trial speed1-delete1 50000 row {DELETE FROM t1}

# Copy one table into another
#
speed_trial speed1-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Delete all content in a table, one row at a time.
#
speed_trial speed1-delete2 50000 row {DELETE FROM t1 WHERE 1}

# Refill the table yet again
#
speed_trial speed1-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Drop the table and recreate it without its indices.
#
db eval BEGIN
speed_trial speed1-drop1 50000 row {
   DROP TABLE t1;
   CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
}
db eval COMMIT

# Refill the table yet again.  This copy should be faster because
# there are no indices to deal with.
#
speed_trial speed1-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Select 20000 rows from the table at random.
#
speed_trial speed1-random1 50000 row {
  SELECT rowid FROM t1 ORDER BY random() LIMIT 20000
}

# Delete 20000 random rows from the table.
#
speed_trial speed1-random-del1 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed1-1.1 {
  db one {SELECT count(*) FROM t1}
} 30000

    
# Delete 20000 more rows at random from the table.
#
speed_trial speed1-random-del2 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed1-1.2 {
  db one {SELECT count(*) FROM t1}
} 10000
speed_trial_summary speed1

db close
sqlite3_shutdown
eval sqlite3_config_lookaside $old_lookaside
sqlite3_initialize
autoinstall_test_functions
finish_test

Added test/speed1p.explain.





























































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# 2008 March 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed.  
#
# This is a copy of speed1.test modified to user prepared statements.
#
# $Id: speed1p.explain,v 1.1 2008/04/16 12:57:48 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

set sqlout [open speed1.txt w]
proc tracesql {sql} {
  puts $::sqlout $sql\;
}
#db trace tracesql

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Create a database schema.
#
do_test speed1p-1.0 {
  execsql {
    PRAGMA page_size=1024;
    PRAGMA cache_size=8192;
    PRAGMA locking_mode=EXCLUSIVE;
    CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
    CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT);
    CREATE INDEX i2a ON t2(a);
    CREATE INDEX i2b ON t2(b);
  }
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1;
  }
} {i2a i2b t1 t2}


# 50000 INSERTs on an unindexed table
#
set list {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  set x [number_name $r]
  lappend list $i $r $x
}
set script {
  foreach {i r x} $::list {
    db eval {INSERT INTO t1 VALUES($i,$r,$x)}
  }
}
explain {INSERT INTO t1 VALUES($i,$r,$x)}
db eval BEGIN
speed_trial_tcl speed1p-insert1 50000 row $script
db eval COMMIT

# 50000 INSERTs on an indexed table
#
set list {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  set x [number_name $r]
  lappend list $i $r $x
}
set script {
  foreach {i r x} $::list {
    db eval {INSERT INTO t2 VALUES($i,$r,$x)}
  }
}
explain {INSERT INTO t2 VALUES($i,$r,$x)}
db eval BEGIN
speed_trial_tcl speed1p-insert2 50000 row $script
db eval COMMIT



# 50 SELECTs on an integer comparison.  There is no index so
# a full table scan is required.
#
set list {}
for {set i 0} {$i<50} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  lappend list $lwr $upr
}
set script {
  foreach {lwr upr} $::list {
    db eval  {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr}
  }
}
explain {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr}
db eval BEGIN
speed_trial_tcl speed1p-select1 [expr {50*50000}] row $script
db eval COMMIT

# 50 SELECTs on an LIKE comparison.  There is no index so a full
# table scan is required.
#
set list {}
for {set i 0} {$i<50} {incr i} {
  lappend list "%[number_name $i]%"
}
set script {
  foreach pattern $::list {
    db eval {SELECT count(*), avg(b) FROM t1 WHERE c LIKE $pattern}
  }
}
explain {SELECT count(*), avg(b) FROM t1 WHERE c LIKE $pattern}
db eval BEGIN
speed_trial_tcl speed1p-select2 [expr {50*50000}] row $script
db eval COMMIT

# Create indices
#
explain {CREATE INDEX i1a ON t1(a)}
explain {CREATE INDEX i1b ON t1(b)}
db eval BEGIN
speed_trial speed1p-createidx 150000 row {
  CREATE INDEX i1a ON t1(a);
  CREATE INDEX i1b ON t1(b);
  CREATE INDEX i1c ON t1(c);
}
db eval COMMIT

# 5000 SELECTs on an integer comparison where the integer is
# indexed.
#
set list {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  lappend list $lwr $upr
}
set script {
  foreach {lwr upr} $::list {
    db eval {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr}
  }
}
explain {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr}
db eval BEGIN
speed_trial_tcl speed1p-select3 5000 stmt $script
db eval COMMIT

# 100000 random SELECTs against rowid.
#
set list {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  lappend list $id
}
set script {
  foreach id $::list {
    db eval {SELECT c FROM t1 WHERE rowid=$id}
  }
}
explain {SELECT c FROM t1 WHERE rowid=$id}
db eval BEGIN
speed_trial_tcl speed1p-select4 100000 row $script
db eval COMMIT

# 100000 random SELECTs against a unique indexed column.
#
set list {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  lappend list $id
}
set script {
  foreach id $::list {
    db eval {SELECT c FROM t1 WHERE a=$id}
  }
}
explain {SELECT c FROM t1 WHERE a=$id}
db eval BEGIN
speed_trial_tcl speed1p-select5 100000 row $script
db eval COMMIT

# 50000 random SELECTs against an indexed column text column
#
set list [db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000}]
set script {
  foreach c $::list {
    db eval {SELECT c FROM t1 WHERE c=$c}
  }
}
explain {SELECT c FROM t1 WHERE c=$c}
db eval BEGIN
speed_trial_tcl speed1p-select6 50000 row $script
db eval COMMIT


# Vacuum
speed_trial speed1p-vacuum 100000 row VACUUM

# 5000 updates of ranges where the field being compared is indexed.
#
set list {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*2}]
  set upr [expr {($i+1)*2}]
  lappend list $lwr $upr
}
set script {
  foreach {lwr upr} $::list {
    db eval {UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr}
  }
}
explain {UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr}
db eval BEGIN
speed_trial_tcl speed1p-update1 5000 stmt $script
db eval COMMIT

# 50000 single-row updates.  An index is used to find the row quickly.
#
set list {}
for {set i 0} {$i<50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  lappend list $i $r
}
set script {
  foreach {i r} $::list {
    db eval {UPDATE t1 SET b=$r WHERE a=$i}
  }
}
explain {UPDATE t1 SET b=$r WHERE a=$i}
db eval BEGIN
speed_trial_tcl speed1p-update2 50000 row $script
db eval COMMIT

# 1 big text update that touches every row in the table.
#
explain {UPDATE t1 SET c=a}
speed_trial speed1p-update3 50000 row {
  UPDATE t1 SET c=a;
}

# Many individual text updates.  Each row in the table is
# touched through an index.
#
set list {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  lappend list $i [number_name $r]
}
set script {
  foreach {i x} $::list {
    db eval {UPDATE t1 SET c=$x WHERE a=$i}
  }
}
explain {UPDATE t1 SET c=$x WHERE a=$i}
db eval BEGIN
speed_trial_tcl speed1p-update4 50000 row $script
db eval COMMIT

# Delete all content in a table.
#
explain {DELETE FROM t1}
speed_trial speed1p-delete1 50000 row {DELETE FROM t1}

# Copy one table into another
#
explain {INSERT INTO t1 SELECT * FROM t2}
speed_trial speed1p-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Delete all content in a table, one row at a time.
#
explain {DELETE FROM t1 WHERE 1}
speed_trial speed1p-delete2 50000 row {DELETE FROM t1 WHERE 1}

# Refill the table yet again
#
speed_trial speed1p-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Drop the table and recreate it without its indices.
#
explain {DROP TABLE t1}
explain {CREATE TABLE tX(a INTEGER, b INTEGER, c TEXT)}
db eval BEGIN
speed_trial speed1p-drop1 50000 row {
   DROP TABLE t1;
   CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
}
db eval COMMIT

# Refill the table yet again.  This copy should be faster because
# there are no indices to deal with.
#
speed_trial speed1p-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Select 20000 rows from the table at random.
#
explain {SELECT rowid FROM t1 ORDER BY random() LIMIT 20000}
speed_trial speed1p-random1 50000 row {
  SELECT rowid FROM t1 ORDER BY random() LIMIT 20000
}

# Delete 20000 random rows from the table.
#
explain {DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)}
speed_trial speed1p-random-del1 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed1p-1.1 {
  db one {SELECT count(*) FROM t1}
} 30000

    
# Delete 20000 more rows at random from the table.
#
speed_trial speed1p-random-del2 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed1p-1.2 {
  db one {SELECT count(*) FROM t1}
} 10000
speed_trial_summary speed1

finish_test

Added test/speed1p.test.





















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# 2008 March 21
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed.  
#
# This is a copy of speed1.test modified to user prepared statements.
#
# $Id: speed1p.test,v 1.7 2009/04/09 01:23:49 drh Exp $
#

sqlite3_shutdown
#sqlite3_config_scratch 29000 1
set old_lookaside [sqlite3_config_lookaside 2048 300]
#sqlite3_config_pagecache 1024 11000
set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Create a database schema.
#
do_test speed1p-1.0 {
  execsql {
    PRAGMA page_size=1024;
    PRAGMA cache_size=500;
    PRAGMA locking_mode=EXCLUSIVE;
    CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
    CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT);
    CREATE INDEX i2a ON t2(a);
    CREATE INDEX i2b ON t2(b);
  }
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1;
  }
} {i2a i2b t1 t2}


# 50000 INSERTs on an unindexed table
#
set list {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  set x [number_name $r]
  lappend list $i $r $x
}
set script {
  foreach {i r x} $::list {
    db eval {INSERT INTO t1 VALUES($i,$r,$x)}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-insert1 50000 row $script
db eval COMMIT

# 50000 INSERTs on an indexed table
#
set list {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  set x [number_name $r]
  lappend list $i $r $x
}
set script {
  foreach {i r x} $::list {
    db eval {INSERT INTO t2 VALUES($i,$r,$x)}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-insert2 50000 row $script
db eval COMMIT



# 50 SELECTs on an integer comparison.  There is no index so
# a full table scan is required.
#
set list {}
for {set i 0} {$i<50} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  lappend list $lwr $upr
}
set script {
  foreach {lwr upr} $::list {
    db eval  {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-select1 [expr {50*50000}] row $script
db eval COMMIT

# 50 SELECTs on an LIKE comparison.  There is no index so a full
# table scan is required.
#
set list {}
for {set i 0} {$i<50} {incr i} {
  lappend list "%[number_name $i]%"
}
set script {
  foreach pattern $::list {
    db eval {SELECT count(*), avg(b) FROM t1 WHERE c LIKE $pattern}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-select2 [expr {50*50000}] row $script
db eval COMMIT

# Create indices
#
db eval BEGIN
speed_trial speed1p-createidx 150000 row {
  CREATE INDEX i1a ON t1(a);
  CREATE INDEX i1b ON t1(b);
  CREATE INDEX i1c ON t1(c);
}
db eval COMMIT

# 5000 SELECTs on an integer comparison where the integer is
# indexed.
#
set list {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  lappend list $lwr $upr
}
set script {
  foreach {lwr upr} $::list {
    db eval {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-select3 5000 stmt $script
db eval COMMIT

# 100000 random SELECTs against rowid.
#
set list {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  lappend list $id
}
set script {
  foreach id $::list {
    db eval {SELECT c FROM t1 WHERE rowid=$id}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-select4 100000 row $script
db eval COMMIT

# 100000 random SELECTs against a unique indexed column.
#
set list {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  lappend list $id
}
set script {
  foreach id $::list {
    db eval {SELECT c FROM t1 WHERE a=$id}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-select5 100000 row $script
db eval COMMIT

# 50000 random SELECTs against an indexed column text column
#
set list [db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000}]
set script {
  foreach c $::list {
    db eval {SELECT c FROM t1 WHERE c=$c}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-select6 50000 row $script
db eval COMMIT


# Vacuum
speed_trial speed1p-vacuum 100000 row VACUUM

# 5000 updates of ranges where the field being compared is indexed.
#
set list {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*2}]
  set upr [expr {($i+1)*2}]
  lappend list $lwr $upr
}
set script {
  foreach {lwr upr} $::list {
    db eval {UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-update1 5000 stmt $script
db eval COMMIT

# 50000 single-row updates.  An index is used to find the row quickly.
#
set list {}
for {set i 0} {$i<50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  lappend list $i $r
}
set script {
  foreach {i r} $::list {
    db eval {UPDATE t1 SET b=$r WHERE a=$i}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-update2 50000 row $script
db eval COMMIT

# 1 big text update that touches every row in the table.
#
speed_trial speed1p-update3 50000 row {
  UPDATE t1 SET c=a;
}

# Many individual text updates.  Each row in the table is
# touched through an index.
#
set list {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  lappend list $i [number_name $r]
}
set script {
  foreach {i x} $::list {
    db eval {UPDATE t1 SET c=$x WHERE a=$i}
  }
}
db eval BEGIN
speed_trial_tcl speed1p-update4 50000 row $script
db eval COMMIT

# Delete all content in a table.
#
speed_trial speed1p-delete1 50000 row {DELETE FROM t1}

# Copy one table into another
#
speed_trial speed1p-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Delete all content in a table, one row at a time.
#
speed_trial speed1p-delete2 50000 row {DELETE FROM t1 WHERE 1}

# Refill the table yet again
#
speed_trial speed1p-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Drop the table and recreate it without its indices.
#
db eval BEGIN
speed_trial speed1p-drop1 50000 row {
   DROP TABLE t1;
   CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
}
db eval COMMIT

# Refill the table yet again.  This copy should be faster because
# there are no indices to deal with.
#
speed_trial speed1p-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Select 20000 rows from the table at random.
#
speed_trial speed1p-random1 50000 row {
  SELECT rowid FROM t1 ORDER BY random() LIMIT 20000
}

# Delete 20000 random rows from the table.
#
speed_trial speed1p-random-del1 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed1p-1.1 {
  db one {SELECT count(*) FROM t1}
} 30000
    
# Delete 20000 more rows at random from the table.
#
speed_trial speed1p-random-del2 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed1p-1.2 {
  db one {SELECT count(*) FROM t1}
} 10000
speed_trial_summary speed1

db close
sqlite3_shutdown
eval sqlite3_config_lookaside $old_lookaside
sqlite3_initialize
autoinstall_test_functions
finish_test

Added test/speed2.test.







































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# 2006 November 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed.
#
# $Id: speed2.test,v 1.7 2007/04/16 15:02:20 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed2

# Set a uniform random seed
expr srand(0)

set sqlout [open speed2.txt w]
proc tracesql {sql} {
  puts $::sqlout $sql\;
}
#db trace tracesql

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Create a database schema.
#
do_test speed2-1.0 {
  execsql {
    PRAGMA page_size=1024;
    PRAGMA cache_size=8192;
    PRAGMA locking_mode=EXCLUSIVE;
    CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
    CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT);
    CREATE INDEX i2a ON t2(a);
    CREATE INDEX i2b ON t2(b);
  }
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1;
  }
} {i2a i2b t1 t2}


# 50000 INSERTs on an unindexed table
#
set sql {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');\n"
}
db eval BEGIN
speed_trial speed2-insert1 50000 row $sql
db eval COMMIT

# 50000 INSERTs on an indexed table
#
set sql {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');\n"
}
db eval BEGIN
speed_trial speed2-insert2 50000 row $sql
db eval COMMIT



# 50 SELECTs on an integer comparison.  There is no index so
# a full table scan is required.
#
set sql {}
for {set i 0} {$i<50} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}
speed_trial speed2-select1a [expr {50*50000}] row $sql

# 50 SELECTs on an LIKE comparison.  There is no index so a full
# table scan is required.
#
set sql {}
for {set i 0} {$i<50} {incr i} {
  append sql \
    "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';"
}
speed_trial speed2-select2a [expr {50*50000}] row $sql

# Vacuum
speed_trial speed2-vacuum1 100000 row VACUUM

# 50 SELECTs on an integer comparison.  There is no index so
# a full table scan is required.
#
set sql {}
for {set i 0} {$i<50} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}
speed_trial speed2-select1b [expr {50*50000}] row $sql

# 50 SELECTs on an LIKE comparison.  There is no index so a full
# table scan is required.
#
set sql {}
for {set i 0} {$i<50} {incr i} {
  append sql \
    "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';"
}
speed_trial speed2-select2b [expr {50*50000}] row $sql

# Create indices
#
db eval BEGIN
speed_trial speed2-createidx 150000 row {
  CREATE INDEX i1a ON t1(a);
  CREATE INDEX i1b ON t1(b);
  CREATE INDEX i1c ON t1(c);
}
db eval COMMIT

# 5000 SELECTs on an integer comparison where the integer is
# indexed.
#
set sql {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}
speed_trial speed2-select3a 5000 stmt $sql

# 100000 random SELECTs against rowid.
#
set sql {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  append sql "SELECT c=='hi' FROM t1 WHERE rowid=$id;\n"
}
speed_trial speed2-select4a 100000 row $sql

# 100000 random SELECTs against a unique indexed column.
#
set sql {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  append sql "SELECT c FROM t1 WHERE a=$id;"
}
speed_trial speed2-select5a 100000 row $sql

# 50000 random SELECTs against an indexed column text column
#
set sql {}
db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000} {
  append sql "SELECT c FROM t1 WHERE c='$c';"
}
speed_trial speed2-select6a 50000 row $sql

# Vacuum
speed_trial speed2-vacuum2 100000 row VACUUM


# 5000 SELECTs on an integer comparison where the integer is
# indexed.
#
set sql {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}
speed_trial speed2-select3b 5000 stmt $sql

# 100000 random SELECTs against rowid.
#
set sql {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  append sql "SELECT c=='hi' FROM t1 WHERE rowid=$id;\n"
}
speed_trial speed2-select4b 100000 row $sql

# 100000 random SELECTs against a unique indexed column.
#
set sql {}
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  append sql "SELECT c FROM t1 WHERE a=$id;"
}
speed_trial speed2-select5b 100000 row $sql

# 50000 random SELECTs against an indexed column text column
#
set sql {}
db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000} {
  append sql "SELECT c FROM t1 WHERE c='$c';"
}
speed_trial speed2-select6b 50000 row $sql

# 5000 updates of ranges where the field being compared is indexed.
#
set sql {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*2}]
  set upr [expr {($i+1)*2}]
  append sql "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;"
}
db eval BEGIN
speed_trial speed2-update1 5000 stmt $sql
db eval COMMIT

# 50000 single-row updates.  An index is used to find the row quickly.
#
set sql {}
for {set i 0} {$i<50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "UPDATE t1 SET b=$r WHERE a=$i;"
}
db eval BEGIN
speed_trial speed2-update2 50000 row $sql
db eval COMMIT

# 1 big text update that touches every row in the table.
#
speed_trial speed2-update3 50000 row {
  UPDATE t1 SET c=a;
}

# Many individual text updates.  Each row in the table is
# touched through an index.
#
set sql {}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  append sql "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;"
}
db eval BEGIN
speed_trial speed2-update4 50000 row $sql
db eval COMMIT

# Delete all content in a table.
#
speed_trial speed2-delete1 50000 row {DELETE FROM t1}

# Copy one table into another
#
speed_trial speed2-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Delete all content in a table, one row at a time.
#
speed_trial speed2-delete2 50000 row {DELETE FROM t1 WHERE 1}

# Refill the table yet again
#
speed_trial speed2-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Drop the table and recreate it without its indices.
#
db eval BEGIN
speed_trial speed2-drop1 50000 row {
   DROP TABLE t1;
   CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
}
db eval COMMIT

# Refill the table yet again.  This copy should be faster because
# there are no indices to deal with.
#
speed_trial speed2-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2}

# Select 20000 rows from the table at random.
#
speed_trial speed2-random1 50000 row {
  SELECT rowid FROM t1 ORDER BY random() LIMIT 20000
}

# Delete 20000 random rows from the table.
#
speed_trial speed2-random-del1 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed2-1.1 {
  db one {SELECT count(*) FROM t1}
} 30000

    
# Delete 20000 more rows at random from the table.
#
speed_trial speed2-random-del2 20000 row {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)
}
do_test speed2-1.2 {
  db one {SELECT count(*) FROM t1}
} 10000
speed_trial_summary speed2


finish_test

Added test/speed3.test.

























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# 2007 May 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library. The 
# focus of this script is testing that the overflow-page related
# enhancements added after version 3.3.17 speed things up.
#
# $Id: speed3.test,v 1.6 2009/07/09 02:48:24 shane Exp $
#

#---------------------------------------------------------------------
# Test plan:
#
# If auto-vacuum is enabled for the database, the following cases
# should show performance improvement with respect to 3.3.17.
#
#   + When deleting rows that span overflow pages. This is faster
#     because the overflow pages no longer need to be read before
#     they can be moved to the free list (test cases speed3-1.X). 
#
#   + When reading a column value stored on an overflow page that
#     is not the first overflow page for the row. The improvement
#     in this case is because the overflow pages between the tree
#     page and the overflow page containing the value do not have
#     to be read (test cases speed3-2.X).
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !tclvar||!attach {
  finish_test
  return
}

speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

set ::NROW 1000

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

proc populate_t1 {db} {
  $db transaction {
    for {set ii 0} {$ii < $::NROW} {incr ii} {
      set N [number_name $ii]
      set repeats [expr {(10000/[string length $N])+1}]
      set text [string range [string repeat $N $repeats] 0 10000]
      $db eval {INSERT INTO main.t1 VALUES($ii, $text, $ii)}
    }
    $db eval {INSERT INTO aux.t1 SELECT * FROM main.t1}
  }
}


proc io_log {db} {
  db_enter db
  array set stats1 [btree_pager_stats [btree_from_db db]]
  array set stats2 [btree_pager_stats [btree_from_db db 2]]
  db_leave db
# puts "1: [array get stats1]"
# puts "2: [array get stats2]"
  puts "Incrvacuum: Read $stats1(read), wrote $stats1(write)"
  puts "Normal    : Read $stats2(read), wrote $stats2(write)"
}

proc reset_db {} {
  db close
  sqlite3 db test.db
  db eval { 
    PRAGMA main.cache_size = 200000;
    PRAGMA main.auto_vacuum = 'incremental';
    ATTACH 'test2.db' AS 'aux'; 
    PRAGMA aux.auto_vacuum = 'none';
  }
}

file delete -force test2.db test2.db-journal
reset_db

# Set up a database in auto-vacuum mode and create a database schema.
#
do_test speed3-0.1 {
  execsql {
    CREATE TABLE main.t1(a INTEGER, b TEXT, c INTEGER);
  }
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1;
  }
} {t1}
do_test speed3-0.2 {
  execsql {
    CREATE TABLE aux.t1(a INTEGER, b TEXT, c INTEGER);
  }
  execsql {
    SELECT name FROM aux.sqlite_master ORDER BY 1;
  }
} {t1}
do_test speed3-0.3 {
  populate_t1 db
  execsql {
    SELECT count(*) FROM main.t1;
    SELECT count(*) FROM aux.t1;
  }
} "$::NROW $::NROW"
do_test speed3-0.4 {
  execsql {
    PRAGMA main.auto_vacuum;
    PRAGMA aux.auto_vacuum;
  }
} {2 0}

# Delete all content in a table, one row at a time.
#
#io_log db
reset_db
speed_trial speed3-1.incrvacuum $::NROW row {DELETE FROM main.t1 WHERE 1}
speed_trial speed3-1.normal     $::NROW row {DELETE FROM aux.t1 WHERE 1}
io_log db

# Select the "C" column (located at the far end of the overflow 
# chain) from each table row.
#
#db eval {PRAGMA incremental_vacuum(500000)}
populate_t1 db
reset_db
speed_trial speed3-2.incrvacuum $::NROW row {SELECT c FROM main.t1}
speed_trial speed3-2.normal     $::NROW row {SELECT c FROM aux.t1}
io_log db

finish_test

Added test/speed4.test.















































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# 2007 October 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed. More specifically,
# the focus is on the speed of:
#
#   * joins
#   * views
#   * sub-selects
#   * triggers
#
# $Id: speed4.test,v 1.2 2008/07/12 14:52:20 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

set sqlout [open speed1.txt w]
proc tracesql {sql} {
  puts $::sqlout $sql\;
}
#db trace tracesql

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Summary of tests:
#
#   speed4-join1: Join three tables using IPK index.
#   speed4-join2: Join three tables using an index.
#   speed4-join3: Join two tables without an index.
#
#   speed4-view1:  Querying a view.
#   speed4-table1: Same queries as in speed4-view1, but run directly against
#                  the tables for comparison purposes.
#
#   speed4-subselect1: A SELECT statement that uses many sub-queries..
#
#   speed4-trigger1: An INSERT statement that fires a trigger.
#   speed4-trigger2: An UPDATE statement that fires a trigger.
#   speed4-trigger3: A DELETE statement that fires a trigger.
#   speed4-notrigger1: Same operation as trigger1, but without the trigger.
#   speed4-notrigger2:        "          trigger2           "
#   speed4-notrigger3:        "          trigger3           "
#

# Set up the schema. Each of the tables t1, t2 and t3 contain 50,000 rows.
# This creates a database of around 16MB.
execsql {
  BEGIN;
  CREATE TABLE t1(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TABLE t2(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TABLE t3(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);

  CREATE VIEW v1 AS SELECT rowid, i, t FROM t1;
  CREATE VIEW v2 AS SELECT rowid, i, t FROM t2;
  CREATE VIEW v3 AS SELECT rowid, i, t FROM t3;
}
for {set jj 1} {$jj <= 3} {incr jj} {
  set stmt [string map "%T% t$jj" {INSERT INTO %T% VALUES(NULL, $i, $t)}]
  for {set ii 0} {$ii < 50000} {incr ii} {
    set i [expr {int(rand()*50000)}]
    set t [number_name $i]
    execsql $stmt
  }
}
execsql {
  CREATE INDEX i1 ON t1(t);
  CREATE INDEX i2 ON t2(t);
  CREATE INDEX i3 ON t3(t);
  COMMIT;
}

# Before running these tests, disable the compiled statement cache built into
# the Tcl interface. This is because we want to test the speed of SQL
# compilation as well as execution.
#
db cache size 0

# Join t1, t2, t3 on IPK.
set sql "SELECT * FROM t1, t2, t3 WHERE t1.oid = t2.oid AND t2.oid = t3.oid"
speed_trial speed4-join1 50000 row $sql

# Join t1, t2, t3 on the non-IPK index.
set sql "SELECT * FROM t1, t2, t3 WHERE t1.t = t2.t AND t2.t = t3.t"
speed_trial speed4-join2 50000 row $sql

# Run 10000 simple queries against the views.
set sql ""
for {set ii 1} {$ii < 10000} {incr ii} {
  append sql "SELECT * FROM v[expr {($ii%3)+1}] WHERE rowid = [expr {$ii*3}];"
}
speed_trial speed4-view1 10000 stmt $sql

# Run the same 10000 simple queries as in the previous test case against
# the underlying tables. The compiled vdbe programs should be identical, so
# the only difference in running time is the extra time taken to compile
# the view definitions.
#
set sql ""
for {set ii 1} {$ii < 10000} {incr ii} {
  append sql "SELECT t FROM t[expr {($ii%3)+1}] WHERE rowid = [expr {$ii*3}];"
}
speed_trial speed4-table1 10000 stmt $sql

# Run a SELECT that uses sub-queries 10000 times. A total of 30000 sub-selects.
#
set sql ""
for {set ii 1} {$ii < 10000} {incr ii} {
  append sql "
    SELECT (SELECT t FROM t1 WHERE rowid = [expr {$ii*3}]), 
           (SELECT t FROM t2 WHERE rowid = [expr {$ii*3}]), 
           (SELECT t FROM t3 WHERE rowid = [expr {$ii*3}])
  ;"
}
speed_trial speed4-subselect1 10000 stmt $sql

# The following block tests the speed of some DML statements that cause
# triggers to fire.
#
execsql {
  CREATE TABLE log(op TEXT, r INTEGER, i INTEGER, t TEXT);
  CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TRIGGER t4_trigger1 AFTER INSERT ON t4 BEGIN
    INSERT INTO log VALUES('INSERT INTO t4', new.rowid, new.i, new.t);
  END;
  CREATE TRIGGER t4_trigger2 AFTER UPDATE ON t4 BEGIN
    INSERT INTO log VALUES('UPDATE OF t4', new.rowid, new.i, new.t);
  END;
  CREATE TRIGGER t4_trigger3 AFTER DELETE ON t4 BEGIN
    INSERT INTO log VALUES('DELETE OF t4', old.rowid, old.i, old.t);
  END;
  BEGIN;
}
set sql ""
for {set ii 1} {$ii < 10000} {incr ii} {
  append sql "INSERT INTO t4 VALUES(NULL, $ii, '[number_name $ii]');"
}
speed_trial speed4-trigger1 10000 stmt $sql
set sql ""
for {set ii 1} {$ii < 20000} {incr ii 2} {
  set ii2 [expr {$ii*2}]
  append sql "
    UPDATE t4 SET i = $ii2, t = '[number_name $ii2]' WHERE rowid = $ii;
  "
}
speed_trial speed4-trigger2 10000 stmt $sql
set sql ""
for {set ii 1} {$ii < 20000} {incr ii 2} {
  append sql "DELETE FROM t4 WHERE rowid = $ii;"
}
speed_trial speed4-trigger3 10000 stmt $sql
execsql {COMMIT}

# The following block contains the same tests as the above block that
# tests triggers, with one crucial difference: no triggers are defined.
# So the difference in speed between these tests and the preceding ones
# is the amount of time taken to compile and execute the trigger programs.
#
execsql {
  DROP TABLE t4;
  DROP TABLE log;
  VACUUM;
  CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  BEGIN;
}
set sql ""
for {set ii 1} {$ii < 10000} {incr ii} {
  append sql "INSERT INTO t4 VALUES(NULL, $ii, '[number_name $ii]');"
}
speed_trial speed4-notrigger1 10000 stmt $sql
set sql ""
for {set ii 1} {$ii < 20000} {incr ii 2} {
  set ii2 [expr {$ii*2}]
  append sql "
    UPDATE t4 SET i = $ii2, t = '[number_name $ii2]' WHERE rowid = $ii;
  "
}
speed_trial speed4-notrigger2 10000 stmt $sql
set sql ""
for {set ii 1} {$ii < 20000} {incr ii 2} {
  append sql "DELETE FROM t4 WHERE rowid = $ii;"
}
speed_trial speed4-notrigger3 10000 stmt $sql
execsql {COMMIT}

speed_trial_summary speed4
finish_test

Added test/speed4p.explain.























































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# 2007 October 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed. More specifically,
# the focus is on the speed of:
#
#   * joins
#   * views
#   * sub-selects
#   * triggers
#
# $Id: speed4p.explain,v 1.1 2008/04/16 12:57:48 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

set sqlout [open speed1.txt w]
proc tracesql {sql} {
  puts $::sqlout $sql\;
}
#db trace tracesql

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Summary of tests:
#
#   speed4p-join1: Join three tables using IPK index.
#   speed4p-join2: Join three tables using an index.
#   speed4p-join3: Join two tables without an index.
#
#   speed4p-view1:  Querying a view.
#   speed4p-table1: Same queries as in speed4p-view1, but run directly against
#                  the tables for comparison purposes.
#
#   speed4p-subselect1: A SELECT statement that uses many sub-queries..
#
#   speed4p-trigger1: An INSERT statement that fires a trigger.
#   speed4p-trigger2: An UPDATE statement that fires a trigger.
#   speed4p-trigger3: A DELETE statement that fires a trigger.
#   speed4p-notrigger1: Same operation as trigger1, but without the trigger.
#   speed4p-notrigger2:        "          trigger2           "
#   speed4p-notrigger3:        "          trigger3           "
#

# Set up the schema. Each of the tables t1, t2 and t3 contain 50,000 rows.
# This creates a database of around 16MB.
execsql {
  PRAGMA page_size=1024;
  PRAGMA cache_size=8192;
  PRAGMA locking_mode=EXCLUSIVE;
  BEGIN;
  CREATE TABLE t1(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TABLE t2(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TABLE t3(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);

  CREATE VIEW v1 AS SELECT rowid, i, t FROM t1;
  CREATE VIEW v2 AS SELECT rowid, i, t FROM t2;
  CREATE VIEW v3 AS SELECT rowid, i, t FROM t3;
}
for {set jj 1} {$jj <= 3} {incr jj} {
  set stmt [string map "%T% t$jj" {INSERT INTO %T% VALUES(NULL, $i, $t)}]
  for {set ii 0} {$ii < 50000} {incr ii} {
    set i [expr {int(rand()*50000)}]
    set t [number_name $i]
    execsql $stmt
  }
}
execsql {
  CREATE INDEX i1 ON t1(t);
  CREATE INDEX i2 ON t2(t);
  CREATE INDEX i3 ON t3(t);
  COMMIT;
}

# Before running these tests, disable the compiled statement cache built into
# the Tcl interface. This is because we want to test the speed of SQL
# compilation as well as execution.
#
db cache size 0

# Join t1, t2, t3 on IPK.
set sql "SELECT * FROM t1, t2, t3 WHERE t1.oid = t2.oid AND t2.oid = t3.oid"
explain $sql
speed_trial speed4p-join1 50000 row $sql

# Join t1, t2, t3 on the non-IPK index.
set sql "SELECT * FROM t1, t2, t3 WHERE t1.t = t2.t AND t2.t = t3.t"
explain $sql
speed_trial speed4p-join2 50000 row $sql

# Run 10000 simple queries against the views.
set script {
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    set t [expr {$ii%3+1}]
    db eval "SELECT * FROM v$t WHERE rowid = \$v"
  }
}
explain {SELECT * FROm v1 WHERE rowid=$v}
speed_trial_tcl speed4p-view1 10000 stmt $script

# Run the same 10000 simple queries as in the previous test case against
# the underlying tables. The compiled vdbe programs should be identical, so
# the only difference in running time is the extra time taken to compile
# the view definitions.
#
set script {
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    set t [expr {$ii%3+1}]
    db eval "SELECT t FROM t$t WHERE rowid = \$v"
  }
}
explain {SELECT * FROM t1 WHERE rowid=$v}
speed_trial_tcl speed4p-table1 10000 stmt $script

# Run a SELECT that uses sub-queries 10000 times. A total of 30000 sub-selects.
#
set script {
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    db eval {
      SELECT (SELECT t FROM t1 WHERE rowid = $v), 
             (SELECT t FROM t2 WHERE rowid = $v), 
             (SELECT t FROM t3 WHERE rowid = $v)
    }
  }
}
explain {
      SELECT (SELECT t FROM t1 WHERE rowid = $v), 
             (SELECT t FROM t2 WHERE rowid = $v), 
             (SELECT t FROM t3 WHERE rowid = $v)
}
speed_trial_tcl speed4p-subselect1 10000 stmt $script

# The following block tests the speed of some DML statements that cause
# triggers to fire.
#
execsql {
  CREATE TABLE log(op TEXT, r INTEGER, i INTEGER, t TEXT);
  CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TRIGGER t4_trigger1 AFTER INSERT ON t4 BEGIN
    INSERT INTO log VALUES('INSERT INTO t4', new.rowid, new.i, new.t);
  END;
  CREATE TRIGGER t4_trigger2 AFTER UPDATE ON t4 BEGIN
    INSERT INTO log VALUES('UPDATE OF t4', new.rowid, new.i, new.t);
  END;
  CREATE TRIGGER t4_trigger3 AFTER DELETE ON t4 BEGIN
    INSERT INTO log VALUES('DELETE OF t4', old.rowid, old.i, old.t);
  END;
  BEGIN;
}
set list {}
for {set ii 1} {$ii < 10000} {incr ii} {
  lappend list $ii [number_name $ii]
}
set script {
  foreach {ii name} $::list {
    db eval {INSERT INTO t4 VALUES(NULL, $ii, $name)}
  }
}
explain {INSERT INTO t4 VALUES(NULL, $ii, $name)}
speed_trial_tcl speed4p-trigger1 10000 stmt $script

set list {}
for {set ii 1} {$ii < 20000} {incr ii 2} {
  set ii2 [expr {$ii*2}]
  lappend list $ii $ii2 [number_name $ii2]
}
set script {
  foreach {ii ii2 name} $::list {
    db eval {
      UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii;
    }
  }
}
explain {UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii}
speed_trial_tcl speed4p-trigger2 10000 stmt $script

set script {
  for {set ii 1} {$ii < 20000} {incr ii 2} {
    db eval {DELETE FROM t4 WHERE rowid = $ii}
  }
}
explain {DELETE FROM t4 WHERE rowid = $ii}
speed_trial_tcl speed4p-trigger3 10000 stmt $script
execsql {COMMIT}

# The following block contains the same tests as the above block that
# tests triggers, with one crucial difference: no triggers are defined.
# So the difference in speed between these tests and the preceding ones
# is the amount of time taken to compile and execute the trigger programs.
#
execsql {
  DROP TABLE t4;
  DROP TABLE log;
  VACUUM;
  CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  BEGIN;
}
set list {}
for {set ii 1} {$ii < 10000} {incr ii} {
  lappend list $ii [number_name $ii]
}
set script {
  foreach {ii name} $::list {
    db eval {INSERT INTO t4 VALUES(NULL, $ii, $name);}
  }
}
explain {INSERT INTO t4 VALUES(NULL, $ii, $name)}
speed_trial_tcl speed4p-notrigger1 10000 stmt $script

set list {}
for {set ii 1} {$ii < 20000} {incr ii 2} {
  set ii2 [expr {$ii*2}]
  lappend list $ii $ii2 [number_name $ii2]
}
set script {
  foreach {ii ii2 name} $::list {
    db eval {
      UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii;
    }
  }
}
explain {UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii}
speed_trial_tcl speed4p-notrigger2 10000 stmt $script

set script {
  for {set ii 1} {$ii < 20000} {incr ii 2} {
    db eval {DELETE FROM t4 WHERE rowid = $ii}
  }
}
explain {DELETE FROM t4 WHERE rowid = $ii}
speed_trial_tcl speed4p-notrigger3 10000 stmt $script
execsql {COMMIT}

speed_trial_summary speed4
finish_test

Added test/speed4p.test.









































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# 2007 October 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is measuring executing speed. More specifically,
# the focus is on the speed of:
#
#   * joins
#   * views
#   * sub-selects
#   * triggers
#
# $Id: speed4p.test,v 1.4 2008/04/10 13:32:37 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
speed_trial_init speed1

# Set a uniform random seed
expr srand(0)

set sqlout [open speed1.txt w]
proc tracesql {sql} {
  puts $::sqlout $sql\;
}
#db trace tracesql

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Summary of tests:
#
#   speed4p-join1: Join three tables using IPK index.
#   speed4p-join2: Join three tables using an index.
#   speed4p-join3: Join two tables without an index.
#
#   speed4p-view1:  Querying a view.
#   speed4p-table1: Same queries as in speed4p-view1, but run directly against
#                  the tables for comparison purposes.
#
#   speed4p-subselect1: A SELECT statement that uses many sub-queries..
#
#   speed4p-trigger1: An INSERT statement that fires a trigger.
#   speed4p-trigger2: An UPDATE statement that fires a trigger.
#   speed4p-trigger3: A DELETE statement that fires a trigger.
#   speed4p-notrigger1: Same operation as trigger1, but without the trigger.
#   speed4p-notrigger2:        "          trigger2           "
#   speed4p-notrigger3:        "          trigger3           "
#

# Set up the schema. Each of the tables t1, t2 and t3 contain 50,000 rows.
# This creates a database of around 16MB.
execsql {
  PRAGMA page_size=1024;
  PRAGMA cache_size=8192;
  PRAGMA locking_mode=EXCLUSIVE;
  BEGIN;
  CREATE TABLE t1(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TABLE t2(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TABLE t3(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);

  CREATE VIEW v1 AS SELECT rowid, i, t FROM t1;
  CREATE VIEW v2 AS SELECT rowid, i, t FROM t2;
  CREATE VIEW v3 AS SELECT rowid, i, t FROM t3;
}
for {set jj 1} {$jj <= 3} {incr jj} {
  set stmt [string map "%T% t$jj" {INSERT INTO %T% VALUES(NULL, $i, $t)}]
  for {set ii 0} {$ii < 50000} {incr ii} {
    set i [expr {int(rand()*50000)}]
    set t [number_name $i]
    execsql $stmt
  }
}
execsql {
  CREATE INDEX i1 ON t1(t);
  CREATE INDEX i2 ON t2(t);
  CREATE INDEX i3 ON t3(t);
  COMMIT;
}

# Join t1, t2, t3 on IPK.
set sql "SELECT * FROM t1, t2, t3 WHERE t1.oid = t2.oid AND t2.oid = t3.oid"
speed_trial speed4p-join1 50000 row $sql

# Join t1, t2, t3 on the non-IPK index.
set sql "SELECT * FROM t1, t2, t3 WHERE t1.t = t2.t AND t2.t = t3.t"
speed_trial speed4p-join2 50000 row $sql

# Run 10000 simple queries against the views.
set script {
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    set t [expr {$ii%3+1}]
    db eval "SELECT * FROM v$t WHERE rowid = \$v"
  }
}
speed_trial_tcl speed4p-view1 10000 stmt $script

# Run the same 10000 simple queries as in the previous test case against
# the underlying tables. The compiled vdbe programs should be identical, so
# the only difference in running time is the extra time taken to compile
# the view definitions.
#
set script {
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    set t [expr {$ii%3+1}]
    db eval "SELECT t FROM t$t WHERE rowid = \$v"
  }
}
speed_trial_tcl speed4p-table1 10000 stmt $script

# Run a SELECT that uses sub-queries 10000 times. A total of 30000 sub-selects.
#
set script {
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    db eval {
      SELECT (SELECT t FROM t1 WHERE rowid = $v), 
             (SELECT t FROM t2 WHERE rowid = $v), 
             (SELECT t FROM t3 WHERE rowid = $v)
    }
  }
}
speed_trial_tcl speed4p-subselect1 10000 stmt $script

# Single-row updates performance.
#
set script {
  db eval BEGIN
  for {set ii 1} {$ii < 10000} {incr ii} {
    set v [expr {$ii*3}]
    db eval {UPDATE t1 SET i=i+1 WHERE rowid=$ii}
  }
  db eval COMMIT
}
speed_trial_tcl speed4p-rowid-update 10000 stmt $script


db eval {
   CREATE TABLE t5(t TEXT PRIMARY KEY, i INTEGER);
}
speed_trial speed4p-insert-ignore 50000 row {
  INSERT OR IGNORE INTO t5 SELECT t, i FROM t1;
}

set list [db eval {SELECT t FROM t5}]
set script {
  db eval BEGIN
  foreach t $::list {
    db eval {UPDATE t5 SET i=i+1 WHERE t=$t}
  }
  db eval COMMIT
}
speed_trial_tcl speed4p-unique-update [llength $list] stmt $script

# The following block tests the speed of some DML statements that cause
# triggers to fire.
#
execsql {
  CREATE TABLE log(op TEXT, r INTEGER, i INTEGER, t TEXT);
  CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  CREATE TRIGGER t4_trigger1 AFTER INSERT ON t4 BEGIN
    INSERT INTO log VALUES('INSERT INTO t4', new.rowid, new.i, new.t);
  END;
  CREATE TRIGGER t4_trigger2 AFTER UPDATE ON t4 BEGIN
    INSERT INTO log VALUES('UPDATE OF t4', new.rowid, new.i, new.t);
  END;
  CREATE TRIGGER t4_trigger3 AFTER DELETE ON t4 BEGIN
    INSERT INTO log VALUES('DELETE OF t4', old.rowid, old.i, old.t);
  END;
  BEGIN;
}
set list {}
for {set ii 1} {$ii < 10000} {incr ii} {
  lappend list $ii [number_name $ii]
}
set script {
  foreach {ii name} $::list {
    db eval {INSERT INTO t4 VALUES(NULL, $ii, $name)}
  }
}
speed_trial_tcl speed4p-trigger1 10000 stmt $script

set list {}
for {set ii 1} {$ii < 20000} {incr ii 2} {
  set ii2 [expr {$ii*2}]
  lappend list $ii $ii2 [number_name $ii2]
}
set script {
  foreach {ii ii2 name} $::list {
    db eval {
      UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii;
    }
  }
}
speed_trial_tcl speed4p-trigger2 10000 stmt $script

set script {
  for {set ii 1} {$ii < 20000} {incr ii 2} {
    db eval {DELETE FROM t4 WHERE rowid = $ii}
  }
}
speed_trial_tcl speed4p-trigger3 10000 stmt $script
execsql {COMMIT}

# The following block contains the same tests as the above block that
# tests triggers, with one crucial difference: no triggers are defined.
# So the difference in speed between these tests and the preceding ones
# is the amount of time taken to compile and execute the trigger programs.
#
execsql {
  DROP TABLE t4;
  DROP TABLE log;
  VACUUM;
  CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT);
  BEGIN;
}
set list {}
for {set ii 1} {$ii < 10000} {incr ii} {
  lappend list $ii [number_name $ii]
}
set script {
  foreach {ii name} $::list {
    db eval {INSERT INTO t4 VALUES(NULL, $ii, $name);}
  }
}
speed_trial_tcl speed4p-notrigger1 10000 stmt $script

set list {}
for {set ii 1} {$ii < 20000} {incr ii 2} {
  set ii2 [expr {$ii*2}]
  lappend list $ii $ii2 [number_name $ii2]
}
set script {
  foreach {ii ii2 name} $::list {
    db eval {
      UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii;
    }
  }
}
speed_trial_tcl speed4p-notrigger2 10000 stmt $script

set script {
  for {set ii 1} {$ii < 20000} {incr ii 2} {
    db eval {DELETE FROM t4 WHERE rowid = $ii}
  }
}
speed_trial_tcl speed4p-notrigger3 10000 stmt $script
execsql {COMMIT}

speed_trial_summary speed4
finish_test

Added test/sqllimits1.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# 2007 May 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file contains tests to verify that the limits defined in
# sqlite source file limits.h are enforced.
#
# $Id: sqllimits1.test,v 1.33 2009/06/25 01:47:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Verify that the default per-connection limits are the same as
# the compile-time hard limits.
#
sqlite3 db2 :memory:
do_test sqllimits1-1.1 {
  sqlite3_limit db SQLITE_LIMIT_LENGTH -1
} $SQLITE_MAX_LENGTH
do_test sqllimits1-1.2 {
  sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH -1
} $SQLITE_MAX_SQL_LENGTH
do_test sqllimits1-1.3 {
  sqlite3_limit db SQLITE_LIMIT_COLUMN -1
} $SQLITE_MAX_COLUMN
do_test sqllimits1-1.4 {
  sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH -1
} $SQLITE_MAX_EXPR_DEPTH
do_test sqllimits1-1.5 {
  sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT -1
} $SQLITE_MAX_COMPOUND_SELECT
do_test sqllimits1-1.6 {
  sqlite3_limit db SQLITE_LIMIT_VDBE_OP -1
} $SQLITE_MAX_VDBE_OP
do_test sqllimits1-1.7 {
  sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1
} $SQLITE_MAX_FUNCTION_ARG
do_test sqllimits1-1.8 {
  sqlite3_limit db SQLITE_LIMIT_ATTACHED -1
} $SQLITE_MAX_ATTACHED
do_test sqllimits1-1.9 {
  sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1
} $SQLITE_MAX_LIKE_PATTERN_LENGTH
do_test sqllimits1-1.10 {
  sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER -1
} $SQLITE_MAX_VARIABLE_NUMBER

# Limit parameters out of range.
#
do_test sqllimits1-1.20 {
  sqlite3_limit db SQLITE_LIMIT_TOOSMALL 123
} {-1}
do_test sqllimits1-1.21 {
  sqlite3_limit db SQLITE_LIMIT_TOOSMALL 123
} {-1}
do_test sqllimits1-1.22 {
  sqlite3_limit db SQLITE_LIMIT_TOOBIG 123
} {-1}
do_test sqllimits1-1.23 {
  sqlite3_limit db SQLITE_LIMIT_TOOBIG 123
} {-1}


# Decrease all limits by half.  Verify that the new limits take.
#
if {$SQLITE_MAX_LENGTH>=2} {
  do_test sqllimits1-2.1.1 {
    sqlite3_limit db SQLITE_LIMIT_LENGTH \
                    [expr {$::SQLITE_MAX_LENGTH/2}]
  } $SQLITE_MAX_LENGTH
  do_test sqllimits1-2.1.2 {
    sqlite3_limit db SQLITE_LIMIT_LENGTH -1
  } [expr {$SQLITE_MAX_LENGTH/2}]
}
if {$SQLITE_MAX_SQL_LENGTH>=2} {
  do_test sqllimits1-2.2.1 {
    sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH \
                    [expr {$::SQLITE_MAX_SQL_LENGTH/2}]
  } $SQLITE_MAX_SQL_LENGTH
  do_test sqllimits1-2.2.2 {
    sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH -1
  } [expr {$SQLITE_MAX_SQL_LENGTH/2}]
}
if {$SQLITE_MAX_COLUMN>=2} {
  do_test sqllimits1-2.3.1 {
    sqlite3_limit db SQLITE_LIMIT_COLUMN \
                    [expr {$::SQLITE_MAX_COLUMN/2}]
  } $SQLITE_MAX_COLUMN
  do_test sqllimits1-2.3.2 {
    sqlite3_limit db SQLITE_LIMIT_COLUMN -1
  } [expr {$SQLITE_MAX_COLUMN/2}]
}
if {$SQLITE_MAX_EXPR_DEPTH>=2} {
  do_test sqllimits1-2.4.1 {
    sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH \
                    [expr {$::SQLITE_MAX_EXPR_DEPTH/2}]
  } $SQLITE_MAX_EXPR_DEPTH
  do_test sqllimits1-2.4.2 {
    sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH -1
  } [expr {$SQLITE_MAX_EXPR_DEPTH/2}]
}
if {$SQLITE_MAX_COMPOUND_SELECT>=2} {
  do_test sqllimits1-2.5.1 {
    sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT \
                    [expr {$::SQLITE_MAX_COMPOUND_SELECT/2}]
  } $SQLITE_MAX_COMPOUND_SELECT
  do_test sqllimits1-2.5.2 {
    sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT -1
  } [expr {$SQLITE_MAX_COMPOUND_SELECT/2}]
}
if {$SQLITE_MAX_VDBE_OP>=2} {
  do_test sqllimits1-2.6.1 {
    sqlite3_limit db SQLITE_LIMIT_VDBE_OP \
                    [expr {$::SQLITE_MAX_VDBE_OP/2}]
  } $SQLITE_MAX_VDBE_OP
  do_test sqllimits1-2.6.2 {
    sqlite3_limit db SQLITE_LIMIT_VDBE_OP -1
  } [expr {$SQLITE_MAX_VDBE_OP/2}]
}
if {$SQLITE_MAX_FUNCTION_ARG>=2} {
  do_test sqllimits1-2.7.1 {
    sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG \
                    [expr {$::SQLITE_MAX_FUNCTION_ARG/2}]
  } $SQLITE_MAX_FUNCTION_ARG
  do_test sqllimits1-2.7.2 {
    sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1
  } [expr {$SQLITE_MAX_FUNCTION_ARG/2}]
}
if {$SQLITE_MAX_ATTACHED>=2} {
  do_test sqllimits1-2.8.1 {
    sqlite3_limit db SQLITE_LIMIT_ATTACHED \
                    [expr {$::SQLITE_MAX_ATTACHED/2}]
  } $SQLITE_MAX_ATTACHED
  do_test sqllimits1-2.8.2 {
    sqlite3_limit db SQLITE_LIMIT_ATTACHED -1
  } [expr {$SQLITE_MAX_ATTACHED/2}]
}
if {$SQLITE_MAX_LIKE_PATTERN_LENGTH>=2} {
  do_test sqllimits1-2.9.1 {
    sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH \
                    [expr {$::SQLITE_MAX_LIKE_PATTERN_LENGTH/2}]
  } $SQLITE_MAX_LIKE_PATTERN_LENGTH
  do_test sqllimits1-2.9.2 {
    sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1
  } [expr {$SQLITE_MAX_LIKE_PATTERN_LENGTH/2}]
}
if {$SQLITE_MAX_VARIABLE_NUMBER>=2} {
  do_test sqllimits1-2.10.1 {
    sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER \
                    [expr {$::SQLITE_MAX_VARIABLE_NUMBER/2}]
  } $SQLITE_MAX_VARIABLE_NUMBER
  do_test sqllimits1-2.10.2 {
    sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER -1
  } [expr {$SQLITE_MAX_VARIABLE_NUMBER/2}]
}

# In a separate database connection, verify that the limits are unchanged.
#
do_test sqllimits1-3.1 {
  sqlite3_limit db2 SQLITE_LIMIT_LENGTH -1
} $SQLITE_MAX_LENGTH
do_test sqllimits1-3.2 {
  sqlite3_limit db2 SQLITE_LIMIT_SQL_LENGTH -1
} $SQLITE_MAX_SQL_LENGTH
do_test sqllimits1-3.3 {
  sqlite3_limit db2 SQLITE_LIMIT_COLUMN -1
} $SQLITE_MAX_COLUMN
do_test sqllimits1-3.4 {
  sqlite3_limit db2 SQLITE_LIMIT_EXPR_DEPTH -1
} $SQLITE_MAX_EXPR_DEPTH
do_test sqllimits1-3.5 {
  sqlite3_limit db2 SQLITE_LIMIT_COMPOUND_SELECT -1
} $SQLITE_MAX_COMPOUND_SELECT
do_test sqllimits1-3.6 {
  sqlite3_limit db2 SQLITE_LIMIT_VDBE_OP -1
} $SQLITE_MAX_VDBE_OP
do_test sqllimits1-3.7 {
  sqlite3_limit db2 SQLITE_LIMIT_FUNCTION_ARG -1
} $SQLITE_MAX_FUNCTION_ARG
do_test sqllimits1-3.8 {
  sqlite3_limit db2 SQLITE_LIMIT_ATTACHED -1
} $SQLITE_MAX_ATTACHED
do_test sqllimits1-3.9 {
  sqlite3_limit db2 SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1
} $SQLITE_MAX_LIKE_PATTERN_LENGTH
do_test sqllimits1-3.10 {
  sqlite3_limit db2 SQLITE_LIMIT_VARIABLE_NUMBER -1
} $SQLITE_MAX_VARIABLE_NUMBER
db2 close

# Attempt to set all limits to the maximum 32-bit integer.  Verify
# that the limit does not exceed the compile-time upper bound.
#
do_test sqllimits1-4.1.1 {
  sqlite3_limit db SQLITE_LIMIT_LENGTH 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_LENGTH -1
} $SQLITE_MAX_LENGTH
do_test sqllimits1-4.2.1 {
  sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH -1
} $SQLITE_MAX_SQL_LENGTH
do_test sqllimits1-4.3.1 {
  sqlite3_limit db SQLITE_LIMIT_COLUMN 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_COLUMN -1
} $SQLITE_MAX_COLUMN
do_test sqllimits1-4.4.1 {
  sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH -1
} $SQLITE_MAX_EXPR_DEPTH
do_test sqllimits1-4.5.1 {
  sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT -1
} $SQLITE_MAX_COMPOUND_SELECT
do_test sqllimits1-4.6.1 {
  sqlite3_limit db SQLITE_LIMIT_VDBE_OP 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_VDBE_OP -1
} $SQLITE_MAX_VDBE_OP
do_test sqllimits1-4.7.1 {
  sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1
} $SQLITE_MAX_FUNCTION_ARG
do_test sqllimits1-4.8.1 {
  sqlite3_limit db SQLITE_LIMIT_ATTACHED 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_ATTACHED -1
} $SQLITE_MAX_ATTACHED
do_test sqllimits1-4.9.1 {
  sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1
} $SQLITE_MAX_LIKE_PATTERN_LENGTH
do_test sqllimits1-4.10.1 {
  sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER 0x7fffffff
  sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER -1
} $SQLITE_MAX_VARIABLE_NUMBER

#--------------------------------------------------------------------
# Test cases sqllimits1-5.* test that the SQLITE_MAX_LENGTH limit
# is enforced.
#
db close
sqlite3 db test.db
set LARGESIZE 99999
set SQLITE_LIMIT_LENGTH 100000
sqlite3_limit db SQLITE_LIMIT_LENGTH $SQLITE_LIMIT_LENGTH

do_test sqllimits1-5.1.1 {
  catchsql { SELECT randomblob(2147483647) }
} {1 {string or blob too big}}
do_test sqllimits1-5.1.2 {
  catchsql { SELECT zeroblob(2147483647) }
} {1 {string or blob too big}}

do_test sqllimits1-5.2 {
  catchsql { SELECT LENGTH(randomblob($::LARGESIZE)) }
} [list 0 $LARGESIZE]

do_test sqllimits1-5.3 {
  catchsql { SELECT quote(randomblob($::LARGESIZE)) }
} {1 {string or blob too big}}

do_test sqllimits1-5.4 {
  catchsql { SELECT LENGTH(zeroblob($::LARGESIZE)) }
} [list 0 $LARGESIZE]

do_test sqllimits1-5.5 {
  catchsql { SELECT quote(zeroblob($::LARGESIZE)) }
} {1 {string or blob too big}}

do_test sqllimits1-5.6 {
  catchsql { SELECT zeroblob(-1) }
} {0 {{}}}

do_test sqllimits1-5.9 {
  set ::str [string repeat A 65537]
  set ::rep [string repeat B 65537]
  catchsql { SELECT replace($::str, 'A', $::rep) }
} {1 {string or blob too big}}

do_test sqllimits1-5.10 {
  set ::str [string repeat %J 2100]
  catchsql { SELECT strftime($::str, '2003-10-31') }
} {1 {string or blob too big}}

do_test sqllimits1-5.11 {
  set ::str1 [string repeat A [expr {$SQLITE_LIMIT_LENGTH - 10}]]
  set ::str2 [string repeat B [expr {$SQLITE_LIMIT_LENGTH - 10}]]
  catchsql { SELECT $::str1 || $::str2 }
} {1 {string or blob too big}}

do_test sqllimits1-5.12 {
  set ::str1 [string repeat ' [expr {$SQLITE_LIMIT_LENGTH - 10}]]
  catchsql { SELECT quote($::str1) }
} {1 {string or blob too big}}

do_test sqllimits1-5.13 {
  set ::str1 [string repeat ' [expr {$SQLITE_LIMIT_LENGTH - 10}]]
  catchsql { SELECT hex($::str1) }
} {1 {string or blob too big}}

do_test sqllimits1-5.14.1 {
  set ::STMT [sqlite3_prepare db "SELECT ?" -1 TAIL]
  sqlite3_bind_zeroblob $::STMT 1 [expr {$SQLITE_LIMIT_LENGTH + 1}]
} {}
do_test sqllimits1-5.14.2 {
  sqlite3_step $::STMT 
} {SQLITE_ERROR}
do_test sqllimits1-5.14.3 {
  sqlite3_reset $::STMT 
} {SQLITE_TOOBIG}
do_test sqllimits1-5.14.4 {
  set np1 [expr {$SQLITE_LIMIT_LENGTH + 1}]
  set ::str1 [string repeat A $np1]
  catch {sqlite3_bind_text $::STMT 1 $::str1 -1} res
  set res
} {SQLITE_TOOBIG}
do_test sqllimits1-5.14.5 {
  catch {sqlite3_bind_text16 $::STMT 1 $::str1 -1} res
  set res
} {SQLITE_TOOBIG}
do_test sqllimits1-5.14.6 {
  catch {sqlite3_bind_text $::STMT 1 $::str1 $np1} res
  set res
} {SQLITE_TOOBIG}
do_test sqllimits1-5.14.7 {
  catch {sqlite3_bind_text16 $::STMT 1 $::str1 $np1} res
  set res
} {SQLITE_TOOBIG}
do_test sqllimits1-5.14.8 {
  set n [expr {$np1-1}]
  catch {sqlite3_bind_text $::STMT 1 $::str1 $n} res
  set res
} {}
do_test sqllimits1-5.14.9 {
  catch {sqlite3_bind_text16 $::STMT 1 $::str1 $n} res
  set res
} {}
sqlite3_finalize $::STMT 

do_test sqllimits1-5.15 {
  execsql {
    CREATE TABLE t4(x);
    INSERT INTO t4 VALUES(1);
    INSERT INTO t4 VALUES(2);
    INSERT INTO t4 SELECT 2+x FROM t4;
  }
  catchsql {
    SELECT group_concat(hex(randomblob(20000))) FROM t4;
  }
} {1 {string or blob too big}}
db eval {DROP TABLE t4}

sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 0x7fffffff
set strvalue [string repeat A $::SQLITE_LIMIT_LENGTH]
do_test sqllimits1-5.16 {
  catchsql "SELECT '$strvalue'"
} [list 0 $strvalue]
do_test sqllimits1-5.17.1 {
  catchsql "SELECT 'A$strvalue'"
} [list 1 {string or blob too big}]
do_test sqllimits1-5.17.2 {
  sqlite3_limit db SQLITE_LIMIT_LENGTH 0x7fffffff
  catchsql {SELECT 'A' || $::strvalue}
} [list 0 A$strvalue]
do_test sqllimits1-5.17.3 {
  sqlite3_limit db SQLITE_LIMIT_LENGTH $SQLITE_LIMIT_LENGTH
  catchsql {SELECT 'A' || $::strvalue}
} [list 1 {string or blob too big}]
set blobvalue [string repeat 41 $::SQLITE_LIMIT_LENGTH]
do_test sqllimits1-5.18 {
  catchsql "SELECT x'$blobvalue'"
} [list 0 $strvalue]
do_test sqllimits1-5.19 {
  catchsql "SELECT '41$blobvalue'"
} [list 1 {string or blob too big}]
unset blobvalue

ifcapable datetime {
  set strvalue [string repeat D [expr {$SQLITE_LIMIT_LENGTH-12}]]
  do_test sqllimits1-5.20 {
    catchsql {SELECT strftime('%Y ' || $::strvalue, '2008-01-02')}
  } [list 0 [list "2008 $strvalue"]]
  do_test sqllimits1-5.21 {
    catchsql {SELECT strftime('%Y-%m-%d ' || $::strvalue, '2008-01-02')}
  } {1 {string or blob too big}}
}
unset strvalue

#--------------------------------------------------------------------
# Test cases sqllimits1-6.* test that the SQLITE_MAX_SQL_LENGTH limit
# is enforced.
#
do_test sqllimits1-6.1 {
  sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 50000
  set sql "SELECT 1 WHERE 1==1"
  set tail " /* A comment to take up space in order to make the string\
                longer without increasing the expression depth */\
                AND   1  ==  1"
  set N [expr {(50000 / [string length $tail])+1}]
  append sql [string repeat $tail $N]
  catchsql $sql
} {1 {string or blob too big}}
do_test sqllimits1-6.3 {
  sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 50000
  set sql "SELECT 1 WHERE 1==1"
  set tail " /* A comment to take up space in order to make the string\
                longer without increasing the expression depth */\
                AND   1  ==  1"
  set N [expr {(50000 / [string length $tail])+1}]
  append sql [string repeat $tail $N]
  set nbytes [string length $sql]
  append sql { AND 0}
  set rc [catch {sqlite3_prepare db $sql $nbytes TAIL} STMT]
  lappend rc $STMT
} {1 {(18) statement too long}}
do_test sqllimits1-6.4 {
  sqlite3_errmsg db
} {statement too long}

#--------------------------------------------------------------------
# Test cases sqllimits1-7.* test that the limit set using the
# max_page_count pragma.
#
do_test sqllimits1-7.1 {
  execsql {
    PRAGMA max_page_count = 1000;
  }
} {1000}
do_test sqllimits1-7.2 {
  execsql { CREATE TABLE trig (a INTEGER, b INTEGER); }

  # Set up a tree of triggers to fire when a row is inserted
  # into table "trig".
  #
  # INSERT -> insert_b -> update_b -> insert_a -> update_a      (chain 1)
  #                    -> update_a -> insert_a -> update_b      (chain 2)
  #        -> insert_a -> update_b -> insert_b -> update_a      (chain 3)
  #                    -> update_a -> insert_b -> update_b      (chain 4)
  #
  # Table starts with N rows.
  #
  #   Chain 1: insert_b (update N rows)
  #              -> update_b (insert 1 rows)
  #                -> insert_a (update N rows)
  #                  -> update_a (insert 1 rows)
  #
  # chains 2, 3 and 4 are similar. Each inserts more than N^2 rows, where
  # N is the number of rows at the conclusion of the previous chain.
  #
  # Therefore, a single insert adds (N^16 plus some) rows to the database.
  # A really long loop...
  #     
  execsql {
    CREATE TRIGGER update_b BEFORE UPDATE ON trig
      FOR EACH ROW BEGIN
        INSERT INTO trig VALUES (65, 'update_b');
      END;

    CREATE TRIGGER update_a AFTER UPDATE ON trig
      FOR EACH ROW BEGIN
        INSERT INTO trig VALUES (65, 'update_a');
      END;

    CREATE TRIGGER insert_b BEFORE INSERT ON trig
      FOR EACH ROW BEGIN
        UPDATE trig SET a = 1;
      END;

    CREATE TRIGGER insert_a AFTER INSERT ON trig
      FOR EACH ROW BEGIN
        UPDATE trig SET a = 1;
      END;
  }
} {}

do_test sqllimits1-7.3 {
  execsql {
    INSERT INTO trig VALUES (1,1); 
  }
} {}

do_test sqllimits1-7.4 {
  execsql {
    SELECT COUNT(*) FROM trig;
  }
} {7}

# This tries to insert so many rows it fills up the database (limited
# to 1MB, so not that noteworthy an achievement).
#
do_test sqllimits1-7.5 {
  catchsql {
    INSERT INTO trig VALUES (1,10);
  }
} {1 {database or disk is full}}

do_test sqllimits1-7.6 {
  catchsql {
    SELECT COUNT(*) FROM trig;
  }
} {0 7}

# Now check the response of the library to opening a file larger than
# the current max_page_count value. The response is to change the
# internal max_page_count value to match the actual size of the file.
if {[db eval {PRAGMA auto_vacuum}]} {
   set fsize 1700
} else {
   set fsize 1691
}
do_test sqllimits1-7.7.1 {
  execsql {
    PRAGMA max_page_count = 1000000;
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc;
    INSERT INTO abc SELECT a, b, c FROM abc;
    INSERT INTO abc SELECT b, a, c FROM abc;
    INSERT INTO abc SELECT c, b, a FROM abc;
  }
  expr [file size test.db] / 1024
} $fsize
do_test sqllimits1-7.7.2 {
  db close
  sqlite3 db test.db
  execsql {
    PRAGMA max_page_count = 1000;
  }
  execsql {
    SELECT count(*) FROM sqlite_master;
  }
} {6}
do_test sqllimits1-7.7.3 {
  execsql {
    PRAGMA max_page_count;
  }
} $fsize
do_test sqllimits1-7.7.4 {
  execsql {
    DROP TABLE abc;
  }
} {}

#--------------------------------------------------------------------
# Test cases sqllimits1-8.* test the SQLITE_MAX_COLUMN limit.
#
set SQLITE_LIMIT_COLUMN 200
sqlite3_limit db SQLITE_LIMIT_COLUMN $SQLITE_LIMIT_COLUMN
do_test sqllimits1-8.1 {
  # Columns in a table.
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols "c$i"
  }
  catchsql "CREATE TABLE t([join $cols ,])" 
} {1 {too many columns on t}}

do_test sqllimits1-8.2 {
  # Columns in the result-set of a SELECT.
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols "sql AS sql$i"
  }
  catchsql "SELECT [join $cols ,] FROM sqlite_master"
} {1 {too many columns in result set}}

do_test sqllimits1-8.3 {
  # Columns in the result-set of a sub-SELECT.
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols "sql AS sql$i"
  }
  catchsql "SELECT sql4 FROM (SELECT [join $cols ,] FROM sqlite_master)"
} {1 {too many columns in result set}}

do_test sqllimits1-8.4 {
  # Columns in an index.
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols c
  }
  set sql1 "CREATE TABLE t1(c);"
  set sql2 "CREATE INDEX i1 ON t1([join $cols ,]);"
  catchsql "$sql1 ; $sql2"
} {1 {too many columns in index}}

do_test sqllimits1-8.5 {
  # Columns in a GROUP BY clause.
  catchsql "SELECT * FROM t1 GROUP BY [join $cols ,]"
} {1 {too many terms in GROUP BY clause}}

do_test sqllimits1-8.6 {
  # Columns in an ORDER BY clause.
  catchsql "SELECT * FROM t1 ORDER BY [join $cols ,]"
} {1 {too many terms in ORDER BY clause}}

do_test sqllimits1-8.7 {
  # Assignments in an UPDATE statement.
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols "c = 1"
  }
  catchsql "UPDATE t1 SET [join $cols ,];"
} {1 {too many columns in set list}}

do_test sqllimits1-8.8 {
  # Columns in a view definition:
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols "c$i"
  }
  catchsql "CREATE VIEW v1 AS SELECT [join $cols ,] FROM t1;"
} {1 {too many columns in result set}}

do_test sqllimits1-8.9 {
  # Columns in a view definition (testing * expansion):
  set cols [list]
  for {set i 0} {$i < $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols "c$i"
  }
  catchsql "CREATE TABLE t2([join $cols ,])"
  catchsql "CREATE VIEW v1 AS SELECT *, c1 AS o FROM t2;"
} {1 {too many columns in result set}}
do_test sqllimits1-8.10 {
  # ORDER BY columns
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols c
  }
  set sql "SELECT c FROM t1 ORDER BY [join $cols ,]"
  catchsql $sql
} {1 {too many terms in ORDER BY clause}}
do_test sqllimits1-8.11 {
  # ORDER BY columns
  set cols [list]
  for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} {
    lappend cols [expr {$i%3 + 1}]
  }
  set sql "SELECT c, c+1, c+2 FROM t1 UNION SELECT c-1, c-2, c-3 FROM t1"
  append sql " ORDER BY [join $cols ,]"
  catchsql $sql
} {1 {too many terms in ORDER BY clause}}


#--------------------------------------------------------------------
# These tests - sqllimits1-9.* - test that the SQLITE_LIMIT_EXPR_DEPTH
# limit is enforced. The limit refers to the number of terms in 
# the expression.
#
if {$SQLITE_MAX_EXPR_DEPTH==0} {
  puts -nonewline stderr "WARNING: Compile with -DSQLITE_MAX_EXPR_DEPTH to run "
  puts stderr "tests sqllimits1-9.X"
} else {
  do_test sqllimits1-9.1 {
    set max $::SQLITE_MAX_EXPR_DEPTH
    set expr "(1 [string repeat {AND 1 } $max])"
    catchsql [subst {
      SELECT $expr
    }]
  } "1 {Expression tree is too large (maximum depth $::SQLITE_MAX_EXPR_DEPTH)}"
  
  # Attempting to beat the expression depth limit using nested SELECT
  # queries causes a parser stack overflow. 
  do_test sqllimits1-9.2 {
    set max $::SQLITE_MAX_EXPR_DEPTH
    set expr "SELECT 1"
    for {set i 0} {$i <= $max} {incr i} {
      set expr "SELECT ($expr)"
    }
    catchsql [subst { $expr }]
  } "1 {parser stack overflow}"
  
if 0 {  
  do_test sqllimits1-9.3 {
    execsql {
      PRAGMA max_page_count = 1000000;  -- 1 GB
      CREATE TABLE v0(a);
      INSERT INTO v0 VALUES(1);
    }
    db transaction {
      for {set i 1} {$i < 200} {incr i} {
        set expr "(a [string repeat {AND 1 } 50]) AS a"
        execsql [subst {
          CREATE VIEW v${i} AS SELECT $expr FROM v[expr {$i-1}]
        }]
      }
    }
  } {}
  
  do_test sqllimits1-9.4 {
    catchsql {
      SELECT a FROM v199
    }
  } "1 {Expression tree is too large (maximum depth $::SQLITE_MAX_EXPR_DEPTH)}"
}
}

#--------------------------------------------------------------------
# Test cases sqllimits1-10.* test that the SQLITE_MAX_VDBE_OP
# limit works as expected. The limit refers to the number of opcodes
# in a single VDBE program.
#
# TODO

#--------------------------------------------------------------------
# Test the SQLITE_LIMIT_FUNCTION_ARG limit works. Test case names
# match the pattern "sqllimits1-11.*".
#
for {set max 5} {$max<=$SQLITE_MAX_FUNCTION_ARG} {incr max} {
  do_test sqllimits1-11.$max.1 {
    set vals [list]
    sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG $::max
    for {set i 0} {$i < $::max} {incr i} {
      lappend vals $i
    }
    catchsql "SELECT max([join $vals ,])"
  } "0 [expr {$::max - 1}]"
  do_test sqllimits1-11.$max.2 {
    set vals [list]
    for {set i 0} {$i <= $::max} {incr i} {
      lappend vals $i
    }
    catchsql "SELECT max([join $vals ,])"
  } {1 {too many arguments on function max}}

  # Test that it is SQLite, and not the implementation of the
  # user function that is throwing the error.
  proc myfunc {args} {error "I don't like to be called!"}
  do_test sqllimits1-11.$max.2 {
    db function myfunc myfunc
    set vals [list]
    for {set i 0} {$i <= $::max} {incr i} {
      lappend vals $i
    }
    catchsql "SELECT myfunc([join $vals ,])"
  } {1 {too many arguments on function myfunc}}
}

#--------------------------------------------------------------------
# Test cases sqllimits1-12.*: Test the SQLITE_MAX_ATTACHED limit.
#
ifcapable attach {
  do_test sqllimits1-12.1 {
    set max $::SQLITE_MAX_ATTACHED
    for {set i 0} {$i < ($max)} {incr i} {
      file delete -force test${i}.db test${i}.db-journal
    }
    for {set i 0} {$i < ($max)} {incr i} {
      execsql "ATTACH 'test${i}.db' AS aux${i}"
    }
    catchsql "ATTACH 'test${i}.db' AS aux${i}"
  } "1 {too many attached databases - max $::SQLITE_MAX_ATTACHED}"
  do_test sqllimits1-12.2 {
    set max $::SQLITE_MAX_ATTACHED
    for {set i 0} {$i < ($max)} {incr i} {
      execsql "DETACH aux${i}"
    }
  } {}
}

#--------------------------------------------------------------------
# Test cases sqllimits1-13.*: Check that the SQLITE_MAX_VARIABLE_NUMBER 
# limit works.
#
do_test sqllimits1-13.1 {
  set max $::SQLITE_MAX_VARIABLE_NUMBER
  catchsql "SELECT ?[expr {$max+1}] FROM t1"
} "1 {variable number must be between ?1 and ?$::SQLITE_MAX_VARIABLE_NUMBER}"
do_test sqllimits1-13.2 {
  set max $::SQLITE_MAX_VARIABLE_NUMBER
  set vals [list]
  for {set i 0} {$i < ($max+3)} {incr i} {
    lappend vals ?
  }
  catchsql "SELECT [join $vals ,] FROM t1"
} "1 {too many SQL variables}"


#--------------------------------------------------------------------
# Test cases sqllimits1-15.* verify that the 
# SQLITE_MAX_LIKE_PATTERN_LENGTH limit is enforced. This limit only
# applies to the built-in LIKE operator, supplying an external 
# implementation by overriding the like() scalar function bypasses
# this limitation.
#
# These tests check that the limit is not incorrectly applied to
# the left-hand-side of the LIKE operator (the string being tested
# against the pattern).
#
set SQLITE_LIMIT_LIKE_PATTERN 1000
sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH $SQLITE_LIMIT_LIKE_PATTERN
do_test sqllimits1-15.1 {
  set max $::SQLITE_LIMIT_LIKE_PATTERN
  set ::pattern [string repeat "A%" [expr $max/2]]
  set ::string  [string repeat "A" [expr {$max*2}]]
  execsql {
    SELECT $::string LIKE $::pattern;
  }
} {1}
do_test sqllimits1-15.2 {
  set max $::SQLITE_LIMIT_LIKE_PATTERN
  set ::pattern [string repeat "A%" [expr {($max/2) + 1}]]
  set ::string  [string repeat "A" [expr {$max*2}]]
  catchsql {
    SELECT $::string LIKE $::pattern;
  }
} {1 {LIKE or GLOB pattern too complex}}

#--------------------------------------------------------------------
# This test case doesn't really belong with the other limits tests.
# It is in this file because it is taxing to run, like the limits tests.
#
do_test sqllimits1-16.1 {
  set ::N [expr int(([expr pow(2,32)]/50) + 1)]
  expr (($::N*50) & 0xffffffff)<55
} {1}
do_test sqllimits1-16.2 {
  set ::format "[string repeat A 60][string repeat "%J" $::N]"
  catchsql {
    SELECT strftime($::format, 1);
  }
} {1 {string or blob too big}}


foreach {key value} [array get saved] {
  catch {set $key $value}
}
finish_test

Added test/subquery.test.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# 2005 January 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is testing correlated subqueries
#
# $Id: subquery.test,v 1.17 2009/01/09 01:12:28 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

do_test subquery-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    INSERT INTO t1 VALUES(5,6);
    INSERT INTO t1 VALUES(7,8);
    CREATE TABLE t2(x,y);
    INSERT INTO t2 VALUES(1,1);
    INSERT INTO t2 VALUES(3,9);
    INSERT INTO t2 VALUES(5,25);
    INSERT INTO t2 VALUES(7,49);
    COMMIT;
  }
  execsql {
    SELECT a, (SELECT y FROM t2 WHERE x=a) FROM t1 WHERE b<8
  }
} {1 1 3 9 5 25}
do_test subquery-1.2 {
  execsql {
    UPDATE t1 SET b=b+(SELECT y FROM t2 WHERE x=a);
    SELECT * FROM t1;
  }
} {1 3 3 13 5 31 7 57}

do_test subquery-1.3 {
  execsql {
    SELECT b FROM t1 WHERE EXISTS(SELECT * FROM t2 WHERE y=a)
  }
} {3}
do_test subquery-1.4 {
  execsql {
    SELECT b FROM t1 WHERE NOT EXISTS(SELECT * FROM t2 WHERE y=a)
  }
} {13 31 57}

# Simple tests to make sure correlated subqueries in WHERE clauses
# are used by the query optimizer correctly.
do_test subquery-1.5 {
  execsql {
    SELECT a, x FROM t1, t2 WHERE t1.a = (SELECT x);
  }
} {1 1 3 3 5 5 7 7}
do_test subquery-1.6 {
  execsql {
    CREATE INDEX i1 ON t1(a);
    SELECT a, x FROM t1, t2 WHERE t1.a = (SELECT x);
  }
} {1 1 3 3 5 5 7 7}
do_test subquery-1.7 {
  execsql {
    SELECT a, x FROM t2, t1 WHERE t1.a = (SELECT x);
  }
} {1 1 3 3 5 5 7 7}

# Try an aggregate in both the subquery and the parent query.
do_test subquery-1.8 {
  execsql {
    SELECT count(*) FROM t1 WHERE a > (SELECT count(*) FROM t2);
  }
} {2}

# Test a correlated subquery disables the "only open the index" optimization.
do_test subquery-1.9.1 {
  execsql {
    SELECT (y*2)>b FROM t1, t2 WHERE a=x;
  }
} {0 1 1 1}
do_test subquery-1.9.2 {
  execsql {
    SELECT a FROM t1 WHERE (SELECT (y*2)>b FROM t2 WHERE a=x); 
  }
} {3 5 7}

# Test that the flattening optimization works with subquery expressions.
do_test subquery-1.10.1 {
  execsql {
    SELECT (SELECT a), b FROM t1;
  }
} {1 3 3 13 5 31 7 57}
do_test subquery-1.10.2 {
  execsql {
    SELECT * FROM (SELECT (SELECT a), b FROM t1);
  }
} {1 3 3 13 5 31 7 57}
do_test subquery-1.10.3 {
  execsql {
    SELECT * FROM (SELECT (SELECT sum(a) FROM t1));
  }
} {16}
do_test subquery-1.10.4 {
  execsql {
    CREATE TABLE t5 (val int, period text PRIMARY KEY);
    INSERT INTO t5 VALUES(5, '2001-3');
    INSERT INTO t5 VALUES(10, '2001-4');
    INSERT INTO t5 VALUES(15, '2002-1');
    INSERT INTO t5 VALUES(5, '2002-2');
    INSERT INTO t5 VALUES(10, '2002-3');
    INSERT INTO t5 VALUES(15, '2002-4');
    INSERT INTO t5 VALUES(10, '2003-1');
    INSERT INTO t5 VALUES(5, '2003-2');
    INSERT INTO t5 VALUES(25, '2003-3');
    INSERT INTO t5 VALUES(5, '2003-4');

    SELECT period, vsum
    FROM (SELECT 
      a.period,
      (select sum(val) from t5 where period between a.period and '2002-4') vsum
      FROM t5 a where a.period between '2002-1' and '2002-4')
    WHERE vsum < 45 ;
  }
} {2002-2 30 2002-3 25 2002-4 15}
do_test subquery-1.10.5 {
  execsql {
    SELECT period, vsum from
      (select a.period,
      (select sum(val) from t5 where period between a.period and '2002-4') vsum
    FROM t5 a where a.period between '2002-1' and '2002-4') 
    WHERE vsum < 45 ;
  }
} {2002-2 30 2002-3 25 2002-4 15}
do_test subquery-1.10.6 {
  execsql {
    DROP TABLE t5;
  }
} {}



#------------------------------------------------------------------
# The following test cases - subquery-2.* - are not logically
# organized. They're here largely because they were failing during
# one stage of development of sub-queries.
#
do_test subquery-2.1 {
  execsql {
    SELECT (SELECT 10);
  }
} {10}
do_test subquery-2.2.1 {
  execsql {
    CREATE TABLE t3(a PRIMARY KEY, b);
    INSERT INTO t3 VALUES(1, 2);
    INSERT INTO t3 VALUES(3, 1);
  }
} {}
do_test subquery-2.2.2 {
  execsql {
    SELECT * FROM t3 WHERE a IN (SELECT b FROM t3);
  }
} {1 2}
do_test subquery-2.2.3 {
  execsql {
    DROP TABLE t3;
  }
} {}
do_test subquery-2.3.1 {
  execsql {
    CREATE TABLE t3(a TEXT);
    INSERT INTO t3 VALUES('10');
  }
} {}
do_test subquery-2.3.2 {
  execsql {
    SELECT a IN (10.0, 20) FROM t3;
  }
} {0}
do_test subquery-2.3.3 {
  execsql {
    DROP TABLE t3;
  }
} {}
do_test subquery-2.4.1 {
  execsql {
    CREATE TABLE t3(a TEXT);
    INSERT INTO t3 VALUES('XX');
  }
} {}
do_test subquery-2.4.2 {
  execsql {
    SELECT count(*) FROM t3 WHERE a IN (SELECT 'XX')
  }
} {1}
do_test subquery-2.4.3 {
  execsql {
    DROP TABLE t3;
  }
} {}
do_test subquery-2.5.1 {
  execsql {
    CREATE TABLE t3(a INTEGER);
    INSERT INTO t3 VALUES(10);

    CREATE TABLE t4(x TEXT);
    INSERT INTO t4 VALUES('10.0');
  }
} {}
do_test subquery-2.5.2 {
  # In the expr "x IN (SELECT a FROM t3)" the RHS of the IN operator
  # has text affinity and the LHS has integer affinity.  The rule is
  # that we try to convert both sides to an integer before doing the
  # comparision.  Hence, the integer value 10 in t3 will compare equal
  # to the string value '10.0' in t4 because the t4 value will be
  # converted into an integer.
  execsql {
    SELECT * FROM t4 WHERE x IN (SELECT a FROM t3);
  }
} {10.0}
do_test subquery-2.5.3.1 {
  # The t4i index cannot be used to resolve the "x IN (...)" constraint
  # because the constraint has integer affinity but t4i has text affinity.
  execsql {
    CREATE INDEX t4i ON t4(x);
    SELECT * FROM t4 WHERE x IN (SELECT a FROM t3);
  }
} {10.0}
do_test subquery-2.5.3.2 {
  # Verify that the t4i index was not used in the previous query
  set ::sqlite_query_plan
} {t4 {}}
do_test subquery-2.5.4 {
  execsql {
    DROP TABLE t3;
    DROP TABLE t4;
  }
} {}

#------------------------------------------------------------------
# The following test cases - subquery-3.* - test tickets that
# were raised during development of correlated subqueries.
#

# Ticket 1083
ifcapable view {
  do_test subquery-3.1 {
    catchsql { DROP TABLE t1; }
    catchsql { DROP TABLE t2; }
    execsql {
      CREATE TABLE t1(a,b);
      INSERT INTO t1 VALUES(1,2);
      CREATE VIEW v1 AS SELECT b FROM t1 WHERE a>0;
      CREATE TABLE t2(p,q);
      INSERT INTO t2 VALUES(2,9);
      SELECT * FROM v1 WHERE EXISTS(SELECT * FROM t2 WHERE p=v1.b);
    }
  } {2}
  do_test subquery-3.1.1 {
    execsql {
      SELECT * FROM v1 WHERE EXISTS(SELECT 1);
    }
  } {2}
} else {
  catchsql { DROP TABLE t1; }
  catchsql { DROP TABLE t2; }
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    CREATE TABLE t2(p,q);
    INSERT INTO t2 VALUES(2,9);
  }
}

# Ticket 1084
do_test subquery-3.2 {
  catchsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
  }
  execsql {
    SELECT (SELECT t1.a) FROM t1;
  }
} {1}

# Test Cases subquery-3.3.* test correlated subqueries where the
# parent query is an aggregate query. Ticket #1105 is an example
# of such a query.
#
do_test subquery-3.3.1 {
  execsql {
    SELECT a, (SELECT b) FROM t1 GROUP BY a;
  }
} {1 2}
do_test subquery-3.3.2 {
  catchsql {DROP TABLE t2}
  execsql {
    CREATE TABLE t2(c, d);
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(2, 'two');
    SELECT a, (SELECT d FROM t2 WHERE a=c) FROM t1 GROUP BY a;
  }
} {1 one}
do_test subquery-3.3.3 {
  execsql {
    INSERT INTO t1 VALUES(2, 4);
    SELECT max(a), (SELECT d FROM t2 WHERE a=c) FROM t1;
  }
} {2 two}
do_test subquery-3.3.4 {
  execsql {
    SELECT a, (SELECT (SELECT d FROM t2 WHERE a=c)) FROM t1 GROUP BY a;
  }
} {1 one 2 two}
do_test subquery-3.3.5 {
  execsql {
    SELECT a, (SELECT count(*) FROM t2 WHERE a=c) FROM t1;
  }
} {1 1 2 1}

#------------------------------------------------------------------
# These tests - subquery-4.* - use the TCL statement cache to try 
# and expose bugs to do with re-using statements that have been 
# passed to sqlite3_reset().
#
# One problem was that VDBE memory cells were not being initialised
# to NULL on the second and subsequent executions.
#
do_test subquery-4.1.1 {
  execsql {
    SELECT (SELECT a FROM t1);
  }
} {1}
do_test subquery-4.2 {
  execsql {
    DELETE FROM t1;
    SELECT (SELECT a FROM t1);
  }
} {{}}
do_test subquery-4.2.1 {
  execsql {
    CREATE TABLE t3(a PRIMARY KEY);
    INSERT INTO t3 VALUES(10);
  }
  execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1)}
} {}
do_test subquery-4.2.2 {
  execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1)}
} {}

#------------------------------------------------------------------
# The subquery-5.* tests make sure string literals in double-quotes
# are handled efficiently.  Double-quote literals are first checked
# to see if they match any column names.  If there is not column name
# match then those literals are used a string constants.  When a
# double-quoted string appears, we want to make sure that the search
# for a matching column name did not cause an otherwise static subquery
# to become a dynamic (correlated) subquery.
#
do_test subquery-5.1 {
  proc callcntproc {n} {
    incr ::callcnt
    return $n
  }
  set callcnt 0
  db function callcnt callcntproc
  execsql {
    CREATE TABLE t4(x,y);
    INSERT INTO t4 VALUES('one',1);
    INSERT INTO t4 VALUES('two',2);
    INSERT INTO t4 VALUES('three',3);
    INSERT INTO t4 VALUES('four',4);
    CREATE TABLE t5(a,b);
    INSERT INTO t5 VALUES(1,11);
    INSERT INTO t5 VALUES(2,22);
    INSERT INTO t5 VALUES(3,33);
    INSERT INTO t5 VALUES(4,44);
    SELECT b FROM t5 WHERE a IN 
       (SELECT callcnt(y)+0 FROM t4 WHERE x="two")
  }
} {22}
do_test subquery-5.2 {
  # This is the key test.  The subquery should have only run once.  If
  # The double-quoted identifier "two" were causing the subquery to be
  # processed as a correlated subquery, then it would have run 4 times.
  set callcnt
} {1}


# Ticket #1380.  Make sure correlated subqueries on an IN clause work
# correctly when the left-hand side of the IN operator is constant.
#
do_test subquery-6.1 {
  set callcnt 0
  execsql {
    SELECT x FROM t4 WHERE 1 IN (SELECT callcnt(count(*)) FROM t5 WHERE a=y)
  }
} {one two three four}
do_test subquery-6.2 {
  set callcnt
} {4}
do_test subquery-6.3 {
  set callcnt 0
  execsql {
    SELECT x FROM t4 WHERE 1 IN (SELECT callcnt(count(*)) FROM t5 WHERE a=1)
  }
} {one two three four}
do_test subquery-6.4 {
  set callcnt
} {1}

if 0 {   #############  disable until we get #2652 fixed
# Ticket #2652.  Allow aggregate functions of outer queries inside
# a non-aggregate subquery.
#
do_test subquery-7.1 {
  execsql {
    CREATE TABLE t7(c7);
    INSERT INTO t7 VALUES(1);
    INSERT INTO t7 VALUES(2);
    INSERT INTO t7 VALUES(3);
    CREATE TABLE t8(c8);
    INSERT INTO t8 VALUES(100);
    INSERT INTO t8 VALUES(200);
    INSERT INTO t8 VALUES(300);
    CREATE TABLE t9(c9);
    INSERT INTO t9 VALUES(10000);
    INSERT INTO t9 VALUES(20000);
    INSERT INTO t9 VALUES(30000);

    SELECT (SELECT c7+c8 FROM t7) FROM t8;
  }
} {101 201 301}
do_test subquery-7.2 {
  execsql {
    SELECT (SELECT max(c7)+c8 FROM t7) FROM t8;
  }
} {103 203 303}
do_test subquery-7.3 {
  execsql {
    SELECT (SELECT c7+max(c8) FROM t8) FROM t7
  }
} {301}
do_test subquery-7.4 {
  execsql {
    SELECT (SELECT max(c7)+max(c8) FROM t8) FROM t7
  }
} {303}
do_test subquery-7.5 {
  execsql {
    SELECT (SELECT c8 FROM t8 WHERE rowid=max(c7)) FROM t7
  }
} {300}
do_test subquery-7.6 {
  execsql {
    SELECT (SELECT (SELECT max(c7+c8+c9) FROM t9) FROM t8) FROM t7
  }
} {30101 30102 30103}
do_test subquery-7.7 {
  execsql {
    SELECT (SELECT (SELECT c7+max(c8+c9) FROM t9) FROM t8) FROM t7
  }
} {30101 30102 30103}
do_test subquery-7.8 {
  execsql {
    SELECT (SELECT (SELECT max(c7)+c8+c9 FROM t9) FROM t8) FROM t7
  }
} {10103}
do_test subquery-7.9 {
  execsql {
    SELECT (SELECT (SELECT c7+max(c8)+c9 FROM t9) FROM t8) FROM t7
  }
} {10301 10302 10303}
do_test subquery-7.10 {
  execsql {
    SELECT (SELECT (SELECT c7+c8+max(c9) FROM t9) FROM t8) FROM t7
  }
} {30101 30102 30103}
do_test subquery-7.11 {
  execsql {
    SELECT (SELECT (SELECT max(c7)+max(c8)+max(c9) FROM t9) FROM t8) FROM t7
  }
} {30303}
}  ;############# Disabled

finish_test

Added test/subselect.test.





































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing SELECT statements that are part of
# expressions.
#
# $Id: subselect.test,v 1.16 2008/08/04 03:51:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Omit this whole file if the library is build without subquery support.
ifcapable !subquery {
  finish_test
  return
}

# Basic sanity checking.  Try a simple subselect.
#
do_test subselect-1.1 {
  execsql {
    CREATE TABLE t1(a int, b int);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    INSERT INTO t1 VALUES(5,6);
  }
  execsql {SELECT * FROM t1 WHERE a = (SELECT count(*) FROM t1)}
} {3 4}

# Try a select with more than one result column.
#
do_test subselect-1.2 {
  set v [catch {execsql {SELECT * FROM t1 WHERE a = (SELECT * FROM t1)}} msg]
  lappend v $msg
} {1 {only a single result allowed for a SELECT that is part of an expression}}

# A subselect without an aggregate.
#
do_test subselect-1.3a {
  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=2)}
} {2}
do_test subselect-1.3b {
  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=4)}
} {4}
do_test subselect-1.3c {
  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=6)}
} {6}
do_test subselect-1.3d {
  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=8)}
} {}
ifcapable compound {
  do_test subselect-1.3e {
    execsql {
      SELECT b FROM t1
       WHERE a = (SELECT a FROM t1 UNION SELECT b FROM t1 ORDER BY 1);
    }
  } {2}
}

# What if the subselect doesn't return any value.  We should get
# NULL as the result.  Check it out.
#
do_test subselect-1.4 {
  execsql {SELECT b from t1 where a = coalesce((SELECT a FROM t1 WHERE b=5),1)}
} {2}

# Try multiple subselects within a single expression.
#
do_test subselect-1.5 {
  execsql {
    CREATE TABLE t2(x int, y int);
    INSERT INTO t2 VALUES(1,2);
    INSERT INTO t2 VALUES(2,4);
    INSERT INTO t2 VALUES(3,8);
    INSERT INTO t2 VALUES(4,16);
  }
  execsql {
    SELECT y from t2 
    WHERE x = (SELECT sum(b) FROM t1 where a notnull) - (SELECT sum(a) FROM t1)
  }
} {8}

# Try something useful.  Delete every entry from t2 where the
# x value is less than half of the maximum.
#
do_test subselect-1.6 {
  execsql {DELETE FROM t2 WHERE x < 0.5*(SELECT max(x) FROM t2)}
  execsql {SELECT x FROM t2 ORDER BY x}
} {2 3 4}

# Make sure sorting works for SELECTs there used as a scalar expression.
#
do_test subselect-2.1 {
  execsql {
    SELECT (SELECT a FROM t1 ORDER BY a), (SELECT a FROM t1 ORDER BY a DESC)
  }
} {1 5}
do_test subselect-2.2 {
  execsql {
    SELECT 1 IN (SELECT a FROM t1 ORDER BY a);
  }
} {1}
do_test subselect-2.3 {
  execsql {
    SELECT 2 IN (SELECT a FROM t1 ORDER BY a DESC);
  }
} {0}

# Verify that the ORDER BY clause is honored in a subquery.
#
ifcapable compound {
do_test subselect-3.1 {
  execsql {
    CREATE TABLE t3(x int);
    INSERT INTO t3 SELECT a FROM t1 UNION ALL SELECT b FROM t1;
    SELECT * FROM t3 ORDER BY x;
  }
} {1 2 3 4 5 6}
} ;# ifcapable compound
ifcapable !compound {
do_test subselect-3.1 {
  execsql {
    CREATE TABLE t3(x int);
    INSERT INTO t3 SELECT a FROM t1; 
    INSERT INTO t3 SELECT b FROM t1;
    SELECT * FROM t3 ORDER BY x;
  }
} {1 2 3 4 5 6}
} ;# ifcapable !compound

do_test subselect-3.2 {
  execsql {
    SELECT sum(x) FROM (SELECT x FROM t3 ORDER BY x LIMIT 2);
  }
} {3}
do_test subselect-3.3 {
  execsql {
    SELECT sum(x) FROM (SELECT x FROM t3 ORDER BY x DESC LIMIT 2);
  }
} {11}
do_test subselect-3.4 {
  execsql {
    SELECT (SELECT x FROM t3 ORDER BY x);
  }
} {1}
do_test subselect-3.5 {
  execsql {
    SELECT (SELECT x FROM t3 ORDER BY x DESC);
  }
} {6}
do_test subselect-3.6 {
  execsql {
    SELECT (SELECT x FROM t3 ORDER BY x LIMIT 1);
  }
} {1}
do_test subselect-3.7 {
  execsql {
    SELECT (SELECT x FROM t3 ORDER BY x DESC LIMIT 1);
  }
} {6}
do_test subselect-3.8 {
  execsql {
    SELECT (SELECT x FROM t3 ORDER BY x LIMIT 1 OFFSET 2);
  }
} {3}
do_test subselect-3.9 {
  execsql {
    SELECT (SELECT x FROM t3 ORDER BY x DESC LIMIT 1 OFFSET 2);
  }
} {4}
do_test subselect-3.10 {
  execsql {
    SELECT x FROM t3 WHERE x IN
       (SELECT x FROM t3 ORDER BY x DESC LIMIT 1 OFFSET 2);
  }
} {4}

# Ticket #2295.
# Make sure type affinities work correctly on subqueries with
# an ORDER BY clause.
#
do_test subselect-4.1 {
  execsql {
    CREATE TABLE t4(a TEXT, b TEXT);
    INSERT INTO t4 VALUES('a','1');
    INSERT INTO t4 VALUES('b','2');
    INSERT INTO t4 VALUES('c','3');
    SELECT a FROM t4 WHERE b IN (SELECT b FROM t4 ORDER BY b);
  }
} {a b c}
do_test subselect-4.2 {
  execsql {
    SELECT a FROM t4 WHERE b IN (SELECT b FROM t4 ORDER BY b LIMIT 1);
  }
} {a}
do_test subselect-4.3 {
  execsql {
    SELECT a FROM t4 WHERE b IN (SELECT b FROM t4 ORDER BY b DESC LIMIT 1);
  }
} {c}

finish_test

Added test/substr.test.































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# 2007 May 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the built-in SUBSTR() functions.
#
# $Id: substr.test,v 1.7 2009/02/03 13:10:54 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !tclvar {
  finish_test
  return
}

# Create a table to work with.
#
execsql { 
  CREATE TABLE t1(t text, b blob)
}
proc substr-test {id string i1 i2 result} {
  db eval {
    DELETE FROM t1;
    INSERT INTO t1(t) VALUES($string)
  }
  do_test substr-$id.1 [subst {
    execsql {
      SELECT substr(t, $i1, $i2) FROM t1
    }
  }] [list $result]
  set qstr '[string map {' ''} $string]'
  do_test substr-$id.2 [subst {
    execsql {
      SELECT substr($qstr, $i1, $i2)
    }
  }] [list $result]
}
proc subblob-test {id hex i1 i2 hexresult} {
  db eval "
    DELETE FROM t1;
    INSERT INTO t1(b) VALUES(x'$hex')
  "
  do_test substr-$id.1 [subst {
    execsql {
      SELECT hex(substr(b, $i1, $i2)) FROM t1
    }
  }] [list $hexresult]
  do_test substr-$id.2 [subst {
    execsql {
      SELECT hex(substr(x'$hex', $i1, $i2))
    }
  }] [list $hexresult]
}

# Basic SUBSTR functionality
#
substr-test 1.1 abcdefg 1 1 a
substr-test 1.2 abcdefg 2 1 b
substr-test 1.3 abcdefg 1 2 ab
substr-test 1.4 abcdefg 1 100 abcdefg
substr-test 1.5 abcdefg 0 2 a
substr-test 1.6 abcdefg -1 1 g
substr-test 1.7 abcdefg -1 10 g
substr-test 1.8 abcdefg -5 3 cde
substr-test 1.9 abcdefg -7 3 abc
substr-test 1.10 abcdefg -100 98 abcde
substr-test 1.11 abcdefg 5 -1 d
substr-test 1.12 abcdefg 5 -4 abcd
substr-test 1.13 abcdefg 5 -5 abcd
substr-test 1.14 abcdefg -5 -1 b
substr-test 1.15 abcdefg -5 -2 ab
substr-test 1.16 abcdefg -5 -3 ab
substr-test 1.17 abcdefg 100 200 {}
substr-test 1.18 abcdefg 200 100 {}

# Make sure NULL is returned if any parameter is NULL
#
do_test substr-1.90 {
  db eval {SELECT ifnull(substr(NULL,1,1),'nil')}
} nil
do_test substr-1.91 {
  db eval {SELECT ifnull(substr(NULL,1),'nil')}
} nil
do_test substr-1.92 {
  db eval {SELECT ifnull(substr('abcdefg',NULL,1),'nil')}
} nil
do_test substr-1.93 {
  db eval {SELECT ifnull(substr('abcdefg',NULL),'nil')}
} nil
do_test substr-1.94 {
  db eval {SELECT ifnull(substr('abcdefg',1,NULL),'nil')}
} nil

# Make sure everything works with long unicode characters
#
substr-test 2.1 \u1234\u2345\u3456 1 1 \u1234
substr-test 2.2 \u1234\u2345\u3456 2 1 \u2345
substr-test 2.3 \u1234\u2345\u3456 1 2 \u1234\u2345
substr-test 2.4 \u1234\u2345\u3456 -1 1 \u3456
substr-test 2.5 a\u1234b\u2345c\u3456c -5 3 b\u2345c
substr-test 2.6 a\u1234b\u2345c\u3456c -2 -3 b\u2345c

# Basic functionality for BLOBs
#
subblob-test 3.1 61626364656667 1 1 61
subblob-test 3.2 61626364656667 2 1 62
subblob-test 3.3 61626364656667 1 2 6162
subblob-test 3.4 61626364656667 1 100 61626364656667
subblob-test 3.5 61626364656667 0 2 61
subblob-test 3.6 61626364656667 -1 1 67
subblob-test 3.7 61626364656667 -1 10 67
subblob-test 3.8 61626364656667 -5 3 636465
subblob-test 3.9 61626364656667 -7 3 616263
subblob-test 3.10 61626364656667 -100 98 6162636465
subblob-test 3.11 61626364656667 100 200 {}
subblob-test 3.12 61626364656667 200 100 {}

# If these blobs were strings, then they would contain multi-byte
# characters.  But since they are blobs, the substr indices refer
# to bytes.
#
subblob-test 4.1 61E188B462E28D8563E3919663 1 1 61
subblob-test 4.2 61E188B462E28D8563E3919663 2 1 E1
subblob-test 4.3 61E188B462E28D8563E3919663 1 2 61E1
subblob-test 4.4 61E188B462E28D8563E3919663 -2 1 96
subblob-test 4.5 61E188B462E28D8563E3919663 -5 4 63E39196
subblob-test 4.6 61E188B462E28D8563E3919663 -100 98 61E188B462E28D8563E391 

# Two-argument SUBSTR
#
proc substr-2-test {id string idx result} {
  db eval {
    DELETE FROM t1;
    INSERT INTO t1(t) VALUES($string)
  }
  do_test substr-$id.1 [subst {
    execsql {
      SELECT substr(t, $idx) FROM t1
    }
  }] [list $result]
  set qstr '[string map {' ''} $string]'
  do_test substr-$id.2 [subst {
    execsql {
      SELECT substr($qstr, $idx)
    }
  }] [list $result]
}
substr-2-test 5.1 abcdefghijklmnop 5 efghijklmnop
substr-2-test 5.2 abcdef -5 bcdef

finish_test

Added test/sync.test.





































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# 2005 August 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that fsync is disabled when
# pragma synchronous=off even for multi-database commits.
#
# $Id: sync.test,v 1.6 2007/10/09 08:29:33 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

#
# These tests are only applicable on unix when pager pragma are
# enabled. Also, since every test uses an ATTACHed database, they
# are only run when ATTACH is enabled.
#
if {$::tcl_platform(platform)!="unix"} {
  finish_test
  return
}
ifcapable !pager_pragmas||!attach {
  finish_test
  return
}

do_test sync-1.1 {
  set sqlite_sync_count 0
  file delete -force test2.db
  file delete -force test2.db-journal
  execsql {
    PRAGMA fullfsync=OFF;
    CREATE TABLE t1(a,b);
    ATTACH DATABASE 'test2.db' AS db2;
    CREATE TABLE db2.t2(x,y);
  }
  ifcapable !dirsync {
    incr sqlite_sync_count 2
  }
  set sqlite_sync_count
} 8
ifcapable pager_pragmas {
  do_test sync-1.2 {
    set sqlite_sync_count 0
    execsql {
      PRAGMA main.synchronous=on;
      PRAGMA db2.synchronous=on;
      BEGIN;
      INSERT INTO t1 VALUES(1,2);
      INSERT INTO t2 VALUES(3,4);
      COMMIT;
    }
    ifcapable !dirsync {
      incr sqlite_sync_count 3
    }
    set sqlite_sync_count
  } 8
}
do_test sync-1.3 {
  set sqlite_sync_count 0
  execsql {
    PRAGMA main.synchronous=full;
    PRAGMA db2.synchronous=full;
    BEGIN;
    INSERT INTO t1 VALUES(3,4);
    INSERT INTO t2 VALUES(5,6);
    COMMIT;
  }
  ifcapable !dirsync {
    incr sqlite_sync_count 3
  }
  set sqlite_sync_count
} 10
ifcapable pager_pragmas {
  do_test sync-1.4 {
    set sqlite_sync_count 0
    execsql {
      PRAGMA main.synchronous=off;
      PRAGMA db2.synchronous=off;
      BEGIN;
      INSERT INTO t1 VALUES(5,6);
      INSERT INTO t2 VALUES(7,8);
      COMMIT;
    }
    set sqlite_sync_count
  } 0
}


finish_test

Added test/table.test.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CREATE TABLE statement.
#
# $Id: table.test,v 1.53 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a basic table and verify it is added to sqlite_master
#
do_test table-1.1 {
  execsql {
    CREATE TABLE test1 (
      one varchar(10),
      two text
    )
  }
  execsql {
    SELECT sql FROM sqlite_master WHERE type!='meta'
  }
} {{CREATE TABLE test1 (
      one varchar(10),
      two text
    )}}


# Verify the other fields of the sqlite_master file.
#
do_test table-1.3 {
  execsql {SELECT name, tbl_name, type FROM sqlite_master WHERE type!='meta'}
} {test1 test1 table}

# Close and reopen the database.  Verify that everything is
# still the same.
#
do_test table-1.4 {
  db close
  sqlite3 db test.db
  execsql {SELECT name, tbl_name, type from sqlite_master WHERE type!='meta'}
} {test1 test1 table}

# Drop the database and make sure it disappears.
#
do_test table-1.5 {
  execsql {DROP TABLE test1}
  execsql {SELECT * FROM sqlite_master WHERE type!='meta'}
} {}

# Close and reopen the database.  Verify that the table is
# still gone.
#
do_test table-1.6 {
  db close
  sqlite3 db test.db
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {}

# Repeat the above steps, but this time quote the table name.
#
do_test table-1.10 {
  execsql {CREATE TABLE "create" (f1 int)}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {create}
do_test table-1.11 {
  execsql {DROP TABLE "create"}
  execsql {SELECT name FROM "sqlite_master" WHERE type!='meta'}
} {}
do_test table-1.12 {
  execsql {CREATE TABLE test1("f1 ho" int)}
  execsql {SELECT name as "X" FROM sqlite_master WHERE type!='meta'}
} {test1}
do_test table-1.13 {
  execsql {DROP TABLE "TEST1"}
  execsql {SELECT name FROM "sqlite_master" WHERE type!='meta'}
} {}



# Verify that we cannot make two tables with the same name
#
do_test table-2.1 {
  execsql {CREATE TABLE TEST2(one text)}
  catchsql {CREATE TABLE test2(two text default 'hi')}
} {1 {table test2 already exists}}
do_test table-2.1.1 {
  catchsql {CREATE TABLE "test2" (two)}
} {1 {table "test2" already exists}}
do_test table-2.1b {
  set v [catch {execsql {CREATE TABLE sqlite_master(two text)}} msg]
  lappend v $msg
} {1 {object name reserved for internal use: sqlite_master}}
do_test table-2.1c {
  db close
  sqlite3 db test.db
  set v [catch {execsql {CREATE TABLE sqlite_master(two text)}} msg]
  lappend v $msg
} {1 {object name reserved for internal use: sqlite_master}}
do_test table-2.1d {
  catchsql {CREATE TABLE IF NOT EXISTS test2(x,y)}
} {0 {}}
do_test table-2.1e {
  catchsql {CREATE TABLE IF NOT EXISTS test2(x UNIQUE, y TEXT PRIMARY KEY)}
} {0 {}}
do_test table-2.1f {
  execsql {DROP TABLE test2; SELECT name FROM sqlite_master WHERE type!='meta'}
} {}

# Verify that we cannot make a table with the same name as an index
#
do_test table-2.2a {
  execsql {CREATE TABLE test2(one text)}
  execsql {CREATE INDEX test3 ON test2(one)}
  catchsql {CREATE TABLE test3(two text)}
} {1 {there is already an index named test3}}
do_test table-2.2b {
  db close
  sqlite3 db test.db
  set v [catch {execsql {CREATE TABLE test3(two text)}} msg]
  lappend v $msg
} {1 {there is already an index named test3}}
do_test table-2.2c {
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {test2 test3}
do_test table-2.2d {
  execsql {DROP INDEX test3}
  set v [catch {execsql {CREATE TABLE test3(two text)}} msg]
  lappend v $msg
} {0 {}}
do_test table-2.2e {
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {test2 test3}
do_test table-2.2f {
  execsql {DROP TABLE test2; DROP TABLE test3}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {}

# Create a table with many field names
#
set big_table \
{CREATE TABLE big(
  f1 varchar(20),
  f2 char(10),
  f3 varchar(30) primary key,
  f4 text,
  f5 text,
  f6 text,
  f7 text,
  f8 text,
  f9 text,
  f10 text,
  f11 text,
  f12 text,
  f13 text,
  f14 text,
  f15 text,
  f16 text,
  f17 text,
  f18 text,
  f19 text,
  f20 text
)}
do_test table-3.1 {
  execsql $big_table
  execsql {SELECT sql FROM sqlite_master WHERE type=='table'}
} \{$big_table\}
do_test table-3.2 {
  set v [catch {execsql {CREATE TABLE BIG(xyz foo)}} msg]
  lappend v $msg
} {1 {table BIG already exists}}
do_test table-3.3 {
  set v [catch {execsql {CREATE TABLE biG(xyz foo)}} msg]
  lappend v $msg
} {1 {table biG already exists}}
do_test table-3.4 {
  set v [catch {execsql {CREATE TABLE bIg(xyz foo)}} msg]
  lappend v $msg
} {1 {table bIg already exists}}
do_test table-3.5 {
  db close
  sqlite3 db test.db
  set v [catch {execsql {CREATE TABLE Big(xyz foo)}} msg]
  lappend v $msg
} {1 {table Big already exists}}
do_test table-3.6 {
  execsql {DROP TABLE big}
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {}

# Try creating large numbers of tables
#
set r {}
for {set i 1} {$i<=100} {incr i} {
  lappend r [format test%03d $i]
}
do_test table-4.1 {
  for {set i 1} {$i<=100} {incr i} {
    set sql "CREATE TABLE [format test%03d $i] ("
    for {set k 1} {$k<$i} {incr k} {
      append sql "field$k text,"
    }
    append sql "last_field text)"
    execsql $sql
  }
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} $r
do_test table-4.1b {
  db close
  sqlite3 db test.db
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} $r

# Drop the even numbered tables
#
set r {}
for {set i 1} {$i<=100} {incr i 2} {
  lappend r [format test%03d $i]
}
do_test table-4.2 {
  for {set i 2} {$i<=100} {incr i 2} {
    # if {$i==38} {execsql {pragma vdbe_trace=on}}
    set sql "DROP TABLE [format TEST%03d $i]"
    execsql $sql
  }
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} $r
#exit

# Drop the odd number tables
#
do_test table-4.3 {
  for {set i 1} {$i<=100} {incr i 2} {
    set sql "DROP TABLE [format test%03d $i]"
    execsql $sql
  }
  execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name}
} {}

# Try to drop a table that does not exist
#
do_test table-5.1.1 {
  catchsql {DROP TABLE test009}
} {1 {no such table: test009}}
do_test table-5.1.2 {
  catchsql {DROP TABLE IF EXISTS test009}
} {0 {}}

# Try to drop sqlite_master
#
do_test table-5.2 {
  catchsql {DROP TABLE IF EXISTS sqlite_master}
} {1 {table sqlite_master may not be dropped}}

# Make sure an EXPLAIN does not really create a new table
#
do_test table-5.3 {
  ifcapable {explain} {
    execsql {EXPLAIN CREATE TABLE test1(f1 int)}
  }
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {}

# Make sure an EXPLAIN does not really drop an existing table
#
do_test table-5.4 {
  execsql {CREATE TABLE test1(f1 int)}
  ifcapable {explain} {
    execsql {EXPLAIN DROP TABLE test1}
  }
  execsql {SELECT name FROM sqlite_master WHERE type!='meta'}
} {test1}

# Create a table with a goofy name
#
#do_test table-6.1 {
#  execsql {CREATE TABLE 'Spaces In This Name!'(x int)}
#  execsql {INSERT INTO 'spaces in this name!' VALUES(1)}
#  set list [glob -nocomplain testdb/spaces*.tbl]
#} {testdb/spaces+in+this+name+.tbl}

# Try using keywords as table names or column names.
# 
do_test table-7.1 {
  set v [catch {execsql {
    CREATE TABLE weird(
      desc text,
      asc text,
      key int,
      [14_vac] boolean,
      fuzzy_dog_12 varchar(10),
      begin blob,
      end clob
    )
  }} msg]
  lappend v $msg
} {0 {}}
do_test table-7.2 {
  execsql {
    INSERT INTO weird VALUES('a','b',9,0,'xyz','hi','y''all');
    SELECT * FROM weird;
  }
} {a b 9 0 xyz hi y'all}
do_test table-7.3 {
  execsql2 {
    SELECT * FROM weird;
  }
} {desc a asc b key 9 14_vac 0 fuzzy_dog_12 xyz begin hi end y'all}
do_test table-7.3 {
  execsql {
    CREATE TABLE savepoint(release);
    INSERT INTO savepoint(release) VALUES(10);
    UPDATE savepoint SET release = 5;
    SELECT release FROM savepoint;
  }
} {5}

# Try out the CREATE TABLE AS syntax
#
do_test table-8.1 {
  execsql2 {
    CREATE TABLE t2 AS SELECT * FROM weird;
    SELECT * FROM t2;
  }
} {desc a asc b key 9 14_vac 0 fuzzy_dog_12 xyz begin hi end y'all}
do_test table-8.1.1 {
  execsql {
    SELECT sql FROM sqlite_master WHERE name='t2';
  }
} {{CREATE TABLE t2(
  "desc" TEXT,
  "asc" TEXT,
  "key" INT,
  "14_vac" NUM,
  fuzzy_dog_12 TEXT,
  "begin",
  "end" TEXT
)}}
do_test table-8.2 {
  execsql {
    CREATE TABLE "t3""xyz"(a,b,c);
    INSERT INTO [t3"xyz] VALUES(1,2,3);
    SELECT * FROM [t3"xyz];
  }
} {1 2 3}
do_test table-8.3 {
  execsql2 {
    CREATE TABLE [t4"abc] AS SELECT count(*) as cnt, max(b+c) FROM [t3"xyz];
    SELECT * FROM [t4"abc];
  }
} {cnt 1 max(b+c) 5}

# Update for v3: The declaration type of anything except a column is now a
# NULL pointer, so the created table has no column types. (Changed result
# from {{CREATE TABLE 't4"abc'(cnt NUMERIC,"max(b+c)" NUMERIC)}}).
do_test table-8.3.1 {
  execsql {
    SELECT sql FROM sqlite_master WHERE name='t4"abc'
  }
} {{CREATE TABLE "t4""abc"(cnt,"max(b+c)")}}

ifcapable tempdb {
  do_test table-8.4 {
    execsql2 {
      CREATE TEMPORARY TABLE t5 AS SELECT count(*) AS [y'all] FROM [t3"xyz];
      SELECT * FROM t5;
    }
  } {y'all 1}
}

do_test table-8.5 {
  db close
  sqlite3 db test.db
  execsql2 {
    SELECT * FROM [t4"abc];
  }
} {cnt 1 max(b+c) 5}
do_test table-8.6 {
  execsql2 {
    SELECT * FROM t2;
  }
} {desc a asc b key 9 14_vac 0 fuzzy_dog_12 xyz begin hi end y'all}
do_test table-8.7 {
  catchsql {
    SELECT * FROM t5;
  }
} {1 {no such table: t5}}
do_test table-8.8 {
  catchsql {
    CREATE TABLE t5 AS SELECT * FROM no_such_table;
  }
} {1 {no such table: no_such_table}}

do_test table-8.9 {
  execsql {
    CREATE TABLE t10("col.1" [char.3]);
    CREATE TABLE t11 AS SELECT * FROM t10;
    SELECT sql FROM sqlite_master WHERE name = 't11';
  }
} {{CREATE TABLE t11("col.1" TEXT)}}
do_test table-8.10 {
  execsql {
    CREATE TABLE t12(
      a INTEGER,
      b VARCHAR(10),
      c VARCHAR(1,10),
      d VARCHAR(+1,-10),
      e VARCHAR (+1,-10),
      f "VARCHAR (+1,-10, 5)",
      g BIG INTEGER
    );
    CREATE TABLE t13 AS SELECT * FROM t12;
    SELECT sql FROM sqlite_master WHERE name = 't13';
  }
} {{CREATE TABLE t13(
  a INT,
  b TEXT,
  c TEXT,
  d TEXT,
  e TEXT,
  f TEXT,
  g INT
)}}

# Make sure we cannot have duplicate column names within a table.
#
do_test table-9.1 {
  catchsql {
    CREATE TABLE t6(a,b,a);
  }
} {1 {duplicate column name: a}}
do_test table-9.2 {
  catchsql {
    CREATE TABLE t6(a varchar(100), b blob, a integer);
  }
} {1 {duplicate column name: a}}

# Check the foreign key syntax.
#
ifcapable {foreignkey} {
do_test table-10.1 {
  catchsql {
    CREATE TABLE t6(a REFERENCES t4(a) NOT NULL);
    INSERT INTO t6 VALUES(NULL);
  }
} {1 {t6.a may not be NULL}}
do_test table-10.2 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a REFERENCES t4(a) MATCH PARTIAL);
  }
} {0 {}}
do_test table-10.3 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a REFERENCES t4 MATCH FULL ON DELETE SET NULL NOT NULL);
  }
} {0 {}}
do_test table-10.4 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a REFERENCES t4 MATCH FULL ON UPDATE SET DEFAULT DEFAULT 1);
  }
} {0 {}}
do_test table-10.5 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a NOT NULL NOT DEFERRABLE INITIALLY IMMEDIATE);
  }
} {0 {}}
do_test table-10.6 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a NOT NULL DEFERRABLE INITIALLY DEFERRED);
  }
} {0 {}}
do_test table-10.7 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a,
      FOREIGN KEY (a) REFERENCES t4(b) DEFERRABLE INITIALLY DEFERRED
    );
  }
} {0 {}}
do_test table-10.8 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a,b,c,
      FOREIGN KEY (b,c) REFERENCES t4(x,y) MATCH PARTIAL
        ON UPDATE SET NULL ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
    );
  }
} {0 {}}
do_test table-10.9 {
  catchsql {
    DROP TABLE t6;
    CREATE TABLE t6(a,b,c,
      FOREIGN KEY (b,c) REFERENCES t4(x)
    );
  }
} {1 {number of columns in foreign key does not match the number of columns in the referenced table}}
do_test table-10.10 {
  catchsql {DROP TABLE t6}
  catchsql {
    CREATE TABLE t6(a,b,c,
      FOREIGN KEY (b,c) REFERENCES t4(x,y,z)
    );
  }
} {1 {number of columns in foreign key does not match the number of columns in the referenced table}}
do_test table-10.11 {
  catchsql {DROP TABLE t6}
  catchsql {
    CREATE TABLE t6(a,b, c REFERENCES t4(x,y));
  }
} {1 {foreign key on c should reference only one column of table t4}}
do_test table-10.12 {
  catchsql {DROP TABLE t6}
  catchsql {
    CREATE TABLE t6(a,b,c,
      FOREIGN KEY (b,x) REFERENCES t4(x,y)
    );
  }
} {1 {unknown column "x" in foreign key definition}}
do_test table-10.13 {
  catchsql {DROP TABLE t6}
  catchsql {
    CREATE TABLE t6(a,b,c,
      FOREIGN KEY (x,b) REFERENCES t4(x,y)
    );
  }
} {1 {unknown column "x" in foreign key definition}}
} ;# endif foreignkey

# Test for the "typeof" function. More tests for the
# typeof() function are found in bind.test and types.test.
#
do_test table-11.1 {
  execsql {
    CREATE TABLE t7(
       a integer primary key,
       b number(5,10),
       c character varying (8),
       d VARCHAR(9),
       e clob,
       f BLOB,
       g Text,
       h
    );
    INSERT INTO t7(a) VALUES(1);
    SELECT typeof(a), typeof(b), typeof(c), typeof(d),
           typeof(e), typeof(f), typeof(g), typeof(h)
    FROM t7 LIMIT 1;
  }
} {integer null null null null null null null} 
do_test table-11.2 {
  execsql {
    SELECT typeof(a+b), typeof(a||b), typeof(c+d), typeof(c||d)
    FROM t7 LIMIT 1;
  }
} {null null null null}

# Test that when creating a table using CREATE TABLE AS, column types are
# assigned correctly for (SELECT ...) and 'x AS y' expressions.
do_test table-12.1 {
  ifcapable subquery {
    execsql {
      CREATE TABLE t8 AS SELECT b, h, a as i, (SELECT f FROM t7) as j FROM t7;
    }
  } else {
    execsql {
      CREATE TABLE t8 AS SELECT b, h, a as i, f as j FROM t7;
    }
  }
} {}
do_test table-12.2 {
  execsql {
    SELECT sql FROM sqlite_master WHERE tbl_name = 't8'
  }
} {{CREATE TABLE t8(b NUM,h,i INT,j)}}

#--------------------------------------------------------------------
# Test cases table-13.*
#
# Test the ability to have default values of CURRENT_TIME, CURRENT_DATE
# and CURRENT_TIMESTAMP.
#
do_test table-13.1 {
  execsql {
    CREATE TABLE tablet8(
       a integer primary key,
       tm text DEFAULT CURRENT_TIME,
       dt text DEFAULT CURRENT_DATE,
       dttm text DEFAULT CURRENT_TIMESTAMP
    );
    SELECT * FROM tablet8;
  }
} {}
set i 0
foreach {date time seconds} {
  1976-07-04 12:00:00 205329600
  1994-04-16 14:00:00 766504800
  2000-01-01 00:00:00 946684800
  2003-12-31 12:34:56 1072874096
} {
  incr i
  set sqlite_current_time $seconds
  do_test table-13.2.$i {
    execsql "
      INSERT INTO tablet8(a) VALUES($i);
      SELECT tm, dt, dttm FROM tablet8 WHERE a=$i;
    "
  } [list $time $date [list $date $time]]
}
set sqlite_current_time 0

#--------------------------------------------------------------------
# Test cases table-14.*
#
# Test that a table cannot be created or dropped while other virtual
# machines are active. This is required because otherwise when in 
# auto-vacuum mode the btree-layer may need to move the root-pages of 
# a table for which there is an open cursor.
#
# 2007-05-02:  A open btree cursor no longer blocks CREATE TABLE.
# But DROP TABLE is still prohibited because we do not want to
# delete a table out from under a running query.
#

# db eval {
#   pragma vdbe_trace = 0;
# }
# Try to create a table from within a callback:
unset -nocomplain result
do_test table-14.1 {
  set rc [
    catch {
      db eval {SELECT * FROM tablet8 LIMIT 1} {} {
        db eval {CREATE TABLE t9(a, b, c)}
      }
    } msg
  ]
  set result [list $rc $msg]
} {0 {}}

# Try to drop a table from within a callback:
do_test table-14.2 {
  set rc [
    catch {
      db eval {SELECT * FROM tablet8 LIMIT 1} {} {
        db eval {DROP TABLE t9;}
      }
    } msg
  ] 
  set result [list $rc $msg]
} {1 {database table is locked}}

ifcapable attach {
  # Now attach a database and ensure that a table can be created in the 
  # attached database whilst in a callback from a query on the main database.
  do_test table-14.3 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      ATTACH 'test2.db' as aux;
    }
    db eval {SELECT * FROM tablet8 LIMIT 1} {} {
      db eval {CREATE TABLE aux.t1(a, b, c)}
    }
  } {}
  
  # On the other hand, it should be impossible to drop a table when any VMs 
  # are active. This is because VerifyCookie instructions may have already
  # been executed, and btree root-pages may not move after this (which a
  # delete table might do).
  do_test table-14.4 {
    set rc [
      catch {
        db eval {SELECT * FROM tablet8 LIMIT 1} {} {
          db eval {DROP TABLE aux.t1;}
        }
      } msg
    ] 
    set result [list $rc $msg]
  } {1 {database table is locked}}
}

# Create and drop 2000 tables. This is to check that the balance_shallow()
# routine works correctly on the sqlite_master table. At one point it
# contained a bug that would prevent the right-child pointer of the
# child page from being copied to the root page.
#
do_test table-15.1 {
  execsql {BEGIN}
  for {set i 0} {$i<2000} {incr i} {
    execsql "CREATE TABLE tbl$i (a, b, c)"
  }
  execsql {COMMIT}
} {}
do_test table-15.2 {
  execsql {BEGIN}
  for {set i 0} {$i<2000} {incr i} {
    execsql "DROP TABLE tbl$i"
  }
  execsql {COMMIT}
} {}

finish_test

Added test/tableapi.test.

























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the sqlite_exec_printf() and
# sqlite_get_table_printf() APIs.
#
# $Id: tableapi.test,v 1.21 2009/07/17 14:37:25 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !gettable {
  finish_test
  return
}

ifcapable memdebug {
  source $testdir/malloc_common.tcl
}

do_test tableapi-1.0 {
  set ::dbx [sqlite3_open test.db]
  catch {sqlite_exec_printf $::dbx {DROP TABLE xyz} {}}
  sqlite3_exec_printf $::dbx {CREATE TABLE %s(a int, b text)} xyz
} {0 {}}
do_test tableapi-1.1 {
  sqlite3_exec_printf $::dbx {
    INSERT INTO xyz VALUES(1,'%q')
  } {Hi Y'all}
} {0 {}}
do_test tableapi-1.2 {
  sqlite3_exec_printf $::dbx {SELECT * FROM xyz} {}
} {0 {a b 1 {Hi Y'all}}}

do_test tableapi-2.1 {
  sqlite3_get_table_printf $::dbx {
    BEGIN TRANSACTION;
    SELECT * FROM xyz WHERE b='%q'
  } {Hi Y'all}
} {0 1 2 a b 1 {Hi Y'all}}
do_test tableapi-2.2 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz
  } {}
} {0 1 2 a b 1 {Hi Y'all}}
do_test tableapi-2.3 {
  for {set i 2} {$i<=50} {incr i} {
    sqlite3_get_table_printf $::dbx \
       "INSERT INTO xyz VALUES($i,'(%s)')" $i
  }
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz ORDER BY a
  } {}
} {0 50 2 a b 1 {Hi Y'all} 2 (2) 3 (3) 4 (4) 5 (5) 6 (6) 7 (7) 8 (8) 9 (9) 10 (10) 11 (11) 12 (12) 13 (13) 14 (14) 15 (15) 16 (16) 17 (17) 18 (18) 19 (19) 20 (20) 21 (21) 22 (22) 23 (23) 24 (24) 25 (25) 26 (26) 27 (27) 28 (28) 29 (29) 30 (30) 31 (31) 32 (32) 33 (33) 34 (34) 35 (35) 36 (36) 37 (37) 38 (38) 39 (39) 40 (40) 41 (41) 42 (42) 43 (43) 44 (44) 45 (45) 46 (46) 47 (47) 48 (48) 49 (49) 50 (50)}
do_test tableapi-2.3.1 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz  WHERE a>49 ORDER BY a
  } {}
} {0 1 2 a b 50 (50)}
do_test tableapi-2.3.2 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>47 ORDER BY a
  } {}
} {0 3 2 a b 48 (48) 49 (49) 50 (50)}
do_test tableapi-2.3.3 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>47 ORDER BY a; invalid
  } {}
} {1 {near "invalid": syntax error}}
do_test tableapi-2.3.4 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>47 ORDER BY a
  } {} 8
} {0 a b 48 (48) 49 (49) 50 (50)}
do_test tableapi-2.4 {
  set manyquote ''''''''
  append manyquote $manyquote
  append manyquote $manyquote
  append manyquote $manyquote
  append manyquote $manyquote
  append manyquote $manyquote
  append manyquote $manyquote
  set ::big_str "$manyquote Hello $manyquote"
  sqlite3_get_table_printf $::dbx {
    INSERT INTO xyz VALUES(51,'%q')
  } $::big_str
} {0 0 0}
do_test tableapi-2.5 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>49 ORDER BY a;
  } {}
} "0 2 2 a b 50 (50) 51 \173$::big_str\175"
do_test tableapi-2.6 {
  sqlite3_get_table_printf $::dbx {
    INSERT INTO xyz VALUES(52,NULL)
  } {}
  ifcapable subquery {
    sqlite3_get_table_printf $::dbx {
      SELECT * FROM xyz WHERE a IN (42,50,52) ORDER BY a DESC
    } {}
  } else {
    sqlite3_get_table_printf $::dbx {
      SELECT * FROM xyz WHERE a=42 OR a=50 OR a=52 ORDER BY a DESC
    } {}
  }
} {0 3 2 a b 52 NULL 50 (50) 42 (42)}
do_test tableapi-2.7 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>1000
  } {}
} {0 0 0}

# Repeat all tests with the empty_result_callbacks pragma turned on
#
do_test tableapi-3.1 {
  sqlite3_get_table_printf $::dbx {
    ROLLBACK;
    PRAGMA empty_result_callbacks = ON;
    SELECT * FROM xyz WHERE b='%q'
  } {Hi Y'all}
} {0 1 2 a b 1 {Hi Y'all}}
do_test tableapi-3.2 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz
  } {}
} {0 1 2 a b 1 {Hi Y'all}}
do_test tableapi-3.3 {
  for {set i 2} {$i<=50} {incr i} {
    sqlite3_get_table_printf $::dbx \
       "INSERT INTO xyz VALUES($i,'(%s)')" $i
  }
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz ORDER BY a
  } {}
} {0 50 2 a b 1 {Hi Y'all} 2 (2) 3 (3) 4 (4) 5 (5) 6 (6) 7 (7) 8 (8) 9 (9) 10 (10) 11 (11) 12 (12) 13 (13) 14 (14) 15 (15) 16 (16) 17 (17) 18 (18) 19 (19) 20 (20) 21 (21) 22 (22) 23 (23) 24 (24) 25 (25) 26 (26) 27 (27) 28 (28) 29 (29) 30 (30) 31 (31) 32 (32) 33 (33) 34 (34) 35 (35) 36 (36) 37 (37) 38 (38) 39 (39) 40 (40) 41 (41) 42 (42) 43 (43) 44 (44) 45 (45) 46 (46) 47 (47) 48 (48) 49 (49) 50 (50)}
do_test tableapi-3.3.1 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz  WHERE a>49 ORDER BY a
  } {}
} {0 1 2 a b 50 (50)}
do_test tableapi-3.3.2 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>47 ORDER BY a
  } {}
} {0 3 2 a b 48 (48) 49 (49) 50 (50)}
do_test tableapi-3.4 {
  sqlite3_get_table_printf $::dbx {
    INSERT INTO xyz VALUES(51,'%q')
  } $::big_str
} {0 0 0}
do_test tableapi-3.5 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>49 ORDER BY a;
  } {}
} "0 2 2 a b 50 (50) 51 \173$::big_str\175"
do_test tableapi-3.6 {
  sqlite3_get_table_printf $::dbx {
    INSERT INTO xyz VALUES(52,NULL)
  } {}
  ifcapable subquery {
    sqlite3_get_table_printf $::dbx {
      SELECT * FROM xyz WHERE a IN (42,50,52) ORDER BY a DESC
    } {}
  } else {
    sqlite3_get_table_printf $::dbx {
      SELECT * FROM xyz WHERE a=42 OR a=50 OR a=52 ORDER BY a DESC
    } {}
  }
} {0 3 2 a b 52 NULL 50 (50) 42 (42)}
do_test tableapi-3.7 {
  sqlite3_get_table_printf $::dbx {
    SELECT * FROM xyz WHERE a>1000
  } {}
} {0 0 2 a b}

do_test tableapi-4.1 {
  set rc [catch {
    sqlite3_get_table_printf $::dbx {
      SELECT * FROM xyz;  SELECT * FROM sqlite_master
    } {}
  } msg]
  concat $rc $msg
} {0 1 {sqlite3_get_table() called with two or more incompatible queries}}

# A report on the mailing list says that the sqlite_get_table() api fails
# on queries involving more than 40 columns.  The following code attempts
# to test that complaint
#
do_test tableapi-5.1 {
  set sql "CREATE TABLE t2("
  set sep ""
  for {set i 1} {$i<=100} {incr i} {
    append sql ${sep}x$i
    set sep ,
  }
  append sql )
  sqlite3_get_table_printf $::dbx $sql {}
  set sql "INSERT INTO t2 VALUES("
  set sep ""
  for {set i 1} {$i<=100} {incr i} {
    append sql ${sep}$i
    set sep ,
  }
  append sql )
  sqlite3_get_table_printf $::dbx $sql {}
  sqlite3_get_table_printf $::dbx {SELECT * FROM t2} {}
} {0 1 100 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100}
do_test tableapi-5.2 {
  set sql "INSERT INTO t2 VALUES("
  set sep ""
  for {set i 1} {$i<=100} {incr i} {
    append sql ${sep}[expr {$i+1000}]
    set sep ,
  }
  append sql )
  sqlite3_get_table_printf $::dbx $sql {}
  sqlite3_get_table_printf $::dbx {SELECT * FROM t2} {}
} {0 2 100 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100}

ifcapable schema_pragmas {
  do_test tableapi-6.1 {
    sqlite3_get_table_printf $::dbx {PRAGMA user_version} {}
  } {0 1 1 user_version 0}
}

ifcapable memdebug {
  do_malloc_test tableapi-7 -sqlprep {
    DROP TABLE IF EXISTS t1;
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    INSERT INTO t1 SELECT a+4, b+4 FROM t1;
    INSERT INTO t1 SELECT a+8, b+8 FROM t1;
  } -tclbody {
    set r [sqlite3_get_table_printf db {SELECT rowid, a, b FROM t1} {}]
    if {[llength $r]<26} {error "out of memory"}
  }
}

do_test tableapi-99.0 {
  sqlite3_close $::dbx
} {SQLITE_OK}

finish_test

Added test/tclsqlite.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for TCL interface to the
# SQLite library. 
#
# Actually, all tests are based on the TCL interface, so the main
# interface is pretty well tested.  This file contains some addition
# tests for fringe issues that the main test suite does not cover.
#
# $Id: tclsqlite.test,v 1.73 2009/03/16 13:19:36 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Check the error messages generated by tclsqlite
#
if {[sqlite3 -has-codec]} {
  set r "sqlite_orig HANDLE FILENAME ?-key CODEC-KEY?"
} else {
  set r "sqlite3 HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN? ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
}
do_test tcl-1.1 {
  set v [catch {sqlite3 bogus} msg]
  regsub {really_sqlite3} $msg {sqlite3} msg
  lappend v $msg
} [list 1 "wrong # args: should be \"$r\""]
do_test tcl-1.2 {
  set v [catch {db bogus} msg]
  lappend v $msg
} {1 {bad option "bogus": must be authorizer, backup, busy, cache, changes, close, collate, collation_needed, commit_hook, complete, copy, enable_load_extension, errorcode, eval, exists, function, incrblob, interrupt, last_insert_rowid, nullvalue, onecolumn, profile, progress, rekey, restore, rollback_hook, status, timeout, total_changes, trace, transaction, unlock_notify, update_hook, or version}}
do_test tcl-1.2.1 {
  set v [catch {db cache bogus} msg]
  lappend v $msg
} {1 {bad option "bogus": must be flush or size}}
do_test tcl-1.2.2 {
  set v [catch {db cache} msg]
  lappend v $msg
} {1 {wrong # args: should be "db cache option ?arg?"}}
do_test tcl-1.3 {
  execsql {CREATE TABLE t1(a int, b int)}
  execsql {INSERT INTO t1 VALUES(10,20)}
  set v [catch {
    db eval {SELECT * FROM t1} data {
      error "The error message"
    }
  } msg]
  lappend v $msg
} {1 {The error message}}
do_test tcl-1.4 {
  set v [catch {
    db eval {SELECT * FROM t2} data {
      error "The error message"
    }
  } msg]
  lappend v $msg
} {1 {no such table: t2}}
do_test tcl-1.5 {
  set v [catch {
    db eval {SELECT * FROM t1} data {
      break
    }
  } msg]
  lappend v $msg
} {0 {}}
catch {expr x*} msg
do_test tcl-1.6 {
  set v [catch {
    db eval {SELECT * FROM t1} data {
      expr x*
    }
  } msg]
  lappend v $msg
} [list 1 $msg]
do_test tcl-1.7 {
  set v [catch {db} msg]
  lappend v $msg
} {1 {wrong # args: should be "db SUBCOMMAND ..."}}
if {[catch {db auth {}}]==0} {
  do_test tcl-1.8 {
    set v [catch {db authorizer 1 2 3} msg]
    lappend v $msg
  } {1 {wrong # args: should be "db authorizer ?CALLBACK?"}}
}
do_test tcl-1.9 {
  set v [catch {db busy 1 2 3} msg]
  lappend v $msg
} {1 {wrong # args: should be "db busy CALLBACK"}}
do_test tcl-1.10 {
  set v [catch {db progress 1} msg]
  lappend v $msg
} {1 {wrong # args: should be "db progress N CALLBACK"}}
do_test tcl-1.11 {
  set v [catch {db changes xyz} msg]
  lappend v $msg
} {1 {wrong # args: should be "db changes "}}
do_test tcl-1.12 {
  set v [catch {db commit_hook a b c} msg]
  lappend v $msg
} {1 {wrong # args: should be "db commit_hook ?CALLBACK?"}}
ifcapable {complete} {
  do_test tcl-1.13 {
    set v [catch {db complete} msg]
    lappend v $msg
  } {1 {wrong # args: should be "db complete SQL"}}
}
do_test tcl-1.14 {
  set v [catch {db eval} msg]
  lappend v $msg
} {1 {wrong # args: should be "db eval SQL ?ARRAY-NAME? ?SCRIPT?"}}
do_test tcl-1.15 {
  set v [catch {db function} msg]
  lappend v $msg
} {1 {wrong # args: should be "db function NAME [-argcount N] SCRIPT"}}
do_test tcl-1.16 {
  set v [catch {db last_insert_rowid xyz} msg]
  lappend v $msg
} {1 {wrong # args: should be "db last_insert_rowid "}}
do_test tcl-1.17 {
  set v [catch {db rekey} msg]
  lappend v $msg
} {1 {wrong # args: should be "db rekey KEY"}}
do_test tcl-1.18 {
  set v [catch {db timeout} msg]
  lappend v $msg
} {1 {wrong # args: should be "db timeout MILLISECONDS"}}
do_test tcl-1.19 {
  set v [catch {db collate} msg]
  lappend v $msg
} {1 {wrong # args: should be "db collate NAME SCRIPT"}}
do_test tcl-1.20 {
  set v [catch {db collation_needed} msg]
  lappend v $msg
} {1 {wrong # args: should be "db collation_needed SCRIPT"}}
do_test tcl-1.21 {
  set v [catch {db total_changes xyz} msg]
  lappend v $msg
} {1 {wrong # args: should be "db total_changes "}}
do_test tcl-1.20 {
  set v [catch {db copy} msg]
  lappend v $msg
} {1 {wrong # args: should be "db copy CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?"}}
do_test tcl-1.21 {
  set v [catch {sqlite3 db2 test.db -vfs nosuchvfs} msg]
  lappend v $msg
} {1 {no such vfs: nosuchvfs}}

catch {unset ::result}
do_test tcl-2.1 {
  execsql "CREATE TABLE t\u0123x(a int, b\u1235 float)"
} {}
ifcapable schema_pragmas {
  do_test tcl-2.2 {
    execsql "PRAGMA table_info(t\u0123x)"
  } "0 a int 0 {} 0 1 b\u1235 float 0 {} 0"
}
do_test tcl-2.3 {
  execsql "INSERT INTO t\u0123x VALUES(1,2.3)"
  db eval "SELECT * FROM t\u0123x" result break
  set result(*)
} "a b\u1235"


# Test the onecolumn method
#
do_test tcl-3.1 {
  execsql {
    INSERT INTO t1 SELECT a*2, b*2 FROM t1;
    INSERT INTO t1 SELECT a*2+1, b*2+1 FROM t1;
    INSERT INTO t1 SELECT a*2+3, b*2+3 FROM t1;
  }
  set rc [catch {db onecolumn {SELECT * FROM t1 ORDER BY a}} msg]
  lappend rc $msg
} {0 10}
do_test tcl-3.2 {
  db onecolumn {SELECT * FROM t1 WHERE a<0}
} {}
do_test tcl-3.3 {
  set rc [catch {db onecolumn} errmsg]
  lappend rc $errmsg
} {1 {wrong # args: should be "db onecolumn SQL"}}
do_test tcl-3.4 {
  set rc [catch {db onecolumn {SELECT bogus}} errmsg]
  lappend rc $errmsg
} {1 {no such column: bogus}}
ifcapable {tclvar} {
  do_test tcl-3.5 {
    set b 50
    set rc [catch {db one {SELECT * FROM t1 WHERE b>$b}} msg]
    lappend rc $msg
  } {0 41}
  do_test tcl-3.6 {
    set b 500
    set rc [catch {db one {SELECT * FROM t1 WHERE b>$b}} msg]
    lappend rc $msg
  } {0 {}}
  do_test tcl-3.7 {
    set b 500
    set rc [catch {db one {
      INSERT INTO t1 VALUES(99,510);
      SELECT * FROM t1 WHERE b>$b
    }} msg]
    lappend rc $msg
  } {0 99}
}
ifcapable {!tclvar} {
   execsql {INSERT INTO t1 VALUES(99,510)}
}

# Turn the busy handler on and off
#
do_test tcl-4.1 {
  proc busy_callback {cnt} {
    break
  }
  db busy busy_callback
  db busy
} {busy_callback}
do_test tcl-4.2 {
  db busy {}
  db busy
} {}

ifcapable {tclvar} {
  # Parsing of TCL variable names within SQL into bound parameters.
  #
  do_test tcl-5.1 {
    execsql {CREATE TABLE t3(a,b,c)}
    catch {unset x}
    set x(1) A
    set x(2) B
    execsql {
      INSERT INTO t3 VALUES($::x(1),$::x(2),$::x(3));
      SELECT * FROM t3
    }
  } {A B {}}
  do_test tcl-5.2 {
    execsql {
      SELECT typeof(a), typeof(b), typeof(c) FROM t3
    }
  } {text text null}
  do_test tcl-5.3 {
    catch {unset x}
    set x [binary format h12 686900686f00]
    execsql {
      UPDATE t3 SET a=$::x;
    }
    db eval {
      SELECT a FROM t3
    } break
    binary scan $a h12 adata
    set adata
  } {686900686f00}
  do_test tcl-5.4 {
    execsql {
      SELECT typeof(a), typeof(b), typeof(c) FROM t3
    }
  } {blob text null}
}

# Operation of "break" and "continue" within row scripts
#
do_test tcl-6.1 {
  db eval {SELECT * FROM t1} {
    break
  }
  lappend a $b
} {10 20}
do_test tcl-6.2 {
  set cnt 0
  db eval {SELECT * FROM t1} {
    if {$a>40} continue
    incr cnt
  }
  set cnt
} {4}
do_test tcl-6.3 {
  set cnt 0
  db eval {SELECT * FROM t1} {
    if {$a<40} continue
    incr cnt
  }
  set cnt
} {5}
do_test tcl-6.4 {
  proc return_test {x} {
    db eval {SELECT * FROM t1} {
      if {$a==$x} {return $b}
    }
  }
  return_test 10
} 20
do_test tcl-6.5 {
  return_test 20
} 40
do_test tcl-6.6 {
  return_test 99
} 510
do_test tcl-6.7 {
  return_test 0
} {}

do_test tcl-7.1 {
  db version
  expr 0
} {0}

# modify and reset the NULL representation
#
do_test tcl-8.1 {
  db nullvalue NaN
  execsql {INSERT INTO t1 VALUES(30,NULL)}
  db eval {SELECT * FROM t1 WHERE b IS NULL}
} {30 NaN}
do_test tcl-8.2 {
  db nullvalue NULL
  db nullvalue
} {NULL}
do_test tcl-8.3 {
  db nullvalue {}
  db eval {SELECT * FROM t1 WHERE b IS NULL}
} {30 {}}

# Test the return type of user-defined functions
#
do_test tcl-9.1 {
  db function ret_str {return "hi"}
  execsql {SELECT typeof(ret_str())}
} {text}
do_test tcl-9.2 {
  db function ret_dbl {return [expr {rand()*0.5}]}
  execsql {SELECT typeof(ret_dbl())}
} {real}
do_test tcl-9.3 {
  db function ret_int {return [expr {int(rand()*200)}]}
  execsql {SELECT typeof(ret_int())}
} {integer}

# Recursive calls to the same user-defined function
#
ifcapable tclvar {
  do_test tcl-9.10 {
    proc userfunc_r1 {n} {
      if {$n<=0} {return 0}
      set nm1 [expr {$n-1}]
      return [expr {[db eval {SELECT r1($nm1)}]+$n}]
    }
    db function r1 userfunc_r1
    execsql {SELECT r1(10)}
  } {55}
  do_test tcl-9.11 {
    execsql {SELECT r1(100)}
  } {5050}
}

# Tests for the new transaction method
#
do_test tcl-10.1 {
  db transaction {}
} {}
do_test tcl-10.2 {
  db transaction deferred {}
} {}
do_test tcl-10.3 {
  db transaction immediate {}
} {}
do_test tcl-10.4 {
  db transaction exclusive {}
} {}
do_test tcl-10.5 {
  set rc [catch {db transaction xyzzy {}} msg]
  lappend rc $msg
} {1 {bad transaction type "xyzzy": must be deferred, exclusive, or immediate}}
do_test tcl-10.6 {
  set rc [catch {db transaction {error test-error}} msg]
  lappend rc $msg
} {1 test-error}
do_test tcl-10.7 {
  db transaction {
    db eval {CREATE TABLE t4(x)}
    db transaction {
      db eval {INSERT INTO t4 VALUES(1)}
    }
  }
  db eval {SELECT * FROM t4}
} 1
do_test tcl-10.8 {
  catch {
    db transaction {
      db eval {INSERT INTO t4 VALUES(2)}
      db eval {INSERT INTO t4 VALUES(3)}
      db eval {INSERT INTO t4 VALUES(4)}
      error test-error
    }
  }
  db eval {SELECT * FROM t4}
} 1
do_test tcl-10.9 {
  db transaction {
    db eval {INSERT INTO t4 VALUES(2)}
    catch {
      db transaction {
        db eval {INSERT INTO t4 VALUES(3)}
        db eval {INSERT INTO t4 VALUES(4)}
        error test-error
      }
    }
  }
  db eval {SELECT * FROM t4}
} {1 2}
do_test tcl-10.10 {
  for {set i 0} {$i<1} {incr i} {
    db transaction {
      db eval {INSERT INTO t4 VALUES(5)}
      continue
    }
    error "This line should not be run"
  }
  db eval {SELECT * FROM t4}
} {1 2 5}
do_test tcl-10.11 {
  for {set i 0} {$i<10} {incr i} {
    db transaction {
      db eval {INSERT INTO t4 VALUES(6)}
      break
    }
  }
  db eval {SELECT * FROM t4}
} {1 2 5 6}
do_test tcl-10.12 {
  set rc [catch {
    for {set i 0} {$i<10} {incr i} {
      db transaction {
        db eval {INSERT INTO t4 VALUES(7)}
        return
      }
    }
  }]
} {2}
do_test tcl-10.13 {
  db eval {SELECT * FROM t4}
} {1 2 5 6 7}

# Now test that [db transaction] commands may be nested with 
# the expected results.
#
do_test tcl-10.14 {
  db transaction {
    db eval {
      DELETE FROM t4;
      INSERT INTO t4 VALUES('one');
    }

    catch { 
      db transaction {
        db eval { INSERT INTO t4 VALUES('two') }
        db transaction {
          db eval { INSERT INTO t4 VALUES('three') }
          error "throw an error!"
        }
      }
    }
  }

  db eval {SELECT * FROM t4}
} {one}
do_test tcl-10.15 {
  # Make sure a transaction has not been left open.
  db eval {BEGIN ; COMMIT}
} {}
do_test tcl-10.16 {
  db transaction {
    db eval { INSERT INTO t4 VALUES('two'); }
    db transaction {
      db eval { INSERT INTO t4 VALUES('three') }
      db transaction {
        db eval { INSERT INTO t4 VALUES('four') }
      }
    }
  }
  db eval {SELECT * FROM t4}
} {one two three four}
do_test tcl-10.17 {
  catch {
    db transaction {
      db eval { INSERT INTO t4 VALUES('A'); }
      db transaction {
        db eval { INSERT INTO t4 VALUES('B') }
        db transaction {
          db eval { INSERT INTO t4 VALUES('C') }
          error "throw an error!"
        }
      }
    }
  }
  db eval {SELECT * FROM t4}
} {one two three four}
do_test tcl-10.18 {
  # Make sure a transaction has not been left open.
  db eval {BEGIN ; COMMIT}
} {}

# Mess up a [db transaction] command by locking the database using a
# second connection when it tries to commit. Make sure the transaction
# is not still open after the "database is locked" exception is thrown.
#
do_test tcl-10.18 {
  sqlite3 db2 test.db
  db2 eval {
    BEGIN;
    SELECT * FROM sqlite_master;
  }

  set rc [catch {
    db transaction {
      db eval {INSERT INTO t4 VALUES('five')}
    }
  } msg]
  list $rc $msg
} {1 {database is locked}}
do_test tcl-10.19 {
  db eval {BEGIN ; COMMIT}
} {}

# Thwart a [db transaction] command by locking the database using a
# second connection with "BEGIN EXCLUSIVE". Make sure no transaction is 
# open after the "database is locked" exception is thrown.
#
do_test tcl-10.20 {
  db2 eval {
    COMMIT;
    BEGIN EXCLUSIVE;
  }
  set rc [catch {
    db transaction {
      db eval {INSERT INTO t4 VALUES('five')}
    }
  } msg]
  list $rc $msg
} {1 {database is locked}}
do_test tcl-10.21 {
  db2 close
  db eval {BEGIN ; COMMIT}
} {}
do_test tcl-10.22 {
  sqlite3 db2 test.db
  db transaction exclusive {
    catch { db2 eval {SELECT * FROM sqlite_master} } msg
    set msg "db2: $msg"
  }
  set msg
} {db2: database is locked}
db2 close

do_test tcl-11.1 {
  db eval {INSERT INTO t4 VALUES(6)}
  db exists {SELECT x,x*2,x+x FROM t4 WHERE x==6}
} {1}
do_test tcl-11.2 {
  db exists {SELECT 0 FROM t4 WHERE x==6}
} {1}
do_test tcl-11.3 {
  db exists {SELECT 1 FROM t4 WHERE x==8}
} {0}
do_test tcl-11.3.1 {
  tcl_objproc db exists {SELECT 1 FROM t4 WHERE x==8}
} {0}

do_test tcl-12.1 {
  unset -nocomplain a b c version
  set version [db version]
  scan $version "%d.%d.%d" a b c
  expr $a*1000000 + $b*1000 + $c
} [sqlite3_libversion_number]


# Check to see that when bindings of the form @aaa are used instead
# of $aaa, that objects are treated as bytearray and are inserted
# as BLOBs.
#
ifcapable tclvar {
  do_test tcl-13.1 {
    db eval {CREATE TABLE t5(x BLOB)}
    set x abc123
    db eval {INSERT INTO t5 VALUES($x)}
    db eval {SELECT typeof(x) FROM t5}
  } {text}
  do_test tcl-13.2 {
    binary scan $x H notUsed
    db eval {
      DELETE FROM t5;
      INSERT INTO t5 VALUES($x);
      SELECT typeof(x) FROM t5;
    }
  } {text}
  do_test tcl-13.3 {
    db eval {
      DELETE FROM t5;
      INSERT INTO t5 VALUES(@x);
      SELECT typeof(x) FROM t5;
    }
  } {blob}
  do_test tcl-13.4 {
    set y 1234
    db eval {
      DELETE FROM t5;
      INSERT INTO t5 VALUES(@y);
      SELECT hex(x), typeof(x) FROM t5
    }
  } {31323334 blob}
}


finish_test

Added test/tempdb.test.































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# 2008 April 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
# The focus of this file is in making sure that rolling back
# a statement journal works correctly.
#
# $Id: tempdb.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Use a temporary database.
#
db close
sqlite3 db {}

# Force a statement journal rollback on a database file that
# has never been opened.
#
do_test tempdb-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(x UNIQUE);
    CREATE TABLE t2(y);
    INSERT INTO t2 VALUES('hello');
    INSERT INTO t2 VALUES(NULL);
  }
  # Because of the transaction, the temporary database file
  # has not even been opened yet.  The following statement
  # will cause a statement journal rollback on this non-existant
  # file.
  catchsql {
    INSERT INTO t1
    SELECT CASE WHEN y IS NULL THEN test_error('oops', 11) ELSE y END
      FROM t2;
  }
} {1 oops}

# Verify that no writes occurred in t1.
#
do_test tempdb-1.2 {
  execsql {
    SELECT * FROM t1
  }
} {}

do_test tempdb-2.1 {
  # Set $::jrnl_in_memory if the journal file is expected to be in-memory.
  # Similarly, set $::subj_in_memory if the sub-journal file is expected
  # to be in memory. These variables are used to calculate the expected
  # number of open files in the test cases below.
  #
  set jrnl_in_memory [expr {
    [info exists ::permutations_test_prefix] &&
    $::permutations_test_prefix eq "inmemory_journal"
  }]
  set subj_in_memory [expr {$jrnl_in_memory || $TEMP_STORE == 3}]

  db close
  sqlite3 db test.db
} {}
do_test tempdb-2.2 {
  execsql {
    CREATE TABLE t1 (a PRIMARY KEY, b, c);
    CREATE TABLE t2 (a, b, c);
    BEGIN;
      INSERT INTO t1 VALUES(1, 2, 3);
      INSERT INTO t1 VALUES(4, 5, 6);
      INSERT INTO t2 SELECT * FROM t1;
  }
  catchsql { INSERT INTO t1 SELECT * FROM t2 }
  set sqlite_open_file_count
} [expr 1 + (0==$jrnl_in_memory) + (0==$subj_in_memory)]
do_test tempdb-2.3 {
  execsql {
    PRAGMA temp_store = 'memory';
    ROLLBACK;
    BEGIN;
      INSERT INTO t1 VALUES(1, 2, 3);
      INSERT INTO t1 VALUES(4, 5, 6);
      INSERT INTO t2 SELECT * FROM t1;
  }
  catchsql { INSERT INTO t1 SELECT * FROM t2 }
  set sqlite_open_file_count
} [expr 1 + (0==$jrnl_in_memory)]

finish_test

Added test/temptable.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# 2001 October 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for temporary tables and indices.
#
# $Id: temptable.test,v 1.21 2009/06/16 17:49:36 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !tempdb {
  finish_test
  return
}

# Create an alternative connection to the database
#
do_test temptable-1.0 {
  sqlite3 db2 ./test.db
  set dummy {}
} {}

# Create a permanent table.
#
do_test temptable-1.1 {
  execsql {CREATE TABLE t1(a,b,c);}
  execsql {INSERT INTO t1 VALUES(1,2,3);}
  execsql {SELECT * FROM t1}
} {1 2 3}
do_test temptable-1.2 {
  catch {db2 eval {SELECT * FROM sqlite_master}}
  db2 eval {SELECT * FROM t1}
} {1 2 3}
do_test temptable-1.3 {
  execsql {SELECT name FROM sqlite_master}
} {t1}
do_test temptable-1.4 {
  db2 eval {SELECT name FROM sqlite_master}
} {t1}

# Create a temporary table.  Verify that only one of the two
# processes can see it.
#
do_test temptable-1.5 {
  db2 eval {
    CREATE TEMP TABLE t2(x,y,z);
    INSERT INTO t2 VALUES(4,5,6);
  }
  db2 eval {SELECT * FROM t2}
} {4 5 6}
do_test temptable-1.6 {
  catch {execsql {SELECT * FROM sqlite_master}}
  catchsql {SELECT * FROM t2}
} {1 {no such table: t2}}
do_test temptable-1.7 {
  catchsql {INSERT INTO t2 VALUES(8,9,0);}
} {1 {no such table: t2}}
do_test temptable-1.8 {
  db2 eval {INSERT INTO t2 VALUES(8,9,0);}
  db2 eval {SELECT * FROM t2 ORDER BY x}
} {4 5 6 8 9 0}
do_test temptable-1.9 {
  db2 eval {DELETE FROM t2 WHERE x==8}
  db2 eval {SELECT * FROM t2 ORDER BY x}
} {4 5 6}
do_test temptable-1.10 {
  db2 eval {DELETE FROM t2}
  db2 eval {SELECT * FROM t2}
} {}
do_test temptable-1.11 {
  db2 eval {
     INSERT INTO t2 VALUES(7,6,5);
     INSERT INTO t2 VALUES(4,3,2);
     SELECT * FROM t2 ORDER BY x;
  }
} {4 3 2 7 6 5}
do_test temptable-1.12 {
  db2 eval {DROP TABLE t2;}
  set r [catch {db2 eval {SELECT * FROM t2}} msg]
  lappend r $msg
} {1 {no such table: t2}}

# Make sure temporary tables work with transactions
#
do_test temptable-2.1 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TEMPORARY TABLE t2(x,y);
    INSERT INTO t2 VALUES(1,2);
    SELECT * FROM t2;
  }
} {1 2}
do_test temptable-2.2 {
  execsql {ROLLBACK}
  catchsql {SELECT * FROM t2}
} {1 {no such table: t2}}
do_test temptable-2.3 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TEMPORARY TABLE t2(x,y);
    INSERT INTO t2 VALUES(1,2);
    SELECT * FROM t2;
  }
} {1 2}
do_test temptable-2.4 {
  execsql {COMMIT}
  catchsql {SELECT * FROM t2}
} {0 {1 2}}
do_test temptable-2.5 {
  set r [catch {db2 eval {SELECT * FROM t2}} msg]
  lappend r $msg
} {1 {no such table: t2}}

# Make sure indices on temporary tables are also temporary.
#
do_test temptable-3.1 {
  execsql {
    CREATE INDEX i2 ON t2(x);
    SELECT name FROM sqlite_master WHERE type='index';
  }
} {}
do_test temptable-3.2 {
  execsql {
    SELECT y FROM t2 WHERE x=1;
  }
} {2}
do_test temptable-3.3 {
  execsql {
    DROP INDEX i2;
    SELECT y FROM t2 WHERE x=1;
  }
} {2}
do_test temptable-3.4 {
  execsql {
    CREATE INDEX i2 ON t2(x);
    DROP TABLE t2;
  }
  catchsql {DROP INDEX i2}
} {1 {no such index: i2}}

# Check for correct name collision processing. A name collision can
# occur when process A creates a temporary table T then process B
# creates a permanent table also named T.  The temp table in process A
# hides the existance of the permanent table.
#
do_test temptable-4.1 {
  execsql {
    CREATE TEMP TABLE t2(x,y);
    INSERT INTO t2 VALUES(10,20);
    SELECT * FROM t2;
  } db2
} {10 20}
do_test temptable-4.2 {
  execsql {
    CREATE TABLE t2(x,y,z);
    INSERT INTO t2 VALUES(9,8,7);
    SELECT * FROM t2;
  }
} {9 8 7}
do_test temptable-4.3 {
  catchsql {
    SELECT * FROM t2;
  } db2
} {0 {10 20}}
do_test temptable-4.4.1 {
  catchsql {
    SELECT * FROM temp.t2;
  } db2
} {0 {10 20}}
do_test temptable-4.4.2 {
  catchsql {
    SELECT * FROM main.t2;
  } db2
} {0 {9 8 7}}
#do_test temptable-4.4.3 {
#  catchsql {
#    SELECT name FROM main.sqlite_master WHERE type='table';
#  } db2
#} {1 {database schema has changed}}
do_test temptable-4.4.4 {
  catchsql {
    SELECT name FROM main.sqlite_master WHERE type='table';
  } db2
} {0 {t1 t2}}
do_test temptable-4.4.5 {
  catchsql {
    SELECT * FROM main.t2;
  } db2
} {0 {9 8 7}}
do_test temptable-4.4.6 {
  # TEMP takes precedence over MAIN
  catchsql {
    SELECT * FROM t2;
  } db2
} {0 {10 20}}
do_test temptable-4.5 {
  catchsql {
    DROP TABLE t2;     -- should drop TEMP
    SELECT * FROM t2;  -- data should be from MAIN
  } db2
} {0 {9 8 7}}
do_test temptable-4.6 {
  db2 close
  sqlite3 db2 ./test.db
  catchsql {
    SELECT * FROM t2;
  } db2
} {0 {9 8 7}}
do_test temptable-4.7 {
  catchsql {
    DROP TABLE t2;
    SELECT * FROM t2;
  }
} {1 {no such table: t2}}
do_test temptable-4.8 {
  db2 close
  sqlite3 db2 ./test.db
  execsql {
    CREATE TEMP TABLE t2(x unique,y);
    INSERT INTO t2 VALUES(1,2);
    SELECT * FROM t2;
  } db2
} {1 2}
do_test temptable-4.9 {
  execsql {
    CREATE TABLE t2(x unique, y);
    INSERT INTO t2 VALUES(3,4);
    SELECT * FROM t2;
  }
} {3 4}
do_test temptable-4.10.1 {
  catchsql {
    SELECT * FROM t2;
  } db2
} {0 {1 2}}
# Update: The schema is reloaded in test temptable-4.10.1. And tclsqlite.c
#         handles it and retries the query anyway.
# do_test temptable-4.10.2 {
#   catchsql {
#     SELECT name FROM sqlite_master WHERE type='table'
#   } db2
# } {1 {database schema has changed}}
do_test temptable-4.10.3 {
  catchsql {
    SELECT name FROM sqlite_master WHERE type='table'
  } db2
} {0 {t1 t2}}
do_test temptable-4.11 {
  execsql {
    SELECT * FROM t2;
  } db2
} {1 2}
do_test temptable-4.12 {
  execsql {
    SELECT * FROM t2;
  }
} {3 4}
do_test temptable-4.13 {
  catchsql {
    DROP TABLE t2;     -- drops TEMP.T2
    SELECT * FROM t2;  -- uses MAIN.T2
  } db2
} {0 {3 4}}
do_test temptable-4.14 {
  execsql {
    SELECT * FROM t2;
  }
} {3 4}
do_test temptable-4.15 {
  db2 close
  sqlite3 db2 ./test.db
  execsql {
    SELECT * FROM t2;
  } db2
} {3 4}

# Now create a temporary table in db2 and a permanent index in db.  The
# temporary table in db2 should mask the name of the permanent index,
# but the permanent index should still be accessible and should still
# be updated when its corresponding table changes.
#
do_test temptable-5.1 {
  execsql {
    CREATE TEMP TABLE mask(a,b,c)
  } db2
  execsql {
    CREATE INDEX mask ON t2(x);
    SELECT * FROM t2;
  }
} {3 4}
#do_test temptable-5.2 {
#  catchsql {
#    SELECT * FROM t2;
#  } db2
#} {1 {database schema has changed}}
do_test temptable-5.3 {
  catchsql {
    SELECT * FROM t2;
  } db2
} {0 {3 4}}
do_test temptable-5.4 {
  execsql {
    SELECT y FROM t2 WHERE x=3
  }
} {4}
do_test temptable-5.5 {
  execsql {
    SELECT y FROM t2 WHERE x=3
  } db2
} {4}
do_test temptable-5.6 {
  execsql {
    INSERT INTO t2 VALUES(1,2);
    SELECT y FROM t2 WHERE x=1;
  } db2
} {2}
do_test temptable-5.7 {
  execsql {
    SELECT y FROM t2 WHERE x=3
  } db2
} {4}
do_test temptable-5.8 {
  execsql {
    SELECT y FROM t2 WHERE x=1;
  }
} {2}
do_test temptable-5.9 {
  execsql {
    SELECT y FROM t2 WHERE x=3
  }
} {4}

db2 close

# Test for correct operation of read-only databases
#
do_test temptable-6.1 {
  execsql {
    CREATE TABLE t8(x);
    INSERT INTO t8 VALUES('xyzzy');
    SELECT * FROM t8;
  }
} {xyzzy}
do_test temptable-6.2 {
  db close
  catch {file attributes test.db -permissions 0444}
  catch {file attributes test.db -readonly 1}
  sqlite3 db test.db
  if {[file writable test.db]} {
    error "Unable to make the database file test.db readonly - rerun this test as an unprivileged user"
  }
  execsql {
    SELECT * FROM t8;
  }
} {xyzzy}
do_test temptable-6.3 {
  if {[file writable test.db]} {
    error "Unable to make the database file test.db readonly - rerun this test as an unprivileged user"
  }
  catchsql {
    CREATE TABLE t9(x,y);
  }
} {1 {attempt to write a readonly database}}
do_test temptable-6.4 {
  catchsql {
    CREATE TEMP TABLE t9(x,y);
  }
} {0 {}}
do_test temptable-6.5 {
  catchsql {
    INSERT INTO t9 VALUES(1,2);
    SELECT * FROM t9;
  }
} {0 {1 2}}
do_test temptable-6.6 {
  if {[file writable test.db]} {
    error "Unable to make the database file test.db readonly - rerun this test as an unprivileged user"
  }
  catchsql {
    INSERT INTO t8 VALUES('hello');
    SELECT * FROM t8;
  }
} {1 {attempt to write a readonly database}}
do_test temptable-6.7 {
  catchsql {
    SELECT * FROM t8,t9;
  }
} {0 {xyzzy 1 2}}
do_test temptable-6.8 {
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM t8,t9;
  }
} {1 {no such table: t9}}

file delete -force test2.db test2.db-journal
ifcapable attach {
  do_test temptable-7.1 {
    catchsql {
      ATTACH 'test2.db' AS two;
      CREATE TEMP TABLE two.abc(x,y);
    }
  } {1 {temporary table name must be unqualified}}
}

# Need to do the following for tcl 8.5 on mac. On that configuration, the
# -readonly flag is taken so seriously that a subsequent [file delete -force]
# (required before the next test file can be executed) will fail.
#
catch {file attributes test.db -readonly 0}

do_test temptable-8.0 {
  db close
  catch {file delete -force test.db}
  sqlite3 db test.db
} {}
do_test temptable-8.1 {
  execsql { CREATE TEMP TABLE tbl2(a, b); }
  execsql {
    CREATE TABLE tbl(a, b);
    INSERT INTO tbl VALUES(1, 2);
  }
  execsql {SELECT * FROM tbl}
} {1 2}
do_test temptable-8.2 {
  execsql { CREATE TEMP TABLE tbl(a, b); }
  execsql {SELECT * FROM tbl}
} {}

finish_test

Added test/temptrigger.test.

























































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# 2009 February 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: temptrigger.test,v 1.3 2009/04/15 13:07:19 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!trigger || !shared_cache} { finish_test ; return }

# Test cases:
#
#   temptrigger-1.*: Shared cache problem.
#   temptrigger-2.*: A similar shared cache problem.
#   temptrigger-3.*: Attached database problem.
#

#-------------------------------------------------------------------------
# Test case temptrigger-1.* demonstrates a problem with temp triggers
# in shared-cache mode. If process 1 connections to a shared-cache and
# creates a temp trigger, the temp trigger is linked into the shared-cache
# schema. If process 2 reloads the shared-cache schema from disk, then
# it does not recreate the temp trigger belonging to process 1. From the
# point of view of process 1, the temp trigger just disappeared.
# 
#   temptrigger-1.1: In shared cache mode, create a table in the main 
#                    database and add a temp trigger to it.
#
#   temptrigger-1.2: Check that the temp trigger is correctly fired. Check
#                    that the temp trigger is not fired by statements
#                    executed by a second connection connected to the 
#                    same shared cache.
#
#   temptrigger-1.3: Using the second connection to the shared-cache, cause
#                    the shared-cache schema to be reloaded.
#
#   temptrigger-1.4: Check that the temp trigger is still fired correctly.
#
#   temptrigger-1.5: Check that the temp trigger can be dropped without error.
#
db close
set ::enable_shared_cache [sqlite3_enable_shared_cache]
sqlite3_enable_shared_cache 1

sqlite3 db test.db
sqlite3 db2 test.db

do_test temptrigger-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TEMP TABLE tt1(a, b);
    CREATE TEMP TRIGGER tr1 AFTER INSERT ON t1 BEGIN
      INSERT INTO tt1 VALUES(new.a, new.b);
    END;
  }
} {}

do_test temptrigger-1.2.1 {
  execsql { INSERT INTO t1 VALUES(1, 2) }
  execsql { SELECT * FROM t1 }
} {1 2}
do_test temptrigger-1.2.2 {
  execsql { SELECT * FROM tt1 }
} {1 2}
do_test temptrigger-1.2.3 {
  execsql { INSERT INTO t1 VALUES(3, 4) } db2
  execsql { SELECT * FROM t1 }
} {1 2 3 4}
do_test temptrigger-1.2.4 {
  execsql { SELECT * FROM tt1 }
} {1 2}

# Cause the shared-cache schema to be reloaded.
#
do_test temptrigger-1.3 {
  execsql { BEGIN; CREATE TABLE t3(a, b); ROLLBACK; } db2
} {}

do_test temptrigger-1.4 {
  execsql { INSERT INTO t1 VALUES(5, 6) }
  execsql { SELECT * FROM tt1 }
} {1 2 5 6}

do_test temptrigger-1.5 {
  # Before the bug was fixed, the following 'DROP TRIGGER' hit an 
  # assert if executed.
  #execsql { DROP TRIGGER tr1 }
} {}

catch {db close}
catch {db2 close}

#-------------------------------------------------------------------------
# Tests temptrigger-2.* are similar to temptrigger-1.*, except that
# temptrigger-2.3 simply opens and closes a connection to the shared-cache.
# It does not do anything special to cause the schema to be reloaded.
# 
do_test temptrigger-2.1 {
  sqlite3 db test.db
  execsql {
    DELETE FROM t1;
    CREATE TEMP TABLE tt1(a, b);
    CREATE TEMP TRIGGER tr1 AFTER INSERT ON t1 BEGIN
      INSERT INTO tt1 VALUES(new.a, new.b);
    END;
  }
} {}
do_test temptrigger-2.2 {
  execsql {
    INSERT INTO t1 VALUES(10, 20);
    SELECT * FROM tt1;
  }
} {10 20}
do_test temptrigger-2.3 {
  sqlite3 db2 test.db
  db2 close
} {}
do_test temptrigger-2.4 {
  execsql {
    INSERT INTO t1 VALUES(30, 40);
    SELECT * FROM tt1;
  }
} {10 20 30 40}
do_test temptrigger-2.5 {
  #execsql { DROP TRIGGER tr1 }
} {}

catch {db close}
catch {db2 close}
sqlite3_enable_shared_cache $::enable_shared_cache

#-------------------------------------------------------------------------
# Test case temptrigger-3.* demonstrates a problem with temp triggers
# on tables located in attached databases. At one point when SQLite reloaded 
# the schema of an attached database (because some other connection had 
# changed the schema cookie) it was not re-creating temp triggers attached 
# to tables located within the attached database.
# 
#   temptrigger-3.1: Attach database 'test2.db' to connection [db]. Add a
#                    temp trigger to a table in 'test2.db'.
#
#   temptrigger-3.2: Check that the temp trigger is correctly fired.
#
#   temptrigger-3.3: Update the schema of 'test2.db' using an external
#                    connection. This forces [db] to reload the 'test2.db'
#                    schema. Check that the temp trigger is still fired
#                    correctly.
#
#   temptrigger-3.4: Check that the temp trigger can be dropped without error.
# 
do_test temptrigger-3.1 {
  catch { file delete -force test2.db test2.db-journal }
  catch { file delete -force test.db test.db-journal }
  sqlite3 db test.db 
  sqlite3 db2 test2.db 
  execsql { CREATE TABLE t2(a, b) } db2
  execsql {
    ATTACH 'test2.db' AS aux;
    CREATE TEMP TABLE tt2(a, b);
    CREATE TEMP TRIGGER tr2 AFTER INSERT ON aux.t2 BEGIN
      INSERT INTO tt2 VALUES(new.a, new.b);
    END;
  }
} {}

do_test temptrigger-3.2.1 {
  execsql { 
    INSERT INTO aux.t2 VALUES(1, 2);
    SELECT * FROM aux.t2;
  }
} {1 2}
do_test temptrigger-3.2.2 {
  execsql { SELECT * FROM tt2 }
} {1 2}

do_test temptrigger-3.3.1 {
  execsql { CREATE TABLE t3(a, b) } db2
  execsql { 
    INSERT INTO aux.t2 VALUES(3, 4);
    SELECT * FROM aux.t2;
  }
} {1 2 3 4}
do_test temptrigger-3.3.2 {
  execsql { SELECT * FROM tt2 }
} {1 2 3 4}

do_test temptrigger-3.4 {
  # Before the bug was fixed, the following 'DROP TRIGGER' hit an 
  # assert if executed.
  #execsql { DROP TRIGGER tr2 }
} {}

catch { db close }
catch { db2 close }

finish_test

Added test/tester.tcl.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements some common TCL routines used for regression
# testing the SQLite library
#
# $Id: tester.tcl,v 1.143 2009/04/09 01:23:49 drh Exp $

#
# What for user input before continuing.  This gives an opportunity
# to connect profiling tools to the process.
#
for {set i 0} {$i<[llength $argv]} {incr i} {
  if {[regexp {^-+pause$} [lindex $argv $i] all value]} {
    puts -nonewline "Press RETURN to begin..."
    flush stdout
    gets stdin
    set argv [lreplace $argv $i $i]
  }
}

set tcl_precision 15
sqlite3_test_control_pending_byte 0x0010000

# 
# Check the command-line arguments for a default soft-heap-limit.
# Store this default value in the global variable ::soft_limit and
# update the soft-heap-limit each time this script is run.  In that
# way if an individual test file changes the soft-heap-limit, it
# will be reset at the start of the next test file.
#
if {![info exists soft_limit]} {
  set soft_limit 0
  for {set i 0} {$i<[llength $argv]} {incr i} {
    if {[regexp {^--soft-heap-limit=(.+)$} [lindex $argv $i] all value]} {
      if {$value!="off"} {
        set soft_limit $value
      }
      set argv [lreplace $argv $i $i]
    }
  }
}
sqlite3_soft_heap_limit $soft_limit

# 
# Check the command-line arguments to set the memory debugger
# backtrace depth.
#
# See the sqlite3_memdebug_backtrace() function in mem2.c or
# test_malloc.c for additional information.
#
for {set i 0} {$i<[llength $argv]} {incr i} {
  if {[lindex $argv $i] eq "--malloctrace"} {
    set argv [lreplace $argv $i $i]
    sqlite3_memdebug_backtrace 10
    sqlite3_memdebug_log start
    set tester_do_malloctrace 1
  }
}
for {set i 0} {$i<[llength $argv]} {incr i} {
  if {[regexp {^--backtrace=(\d+)$} [lindex $argv $i] all value]} {
    sqlite3_memdebug_backtrace $value
    set argv [lreplace $argv $i $i]
  }
}


proc ostrace_call {zCall nClick zFile i32 i64} {
  set s "INSERT INTO ostrace VALUES('$zCall', $nClick, '$zFile', $i32, $i64);"
  puts $::ostrace_fd $s
}

for {set i 0} {$i<[llength $argv]} {incr i} {
  if {[lindex $argv $i] eq "--ossummary" || [lindex $argv $i] eq "--ostrace"} {
    sqlite3_instvfs create -default ostrace
    set tester_do_ostrace 1
    set ostrace_fd [open ostrace.sql w]
    puts $ostrace_fd "BEGIN;"
    if {[lindex $argv $i] eq "--ostrace"} {
      set    s "CREATE TABLE ostrace"
      append s "(method TEXT, clicks INT, file TEXT, i32 INT, i64 INT);"
      puts $ostrace_fd $s
      sqlite3_instvfs configure ostrace ostrace_call
      sqlite3_instvfs configure ostrace ostrace_call
    }
    set argv [lreplace $argv $i $i]
  }
  if {[lindex $argv $i] eq "--binarylog"} {
    set tester_do_binarylog 1
    set argv [lreplace $argv $i $i]
  }
}

# 
# Check the command-line arguments to set the maximum number of
# errors tolerated before halting.
#
if {![info exists maxErr]} {
  set maxErr 1000
}
for {set i 0} {$i<[llength $argv]} {incr i} {
  if {[regexp {^--maxerror=(\d+)$} [lindex $argv $i] all maxErr]} {
    set argv [lreplace $argv $i $i]
  }
}
#puts "Max error = $maxErr"


# Use the pager codec if it is available
#
if {[sqlite3 -has-codec] && [info command sqlite_orig]==""} {
  rename sqlite3 sqlite_orig
  proc sqlite3 {args} {
    if {[llength $args]==2 && [string index [lindex $args 0] 0]!="-"} {
      lappend args -key {xyzzy}
    }
    uplevel 1 sqlite_orig $args
  }
}


# Create a test database
#
if {![info exists nTest]} {
  sqlite3_shutdown 
  install_malloc_faultsim 1 
  sqlite3_initialize
  autoinstall_test_functions
  if {[info exists tester_do_binarylog]} {
    sqlite3_instvfs binarylog -default binarylog ostrace.bin
    sqlite3_instvfs marker binarylog "$argv0 $argv"
  }
}

proc reset_db {} {
  catch {db close}
  file delete -force test.db
  file delete -force test.db-journal
  sqlite3 db ./test.db
  set ::DB [sqlite3_connection_pointer db]
  if {[info exists ::SETUP_SQL]} {
    db eval $::SETUP_SQL
  }
}
reset_db

# Abort early if this script has been run before.
#
if {[info exists nTest]} return

# Set the test counters to zero
#
set nErr 0
set nTest 0
set skip_test 0
set failList {}
set omitList {}
if {![info exists speedTest]} {
  set speedTest 0
}

# Record the fact that a sequence of tests were omitted.
#
proc omit_test {name reason} {
  global omitList
  lappend omitList [list $name $reason]
}

# Invoke the do_test procedure to run a single test 
#
proc do_test {name cmd expected} {
  global argv nErr nTest skip_test maxErr
  sqlite3_memdebug_settitle $name
  if {[info exists ::tester_do_binarylog]} {
    sqlite3_instvfs marker binarylog "Start of $name"
  }
  if {$skip_test} {
    set skip_test 0
    return
  }
  if {[llength $argv]==0} { 
    set go 1
  } else {
    set go 0
    foreach pattern $argv {
      if {[string match $pattern $name]} {
        set go 1
        break
      }
    }
  }
  if {!$go} return
  incr nTest
  puts -nonewline $name...
  flush stdout
  if {[catch {uplevel #0 "$cmd;\n"} result]} {
    puts "\nError: $result"
    incr nErr
    lappend ::failList $name
    if {$nErr>$maxErr} {puts "*** Giving up..."; finalize_testing}
  } elseif {[string compare $result $expected]} {
    puts "\nExpected: \[$expected\]\n     Got: \[$result\]"
    incr nErr
    lappend ::failList $name
    if {$nErr>=$maxErr} {puts "*** Giving up..."; finalize_testing}
  } else {
    puts " Ok"
  }
  flush stdout
  if {[info exists ::tester_do_binarylog]} {
    sqlite3_instvfs marker binarylog "End of $name"
  }
}

# Run an SQL script.  
# Return the number of microseconds per statement.
#
proc speed_trial {name numstmt units sql} {
  puts -nonewline [format {%-21.21s } $name...]
  flush stdout
  set speed [time {sqlite3_exec_nr db $sql}]
  set tm [lindex $speed 0]
  if {$tm == 0} {
    set rate [format %20s "many"]
  } else {
    set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
  }
  set u2 $units/s
  puts [format {%12d uS %s %s} $tm $rate $u2]
  global total_time
  set total_time [expr {$total_time+$tm}]
}
proc speed_trial_tcl {name numstmt units script} {
  puts -nonewline [format {%-21.21s } $name...]
  flush stdout
  set speed [time {eval $script}]
  set tm [lindex $speed 0]
  if {$tm == 0} {
    set rate [format %20s "many"]
  } else {
    set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
  }
  set u2 $units/s
  puts [format {%12d uS %s %s} $tm $rate $u2]
  global total_time
  set total_time [expr {$total_time+$tm}]
}
proc speed_trial_init {name} {
  global total_time
  set total_time 0
}
proc speed_trial_summary {name} {
  global total_time
  puts [format {%-21.21s %12d uS TOTAL} $name $total_time]
}

# Run this routine last
#
proc finish_test {} {
  finalize_testing
}
proc finalize_testing {} {
  global nTest nErr sqlite_open_file_count omitList

  catch {db close}
  catch {db2 close}
  catch {db3 close}

  vfs_unlink_test
  sqlite3 db {}
  # sqlite3_clear_tsd_memdebug
  db close
  sqlite3_reset_auto_extension
  set heaplimit [sqlite3_soft_heap_limit]
  if {$heaplimit!=$::soft_limit} {
    puts "soft-heap-limit changed by this script\
          from $::soft_limit to $heaplimit"
  } elseif {$heaplimit!="" && $heaplimit>0} {
    puts "soft-heap-limit set to $heaplimit"
  }
  sqlite3_soft_heap_limit 0
  incr nTest
  puts "$nErr errors out of $nTest tests"
  if {$nErr>0} {
    puts "Failures on these tests: $::failList"
  }
  run_thread_tests 1
  if {[llength $omitList]>0} {
    puts "Omitted test cases:"
    set prec {}
    foreach {rec} [lsort $omitList] {
      if {$rec==$prec} continue
      set prec $rec
      puts [format {  %-12s %s} [lindex $rec 0] [lindex $rec 1]]
    }
  }
  if {$nErr>0 && ![working_64bit_int]} {
    puts "******************************************************************"
    puts "N.B.:  The version of TCL that you used to build this test harness"
    puts "is defective in that it does not support 64-bit integers.  Some or"
    puts "all of the test failures above might be a result from this defect"
    puts "in your TCL build."
    puts "******************************************************************"
  }
  if {[info exists ::tester_do_binarylog]} {
    sqlite3_instvfs destroy binarylog
  }
  if {$sqlite_open_file_count} {
    puts "$sqlite_open_file_count files were left open"
    incr nErr
  }
  if {[info exists ::tester_do_ostrace]} {
    puts "Writing ostrace.sql..."
    set fd $::ostrace_fd

    puts -nonewline $fd "CREATE TABLE ossummary"
    puts $fd "(method TEXT, clicks INTEGER, count INTEGER);"
    foreach row [sqlite3_instvfs report ostrace] {
      foreach {method count clicks} $row break
      puts $fd "INSERT INTO ossummary VALUES('$method', $clicks, $count);"
    }
    puts $fd "COMMIT;"
    close $fd
    sqlite3_instvfs destroy ostrace
  }
  if {[sqlite3_memory_used]>0} {
    puts "Unfreed memory: [sqlite3_memory_used] bytes"
    incr nErr
    ifcapable memdebug||mem5||(mem3&&debug) {
      puts "Writing unfreed memory log to \"./memleak.txt\""
      sqlite3_memdebug_dump ./memleak.txt
    }
  } else {
    puts "All memory allocations freed - no leaks"
    ifcapable memdebug||mem5 {
      sqlite3_memdebug_dump ./memusage.txt
    }
  }
  show_memstats
  puts "Maximum memory usage: [sqlite3_memory_highwater 1] bytes"
  puts "Current memory usage: [sqlite3_memory_highwater] bytes"
  if {[info commands sqlite3_memdebug_malloc_count] ne ""} {
    puts "Number of malloc()  : [sqlite3_memdebug_malloc_count] calls"
  }
  if {[info exists ::tester_do_malloctrace]} {
    puts "Writing mallocs.sql..."
    memdebug_log_sql
    sqlite3_memdebug_log stop
    sqlite3_memdebug_log clear

    if {[sqlite3_memory_used]>0} {
      puts "Writing leaks.sql..."
      sqlite3_memdebug_log sync
      memdebug_log_sql leaks.sql
    }
  }
  foreach f [glob -nocomplain test.db-*-journal] {
    file delete -force $f
  }
  foreach f [glob -nocomplain test.db-mj*] {
    file delete -force $f
  }
  exit [expr {$nErr>0}]
}

# Display memory statistics for analysis and debugging purposes.
#
proc show_memstats {} {
  set x [sqlite3_status SQLITE_STATUS_MEMORY_USED 0]
  set y [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0]
  set val [format {now %10d  max %10d  max-size %10d} \
              [lindex $x 1] [lindex $x 2] [lindex $y 2]]
  puts "Memory used:          $val"
  set x [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0]
  set y [sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 0]
  set val [format {now %10d  max %10d  max-size %10d} \
              [lindex $x 1] [lindex $x 2] [lindex $y 2]]
  puts "Page-cache used:      $val"
  set x [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0]
  set val [format {now %10d  max %10d} [lindex $x 1] [lindex $x 2]]
  puts "Page-cache overflow:  $val"
  set x [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0]
  set val [format {now %10d  max %10d} [lindex $x 1] [lindex $x 2]]
  puts "Scratch memory used:  $val"
  set x [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0]
  set y [sqlite3_status SQLITE_STATUS_SCRATCH_SIZE 0]
  set val [format {now %10d  max %10d  max-size %10d} \
               [lindex $x 1] [lindex $x 2] [lindex $y 2]]
  puts "Scratch overflow:     $val"
  ifcapable yytrackmaxstackdepth {
    set x [sqlite3_status SQLITE_STATUS_PARSER_STACK 0]
    set val [format {               max %10d} [lindex $x 2]]
    puts "Parser stack depth:    $val"
  }
}

# A procedure to execute SQL
#
proc execsql {sql {db db}} {
  # puts "SQL = $sql"
  uplevel [list $db eval $sql]
}

# Execute SQL and catch exceptions.
#
proc catchsql {sql {db db}} {
  # puts "SQL = $sql"
  set r [catch {$db eval $sql} msg]
  lappend r $msg
  return $r
}

# Do an VDBE code dump on the SQL given
#
proc explain {sql {db db}} {
  puts ""
  puts "addr  opcode        p1      p2      p3      p4               p5  #"
  puts "----  ------------  ------  ------  ------  ---------------  --  -"
  $db eval "explain $sql" {} {
    puts [format {%-4d  %-12.12s  %-6d  %-6d  %-6d  % -17s %s  %s} \
      $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment
    ]
  }
}

# Show the VDBE program for an SQL statement but omit the Trace
# opcode at the beginning.  This procedure can be used to prove
# that different SQL statements generate exactly the same VDBE code.
#
proc explain_no_trace {sql} {
  set tr [db eval "EXPLAIN $sql"]
  return [lrange $tr 7 end]
}

# Another procedure to execute SQL.  This one includes the field
# names in the returned list.
#
proc execsql2 {sql} {
  set result {}
  db eval $sql data {
    foreach f $data(*) {
      lappend result $f $data($f)
    }
  }
  return $result
}

# Use the non-callback API to execute multiple SQL statements
#
proc stepsql {dbptr sql} {
  set sql [string trim $sql]
  set r 0
  while {[string length $sql]>0} {
    if {[catch {sqlite3_prepare $dbptr $sql -1 sqltail} vm]} {
      return [list 1 $vm]
    }
    set sql [string trim $sqltail]
#    while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} {
#      foreach v $VAL {lappend r $v}
#    }
    while {[sqlite3_step $vm]=="SQLITE_ROW"} {
      for {set i 0} {$i<[sqlite3_data_count $vm]} {incr i} {
        lappend r [sqlite3_column_text $vm $i]
      }
    }
    if {[catch {sqlite3_finalize $vm} errmsg]} {
      return [list 1 $errmsg]
    }
  }
  return $r
}

# Delete a file or directory
#
proc forcedelete {filename} {
  if {[catch {file delete -force $filename}]} {
    exec rm -rf $filename
  }
}

# Do an integrity check of the entire database
#
proc integrity_check {name {db db}} {
  ifcapable integrityck {
    do_test $name [list execsql {PRAGMA integrity_check} $db] {ok}
  }
}

proc fix_ifcapable_expr {expr} {
  set ret ""
  set state 0
  for {set i 0} {$i < [string length $expr]} {incr i} {
    set char [string range $expr $i $i]
    set newstate [expr {[string is alnum $char] || $char eq "_"}]
    if {$newstate && !$state} {
      append ret {$::sqlite_options(}
    }
    if {!$newstate && $state} {
      append ret )
    }
    append ret $char
    set state $newstate
  }
  if {$state} {append ret )}
  return $ret
}

# Evaluate a boolean expression of capabilities.  If true, execute the
# code.  Omit the code if false.
#
proc ifcapable {expr code {else ""} {elsecode ""}} {
  #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2
  set e2 [fix_ifcapable_expr $expr]
  if ($e2) {
    set c [catch {uplevel 1 $code} r]
  } else {
    set c [catch {uplevel 1 $elsecode} r]
  }
  return -code $c $r
}

# This proc execs a seperate process that crashes midway through executing
# the SQL script $sql on database test.db.
#
# The crash occurs during a sync() of file $crashfile. When the crash
# occurs a random subset of all unsynced writes made by the process are
# written into the files on disk. Argument $crashdelay indicates the
# number of file syncs to wait before crashing.
#
# The return value is a list of two elements. The first element is a
# boolean, indicating whether or not the process actually crashed or
# reported some other error. The second element in the returned list is the
# error message. This is "child process exited abnormally" if the crash
# occured.
#
#   crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql
#
proc crashsql {args} {
  if {$::tcl_platform(platform)!="unix"} {
    error "crashsql should only be used on unix"
  }

  set blocksize ""
  set crashdelay 1
  set prngseed 0
  set tclbody {}
  set crashfile ""
  set dc ""
  set sql [lindex $args end]
  
  for {set ii 0} {$ii < [llength $args]-1} {incr ii 2} {
    set z [lindex $args $ii]
    set n [string length $z]
    set z2 [lindex $args [expr $ii+1]]

    if     {$n>1 && [string first $z -delay]==0}     {set crashdelay $z2} \
    elseif {$n>1 && [string first $z -seed]==0}      {set prngseed $z2} \
    elseif {$n>1 && [string first $z -file]==0}      {set crashfile $z2}  \
    elseif {$n>1 && [string first $z -tclbody]==0}   {set tclbody $z2}  \
    elseif {$n>1 && [string first $z -blocksize]==0} {set blocksize "-s $z2" } \
    elseif {$n>1 && [string first $z -characteristics]==0} {set dc "-c {$z2}" } \
    else   { error "Unrecognized option: $z" }
  }

  if {$crashfile eq ""} {
    error "Compulsory option -file missing"
  }

  set cfile [file join [pwd] $crashfile]

  set f [open crash.tcl w]
  puts $f "sqlite3_crash_enable 1"
  puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
  puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
  puts $f "sqlite3 db test.db -vfs crash"

  # This block sets the cache size of the main database to 10
  # pages. This is done in case the build is configured to omit
  # "PRAGMA cache_size".
  puts $f {db eval {SELECT * FROM sqlite_master;}}
  puts $f {set bt [btree_from_db db]}
  puts $f {btree_set_cache_size $bt 10}
  if {$prngseed} {
    set seed [expr {$prngseed%10007+1}]
    # puts seed=$seed
    puts $f "db eval {SELECT randomblob($seed)}"
  }

  if {[string length $tclbody]>0} {
    puts $f $tclbody
  }
  if {[string length $sql]>0} {
    puts $f "db eval {"
    puts $f   "$sql"
    puts $f "}"
  }
  close $f

  set r [catch {
    exec [info nameofexec] crash.tcl >@stdout
  } msg]
  lappend r $msg
}

# Usage: do_ioerr_test <test number> <options...>
#
# This proc is used to implement test cases that check that IO errors
# are correctly handled. The first argument, <test number>, is an integer 
# used to name the tests executed by this proc. Options are as follows:
#
#     -tclprep          TCL script to run to prepare test.
#     -sqlprep          SQL script to run to prepare test.
#     -tclbody          TCL script to run with IO error simulation.
#     -sqlbody          TCL script to run with IO error simulation.
#     -exclude          List of 'N' values not to test.
#     -erc              Use extended result codes
#     -persist          Make simulated I/O errors persistent
#     -start            Value of 'N' to begin with (default 1)
#
#     -cksum            Boolean. If true, test that the database does
#                       not change during the execution of the test case.
#
proc do_ioerr_test {testname args} {

  set ::ioerropts(-start) 1
  set ::ioerropts(-cksum) 0
  set ::ioerropts(-erc) 0
  set ::ioerropts(-count) 100000000
  set ::ioerropts(-persist) 1
  set ::ioerropts(-ckrefcount) 0
  set ::ioerropts(-restoreprng) 1
  array set ::ioerropts $args

  # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
  # a couple of obscure IO errors that do not return them.
  set ::ioerropts(-erc) 0

  set ::go 1
  #reset_prng_state
  save_prng_state
  for {set n $::ioerropts(-start)} {$::go} {incr n} {
    set ::TN $n
    incr ::ioerropts(-count) -1
    if {$::ioerropts(-count)<0} break
 
    # Skip this IO error if it was specified with the "-exclude" option.
    if {[info exists ::ioerropts(-exclude)]} {
      if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue
    }
    if {$::ioerropts(-restoreprng)} {
      restore_prng_state
    }

    # Delete the files test.db and test2.db, then execute the TCL and 
    # SQL (in that order) to prepare for the test case.
    do_test $testname.$n.1 {
      set ::sqlite_io_error_pending 0
      catch {db close}
      catch {db2 close}
      catch {file delete -force test.db}
      catch {file delete -force test.db-journal}
      catch {file delete -force test2.db}
      catch {file delete -force test2.db-journal}
      set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
      sqlite3_extended_result_codes $::DB $::ioerropts(-erc)
      if {[info exists ::ioerropts(-tclprep)]} {
        eval $::ioerropts(-tclprep)
      }
      if {[info exists ::ioerropts(-sqlprep)]} {
        execsql $::ioerropts(-sqlprep)
      }
      expr 0
    } {0}

    # Read the 'checksum' of the database.
    if {$::ioerropts(-cksum)} {
      set checksum [cksum]
    }

    # Set the Nth IO error to fail.
    do_test $testname.$n.2 [subst {
      set ::sqlite_io_error_persist $::ioerropts(-persist)
      set ::sqlite_io_error_pending $n
    }] $n
  
    # Create a single TCL script from the TCL and SQL specified
    # as the body of the test.
    set ::ioerrorbody {}
    if {[info exists ::ioerropts(-tclbody)]} {
      append ::ioerrorbody "$::ioerropts(-tclbody)\n"
    }
    if {[info exists ::ioerropts(-sqlbody)]} {
      append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}"
    }

    # Execute the TCL Script created in the above block. If
    # there are at least N IO operations performed by SQLite as
    # a result of the script, the Nth will fail.
    do_test $testname.$n.3 {
      set ::sqlite_io_error_hit 0
      set ::sqlite_io_error_hardhit 0
      set r [catch $::ioerrorbody msg]
      set ::errseen $r
      set rc [sqlite3_errcode $::DB]
      if {$::ioerropts(-erc)} {
        # If we are in extended result code mode, make sure all of the
        # IOERRs we get back really do have their extended code values.
        # If an extended result code is returned, the sqlite3_errcode
        # TCLcommand will return a string of the form:  SQLITE_IOERR+nnnn
        # where nnnn is a number
        if {[regexp {^SQLITE_IOERR} $rc] && ![regexp {IOERR\+\d} $rc]} {
          return $rc
        }
      } else {
        # If we are not in extended result code mode, make sure no
        # extended error codes are returned.
        if {[regexp {\+\d} $rc]} {
          return $rc
        }
      }
      # The test repeats as long as $::go is non-zero.  $::go starts out
      # as 1.  When a test runs to completion without hitting an I/O
      # error, that means there is no point in continuing with this test
      # case so set $::go to zero.
      #
      if {$::sqlite_io_error_pending>0} {
        set ::go 0
        set q 0
        set ::sqlite_io_error_pending 0
      } else {
        set q 1
      }

      set s [expr $::sqlite_io_error_hit==0]
      if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} {
        set r 1
      }
      set ::sqlite_io_error_hit 0

      # One of two things must have happened. either
      #   1.  We never hit the IO error and the SQL returned OK
      #   2.  An IO error was hit and the SQL failed
      #
      expr { ($s && !$r && !$q) || (!$s && $r && $q) }
    } {1}

    set ::sqlite_io_error_hit 0
    set ::sqlite_io_error_pending 0

    # Check that no page references were leaked. There should be 
    # a single reference if there is still an active transaction, 
    # or zero otherwise.
    #
    # UPDATE: If the IO error occurs after a 'BEGIN' but before any
    # locks are established on database files (i.e. if the error 
    # occurs while attempting to detect a hot-journal file), then
    # there may 0 page references and an active transaction according
    # to [sqlite3_get_autocommit].
    #
    if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} {
      do_test $testname.$n.4 {
        set bt [btree_from_db db]
        db_enter db
        array set stats [btree_pager_stats $bt]
        db_leave db
        set nRef $stats(ref)
        expr {$nRef == 0 || ([sqlite3_get_autocommit db]==0 && $nRef == 1)}
      } {1}
    }

    # If there is an open database handle and no open transaction, 
    # and the pager is not running in exclusive-locking mode,
    # check that the pager is in "unlocked" state. Theoretically,
    # if a call to xUnlock() failed due to an IO error the underlying
    # file may still be locked.
    #
    ifcapable pragma {
      if { [info commands db] ne ""
        && $::ioerropts(-ckrefcount)
        && [db one {pragma locking_mode}] eq "normal"
        && [sqlite3_get_autocommit db]
      } {
        do_test $testname.$n.5 {
          set bt [btree_from_db db]
          db_enter db
          array set stats [btree_pager_stats $bt]
          db_leave db
          set stats(state)
        } 0
      }
    }

    # If an IO error occured, then the checksum of the database should
    # be the same as before the script that caused the IO error was run.
    #
    if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} {
      do_test $testname.$n.6 {
        catch {db close}
        catch {db2 close}
        set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
        cksum
      } $checksum
    }

    set ::sqlite_io_error_hardhit 0
    set ::sqlite_io_error_pending 0
    if {[info exists ::ioerropts(-cleanup)]} {
      catch $::ioerropts(-cleanup)
    }
  }
  set ::sqlite_io_error_pending 0
  set ::sqlite_io_error_persist 0
  unset ::ioerropts
}

# Return a checksum based on the contents of the main database associated
# with connection $db
#
proc cksum {{db db}} {
  set txt [$db eval {
      SELECT name, type, sql FROM sqlite_master order by name
  }]\n
  foreach tbl [$db eval {
      SELECT name FROM sqlite_master WHERE type='table' order by name
  }] {
    append txt [$db eval "SELECT * FROM $tbl"]\n
  }
  foreach prag {default_synchronous default_cache_size} {
    append txt $prag-[$db eval "PRAGMA $prag"]\n
  }
  set cksum [string length $txt]-[md5 $txt]
  # puts $cksum-[file size test.db]
  return $cksum
}

# Generate a checksum based on the contents of the main and temp tables
# database $db. If the checksum of two databases is the same, and the
# integrity-check passes for both, the two databases are identical.
#
proc allcksum {{db db}} {
  set ret [list]
  ifcapable tempdb {
    set sql {
      SELECT name FROM sqlite_master WHERE type = 'table' UNION
      SELECT name FROM sqlite_temp_master WHERE type = 'table' UNION
      SELECT 'sqlite_master' UNION
      SELECT 'sqlite_temp_master' ORDER BY 1
    }
  } else {
    set sql {
      SELECT name FROM sqlite_master WHERE type = 'table' UNION
      SELECT 'sqlite_master' ORDER BY 1
    }
  }
  set tbllist [$db eval $sql]
  set txt {}
  foreach tbl $tbllist {
    append txt [$db eval "SELECT * FROM $tbl"]
  }
  foreach prag {default_cache_size} {
    append txt $prag-[$db eval "PRAGMA $prag"]\n
  }
  # puts txt=$txt
  return [md5 $txt]
}

# Generate a checksum based on the contents of a single database with
# a database connection.  The name of the database is $dbname.  
# Examples of $dbname are "temp" or "main".
#
proc dbcksum {db dbname} {
  if {$dbname=="temp"} {
    set master sqlite_temp_master
  } else {
    set master $dbname.sqlite_master
  }
  set alltab [$db eval "SELECT name FROM $master WHERE type='table'"]
  set txt [$db eval "SELECT * FROM $master"]\n
  foreach tab $alltab {
    append txt [$db eval "SELECT * FROM $dbname.$tab"]\n
  }
  return [md5 $txt]
}

proc memdebug_log_sql {{filename mallocs.sql}} {

  set data [sqlite3_memdebug_log dump]
  set nFrame [expr [llength [lindex $data 0]]-2]
  if {$nFrame < 0} { return "" }

  set database temp

  set tbl "CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);"

  set sql ""
  foreach e $data {
    set nCall [lindex $e 0]
    set nByte [lindex $e 1]
    set lStack [lrange $e 2 end]
    append sql "INSERT INTO ${database}.malloc VALUES"
    append sql "('test', $nCall, $nByte, '$lStack');\n"
    foreach f $lStack {
      set frames($f) 1
    }
  }

  set tbl2 "CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n"
  set tbl3 "CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n"

  foreach f [array names frames] {
    set addr [format %x $f]
    set cmd "addr2line -e [info nameofexec] $addr"
    set line [eval exec $cmd]
    append sql "INSERT INTO ${database}.frame VALUES($f, '$line');\n"

    set file [lindex [split $line :] 0]
    set files($file) 1
  }

  foreach f [array names files] {
    set contents ""
    catch {
      set fd [open $f]
      set contents [read $fd]
      close $fd
    }
    set contents [string map {' ''} $contents]
    append sql "INSERT INTO ${database}.file VALUES('$f', '$contents');\n"
  }

  set fd [open $filename w]
  puts $fd "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;"
  close $fd
}

# Copy file $from into $to. This is used because some versions of
# TCL for windows (notably the 8.4.1 binary package shipped with the
# current mingw release) have a broken "file copy" command.
#
proc copy_file {from to} {
  if {$::tcl_platform(platform)=="unix"} {
    file copy -force $from $to
  } else {
    set f [open $from]
    fconfigure $f -translation binary
    set t [open $to w]
    fconfigure $t -translation binary
    puts -nonewline $t [read $f [file size $from]]
    close $t
    close $f
  }
}

# Drop all tables in database [db]
proc drop_all_tables {{db db}} {
  set pk [$db one "PRAGMA foreign_keys"]
  $db eval "PRAGMA foreign_keys = OFF"
  foreach {t type} [$db eval {
    SELECT name, type FROM sqlite_master 
    WHERE type IN('table', 'view') AND name NOT like 'sqlite_%'
  }] {
    $db eval "DROP $type $t"
  }
  $db eval " PRAGMA foreign_keys = $pk "
}


# If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
# to non-zero, then set the global variable $AUTOVACUUM to 1.
set AUTOVACUUM $sqlite_options(default_autovacuum)

source $testdir/thread_common.tcl

Added test/thread001.test.



































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# 2007 September 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: thread001.test,v 1.10 2009/03/26 14:48:07 danielk1977 Exp $

set testdir [file dirname $argv0]

source $testdir/tester.tcl
if {[run_thread_tests]==0} { finish_test ; return }

set ::enable_shared_cache [sqlite3_enable_shared_cache]

set ::NTHREAD 10

# Run this test three times: 
# 
#    1) All threads use the same database handle.
#    2) All threads use their own database handles.
#    3) All threads use their own database handles, shared-cache is enabled.
#
#
#
foreach {tn same_db shared_cache} [list \
         1  1       0                   \
         2  0       0                   \
         3  0       1                   \
] {
  # Empty the database.
  #
  catchsql { DROP TABLE ab; }

  do_test thread001.$tn.0 {
    db close
    sqlite3_enable_shared_cache $shared_cache
    sqlite3_enable_shared_cache $shared_cache
  } $shared_cache
  sqlite3 db test.db -fullmutex 1

  set dbconfig ""
  if {$same_db} {
    set dbconfig [list set ::DB [sqlite3_connection_pointer db]]
  }

  # Set up a database and a schema. The database contains a single
  # table with two columns. The first column ("a") is an INTEGER PRIMARY 
  # KEY. The second contains the md5sum of all rows in the table with
  # a smaller value stored in column "a".
  #
  do_test thread001.$tn.1 {
    execsql {
      CREATE TABLE ab(a INTEGER PRIMARY KEY, b);
      CREATE INDEX ab_i ON ab(b);
      INSERT INTO ab SELECT NULL, md5sum(a, b) FROM ab;
      SELECT count(*) FROM ab;
    }
  } {1}
  do_test thread001.$tn.2 {
    execsql {
      SELECT 
        (SELECT md5sum(a, b) FROM ab WHERE a < (SELECT max(a) FROM ab)) ==
        (SELECT b FROM ab WHERE a = (SELECT max(a) FROM ab))
    }
  } {1}
  do_test thread001.$tn.3 {
    execsql { PRAGMA integrity_check }
  } {ok}

  set thread_program {
    #sqlthread parent {puts STARTING..}
    set needToClose 0
    if {![info exists ::DB]} {
      set ::DB [sqlthread open test.db]
      #sqlthread parent "puts \"OPEN $::DB\""
      set needToClose 1
    }
  
    for {set i 0} {$i < 100} {incr i} {
      # Test that the invariant is true.
      do_test t1 {
        execsql {
          SELECT 
            (SELECT md5sum(a, b) FROM ab WHERE a < (SELECT max(a) FROM ab)) ==
            (SELECT b FROM ab WHERE a = (SELECT max(a) FROM ab))
        }
      } {1}
  
      # Add another row to the database.
      execsql { INSERT INTO ab SELECT NULL, md5sum(a, b) FROM ab }
    }
  
    if {$needToClose} {
      #sqlthread parent "puts \"CLOSE $::DB\""
      sqlite3_close $::DB
    }
    #sqlthread parent "puts \"DONE\""
  
    list OK
  }
  
  # Kick off $::NTHREAD threads:
  #
  array unset finished
  for {set i 0} {$i < $::NTHREAD} {incr i} {
    thread_spawn finished($i) $dbconfig $thread_procs $thread_program
  }
  
  # Wait for all threads to finish,  then check they all returned "OK".
  #
  for {set i 0} {$i < $::NTHREAD} {incr i} {
    if {![info exists finished($i)]} {
      vwait finished($i)
    }
    do_test thread001.$tn.4.$i {
      set ::finished($i)
    } OK
  }
  
  # Check the database still looks Ok.
  #
  do_test thread001.$tn.5 {
    execsql { SELECT count(*) FROM ab; }
  } [expr {1 + $::NTHREAD*100}]
  do_test thread001.$tn.6 {
    execsql {
      SELECT 
        (SELECT md5sum(a, b) FROM ab WHERE a < (SELECT max(a) FROM ab)) ==
        (SELECT b FROM ab WHERE a = (SELECT max(a) FROM ab))
    }
  } {1}
  do_test thread001.$tn.7 {
    execsql { PRAGMA integrity_check }
  } {ok}
}

sqlite3_enable_shared_cache $::enable_shared_cache
set sqlite_open_file_count 0
finish_test

Added test/thread002.test.















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 2007 September 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
#   This test attempts to deadlock SQLite in shared-cache mode.
#     
#
# $Id: thread002.test,v 1.9 2009/03/26 14:48:07 danielk1977 Exp $

set testdir [file dirname $argv0]

source $testdir/tester.tcl
if {[run_thread_tests]==0} { finish_test ; return }

db close
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

set ::NTHREAD 10

do_test thread002.1 {
  # Create 3 databases with identical schemas:
  for {set ii 0} {$ii < 3} {incr ii} {
    file delete -force test${ii}.db
    sqlite3 db test${ii}.db
    execsql {
      CREATE TABLE t1(k, v);
      CREATE INDEX t1_i ON t1(v);
      INSERT INTO t1(v) VALUES(1.0);
    }
    db close
  }
} {}

set thread_program {
  set ::DB [sqlite3_open test.db]
  for {set ii 1} {$ii <= 3} {incr ii} {
    set T [lindex $order [expr $ii-1]]
    execsql "ATTACH 'test${T}.db' AS aux${ii}"
  }

  for {set ii 0} {$ii < 100} {incr ii} {
    execsql { SELECT * FROM aux1.t1 }
    execsql { INSERT INTO aux1.t1(v) SELECT sum(v) FROM aux2.t1 }
  
    execsql { SELECT * FROM aux2.t1 }
    execsql { INSERT INTO aux2.t1(v) SELECT sum(v) FROM aux3.t1 }
  
    execsql { SELECT * FROM aux3.t1 }
    execsql { INSERT INTO aux3.t1(v) SELECT sum(v) FROM aux1.t1 }

    execsql { CREATE TABLE IF NOT EXISTS aux1.t2(a,b) }
    execsql { DROP TABLE IF EXISTS aux1.t2 }

    # if {($ii%10)==0} {puts -nonewline . ; flush stdout}
    puts -nonewline . ; flush stdout
  }

  sqlite3_close $::DB
  list OK
}

set order_list [list {0 1 2} {0 2 1} {1 0 2} {1 2 0} {2 0 1} {2 1 0}]

array unset finished
for {set ii 0} {$ii < $::NTHREAD} {incr ii} {
  set order [lindex $order_list [expr $ii%6]]
  thread_spawn finished($ii) $thread_procs "set order {$order}" $thread_program
}

# Wait for all threads to finish,  then check they all returned "OK".
#
for {set i 0} {$i < $::NTHREAD} {incr i} {
  if {![info exists finished($i)]} {
    vwait finished($i)
  }
  do_test thread002.2.$i {
    set ::finished($i)
  } OK
}

# Check all three databases are Ok.
for {set ii 0} {$ii < 3} {incr ii} {
  do_test thread002.3.$ii {
    sqlite3 db test${ii}.db
    set res [list                         \
      [execsql {SELECT count(*) FROM t1}] \
      [execsql {PRAGMA integrity_check}]  \
    ]
    db close
    set res
  } [list [expr 1 + $::NTHREAD*100] ok]
}

sqlite3_enable_shared_cache $::enable_shared_cache
set sqlite_open_file_count 0
finish_test

Added test/thread003.test.



























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# 2007 September 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
#   This file contains tests that attempt to break the pcache module
#   by bombarding it with simultaneous requests from multiple threads.
#     
# $Id: thread003.test,v 1.8 2009/03/26 14:48:07 danielk1977 Exp $

set testdir [file dirname $argv0]

source $testdir/tester.tcl
if {[run_thread_tests]==0} { finish_test ; return }

# Set up a couple of different databases full of pseudo-randomly 
# generated data.
#
do_test thread003.1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b, c);
  }
  for {set ii 0} {$ii < 5000} {incr ii} {
    execsql {INSERT INTO t1 VALUES($ii, randomblob(200), randomblob(200))}
  }
  execsql { 
    CREATE INDEX i1 ON t1(a, b); 
    COMMIT;
  }
} {}
do_test thread003.1.2 {
  expr {([file size test.db] / 1024) > 2000}
} {1}
do_test thread003.1.3 {
  db close
  file delete -force test2.db
  sqlite3 db test2.db
} {}
do_test thread003.1.4 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b, c);
  }
  for {set ii 0} {$ii < 5000} {incr ii} {
    execsql {INSERT INTO t1 VALUES($ii, randomblob(200), randomblob(200))}
  }
  execsql { 
    CREATE INDEX i1 ON t1(a, b); 
    COMMIT;
  }
} {}
do_test thread003.1.5 {
  expr {([file size test.db] / 1024) > 2000}
} {1}
do_test thread003.1.6 {
  db close
} {}


# This test opens a connection on each of the large (>2MB) database files
# created by the previous block. The connections do not share a cache.
# Both "cache_size" parameters are set to 15, so there is a maximum of
# 30 pages available globally.
#
# Then, in separate threads, the databases are randomly queried over and
# over again. This will force the connections to recycle clean pages from
# each other. If there is a thread-safety problem, a segfault or assertion
# failure may eventually occur.
#
set nSecond 30
puts "Starting thread003.2 (should run for ~$nSecond seconds)"
do_test thread003.2 {
  foreach zFile {test.db test2.db} {
    set SCRIPT [format {
      set iEnd [expr {[clock_seconds] + %d}]
      set ::DB [sqlthread open %s]
  
      # Set the cache size to 15 pages per cache. 30 available globally.
      execsql { PRAGMA cache_size = 15 }
  
      while {[clock_seconds] < $iEnd} {
        set iQuery [expr {int(rand()*5000)}]
        execsql " SELECT * FROM t1 WHERE a = $iQuery "
      }
  
      sqlite3_close $::DB
      expr 1
    } $nSecond $zFile]
  
    unset -nocomplain finished($zFile)
    thread_spawn finished($zFile) $thread_procs $SCRIPT
  }
  foreach zFile {test.db test2.db} {
    if {![info exists finished($zFile)]} {
      vwait finished($zFile)
    }
  }
  expr 0
} {0}

# This test is the same as the test above, except that each thread also
# writes to the database. This causes pages to be moved back and forth 
# between the caches internal dirty and clean lists, which is another
# opportunity for a thread-related bug to present itself.
#
set nSecond 30
puts "Starting thread003.3 (should run for ~$nSecond seconds)"
do_test thread003.3 {
  foreach zFile {test.db test2.db} {
    set SCRIPT [format {
      set iStart [clock_seconds]
      set iEnd [expr {[clock_seconds] + %d}]
      set ::DB [sqlthread open %s]
  
      # Set the cache size to 15 pages per cache. 30 available globally.
      execsql { PRAGMA cache_size = 15 }
  
      while {[clock_seconds] < $iEnd} {
        set iQuery [expr {int(rand()*5000)}]
        execsql "SELECT * FROM t1 WHERE a = $iQuery"
        execsql "UPDATE t1 SET b = randomblob(200) 
                 WHERE a < $iQuery AND a > $iQuery + 20
        "
      }
  
      sqlite3_close $::DB
      expr 1
    } $nSecond $zFile]
  
    unset -nocomplain finished($zFile)
    thread_spawn finished($zFile) $thread_procs $SCRIPT
  }
  foreach zFile {test.db test2.db} {
    if {![info exists finished($zFile)]} {
      vwait finished($zFile)
    }
  }
  expr 0
} {0}

# In this test case, one thread is continually querying the database.
# The other thread does not have a database connection, but calls
# sqlite3_release_memory() over and over again.
#
set nSecond 30
puts "Starting thread003.4 (should run for ~$nSecond seconds)"
unset -nocomplain finished(1)
unset -nocomplain finished(2)
do_test thread003.4 {
  thread_spawn finished(1) $thread_procs [format {
    set iEnd [expr {[clock_seconds] + %d}]
    set ::DB [sqlthread open test.db]

    # Set the cache size to 15 pages per cache. 30 available globally.
    execsql { PRAGMA cache_size = 15 }

    while {[clock_seconds] < $iEnd} {
      set iQuery [expr {int(rand()*5000)}]
      execsql "SELECT * FROM t1 WHERE a = $iQuery"
    }

    sqlite3_close $::DB
    expr 1
  } $nSecond] 
  thread_spawn finished(2) [format {
    set iEnd [expr {[clock_seconds] + %d}]

    while {[clock_seconds] < $iEnd} {
      sqlite3_release_memory 1000
    }
  } $nSecond]
  
  foreach ii {1 2} {
    if {![info exists finished($ii)]} {
      vwait finished($ii)
    }
  }
  expr 0
} {0}

set sqlite_open_file_count 0
finish_test

Added test/thread004.test.































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 2009 February 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: thread004.test,v 1.3 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]

source $testdir/tester.tcl
if {[run_thread_tests]==0} { finish_test ; return }
ifcapable !shared_cache {
  finish_test
  return
}
if { [info commands sqlite3_table_column_metadata] eq "" } {
  finish_test
  return
}

# Use shared-cache mode for this test.
# 
db close
set ::enable_shared_cache [sqlite3_enable_shared_cache]
sqlite3_enable_shared_cache 1

# Create a table in database test.db
#
sqlite3 db test.db
do_test thread004-1.1 {
  execsql { CREATE TABLE t1(a, b, c) }
} {}

do_test thread004-1.2 {

  set ThreadOne {
    set iStart [clock_seconds]
    while {[clock_seconds]<$iStart+20} {
      set ::DB [sqlite3_open test.db]
      sqlite3_close $::DB
    }
  }
  set ThreadTwo {
    set ::DB [sqlite3_open test.db]
    set iStart [clock_seconds]
    set nErr 0
    while {[clock_seconds] <$iStart+20} {
      incr nErr [catch {sqlite3_table_column_metadata $::DB main t1 a}]
    }
    sqlite3_close $::DB
    set nErr
  }
  
  # Run two threads. The first thread opens and closes database test.db
  # repeatedly. Each time this happens, the in-memory schema used by
  # all connections to test.db is discarded.
  #
  # The second thread calls sqlite3_table_column_metadata() over and
  # over again. Each time it is called, the database schema is loaded
  # if it is not already in memory. At one point this was crashing.
  #
  unset -nocomplain finished
  thread_spawn finished(1) $thread_procs $ThreadOne
  thread_spawn finished(2) $thread_procs $ThreadTwo
  
  foreach t {1 2} {
    if {![info exists finished($t)]} { vwait finished($t) }
  }

  set finished(2)
} {0}
sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/thread005.test.





























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# 2009 March 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Test a race-condition that shows up in shared-cache mode.
#
# $Id: thread005.test,v 1.5 2009/03/26 14:48:07 danielk1977 Exp $

set testdir [file dirname $argv0]

source $testdir/tester.tcl
if {[run_thread_tests]==0} { finish_test ; return }
ifcapable !shared_cache {
  finish_test
  return
}

db close

# Use shared-cache mode for these tests.
# 
set ::enable_shared_cache [sqlite3_enable_shared_cache]
sqlite3_enable_shared_cache 1

#-------------------------------------------------------------------------
# This test attempts to hit the race condition fixed by commit [6363].
#
proc runsql {zSql {db {}}} {
  set rc SQLITE_OK
  while {$rc=="SQLITE_OK" && $zSql ne ""} {
    set STMT [sqlite3_prepare_v2 $db $zSql -1 zSql]
    while {[set rc [sqlite3_step $STMT]] eq "SQLITE_ROW"} { }
    set rc [sqlite3_finalize $STMT]
  }
  return $rc
}
do_test thread005-1.1 {
  sqlite3 db test.db
  db eval { CREATE TABLE t1(a, b) }
  db close
} {}
for {set ii 2} {$ii < 500} {incr ii} {
  unset -nocomplain finished
  thread_spawn finished(0) {sqlite3_open test.db}
  thread_spawn finished(1) {sqlite3_open test.db}
  if {![info exists finished(0)]} { vwait finished(0) }
  if {![info exists finished(1)]} { vwait finished(1) }

  do_test thread005-1.$ii {
    runsql { BEGIN }                       $finished(0)
    runsql { INSERT INTO t1 VALUES(1, 2) } $finished(0)

    # If the race-condition was hit, then $finished(0 and $finished(1)
    # will not use the same pager cache. In this case the next statement
    # can be executed succesfully. However, if the race-condition is not
    # hit, then $finished(1) will be blocked by the write-lock held by 
    # $finished(0) on the shared-cache table t1 and the statement will
    # return SQLITE_LOCKED.
    #
    runsql { SELECT * FROM t1 }            $finished(1)
  } {SQLITE_LOCKED}

  sqlite3_close $finished(0)
  sqlite3_close $finished(1)
}


#-------------------------------------------------------------------------
# This test tries to exercise a race-condition that existed in shared-cache
# mode at one point. The test uses two threads; each has a database connection
# open on the same shared cache. The schema of the database is:
#
#    CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE);
#
# One thread is a reader and the other thread a reader and a writer. The 
# writer thread repeats the following transaction as fast as possible:
# 
#      BEGIN;
#        DELETE FROM t1 WHERE a = (SELECT max(a) FROM t1);
#        INSERT INTO t1 VALUES(NULL, NULL);
#        UPDATE t1 SET b = a WHERE a = (SELECT max(a) FROM t1);
#        SELECT count(*) FROM t1 WHERE b IS NULL;
#      COMMIT;
#
# The reader thread does the following over and over as fast as possible:
#
#      BEGIN;
#        SELECT count(*) FROM t1 WHERE b IS NULL;
#      COMMIT;
#
# The test runs for 20 seconds or until one of the "SELECT count(*)" 
# statements returns a non-zero value. If an SQLITE_LOCKED error occurs,
# the connection issues a ROLLBACK immediately to abandon the current
# transaction.
#
# If everything is working correctly, the "SELECT count(*)" statements 
# should never return a value other than 0. The "INSERT" statement 
# executed by the writer adds a row with "b IS NULL" to the table, but
# the subsequent UPDATE statement sets its "b" value to an integer
# immediately afterwards.
#
# However, before the race-condition was fixed, if the reader's SELECT
# statement hit an error (say an SQLITE_LOCKED) at the same time as the
# writer was executing the UPDATE statement, then it could incorrectly
# rollback the statement-transaction belonging to the UPDATE statement.
# The UPDATE statement would still be reported as successful to the user,
# but it would have no effect on the database contents.
# 
# Note that it has so far only proved possible to hit this race-condition
# when using an ATTACHed database. There doesn't seem to be any reason
# for this, other than that operating on an ATTACHed database means there
# are a few more mutex grabs and releases during the window of time open
# for the race-condition. Maybe this encourages the scheduler to context
# switch or something...
#

file delete -force test.db test2.db
unset -nocomplain finished

do_test thread005-2.1 {
  sqlite3 db test.db
  execsql { ATTACH 'test2.db' AS aux }
  execsql {
    CREATE TABLE aux.t1(a INTEGER PRIMARY KEY, b UNIQUE);
    INSERT INTO t1 VALUES(1, 1);
    INSERT INTO t1 VALUES(2, 2);
  }
  db close
} {}


set ThreadProgram {
  proc execsql {zSql {db {}}} {
    if {$db eq ""} {set db $::DB}

    set lRes [list]
    set rc SQLITE_OK

    while {$rc=="SQLITE_OK" && $zSql ne ""} {
      set STMT [sqlite3_prepare_v2 $db $zSql -1 zSql]
      while {[set rc [sqlite3_step $STMT]] eq "SQLITE_ROW"} {
        for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} {
          lappend lRes [sqlite3_column_text $STMT 0]
        }
      }
      set rc [sqlite3_finalize $STMT]
    }

    if {$rc != "SQLITE_OK"} { error "$rc [sqlite3_errmsg $db]" }
    return $lRes
  }

  if {$isWriter} {
    set Sql {
      BEGIN;
        DELETE FROM t1 WHERE a = (SELECT max(a) FROM t1);
        INSERT INTO t1 VALUES(NULL, NULL);
        UPDATE t1 SET b = a WHERE a = (SELECT max(a) FROM t1);
        SELECT count(*) FROM t1 WHERE b IS NULL;
      COMMIT;
    }
  } else {
    set Sql {
      BEGIN;
      SELECT count(*) FROM t1 WHERE b IS NULL;
      COMMIT;
    }
  }

  set ::DB [sqlite3_open test.db]

  execsql { ATTACH 'test2.db' AS aux }

  set result "ok"
  set finish [expr [clock_seconds]+5]
  while {$result eq "ok" && [clock_seconds] < $finish} {
    set rc [catch {execsql $Sql} msg]
    if {$rc} {
      if {[string match "SQLITE_LOCKED*" $msg]} {
        catch { execsql ROLLBACK }
      } else {
        sqlite3_close $::DB
        error $msg
      }
    } elseif {$msg ne "0"} {
      set result "failed"
    }
  }

  sqlite3_close $::DB
  set result
}

# There is a race-condition in btree.c that means that if two threads
# attempt to open the same database at roughly the same time, and there
# does not already exist a shared-cache corresponding to that database,
# then two shared-caches can be created instead of one. Things still more
# or less work, but the two database connections do not use the same
# shared-cache.
#
# If the threads run by this test hit this race-condition, the tests
# fail (because SQLITE_BUSY may be unexpectedly returned instead of
# SQLITE_LOCKED). To prevent this from happening, open a couple of
# connections to test.db and test2.db now to make sure that there are
# already shared-caches in memory for all databases opened by the
# test threads.
#
sqlite3 db test.db
sqlite3 db test2.db

puts "Running thread-tests for ~20 seconds"
thread_spawn finished(0) {set isWriter 0} $ThreadProgram
thread_spawn finished(1) {set isWriter 1} $ThreadProgram
if {![info exists finished(0)]} { vwait finished(0) }
if {![info exists finished(1)]} { vwait finished(1) }

catch { db close }
catch { db2 close }

do_test thread005-2.2 {
  list $finished(0) $finished(1)
} {ok ok}

do_test thread005-2.3 {
  sqlite3 db test.db
  execsql { ATTACH 'test2.db' AS aux }
  execsql { SELECT count(*) FROM t1 WHERE b IS NULL }
} {0}

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/thread1.test.

































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# 2003 December 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is multithreading behavior
#
# $Id: thread1.test,v 1.8 2008/10/07 15:25:49 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Skip this whole file if the thread testing code is not enabled
#
ifcapable !mutex {
  finish_test
  return
}
if {[llength [info command thread_step]]==0 || [sqlite3 -has-codec]} {
  finish_test
  return
}

# Create some data to work with
#
do_test thread1-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,'abcdefgh');
    INSERT INTO t1 SELECT a+1, b||b FROM t1;
    INSERT INTO t1 SELECT a+2, b||b FROM t1;
    INSERT INTO t1 SELECT a+4, b||b FROM t1;
    SELECT count(*), max(length(b)) FROM t1;
  }
} {8 64}

# Interleave two threads on read access.  Then make sure a third
# thread can write the database.  In other words:
#
#    read-lock A
#    read-lock B
#    unlock A
#    unlock B
#    write-lock C
#
# At one point, the write-lock of C would fail on Linux. 
#
do_test thread1-1.2 {
  thread_create A test.db
  thread_create B test.db
  thread_create C test.db
  thread_compile A {SELECT a FROM t1}
  thread_step A
  thread_result A
} SQLITE_ROW
do_test thread1-1.3 {
  thread_argc A
} 1
do_test thread1-1.4 {
  thread_argv A 0
} 1
do_test thread1-1.5 {
  thread_compile B {SELECT b FROM t1}
  thread_step B
  thread_result B
} SQLITE_ROW
do_test thread1-1.6 {
  thread_argc B
} 1
do_test thread1-1.7 {
  thread_argv B 0
} abcdefgh
do_test thread1-1.8 {
  thread_finalize A
  thread_result A
} SQLITE_OK
do_test thread1-1.9 {
  thread_finalize B
  thread_result B
} SQLITE_OK
do_test thread1-1.10 {
  thread_compile C {CREATE TABLE t2(x,y)}
  thread_step C
  thread_result C
} SQLITE_DONE
do_test thread1-1.11 {
  thread_finalize C
  thread_result C
} SQLITE_OK
do_test thread1-1.12 {
  catchsql {SELECT name FROM sqlite_master}
  execsql {SELECT name FROM sqlite_master}
} {t1 t2}


#
# The following tests - thread1-2.* - test the following scenario:
#
# 1:  Read-lock thread A
# 2:  Read-lock thread B
# 3:  Attempt to write in thread C -> SQLITE_BUSY
# 4:  Check db write failed from main thread.
# 5:  Unlock from thread A.
# 6:  Attempt to write in thread C -> SQLITE_BUSY
# 7:  Check db write failed from main thread.
# 8:  Unlock from thread B.
# 9:  Attempt to write in thread C -> SQLITE_DONE
# 10: Finalize the write from thread C
# 11: Check db write succeeded from main thread.
#
do_test thread1-2.1 {
  thread_halt *
  thread_create A test.db
  thread_compile A {SELECT a FROM t1}
  thread_step A
  thread_result A
} SQLITE_ROW
do_test thread1-2.2 {
  thread_create B test.db
  thread_compile B {SELECT b FROM t1}
  thread_step B
  thread_result B
} SQLITE_ROW
do_test thread1-2.3 {
  thread_create C test.db
  thread_compile C {INSERT INTO t2 VALUES(98,99)}
  thread_step C
  thread_result C
  thread_finalize C
  thread_result C
} SQLITE_BUSY

do_test thread1-2.4 {
  execsql {SELECT * FROM t2}
} {}

do_test thread1-2.5 {
  thread_finalize A
  thread_result A
} SQLITE_OK
do_test thread1-2.6 {
  thread_compile C {INSERT INTO t2 VALUES(98,99)}
  thread_step C
  thread_result C
  thread_finalize C
  thread_result C
} SQLITE_BUSY
do_test thread1-2.7 {
  execsql {SELECT * FROM t2}
} {}
do_test thread1-2.8 {
  thread_finalize B
  thread_result B
} SQLITE_OK
do_test thread1-2.9 {
  thread_compile C {INSERT INTO t2 VALUES(98,99)}
  thread_step C
  thread_result C
} SQLITE_DONE
do_test thread1-2.10 {
  thread_finalize C
  thread_result C
} SQLITE_OK
do_test thread1-2.11 {
  execsql {SELECT * FROM t2}
} {98 99}

thread_halt *   
finish_test

Added test/thread2.test.

































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# 2006 January 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is multithreading behavior
#
# $Id: thread2.test,v 1.3 2008/10/07 15:25:49 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !mutex {
  finish_test
  return
}


# Skip this whole file if the thread testing code is not enabled
#
if {[llength [info command thread_step]]==0 || [sqlite3 -has-codec]} {
  finish_test
  return
}
if {![info exists threadsOverrideEachOthersLocks]} {
  finish_test
  return
}

# Create some data to work with
#
do_test thread1-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,'abcdefgh');
    INSERT INTO t1 SELECT a+1, b||b FROM t1;
    INSERT INTO t1 SELECT a+2, b||b FROM t1;
    INSERT INTO t1 SELECT a+4, b||b FROM t1;
    SELECT count(*), max(length(b)) FROM t1;
  }
} {8 64}

# Use the thread_swap command to move the database connections between
# threads, then verify that they still work.
#
do_test thread2-1.2 {
  db close
  thread_create A test.db
  thread_create B test.db
  thread_swap A B
  thread_compile A {SELECT a FROM t1 LIMIT 1}
  thread_result A
} {SQLITE_OK}
do_test thread2-1.3 {
  thread_step A
  thread_result A
} {SQLITE_ROW}
do_test thread2-1.4 {
  thread_argv A 0
} {1}
do_test thread2-1.5 {
  thread_finalize A
  thread_result A
} {SQLITE_OK}
do_test thread2-1.6 {
  thread_compile B {SELECT a FROM t1 LIMIT 1}
  thread_result B
} {SQLITE_OK}
do_test thread2-1.7 {
  thread_step B
  thread_result B
} {SQLITE_ROW}
do_test thread2-1.8 {
  thread_argv B 0
} {1}
do_test thread2-1.9 {
  thread_finalize B
  thread_result B
} {SQLITE_OK}

# Swap them again.
#
do_test thread2-2.2 {
  thread_swap A B
  thread_compile A {SELECT a FROM t1 LIMIT 1}
  thread_result A
} {SQLITE_OK}
do_test thread2-2.3 {
  thread_step A
  thread_result A
} {SQLITE_ROW}
do_test thread2-2.4 {
  thread_argv A 0
} {1}
do_test thread2-2.5 {
  thread_finalize A
  thread_result A
} {SQLITE_OK}
do_test thread2-2.6 {
  thread_compile B {SELECT a FROM t1 LIMIT 1}
  thread_result B
} {SQLITE_OK}
do_test thread2-2.7 {
  thread_step B
  thread_result B
} {SQLITE_ROW}
do_test thread2-2.8 {
  thread_argv B 0
} {1}
do_test thread2-2.9 {
  thread_finalize B
  thread_result B
} {SQLITE_OK}
thread_halt A
thread_halt B

# Save the original (correct) value of threadsOverrideEachOthersLocks
# so that it can be restored.  If this value is left set incorrectly, lots
# of things will go wrong in future tests.
#
set orig_threadOverride $threadsOverrideEachOthersLocks

# Pretend we are on a system (like RedHat9) were threads do not
# override each others locks.
#
set threadsOverrideEachOthersLocks 0

# Verify that we can move database connections between threads as
# long as no locks are held.
#
do_test thread2-3.1 {
  thread_create A test.db
  set DB [thread_db_get A]
  thread_halt A
} {}
do_test thread2-3.2 {
  set STMT [sqlite3_prepare $DB {SELECT a FROM t1 LIMIT 1} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
do_test thread2-3.3 {
  sqlite3_column_int $STMT 0
} 1
do_test thread2-3.4 {
  sqlite3_finalize $STMT
} SQLITE_OK
do_test thread2-3.5 {
  set STMT [sqlite3_prepare $DB {SELECT max(a) FROM t1} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
do_test thread2-3.6 {
  sqlite3_column_int $STMT 0
} 8
do_test thread2-3.7 {
  sqlite3_finalize $STMT
} SQLITE_OK
do_test thread2-3.8 {
  sqlite3_close $DB
} {SQLITE_OK}

do_test thread2-3.10 {
  thread_create A test.db
  thread_compile A {SELECT a FROM t1 LIMIT 1}
  thread_step A
  thread_finalize A
  set DB [thread_db_get A]
  thread_halt A
} {}
do_test thread2-3.11 {
  set STMT [sqlite3_prepare $DB {SELECT a FROM t1 LIMIT 1} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ROW
do_test thread2-3.12 {
  sqlite3_column_int $STMT 0
} 1
do_test thread2-3.13 {
  sqlite3_finalize $STMT
} SQLITE_OK
do_test thread2-3.14 {
  sqlite3_close $DB
} SQLITE_OK

do_test thread2-3.20 {
  thread_create A test.db
  thread_compile A {SELECT a FROM t1 LIMIT 3}
  thread_step A
  set STMT [thread_stmt_get A]
  set DB [thread_db_get A]
  sqlite3_step $STMT
} SQLITE_ROW
do_test thread2-3.22 {
  sqlite3_column_int $STMT 0
} 2
do_test thread2-3.23 {
  # The unlock fails here.  But because we never check the return
  # code from sqlite3OsUnlock (because we cannot do anything about it
  # if it fails) we do not realize that an error has occurred.
  breakpoint
  sqlite3_finalize $STMT
} SQLITE_OK
do_test thread2-3.25 {
  thread_db_put A $DB
  thread_halt A
} {}

do_test thread2-3.30 {
  thread_create A test.db
  thread_compile A {BEGIN}
  thread_step A
  thread_finalize A
  thread_compile A {SELECT a FROM t1 LIMIT 1}
  thread_step A
  thread_finalize A
  set DB [thread_db_get A]
  set STMT [sqlite3_prepare $DB {INSERT INTO t1 VALUES(99,'error')} -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ERROR
do_test thread2-3.32 {
  sqlite3_finalize $STMT
} SQLITE_MISUSE
do_test thread2-3.33 {
  thread_db_put A $DB
  thread_halt A
} {}

# VERY important to set the override flag back to its true value.
#
set threadsOverrideEachOthersLocks $orig_threadOverride

# Also important to halt the worker threads, which are using spin
# locks and eating away CPU cycles.
#
thread_halt *   
finish_test

Added test/thread_common.tcl.



































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# 2007 September 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: thread_common.tcl,v 1.5 2009/03/26 14:48:07 danielk1977 Exp $

if {[info exists ::thread_procs]} {
  return 0
}

# The following script is sourced by every thread spawned using 
# [sqlthread spawn]:
set thread_procs {

  # Execute the supplied SQL using database handle $::DB.
  #
  proc execsql {sql} {

    set rc SQLITE_LOCKED
    while {$rc eq "SQLITE_LOCKED" 
        || $rc eq "SQLITE_BUSY" 
        || $rc eq "SQLITE_SCHEMA"} {
      set res [list]

      enter_db_mutex $::DB
      set err [catch {
        set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 dummy_tail]
      } msg]

      if {$err == 0} {
        while {[set rc [sqlite3_step $::STMT]] eq "SQLITE_ROW"} {
          for {set i 0} {$i < [sqlite3_column_count $::STMT]} {incr i} {
            lappend res [sqlite3_column_text $::STMT 0]
          }
        }
        set rc [sqlite3_finalize $::STMT]
      } else {
        if {[lindex $msg 0]=="(6)"} {
          set rc SQLITE_LOCKED
        } else {
          set rc SQLITE_ERROR
        }
      }

      if {[string first locked [sqlite3_errmsg $::DB]]>=0} {
        set rc SQLITE_LOCKED
      }
      if {$rc ne "SQLITE_OK"} {
        set errtxt "$rc - [sqlite3_errmsg $::DB] (debug1)"
      }
      leave_db_mutex $::DB

      if {$rc eq "SQLITE_LOCKED" || $rc eq "SQLITE_BUSY"} {
        #sqlthread parent "puts \"thread [sqlthread id] is busy.  rc=$rc\""
        after 200
      } else {
        #sqlthread parent "puts \"thread [sqlthread id] ran $sql\""
      }
    }

    if {$rc ne "SQLITE_OK"} {
      error $errtxt
    }
    set res
  }

  proc do_test {name script result} {
    set res [eval $script]
    if {$res ne $result} {
      error "$name failed: expected \"$result\" got \"$res\""
    }
  }
}

proc thread_spawn {varname args} {
  sqlthread spawn $varname [join $args ;]
}

# Return true if this build can run the multi-threaded tests.
#
proc run_thread_tests {{print_warning 0}} {
  ifcapable !mutex { 
    set zProblem "SQLite build is not threadsafe"
  }
  if {[info commands sqlthread] eq ""} {
    set zProblem "SQLite build is not threadsafe"
  }
  if {![info exists ::tcl_platform(threaded)]} {
    set zProblem "Linked against a non-threadsafe Tcl build"
  }
  if {[info exists zProblem]} {
    if {$print_warning} {
      if {[info exists ::run_thread_tests_failed]} {
        puts "WARNING: Multi-threaded tests skipped: $zProblem"
      }
    } else {
      puts "Skipping thread tests: $zProblem"
      set ::run_thread_tests_failed 1
    }
    return 0
  }
  return 1;
}

return 0

Added test/threadtest1.c.



































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
** 2002 January 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements a simple standalone program used to test whether
** or not the SQLite library is threadsafe.
**
** Testing the thread safety of SQLite is difficult because there are very
** few places in the code that are even potentially unsafe, and those
** places execute for very short periods of time.  So even if the library
** is compiled with its mutexes disabled, it is likely to work correctly
** in a multi-threaded program most of the time.  
**
** This file is NOT part of the standard SQLite library.  It is used for
** testing only.
*/
#include "sqlite.h"
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/*
** Enable for tracing
*/
static int verbose = 0;

/*
** Come here to die.
*/
static void Exit(int rc){
  exit(rc);
}

extern char *sqlite3_mprintf(const char *zFormat, ...);
extern char *sqlite3_vmprintf(const char *zFormat, va_list);

/*
** When a lock occurs, yield.
*/
static int db_is_locked(void *NotUsed, int iCount){
  /* sched_yield(); */
  if( verbose ) printf("BUSY %s #%d\n", (char*)NotUsed, iCount);
  usleep(100);
  return iCount<25;
}

/*
** Used to accumulate query results by db_query()
*/
struct QueryResult {
  const char *zFile;  /* Filename - used for error reporting */
  int nElem;          /* Number of used entries in azElem[] */
  int nAlloc;         /* Number of slots allocated for azElem[] */
  char **azElem;      /* The result of the query */
};

/*
** The callback function for db_query
*/
static int db_query_callback(
  void *pUser,     /* Pointer to the QueryResult structure */
  int nArg,        /* Number of columns in this result row */
  char **azArg,    /* Text of data in all columns */
  char **NotUsed   /* Names of the columns */
){
  struct QueryResult *pResult = (struct QueryResult*)pUser;
  int i;
  if( pResult->nElem + nArg >= pResult->nAlloc ){
    if( pResult->nAlloc==0 ){
      pResult->nAlloc = nArg+1;
    }else{
      pResult->nAlloc = pResult->nAlloc*2 + nArg + 1;
    }
    pResult->azElem = realloc( pResult->azElem, pResult->nAlloc*sizeof(char*));
    if( pResult->azElem==0 ){
      fprintf(stdout,"%s: malloc failed\n", pResult->zFile);
      return 1;
    }
  }
  if( azArg==0 ) return 0;
  for(i=0; i<nArg; i++){
    pResult->azElem[pResult->nElem++] =
        sqlite3_mprintf("%s",azArg[i] ? azArg[i] : ""); 
  }
  return 0;
}

/*
** Execute a query against the database.  NULL values are returned
** as an empty string.  The list is terminated by a single NULL pointer.
*/
char **db_query(sqlite *db, const char *zFile, const char *zFormat, ...){
  char *zSql;
  int rc;
  char *zErrMsg = 0;
  va_list ap;
  struct QueryResult sResult;
  va_start(ap, zFormat);
  zSql = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  memset(&sResult, 0, sizeof(sResult));
  sResult.zFile = zFile;
  if( verbose ) printf("QUERY %s: %s\n", zFile, zSql);
  rc = sqlite3_exec(db, zSql, db_query_callback, &sResult, &zErrMsg);
  if( rc==SQLITE_SCHEMA ){
    if( zErrMsg ) free(zErrMsg);
    rc = sqlite3_exec(db, zSql, db_query_callback, &sResult, &zErrMsg);
  }
  if( verbose ) printf("DONE %s %s\n", zFile, zSql);
  if( zErrMsg ){
    fprintf(stdout,"%s: query failed: %s - %s\n", zFile, zSql, zErrMsg);
    free(zErrMsg);
    free(zSql);
    Exit(1);
  }
  sqlite3_free(zSql);
  if( sResult.azElem==0 ){
    db_query_callback(&sResult, 0, 0, 0);
  }
  sResult.azElem[sResult.nElem] = 0;
  return sResult.azElem;
}

/*
** Execute an SQL statement.
*/
void db_execute(sqlite *db, const char *zFile, const char *zFormat, ...){
  char *zSql;
  int rc;
  char *zErrMsg = 0;
  va_list ap;
  va_start(ap, zFormat);
  zSql = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  if( verbose ) printf("EXEC %s: %s\n", zFile, zSql);
  do{
    rc = sqlite3_exec(db, zSql, 0, 0, &zErrMsg);
  }while( rc==SQLITE_BUSY );
  if( verbose ) printf("DONE %s: %s\n", zFile, zSql);
  if( zErrMsg ){
    fprintf(stdout,"%s: command failed: %s - %s\n", zFile, zSql, zErrMsg);
    free(zErrMsg);
    sqlite3_free(zSql);
    Exit(1);
  }
  sqlite3_free(zSql);
}

/*
** Free the results of a db_query() call.
*/
void db_query_free(char **az){
  int i;
  for(i=0; az[i]; i++){
    sqlite3_free(az[i]);
  }
  free(az);
}

/*
** Check results
*/
void db_check(const char *zFile, const char *zMsg, char **az, ...){
  va_list ap;
  int i;
  char *z;
  va_start(ap, az);
  for(i=0; (z = va_arg(ap, char*))!=0; i++){
    if( az[i]==0 || strcmp(az[i],z)!=0 ){
      fprintf(stdout,"%s: %s: bad result in column %d: %s\n",
        zFile, zMsg, i+1, az[i]);
      db_query_free(az);
      Exit(1);
    }
  }
  va_end(ap);
  db_query_free(az);
}

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sig = PTHREAD_COND_INITIALIZER;
int thread_cnt = 0;

static void *worker_bee(void *pArg){
  const char *zFilename = (char*)pArg;
  char *azErr;
  int i, cnt;
  int t = atoi(zFilename);
  char **az;
  sqlite *db;

  pthread_mutex_lock(&lock);
  thread_cnt++;
  pthread_mutex_unlock(&lock);
  printf("%s: START\n", zFilename);
  fflush(stdout);
  for(cnt=0; cnt<10; cnt++){
    sqlite3_open(&zFilename[2], &db);
    if( db==0 ){
      fprintf(stdout,"%s: can't open\n", zFilename);
      Exit(1);
    }
    sqlite3_busy_handler(db, db_is_locked, zFilename);
    db_execute(db, zFilename, "CREATE TABLE t%d(a,b,c);", t);
    for(i=1; i<=100; i++){
      db_execute(db, zFilename, "INSERT INTO t%d VALUES(%d,%d,%d);",
         t, i, i*2, i*i);
    }
    az = db_query(db, zFilename, "SELECT count(*) FROM t%d", t);
    db_check(zFilename, "tX size", az, "100", 0);  
    az = db_query(db, zFilename, "SELECT avg(b) FROM t%d", t);
    db_check(zFilename, "tX avg", az, "101", 0);  
    db_execute(db, zFilename, "DELETE FROM t%d WHERE a>50", t);
    az = db_query(db, zFilename, "SELECT avg(b) FROM t%d", t);
    db_check(zFilename, "tX avg2", az, "51", 0);
    for(i=1; i<=50; i++){
      char z1[30], z2[30];
      az = db_query(db, zFilename, "SELECT b, c FROM t%d WHERE a=%d", t, i);
      sprintf(z1, "%d", i*2);
      sprintf(z2, "%d", i*i);
      db_check(zFilename, "readback", az, z1, z2, 0);
    }
    db_execute(db, zFilename, "DROP TABLE t%d;", t);
    sqlite3_close(db);
  }
  printf("%s: END\n", zFilename);
  /* unlink(zFilename); */
  fflush(stdout);
  pthread_mutex_lock(&lock);
  thread_cnt--;
  if( thread_cnt<=0 ){
    pthread_cond_signal(&sig);
  }
  pthread_mutex_unlock(&lock);
  return 0;
}

int main(int argc, char **argv){
  char *zFile;
  int i, n;
  pthread_t id;
  if( argc>2 && strcmp(argv[1], "-v")==0 ){
    verbose = 1;
    argc--;
    argv++;
  }
  if( argc<2 || (n=atoi(argv[1]))<1 ) n = 10;
  for(i=0; i<n; i++){
    char zBuf[200];
    sprintf(zBuf, "testdb-%d", (i+1)/2);
    unlink(zBuf);
  }
  for(i=0; i<n; i++){
    zFile = sqlite3_mprintf("%d.testdb-%d", i%2+1, (i+2)/2);
    if( (i%2)==0 ){
      /* Remove both the database file and any old journal for the file
      ** being used by this thread and the next one. */
      char *zDb = &zFile[2];
      char *zJournal = sqlite3_mprintf("%s-journal", zDb);
      unlink(zDb);
      unlink(zJournal);
      free(zJournal);
    }
      
    pthread_create(&id, 0, worker_bee, (void*)zFile);
    pthread_detach(id);
  }
  pthread_mutex_lock(&lock);
  while( thread_cnt>0 ){
    pthread_cond_wait(&sig, &lock);
  }
  pthread_mutex_unlock(&lock);
  for(i=0; i<n; i++){
    char zBuf[200];
    sprintf(zBuf, "testdb-%d", (i+1)/2);
    unlink(zBuf);
  }
  return 0;
}

Added test/threadtest2.c.











































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
** 2004 January 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements a simple standalone program used to test whether
** or not the SQLite library is threadsafe.
**
** This file is NOT part of the standard SQLite library.  It is used for
** testing only.
*/
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include "sqlite.h"

/*
** Name of the database
*/
#define DB_FILE "test.db"

/* 
** When this variable becomes non-zero, all threads stop
** what they are doing.
*/
volatile int all_stop = 0;

/* 
** Callback from the integrity check.  If the result is anything other
** than "ok" it means the integrity check has failed.  Set the "all_stop"
** global variable to stop all other activity.  Print the error message
** or print OK if the string "ok" is seen.
*/
int check_callback(void *pid, int argc, char **argv, char **notUsed2){
  int id = (int)pid;
  if( strcmp(argv[0],"ok") ){
    all_stop = 1;
    fprintf(stderr,"id: %s\n", id, argv[0]);
  }else{
    /* fprintf(stderr,"%d: OK\n", id); */
  }
  return 0;
}

/*
** Do an integrity check on the database.  If the first integrity check
** fails, try it a second time.
*/
int integrity_check(sqlite *db, int id){
  int rc;
  if( all_stop ) return 0;
  /* fprintf(stderr,"%d: CHECK\n", id); */
  rc = sqlite3_exec(db, "pragma integrity_check", check_callback, 0, 0);
  if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
    fprintf(stderr,"%d, Integrity check returns %d\n", id, rc);
  }
  if( all_stop ){
    sqlite3_exec(db, "pragma integrity_check", check_callback, 0, 0);
  }
  return 0;
}

/*
** This is the worker thread
*/
void *worker(void *workerArg){
  sqlite *db;
  int id = (int)workerArg;
  int rc;
  int cnt = 0;
  fprintf(stderr, "Starting worker %d\n", id);
  while( !all_stop && cnt++<10000 ){
    if( cnt%100==0 ) printf("%d: %d\n", id, cnt);
    while( (sqlite3_open(DB_FILE, &db))!=SQLITE_OK ) sched_yield();
    sqlite3_exec(db, "PRAGMA synchronous=OFF", 0, 0, 0);
    /* integrity_check(db, id); */
    if( all_stop ){ sqlite3_close(db); break; }
    /* fprintf(stderr, "%d: BEGIN\n", id); */
    rc = sqlite3_exec(db, "INSERT INTO t1 VALUES('bogus data')", 0, 0, 0);
    /* fprintf(stderr, "%d: END rc=%d\n", id, rc); */
    sqlite3_close(db);
  }
  fprintf(stderr, "Worker %d finished\n", id);
  return 0;
}

/*
** Initialize the database and start the threads
*/
int main(int argc, char **argv){
  sqlite *db;
  int i, rc;
  pthread_t aThread[5];

  if( strcmp(DB_FILE,":memory:") ){
    char *zJournal = sqlite3_mprintf("%s-journal", DB_FILE);
    unlink(DB_FILE);
    unlink(zJournal);
    sqlite3_free(zJournal);
  }  
  sqlite3_open(DB_FILE, &db);
  if( db==0 ){
    fprintf(stderr,"unable to initialize database\n");
    exit(1);
  }
  rc = sqlite3_exec(db, "CREATE TABLE t1(x);", 0,0,0);
  if( rc ){
    fprintf(stderr,"cannot create table t1: %d\n", rc);
    exit(1);
  }
  sqlite3_close(db);
  for(i=0; i<sizeof(aThread)/sizeof(aThread[0]); i++){
    pthread_create(&aThread[i], 0, worker, (void*)i);
  }
  for(i=0; i<sizeof(aThread)/sizeof(aThread[i]); i++){
    pthread_join(aThread[i], 0);
  }
  if( !all_stop ){
    printf("Everything seems ok.\n");
    return 0;
  }else{
    printf("We hit an error.\n");
    return 1;
  }
}

Added test/tkt-2ea2425d34.test.































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 2009 September 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket [2ea2425d34be] has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt-2ea24-1.1 {
  db eval {
    PRAGMA encoding=UTF16;
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,'abc');
    INSERT INTO t1 VALUES(2,'def');
    INSERT INTO t1 VALUES(3,'ghi');
    SELECT a FROM t1 WHERE length(b)<10 AND b<>'def' ORDER BY a;
  }
} {1 3}

finish_test

Added test/tkt-3fe897352e.test.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 2009 October 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket [3fe897352e8d8] has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt-3fe89-1.1 {
  db close
  sqlite3 db :memory:
  db eval {
    PRAGMA encoding=UTF8;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(hex_to_utf16be('D800'));
    SELECT hex(x) FROM t1;
  }
} {EDA080}
do_test tkt-3fe89-1.2 {
  db eval {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(hex_to_utf16le('00D8'));
    SELECT hex(x) FROM t1;
  }
} {EDA080}
do_test tkt-3fe89-1.3 {
  db eval {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(hex_to_utf16be('DFFF'));
    SELECT hex(x) FROM t1;
  }
} {EDBFBF}
do_test tkt-3fe89-1.4 {
  db eval {
    DELETE FROM t1;
    INSERT INTO t1 VALUES(hex_to_utf16le('FFDF'));
    SELECT hex(x) FROM t1;
  }
} {EDBFBF}


finish_test

Added test/tkt-4a03edc4c8.test.





























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 2009 September 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that
# ticket [4a03edc4c8c028c93e9269f64fc5e97f632c1166] has been fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt-4a03ed-1.1 {
  db eval {
    CREATE TABLE t1(
      a INTEGER PRIMARY KEY ON CONFLICT REPLACE,
      b UNIQUE ON CONFLICT FAIL
    );
    INSERT INTO t1 VALUES(1, 1);
    INSERT INTO t1 VALUES(2, 2);
  }
  catchsql {
    BEGIN;
      INSERT INTO t1 VALUES(1, 2);
    COMMIT;
  }
} {1 {column b is not unique}}
do_test tkt-4a03ed-1.2 {
  db eval {
    PRAGMA integrity_check;
  }
} {ok}
do_test tkt-4a03ed-1.3 {
  db eval {
    SELECT * FROM t1 ORDER BY a;
  }
} {1 1 2 2}

finish_test

Added test/tkt-5ee23731f.test.





















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 2009 October 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket [5ee23731f15] has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt-5ee237-1.1 {
  db close
  file delete -force test.db
  sqlite3 db test.db
  db eval {
    CREATE TABLE t1(x UNIQUE);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 SELECT x+2 FROM t1;
    INSERT INTO t1 SELECT x+4 FROM t1;
    INSERT INTO t1 SELECT x+8 FROM t1;
  }
  db close
  sqlite3 db test.db -readonly 1
  set rc [catch {
    db eval {SELECT rowid, x FROM t1 ORDER BY x} {
      db eval {UPDATE t1 SET x=x+1 WHERE rowid=:rowid}
    }
  } msg]
  lappend rc $msg
} {1 {attempt to write a readonly database}}

finish_test

Added test/tkt-94c04eaadb.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2009 October 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {[info commands sqlite3async_initialize] eq ""} {
  # The async logic is not built into this system
  finish_test
  return
}

# Create a database.
do_test tkt-94c94-1.1 {
  execsql { CREATE TABLE t1(a, b) }
} {}

# Grow the file to larger than 4096MB (2^32 bytes)
db close
if {[catch {fake_big_file 4096 [pwd]/test.db} msg]} {
  puts "**** Unable to create a file larger than 4096 MB. *****"
  finish_test
  return
}

# Switch to async mode.
sqlite3async_initialize "" 1
sqlite3 db test.db
sqlite3 db2 test.db

# Read from and write to the db just past the 4096MB mark.
#
do_test tkt-94c94-2.1 {
  execsql { CREATE TABLE t2(x, y) } db
} {}
do_test tkt-94c94-2.2 {
breakpoint
  execsql { INSERT INTO t2 VALUES(1, 2) } db2
} {}
do_test tkt-94c94-2.3 {
  execsql { SELECT * FROM t2 } db
} {1 2}
do_test tkt-94c94-2.4 {
  sqlite3async_control halt idle
  sqlite3async_start
  sqlite3async_wait
} {}
do_test tkt-94c94-2.5 {
  execsql { SELECT * FROM t2 } db
} {1 2}
do_test tkt-94c94-2.6 {
  sqlite3async_start
  sqlite3async_wait
} {}

db close
db2 close
sqlite3async_start
sqlite3async_wait
sqlite3async_shutdown

finish_test

Added test/tkt-d82e3f3721.txt.































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 2009 September 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket [d82e3f3721] has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt-d82e3-1.1 {
  db eval {
    CREATE TABLE t1(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
    INSERT INTO t1 VALUES(null,'abc');
    INSERT INTO t1 VALUES(null,'def');
    DELETE FROM t1;
    INSERT INTO t1 VALUES(null,'ghi');
    SELECT * FROM t1;
  }
} {3 ghi}
do_test tkt-d82e3-1.2 {
  db eval {
    CREATE TEMP TABLE t2(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
    INSERT INTO t2 VALUES(null,'jkl');
    INSERT INTO t2 VALUES(null,'mno');
    DELETE FROM t2;
    INSERT INTO t2 VALUES(null,'pqr');
    SELECT * FROM t2;
  }
} {3 pqr}
do_test tkt-d82e3-1.3 {
  db eval {
    SELECT 'main', * FROM main.sqlite_sequence
    UNION ALL
    SELECT 'temp', * FROM temp.sqlite_sequence
    ORDER BY 2
  }
} {main t1 3 temp t2 3}
do_test tkt-d82e3-1.4 {
  db eval {
    VACUUM;
    SELECT 'main', * FROM main.sqlite_sequence
    UNION ALL
    SELECT 'temp', * FROM temp.sqlite_sequence
    ORDER BY 2
  }
} {main t1 3 temp t2 3}

sqlite3 db2 test.db
do_test tkt-d82e3-2.1 {
  db eval {
    CREATE TEMP TABLE t3(x);
    INSERT INTO t3 VALUES(1);
  }
  db2 eval {
    CREATE TABLE t3(y,z);
    INSERT INTO t3 VALUES(8,9);
  }
  db eval {
    SELECT * FROM temp.t3 JOIN main.t3;
  }
} {1 8 9}
do_test tkt-d82e3-2.2 {
  db eval {
    VACUUM;
    SELECT * FROM temp.t3 JOIN main.t3;
  }
} {1 8 9}

finish_test

Added test/tkt-f777251dc7a.test.







































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 2009 October 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket [f777251dc7a] has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt-f7772-1.1 {
  execsql {
     CREATE TEMP TABLE t1(x UNIQUE);
     INSERT INTO t1 VALUES(1);
     CREATE TABLE t2(x, y);
     INSERT INTO t2 VALUES(1, 2);
     CREATE TEMP TABLE t3(w, z);
  }
} {}

proc force_rollback {} {
  catch {db eval {INSERT OR ROLLBACK INTO t1 VALUES(1)}}
}
db function force_rollback force_rollback

do_test tkt-f7772-1.2 {
  catchsql {
    BEGIN IMMEDIATE;
    SELECT x, force_rollback(), EXISTS(SELECT 1 FROM t3 WHERE w=x) FROM t2;
  }
} {1 {callback requested query abort}}
do_test tkt-f7772-1.3 {
  sqlite3_get_autocommit db
} {1}

do_test tkt-f7772-2.1 {
  execsql {
     DROP TABLE IF EXISTS t1;
     DROP TABLE IF EXISTS t2;
     DROP TABLE IF EXISTS t3;

     CREATE TEMP TABLE t1(x UNIQUE);
     INSERT INTO t1 VALUES(1);
     CREATE TABLE t2(x, y);
     INSERT INTO t2 VALUES(1, 2);
  }
} {}
do_test tkt-f7772-2.2 {
  execsql {
    BEGIN IMMEDIATE;
    CREATE TEMP TABLE t3(w, z);
  }
  catchsql {
    SELECT x, force_rollback(), EXISTS(SELECT 1 FROM t3 WHERE w=x) FROM t2
  }
} {1 {callback requested query abort}}
do_test tkt-f7772-2.3 {
  sqlite3_get_autocommit db
} {1}

do_test tkt-f7772-3.1 {
  execsql {
    DROP TABLE IF EXISTS t1;
    DROP TABLE IF EXISTS t2;
    DROP TABLE IF EXISTS t3;

    CREATE TEMP TABLE t1(x);
    CREATE TABLE t2(x);
    CREATE TABLE t3(x);
  
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
  }
} {}

proc ins {} { db eval {INSERT INTO t3 VALUES('hello')} }
db function ins ins

do_test tkt-f7772-3.2 {
  execsql {
    SELECT ins() AS x FROM t2 UNION ALL SELECT ins() AS x FROM t1
  }
} {{} {} {} {}}
do_test tkt-f7772-3.3 {
  execsql { SELECT * FROM t3 }
} {hello hello hello hello}

finish_test

Added test/tkt1435.test.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# 2005 September 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1435 has been
# fixed.  
#
#
# $Id: tkt1435.test,v 1.2 2006/01/17 09:35:02 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !memorydb {
  finish_test
  return
}

# Construct the sample database.
#
do_test tkt1435-1.0 {
  sqlite3 db :memory:
  execsql {
    CREATE TABLE Instances(
    	instanceId INTEGER PRIMARY KEY,
    	troveName STR,
    	versionId INT,
    	flavorId INT,
    	timeStamps STR,
    	isPresent INT,
    	pinned BOOLEAN
    );
    INSERT INTO "Instances"
       VALUES(1, 'libhello:runtime', 1, 1, 1126929880.094, 1, 1);
    INSERT INTO "Instances"
       VALUES(2, 'libhello:user', 1, 1, 1126929880.094, 1, 0);
    INSERT INTO "Instances"
       VALUES(3, 'libhello:script', 1, 1, 1126929880.094, 1, 0);
    INSERT INTO "Instances"
       VALUES(4, 'libhello', 1, 1, 1126929880.094, 1, 0);
    
    CREATE TABLE Versions(versionId INTEGER PRIMARY KEY,version STR UNIQUE);
    INSERT INTO "Versions" VALUES(0, NULL);
    INSERT INTO "Versions" VALUES(1, '/localhost@rpl:linux/0-1-1');
    
    CREATE TABLE Flavors(flavorId integer primary key, flavor str unique);
    INSERT INTO "Flavors" VALUES(0, NULL);
    INSERT INTO "Flavors" VALUES(1, '1#x86');
    
    CREATE TEMPORARY TABLE tlList (
       row INTEGER PRIMARY KEY,
       name STRING,
       version STRING,
       flavor STRING
    );
    
    INSERT INTO tlList 
      values(NULL, 'libhello:script', '/localhost@rpl:linux/0-1-1', '1#x86');
    INSERT INTO tlList 
      values(NULL, 'libhello:user', '/localhost@rpl:linux/0-1-1', '1#x86');
    INSERT INTO tlList 
      values(NULL, 'libhello:runtime', '/localhost@rpl:linux/0-1-1', '1#x86');
  }
} {}

# Run the query with an index
#
do_test tkt1435-1.1 {
  execsql {
    select row, pinned from tlList, Instances, Versions, Flavors
        where
            Instances.troveName = tlList.name
        and Versions.version = tlList.version
        and Instances.versionId = Versions.versionId
        and (    Flavors.flavor = tlList.flavor or Flavors.flavor is NULL
             and tlList.flavor = '')
        and Instances.flavorId = Flavors.flavorId
    order by row asc;
  }
} {1 0 2 0 3 1}

# Create a indices, analyze and rerun the query. 
# Verify that the results are the same
#
do_test tkt1435-1.2 {
  execsql {
    CREATE INDEX InstancesNameIdx ON Instances(troveName);
    CREATE UNIQUE INDEX InstancesIdx 
      ON Instances(troveName, versionId, flavorId);
    ANALYZE;
    select row, pinned from tlList, Instances, Versions, Flavors
        where
            Instances.troveName = tlList.name
        and Versions.version = tlList.version
        and Instances.versionId = Versions.versionId
        and (    Flavors.flavor = tlList.flavor or Flavors.flavor is NULL
             and tlList.flavor = '')
        and Instances.flavorId = Flavors.flavorId
    order by row asc;
  }
} {1 0 2 0 3 1}

finish_test

Added test/tkt1443.test.









































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# 2005 September 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1433 has been
# fixed.  
#
# The problem in ticket #1433 was that the dependencies on the right-hand
# side of an IN operator were not being checked correctly.  So in an
# expression of the form:
#
#         t1.x IN (1,t2.b,3)
#
# the optimizer was missing the fact that the right-hand side of the IN
# depended on table t2.  It was checking dependencies based on the
# Expr.pRight field rather than Expr.pList and Expr.pSelect.  
#
# Such a bug could be verifed using a less elaborate test case.  But
# this test case (from the original bug poster) exercises so many different
# parts of the system all at once, that it seemed like a good one to
# include in the test suite. 
#
# NOTE:  Yes, in spite of the name of this file (tkt1443.test) this
# test is for ticket #1433 not #1443.  I mistyped the name when I was
# creating the file and I had already checked in the file by the wrong
# name be the time I noticed the error.  With CVS it is a really hassle
# to change filenames, so I'll just leave it as is.  No harm done.
#
# $Id: tkt1443.test,v 1.4 2006/01/17 09:35:02 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery||!memorydb {
  finish_test
  return
}

# Construct the sample database.
#
do_test tkt1443-1.0 {
  sqlite3 db :memory:
  execsql {
    CREATE TABLE Items(
    	itemId integer primary key,
    	 item str unique
    );
    INSERT INTO "Items" VALUES(0, 'ALL');
    INSERT INTO "Items" VALUES(1, 'double:source');
    INSERT INTO "Items" VALUES(2, 'double');
    INSERT INTO "Items" VALUES(3, 'double:runtime');
    INSERT INTO "Items" VALUES(4, '.*:runtime');
    
    CREATE TABLE Labels(
    	labelId INTEGER PRIMARY KEY,
    	label STR UNIQUE
    );
    INSERT INTO "Labels" VALUES(0, 'ALL');
    INSERT INTO "Labels" VALUES(1, 'localhost@rpl:linux');
    INSERT INTO "Labels" VALUES(2, 'localhost@rpl:branch');
    
    CREATE TABLE LabelMap(
    	itemId INTEGER,
    	labelId INTEGER,
    	branchId integer
    );
    INSERT INTO "LabelMap" VALUES(1, 1, 1);
    INSERT INTO "LabelMap" VALUES(2, 1, 1);
    INSERT INTO "LabelMap" VALUES(3, 1, 1);
    INSERT INTO "LabelMap" VALUES(1, 2, 2);
    INSERT INTO "LabelMap" VALUES(2, 2, 3);
    INSERT INTO "LabelMap" VALUES(3, 2, 3);
    
    CREATE TABLE Users (
    	userId INTEGER PRIMARY KEY,
    	user STRING UNIQUE,
    	salt BINARY,
    	password STRING
    );
    INSERT INTO "Users" VALUES(1, 'test', 'Šæ$d',
               '43ba0f45014306bd6df529551ffdb3df');
    INSERT INTO "Users" VALUES(2, 'limited', 'ªš>S',
               'cf07c8348fdf675cc1f7696b7d45191b');
    CREATE TABLE UserGroups (
    	userGroupId INTEGER PRIMARY KEY,
    	userGroup STRING UNIQUE
    );
    INSERT INTO "UserGroups" VALUES(1, 'test');
    INSERT INTO "UserGroups" VALUES(2, 'limited');
    
    CREATE TABLE UserGroupMembers (
    	userGroupId INTEGER,
    	userId INTEGER
    );
    INSERT INTO "UserGroupMembers" VALUES(1, 1);
    INSERT INTO "UserGroupMembers" VALUES(2, 2);
    
    CREATE TABLE Permissions (
    	userGroupId INTEGER,
    	labelId INTEGER NOT NULL,
    	itemId INTEGER NOT NULL,
    	write INTEGER,
    	capped INTEGER,
    	admin INTEGER
    );
    INSERT INTO "Permissions" VALUES(1, 0, 0, 1, 0, 1);
    INSERT INTO "Permissions" VALUES(2, 2, 4, 0, 0, 0);
  }
} {}

# Run the query with an index
#
do_test tkt1443-1.1 {
  execsql {
    select distinct
        Items.Item as trove, UP.pattern as pattern
    from
       ( select
           Permissions.labelId as labelId,
           PerItems.item as pattern
         from
           Users, UserGroupMembers, Permissions
           left outer join Items as PerItems
                 on Permissions.itemId = PerItems.itemId
         where
               Users.user = 'limited'
           and Users.userId = UserGroupMembers.userId
           and UserGroupMembers.userGroupId = Permissions.userGroupId
       ) as UP join LabelMap on ( UP.labelId = 0 or
                                  UP.labelId = LabelMap.labelId ),
       Labels, Items
    where
        Labels.label = 'localhost@rpl:branch'
    and Labels.labelId = LabelMap.labelId
    and LabelMap.itemId = Items.itemId
    ORDER BY +trove, +pattern
  }
} {double .*:runtime double:runtime .*:runtime double:source .*:runtime}

# Create an index and rerun the query. 
# Verify that the results are the same
#
do_test tkt1443-1.2 {
  execsql {
    CREATE UNIQUE INDEX PermissionsIdx
         ON Permissions(userGroupId, labelId, itemId);
    select distinct
        Items.Item as trove, UP.pattern as pattern
    from
       ( select
           Permissions.labelId as labelId,
           PerItems.item as pattern
         from
           Users, UserGroupMembers, Permissions
           left outer join Items as PerItems
                 on Permissions.itemId = PerItems.itemId
         where
               Users.user = 'limited'
           and Users.userId = UserGroupMembers.userId
           and UserGroupMembers.userGroupId = Permissions.userGroupId
       ) as UP join LabelMap on ( UP.labelId = 0 or
                                  UP.labelId = LabelMap.labelId ),
       Labels, Items
    where
        Labels.label = 'localhost@rpl:branch'
    and Labels.labelId = LabelMap.labelId
    and LabelMap.itemId = Items.itemId
    ORDER BY +trove, +pattern
  }
} {double .*:runtime double:runtime .*:runtime double:source .*:runtime}

finish_test

Added test/tkt1444.test.

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1444 has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound||!view {
  finish_test
  return 
}

# The use of a VIEW that contained an ORDER BY clause within a UNION ALL
# was causing problems.  See ticket #1444.
#
do_test tkt1444-1.1 {
  execsql {
    CREATE TABLE DemoTable (x INTEGER, TextKey TEXT, DKey Real);
    CREATE INDEX DemoTableIdx ON DemoTable (TextKey);
    INSERT INTO DemoTable VALUES(9,8,7);
    INSERT INTO DemoTable VALUES(1,2,3);
    CREATE VIEW DemoView AS SELECT * FROM DemoTable ORDER BY TextKey;
    SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView ORDER BY 1;
  }
} {1 2 3.0 1 2 3.0 9 8 7.0 9 8 7.0}
do_test tkt1444-1.2 {
  execsql {
    SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView;
  }
} {9 8 7.0 1 2 3.0 1 2 3.0 9 8 7.0}
do_test tkt1444-1.3 {
  execsql {
    DROP VIEW DemoView;
    CREATE VIEW DemoView AS SELECT * FROM DemoTable;
    SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView ORDER BY 1;
  }
} {1 2 3.0 1 2 3.0 9 8 7.0 9 8 7.0}
do_test tkt1444-1.4 {
  execsql {
    SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView;
  }
} {9 8 7.0 1 2 3.0 9 8 7.0 1 2 3.0}

finish_test

Added test/tkt1449.test.













































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1449 has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Somewhere in tkt1449-1.1 is a VIEW definition that uses a subquery and
# a compound SELECT. So we cannot run this file if any of these features
# are not available.
ifcapable !subquery||!compound||!view {
  finish_test
  return
}

# The following schema generated problems in ticket #1449.  We've retained
# the original schema here because it is some unbelievably complex, it seemed
# like a good test case for SQLite.
#
do_test tkt1449-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE ACLS(ISSUEID text(50) not null, OBJECTID text(50) not null, PARTICIPANTID text(50) not null, PERMISSIONBITS int not null, constraint PK_ACLS primary key (ISSUEID, OBJECTID, PARTICIPANTID));
    CREATE TABLE ACTIONITEMSTATUSES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, FRIENDLYNAME text(100) not null, REVISION int not null, SHORTNAME text(30) not null, LONGNAME text(200) not null, ATTACHMENTHANDLING int not null, RESULT int not null, NOTIFYCREATOR text(1) null, NOTIFYASSIGNEE text(1) null, NOTIFYFYI text(1) null, NOTIFYCLOSURETEAM text(1) null, NOTIFYCOORDINATORS text(1) null, COMMENTREQUIRED text(1) not null, constraint PK_ACTIONITEMSTATUSES primary key (ISSUEID, OBJECTID));
    CREATE TABLE ACTIONITEMTYPES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, REVISION int not null, LABEL text(200) not null, INSTRUCTIONS text not null, EMAILINSTRUCTIONS text null, ALLOWEDSTATUSES text not null, INITIALSTATUS text(100) not null, COMMENTREQUIRED text(1) not null, ATTACHMENTHANDLING int not null, constraint PK_ACTIONITEMTYPES primary key (ISSUEID, OBJECTID));
    CREATE TABLE ATTACHMENTS(TQUNID text(36) not null, OBJECTID text(50) null, ISSUEID text(50) null, DATASTREAM blob not null, CONTENTENCODING text(50) null, CONTENTCHARSET text(50) null, CONTENTTYPE text(100) null, CONTENTID text(100) null, CONTENTLOCATION text(100) null, CONTENTNAME text(100) not null, constraint PK_ATTACHMENTS primary key (TQUNID));
    CREATE TABLE COMPLIANCEPOLICIES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, BODY text null, constraint PK_COMPLIANCEPOLICIES primary key (ISSUEID, OBJECTID));
    CREATE TABLE DBHISTORY(DATETIME text(25) not null, OPERATION text(20) not null, KUBIVERSION text(100) not null, FROMVERSION int null, TOVERSION int null);
    CREATE TABLE DBINFO(FINGERPRINT text(32) not null, VERSION int not null);
    CREATE TABLE DETACHEDATTACHMENTS (TQUNID text(36) not null, ISSUEID text(50) not null, OBJECTID text(50) not null, PATH text(300) not null, DETACHEDFILELASTMODTIMESTAMP text(25) null, CONTENTID text(100) not null, constraint PK_DETACHEDATTACHMENTS primary key (TQUNID));
    CREATE TABLE DOCREFERENCES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, REFERENCEDOCUMENTID text(50) null, constraint PK_DOCREFERENCES primary key (ISSUEID, OBJECTID));
    CREATE TABLE DQ (TQUNID text(36) not null, ISSUEID text(50) not null, DEPENDSID text(50) null, DEPENDSTYPE int null, DEPENDSCOMMANDSTREAM blob null, DEPENDSNODEIDSEQNOKEY text(100) null, DEPENDSACLVERSION int null, constraint PK_DQ primary key (TQUNID));
    CREATE TABLE EMAILQ(TIMEQUEUED int not null, NODEID text(50) not null, MIME blob not null, TQUNID text(36) not null);
    CREATE TABLE ENTERPRISEDATA(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, DATE1 text(25) null, DATE2 text(25) null, DATE3 text(25) null, DATE4 text(25) null, DATE5 text(25) null, DATE6 text(25) null, DATE7 text(25) null, DATE8 text(25) null, DATE9 text(25) null, DATE10 text(25) null, VALUE1 int null, VALUE2 int null, VALUE3 int null, VALUE4 int null, VALUE5 int null, VALUE6 int null, VALUE7 int null, VALUE8 int null, VALUE9 int null, VALUE10 int null, VALUE11 int null, VALUE12 int null, VALUE13 int null, VALUE14 int null, VALUE15 int null, VALUE16 int null, VALUE17 int null, VALUE18 int null, VALUE19 int null, VALUE20 int null, STRING1 text(300) null, STRING2 text(300) null, STRING3 text(300) null, STRING4 text(300) null, STRING5 text(300) null, STRING6 text(300) null, STRING7 text(300) null, STRING8 text(300) null, STRING9 text(300) null, STRING10 text(300) null, LONGSTRING1 text null, LONGSTRING2 text null, LONGSTRING3 text null, LONGSTRING4 text null, LONGSTRING5 text null, LONGSTRING6 text null, LONGSTRING7 text null, LONGSTRING8 text null, LONGSTRING9 text null, LONGSTRING10 text null, constraint PK_ENTERPRISEDATA primary key (ISSUEID, OBJECTID));
    CREATE TABLE FILEMORGUE(TQUNID text(36) not null, PATH text(300) not null, DELETEFOLDERWHENEMPTY text(1) null, constraint PK_FILEMORGUE primary key (TQUNID));
    CREATE TABLE FILES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, FILENAME text(300) not null, VISIBLENAME text(300) not null, VERSIONSTRING text(300) not null, DOCUMENTHASH text(40) not null, ISFINAL text(1) null, DOCREFERENCEID text(50) not null, constraint PK_FILES primary key (ISSUEID, OBJECTID));
    CREATE TABLE FOLDERS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, CONTAINERNAME text(300) null, CONTAINERACLSETTINGS text null, constraint PK_FOLDERS primary key (ISSUEID, OBJECTID));
    CREATE TABLE GLOBALSETTINGS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, SINGULARPROJECTLABEL text(30) not null, PLURALPROJECTLABEL text(30) not null, PROJECTREQUIRED text(1) not null, CUSTOMPROJECTSALLOWED text(1) not null, ACTIONITEMSPECXML text null, PROJECTLISTXML text null, ENTERPRISEDATALABELS text null, ENTERPRISEDATATABXSL text null, constraint PK_GLOBALSETTINGS primary key (ISSUEID, OBJECTID));
    CREATE TABLE GLOBALSTRINGPROPERTIES(ID int not null, VALUE text(300) not null, constraint PK_GLOBALSTRINGPROPERTIES primary key (ID));
    CREATE TABLE IMQ(TQUNID text(36) not null, DATETIMEQUEUED text(25) not null, ISSUEID text(50) not null, KUBIBUILD text(30) not null, FAILCOUNT int not null, LASTRUN text(25) null, ENVELOPESTREAM blob not null, PAYLOADSTREAM blob not null, constraint PK_IMQ primary key (TQUNID));
    CREATE TABLE INVITATIONNODES(INVITATIONID text(50) not null, RECIPIENTNODEID text(50) not null, DATECREATED text(25) not null, constraint PK_INVITATIONNODES primary key (INVITATIONID, RECIPIENTNODEID));
    CREATE TABLE INVITATIONS (INVITATIONID text(50) not null, SENDERNODEID text(50) not null, RECIPIENTEMAILADDR text(200) not null, RECIPIENTUSERID text(50) null, RECIPIENTNODES text null, ISSUEID text(50) not null, ENVELOPE text not null, MESSAGEBLOB blob not null, INVITATIONSTATE int not null, TQUNID text(36) not null, DATECREATED text(25) not null);
    CREATE TABLE ISSUES (CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, CONTAINERNAME text(300) null, CONTAINERACLSETTINGS text null, ISINITIALIZED text(1) null, BLINDINVITES text null, ISSYSTEMISSUE text(1) not null, ISSUETYPE int not null, ACTIVITYTYPEID text(50) null, ISINCOMPLETE text(1) not null, constraint PK_ISSUES primary key (ISSUEID, OBJECTID));
    CREATE TABLE ISSUESETTINGS (CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, ISSUENAME text(300) not null, ISSUEACLSETTINGS text not null, ISSUEDUEDATE text(25) null, ISSUEPRIORITY int null, ISSUESTATUS int null, DESCRIPTION text null, PROJECTID text(100) null, PROJECTNAME text null, PROJECTNAMEISCUSTOM text(1) null, ISSYSTEMISSUE text(1) not null, ACTIONITEMREVNUM int not null, constraint PK_ISSUESETTINGS primary key (ISSUEID, OBJECTID));
    CREATE TABLE KMTPMSG (MSGID integer not null, SENDERID text(50) null, RECIPIENTIDLIST text not null, ISSUEID text(50) null, MESSAGETYPE int not null, ENVELOPE text null, MESSAGEBLOB blob not null, RECEIVEDDATE text(25) not null, constraint PK_KMTPMSG primary key (MSGID));
    CREATE TABLE KMTPNODEQ(NODEID text(50) not null, MSGID int not null, RECEIVEDDATE text(25) not null, SENDCOUNT int not null);
    CREATE TABLE KMTPQ(MSGID integer not null, SENDERID text(50) null, RECIPIENTIDLIST text not null, ISSUEID text(50) null, MESSAGETYPE int not null, ENVELOPE text null, MESSAGEBLOB blob not null, constraint PK_KMTPQ primary key (MSGID));
    CREATE TABLE LOGENTRIES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, ACTIONTYPE int not null, ASSOCIATEDOBJECTIDS text null, OLDENTITIES text null, NEWENTITIES text null, OTHERENTITIES text null, constraint PK_LOGENTRIES primary key (ISSUEID, OBJECTID));
    CREATE TABLE LSBI(TQUNID text(36) not null, ISSUEID text(50) not null, TABLEITEMID text(50) null, TABLENODEID text(50) null, TABLECMD int null, TABLECONTAINERID text(50) null, TABLESEQNO int null, DIRTYCONTENT text null, STUBBED text(1) null, ENTITYSTUBDATA text null, UPDATENUMBER int not null, constraint PK_LSBI primary key (TQUNID));
    CREATE TABLE LSBN(TQUNID text(36) not null, ISSUEID text(50) not null, NODEID text(50) not null, STORESEQNO int not null, SYNCSEQNO int not null, LASTMSGDATE text(25) null, constraint PK_LSBN primary key (TQUNID));
    CREATE TABLE MMQ(TQUNID text(36) not null, ISSUEID text(50) not null, TABLEREQUESTNODE text(50) null, MMQENTRYINDEX text(60) null, DIRECTION int null, NODEID text(50) null, TABLEFIRSTSEQNO int null, TABLELASTSEQNO int null, NEXTRESENDTIMEOUT text(25) null, TABLETIMEOUTMULTIPLIER int null, constraint PK_MMQ primary key (TQUNID));
    CREATE TABLE NODEREG(NODEID text(50) not null, USERID text(50) null, CREATETIME text(25) not null, TQUNID text(36) not null);
    CREATE TABLE NODES (NODEID text(50) not null, USERID text(50) null, NODESTATE int not null, NODECERT text null, KUBIVERSION int not null, KUBIBUILD text(30) not null, TQUNID text(36) not null, LASTBINDDATE text(25) null, LASTUNBINDDATE text(25) null, LASTBINDIP text(15) null, NUMBINDS int not null, NUMSENDS int not null, NUMPOLLS int not null, NUMRECVS int not null);
    CREATE TABLE PARTICIPANTNODES(ISSUEID text(50) not null, OBJECTID text(50) not null, NODEID text(50) not null, USERID text(50) null, NODESTATE int not null, NODECERT text null, KUBIVERSION int not null, KUBIBUILD text(30) not null, TQUNID text(36) not null);
    CREATE TABLE PARTICIPANTS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARTICIPANTSTATE int not null, PARTICIPANTROLE int not null, PARTICIPANTTEAM int not null, ISREQUIREDMEMBER text(1) null, USERID text(50) null, ISAGENT text(1) null, NAME text(150) not null, EMAILADDRESS text(200) not null, ISEMAILONLY text(1) not null, INVITATION text null, ACCEPTRESENDCOUNT int null, ACCEPTRESENDTIMEOUT text(25) null, ACCEPTLASTSENTTONODEID text(50) null, constraint PK_PARTICIPANTS primary key (ISSUEID, OBJECTID));
    CREATE TABLE PARTICIPANTSETTINGS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARTICIPANTID text(50) not null, TASKPIMSYNC text(1) null, MOBILESUPPORT text(1) null, NOTIFYBYEMAIL text(1) null, MARKEDCRITICAL text(1) null, constraint PK_PARTICIPANTSETTINGS primary key (ISSUEID, OBJECTID));
    CREATE TABLE PARTITIONS(PARTITIONID text(50) not null, NAME text(100) not null, LDAPDN text(300) not null, SERVERNODEID text(50) not null, TQUNID text(36) not null);
    CREATE TABLE PROJECTS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, NAME text(100) not null, ID text(100) null, constraint PK_PROJECTS primary key (ISSUEID, OBJECTID));
    CREATE TABLE TASKCOMPLETIONS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, TASKID text(50) not null, DISPOSITION int not null, STATUSID text(50) not null, SHORTNAME text(30) not null, LONGNAME text(200) not null, constraint PK_TASKCOMPLETIONS primary key (ISSUEID, OBJECTID));
    CREATE TABLE TASKS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, DUETIME text(25) null, ASSIGNEDTO text(50) not null, TARGETOBJECTIDS text null, RESPONSEID text(50) not null, TYPEID text(50) not null, LABEL text(200) not null, INSTRUCTIONS text not null, ALLOWEDSTATUSES text not null, ISSERIALREVIEW text(1) null, DAYSTOREVIEW int null, REVIEWERIDS text(500) null, REVIEWTYPE int null, REVIEWGROUP text(300) null, constraint PK_TASKS primary key (ISSUEID, OBJECTID));
    CREATE TABLE USERS (USERID text(50) not null, USERSID text(100) not null, ENTERPRISEUSER text(1) not null, USEREMAILADDRESS text(200) null, EMAILVALIDATED text(1) null, VALIDATIONCOOKIE text(50) null, CREATETIME text(25) not null, TQUNID text(36) not null, PARTITIONID text(50) null);
    CREATE VIEW CRITICALISSUES as 
    
   
   		select
    			USERID, ISSUEID, ISSUENAME, min(DATE1) DATE1
    			from (
    			select p.USERID USERID, p.ISSUEID ISSUEID, iset.ISSUENAME ISSUENAME, t.DUETIME DATE1
    				from PARTICIPANTS p
    				join TASKS t on t.ASSIGNEDTO = p.OBJECTID
    				join TASKCOMPLETIONS tc on tc.TASKID = t.OBJECTID
    				join ISSUESETTINGS iset on iset.ISSUEID = p.ISSUEID
    				where (t.ISOBSOLETE = 'n' or t.ISOBSOLETE is null)
    				and tc.DISPOSITION = 1
    				and iset.ISSUESTATUS = 1
    			union
    			select p.USERID USERID, p.ISSUEID ISSUEID, iset.ISSUENAME ISSUENAME, iset.ISSUEDUEDATE DATE1
    				from PARTICIPANTS p
    				join PARTICIPANTSETTINGS ps on ps.PARTICIPANTID = p.OBJECTID
    				join ISSUESETTINGS iset on iset.ISSUEID = p.ISSUEID
    				where ps.MARKEDCRITICAL = 'y'
    				and iset.ISSUESTATUS = 1
    			) as CRITICALDATA
    			group by USERID, ISSUEID, ISSUENAME;
    CREATE VIEW CURRENTFILES as 
    
   
   		select
    			d.ISSUEID as ISSUEID,
    			d.REFERENCEDOCUMENTID as OBJECTID,
    			f.VISIBLENAME as VISIBLENAME
    			from
    				DOCREFERENCES d
    				join FILES f on f.OBJECTID = d.REFERENCEDOCUMENTID;
    CREATE VIEW ISSUEDATA as 
    
   
   		select
    			ISSUES.OBJECTID as ISSUEID,
    			ISSUES.CREATIONDATE as CREATIONDATE,
    			ISSUES.AUTHORID as AUTHORID,
    			ISSUES.LASTMODIFIEDDATE as LASTMODIFIEDDATE,
    			ISSUES.LASTMODIFIEDBYID as LASTMODIFIEDBYID,
    			ISSUESETTINGS.ISSUENAME as ISSUENAME,
    			ISSUES.ISINITIALIZED as ISINITIALIZED,
    			ISSUES.ISSYSTEMISSUE as ISSYSTEMISSUE,
    			ISSUES.ISSUETYPE as ISSUETYPE,
    			ISSUES.ISINCOMPLETE as ISINCOMPLETE,
    			ISSUESETTINGS.REVISIONNUM as ISSUESETTINGS_REVISIONNUM,
    			ISSUESETTINGS.LASTMODIFIEDDATE as ISSUESETTINGS_LASTMODIFIEDDATE,
    			ISSUESETTINGS.LASTMODIFIEDBYID as ISSUESETTINGS_LASTMODIFIEDBYID,
    			ISSUESETTINGS.ISSUEDUEDATE as ISSUEDUEDATE,
    			ISSUESETTINGS.ISSUEPRIORITY as ISSUEPRIORITY,
    			ISSUESETTINGS.ISSUESTATUS as ISSUESTATUS,
    			ISSUESETTINGS.DESCRIPTION as DESCRIPTION,
    			ISSUESETTINGS.PROJECTID as PROJECTID,
    			ISSUESETTINGS.PROJECTNAME as PROJECTNAME,
    			ISSUESETTINGS.PROJECTNAMEISCUSTOM as PROJECTNAMEISCUSTOM,
    			ENTERPRISEDATA.REVISIONNUM as ENTERPRISEDATA_REVISIONNUM,
    			ENTERPRISEDATA.CREATIONDATE as ENTERPRISEDATA_CREATIONDATE,
    			ENTERPRISEDATA.AUTHORID as ENTERPRISEDATA_AUTHORID,
    			ENTERPRISEDATA.LASTMODIFIEDDATE as ENTERPRISEDATA_LASTMODIFIEDDATE,
    			ENTERPRISEDATA.LASTMODIFIEDBYID as ENTERPRISEDATA_LASTMODIFIEDBYID,
    			ENTERPRISEDATA.DATE1 as DATE1,
    			ENTERPRISEDATA.DATE2 as DATE2,
    			ENTERPRISEDATA.DATE3 as DATE3,
    			ENTERPRISEDATA.DATE4 as DATE4,
    			ENTERPRISEDATA.DATE5 as DATE5,
    			ENTERPRISEDATA.DATE6 as DATE6,
    			ENTERPRISEDATA.DATE7 as DATE7,
    			ENTERPRISEDATA.DATE8 as DATE8,
    			ENTERPRISEDATA.DATE9 as DATE9,
    			ENTERPRISEDATA.DATE10 as DATE10,
    			ENTERPRISEDATA.VALUE1 as VALUE1,
    			ENTERPRISEDATA.VALUE2 as VALUE2,
    			ENTERPRISEDATA.VALUE3 as VALUE3,
    			ENTERPRISEDATA.VALUE4 as VALUE4,
    			ENTERPRISEDATA.VALUE5 as VALUE5,
    			ENTERPRISEDATA.VALUE6 as VALUE6,
    			ENTERPRISEDATA.VALUE7 as VALUE7,
    			ENTERPRISEDATA.VALUE8 as VALUE8,
    			ENTERPRISEDATA.VALUE9 as VALUE9,
    			ENTERPRISEDATA.VALUE10 as VALUE10,
    			ENTERPRISEDATA.VALUE11 as VALUE11,
    			ENTERPRISEDATA.VALUE12 as VALUE12,
    			ENTERPRISEDATA.VALUE13 as VALUE13,
    			ENTERPRISEDATA.VALUE14 as VALUE14,
    			ENTERPRISEDATA.VALUE15 as VALUE15,
    			ENTERPRISEDATA.VALUE16 as VALUE16,
    			ENTERPRISEDATA.VALUE17 as VALUE17,
    			ENTERPRISEDATA.VALUE18 as VALUE18,
    			ENTERPRISEDATA.VALUE19 as VALUE19,
    			ENTERPRISEDATA.VALUE20 as VALUE20,
    			ENTERPRISEDATA.STRING1 as STRING1,
    			ENTERPRISEDATA.STRING2 as STRING2,
    			ENTERPRISEDATA.STRING3 as STRING3,
    			ENTERPRISEDATA.STRING4 as STRING4,
    			ENTERPRISEDATA.STRING5 as STRING5,
    			ENTERPRISEDATA.STRING6 as STRING6,
    			ENTERPRISEDATA.STRING7 as STRING7,
    			ENTERPRISEDATA.STRING8 as STRING8,
    			ENTERPRISEDATA.STRING9 as STRING9,
    			ENTERPRISEDATA.STRING10 as STRING10,
    			ENTERPRISEDATA.LONGSTRING1 as LONGSTRING1,
    			ENTERPRISEDATA.LONGSTRING2 as LONGSTRING2,
    			ENTERPRISEDATA.LONGSTRING3 as LONGSTRING3,
    			ENTERPRISEDATA.LONGSTRING4 as LONGSTRING4,
    			ENTERPRISEDATA.LONGSTRING5 as LONGSTRING5,
    			ENTERPRISEDATA.LONGSTRING6 as LONGSTRING6,
    			ENTERPRISEDATA.LONGSTRING7 as LONGSTRING7,
    			ENTERPRISEDATA.LONGSTRING8 as LONGSTRING8,
    			ENTERPRISEDATA.LONGSTRING9 as LONGSTRING9,
    			ENTERPRISEDATA.LONGSTRING10 as LONGSTRING10
    		from
    			ISSUES 
    			join ISSUESETTINGS on ISSUES.OBJECTID = ISSUESETTINGS.ISSUEID
    			left outer join ENTERPRISEDATA on ISSUES.OBJECTID = ENTERPRISEDATA.ISSUEID;
    CREATE VIEW ITEMS as 
    
   select 'FILES' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, FILENAME, VISIBLENAME, VERSIONSTRING, DOCUMENTHASH, ISFINAL, DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from FILES
    union all
    select 'LOGENTRIES' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, ACTIONTYPE, ASSOCIATEDOBJECTIDS, OLDENTITIES, NEWENTITIES, OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from LOGENTRIES
    union all
    select 'LSBI' as TABLENAME, NULL as CLASSID, NULL as SEQNO, NULL as LASTMODONNODEID, NULL as PREVMODONNODEID, ISSUEID, NULL as OBJECTID, NULL as REVISIONNUM, NULL as CONTAINERID, NULL as AUTHORID, NULL as CREATIONDATE, NULL as LASTMODIFIEDDATE, UPDATENUMBER, NULL as PREVREVISIONNUM, NULL as LASTCMD, NULL as LASTCMDACLVERSION, NULL as USERDEFINEDFIELD, NULL as LASTMODIFIEDBYID, NULL as PARENTENTITYID, NULL as BODY, NULL as BODYCONTENTTYPE, NULL as ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, TQUNID, TABLEITEMID, TABLENODEID, TABLECMD, TABLECONTAINERID, TABLESEQNO, DIRTYCONTENT, STUBBED, ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from LSBI where TABLECMD=3
    union all
    select 'PARTICIPANTS' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, NULL as PARENTENTITYID, NULL as BODY, NULL as BODYCONTENTTYPE, NULL as ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, PARTICIPANTSTATE, PARTICIPANTROLE, PARTICIPANTTEAM, ISREQUIREDMEMBER, USERID, ISAGENT, NAME, EMAILADDRESS, ISEMAILONLY, INVITATION, ACCEPTRESENDCOUNT, ACCEPTRESENDTIMEOUT, ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from PARTICIPANTS
    union all
    select 'TASKCOMPLETIONS' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, TASKID, DISPOSITION, STATUSID, SHORTNAME, LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from TASKCOMPLETIONS
    union all
    select 'TASKS' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, DUETIME, ASSIGNEDTO, TARGETOBJECTIDS, RESPONSEID, TYPEID, LABEL, INSTRUCTIONS, ALLOWEDSTATUSES, ISSERIALREVIEW, DAYSTOREVIEW, REVIEWERIDS, REVIEWTYPE, REVIEWGROUP from TASKS;
    CREATE VIEW TASKINFO as 
    
   
   		select
    			t.ISSUEID as ISSUEID,
    			t.OBJECTID as OBJECTID,
    			t.ASSIGNEDTO as ASSIGNEDTO,
    			t.TARGETOBJECTIDS as TARGETOBJECTIDS,
    			t.DUETIME as DUETIME,
    			t.ISOBSOLETE as ISOBSOLETE,
    			tc.DISPOSITION as DISPOSITION
    			from
    				TASKS t
    				join TASKCOMPLETIONS tc on tc.TASKID = t.OBJECTID;
    CREATE INDEX DQ_ISSUEID_DEPENDSID on DQ (ISSUEID, DEPENDSID);
    CREATE INDEX EMAILQ_TIMEQUEUED on EMAILQ (TIMEQUEUED);
    CREATE INDEX FOLDERS_CONTAINERID_ISSUEID on FOLDERS (CONTAINERID, ISSUEID);
    CREATE INDEX IMQ_DATETIMEQUEUED on IMQ (DATETIMEQUEUED);
    CREATE INDEX INVITATIONS_RECIPIENTUSERID_INVITATIONID on INVITATIONS (RECIPIENTUSERID, INVITATIONID);
    CREATE INDEX INVITATIONS_TQUNID on INVITATIONS (TQUNID);
    CREATE INDEX ISSUESETTINGS_CONTAINERID on ISSUESETTINGS (CONTAINERID);
    CREATE INDEX KMTPMSG_RECEIVEDDATE on KMTPMSG (RECEIVEDDATE desc);
    CREATE INDEX KMTPNODEQ_MSGID on KMTPNODEQ (MSGID);
    CREATE INDEX KMTPNODEQ_NODEID_MSGID on KMTPNODEQ (NODEID, MSGID);
    CREATE INDEX KMTPNODEQ_RECEIVEDDATE on KMTPNODEQ (RECEIVEDDATE desc);
    CREATE INDEX LSBI_ISSUEID_TABLEITEMID on LSBI (ISSUEID, TABLEITEMID);
    CREATE INDEX LSBN_ISSUEID_NODEID on LSBN (ISSUEID, NODEID);
    CREATE INDEX MMQ_ISSUEID_MMQENTRYINDEX on MMQ (ISSUEID, MMQENTRYINDEX);
    CREATE INDEX NODEREG_NODEID_USERID on NODEREG (NODEID, USERID);
    CREATE INDEX NODEREG_TQUNID on NODEREG (TQUNID);
    CREATE INDEX NODEREG_USERID_NODEID on NODEREG (USERID, NODEID);
    CREATE INDEX NODES_NODEID on NODES (NODEID);
    CREATE INDEX NODES_TQUNID on NODES (TQUNID);
    CREATE INDEX PARTICIPANTNODES_ISSUEID_OBJECTID_NODEID on PARTICIPANTNODES (ISSUEID, OBJECTID, NODEID);
    CREATE INDEX PARTICIPANTNODES_TQUNID on PARTICIPANTNODES (TQUNID);
    CREATE INDEX PARTICIPANTSETTINGS_PARTICIPANTID on PARTICIPANTSETTINGS (PARTICIPANTID);
    CREATE INDEX PARTITIONS_LDAPDN on PARTITIONS (LDAPDN);
    CREATE INDEX PARTITIONS_PARTITIONID_SERVERNODEID on PARTITIONS (PARTITIONID, SERVERNODEID);
    CREATE INDEX PARTITIONS_SERVERNODEID_PARTITIONID on PARTITIONS (SERVERNODEID, PARTITIONID);
    CREATE INDEX PARTITIONS_TQUNID on PARTITIONS (TQUNID);
    CREATE INDEX TASKCOMPLETIONS_TASKID on TASKCOMPLETIONS (TASKID);
    CREATE INDEX TASKS_ASSIGNEDTO on TASKS (ASSIGNEDTO);
    CREATE INDEX USERS_PARTITIONID_USERID on USERS (PARTITIONID, USERID);
    CREATE INDEX USERS_TQUNID on USERS (TQUNID);
    CREATE INDEX USERS_USERID_PARTITIONID on USERS (USERID, PARTITIONID);
    CREATE INDEX USERS_USERSID_USERID on USERS (USERSID, USERID);
    COMMIT;
  }
} {}

# Given the schema above, the following query was cause an assertion fault
# do to an uninitialized field in a Select structure.
#
do_test tkt1449-1.2 {
  execsql {
    select NEWENTITIES from ITEMS where ((ISSUEID = 'x') and (OBJECTID = 'y'))
  }
} {}

finish_test

Added test/tkt1473.test.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1473 has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound {
  finish_test
  return 
}

do_test tkt1473-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    SELECT * FROM t1
  }
} {1 2 3 4}

do_test tkt1473-1.2 {
  execsql {
    SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=0
  }
} {1}
do_test tkt1473-1.3 {
  execsql {
    SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=0
  }
} {1}
do_test tkt1473-1.4 {
  execsql {
    SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=4
  }
} {1 2}
do_test tkt1473-1.5 {
  execsql {
    SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=4
  }
} {1 2}
do_test tkt1473-1.6 {
  execsql {
    SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=4
  }
} {2}
do_test tkt1473-1.7 {
  execsql {
    SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=4
  }
} {2}
do_test tkt1473-1.8 {
  execsql {
    SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=0
  }
} {}
do_test tkt1473-1.9 {
  execsql {
    SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=0
  }
} {}

# Everything from this point on depends on sub-queries. So skip it
# if sub-queries are not available.
ifcapable !subquery {
  finish_test
  return
}

do_test tkt1473-2.2 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=0)
  }
} {1}
do_test tkt1473-2.3 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=0)
  }
} {1}
do_test tkt1473-2.4 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=4)
  }
} {1}
do_test tkt1473-2.5 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=4)
  }
} {1}
do_test tkt1473-2.6 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=4)
  }
} {2}
do_test tkt1473-2.7 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=4)
  }
} {2}
do_test tkt1473-2.8 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=0)
  }
} {{}}
do_test tkt1473-2.9 {
  execsql {
    SELECT (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=0)
  }
} {{}}

do_test tkt1473-3.2 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=0)
  }
} {1}
do_test tkt1473-3.3 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=0)
  }
} {1}
do_test tkt1473-3.4 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=4)
  }
} {1}
do_test tkt1473-3.5 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=4)
  }
} {1}
do_test tkt1473-3.6 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=4)
  }
} {1}
do_test tkt1473-3.7 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=4)
  }
} {1}
do_test tkt1473-3.8 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=0)
  }
} {0}
do_test tkt1473-3.9 {
  execsql {
    SELECT EXISTS
      (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=0)
  }
} {0}

do_test tkt1473-4.1 {
  execsql {
    CREATE TABLE t2(x,y);
    INSERT INTO t2 VALUES(1,2);
    INSERT INTO t2 SELECT x+2, y+2 FROM t2;
    INSERT INTO t2 SELECT x+4, y+4 FROM t2;
    INSERT INTO t2 SELECT x+8, y+8 FROM t2;
    INSERT INTO t2 SELECT x+16, y+16 FROM t2;
    INSERT INTO t2 SELECT x+32, y+32 FROM t2;
    INSERT INTO t2 SELECT x+64, y+64 FROM t2;
    SELECT count(*), sum(x), sum(y) FROM t2;
  }
} {64 4096 4160}
do_test tkt1473-4.2 {
  execsql {
    SELECT 1 FROM t2 WHERE x=0
    UNION ALL
    SELECT 2 FROM t2 WHERE x=1
    UNION ALL
    SELECT 3 FROM t2 WHERE x=2
    UNION ALL
    SELECT 4 FROM t2 WHERE x=3
    UNION ALL
    SELECT 5 FROM t2 WHERE x=4
    UNION ALL
    SELECT 6 FROM t2 WHERE y=0
    UNION ALL
    SELECT 7 FROM t2 WHERE y=1
    UNION ALL
    SELECT 8 FROM t2 WHERE y=2
    UNION ALL
    SELECT 9 FROM t2 WHERE y=3
    UNION ALL
    SELECT 10 FROM t2 WHERE y=4
  }
} {2 4 8 10}
do_test tkt1473-4.3 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=3
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=2
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {2}
do_test tkt1473-4.4 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=3
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=2
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {4}
do_test tkt1473-4.5 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=2
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {8}
do_test tkt1473-4.6 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=-2
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=-3
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {10}
do_test tkt1473-4.7 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=-2
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=-3
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {{}}

do_test tkt1473-5.3 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=3
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=2
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}
do_test tkt1473-5.4 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=3
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=2
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}

do_test tkt1473-5.5 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=2
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {1}
do_test tkt1473-5.6 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=-2
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=-3
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}
do_test tkt1473-5.7 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION ALL
      SELECT 2 FROM t2 WHERE x=-1
      UNION ALL
      SELECT 3 FROM t2 WHERE x=2
      UNION ALL
      SELECT 4 FROM t2 WHERE x=-2
      UNION ALL
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION ALL
      SELECT 7 FROM t2 WHERE y=1
      UNION ALL
      SELECT 8 FROM t2 WHERE y=-3
      UNION ALL
      SELECT 9 FROM t2 WHERE y=3
      UNION ALL
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {0}

do_test tkt1473-6.3 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=3
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=2
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}
do_test tkt1473-6.4 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=-1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=3
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=2
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}

do_test tkt1473-6.5 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=-1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=-1
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=2
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {1}
do_test tkt1473-6.6 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=-1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=-2
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=-3
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}
do_test tkt1473-6.7 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=-1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=-2
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=-3
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {0}
do_test tkt1473-6.8 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=-1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=-2
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=-3
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=4
    )
  }
} {1}
do_test tkt1473-6.9 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0
      UNION
      SELECT 2 FROM t2 WHERE x=-1
      UNION
      SELECT 3 FROM t2 WHERE x=2
      UNION
      SELECT 4 FROM t2 WHERE x=-2
      UNION
      SELECT 5 FROM t2 WHERE x=4
      UNION ALL
      SELECT 6 FROM t2 WHERE y=0
      UNION
      SELECT 7 FROM t2 WHERE y=1
      UNION
      SELECT 8 FROM t2 WHERE y=-3
      UNION
      SELECT 9 FROM t2 WHERE y=3
      UNION
      SELECT 10 FROM t2 WHERE y=-4
    )
  }
} {0}

do_test tkt1473-7.1 {
  execsql {
    SELECT 1 FROM t2 WHERE x=1 EXCEPT SELECT 2 FROM t2 WHERE y=2
  }
} {1}
do_test tkt1473-7.2 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=1 EXCEPT SELECT 2 FROM t2 WHERE y=2
    )
  }
} {1}
do_test tkt1473-7.3 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=1 EXCEPT SELECT 2 FROM t2 WHERE y=2
    )
  }
} {1}
do_test tkt1473-7.4 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0 EXCEPT SELECT 2 FROM t2 WHERE y=2
    )
  }
} {{}}
do_test tkt1473-7.5 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=0 EXCEPT SELECT 2 FROM t2 WHERE y=2
    )
  }
} {0}

do_test tkt1473-8.1 {
  execsql {
    SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 2 FROM t2 WHERE y=2
  }
} {}
do_test tkt1473-8.1 {
  execsql {
    SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=2
  }
} {1}
do_test tkt1473-8.3 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 2 FROM t2 WHERE y=2
    )
  }
} {{}}
do_test tkt1473-8.4 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=2
    )
  }
} {1}
do_test tkt1473-8.5 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 2 FROM t2 WHERE y=2
    )
  }
} {0}
do_test tkt1473-8.6 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=2
    )
  }
} {1}
do_test tkt1473-8.7 {
  execsql {
    SELECT (
      SELECT 1 FROM t2 WHERE x=0 INTERSECT SELECT 1 FROM t2 WHERE y=2
    )
  }
} {{}}
do_test tkt1473-8.8 {
  execsql {
    SELECT EXISTS (
      SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=0
    )
  }
} {0}




finish_test

Added test/tkt1501.test.









































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 2005 November 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1501 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound {
  finish_test
  return
}

do_test tkt1501-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    SELECT a, b, 'abc' FROM t1
      UNION
      SELECT b, a, 'xyz' FROM t1
      ORDER BY 2, 3;
  }
} {2 1 xyz 1 2 abc}

finish_test

Added test/tkt1512.test.













































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1512 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!vacuum || !autovacuum} {
  finish_test
  return
}
if {[db one {PRAGMA auto_vacuum}]} {
  finish_test
  return
}

do_test tkt1512-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    SELECT * FROM t1
  }
} {1 2 3 4}
do_test tkt1512-1.2 {
  file size test.db
} {2048}
do_test tkt1512-1.3 {
  execsql {
    DROP TABLE t1;
  }
  file size test.db
} {2048}
do_test tkt1512-1.4 {
  execsql {
    VACUUM;
  }
  file size test.db
} {1024}


finish_test

Added test/tkt1514.test.























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 2005 November 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1514 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt1514-1.1 {
  catchsql {
    CREATE TABLE t1(a,b);
    SELECT a FROM t1 WHERE max(b)<10 GROUP BY a;
  }
} {1 {misuse of aggregate: max()}}

finish_test

Added test/tkt1536.test.













































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 2005 November 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1536 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt1536-1.1 {
  execsql {
    CREATE TABLE t1(
      a INTEGER PRIMARY KEY,
      b TEXT
    );
    INSERT INTO t1 VALUES(1,'01');
    SELECT typeof(a), typeof(b) FROM t1;
  }
} {integer text}
do_test tkt1536-1.2 {
  execsql {
    INSERT INTO t1(b) SELECT b FROM t1;
    SELECT b FROM t1 WHERE rowid=2;
  }
} {01}
 

finish_test

Added test/tkt1537.test.





















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# 2005 November 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1537 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt1537-1.1 {
  execsql {
    CREATE TABLE t1(id, a1, a2);
    INSERT INTO t1 VALUES(1, NULL, NULL);
    INSERT INTO t1 VALUES(2, 1, 3);
    CREATE TABLE t2(id, b);
    INSERT INTO t2 VALUES(3, 1);
    INSERT INTO t2 VALUES(4, NULL);
    SELECT * FROM t1 LEFT JOIN t2 ON a1=b OR a2=+b;
  }
} {1 {} {} {} {} 2 1 3 3 1}
do_test tkt1537-1.2 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON a1=b OR a2=b;
  }
} {1 {} {} {} {} 2 1 3 3 1}
do_test tkt1537-1.3 {
  execsql {
    SELECT * FROM t2 LEFT JOIN t1 ON a1=b OR a2=b;
  }
} {3 1 2 1 3 4 {} {} {} {}}
ifcapable subquery {
  do_test tkt1537-1.4 {
    execsql {
      SELECT * FROM t1 LEFT JOIN t2 ON b IN (a1,a2);
    }
  } {1 {} {} {} {} 2 1 3 3 1}
  do_test tkt1537-1.5 {
    execsql {
      SELECT * FROM t2 LEFT JOIN t1 ON b IN (a2,a1);
    }
  } {3 1 2 1 3 4 {} {} {} {}}
}
do_test tkt1537-1.6 {
  execsql {
    CREATE INDEX t1a1 ON t1(a1);
    CREATE INDEX t1a2 ON t1(a2);
    CREATE INDEX t2b ON t2(b);
    SELECT * FROM t1 LEFT JOIN t2 ON a1=b OR a2=b;
  }
} {1 {} {} {} {} 2 1 3 3 1}
do_test tkt1537-1.7 {
  execsql {
    SELECT * FROM t2 LEFT JOIN t1 ON a1=b OR a2=b;
  }
} {3 1 2 1 3 4 {} {} {} {}}

ifcapable subquery {
  do_test tkt1537-1.8 {
    execsql {
      SELECT * FROM t1 LEFT JOIN t2 ON b IN (a1,a2);
    }
  } {1 {} {} {} {} 2 1 3 3 1}
  do_test tkt1537-1.9 {
    execsql {
      SELECT * FROM t2 LEFT JOIN t1 ON b IN (a2,a1);
    }
  } {3 1 2 1 3 4 {} {} {} {}}
}

execsql {
  DROP INDEX t1a1;
  DROP INDEX t1a2;
  DROP INDEX t2b;
}

do_test tkt1537-2.1 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b BETWEEN a1 AND a2;
  }
} {1 {} {} {} {} 2 1 3 3 1}
do_test tkt1537-2.2 {
  execsql {
    CREATE INDEX t2b ON t2(b);
    SELECT * FROM t1 LEFT JOIN t2 ON b BETWEEN a1 AND a2;
  }
} {1 {} {} {} {} 2 1 3 3 1}
do_test tkt1537-2.3 {
  execsql {
    SELECT * FROM t2 LEFT JOIN t1 ON b BETWEEN a1 AND a2;
  }
} {3 1 2 1 3 4 {} {} {} {}}
do_test tkt1537-2.4 {
  execsql {
    CREATE INDEX t1a1 ON t1(a1);
    CREATE INDEX t1a2 ON t1(a2);
    SELECT * FROM t2 LEFT JOIN t1 ON b BETWEEN a1 AND a2;
  }
} {3 1 2 1 3 4 {} {} {} {}}

do_test tkt1537-3.1 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b GLOB 'abc*' WHERE t1.id=1;
  }
} {1 {} {} {} {}}
do_test tkt1537-3.2 {
  execsql { 
    SELECT * FROM t2 LEFT JOIN t1 ON a1 GLOB 'abc*' WHERE t2.id=3;
  }
} {3 1 {} {} {}}


finish_test

Added test/tkt1567.test.







































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 2005 December 19 2005
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1567 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt1567-1.1 {
  execsql {
    CREATE TABLE t1(a TEXT PRIMARY KEY);
  }
  set bigstr abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  for {set i 0} {$i<100} {incr i} {
    set x [format %5d [expr $i*2]]
    set sql "INSERT INTO t1 VALUES('$x-$bigstr')"
    execsql $sql
  }
} {}
integrity_check tkt1567-1.2

do_test tkt1567-1.3 {
  execsql {
    BEGIN;
    UPDATE t1 SET a = a||'x' WHERE rowid%2==0;
  }
} {}
do_test tkt1567-1.4 {
  catchsql {
    UPDATE t1 SET a = CASE WHEN rowid<90 THEN substr(a,1,10) ELSE '9999' END;
  }
} {1 {column a is not unique}}
do_test tkt1567-1.5 {
  execsql {
    COMMIT;
  }
} {}
integrity_check tkt1567-1.6

finish_test

Added test/tkt1644.test.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# 2006 January 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1644 is
# fixed.  Ticket #1644 complains that precompiled statements
# are not expired correctly as a result of changes to TEMP
# views and triggers.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !tempdb||!view {
  finish_test
  return
}  

# Create two tables T1 and T2 and make V1 point to T1.
do_test tkt1644-1.1 {
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(1);
    CREATE TABLE t2(b);
    INSERT INTO t2 VALUES(99);
    CREATE TEMP VIEW v1 AS SELECT * FROM t1;
    SELECT * FROM v1;
  }
} {1}

# The "SELECT * FROM v1" should be in the TCL interface cache below.
# It will continue to point to T1 unless the cache is invalidated when
# the view changes.
#
do_test tkt1644-1.2 {
  execsql {
    DROP VIEW v1;
    CREATE TEMP VIEW v1 AS SELECT * FROM t2;
    SELECT * FROM v1;
  }
} {99}

# Cache an access to the T1 table.
#
do_test tkt1644-1.3 {
  execsql {
    SELECT * FROM t1;
  }
} {1}

# Create a temp table T1.  Make sure the cache is invalidated so that
# the statement is recompiled and refers to the empty temp table.
#
do_test tkt1644-1.4 {
  execsql {
    CREATE TEMP TABLE t1(x);
  }
  execsql {
    SELECT * FROM t1;
  }
} {}

ifcapable view {
  do_test tkt1644-2.1 {
    execsql {
      CREATE TEMP TABLE temp_t1(a, b);
    }
    set ::DB [sqlite3_connection_pointer db]
    set ::STMT [sqlite3_prepare $::DB "SELECT * FROM temp_t1" -1 DUMMY]
    execsql {
      DROP TABLE temp_t1;
    }
    list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT]
  } {SQLITE_ERROR SQLITE_SCHEMA}
  
  do_test tkt1644-2.2 {
    execsql {
      CREATE TABLE real_t1(a, b);
      CREATE TEMP VIEW temp_v1 AS SELECT * FROM real_t1;
    }
    set ::DB [sqlite3_connection_pointer db]
    set ::STMT [sqlite3_prepare $::DB "SELECT * FROM temp_v1" -1 DUMMY]
    execsql {
      DROP VIEW temp_v1;
    }
    list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT]
  } {SQLITE_ERROR SQLITE_SCHEMA}

  do_test tkt1644-2.3 {
    execsql {
      CREATE TEMP VIEW temp_v1 AS SELECT * FROM real_t1 LIMIT 10 OFFSET 10;
    }
    set ::DB [sqlite3_connection_pointer db]
    set ::STMT [sqlite3_prepare $::DB "SELECT * FROM temp_v1" -1 DUMMY]
    execsql {
      DROP VIEW temp_v1;
    }
    list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT]
  } {SQLITE_ERROR SQLITE_SCHEMA}
}


finish_test

Added test/tkt1667.test.







































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# 2006 February 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1667 has been
# fixed.  
#
#
# $Id: tkt1667.test,v 1.4 2009/02/05 17:00:54 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !autovacuum||!tclvar {
  finish_test
  return
}

db close
file delete -force test.db test.db-journal

# Set the pending byte offset such that the page it is on is
# the first autovacuum pointer map page in the file (assume a page 
# size of 1024).

set first_ptrmap_page   [expr 1024/5 + 3]
sqlite3_test_control_pending_byte [expr 1024 * ($first_ptrmap_page-1)]

sqlite db test.db

do_test tkt1667-1 {
  execsql {
    PRAGMA auto_vacuum = 1;
    BEGIN;
    CREATE TABLE t1(a, b);
  }
  for {set i 0} {$i < 500} {incr i} {
    execsql {
      INSERT INTO t1 VALUES($i, randstr(1000, 2000))
    }
  }
  execsql {
    COMMIT;
  }
} {}
for {set i 0} {$i < 500} {incr i} {
  do_test tkt1667-2.$i.1 {
    execsql {
      DELETE FROM t1 WHERE a = $i;
    }
  } {}
  integrity_check tkt1667-2.$i.2
}

do_test tkt1667-3 {
  execsql {
    BEGIN;
  }
  for {set i 0} {$i < 500} {incr i} {
    execsql {
      INSERT INTO t1 VALUES($i, randstr(1000, 2000))
    }
  }
  execsql {
    COMMIT;
  }
} {}
do_test tkt1667-4.1 {
  execsql {
    DELETE FROM t1;
  }
} {}
integrity_check tkt1667-4.2

finish_test

Added test/tkt1873.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2006 June 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1873 has been
# fixed.  
#
#
# $Id: tkt1873.test,v 1.2 2007/10/09 08:29:33 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !attach {
  finish_test
  return
}

file delete -force test2.db test2.db-journal

do_test tkt1873-1.1 {
  execsql {
    CREATE TABLE t1(x, y);
    ATTACH 'test2.db' AS aux;
    CREATE TABLE aux.t2(x, y);
    INSERT INTO t1 VALUES(1, 2);
    INSERT INTO t1 VALUES(3, 4);
    INSERT INTO t2 VALUES(5, 6);
    INSERT INTO t2 VALUES(7, 8);
  }
} {}

do_test tkt1873-1.2 {
  set rc [catch {
    db eval {SELECT * FROM t2 LIMIT 1} {
      db eval {DETACH aux}
    }
  } msg]
  list $rc $msg
} {1 {database aux is locked}}

do_test tkt1873-1.3 {
  set rc [catch {
    db eval {SELECT * FROM t1 LIMIT 1} {
      db eval {DETACH aux}
    }
  } msg]
  list $rc $msg
} {0 {}}

do_test tkt1873-1.4 {
  catchsql {
    select * from t2;
  }
} {1 {no such table: t2}}

do_test tkt1873-1.5 {
  catchsql {
    ATTACH 'test2.db' AS aux;
    select * from t2;
  }
} {0 {5 6 7 8}}

finish_test

Added test/tkt2141.test.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 2007 January 03
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #2141 has been
# fixed.  
#
#
# $Id: tkt2141.test,v 1.2 2007/09/12 17:01:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

do_test tkt2141-1.1 {
  execsql {
      CREATE TABLE tab1 (t1_id integer PRIMARY KEY, t1_desc);
      INSERT INTO tab1 VALUES(1,'rec 1 tab 1');
      CREATE TABLE tab2 (t2_id integer PRIMARY KEY, t2_id_t1, t2_desc);
      INSERT INTO tab2 VALUES(1,1,'rec 1 tab 2');
      CREATE TABLE tab3 (t3_id integer PRIMARY KEY, t3_id_t2, t3_desc);
      INSERT INTO tab3 VALUES(1,1,'aa');
      SELECT *
      FROM tab1 t1 LEFT JOIN tab2 t2 ON t1.t1_id = t2.t2_id_t1
      WHERE t2.t2_id IN
           (SELECT t2_id FROM tab2, tab3 ON t2_id = t3_id_t2
             WHERE t3_id IN (1,2) GROUP BY t2_id);
  }
} {1 {rec 1 tab 1} 1 1 {rec 1 tab 2}}
do_test tkt2141-1.2 {
  execsql {
      SELECT *
      FROM tab1 t1 LEFT JOIN tab2 t2 ON t1.t1_id = t2.t2_id_t1
      WHERE t2.t2_id IN
           (SELECT t2_id FROM tab2, tab3 ON t2_id = t3_id_t2
             WHERE t3_id IN (1,2));
  }
} {1 {rec 1 tab 1} 1 1 {rec 1 tab 2}}
do_test tkt2141-1.3 {
  execsql {
      SELECT *
      FROM tab1 t1 LEFT JOIN tab2 t2
      WHERE t2.t2_id IN
           (SELECT t2_id FROM tab2, tab3 ON t2_id = t3_id_t2
             WHERE t3_id IN (1,2));
  }
} {1 {rec 1 tab 1} 1 1 {rec 1 tab 2}}

finish_test

Added test/tkt2192.test.

























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# 2007 January 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #2192 has been
# fixed.  
#
#
# $Id: tkt2192.test,v 1.3 2008/08/04 03:51:24 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !datetime||!compound {
  finish_test
  return
}

do_test tkt2192-1.1 {
  execsql {
    -- Raw data (RBS) --------
    
    create table records (
      date          real,
      type          text,
      description   text,
      value         integer,
      acc_name      text,
      acc_no        text
    );
    
    -- Direct Debits ----------------
    create view direct_debits as
      select * from records where type = 'D/D';
    
    create view monthly_direct_debits as
      select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value
        from direct_debits
       group by strftime('%Y-%m', date);
    
    -- Expense Categories ---------------
    create view energy as
      select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value
        from direct_debits
       where description like '%NPOWER%'
       group by strftime('%Y-%m', date);
    
    create view phone_internet as
      select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value
        from direct_debits
       where description like '%BT DIRECT%'
          or description like '%SUPANET%'
          or description like '%ORANGE%'
       group by strftime('%Y-%m', date);
    
    create view credit_cards as
      select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value
        from direct_debits where description like '%VISA%'
       group by strftime('%Y-%m', date);
    
    -- Overview ---------------------
    
    create view expense_overview as
      select 'Energy' as expense, date, value from energy
      union
      select 'Phone/Internet' as expense, date, value from phone_internet
      union
      select 'Credit Card' as expense, date, value from credit_cards;
    
    create view jan as
      select 'jan', expense, value from expense_overview
       where date like '%-01';
    
    create view nov as
      select 'nov', expense, value from expense_overview
       where date like '%-11';
    
    create view summary as
      select * from jan join nov on (jan.expense = nov.expense);
  }
} {}
do_test tkt2192-1.2 {
  # set ::sqlite_addop_trace 1
  execsql {
    select * from summary;
  }
} {}
do_test tkt2192-2.1 {
  execsql {
    CREATE TABLE t1(a,b);
    CREATE VIEW v1 AS
      SELECT * FROM t1 WHERE b%7=0 UNION SELECT * FROM t1 WHERE b%5=0;
    INSERT INTO t1 VALUES(1,7);
    INSERT INTO t1 VALUES(2,10);
    INSERT INTO t1 VALUES(3,14);
    INSERT INTO t1 VALUES(4,15);
    INSERT INTO t1 VALUES(1,16);
    INSERT INTO t1 VALUES(2,17);
    INSERT INTO t1 VALUES(3,20);
    INSERT INTO t1 VALUES(4,21);
    INSERT INTO t1 VALUES(1,22);
    INSERT INTO t1 VALUES(2,24);
    INSERT INTO t1 VALUES(3,25);
    INSERT INTO t1 VALUES(4,26);
    INSERT INTO t1 VALUES(1,27);
 
    SELECT b FROM v1 ORDER BY b;
  }
} {7 10 14 15 20 21 25}
do_test tkt2192-2.2 {
  execsql {
    SELECT * FROM v1 ORDER BY a, b;
  }
} {1 7 2 10 3 14 3 20 3 25 4 15 4 21}
do_test tkt2192-2.3 {
  execsql {
    SELECT x.a || '/' || x.b || '/' || y.b
      FROM v1 AS x JOIN v1 AS y ON x.a=y.a AND x.b<y.b
     ORDER BY x.a, x.b, y.b
  }
} {3/14/20 3/14/25 3/20/25 4/15/21}
do_test tkt2192-2.4 {
  execsql {
    CREATE VIEW v2 AS
    SELECT x.a || '/' || x.b || '/' || y.b AS z
      FROM v1 AS x JOIN v1 AS y ON x.a=y.a AND x.b<y.b
     ORDER BY x.a, x.b, y.b;
    SELECT * FROM v2;
  }
} {3/14/20 3/14/25 3/20/25 4/15/21}

finish_test

Added test/tkt2213.test.



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 2007 Febuary 05
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #2213 has been
# fixed.  
#
#
# $Id: tkt2213.test,v 1.2 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt2213-1 {
  sqlite3_create_function db
  catchsql {
    SELECT tkt2213func(tkt2213func('abcd'));
  }
} {0 abcd}

finish_test

Added test/tkt2251.test.

























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# 2007 Febuary 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that table column values
# are pulled out of the database correctly.
#
# Long ago, the OP_Column opcode was sufficient to pull out the
# value of a table column.  But then we added the ALTER TABLE ADD COLUMN
# feature.  An added column might not actually exist in every row,
# and so the OP_Column opcode has to contain a default value.  Later
# still we added a feature whereby a REAL value with no fractional
# part is stored in the database file as an integer to save space.
# After extracting the value, we have to call OP_RealAffinity to
# convert it back to a REAL.
#
# The sqlite3ExprCodeGetColumn() routine was added to take care of
# all of the complications above.  The tests in this file attempt
# to verify that sqlite3ExprCodeGetColumn() is used instead of a
# raw OP_Column in all places where a table column is extracted from
# the database.
#
# $Id: tkt2251.test,v 1.2 2007/09/12 17:01:45 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !altertable {
  finish_test
  return
}

# Create sample data.  Verify that the default value and type of an added
# column is correct for aggregates.
do_test tkt2251-1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES(9);
    INSERT INTO t1 VALUES(9);
    INSERT INTO t1 VALUES(9);
    INSERT INTO t1 VALUES(3);
    INSERT INTO t1 VALUES(2);
    ALTER TABLE t1 ADD COLUMN b REAL DEFAULT 4.0;
    SELECT avg(b), typeof(avg(b)) FROM t1;
  }
} {4.0 real}
do_test tkt2251-1.2 {
  execsql {
    SELECT sum(b), typeof(sum(b)) FROM t1;
  }
} {32.0 real}
do_test tkt2251-1.3 {
  execsql {
    SELECT a, sum(b), typeof(sum(b)) FROM t1 GROUP BY a ORDER BY a;
  }
} {1 8.0 real 2 8.0 real 3 4.0 real 9 12.0 real}

# Make sure that the REAL value comes out when values are accessed
# by index.
#
do_test tkt2251-2.1 {
  execsql {
    SELECT b, typeof(b) FROM t1 WHERE a=3;
  }
} {4.0 real}
do_test tkt2251-2.2 {
  execsql {
    CREATE INDEX t1i1 ON t1(a,b);
    SELECT b, typeof(b) FROM t1 WHERE a=3;
  }
} {4.0 real}
do_test tkt2251-2.3 {
  execsql {
    REINDEX;
    SELECT b, typeof(b) FROM t1 WHERE a=3;
  }
} {4.0 real}

# Make sure the correct REAL value is used when copying from one
# table to another.
#
do_test tkt2251-3.1 {
  execsql {
    CREATE TABLE t2(x,y);
    INSERT INTO t2 SELECT * FROM t1;
    SELECT y, typeof(y) FROM t2 WHERE x=3;
  }
} {4.0 real}
do_test tkt2251-3.2 {
  execsql {
    CREATE TABLE t3 AS SELECT * FROM t1;
    SELECT b, typeof(b) FROM t3 WHERE a=3;
  }
} {4.0 real}


finish_test

Added test/tkt2285.test.

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 2005 September 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. Specifically.
# it contains tests to verify that ticket #2285 has been fixed.  
#
# $Id: tkt2285.test,v 1.2 2008/07/12 14:52:20 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !tempdb {
  finish_test
  return
}

do_test tkt2285-1.1 {
  execsql {
    PRAGMA locking_mode = EXCLUSIVE;
  }
  execsql {
    BEGIN;
    CREATE TABLE abc(a, b, c);
    ROLLBACK;
  }
} {}

do_test tkt2285-1.2 {
  execsql {
    SELECT * FROM sqlite_master;
  }
} {}

ifcapable tempdb {
  do_test tkt2285-2.1 {
    execsql {
      BEGIN;
      CREATE TEMP TABLE abc(a, b, c);
      ROLLBACK;
    }
  } {}
  do_test tkt2285-2.2 {
    execsql {
      SELECT * FROM sqlite_temp_master;
    }
  } {}
}

finish_test

Added test/tkt2332.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2007 May 3
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt2332.test,v 1.4 2007/09/12 17:01:45 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !incrblob||!tclvar {
  finish_test
  return
}

do_test tkt2332.1 {
  execsql {
    CREATE TABLE blobs (k INTEGER PRIMARY KEY, v BLOB);
    PRAGMA cache_size = 100;
  }
} {}

set ::iKey 1
foreach Len [list 10000 100000 1000000] {
  do_test tkt2332.$Len.1 {
    set val "[expr rand()][expr rand()][expr rand()][expr rand()][expr rand()]"
    set ::blobstr [string range \
      [string repeat $val [expr ($Len/[string length $val])+1]] 0 [expr $Len-1]
    ]

    db eval { INSERT INTO blobs VALUES($::iKey, zeroblob($Len)) }
  } {}

  do_test tkt2332.$Len.2 {
    execsql {
      SELECT length(v) FROM blobs WHERE k = $::iKey;
    }
  } $Len

  do_test tkt2332.$Len.3 {
    set ::fd [db incrblob blobs v $::iKey]
    puts -nonewline $::fd $::blobstr
    close $::fd
  } {}

  do_test tkt2332.$Len.4 {
    execsql { SELECT length(v) FROM blobs WHERE k = $::iKey; }
  } $Len

  do_test tkt2332.$Len.5 {
    lindex [execsql {SELECT v FROM blobs WHERE k = $::iKey}] 0
  } $::blobstr

  incr ::iKey
}

# Free memory:
unset ::blobstr

finish_test

Added test/tkt2339.test.









































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# 2007 May 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt2339.test,v 1.2 2007/09/12 17:01:45 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery||!compound {
  finish_test
  return
}

do_test tkt2339.1 {
  execsql {
    create table t1(num int);
    insert into t1 values (1);
    insert into t1 values (2);
    insert into t1 values (3);
    insert into t1 values (4);
    
    create table t2(num int);
    insert into t2 values (11);
    insert into t2 values (12);
    insert into t2 values (13);
    insert into t2 values (14);
    
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC LIMIT 2)
    UNION
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC LIMIT 2)
  }
} {3 4 13 14}
do_test tkt2339.2 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC LIMIT 2)
    UNION ALL
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC LIMIT 2)
  }
} {4 3 14 13}
do_test tkt2339.3 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC)
    UNION ALL
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC LIMIT 2)
  }
} {4 3 2 1 14 13}
do_test tkt2339.4 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC LIMIT 2)
    UNION ALL
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC)
  }
} {4 3 14 13 12 11}
do_test tkt2339.5 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC LIMIT 2)
    UNION
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC)
  }
} {3 4 11 12 13 14}
do_test tkt2339.6 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC LIMIT 2)
    EXCEPT
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC)
  }
} {3 4}
do_test tkt2339.7 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 LIMIT 2)
    UNION
    SELECT * FROM (SELECT * FROM t2 ORDER BY num DESC LIMIT 2)
  }
} {1 2 13 14}
do_test tkt2339.8 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 LIMIT 2)
    UNION
    SELECT * FROM (SELECT * FROM t2 LIMIT 2)
  }
} {1 2 11 12}
do_test tkt2339.9 {
  execsql {
    SELECT * FROM (SELECT * FROM t1 ORDER BY num DESC LIMIT 2)
    UNION
    SELECT * FROM (SELECT * FROM t2 LIMIT 2)
  }
} {3 4 11 12}


finish_test

Added test/tkt2391.test.



































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#
# 2007 May 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# $Id: tkt2391.test,v 1.1 2007/05/29 12:11:30 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt2391.1 {
  execsql {
    CREATE TABLE folders(folderid, parentid, foldername COLLATE binary);
    INSERT INTO folders VALUES(1, 3, 'FolderA');
    INSERT INTO folders VALUES(1, 3, 'folderB');
    INSERT INTO folders VALUES(4, 0, 'FolderC');
  }
} {}

do_test tkt2391.2 {
  execsql {
    SELECT count(*) FROM folders WHERE foldername < 'FolderC';
  }
} {1}

do_test tkt2391.3 {
  execsql {
    SELECT count(*) FROM folders WHERE foldername < 'FolderC' COLLATE nocase;
  }
} {2}

# This demonstrates the bug. Creating the index causes SQLite to ignore
# the "COLLATE nocase" clause and use the default collation sequence 
# for column "foldername" instead (happens to be BINARY in this case).
#
do_test tkt2391.4 {
  execsql {
    CREATE INDEX f_i ON folders(foldername);
    SELECT count(*) FROM folders WHERE foldername < 'FolderC' COLLATE nocase;
  }
} {2}

finish_test

Added test/tkt2409.test.











































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# 2007 June 13
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #2409 has been
# fixed. More specifically, they verify that if SQLite cannot
# obtain an EXCLUSIVE lock while trying to spill the cache during
# any statement other than a COMMIT, an I/O error is returned instead
# of SQLITE_BUSY.
#
# $Id: tkt2409.test,v 1.6 2008/08/28 17:46:19 drh Exp $

# Test Outline:
#
#   tkt-2409-1.*: Cause a cache-spill during an INSERT that is within
#       a db transaction but does not start a statement transaction.
#       Verify that the transaction is automatically rolled back
#       and SQLITE_IOERR_BLOCKED is returned
#
#       UPDATE: As of the pcache modifications, failing to upgrade to
#       an exclusive lock when attempting a cache-spill is no longer an
#       error. The pcache module allocates more space and keeps working
#       in memory if this occurs.
#
#   tkt-2409-2.*: Cause a cache-spill while updating the change-counter
#       during a database COMMIT. Verify that the transaction is not
#       rolled back and SQLITE_BUSY is returned.
#
#   tkt-2409-3.*: Similar to 2409-1.*, but using many INSERT statements
#       within a transaction instead of just one.
#
#       UPDATE: Again, pcache now just keeps working in main memory.
#
#   tkt-2409-4.*: Similar to 2409-1.*, but rig it so that the
#       INSERT statement starts a statement transaction. Verify that
#       SQLITE_BUSY is returned and the transaction is not rolled back.
#
#       UPDATE: This time, SQLITE_BUSY is not returned. pcache just uses
#       more malloc()'d memory.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !pager_pragmas {
  finish_test
  return
}

sqlite3_extended_result_codes $::DB 1

# Aquire a read-lock on the database using handle [db2].
#
proc read_lock_db {} {
  if {$::STMT eq ""} {
    set ::STMT [sqlite3_prepare db2 {SELECT rowid FROM sqlite_master} -1 TAIL]
    set rc [sqlite3_step $::STMT]
    if {$rc eq "SQLITE_ERROR"} {
      unread_lock_db
      read_lock_db
    }
  }
}

# Release any read-lock obtained using [read_lock_db]
#
proc unread_lock_db {} {
  if {$::STMT ne ""} {
    sqlite3_finalize $::STMT
    set ::STMT ""
  }
}

# Open the db handle used by [read_lock_db].
#
sqlite3 db2 test.db
set ::STMT ""

do_test tkt2409-1.1 {
  execsql {
    PRAGMA cache_size=10;
    CREATE TABLE t1(x TEXT UNIQUE NOT NULL, y BLOB);
  }
  read_lock_db
  set ::zShort [string repeat 0123456789 1]
  set ::zLong  [string repeat 0123456789 1500]
  catchsql {
    BEGIN;
    INSERT INTO t1 VALUES($::zShort, $::zLong);
  }
} {0 {}}

do_test tkt2409-1.2 {
  sqlite3_errcode $::DB
} {SQLITE_OK}

# Check the integrity of the cache.
#
integrity_check tkt2409-1.3

# Check that the transaction was rolled back. Because the INSERT
# statement in which the "I/O error" occured did not open a statement
# transaction, SQLite had no choice but to roll back the transaction.
#
do_test tkt2409-1.4 {
  unread_lock_db
  catchsql { ROLLBACK }
} {0 {}}

set ::zShort [string repeat 0123456789 1]
set ::zLong  [string repeat 0123456789 1500]
set ::rc 1
for {set iCache 10} {$::rc} {incr iCache} {
  execsql "PRAGMA cache_size = $iCache"
  do_test tkt2409-2.1.$iCache {
    read_lock_db
    set ::rc [catch {
      execsql {
        BEGIN;
        INSERT INTO t1 VALUES($::zShort, $::zLong);
      }
    } msg]
    expr {($::rc == 1 && $msg eq "disk I/O error") || $::rc == 0}
  } {1}
}

do_test tkt2409-2.2 {
  catchsql {
    ROLLBACK;
    BEGIN;
    INSERT INTO t1 VALUES($::zShort, $::zLong);
    COMMIT;
  }
} {1 {database is locked}}

do_test tkt2409-2.3 {
  unread_lock_db
  catchsql {
    COMMIT;
  }
} {0 {}}


do_test tkt2409-3.1 {
  db close
  set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
  sqlite3_extended_result_codes $::DB 1
  execsql {
    PRAGMA cache_size=10;
    DELETE FROM t1;
  }
  read_lock_db
  set ::zShort [string repeat 0123456789 1]
  set ::zLong  [string repeat 0123456789 1500]
  catchsql {
    BEGIN;
    INSERT INTO t1 SELECT $::zShort, $::zLong;
  }
} {0 {}}

do_test tkt2409-3.2 {
  sqlite3_errcode $::DB
} {SQLITE_OK}

# Check the integrity of the cache.
#
integrity_check tkt2409-3.3

# Check that the transaction was rolled back. Because the INSERT
# statement in which the "I/O error" occured did not open a statement
# transaction, SQLite had no choice but to roll back the transaction.
#
do_test tkt2409-3.4 {
  unread_lock_db
  catchsql { ROLLBACK }
} {0 {}}
integrity_check tkt2409-3.5

expr {srand(1)}
do_test tkt2409-4.1 {
  execsql {
    PRAGMA cache_size=20;
    DROP TABLE t1;
    CREATE TABLE t1 (x TEXT UNIQUE NOT NULL);
  }

  unset -nocomplain t1
  array unset t1
  set t1(0) 1
  set sql ""
  for {set i 0} {$i<5000} {incr i} {
    set r 0
    while {[info exists t1($r)]} {
      set r [expr {int(rand()*1000000000)}]
    }
    set t1($r) 1
    append sql "INSERT INTO t1 VALUES('some-text-$r');"
  }

  read_lock_db
  execsql BEGIN
  catchsql $sql
} {0 {}}

do_test tkt2409-4.2 {
  sqlite3_errcode $::DB
} {SQLITE_OK}

# Check the integrity of the cache.
#
integrity_check tkt2409-4.3

do_test tkt2409-4.4 {
  catchsql { ROLLBACK }
} {0 {}}
integrity_check tkt2409-4.5

unread_lock_db
db2 close
unset -nocomplain t1
finish_test

Added test/tkt2450.test.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 2007 June 24
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2450 has been fixed.
#
# $Id: tkt2450.test,v 1.1 2007/06/24 06:32:18 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt2450-1 {
  execsql {
    CREATE TABLE "t a" ("""cb""");
    INSERT INTO "t a" ("""cb""") VALUES (1);
    SELECT """cb""" FROM "t a";
  }
} {1}

do_test tkt2450-2 {
  execsql {
    SELECT * FROM "t a";
  }
} {1}

do_test tkt2450-3 {
  execsql {
    SELECT "t a".* FROM "t a";
  }
} {1}

do_test tkt2450-3 {
  execsql {
    CREATE TABLE t1(a);
    INSERT INTO t1 VALUES(2);
    SELECT * FROM "t a", t1;
  }
} {1 2}

finish_test

Added test/tkt2565.test.

























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# 2009 January 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This script attempts to reproduce the circumstances of ticket #2565.
#
# More specifically, this script attempts to generate rollback journals
# that contain headers with nRec==0 that are followed by additional
# valid headers.
#
# $Id: tkt2565.test,v 1.2 2009/04/09 01:23:49 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Use the alternative pcache and rig it to call pagerStress()
# very frequently.
#
db close
sqlite3_shutdown
sqlite3_config_alt_pcache 1 100 0 1

# Open two database connections to database "test.db".
#
proc reopen_database {} {
  catch {db close}
  sqlite3 db test.db
  db cache size 0
  execsql {
    pragma page_size=512;
    pragma auto_vacuum=2;
    pragma cache_size=16;
  }
}

# Open two database connections and create a single table in the db.
#
do_test tkt2565-1.0 {
  reopen_database
  execsql { CREATE TABLE A(Id INTEGER, Name TEXT) }
} {}

for {set iFail 1} {$iFail<200} {incr iFail} {
  reopen_database
  execsql { pragma locking_mode=exclusive }
  set nRow [db one {SELECT count(*) FROM a}]
  
  # Dirty (at least) one of the pages in the cache.
  do_test tkt2565-1.$iFail.1 {
    execsql {
      BEGIN EXCLUSIVE;
      INSERT INTO a VALUES(1, 'ABCDEFGHIJKLMNOP');
    }
  } {}
  
  # Now try to commit the transaction. Cause an IO error to occur
  # within this operation, which moves the pager into the error state.
  #
  set ::sqlite_io_error_persist 1
  set ::sqlite_io_error_pending $iFail
  do_test tkt2565-1.$iFail.2 {
    set rc [catchsql {COMMIT}]
    list
  } {}
  set ::sqlite_io_error_persist 0
  set ::sqlite_io_error_pending 0
  if {!$::sqlite_io_error_hit} break
  set ::sqlite_io_error_hit 0
}

# Make sure this test script doesn't leave any files open.
#
do_test tkt2565-1.X {
  catch { db close }
  set sqlite_open_file_count
} 0

# Restore the pcache configuration for subsequent tests.
#
sqlite3_shutdown
sqlite3_config_alt_pcache 0
sqlite3_initialize
autoinstall_test_functions

finish_test

Added test/tkt2640.test.

























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# 2007 Sep 12
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2640 has been fixed.
#
# $Id: tkt2640.test,v 1.3 2008/08/04 03:51:24 danielk1977 Exp $
#

# The problem in ticket #2640 was that the query optimizer was 
# not recognizing all uses of tables within subqueries in the
# WHERE clause.  If the subquery contained a compound SELECT,
# then tables that were used by terms of the compound other than
# the last term would not be recognized as dependencies.
# So if one of the SELECT statements within a compound made
# use of a table that occurs later in a join, the query
# optimizer would not recognize this and would try to evaluate
# the subquery too early, before that tables value had been
# established.

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery||!compound {
  finish_test
  return
}

do_test tkt2640-1.1 {
  execsql {
    CREATE TABLE persons(person_id, name);
    INSERT INTO persons VALUES(1,'fred');
    INSERT INTO persons VALUES(2,'barney');
    INSERT INTO persons VALUES(3,'wilma');
    INSERT INTO persons VALUES(4,'pebbles');
    INSERT INTO persons VALUES(5,'bambam');
    CREATE TABLE directors(person_id);
    INSERT INTO directors VALUES(5);
    INSERT INTO directors VALUES(3);
    CREATE TABLE writers(person_id);
    INSERT INTO writers VALUES(2);
    INSERT INTO writers VALUES(3);
    INSERT INTO writers VALUES(4);
    SELECT DISTINCT p.name
      FROM persons p, directors d
     WHERE d.person_id=p.person_id
       AND NOT EXISTS (
             SELECT person_id FROM directors d1 WHERE d1.person_id=p.person_id
             EXCEPT
             SELECT person_id FROM writers w
           );
  }
} {wilma}
do_test tkt2640-1.2 {
  execsql {
    SELECT DISTINCT p.name
      FROM persons p CROSS JOIN directors d
     WHERE d.person_id=p.person_id
       AND NOT EXISTS (
             SELECT person_id FROM directors d1 WHERE d1.person_id=p.person_id
             EXCEPT
             SELECT person_id FROM writers w
           );
  }
} {wilma}
do_test tkt2640-1.3 {
  execsql {
    SELECT DISTINCT p.name
      FROM directors d CROSS JOIN persons p
     WHERE d.person_id=p.person_id
       AND NOT EXISTS (
             SELECT person_id FROM directors d1 WHERE d1.person_id=p.person_id
             EXCEPT
             SELECT person_id FROM writers w
           );
  }
} {wilma}
do_test tkt2640-1.4 {
  execsql {
    SELECT DISTINCT p.name
      FROM persons p, directors d
     WHERE d.person_id=p.person_id
       AND NOT EXISTS (
             SELECT person_id FROM directors d1 WHERE d1.person_id=d.person_id
             EXCEPT
             SELECT person_id FROM writers w
           );
  }
} {wilma}
do_test tkt2640-1.5 {
  execsql {
    SELECT DISTINCT p.name
      FROM persons p CROSS JOIN directors d
     WHERE d.person_id=p.person_id
       AND NOT EXISTS (
             SELECT person_id FROM directors d1 WHERE d1.person_id=d.person_id
             EXCEPT
             SELECT person_id FROM writers w
           );
  }
} {wilma}
do_test tkt2640-1.6 {
  execsql {
    SELECT DISTINCT p.name
      FROM directors d CROSS JOIN persons p
     WHERE d.person_id=p.person_id
       AND NOT EXISTS (
             SELECT person_id FROM directors d1 WHERE d1.person_id=d.person_id
             EXCEPT
             SELECT person_id FROM writers w
           );
  }
} {wilma}



finish_test

Added test/tkt2643.test.















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 2007 Sep 12
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2643 has been fixed.
#
# $Id: tkt2643.test,v 1.1 2007/09/13 17:54:41 drh Exp $
#

# The problem in ticket #2643 has to do with the query optimizer
# making bad assumptions about index cost when data from ANALYZE
# is available.

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt2643-1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE, c);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(2,3,4);
    ANALYZE;
  }
  db close
  sqlite3 db test.db
  execsql {
    CREATE INDEX i1 ON t1(c);
    SELECT count(*) FROM t1 WHERE c IS NOT NULL
  }
} {2}

finish_test

Added test/tkt2686.test.



































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 2007 Oct 3
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2686 has been fixed.
#
# $Id: tkt2686.test,v 1.3 2008/02/02 02:48:52 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

db eval {
  PRAGMA page_size=1024;
  PRAGMA max_page_count=50;
  PRAGMA auto_vacuum=0;
  CREATE TABLE filler (fill);
}
for {set i 1} {$i<2000} {incr i} {
  do_test tkt2686-$i.1 {
    db eval BEGIN
    set rc [catch {
      while 1 {
        db eval {INSERT INTO filler (fill) VALUES (randstr(1000, 10000)) }
      }
    } msg]
    lappend rc $msg
  } {1 {database or disk is full}}
  do_test tkt2686-$i.2 {
    execsql {
      DELETE FROM filler 
       WHERE rowid <= (SELECT MAX(rowid) FROM filler LIMIT 20)
    }
  } {}
  integrity_check tkt2686-$i.3
  catch {db eval COMMIT}
}

db close
file delete -force test.db test.db-journal
sqlite3 db test.db

db eval {
  PRAGMA page_size=1024;
  PRAGMA max_page_count=50;
  PRAGMA auto_vacuum=1;
  CREATE TABLE filler (fill);
}
for {set i 10000} {$i<12000} {incr i} {
  do_test tkt2686-$i.1 {
    db eval BEGIN
    set rc [catch {
      while 1 {
        db eval {INSERT INTO filler (fill) VALUES (randstr(1000, 10000)) }
      }
    } msg]
    lappend rc $msg
  } {1 {database or disk is full}}
  do_test tkt2686-$i.2 {
    execsql {
      DELETE FROM filler 
       WHERE rowid <= (SELECT MAX(rowid) FROM filler LIMIT 20)
    }
  } {}
  integrity_check tkt2686-$i.3
  catch {db eval COMMIT}
}

finish_test

Added test/tkt2767.test.





















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 2007 Oct 3
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2767 has been fixed.
# Ticket #2767 is for a VDBE stack overflow on BEFORE
# triggers that run RAISE(IGNORE).
#
# $Id: tkt2767.test,v 1.3 2009/04/07 14:14:23 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !trigger { finish_test ; return }

do_test tkt2767-1.1 {
  execsql {
    -- Construct a table with many rows of data
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 SELECT x+2 FROM t1;
    INSERT INTO t1 SELECT x+4 FROM t1;
    INSERT INTO t1 SELECT x+8 FROM t1;
    INSERT INTO t1 SELECT x+16 FROM t1;

    -- BEFORE triggers that invoke raise(ignore).  The effect of
    -- these triggers should be to make INSERTs, UPDATEs, and DELETEs
    -- into no-ops.
    CREATE TRIGGER r1 BEFORE UPDATE ON t1 BEGIN
      SELECT raise(ignore);
    END;
    CREATE TRIGGER r2 BEFORE DELETE ON t1 BEGIN
      SELECT raise(ignore);
    END;
    CREATE TRIGGER r3 BEFORE INSERT ON t1 BEGIN
      SELECT raise(ignore);
    END;

    -- Verify the table content
    SELECT count(*), sum(x) FROM t1;
  }
} {32 528}

# Try to delete all elements of the table.  This will invoke the
# DELETE trigger 32 times, which should overflow the VDBE stack if
# the problem of #2767 is not fixed.  If the problem is fixed, all
# the deletes should be no-ops so the table should remain unchanged.
#
do_test tkt2767-1.2 {
  execsql {
    DELETE FROM t1 WHERE x>0;
    SELECT count(*), sum(x) FROM t1;
  }
} {32 528}

# Try to update all elements of the table.  This will invoke the
# UPDATE trigger 32 times, which should overflow the VDBE stack if
# the problem of #2767 is not fixed.  If the problem is fixed, all
# the updates should be no-ops so the table should remain unchanged.
#
do_test tkt2767-1.3 {
  execsql {
    UPDATE t1 SET x=x+1;
    SELECT count(*), sum(x) FROM t1;
  }
} {32 528}

# Invoke the insert trigger.  The insert trigger was working
# even prior to the fix of #2767.  But it seems good to go ahead
# and verify that it works.
#
do_test tkt2767-1.4 {
  execsql {
    INSERT INTO t1 SELECT x+32 FROM t1;
    SELECT count(*), sum(x) FROM t1;
  }
} {32 528}



finish_test

Added test/tkt2817.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2007 December 02 
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# Specifically, it tests that bug 2817 is fixed.
#
# $Id: tkt2817.test,v 1.2 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt2817-1.0 {
  execsql {
    CREATE TEMP TABLE tbl(a, b, c);
    -- INSERT INTO tbl VALUES(1, 'abc', 'def');
    -- INSERT INTO tbl VALUES(2, 'ghi', 'jkl');
  }
} {}
do_test tkt2817-1.1 {
  execsql {
    CREATE TABLE main.tbl(a, b, c); 
    CREATE INDEX main.tbli ON tbl(a, b, c);
    INSERT INTO main.tbl SELECT a, b, c FROM temp.tbl;
  }
} {}

# When bug #2817 existed, this test was failing.
#
integrity_check tkt2817-1.2

# So was this one.
#
db close
sqlite3 db test.db
integrity_check tkt2817-1.3


# These tests - tkt2817-2.* - are the same as the previous block, except
# for the fact that the temp-table and the main table do not share the
# same name. #2817 did not cause a problem with these tests.
#
db close
file delete -force test.db
sqlite3 db test.db
do_test tkt2817-2.0 {
  execsql {
    CREATE TEMP TABLE tmp(a, b, c);
    INSERT INTO tmp VALUES(1, 'abc', 'def');
    INSERT INTO tmp VALUES(2, 'ghi', 'jkl');
  }
} {}
do_test tkt2817-2.1 {
  execsql {
    CREATE TABLE main.tbl(a, b, c); 
    CREATE INDEX main.tbli ON tbl(a, b, c);
    INSERT INTO main.tbl SELECT a, b, c FROM temp.tmp;
  }
} {}
integrity_check tkt2817-2.2
db close
sqlite3 db test.db
integrity_check tkt2817-2.3

finish_test

Added test/tkt2820.test.





























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# 2007 Dec 4
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2820 has been fixed.
# Ticket #2820 observes that a DROP TABLE statement that
# occurs while a query is in process will fail with a
# "database is locked" error, but the entry in the sqlite_master
# table will still be removed.  This is incorrect.  The
# entry in the sqlite_master table should persist when 
# the DROP fails due to an error.
#
# $Id: tkt2820.test,v 1.1 2007/12/04 16:54:53 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc test_schema_change {testid init ddl res} {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  execsql $init
  do_test tkt2820-$testid.1 {
    set STMT [sqlite3_prepare db {SELECT * FROM sqlite_master} -1 DUMMY]
    sqlite3_step $STMT
  } {SQLITE_ROW}
#if {$testid==3} {execsql {PRAGMA vdbe_trace=ON}}
  do_test tkt2820-$testid.2 "catchsql [list $ddl]" \
       {1 {database table is locked}}
  do_test tkt2820-$testid.3 {
    sqlite3_finalize $STMT
    execsql {SELECT name FROM sqlite_master ORDER BY 1}
  } $res
  integrity_check tkt2820-$testid.4
  db close
  sqlite3 db test.db
  integrity_check tkt2820-$testid.5
}

test_schema_change 1 {
  CREATE TABLE t1(a);
} {
  DROP TABLE t1
} {t1}
test_schema_change 2 {
  CREATE TABLE t1(a);
  CREATE TABLE t2(b);
} {
  DROP TABLE t2
} {t1 t2}
test_schema_change 3 {
  CREATE TABLE t1(a);
  CREATE INDEX i1 ON t1(a);
} {
  DROP INDEX i1
} {i1 t1}

# We further observe that prior to the fix associated with ticket #2820,
# no statement journal would be created on an SQL statement that was run
# while a second statement was active, as long as we are in autocommit
# mode.  This is incorrect.
#
do_test tkt2820-4.1 {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  db eval {
    CREATE TABLE t1(a INTEGER PRIMARY KEY);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
  }

  # The INSERT statement within the loop should fail on a
  # constraint violation on the second inserted row.  This
  # should cause the entire INSERT to rollback using a statement
  # journal.
  #
  db eval {SELECT name FROM sqlite_master} {
    catch {db eval {
      INSERT INTO t1 SELECT a+1 FROM t1 ORDER BY a DESC
    }}
  }
  db eval {SELECT a FROM t1 ORDER BY a}
} {1 2}

finish_test

Added test/tkt2822.test.

































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# 2007 Dec 4
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that the issues surrounding expressions in
# ORDER BY clauses on compound SELECT statements raised by ticket
# #2822 have been dealt with.
#
# $Id: tkt2822.test,v 1.6 2008/08/20 16:35:10 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound {
  finish_test
  return
}

# The ORDER BY matching algorithm is three steps:
# 
#   (1)  If the ORDER BY term is an integer constant i, then
#        sort by the i-th column of the result set.
# 
#   (2)  If the ORDER BY term is an identifier (not x.y or x.y.z
#        but simply x) then look for a column alias with the same
#        name.  If found, then sort by that column.
# 
#   (3)  Evaluate the term as an expression and sort by the
#        value of the expression.
# 
# For a compound SELECT the rules are modified slightly.
# In the third rule, the expression must exactly match one
# of the result columns.  The sequences of three rules is
# attempted first on the left-most SELECT.  If that doesn't
# work, we move to the right, one by one.
#
# Rule (3) is not in standard SQL - it is an SQLite extension,
# though one copied from PostgreSQL.  The rule for compound
# queries where a search is made of SELECTs to the right
# if the left-most SELECT does not match is not a part of
# standard SQL either.  This extension is unique to SQLite
# as far as we know.
#
# Rule (2) was added by the changes ticket #2822.  Prior to
# that changes, SQLite did not support rule (2), making it
# technically in violation of standard SQL semantics.  
# No body noticed because rule (3) has the same effect as
# rule (2) except in some obscure cases.
#


# Test plan:
#
#   tkt2822-1.* - Simple identifier as ORDER BY expression.
#   tkt2822-2.* - More complex ORDER BY expressions.

do_test tkt2822-0.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(a, b, c);

    INSERT INTO t1 VALUES(1, 3, 9);
    INSERT INTO t1 VALUES(3, 9, 27);
    INSERT INTO t1 VALUES(5, 15, 45);

    INSERT INTO t2 VALUES(2, 6, 18);
    INSERT INTO t2 VALUES(4, 12, 36);
    INSERT INTO t2 VALUES(6, 18, 54);
  }
} {}

# Test the "ORDER BY <integer>" syntax.
#
do_test tkt2822-1.1 {
  execsql {
    SELECT a, b, c FROM t1 UNION ALL SELECT a, b, c FROM t2 ORDER BY 1;
  }
} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54}
do_test tkt2822-1.2 {
  execsql {
    SELECT a, CAST (b AS TEXT), c FROM t1 
      UNION ALL 
    SELECT a, b, c FROM t2 
      ORDER BY 2;
  }
} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27}

# Test the "ORDER BY <identifier>" syntax.
#
do_test tkt2822-2.1 {
  execsql {
    SELECT a, b, c FROM t1 UNION ALL SELECT a, b, c FROM t2 ORDER BY a;
  }
} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54}

do_test tkt2822-2.2 {
  execsql {
    SELECT a, CAST (b AS TEXT) AS x, c FROM t1 
      UNION ALL 
    SELECT a, b, c FROM t2 
      ORDER BY x;
  }
} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27}
do_test tkt2822-2.3 {
  execsql {
    SELECT t1.a, b, c FROM t1 UNION ALL SELECT t2.a, b, c FROM t2 ORDER BY a;
  }
} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54}

# Test the "ORDER BY <expression>" syntax.
#
do_test tkt2822-3.1 {
  execsql {
    SELECT a, CAST (b AS TEXT) AS x, c FROM t1 
      UNION ALL 
    SELECT a, b, c FROM t2 
      ORDER BY CAST (b AS TEXT);
  }
} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27}
do_test tkt2822-3.2 {
  execsql {
    SELECT t1.a, b, c FROM t1 UNION ALL SELECT t2.a, b, c FROM t2 ORDER BY t1.a;
  }
} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54}

# Test that if a match cannot be found in the leftmost SELECT, an
# attempt is made to find a match in subsequent SELECT statements.
#
do_test tkt2822-3.3 {
  execsql {
    SELECT a, b, c FROM t1 UNION ALL SELECT a AS x, b, c FROM t2 ORDER BY x;
  }
} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54}
do_test tkt2822-3.4 {
  # But the leftmost SELECT takes precedence.
  execsql {
    SELECT a AS b, CAST (b AS TEXT) AS a, c FROM t1 
      UNION ALL 
    SELECT a, b, c FROM t2 
      ORDER BY a;
  }
} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27}
do_test tkt2822-3.5 {
  execsql {
    SELECT a, b, c FROM t2 
      UNION ALL 
    SELECT a AS b, CAST (b AS TEXT) AS a, c FROM t1 
      ORDER BY a;
  }
} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54}

# Test some error conditions (ORDER BY clauses that match no column).
#
do_test tkt2822-4.1 {
  catchsql {
    SELECT a, b, c FROM t1 UNION ALL SELECT a, b, c FROM t2 ORDER BY x
  }
} {1 {1st ORDER BY term does not match any column in the result set}}
do_test tkt2822-4.2 {
  catchsql {
    SELECT a, CAST (b AS TEXT) AS x, c FROM t1 
      UNION ALL 
    SELECT a, b, c FROM t2 
      ORDER BY CAST (b AS INTEGER);
  }
} {1 {1st ORDER BY term does not match any column in the result set}}

# Tests for rule (2).
#
# The "ORDER BY b" should match the column alias (rule 2), not the
# the t3.b value (rule 3).  
#
do_test tkt2822-5.1 {
  execsql {
    CREATE TABLE t3(a,b);
    INSERT INTO t3 VALUES(1,8);
    INSERT INTO t3 VALUES(9,2);

    SELECT a AS b FROM t3 ORDER BY b;
  }
} {1 9}
do_test tkt2822-5.2 {
  # Case does not matter.  b should match B
  execsql {
    SELECT a AS b FROM t3 ORDER BY B;
  }
} {1 9}
do_test tkt2822-5.3 {
  # Quoting should not matter
  execsql {
    SELECT a AS 'b' FROM t3 ORDER BY "B";
  }
} {1 9}
do_test tkt2822-5.4 {
  # Quoting should not matter
  execsql {
    SELECT a AS "b" FROM t3 ORDER BY [B];
  }
} {1 9}

# In "ORDER BY +b" the term is now an expression rather than
# a label.  It therefore matches by rule (3) instead of rule (2).
# 
do_test tkt2822-5.5 {
  execsql {
    SELECT a AS b FROM t3 ORDER BY +b;
  }
} {9 1}

# Tests for rule 2 in compound queries
#
do_test tkt2822-6.1 {
  execsql {
    CREATE TABLE t6a(p,q);
    INSERT INTO t6a VALUES(1,8);
    INSERT INTO t6a VALUES(9,2);
    CREATE TABLE t6b(x,y);
    INSERT INTO t6b VALUES(1,7);
    INSERT INTO t6b VALUES(7,2);

    SELECT p, q FROM t6a UNION ALL SELECT x, y FROM t6b ORDER BY 1, 2
  }
} {1 7 1 8 7 2 9 2}
do_test tkt2822-6.2 {
  execsql {
    SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b
    ORDER BY PX, YX
  }
} {1 7 1 8 7 2 9 2}
do_test tkt2822-6.3 {
  execsql {
    SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b
    ORDER BY XX, QX
  }
} {1 7 1 8 7 2 9 2}
do_test tkt2822-6.4 {
  execsql {
    SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b
    ORDER BY QX, XX
  }
} {7 2 9 2 1 7 1 8}
do_test tkt2822-6.5 {
  execsql {
    SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b
    ORDER BY t6b.x, QX
  }
} {1 7 1 8 7 2 9 2}
do_test tkt2822-6.6 {
  execsql {
    SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b
    ORDER BY t6a.q, XX
  }
} {7 2 9 2 1 7 1 8}

# More error message tests.  This is really more of a test of the
# %r ordinal value formatting capablity added to sqlite3_snprintf()
# by ticket #2822.
#
do_test tkt2822-7.1 {
  execsql {
    CREATE TABLE t7(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,
                    a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25);
  }
  catchsql {
    SELECT * FROM t7 ORDER BY 0;
  }
} {1 {1st ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.2 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 0;
  }
} {1 {2nd ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.3 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 0;
  }
} {1 {3rd ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.4 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 0;
  }
} {1 {4th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.9 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 0;
  }
} {1 {9th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.10 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 0;
  }
} {1 {10th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.11 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0;
  }
} {1 {11th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.12 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 0;
  }
} {1 {12th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.13 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 0;
  }
} {1 {13th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.20 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                             11,12,13,14,15,16,17,18,19, 0
  }
} {1 {20th ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.21 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                             11,12,13,14,15,16,17,18,19, 20, 0
  }
} {1 {21st ORDER BY term out of range - should be between 1 and 25}}
do_test tkt2822-7.22 {
  catchsql {
    SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                             11,12,13,14,15,16,17,18,19, 20, 21, 0
  }
} {1 {22nd ORDER BY term out of range - should be between 1 and 25}}


finish_test

Added test/tkt2832.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2007 Dec 12
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2832 has been fixed.
#
# $Id: tkt2832.test,v 1.5 2009/04/07 14:14:23 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !trigger { finish_test ; return }

do_test tkt2832-1.1 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(3);
  }
} {}
do_test tkt2832-1.2 {
  execsql {
    UPDATE OR REPLACE t1 SET a = 1;
    SELECT * FROM t1;
  }
} {1}

do_test tkt2832-2.1 {
  execsql {
    CREATE TABLE t2(a, b);
    CREATE TRIGGER t2_t AFTER UPDATE ON t2 BEGIN
      DELETE FROM t2 WHERE a = new.a + 1;
    END;
    INSERT INTO t2 VALUES(1, 2);
    INSERT INTO t2 VALUES(2, 3);
  }
} {}
do_test tkt2832-2.2 {
  execsql { 
    UPDATE t2 SET b = 5 
  }
} {}

do_test tkt2832-3.1 {
  execsql {
    CREATE TABLE t3(a, b);
    CREATE TRIGGER t3_t AFTER DELETE ON t3 BEGIN
      DELETE FROM t3 WHERE a = old.a + 1;
    END;
    INSERT INTO t3 VALUES(1, 2);
    INSERT INTO t3 VALUES(2, 3);
  }
} {}
do_test tkt2832-3.2 {
  execsql { DELETE FROM t3 WHERE 1 }
} {}

finish_test

Added test/tkt2854.test.











































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# 2007 December 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt2854.test,v 1.4 2009/03/16 13:19:36 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
db close

ifcapable !shared_cache {
  finish_test
  return
}

set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

# Open 3 database connections. Connection "db" and "db2" share a cache.
# Connection "db3" has its own cache.
#
do_test tkt2854-1.1 {
  sqlite3 db test.db
  sqlite3 db2 test.db

  # This is taken from shared.test.  The Windows VFS expands 
  # ./test.db (and test.db) to be the same thing so the path
  # matches and they share a cache.  By changing the case 
  # for Windows platform, we get around this and get a separate
  # connection.
  if {$::tcl_platform(platform)=="unix"} {
    sqlite3 db3 ./test.db
  } else {
    sqlite3 db3 TEST.DB
  }

  db eval {
    CREATE TABLE abc(a, b, c);
  }
} {}

# Check that an exclusive lock cannot be obtained if some other 
# shared-cache connection has a read-lock on a table.
#
do_test tkt2854-1.2 {
  execsql { 
    BEGIN;
    SELECT * FROM abc;
  } db2
} {}
do_test tkt2854-1.3 {
  catchsql { BEGIN EXCLUSIVE } db
} {1 {database table is locked}}
do_test tkt2854-1.4 {
  execsql { SELECT * FROM abc } db3
} {}
do_test tkt2854-1.5 {
  catchsql { INSERT INTO abc VALUES(1, 2, 3) } db3
} {1 {database is locked}}
do_test tkt2854-1.6 {
  execsql { COMMIT } db2
} {}

# Check that an exclusive lock prevents other shared-cache users from
# starting a transaction.
#
do_test tkt2854-1.7 {
  set ::DB2 [sqlite3_connection_pointer db2]
  set ::STMT1 [sqlite3_prepare $DB2 "SELECT * FROM abc" -1 TAIL]
  set ::STMT2 [sqlite3_prepare $DB2 "BEGIN EXCLUSIVE" -1 TAIL]
  set ::STMT3 [sqlite3_prepare $DB2 "BEGIN IMMEDIATE" -1 TAIL]
  set ::STMT4 [sqlite3_prepare $DB2 "BEGIN" -1 TAIL]
  set ::STMT5 [sqlite3_prepare $DB2 "COMMIT" -1 TAIL]
  execsql { BEGIN EXCLUSIVE } db
} {}
do_test tkt2854-1.8 {
  catchsql { BEGIN EXCLUSIVE } db2
} {1 {database schema is locked: main}}
do_test tkt2854-1.9 {
  catchsql { BEGIN IMMEDIATE } db2
} {1 {database schema is locked: main}}
do_test tkt2854-1.10 {
  # This fails because the schema of main cannot be verified.
  catchsql { BEGIN } db2
} {1 {database schema is locked: main}}

# Check that an exclusive lock prevents other shared-cache users from
# reading the database. Use stored statements so that the error occurs
# at the b-tree level, not the schema level.
#
do_test tkt2854-1.11 {
  list [sqlite3_step $::STMT1] [sqlite3_finalize $::STMT1]
} {SQLITE_ERROR SQLITE_LOCKED}
do_test tkt2854-1.12 {
  list [sqlite3_step $::STMT2] [sqlite3_finalize $::STMT2]
} {SQLITE_ERROR SQLITE_LOCKED}
do_test tkt2854-1.13 {
  list [sqlite3_step $::STMT3] [sqlite3_finalize $::STMT3]
} {SQLITE_ERROR SQLITE_LOCKED}
do_test tkt2854-1.14 {
  # A regular "BEGIN" doesn't touch any databases. So it succeeds.
  list [sqlite3_step $::STMT4] [sqlite3_finalize $::STMT4]
} {SQLITE_DONE SQLITE_OK}
do_test tkt2854-1.15 {
  # As does a COMMIT.
  list [sqlite3_step $::STMT5] [sqlite3_finalize $::STMT5]
} {SQLITE_DONE SQLITE_OK}

# Try to read the database using connection "db3" (which does not share
# a cache with "db"). The database should be locked.
do_test tkt2854-1.16 {
  catchsql { SELECT * FROM abc } db3
} {1 {database is locked}}
do_test tkt2854-1.17 {
  execsql { COMMIT } db
} {}
do_test tkt2854-1.18 {
  execsql { SELECT * FROM abc } db2
} {}

# Check that if an attempt to obtain an exclusive lock fails because an
# attached db cannot be locked, the internal exclusive flag used by
# shared-cache users is correctly cleared.
do_test tkt2854-1.19 {
  file delete -force test2.db test2.db-journal
  sqlite3 db4 test2.db
  execsql { CREATE TABLE def(d, e, f) } db4
  execsql { ATTACH 'test2.db' AS aux } db
} {}
do_test tkt2854-1.20 {
  execsql {BEGIN IMMEDIATE} db4
  catchsql {BEGIN EXCLUSIVE} db
} {1 {database table is locked}}
do_test tkt2854-1.21 {
  execsql {SELECT * FROM abc} db2
} {}

db close
db2 close
db3 close
db4 close
sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/tkt2920.test.





























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 2008 Feb 1
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2920 is fixed.
#
# $Id: tkt2920.test,v 1.1 2008/02/02 02:48:52 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create a database file that is full.
#
do_test tkt2920-1.1 {
  db eval {
    PRAGMA page_size=1024;
    PRAGMA max_page_count=40;
    PRAGMA auto_vacuum=0;
    CREATE TABLE filler (fill);
  }
  file size test.db
} {2048}
do_test tkt2920-1.2 {
  db eval BEGIN
  for {set i 0} {$i<34} {incr i} {
    db eval {INSERT INTO filler VALUES(randomblob(1024))}
  }
  db eval COMMIT
}  {}

# Try to add a single new page to the full database.  We get
# a disk full error.  But this does not corrupt the database.
#
do_test tkt2920-1.3 {
  db eval BEGIN
  catchsql {
     INSERT INTO filler VALUES(randomblob(1024))
  }
} {1 {database or disk is full}}
integrity_check tkt2920-1.4

# Increase the maximum size of the database file by 1 page,
# but then try to add a two-page record.  This also fails.
#
do_test tkt2920-1.5 {
  db eval {PRAGMA max_page_count=41}
  catchsql {
     INSERT INTO filler VALUES(randomblob(2048))
  }
} {1 {database or disk is full}}
integrity_check tkt2920-1.6

# Increase the maximum size of the database by one more page.
# This time the insert works.
#
do_test tkt2920-1.7 {
  db eval {PRAGMA max_page_count=42}
  catchsql {
     INSERT INTO filler VALUES(randomblob(2048))
  }
} {0 {}}
integrity_check tkt2920-1.8

# The previous errors cancelled the transaction.
#
do_test tkt2920-1.9 {
  catchsql {COMMIT}
} {1 {cannot commit - no transaction is active}}

finish_test

Added test/tkt2927.test.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# 2008 Feb 6
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file is to test that ticket #2927 is fixed.
#
# $Id: tkt2927.test,v 1.4 2008/08/04 03:51:24 danielk1977 Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !compound {
  finish_test
  return
}

# Create a database.
#
do_test tkt2927-1.1 {
  db eval {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1,11);
    INSERT INTO t1 VALUES(2,22);
    INSERT INTO t1 VALUES(3,33);
    INSERT INTO t1 VALUES(4,44);
    INSERT INTO t1 VALUES(5,55);
    SELECT * FROM t1;
  }
} {1 11 2 22 3 33 4 44 5 55}


do_test tkt2927-2.1 {
  db eval {
    SELECT a, b FROM t1
    UNION ALL
    SELECT a, b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.2 {
#set sqlite_addop_trace 1
  db eval {
    SELECT a, b FROM t1
    UNION ALL
    SELECT a, abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.3 {
  db eval {
    SELECT a, b FROM t1
    UNION ALL
    SELECT abs(a), b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.4 {
  db eval {
    SELECT a, b FROM t1
    UNION ALL
    SELECT abs(a), abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.5 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION ALL
    SELECT a, b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.6 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION ALL
    SELECT a, abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.7 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION ALL
    SELECT abs(a), b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.8 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION ALL
    SELECT abs(a), abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.9 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION ALL
    SELECT a, b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.10 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION ALL
    SELECT a, abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.11 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION ALL
    SELECT abs(a), b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.12 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION ALL
    SELECT abs(a), abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.13 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION ALL
    SELECT a, b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.14 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION ALL
    SELECT a, abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.15 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION ALL
    SELECT abs(a), b FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-2.16 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION ALL
    SELECT abs(a), abs(b) FROM t1
  }
} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55}


do_test tkt2927-3.1 {
  db eval {
    SELECT a, b FROM t1
    UNION 
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.2 {
  db eval {
    SELECT a, b FROM t1
    UNION 
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.3 {
  db eval {
    SELECT a, b FROM t1
    UNION 
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.4 {
  db eval {
    SELECT a, b FROM t1
    UNION 
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.5 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION 
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.6 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION 
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.7 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION 
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.8 {
  db eval {
    SELECT a, abs(b) FROM t1
    UNION 
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.9 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION 
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.10 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION 
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.11 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION 
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.12 {
  db eval {
    SELECT abs(a), b FROM t1
    UNION 
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.13 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION 
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.14 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION 
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.15 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION 
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-3.16 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    UNION 
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}


do_test tkt2927-4.1 {
  db eval {
    SELECT a+b, a-b, a, b FROM t1
    UNION ALL
    SELECT a+b, a-b, a, b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.2 {
  db eval {
    SELECT a+b, a-b, a, b FROM t1
    UNION ALL
    SELECT a+b, a-b, a, abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.3 {
  db eval {
    SELECT a+b, a-b, a, b FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.4 {
  db eval {
    SELECT a+b, a-b, a, b FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.5 {
  db eval {
    SELECT a+b, a-b, a, abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, a, b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.6 {
  db eval {
    SELECT a+b, a-b, a, abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, a, abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.7 {
  db eval {
    SELECT a+b, a-b, a, abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.8 {
  db eval {
    SELECT a+b, a-b, a, abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.9 {
  db eval {
    SELECT a+b, a-b, abs(a), b FROM t1
    UNION ALL
    SELECT a+b, a-b, a, b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.10 {
  db eval {
    SELECT a+b, a-b, abs(a), b FROM t1
    UNION ALL
    SELECT a+b, a-b, a, abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.11 {
  db eval {
    SELECT a+b, a-b, abs(a), b FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.12 {
  db eval {
    SELECT a+b, a-b, abs(a), b FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.13 {
  db eval {
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, a, b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.14 {
  db eval {
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, a, abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.15 {
  db eval {
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), b FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}
do_test tkt2927-4.16 {
  db eval {
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
    UNION ALL
    SELECT a+b, a-b, abs(a), abs(b) FROM t1
  }
} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55}


do_test tkt2927-5.1 {
  db eval {
    SELECT a, b FROM t1
    EXCEPT
    SELECT a, b FROM t1
  }
} {}
do_test tkt2927-5.2 {
  db eval {
    SELECT a, b FROM t1
    EXCEPT
    SELECT a, abs(b) FROM t1
  }
} {}
do_test tkt2927-5.3 {
  db eval {
    SELECT a, b FROM t1
    EXCEPT
    SELECT abs(a), b FROM t1
  }
} {}
do_test tkt2927-5.4 {
  db eval {
    SELECT a, b FROM t1
    EXCEPT
    SELECT abs(a), abs(b) FROM t1
  }
} {}
do_test tkt2927-5.5 {
  db eval {
    SELECT a, abs(b) FROM t1
    EXCEPT
    SELECT a, b FROM t1
  }
} {}
do_test tkt2927-5.6 {
  db eval {
    SELECT a, abs(b) FROM t1
    EXCEPT
    SELECT a, abs(b) FROM t1
  }
} {}
do_test tkt2927-5.7 {
  db eval {
    SELECT a, abs(b) FROM t1
    EXCEPT
    SELECT abs(a), b FROM t1
  }
} {}
do_test tkt2927-5.8 {
  db eval {
    SELECT a, abs(b) FROM t1
    EXCEPT
    SELECT abs(a), abs(b) FROM t1
  }
} {}
do_test tkt2927-5.9 {
  db eval {
    SELECT abs(a), b FROM t1
    EXCEPT
    SELECT a, b FROM t1
  }
} {}
do_test tkt2927-5.10 {
  db eval {
    SELECT abs(a), b FROM t1
    EXCEPT
    SELECT a, abs(b) FROM t1
  }
} {}
do_test tkt2927-5.11 {
  db eval {
    SELECT abs(a), b FROM t1
    EXCEPT
    SELECT abs(a), b FROM t1
  }
} {}
do_test tkt2927-5.12 {
  db eval {
    SELECT abs(a), b FROM t1
    EXCEPT
    SELECT abs(a), abs(b) FROM t1
  }
} {}
do_test tkt2927-5.13 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    EXCEPT
    SELECT a, b FROM t1
  }
} {}
do_test tkt2927-5.14 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    EXCEPT
    SELECT a, abs(b) FROM t1
  }
} {}
do_test tkt2927-5.15 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    EXCEPT
    SELECT abs(a), b FROM t1
  }
} {}
do_test tkt2927-5.16 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    EXCEPT
    SELECT abs(a), abs(b) FROM t1
  }
} {}


do_test tkt2927-6.1 {
  db eval {
    SELECT a, b FROM t1
    INTERSECT
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.2 {
  db eval {
    SELECT a, b FROM t1
    INTERSECT
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.3 {
  db eval {
    SELECT a, b FROM t1
    INTERSECT
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.4 {
  db eval {
    SELECT a, b FROM t1
    INTERSECT
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.5 {
  db eval {
    SELECT a, abs(b) FROM t1
    INTERSECT
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.6 {
  db eval {
    SELECT a, abs(b) FROM t1
    INTERSECT
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.7 {
  db eval {
    SELECT a, abs(b) FROM t1
    INTERSECT
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.8 {
  db eval {
    SELECT a, abs(b) FROM t1
    INTERSECT
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.9 {
  db eval {
    SELECT abs(a), b FROM t1
    INTERSECT
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.10 {
  db eval {
    SELECT abs(a), b FROM t1
    INTERSECT
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.11 {
  db eval {
    SELECT abs(a), b FROM t1
    INTERSECT
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.12 {
  db eval {
    SELECT abs(a), b FROM t1
    INTERSECT
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.13 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    INTERSECT
    SELECT a, b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.14 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    INTERSECT
    SELECT a, abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.15 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    INTERSECT
    SELECT abs(a), b FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}
do_test tkt2927-6.16 {
  db eval {
    SELECT abs(a), abs(b) FROM t1
    INTERSECT
    SELECT abs(a), abs(b) FROM t1
    ORDER BY 1
  }
} {1 11 2 22 3 33 4 44 5 55}

# Ticket #3092 is the same bug.  But another test case never hurts.
#
do_test tkt2927-7.1 {
  db eval {
    CREATE TABLE host (
     hostname text not null primary key,
     consoleHost text,
     consolePort text
    );
    INSERT INTO "host" VALUES('aald04','aalp03','4');
    INSERT INTO "host" VALUES('aald17','aalp01','1');
    CREATE VIEW consolemap1a as
      select hostname, consolehost, '/dev/cuaD0.' || (consoleport-1) consoleport
        from host where consolehost='aalp01';
    CREATE VIEW consolemap1b as
      select hostname hostname, consolehost consolehost, '/dev/cuaD' ||
             substr('01',1+((consoleport-1)/16),1) ||
             substr('0123456789abcdef',1+((consoleport-1)%16),1) consoleport
        from host where consolehost='aalp03';
    CREATE VIEW consolemap1 as
      select * from consolemap1a
      union
      select * from consolemap1b;
    SELECT * from consolemap1b;
  }
} {aald04 aalp03 /dev/cuaD03}
do_test tkt2927-7.2 {
  db eval {
    SELECT * FROM consolemap1
  }
} {aald04 aalp03 /dev/cuaD03 aald17 aalp01 /dev/cuaD0.0}

finish_test

Added test/tkt2942.test.





























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 2008 February 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #2942.  
#
# Queries of the form:
#
#     SELECT group_concat(x) FROM (SELECT * FROM table ORDER BY 1);
#
# The ORDER BY would be dropped by the query flattener.  This used
# to not matter because aggregate functions sum(), min(), max(), avg(),
# and so forth give the same result regardless of the order of inputs.
# But with the addition of the group_concat() function, suddenly the
# order does matter.
#
# $Id: tkt2942.test,v 1.1 2008/02/15 14:33:04 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

do_test tkt2942.1 {
  execsql {
    create table t1(num int);
    insert into t1 values (2);
    insert into t1 values (1);
    insert into t1 values (3);
    insert into t1 values (4);
    SELECT group_concat(num) FROM (SELECT num FROM t1 ORDER BY num DESC);
  }
} {4,3,2,1}
do_test tkt2942.2 {
  execsql {
    SELECT group_concat(num) FROM (SELECT num FROM t1 ORDER BY num);
  }
} {1,2,3,4}
do_test tkt2942.3 {
  execsql {
    SELECT group_concat(num) FROM (SELECT num FROM t1);
  }
} {2,1,3,4}
do_test tkt2942.4 {
  execsql {
    SELECT group_concat(num) FROM (SELECT num FROM t1 ORDER BY rowid DESC);
  }
} {4,3,1,2}


finish_test

Added test/tkt3080.test.



























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 2008 April 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3080
#
# Make sure that application-defined functions are able to recursively
# invoke SQL statements that create and drop virtual tables.
#
# $Id: tkt3080.test,v 1.2 2008/11/05 16:37:35 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3080.1 {
  db function execsql execsql
  db eval {
    SELECT execsql('CREATE TABLE t1(x)');
  }
  execsql {SELECT name FROM sqlite_master}
} {t1}
do_test tkt3080.2 {
  db eval {
    INSERT INTO t1 VALUES('CREATE TABLE t2(y);');
    SELECT execsql(x) FROM t1;
  }
  db eval {
    SELECT name FROM sqlite_master;
  }
} {t1 t2}
do_test tkt3080.3 {
  execsql {
    INSERT INTO t1 VALUES('CREATE TABLE t3(z); DROP TABLE t3;');
  }
  catchsql {
    SELECT execsql(x) FROM t1 WHERE rowid=2;
  }
} {1 {database table is locked}}
do_test tkt3080.4 {
  db eval {
    SELECT name FROM sqlite_master;
  }
} {t1 t2 t3}

ifcapable vtab {
  register_echo_module [sqlite3_connection_pointer db]
  do_test tkt3080.10 {
     set sql {
       CREATE VIRTUAL TABLE t4 USING echo(t2);
       INSERT INTO t4 VALUES(123);
       DROP TABLE t4;
     }
     execsql {
       DELETE FROM t1;
       INSERT INTO t1 VALUES($sql);
     }
     db eval {
       SELECT execsql(x) FROM t1
     }
     execsql {SELECT name FROM sqlite_master}
  } {t1 t2 t3}
  do_test tkt3080.11 {
     execsql {SELECT * FROM t2}
  } {123}
}
  


finish_test

Added test/tkt3093.test.













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# 2008 May 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3093
#
# Verify that a busy callback waiting on a reserved lock resolves
# once the lock clears.
#
# $Id: tkt3093.test,v 1.2 2008/05/02 14:23:55 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Set up a test database
#
do_test tkt3093.1 {
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    SELECT * FROM t1
  }
} {1}

# Establish a separate, independent connection to that database.
#
do_test tkt3093.2 {
  catch {sqlite3_enable_shared_cache 0}
  sqlite3 db2 test.db
  db2 eval {
    SELECT * FROM t1
  }
} {1}

# Make sure that clearing a lock allows a pending request for
# a reserved lock to continue.
#
do_test tkt3093.3 {
  # This will be the busy callback for connection db2.  On the first
  # busy callback, commit the transaction in db.  This should clear
  # the lock so that there should not be a second callback.  If the
  # busy handler is called a second time, then fail so that we get
  # timeout.
  proc busy_callback {cnt} {
    if {$cnt==0} {
      db eval COMMIT
      return 0
    } else {
      return 1
    }
  }
  db2 busy ::busy_callback

  # Start a write transaction on db.
  db eval {
     BEGIN;
     INSERT INTO t1 VALUES(2);
  }

  # Attempt to modify the database on db2
  catchsql {
     UPDATE t1 SET x=x+1;
  } db2
} {0 {}}

# Verify that everything worked as expected.  The db transaction should
# have gone first and added entry 2.  Then the db2 transaction would have
# run and added one to each entry.
#
do_test tkt3093.4 {
  db eval {SELECT * FROM t1}
} {2 3}
do_test tkt3093.5 {
  db2 eval {SELECT * FROM t1}
} {2 3}
db2 close

finish_test

Added test/tkt3121.test.





































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 2008 May 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt3121.test,v 1.2 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

# Register the module
register_echo_module [sqlite3_connection_pointer db]

do_test vtabD-1.1 {
  execsql {
    PRAGMA encoding = 'utf16';

    CREATE TABLE r1(field);
    CREATE TABLE r2(col PRIMARY KEY, descr);

    INSERT INTO r1 VALUES('abcd');
    INSERT INTO r2 VALUES('abcd', 'A nice description');
    INSERT INTO r2 VALUES('efgh', 'Another description');

    CREATE VIRTUAL TABLE t1 USING echo(r1);
    CREATE VIRTUAL TABLE t2 USING echo(r2);
  }
} {}

do_test vtabD-1.2 {
  execsql {
    select
      t1.field as Field,
      t2.descr as Descr
    from t1 inner join t2 on t1.field = t2.col order by t1.field
  }
} {abcd {A nice description}}

finish_test

Added test/tkt3201.test.



















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 2008 July 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
# Specifically, it tests that bug #3201 has been fixed.
#
# $Id: tkt3201.test,v 1.3 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3201-1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT);
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
  }
} {}

do_test tkt3201-2 {
  execsql {
    SELECT l.a, r.a FROM t1 AS l, t1 AS r WHERE l.a < r.a;
  }
} {1 2}

do_test tkt3201-3 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b TEXT);
    INSERT INTO t2 VALUES(2, 'two');
  }
  execsql {
    SELECT l.a, r.a FROM t1 AS l, t2 AS r WHERE l.a < r.a;
  }
} {1 2}

do_test tkt3201-4 {
  execsql {
    DELETE FROM t1 WHERE a = 2;
  }
  execsql {
    SELECT l.a, r.a FROM t1 AS l, t2 AS r WHERE l.a < r.a;
  }
} {1 2}

do_test tkt3201-5 {
  execsql {
    DELETE FROM t1 WHERE a = 2;
  }
  execsql {
    SELECT t1.a, t1.b, t2.a, t2.b FROM t1, t2;
  }
} {1 one 2 two}

do_test tkt3201-6 {
  execsql {
    CREATE TABLE t3(c INTEGER PRIMARY KEY, d TEXT);
    INSERT INTO t3 VALUES(2, 'two');
  }
  execsql { SELECT a, b, c, d FROM t1, t3 }
} {1 one 2 two}

do_test tkt3201-7 {
  execsql { SELECT a, b, c, d FROM t1, t3 WHERE a < c }
} {1 one 2 two}

# Ticket [efc02f977919]
#
ifcapable trigger {
  do_test tkt3201-4.0 {
    db eval {
     CREATE TABLE t4(x);
     CREATE TABLE t4_log(x);
     CREATE TRIGGER r4_1 AFTER INSERT ON t4 WHEN new.x=1 BEGIN
       INSERT INTO t4_log(x) VALUES(new.x);
     END;
     CREATE TRIGGER r4_2 AFTER INSERT ON t4 WHEN new.x=2 BEGIN
       INSERT INTO t4_log(x) VALUES(new.x);
     END;
     CREATE TRIGGER r4_3 AFTER INSERT ON t4 WHEN new.x=3 BEGIN
       INSERT INTO t4_log(x) VALUES(new.x);
     END;
     CREATE TRIGGER r4_4 AFTER INSERT ON t4 WHEN new.x=4 BEGIN
       INSERT INTO t4_log(x) VALUES(new.x);
     END;
     INSERT INTO t4 VALUES(1);
     INSERT INTO t4 VALUES(2);
     INSERT INTO t4 VALUES(3);
     INSERT INTO t4 VALUES(4);
     SELECT * FROM t4_log;
    }
  } {1 2 3 4}
}





finish_test

Added test/tkt3292.test.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 2008 August 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
# Specifically, it tests the behavior of the sqlite3VdbeRecordCompare()
# routine in cases where the rowid is 0 or 1 in file format 4
# (meaning that the rowid has type code 8 or 9 with zero bytes of
# data).  Ticket #3292.
#
# $Id: tkt3292.test,v 1.1 2008/08/13 14:07:41 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3292-1.1 {
  execsql {
    PRAGMA legacy_file_format=OFF;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
    INSERT INTO t1 VALUES(0, 1);
    INSERT INTO t1 VALUES(1, 1);
    INSERT INTO t1 VALUES(2, 1);
    CREATE INDEX i1 ON t1(b);
    SELECT * FROM t1 WHERE b>=1;
  }
} {0 1 1 1 2 1}
do_test tkt3292-1.2 {
  execsql {
    INSERT INTO t1 VALUES(3, 0);
    INSERT INTO t1 VALUES(4, 2);
    SELECT * FROM t1 WHERE b>=1;
  }
} {0 1 1 1 2 1 4 2}


do_test tkt3292-2.1 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c, d);
    INSERT INTO t2 VALUES(0, 1, 'hello', x'012345');
    INSERT INTO t2 VALUES(1, 1, 'hello', x'012345');
    INSERT INTO t2 VALUES(2, 1, 'hello', x'012345');
    CREATE INDEX i2 ON t2(b,c,d);
    SELECT a FROM t2 WHERE b=1 AND c='hello' AND d>=x'012345';
  }
} {0 1 2}
do_test tkt3292-2.2 {
  execsql {
    INSERT INTO t2 VALUES(3, 1, 'hello', x'012344');
    INSERT INTO t2 VALUES(4, 1, 'hello', x'012346');
    SELECT a FROM t2 WHERE b=1 AND c='hello' AND d>=x'012345';
  }
} {0 1 2 4}


finish_test

Added test/tkt3298.test.

































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 2008 August 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# 
# This file tests changes to the name resolution logic that occurred
# in august of 2008 and where associated with tickets #3298 and #3301
#
# $Id: tkt3298.test,v 1.3 2009/04/07 14:14:23 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !trigger { finish_test ; return }

do_test tkt3298-1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
    INSERT INTO t1 VALUES(0, 1);
    INSERT INTO t1 VALUES(1, 1);
    INSERT INTO t1 VALUES(2, 1);
    CREATE VIEW v1 AS SELECT a AS x, b+1 AS y FROM t1;
    CREATE TRIGGER r1 INSTEAD OF UPDATE ON v1
      BEGIN
        UPDATE t1 SET b=new.y-1 WHERE a=new.x;
      END;
    CREATE TRIGGER r2 INSTEAD OF DELETE ON v1
      BEGIN
        DELETE FROM t1 WHERE a=old.x;
      END;
    SELECT * FROM v1 ORDER BY x;
  }
} {0 2 1 2 2 2}
do_test tkt3298-1.2 {
  execsql {
    UPDATE v1 SET y=3 WHERE x=0;
    SELECT * FROM v1 ORDER by x;
  }
} {0 3 1 2 2 2}
do_test tkt3298-1.3 {
  execsql {
    UPDATE v1 SET y=4 WHERE v1.x=2;
    SELECT * FROM v1 ORDER by x;
  }
} {0 3 1 2 2 4}
do_test tkt3298-1.4 {
  execsql {
    DELETE FROM v1 WHERE x=1;
    SELECT * FROM v1 ORDER BY x;
  }
} {0 3 2 4}
do_test tkt3298-1.5 {
  execsql {
    DELETE FROM v1 WHERE v1.x=2;
    SELECT * FROM v1 ORDER BY x;
  }
} {0 3}

# Ticket #3301
#
do_test tkt3298-2.1 {
  execsql {
    CREATE TABLE t2(p,q);
    INSERT INTO t2 VALUES(1,11);
    INSERT INTO t2 VALUES(2,22);
    CREATE TABLE t3(x,y);
    INSERT INTO t3 VALUES(1,'one');

    SELECT *, (SELECT z FROM (SELECT y AS z FROM t3 WHERE x=t1.a+1) ) FROM t1;
  }
} {0 2 one}


finish_test

Added test/tkt3334.test.









































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# 2008 August 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library. 
# Specifically, it tests that bug #3334 has been fixed by the
# addition of restriction (19) to the subquery flattener optimization.
#
# $Id: tkt3334.test,v 1.1 2008/08/26 12:56:14 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3334-1.0 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,934);
    INSERT INTO t1 VALUES(2,221);
    INSERT INTO t1 VALUES(1,372);
    INSERT INTO t1 VALUES(3,552);
    INSERT INTO t1 VALUES(1,719);
    INSERT INTO t1 VALUES(4,102);
    SELECT * FROM t1 ORDER BY b;
  }
} {4 102 2 221 1 372 3 552 1 719 1 934}

do_test tkt3334-1.1 {
  execsql {
    SELECT a FROM (SELECT a FROM t1 ORDER BY b LIMIT 2) WHERE a=1;
  }
} {}
do_test tkt3334-1.2 {
  execsql {
    SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b LIMIT 2) WHERE a=1;
  }
} {0}
do_test tkt3334-1.3 {
  execsql {
    SELECT a FROM (SELECT a FROM t1 ORDER BY b LIMIT 3) WHERE a=1;
  }
} {1}
do_test tkt3334-1.4 {
  execsql {
    SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b LIMIT 3) WHERE a=1;
  }
} {1}
do_test tkt3334-1.5 {
  execsql {
    SELECT a FROM (SELECT a FROM t1 ORDER BY b LIMIT 99) WHERE a=1;
  }
} {1 1 1}
do_test tkt3334-1.6 {
  execsql {
    SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b LIMIT 99) WHERE a=1;
  }
} {3}
do_test tkt3334-1.7 {
  execsql {
    SELECT a FROM (SELECT a FROM t1 ORDER BY b) WHERE a=1;
  }
} {1 1 1}
do_test tkt3334-1.8 {
  execsql {
    SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b) WHERE a=1;
  }
} {3}
do_test tkt3334-1.9 {
  execsql {
    SELECT a FROM (SELECT a FROM t1) WHERE a=1;
  }
} {1 1 1}
do_test tkt3334-1.10 {
  execsql {
    SELECT count(*) FROM (SELECT a FROM t1) WHERE a=1;
  }
} {3}

Added test/tkt3346.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2008 September 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the fix for ticket #3346
#
# $Id: tkt3346.test,v 1.3 2008/12/09 13:12:57 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3346-1.1 {
  db eval {
   CREATE TABLE t1(a,b);
   INSERT INTO t1 VALUES(2,'bob');
   INSERT INTO t1 VALUES(1,'alice');
   INSERT INTO t1 VALUES(3,'claire');
   SELECT *, ( SELECT y FROM (SELECT x.b='alice' AS y) )
     FROM ( SELECT * FROM t1 ) AS x;
  }
} {2 bob 0 1 alice 1 3 claire 0}
do_test tkt3346-1.2 {
  db eval {
    SELECT b FROM (SELECT * FROM t1) AS x
     WHERE (SELECT y FROM (SELECT x.b='alice' AS y))=0
  }
} {bob claire}
do_test tkt3346-1.3 {
  db eval {
    SELECT b FROM (SELECT * FROM t1 ORDER BY a) AS x
     WHERE (SELECT y FROM (SELECT a||b y FROM t1 WHERE t1.b=x.b))=(x.a||x.b)
  }
} {alice bob claire}
do_test tkt3346-1.4 {
  db eval {
    SELECT b FROM (SELECT * FROM t1 ORDER BY a) AS x
     WHERE (SELECT y FROM (SELECT a||b y FROM t1 WHERE t1.b=x.b))=('2'||x.b)
  }
} {bob}

# Ticket #3530
#
# As shown by ticket #3346 above (see also ticket #3298) it is important
# that a subquery in the result-set be able to look up through multiple
# FROM levels in order to view tables in the FROM clause at the top level.
#
# But ticket #3530 shows us that a subquery in the FROM clause should not
# be able to look up to higher levels:
#
do_test tkt3346-2.1 {
  catchsql {
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES(1);
    
    SELECT * FROM (SELECT * FROM t1 WHERE 1=x.a) AS x;
  }
} {1 {no such column: x.a}}

finish_test

Added test/tkt3357.test.

































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 2008 September 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the fix for ticket #3357.
#
# $Id: tkt3357.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3357-1.1 {
  execsql {
    create table a(id integer primary key, b_id integer, myvalue varchar);
    create table b(id integer primary key, bvalue varchar);
    insert into a(b_id, myvalue) values(1,'Test');
    insert into a(b_id, myvalue) values(1,'Test2');
    insert into a(b_id, myvalue) values(1,'Test3');
    insert into b(bvalue) values('btest');
  }
} {}

do_test tkt3357-1.2 {
  execsql {
    SELECT cc.id, cc.b_id, cc.myvalue, dd.bvalue 
    FROM (
      SELECT DISTINCT a.id, a.b_id, a.myvalue FROM a
      INNER JOIN b ON a.b_id = b.id WHERE b.bvalue = 'btest'
    ) cc
    LEFT OUTER JOIN b dd ON cc.b_id = dd.id
  }
} {1 1 Test btest 2 1 Test2 btest 3 1 Test3 btest}

do_test tkt3357-1.3 {
  execsql {
    SELECT cc.id, cc.b_id, cc.myvalue
    FROM (
      SELECT a.id, a.b_id, a.myvalue 
      FROM a, b WHERE a.b_id = b.id
    ) cc
    LEFT OUTER JOIN b dd ON cc.b_id = dd.id
  }
} {1 1 Test 2 1 Test2 3 1 Test3}

do_test tkt3357-1.4 {
  execsql {
    SELECT cc.id, cc.b_id, cc.myvalue
    FROM (
      SELECT DISTINCT a.id, a.b_id, a.myvalue 
      FROM a, b WHERE a.b_id = b.id
    ) cc
    LEFT OUTER JOIN b dd ON cc.b_id = dd.id
  }
} {1 1 Test 2 1 Test2 3 1 Test3}

finish_test

Added test/tkt3419.test.



















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# 2008 October 06
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the fix for ticket #3419.
# Ticket #3419 is really a duplication of #3408 and had already
# been fixed by the time it was reported.  But it never hurts to
# add new test cases.
#
# $Id: tkt3419.test,v 1.1 2008/10/06 15:31:13 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3419-1.1 {
  execsql {
    create table a(id integer primary key);
    create table b(id integer primary key, a_id integer);
    create table c(id integer primary key, b_id integer);
  
    insert into a values (1);
    insert into a values (2);
  
    insert into b values (3, 1);
    insert into b values (4, 1);
    insert into b values (5, 1);
    insert into b values (6, 1);
    insert into b values (9, 2);
  
    insert into c values (4, 3);
    insert into c values (5, 5);
    insert into c values (6, 4);
    insert into c values (7, 6);
    insert into c values (8, 9);
  
    select * FROM a, b, c WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id;
  }
} {2 9 2 8 9}
do_test tkt3419-1.2 {
  execsql {
    select * FROM a, c, b WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id;
  }
} {2 8 9 9 2}
do_test tkt3419-1.3 {
  execsql {
    select * FROM b, a, c WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id;
  }
} {9 2 2 8 9}
do_test tkt3419-1.4 {
  execsql {
    select * FROM b, c, a WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id;
  }
} {9 2 8 9 2}
do_test tkt3419-1.5 {
  execsql {
    select * FROM c, a, b WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id;
  }
} {8 9 2 9 2}
do_test tkt3419-1.6 {
  execsql {
    select * FROM c, b, a WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id;
  }
} {8 9 9 2 2}

finish_test

Added test/tkt3424.test.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 2008 October 06
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
#
# $Id: tkt3424.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3424-1.1 {
  execsql {
    CREATE TABLE names(id INTEGER, data TEXT, code TEXT);
    INSERT INTO names VALUES(1,'E1','AAA');
    INSERT INTO names VALUES(2,NULL,'BBB');

    CREATE TABLE orig(code TEXT, data TEXT);
    INSERT INTO orig VALUES('AAA','E1');
    INSERT INTO orig VALUES('AAA','E2');
    INSERT INTO orig VALUES('AAA','E3');
    INSERT INTO orig VALUES('AAA','E4');
    INSERT INTO orig VALUES('AAA','E5');
  }
} {}

do_test tkt3424-1.2 {
  execsql {
    SELECT * FROM 
    names LEFT OUTER JOIN orig
    ON names.data = orig.data AND names.code = orig.code;
  }
} {1 E1 AAA AAA E1 2 {} BBB {} {}}

do_test tkt3424-1.3 {
  execsql { CREATE INDEX udx_orig_code_data ON orig(code, data) }
} {}

do_test tkt3424-1.4 {
  execsql {
    SELECT * FROM 
    names LEFT OUTER JOIN orig
    ON names.data = orig.data AND names.code = orig.code;
  }
} {1 E1 AAA AAA E1 2 {} BBB {} {}}

finish_test

Added test/tkt3442.test.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2008 October 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #3442 has been
# fixed.  
#
#
# $Id: tkt3442.test,v 1.2 2009/06/05 17:09:12 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl


# Create a schema with some indexes.
#
do_test tkt3442-1.1 {
  execsql {
     CREATE TABLE listhash(
       key INTEGER PRIMARY KEY,
       id TEXT,
       node INTEGER
     );
     CREATE UNIQUE INDEX ididx ON listhash(id);
  }
} {}


# Explain Query Plan
#
proc EQP {sql} {
  uplevel "execsql {EXPLAIN QUERY PLAN $sql}"
}


# These tests perform an EXPLAIN QUERY PLAN on both versions of the 
# SELECT referenced in ticket #3442 (both '5000' and "5000") 
# and verify that the query plan is the same.
#
ifcapable explain {
  do_test tkt3442-1.2 {
    EQP { SELECT node FROM listhash WHERE id='5000' LIMIT 1; }
  } {0 0 {TABLE listhash WITH INDEX ididx}}
  do_test tkt3442-1.3 {
    EQP { SELECT node FROM listhash WHERE id="5000" LIMIT 1; }
  } {0 0 {TABLE listhash WITH INDEX ididx}}
}


# Some extra tests testing other permutations of 5000.
#
ifcapable explain {
  do_test tkt3442-1.4 {
    EQP { SELECT node FROM listhash WHERE id=5000 LIMIT 1; }
  } {0 0 {TABLE listhash WITH INDEX ididx}}
}
do_test tkt3442-1.5 {
  catchsql {
    SELECT node FROM listhash WHERE id=[5000] LIMIT 1;
  }
} {1 {no such column: 5000}}

finish_test

Added test/tkt3457.test.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 2008 October 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# $Id: tkt3457.test,v 1.3 2009/06/26 07:12:07 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {$tcl_platform(platform) != "unix"} {
  finish_test
  return
}

#-----------------------------------------------------------------------
# To roll back a hot-journal file, the application needs read and write 
# permission on the journal file in question. The following tests test
# the outcome of trying to rollback a hot-journal file when this is not
# the case.
# 
#   tkt3457-1.2: Application has neither read, nor write permission on
#                the hot-journal file. Result: SQLITE_CANTOPEN.
#                
#   tkt3457-1.3: Application has write but not read permission on
#                the hot-journal file. Result: SQLITE_CANTOPEN.
#
#   tkt3457-1.4: Application has read but not write permission on
#                the hot-journal file. Result: SQLITE_CANTOPEN.
#
#   tkt3457-1.5: Application has read/write permission on the hot-journal 
#                file. Result: SQLITE_OK.
# 
do_test tkt3457-1.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    INSERT INTO t1 VALUES(1, 2, 3);
    BEGIN;
    INSERT INTO t1 VALUES(4, 5, 6);
  }

  file copy -force test.db bak.db
  file copy -force test.db-journal bak.db-journal

  # Fix the first journal-header in the journal-file. Because the
  # journal file has not yet been synced, the 8-byte magic string at the
  # start of the first journal-header has not been written by SQLite.
  # So write it now.
  set fd [open bak.db-journal a+]
  fconfigure $fd -encoding binary -translation binary
  seek $fd 0
  puts -nonewline $fd "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7"
  close $fd

  execsql COMMIT
} {}

do_test tkt3457-1.2 {
  file copy -force bak.db-journal test.db-journal
  file attributes test.db-journal -permissions ---------
  catchsql { SELECT * FROM t1 }
} {1 {unable to open database file}}
do_test tkt3457-1.3 {
  file copy -force bak.db-journal test.db-journal
  file attributes test.db-journal -permissions -w--w--w-
  catchsql { SELECT * FROM t1 }
} {1 {unable to open database file}}
do_test tkt3457-1.4 {
  file copy -force bak.db-journal test.db-journal
  file attributes test.db-journal -permissions r--r--r--
  catchsql { SELECT * FROM t1 }
} {1 {unable to open database file}}

do_test tkt3457-1.5 {
  file copy -force bak.db-journal test.db-journal
  file attributes test.db-journal -permissions rw-rw-rw-
  catchsql { SELECT * FROM t1 }
} {0 {1 2 3 4 5 6}}

finish_test

Added test/tkt3461.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2008 October 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #3461 has been
# fixed.  
#
# $Id: tkt3461.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

####################################
####################################
# REMOVE THESE TWO LINES:
####################################
####################################
#finish_test
#return

do_test tkt3461-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(1, 2);
  }
} {}

do_test tkt3461-1.2 {
  execsql { SELECT a, b+1 AS b_plus_one FROM t1 WHERE a=1 }
} {1 3}

do_test tkt3461-1.3 {
  # explain { SELECT a, b+1 AS b_plus_one FROM t1 WHERE a=1 OR b_plus_one }
  # execsql { PRAGMA vdbe_trace = 1; PRAGMA vdbe_listing=1 }
  execsql { SELECT a, b+1 AS b_plus_one FROM t1 WHERE a=1 OR b_plus_one }
} {1 3}

do_test tkt3461-2.1 {
  execsql { 
    SELECT a, b+1 AS b_plus_one 
    FROM t1 
    WHERE CASE WHEN a=1 THEN 1 ELSE b_plus_one END 
  }
} {1 3}

do_test tkt3461-3.1 {
  execsql {
    CREATE TABLE t2(c, d);
    INSERT INTO t2 VALUES(3, 4);
  }
  # execsql { PRAGMA vdbe_trace = 1; PRAGMA vdbe_listing=1 }
  execsql { 
    SELECT a, b+1 AS b_plus_one, c, d 
    FROM t1 LEFT JOIN t2 
    ON (a=c AND d=b_plus_one)
  }
} {1 3 {} {}}

finish_test

Added test/tkt3472.test.















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 2008 November 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#     
# $Id: tkt3472.test,v 1.4 2008/12/03 22:32:45 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {![info exists threadsOverrideEachOthersLocks]} {
  finish_test
  return
}

set ::correctvalue $threadsOverrideEachOthersLocks
puts "threadsOverrideEachOthersLocks = $::correctvalue"

do_test tkt3472-1.1 {
  db close
  set threadsOverrideEachOthersLocks -1
  sqlite3 db test.db
  set threadsOverrideEachOthersLocks
} $::correctvalue

do_test tkt3472-1.2 {
  db close
  set threadsOverrideEachOthersLocks -1
  sqlite3 db test.db -readonly 1
  set threadsOverrideEachOthersLocks
} $::correctvalue

finish_test

Added test/tkt3493.test.



















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# 2008 October 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. Specifically,
# it tests that affinities and collation sequences are correctly applied
# in aggregate queries.
#
# $Id: tkt3493.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3493-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE A (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT);
    INSERT INTO A VALUES(1,'123');
    INSERT INTO A VALUES(2,'456');
    CREATE TABLE B (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT);
    INSERT INTO B VALUES(1,1);
    INSERT INTO B VALUES(2,2);
    CREATE TABLE A_B (B_id INTEGER NOT NULL, A_id INTEGER);
    INSERT INTO A_B VALUES(1,1);
    INSERT INTO A_B VALUES(2,2);
    COMMIT;
  }
} {}
do_test tkt3493-1.2 {
  execsql {
    SELECT 
      CASE 
         WHEN B.val = 1 THEN 'XYZ' 
         ELSE A.val 
      END AS Col1
    FROM B  
    LEFT OUTER JOIN A_B ON B.id = A_B.B_id  
    LEFT OUTER JOIN A ON A.id = A_B.A_id
    ORDER BY Col1 ASC;
  }
} {456 XYZ}
do_test tkt3493-1.3 {
  execsql {
    SELECT DISTINCT
      CASE 
         WHEN B.val = 1 THEN 'XYZ' 
         ELSE A.val 
      END AS Col1
    FROM B  
    LEFT OUTER JOIN A_B ON B.id = A_B.B_id  
    LEFT OUTER JOIN A ON A.id = A_B.A_id
    ORDER BY Col1 ASC;
  }
} {456 XYZ}
do_test tkt3493-1.4 {
  execsql {
    SELECT b.val, CASE WHEN b.val = 1 THEN 'xyz' ELSE b.val END AS col1 FROM b;
  }
} {1 xyz 2 2}
do_test tkt3493-1.5 {
  execsql {
    SELECT DISTINCT 
      b.val, 
      CASE WHEN b.val = 1 THEN 'xyz' ELSE b.val END AS col1 
    FROM b;
  }
} {1 xyz 2 2}
do_test tkt3493-1.6 {
  execsql {
    SELECT DISTINCT 
      b.val, 
      CASE WHEN b.val = '1' THEN 'xyz' ELSE b.val END AS col1 
    FROM b;
  }
} {1 xyz 2 2}


do_test tkt3493-2.1 {
  execsql {
    CREATE TABLE t1(a TEXT, b INT);
    INSERT INTO t1 VALUES(123, 456);
  }
} {}
do_test tkt3493-2.2.1 {
  execsql { SELECT a=123 FROM t1 GROUP BY a }
} {1}
do_test tkt3493-2.2.2 {
  execsql { SELECT a=123 FROM t1 }
} {1}
do_test tkt3493-2.2.3 {
  execsql { SELECT a='123' FROM t1 }
} {1}
do_test tkt3493-2.2.4 {
  execsql { SELECT count(*), a=123 FROM t1 }
} {1 1}
do_test tkt3493-2.2.5 {
  execsql { SELECT count(*), +a=123 FROM t1 }
} {1 0}
do_test tkt3493-2.3.3 {
  execsql { SELECT b='456' FROM t1 GROUP BY a }
} {1}
do_test tkt3493-2.3.1 {
  execsql { SELECT b='456' FROM t1 GROUP BY b }
} {1}
do_test tkt3493-2.3.2 {
  execsql { SELECT b='456' FROM t1 }
} {1}
do_test tkt3493-2.4.1 {
  execsql { SELECT typeof(a), a FROM t1 GROUP BY a HAVING a=123 }
} {text 123}
do_test tkt3493-2.4.2 {
  execsql { SELECT typeof(a), a FROM t1 GROUP BY b HAVING a=123 }
} {text 123}
do_test tkt3493-2.5.1 {
  execsql { SELECT typeof(b), b FROM t1 GROUP BY a HAVING b='456' }
} {integer 456}
do_test tkt3493-2.5.2 {
  execsql { SELECT typeof(b), b FROM t1 GROUP BY b HAVING b='456' }
} {integer 456}

do_test tkt3493-3.1 {
  execsql {
    CREATE TABLE t2(a COLLATE NOCASE, b COLLATE BINARY);
    INSERT INTO t2 VALUES('aBc', 'DeF');
  }
} {}
do_test tkt3493-3.2.1 {
  execsql { SELECT a='abc' FROM t2 GROUP BY a }
} {1}
do_test tkt3493-3.2.2 {
  execsql { SELECT a='abc' FROM t2 }
} {1}

do_test tkt3493-3.3.1 {
  execsql { SELECT a>b FROM t2 GROUP BY a, b}
} {0}
do_test tkt3493-3.3.2 {
  execsql { SELECT a>b COLLATE BINARY FROM t2 GROUP BY a, b}
} {1}
do_test tkt3493-3.3.3 {
  execsql { SELECT b>a FROM t2 GROUP BY a, b}
} {0}
do_test tkt3493-3.3.4 {
  execsql { SELECT b>a COLLATE NOCASE FROM t2 GROUP BY a, b}
} {1}

finish_test

Added test/tkt3508.test.













































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 2008 November 22
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. 
#
# $Id: tkt3508.test,v 1.5 2009/05/28 01:00:56 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3508-1.1 {
  catchsql {
    CREATE TABLE modificationsTmp (
      SUBSTRATE_HPRD_ID VARCHAR(80),
      SUBSTRATE_GENE_SYMBOL VARCHAR(80),
      SUBSTRATE_ISOFORM_ID VARCHAR(80),
      SUBSTRATE_REFSEQ_ID VARCHAR(80),
      SITE INTEGER,
      RESIDUE VARCHAR(80),
      ENZYME_NAME VARCHAR(80),
      ENZYME_HPRD_ID VARCHAR(80),
      MODIFICATION_TYPE VARCHAR(80),
      EXPERIMENT_TYPE VARCHAR(80),
      REFERENCE_ID VARCHAR(80)
    );
    select SUBSTRATE_HPRD_ID, count(substrate_refseq_id) as c
      from modificationsTmp where c > 1 group by SUBSTRATE_HPRD_ID;
  }
} {1 {misuse of aggregate: count()}}

finish_test

Added test/tkt3522.test.























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 2008 December 4
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is a verification that the bugs identified in ticket
# #3522 have been fixed.
#
# $Id: tkt3522.test,v 1.1 2008/12/05 00:00:07 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3522-1.1 {
  db eval {
    CREATE TABLE tab4(
       col0 INTEGER,
       col1 INTEGER,
       col2 INTEGER,
       col3 INTEGER,
       col4 INTEGER
    );
    SELECT cor1.*
      FROM tab4 AS cor0
      JOIN tab4 AS cor1 USING ( col4, col3, col2, col1, col0 );
  }
} {}
do_test tkt3522-1.2 {
  db eval {
    CREATE TABLE tab1(col0 INTEGER);
    CREATE TABLE tab2(col0 INTEGER);
    SELECT cor0.* FROM tab1 NATURAL JOIN tab2 AS cor0;
  }
} {}

finish_test

Added test/tkt3527.test.













































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# 2008 December 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is a verification that the bugs identified in ticket
# #3527 have been fixed.
#
# $Id: tkt3527.test,v 1.1 2008/12/08 13:42:36 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3527-1.1 {
  db eval {
    CREATE TABLE Element (
     Code INTEGER PRIMARY KEY,
     Name VARCHAR(60)
    );
    
    CREATE TABLE ElemOr (
     CodeOr INTEGER NOT NULL,
     Code INTEGER NOT NULL,
     PRIMARY KEY(CodeOr,Code)
    );
    
    CREATE TABLE ElemAnd (
     CodeAnd INTEGER,
     Code INTEGER,
     Attr1 INTEGER,
     Attr2 INTEGER,
     Attr3 INTEGER,
     PRIMARY KEY(CodeAnd,Code)
    );
    
    INSERT INTO Element VALUES(1,'Elem1');
    INSERT INTO Element VALUES(2,'Elem2');
    INSERT INTO Element VALUES(3,'Elem3');
    INSERT INTO Element VALUES(4,'Elem4');
    INSERT INTO Element VALUES(5,'Elem5');
    INSERT INTO ElemOr Values(3,4);
    INSERT INTO ElemOr Values(3,5);
    INSERT INTO ElemAnd VALUES(1,3,1,1,1);
    INSERT INTO ElemAnd VALUES(1,2,1,1,1);
    
    CREATE VIEW ElemView1 AS
    SELECT
      CAST(Element.Code AS VARCHAR(50)) AS ElemId,
     Element.Code AS ElemCode,
     Element.Name AS ElemName,
     ElemAnd.Code AS InnerCode,
     ElemAnd.Attr1 AS Attr1,
     ElemAnd.Attr2 AS Attr2,
     ElemAnd.Attr3 AS Attr3,
     0 AS Level,
     0 AS IsOrElem
    FROM Element JOIN ElemAnd ON ElemAnd.CodeAnd=Element.Code
    WHERE ElemAnd.CodeAnd NOT IN (SELECT CodeOr FROM ElemOr)
    UNION ALL
    SELECT
      CAST(ElemOr.CodeOr AS VARCHAR(50)) AS ElemId,
      Element.Code AS ElemCode,
      Element.Name AS ElemName,
      ElemOr.Code AS InnerCode,
      NULL AS Attr1,
      NULL AS Attr2,
      NULL AS Attr3,
      0 AS Level,
      1 AS IsOrElem
    FROM ElemOr JOIN Element ON Element.Code=ElemOr.CodeOr
    ORDER BY ElemId, InnerCode;
    
    CREATE VIEW ElemView2 AS
    SELECT
      ElemId,
      ElemCode,
      ElemName,
      InnerCode,
      Attr1,
      Attr2,
      Attr3,
      Level,
      IsOrElem
    FROM ElemView1
    UNION ALL
    SELECT
      Element.ElemId || '.' || InnerElem.ElemId AS ElemId,
      InnerElem.ElemCode,
      InnerElem.ElemName,
      InnerElem.InnerCode,
      InnerElem.Attr1,
      InnerElem.Attr2,
      InnerElem.Attr3,
      InnerElem.Level+1,
      InnerElem.IsOrElem
    FROM ElemView1 AS Element
    JOIN ElemView1 AS InnerElem
         ON Element.Level=0 AND Element.InnerCode=InnerElem.ElemCode
    ORDER BY ElemId, InnerCode;
 
    SELECT * FROM ElemView1;
  }
} {1 1 Elem1 2 1 1 1 0 0 1 1 Elem1 3 1 1 1 0 0 3 3 Elem3 4 {} {} {} 0 1 3 3 Elem3 5 {} {} {} 0 1}
   
do_test tkt3527-1.2 {
  db eval {
    SELECT * FROM ElemView2;
  }
} {1 1 Elem1 2 1 1 1 0 0 1 1 Elem1 3 1 1 1 0 0 1.3 3 Elem3 4 {} {} {} 1 1 1.3 3 Elem3 5 {} {} {} 1 1 3 3 Elem3 4 {} {} {} 0 1 3 3 Elem3 5 {} {} {} 0 1}

finish_test

Added test/tkt3541.test.







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 2008 December 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file is a verification that the bugs identified in ticket
# #3541 have been fixed.
#
# $Id: tkt3541.test,v 1.1 2008/12/15 15:27:52 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3541-1.1 {
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(123);
    SELECT CASE ~max(x) WHEN min(x) THEN 1 ELSE max(x) END FROM t1;
  }
} {123}
do_test tkt3541-1.2 {
  db eval {
    SELECT CASE NOT max(x) WHEN min(x) THEN 1 ELSE max(x) END FROM t1;
  }
} {123}


finish_test

Added test/tkt3554.test.







































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 2008 December 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #3554 has been
# fixed.  
#
# $Id: tkt3554.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !trigger {
  finish_test
  return
}

do_test tkt3544-1.1 {
  execsql {
    CREATE TABLE test ( obj, t1, t2, PRIMARY KEY(obj, t1, t2) );
  
    CREATE TRIGGER test_insert BEFORE INSERT ON test BEGIN
      UPDATE test SET t1 = new.t1 
        WHERE obj = new.obj AND new.t1 < t1 AND new.t2 >= t1;
  
      UPDATE test SET t2 = new.t2 
        WHERE obj = new.obj AND new.t2 > t2 AND new.t1 <= t2;
  
      SELECT RAISE(IGNORE) WHERE EXISTS (
        SELECT obj FROM test 
        WHERE obj = new.obj AND new.t1 >= t1 AND new.t2 <= t2
      );
    END;
  }
} {}

do_test tkt3544-1.2 {
  execsql {
    INSERT INTO test VALUES('a', 10000, 11000);
    SELECT * FROM test;
  }
} {a 10000 11000}


do_test tkt3544-1.3 {
  execsql {
    INSERT INTO test VALUES('a', 9000, 10500);
  }
  execsql { SELECT * FROM test }
} {a 9000 11000}

do_test tkt3544-1.4 {
  execsql {
    INSERT INTO test VALUES('a', 10000, 12000);
  }
  execsql { SELECT * FROM test }
} {a 9000 12000}

finish_test

Added test/tkt3581.test.













































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 2008 January 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #3581 has been
# fixed.  
#
# $Id: tkt3581.test,v 1.1 2009/01/14 01:10:40 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3581-1.1 {
  db eval {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
    INSERT INTO t1 VALUES(0,544,846);
    INSERT INTO t1 VALUES(1,345,51);
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c);
    INSERT INTO t2 SELECT * FROM t1;
    CREATE INDEX i2 on t2(c);
  }
} {}

do_test tkt3581-1.2 {
  db eval {
    SELECT a FROM t1
     WHERE (b > 45 AND c < 356)
        OR b <= 733
        OR b >= 557
        OR (b >= 614 AND c < 251)
     ORDER BY b;
  }
} {1 0}

do_test tkt3581-1.3 {
  db eval {
    SELECT a FROM t2
     WHERE (b > 45 AND c < 356)
        OR b <= 733
        OR b >= 557
        OR (b >= 614 AND c < 251)
     ORDER BY b;
  }
} {1 0}

finish_test

Added test/tkt35xx.test.













































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# 2008 November 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# When a transaction rolls back, make sure that dirty pages in the
# page cache which are not in the rollback journal are reinitialized
# in the btree layer.
#
# $Id: tkt35xx.test,v 1.4 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt35xx-1.1 {
  execsql {
    PRAGMA auto_vacuum = 0;
    PRAGMA page_size = 1024;
  }
} {}

# Trigger the problem using explicit rollback.
#
do_test tkt35xx-1.1 {
  execsql {
    PRAGMA auto_vacuum = 0;
    CREATE TABLE t1(a,b,c);
    CREATE INDEX i1 ON t1(c);
    INSERT INTO t1 VALUES(0, 0, zeroblob(676));
    INSERT INTO t1 VALUES(1, 1, zeroblob(676));
    DELETE FROM t1;
    BEGIN;
    INSERT INTO t1 VALUES(0, 0, zeroblob(676));
    INSERT INTO t1 VALUES(1, 1, zeroblob(676));
    ROLLBACK;
    INSERT INTO t1 VALUES(0, 0, zeroblob(676));
  }
  execsql {
    INSERT INTO t1 VALUES(1, 1, zeroblob(676));
  }
} {}

# Trigger the problem using statement rollback.
#
db close
file delete test.db
sqlite3 db test.db
set big [string repeat abcdefghij 22]    ;# 220 byte string
do_test tkt35xx-1.2.1 {
  execsql {
    PRAGMA auto_vacuum = 0;
    PRAGMA page_size = 1024;
    CREATE TABLE t3(a INTEGER PRIMARY KEY, b);
    INSERT INTO t3 VALUES(1, $big);
    INSERT INTO t3 VALUES(2, $big);
    INSERT INTO t3 VALUES(3, $big);
    INSERT INTO t3 VALUES(4, $big);
    CREATE TABLE t4(c, d);
    INSERT INTO t4 VALUES(5, $big);
    INSERT INTO t4 VALUES(1, $big);
  }
} {}
do_test tkt35xx-1.2.2 {
  catchsql {
    BEGIN;
    CREATE TABLE t5(e PRIMARY KEY, f);
    DROP TABLE t5;
    INSERT INTO t3(a, b) SELECT c, d FROM t4;
  }
} {1 {PRIMARY KEY must be unique}}
do_test tkt35xx-1.2.3 {
  # Show that the transaction has not been rolled back.
  catchsql BEGIN
} {1 {cannot start a transaction within a transaction}}
do_test tkt35xx-1.2.4 {
  execsql { SELECT count(*) FROM t3 }
} {4}
do_test tkt35xx-1.2.5 {
  # Before the bug was fixed, if SQLITE_DEBUG was defined an assert()
  # would fail during the following INSERT statement. If SQLITE_DEBUG
  # was not defined, then the statement would pass and the transaction
  # would be committed. But, the "SELECT count(*)" in tkt35xx-1.2.6 would
  # return 1, not 5. Data magically disappeared!
  #
  execsql { 
    INSERT INTO t3 VALUES(5, $big);
    COMMIT;
  }
} {}
do_test tkt35xx-1.2.6 {
  execsql { SELECT count(*) FROM t3 }
} {5}
integrity_check tkt35xx-1.2.7

finish_test

Added test/tkt3630.test.































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 2009 February 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# 
# This file checks to make sure the "TEMP" or "TEMPORARY" keyword is
# omitted from the schema of a table that is created using that
# keyword.  Ticket #3630.
#
# $Id: tkt3630.test,v 1.1 2009/02/02 18:03:22 drh Exp $
#

set testdir [file dirname $argv0]

source $testdir/tester.tcl

do_test tkt3630-1 {
  db eval {
    CREATE TEMP TABLE temp1(a,b,c);
    SELECT * FROM sqlite_temp_master WHERE sql GLOB '*TEMP*';
  }
} {}
do_test tkt3630-2 {
  db eval {
    CREATE TABLE main1(a,b,c);
    CREATE TEMP TABLE temp2 AS SELECT * FROM main1;
    SELECT * FROM sqlite_temp_master WHERE sql GLOB '*TEMP*';
  }
} {}

ifcapable altertable {
  do_test tkt3630-3 {
    db eval {
      ALTER TABLE temp2 ADD COLUMN d;
      ALTER TABLE temp2 RENAME TO temp2rn;
      SELECT name FROM sqlite_temp_master WHERE name LIKE 'temp2%';
    }
  } {temp2rn}
}

finish_test

Added test/tkt3718.test.













































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the execution of SQL statements from
# within callbacks generated by VMs that themselves open statement 
# transactions.
#
# $Id: tkt3718.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3718-1.1 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES(1, 'one');
    INSERT INTO t1 VALUES(2, 'two');
    INSERT INTO t1 VALUES(3, 'three');
    INSERT INTO t1 VALUES(4, 'four');
    INSERT INTO t1 VALUES(5, 'five');
    CREATE TABLE t2(a PRIMARY KEY, b);
  }
} {}

# SQL scalar function:
#
#   f1(<arg>)
#
# Uses database handle [db] to execute "SELECT f2(<arg>)". Returns either
# the results or error message from the "SELECT f2(<arg>)" query to the
# caller.
#
proc f1 {args} {
  set a [lindex $args 0]
  catch { db eval {SELECT f2($a)} } msg
  set msg
}

# SQL scalar function:
#
#   f2(<arg>)
#
# Return the value of <arg>. Unless <arg> is "three", in which case throw
# an exception.
#
proc f2 {args} {
  set a [lindex $args 0]
  if {$a == "three"} { error "Three!!" }
  return $a
}

db func f1 f1
db func f2 f2

# The second INSERT statement below uses the f1 user function such that
# half-way through the INSERT operation f1() will run an SQL statement
# that throws an exception. At one point, before #3718 was fixed, this
# caused the statement transaction belonging to the INSERT statement to
# be rolled back. The result was that some (but not all) of the rows that 
# should have been inserted went missing.
#
do_test tkt3718-1.2 {
  execsql {
    BEGIN;
    INSERT INTO t2 SELECT a, b FROM t1;
    INSERT INTO t2 SELECT a+5, f1(b) FROM t1;
    COMMIT;
  }
  execsql {
    SELECT a FROM t2;
  }
} {1 2 3 4 5 6 7 8 9 10}

# This test turns on the count_changes pragma (causing DML statements to
# return SQLITE_ROW once, with a single integer result value reporting the
# number of rows affected by the statement). It then executes an INSERT
# statement that requires a statement journal. After stepping the statement
# once, so that it returns SQLITE_ROW, a second SQL statement that throws an
# exception is run. At one point, before #3718 was fixed, this caused the
# statement transaction belonging to the INSERT statement to be rolled back.
# The result was that none of the rows were actually inserted.
# 
#
do_test tkt3718-1.3 {
  execsql { 
    DELETE FROM t2 WHERE a > 5;
    PRAGMA count_changes = 1;
    BEGIN;
  }
  db eval {INSERT INTO t2 SELECT a+5, b||'+5' FROM t1} {
    catch { db eval {SELECT f2('three')} } msg
  }
  execsql {
    COMMIT;
    SELECT a FROM t2;
  }
} {1 2 3 4 5 6 7 8 9 10}

do_test tkt3718-1.4 {
  execsql {pragma count_changes=0}
} {}

# This SQL function executes the SQL specified as an argument against
# database [db].
#
proc sql {doit zSql} {
  if {$doit} { catchsql $zSql }
}
db func sql [list sql]

# The following tests, tkt3718-2.*, test that a nested statement 
# transaction can be successfully committed or reverted without 
# affecting the parent statement transaction.
#
do_test tkt3718-2.1 {
  execsql { SELECT sql(1, 'DELETE FROM t2 WHERE a = '||a ) FROM t2 WHERE a>5 }
  execsql { SELECT a from t2 }
} {1 2 3 4 5}
do_test tkt3718-2.2 {
  execsql {
    DELETE FROM t2 WHERE a > 5;
    BEGIN;
    INSERT INTO t2 SELECT a+5, sql(a==3,
        'INSERT INTO t2 SELECT a+10, f2(b) FROM t1'
    ) FROM t1;
  }
  execsql {
    COMMIT;
    SELECT a FROM t2;
  }
} {1 2 3 4 5 6 7 8 9 10}
do_test tkt3718-2.3 {
  execsql {
    DELETE FROM t2 WHERE a > 5;
    BEGIN;
    INSERT INTO t2 SELECT a+5, sql(a==3,
        'INSERT INTO t2 SELECT a+10, b FROM t1'
    ) FROM t1;
    COMMIT;
  }
  execsql { SELECT a FROM t2 ORDER BY a+0}
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}
integrity_check tkt3718.2-4

# The next set of tests, tkt3718-3.*, test that a statement transaction
# that has a committed statement transaction nested inside of it can
# be committed or reverted.
#
foreach {tn io ii results} {
  1 0 10 {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20}
  2 1 10 {6 7 8 9 10 16 17 18 19 20}
  3 0 11 {1 2 3 4 5 6 7 8 9 10 16 17 18 19 20}
  4 1 11 {6 7 8 9 10 16 17 18 19 20}
} {
  do_test tkt3718-3.$tn {
    execsql { 
      DELETE FROM t2;
      INSERT INTO t2 SELECT a+5, b FROM t1;
      INSERT INTO t2 SELECT a+15, b FROM t1;
    }

    catchsql "
      BEGIN;
      INSERT INTO t2 SELECT a+$io, sql(a==3,
          'INSERT INTO t2 SELECT a+$ii, b FROM t1'
      ) FROM t1;
    "

    execsql { COMMIT }

    execsql { SELECT a FROM t2 ORDER BY a+0}
  } $results

  integrity_check tkt3718-3.$tn.integrity
}

# This is the same test as tkt3718-3.*, but with 3 levels of nesting.
#
foreach {tn i1 i2 i3 results} {
  1   0 10 20   {5 10 15 20 25 30}
  2   0 10 21   {5 10 15 20 30}
  3   0 11 20   {5 10 20 30}
  4   0 11 21   {5 10 20 30}
  5   1 10 20   {10 20 30}
  6   1 10 21   {10 20 30}
  7   1 11 20   {10 20 30}
  8   1 11 21   {10 20 30}
} {
  do_test tkt3718-4.$tn {
    execsql { 
      DELETE FROM t2;
      INSERT INTO t2 SELECT a+5, b FROM t1;
      INSERT INTO t2 SELECT a+15, b FROM t1;
      INSERT INTO t2 SELECT a+25, b FROM t1;
    }

    catchsql "
      BEGIN;
      INSERT INTO t2 SELECT a+$i1, sql(a==3,
          'INSERT INTO t2 SELECT a+$i2, sql(a==3, 
             ''INSERT INTO t2 SELECT a+$i3, b FROM t1''
           ) FROM t1'
      ) FROM t1;
    "

    execsql { COMMIT }

    execsql { SELECT a FROM t2 WHERE (a%5)==0 ORDER BY a+0}
  } $results

  do_test tkt3718-4.$tn.extra {
    execsql {
      SELECT 
        (SELECT sum(a) FROM t2)==(SELECT sum(a*5-10) FROM t2 WHERE (a%5)==0)
    }
  } {1}

  integrity_check tkt3718-4.$tn.integrity
}


finish_test

Added test/tkt3731.test.

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 2009 March 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt3731.test,v 1.1 2009/03/17 22:33:01 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# The tests in this file were written before SQLite supported recursive
# trigger invocation, and some tests depend on that to pass. So disable
# recursive triggers for this file.
catchsql { pragma recursive_triggers = off } 

do_test tkt3731-1.1 {
  execsql {
    CREATE TABLE t1(a PRIMARY KEY, b);
    CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN
      INSERT INTO t1 VALUES(new.a || '+', new.b || '+');
    END;
  }
} {}

do_test tkt3731-1.2 {
  execsql {
    INSERT INTO t1 VALUES('a', 'b');
    INSERT INTO t1 VALUES('c', 'd');
    SELECT * FROM t1;
  }
} {a b a+ b+ c d c+ d+}

do_test tkt3731-1.3 {
  execsql {
    DELETE FROM t1;
    CREATE TABLE t2(a, b);
    INSERT INTO t2 VALUES('e', 'f');
    INSERT INTO t2 VALUES('g', 'h');
    INSERT INTO t1 SELECT * FROM t2;
    SELECT * FROM t1;
  }
} {e f e+ f+ g h g+ h+}

integrity_check tkt3731-1.4

finish_test

Added test/tkt3757.test.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 2009 March 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3757:  The cost functions on the query optimizer for the
# IN operator can be improved.
#
# $Id: tkt3757.test,v 1.1 2009/03/29 00:13:04 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Evaluate SQL.  Return the result set followed by the
# and the number of full-scan steps.
#
proc count_steps {sql} {
  set r [db eval $sql]
  lappend r scan [db status step] sort [db status sort]
}

# Construct tables
#
do_test tkt3757-1.1 {
  db eval {
     CREATE TABLE t1(x INTEGER, y INTEGER, z TEXT);
     CREATE INDEX t1i1 ON t1(y,z);
     INSERT INTO t1 VALUES(1,2,'three');
     CREATE TABLE t2(a INTEGER, b TEXT);
     INSERT INTO t2 VALUES(2, 'two');
     ANALYZE;
     SELECT * FROM sqlite_stat1;
  }
} {t1 t1i1 {1 1 1}}

# Modify statistics in order to make the optimizer then that:
#
#   (1)  Table T1 has about 250K entries
#   (2)  There are only about 5 distinct values of T1.
#
# Then run a query with "t1.y IN (SELECT ..)" in the WHERE clause.
# Make sure the index is used.
#
do_test tkt3757-1.2 {
  db eval {
    DELETE FROM sqlite_stat1;
    INSERT INTO sqlite_stat1 VALUES('t1','t1i1','250000 50000 30');
  }
  count_steps {
    SELECT * FROM t1 WHERE y IN (SELECT a FROM t2)
  }
} {1 2 three scan 0 sort 0}

finish_test

Added test/tkt3761.test.

















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 2009 March 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3761:  Make sure that an incremental vacuum on an in-memory
# database can be rolled back.
#
# $Id: tkt3761.test,v 1.1 2009/03/31 02:54:40 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3761-1.1 {
  db close
  sqlite3 db :memory:
  db eval {
    PRAGMA auto_vacuum=INCREMENTAL;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(zeroblob(900));
    INSERT INTO t1 VALUES(zeroblob(900));
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    BEGIN;
    DELETE FROM t1 WHERE rowid%2;
    PRAGMA incremental_vacuum(4);
    ROLLBACK;
  }
  db eval {PRAGMA integrity_check}
} {ok}

finish_test

Added test/tkt3762.test.













































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 2009 March 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3762:  Make sure that an incremental vacuum that reduces the
# size of the database file such that a pointer-map page is elemented
# can be correctly rolled back.
#
# That ticket #3762 has been fixed has already been verified by the
# savepoint6.test test script.  But this script is simplier and a
# redundant test never hurts.
#
# $Id: tkt3762.test,v 1.1 2009/03/31 00:50:36 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3762-1.1 {
  db eval {
    PRAGMA auto_vacuum=INCREMENTAL;
    PRAGMA page_size=1024;
    PRAGMA cache_size=10;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(zeroblob(900));
    INSERT INTO t1 VALUES(zeroblob(900));
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    INSERT INTO t1 SELECT x FROM t1;
    DELETE FROM t1 WHERE rowid>202;
    VACUUM;
    
    BEGIN;
    DELETE FROM t1 WHERE rowid IN (10,11,12) ;
    PRAGMA incremental_vacuum(10);
    UPDATE t1 SET x=zeroblob(900) WHERE rowid BETWEEN 100 AND 110;
    INSERT INTO t1 VALUES(zeroblob(39000));
    SELECT count(*) FROM t1;
    ROLLBACK;
  }
  db eval {PRAGMA integrity_check}
} {ok}

finish_test

Added test/tkt3773.test.













































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 2009 April 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3773:  Be careful not to over-optimize when a compound
# subquery contains an ORDER BY clause.
#
#
# $Id: tkt3773.test,v 1.1 2009/04/02 16:59:47 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3773-1.1 {
  db eval {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(2,1);
    INSERT INTO t1 VALUES(33,3);
    CREATE TABLE t2(x,y);
    INSERT INTO t2 VALUES(123,2);
    INSERT INTO t2 VALUES(4,4);
    SELECT a FROM (
      SELECT a, b FROM t1
      UNION ALL
      SELECT x, y FROM t2
      ORDER BY 2
    );
  }
} {2 123 33 4}

finish_test

Added test/tkt3791.test.

























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 2009 April 2
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3791:  A segfault when inserting into a table that contains
# an arbitrary expression as its default value.
#
# $Id: tkt3791.test,v 1.1 2009/04/08 12:21:31 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3791-1.1 {
  db eval {
    CREATE TABLE t1(x, y DEFAULT(datetime('now')));
    INSERT INTO t1(x) VALUES(1);
    SELECT x, length(y) FROM t1;
  }
} {1 19}

finish_test

Added test/tkt3793.test.















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# 2009 April 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #3793 has been
# fixed.  
#
# $Id: tkt3793.test,v 1.2 2009/06/01 16:42:18 shane Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !shared_cache||!attach {
  finish_test
  return
}
set ::enable_shared_cache [sqlite3_enable_shared_cache 1]

do_test tkt3793-1.1 {
  # This is taken from shared.test.  The Windows VFS expands 
  # ./test.db (and test.db) to be the same thing so the path
  # matches and they share a cache.  By changing the case 
  # for Windows platform, we get around this and get a separate
  # connection.
  if {$::tcl_platform(platform)=="unix"} {
    sqlite3 db1 test.db
    sqlite3 db2 test.db
  } else {
    sqlite3 db1 TEST.DB
    sqlite3 db2 TEST.DB
  }
  execsql {
    BEGIN;
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(a PRIMARY KEY, b);
    INSERT INTO t1 VALUES(randstr(50,50), randstr(50,50));
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1;
    INSERT INTO t2 SELECT * FROM t1;
    COMMIT;
  }
} {}

proc busyhandler {db args} { set ::busyconnection $db ; return 1 }
db2 busy {busyhandler db2}
db1 busy {busyhandler db1}

# Establish a read-lock on the database file using connection [db].
#
do_test tkt3793-1.2 {
  execsql {
    BEGIN;
    SELECT count(*) FROM t1;
  }
} {1024}

# Set the size of the cache shared by [db1] and [db2] to 10. Then update
# more than 10 pages of table t1. At this point the shared-cache will
# hold a RESERVED lock on the database file. Even though there are now
# more than 10 dirty pages in memory, it cannot upgrade to an EXCLUSIVE 
# lock because of the read-lock held by [db].
#
do_test tkt3793-1.3 {
  execsql {
    PRAGMA cache_size = 10;
    BEGIN;
    UPDATE t1 SET b = randstr(50,50);
  } db1
} {}

set x 0

# Run one SELECT query on the shared-cache using [db1], then from within 
# the callback run another via [db2]. Because of the large number of dirty
# pages within the cache, each time a new page is read from the database
# SQLite will attempt to upgrade to an EXCLUSIVE lock, and hence invoke
# the busy-handler. The tests here verify that the correct busy-handler
# function is invoked (the busy-handler associated with the database
# connection that called sqlite3_step()). When bug #3793 existed, sometimes
# the [db2] busy-handler was invoked from within the call to sqlite3_step()
# associated with [db1]. 
#
# Note: Before the bug was fixed, if [db2] was opened with the "-fullmutex 1"
# option, then this test case would cause an assert() to fail.
#
set ::busyconnection db1
db1 eval {SELECT * FROM t2 ORDER BY a LIMIT 20} {
  do_test tkt3793-2.[incr x] { set ::busyconnection } db1
  set ::busyconnection db2

  db2 eval { SELECT count(*) FROM t2 }
  do_test tkt3793-2.[incr x] { set ::busyconnection } db2
  set ::busyconnection db1
}

do_test tkt3793-3 {
  db1 close
  db2 close
} {}

sqlite3_enable_shared_cache $::enable_shared_cache
finish_test

Added test/tkt3810.test.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 2009 August 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to make sure #3810 is fixed.
#
# $Id: tkt3810.test,v 1.4 2009/08/06 17:43:31 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# Create a table using the first database connection.
#
do_test tkt3810-1.1 {
  execsql {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(123);
    SELECT * FROM t1;
    CREATE TABLE t2(y);
    CREATE TABLE t3(z);
  }
} 123

# Create a second connection to the same database.  Make sure the
# schema of the database has been parsed by the second connection.
#
do_test tkt3810-2 {
  sqlite3 db2 test.db
  execsql {
    SELECT * FROM t1;
  } db2
} 123

# DROP the table using the second connection.  The table no longer exists
# but the first connection does not yet know this.  Then try to create a TEMP
# trigger in the first connection that references the table that was dropped.
#
do_test tkt3810-3 {
  execsql {DROP TABLE t1} db2
  execsql {
     CREATE TEMP TRIGGER r1 AFTER INSERT ON t1 BEGIN
       INSERT INTO t2 VALUES(new.rowid);
     END;
  }
  catchsql {
    SELECT * FROM t3;
  }
} {0 {}}

# Trigger still exists in the sqlite_temp_master table, but now it is
# an orphan.
#
do_test tkt3810-4 {
  execsql {SELECT name FROM sqlite_temp_master ORDER BY name}
} {r1}

# Because it is an orphan, it cannot be dropped.
#
do_test tkt3810-5 {
  catchsql {DROP TRIGGER r1}
} {1 {no such trigger: r1}}

# Create a table t1 then drop the table in order to drop the orphaned
# trigger.
#
do_test tkt3810-6 {
  execsql {CREATE TABLE t1(x)} db2
  execsql {DROP TABLE t1}
  execsql {
    SELECT name FROM sqlite_temp_master;
  }
} {}

db2 close

finish_test

Added test/tkt3824.test.







































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 2009 April 24                                                                 
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3824
#
# When you use an "IS NULL" constraint on a UNIQUE index, the result
# is not necessarily UNIQUE.  Make sure the optimizer does not assume
# uniqueness.
#
# $Id: tkt3824.test,v 1.2 2009/04/24 20:32:31 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc execsql_status {sql {db db}} {
  set result [uplevel $db eval [list $sql]]
  if {[db status sort]} {
    concat $result sort
  } else {
    concat $result nosort
  }
}

do_test tkt3824-1.1 {
  db eval {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,NULL);
    INSERT INTO t1 VALUES(9,NULL);
    INSERT INTO t1 VALUES(5,NULL);
    INSERT INTO t1 VALUES(123,NULL);
    INSERT INTO t1 VALUES(-10,NULL);
    CREATE UNIQUE INDEX t1b ON t1(b);
  }
  execsql_status {
    SELECT a FROM t1 WHERE b IS NULL ORDER BY a;
  }
} {-10 1 5 9 123 sort}
do_test tkt3824-1.2 {
  execsql_status {
    SELECT a FROM t1 WHERE b IS NULL ORDER BY b, a;
  }
} {-10 1 5 9 123 sort}

do_test tkt3824-2.1 {
  db eval {
    CREATE TABLE t2(a,b,c);
    INSERT INTO t2 VALUES(1,1,NULL);
    INSERT INTO t2 VALUES(9,2,NULL);
    INSERT INTO t2 VALUES(5,2,NULL);
    INSERT INTO t2 VALUES(123,3,NULL);
    INSERT INTO t2 VALUES(-10,3,NULL);
    CREATE UNIQUE INDEX t2bc ON t2(b,c);
  }
  execsql_status {
    SELECT a FROM t2 WHERE b=2 AND c IS NULL ORDER BY a;
  }
} {5 9 sort}
do_test tkt3824-2.2 {
  execsql_status {
    SELECT a FROM t2 WHERE b=2 AND c IS NULL ORDER BY b, a;
  }
} {5 9 sort}
do_test tkt3824-2.3 {
  lsort [execsql_status {
    SELECT a FROM t2 WHERE b=2 AND c IS NULL ORDER BY b;
  }]
} {5 9 sort}

do_test tkt3824-3.1 {
  db eval {
    CREATE TABLE t3(x,y);
    INSERT INTO t3 SELECT a, b FROM t1;
    INSERT INTO t3 VALUES(234,567);
    CREATE UNIQUE INDEX t3y ON t3(y);
    DELETE FROM t3 WHERE y IS NULL;
    SELECT * FROM t3;
  }
} {234 567}

do_test tkt3824-4.1 {
  db eval {
    CREATE TABLE t4(x,y);
    INSERT INTO t4 SELECT a, b FROM t1;
    INSERT INTO t4 VALUES(234,567);
    CREATE UNIQUE INDEX t4y ON t4(y);
    UPDATE t4 SET rowid=rowid+100 WHERE y IS NULL;
    SELECT rowid, x FROM t4 ORDER BY rowid;
  }
} {6 234 101 1 102 9 103 5 104 123 105 -10}

finish_test

Added test/tkt3832.test.



















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 2009 April 30                                                            
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3832
#
# A segfault when using a BEFORE trigger on an INSERT and inserting
# a NULL into the INTEGER PRIMARY KEY.
#
# $Id: tkt3832.test,v 1.1 2009/05/01 02:08:04 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}


do_test tkt3832-1.1 {
  db eval {
    CREATE TABLE t1(a INT, b INTEGER PRIMARY KEY);
    CREATE TABLE log(x);
    CREATE TRIGGER t1r1 BEFORE INSERT ON t1 BEGIN
      INSERT INTO log VALUES(new.b);
    END;
    INSERT INTO t1 VALUES(NULL,5);
    INSERT INTO t1 SELECT b, a FROM t1 ORDER BY b;
    SELECT rowid, * FROM t1;
    SELECT rowid, * FROM log;
  }
} {5 {} 5 6 5 6 1 5 2 -1}

finish_test

Added test/tkt3838.test.



















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 2009 May 5
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3838
#
# The ticket reports that the encoding is UTF8 on the DEFAULT VALUE of
# a column added using ALTER TABLE even when the database is UTF16.
# Verify that this has been fixed.
#
# $Id: tkt3838.test,v 1.1 2009/05/05 12:54:50 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !altertable {
  finish_test
  return
}

do_test tkt3838-1.1 {
  db eval {
    PRAGMA encoding=UTF16;
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    ALTER TABLE t1 ADD COLUMN b INTEGER DEFAULT '999';
    ALTER TABLE t1 ADD COLUMN c REAL DEFAULT '9e99';
    ALTER TABLE t1 ADD COLUMN d TEXT DEFAULT 'xyzzy';
    UPDATE t1 SET x=x+1;
    SELECT * FROM t1;
  }
} {2 999 9e+99 xyzzy}

finish_test

Added test/tkt3841.test.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 2009 May 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Ticket #3841
#
# The sqlite3_aggregate_count() is not being reset when an aggregate
# functio is used in a correlated subquery.
#
set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !subquery {
  finish_test
  return
}

do_test tkt3841.1 {
  execsql {
    CREATE TABLE table2 (key TEXT, x TEXT);
    CREATE TABLE list (key TEXT, value TEXT);
  
    INSERT INTO table2 VALUES ("a", "alist");
    INSERT INTO table2 VALUES ("b", "blist");
    INSERT INTO list VALUES ("a", 1);
    INSERT INTO list VALUES ("a", 2);
    INSERT INTO list VALUES ("a", 3);
    INSERT INTO list VALUES ("b", 4);
    INSERT INTO list VALUES ("b", 5);
    INSERT INTO list VALUES ("b", 6);

    SELECT
      table2.x,
      (SELECT group_concat(list.value)
        FROM list
        WHERE list.key = table2.key)
    FROM table2;
  }
} {alist 1,2,3 blist 4,5,6}

finish_test

Added test/tkt3871.test.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

register_echo_module [sqlite3_connection_pointer db]

do_test tkt3871-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a PRIMARY KEY, b UNIQUE);
  }
  for {set i 0} {$i < 500} {incr i} {
    execsql { INSERT INTO t1 VALUES($i, $i*$i) }
  }
  execsql COMMIT
  execsql { 
    CREATE VIRTUAL TABLE e USING echo(t1);
    SELECT count(*) FROM e;
  }
} {500}

do_test tkt3871-1.2 {
  execsql { SELECT * FROM e WHERE a = 1 OR a = 2 }
} {1 1 2 4}
do_test tkt3871-1.3 {
  set echo_module ""
  execsql { SELECT * FROM e WHERE a = 1 OR a = 2 }
  set echo_module
} [list \
  xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 1 \
  xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 2 \
]

do_test tkt3871-1.4 {
  execsql { SELECT * FROM e WHERE a = 1 OR a = 2 OR b = 9 }
} {1 1 2 4 3 9}
do_test tkt3871-1.5 {
  set echo_module ""
  execsql { SELECT * FROM e WHERE a = 1 OR a = 2 OR b = 9 }
  set echo_module
} [list \
  xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 1 \
  xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 2 \
  xFilter {SELECT rowid, * FROM 't1' WHERE b = ?} 9
]


finish_test

Added test/tkt3879.test.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 2009 May 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to verify ticket #3879 is fixed.
#
# $Id: tkt3879.test,v 1.2 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3879.1.1 {
  execsql {
    CREATE TABLE t1 (a PRIMARY KEY, b);
    INSERT INTO t1 VALUES ('w',  1);
    INSERT INTO t1 VALUES ('z', -1);
  
    CREATE TABLE t2 (m INTEGER PRIMARY KEY, n, a, p);
    INSERT INTO t2 VALUES (25, 13, 'w', 1);
    INSERT INTO t2 VALUES (26, 25, 'z', 153);
    INSERT INTO t2 VALUES (27, 25, 'z', 68);

    CREATE TABLE t3 (m);
    INSERT INTO t3 VALUES (25);
  }
} {}

do_test tkt3879.1.2 {
  execsql {
    SELECT 111, t1.b*123
    FROM t3, t2 AS j0, t2 AS j1, t1
    WHERE j0.m=t3.m AND t1.a=j0.a AND j1.n=j0.m;
  }
} {111 123 111 123}

do_test tkt3879.1.3 {
  execsql {
    SELECT 222, t1.b*123
    FROM t3, t2 AS j0, t2 AS j1, t1
    WHERE j0.m=t3.m AND t1.a=j0.a AND j1.n=j0.m
    ORDER BY t1.b;
  }
} {222 123 222 123}

finish_test

Added test/tkt3911.test.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 2009 June 11
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to verify ticket #3911 is fixed.
#
# $Id: tkt3911.test,v 1.1 2009/06/12 03:27:28 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3911.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(11,12);

    CREATE TABLE t2(b,c);
    INSERT INTO t2 VALUES(2,3);
    INSERT INTO t2 VALUES(22,23);

    SELECT * FROM t1 JOIN t2 USING(b);
  }
} {1 2 3}
do_test tkt3911.2 {
  db eval {
    SELECT * FROM t1 JOIN (t2) AS x USING (b);
  }
} {1 2 3}
do_test tkt3911.3 {
  db eval {
    SELECT * FROM t1 JOIN (SELECT * FROM t2) AS x USING (b);
  }
} {1 2 3}

do_test tkt3911.4 {
  db eval {
    CREATE TABLE t3(m,a);
    INSERT INTO t3 VALUES('one',1);
    INSERT INTO t3 VALUES('two',2);

    SELECT * FROM t3 JOIN (SELECT * FROM t1 NATURAL JOIN t2) AS x USING(a);
  }
} {one 1 2 3}
do_test tkt3911.5 {
  db eval {
    SELECT * FROM t3 JOIN (SELECT * FROM t1 JOIN t2 USING (b)) AS x USING(a);
  }
} {one 1 2 3}

finish_test

Added test/tkt3918.test.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 2009 June 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt3918.test,v 1.1 2009/06/17 11:13:28 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3918.1 {
  execsql {
    PRAGMA page_size = 1024;
    PRAGMA auto_vacuum = incremental;
    CREATE TABLE t1(i, x);
  }
} {}
do_test tkt3918.2 {
  execsql {
    INSERT INTO t1 VALUES(1, randstr(1000,1000));
    INSERT INTO t1 VALUES(2, zeroblob(248*1020 + 100));
    INSERT INTO t1 VALUES(3, zeroblob(2*1020 + 100));
  }
} {}

# This set of statements sets up the free list so that the
# first free-list trunk page contains only a single leaf.
# The leaf page is also the last page in the database. The
# second free-list trunk page contains, amongst other things,
# page number 4.
do_test tkt3918.3 {
  execsql {
    DELETE FROM t1 WHERE i = 2;
    DELETE FROM t1 WHERE i = 1;
    DELETE FROM t1 WHERE i = 3;
  }
} {}

# Incrementally vacuum the database to reduce its size by a single
# page. This will remove the single leaf from the first page in
# the linked list of free-list trunk pages.
do_test tkt3918.4 {
  execsql { PRAGMA incremental_vacuum = 1 }
} {}

# Create another table. This operation will attempt to extract 
# page 4 from the database free-list. Bug 3918 caused sqlite to
# incorrectly report corruption here.
do_test tkt3918.5 {
  execsql { CREATE TABLE t2(a, b) }
} {}

finish_test

Added test/tkt3922.test.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 2009 June 17
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt3922.test,v 1.2 2009/06/26 14:17:47 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

if {[working_64bit_int]} {
  do_test tkt3922.1 {
    execsql {
      CREATE TABLE t1(a NUMBER);
      INSERT INTO t1 VALUES('-9223372036854775808');
      SELECT a, typeof(a) FROM t1;
    }
  } {-9223372036854775808 integer}
} else {
  # this alternate version of tkt3922.1 doesn't
  # really test the same thing as the original, 
  # but is needed to create the table and 
  # provided simply as a place holder for 
  # platforms without working 64bit support.
  do_test tkt3922.1 {
    execsql {
      CREATE TABLE t1(a NUMBER);
      INSERT INTO t1 VALUES('-1');
      SELECT a, typeof(a) FROM t1;
    }
  } {-1 integer}
}
do_test tkt3922.2 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES('-9223372036854775809');
    SELECT a, typeof(a) FROM t1;
  }
} {-9.22337203685478e+18 real}
do_test tkt3922.3 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES('-9223372036854776832');
    SELECT a, typeof(a) FROM t1;
  }
} {-9.22337203685478e+18 real}
do_test tkt3922.4 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES('-9223372036854776833');
    SELECT a, typeof(a) FROM t1;
  }
} {-9.22337203685478e+18 real}
if {[working_64bit_int]} {
  do_test tkt3922.5 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES('9223372036854775807');
      SELECT a, typeof(a) FROM t1;
    }
  } {9223372036854775807 integer}
} else {
  # this alternate version of tkt3922.5 doesn't
  # really test the same thing as the original, 
  # but provided simply as a place holder for 
  # platforms without working 64bit support.
  do_test tkt3922.5 {
    execsql {
      DELETE FROM t1;
      INSERT INTO t1 VALUES('1');
      SELECT a, typeof(a) FROM t1;
    }
  } {1 integer}
}
do_test tkt3922.6 {
  execsql {
    DELETE FROM t1;
    INSERT INTO t1 VALUES('9223372036854775808');
    SELECT a, typeof(a) FROM t1;
  }
} {9.22337203685478e+18 real}

finish_test

Added test/tkt3929.test.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 2009 June 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to verify ticket #3929 is fixed.
#
# $Id: tkt3929.test,v 1.1 2009/06/23 11:53:09 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

do_test tkt3929-1.0 {
  execsql {
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a, b);
    CREATE TRIGGER t1_t1 AFTER INSERT ON t1 BEGIN
      UPDATE t1 SET b = 'value: ' || a WHERE t1.rowid = new.rowid;
    END;
  }
} {}

do_test tkt3929-1.1 {
  execsql {
    INSERT INTO t1(a) VALUES(1);
    INSERT INTO t1(a) VALUES(2);
    SELECT * FROM t1;
  }
} {1 {value: 1} 2 {value: 2}}

# Before it was fixed, the following provoked the bug, causing either an
# assertion failure or a "database is malformed" error.
#
do_test tkt3930-1.2 {
  for {set i 3} {$i < 100} {incr i} {
    execsql { INSERT INTO t1(a) VALUES($i) }
  }
} {}

integrity_check tkt3930-1.3
finish_test

Added test/tkt3935.test.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 2009 July 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #3935 has been fixed.
#
# $Id: tkt3935.test,v 1.2 2009/07/01 16:12:08 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3935.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(c, d);
  }
} {}

do_test tkt3935.2 {
  execsql { SELECT j1.b FROM ( SELECT * FROM t1 INNER JOIN t2 ON a=c ) AS j1 }
} {}
do_test tkt3935.3 {
  execsql { SELECT j1.b FROM (t1 INNER JOIN t2 ON a=c) AS j1 }
} {}


do_test tkt3935.4 {
  catchsql { SELECT a FROM (t1) AS t ON b USING(a) }
} {1 {a JOIN clause is required before ON}}
do_test tkt3935.5 {
  catchsql { SELECT a FROM (t1) AS t ON b }
} {1 {a JOIN clause is required before ON}}
do_test tkt3935.6 {
  catchsql { SELECT a FROM (SELECT * FROM t1) AS t ON b USING(a) }
} {1 {a JOIN clause is required before ON}}
do_test tkt3935.7 {
  catchsql { SELECT a FROM (SELECT * FROM t1) AS t ON b }
} {1 {a JOIN clause is required before ON}}
do_test tkt3935.8 {
  catchsql { SELECT a FROM t1 AS t ON b }
} {1 {a JOIN clause is required before ON}}
do_test tkt3935.9 {
  catchsql { SELECT a FROM t1 AS t ON b USING(a) }
} {1 {a JOIN clause is required before ON}}
do_test tkt3935.10 {
  catchsql { SELECT a FROM t1 AS t USING(a) }
} {1 {a JOIN clause is required before USING}}

finish_test

Added test/tkt3992.test.



































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: tkt3992.test,v 1.1 2009/07/27 10:05:06 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tkt3992-1.1 {
  execsql {
    CREATE TABLE parameters1(
       mountcnt    INT NOT NULL CHECK (typeof(mountcnt) == 'integer'),
       version     REAL NOT NULL
    );
    INSERT INTO parameters1(mountcnt, version) VALUES(1, 1.0);

    CREATE TABLE parameters2(
       mountcnt    INT NOT NULL CHECK (typeof(mountcnt) == 'integer'),
       version     REAL CHECK (typeof(version) == 'real')
    );
    INSERT INTO parameters2(mountcnt, version) VALUES(1, 1.0);
  }
} {}

do_test tkt3992-1.2 {
  execsql {
    UPDATE parameters1 SET mountcnt = mountcnt + 1;
    SELECT * FROM parameters1;
  }
} {2 1.0}

do_test tkt3992-1.3 {
  execsql {
    UPDATE parameters2 SET mountcnt = mountcnt + 1;
    SELECT * FROM parameters2;
  }
} {2 1.0}

ifcapable altertable {
  do_test tkt3992-2.1 {
    execsql {
      CREATE TABLE t1(a, b);
      INSERT INTO t1 VALUES(1, 2);
      ALTER TABLE t1 ADD COLUMN c DEFAULT 3;
      SELECT * FROM t1;
    }
  } {1 2 3}
  do_test tkt3992-2.2 {
    execsql {
      UPDATE t1 SET a = 'one';
      SELECT * FROM t1;
    }
  } {one 2 3}
}

ifcapable trigger {
  db function tcl eval
  do_test tkt3992-2.3 {
    execsql {
      CREATE TABLE t2(a REAL, b REAL, c REAL);
      INSERT INTO t2 VALUES(1, 2, 3);
      CREATE TRIGGER tr2 BEFORE UPDATE ON t2 BEGIN
        SELECT tcl('set res', typeof(new.c));
      END;
  
      UPDATE t2 SET a = 'I';
    }
    set res
  } {real}
}


finish_test

Added test/tkt3997.test.



















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Tests to make sure #3997 is fixed.
#
# $Id: tkt3997.test,v 1.1 2009/07/28 13:30:31 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc reverse {lhs rhs} {
  return [string compare $rhs $lhs]
}
proc usual {lhs rhs} {
  return [string compare $lhs $rhs]
}

db collate reverse reverse
db collate usual usual

do_test tkt3997-1.1 {
  execsql {
    create table mytext(name BLOB);
    INSERT INTO mytext VALUES('abc');
    INSERT INTO mytext VALUES('acd');
    INSERT INTO mytext VALUES('afe');
  }
} {}
do_test tkt3997-1.2 {
  execsql { 
    SELECT name 
    FROM mytext 
    ORDER BY name COLLATE reverse 
  }
} {afe acd abc}
do_test tkt3997-1.3 {
  execsql { 
    SELECT name 
    FROM (SELECT name FROM mytext)  
    ORDER BY name COLLATE reverse 
  }
} {afe acd abc}

do_test tkt3997-2.1 {
  execsql { 
    CREATE TABLE mytext2(name COLLATE reverse);
    INSERT INTO mytext2 SELECT name FROM mytext;
  }
} {}
do_test tkt3997-2.2 {
  execsql { 
    SELECT name 
    FROM (SELECT name FROM mytext2)  
    ORDER BY name
  }
} {afe acd abc}
do_test tkt3997-2.3 {
  execsql { 
    SELECT name 
    FROM (SELECT name FROM mytext2)
    ORDER BY name COLLATE usual
  }
} {abc acd afe}

finish_test

Added test/tkt4018.test.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 2009 August 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #4018 has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc testsql {sql} {
  set fd [open tf_main.tcl w]
  puts $fd [subst -nocommands {
    sqlite3_test_control_pending_byte 0x0010000
    sqlite3 db test.db
    set rc [catch { db eval {$sql} } msg]
    puts -nonewline "[set rc] {[set msg]}"
    flush stdout
    exit
  }]
  close $fd
  set fd [open "| [info nameofexec] ./tf_main.tcl" r] 
  set res [read $fd]
  close $fd
  return $res
}

do_test tkt4018-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    BEGIN;
    SELECT * FROM t1;
  }
} {}

# The database is locked by connection [db]. Open and close a second
# connection to test.db 10000 times. If file-descriptors are not being
# reused, then the process will quickly exceed its maximum number of
# file descriptors (1024 by default on linux).
do_test tkt4018-1.2 {
  for {set i 0} {$i < 10000} {incr i} {
    sqlite3 db2 test.db
    db2 close
  }
} {}

# Now check that connection [db] is still holding a SHARED lock by
# having a second process try to write the db.
do_test tkt4018-1.3 {
  testsql {INSERT INTO t1 VALUES(3, 4)}
} {1 {database is locked}}

# Sanity checking. Have [db] release the lock and then retry the
# INSERT from the previous test case.
do_test tkt4018-1.4 {
  db eval COMMIT
  testsql {INSERT INTO t1 VALUES(3, 4)}
} {0 {}}

# Check that reusing a file descriptor cannot change a read-only 
# connection into a read-write connection.
do_test tkt4018-2.1 {
  sqlite3 db2 test.db
  execsql {INSERT INTO t1 VALUES(1, 2)} db2
} {}
do_test tkt4018-2.2 {
  execsql {
    BEGIN;
    SELECT * FROM t1 ORDER BY a;
  }
} {1 2 3 4}
do_test tkt4018-2.3 {
  db2 close
  sqlite3 db2 test.db -readonly 1
  execsql COMMIT
  catchsql {INSERT INTO t1 VALUES(5, 6)} db2
} {1 {attempt to write a readonly database}}
db2 close

finish_test

Added test/tokenize.test.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 2008 July 7
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script testing the tokenizer
#
# $Id: tokenize.test,v 1.1 2008/07/08 00:06:51 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test tokenize-1.1 {
  catchsql {SELECT 1.0e+}
} {1 {unrecognized token: "1.0e"}}
do_test tokenize-1.2 {
  catchsql {SELECT 1.0E+}
} {1 {unrecognized token: "1.0E"}}
do_test tokenize-1.3 {
  catchsql {SELECT 1.0e-}
} {1 {unrecognized token: "1.0e"}}
do_test tokenize-1.4 {
  catchsql {SELECT 1.0E-}
} {1 {unrecognized token: "1.0E"}}
do_test tokenize-1.5 {
  catchsql {SELECT 1.0e+/}
} {1 {unrecognized token: "1.0e"}}
do_test tokenize-1.6 {
  catchsql {SELECT 1.0E+:}
} {1 {unrecognized token: "1.0E"}}
do_test tokenize-1.7 {
  catchsql {SELECT 1.0e-:}
} {1 {unrecognized token: "1.0e"}}
do_test tokenize-1.8 {
  catchsql {SELECT 1.0E-/}
} {1 {unrecognized token: "1.0E"}}
do_test tokenize-1.9 {
  catchsql {SELECT 1.0F+5}
} {1 {unrecognized token: "1.0F"}}
do_test tokenize-1.10 {
  catchsql {SELECT 1.0d-10}
} {1 {unrecognized token: "1.0d"}}
do_test tokenize-1.11 {
  catchsql {SELECT 1.0e,5}
} {1 {unrecognized token: "1.0e"}}
do_test tokenize-1.12 {
  catchsql {SELECT 1.0E.10}
} {1 {unrecognized token: "1.0E"}}

do_test tokenize-2.1 {
  catchsql {SELECT 1, 2 /*}
} {1 {near "*": syntax error}}
do_test tokenize-2.2 {
  catchsql {SELECT 1, 2 /* }
} {0 {1 2}}


finish_test

Added test/trace.test.























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# 2004 Jun 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for the "sqlite3_trace()" API.
#
# $Id: trace.test,v 1.8 2009/04/07 14:14:23 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !trace {
  finish_test
  return
}

set ::stmtlist {}
do_test trace-1.1 {
  set rc [catch {db trace 1 2 3} msg]
  lappend rc $msg
} {1 {wrong # args: should be "db trace ?CALLBACK?"}}
proc trace_proc cmd {
  lappend ::stmtlist [string trim $cmd]
}
do_test trace-1.2 {
  db trace trace_proc
  db trace
} {trace_proc}
do_test trace-1.3 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    SELECT * FROM t1;
  }
} {1 2}
do_test trace-1.4 {
  set ::stmtlist
} {{CREATE TABLE t1(a,b);} {INSERT INTO t1 VALUES(1,2);} {SELECT * FROM t1;}}
do_test trace-1.5 {
  db trace {}
  db trace
} {}

# If we prepare a statement and execute it multiple times, the trace
# happens on each execution.
#
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test trace-2.1 {
  set STMT [sqlite3_prepare $DB {INSERT INTO t1 VALUES(2,3)} -1 TAIL]
  db trace trace_proc
  proc trace_proc sql {
    global TRACE_OUT
    set TRACE_OUT $sql
  }
  set TRACE_OUT {}
  sqlite3_step $STMT
  set TRACE_OUT
} {INSERT INTO t1 VALUES(2,3)}
do_test trace-2.2 {
  set TRACE_OUT {}
  sqlite3_reset $STMT
  set TRACE_OUT 
} {}
do_test trace-2.3 {
  sqlite3_step $STMT
  set TRACE_OUT
} {INSERT INTO t1 VALUES(2,3)}
do_test trace-2.4 {
  execsql {SELECT * FROM t1}
} {1 2 2 3 2 3}
do_test trace-2.5 {
  set TRACE_OUT
} {SELECT * FROM t1}
catch {sqlite3_finalize $STMT}

# Similar tests, but this time for profiling.
# 
do_test trace-3.1 {
  set rc [catch {db profile 1 2 3} msg]
  lappend rc $msg
} {1 {wrong # args: should be "db profile ?CALLBACK?"}}
set ::stmtlist {}
proc profile_proc {cmd tm} {
  lappend ::stmtlist [string trim $cmd]
}
do_test trace-3.2 {
  db trace {}
  db profile profile_proc
  db profile
} {profile_proc}
do_test trace-3.3 {
  execsql {
    CREATE TABLE t2(a,b);
    INSERT INTO t2 VALUES(1,2);
    SELECT * FROM t2;
  }
} {1 2}
do_test trace-3.4 {
  set ::stmtlist
} {{CREATE TABLE t2(a,b);} {INSERT INTO t2 VALUES(1,2);} {SELECT * FROM t2;}}
do_test trace-3.5 {
  db profile {}
  db profile
} {}

# If we prepare a statement and execute it multiple times, the profile
# happens on each execution.
#
db close
sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
do_test trace-4.1 {
  set STMT [sqlite3_prepare $DB {INSERT INTO t2 VALUES(2,3)} -1 TAIL]
  db trace trace_proc
  proc profile_proc {sql tm} {
    global TRACE_OUT
    set TRACE_OUT $sql
  }
  set TRACE_OUT {}
  sqlite3_step $STMT
  set TRACE_OUT
} {INSERT INTO t2 VALUES(2,3)}
do_test trace-4.2 {
  set TRACE_OUT {}
  sqlite3_reset $STMT
  set TRACE_OUT 
} {}
do_test trace-4.3 {
  sqlite3_step $STMT
  set TRACE_OUT
} {INSERT INTO t2 VALUES(2,3)}
do_test trace-4.4 {
  execsql {SELECT * FROM t1}
} {1 2 2 3 2 3}
do_test trace-4.5 {
  set TRACE_OUT
} {SELECT * FROM t1}
catch {sqlite3_finalize $STMT}

# Trigger tracing.
#
ifcapable trigger {
  do_test trace-5.1 {
    db eval {
      CREATE TRIGGER r1t1 AFTER UPDATE ON t1 BEGIN
        UPDATE t2 SET a=new.a WHERE rowid=new.rowid;
      END;
      CREATE TRIGGER r1t2 AFTER UPDATE ON t2 BEGIN
        SELECT 'hello';
      END;
    }
    set TRACE_OUT {}
    proc trace_proc cmd {
      lappend ::TRACE_OUT [string trim $cmd]
    }
    db eval {
      UPDATE t1 SET a=a+1;
    }
    set TRACE_OUT
  } {{UPDATE t1 SET a=a+1;} {-- TRIGGER r1t1} {-- TRIGGER r1t2} {-- TRIGGER r1t1} {-- TRIGGER r1t2} {-- TRIGGER r1t1} {-- TRIGGER r1t2}}
}

finish_test

Added test/trans.test.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is database locks.
#
# $Id: trans.test,v 1.41 2009/04/28 16:37:59 danielk1977 Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Create several tables to work with.
#
do_test trans-1.0 {
  execsql {
    CREATE TABLE one(a int PRIMARY KEY, b text);
    INSERT INTO one VALUES(1,'one');
    INSERT INTO one VALUES(2,'two');
    INSERT INTO one VALUES(3,'three');
    SELECT b FROM one ORDER BY a;
  }
} {one two three}
integrity_check trans-1.0.1
do_test trans-1.1 {
  execsql {
    CREATE TABLE two(a int PRIMARY KEY, b text);
    INSERT INTO two VALUES(1,'I');
    INSERT INTO two VALUES(5,'V');
    INSERT INTO two VALUES(10,'X');
    SELECT b FROM two ORDER BY a;
  }
} {I V X}
do_test trans-1.9 {
  sqlite3 altdb test.db
  execsql {SELECT b FROM one ORDER BY a} altdb
} {one two three}
do_test trans-1.10 {
  execsql {SELECT b FROM two ORDER BY a} altdb
} {I V X}
integrity_check trans-1.11

# Basic transactions
#
do_test trans-2.1 {
  set v [catch {execsql {BEGIN}} msg]
  lappend v $msg
} {0 {}}
do_test trans-2.2 {
  set v [catch {execsql {END}} msg]
  lappend v $msg
} {0 {}}
do_test trans-2.3 {
  set v [catch {execsql {BEGIN TRANSACTION}} msg]
  lappend v $msg
} {0 {}}
do_test trans-2.4 {
  set v [catch {execsql {COMMIT TRANSACTION}} msg]
  lappend v $msg
} {0 {}}
do_test trans-2.5 {
  set v [catch {execsql {BEGIN TRANSACTION 'foo'}} msg]
  lappend v $msg
} {0 {}}
do_test trans-2.6 {
  set v [catch {execsql {ROLLBACK TRANSACTION 'foo'}} msg]
  lappend v $msg
} {0 {}}
do_test trans-2.10 {
  execsql {
    BEGIN;
    SELECT a FROM one ORDER BY a;
    SELECT a FROM two ORDER BY a;
    END;
  }
} {1 2 3 1 5 10}
integrity_check trans-2.11

# Check the locking behavior
#
do_test trans-3.1 {
  execsql {
    BEGIN;
    UPDATE one SET a = 0 WHERE 0;
    SELECT a FROM one ORDER BY a;
  }
} {1 2 3}
do_test trans-3.2 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 5 10}}

do_test trans-3.3 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3}}
do_test trans-3.4 {
  catchsql {
    INSERT INTO one VALUES(4,'four');
  }
} {0 {}}
do_test trans-3.5 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 5 10}}
do_test trans-3.6 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3}}
do_test trans-3.7 {
  catchsql {
    INSERT INTO two VALUES(4,'IV');
  }
} {0 {}}
do_test trans-3.8 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 5 10}}
do_test trans-3.9 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3}}
do_test trans-3.10 {
  execsql {END TRANSACTION}
} {}

do_test trans-3.11 {
  set v [catch {execsql {
    SELECT a FROM two ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test trans-3.12 {
  set v [catch {execsql {
    SELECT a FROM one ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 2 3 4}}
do_test trans-3.13 {
  set v [catch {execsql {
    SELECT a FROM two ORDER BY a;
  } db} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test trans-3.14 {
  set v [catch {execsql {
    SELECT a FROM one ORDER BY a;
  } db} msg]
  lappend v $msg
} {0 {1 2 3 4}}
integrity_check trans-3.15

do_test trans-4.1 {
  set v [catch {execsql {
    COMMIT;
  } db} msg]
  lappend v $msg
} {1 {cannot commit - no transaction is active}}
do_test trans-4.2 {
  set v [catch {execsql {
    ROLLBACK;
  } db} msg]
  lappend v $msg
} {1 {cannot rollback - no transaction is active}}
do_test trans-4.3 {
  catchsql {
    BEGIN TRANSACTION;
    UPDATE two SET a = 0 WHERE 0;
    SELECT a FROM two ORDER BY a;
  } db
} {0 {1 4 5 10}}
do_test trans-4.4 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 4 5 10}}
do_test trans-4.5 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3 4}}
do_test trans-4.6 {
  catchsql {
    BEGIN TRANSACTION;
    SELECT a FROM one ORDER BY a;
  } db
} {1 {cannot start a transaction within a transaction}}
do_test trans-4.7 {
  catchsql {
    SELECT a FROM two ORDER BY a;
  } altdb
} {0 {1 4 5 10}}
do_test trans-4.8 {
  catchsql {
    SELECT a FROM one ORDER BY a;
  } altdb
} {0 {1 2 3 4}}
do_test trans-4.9 {
  set v [catch {execsql {
    END TRANSACTION;
    SELECT a FROM two ORDER BY a;
  } db} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test trans-4.10 {
  set v [catch {execsql {
    SELECT a FROM two ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 4 5 10}}
do_test trans-4.11 {
  set v [catch {execsql {
    SELECT a FROM one ORDER BY a;
  } altdb} msg]
  lappend v $msg
} {0 {1 2 3 4}}
integrity_check trans-4.12
do_test trans-4.98 {
  altdb close
  execsql {
    DROP TABLE one;
    DROP TABLE two;
  }
} {}
integrity_check trans-4.99

# Check out the commit/rollback behavior of the database
#
do_test trans-5.1 {
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test trans-5.2 {
  execsql {BEGIN TRANSACTION}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test trans-5.3 {
  execsql {CREATE TABLE one(a text, b int)}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {one}
do_test trans-5.4 {
  execsql {SELECT a,b FROM one ORDER BY b}
} {}
do_test trans-5.5 {
  execsql {INSERT INTO one(a,b) VALUES('hello', 1)}
  execsql {SELECT a,b FROM one ORDER BY b}
} {hello 1}
do_test trans-5.6 {
  execsql {ROLLBACK}
  execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name}
} {}
do_test trans-5.7 {
  set v [catch {
    execsql {SELECT a,b FROM one ORDER BY b}
  } msg]
  lappend v $msg
} {1 {no such table: one}}

# Test commits and rollbacks of table CREATE TABLEs, CREATE INDEXs
# DROP TABLEs and DROP INDEXs
#
do_test trans-5.8 {
  execsql {
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name
  }
} {}
do_test trans-5.9 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE t1(a int, b int, c int);
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {t1}
do_test trans-5.10 {
  execsql {
    CREATE INDEX i1 ON t1(a);
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test trans-5.11 {
  execsql {
    COMMIT;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test trans-5.12 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE t2(a int, b int, c int);
    CREATE INDEX i2a ON t2(a);
    CREATE INDEX i2b ON t2(b);
    DROP TABLE t1;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2a i2b t2}
do_test trans-5.13 {
  execsql {
    ROLLBACK;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test trans-5.14 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {t1}
do_test trans-5.15 {
  execsql {
    ROLLBACK;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i1 t1}
do_test trans-5.16 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    CREATE TABLE t2(x int, y int, z int);
    CREATE INDEX i2x ON t2(x);
    CREATE INDEX i2y ON t2(y);
    INSERT INTO t2 VALUES(1,2,3);
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2x i2y t1 t2}
do_test trans-5.17 {
  execsql {
    COMMIT;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2x i2y t1 t2}
do_test trans-5.18 {
  execsql {
    SELECT * FROM t2;
  }
} {1 2 3}
do_test trans-5.19 {
  execsql {
    SELECT x FROM t2 WHERE y=2;
  }
} {1}
do_test trans-5.20 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    DROP TABLE t2;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {}
do_test trans-5.21 {
  set r [catch {execsql {
    SELECT * FROM t2
  }} msg]
  lappend r $msg
} {1 {no such table: t2}}
do_test trans-5.22 {
  execsql {
    ROLLBACK;
    SELECT name fROM sqlite_master 
    WHERE type='table' OR type='index'
    ORDER BY name;
  }
} {i2x i2y t1 t2}
do_test trans-5.23 {
  execsql {
    SELECT * FROM t2;
  }
} {1 2 3}
integrity_check trans-5.23


# Try to DROP and CREATE tables and indices with the same name
# within a transaction.  Make sure ROLLBACK works.
#
do_test trans-6.1 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p,q,r);
    ROLLBACK;
    SELECT * FROM t1;
  }
} {a 1 b 2 c 3}
do_test trans-6.2 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p,q,r);
    COMMIT;
    SELECT * FROM t1;
  }
} {}
do_test trans-6.3 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test trans-6.4 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test trans-6.5 {
  execsql2 {
    ROLLBACK;
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test trans-6.6 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test trans-6.7 {
  catchsql {
    COMMIT;
    SELECT * FROM t1;
  }
} {1 {no such table: t1}}

# Repeat on a table with an automatically generated index.
#
do_test trans-6.10 {
  execsql2 {
    CREATE TABLE t1(a unique,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p unique,q,r);
    ROLLBACK;
    SELECT * FROM t1;
  }
} {a 1 b 2 c 3}
do_test trans-6.11 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(p unique,q,r);
    COMMIT;
    SELECT * FROM t1;
  }
} {}
do_test trans-6.12 {
  execsql2 {
    INSERT INTO t1 VALUES(1,2,3);
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test trans-6.13 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a unique,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test trans-6.14 {
  execsql2 {
    ROLLBACK;
    SELECT * FROM t1;
  }
} {p 1 q 2 r 3}
do_test trans-6.15 {
  execsql2 {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a unique,b,c);
    INSERT INTO t1 VALUES(4,5,6);
    SELECT * FROM t1;
    DROP TABLE t1;
  }
} {a 4 b 5 c 6}
do_test trans-6.16 {
  catchsql {
    COMMIT;
    SELECT * FROM t1;
  }
} {1 {no such table: t1}}

do_test trans-6.20 {
  execsql {
    CREATE TABLE t1(a integer primary key,b,c);
    INSERT INTO t1 VALUES(1,-2,-3);
    INSERT INTO t1 VALUES(4,-5,-6);
    SELECT * FROM t1;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.21 {
  execsql {
    CREATE INDEX i1 ON t1(b);
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.22 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    SELECT * FROM t1 WHERE b<1;
    ROLLBACK;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.23 {
  execsql {
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.24 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}

do_test trans-6.25 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    CREATE INDEX i1 ON t1(c);
    SELECT * FROM t1 WHERE b<1;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.26 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.27 {
  execsql {
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.28 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {1 -2 -3 4 -5 -6}

# The following repeats steps 6.20 through 6.28, but puts a "unique"
# constraint the first field of the table in order to generate an
# automatic index.
#
do_test trans-6.30 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    CREATE TABLE t1(a int unique,b,c);
    COMMIT;
    INSERT INTO t1 VALUES(1,-2,-3);
    INSERT INTO t1 VALUES(4,-5,-6);
    SELECT * FROM t1 ORDER BY a;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.31 {
  execsql {
    CREATE INDEX i1 ON t1(b);
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.32 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    SELECT * FROM t1 WHERE b<1;
    ROLLBACK;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.33 {
  execsql {
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.34 {
  execsql {
    BEGIN TRANSACTION;
    DROP TABLE t1;
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}

do_test trans-6.35 {
  execsql {
    BEGIN TRANSACTION;
    DROP INDEX i1;
    CREATE INDEX i1 ON t1(c);
    SELECT * FROM t1 WHERE b<1;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.36 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.37 {
  execsql {
    DROP INDEX i1;
    SELECT * FROM t1 WHERE c<1;
  }
} {1 -2 -3 4 -5 -6}
do_test trans-6.38 {
  execsql {
    ROLLBACK;
    SELECT * FROM t1 WHERE b<1;
  }
} {4 -5 -6 1 -2 -3}
do_test trans-6.39 {
  execsql {
    SELECT * FROM t1 WHERE c<1;
  }
} {1 -2 -3 4 -5 -6}
integrity_check trans-6.40

# Test to make sure rollback restores the database back to its original
# state.
#
do_test trans-7.1 {
  execsql {BEGIN}
  for {set i 0} {$i<1000} {incr i} {
    set r1 [expr {rand()}]
    set r2 [expr {rand()}]
    set r3 [expr {rand()}]
    execsql "INSERT INTO t2 VALUES($r1,$r2,$r3)"
  }
  execsql {COMMIT}
  set ::checksum [execsql {SELECT md5sum(x,y,z) FROM t2}]
  set ::checksum2 [
    execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
  ]
  execsql {SELECT count(*) FROM t2}
} {1001}
do_test trans-7.2 {
  execsql {SELECT md5sum(x,y,z) FROM t2}
} $checksum
do_test trans-7.2.1 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
do_test trans-7.3 {
  execsql {
    BEGIN;
    DELETE FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test trans-7.4 {
  execsql {
    BEGIN;
    INSERT INTO t2 SELECT * FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test trans-7.5 {
  execsql {
    BEGIN;
    DELETE FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test trans-7.6 {
  execsql {
    BEGIN;
    INSERT INTO t2 SELECT * FROM t2;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test trans-7.7 {
  execsql {
    BEGIN;
    CREATE TABLE t3 AS SELECT * FROM t2;
    INSERT INTO t2 SELECT * FROM t3;
    ROLLBACK;
    SELECT md5sum(x,y,z) FROM t2;
  }
} $checksum
do_test trans-7.8 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
ifcapable tempdb {
  do_test trans-7.9 {
    execsql {
      BEGIN;
      CREATE TEMP TABLE t3 AS SELECT * FROM t2;
      INSERT INTO t2 SELECT * FROM t3;
      ROLLBACK;
      SELECT md5sum(x,y,z) FROM t2;
    }
  } $checksum
}
do_test trans-7.10 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
ifcapable tempdb {
  do_test trans-7.11 {
    execsql {
      BEGIN;
      CREATE TEMP TABLE t3 AS SELECT * FROM t2;
      INSERT INTO t2 SELECT * FROM t3;
      DROP INDEX i2x;
      DROP INDEX i2y;
      CREATE INDEX i3a ON t3(x);
      ROLLBACK;
      SELECT md5sum(x,y,z) FROM t2;
    }
  } $checksum
}
do_test trans-7.12 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
ifcapable tempdb {
  do_test trans-7.13 {
    execsql {
      BEGIN;
      DROP TABLE t2;
      ROLLBACK;
      SELECT md5sum(x,y,z) FROM t2;
    }
  } $checksum
}
do_test trans-7.14 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
integrity_check trans-7.15

# Arrange for another process to begin modifying the database but abort
# and die in the middle of the modification.  Then have this process read
# the database.  This process should detect the journal file and roll it
# back.  Verify that this happens correctly.
#
set fd [open test.tcl w]
puts $fd {
  sqlite3_test_control_pending_byte 0x0010000
  sqlite3 db test.db
  db eval {
    PRAGMA default_cache_size=20;
    BEGIN;
    CREATE TABLE t3 AS SELECT * FROM t2;
    DELETE FROM t2;
  }
  sqlite_abort
}
close $fd
do_test trans-8.1 {
  catch {exec [info nameofexec] test.tcl}
  execsql {SELECT md5sum(x,y,z) FROM t2}
} $checksum
do_test trans-8.2 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
integrity_check trans-8.3
set fd [open test.tcl w]
puts $fd {
  sqlite3_test_control_pending_byte 0x0010000
  sqlite3 db test.db
  db eval {
    PRAGMA journal_mode=persist;
    PRAGMA default_cache_size=20;
    BEGIN;
    CREATE TABLE t3 AS SELECT * FROM t2;
    DELETE FROM t2;
  }
  sqlite_abort
}
close $fd
do_test trans-8.4 {
  catch {exec [info nameofexec] test.tcl}
  execsql {SELECT md5sum(x,y,z) FROM t2}
} $checksum
do_test trans-8.5 {
  execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master}
} $checksum2
integrity_check trans-8.6


# In the following sequence of tests, compute the MD5 sum of the content
# of a table, make lots of modifications to that table, then do a rollback.
# Verify that after the rollback, the MD5 checksum is unchanged.
#
do_test trans-9.1 {
  execsql {
    PRAGMA default_cache_size=10;
  }
  db close
  sqlite3 db test.db
  execsql {
    BEGIN;
    CREATE TABLE t3(x TEXT);
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 VALUES(randstr(10,400));
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    INSERT INTO t3 SELECT randstr(10,400) FROM t3;
    COMMIT;
    SELECT count(*) FROM t3;
  }
} {1024}

# The following procedure computes a "signature" for table "t3".  If
# T3 changes in any way, the signature should change.  
#
# This is used to test ROLLBACK.  We gather a signature for t3, then
# make lots of changes to t3, then rollback and take another signature.
# The two signatures should be the same.
#
proc signature {} {
  return [db eval {SELECT count(*), md5sum(x) FROM t3}]
}

# Repeat the following group of tests 20 times for quick testing and
# 40 times for full testing.  Each iteration of the test makes table
# t3 a little larger, and thus takes a little longer, so doing 40 tests
# is more than 2.0 times slower than doing 20 tests.  Considerably more.
#
# Also, if temporary tables are stored in memory and the test pcache
# is in use, only 20 iterations. Otherwise the test pcache runs out
# of page slots and SQLite reports "out of memory".
#
if {[info exists ISQUICK] || (
  $TEMP_STORE==3 && [catch {set ::permutations_test_prefix} val]==0 && 
  [regexp {^pcache[[:digit:]]*$} $val]
) } {
  set limit 20
} elseif {[info exists SOAKTEST]} {
  set limit 100
} else {
  set limit 40
}

# Do rollbacks.  Make sure the signature does not change.
#
for {set i 2} {$i<=$limit} {incr i} {
  set ::sig [signature]
  set cnt [lindex $::sig 0]
  if {$i%2==0} {
    execsql {PRAGMA fullfsync=ON}
  } else {
    execsql {PRAGMA fullfsync=OFF}
  }
  set sqlite_sync_count 0
  set sqlite_fullsync_count 0
  do_test trans-9.$i.1-$cnt {
     execsql {
       BEGIN;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       ROLLBACK;
     }
     signature
  } $sig
  do_test trans-9.$i.2-$cnt {
     execsql {
       BEGIN;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       DELETE FROM t3 WHERE random()%10!=0;
       INSERT INTO t3 SELECT randstr(10,10)||x FROM t3;
       ROLLBACK;
     }
     signature
  } $sig
  if {$i<$limit} {
    do_test trans-9.$i.3-$cnt {
       execsql {
         INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0;
       }
    } {}
    if {$tcl_platform(platform)=="unix"} {
      do_test trans-9.$i.4-$cnt {
         expr {$sqlite_sync_count>0}
      } 1
      ifcapable pager_pragmas {
        do_test trans-9.$i.5-$cnt {
           expr {$sqlite_fullsync_count>0}
        } [expr {$i%2==0}]
      } else {
        do_test trans-9.$i.5-$cnt {
          expr {$sqlite_fullsync_count==0}
        } {1}
      }
    }
  }
  set ::pager_old_format 0
}
   
finish_test

Added test/trans2.test.

















































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# 2008 August 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this script is transactions
#
# $Id: trans2.test,v 1.1 2008/08/27 18:56:36 drh Exp $
#
set testdir [file dirname $argv0]
source $testdir/tester.tcl

# A procedure to scramble the elements of list $inlist into a random order.
#
proc scramble {inlist} {
  set y {}
  foreach x $inlist {
    lappend y [list [expr {rand()}] $x]
  }
  set y [lsort $y]
  set outlist {}
  foreach x $y {
    lappend outlist [lindex $x 1]
  }
  return $outlist
}

# Generate a UUID using randomness.
#
expr srand(1)
proc random_uuid {} {
  set u {}
  for {set i 0} {$i<5} {incr i} {
    append u [format %06x [expr {int(rand()*16777216)}]]
  }
  return $u
}

# Compute hashes on the u1 and u2 fields of the sample data.
#
proc hash1 {} {
  global data
  set x ""
  foreach rec [lsort -integer -index 0 $data] {
    append x [lindex $rec 1]
  }
  return [md5 $x]
}
proc hash2 {} {
  global data
  set x ""
  foreach rec [lsort -integer -index 0 $data] {
    append x [lindex $rec 3]
  }
  return [md5 $x]
}

# Create the initial data set
#
unset -nocomplain data i max_rowid todel n rec max1 id origres newres
unset -nocomplain inssql modsql s j z
set data {}
for {set i 0} {$i<400} {incr i} {
  set rec [list $i [random_uuid] [expr {int(rand()*5000)+1000}] [random_uuid]]
  lappend data $rec
}
set max_rowid [expr {$i-1}]

# Create the T1 table used to hold test data.  Populate that table with
# the initial data set and check hashes to make sure everything is correct.
#
do_test trans2-1.1 {
  execsql {
    PRAGMA cache_size=100;
    CREATE TABLE t1(
      id INTEGER PRIMARY KEY,
      u1 TEXT UNIQUE,
      z BLOB NOT NULL,
      u2 TEXT UNIQUE
    );
  }
  foreach rec [scramble $data] {
    foreach {id u1 z u2} $rec break
    db eval {INSERT INTO t1 VALUES($id,$u1,zeroblob($z),$u2)}
  }
  db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
} [list [hash1] [hash2]]

# Repeat the main test loop multiple times.
#
for {set i 2} {$i<=30} {incr i} {
  # Delete one row out of every 10 in the database.  This will add
  # many pages to the freelist.
  #
  set todel {}
  set n [expr {[llength $data]/10}]
  set data [scramble $data]
  foreach rec [lrange $data 0 $n] {
    lappend todel [lindex $rec 0]
  }
  set data [lrange $data [expr {$n+1}] end]
  set max1 [lindex [lindex $data 0] 0]
  foreach rec $data {
    set id [lindex $rec 0]
    if {$id>$max1} {set max1 $id}
  }
  set origres [list [hash1] [hash2]]
  do_test trans2-$i.1 {
    db eval "DELETE FROM t1 WHERE id IN ([join $todel ,])"
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $origres
  integrity_check trans2-$i.2

  # Begin a transaction and insert many new records.
  #
  set newdata {}
  foreach id $todel {
    set rec [list $id [random_uuid] \
                      [expr {int(rand()*5000)+1000}] [random_uuid]]
    lappend newdata $rec
    lappend data $rec
  }
  for {set j 1} {$j<50} {incr j} {
    set id [expr {$max_rowid+$j}]
    lappend todel $id
    set rec [list $id [random_uuid] \
                      [expr {int(rand()*5000)+1000}] [random_uuid]]
    lappend newdata $rec
    lappend data $rec
  }
  set max_rowid [expr {$max_rowid+$j-1}]
  set modsql {}
  set inssql {}
  set newres [list [hash1] [hash2]]
  do_test trans2-$i.3 {
    db eval BEGIN
    foreach rec [scramble $newdata] {
      foreach {id u1 z u2} $rec break
      set s "INSERT INTO t1 VALUES($id,'$u1',zeroblob($z),'$u2');"
      append modsql $s\n
      append inssql $s\n
      db eval $s
    }
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $newres
  integrity_check trans2-$i.4

  # Do a large update that aborts do to a constraint failure near
  # the end.  This stresses the statement journal mechanism.
  #
  do_test trans2-$i.10 {
    catchsql {
      UPDATE t1 SET u1=u1||'x',
          z = CASE WHEN id<$max_rowid
                   THEN zeroblob((random()&65535)%5000 + 1000) END;
    }
  } {1 {t1.z may not be NULL}}
  do_test trans2-$i.11 {
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $newres

  # Delete all of the newly inserted records.  Verify that the database
  # is back to its original state.
  #
  do_test trans2-$i.20 {
    set s "DELETE FROM t1 WHERE id IN ([join $todel ,]);"
    append modsql $s\n
    db eval $s
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $origres

  # Do another large update that aborts do to a constraint failure near
  # the end.  This stresses the statement journal mechanism.
  #
  do_test trans2-$i.30 {
    catchsql {
      UPDATE t1 SET u1=u1||'x',
          z = CASE WHEN id<$max1
                   THEN zeroblob((random()&65535)%5000 + 1000) END;
    }
  } {1 {t1.z may not be NULL}}
  do_test trans2-$i.31 {
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $origres

  # Redo the inserts
  #
  do_test trans2-$i.40 {
    db eval $inssql
    append modsql $inssql
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $newres

  # Rollback the transaction.  Verify that the content is restored.
  #
  do_test trans2-$i.90 {
    db eval ROLLBACK
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $origres
  integrity_check trans2-$i.91

  # Repeat all the changes, but this time commit.
  #
  do_test trans2-$i.92 {
    db eval BEGIN
    catchsql {
      UPDATE t1 SET u1=u1||'x',
          z = CASE WHEN id<$max1
                   THEN zeroblob((random()&65535)%5000 + 1000) END;
    }
    db eval $modsql
    catchsql {
      UPDATE t1 SET u1=u1||'x',
          z = CASE WHEN id<$max1
                   THEN zeroblob((random()&65535)%5000 + 1000) END;
    }
    db eval COMMIT
    db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id}
  } $newres
  integrity_check trans2-$i.93
}

unset -nocomplain data i max_rowid todel n rec max1 id origres newres
unset -nocomplain inssql modsql s j z
finish_test

Added test/trans3.test.



























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 2008 November 3
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file implements regression tests for SQLite library.  The
# focus of this script is the response of COMMIT and ROLLBACK when
# statements are still pending.
#
# $Id: trans3.test,v 1.2 2008/11/05 16:37:35 drh Exp $
#
set testdir [file dirname $argv0]
source $testdir/tester.tcl
unset -nocomplain ecode

do_test trans3-1.1 {
  db eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES(3);
    SELECT * FROM t1;
  }
} {1 2 3}
do_test trans3-1.2 {
  db eval BEGIN
  db eval {INSERT INTO t1 VALUES(4);}
  set ::ecode {}
  set x [catch {
     db eval {SELECT * FROM t1 LIMIT 1} {
        if {[catch {db eval COMMIT} errmsg]} {
           set ::ecode [sqlite3_extended_errcode db]
           error $errmsg
        }
     }
  } errmsg]
  lappend x $errmsg
} {0 {}}
do_test trans3-1.3 {
  set ::ecode
} {}
do_test trans3-1.3.1 {
  sqlite3_get_autocommit db
} 1
do_test trans3-1.4 {
  db eval {SELECT * FROM t1}
} {1 2 3 4}
do_test trans3-1.5 {
  db eval BEGIN
  db eval {INSERT INTO t1 VALUES(5);}
  set ::ecode {}
  set x [catch {
     db eval {SELECT * FROM t1} {
        if {[catch {db eval ROLLBACK} errmsg]} {
           set ::ecode [sqlite3_extended_errcode db]
           error $errmsg
        }
     }
  } errmsg]
  lappend x $errmsg
} {1 {cannot rollback transaction - SQL statements in progress}}
do_test trans3-1.6 {
  set ::ecode
} {SQLITE_BUSY}
do_test trans3-1.7 {
  db eval COMMIT
  db eval {SELECT * FROM t1}
} {1 2 3 4 5}
unset -nocomplain ecode

finish_test

Added test/trigger1.test.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests creating and dropping triggers, and interaction thereof
# with the database COMMIT/ROLLBACK logic.
#
# 1. CREATE and DROP TRIGGER tests
# trig-1.1: Error if table does not exist
# trig-1.2: Error if trigger already exists
# trig-1.3: Created triggers are deleted if the transaction is rolled back
# trig-1.4: DROP TRIGGER removes trigger
# trig-1.5: Dropped triggers are restored if the transaction is rolled back
# trig-1.6: Error if dropped trigger doesn't exist
# trig-1.7: Dropping the table automatically drops all triggers
# trig-1.8: A trigger created on a TEMP table is not inserted into sqlite_master
# trig-1.9: Ensure that we cannot create a trigger on sqlite_master
# trig-1.10:
# trig-1.11:
# trig-1.12: Ensure that INSTEAD OF triggers cannot be created on tables
# trig-1.13: Ensure that AFTER triggers cannot be created on views
# trig-1.14: Ensure that BEFORE triggers cannot be created on views
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

do_test trigger1-1.1.1 {
   catchsql {
     CREATE TRIGGER trig UPDATE ON no_such_table BEGIN
       SELECT * from sqlite_master;
     END;
   } 
} {1 {no such table: main.no_such_table}}

ifcapable tempdb {
  do_test trigger1-1.1.2 {
     catchsql {
       CREATE TEMP TRIGGER trig UPDATE ON no_such_table BEGIN
         SELECT * from sqlite_master;
       END;
     } 
  } {1 {no such table: no_such_table}}
}

execsql {
    CREATE TABLE t1(a);
}
do_test trigger1-1.1.3 {
  catchsql {
     CREATE TRIGGER trig UPDATE ON t1 FOR EACH STATEMENT BEGIN
        SELECT * FROM sqlite_master;
     END;
  }
} {1 {near "STATEMENT": syntax error}}
execsql {
        CREATE TRIGGER tr1 INSERT ON t1 BEGIN
          INSERT INTO t1 values(1);
         END;
}
do_test trigger1-1.2.0 {
    catchsql {
        CREATE TRIGGER IF NOT EXISTS tr1 DELETE ON t1 BEGIN
            SELECT * FROM sqlite_master;
         END
     }
} {0 {}}
do_test trigger1-1.2.1 {
    catchsql {
        CREATE TRIGGER tr1 DELETE ON t1 BEGIN
            SELECT * FROM sqlite_master;
         END
     }
} {1 {trigger tr1 already exists}}
do_test trigger1-1.2.2 {
    catchsql {
        CREATE TRIGGER "tr1" DELETE ON t1 BEGIN
            SELECT * FROM sqlite_master;
         END
     }
} {1 {trigger "tr1" already exists}}
do_test trigger1-1.2.3 {
    catchsql {
        CREATE TRIGGER [tr1] DELETE ON t1 BEGIN
            SELECT * FROM sqlite_master;
         END
     }
} {1 {trigger [tr1] already exists}}

do_test trigger1-1.3 {
    catchsql {
        BEGIN;
        CREATE TRIGGER tr2 INSERT ON t1 BEGIN
            SELECT * from sqlite_master; END;
        ROLLBACK;
        CREATE TRIGGER tr2 INSERT ON t1 BEGIN
            SELECT * from sqlite_master; END;
    }
} {0 {}}

do_test trigger1-1.4 {
    catchsql {
        DROP TRIGGER IF EXISTS tr1;
        CREATE TRIGGER tr1 DELETE ON t1 BEGIN
            SELECT * FROM sqlite_master;
        END
    }
} {0 {}}

do_test trigger1-1.5 {
    execsql {
        BEGIN;
        DROP TRIGGER tr2;
        ROLLBACK;
        DROP TRIGGER tr2;
    }
} {}

do_test trigger1-1.6.1 {
    catchsql {
        DROP TRIGGER IF EXISTS biggles;
    }
} {0 {}}

do_test trigger1-1.6.2 {
    catchsql {
        DROP TRIGGER biggles;
    }
} {1 {no such trigger: biggles}}

do_test trigger1-1.7 {
    catchsql {
        DROP TABLE t1;
        DROP TRIGGER tr1;
    }
} {1 {no such trigger: tr1}}

ifcapable tempdb {
  execsql {
    CREATE TEMP TABLE temp_table(a);
  }
  do_test trigger1-1.8 {
    execsql {
          CREATE TRIGGER temp_trig UPDATE ON temp_table BEGIN
              SELECT * from sqlite_master;
          END;
          SELECT count(*) FROM sqlite_master WHERE name = 'temp_trig';
    } 
  } {0}
}

do_test trigger1-1.9 {
  catchsql {
    CREATE TRIGGER tr1 AFTER UPDATE ON sqlite_master BEGIN
       SELECT * FROM sqlite_master;
    END;
  }
} {1 {cannot create trigger on system table}}

# Check to make sure that a DELETE statement within the body of
# a trigger does not mess up the DELETE that caused the trigger to
# run in the first place.
#
do_test trigger1-1.10 {
  execsql {
    create table t1(a,b);
    insert into t1 values(1,'a');
    insert into t1 values(2,'b');
    insert into t1 values(3,'c');
    insert into t1 values(4,'d');
    create trigger r1 after delete on t1 for each row begin
      delete from t1 WHERE a=old.a+2;
    end;
    delete from t1 where a=1 OR a=3;
    select * from t1;
    drop table t1;
  }
} {2 b 4 d}

do_test trigger1-1.11 {
  execsql {
    create table t1(a,b);
    insert into t1 values(1,'a');
    insert into t1 values(2,'b');
    insert into t1 values(3,'c');
    insert into t1 values(4,'d');
    create trigger r1 after update on t1 for each row begin
      delete from t1 WHERE a=old.a+2;
    end;
    update t1 set b='x-' || b where a=1 OR a=3;
    select * from t1;
    drop table t1;
  }
} {1 x-a 2 b 4 d}

# Ensure that we cannot create INSTEAD OF triggers on tables
do_test trigger1-1.12 {
  catchsql {
    create table t1(a,b);
    create trigger t1t instead of update on t1 for each row begin
      delete from t1 WHERE a=old.a+2;
    end;
  }
} {1 {cannot create INSTEAD OF trigger on table: main.t1}}

ifcapable view {
# Ensure that we cannot create BEFORE triggers on views
do_test trigger1-1.13 {
  catchsql {
    create view v1 as select * from t1;
    create trigger v1t before update on v1 for each row begin
      delete from t1 WHERE a=old.a+2;
    end;
  }
} {1 {cannot create BEFORE trigger on view: main.v1}}
# Ensure that we cannot create AFTER triggers on views
do_test trigger1-1.14 {
  catchsql {
    drop view v1;
    create view v1 as select * from t1;
    create trigger v1t AFTER update on v1 for each row begin
      delete from t1 WHERE a=old.a+2;
    end;
  }
} {1 {cannot create AFTER trigger on view: main.v1}}
} ;# ifcapable view

# Check for memory leaks in the trigger parser
#
do_test trigger1-2.1 {
  catchsql {
    CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN
      SELECT * FROM;  -- Syntax error
    END;
  }
} {1 {near ";": syntax error}}
do_test trigger1-2.2 {
  catchsql {
    CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN
      SELECT * FROM t1;
      SELECT * FROM;  -- Syntax error
    END;
  }
} {1 {near ";": syntax error}}

# Create a trigger that refers to a table that might not exist.
#
ifcapable tempdb {
  do_test trigger1-3.1 {
    execsql {
      CREATE TEMP TABLE t2(x,y);
    }
    catchsql {
      CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN
        INSERT INTO t2 VALUES(NEW.a,NEW.b);
      END;
    }
  } {0 {}}
  do_test trigger-3.2 {
    catchsql {
      INSERT INTO t1 VALUES(1,2);
      SELECT * FROM t2;
    }
  } {1 {no such table: main.t2}}
  do_test trigger-3.3 {
    db close
    set rc [catch {sqlite3 db test.db} err]
    if {$rc} {lappend rc $err}
    set rc
  } {0}
  do_test trigger-3.4 {
    catchsql {
      INSERT INTO t1 VALUES(1,2);
      SELECT * FROM t2;
    }
  } {1 {no such table: main.t2}}
  do_test trigger-3.5 {
    catchsql {
      CREATE TEMP TABLE t2(x,y);
      INSERT INTO t1 VALUES(1,2);
      SELECT * FROM t2;
    }
  } {1 {no such table: main.t2}}
  do_test trigger-3.6 {
    catchsql {
      DROP TRIGGER r1;
      CREATE TEMP TRIGGER r1 AFTER INSERT ON t1 BEGIN
        INSERT INTO t2 VALUES(NEW.a,NEW.b);
      END;
      INSERT INTO t1 VALUES(1,2);
      SELECT * FROM t2;
    }
  } {0 {1 2}}
  do_test trigger-3.7 {
    execsql {
      DROP TABLE t2;
      CREATE TABLE t2(x,y);
      SELECT * FROM t2;
    }
  } {}

  # There are two versions of trigger-3.8 and trigger-3.9. One that uses
  # compound SELECT statements, and another that does not.
  ifcapable compound {
  do_test trigger1-3.8 {
    execsql {
      INSERT INTO t1 VALUES(3,4);
      SELECT * FROM t1 UNION ALL SELECT * FROM t2;
    }
  } {1 2 3 4 3 4}
  do_test trigger1-3.9 {
    db close
    sqlite3 db test.db
    execsql {
      INSERT INTO t1 VALUES(5,6);
      SELECT * FROM t1 UNION ALL SELECT * FROM t2;
    }
  } {1 2 3 4 5 6 3 4}
  } ;# ifcapable compound
  ifcapable !compound {
  do_test trigger1-3.8 {
    execsql {
      INSERT INTO t1 VALUES(3,4);
      SELECT * FROM t1; 
      SELECT * FROM t2;
    }
  } {1 2 3 4 3 4}
  do_test trigger1-3.9 {
    db close
    sqlite3 db test.db
    execsql {
      INSERT INTO t1 VALUES(5,6);
      SELECT * FROM t1;
      SELECT * FROM t2;
    }
  } {1 2 3 4 5 6 3 4}
  } ;# ifcapable !compound

  do_test trigger1-4.1 {
    execsql {
      CREATE TEMP TRIGGER r1 BEFORE INSERT ON t1 BEGIN
        INSERT INTO t2 VALUES(NEW.a,NEW.b);
      END;
      INSERT INTO t1 VALUES(7,8);
      SELECT * FROM t2;
    }
  } {3 4 7 8}
  do_test trigger1-4.2 {
    sqlite3 db2 test.db
    execsql {
      INSERT INTO t1 VALUES(9,10);
    } db2;
    db2 close
    execsql {
      SELECT * FROM t2;
    }
  } {3 4 7 8}
  do_test trigger1-4.3 {
    execsql {
      DROP TABLE t1;
      SELECT * FROM t2;
    };
  } {3 4 7 8}
  do_test trigger1-4.4 {
    db close
    sqlite3 db test.db
    execsql {
      SELECT * FROM t2;
    };
  } {3 4 7 8}
} else {
  execsql {
    CREATE TABLE t2(x,y);
    DROP TABLE t1;
    INSERT INTO t2 VALUES(3, 4);
    INSERT INTO t2 VALUES(7, 8);
  }
}


integrity_check trigger1-5.1

# Create a trigger with the same name as a table.  Make sure the
# trigger works.  Then drop the trigger.  Make sure the table is
# still there.
#
set view_v1 {}
ifcapable view {
  set view_v1 {view v1}
}
do_test trigger1-6.1 {
  execsql {SELECT type, name FROM sqlite_master}
} [concat $view_v1 {table t2}]
do_test trigger1-6.2 {
  execsql {
    CREATE TRIGGER t2 BEFORE DELETE ON t2 BEGIN
      SELECT RAISE(ABORT,'deletes are not permitted');
    END;
    SELECT type, name FROM sqlite_master;
  }
} [concat $view_v1 {table t2 trigger t2}]
do_test trigger1-6.3 {
  catchsql {DELETE FROM t2}
} {1 {deletes are not permitted}}
do_test trigger1-6.4 {
  execsql {SELECT * FROM t2}
} {3 4 7 8}
do_test trigger1-6.5 {
  db close
  sqlite3 db test.db
  execsql {SELECT type, name FROM sqlite_master}
} [concat $view_v1 {table t2 trigger t2}]
do_test trigger1-6.6 {
  execsql {
    DROP TRIGGER t2;
    SELECT type, name FROM sqlite_master;
  }
} [concat $view_v1 {table t2}]
do_test trigger1-6.7 {
  execsql {SELECT * FROM t2}
} {3 4 7 8}
do_test trigger1-6.8 {
  db close
  sqlite3 db test.db
  execsql {SELECT * FROM t2}
} {3 4 7 8}

integrity_check trigger-7.1

# Check to make sure the name of a trigger can be quoted so that keywords
# can be used as trigger names.  Ticket #468
#
do_test trigger1-8.1 {
  execsql {
    CREATE TRIGGER 'trigger' AFTER INSERT ON t2 BEGIN SELECT 1; END;
    SELECT name FROM sqlite_master WHERE type='trigger';
  }
} {trigger}
do_test trigger1-8.2 {
  execsql {
    DROP TRIGGER 'trigger';
    SELECT name FROM sqlite_master WHERE type='trigger';
  }
} {}
do_test trigger1-8.3 {
  execsql {
    CREATE TRIGGER "trigger" AFTER INSERT ON t2 BEGIN SELECT 1; END;
    SELECT name FROM sqlite_master WHERE type='trigger';
  }
} {trigger}
do_test trigger1-8.4 {
  execsql {
    DROP TRIGGER "trigger";
    SELECT name FROM sqlite_master WHERE type='trigger';
  }
} {}
do_test trigger1-8.5 {
  execsql {
    CREATE TRIGGER [trigger] AFTER INSERT ON t2 BEGIN SELECT 1; END;
    SELECT name FROM sqlite_master WHERE type='trigger';
  }
} {trigger}
do_test trigger1-8.6 {
  execsql {
    DROP TRIGGER [trigger];
    SELECT name FROM sqlite_master WHERE type='trigger';
  }
} {}

ifcapable conflict {
  # Make sure REPLACE works inside of triggers.
  #
  # There are two versions of trigger-9.1 and trigger-9.2. One that uses
  # compound SELECT statements, and another that does not.
  ifcapable compound {
    do_test trigger1-9.1 {
      execsql {
        CREATE TABLE t3(a,b);
        CREATE TABLE t4(x UNIQUE, b);
        CREATE TRIGGER r34 AFTER INSERT ON t3 BEGIN
          REPLACE INTO t4 VALUES(new.a,new.b);
        END;
        INSERT INTO t3 VALUES(1,2);
        SELECT * FROM t3 UNION ALL SELECT 99, 99 UNION ALL SELECT * FROM t4;
      }
    } {1 2 99 99 1 2}
    do_test trigger1-9.2 {
      execsql {
        INSERT INTO t3 VALUES(1,3);
        SELECT * FROM t3 UNION ALL SELECT 99, 99 UNION ALL SELECT * FROM t4;
      }
    } {1 2 1 3 99 99 1 3}
  } else {
    do_test trigger1-9.1 {
      execsql {
        CREATE TABLE t3(a,b);
        CREATE TABLE t4(x UNIQUE, b);
        CREATE TRIGGER r34 AFTER INSERT ON t3 BEGIN
          REPLACE INTO t4 VALUES(new.a,new.b);
        END;
        INSERT INTO t3 VALUES(1,2);
        SELECT * FROM t3; SELECT 99, 99; SELECT * FROM t4;
      }
    } {1 2 99 99 1 2}
    do_test trigger1-9.2 {
      execsql {
        INSERT INTO t3 VALUES(1,3);
        SELECT * FROM t3; SELECT 99, 99; SELECT * FROM t4;
      }
    } {1 2 1 3 99 99 1 3}
  }
  execsql {
    DROP TABLE t3;
    DROP TABLE t4;
  }
}


# Ticket #764. At one stage TEMP triggers would fail to re-install when the
# schema was reloaded. The following tests ensure that TEMP triggers are
# correctly re-installed.
#
# Also verify that references within trigger programs are resolved at
# statement compile time, not trigger installation time. This means, for
# example, that you can drop and re-create tables referenced by triggers. 
ifcapable tempdb&&attach {
  do_test trigger1-10.0 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      ATTACH 'test2.db' AS aux;
    }
  } {}
  do_test trigger1-10.1 {
    execsql {
      CREATE TABLE main.t4(a, b, c);
      CREATE TABLE temp.t4(a, b, c);
      CREATE TABLE aux.t4(a, b, c);
      CREATE TABLE insert_log(db, a, b, c);
    }
  } {}
  do_test trigger1-10.2 {
    execsql {
      CREATE TEMP TRIGGER trig1 AFTER INSERT ON main.t4 BEGIN 
        INSERT INTO insert_log VALUES('main', new.a, new.b, new.c);
      END;
      CREATE TEMP TRIGGER trig2 AFTER INSERT ON temp.t4 BEGIN 
        INSERT INTO insert_log VALUES('temp', new.a, new.b, new.c);
      END;
      CREATE TEMP TRIGGER trig3 AFTER INSERT ON aux.t4 BEGIN 
        INSERT INTO insert_log VALUES('aux', new.a, new.b, new.c);
      END;
    }
  } {}
  do_test trigger1-10.3 {
    execsql {
      INSERT INTO main.t4 VALUES(1, 2, 3);
      INSERT INTO temp.t4 VALUES(4, 5, 6);
      INSERT INTO aux.t4  VALUES(7, 8, 9);
    }
  } {}
  do_test trigger1-10.4 {
    execsql {
      SELECT * FROM insert_log;
    }
  } {main 1 2 3 temp 4 5 6 aux 7 8 9}
  do_test trigger1-10.5 {
    execsql {
      BEGIN;
      INSERT INTO main.t4 VALUES(1, 2, 3);
      INSERT INTO temp.t4 VALUES(4, 5, 6);
      INSERT INTO aux.t4  VALUES(7, 8, 9);
      ROLLBACK;
    }
  } {}
  do_test trigger1-10.6 {
    execsql {
      SELECT * FROM insert_log;
    }
  } {main 1 2 3 temp 4 5 6 aux 7 8 9}
  do_test trigger1-10.7 {
    execsql {
      DELETE FROM insert_log;
      INSERT INTO main.t4 VALUES(11, 12, 13);
      INSERT INTO temp.t4 VALUES(14, 15, 16);
      INSERT INTO aux.t4  VALUES(17, 18, 19);
    }
  } {}
  do_test trigger1-10.8 {
    execsql {
      SELECT * FROM insert_log;
    }
  } {main 11 12 13 temp 14 15 16 aux 17 18 19}
  do_test trigger1-10.8 {
  # Drop and re-create the insert_log table in a different database. Note
  # that we can change the column names because the trigger programs don't
  # use them explicitly.
    execsql {
      DROP TABLE insert_log;
      CREATE TABLE aux.insert_log(db, d, e, f);
    }
  } {}
  do_test trigger1-10.10 {
    execsql {
      INSERT INTO main.t4 VALUES(21, 22, 23);
      INSERT INTO temp.t4 VALUES(24, 25, 26);
      INSERT INTO aux.t4  VALUES(27, 28, 29);
    }
  } {}
  do_test trigger1-10.11 {
    execsql {
      SELECT * FROM insert_log;
    }
  } {main 21 22 23 temp 24 25 26 aux 27 28 29}
}

do_test trigger1-11.1 {
  catchsql {SELECT raise(abort,'message');}
} {1 {RAISE() may only be used within a trigger-program}}

do_test trigger1-15.1 {
  execsql {
    CREATE TABLE tA(a INTEGER PRIMARY KEY, b, c);
    CREATE TRIGGER tA_trigger BEFORE UPDATE ON "tA" BEGIN SELECT 1; END;
    INSERT INTO tA VALUES(1, 2, 3);
  }
  catchsql { UPDATE tA SET a = 'abc' }
} {1 {datatype mismatch}}
do_test trigger1-15.2 {
  catchsql { INSERT INTO tA VALUES('abc', 2, 3) }
} {1 {datatype mismatch}}

# Ticket #3947:  Do not allow qualified table names on INSERT, UPDATE, and
# DELETE statements within triggers.  Actually, this has never been allowed
# by the grammar.  But the error message is confusing: one simply gets a
# "syntax error".  That has now been changed to give a full error message.
#
do_test trigger1-16.1 {
  db eval {
    CREATE TABLE t16(a,b,c);
    CREATE INDEX t16a ON t16(a);
    CREATE INDEX t16b ON t16(b);
  }
  catchsql {
    CREATE TRIGGER main.t16err1 AFTER INSERT ON tA BEGIN
      INSERT INTO main.t16 VALUES(1,2,3);
    END;
  }
} {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}}
do_test trigger1-16.2 {
  catchsql {
    CREATE TRIGGER main.t16err2 AFTER INSERT ON tA BEGIN
      UPDATE main.t16 SET rowid=rowid+1;
    END;
  }
} {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}}
do_test trigger1-16.3 {
  catchsql {
    CREATE TRIGGER main.t16err3 AFTER INSERT ON tA BEGIN
      DELETE FROM main.t16;
    END;
  }
} {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}}
do_test trigger1-16.4 {
  catchsql {
    CREATE TRIGGER main.t16err4 AFTER INSERT ON tA BEGIN
      UPDATE t16 NOT INDEXED SET rowid=rowid+1;
    END;
  }
} {1 {the NOT INDEXED clause is not allowed on UPDATE or DELETE statements within triggers}}
do_test trigger1-16.5 {
  catchsql {
    CREATE TRIGGER main.t16err5 AFTER INSERT ON tA BEGIN
      UPDATE t16 INDEXED BY t16a SET rowid=rowid+1 WHERE a=1;
    END;
  }
} {1 {the INDEXED BY clause is not allowed on UPDATE or DELETE statements within triggers}}
do_test trigger1-16.6 {
  catchsql {
    CREATE TRIGGER main.t16err6 AFTER INSERT ON tA BEGIN
      DELETE FROM t16 NOT INDEXED WHERE a=123;
    END;
  }
} {1 {the NOT INDEXED clause is not allowed on UPDATE or DELETE statements within triggers}}
do_test trigger1-16.7 {
  catchsql {
    CREATE TRIGGER main.t16err7 AFTER INSERT ON tA BEGIN
      DELETE FROM t16 INDEXED BY t16a WHERE a=123;
    END;
  }
} {1 {the INDEXED BY clause is not allowed on UPDATE or DELETE statements within triggers}}

finish_test

Added test/trigger2.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# Regression testing of FOR EACH ROW table triggers
#
# 1. Trigger execution order tests. 
# These tests ensure that BEFORE and AFTER triggers are fired at the correct
# times relative to each other and the triggering statement. 
#
# trigger2-1.1.*: ON UPDATE trigger execution model.
# trigger2-1.2.*: DELETE trigger execution model.
# trigger2-1.3.*: INSERT trigger execution model.
#
# 2. Trigger program execution tests.
# These tests ensure that trigger programs execute correctly (ie. that a
# trigger program can correctly execute INSERT, UPDATE, DELETE * SELECT
# statements, and combinations thereof).
#
# 3. Selective trigger execution 
# This tests that conditional triggers (ie. UPDATE OF triggers and triggers
# with WHEN clauses) are fired only fired when they are supposed to be.
#
# trigger2-3.1: UPDATE OF triggers
# trigger2-3.2: WHEN clause
#
# 4. Cascaded trigger execution 
# Tests that trigger-programs may cause other triggers to fire. Also that a 
# trigger-program is never executed recursively.
# 
# trigger2-4.1: Trivial cascading trigger
# trigger2-4.2: Trivial recursive trigger handling 
#
# 5. Count changes behaviour.
# Verify that rows altered by triggers are not included in the return value
# of the "count changes" interface.
#
# 6. ON CONFLICT clause handling
# trigger2-6.1[a-f]: INSERT statements
# trigger2-6.2[a-f]: UPDATE statements
#
# 7. & 8. Triggers on views fire correctly.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# The tests in this file were written before SQLite supported recursive
# trigger invocation, and some tests depend on that to pass. So disable
# recursive triggers for this file.
catchsql { pragma recursive_triggers = off } 

# 1.
ifcapable subquery {
  set ii 0
  set tbl_definitions [list \
  	{CREATE TABLE tbl (a, b);}                                      \
  	{CREATE TABLE tbl (a INTEGER PRIMARY KEY, b);}                  \
        {CREATE TABLE tbl (a, b PRIMARY KEY);}                          \
  	{CREATE TABLE tbl (a, b); CREATE INDEX tbl_idx ON tbl(b);}      \
  ]
  ifcapable tempdb {
    lappend tbl_definitions \
        {CREATE TEMP TABLE tbl (a, b); CREATE INDEX tbl_idx ON tbl(b);} 
    lappend tbl_definitions {CREATE TEMP TABLE tbl (a, b);}
    lappend tbl_definitions \
        {CREATE TEMPORARY TABLE tbl (a INTEGER PRIMARY KEY, b);}
  }
  foreach tbl_defn $tbl_definitions {
    incr ii
    catchsql { DROP INDEX tbl_idx; }
    catchsql {
      DROP TABLE rlog;
      DROP TABLE clog;
      DROP TABLE tbl;
      DROP TABLE other_tbl;
    }
  
    execsql $tbl_defn
  
    execsql {
      INSERT INTO tbl VALUES(1, 2);
      INSERT INTO tbl VALUES(3, 4);
  
      CREATE TABLE rlog (idx, old_a, old_b, db_sum_a, db_sum_b, new_a, new_b);
      CREATE TABLE clog (idx, old_a, old_b, db_sum_a, db_sum_b, new_a, new_b);
  
      CREATE TRIGGER before_update_row BEFORE UPDATE ON tbl FOR EACH ROW 
        BEGIN
        INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), 
  	  old.a, old.b, 
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  new.a, new.b);
      END;
  
      CREATE TRIGGER after_update_row AFTER UPDATE ON tbl FOR EACH ROW 
        BEGIN
        INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), 
  	  old.a, old.b, 
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  new.a, new.b);
      END;
  
      CREATE TRIGGER conditional_update_row AFTER UPDATE ON tbl FOR EACH ROW
        WHEN old.a = 1
        BEGIN
        INSERT INTO clog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM clog), 
  	  old.a, old.b, 
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  new.a, new.b);
      END;
    }
  
    do_test trigger2-1.$ii.1 {
      set r {}
      foreach v [execsql { 
        UPDATE tbl SET a = a * 10, b = b * 10;
        SELECT * FROM rlog ORDER BY idx;
        SELECT * FROM clog ORDER BY idx;
      }] {
        lappend r [expr {int($v)}]
      }
      set r
    } [list 1 1 2  4  6 10 20 \
            2 1 2 13 24 10 20 \
  	    3 3 4 13 24 30 40 \
  	    4 3 4 40 60 30 40 \
            1 1 2 13 24 10 20 ]
  
    execsql {
      DELETE FROM rlog;
      DELETE FROM tbl;
      INSERT INTO tbl VALUES (100, 100);
      INSERT INTO tbl VALUES (300, 200);
      CREATE TRIGGER delete_before_row BEFORE DELETE ON tbl FOR EACH ROW
        BEGIN
        INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), 
  	  old.a, old.b, 
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  0, 0);
      END;
  
      CREATE TRIGGER delete_after_row AFTER DELETE ON tbl FOR EACH ROW
        BEGIN
        INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), 
  	  old.a, old.b, 
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  0, 0);
      END;
    }
    do_test trigger2-1.$ii.2 {
      set r {}
      foreach v [execsql {
        DELETE FROM tbl;
        SELECT * FROM rlog;
      }] {
        lappend r [expr {int($v)}]
      }
      set r
    } [list 1 100 100 400 300 0 0 \
            2 100 100 300 200 0 0 \
            3 300 200 300 200 0 0 \
            4 300 200 0 0 0 0 ]
  
    execsql {
      DELETE FROM rlog;
      CREATE TRIGGER insert_before_row BEFORE INSERT ON tbl FOR EACH ROW
        BEGIN
        INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), 
  	  0, 0,
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  new.a, new.b);
      END;
  
      CREATE TRIGGER insert_after_row AFTER INSERT ON tbl FOR EACH ROW
        BEGIN
        INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), 
  	  0, 0,
  	  (SELECT coalesce(sum(a),0) FROM tbl),
          (SELECT coalesce(sum(b),0) FROM tbl), 
  	  new.a, new.b);
      END;
    }
    do_test trigger2-1.$ii.3 {
      execsql {
  
        CREATE TABLE other_tbl(a, b);
        INSERT INTO other_tbl VALUES(1, 2);
        INSERT INTO other_tbl VALUES(3, 4);
        -- INSERT INTO tbl SELECT * FROM other_tbl;
        INSERT INTO tbl VALUES(5, 6);
        DROP TABLE other_tbl;
  
        SELECT * FROM rlog;
      }
    } [list 1 0 0 0 0 5 6 \
            2 0 0 5 6 5 6 ]
  
    integrity_check trigger2-1.$ii.4
  }
  catchsql {
    DROP TABLE rlog;
    DROP TABLE clog;
    DROP TABLE tbl;
    DROP TABLE other_tbl;
  }
}

# 2.
set ii 0
foreach tr_program {
  {UPDATE tbl SET b = old.b;}
  {INSERT INTO log VALUES(new.c, 2, 3);}
  {DELETE FROM log WHERE a = 1;}
  {INSERT INTO tbl VALUES(500, new.b * 10, 700); 
    UPDATE tbl SET c = old.c; 
    DELETE FROM log;}
  {INSERT INTO log select * from tbl;} 
} {
  foreach test_varset [ list \
    {
      set statement {UPDATE tbl SET c = 10 WHERE a = 1;} 
      set prep      {INSERT INTO tbl VALUES(1, 2, 3);}
      set newC 10
      set newB 2
      set newA 1
      set oldA 1
      set oldB 2
      set oldC 3
    } \
    {
      set statement {DELETE FROM tbl WHERE a = 1;}
      set prep      {INSERT INTO tbl VALUES(1, 2, 3);}
      set oldA 1
      set oldB 2
      set oldC 3
    } \
    {
      set statement {INSERT INTO tbl VALUES(1, 2, 3);}
      set newA 1
      set newB 2
      set newC 3
    }
  ] \
  {
    set statement {}
    set prep {}
    set newA {''}
    set newB {''}
    set newC {''}
    set oldA {''}
    set oldB {''}
    set oldC {''}

    incr ii

    eval $test_varset

    set statement_type [string range $statement 0 5]
    set tr_program_fixed $tr_program
    if {$statement_type == "DELETE"} {
      regsub -all new\.a $tr_program_fixed {''} tr_program_fixed 
      regsub -all new\.b $tr_program_fixed {''} tr_program_fixed 
      regsub -all new\.c $tr_program_fixed {''} tr_program_fixed 
    }
    if {$statement_type == "INSERT"} {
      regsub -all old\.a $tr_program_fixed {''} tr_program_fixed 
      regsub -all old\.b $tr_program_fixed {''} tr_program_fixed 
      regsub -all old\.c $tr_program_fixed {''} tr_program_fixed 
    }


    set tr_program_cooked $tr_program
    regsub -all new\.a $tr_program_cooked $newA tr_program_cooked 
    regsub -all new\.b $tr_program_cooked $newB tr_program_cooked 
    regsub -all new\.c $tr_program_cooked $newC tr_program_cooked 
    regsub -all old\.a $tr_program_cooked $oldA tr_program_cooked 
    regsub -all old\.b $tr_program_cooked $oldB tr_program_cooked 
    regsub -all old\.c $tr_program_cooked $oldC tr_program_cooked 

    catchsql {
      DROP TABLE tbl;
      DROP TABLE log;
    }

    execsql {
      CREATE TABLE tbl(a PRIMARY KEY, b, c);
      CREATE TABLE log(a, b, c);
    }

    set query {SELECT * FROM tbl; SELECT * FROM log;}
    set prep "$prep; INSERT INTO log VALUES(1, 2, 3);\
             INSERT INTO log VALUES(10, 20, 30);"

# Check execution of BEFORE programs:

    set before_data [ execsql "$prep $tr_program_cooked $statement $query" ]

    execsql "DELETE FROM tbl; DELETE FROM log; $prep";
    execsql "CREATE TRIGGER the_trigger BEFORE [string range $statement 0 6]\
             ON tbl BEGIN $tr_program_fixed END;"

    do_test trigger2-2.$ii-before "execsql {$statement $query}" $before_data

    execsql "DROP TRIGGER the_trigger;"
    execsql "DELETE FROM tbl; DELETE FROM log;"

# Check execution of AFTER programs
    set after_data [ execsql "$prep $statement $tr_program_cooked $query" ]

    execsql "DELETE FROM tbl; DELETE FROM log; $prep";
    execsql "CREATE TRIGGER the_trigger AFTER [string range $statement 0 6]\
             ON tbl BEGIN $tr_program_fixed END;"

    do_test trigger2-2.$ii-after "execsql {$statement $query}" $after_data
    execsql "DROP TRIGGER the_trigger;"

    integrity_check trigger2-2.$ii-integrity
  }
}
catchsql {
  DROP TABLE tbl;
  DROP TABLE log;
}

# 3.

# trigger2-3.1: UPDATE OF triggers
execsql {
  CREATE TABLE tbl (a, b, c, d);
  CREATE TABLE log (a);
  INSERT INTO log VALUES (0);
  INSERT INTO tbl VALUES (0, 0, 0, 0);
  INSERT INTO tbl VALUES (1, 0, 0, 0);
  CREATE TRIGGER tbl_after_update_cd BEFORE UPDATE OF c, d ON tbl
    BEGIN
      UPDATE log SET a = a + 1;
    END;
}
do_test trigger2-3.1 {
  execsql {
    UPDATE tbl SET b = 1, c = 10; -- 2
    UPDATE tbl SET b = 10; -- 0
    UPDATE tbl SET d = 4 WHERE a = 0; --1
    UPDATE tbl SET a = 4, b = 10; --0
    SELECT * FROM log;
  }
} {3}
execsql {
  DROP TABLE tbl;
  DROP TABLE log;
}

# trigger2-3.2: WHEN clause
set when_triggers [list {t1 BEFORE INSERT ON tbl WHEN new.a > 20}]
ifcapable subquery {
  lappend when_triggers \
      {t2 BEFORE INSERT ON tbl WHEN (SELECT count(*) FROM tbl) = 0}
}

execsql {
  CREATE TABLE tbl (a, b, c, d);
  CREATE TABLE log (a);
  INSERT INTO log VALUES (0);
}

foreach trig $when_triggers {
  execsql "CREATE TRIGGER $trig BEGIN UPDATE log set a = a + 1; END;"
}

ifcapable subquery {
  set t232 {1 0 1}
} else {
  set t232 {0 0 1}
}
do_test trigger2-3.2 {
  execsql { 

    INSERT INTO tbl VALUES(0, 0, 0, 0);     -- 1 (ifcapable subquery)
    SELECT * FROM log;
    UPDATE log SET a = 0;

    INSERT INTO tbl VALUES(0, 0, 0, 0);     -- 0
    SELECT * FROM log;
    UPDATE log SET a = 0;

    INSERT INTO tbl VALUES(200, 0, 0, 0);     -- 1
    SELECT * FROM log;
    UPDATE log SET a = 0;
  }
} $t232
execsql {
  DROP TABLE tbl;
  DROP TABLE log;
}
integrity_check trigger2-3.3

# Simple cascaded trigger
execsql {
  CREATE TABLE tblA(a, b);
  CREATE TABLE tblB(a, b);
  CREATE TABLE tblC(a, b);

  CREATE TRIGGER tr1 BEFORE INSERT ON tblA BEGIN
    INSERT INTO tblB values(new.a, new.b);
  END;

  CREATE TRIGGER tr2 BEFORE INSERT ON tblB BEGIN
    INSERT INTO tblC values(new.a, new.b);
  END;
}
do_test trigger2-4.1 {
  execsql {
    INSERT INTO tblA values(1, 2);
    SELECT * FROM tblA;
    SELECT * FROM tblB;
    SELECT * FROM tblC;
  }
} {1 2 1 2 1 2}
execsql {
  DROP TABLE tblA;
  DROP TABLE tblB;
  DROP TABLE tblC;
}

# Simple recursive trigger
execsql {
  CREATE TABLE tbl(a, b, c);
  CREATE TRIGGER tbl_trig BEFORE INSERT ON tbl 
    BEGIN
      INSERT INTO tbl VALUES (new.a, new.b, new.c);
    END;
}
do_test trigger2-4.2 {
  execsql {
    INSERT INTO tbl VALUES (1, 2, 3);
    select * from tbl;
  }
} {1 2 3 1 2 3}
execsql {
  DROP TABLE tbl;
}

# 5.
execsql {
  CREATE TABLE tbl(a, b, c);
  CREATE TRIGGER tbl_trig BEFORE INSERT ON tbl 
    BEGIN
      INSERT INTO tbl VALUES (1, 2, 3);
      INSERT INTO tbl VALUES (2, 2, 3);
      UPDATE tbl set b = 10 WHERE a = 1;
      DELETE FROM tbl WHERE a = 1;
      DELETE FROM tbl;
    END;
}
do_test trigger2-5 {
  execsql {
    INSERT INTO tbl VALUES(100, 200, 300);
  }
  db changes
} {1}
execsql {
  DROP TABLE tbl;
}

ifcapable conflict {
  # Handling of ON CONFLICT by INSERT statements inside triggers
  execsql {
    CREATE TABLE tbl (a primary key, b, c);
    CREATE TRIGGER ai_tbl AFTER INSERT ON tbl BEGIN
      INSERT OR IGNORE INTO tbl values (new.a, 0, 0);
    END;
  }
  do_test trigger2-6.1a {
    execsql {
      BEGIN;
      INSERT INTO tbl values (1, 2, 3);
      SELECT * from tbl;
    }
  } {1 2 3}
  do_test trigger2-6.1b {
    catchsql {
      INSERT OR ABORT INTO tbl values (2, 2, 3);
    }
  } {1 {column a is not unique}}
  do_test trigger2-6.1c {
    execsql {
      SELECT * from tbl;
    }
  } {1 2 3}
  do_test trigger2-6.1d {
    catchsql {
      INSERT OR FAIL INTO tbl values (2, 2, 3);
    }
  } {1 {column a is not unique}}
  do_test trigger2-6.1e {
    execsql {
      SELECT * from tbl;
    }
  } {1 2 3 2 2 3}
  do_test trigger2-6.1f {
    execsql {
      INSERT OR REPLACE INTO tbl values (2, 2, 3);
      SELECT * from tbl;
    }
  } {1 2 3 2 0 0}
  do_test trigger2-6.1g {
    catchsql {
      INSERT OR ROLLBACK INTO tbl values (3, 2, 3);
    }
  } {1 {column a is not unique}}
  do_test trigger2-6.1h {
    execsql {
      SELECT * from tbl;
    }
  } {}
  execsql {DELETE FROM tbl}
  
  
  # Handling of ON CONFLICT by UPDATE statements inside triggers
  execsql {
    INSERT INTO tbl values (4, 2, 3);
    INSERT INTO tbl values (6, 3, 4);
    CREATE TRIGGER au_tbl AFTER UPDATE ON tbl BEGIN
      UPDATE OR IGNORE tbl SET a = new.a, c = 10;
    END;
  }
  do_test trigger2-6.2a {
    execsql {
      BEGIN;
      UPDATE tbl SET a = 1 WHERE a = 4;
      SELECT * from tbl;
    }
  } {1 2 10 6 3 4}
  do_test trigger2-6.2b {
    catchsql {
      UPDATE OR ABORT tbl SET a = 4 WHERE a = 1;
    }
  } {1 {column a is not unique}}
  do_test trigger2-6.2c {
    execsql {
      SELECT * from tbl;
    }
  } {1 2 10 6 3 4}
  do_test trigger2-6.2d {
    catchsql {
      UPDATE OR FAIL tbl SET a = 4 WHERE a = 1;
    }
  } {1 {column a is not unique}}
  do_test trigger2-6.2e {
    execsql {
      SELECT * from tbl;
    }
  } {4 2 10 6 3 4}
  do_test trigger2-6.2f.1 {
    execsql {
      UPDATE OR REPLACE tbl SET a = 1 WHERE a = 4;
      SELECT * from tbl;
    }
  } {1 3 10}
  do_test trigger2-6.2f.2 {
    execsql {
      INSERT INTO tbl VALUES (2, 3, 4);
      SELECT * FROM tbl;
    }
  } {1 3 10 2 3 4}
  do_test trigger2-6.2g {
    catchsql {
      UPDATE OR ROLLBACK tbl SET a = 4 WHERE a = 1;
    }
  } {1 {column a is not unique}}
  do_test trigger2-6.2h {
    execsql {
      SELECT * from tbl;
    }
  } {4 2 3 6 3 4}
  execsql {
    DROP TABLE tbl;
  }
} ; # ifcapable conflict

# 7. Triggers on views
ifcapable view {

do_test trigger2-7.1 {
  execsql {
  CREATE TABLE ab(a, b);
  CREATE TABLE cd(c, d);
  INSERT INTO ab VALUES (1, 2);
  INSERT INTO ab VALUES (0, 0);
  INSERT INTO cd VALUES (3, 4);

  CREATE TABLE tlog(ii INTEGER PRIMARY KEY, 
      olda, oldb, oldc, oldd, newa, newb, newc, newd);

  CREATE VIEW abcd AS SELECT a, b, c, d FROM ab, cd;

  CREATE TRIGGER before_update INSTEAD OF UPDATE ON abcd BEGIN
    INSERT INTO tlog VALUES(NULL, 
	old.a, old.b, old.c, old.d, new.a, new.b, new.c, new.d);
  END;
  CREATE TRIGGER after_update INSTEAD OF UPDATE ON abcd BEGIN
    INSERT INTO tlog VALUES(NULL, 
	old.a, old.b, old.c, old.d, new.a, new.b, new.c, new.d);
  END;

  CREATE TRIGGER before_delete INSTEAD OF DELETE ON abcd BEGIN
    INSERT INTO tlog VALUES(NULL, 
	old.a, old.b, old.c, old.d, 0, 0, 0, 0);
  END;
  CREATE TRIGGER after_delete INSTEAD OF DELETE ON abcd BEGIN
    INSERT INTO tlog VALUES(NULL, 
	old.a, old.b, old.c, old.d, 0, 0, 0, 0);
  END;

  CREATE TRIGGER before_insert INSTEAD OF INSERT ON abcd BEGIN
    INSERT INTO tlog VALUES(NULL, 
	0, 0, 0, 0, new.a, new.b, new.c, new.d);
  END;
   CREATE TRIGGER after_insert INSTEAD OF INSERT ON abcd BEGIN
    INSERT INTO tlog VALUES(NULL, 
	0, 0, 0, 0, new.a, new.b, new.c, new.d);
   END;
  }
} {};

do_test trigger2-7.2 {
  execsql {
    UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1;
    DELETE FROM abcd WHERE a = 1;
    INSERT INTO abcd VALUES(10, 20, 30, 40);
    SELECT * FROM tlog;
  }
} [ list 1 1 2 3 4 100 25 3 4 \
         2 1 2 3 4 100 25 3 4 \
	 3 1 2 3 4 0 0 0 0 \
	 4 1 2 3 4 0 0 0 0 \
	 5 0 0 0 0 10 20 30 40 \
	 6 0 0 0 0 10 20 30 40 ]

do_test trigger2-7.3 {
  execsql {
    DELETE FROM tlog;
    INSERT INTO abcd VALUES(10, 20, 30, 40);
    UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1;
    DELETE FROM abcd WHERE a = 1;
    SELECT * FROM tlog;
  }
} [ list \
   1 0 0 0 0 10 20 30 40 \
   2 0 0 0 0 10 20 30 40 \
   3 1 2 3 4 100 25 3 4 \
   4 1 2 3 4 100 25 3 4 \
   5 1 2 3 4 0 0 0 0 \
   6 1 2 3 4 0 0 0 0 \
]
do_test trigger2-7.4 {
  execsql {
    DELETE FROM tlog;
    DELETE FROM abcd WHERE a = 1;
    INSERT INTO abcd VALUES(10, 20, 30, 40);
    UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1;
    SELECT * FROM tlog;
  }
} [ list \
   1 1 2 3 4 0 0 0 0 \
   2 1 2 3 4 0 0 0 0 \
   3 0 0 0 0 10 20 30 40 \
   4 0 0 0 0 10 20 30 40 \
   5 1 2 3 4 100 25 3 4 \
   6 1 2 3 4 100 25 3 4 \
]

do_test trigger2-8.1 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    CREATE VIEW v1 AS
      SELECT a+b AS x, b+c AS y, a+c AS z FROM t1;
    SELECT * FROM v1;
  }
} {3 5 4}
do_test trigger2-8.2 {
  execsql {
    CREATE TABLE v1log(a,b,c,d,e,f);
    CREATE TRIGGER r1 INSTEAD OF DELETE ON v1 BEGIN
      INSERT INTO v1log VALUES(OLD.x,NULL,OLD.y,NULL,OLD.z,NULL);
    END;
    DELETE FROM v1 WHERE x=1;
    SELECT * FROM v1log;
  }
} {}
do_test trigger2-8.3 {
  execsql {
    DELETE FROM v1 WHERE x=3;
    SELECT * FROM v1log;
  }
} {3 {} 5 {} 4 {}}
do_test trigger2-8.4 {
  execsql {
    INSERT INTO t1 VALUES(4,5,6);
    DELETE FROM v1log;
    DELETE FROM v1 WHERE y=11;
    SELECT * FROM v1log;
  }
} {9 {} 11 {} 10 {}}
do_test trigger2-8.5 {
  execsql {
    CREATE TRIGGER r2 INSTEAD OF INSERT ON v1 BEGIN
      INSERT INTO v1log VALUES(NULL,NEW.x,NULL,NEW.y,NULL,NEW.z);
    END;
    DELETE FROM v1log;
    INSERT INTO v1 VALUES(1,2,3);
    SELECT * FROM v1log;
  }
} {{} 1 {} 2 {} 3}
do_test trigger2-8.6 {
  execsql {
    CREATE TRIGGER r3 INSTEAD OF UPDATE ON v1 BEGIN
      INSERT INTO v1log VALUES(OLD.x,NEW.x,OLD.y,NEW.y,OLD.z,NEW.z);
    END;
    DELETE FROM v1log;
    UPDATE v1 SET x=x+100, y=y+200, z=z+300;
    SELECT * FROM v1log;
  }
} {3 103 5 205 4 304 9 109 11 211 10 310}

# At one point the following was causing a segfault.
do_test trigger2-9.1 {
  execsql {
    CREATE TABLE t3(a TEXT, b TEXT);
    CREATE VIEW v3 AS SELECT t3.a FROM t3;
    CREATE TRIGGER trig1 INSTEAD OF DELETE ON v3 BEGIN
      SELECT 1;
    END;
    DELETE FROM v3 WHERE a = 1;
  }
} {}

} ;# ifcapable view

integrity_check trigger2-9.9

finish_test

Added test/trigger3.test.





































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests the RAISE() function.
#


set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# The tests in this file were written before SQLite supported recursive }
# trigger invocation, and some tests depend on that to pass. So disable
# recursive triggers for this file.
catchsql { pragma recursive_triggers = off } 

# Test that we can cause ROLLBACK, FAIL and ABORT correctly
#
catchsql { CREATE TABLE tbl(a, b ,c) }
execsql {
    CREATE TRIGGER before_tbl_insert BEFORE INSERT ON tbl BEGIN SELECT CASE 
        WHEN (new.a = 4) THEN RAISE(IGNORE) END;
    END;

    CREATE TRIGGER after_tbl_insert AFTER INSERT ON tbl BEGIN SELECT CASE 
        WHEN (new.a = 1) THEN RAISE(ABORT,    'Trigger abort') 
        WHEN (new.a = 2) THEN RAISE(FAIL,     'Trigger fail') 
        WHEN (new.a = 3) THEN RAISE(ROLLBACK, 'Trigger rollback') END;
    END;
}
# ABORT
do_test trigger3-1.1 {
    catchsql {
        BEGIN;
        INSERT INTO tbl VALUES (5, 5, 6);
        INSERT INTO tbl VALUES (1, 5, 6);
    }
} {1 {Trigger abort}}
do_test trigger3-1.2 {
    execsql {
        SELECT * FROM tbl;
        ROLLBACK;
    }
} {5 5 6}
do_test trigger3-1.3 {
    execsql {SELECT * FROM tbl}
} {}

# FAIL
do_test trigger3-2.1 {
    catchsql {
        BEGIN;
        INSERT INTO tbl VALUES (5, 5, 6);
        INSERT INTO tbl VALUES (2, 5, 6);
    }
} {1 {Trigger fail}}
do_test trigger3-2.2 {
    execsql {
        SELECT * FROM tbl;
        ROLLBACK;
    }
} {5 5 6 2 5 6}
# ROLLBACK
do_test trigger3-3.1 {
    catchsql {
        BEGIN;
        INSERT INTO tbl VALUES (5, 5, 6);
        INSERT INTO tbl VALUES (3, 5, 6);
    }
} {1 {Trigger rollback}}
do_test trigger3-3.2 {
    execsql {
        SELECT * FROM tbl;
    }
} {}

# Verify that a ROLLBACK trigger works like a FAIL trigger if
# we are not within a transaction.  Ticket #3035.
#
do_test trigger3-3.3 {
    catchsql {COMMIT}
    catchsql {
        INSERT INTO tbl VALUES (3, 9, 10);
    }
} {1 {Trigger rollback}}
do_test trigger3-3.4 {
    execsql {SELECT * FROM tbl}
} {}

# IGNORE
do_test trigger3-4.1 {
    catchsql {
        BEGIN;
        INSERT INTO tbl VALUES (5, 5, 6);
        INSERT INTO tbl VALUES (4, 5, 6);
    }
} {0 {}}
do_test trigger3-4.2 {
    execsql {
        SELECT * FROM tbl;
        ROLLBACK;
    }
} {5 5 6}

# Check that we can also do RAISE(IGNORE) for UPDATE and DELETE
execsql {DROP TABLE tbl;}
execsql {CREATE TABLE tbl (a, b, c);}
execsql {INSERT INTO tbl VALUES(1, 2, 3);}
execsql {INSERT INTO tbl VALUES(4, 5, 6);}
execsql {
    CREATE TRIGGER before_tbl_update BEFORE UPDATE ON tbl BEGIN
        SELECT CASE WHEN (old.a = 1) THEN RAISE(IGNORE) END;
    END;

    CREATE TRIGGER before_tbl_delete BEFORE DELETE ON tbl BEGIN
        SELECT CASE WHEN (old.a = 1) THEN RAISE(IGNORE) END;
    END;
}
do_test trigger3-5.1 {
    execsql {
        UPDATE tbl SET c = 10;
        SELECT * FROM tbl;
    }
} {1 2 3 4 5 10}
do_test trigger3-5.2 {
    execsql {
        DELETE FROM tbl;
        SELECT * FROM tbl;
    }
} {1 2 3}

# Check that RAISE(IGNORE) works correctly for nested triggers:
execsql {CREATE TABLE tbl2(a, b, c)}
execsql {
    CREATE TRIGGER after_tbl2_insert AFTER INSERT ON tbl2 BEGIN
        UPDATE tbl SET c = 10;
        INSERT INTO tbl2 VALUES (new.a, new.b, new.c);
    END;
}
do_test trigger3-6 {
    execsql {
        INSERT INTO tbl2 VALUES (1, 2, 3);
        SELECT * FROM tbl2;
        SELECT * FROM tbl;
    }
} {1 2 3 1 2 3 1 2 3}

# Check that things also work for view-triggers

ifcapable view {

execsql {CREATE VIEW tbl_view AS SELECT * FROM tbl}
execsql {
    CREATE TRIGGER tbl_view_insert INSTEAD OF INSERT ON tbl_view BEGIN
        SELECT CASE WHEN (new.a = 1) THEN RAISE(ROLLBACK, 'View rollback')
                    WHEN (new.a = 2) THEN RAISE(IGNORE) 
                    WHEN (new.a = 3) THEN RAISE(ABORT, 'View abort') END;
    END;
}

do_test trigger3-7.1 {
    catchsql {
        INSERT INTO tbl_view VALUES(1, 2, 3);
    }
} {1 {View rollback}}
do_test trigger3-7.2 {
    catchsql {
        INSERT INTO tbl_view VALUES(2, 2, 3);
    }
} {0 {}}
do_test trigger3-7.3 {
    catchsql {
        INSERT INTO tbl_view VALUES(3, 2, 3);
    }
} {1 {View abort}}

} ;# ifcapable view

integrity_check trigger3-8.1

catchsql { DROP TABLE tbl; } 
catchsql { DROP TABLE tbl2; } 
catchsql { DROP VIEW tbl_view; }

finish_test

Added test/trigger4.test.

















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests the triggers of views.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If either views or triggers are disabled in this build, omit this file.
ifcapable {!trigger || !view} {
  finish_test
  return
}

do_test trigger4-1.1 {
  execsql {
    create table test1(id integer primary key,a);
    create table test2(id integer,b);
    create view test as
      select test1.id as id,a as a,b as b
      from test1 join test2 on test2.id =  test1.id;
    create trigger I_test instead of insert on test
      begin
        insert into test1 (id,a) values (NEW.id,NEW.a);
        insert into test2 (id,b) values (NEW.id,NEW.b);
      end;
    insert into test values(1,2,3);
    select * from test1;
  }
} {1 2}
do_test trigger4-1.2 {
  execsql {
    select * from test2;
  }
} {1 3}
do_test trigger4-1.3 {
  db close
  sqlite3 db test.db
  execsql {
    insert into test values(4,5,6);
    select * from test1;
  }
} {1 2 4 5}
do_test trigger4-1.4 {
  execsql {
    select * from test2;
  }
} {1 3 4 6}

do_test trigger4-2.1 {
  execsql {
    create trigger U_test instead of update on test
      begin
        update test1 set a=NEW.a where id=NEW.id;
        update test2 set b=NEW.b where id=NEW.id;
      end;
    update test set a=22 where id=1;
    select * from test1;
  }
} {1 22 4 5}
do_test trigger4-2.2 {
  execsql {
    select * from test2;
  }
} {1 3 4 6}
do_test trigger4-2.3 {
  db close
  sqlite3 db test.db
  execsql {
    update test set b=66 where id=4;
    select * from test1;
  }
} {1 22 4 5}
do_test trigger4-2.4 {
  execsql {
    select * from test2;
  }
} {1 3 4 66}

do_test trigger4-3.1 {
  catchsql {
    drop table test2;
    insert into test values(7,8,9);
  }
} {1 {no such table: main.test2}}
do_test trigger4-3.2 {
  db close
  sqlite3 db test.db
  catchsql {
    insert into test values(7,8,9);
  }
} {1 {no such table: main.test2}}
do_test trigger4-3.3 {
  catchsql {
    update test set a=222 where id=1;
  }
} {1 {no such table: main.test2}}
do_test trigger4-3.4 {
  execsql {
    select * from test1;
  }
} {1 22 4 5}
do_test trigger4-3.5 {
  execsql {
    create table test2(id,b);
    insert into test values(7,8,9);
    select * from test1;
  }
} {1 22 4 5 7 8}
do_test trigger4-3.6 {
  execsql {
    select * from test2;
  }
} {7 9}
do_test trigger4-3.7 {
  db close
  sqlite3 db test.db
  execsql {
    update test set b=99 where id=7;
    select * from test2;
  }
} {7 99}

do_test trigger4-4.1 {
    db close
    file delete -force trigtest.db
    file delete -force trigtest.db-journal
    sqlite3 db trigtest.db
    catchsql {drop table tbl; drop view vw}
    execsql {
	create table tbl(a integer primary key, b integer);
	create view vw as select * from tbl;
	create trigger t_del_tbl instead of delete on vw for each row begin
	  delete from tbl where a = old.a;
	end;
	create trigger t_upd_tbl instead of update on vw for each row begin
	  update tbl set a=new.a, b=new.b where a = old.a;
	end;
	create trigger t_ins_tbl instead of insert on vw for each row begin
	  insert into tbl values (new.a,new.b);
	end;
	insert into tbl values(101,1001);
	insert into tbl values(102,1002);
	insert into tbl select a+2, b+2 from tbl;
	insert into tbl select a+4, b+4 from tbl;
	insert into tbl select a+8, b+8 from tbl;
	insert into tbl select a+16, b+16 from tbl;
	insert into tbl select a+32, b+32 from tbl;
	insert into tbl select a+64, b+64 from tbl;
	select count(*) from vw;
    }
} {128}
do_test trigger4-4.2 {
    execsql {select a, b from vw where a<103 or a>226 order by a}
} {101 1001 102 1002 227 1127 228 1128}

#test delete from view
do_test trigger4-5.1 {
    catchsql {delete from vw where a>101 and a<2000}
} {0 {}}
do_test trigger4-5.2 {
    execsql {select * from vw}
} {101 1001}

#test insert into view
do_test trigger4-6.1 {
    catchsql {
	insert into vw values(102,1002);
	insert into vw select a+2, b+2 from vw;
	insert into vw select a+4, b+4 from vw;
	insert into vw select a+8, b+8 from vw;
	insert into vw select a+16, b+16 from vw;
	insert into vw select a+32, b+32 from vw;
	insert into vw select a+64, b+64 from vw;
    }
} {0 {}}
do_test trigger4-6.2 {
    execsql {select count(*) from vw}
} {128}

#test update of view
do_test trigger4-7.1 {
    catchsql {update vw set b=b+1000 where a>101 and a<2000}
} {0 {}}
do_test trigger4-7.2 {
    execsql {select a, b from vw where a<=102 or a>=227 order by a}
} {101 1001 102 2002 227 2127 228 2128}

integrity_check trigger4-99.9
db close
file delete -force trigtest.db trigtest.db-journal

finish_test

Added test/trigger5.test.























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests the triggers of views.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# Ticket #844
#
do_test trigger5-1.1 {
  execsql {
    CREATE TABLE Item(
       a integer PRIMARY KEY NOT NULL ,
       b double NULL ,
       c int NOT NULL DEFAULT 0
    );
    CREATE TABLE Undo(UndoAction TEXT);
    INSERT INTO Item VALUES (1,38205.60865,340);
    CREATE TRIGGER trigItem_UNDO_AD AFTER DELETE ON Item FOR EACH ROW
    BEGIN
      INSERT INTO Undo SELECT 'INSERT INTO Item (a,b,c) VALUES ('
       || coalesce(old.a,'NULL') || ',' || quote(old.b) || ',' || old.c || ');';
    END;
    DELETE FROM Item WHERE a = 1;
    SELECT * FROM Undo;
  }
} {{INSERT INTO Item (a,b,c) VALUES (1,38205.60865,340);}}

integrity_check trigger5-99.9

finish_test

Added test/trigger6.test.





































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# 2004 December 07
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure expression of an INSERT
# and UPDATE statement are only evaluated once.  See ticket #980.
# If an expression uses a function that has side-effects or which
# is not deterministic (ex: random()) then we want to make sure
# that the same evaluation occurs for the actual INSERT/UPDATE and
# for the NEW.* fields of any triggers that fire.
#
# $Id: trigger6.test,v 1.2 2005/05/05 11:04:50 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

do_test trigger6-1.1 {
  execsql {
    CREATE TABLE t1(x, y);
    CREATE TABLE log(a, b, c);
    CREATE TRIGGER r1 BEFORE INSERT ON t1 BEGIN
      INSERT INTO log VALUES(1, new.x, new.y);
    END;
    CREATE TRIGGER r2 BEFORE UPDATE ON t1 BEGIN
      INSERT INTO log VALUES(2, new.x, new.y);
    END;
  }
  set ::trigger6_cnt 0
  proc trigger6_counter {args} {
    incr ::trigger6_cnt
    return $::trigger6_cnt
  }
  db function counter trigger6_counter
  execsql {
    INSERT INTO t1 VALUES(1,counter());
    SELECT * FROM t1;
  }
} {1 1}
do_test trigger6-1.2 {
  execsql {
    SELECT * FROM log;
  }
} {1 1 1}
do_test trigger6-1.3 {
  execsql {
    DELETE FROM t1;
    DELETE FROM log;
    INSERT INTO t1 VALUES(2,counter(2,3)+4);
    SELECT * FROM t1;
  }
} {2 6}
do_test trigger6-1.4 {
  execsql {
    SELECT * FROM log;
  }
} {1 2 6}
do_test trigger6-1.5 {
  execsql {
    DELETE FROM log;
    UPDATE t1 SET y=counter(5);
    SELECT * FROM t1;
  }
} {2 3}
do_test trigger6-1.6 {
  execsql {
    SELECT * FROM log;
  }
} {2 2 3}

finish_test

Added test/trigger7.test.



















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# 2005 August 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to increase coverage of trigger.c.
#
# $Id: trigger7.test,v 1.3 2008/08/11 18:44:58 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}


# Error messages resulting from qualified trigger names.
#
do_test trigger7-1.1 {
  execsql {
    CREATE TABLE t1(x, y);
  }
  catchsql {
    CREATE TEMP TRIGGER main.r1 AFTER INSERT ON t1 BEGIN
      SELECT 'no nothing';
    END
  }
} {1 {temporary trigger may not have qualified name}}
do_test trigger7-1.2 {
  catchsql {
    CREATE TRIGGER not_a_db.r1 AFTER INSERT ON t1 BEGIN
      SELECT 'no nothing';
    END
  }
} {1 {unknown database not_a_db}}


# When the UPDATE OF syntax is used, no code is generated for triggers
# that do not match the update columns.
#
ifcapable explain {
  do_test trigger7-2.1 {
    execsql {
      CREATE TRIGGER r1 AFTER UPDATE OF x ON t1 BEGIN
        SELECT '___update_t1.x___';
      END;
      CREATE TRIGGER r2 AFTER UPDATE OF y ON t1 BEGIN
        SELECT '___update_t1.y___';
      END;
    }
    set txt [db eval {EXPLAIN UPDATE t1 SET x=5}]
    string match *___update_t1.x___* $txt
  } 1
  do_test trigger7-2.2 {
    set txt [db eval {EXPLAIN UPDATE t1 SET x=5}]
    string match *___update_t1.y___* $txt
  } 0
  do_test trigger7-2.3 {
    set txt [db eval {EXPLAIN UPDATE t1 SET y=5}]
    string match *___update_t1.x___* $txt
  } 0
  do_test trigger7-2.4 {
    set txt [db eval {EXPLAIN UPDATE t1 SET y=5}]
    string match *___update_t1.y___* $txt
  } 1
  do_test trigger7-2.5 {
    set txt [db eval {EXPLAIN UPDATE t1 SET rowid=5}]
    string match *___update_t1.x___* $txt
  } 0
  do_test trigger7-2.6 {
    set txt [db eval {EXPLAIN UPDATE t1 SET rowid=5}]
    string match *___update_t1.x___* $txt
  } 0
}

# Test the ability to create many triggers on the same table, then
# selectively drop those triggers.
#
do_test trigger7-3.1 {
  execsql {
    CREATE TABLE t2(x,y,z);
    CREATE TRIGGER t2r1 AFTER INSERT ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r2 BEFORE INSERT ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r3 AFTER UPDATE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r4 BEFORE UPDATE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r5 AFTER DELETE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r6 BEFORE DELETE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r7 AFTER INSERT ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r8 BEFORE INSERT ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r9 AFTER UPDATE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r10 BEFORE UPDATE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r11 AFTER DELETE ON t2 BEGIN SELECT 1; END;
    CREATE TRIGGER t2r12 BEFORE DELETE ON t2 BEGIN SELECT 1; END;
    DROP TRIGGER t2r6;
  }
} {}

# This test corrupts the database file so it must be the last test
# in the series.
#
do_test trigger7-99.1 {
  execsql {
    PRAGMA writable_schema=on;
    UPDATE sqlite_master SET sql='nonsense';
  }
  db close
  sqlite3 db test.db
  catchsql {
    DROP TRIGGER t2r5
  }
} {1 {malformed database schema (t2r12) - near "nonsense": syntax error}}

finish_test

Added test/trigger8.test.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 2006 February 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to make sure abusively large triggers
# (triggers with 100s or 1000s of statements) work.
#
# $Id: trigger8.test,v 1.2 2008/09/17 16:14:10 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# Set variable $nStatement to the number of statements to include in the
# body of the trigger. On a workstation with virtually unlimited memory, 
# use 10000. But on symbian, which allows each application at most a 32MB
# heap, use 1000.
#
set nStatement 10000
if {$tcl_platform(platform) == "symbian"} {
  set nStatement 1000
}

set nStatement 5
do_test trigger8-1.1 {
  execsql {
    CREATE TABLE t1(x);
    CREATE TABLE t2(y);
  }
  set sql "CREATE TRIGGER r${nStatement} AFTER INSERT ON t1 BEGIN\n"
  for {set i 0} {$i<$nStatement} {incr i} {
    append sql "  INSERT INTO t2 VALUES($i);\n"
  }
  append sql "END;"
  execsql $sql
  execsql {
    INSERT INTO t1 VALUES(5);
    SELECT count(*) FROM t2;
  }
} $nStatement

finish_test

Added test/trigger9.test.































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# 2008 January 1
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. Specifically,
# it tests some compiler optimizations for SQL statements featuring
# triggers:
#
#
#

# trigger9-1.* -   Test that if there are no references to OLD.* cols, or a
#                  reference to only OLD.rowid, the data is not loaded.
#
# trigger9-2.* -   Test that for NEW.* records populated by UPDATE 
#                  statements, unused fields are populated with NULL values. 
#
# trigger9-3.* -   Test that the temporary tables used for OLD.* references
#                  in "INSTEAD OF" triggers have NULL values in unused 
#                  fields.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

proc has_rowdata {sql} {
  expr {[lsearch [execsql "explain $sql"] RowData]>=0}
}

do_test trigger9-1.1 {
  execsql {
    PRAGMA page_size = 1024;
    CREATE TABLE t1(x, y, z);
    INSERT INTO t1 VALUES('1', randstr(10000,10000), '2');
    INSERT INTO t1 VALUES('2', randstr(10000,10000), '4');
    INSERT INTO t1 VALUES('3', randstr(10000,10000), '6');
    CREATE TABLE t2(x);
  }
} {}

do_test trigger9-1.2.1 {
  execsql {
    BEGIN;
      CREATE TRIGGER trig1 BEFORE DELETE ON t1 BEGIN
        INSERT INTO t2 VALUES(old.rowid);
      END;
      DELETE FROM t1;
      SELECT * FROM t2;
  }
} {1 2 3}
do_test trigger9-1.2.3 {
  has_rowdata {DELETE FROM t1}
} 0
do_test trigger9-1.2.4 { execsql { ROLLBACK } } {}

do_test trigger9-1.3.1 {
  execsql {
    BEGIN;
      CREATE TRIGGER trig1 BEFORE DELETE ON t1 BEGIN
        INSERT INTO t2 VALUES(old.x);
      END;
      DELETE FROM t1;
      SELECT * FROM t2;
  }
} {1 2 3}
do_test trigger9-1.3.2 {
  has_rowdata {DELETE FROM t1}
} 0
do_test trigger9-1.3.3 { execsql { ROLLBACK } } {}

do_test trigger9-1.4.1 {
  execsql {
    BEGIN;
      CREATE TRIGGER trig1 BEFORE DELETE ON t1 WHEN old.x='1' BEGIN
        INSERT INTO t2 VALUES(old.rowid);
      END;
      DELETE FROM t1;
      SELECT * FROM t2;
  }
} {1}
do_test trigger9-1.4.2 {
  has_rowdata {DELETE FROM t1}
} 0
do_test trigger9-1.4.3 { execsql { ROLLBACK } } {}

do_test trigger9-1.5.1 {
  execsql {
    BEGIN;
      CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN
        INSERT INTO t2 VALUES(old.rowid);
      END;
      UPDATE t1 SET y = '';
      SELECT * FROM t2;
  }
} {1 2 3}
do_test trigger9-1.5.2 {
  has_rowdata {UPDATE t1 SET y = ''}
} 0
do_test trigger9-1.5.3 { execsql { ROLLBACK } } {}

do_test trigger9-1.6.1 {
  execsql {
    BEGIN;
      CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN
        INSERT INTO t2 VALUES(old.x);
      END;
      UPDATE t1 SET y = '';
      SELECT * FROM t2;
  }
} {1 2 3}
do_test trigger9-1.6.2 {
  has_rowdata {UPDATE t1 SET y = ''}
} 0
do_test trigger9-1.6.3 { execsql { ROLLBACK } } {}

do_test trigger9-1.7.1 {
  execsql {
    BEGIN;
      CREATE TRIGGER trig1 BEFORE UPDATE ON t1 WHEN old.x>='2' BEGIN
        INSERT INTO t2 VALUES(old.x);
      END;
      UPDATE t1 SET y = '';
      SELECT * FROM t2;
  }
} {2 3}
do_test trigger9-1.7.2 {
  has_rowdata {UPDATE t1 SET y = ''}
} 0
do_test trigger9-1.7.3 { execsql { ROLLBACK } } {}

do_test trigger9-3.1 {
  execsql {
    CREATE TABLE t3(a, b);
    INSERT INTO t3 VALUES(1, 'one');
    INSERT INTO t3 VALUES(2, 'two');
    INSERT INTO t3 VALUES(3, 'three');
  }
} {}
do_test trigger9-3.2 {
  execsql {
    BEGIN;
      CREATE VIEW v1 AS SELECT * FROM t3;
      CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN
        INSERT INTO t2 VALUES(old.a);
      END;
      UPDATE v1 SET b = 'hello';
      SELECT * FROM t2;
    ROLLBACK;
  }
} {1 2 3}
do_test trigger9-3.3 {
  # In this test the 'c' column of the view is not required by
  # the INSTEAD OF trigger, but the expression is reused internally as
  # part of the view's WHERE clause. Check that this does not cause
  # a problem.
  #
  execsql {
    BEGIN;
      CREATE VIEW v1 AS SELECT a, b AS c FROM t3 WHERE c > 'one';
      CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN
        INSERT INTO t2 VALUES(old.a);
      END;
      UPDATE v1 SET c = 'hello';
      SELECT * FROM t2;
    ROLLBACK;
  }
} {2 3}
do_test trigger9-3.4 {
  execsql {
    BEGIN;
      INSERT INTO t3 VALUES(3, 'three');
      INSERT INTO t3 VALUES(3, 'four');
      CREATE VIEW v1 AS SELECT DISTINCT a, b FROM t3;
      CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN
        INSERT INTO t2 VALUES(old.a);
      END;
      UPDATE v1 SET b = 'hello';
      SELECT * FROM t2;
    ROLLBACK;
  }
} {1 2 3 3}

ifcapable compound {
  do_test trigger9-3.5 {
    execsql {
      BEGIN;
        INSERT INTO t3 VALUES(1, 'uno');
        CREATE VIEW v1 AS SELECT a, b FROM t3 EXCEPT SELECT 1, 'one';
        CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN
          INSERT INTO t2 VALUES(old.a);
        END;
        UPDATE v1 SET b = 'hello';
        SELECT * FROM t2;
      ROLLBACK;
    }
  } {1 2 3}
  do_test trigger9-3.6 {
    execsql {
      BEGIN;
        INSERT INTO t3 VALUES(1, 'zero');
        CREATE VIEW v1 AS 
          SELECT sum(a) AS a, max(b) AS b FROM t3 GROUP BY t3.a HAVING b>'two';
        CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN
          INSERT INTO t2 VALUES(old.a);
        END;
        UPDATE v1 SET b = 'hello';
        SELECT * FROM t2;
      ROLLBACK;
    }
  } {2}
}

finish_test

Added test/triggerA.test.













































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# 2008 February 12
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. Specifically,
# it tests issues relating to firing an INSTEAD OF trigger on a VIEW
# when one tries to UPDATE or DELETE from the view.  Does the WHERE
# clause of the UPDATE or DELETE statement get passed down correctly 
# into the query that manifests the view?
#
# Ticket #2938
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable !trigger||!compound {
  finish_test
  return
}

# Create two table containing some sample data
#
do_test triggerA-1.1 {
  db eval {
    CREATE TABLE t1(x INTEGER PRIMARY KEY, y TEXT UNIQUE);
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b INTEGER UNIQUE, c TEXT);
  }
  set i 1
  foreach word {one two three four five six seven eight nine ten} {
    set j [expr {$i*100 + [string length $word]}]
    db eval {
       INSERT INTO t1 VALUES($i,$word);
       INSERT INTO t2 VALUES(20-$i,$j,$word);
    }
    incr i
  }
  db eval {
    SELECT count(*) FROM t1 UNION ALL SELECT count(*) FROM t2;
  }
} {10 10}

# Create views of various forms against one or both of the two tables.
#
do_test triggerA-1.2 {
  db eval {
     CREATE VIEW v1 AS SELECT y, x FROM t1;
     SELECT * FROM v1 ORDER BY 1;
  }
} {eight 8 five 5 four 4 nine 9 one 1 seven 7 six 6 ten 10 three 3 two 2}
do_test triggerA-1.3 {
  db eval {
     CREATE VIEW v2 AS SELECT x, y FROM t1 WHERE y GLOB '*e*';
     SELECT * FROM v2 ORDER BY 1;
  }
} {1 one 3 three 5 five 7 seven 8 eight 9 nine 10 ten}
do_test triggerA-1.4 {
  db eval {
     CREATE VIEW v3 AS
       SELECT CAST(x AS TEXT) AS c1 FROM t1 UNION SELECT y FROM t1;
     SELECT * FROM v3 ORDER BY c1;
  }
} {1 10 2 3 4 5 6 7 8 9 eight five four nine one seven six ten three two}
do_test triggerA-1.5 {
  db eval {
     CREATE VIEW v4 AS
        SELECT CAST(x AS TEXT) AS c1 FROM t1
        UNION SELECT y FROM t1 WHERE x BETWEEN 3 and 5;
     SELECT * FROM v4 ORDER BY 1;
  }
} {1 10 2 3 4 5 6 7 8 9 five four three}
do_test triggerA-1.6 {
  db eval {
     CREATE VIEW v5 AS SELECT x, b FROM t1, t2 WHERE y=c;
     SELECT * FROM v5;
  }
} {10 1003 9 904 8 805 7 705 6 603 5 504 4 404 3 305 2 203 1 103}

# Create INSTEAD OF triggers on the views.  Run UPDATE and DELETE statements
# using those triggers.  Verify correct operation.
#
do_test triggerA-2.1 {
  db eval {
     CREATE TABLE result2(a,b);
     CREATE TRIGGER r1d INSTEAD OF DELETE ON v1 BEGIN
       INSERT INTO result2(a,b) VALUES(old.y, old.x);
     END;
     DELETE FROM v1 WHERE x=5;
     SELECT * FROM result2;
  }
} {five 5}
do_test triggerA-2.2 {
  db eval {
     CREATE TABLE result4(a,b,c,d);
     CREATE TRIGGER r1u INSTEAD OF UPDATE ON v1 BEGIN
       INSERT INTO result4(a,b,c,d) VALUES(old.y, old.x, new.y, new.x);
     END;
     UPDATE v1 SET y=y||'-extra' WHERE x BETWEEN 3 AND 5;
     SELECT * FROM result4 ORDER BY a;
  }
} {five 5 five-extra 5 four 4 four-extra 4 three 3 three-extra 3}


do_test triggerA-2.3 {
  db eval {
     DELETE FROM result2;
     CREATE TRIGGER r2d INSTEAD OF DELETE ON v2 BEGIN
       INSERT INTO result2(a,b) VALUES(old.y, old.x);
     END;
     DELETE FROM v2 WHERE x=5;
     SELECT * FROM result2;
  }
} {five 5}
do_test triggerA-2.4 {
  db eval {
     DELETE FROM result4;
     CREATE TRIGGER r2u INSTEAD OF UPDATE ON v2 BEGIN
       INSERT INTO result4(a,b,c,d) VALUES(old.y, old.x, new.y, new.x);
     END;
     UPDATE v2 SET y=y||'-extra' WHERE x BETWEEN 3 AND 5;
     SELECT * FROM result4 ORDER BY a;
  }
} {five 5 five-extra 5 three 3 three-extra 3}


do_test triggerA-2.5 {
  db eval {
     CREATE TABLE result1(a);
     CREATE TRIGGER r3d INSTEAD OF DELETE ON v3 BEGIN
       INSERT INTO result1(a) VALUES(old.c1);
     END;
     DELETE FROM v3 WHERE c1 BETWEEN '8' AND 'eight';
     SELECT * FROM result1 ORDER BY a;
  }
} {8 9 eight}
do_test triggerA-2.6 {
  db eval {
     DELETE FROM result2;
     CREATE TRIGGER r3u INSTEAD OF UPDATE ON v3 BEGIN
       INSERT INTO result2(a,b) VALUES(old.c1, new.c1);
     END;
     UPDATE v3 SET c1 = c1 || '-extra' WHERE c1 BETWEEN '8' and 'eight';
     SELECT * FROM result2 ORDER BY a;
  }
} {8 8-extra 9 9-extra eight eight-extra}


do_test triggerA-2.7 {
  db eval {
     DELETE FROM result1;
     CREATE TRIGGER r4d INSTEAD OF DELETE ON v4 BEGIN
       INSERT INTO result1(a) VALUES(old.c1);
     END;
     DELETE FROM v4 WHERE c1 BETWEEN '8' AND 'eight';
     SELECT * FROM result1 ORDER BY a;
  }
} {8 9}
do_test triggerA-2.8 {
  db eval {
     DELETE FROM result2;
     CREATE TRIGGER r4u INSTEAD OF UPDATE ON v4 BEGIN
       INSERT INTO result2(a,b) VALUES(old.c1, new.c1);
     END;
     UPDATE v4 SET c1 = c1 || '-extra' WHERE c1 BETWEEN '8' and 'eight';
     SELECT * FROM result2 ORDER BY a;
  }
} {8 8-extra 9 9-extra}


do_test triggerA-2.9 {
  db eval {
     DELETE FROM result2;
     CREATE TRIGGER r5d INSTEAD OF DELETE ON v5 BEGIN
       INSERT INTO result2(a,b) VALUES(old.x, old.b);
     END;
     DELETE FROM v5 WHERE x=5;
     SELECT * FROM result2;
  }
} {5 504}
do_test triggerA-2.10 {
  db eval {
     DELETE FROM result4;
     CREATE TRIGGER r5u INSTEAD OF UPDATE ON v5 BEGIN
       INSERT INTO result4(a,b,c,d) VALUES(old.x, old.b, new.x, new.b);
     END;
     UPDATE v5 SET b = b+9900000 WHERE x BETWEEN 3 AND 5;
     SELECT * FROM result4 ORDER BY a;
  }
} {3 305 3 9900305 4 404 4 9900404 5 504 5 9900504}

# Only run the reamining tests if memory debugging is turned on.
#
ifcapable !memdebug {
   puts "Skipping triggerA malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}
source $testdir/malloc_common.tcl

# Save a copy of the current database configuration.
#
db close
file delete -force test.db-triggerA
file copy test.db test.db-triggerA
sqlite3 db test.db

# Run malloc tests on the INSTEAD OF trigger firing.
#
do_malloc_test triggerA-3 -tclprep {
  db close
  file delete -force test.db test.db-journal
  file copy -force test.db-triggerA test.db
  sqlite3 db test.db
  sqlite3_extended_result_codes db 1  
  db eval {SELECT * FROM v5; -- warm up the cache}
} -sqlbody {
   DELETE FROM v5 WHERE x=5;
   UPDATE v5 SET b=b+9900000 WHERE x BETWEEN 3 AND 5;
}

# Clean up the saved database copy.
#
file delete -force test.db-triggerA

finish_test

Added test/triggerB.test.



















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# 2008 April 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice', here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. Specifically,
# it tests updating tables with constraints within a trigger.  Ticket #3055.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

# Create test tables with constraints.
#
do_test triggerB-1.1 {
  execsql {
    CREATE TABLE x(x INTEGER PRIMARY KEY, y INT NOT NULL);
    INSERT INTO x(y) VALUES(1);
    INSERT INTO x(y) VALUES(1);
    CREATE TEMP VIEW vx AS SELECT x, y, 0 AS yy FROM x;
    CREATE TEMP TRIGGER tx INSTEAD OF UPDATE OF y ON vx
    BEGIN
      UPDATE x SET y = new.y WHERE x = new.x;
    END;
    SELECT * FROM vx;
  }
} {1 1 0 2 1 0}
do_test triggerB-1.2 {
  execsql {
    UPDATE vx SET y = yy;
    SELECT * FROM vx;
  }
} {1 0 0 2 0 0}

# Added 2008-08-22:
#
# Name resolution within triggers.
#
do_test triggerB-2.1 {
  catchsql {
    CREATE TRIGGER ty AFTER INSERT ON x BEGIN
       SELECT wen.x; -- Unrecognized name
    END;
    INSERT INTO x VALUES(1,2);
  }
} {1 {no such column: wen.x}}
do_test triggerB-2.2 {
  catchsql {
    CREATE TRIGGER tz AFTER UPDATE ON x BEGIN
       SELECT dlo.x; -- Unrecognized name
    END;
    UPDATE x SET y=y+1;
  }
} {1 {no such column: dlo.x}}

do_test triggerB-2.3 {
  execsql {
    CREATE TABLE t2(a INTEGER PRIMARY KEY, b);
    INSERT INTO t2 VALUES(1,2);
    CREATE TABLE changes(x,y);
    CREATE TRIGGER r1t2 AFTER UPDATE ON t2 BEGIN
      INSERT INTO changes VALUES(new.a, new.b);
    END;
  }
  execsql {
    UPDATE t2 SET a=a+10;
    SELECT * FROM changes;
  }
} {11 2}
do_test triggerB-2.4 {
  execsql {
    CREATE TRIGGER r2t2 AFTER DELETE ON t2 BEGIN
      INSERT INTO changes VALUES(old.a, old.c);
    END;
  }
  catchsql {
    DELETE FROM t2;
  }
} {1 {no such column: old.c}}

# Triggers maintain a mask of columns from the invoking table that are
# used in the trigger body as NEW.column or OLD.column.  That mask is then
# used to reduce the amount of information that needs to be loaded into
# the NEW and OLD pseudo-tables at run-time.
#
# These tests cases check the logic for when there are many columns - more
# than will fit in a bitmask.
#
do_test triggerB-3.1 {
  execsql {
    CREATE TABLE t3(
       c0,  c1,  c2,  c3,  c4,  c5,  c6,  c7,  c8,  c9,
       c10, c11, c12, c13, c14, c15, c16, c17, c18, c19,
       c20, c21, c22, c23, c24, c25, c26, c27, c28, c29,
       c30, c31, c32, c33, c34, c35, c36, c37, c38, c39,
       c40, c41, c42, c43, c44, c45, c46, c47, c48, c49,
       c50, c51, c52, c53, c54, c55, c56, c57, c58, c59,
       c60, c61, c62, c63, c64, c65
    );
    CREATE TABLE t3_changes(colnum, oldval, newval);
    INSERT INTO t3 VALUES(
       'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9',
       'a10','a11','a12','a13','a14','a15','a16','a17','a18','a19',
       'a20','a21','a22','a23','a24','a25','a26','a27','a28','a29',
       'a30','a31','a32','a33','a34','a35','a36','a37','a38','a39',
       'a40','a41','a42','a43','a44','a45','a46','a47','a48','a49',
       'a50','a51','a52','a53','a54','a55','a56','a57','a58','a59',
       'a60','a61','a62','a63','a64','a65'
    );
  }
  for {set i 0} {$i<=65} {incr i} {
    set sql [subst {
      CREATE TRIGGER t3c$i AFTER UPDATE ON t3
         WHEN old.c$i!=new.c$i BEGIN
          INSERT INTO t3_changes VALUES($i, old.c$i, new.c$i);
      END
    }]
    db eval $sql
  }
  execsql {
    SELECT * FROM t3_changes
  }
} {}
for {set i 0} {$i<=64} {incr i} {
  do_test triggerB-3.2.$i.1 [subst {
    execsql {
      UPDATE t3 SET c$i='b$i';
      SELECT * FROM t3_changes ORDER BY rowid DESC LIMIT 1;
    }
  }] [subst {$i a$i b$i}]
  do_test triggerB-3.2.$i.2 [subst {
    execsql {
      SELECT count(*) FROM t3_changes
    }
  }] [expr {$i+1}]
  do_test triggerB-3.2.$i.2 [subst {
    execsql {
      SELECT * FROM t3_changes WHERE colnum=$i
    }
  }] [subst {$i a$i b$i}]
}
  

finish_test

Added test/triggerC.test.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# 2009 August 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice', here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
ifcapable {!trigger} {
  finish_test
  return
}

#-------------------------------------------------------------------------
# Test organization:
#
# triggerC-1.*: Haphazardly designed trigger related tests that were useful
#               during an upgrade of the triggers sub-system.
# 
# triggerC-2.*:
#
# triggerC-3.*:
#
# triggerC-4.*:
#
# triggerC-5.*: Test that when recursive triggers are enabled DELETE 
#               triggers are fired when rows are deleted as part of OR
#               REPLACE conflict resolution. And that they are not fired
#               if recursive triggers are not enabled.
#
# triggerC-6.*: Test that the recursive_triggers pragma returns correct
#               results when invoked without an argument.
#

# Enable recursive triggers for this file.
#
execsql { PRAGMA recursive_triggers = on }

#sqlite3_db_config_lookaside db 0 0 0

#-------------------------------------------------------------------------
# This block of tests, triggerC-1.*, are not aimed at any specific
# property of the triggers sub-system. They were created to debug
# specific problems while modifying SQLite to support recursive
# triggers. They are left here in case they can help debug the
# same problems again.
#
do_test triggerC-1.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    CREATE TABLE log(t, a1, b1, c1, a2, b2, c2);
    CREATE TRIGGER trig1 BEFORE INSERT ON t1 BEGIN
      INSERT INTO log VALUES('before', NULL, NULL, NULL, new.a, new.b, new.c);
    END;
    CREATE TRIGGER trig2 AFTER INSERT ON t1 BEGIN
      INSERT INTO log VALUES('after', NULL, NULL, NULL, new.a, new.b, new.c);
    END;
    CREATE TRIGGER trig3 BEFORE UPDATE ON t1 BEGIN
      INSERT INTO log VALUES('before', old.a,old.b,old.c, new.a,new.b,new.c);
    END;
    CREATE TRIGGER trig4 AFTER UPDATE ON t1 BEGIN
      INSERT INTO log VALUES('after', old.a,old.b,old.c, new.a,new.b,new.c);
    END;

    CREATE TRIGGER trig5 BEFORE DELETE ON t1 BEGIN
      INSERT INTO log VALUES('before', old.a,old.b,old.c, NULL,NULL,NULL);
    END;
    CREATE TRIGGER trig6 AFTER DELETE ON t1 BEGIN
      INSERT INTO log VALUES('after', old.a,old.b,old.c, NULL,NULL,NULL);
    END;
  }
} {}
do_test triggerC-1.2 {
  execsql {
    INSERT INTO t1 VALUES('A', 'B', 'C');
    SELECT * FROM log;
  }
} {before {} {} {} A B C after {} {} {} A B C}
do_test triggerC-1.3 {
  execsql { SELECT * FROM t1 }
} {A B C}
do_test triggerC-1.4 {
  execsql {
    DELETE FROM log;
    UPDATE t1 SET a = 'a';
    SELECT * FROM log;
  }
} {before A B C a B C after A B C a B C}
do_test triggerC-1.5 {
  execsql { SELECT * FROM t1 }
} {a B C}
do_test triggerC-1.6 {
  execsql {
    DELETE FROM log;
    DELETE FROM t1;
    SELECT * FROM log;
  }
} {before a B C {} {} {} after a B C {} {} {}}
do_test triggerC-1.7 {
  execsql { SELECT * FROM t1 }
} {}
do_test triggerC-1.8 {
  execsql {
    CREATE TABLE t4(a, b);
    CREATE TRIGGER t4t AFTER DELETE ON t4 BEGIN
      SELECT RAISE(ABORT, 'delete is not supported');
    END;
  }
} {}
do_test triggerC-1.9 {
  execsql { INSERT INTO t4 VALUES(1, 2) }
  catchsql { DELETE FROM t4 }
} {1 {delete is not supported}}
do_test triggerC-1.10 {
  execsql { SELECT * FROM t4 }
} {1 2}
do_test triggerC-1.11 {
  execsql {
    CREATE TABLE t5 (a primary key, b, c);
    INSERT INTO t5 values (1, 2, 3);
    CREATE TRIGGER au_tbl AFTER UPDATE ON t5 BEGIN
      UPDATE OR IGNORE t5 SET a = new.a, c = 10;
    END;
  }
} {}
do_test triggerC-1.12 {
  catchsql { UPDATE OR REPLACE t5 SET a = 4 WHERE a = 1 }
} {1 {too many levels of trigger recursion}}
do_test triggerC-1.13 {
  execsql {
    CREATE TABLE t6(a INTEGER PRIMARY KEY, b);
    INSERT INTO t6 VALUES(1, 2);
    create trigger r1 after update on t6 for each row begin
      SELECT 1;
    end;
    UPDATE t6 SET a=a; 
  }
} {}
do_test triggerC-1.14 {
  execsql {
    DROP TABLE t1;
    CREATE TABLE cnt(n);
    INSERT INTO cnt VALUES(0);
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE, c, d, e);
    CREATE INDEX t1cd ON t1(c,d);
    CREATE TRIGGER t1r1 AFTER UPDATE ON t1 BEGIN UPDATE cnt SET n=n+1; END;
    INSERT INTO t1 VALUES(1,2,3,4,5);
    INSERT INTO t1 VALUES(6,7,8,9,10);
    INSERT INTO t1 VALUES(11,12,13,14,15);
  }
} {}
do_test triggerC-1.15 {
  catchsql { UPDATE OR ROLLBACK t1 SET a=100 }
} {1 {PRIMARY KEY must be unique}}


#-------------------------------------------------------------------------
# This block of tests, triggerC-2.*, tests that recursive trigger
# programs (triggers that fire themselves) work. More specifically,
# this block focuses on recursive INSERT triggers.
#
do_test triggerC-2.1.0 {
  execsql {
    CREATE TABLE t2(a PRIMARY KEY);
  }
} {}

foreach {n tdefn rc} {
  1 { 
    CREATE TRIGGER t2_trig AFTER INSERT ON t2 WHEN (new.a>0) BEGIN
      INSERT INTO t2 VALUES(new.a - 1);
    END; 
  } {0 {10 9 8 7 6 5 4 3 2 1 0}}

  2 {
    CREATE TRIGGER t2_trig AFTER INSERT ON t2 BEGIN
      SELECT CASE WHEN new.a==2 THEN RAISE(IGNORE) ELSE NULL END;
      INSERT INTO t2 VALUES(new.a - 1);
    END;
  } {0 {10 9 8 7 6 5 4 3 2}}

  3 { 
    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 WHEN (new.a>0) BEGIN
      INSERT INTO t2 VALUES(new.a - 1);
    END; 
  } {0 {0 1 2 3 4 5 6 7 8 9 10}}

  4 { 
    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 BEGIN
      SELECT CASE WHEN new.a==2 THEN RAISE(IGNORE) ELSE NULL END;
      INSERT INTO t2 VALUES(new.a - 1);
    END;
  } {0 {3 4 5 6 7 8 9 10}}

  5 { 
    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 BEGIN
      INSERT INTO t2 VALUES(new.a - 1);
    END;
  } {1 {too many levels of trigger recursion}}

  6 { 
    CREATE TRIGGER t2_trig AFTER INSERT ON t2 WHEN (new.a>0) BEGIN
      INSERT OR IGNORE INTO t2 VALUES(new.a);
    END;
  } {0 10}

  7 { 
    CREATE TRIGGER t2_trig BEFORE INSERT ON t2 WHEN (new.a>0) BEGIN
      INSERT OR IGNORE INTO t2 VALUES(new.a);
    END;
  } {1 {too many levels of trigger recursion}}
} {
  do_test triggerC-2.1.$n {
    catchsql { DROP TRIGGER t2_trig }
    execsql  { DELETE FROM t2 }
    execsql  $tdefn
    catchsql {
      INSERT INTO t2 VALUES(10);
      SELECT * FROM t2;
    }
  } $rc
}

do_test triggerC-2.2 {
  execsql {
    CREATE TABLE t22(x);

    CREATE TRIGGER t22a AFTER INSERT ON t22 BEGIN
      INSERT INTO t22 SELECT x + (SELECT max(x) FROM t22) FROM t22;
    END;
    CREATE TRIGGER t22b BEFORE INSERT ON t22 BEGIN
      SELECT CASE WHEN (SELECT count(*) FROM t22) >= 100
                  THEN RAISE(IGNORE)
                  ELSE NULL END;
    END;

    INSERT INTO t22 VALUES(1);
    SELECT count(*) FROM t22;
  }
} {100}

do_test triggerC-2.3 {
  execsql {
    CREATE TABLE t23(x PRIMARY KEY);

    CREATE TRIGGER t23a AFTER INSERT ON t23 BEGIN
      INSERT INTO t23 VALUES(new.x + 1);
    END;

    CREATE TRIGGER t23b BEFORE INSERT ON t23 BEGIN
      SELECT CASE WHEN new.x>500
                  THEN RAISE(IGNORE)
                  ELSE NULL END;
    END;

    INSERT INTO t23 VALUES(1);
    SELECT count(*) FROM t23;
  }
} {500}
 

#-----------------------------------------------------------------------
# This block of tests, triggerC-3.*, test that SQLite throws an exception
# when it detects excessive recursion.
#
do_test triggerC-3.1.1 {
  execsql {
    CREATE TABLE t3(a, b);
    CREATE TRIGGER t3i AFTER INSERT ON t3 BEGIN
      DELETE FROM t3 WHERE rowid = new.rowid;
    END;
    CREATE TRIGGER t3d AFTER DELETE ON t3 BEGIN
      INSERT INTO t3 VALUES(old.a, old.b);
    END;
  }
} {}
do_test triggerC-3.1.2 {
  catchsql { INSERT INTO t3 VALUES(0,0) }
} {1 {too many levels of trigger recursion}}
do_test triggerC-3.1.3 {
  execsql { SELECT * FROM t3 }
} {}

do_test triggerC-3.2.1 {
  execsql {
    CREATE TABLE t3b(x);
    CREATE TRIGGER t3bi AFTER INSERT ON t3b WHEN new.x<2000 BEGIN
      INSERT INTO t3b VALUES(new.x+1);
    END;
  }
  catchsql {
    INSERT INTO t3b VALUES(1);
  }
} {1 {too many levels of trigger recursion}}
do_test triggerC-3.2.2 {
  db eval {SELECT * FROM t3b}
} {}

do_test triggerC-3.3.1 {
  catchsql {
    INSERT INTO t3b VALUES(1001);
  }
} {0 {}}
do_test triggerC-3.3.2 {
  db eval {SELECT count(*), max(x), min(x) FROM t3b}
} {1000 2000 1001}

do_test triggerC-3.4.1 {
  catchsql {
    DELETE FROM t3b;
    INSERT INTO t3b VALUES(999);
  }
} {1 {too many levels of trigger recursion}}
do_test triggerC-3.4.2 {
  db eval {SELECT count(*), max(x), min(x) FROM t3b}
} {0 {} {}}

do_test triggerC-3.5.1 {
  sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 100
  catchsql {
    INSERT INTO t3b VALUES(1901);
  }
} {0 {}}
do_test triggerC-3.5.2 {
  db eval {SELECT count(*), max(x), min(x) FROM t3b}
} {100 2000 1901}

do_test triggerC-3.5.3 {
  catchsql {
    DELETE FROM t3b;
    INSERT INTO t3b VALUES(1900);
  }
} {1 {too many levels of trigger recursion}}
do_test triggerC-3.5.4 {
  db eval {SELECT count(*), max(x), min(x) FROM t3b}
} {0 {} {}}

do_test triggerC-3.6.1 {
  sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1
  catchsql {
    INSERT INTO t3b VALUES(2000);
  }
} {0 {}}
do_test triggerC-3.6.2 {
  db eval {SELECT count(*), max(x), min(x) FROM t3b}
} {1 2000 2000}

do_test triggerC-3.6.3 {
  catchsql {
    DELETE FROM t3b;
    INSERT INTO t3b VALUES(1999);
  }
} {1 {too many levels of trigger recursion}}
do_test triggerC-3.6.4 {
  db eval {SELECT count(*), max(x), min(x) FROM t3b}
} {0 {} {}}
sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1000
      

#-----------------------------------------------------------------------
# This next block of tests, triggerC-4.*, checks that affinity 
# transformations and constraint processing is performed at the correct 
# times relative to BEFORE and AFTER triggers.
#
# For an INSERT statement, for each row to be inserted:
#
#   1. Apply affinities to non-rowid values to be inserted.
#   2. Fire BEFORE triggers.
#   3. Process constraints.
#   4. Insert new record.
#   5. Fire AFTER triggers.
#
# If the value of the rowid field is to be automatically assigned, it is
# set to -1 in the new.* record. Even if it is explicitly set to NULL
# by the INSERT statement.
#
# For an UPDATE statement, for each row to be deleted:
#
#   1. Apply affinities to non-rowid values to be inserted.
#   2. Fire BEFORE triggers.
#   3. Process constraints.
#   4. Insert new record.
#   5. Fire AFTER triggers.
#
# For a DELETE statement, for each row to be deleted:
#
#   1. Fire BEFORE triggers.
#   2. Remove database record.
#   3. Fire AFTER triggers.
#
# When a numeric value that as an exact integer representation is stored
# in a column with REAL affinity, it is actually stored as an integer.
# These tests check that the typeof() such values is always 'real',
# not 'integer'.
#
# triggerC-4.1.*: Check that affinity transformations are made before
#                 triggers are invoked.
#
do_test triggerC-4.1.1 {
  catchsql { DROP TABLE log }
  catchsql { DROP TABLE t4 }
  execsql {
    CREATE TABLE log(t);
    CREATE TABLE t4(a TEXT,b INTEGER,c REAL);
    CREATE TRIGGER t4bi BEFORE INSERT ON t4 BEGIN
      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
                             new.a     || ' ' || typeof(new.a)     || ' ' ||
                             new.b     || ' ' || typeof(new.b)     || ' ' ||
                             new.c     || ' ' || typeof(new.c)
      );
    END;
    CREATE TRIGGER t4ai AFTER INSERT ON t4 BEGIN
      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
                             new.a     || ' ' || typeof(new.a)     || ' ' ||
                             new.b     || ' ' || typeof(new.b)     || ' ' ||
                             new.c     || ' ' || typeof(new.c)
      );
    END;
    CREATE TRIGGER t4bd BEFORE DELETE ON t4 BEGIN
      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
                             old.a     || ' ' || typeof(old.a)     || ' ' ||
                             old.b     || ' ' || typeof(old.b)     || ' ' ||
                             old.c     || ' ' || typeof(old.c)
      );
    END;
    CREATE TRIGGER t4ad AFTER DELETE ON t4 BEGIN
      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
                             old.a     || ' ' || typeof(old.a)     || ' ' ||
                             old.b     || ' ' || typeof(old.b)     || ' ' ||
                             old.c     || ' ' || typeof(old.c)
      );
    END;
    CREATE TRIGGER t4bu BEFORE UPDATE ON t4 BEGIN
      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
                             old.a     || ' ' || typeof(old.a)     || ' ' ||
                             old.b     || ' ' || typeof(old.b)     || ' ' ||
                             old.c     || ' ' || typeof(old.c)
      );
      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
                             new.a     || ' ' || typeof(new.a)     || ' ' ||
                             new.b     || ' ' || typeof(new.b)     || ' ' ||
                             new.c     || ' ' || typeof(new.c)
      );
    END;
    CREATE TRIGGER t4au AFTER UPDATE ON t4 BEGIN
      INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' ||
                             old.a     || ' ' || typeof(old.a)     || ' ' ||
                             old.b     || ' ' || typeof(old.b)     || ' ' ||
                             old.c     || ' ' || typeof(old.c)
      );
      INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' ||
                             new.a     || ' ' || typeof(new.a)     || ' ' ||
                             new.b     || ' ' || typeof(new.b)     || ' ' ||
                             new.c     || ' ' || typeof(new.c)
      );
    END;
  }
} {}
foreach {n insert log} {

  2 { 
   INSERT INTO t4 VALUES('1', '1', '1');
   DELETE FROM t4;
  } {
    -1 integer 1 text 1 integer 1.0 real 
     1 integer 1 text 1 integer 1.0 real
     1 integer 1 text 1 integer 1.0 real 
     1 integer 1 text 1 integer 1.0 real
  }

  3 { 
   INSERT INTO t4(rowid,a,b,c) VALUES(45, 45, 45, 45);
   DELETE FROM t4;
  } {
    45 integer 45 text 45 integer 45.0 real
    45 integer 45 text 45 integer 45.0 real
    45 integer 45 text 45 integer 45.0 real
    45 integer 45 text 45 integer 45.0 real
  }

  4 { 
   INSERT INTO t4(rowid,a,b,c) VALUES(-42.0, -42.0, -42.0, -42.0);
   DELETE FROM t4;
  } {
    -42 integer -42.0 text -42 integer -42.0 real 
    -42 integer -42.0 text -42 integer -42.0 real
    -42 integer -42.0 text -42 integer -42.0 real 
    -42 integer -42.0 text -42 integer -42.0 real
  }

  5 { 
   INSERT INTO t4(rowid,a,b,c) VALUES(NULL, -42.4, -42.4, -42.4);
   DELETE FROM t4;
  } {
    -1 integer -42.4 text -42.4 real -42.4 real
     1 integer -42.4 text -42.4 real -42.4 real
     1 integer -42.4 text -42.4 real -42.4 real
     1 integer -42.4 text -42.4 real -42.4 real
  }

  6 { 
   INSERT INTO t4 VALUES(7, 7, 7);
   UPDATE t4 SET a=8, b=8, c=8;
  } {
    -1 integer 7 text 7 integer 7.0 real
     1 integer 7 text 7 integer 7.0 real
     1 integer 7 text 7 integer 7.0 real
     1 integer 8 text 8 integer 8.0 real
     1 integer 7 text 7 integer 7.0 real
     1 integer 8 text 8 integer 8.0 real
  }

  7 { 
   UPDATE t4 SET rowid=2;
  } {
     1 integer 8 text 8 integer 8.0 real
     2 integer 8 text 8 integer 8.0 real
     1 integer 8 text 8 integer 8.0 real
     2 integer 8 text 8 integer 8.0 real
  }

  8 { 
   UPDATE t4 SET a='9', b='9', c='9';
  } {
     2 integer 8 text 8 integer 8.0 real
     2 integer 9 text 9 integer 9.0 real
     2 integer 8 text 8 integer 8.0 real
     2 integer 9 text 9 integer 9.0 real
  }

  9 { 
   UPDATE t4 SET a='9.1', b='9.1', c='9.1';
  } {
     2 integer 9   text 9   integer 9.0 real
     2 integer 9.1 text 9.1 real    9.1 real
     2 integer 9   text 9   integer 9.0 real
     2 integer 9.1 text 9.1 real    9.1 real
  }
} {
  do_test triggerC-4.1.$n {
    eval concat [execsql " 
      DELETE FROM log;
      $insert ; 
      SELECT * FROM log;
    "]
  } [join $log " "]
} 

#-------------------------------------------------------------------------
# This block of tests, triggerC-5.*, test that DELETE triggers are fired
# if a row is deleted as a result of OR REPLACE conflict resolution.
#
do_test triggerC-5.1.0 {
  execsql {
    DROP TABLE IF EXISTS t5;
    CREATE TABLE t5(a INTEGER PRIMARY KEY, b);
    CREATE UNIQUE INDEX t5i ON t5(b);
    INSERT INTO t5 VALUES(1, 'a');
    INSERT INTO t5 VALUES(2, 'b');
    INSERT INTO t5 VALUES(3, 'c');

    CREATE TABLE t5g(a, b, c);
    CREATE TRIGGER t5t BEFORE DELETE ON t5 BEGIN
      INSERT INTO t5g VALUES(old.a, old.b, (SELECT count(*) FROM t5));
    END;
  }
} {}
foreach {n dml t5g t5} {
  1 "DELETE FROM t5 WHERE a=2"                        {2 b 3} {1 a 3 c}
  2 "INSERT OR REPLACE INTO t5 VALUES(2, 'd')"        {2 b 3} {1 a 2 d 3 c}
  3 "UPDATE OR REPLACE t5 SET a = 2 WHERE a = 3"      {2 b 3} {1 a 2 c}
  4 "INSERT OR REPLACE INTO t5 VALUES(4, 'b')"        {2 b 3} {1 a 3 c 4 b}
  5 "UPDATE OR REPLACE t5 SET b = 'b' WHERE b = 'c'"  {2 b 3} {1 a 3 b}
  6 "INSERT OR REPLACE INTO t5 VALUES(2, 'c')"        {2 b 3 3 c 2} {1 a 2 c}
  7 "UPDATE OR REPLACE t5 SET a=1, b='b' WHERE a = 3" {1 a 3 2 b 2} {1 b}
} {
  do_test triggerC-5.1.$n {
    execsql "
      BEGIN;
        $dml ;
        SELECT * FROM t5g;
        SELECT * FROM t5;
      ROLLBACK;
    "
  } [concat $t5g $t5]
}
do_test triggerC-5.2.0 {
  execsql {
    DROP TRIGGER t5t;
    CREATE TRIGGER t5t AFTER DELETE ON t5 BEGIN
      INSERT INTO t5g VALUES(old.a, old.b, (SELECT count(*) FROM t5));
    END;
  }
} {}
foreach {n dml t5g t5} {
  1 "DELETE FROM t5 WHERE a=2"                        {2 b 2} {1 a 3 c}
  2 "INSERT OR REPLACE INTO t5 VALUES(2, 'd')"        {2 b 2} {1 a 2 d 3 c}
  3 "UPDATE OR REPLACE t5 SET a = 2 WHERE a = 3"      {2 b 2} {1 a 2 c}
  4 "INSERT OR REPLACE INTO t5 VALUES(4, 'b')"        {2 b 2} {1 a 3 c 4 b}
  5 "UPDATE OR REPLACE t5 SET b = 'b' WHERE b = 'c'"  {2 b 2} {1 a 3 b}
  6 "INSERT OR REPLACE INTO t5 VALUES(2, 'c')"        {2 b 2 3 c 1} {1 a 2 c}
  7 "UPDATE OR REPLACE t5 SET a=1, b='b' WHERE a = 3" {1 a 2 2 b 1} {1 b}
} {
  do_test triggerC-5.2.$n {
    execsql "
      BEGIN;
        $dml ;
        SELECT * FROM t5g;
        SELECT * FROM t5;
      ROLLBACK;
    "
  } [concat $t5g $t5]
}
do_test triggerC-5.3.0 {
  execsql { PRAGMA recursive_triggers = off }
} {}
foreach {n dml t5g t5} {
  1 "DELETE FROM t5 WHERE a=2"                        {2 b 2} {1 a 3 c}
  2 "INSERT OR REPLACE INTO t5 VALUES(2, 'd')"        {} {1 a 2 d 3 c}
  3 "UPDATE OR REPLACE t5 SET a = 2 WHERE a = 3"      {} {1 a 2 c}
  4 "INSERT OR REPLACE INTO t5 VALUES(4, 'b')"        {} {1 a 3 c 4 b}
  5 "UPDATE OR REPLACE t5 SET b = 'b' WHERE b = 'c'"  {} {1 a 3 b}
  6 "INSERT OR REPLACE INTO t5 VALUES(2, 'c')"        {} {1 a 2 c}
  7 "UPDATE OR REPLACE t5 SET a=1, b='b' WHERE a = 3" {} {1 b}
} {
  do_test triggerC-5.3.$n {
    execsql "
      BEGIN;
        $dml ;
        SELECT * FROM t5g;
        SELECT * FROM t5;
      ROLLBACK;
    "
  } [concat $t5g $t5]
}
do_test triggerC-5.3.8 {
  execsql { PRAGMA recursive_triggers = on }
} {}

#-------------------------------------------------------------------------
# This block of tests, triggerC-6.*, tests that "PRAGMA recursive_triggers"
# statements return the current value of the recursive triggers flag.
#
do_test triggerC-6.1 {
  execsql { PRAGMA recursive_triggers }
} {1}
do_test triggerC-6.2 {
  execsql { 
    PRAGMA recursive_triggers = off;
    PRAGMA recursive_triggers;
  }
} {0}
do_test triggerC-6.3 {
  execsql { 
    PRAGMA recursive_triggers = on;
    PRAGMA recursive_triggers;
  }
} {1}

#-------------------------------------------------------------------------
# Test some of the "undefined behaviour" associated with triggers. The
# undefined behaviour occurs when a row being updated or deleted is 
# manipulated by a BEFORE trigger.
# 
do_test triggerC-7.1 {
  execsql {
    CREATE TABLE t8(x);
    CREATE TABLE t7(a, b);
    INSERT INTO t7 VALUES(1, 2);
    INSERT INTO t7 VALUES(3, 4);
    INSERT INTO t7 VALUES(5, 6);
    CREATE TRIGGER t7t BEFORE UPDATE ON t7 BEGIN
      DELETE FROM t7 WHERE a = 1;
    END;
    CREATE TRIGGER t7ta AFTER UPDATE ON t7 BEGIN
      INSERT INTO t8 VALUES('after fired ' || old.rowid || '->' || new.rowid);
    END;
  }
} {}
do_test triggerC-7.2 {
  execsql {
    BEGIN;
      UPDATE t7 SET b=7 WHERE a = 5;
      SELECT * FROM t7;
      SELECT * FROM t8;
    ROLLBACK;
  }
} {3 4 5 7 {after fired 3->3}}
do_test triggerC-7.3 {
  execsql {
    BEGIN;
      UPDATE t7 SET b=7 WHERE a = 1;
      SELECT * FROM t7;
      SELECT * FROM t8;
    ROLLBACK;
  }
} {3 4 5 6}

do_test triggerC-7.4 {
  execsql {
    DROP TRIGGER t7t;
    CREATE TRIGGER t7t BEFORE UPDATE ON t7 WHEN (old.rowid!=1 OR new.rowid!=8)
    BEGIN
      UPDATE t7 set rowid = 8 WHERE rowid=1;
    END;
  }
} {}
do_test triggerC-7.5 {
  execsql {
    BEGIN;
      UPDATE t7 SET b=7 WHERE a = 5;
      SELECT rowid, * FROM t7;
      SELECT * FROM t8;
    ROLLBACK;
  }
} {2 3 4 3 5 7 8 1 2 {after fired 1->8} {after fired 3->3}}
do_test triggerC-7.6 {
  execsql {
    BEGIN;
      UPDATE t7 SET b=7 WHERE a = 1;
      SELECT rowid, * FROM t7;
      SELECT * FROM t8;
    ROLLBACK;
  }
} {2 3 4 3 5 6 8 1 2 {after fired 1->8}}

do_test triggerC-7.7 {
  execsql {
    DROP TRIGGER t7t;
    DROP TRIGGER t7ta;
    CREATE TRIGGER t7t BEFORE DELETE ON t7 BEGIN
      UPDATE t7 set rowid = 8 WHERE rowid=1;
    END;
    CREATE TRIGGER t7ta AFTER DELETE ON t7 BEGIN
      INSERT INTO t8 VALUES('after fired ' || old.rowid);
    END;
  }
} {}
do_test triggerC-7.8 {
  execsql {
    BEGIN;
      DELETE FROM t7 WHERE a = 3;
      SELECT rowid, * FROM t7;
      SELECT * FROM t8;
    ROLLBACK;
  }
} {3 5 6 8 1 2 {after fired 2}}
do_test triggerC-7.9 {
  execsql {
    BEGIN;
      DELETE FROM t7 WHERE a = 1;
      SELECT rowid, * FROM t7;
      SELECT * FROM t8;
    ROLLBACK;
  }
} {2 3 4 3 5 6 8 1 2}

# Ticket [e25d9ea771febc9c311928c1c01c3163dcb26643]
# 
do_test triggerC-9.1 {
  execsql {
    CREATE TABLE t9(a,b);
    CREATE INDEX t9b ON t9(b);
    INSERT INTO t9 VALUES(1,0);
    INSERT INTO t9 VALUES(2,1);
    INSERT INTO t9 VALUES(3,2);
    INSERT INTO t9 SELECT a+3, a+2 FROM t9;
    INSERT INTO t9 SELECT a+6, a+5 FROM t9;
    SELECT a FROM t9 ORDER BY a;
  }
} {1 2 3 4 5 6 7 8 9 10 11 12}
do_test triggerC-9.2 {
  execsql {
    CREATE TRIGGER t9r1 AFTER DELETE ON t9 BEGIN
      DELETE FROM t9 WHERE b=old.a;
    END;
    DELETE FROM t9 WHERE b=4;
    SELECT a FROM t9 ORDER BY a;
  }
} {1 2 3 4}
 



finish_test

Added test/types.test.











































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. Specfically
# it tests that the different storage classes (integer, real, text etc.)
# all work correctly.
#
# $Id: types.test,v 1.20 2009/06/29 06:00:37 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Tests in this file are organized roughly as follows:
#
# types-1.*.*: Test that values are stored using the expected storage
#              classes when various forms of literals are inserted into
#              columns with different affinities.
# types-1.1.*: INSERT INTO <table> VALUES(...)
# types-1.2.*: INSERT INTO <table> SELECT...
# types-1.3.*: UPDATE <table> SET...
#
# types-2.*.*: Check that values can be stored and retrieving using the
#              various storage classes.
# types-2.1.*: INTEGER
# types-2.2.*: REAL
# types-2.3.*: NULL
# types-2.4.*: TEXT
# types-2.5.*: Records with a few different storage classes.
#
# types-3.*: Test that the '=' operator respects manifest types.
#

# Disable encryption on the database for this test.
db close
set DB [sqlite3 db test.db; sqlite3_connection_pointer db]
sqlite3_rekey $DB {}

# Create a table with one column for each type of affinity
do_test types-1.1.0 {
  execsql {
    CREATE TABLE t1(i integer, n numeric, t text, o blob);
  }
} {}

# Each element of the following list represents one test case.
#
# The first value of each sub-list is an SQL literal. The following
# four value are the storage classes that would be used if the
# literal were inserted into a column with affinity INTEGER, NUMERIC, TEXT
# or NONE, respectively.
set values {
  { 5.0    integer integer text real    }
  { 5.1    real    real    text real    }
  { 5      integer integer text integer }
  { '5.0'  integer integer text text    }
  { '5.1'  real    real    text text    }
  { '-5.0' integer integer text text    }
  { '-5.0' integer integer text text    }
  { '5'    integer integer text text    }
  { 'abc'  text    text    text text    }
  { NULL   null    null    null null    }
}
ifcapable {bloblit} {
  lappend values  { X'00'  blob    blob    blob blob    }
}

# This code tests that the storage classes specified above (in the $values
# table) are correctly assigned when values are inserted using a statement
# of the form:
#
# INSERT INTO <table> VALUE(<values>);
#
set tnum 1
foreach val $values {
  set lit [lindex $val 0]
  execsql "DELETE FROM t1;"
  execsql "INSERT INTO t1 VALUES($lit, $lit, $lit, $lit);"
  do_test types-1.1.$tnum {
    execsql {
      SELECT typeof(i), typeof(n), typeof(t), typeof(o) FROM t1;
    }
  } [lrange $val 1 end]
  incr tnum
}

# This code tests that the storage classes specified above (in the $values
# table) are correctly assigned when values are inserted using a statement
# of the form:
#
# INSERT INTO t1 SELECT ....
#
set tnum 1
foreach val $values {
  set lit [lindex $val 0]
  execsql "DELETE FROM t1;"
  execsql "INSERT INTO t1 SELECT $lit, $lit, $lit, $lit;"
  do_test types-1.2.$tnum {
    execsql {
      SELECT typeof(i), typeof(n), typeof(t), typeof(o) FROM t1;
    }
  } [lrange $val 1 end]
  incr tnum
}

# This code tests that the storage classes specified above (in the $values
# table) are correctly assigned when values are inserted using a statement
# of the form:
#
# UPDATE <table> SET <column> = <value>;
#
set tnum 1
foreach val $values {
  set lit [lindex $val 0]
  execsql "UPDATE t1 SET i = $lit, n = $lit, t = $lit, o = $lit;"
  do_test types-1.3.$tnum {
    execsql {
      SELECT typeof(i), typeof(n), typeof(t), typeof(o) FROM t1;
    }
  } [lrange $val 1 end]
  incr tnum
}

execsql {
  DROP TABLE t1;
}

# Open the table with root-page $rootpage at the btree
# level. Return a list that is the length of each record
# in the table, in the tables default scanning order.
proc record_sizes {rootpage} {
  set bt [btree_open test.db 10 0]
  btree_begin_transaction $bt
  set c [btree_cursor $bt $rootpage 0]
  btree_first $c
  while 1 {
    lappend res [btree_payload_size $c]
    if {[btree_next $c]} break
  }
  btree_close_cursor $c
  btree_close $bt
  set res
}


# Create a table and insert some 1-byte integers. Make sure they 
# can be read back OK. These should be 3 byte records.
do_test types-2.1.1 {
  execsql {
    CREATE TABLE t1(a integer);
    INSERT INTO t1 VALUES(0);
    INSERT INTO t1 VALUES(120);
    INSERT INTO t1 VALUES(-120);
  }
} {}
do_test types-2.1.2 {
  execsql {
    SELECT a FROM t1;
  }
} {0 120 -120}

# Try some 2-byte integers (4 byte records)
do_test types-2.1.3 {
  execsql {
    INSERT INTO t1 VALUES(30000);
    INSERT INTO t1 VALUES(-30000);
  }
} {}
do_test types-2.1.4 {
  execsql {
    SELECT a FROM t1;
  }
} {0 120 -120 30000 -30000}

# 4-byte integers (6 byte records)
do_test types-2.1.5 {
  execsql {
    INSERT INTO t1 VALUES(2100000000);
    INSERT INTO t1 VALUES(-2100000000);
  }
} {}
do_test types-2.1.6 {
  execsql {
    SELECT a FROM t1;
  }
} {0 120 -120 30000 -30000 2100000000 -2100000000}

# 8-byte integers (10 byte records)
do_test types-2.1.7 {
  execsql {
    INSERT INTO t1 VALUES(9000000*1000000*1000000);
    INSERT INTO t1 VALUES(-9000000*1000000*1000000);
  }
} {}
do_test types-2.1.8 {
  execsql {
    SELECT a FROM t1;
  }
} [list 0 120 -120 30000 -30000 2100000000 -2100000000 \
        9000000000000000000 -9000000000000000000]

# Check that all the record sizes are as we expected.
ifcapable legacyformat {
  do_test types-2.1.9 {
    set root [db eval {select rootpage from sqlite_master where name = 't1'}]
    record_sizes $root
  } {3 3 3 4 4 6 6 10 10}
} else {
  do_test types-2.1.9 {
    set root [db eval {select rootpage from sqlite_master where name = 't1'}]
    record_sizes $root
  } {2 3 3 4 4 6 6 10 10}
}
  
# Insert some reals. These should be 10 byte records.
do_test types-2.2.1 {
  execsql {
    CREATE TABLE t2(a float);
    INSERT INTO t2 VALUES(0.0);
    INSERT INTO t2 VALUES(12345.678);
    INSERT INTO t2 VALUES(-12345.678);
  }
} {}
do_test types-2.2.2 {
  execsql {
    SELECT a FROM t2;
  }
} {0.0 12345.678 -12345.678}

# Check that all the record sizes are as we expected.
ifcapable legacyformat {
  do_test types-2.2.3 {
    set root [db eval {select rootpage from sqlite_master where name = 't2'}]
    record_sizes $root
  } {3 10 10}
} else {
  do_test types-2.2.3 {
    set root [db eval {select rootpage from sqlite_master where name = 't2'}]
    record_sizes $root
  } {2 10 10}
}
  
# Insert a NULL. This should be a two byte record.
do_test types-2.3.1 {
  execsql {
    CREATE TABLE t3(a nullvalue);
    INSERT INTO t3 VALUES(NULL);
  }
} {}
do_test types-2.3.2 {
  execsql {
    SELECT a ISNULL FROM t3;
  }
} {1}

# Check that all the record sizes are as we expected.
do_test types-2.3.3 {
  set root [db eval {select rootpage from sqlite_master where name = 't3'}]
  record_sizes $root
} {2}

# Insert a couple of strings.
do_test types-2.4.1 {
  set string10 abcdefghij
  set string500 [string repeat $string10 50]
  set string500000 [string repeat $string10 50000]

  execsql "
    CREATE TABLE t4(a string);
    INSERT INTO t4 VALUES('$string10');
    INSERT INTO t4 VALUES('$string500');
    INSERT INTO t4 VALUES('$string500000');
  "
} {}
do_test types-2.4.2 {
  execsql {
    SELECT a FROM t4;
  }
} [list $string10 $string500 $string500000]

# Check that all the record sizes are as we expected. This is dependant on
# the database encoding.
if { $sqlite_options(utf16)==0 || [execsql {pragma encoding}] == "UTF-8" } {
  do_test types-2.4.3 {
    set root [db eval {select rootpage from sqlite_master where name = 't4'}]
    record_sizes $root
  } {12 503 500004}
} else {
  do_test types-2.4.3 {
    set root [db eval {select rootpage from sqlite_master where name = 't4'}]
    record_sizes $root
  } {22 1003 1000004}
}

do_test types-2.5.1 {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    DROP TABLE t3;
    DROP TABLE t4;
    CREATE TABLE t1(a, b, c);
  }
} {}
do_test types-2.5.2 {
  set string10 abcdefghij
  set string500 [string repeat $string10 50]
  set string500000 [string repeat $string10 50000]

  execsql "INSERT INTO t1 VALUES(NULL, '$string10', 4000);"
  execsql "INSERT INTO t1 VALUES('$string500', 4000, NULL);"
  execsql "INSERT INTO t1 VALUES(4000, NULL, '$string500000');"
} {}
do_test types-2.5.3 {
  execsql {
    SELECT * FROM t1;
  }
} [list {} $string10 4000 $string500 4000 {} 4000 {} $string500000]

finish_test

Added test/types2.test.









































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# of this file is testing the interaction of manifest types, type affinity
# and comparison expressions.
#
# $Id: types2.test,v 1.7 2007/02/23 03:00:45 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Tests in this file are organized roughly as follows:
#
# types2-1.*: The '=' operator in the absence of an index.
# types2-2.*: The '=' operator implemented using an index.
# types2-3.*: The '<' operator implemented using an index.
# types2-4.*: The '>' operator in the absence of an index.
# types2-5.*: The 'IN(x, y...)' operator in the absence of an index.
# types2-6.*: The 'IN(x, y...)' operator with an index.
# types2-7.*: The 'IN(SELECT...)' operator in the absence of an index.
# types2-8.*: The 'IN(SELECT...)' operator with an index.
#
# All tests test the operators using literals and columns, but no
# other types of expressions. All expressions except columns are
# handled similarly in the implementation.

execsql {
  CREATE TABLE t1(
    i1 INTEGER,
    i2 INTEGER,
    n1 NUMERIC,
    n2 NUMERIC,
    t1 TEXT,
    t2 TEXT,
    o1 BLOB,
    o2 BLOB
  );
  INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
}

proc test_bool {testname vars expr res} {
  if { $vars != "" } {
    execsql "UPDATE t1 SET $vars"
  }

  foreach {t e r} [list $testname $expr $res] {}

  do_test $t.1 "execsql {SELECT $e FROM t1}" $r
  do_test $t.2 "execsql {SELECT 1 FROM t1 WHERE $expr}" [expr $r?"1":""]
  do_test $t.3 "execsql {SELECT 1 FROM t1 WHERE NOT ($e)}" [expr $r?"":"1"]
}

# Compare literals against literals. This should always use a numeric
# comparison.
#
# Changed by ticket #805:  Use no affinity for literal comparisons.
#
test_bool types2-1.1 "" {500 = 500.0} 1
test_bool types2-1.2 "" {'500' = 500.0} 0
test_bool types2-1.3 "" {500 = '500.0'} 0
test_bool types2-1.4 "" {'500' = '500.0'} 0

# Compare literals against a column with TEXT affinity
test_bool types2-1.5 {t1=500} {500 = t1} 1
test_bool types2-1.6 {t1=500} {'500' = t1} 1
test_bool types2-1.7 {t1=500} {500.0 = t1} 0
test_bool types2-1.8 {t1=500} {'500.0' = t1} 0
test_bool types2-1.9 {t1='500'} {500 = t1} 1
test_bool types2-1.10 {t1='500'} {'500' = t1} 1
test_bool types2-1.11 {t1='500'} {500.0 = t1} 0
test_bool types2-1.12 {t1='500'} {'500.0' = t1} 0

# Compare literals against a column with NUMERIC affinity
test_bool types2-1.13 {n1=500} {500 = n1} 1
test_bool types2-1.14 {n1=500} {'500' = n1} 1
test_bool types2-1.15 {n1=500} {500.0 = n1} 1
test_bool types2-1.16 {n1=500} {'500.0' = n1} 1
test_bool types2-1.17 {n1='500'} {500 = n1} 1
test_bool types2-1.18 {n1='500'} {'500' = n1} 1
test_bool types2-1.19 {n1='500'} {500.0 = n1} 1
test_bool types2-1.20 {n1='500'} {'500.0' = n1} 1

# Compare literals against a column with affinity NONE
test_bool types2-1.21 {o1=500} {500 = o1} 1
test_bool types2-1.22 {o1=500} {'500' = o1} 0
test_bool types2-1.23 {o1=500} {500.0 = o1} 1
test_bool types2-1.24 {o1=500} {'500.0' = o1} 0
test_bool types2-1.25 {o1='500'} {500 = o1} 0
test_bool types2-1.26 {o1='500'} {'500' = o1} 1
test_bool types2-1.27 {o1='500'} {500.0 = o1} 0
test_bool types2-1.28 {o1='500'} {'500.0' = o1} 0

set vals [list 10 10.0 '10' '10.0' 20 20.0 '20' '20.0' 30 30.0 '30' '30.0']
#              1  2    3    4      5  6    7    8      9  10   11   12

execsql {
  CREATE TABLE t2(i INTEGER, n NUMERIC, t TEXT, o XBLOBY);
  CREATE INDEX t2i1 ON t2(i);
  CREATE INDEX t2i2 ON t2(n);
  CREATE INDEX t2i3 ON t2(t);
  CREATE INDEX t2i4 ON t2(o);
}
foreach v $vals {
  execsql "INSERT INTO t2 VALUES($v, $v, $v, $v);"
}

proc test_boolset {testname where set} {
  set ::tb_sql "SELECT rowid FROM t2 WHERE $where"
  do_test $testname {
    lsort -integer [execsql $::tb_sql]
  } $set
}

test_boolset types2-2.1 {i = 10} {1 2 3 4}
test_boolset types2-2.2 {i = 10.0} {1 2 3 4}
test_boolset types2-2.3 {i = '10'} {1 2 3 4}
test_boolset types2-2.4 {i = '10.0'} {1 2 3 4}

test_boolset types2-2.5 {n = 20} {5 6 7 8}
test_boolset types2-2.6 {n = 20.0} {5 6 7 8}
test_boolset types2-2.7 {n = '20'} {5 6 7 8}
test_boolset types2-2.8 {n = '20.0'} {5 6 7 8}

test_boolset types2-2.9 {t = 20} {5 7}
test_boolset types2-2.10 {t = 20.0} {6 8}
test_boolset types2-2.11 {t = '20'} {5 7}
test_boolset types2-2.12 {t = '20.0'} {6 8}

test_boolset types2-2.10 {o = 30} {9 10}
test_boolset types2-2.11 {o = 30.0} {9 10}
test_boolset types2-2.12 {o = '30'} 11
test_boolset types2-2.13 {o = '30.0'} 12

test_boolset types2-3.1 {i < 20} {1 2 3 4}
test_boolset types2-3.2 {i < 20.0} {1 2 3 4}
test_boolset types2-3.3 {i < '20'} {1 2 3 4}
test_boolset types2-3.4 {i < '20.0'} {1 2 3 4}

test_boolset types2-3.1 {n < 20} {1 2 3 4}
test_boolset types2-3.2 {n < 20.0} {1 2 3 4}
test_boolset types2-3.3 {n < '20'} {1 2 3 4}
test_boolset types2-3.4 {n < '20.0'} {1 2 3 4}

test_boolset types2-3.1 {t < 20} {1 2 3 4}
test_boolset types2-3.2 {t < 20.0} {1 2 3 4 5 7}
test_boolset types2-3.3 {t < '20'} {1 2 3 4}
test_boolset types2-3.4 {t < '20.0'} {1 2 3 4 5 7}

test_boolset types2-3.1 {o < 20} {1 2}
test_boolset types2-3.2 {o < 20.0} {1 2}
test_boolset types2-3.3 {o < '20'} {1 2 3 4 5 6 9 10}
test_boolset types2-3.3 {o < '20.0'} {1 2 3 4 5 6 7 9 10}

# Compare literals against literals (always a numeric comparison).
# Change (by ticket #805):  No affinity in comparisons
test_bool types2-4.1 "" {500 > 60.0} 1
test_bool types2-4.2 "" {'500' > 60.0} 1
test_bool types2-4.3 "" {500 > '60.0'} 0
test_bool types2-4.4 "" {'500' > '60.0'} 0

# Compare literals against a column with TEXT affinity
test_bool types2-4.5 {t1=500.0} {t1 > 500} 1
test_bool types2-4.6 {t1=500.0} {t1 > '500' } 1
test_bool types2-4.7 {t1=500.0} {t1 > 500.0 } 0
test_bool types2-4.8 {t1=500.0} {t1 > '500.0' } 0
test_bool types2-4.9 {t1='500.0'} {t1 > 500 } 1
test_bool types2-4.10 {t1='500.0'} {t1 > '500' } 1
test_bool types2-4.11 {t1='500.0'} {t1 > 500.0 } 0
test_bool types2-4.12 {t1='500.0'} {t1 > '500.0' } 0

# Compare literals against a column with NUMERIC affinity
test_bool types2-4.13 {n1=400} {500 > n1} 1
test_bool types2-4.14 {n1=400} {'500' > n1} 1
test_bool types2-4.15 {n1=400} {500.0 > n1} 1
test_bool types2-4.16 {n1=400} {'500.0' > n1} 1
test_bool types2-4.17 {n1='400'} {500 > n1} 1
test_bool types2-4.18 {n1='400'} {'500' > n1} 1
test_bool types2-4.19 {n1='400'} {500.0 > n1} 1
test_bool types2-4.20 {n1='400'} {'500.0' > n1} 1

# Compare literals against a column with affinity NONE
test_bool types2-4.21 {o1=500} {500 > o1} 0
test_bool types2-4.22 {o1=500} {'500' > o1} 1
test_bool types2-4.23 {o1=500} {500.0 > o1} 0
test_bool types2-4.24 {o1=500} {'500.0' > o1} 1
test_bool types2-4.25 {o1='500'} {500 > o1} 0
test_bool types2-4.26 {o1='500'} {'500' > o1} 0
test_bool types2-4.27 {o1='500'} {500.0 > o1} 0
test_bool types2-4.28 {o1='500'} {'500.0' > o1} 1

ifcapable subquery {
  # types2-5.* - The 'IN (x, y....)' operator with no index.
  # 
  # Compare literals against literals (no affinity applied)
  test_bool types2-5.1 {} {(NULL IN ('10.0', 20)) ISNULL} 1
  test_bool types2-5.2 {} {10 IN ('10.0', 20)} 0
  test_bool types2-5.3 {} {'10' IN ('10.0', 20)} 0
  test_bool types2-5.4 {} {10 IN (10.0, 20)} 1
  test_bool types2-5.5 {} {'10.0' IN (10, 20)} 0
  
  # Compare literals against a column with TEXT affinity
  test_bool types2-5.6 {t1='10.0'} {t1 IN (10.0, 20)} 1
  test_bool types2-5.7 {t1='10.0'} {t1 IN (10, 20)} 0
  test_bool types2-5.8 {t1='10'} {t1 IN (10.0, 20)} 0
  test_bool types2-5.9 {t1='10'} {t1 IN (20, '10.0')} 0
  test_bool types2-5.10 {t1=10} {t1 IN (20, '10')} 1
  
  # Compare literals against a column with NUMERIC affinity
  test_bool types2-5.11 {n1='10.0'} {n1 IN (10.0, 20)} 1
  test_bool types2-5.12 {n1='10.0'} {n1 IN (10, 20)} 1
  test_bool types2-5.13 {n1='10'} {n1 IN (10.0, 20)} 1
  test_bool types2-5.14 {n1='10'} {n1 IN (20, '10.0')} 1
  test_bool types2-5.15 {n1=10} {n1 IN (20, '10')} 1
  
  # Compare literals against a column with affinity NONE
  test_bool types2-5.16 {o1='10.0'} {o1 IN (10.0, 20)} 0
  test_bool types2-5.17 {o1='10.0'} {o1 IN (10, 20)} 0
  test_bool types2-5.18 {o1='10'} {o1 IN (10.0, 20)} 0
  test_bool types2-5.19 {o1='10'} {o1 IN (20, '10.0')} 0
  test_bool types2-5.20 {o1=10} {o1 IN (20, '10')} 0
  test_bool types2-5.21 {o1='10.0'} {o1 IN (10, 20, '10.0')} 1
  test_bool types2-5.22 {o1='10'} {o1 IN (10.0, 20, '10')} 1
  test_bool types2-5.23 {o1=10} {n1 IN (20, '10', 10)} 1

  # Ticket #2248:  Comparisons of strings literals that look like
  # numbers.
  test_bool types2-5.24 {} {'1' IN ('1')} 1
  test_bool types2-5.25 {} {'2' IN (2)} 0
  test_bool types2-5.26 {} {3 IN ('3')} 0
  test_bool types2-5.27 {} {4 IN (4)} 1

  # The affinity of columns on the right side of IN(...) is ignored.
  # All values in the expression list are treated as ordinary expressions,
  # even if they are columns with affinity.
  test_bool types2-5.30 {t1='10'} {10 IN (5,t1,'abc')} 0
  test_bool types2-5.31 {t1='10'} {10 IN ('abc',t1,5)} 0
  test_bool types2-5.32 {t1='010'} {10 IN (5,t1,'abc')} 0
  test_bool types2-5.33 {t1='010'} {10 IN ('abc',t1,5)} 0
  test_bool types2-5.34 {t1='10'} {'10' IN (5,t1,'abc')} 1
  test_bool types2-5.35 {t1='10'} {'10' IN ('abc',t1,5)} 1
  test_bool types2-5.36 {t1='010'} {'10' IN (5,t1,'abc')} 0
  test_bool types2-5.37 {t1='010'} {'10' IN ('abc',t1,5)} 0
  
  # Columns on both the left and right of IN(...).  Only the column
  # on the left matters.  The all values on the right are treated like
  # expressions.
  test_bool types2-5.40 {t1='10',n1=10} {t1 IN (5,n1,11)} 1
  test_bool types2-5.41 {t1='010',n1=10} {t1 IN (5,n1,11)} 0
  test_bool types2-5.42 {t1='10',n1=10} {n1 IN (5,t1,11)} 1
  test_bool types2-5.43 {t1='010',n1=10} {n1 IN (5,t1,11)} 1
}

# Tests named types2-6.* use the same infrastructure as the types2-2.*
# tests. The contents of the vals array is repeated here for easy 
# reference.
# 
# set vals [list 10 10.0 '10' '10.0' 20 20.0 '20' '20.0' 30 30.0 '30' '30.0']
#                1  2    3    4      5  6    7    8      9  10   11   12

ifcapable subquery {
  test_boolset types2-6.1 {o IN ('10', 30)} {3 9 10}
  test_boolset types2-6.2 {o IN (20.0, 30.0)} {5 6 9 10}
  test_boolset types2-6.3 {t IN ('10', 30)} {1 3 9 11}
  test_boolset types2-6.4 {t IN (20.0, 30.0)} {6 8 10 12}
  test_boolset types2-6.5 {n IN ('10', 30)} {1 2 3 4 9 10 11 12}
  test_boolset types2-6.6 {n IN (20.0, 30.0)} {5 6 7 8 9 10 11 12}
  test_boolset types2-6.7 {i IN ('10', 30)} {1 2 3 4 9 10 11 12}
  test_boolset types2-6.8 {i IN (20.0, 30.0)} {5 6 7 8 9 10 11 12}

  # Also test than IN(x, y, z) works on a rowid:
  test_boolset types2-6.9 {rowid IN (1, 6, 10)} {1 6 10}
}

# Tests types2-7.* concentrate on expressions of the form 
# "x IN (SELECT...)" with no index.
execsql {
  CREATE TABLE t3(i INTEGER, n NUMERIC, t TEXT, o BLOB);
  INSERT INTO t3 VALUES(1, 1, 1, 1);
  INSERT INTO t3 VALUES(2, 2, 2, 2);
  INSERT INTO t3 VALUES(3, 3, 3, 3);
  INSERT INTO t3 VALUES('1', '1', '1', '1');
  INSERT INTO t3 VALUES('1.0', '1.0', '1.0', '1.0');
}

ifcapable subquery {
  test_bool types2-7.1 {i1=1} {i1 IN (SELECT i FROM t3)} 1
  test_bool types2-7.2 {i1='2.0'} {i1 IN (SELECT i FROM t3)} 1
  test_bool types2-7.3 {i1='2.0'} {i1 IN (SELECT n FROM t3)} 1
  test_bool types2-7.4 {i1='2.0'} {i1 IN (SELECT t FROM t3)} 1
  test_bool types2-7.5 {i1='2.0'} {i1 IN (SELECT o FROM t3)} 1
  
  test_bool types2-7.6 {n1=1} {n1 IN (SELECT n FROM t3)} 1
  test_bool types2-7.7 {n1='2.0'} {n1 IN (SELECT i FROM t3)} 1
  test_bool types2-7.8 {n1='2.0'} {n1 IN (SELECT n FROM t3)} 1
  test_bool types2-7.9 {n1='2.0'} {n1 IN (SELECT t FROM t3)} 1
  test_bool types2-7.10 {n1='2.0'} {n1 IN (SELECT o FROM t3)} 1
  
  test_bool types2-7.6 {t1=1} {t1 IN (SELECT t FROM t3)} 1
  test_bool types2-7.7 {t1='2.0'} {t1 IN (SELECT t FROM t3)} 0
  test_bool types2-7.8 {t1='2.0'} {t1 IN (SELECT n FROM t3)} 1
  test_bool types2-7.9 {t1='2.0'} {t1 IN (SELECT i FROM t3)} 1
  test_bool types2-7.10 {t1='2.0'} {t1 IN (SELECT o FROM t3)} 0
  test_bool types2-7.11 {t1='1.0'} {t1 IN (SELECT t FROM t3)} 1
  test_bool types2-7.12 {t1='1.0'} {t1 IN (SELECT o FROM t3)} 1
  
  test_bool types2-7.13 {o1=2} {o1 IN (SELECT o FROM t3)} 1
  test_bool types2-7.14 {o1='2'} {o1 IN (SELECT o FROM t3)} 0
  test_bool types2-7.15 {o1='2'} {o1 IN (SELECT o||'' FROM t3)} 1
}

# set vals [list 10 10.0 '10' '10.0' 20 20.0 '20' '20.0' 30 30.0 '30' '30.0']
#                1  2    3    4      5  6    7    8      9  10   11   12
execsql {
  CREATE TABLE t4(i INTEGER, n NUMERIC, t VARCHAR(20), o LARGE BLOB);
  INSERT INTO t4 VALUES(10, 20, 20, 30);
}
ifcapable subquery {
  test_boolset types2-8.1 {i IN (SELECT i FROM t4)} {1 2 3 4}
  test_boolset types2-8.2 {n IN (SELECT i FROM t4)} {1 2 3 4}
  test_boolset types2-8.3 {t IN (SELECT i FROM t4)} {1 2 3 4}
  test_boolset types2-8.4 {o IN (SELECT i FROM t4)} {1 2 3 4}
  test_boolset types2-8.5 {i IN (SELECT t FROM t4)} {5 6 7 8}
  test_boolset types2-8.6 {n IN (SELECT t FROM t4)} {5 6 7 8}
  test_boolset types2-8.7 {t IN (SELECT t FROM t4)} {5 7}
  test_boolset types2-8.8 {o IN (SELECT t FROM t4)} {7}
  test_boolset types2-8.9 {i IN (SELECT o FROM t4)} {9 10 11 12}
  test_boolset types2-8.6 {n IN (SELECT o FROM t4)} {9 10 11 12}
  test_boolset types2-8.7 {t IN (SELECT o FROM t4)} {9 11}
  test_boolset types2-8.8 {o IN (SELECT o FROM t4)} {9 10}
}

finish_test

Added test/types3.test.







































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 2005 June 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# of this file is testing the interaction of SQLite manifest types
# with Tcl dual-representations.
#
# $Id: types3.test,v 1.8 2008/04/28 13:02:58 drh Exp $
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# A variable with only a string representation comes in as TEXT
do_test types3-1.1 {
  set V {}
  append V {}
  concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
} {string text}

# A variable with an integer representation comes in as INTEGER
do_test types3-1.2 {
  set V [expr {int(1+2)}]
  concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
} {int integer}
set V [expr {1+12345678012345}]
if {[tcl_variable_type V]=="wideInt"} {
  do_test types3-1.3 {
    set V [expr {1+123456789012345}]
    concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
  } {wideInt integer}
} else {
  do_test types3-1.3 {
    set V [expr {1+123456789012345}]
    concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
  } {int integer}
}

# A double variable comes in as REAL
do_test types3-1.4 {
  set V [expr {1.0+1}]
  concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
} {double real}

# A byte-array variable comes in a BLOB if it has no string representation
# or as TEXT if there is a string representation.
#
do_test types3-1.5 {
  set V [binary format a3 abc]
  concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
} {bytearray blob}
do_test types3-1.6 {
  set V "abc"
  binary scan $V a3 x
  concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}]
} {bytearray text}

# Check to make sure return values are of the right types.
#
ifcapable bloblit {
  do_test types3-2.1 {
    set V [db one {SELECT x'616263'}]
    tcl_variable_type V
  } bytearray
}
do_test types3-2.2 {
  set V [db one {SELECT 123}]
  tcl_variable_type V
} int
set Vx [expr {1+wide(123456789123456)}]
do_test types3-2.3 {
  set V [db one {SELECT 1234567890123456}]
  tcl_variable_type V
} [tcl_variable_type Vx]
do_test types3-2.4.1 {
  set V [db one {SELECT 1234567890123456.1}]
  tcl_variable_type V
} double
do_test types3-2.4.2 {
  set V [db one {SELECT 1234567890123.456}]
  tcl_variable_type V
} double
do_test types3-2.5 {
  set V [db one {SELECT '1234567890123456.0'}]
  tcl_variable_type V
} {}
do_test types3-2.6 {
  set V [db one {SELECT NULL}]
  tcl_variable_type V
} {}

finish_test

Added test/unique.test.



























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# 2001 September 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the CREATE UNIQUE INDEX statement,
# and primary keys, and the UNIQUE constraint on table columns
#
# $Id: unique.test,v 1.9 2009/05/02 15:46:47 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Try to create a table with two primary keys.
# (This is allowed in SQLite even that it is not valid SQL)
#
do_test unique-1.1 {
  catchsql {
    CREATE TABLE t1(
       a int PRIMARY KEY,
       b int PRIMARY KEY,
       c text
    );
  }
} {1 {table "t1" has more than one primary key}}
do_test unique-1.1b {
  catchsql {
    CREATE TABLE t1(
       a int PRIMARY KEY,
       b int UNIQUE,
       c text
    );
  }
} {0 {}}
do_test unique-1.2 {
  catchsql {
    INSERT INTO t1(a,b,c) VALUES(1,2,3)
  }
} {0 {}}
do_test unique-1.3 {
  catchsql {
    INSERT INTO t1(a,b,c) VALUES(1,3,4)
  }
} {1 {column a is not unique}}
do_test unique-1.4 {
  execsql {
    SELECT * FROM t1 ORDER BY a;
  }
} {1 2 3}
do_test unique-1.5 {
  catchsql {
    INSERT INTO t1(a,b,c) VALUES(3,2,4)
  }
} {1 {column b is not unique}}
do_test unique-1.6 {
  execsql {
    SELECT * FROM t1 ORDER BY a;
  }
} {1 2 3}
do_test unique-1.7 {
  catchsql {
    INSERT INTO t1(a,b,c) VALUES(3,4,5)
  }
} {0 {}}
do_test unique-1.8 {
  execsql {
    SELECT * FROM t1 ORDER BY a;
  }
} {1 2 3 3 4 5}
integrity_check unique-1.9

do_test unique-2.0 {
  execsql {
    DROP TABLE t1;
    CREATE TABLE t2(a int, b int);
    INSERT INTO t2(a,b) VALUES(1,2);
    INSERT INTO t2(a,b) VALUES(3,4);
    SELECT * FROM t2 ORDER BY a;
  }
} {1 2 3 4}
do_test unique-2.1 {
  catchsql {
    CREATE UNIQUE INDEX i2 ON t2(a)
  }
} {0 {}}
do_test unique-2.2 {
  catchsql {
    SELECT * FROM t2 ORDER BY a
  }
} {0 {1 2 3 4}}
do_test unique-2.3 {
  catchsql {
    INSERT INTO t2 VALUES(1,5);
  }
} {1 {column a is not unique}}
do_test unique-2.4 {
  catchsql {
    SELECT * FROM t2 ORDER BY a
  }
} {0 {1 2 3 4}}
do_test unique-2.5 {
  catchsql {
    DROP INDEX i2;
    SELECT * FROM t2 ORDER BY a;
  }
} {0 {1 2 3 4}}
do_test unique-2.6 {
  catchsql {
    INSERT INTO t2 VALUES(1,5)
  }
} {0 {}}
do_test unique-2.7 {
  catchsql {
    SELECT * FROM t2 ORDER BY a, b;
  }
} {0 {1 2 1 5 3 4}}
do_test unique-2.8 {
  catchsql {
    CREATE UNIQUE INDEX i2 ON t2(a);
  }
} {1 {indexed columns are not unique}}
do_test unique-2.9 {
  catchsql {
    CREATE INDEX i2 ON t2(a);
  }
} {0 {}}
integrity_check unique-2.10

# Test the UNIQUE keyword as used on two or more fields.
#
do_test unique-3.1 {
  catchsql {
    CREATE TABLE t3(
       a int,
       b int,
       c int,
       d int,
       unique(a,c,d)
     );
  }
} {0 {}}
do_test unique-3.2 {
  catchsql {
    INSERT INTO t3(a,b,c,d) VALUES(1,2,3,4);
    SELECT * FROM t3 ORDER BY a,b,c,d;
  }
} {0 {1 2 3 4}}
do_test unique-3.3 {
  catchsql {
    INSERT INTO t3(a,b,c,d) VALUES(1,2,3,5);
    SELECT * FROM t3 ORDER BY a,b,c,d;
  }
} {0 {1 2 3 4 1 2 3 5}}
do_test unique-3.4 {
  catchsql {
    INSERT INTO t3(a,b,c,d) VALUES(1,4,3,5);
    SELECT * FROM t3 ORDER BY a,b,c,d;
  }
} {1 {columns a, c, d are not unique}}
integrity_check unique-3.5

# Make sure NULLs are distinct as far as the UNIQUE tests are
# concerned.
#
do_test unique-4.1 {
  execsql {
    CREATE TABLE t4(a UNIQUE, b, c, UNIQUE(b,c));
    INSERT INTO t4 VALUES(1,2,3);
    INSERT INTO t4 VALUES(NULL, 2, NULL);
    SELECT * FROM t4;
  }
} {1 2 3 {} 2 {}}
do_test unique-4.2 {
  catchsql {
    INSERT INTO t4 VALUES(NULL, 3, 4);
  }
} {0 {}}
do_test unique-4.3 {
  execsql {
    SELECT * FROM t4
  }
} {1 2 3 {} 2 {} {} 3 4}
do_test unique-4.4 {
  catchsql {
    INSERT INTO t4 VALUES(2, 2, NULL);
  }
} {0 {}}
do_test unique-4.5 {
  execsql {
    SELECT * FROM t4
  }
} {1 2 3 {} 2 {} {} 3 4 2 2 {}}

# Ticket #1301.  Any NULL value in a set of unique columns should
# cause the rows to be distinct.
#
do_test unique-4.6 {
  catchsql {
    INSERT INTO t4 VALUES(NULL, 2, NULL);
  }
} {0 {}}
do_test unique-4.7 {
  execsql {SELECT * FROM t4}
} {1 2 3 {} 2 {} {} 3 4 2 2 {} {} 2 {}}
do_test unique-4.8 {
  catchsql {CREATE UNIQUE INDEX i4a ON t4(a,b)}
} {0 {}}
do_test unique-4.9 {
  catchsql {CREATE UNIQUE INDEX i4b ON t4(a,b,c)}
} {0 {}}
do_test unique-4.10 {
  catchsql {CREATE UNIQUE INDEX i4c ON t4(b)}
} {1 {indexed columns are not unique}}
integrity_check unique-4.99

# Test the error message generation logic.  In particular, make sure we
# do not overflow the static buffer used to generate the error message.
#
do_test unique-5.1 {
  execsql {
    CREATE TABLE t5(
      first_column_with_long_name,
      second_column_with_long_name,
      third_column_with_long_name,
      fourth_column_with_long_name,
      fifth_column_with_long_name,
      sixth_column_with_long_name,
      UNIQUE(
        first_column_with_long_name,
        second_column_with_long_name,
        third_column_with_long_name,
        fourth_column_with_long_name,
        fifth_column_with_long_name,
        sixth_column_with_long_name
      )
    );
    INSERT INTO t5 VALUES(1,2,3,4,5,6);
    SELECT * FROM t5;
  }
} {1 2 3 4 5 6}
do_test unique-5.2 {
  catchsql {
    INSERT INTO t5 VALUES(1,2,3,4,5,6);
  }
} {1 {columns first_column_with_long_name, second_column_with_long_name, third_column_with_long_name, fourth_column_with_long_name, fifth_column_with_long_name, sixth_column_with_long_name are not unique}}

finish_test

Added test/update.test.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the UPDATE statement.
#
# $Id: update.test,v 1.19 2008/04/10 18:44:36 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Try to update an non-existent table
#
do_test update-1.1 {
  set v [catch {execsql {UPDATE test1 SET f2=5 WHERE f1<1}} msg]
  lappend v $msg
} {1 {no such table: test1}}

# Try to update a read-only table
#
do_test update-2.1 {
  set v [catch \
       {execsql {UPDATE sqlite_master SET name='xyz' WHERE name='123'}} msg]
  lappend v $msg
} {1 {table sqlite_master may not be modified}}

# Create a table to work with
#
do_test update-3.1 {
  execsql {CREATE TABLE test1(f1 int,f2 int)}
  for {set i 1} {$i<=10} {incr i} {
    set sql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])"
    execsql $sql
  }
  execsql {SELECT * FROM test1 ORDER BY f1}
} {1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024}

# Unknown column name in an expression
#
do_test update-3.2 {
  set v [catch {execsql {UPDATE test1 SET f1=f3*2 WHERE f2==32}} msg]
  lappend v $msg
} {1 {no such column: f3}}
do_test update-3.3 {
  set v [catch {execsql {UPDATE test1 SET f1=test2.f1*2 WHERE f2==32}} msg]
  lappend v $msg
} {1 {no such column: test2.f1}}
do_test update-3.4 {
  set v [catch {execsql {UPDATE test1 SET f3=f1*2 WHERE f2==32}} msg]
  lappend v $msg
} {1 {no such column: f3}}

# Actually do some updates
#
do_test update-3.5 {
  execsql {UPDATE test1 SET f2=f2*3}
} {}
do_test update-3.5.1 {
  db changes
} {10}

# verify that SELECT does not reset the change counter
do_test update-3.5.2 {
  db eval {SELECT count(*) FROM test1}
} {10}
do_test update-3.5.3 {
  db changes
} {10}

do_test update-3.6 {
  execsql {SELECT * FROM test1 ORDER BY f1}
} {1 6 2 12 3 24 4 48 5 96 6 192 7 384 8 768 9 1536 10 3072}
do_test update-3.7 {
  execsql {PRAGMA count_changes=on}
  execsql {UPDATE test1 SET f2=f2/3 WHERE f1<=5}
} {5}
do_test update-3.8 {
  execsql {SELECT * FROM test1 ORDER BY f1}
} {1 2 2 4 3 8 4 16 5 32 6 192 7 384 8 768 9 1536 10 3072}
do_test update-3.9 {
  execsql {UPDATE test1 SET f2=f2/3 WHERE f1>5}
} {5}
do_test update-3.10 {
  execsql {SELECT * FROM test1 ORDER BY f1}
} {1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024}

# Swap the values of f1 and f2 for all elements
#
do_test update-3.11 {
  execsql {UPDATE test1 SET F2=f1, F1=f2}
} {10}
do_test update-3.12 {
  execsql {SELECT * FROM test1 ORDER BY F1}
} {2 1 4 2 8 3 16 4 32 5 64 6 128 7 256 8 512 9 1024 10}
do_test update-3.13 {
  execsql {PRAGMA count_changes=off}
  execsql {UPDATE test1 SET F2=f1, F1=f2}
} {}
do_test update-3.14 {
  execsql {SELECT * FROM test1 ORDER BY F1}
} {1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024}

# Create duplicate entries and make sure updating still
# works.
#
do_test update-4.0 {
  execsql {
    DELETE FROM test1 WHERE f1<=5;
    INSERT INTO test1(f1,f2) VALUES(8,88);
    INSERT INTO test1(f1,f2) VALUES(8,888);
    INSERT INTO test1(f1,f2) VALUES(77,128);
    INSERT INTO test1(f1,f2) VALUES(777,128);
  }
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-4.1 {
  execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128}
do_test update-4.2 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128}
do_test update-4.3 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-4.4 {
  execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128}
do_test update-4.5 {
  execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128}
do_test update-4.6 {
  execsql {
    PRAGMA count_changes=on;
    UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128;
  }
} {2}
do_test update-4.7 {
  execsql {
    PRAGMA count_changes=off;
    SELECT * FROM test1 ORDER BY f1,f2
  }
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}

# Repeat the previous sequence of tests with an index.
#
do_test update-5.0 {
  execsql {CREATE INDEX idx1 ON test1(f1)}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-5.1 {
  execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128}
do_test update-5.2 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128}
do_test update-5.3 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-5.4 {
  execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128}
do_test update-5.4.1 {
  execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2}
} {78 128}
do_test update-5.4.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {778 128}
do_test update-5.4.3 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 128 8 256 8 888}
do_test update-5.5 {
  execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128}
} {}
do_test update-5.5.1 {
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128}
do_test update-5.5.2 {
  execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2}
} {78 128}
do_test update-5.5.3 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {}
do_test update-5.5.4 {
  execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2}
} {777 128}
do_test update-5.5.5 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 128 8 256 8 888}
do_test update-5.6 {
  execsql {
    PRAGMA count_changes=on;
    UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128;
  }
} {2}
do_test update-5.6.1 {
  execsql {
    PRAGMA count_changes=off;
    SELECT * FROM test1 ORDER BY f1,f2
  }
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-5.6.2 {
  execsql {SELECT * FROM test1 WHERE f1==77 ORDER BY f1,f2}
} {77 128}
do_test update-5.6.3 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {}
do_test update-5.6.4 {
  execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2}
} {777 128}
do_test update-5.6.5 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 256 8 888}

# Repeat the previous sequence of tests with a different index.
#
execsql {PRAGMA synchronous=FULL}
do_test update-6.0 {
  execsql {DROP INDEX idx1}
  execsql {CREATE INDEX idx1 ON test1(f2)}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-6.1 {
  execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128}
do_test update-6.1.1 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 89 8 257 8 889}
do_test update-6.1.2 {
  execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2}
} {8 89}
do_test update-6.1.3 {
  execsql {SELECT * FROM test1 WHERE f1==88 ORDER BY f1,f2}
} {}
do_test update-6.2 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128}
do_test update-6.3 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-6.3.1 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 256 8 888}
do_test update-6.3.2 {
  execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2}
} {}
do_test update-6.3.3 {
  execsql {SELECT * FROM test1 WHERE f2==88 ORDER BY f1,f2}
} {8 88}
do_test update-6.4 {
  execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128}
do_test update-6.4.1 {
  execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2}
} {78 128}
do_test update-6.4.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {778 128}
do_test update-6.4.3 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 128 8 256 8 888}
do_test update-6.5 {
  execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128}
do_test update-6.5.1 {
  execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2}
} {78 128}
do_test update-6.5.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {}
do_test update-6.5.3 {
  execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2}
} {777 128}
do_test update-6.5.4 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 128 8 256 8 888}
do_test update-6.6 {
  execsql {UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-6.6.1 {
  execsql {SELECT * FROM test1 WHERE f1==77 ORDER BY f1,f2}
} {77 128}
do_test update-6.6.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {}
do_test update-6.6.3 {
  execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2}
} {777 128}
do_test update-6.6.4 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 256 8 888}

# Repeat the previous sequence of tests with multiple
# indices
#
do_test update-7.0 {
  execsql {CREATE INDEX idx2 ON test1(f2)}
  execsql {CREATE INDEX idx3 ON test1(f1,f2)}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-7.1 {
  execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128}
do_test update-7.1.1 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 89 8 257 8 889}
do_test update-7.1.2 {
  execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2}
} {8 89}
do_test update-7.1.3 {
  execsql {SELECT * FROM test1 WHERE f1==88 ORDER BY f1,f2}
} {}
do_test update-7.2 {
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128}
do_test update-7.3 {
  # explain {UPDATE test1 SET f2=f2-1 WHERE f1==8 and F2<300}
  execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-7.3.1 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 256 8 888}
do_test update-7.3.2 {
  execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2}
} {}
do_test update-7.3.3 {
  execsql {SELECT * FROM test1 WHERE f2==88 ORDER BY f1,f2}
} {8 88}
do_test update-7.4 {
  execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128}
do_test update-7.4.1 {
  execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2}
} {78 128}
do_test update-7.4.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {778 128}
do_test update-7.4.3 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 128 8 256 8 888}
do_test update-7.5 {
  execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128}
do_test update-7.5.1 {
  execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2}
} {78 128}
do_test update-7.5.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {}
do_test update-7.5.3 {
  execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2}
} {777 128}
do_test update-7.5.4 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 128 8 256 8 888}
do_test update-7.6 {
  execsql {UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128}
  execsql {SELECT * FROM test1 ORDER BY f1,f2}
} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128}
do_test update-7.6.1 {
  execsql {SELECT * FROM test1 WHERE f1==77 ORDER BY f1,f2}
} {77 128}
do_test update-7.6.2 {
  execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2}
} {}
do_test update-7.6.3 {
  execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2}
} {777 128}
do_test update-7.6.4 {
  execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2}
} {8 88 8 256 8 888}

# Error messages
#
do_test update-9.1 {
  set v [catch {execsql {
    UPDATE test1 SET x=11 WHERE f1=1025
  }} msg]
  lappend v $msg
} {1 {no such column: x}}
do_test update-9.2 {
  set v [catch {execsql {
    UPDATE test1 SET f1=x(11) WHERE f1=1025
  }} msg]
  lappend v $msg
} {1 {no such function: x}}
do_test update-9.3 {
  set v [catch {execsql {
    UPDATE test1 SET f1=11 WHERE x=1025
  }} msg]
  lappend v $msg
} {1 {no such column: x}}
do_test update-9.4 {
  set v [catch {execsql {
    UPDATE test1 SET f1=11 WHERE x(f1)=1025
  }} msg]
  lappend v $msg
} {1 {no such function: x}}

# Try doing updates on a unique column where the value does not
# really change.
#
do_test update-10.1 {
  execsql {
    DROP TABLE test1;
    CREATE TABLE t1(
       a integer primary key,
       b UNIQUE, 
       c, d,
       e, f,
       UNIQUE(c,d)
    );
    INSERT INTO t1 VALUES(1,2,3,4,5,6);
    INSERT INTO t1 VALUES(2,3,4,4,6,7);
    SELECT * FROM t1
  }
} {1 2 3 4 5 6 2 3 4 4 6 7}
do_test update-10.2 {
  catchsql {
    UPDATE t1 SET a=1, e=9 WHERE f=6;
    SELECT * FROM t1;
  }
} {0 {1 2 3 4 9 6 2 3 4 4 6 7}}
do_test update-10.3 {
  catchsql {
    UPDATE t1 SET a=1, e=10 WHERE f=7;
    SELECT * FROM t1;
  }
} {1 {PRIMARY KEY must be unique}}
do_test update-10.4 {
  catchsql {
    SELECT * FROM t1;
  }
} {0 {1 2 3 4 9 6 2 3 4 4 6 7}}
do_test update-10.5 {
  catchsql {
    UPDATE t1 SET b=2, e=11 WHERE f=6;
    SELECT * FROM t1;
  }
} {0 {1 2 3 4 11 6 2 3 4 4 6 7}}
do_test update-10.6 {
  catchsql {
    UPDATE t1 SET b=2, e=12 WHERE f=7;
    SELECT * FROM t1;
  }
} {1 {column b is not unique}}
do_test update-10.7 {
  catchsql {
    SELECT * FROM t1;
  }
} {0 {1 2 3 4 11 6 2 3 4 4 6 7}}
do_test update-10.8 {
  catchsql {
    UPDATE t1 SET c=3, d=4, e=13 WHERE f=6;
    SELECT * FROM t1;
  }
} {0 {1 2 3 4 13 6 2 3 4 4 6 7}}
do_test update-10.9 {
  catchsql {
    UPDATE t1 SET c=3, d=4, e=14 WHERE f=7;
    SELECT * FROM t1;
  }
} {1 {columns c, d are not unique}}
do_test update-10.10 {
  catchsql {
    SELECT * FROM t1;
  }
} {0 {1 2 3 4 13 6 2 3 4 4 6 7}}

# Make sure we can handle a subquery in the where clause.
#
ifcapable subquery {
  do_test update-11.1 {
    execsql {
      UPDATE t1 SET e=e+1 WHERE b IN (SELECT b FROM t1);
      SELECT b,e FROM t1;
    }
  } {2 14 3 7}
  do_test update-11.2 {
    execsql {
      UPDATE t1 SET e=e+1 WHERE a IN (SELECT a FROM t1);
      SELECT a,e FROM t1;
    }
  } {1 15 2 8}
}

integrity_check update-12.1

# Ticket 602.  Updates should occur in the same order as the records
# were discovered in the WHERE clause.
#
do_test update-13.1 {
  execsql {
    BEGIN;
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    INSERT INTO t2 SELECT a+2 FROM t2;
    INSERT INTO t2 SELECT a+4 FROM t2;
    INSERT INTO t2 SELECT a+8 FROM t2;
    INSERT INTO t2 SELECT a+16 FROM t2;
    INSERT INTO t2 SELECT a+32 FROM t2;
    INSERT INTO t2 SELECT a+64 FROM t2;
    INSERT INTO t2 SELECT a+128 FROM t2;
    INSERT INTO t2 SELECT a+256 FROM t2;
    INSERT INTO t2 SELECT a+512 FROM t2;
    INSERT INTO t2 SELECT a+1024 FROM t2;
    COMMIT;
    SELECT count(*) FROM t2;
  }
} {2048}
do_test update-13.2 {
  execsql {
    SELECT count(*) FROM t2 WHERE a=rowid;
  }
} {2048}
do_test update-13.3 {
  execsql {
    UPDATE t2 SET rowid=rowid-1;
    SELECT count(*) FROM t2 WHERE a=rowid+1;
  }
} {2048}
do_test update-13.3 {
  execsql {
    UPDATE t2 SET rowid=rowid+10000;
    UPDATE t2 SET rowid=rowid-9999;
    SELECT count(*) FROM t2 WHERE a=rowid;
  }
} {2048}
do_test update-13.4 {
  execsql {
    BEGIN;
    INSERT INTO t2 SELECT a+2048 FROM t2;
    INSERT INTO t2 SELECT a+4096 FROM t2;
    INSERT INTO t2 SELECT a+8192 FROM t2;
    SELECT count(*) FROM t2 WHERE a=rowid;
    COMMIT;
  }
} 16384
do_test update-13.5 {
  execsql {
    UPDATE t2 SET rowid=rowid-1;
    SELECT count(*) FROM t2 WHERE a=rowid+1;
  }
} 16384

integrity_check update-13.6

ifcapable {trigger} {
# Test for proper detection of malformed WHEN clauses on UPDATE triggers.
#
do_test update-14.1 {
  execsql {
    CREATE TABLE t3(a,b,c);
    CREATE TRIGGER t3r1 BEFORE UPDATE on t3 WHEN nosuchcol BEGIN
      SELECT 'illegal WHEN clause';
    END;
  }
} {}
do_test update-14.2 {
  catchsql {
    UPDATE t3 SET a=1;
  }
} {1 {no such column: nosuchcol}}
do_test update-14.3 {
  execsql {
    CREATE TABLE t4(a,b,c);
    CREATE TRIGGER t4r1 AFTER UPDATE on t4 WHEN nosuchcol BEGIN
      SELECT 'illegal WHEN clause';
    END;
  }
} {}
do_test update-14.4 {
  catchsql {
    UPDATE t4 SET a=1;
  }
} {1 {no such column: nosuchcol}}

} ;# ifcapable {trigger}


finish_test

Added test/utf16align.test.































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# 2006 February 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# 
# This file contains code to verify that the SQLITE_UTF16_ALIGNED
# flag passed into the sqlite3_create_collation() function insures
# that all strings passed to that function are aligned on an even
# byte boundary.
#
# $Id: utf16align.test,v 1.2 2008/11/07 03:29:34 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Skip this entire test if we do not support UTF16
#
ifcapable !utf16 {
  finish_test
  return
}

# Create a database with a UTF16 encoding.  Put in lots of string
# data of varying lengths.
#
do_test utf16align-1.0 {
  set unaligned_string_counter 0
  add_alignment_test_collations [sqlite3_connection_pointer db]
  execsql {
    PRAGMA encoding=UTF16;
    CREATE TABLE t1(
      id INTEGER PRIMARY KEY,
      spacer TEXT,
      a TEXT COLLATE utf16_aligned,
      b TEXT COLLATE utf16_unaligned
    );
    INSERT INTO t1(a) VALUES("abc");
    INSERT INTO t1(a) VALUES("defghi");
    INSERT INTO t1(a) VALUES("jklmnopqrstuv");
    INSERT INTO t1(a) VALUES("wxyz0123456789-");
    UPDATE t1 SET b=a||'-'||a;
    INSERT INTO t1(a,b) SELECT a||b, b||a FROM t1;
    INSERT INTO t1(a,b) SELECT a||b, b||a FROM t1;
    INSERT INTO t1(a,b) SELECT a||b, b||a FROM t1;
    INSERT INTO t1(a,b) VALUES('one','two');
    INSERT INTO t1(a,b) SELECT a, b FROM t1;
    UPDATE t1 SET spacer = CASE WHEN rowid&1 THEN 'x' ELSE 'xx' END;
    SELECT count(*) FROM t1;
  }
} 66
do_test utf16align-1.1 {
  set unaligned_string_counter
} 0

# Creating an index that uses the unaligned collation.  We should see
# some unaligned strings passed to the collating function.
#
do_test utf16align-1.2 {
  execsql {
    CREATE INDEX t1i1 ON t1(spacer, b);
  }
  # puts $unaligned_string_counter
  expr {$unaligned_string_counter>0}
} 1

# Create another index that uses the aligned collation.  This time
# there should be no unaligned accesses
#
do_test utf16align-1.3 {
  set unaligned_string_counter 0
  execsql {
    CREATE INDEX t1i2 ON t1(spacer, a);
  }
  expr {$unaligned_string_counter>0}
} 0
integrity_check utf16align-1.4

# ticket #3482
#
db close
sqlite3 db :memory:
do_test utf16align-2.1 {
  db eval {
    PRAGMA encoding=UTF16be;
    SELECT hex(ltrim(x'6efcda'));
  }
} {6EFC}

finish_test

Added test/vacuum.test.































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the VACUUM statement.
#
# $Id: vacuum.test,v 1.43 2009/01/31 14:54:07 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If the VACUUM statement is disabled in the current build, skip all
# the tests in this file.
#
ifcapable {!vacuum} {
  omit_test vacuum.test {Compiled with SQLITE_OMIT_VACUUM}
  finish_test
  return
}
if $AUTOVACUUM {
  omit_test vacuum.test {Auto-vacuum is enabled}
  finish_test
  return
}

set fcnt 1
do_test vacuum-1.1 {
  execsql {
    BEGIN;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
    INSERT INTO t1 VALUES(NULL,randstr(10,100),randstr(5,50));
    INSERT INTO t1 VALUES(123456,randstr(10,100),randstr(5,50));
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1;
    CREATE INDEX i1 ON t1(b,c);
    CREATE UNIQUE INDEX i2 ON t1(c,a);
    CREATE TABLE t2 AS SELECT * FROM t1;
    COMMIT;
    DROP TABLE t2;
  }
  set ::size1 [file size test.db]
  set ::cksum [cksum]
  expr {$::cksum!=""}
} {1}
do_test vacuum-1.2 {
  execsql {
    VACUUM;
  }
  cksum
} $cksum
ifcapable vacuum {
  do_test vacuum-1.3 {
    expr {[file size test.db]<$::size1}
  } {1}
}
do_test vacuum-1.4 {
  set sql_script {
    BEGIN;
    CREATE TABLE t2 AS SELECT * FROM t1;
    CREATE TABLE t3 AS SELECT * FROM t1;
    CREATE VIEW v1 AS SELECT b, c FROM t3;
    CREATE TRIGGER r1 AFTER DELETE ON t2 BEGIN SELECT 1; END;
    COMMIT;
    DROP TABLE t2;
  }
  # If the library was compiled to omit view support, comment out the
  # create view in the script $sql_script before executing it. Similarly,
  # if triggers are not supported, comment out the trigger definition.
  ifcapable !view {
    regsub {CREATE VIEW} $sql_script {-- CREATE VIEW} sql_script
  }
  ifcapable !trigger {
    regsub {CREATE TRIGGER} $sql_script {-- CREATE TRIGGER} sql_script
  }
  execsql $sql_script
  set ::size1 [file size test.db]
  set ::cksum [cksum]
  expr {$::cksum!=""}
} {1}
do_test vacuum-1.5 {
  execsql {
    VACUUM;
  }
  cksum
} $cksum

ifcapable vacuum {
  do_test vacuum-1.6 {
    expr {[file size test.db]<$::size1}
  } {1}
}
ifcapable vacuum {
  do_test vacuum-2.1.1 {
    catchsql {
      BEGIN;
      VACUUM;
    }
  } {1 {cannot VACUUM from within a transaction}}
  do_test vacuum-2.1.2 {
    sqlite3_get_autocommit db
  } {0}
  do_test vacuum-2.1.3 {
    db eval {COMMIT}
  } {}
}
do_test vacuum-2.2 {
  sqlite3 db2 test.db
  execsql {
    BEGIN;
    CREATE TABLE t4 AS SELECT * FROM t1;
    CREATE TABLE t5 AS SELECT * FROM t1;
    COMMIT;
    DROP TABLE t4;
    DROP TABLE t5;
  } db2
  set ::cksum [cksum db2]
  catchsql {
    VACUUM
  }
} {0 {}}
do_test vacuum-2.3 {
  cksum
} $cksum
do_test vacuum-2.4 {
  catch {db2 eval {SELECT count(*) FROM sqlite_master}}
  cksum db2
} $cksum

# Make sure the schema cookie is incremented by vacuum.
#
do_test vacuum-2.5 {
  execsql {
    BEGIN;
    CREATE TABLE t6 AS SELECT * FROM t1;
    CREATE TABLE t7 AS SELECT * FROM t1;
    COMMIT;
  }
  sqlite3 db3 test.db
  execsql {
    -- The "SELECT * FROM sqlite_master" statement ensures that this test
    -- works when shared-cache is enabled. If shared-cache is enabled, then
    -- db3 shares a cache with db2 (but not db - it was opened as 
    -- "./test.db").
    SELECT * FROM sqlite_master;
    SELECT * FROM t7 LIMIT 1
  } db3
  execsql {
    VACUUM;
  }
  execsql {
    INSERT INTO t7 VALUES(1234567890,'hello','world');
  } db3
  execsql {
    SELECT * FROM t7 WHERE a=1234567890
  }
} {1234567890 hello world}
integrity_check vacuum-2.6
do_test vacuum-2.7 {
  execsql {
    SELECT * FROM t7 WHERE a=1234567890
  } db3
} {1234567890 hello world}
do_test vacuum-2.8 {
  execsql {
    INSERT INTO t7 SELECT * FROM t6;
    SELECT count(*) FROM t7;
  }
} 513
integrity_check vacuum-2.9
do_test vacuum-2.10 {
  execsql {
    DELETE FROM t7;
    SELECT count(*) FROM t7;
  } db3
} 0
integrity_check vacuum-2.11
db3 close
 

# Ticket #427.  Make sure VACUUM works when the EMPTY_RESULT_CALLBACKS
# pragma is turned on.
#
do_test vacuum-3.1 {
  db close
  db2 close
  file delete test.db
  sqlite3 db test.db
  execsql {
    PRAGMA empty_result_callbacks=on;
    VACUUM;
  }
} {}

# Ticket #464.  Make sure VACUUM works with the sqlite3_prepare() API.
#
do_test vacuum-4.1 {
  db close
  sqlite3 db test.db; set DB [sqlite3_connection_pointer db]
  set VM [sqlite3_prepare $DB {VACUUM} -1 TAIL]
  sqlite3_step $VM
} {SQLITE_DONE}
do_test vacuum-4.2 {
  sqlite3_finalize $VM
} SQLITE_OK

# Ticket #515.  VACUUM after deleting and recreating the table that
# a view refers to. Omit this test if the library is not view-enabled.
#
ifcapable view {
do_test vacuum-5.1 {
  db close
  file delete -force test.db
  sqlite3 db test.db
  catchsql {
    CREATE TABLE Test (TestID int primary key);
    INSERT INTO Test VALUES (NULL);
    CREATE VIEW viewTest AS SELECT * FROM Test;

    BEGIN;
    CREATE TABLE tempTest (TestID int primary key, Test2 int NULL);
    INSERT INTO tempTest SELECT TestID, 1 FROM Test;
    DROP TABLE Test;
    CREATE TABLE Test(TestID int primary key, Test2 int NULL);
    INSERT INTO Test SELECT * FROM tempTest;
    DROP TABLE tempTest;
    COMMIT;
    VACUUM;
  }
} {0 {}}
do_test vacuum-5.2 {
  catchsql {
    VACUUM;
  }
} {0 {}}
} ;# ifcapable view

# Ensure vacuum works with complicated tables names.
do_test vacuum-6.1 {
  execsql {
    CREATE TABLE "abc abc"(a, b, c);
    INSERT INTO "abc abc" VALUES(1, 2, 3);
    VACUUM;
  }
} {}
do_test vacuum-6.2 {
  execsql {
    select * from "abc abc";
  }
} {1 2 3}

# Also ensure that blobs survive a vacuum.
ifcapable {bloblit} {
  do_test vacuum-6.3 {
    execsql {
      DELETE FROM "abc abc";
      INSERT INTO "abc abc" VALUES(X'00112233', NULL, NULL);
      VACUUM;
    }
  } {}
  do_test vacuum-6.4 {
    execsql {
      select count(*) from "abc abc" WHERE a = X'00112233';
    }
  } {1}
}

# Check what happens when an in-memory database is vacuumed. The
# [file delete] command covers us in case the library was compiled
# without in-memory database support.
#
file delete -force :memory:
do_test vacuum-7.0 {
  sqlite3 db2 :memory:
  execsql {
    CREATE TABLE t1(t);
    VACUUM;
  } db2
  execsql {
    CREATE TABLE t2(t);
    CREATE TABLE t3(t);
    DROP TABLE t2;
    VACUUM;
    pragma integrity_check;
  } db2
} {ok}
db2 close

# Ticket #873.  VACUUM a database that has ' in its name.
#
do_test vacuum-8.1 {
  file delete -force a'z.db
  file delete -force a'z.db-journal
  sqlite3 db2 a'z.db
  execsql {
    CREATE TABLE t1(t);
    VACUUM;
  } db2
} {}
db2 close

# Ticket #1095:  Vacuum a table that uses AUTOINCREMENT
#
ifcapable {autoinc} {
  do_test vacuum-9.1 {
    execsql {
      DROP TABLE 'abc abc';
      CREATE TABLE autoinc(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
      INSERT INTO autoinc(b) VALUES('hi');
      INSERT INTO autoinc(b) VALUES('there');
      DELETE FROM autoinc;
    }
    set ::cksum [cksum]
    expr {$::cksum!=""}
  } {1}
  do_test vacuum-9.2 {
    execsql {
      VACUUM;
    }
    cksum
  } $::cksum
  do_test vacuum-9.3 {
    execsql {
      INSERT INTO autoinc(b) VALUES('one');
      INSERT INTO autoinc(b) VALUES('two');
    }
    set ::cksum [cksum]
    expr {$::cksum!=""}
  } {1}
  do_test vacuum-9.4 {
    execsql {
      VACUUM;
    }
    cksum
  } $::cksum
}

file delete -force {a'z.db}

finish_test

Added test/vacuum2.test.



















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# 2005 February 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the VACUUM statement.
#
# $Id: vacuum2.test,v 1.10 2009/02/18 20:31:18 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If the VACUUM statement is disabled in the current build, skip all
# the tests in this file.
#
ifcapable {!vacuum||!autoinc} {
  finish_test
  return
}
if $AUTOVACUUM {
  finish_test
  return
}

# Ticket #1121 - make sure vacuum works if all autoincrement tables
# have been deleted.
#
do_test vacuum2-1.1 {
  execsql {
    CREATE TABLE t1(x INTEGER PRIMARY KEY AUTOINCREMENT, y);
    DROP TABLE t1;
    VACUUM;
  }
} {}

# Ticket #2518.  Make sure vacuum increments the change counter
# in the database header.
#
do_test vacuum2-2.1 {
  execsql {
    CREATE TABLE t1(x);
    CREATE TABLE t2(y);
    INSERT INTO t1 VALUES(1);
  }
  hexio_get_int [hexio_read test.db 24 4]
} [expr {[hexio_get_int [hexio_read test.db 24 4]]+3}]
do_test vacuum2-2.1 {
  execsql {
    VACUUM
  }
  hexio_get_int [hexio_read test.db 24 4]
} [expr {[hexio_get_int [hexio_read test.db 24 4]]+1}]

############################################################################
# Verify that we can use the auto_vacuum pragma to request a new
# autovacuum setting, do a VACUUM, and the new setting takes effect.
# Make sure this happens correctly even if there are multiple open
# connections to the same database file.
#
sqlite3 db2 test.db
set pageSize [db eval {pragma page_size}]

# We are currently not autovacuuming so the database should be 3 pages
# in size.  1 page for each of sqlite_master, t1, and t2.
#
do_test vacuum2-3.1 {
  execsql {
    INSERT INTO t1 VALUES('hello');
    INSERT INTO t2 VALUES('out there');
  }
  expr {[file size test.db]/$pageSize}
} {3}
set cksum [cksum]
do_test vacuum2-3.2 {
  cksum db2
} $cksum

# Convert the database to an autovacuumed database.
ifcapable autovacuum {
  do_test vacuum2-3.3 {
    execsql {
      PRAGMA auto_vacuum=FULL;
      VACUUM;
    }
    expr {[file size test.db]/$pageSize}
  } {4}
}
do_test vacuum2-3.4 {
  cksum db2
} $cksum
do_test vacuum2-3.5 {
  cksum
} $cksum
do_test vacuum2-3.6 {
  execsql {PRAGMA integrity_check} db2
} {ok}
do_test vacuum2-3.7 {
  execsql {PRAGMA integrity_check} db
} {ok}

# Convert the database back to a non-autovacuumed database.
do_test vacuum2-3.13 {
  execsql {
    PRAGMA auto_vacuum=NONE;
    VACUUM;
  }
  expr {[file size test.db]/$pageSize}
} {3}
do_test vacuum2-3.14 {
  cksum db2
} $cksum
do_test vacuum2-3.15 {
  cksum
} $cksum
do_test vacuum2-3.16 {
  execsql {PRAGMA integrity_check} db2
} {ok}
do_test vacuum2-3.17 {
  execsql {PRAGMA integrity_check} db
} {ok}

db2 close

ifcapable autovacuum {
  do_test vacuum2-4.1 {
    db close
    file delete -force test.db
    sqlite3 db test.db
    execsql {
      pragma auto_vacuum=1;
      create table t(a, b);
      insert into t values(1, 2);
      insert into t values(1, 2);
      pragma auto_vacuum=0;
      vacuum;
      pragma auto_vacuum;
    }
  } {0}
  do_test vacuum2-4.2 {
    execsql {
      pragma auto_vacuum=1;
      vacuum;
      pragma auto_vacuum;
    }
  } {1}
  do_test vacuum2-4.3 {
    execsql {
      pragma integrity_check
    }
  } {ok}
  do_test vacuum2-4.4 {
    db close
    sqlite3 db test.db
    execsql {
      pragma auto_vacuum;
    }
  } {1}
  do_test vacuum2-4.5 {  # Ticket #3663
    execsql {
      pragma auto_vacuum=2;
      vacuum;
      pragma auto_vacuum;
    }
  } {2}
  do_test vacuum2-4.6 {
    execsql {
      pragma integrity_check
    }
  } {ok}
  do_test vacuum2-4.7 {
    db close
    sqlite3 db test.db
    execsql {
      pragma auto_vacuum;
    }
  } {2}
}

finish_test

Added test/vacuum3.test.









































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# 2007 March 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is changing the database page size using a 
# VACUUM statement.
#
# $Id: vacuum3.test,v 1.9 2008/08/26 21:07:27 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# If the VACUUM statement is disabled in the current build, skip all
# the tests in this file.
#
ifcapable !vacuum {
  finish_test
  return
}


#-------------------------------------------------------------------
# Test cases vacuum3-1.* convert a simple 2-page database between a 
# few different page sizes.
#
do_test vacuum3-1.1 {
  execsql {
    PRAGMA auto_vacuum=OFF;
    PRAGMA page_size = 1024;
    CREATE TABLE t1(a, b, c);
    INSERT INTO t1 VALUES(1, 2, 3);
  }
} {}
do_test vacuum3-1.2 {
  execsql { PRAGMA page_size }
} {1024}
do_test vacuum3-1.3 {
  file size test.db
} {2048}

set I 4
foreach {request actual database} [list \
  2048 2048 4096                        \
  1024 1024 2048                        \
  1170 1024 2048                        \
  256  1024 2048                        \
  512  512  1024                        \
  4096 4096 8192                        \
  1024 1024 2048                        \
] {
  do_test vacuum3-1.$I.1 {
    execsql " 
      PRAGMA page_size = $request;
      VACUUM;
    "
    execsql { PRAGMA page_size }
  } $actual
  do_test vacuum3-1.$I.2 {
    file size test.db
  } $database
  do_test vacuum3-1.$I.3 {
    execsql { SELECT * FROM t1 }
  } {1 2 3}
  integrity_check vacuum3-1.$I.4

  incr I
}

#-------------------------------------------------------------------
# Test cases vacuum3-2.* convert a simple 3-page database between a 
# few different page sizes.
#
do_test vacuum3-2.1 {
  execsql {
    PRAGMA page_size = 1024;
    VACUUM;
    ALTER TABLE t1 ADD COLUMN d;
    UPDATE t1 SET d = randomblob(1000);
  }
  file size test.db
} {3072}
do_test vacuum3-2.2 {
  execsql { PRAGMA page_size }
} {1024}
do_test vacuum3-2.3 {
  set blob [db one {select d from t1}]
  string length $blob
} {1000}

set I 4
foreach {request actual database} [list \
  2048 2048 4096                        \
  1024 1024 3072                        \
  1170 1024 3072                        \
  256  1024 3072                        \
  512  512  2048                        \
  4096 4096 8192                        \
  1024 1024 3072                        \
] {
  do_test vacuum3-2.$I.1 {
    execsql " 
      PRAGMA page_size = $request;
      VACUUM;
    "
    execsql { PRAGMA page_size }
  } $actual
  do_test vacuum3-2.$I.2 {
    file size test.db
  } $database
  do_test vacuum3-2.$I.3 {
    execsql { SELECT * FROM t1 }
  } [list 1 2 3 $blob]
  integrity_check vacuum3-1.$I.4

  incr I
}

#-------------------------------------------------------------------
# Test cases vacuum3-3.* converts a database large enough to include
# the locking page (in a test environment) between few different 
# page sizes.
#
proc signature {} {
  return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}]
}
do_test vacuum3-3.1 {
  execsql "
    PRAGMA page_size = 1024;
    BEGIN;
    CREATE TABLE abc(a PRIMARY KEY, b, c);
    INSERT INTO abc VALUES(randomblob(100), randomblob(200), randomblob(1000));
    INSERT INTO abc 
        SELECT randomblob(1000), randomblob(200), randomblob(100)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(100), randomblob(200), randomblob(1000)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(100), randomblob(200), randomblob(1000)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(100), randomblob(200), randomblob(1000)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(100), randomblob(200), randomblob(1000)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(25), randomblob(45), randomblob(9456)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(100), randomblob(200), randomblob(1000)
        FROM abc;
    INSERT INTO abc 
        SELECT randomblob(25), randomblob(45), randomblob(9456)
        FROM abc;
    COMMIT;
  "
} {}
do_test vacuum3-3.2 {
  execsql { PRAGMA page_size }
} {1024}

set ::sig [signature]

set I 3
foreach {request actual} [list \
  2048 2048                    \
  1024 1024                    \
  1170 1024                    \
  256  1024                    \
  512  512                     \
  4096 4096                    \
  1024 1024                    \
] {
  do_test vacuum3-3.$I.1 {
    execsql " 
      PRAGMA page_size = $request;
      VACUUM;
    "
    execsql { PRAGMA page_size }
  } $actual
  do_test vacuum3-3.$I.2 {
    signature
  } $::sig
  integrity_check vacuum3-3.$I.3

  incr I
}

do_test vacuum3-4.1 {
  db close
  file delete test.db
  sqlite3 db test.db
  execsql {
    PRAGMA page_size=1024;
    CREATE TABLE abc(a, b, c);
    INSERT INTO abc VALUES(1, 2, 3);
    INSERT INTO abc VALUES(4, 5, 6);
  }
  execsql { SELECT * FROM abc }
} {1 2 3 4 5 6}
do_test vacuum3-4.2 {
  sqlite3 db2 test.db
  execsql { SELECT * FROM abc } db2
} {1 2 3 4 5 6}
do_test vacuum3-4.3 {
  execsql { 
    PRAGMA page_size = 2048;
    VACUUM;
  }
  execsql { SELECT * FROM abc }
} {1 2 3 4 5 6}
do_test vacuum3-4.4 {
  execsql { SELECT * FROM abc } db2
} {1 2 3 4 5 6}
do_test vacuum3-4.5 {
  execsql {
    PRAGMA page_size=16384;
    VACUUM;
  } db2
  execsql { SELECT * FROM abc } db2
} {1 2 3 4 5 6}
do_test vacuum3-4.6 {
  execsql {
    PRAGMA page_size=1024;
    VACUUM;
  }
  execsql { SELECT * FROM abc } db2
} {1 2 3 4 5 6}

# Unable to change the page-size of an in-memory using vacuum.
db2 close
sqlite3 db2 :memory:
do_test vacuum3-5.1 {
  db2 eval {
    CREATE TABLE t1(x);
    INSERT INTO t1 VALUES(1234);
    PRAGMA page_size=4096;
    VACUUM;
    SELECT * FROM t1;
  }
} {1234}
do_test vacuum3-5.2 {
  db2 eval {
    PRAGMA page_size
  }
} {1024}

set create_database_sql {
  BEGIN; 
  CREATE TABLE t1(a, b, c); 
  INSERT INTO t1 VALUES(1, randstr(50,50), randstr(50,50)); 
  INSERT INTO t1 SELECT a+2, b||'-'||rowid, c||'-'||rowid FROM t1; 
  INSERT INTO t1 SELECT a+4, b||'-'||rowid, c||'-'||rowid FROM t1;
  INSERT INTO t1 SELECT a+8, b||'-'||rowid, c||'-'||rowid FROM t1;
  INSERT INTO t1 SELECT a+16, b||'-'||rowid, c||'-'||rowid FROM t1;
  INSERT INTO t1 SELECT a+32, b||'-'||rowid, c||'-'||rowid FROM t1;
  INSERT INTO t1 SELECT a+64, b||'-'||rowid, c||'-'||rowid FROM t1;
  INSERT INTO t1 SELECT a+128, b||'-'||rowid, c||'-'||rowid FROM t1;
  INSERT INTO t1 VALUES(1, randstr(600,600), randstr(600,600));
  CREATE TABLE t2 AS SELECT * FROM t1;
  CREATE TABLE t3 AS SELECT * FROM t1;
  COMMIT;
  DROP TABLE t2;
}

do_ioerr_test vacuum3-ioerr-1 -cksum true -sqlprep "
  PRAGMA page_size = 1024;
  $create_database_sql
" -sqlbody {
  PRAGMA page_size = 4096;
  VACUUM;
} 
do_ioerr_test vacuum3-ioerr-2 -cksum true -sqlprep " 
  PRAGMA page_size = 2048;
  $create_database_sql
" -sqlbody {
  PRAGMA page_size = 512;
  VACUUM;
} 

ifcapable autovacuum {
  do_ioerr_test vacuum3-ioerr-3 -cksum true -sqlprep "
    PRAGMA auto_vacuum = 0;
    $create_database_sql
  " -sqlbody {
    PRAGMA auto_vacuum = 1;
    VACUUM;
  } 
  do_ioerr_test vacuum3-ioerr-4 -cksum true -sqlprep "
    PRAGMA auto_vacuum = 1;
    $create_database_sql
  " -sqlbody {
    PRAGMA auto_vacuum = 0;
    VACUUM;
  } 
}

source $testdir/malloc_common.tcl
if {$MEMDEBUG} {
  do_malloc_test vacuum3-malloc-1 -sqlprep { 
    PRAGMA page_size = 2048;
    BEGIN; 
    CREATE TABLE t1(a, b, c); 
    INSERT INTO t1 VALUES(1, randstr(50,50), randstr(50,50)); 
    INSERT INTO t1 SELECT a+2, b||'-'||rowid, c||'-'||rowid FROM t1; 
    INSERT INTO t1 SELECT a+4, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+8, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+16, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+32, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+64, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 SELECT a+128, b||'-'||rowid, c||'-'||rowid FROM t1;
    INSERT INTO t1 VALUES(1, randstr(600,600), randstr(600,600));
    CREATE TABLE t2 AS SELECT * FROM t1;
    CREATE TABLE t3 AS SELECT * FROM t1;
    COMMIT;
    DROP TABLE t2;
  } -sqlbody {
    PRAGMA page_size = 512;
    VACUUM;
  } 
  do_malloc_test vacuum3-malloc-2 -sqlprep { 
    PRAGMA encoding=UTF16;
    CREATE TABLE t1(a, b, c);
    INSERT INTO t1 VALUES(1, 2, 3);
    CREATE TABLE t2(x,y,z);
    INSERT INTO t2 SELECT * FROM t1;
  } -sqlbody {
    VACUUM;
  } 
}

finish_test

Added test/varint.test.

































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this script is variable-length integer encoding scheme.
#
# $Id: varint.test,v 1.1 2004/05/18 15:57:42 drh Exp $


set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Test reading and writing of varints.
#
set cnt 0
foreach start {0 100 10000 1000000 0x10000000} {
  foreach mult {1 0x10 0x100 0x1000 0x10000 0x100000 0x1000000 0x10000000} {
    foreach incr {1 500 10000 50000000} {
      incr cnt
      do_test varint-1.$cnt {
        btree_varint_test $start $mult 5000 $incr
      } {}
    }
  }
}

Added test/veryquick.test.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file runs all the tests run by quick.test except for those related
# to malloc or IO error simulation. With these tests omitted, the overall
# run time is reduced by about 75%.
#
# $Id: veryquick.test,v 1.9 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
set ISVERYQUICK 1
source $testdir/quick.test

Added test/view.test.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# 2002 February 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing VIEW statements.
#
# $Id: view.test,v 1.39 2008/12/14 14:45:21 danielk1977 Exp $
set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Omit this entire file if the library is not configured with views enabled.
ifcapable !view {
  finish_test
  return
}

do_test view-1.0 {
  execsql {
    CREATE TABLE t1(a,b,c);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(4,5,6);
    INSERT INTO t1 VALUES(7,8,9);
    SELECT * FROM t1;
  }
} {1 2 3 4 5 6 7 8 9}

do_test view-1.1 {
  execsql {
    BEGIN;
    CREATE VIEW IF NOT EXISTS v1 AS SELECT a,b FROM t1;
    SELECT * FROM v1 ORDER BY a;
  }
} {1 2 4 5 7 8}
do_test view-1.2 {
  catchsql {
    ROLLBACK;
    SELECT * FROM v1 ORDER BY a;
  }
} {1 {no such table: v1}}
do_test view-1.3 {
  execsql {
    CREATE VIEW v1 AS SELECT a,b FROM t1;
    SELECT * FROM v1 ORDER BY a;
  }
} {1 2 4 5 7 8}
do_test view-1.3.1 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM v1 ORDER BY a;
  }
} {1 2 4 5 7 8}
do_test view-1.4 {
  catchsql {
    DROP VIEW IF EXISTS v1;
    SELECT * FROM v1 ORDER BY a;
  }
} {1 {no such table: v1}}
do_test view-1.5 {
  execsql {
    CREATE VIEW v1 AS SELECT a,b FROM t1;
    SELECT * FROM v1 ORDER BY a;
  }
} {1 2 4 5 7 8}
do_test view-1.6 {
  catchsql {
    DROP TABLE t1;
    SELECT * FROM v1 ORDER BY a;
  }
} {1 {no such table: main.t1}}
do_test view-1.7 {
  execsql {
    CREATE TABLE t1(x,a,b,c);
    INSERT INTO t1 VALUES(1,2,3,4);
    INSERT INTO t1 VALUES(4,5,6,7);
    INSERT INTO t1 VALUES(7,8,9,10);
    SELECT * FROM v1 ORDER BY a;
  }
} {2 3 5 6 8 9}
do_test view-1.8 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM v1 ORDER BY a;
  }
} {2 3 5 6 8 9}

do_test view-2.1 {
  execsql {
    CREATE VIEW v2 AS SELECT * FROM t1 WHERE a>5
  };  # No semicolon
  execsql2 {
    SELECT * FROM v2;
  }
} {x 7 a 8 b 9 c 10}
do_test view-2.2 {
  catchsql {
    INSERT INTO v2 VALUES(1,2,3,4);
  }
} {1 {cannot modify v2 because it is a view}}
do_test view-2.3 {
  catchsql {
    UPDATE v2 SET a=10 WHERE a=5;
  }
} {1 {cannot modify v2 because it is a view}}
do_test view-2.4 {
  catchsql {
    DELETE FROM v2;
  }
} {1 {cannot modify v2 because it is a view}}
do_test view-2.5 {
  execsql {
    INSERT INTO t1 VALUES(11,12,13,14);
    SELECT * FROM v2 ORDER BY x;
  }
} {7 8 9 10 11 12 13 14}
do_test view-2.6 {
  execsql {
    SELECT x FROM v2 WHERE a>10
  }
} {11}

# Test that column name of views are generated correctly.
#
do_test view-3.1 {
  execsql2 {
    SELECT * FROM v1 LIMIT 1
  }
} {a 2 b 3}
do_test view-3.2 {
  execsql2 {
    SELECT * FROM v2 LIMIT 1
  }
} {x 7 a 8 b 9 c 10}
do_test view-3.3.1 {
  execsql2 {
    DROP VIEW v1;
    CREATE VIEW v1 AS SELECT a AS 'xyz', b+c AS 'pqr', c-b FROM t1;
    SELECT * FROM v1 LIMIT 1
  }
} {xyz 2 pqr 7 c-b 1}
do_test view-3.3.2 {
  execsql2 {
    CREATE VIEW v1b AS SELECT t1.a, b+c, t1.c FROM t1;
    SELECT * FROM v1b LIMIT 1
  }
} {a 2 b+c 7 c 4}

ifcapable compound {
do_test  view-3.4 {
  execsql2 {
    CREATE VIEW v3 AS SELECT a FROM t1 UNION SELECT b FROM t1 ORDER BY b;
    SELECT * FROM v3 LIMIT 4;
  }
} {a 2 a 3 a 5 a 6}
do_test view-3.5 {
  execsql2 {
    CREATE VIEW v4 AS 
      SELECT a, b FROM t1 
      UNION
      SELECT b AS 'x', a AS 'y' FROM t1
      ORDER BY x, y;
    SELECT b FROM v4 ORDER BY b LIMIT 4;
  }
} {b 2 b 3 b 5 b 6}
} ;# ifcapable compound


do_test view-4.1 {
  catchsql {
    DROP VIEW t1;
  }
} {1 {use DROP TABLE to delete table t1}}
do_test view-4.2 {
  execsql {
    SELECT 1 FROM t1 LIMIT 1;
  }
} 1
do_test view-4.3 {
  catchsql {
    DROP TABLE v1;
  }
} {1 {use DROP VIEW to delete view v1}}
do_test view-4.4 {
  execsql {
     SELECT 1 FROM v1 LIMIT 1;
  }
} {1}
do_test view-4.5 {
  catchsql {
    CREATE INDEX i1v1 ON v1(xyz);
  }
} {1 {views may not be indexed}}

do_test view-5.1 {
  execsql {
    CREATE TABLE t2(y,a);
    INSERT INTO t2 VALUES(22,2);
    INSERT INTO t2 VALUES(33,3);
    INSERT INTO t2 VALUES(44,4);
    INSERT INTO t2 VALUES(55,5);
    SELECT * FROM t2;
  }
} {22 2 33 3 44 4 55 5}
do_test view-5.2 {
  execsql {
    CREATE VIEW v5 AS
      SELECT t1.x AS v, t2.y AS w FROM t1 JOIN t2 USING(a);
    SELECT * FROM v5;
  }
} {1 22 4 55}

# Verify that the view v5 gets flattened.  see sqliteFlattenSubquery().
# This will only work if EXPLAIN is enabled.
# Ticket #272
#
ifcapable {explain} {
do_test view-5.3 {
  lsearch [execsql {
    EXPLAIN SELECT * FROM v5;
  }] OpenEphemeral
} {-1}
do_test view-5.4 {
  execsql {
    SELECT * FROM v5 AS a, t2 AS b WHERE a.w=b.y;
  }
} {1 22 22 2 4 55 55 5}
do_test view-5.5 {
  lsearch [execsql {
    EXPLAIN SELECT * FROM v5 AS a, t2 AS b WHERE a.w=b.y;
  }] OpenEphemeral
} {-1}
do_test view-5.6 {
  execsql {
    SELECT * FROM t2 AS b, v5 AS a WHERE a.w=b.y;
  }
} {22 2 1 22 55 5 4 55}
do_test view-5.7 {
  lsearch [execsql {
    EXPLAIN SELECT * FROM t2 AS b, v5 AS a WHERE a.w=b.y;
  }] OpenEphemeral
} {-1}
do_test view-5.8 {
  execsql {
    SELECT * FROM t1 AS a, v5 AS b, t2 AS c WHERE a.x=b.v AND b.w=c.y;
  }
} {1 2 3 4 1 22 22 2 4 5 6 7 4 55 55 5}
do_test view-5.9 {
  lsearch [execsql {
    EXPLAIN SELECT * FROM t1 AS a, v5 AS b, t2 AS c WHERE a.x=b.v AND b.w=c.y;
  }] OpenEphemeral
} {-1}
} ;# endif explain

do_test view-6.1 {
  execsql {
    SELECT min(x), min(a), min(b), min(c), min(a+b+c) FROM v2;
  }
} {7 8 9 10 27}
do_test view-6.2 {
  execsql {
    SELECT max(x), max(a), max(b), max(c), max(a+b+c) FROM v2;
  }
} {11 12 13 14 39}

do_test view-7.1 {
  execsql {
    CREATE TABLE test1(id integer primary key, a);
    CREATE TABLE test2(id integer, b);
    INSERT INTO test1 VALUES(1,2);
    INSERT INTO test2 VALUES(1,3);
    CREATE VIEW test AS
      SELECT test1.id, a, b
      FROM test1 JOIN test2 ON test2.id=test1.id;
    SELECT * FROM test;
  }
} {1 2 3}
do_test view-7.2 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM test;
  }
} {1 2 3}
do_test view-7.3 {
  execsql {
    DROP VIEW test;
    CREATE VIEW test AS
      SELECT test1.id, a, b
      FROM test1 JOIN test2 USING(id);
    SELECT * FROM test;
  }
} {1 2 3}
do_test view-7.4 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM test;
  }
} {1 2 3}
do_test view-7.5 {
  execsql {
    DROP VIEW test;
    CREATE VIEW test AS
      SELECT test1.id, a, b
      FROM test1 NATURAL JOIN test2;
    SELECT * FROM test;
  }
} {1 2 3}
do_test view-7.6 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM test;
  }
} {1 2 3}

do_test view-8.1 {
  execsql {
    CREATE VIEW v6 AS SELECT pqr, xyz FROM v1;
    SELECT * FROM v6 ORDER BY xyz;
  }
} {7 2 13 5 19 8 27 12}
do_test view-8.2 {
  db close
  sqlite3 db test.db
  execsql {
    SELECT * FROM v6 ORDER BY xyz;
  }
} {7 2 13 5 19 8 27 12}
do_test view-8.3 {
  execsql {
    CREATE VIEW v7 AS SELECT pqr+xyz AS a FROM v6;
    SELECT * FROM v7 ORDER BY a;
  }
} {9 18 27 39}

ifcapable subquery {
  do_test view-8.4 {
    execsql {
      CREATE VIEW v8 AS SELECT max(cnt) AS mx FROM
        (SELECT a%2 AS eo, count(*) AS cnt FROM t1 GROUP BY eo);
      SELECT * FROM v8;
    }
  } 3
  do_test view-8.5 {
    execsql {
      SELECT mx+10, mx*2 FROM v8;
    }
  } {13 6}
  do_test view-8.6 {
    execsql {
      SELECT mx+10, pqr FROM v6, v8 WHERE xyz=2;
    }
  } {13 7}
  do_test view-8.7 {
    execsql {
      SELECT mx+10, pqr FROM v6, v8 WHERE xyz>2;
    }
  } {13 13 13 19 13 27}
} ;# ifcapable subquery

# Tests for a bug found by Michiel de Wit involving ORDER BY in a VIEW.
#
do_test view-9.1 {
  execsql {
    INSERT INTO t2 SELECT * FROM t2 WHERE a<5;
    INSERT INTO t2 SELECT * FROM t2 WHERE a<4;
    INSERT INTO t2 SELECT * FROM t2 WHERE a<3;
    SELECT DISTINCT count(*) FROM t2 GROUP BY a ORDER BY 1;
  }
} {1 2 4 8}
do_test view-9.2 {
  execsql {
    SELECT DISTINCT count(*) FROM t2 GROUP BY a ORDER BY 1 LIMIT 3;
  }
} {1 2 4}
do_test view-9.3 {
  execsql {
    CREATE VIEW v9 AS 
       SELECT DISTINCT count(*) FROM t2 GROUP BY a ORDER BY 1 LIMIT 3;
    SELECT * FROM v9;
  }
} {1 2 4}
do_test view-9.4 {
  execsql {
    SELECT * FROM v9 ORDER BY 1 DESC;
  }
} {4 2 1}
do_test view-9.5 {
  execsql {
    CREATE VIEW v10 AS 
       SELECT DISTINCT a, count(*) FROM t2 GROUP BY a ORDER BY 2 LIMIT 3;
    SELECT * FROM v10;
  }
} {5 1 4 2 3 4}
do_test view-9.6 {
  execsql {
    SELECT * FROM v10 ORDER BY 1;
  }
} {3 4 4 2 5 1}

# Tables with columns having peculiar quoted names used in views
# Ticket #756.
#
do_test view-10.1 {
  execsql {
    CREATE TABLE t3("9" integer, [4] text);
    INSERT INTO t3 VALUES(1,2);
    CREATE VIEW v_t3_a AS SELECT a.[9] FROM t3 AS a;
    CREATE VIEW v_t3_b AS SELECT "4" FROM t3;
    SELECT * FROM v_t3_a;
  }
} {1}
do_test view-10.2 {
  execsql {
    SELECT * FROM v_t3_b;
  }
} {2}

do_test view-11.1 {
  execsql {
    CREATE TABLE t4(a COLLATE NOCASE);
    INSERT INTO t4 VALUES('This');
    INSERT INTO t4 VALUES('this');
    INSERT INTO t4 VALUES('THIS');
    SELECT * FROM t4 WHERE a = 'THIS';
  }
} {This this THIS}
ifcapable subquery {
  do_test view-11.2 {
    execsql {
      SELECT * FROM (SELECT * FROM t4) WHERE a = 'THIS';
    }
  } {This this THIS}
}
do_test view-11.3 {
  execsql {
    CREATE VIEW v11 AS SELECT * FROM t4;
    SELECT * FROM v11 WHERE a = 'THIS';
  }
} {This this THIS}

# Ticket #1270:  Do not allow parameters in view definitions.
#
do_test view-12.1 {
  catchsql {
    CREATE VIEW v12 AS SELECT a FROM t1 WHERE b=?
  }
} {1 {parameters are not allowed in views}}

ifcapable attach {
  do_test view-13.1 {
    file delete -force test2.db
    catchsql {
      ATTACH 'test2.db' AS two;
      CREATE TABLE two.t2(x,y);
      CREATE VIEW v13 AS SELECT y FROM two.t2;
    }
  } {1 {view v13 cannot reference objects in database two}}
}

# Ticket #1658
#
do_test view-14.1 {
  catchsql {
    CREATE TEMP VIEW t1 AS SELECT a,b FROM t1;
    SELECT * FROM temp.t1;
  }
} {1 {view t1 is circularly defined}}

# Tickets #1688, #1709
#
do_test view-15.1 {
  execsql2 {
    CREATE VIEW v15 AS SELECT a AS x, b AS y FROM t1;
    SELECT * FROM v15 LIMIT 1;
  }
} {x 2 y 3}
do_test view-15.2 {
  execsql2 {
    SELECT x, y FROM v15 LIMIT 1
  }
} {x 2 y 3}

do_test view-16.1 {
  catchsql {
    CREATE VIEW IF NOT EXISTS v1 AS SELECT * FROM t1;
  }
} {0 {}}
do_test view-16.2 {
  execsql {
    SELECT sql FROM sqlite_master WHERE name='v1'
  }
} {{CREATE VIEW v1 AS SELECT a AS 'xyz', b+c AS 'pqr', c-b FROM t1}}
do_test view-16.3 {
  catchsql {
    DROP VIEW IF EXISTS nosuchview
  }
} {0 {}}

# correct error message when attempting to drop a view that does not
# exist.
#
do_test view-17.1 {
  catchsql {
    DROP VIEW nosuchview
  }
} {1 {no such view: nosuchview}}
do_test view-17.2 {
  catchsql {
    DROP VIEW main.nosuchview
  }
} {1 {no such view: main.nosuchview}}

do_test view-18.1 {
  execsql {
    DROP VIEW t1;
    DROP TABLE t1;
    CREATE TABLE t1(a, b, c);
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);

    CREATE VIEW vv1 AS SELECT * FROM t1;
    CREATE VIEW vv2 AS SELECT * FROM vv1;
    CREATE VIEW vv3 AS SELECT * FROM vv2;
    CREATE VIEW vv4 AS SELECT * FROM vv3;
    CREATE VIEW vv5 AS SELECT * FROM vv4;

    SELECT * FROM vv5;
  }
} {1 2 3 4 5 6}

# Ticket #3308
# Make sure "rowid" columns in a view are named correctly.
#
do_test view-19.1 {
  execsql {
    CREATE VIEW v3308a AS SELECT rowid, * FROM t1;
  }
  execsql2 {
    SELECT * FROM v3308a
  }
} {rowid 1 a 1 b 2 c 3 rowid 2 a 4 b 5 c 6}
do_test view-19.2 {
  execsql {
    CREATE VIEW v3308b AS SELECT t1.rowid, t1.a, t1.b+t1.c FROM t1;
  }
  execsql2 {
    SELECT * FROM v3308b
  }
} {rowid 1 a 1 t1.b+t1.c 5 rowid 2 a 4 t1.b+t1.c 11}
do_test view-19.3 {
  execsql {
    CREATE VIEW v3308c AS SELECT t1.oid, A, t1.b+t1.c AS x FROM t1;
  }
  execsql2 {
    SELECT * FROM v3308c
  }
} {rowid 1 a 1 x 5 rowid 2 a 4 x 11}

# Ticket #3539 had this crashing (see commit [5940]).
do_test view-20.1 {
  execsql {
    DROP TABLE IF EXISTS t1;
    DROP VIEW IF EXISTS v1;
    CREATE TABLE t1(c1);
    CREATE VIEW v1 AS SELECT c1 FROM (SELECT t1.c1 FROM t1);
  }
} {}

finish_test

Added test/vtab1.test.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
# 2006 June 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is creating and dropping virtual tables.
#
# $Id: vtab1.test,v 1.57 2008/08/01 17:51:47 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab||!schema_pragmas {
  finish_test
  return
}

#----------------------------------------------------------------------
# Organization of tests in this file:
#
# vtab1-1.*: Error conditions and other issues surrounding creation/connection
#            of a virtual module.
# vtab1-2.*: Test sqlite3_declare_vtab() and the xConnect/xDisconnect methods.
# vtab1-3.*: Table scans and WHERE clauses.
# vtab1-4.*: Table scans and ORDER BY clauses.
# vtab1-5.*: Test queries that include joins. This brings the
#            sqlite3_index_info.estimatedCost variable into play.
# vtab1-6.*: Test UPDATE/INSERT/DELETE on vtables.
# vtab1-7.*: Test sqlite3_last_insert_rowid().
#
# This file uses the "echo" module (see src/test8.c). Refer to comments
# in that file for the special behaviour of the Tcl $echo_module variable.
#
# TODO: 
#   * How to test the sqlite3_index_constraint_usage.omit field?
#   * vtab1-5.*
#
# vtab1-14.*: Test 'IN' constraints - i.e. "SELECT * FROM t1 WHERE id IN(...)"
#


#----------------------------------------------------------------------
# Test cases vtab1.1.*
#

# We cannot create a virtual table if the module has not been registered.
#
do_test vtab1-1.1 {
  explain {
    CREATE VIRTUAL TABLE t1 USING echo;
  }
  catchsql {
    CREATE VIRTUAL TABLE t1 USING echo;
  }
} {1 {no such module: echo}}
do_test vtab1-1.2 {
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1
  }
} {}

# Register the module
register_echo_module [sqlite3_connection_pointer db]

# Once a module has been registered, virtual tables using that module
# may be created. However if a module xCreate() fails to call
# sqlite3_declare_vtab() an error will be raised and the table not created.
#
# The "echo" module does not invoke sqlite3_declare_vtab() if it is
# passed zero arguments.
#
do_test vtab1-1.3 {
  catchsql {
    CREATE VIRTUAL TABLE t1 USING echo;
  }
} {1 {vtable constructor did not declare schema: t1}}
do_test vtab1-1.4 {
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1
  }
} {}

# The "echo" module xCreate method returns an error and does not create
# the virtual table if it is passed an argument that does not correspond
# to an existing real table in the same database.
#
do_test vtab1-1.5 {
  catchsql {
    CREATE VIRTUAL TABLE t1 USING echo(no_such_table);
  }
} {1 {vtable constructor failed: t1}}
do_test vtab1-1.6 {
  execsql {
    SELECT name FROM sqlite_master ORDER BY 1
  }
} {}

# Ticket #2156.  Using the sqlite3_prepare_v2() API, make sure that
# a CREATE VIRTUAL TABLE statement can be used multiple times.
#
do_test vtab1-1.2152.1 {
  set DB [sqlite3_connection_pointer db]
  set sql {CREATE VIRTUAL TABLE t2152a USING echo(t2152b)}
  set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL]
  sqlite3_step $STMT
} SQLITE_ERROR
do_test vtab-1.2152.2 {
  sqlite3_reset $STMT
  sqlite3_step $STMT
} SQLITE_ERROR
do_test vtab-1.2152.3 {
  sqlite3_reset $STMT
  db eval {CREATE TABLE t2152b(x,y)}
  sqlite3_step $STMT
} SQLITE_DONE
do_test vtab-1.2152.4 {
  sqlite3_finalize $STMT
  db eval {DROP TABLE t2152a; DROP TABLE t2152b}
} {}

# Test to make sure nothing goes wrong and no memory is leaked if we 
# select an illegal table-name (i.e a reserved name or the name of a
# table that already exists).
#
do_test vtab1-1.7 {
  catchsql {
    CREATE VIRTUAL TABLE sqlite_master USING echo;
  }
} {1 {object name reserved for internal use: sqlite_master}}
do_test vtab1-1.8 {
  catchsql {
    CREATE TABLE treal(a, b, c);
    CREATE VIRTUAL TABLE treal USING echo(treal);
  }
} {1 {table treal already exists}}
do_test vtab1-1.9 {
  execsql {
    DROP TABLE treal;
    SELECT name FROM sqlite_master ORDER BY 1
  }
} {}

do_test vtab1-1.10 {
  execsql {
    CREATE TABLE treal(a, b, c);
    CREATE VIRTUAL TABLE techo USING echo(treal);
  }
  db close
  sqlite3 db test.db
  catchsql {
    SELECT * FROM techo;
  }
} {1 {no such module: echo}}
do_test vtab1-1.11 {
  catchsql {
    INSERT INTO techo VALUES(1, 2, 3);
  }
} {1 {no such module: echo}}
do_test vtab1-1.12 {
  catchsql {
    UPDATE techo SET a = 10;
  }
} {1 {no such module: echo}}
do_test vtab1-1.13 {
  catchsql {
    DELETE FROM techo;
  }
} {1 {no such module: echo}}
do_test vtab1-1.14 {
  catchsql {
    PRAGMA table_info(techo)
  }
} {1 {no such module: echo}}
do_test vtab1-1.15 {
  catchsql {
    DROP TABLE techo;
  }
} {1 {no such module: echo}}

register_echo_module [sqlite3_connection_pointer db]
register_echo_module [sqlite3_connection_pointer db]

# Test an error message returned from a v-table constructor.
#
do_test vtab1-1.16 {
  execsql {
    DROP TABLE techo;
    CREATE TABLE logmsg(log);
  }
  catchsql {
    CREATE VIRTUAL TABLE techo USING echo(treal, logmsg);
  }
} {1 {table 'logmsg' already exists}}

do_test vtab1-1.17 {
  execsql {
    DROP TABLE treal;
    DROP TABLE logmsg;
    SELECT sql FROM sqlite_master;
  }
} {}

#----------------------------------------------------------------------
# Test cases vtab1.2.*
#
# At this point, the database is completely empty. The echo module
# has already been registered.

# If a single argument is passed to the echo module during table
# creation, it is assumed to be the name of a table in the same
# database. The echo module attempts to set the schema of the
# new virtual table to be the same as the existing database table.
#
do_test vtab1-2.1 {
  execsql {
    CREATE TABLE template(a, b, c);
  }
  execsql { PRAGMA table_info(template); }
} [list         \
  0 a {} 0 {} 0 \
  1 b {} 0 {} 0 \
  2 c {} 0 {} 0 \
]
do_test vtab1-2.2 {
  execsql {
    CREATE VIRTUAL TABLE t1 USING echo(template);
  }
  execsql { PRAGMA table_info(t1); }
} [list         \
  0 a {} 0 {} 0 \
  1 b {} 0 {} 0 \
  2 c {} 0 {} 0 \
]

# Test that the database can be unloaded. This should invoke the xDisconnect()
# callback for the successfully create virtual table (t1).
#
do_test vtab1-2.3 {
  set echo_module [list]
  db close
  set echo_module
} [list xDisconnect]

# Re-open the database. This should not cause any virtual methods to 
# be called. The invocation of xConnect() is delayed until the virtual
# table schema is first required by the compiler.
#
do_test vtab1-2.4 {
  set echo_module [list]
  sqlite3 db test.db
  db cache size 0
  set echo_module
} {}

# Try to query the virtual table schema. This should fail, as the
# echo module has not been registered with this database connection.
#
do_test vtab1.2.6 {
  catchsql { PRAGMA table_info(t1); }
} {1 {no such module: echo}}

# Register the module
register_echo_module [sqlite3_connection_pointer db]

# Try to query the virtual table schema again. This time it should
# invoke the xConnect method and succeed.
#
do_test vtab1.2.7 {
  execsql { PRAGMA table_info(t1); }
} [list         \
  0 a {} 0 {} 0 \
  1 b {} 0 {} 0 \
  2 c {} 0 {} 0 \
]
do_test vtab1.2.8 {
  set echo_module
} {xConnect echo main t1 template}

# Drop table t1. This should cause the xDestroy (but not xDisconnect) method 
# to be invoked.
do_test vtab1-2.5 {
  set echo_module ""
  execsql {
    DROP TABLE t1;
  }
  set echo_module
} {xDestroy}

do_test vtab1-2.6 {
  execsql { 
    PRAGMA table_info(t1); 
  }
} {}
do_test vtab1-2.7 {
  execsql {
    SELECT sql FROM sqlite_master;
  }
} [list {CREATE TABLE template(a, b, c)}]
# Clean up other test artifacts:
do_test vtab1-2.8 {
  execsql { 
    DROP TABLE template;
    SELECT sql FROM sqlite_master;
  }
} [list]

#----------------------------------------------------------------------
# Test case vtab1-3 test table scans and the echo module's 
# xBestIndex/xFilter handling of WHERE conditions.

do_test vtab1-3.1 {
  set echo_module ""
  execsql {
    CREATE TABLE treal(a INTEGER, b INTEGER, c); 
    CREATE INDEX treal_idx ON treal(b);
    CREATE VIRTUAL TABLE t1 USING echo(treal);
  }
  set echo_module
} [list xCreate echo main t1 treal   \
        xSync   echo(treal)  \
        xCommit echo(treal)  \
]

# Test that a SELECT on t1 doesn't crash. No rows are returned
# because the underlying real table is currently empty.
#
do_test vtab1-3.2 {
  execsql {
    SELECT a, b, c FROM t1;
  }
} {}

# Put some data into the table treal. Then try a few simple SELECT 
# statements on t1.
#
do_test vtab1-3.3 {
  execsql {
    INSERT INTO treal VALUES(1, 2, 3);
    INSERT INTO treal VALUES(4, 5, 6);
    SELECT * FROM t1;
  }
} {1 2 3 4 5 6}
do_test vtab1-3.4 {
  execsql {
    SELECT a FROM t1;
  }
} {1 4}
do_test vtab1-3.5 {
  execsql {
    SELECT rowid FROM t1;
  }
} {1 2}
do_test vtab1-3.6 {
  set echo_module ""
  execsql {
    SELECT * FROM t1;
  }
} {1 2 3 4 5 6}
do_test vtab1-3.7 {
  execsql {
    SELECT rowid, * FROM t1;
  }
} {1 1 2 3 2 4 5 6}
do_test vtab1-3.8 {
  execsql {
    SELECT a AS d, b AS e, c AS f FROM t1;
  }
} {1 2 3 4 5 6}

# Execute some SELECT statements with WHERE clauses on the t1 table.
# Then check the echo_module variable (written to by the module methods
# in test8.c) to make sure the xBestIndex() and xFilter() methods were
# called correctly.
#
do_test vtab1-3.8 {
  set echo_module ""
  execsql {
    SELECT * FROM t1;
  }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal'} \
        xFilter    {SELECT rowid, * FROM 'treal'} ]
do_test vtab1-3.9 {
  set echo_module ""
  execsql {
    SELECT * FROM t1 WHERE b = 5;
  }
} {4 5 6}
do_test vtab1-3.10 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal' WHERE b = ?}   \
        xFilter    {SELECT rowid, * FROM 'treal' WHERE b = ?} 5 ]
do_test vtab1-3.10 {
  set echo_module ""
  execsql {
    SELECT * FROM t1 WHERE b >= 5 AND b <= 10;
  }
} {4 5 6}
do_test vtab1-3.11 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?}      \
        xFilter    {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?} 5 10 ]
do_test vtab1-3.12 {
  set echo_module ""
  execsql {
    SELECT * FROM t1 WHERE b BETWEEN 2 AND 10;
  }
} {1 2 3 4 5 6}
do_test vtab1-3.13 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?}      \
        xFilter    {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?} 2 10 ]

# Add a function for the MATCH operator. Everything always matches!
#proc test_match {lhs rhs} {
#  lappend ::echo_module MATCH $lhs $rhs
#  return 1
#}
#db function match test_match

set echo_module ""
do_test vtab1-3.12 {
  set echo_module ""
  catchsql {
    SELECT * FROM t1 WHERE a MATCH 'string';
  }
} {1 {unable to use function MATCH in the requested context}}
do_test vtab1-3.13 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal'} \
        xFilter    {SELECT rowid, * FROM 'treal'}]
ifcapable subquery {
# The echo module uses a subquery internally to implement the MATCH operator.
do_test vtab1-3.14 {
  set echo_module ""
  execsql {
    SELECT * FROM t1 WHERE b MATCH 'string';
  }
} {}
do_test vtab1-3.15 {
  set echo_module
} [list xBestIndex \
        {SELECT rowid, * FROM 'treal' WHERE b LIKE (SELECT '%'||?||'%')}  \
        xFilter \
        {SELECT rowid, * FROM 'treal' WHERE b LIKE (SELECT '%'||?||'%')} \
        string ]
}; #ifcapable subquery

#----------------------------------------------------------------------
# Test case vtab1-3 test table scans and the echo module's 
# xBestIndex/xFilter handling of ORDER BY clauses.

# This procedure executes the SQL.  Then it checks to see if the OP_Sort
# opcode was executed.  If an OP_Sort did occur, then "sort" is appended
# to the result.  If no OP_Sort happened, then "nosort" is appended.
#
# This procedure is used to check to make sure sorting is or is not
# occurring as expected.
#
proc cksort {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

do_test vtab1-4.1 {
  set echo_module ""
  cksort {
    SELECT b FROM t1 ORDER BY b;
  }
} {2 5 nosort}
do_test vtab1-4.2 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal' ORDER BY b ASC} \
        xFilter    {SELECT rowid, * FROM 'treal' ORDER BY b ASC} ]
do_test vtab1-4.3 {
  set echo_module ""
  cksort {
    SELECT b FROM t1 ORDER BY b DESC;
  }
} {5 2 nosort}
do_test vtab1-4.4 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal' ORDER BY b DESC} \
        xFilter    {SELECT rowid, * FROM 'treal' ORDER BY b DESC} ]
do_test vtab1-4.3 {
  set echo_module ""
  cksort {
    SELECT b FROM t1 ORDER BY b||'';
  }
} {2 5 sort}
do_test vtab1-4.4 {
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal'} \
        xFilter    {SELECT rowid, * FROM 'treal'} ]

execsql {
  DROP TABLE t1;
  DROP TABLE treal;
}

#----------------------------------------------------------------------
# Test cases vtab1-5 test SELECT queries that include joins on virtual 
# tables.

proc filter {log} {
  set out [list]
  for {set ii 0} {$ii < [llength $log]} {incr ii} {
    if {[lindex $log $ii] eq "xFilter"} {
      lappend out xFilter
      lappend out [lindex $log [expr $ii+1]]
    }
  }
  return $out
}

do_test vtab1-5-1 {
  execsql { 
    CREATE TABLE t1(a, b, c);
    CREATE TABLE t2(d, e, f);
    INSERT INTO t1 VALUES(1, 'red', 'green');
    INSERT INTO t1 VALUES(2, 'blue', 'black');
    INSERT INTO t2 VALUES(1, 'spades', 'clubs');
    INSERT INTO t2 VALUES(2, 'hearts', 'diamonds');
    CREATE VIRTUAL TABLE et1 USING echo(t1);
    CREATE VIRTUAL TABLE et2 USING echo(t2);
  }
} {}

do_test vtab1-5-2 {
  set echo_module ""
  execsql {
    SELECT * FROM et1, et2;
  }
} [list \
  1 red green 1 spades clubs     \
  1 red green 2 hearts diamonds  \
  2 blue black 1 spades clubs    \
  2 blue black 2 hearts diamonds \
]
do_test vtab1-5-3 {
  filter $echo_module
} [list \
  xFilter {SELECT rowid, * FROM 't1'} \
  xFilter {SELECT rowid, * FROM 't2'} \
  xFilter {SELECT rowid, * FROM 't2'} \
]
do_test vtab1-5-4 {
  set echo_module ""
  execsql {
    SELECT * FROM et1, et2 WHERE et2.d = 2;
  }
} [list \
  1 red green 2 hearts diamonds  \
  2 blue black 2 hearts diamonds \
]
do_test vtab1-5-5 {
  filter $echo_module
} [list \
  xFilter {SELECT rowid, * FROM 't1'} \
  xFilter {SELECT rowid, * FROM 't2'} \
  xFilter {SELECT rowid, * FROM 't2'} \
]
do_test vtab1-5-6 {
  execsql {
    CREATE INDEX i1 ON t2(d);
  }

  db close
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]

  set ::echo_module ""
  execsql {
    SELECT * FROM et1, et2 WHERE et2.d = 2;
  }
} [list \
  1 red green 2 hearts diamonds  \
  2 blue black 2 hearts diamonds \
]
do_test vtab1-5-7 {
  filter $::echo_module
} [list \
  xFilter {SELECT rowid, * FROM 't2' WHERE d = ?} \
  xFilter {SELECT rowid, * FROM 't1'}             \
]

execsql {
  DROP TABLE t1;
  DROP TABLE t2;
  DROP TABLE et1;
  DROP TABLE et2;
}

#----------------------------------------------------------------------
# Test cases vtab1-6 test INSERT, UPDATE and DELETE operations 
# on virtual tables.
do_test vtab1-6-1 {
  execsql { SELECT sql FROM sqlite_master }
} {}
do_test vtab1-6-2 {
  execsql {
    CREATE TABLE treal(a PRIMARY KEY, b, c);
    CREATE VIRTUAL TABLE techo USING echo(treal);
    SELECT name FROM sqlite_master WHERE type = 'table';
  }
} {treal techo}
do_test vtab1-6-3.1.1 {
  execsql {
    PRAGMA count_changes=ON;
    INSERT INTO techo VALUES(1, 2, 3);
  }
} {1}
do_test vtab1-6-3.1.2 {
  db changes
} {1}
do_test vtab1-6-3.2 {
  execsql {
    SELECT * FROM techo;
  }
} {1 2 3}
do_test vtab1-6-4.1 {
  execsql {
    UPDATE techo SET a = 5;
  }
  db changes
} {1}
do_test vtab1-6-4.2 {
  execsql {
    SELECT * FROM techo;
  }
} {5 2 3}
do_test vtab1-6-4.3 {
  execsql {
    UPDATE techo SET a=6 WHERE a<0;
  }
  db changes
} {0}
do_test vtab1-6-4.4 {
  execsql {
    SELECT * FROM techo;
  }
} {5 2 3}

do_test vtab1-6-5.1 {
 execsql {
   UPDATE techo set a = a||b||c;
 }
 db changes
} {1}
do_test vtab1-6-5.2 {
 execsql {
   SELECT * FROM techo;
 }
} {523 2 3}

do_test vtab1-6-6.1 {
  execsql {
    UPDATE techo set rowid = 10;
  }
  db changes
} {1}
do_test vtab1-6-6.2 {
  execsql {
    SELECT rowid FROM techo;
  }
} {10}

do_test vtab1-6-7.1.1 {
  execsql {
    INSERT INTO techo VALUES(11,12,13);
  }
} {1}
do_test vtab1-6-7.1.2 {
  db changes
} {1}
do_test vtab1-6-7.2 {
  execsql {
    SELECT * FROM techo ORDER BY a;
  }
} {11 12 13 523 2 3}
do_test vtab1-6-7.3 {
  execsql {
    UPDATE techo SET b=b+1000
  }
  db changes
} {2}
do_test vtab1-6-7.4 {
  execsql {
    SELECT * FROM techo ORDER BY a;
  }
} {11 1012 13 523 1002 3}


do_test vtab1-6-8.1 {
  execsql {
    DELETE FROM techo WHERE a=5;
  }
  db changes
} {0}
do_test vtab1-6-8.2 {
  execsql {
    SELECT * FROM techo ORDER BY a;
  }
} {11 1012 13 523 1002 3}
do_test vtab1-6-8.3 {
  execsql {
    DELETE FROM techo;
  }
  db changes
} {2}
do_test vtab1-6-8.4 {
  execsql {
    SELECT * FROM techo ORDER BY a;
  }
} {}
execsql {PRAGMA count_changes=OFF}

file delete -force test2.db
file delete -force test2.db-journal
sqlite3 db2 test2.db
execsql {
  CREATE TABLE techo(a PRIMARY KEY, b, c);
} db2
proc check_echo_table {tn} {
  set ::data1 [execsql {SELECT rowid, * FROM techo}]
  set ::data2 [execsql {SELECT rowid, * FROM techo} db2]
  do_test $tn {
    string equal $::data1 $::data2
  } 1
}
set tn 0
foreach stmt [list \
  {INSERT INTO techo VALUES('abc', 'def', 'ghi')}                        \
  {INSERT INTO techo SELECT a||'.'||rowid, b, c FROM techo}              \
  {INSERT INTO techo SELECT a||'x'||rowid, b, c FROM techo}              \
  {INSERT INTO techo SELECT a||'y'||rowid, b, c FROM techo}              \
  {DELETE FROM techo WHERE (oid % 3) = 0}                                \
  {UPDATE techo set rowid = 100 WHERE rowid = 1}                         \
  {INSERT INTO techo(a, b) VALUES('hello', 'world')}                     \
  {DELETE FROM techo}                                                    \
] {
  execsql $stmt
  execsql $stmt db2
  check_echo_table vtab1-6.8.[incr tn]
}

db2 close



#----------------------------------------------------------------------
# Test cases vtab1-7 tests that the value returned by 
# sqlite3_last_insert_rowid() is set correctly when rows are inserted
# into virtual tables.
do_test vtab1.7-1 {
  execsql {
    CREATE TABLE real_abc(a PRIMARY KEY, b, c);
    CREATE VIRTUAL TABLE echo_abc USING echo(real_abc);
  }
} {}
do_test vtab1.7-2 {
  execsql {
    INSERT INTO echo_abc VALUES(1, 2, 3);
    SELECT last_insert_rowid();
  }
} {1}
do_test vtab1.7-3 {
  execsql {
    INSERT INTO echo_abc(rowid) VALUES(31427);
    SELECT last_insert_rowid();
  }
} {31427}
do_test vtab1.7-4 {
  execsql {
    INSERT INTO echo_abc SELECT a||'.v2', b, c FROM echo_abc;
    SELECT last_insert_rowid();
  }
} {31429}
do_test vtab1.7-5 {
  execsql {
    SELECT rowid, a, b, c FROM echo_abc
  }
} [list 1     1    2  3  \
        31427 {}   {} {} \
        31428 1.v2 2  3  \
        31429 {}  {} {}  \
]

# Now test that DELETE and UPDATE operations do not modify the value.
do_test vtab1.7-6 {
  execsql {
    UPDATE echo_abc SET c = 5 WHERE b = 2;
    SELECT last_insert_rowid();
  }
} {31429}
do_test vtab1.7-7 {
  execsql {
    UPDATE echo_abc SET rowid = 5 WHERE rowid = 1;
    SELECT last_insert_rowid();
  }
} {31429}
do_test vtab1.7-8 {
  execsql {
    DELETE FROM echo_abc WHERE b = 2;
    SELECT last_insert_rowid();
  }
} {31429}
do_test vtab1.7-9 {
  execsql {
    SELECT rowid, a, b, c FROM echo_abc
  }
} [list 31427 {} {} {} \
        31429 {} {} {} \
]
do_test vtab1.7-10 {
  execsql {
    DELETE FROM echo_abc WHERE b = 2;
    SELECT last_insert_rowid();
  }
} {31429}
do_test vtab1.7-11 {
  execsql {
    SELECT rowid, a, b, c FROM real_abc
  }
} [list 31427 {} {} {} \
        31429 {} {} {} \
]
do_test vtab1.7-12 {
  execsql {
    DELETE FROM echo_abc;
    SELECT last_insert_rowid();
  }
} {31429}
do_test vtab1.7-13 {
  execsql {
    SELECT rowid, a, b, c FROM real_abc
  }
} {}

ifcapable attach {
  do_test vtab1.8-1 {
    set echo_module ""
    execsql {
      ATTACH 'test2.db' AS aux;
      CREATE VIRTUAL TABLE aux.e2 USING echo(real_abc);
    }
    set echo_module
  } [list xCreate echo aux e2 real_abc   \
          xSync   echo(real_abc)         \
          xCommit echo(real_abc)         \
  ]
}
do_test vtab1.8-2 {
  catchsql {
    DROP TABLE aux.e2;
  }
  execsql {
    DROP TABLE treal;
    DROP TABLE techo;
    DROP TABLE echo_abc;
    DROP TABLE real_abc;
  }
} {}

do_test vtab1.9-1 {
  set echo_module ""
  execsql {
    CREATE TABLE r(a, b, c);
    CREATE VIRTUAL TABLE e USING echo(r, e_log);
    SELECT name FROM sqlite_master;
  }
} {r e e_log}
do_test vtab1.9-2 {
  execsql {
    DROP TABLE e;
    SELECT name FROM sqlite_master;
  }
} {r}

do_test vtab1.9-3 {
  set echo_module ""
  execsql {
    CREATE VIRTUAL TABLE e USING echo(r, e_log, virtual 1 2 3 varchar(32));
  }
  set echo_module
} [list                                                        \
  xCreate echo main e r e_log {virtual 1 2 3 varchar(32)}      \
  xSync echo(r)                                                \
  xCommit echo(r)                                              \
]

do_test vtab1.10-1 {
  execsql {
    CREATE TABLE del(d);
    CREATE VIRTUAL TABLE e2 USING echo(del);
  }
  db close
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    DROP TABLE del;
  }
  catchsql {
    SELECT * FROM e2;
  }
} {1 {vtable constructor failed: e2}}
do_test vtab1.10-2 {
  set rc [catch {
    set ptr [sqlite3_connection_pointer db]
    sqlite3_declare_vtab $ptr {CREATE TABLE abc(a, b, c)}
  } msg]
  list $rc $msg
} {1 {library routine called out of sequence}}
do_test vtab1.10-3 {
  set ::echo_module_begin_fail r
  catchsql {
    INSERT INTO e VALUES(1, 2, 3);
  }
} {1 {SQL logic error or missing database}}
do_test vtab1.10-4 {
  catch {execsql {
    EXPLAIN SELECT * FROM e WHERE rowid = 2;
    EXPLAIN QUERY PLAN SELECT * FROM e WHERE rowid = 2 ORDER BY rowid;
  }}
} {0}

do_test vtab1.10-5 {
  set echo_module ""
  execsql {
    SELECT * FROM e WHERE rowid||'' MATCH 'pattern';
  }
  set echo_module
} [list \
  xBestIndex {SELECT rowid, * FROM 'r'} \
  xFilter {SELECT rowid, * FROM 'r'}    \
]
proc match_func {args} {return ""}
do_test vtab1.10-6 {
  set echo_module ""
  db function match match_func
  execsql {
    SELECT * FROM e WHERE match('pattern', rowid, 'pattern2');
  }
  set echo_module
} [list \
  xBestIndex {SELECT rowid, * FROM 'r'} \
  xFilter {SELECT rowid, * FROM 'r'}    \
]


# Testing the xFindFunction interface
#
catch {rename ::echo_glob_overload {}}
do_test vtab1.11-1 {
  execsql {
    INSERT INTO r(a,b,c) VALUES(1,'?',99);
    INSERT INTO r(a,b,c) VALUES(2,3,99);
    SELECT a GLOB b FROM e
  }
} {1 0}
proc ::echo_glob_overload {a b} {
 return [list $b $a]
}
do_test vtab1.11-2 {
  execsql {
    SELECT a like 'b' FROM e
  }
} {0 0}
do_test vtab1.11-3 {
  execsql {
    SELECT a glob '2' FROM e
  }
} {{1 2} {2 2}}
do_test vtab1.11-4 {
  execsql {
    SELECT  glob('2',a) FROM e
  }
} {0 1}
do_test vtab1.11-5 {
  execsql {
    SELECT  glob(a,'2') FROM e
  }
} {{2 1} {2 2}}
 
#----------------------------------------------------------------------
# Test the outcome if a constraint is encountered half-way through
# a multi-row INSERT that is inside a transaction
#
do_test vtab1.12-1 {
  execsql {
    CREATE TABLE b(a, b, c);
    CREATE TABLE c(a UNIQUE, b, c);
    INSERT INTO b VALUES(1, 'A', 'B');
    INSERT INTO b VALUES(2, 'C', 'D');
    INSERT INTO b VALUES(3, 'E', 'F');
    INSERT INTO c VALUES(3, 'G', 'H');
    CREATE VIRTUAL TABLE echo_c USING echo(c);
  }
} {}

# First test outside of a transaction.
do_test vtab1.12-2 {
  catchsql { INSERT INTO echo_c SELECT * FROM b; }
} {1 {echo-vtab-error: column a is not unique}}
do_test vtab1.12-2.1 {
  sqlite3_errmsg db
} {echo-vtab-error: column a is not unique}
do_test vtab1.12-3 {
  execsql { SELECT * FROM c }
} {3 G H}

# Now the real test - wrapped in a transaction.
do_test vtab1.12-4 {
  execsql  {BEGIN}
  catchsql { INSERT INTO echo_c SELECT * FROM b; }
} {1 {echo-vtab-error: column a is not unique}}
do_test vtab1.12-5 {
  execsql { SELECT * FROM c }
} {3 G H}
do_test vtab1.12-6 {
  execsql { COMMIT }
  execsql { SELECT * FROM c }
} {3 G H}

# At one point (ticket #2759), a WHERE clause of the form "<column> IS NULL"
# on a virtual table was causing an assert() to fail in the compiler.
#
# "IS NULL" clauses should not be passed through to the virtual table
# implementation. They are handled by SQLite after the vtab returns its
# data.
#
do_test vtab1.13-1 {
  execsql { 
    SELECT * FROM echo_c WHERE a IS NULL 
  }
} {}
do_test vtab1.13-2 {
  execsql { 
    INSERT INTO c VALUES(NULL, 15, 16);
    SELECT * FROM echo_c WHERE a IS NULL 
  }
} {{} 15 16}
do_test vtab1.13-3 {
  execsql { 
    INSERT INTO c VALUES(15, NULL, 16);
    SELECT * FROM echo_c WHERE b IS NULL 
  }
} {15 {} 16}
do_test vtab1.13-3 {
  execsql { 
    SELECT * FROM echo_c WHERE b IS NULL AND a = 15;
  }
} {15 {} 16}


do_test vtab1-14.1 {
  execsql { DELETE FROM c }
  set echo_module ""
  execsql { SELECT * FROM echo_c WHERE rowid IN (1, 2, 3) }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'c'} xFilter {SELECT rowid, * FROM 'c'}]

do_test vtab1-14.2 {
  set echo_module ""
  execsql { SELECT * FROM echo_c WHERE rowid = 1 }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'c' WHERE rowid = ?} xFilter {SELECT rowid, * FROM 'c' WHERE rowid = ?} 1]

do_test vtab1-14.3 {
  set echo_module ""
  execsql { SELECT * FROM echo_c WHERE a = 1 }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'c' WHERE a = ?} xFilter {SELECT rowid, * FROM 'c' WHERE a = ?} 1]

do_test vtab1-14.4 {
  set echo_module ""
  execsql { SELECT * FROM echo_c WHERE a IN (1, 2) }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'c'} xFilter {SELECT rowid, * FROM 'c'}]

do_test vtab1-15.1 {
  execsql {
    CREATE TABLE t1(a, b, c);
    CREATE VIRTUAL TABLE echo_t1 USING echo(t1);
  }
} {}
do_test vtab1-15.2 {
  execsql {
    INSERT INTO echo_t1(rowid) VALUES(45);
    SELECT rowid, * FROM echo_t1;
  }
} {45 {} {} {}}
do_test vtab1-15.3 {
  execsql {
    INSERT INTO echo_t1(rowid) VALUES(NULL);
    SELECT rowid, * FROM echo_t1;
  }
} {45 {} {} {} 46 {} {} {}}
do_test vtab1-15.4 {
  catchsql {
    INSERT INTO echo_t1(rowid) VALUES('new rowid');
  }
} {1 {datatype mismatch}}

# The following tests - vtab1-16.* - are designed to test that setting 
# sqlite3_vtab.zErrMsg variable can be used by the vtab interface to 
# return an error message to the user.
# 
do_test vtab1-16.1 {
  execsql {
    CREATE TABLE t2(a PRIMARY KEY, b, c);
    INSERT INTO t2 VALUES(1, 2, 3);
    INSERT INTO t2 VALUES(4, 5, 6);
    CREATE VIRTUAL TABLE echo_t2 USING echo(t2);
  }
} {}

set tn 2
foreach method [list \
    xBestIndex       \
    xOpen            \
    xFilter          \
    xNext            \
    xColumn          \
    xRowid           \
] {
  do_test vtab1-16.$tn {
    set echo_module_fail($method,t2) "the $method method has failed"
    catchsql { SELECT rowid, * FROM echo_t2 WHERE a >= 1 }
  } "1 {echo-vtab-error: the $method method has failed}"
  unset echo_module_fail($method,t2)
  incr tn
}

foreach method [list \
  xUpdate            \
  xBegin             \
  xSync              \
] {
  do_test vtab1-16.$tn {
    set echo_module_fail($method,t2) "the $method method has failed"
    catchsql { INSERT INTO echo_t2 VALUES(7, 8, 9) }
  } "1 {echo-vtab-error: the $method method has failed}"
  unset echo_module_fail($method,t2)
  incr tn
}

ifcapable altertable {
  do_test vtab1-16.$tn {
    set echo_module_fail(xRename,t2) "the xRename method has failed"
    catchsql { ALTER TABLE echo_t2 RENAME TO another_name }
  } "1 {echo-vtab-error: the xRename method has failed}"
  unset echo_module_fail(xRename,t2)
  incr tn
}

unset -nocomplain echo_module_begin_fail
finish_test

Added test/vtab2.test.

















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# 2006 June 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# $Id: vtab2.test,v 1.9 2008/10/13 10:37:50 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab||!schema_pragmas {
  finish_test
  return
}

register_schema_module [sqlite3_connection_pointer db]
do_test vtab2-1.1 {
  execsql {
    CREATE VIRTUAL TABLE schema USING schema;
    SELECT * FROM schema;
  }
} [list \
  main schema 0 database   {} 0 {} 0 \
  main schema 1 tablename  {} 0 {} 0 \
  main schema 2 cid        {} 0 {} 0 \
  main schema 3 name       {} 0 {} 0 \
  main schema 4 type       {} 0 {} 0 \
  main schema 5 not_null   {} 0 {} 0 \
  main schema 6 dflt_value {} 0 {} 0 \
  main schema 7 pk         {} 0 {} 0 \
]

# See ticket #2230.
#
do_test vtab2-1.2 {
  execsql {
    SELECT length(tablename) FROM schema GROUP by tablename;
  }
} {6}
do_test vtab2-1.3 {
  execsql {
    SELECT tablename FROM schema GROUP by length(tablename);
  }
} {schema}
do_test vtab2-1.4 {
  execsql {
    SELECT length(tablename) FROM schema GROUP by length(tablename);
  }
} {6}

register_tclvar_module [sqlite3_connection_pointer db]
do_test vtab2-2.1 {
  set ::abc 123
  execsql {
    CREATE VIRTUAL TABLE vars USING tclvar;
    SELECT * FROM vars WHERE name='abc';
  }
} [list abc "" 123]
do_test vtab2-2.2 {
  set A(1) 1
  set A(2) 4
  set A(3) 9
  execsql {
    SELECT * FROM vars WHERE name='A';
  }
} [list A 1 1 A 2 4 A 3 9]
unset -nocomplain result
unset -nocomplain var
set result {}
foreach var [lsort [info vars tcl_*]] {
  catch {lappend result $var [set $var]}
}
do_test vtab2-2.3 {
  execsql {
    SELECT name, value FROM vars
      WHERE name MATCH 'tcl_*' AND arrayname = '' 
      ORDER BY name;
  }
} $result
unset result
unset var

# Ticket #2894.
#
# Make sure we do call Column(), and Rowid() methods of
# a virtual table when that table is in a LEFT JOIN.
#
do_test vtab2-3.1 {
  execsql {
    SELECT * FROM schema WHERE dflt_value IS NULL LIMIT 1
  }
} {main schema 0 database {} 0 {} 0}
do_test vtab2-3.2 {
  execsql {
    SELECT *, b.rowid
      FROM schema a LEFT JOIN schema b ON a.dflt_value=b.dflt_value
     WHERE a.rowid=1
  }
} {main schema 0 database {} 0 {} 0 {} {} {} {} {} {} {} {} {}}

do_test vtab2-4.1 {
  execsql {
    BEGIN TRANSACTION;
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c));
    CREATE TABLE fkey(
      to_tbl,
      to_col
    );
    INSERT INTO "fkey" VALUES('t1',NULL);
    COMMIT;
  }
} {}
do_test vtab2-4.2 {
  execsql { CREATE VIRTUAL TABLE v_col USING schema }
} {}
do_test vtab2-4.3 {
  execsql { SELECT name FROM v_col WHERE tablename = 't1' AND pk }
} {a}
do_test vtab2-4.4 {
  execsql {
    UPDATE fkey 
    SET to_col = (SELECT name FROM v_col WHERE tablename = 't1' AND pk);
  }
} {}
do_test vtab2-4.5 {
  execsql { SELECT * FROM fkey }
} {t1 a}

finish_test

Added test/vtab3.test.

























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# 2006 June 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is the authorisation callback and virtual tables.
#
# $Id: vtab3.test,v 1.3 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab||!auth {
  finish_test
  return
}

set ::auth_fail 0
set ::auth_log [list]
set ::auth_filter [list SQLITE_READ SQLITE_UPDATE SQLITE_SELECT SQLITE_PRAGMA]

proc auth {code arg1 arg2 arg3 arg4} {
  if {[lsearch $::auth_filter $code]>-1} {
    return SQLITE_OK
  }
  lappend ::auth_log $code $arg1 $arg2 $arg3 $arg4
  incr ::auth_fail -1
  if {$::auth_fail == 0} {
    return SQLITE_DENY
  }
  return SQLITE_OK
}

do_test vtab3-1.1 {
  execsql {
    CREATE TABLE elephant(
      name VARCHAR(32), 
      color VARCHAR(16), 
      age INTEGER, 
      UNIQUE(name, color)
    );
  }
} {}


do_test vtab3-1.2 {
  register_echo_module [sqlite3_connection_pointer db]
  db authorizer ::auth
  execsql {
    CREATE VIRTUAL TABLE pachyderm USING echo(elephant);
  }
  set ::auth_log
} [list \
  SQLITE_INSERT        sqlite_master {}   main {} \
  SQLITE_CREATE_VTABLE pachyderm     echo main {} \
]

do_test vtab3-1.3 {
  set ::auth_log [list]
  execsql {
    DROP TABLE pachyderm;
  }
  set ::auth_log
} [list \
  SQLITE_DELETE        sqlite_master {}   main {} \
  SQLITE_DROP_VTABLE   pachyderm     echo main {} \
  SQLITE_DELETE        pachyderm     {}   main {} \
  SQLITE_DELETE        sqlite_master {}   main {} \
]

do_test vtab3-1.4 {
  set ::auth_fail 1
  catchsql {
    CREATE VIRTUAL TABLE pachyderm USING echo(elephant);
  }
} {1 {not authorized}}
do_test vtab3-1.5 {
  execsql {
    SELECT name FROM sqlite_master WHERE type = 'table';
  }
} {elephant}

do_test vtab3-1.5 {
  set ::auth_fail 2
  catchsql {
    CREATE VIRTUAL TABLE pachyderm USING echo(elephant);
  }
} {1 {not authorized}}
do_test vtab3-1.6 {
  execsql {
    SELECT name FROM sqlite_master WHERE type = 'table';
  }
} {elephant}

do_test vtab3-1.5 {
  set ::auth_fail 3
  catchsql {
    CREATE VIRTUAL TABLE pachyderm USING echo(elephant);
  }
} {0 {}}
do_test vtab3-1.6 {
  execsql {
    SELECT name FROM sqlite_master WHERE type = 'table';
  }
} {elephant pachyderm}

foreach i [list 1 2 3 4] {
  set ::auth_fail $i
  do_test vtab3-1.7.$i.1 {
    set rc [catch {
      execsql {DROP TABLE pachyderm;}
    } msg]
    if {$msg eq "authorization denied"} {set msg "not authorized"}
    list $rc $msg
  } {1 {not authorized}}
  do_test vtab3-1.7.$i.2 {
    execsql {
      SELECT name FROM sqlite_master WHERE type = 'table';
    }
  } {elephant pachyderm}
}
do_test vtab3-1.8.1 {
  set ::auth_fail 0
  catchsql {
    DROP TABLE pachyderm;
  }
} {0 {}}
do_test vtab3-1.8.2 {
  execsql {
    SELECT name FROM sqlite_master WHERE type = 'table';
  }
} {elephant}

finish_test

Added test/vtab4.test.



































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# 2006 June 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The
# focus is on testing the following virtual table methods:
#
#     xBegin
#     xSync
#     xCommit
#     xRollback
#
# $Id: vtab4.test,v 1.3 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

unset -nocomplain echo_module
unset -nocomplain echo_module_sync_fail

ifcapable !vtab {
  finish_test
  return
}

# Register the echo module
db cache size 0
register_echo_module [sqlite3_connection_pointer db]

do_test vtab4-1.1 {
  execsql {
    CREATE TABLE treal(a PRIMARY KEY, b, c);
    CREATE VIRTUAL TABLE techo USING echo(treal);
  }
} {}

# Test an INSERT, UPDATE and DELETE statement on the virtual table
# in an implicit transaction. Each should result in a single call
# to xBegin, xSync and xCommit.
#
do_test vtab4-1.2 {
  set echo_module [list]
  execsql {
    INSERT INTO techo VALUES(1, 2, 3);
  }
  set echo_module
} {xBegin echo(treal) xSync echo(treal) xCommit echo(treal)}
do_test vtab4-1.3 {
  set echo_module [list]
  execsql {
    UPDATE techo SET a = 2;
  }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal'} \
        xBegin     echo(treal)                    \
        xFilter    {SELECT rowid, * FROM 'treal'} \
        xSync      echo(treal)                    \
        xCommit    echo(treal)                    \
]
do_test vtab4-1.4 {
  set echo_module [list]
  execsql {
    DELETE FROM techo;
  }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal'} \
        xBegin     echo(treal)                    \
        xFilter    {SELECT rowid, * FROM 'treal'} \
        xSync      echo(treal)                    \
        xCommit    echo(treal)                    \
]

# Ensure xBegin is not called more than once in a single transaction.
#
do_test vtab4-2.1 {
  set echo_module [list]
  execsql {
    BEGIN;
    INSERT INTO techo VALUES(1, 2, 3);
    INSERT INTO techo VALUES(4, 5, 6);
    INSERT INTO techo VALUES(7, 8, 9);
    COMMIT;
  }
  set echo_module
} {xBegin echo(treal) xSync echo(treal) xCommit echo(treal)}

# Try a transaction with two virtual tables.
#
do_test vtab4-2.2 {
  execsql {
    CREATE TABLE sreal(a, b, c UNIQUE);
    CREATE VIRTUAL TABLE secho USING echo(sreal);
  }
  set echo_module [list]
  execsql {
    BEGIN;
    INSERT INTO secho SELECT * FROM techo;
    DELETE FROM techo;
    COMMIT;
  }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'treal'} \
        xBegin     echo(sreal)                    \
        xFilter    {SELECT rowid, * FROM 'treal'} \
        xBestIndex {SELECT rowid, * FROM 'treal'} \
        xBegin     echo(treal)                    \
        xFilter    {SELECT rowid, * FROM 'treal'} \
        xSync   echo(sreal)                       \
        xSync   echo(treal)                       \
        xCommit echo(sreal)                       \
        xCommit echo(treal)                       \
]
do_test vtab4-2.3 {
  execsql {
    SELECT * FROM secho;
  }
} {1 2 3 4 5 6 7 8 9}
do_test vtab4-2.4 {
  execsql {
    SELECT * FROM techo;
  }
} {}

# Try an explicit ROLLBACK on a transaction with two open virtual tables.
do_test vtab4-2.5 {
  set echo_module [list]
  execsql {
    BEGIN;
    INSERT INTO techo SELECT * FROM secho;
    DELETE FROM secho;
    ROLLBACK;
  }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'sreal'} \
        xBegin     echo(treal)                    \
        xFilter    {SELECT rowid, * FROM 'sreal'} \
        xBestIndex {SELECT rowid, * FROM 'sreal'} \
        xBegin     echo(sreal)                    \
        xFilter    {SELECT rowid, * FROM 'sreal'} \
        xRollback  echo(treal)                    \
        xRollback  echo(sreal)                    \
]
do_test vtab4-2.6 {
  execsql {
    SELECT * FROM secho;
  }
} {1 2 3 4 5 6 7 8 9}
do_test vtab4-2.7 {
  execsql {
    SELECT * FROM techo;
  }
} {}

do_test vtab4-3.1 {
  set echo_module [list]
  set echo_module_sync_fail treal
  catchsql {
    INSERT INTO techo VALUES(1, 2, 3);
  }
} {1 {unknown error}}
do_test vtab4-3.2 {
  set echo_module
} {xBegin echo(treal) xSync echo(treal) xRollback echo(treal)}

do_test vtab4-3.3 {
  set echo_module [list]
  set echo_module_sync_fail sreal
  catchsql {
    BEGIN;
    INSERT INTO techo SELECT * FROM secho;
    DELETE FROM secho;
    COMMIT;
  }
  set echo_module
} [list xBestIndex {SELECT rowid, * FROM 'sreal'} \
        xBegin     echo(treal)                    \
        xFilter    {SELECT rowid, * FROM 'sreal'} \
        xBestIndex {SELECT rowid, * FROM 'sreal'} \
        xBegin     echo(sreal)                    \
        xFilter    {SELECT rowid, * FROM 'sreal'} \
        xSync      echo(treal)                    \
        xSync      echo(sreal)                    \
        xRollback  echo(treal)                    \
        xRollback  echo(sreal)                    \
]

finish_test

Added test/vtab5.test.





















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# 2006 June 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# $Id: vtab5.test,v 1.8 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

# The following tests - vtab5-1.* - ensure that an INSERT, DELETE or UPDATE
# statement can be executed immediately after a CREATE or schema reload. The
# point here is testing that the parser always calls xConnect() before the
# schema of a virtual table is used.
#
register_echo_module [sqlite3_connection_pointer db]
do_test vtab5-1.1 {
  execsql {
    CREATE TABLE treal(a VARCHAR(16), b INTEGER, c FLOAT);
    INSERT INTO treal VALUES('a', 'b', 'c');
    CREATE VIRTUAL TABLE techo USING echo(treal);
  }
} {}
do_test vtab5.1.2 {
  execsql {
    SELECT * FROM techo;
  }
} {a b c}
do_test vtab5.1.3 {
  db close
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    INSERT INTO techo VALUES('c', 'd', 'e');
    SELECT * FROM techo;
  }
} {a b c c d e}
do_test vtab5.1.4 {
  db close
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    UPDATE techo SET a = 10;
    SELECT * FROM techo;
  }
} {10 b c 10 d e}
do_test vtab5.1.5 {
  db close
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    DELETE FROM techo WHERE b > 'c';
    SELECT * FROM techo;
  }
} {10 b c}
do_test vtab5.1.X {
  execsql {
    DROP TABLE techo;
    DROP TABLE treal;
  }
} {}

# The following tests - vtab5-2.* - ensure that collation sequences
# assigned to virtual table columns via the "CREATE TABLE" statement 
# passed to sqlite3_declare_vtab() are used correctly.
#
do_test vtab5.2.1 {
  execsql {
    CREATE TABLE strings(str COLLATE NOCASE);
    INSERT INTO strings VALUES('abc1');
    INSERT INTO strings VALUES('Abc3');
    INSERT INTO strings VALUES('ABc2');
    INSERT INTO strings VALUES('aBc4');
    SELECT str FROM strings ORDER BY 1;
  }
} {abc1 ABc2 Abc3 aBc4}
do_test vtab5.2.2 {
  execsql {
    CREATE VIRTUAL TABLE echo_strings USING echo(strings);
    SELECT str FROM echo_strings ORDER BY 1;
  }
} {abc1 ABc2 Abc3 aBc4}
do_test vtab5.2.3 {
  execsql {
    SELECT str||'' FROM echo_strings ORDER BY 1;
  }
} {ABc2 Abc3 aBc4 abc1}

# Test that it is impossible to create a triggger on a virtual table.
#
ifcapable trigger {
  do_test vtab5.3.1 {
    catchsql {
      CREATE TRIGGER trig INSTEAD OF INSERT ON echo_strings BEGIN
        SELECT 1, 2, 3;
      END;
    }
  } {1 {cannot create triggers on virtual tables}}
  do_test vtab5.3.2 {
    catchsql {
      CREATE TRIGGER trig AFTER INSERT ON echo_strings BEGIN
        SELECT 1, 2, 3;
      END;
    }
  } {1 {cannot create triggers on virtual tables}}
  do_test vtab5.3.2 {
    catchsql {
      CREATE TRIGGER trig BEFORE INSERT ON echo_strings BEGIN
        SELECT 1, 2, 3;
      END;
    }
  } {1 {cannot create triggers on virtual tables}}
}

# Test that it is impossible to create an index on a virtual table.
#
do_test vtab5.4.1 {
  catchsql {
    CREATE INDEX echo_strings_i ON echo_strings(str);
  }
} {1 {virtual tables may not be indexed}}

# Test that it is impossible to add a column to a virtual table.
#
ifcapable altertable {
  do_test vtab5.4.2 {
    catchsql {
      ALTER TABLE echo_strings ADD COLUMN col2;
    }
  } {1 {virtual tables may not be altered}}
}

# Test that it is impossible to rename a virtual table.
# UPDATE: It is now possible.
#
# do_test vtab5.4.3 {
#   catchsql {
#     ALTER TABLE echo_strings RENAME TO echo_strings2;
#   }
# } {1 {virtual tables may not be altered}}

finish_test

Added test/vtab6.test.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# 2002 May 24
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests for joins, including outer joins involving
# virtual tables. The test cases in this file are copied from the file
# join.test, and some of the comments still reflect that.
#
# $Id: vtab6.test,v 1.5 2009/07/01 16:12:08 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

register_echo_module [sqlite3_connection_pointer db]

execsql {
  CREATE TABLE real_t1(a,b,c);
  CREATE TABLE real_t2(b,c,d);
  CREATE TABLE real_t3(c,d,e);
  CREATE TABLE real_t4(d,e,f);
  CREATE TABLE real_t5(a INTEGER PRIMARY KEY);
  CREATE TABLE real_t6(a INTEGER);
  CREATE TABLE real_t7 (x, y);
  CREATE TABLE real_t8 (a integer primary key, b);
  CREATE TABLE real_t9(a INTEGER PRIMARY KEY, b);
  CREATE TABLE real_t10(x INTEGER PRIMARY KEY, y);
  CREATE TABLE real_t11(p INTEGER PRIMARY KEY, q);
  CREATE TABLE real_t12(a,b);
  CREATE TABLE real_t13(b,c);
  CREATE TABLE real_t21(a,b,c);
  CREATE TABLE real_t22(p,q);
}
foreach t [list t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t21 t22] {
  execsql "CREATE VIRTUAL TABLE $t USING echo(real_$t)"
}

do_test vtab6-1.1 {
  execsql {
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(2,3,4);
    INSERT INTO t1 VALUES(3,4,5);
    SELECT * FROM t1;
  }  
} {1 2 3 2 3 4 3 4 5}
do_test vtab6-1.2 {
  execsql {
    INSERT INTO t2 VALUES(1,2,3);
    INSERT INTO t2 VALUES(2,3,4);
    INSERT INTO t2 VALUES(3,4,5);
    SELECT * FROM t2;
  }  
} {1 2 3 2 3 4 3 4 5}

do_test vtab6-1.3 {
  execsql2 {
    SELECT * FROM t1 NATURAL JOIN t2;
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test vtab6-1.3.1 {
  execsql2 {
    SELECT * FROM t2 NATURAL JOIN t1;
  }
} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2}
do_test vtab6-1.3.2 {
  execsql2 {
    SELECT * FROM t2 AS x NATURAL JOIN t1;
  }
} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2}
do_test vtab6-1.3.3 {
  execsql2 {
    SELECT * FROM t2 NATURAL JOIN t1 AS y;
  }
} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2}
do_test vtab6-1.3.4 {
  execsql {
    SELECT b FROM t1 NATURAL JOIN t2;
  }
} {2 3}
do_test vtab6-1.4.1 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test vtab6-1.4.2 {
  execsql2 {
    SELECT * FROM t1 AS x INNER JOIN t2 USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test vtab6-1.4.3 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 AS y USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test vtab6-1.4.4 {
  execsql2 {
    SELECT * FROM t1 AS x INNER JOIN t2 AS y USING(b,c);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}
do_test vtab6-1.4.5 {
  execsql {
    SELECT b FROM t1 JOIN t2 USING(b);
  }
} {2 3}
do_test vtab6-1.5 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(b);
  }
} {a 1 b 2 c 3 c 3 d 4 a 2 b 3 c 4 c 4 d 5}
do_test vtab6-1.6 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(c);
  }
} {a 1 b 2 c 3 b 2 d 4 a 2 b 3 c 4 b 3 d 5}
do_test vtab6-1.7 {
  execsql2 {
    SELECT * FROM t1 INNER JOIN t2 USING(c,b);
  }
} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5}

do_test vtab6-1.8 {
  execsql {
    SELECT * FROM t1 NATURAL CROSS JOIN t2;
  }
} {1 2 3 4 2 3 4 5}
do_test vtab6-1.9 {
  execsql {
    SELECT * FROM t1 CROSS JOIN t2 USING(b,c);
  }
} {1 2 3 4 2 3 4 5}
do_test vtab6-1.10 {
  execsql {
    SELECT * FROM t1 NATURAL INNER JOIN t2;
  }
} {1 2 3 4 2 3 4 5}
do_test vtab6-1.11 {
  execsql {
    SELECT * FROM t1 INNER JOIN t2 USING(b,c);
  }
} {1 2 3 4 2 3 4 5}
do_test vtab6-1.12 {
  execsql {
    SELECT * FROM t1 natural inner join t2;
  }
} {1 2 3 4 2 3 4 5}

ifcapable subquery {
  do_test vtab6-1.13 {
    execsql2 {
      SELECT * FROM t1 NATURAL JOIN 
        (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as t3
    }
  } {a 1 b 2 c 3 d 4 e 5}
  do_test vtab6-1.14 {
    execsql2 {
      SELECT * FROM (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as 'tx'
          NATURAL JOIN t1
    }
  } {c 3 d 4 e 5 a 1 b 2}
}

do_test vtab6-1.15 {
  execsql {
    INSERT INTO t3 VALUES(2,3,4);
    INSERT INTO t3 VALUES(3,4,5);
    INSERT INTO t3 VALUES(4,5,6);
    SELECT * FROM t3;
  }  
} {2 3 4 3 4 5 4 5 6}
do_test vtab6-1.16 {
  execsql {
    SELECT * FROM t1 natural join t2 natural join t3;
  }
} {1 2 3 4 5 2 3 4 5 6}
do_test vtab6-1.17 {
  execsql2 {
    SELECT * FROM t1 natural join t2 natural join t3;
  }
} {a 1 b 2 c 3 d 4 e 5 a 2 b 3 c 4 d 5 e 6}
do_test vtab6-1.18 {
  execsql {
    INSERT INTO t4 VALUES(2,3,4);
    INSERT INTO t4 VALUES(3,4,5);
    INSERT INTO t4 VALUES(4,5,6);
    SELECT * FROM t4;
  }  
} {2 3 4 3 4 5 4 5 6}
do_test vtab6-1.19.1 {
  execsql {
    SELECT * FROM t1 natural join t2 natural join t4;
  }
} {1 2 3 4 5 6}
do_test vtab6-1.19.2 {
  execsql2 {
    SELECT * FROM t1 natural join t2 natural join t4;
  }
} {a 1 b 2 c 3 d 4 e 5 f 6}
do_test vtab6-1.20 {
  execsql {
    SELECT * FROM t1 natural join t2 natural join t3 WHERE t1.a=1
  }
} {1 2 3 4 5}

do_test vtab6-2.1 {
  execsql {
    SELECT * FROM t1 NATURAL LEFT JOIN t2;
  }
} {1 2 3 4 2 3 4 5 3 4 5 {}}
do_test vtab6-2.2 {
  execsql {
    SELECT * FROM t2 NATURAL LEFT OUTER JOIN t1;
  }
} {1 2 3 {} 2 3 4 1 3 4 5 2}
do_test vtab6-2.3 {
  catchsql {
    SELECT * FROM t1 NATURAL RIGHT OUTER JOIN t2;
  }
} {1 {RIGHT and FULL OUTER JOINs are not currently supported}}
do_test vtab6-2.4 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d
  }
} {1 2 3 {} {} {} 2 3 4 {} {} {} 3 4 5 1 2 3}
do_test vtab6-2.5 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t1.a>1
  }
} {2 3 4 {} {} {} 3 4 5 1 2 3}
do_test vtab6-2.6 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t2.b IS NULL OR t2.b>1
  }
} {1 2 3 {} {} {} 2 3 4 {} {} {}}

do_test vtab6-3.1 {
  catchsql {
    SELECT * FROM t1 NATURAL JOIN t2 ON t1.a=t2.b;
  }
} {1 {a NATURAL join may not have an ON or USING clause}}
do_test vtab6-3.2 {
  catchsql {
    SELECT * FROM t1 NATURAL JOIN t2 USING(b);
  }
} {1 {a NATURAL join may not have an ON or USING clause}}
do_test vtab6-3.3 {
  catchsql {
    SELECT * FROM t1 JOIN t2 ON t1.a=t2.b USING(b);
  }
} {1 {cannot have both ON and USING clauses in the same join}}
do_test vtab6-3.4 {
  catchsql {
    SELECT * FROM t1 JOIN t2 USING(a);
  }
} {1 {cannot join using column a - column not present in both tables}}
do_test vtab6-3.5 {
  catchsql { SELECT * FROM t1 USING(a) }
} {1 {a JOIN clause is required before USING}}
do_test vtab6-3.6 {
  catchsql {
    SELECT * FROM t1 JOIN t2 ON t3.a=t2.b;
  }
} {1 {no such column: t3.a}}
do_test vtab6-3.7 {
  catchsql {
    SELECT * FROM t1 INNER OUTER JOIN t2;
  }
} {1 {unknown or unsupported join type: INNER OUTER}}
do_test vtab6-3.7 {
  catchsql {
    SELECT * FROM t1 LEFT BOGUS JOIN t2;
  }
} {1 {unknown or unsupported join type: LEFT BOGUS}}

do_test vtab6-4.1 {
  execsql {
    BEGIN;
    INSERT INTO t6 VALUES(NULL);
    INSERT INTO t6 VALUES(NULL);
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    INSERT INTO t6 SELECT * FROM t6;
    COMMIT;
  }
  execsql {
    SELECT * FROM t6 NATURAL JOIN t5;
  }
} {}
do_test vtab6-4.2 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a<t5.a;
  }
} {}
do_test vtab6-4.3 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a>t5.a;
  }
} {}
do_test vtab6-4.4 {
  execsql {
    UPDATE t6 SET a='xyz';
    SELECT * FROM t6 NATURAL JOIN t5;
  }
} {}
do_test vtab6-4.6 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a<t5.a;
  }
} {}
do_test vtab6-4.7 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a>t5.a;
  }
} {}
do_test vtab6-4.8 {
  execsql {
    UPDATE t6 SET a=1;
    SELECT * FROM t6 NATURAL JOIN t5;
  }
} {}
do_test vtab6-4.9 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a<t5.a;
  }
} {}
do_test vtab6-4.10 {
  execsql {
    SELECT * FROM t6, t5 WHERE t6.a>t5.a;
  }
} {}

# A test for ticket #247.
#
do_test vtab6-7.1 {
  execsql {
    INSERT INTO t7 VALUES ("pa1", 1);
    INSERT INTO t7 VALUES ("pa2", NULL);
    INSERT INTO t7 VALUES ("pa3", NULL);
    INSERT INTO t7 VALUES ("pa4", 2);
    INSERT INTO t7 VALUES ("pa30", 131);
    INSERT INTO t7 VALUES ("pa31", 130);
    INSERT INTO t7 VALUES ("pa28", NULL);

    INSERT INTO t8 VALUES (1, "pa1");
    INSERT INTO t8 VALUES (2, "pa4");
    INSERT INTO t8 VALUES (3, NULL);
    INSERT INTO t8 VALUES (4, NULL);
    INSERT INTO t8 VALUES (130, "pa31");
    INSERT INTO t8 VALUES (131, "pa30");

    SELECT coalesce(t8.a,999) from t7 LEFT JOIN t8 on y=a;
  }
} {1 999 999 2 131 130 999}

# Make sure a left join where the right table is really a view that
# is itself a join works right.  Ticket #306.
#
ifcapable view {
do_test vtab6-8.1 {
  execsql {
    BEGIN;
    INSERT INTO t9 VALUES(1,11);
    INSERT INTO t9 VALUES(2,22);
    INSERT INTO t10 VALUES(1,2);
    INSERT INTO t10 VALUES(3,3);    
    INSERT INTO t11 VALUES(2,111);
    INSERT INTO t11 VALUES(3,333);    
    CREATE VIEW v10_11 AS SELECT x, q FROM t10, t11 WHERE t10.y=t11.p;
    COMMIT;
    SELECT * FROM t9 LEFT JOIN v10_11 ON( a=x );
  }
} {1 11 1 111 2 22 {} {}}
ifcapable subquery {
  do_test vtab6-8.2 {
    execsql {
      SELECT * FROM t9 LEFT JOIN (SELECT x, q FROM t10, t11 WHERE t10.y=t11.p)
           ON( a=x);
    }
  } {1 11 1 111 2 22 {} {}}
}
do_test vtab6-8.3 {
  execsql {
    SELECT * FROM v10_11 LEFT JOIN t9 ON( a=x );
  }
} {1 111 1 11 3 333 {} {}}
} ;# ifcapable view

# Ticket #350 describes a scenario where LEFT OUTER JOIN does not
# function correctly if the right table in the join is really
# subquery.
#
# To test the problem, we generate the same LEFT OUTER JOIN in two
# separate selects but with on using a subquery and the other calling
# the table directly.  Then connect the two SELECTs using an EXCEPT.
# Both queries should generate the same results so the answer should
# be an empty set.
#
ifcapable compound {
do_test vtab6-9.1 {
  execsql {
    BEGIN;
    INSERT INTO t12 VALUES(1,11);
    INSERT INTO t12 VALUES(2,22);
    INSERT INTO t13 VALUES(22,222);
    COMMIT;
  }
} {}

ifcapable subquery {
  do_test vtab6-9.1.1 {
    execsql {
      SELECT * FROM t12 NATURAL LEFT JOIN t13
      EXCEPT
      SELECT * FROM t12 NATURAL LEFT JOIN (SELECT * FROM t13 WHERE b>0);
    }
  } {}
}
ifcapable view {
  do_test vtab6-9.2 {
    execsql {
      CREATE VIEW v13 AS SELECT * FROM t13 WHERE b>0;
      SELECT * FROM t12 NATURAL LEFT JOIN t13
        EXCEPT
        SELECT * FROM t12 NATURAL LEFT JOIN v13;
    }
  } {}
} ;# ifcapable view
} ;# ifcapable compound

ifcapable subquery {
do_test vtab6-10.1 {
  execsql {
    CREATE INDEX i22 ON real_t22(q);
    SELECT a FROM t21 LEFT JOIN t22 ON b=p WHERE q=
       (SELECT max(m.q) FROM t22 m JOIN t21 n ON n.b=m.p WHERE n.c=1);
  }  
} {}
} ;# ifcapable subquery

do_test vtab6-11.1.0 {
  execsql {
    CREATE TABLE ab_r(a, b);
    CREATE TABLE bc_r(b, c);

    CREATE VIRTUAL TABLE ab USING echo(ab_r); 
    CREATE VIRTUAL TABLE bc USING echo(bc_r); 

    INSERT INTO ab VALUES(1, 2);
    INSERT INTO bc VALUES(2, 3);
  }
} {}

do_test vtab6-11.1.1 {
  execsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 2 3}
do_test vtab6-11.1.2 {
  execsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 2 3}

set ::echo_module_cost 1.0

do_test vtab6-11.1.3 {
  execsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 2 3}
do_test vtab6-11.1.4 {
  execsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 2 3}


do_test vtab6-11.2.0 {
  execsql {
    CREATE INDEX ab_i ON ab_r(b);
    CREATE INDEX bc_i ON bc_r(b);
  }
} {}

unset ::echo_module_cost

do_test vtab6-11.2.1 {
  execsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 2 3}
do_test vtab6-11.2.2 {
  execsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 2 3}

set ::echo_module_cost 1.0

do_test vtab6-11.2.3 {
  execsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 2 3}
do_test vtab6-11.2.4 {
  execsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 2 3}

unset ::echo_module_cost
db close
sqlite3 db test.db
register_echo_module [sqlite3_connection_pointer db]

do_test vtab6-11.3.1 {
  execsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 2 3}

do_test vtab6-11.3.2 {
  execsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 2 3}

set ::echo_module_cost 1.0

do_test vtab6-11.3.3 {
  execsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 2 3}
do_test vtab6-11.3.4 {
  execsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 2 3}

unset ::echo_module_cost

set ::echo_module_ignore_usable 1
db cache flush

do_test vtab6-11.4.1 {
  catchsql {
    SELECT a, b, c FROM ab NATURAL JOIN bc;
  }
} {1 {table bc: xBestIndex returned an invalid plan}}
do_test vtab6-11.4.2 {
  catchsql {
    SELECT a, b, c FROM bc NATURAL JOIN ab;
  }
} {1 {table ab: xBestIndex returned an invalid plan}}

unset ::echo_module_ignore_usable

finish_test

Added test/vtab7.test.































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# 2006 July 25
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# of this test is reading and writing to the database from within a
# virtual table xSync() callback.
#
# $Id: vtab7.test,v 1.4 2007/12/04 16:54:53 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

# Register the echo module. Code inside the echo module appends elements
# to the global tcl list variable ::echo_module whenever SQLite invokes
# certain module callbacks. This includes the xSync(), xCommit() and 
# xRollback() callbacks. For each of these callback, two elements are
# appended to ::echo_module, as follows:
#
#     Module method        Elements appended to ::echo_module
#     -------------------------------------------------------
#     xSync()              xSync echo($tablename)
#     xCommit()            xCommit echo($tablename)
#     xRollback()          xRollback echo($tablename)
#     -------------------------------------------------------
#
# In each case, $tablename is replaced by the name of the real table (not
# the echo table). By setting up a tcl trace on the ::echo_module variable,
# code in this file arranges for a Tcl script to be executed from within
# the echo module xSync() callback.
#
register_echo_module [sqlite3_connection_pointer db]
trace add variable ::echo_module write echo_module_trace

# This Tcl proc is invoked whenever the ::echo_module variable is written.
#
proc echo_module_trace {args} {
  # Filter out writes to ::echo_module that are not xSync, xCommit or 
  # xRollback callbacks.
  if {[llength $::echo_module] < 2} return
  set x [lindex $::echo_module end-1]
  if {$x ne "xSync" && $x ne "xCommit" && $x ne "xRollback"} return

  regexp {^echo.(.*).$} [lindex $::echo_module end] dummy tablename
  # puts "Ladies and gentlemen, an $x on $tablename!"

  if {[info exists ::callbacks($x,$tablename)]} {
    eval $::callbacks($x,$tablename)
  }
}

# The following tests, vtab7-1.*, test that the trace callback on 
# ::echo_module is providing the expected tcl callbacks.
do_test vtab7-1.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
    CREATE VIRTUAL TABLE abc2 USING echo(abc);
  }
} {}

do_test vtab7-1.2 {
  set ::callbacks(xSync,abc) {incr ::counter}
  set ::counter 0
  execsql {
    INSERT INTO abc2 VALUES(1, 2, 3);
  }
  set ::counter
} {1}

# Write to an existing database table from within an xSync callback.
do_test vtab7-2.1 {
  set ::callbacks(xSync,abc) {
    execsql {INSERT INTO log VALUES('xSync');}
  }
  execsql {
    CREATE TABLE log(msg);
    INSERT INTO abc2 VALUES(4, 5, 6);
    SELECT * FROM log;
  }
} {xSync}
do_test vtab7-2.3 {
  execsql {
    INSERT INTO abc2 VALUES(4, 5, 6);
    SELECT * FROM log;
  }
} {xSync xSync}
do_test vtab7-2.4 {
  execsql {
    INSERT INTO abc2 VALUES(4, 5, 6);
    SELECT * FROM log;
  }
} {xSync xSync xSync}

# Create a database table from within xSync callback.
do_test vtab7-2.5 {
  set ::callbacks(xSync,abc) {
    execsql { CREATE TABLE newtab(d, e, f); }
  }
  execsql {
    INSERT INTO abc2 VALUES(1, 2, 3);
    SELECT name FROM sqlite_master ORDER BY name;
  }
} {abc abc2 log newtab}

# Drop a database table from within xSync callback.
# This is not allowed.  Tables cannot be dropped while
# any other statement is active.
#
do_test vtab7-2.6 {
  set ::callbacks(xSync,abc) {
    set ::rc [catchsql { DROP TABLE newtab }]
  }
  execsql {
    INSERT INTO abc2 VALUES(1, 2, 3);
    SELECT name FROM sqlite_master ORDER BY name;
  }
} {abc abc2 log newtab}
do_test vtab7-2.6.1 {
  set ::rc
} {1 {database table is locked}}
execsql {DROP TABLE newtab}

# Write to an attached database from xSync().
ifcapable attach {
  do_test vtab7-3.1 {
    file delete -force test2.db
    file delete -force test2.db-journal
    execsql {
      ATTACH 'test2.db' AS db2;
      CREATE TABLE db2.stuff(description, shape, color);
    }
    set ::callbacks(xSync,abc) {
      execsql { INSERT INTO db2.stuff VALUES('abc', 'square', 'green'); }
    }
    execsql {
      INSERT INTO abc2 VALUES(1, 2, 3);
      SELECT * from stuff;
    }
  } {abc square green}
}

# UPDATE: The next test passes, but leaks memory. So leave it out.
#
# The following tests test that writing to the database from within
# the xCommit callback causes a misuse error.
# do_test vtab7-4.1 {
#   unset -nocomplain ::callbacks(xSync,abc)
#   set ::callbacks(xCommit,abc) {
#     execsql { INSERT INTO log VALUES('hello') }
#   }
#   catchsql {
#     INSERT INTO abc2 VALUES(1, 2, 3);
#   }
# } {1 {library routine called out of sequence}}

# These tests, vtab7-4.*, test that an SQLITE_LOCKED error is returned
# if an attempt to write to a virtual module table or create a new 
# virtual table from within an xSync() callback.
do_test vtab7-4.1 {
  execsql {
    CREATE TABLE def(d, e, f);
    CREATE VIRTUAL TABLE def2 USING echo(def);
  }
  set ::callbacks(xSync,abc) {
    set ::error [catchsql { INSERT INTO def2 VALUES(1, 2, 3) }]
  }
  execsql {
    INSERT INTO abc2 VALUES(1, 2, 3);
  }
  set ::error
} {1 {database table is locked}}
do_test vtab7-4.2 {
  set ::callbacks(xSync,abc) {
    set ::error [catchsql { CREATE VIRTUAL TABLE def3 USING echo(def) }]
  }
  execsql {
    INSERT INTO abc2 VALUES(1, 2, 3);
  }
  set ::error
} {1 {database table is locked}}

do_test vtab7-4.3 {
  set ::callbacks(xSync,abc) {
    set ::error [catchsql { DROP TABLE def2 }]
  }
  execsql {
    INSERT INTO abc2 VALUES(1, 2, 3);
    SELECT name FROM sqlite_master ORDER BY name;
  }
  set ::error
} {1 {database table is locked}}

trace remove variable ::echo_module write echo_module_trace
unset -nocomplain ::callbacks

finish_test

Added test/vtab8.test.





























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 2006 August 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file inserting into virtual tables from a SELECT
# statement.
#
# $Id: vtab8.test,v 1.2 2007/03/02 08:12:23 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

register_echo_module [sqlite3_connection_pointer db]

# See ticket #2244
#
do_test vtab1.2244-1 {
  execsql {
    CREATE TABLE t2244(a, b);
    CREATE VIRTUAL TABLE t2244e USING echo(t2244);
    INSERT INTO t2244 VALUES('AA', 'BB');
    INSERT INTO t2244 VALUES('CC', 'DD');
    SELECT rowid, * FROM t2244e;
  }
} {1 AA BB 2 CC DD}
do_test vtab1.2244-2 {
  execsql {
    SELECT * FROM t2244e WHERE rowid = 10;
  }
} {}
do_test vtab1.2244-3 {
  execsql {
    UPDATE t2244e SET a = 'hello world' WHERE 0;
    SELECT rowid, * FROM t2244e;
  }
} {1 AA BB 2 CC DD}

do_test vtab1-2250-2 {
  execsql {
    CREATE TABLE t2250(a, b);
    INSERT INTO t2250 VALUES(10, 20);
    CREATE VIRTUAL TABLE t2250e USING echo(t2250);
    select max(rowid) from t2250;
    select max(rowid) from t2250e;
  }
} {1 1}

# See ticket #2260.
#
do_test vtab1.2260-1 {
  execsql {
    CREATE TABLE t2260a_real(a, b);
    CREATE TABLE t2260b_real(a, b);

    CREATE INDEX i2260 ON t2260a_real(a);
    CREATE INDEX i2260x ON t2260b_real(a);

    CREATE VIRTUAL TABLE t2260a USING echo(t2260a_real);
    CREATE VIRTUAL TABLE t2260b USING echo(t2260b_real);

    SELECT * FROM t2260a, t2260b WHERE t2260a.a = t2260b.a AND t2260a.a > 101;
  }
} {}

unset -nocomplain echo_module_begin_fail
finish_test

Added test/vtab9.test.













































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 2006 August 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file inserting into virtual tables from a SELECT
# statement.
#
# $Id: vtab9.test,v 1.2 2007/04/16 15:06:26 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

do_test vtab9-1.1 {
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    CREATE TABLE t0(a);
    CREATE VIRTUAL TABLE t1 USING echo(t0);
    INSERT INTO t1 SELECT 'hello';
    SELECT rowid, * FROM t1;
  }
} {1 hello}

do_test vtab9-1.2 {
  execsql {
    CREATE TABLE t2(a,b,c);
    CREATE VIRTUAL TABLE t3 USING echo(t2);
    CREATE TABLE d1(a,b,c);
    INSERT INTO d1 VALUES(1,2,3);
    INSERT INTO d1 VALUES('a','b','c');
    INSERT INTO d1 VALUES(NULL,'x',123.456);
    INSERT INTO d1 VALUES(x'6869',123456789,-12345);
    INSERT INTO t3(a,b,c) SELECT * FROM d1;
    SELECT rowid, * FROM t3;
  }
} {1 1 2 3 2 a b c 3 {} x 123.456 4 hi 123456789 -12345}

# do_test vtab9-2.1 {
#   execsql {
#     CREATE TABLE t4(a);
#     CREATE VIRTUAL TABLE t5 USING echo(t4);
#     INSERT INTO t4 VALUES('hello');
#     SELECT rowid, a FROM t5;
#   }
# } {1 hello}
# do_test vtab9-2.2 {
#   execsql {
#     INSERT INTO t5(rowid, a) VALUES(1, 'goodbye');
#   }
# } {1 hello}
# do_test vtab9-2.3 {
#   execsql {
#     REPLACE INTO t5(rowid, a) VALUES(1, 'goodbye');
#     SELECT * FROM t5;
#   }
# } {1 goodbye}

unset -nocomplain echo_module_begin_fail
finish_test

Added test/vtabA.test.













































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# 2007 June 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is 'hidden' virtual table columns.
#
# $Id: vtabA.test,v 1.2 2008/07/12 14:52:21 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

proc get_decltype {table col} {
  set STMT [sqlite3_prepare $::DB "SELECT $col FROM $table" -1 TAIL]
  set decltype [sqlite3_column_decltype $STMT 0]
  sqlite3_finalize $STMT
  set decltype
}

proc get_collist {table} {
  set ret [list]
  db eval "PRAGMA table_info($table)" { lappend ret $name }
  set ret
}

# Register the echo module
register_echo_module [sqlite3_connection_pointer db]

# Create a virtual table with a 'hidden' column (column b).
#
do_test vtabA-1.1 {
  execsql { CREATE TABLE t1(a, b HIDDEN VARCHAR, c INTEGER) }
} {}
do_test vtabA-1.2 {
  execsql { CREATE VIRTUAL TABLE t1e USING echo(t1) }
} {}

# Test that the hidden column is not listed by [PRAGMA table_info].
#
do_test vtabA-1.3 {
  execsql { PRAGMA table_info(t1e) }
} [list              \
  0 a {}      0 {} 0 \
  1 c INTEGER 0 {} 0 \
]

# Test that the hidden column is not require in the default column
# list for an INSERT statement.
#
do_test vtabA-1.4 {
  catchsql {
    INSERT INTO t1e VALUES('value a', 'value c');
  }
} {0 {}}
do_test vtabA-1.5 {
  execsql {
    SELECT a, b, c FROM t1e;
  }
} {{value a} {} {value c}}

do_test vtabA-1.6 {
  execsql {
    SELECT * FROM t1e;
  }
} {{value a} {value c}}

# Test that the expansion of a '*' expression in the result set of
# a SELECT does not include the hidden column.
#
do_test vtabA-1.7 {
  execsql {
    INSERT INTO t1e SELECT * FROM t1e;
  }
} {}
do_test vtabA-1.8 {
  execsql {
    SELECT * FROM t1e;
  }
} {{value a} {value c} {value a} {value c}}

# Test that the declaration type of the hidden column does not include
# the token "HIDDEN".
#
do_test vtabA-1.9 {
  get_decltype t1e b
} {VARCHAR}
do_test vtabA-1.10 {
  get_collist t1e
} {a c}

#----------------------------------------------------------------------
# These tests vtabA-2.* concentrate on testing that the HIDDEN token
# is detected and handled correctly in various declarations.
#
proc analyse_parse {columns decltype_list} {
  db eval { DROP TABLE IF EXISTS t1e; }
  db eval { DROP TABLE IF EXISTS t1; }
  db eval " CREATE TABLE t1 $columns "
  db eval { CREATE VIRTUAL TABLE t1e USING echo(t1) }
  set ret [list [get_collist t1e]]
  foreach c $decltype_list {
    lappend ret [get_decltype t1e $c]
  }
  set ret
}

do_test vtabA-2.1 {
  analyse_parse {(a text, b integer hidden, c hidden)} {a b c}
} {a text integer {}}

do_test vtabA-2.2 {
  analyse_parse {(a hidden   , b integerhidden, c hidden1)} {a b c}
} {{b c} {} integerhidden hidden1}

do_test vtabA-2.3 {
  analyse_parse {(a HiDden, b HIDDEN, c hidden)} {a b c}
} {{} {} {} {}}

do_test vtabA-2.4 {
  analyse_parse {(a whatelse can i hidden test, b HIDDEN hidden)} {a b}
} {{} {whatelse can i test} hidden}

finish_test

Added test/vtabB.test.































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 2008 April 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is is verifying that a virtual table in the
# TEMP database that is created and dropped within a transaction
# is handled correctly.  Ticket #2994.
#
# Also make sure a virtual table on the right-hand side of an IN operator
# is materialized rather than being used directly.  Ticket #3082.
#

#
# $Id: vtabB.test,v 1.2 2008/04/25 12:10:15 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

do_test vtabB-1.1 {
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    CREATE TABLE t1(x);
    BEGIN;
    CREATE VIRTUAL TABLE temp.echo_test1 USING echo(t1);
    DROP TABLE echo_test1;
    ROLLBACK;
  }
} {}

do_test vtabB-2.1 {
  execsql {
    INSERT INTO t1 VALUES(2);
    INSERT INTO t1 VALUES(3);
    CREATE TABLE t2(y);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    CREATE VIRTUAL TABLE echo_t2 USING echo(t2);
    SELECT * FROM t1 WHERE x IN (SELECT rowid FROM t2);
  }
} {2}
do_test vtab8-2.2 {
  execsql {
    SELECT rowid FROM echo_t2
  }
} {1 2}
do_test vtabB-2.3 {
  execsql {
    SELECT * FROM t1 WHERE x IN (SELECT rowid FROM t2);
  }
} {2}
do_test vtabB-2.4 {
  execsql {
    SELECT * FROM t1 WHERE x IN (SELECT rowid FROM echo_t2);
  }
} {2}
do_test vtabB-2.5 {
  execsql {
    SELECT * FROM t1 WHERE x IN (SELECT y FROM t2);
  }
} {2}
do_test vtabB-2.6 {
  execsql {
    SELECT * FROM t1 WHERE x IN (SELECT y FROM echo_t2);
  }
} {2}

finish_test

Added test/vtabC.test.









































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# 2008 April 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is is verifying that the xUpdate, xSync, xCommit
# and xRollback methods are only invoked after an xBegin or xCreate.
# Ticket #3083.
#
# $Id: vtabC.test,v 1.2 2009/04/07 14:14:23 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}

ifcapable !trigger { finish_test ; return }


# N will be the number of virtual tables we have defined.
#
unset -nocomplain N
for {set N 1} {$N<=20} {incr N} {
  db close
  file delete -force test.db test.db-journal
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]

  # Create $N tables and $N virtual tables to echo them.
  #
  unset -nocomplain tablist
  set tablist {}
  do_test vtabC-1.$N.1 {
    for {set i 1} {$i<=$::N} {incr i} {
      execsql "CREATE TABLE t${i}(x)"
      execsql "CREATE VIRTUAL TABLE vt$i USING echo(t$i)"
      lappend ::tablist t$i vt$i
    }
    execsql {SELECT count(*) FROM sqlite_master}
  } [expr {$N*2}]
  do_test vtabC-1.$N.2 {
    execsql {SELECT name FROM sqlite_master}
  } $tablist

  # Create a table m and add triggers to make changes on all
  # of the virtual tables when m is changed.
  #
  do_test vtabC-1.$N.3 {
    execsql {CREATE TABLE m(a)}
    set sql "CREATE TRIGGER rins AFTER INSERT ON m BEGIN\n"
    for {set i 1} {$i<=$::N} {incr i} {
      append sql "  INSERT INTO vt$i VALUES(NEW.a+$i);\n"
    }
    append sql "END;"
    execsql $sql
    execsql {SELECT count(*) FROM sqlite_master}
  } [expr {$N*2+2}]
  do_test vtabC-1.$N.4 {
    execsql {
      INSERT INTO m VALUES(1000);
      SELECT * FROM m;
    }
  } {1000}
  for {set j 1} {$j<=$::N} {incr j} {
    do_test vtabC-1.$N.5.$j {
      execsql "SELECT * FROM t$::j"
    } [expr {$j+1000}]
    do_test vtabC-1.$N.6.$j {
      execsql "SELECT * FROM vt$::j"
    } [expr {$j+1000}]
  }
  do_test vtabC-1.$N.7 {
    set sql "CREATE TRIGGER rins2 BEFORE INSERT ON m BEGIN\n"
    for {set i 1} {$i<=$::N} {incr i} {
      append sql "  INSERT INTO vt$i VALUES(NEW.a+$i*100);\n"
    }
    for {set i 1} {$i<=$::N} {incr i} {
      append sql "  INSERT INTO vt$i VALUES(NEW.a+$i*10000);\n"
    }
    append sql "END;"
    execsql $sql
    execsql {SELECT count(*) FROM sqlite_master}
  } [expr {$N*2+3}]
  do_test vtabC-1.$N.8 {
    execsql {
      INSERT INTO m VALUES(9000000);
      SELECT * FROM m;
    }
  } {1000 9000000}
  unset -nocomplain res
  for {set j 1} {$j<=$::N} {incr j} {
    set res [expr {$j+1000}]
    lappend res [expr {$j*100+9000000}]
    lappend res [expr {$j*10000+9000000}]
    lappend res [expr {$j+9000000}]
    do_test vtabC-1.$N.9.$j {
      execsql "SELECT * FROM t$::j"
    } $res
    do_test vtabC-1.$N.10.$j {
      execsql "SELECT * FROM vt$::j"
    } $res
  }
}
unset -nocomplain res N i j


finish_test

Added test/vtabD.test.















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 2009 April 14
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is creating and dropping virtual tables.
#
# $Id: vtabD.test,v 1.3 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab||!schema_pragmas { finish_test ; return }

# Register the echo module
register_echo_module [sqlite3_connection_pointer db]

do_test vtabD-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE INDEX i1 ON t1(a);
    CREATE INDEX i2 ON t1(b);
    CREATE VIRTUAL TABLE tv1 USING echo(t1);
  }
} {}
do_test vtabD-1.2 {
  execsql BEGIN
  for {set i 0} {$i < 100000} {incr i} {
    execsql { INSERT INTO t1 VALUES($i, $i*$i) }
  }
  execsql COMMIT
} {}
do_test vtabD-1.3 {
  execsql { SELECT * FROM tv1 WHERE a = 1 OR b = 4 }
} {1 1 2 4}
do_test vtabD-1.4 {
  execsql { SELECT * FROM tv1 WHERE a = 1 OR b = 1 }
} {1 1}
do_test vtabD-1.5 {
  execsql { SELECT * FROM tv1 WHERE (a > 0 AND a < 5) OR (b > 15 AND b < 65) }
} {1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64}

do_test vtabD-1.6 {
  execsql { SELECT * FROM tv1 WHERE a < 500 OR b = 810000 }
} [execsql {
  SELECT * FROM t1 WHERE a < 500
    UNION ALL
  SELECT * FROM t1 WHERE b = 810000 AND NOT (a < 500)
}]

do_test vtabD-1.7 {
  execsql { SELECT * FROM tv1 WHERE a < 90000 OR b = 8100000000 }
} [execsql {
  SELECT * FROM t1 WHERE a < 90000
    UNION ALL
  SELECT * FROM t1 WHERE b = 8100000000 AND NOT (a < 90000)
}]

if {[working_64bit_int]} {
do_test vtabD-1.8 {
  execsql { SELECT * FROM tv1 WHERE a = 90001 OR b = 810000 }
} {90001 8100180001 900 810000}
}

finish_test

Added test/vtab_alter.test.















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 2007 June 26
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the ALTER TABLE ... RENAME TO
# command on virtual tables.
#
# $Id: vtab_alter.test,v 1.3 2007/12/13 21:54:11 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab||!altertable {
  finish_test
  return
}

# Register the echo module.
#
# This test uses a special feature of the echo module. If the name
# of the virtual table is a prefix of the name of the underlying
# real table (for example if the v-table is "tbl" and the real table
# is "tbl_base"), then the name of the real table is modified
# when an "ALTER TABLE ... RENAME TO" is executed on the v-table.
# For example:
#
#   sqlite> CREATE TABLE t1_base(a, b, c); 
#   sqlite> CREATE VIRTUAL TABLE t1 USING(t1_base);
#   sqlite> ALTER TABLE t1 RENAME TO t2;
#   sqlite> SELECT tbl_name FROM sqlite_master;
#   t2_base
#   t2
#
register_echo_module [sqlite3_connection_pointer db]


# Try to rename an echo table. Make sure nothing terrible happens.
#
do_test vtab_alter-1.1 {
  execsql { CREATE TABLE t1(a, b VARCHAR, c INTEGER) }
} {}
do_test vtab_alter-1.2 {
  execsql { CREATE VIRTUAL TABLE t1echo USING echo(t1) }
} {}
do_test vtab_alter-1.3 {
  catchsql { SELECT * FROM t1echo }
} {0 {}}
do_test vtab_alter-1.4 {
  execsql { ALTER TABLE t1echo RENAME TO new }
} {}
do_test vtab_alter-1.5 {
  catchsql { SELECT * FROM t1echo }
} {1 {no such table: t1echo}}
do_test vtab_alter-1.6 {
  catchsql { SELECT * FROM new }
} {0 {}}

# Try to rename an echo table that renames its base table. Make 
# sure nothing terrible happens.
#
do_test vtab_alter-2.1 {
  execsql { 
    DROP TABLE new;
    DROP TABLE t1;
    CREATE TABLE t1_base(a, b, c);
    CREATE VIRTUAL TABLE t1 USING echo('*_base');
  }
} {}
do_test vtab_alter-2.2 {
  execsql { 
    INSERT INTO t1_base VALUES(1, 2, 3);
    SELECT * FROM t1;
  }
} {1 2 3}
do_test vtab_alter-2.3 {
  execsql { ALTER TABLE t1 RENAME TO x }
} {}
do_test vtab_alter-2.4 {
  execsql { SELECT * FROM x; }
} {1 2 3}
do_test vtab_alter-2.5 {
  execsql { SELECT * FROM x_base; }
} {1 2 3}

# Cause an error to occur when the echo module renames its
# backing store table.
#
do_test vtab_alter-3.1 {
  execsql  { CREATE TABLE y_base(a, b, c) }
  catchsql { ALTER TABLE x RENAME TO y }
} {1 {SQL logic error or missing database}}
do_test vtab_alter-3.2 {
  execsql  { SELECT * FROM x }
} {1 2 3}

finish_test

Added test/vtab_err.test.















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 2006 June 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# $Id: vtab_err.test,v 1.8 2007/09/03 16:12:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab {
  finish_test
  return
}



unset -nocomplain echo_module_begin_fail
do_ioerr_test vtab_err-1 -tclprep {
  register_echo_module [sqlite3_connection_pointer db]
} -sqlbody {
  BEGIN;
  CREATE TABLE r(a PRIMARY KEY, b, c);
  CREATE VIRTUAL TABLE e USING echo(r);
  INSERT INTO e VALUES(1, 2, 3);
  INSERT INTO e VALUES('a', 'b', 'c');
  UPDATE e SET c = 10;
  DELETE FROM e WHERE a = 'a';
  COMMIT;
  BEGIN;
    CREATE TABLE r2(a, b, c);
    INSERT INTO r2 SELECT * FROM e;
    INSERT INTO e SELECT a||'x', b, c FROM r2;
  COMMIT;
}

ifcapable !memdebug {
   puts "Skipping vtab_err-2 tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}
source $testdir/malloc_common.tcl


do_malloc_test vtab_err-2 -tclprep { 
  register_echo_module [sqlite3_connection_pointer db]
} -sqlbody {
  BEGIN;
  CREATE TABLE r(a PRIMARY KEY, b, c);
  CREATE VIRTUAL TABLE e USING echo(r);
  INSERT INTO e VALUES(1, 2, 3);
  INSERT INTO e VALUES('a', 'b', 'c');
  UPDATE e SET c = 10;
  DELETE FROM e WHERE a = 'a';
  COMMIT;
  BEGIN;
    CREATE TABLE r2(a, b, c);
    INSERT INTO r2 SELECT * FROM e;
    INSERT INTO e SELECT a||'x', b, c FROM r2;
  COMMIT;
} 

sqlite3_memdebug_fail -1

finish_test

Added test/vtab_shared.test.















































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# 2007 April 16
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file tests interactions between the virtual table and
# shared-schema functionality.
#
# $Id: vtab_shared.test,v 1.3 2009/07/24 17:58:53 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !vtab||!shared_cache {
  finish_test
  return
}

db close
sqlite3_enable_shared_cache 1
sqlite3 db  test.db
sqlite3 db2 test.db

do_test vtab_shared-1.1 {
  register_echo_module [sqlite3_connection_pointer db]
  execsql {
    CREATE TABLE t0(a, b, c);
    INSERT INTO t0 VALUES(1, 2, 3);
    CREATE VIRTUAL TABLE t1 USING echo(t0);
  }
} {}

do_test vtab_shared-1.2 {
  execsql { SELECT * FROM t1 } db
} {1 2 3}

# Fails because the 'echo' module has not been registered with connection db2
do_test vtab_shared-1.3 {
  catchsql { SELECT * FROM t1 } db2
} {1 {no such module: echo}}

do_test vtab_shared-1.4 {
  execsql { SELECT * FROM t0 } db2
} {1 2 3}

do_test vtab_shared-1.5 {
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { SELECT * FROM t1 } db
} {1 2 3}

# Works after the module is registered with db2
do_test vtab_shared-1.6 {
  execsql { SELECT * FROM t1 } db2
} {1 2 3}

# Set a write-lock on table t0 using connection [db]. Then try to read from
# virtual table t1 using [db2]. That this returns an SQLITE_LOCKED error
# shows that the correct sqlite3_vtab is being used.
#
do_test vtab_shared-1.8.1 {
  execsql { 
    BEGIN;
    INSERT INTO t1 VALUES(4, 5, 6);
    SELECT * FROM t1;
  }
} {1 2 3 4 5 6}
do_test vtab_shared-1.8.2 {
  catchsql { SELECT * FROM t1 } db2
} {1 {database table is locked}}
do_test vtab_shared-1.8.3 {
  catchsql { SELECT *  FROM t0 } db2
} {1 {database table is locked: t0}}
do_test vtab_shared-1.8.4 {
  execsql { SELECT * FROM t0 } db
} {1 2 3 4 5 6}
do_test vtab_shared-1.8.5 {
  execsql { COMMIT } db
  execsql { SELECT *  FROM t1 } db2
} {1 2 3 4 5 6}

# While a SELECT is active on virtual table t1 via connection [db], close 
# [db2]. This causes the schema to be reset internally. Verify that this
# does not cause a problem.
#
foreach {iTest dbSelect dbClose} {
  1 db  db2
  2 db  db2
  3 db2 db
} {
  do_test vtab_shared-1.9.$iTest {
    set res [list]
    $dbSelect eval { SELECT * FROM t1 } {
      if {$a == 1} {$dbClose close}
      lappend res $a $b $c
    }
    sqlite3 $dbClose test.db
    register_echo_module [sqlite3_connection_pointer $dbClose]
    set res
  } {1 2 3 4 5 6}
}

# Ensure that it is not possible for one connection to DROP a virtual
# table while a second connection is reading from the database.
#
do_test vtab_shared-1.10 {
  db eval { SELECT * FROM t1 } {
    set error [catchsql { DROP TABLE t1 } db2]
    break
  }
  set error
} {1 {database table is locked: sqlite_master}}

do_test vtab_shared-1.11 {
breakpoint
  execsql {
    CREATE VIRTUAL TABLE t2 USING echo(t0);
    CREATE VIRTUAL TABLE t3 USING echo(t0);
  }
  execsql { SELECT * FROM t3 } db2
} {1 2 3 4 5 6}

do_test vtab_shared-1.12.1 {
  db close
  execsql { 
    SELECT * FROM t1 UNION ALL
    SELECT * FROM t2 UNION ALL
    SELECT * FROM t3 
  } db2
} {1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6}
do_test vtab_shared-1.12.2 {
  sqlite3 db test.db
  register_echo_module [sqlite3_connection_pointer db]
  execsql { 
    SELECT * FROM t1 UNION ALL
    SELECT * FROM t2 UNION ALL
    SELECT * FROM t3 
  } db
} {1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6}

# Try a rename or two.
#
ifcapable altertable {
  do_test vtab_shared-1.13.1 {
    execsql { ALTER TABLE t1 RENAME TO t4 }
    execsql { SELECT * FROM t4 } db
  } {1 2 3 4 5 6}
  do_test vtab_shared-1.13.2 {
    execsql { SELECT * FROM t4 } db2
  } {1 2 3 4 5 6}
  do_test vtab_shared-1.13.3 {
    execsql { ALTER TABLE t2 RENAME TO t5 }
    execsql { SELECT * FROM t4 } db2
  } {1 2 3 4 5 6}
}

# Try an UPDATE/INSERT/DELETE on a shared vtab as the first statement after a
# schema is loaded.
do_test vtab_shared_1.14.1 {
  db2 close
  sqlite3 db2 test.db
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { SELECT * FROM t3 }
} {1 2 3 4 5 6}
do_test vtab_shared_1.14.2 {
  execsql { 
    UPDATE t3 SET c = 'six' WHERE c = 6;
    SELECT * FROM t3;
  } db2
} {1 2 3 4 5 six}
do_test vtab_shared_1.14.3 {
  db2 close
  sqlite3 db2 test.db
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { SELECT * FROM t3 }
} {1 2 3 4 5 six}
do_test vtab_shared_1.14.4 {
  execsql { 
    DELETE FROM t3 WHERE c = 'six';
    SELECT * FROM t3;
  } db2
} {1 2 3}
do_test vtab_shared_1.14.5 {
  db2 close
  sqlite3 db2 test.db
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { SELECT * FROM t3 }
} {1 2 3}
do_test vtab_shared_1.14.6 {
  execsql { 
    INSERT INTO t3 VALUES(4, 5, 6);
    SELECT * FROM t3;
  } db2
} {1 2 3 4 5 6}

do_test vtab_shared_1.15.1 {
  db2 close
  sqlite3 db2 test.db
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { 
    UPDATE t3 SET c = 'six' WHERE c = 6;
    SELECT * FROM t3;
  } db2
} {1 2 3 4 5 six}
do_test vtab_shared_1.15.2 {
  db2 close
  sqlite3 db2 test.db
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { 
    DELETE FROM t3 WHERE c = 'six';
    SELECT * FROM t3;
  } db2
} {1 2 3}
do_test vtab_shared_1.15.3 {
  db2 close
  sqlite3 db2 test.db
  register_echo_module [sqlite3_connection_pointer db2]
  execsql { 
    INSERT INTO t3 VALUES(4, 5, 6);
    SELECT * FROM t3;
  }
} {1 2 3 4 5 6}

db close
db2 close
sqlite3_enable_shared_cache 0
finish_test

Added test/where.test.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the use of indices in WHERE clases.
#
# $Id: where.test,v 1.50 2008/11/03 09:06:06 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
do_test where-1.0 {
  execsql {
    CREATE TABLE t1(w int, x int, y int);
    CREATE TABLE t2(p int, q int, r int, s int);
  }
  for {set i 1} {$i<=100} {incr i} {
    set w $i
    set x [expr {int(log($i)/log(2))}]
    set y [expr {$i*$i + 2*$i + 1}]
    execsql "INSERT INTO t1 VALUES($w,$x,$y)"
  }

  ifcapable subquery {
    execsql {
      INSERT INTO t2 SELECT 101-w, x, (SELECT max(y) FROM t1)+1-y, y FROM t1;
    }
  } else {
    set maxy [execsql {select max(y) from t1}]
    execsql "
      INSERT INTO t2 SELECT 101-w, x, $maxy+1-y, y FROM t1;
    "
  }

  execsql {
    CREATE INDEX i1w ON t1(w);
    CREATE INDEX i1xy ON t1(x,y);
    CREATE INDEX i2p ON t2(p);
    CREATE INDEX i2r ON t2(r);
    CREATE INDEX i2qs ON t2(q, s);
  }
} {}

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  return [concat [execsql $sql] $::sqlite_search_count]
}

# Verify that queries use an index.  We are using the special variable
# "sqlite_search_count" which tallys the number of executions of MoveTo
# and Next operators in the VDBE.  By verifing that the search count is
# small we can be assured that indices are being used properly.
#
do_test where-1.1.1 {
  count {SELECT x, y, w FROM t1 WHERE w=10}
} {3 121 10 3}
do_test where-1.1.2 {
  set sqlite_query_plan
} {t1 i1w}
do_test where-1.1.3 {
  db status step
} {0}
do_test where-1.1.4 {
  db eval {SELECT x, y, w FROM t1 WHERE +w=10}
} {3 121 10}
do_test where-1.1.5 {
  db status step
} {99}
do_test where-1.1.6 {
  set sqlite_query_plan
} {t1 {}}
do_test where-1.1.7 {
  count {SELECT x, y, w AS abc FROM t1 WHERE abc=10}
} {3 121 10 3}
do_test where-1.1.8 {
  set sqlite_query_plan
} {t1 i1w}
do_test where-1.1.9 {
  db status step
} {0}
do_test where-1.2.1 {
  count {SELECT x, y, w FROM t1 WHERE w=11}
} {3 144 11 3}
do_test where-1.2.2 {
  count {SELECT x, y, w AS abc FROM t1 WHERE abc=11}
} {3 144 11 3}
do_test where-1.3.1 {
  count {SELECT x, y, w AS abc FROM t1 WHERE 11=w}
} {3 144 11 3}
do_test where-1.3.2 {
  count {SELECT x, y, w AS abc FROM t1 WHERE 11=abc}
} {3 144 11 3}
do_test where-1.4.1 {
  count {SELECT w, x, y FROM t1 WHERE 11=w AND x>2}
} {11 3 144 3}
do_test where-1.4.2 {
  set sqlite_query_plan
} {t1 i1w}
do_test where-1.4.3 {
  count {SELECT w AS a, x AS b, y FROM t1 WHERE 11=a AND b>2}
} {11 3 144 3}
do_test where-1.4.4 {
  set sqlite_query_plan
} {t1 i1w}
do_test where-1.5 {
  count {SELECT x, y FROM t1 WHERE y<200 AND w=11 AND x>2}
} {3 144 3}
do_test where-1.5.2 {
  set sqlite_query_plan
} {t1 i1w}
do_test where-1.6 {
  count {SELECT x, y FROM t1 WHERE y<200 AND x>2 AND w=11}
} {3 144 3}
do_test where-1.7 {
  count {SELECT x, y FROM t1 WHERE w=11 AND y<200 AND x>2}
} {3 144 3}
do_test where-1.8 {
  count {SELECT x, y FROM t1 WHERE w>10 AND y=144 AND x=3}
} {3 144 3}
do_test where-1.8.2 {
  set sqlite_query_plan
} {t1 i1xy}
do_test where-1.8.3 {
  count {SELECT x, y FROM t1 WHERE y=144 AND x=3}
  set sqlite_query_plan
} {{} i1xy}
do_test where-1.9 {
  count {SELECT x, y FROM t1 WHERE y=144 AND w>10 AND x=3}
} {3 144 3}
do_test where-1.10 {
  count {SELECT x, y FROM t1 WHERE x=3 AND w>=10 AND y=121}
} {3 121 3}
do_test where-1.11 {
  count {SELECT x, y FROM t1 WHERE x=3 AND y=100 AND w<10}
} {3 100 3}

# New for SQLite version 2.1: Verify that that inequality constraints
# are used correctly.
#
do_test where-1.12 {
  count {SELECT w FROM t1 WHERE x=3 AND y<100}
} {8 3}
do_test where-1.13 {
  count {SELECT w FROM t1 WHERE x=3 AND 100>y}
} {8 3}
do_test where-1.14 {
  count {SELECT w FROM t1 WHERE 3=x AND y<100}
} {8 3}
do_test where-1.15 {
  count {SELECT w FROM t1 WHERE 3=x AND 100>y}
} {8 3}
do_test where-1.16 {
  count {SELECT w FROM t1 WHERE x=3 AND y<=100}
} {8 9 5}
do_test where-1.17 {
  count {SELECT w FROM t1 WHERE x=3 AND 100>=y}
} {8 9 5}
do_test where-1.18 {
  count {SELECT w FROM t1 WHERE x=3 AND y>225}
} {15 3}
do_test where-1.19 {
  count {SELECT w FROM t1 WHERE x=3 AND 225<y}
} {15 3}
do_test where-1.20 {
  count {SELECT w FROM t1 WHERE x=3 AND y>=225}
} {14 15 5}
do_test where-1.21 {
  count {SELECT w FROM t1 WHERE x=3 AND 225<=y}
} {14 15 5}
do_test where-1.22 {
  count {SELECT w FROM t1 WHERE x=3 AND y>121 AND y<196}
} {11 12 5}
do_test where-1.23 {
  count {SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<=196}
} {10 11 12 13 9}
do_test where-1.24 {
  count {SELECT w FROM t1 WHERE x=3 AND 121<y AND 196>y}
} {11 12 5}
do_test where-1.25 {
  count {SELECT w FROM t1 WHERE x=3 AND 121<=y AND 196>=y}
} {10 11 12 13 9}

# Need to work on optimizing the BETWEEN operator.  
#
# do_test where-1.26 {
#   count {SELECT w FROM t1 WHERE x=3 AND y BETWEEN 121 AND 196}
# } {10 11 12 13 9}

do_test where-1.27 {
  count {SELECT w FROM t1 WHERE x=3 AND y+1==122}
} {10 10}

do_test where-1.28 {
  count {SELECT w FROM t1 WHERE x+1=4 AND y+1==122}
} {10 99}
do_test where-1.29 {
  count {SELECT w FROM t1 WHERE y==121}
} {10 99}


do_test where-1.30 {
  count {SELECT w FROM t1 WHERE w>97}
} {98 99 100 3}
do_test where-1.31 {
  count {SELECT w FROM t1 WHERE w>=97}
} {97 98 99 100 4}
do_test where-1.33 {
  count {SELECT w FROM t1 WHERE w==97}
} {97 2}
do_test where-1.33.1  {
  count {SELECT w FROM t1 WHERE w<=97 AND w==97}
} {97 2}
do_test where-1.33.2  {
  count {SELECT w FROM t1 WHERE w<98 AND w==97}
} {97 2}
do_test where-1.33.3  {
  count {SELECT w FROM t1 WHERE w>=97 AND w==97}
} {97 2}
do_test where-1.33.4  {
  count {SELECT w FROM t1 WHERE w>96 AND w==97}
} {97 2}
do_test where-1.33.5  {
  count {SELECT w FROM t1 WHERE w==97 AND w==97}
} {97 2}
do_test where-1.34 {
  count {SELECT w FROM t1 WHERE w+1==98}
} {97 99}
do_test where-1.35 {
  count {SELECT w FROM t1 WHERE w<3}
} {1 2 2}
do_test where-1.36 {
  count {SELECT w FROM t1 WHERE w<=3}
} {1 2 3 3}
do_test where-1.37 {
  count {SELECT w FROM t1 WHERE w+1<=4 ORDER BY w}
} {1 2 3 99}

do_test where-1.38 {
  count {SELECT (w) FROM t1 WHERE (w)>(97)}
} {98 99 100 3}
do_test where-1.39 {
  count {SELECT (w) FROM t1 WHERE (w)>=(97)}
} {97 98 99 100 4}
do_test where-1.40 {
  count {SELECT (w) FROM t1 WHERE (w)==(97)}
} {97 2}
do_test where-1.41 {
  count {SELECT (w) FROM t1 WHERE ((w)+(1))==(98)}
} {97 99}


# Do the same kind of thing except use a join as the data source.
#
do_test where-2.1 {
  count {
    SELECT w, p FROM t2, t1
    WHERE x=q AND y=s AND r=8977
  }
} {34 67 6}
do_test where-2.2 {
  count {
    SELECT w, p FROM t2, t1
    WHERE x=q AND s=y AND r=8977
  }
} {34 67 6}
do_test where-2.3 {
  count {
    SELECT w, p FROM t2, t1
    WHERE x=q AND s=y AND r=8977 AND w>10
  }
} {34 67 6}
do_test where-2.4 {
  count {
    SELECT w, p FROM t2, t1
    WHERE p<80 AND x=q AND s=y AND r=8977 AND w>10
  }
} {34 67 6}
do_test where-2.5 {
  count {
    SELECT w, p FROM t2, t1
    WHERE p<80 AND x=q AND 8977=r AND s=y AND w>10
  }
} {34 67 6}
do_test where-2.6 {
  count {
    SELECT w, p FROM t2, t1
    WHERE x=q AND p=77 AND s=y AND w>5
  }
} {24 77 6}
do_test where-2.7 {
  count {
    SELECT w, p FROM t1, t2
    WHERE x=q AND p>77 AND s=y AND w=5
  }
} {5 96 6}

# Lets do a 3-way join.
#
do_test where-3.1 {
  count {
    SELECT A.w, B.p, C.w FROM t1 as A, t2 as B, t1 as C
    WHERE C.w=101-B.p AND B.r=10202-A.y AND A.w=11
  }
} {11 90 11 8}
do_test where-3.2 {
  count {
    SELECT A.w, B.p, C.w FROM t1 as A, t2 as B, t1 as C
    WHERE C.w=101-B.p AND B.r=10202-A.y AND A.w=12
  }
} {12 89 12 8}
do_test where-3.3 {
  count {
    SELECT A.w, B.p, C.w FROM t1 as A, t2 as B, t1 as C
    WHERE A.w=15 AND B.p=C.w AND B.r=10202-A.y
  }
} {15 86 86 8}

# Test to see that the special case of a constant WHERE clause is
# handled.
#
do_test where-4.1 {
  count {
    SELECT * FROM t1 WHERE 0
  }
} {0}
do_test where-4.2 {
  count {
    SELECT * FROM t1 WHERE 1 LIMIT 1
  }
} {1 0 4 0}
do_test where-4.3 {
  execsql {
    SELECT 99 WHERE 0
  }
} {}
do_test where-4.4 {
  execsql {
    SELECT 99 WHERE 1
  }
} {99}
do_test where-4.5 {
  execsql {
    SELECT 99 WHERE 0.1
  }
} {99}
do_test where-4.6 {
  execsql {
    SELECT 99 WHERE 0.0
  }
} {}
do_test where-4.7 {
  execsql {
    SELECT count(*) FROM t1 WHERE t1.w
  }
} {100}

# Verify that IN operators in a WHERE clause are handled correctly.
# Omit these tests if the build is not capable of sub-queries.
#
ifcapable subquery {
  do_test where-5.1 {
    count {
      SELECT * FROM t1 WHERE rowid IN (1,2,3,1234) order by 1;
    }
  } {1 0 4 2 1 9 3 1 16 4}
  do_test where-5.2 {
    count {
      SELECT * FROM t1 WHERE rowid+0 IN (1,2,3,1234) order by 1;
    }
  } {1 0 4 2 1 9 3 1 16 102}
  do_test where-5.3 {
    count {
      SELECT * FROM t1 WHERE w IN (-1,1,2,3) order by 1;
    }
  } {1 0 4 2 1 9 3 1 16 14}
  do_test where-5.4 {
    count {
      SELECT * FROM t1 WHERE w+0 IN (-1,1,2,3) order by 1;
    }
  } {1 0 4 2 1 9 3 1 16 102}
  do_test where-5.5 {
    count {
      SELECT * FROM t1 WHERE rowid IN 
         (select rowid from t1 where rowid IN (-1,2,4))
      ORDER BY 1;
    }
  } {2 1 9 4 2 25 3}
  do_test where-5.6 {
    count {
      SELECT * FROM t1 WHERE rowid+0 IN 
         (select rowid from t1 where rowid IN (-1,2,4))
      ORDER BY 1;
    }
  } {2 1 9 4 2 25 103}
  do_test where-5.7 {
    count {
      SELECT * FROM t1 WHERE w IN 
         (select rowid from t1 where rowid IN (-1,2,4))
      ORDER BY 1;
    }
  } {2 1 9 4 2 25 9}
  do_test where-5.8 {
    count {
      SELECT * FROM t1 WHERE w+0 IN 
         (select rowid from t1 where rowid IN (-1,2,4))
      ORDER BY 1;
    }
  } {2 1 9 4 2 25 103}
  do_test where-5.9 {
    count {
      SELECT * FROM t1 WHERE x IN (1,7) ORDER BY 1;
    }
  } {2 1 9 3 1 16 7}
  do_test where-5.10 {
    count {
      SELECT * FROM t1 WHERE x+0 IN (1,7) ORDER BY 1;
    }
  } {2 1 9 3 1 16 199}
  do_test where-5.11 {
    count {
      SELECT * FROM t1 WHERE y IN (6400,8100) ORDER BY 1;
    }
  } {79 6 6400 89 6 8100 199}
  do_test where-5.12 {
    count {
      SELECT * FROM t1 WHERE x=6 AND y IN (6400,8100) ORDER BY 1;
    }
  } {79 6 6400 89 6 8100 7}
  do_test where-5.13 {
    count {
      SELECT * FROM t1 WHERE x IN (1,7) AND y NOT IN (6400,8100) ORDER BY 1;
    }
  } {2 1 9 3 1 16 7}
  do_test where-5.14 {
    count {
      SELECT * FROM t1 WHERE x IN (1,7) AND y IN (9,10) ORDER BY 1;
    }
  } {2 1 9 8}
  do_test where-5.15 {
    count {
      SELECT * FROM t1 WHERE x IN (1,7) AND y IN (9,16) ORDER BY 1;
    }
  } {2 1 9 3 1 16 11}
}

# This procedure executes the SQL.  Then it checks to see if the OP_Sort
# opcode was executed.  If an OP_Sort did occur, then "sort" is appended
# to the result.  If no OP_Sort happened, then "nosort" is appended.
#
# This procedure is used to check to make sure sorting is or is not
# occurring as expected.
#
proc cksort {sql} {
  set data [execsql $sql]
  if {[db status sort]} {set x sort} {set x nosort}
  lappend data $x
  return $data
}
# Check out the logic that attempts to implement the ORDER BY clause
# using an index rather than by sorting.
#
do_test where-6.1 {
  execsql {
    CREATE TABLE t3(a,b,c);
    CREATE INDEX t3a ON t3(a);
    CREATE INDEX t3bc ON t3(b,c);
    CREATE INDEX t3acb ON t3(a,c,b);
    INSERT INTO t3 SELECT w, 101-w, y FROM t1;
    SELECT count(*), sum(a), sum(b), sum(c) FROM t3;
  }
} {100 5050 5050 348550}
do_test where-6.2 {
  cksort {
    SELECT * FROM t3 ORDER BY a LIMIT 3
  }
} {1 100 4 2 99 9 3 98 16 nosort}
do_test where-6.3 {
  cksort {
    SELECT * FROM t3 ORDER BY a+1 LIMIT 3
  }
} {1 100 4 2 99 9 3 98 16 sort}
do_test where-6.4 {
  cksort {
    SELECT * FROM t3 WHERE a<10 ORDER BY a LIMIT 3
  }
} {1 100 4 2 99 9 3 98 16 nosort}
do_test where-6.5 {
  cksort {
    SELECT * FROM t3 WHERE a>0 AND a<10 ORDER BY a LIMIT 3
  }
} {1 100 4 2 99 9 3 98 16 nosort}
do_test where-6.6 {
  cksort {
    SELECT * FROM t3 WHERE a>0 ORDER BY a LIMIT 3
  }
} {1 100 4 2 99 9 3 98 16 nosort}
do_test where-6.7 {
  cksort {
    SELECT * FROM t3 WHERE b>0 ORDER BY a LIMIT 3
  }
} {1 100 4 2 99 9 3 98 16 nosort}
ifcapable subquery {
  do_test where-6.8 {
    cksort {
      SELECT * FROM t3 WHERE a IN (3,5,7,1,9,4,2) ORDER BY a LIMIT 3
    }
  } {1 100 4 2 99 9 3 98 16 sort}
}
do_test where-6.9.1 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.1.1 {
  cksort {
    SELECT * FROM t3 WHERE a>=1 AND a=1 AND c>0 ORDER BY a LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.1.2 {
  cksort {
    SELECT * FROM t3 WHERE a<2 AND a=1 AND c>0 ORDER BY a LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.2 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a,c LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.3 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY c LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.4 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a DESC LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.5 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a DESC, c DESC LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.6 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY c DESC LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.7 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY c,a LIMIT 3
  }
} {1 100 4 sort}
do_test where-6.9.8 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a DESC, c ASC LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.9.9 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a ASC, c DESC LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.10 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.11 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a,c LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.12 {
  cksort {
    SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a,c,b LIMIT 3
  }
} {1 100 4 nosort}
do_test where-6.13 {
  cksort {
    SELECT * FROM t3 WHERE a>0 ORDER BY a DESC LIMIT 3
  }
} {100 1 10201 99 2 10000 98 3 9801 nosort}
do_test where-6.13.1 {
  cksort {
    SELECT * FROM t3 WHERE a>0 ORDER BY -a LIMIT 3
  }
} {100 1 10201 99 2 10000 98 3 9801 sort}
do_test where-6.14 {
  cksort {
    SELECT * FROM t3 ORDER BY b LIMIT 3
  }
} {100 1 10201 99 2 10000 98 3 9801 nosort}
do_test where-6.15 {
  cksort {
    SELECT t3.a, t1.x FROM t3, t1 WHERE t3.a=t1.w ORDER BY t3.a LIMIT 3
  }
} {1 0 2 1 3 1 nosort}
do_test where-6.16 {
  cksort {
    SELECT t3.a, t1.x FROM t3, t1 WHERE t3.a=t1.w ORDER BY t1.x, t3.a LIMIT 3
  }
} {1 0 2 1 3 1 sort}
do_test where-6.19 {
  cksort {
    SELECT y FROM t1 ORDER BY w LIMIT 3;
  }
} {4 9 16 nosort}
do_test where-6.20 {
  cksort {
    SELECT y FROM t1 ORDER BY rowid LIMIT 3;
  }
} {4 9 16 nosort}
do_test where-6.21 {
  cksort {
    SELECT y FROM t1 ORDER BY rowid, y LIMIT 3;
  }
} {4 9 16 nosort}
do_test where-6.22 {
  cksort {
    SELECT y FROM t1 ORDER BY rowid, y DESC LIMIT 3;
  }
} {4 9 16 nosort}
do_test where-6.23 {
  cksort {
    SELECT y FROM t1 WHERE y>4 ORDER BY rowid, w, x LIMIT 3;
  }
} {9 16 25 nosort}
do_test where-6.24 {
  cksort {
    SELECT y FROM t1 WHERE y>=9 ORDER BY rowid, x DESC, w LIMIT 3;
  }
} {9 16 25 nosort}
do_test where-6.25 {
  cksort {
    SELECT y FROM t1 WHERE y>4 AND y<25 ORDER BY rowid;
  }
} {9 16 nosort}
do_test where-6.26 {
  cksort {
    SELECT y FROM t1 WHERE y>=4 AND y<=25 ORDER BY oid;
  }
} {4 9 16 25 nosort}
do_test where-6.27 {
  cksort {
    SELECT y FROM t1 WHERE y<=25 ORDER BY _rowid_, w+y;
  }
} {4 9 16 25 nosort}


# Tests for reverse-order sorting.
#
do_test where-7.1 {
  cksort {
    SELECT w FROM t1 WHERE x=3 ORDER BY y;
  }
} {8 9 10 11 12 13 14 15 nosort}
do_test where-7.2 {
  cksort {
    SELECT w FROM t1 WHERE x=3 ORDER BY y DESC;
  }
} {15 14 13 12 11 10 9 8 nosort}
do_test where-7.3 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>100 ORDER BY y LIMIT 3;
  }
} {10 11 12 nosort}
do_test where-7.4 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>100 ORDER BY y DESC LIMIT 3;
  }
} {15 14 13 nosort}
do_test where-7.5 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>121 ORDER BY y DESC;
  }
} {15 14 13 12 11 nosort}
do_test where-7.6 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=121 ORDER BY y DESC;
  }
} {15 14 13 12 11 10 nosort}
do_test where-7.7 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<196 ORDER BY y DESC;
  }
} {12 11 10 nosort}
do_test where-7.8 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<=196 ORDER BY y DESC;
  }
} {13 12 11 10 nosort}
do_test where-7.9 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>121 AND y<=196 ORDER BY y DESC;
  }
} {13 12 11 nosort}
do_test where-7.10 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>100 AND y<196 ORDER BY y DESC;
  }
} {12 11 10 nosort}
do_test where-7.11 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<196 ORDER BY y;
  }
} {10 11 12 nosort}
do_test where-7.12 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<=196 ORDER BY y;
  }
} {10 11 12 13 nosort}
do_test where-7.13 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>121 AND y<=196 ORDER BY y;
  }
} {11 12 13 nosort}
do_test where-7.14 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>100 AND y<196 ORDER BY y;
  }
} {10 11 12 nosort}
do_test where-7.15 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y<81 ORDER BY y;
  }
} {nosort}
do_test where-7.16 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y<=81 ORDER BY y;
  }
} {8 nosort}
do_test where-7.17 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>256 ORDER BY y;
  }
} {nosort}
do_test where-7.18 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=256 ORDER BY y;
  }
} {15 nosort}
do_test where-7.19 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y<81 ORDER BY y DESC;
  }
} {nosort}
do_test where-7.20 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y<=81 ORDER BY y DESC;
  }
} {8 nosort}
do_test where-7.21 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>256 ORDER BY y DESC;
  }
} {nosort}
do_test where-7.22 {
  cksort {
    SELECT w FROM t1 WHERE x=3 AND y>=256 ORDER BY y DESC;
  }
} {15 nosort}
do_test where-7.23 {
  cksort {
    SELECT w FROM t1 WHERE x=0 AND y<4 ORDER BY y;
  }
} {nosort}
do_test where-7.24 {
  cksort {
    SELECT w FROM t1 WHERE x=0 AND y<=4 ORDER BY y;
  }
} {1 nosort}
do_test where-7.25 {
  cksort {
    SELECT w FROM t1 WHERE x=6 AND y>10201 ORDER BY y;
  }
} {nosort}
do_test where-7.26 {
  cksort {
    SELECT w FROM t1 WHERE x=6 AND y>=10201 ORDER BY y;
  }
} {100 nosort}
do_test where-7.27 {
  cksort {
    SELECT w FROM t1 WHERE x=0 AND y<4 ORDER BY y DESC;
  }
} {nosort}
do_test where-7.28 {
  cksort {
    SELECT w FROM t1 WHERE x=0 AND y<=4 ORDER BY y DESC;
  }
} {1 nosort}
do_test where-7.29 {
  cksort {
    SELECT w FROM t1 WHERE x=6 AND y>10201 ORDER BY y DESC;
  }
} {nosort}
do_test where-7.30 {
  cksort {
    SELECT w FROM t1 WHERE x=6 AND y>=10201 ORDER BY y DESC;
  }
} {100 nosort}
do_test where-7.31 {
  cksort {
    SELECT y FROM t1 ORDER BY rowid DESC LIMIT 3
  }
} {10201 10000 9801 nosort}
do_test where-7.32 {
  cksort {
    SELECT y FROM t1 WHERE y<25 ORDER BY rowid DESC
  }
} {16 9 4 nosort}
do_test where-7.33 {
  cksort {
    SELECT y FROM t1 WHERE y<=25 ORDER BY rowid DESC
  }
} {25 16 9 4 nosort}
do_test where-7.34 {
  cksort {
    SELECT y FROM t1 WHERE y<25 AND y>4 ORDER BY rowid DESC, y DESC
  }
} {16 9 nosort}
do_test where-7.35 {
  cksort {
    SELECT y FROM t1 WHERE y<25 AND y>=4 ORDER BY rowid DESC
  }
} {16 9 4 nosort}

do_test where-8.1 {
  execsql {
    CREATE TABLE t4 AS SELECT * FROM t1;
    CREATE INDEX i4xy ON t4(x,y);
  }
  cksort {
    SELECT w FROM t4 WHERE x=4 and y<1000 ORDER BY y DESC limit 3;
  }
} {30 29 28 nosort}
do_test where-8.2 {
  execsql {
    DELETE FROM t4;
  }
  cksort {
    SELECT w FROM t4 WHERE x=4 and y<1000 ORDER BY y DESC limit 3;
  }
} {nosort}

# Make sure searches with an index work with an empty table.
#
do_test where-9.1 {
  execsql {
    CREATE TABLE t5(x PRIMARY KEY);
    SELECT * FROM t5 WHERE x<10;
  }
} {}
do_test where-9.2 {
  execsql {
    SELECT * FROM t5 WHERE x<10 ORDER BY x DESC;
  }
} {}
do_test where-9.3 {
  execsql {
    SELECT * FROM t5 WHERE x=10;
  }
} {}

do_test where-10.1 {
  execsql {
    SELECT 1 WHERE abs(random())<0
  }
} {}
do_test where-10.2 {
  proc tclvar_func {vname} {return [set ::$vname]}
  db function tclvar tclvar_func
  set ::v1 0
  execsql {
    SELECT count(*) FROM t1 WHERE tclvar('v1');
  }
} {0}
do_test where-10.3 {
  set ::v1 1
  execsql {
    SELECT count(*) FROM t1 WHERE tclvar('v1');
  }
} {100}
do_test where-10.4 {
  set ::v1 1
  proc tclvar_func {vname} {
    upvar #0 $vname v
    set v [expr {!$v}]
    return $v
  }
  execsql {
    SELECT count(*) FROM t1 WHERE tclvar('v1');
  }
} {50}

# Ticket #1376.  The query below was causing a segfault.
# The problem was the age-old error of calling realloc() on an
# array while there are still pointers to individual elements of
# that array.
#
do_test where-11.1 {
  execsql {
   CREATE TABLE t99(Dte INT, X INT);
   DELETE FROM t99 WHERE (Dte = 2451337) OR (Dte = 2451339) OR
     (Dte BETWEEN 2451345 AND 2451347) OR (Dte = 2451351) OR 
     (Dte BETWEEN 2451355 AND 2451356) OR (Dte = 2451358) OR
     (Dte = 2451362) OR (Dte = 2451365) OR (Dte = 2451367) OR
     (Dte BETWEEN 2451372 AND 2451376) OR (Dte BETWEEN 2451382 AND 2451384) OR
     (Dte = 2451387) OR (Dte BETWEEN 2451389 AND 2451391) OR 
     (Dte BETWEEN 2451393 AND 2451395) OR (Dte = 2451400) OR 
     (Dte = 2451402) OR (Dte = 2451404) OR (Dte BETWEEN 2451416 AND 2451418) OR 
     (Dte = 2451422) OR (Dte = 2451426) OR (Dte BETWEEN 2451445 AND 2451446) OR
     (Dte = 2451456) OR (Dte = 2451458) OR (Dte BETWEEN 2451465 AND 2451467) OR
     (Dte BETWEEN 2451469 AND 2451471) OR (Dte = 2451474) OR
     (Dte BETWEEN 2451477 AND 2451501) OR (Dte BETWEEN 2451503 AND 2451509) OR
     (Dte BETWEEN 2451511 AND 2451514) OR (Dte BETWEEN 2451518 AND 2451521) OR
     (Dte BETWEEN 2451523 AND 2451531) OR (Dte BETWEEN 2451533 AND 2451537) OR
     (Dte BETWEEN 2451539 AND 2451544) OR (Dte BETWEEN 2451546 AND 2451551) OR
     (Dte BETWEEN 2451553 AND 2451555) OR (Dte = 2451557) OR
     (Dte BETWEEN 2451559 AND 2451561) OR (Dte = 2451563) OR
     (Dte BETWEEN 2451565 AND 2451566) OR (Dte BETWEEN 2451569 AND 2451571) OR 
     (Dte = 2451573) OR (Dte = 2451575) OR (Dte = 2451577) OR (Dte = 2451581) OR
     (Dte BETWEEN 2451583 AND 2451586) OR (Dte BETWEEN 2451588 AND 2451592) OR 
     (Dte BETWEEN 2451596 AND 2451598) OR (Dte = 2451600) OR
     (Dte BETWEEN 2451602 AND 2451603) OR (Dte = 2451606) OR (Dte = 2451611);
  }
} {}

# Ticket #2116:  Make sure sorting by index works well with nn INTEGER PRIMARY
# KEY.
#
do_test where-12.1 {
  execsql {
    CREATE TABLE t6(a INTEGER PRIMARY KEY, b TEXT);
    INSERT INTO t6 VALUES(1,'one');
    INSERT INTO t6 VALUES(4,'four');
    CREATE INDEX t6i1 ON t6(b);
  }
  cksort {
    SELECT * FROM t6 ORDER BY b;
  }
} {4 four 1 one nosort}
do_test where-12.2 {
  cksort {
    SELECT * FROM t6 ORDER BY b, a;
  }
} {4 four 1 one nosort}
do_test where-12.3 {
  cksort {
    SELECT * FROM t6 ORDER BY a;
  }
} {1 one 4 four nosort}
do_test where-12.4 {
  cksort {
    SELECT * FROM t6 ORDER BY a, b;
  }
} {1 one 4 four nosort}
do_test where-12.5 {
  cksort {
    SELECT * FROM t6 ORDER BY b DESC;
  }
} {1 one 4 four nosort}
do_test where-12.6 {
  cksort {
    SELECT * FROM t6 ORDER BY b DESC, a DESC;
  }
} {1 one 4 four nosort}
do_test where-12.7 {
  cksort {
    SELECT * FROM t6 ORDER BY b DESC, a ASC;
  }
} {1 one 4 four sort}
do_test where-12.8 {
  cksort {
    SELECT * FROM t6 ORDER BY b ASC, a DESC;
  }
} {4 four 1 one sort}
do_test where-12.9 {
  cksort {
    SELECT * FROM t6 ORDER BY a DESC;
  }
} {4 four 1 one nosort}
do_test where-12.10 {
  cksort {
    SELECT * FROM t6 ORDER BY a DESC, b DESC;
  }
} {4 four 1 one nosort}
do_test where-12.11 {
  cksort {
    SELECT * FROM t6 ORDER BY a DESC, b ASC;
  }
} {4 four 1 one nosort}
do_test where-12.12 {
  cksort {
    SELECT * FROM t6 ORDER BY a ASC, b DESC;
  }
} {1 one 4 four nosort}
do_test where-13.1 {
  execsql {
    CREATE TABLE t7(a INTEGER PRIMARY KEY, b TEXT);
    INSERT INTO t7 VALUES(1,'one');
    INSERT INTO t7 VALUES(4,'four');
    CREATE INDEX t7i1 ON t7(b);
  }
  cksort {
    SELECT * FROM t7 ORDER BY b;
  }
} {4 four 1 one nosort}
do_test where-13.2 {
  cksort {
    SELECT * FROM t7 ORDER BY b, a;
  }
} {4 four 1 one nosort}
do_test where-13.3 {
  cksort {
    SELECT * FROM t7 ORDER BY a;
  }
} {1 one 4 four nosort}
do_test where-13.4 {
  cksort {
    SELECT * FROM t7 ORDER BY a, b;
  }
} {1 one 4 four nosort}
do_test where-13.5 {
  cksort {
    SELECT * FROM t7 ORDER BY b DESC;
  }
} {1 one 4 four nosort}
do_test where-13.6 {
  cksort {
    SELECT * FROM t7 ORDER BY b DESC, a DESC;
  }
} {1 one 4 four nosort}
do_test where-13.7 {
  cksort {
    SELECT * FROM t7 ORDER BY b DESC, a ASC;
  }
} {1 one 4 four sort}
do_test where-13.8 {
  cksort {
    SELECT * FROM t7 ORDER BY b ASC, a DESC;
  }
} {4 four 1 one sort}
do_test where-13.9 {
  cksort {
    SELECT * FROM t7 ORDER BY a DESC;
  }
} {4 four 1 one nosort}
do_test where-13.10 {
  cksort {
    SELECT * FROM t7 ORDER BY a DESC, b DESC;
  }
} {4 four 1 one nosort}
do_test where-13.11 {
  cksort {
    SELECT * FROM t7 ORDER BY a DESC, b ASC;
  }
} {4 four 1 one nosort}
do_test where-13.12 {
  cksort {
    SELECT * FROM t7 ORDER BY a ASC, b DESC;
  }
} {1 one 4 four nosort}

# Ticket #2211.
#
# When optimizing out ORDER BY clauses, make sure that trailing terms
# of the ORDER BY clause do not reference other tables in a join.
#
do_test where-14.1 {
  execsql {
    CREATE TABLE t8(a INTEGER PRIMARY KEY, b TEXT UNIQUE);
    INSERT INTO t8 VALUES(1,'one');
    INSERT INTO t8 VALUES(4,'four');
  }
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, y.b
  } 
} {1/4 1/1 4/4 4/1 sort}
do_test where-14.2 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, y.b DESC
  } 
} {1/1 1/4 4/1 4/4 sort}
do_test where-14.3 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, x.b
  } 
} {1/1 1/4 4/1 4/4 nosort}
do_test where-14.4 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, x.b DESC
  } 
} {1/1 1/4 4/1 4/4 nosort}
do_test where-14.5 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||x.b
  } 
} {4/1 4/4 1/1 1/4 nosort}
do_test where-14.6 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||x.b DESC
  } 
} {4/1 4/4 1/1 1/4 nosort}
do_test where-14.7 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||y.b
  } 
} {4/1 4/4 1/1 1/4 sort}
do_test where-14.7.1 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a, y.a||y.b
  } 
} {4/1 4/4 1/1 1/4 sort}
do_test where-14.7.2 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a, x.a||x.b
  } 
} {4/1 4/4 1/1 1/4 nosort}
do_test where-14.8 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||y.b DESC
  } 
} {4/4 4/1 1/4 1/1 sort}
do_test where-14.9 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||y.b
  } 
} {4/4 4/1 1/4 1/1 sort}
do_test where-14.10 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||y.b DESC
  } 
} {4/1 4/4 1/1 1/4 sort}
do_test where-14.11 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||x.b
  } 
} {4/1 4/4 1/1 1/4 sort}
do_test where-14.12 {
  cksort {
    SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||x.b DESC
  } 
} {4/4 4/1 1/4 1/1 sort}

# Ticket #2445.
#
# There was a crash that could occur when a where clause contains an
# alias for an expression in the result set, and that expression retrieves
# a column of the second or subsequent table in a join.
#
do_test where-15.1 {
  execsql {
    CREATE TEMP TABLE t1 (a, b, c, d, e);
    CREATE TEMP TABLE t2 (f);
    SELECT t1.e AS alias FROM t2, t1 WHERE alias = 1 ;
  }
} {}

# Ticket #3408.
# 
# The branch of code in where.c that generated rowid lookups was
# incorrectly deallocating a constant register, meaning that if the 
# vdbe code ran more than once, the second time around the constant
# value may have been clobbered by some other value.
# 
do_test where-16.1 {
  execsql {
    CREATE TABLE a1(id INTEGER PRIMARY KEY, v);
    CREATE TABLE a2(id INTEGER PRIMARY KEY, v);
    INSERT INTO a1 VALUES(1, 'one');
    INSERT INTO a1 VALUES(2, 'two');
    INSERT INTO a2 VALUES(1, 'one');
    INSERT INTO a2 VALUES(2, 'two');
  }
} {}
do_test where-16.2 {
  execsql {
    SELECT * FROM a2 CROSS JOIN a1 WHERE a1.id=1 AND a1.v='one';
  }
} {1 one 1 one 2 two 1 one}

# The actual problem reported in #3408.
do_test where-16.3 {
  execsql {
    CREATE TEMP TABLE foo(idx INTEGER);
    INSERT INTO foo VALUES(1);
    INSERT INTO foo VALUES(1);
    INSERT INTO foo VALUES(1);
    INSERT INTO foo VALUES(2);
    INSERT INTO foo VALUES(2);
    CREATE TEMP TABLE bar(stuff INTEGER);
    INSERT INTO bar VALUES(100);
    INSERT INTO bar VALUES(200);
    INSERT INTO bar VALUES(300);
  }
} {}
do_test where-16.4 {
  execsql {
    SELECT bar.RowID id FROM foo, bar WHERE foo.idx = bar.RowID AND id = 2;
  }
} {2 2}

integrity_check {where-99.0}

#---------------------------------------------------------------------
# These tests test that a bug surrounding the use of ForceInt has been
# fixed in where.c.
#
do_test where-17.1 {
  execsql {
    CREATE TABLE tbooking (
      id INTEGER PRIMARY KEY,
      eventtype INTEGER NOT NULL
    );
    INSERT INTO tbooking VALUES(42, 3);
    INSERT INTO tbooking VALUES(43, 4);
  }
} {}
do_test where-17.2 {
  execsql {
    SELECT a.id
    FROM tbooking AS a
    WHERE a.eventtype=3;
  }
} {42}
do_test where-17.3 {
  execsql {
    SELECT a.id, (SELECT b.id FROM tbooking AS b WHERE b.id>a.id)
    FROM tbooking AS a
    WHERE a.eventtype=3;
  }
} {42 43}
do_test where-17.4 {
  execsql {
    SELECT a.id, (SELECT b.id FROM tbooking AS b WHERE b.id>a.id)
    FROM (SELECT 1.5 AS id) AS a
  }
} {1.5 42}
do_test where-17.5 {
  execsql {
    CREATE TABLE tother(a, b);
    INSERT INTO tother VALUES(1, 3.7);
    SELECT id, a FROM tbooking, tother WHERE id>a;
  }
} {42 1 43 1}

finish_test

Added test/where2.test.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# 2005 July 28
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the use of indices in WHERE clauses
# based on recent changes to the optimizer.
#
# $Id: where2.test,v 1.15 2009/02/02 01:50:40 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
do_test where2-1.0 {
  execsql {
    BEGIN;
    CREATE TABLE t1(w int, x int, y int, z int);
  }
  for {set i 1} {$i<=100} {incr i} {
    set w $i
    set x [expr {int(log($i)/log(2))}]
    set y [expr {$i*$i + 2*$i + 1}]
    set z [expr {$x+$y}]
    ifcapable tclvar {
      execsql {INSERT INTO t1 VALUES($::w,$::x,$::y,$::z)}
    } else {
      execsql {INSERT INTO t1 VALUES(:w,:x,:y,:z)}
    }
  }
  execsql {
    CREATE UNIQUE INDEX i1w ON t1(w);
    CREATE INDEX i1xy ON t1(x,y);
    CREATE INDEX i1zyx ON t1(z,y,x);
    COMMIT;
  }
} {}

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  return [concat [execsql $sql] $::sqlite_search_count]
}

# This procedure executes the SQL.  Then it checks to see if the OP_Sort
# opcode was executed.  If an OP_Sort did occur, then "sort" is appended
# to the result.  If no OP_Sort happened, then "nosort" is appended.
#
# This procedure is used to check to make sure sorting is or is not
# occurring as expected.
#
proc cksort {sql} {
  set data [execsql $sql]
  if {[db status sort]} {set x sort} {set x nosort}
  lappend data $x
  return $data
}

# This procedure executes the SQL.  Then it appends to the result the
# "sort" or "nosort" keyword (as in the cksort procedure above) then
# it appends the ::sqlite_query_plan variable.
#
proc queryplan {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  if {$::sqlite_sort_count} {set x sort} {set x nosort}
  lappend data $x
  return [concat $data $::sqlite_query_plan]
}


# Prefer a UNIQUE index over another index.
#
do_test where2-1.1 {
  queryplan {
    SELECT * FROM t1 WHERE w=85 AND x=6 AND y=7396
  }
} {85 6 7396 7402 nosort t1 i1w}

# Always prefer a rowid== constraint over any other index.
#
do_test where2-1.3 {
  queryplan {
    SELECT * FROM t1 WHERE w=85 AND x=6 AND y=7396 AND rowid=85
  }
} {85 6 7396 7402 nosort t1 *}

# When constrained by a UNIQUE index, the ORDER BY clause is always ignored.
#
do_test where2-2.1 {
  queryplan {
    SELECT * FROM t1 WHERE w=85 ORDER BY random();
  }
} {85 6 7396 7402 nosort t1 i1w}
do_test where2-2.2 {
  queryplan {
    SELECT * FROM t1 WHERE x=6 AND y=7396 ORDER BY random();
  }
} {85 6 7396 7402 sort t1 i1xy}
do_test where2-2.3 {
  queryplan {
    SELECT * FROM t1 WHERE rowid=85 AND x=6 AND y=7396 ORDER BY random();
  }
} {85 6 7396 7402 nosort t1 *}


# Efficient handling of forward and reverse table scans.
#
do_test where2-3.1 {
  queryplan {
    SELECT * FROM t1 ORDER BY rowid LIMIT 2
  }
} {1 0 4 4 2 1 9 10 nosort t1 *}
do_test where2-3.2 {
  queryplan {
    SELECT * FROM t1 ORDER BY rowid DESC LIMIT 2
  }
} {100 6 10201 10207 99 6 10000 10006 nosort t1 *}

# The IN operator can be used by indices at multiple layers
#
ifcapable subquery {
  do_test where2-4.1 {
    queryplan {
      SELECT * FROM t1 WHERE z IN (10207,10006) AND y IN (10000,10201)
                       AND x>0 AND x<10
      ORDER BY w
    }
  } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx}
  do_test where2-4.2 {
    queryplan {
      SELECT * FROM t1 WHERE z IN (10207,10006) AND y=10000
                       AND x>0 AND x<10
      ORDER BY w
    }
  } {99 6 10000 10006 sort t1 i1zyx}
  do_test where2-4.3 {
    queryplan {
      SELECT * FROM t1 WHERE z=10006 AND y IN (10000,10201)
                       AND x>0 AND x<10
      ORDER BY w
    }
  } {99 6 10000 10006 sort t1 i1zyx}
  ifcapable compound {
    do_test where2-4.4 {
      queryplan {
        SELECT * FROM t1 WHERE z IN (SELECT 10207 UNION SELECT 10006)
                         AND y IN (10000,10201)
                         AND x>0 AND x<10
        ORDER BY w
      }
    } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx}
    do_test where2-4.5 {
      queryplan {
        SELECT * FROM t1 WHERE z IN (SELECT 10207 UNION SELECT 10006)
                         AND y IN (SELECT 10000 UNION SELECT 10201)
                         AND x>0 AND x<10
        ORDER BY w
      }
    } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx}
  }
  do_test where2-4.6 {
    queryplan {
      SELECT * FROM t1
       WHERE x IN (1,2,3,4,5,6,7,8)
         AND y IN (10000,10001,10002,10003,10004,10005)
       ORDER BY 2
    }
  } {99 6 10000 10006 sort t1 i1xy}

  # Duplicate entires on the RHS of an IN operator do not cause duplicate
  # output rows.
  #
  do_test where2-4.6 {
    queryplan {
      SELECT * FROM t1 WHERE z IN (10207,10006,10006,10207)
      ORDER BY w
    }
  } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx}
  ifcapable compound {
    do_test where2-4.7 {
      queryplan {
        SELECT * FROM t1 WHERE z IN (
           SELECT 10207 UNION ALL SELECT 10006
           UNION ALL SELECT 10006 UNION ALL SELECT 10207)
        ORDER BY w
      }
    } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx}
  }

} ;# ifcapable subquery

# The use of an IN operator disables the index as a sorter.
#
do_test where2-5.1 {
  queryplan {
    SELECT * FROM t1 WHERE w=99 ORDER BY w
  }
} {99 6 10000 10006 nosort t1 i1w}

ifcapable subquery {
  do_test where2-5.2 {
    queryplan {
      SELECT * FROM t1 WHERE w IN (99) ORDER BY w
    }
  } {99 6 10000 10006 sort t1 i1w}
}

# Verify that OR clauses get translated into IN operators.
#
set ::idx {}
ifcapable subquery {set ::idx i1w}
do_test where2-6.1.1 {
  queryplan {
    SELECT * FROM t1 WHERE w=99 OR w=100 ORDER BY +w
  }
} [list 99 6 10000 10006 100 6 10201 10207 sort t1 $::idx]
do_test where2-6.1.2 {
  queryplan {
    SELECT * FROM t1 WHERE 99=w OR 100=w ORDER BY +w
  }
} [list 99 6 10000 10006 100 6 10201 10207 sort t1 $::idx]
do_test where2-6.2 {
  queryplan {
    SELECT * FROM t1 WHERE w=99 OR w=100 OR 6=w ORDER BY +w
  }
} [list 6 2 49 51 99 6 10000 10006 100 6 10201 10207 sort t1 $::idx]

do_test where2-6.3 {
  queryplan {
    SELECT * FROM t1 WHERE w=99 OR w=100 OR 6=+w ORDER BY +w
  }
} {6 2 49 51 99 6 10000 10006 100 6 10201 10207 sort t1 {}}
do_test where2-6.4 {
  queryplan {
    SELECT * FROM t1 WHERE w=99 OR +w=100 OR 6=w ORDER BY +w
  }
} {6 2 49 51 99 6 10000 10006 100 6 10201 10207 sort t1 {}}

set ::idx {}
ifcapable subquery {set ::idx i1zyx}
do_test where2-6.5 {
  queryplan {
    SELECT b.* FROM t1 a, t1 b
     WHERE a.w=1 AND (a.y=b.z OR b.z=10)
     ORDER BY +b.w
  }
} [list 1 0 4 4 2 1 9 10 sort a i1w b $::idx]
do_test where2-6.6 {
  queryplan {
    SELECT b.* FROM t1 a, t1 b
     WHERE a.w=1 AND (b.z=10 OR a.y=b.z OR b.z=10)
     ORDER BY +b.w
  }
} [list 1 0 4 4 2 1 9 10 sort a i1w b $::idx]

# Ticket #2249.  Make sure the OR optimization is not attempted if
# comparisons between columns of different affinities are needed.
#
do_test where2-6.7 {
  execsql {
    CREATE TABLE t2249a(a TEXT UNIQUE);
    CREATE TABLE t2249b(b INTEGER);
    INSERT INTO t2249a VALUES('0123');
    INSERT INTO t2249b VALUES(123);
  }
  queryplan {
    -- Because a is type TEXT and b is type INTEGER, both a and b
    -- will attempt to convert to NUMERIC before the comparison.
    -- They will thus compare equal.
    --
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE a=b;
  }
} {123 0123 nosort t2249b {} t2249a {}}
do_test where2-6.9 {
  queryplan {
    -- The + operator removes affinity from the rhs.  No conversions
    -- occur and the comparison is false.  The result is an empty set.
    --
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE a=+b;
  }
} {nosort t2249b {} {} sqlite_autoindex_t2249a_1}
do_test where2-6.9.2 {
  # The same thing but with the expression flipped around.
  queryplan {
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE +b=a
  }
} {nosort t2249b {} {} sqlite_autoindex_t2249a_1}
do_test where2-6.10 {
  queryplan {
    -- Use + on both sides of the comparison to disable indices
    -- completely.  Make sure we get the same result.
    --
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE +a=+b;
  }
} {nosort t2249b {} t2249a {}}
do_test where2-6.11 {
  # This will not attempt the OR optimization because of the a=b
  # comparison.
  queryplan {
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE a=b OR a='hello';
  }
} {123 0123 nosort t2249b {} t2249a {}}
do_test where2-6.11.2 {
  # Permutations of the expression terms.
  queryplan {
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE b=a OR a='hello';
  }
} {123 0123 nosort t2249b {} t2249a {}}
do_test where2-6.11.3 {
  # Permutations of the expression terms.
  queryplan {
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE 'hello'=a OR b=a;
  }
} {123 0123 nosort t2249b {} t2249a {}}
do_test where2-6.11.4 {
  # Permutations of the expression terms.
  queryplan {
    SELECT * FROM t2249b CROSS JOIN t2249a WHERE a='hello' OR b=a;
  }
} {123 0123 nosort t2249b {} t2249a {}}
ifcapable explain&&subquery {
  # These tests are not run if subquery support is not included in the
  # build. This is because these tests test the "a = 1 OR a = 2" to
  # "a IN (1, 2)" optimisation transformation, which is not enabled if
  # subqueries and the IN operator is not available.
  #
  do_test where2-6.12 {
    # In this case, the +b disables the affinity conflict and allows
    # the OR optimization to be used again.  The result is now an empty
    # set, the same as in where2-6.9.
    queryplan {
      SELECT * FROM t2249b CROSS JOIN t2249a WHERE a=+b OR a='hello';
    }
  } {nosort t2249b {} {} sqlite_autoindex_t2249a_1}
  do_test where2-6.12.2 {
    # In this case, the +b disables the affinity conflict and allows
    # the OR optimization to be used again.  The result is now an empty
    # set, the same as in where2-6.9.
    queryplan {
      SELECT * FROM t2249b CROSS JOIN t2249a WHERE a='hello' OR +b=a;
    }
  } {nosort t2249b {} {} sqlite_autoindex_t2249a_1}
  do_test where2-6.12.3 {
    # In this case, the +b disables the affinity conflict and allows
    # the OR optimization to be used again.  The result is now an empty
    # set, the same as in where2-6.9.
    queryplan {
      SELECT * FROM t2249b CROSS JOIN t2249a WHERE +b=a OR a='hello';
    }
  } {nosort t2249b {} {} sqlite_autoindex_t2249a_1}
  do_test where2-6.13 {
    # The addition of +a on the second term disabled the OR optimization.
    # But we should still get the same empty-set result as in where2-6.9.
    queryplan {
      SELECT * FROM t2249b CROSS JOIN t2249a WHERE a=+b OR +a='hello';
    }
  } {nosort t2249b {} t2249a {}}
}

# Variations on the order of terms in a WHERE clause in order
# to make sure the OR optimizer can recognize them all.
do_test where2-6.20 {
  queryplan {
    SELECT * FROM t2249a x CROSS JOIN t2249a y WHERE x.a=y.a
  }
} {0123 0123 nosort x {} {} sqlite_autoindex_t2249a_1}
ifcapable explain&&subquery {
  # These tests are not run if subquery support is not included in the
  # build. This is because these tests test the "a = 1 OR a = 2" to
  # "a IN (1, 2)" optimisation transformation, which is not enabled if
  # subqueries and the IN operator is not available.
  #
  do_test where2-6.21 {
    queryplan {
      SELECT * FROM t2249a x CROSS JOIN t2249a y WHERE x.a=y.a OR y.a='hello'
    }
  } {0123 0123 nosort x {} {} sqlite_autoindex_t2249a_1}
  do_test where2-6.22 {
    queryplan {
      SELECT * FROM t2249a x CROSS JOIN t2249a y WHERE y.a=x.a OR y.a='hello'
    }
  } {0123 0123 nosort x {} {} sqlite_autoindex_t2249a_1}
  do_test where2-6.23 {
    queryplan {
      SELECT * FROM t2249a x CROSS JOIN t2249a y WHERE y.a='hello' OR x.a=y.a
    }
  } {0123 0123 nosort x {} {} sqlite_autoindex_t2249a_1}
}

# Unique queries (queries that are guaranteed to return only a single
# row of result) do not call the sorter.  But all tables must give
# a unique result.  If any one table in the join does not give a unique
# result then sorting is necessary.
#
do_test where2-7.1 {
  cksort {
    create table t8(a unique, b, c);
    insert into t8 values(1,2,3);
    insert into t8 values(2,3,4);
    create table t9(x,y);
    insert into t9 values(2,4);
    insert into t9 values(2,3);
    select y from t8, t9 where a=1 order by a, y;
  }
} {3 4 sort}
do_test where2-7.2 {
  cksort {
    select * from t8 where a=1 order by b, c
  }
} {1 2 3 nosort}
do_test where2-7.3 {
  cksort {
    select * from t8, t9 where a=1 and y=3 order by b, x
  }
} {1 2 3 2 3 sort}
do_test where2-7.4 {
  cksort {
    create unique index i9y on t9(y);
    select * from t8, t9 where a=1 and y=3 order by b, x
  }
} {1 2 3 2 3 nosort}

# Ticket #1807.  Using IN constrains on multiple columns of
# a multi-column index.
#
ifcapable subquery {
  do_test where2-8.1 {
    execsql {
      SELECT * FROM t1 WHERE x IN (20,21) AND y IN (1,2)
    }
  } {}
  do_test where2-8.2 {
    execsql {
      SELECT * FROM t1 WHERE x IN (1,2) AND y IN (-5,-6)
    }
  } {}
  execsql {CREATE TABLE tx AS SELECT * FROM t1}
  do_test where2-8.3 {
    execsql {
      SELECT w FROM t1
       WHERE x IN (SELECT x FROM tx WHERE rowid<0)
         AND +y IN (SELECT y FROM tx WHERE rowid=1)
    }
  } {}
  do_test where2-8.4 {
    execsql {
      SELECT w FROM t1
       WHERE x IN (SELECT x FROM tx WHERE rowid=1)
         AND y IN (SELECT y FROM tx WHERE rowid<0)
    }
  } {}
  #set sqlite_where_trace 1
  do_test where2-8.5 {
    execsql {
      CREATE INDEX tx_xyz ON tx(x, y, z, w);
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 12 AND 14)
    }
  } {12 13 14}
  do_test where2-8.6 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 12 AND 14)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {12 13 14}
  do_test where2-8.7 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 12 AND 14)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {10 11 12 13 14 15}
  do_test where2-8.8 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {10 11 12 13 14 15 16 17 18 19 20}
  do_test where2-8.9 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 2 AND 4)
    }
  } {}
  do_test where2-8.10 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 2 AND 4)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.11 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 2 AND 4)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.12 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN -4 AND -2)
    }
  } {}
  do_test where2-8.13 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN -4 AND -2)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.14 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN -4 AND -2)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.15 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 200 AND 300)
    }
  } {}
  do_test where2-8.16 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 200 AND 300)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.17 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 200 AND 300)
         AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.18 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE +w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE +w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE +w BETWEEN 200 AND 300)
    }
  } {}
  do_test where2-8.19 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE +w BETWEEN 10 AND 20)
         AND y IN (SELECT y FROM t1 WHERE +w BETWEEN 200 AND 300)
         AND z IN (SELECT z FROM t1 WHERE +w BETWEEN 10 AND 20)
    }
  } {}
  do_test where2-8.20 {
    execsql {
      SELECT w FROM tx
       WHERE x IN (SELECT x FROM t1 WHERE +w BETWEEN 200 AND 300)
         AND y IN (SELECT y FROM t1 WHERE +w BETWEEN 10 AND 20)
         AND z IN (SELECT z FROM t1 WHERE +w BETWEEN 10 AND 20)
    }
  } {}
}  

# Make sure WHERE clauses of the form A=1 AND (B=2 OR B=3) are optimized
# when we have an index on A and B.
#
ifcapable or_opt&&tclvar {
  do_test where2-9.1 {
    execsql {
      BEGIN;
      CREATE TABLE t10(a,b,c);
      INSERT INTO t10 VALUES(1,1,1);
      INSERT INTO t10 VALUES(1,2,2);
      INSERT INTO t10 VALUES(1,3,3);
    }
    for {set i 4} {$i<=1000} {incr i} {
      execsql {INSERT INTO t10 VALUES(1,$i,$i)}
    }
    execsql {
      CREATE INDEX i10 ON t10(a,b);
      COMMIT;
      SELECT count(*) FROM t10;
    }
  } 1000
  ifcapable subquery {
    do_test where2-9.2 {
      count {
        SELECT * FROM t10 WHERE a=1 AND (b=2 OR b=3)
      }
    } {1 2 2 1 3 3 7}
  }
}

finish_test

Added test/where3.test.

















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# 2006 January 31
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the join reordering optimization
# in cases that include a LEFT JOIN.
#
# $Id: where3.test,v 1.4 2008/04/17 19:14:02 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# The following is from ticket #1652.
#
# A comma join then a left outer join:  A,B left join C.
# Arrange indices so that the B table is chosen to go first.
# Also put an index on C, but make sure that A is chosen before C.
#
do_test where3-1.1 {
  execsql {
    CREATE TABLE t1(a, b);
    CREATE TABLE t2(p, q);
    CREATE TABLE t3(x, y);
    
    INSERT INTO t1 VALUES(111,'one');
    INSERT INTO t1 VALUES(222,'two');
    INSERT INTO t1 VALUES(333,'three');
    
    INSERT INTO t2 VALUES(1,111);
    INSERT INTO t2 VALUES(2,222);
    INSERT INTO t2 VALUES(4,444);
    CREATE INDEX t2i1 ON t2(p);
    
    INSERT INTO t3 VALUES(999,'nine');
    CREATE INDEX t3i1 ON t3(x);
    
    SELECT * FROM t1, t2 LEFT JOIN t3 ON q=x WHERE p=2 AND a=q;
  }
} {222 two 2 222 {} {}}

ifcapable explain {
  do_test where3-1.1.1 {
     explain_no_trace {SELECT * FROM t1, t2 LEFT JOIN t3 ON q=x
                        WHERE p=2 AND a=q}
  } [explain_no_trace {SELECT * FROM t1, t2 LEFT JOIN t3 ON x=q
                        WHERE p=2 AND a=q}]
}

# Ticket #1830
#
# This is similar to the above but with the LEFT JOIN on the
# other side.
#
do_test where3-1.2 {
  execsql {
    CREATE TABLE parent1(parent1key, child1key, Child2key, child3key);
    CREATE TABLE child1 ( child1key NVARCHAR, value NVARCHAR );
    CREATE UNIQUE INDEX PKIDXChild1 ON child1 ( child1key );
    CREATE TABLE child2 ( child2key NVARCHAR, value NVARCHAR );

    INSERT INTO parent1(parent1key,child1key,child2key)
       VALUES ( 1, 'C1.1', 'C2.1' );
    INSERT INTO child1 ( child1key, value ) VALUES ( 'C1.1', 'Value for C1.1' );
    INSERT INTO child2 ( child2key, value ) VALUES ( 'C2.1', 'Value for C2.1' );

    INSERT INTO parent1 ( parent1key, child1key, child2key )
       VALUES ( 2, 'C1.2', 'C2.2' );
    INSERT INTO child2 ( child2key, value ) VALUES ( 'C2.2', 'Value for C2.2' );

    INSERT INTO parent1 ( parent1key, child1key, child2key )
       VALUES ( 3, 'C1.3', 'C2.3' );
    INSERT INTO child1 ( child1key, value ) VALUES ( 'C1.3', 'Value for C1.3' );
    INSERT INTO child2 ( child2key, value ) VALUES ( 'C2.3', 'Value for C2.3' );

    SELECT parent1.parent1key, child1.value, child2.value
    FROM parent1
    LEFT OUTER JOIN child1 ON child1.child1key = parent1.child1key
    INNER JOIN child2 ON child2.child2key = parent1.child2key;
  }
} {1 {Value for C1.1} {Value for C2.1} 2 {} {Value for C2.2} 3 {Value for C1.3} {Value for C2.3}}

ifcapable explain {
  do_test where3-1.2.1 {
     explain_no_trace {
       SELECT parent1.parent1key, child1.value, child2.value
       FROM parent1
       LEFT OUTER JOIN child1 ON child1.child1key = parent1.child1key
       INNER JOIN child2 ON child2.child2key = parent1.child2key;
     }
  } [explain_no_trace {
       SELECT parent1.parent1key, child1.value, child2.value
       FROM parent1
       LEFT OUTER JOIN child1 ON parent1.child1key = child1.child1key 
       INNER JOIN child2 ON child2.child2key = parent1.child2key;
     }]
}

# This procedure executes the SQL.  Then it appends 
# the ::sqlite_query_plan variable.
#
proc queryplan {sql} {
  set ::sqlite_sort_count 0
  set data [execsql $sql]
  return [concat $data $::sqlite_query_plan]
}


# If you have a from clause of the form:   A B C left join D
# then make sure the query optimizer is able to reorder the 
# A B C part anyway it wants. 
#
# Following the fix to ticket #1652, there was a time when
# the C table would not reorder.  So the following reorderings
# were possible:
#
#            A B C left join D
#            B A C left join D
#
# But these reorders were not allowed
#
#            C A B left join D
#            A C B left join D
#            C B A left join D
#            B C A left join D
#
# The following tests are here to verify that the latter four
# reorderings are allowed again.
#
do_test where3-2.1 {
  execsql {
    CREATE TABLE tA(apk integer primary key, ax);
    CREATE TABLE tB(bpk integer primary key, bx);
    CREATE TABLE tC(cpk integer primary key, cx);
    CREATE TABLE tD(dpk integer primary key, dx);
  }
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE cpk=bx AND bpk=ax
  }
} {tA {} tB * tC * tD *}
do_test where3-2.1.1 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON cx=dpk
     WHERE cpk=bx AND bpk=ax
  }
} {tA {} tB * tC * tD *}
do_test where3-2.1.2 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON cx=dpk
     WHERE bx=cpk AND bpk=ax
  }
} {tA {} tB * tC * tD *}
do_test where3-2.1.3 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON cx=dpk
     WHERE bx=cpk AND ax=bpk
  }
} {tA {} tB * tC * tD *}
do_test where3-2.1.4 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE bx=cpk AND ax=bpk
  }
} {tA {} tB * tC * tD *}
do_test where3-2.1.5 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE cpk=bx AND ax=bpk
  }
} {tA {} tB * tC * tD *}
do_test where3-2.2 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE cpk=bx AND apk=bx
  }
} {tB {} tA * tC * tD *}
do_test where3-2.3 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE cpk=bx AND apk=bx
  }
} {tB {} tA * tC * tD *}
do_test where3-2.4 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE apk=cx AND bpk=ax
  }
} {tC {} tA * tB * tD *}
do_test where3-2.5 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE cpk=ax AND bpk=cx
  }
} {tA {} tC * tB * tD *}
do_test where3-2.5 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE bpk=cx AND apk=bx
  }
} {tC {} tB * tA * tD *}
do_test where3-2.6 {
  queryplan {
    SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx
     WHERE cpk=bx AND apk=cx
  }
} {tB {} tC * tA * tD *}


finish_test

Added test/where4.test.



































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# 2006 October 27
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the use of indices in WHERE clauses.
# This file was created when support for optimizing IS NULL phrases
# was added.  And so the principle purpose of this file is to test
# that IS NULL phrases are correctly optimized.  But you can never
# have too many tests, so some other tests are thrown in as well.
#
# $Id: where4.test,v 1.6 2007/12/10 05:03:48 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !tclvar||!bloblit {
  finish_test
  return
}

# Build some test data
#
do_test where4-1.0 {
  execsql {
    CREATE TABLE t1(w, x, y);
    CREATE INDEX i1wxy ON t1(w,x,y);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 VALUES(1,NULL,3);
    INSERT INTO t1 VALUES('a','b','c');
    INSERT INTO t1 VALUES('a',NULL,'c');
    INSERT INTO t1 VALUES(X'78',x'79',x'7a');
    INSERT INTO t1 VALUES(X'78',NULL,X'7A');
    INSERT INTO t1 VALUES(NULL,NULL,NULL);
    SELECT count(*) FROM t1;
  }
} {7}

# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_search_count 0
  return [concat [execsql $sql] $::sqlite_search_count]
}

# Verify that queries use an index.  We are using the special variable
# "sqlite_search_count" which tallys the number of executions of MoveTo
# and Next operators in the VDBE.  By verifing that the search count is
# small we can be assured that indices are being used properly.
#
do_test where4-1.1 {
  count {SELECT rowid FROM t1 WHERE w IS NULL}
} {7 2}
do_test where4-1.2 {
  count {SELECT rowid FROM t1 WHERE +w IS NULL}
} {7 6}
do_test where4-1.3 {
  count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL}
} {2 2}
do_test where4-1.4 {
  count {SELECT rowid FROM t1 WHERE w=1 AND +x IS NULL}
} {2 3}
do_test where4-1.5 {
  count {SELECT rowid FROM t1 WHERE w=1 AND x>0}
} {1 2}
do_test where4-1.6 {
  count {SELECT rowid FROM t1 WHERE w=1 AND x<9}
} {1 3}
do_test where4-1.7 {
  count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL AND y=3}
} {2 2}
do_test where4-1.8 {
  count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL AND y>2}
} {2 2}
do_test where4-1.9 {
  count {SELECT rowid FROM t1 WHERE w='a' AND x IS NULL AND y='c'}
} {4 2}
do_test where4-1.10 {
  count {SELECT rowid FROM t1 WHERE w=x'78' AND x IS NULL}
} {6 2}
do_test where4-1.11 {
  count {SELECT rowid FROM t1 WHERE w=x'78' AND x IS NULL AND y=123}
} {1}
do_test where4-1.12 {
  count {SELECT rowid FROM t1 WHERE w=x'78' AND x IS NULL AND y=x'7A'}
} {6 2}
do_test where4-1.13 {
  count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL}
} {7 2}
do_test where4-1.14 {
  count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y IS NULL}
} {7 2}
do_test where4-1.15 {
  count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y<0}
} {2}
do_test where4-1.16 {
  count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y>=0}
} {1}

do_test where4-2.1 {
  execsql {SELECT rowid FROM t1 ORDER BY w, x, y}
} {7 2 1 4 3 6 5}
do_test where4-2.2 {
  execsql {SELECT rowid FROM t1 ORDER BY w DESC, x, y}
} {6 5 4 3 2 1 7}
do_test where4-2.3 {
  execsql {SELECT rowid FROM t1 ORDER BY w, x DESC, y}
} {7 1 2 3 4 5 6}


# Ticket #2177
#
# Suppose you have a left join where the right table of the left
# join (the one that can be NULL) has an index on two columns.
# The first indexed column is used in the ON clause of the join.
# The second indexed column is used in the WHERE clause with an IS NULL
# constraint.  It is not allowed to use the IS NULL optimization to
# optimize the query because the second column might be NULL because
# the right table did not match - something the index does not know
# about.
#
do_test where4-3.1 {
  execsql {
    CREATE TABLE t2(a);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    INSERT INTO t2 VALUES(3);
    CREATE TABLE t3(x,y,UNIQUE(x,y));
    INSERT INTO t3 VALUES(1,11);
    INSERT INTO t3 VALUES(2,NULL);
 
    SELECT * FROM t2 LEFT JOIN t3 ON a=x WHERE +y IS NULL;
  }
} {2 2 {} 3 {} {}}
do_test where4-3.2 {
  execsql {
    SELECT * FROM t2 LEFT JOIN t3 ON a=x WHERE y IS NULL;
  }
} {2 2 {} 3 {} {}}

# Ticket #2189.  Probably the same bug as #2177.
#
do_test where4-4.1 {
  execsql {
    CREATE TABLE test(col1 TEXT PRIMARY KEY);
    INSERT INTO test(col1) values('a');
    INSERT INTO test(col1) values('b');
    INSERT INTO test(col1) values('c');
    CREATE TABLE test2(col1 TEXT PRIMARY KEY);
    INSERT INTO test2(col1) values('a');
    INSERT INTO test2(col1) values('b');
    INSERT INTO test2(col1) values('c');
    SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1
      WHERE +t2.col1 IS NULL;
  }
} {}
do_test where4-4.2 {
  execsql {
    SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1
      WHERE t2.col1 IS NULL;
  }
} {}
do_test where4-4.3 {
  execsql {
    SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1
      WHERE +t1.col1 IS NULL;
  }
} {}
do_test where4-4.4 {
  execsql {
    SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1
      WHERE t1.col1 IS NULL;
  }
} {}

# Ticket #2273.  Problems with IN operators and NULLs.
#
ifcapable subquery {
do_test where4-5.1 {
  execsql {
    CREATE TABLE t4(x,y,z,PRIMARY KEY(x,y));
  }
  execsql {
    SELECT *
      FROM t2 LEFT JOIN t4 b1
              LEFT JOIN t4 b2 ON b2.x=b1.x AND b2.y IN (b1.y);
  }
} {1 {} {} {} {} {} {} 2 {} {} {} {} {} {} 3 {} {} {} {} {} {}}
do_test where4-5.2 {
  execsql {
    INSERT INTO t4 VALUES(1,1,11);
    INSERT INTO t4 VALUES(1,2,12);
    INSERT INTO t4 VALUES(1,3,13);
    INSERT INTO t4 VALUES(2,2,22);
    SELECT rowid FROM t4 WHERE x IN (1,9,2,5) AND y IN (1,3,NULL,2) AND z!=13;
  }
} {1 2 4}
do_test where4-5.3 {
  execsql {
    SELECT rowid FROM t4 WHERE x IN (1,9,NULL,2) AND y IN (1,3,2) AND z!=13;
  }
} {1 2 4}
do_test where4-6.1 {
  execsql {
    CREATE TABLE t5(a,b,c,d,e,f,UNIQUE(a,b,c,d,e,f));
    INSERT INTO t5 VALUES(1,1,1,1,1,11111);
    INSERT INTO t5 VALUES(2,2,2,2,2,22222);
    INSERT INTO t5 VALUES(1,2,3,4,5,12345);
    INSERT INTO t5 VALUES(2,3,4,5,6,23456);
  }
  execsql {
    SELECT rowid FROM t5
     WHERE a IN (1,9,2) AND b=2 AND c IN (1,2,3,4) AND d>0
  }
} {3 2}
do_test where4-6.2 {
  execsql {
    SELECT rowid FROM t5
     WHERE a IN (1,NULL,2) AND b=2 AND c IN (1,2,3,4) AND d>0
  }
} {3 2}
do_test where4-7.1 {
  execsql {
    CREATE TABLE t6(y,z,PRIMARY KEY(y,z));
  }
  execsql {
    SELECT * FROM t6 WHERE y=NULL AND z IN ('hello');
  }
} {}

integrity_check {where4-99.0}

do_test where4-7.1 {
  execsql {
    BEGIN;
    CREATE TABLE t8(a, b, c, d);
    CREATE INDEX t8_i ON t8(a, b, c);
    CREATE TABLE t7(i);

    INSERT INTO t7 VALUES(1);
    INSERT INTO t7 SELECT i*2 FROM t7;
    INSERT INTO t7 SELECT i*2 FROM t7;
    INSERT INTO t7 SELECT i*2 FROM t7;
    INSERT INTO t7 SELECT i*2 FROM t7;
    INSERT INTO t7 SELECT i*2 FROM t7;
    INSERT INTO t7 SELECT i*2 FROM t7;

    COMMIT;
  }
} {}

# At one point the sub-select inside the aggregate sum() function in the
# following query was leaking a couple of stack entries. This query 
# runs the SELECT in a loop enough times that an assert() fails. Or rather,
# did fail before the bug was fixed.
#
do_test where4-7.2 {
  execsql {
    SELECT sum((
      SELECT d FROM t8 WHERE a = i AND b = i AND c < NULL
    )) FROM t7;
  }
} {{}}

}; #ifcapable subquery

finish_test

Added test/where5.test.

































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# 2007 June 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing NULL comparisons in the WHERE clause.
# See ticket #2404.
#
# $Id: where5.test,v 1.2 2007/06/08 08:43:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
do_test where5-1.0 {
  execsql {
    CREATE TABLE t1(x TEXT);
    CREATE TABLE t2(x INTEGER);
    CREATE TABLE t3(x INTEGER PRIMARY KEY);
    INSERT INTO t1 VALUES(-1);
    INSERT INTO t1 VALUES(0);
    INSERT INTO t1 VALUES(1);
    INSERT INTO t2 SELECT * FROM t1;
    INSERT INTO t3 SELECT * FROM t2;
  }
  execsql {
    SELECT * FROM t1 WHERE x<0
  }
} {-1}
do_test where5-1.1 {
  execsql {
    SELECT * FROM t1 WHERE x<=0
  }
} {-1 0}
do_test where5-1.2 {
  execsql {
    SELECT * FROM t1 WHERE x=0
  }
} {0}
do_test where5-1.3 {
  execsql {
    SELECT * FROM t1 WHERE x>=0
  }
} {0 1}
do_test where5-1.4 {
  execsql {
    SELECT * FROM t1 WHERE x>0
  }
} {1}
do_test where5-1.5 {
  execsql {
    SELECT * FROM t1 WHERE x<>0
  }
} {-1 1}
do_test where5-1.6 {
  execsql {
    SELECT * FROM t1 WHERE x<NULL
  }
} {}
do_test where5-1.7 {
  execsql {
    SELECT * FROM t1 WHERE x<=NULL
  }
} {}
do_test where5-1.8 {
  execsql {
    SELECT * FROM t1 WHERE x=NULL
  }
} {}
do_test where5-1.9 {
  execsql {
    SELECT * FROM t1 WHERE x>=NULL
  }
} {}
do_test where5-1.10 {
  execsql {
    SELECT * FROM t1 WHERE x>NULL
  }
} {}
do_test where5-1.11 {
  execsql {
    SELECT * FROM t1 WHERE x!=NULL
  }
} {}
do_test where5-1.12 {
  execsql {
    SELECT * FROM t1 WHERE x IS NULL
  }
} {}
do_test where5-1.13 {
  execsql {
    SELECT * FROM t1 WHERE x IS NOT NULL
  }
} {-1 0 1}


do_test where5-2.0 {
  execsql {
    SELECT * FROM t2 WHERE x<0
  }
} {-1}
do_test where5-2.1 {
  execsql {
    SELECT * FROM t2 WHERE x<=0
  }
} {-1 0}
do_test where5-2.2 {
  execsql {
    SELECT * FROM t2 WHERE x=0
  }
} {0}
do_test where5-2.3 {
  execsql {
    SELECT * FROM t2 WHERE x>=0
  }
} {0 1}
do_test where5-2.4 {
  execsql {
    SELECT * FROM t2 WHERE x>0
  }
} {1}
do_test where5-2.5 {
  execsql {
    SELECT * FROM t2 WHERE x<>0
  }
} {-1 1}
do_test where5-2.6 {
  execsql {
    SELECT * FROM t2 WHERE x<NULL
  }
} {}
do_test where5-2.7 {
  execsql {
    SELECT * FROM t2 WHERE x<=NULL
  }
} {}
do_test where5-2.8 {
  execsql {
    SELECT * FROM t2 WHERE x=NULL
  }
} {}
do_test where5-2.9 {
  execsql {
    SELECT * FROM t2 WHERE x>=NULL
  }
} {}
do_test where5-2.10 {
  execsql {
    SELECT * FROM t2 WHERE x>NULL
  }
} {}
do_test where5-2.11 {
  execsql {
    SELECT * FROM t2 WHERE x!=NULL
  }
} {}
do_test where5-2.12 {
  execsql {
    SELECT * FROM t2 WHERE x IS NULL
  }
} {}
do_test where5-2.13 {
  execsql {
    SELECT * FROM t2 WHERE x IS NOT NULL
  }
} {-1 0 1}


do_test where5-3.0 {
  execsql {
    SELECT * FROM t3 WHERE x<0
  }
} {-1}
do_test where5-3.1 {
  execsql {
    SELECT * FROM t3 WHERE x<=0
  }
} {-1 0}
do_test where5-3.2 {
  execsql {
    SELECT * FROM t3 WHERE x=0
  }
} {0}
do_test where5-3.3 {
  execsql {
    SELECT * FROM t3 WHERE x>=0
  }
} {0 1}
do_test where5-3.4 {
  execsql {
    SELECT * FROM t3 WHERE x>0
  }
} {1}
do_test where5-3.5 {
  execsql {
    SELECT * FROM t3 WHERE x<>0
  }
} {-1 1}
do_test where5-3.6 {
  execsql {
    SELECT * FROM t3 WHERE x<NULL
  }
} {}
do_test where5-3.7 {
  execsql {
    SELECT * FROM t3 WHERE x<=NULL
  }
} {}
do_test where5-3.8 {
  execsql {
    SELECT * FROM t3 WHERE x=NULL
  }
} {}
do_test where5-3.9 {
  execsql {
    SELECT * FROM t3 WHERE x>=NULL
  }
} {}
do_test where5-3.10 {
  execsql {
    SELECT * FROM t3 WHERE x>NULL
  }
} {}
do_test where5-3.11 {
  execsql {
    SELECT * FROM t3 WHERE x!=NULL
  }
} {}
do_test where5-3.12 {
  execsql {
    SELECT * FROM t3 WHERE x IS NULL
  }
} {}
do_test where5-3.13 {
  execsql {
    SELECT * FROM t3 WHERE x IS NOT NULL
  }
} {-1 0 1}

do_test where5-4.0 {
  execsql {
    SELECT x<NULL FROM t3
  }
} {{} {} {}}
do_test where5-4.1 {
  execsql {
    SELECT x<=NULL FROM t3
  }
} {{} {} {}}
do_test where5-4.2 {
  execsql {
    SELECT x==NULL FROM t3
  }
} {{} {} {}}
do_test where5-4.3 {
  execsql {
    SELECT x>NULL FROM t3
  }
} {{} {} {}}
do_test where5-4.4 {
  execsql {
    SELECT x>=NULL FROM t3
  }
} {{} {} {}}
do_test where5-4.5 {
  execsql {
    SELECT x!=NULL FROM t3
  }
} {{} {} {}}
do_test where5-4.6 {
  execsql {
    SELECT x IS NULL FROM t3
  }
} {0 0 0}
do_test where5-4.7 {
  execsql {
    SELECT x IS NOT NULL FROM t3
  }
} {1 1 1}

finish_test

Added test/where6.test.





































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# 2007 June 8
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing that terms in the ON clause of
# a LEFT OUTER JOIN are not used with indices.  See ticket #3015.
#
# $Id: where6.test,v 1.2 2008/04/17 19:14:02 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Build some test data
#
do_test where6-1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY,b,c);
    INSERT INTO t1 VALUES(1,3,1);
    INSERT INTO t1 VALUES(2,4,2);
    CREATE TABLE t2(x INTEGER PRIMARY KEY);
    INSERT INTO t2 VALUES(3);

    SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1;
  }
} {1 3 1 3 2 4 2 {}}
do_test where6-1.2 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b AND c=1;
  }
} {1 3 1 3 2 4 2 {}}
do_test where6-1.3 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c;
  }
} {1 3 1 3 2 4 2 {}}
do_test where6-1.4 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b=x AND 1=c;
  }
} {1 3 1 3 2 4 2 {}}

ifcapable explain {
  do_test where6-1.5 {
     explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c}
  } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1}]
  do_test where6-1.6 {
     explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE 1=c}
  } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1}]
}

do_test where6-1.11 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1;
  }
} {1 3 1 3}
do_test where6-1.12 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE c=1;
  }
} {1 3 1 3}
do_test where6-1.13 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE 1=c;
  }
} {1 3 1 3}



do_test where6-2.1 {
  execsql {
    CREATE INDEX i1 ON t1(c);

    SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1;
  }
} {1 3 1 3 2 4 2 {}}
do_test where6-2.2 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b AND c=1;
  }
} {1 3 1 3 2 4 2 {}}
do_test where6-2.3 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c;
  }
} {1 3 1 3 2 4 2 {}}
do_test where6-2.4 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b=x AND 1=c;
  }
} {1 3 1 3 2 4 2 {}}

ifcapable explain {
  do_test where6-2.5 {
     explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c}
  } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1}]
  do_test where6-2.6 {
     explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE 1=c}
  } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1}]
}


do_test where6-2.11 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1;
  }
} {1 3 1 3}
do_test where6-2.12 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE c=1;
  }
} {1 3 1 3}
do_test where6-2.13 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE 1=c;
  }
} {1 3 1 3}
do_test where6-2.14 {
  execsql {
    SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE 1=c;
  }
} {1 3 1 3}

finish_test

Added test/where7.test.

more than 10,000 changes

Added test/where8.test.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# 2008 December 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# is testing of where.c. More specifically, the focus is the optimization
# of WHERE clauses that feature the OR operator.
#
# $Id: where8.test,v 1.9 2009/07/31 06:14:52 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Test organization:
#
#   where8-1.*: Tests to demonstrate simple cases work with a single table
#               in the FROM clause.
#
#   where8-2.*: Tests surrounding virtual tables and the OR optimization.
#
#   where8-3.*: Tests with more than one table in the FROM clause.
# 

proc execsql_status {sql {db db}} {
  set result [uplevel $db eval [list $sql]]
  concat $result [db status step] [db status sort]
}

proc execsql_status2 {sql {db db}} {
  set ::sqlite_search_count 0
  set result [uplevel [list execsql_status $sql $db]]
  concat $result $::sqlite_search_count
}

do_test where8-1.1 {
  execsql {
    CREATE TABLE t1(a, b TEXT, c);
    CREATE INDEX i1 ON t1(a);
    CREATE INDEX i2 ON t1(b);

    INSERT INTO t1 VALUES(1,  'one',   'I');
    INSERT INTO t1 VALUES(2,  'two',   'II');
    INSERT INTO t1 VALUES(3,  'three', 'III');
    INSERT INTO t1 VALUES(4,  'four',  'IV');
    INSERT INTO t1 VALUES(5,  'five',  'V');
    INSERT INTO t1 VALUES(6,  'six',   'VI');
    INSERT INTO t1 VALUES(7,  'seven', 'VII');
    INSERT INTO t1 VALUES(8,  'eight', 'VIII');
    INSERT INTO t1 VALUES(9,  'nine',  'IX');
    INSERT INTO t1 VALUES(10, 'ten',   'X');
  }
} {}

do_test where8-1.2 { 
  execsql_status2 { SELECT c FROM t1 WHERE a = 1 OR b = 'nine' }
} {I IX 0 0 6}

do_test where8-1.3 { 
  execsql_status2 { SELECT c FROM t1 WHERE a > 8 OR b = 'two' }
} {IX X II 0 0 6}

do_test where8-1.4 { 
  execsql_status2 { SELECT c FROM t1 WHERE a > 8 OR b GLOB 't*' }
} {IX X III II 0 0 9}

do_test where8-1.5 { 
  execsql_status2 { SELECT c FROM t1 WHERE a > 8 OR b GLOB 'f*' }
} {IX X V IV 0 0 9}

do_test where8-1.6 { 
  execsql_status { SELECT c FROM t1 WHERE a = 1 OR b = 'three' ORDER BY rowid }
} {I III 0 1}

do_test where8-1.7 { 
  execsql_status { SELECT c FROM t1 WHERE a = 1 OR b = 'three' ORDER BY a }
} {I III 0 1}

do_test where8-1.8 {
  # 18 searches. 9 on the index cursor and 9 on the table cursor.
  execsql_status2 { SELECT c FROM t1 WHERE a > 1 AND c LIKE 'I%' }
} {II III IV IX 0 0 18}

do_test where8-1.9 {
  execsql_status2 { SELECT c FROM t1 WHERE a >= 9 OR b <= 'eight' }
} {IX X VIII 0 0 6}

do_test where8-1.10 {
  execsql_status2 { 
    SELECT c FROM t1 WHERE (a >= 9 AND c != 'X') OR b <= 'eight' 
  }
} {IX VIII 0 0 6}

do_test where8-1.11 {
  execsql_status2 { 
    SELECT c FROM t1 WHERE (a >= 4 AND a <= 6) OR b = 'nine' 
  }
} {IV V VI IX 0 0 10}

do_test where8-1.12.1 {
  execsql_status2 { 
    SELECT c FROM t1 WHERE a IN(1, 2, 3) OR a = 5
  }
} {I II III V 0 0 14}

do_test where8-1.12.2 {
  execsql_status2 { 
    SELECT c FROM t1 WHERE +a IN(1, 2, 3) OR +a = 5
  }
} {I II III V 9 0 9}

do_test where8-1.13 {
  execsql_status2 {
    SELECT c FROM t1
    WHERE a = 2 OR b = 'three' OR a = 4 OR b = 'five' OR a = 6
    ORDER BY rowid
  }
} {II III IV V VI 0 1 18}
do_test where8-1.14 {
  execsql_status2 {
    SELECT c FROM t1
    WHERE 
      a = 2 OR b = 'three' OR a = 4 OR b = 'five' OR a = 6 OR
      b = 'seven' OR a = 8 OR b = 'nine' OR a = 10
    ORDER BY rowid
  }
} {II III IV V VI VII VIII IX X 0 1 33}

do_test where8-1.15 {
  execsql_status2 {
    SELECT c FROM t1 WHERE 
      a BETWEEN 2 AND 4 OR b = 'nine'
    ORDER BY rowid
  }
} {II III IV IX 0 1 12}


#--------------------------------------------------------------------------
# Tests where8-2.*: Virtual tables
# 

if 0 {
ifcapable vtab {
  # Register the 'echo' module used for testing virtual tables.
  #
  register_echo_module [sqlite3_connection_pointer db]

  do_test where8-2.1 {
    execsql {
      CREATE VIRTUAL TABLE e1 USING echo(t1);
      SELECT b FROM e1;
    }
  } {one two three four five six seven eight nine ten}

  do_test where8-2.2.1 {
    set echo_module ""
    execsql {
      SELECT c FROM e1 WHERE a=1 OR b='three';
    }
  } {I III}
  do_test where8-2.2.2 {
    set echo_module
  } {TODO: What should this be?}
}
}

#--------------------------------------------------------------------------
# Tests where8-3.*: Cases with multiple tables in the FROM clause.
# 
do_test where8-3.1 {
  execsql {
    CREATE TABLE t2(d, e, f);
    CREATE INDEX i3 ON t2(d);
    CREATE INDEX i4 ON t2(e);

    INSERT INTO t2 VALUES(1,  NULL,         'I');
    INSERT INTO t2 VALUES(2,  'four',       'IV');
    INSERT INTO t2 VALUES(3,  NULL,         'IX');
    INSERT INTO t2 VALUES(4,  'sixteen',    'XVI');
    INSERT INTO t2 VALUES(5,  NULL,         'XXV');
    INSERT INTO t2 VALUES(6,  'thirtysix',  'XXXVI');
    INSERT INTO t2 VALUES(7,  'fortynine',  'XLIX');
    INSERT INTO t2 VALUES(8,  'sixtyeight', 'LXIV');
    INSERT INTO t2 VALUES(9,  'eightyone',  'LXXXIX');
    INSERT INTO t2 VALUES(10, NULL,         'C');
  }
} {}

do_test where8-3.2 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE b=e
  }
} {4 2 9 0}

do_test where8-3.3 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE (a = 2 OR a = 3) AND d = 6
  }
} {2 6 3 6 0 0}

do_test where8-3.4 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE (a = 2 OR a = 3) AND d = a
  }
} {2 2 3 3 0 0}

do_test where8-3.5 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE (a = 2 OR a = 3) AND (d = a OR e = 'sixteen')
  }
} {2 2 2 4 3 3 3 4 0 0}

do_test where8-3.6 {
  # The first part of the WHERE clause in this query, (a=2 OR a=3) is
  # transformed into "a IN (2, 3)". This is why the sort is required.
  #
  execsql_status {
    SELECT a, d 
    FROM t1, t2 
    WHERE (a = 2 OR a = 3) AND (d = a OR e = 'sixteen')
    ORDER BY t1.rowid
  }
} {2 2 2 4 3 3 3 4 0 1}
do_test where8-3.7 {
  execsql_status {
    SELECT a, d 
    FROM t1, t2 
    WHERE a = 2 AND (d = a OR e = 'sixteen')
    ORDER BY t1.rowid
  }
} {2 2 2 4 0 0}
do_test where8-3.8 {
  execsql_status {
    SELECT a, d 
    FROM t1, t2 
    WHERE (a = 2 OR b = 'three') AND (d = a OR e = 'sixteen')
    ORDER BY t1.rowid
  }
} {2 2 2 4 3 3 3 4 0 1}

do_test where8-3.9 {
  # The "OR c = 'IX'" term forces a linear scan.
  execsql_status {
    SELECT a, d 
    FROM t1, t2 
    WHERE (a = 2 OR b = 'three' OR c = 'IX') AND (d = a OR e = 'sixteen')
    ORDER BY t1.rowid
  }
} {2 2 2 4 3 3 3 4 9 9 9 4 9 0}

do_test where8-3.10 {
  execsql_status {
    SELECT d FROM t2 WHERE e IS NULL OR e = 'four'
  }
} {1 3 5 10 2 0 0}

do_test where8-3.11 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE (a=d OR b=e) AND a<5 ORDER BY a
  }
} {1 1 2 2 3 3 4 2 4 4 0 0}
do_test where8-3.12 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE (a=d OR b=e) AND +a<5 ORDER BY a
  }
} {1 1 2 2 3 3 4 2 4 4 0 0}
do_test where8-3.13 {
  execsql_status {
    SELECT a, d FROM t1, t2 WHERE (a=d OR b=e) AND +a<5
  }
} {1 1 2 2 3 3 4 2 4 4 9 0}

do_test where8-3.14 {
  execsql_status {
    SELECT c FROM t1 WHERE a > (SELECT d FROM t2 WHERE e = b) OR a = 5
  }
} {IV V 9 0}

do_test where8-3.15 {
  execsql_status {
    SELECT c FROM t1, t2 WHERE a BETWEEN 1 AND 2 OR a = (
      SELECT sum(e IS NULL) FROM t2 AS inner WHERE t2.d>inner.d
    )
  }
} {I II I II I II I II I II I II III I II III I II III I II III I II III 9 0}

#-----------------------------------------------------------------------
# The following tests - where8-4.* - verify that adding or removing 
# indexes does not change the results returned by various queries.
#
do_test where8-4.1 {
  execsql {
    BEGIN;
    CREATE TABLE t3(a INTEGER, b REAL, c TEXT);
    CREATE TABLE t4(f INTEGER, g REAL, h TEXT);
    INSERT INTO t3 VALUES('hills', NULL, 1415926535);
    INSERT INTO t3 VALUES('and', 'of', NULL);
    INSERT INTO t3 VALUES('have', 'towering', 53594.08128);
    INSERT INTO t3 VALUES(NULL, 45.64856692, 'Not');
    INSERT INTO t3 VALUES('same', 5028841971, NULL);
    INSERT INTO t3 VALUES('onlookers', 'in', 8214808651);
    INSERT INTO t3 VALUES(346.0348610, 2643383279, NULL);
    INSERT INTO t3 VALUES(1415926535, 'of', 'are');
    INSERT INTO t3 VALUES(NULL, 0.4811174502, 'snapshots');
    INSERT INTO t3 VALUES('over', 'the', 8628034825);
    INSERT INTO t3 VALUES(8628034825, 66.59334461, 2847564.823);
    INSERT INTO t3 VALUES('onlookers', 'same', 'and');
    INSERT INTO t3 VALUES(NULL, 'light', 6939937510);
    INSERT INTO t3 VALUES('from', 'their', 'viewed');
    INSERT INTO t3 VALUES('from', 'Alpine', 'snapshots');
    INSERT INTO t3 VALUES('from', 'sometimes', 'unalike');
    INSERT INTO t3 VALUES(1339.360726, 'light', 'have');
    INSERT INTO t3 VALUES(6939937510, 3282306647, 'other');
    INSERT INTO t3 VALUES('paintings', 8628034825, 'all');
    INSERT INTO t3 VALUES('paintings', NULL, 'same');
    INSERT INTO t3 VALUES('Alpine', 378678316.5, 'unalike');
    INSERT INTO t3 VALUES('Alpine', NULL, 'same');
    INSERT INTO t3 VALUES(1339.360726, 2847564.823, 'over');
    INSERT INTO t3 VALUES('villages', 'their', 'have');
    INSERT INTO t3 VALUES('unalike', 'remarkably', 'in');
    INSERT INTO t3 VALUES('and', 8979323846, 'and');
    INSERT INTO t3 VALUES(NULL, 1415926535, 'an');
    INSERT INTO t3 VALUES(271.2019091, 8628034825, 0.4811174502);
    INSERT INTO t3 VALUES('all', 3421170679, 'the');
    INSERT INTO t3 VALUES('Not', 'and', 1415926535);
    INSERT INTO t3 VALUES('of', 'other', 'light');
    INSERT INTO t3 VALUES(NULL, 'towering', 'Not');
    INSERT INTO t3 VALUES(346.0348610, NULL, 'other');
    INSERT INTO t3 VALUES('Not', 378678316.5, NULL);
    INSERT INTO t3 VALUES('snapshots', 8628034825, 'of');
    INSERT INTO t3 VALUES(3282306647, 271.2019091, 'and');
    INSERT INTO t3 VALUES(50.58223172, 378678316.5, 5028841971);
    INSERT INTO t3 VALUES(50.58223172, 2643383279, 'snapshots');
    INSERT INTO t3 VALUES('writings', 8979323846, 8979323846);
    INSERT INTO t3 VALUES('onlookers', 'his', 'in');
    INSERT INTO t3 VALUES('unalike', 8628034825, 1339.360726);
    INSERT INTO t3 VALUES('of', 'Alpine', 'and');
    INSERT INTO t3 VALUES('onlookers', NULL, 'from');
    INSERT INTO t3 VALUES('writings', 'it', 1339.360726);
    INSERT INTO t3 VALUES('it', 'and', 'villages');
    INSERT INTO t3 VALUES('an', 'the', 'villages');
    INSERT INTO t3 VALUES(8214808651, 8214808651, 'same');
    INSERT INTO t3 VALUES(346.0348610, 'light', 1415926535);
    INSERT INTO t3 VALUES(NULL, 8979323846, 'and');
    INSERT INTO t3 VALUES(NULL, 'same', 1339.360726);
    INSERT INTO t4 VALUES('his', 'from', 'an');
    INSERT INTO t4 VALUES('snapshots', 'or', NULL);
    INSERT INTO t4 VALUES('Alpine', 'have', 'it');
    INSERT INTO t4 VALUES('have', 'peak', 'remarkably');
    INSERT INTO t4 VALUES('hills', NULL, 'Not');
    INSERT INTO t4 VALUES('same', 'from', 2643383279);
    INSERT INTO t4 VALUES('have', 'angle', 8628034825);
    INSERT INTO t4 VALUES('sometimes', 'it', 2847564.823);
    INSERT INTO t4 VALUES(0938446095, 'peak', 'of');
    INSERT INTO t4 VALUES(8628034825, 'and', 'same');
    INSERT INTO t4 VALUES('and', 271.2019091, 'their');
    INSERT INTO t4 VALUES('the', 'of', 'remarkably');
    INSERT INTO t4 VALUES('and', 3421170679, 1415926535);
    INSERT INTO t4 VALUES('and', 'in', 'all');
    INSERT INTO t4 VALUES(378678316.5, 0.4811174502, 'snapshots');
    INSERT INTO t4 VALUES('it', 'are', 'have');
    INSERT INTO t4 VALUES('angle', 'snapshots', 378678316.5);
    INSERT INTO t4 VALUES('from', 1415926535, 8628034825);
    INSERT INTO t4 VALUES('snapshots', 'angle', 'have');
    INSERT INTO t4 VALUES(3421170679, 0938446095, 'Not');
    INSERT INTO t4 VALUES('peak', NULL, 0.4811174502);
    INSERT INTO t4 VALUES('same', 'have', 'Alpine');
    INSERT INTO t4 VALUES(271.2019091, 66.59334461, 0938446095);
    INSERT INTO t4 VALUES(8979323846, 'his', 'an');
    INSERT INTO t4 VALUES(NULL, 'and', 3282306647);
    INSERT INTO t4 VALUES('remarkably', NULL, 'Not');
    INSERT INTO t4 VALUES('villages', 4543.266482, 'his');
    INSERT INTO t4 VALUES(2643383279, 'paintings', 'onlookers');
    INSERT INTO t4 VALUES(1339.360726, 'of', 'the');
    INSERT INTO t4 VALUES('peak', 'other', 'peak');
    INSERT INTO t4 VALUES('it', 'or', 8979323846);
    INSERT INTO t4 VALUES('onlookers', 'Not', 'towering');
    INSERT INTO t4 VALUES(NULL, 'peak', 'Not');
    INSERT INTO t4 VALUES('of', 'have', 6939937510);
    INSERT INTO t4 VALUES('light', 'hills', 0.4811174502);
    INSERT INTO t4 VALUES(5028841971, 'Not', 'it');
    INSERT INTO t4 VALUES('and', 'Not', NULL);
    INSERT INTO t4 VALUES(346.0348610, 'villages', NULL);
    INSERT INTO t4 VALUES(8979323846, NULL, 6939937510);
    INSERT INTO t4 VALUES('an', 'light', 'peak');
    INSERT INTO t4 VALUES(5028841971, 6939937510, 'light');
    INSERT INTO t4 VALUES('sometimes', 'peak', 'peak');
    INSERT INTO t4 VALUES(378678316.5, 5028841971, 'an');
    INSERT INTO t4 VALUES(378678316.5, 'his', 'Alpine');
    INSERT INTO t4 VALUES('from', 'of', 'all');
    INSERT INTO t4 VALUES(0938446095, 'same', NULL);
    INSERT INTO t4 VALUES(0938446095, 'Alpine', NULL);
    INSERT INTO t4 VALUES('his', 'of', 378678316.5);
    INSERT INTO t4 VALUES(271.2019091, 'viewed', 3282306647);
    INSERT INTO t4 VALUES('hills', 'all', 'peak');
    COMMIT;
  }
} {}

catch {unset results}
catch {unset A}
catch {unset B}

set A 2
foreach idxsql {
  { 
    /* No indexes */ 
  } {
    CREATE INDEX i5 ON t3(a);
  } {
    CREATE INDEX i5 ON t3(a, b);
    CREATE INDEX i6 ON t4(f);
  } {
    CREATE UNIQUE INDEX i5 ON t3(a, b);
    CREATE INDEX i7 ON t3(c);
    CREATE INDEX i6 ON t4(f);
    CREATE INDEX i8 ON t4(h);
  } {
    CREATE INDEX i5 ON t3(a, b, c);
    CREATE INDEX i6 ON t4(f, g, h);
    CREATE INDEX i7 ON t3(c, b, a);
    CREATE INDEX i8 ON t4(h, g, f);
  }
} {

  execsql {
    DROP INDEX IF EXISTS i5;
    DROP INDEX IF EXISTS i6;
    DROP INDEX IF EXISTS i7;
    DROP INDEX IF EXISTS i8;
  }
  execsql $idxsql

  foreach {B sql} {
 1  { SELECT * FROM t3 WHERE c LIKE b }
 2  { SELECT * FROM t3 WHERE c||'' LIKE 'the%' }
 3  { SELECT * FROM t3 WHERE rowid LIKE '12%' }
 4  { SELECT * FROM t3 WHERE +c LIKE 'the%' }
 5  { SELECT * FROM t3 WHERE c LIKE 'the%' }
 6  { SELECT * FROM t3 WHERE c GLOB '*llo' }

 7  { SELECT * FROM t3 WHERE a = 'angle' }
 8  { SELECT * FROM t3 WHERE a = 'it' OR b = 6939937510 }
 9  { SELECT * FROM t3, t4 WHERE a = 'painting' OR a = 'are' OR a = f }
10  { SELECT * FROM t3, t4 WHERE a = 'all' OR a = 'and' OR a = h }
11  { SELECT * FROM t3, t4 WHERE a < 'of' OR b > 346 AND c IS NULL }
12  { SELECT * FROM t3, t4 WHERE 'the' > a OR b > 'have' AND c = 1415926535 }

13  { SELECT * FROM t3 WHERE a BETWEEN 'one' AND 'two' OR a = 3421170679 }
14  { SELECT * FROM t3 WHERE a BETWEEN 'one' AND 'two' OR a IS NULL }
15  { SELECT * FROM t3 WHERE c > 'one' OR c >= 'one' OR c LIKE 'one%' }
16  { SELECT * FROM t3 WHERE c > 'one' OR c = c OR c = a }
17  { SELECT * FROM t3 WHERE c IS NULL OR a >= 'peak' }
18  { SELECT * FROM t3 WHERE c IN ('other', 'all', 'snapshots') OR a>1 }
19  { SELECT * FROM t3 WHERE c IN ('other', 'all', 'snapshots') AND a>1 }
20  { SELECT * FROM t3 WHERE c IS NULL AND a>'one' }
21  { SELECT * FROM t3 WHERE c IS NULL OR a>'one' }
22  { SELECT * FROM t3 WHERE b = b AND a > 'are' }
23  { SELECT * FROM t3 WHERE c <= b OR b < 'snapshots' }
24  { SELECT * FROM t3 WHERE 'onlookers' >= c AND a <= b OR b = 'angle' }
25  { SELECT * FROM t3 WHERE b = 'from' }
26  { SELECT * FROM t3 WHERE b = 4543.266482 }
27  { SELECT * FROM t3 WHERE c < 3282306647 }
28  { SELECT * FROM t3 WHERE c IS NULL AND b >= c }
29  { SELECT * FROM t3 WHERE b > 0.4811174502 AND c = 'other' AND 'viewed' > a }
30  { SELECT * FROM t3 WHERE c = 'peak' }
31  { SELECT * FROM t3 WHERE c < 53594.08128 OR c <= b }
32  { SELECT * FROM t3 WHERE 'writings' <= b }
33  { SELECT * FROM t3 WHERE 2643383279 = b OR c < b AND b <= 3282306647 }
34  { SELECT * FROM t3 WHERE a IS NULL }
35  { SELECT * FROM t3 WHERE 'writings' = a OR b = 378678316.5 }
36  { SELECT * FROM t3 WHERE 'and' >= c }
37  { SELECT * FROM t3 WHERE c < 'from' }
38  { SELECT * FROM t3 WHERE 'his' < c OR b < b }
39  { SELECT * FROM t3 WHERE 53594.08128 = b AND c >= b }
40  { SELECT * FROM t3 WHERE 'unalike' < c AND 'are' >= c AND a <= b }
41  { SELECT * FROM t3 WHERE b >= 4543.266482 OR 'Alpine' > a OR 271.2019091 <= a }
42  { SELECT * FROM t3 WHERE b = c }
43  { SELECT * FROM t3 WHERE c > a AND b < 'all' }
44  { SELECT * FROM t3 WHERE c BETWEEN 'hills' AND 'snapshots' AND c <= 'the' OR c = a }
45  { SELECT * FROM t3 WHERE b > c AND c >= 'hills' }
46  { SELECT * FROM t3 WHERE b > 'or' OR a <= 'hills' OR c IS NULL }
47  { SELECT * FROM t3 WHERE c > b OR b BETWEEN 1339.360726 AND 'onlookers' OR 1415926535 >= b }
48  { SELECT * FROM t3 WHERE a IS NULL }
49  { SELECT * FROM t3 WHERE a > 'other' }
50  { SELECT * FROM t3 WHERE 'the' <= c AND a <= c }
51  { SELECT * FROM t3 WHERE 346.0348610 = a AND c = b }
52  { SELECT * FROM t3 WHERE c BETWEEN 50.58223172 AND 'same' AND a < b }
53  { SELECT * FROM t3 WHERE 'Alpine' <= b AND c >= 'angle' OR b <= 271.2019091 }
54  { SELECT * FROM t3 WHERE a < a AND 1415926535 > b }
55  { SELECT * FROM t3 WHERE c > a AND 'have' >= c }
56  { SELECT * FROM t3 WHERE b <= b AND c > b }
57  { SELECT * FROM t3 WHERE a IS NULL AND c <= c }
58  { SELECT * FROM t3 WHERE b < c OR b = c }
59  { SELECT * FROM t3 WHERE c < b AND b >= 'it' }
60  { SELECT * FROM t3 WHERE a = b AND a <= b OR b >= a }
61  { SELECT * FROM t3 WHERE b = c }
62  { SELECT * FROM t3 WHERE c BETWEEN 'the' AND 271.2019091 OR c <= 3282306647 AND c >= b }
63  { SELECT * FROM t3 WHERE c >= c AND c < 'writings' }
64  { SELECT * FROM t3 WHERE c <= 3282306647 AND b > a OR 'unalike' <= a }
65  { SELECT * FROM t3 WHERE a > c }
66  { SELECT * FROM t3 WHERE c = 'it' OR b >= b }
67  { SELECT * FROM t3 WHERE c = a OR b < c }
68  { SELECT * FROM t3 WHERE b > a }
69  { SELECT * FROM t3 WHERE a < b OR a > 4543.266482 OR 'same' = b }
70  { SELECT * FROM t3 WHERE c < c OR b <= c OR a <= b }
71  { SELECT * FROM t3 WHERE c > a }
72  { SELECT * FROM t3 WHERE c > b }
73  { SELECT * FROM t3 WHERE b <= a }
74  { SELECT * FROM t3 WHERE 3282306647 < b AND a >= 'or' OR a >= 378678316.5 }
75  { SELECT * FROM t3 WHERE 50.58223172 <= c OR c = c AND b < b }
76  { SELECT * FROM t3 WHERE 'and' < b OR b < c OR c > 1339.360726 }
77  { SELECT * FROM t3 WHERE b <= c }
78  { SELECT * FROM t3 WHERE 'in' <= c }
79  { SELECT * FROM t3 WHERE c <= b AND a > a AND c < b }
80  { SELECT * FROM t3 WHERE 'over' < b }
81  { SELECT * FROM t3 WHERE b >= b OR b < c OR a < b }
82  { SELECT * FROM t3 WHERE 'towering' <= b OR 'towering' = a AND c > b }
83  { SELECT * FROM t3 WHERE 'peak' = a OR b BETWEEN 2643383279 AND 'the' }
84  { SELECT * FROM t3 WHERE 'an' < c AND c > 'the' AND c IS NULL }
85  { SELECT * FROM t3 WHERE a <= 'sometimes' AND a BETWEEN 'unalike' AND 1339.360726 }
86  { SELECT * FROM t3 WHERE 1339.360726 < c AND c IS NULL }
87  { SELECT * FROM t3 WHERE b > 'the' }
88  { SELECT * FROM t3 WHERE 'and' = a }
89  { SELECT * FROM t3 WHERE b >= b }
90  { SELECT * FROM t3 WHERE b >= 8979323846 }
91  { SELECT * FROM t3 WHERE c <= a }
92  { SELECT * FROM t3 WHERE a BETWEEN 'have' AND 'light' OR a > b OR a >= 378678316.5 }
93  { SELECT * FROM t3 WHERE c > 3282306647 }
94  { SELECT * FROM t3 WHERE b > c }
95  { SELECT * FROM t3 WHERE b >= a AND 'villages' > a AND b >= c }
96  { SELECT * FROM t3 WHERE 'angle' > a }
97  { SELECT * FROM t3 WHERE 'paintings' >= a }
98  { SELECT * FROM t3 WHERE 'or' >= c }
99  { SELECT * FROM t3 WHERE c < b }


101  { SELECT * FROM t3, t4 WHERE f < 'sometimes' OR 'over' <= g AND h < 1415926535 }
102  { SELECT * FROM t3, t4 WHERE h >= 'from' AND h < 6939937510 OR g > h }
103  { SELECT * FROM t3, t4 WHERE c <= h AND g = h AND c >= 'all' }
104  { SELECT * FROM t3, t4 WHERE c = a }
105  { SELECT * FROM t3, t4 WHERE 'of' >= h }
106  { SELECT * FROM t3, t4 WHERE f >= b AND a < g AND h < 'and' }
107  { SELECT * FROM t3, t4 WHERE f <= 8628034825 AND 0938446095 >= b }
108  { SELECT * FROM t3, t4 WHERE a < 'the' }
109  { SELECT * FROM t3, t4 WHERE f = 'sometimes' OR b < 'of' }
110  { SELECT * FROM t3, t4 WHERE c IS NULL }
111  { SELECT * FROM t3, t4 WHERE 'have' = b OR g <= 346.0348610 }
112  { SELECT * FROM t3, t4 WHERE f > b AND b <= h }
113  { SELECT * FROM t3, t4 WHERE f > c OR 'the' = a OR 50.58223172 = a }
114  { SELECT * FROM t3, t4 WHERE 2643383279 <= a AND c = a }
115  { SELECT * FROM t3, t4 WHERE h >= b AND 'it' <= b }
116  { SELECT * FROM t3, t4 WHERE g BETWEEN 'from' AND 'peak' }
117  { SELECT * FROM t3, t4 WHERE 'their' > a AND g > b AND f <= c }
118  { SELECT * FROM t3, t4 WHERE h = 5028841971 AND 'unalike' <= f }
119  { SELECT * FROM t3, t4 WHERE c IS NULL AND a = 3282306647 OR a <= 'Alpine' }
120  { SELECT * FROM t3, t4 WHERE 'sometimes' <= f OR 8214808651 >= a AND b <= 53594.08128 }
121  { SELECT * FROM t3, t4 WHERE 6939937510 <= f OR c < f OR 'sometimes' = c }
122  { SELECT * FROM t3, t4 WHERE b < 'onlookers' AND 'paintings' = g AND c <= h }
123  { SELECT * FROM t3, t4 WHERE a BETWEEN 'all' AND 'from' OR c > 346.0348610 }
124  { SELECT * FROM t3, t4 WHERE 'from' <= b OR a BETWEEN 53594.08128 AND 'their' AND c > a }
125  { SELECT * FROM t3, t4 WHERE h = 2643383279 }
126  { SELECT * FROM t3, t4 WHERE a <= 'the' }
127  { SELECT * FROM t3, t4 WHERE h <= c }
128  { SELECT * FROM t3, t4 WHERE g <= 346.0348610 AND 66.59334461 >= f AND f <= f }
129  { SELECT * FROM t3, t4 WHERE g >= c OR 'in' < b OR b > g }
130  { SELECT * FROM t3, t4 WHERE 'over' > g AND b BETWEEN 'unalike' AND 'remarkably' }
131  { SELECT * FROM t3, t4 WHERE h <= 2847564.823 }
132  { SELECT * FROM t3, t4 WHERE h <= 'remarkably' AND 4543.266482 > h }
133  { SELECT * FROM t3, t4 WHERE a >= c AND 'it' > g AND c < c }
134  { SELECT * FROM t3, t4 WHERE h <= 66.59334461 AND b > 3421170679 }
135  { SELECT * FROM t3, t4 WHERE h < 'are' OR f BETWEEN 0938446095 AND 'are' OR b = b }
136  { SELECT * FROM t3, t4 WHERE h = a OR 66.59334461 <= f }
137  { SELECT * FROM t3, t4 WHERE f > 'of' OR h <= h OR a = f }
138  { SELECT * FROM t3, t4 WHERE 'other' >= g }
139  { SELECT * FROM t3, t4 WHERE b <= 3421170679 }
140  { SELECT * FROM t3, t4 WHERE 'all' = f AND 4543.266482 = b OR f BETWEEN 'and' AND 'angle' }
141  { SELECT * FROM t3, t4 WHERE 'light' = f OR h BETWEEN 'remarkably' AND 1415926535 }
142  { SELECT * FROM t3, t4 WHERE 'hills' = f OR 'the' >= f }
143  { SELECT * FROM t3, t4 WHERE a > 346.0348610 }
144  { SELECT * FROM t3, t4 WHERE 5028841971 = h }
145  { SELECT * FROM t3, t4 WHERE b >= c AND 'the' >= g OR 45.64856692 <= g }
146  { SELECT * FROM t3, t4 WHERE c < 5028841971 }
147  { SELECT * FROM t3, t4 WHERE a > a }
148  { SELECT * FROM t3, t4 WHERE c = 'snapshots' }
149  { SELECT * FROM t3, t4 WHERE h > 1339.360726 AND 'and' > c }
150  { SELECT * FROM t3, t4 WHERE 'and' > g OR 'sometimes' = c }
151  { SELECT * FROM t3, t4 WHERE g >= 'the' AND b >= 'onlookers' }
152  { SELECT * FROM t3, t4 WHERE h BETWEEN 'other' AND 2643383279 }
153  { SELECT * FROM t3, t4 WHERE 'it' = b }
154  { SELECT * FROM t3, t4 WHERE f = c OR c BETWEEN 'and' AND 0.4811174502 }
155  { SELECT * FROM t3, t4 WHERE b <= 'sometimes' OR c <= 0938446095 }
156  { SELECT * FROM t3, t4 WHERE 'and' <= b }
157  { SELECT * FROM t3, t4 WHERE g > a AND f = 'the' AND b < a }
158  { SELECT * FROM t3, t4 WHERE a < 'an' }
159  { SELECT * FROM t3, t4 WHERE a BETWEEN 'his' AND 'same' OR 8628034825 > f }
160  { SELECT * FROM t3, t4 WHERE b = 'peak' }
161  { SELECT * FROM t3, t4 WHERE f IS NULL AND a >= h }
162  { SELECT * FROM t3, t4 WHERE a IS NULL OR 2643383279 = c }
163  { SELECT * FROM t3, t4 WHERE b >= 5028841971 AND f < c AND a IS NULL }
164  { SELECT * FROM t3, t4 WHERE a >= g }
165  { SELECT * FROM t3, t4 WHERE c IS NULL }
166  { SELECT * FROM t3, t4 WHERE h >= h }
167  { SELECT * FROM t3, t4 WHERE 'over' <= h }
168  { SELECT * FROM t3, t4 WHERE b < 4543.266482 OR b = 2643383279 OR 8628034825 < b }
169  { SELECT * FROM t3, t4 WHERE g >= 6939937510 }
170  { SELECT * FROM t3, t4 WHERE 'or' < a OR b < g }
171  { SELECT * FROM t3, t4 WHERE h < 'hills' OR 'and' > g }
172  { SELECT * FROM t3, t4 WHERE 'from' > f OR f <= f }
173  { SELECT * FROM t3, t4 WHERE 'viewed' > b AND f < c }
174  { SELECT * FROM t3, t4 WHERE 'of' <= a }
175  { SELECT * FROM t3, t4 WHERE f > 0938446095 }
176  { SELECT * FROM t3, t4 WHERE a = g }
177  { SELECT * FROM t3, t4 WHERE g >= b AND f BETWEEN 'peak' AND 'and' }
178  { SELECT * FROM t3, t4 WHERE g = a AND 'it' > f }
179  { SELECT * FROM t3, t4 WHERE a <= b OR 'from' > f }
180  { SELECT * FROM t3, t4 WHERE f < 'and' }
181  { SELECT * FROM t3, t4 WHERE 6939937510 < b OR 'sometimes' < h }
182  { SELECT * FROM t3, t4 WHERE f > g AND f < 'peak' }
183  { SELECT * FROM t3, t4 WHERE a <= 53594.08128 AND c <= f AND f >= c }
184  { SELECT * FROM t3, t4 WHERE f = c OR 'it' > b OR g BETWEEN 'the' AND 'all' }
185  { SELECT * FROM t3, t4 WHERE c <= g OR a = h }
186  { SELECT * FROM t3, t4 WHERE 'same' = b OR c >= 2643383279 }
187  { SELECT * FROM t3, t4 WHERE h <= g OR c > 66.59334461 OR a <= f }
188  { SELECT * FROM t3, t4 WHERE b < c AND f = 'writings' }
189  { SELECT * FROM t3, t4 WHERE b < a }
190  { SELECT * FROM t3, t4 WHERE c >= f OR c = 'and' }
191  { SELECT * FROM t3, t4 WHERE f >= 'peak' AND g > f AND h > g }
192  { SELECT * FROM t3, t4 WHERE a >= 8979323846 AND 'same' > b OR c = 'and' }
193  { SELECT * FROM t3, t4 WHERE c >= g OR 'writings' >= c AND b = 'all' }
194  { SELECT * FROM t3, t4 WHERE 'remarkably' < g }
195  { SELECT * FROM t3, t4 WHERE a BETWEEN 'or' AND 'paintings' AND g <= f }
196  { SELECT * FROM t3, t4 WHERE 0938446095 > b OR g <= a OR h > b }
197  { SELECT * FROM t3, t4 WHERE g = 2643383279 AND f = g }
198  { SELECT * FROM t3, t4 WHERE g < 8979323846 }
199  { SELECT * FROM t3, t4 WHERE 'are' <= b }

  } {
    do_test where8-4.$A.$B.1 {
      set R [execsql $sql]
      if {![info exists results($B)]} {
        set results($B) $R
      }
      list
    } {}

    do_test where8-4.$A.$B.2 { lsort $R } [lsort $results($B)]
  }
  incr A
}
catch {unset results}
catch {unset A}
catch {unset B}

# At one point the following tests provoked an invalid write error (writing
# to memory that had already been freed). It was not possible to demonstrate
# that this bug could cause a query to return bad data.
# 
do_test where8-5.1 {
  db close
  sqlite3 db test.db
  sqlite3_db_config_lookaside db 0 0 0
  execsql {
    CREATE TABLE tA(
      a, b, c, d, e, f, g, h, 
      i, j, k, l, m, n, o, p
    );
  }
  execsql {
    SELECT * FROM tA WHERE
      a=1 AND b=2 AND c=3 AND d=4 AND e=5 AND f=6 AND g=7 AND h=8 AND
      i=1 AND j=2 AND k=3 AND l=4 AND m=5 AND n=6 AND o=7 AND
      (p = 1 OR p = 2 OR p = 3)
  }
} {}
do_test where8-5.2 {
  execsql {
    SELECT * FROM tA WHERE
      a=1 AND b=2 AND c=3 AND d=4 AND e=5 AND f=6 AND g=7 AND h=8 AND
      i=1 AND j=2 AND k=3 AND l=4 AND m=5 AND
      (p = 1 OR p = 2 OR p = 3) AND n=6 AND o=7
  }
} {}
do_test where8-5.3 {
  execsql {
    INSERT INTO tA VALUES(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8); 
    CREATE UNIQUE INDEX tAI ON tA(p);
    CREATE TABLE tB(x);
    INSERT INTO tB VALUES('x');
  }
  execsql {
    SELECT a, x FROM tA LEFT JOIN tB ON (
      a=1 AND b=2 AND c=3 AND d=4 AND e=5 AND f=6 AND g=7 AND h=8 AND
      i=1 AND j=2 AND k=3 AND l=4 AND m=5 AND n=6 AND o=7 AND
      (p = 1 OR p = 2 OR p = 3)
    )
  }
} {1 {}}

finish_test

Added test/where8m.test.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 2008 December 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The focus
# is testing of where.c. More specifically, the focus is the optimization
# of WHERE clauses that feature the OR operator.
#
# $Id: where8m.test,v 1.3 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

source $testdir/malloc_common.tcl

do_malloc_test where8m-1 -sqlprep {
  CREATE TABLE t1(a, b, c);
  CREATE INDEX i1 ON t1(a);
  CREATE INDEX i2 ON t1(b);
} -sqlbody {
  SELECT c FROM t1
  WHERE 
    a = 2 OR b = 'three' OR a = 4 OR b = 'five' OR a = 6 OR
    b = 'seven' OR a = 8 OR b = 'nine' OR a = 10
  ORDER BY rowid;

  SELECT c FROM t1 WHERE
    a = 1 OR a = 2 OR a = 3 OR a = 4 OR a = 5 OR a = 6;

  SELECT c FROM t1 WHERE
    a BETWEEN 1 AND 3  AND b < 5 AND b > 2 AND c = 4;
}

do_malloc_test where8m-2 -tclprep {
  db eval {
    BEGIN;
    CREATE TABLE t1(a, b, c);
    CREATE INDEX i1 ON t1(a);
    CREATE INDEX i2 ON t1(b);
  }
  for {set i 0} {$i < 1000} {incr i} {
    set ii [expr $i*$i]
    set iii [expr $i*$i]
    db eval { INSERT INTO t1 VALUES($i, $ii, $iii) }
  }
  db eval COMMIT
} -sqlbody {
  SELECT count(*) FROM t1 WHERE a BETWEEN 5 AND 995 OR b BETWEEN 5 AND 900000;
}

finish_test

Added test/where9.test.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# 2008 December 30
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the multi-index OR clause optimizer.
#
# $Id: where9.test,v 1.9 2009/06/05 17:09:12 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !or_opt {
  finish_test
  return
}

# Evaluate SQL.  Return the result set followed by the
# and the number of full-scan steps.
#
proc count_steps {sql} {
  set r [db eval $sql]
  lappend r scan [db status step] sort [db status sort]
}


# Construct test data.  
# 
do_test where9-1.1 {
  db eval {
    CREATE TABLE t1(a INTEGER PRIMARY KEY,b,c,d,e,f,g);
    INSERT INTO t1 VALUES(1,11,1001,1.001,100.1,'bcdefghij','yxwvuts');
    INSERT INTO t1 VALUES(2,22,1001,2.002,100.1,'cdefghijk','yxwvuts');
    INSERT INTO t1 VALUES(3,33,1001,3.003,100.1,'defghijkl','xwvutsr');
    INSERT INTO t1 VALUES(4,44,2002,4.004,200.2,'efghijklm','xwvutsr');
    INSERT INTO t1 VALUES(5,55,2002,5.005,200.2,'fghijklmn','xwvutsr');
    INSERT INTO t1 VALUES(6,66,2002,6.006,200.2,'ghijklmno','xwvutsr');
    INSERT INTO t1 VALUES(7,77,3003,7.007,300.3,'hijklmnop','xwvutsr');
    INSERT INTO t1 VALUES(8,88,3003,8.008,300.3,'ijklmnopq','wvutsrq');
    INSERT INTO t1 VALUES(9,99,3003,9.009,300.3,'jklmnopqr','wvutsrq');
    INSERT INTO t1 VALUES(10,110,4004,10.01,400.4,'klmnopqrs','wvutsrq');
    INSERT INTO t1 VALUES(11,121,4004,11.011,400.4,'lmnopqrst','wvutsrq');
    INSERT INTO t1 VALUES(12,132,4004,12.012,400.4,'mnopqrstu','wvutsrq');
    INSERT INTO t1 VALUES(13,143,5005,13.013,500.5,'nopqrstuv','vutsrqp');
    INSERT INTO t1 VALUES(14,154,5005,14.014,500.5,'opqrstuvw','vutsrqp');
    INSERT INTO t1 VALUES(15,165,5005,15.015,500.5,'pqrstuvwx','vutsrqp');
    INSERT INTO t1 VALUES(16,176,6006,16.016,600.6,'qrstuvwxy','vutsrqp');
    INSERT INTO t1 VALUES(17,187,6006,17.017,600.6,'rstuvwxyz','vutsrqp');
    INSERT INTO t1 VALUES(18,198,6006,18.018,600.6,'stuvwxyza','utsrqpo');
    INSERT INTO t1 VALUES(19,209,7007,19.019,700.7,'tuvwxyzab','utsrqpo');
    INSERT INTO t1 VALUES(20,220,7007,20.02,700.7,'uvwxyzabc','utsrqpo');
    INSERT INTO t1 VALUES(21,231,7007,21.021,700.7,'vwxyzabcd','utsrqpo');
    INSERT INTO t1 VALUES(22,242,8008,22.022,800.8,'wxyzabcde','utsrqpo');
    INSERT INTO t1 VALUES(23,253,8008,23.023,800.8,'xyzabcdef','tsrqpon');
    INSERT INTO t1 VALUES(24,264,8008,24.024,800.8,'yzabcdefg','tsrqpon');
    INSERT INTO t1 VALUES(25,275,9009,25.025,900.9,'zabcdefgh','tsrqpon');
    INSERT INTO t1 VALUES(26,286,9009,26.026,900.9,'abcdefghi','tsrqpon');
    INSERT INTO t1 VALUES(27,297,9009,27.027,900.9,'bcdefghij','tsrqpon');
    INSERT INTO t1 VALUES(28,308,10010,28.028,1001.0,'cdefghijk','srqponm');
    INSERT INTO t1 VALUES(29,319,10010,29.029,1001.0,'defghijkl','srqponm');
    INSERT INTO t1 VALUES(30,330,10010,30.03,1001.0,'efghijklm','srqponm');
    INSERT INTO t1 VALUES(31,341,11011,31.031,1101.1,'fghijklmn','srqponm');
    INSERT INTO t1 VALUES(32,352,11011,32.032,1101.1,'ghijklmno','srqponm');
    INSERT INTO t1 VALUES(33,363,11011,33.033,1101.1,'hijklmnop','rqponml');
    INSERT INTO t1 VALUES(34,374,12012,34.034,1201.2,'ijklmnopq','rqponml');
    INSERT INTO t1 VALUES(35,385,12012,35.035,1201.2,'jklmnopqr','rqponml');
    INSERT INTO t1 VALUES(36,396,12012,36.036,1201.2,'klmnopqrs','rqponml');
    INSERT INTO t1 VALUES(37,407,13013,37.037,1301.3,'lmnopqrst','rqponml');
    INSERT INTO t1 VALUES(38,418,13013,38.038,1301.3,'mnopqrstu','qponmlk');
    INSERT INTO t1 VALUES(39,429,13013,39.039,1301.3,'nopqrstuv','qponmlk');
    INSERT INTO t1 VALUES(40,440,14014,40.04,1401.4,'opqrstuvw','qponmlk');
    INSERT INTO t1 VALUES(41,451,14014,41.041,1401.4,'pqrstuvwx','qponmlk');
    INSERT INTO t1 VALUES(42,462,14014,42.042,1401.4,'qrstuvwxy','qponmlk');
    INSERT INTO t1 VALUES(43,473,15015,43.043,1501.5,'rstuvwxyz','ponmlkj');
    INSERT INTO t1 VALUES(44,484,15015,44.044,1501.5,'stuvwxyza','ponmlkj');
    INSERT INTO t1 VALUES(45,495,15015,45.045,1501.5,'tuvwxyzab','ponmlkj');
    INSERT INTO t1 VALUES(46,506,16016,46.046,1601.6,'uvwxyzabc','ponmlkj');
    INSERT INTO t1 VALUES(47,517,16016,47.047,1601.6,'vwxyzabcd','ponmlkj');
    INSERT INTO t1 VALUES(48,528,16016,48.048,1601.6,'wxyzabcde','onmlkji');
    INSERT INTO t1 VALUES(49,539,17017,49.049,1701.7,'xyzabcdef','onmlkji');
    INSERT INTO t1 VALUES(50,550,17017,50.05,1701.7,'yzabcdefg','onmlkji');
    INSERT INTO t1 VALUES(51,561,17017,51.051,1701.7,'zabcdefgh','onmlkji');
    INSERT INTO t1 VALUES(52,572,18018,52.052,1801.8,'abcdefghi','onmlkji');
    INSERT INTO t1 VALUES(53,583,18018,53.053,1801.8,'bcdefghij','nmlkjih');
    INSERT INTO t1 VALUES(54,594,18018,54.054,1801.8,'cdefghijk','nmlkjih');
    INSERT INTO t1 VALUES(55,605,19019,55.055,1901.9,'defghijkl','nmlkjih');
    INSERT INTO t1 VALUES(56,616,19019,56.056,1901.9,'efghijklm','nmlkjih');
    INSERT INTO t1 VALUES(57,627,19019,57.057,1901.9,'fghijklmn','nmlkjih');
    INSERT INTO t1 VALUES(58,638,20020,58.058,2002.0,'ghijklmno','mlkjihg');
    INSERT INTO t1 VALUES(59,649,20020,59.059,2002.0,'hijklmnop','mlkjihg');
    INSERT INTO t1 VALUES(60,660,20020,60.06,2002.0,'ijklmnopq','mlkjihg');
    INSERT INTO t1 VALUES(61,671,21021,61.061,2102.1,'jklmnopqr','mlkjihg');
    INSERT INTO t1 VALUES(62,682,21021,62.062,2102.1,'klmnopqrs','mlkjihg');
    INSERT INTO t1 VALUES(63,693,21021,63.063,2102.1,'lmnopqrst','lkjihgf');
    INSERT INTO t1 VALUES(64,704,22022,64.064,2202.2,'mnopqrstu','lkjihgf');
    INSERT INTO t1 VALUES(65,715,22022,65.065,2202.2,'nopqrstuv','lkjihgf');
    INSERT INTO t1 VALUES(66,726,22022,66.066,2202.2,'opqrstuvw','lkjihgf');
    INSERT INTO t1 VALUES(67,737,23023,67.067,2302.3,'pqrstuvwx','lkjihgf');
    INSERT INTO t1 VALUES(68,748,23023,68.068,2302.3,'qrstuvwxy','kjihgfe');
    INSERT INTO t1 VALUES(69,759,23023,69.069,2302.3,'rstuvwxyz','kjihgfe');
    INSERT INTO t1 VALUES(70,770,24024,70.07,2402.4,'stuvwxyza','kjihgfe');
    INSERT INTO t1 VALUES(71,781,24024,71.071,2402.4,'tuvwxyzab','kjihgfe');
    INSERT INTO t1 VALUES(72,792,24024,72.072,2402.4,'uvwxyzabc','kjihgfe');
    INSERT INTO t1 VALUES(73,803,25025,73.073,2502.5,'vwxyzabcd','jihgfed');
    INSERT INTO t1 VALUES(74,814,25025,74.074,2502.5,'wxyzabcde','jihgfed');
    INSERT INTO t1 VALUES(75,825,25025,75.075,2502.5,'xyzabcdef','jihgfed');
    INSERT INTO t1 VALUES(76,836,26026,76.076,2602.6,'yzabcdefg','jihgfed');
    INSERT INTO t1 VALUES(77,847,26026,77.077,2602.6,'zabcdefgh','jihgfed');
    INSERT INTO t1 VALUES(78,858,26026,78.078,2602.6,'abcdefghi','ihgfedc');
    INSERT INTO t1 VALUES(79,869,27027,79.079,2702.7,'bcdefghij','ihgfedc');
    INSERT INTO t1 VALUES(80,880,27027,80.08,2702.7,'cdefghijk','ihgfedc');
    INSERT INTO t1 VALUES(81,891,27027,81.081,2702.7,'defghijkl','ihgfedc');
    INSERT INTO t1 VALUES(82,902,28028,82.082,2802.8,'efghijklm','ihgfedc');
    INSERT INTO t1 VALUES(83,913,28028,83.083,2802.8,'fghijklmn','hgfedcb');
    INSERT INTO t1 VALUES(84,924,28028,84.084,2802.8,'ghijklmno','hgfedcb');
    INSERT INTO t1 VALUES(85,935,29029,85.085,2902.9,'hijklmnop','hgfedcb');
    INSERT INTO t1 VALUES(86,946,29029,86.086,2902.9,'ijklmnopq','hgfedcb');
    INSERT INTO t1 VALUES(87,957,29029,87.087,2902.9,'jklmnopqr','hgfedcb');
    INSERT INTO t1 VALUES(88,968,30030,88.088,3003.0,'klmnopqrs','gfedcba');
    INSERT INTO t1 VALUES(89,979,30030,89.089,3003.0,'lmnopqrst','gfedcba');
    INSERT INTO t1 VALUES(90,NULL,30030,90.09,3003.0,'mnopqrstu','gfedcba');
    INSERT INTO t1 VALUES(91,1001,NULL,91.091,3103.1,'nopqrstuv','gfedcba');
    INSERT INTO t1 VALUES(92,1012,31031,NULL,3103.1,'opqrstuvw','gfedcba');
    INSERT INTO t1 VALUES(93,1023,31031,93.093,NULL,'pqrstuvwx','fedcbaz');
    INSERT INTO t1 VALUES(94,1034,32032,94.094,3203.2,NULL,'fedcbaz');
    INSERT INTO t1 VALUES(95,1045,32032,95.095,3203.2,'rstuvwxyz',NULL);
    INSERT INTO t1 VALUES(96,NULL,NULL,96.096,3203.2,'stuvwxyza','fedcbaz');
    INSERT INTO t1 VALUES(97,1067,33033,NULL,NULL,'tuvwxyzab','fedcbaz');
    INSERT INTO t1 VALUES(98,1078,33033,98.098,3303.3,NULL,NULL);
    INSERT INTO t1 VALUES(99,NULL,NULL,NULL,NULL,NULL,NULL);
    CREATE INDEX t1b ON t1(b);
    CREATE INDEX t1c ON t1(c);
    CREATE INDEX t1d ON t1(d);
    CREATE INDEX t1e ON t1(e);
    CREATE INDEX t1f ON t1(f);
    CREATE INDEX t1g ON t1(g);
    CREATE TABLE t2(a INTEGER PRIMARY KEY,b,c,d,e,f,g);
    INSERT INTO t2 SELECT * FROM t1;
    CREATE INDEX t2b ON t2(b,c);
    CREATE INDEX t2c ON t2(c,e);
    CREATE INDEX t2d ON t2(d,g);
    CREATE INDEX t2e ON t2(e,f,g);
    CREATE INDEX t2f ON t2(f,b,d,c);
    CREATE INDEX t2g ON t2(g,f);
    CREATE TABLE t3(x,y);
    INSERT INTO t3 VALUES(1,80);
    INSERT INTO t3 VALUES(2,80);
    CREATE TABLE t4(a INTEGER PRIMARY KEY,b,c,d,e,f,g);
    INSERT INTO t4 SELECT * FROM t1;
    CREATE INDEX t4b ON t4(b);
    CREATE INDEX t4c ON t4(c);
  }
} {}

do_test where9-1.2.1 {
  count_steps {
    SELECT a FROM t1
     WHERE b IS NULL
        OR c IS NULL
        OR d IS NULL
    ORDER BY a
  }
} {90 91 92 96 97 99 scan 0 sort 1}
do_test where9-1.2.2 {
  count_steps {
    SELECT a FROM t1
     WHERE +b IS NULL
        OR c IS NULL
        OR d IS NULL
    ORDER BY a
  }
} {90 91 92 96 97 99 scan 98 sort 0}
do_test where9-1.2.3 {
  count_steps {
    SELECT a FROM t1
     WHERE b IS NULL
        OR +c IS NULL
        OR d IS NULL
    ORDER BY a
  }
} {90 91 92 96 97 99 scan 98 sort 0}
do_test where9-1.2.4 {
  count_steps {
    SELECT a FROM t1
     WHERE b IS NULL
        OR c IS NULL
        OR +d IS NULL
    ORDER BY a
  }
} {90 91 92 96 97 99 scan 98 sort 0}
do_test where9-1.2.5 {
  count_steps {
    SELECT a FROM t4
     WHERE b IS NULL
        OR c IS NULL
        OR d IS NULL
    ORDER BY a
  }
} {90 91 92 96 97 99 scan 98 sort 0}

do_test where9-1.3.1 {
  count_steps {
    SELECT a FROM t1
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
    ORDER BY a
  }
} {90 91 92 97 scan 0 sort 1}
do_test where9-1.3.2 {
  count_steps {
    SELECT a FROM t4
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
    ORDER BY a
  }
} {90 91 92 97 scan 98 sort 0}
do_test where9-1.3.3 {
  count_steps {
    SELECT a FROM t4
     WHERE (b NOT NULL AND c NOT NULL AND d IS NULL)
        OR (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
    ORDER BY a
  }
} {90 91 92 97 scan 98 sort 0}
do_test where9-1.3.4 {
  count_steps {
    SELECT a FROM t4
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
    ORDER BY a
  }
} {90 91 92 97 scan 98 sort 0}

do_test where9-1.4 {
  count_steps {
    SELECT a FROM t1
     WHERE (b>=950 AND b<=1010) OR (b IS NULL AND c NOT NULL)
    ORDER BY a
  }
} {87 88 89 90 91 scan 0 sort 1}
do_test where9-1.5 {
  # When this test was originally written, SQLite used a rowset object 
  # to optimize the "ORDER BY a" clause. Now that it is using a rowhash,
  # this is not possible. So we have to comment out one term of the OR
  # expression in order to prevent SQLite from deeming a full-table
  # scan to be a better strategy than using multiple indexes, which would
  # defeat the point of the test.
  count_steps {
    SELECT a FROM t1
     WHERE a=83
        OR b=913
        OR c=28028
        OR (d>=82 AND d<83)
/*      OR (e>2802 AND e<2803)  */
        OR f='fghijklmn'
        OR g='hgfedcb'
    ORDER BY a
  }
} {5 31 57 82 83 84 85 86 87 scan 0 sort 1}
do_test where9-1.6 {
  count_steps {
    SELECT a FROM t1
     WHERE b=1012
        OR (d IS NULL AND e IS NOT NULL)
  }
} {92 scan 0 sort 0}
do_test where9-1.7 {
  count_steps {
    SELECT a FROM t1
     WHERE (b=1012 OR (d IS NULL AND e IS NOT NULL))
       AND f!=g
  }
} {92 scan 0 sort 0}
do_test where9-1.8 {
  count_steps {
    SELECT a FROM t1
     WHERE (b=1012 OR (d IS NULL AND e IS NOT NULL))
       AND f==g
  }
} {scan 0 sort 0}

do_test where9-2.1 {
  count_steps {
    SELECT t2.a FROM t1, t2
     WHERE t1.a=80
       AND (t1.c=t2.c OR t1.d=t2.d)
    ORDER BY 1
  }
} {79 80 81 scan 0 sort 1}
do_test where9-2.2 {
  count_steps {
    SELECT t2.a FROM t1, t2
     WHERE t1.a=80
       AND ((t1.c=t2.c AND t1.d=t2.d) OR t1.f=t2.f)
    ORDER BY 1
  }
} {2 28 54 80 scan 0 sort 1}
do_test where9-2.3 {
  count_steps {
    SELECT coalesce(t2.a,9999)
      FROM t1 LEFT JOIN t2 ON (t1.c=t2.c AND t1.d=t2.d) OR t1.f=t2.f
     WHERE t1.a=80
    ORDER BY 1
  }
} {2 28 54 80 scan 0 sort 1}
do_test where9-2.4 {
  count_steps {
    SELECT coalesce(t2.a,9999)
      FROM t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f
     WHERE t1.a=80
    ORDER BY 1
  }
} {9999 scan 0 sort 1}
do_test where9-2.5 {
  count_steps {
    SELECT t1.a, coalesce(t2.a,9999)
      FROM t1 LEFT JOIN t2 ON (t1.c=t2.c AND t1.d=t2.d) OR (t1.f)=t2.f
     WHERE t1.a=80 OR t1.b=880 OR (t1.c=27027 AND round(t1.d)==80)
    ORDER BY 1
  }
} {80 80 80 2 80 28 80 54 scan 0 sort 1}
do_test where9-2.6 {
  count_steps {
    SELECT t1.a, coalesce(t2.a,9999)
      FROM t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f
     WHERE t1.a=80 OR t1.b=880 OR (t1.c=27027 AND round(t1.d)==80)
    ORDER BY 1
  }
} {80 9999 scan 0 sort 1}
do_test where9-2.7 {
  count_steps {
    SELECT t3.x, t1.a, coalesce(t2.a,9999)
      FROM t3 JOIN
           t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f
     WHERE t1.a=t3.y OR t1.b=t3.y*11 OR (t1.c=27027 AND round(t1.d)==80)
    ORDER BY 1, 2
  }
} {1 80 9999 2 80 9999 scan 1 sort 1}
do_test where9-2.8 {
  count_steps {
    SELECT t3.x, t1.a, coalesce(t2.a,9999)
      FROM t3 JOIN
           t1 LEFT JOIN t2 ON (t1.c=t2.c AND t1.d=t2.d) OR (t1.f)=t2.f
     WHERE t1.a=t3.y OR t1.b=t3.y*11 OR (t1.c=27027 AND round(t1.d)==80)
    ORDER BY 1, 2, 3
  }
} {1 80 2 1 80 28 1 80 54 1 80 80 2 80 2 2 80 28 2 80 54 2 80 80 scan 1 sort 1}


ifcapable explain {
  do_test where9-3.1 {
    set r [db eval {
      EXPLAIN QUERY PLAN
      SELECT t2.a FROM t1, t2
       WHERE t1.a=80
         AND ((t1.c=t2.c AND t1.d=t2.d) OR t1.f=t2.f)
    }]
    set a [expr {[lsearch $r {TABLE t2 VIA MULTI-INDEX UNION}]>=0}]
    set b [expr {[lsearch $r {TABLE t2 WITH INDEX t2f}]>=0}]
    set c [expr {([lsearch $r {TABLE t2 WITH INDEX t2c}]>=0)+
                  [lsearch $r {TABLE t2 WITH INDEX t2d}]>=0}]
    concat $a $b $c
  } {1 1 1}
  do_test where9-3.2 {
    set r [db eval {
      EXPLAIN QUERY PLAN
      SELECT coalesce(t2.a,9999)
        FROM t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f
       WHERE t1.a=80
    }]
    set a [expr {[lsearch $r {TABLE t2 VIA MULTI-INDEX UNION}]>=0}]
    set b [expr {[lsearch $r {TABLE t2 WITH INDEX t2f}]>=0}]
    set c [expr {([lsearch $r {TABLE t2 WITH INDEX t2c}]>=0)+
                  [lsearch $r {TABLE t2 WITH INDEX t2d}]>=0}]
    concat $a $b $c
  } {1 1 1}
} 

# Make sure that INDEXED BY and multi-index OR clauses play well with
# one another.
#
do_test where9-4.1 {
  count_steps {
    SELECT a FROM t1
     WHERE b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {92 93 97 scan 0 sort 1}
do_test where9-4.2 {
  count_steps {
    SELECT a FROM t1
     WHERE b>1000
       AND (c=31031 OR +d IS NULL)
     ORDER BY +a
  }
} {92 93 97 scan 0 sort 1}
do_test where9-4.3 {
  count_steps {
    SELECT a FROM t1
     WHERE +b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {92 93 97 scan 0 sort 1}
do_test where9-4.4 {
  count_steps {
    SELECT a FROM t1 INDEXED BY t1b
     WHERE b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {92 93 97 scan 0 sort 1}
do_test where9-4.5 {
  catchsql {
    SELECT a FROM t1 INDEXED BY t1b
     WHERE +b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {1 {cannot use index: t1b}}
do_test where9-4.6 {
  count_steps {
    SELECT a FROM t1 NOT INDEXED
     WHERE b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {92 93 97 scan 98 sort 1}
do_test where9-4.7 {
  catchsql {
    SELECT a FROM t1 INDEXED BY t1c
     WHERE b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {1 {cannot use index: t1c}}
do_test where9-4.8 {
  catchsql {
    SELECT a FROM t1 INDEXED BY t1d
     WHERE b>1000
       AND (c=31031 OR d IS NULL)
     ORDER BY +a
  }
} {1 {cannot use index: t1d}}

ifcapable explain {
  # The (c=31031 OR d IS NULL) clause is preferred over b>1000 because
  # the former is an equality test which is expected to return fewer rows.
  #
  do_test where9-5.1 {
    set r [db eval {
      EXPLAIN QUERY PLAN
      SELECT a FROM t1
       WHERE b>1000
         AND (c=31031 OR d IS NULL)
    }]
    set a [expr {[lsearch $r {TABLE t1 VIA MULTI-INDEX UNION}]>=0}]
    set b [expr {[lsearch $r {TABLE t1 WITH INDEX t1b}]>=0}]
    concat $a $b
  } {1 0}

  # In contrast, b=1000 is preferred over any OR-clause.
  #
  do_test where9-5.2 {
    set r [db eval {
      EXPLAIN QUERY PLAN
      SELECT a FROM t1
       WHERE b=1000
         AND (c=31031 OR d IS NULL)
    }]
    set a [expr {[lsearch $r {TABLE t1 VIA MULTI-INDEX UNION}]>=0}]
    set b [expr {[lsearch $r {TABLE t1 WITH INDEX t1b}]>=0}]
    concat $a $b
  } {0 1}

  # Likewise, inequalities in an AND are preferred over inequalities in
  # an OR.
  #
  do_test where9-5.3 {
    set r [db eval {
      EXPLAIN QUERY PLAN
      SELECT a FROM t1
       WHERE b>1000
         AND (c>=31031 OR d IS NULL)
    }]
    set a [expr {[lsearch $r {TABLE t1 VIA MULTI-INDEX UNION}]>=0}]
    set b [expr {[lsearch $r {TABLE t1 WITH INDEX t1b}]>=0}]
    concat $a $b
  } {0 1}
}

############################################################################
# Make sure OR-clauses work correctly on UPDATE and DELETE statements.

do_test where9-6.2.1 {
  db eval {SELECT count(*) FROM t1 UNION ALL SELECT a FROM t1 WHERE a>=85}
} {99 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99}

do_test where9-6.2.2 {   ;# Deletes entries 90 91 92 96 97 99
  count_steps {
     BEGIN;
     DELETE FROM t1
     WHERE b IS NULL
        OR c IS NULL
        OR d IS NULL
  }
} {scan 0 sort 0}

do_test where9-6.2.3 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a>=85;
    ROLLBACK;
  }
} {93 85 86 87 88 89 93 94 95 98}

do_test where9-6.2.4 {   ;# Deletes entries 90 91 92 96 97 99
  count_steps {
     BEGIN;
     DELETE FROM t1
     WHERE +b IS NULL
        OR c IS NULL
        OR d IS NULL
  }
} {scan 98 sort 0}

do_test where9-6.2.5 {
  db eval {
     SELECT count(*) FROM t1 UNION ALL
     SELECT a FROM t1 WHERE a>=85;
     ROLLBACK;
  }
} {93 85 86 87 88 89 93 94 95 98}

do_test where9-6.2.6 {
  count_steps {
     BEGIN;
     UPDATE t1 SET a=a+100
     WHERE (b IS NULL
            OR c IS NULL
            OR d IS NULL)
       AND a!=92
       AND a!=97
  }
} {scan 0 sort 0}   ;# Add 100 to entries 90 91 96 99

do_test where9-6.2.7 {
  db eval {
     SELECT count(*) FROM t1 UNION ALL
     SELECT a FROM t1 WHERE a>=85;
     ROLLBACK
  }
} {99 85 86 87 88 89 92 93 94 95 97 98 190 191 196 199}

do_test where9-6.2.8 {   ;# Deletes entries 90 91 92 97 99
  count_steps {
     BEGIN;
     DELETE FROM t1
     WHERE (b IS NULL
            OR c IS NULL
            OR d IS NULL)
       AND a!=96
  }
} {scan 0 sort 0}

do_test where9-6.2.9 {
  db eval {
     SELECT count(*) FROM t1 UNION ALL SELECT a FROM t1 WHERE a>=85;
     ROLLBACK;
  }
} {94 85 86 87 88 89 93 94 95 96 98}

do_test where9-6.3.1 {
  count_steps {
    BEGIN;
    DELETE FROM t1
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 0 sort 0}   ;# DELETEs rows 90 91 92 97
do_test where9-6.3.2 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {95 85 86 87 88 89 93 94 95 96 98 99}

do_test where9-6.3.3 {
  count_steps {
    BEGIN;
    UPDATE t1 SET a=a+100
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 0 sort 0}   ;# Add 100 to rowids 90 91 92 97
do_test where9-6.3.4 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 200;
    ROLLBACK;
  }
} {99 85 86 87 88 89 93 94 95 96 98 99 190 191 192 197}

do_test where9-6.3.5 {
  count_steps {
    BEGIN;
    DELETE FROM t1
     WHERE (+b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 98 sort 0}   ;# DELETEs rows 90 91 92 97
do_test where9-6.3.6 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {95 85 86 87 88 89 93 94 95 96 98 99}

do_test where9-6.3.7 {
  count_steps {
    BEGIN;
    UPDATE t1 SET a=a+100
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND +c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 98 sort 0}   ;# Add 100 to rowids 90 91 92 97
do_test where9-6.3.8 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {99 85 86 87 88 89 93 94 95 96 98 99}


do_test where9-6.4.1 {
  count_steps {
    BEGIN;
    DELETE FROM t1
     WHERE (b>=950 AND b<=1010) OR (b IS NULL AND c NOT NULL)
  }
} {scan 0 sort 0}  ;# DELETE rows 87 88 89 90 91
do_test where9-6.4.2 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {94 85 86 92 93 94 95 96 97 98 99}
do_test where9-6.4.3 {
  count_steps {
    BEGIN;
    UPDATE t1 SET a=a+100
     WHERE (b>=950 AND b<=1010) OR (b IS NULL AND c NOT NULL)
  }
} {scan 0 sort 0}  ;# Add 100 to rowids 87 88 89 90 91
do_test where9-6.4.4 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {99 85 86 92 93 94 95 96 97 98 99}


do_test where9-6.5.1 {
  count_steps {
    BEGIN;
    DELETE FROM t1
     WHERE a=83
        OR b=913
        OR c=28028
        OR (d>=82 AND d<83)
        OR (e>2802 AND e<2803) 
        OR f='fghijklmn'
        OR g='hgfedcb'
  }
} {scan 0 sort 0}   ;#  DELETE rows 5 31 57 82 83 84 85 86 87
do_test where9-6.5.2 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a IN (5,31,57,82,83,84,85,86,87);
    ROLLBACK;
  }
} {90}

do_test where9-6.5.3 {
  count_steps {
    BEGIN;
    UPDATE t1 SET a=a+100
     WHERE a=83
        OR b=913
        OR c=28028
        OR (d>=82 AND d<83)
        OR (e>2802 AND e<2803) 
        OR f='fghijklmn'
        OR g='hgfedcb'
  }
} {scan 0 sort 0}   ;#  Add 100 to rowids 5 31 57 82 83 84 85 86 87
do_test where9-6.5.4 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a%100 IN (5,31,57,82,83,84,85,86,87);
    ROLLBACK;
  }
} {99 105 131 157 182 183 184 185 186 187}

do_test where9-6.6.1 {
  count_steps {
    BEGIN;
    DELETE FROM t1
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND +c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 98 sort 0}   ;# DELETEs rows 90 91 92 97
do_test where9-6.6.2 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {95 85 86 87 88 89 93 94 95 96 98 99}

do_test where9-6.6.3 {
  count_steps {
    BEGIN;
    UPDATE t1 SET a=a+100
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND +c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 98 sort 0}   ;# Add 100 to rowids 90 91 92 97
do_test where9-6.6.4 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 200;
    ROLLBACK;
  }
} {99 85 86 87 88 89 93 94 95 96 98 99 190 191 192 197}

do_test where9-6.7.1 {
  count_steps {
    BEGIN;
    DELETE FROM t1 NOT INDEXED
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 98 sort 0}   ;# DELETEs rows 90 91 92 97
do_test where9-6.7.2 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 100;
    ROLLBACK;
  }
} {95 85 86 87 88 89 93 94 95 96 98 99}

do_test where9-6.7.3 {
  count_steps {
    BEGIN;
    UPDATE t1 NOT INDEXED SET a=a+100
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {scan 98 sort 0}   ;# Add 100 to rowids 90 91 92 97
do_test where9-6.7.4 {
  db eval {
    SELECT count(*) FROM t1 UNION ALL
    SELECT a FROM t1 WHERE a BETWEEN 85 AND 200;
    ROLLBACK;
  }
} {99 85 86 87 88 89 93 94 95 96 98 99 190 191 192 197}

do_test where9-6.8.1 {
  catchsql {
    DELETE FROM t1 INDEXED BY t1b
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {1 {cannot use index: t1b}}
do_test where9-6.8.2 {
  catchsql {
    UPDATE t1 INDEXED BY t1b SET a=a+100
     WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)
        OR (b NOT NULL AND c IS NULL AND d NOT NULL)
        OR (b NOT NULL AND c NOT NULL AND d IS NULL)
  }
} {1 {cannot use index: t1b}}

finish_test

Added test/whereA.test.





























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# 2009 February 23
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The
# focus of this file is testing the reverse_select_order pragma.
#
# $Id: whereA.test,v 1.3 2009/06/10 19:33:29 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test whereA-1.1 {
  db eval {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE, c);
    INSERT INTO t1 VALUES(1,2,3);
    INSERT INTO t1 values(2,'hello','world');
    INSERT INTO t1 VALUES(3,4.53,NULL);
    SELECT * FROM t1
  }
} {1 2 3 2 hello world 3 4.53 {}}
do_test whereA-1.2 {
  db eval {
    PRAGMA reverse_unordered_selects=1;
    SELECT * FROM t1;
  }
} {3 4.53 {} 2 hello world 1 2 3}

do_test whereA-1.3 {
  db eval {
    PRAGMA reverse_unordered_selects=1;
    SELECT * FROM t1 ORDER BY rowid;
  }
} {1 2 3 2 hello world 3 4.53 {}}

do_test whereA-2.1 {
  db eval {
    PRAGMA reverse_unordered_selects=0;
    SELECT * FROM t1 WHERE a>0;
  }
} {1 2 3 2 hello world 3 4.53 {}}
do_test whereA-2.2 {
  db eval {
    PRAGMA reverse_unordered_selects=1;
    SELECT * FROM t1 WHERE a>0;
  }
} {3 4.53 {} 2 hello world 1 2 3}

do_test whereA-2.3 {
  db eval {
    PRAGMA reverse_unordered_selects=1;
    SELECT * FROM t1 WHERE a>0 ORDER BY rowid;
  }
} {1 2 3 2 hello world 3 4.53 {}}

do_test whereA-3.1 {
  db eval {
    PRAGMA reverse_unordered_selects=0;
    SELECT * FROM t1 WHERE b>0;
  }
} {1 2 3 3 4.53 {} 2 hello world}
do_test whereA-3.2 {
  db eval {
    PRAGMA reverse_unordered_selects=1;
    SELECT * FROM t1 WHERE b>0;
  }
} {2 hello world 3 4.53 {} 1 2 3}
do_test whereA-3.3 {
  db eval {
    PRAGMA reverse_unordered_selects=1;
    SELECT * FROM t1 WHERE b>0 ORDER BY b;
  }
} {1 2 3 3 4.53 {} 2 hello world}

do_test whereA-4.1 {
  db eval {
    CREATE TABLE t2(x);
    INSERT INTO t2 VALUES(1);
    INSERT INTO t2 VALUES(2);
    SELECT x FROM t2;
  }
} {2 1}
# Do an SQL statement.  Append the search count to the end of the result.
#
proc count sql {
  set ::sqlite_sort_count 0
  return [concat [execsql $sql] $::sqlite_sort_count]
}
do_test whereA-4.2 {   ;# Ticket #3904
  db eval {
    CREATE INDEX t2x ON t2(x);
  }
  count {
    SELECT x FROM t2;
  }
} {2 1 0}
do_test whereA-4.3 {
  count {
    SELECT x FROM t2 ORDER BY x;
  }
} {1 2 0}
do_test whereA-4.4 {
  count {
    SELECT x FROM t2 ORDER BY x DESC;
  }
} {2 1 0}
do_test whereA-4.5 {
  db eval {DROP INDEX t2x;}
  count {
    SELECT x FROM t2 ORDER BY x;
  }
} {1 2 1}
do_test whereA-4.6 {
  count {
    SELECT x FROM t2 ORDER BY x DESC;
  }
} {2 1 1}


finish_test

Added test/whereB.test.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
# 2009 August 13
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library. The
# focus of this file is testing WHERE clause conditions with
# subtle affinity issues.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# For this set of tests:
#
#  *   t1.y holds an integer value with affinity NONE
#  *   t2.b holds a text value with affinity TEXT
#
# These values are not equal and because neither affinity is NUMERIC
# no type conversion occurs.
#
do_test whereB-1.1 {
  db eval {
    CREATE TABLE t1(x,y);    -- affinity of t1.y is NONE
    INSERT INTO t1 VALUES(1,99);

    CREATE TABLE t2(a, b TEXT);  -- affinity of t2.b is TEXT
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,99);

    SELECT x, a, y=b FROM t1, t2 ORDER BY +x, +a;
  }
} {1 2 0}
do_test whereB-1.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {}
do_test whereB-1.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {}
do_test whereB-1.4 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-1.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {}
do_test whereB-1.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {}
do_test whereB-1.102 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}

# For this set of tests:
#
#  *   t1.y holds a text value with affinity TEXT
#  *   t2.b holds an integer value with affinity NONE
#
# These values are not equal and because neither affinity is NUMERIC
# no type conversion occurs.
#
do_test whereB-2.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y TEXT);    -- affinity of t1.y is TEXT
    INSERT INTO t1 VALUES(1,99);

    CREATE TABLE t2(a, b BLOB);  -- affinity of t2.b is NONE
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,99);

    SELECT x, a, y=b FROM t1, t2 ORDER BY +x, +a;
  }
} {1 2 0}
do_test whereB-2.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {}
do_test whereB-2.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {}
do_test whereB-2.4 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-2.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {}
do_test whereB-2.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {}
do_test whereB-2.102 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}

# For this set of tests:
#
#  *   t1.y holds a text value with affinity NONE
#  *   t2.b holds an integer value with affinity NONE
#
# These values are not equal and because neither affinity is NUMERIC
# no type conversion occurs.
#
do_test whereB-3.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y BLOB);    -- affinity of t1.y is NONE
    INSERT INTO t1 VALUES(1,99);

    CREATE TABLE t2(a, b BLOB);  -- affinity of t2.b is NONE
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,'99');

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 0}
do_test whereB-3.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {}
do_test whereB-3.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {}
do_test whereB-3.4 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-3.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {}
do_test whereB-3.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {}
do_test whereB-3.102 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}


# For this set of tests:
#
#  *   t1.y holds a text value with affinity NONE
#  *   t2.b holds an integer value with affinity NUMERIC
#
# Because t2.b has a numeric affinity, type conversion should occur
# and the two fields should be equal.
#
do_test whereB-4.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y BLOB);    -- affinity of t1.y is NONE
    INSERT INTO t1 VALUES(1,'99');

    CREATE TABLE t2(a, b NUMERIC);  -- affinity of t2.b is NUMERIC
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,99);

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 1}
do_test whereB-4.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-4.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-4.4 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-4.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-4.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-4.102 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}



# For this set of tests:
#
#  *   t1.y holds a text value with affinity NONE
#  *   t2.b holds an integer value with affinity INTEGER
#
# Because t2.b has a numeric affinity, type conversion should occur
# and the two fields should be equal.
#
do_test whereB-5.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y BLOB);    -- affinity of t1.y is NONE
    INSERT INTO t1 VALUES(1,'99');

    CREATE TABLE t2(a, b INT);  -- affinity of t2.b is INTEGER
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,99);

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 1}
do_test whereB-5.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-5.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-5.4 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-5.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-5.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-5.102 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}


# For this set of tests:
#
#  *   t1.y holds a text value with affinity NONE
#  *   t2.b holds an integer value with affinity REAL
#
# Because t2.b has a numeric affinity, type conversion should occur
# and the two fields should be equal.
#
do_test whereB-6.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y BLOB);    -- affinity of t1.y is NONE
    INSERT INTO t1 VALUES(1,'99');

    CREATE TABLE t2(a, b REAL);  -- affinity of t2.b is REAL
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,99.0);

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 1}
do_test whereB-6.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-6.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-6.4 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-6.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-6.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-6.102 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}


# For this set of tests:
#
#  *   t1.y holds an integer value with affinity NUMERIC
#  *   t2.b holds a text value with affinity NONE
#
# Because t1.y has a numeric affinity, type conversion should occur
# and the two fields should be equal.
#
do_test whereB-7.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y NUMERIC);  -- affinity of t1.y is NUMERIC
    INSERT INTO t1 VALUES(1,99);

    CREATE TABLE t2(a, b BLOB);  -- affinity of t2.b is NONE
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,'99');

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 1}
do_test whereB-7.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-7.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-7.4 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-7.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-7.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-7.102 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}

# For this set of tests:
#
#  *   t1.y holds an integer value with affinity INTEGER
#  *   t2.b holds a text value with affinity NONE
#
# Because t1.y has a numeric affinity, type conversion should occur
# and the two fields should be equal.
#
do_test whereB-8.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y INT);  -- affinity of t1.y is INTEGER
    INSERT INTO t1 VALUES(1,99);

    CREATE TABLE t2(a, b BLOB);  -- affinity of t2.b is NONE
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,'99');

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 1}
do_test whereB-8.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-8.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-8.4 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-8.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-8.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-8.102 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}

# For this set of tests:
#
#  *   t1.y holds an integer value with affinity REAL
#  *   t2.b holds a text value with affinity NONE
#
# Because t1.y has a numeric affinity, type conversion should occur
# and the two fields should be equal.
#
do_test whereB-9.1 {
  db eval {
    DROP TABLE t1;
    DROP TABLE t2;

    CREATE TABLE t1(x, y REAL);  -- affinity of t1.y is REAL
    INSERT INTO t1 VALUES(1,99.0);

    CREATE TABLE t2(a, b BLOB);  -- affinity of t2.b is NONE
    CREATE INDEX t2b ON t2(b);
    INSERT INTO t2 VALUES(2,'99');

    SELECT x, a, y=b FROM t1, t2;
  }
} {1 2 1}
do_test whereB-9.2 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-9.3 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-9.4 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}
do_test whereB-9.100 {
  db eval {
    DROP INDEX t2b;
    SELECT x, a, y=b FROM t1, t2 WHERE y=b;
  }
} {1 2 1}
do_test whereB-9.101 {
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE b=y;
  }
} {1 2 1}
do_test whereB-9.102 {
  # In this case the unary "+" operator removes the column affinity so
  # the columns compare false
  db eval {
    SELECT x, a, y=b FROM t1, t2 WHERE +y=+b;
  }
} {}




finish_test

Added test/wherelimit.test.

























































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# 2008 October 6
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the LIMIT ... OFFSET ... clause
#  of UPDATE and DELETE statements.
#
# $Id: wherelimit.test,v 1.2 2008/10/10 18:25:46 shane Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

proc create_test_data {size} {
  # Build some test data
  #
  execsql {
    DROP TABLE IF EXISTS t1;
    CREATE TABLE t1(x int, y int);
    BEGIN;
  }
  for {set i 1} {$i<=$size} {incr i} {
    for {set j 1} {$j<=$size} {incr j} {
      execsql "INSERT INTO t1 VALUES([expr {$i}],[expr {$j}])"
    }
  }
  execsql {
    COMMIT;
  }
  return {}
}

ifcapable {update_delete_limit} {

  # check syntax error support
  do_test wherelimit-0.1 {
    catchsql {DELETE FROM t1 ORDER BY x}
  } {1 {ORDER BY without LIMIT on DELETE}}
  do_test wherelimit-0.2 {
    catchsql {DELETE FROM t1 WHERE x=1 ORDER BY x}
  } {1 {ORDER BY without LIMIT on DELETE}}
  do_test wherelimit-0.3 {
    catchsql {UPDATE t1 SET y=1 WHERE x=1 ORDER BY x}
  } {1 {ORDER BY without LIMIT on UPDATE}}

  # no AS on table sources
  do_test wherelimit-0.4 {
    catchsql {DELETE FROM t1 AS a WHERE x=1}
  } {1 {near "AS": syntax error}}
  do_test wherelimit-0.5 {
    catchsql {UPDATE t1 AS a SET y=1 WHERE x=1}
  } {1 {near "AS": syntax error}}

  # OFFSET w/o LIMIT
  do_test wherelimit-0.6 {
    catchsql {DELETE FROM t1 WHERE x=1 OFFSET 2}
  } {1 {near "OFFSET": syntax error}}
  do_test wherelimit-0.7 {
    catchsql {UPDATE t1 SET y=1 WHERE x=1 OFFSET 2}
  } {1 {near "OFFSET": syntax error}}


  # check deletes w/o where clauses but with limit/offsets
  create_test_data 5
  do_test wherelimit-1.0 {
    execsql {SELECT count(*) FROM t1}
  } {25}
  do_test wherelimit-1.1 {
    execsql {DELETE FROM t1}
    execsql {SELECT count(*) FROM t1}
  } {0}
  create_test_data 5
  do_test wherelimit-1.2 {
    execsql {DELETE FROM t1 LIMIT 5}
    execsql {SELECT count(*) FROM t1}
  } {20}
  do_test wherelimit-1.3 {
    # limit 5
    execsql {DELETE FROM t1 ORDER BY x LIMIT 5}
    execsql {SELECT count(*) FROM t1}
  } {15}
  do_test wherelimit-1.4 {
    # limit 5, offset 2
    execsql {DELETE FROM t1 ORDER BY x LIMIT 5 OFFSET 2}
    execsql {SELECT count(*) FROM t1}
  } {10}
  do_test wherelimit-1.5 {
    # limit 5, offset -2
    execsql {DELETE FROM t1 ORDER BY x LIMIT 5 OFFSET -2}
    execsql {SELECT count(*) FROM t1}
  } {5}
  do_test wherelimit-1.6 {
    # limit -5 (no limit), offset 2
    execsql {DELETE FROM t1 ORDER BY x LIMIT 2, -5}
    execsql {SELECT count(*) FROM t1}
  } {2}
  do_test wherelimit-1.7 {
    # limit 5, offset -2 (no offset)
    execsql {DELETE FROM t1 ORDER BY x LIMIT -2, 5}
    execsql {SELECT count(*) FROM t1}
  } {0}
  create_test_data 5
  do_test wherelimit-1.8 {
    # limit -5 (no limit), offset -2 (no offset)
    execsql {DELETE FROM t1 ORDER BY x LIMIT -2, -5}
    execsql {SELECT count(*) FROM t1}
  } {0}
  create_test_data 3
  do_test wherelimit-1.9 {
    # limit 5, offset 2
    execsql {DELETE FROM t1 ORDER BY x LIMIT 2, 5}
    execsql {SELECT count(*) FROM t1}
  } {4}
  do_test wherelimit-1.10 {
    # limit 5, offset 5
    execsql {DELETE FROM t1 ORDER BY x LIMIT 5 OFFSET 5}
    execsql {SELECT count(*) FROM t1}
  } {4}
  do_test wherelimit-1.11 {
    # limit 50, offset 30
    execsql {DELETE FROM t1 ORDER BY x LIMIT 50 OFFSET 30}
    execsql {SELECT count(*) FROM t1}
  } {4}
  do_test wherelimit-1.12 {
    # limit 50, offset 30
    execsql {DELETE FROM t1 ORDER BY x LIMIT 30, 50}
    execsql {SELECT count(*) FROM t1}
  } {4}
  do_test wherelimit-1.13 {
    execsql {DELETE FROM t1 ORDER BY x LIMIT 50 OFFSET 50}
    execsql {SELECT count(*) FROM t1}
  } {4}


  create_test_data 6
  do_test wherelimit-2.0 {
    execsql {SELECT count(*) FROM t1}
  } {36}
  do_test wherelimit-2.1 {
    execsql {DELETE FROM t1 WHERE x=1}
    execsql {SELECT count(*) FROM t1}
  } {30}
  create_test_data 6
  do_test wherelimit-2.2 {
    execsql {DELETE FROM t1 WHERE x=1 LIMIT 5}
    execsql {SELECT count(*) FROM t1}
  } {31}
  do_test wherelimit-2.3 {
    # limit 5
    execsql {DELETE FROM t1 WHERE x=1 ORDER BY x LIMIT 5}
    execsql {SELECT count(*) FROM t1}
  } {30}
  do_test wherelimit-2.4 {
    # limit 5, offset 2
    execsql {DELETE FROM t1 WHERE x=2 ORDER BY x LIMIT 5 OFFSET 2}
    execsql {SELECT count(*) FROM t1}
  } {26}
  do_test wherelimit-2.5 {
    # limit 5, offset -2
    execsql {DELETE FROM t1 WHERE x=2 ORDER BY x LIMIT 5 OFFSET -2}
    execsql {SELECT count(*) FROM t1}
  } {24}
  do_test wherelimit-2.6 {
    # limit -5 (no limit), offset 2
    execsql {DELETE FROM t1 WHERE x=3 ORDER BY x LIMIT 2, -5}
    execsql {SELECT count(*) FROM t1}
  } {20}
  do_test wherelimit-2.7 {
    # limit 5, offset -2 (no offset)
    execsql {DELETE FROM t1 WHERE x=3 ORDER BY x LIMIT -2, 5}
    execsql {SELECT count(*) FROM t1}
  } {18}
  do_test wherelimit-2.8 {
    # limit -5 (no limit), offset -2 (no offset)
    execsql {DELETE FROM t1 WHERE x=4 ORDER BY x LIMIT -2, -5}
    execsql {SELECT count(*) FROM t1}
  } {12}
  create_test_data 6
  do_test wherelimit-2.9 {
    # limit 5, offset 2
    execsql {DELETE FROM t1 WHERE x=5 ORDER BY x LIMIT 2, 5}
    execsql {SELECT count(*) FROM t1}
  } {32}
  do_test wherelimit-2.10 {
    # limit 5, offset 5
    execsql {DELETE FROM t1 WHERE x=6 ORDER BY x LIMIT 5 OFFSET 5}
    execsql {SELECT count(*) FROM t1}
  } {31}
  do_test wherelimit-2.11 {
    # limit 50, offset 30
    execsql {DELETE FROM t1 WHERE x=1 ORDER BY x LIMIT 50 OFFSET 30}
    execsql {SELECT count(*) FROM t1}
  } {31}
  do_test wherelimit-2.12 {
    # limit 50, offset 30
    execsql {DELETE FROM t1 WHERE x=2 ORDER BY x LIMIT 30, 50}
    execsql {SELECT count(*) FROM t1}
  } {31}
  do_test wherelimit-2.13 {
    execsql {DELETE FROM t1 WHERE x=3 ORDER BY x LIMIT 50 OFFSET 50}
    execsql {SELECT count(*) FROM t1}
  } {31}


  create_test_data 6
  do_test wherelimit-3.0 {
    execsql {SELECT count(*) FROM t1}
  } {36}
  do_test wherelimit-3.1 {
    execsql {UPDATE t1 SET y=1 WHERE x=1}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {11}
  create_test_data 6
  do_test wherelimit-3.2 {
    execsql {UPDATE t1 SET y=1 WHERE x=1 LIMIT 5}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {10}
  do_test wherelimit-3.3 {
    # limit 5
    execsql {UPDATE t1 SET y=2 WHERE x=2 ORDER BY x LIMIT 5}
    execsql {SELECT count(*) FROM t1 WHERE y=2}
  } {9}
  create_test_data 6
  do_test wherelimit-3.4 {
    # limit 5, offset 2
    execsql {UPDATE t1 SET y=2 WHERE x=2 ORDER BY x LIMIT 5 OFFSET 2}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {6}
  do_test wherelimit-3.5 {
    # limit 5, offset -2
    execsql {UPDATE t1 SET y=2 WHERE x=2 ORDER BY x LIMIT 5 OFFSET -2}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {5}
  do_test wherelimit-3.6 {
    # limit -5 (no limit), offset 2
    execsql {UPDATE t1 SET y=3 WHERE x=3 ORDER BY x LIMIT 2, -5}
    execsql {SELECT count(*) FROM t1 WHERE y=3}
  } {8}
  do_test wherelimit-3.7 {
    # limit 5, offset -2 (no offset)
    execsql {UPDATE t1 SET y=3 WHERE x=3 ORDER BY x LIMIT -2, 5}
    execsql {SELECT count(*) FROM t1 WHERE y=3}
  } {10}

  do_test wherelimit-3.8 {
    # limit -5 (no limit), offset -2 (no offset)
    execsql {UPDATE t1 SET y=4 WHERE x=4 ORDER BY x LIMIT -2, -5}
    execsql {SELECT count(*) FROM t1 WHERE y=4}
  } {9}
  create_test_data 6
  do_test wherelimit-3.9 {
    # limit 5, offset 2
    execsql {UPDATE t1 SET y=4 WHERE x=5 ORDER BY x LIMIT 2, 5}
    execsql {SELECT count(*) FROM t1 WHERE y=4}
  } {9}
  do_test wherelimit-3.10 {
    # limit 5, offset 5
    execsql {UPDATE t1 SET y=4 WHERE x=6 ORDER BY x LIMIT 5 OFFSET 5}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {6}
  do_test wherelimit-3.11 {
    # limit 50, offset 30
    execsql {UPDATE t1 SET y=1 WHERE x=1 ORDER BY x LIMIT 50 OFFSET 30}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {6}
  do_test wherelimit-3.12 {
    # limit 50, offset 30
    execsql {UPDATE t1 SET y=1 WHERE x=2 ORDER BY x LIMIT 30, 50}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {6}
  do_test wherelimit-3.13 {
    execsql {UPDATE t1 SET y=1 WHERE x=3 ORDER BY x LIMIT 50 OFFSET 50}
    execsql {SELECT count(*) FROM t1 WHERE y=1}
  } {6}

}

finish_test

Added test/zeroblob.test.







































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# 2007 May 02
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing of the zero-filled blob functionality
# including the sqlite3_bind_zeroblob(), sqlite3_result_zeroblob(),
# and the built-in zeroblob() SQL function.
#
# $Id: zeroblob.test,v 1.14 2009/07/14 02:33:02 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !incrblob {
  finish_test
  return
}

# When zeroblob() is used for the last field of a column, then the
# content of the zeroblob is never instantiated on the VDBE stack.
# But it does get inserted into the database correctly.
#
db eval {PRAGMA cache_size=10}
sqlite3_memory_highwater 1
unset -nocomplain memused
set memused [sqlite3_memory_used]
do_test zeroblob-1.1 {
  execsql {
    CREATE TABLE t1(a,b,c,d);
  }
  set ::sqlite3_max_blobsize 0
  execsql {
    INSERT INTO t1 VALUES(2,3,4,zeroblob(1000000));
  }
  set ::sqlite3_max_blobsize
} {10}
do_test zeroblob-1.1.1 {
  expr {[sqlite3_memory_highwater]<$::memused+25000}
} {1}
do_test zeroblob-1.2 {
  execsql {
    SELECT length(d) FROM t1
  }
} {1000000}

# If a non-NULL column follows the zeroblob, then the content of
# the zeroblob must be instantiated.
#
do_test zeroblob-1.3 {
  set ::sqlite3_max_blobsize 0
  execsql {
    INSERT INTO t1 VALUES(3,4,zeroblob(10000),5);
  }
  set ::sqlite3_max_blobsize
} {10010}
do_test zeroblob-1.4 {
  execsql {
    SELECT length(c), length(d) FROM t1
  }
} {1 1000000 10000 1}

# Multiple zeroblobs can appear at the end of record.  No instantiation
# of the blob content occurs on the stack.
#
do_test zeroblob-1.5 {
  set ::sqlite3_max_blobsize 0
  execsql {
    INSERT INTO t1 VALUES(4,5,zeroblob(10000),zeroblob(10000));
  }
  set ::sqlite3_max_blobsize
} {11}
do_test zeroblob-1.6 {
  execsql {
    SELECT length(c), length(d) FROM t1
  }
} {1 1000000 10000 1 10000 10000}

# NULLs can follow the zeroblob() or be intermixed with zeroblobs and
# no instantiation of the zeroblobs occurs on the stack.
#
do_test zeroblob-1.7 {
  set ::sqlite3_max_blobsize 0
  execsql {
    INSERT INTO t1 VALUES(5,zeroblob(10000),NULL,zeroblob(10000));
  }
  set ::sqlite3_max_blobsize
} {10}
do_test zeroblob-1.8 {
  execsql {
    SELECT length(b), length(d) FROM t1 WHERE a=5
  }
} {10000 10000}

# Comparisons against zeroblobs work.
#
do_test zeroblob-2.1 {
  execsql {
    SELECT a FROM t1 WHERE b=zeroblob(10000)
  }
} {5}

# Comparisons against zeroblobs work even when indexed.
#
do_test zeroblob-2.2 {
  execsql {
    CREATE INDEX i1_1 ON t1(b);
    SELECT a FROM t1 WHERE b=zeroblob(10000);
  }
} {5}

# DISTINCT works for zeroblobs
#
ifcapable bloblit&&subquery&&compound {
  do_test zeroblob-3.1 {
    execsql {
      SELECT count(DISTINCT a) FROM (
        SELECT x'00000000000000000000' AS a
        UNION ALL
        SELECT zeroblob(10) AS a
      )
    }
  } {1}
}

# Concatentation works with zeroblob
#
ifcapable bloblit {
  do_test zeroblob-4.1 {
    execsql {
      SELECT hex(zeroblob(2) || x'61')
    }
  } {000061}
}

# Check various CAST(...) operations on zeroblob.
#
do_test zeroblob-5.1 {
  execsql {
    SELECT CAST (zeroblob(100) AS REAL);
  }
} {0.0}
do_test zeroblob-5.2 {
  execsql {
    SELECT CAST (zeroblob(100) AS INTEGER);
  }
} {0}
do_test zeroblob-5.3 {
  execsql {
    SELECT CAST (zeroblob(100) AS TEXT);
  }
} {{}}
do_test zeroblob-5.4 {
  execsql {
    SELECT CAST(zeroblob(100) AS BLOB);
  }
} [execsql {SELECT zeroblob(100)}]
  

# Check for malicious use of zeroblob.  Make sure nothing crashes.
#
do_test zeroblob-6.1.1 { 
  execsql {select zeroblob(-1)} 
} {{}} 
do_test zeroblob-6.1.2 { 
  execsql {select zeroblob(-10)} 
} {{}} 
do_test zeroblob-6.1.3 { 
  execsql {select zeroblob(-100)} 
} {{}} 
do_test zeroblob-6.2 { 
  execsql {select length(zeroblob(-1))} 
} {0} 
do_test zeroblob-6.3 { 
  execsql {select zeroblob(-1)|1} 
} {1} 
do_test zeroblob-6.4 { 
  catchsql {select length(zeroblob(2147483648))} 
} {1 {string or blob too big}} 
do_test zeroblob-6.5 { 
  catchsql {select zeroblob(2147483648)} 
} {1 {string or blob too big}}
do_test zeroblob-6.6 {
  execsql {select hex(zeroblob(-1))}
} {{}}
do_test zeroblob-6.7 {
  execsql {select typeof(zeroblob(-1))}
} {blob}

# Test bind_zeroblob()
#
sqlite3_memory_highwater 1
unset -nocomplain memused
set memused [sqlite3_memory_used]
do_test zeroblob-7.1 {
  set ::STMT [sqlite3_prepare $::DB "SELECT length(?)" -1 DUMMY]
  set ::sqlite3_max_blobsize 0
  sqlite3_bind_zeroblob $::STMT 1 450000
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test zeroblob-7.2 {
  sqlite3_column_int $::STMT 0
} {450000}
do_test zeroblob-7.3 {
  sqlite3_finalize $::STMT
} {SQLITE_OK}
do_test zeroblob-7.4 {
  set ::sqlite3_max_blobsize
} {0}
do_test zeroblob-7.5 {
  expr {[sqlite3_memory_highwater]<$::memused+10000}
} {1}

# Test that MakeRecord can handle a value with some real content
# and a zero-blob tail.
#
do_test zeroblob-8.1 {
  llength [execsql {
    SELECT 'hello' AS a, zeroblob(10) as b from t1 ORDER BY a, b;
  }]
} {8}


# Ticket #3965
# zeroblobs on either size of an IN operator
#
do_test zeroblob-9.1 {
  db eval {SELECT x'0000' IN (x'000000')}
} {0}
do_test zeroblob-9.2 {
  db eval {SELECT x'0000' IN (x'0000')}
} {1}
do_test zeroblob-9.3 {
  db eval {SELECT zeroblob(2) IN (x'000000')}
} {0}
do_test zeroblob-9.4 {
  db eval {SELECT zeroblob(2) IN (x'0000')}
} {1}
do_test zeroblob-9.5 {
  db eval {SELECT x'0000' IN (zeroblob(3))}
} {0}
do_test zeroblob-9.6 {
  db eval {SELECT x'0000' IN (zeroblob(2))}
} {1}
do_test zeroblob-9.7 {
  db eval {SELECT zeroblob(2) IN (zeroblob(3))}
} {0}
do_test zeroblob-9.8 {
  db eval {SELECT zeroblob(2) IN (zeroblob(2))}
} {1}


finish_test

Added tool/diffdb.c.

























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
** A utility for printing the differences between two SQLite database files.
*/
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


#define PAGESIZE 1024
static int db1 = -1;
static int db2 = -1;

int main(int argc, char **argv){
  int iPg;
  unsigned char a1[PAGESIZE], a2[PAGESIZE];
  if( argc!=3 ){
    fprintf(stderr,"Usage: %s FILENAME FILENAME\n", argv[0]);
    exit(1);
  }
  db1 = open(argv[1], O_RDONLY);
  if( db1<0 ){
    fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]);
    exit(1);
  }
  db2 = open(argv[2], O_RDONLY);
  if( db2<0 ){
    fprintf(stderr,"%s: can't open %s\n", argv[0], argv[2]);
    exit(1);
  }
  iPg = 1;
  while( read(db1, a1, PAGESIZE)==PAGESIZE && read(db2,a2,PAGESIZE)==PAGESIZE ){
    if( memcmp(a1,a2,PAGESIZE) ){
      printf("Page %d\n", iPg);
    }
    iPg++;
  }
  printf("%d pages checked\n", iPg-1);
  close(db1);
  close(db2);
}

Added tool/fragck.tcl.











































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# Run this TCL script using "testfixture" to get a report that shows
# the sequence of database pages used by a particular table or index.
# This information is used for fragmentation analysis.
#

# Get the name of the database to analyze
#

if {[llength $argv]!=2} {
  puts stderr "Usage: $argv0 database-name table-or-index-name"
  exit 1
}
set file_to_analyze [lindex $argv 0]
if {![file exists $file_to_analyze]} {
  puts stderr "No such file: $file_to_analyze"
  exit 1
}
if {![file readable $file_to_analyze]} {
  puts stderr "File is not readable: $file_to_analyze"
  exit 1
}
if {[file size $file_to_analyze]<512} {
  puts stderr "Empty or malformed database: $file_to_analyze"
  exit 1
}
set objname [lindex $argv 1]

# Open the database
#
sqlite3 db [lindex $argv 0]
set DB [btree_open [lindex $argv 0] 1000 0]

# This proc is a wrapper around the btree_cursor_info command. The
# second argument is an open btree cursor returned by [btree_cursor].
# The first argument is the name of an array variable that exists in
# the scope of the caller. If the third argument is non-zero, then
# info is returned for the page that lies $up entries upwards in the
# tree-structure. (i.e. $up==1 returns the parent page, $up==2 the 
# grandparent etc.)
#
# The following entries in that array are filled in with information retrieved
# using [btree_cursor_info]:
#
#   $arrayvar(page_no)             =  The page number
#   $arrayvar(entry_no)            =  The entry number
#   $arrayvar(page_entries)        =  Total number of entries on this page
#   $arrayvar(cell_size)           =  Cell size (local payload + header)
#   $arrayvar(page_freebytes)      =  Number of free bytes on this page
#   $arrayvar(page_freeblocks)     =  Number of free blocks on the page
#   $arrayvar(payload_bytes)       =  Total payload size (local + overflow)
#   $arrayvar(header_bytes)        =  Header size in bytes
#   $arrayvar(local_payload_bytes) =  Local payload size
#   $arrayvar(parent)              =  Parent page number
# 
proc cursor_info {arrayvar csr {up 0}} {
  upvar $arrayvar a
  foreach [list a(page_no) \
                a(entry_no) \
                a(page_entries) \
                a(cell_size) \
                a(page_freebytes) \
                a(page_freeblocks) \
                a(payload_bytes) \
                a(header_bytes) \
                a(local_payload_bytes) \
                a(parent) \
                a(first_ovfl) ] [btree_cursor_info $csr $up] break
}

# Determine the page-size of the database. This global variable is used
# throughout the script.
#
set pageSize [db eval {PRAGMA page_size}]

# Find the root page of table or index to be analyzed.  Also find out
# if the object is a table or an index.
#
if {$objname=="sqlite_master"} {
  set rootpage 1
  set type table
} else {
  db eval {
    SELECT rootpage, type FROM sqlite_master
     WHERE name=$objname
  } break
  if {![info exists rootpage]} {
    puts stderr "no such table or index: $objname"
    exit 1
  }
  if {$type!="table" && $type!="index"} {
    puts stderr "$objname is something other than a table or index"
    exit 1
  }
  if {![string is integer -strict $rootpage]} {
    puts stderr "invalid root page for $objname: $rootpage"
    exit 1
  } 
}

# The cursor $csr is pointing to an entry.  Print out information
# about the page that $up levels above that page that contains
# the entry.  If $up==0 use the page that contains the entry.
# 
# If information about the page has been printed already, then
# this is a no-op.
# 
proc page_info {csr up} {
  global seen
  cursor_info ci $csr $up
  set pg $ci(page_no)
  if {[info exists seen($pg)]} return
  set seen($pg) 1

  # Do parent pages first
  #
  if {$ci(parent)} {
    page_info $csr [expr {$up+1}]
  }

  # Find the depth of this page
  #
  set depth 1
  set i $up
  while {$ci(parent)} {
    incr i
    incr depth
    cursor_info ci $csr $i
  }

  # print the results
  #
  puts [format {LEVEL %d:  %6d} $depth $pg]
}  

  
  

# Loop through the object and print out page numbers
#
set csr [btree_cursor $DB $rootpage 0]
for {btree_first $csr} {![btree_eof $csr]} {btree_next $csr} {
  page_info $csr 0
  set i 1
  foreach pg [btree_ovfl_info $DB $csr] {
    puts [format {OVFL %3d: %6d} $i $pg]
    incr i
  }
}
exit 0

Added tool/genfkey.README.



















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137

OVERVIEW

  The SQLite library is capable of parsing SQL foreign key constraints 
  supplied as part of CREATE TABLE statements, but it does not actually 
  implement them. However, most of the features of foreign keys may be
  implemented using SQL triggers, which SQLite does support. This text
  file describes a feature of the SQLite shell tool (sqlite3) that
  extracts foreign key definitions from an existing SQLite database and
  creates the set of CREATE TRIGGER statements required to implement
  the foreign key constraints.

CAPABILITIES

  An SQL foreign key is a constraint that requires that each row in
  the "child" table corresponds to a row in the "parent" table. For
  example, the following schema:

    CREATE TABLE parent(a, b, c, PRIMARY KEY(a, b));
    CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent(a, b));

  implies that for each row in table "child", there must be a row in
  "parent" for which the expression (child.d==parent.a AND child.e==parent.b) 
  is true. The columns in the parent table are required to be either the
  primary key columns or subject to a UNIQUE constraint. There is no such
  requirement for the columns of the child table.

  At this time, all foreign keys are implemented as if they were 
  "MATCH NONE", even if the declaration specified "MATCH PARTIAL" or 
  "MATCH FULL". "MATCH NONE" means that if any of the key columns in
  the child table are NULL, then there is no requirement for a corresponding
  row in the parent table. So, taking this into account, the expression that
  must be true for every row of the child table in the above example is
  actually:

      (child.d IS NULL) OR 
      (child.e IS NULL) OR 
      (child.d==parent.a AND child.e==parent.b)

  Attempting to insert or update a row in the child table so that the 
  affected row violates this constraint results in an exception being 
  thrown.

  The effect of attempting to delete or update a row in the parent table 
  so that the constraint becomes untrue for one or more rows in the child
  table depends on the "ON DELETE" or "ON UPDATE" actions specified as
  part of the foreign key definition, respectively. Three different actions
  are supported: "RESTRICT" (the default), "CASCADE" and "SET NULL". SQLite
  will also parse the "SET DEFAULT" action, but this is not implemented
  and "RESTRICT" is used instead.

    RESTRICT: Attempting to update or delete a row in the parent table so
              that the constraint becomes untrue for one or more rows in
              the child table is not allowed. An exception is thrown.

    CASCADE:  Instead of throwing an exception, all corresponding child table
              rows are either deleted (if the parent row is being deleted)
              or updated to match the new parent key values (if the parent 
              row is being updated).

    SET NULL: Instead of throwing an exception, the foreign key fields of
              all corresponding child table rows are set to NULL.

LIMITATIONS

  Apart from those limitiations described above:

    * Implicit mapping to composite primary keys is not supported. If
      a parent table has a composite primary key, then any child table
      that refers to it must explicitly map each column. For example, given
      the following definition of table "parent":

        CREATE TABLE parent(a, b, c, PRIMARY KEY(a, b));

      only the first of the following two definitions of table "child"
      is supported:

        CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent(a, b));
        CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent);

      An implicit reference to a composite primary key is detected as an
      error when the program is run (see below).

    * SQLite does not support recursive triggers, and therefore this program
      does not support recursive CASCADE or SET NULL foreign key 
      relationships. If the parent and the child tables of a CASCADE or
      SET NULL foreign key are the same table, the generated triggers will
      malfunction. This is also true if the recursive foreign key constraint
      is indirect (for example if table A references table B which references
      table A with a CASCADE or SET NULL foreign key constraint).

      Recursive CASCADE or SET NULL foreign key relationships are *not*
      detected as errors when the program is run. Buyer beware.

USAGE

  The functionality is accessed through an sqlite3 shell tool "dot-command":

    .genfkey ?--no-drop? ?--ignore-errors? ?--exec?

  When this command is run, it first checks the schema of the open SQLite
  database for foreign key related errors or inconsistencies. For example,
  a foreign key that refers to a parent table that does not exist, or
  a foreign key that refers to columns in a parent table that are not
  guaranteed to be unique. If such errors are found and the --ignore-errors
  option was not present, a message for each one is printed to stderr and
  no further processing takes place.

  If errors are found and the --ignore-errors option is passed, then
  no error messages are printed. No "CREATE TRIGGER" statements are generated
  for foriegn-key definitions that contained errors, they are silently
  ignored by subsequent processing.

  All triggers generated by this command have names that match the pattern
  "genfkey*". Unless the --no-drop option is specified, then the program
  also generates a "DROP TRIGGER" statement for each trigger that exists
  in the database with a name that matches this pattern. This allows the
  program to be used to upgrade a database schema for which foreign key
  triggers have already been installed (i.e. after new tables are created
  or existing tables dropped).

  Finally, a series of SQL trigger definitions (CREATE TRIGGER statements) 
  that implement the foreign key constraints found in the database schema are
  generated.

  If the --exec option was passed, then all generated SQL is immediately
  executed on the database. Otherwise, the generated SQL strings are output
  in the same way as the results of SELECT queries are. Normally, this means
  they will be printed to stdout, but this can be configured using other
  dot-commands (i.e. ".output").

  The simplest way to activate the foriegn key definitions in a database
  is simply to open it using the shell tool and enter the command 
  ".genfkey --exec":

    sqlite> .genfkey --exec

Added tool/genfkey.test.





































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

package require sqlite3

proc do_test {name cmd expected} {
  puts -nonewline "$name ..."
  set res [uplevel $cmd]
  if {$res eq $expected} {
    puts Ok
  } else {
    puts Error
    puts "  Got: $res"
    puts "  Expected: $expected"
    exit
  }
}

proc execsql {sql} {
  uplevel [list db eval $sql]
}

proc catchsql {sql} {
  set rc [catch {uplevel [list db eval $sql]} msg]
  list $rc $msg
}

file delete -force test.db test.db.journal
sqlite3 db test.db

# The following tests - genfkey-1.* - test RESTRICT foreign keys.
#
do_test genfkey-1.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c));
    CREATE TABLE t2(e REFERENCES t1, f);
    CREATE TABLE t3(g, h, i, FOREIGN KEY (h, i) REFERENCES t1(b, c));
  }
} {}
do_test genfkey-1.2 {
  execsql [exec ./sqlite3 test.db .genfkey]
} {}
do_test genfkey-1.3 {
  catchsql { INSERT INTO t2 VALUES(1, 2) }
} {1 {constraint failed}}
do_test genfkey-1.4 {
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t2 VALUES(1, 2);
  }
} {}
do_test genfkey-1.5 {
  execsql { INSERT INTO t2 VALUES(NULL, 3) }
} {}
do_test genfkey-1.6 {
  catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL }
} {1 {constraint failed}}
do_test genfkey-1.7 {
  execsql { UPDATE t2 SET e = 1 WHERE e IS NULL }
} {}
do_test genfkey-1.8 {
  execsql { UPDATE t2 SET e = NULL WHERE f = 3 }
} {}
do_test genfkey-1.9 {
  catchsql { UPDATE t1 SET a = 10 }
} {1 {constraint failed}}
do_test genfkey-1.9a {
  catchsql { UPDATE t1 SET a = NULL }
} {1 {datatype mismatch}}
do_test genfkey-1.10 {
  catchsql { DELETE FROM t1 }
} {1 {constraint failed}}
do_test genfkey-1.11 {
  execsql { UPDATE t2 SET e = NULL }
} {}
do_test genfkey-1.12 {
  execsql { 
    UPDATE t1 SET a = 10 ;
    DELETE FROM t1;
    DELETE FROM t2;
  }
} {}

do_test genfkey-1.13 {
  execsql {
    INSERT INTO t3 VALUES(1, NULL, NULL);
    INSERT INTO t3 VALUES(1, 2, NULL);
    INSERT INTO t3 VALUES(1, NULL, 3);
  }
} {}
do_test genfkey-1.14 {
  catchsql { INSERT INTO t3 VALUES(3, 1, 4) }
} {1 {constraint failed}}
do_test genfkey-1.15 {
  execsql { 
    INSERT INTO t1 VALUES(1, 1, 4);
    INSERT INTO t3 VALUES(3, 1, 4);
  }
} {}
do_test genfkey-1.16 {
  catchsql { DELETE FROM t1 }
} {1 {constraint failed}}
do_test genfkey-1.17 {
  catchsql { UPDATE t1 SET b = 10}
} {1 {constraint failed}}
do_test genfkey-1.18 {
  execsql { UPDATE t1 SET a = 10}
} {}
do_test genfkey-1.19 {
  catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3}
} {1 {constraint failed}}

do_test genfkey-1.X {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    DROP TABLE t3;
  }
} {}

# The following tests - genfkey-2.* - test CASCADE foreign keys.
#
do_test genfkey-2.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c));
    CREATE TABLE t2(e REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE, f);
    CREATE TABLE t3(g, h, i, 
        FOREIGN KEY (h, i) 
        REFERENCES t1(b, c) ON UPDATE CASCADE ON DELETE CASCADE
    );
  }
} {}
do_test genfkey-2.2 {
  execsql [exec ./sqlite3 test.db .genfkey]
} {}
do_test genfkey-2.3 {
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(4, 'four');
  }
} {}
do_test genfkey-2.4 {
  execsql {
    UPDATE t1 SET a = 2 WHERE a = 1;
    SELECT * FROM t2;
  }
} {2 one 4 four}
do_test genfkey-2.5 {
  execsql {
    DELETE FROM t1 WHERE a = 4;
    SELECT * FROM t2;
  }
} {2 one}
do_test genfkey-2.6 {
  execsql {
    INSERT INTO t3 VALUES('hello', 2, 3);
    UPDATE t1 SET c = 2;
    SELECT * FROM t3;
  }
} {hello 2 2}
do_test genfkey-2.7 {
  execsql {
    DELETE FROM t1;
    SELECT * FROM t3;
  }
} {}
do_test genfkey-2.X {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    DROP TABLE t3;
  }
} {}


# The following tests - genfkey-3.* - test SET NULL foreign keys.
#
do_test genfkey-3.1 {
  execsql {
    CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(c, b));
    CREATE TABLE t2(e REFERENCES t1 ON UPDATE SET NULL ON DELETE SET NULL, f);
    CREATE TABLE t3(g, h, i, 
        FOREIGN KEY (h, i) 
        REFERENCES t1(b, c) ON UPDATE SET NULL ON DELETE SET NULL
    );
  }
} {}
do_test genfkey-3.2 {
  execsql [exec ./sqlite3 test.db .genfkey]
} {}
do_test genfkey-3.3 {
  execsql {
    INSERT INTO t1 VALUES(1, 2, 3);
    INSERT INTO t1 VALUES(4, 5, 6);
    INSERT INTO t2 VALUES(1, 'one');
    INSERT INTO t2 VALUES(4, 'four');
  }
} {}
do_test genfkey-3.4 {
  execsql {
    UPDATE t1 SET a = 2 WHERE a = 1;
    SELECT * FROM t2;
  }
} {{} one 4 four}
do_test genfkey-3.5 {
  execsql {
    DELETE FROM t1 WHERE a = 4;
    SELECT * FROM t2;
  }
} {{} one {} four}
do_test genfkey-3.6 {
  execsql {
    INSERT INTO t3 VALUES('hello', 2, 3);
    UPDATE t1 SET c = 2;
    SELECT * FROM t3;
  }
} {hello {} {}}
do_test genfkey-2.7 {
  execsql {
    UPDATE t3 SET h = 2, i = 2;
    DELETE FROM t1;
    SELECT * FROM t3;
  }
} {hello {} {}}
do_test genfkey-3.X {
  execsql {
    DROP TABLE t1;
    DROP TABLE t2;
    DROP TABLE t3;
  }
} {}

# The following tests - genfkey-4.* - test that errors in the schema
# are detected correctly.
#
do_test genfkey-4.1 {
  execsql {
    CREATE TABLE t1(a REFERENCES nosuchtable, b);
    CREATE TABLE t2(a REFERENCES t1, b);

    CREATE TABLE t3(a, b, c, PRIMARY KEY(a, b));
    CREATE TABLE t4(a, b, c, FOREIGN KEY(c, b) REFERENCES t3);

    CREATE TABLE t5(a REFERENCES t4(d), b, c);
    CREATE TABLE t6(a REFERENCES t4(a), b, c);
    CREATE TABLE t7(a REFERENCES t3(a), b, c);
    CREATE TABLE t8(a REFERENCES nosuchtable(a), b, c);
  }
} {}

do_test genfkey-4.X {
  set rc [catch {exec ./sqlite3 test.db .genfkey} msg]
  list $rc $msg
} "1 {[string trim {
Error in table t5: foreign key columns do not exist
Error in table t8: foreign key columns do not exist
Error in table t4: implicit mapping to composite primary key
Error in table t1: implicit mapping to non-existant primary key
Error in table t2: implicit mapping to non-existant primary key
Error in table t6: foreign key is not unique
Error in table t7: foreign key is not unique
}]}"

# Test that ticket #3800 has been resolved.
#
do_test genfkey-5.1 {
  execsql {
    DROP TABLE t1; DROP TABLE t2; DROP TABLE t3;
    DROP TABLE t4; DROP TABLE t5; DROP TABLE t6;
    DROP TABLE t7; DROP TABLE t8;
  }
} {}
do_test genfkey-5.2 {
  execsql {
    CREATE TABLE "t.3" (c1 PRIMARY KEY);
    CREATE TABLE t13 (c1, foreign key(c1) references "t.3"(c1));
  }
} {}
do_test genfkey-5.3 {
  set rc [catch {exec ./sqlite3 test.db .genfkey} msg]
} {0}
do_test genfkey-5.4 {
  db eval $msg
} {}
do_test genfkey-5.5 {
  catchsql { INSERT INTO t13 VALUES(1) }
} {1 {constraint failed}}
do_test genfkey-5.5 {
  catchsql { 
    INSERT INTO "t.3" VALUES(1);
    INSERT INTO t13 VALUES(1);
  }
} {0 {}}

# Test also column names that require quoting.
do_test genfkey-6.1 {
  execsql {
    DROP TABLE "t.3";
    DROP TABLE t13;
    CREATE TABLE p(
      "a.1 first", "b.2 second", 
      UNIQUE("a.1 first", "b.2 second")
    );
    CREATE TABLE c(
      "c.1 I", "d.2 II", 
        FOREIGN KEY("c.1 I", "d.2 II") 
        REFERENCES p("a.1 first", "b.2 second")
        ON UPDATE CASCADE ON DELETE CASCADE
    );
  }
} {}
do_test genfkey-6.2 {
  set rc [catch {exec ./sqlite3 test.db .genfkey} msg]
} {0}
do_test genfkey-6.3 {
  execsql $msg
  execsql {
    INSERT INTO p VALUES('A', 'B');
    INSERT INTO p VALUES('C', 'D');
    INSERT INTO c VALUES('A', 'B');
    INSERT INTO c VALUES('C', 'D');
    UPDATE p SET "a.1 first" = 'X' WHERE rowid = 1;
    DELETE FROM p WHERE rowid = 2;
  }
  execsql { SELECT * FROM c }
} {X B}

do_test genfkey-6.4 {
  execsql {
    DROP TABLE p;
    DROP TABLE c;
    CREATE TABLE parent("a.1", PRIMARY KEY("a.1"));
    CREATE TABLE child("b.2", FOREIGN KEY("b.2") REFERENCES parent("a.1"));
  }
  set rc [catch {exec ./sqlite3 test.db .genfkey} msg]
} {0}
do_test genfkey-6.5 {
  execsql $msg
  execsql {
    INSERT INTO parent VALUES(1);
    INSERT INTO child VALUES(1);
  }
  catchsql { UPDATE parent SET "a.1"=0 }
} {1 {constraint failed}}
do_test genfkey-6.6 {
  catchsql { UPDATE child SET "b.2"=7 }
} {1 {constraint failed}}
do_test genfkey-6.7 {
  execsql {
    SELECT * FROM parent;
    SELECT * FROM child;
  }
} {1 1}

Added tool/lemon.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
/*
** This file contains all sources (including headers) to the LEMON
** LALR(1) parser generator.  The sources have been combined into a
** single file to make it easy to include LEMON in the source tree
** and Makefile of another program.
**
** The author of this program disclaims copyright.
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <assert.h>

#ifndef __WIN32__
#   if defined(_WIN32) || defined(WIN32)
#	define __WIN32__
#   endif
#endif

#ifdef __WIN32__
extern int access();
#else
#include <unistd.h>
#endif

/* #define PRIVATE static */
#define PRIVATE

#ifdef TEST
#define MAXRHS 5       /* Set low to exercise exception code */
#else
#define MAXRHS 1000
#endif

static char *msort(char*,char**,int(*)(const char*,const char*));

/*
** Compilers are getting increasingly pedantic about type conversions
** as C evolves ever closer to Ada....  To work around the latest problems
** we have to define the following variant of strlen().
*/
#define lemonStrlen(X)   ((int)strlen(X))

static struct action *Action_new(void);
static struct action *Action_sort(struct action *);

/********** From the file "build.h" ************************************/
void FindRulePrecedences();
void FindFirstSets();
void FindStates();
void FindLinks();
void FindFollowSets();
void FindActions();

/********* From the file "configlist.h" *********************************/
void Configlist_init(/* void */);
struct config *Configlist_add(/* struct rule *, int */);
struct config *Configlist_addbasis(/* struct rule *, int */);
void Configlist_closure(/* void */);
void Configlist_sort(/* void */);
void Configlist_sortbasis(/* void */);
struct config *Configlist_return(/* void */);
struct config *Configlist_basis(/* void */);
void Configlist_eat(/* struct config * */);
void Configlist_reset(/* void */);

/********* From the file "error.h" ***************************************/
void ErrorMsg(const char *, int,const char *, ...);

/****** From the file "option.h" ******************************************/
struct s_options {
  enum { OPT_FLAG=1,  OPT_INT,  OPT_DBL,  OPT_STR,
         OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
  char *label;
  char *arg;
  char *message;
};
int    OptInit(/* char**,struct s_options*,FILE* */);
int    OptNArgs(/* void */);
char  *OptArg(/* int */);
void   OptErr(/* int */);
void   OptPrint(/* void */);

/******** From the file "parse.h" *****************************************/
void Parse(/* struct lemon *lemp */);

/********* From the file "plink.h" ***************************************/
struct plink *Plink_new(/* void */);
void Plink_add(/* struct plink **, struct config * */);
void Plink_copy(/* struct plink **, struct plink * */);
void Plink_delete(/* struct plink * */);

/********** From the file "report.h" *************************************/
void Reprint(/* struct lemon * */);
void ReportOutput(/* struct lemon * */);
void ReportTable(/* struct lemon * */);
void ReportHeader(/* struct lemon * */);
void CompressTables(/* struct lemon * */);
void ResortStates(/* struct lemon * */);

/********** From the file "set.h" ****************************************/
void  SetSize(/* int N */);             /* All sets will be of size N */
char *SetNew(/* void */);               /* A new set for element 0..N */
void  SetFree(/* char* */);             /* Deallocate a set */

int SetAdd(/* char*,int */);            /* Add element to a set */
int SetUnion(/* char *A,char *B */);    /* A <- A U B, thru element N */

#define SetFind(X,Y) (X[Y])       /* True if Y is in set X */

/********** From the file "struct.h" *************************************/
/*
** Principal data structures for the LEMON parser generator.
*/

typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;

/* Symbols (terminals and nonterminals) of the grammar are stored
** in the following: */
struct symbol {
  char *name;              /* Name of the symbol */
  int index;               /* Index number for this symbol */
  enum {
    TERMINAL,
    NONTERMINAL,
    MULTITERMINAL
  } type;                  /* Symbols are all either TERMINALS or NTs */
  struct rule *rule;       /* Linked list of rules of this (if an NT) */
  struct symbol *fallback; /* fallback token in case this token doesn't parse */
  int prec;                /* Precedence if defined (-1 otherwise) */
  enum e_assoc {
    LEFT,
    RIGHT,
    NONE,
    UNK
  } assoc;                 /* Associativity if precedence is defined */
  char *firstset;          /* First-set for all rules of this symbol */
  Boolean lambda;          /* True if NT and can generate an empty string */
  int useCnt;              /* Number of times used */
  char *destructor;        /* Code which executes whenever this symbol is
                           ** popped from the stack during error processing */
  int destLineno;          /* Line number for start of destructor */
  char *datatype;          /* The data type of information held by this
                           ** object. Only used if type==NONTERMINAL */
  int dtnum;               /* The data type number.  In the parser, the value
                           ** stack is a union.  The .yy%d element of this
                           ** union is the correct data type for this object */
  /* The following fields are used by MULTITERMINALs only */
  int nsubsym;             /* Number of constituent symbols in the MULTI */
  struct symbol **subsym;  /* Array of constituent symbols */
};

/* Each production rule in the grammar is stored in the following
** structure.  */
struct rule {
  struct symbol *lhs;      /* Left-hand side of the rule */
  char *lhsalias;          /* Alias for the LHS (NULL if none) */
  int lhsStart;            /* True if left-hand side is the start symbol */
  int ruleline;            /* Line number for the rule */
  int nrhs;                /* Number of RHS symbols */
  struct symbol **rhs;     /* The RHS symbols */
  char **rhsalias;         /* An alias for each RHS symbol (NULL if none) */
  int line;                /* Line number at which code begins */
  char *code;              /* The code executed when this rule is reduced */
  struct symbol *precsym;  /* Precedence symbol for this rule */
  int index;               /* An index number for this rule */
  Boolean canReduce;       /* True if this rule is ever reduced */
  struct rule *nextlhs;    /* Next rule with the same LHS */
  struct rule *next;       /* Next rule in the global list */
};

/* A configuration is a production rule of the grammar together with
** a mark (dot) showing how much of that rule has been processed so far.
** Configurations also contain a follow-set which is a list of terminal
** symbols which are allowed to immediately follow the end of the rule.
** Every configuration is recorded as an instance of the following: */
struct config {
  struct rule *rp;         /* The rule upon which the configuration is based */
  int dot;                 /* The parse point */
  char *fws;               /* Follow-set for this configuration only */
  struct plink *fplp;      /* Follow-set forward propagation links */
  struct plink *bplp;      /* Follow-set backwards propagation links */
  struct state *stp;       /* Pointer to state which contains this */
  enum {
    COMPLETE,              /* The status is used during followset and */
    INCOMPLETE             /*    shift computations */
  } status;
  struct config *next;     /* Next configuration in the state */
  struct config *bp;       /* The next basis configuration */
};

/* Every shift or reduce operation is stored as one of the following */
struct action {
  struct symbol *sp;       /* The look-ahead symbol */
  enum e_action {
    SHIFT,
    ACCEPT,
    REDUCE,
    ERROR,
    SSCONFLICT,              /* A shift/shift conflict */
    SRCONFLICT,              /* Was a reduce, but part of a conflict */
    RRCONFLICT,              /* Was a reduce, but part of a conflict */
    SH_RESOLVED,             /* Was a shift.  Precedence resolved conflict */
    RD_RESOLVED,             /* Was reduce.  Precedence resolved conflict */
    NOT_USED                 /* Deleted by compression */
  } type;
  union {
    struct state *stp;     /* The new state, if a shift */
    struct rule *rp;       /* The rule, if a reduce */
  } x;
  struct action *next;     /* Next action for this state */
  struct action *collide;  /* Next action with the same hash */
};

/* Each state of the generated parser's finite state machine
** is encoded as an instance of the following structure. */
struct state {
  struct config *bp;       /* The basis configurations for this state */
  struct config *cfp;      /* All configurations in this set */
  int statenum;            /* Sequential number for this state */
  struct action *ap;       /* Array of actions for this state */
  int nTknAct, nNtAct;     /* Number of actions on terminals and nonterminals */
  int iTknOfst, iNtOfst;   /* yy_action[] offset for terminals and nonterms */
  int iDflt;               /* Default action */
};
#define NO_OFFSET (-2147483647)

/* A followset propagation link indicates that the contents of one
** configuration followset should be propagated to another whenever
** the first changes. */
struct plink {
  struct config *cfp;      /* The configuration to which linked */
  struct plink *next;      /* The next propagate link */
};

/* The state vector for the entire parser generator is recorded as
** follows.  (LEMON uses no global variables and makes little use of
** static variables.  Fields in the following structure can be thought
** of as begin global variables in the program.) */
struct lemon {
  struct state **sorted;   /* Table of states sorted by state number */
  struct rule *rule;       /* List of all rules */
  int nstate;              /* Number of states */
  int nrule;               /* Number of rules */
  int nsymbol;             /* Number of terminal and nonterminal symbols */
  int nterminal;           /* Number of terminal symbols */
  struct symbol **symbols; /* Sorted array of pointers to symbols */
  int errorcnt;            /* Number of errors */
  struct symbol *errsym;   /* The error symbol */
  struct symbol *wildcard; /* Token that matches anything */
  char *name;              /* Name of the generated parser */
  char *arg;               /* Declaration of the 3th argument to parser */
  char *tokentype;         /* Type of terminal symbols in the parser stack */
  char *vartype;           /* The default type of non-terminal symbols */
  char *start;             /* Name of the start symbol for the grammar */
  char *stacksize;         /* Size of the parser stack */
  char *include;           /* Code to put at the start of the C file */
  char *error;             /* Code to execute when an error is seen */
  char *overflow;          /* Code to execute on a stack overflow */
  char *failure;           /* Code to execute on parser failure */
  char *accept;            /* Code to execute when the parser excepts */
  char *extracode;         /* Code appended to the generated file */
  char *tokendest;         /* Code to execute to destroy token data */
  char *vardest;           /* Code for the default non-terminal destructor */
  char *filename;          /* Name of the input file */
  char *outname;           /* Name of the current output file */
  char *tokenprefix;       /* A prefix added to token names in the .h file */
  int nconflict;           /* Number of parsing conflicts */
  int tablesize;           /* Size of the parse tables */
  int basisflag;           /* Print only basis configurations */
  int has_fallback;        /* True if any %fallback is seen in the grammar */
  int nolinenosflag;       /* True if #line statements should not be printed */
  char *argv0;             /* Name of the program */
};

#define MemoryCheck(X) if((X)==0){ \
  extern void memory_error(); \
  memory_error(); \
}

/**************** From the file "table.h" *********************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
**              "table.q"
** by the associative array code building program "aagen".
** Do not edit this file!  Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/

/* Routines for handling a strings */

char *Strsafe();

void Strsafe_init(/* void */);
int Strsafe_insert(/* char * */);
char *Strsafe_find(/* char * */);

/* Routines for handling symbols of the grammar */

struct symbol *Symbol_new();
int Symbolcmpp(/* struct symbol **, struct symbol ** */);
void Symbol_init(/* void */);
int Symbol_insert(/* struct symbol *, char * */);
struct symbol *Symbol_find(/* char * */);
struct symbol *Symbol_Nth(/* int */);
int Symbol_count(/*  */);
struct symbol **Symbol_arrayof(/*  */);

/* Routines to manage the state table */

int Configcmp(/* struct config *, struct config * */);
struct state *State_new();
void State_init(/* void */);
int State_insert(/* struct state *, struct config * */);
struct state *State_find(/* struct config * */);
struct state **State_arrayof(/*  */);

/* Routines used for efficiency in Configlist_add */

void Configtable_init(/* void */);
int Configtable_insert(/* struct config * */);
struct config *Configtable_find(/* struct config * */);
void Configtable_clear(/* int(*)(struct config *) */);
/****************** From the file "action.c" *******************************/
/*
** Routines processing parser actions in the LEMON parser generator.
*/

/* Allocate a new parser action */
static struct action *Action_new(void){
  static struct action *freelist = 0;
  struct action *new;

  if( freelist==0 ){
    int i;
    int amt = 100;
    freelist = (struct action *)calloc(amt, sizeof(struct action));
    if( freelist==0 ){
      fprintf(stderr,"Unable to allocate memory for a new parser action.");
      exit(1);
    }
    for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
    freelist[amt-1].next = 0;
  }
  new = freelist;
  freelist = freelist->next;
  return new;
}

/* Compare two actions for sorting purposes.  Return negative, zero, or
** positive if the first action is less than, equal to, or greater than
** the first
*/
static int actioncmp(
  struct action *ap1,
  struct action *ap2
){
  int rc;
  rc = ap1->sp->index - ap2->sp->index;
  if( rc==0 ){
    rc = (int)ap1->type - (int)ap2->type;
  }
  if( rc==0 && ap1->type==REDUCE ){
    rc = ap1->x.rp->index - ap2->x.rp->index;
  }
  if( rc==0 ){
    rc = ap2 - ap1;
  }
  return rc;
}

/* Sort parser actions */
static struct action *Action_sort(
  struct action *ap
){
  ap = (struct action *)msort((char *)ap,(char **)&ap->next,
                              (int(*)(const char*,const char*))actioncmp);
  return ap;
}

void Action_add(app,type,sp,arg)
struct action **app;
enum e_action type;
struct symbol *sp;
char *arg;
{
  struct action *new;
  new = Action_new();
  new->next = *app;
  *app = new;
  new->type = type;
  new->sp = sp;
  if( type==SHIFT ){
    new->x.stp = (struct state *)arg;
  }else{
    new->x.rp = (struct rule *)arg;
  }
}
/********************** New code to implement the "acttab" module ***********/
/*
** This module implements routines use to construct the yy_action[] table.
*/

/*
** The state of the yy_action table under construction is an instance of
** the following structure
*/
typedef struct acttab acttab;
struct acttab {
  int nAction;                 /* Number of used slots in aAction[] */
  int nActionAlloc;            /* Slots allocated for aAction[] */
  struct {
    int lookahead;             /* Value of the lookahead token */
    int action;                /* Action to take on the given lookahead */
  } *aAction,                  /* The yy_action[] table under construction */
    *aLookahead;               /* A single new transaction set */
  int mnLookahead;             /* Minimum aLookahead[].lookahead */
  int mnAction;                /* Action associated with mnLookahead */
  int mxLookahead;             /* Maximum aLookahead[].lookahead */
  int nLookahead;              /* Used slots in aLookahead[] */
  int nLookaheadAlloc;         /* Slots allocated in aLookahead[] */
};

/* Return the number of entries in the yy_action table */
#define acttab_size(X) ((X)->nAction)

/* The value for the N-th entry in yy_action */
#define acttab_yyaction(X,N)  ((X)->aAction[N].action)

/* The value for the N-th entry in yy_lookahead */
#define acttab_yylookahead(X,N)  ((X)->aAction[N].lookahead)

/* Free all memory associated with the given acttab */
void acttab_free(acttab *p){
  free( p->aAction );
  free( p->aLookahead );
  free( p );
}

/* Allocate a new acttab structure */
acttab *acttab_alloc(void){
  acttab *p = calloc( 1, sizeof(*p) );
  if( p==0 ){
    fprintf(stderr,"Unable to allocate memory for a new acttab.");
    exit(1);
  }
  memset(p, 0, sizeof(*p));
  return p;
}

/* Add a new action to the current transaction set
*/
void acttab_action(acttab *p, int lookahead, int action){
  if( p->nLookahead>=p->nLookaheadAlloc ){
    p->nLookaheadAlloc += 25;
    p->aLookahead = realloc( p->aLookahead,
                             sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
    if( p->aLookahead==0 ){
      fprintf(stderr,"malloc failed\n");
      exit(1);
    }
  }
  if( p->nLookahead==0 ){
    p->mxLookahead = lookahead;
    p->mnLookahead = lookahead;
    p->mnAction = action;
  }else{
    if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
    if( p->mnLookahead>lookahead ){
      p->mnLookahead = lookahead;
      p->mnAction = action;
    }
  }
  p->aLookahead[p->nLookahead].lookahead = lookahead;
  p->aLookahead[p->nLookahead].action = action;
  p->nLookahead++;
}

/*
** Add the transaction set built up with prior calls to acttab_action()
** into the current action table.  Then reset the transaction set back
** to an empty set in preparation for a new round of acttab_action() calls.
**
** Return the offset into the action table of the new transaction.
*/
int acttab_insert(acttab *p){
  int i, j, k, n;
  assert( p->nLookahead>0 );

  /* Make sure we have enough space to hold the expanded action table
  ** in the worst case.  The worst case occurs if the transaction set
  ** must be appended to the current action table
  */
  n = p->mxLookahead + 1;
  if( p->nAction + n >= p->nActionAlloc ){
    int oldAlloc = p->nActionAlloc;
    p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
    p->aAction = realloc( p->aAction,
                          sizeof(p->aAction[0])*p->nActionAlloc);
    if( p->aAction==0 ){
      fprintf(stderr,"malloc failed\n");
      exit(1);
    }
    for(i=oldAlloc; i<p->nActionAlloc; i++){
      p->aAction[i].lookahead = -1;
      p->aAction[i].action = -1;
    }
  }

  /* Scan the existing action table looking for an offset where we can
  ** insert the current transaction set.  Fall out of the loop when that
  ** offset is found.  In the worst case, we fall out of the loop when
  ** i reaches p->nAction, which means we append the new transaction set.
  **
  ** i is the index in p->aAction[] where p->mnLookahead is inserted.
  */
  for(i=p->nAction-1; i>=0; i--){
    /* First look for an existing action table entry that can be reused */
    if( p->aAction[i].lookahead==p->mnLookahead ){
      if( p->aAction[i].action!=p->mnAction ) continue;
      for(j=0; j<p->nLookahead; j++){
        k = p->aLookahead[j].lookahead - p->mnLookahead + i;
        if( k<0 || k>=p->nAction ) break;
        if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
        if( p->aLookahead[j].action!=p->aAction[k].action ) break;
      }
      if( j<p->nLookahead ) continue;
      n = 0;
      for(j=0; j<p->nAction; j++){
        if( p->aAction[j].lookahead<0 ) continue;
        if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
      }
      if( n==p->nLookahead ){
        break;  /* Same as a prior transaction set */
      }
    }
  }
  if( i<0 ){
    /* If no reusable entry is found, look for an empty slot */
    for(i=0; i<p->nAction; i++){
      if( p->aAction[i].lookahead<0 ){
        for(j=0; j<p->nLookahead; j++){
          k = p->aLookahead[j].lookahead - p->mnLookahead + i;
          if( k<0 ) break;
          if( p->aAction[k].lookahead>=0 ) break;
        }
        if( j<p->nLookahead ) continue;
        for(j=0; j<p->nAction; j++){
          if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
        }
        if( j==p->nAction ){
          break;  /* Fits in empty slots */
        }
      }
    }
  }
  /* Insert transaction set at index i. */
  for(j=0; j<p->nLookahead; j++){
    k = p->aLookahead[j].lookahead - p->mnLookahead + i;
    p->aAction[k] = p->aLookahead[j];
    if( k>=p->nAction ) p->nAction = k+1;
  }
  p->nLookahead = 0;

  /* Return the offset that is added to the lookahead in order to get the
  ** index into yy_action of the action */
  return i - p->mnLookahead;
}

/********************** From the file "build.c" *****************************/
/*
** Routines to construction the finite state machine for the LEMON
** parser generator.
*/

/* Find a precedence symbol of every rule in the grammar.
** 
** Those rules which have a precedence symbol coded in the input
** grammar using the "[symbol]" construct will already have the
** rp->precsym field filled.  Other rules take as their precedence
** symbol the first RHS symbol with a defined precedence.  If there
** are not RHS symbols with a defined precedence, the precedence
** symbol field is left blank.
*/
void FindRulePrecedences(xp)
struct lemon *xp;
{
  struct rule *rp;
  for(rp=xp->rule; rp; rp=rp->next){
    if( rp->precsym==0 ){
      int i, j;
      for(i=0; i<rp->nrhs && rp->precsym==0; i++){
        struct symbol *sp = rp->rhs[i];
        if( sp->type==MULTITERMINAL ){
          for(j=0; j<sp->nsubsym; j++){
            if( sp->subsym[j]->prec>=0 ){
              rp->precsym = sp->subsym[j];
              break;
            }
          }
        }else if( sp->prec>=0 ){
          rp->precsym = rp->rhs[i];
	}
      }
    }
  }
  return;
}

/* Find all nonterminals which will generate the empty string.
** Then go back and compute the first sets of every nonterminal.
** The first set is the set of all terminal symbols which can begin
** a string generated by that nonterminal.
*/
void FindFirstSets(lemp)
struct lemon *lemp;
{
  int i, j;
  struct rule *rp;
  int progress;

  for(i=0; i<lemp->nsymbol; i++){
    lemp->symbols[i]->lambda = LEMON_FALSE;
  }
  for(i=lemp->nterminal; i<lemp->nsymbol; i++){
    lemp->symbols[i]->firstset = SetNew();
  }

  /* First compute all lambdas */
  do{
    progress = 0;
    for(rp=lemp->rule; rp; rp=rp->next){
      if( rp->lhs->lambda ) continue;
      for(i=0; i<rp->nrhs; i++){
         struct symbol *sp = rp->rhs[i];
         if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
      }
      if( i==rp->nrhs ){
        rp->lhs->lambda = LEMON_TRUE;
        progress = 1;
      }
    }
  }while( progress );

  /* Now compute all first sets */
  do{
    struct symbol *s1, *s2;
    progress = 0;
    for(rp=lemp->rule; rp; rp=rp->next){
      s1 = rp->lhs;
      for(i=0; i<rp->nrhs; i++){
        s2 = rp->rhs[i];
        if( s2->type==TERMINAL ){
          progress += SetAdd(s1->firstset,s2->index);
          break;
        }else if( s2->type==MULTITERMINAL ){
          for(j=0; j<s2->nsubsym; j++){
            progress += SetAdd(s1->firstset,s2->subsym[j]->index);
          }
          break;
	}else if( s1==s2 ){
          if( s1->lambda==LEMON_FALSE ) break;
	}else{
          progress += SetUnion(s1->firstset,s2->firstset);
          if( s2->lambda==LEMON_FALSE ) break;
	}
      }
    }
  }while( progress );
  return;
}

/* Compute all LR(0) states for the grammar.  Links
** are added to between some states so that the LR(1) follow sets
** can be computed later.
*/
PRIVATE struct state *getstate(/* struct lemon * */);  /* forward reference */
void FindStates(lemp)
struct lemon *lemp;
{
  struct symbol *sp;
  struct rule *rp;

  Configlist_init();

  /* Find the start symbol */
  if( lemp->start ){
    sp = Symbol_find(lemp->start);
    if( sp==0 ){
      ErrorMsg(lemp->filename,0,
"The specified start symbol \"%s\" is not \
in a nonterminal of the grammar.  \"%s\" will be used as the start \
symbol instead.",lemp->start,lemp->rule->lhs->name);
      lemp->errorcnt++;
      sp = lemp->rule->lhs;
    }
  }else{
    sp = lemp->rule->lhs;
  }

  /* Make sure the start symbol doesn't occur on the right-hand side of
  ** any rule.  Report an error if it does.  (YACC would generate a new
  ** start symbol in this case.) */
  for(rp=lemp->rule; rp; rp=rp->next){
    int i;
    for(i=0; i<rp->nrhs; i++){
      if( rp->rhs[i]==sp ){   /* FIX ME:  Deal with multiterminals */
        ErrorMsg(lemp->filename,0,
"The start symbol \"%s\" occurs on the \
right-hand side of a rule. This will result in a parser which \
does not work properly.",sp->name);
        lemp->errorcnt++;
      }
    }
  }

  /* The basis configuration set for the first state
  ** is all rules which have the start symbol as their
  ** left-hand side */
  for(rp=sp->rule; rp; rp=rp->nextlhs){
    struct config *newcfp;
    rp->lhsStart = 1;
    newcfp = Configlist_addbasis(rp,0);
    SetAdd(newcfp->fws,0);
  }

  /* Compute the first state.  All other states will be
  ** computed automatically during the computation of the first one.
  ** The returned pointer to the first state is not used. */
  (void)getstate(lemp);
  return;
}

/* Return a pointer to a state which is described by the configuration
** list which has been built from calls to Configlist_add.
*/
PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
PRIVATE struct state *getstate(lemp)
struct lemon *lemp;
{
  struct config *cfp, *bp;
  struct state *stp;

  /* Extract the sorted basis of the new state.  The basis was constructed
  ** by prior calls to "Configlist_addbasis()". */
  Configlist_sortbasis();
  bp = Configlist_basis();

  /* Get a state with the same basis */
  stp = State_find(bp);
  if( stp ){
    /* A state with the same basis already exists!  Copy all the follow-set
    ** propagation links from the state under construction into the
    ** preexisting state, then return a pointer to the preexisting state */
    struct config *x, *y;
    for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
      Plink_copy(&y->bplp,x->bplp);
      Plink_delete(x->fplp);
      x->fplp = x->bplp = 0;
    }
    cfp = Configlist_return();
    Configlist_eat(cfp);
  }else{
    /* This really is a new state.  Construct all the details */
    Configlist_closure(lemp);    /* Compute the configuration closure */
    Configlist_sort();           /* Sort the configuration closure */
    cfp = Configlist_return();   /* Get a pointer to the config list */
    stp = State_new();           /* A new state structure */
    MemoryCheck(stp);
    stp->bp = bp;                /* Remember the configuration basis */
    stp->cfp = cfp;              /* Remember the configuration closure */
    stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
    stp->ap = 0;                 /* No actions, yet. */
    State_insert(stp,stp->bp);   /* Add to the state table */
    buildshifts(lemp,stp);       /* Recursively compute successor states */
  }
  return stp;
}

/*
** Return true if two symbols are the same.
*/
int same_symbol(a,b)
struct symbol *a;
struct symbol *b;
{
  int i;
  if( a==b ) return 1;
  if( a->type!=MULTITERMINAL ) return 0;
  if( b->type!=MULTITERMINAL ) return 0;
  if( a->nsubsym!=b->nsubsym ) return 0;
  for(i=0; i<a->nsubsym; i++){
    if( a->subsym[i]!=b->subsym[i] ) return 0;
  }
  return 1;
}

/* Construct all successor states to the given state.  A "successor"
** state is any state which can be reached by a shift action.
*/
PRIVATE void buildshifts(lemp,stp)
struct lemon *lemp;
struct state *stp;     /* The state from which successors are computed */
{
  struct config *cfp;  /* For looping thru the config closure of "stp" */
  struct config *bcfp; /* For the inner loop on config closure of "stp" */
  struct config *new;  /* */
  struct symbol *sp;   /* Symbol following the dot in configuration "cfp" */
  struct symbol *bsp;  /* Symbol following the dot in configuration "bcfp" */
  struct state *newstp; /* A pointer to a successor state */

  /* Each configuration becomes complete after it contibutes to a successor
  ** state.  Initially, all configurations are incomplete */
  for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;

  /* Loop through all configurations of the state "stp" */
  for(cfp=stp->cfp; cfp; cfp=cfp->next){
    if( cfp->status==COMPLETE ) continue;    /* Already used by inner loop */
    if( cfp->dot>=cfp->rp->nrhs ) continue;  /* Can't shift this config */
    Configlist_reset();                      /* Reset the new config set */
    sp = cfp->rp->rhs[cfp->dot];             /* Symbol after the dot */

    /* For every configuration in the state "stp" which has the symbol "sp"
    ** following its dot, add the same configuration to the basis set under
    ** construction but with the dot shifted one symbol to the right. */
    for(bcfp=cfp; bcfp; bcfp=bcfp->next){
      if( bcfp->status==COMPLETE ) continue;    /* Already used */
      if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
      bsp = bcfp->rp->rhs[bcfp->dot];           /* Get symbol after dot */
      if( !same_symbol(bsp,sp) ) continue;      /* Must be same as for "cfp" */
      bcfp->status = COMPLETE;                  /* Mark this config as used */
      new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
      Plink_add(&new->bplp,bcfp);
    }

    /* Get a pointer to the state described by the basis configuration set
    ** constructed in the preceding loop */
    newstp = getstate(lemp);

    /* The state "newstp" is reached from the state "stp" by a shift action
    ** on the symbol "sp" */
    if( sp->type==MULTITERMINAL ){
      int i;
      for(i=0; i<sp->nsubsym; i++){
        Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
      }
    }else{
      Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
    }
  }
}

/*
** Construct the propagation links
*/
void FindLinks(lemp)
struct lemon *lemp;
{
  int i;
  struct config *cfp, *other;
  struct state *stp;
  struct plink *plp;

  /* Housekeeping detail:
  ** Add to every propagate link a pointer back to the state to
  ** which the link is attached. */
  for(i=0; i<lemp->nstate; i++){
    stp = lemp->sorted[i];
    for(cfp=stp->cfp; cfp; cfp=cfp->next){
      cfp->stp = stp;
    }
  }

  /* Convert all backlinks into forward links.  Only the forward
  ** links are used in the follow-set computation. */
  for(i=0; i<lemp->nstate; i++){
    stp = lemp->sorted[i];
    for(cfp=stp->cfp; cfp; cfp=cfp->next){
      for(plp=cfp->bplp; plp; plp=plp->next){
        other = plp->cfp;
        Plink_add(&other->fplp,cfp);
      }
    }
  }
}

/* Compute all followsets.
**
** A followset is the set of all symbols which can come immediately
** after a configuration.
*/
void FindFollowSets(lemp)
struct lemon *lemp;
{
  int i;
  struct config *cfp;
  struct plink *plp;
  int progress;
  int change;

  for(i=0; i<lemp->nstate; i++){
    for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
      cfp->status = INCOMPLETE;
    }
  }
  
  do{
    progress = 0;
    for(i=0; i<lemp->nstate; i++){
      for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
        if( cfp->status==COMPLETE ) continue;
        for(plp=cfp->fplp; plp; plp=plp->next){
          change = SetUnion(plp->cfp->fws,cfp->fws);
          if( change ){
            plp->cfp->status = INCOMPLETE;
            progress = 1;
	  }
	}
        cfp->status = COMPLETE;
      }
    }
  }while( progress );
}

static int resolve_conflict();

/* Compute the reduce actions, and resolve conflicts.
*/
void FindActions(lemp)
struct lemon *lemp;
{
  int i,j;
  struct config *cfp;
  struct state *stp;
  struct symbol *sp;
  struct rule *rp;

  /* Add all of the reduce actions 
  ** A reduce action is added for each element of the followset of
  ** a configuration which has its dot at the extreme right.
  */
  for(i=0; i<lemp->nstate; i++){   /* Loop over all states */
    stp = lemp->sorted[i];
    for(cfp=stp->cfp; cfp; cfp=cfp->next){  /* Loop over all configurations */
      if( cfp->rp->nrhs==cfp->dot ){        /* Is dot at extreme right? */
        for(j=0; j<lemp->nterminal; j++){
          if( SetFind(cfp->fws,j) ){
            /* Add a reduce action to the state "stp" which will reduce by the
            ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
            Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
          }
	}
      }
    }
  }

  /* Add the accepting token */
  if( lemp->start ){
    sp = Symbol_find(lemp->start);
    if( sp==0 ) sp = lemp->rule->lhs;
  }else{
    sp = lemp->rule->lhs;
  }
  /* Add to the first state (which is always the starting state of the
  ** finite state machine) an action to ACCEPT if the lookahead is the
  ** start nonterminal.  */
  Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);

  /* Resolve conflicts */
  for(i=0; i<lemp->nstate; i++){
    struct action *ap, *nap;
    struct state *stp;
    stp = lemp->sorted[i];
    /* assert( stp->ap ); */
    stp->ap = Action_sort(stp->ap);
    for(ap=stp->ap; ap && ap->next; ap=ap->next){
      for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
         /* The two actions "ap" and "nap" have the same lookahead.
         ** Figure out which one should be used */
         lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
      }
    }
  }

  /* Report an error for each rule that can never be reduced. */
  for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
  for(i=0; i<lemp->nstate; i++){
    struct action *ap;
    for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
      if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
    }
  }
  for(rp=lemp->rule; rp; rp=rp->next){
    if( rp->canReduce ) continue;
    ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
    lemp->errorcnt++;
  }
}

/* Resolve a conflict between the two given actions.  If the
** conflict can't be resolved, return non-zero.
**
** NO LONGER TRUE:
**   To resolve a conflict, first look to see if either action
**   is on an error rule.  In that case, take the action which
**   is not associated with the error rule.  If neither or both
**   actions are associated with an error rule, then try to
**   use precedence to resolve the conflict.
**
** If either action is a SHIFT, then it must be apx.  This
** function won't work if apx->type==REDUCE and apy->type==SHIFT.
*/
static int resolve_conflict(apx,apy,errsym)
struct action *apx;
struct action *apy;
struct symbol *errsym;   /* The error symbol (if defined.  NULL otherwise) */
{
  struct symbol *spx, *spy;
  int errcnt = 0;
  assert( apx->sp==apy->sp );  /* Otherwise there would be no conflict */
  if( apx->type==SHIFT && apy->type==SHIFT ){
    apy->type = SSCONFLICT;
    errcnt++;
  }
  if( apx->type==SHIFT && apy->type==REDUCE ){
    spx = apx->sp;
    spy = apy->x.rp->precsym;
    if( spy==0 || spx->prec<0 || spy->prec<0 ){
      /* Not enough precedence information. */
      apy->type = SRCONFLICT;
      errcnt++;
    }else if( spx->prec>spy->prec ){    /* Lower precedence wins */
      apy->type = RD_RESOLVED;
    }else if( spx->prec<spy->prec ){
      apx->type = SH_RESOLVED;
    }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
      apy->type = RD_RESOLVED;                             /* associativity */
    }else if( spx->prec==spy->prec && spx->assoc==LEFT ){  /* to break tie */
      apx->type = SH_RESOLVED;
    }else{
      assert( spx->prec==spy->prec && spx->assoc==NONE );
      apy->type = SRCONFLICT;
      errcnt++;
    }
  }else if( apx->type==REDUCE && apy->type==REDUCE ){
    spx = apx->x.rp->precsym;
    spy = apy->x.rp->precsym;
    if( spx==0 || spy==0 || spx->prec<0 ||
    spy->prec<0 || spx->prec==spy->prec ){
      apy->type = RRCONFLICT;
      errcnt++;
    }else if( spx->prec>spy->prec ){
      apy->type = RD_RESOLVED;
    }else if( spx->prec<spy->prec ){
      apx->type = RD_RESOLVED;
    }
  }else{
    assert( 
      apx->type==SH_RESOLVED ||
      apx->type==RD_RESOLVED ||
      apx->type==SSCONFLICT ||
      apx->type==SRCONFLICT ||
      apx->type==RRCONFLICT ||
      apy->type==SH_RESOLVED ||
      apy->type==RD_RESOLVED ||
      apy->type==SSCONFLICT ||
      apy->type==SRCONFLICT ||
      apy->type==RRCONFLICT
    );
    /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
    ** REDUCEs on the list.  If we reach this point it must be because
    ** the parser conflict had already been resolved. */
  }
  return errcnt;
}
/********************* From the file "configlist.c" *************************/
/*
** Routines to processing a configuration list and building a state
** in the LEMON parser generator.
*/

static struct config *freelist = 0;      /* List of free configurations */
static struct config *current = 0;       /* Top of list of configurations */
static struct config **currentend = 0;   /* Last on list of configs */
static struct config *basis = 0;         /* Top of list of basis configs */
static struct config **basisend = 0;     /* End of list of basis configs */

/* Return a pointer to a new configuration */
PRIVATE struct config *newconfig(){
  struct config *new;
  if( freelist==0 ){
    int i;
    int amt = 3;
    freelist = (struct config *)calloc( amt, sizeof(struct config) );
    if( freelist==0 ){
      fprintf(stderr,"Unable to allocate memory for a new configuration.");
      exit(1);
    }
    for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
    freelist[amt-1].next = 0;
  }
  new = freelist;
  freelist = freelist->next;
  return new;
}

/* The configuration "old" is no longer used */
PRIVATE void deleteconfig(old)
struct config *old;
{
  old->next = freelist;
  freelist = old;
}

/* Initialized the configuration list builder */
void Configlist_init(){
  current = 0;
  currentend = &current;
  basis = 0;
  basisend = &basis;
  Configtable_init();
  return;
}

/* Initialized the configuration list builder */
void Configlist_reset(){
  current = 0;
  currentend = &current;
  basis = 0;
  basisend = &basis;
  Configtable_clear(0);
  return;
}

/* Add another configuration to the configuration list */
struct config *Configlist_add(rp,dot)
struct rule *rp;    /* The rule */
int dot;            /* Index into the RHS of the rule where the dot goes */
{
  struct config *cfp, model;

  assert( currentend!=0 );
  model.rp = rp;
  model.dot = dot;
  cfp = Configtable_find(&model);
  if( cfp==0 ){
    cfp = newconfig();
    cfp->rp = rp;
    cfp->dot = dot;
    cfp->fws = SetNew();
    cfp->stp = 0;
    cfp->fplp = cfp->bplp = 0;
    cfp->next = 0;
    cfp->bp = 0;
    *currentend = cfp;
    currentend = &cfp->next;
    Configtable_insert(cfp);
  }
  return cfp;
}

/* Add a basis configuration to the configuration list */
struct config *Configlist_addbasis(rp,dot)
struct rule *rp;
int dot;
{
  struct config *cfp, model;

  assert( basisend!=0 );
  assert( currentend!=0 );
  model.rp = rp;
  model.dot = dot;
  cfp = Configtable_find(&model);
  if( cfp==0 ){
    cfp = newconfig();
    cfp->rp = rp;
    cfp->dot = dot;
    cfp->fws = SetNew();
    cfp->stp = 0;
    cfp->fplp = cfp->bplp = 0;
    cfp->next = 0;
    cfp->bp = 0;
    *currentend = cfp;
    currentend = &cfp->next;
    *basisend = cfp;
    basisend = &cfp->bp;
    Configtable_insert(cfp);
  }
  return cfp;
}

/* Compute the closure of the configuration list */
void Configlist_closure(lemp)
struct lemon *lemp;
{
  struct config *cfp, *newcfp;
  struct rule *rp, *newrp;
  struct symbol *sp, *xsp;
  int i, dot;

  assert( currentend!=0 );
  for(cfp=current; cfp; cfp=cfp->next){
    rp = cfp->rp;
    dot = cfp->dot;
    if( dot>=rp->nrhs ) continue;
    sp = rp->rhs[dot];
    if( sp->type==NONTERMINAL ){
      if( sp->rule==0 && sp!=lemp->errsym ){
        ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
          sp->name);
        lemp->errorcnt++;
      }
      for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
        newcfp = Configlist_add(newrp,0);
        for(i=dot+1; i<rp->nrhs; i++){
          xsp = rp->rhs[i];
          if( xsp->type==TERMINAL ){
            SetAdd(newcfp->fws,xsp->index);
            break;
          }else if( xsp->type==MULTITERMINAL ){
            int k;
            for(k=0; k<xsp->nsubsym; k++){
              SetAdd(newcfp->fws, xsp->subsym[k]->index);
            }
            break;
	  }else{
            SetUnion(newcfp->fws,xsp->firstset);
            if( xsp->lambda==LEMON_FALSE ) break;
	  }
	}
        if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
      }
    }
  }
  return;
}

/* Sort the configuration list */
void Configlist_sort(){
  current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
  currentend = 0;
  return;
}

/* Sort the basis configuration list */
void Configlist_sortbasis(){
  basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
  basisend = 0;
  return;
}

/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_return(){
  struct config *old;
  old = current;
  current = 0;
  currentend = 0;
  return old;
}

/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_basis(){
  struct config *old;
  old = basis;
  basis = 0;
  basisend = 0;
  return old;
}

/* Free all elements of the given configuration list */
void Configlist_eat(cfp)
struct config *cfp;
{
  struct config *nextcfp;
  for(; cfp; cfp=nextcfp){
    nextcfp = cfp->next;
    assert( cfp->fplp==0 );
    assert( cfp->bplp==0 );
    if( cfp->fws ) SetFree(cfp->fws);
    deleteconfig(cfp);
  }
  return;
}
/***************** From the file "error.c" *********************************/
/*
** Code for printing error message.
*/

/* Find a good place to break "msg" so that its length is at least "min"
** but no more than "max".  Make the point as close to max as possible.
*/
static int findbreak(msg,min,max)
char *msg;
int min;
int max;
{
  int i,spot;
  char c;
  for(i=spot=min; i<=max; i++){
    c = msg[i];
    if( c=='\t' ) msg[i] = ' ';
    if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
    if( c==0 ){ spot = i; break; }
    if( c=='-' && i<max-1 ) spot = i+1;
    if( c==' ' ) spot = i;
  }
  return spot;
}

/*
** The error message is split across multiple lines if necessary.  The
** splits occur at a space, if there is a space available near the end
** of the line.
*/
#define ERRMSGSIZE  10000 /* Hope this is big enough.  No way to error check */
#define LINEWIDTH      79 /* Max width of any output line */
#define PREFIXLIMIT    30 /* Max width of the prefix on each line */
void ErrorMsg(const char *filename, int lineno, const char *format, ...){
  char errmsg[ERRMSGSIZE];
  char prefix[PREFIXLIMIT+10];
  int errmsgsize;
  int prefixsize;
  int availablewidth;
  va_list ap;
  int end, restart, base;

  va_start(ap, format);
  /* Prepare a prefix to be prepended to every output line */
  if( lineno>0 ){
    sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
  }else{
    sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
  }
  prefixsize = lemonStrlen(prefix);
  availablewidth = LINEWIDTH - prefixsize;

  /* Generate the error message */
  vsprintf(errmsg,format,ap);
  va_end(ap);
  errmsgsize = lemonStrlen(errmsg);
  /* Remove trailing '\n's from the error message. */
  while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
     errmsg[--errmsgsize] = 0;
  }

  /* Print the error message */
  base = 0;
  while( errmsg[base]!=0 ){
    end = restart = findbreak(&errmsg[base],0,availablewidth);
    restart += base;
    while( errmsg[restart]==' ' ) restart++;
    fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
    base = restart;
  }
}
/**************** From the file "main.c" ************************************/
/*
** Main program file for the LEMON parser generator.
*/

/* Report an out-of-memory condition and abort.  This function
** is used mostly by the "MemoryCheck" macro in struct.h
*/
void memory_error(){
  fprintf(stderr,"Out of memory.  Aborting...\n");
  exit(1);
}

static int nDefine = 0;      /* Number of -D options on the command line */
static char **azDefine = 0;  /* Name of the -D macros */

/* This routine is called with the argument to each -D command-line option.
** Add the macro defined to the azDefine array.
*/
static void handle_D_option(char *z){
  char **paz;
  nDefine++;
  azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
  if( azDefine==0 ){
    fprintf(stderr,"out of memory\n");
    exit(1);
  }
  paz = &azDefine[nDefine-1];
  *paz = malloc( lemonStrlen(z)+1 );
  if( *paz==0 ){
    fprintf(stderr,"out of memory\n");
    exit(1);
  }
  strcpy(*paz, z);
  for(z=*paz; *z && *z!='='; z++){}
  *z = 0;
}


/* The main program.  Parse the command line and do it... */
int main(argc,argv)
int argc;
char **argv;
{
  static int version = 0;
  static int rpflag = 0;
  static int basisflag = 0;
  static int compress = 0;
  static int quiet = 0;
  static int statistics = 0;
  static int mhflag = 0;
  static int nolinenosflag = 0;
  static struct s_options options[] = {
    {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
    {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
    {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
    {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
    {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
    {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
    {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
    {OPT_FLAG, "s", (char*)&statistics,
                                   "Print parser stats to standard output."},
    {OPT_FLAG, "x", (char*)&version, "Print the version number."},
    {OPT_FLAG,0,0,0}
  };
  int i;
  struct lemon lem;

  OptInit(argv,options,stderr);
  if( version ){
     printf("Lemon version 1.0\n");
     exit(0); 
  }
  if( OptNArgs()!=1 ){
    fprintf(stderr,"Exactly one filename argument is required.\n");
    exit(1);
  }
  memset(&lem, 0, sizeof(lem));
  lem.errorcnt = 0;

  /* Initialize the machine */
  Strsafe_init();
  Symbol_init();
  State_init();
  lem.argv0 = argv[0];
  lem.filename = OptArg(0);
  lem.basisflag = basisflag;
  lem.nolinenosflag = nolinenosflag;
  Symbol_new("$");
  lem.errsym = Symbol_new("error");
  lem.errsym->useCnt = 0;

  /* Parse the input file */
  Parse(&lem);
  if( lem.errorcnt ) exit(lem.errorcnt);
  if( lem.nrule==0 ){
    fprintf(stderr,"Empty grammar.\n");
    exit(1);
  }

  /* Count and index the symbols of the grammar */
  lem.nsymbol = Symbol_count();
  Symbol_new("{default}");
  lem.symbols = Symbol_arrayof();
  for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
  qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
        (int(*)())Symbolcmpp);
  for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
  for(i=1; isupper(lem.symbols[i]->name[0]); i++);
  lem.nterminal = i;

  /* Generate a reprint of the grammar, if requested on the command line */
  if( rpflag ){
    Reprint(&lem);
  }else{
    /* Initialize the size for all follow and first sets */
    SetSize(lem.nterminal+1);

    /* Find the precedence for every production rule (that has one) */
    FindRulePrecedences(&lem);

    /* Compute the lambda-nonterminals and the first-sets for every
    ** nonterminal */
    FindFirstSets(&lem);

    /* Compute all LR(0) states.  Also record follow-set propagation
    ** links so that the follow-set can be computed later */
    lem.nstate = 0;
    FindStates(&lem);
    lem.sorted = State_arrayof();

    /* Tie up loose ends on the propagation links */
    FindLinks(&lem);

    /* Compute the follow set of every reducible configuration */
    FindFollowSets(&lem);

    /* Compute the action tables */
    FindActions(&lem);

    /* Compress the action tables */
    if( compress==0 ) CompressTables(&lem);

    /* Reorder and renumber the states so that states with fewer choices
    ** occur at the end. */
    ResortStates(&lem);

    /* Generate a report of the parser generated.  (the "y.output" file) */
    if( !quiet ) ReportOutput(&lem);

    /* Generate the source code for the parser */
    ReportTable(&lem, mhflag);

    /* Produce a header file for use by the scanner.  (This step is
    ** omitted if the "-m" option is used because makeheaders will
    ** generate the file for us.) */
    if( !mhflag ) ReportHeader(&lem);
  }
  if( statistics ){
    printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
      lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
    printf("                   %d states, %d parser table entries, %d conflicts\n",
      lem.nstate, lem.tablesize, lem.nconflict);
  }
  if( lem.nconflict ){
    fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
  }
  exit(lem.errorcnt + lem.nconflict);
  return (lem.errorcnt + lem.nconflict);
}
/******************** From the file "msort.c" *******************************/
/*
** A generic merge-sort program.
**
** USAGE:
** Let "ptr" be a pointer to some structure which is at the head of
** a null-terminated list.  Then to sort the list call:
**
**     ptr = msort(ptr,&(ptr->next),cmpfnc);
**
** In the above, "cmpfnc" is a pointer to a function which compares
** two instances of the structure and returns an integer, as in
** strcmp.  The second argument is a pointer to the pointer to the
** second element of the linked list.  This address is used to compute
** the offset to the "next" field within the structure.  The offset to
** the "next" field must be constant for all structures in the list.
**
** The function returns a new pointer which is the head of the list
** after sorting.
**
** ALGORITHM:
** Merge-sort.
*/

/*
** Return a pointer to the next structure in the linked list.
*/
#define NEXT(A) (*(char**)(((unsigned long)A)+offset))

/*
** Inputs:
**   a:       A sorted, null-terminated linked list.  (May be null).
**   b:       A sorted, null-terminated linked list.  (May be null).
**   cmp:     A pointer to the comparison function.
**   offset:  Offset in the structure to the "next" field.
**
** Return Value:
**   A pointer to the head of a sorted list containing the elements
**   of both a and b.
**
** Side effects:
**   The "next" pointers for elements in the lists a and b are
**   changed.
*/
static char *merge(
  char *a,
  char *b,
  int (*cmp)(const char*,const char*),
  int offset
){
  char *ptr, *head;

  if( a==0 ){
    head = b;
  }else if( b==0 ){
    head = a;
  }else{
    if( (*cmp)(a,b)<=0 ){
      ptr = a;
      a = NEXT(a);
    }else{
      ptr = b;
      b = NEXT(b);
    }
    head = ptr;
    while( a && b ){
      if( (*cmp)(a,b)<=0 ){
        NEXT(ptr) = a;
        ptr = a;
        a = NEXT(a);
      }else{
        NEXT(ptr) = b;
        ptr = b;
        b = NEXT(b);
      }
    }
    if( a ) NEXT(ptr) = a;
    else    NEXT(ptr) = b;
  }
  return head;
}

/*
** Inputs:
**   list:      Pointer to a singly-linked list of structures.
**   next:      Pointer to pointer to the second element of the list.
**   cmp:       A comparison function.
**
** Return Value:
**   A pointer to the head of a sorted list containing the elements
**   orginally in list.
**
** Side effects:
**   The "next" pointers for elements in list are changed.
*/
#define LISTSIZE 30
static char *msort(
  char *list,
  char **next,
  int (*cmp)(const char*,const char*)
){
  unsigned long offset;
  char *ep;
  char *set[LISTSIZE];
  int i;
  offset = (unsigned long)next - (unsigned long)list;
  for(i=0; i<LISTSIZE; i++) set[i] = 0;
  while( list ){
    ep = list;
    list = NEXT(list);
    NEXT(ep) = 0;
    for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
      ep = merge(ep,set[i],cmp,offset);
      set[i] = 0;
    }
    set[i] = ep;
  }
  ep = 0;
  for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
  return ep;
}
/************************ From the file "option.c" **************************/
static char **argv;
static struct s_options *op;
static FILE *errstream;

#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)

/*
** Print the command line with a carrot pointing to the k-th character
** of the n-th field.
*/
static void errline(n,k,err)
int n;
int k;
FILE *err;
{
  int spcnt, i;
  if( argv[0] ) fprintf(err,"%s",argv[0]);
  spcnt = lemonStrlen(argv[0]) + 1;
  for(i=1; i<n && argv[i]; i++){
    fprintf(err," %s",argv[i]);
    spcnt += lemonStrlen(argv[i])+1;
  }
  spcnt += k;
  for(; argv[i]; i++) fprintf(err," %s",argv[i]);
  if( spcnt<20 ){
    fprintf(err,"\n%*s^-- here\n",spcnt,"");
  }else{
    fprintf(err,"\n%*shere --^\n",spcnt-7,"");
  }
}

/*
** Return the index of the N-th non-switch argument.  Return -1
** if N is out of range.
*/
static int argindex(n)
int n;
{
  int i;
  int dashdash = 0;
  if( argv!=0 && *argv!=0 ){
    for(i=1; argv[i]; i++){
      if( dashdash || !ISOPT(argv[i]) ){
        if( n==0 ) return i;
        n--;
      }
      if( strcmp(argv[i],"--")==0 ) dashdash = 1;
    }
  }
  return -1;
}

static char emsg[] = "Command line syntax error: ";

/*
** Process a flag command line argument.
*/
static int handleflags(i,err)
int i;
FILE *err;
{
  int v;
  int errcnt = 0;
  int j;
  for(j=0; op[j].label; j++){
    if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
  }
  v = argv[i][0]=='-' ? 1 : 0;
  if( op[j].label==0 ){
    if( err ){
      fprintf(err,"%sundefined option.\n",emsg);
      errline(i,1,err);
    }
    errcnt++;
  }else if( op[j].type==OPT_FLAG ){
    *((int*)op[j].arg) = v;
  }else if( op[j].type==OPT_FFLAG ){
    (*(void(*)())(op[j].arg))(v);
  }else if( op[j].type==OPT_FSTR ){
    (*(void(*)())(op[j].arg))(&argv[i][2]);
  }else{
    if( err ){
      fprintf(err,"%smissing argument on switch.\n",emsg);
      errline(i,1,err);
    }
    errcnt++;
  }
  return errcnt;
}

/*
** Process a command line switch which has an argument.
*/
static int handleswitch(i,err)
int i;
FILE *err;
{
  int lv = 0;
  double dv = 0.0;
  char *sv = 0, *end;
  char *cp;
  int j;
  int errcnt = 0;
  cp = strchr(argv[i],'=');
  assert( cp!=0 );
  *cp = 0;
  for(j=0; op[j].label; j++){
    if( strcmp(argv[i],op[j].label)==0 ) break;
  }
  *cp = '=';
  if( op[j].label==0 ){
    if( err ){
      fprintf(err,"%sundefined option.\n",emsg);
      errline(i,0,err);
    }
    errcnt++;
  }else{
    cp++;
    switch( op[j].type ){
      case OPT_FLAG:
      case OPT_FFLAG:
        if( err ){
          fprintf(err,"%soption requires an argument.\n",emsg);
          errline(i,0,err);
        }
        errcnt++;
        break;
      case OPT_DBL:
      case OPT_FDBL:
        dv = strtod(cp,&end);
        if( *end ){
          if( err ){
            fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
            errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
          }
          errcnt++;
        }
        break;
      case OPT_INT:
      case OPT_FINT:
        lv = strtol(cp,&end,0);
        if( *end ){
          if( err ){
            fprintf(err,"%sillegal character in integer argument.\n",emsg);
            errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
          }
          errcnt++;
        }
        break;
      case OPT_STR:
      case OPT_FSTR:
        sv = cp;
        break;
    }
    switch( op[j].type ){
      case OPT_FLAG:
      case OPT_FFLAG:
        break;
      case OPT_DBL:
        *(double*)(op[j].arg) = dv;
        break;
      case OPT_FDBL:
        (*(void(*)())(op[j].arg))(dv);
        break;
      case OPT_INT:
        *(int*)(op[j].arg) = lv;
        break;
      case OPT_FINT:
        (*(void(*)())(op[j].arg))((int)lv);
        break;
      case OPT_STR:
        *(char**)(op[j].arg) = sv;
        break;
      case OPT_FSTR:
        (*(void(*)())(op[j].arg))(sv);
        break;
    }
  }
  return errcnt;
}

int OptInit(a,o,err)
char **a;
struct s_options *o;
FILE *err;
{
  int errcnt = 0;
  argv = a;
  op = o;
  errstream = err;
  if( argv && *argv && op ){
    int i;
    for(i=1; argv[i]; i++){
      if( argv[i][0]=='+' || argv[i][0]=='-' ){
        errcnt += handleflags(i,err);
      }else if( strchr(argv[i],'=') ){
        errcnt += handleswitch(i,err);
      }
    }
  }
  if( errcnt>0 ){
    fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
    OptPrint();
    exit(1);
  }
  return 0;
}

int OptNArgs(){
  int cnt = 0;
  int dashdash = 0;
  int i;
  if( argv!=0 && argv[0]!=0 ){
    for(i=1; argv[i]; i++){
      if( dashdash || !ISOPT(argv[i]) ) cnt++;
      if( strcmp(argv[i],"--")==0 ) dashdash = 1;
    }
  }
  return cnt;
}

char *OptArg(n)
int n;
{
  int i;
  i = argindex(n);
  return i>=0 ? argv[i] : 0;
}

void OptErr(n)
int n;
{
  int i;
  i = argindex(n);
  if( i>=0 ) errline(i,0,errstream);
}

void OptPrint(){
  int i;
  int max, len;
  max = 0;
  for(i=0; op[i].label; i++){
    len = lemonStrlen(op[i].label) + 1;
    switch( op[i].type ){
      case OPT_FLAG:
      case OPT_FFLAG:
        break;
      case OPT_INT:
      case OPT_FINT:
        len += 9;       /* length of "<integer>" */
        break;
      case OPT_DBL:
      case OPT_FDBL:
        len += 6;       /* length of "<real>" */
        break;
      case OPT_STR:
      case OPT_FSTR:
        len += 8;       /* length of "<string>" */
        break;
    }
    if( len>max ) max = len;
  }
  for(i=0; op[i].label; i++){
    switch( op[i].type ){
      case OPT_FLAG:
      case OPT_FFLAG:
        fprintf(errstream,"  -%-*s  %s\n",max,op[i].label,op[i].message);
        break;
      case OPT_INT:
      case OPT_FINT:
        fprintf(errstream,"  %s=<integer>%*s  %s\n",op[i].label,
          (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
        break;
      case OPT_DBL:
      case OPT_FDBL:
        fprintf(errstream,"  %s=<real>%*s  %s\n",op[i].label,
          (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
        break;
      case OPT_STR:
      case OPT_FSTR:
        fprintf(errstream,"  %s=<string>%*s  %s\n",op[i].label,
          (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
        break;
    }
  }
}
/*********************** From the file "parse.c" ****************************/
/*
** Input file parser for the LEMON parser generator.
*/

/* The state of the parser */
struct pstate {
  char *filename;       /* Name of the input file */
  int tokenlineno;      /* Linenumber at which current token starts */
  int errorcnt;         /* Number of errors so far */
  char *tokenstart;     /* Text of current token */
  struct lemon *gp;     /* Global state vector */
  enum e_state {
    INITIALIZE,
    WAITING_FOR_DECL_OR_RULE,
    WAITING_FOR_DECL_KEYWORD,
    WAITING_FOR_DECL_ARG,
    WAITING_FOR_PRECEDENCE_SYMBOL,
    WAITING_FOR_ARROW,
    IN_RHS,
    LHS_ALIAS_1,
    LHS_ALIAS_2,
    LHS_ALIAS_3,
    RHS_ALIAS_1,
    RHS_ALIAS_2,
    PRECEDENCE_MARK_1,
    PRECEDENCE_MARK_2,
    RESYNC_AFTER_RULE_ERROR,
    RESYNC_AFTER_DECL_ERROR,
    WAITING_FOR_DESTRUCTOR_SYMBOL,
    WAITING_FOR_DATATYPE_SYMBOL,
    WAITING_FOR_FALLBACK_ID,
    WAITING_FOR_WILDCARD_ID
  } state;                   /* The state of the parser */
  struct symbol *fallback;   /* The fallback token */
  struct symbol *lhs;        /* Left-hand side of current rule */
  char *lhsalias;            /* Alias for the LHS */
  int nrhs;                  /* Number of right-hand side symbols seen */
  struct symbol *rhs[MAXRHS];  /* RHS symbols */
  char *alias[MAXRHS];       /* Aliases for each RHS symbol (or NULL) */
  struct rule *prevrule;     /* Previous rule parsed */
  char *declkeyword;         /* Keyword of a declaration */
  char **declargslot;        /* Where the declaration argument should be put */
  int insertLineMacro;       /* Add #line before declaration insert */
  int *decllinenoslot;       /* Where to write declaration line number */
  enum e_assoc declassoc;    /* Assign this association to decl arguments */
  int preccounter;           /* Assign this precedence to decl arguments */
  struct rule *firstrule;    /* Pointer to first rule in the grammar */
  struct rule *lastrule;     /* Pointer to the most recently parsed rule */
};

/* Parse a single token */
static void parseonetoken(psp)
struct pstate *psp;
{
  char *x;
  x = Strsafe(psp->tokenstart);     /* Save the token permanently */
#if 0
  printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
    x,psp->state);
#endif
  switch( psp->state ){
    case INITIALIZE:
      psp->prevrule = 0;
      psp->preccounter = 0;
      psp->firstrule = psp->lastrule = 0;
      psp->gp->nrule = 0;
      /* Fall thru to next case */
    case WAITING_FOR_DECL_OR_RULE:
      if( x[0]=='%' ){
        psp->state = WAITING_FOR_DECL_KEYWORD;
      }else if( islower(x[0]) ){
        psp->lhs = Symbol_new(x);
        psp->nrhs = 0;
        psp->lhsalias = 0;
        psp->state = WAITING_FOR_ARROW;
      }else if( x[0]=='{' ){
        if( psp->prevrule==0 ){
          ErrorMsg(psp->filename,psp->tokenlineno,
"There is no prior rule opon which to attach the code \
fragment which begins on this line.");
          psp->errorcnt++;
	}else if( psp->prevrule->code!=0 ){
          ErrorMsg(psp->filename,psp->tokenlineno,
"Code fragment beginning on this line is not the first \
to follow the previous rule.");
          psp->errorcnt++;
        }else{
          psp->prevrule->line = psp->tokenlineno;
          psp->prevrule->code = &x[1];
	}
      }else if( x[0]=='[' ){
        psp->state = PRECEDENCE_MARK_1;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Token \"%s\" should be either \"%%\" or a nonterminal name.",
          x);
        psp->errorcnt++;
      }
      break;
    case PRECEDENCE_MARK_1:
      if( !isupper(x[0]) ){
        ErrorMsg(psp->filename,psp->tokenlineno,
          "The precedence symbol must be a terminal.");
        psp->errorcnt++;
      }else if( psp->prevrule==0 ){
        ErrorMsg(psp->filename,psp->tokenlineno,
          "There is no prior rule to assign precedence \"[%s]\".",x);
        psp->errorcnt++;
      }else if( psp->prevrule->precsym!=0 ){
        ErrorMsg(psp->filename,psp->tokenlineno,
"Precedence mark on this line is not the first \
to follow the previous rule.");
        psp->errorcnt++;
      }else{
        psp->prevrule->precsym = Symbol_new(x);
      }
      psp->state = PRECEDENCE_MARK_2;
      break;
    case PRECEDENCE_MARK_2:
      if( x[0]!=']' ){
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Missing \"]\" on precedence mark.");
        psp->errorcnt++;
      }
      psp->state = WAITING_FOR_DECL_OR_RULE;
      break;
    case WAITING_FOR_ARROW:
      if( x[0]==':' && x[1]==':' && x[2]=='=' ){
        psp->state = IN_RHS;
      }else if( x[0]=='(' ){
        psp->state = LHS_ALIAS_1;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Expected to see a \":\" following the LHS symbol \"%s\".",
          psp->lhs->name);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case LHS_ALIAS_1:
      if( isalpha(x[0]) ){
        psp->lhsalias = x;
        psp->state = LHS_ALIAS_2;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "\"%s\" is not a valid alias for the LHS \"%s\"\n",
          x,psp->lhs->name);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case LHS_ALIAS_2:
      if( x[0]==')' ){
        psp->state = LHS_ALIAS_3;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case LHS_ALIAS_3:
      if( x[0]==':' && x[1]==':' && x[2]=='=' ){
        psp->state = IN_RHS;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Missing \"->\" following: \"%s(%s)\".",
           psp->lhs->name,psp->lhsalias);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case IN_RHS:
      if( x[0]=='.' ){
        struct rule *rp;
        rp = (struct rule *)calloc( sizeof(struct rule) + 
             sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
        if( rp==0 ){
          ErrorMsg(psp->filename,psp->tokenlineno,
            "Can't allocate enough memory for this rule.");
          psp->errorcnt++;
          psp->prevrule = 0;
	}else{
          int i;
          rp->ruleline = psp->tokenlineno;
          rp->rhs = (struct symbol**)&rp[1];
          rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
          for(i=0; i<psp->nrhs; i++){
            rp->rhs[i] = psp->rhs[i];
            rp->rhsalias[i] = psp->alias[i];
	  }
          rp->lhs = psp->lhs;
          rp->lhsalias = psp->lhsalias;
          rp->nrhs = psp->nrhs;
          rp->code = 0;
          rp->precsym = 0;
          rp->index = psp->gp->nrule++;
          rp->nextlhs = rp->lhs->rule;
          rp->lhs->rule = rp;
          rp->next = 0;
          if( psp->firstrule==0 ){
            psp->firstrule = psp->lastrule = rp;
	  }else{
            psp->lastrule->next = rp;
            psp->lastrule = rp;
	  }
          psp->prevrule = rp;
	}
        psp->state = WAITING_FOR_DECL_OR_RULE;
      }else if( isalpha(x[0]) ){
        if( psp->nrhs>=MAXRHS ){
          ErrorMsg(psp->filename,psp->tokenlineno,
            "Too many symbols on RHS of rule beginning at \"%s\".",
            x);
          psp->errorcnt++;
          psp->state = RESYNC_AFTER_RULE_ERROR;
	}else{
          psp->rhs[psp->nrhs] = Symbol_new(x);
          psp->alias[psp->nrhs] = 0;
          psp->nrhs++;
	}
      }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
        struct symbol *msp = psp->rhs[psp->nrhs-1];
        if( msp->type!=MULTITERMINAL ){
          struct symbol *origsp = msp;
          msp = calloc(1,sizeof(*msp));
          memset(msp, 0, sizeof(*msp));
          msp->type = MULTITERMINAL;
          msp->nsubsym = 1;
          msp->subsym = calloc(1,sizeof(struct symbol*));
          msp->subsym[0] = origsp;
          msp->name = origsp->name;
          psp->rhs[psp->nrhs-1] = msp;
        }
        msp->nsubsym++;
        msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
        msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
        if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
          ErrorMsg(psp->filename,psp->tokenlineno,
            "Cannot form a compound containing a non-terminal");
          psp->errorcnt++;
        }
      }else if( x[0]=='(' && psp->nrhs>0 ){
        psp->state = RHS_ALIAS_1;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Illegal character on RHS of rule: \"%s\".",x);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case RHS_ALIAS_1:
      if( isalpha(x[0]) ){
        psp->alias[psp->nrhs-1] = x;
        psp->state = RHS_ALIAS_2;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
          x,psp->rhs[psp->nrhs-1]->name);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case RHS_ALIAS_2:
      if( x[0]==')' ){
        psp->state = IN_RHS;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_RULE_ERROR;
      }
      break;
    case WAITING_FOR_DECL_KEYWORD:
      if( isalpha(x[0]) ){
        psp->declkeyword = x;
        psp->declargslot = 0;
        psp->decllinenoslot = 0;
        psp->insertLineMacro = 1;
        psp->state = WAITING_FOR_DECL_ARG;
        if( strcmp(x,"name")==0 ){
          psp->declargslot = &(psp->gp->name);
          psp->insertLineMacro = 0;
	}else if( strcmp(x,"include")==0 ){
          psp->declargslot = &(psp->gp->include);
	}else if( strcmp(x,"code")==0 ){
          psp->declargslot = &(psp->gp->extracode);
	}else if( strcmp(x,"token_destructor")==0 ){
          psp->declargslot = &psp->gp->tokendest;
	}else if( strcmp(x,"default_destructor")==0 ){
          psp->declargslot = &psp->gp->vardest;
	}else if( strcmp(x,"token_prefix")==0 ){
          psp->declargslot = &psp->gp->tokenprefix;
          psp->insertLineMacro = 0;
	}else if( strcmp(x,"syntax_error")==0 ){
          psp->declargslot = &(psp->gp->error);
	}else if( strcmp(x,"parse_accept")==0 ){
          psp->declargslot = &(psp->gp->accept);
	}else if( strcmp(x,"parse_failure")==0 ){
          psp->declargslot = &(psp->gp->failure);
	}else if( strcmp(x,"stack_overflow")==0 ){
          psp->declargslot = &(psp->gp->overflow);
        }else if( strcmp(x,"extra_argument")==0 ){
          psp->declargslot = &(psp->gp->arg);
          psp->insertLineMacro = 0;
        }else if( strcmp(x,"token_type")==0 ){
          psp->declargslot = &(psp->gp->tokentype);
          psp->insertLineMacro = 0;
        }else if( strcmp(x,"default_type")==0 ){
          psp->declargslot = &(psp->gp->vartype);
          psp->insertLineMacro = 0;
        }else if( strcmp(x,"stack_size")==0 ){
          psp->declargslot = &(psp->gp->stacksize);
          psp->insertLineMacro = 0;
        }else if( strcmp(x,"start_symbol")==0 ){
          psp->declargslot = &(psp->gp->start);
          psp->insertLineMacro = 0;
        }else if( strcmp(x,"left")==0 ){
          psp->preccounter++;
          psp->declassoc = LEFT;
          psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
        }else if( strcmp(x,"right")==0 ){
          psp->preccounter++;
          psp->declassoc = RIGHT;
          psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
        }else if( strcmp(x,"nonassoc")==0 ){
          psp->preccounter++;
          psp->declassoc = NONE;
          psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
	}else if( strcmp(x,"destructor")==0 ){
          psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
	}else if( strcmp(x,"type")==0 ){
          psp->state = WAITING_FOR_DATATYPE_SYMBOL;
        }else if( strcmp(x,"fallback")==0 ){
          psp->fallback = 0;
          psp->state = WAITING_FOR_FALLBACK_ID;
        }else if( strcmp(x,"wildcard")==0 ){
          psp->state = WAITING_FOR_WILDCARD_ID;
        }else{
          ErrorMsg(psp->filename,psp->tokenlineno,
            "Unknown declaration keyword: \"%%%s\".",x);
          psp->errorcnt++;
          psp->state = RESYNC_AFTER_DECL_ERROR;
	}
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Illegal declaration keyword: \"%s\".",x);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_DECL_ERROR;
      }
      break;
    case WAITING_FOR_DESTRUCTOR_SYMBOL:
      if( !isalpha(x[0]) ){
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Symbol name missing after %destructor keyword");
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_DECL_ERROR;
      }else{
        struct symbol *sp = Symbol_new(x);
        psp->declargslot = &sp->destructor;
        psp->decllinenoslot = &sp->destLineno;
        psp->insertLineMacro = 1;
        psp->state = WAITING_FOR_DECL_ARG;
      }
      break;
    case WAITING_FOR_DATATYPE_SYMBOL:
      if( !isalpha(x[0]) ){
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Symbol name missing after %destructor keyword");
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_DECL_ERROR;
      }else{
        struct symbol *sp = Symbol_new(x);
        psp->declargslot = &sp->datatype;
        psp->insertLineMacro = 0;
        psp->state = WAITING_FOR_DECL_ARG;
      }
      break;
    case WAITING_FOR_PRECEDENCE_SYMBOL:
      if( x[0]=='.' ){
        psp->state = WAITING_FOR_DECL_OR_RULE;
      }else if( isupper(x[0]) ){
        struct symbol *sp;
        sp = Symbol_new(x);
        if( sp->prec>=0 ){
          ErrorMsg(psp->filename,psp->tokenlineno,
            "Symbol \"%s\" has already be given a precedence.",x);
          psp->errorcnt++;
	}else{
          sp->prec = psp->preccounter;
          sp->assoc = psp->declassoc;
	}
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Can't assign a precedence to \"%s\".",x);
        psp->errorcnt++;
      }
      break;
    case WAITING_FOR_DECL_ARG:
      if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
        char *zOld, *zNew, *zBuf, *z;
        int nOld, n, nLine, nNew, nBack;
        int addLineMacro;
        char zLine[50];
        zNew = x;
        if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
        nNew = lemonStrlen(zNew);
        if( *psp->declargslot ){
          zOld = *psp->declargslot;
        }else{
          zOld = "";
        }
        nOld = lemonStrlen(zOld);
        n = nOld + nNew + 20;
        addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
                        (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
        if( addLineMacro ){
          for(z=psp->filename, nBack=0; *z; z++){
            if( *z=='\\' ) nBack++;
          }
          sprintf(zLine, "#line %d ", psp->tokenlineno);
          nLine = lemonStrlen(zLine);
          n += nLine + lemonStrlen(psp->filename) + nBack;
        }
        *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
        zBuf += nOld;
        if( addLineMacro ){
          if( nOld && zBuf[-1]!='\n' ){
            *(zBuf++) = '\n';
          }
          memcpy(zBuf, zLine, nLine);
          zBuf += nLine;
          *(zBuf++) = '"';
          for(z=psp->filename; *z; z++){
            if( *z=='\\' ){
              *(zBuf++) = '\\';
            }
            *(zBuf++) = *z;
          }
          *(zBuf++) = '"';
          *(zBuf++) = '\n';
        }
        if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
          psp->decllinenoslot[0] = psp->tokenlineno;
        }
        memcpy(zBuf, zNew, nNew);
        zBuf += nNew;
        *zBuf = 0;
        psp->state = WAITING_FOR_DECL_OR_RULE;
      }else{
        ErrorMsg(psp->filename,psp->tokenlineno,
          "Illegal argument to %%%s: %s",psp->declkeyword,x);
        psp->errorcnt++;
        psp->state = RESYNC_AFTER_DECL_ERROR;
      }
      break;
    case WAITING_FOR_FALLBACK_ID:
      if( x[0]=='.' ){
        psp->state = WAITING_FOR_DECL_OR_RULE;
      }else if( !isupper(x[0]) ){
        ErrorMsg(psp->filename, psp->tokenlineno,
          "%%fallback argument \"%s\" should be a token", x);
        psp->errorcnt++;
      }else{
        struct symbol *sp = Symbol_new(x);
        if( psp->fallback==0 ){
          psp->fallback = sp;
        }else if( sp->fallback ){
          ErrorMsg(psp->filename, psp->tokenlineno,
            "More than one fallback assigned to token %s", x);
          psp->errorcnt++;
        }else{
          sp->fallback = psp->fallback;
          psp->gp->has_fallback = 1;
        }
      }
      break;
    case WAITING_FOR_WILDCARD_ID:
      if( x[0]=='.' ){
        psp->state = WAITING_FOR_DECL_OR_RULE;
      }else if( !isupper(x[0]) ){
        ErrorMsg(psp->filename, psp->tokenlineno,
          "%%wildcard argument \"%s\" should be a token", x);
        psp->errorcnt++;
      }else{
        struct symbol *sp = Symbol_new(x);
        if( psp->gp->wildcard==0 ){
          psp->gp->wildcard = sp;
        }else{
          ErrorMsg(psp->filename, psp->tokenlineno,
            "Extra wildcard to token: %s", x);
          psp->errorcnt++;
        }
      }
      break;
    case RESYNC_AFTER_RULE_ERROR:
/*      if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
**      break; */
    case RESYNC_AFTER_DECL_ERROR:
      if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
      if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
      break;
  }
}

/* Run the preprocessor over the input file text.  The global variables
** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
** macros.  This routine looks for "%ifdef" and "%ifndef" and "%endif" and
** comments them out.  Text in between is also commented out as appropriate.
*/
static void preprocess_input(char *z){
  int i, j, k, n;
  int exclude = 0;
  int start = 0;
  int lineno = 1;
  int start_lineno = 1;
  for(i=0; z[i]; i++){
    if( z[i]=='\n' ) lineno++;
    if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
    if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
      if( exclude ){
        exclude--;
        if( exclude==0 ){
          for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
        }
      }
      for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
    }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
          || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
      if( exclude ){
        exclude++;
      }else{
        for(j=i+7; isspace(z[j]); j++){}
        for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
        exclude = 1;
        for(k=0; k<nDefine; k++){
          if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
            exclude = 0;
            break;
          }
        }
        if( z[i+3]=='n' ) exclude = !exclude;
        if( exclude ){
          start = i;
          start_lineno = lineno;
        }
      }
      for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
    }
  }
  if( exclude ){
    fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
    exit(1);
  }
}

/* In spite of its name, this function is really a scanner.  It read
** in the entire input file (all at once) then tokenizes it.  Each
** token is passed to the function "parseonetoken" which builds all
** the appropriate data structures in the global state vector "gp".
*/
void Parse(gp)
struct lemon *gp;
{
  struct pstate ps;
  FILE *fp;
  char *filebuf;
  int filesize;
  int lineno;
  int c;
  char *cp, *nextcp;
  int startline = 0;

  memset(&ps, '\0', sizeof(ps));
  ps.gp = gp;
  ps.filename = gp->filename;
  ps.errorcnt = 0;
  ps.state = INITIALIZE;

  /* Begin by reading the input file */
  fp = fopen(ps.filename,"rb");
  if( fp==0 ){
    ErrorMsg(ps.filename,0,"Can't open this file for reading.");
    gp->errorcnt++;
    return;
  }
  fseek(fp,0,2);
  filesize = ftell(fp);
  rewind(fp);
  filebuf = (char *)malloc( filesize+1 );
  if( filebuf==0 ){
    ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
      filesize+1);
    gp->errorcnt++;
    return;
  }
  if( fread(filebuf,1,filesize,fp)!=filesize ){
    ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
      filesize);
    free(filebuf);
    gp->errorcnt++;
    return;
  }
  fclose(fp);
  filebuf[filesize] = 0;

  /* Make an initial pass through the file to handle %ifdef and %ifndef */
  preprocess_input(filebuf);

  /* Now scan the text of the input file */
  lineno = 1;
  for(cp=filebuf; (c= *cp)!=0; ){
    if( c=='\n' ) lineno++;              /* Keep track of the line number */
    if( isspace(c) ){ cp++; continue; }  /* Skip all white space */
    if( c=='/' && cp[1]=='/' ){          /* Skip C++ style comments */
      cp+=2;
      while( (c= *cp)!=0 && c!='\n' ) cp++;
      continue;
    }
    if( c=='/' && cp[1]=='*' ){          /* Skip C style comments */
      cp+=2;
      while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
        if( c=='\n' ) lineno++;
        cp++;
      }
      if( c ) cp++;
      continue;
    }
    ps.tokenstart = cp;                /* Mark the beginning of the token */
    ps.tokenlineno = lineno;           /* Linenumber on which token begins */
    if( c=='\"' ){                     /* String literals */
      cp++;
      while( (c= *cp)!=0 && c!='\"' ){
        if( c=='\n' ) lineno++;
        cp++;
      }
      if( c==0 ){
        ErrorMsg(ps.filename,startline,
"String starting on this line is not terminated before the end of the file.");
        ps.errorcnt++;
        nextcp = cp;
      }else{
        nextcp = cp+1;
      }
    }else if( c=='{' ){               /* A block of C code */
      int level;
      cp++;
      for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
        if( c=='\n' ) lineno++;
        else if( c=='{' ) level++;
        else if( c=='}' ) level--;
        else if( c=='/' && cp[1]=='*' ){  /* Skip comments */
          int prevc;
          cp = &cp[2];
          prevc = 0;
          while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
            if( c=='\n' ) lineno++;
            prevc = c;
            cp++;
	  }
	}else if( c=='/' && cp[1]=='/' ){  /* Skip C++ style comments too */
          cp = &cp[2];
          while( (c= *cp)!=0 && c!='\n' ) cp++;
          if( c ) lineno++;
	}else if( c=='\'' || c=='\"' ){    /* String a character literals */
          int startchar, prevc;
          startchar = c;
          prevc = 0;
          for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
            if( c=='\n' ) lineno++;
            if( prevc=='\\' ) prevc = 0;
            else              prevc = c;
	  }
	}
      }
      if( c==0 ){
        ErrorMsg(ps.filename,ps.tokenlineno,
"C code starting on this line is not terminated before the end of the file.");
        ps.errorcnt++;
        nextcp = cp;
      }else{
        nextcp = cp+1;
      }
    }else if( isalnum(c) ){          /* Identifiers */
      while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
      nextcp = cp;
    }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
      cp += 3;
      nextcp = cp;
    }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
      cp += 2;
      while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
      nextcp = cp;
    }else{                          /* All other (one character) operators */
      cp++;
      nextcp = cp;
    }
    c = *cp;
    *cp = 0;                        /* Null terminate the token */
    parseonetoken(&ps);             /* Parse the token */
    *cp = c;                        /* Restore the buffer */
    cp = nextcp;
  }
  free(filebuf);                    /* Release the buffer after parsing */
  gp->rule = ps.firstrule;
  gp->errorcnt = ps.errorcnt;
}
/*************************** From the file "plink.c" *********************/
/*
** Routines processing configuration follow-set propagation links
** in the LEMON parser generator.
*/
static struct plink *plink_freelist = 0;

/* Allocate a new plink */
struct plink *Plink_new(){
  struct plink *new;

  if( plink_freelist==0 ){
    int i;
    int amt = 100;
    plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
    if( plink_freelist==0 ){
      fprintf(stderr,
      "Unable to allocate memory for a new follow-set propagation link.\n");
      exit(1);
    }
    for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
    plink_freelist[amt-1].next = 0;
  }
  new = plink_freelist;
  plink_freelist = plink_freelist->next;
  return new;
}

/* Add a plink to a plink list */
void Plink_add(plpp,cfp)
struct plink **plpp;
struct config *cfp;
{
  struct plink *new;
  new = Plink_new();
  new->next = *plpp;
  *plpp = new;
  new->cfp = cfp;
}

/* Transfer every plink on the list "from" to the list "to" */
void Plink_copy(to,from)
struct plink **to;
struct plink *from;
{
  struct plink *nextpl;
  while( from ){
    nextpl = from->next;
    from->next = *to;
    *to = from;
    from = nextpl;
  }
}

/* Delete every plink on the list */
void Plink_delete(plp)
struct plink *plp;
{
  struct plink *nextpl;

  while( plp ){
    nextpl = plp->next;
    plp->next = plink_freelist;
    plink_freelist = plp;
    plp = nextpl;
  }
}
/*********************** From the file "report.c" **************************/
/*
** Procedures for generating reports and tables in the LEMON parser generator.
*/

/* Generate a filename with the given suffix.  Space to hold the
** name comes from malloc() and must be freed by the calling
** function.
*/
PRIVATE char *file_makename(lemp,suffix)
struct lemon *lemp;
char *suffix;
{
  char *name;
  char *cp;

  name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
  if( name==0 ){
    fprintf(stderr,"Can't allocate space for a filename.\n");
    exit(1);
  }
  strcpy(name,lemp->filename);
  cp = strrchr(name,'.');
  if( cp ) *cp = 0;
  strcat(name,suffix);
  return name;
}

/* Open a file with a name based on the name of the input file,
** but with a different (specified) suffix, and return a pointer
** to the stream */
PRIVATE FILE *file_open(lemp,suffix,mode)
struct lemon *lemp;
char *suffix;
char *mode;
{
  FILE *fp;

  if( lemp->outname ) free(lemp->outname);
  lemp->outname = file_makename(lemp, suffix);
  fp = fopen(lemp->outname,mode);
  if( fp==0 && *mode=='w' ){
    fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
    lemp->errorcnt++;
    return 0;
  }
  return fp;
}

/* Duplicate the input file without comments and without actions 
** on rules */
void Reprint(lemp)
struct lemon *lemp;
{
  struct rule *rp;
  struct symbol *sp;
  int i, j, maxlen, len, ncolumns, skip;
  printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
  maxlen = 10;
  for(i=0; i<lemp->nsymbol; i++){
    sp = lemp->symbols[i];
    len = lemonStrlen(sp->name);
    if( len>maxlen ) maxlen = len;
  }
  ncolumns = 76/(maxlen+5);
  if( ncolumns<1 ) ncolumns = 1;
  skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
  for(i=0; i<skip; i++){
    printf("//");
    for(j=i; j<lemp->nsymbol; j+=skip){
      sp = lemp->symbols[j];
      assert( sp->index==j );
      printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
    }
    printf("\n");
  }
  for(rp=lemp->rule; rp; rp=rp->next){
    printf("%s",rp->lhs->name);
    /*    if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
    printf(" ::=");
    for(i=0; i<rp->nrhs; i++){
      sp = rp->rhs[i];
      printf(" %s", sp->name);
      if( sp->type==MULTITERMINAL ){
        for(j=1; j<sp->nsubsym; j++){
          printf("|%s", sp->subsym[j]->name);
        }
      }
      /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
    }
    printf(".");
    if( rp->precsym ) printf(" [%s]",rp->precsym->name);
    /* if( rp->code ) printf("\n    %s",rp->code); */
    printf("\n");
  }
}

void ConfigPrint(fp,cfp)
FILE *fp;
struct config *cfp;
{
  struct rule *rp;
  struct symbol *sp;
  int i, j;
  rp = cfp->rp;
  fprintf(fp,"%s ::=",rp->lhs->name);
  for(i=0; i<=rp->nrhs; i++){
    if( i==cfp->dot ) fprintf(fp," *");
    if( i==rp->nrhs ) break;
    sp = rp->rhs[i];
    fprintf(fp," %s", sp->name);
    if( sp->type==MULTITERMINAL ){
      for(j=1; j<sp->nsubsym; j++){
        fprintf(fp,"|%s",sp->subsym[j]->name);
      }
    }
  }
}

/* #define TEST */
#if 0
/* Print a set */
PRIVATE void SetPrint(out,set,lemp)
FILE *out;
char *set;
struct lemon *lemp;
{
  int i;
  char *spacer;
  spacer = "";
  fprintf(out,"%12s[","");
  for(i=0; i<lemp->nterminal; i++){
    if( SetFind(set,i) ){
      fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
      spacer = " ";
    }
  }
  fprintf(out,"]\n");
}

/* Print a plink chain */
PRIVATE void PlinkPrint(out,plp,tag)
FILE *out;
struct plink *plp;
char *tag;
{
  while( plp ){
    fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
    ConfigPrint(out,plp->cfp);
    fprintf(out,"\n");
    plp = plp->next;
  }
}
#endif

/* Print an action to the given file descriptor.  Return FALSE if
** nothing was actually printed.
*/
int PrintAction(struct action *ap, FILE *fp, int indent){
  int result = 1;
  switch( ap->type ){
    case SHIFT:
      fprintf(fp,"%*s shift  %d",indent,ap->sp->name,ap->x.stp->statenum);
      break;
    case REDUCE:
      fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
      break;
    case ACCEPT:
      fprintf(fp,"%*s accept",indent,ap->sp->name);
      break;
    case ERROR:
      fprintf(fp,"%*s error",indent,ap->sp->name);
      break;
    case SRCONFLICT:
    case RRCONFLICT:
      fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
        indent,ap->sp->name,ap->x.rp->index);
      break;
    case SSCONFLICT:
      fprintf(fp,"%*s shift  %d ** Parsing conflict **", 
        indent,ap->sp->name,ap->x.stp->statenum);
      break;
    case SH_RESOLVED:
    case RD_RESOLVED:
    case NOT_USED:
      result = 0;
      break;
  }
  return result;
}

/* Generate the "y.output" log file */
void ReportOutput(lemp)
struct lemon *lemp;
{
  int i;
  struct state *stp;
  struct config *cfp;
  struct action *ap;
  FILE *fp;

  fp = file_open(lemp,".out","wb");
  if( fp==0 ) return;
  for(i=0; i<lemp->nstate; i++){
    stp = lemp->sorted[i];
    fprintf(fp,"State %d:\n",stp->statenum);
    if( lemp->basisflag ) cfp=stp->bp;
    else                  cfp=stp->cfp;
    while( cfp ){
      char buf[20];
      if( cfp->dot==cfp->rp->nrhs ){
        sprintf(buf,"(%d)",cfp->rp->index);
        fprintf(fp,"    %5s ",buf);
      }else{
        fprintf(fp,"          ");
      }
      ConfigPrint(fp,cfp);
      fprintf(fp,"\n");
#if 0
      SetPrint(fp,cfp->fws,lemp);
      PlinkPrint(fp,cfp->fplp,"To  ");
      PlinkPrint(fp,cfp->bplp,"From");
#endif
      if( lemp->basisflag ) cfp=cfp->bp;
      else                  cfp=cfp->next;
    }
    fprintf(fp,"\n");
    for(ap=stp->ap; ap; ap=ap->next){
      if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
    }
    fprintf(fp,"\n");
  }
  fprintf(fp, "----------------------------------------------------\n");
  fprintf(fp, "Symbols:\n");
  for(i=0; i<lemp->nsymbol; i++){
    int j;
    struct symbol *sp;

    sp = lemp->symbols[i];
    fprintf(fp, "  %3d: %s", i, sp->name);
    if( sp->type==NONTERMINAL ){
      fprintf(fp, ":");
      if( sp->lambda ){
        fprintf(fp, " <lambda>");
      }
      for(j=0; j<lemp->nterminal; j++){
        if( sp->firstset && SetFind(sp->firstset, j) ){
          fprintf(fp, " %s", lemp->symbols[j]->name);
        }
      }
    }
    fprintf(fp, "\n");
  }
  fclose(fp);
  return;
}

/* Search for the file "name" which is in the same directory as
** the exacutable */
PRIVATE char *pathsearch(argv0,name,modemask)
char *argv0;
char *name;
int modemask;
{
  char *pathlist;
  char *path,*cp;
  char c;

#ifdef __WIN32__
  cp = strrchr(argv0,'\\');
#else
  cp = strrchr(argv0,'/');
#endif
  if( cp ){
    c = *cp;
    *cp = 0;
    path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
    if( path ) sprintf(path,"%s/%s",argv0,name);
    *cp = c;
  }else{
    extern char *getenv();
    pathlist = getenv("PATH");
    if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
    path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
    if( path!=0 ){
      while( *pathlist ){
        cp = strchr(pathlist,':');
        if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
        c = *cp;
        *cp = 0;
        sprintf(path,"%s/%s",pathlist,name);
        *cp = c;
        if( c==0 ) pathlist = "";
        else pathlist = &cp[1];
        if( access(path,modemask)==0 ) break;
      }
    }
  }
  return path;
}

/* Given an action, compute the integer value for that action
** which is to be put in the action table of the generated machine.
** Return negative if no action should be generated.
*/
PRIVATE int compute_action(lemp,ap)
struct lemon *lemp;
struct action *ap;
{
  int act;
  switch( ap->type ){
    case SHIFT:  act = ap->x.stp->statenum;            break;
    case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
    case ERROR:  act = lemp->nstate + lemp->nrule;     break;
    case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
    default:     act = -1; break;
  }
  return act;
}

#define LINESIZE 1000
/* The next cluster of routines are for reading the template file
** and writing the results to the generated parser */
/* The first function transfers data from "in" to "out" until
** a line is seen which begins with "%%".  The line number is
** tracked.
**
** if name!=0, then any word that begin with "Parse" is changed to
** begin with *name instead.
*/
PRIVATE void tplt_xfer(name,in,out,lineno)
char *name;
FILE *in;
FILE *out;
int *lineno;
{
  int i, iStart;
  char line[LINESIZE];
  while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
    (*lineno)++;
    iStart = 0;
    if( name ){
      for(i=0; line[i]; i++){
        if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
          && (i==0 || !isalpha(line[i-1]))
        ){
          if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
          fprintf(out,"%s",name);
          i += 4;
          iStart = i+1;
        }
      }
    }
    fprintf(out,"%s",&line[iStart]);
  }
}

/* The next function finds the template file and opens it, returning
** a pointer to the opened file. */
PRIVATE FILE *tplt_open(lemp)
struct lemon *lemp;
{
  static char templatename[] = "lempar.c";
  char buf[1000];
  FILE *in;
  char *tpltname;
  char *cp;

  cp = strrchr(lemp->filename,'.');
  if( cp ){
    sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
  }else{
    sprintf(buf,"%s.lt",lemp->filename);
  }
  if( access(buf,004)==0 ){
    tpltname = buf;
  }else if( access(templatename,004)==0 ){
    tpltname = templatename;
  }else{
    tpltname = pathsearch(lemp->argv0,templatename,0);
  }
  if( tpltname==0 ){
    fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
    templatename);
    lemp->errorcnt++;
    return 0;
  }
  in = fopen(tpltname,"rb");
  if( in==0 ){
    fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
    lemp->errorcnt++;
    return 0;
  }
  return in;
}

/* Print a #line directive line to the output file. */
PRIVATE void tplt_linedir(out,lineno,filename)
FILE *out;
int lineno;
char *filename;
{
  fprintf(out,"#line %d \"",lineno);
  while( *filename ){
    if( *filename == '\\' ) putc('\\',out);
    putc(*filename,out);
    filename++;
  }
  fprintf(out,"\"\n");
}

/* Print a string to the file and keep the linenumber up to date */
PRIVATE void tplt_print(out,lemp,str,lineno)
FILE *out;
struct lemon *lemp;
char *str;
int *lineno;
{
  if( str==0 ) return;
  while( *str ){
    putc(*str,out);
    if( *str=='\n' ) (*lineno)++;
    str++;
  }
  if( str[-1]!='\n' ){
    putc('\n',out);
    (*lineno)++;
  }
  if (!lemp->nolinenosflag) {
    (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); 
  }
  return;
}

/*
** The following routine emits code for the destructor for the
** symbol sp
*/
void emit_destructor_code(out,sp,lemp,lineno)
FILE *out;
struct symbol *sp;
struct lemon *lemp;
int *lineno;
{
 char *cp = 0;

 if( sp->type==TERMINAL ){
   cp = lemp->tokendest;
   if( cp==0 ) return;
   fprintf(out,"{\n"); (*lineno)++;
 }else if( sp->destructor ){
   cp = sp->destructor;
   fprintf(out,"{\n"); (*lineno)++;
   if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
 }else if( lemp->vardest ){
   cp = lemp->vardest;
   if( cp==0 ) return;
   fprintf(out,"{\n"); (*lineno)++;
 }else{
   assert( 0 );  /* Cannot happen */
 }
 for(; *cp; cp++){
   if( *cp=='$' && cp[1]=='$' ){
     fprintf(out,"(yypminor->yy%d)",sp->dtnum);
     cp++;
     continue;
   }
   if( *cp=='\n' ) (*lineno)++;
   fputc(*cp,out);
 }
 fprintf(out,"\n"); (*lineno)++;
 if (!lemp->nolinenosflag) { 
   (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); 
 }
 fprintf(out,"}\n"); (*lineno)++;
 return;
}

/*
** Return TRUE (non-zero) if the given symbol has a destructor.
*/
int has_destructor(sp, lemp)
struct symbol *sp;
struct lemon *lemp;
{
  int ret;
  if( sp->type==TERMINAL ){
    ret = lemp->tokendest!=0;
  }else{
    ret = lemp->vardest!=0 || sp->destructor!=0;
  }
  return ret;
}

/*
** Append text to a dynamically allocated string.  If zText is 0 then
** reset the string to be empty again.  Always return the complete text
** of the string (which is overwritten with each call).
**
** n bytes of zText are stored.  If n==0 then all of zText up to the first
** \000 terminator is stored.  zText can contain up to two instances of
** %d.  The values of p1 and p2 are written into the first and second
** %d.
**
** If n==-1, then the previous character is overwritten.
*/
PRIVATE char *append_str(char *zText, int n, int p1, int p2){
  static char *z = 0;
  static int alloced = 0;
  static int used = 0;
  int c;
  char zInt[40];

  if( zText==0 ){
    used = 0;
    return z;
  }
  if( n<=0 ){
    if( n<0 ){
      used += n;
      assert( used>=0 );
    }
    n = lemonStrlen(zText);
  }
  if( n+sizeof(zInt)*2+used >= alloced ){
    alloced = n + sizeof(zInt)*2 + used + 200;
    z = realloc(z,  alloced);
  }
  if( z==0 ) return "";
  while( n-- > 0 ){
    c = *(zText++);
    if( c=='%' && n>0 && zText[0]=='d' ){
      sprintf(zInt, "%d", p1);
      p1 = p2;
      strcpy(&z[used], zInt);
      used += lemonStrlen(&z[used]);
      zText++;
      n--;
    }else{
      z[used++] = c;
    }
  }
  z[used] = 0;
  return z;
}

/*
** zCode is a string that is the action associated with a rule.  Expand
** the symbols in this string so that the refer to elements of the parser
** stack.
*/
PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
  char *cp, *xp;
  int i;
  char lhsused = 0;    /* True if the LHS element has been used */
  char used[MAXRHS];   /* True for each RHS element which is used */

  for(i=0; i<rp->nrhs; i++) used[i] = 0;
  lhsused = 0;

  if( rp->code==0 ){
    rp->code = "\n";
    rp->line = rp->ruleline;
  }

  append_str(0,0,0,0);
  for(cp=rp->code; *cp; cp++){
    if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
      char saved;
      for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
      saved = *xp;
      *xp = 0;
      if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
        append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
        cp = xp;
        lhsused = 1;
      }else{
        for(i=0; i<rp->nrhs; i++){
          if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
            if( cp!=rp->code && cp[-1]=='@' ){
              /* If the argument is of the form @X then substituted
              ** the token number of X, not the value of X */
              append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
            }else{
              struct symbol *sp = rp->rhs[i];
              int dtnum;
              if( sp->type==MULTITERMINAL ){
                dtnum = sp->subsym[0]->dtnum;
              }else{
                dtnum = sp->dtnum;
              }
              append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
            }
            cp = xp;
            used[i] = 1;
            break;
          }
        }
      }
      *xp = saved;
    }
    append_str(cp, 1, 0, 0);
  } /* End loop */

  /* Check to make sure the LHS has been used */
  if( rp->lhsalias && !lhsused ){
    ErrorMsg(lemp->filename,rp->ruleline,
      "Label \"%s\" for \"%s(%s)\" is never used.",
        rp->lhsalias,rp->lhs->name,rp->lhsalias);
    lemp->errorcnt++;
  }

  /* Generate destructor code for RHS symbols which are not used in the
  ** reduce code */
  for(i=0; i<rp->nrhs; i++){
    if( rp->rhsalias[i] && !used[i] ){
      ErrorMsg(lemp->filename,rp->ruleline,
        "Label %s for \"%s(%s)\" is never used.",
        rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
      lemp->errorcnt++;
    }else if( rp->rhsalias[i]==0 ){
      if( has_destructor(rp->rhs[i],lemp) ){
        append_str("  yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
           rp->rhs[i]->index,i-rp->nrhs+1);
      }else{
        /* No destructor defined for this term */
      }
    }
  }
  if( rp->code ){
    cp = append_str(0,0,0,0);
    rp->code = Strsafe(cp?cp:"");
  }
}

/* 
** Generate code which executes when the rule "rp" is reduced.  Write
** the code to "out".  Make sure lineno stays up-to-date.
*/
PRIVATE void emit_code(out,rp,lemp,lineno)
FILE *out;
struct rule *rp;
struct lemon *lemp;
int *lineno;
{
 char *cp;

 /* Generate code to do the reduce action */
 if( rp->code ){
   if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
   fprintf(out,"{%s",rp->code);
   for(cp=rp->code; *cp; cp++){
     if( *cp=='\n' ) (*lineno)++;
   } /* End loop */
   fprintf(out,"}\n"); (*lineno)++;
   if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
 } /* End if( rp->code ) */

 return;
}

/*
** Print the definition of the union used for the parser's data stack.
** This union contains fields for every possible data type for tokens
** and nonterminals.  In the process of computing and printing this
** union, also set the ".dtnum" field of every terminal and nonterminal
** symbol.
*/
void print_stack_union(out,lemp,plineno,mhflag)
FILE *out;                  /* The output stream */
struct lemon *lemp;         /* The main info structure for this parser */
int *plineno;               /* Pointer to the line number */
int mhflag;                 /* True if generating makeheaders output */
{
  int lineno = *plineno;    /* The line number of the output */
  char **types;             /* A hash table of datatypes */
  int arraysize;            /* Size of the "types" array */
  int maxdtlength;          /* Maximum length of any ".datatype" field. */
  char *stddt;              /* Standardized name for a datatype */
  int i,j;                  /* Loop counters */
  int hash;                 /* For hashing the name of a type */
  char *name;               /* Name of the parser */

  /* Allocate and initialize types[] and allocate stddt[] */
  arraysize = lemp->nsymbol * 2;
  types = (char**)calloc( arraysize, sizeof(char*) );
  for(i=0; i<arraysize; i++) types[i] = 0;
  maxdtlength = 0;
  if( lemp->vartype ){
    maxdtlength = lemonStrlen(lemp->vartype);
  }
  for(i=0; i<lemp->nsymbol; i++){
    int len;
    struct symbol *sp = lemp->symbols[i];
    if( sp->datatype==0 ) continue;
    len = lemonStrlen(sp->datatype);
    if( len>maxdtlength ) maxdtlength = len;
  }
  stddt = (char*)malloc( maxdtlength*2 + 1 );
  if( types==0 || stddt==0 ){
    fprintf(stderr,"Out of memory.\n");
    exit(1);
  }

  /* Build a hash table of datatypes. The ".dtnum" field of each symbol
  ** is filled in with the hash index plus 1.  A ".dtnum" value of 0 is
  ** used for terminal symbols.  If there is no %default_type defined then
  ** 0 is also used as the .dtnum value for nonterminals which do not specify
  ** a datatype using the %type directive.
  */
  for(i=0; i<lemp->nsymbol; i++){
    struct symbol *sp = lemp->symbols[i];
    char *cp;
    if( sp==lemp->errsym ){
      sp->dtnum = arraysize+1;
      continue;
    }
    if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
      sp->dtnum = 0;
      continue;
    }
    cp = sp->datatype;
    if( cp==0 ) cp = lemp->vartype;
    j = 0;
    while( isspace(*cp) ) cp++;
    while( *cp ) stddt[j++] = *cp++;
    while( j>0 && isspace(stddt[j-1]) ) j--;
    stddt[j] = 0;
    if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
      sp->dtnum = 0;
      continue;
    }
    hash = 0;
    for(j=0; stddt[j]; j++){
      hash = hash*53 + stddt[j];
    }
    hash = (hash & 0x7fffffff)%arraysize;
    while( types[hash] ){
      if( strcmp(types[hash],stddt)==0 ){
        sp->dtnum = hash + 1;
        break;
      }
      hash++;
      if( hash>=arraysize ) hash = 0;
    }
    if( types[hash]==0 ){
      sp->dtnum = hash + 1;
      types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
      if( types[hash]==0 ){
        fprintf(stderr,"Out of memory.\n");
        exit(1);
      }
      strcpy(types[hash],stddt);
    }
  }

  /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
  name = lemp->name ? lemp->name : "Parse";
  lineno = *plineno;
  if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
  fprintf(out,"#define %sTOKENTYPE %s\n",name,
    lemp->tokentype?lemp->tokentype:"void*");  lineno++;
  if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
  fprintf(out,"typedef union {\n"); lineno++;
  fprintf(out,"  int yyinit;\n"); lineno++;
  fprintf(out,"  %sTOKENTYPE yy0;\n",name); lineno++;
  for(i=0; i<arraysize; i++){
    if( types[i]==0 ) continue;
    fprintf(out,"  %s yy%d;\n",types[i],i+1); lineno++;
    free(types[i]);
  }
  if( lemp->errsym->useCnt ){
    fprintf(out,"  int yy%d;\n",lemp->errsym->dtnum); lineno++;
  }
  free(stddt);
  free(types);
  fprintf(out,"} YYMINORTYPE;\n"); lineno++;
  *plineno = lineno;
}

/*
** Return the name of a C datatype able to represent values between
** lwr and upr, inclusive.
*/
static const char *minimum_size_type(int lwr, int upr){
  if( lwr>=0 ){
    if( upr<=255 ){
      return "unsigned char";
    }else if( upr<65535 ){
      return "unsigned short int";
    }else{
      return "unsigned int";
    }
  }else if( lwr>=-127 && upr<=127 ){
    return "signed char";
  }else if( lwr>=-32767 && upr<32767 ){
    return "short";
  }else{
    return "int";
  }
}

/*
** Each state contains a set of token transaction and a set of
** nonterminal transactions.  Each of these sets makes an instance
** of the following structure.  An array of these structures is used
** to order the creation of entries in the yy_action[] table.
*/
struct axset {
  struct state *stp;   /* A pointer to a state */
  int isTkn;           /* True to use tokens.  False for non-terminals */
  int nAction;         /* Number of actions */
  int iOrder;          /* Original order of action sets */
};

/*
** Compare to axset structures for sorting purposes
*/
static int axset_compare(const void *a, const void *b){
  struct axset *p1 = (struct axset*)a;
  struct axset *p2 = (struct axset*)b;
  int c;
  c = p2->nAction - p1->nAction;
  if( c==0 ){
    c = p2->iOrder - p1->iOrder;
  }
  assert( c!=0 || p1==p2 );
  return c;
}

/*
** Write text on "out" that describes the rule "rp".
*/
static void writeRuleText(FILE *out, struct rule *rp){
  int j;
  fprintf(out,"%s ::=", rp->lhs->name);
  for(j=0; j<rp->nrhs; j++){
    struct symbol *sp = rp->rhs[j];
    fprintf(out," %s", sp->name);
    if( sp->type==MULTITERMINAL ){
      int k;
      for(k=1; k<sp->nsubsym; k++){
        fprintf(out,"|%s",sp->subsym[k]->name);
      }
    }
  }
}


/* Generate C source code for the parser */
void ReportTable(lemp, mhflag)
struct lemon *lemp;
int mhflag;     /* Output in makeheaders format if true */
{
  FILE *out, *in;
  char line[LINESIZE];
  int  lineno;
  struct state *stp;
  struct action *ap;
  struct rule *rp;
  struct acttab *pActtab;
  int i, j, k, n;
  char *name;
  int mnTknOfst, mxTknOfst;
  int mnNtOfst, mxNtOfst;
  struct axset *ax;

  in = tplt_open(lemp);
  if( in==0 ) return;
  out = file_open(lemp,".c","wb");
  if( out==0 ){
    fclose(in);
    return;
  }
  lineno = 1;
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate the include code, if any */
  tplt_print(out,lemp,lemp->include,&lineno);
  if( mhflag ){
    char *name = file_makename(lemp, ".h");
    fprintf(out,"#include \"%s\"\n", name); lineno++;
    free(name);
  }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate #defines for all tokens */
  if( mhflag ){
    char *prefix;
    fprintf(out,"#if INTERFACE\n"); lineno++;
    if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
    else                    prefix = "";
    for(i=1; i<lemp->nterminal; i++){
      fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
      lineno++;
    }
    fprintf(out,"#endif\n"); lineno++;
  }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate the defines */
  fprintf(out,"#define YYCODETYPE %s\n",
    minimum_size_type(0, lemp->nsymbol+1)); lineno++;
  fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1);  lineno++;
  fprintf(out,"#define YYACTIONTYPE %s\n",
    minimum_size_type(0, lemp->nstate+lemp->nrule+5));  lineno++;
  if( lemp->wildcard ){
    fprintf(out,"#define YYWILDCARD %d\n",
       lemp->wildcard->index); lineno++;
  }
  print_stack_union(out,lemp,&lineno,mhflag);
  fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
  if( lemp->stacksize ){
    fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize);  lineno++;
  }else{
    fprintf(out,"#define YYSTACKDEPTH 100\n");  lineno++;
  }
  fprintf(out, "#endif\n"); lineno++;
  if( mhflag ){
    fprintf(out,"#if INTERFACE\n"); lineno++;
  }
  name = lemp->name ? lemp->name : "Parse";
  if( lemp->arg && lemp->arg[0] ){
    int i;
    i = lemonStrlen(lemp->arg);
    while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
    while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
    fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg);  lineno++;
    fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg);  lineno++;
    fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
                 name,lemp->arg,&lemp->arg[i]);  lineno++;
    fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
                 name,&lemp->arg[i],&lemp->arg[i]);  lineno++;
  }else{
    fprintf(out,"#define %sARG_SDECL\n",name);  lineno++;
    fprintf(out,"#define %sARG_PDECL\n",name);  lineno++;
    fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
    fprintf(out,"#define %sARG_STORE\n",name); lineno++;
  }
  if( mhflag ){
    fprintf(out,"#endif\n"); lineno++;
  }
  fprintf(out,"#define YYNSTATE %d\n",lemp->nstate);  lineno++;
  fprintf(out,"#define YYNRULE %d\n",lemp->nrule);  lineno++;
  if( lemp->errsym->useCnt ){
    fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index);  lineno++;
    fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum);  lineno++;
  }
  if( lemp->has_fallback ){
    fprintf(out,"#define YYFALLBACK 1\n");  lineno++;
  }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate the action table and its associates:
  **
  **  yy_action[]        A single table containing all actions.
  **  yy_lookahead[]     A table containing the lookahead for each entry in
  **                     yy_action.  Used to detect hash collisions.
  **  yy_shift_ofst[]    For each state, the offset into yy_action for
  **                     shifting terminals.
  **  yy_reduce_ofst[]   For each state, the offset into yy_action for
  **                     shifting non-terminals after a reduce.
  **  yy_default[]       Default action for each state.
  */

  /* Compute the actions on all states and count them up */
  ax = calloc(lemp->nstate*2, sizeof(ax[0]));
  if( ax==0 ){
    fprintf(stderr,"malloc failed\n");
    exit(1);
  }
  for(i=0; i<lemp->nstate; i++){
    stp = lemp->sorted[i];
    ax[i*2].stp = stp;
    ax[i*2].isTkn = 1;
    ax[i*2].nAction = stp->nTknAct;
    ax[i*2+1].stp = stp;
    ax[i*2+1].isTkn = 0;
    ax[i*2+1].nAction = stp->nNtAct;
  }
  mxTknOfst = mnTknOfst = 0;
  mxNtOfst = mnNtOfst = 0;

  /* Compute the action table.  In order to try to keep the size of the
  ** action table to a minimum, the heuristic of placing the largest action
  ** sets first is used.
  */
  for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
  qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
  pActtab = acttab_alloc();
  for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
    stp = ax[i].stp;
    if( ax[i].isTkn ){
      for(ap=stp->ap; ap; ap=ap->next){
        int action;
        if( ap->sp->index>=lemp->nterminal ) continue;
        action = compute_action(lemp, ap);
        if( action<0 ) continue;
        acttab_action(pActtab, ap->sp->index, action);
      }
      stp->iTknOfst = acttab_insert(pActtab);
      if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
      if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
    }else{
      for(ap=stp->ap; ap; ap=ap->next){
        int action;
        if( ap->sp->index<lemp->nterminal ) continue;
        if( ap->sp->index==lemp->nsymbol ) continue;
        action = compute_action(lemp, ap);
        if( action<0 ) continue;
        acttab_action(pActtab, ap->sp->index, action);
      }
      stp->iNtOfst = acttab_insert(pActtab);
      if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
      if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
    }
  }
  free(ax);

  /* Output the yy_action table */
  n = acttab_size(pActtab);
  fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
  fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
  for(i=j=0; i<n; i++){
    int action = acttab_yyaction(pActtab, i);
    if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
    if( j==0 ) fprintf(out," /* %5d */ ", i);
    fprintf(out, " %4d,", action);
    if( j==9 || i==n-1 ){
      fprintf(out, "\n"); lineno++;
      j = 0;
    }else{
      j++;
    }
  }
  fprintf(out, "};\n"); lineno++;

  /* Output the yy_lookahead table */
  fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
  for(i=j=0; i<n; i++){
    int la = acttab_yylookahead(pActtab, i);
    if( la<0 ) la = lemp->nsymbol;
    if( j==0 ) fprintf(out," /* %5d */ ", i);
    fprintf(out, " %4d,", la);
    if( j==9 || i==n-1 ){
      fprintf(out, "\n"); lineno++;
      j = 0;
    }else{
      j++;
    }
  }
  fprintf(out, "};\n"); lineno++;

  /* Output the yy_shift_ofst[] table */
  fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
  n = lemp->nstate;
  while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
  fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
  fprintf(out, "#define YY_SHIFT_MIN   (%d)\n", mnTknOfst); lineno++;
  fprintf(out, "#define YY_SHIFT_MAX   (%d)\n", mxTknOfst); lineno++;
  fprintf(out, "static const %s yy_shift_ofst[] = {\n", 
          minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
  for(i=j=0; i<n; i++){
    int ofst;
    stp = lemp->sorted[i];
    ofst = stp->iTknOfst;
    if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
    if( j==0 ) fprintf(out," /* %5d */ ", i);
    fprintf(out, " %4d,", ofst);
    if( j==9 || i==n-1 ){
      fprintf(out, "\n"); lineno++;
      j = 0;
    }else{
      j++;
    }
  }
  fprintf(out, "};\n"); lineno++;

  /* Output the yy_reduce_ofst[] table */
  fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
  n = lemp->nstate;
  while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
  fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
  fprintf(out, "#define YY_REDUCE_MIN   (%d)\n", mnNtOfst); lineno++;
  fprintf(out, "#define YY_REDUCE_MAX   (%d)\n", mxNtOfst); lineno++;
  fprintf(out, "static const %s yy_reduce_ofst[] = {\n", 
          minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
  for(i=j=0; i<n; i++){
    int ofst;
    stp = lemp->sorted[i];
    ofst = stp->iNtOfst;
    if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
    if( j==0 ) fprintf(out," /* %5d */ ", i);
    fprintf(out, " %4d,", ofst);
    if( j==9 || i==n-1 ){
      fprintf(out, "\n"); lineno++;
      j = 0;
    }else{
      j++;
    }
  }
  fprintf(out, "};\n"); lineno++;

  /* Output the default action table */
  fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
  n = lemp->nstate;
  for(i=j=0; i<n; i++){
    stp = lemp->sorted[i];
    if( j==0 ) fprintf(out," /* %5d */ ", i);
    fprintf(out, " %4d,", stp->iDflt);
    if( j==9 || i==n-1 ){
      fprintf(out, "\n"); lineno++;
      j = 0;
    }else{
      j++;
    }
  }
  fprintf(out, "};\n"); lineno++;
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate the table of fallback tokens.
  */
  if( lemp->has_fallback ){
    int mx = lemp->nterminal - 1;
    while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
    for(i=0; i<=mx; i++){
      struct symbol *p = lemp->symbols[i];
      if( p->fallback==0 ){
        fprintf(out, "    0,  /* %10s => nothing */\n", p->name);
      }else{
        fprintf(out, "  %3d,  /* %10s => %s */\n", p->fallback->index,
          p->name, p->fallback->name);
      }
      lineno++;
    }
  }
  tplt_xfer(lemp->name, in, out, &lineno);

  /* Generate a table containing the symbolic name of every symbol
  */
  for(i=0; i<lemp->nsymbol; i++){
    sprintf(line,"\"%s\",",lemp->symbols[i]->name);
    fprintf(out,"  %-15s",line);
    if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
  }
  if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate a table containing a text string that describes every
  ** rule in the rule set of the grammar.  This information is used
  ** when tracing REDUCE actions.
  */
  for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
    assert( rp->index==i );
    fprintf(out," /* %3d */ \"", i);
    writeRuleText(out, rp);
    fprintf(out,"\",\n"); lineno++;
  }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate code which executes every time a symbol is popped from
  ** the stack while processing errors or while destroying the parser. 
  ** (In other words, generate the %destructor actions)
  */
  if( lemp->tokendest ){
    int once = 1;
    for(i=0; i<lemp->nsymbol; i++){
      struct symbol *sp = lemp->symbols[i];
      if( sp==0 || sp->type!=TERMINAL ) continue;
      if( once ){
        fprintf(out, "      /* TERMINAL Destructor */\n"); lineno++;
        once = 0;
      }
      fprintf(out,"    case %d: /* %s */\n", sp->index, sp->name); lineno++;
    }
    for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
    if( i<lemp->nsymbol ){
      emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
      fprintf(out,"      break;\n"); lineno++;
    }
  }
  if( lemp->vardest ){
    struct symbol *dflt_sp = 0;
    int once = 1;
    for(i=0; i<lemp->nsymbol; i++){
      struct symbol *sp = lemp->symbols[i];
      if( sp==0 || sp->type==TERMINAL ||
          sp->index<=0 || sp->destructor!=0 ) continue;
      if( once ){
        fprintf(out, "      /* Default NON-TERMINAL Destructor */\n"); lineno++;
        once = 0;
      }
      fprintf(out,"    case %d: /* %s */\n", sp->index, sp->name); lineno++;
      dflt_sp = sp;
    }
    if( dflt_sp!=0 ){
      emit_destructor_code(out,dflt_sp,lemp,&lineno);
    }
    fprintf(out,"      break;\n"); lineno++;
  }
  for(i=0; i<lemp->nsymbol; i++){
    struct symbol *sp = lemp->symbols[i];
    if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
    fprintf(out,"    case %d: /* %s */\n", sp->index, sp->name); lineno++;

    /* Combine duplicate destructors into a single case */
    for(j=i+1; j<lemp->nsymbol; j++){
      struct symbol *sp2 = lemp->symbols[j];
      if( sp2 && sp2->type!=TERMINAL && sp2->destructor
          && sp2->dtnum==sp->dtnum
          && strcmp(sp->destructor,sp2->destructor)==0 ){
         fprintf(out,"    case %d: /* %s */\n",
                 sp2->index, sp2->name); lineno++;
         sp2->destructor = 0;
      }
    }

    emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
    fprintf(out,"      break;\n"); lineno++;
  }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate code which executes whenever the parser stack overflows */
  tplt_print(out,lemp,lemp->overflow,&lineno);
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate the table of rule information 
  **
  ** Note: This code depends on the fact that rules are number
  ** sequentually beginning with 0.
  */
  for(rp=lemp->rule; rp; rp=rp->next){
    fprintf(out,"  { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
  }
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate code which execution during each REDUCE action */
  for(rp=lemp->rule; rp; rp=rp->next){
    translate_code(lemp, rp);
  }
  /* First output rules other than the default: rule */
  for(rp=lemp->rule; rp; rp=rp->next){
    struct rule *rp2;               /* Other rules with the same action */
    if( rp->code==0 ) continue;
    if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
    fprintf(out,"      case %d: /* ", rp->index);
    writeRuleText(out, rp);
    fprintf(out, " */\n"); lineno++;
    for(rp2=rp->next; rp2; rp2=rp2->next){
      if( rp2->code==rp->code ){
        fprintf(out,"      case %d: /* ", rp2->index);
        writeRuleText(out, rp2);
        fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
        rp2->code = 0;
      }
    }
    emit_code(out,rp,lemp,&lineno);
    fprintf(out,"        break;\n"); lineno++;
    rp->code = 0;
  }
  /* Finally, output the default: rule.  We choose as the default: all
  ** empty actions. */
  fprintf(out,"      default:\n"); lineno++;
  for(rp=lemp->rule; rp; rp=rp->next){
    if( rp->code==0 ) continue;
    assert( rp->code[0]=='\n' && rp->code[1]==0 );
    fprintf(out,"      /* (%d) ", rp->index);
    writeRuleText(out, rp);
    fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
  }
  fprintf(out,"        break;\n"); lineno++;
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate code which executes if a parse fails */
  tplt_print(out,lemp,lemp->failure,&lineno);
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate code which executes when a syntax error occurs */
  tplt_print(out,lemp,lemp->error,&lineno);
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Generate code which executes when the parser accepts its input */
  tplt_print(out,lemp,lemp->accept,&lineno);
  tplt_xfer(lemp->name,in,out,&lineno);

  /* Append any addition code the user desires */
  tplt_print(out,lemp,lemp->extracode,&lineno);

  fclose(in);
  fclose(out);
  return;
}

/* Generate a header file for the parser */
void ReportHeader(lemp)
struct lemon *lemp;
{
  FILE *out, *in;
  char *prefix;
  char line[LINESIZE];
  char pattern[LINESIZE];
  int i;

  if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
  else                    prefix = "";
  in = file_open(lemp,".h","rb");
  if( in ){
    for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
      sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
      if( strcmp(line,pattern) ) break;
    }
    fclose(in);
    if( i==lemp->nterminal ){
      /* No change in the file.  Don't rewrite it. */
      return;
    }
  }
  out = file_open(lemp,".h","wb");
  if( out ){
    for(i=1; i<lemp->nterminal; i++){
      fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
    }
    fclose(out);  
  }
  return;
}

/* Reduce the size of the action tables, if possible, by making use
** of defaults.
**
** In this version, we take the most frequent REDUCE action and make
** it the default.  Except, there is no default if the wildcard token
** is a possible look-ahead.
*/
void CompressTables(lemp)
struct lemon *lemp;
{
  struct state *stp;
  struct action *ap, *ap2;
  struct rule *rp, *rp2, *rbest;
  int nbest, n;
  int i;
  int usesWildcard;

  for(i=0; i<lemp->nstate; i++){
    stp = lemp->sorted[i];
    nbest = 0;
    rbest = 0;
    usesWildcard = 0;

    for(ap=stp->ap; ap; ap=ap->next){
      if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
        usesWildcard = 1;
      }
      if( ap->type!=REDUCE ) continue;
      rp = ap->x.rp;
      if( rp->lhsStart ) continue;
      if( rp==rbest ) continue;
      n = 1;
      for(ap2=ap->next; ap2; ap2=ap2->next){
        if( ap2->type!=REDUCE ) continue;
        rp2 = ap2->x.rp;
        if( rp2==rbest ) continue;
        if( rp2==rp ) n++;
      }
      if( n>nbest ){
        nbest = n;
        rbest = rp;
      }
    }
 
    /* Do not make a default if the number of rules to default
    ** is not at least 1 or if the wildcard token is a possible
    ** lookahead.
    */
    if( nbest<1 || usesWildcard ) continue;


    /* Combine matching REDUCE actions into a single default */
    for(ap=stp->ap; ap; ap=ap->next){
      if( ap->type==REDUCE && ap->x.rp==rbest ) break;
    }
    assert( ap );
    ap->sp = Symbol_new("{default}");
    for(ap=ap->next; ap; ap=ap->next){
      if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
    }
    stp->ap = Action_sort(stp->ap);
  }
}


/*
** Compare two states for sorting purposes.  The smaller state is the
** one with the most non-terminal actions.  If they have the same number
** of non-terminal actions, then the smaller is the one with the most
** token actions.
*/
static int stateResortCompare(const void *a, const void *b){
  const struct state *pA = *(const struct state**)a;
  const struct state *pB = *(const struct state**)b;
  int n;

  n = pB->nNtAct - pA->nNtAct;
  if( n==0 ){
    n = pB->nTknAct - pA->nTknAct;
    if( n==0 ){
      n = pB->statenum - pA->statenum;
    }
  }
  assert( n!=0 );
  return n;
}


/*
** Renumber and resort states so that states with fewer choices
** occur at the end.  Except, keep state 0 as the first state.
*/
void ResortStates(lemp)
struct lemon *lemp;
{
  int i;
  struct state *stp;
  struct action *ap;

  for(i=0; i<lemp->nstate; i++){
    stp = lemp->sorted[i];
    stp->nTknAct = stp->nNtAct = 0;
    stp->iDflt = lemp->nstate + lemp->nrule;
    stp->iTknOfst = NO_OFFSET;
    stp->iNtOfst = NO_OFFSET;
    for(ap=stp->ap; ap; ap=ap->next){
      if( compute_action(lemp,ap)>=0 ){
        if( ap->sp->index<lemp->nterminal ){
          stp->nTknAct++;
        }else if( ap->sp->index<lemp->nsymbol ){
          stp->nNtAct++;
        }else{
          stp->iDflt = compute_action(lemp, ap);
        }
      }
    }
  }
  qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
        stateResortCompare);
  for(i=0; i<lemp->nstate; i++){
    lemp->sorted[i]->statenum = i;
  }
}


/***************** From the file "set.c" ************************************/
/*
** Set manipulation routines for the LEMON parser generator.
*/

static int size = 0;

/* Set the set size */
void SetSize(n)
int n;
{
  size = n+1;
}

/* Allocate a new set */
char *SetNew(){
  char *s;
  s = (char*)calloc( size, 1);
  if( s==0 ){
    extern void memory_error();
    memory_error();
  }
  return s;
}

/* Deallocate a set */
void SetFree(s)
char *s;
{
  free(s);
}

/* Add a new element to the set.  Return TRUE if the element was added
** and FALSE if it was already there. */
int SetAdd(s,e)
char *s;
int e;
{
  int rv;
  assert( e>=0 && e<size );
  rv = s[e];
  s[e] = 1;
  return !rv;
}

/* Add every element of s2 to s1.  Return TRUE if s1 changes. */
int SetUnion(s1,s2)
char *s1;
char *s2;
{
  int i, progress;
  progress = 0;
  for(i=0; i<size; i++){
    if( s2[i]==0 ) continue;
    if( s1[i]==0 ){
      progress = 1;
      s1[i] = 1;
    }
  }
  return progress;
}
/********************** From the file "table.c" ****************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
**              "table.q"
** by the associative array code building program "aagen".
** Do not edit this file!  Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/

PRIVATE int strhash(x)
char *x;
{
  int h = 0;
  while( *x) h = h*13 + *(x++);
  return h;
}

/* Works like strdup, sort of.  Save a string in malloced memory, but
** keep strings in a table so that the same string is not in more
** than one place.
*/
char *Strsafe(y)
char *y;
{
  char *z;

  if( y==0 ) return 0;
  z = Strsafe_find(y);
  if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
    strcpy(z,y);
    Strsafe_insert(z);
  }
  MemoryCheck(z);
  return z;
}

/* There is one instance of the following structure for each
** associative array of type "x1".
*/
struct s_x1 {
  int size;               /* The number of available slots. */
                          /*   Must be a power of 2 greater than or */
                          /*   equal to 1 */
  int count;              /* Number of currently slots filled */
  struct s_x1node *tbl;  /* The data stored here */
  struct s_x1node **ht;  /* Hash table for lookups */
};

/* There is one instance of this structure for every data element
** in an associative array of type "x1".
*/
typedef struct s_x1node {
  char *data;                  /* The data */
  struct s_x1node *next;   /* Next entry with the same hash */
  struct s_x1node **from;  /* Previous link */
} x1node;

/* There is only one instance of the array, which is the following */
static struct s_x1 *x1a;

/* Allocate a new associative array */
void Strsafe_init(){
  if( x1a ) return;
  x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
  if( x1a ){
    x1a->size = 1024;
    x1a->count = 0;
    x1a->tbl = (x1node*)malloc( 
      (sizeof(x1node) + sizeof(x1node*))*1024 );
    if( x1a->tbl==0 ){
      free(x1a);
      x1a = 0;
    }else{
      int i;
      x1a->ht = (x1node**)&(x1a->tbl[1024]);
      for(i=0; i<1024; i++) x1a->ht[i] = 0;
    }
  }
}
/* Insert a new record into the array.  Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Strsafe_insert(data)
char *data;
{
  x1node *np;
  int h;
  int ph;

  if( x1a==0 ) return 0;
  ph = strhash(data);
  h = ph & (x1a->size-1);
  np = x1a->ht[h];
  while( np ){
    if( strcmp(np->data,data)==0 ){
      /* An existing entry with the same key is found. */
      /* Fail because overwrite is not allows. */
      return 0;
    }
    np = np->next;
  }
  if( x1a->count>=x1a->size ){
    /* Need to make the hash table bigger */
    int i,size;
    struct s_x1 array;
    array.size = size = x1a->size*2;
    array.count = x1a->count;
    array.tbl = (x1node*)malloc(
      (sizeof(x1node) + sizeof(x1node*))*size );
    if( array.tbl==0 ) return 0;  /* Fail due to malloc failure */
    array.ht = (x1node**)&(array.tbl[size]);
    for(i=0; i<size; i++) array.ht[i] = 0;
    for(i=0; i<x1a->count; i++){
      x1node *oldnp, *newnp;
      oldnp = &(x1a->tbl[i]);
      h = strhash(oldnp->data) & (size-1);
      newnp = &(array.tbl[i]);
      if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
      newnp->next = array.ht[h];
      newnp->data = oldnp->data;
      newnp->from = &(array.ht[h]);
      array.ht[h] = newnp;
    }
    free(x1a->tbl);
    *x1a = array;
  }
  /* Insert the new data */
  h = ph & (x1a->size-1);
  np = &(x1a->tbl[x1a->count++]);
  np->data = data;
  if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
  np->next = x1a->ht[h];
  x1a->ht[h] = np;
  np->from = &(x1a->ht[h]);
  return 1;
}

/* Return a pointer to data assigned to the given key.  Return NULL
** if no such key. */
char *Strsafe_find(key)
char *key;
{
  int h;
  x1node *np;

  if( x1a==0 ) return 0;
  h = strhash(key) & (x1a->size-1);
  np = x1a->ht[h];
  while( np ){
    if( strcmp(np->data,key)==0 ) break;
    np = np->next;
  }
  return np ? np->data : 0;
}

/* Return a pointer to the (terminal or nonterminal) symbol "x".
** Create a new symbol if this is the first time "x" has been seen.
*/
struct symbol *Symbol_new(x)
char *x;
{
  struct symbol *sp;

  sp = Symbol_find(x);
  if( sp==0 ){
    sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
    MemoryCheck(sp);
    sp->name = Strsafe(x);
    sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
    sp->rule = 0;
    sp->fallback = 0;
    sp->prec = -1;
    sp->assoc = UNK;
    sp->firstset = 0;
    sp->lambda = LEMON_FALSE;
    sp->destructor = 0;
    sp->destLineno = 0;
    sp->datatype = 0;
    sp->useCnt = 0;
    Symbol_insert(sp,sp->name);
  }
  sp->useCnt++;
  return sp;
}

/* Compare two symbols for working purposes
**
** Symbols that begin with upper case letters (terminals or tokens)
** must sort before symbols that begin with lower case letters
** (non-terminals).  Other than that, the order does not matter.
**
** We find experimentally that leaving the symbols in their original
** order (the order they appeared in the grammar file) gives the
** smallest parser tables in SQLite.
*/
int Symbolcmpp(struct symbol **a, struct symbol **b){
  int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
  int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
  assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
  return i1-i2;
}

/* There is one instance of the following structure for each
** associative array of type "x2".
*/
struct s_x2 {
  int size;               /* The number of available slots. */
                          /*   Must be a power of 2 greater than or */
                          /*   equal to 1 */
  int count;              /* Number of currently slots filled */
  struct s_x2node *tbl;  /* The data stored here */
  struct s_x2node **ht;  /* Hash table for lookups */
};

/* There is one instance of this structure for every data element
** in an associative array of type "x2".
*/
typedef struct s_x2node {
  struct symbol *data;                  /* The data */
  char *key;                   /* The key */
  struct s_x2node *next;   /* Next entry with the same hash */
  struct s_x2node **from;  /* Previous link */
} x2node;

/* There is only one instance of the array, which is the following */
static struct s_x2 *x2a;

/* Allocate a new associative array */
void Symbol_init(){
  if( x2a ) return;
  x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
  if( x2a ){
    x2a->size = 128;
    x2a->count = 0;
    x2a->tbl = (x2node*)malloc( 
      (sizeof(x2node) + sizeof(x2node*))*128 );
    if( x2a->tbl==0 ){
      free(x2a);
      x2a = 0;
    }else{
      int i;
      x2a->ht = (x2node**)&(x2a->tbl[128]);
      for(i=0; i<128; i++) x2a->ht[i] = 0;
    }
  }
}
/* Insert a new record into the array.  Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Symbol_insert(data,key)
struct symbol *data;
char *key;
{
  x2node *np;
  int h;
  int ph;

  if( x2a==0 ) return 0;
  ph = strhash(key);
  h = ph & (x2a->size-1);
  np = x2a->ht[h];
  while( np ){
    if( strcmp(np->key,key)==0 ){
      /* An existing entry with the same key is found. */
      /* Fail because overwrite is not allows. */
      return 0;
    }
    np = np->next;
  }
  if( x2a->count>=x2a->size ){
    /* Need to make the hash table bigger */
    int i,size;
    struct s_x2 array;
    array.size = size = x2a->size*2;
    array.count = x2a->count;
    array.tbl = (x2node*)malloc(
      (sizeof(x2node) + sizeof(x2node*))*size );
    if( array.tbl==0 ) return 0;  /* Fail due to malloc failure */
    array.ht = (x2node**)&(array.tbl[size]);
    for(i=0; i<size; i++) array.ht[i] = 0;
    for(i=0; i<x2a->count; i++){
      x2node *oldnp, *newnp;
      oldnp = &(x2a->tbl[i]);
      h = strhash(oldnp->key) & (size-1);
      newnp = &(array.tbl[i]);
      if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
      newnp->next = array.ht[h];
      newnp->key = oldnp->key;
      newnp->data = oldnp->data;
      newnp->from = &(array.ht[h]);
      array.ht[h] = newnp;
    }
    free(x2a->tbl);
    *x2a = array;
  }
  /* Insert the new data */
  h = ph & (x2a->size-1);
  np = &(x2a->tbl[x2a->count++]);
  np->key = key;
  np->data = data;
  if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
  np->next = x2a->ht[h];
  x2a->ht[h] = np;
  np->from = &(x2a->ht[h]);
  return 1;
}

/* Return a pointer to data assigned to the given key.  Return NULL
** if no such key. */
struct symbol *Symbol_find(key)
char *key;
{
  int h;
  x2node *np;

  if( x2a==0 ) return 0;
  h = strhash(key) & (x2a->size-1);
  np = x2a->ht[h];
  while( np ){
    if( strcmp(np->key,key)==0 ) break;
    np = np->next;
  }
  return np ? np->data : 0;
}

/* Return the n-th data.  Return NULL if n is out of range. */
struct symbol *Symbol_Nth(n)
int n;
{
  struct symbol *data;
  if( x2a && n>0 && n<=x2a->count ){
    data = x2a->tbl[n-1].data;
  }else{
    data = 0;
  }
  return data;
}

/* Return the size of the array */
int Symbol_count()
{
  return x2a ? x2a->count : 0;
}

/* Return an array of pointers to all data in the table.
** The array is obtained from malloc.  Return NULL if memory allocation
** problems, or if the array is empty. */
struct symbol **Symbol_arrayof()
{
  struct symbol **array;
  int i,size;
  if( x2a==0 ) return 0;
  size = x2a->count;
  array = (struct symbol **)calloc(size, sizeof(struct symbol *));
  if( array ){
    for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
  }
  return array;
}

/* Compare two configurations */
int Configcmp(a,b)
struct config *a;
struct config *b;
{
  int x;
  x = a->rp->index - b->rp->index;
  if( x==0 ) x = a->dot - b->dot;
  return x;
}

/* Compare two states */
PRIVATE int statecmp(a,b)
struct config *a;
struct config *b;
{
  int rc;
  for(rc=0; rc==0 && a && b;  a=a->bp, b=b->bp){
    rc = a->rp->index - b->rp->index;
    if( rc==0 ) rc = a->dot - b->dot;
  }
  if( rc==0 ){
    if( a ) rc = 1;
    if( b ) rc = -1;
  }
  return rc;
}

/* Hash a state */
PRIVATE int statehash(a)
struct config *a;
{
  int h=0;
  while( a ){
    h = h*571 + a->rp->index*37 + a->dot;
    a = a->bp;
  }
  return h;
}

/* Allocate a new state structure */
struct state *State_new()
{
  struct state *new;
  new = (struct state *)calloc(1, sizeof(struct state) );
  MemoryCheck(new);
  return new;
}

/* There is one instance of the following structure for each
** associative array of type "x3".
*/
struct s_x3 {
  int size;               /* The number of available slots. */
                          /*   Must be a power of 2 greater than or */
                          /*   equal to 1 */
  int count;              /* Number of currently slots filled */
  struct s_x3node *tbl;  /* The data stored here */
  struct s_x3node **ht;  /* Hash table for lookups */
};

/* There is one instance of this structure for every data element
** in an associative array of type "x3".
*/
typedef struct s_x3node {
  struct state *data;                  /* The data */
  struct config *key;                   /* The key */
  struct s_x3node *next;   /* Next entry with the same hash */
  struct s_x3node **from;  /* Previous link */
} x3node;

/* There is only one instance of the array, which is the following */
static struct s_x3 *x3a;

/* Allocate a new associative array */
void State_init(){
  if( x3a ) return;
  x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
  if( x3a ){
    x3a->size = 128;
    x3a->count = 0;
    x3a->tbl = (x3node*)malloc( 
      (sizeof(x3node) + sizeof(x3node*))*128 );
    if( x3a->tbl==0 ){
      free(x3a);
      x3a = 0;
    }else{
      int i;
      x3a->ht = (x3node**)&(x3a->tbl[128]);
      for(i=0; i<128; i++) x3a->ht[i] = 0;
    }
  }
}
/* Insert a new record into the array.  Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int State_insert(data,key)
struct state *data;
struct config *key;
{
  x3node *np;
  int h;
  int ph;

  if( x3a==0 ) return 0;
  ph = statehash(key);
  h = ph & (x3a->size-1);
  np = x3a->ht[h];
  while( np ){
    if( statecmp(np->key,key)==0 ){
      /* An existing entry with the same key is found. */
      /* Fail because overwrite is not allows. */
      return 0;
    }
    np = np->next;
  }
  if( x3a->count>=x3a->size ){
    /* Need to make the hash table bigger */
    int i,size;
    struct s_x3 array;
    array.size = size = x3a->size*2;
    array.count = x3a->count;
    array.tbl = (x3node*)malloc(
      (sizeof(x3node) + sizeof(x3node*))*size );
    if( array.tbl==0 ) return 0;  /* Fail due to malloc failure */
    array.ht = (x3node**)&(array.tbl[size]);
    for(i=0; i<size; i++) array.ht[i] = 0;
    for(i=0; i<x3a->count; i++){
      x3node *oldnp, *newnp;
      oldnp = &(x3a->tbl[i]);
      h = statehash(oldnp->key) & (size-1);
      newnp = &(array.tbl[i]);
      if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
      newnp->next = array.ht[h];
      newnp->key = oldnp->key;
      newnp->data = oldnp->data;
      newnp->from = &(array.ht[h]);
      array.ht[h] = newnp;
    }
    free(x3a->tbl);
    *x3a = array;
  }
  /* Insert the new data */
  h = ph & (x3a->size-1);
  np = &(x3a->tbl[x3a->count++]);
  np->key = key;
  np->data = data;
  if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
  np->next = x3a->ht[h];
  x3a->ht[h] = np;
  np->from = &(x3a->ht[h]);
  return 1;
}

/* Return a pointer to data assigned to the given key.  Return NULL
** if no such key. */
struct state *State_find(key)
struct config *key;
{
  int h;
  x3node *np;

  if( x3a==0 ) return 0;
  h = statehash(key) & (x3a->size-1);
  np = x3a->ht[h];
  while( np ){
    if( statecmp(np->key,key)==0 ) break;
    np = np->next;
  }
  return np ? np->data : 0;
}

/* Return an array of pointers to all data in the table.
** The array is obtained from malloc.  Return NULL if memory allocation
** problems, or if the array is empty. */
struct state **State_arrayof()
{
  struct state **array;
  int i,size;
  if( x3a==0 ) return 0;
  size = x3a->count;
  array = (struct state **)malloc( sizeof(struct state *)*size );
  if( array ){
    for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
  }
  return array;
}

/* Hash a configuration */
PRIVATE int confighash(a)
struct config *a;
{
  int h=0;
  h = h*571 + a->rp->index*37 + a->dot;
  return h;
}

/* There is one instance of the following structure for each
** associative array of type "x4".
*/
struct s_x4 {
  int size;               /* The number of available slots. */
                          /*   Must be a power of 2 greater than or */
                          /*   equal to 1 */
  int count;              /* Number of currently slots filled */
  struct s_x4node *tbl;  /* The data stored here */
  struct s_x4node **ht;  /* Hash table for lookups */
};

/* There is one instance of this structure for every data element
** in an associative array of type "x4".
*/
typedef struct s_x4node {
  struct config *data;                  /* The data */
  struct s_x4node *next;   /* Next entry with the same hash */
  struct s_x4node **from;  /* Previous link */
} x4node;

/* There is only one instance of the array, which is the following */
static struct s_x4 *x4a;

/* Allocate a new associative array */
void Configtable_init(){
  if( x4a ) return;
  x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
  if( x4a ){
    x4a->size = 64;
    x4a->count = 0;
    x4a->tbl = (x4node*)malloc( 
      (sizeof(x4node) + sizeof(x4node*))*64 );
    if( x4a->tbl==0 ){
      free(x4a);
      x4a = 0;
    }else{
      int i;
      x4a->ht = (x4node**)&(x4a->tbl[64]);
      for(i=0; i<64; i++) x4a->ht[i] = 0;
    }
  }
}
/* Insert a new record into the array.  Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Configtable_insert(data)
struct config *data;
{
  x4node *np;
  int h;
  int ph;

  if( x4a==0 ) return 0;
  ph = confighash(data);
  h = ph & (x4a->size-1);
  np = x4a->ht[h];
  while( np ){
    if( Configcmp(np->data,data)==0 ){
      /* An existing entry with the same key is found. */
      /* Fail because overwrite is not allows. */
      return 0;
    }
    np = np->next;
  }
  if( x4a->count>=x4a->size ){
    /* Need to make the hash table bigger */
    int i,size;
    struct s_x4 array;
    array.size = size = x4a->size*2;
    array.count = x4a->count;
    array.tbl = (x4node*)malloc(
      (sizeof(x4node) + sizeof(x4node*))*size );
    if( array.tbl==0 ) return 0;  /* Fail due to malloc failure */
    array.ht = (x4node**)&(array.tbl[size]);
    for(i=0; i<size; i++) array.ht[i] = 0;
    for(i=0; i<x4a->count; i++){
      x4node *oldnp, *newnp;
      oldnp = &(x4a->tbl[i]);
      h = confighash(oldnp->data) & (size-1);
      newnp = &(array.tbl[i]);
      if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
      newnp->next = array.ht[h];
      newnp->data = oldnp->data;
      newnp->from = &(array.ht[h]);
      array.ht[h] = newnp;
    }
    free(x4a->tbl);
    *x4a = array;
  }
  /* Insert the new data */
  h = ph & (x4a->size-1);
  np = &(x4a->tbl[x4a->count++]);
  np->data = data;
  if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
  np->next = x4a->ht[h];
  x4a->ht[h] = np;
  np->from = &(x4a->ht[h]);
  return 1;
}

/* Return a pointer to data assigned to the given key.  Return NULL
** if no such key. */
struct config *Configtable_find(key)
struct config *key;
{
  int h;
  x4node *np;

  if( x4a==0 ) return 0;
  h = confighash(key) & (x4a->size-1);
  np = x4a->ht[h];
  while( np ){
    if( Configcmp(np->data,key)==0 ) break;
    np = np->next;
  }
  return np ? np->data : 0;
}

/* Remove all data from the table.  Pass each data to the function "f"
** as it is removed.  ("f" may be null to avoid this step.) */
void Configtable_clear(f)
int(*f)(/* struct config * */);
{
  int i;
  if( x4a==0 || x4a->count==0 ) return;
  if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
  for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
  x4a->count = 0;
  return;
}

Added tool/lempar.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
/* Driver template for the LEMON parser generator.
** The author disclaims copyright to this source code.
*/
/* First off, code is included that follows the "include" declaration
** in the input grammar file. */
#include <stdio.h>
%%
/* Next is all token values, in a form suitable for use by makeheaders.
** This section will be null unless lemon is run with the -m switch.
*/
/* 
** These constants (all generated automatically by the parser generator)
** specify the various kinds of tokens (terminals) that the parser
** understands. 
**
** Each symbol here is a terminal symbol in the grammar.
*/
%%
/* Make sure the INTERFACE macro is defined.
*/
#ifndef INTERFACE
# define INTERFACE 1
#endif
/* The next thing included is series of defines which control
** various aspects of the generated parser.
**    YYCODETYPE         is the data type used for storing terminal
**                       and nonterminal numbers.  "unsigned char" is
**                       used if there are fewer than 250 terminals
**                       and nonterminals.  "int" is used otherwise.
**    YYNOCODE           is a number of type YYCODETYPE which corresponds
**                       to no legal terminal or nonterminal number.  This
**                       number is used to fill in empty slots of the hash 
**                       table.
**    YYFALLBACK         If defined, this indicates that one or more tokens
**                       have fall-back values which should be used if the
**                       original value of the token will not parse.
**    YYACTIONTYPE       is the data type used for storing terminal
**                       and nonterminal numbers.  "unsigned char" is
**                       used if there are fewer than 250 rules and
**                       states combined.  "int" is used otherwise.
**    ParseTOKENTYPE     is the data type used for minor tokens given 
**                       directly to the parser from the tokenizer.
**    YYMINORTYPE        is the data type used for all minor tokens.
**                       This is typically a union of many types, one of
**                       which is ParseTOKENTYPE.  The entry in the union
**                       for base tokens is called "yy0".
**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
**                       zero the stack is dynamically sized using realloc()
**    ParseARG_SDECL     A static variable declaration for the %extra_argument
**    ParseARG_PDECL     A parameter declaration for the %extra_argument
**    ParseARG_STORE     Code to store %extra_argument into yypParser
**    ParseARG_FETCH     Code to extract %extra_argument from yypParser
**    YYNSTATE           the combined number of states.
**    YYNRULE            the number of rules in the grammar
**    YYERRORSYMBOL      is the code number of the error symbol.  If not
**                       defined, then do no error processing.
*/
%%
#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)

/* The yyzerominor constant is used to initialize instances of
** YYMINORTYPE objects to zero. */
static const YYMINORTYPE yyzerominor = { 0 };

/* Define the yytestcase() macro to be a no-op if is not already defined
** otherwise.
**
** Applications can choose to define yytestcase() in the %include section
** to a macro that can assist in verifying code coverage.  For production
** code the yytestcase() macro should be turned off.  But it is useful
** for testing.
*/
#ifndef yytestcase
# define yytestcase(X)
#endif


/* Next are the tables used to determine what action to take based on the
** current state and lookahead token.  These tables are used to implement
** functions that take a state number and lookahead value and return an
** action integer.  
**
** Suppose the action integer is N.  Then the action is determined as
** follows
**
**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
**                                      token onto the stack and goto state N.
**
**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
**
**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
**
**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
**
**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
**                                      slots in the yy_action[] table.
**
** The action table is constructed as a single large table named yy_action[].
** Given state S and lookahead X, the action is computed as
**
**      yy_action[ yy_shift_ofst[S] + X ]
**
** If the index value yy_shift_ofst[S]+X is out of range or if the value
** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
** and that yy_default[S] should be used instead.  
**
** The formula above is for computing the action when the lookahead is
** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
** a reduce action) then the yy_reduce_ofst[] array is used in place of
** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
** YY_SHIFT_USE_DFLT.
**
** The following are the tables generated in this section:
**
**  yy_action[]        A single table containing all actions.
**  yy_lookahead[]     A table containing the lookahead for each entry in
**                     yy_action.  Used to detect hash collisions.
**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
*/
%%

/* The next table maps tokens into fallback tokens.  If a construct
** like the following:
** 
**      %fallback ID X Y Z.
**
** appears in the grammar, then ID becomes a fallback token for X, Y,
** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
** but it does not parse, the type of the token is changed to ID and
** the parse is retried before an error is thrown.
*/
#ifdef YYFALLBACK
static const YYCODETYPE yyFallback[] = {
%%
};
#endif /* YYFALLBACK */

/* The following structure represents a single element of the
** parser's stack.  Information stored includes:
**
**   +  The state number for the parser at this level of the stack.
**
**   +  The value of the token stored at this level of the stack.
**      (In other words, the "major" token.)
**
**   +  The semantic value stored at this level of the stack.  This is
**      the information used by the action routines in the grammar.
**      It is sometimes called the "minor" token.
*/
struct yyStackEntry {
  YYACTIONTYPE stateno;  /* The state-number */
  YYCODETYPE major;      /* The major token value.  This is the code
                         ** number for the token at this stack level */
  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
                         ** is the value of the token  */
};
typedef struct yyStackEntry yyStackEntry;

/* The state of the parser is completely contained in an instance of
** the following structure */
struct yyParser {
  int yyidx;                    /* Index of top element in stack */
#ifdef YYTRACKMAXSTACKDEPTH
  int yyidxMax;                 /* Maximum value of yyidx */
#endif
  int yyerrcnt;                 /* Shifts left before out of the error */
  ParseARG_SDECL                /* A place to hold %extra_argument */
#if YYSTACKDEPTH<=0
  int yystksz;                  /* Current side of the stack */
  yyStackEntry *yystack;        /* The parser's stack */
#else
  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
#endif
};
typedef struct yyParser yyParser;

#ifndef NDEBUG
#include <stdio.h>
static FILE *yyTraceFILE = 0;
static char *yyTracePrompt = 0;
#endif /* NDEBUG */

#ifndef NDEBUG
/* 
** Turn parser tracing on by giving a stream to which to write the trace
** and a prompt to preface each trace message.  Tracing is turned off
** by making either argument NULL 
**
** Inputs:
** <ul>
** <li> A FILE* to which trace output should be written.
**      If NULL, then tracing is turned off.
** <li> A prefix string written at the beginning of every
**      line of trace output.  If NULL, then tracing is
**      turned off.
** </ul>
**
** Outputs:
** None.
*/
void ParseTrace(FILE *TraceFILE, char *zTracePrompt){
  yyTraceFILE = TraceFILE;
  yyTracePrompt = zTracePrompt;
  if( yyTraceFILE==0 ) yyTracePrompt = 0;
  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
}
#endif /* NDEBUG */

#ifndef NDEBUG
/* For tracing shifts, the names of all terminals and nonterminals
** are required.  The following table supplies these names */
static const char *const yyTokenName[] = { 
%%
};
#endif /* NDEBUG */

#ifndef NDEBUG
/* For tracing reduce actions, the names of all rules are required.
*/
static const char *const yyRuleName[] = {
%%
};
#endif /* NDEBUG */


#if YYSTACKDEPTH<=0
/*
** Try to increase the size of the parser stack.
*/
static void yyGrowStack(yyParser *p){
  int newSize;
  yyStackEntry *pNew;

  newSize = p->yystksz*2 + 100;
  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  if( pNew ){
    p->yystack = pNew;
    p->yystksz = newSize;
#ifndef NDEBUG
    if( yyTraceFILE ){
      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
              yyTracePrompt, p->yystksz);
    }
#endif
  }
}
#endif

/* 
** This function allocates a new parser.
** The only argument is a pointer to a function which works like
** malloc.
**
** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser.  This pointer is used in subsequent calls
** to Parse and ParseFree.
*/
void *ParseAlloc(void *(*mallocProc)(size_t)){
  yyParser *pParser;
  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  if( pParser ){
    pParser->yyidx = -1;
#ifdef YYTRACKMAXSTACKDEPTH
    pParser->yyidxMax = 0;
#endif
#if YYSTACKDEPTH<=0
    pParser->yystack = NULL;
    pParser->yystksz = 0;
    yyGrowStack(pParser);
#endif
  }
  return pParser;
}

/* The following function deletes the value associated with a
** symbol.  The symbol can be either a terminal or nonterminal.
** "yymajor" is the symbol code, and "yypminor" is a pointer to
** the value.
*/
static void yy_destructor(
  yyParser *yypParser,    /* The parser */
  YYCODETYPE yymajor,     /* Type code for object to destroy */
  YYMINORTYPE *yypminor   /* The object to be destroyed */
){
  ParseARG_FETCH;
  switch( yymajor ){
    /* Here is inserted the actions which take place when a
    ** terminal or non-terminal is destroyed.  This can happen
    ** when the symbol is popped from the stack during a
    ** reduce or during error processing or when a parser is 
    ** being destroyed before it is finished parsing.
    **
    ** Note: during a reduce, the only symbols destroyed are those
    ** which appear on the RHS of the rule, but which are not used
    ** inside the C code.
    */
%%
    default:  break;   /* If no destructor action specified: do nothing */
  }
}

/*
** Pop the parser's stack once.
**
** If there is a destructor routine associated with the token which
** is popped from the stack, then call it.
**
** Return the major token number for the symbol popped.
*/
static int yy_pop_parser_stack(yyParser *pParser){
  YYCODETYPE yymajor;
  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];

  if( pParser->yyidx<0 ) return 0;
#ifndef NDEBUG
  if( yyTraceFILE && pParser->yyidx>=0 ){
    fprintf(yyTraceFILE,"%sPopping %s\n",
      yyTracePrompt,
      yyTokenName[yytos->major]);
  }
#endif
  yymajor = yytos->major;
  yy_destructor(pParser, yymajor, &yytos->minor);
  pParser->yyidx--;
  return yymajor;
}

/* 
** Deallocate and destroy a parser.  Destructors are all called for
** all stack elements before shutting the parser down.
**
** Inputs:
** <ul>
** <li>  A pointer to the parser.  This should be a pointer
**       obtained from ParseAlloc.
** <li>  A pointer to a function used to reclaim memory obtained
**       from malloc.
** </ul>
*/
void ParseFree(
  void *p,                    /* The parser to be deleted */
  void (*freeProc)(void*)     /* Function used to reclaim memory */
){
  yyParser *pParser = (yyParser*)p;
  if( pParser==0 ) return;
  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
  free(pParser->yystack);
#endif
  (*freeProc)((void*)pParser);
}

/*
** Return the peak depth of the stack for a parser.
*/
#ifdef YYTRACKMAXSTACKDEPTH
int ParseStackPeak(void *p){
  yyParser *pParser = (yyParser*)p;
  return pParser->yyidxMax;
}
#endif

/*
** Find the appropriate action for a parser given the terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead.  If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_shift_action(
  yyParser *pParser,        /* The parser */
  YYCODETYPE iLookAhead     /* The look-ahead token */
){
  int i;
  int stateno = pParser->yystack[pParser->yyidx].stateno;
 
  if( stateno>YY_SHIFT_COUNT
   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
    return yy_default[stateno];
  }
  assert( iLookAhead!=YYNOCODE );
  i += iLookAhead;
  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
    if( iLookAhead>0 ){
#ifdef YYFALLBACK
      YYCODETYPE iFallback;            /* Fallback token */
      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
             && (iFallback = yyFallback[iLookAhead])!=0 ){
#ifndef NDEBUG
        if( yyTraceFILE ){
          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
        }
#endif
        return yy_find_shift_action(pParser, iFallback);
      }
#endif
#ifdef YYWILDCARD
      {
        int j = i - iLookAhead + YYWILDCARD;
        if( 
#if YY_SHIFT_MIN+YYWILDCARD<0
          j>=0 &&
#endif
#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
          j<YY_ACTTAB_COUNT &&
#endif
          yy_lookahead[j]==YYWILDCARD
        ){
#ifndef NDEBUG
          if( yyTraceFILE ){
            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
          }
#endif /* NDEBUG */
          return yy_action[j];
        }
      }
#endif /* YYWILDCARD */
    }
    return yy_default[stateno];
  }else{
    return yy_action[i];
  }
}

/*
** Find the appropriate action for a parser given the non-terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead.  If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_reduce_action(
  int stateno,              /* Current state number */
  YYCODETYPE iLookAhead     /* The look-ahead token */
){
  int i;
#ifdef YYERRORSYMBOL
  if( stateno>YY_REDUCE_COUNT ){
    return yy_default[stateno];
  }
#else
  assert( stateno<=YY_REDUCE_COUNT );
#endif
  i = yy_reduce_ofst[stateno];
  assert( i!=YY_REDUCE_USE_DFLT );
  assert( iLookAhead!=YYNOCODE );
  i += iLookAhead;
#ifdef YYERRORSYMBOL
  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
    return yy_default[stateno];
  }
#else
  assert( i>=0 && i<YY_ACTTAB_COUNT );
  assert( yy_lookahead[i]==iLookAhead );
#endif
  return yy_action[i];
}

/*
** The following routine is called if the stack overflows.
*/
static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   ParseARG_FETCH;
   yypParser->yyidx--;
#ifndef NDEBUG
   if( yyTraceFILE ){
     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   }
#endif
   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   /* Here code is inserted which will execute if the parser
   ** stack every overflows */
%%
   ParseARG_STORE; /* Suppress warning about unused %extra_argument var */
}

/*
** Perform a shift action.
*/
static void yy_shift(
  yyParser *yypParser,          /* The parser to be shifted */
  int yyNewState,               /* The new state to shift in */
  int yyMajor,                  /* The major token to shift in */
  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
){
  yyStackEntry *yytos;
  yypParser->yyidx++;
#ifdef YYTRACKMAXSTACKDEPTH
  if( yypParser->yyidx>yypParser->yyidxMax ){
    yypParser->yyidxMax = yypParser->yyidx;
  }
#endif
#if YYSTACKDEPTH>0 
  if( yypParser->yyidx>=YYSTACKDEPTH ){
    yyStackOverflow(yypParser, yypMinor);
    return;
  }
#else
  if( yypParser->yyidx>=yypParser->yystksz ){
    yyGrowStack(yypParser);
    if( yypParser->yyidx>=yypParser->yystksz ){
      yyStackOverflow(yypParser, yypMinor);
      return;
    }
  }
#endif
  yytos = &yypParser->yystack[yypParser->yyidx];
  yytos->stateno = (YYACTIONTYPE)yyNewState;
  yytos->major = (YYCODETYPE)yyMajor;
  yytos->minor = *yypMinor;
#ifndef NDEBUG
  if( yyTraceFILE && yypParser->yyidx>0 ){
    int i;
    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
    for(i=1; i<=yypParser->yyidx; i++)
      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
    fprintf(yyTraceFILE,"\n");
  }
#endif
}

/* The following table contains information about every rule that
** is used during the reduce.
*/
static const struct {
  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
} yyRuleInfo[] = {
%%
};

static void yy_accept(yyParser*);  /* Forward Declaration */

/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
*/
static void yy_reduce(
  yyParser *yypParser,         /* The parser */
  int yyruleno                 /* Number of the rule by which to reduce */
){
  int yygoto;                     /* The next state */
  int yyact;                      /* The next action */
  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
  yyStackEntry *yymsp;            /* The top of the parser's stack */
  int yysize;                     /* Amount to pop the stack */
  ParseARG_FETCH;
  yymsp = &yypParser->yystack[yypParser->yyidx];
#ifndef NDEBUG
  if( yyTraceFILE && yyruleno>=0 
        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
      yyRuleName[yyruleno]);
  }
#endif /* NDEBUG */

  /* Silence complaints from purify about yygotominor being uninitialized
  ** in some cases when it is copied into the stack after the following
  ** switch.  yygotominor is uninitialized when a rule reduces that does
  ** not set the value of its left-hand side nonterminal.  Leaving the
  ** value of the nonterminal uninitialized is utterly harmless as long
  ** as the value is never used.  So really the only thing this code
  ** accomplishes is to quieten purify.  
  **
  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
  ** without this code, their parser segfaults.  I'm not sure what there
  ** parser is doing to make this happen.  This is the second bug report
  ** from wireshark this week.  Clearly they are stressing Lemon in ways
  ** that it has not been previously stressed...  (SQLite ticket #2172)
  */
  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  yygotominor = yyzerominor;


  switch( yyruleno ){
  /* Beginning here are the reduction cases.  A typical example
  ** follows:
  **   case 0:
  **  #line <lineno> <grammarfile>
  **     { ... }           // User supplied code
  **  #line <lineno> <thisfile>
  **     break;
  */
%%
  };
  yygoto = yyRuleInfo[yyruleno].lhs;
  yysize = yyRuleInfo[yyruleno].nrhs;
  yypParser->yyidx -= yysize;
  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  if( yyact < YYNSTATE ){
#ifdef NDEBUG
    /* If we are not debugging and the reduce action popped at least
    ** one element off the stack, then we can push the new element back
    ** onto the stack here, and skip the stack overflow test in yy_shift().
    ** That gives a significant speed improvement. */
    if( yysize ){
      yypParser->yyidx++;
      yymsp -= yysize-1;
      yymsp->stateno = (YYACTIONTYPE)yyact;
      yymsp->major = (YYCODETYPE)yygoto;
      yymsp->minor = yygotominor;
    }else
#endif
    {
      yy_shift(yypParser,yyact,yygoto,&yygotominor);
    }
  }else{
    assert( yyact == YYNSTATE + YYNRULE + 1 );
    yy_accept(yypParser);
  }
}

/*
** The following code executes when the parse fails
*/
#ifndef YYNOERRORRECOVERY
static void yy_parse_failed(
  yyParser *yypParser           /* The parser */
){
  ParseARG_FETCH;
#ifndef NDEBUG
  if( yyTraceFILE ){
    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  }
#endif
  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  /* Here code is inserted which will be executed whenever the
  ** parser fails */
%%
  ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
#endif /* YYNOERRORRECOVERY */

/*
** The following code executes when a syntax error first occurs.
*/
static void yy_syntax_error(
  yyParser *yypParser,           /* The parser */
  int yymajor,                   /* The major type of the error token */
  YYMINORTYPE yyminor            /* The minor type of the error token */
){
  ParseARG_FETCH;
#define TOKEN (yyminor.yy0)
%%
  ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}

/*
** The following is executed when the parser accepts
*/
static void yy_accept(
  yyParser *yypParser           /* The parser */
){
  ParseARG_FETCH;
#ifndef NDEBUG
  if( yyTraceFILE ){
    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  }
#endif
  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  /* Here code is inserted which will be executed whenever the
  ** parser accepts */
%%
  ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}

/* The main parser program.
** The first argument is a pointer to a structure obtained from
** "ParseAlloc" which describes the current state of the parser.
** The second argument is the major token number.  The third is
** the minor token.  The fourth optional argument is whatever the
** user wants (and specified in the grammar) and is available for
** use by the action routines.
**
** Inputs:
** <ul>
** <li> A pointer to the parser (an opaque structure.)
** <li> The major token number.
** <li> The minor token number.
** <li> An option argument of a grammar-specified type.
** </ul>
**
** Outputs:
** None.
*/
void Parse(
  void *yyp,                   /* The parser */
  int yymajor,                 /* The major token code number */
  ParseTOKENTYPE yyminor       /* The value for the token */
  ParseARG_PDECL               /* Optional %extra_argument parameter */
){
  YYMINORTYPE yyminorunion;
  int yyact;            /* The parser action. */
  int yyendofinput;     /* True if we are at the end of input */
#ifdef YYERRORSYMBOL
  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
#endif
  yyParser *yypParser;  /* The parser */

  /* (re)initialize the parser, if necessary */
  yypParser = (yyParser*)yyp;
  if( yypParser->yyidx<0 ){
#if YYSTACKDEPTH<=0
    if( yypParser->yystksz <=0 ){
      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
      yyminorunion = yyzerominor;
      yyStackOverflow(yypParser, &yyminorunion);
      return;
    }
#endif
    yypParser->yyidx = 0;
    yypParser->yyerrcnt = -1;
    yypParser->yystack[0].stateno = 0;
    yypParser->yystack[0].major = 0;
  }
  yyminorunion.yy0 = yyminor;
  yyendofinput = (yymajor==0);
  ParseARG_STORE;

#ifndef NDEBUG
  if( yyTraceFILE ){
    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  }
#endif

  do{
    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
    if( yyact<YYNSTATE ){
      assert( !yyendofinput );  /* Impossible to shift the $ token */
      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
      yypParser->yyerrcnt--;
      yymajor = YYNOCODE;
    }else if( yyact < YYNSTATE + YYNRULE ){
      yy_reduce(yypParser,yyact-YYNSTATE);
    }else{
      assert( yyact == YY_ERROR_ACTION );
#ifdef YYERRORSYMBOL
      int yymx;
#endif
#ifndef NDEBUG
      if( yyTraceFILE ){
        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
      }
#endif
#ifdef YYERRORSYMBOL
      /* A syntax error has occurred.
      ** The response to an error depends upon whether or not the
      ** grammar defines an error token "ERROR".  
      **
      ** This is what we do if the grammar does define ERROR:
      **
      **  * Call the %syntax_error function.
      **
      **  * Begin popping the stack until we enter a state where
      **    it is legal to shift the error symbol, then shift
      **    the error symbol.
      **
      **  * Set the error count to three.
      **
      **  * Begin accepting and shifting new tokens.  No new error
      **    processing will occur until three tokens have been
      **    shifted successfully.
      **
      */
      if( yypParser->yyerrcnt<0 ){
        yy_syntax_error(yypParser,yymajor,yyminorunion);
      }
      yymx = yypParser->yystack[yypParser->yyidx].major;
      if( yymx==YYERRORSYMBOL || yyerrorhit ){
#ifndef NDEBUG
        if( yyTraceFILE ){
          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
             yyTracePrompt,yyTokenName[yymajor]);
        }
#endif
        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
        yymajor = YYNOCODE;
      }else{
         while(
          yypParser->yyidx >= 0 &&
          yymx != YYERRORSYMBOL &&
          (yyact = yy_find_reduce_action(
                        yypParser->yystack[yypParser->yyidx].stateno,
                        YYERRORSYMBOL)) >= YYNSTATE
        ){
          yy_pop_parser_stack(yypParser);
        }
        if( yypParser->yyidx < 0 || yymajor==0 ){
          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
          yy_parse_failed(yypParser);
          yymajor = YYNOCODE;
        }else if( yymx!=YYERRORSYMBOL ){
          YYMINORTYPE u2;
          u2.YYERRSYMDT = 0;
          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
        }
      }
      yypParser->yyerrcnt = 3;
      yyerrorhit = 1;
#elif defined(YYNOERRORRECOVERY)
      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
      ** do any kind of error recovery.  Instead, simply invoke the syntax
      ** error routine and continue going as if nothing had happened.
      **
      ** Applications can set this macro (for example inside %include) if
      ** they intend to abandon the parse upon the first syntax error seen.
      */
      yy_syntax_error(yypParser,yymajor,yyminorunion);
      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
      yymajor = YYNOCODE;
      
#else  /* YYERRORSYMBOL is not defined */
      /* This is what we do if the grammar does not define ERROR:
      **
      **  * Report an error message, and throw away the input token.
      **
      **  * If the input token is $, then fail the parse.
      **
      ** As before, subsequent error messages are suppressed until
      ** three input tokens have been successfully shifted.
      */
      if( yypParser->yyerrcnt<=0 ){
        yy_syntax_error(yypParser,yymajor,yyminorunion);
      }
      yypParser->yyerrcnt = 3;
      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
      if( yyendofinput ){
        yy_parse_failed(yypParser);
      }
      yymajor = YYNOCODE;
#endif
    }
  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  return;
}

Added tool/mkkeywordhash.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*
** Compile and run this standalone program in order to generate code that
** implements a function that will translate alphabetic identifiers into
** parser token codes.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

/*
** A header comment placed at the beginning of generated code.
*/
static const char zHdr[] = 
  "/***** This file contains automatically generated code ******\n"
  "**\n"
  "** The code in this file has been automatically generated by\n"
  "**\n"
  "**   sqlite/tool/mkkeywordhash.c\n"
  "**\n"
  "** The code in this file implements a function that determines whether\n"
  "** or not a given identifier is really an SQL keyword.  The same thing\n"
  "** might be implemented more directly using a hand-written hash table.\n"
  "** But by using this automatically generated code, the size of the code\n"
  "** is substantially reduced.  This is important for embedded applications\n"
  "** on platforms with limited memory.\n"
  "*/\n"
;

/*
** All the keywords of the SQL language are stored in a hash
** table composed of instances of the following structure.
*/
typedef struct Keyword Keyword;
struct Keyword {
  char *zName;         /* The keyword name */
  char *zTokenType;    /* Token value for this keyword */
  int mask;            /* Code this keyword if non-zero */
  int id;              /* Unique ID for this record */
  int hash;            /* Hash on the keyword */
  int offset;          /* Offset to start of name string */
  int len;             /* Length of this keyword, not counting final \000 */
  int prefix;          /* Number of characters in prefix */
  int longestSuffix;   /* Longest suffix that is a prefix on another word */
  int iNext;           /* Index in aKeywordTable[] of next with same hash */
  int substrId;        /* Id to another keyword this keyword is embedded in */
  int substrOffset;    /* Offset into substrId for start of this keyword */
  char zOrigName[20];  /* Original keyword name before processing */
};

/*
** Define masks used to determine which keywords are allowed
*/
#ifdef SQLITE_OMIT_ALTERTABLE
#  define ALTER      0
#else
#  define ALTER      0x00000001
#endif
#define ALWAYS       0x00000002
#ifdef SQLITE_OMIT_ANALYZE
#  define ANALYZE    0
#else
#  define ANALYZE    0x00000004
#endif
#ifdef SQLITE_OMIT_ATTACH
#  define ATTACH     0
#else
#  define ATTACH     0x00000008
#endif
#ifdef SQLITE_OMIT_AUTOINCREMENT
#  define AUTOINCR   0
#else
#  define AUTOINCR   0x00000010
#endif
#ifdef SQLITE_OMIT_CAST
#  define CAST       0
#else
#  define CAST       0x00000020
#endif
#ifdef SQLITE_OMIT_COMPOUND_SELECT
#  define COMPOUND   0
#else
#  define COMPOUND   0x00000040
#endif
#ifdef SQLITE_OMIT_CONFLICT_CLAUSE
#  define CONFLICT   0
#else
#  define CONFLICT   0x00000080
#endif
#ifdef SQLITE_OMIT_EXPLAIN
#  define EXPLAIN    0
#else
#  define EXPLAIN    0x00000100
#endif
#ifdef SQLITE_OMIT_FOREIGN_KEY
#  define FKEY       0
#else
#  define FKEY       0x00000200
#endif
#ifdef SQLITE_OMIT_PRAGMA
#  define PRAGMA     0
#else
#  define PRAGMA     0x00000400
#endif
#ifdef SQLITE_OMIT_REINDEX
#  define REINDEX    0
#else
#  define REINDEX    0x00000800
#endif
#ifdef SQLITE_OMIT_SUBQUERY
#  define SUBQUERY   0
#else
#  define SUBQUERY   0x00001000
#endif
#ifdef SQLITE_OMIT_TRIGGER
#  define TRIGGER    0
#else
#  define TRIGGER    0x00002000
#endif
#if defined(SQLITE_OMIT_AUTOVACUUM) && \
    (defined(SQLITE_OMIT_VACUUM) || defined(SQLITE_OMIT_ATTACH))
#  define VACUUM     0
#else
#  define VACUUM     0x00004000
#endif
#ifdef SQLITE_OMIT_VIEW
#  define VIEW       0
#else
#  define VIEW       0x00008000
#endif
#ifdef SQLITE_OMIT_VIRTUALTABLE
#  define VTAB       0
#else
#  define VTAB       0x00010000
#endif
#ifdef SQLITE_OMIT_AUTOVACUUM
#  define AUTOVACUUM 0
#else
#  define AUTOVACUUM 0x00020000
#endif

/*
** These are the keywords
*/
static Keyword aKeywordTable[] = {
  { "ABORT",            "TK_ABORT",        CONFLICT|TRIGGER       },
  { "ACTION",           "TK_ACTION",       FKEY                   },
  { "ADD",              "TK_ADD",          ALTER                  },
  { "AFTER",            "TK_AFTER",        TRIGGER                },
  { "ALL",              "TK_ALL",          ALWAYS                 },
  { "ALTER",            "TK_ALTER",        ALTER                  },
  { "ANALYZE",          "TK_ANALYZE",      ANALYZE                },
  { "AND",              "TK_AND",          ALWAYS                 },
  { "AS",               "TK_AS",           ALWAYS                 },
  { "ASC",              "TK_ASC",          ALWAYS                 },
  { "ATTACH",           "TK_ATTACH",       ATTACH                 },
  { "AUTOINCREMENT",    "TK_AUTOINCR",     AUTOINCR               },
  { "BEFORE",           "TK_BEFORE",       TRIGGER                },
  { "BEGIN",            "TK_BEGIN",        ALWAYS                 },
  { "BETWEEN",          "TK_BETWEEN",      ALWAYS                 },
  { "BY",               "TK_BY",           ALWAYS                 },
  { "CASCADE",          "TK_CASCADE",      FKEY                   },
  { "CASE",             "TK_CASE",         ALWAYS                 },
  { "CAST",             "TK_CAST",         CAST                   },
  { "CHECK",            "TK_CHECK",        ALWAYS                 },
  { "COLLATE",          "TK_COLLATE",      ALWAYS                 },
  { "COLUMN",           "TK_COLUMNKW",     ALTER                  },
  { "COMMIT",           "TK_COMMIT",       ALWAYS                 },
  { "CONFLICT",         "TK_CONFLICT",     CONFLICT               },
  { "CONSTRAINT",       "TK_CONSTRAINT",   ALWAYS                 },
  { "CREATE",           "TK_CREATE",       ALWAYS                 },
  { "CROSS",            "TK_JOIN_KW",      ALWAYS                 },
  { "CURRENT_DATE",     "TK_CTIME_KW",     ALWAYS                 },
  { "CURRENT_TIME",     "TK_CTIME_KW",     ALWAYS                 },
  { "CURRENT_TIMESTAMP","TK_CTIME_KW",     ALWAYS                 },
  { "DATABASE",         "TK_DATABASE",     ATTACH                 },
  { "DEFAULT",          "TK_DEFAULT",      ALWAYS                 },
  { "DEFERRED",         "TK_DEFERRED",     ALWAYS                 },
  { "DEFERRABLE",       "TK_DEFERRABLE",   FKEY                   },
  { "DELETE",           "TK_DELETE",       ALWAYS                 },
  { "DESC",             "TK_DESC",         ALWAYS                 },
  { "DETACH",           "TK_DETACH",       ATTACH                 },
  { "DISTINCT",         "TK_DISTINCT",     ALWAYS                 },
  { "DROP",             "TK_DROP",         ALWAYS                 },
  { "END",              "TK_END",          ALWAYS                 },
  { "EACH",             "TK_EACH",         TRIGGER                },
  { "ELSE",             "TK_ELSE",         ALWAYS                 },
  { "ESCAPE",           "TK_ESCAPE",       ALWAYS                 },
  { "EXCEPT",           "TK_EXCEPT",       COMPOUND               },
  { "EXCLUSIVE",        "TK_EXCLUSIVE",    ALWAYS                 },
  { "EXISTS",           "TK_EXISTS",       ALWAYS                 },
  { "EXPLAIN",          "TK_EXPLAIN",      EXPLAIN                },
  { "FAIL",             "TK_FAIL",         CONFLICT|TRIGGER       },
  { "FOR",              "TK_FOR",          TRIGGER                },
  { "FOREIGN",          "TK_FOREIGN",      FKEY                   },
  { "FROM",             "TK_FROM",         ALWAYS                 },
  { "FULL",             "TK_JOIN_KW",      ALWAYS                 },
  { "GLOB",             "TK_LIKE_KW",      ALWAYS                 },
  { "GROUP",            "TK_GROUP",        ALWAYS                 },
  { "HAVING",           "TK_HAVING",       ALWAYS                 },
  { "IF",               "TK_IF",           ALWAYS                 },
  { "IGNORE",           "TK_IGNORE",       CONFLICT|TRIGGER       },
  { "IMMEDIATE",        "TK_IMMEDIATE",    ALWAYS                 },
  { "IN",               "TK_IN",           ALWAYS                 },
  { "INDEX",            "TK_INDEX",        ALWAYS                 },
  { "INDEXED",          "TK_INDEXED",      ALWAYS                 },
  { "INITIALLY",        "TK_INITIALLY",    FKEY                   },
  { "INNER",            "TK_JOIN_KW",      ALWAYS                 },
  { "INSERT",           "TK_INSERT",       ALWAYS                 },
  { "INSTEAD",          "TK_INSTEAD",      TRIGGER                },
  { "INTERSECT",        "TK_INTERSECT",    COMPOUND               },
  { "INTO",             "TK_INTO",         ALWAYS                 },
  { "IS",               "TK_IS",           ALWAYS                 },
  { "ISNULL",           "TK_ISNULL",       ALWAYS                 },
  { "JOIN",             "TK_JOIN",         ALWAYS                 },
  { "KEY",              "TK_KEY",          ALWAYS                 },
  { "LEFT",             "TK_JOIN_KW",      ALWAYS                 },
  { "LIKE",             "TK_LIKE_KW",      ALWAYS                 },
  { "LIMIT",            "TK_LIMIT",        ALWAYS                 },
  { "MATCH",            "TK_MATCH",        ALWAYS                 },
  { "NATURAL",          "TK_JOIN_KW",      ALWAYS                 },
  { "NO",               "TK_NO",           FKEY                   },
  { "NOT",              "TK_NOT",          ALWAYS                 },
  { "NOTNULL",          "TK_NOTNULL",      ALWAYS                 },
  { "NULL",             "TK_NULL",         ALWAYS                 },
  { "OF",               "TK_OF",           ALWAYS                 },
  { "OFFSET",           "TK_OFFSET",       ALWAYS                 },
  { "ON",               "TK_ON",           ALWAYS                 },
  { "OR",               "TK_OR",           ALWAYS                 },
  { "ORDER",            "TK_ORDER",        ALWAYS                 },
  { "OUTER",            "TK_JOIN_KW",      ALWAYS                 },
  { "PLAN",             "TK_PLAN",         EXPLAIN                },
  { "PRAGMA",           "TK_PRAGMA",       PRAGMA                 },
  { "PRIMARY",          "TK_PRIMARY",      ALWAYS                 },
  { "QUERY",            "TK_QUERY",        EXPLAIN                },
  { "RAISE",            "TK_RAISE",        TRIGGER                },
  { "REFERENCES",       "TK_REFERENCES",   FKEY                   },
  { "REGEXP",           "TK_LIKE_KW",      ALWAYS                 },
  { "REINDEX",          "TK_REINDEX",      REINDEX                },
  { "RELEASE",          "TK_RELEASE",      ALWAYS                 },
  { "RENAME",           "TK_RENAME",       ALTER                  },
  { "REPLACE",          "TK_REPLACE",      CONFLICT               },
  { "RESTRICT",         "TK_RESTRICT",     FKEY                   },
  { "RIGHT",            "TK_JOIN_KW",      ALWAYS                 },
  { "ROLLBACK",         "TK_ROLLBACK",     ALWAYS                 },
  { "ROW",              "TK_ROW",          TRIGGER                },
  { "SAVEPOINT",        "TK_SAVEPOINT",    ALWAYS                 },
  { "SELECT",           "TK_SELECT",       ALWAYS                 },
  { "SET",              "TK_SET",          ALWAYS                 },
  { "TABLE",            "TK_TABLE",        ALWAYS                 },
  { "TEMP",             "TK_TEMP",         ALWAYS                 },
  { "TEMPORARY",        "TK_TEMP",         ALWAYS                 },
  { "THEN",             "TK_THEN",         ALWAYS                 },
  { "TO",               "TK_TO",           ALWAYS                 },
  { "TRANSACTION",      "TK_TRANSACTION",  ALWAYS                 },
  { "TRIGGER",          "TK_TRIGGER",      TRIGGER                },
  { "UNION",            "TK_UNION",        COMPOUND               },
  { "UNIQUE",           "TK_UNIQUE",       ALWAYS                 },
  { "UPDATE",           "TK_UPDATE",       ALWAYS                 },
  { "USING",            "TK_USING",        ALWAYS                 },
  { "VACUUM",           "TK_VACUUM",       VACUUM                 },
  { "VALUES",           "TK_VALUES",       ALWAYS                 },
  { "VIEW",             "TK_VIEW",         VIEW                   },
  { "VIRTUAL",          "TK_VIRTUAL",      VTAB                   },
  { "WHEN",             "TK_WHEN",         ALWAYS                 },
  { "WHERE",            "TK_WHERE",        ALWAYS                 },
};

/* Number of keywords */
static int nKeyword = (sizeof(aKeywordTable)/sizeof(aKeywordTable[0]));

/* An array to map all upper-case characters into their corresponding
** lower-case character. 
*/
const unsigned char sqlite3UpperToLower[] = {
      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
    252,253,254,255
};
#define UpperToLower sqlite3UpperToLower

/*
** Comparision function for two Keyword records
*/
static int keywordCompare1(const void *a, const void *b){
  const Keyword *pA = (Keyword*)a;
  const Keyword *pB = (Keyword*)b;
  int n = pA->len - pB->len;
  if( n==0 ){
    n = strcmp(pA->zName, pB->zName);
  }
  assert( n!=0 );
  return n;
}
static int keywordCompare2(const void *a, const void *b){
  const Keyword *pA = (Keyword*)a;
  const Keyword *pB = (Keyword*)b;
  int n = pB->longestSuffix - pA->longestSuffix;
  if( n==0 ){
    n = strcmp(pA->zName, pB->zName);
  }
  assert( n!=0 );
  return n;
}
static int keywordCompare3(const void *a, const void *b){
  const Keyword *pA = (Keyword*)a;
  const Keyword *pB = (Keyword*)b;
  int n = pA->offset - pB->offset;
  if( n==0 ) n = pB->id - pA->id;
  assert( n!=0 );
  return n;
}

/*
** Return a KeywordTable entry with the given id
*/
static Keyword *findById(int id){
  int i;
  for(i=0; i<nKeyword; i++){
    if( aKeywordTable[i].id==id ) break;
  }
  return &aKeywordTable[i];
}

/*
** This routine does the work.  The generated code is printed on standard
** output.
*/
int main(int argc, char **argv){
  int i, j, k, h;
  int bestSize, bestCount;
  int count;
  int nChar;
  int totalLen = 0;
  int aHash[1000];  /* 1000 is much bigger than nKeyword */
  char zText[2000];

  /* Remove entries from the list of keywords that have mask==0 */
  for(i=j=0; i<nKeyword; i++){
    if( aKeywordTable[i].mask==0 ) continue;
    if( j<i ){
      aKeywordTable[j] = aKeywordTable[i];
    }
    j++;
  }
  nKeyword = j;

  /* Fill in the lengths of strings and hashes for all entries. */
  for(i=0; i<nKeyword; i++){
    Keyword *p = &aKeywordTable[i];
    p->len = strlen(p->zName);
    assert( p->len<sizeof(p->zOrigName) );
    strcpy(p->zOrigName, p->zName);
    totalLen += p->len;
    p->hash = (UpperToLower[(int)p->zName[0]]*4) ^
              (UpperToLower[(int)p->zName[p->len-1]]*3) ^ p->len;
    p->id = i+1;
  }

  /* Sort the table from shortest to longest keyword */
  qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare1);

  /* Look for short keywords embedded in longer keywords */
  for(i=nKeyword-2; i>=0; i--){
    Keyword *p = &aKeywordTable[i];
    for(j=nKeyword-1; j>i && p->substrId==0; j--){
      Keyword *pOther = &aKeywordTable[j];
      if( pOther->substrId ) continue;
      if( pOther->len<=p->len ) continue;
      for(k=0; k<=pOther->len-p->len; k++){
        if( memcmp(p->zName, &pOther->zName[k], p->len)==0 ){
          p->substrId = pOther->id;
          p->substrOffset = k;
          break;
        }
      }
    }
  }

  /* Compute the longestSuffix value for every word */
  for(i=0; i<nKeyword; i++){
    Keyword *p = &aKeywordTable[i];
    if( p->substrId ) continue;
    for(j=0; j<nKeyword; j++){
      Keyword *pOther;
      if( j==i ) continue;
      pOther = &aKeywordTable[j];
      if( pOther->substrId ) continue;
      for(k=p->longestSuffix+1; k<p->len && k<pOther->len; k++){
        if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){
          p->longestSuffix = k;
        }
      }
    }
  }

  /* Sort the table into reverse order by length */
  qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare2);

  /* Fill in the offset for all entries */
  nChar = 0;
  for(i=0; i<nKeyword; i++){
    Keyword *p = &aKeywordTable[i];
    if( p->offset>0 || p->substrId ) continue;
    p->offset = nChar;
    nChar += p->len;
    for(k=p->len-1; k>=1; k--){
      for(j=i+1; j<nKeyword; j++){
        Keyword *pOther = &aKeywordTable[j];
        if( pOther->offset>0 || pOther->substrId ) continue;
        if( pOther->len<=k ) continue;
        if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){
          p = pOther;
          p->offset = nChar - k;
          nChar = p->offset + p->len;
          p->zName += k;
          p->len -= k;
          p->prefix = k;
          j = i;
          k = p->len;
        }
      }
    }
  }
  for(i=0; i<nKeyword; i++){
    Keyword *p = &aKeywordTable[i];
    if( p->substrId ){
      p->offset = findById(p->substrId)->offset + p->substrOffset;
    }
  }

  /* Sort the table by offset */
  qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare3);

  /* Figure out how big to make the hash table in order to minimize the
  ** number of collisions */
  bestSize = nKeyword;
  bestCount = nKeyword*nKeyword;
  for(i=nKeyword/2; i<=2*nKeyword; i++){
    for(j=0; j<i; j++) aHash[j] = 0;
    for(j=0; j<nKeyword; j++){
      h = aKeywordTable[j].hash % i;
      aHash[h] *= 2;
      aHash[h]++;
    }
    for(j=count=0; j<i; j++) count += aHash[j];
    if( count<bestCount ){
      bestCount = count;
      bestSize = i;
    }
  }

  /* Compute the hash */
  for(i=0; i<bestSize; i++) aHash[i] = 0;
  for(i=0; i<nKeyword; i++){
    h = aKeywordTable[i].hash % bestSize;
    aKeywordTable[i].iNext = aHash[h];
    aHash[h] = i+1;
  }

  /* Begin generating code */
  printf("%s", zHdr);
  printf("/* Hash score: %d */\n", bestCount);
  printf("static int keywordCode(const char *z, int n){\n");
  printf("  /* zText[] encodes %d bytes of keywords in %d bytes */\n",
          totalLen + nKeyword, nChar+1 );
  for(i=j=k=0; i<nKeyword; i++){
    Keyword *p = &aKeywordTable[i];
    if( p->substrId ) continue;
    memcpy(&zText[k], p->zName, p->len);
    k += p->len;
    if( j+p->len>70 ){
      printf("%*s */\n", 74-j, "");
      j = 0;
    }
    if( j==0 ){
      printf("  /*   ");
      j = 8;
    }
    printf("%s", p->zName);
    j += p->len;
  }
  if( j>0 ){
    printf("%*s */\n", 74-j, "");
  }
  printf("  static const char zText[%d] = {\n", nChar);
  zText[nChar] = 0;
  for(i=j=0; i<k; i++){
    if( j==0 ){
      printf("    ");
    }
    if( zText[i]==0 ){
      printf("0");
    }else{
      printf("'%c',", zText[i]);
    }
    j += 4;
    if( j>68 ){
      printf("\n");
      j = 0;
    }
  }
  if( j>0 ) printf("\n");
  printf("  };\n");

  printf("  static const unsigned char aHash[%d] = {\n", bestSize);
  for(i=j=0; i<bestSize; i++){
    if( j==0 ) printf("    ");
    printf(" %3d,", aHash[i]);
    j++;
    if( j>12 ){
      printf("\n");
      j = 0;
    }
  }
  printf("%s  };\n", j==0 ? "" : "\n");    

  printf("  static const unsigned char aNext[%d] = {\n", nKeyword);
  for(i=j=0; i<nKeyword; i++){
    if( j==0 ) printf("    ");
    printf(" %3d,", aKeywordTable[i].iNext);
    j++;
    if( j>12 ){
      printf("\n");
      j = 0;
    }
  }
  printf("%s  };\n", j==0 ? "" : "\n");    

  printf("  static const unsigned char aLen[%d] = {\n", nKeyword);
  for(i=j=0; i<nKeyword; i++){
    if( j==0 ) printf("    ");
    printf(" %3d,", aKeywordTable[i].len+aKeywordTable[i].prefix);
    j++;
    if( j>12 ){
      printf("\n");
      j = 0;
    }
  }
  printf("%s  };\n", j==0 ? "" : "\n");    

  printf("  static const unsigned short int aOffset[%d] = {\n", nKeyword);
  for(i=j=0; i<nKeyword; i++){
    if( j==0 ) printf("    ");
    printf(" %3d,", aKeywordTable[i].offset);
    j++;
    if( j>12 ){
      printf("\n");
      j = 0;
    }
  }
  printf("%s  };\n", j==0 ? "" : "\n");

  printf("  static const unsigned char aCode[%d] = {\n", nKeyword);
  for(i=j=0; i<nKeyword; i++){
    char *zToken = aKeywordTable[i].zTokenType;
    if( j==0 ) printf("    ");
    printf("%s,%*s", zToken, (int)(14-strlen(zToken)), "");
    j++;
    if( j>=5 ){
      printf("\n");
      j = 0;
    }
  }
  printf("%s  };\n", j==0 ? "" : "\n");

  printf("  int h, i;\n");
  printf("  if( n<2 ) return TK_ID;\n");
  printf("  h = ((charMap(z[0])*4) ^\n"
         "      (charMap(z[n-1])*3) ^\n"
         "      n) %% %d;\n", bestSize);
  printf("  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){\n");
  printf("    if( aLen[i]==n &&"
                   " sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){\n");
  for(i=0; i<nKeyword; i++){
    printf("      testcase( i==%d ); /* %s */\n",
           i, aKeywordTable[i].zOrigName);
  }
  printf("      return aCode[i];\n");
  printf("    }\n");
  printf("  }\n");
  printf("  return TK_ID;\n");
  printf("}\n");
  printf("int sqlite3KeywordCode(const unsigned char *z, int n){\n");
  printf("  return keywordCode((char*)z, n);\n");
  printf("}\n");

  return 0;
}

Added tool/mkopts.tcl.







































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/tclsh
#
# This script is used to generate the array of strings and the enum
# that appear at the beginning of the C code implementation of a
# a TCL command and that define the available subcommands for that
# TCL command.

set prefix {}
while {![eof stdin]} {
  set line [gets stdin]
  if {$line==""} continue
  regsub -all "\[ \t\n,\]+" [string trim $line] { } line
  foreach token [split $line { }] {
    if {![regexp {(([a-zA-Z]+)_)?([_a-zA-Z]+)} $token all px p2 name]} continue
    lappend namelist [string tolower $name]
    if {$px!=""} {set prefix $p2}
  }
}

puts "  static const char *${prefix}_strs\[\] = \173"
set col 0
proc put_item x {
  global col
  if {$col==0} {puts -nonewline "   "}
  if {$col<2} {
    puts -nonewline [format " %-21s" $x]
    incr col
  } else {
    puts $x
    set col 0
  }
}
proc finalize {} {
  global col
  if {$col>0} {puts {}}
  set col 0
}

foreach name [lsort $namelist] {
  put_item \"$name\",
}
put_item 0
finalize
puts "  \175;"
puts "  enum ${prefix}_enum \173"
foreach name [lsort $namelist] {
  regsub -all {@} $name {} name
  put_item ${prefix}_[string toupper $name],
}
finalize
puts "  \175;"

Added tool/mkspeedsql.tcl.



























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# 2008 October 9
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#*************************************************************************
# This file generates SQL text used for performance testing.
#
# $Id: mkspeedsql.tcl,v 1.1 2008/10/09 17:57:34 drh Exp $
#

# Set a uniform random seed
expr srand(0)

# The number_name procedure below converts its argment (an integer)
# into a string which is the English-language name for that number.
#
# Example:
#
#     puts [number_name 123]   ->  "one hundred twenty three"
#
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}

# Create a database schema.
#
puts {
  PRAGMA page_size=1024;
  PRAGMA cache_size=8192;
  PRAGMA locking_mode=EXCLUSIVE;
  CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
  CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT);
  CREATE INDEX i2a ON t2(a);
  CREATE INDEX i2b ON t2(b);
  SELECT name FROM sqlite_master ORDER BY 1;
}


# 50000 INSERTs on an unindexed table
#
set t1c_list {}
puts {BEGIN;}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  set x [number_name $r]
  lappend t1c_list $x
  puts "INSERT INTO t1 VALUES($i,$r,'$x');"
}
puts {COMMIT;}

# 50000 INSERTs on an indexed table
#
puts {BEGIN;}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');"
}
puts {COMMIT;}


# 50 SELECTs on an integer comparison.  There is no index so
# a full table scan is required.
#
for {set i 0} {$i<50} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  puts "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}

# 50 SELECTs on an LIKE comparison.  There is no index so a full
# table scan is required.
#
for {set i 0} {$i<50} {incr i} {
  puts "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';"
}

# Create indices
#
puts {BEGIN;}
puts {
  CREATE INDEX i1a ON t1(a);
  CREATE INDEX i1b ON t1(b);
  CREATE INDEX i1c ON t1(c);
}
puts {COMMIT;}

# 5000 SELECTs on an integer comparison where the integer is
# indexed.
#
set sql {}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  puts "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;"
}

# 100000 random SELECTs against rowid.
#
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  puts "SELECT c FROM t1 WHERE rowid=$id;"
}

# 100000 random SELECTs against a unique indexed column.
#
for {set i 1} {$i<=100000} {incr i} {
  set id [expr {int(rand()*50000)+1}]
  puts "SELECT c FROM t1 WHERE a=$id;"
}

# 50000 random SELECTs against an indexed column text column
#
set nt1c [llength $t1c_list]
for {set i 0} {$i<50000} {incr i} {
  set r [expr {int(rand()*$nt1c)}]
  set c [lindex $t1c_list $i]
  puts "SELECT c FROM t1 WHERE c='$c';"
}


# Vacuum
puts {VACUUM;}

# 5000 updates of ranges where the field being compared is indexed.
#
puts {BEGIN;}
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*2}]
  set upr [expr {($i+1)*2}]
  puts "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;"
}
puts {COMMIT;}

# 50000 single-row updates.  An index is used to find the row quickly.
#
puts {BEGIN;}
for {set i 0} {$i<50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts "UPDATE t1 SET b=$r WHERE a=$i;"
}
puts {COMMIT;}

# 1 big text update that touches every row in the table.
#
puts {
  UPDATE t1 SET c=a;
}

# Many individual text updates.  Each row in the table is
# touched through an index.
#
puts {BEGIN;}
for {set i 1} {$i<=50000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;"
}
puts {COMMIT;}

# Delete all content in a table.
#
puts {DELETE FROM t1;}

# Copy one table into another
#
puts {INSERT INTO t1 SELECT * FROM t2;}

# Delete all content in a table, one row at a time.
#
puts {DELETE FROM t1 WHERE 1;}

# Refill the table yet again
#
puts {INSERT INTO t1 SELECT * FROM t2;}

# Drop the table and recreate it without its indices.
#
puts {BEGIN;}
puts {
   DROP TABLE t1;
   CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT);
}
puts {COMMIT;}

# Refill the table yet again.  This copy should be faster because
# there are no indices to deal with.
#
puts {INSERT INTO t1 SELECT * FROM t2;}

# Select 20000 rows from the table at random.
#
puts {
  SELECT rowid FROM t1 ORDER BY random() LIMIT 20000;
}

# Delete 20000 random rows from the table.
#
puts {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000);
}
puts {SELECT count(*) FROM t1;}
    
# Delete 20000 more rows at random from the table.
#
puts {
  DELETE FROM t1 WHERE rowid IN
    (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000);
}
puts {SELECT count(*) FROM t1;}

Added tool/mksqlite3c.tcl.





































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/tclsh
#
# To build a single huge source file holding all of SQLite (or at
# least the core components - the test harness, shell, and TCL 
# interface are omitted.) first do
#
#      make target_source
#
# The make target above moves all of the source code files into
# a subdirectory named "tsrc".  (This script expects to find the files
# there and will not work if they are not found.)  There are a few
# generated C code files that are also added to the tsrc directory.
# For example, the "parse.c" and "parse.h" files to implement the
# the parser are derived from "parse.y" using lemon.  And the 
# "keywordhash.h" files is generated by a program named "mkkeywordhash".
#
# After the "tsrc" directory has been created and populated, run
# this script:
#
#      tclsh mksqlite3c.tcl
#
# The amalgamated SQLite code will be written into sqlite3.c
#

# Begin by reading the "sqlite3.h" header file.  Extract the version number
# from in this file.  The versioon number is needed to generate the header
# comment of the amalgamation.
#
if {[lsearch $argv --nostatic]>=0} {
  set addstatic 0
} else {
  set addstatic 1
}
set in [open tsrc/sqlite3.h]
set cnt 0
set VERSION ?????
while {![eof $in]} {
  set line [gets $in]
  if {$line=="" && [eof $in]} break
  incr cnt
  regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION
}
close $in

# Open the output file and write a header comment at the beginning
# of the file.
#
set out [open sqlite3.c w]
set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1]
puts $out [subst \
{/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version $VERSION.  By combining all the individual C code files into this 
** single large file, the entire code can be compiled as a one translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% are more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other
** programs, you need this file and the "sqlite3.h" header file that defines
** the programming interface to the SQLite library.  (If you do not have 
** the "sqlite3.h" header file at hand, you will find a copy embedded within
** the text of this file.  Search for "Begin file sqlite3.h" to find the start
** of the embedded sqlite3.h header file.) Additional code files may be needed
** if you want a wrapper to interface SQLite with your choice of programming
** language. The code for the "sqlite3" command-line shell is also in a
** separate file. This file contains only code for the core SQLite library.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1}]
if {$addstatic} {
  puts $out \
{#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
#ifndef SQLITE_API
# define SQLITE_API
#endif}
}

# These are the header files used by SQLite.  The first time any of these 
# files are seen in a #include statement in the C code, include the complete
# text of the file in-line.  The file only needs to be included once.
#
foreach hdr {
   btree.h
   btreeInt.h
   fts3.h
   fts3_expr.h
   fts3_hash.h
   fts3_tokenizer.h
   hash.h
   hwtime.h
   keywordhash.h
   mutex.h
   opcodes.h
   os_common.h
   os.h
   os_os2.h
   pager.h
   parse.h
   pcache.h
   rtree.h
   sqlite3ext.h
   sqlite3.h
   sqliteicu.h
   sqliteInt.h
   sqliteLimit.h
   vdbe.h
   vdbeInt.h
} {
  set available_hdr($hdr) 1
}
set available_hdr(sqliteInt.h) 0

# 78 stars used for comment formatting.
set s78 \
{*****************************************************************************}

# Insert a comment into the code
#
proc section_comment {text} {
  global out s78
  set n [string length $text]
  set nstar [expr {60 - $n}]
  set stars [string range $s78 0 $nstar]
  puts $out "/************** $text $stars/"
}

# Read the source file named $filename and write it into the
# sqlite3.c output file.  If any #include statements are seen,
# process them approprately.
#
proc copy_file {filename} {
  global seen_hdr available_hdr out addstatic
  set tail [file tail $filename]
  section_comment "Begin file $tail"
  set in [open $filename r]
  set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+(sqlite3[_a-zA-Z0-9]+)(\[|;| =)}
  set declpattern {[a-zA-Z][a-zA-Z_0-9 ]+ \**(sqlite3[_a-zA-Z0-9]+)\(}
  if {[file extension $filename]==".h"} {
    set declpattern " *$declpattern"
  }
  set declpattern ^$declpattern
  while {![eof $in]} {
    set line [gets $in]
    if {[regexp {^\s*#\s*include\s+["<]([^">]+)[">]} $line all hdr]} {
      if {[info exists available_hdr($hdr)]} {
        if {$available_hdr($hdr)} {
          if {$hdr!="os_common.h" && $hdr!="hwtime.h"} {
            set available_hdr($hdr) 0
          }
          section_comment "Include $hdr in the middle of $tail"
          copy_file tsrc/$hdr
          section_comment "Continuing where we left off in $tail"
        }
      } elseif {![info exists seen_hdr($hdr)]} {
        set seen_hdr($hdr) 1
        puts $out $line
      }
    } elseif {[regexp {^#ifdef __cplusplus} $line]} {
      puts $out "#if 0"
    } elseif {[regexp {^#line} $line]} {
      # Skip #line directives.
    } elseif {$addstatic && ![regexp {^(static|typedef)} $line]} {
      regsub {^SQLITE_API } $line {} line
      if {[regexp $declpattern $line all funcname]} {
        # Add the SQLITE_PRIVATE or SQLITE_API keyword before functions.
        # so that linkage can be modified at compile-time.
        if {[regexp {^sqlite3_} $funcname]} {
          puts $out "SQLITE_API $line"
        } else {
          puts $out "SQLITE_PRIVATE $line"
        }
      } elseif {[regexp $varpattern $line all varname]} {
        # Add the SQLITE_PRIVATE before variable declarations or
        # definitions for internal use
        if {![regexp {^sqlite3_} $varname]} {
          regsub {^extern } $line {} line
          puts $out "SQLITE_PRIVATE $line"
        } else {
          if {[regexp {const char sqlite3_version\[\];} $line]} {
            set line {const char sqlite3_version[] = SQLITE_VERSION;}
          }
          regsub {^SQLITE_EXTERN } $line {} line
          puts $out "SQLITE_API $line"
        }
      } elseif {[regexp {^(SQLITE_EXTERN )?void \(\*sqlite3IoTrace\)} $line]} {
        regsub {^SQLITE_EXTERN } $line {} line
        puts $out "SQLITE_PRIVATE $line"
      } elseif {[regexp {^void \(\*sqlite3Os} $line]} {
        puts $out "SQLITE_PRIVATE $line"
      } else {
        puts $out $line
      }
    } else {
      puts $out $line
    }
  }
  close $in
  section_comment "End of $tail"
}


# Process the source files.  Process files containing commonly
# used subroutines first in order to help the compiler find
# inlining opportunities.
#
foreach file {
   sqliteInt.h

   global.c
   status.c
   date.c
   os.c

   fault.c
   mem0.c
   mem1.c
   mem2.c
   mem3.c
   mem5.c
   mutex.c
   mutex_noop.c
   mutex_os2.c
   mutex_unix.c
   mutex_w32.c
   malloc.c
   printf.c
   random.c
   utf.c
   util.c
   hash.c
   opcodes.c

   os_os2.c
   os_unix.c
   os_win.c

   bitvec.c
   pcache.c
   pcache1.c
   rowset.c
   pager.c

   btmutex.c
   btree.c
   backup.c

   vdbemem.c
   vdbeaux.c
   vdbeapi.c
   vdbe.c
   vdbeblob.c
   journal.c
   memjournal.c

   walker.c
   resolve.c
   expr.c
   alter.c
   analyze.c
   attach.c
   auth.c
   build.c
   callback.c
   delete.c
   func.c
   fkey.c
   insert.c
   legacy.c
   loadext.c
   pragma.c
   prepare.c
   select.c
   table.c
   trigger.c
   update.c
   vacuum.c
   vtab.c
   where.c

   parse.c

   tokenize.c
   complete.c

   main.c
   notify.c

   fts3.c
   fts3_expr.c
   fts3_hash.c
   fts3_porter.c
   fts3_tokenizer.c
   fts3_tokenizer1.c

   rtree.c
   icu.c
   fts3_icu.c
} {
  copy_file tsrc/$file
}

close $out

Added tool/mksqlite3h.tcl.

































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/tclsh
#
# This script constructs the "sqlite3.h" header file from the following
# sources:
#
#   1) The src/sqlite.h.in source file.  This is the template for sqlite3.h.
#   2) The VERSION file containing the current SQLite version number.
#   3) The manifest file from the fossil SCM.  This gives use the date.
#   4) The manifest.uuid file from the fossil SCM.  This gives the SHA1 hash.
#
# Run this script by specifying the root directory of the source tree
# on the command-line.
# 
# This script performs processing on src/sqlite.h.in. It:
#
#   1) Adds SQLITE_EXTERN in front of the declaration of global variables,
#   2) Adds SQLITE_API in front of the declaration of API functions,
#   3) Replaces the string --VERS-- with the current library version, 
#      formatted as a string (e.g. "3.6.17"), and
#   4) Replaces the string --VERSION-NUMBER-- with current library version,
#      formatted as an integer (e.g. "3006017").
#   5) Replaces the string --SOURCE-ID-- with the date and time and sha1 
#      hash of the fossil-scm manifest for the source tree.
#
# This script outputs to stdout.
#
# Example usage:
#
#   tclsh mksqlite3h.tcl ../sqlite >sqlite3.h
#


# Get the source tree root directory from the command-line
#
set TOP [lindex $argv 0]

# Get the SQLite version number (ex: 3.6.18) from the $TOP/VERSION file.
#
set in [open $TOP/VERSION]
set zVersion [string trim [read $in]]
close $in
set nVersion [eval format "%d%03d%03d" [split $zVersion .]]

# Get the fossil-scm version number from $TOP/manifest.uuid.
#
set in [open $TOP/manifest.uuid]
set zUuid [string trim [read $in]]
close $in

# Get the fossil-scm check-in date from the "D" card of $TOP/manifest.
#
set in [open $TOP/manifest]
set zDate {}
while {![eof $in]} {
  set line [gets $in]
  if {[regexp {^D (2.*[0-9])} $line all date]} {
    set zDate [string map {T { }} $date]
    break
  }
}
close $in

# Set up patterns for recognizing API declarations.
#
set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+sqlite3_[_a-zA-Z0-9]+(\[|;| =)}
set declpattern {^ *[a-zA-Z][a-zA-Z_0-9 ]+ \**sqlite3_[_a-zA-Z0-9]+\(}

# Process the  src/sqlite.h.in  file.
#
set in [open $TOP/src/sqlite.h.in]
while {![eof $in]} {

  set line [gets $in]

  regsub -- --VERS--           $line $zVersion line
  regsub -- --VERSION-NUMBER-- $line $nVersion line
  regsub -- --SOURCE-ID--      $line "$zDate $zUuid" line

  if {[regexp {define SQLITE_EXTERN extern} $line]} {
    puts $line
    puts [gets $in]
    puts ""
    puts "#ifndef SQLITE_API"
    puts "# define SQLITE_API"
    puts "#endif"
    set line ""
  }

  if {([regexp $varpattern $line] && ![regexp {^ *typedef} $line])
   || ([regexp $declpattern $line])
  } {
    set line "SQLITE_API $line"
  }
  puts $line
}
close $in

Added tool/mksqlite3internalh.tcl.





































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/tclsh
#
# To build a single huge source file holding all of SQLite (or at
# least the core components - the test harness, shell, and TCL 
# interface are omitted.) first do
#
#      make target_source
#
# The make target above moves all of the source code files into
# a subdirectory named "tsrc".  (This script expects to find the files
# there and will not work if they are not found.)  There are a few
# generated C code files that are also added to the tsrc directory.
# For example, the "parse.c" and "parse.h" files to implement the
# the parser are derived from "parse.y" using lemon.  And the 
# "keywordhash.h" files is generated by a program named "mkkeywordhash".
#
# After the "tsrc" directory has been created and populated, run
# this script:
#
#      tclsh mksqlite3c.tcl
#
# The amalgamated SQLite code will be written into sqlite3.c
#

# Begin by reading the "sqlite3.h" header file.  Count the number of lines
# in this file and extract the version number.  That information will be
# needed in order to generate the header of the amalgamation.
#
set in [open tsrc/sqlite3.h]
set cnt 0
set VERSION ?????
while {![eof $in]} {
  set line [gets $in]
  if {$line=="" && [eof $in]} break
  incr cnt
  regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION
}
close $in

# Open the output file and write a header comment at the beginning
# of the file.
#
set out [open sqlite3internal.h w]
set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1]
puts $out [subst \
{/******************************************************************************
** This file is an amalgamation of many private header files from SQLite
** version $VERSION. 
*/}]

# These are the header files used by SQLite.  The first time any of these 
# files are seen in a #include statement in the C code, include the complete
# text of the file in-line.  The file only needs to be included once.
#
foreach hdr {
   btree.h
   btreeInt.h
   hash.h
   hwtime.h
   keywordhash.h
   opcodes.h
   os_common.h
   os.h
   os_os2.h
   pager.h
   parse.h
   sqlite3ext.h
   sqlite3.h
   sqliteInt.h
   sqliteLimit.h
   vdbe.h
   vdbeInt.h
} {
  set available_hdr($hdr) 1
}

# 78 stars used for comment formatting.
set s78 \
{*****************************************************************************}

# Insert a comment into the code
#
proc section_comment {text} {
  global out s78
  set n [string length $text]
  set nstar [expr {60 - $n}]
  set stars [string range $s78 0 $nstar]
  puts $out "/************** $text $stars/"
}

# Read the source file named $filename and write it into the
# sqlite3.c output file.  If any #include statements are seen,
# process them approprately.
#
proc copy_file {filename} {
  global seen_hdr available_hdr out
  set tail [file tail $filename]
  section_comment "Begin file $tail"
  set in [open $filename r]
  while {![eof $in]} {
    set line [gets $in]
    if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} {
      if {[info exists available_hdr($hdr)]} {
        if {$available_hdr($hdr)} {
          section_comment "Include $hdr in the middle of $tail"
          copy_file tsrc/$hdr
          section_comment "Continuing where we left off in $tail"
        }
      } elseif {![info exists seen_hdr($hdr)]} {
        set seen_hdr($hdr) 1
        puts $out $line
      }
    } elseif {[regexp {^#ifdef __cplusplus} $line]} {
      puts $out "#if 0"
    } elseif {[regexp {^#line} $line]} {
      # Skip #line directives.
    } else {
      puts $out $line
    }
  }
  close $in
  section_comment "End of $tail"
}


# Process the source files.  Process files containing commonly
# used subroutines first in order to help the compiler find
# inlining opportunities.
#
foreach file {
   sqliteInt.h
   sqlite3.h
   btree.h
   hash.h
   os.h
   pager.h
   parse.h
   sqlite3ext.h
   vdbe.h
} {
  if {$available_hdr($file)} {
    copy_file tsrc/$file
  }
}

close $out

Added tool/omittest.tcl.

















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

set rcsid {$Id: omittest.tcl,v 1.8 2008/10/13 15:35:09 drh Exp $}

# Documentation for this script. This may be output to stderr
# if the script is invoked incorrectly.
set ::USAGE_MESSAGE {
This Tcl script is used to test the various compile time options 
available for omitting code (the SQLITE_OMIT_xxx options). It
should be invoked as follows:

    <script> ?-makefile PATH-TO-MAKEFILE?

The default value for ::MAKEFILE is "../Makefile.linux.gcc".

This script builds the testfixture program and runs the SQLite test suite
once with each SQLITE_OMIT_ option defined and then once with all options
defined together. Each run is performed in a seperate directory created
as a sub-directory of the current directory by the script. The output
of the build is saved in <sub-directory>/build.log. The output of the
test-suite is saved in <sub-directory>/test.log.

Almost any SQLite makefile (except those generated by configure - see below)
should work. The following properties are required:

  * The makefile should support the "testfixture" target.
  * The makefile should support the "test" target.
  * The makefile should support the variable "OPTS" as a way to pass
    options from the make command line to lemon and the C compiler.

More precisely, the following two invocations must be supported:

  make -f $::MAKEFILE testfixture OPTS="-DSQLITE_OMIT_ALTERTABLE=1"
  make -f $::MAKEFILE test

Makefiles generated by the sqlite configure program cannot be used as
they do not respect the OPTS variable.
}


# Build a testfixture executable and run quick.test using it. The first
# parameter is the name of the directory to create and use to run the
# test in. The second parameter is a list of OMIT symbols to define
# when doing so. For example:
#
#     run_quick_test /tmp/testdir {SQLITE_OMIT_TRIGGER SQLITE_OMIT_VIEW}
#
#
proc run_quick_test {dir omit_symbol_list} {
  # Compile the value of the OPTS Makefile variable.
  set opts "-DSQLITE_MEMDEBUG -DSQLITE_DEBUG -DSQLITE_NO_SYNC" 
  if {$::tcl_platform(platform)=="windows"} {
    append opts " -DSQLITE_OS_WIN=1"
  } elseif {$::tcl_platform(platform)=="os2"} {
    append opts " -DSQLITE_OS_OS2=1"
  } else {
    append opts " -DSQLITE_OS_UNIX=1"
  }
  foreach sym $omit_symbol_list {
    append opts " -D${sym}=1"
  }

  # Create the directory and do the build. If an error occurs return
  # early without attempting to run the test suite.
  file mkdir $dir
  puts -nonewline "Building $dir..."
  flush stdout
catch {
  file copy -force ./config.h $dir
  file copy -force ./libtool $dir
}
  set rc [catch {
    exec make -C $dir -f $::MAKEFILE testfixture OPTS=$opts >& $dir/build.log
  }]
  if {$rc} {
    puts "No good. See $dir/build.log."
    return
  } else {
    puts "Ok"
  }
  
  # Create an empty file "$dir/sqlite3". This is to trick the makefile out 
  # of trying to build the sqlite shell. The sqlite shell won't build 
  # with some of the OMIT options (i.e OMIT_COMPLETE).
  set sqlite3_dummy $dir/sqlite3
  if {$::tcl_platform(platform)=="windows" || $::tcl_platform(platform)=="os2"} {
    append sqlite3_dummy ".exe"
  }
  if {![file exists $sqlite3_dummy]} {
    set wr [open $sqlite3_dummy w]
    puts $wr "dummy"
    close $wr
  }

  # Run the test suite.
  puts -nonewline "Testing $dir..."
  flush stdout
  set rc [catch {
    exec make -C $dir -f $::MAKEFILE test OPTS=$opts >& $dir/test.log
  }]
  if {$rc} {
    puts "No good. See $dir/test.log."
  } else {
    puts "Ok"
  }
}


# This proc processes the command line options passed to this script.
# Currently the only option supported is "-makefile", default
# "../Makefile.linux-gcc". Set the ::MAKEFILE variable to the value of this
# option.
#
proc process_options {argv} {
  if {$::tcl_platform(platform)=="windows" || $::tcl_platform(platform)=="os2"} {
      set ::MAKEFILE ../Makefile                        ;# Default value
  } else {
      set ::MAKEFILE ../Makefile.linux-gcc              ;# Default value
  }
  for {set i 0} {$i < [llength $argv]} {incr i} {
    switch -- [lindex $argv $i] {
      -makefile {
        incr i
        set ::MAKEFILE [lindex $argv $i]
      }
  
      default {
        puts stderr [string trim $::USAGE_MESSAGE]
        exit -1
      }
    }
    set ::MAKEFILE [file normalize $::MAKEFILE]
  }
}

# Main routine.
#

proc main {argv} {
  # List of SQLITE_OMIT_XXX symbols supported by SQLite.
  set ::SYMBOLS [list                  \
    SQLITE_OMIT_ALTERTABLE             \
    SQLITE_OMIT_ANALYZE                \
    SQLITE_OMIT_ATTACH                 \
    SQLITE_OMIT_AUTHORIZATION          \
    SQLITE_OMIT_AUTOINCREMENT          \
    SQLITE_OMIT_AUTOINIT               \
    SQLITE_OMIT_AUTOVACUUM             \
    SQLITE_OMIT_BETWEEN_OPTIMIZATION   \
    SQLITE_OMIT_BLOB_LITERAL           \
    SQLITE_OMIT_BUILTIN_TEST           \
    SQLITE_OMIT_CAST                   \
    SQLITE_OMIT_CHECK                  \
    SQLITE_OMIT_COMPLETE               \
    SQLITE_OMIT_COMPOUND_SELECT        \
    SQLITE_OMIT_CONFLICT_CLAUSE        \
    SQLITE_OMIT_DATETIME_FUNCS         \
    SQLITE_OMIT_DECLTYPE               \
    off_SQLITE_OMIT_DISKIO                 \
    SQLITE_OMIT_EXPLAIN                \
    SQLITE_OMIT_FLAG_PRAGMAS           \
    SQLITE_OMIT_FLOATING_POINT         \
    SQLITE_OMIT_FOREIGN_KEY            \
    SQLITE_OMIT_GET_TABLE              \
    SQLITE_OMIT_GLOBALRECOVER          \
    SQLITE_OMIT_INCRBLOB               \
    SQLITE_OMIT_INTEGRITY_CHECK        \
    SQLITE_OMIT_LIKE_OPTIMIZATION      \
    SQLITE_OMIT_LOAD_EXTENSION         \
    SQLITE_OMIT_LOCALTIME              \
    SQLITE_OMIT_MEMORYDB               \
    SQLITE_OMIT_OR_OPTIMIZATION        \
    SQLITE_OMIT_PAGER_PRAGMAS          \
    SQLITE_OMIT_PRAGMA                 \
    SQLITE_OMIT_PROGRESS_CALLBACK      \
    SQLITE_OMIT_QUICKBALANCE           \
    SQLITE_OMIT_REINDEX                \
    SQLITE_OMIT_SCHEMA_PRAGMAS         \
    SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS \
    SQLITE_OMIT_SHARED_CACHE           \
    SQLITE_OMIT_SUBQUERY               \
    SQLITE_OMIT_TCL_VARIABLE           \
    SQLITE_OMIT_TEMPDB                 \
    SQLITE_OMIT_TRACE                  \
    SQLITE_OMIT_TRIGGER                \
    SQLITE_OMIT_UTF16                  \
    SQLITE_OMIT_VACUUM                 \
    SQLITE_OMIT_VIEW                   \
    SQLITE_OMIT_VIRTUALTABLE           \
    SQLITE_OMIT_XFER_OPT               \
  ]

  # Process any command line options.
  process_options $argv
  
  # First try a test with all OMIT symbols except SQLITE_OMIT_FLOATING_POINT 
  # and SQLITE_OMIT_PRAGMA defined. The former doesn't work (causes segfaults)
  # and the latter is currently incompatible with the test suite (this should
  # be fixed, but it will be a lot of work).
  set allsyms [list]
  foreach s $::SYMBOLS {
    if {$s!="SQLITE_OMIT_FLOATING_POINT" && $s!="SQLITE_OMIT_PRAGMA"} {
      lappend allsyms $s
    }
  }
  run_quick_test test_OMIT_EVERYTHING $allsyms

  # Now try one quick.test with each of the OMIT symbols defined. Included
  # are the OMIT_FLOATING_POINT and OMIT_PRAGMA symbols, even though we
  # know they will fail. It's good to be reminded of this from time to time.
  foreach sym $::SYMBOLS {
    set dirname "test_[string range $sym 7 end]"
    run_quick_test $dirname $sym
  }
}

main $argv

Added tool/opcodeDoc.awk.















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# Extract opcode documentation for sqliteVdbe.c and generate HTML
#
BEGIN {
  print "<html><body bgcolor=white>"
  print "<h1>SQLite Virtual Database Engine Opcodes</h1>"
  print "<table>"
}
/ Opcode: /,/\*\// {
  if( $2=="Opcode:" ){
    printf "<tr><td>%s&nbsp;%s&nbsp;%s&nbsp;%s</td>\n<td>\n", $3, $4, $5, $6
  }else if( $1=="*/" ){
    printf "</td></tr>\n"
  }else if( NF>1 ){
    sub(/^ *\*\* /,"")
    gsub(/</,"&lt;")
    gsub(/&/,"&amp;")
    print
  }
}
END {
  print "</table></body></html>"
}

Added tool/showdb.c.













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
** A utility for printing all or part of an SQLite database file.
*/
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


static int pagesize = 1024;
static int db = -1;
static int mxPage = 0;
static int perLine = 32;

static void out_of_memory(void){
  fprintf(stderr,"Out of memory...\n");
  exit(1);
}

static print_page(int iPg){
  unsigned char *aData;
  int i, j;
  aData = malloc(pagesize);
  if( aData==0 ) out_of_memory();
  lseek(db, (iPg-1)*(long long int)pagesize, SEEK_SET);
  read(db, aData, pagesize);
  fprintf(stdout, "Page %d:\n", iPg);
  for(i=0; i<pagesize; i += perLine){
    fprintf(stdout, " %03x: ",i);
    for(j=0; j<perLine; j++){
      fprintf(stdout,"%02x ", aData[i+j]);
    }
    for(j=0; j<perLine; j++){
      fprintf(stdout,"%c", isprint(aData[i+j]) ? aData[i+j] : '.');
    }
    fprintf(stdout,"\n");
  }
  free(aData);
}

int main(int argc, char **argv){
  struct stat sbuf;
  if( argc<2 ){
    fprintf(stderr,"Usage: %s FILENAME ?PAGE? ...\n", argv[0]);
    exit(1);
  }
  db = open(argv[1], O_RDONLY);
  if( db<0 ){
    fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]);
    exit(1);
  }
  fstat(db, &sbuf);
  mxPage = sbuf.st_size/pagesize + 1;
  if( argc==2 ){
    int i;
    for(i=1; i<=mxPage; i++) print_page(i);
  }else{
    int i;
    for(i=2; i<argc; i++){
      int iStart, iEnd;
      char *zLeft;
      iStart = strtol(argv[i], &zLeft, 0);
      if( zLeft && strcmp(zLeft,"..end")==0 ){
        iEnd = mxPage;
      }else if( zLeft && zLeft[0]=='.' && zLeft[1]=='.' ){
        iEnd = strtol(&zLeft[2], 0, 0);
      }else{
        iEnd = iStart;
      }
      if( iStart<1 || iEnd<iStart || iEnd>mxPage ){
        fprintf(stderr,
          "Page argument should be LOWER?..UPPER?.  Range 1 to %d\n",
          mxPage);
        exit(1);
      }
      while( iStart<=iEnd ){
        print_page(iStart);
        iStart++;
      }
    }
  }
  close(db);
}

Added tool/showjournal.c.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
** A utility for printing an SQLite database journal.
*/
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


static int pagesize = 1024;
static int db = -1;
static int mxPage = 0;

static void out_of_memory(void){
  fprintf(stderr,"Out of memory...\n");
  exit(1);
}

static print_page(int iPg){
  unsigned char *aData;
  int i, j;
  aData = malloc(pagesize);
  if( aData==0 ) out_of_memory();
  read(db, aData, pagesize);
  fprintf(stdout, "Page %d:\n", iPg);
  for(i=0; i<pagesize; i += 16){
    fprintf(stdout, " %03x: ",i);
    for(j=0; j<16; j++){
      fprintf(stdout,"%02x ", aData[i+j]);
    }
    for(j=0; j<16; j++){
      fprintf(stdout,"%c", isprint(aData[i+j]) ? aData[i+j] : '.');
    }
    fprintf(stdout,"\n");
  }
  free(aData);
}

int main(int argc, char **argv){
  struct stat sbuf;
  unsigned int u;
  int rc;
  unsigned char zBuf[10];
  unsigned char zBuf2[sizeof(u)];
  if( argc!=2 ){
    fprintf(stderr,"Usage: %s FILENAME\n", argv[0]);
    exit(1);
  }
  db = open(argv[1], O_RDONLY);
  if( db<0 ){
    fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]);
    exit(1);
  }
  read(db, zBuf, 8);
  if( zBuf[7]==0xd6 ){
    read(db, &u, sizeof(u));
    printf("Records in Journal: %u\n", u);
    read(db, &u, sizeof(u));
    printf("Magic Number: 0x%08x\n", u);
  }
  read(db, zBuf2, sizeof(zBuf2));
  u = zBuf2[0]<<24 | zBuf2[1]<<16 | zBuf2[2]<<8 | zBuf2[3];
  printf("Database Size: %u\n", u);
  while( read(db, zBuf2, sizeof(zBuf2))==sizeof(zBuf2) ){
    u = zBuf2[0]<<24 | zBuf2[1]<<16 | zBuf2[2]<<8 | zBuf2[3];
    print_page(u);
    if( zBuf[7]==0xd6 ){
      read(db, &u, sizeof(u));
      printf("Checksum: 0x%08x\n", u);
    }
  }
  close(db);
}

Added tool/soak1.tcl.















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/tclsh
#
# Usage:
#
#    tclsh soak1.tcl local-makefile.mk ?target? ?scenario?
#
# This generates many variations on local-makefile.mk (by modifing
# the OPT = lines) and runs them will fulltest, one by one.  The
# constructed makefiles are named "soak1.mk".
#
# If ?target? is provided, that is the makefile target that is run.
# The default is "fulltest"
#
# If ?scenario? is provided, it is the name of a single scenario to
# be run.   All other scenarios are skipped.
#
set localmake [lindex $argv 0]
set target [lindex $argv 1]
set scene [lindex $argv 2]
if {$target==""} {set target fulltest}
if {$scene==""} {set scene all}

set in [open $localmake]
set maketxt [read $in]
close $in
regsub -all {\\\n} $maketxt {} maketxt
#set makefilename "soak1-[expr {int(rand()*1000000000)}].mk"
set makefilename "soak1.mk"

# Generate a makefile
#
proc generate_makefile {pattern} {
  global makefilename maketxt
  set out [open $makefilename w]
  set seen_opt 0
  foreach line [split $maketxt \n] {
    if {[regexp {^ *#? *OPTS[ =+]} $line]} {
      if {!$seen_opt} {
         puts $out "OPTS += -DSQLITE_NO_SYNC=1"
         foreach x $pattern {
           puts $out "OPTS += -D$x"
         }
         set seen_opt 1
      }
    } else {
      puts $out $line
    }
  }
  close $out
}

# Run a test
#
proc scenario {id title pattern} {
  global makefilename target scene
  if {$scene!="all" && $scene!=$id && $scene!=$title} return
  puts "**************** $title ***************"
  generate_makefile $pattern
  exec make -f $makefilename clean >@stdout 2>@stdout
  exec make -f $makefilename $target >@stdout 2>@stdout
}

###############################################################################
# Add new scenarios here
#
scenario 0 {Default} {}
scenario 1 {Debug} {
  SQLITE_DEBUG=1
  SQLITE_MEMDEBUG=1
}
scenario 2 {Everything} {
  SQLITE_DEBUG=1
  SQLITE_MEMDEBUG=1
  SQLITE_ENABLE_MEMORY_MANAGEMENT=1
  SQLITE_ENABLE_COLUMN_METADATA=1
  SQLITE_ENABLE_LOAD_EXTENSION=1 HAVE_DLOPEN=1
  SQLITE_ENABLE_MEMORY_MANAGEMENT=1
}
scenario 3 {Customer-1} {
  SQLITE_DEBUG=1 SQLITE_MEMDEBUG=1
  SQLITE_THREADSAFE=1 SQLITE_OS_UNIX=1
  SQLITE_DISABLE_LFS=1
  SQLITE_DEFAULT_AUTOVACUUM=1
  SQLITE_DEFAULT_PAGE_SIZE=1024
  SQLITE_MAX_PAGE_SIZE=4096
  SQLITE_DEFAULT_CACHE_SIZE=64
  SQLITE_DEFAULT_TEMP_CACHE_SIZE=32
  SQLITE_TEMP_STORE=3
  SQLITE_OMIT_PROGRESS_CALLBACK=1
  SQLITE_OMIT_LOAD_EXTENSION=1
  SQLITE_OMIT_VIRTUALTABLE=1
  SQLITE_ENABLE_IOTRACE=1
}
scenario 4 {Small-Cache} {
  SQLITE_DEBUG=1 SQLITE_MEMDEBUG=1
  SQLITE_THREADSAFE=1 SQLITE_OS_UNIX=1
  SQLITE_DEFAULT_AUTOVACUUM=1
  SQLITE_DEFAULT_PAGE_SIZE=1024
  SQLITE_MAX_PAGE_SIZE=2048
  SQLITE_DEFAULT_CACHE_SIZE=13
  SQLITE_DEFAULT_TEMP_CACHE_SIZE=11
  SQLITE_TEMP_STORE=1
}

Added tool/space_used.tcl.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# Run this TCL script using "testfixture" in order get a report that shows
# how much disk space is used by a particular data to actually store data
# versus how much space is unused.
#

# Get the name of the database to analyze
#
if {[llength $argv]!=1} {
  puts stderr "Usage: $argv0 database-name"
  exit 1
}
set file_to_analyze [lindex $argv 0]

# Open the database
#
sqlite db [lindex $argv 0]
set DB [btree_open [lindex $argv 0]]

# Output the schema for the generated report
#
puts \
{BEGIN;
CREATE TABLE space_used(
   name clob,        -- Name of a table or index in the database file
   is_index boolean, -- TRUE if it is an index, false for a table
   payload int,      -- Total amount of data stored in this table or index
   pri_pages int,    -- Number of primary pages used
   ovfl_pages int,   -- Number of overflow pages used
   pri_unused int,   -- Number of unused bytes on primary pages
   ovfl_unused int   -- Number of unused bytes on overflow pages
);}

# This query will be used to find the root page number for every index and
# table in the database.
#
set sql {
  SELECT name, type, rootpage FROM sqlite_master
  UNION ALL
  SELECT 'sqlite_master', 'table', 2
  ORDER BY 1
}

# Initialize variables used for summary statistics.
#
set total_size 0
set total_primary 0
set total_overflow 0
set total_unused_primary 0
set total_unused_ovfl 0

# Analyze every table in the database, one at a time.
#
foreach {name type rootpage} [db eval $sql] {
  set cursor [btree_cursor $DB $rootpage 0]
  set go [btree_first $cursor]
  set size 0
  catch {unset pg_used}
  set unused_ovfl 0
  set n_overflow 0
  while {$go==0} {
    set payload [btree_payload_size $cursor]
    incr size $payload
    set stat [btree_cursor_dump $cursor]
    set pgno [lindex $stat 0]
    set freebytes [lindex $stat 4]
    set pg_used($pgno) $freebytes
    if {$payload>238} {
      set n [expr {($payload-238+1019)/1020}]
      incr n_overflow $n
      incr unused_ovfl [expr {$n*1020+238-$payload}]
    }
    set go [btree_next $cursor]
  }
  btree_close_cursor $cursor
  set n_primary [llength [array names pg_used]]
  set unused_primary 0
  foreach x [array names pg_used] {incr unused_primary $pg_used($x)}
  regsub -all ' $name '' name
  puts -nonewline "INSERT INTO space_used VALUES('$name'"
  puts -nonewline ",[expr {$type=="index"}]"
  puts ",$size,$n_primary,$n_overflow,$unused_primary,$unused_ovfl);"
  incr total_size $size
  incr total_primary $n_primary
  incr total_overflow $n_overflow
  incr total_unused_primary $unused_primary
  incr total_unused_ovfl $unused_ovfl
}

# Output summary statistics:
#
puts "-- Total payload size: $total_size"
puts "-- Total pages used: $total_primary primary and $total_overflow overflow"
set file_pgcnt [expr {[file size [lindex $argv 0]]/1024}]
puts -nonewline "-- Total unused bytes on primary pages: $total_unused_primary"
if {$total_primary>0} {
  set upp [expr {$total_unused_primary/$total_primary}]
  puts " (avg $upp bytes/page)"
} else {
  puts ""
}
puts -nonewline "-- Total unused bytes on overflow pages: $total_unused_ovfl"
if {$total_overflow>0} {
  set upp [expr {$total_unused_ovfl/$total_overflow}]
  puts " (avg $upp bytes/page)"
} else {
  puts ""
}
set n_free [expr {$file_pgcnt-$total_primary-$total_overflow}]
if {$n_free>0} {incr n_free -1}
puts "-- Total pages on freelist: $n_free"
puts "COMMIT;"

Added tool/spaceanal.tcl.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# Run this TCL script using "testfixture" in order get a report that shows
# how much disk space is used by a particular data to actually store data
# versus how much space is unused.
#

if {[catch {

# Get the name of the database to analyze
#
#set argv $argv0
if {[llength $argv]!=1} {
  puts stderr "Usage: $argv0 database-name"
  exit 1
}
set file_to_analyze [lindex $argv 0]
if {![file exists $file_to_analyze]} {
  puts stderr "No such file: $file_to_analyze"
  exit 1
}
if {![file readable $file_to_analyze]} {
  puts stderr "File is not readable: $file_to_analyze"
  exit 1
}
if {[file size $file_to_analyze]<512} {
  puts stderr "Empty or malformed database: $file_to_analyze"
  exit 1
}

# Maximum distance between pages before we consider it a "gap"
#
set MAXGAP 3

# Open the database
#
sqlite3 db [lindex $argv 0]
set DB [btree_open [lindex $argv 0] 1000 0]

# In-memory database for collecting statistics. This script loops through
# the tables and indices in the database being analyzed, adding a row for each
# to an in-memory database (for which the schema is shown below). It then
# queries the in-memory db to produce the space-analysis report.
#
sqlite3 mem :memory:
set tabledef\
{CREATE TABLE space_used(
   name clob,        -- Name of a table or index in the database file
   tblname clob,     -- Name of associated table
   is_index boolean, -- TRUE if it is an index, false for a table
   nentry int,       -- Number of entries in the BTree
   leaf_entries int, -- Number of leaf entries
   payload int,      -- Total amount of data stored in this table or index
   ovfl_payload int, -- Total amount of data stored on overflow pages
   ovfl_cnt int,     -- Number of entries that use overflow
   mx_payload int,   -- Maximum payload size
   int_pages int,    -- Number of interior pages used
   leaf_pages int,   -- Number of leaf pages used
   ovfl_pages int,   -- Number of overflow pages used
   int_unused int,   -- Number of unused bytes on interior pages
   leaf_unused int,  -- Number of unused bytes on primary pages
   ovfl_unused int,  -- Number of unused bytes on overflow pages
   gap_cnt int       -- Number of gaps in the page layout
);}
mem eval $tabledef

proc integerify {real} {
  if {[string is double -strict $real]} {
    return [expr {int($real)}]
  } else {
    return 0
  }
}
mem function int integerify

# Quote a string for use in an SQL query. Examples:
#
# [quote {hello world}]   == {'hello world'}
# [quote {hello world's}] == {'hello world''s'}
#
proc quote {txt} {
  regsub -all ' $txt '' q
  return '$q'
}

# This proc is a wrapper around the btree_cursor_info command. The
# second argument is an open btree cursor returned by [btree_cursor].
# The first argument is the name of an array variable that exists in
# the scope of the caller. If the third argument is non-zero, then
# info is returned for the page that lies $up entries upwards in the
# tree-structure. (i.e. $up==1 returns the parent page, $up==2 the 
# grandparent etc.)
#
# The following entries in that array are filled in with information retrieved
# using [btree_cursor_info]:
#
#   $arrayvar(page_no)             =  The page number
#   $arrayvar(entry_no)            =  The entry number
#   $arrayvar(page_entries)        =  Total number of entries on this page
#   $arrayvar(cell_size)           =  Cell size (local payload + header)
#   $arrayvar(page_freebytes)      =  Number of free bytes on this page
#   $arrayvar(page_freeblocks)     =  Number of free blocks on the page
#   $arrayvar(payload_bytes)       =  Total payload size (local + overflow)
#   $arrayvar(header_bytes)        =  Header size in bytes
#   $arrayvar(local_payload_bytes) =  Local payload size
#   $arrayvar(parent)              =  Parent page number
# 
proc cursor_info {arrayvar csr {up 0}} {
  upvar $arrayvar a
  foreach [list a(page_no) \
                a(entry_no) \
                a(page_entries) \
                a(cell_size) \
                a(page_freebytes) \
                a(page_freeblocks) \
                a(payload_bytes) \
                a(header_bytes) \
                a(local_payload_bytes) \
                a(parent) \
                a(first_ovfl) ] [btree_cursor_info $csr $up] break
}

# Determine the page-size of the database. This global variable is used
# throughout the script.
#
set pageSize [db eval {PRAGMA page_size}]

# Analyze every table in the database, one at a time.
#
# The following query returns the name and root-page of each table in the
# database, including the sqlite_master table.
#
set sql {
  SELECT name, rootpage FROM sqlite_master
   WHERE type='table' AND rootpage>0
  UNION ALL
  SELECT 'sqlite_master', 1
  ORDER BY 1
}
set wideZero [expr {10000000000 - 10000000000}]
foreach {name rootpage} [db eval $sql] {
  puts stderr "Analyzing table $name..."

  # Code below traverses the table being analyzed (table name $name), using the
  # btree cursor $cursor. Statistics related to table $name are accumulated in
  # the following variables:
  #
  set total_payload $wideZero        ;# Payload space used by all entries
  set total_ovfl $wideZero           ;# Payload space on overflow pages
  set unused_int $wideZero           ;# Unused space on interior nodes
  set unused_leaf $wideZero          ;# Unused space on leaf nodes
  set unused_ovfl $wideZero          ;# Unused space on overflow pages
  set cnt_ovfl $wideZero             ;# Number of entries that use overflows
  set cnt_leaf_entry $wideZero       ;# Number of leaf entries
  set cnt_int_entry $wideZero        ;# Number of interor entries
  set mx_payload $wideZero           ;# Maximum payload size
  set ovfl_pages $wideZero           ;# Number of overflow pages used
  set leaf_pages $wideZero           ;# Number of leaf pages
  set int_pages $wideZero            ;# Number of interior pages
  set gap_cnt 0                      ;# Number of holes in the page sequence
  set prev_pgno 0                    ;# Last page number seen

  # As the btree is traversed, the array variable $seen($pgno) is set to 1
  # the first time page $pgno is encountered.
  #
  catch {unset seen}

  # The following loop runs once for each entry in table $name. The table
  # is traversed using the btree cursor stored in variable $csr
  #
  set csr [btree_cursor $DB $rootpage 0]
  for {btree_first $csr} {![btree_eof $csr]} {btree_next $csr} {
    incr cnt_leaf_entry

    # Retrieve information about the entry the btree-cursor points to into
    # the array variable $ci (cursor info).
    #
    cursor_info ci $csr

    # Check if the payload of this entry is greater than the current 
    # $mx_payload statistic for the table. Also increase the $total_payload
    # statistic.
    #
    if {$ci(payload_bytes)>$mx_payload} {set mx_payload $ci(payload_bytes)}
    incr total_payload $ci(payload_bytes)

    # If this entry uses overflow pages, then update the $cnt_ovfl, 
    # $total_ovfl, $ovfl_pages and $unused_ovfl statistics.
    #
    set ovfl [expr {$ci(payload_bytes)-$ci(local_payload_bytes)}]
    if {$ovfl} {
      incr cnt_ovfl
      incr total_ovfl $ovfl
      set n [expr {int(ceil($ovfl/($pageSize-4.0)))}]
      incr ovfl_pages $n
      incr unused_ovfl [expr {$n*($pageSize-4) - $ovfl}]
      set pglist [btree_ovfl_info $DB $csr]
    } else {
      set pglist {}
    }

    # If this is the first table entry analyzed for the page, then update
    # the page-related statistics $leaf_pages and $unused_leaf. Also, if
    # this page has a parent page that has not been analyzed, retrieve
    # info for the parent and update statistics for it too.
    #
    if {![info exists seen($ci(page_no))]} {
      set seen($ci(page_no)) 1
      incr leaf_pages
      incr unused_leaf $ci(page_freebytes)
      set pglist "$ci(page_no) $pglist"

      # Now check if the page has a parent that has not been analyzed. If
      # so, update the $int_pages, $cnt_int_entry and $unused_int statistics
      # accordingly. Then check if the parent page has a parent that has
      # not yet been analyzed etc.
      #
      # set parent $ci(parent_page_no)
      for {set up 1} \
          {$ci(parent)!=0 && ![info exists seen($ci(parent))]} {incr up} \
      {
        # Mark the parent as seen.
        #
        set seen($ci(parent)) 1

        # Retrieve info for the parent and update statistics.
        cursor_info ci $csr $up
        incr int_pages
        incr cnt_int_entry $ci(page_entries)
        incr unused_int $ci(page_freebytes)

        # parent pages come before their first child
        set pglist "$ci(page_no) $pglist"
      }
    }

    # Check the page list for fragmentation
    #
    foreach pg $pglist {
      if {$pg!=$prev_pgno+1 && $prev_pgno>0} {
        incr gap_cnt
      }
      set prev_pgno $pg
    }
  }
  btree_close_cursor $csr

  # Handle the special case where a table contains no data. In this case
  # all statistics are zero, except for the number of leaf pages (1) and
  # the unused bytes on leaf pages ($pageSize - 8).
  #
  # An exception to the above is the sqlite_master table. If it is empty
  # then all statistics are zero except for the number of leaf pages (1),
  # and the number of unused bytes on leaf pages ($pageSize - 112).
  #
  if {[llength [array names seen]]==0} {
    set leaf_pages 1
    if {$rootpage==1} {
      set unused_leaf [expr {$pageSize-112}]
    } else {
      set unused_leaf [expr {$pageSize-8}]
    }
  }

  # Insert the statistics for the table analyzed into the in-memory database.
  #
  set sql "INSERT INTO space_used VALUES("
  append sql [quote $name]
  append sql ",[quote $name]"
  append sql ",0"
  append sql ",[expr {$cnt_leaf_entry+$cnt_int_entry}]"
  append sql ",$cnt_leaf_entry"
  append sql ",$total_payload"
  append sql ",$total_ovfl"
  append sql ",$cnt_ovfl"
  append sql ",$mx_payload"
  append sql ",$int_pages"
  append sql ",$leaf_pages"
  append sql ",$ovfl_pages"
  append sql ",$unused_int"
  append sql ",$unused_leaf"
  append sql ",$unused_ovfl"
  append sql ",$gap_cnt"
  append sql );
  mem eval $sql
}

# Analyze every index in the database, one at a time.
#
# The query below returns the name, associated table and root-page number 
# for every index in the database.
#
set sql {
  SELECT name, tbl_name, rootpage FROM sqlite_master WHERE type='index'
  ORDER BY 2, 1
}
foreach {name tbl_name rootpage} [db eval $sql] {
  puts stderr "Analyzing index $name of table $tbl_name..."

  # Code below traverses the index being analyzed (index name $name), using the
  # btree cursor $cursor. Statistics related to index $name are accumulated in
  # the following variables:
  #
  set total_payload $wideZero        ;# Payload space used by all entries
  set total_ovfl $wideZero           ;# Payload space on overflow pages
  set unused_leaf $wideZero          ;# Unused space on leaf nodes
  set unused_ovfl $wideZero          ;# Unused space on overflow pages
  set cnt_ovfl $wideZero             ;# Number of entries that use overflows
  set cnt_leaf_entry $wideZero       ;# Number of leaf entries
  set mx_payload $wideZero           ;# Maximum payload size
  set ovfl_pages $wideZero           ;# Number of overflow pages used
  set leaf_pages $wideZero           ;# Number of leaf pages
  set gap_cnt 0                      ;# Number of holes in the page sequence
  set prev_pgno 0                    ;# Last page number seen

  # As the btree is traversed, the array variable $seen($pgno) is set to 1
  # the first time page $pgno is encountered.
  #
  catch {unset seen}

  # The following loop runs once for each entry in index $name. The index
  # is traversed using the btree cursor stored in variable $csr
  #
  set csr [btree_cursor $DB $rootpage 0]
  for {btree_first $csr} {![btree_eof $csr]} {btree_next $csr} {
    incr cnt_leaf_entry

    # Retrieve information about the entry the btree-cursor points to into
    # the array variable $ci (cursor info).
    #
    cursor_info ci $csr

    # Check if the payload of this entry is greater than the current 
    # $mx_payload statistic for the table. Also increase the $total_payload
    # statistic.
    #
    set payload [btree_keysize $csr]
    if {$payload>$mx_payload} {set mx_payload $payload}
    incr total_payload $payload

    # If this entry uses overflow pages, then update the $cnt_ovfl, 
    # $total_ovfl, $ovfl_pages and $unused_ovfl statistics.
    #
    set ovfl [expr {$payload-$ci(local_payload_bytes)}]
    if {$ovfl} {
      incr cnt_ovfl
      incr total_ovfl $ovfl
      set n [expr {int(ceil($ovfl/($pageSize-4.0)))}]
      incr ovfl_pages $n
      incr unused_ovfl [expr {$n*($pageSize-4) - $ovfl}]
    }

    # If this is the first table entry analyzed for the page, then update
    # the page-related statistics $leaf_pages and $unused_leaf.
    #
    if {![info exists seen($ci(page_no))]} {
      set seen($ci(page_no)) 1
      incr leaf_pages
      incr unused_leaf $ci(page_freebytes)
      set pg $ci(page_no)
      if {$prev_pgno>0 && $pg!=$prev_pgno+1} {
        incr gap_cnt
      }
      set prev_pgno $ci(page_no)
    }
  }
  btree_close_cursor $csr

  # Handle the special case where a index contains no data. In this case
  # all statistics are zero, except for the number of leaf pages (1) and
  # the unused bytes on leaf pages ($pageSize - 8).
  #
  if {[llength [array names seen]]==0} {
    set leaf_pages 1
    set unused_leaf [expr {$pageSize-8}]
  }

  # Insert the statistics for the index analyzed into the in-memory database.
  #
  set sql "INSERT INTO space_used VALUES("
  append sql [quote $name]
  append sql ",[quote $tbl_name]"
  append sql ",1"
  append sql ",$cnt_leaf_entry"
  append sql ",$cnt_leaf_entry"
  append sql ",$total_payload"
  append sql ",$total_ovfl"
  append sql ",$cnt_ovfl"
  append sql ",$mx_payload"
  append sql ",0"
  append sql ",$leaf_pages"
  append sql ",$ovfl_pages"
  append sql ",0"
  append sql ",$unused_leaf"
  append sql ",$unused_ovfl"
  append sql ",$gap_cnt"
  append sql );
  mem eval $sql
}

# Generate a single line of output in the statistics section of the
# report.
#
proc statline {title value {extra {}}} {
  set len [string length $title]
  set dots [string range {......................................} $len end]
  set len [string length $value]
  set sp2 [string range {          } $len end]
  if {$extra ne ""} {
    set extra " $extra"
  }
  puts "$title$dots $value$sp2$extra"
}

# Generate a formatted percentage value for $num/$denom
#
proc percent {num denom {of {}}} {
  if {$denom==0.0} {return ""}
  set v [expr {$num*100.0/$denom}]
  set of {}
  if {$v==100.0 || $v<0.001 || ($v>1.0 && $v<99.0)} {
    return [format {%5.1f%% %s} $v $of]
  } elseif {$v<0.1 || $v>99.9} {
    return [format {%7.3f%% %s} $v $of]
  } else {
    return [format {%6.2f%% %s} $v $of]
  }
}

proc divide {num denom} {
  if {$denom==0} {return 0.0}
  return [format %.2f [expr double($num)/double($denom)]]
}

# Generate a subreport that covers some subset of the database.
# the $where clause determines which subset to analyze.
#
proc subreport {title where} {
  global pageSize file_pgcnt

  # Query the in-memory database for the sum of various statistics 
  # for the subset of tables/indices identified by the WHERE clause in
  # $where. Note that even if the WHERE clause matches no rows, the
  # following query returns exactly one row (because it is an aggregate).
  #
  # The results of the query are stored directly by SQLite into local 
  # variables (i.e. $nentry, $nleaf etc.).
  #
  mem eval "
    SELECT
      int(sum(nentry)) AS nentry,
      int(sum(leaf_entries)) AS nleaf,
      int(sum(payload)) AS payload,
      int(sum(ovfl_payload)) AS ovfl_payload,
      max(mx_payload) AS mx_payload,
      int(sum(ovfl_cnt)) as ovfl_cnt,
      int(sum(leaf_pages)) AS leaf_pages,
      int(sum(int_pages)) AS int_pages,
      int(sum(ovfl_pages)) AS ovfl_pages,
      int(sum(leaf_unused)) AS leaf_unused,
      int(sum(int_unused)) AS int_unused,
      int(sum(ovfl_unused)) AS ovfl_unused,
      int(sum(gap_cnt)) AS gap_cnt
    FROM space_used WHERE $where" {} {}

  # Output the sub-report title, nicely decorated with * characters.
  #
  puts ""
  set len [string length $title]
  set stars [string repeat * [expr 65-$len]]
  puts "*** $title $stars"
  puts ""

  # Calculate statistics and store the results in TCL variables, as follows:
  #
  # total_pages: Database pages consumed.
  # total_pages_percent: Pages consumed as a percentage of the file.
  # storage: Bytes consumed.
  # payload_percent: Payload bytes used as a percentage of $storage.
  # total_unused: Unused bytes on pages.
  # avg_payload: Average payload per btree entry.
  # avg_fanout: Average fanout for internal pages.
  # avg_unused: Average unused bytes per btree entry.
  # ovfl_cnt_percent: Percentage of btree entries that use overflow pages.
  #
  set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
  set total_pages_percent [percent $total_pages $file_pgcnt]
  set storage [expr {$total_pages*$pageSize}]
  set payload_percent [percent $payload $storage {of storage consumed}]
  set total_unused [expr {$ovfl_unused+$int_unused+$leaf_unused}]
  set avg_payload [divide $payload $nleaf]
  set avg_unused [divide $total_unused $nleaf]
  if {$int_pages>0} {
    # TODO: Is this formula correct?
    set nTab [mem eval "
      SELECT count(*) FROM (
          SELECT DISTINCT tblname FROM space_used WHERE $where AND is_index=0
      )
    "]
    set avg_fanout [mem eval "
      SELECT (sum(leaf_pages+int_pages)-$nTab)/sum(int_pages) FROM space_used
          WHERE $where AND is_index = 0
    "]
    set avg_fanout [format %.2f $avg_fanout]
  }
  set ovfl_cnt_percent [percent $ovfl_cnt $nleaf {of all entries}]

  # Print out the sub-report statistics.
  #
  statline {Percentage of total database} $total_pages_percent
  statline {Number of entries} $nleaf
  statline {Bytes of storage consumed} $storage
  statline {Bytes of payload} $payload $payload_percent
  statline {Average payload per entry} $avg_payload
  statline {Average unused bytes per entry} $avg_unused
  if {[info exists avg_fanout]} {
    statline {Average fanout} $avg_fanout
  }
  if {$total_pages>1} {
    set fragmentation [percent $gap_cnt [expr {$total_pages-1}] {fragmentation}]
    statline {Fragmentation} $fragmentation
  }
  statline {Maximum payload per entry} $mx_payload
  statline {Entries that use overflow} $ovfl_cnt $ovfl_cnt_percent
  if {$int_pages>0} {
    statline {Index pages used} $int_pages
  }
  statline {Primary pages used} $leaf_pages
  statline {Overflow pages used} $ovfl_pages
  statline {Total pages used} $total_pages
  if {$int_unused>0} {
    set int_unused_percent \
         [percent $int_unused [expr {$int_pages*$pageSize}] {of index space}]
    statline "Unused bytes on index pages" $int_unused $int_unused_percent
  }
  statline "Unused bytes on primary pages" $leaf_unused \
     [percent $leaf_unused [expr {$leaf_pages*$pageSize}] {of primary space}]
  statline "Unused bytes on overflow pages" $ovfl_unused \
     [percent $ovfl_unused [expr {$ovfl_pages*$pageSize}] {of overflow space}]
  statline "Unused bytes on all pages" $total_unused \
               [percent $total_unused $storage {of all space}]
  return 1
}

# Calculate the overhead in pages caused by auto-vacuum. 
#
# This procedure calculates and returns the number of pages used by the 
# auto-vacuum 'pointer-map'. If the database does not support auto-vacuum,
# then 0 is returned. The two arguments are the size of the database file in
# pages and the page size used by the database (in bytes).
proc autovacuum_overhead {filePages pageSize} {

  # Read the value of meta 4. If non-zero, then the database supports
  # auto-vacuum. It would be possible to use "PRAGMA auto_vacuum" instead,
  # but that would not work if the SQLITE_OMIT_PRAGMA macro was defined
  # when the library was built.
  set meta4 [lindex [btree_get_meta $::DB] 4]

  # If the database is not an auto-vacuum database or the file consists
  # of one page only then there is no overhead for auto-vacuum. Return zero.
  if {0==$meta4 || $filePages==1} {
    return 0
  }

  # The number of entries on each pointer map page. The layout of the
  # database file is one pointer-map page, followed by $ptrsPerPage other
  # pages, followed by a pointer-map page etc. The first pointer-map page
  # is the second page of the file overall.
  set ptrsPerPage [expr double($pageSize/5)]

  # Return the number of pointer map pages in the database.
  return [expr int(ceil( ($filePages-1.0)/($ptrsPerPage+1.0) ))]
}


# Calculate the summary statistics for the database and store the results
# in TCL variables. They are output below. Variables are as follows:
#
# pageSize:      Size of each page in bytes.
# file_bytes:    File size in bytes.
# file_pgcnt:    Number of pages in the file.
# file_pgcnt2:   Number of pages in the file (calculated).
# av_pgcnt:      Pages consumed by the auto-vacuum pointer-map.
# av_percent:    Percentage of the file consumed by auto-vacuum pointer-map.
# inuse_pgcnt:   Data pages in the file.
# inuse_percent: Percentage of pages used to store data.
# free_pgcnt:    Free pages calculated as (<total pages> - <in-use pages>)
# free_pgcnt2:   Free pages in the file according to the file header.
# free_percent:  Percentage of file consumed by free pages (calculated).
# free_percent2: Percentage of file consumed by free pages (header).
# ntable:        Number of tables in the db.
# nindex:        Number of indices in the db.
# nautoindex:    Number of indices created automatically.
# nmanindex:     Number of indices created manually.
# user_payload:  Number of bytes of payload in table btrees 
#                (not including sqlite_master)
# user_percent:  $user_payload as a percentage of total file size.

set file_bytes  [file size $file_to_analyze]
set file_pgcnt  [expr {$file_bytes/$pageSize}]

set av_pgcnt    [autovacuum_overhead $file_pgcnt $pageSize]
set av_percent  [percent $av_pgcnt $file_pgcnt]

set sql {SELECT sum(leaf_pages+int_pages+ovfl_pages) FROM space_used}
set inuse_pgcnt   [expr int([mem eval $sql])]
set inuse_percent [percent $inuse_pgcnt $file_pgcnt]

set free_pgcnt    [expr $file_pgcnt-$inuse_pgcnt-$av_pgcnt]
set free_percent  [percent $free_pgcnt $file_pgcnt]
set free_pgcnt2   [lindex [btree_get_meta $DB] 0]
set free_percent2 [percent $free_pgcnt2 $file_pgcnt]

set file_pgcnt2 [expr {$inuse_pgcnt+$free_pgcnt2+$av_pgcnt}]

set ntable [db eval {SELECT count(*)+1 FROM sqlite_master WHERE type='table'}]
set nindex [db eval {SELECT count(*) FROM sqlite_master WHERE type='index'}]
set sql {SELECT count(*) FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
set nautoindex [db eval $sql]
set nmanindex [expr {$nindex-$nautoindex}]

# set total_payload [mem eval "SELECT sum(payload) FROM space_used"]
set user_payload [mem one {SELECT int(sum(payload)) FROM space_used
     WHERE NOT is_index AND name NOT LIKE 'sqlite_master'}]
set user_percent [percent $user_payload $file_bytes]

# Output the summary statistics calculated above.
#
puts "/** Disk-Space Utilization Report For $file_to_analyze"
catch {
  puts "*** As of [clock format [clock seconds] -format {%Y-%b-%d %H:%M:%S}]"
}
puts ""
statline {Page size in bytes} $pageSize
statline {Pages in the whole file (measured)} $file_pgcnt
statline {Pages in the whole file (calculated)} $file_pgcnt2
statline {Pages that store data} $inuse_pgcnt $inuse_percent
statline {Pages on the freelist (per header)} $free_pgcnt2 $free_percent2
statline {Pages on the freelist (calculated)} $free_pgcnt $free_percent
statline {Pages of auto-vacuum overhead} $av_pgcnt $av_percent
statline {Number of tables in the database} $ntable
statline {Number of indices} $nindex
statline {Number of named indices} $nmanindex
statline {Automatically generated indices} $nautoindex
statline {Size of the file in bytes} $file_bytes
statline {Bytes of user payload stored} $user_payload $user_percent

# Output table rankings
#
puts ""
puts "*** Page counts for all tables with their indices ********************"
puts ""
mem eval {SELECT tblname, count(*) AS cnt, 
              int(sum(int_pages+leaf_pages+ovfl_pages)) AS size
          FROM space_used GROUP BY tblname ORDER BY size+0 DESC, tblname} {} {
  statline [string toupper $tblname] $size [percent $size $file_pgcnt]
}

# Output subreports
#
if {$nindex>0} {
  subreport {All tables and indices} 1
}
subreport {All tables} {NOT is_index}
if {$nindex>0} {
  subreport {All indices} {is_index}
}
foreach tbl [mem eval {SELECT name FROM space_used WHERE NOT is_index
                       ORDER BY name}] {
  regsub ' $tbl '' qn
  set name [string toupper $tbl]
  set n [mem eval "SELECT count(*) FROM space_used WHERE tblname='$qn'"]
  if {$n>1} {
    subreport "Table $name and all its indices" "tblname='$qn'"
    subreport "Table $name w/o any indices" "name='$qn'"
    subreport "Indices of table $name" "tblname='$qn' AND is_index"
  } else {
    subreport "Table $name" "name='$qn'"
  }
}

# Output instructions on what the numbers above mean.
#
puts {
*** Definitions ******************************************************

Page size in bytes

    The number of bytes in a single page of the database file.  
    Usually 1024.

Number of pages in the whole file
}
puts \
"    The number of $pageSize-byte pages that go into forming the complete
    database"
puts \
{
Pages that store data

    The number of pages that store data, either as primary B*Tree pages or
    as overflow pages.  The number at the right is the data pages divided by
    the total number of pages in the file.

Pages on the freelist

    The number of pages that are not currently in use but are reserved for
    future use.  The percentage at the right is the number of freelist pages
    divided by the total number of pages in the file.

Pages of auto-vacuum overhead

    The number of pages that store data used by the database to facilitate
    auto-vacuum. This is zero for databases that do not support auto-vacuum.

Number of tables in the database

    The number of tables in the database, including the SQLITE_MASTER table
    used to store schema information.

Number of indices

    The total number of indices in the database.

Number of named indices

    The number of indices created using an explicit CREATE INDEX statement.

Automatically generated indices

    The number of indices used to implement PRIMARY KEY or UNIQUE constraints
    on tables.

Size of the file in bytes

    The total amount of disk space used by the entire database files.

Bytes of user payload stored

    The total number of bytes of user payload stored in the database. The
    schema information in the SQLITE_MASTER table is not counted when
    computing this number.  The percentage at the right shows the payload
    divided by the total file size.

Percentage of total database

    The amount of the complete database file that is devoted to storing
    information described by this category.

Number of entries

    The total number of B-Tree key/value pairs stored under this category.

Bytes of storage consumed

    The total amount of disk space required to store all B-Tree entries
    under this category.  The is the total number of pages used times
    the pages size.

Bytes of payload

    The amount of payload stored under this category.  Payload is the data
    part of table entries and the key part of index entries.  The percentage
    at the right is the bytes of payload divided by the bytes of storage 
    consumed.

Average payload per entry

    The average amount of payload on each entry.  This is just the bytes of
    payload divided by the number of entries.

Average unused bytes per entry

    The average amount of free space remaining on all pages under this
    category on a per-entry basis.  This is the number of unused bytes on
    all pages divided by the number of entries.

Fragmentation

    The percentage of pages in the table or index that are not
    consecutive in the disk file.  Many filesystems are optimized
    for sequential file access so smaller fragmentation numbers 
    sometimes result in faster queries, especially for larger
    database files that do not fit in the disk cache.

Maximum payload per entry

    The largest payload size of any entry.

Entries that use overflow

    The number of entries that user one or more overflow pages.

Total pages used

    This is the number of pages used to hold all information in the current
    category.  This is the sum of index, primary, and overflow pages.

Index pages used

    This is the number of pages in a table B-tree that hold only key (rowid)
    information and no data.

Primary pages used

    This is the number of B-tree pages that hold both key and data.

Overflow pages used

    The total number of overflow pages used for this category.

Unused bytes on index pages

    The total number of bytes of unused space on all index pages.  The
    percentage at the right is the number of unused bytes divided by the
    total number of bytes on index pages.

Unused bytes on primary pages

    The total number of bytes of unused space on all primary pages.  The
    percentage at the right is the number of unused bytes divided by the
    total number of bytes on primary pages.

Unused bytes on overflow pages

    The total number of bytes of unused space on all overflow pages.  The
    percentage at the right is the number of unused bytes divided by the
    total number of bytes on overflow pages.

Unused bytes on all pages

    The total number of bytes of unused space on all primary and overflow 
    pages.  The percentage at the right is the number of unused bytes 
    divided by the total number of bytes.
}

# Output a dump of the in-memory database. This can be used for more
# complex offline analysis.
#
puts "**********************************************************************"
puts "The entire text of this report can be sourced into any SQL database"
puts "engine for further analysis.  All of the text above is an SQL comment."
puts "The data used to generate this report follows:"
puts "*/"
puts "BEGIN;"
puts $tabledef
unset -nocomplain x
mem eval {SELECT * FROM space_used} x {
  puts -nonewline "INSERT INTO space_used VALUES"
  set sep (
  foreach col $x(*) {
    set v $x($col)
    if {$v=="" || ![string is double $v]} {set v [quote $v]}
    puts -nonewline $sep$v
    set sep ,
  }
  puts ");"
}
puts "COMMIT;"

} err]} {
  puts "ERROR: $err"
  puts $errorInfo
  exit 1
}

Added tool/speedtest.tcl.







































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/tclsh
#
# Run this script using TCLSH to do a speed comparison between
# various versions of SQLite and PostgreSQL and MySQL
#

# Run a test
#
set cnt 1
proc runtest {title} {
  global cnt
  set sqlfile test$cnt.sql
  puts "<h2>Test $cnt: $title</h2>"
  incr cnt
  set fd [open $sqlfile r]
  set sql [string trim [read $fd [file size $sqlfile]]]
  close $fd
  set sx [split $sql \n]
  set n [llength $sx]
  if {$n>8} {
    set sql {}
    for {set i 0} {$i<3} {incr i} {append sql [lindex $sx $i]<br>\n}
    append sql  "<i>... [expr {$n-6}] lines omitted</i><br>\n"
    for {set i [expr {$n-3}]} {$i<$n} {incr i} {
      append sql [lindex $sx $i]<br>\n
    }
  } else {
    regsub -all \n [string trim $sql] <br> sql
  }
  puts "<blockquote>"
  puts "$sql"
  puts "</blockquote><table border=0 cellpadding=0 cellspacing=0>"
  set format {<tr><td>%s</td><td align="right">&nbsp;&nbsp;&nbsp;%.3f</td></tr>}
  set delay 1000
#  exec sync; after $delay;
#  set t [time "exec psql drh <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format PostgreSQL: $t]
  exec sync; after $delay;
  set t [time "exec mysql -f drh <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format MySQL: $t]
#  set t [time "exec ./sqlite232 s232.db <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format {SQLite 2.3.2:} $t]
#  set t [time "exec ./sqlite-100 s100.db <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format {SQLite 2.4 (cache=100):} $t]
  exec sync; after $delay;
  set t [time "exec ./sqlite248 s2k.db <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format {SQLite 2.4.8:} $t]
  exec sync; after $delay;
  set t [time "exec ./sqlite248 sns.db <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format {SQLite 2.4.8 (nosync):} $t]
  exec sync; after $delay;
  set t [time "exec ./sqlite2412 s2kb.db <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format {SQLite 2.4.12:} $t]
  exec sync; after $delay;
  set t [time "exec ./sqlite2412 snsb.db <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format {SQLite 2.4.12 (nosync):} $t]
#  set t [time "exec ./sqlite-t1 st1.db <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format {SQLite 2.4 (test):} $t]
  puts "</table>"
}

# Initialize the environment
#
expr srand(1)
catch {exec /bin/sh -c {rm -f s*.db}}
set fd [open clear.sql w]
puts $fd {
  drop table t1;
  drop table t2;
}
close $fd
catch {exec psql drh <clear.sql}
catch {exec mysql drh <clear.sql}
set fd [open 2kinit.sql w]
puts $fd {
  PRAGMA default_cache_size=2000;
  PRAGMA default_synchronous=on;
}
close $fd
exec ./sqlite248 s2k.db <2kinit.sql
exec ./sqlite2412 s2kb.db <2kinit.sql
set fd [open nosync-init.sql w]
puts $fd {
  PRAGMA default_cache_size=2000;
  PRAGMA default_synchronous=off;
}
close $fd
exec ./sqlite248 sns.db <nosync-init.sql
exec ./sqlite2412 snsb.db <nosync-init.sql
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}



set fd [open test$cnt.sql w]
puts $fd "CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100));"
for {set i 1} {$i<=1000} {incr i} {
  set r [expr {int(rand()*100000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
close $fd
runtest {1000 INSERTs}



set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
puts $fd "CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100));"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 INSERTs in a transaction}



set fd [open test$cnt.sql w]
for {set i 0} {$i<100} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+10)*100}]
  puts $fd "SELECT count(*), avg(b) FROM t2 WHERE b>=$lwr AND b<$upr;"
}
close $fd
runtest {100 SELECTs without an index}



set fd [open test$cnt.sql w]
for {set i 1} {$i<=100} {incr i} {
  puts $fd "SELECT count(*), avg(b) FROM t2 WHERE c LIKE '%[number_name $i]%';"
}
close $fd
runtest {100 SELECTs on a string comparison}



set fd [open test$cnt.sql w]
puts $fd {CREATE INDEX i2a ON t2(a);}
puts $fd {CREATE INDEX i2b ON t2(b);}
close $fd
runtest {Creating an index}



set fd [open test$cnt.sql w]
for {set i 0} {$i<5000} {incr i} {
  set lwr [expr {$i*100}]
  set upr [expr {($i+1)*100}]
  puts $fd "SELECT count(*), avg(b) FROM t2 WHERE b>=$lwr AND b<$upr;"
}
close $fd
runtest {5000 SELECTs with an index}



set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 0} {$i<1000} {incr i} {
  set lwr [expr {$i*10}]
  set upr [expr {($i+1)*10}]
  puts $fd "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;"
}
puts $fd "COMMIT;"
close $fd
runtest {1000 UPDATEs without an index}



set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "UPDATE t2 SET b=$r WHERE a=$i;"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 UPDATEs with an index}


set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "UPDATE t2 SET c='[number_name $r]' WHERE a=$i;"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 text UPDATEs with an index}



set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
puts $fd "INSERT INTO t1 SELECT * FROM t2;"
puts $fd "INSERT INTO t2 SELECT * FROM t1;"
puts $fd "COMMIT;"
close $fd
runtest {INSERTs from a SELECT}



set fd [open test$cnt.sql w]
puts $fd {DELETE FROM t2 WHERE c LIKE '%fifty%';}
close $fd
runtest {DELETE without an index}



set fd [open test$cnt.sql w]
puts $fd {DELETE FROM t2 WHERE a>10 AND a<20000;}
close $fd
runtest {DELETE with an index}



set fd [open test$cnt.sql w]
puts $fd {INSERT INTO t2 SELECT * FROM t1;}
close $fd
runtest {A big INSERT after a big DELETE}



set fd [open test$cnt.sql w]
puts $fd {BEGIN;}
puts $fd {DELETE FROM t1;}
for {set i 1} {$i<=3000} {incr i} {
  set r [expr {int(rand()*100000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
puts $fd {COMMIT;}
close $fd
runtest {A big DELETE followed by many small INSERTs}



set fd [open test$cnt.sql w]
puts $fd {DROP TABLE t1;}
puts $fd {DROP TABLE t2;}
close $fd
runtest {DROP TABLE}

Added tool/speedtest16.c.



















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/*
** Performance test for SQLite.
**
** This program reads ASCII text from a file named on the command-line.
** It converts each SQL statement into UTF16 and submits it to SQLite
** for evaluation.  A new UTF16 database is created at the beginning of
** the program.  All statements are timed using the high-resolution timer
** built into Intel-class processors.
**
** To compile this program, first compile the SQLite library separately
** will full optimizations.  For example:
**
**     gcc -c -O6 -DSQLITE_THREADSAFE=0 sqlite3.c
**
** Then link against this program.  But to do optimize this program
** because that defeats the hi-res timer.
**
**     gcc speedtest16.c sqlite3.o -ldl -I../src
**
** Then run this program with a single argument which is the name of
** a file containing SQL script that you want to test:
**
**     ./a.out database.db test.sql
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include "sqlite3.h"

/* 
** hwtime.h contains inline assembler code for implementing 
** high-performance timing routines.
*/
#include "hwtime.h"

/*
** Convert a zero-terminated ASCII string into a zero-terminated
** UTF-16le string.  Memory to hold the returned string comes 
** from malloc() and should be freed by the caller.
*/
static void *asciiToUtf16le(const char *z){
  int n = strlen(z);
  char *z16;
  int i, j;

  z16 = malloc( n*2 + 2 );
  for(i=j=0; i<=n; i++){
    z16[j++] = z[i];
    z16[j++] = 0;
  }
  return (void*)z16;
}

/*
** Timers
*/
static sqlite_uint64 prepTime = 0;
static sqlite_uint64 runTime = 0;
static sqlite_uint64 finalizeTime = 0;

/*
** Prepare and run a single statement of SQL.
*/
static void prepareAndRun(sqlite3 *db, const char *zSql){
  void *utf16;
  sqlite3_stmt *pStmt;
  const void *stmtTail;
  sqlite_uint64 iStart, iElapse;
  int rc;
  
  printf("****************************************************************\n");
  printf("SQL statement: [%s]\n", zSql);
  utf16 = asciiToUtf16le(zSql);
  iStart = sqlite3Hwtime();
  rc = sqlite3_prepare16_v2(db, utf16, -1, &pStmt, &stmtTail);
  iElapse = sqlite3Hwtime() - iStart;
  prepTime += iElapse;
  printf("sqlite3_prepare16_v2() returns %d in %llu cycles\n", rc, iElapse);
  if( rc==SQLITE_OK ){
    int nRow = 0;
    iStart = sqlite3Hwtime();
    while( (rc=sqlite3_step(pStmt))==SQLITE_ROW ){ nRow++; }
    iElapse = sqlite3Hwtime() - iStart;
    runTime += iElapse;
    printf("sqlite3_step() returns %d after %d rows in %llu cycles\n",
           rc, nRow, iElapse);
    iStart = sqlite3Hwtime();
    rc = sqlite3_finalize(pStmt);
    iElapse = sqlite3Hwtime() - iStart;
    finalizeTime += iElapse;
    printf("sqlite3_finalize() returns %d in %llu cycles\n", rc, iElapse);
  }
  free(utf16);
}

int main(int argc, char **argv){
  void *utf16;
  sqlite3 *db;
  int rc;
  int nSql;
  char *zSql;
  int i, j;
  FILE *in;
  sqlite_uint64 iStart, iElapse;
  sqlite_uint64 iSetup = 0;
  int nStmt = 0;
  int nByte = 0;

  if( argc!=3 ){
    fprintf(stderr, "Usage: %s FILENAME SQL-SCRIPT\n"
                    "Runs SQL-SCRIPT as UTF16 against a UTF16 database\n",
                    argv[0]);
    exit(1);
  }
  in = fopen(argv[2], "r");
  fseek(in, 0L, SEEK_END);
  nSql = ftell(in);
  zSql = malloc( nSql+1 );
  fseek(in, 0L, SEEK_SET);
  nSql = fread(zSql, 1, nSql, in);
  zSql[nSql] = 0;

  printf("SQLite version: %d\n", sqlite3_libversion_number());
  unlink(argv[1]);
  utf16 = asciiToUtf16le(argv[1]);
  iStart = sqlite3Hwtime();
  rc = sqlite3_open16(utf16, &db);
  iElapse = sqlite3Hwtime() - iStart;
  iSetup = iElapse;
  printf("sqlite3_open16() returns %d in %llu cycles\n", rc, iElapse);
  free(utf16);
  for(i=j=0; j<nSql; j++){
    if( zSql[j]==';' ){
      int isComplete;
      char c = zSql[j+1];
      zSql[j+1] = 0;
      isComplete = sqlite3_complete(&zSql[i]);
      zSql[j+1] = c;
      if( isComplete ){
        zSql[j] = 0;
        while( i<j && isspace(zSql[i]) ){ i++; }
        if( i<j ){
          nStmt++;
          nByte += j-i;
          prepareAndRun(db, &zSql[i]);
        }
        zSql[j] = ';';
        i = j+1;
      }
    }
  }
  iStart = sqlite3Hwtime();
  sqlite3_close(db);
  iElapse = sqlite3Hwtime() - iStart;
  iSetup += iElapse;
  printf("sqlite3_close() returns in %llu cycles\n", iElapse);
  printf("\n");
  printf("Statements run:       %15d\n", nStmt);
  printf("Bytes of SQL text:    %15d\n", nByte);
  printf("Total prepare time:   %15llu cycles\n", prepTime);
  printf("Total run time:       %15llu cycles\n", runTime);
  printf("Total finalize time:  %15llu cycles\n", finalizeTime);
  printf("Open/Close time:      %15llu cycles\n", iSetup);
  printf("Total Time:           %15llu cycles\n",
      prepTime + runTime + finalizeTime + iSetup);
  return 0;
}

Added tool/speedtest2.tcl.































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/usr/bin/tclsh
#
# Run this script using TCLSH to do a speed comparison between
# various versions of SQLite and PostgreSQL and MySQL
#

# Run a test
#
set cnt 1
proc runtest {title} {
  global cnt
  set sqlfile test$cnt.sql
  puts "<h2>Test $cnt: $title</h2>"
  incr cnt
  set fd [open $sqlfile r]
  set sql [string trim [read $fd [file size $sqlfile]]]
  close $fd
  set sx [split $sql \n]
  set n [llength $sx]
  if {$n>8} {
    set sql {}
    for {set i 0} {$i<3} {incr i} {append sql [lindex $sx $i]<br>\n}
    append sql  "<i>... [expr {$n-6}] lines omitted</i><br>\n"
    for {set i [expr {$n-3}]} {$i<$n} {incr i} {
      append sql [lindex $sx $i]<br>\n
    }
  } else {
    regsub -all \n [string trim $sql] <br> sql
  }
  puts "<blockquote>"
  puts "$sql"
  puts "</blockquote><table border=0 cellpadding=0 cellspacing=0>"
  set format {<tr><td>%s</td><td align="right">&nbsp;&nbsp;&nbsp;%.3f</td></tr>}
  set delay 1000
  exec sync; after $delay;
  set t [time "exec psql drh <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format PostgreSQL: $t]
  exec sync; after $delay;
  set t [time "exec mysql -f drh <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format MySQL: $t]
#  set t [time "exec ./sqlite232 s232.db <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format {SQLite 2.3.2:} $t]
#  set t [time "exec ./sqlite-100 s100.db <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format {SQLite 2.4 (cache=100):} $t]
  exec sync; after $delay;
  set t [time "exec ./sqlite240 s2k.db <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format {SQLite 2.4:} $t]
  exec sync; after $delay;
  set t [time "exec ./sqlite240 sns.db <$sqlfile" 1]
  set t [expr {[lindex $t 0]/1000000.0}]
  puts [format $format {SQLite 2.4 (nosync):} $t]
#  set t [time "exec ./sqlite-t1 st1.db <$sqlfile" 1]
#  set t [expr {[lindex $t 0]/1000000.0}]
#  puts [format $format {SQLite 2.4 (test):} $t]
  puts "</table>"
}

# Initialize the environment
#
expr srand(1)
catch {exec /bin/sh -c {rm -f s*.db}}
set fd [open clear.sql w]
puts $fd {
  drop table t1;
  drop table t2;
}
close $fd
catch {exec psql drh <clear.sql}
catch {exec mysql drh <clear.sql}
set fd [open 2kinit.sql w]
puts $fd {
  PRAGMA default_cache_size=2000;
  PRAGMA default_synchronous=on;
}
close $fd
exec ./sqlite240 s2k.db <2kinit.sql
exec ./sqlite-t1 st1.db <2kinit.sql
set fd [open nosync-init.sql w]
puts $fd {
  PRAGMA default_cache_size=2000;
  PRAGMA default_synchronous=off;
}
close $fd
exec ./sqlite240 sns.db <nosync-init.sql
set ones {zero one two three four five six seven eight nine
          ten eleven twelve thirteen fourteen fifteen sixteen seventeen
          eighteen nineteen}
set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety}
proc number_name {n} {
  if {$n>=1000} {
    set txt "[number_name [expr {$n/1000}]] thousand"
    set n [expr {$n%1000}]
  } else {
    set txt {}
  }
  if {$n>=100} {
    append txt " [lindex $::ones [expr {$n/100}]] hundred"
    set n [expr {$n%100}]
  }
  if {$n>=20} {
    append txt " [lindex $::tens [expr {$n/10}]]"
    set n [expr {$n%10}]
  }
  if {$n>0} {
    append txt " [lindex $::ones $n]"
  }
  set txt [string trim $txt]
  if {$txt==""} {set txt zero}
  return $txt
}


set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
puts $fd "CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100));"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 INSERTs in a transaction}


set fd [open test$cnt.sql w]
puts $fd "DELETE FROM t1;"
close $fd
runtest {DELETE everything}


set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 INSERTs in a transaction}


set fd [open test$cnt.sql w]
puts $fd "DELETE FROM t1;"
close $fd
runtest {DELETE everything}


set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 INSERTs in a transaction}


set fd [open test$cnt.sql w]
puts $fd "DELETE FROM t1;"
close $fd
runtest {DELETE everything}


set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 INSERTs in a transaction}


set fd [open test$cnt.sql w]
puts $fd "DELETE FROM t1;"
close $fd
runtest {DELETE everything}


set fd [open test$cnt.sql w]
puts $fd "BEGIN;"
for {set i 1} {$i<=25000} {incr i} {
  set r [expr {int(rand()*500000)}]
  puts $fd "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');"
}
puts $fd "COMMIT;"
close $fd
runtest {25000 INSERTs in a transaction}


set fd [open test$cnt.sql w]
puts $fd "DELETE FROM t1;"
close $fd
runtest {DELETE everything}


set fd [open test$cnt.sql w]
puts $fd {DROP TABLE t1;}
close $fd
runtest {DROP TABLE}

Added tool/speedtest8.c.









































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
** Performance test for SQLite.
**
** This program reads ASCII text from a file named on the command-line
** and submits that text  to SQLite for evaluation.  A new database
** is created at the beginning of the program.  All statements are
** timed using the high-resolution timer built into Intel-class processors.
**
** To compile this program, first compile the SQLite library separately
** will full optimizations.  For example:
**
**     gcc -c -O6 -DSQLITE_THREADSAFE=0 sqlite3.c
**
** Then link against this program.  But to do optimize this program
** because that defeats the hi-res timer.
**
**     gcc speedtest8.c sqlite3.o -ldl -I../src
**
** Then run this program with a single argument which is the name of
** a file containing SQL script that you want to test:
**
**     ./a.out test.db  test.sql
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

#if defined(_MSC_VER)
#include <windows.h>
#else
#include <unistd.h>
#include <sys/times.h>
#include <sched.h>
#endif

#include "sqlite3.h"

/* 
** hwtime.h contains inline assembler code for implementing 
** high-performance timing routines.
*/
#include "hwtime.h"

/*
** Timers
*/
static sqlite_uint64 prepTime = 0;
static sqlite_uint64 runTime = 0;
static sqlite_uint64 finalizeTime = 0;

/*
** Prepare and run a single statement of SQL.
*/
static void prepareAndRun(sqlite3 *db, const char *zSql, int bQuiet){
  sqlite3_stmt *pStmt;
  const char *stmtTail;
  sqlite_uint64 iStart, iElapse;
  int rc;
  
  if (!bQuiet){
    printf("***************************************************************\n");
  }
  if (!bQuiet) printf("SQL statement: [%s]\n", zSql);
  iStart = sqlite3Hwtime();
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &stmtTail);
  iElapse = sqlite3Hwtime() - iStart;
  prepTime += iElapse;
  if (!bQuiet){
    printf("sqlite3_prepare_v2() returns %d in %llu cycles\n", rc, iElapse);
  }
  if( rc==SQLITE_OK ){
    int nRow = 0;
    iStart = sqlite3Hwtime();
    while( (rc=sqlite3_step(pStmt))==SQLITE_ROW ){ nRow++; }
    iElapse = sqlite3Hwtime() - iStart;
    runTime += iElapse;
    if (!bQuiet){
      printf("sqlite3_step() returns %d after %d rows in %llu cycles\n",
             rc, nRow, iElapse);
    }
    iStart = sqlite3Hwtime();
    rc = sqlite3_finalize(pStmt);
    iElapse = sqlite3Hwtime() - iStart;
    finalizeTime += iElapse;
    if (!bQuiet){
      printf("sqlite3_finalize() returns %d in %llu cycles\n", rc, iElapse);
    }
  }
}

int main(int argc, char **argv){
  sqlite3 *db;
  int rc;
  int nSql;
  char *zSql;
  int i, j;
  FILE *in;
  sqlite_uint64 iStart, iElapse;
  sqlite_uint64 iSetup = 0;
  int nStmt = 0;
  int nByte = 0;
  const char *zArgv0 = argv[0];
  int bQuiet = 0;
#if !defined(_MSC_VER)
  struct tms tmsStart, tmsEnd;
  clock_t clkStart, clkEnd;
#endif

#ifdef HAVE_OSINST
  extern sqlite3_vfs *sqlite3_instvfs_binarylog(char *, char *, char *);
  extern void sqlite3_instvfs_destroy(sqlite3_vfs *);
  sqlite3_vfs *pVfs = 0;
#endif

  while (argc>3)
  {
#ifdef HAVE_OSINST
    if( argc>4 && (strcmp(argv[1], "-log")==0) ){
     pVfs = sqlite3_instvfs_binarylog("oslog", 0, argv[2]);
     sqlite3_vfs_register(pVfs, 1);
     argv += 2;
     argc -= 2;
     continue;
    }
#endif

    /*
    ** Increasing the priority slightly above normal can help with
    ** repeatability of testing.  Note that with Cygwin, -5 equates
    ** to "High", +5 equates to "Low", and anything in between
    ** equates to "Normal".
    */
    if( argc>4 && (strcmp(argv[1], "-priority")==0) ){
#if defined(_MSC_VER)
      int new_priority = atoi(argv[2]);
      if(!SetPriorityClass(GetCurrentProcess(), 
        (new_priority<=-5) ? HIGH_PRIORITY_CLASS : 
        (new_priority<=0)  ? ABOVE_NORMAL_PRIORITY_CLASS : 
        (new_priority==0)  ? NORMAL_PRIORITY_CLASS : 
        (new_priority<5)   ? BELOW_NORMAL_PRIORITY_CLASS : 
        IDLE_PRIORITY_CLASS)){
        printf ("error setting priority\n"); 
        exit(2); 
      }
#else
      struct sched_param myParam;
      sched_getparam(0, &myParam);
      printf ("Current process priority is %d.\n", (int)myParam.sched_priority); 
      myParam.sched_priority = atoi(argv[2]);
      printf ("Setting process priority to %d.\n", (int)myParam.sched_priority); 
      if (sched_setparam (0, &myParam) != 0){
        printf ("error setting priority\n"); 
        exit(2); 
      }
#endif
      argv += 2;
      argc -= 2;
      continue;
    }

    if( argc>3 && strcmp(argv[1], "-quiet")==0 ){
     bQuiet = -1;
     argv++;
     argc--;
     continue;
    }

    break;
  }

  if( argc!=3 ){
   fprintf(stderr, "Usage: %s [options] FILENAME SQL-SCRIPT\n"
              "Runs SQL-SCRIPT against a UTF8 database\n"
              "\toptions:\n"
#ifdef HAVE_OSINST
              "\t-log <log>\n"
#endif
              "\t-priority <value> : set priority of task\n"
              "\t-quiet : only display summary results\n",
              zArgv0);
   exit(1);
  }

  in = fopen(argv[2], "r");
  fseek(in, 0L, SEEK_END);
  nSql = ftell(in);
  zSql = malloc( nSql+1 );
  fseek(in, 0L, SEEK_SET);
  nSql = fread(zSql, 1, nSql, in);
  zSql[nSql] = 0;

  printf("SQLite version: %d\n", sqlite3_libversion_number());
  unlink(argv[1]);
#if !defined(_MSC_VER)
  clkStart = times(&tmsStart);
#endif
  iStart = sqlite3Hwtime();
  rc = sqlite3_open(argv[1], &db);
  iElapse = sqlite3Hwtime() - iStart;
  iSetup = iElapse;
  if (!bQuiet) printf("sqlite3_open() returns %d in %llu cycles\n", rc, iElapse);
  for(i=j=0; j<nSql; j++){
    if( zSql[j]==';' ){
      int isComplete;
      char c = zSql[j+1];
      zSql[j+1] = 0;
      isComplete = sqlite3_complete(&zSql[i]);
      zSql[j+1] = c;
      if( isComplete ){
        zSql[j] = 0;
        while( i<j && isspace(zSql[i]) ){ i++; }
        if( i<j ){
          int n = j - i;
          if( n>=6 && memcmp(&zSql[i], ".crash",6)==0 ) exit(1);
          nStmt++;
          nByte += n;
          prepareAndRun(db, &zSql[i], bQuiet);
        }
        zSql[j] = ';';
        i = j+1;
      }
    }
  }
  iStart = sqlite3Hwtime();
  sqlite3_close(db);
  iElapse = sqlite3Hwtime() - iStart;
#if !defined(_MSC_VER)
  clkEnd = times(&tmsEnd);
#endif
  iSetup += iElapse;
  if (!bQuiet) printf("sqlite3_close() returns in %llu cycles\n", iElapse);

  printf("\n");
  printf("Statements run:        %15d stmts\n", nStmt);
  printf("Bytes of SQL text:     %15d bytes\n", nByte);
  printf("Total prepare time:    %15llu cycles\n", prepTime);
  printf("Total run time:        %15llu cycles\n", runTime);
  printf("Total finalize time:   %15llu cycles\n", finalizeTime);
  printf("Open/Close time:       %15llu cycles\n", iSetup);
  printf("Total time:            %15llu cycles\n",
      prepTime + runTime + finalizeTime + iSetup);

#if !defined(_MSC_VER)
  printf("\n");
  printf("Total user CPU time:   %15.3g secs\n", (tmsEnd.tms_utime - tmsStart.tms_utime)/(double)CLOCKS_PER_SEC );
  printf("Total system CPU time: %15.3g secs\n", (tmsEnd.tms_stime - tmsStart.tms_stime)/(double)CLOCKS_PER_SEC );
  printf("Total real time:       %15.3g secs\n", (clkEnd -clkStart)/(double)CLOCKS_PER_SEC );
#endif

#ifdef HAVE_OSINST
  if( pVfs ){
    sqlite3_instvfs_destroy(pVfs);
    printf("vfs log written to %s\n", argv[0]);
  }
#endif

  return 0;
}

Added tool/speedtest8inst1.c.

















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/*
** Performance test for SQLite.
**
** This program reads ASCII text from a file named on the command-line
** and submits that text  to SQLite for evaluation.  A new database
** is created at the beginning of the program.  All statements are
** timed using the high-resolution timer built into Intel-class processors.
**
** To compile this program, first compile the SQLite library separately
** will full optimizations.  For example:
**
**     gcc -c -O6 -DSQLITE_THREADSAFE=0 sqlite3.c
**
** Then link against this program.  But to do optimize this program
** because that defeats the hi-res timer.
**
**     gcc speedtest8.c sqlite3.o -ldl -I../src
**
** Then run this program with a single argument which is the name of
** a file containing SQL script that you want to test:
**
**     ./a.out test.db  test.sql
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <stdarg.h>
#include "sqlite3.h"

#include "test_osinst.c"

/*
** Prepare and run a single statement of SQL.
*/
static void prepareAndRun(sqlite3_vfs *pInstVfs, sqlite3 *db, const char *zSql){
  sqlite3_stmt *pStmt;
  const char *stmtTail;
  int rc;
  char zMessage[1024];
  zMessage[1023] = '\0';

  sqlite3_uint64 iTime;

  sqlite3_snprintf(1023, zMessage, "sqlite3_prepare_v2: %s", zSql);
  sqlite3_instvfs_binarylog_marker(pInstVfs, zMessage);

  iTime = sqlite3Hwtime();
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &stmtTail);
  iTime = sqlite3Hwtime() - iTime;
  sqlite3_instvfs_binarylog_call(pInstVfs,BINARYLOG_PREPARE_V2,iTime,rc,zSql);

  if( rc==SQLITE_OK ){
    int nRow = 0;

    sqlite3_snprintf(1023, zMessage, "sqlite3_step loop: %s", zSql);
    sqlite3_instvfs_binarylog_marker(pInstVfs, zMessage);
    iTime = sqlite3Hwtime();
    while( (rc=sqlite3_step(pStmt))==SQLITE_ROW ){ nRow++; }
    iTime = sqlite3Hwtime() - iTime;
    sqlite3_instvfs_binarylog_call(pInstVfs, BINARYLOG_STEP, iTime, rc, zSql);

    sqlite3_snprintf(1023, zMessage, "sqlite3_finalize: %s", zSql);
    sqlite3_instvfs_binarylog_marker(pInstVfs, zMessage);
    iTime = sqlite3Hwtime();
    rc = sqlite3_finalize(pStmt);
    iTime = sqlite3Hwtime() - iTime;
    sqlite3_instvfs_binarylog_call(pInstVfs, BINARYLOG_FINALIZE, iTime, rc, zSql);
  }
}

static int stringcompare(const char *zLeft, const char *zRight){
  int ii;
  for(ii=0; zLeft[ii] && zRight[ii]; ii++){
    if( zLeft[ii]!=zRight[ii] ) return 0;
  }
  return( zLeft[ii]==zRight[ii] );
}

static char *readScriptFile(const char *zFile, int *pnScript){
  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  sqlite3_file *p;
  int rc;
  sqlite3_int64 nByte;
  char *zData = 0;
  int flags = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_DB;

  p = (sqlite3_file *)malloc(pVfs->szOsFile);
  rc = pVfs->xOpen(pVfs, zFile, p, flags, &flags);
  if( rc!=SQLITE_OK ){
    goto error_out;
  }

  rc = p->pMethods->xFileSize(p, &nByte);
  if( rc!=SQLITE_OK ){
    goto close_out;
  }

  zData = (char *)malloc(nByte+1);
  rc = p->pMethods->xRead(p, zData, nByte, 0);
  if( rc!=SQLITE_OK ){
    goto close_out;
  }
  zData[nByte] = '\0';

  p->pMethods->xClose(p);
  free(p);
  *pnScript = nByte;
  return zData;

close_out:
  p->pMethods->xClose(p);

error_out:
  free(p);
  free(zData);
  return 0;
}

int main(int argc, char **argv){

  const char zUsageMsg[] = 
    "Usage: %s options...\n"
    "  where available options are:\n"
    "\n"
    "    -db      DATABASE-FILE  (database file to operate on)\n"
    "    -script  SCRIPT-FILE    (script file to read sql from)\n"
    "    -log     LOG-FILE       (log file to create)\n"
    "    -logdata                (log all data to log file)\n"
    "\n"
    "  Options -db, -script and -log are compulsory\n"
    "\n"
  ;

  const char *zDb = 0;
  const char *zScript = 0;
  const char *zLog = 0;
  int logdata = 0;

  int ii;
  int i, j;
  int rc;

  sqlite3_vfs *pInstVfs;                 /* Instrumentation VFS */

  char *zSql = 0;
  int nSql;

  sqlite3 *db;

  for(ii=1; ii<argc; ii++){
    if( stringcompare("-db", argv[ii]) && (ii+1)<argc ){
      zDb = argv[++ii];
    }

    else if( stringcompare("-script", argv[ii]) && (ii+1)<argc ){
      zScript = argv[++ii];
    }

    else if( stringcompare("-log", argv[ii]) && (ii+1)<argc ){
      zLog = argv[++ii];
    }

    else if( stringcompare("-logdata", argv[ii]) ){
      logdata = 1;
    }

    else {
      goto usage;
    }
  }
  if( !zDb || !zScript || !zLog ) goto usage;

  zSql = readScriptFile(zScript, &nSql);
  if( !zSql ){
    fprintf(stderr, "Failed to read script file\n");
    return -1;
  }

  pInstVfs = sqlite3_instvfs_binarylog("logging", 0, zLog, logdata);

  rc = sqlite3_open_v2(
     zDb, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, "logging"
  );
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "Failed to open db: %s\n", sqlite3_errmsg(db));
    return -2;
  }

  for(i=j=0; j<nSql; j++){
    if( zSql[j]==';' ){
      int isComplete;
      char c = zSql[j+1];
      zSql[j+1] = 0;
      isComplete = sqlite3_complete(&zSql[i]);
      zSql[j+1] = c;
      if( isComplete ){
        zSql[j] = 0;
        while( i<j && isspace(zSql[i]) ){ i++; }
        if( i<j ){
          prepareAndRun(pInstVfs, db, &zSql[i]);
        }
        zSql[j] = ';';
        i = j+1;
      }
    }
  }
  
  sqlite3_instvfs_destroy(pInstVfs);
  return 0;
  
usage:
  fprintf(stderr, zUsageMsg, argv[0]);
  return -3;
}

Added tool/vdbe-compress.tcl.



























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/tcl
#
# This script makes modifications to the vdbe.c source file which reduce
# the amount of stack space required by the sqlite3VdbeExec() routine.
#
# The modifications performed by this script are optional.  The vdbe.c
# source file will compile correctly with and without the modifications
# performed by this script.  And all routines within vdbe.c will compute
# the same result.  The modifications made by this script merely help
# the C compiler to generate code for sqlite3VdbeExec() that uses less
# stack space.
#
# Script usage:
#
#          mv vdbe.c vdbe.c.template
#          tclsh vdbe-compress.tcl <vdbe.c.template >vdbe.c
#
# Modifications made:
#
# All modifications are within the sqlite3VdbeExec() function.  The
# modifications seek to reduce the amount of stack space allocated by
# this routine by moving local variable declarations out of individual
# opcode implementations and into a single large union.  The union contains
# a separate structure for each opcode and that structure contains the
# local variables used by that opcode.  In this way, the total amount
# of stack space required by sqlite3VdbeExec() is reduced from the
# sum of all local variables to the maximum of the local variable space
# required for any single opcode.
#
# In order to be recognized by this script, local variables must appear
# on the first line after the open curly-brace that begins a new opcode
# implementation.  Local variables must not have initializers, though they
# may be commented.
#
# The union definition is inserted in place of a special marker comment
# in the preamble to the sqlite3VdbeExec() implementation.
#
#############################################################################
#
set beforeUnion {}   ;# C code before union
set unionDef {}      ;# C code of the union
set afterUnion {}    ;# C code after the union
set sCtr 0           ;# Context counter

# Read program text up to the spot where the union should be
# inserted.
#
while {![eof stdin]} {
  set line [gets stdin]
  if {[regexp {INSERT STACK UNION HERE} $line]} break
  append beforeUnion $line\n
}

# Process the remaining text.  Build up the union definition as we go.
#
set vlist {}
set seenDecl 0
set namechars {abcdefghijklmnopqrstuvwxyz}
set nnc [string length $namechars]
while {![eof stdin]} {
  set line [gets stdin]
  if {[regexp "^case (OP_\\w+): \173" $line all operator]} {
    append afterUnion $line\n
    set vlist {}
    while {![eof stdin]} {
      set line [gets stdin]
      if {[regexp {^ +(const )?\w+ \**(\w+)(\[.*\])?;} $line \
           all constKeyword vname notused1]} {
        if {!$seenDecl} {
          set sname {}
          append sname [string index $namechars [expr {$sCtr/$nnc}]]
          append sname [string index $namechars [expr {$sCtr%$nnc}]]
          incr sCtr
          append unionDef "    struct ${operator}_stack_vars \173\n"
          append afterUnion \
             "#if 0  /* local variables moved into u.$sname */\n"
          set seenDecl 1
        }
        append unionDef "    $line\n"
        append afterUnion $line\n
        lappend vlist $vname
      } else {
        break
      }
    }
    if {$seenDecl} {
      append unionDef   "    \175 $sname;\n"
      append afterUnion "#endif /* local variables moved into u.$sname */\n"
    }
    set seenDecl 0
  }
  if {[regexp "^\175" $line]} {
    append afterUnion $line\n
    set vlist {}
  } elseif {[llength $vlist]>0} {
    append line " "
    foreach v $vlist {
      regsub -all "(\[^a-zA-Z0-9>.\])${v}(\\W)" $line "\\1u.$sname.$v\\2" line
      regsub -all "(\[^a-zA-Z0-9>.\])${v}(\\W)" $line "\\1u.$sname.$v\\2" line
    }
    append afterUnion [string trimright $line]\n
  } elseif {$line=="" && [eof stdin]} {
    # no-op
  } else {
    append afterUnion $line\n
  }
}

# Output the resulting text.
#
puts -nonewline $beforeUnion
puts "  /********************************************************************"
puts "  ** Automatically generated code"
puts "  **"
puts "  ** The following union is automatically generated by the"
puts "  ** vdbe-compress.tcl script.  The purpose of this union is to"
puts "  ** reduce the amount of stack space required by this function."
puts "  ** See comments in the vdbe-compress.tcl script for details."
puts "  */"
puts "  union vdbeExecUnion \173"
puts -nonewline $unionDef
puts "  \175 u;"
puts "  /* End automatically generated code"
puts "  ********************************************************************/"
puts -nonewline $afterUnion